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.
feature/Folder-entry-rule · L-261015-966530 (#1448)
Louis Choquel6683f0c90026
diff --git a/.drift/acks/cli-docs.toml b/.drift/acks/cli-docs.tomlindex 81d69729f..598d1f4ed 100644--- a/.drift/acks/cli-docs.toml+++ b/.drift/acks/cli-docs.toml@@ -1,18 +1,18 @@contract = "cli-docs"-digest = "sha256:2eed486cdc33f2c309e73dcc98319838bbfe08a441579f76ce52e069a8b51a85"+digest = "sha256:d1722558e88c5052fb5b204cd39b7caec1acaec8ccf07b1690ff09a9cc9a9ad6"reviewed_by = "Louis Choquel"-reviewed_at = "2026-10-16T03:27:39Z"-rationale = "real-catch: fix function-names now reports unresolved_markers (a marker kept because a step naming it is unresolved, or whose name is not a string literal) and exits 1 for them; docs/tools/cli/fix.md and agent-cli.md were updated with the change, and pipelex/cli/agent_cli/CLAUDE.md, which still listed the old envelope without unresolved_markers, now names it and the exit rule."+reviewed_at = "2026-10-17T01:00:26Z"+rationale = "real-catch: the fix write scope is now the method tree's root and --diff mirrors that root, build inputs/output load the entry with its whole folder and name the command in failures, a refused tree on agent fix is the FixBundleError envelope, and a pre-boot configuration error is reported as the failed boot; docs/tools/cli/fix.md, validate.md, agent-cli.md, build/inputs.md, build/output.md and pipelex/cli/agent_cli/CLAUDE.md now say so, and validate.md and agent-cli.md say a nested package, a dependency and the -L directories load without being judged."[trigger_files]"pipelex/cli/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc""pipelex/cli/_cli.py" = "blob:86fa74a5c45f33915548dc5ad4ec8ddbaf2b75d6""pipelex/cli/agent_cli/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/agent_cli/_agent_cli.py" = "blob:8146c939ab6558e90f6c62f51d1d50a83c559bf9"+"pipelex/cli/agent_cli/_agent_cli.py" = "blob:ad97a597f92ece45d06e571792f77c5b4805826e""pipelex/cli/agent_cli/commands/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/agent_cli/commands/agent_cli_factory.py" = "blob:050ca1344abc4c1ca22d431923e1577681552fe6"+"pipelex/cli/agent_cli/commands/agent_cli_factory.py" = "blob:512ca7ac621f660a9bfafda298583aef1ce28a71""pipelex/cli/agent_cli/commands/agent_output.py" = "blob:10588465f86eb7ce7d0bed3985304612b154d013"-"pipelex/cli/agent_cli/commands/bundle_path_resolver.py" = "blob:a1904517c731afb72af7d49adf6d217dc50b2660"+"pipelex/cli/agent_cli/commands/bundle_path_resolver.py" = "blob:93dd3c074626be471437c3815e51b6783cb52d13""pipelex/cli/agent_cli/commands/check_model_cmd.py" = "blob:3a9c93daecadf266b3eba466904b3d005d448d40""pipelex/cli/agent_cli/commands/codegen/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/agent_cli/commands/codegen/app.py" = "blob:56130b89fe9efec5ad3d014ed6bc16bef1bd1645"@@ -20,15 +20,15 @@ rationale = "real-catch: fix function-names now reports unresolved_markers (a ma"pipelex/cli/agent_cli/commands/codegen/types_cmd.py" = "blob:5c78bd70803a8f32616ccba9c57538ed49ab2d60""pipelex/cli/agent_cli/commands/doctor_cmd.py" = "blob:948be63cf4fab165846c83b4bd2517bd4a46be5e""pipelex/cli/agent_cli/commands/fix/__init__.py" = "blob:65662c86f17f610ad55ecfc3e27a022b9aa26e8b"-"pipelex/cli/agent_cli/commands/fix/app.py" = "blob:b11db5417fea85fbb8ea4bbf900663d9a1acc0ab"-"pipelex/cli/agent_cli/commands/fix/bundle_cmd.py" = "blob:cfd9e645986636c44c02a6a04a0fc67ed60d444b"+"pipelex/cli/agent_cli/commands/fix/app.py" = "blob:fbf3b1ff8298b0cd18f0b712b7623652c5975662"+"pipelex/cli/agent_cli/commands/fix/bundle_cmd.py" = "blob:96c978985debd9deba7a25e055c541c6f85f592e""pipelex/cli/agent_cli/commands/fix/function_names_cmd.py" = "blob:4b06e5d112fe9b9dfd3e9a5fdda5ba1bc99cff14""pipelex/cli/agent_cli/commands/fmt_cmd.py" = "blob:97d6fb6c328e0b718b1293bd6b73cba03edcb7dc""pipelex/cli/agent_cli/commands/init_cmd.py" = "blob:513b1160d8e3815b34b905bbabccd59d6c379842""pipelex/cli/agent_cli/commands/inputs/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/agent_cli/commands/inputs/_inputs_core.py" = "blob:4161029643f3a302de54fa637d2676521e10d873"-"pipelex/cli/agent_cli/commands/inputs/app.py" = "blob:7e19284687b334c684fb03381a8d9d20af1aa152"-"pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py" = "blob:30efc54a0501015527a4a03b72ba49b2e97385de"+"pipelex/cli/agent_cli/commands/inputs/app.py" = "blob:b30915d6fce2f524af4f0b2a50a37ffd7eaffab6"+"pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py" = "blob:fedf9fb6f37b37f80dd73be5380a603e23248bfa""pipelex/cli/agent_cli/commands/inputs/method_cmd.py" = "blob:604e91b2e65d951fd9a6eeed924a01f04fe2096f""pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py" = "blob:5c9c233b00d626599dea4907b148b4f08cdd58a0""pipelex/cli/agent_cli/commands/lint_cmd.py" = "blob:91ad9cb4d618ba4c0b7da366cde2f74f38d350df"@@ -40,35 +40,35 @@ rationale = "real-catch: fix function-names now reports unresolved_markers (a ma"pipelex/cli/agent_cli/commands/run/_run_core.py" = "blob:d71aee873856cfa72eb0ff18eb82c79e348f124a""pipelex/cli/agent_cli/commands/run/_run_hosted.py" = "blob:cea011e61feb082a7b9d82d7693b4fd3246737e5""pipelex/cli/agent_cli/commands/run/app.py" = "blob:7546d9b31ea2dc22b1ddae538edfbc8e7f7d08df"-"pipelex/cli/agent_cli/commands/run/bundle_cmd.py" = "blob:593854e8d3e39f5fe31d6b0b0c71b136933f06a7"+"pipelex/cli/agent_cli/commands/run/bundle_cmd.py" = "blob:6ee1041a4b5201cca1863fe9acaa3850c70faf03""pipelex/cli/agent_cli/commands/run/method_cmd.py" = "blob:776d1cf4bfbdce645f3cbfcd28be46bfb97174b0""pipelex/cli/agent_cli/commands/run/pipe_cmd.py" = "blob:f421c75ee696c18f85a7f63805455ef23637302f""pipelex/cli/agent_cli/commands/run/stdin_resolver.py" = "blob:c7c7d7495508f1c4e5a46eba336a4ab1694ebcf7""pipelex/cli/agent_cli/commands/validate/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/agent_cli/commands/validate/_validate_core.py" = "blob:c6eb0e986e0306fd5c8a9107792712a1a433b575"-"pipelex/cli/agent_cli/commands/validate/app.py" = "blob:d2d0ed19288c2d1c25be1650dd962189fcdb3b86"-"pipelex/cli/agent_cli/commands/validate/bundle_cmd.py" = "blob:6b02bb77dadf0ecd1814176580920962fcda2a42"+"pipelex/cli/agent_cli/commands/validate/_validate_core.py" = "blob:b15fb5ee5b3d84cb229f3eb3353df8354cfd488d"+"pipelex/cli/agent_cli/commands/validate/app.py" = "blob:1982684a2aae81e0d634bb3b262457a5f187d979"+"pipelex/cli/agent_cli/commands/validate/bundle_cmd.py" = "blob:ee5dd482fdf03eb2530afcdebfc393fe68646893""pipelex/cli/agent_cli/commands/validate/method_cmd.py" = "blob:0f4cf76d99b39422610c5daf6b5a0500de234818""pipelex/cli/agent_cli/commands/validate/pipe_cmd.py" = "blob:9a315ab32c89430c8ea111a0a50e629ed1acd6bf"-"pipelex/cli/bundle_target_resolution.py" = "blob:460aa997ea0886c6faee0f3a42bd55231c480240"+"pipelex/cli/bundle_target_resolution.py" = "blob:a712accba29d18c2a89e64fdc2b04854c5dd4ea8""pipelex/cli/cli_factory.py" = "blob:310ad1a2d055469cdc4f4728c82b9e83a9ff5852""pipelex/cli/commands/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/build/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/build/app.py" = "blob:d3205e1dc0268a9d32a517e4f9a9a3b4647e8889""pipelex/cli/commands/build/inputs/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/build/inputs/_inputs_core.py" = "blob:7706dfd81d078e81af876516e459594f9e727dfa"-"pipelex/cli/commands/build/inputs/app.py" = "blob:2a7770c8294b8c2c1b4420ac00d6ffdfa50609bf"-"pipelex/cli/commands/build/inputs/bundle_cmd.py" = "blob:699980753d79480387ef1edc7f94b00325827e63"+"pipelex/cli/commands/build/inputs/_inputs_core.py" = "blob:e5c2bd98e3b9afa438a5dcda538506cb85e8f17d"+"pipelex/cli/commands/build/inputs/app.py" = "blob:553e285ae7d1a9bf356b98ec268ba44bb1c30244"+"pipelex/cli/commands/build/inputs/bundle_cmd.py" = "blob:bd26ee8bd660ae5c09a7fa8a00720930c9854749""pipelex/cli/commands/build/inputs/method_cmd.py" = "blob:2fcaea4f05df4947d6ec1a49b2fa23b52c23ca3c""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:3b7462ccb49c18522c5453fe3ae482586bcebf05"-"pipelex/cli/commands/build/output/app.py" = "blob:67996650b99551fbd58be30e692688204d16935a"-"pipelex/cli/commands/build/output/bundle_cmd.py" = "blob:7cafc55438704ecc6e86d1182069e4b1f73f9794"+"pipelex/cli/commands/build/output/_output_core.py" = "blob:52549b3657f34ac0ff9f9a620ed212a284e97f2b"+"pipelex/cli/commands/build/output/app.py" = "blob:2bd9575e2093f13a1b5240f49b6f5a6a88bd1fee"+"pipelex/cli/commands/build/output/bundle_cmd.py" = "blob:0209b48f1c221fae59cf5bede2fbd92558a87f56""pipelex/cli/commands/build/output/method_cmd.py" = "blob:242434d518aff0b9706b910e7f937b53a601fde1""pipelex/cli/commands/build/output/pipe_cmd.py" = "blob:eb0db8279c93fcff9d5fe4546f593d753282acb5""pipelex/cli/commands/build/structures_cmd.py" = "blob:177c190e1679e26f7ab20d9ff3f6199aaf2cfe19"-"pipelex/cli/commands/bundle_path_resolver.py" = "blob:c98794b23efde0f279ac3c113fd5f5175f2db479"+"pipelex/cli/commands/bundle_path_resolver.py" = "blob:b3176ff36aa2100300969009712c06e5956ba483""pipelex/cli/commands/codegen/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/codegen/app.py" = "blob:9158084a89da23654e122e9df3a0a9c726401642""pipelex/cli/commands/codegen/check_cmd.py" = "blob:329f410bca90eb022fad2abc729e8b5203138c02"@@ -77,10 +77,10 @@ rationale = "real-catch: fix function-names now reports unresolved_markers (a ma"pipelex/cli/commands/crate_loading.py" = "blob:3d7d651931ecf1a15a3e2d72411b3212b55d74ef""pipelex/cli/commands/doctor_cmd.py" = "blob:a991d210787c0df68d9cc6bac29361df89e8e9c7""pipelex/cli/commands/fix/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/fix/_diff_sandbox.py" = "blob:d39c0df92b95567f74881deb01f8c1b3119fc8ef"-"pipelex/cli/commands/fix/_fix_core.py" = "blob:aa698305e6b60dfb7caf133698dc1d5c1f5f68f1"-"pipelex/cli/commands/fix/app.py" = "blob:23b28875f874e2687e183c759e45459377256711"-"pipelex/cli/commands/fix/bundle_cmd.py" = "blob:427364cc453957dfe0cec879f019050329c13b3c"+"pipelex/cli/commands/fix/_diff_sandbox.py" = "blob:d05eb4351f7065eaa45f63089f2daae0b02457dd"+"pipelex/cli/commands/fix/_fix_core.py" = "blob:afd6b07809e2a67105d5a2a9fea31523e2d14c9e"+"pipelex/cli/commands/fix/app.py" = "blob:61ed114633c679a252fa7d9367d4cf8e800f86ee"+"pipelex/cli/commands/fix/bundle_cmd.py" = "blob:83bf3fda431fb5d81f1763be28835730df0a9872""pipelex/cli/commands/fix/function_names_cmd.py" = "blob:b645a3d7687f01f18474446d29e23df4f1acc751""pipelex/cli/commands/graph_cmd.py" = "blob:d215ad2b66c4421364c90f2d8f875b6312dadfe4""pipelex/cli/commands/init/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"@@ -111,12 +111,11 @@ rationale = "real-catch: fix function-names now reports unresolved_markers (a ma"pipelex/cli/commands/run/_inputs_file_loader.py" = "blob:957e6eb00531d168b3b1e179a517717d069cb7fc""pipelex/cli/commands/run/_inputs_path_resolver.py" = "blob:c8ec89d98718e18af7aaaded44c9f545be60adab""pipelex/cli/commands/run/_main_stuff_file.py" = "blob:ca806e55085aa2e5748492751521296ce1f42960"-"pipelex/cli/commands/run/_method_folder.py" = "blob:11bd4f37a1a4fdee324c7aa5623ddab85cbebf81""pipelex/cli/commands/run/_run_core.py" = "blob:5b46ee698300deca87491d0491177fd4fe891220""pipelex/cli/commands/run/_run_hosted.py" = "blob:261439461abc1532d16393f33baf32f770207814""pipelex/cli/commands/run/_run_output_folder.py" = "blob:5834889a5e35e6457acf24761b408bc6a7bbfd6c""pipelex/cli/commands/run/app.py" = "blob:e312b159625e0a72bc9a18d3bfd2c73e7ac59f24"-"pipelex/cli/commands/run/bundle_cmd.py" = "blob:801027bff8303114da7b1c2d43c8e3715b0be3c2"+"pipelex/cli/commands/run/bundle_cmd.py" = "blob:ecb22be793b5cd49ad1a195ec2f40013aa58aff7""pipelex/cli/commands/run/exceptions.py" = "blob:e9552226e597922b6ac0757f7b52eb880a2e1472""pipelex/cli/commands/run/method_cmd.py" = "blob:924bca6e242d8490e32eeb9ed2329db3d1b58b8d""pipelex/cli/commands/run/pipe_cmd.py" = "blob:eafdc4bcf3f3f84042ecf9644e0f17fc355e0e17"@@ -124,16 +123,17 @@ rationale = "real-catch: fix function-names now reports unresolved_markers (a ma"pipelex/cli/commands/update_cmd.py" = "blob:b2db6170ddd9c67f17d88096ba1f1796a897557d""pipelex/cli/commands/usage_stats_cmd.py" = "blob:b3723c64f911d1b69e1e1aa126610a132a16e3da""pipelex/cli/commands/validate/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/validate/_validate_core.py" = "blob:7ed6ea06b1d99b850c530404531f69e1d1db042b"-"pipelex/cli/commands/validate/app.py" = "blob:33b6c2d374e456b2a47a27861f99c581945b21af"-"pipelex/cli/commands/validate/bundle_cmd.py" = "blob:1fbf3e0cf695db39101c83160a724df6468988e9"+"pipelex/cli/commands/validate/_validate_core.py" = "blob:735fb75881bee14bb120a3a7f7fe7746307ad30a"+"pipelex/cli/commands/validate/app.py" = "blob:457e110f0458bbe042a5489f58bba91acd885ebd"+"pipelex/cli/commands/validate/bundle_cmd.py" = "blob:1bf408a2d49b92476c87fa080b850b82cc870a88""pipelex/cli/commands/validate/method_cmd.py" = "blob:f12ee233fc985d04a4512f1fef6b9ea02a1b9644""pipelex/cli/commands/validate/pipe_cmd.py" = "blob:791b9a693f4ec52f727b42dab4b102af46a4ee22""pipelex/cli/commands/which_cmd.py" = "blob:5febd14510603f09ef0fb29d5ef97c35b7a6692f""pipelex/cli/deck_notice.py" = "blob:542877125e89e35b02bc969cfee952155b0d7c2c"-"pipelex/cli/error_handlers.py" = "blob:b4ddd1a0a40d75f948779e86a52739d793e4cff6"+"pipelex/cli/error_handlers.py" = "blob:346737863adac1992351e685294f56394712f476""pipelex/cli/exceptions.py" = "blob:1d51c3a53ddd3f6cf8de566fa2ade3fa75ab7a3a""pipelex/cli/installed_methods.py" = "blob:f7818b7857a8350389cf196e32630e7b3c51818c"+"pipelex/cli/judged_target.py" = "blob:8d3f3b3359992feeeca2bd4acd1d404262cbaf87""pipelex/cli/method_resolver.py" = "blob:34612bb21e9aae60cd5244abfa111d554443533a""pipelex/cli/readiness.py" = "blob:6d185324ed0784663e1dc78d1194a28312c54798""pipelex/cli/usage_stats_cli.py" = "blob:d04e2191e6f6a18027558a3e063f945be7b77679"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 663884956..94597f96d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,11 +9,14 @@### Changed+- **Every command taking a method's folder reads it as its method tree (Breaking)**: `validate bundle` and `fix bundle` on both CLIs judge every bundle of the folder's tree, as the MTHDS protocol's validation does, instead of a `bundle.mthds` or the folder's only `.mthds` file, so a folder whose bundles declare several `main_pipe`s, or none, is validated and fixed like any other, one holding no bundle exits with code `2` under `EmptyMethodTreeError`, one whose tree cannot be read is their invalid verdict naming the folder (`FixBundleError` on `pipelex-agent fix bundle`), and a fix writes anywhere in the tree from its root, the `--diff` preview proposing what the real run writes. `pipelex-agent inputs bundle`, `pipelex build inputs bundle` and `pipelex build output bundle` act, with no `--pipe`, on the pipe `run bundle` starts at, the `METHODS.toml`'s `main_pipe` or, with no manifest, the one `main_pipe` its bundles declare, loaded with the rest of the method's folder, and refuse a folder that decides none with the `MethodEntryError` `run bundle` gives. `pipelex-agent validate bundle <folder> --graph` draws that same pipe, or the one `--pipe` names, and when the folder decides none it says why in `graph_unavailable` instead of failing the validation; on every command reading a folder, a configuration that does not validate, read before the boot for the tree's limits, is reported as the failed boot it would be.+- **Validating a method's tree judges only its own pipes (Breaking)**: `validate_bundle(method_dir=...)`, and so `POST /v1/validate` on a method's files and `validate bundle <folder>`, dry-runs and reports only the bundles of the method's own tree; a nested package below it with its own `METHODS.toml`, the packages it depends on and the `-L` directories still load for its bundles to use, but their pipes are no longer judged with it.- **`/v1/resolve`, `/v1/codegen` and `/v1/pipe-io` take the method tree (Breaking)**: the three routes take the method as `/v1/validate` and the run routes do, `files` being the MTHDS protocol's map of file entries with `dependencies`, `resources` and `read_scope` beside it, or a `method_ref` whose package's whole tree is loaded with the packages it ships, so a call into another package by its address resolves when that package was shipped, while one nothing shipped is the invalid verdict, never looked up among the runner's installed methods or fetched, and a `METHODS.toml` at the root of a sent tree names the default pipe of `/v1/pipe-io`, which reads it only for a request naming no pipe. A `files` list of `{content, source}` items is refused with a `422` `InvalidMethodFiles`, the tree's refusals and the custom-Python `403`s are those of `/v1/validate`, `include_files` echoes the method's `.mthds` bundles as a map from tree path to text, and the request models `MthdsFilesRequest`, `MthdsFileItem` and `MthdsPipeRequest` are removed. The routes load the method in a worker thread, so a slow load never holds up the server's other requests.- **A bundle validator receives the read scope, plugin API version 8 (Breaking)**: `BundleValidatorProtocol.validate_bundles` takes `read_scope`, the scope the host named for the validation, `None` when it named none, so a validator dispatching the validation to another process hands the method's trees to its worker through that scope's blob store and the worker reads them by digest under it, as a run's worker reads under the run's read scope. The API server's `POST /v1/validate` hands its validator the request's `read_scope` on every arm, never the caller's own id, and `PLUGIN_API_VERSION` moves to 8, so a plugin declaring `targets_api = 7` is refused at discovery with `PluginApiVersionMismatchError`.### Fixed+- **A `main_pipe` that is not a pipe code is an invalid bundle**: a bundle declaring its `main_pipe` as another type, such as a list, is refused with a validation error located on `main_pipe` instead of crashing the parse with a `TypeError`, and a folder's entry rule refuses a `main_pipe` that is no pipe code, such as `domain.pipe`, a camelCase name or an empty string, with the same located error instead of reading an empty one as declaring none.- **Load errors name a written tree's bundles by their tree paths**: an error raised once the bundles of a tree the server wrote out have parsed, such as a concept declared in two bundles, names them by their tree paths instead of the directory they were written to, so a verdict of `/v1/validate`, a run or a crate route no longer discloses a path on the server.### Securitydiff --git a/api/pipelex_api/method_tree_request.py b/api/pipelex_api/method_tree_request.pyindex ba00488b9..10be07410 100644--- a/api/pipelex_api/method_tree_request.py+++ b/api/pipelex_api/method_tree_request.py@@ -698,7 +698,7 @@ def select_tree_entry(*, tree: RequestTree, method_label: str) -> MethodEntry:raise MethodEntryError(msg) from excwith translate_to_validate_bundle_error():blueprint = MthdsParser.make_pipelex_bundle_blueprint(mthds_content=content, mthds_source=tree_path)- candidates.append(EntryCandidate(tree_path=tree_path, blueprint=blueprint))+ candidates.append(EntryCandidate.of_blueprint(tree_path=tree_path, blueprint=blueprint))manifest = manifest_of(tree=tree, label=f"the method {method_label}")return select_entry(candidates=candidates, manifest=manifest, method_label=method_label)diff --git a/docs/contribute/mthds-test-corpus.md b/docs/contribute/mthds-test-corpus.mdindex e0ee12cf5..244018a7e 100644--- a/docs/contribute/mthds-test-corpus.md+++ b/docs/contribute/mthds-test-corpus.md@@ -25,7 +25,7 @@ pipelex/test_extras/mthds_corpus/inputs.json optional```-An entry directory holds either exactly one `.mthds` file, or several with a `bundle.mthds` acting as the entry point — which is exactly what `pipelex validate bundle <dir>` already resolves, so an entry directory is a valid CLI argument as it stands.+An entry directory is a method's folder whose bundles declare one `main_pipe` between them, or whose `METHODS.toml` names it: the pipe the MTHDS protocol's entry rule starts the folder at, and the bundle defining it is the entry's bundle. That is exactly where `pipelex run bundle <dir>` starts, while `pipelex validate bundle <dir>` judges every bundle of the folder, so an entry directory is a valid CLI argument as it stands. The rule reads only what the bundles declare, so a deliberately invalid entry still resolves as long as its bundle is TOML that declares its `domain` and `main_pipe`; an entry whose one bundle declares a `main_pipe` that is no pipe code, which the rule refuses as `run bundle` does, resolves to that bundle, the one the refusal names. Each entry directory is read as its own method tree's root, with no search for a `METHODS.toml` above it, since the corpus ships inside an installed package whose ancestors are no part of it.## Adding an entrydiff --git a/docs/errors/authoring-and-language.md b/docs/errors/authoring-and-language.mdindex b22753d02..b1a5e2cc5 100644--- a/docs/errors/authoring-and-language.md+++ b/docs/errors/authoring-and-language.md@@ -123,6 +123,7 @@ own page. Classes are grouped by subsystem.- [`CrateNormalizationError`](crate-normalization-error.md) — Crate normalization error- [`DomainLibraryError`](domain-library-error.md) — Domain library- [`DomainLoadingError`](domain-loading-error.md) — Domain loading+- [`EmptyMethodTreeError`](empty-method-tree-error.md) — Empty method tree- [`EntryPipeAmbiguousError`](entry-pipe-ambiguous-error.md) — Entry pipe ambiguous- [`EntryPipeNotFoundError`](entry-pipe-not-found-error.md) — Entry pipe not found- [`HostLibraryRequirementsError`](host-library-requirements-error.md) — Host library requirementsdiff --git a/docs/errors/empty-method-tree-error.md b/docs/errors/empty-method-tree-error.mdnew file mode 100644index 000000000..538ae6b82--- /dev/null+++ b/docs/errors/empty-method-tree-error.md@@ -0,0 +1,21 @@+---+title: "Empty method tree"+description: "Reference for the `EmptyMethodTreeError` Pipelex error class."+---++<!-- pipelex:generated -->++# Empty method tree++Raised when a folder handed over as a method holds no bundle.++| Field | Value |+|---|---|+| `error_type` | `EmptyMethodTreeError` |+| `title` | Empty method tree |+| `type_uri` | `https://docs.pipelex.com/latest/errors/empty-method-tree-error/` |+| `error_domain` | _(inherited from parent)_ |+| Defined in | `pipelex.libraries.exceptions` |+| Parent class | [`MethodTreeLoadError`](method-tree-load-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/errors/method-entry-error.md b/docs/errors/method-entry-error.mdindex 4d9bd7f85..310e6ec1e 100644--- a/docs/errors/method-entry-error.md+++ b/docs/errors/method-entry-error.md@@ -7,7 +7,7 @@ description: "Reference for the `MethodEntryError` Pipelex error class."# Method entry-Raised when a method run with no pipe named has no single pipe to start at.+Raised when a method has no single pipe to start at, or no single bundle defining the pipe named.| Field | Value ||---|---|@@ -18,6 +18,6 @@ Raised when a method run with no pipe named has no single pipe to start at.| Defined in | `pipelex.pipeline.exceptions` || Parent class | [`PipelexError`](pipelex-error.md) || `retryable` | `false` |-| `user_action` | `change_input` — Name the pipe to run, or declare the method's one main_pipe: in its METHODS.toml, or in one of its bundles |+| `user_action` | `change_input` — Name the pipe, or declare the method's one main_pipe: in its METHODS.toml, or in one of its bundles |[Back to Error Reference](index.md)diff --git a/docs/tools/cli/agent-cli.md b/docs/tools/cli/agent-cli.mdindex 1f3782586..419e6c28a 100644--- a/docs/tools/cli/agent-cli.md+++ b/docs/tools/cli/agent-cli.md@@ -84,11 +84,13 @@ pipelex-agent validate method <NAME> [OPTIONS]For `bundle`, additional options are available:-- `--pipe` - Require a specific pipe in the bundle+- `--pipe` - Require a specific pipe in the bundle, and dry-run only that pipe; for a method's folder, the whole tree is still validated- `--graph`, `-g` - Generate an execution graph visualization- `--graph-format`, `-f` - Graph output format (`mermaidflow`, `reactflow`, or `both`)- `--direction` - Graph layout direction+`validate bundle <folder>` reads the folder as its [method tree](../../building-methods/method-trees.md), the method rooted at the nearest `METHODS.toml` at or above it, else at the folder itself, and judges the whole tree, as the MTHDS protocol's validation judges a method: every bundle of it is loaded and every pipe of it dry-run. It needs no pipe to start at, so a folder whose bundles declare several `main_pipe`s, or none, is validated like any other, and `bundle_path` in the envelope names the folder. Only the tree's own pipes are judged: the `-L` directories, a nested package below the folder with its own `METHODS.toml`, and the packages the method depends on all load for its bundles to use, but their own pipes are not judged. A graph, which is drawn from one pipe, is drawn from the pipe named by `--pipe`, else from the pipe a run of the folder starts at, the manifest's `main_pipe` or, with no manifest, the one `main_pipe` its bundles declare; when the folder decides no such pipe, `--graph` and `--view` draw nothing and the envelope carries `graph_unavailable`, a sentence saying why, while the validation stands and exits on its own verdict. A folder holding no `.mthds` bundle produces no verdict: `error_type: EmptyMethodTreeError`, exit code `2`.+!!! note "Signature pipes"`pipelex-agent validate` is strict by default — same as `pipelex validate`. A bundle whose dependency graph reaches a `PipeSignature` is rejected unless you pass `--allow-signatures`, which dry-runs signatures as mocks.@@ -118,7 +120,7 @@ pipelex-agent fix bundle <PATH> [OPTIONS]- `--format` - Success output format: `markdown` (default) or `json`- `--error-format` - Error output format: `markdown` or `json` (defaults to `--format`'s value)-The result reports `iterations`, `fixes_applied`, `files_written`, and any `remaining_errors`. A fully valid result exits 0; a completed fix attempt that remains invalid exits 1; argument, setup, or unexpected failures exit 2.+The result reports `iterations`, `fixes_applied`, `files_written`, and any `remaining_errors`. A fully valid result exits 0; a completed fix attempt that remains invalid exits 1; argument, setup, or unexpected failures exit 2, and so does a folder holding no `.mthds` bundle. A folder is fixed whole, as `validate bundle` judges it: every file of its method tree, from the tree's root down, is inside the write scope, a fix lands in the file its error names, and a folder whose bundles declare several `main_pipe`s, or none, is fixed like any other. A folder whose tree cannot be read, such as one past this machine's limits, leaves as the still-invalid verdict, `error_type: FixBundleError` with exit code `1`, its `remaining_errors` carrying the refusal. A configuration that does not validate, which these commands read before the boot for the tree's limits, is reported as the failed boot it would have been, under the configuration error's own `error_type` with the boot's hint.Rewrite a method's flat `PipeFunc` function names as import paths from its folder, the migration of the retired function registry (see [PipeFunc](../../building-methods/pipes/pipe-operators/PipeFunc.md#migrating-flat-function-names)):@@ -144,7 +146,7 @@ pipelex-agent inputs method <NAME> [OPTIONS]- `--format` - Template serialization: `json` (default) or `toml`- `--explicit` - Emit the ceremonial `{concept, content}` envelope form instead of the light values-For `bundle` and `method`, use `--pipe` to target a specific pipe.+For `bundle` and `method`, use `--pipe` to target a specific pipe. With no `--pipe`, a method's folder generates the template of the pipe a run of the folder starts at, as `run bundle` selects it; a folder whose bundles declare no `main_pipe`, or several, is refused under `error_type: MethodEntryError` with exit code `1`, and a folder holding no bundle is refused the same way. With `--pipe`, the folder loads as the method's library and the pipe is looked up there, as `run bundle <folder> --pipe` runs it.The JSON success envelope names the pipe the template was generated for as `pipe_ref`, the qualified `domain.pipe_code` of the pipe that was resolved, whether you named it with a bare code, a qualified ref, or let it default to the bundle's `main_pipe`. A pipe you reached through a dependency alias keeps that alias, `alias->domain.pipe_code`, since that is the ref that selects it again:diff --git a/docs/tools/cli/build/inputs.md b/docs/tools/cli/build/inputs.mdindex ded1485cc..4288ae3b4 100644--- a/docs/tools/cli/build/inputs.md+++ b/docs/tools/cli/build/inputs.md@@ -33,15 +33,17 @@ pipelex build inputs pipe <PIPE_CODE> [OPTIONS]pipelex build inputs bundle <PATH> [OPTIONS]```+A folder is read as its [method tree](../../../building-methods/method-trees.md), as [`pipelex run bundle`](../run.md#run-bundle) reads it. With no `--pipe`, the template is for the pipe a run of the folder starts at: the manifest's `main_pipe`, or, with no manifest, the one `main_pipe` its bundles declare. A folder whose bundles declare none, or several, is refused with the message `run bundle` gives, naming each bundle by its path in the tree. The bundle defining that pipe loads with the rest of the method's folder and the `-L` directories, as a run loads it, so a concept or a pipe it takes from a sibling bundle resolves. With `--pipe`, the folder loads as the method's library and the pipe named is looked up there, as a run naming its pipe does. A refusal names the command, as in `Failed to build inputs: ...`. Either way the file is written in the folder unless `--output` says otherwise, so `pipelex run bundle` on the same folder finds it.+**Arguments:**-- `PATH` - Path to a `.mthds` bundle file or a pipeline directory+- `PATH` - Path to a `.mthds` bundle file or a method's folder**Options:**-- `--pipe` - Pipe code to use (can be omitted if the bundle declares a `main_pipe`)+- `--pipe` - Pipe code to use (can be omitted if the bundle, or the method's folder, 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 inputs file (defaults to the bundle's directory, filename `inputs.json` or `inputs.toml` depending on `--format`)+- `--output`, `-o` - Path to save the generated inputs file (defaults to the method's folder, or to the bundle file's directory, filename `inputs.json` or `inputs.toml` depending on `--format`)- `--format` - Template format: `json` (default) or `toml`- `--explicit` - Emit the ceremonial `{concept, content}` envelope form instead of the light values@@ -77,7 +79,7 @@ pipelex build inputs pipe my_domain.my_pipepipelex build inputs bundle my_bundle.mthds```-**Generate inputs from a pipeline directory:**+**Generate inputs for the main pipe of a method's folder:**```bashpipelex build inputs bundle pipeline_01/diff --git a/docs/tools/cli/build/output.md b/docs/tools/cli/build/output.mdindex cb232fe85..a648e9adc 100644--- a/docs/tools/cli/build/output.md+++ b/docs/tools/cli/build/output.md@@ -33,15 +33,17 @@ pipelex build output pipe <PIPE_CODE> [OPTIONS]pipelex build output bundle <PATH> [OPTIONS]```+A folder is read as its [method tree](../../../building-methods/method-trees.md), as [`pipelex run bundle`](../run.md#run-bundle) reads it. With no `--pipe`, the representation is for the pipe a run of the folder starts at: the manifest's `main_pipe`, or, with no manifest, the one `main_pipe` its bundles declare. A folder whose bundles declare none, or several, is refused with the message `run bundle` gives, naming each bundle by its path in the tree. The bundle defining that pipe loads with the rest of the method's folder and the `-L` directories, as a run loads it, so a concept or a pipe it takes from a sibling bundle resolves. With `--pipe`, the folder loads as the method's library and the pipe named is looked up there, as a run naming its pipe does. A refusal names the command, as in `Failed to build output: ...`. Either way the file is written in the folder unless `--output` says otherwise.+**Arguments:**-- `PATH` - Path to a `.mthds` bundle file or a pipeline directory+- `PATH` - Path to a `.mthds` bundle file or a method's folder**Options:**-- `--pipe` - Pipe code to use (can be omitted if the bundle declares a `main_pipe`)+- `--pipe` - Pipe code to use (can be omitted if the bundle, or the method's folder, 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 file (defaults to bundle's directory)+- `--output`, `-o` - Path to save the generated file (defaults to the method's folder, or to the bundle file's directory)- `--format`, `-f` - Output format (default: `json`): `json`, `python`, or `schema`### From an installed method@@ -81,7 +83,7 @@ pipelex build output bundle my_bundle.mthdspipelex build output bundle my_bundle.mthds --format schema```-**Generate output from a pipeline directory:**+**Generate output for the main pipe of a method's folder:**```bashpipelex build output bundle pipeline_01/diff --git a/docs/tools/cli/fix.md b/docs/tools/cli/fix.mdindex ee91d0a9b..249350b51 100644--- a/docs/tools/cli/fix.md+++ b/docs/tools/cli/fix.md@@ -19,11 +19,11 @@ When `pipelex validate` reports errors that have a deterministic safe fix, eachpipelex fix bundle <PATH>```-Fixes a bundle file (`.mthds`) or a pipeline directory in place. When a directory is given, the bundle file is auto-detected inside it — exactly the same resolution as `pipelex validate bundle`, so fix patches exactly what validate judged.+Fixes a bundle file (`.mthds`) or a method's folder in place. A folder is read as its [method tree](../../building-methods/method-trees.md) and judged whole, every bundle of it, exactly as `pipelex validate bundle` judges it, so fix patches exactly what validate judged; it needs no pipe to start at, so a folder whose bundles declare several `main_pipe`s, or none, is fixed like any other. The whole method tree is inside the fix write scope, from its root down, so a fix lands in the file its error names even when that file is a bundle above or beside the folder you named, and `--diff` mirrors the same tree into its preview, so the preview proposes exactly what the real run writes. A folder whose tree cannot be read, such as one past this machine's limits or holding a symbolic link, gets the negative verdict: the refusal is reported as the fix's remaining error, naming the folder, with exit code `1`.**Arguments:**-- `PATH` - Path to a `.mthds` bundle file or a directory containing one+- `PATH` - Path to a `.mthds` bundle file or a method's folder**Options:**@@ -43,7 +43,7 @@ pipelex fix bundle my_pipeline.mthds# Preview the changes without writing anythingpipelex fix bundle my_pipeline.mthds --diff-# Fix a pipeline directory (auto-detects the bundle file)+# Fix a method's folder (every bundle of its method tree)pipelex fix bundle pipelines/invoice_processor/# Fix with additional library directories (also widens the write scope)@@ -57,7 +57,7 @@ pipelex fix bundle my_bundle.mthds --select match-sequence-output- `0` - The bundle is valid after the run (fixed, or already valid)- `1` - Negative verdict: the bundle is still invalid, or valid but not runnable (pending `PipeSignature` placeholders without `--allow-signatures`)-- `2` - No verdict: bad path, ambiguous bundle directory, invalid rule filter, or an unexpected failure+- `2` - No verdict: bad path, a folder holding no `.mthds` bundle, invalid rule filter, or an unexpected failure## What Gets Fixeddiff --git a/docs/tools/cli/validate.md b/docs/tools/cli/validate.mdindex ad65b87e7..08ab1cd6c 100644--- a/docs/tools/cli/validate.md+++ b/docs/tools/cli/validate.md@@ -64,11 +64,11 @@ pipelex validate --all --allow-signaturespipelex validate bundle <PATH>```-Validates all pipes defined in a bundle file (`.mthds`) or a pipeline directory. When a directory is given, the bundle file is auto-detected inside it.+Validates all pipes defined in a bundle file (`.mthds`), or every bundle of a method's folder. A folder is read as its [method tree](../../building-methods/method-trees.md), the method rooted at the nearest `METHODS.toml` at or above it, else at the folder itself, and the whole tree is judged, as the MTHDS protocol's validation judges a method: every bundle of it is loaded and every pipe of it dry-run, whatever its bundles declare of where the method starts. A folder whose bundles declare several `main_pipe`s, or none, is validated like any other, since validation needs no pipe to start at; only a command acting on one pipe, such as [`pipelex run bundle`](run.md#run-bundle), needs the folder's entry. Only the tree's own pipes are judged: the `-L` directories, a nested package below the folder with its own `METHODS.toml`, and the packages the method depends on all load for its bundles to use, but their own pipes are not judged. A folder whose tree cannot be read, such as one past this machine's limits or holding a symbolic link, is an invalid verdict naming the folder, with exit code `1`. A folder holding no `.mthds` bundle produces no verdict and exits with code `2`.**Arguments:**-- `PATH` - Path to a `.mthds` bundle file or a directory containing one+- `PATH` - Path to a `.mthds` bundle file or a method's folder**Options:**@@ -82,7 +82,7 @@ Validates all pipes defined in a bundle file (`.mthds`) or a pipeline directory.pipelex validate bundle my_pipeline.mthdspipelex validate bundle pipelines/invoice_processor.mthds-# Validate a pipeline directory (auto-detects the bundle file)+# Validate a method's folder (every bundle of its method tree)pipelex validate bundle pipelines/invoice_processor/# Validate with additional library directoriesdiff --git a/pipelex/cli/agent_cli/CLAUDE.md b/pipelex/cli/agent_cli/CLAUDE.mdindex 6e5132322..5ec7a1406 100644--- a/pipelex/cli/agent_cli/CLAUDE.md+++ b/pipelex/cli/agent_cli/CLAUDE.md@@ -18,7 +18,7 @@ Only the error format is backed by a module-level `ContextVar` in `agent_output.Markdown structure per command:- `run`: `# Pipeline run complete`, a `## Result` section (the rendered `main_stuff` markdown with `--with-memory`, otherwise the concept JSON in a fenced block), and output / graph file paths. With the graph on, the `graph_files` object of the `--with-memory` envelope names the viewer (`graph_html`), the graph on a live run (`graph_spec`, the graphspec renamed `live_run_graph.json`) and the graph's three companions written beside it under their canonical names (`pipe_io_contracts`, `input_form`, `output_form` — the validate artifacts describing the graph's data, keyed by `pipe_ref`); the agent CLI settles its graph inclusion (graphspec on, viewer on) before the run rather than at render time, since the companions are built inside the run's library window under that same flag; a viewer resolves them from the graph file's directory, so the rename never moves them. Cost is machine-first: on the local runner, when costs are on (`--costs`, the default) and the run did reportable work (any tokens or any cost), a best-effort `cost_report` object (`{total_cost, by_model: [...]}`, real USD) rides the JSON `--with-memory` envelope — there is **no** Rich cost table on stderr (unlike the human `pipelex run` CLI). The markdown renderer ignores the `cost_report` key, so it is JSON-only. A free/zero-price model still reports its token usage (with `total_cost` 0). The `cost_report` is **absent** when the run did no reportable work (dry runs), when `--no-costs` is passed, on a hosted run (which assembles no local usage), or if cost-summary aggregation fails (caught and skipped so it never fails an otherwise-successful run) — so consumers must treat it as optional. A local `run bundle` also carries `method_tree_digest`, the digest of the method tree it read, in its output file and its `--with-memory` envelope.-- `validate`: `# Validation passed`, the bundle path when relevant, and a list of validated pipes with their status. Every entry in `validated_pipes` (markdown and JSON) identifies its pipe by the namespaced `pipe_ref` (`domain.code`) — the same unambiguous identity across `validate all`, `validate bundle`, and `validate pipe`, so the same pipe is never reported under two identifiers. `validate bundle`, `validate method`, and `validate all` carry `pending_signatures` — the library-wide list of pipes still declared as `PipeSignature` (unimplemented forward declarations), namespaced by `pipe_ref` — rendered as a "Pending signatures" section in markdown. They also carry a derived `is_runnable` boolean (`true` ⇔ `pending_signatures` is empty), and the markdown adds an explicit plain-English runnability verdict on those surfaces: a complete bundle/library states it is runnable, while one with pending signatures states it is NOT yet runnable immediately above the verbatim "Pending signatures" heading. These whole-bundle/whole-library surfaces are **strict by default**: they exit non-zero on `not is_runnable` unless `--allow-signatures` is passed (which both tolerates the placeholders for the exit code and mock-runs the signature pipes in the sweep). Single-pipe surfaces make no library-wide runnability claim and never gate the exit code on it: bare `validate pipe <code>` omits the key and emits no verdict, while `validate bundle`/`validate method` with `--pipe` still surface the library-wide `pending_signatures` for information but do not gate on it (the requested slice can be fully implemented even when unrelated placeholders remain elsewhere). The whole-bundle and whole-library surfaces also carry a `warnings` array — the advisory lints, then what the sweep's dry runs found without failing (a `PipeDocGen` template check's `template_check_warning`s), rendered as a "Warnings" section in markdown — assembled by `pipelex/pipeline/advisory_warnings.py`, the ONE composition point every advisory-bearing channel calls (this CLI, the bare CLI and the protocol report). Bare `validate pipe <code>` carries the dry-run findings alone (`pipelex/pipeline/dry_run_warnings.py`), since one pipe has no flow to lint but what its dry run found is about it; `validate bundle` / `validate method` with `--pipe` carry every family, because they validate the whole bundle and only narrow the dry run, so the array stays bundle-wide there. Add a new advisory family there, never at a call site: the sites used to assemble their own and disagreed about which families they carried.+- `validate`: `# Validation passed`, the bundle path when relevant (a method's folder, for a folder judged whole), and a list of validated pipes with their status. `validate bundle <folder> --graph` / `--view` on a folder that decides no pipe to start at adds `graph_unavailable`, a sentence saying why no graph was drawn, rendered as a `## Graph` section. Every entry in `validated_pipes` (markdown and JSON) identifies its pipe by the namespaced `pipe_ref` (`domain.code`) — the same unambiguous identity across `validate all`, `validate bundle`, and `validate pipe`, so the same pipe is never reported under two identifiers. `validate bundle`, `validate method`, and `validate all` carry `pending_signatures` — the library-wide list of pipes still declared as `PipeSignature` (unimplemented forward declarations), namespaced by `pipe_ref` — rendered as a "Pending signatures" section in markdown. They also carry a derived `is_runnable` boolean (`true` ⇔ `pending_signatures` is empty), and the markdown adds an explicit plain-English runnability verdict on those surfaces: a complete bundle/library states it is runnable, while one with pending signatures states it is NOT yet runnable immediately above the verbatim "Pending signatures" heading. These whole-bundle/whole-library surfaces are **strict by default**: they exit non-zero on `not is_runnable` unless `--allow-signatures` is passed (which both tolerates the placeholders for the exit code and mock-runs the signature pipes in the sweep). Single-pipe surfaces make no library-wide runnability claim and never gate the exit code on it: bare `validate pipe <code>` omits the key and emits no verdict, while `validate bundle`/`validate method` with `--pipe` still surface the library-wide `pending_signatures` for information but do not gate on it (the requested slice can be fully implemented even when unrelated placeholders remain elsewhere). The whole-bundle and whole-library surfaces also carry a `warnings` array — the advisory lints, then what the sweep's dry runs found without failing (a `PipeDocGen` template check's `template_check_warning`s), rendered as a "Warnings" section in markdown — assembled by `pipelex/pipeline/advisory_warnings.py`, the ONE composition point every advisory-bearing channel calls (this CLI, the bare CLI and the protocol report). Bare `validate pipe <code>` carries the dry-run findings alone (`pipelex/pipeline/dry_run_warnings.py`), since one pipe has no flow to lint but what its dry run found is about it; `validate bundle` / `validate method` with `--pipe` carry every family, because they validate the whole bundle and only narrow the dry run, so the array stays bundle-wide there. Add a new advisory family there, never at a call site: the sites used to assemble their own and disagreed about which families they carried.- `fix`: `# Fix applied - bundle is valid` after one or more fixes, `# Bundle already valid` when the loop had nothing to apply, or `# Bundle valid but not runnable` when pending `PipeSignature` placeholders remain. The JSON success envelope carries `is_valid`, `bundle_path`, `iterations`, `fixes_applied`, `files_written`, `remaining_errors`, and, on successful validation, `pending_signatures` plus `is_runnable`. Whole-bundle fix runs are strict by default: they emit the success envelope but exit 1 on `not is_runnable` unless `--allow-signatures` is passed. A still-invalid verdict exits 1 via `FixBundleError` on stderr with the same structured result fields plus any `bail_reason`. `fix function-names <method folder>` is the migration of a method's flat PipeFunc `function_name`s into import paths from the method tree's root (`pipelex/migration/function_names.py`): `# Function names of the method at <folder>` then the rewrites, the `@pipe_func(...)` registration names dropped, the names left unresolved with their reason and candidates, and the markers whose argument it kept (one registering a name a step still holds unresolved, or one whose name is not a string literal); the JSON envelope carries `directory`, `is_dry_run`, `is_complete`, `changed_files`, `rewrites`, `marker_removals`, `unresolved` and `unresolved_markers`. It exits 1 after the envelope when a name or a marker is left unresolved, and 2 via `FunctionNamesMigrationError` when the folder is not a method tree.- `migrate`: `# Configuration migration`, the mode (applied / dry run) and verdict, the directories walked, a files-walked/changed/written count and, when a former release left something, its file count, then one `## <path>` section per file the former-release cleanup touches, listing its changes and its backup, a `## Pipelex still cannot start` section when the cleanup's check, run on every run, found something, and one per file that is not clean listing the entries applied, the entries blocked with their reason and guidance, and any unexplained paths. Paths, operation kinds, ledger-supplied values and the names of retired backends and profiles only — no value read from the user's file is ever rendered, in either format.- `init`: `# Pipelex initialized` with target directory and execution, then enabled backends and routing profile for a local setup, or whether a Pipelex API key is set for a hosted one.@@ -105,7 +105,8 @@ commands/- **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/`). A `run` writes into a new numbered folder, `results/<pipe_code>_output_<NN>/`, made by `make_run_output_folder` (`pipelex/cli/commands/run/_run_output_folder.py`) beside the bundle it ran, else under `mthds-wip/`; the folder holds a `.gitignore` of `*`, so a run's outputs never join the method tree and two runs read the same tree, with the same `method_tree_digest`. `run_pipeline_core`'s `output_dir_override` replaces the directory the folder is made under: `run method` on a fetched target (a method address or GitHub URL) passes `results/` under the caller's CWD, since the fetched clone is an ephemeral temp dir deleted at process exit, and `run bundle <folder> --pipe` passes the folder's `results/`, having no entry bundle to write beside.- **Validate refusals are verdicts**: the `validate` commands run their library load inside `translate_to_validate_bundle_error` (`pipelex/pipeline/validate_bundle_translation.py`), so every input-domained refusal raised while loading a bundle, the unknown model (`PipeOperatorModelChoiceError`, an `unknown_model` item) included, reaches the command as a `ValidateBundleError` and leaves with the invalid-verdict envelope and exit 1. No `validate` command keeps an arm of its own for a model-choice error; exit 2 stays for a failure of the tool or its environment (config, runtime, security).-- **Run refusals are verdicts too**: a run loads its bundle inside the same translation (`acquire_library`), so an invalid bundle leaves `run pipe` / `run bundle` / `run method` as a `ValidateBundleError` with exit 1, through the generic `agent_error` arm, and `_assemble_error_payload` copies the report's `validation_errors` into the envelope for any cause that carries them. `run_pipeline_core` sets `library_dirs_are_callers=True`, so a refusal in a `-L` directory (or the bundle's own directory) is the same verdict; `run bundle`'s own parse of a bundle without `--pipe` goes through the translation too, and so does its reading of the method tree: a folder resolves through `pipelex/cli/commands/run/_method_folder.py` (`resolve_method_folder_run`, the protocol's entry rule in `pipelex/pipeline/method_entry.py`) and a lone file through `list_bundle_file_tree`, so a folder with no single `main_pipe`, a tree past its limits or a symbolic link in the tree is a `ValidateBundleError` too. So no `run` command keeps an arm of its own for a model-choice error either: an unknown model reaches it as the verdict's `unknown_model` item.+- **Run refusals are verdicts too**: a run loads its bundle inside the same translation (`acquire_library`), so an invalid bundle leaves `run pipe` / `run bundle` / `run method` as a `ValidateBundleError` with exit 1, through the generic `agent_error` arm, and `_assemble_error_payload` copies the report's `validation_errors` into the envelope for any cause that carries them. `run_pipeline_core` sets `library_dirs_are_callers=True`, so a refusal in a `-L` directory (or the bundle's own directory) is the same verdict; `run bundle`'s own parse of a bundle without `--pipe` goes through the translation too, and so does its reading of the method tree: a folder resolves through `pipelex/cli/bundle_target_resolution.py` (`resolve_method_folder_run`, the protocol's entry rule in `pipelex/pipeline/method_entry.py`) and a lone file through `list_bundle_file_tree`, so a folder with no single `main_pipe`, a tree past its limits or a symbolic link in the tree is a `ValidateBundleError` too. So no `run` command keeps an arm of its own for a model-choice error either: an unknown model reaches it as the verdict's `unknown_model` item.+- **Two readings of a folder, one resolution path**: `run bundle`, `validate bundle`, `fix bundle` and `inputs bundle` read a folder through `pipelex/cli/bundle_target_resolution.py` (`run` through `resolve_method_folder_run`, the others through `resolve_bundle_target_core`, validate and fix by way of `pipelex/cli/judged_target.py`, whose `JudgedBundleTarget.judged_path` is the path the verdict names and whose `fix_judged_target` is the one fix dispatch both CLIs call, and of `commands/bundle_path_resolver.py`), as its method tree, but with the `FolderReading` their job asks for. `validate` and `fix` take `WHOLE_TREE`, the MTHDS protocol's validation (`mthds/docs/spec/protocol.md`): every bundle of the tree is judged (`validate_bundle(method_dir=..., library_dirs_are_callers=True)`, `fix_method_folder`), with no pipe to start at, so a folder whose bundles declare several `main_pipe`s, or none, is validated like any other; mthds-js's local runner calls `pipelex validate bundle <dir>` to validate a whole method at install and relies on this. `--pipe` there only narrows the dry run, and `--graph` / `--view` draw from the pipe named, else from the entry (`locate_folder_pipe`), or, when the folder decides none, put `graph_unavailable` in the envelope and leave the verdict alone. `run` and `inputs` take `ENTRY_PIPE`, acting on one pipe: the one `--pipe` names, else the protocol's entry (`select_method_entry` in `pipelex/pipeline/method_entry.py`); no single `main_pipe` is a `ValidateBundleError` verdict on a run and the `MethodEntryError` with exit 1 on `inputs`, the message the same. A folder holding no bundle is `EmptyMethodTreeError` with exit 2 on `validate` and `fix`, and a `MethodEntryError` saying it has no pipe to start at on the others. A folder whose tree is refused at resolution (past its limits, a symbolic link) is the invalid verdict: `ValidateBundleError` on `validate`, and on `fix` the `FixBundleError` envelope of a fix that could not start (`unfixable_method_result`), exit 1 both. A fix of a folder writes anywhere in its method tree, from the root (`method_tree_root`) down, and the human `--diff` preview mirrors that root, so a fix landing in a bundle above the folder named is proposed and written alike. Only the tree's own pipes are judged: `validate_bundle(method_dir=...)` keeps the blueprints its tree lists (`_is_member_blueprint`), so a nested package, a dependency or a `-L` directory loads without being judged; `dirs_beside_method` is the one place the `-L` directories naming the folder itself are dropped, compared resolved. Reading the tree's limits loads the configuration before the boot, so each resolution site catches `PipelexConfigError` and reports it through `report_agent_init_failure` (`agent_cli_factory.py`), the envelope a failed boot gives.- **Hosted runs**: every `run` subcommand takes `--runner local|hosted`, `--hosted/--local` and `--base-url`; `resolve_agent_run_execution()` (`run/_run_hosted.py`) settles them through `pipelex.hosted.execution.resolve_run_execution` (the flag, then `[run] execution`, then local), refusing a `--runner` that contradicts the flag pair and a `--base-url` on a local run; a `PipelexConfigError` there carries `AGENT_INIT_FAILURE_HINT`, the hint a failed boot gives (`agent_cli_factory.py`). A hosted run boots nothing: it builds a `HostedRunRequest` from what `pipelex/cli/commands/run/_hosted_sources.py` resolves (the bundle and its library's `.mthds` files, a pipe's library, or a method's files; an address or a catalog id as `method_ref` / `method_id`, never fetched) and `run_hosted_for_agent()` runs it through `pipelex.hosted.hosted_run.run_hosted`, which reads the signature and uploads local input files (only when some input string names an existing local file, so a method with an address-based dependency runs with any other inputs), then drives the lifecycle `start_and_wait` drives step by step (the `/v1/version` handshake, `start`, `wait_for_result`, and the blocking `execute` on a server with no run store), so a failure while following an acknowledged run is a `HostedRunPollingError` naming the run, and a transport failure after the run request was sent is a `HostedRunOutcomeUnknownError` rather than an `ApiUnreachableError`. `run_hosted`'s `on_started` callback records the acknowledged run's id, so Ctrl-C (`KeyboardInterrupt`, or the `CancelledError` of a cancelled task) leaves as a `HostedRunInterruptedError` envelope carrying `pipeline_run_id`, with exit code 130. `run bundle` on a file with no `-L` sends `PIPELEXPATH`'s files (`hosted_library_dirs`), and an installed method named like a catalog id is that method. An exception no hosted arm names leaves through the command-boundary catch-all as the envelope. Its success envelope is `build_run_output()`'s, with the main output's content as `json`, an empty `markdown`, the working memory dump and `pipeline_run_id`; nothing is written to disk. `--dry-run` / `--mock-inputs` are refused on it, while `--graph` and `--costs` are accepted and ignored. There is no global `--runner` any more, and no `ctx.obj`.- **Hosted refusals**: `agent_error_hosted()` routes pipelex-sdk's `ApiResponseError` (every `PipelexAPIClient` route raises it on a non-2xx answer) to `agent_error_api_response()`. `api_response_error_payload()` builds the envelope from the problem document alone: `error_type` is the runner's class (`ValidateBundleError` at load, as a local run reports it, or the root fault of a failed run, which a local run reports as `cause_type` under `PipelineExecutionError`; this path has no `cause_type`), `message` is the error's own `API POST /v1/start failed (<status>): <reason>` without the next step it appends, `hint` is `user_action.detail`, and `error_domain` / `error_category` / `retryable` / `validation_errors` / `pipe_code` / `pipe_stack` / `request_id` are the runner's, plus `error_code` (the problem's `code`), `retry_after_seconds` (the `Retry-After` header) and `http_status`. It deliberately bypasses `agent_error()`'s lookups: the dict hints keyed on a class name local commands (`doctor`, `check-model`) that cannot fix a remote refusal, and the domain is only the runner's to say, so one with no `error_domain` carries none. Both `error_domain` and `retryable` come from `pipelex.hosted.error_rendering.sent_verdict()`, the members the problem document carried, never from the verdict pipelex-sdk decides for every `ApiResponseError`, which fills an unsent member from its own status table and reads every 5xx, a 503 included, as retryable. A refusal with no `user_action` — the hosted plane's own answers in front of the runner: the gateway's 403 for a bad key, the rate limiter's 429, the unreachable runner's 503 — gets its status's next step from `pipelex.hosted.error_rendering` (`HOSTED_REFUSAL_NEXT_STEPS_BY_STATUS`, the table the human CLI reads too; 401 and 403 point at `PIPELEX_API_KEY` and `pipelex login`, 404 at the method and the origin), else `HOSTED_REFUSAL_CALLER_NEXT_STEP` for any other 4xx and `HOSTED_SERVER_FAULT_NEXT_STEP` for the rest. Only a 429 that did not say otherwise is inferred `retryable`: the platform can answer a 503 after the run completed, when it failed to record the result, so its hint warns that a retry can repeat a paid run. Every other failure, the SDK's and pipelex's own `HostedRunError` subclasses alike, goes through `agent_error()` with what `describe_hosted_error()` reads off it, the view the human CLI prints too: the class, message, next step, domain and `retryable`, the `pipeline_run_id` of any failure met once the run was acknowledged (`RunFailedError`, `RunTimeoutError`, `MissingMainStuffError`, `HostedRunPollingError`, `HostedRunInterruptedError`), a `retryable` passed whenever the hosted API gave a verdict, `false` included, so `RETRYABLE_ERROR_TYPES` keyed on the runner's class never overrides it, and the `validation_errors` of a failed run or of a `HostedMethodInvalidError` (pipe-io's verdict on a method that does not load, whose items name the faulty file in `source`); a `RunFailedError` adds `run_status` and its report's category, model and provider. The markdown renderer keeps a runner item this pipelex's `ValidationErrorItem` cannot type (a newer `error_type`, an unknown field) as JSON under Details instead of failing.- **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.diff --git a/pipelex/cli/agent_cli/_agent_cli.py b/pipelex/cli/agent_cli/_agent_cli.pyindex 8146c939a..ad97a597f 100644--- a/pipelex/cli/agent_cli/_agent_cli.py+++ b/pipelex/cli/agent_cli/_agent_cli.py@@ -155,7 +155,7 @@ def app_callback(app.command(name="init", help="Initialize Pipelex configuration (non-interactive)")(agent_init_cmd)app.add_typer(run_app, name="run", help="Execute a pipeline and output JSON results")app.add_typer(validate_app, name="validate", help="Validate a pipe, bundle, or all pipes and output JSON results")-app.add_typer(fix_app, name="fix", help="Fix a bundle file or pipeline directory in place, or migrate a method's function names")+app.add_typer(fix_app, name="fix", help="Fix a bundle file or a method's folder in place, or migrate a method's function names")app.command(name="fmt", help="Format a .mthds, .toml, or .plx file in-place")(fmt_cmd)app.command(name="lint", help="Lint a .mthds, .toml, or .plx file")(lint_cmd)app.add_typer(inputs_app, name="inputs", help="Generate example input JSON for a pipe")diff --git a/pipelex/cli/agent_cli/commands/agent_cli_factory.py b/pipelex/cli/agent_cli/commands/agent_cli_factory.pyindex 050ca1344..512ca7ac6 100644--- a/pipelex/cli/agent_cli/commands/agent_cli_factory.py+++ b/pipelex/cli/agent_cli/commands/agent_cli_factory.py@@ -5,7 +5,7 @@ import sysfrom collections.abc import Mappingfrom pathlib import Pathfrom types import MappingProxyType-from typing import Any+from typing import Any, NoReturnfrom pipelex.cli.agent_cli.commands.agent_output import agent_errorfrom pipelex.cogt.exceptions import ModelDeckPresetValidatonError@@ -163,6 +163,37 @@ def apply_agent_cli_output_discipline() -> None:hub.set_console_print_target(target=ConsoleTarget.STDERR)+def report_agent_init_failure(*, error: Exception) -> NoReturn:+ """Report a failure to initialize Pipelex, or to read the configuration it boots from, as the agent error envelope.++ The one account of a failed boot, given whether the boot raised it or a step reading this machine's configuration+ before the boot did, such as listing a method's tree under the configured limits: the same configuration fails the+ same way wherever it is first read.+ """+ if isinstance(error, TelemetryConfigValidationError):+ agent_error(error.message, error_type="TelemetryConfigValidationError", cause=error)+ if isinstance(error, FormerReleaseConfigError):+ # Its own hint, the class's user_action, rather than the generic one, which offers a reset: the cleanup keeps+ # everything but what a former release left, and an agent can run it.+ agent_error(error.message, error_type="FormerReleaseConfigError", cause=error)+ if isinstance(error, ModelDeckPresetValidatonError):+ agent_error(+ error.message,+ error_type="ModelDeckPresetValidatonError",+ cause=error,+ preset_id=error.preset_id,+ model_type=str(error.model_type),+ model_handle=error.model_handle,+ enabled_backends=sorted(error.enabled_backends),+ )+ agent_error(+ f"Pipelex initialization failed: {error}",+ error_type=type(error).__name__,+ cause=error,+ hint=AGENT_INIT_FAILURE_HINT,+ )++def make_pipelex_for_agent_cli(*, library_dirs: list[str] | list[Path] | None = None, needs_inference: bool = True) -> Pipelex:"""Initialize Pipelex for agent CLI commands with JSON error output.@@ -210,30 +241,10 @@ def make_pipelex_for_agent_cli(*, library_dirs: list[str] | list[Path] | None =needs_inference=needs_inference,config_overrides=dict(AGENT_CLI_CONFIG_OVERRIDES),)- except TelemetryConfigValidationError as exc:- agent_error(exc.message, error_type="TelemetryConfigValidationError", cause=exc)- except FormerReleaseConfigError as exc:- # Its own hint, the class's user_action, rather than the generic one, which offers a reset: the cleanup keeps- # everything but what a former release left, and an agent can run it.- agent_error(exc.message, error_type="FormerReleaseConfigError", cause=exc)- except ModelDeckPresetValidatonError as exc:- agent_error(- exc.message,- error_type="ModelDeckPresetValidatonError",- cause=exc,- preset_id=exc.preset_id,- model_type=str(exc.model_type),- model_handle=exc.model_handle,- enabled_backends=sorted(exc.enabled_backends),- )except Exception as exc: # ruff: ignore[blind-except]- # Agent CLI command boundary: agent_error() (NoReturn) converts any unexpected failure into the structured error payload.- agent_error(- f"Pipelex initialization failed: {exc}",- error_type=type(exc).__name__,- cause=exc,- hint=AGENT_INIT_FAILURE_HINT,- )+ # Agent CLI command boundary: report_agent_init_failure() (NoReturn) converts any boot failure into the structured+ # error payload, the known configuration failures with their own fields and hints.+ report_agent_init_failure(error=exc)# Silence pipelex logs and Rich pretty-printing so the agent CLI emits only the# structured success/error envelope. Defense-in-depth on top of the init-timediff --git a/pipelex/cli/agent_cli/commands/bundle_path_resolver.py b/pipelex/cli/agent_cli/commands/bundle_path_resolver.pyindex a1904517c..93dd3c074 100644--- a/pipelex/cli/agent_cli/commands/bundle_path_resolver.py+++ b/pipelex/cli/agent_cli/commands/bundle_path_resolver.py@@ -1,77 +1,54 @@"""Path-to-bundle resolution for agent CLI bundle commands.-``validate bundle`` and ``fix bundle`` must resolve the user's ``path`` argument identically —-fix must patch exactly the file validate judged. The shared core owns the filesystem-decision-making; this wrapper owns agent error envelopes.+``validate bundle`` and ``fix bundle`` must resolve the user's ``path`` argument identically: fix must patch exactly+what validate judged, a bundle file or a method's whole folder. The shared core (``pipelex.cli.judged_target``, over+``pipelex.cli.bundle_target_resolution``) owns the decision, the one every command taking a bundle path makes,+``run bundle`` included; this wrapper owns the agent error envelopes of a target that names nothing to judge, and of+a configuration that cannot be read before the boot."""-from pathlib import Path-from typing import NoReturn-+from pipelex.base_exceptions import PipelexConfigError+from pipelex.cli.agent_cli.commands.agent_cli_factory import report_agent_init_failurefrom pipelex.cli.agent_cli.commands.agent_output import agent_error-from pipelex.cli.bundle_target_resolution import (- BundleTargetResolutionError,- BundleTargetResolutionErrorKind,- BundleTargetResolutionSuccess,- resolve_bundle_target_core,-)-from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAME---def _stringify_library_dirs(library_dirs: list[Path] | None) -> list[str] | None:- if library_dirs is None:- return None- return [str(library_dir) for library_dir in library_dirs]+from pipelex.cli.bundle_target_resolution import BundleTargetResolutionError+from pipelex.cli.judged_target import JudgedBundleTarget, resolve_judged_target+from pipelex.libraries.exceptions import EmptyMethodTreeError-def _handle_resolution_error(error: BundleTargetResolutionError) -> NoReturn:- match error.kind:- case BundleTargetResolutionErrorKind.NO_MTHDS_FILE:- agent_error(f"No .mthds bundle file found in directory '{error.input_path}'", error_type="FileNotFoundError", exit_code=2)- case BundleTargetResolutionErrorKind.AMBIGUOUS_MTHDS_FILES:- mthds_names = ", ".join(mthds_file.name for mthds_file in error.candidate_files)- agent_error(- f"Multiple .mthds files found in '{error.input_path}' ({mthds_names}) and no '{DEFAULT_BUNDLE_FILE_NAME}'. "- f"Pass the .mthds file directly instead.",- error_type="ArgumentError",- exit_code=2,- )- case BundleTargetResolutionErrorKind.UNSAFE_AUTO_DETECTED_SYMLINK:- agent_error(- f"Refusing to auto-detect symlinked bundle '{error.candidate_files[0]}'. Pass a regular .mthds file inside the directory.",- error_type="ArgumentError",- exit_code=2,- )- case BundleTargetResolutionErrorKind.NOT_BUNDLE_TARGET:- agent_error(- f"'{error.input_path}' is not a .mthds file or directory. "- f"Use 'validate pipe <code>' for pipe codes, or 'validate bundle <path>' for .mthds files/directories.",- error_type="ArgumentError",- exit_code=2,- )+def resolve_bundle_target(path: str, *, library_dir: list[str] | None) -> JudgedBundleTarget:+ """Resolve the ``path`` argument of ``validate bundle`` or ``fix bundle`` into what the command judges.+ A folder is read as its method tree and judged whole, every bundle of it, as the MTHDS protocol's validation judges+ a method: it needs no pipe to start at. The folder is prepended to the library directories; a fix may write any+ bundle of its tree, being user-passed.-def resolve_bundle_target(path: str, *, library_dir: list[str] | None) -> tuple[str, list[str] | None]:- """Resolve a ``path`` CLI argument into ``(bundle_path, library_dir)``.+ A folder holding no bundle and a path that is neither a ``.mthds`` file nor a directory produce no verdict: exit 2+ via ``agent_error``. A configuration that does not validate, read for the tree's limits before the boot, is+ reported as the failed boot it would have been.- Directory mode auto-detects the bundle file — ``DEFAULT_BUNDLE_FILE_NAME`` if present, else- a single ``*.mthds`` — and prepends the directory itself to ``library_dir`` so sibling- files load (and, being user-passed, fall inside the fix write scope). No file / multiple- ambiguous files / not-a-``.mthds`` path exit 2 via ``agent_error`` (no verdict produced).-- Both ``path`` and each ``library_dir`` entry have ``~`` expanded before resolution, so- home-relative inputs behave like every other CLI path argument.+ Both ``path`` and each ``library_dir`` entry have ``~`` expanded before resolution, so home-relative inputs behave+ like every other CLI path argument.Args:- path: The user's ``path`` argument (a ``.mthds`` file or a bundle directory).+ path: The user's ``path`` argument (a ``.mthds`` file or a method's folder).library_dir: The ``-L/--library-dir`` values as passed, or ``None``.- Returns:- ``(bundle_path, library_dir)`` — the resolved bundle file path, and the possibly- directory-augmented library dirs (``None`` when none apply).+ Raises:+ ValidateBundleError: For a folder, its tree is refused or past this machine's limits: the invalid verdict,+ which the command renders as its own surface does."""- result = resolve_bundle_target_core(path, library_dir=library_dir)- if isinstance(result, BundleTargetResolutionSuccess):- return str(result.bundle_path), _stringify_library_dirs(result.library_dirs)-- _handle_resolution_error(result)+ try:+ result = resolve_judged_target(path=path, library_dir=library_dir)+ except EmptyMethodTreeError as exc:+ agent_error(exc.message, error_type=type(exc).__name__, cause=exc, exit_code=2)+ except PipelexConfigError as exc:+ report_agent_init_failure(error=exc)++ if isinstance(result, BundleTargetResolutionError):+ agent_error(+ f"'{result.input_path}' is not a .mthds file or directory. "+ f"Use 'validate pipe <code>' for pipe codes, or 'validate bundle <path>' for .mthds files/directories.",+ error_type="ArgumentError",+ exit_code=2,+ )+ return resultdiff --git a/pipelex/cli/agent_cli/commands/fix/app.py b/pipelex/cli/agent_cli/commands/fix/app.pyindex b11db5417..fbf3b1ff8 100644--- a/pipelex/cli/agent_cli/commands/fix/app.py+++ b/pipelex/cli/agent_cli/commands/fix/app.py@@ -10,5 +10,5 @@ fix_app = typer.Typer(no_args_is_help=True,)-fix_app.command(name="bundle", help="Fix a bundle file (.mthds) or pipeline directory")(fix_bundle_cmd)+fix_app.command(name="bundle", help="Fix a bundle file (.mthds) or a method's whole folder")(fix_bundle_cmd)fix_app.command(name="function-names", help="Rewrite a method's flat PipeFunc function names as import paths")(fix_function_names_cmd)diff --git a/pipelex/cli/agent_cli/commands/fix/bundle_cmd.py b/pipelex/cli/agent_cli/commands/fix/bundle_cmd.pyindex cfd9e6459..96c978985 100644--- a/pipelex/cli/agent_cli/commands/fix/bundle_cmd.py+++ b/pipelex/cli/agent_cli/commands/fix/bundle_cmd.py@@ -3,7 +3,7 @@import asyncioimport sysfrom pathlib import Path-from typing import Annotated, Any+from typing import Annotated, Any, NoReturnimport typer@@ -16,10 +16,12 @@ from pipelex.cli.agent_cli.commands.agent_output import (set_agent_cli_error_format,)from pipelex.cli.agent_cli.commands.bundle_path_resolver import resolve_bundle_target+from pipelex.cli.judged_target import fix_judged_targetfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import Pipelex-from pipelex.pipeline.fixes.fix_loop import FixBundleResult, fix_bundle_file+from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.fixes.fix_loop import FixBundleResult, unfixable_method_resultfrom pipelex.pipeline.fixes.fix_render import format_fix_markdown, format_fix_still_invalid_markdownfrom pipelex.pipeline.fixes.planner import KNOWN_FIX_CODES@@ -74,10 +76,26 @@ def _failure_message(result: FixBundleResult) -> str:return message+def _emit_still_invalid(*, result: FixBundleResult, bundle_path: str) -> NoReturn:+ """Emit the still-invalid verdict, format-aware, and exit 1.++ JSON keeps the exact FixBundleError envelope (the result fields + bail_reason via the payload); markdown renders the+ remaining errors as prose with their 💡 lines (mirroring the human still-invalid panel) instead of a raw JSON dump+ of the details.+ """+ payload = _result_payload(result, bundle_path=bundle_path)+ match get_agent_cli_error_format():+ case CliOutputFormat.JSON:+ agent_error(_failure_message(result), error_type="FixBundleError", exit_code=1, **payload)+ case CliOutputFormat.MARKDOWN:+ print(format_fix_still_invalid_markdown(result, bundle_path=str(payload["bundle_path"])), file=sys.stderr)+ raise typer.Exit(1)++def fix_bundle_cmd(path: Annotated[str,- typer.Argument(help="Path to a .mthds bundle file or a pipeline directory"),+ typer.Argument(help="Path to a .mthds bundle file, or a method's folder, whose every bundle is judged"),],library_dir: Annotated[list[str] | None,@@ -111,44 +129,44 @@ def fix_bundle_cmd(typer.Option("--error-format", help="Error output format (defaults to --format value): markdown or json"),] = None,) -> None:- """Fix a bundle file (.mthds) or pipeline directory in place."""+ """Fix a bundle file (.mthds) or a method's folder in place.++ A folder is judged whole, every bundle of its method tree, as `validate bundle` judges it.+ """set_agent_cli_error_format(error_format or output_format)select_codes = _normalize_rule_codes(select_codes_raw)ignore_codes = _normalize_rule_codes(ignore_codes_raw)_reject_invalid_rule_filters(select_codes=select_codes, ignore_codes=ignore_codes)- bundle_path, library_dir = resolve_bundle_target(path, library_dir=library_dir)- library_dirs = [Path(lib_dir) for lib_dir in library_dir] if library_dir else None+ # A folder is judged whole, every bundle of its method tree, as `validate bundle` judges it. A folder whose tree is+ # refused is the still-invalid verdict, with nothing to fix, as `validate bundle` gives it the invalid one.+ try:+ target = resolve_bundle_target(path, library_dir=library_dir)+ except ValidateBundleError as exc:+ _emit_still_invalid(result=unfixable_method_result(error=exc), bundle_path=str(Path(path).expanduser()))+ bundle_path = str(target.judged_path)+ library_dirs = target.library_dirstry:make_pipelex_for_agent_cli(library_dirs=library_dirs, needs_inference=False)result = asyncio.run(- fix_bundle_file(- Path(bundle_path),- library_dirs=library_dirs,+ fix_judged_target(+ target=target,+ writable_library_dirs=None,allow_signatures=allow_signatures,max_iterations=max_iterations,select_codes=select_codes,ignore_codes=ignore_codes,))- payload = _result_payload(result, bundle_path=bundle_path)if result.is_valid:+ payload = _result_payload(result, bundle_path=bundle_path)agent_success_formatted({"success": True, **payload}, markdown_renderer=format_fix_markdown, output_format=output_format)if not allow_signatures and result.is_runnable is False:raise typer.Exit(1)return-- # Still-invalid verdict: format-aware. JSON keeps the exact FixBundleError envelope (the result- # fields + bail_reason via **payload); markdown renders the remaining errors as prose with their- # 💡 lines (mirroring the human still-invalid panel) instead of a raw JSON dump of the details.- match get_agent_cli_error_format():- case CliOutputFormat.JSON:- agent_error(_failure_message(result), error_type="FixBundleError", exit_code=1, **payload)- case CliOutputFormat.MARKDOWN:- print(format_fix_still_invalid_markdown(result, bundle_path=str(payload["bundle_path"])), file=sys.stderr)- raise typer.Exit(1)+ _emit_still_invalid(result=result, bundle_path=bundle_path)except FileNotFoundError as exc:agent_error(f"Bundle file not found: {bundle_path}", error_type="FileNotFoundError", cause=exc, exit_code=2)diff --git a/pipelex/cli/agent_cli/commands/inputs/app.py b/pipelex/cli/agent_cli/commands/inputs/app.pyindex 7e1928468..b30915d6f 100644--- a/pipelex/cli/agent_cli/commands/inputs/app.py+++ b/pipelex/cli/agent_cli/commands/inputs/app.py@@ -15,4 +15,4 @@ inputs_app = typer.Typer(inputs_app.command(name="method", help="Generate example inputs for an installed method")(inputs_method_cmd)inputs_app.command(name="pipe", help="Generate example inputs for a pipe by code")(inputs_pipe_cmd)-inputs_app.command(name="bundle", help="Generate example inputs from a bundle file (.mthds) or directory")(inputs_bundle_cmd)+inputs_app.command(name="bundle", help="Generate example inputs from a bundle file (.mthds) or a method's folder")(inputs_bundle_cmd)diff --git a/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py b/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.pyindex 30efc54a0..fedf9fb6f 100644--- a/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py+++ b/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py@@ -3,27 +3,26 @@from __future__ import annotationsimport asyncio-from pathlib import Pathfrom typing import Annotated, Anyimport typer-from pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_cli+from pipelex.base_exceptions import PipelexConfigError+from pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_cli, report_agent_init_failurefrom pipelex.cli.agent_cli.commands.agent_output import agent_error, extract_validation_errorsfrom pipelex.cli.agent_cli.commands.inputs._inputs_core import emit_inputs_result, inputs_core+from pipelex.cli.bundle_target_resolution import BundleTargetResolutionError, FolderReading, resolve_bundle_target_corefrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError-from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_filefrom pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormatfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import Pipelex-from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAME-from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.exceptions import MethodEntryError, ValidateBundleErrordef inputs_bundle_cmd(path: Annotated[str,- typer.Argument(help="Path to a .mthds bundle file or a pipeline directory"),+ typer.Argument(help="Path to a .mthds bundle file, or a method's folder, which starts at its entry pipe unless --pipe names one"),],pipe: Annotated[str | None,@@ -55,48 +54,29 @@ def inputs_bundle_cmd(pipelex-agent inputs bundle pipeline_01/ --format tomlpipelex-agent inputs bundle pipeline_01/ --explicit"""- bundle_path: str | None = None- target_path = Path(path)-- if target_path.is_dir():- # Directory mode: auto-detect bundle file- bundle_file = target_path / DEFAULT_BUNDLE_FILE_NAME- if bundle_file.is_file():- bundle_path = str(bundle_file)- else:- mthds_files = list(target_path.glob(f"*{MTHDS_EXTENSION}"))- if len(mthds_files) == 0:- agent_error(f"No .mthds bundle file found in directory '{path}'", error_type="FileNotFoundError")- if len(mthds_files) > 1:- mthds_names = ", ".join(mthds_file.name for mthds_file in mthds_files)- agent_error(- f"Multiple .mthds files found in '{path}' ({mthds_names}) and no '{DEFAULT_BUNDLE_FILE_NAME}'. "- f"Pass the .mthds file directly instead.",- error_type="ArgumentError",- )- bundle_path = str(mthds_files[0])-- # Add directory as library dir- target_dir_str = str(target_path)- if library_dir is None:- library_dir = [target_dir_str]- elif target_dir_str not in library_dir:- library_dir = [target_dir_str, *library_dir]-- elif is_pipelex_file(target_path):- bundle_path = path- else:+ # A folder is read as its method tree: the pipe is the one named, else the one the method starts at, as `run bundle`+ # reads it. A folder whose pipe was named loads as the method's library, with no entry bundle, as `run bundle` runs it.+ try:+ target = resolve_bundle_target_core(path, library_dir=library_dir, reading=FolderReading.ENTRY_PIPE, pipe_override=pipe)+ except MethodEntryError as exc:+ agent_error(exc.message, error_type=type(exc).__name__, cause=exc)+ except ValidateBundleError as exc:+ agent_error(exc.message, error_type="ValidateBundleError", cause=exc, validation_errors=extract_validation_errors(exc))+ except PipelexConfigError as exc:+ # Listing the tree reads its limits from the configuration, before the boot would.+ report_agent_init_failure(error=exc)+ if isinstance(target, BundleTargetResolutionError):agent_error(f"'{path}' is not a .mthds file or directory. "f"Use 'inputs pipe <code>' for pipe codes, or 'inputs bundle <path>' for .mthds files/directories.",error_type="ArgumentError",)-- library_dirs = [Path(lib_dir) for lib_dir in library_dir] if library_dir else None+ bundle_path = target.bundle_path+ library_dirs = target.library_dirsmake_pipelex_for_agent_cli(library_dirs=library_dirs, needs_inference=False)try:- result = asyncio.run(inputs_core(pipe_code=pipe, bundle_path=Path(bundle_path), library_dirs=library_dirs, explicit=explicit)) # type: ignore[arg-type]+ result = asyncio.run(inputs_core(pipe_code=target.pipe_code, bundle_path=bundle_path, library_dirs=library_dirs, explicit=explicit))emit_inputs_result(result, template_format=template_format, explicit=explicit)except FileNotFoundError as exc:diff --git a/pipelex/cli/agent_cli/commands/run/bundle_cmd.py b/pipelex/cli/agent_cli/commands/run/bundle_cmd.pyindex 593854e8d..6ee1041a4 100644--- a/pipelex/cli/agent_cli/commands/run/bundle_cmd.py+++ b/pipelex/cli/agent_cli/commands/run/bundle_cmd.py@@ -9,7 +9,8 @@ from typing import TYPE_CHECKING, Annotated, Anyimport typer-from pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_cli+from pipelex.base_exceptions import PipelexConfigError+from pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_cli, report_agent_init_failurefrom pipelex.cli.agent_cli.commands.agent_output import (CliOutputFormat,agent_error,@@ -28,8 +29,8 @@ from pipelex.cli.agent_cli.commands.run._run_hosted import (run_hosted_for_agent,)from pipelex.cli.agent_cli.commands.run.stdin_resolver import parse_cli_inputs+from pipelex.cli.bundle_target_resolution import list_bundle_file_tree, resolve_method_folder_runfrom pipelex.cli.commands.run._hosted_sources import collect_mthds_files, hosted_library_dirs-from pipelex.cli.commands.run._method_folder import list_bundle_file_tree, resolve_method_folder_runfrom pipelex.cli.commands.run._run_output_folder import RUN_RESULTS_DIR_NAMEfrom pipelex.hosted.exceptions import HostedRunSourceErrorfrom pipelex.hosted.hosted_run import HostedRunRequest@@ -48,7 +49,7 @@ if TYPE_CHECKING:def run_bundle_cmd(path: Annotated[str,- typer.Argument(help="Path to a .mthds bundle file or a pipeline directory"),+ typer.Argument(help="Path to a .mthds bundle file, or a method's folder, which starts at its entry pipe unless --pipe names one"),],pipe: Annotated[str | None,@@ -141,6 +142,9 @@ def run_bundle_cmd(folder_run = resolve_method_folder_run(directory=target_path, pipe_override=pipe)except ValidateBundleError as exc:agent_error(exc.message, error_type="ValidateBundleError", cause=exc)+ except PipelexConfigError as exc:+ # Listing the tree reads its limits from the configuration, before the boot would.+ report_agent_init_failure(error=exc)method_tree = folder_run.treepipe_code = folder_run.pipe_codeif folder_run.entry is not None and folder_run.entry_bundle_file is not None:@@ -167,6 +171,8 @@ def run_bundle_cmd(method_tree = list_bundle_file_tree(bundle_file=target_path)except ValidateBundleError as exc:agent_error(exc.message, error_type="ValidateBundleError", cause=exc)+ except PipelexConfigError as exc:+ report_agent_init_failure(error=exc)else:agent_error(f"'{path}' is not a .mthds file or directory. Use 'run pipe <code>' for pipe codes, or 'run bundle <path>' for .mthds files/directories.",diff --git a/pipelex/cli/agent_cli/commands/validate/_validate_core.py b/pipelex/cli/agent_cli/commands/validate/_validate_core.pyindex c6eb0e986..b15fb5ee5 100644--- a/pipelex/cli/agent_cli/commands/validate/_validate_core.py+++ b/pipelex/cli/agent_cli/commands/validate/_validate_core.py@@ -154,6 +154,61 @@ async def validate_bundle_core(}+async def validate_method_folder_core(+ *,+ method_dir: Path,+ library_dirs: list[Path] | None,+ allow_signatures: bool,+ pipe_code: str | None,+) -> dict[str, Any]:+ """Validate a method's folder whole: every bundle of its method tree, as the MTHDS protocol's validation judges a method.++ The folder needs no pipe to start at. Every pipe its bundles define is dry-run, or only ``pipe_code`` when one is+ named, while the whole tree still loads; the ``library_dirs`` load beside it for its bundles to use and are not+ judged.++ Args:+ method_dir: The method's folder.+ library_dirs: The folder and the ``-L`` directories, the caller's own.+ allow_signatures: Whether to accept PipeSignature placeholders in the dependency graph.+ pipe_code: The one pipe to dry-run, or None for every pipe of the method.++ Returns:+ Dictionary with validation results suitable for JSON serialization, ``bundle_path`` naming the folder.++ Raises:+ ValidateBundleError: If validation fails.+ EntryPipeNotFoundError: If ``pipe_code`` is defined by no bundle of the method.+ """+ with MethodValidationReport() as validation_report:+ result = await validate_bundle(+ method_dir=method_dir,+ library_dirs=library_dirs,+ library_dirs_are_callers=True,+ allow_signatures=allow_signatures,+ dry_run_pipe_codes=[pipe_code] if pipe_code else None,+ collect_dry_run_warnings=True,+ )+ warnings = collect_advisory_warnings(+ pipes=result.pipes,+ entry_pipe_refs=collect_entry_pipe_refs(result.blueprints),+ dry_run_result=result.dry_run_result,+ )+ validation_report.describe(pipes=result.pipes)+ validation_report.count_warnings(count=len(warnings))++ return {+ "success": True,+ "is_valid": True,+ "bundle_path": str(method_dir),+ "validated_pipes": build_validated_pipes(result.dry_run_result),+ "total_pipes": len(result.dry_run_result),+ "pending_signatures": result.pending_signatures,+ "is_runnable": not result.pending_signatures,+ "warnings": [warning.model_dump(exclude_none=True) for warning in warnings],+ }++async def validate_pipe_core(pipe_code: str,*,diff --git a/pipelex/cli/agent_cli/commands/validate/app.py b/pipelex/cli/agent_cli/commands/validate/app.pyindex d2d0ed192..1982684a2 100644--- a/pipelex/cli/agent_cli/commands/validate/app.py+++ b/pipelex/cli/agent_cli/commands/validate/app.py@@ -15,4 +15,4 @@ validate_app = typer.Typer(validate_app.command(name="method", help="Validate an installed method")(validate_method_cmd)validate_app.command(name="pipe", help="Validate a pipe by code, or all pipes")(validate_pipe_cmd)-validate_app.command(name="bundle", help="Validate a bundle file (.mthds) or pipeline directory")(validate_bundle_cmd)+validate_app.command(name="bundle", help="Validate a bundle file (.mthds) or a method's whole folder")(validate_bundle_cmd)diff --git a/pipelex/cli/agent_cli/commands/validate/bundle_cmd.py b/pipelex/cli/agent_cli/commands/validate/bundle_cmd.pyindex 6b02bb77d..ee5dd482f 100644--- a/pipelex/cli/agent_cli/commands/validate/bundle_cmd.py+++ b/pipelex/cli/agent_cli/commands/validate/bundle_cmd.py@@ -2,10 +2,11 @@import asynciofrom pathlib import Path-from typing import Annotated, Any+from typing import Annotated, Any, NamedTupleimport typer+from pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_clifrom pipelex.cli.agent_cli.commands.agent_output import (CliOutputFormat,@@ -18,23 +19,55 @@ from pipelex.cli.agent_cli.commands.agent_output import (from pipelex.cli.agent_cli.commands.bundle_path_resolver import resolve_bundle_targetfrom pipelex.cli.agent_cli.commands.validate._validate_core import (validate_bundle_core,+ validate_method_folder_core,validate_pipe_in_bundle_core,)+from pipelex.cli.bundle_target_resolution import locate_folder_pipe+from pipelex.cli.judged_target import JudgedBundleTargetfrom pipelex.graph.graph_rendering import GraphFormatfrom pipelex.libraries.pipe.exceptions import PipeNotFoundErrorfrom pipelex.mthds_parsing.exceptions import MthdsParserErrorfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import Pipelexfrom pipelex.pipeline.bundle_graph_rendering import generate_graph_for_bundle, generate_view_for_bundle-from pipelex.pipeline.exceptions import PipelineExecutionError, ValidateBundleError+from pipelex.pipeline.exceptions import MethodEntryError, PipelineExecutionError, ValidateBundleErrorfrom pipelex.pipeline.validation_render import format_validate_markdownfrom pipelex.tools.misc.chart_utils import FlowchartDirection+_GRAPH_UNAVAILABLE_KEY = "graph_unavailable"+++class _GraphTarget(NamedTuple):+ """The bundle file a graph is drawn from, and the pipe drawn: the one named, else the bundle's or method's entry."""++ bundle_path: Path+ pipe_code: str | None+++def _graph_target(*, target: JudgedBundleTarget, pipe: str | None) -> _GraphTarget | str:+ """Where `--graph` and `--view` draw from, or why no graph is drawn.++ A bundle file draws its pipe named, else its own `main_pipe`. A method's folder, judged whole, draws the pipe named,+ in the bundle defining it, else the pipe the method starts at by the MTHDS protocol's rule; when no single bundle+ defines the pipe named, or the method has no single pipe to start at, nothing is drawn and the reason is returned,+ the validation standing as it is.+ """+ if target.bundle_path is not None:+ return _GraphTarget(bundle_path=target.bundle_path, pipe_code=pipe)+ if target.method_tree is None:+ msg = "A method's folder was resolved without its method tree."+ raise PipelexUnexpectedError(msg)+ try:+ entry = locate_folder_pipe(tree=target.method_tree, pipe_override=pipe)+ except MethodEntryError as exc:+ return f"No graph was drawn, since a graph is drawn from one pipe: {exc.message}"+ return _GraphTarget(bundle_path=target.method_tree.file_location(entry.tree_path), pipe_code=entry.pipe_ref)+def validate_bundle_cmd(path: Annotated[str,- typer.Argument(help="Path to a .mthds bundle file or a pipeline directory"),+ typer.Argument(help="Path to a .mthds bundle file, or a method's folder, whose every bundle is judged"),],pipe: Annotated[str | None,@@ -76,7 +109,10 @@ def validate_bundle_cmd(typer.Option("--error-format", help="Error output format (defaults to --format value): markdown or json"),] = None,) -> None:- """Validate a bundle file (.mthds) or pipeline directory and output the results.+ """Validate a bundle file (.mthds) or a method's folder and output the results.++ A folder is judged whole: every bundle of its method tree, with no pipe to start at needed. --pipe narrows the dry+ run to one pipe. --graph and --view draw the pipe named, else the method's main pipe, and say so when it has none.Default output is markdown; use --format json for structured JSON.Results go to stdout on success, errors to stderr with exit code 1.@@ -85,15 +121,26 @@ def validate_bundle_cmd(pipelex-agent validate bundle my_bundle.mthdspipelex-agent validate bundle my_bundle.mthds --pipe my_pipepipelex-agent validate bundle my_bundle.mthds --graph- pipelex-agent validate bundle pipeline_01/- pipelex-agent validate bundle pipeline_01/ --graph+ pipelex-agent validate bundle my_method/+ pipelex-agent validate bundle my_method/ --pipe my_domain.my_pipe+ pipelex-agent validate bundle my_method/ --graphpipelex-agent validate bundle draft_pipeline.mthds --allow-signatures"""set_agent_cli_error_format(error_format or output_format)- bundle_path, library_dir = resolve_bundle_target(path, library_dir=library_dir)-- library_dirs = [Path(lib_dir) for lib_dir in library_dir] if library_dir else None+ # A folder is judged whole, as the MTHDS protocol's validation judges a method: every bundle of its tree.+ try:+ target = resolve_bundle_target(path, library_dir=library_dir)+ except ValidateBundleError as exc:+ agent_error_validate_bundle(+ exc,+ bundle_path=Path(path).expanduser(),+ library_dirs=[Path(lib_dir).expanduser() for lib_dir in library_dir] if library_dir else None,+ allow_signatures=allow_signatures,+ )+ # The path judged: the method's folder, or the bundle file.+ judged_path = target.judged_path+ library_dirs = target.library_dirs# Convert library_dirs to list[str] for graph helperlibrary_dir_strings = [str(lib_dir) for lib_dir in library_dirs] if library_dirs else None@@ -101,26 +148,35 @@ def validate_bundle_cmd(make_pipelex_for_agent_cli(library_dirs=library_dirs, needs_inference=False)try:- if pipe:- # Validate a specific pipe within the bundle+ if target.method_dir is not None:+ # The whole method, every pipe of it, or only the pipe named while the whole tree loadsresult = asyncio.run(- validate_pipe_in_bundle_core(- bundle_path=Path(bundle_path), pipe_code=pipe, library_dirs=library_dirs, allow_signatures=allow_signatures+ validate_method_folder_core(+ method_dir=target.method_dir, library_dirs=library_dirs, allow_signatures=allow_signatures, pipe_code=pipe))+ elif pipe:+ # Validate a specific pipe within the bundle+ result = asyncio.run(+ validate_pipe_in_bundle_core(bundle_path=judged_path, pipe_code=pipe, library_dirs=library_dirs, allow_signatures=allow_signatures)+ )else:# Validate the entire bundle- result = asyncio.run(validate_bundle_core(bundle_path=Path(bundle_path), library_dirs=library_dirs, allow_signatures=allow_signatures))+ result = asyncio.run(validate_bundle_core(bundle_path=judged_path, library_dirs=library_dirs, allow_signatures=allow_signatures))++ graph_target: _GraphTarget | str | None = _graph_target(target=target, pipe=pipe) if graph or view else None+ if isinstance(graph_target, str):+ result[_GRAPH_UNAVAILABLE_KEY] = graph_target# Generate graph if requested and validation succeeded- if graph:+ if graph and isinstance(graph_target, _GraphTarget):try:graph_result = asyncio.run(generate_graph_for_bundle(- bundle_path=Path(bundle_path),+ bundle_path=graph_target.bundle_path,graph_format=graph_format,library_dirs=library_dir_strings,- pipe_code=pipe,+ pipe_code=graph_target.pipe_code,direction=direction,))@@ -142,13 +198,13 @@ def validate_bundle_cmd(agent_error(f"Graph generation failed: {exc}", error_type=type(exc).__name__, cause=exc, exit_code=2)# Generate view (GraphSpec JSON) if requested and validation succeeded- if view:+ if view and isinstance(graph_target, _GraphTarget):try:view_result = asyncio.run(generate_view_for_bundle(- bundle_path=Path(bundle_path),+ bundle_path=graph_target.bundle_path,library_dirs=library_dir_strings,- pipe_code=pipe,+ pipe_code=graph_target.pipe_code,direction=direction,))@@ -189,14 +245,14 @@ def validate_bundle_cmd(agent_error(str(exc), error_type=type(exc).__name__, cause=exc, exit_code=2)except FileNotFoundError as exc:- agent_error(f"Bundle file not found: {bundle_path}", error_type="FileNotFoundError", cause=exc, exit_code=2)+ agent_error(f"Bundle file not found: {judged_path}", error_type="FileNotFoundError", cause=exc, exit_code=2)except ValidateBundleError as exc:# Invalid verdict: emit the format-aware failure surface. JSON keeps the exact structured# envelope (is_valid:false discriminant + validation_errors[], the shared builder's output,# non-empty on every invalid verdict); markdown renders those items as prose with a fix-aware# footer. Signatures never reach here (they are a runnability fact, gated above).- agent_error_validate_bundle(exc, bundle_path=Path(bundle_path), library_dirs=library_dirs, allow_signatures=allow_signatures)+ agent_error_validate_bundle(exc, bundle_path=judged_path, library_dirs=library_dirs, allow_signatures=allow_signatures)except PipeOperatorModelAvailabilityError as exc:availability_extra: dict[str, Any] = {diff --git a/pipelex/cli/bundle_target_resolution.py b/pipelex/cli/bundle_target_resolution.pyindex 460aa997e..a712accba 100644--- a/pipelex/cli/bundle_target_resolution.py+++ b/pipelex/cli/bundle_target_resolution.py@@ -1,105 +1,238 @@-"""Shared bundle target resolution for human and agent CLI wrappers."""+"""How every CLI command taking a bundle path reads it: a `.mthds` file, or a method's folder.++`run bundle`, `validate bundle`, `fix bundle`, `pipelex-agent inputs bundle`, `pipelex build inputs bundle` and+`pipelex build output bundle`, on both CLIs, read their target here, so the same arguments name the same method on every+command:++- A folder is the method rooted at the nearest `METHODS.toml` at or above it, else at the folder itself, listed as its+ method tree under this machine's limits (`[interpreter.method_tree_limits]`). The folder joins the library+ directories, ahead of `-L`. What a command reads of it depends on what the command does (`FolderReading`):+ - A command acting on one pipe, `run`, `inputs` and `build`, acts on the pipe named, else on the pipe the MTHDS+ protocol says a run naming no pipe starts at (`pipelex.pipeline.method_entry`): the manifest's `main_pipe`, else+ the one `main_pipe` its bundles declare; none or several is refused, the bundles named by their tree paths.+ - A command judging the method, `validate` and `fix`, reads the whole tree, every bundle of it, as the protocol's+ validation does, and so needs no pipe to start at.+- A `.mthds` file named alone is the member of its own file's tree (see `list_bundle_file_tree`), and acts on its own+ `main_pipe` unless a pipe is named.++The shared core decides; each command renders the refusals as its own surface renders them.+"""from enum import StrEnumfrom pathlib import Pathfrom typing import NamedTuple-from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file-from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAME---class BundleTargetResolutionErrorKind(StrEnum):- """Failure kinds for resolving a CLI bundle target."""-- NO_MTHDS_FILE = "no_mthds_file"- AMBIGUOUS_MTHDS_FILES = "ambiguous_mthds_files"- UNSAFE_AUTO_DETECTED_SYMLINK = "unsafe_auto_detected_symlink"- NOT_BUNDLE_TARGET = "not_bundle_target"+from mthds.method_tree.discovery import BUNDLE_SUFFIX+from mthds.method_tree.models import MethodTree++from pipelex.libraries.exceptions import EmptyMethodTreeError, MethodTreeLoadError+from pipelex.libraries.method_trees import list_local_method_tree+from pipelex.mthds_parsing.helpers import is_pipelex_file+from pipelex.pipeline.exceptions import MethodEntryError+from pipelex.pipeline.method_entry import (+ MethodEntry,+ read_method_candidates,+ read_method_manifest,+ select_entry,+ select_named_pipe,+ tree_method_label,+)+from pipelex.pipeline.validate_bundle import dirs_beside_method+from pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_error+++class FolderReading(StrEnum):+ """What a command handed a method's folder reads of it."""++ # The pipe named, else the pipe the method starts at, in the bundle defining it: `run`, `inputs`, `build`.+ ENTRY_PIPE = "entry_pipe"+ # Every bundle of the method's tree, with no pipe to start at: `validate`, `fix`.+ WHOLE_TREE = "whole_tree"+++class MethodFolderTarget(NamedTuple):+ """A method's folder handed to a command acting on one pipe: its tree, that pipe, and the bundle defining it."""++ tree: MethodTree+ #: The pipe named, as given, else the selected entry's `domain.pipe_code`.+ pipe_code: str+ #: The pipe the protocol's rule selected, or None when the caller named the pipe.+ entry: MethodEntry | None+ #: The file on this host of the bundle defining the selected entry, or None when the caller named the pipe.+ entry_bundle_file: Path | None+++def list_method_folder(*, directory: Path) -> MethodTree:+ """The method tree of a folder handed to a command.++ Raises:+ EmptyMethodTreeError: The tree holds no bundle: the membership rule keeps every file of the folder out of it, or+ none of the files it keeps is a bundle. The folder names no method, which each command reports as it reports+ a target it cannot resolve.+ ValidateBundleError: The tree is refused otherwise, or past this machine's limits, as the invalid verdict+ `validate` gives.+ """+ msg = f"The folder '{directory}' holds no .mthds bundle."+ try:+ tree = list_local_method_tree(handed_over=directory)+ except EmptyMethodTreeError as exc:+ raise EmptyMethodTreeError(msg) from exc+ except MethodTreeLoadError:+ with translate_to_validate_bundle_error():+ raise+ if not any(tree_path.endswith(BUNDLE_SUFFIX) for tree_path in tree.tree_paths):+ raise EmptyMethodTreeError(msg)+ return tree+++def resolve_method_folder(*, directory: Path, pipe_override: str | None) -> MethodFolderTarget:+ """List a method folder's tree and settle the one pipe a command acts on.++ Raises:+ MethodEntryError: The folder holds no bundle, or no pipe was named and the method has no single pipe to start+ at, or its manifest cannot be read: the target names no pipe, which each command reports as it reports a+ target it cannot resolve.+ ValidateBundleError: The tree is refused or past this machine's limits, or a bundle's declarations cannot be+ read, each as the invalid verdict `validate` gives.+ """+ try:+ tree = list_method_folder(directory=directory)+ except EmptyMethodTreeError as exc:+ msg = f"The folder '{directory}' holds no .mthds bundle, so it has no pipe to start at."+ raise MethodEntryError(msg) from exc+ if pipe_override:+ return MethodFolderTarget(tree=tree, pipe_code=pipe_override, entry=None, entry_bundle_file=None)+ with translate_to_validate_bundle_error():+ candidates = read_method_candidates(tree=tree)+ manifest = read_method_manifest(tree=tree)+ entry = select_entry(candidates=candidates, manifest=manifest, method_label=tree_method_label(tree=tree))+ return MethodFolderTarget(tree=tree, pipe_code=entry.pipe_ref, entry=entry, entry_bundle_file=tree.file_location(entry.tree_path))+++def resolve_method_folder_run(*, directory: Path, pipe_override: str | None) -> MethodFolderTarget:+ """A method folder as `run bundle` reads it: every refusal, the method's lack of a single entry included, is the verdict.++ Raises:+ ValidateBundleError: The tree is refused or past this machine's limits, a bundle does not parse, or the method+ has no single pipe to start at, each as the invalid verdict `validate` gives.+ """+ with translate_to_validate_bundle_error():+ return resolve_method_folder(directory=directory, pipe_override=pipe_override)+++def locate_folder_pipe(*, tree: MethodTree, pipe_override: str | None) -> MethodEntry:+ """The bundle of a method's tree defining the pipe named, else the pipe the method starts at, and its bundle.++ For a command that judged the whole tree and then draws one pipe of it, such as `validate bundle --graph`.++ Raises:+ MethodEntryError: No pipe was named and the method has no single pipe to start at, or no single bundle of the+ method defines the pipe named.+ ValidateBundleError: A bundle's declarations cannot be read, as the invalid verdict `validate` gives.+ """+ with translate_to_validate_bundle_error():+ candidates = read_method_candidates(tree=tree)+ method_label = tree_method_label(tree=tree)+ if pipe_override:+ return select_named_pipe(candidates=candidates, pipe_ref=pipe_override, method_label=method_label)+ return select_entry(candidates=candidates, manifest=read_method_manifest(tree=tree), method_label=method_label)+++def list_bundle_file_tree(*, bundle_file: Path) -> MethodTree:+ """The method tree of a `.mthds` file named alone, as the run loads it.++ It is the member of the tree rooted at the nearest `METHODS.toml` at or above its folder, else the one-file tree of+ that file, from which a reference to any other file is refused.++ Raises:+ ValidateBundleError: The tree is refused or past this machine's limits, as the invalid verdict `validate` gives.+ """+ with translate_to_validate_bundle_error():+ return list_local_method_tree(handed_over=bundle_file)class BundleTargetResolutionSuccess(NamedTuple):- """Successful bundle target resolution."""-- bundle_path: Path+ """A resolved bundle target: the bundle file or the method folder a command reads, the pipe it acts on, its library."""++ #: The file named, or the file of the bundle defining a folder's entry pipe; None for a folder read whole, or whose+ #: pipe was named.+ bundle_path: Path | None+ #: The pipe named, or a folder's entry pipe as `domain.pipe_code`; None for a file named with no pipe, which acts+ #: on its own `main_pipe`, and for a folder read whole with no pipe named.+ pipe_code: str | None+ #: The folder, then the `-L` directories, `~` expanded; None for a file named with no `-L`.library_dirs: list[Path] | None- auto_detected: bool+ #: The folder named, `~` expanded, or None for a file.+ method_dir: Path | None+ #: The folder's method tree, or None for a file.+ method_tree: MethodTree | None+ #: The pipe the protocol's rule selected for a folder whose command acts on one pipe and named none, else None.+ entry: MethodEntry | Noneclass BundleTargetResolutionError(NamedTuple):- """Typed resolution failure for CLI-specific rendering."""+ """A path that is neither a `.mthds` file nor a directory: no bundle target, for the command to report."""- kind: BundleTargetResolutionErrorKindinput_path: strtarget_path: Path- candidate_files: list[Path]def resolve_bundle_target_core(path: str,*,library_dir: list[str] | None,+ reading: FolderReading,+ pipe_override: str | None = None,) -> BundleTargetResolutionSuccess | BundleTargetResolutionError:- """Resolve a CLI path argument without deciding how errors are rendered."""+ """Resolve a CLI path argument without deciding how errors are rendered.++ Args:+ path: The `path` argument, a `.mthds` file or a method's folder, `~` expanded.+ library_dir: The `-L/--library-dir` values as passed, `~` expanded.+ reading: What the command reads of a folder: the one pipe it acts on, or the whole tree.+ pipe_override: The pipe the caller named with `--pipe`, if any.++ Raises:+ EmptyMethodTreeError: For a folder read whole, it holds no bundle.+ MethodEntryError: For a folder whose command acts on one pipe, it holds no bundle, or no pipe was named and the+ method has no single pipe to start at.+ ValidateBundleError: For a folder, its tree is refused or a bundle's declarations cannot be read.+ """library_dirs = [Path(library_dir_item).expanduser() for library_dir_item in library_dir] if library_dir else Nonetarget_path = Path(path).expanduser()if target_path.is_dir():- default_bundle_path = target_path / DEFAULT_BUNDLE_FILE_NAME- if default_bundle_path.is_symlink():- return BundleTargetResolutionError(- kind=BundleTargetResolutionErrorKind.UNSAFE_AUTO_DETECTED_SYMLINK,- input_path=path,- target_path=target_path,- candidate_files=[default_bundle_path],- )- if default_bundle_path.is_file():- bundle_path = default_bundle_path- else:- mthds_files = sorted(target_path.glob(f"*{MTHDS_EXTENSION}"), key=lambda file_path: file_path.name)- if len(mthds_files) == 0:- return BundleTargetResolutionError(- kind=BundleTargetResolutionErrorKind.NO_MTHDS_FILE,- input_path=path,- target_path=target_path,- candidate_files=[],- )- if len(mthds_files) == 1 and mthds_files[0].is_symlink():- return BundleTargetResolutionError(- kind=BundleTargetResolutionErrorKind.UNSAFE_AUTO_DETECTED_SYMLINK,- input_path=path,- target_path=target_path,- candidate_files=mthds_files,+ # The folder first, then the -L directories that are not the folder, however either is spelled.+ library_dirs = [target_path, *dirs_beside_method(method_dir=target_path, library_dirs=library_dirs)]+ match reading:+ case FolderReading.ENTRY_PIPE:+ folder = resolve_method_folder(directory=target_path, pipe_override=pipe_override)+ return BundleTargetResolutionSuccess(+ bundle_path=folder.entry_bundle_file,+ pipe_code=folder.pipe_code,+ library_dirs=library_dirs,+ method_dir=target_path,+ method_tree=folder.tree,+ entry=folder.entry,)- if len(mthds_files) > 1:- return BundleTargetResolutionError(- kind=BundleTargetResolutionErrorKind.AMBIGUOUS_MTHDS_FILES,- input_path=path,- target_path=target_path,- candidate_files=mthds_files,+ case FolderReading.WHOLE_TREE:+ return BundleTargetResolutionSuccess(+ bundle_path=None,+ pipe_code=pipe_override,+ library_dirs=library_dirs,+ method_dir=target_path,+ method_tree=list_method_folder(directory=target_path),+ entry=None,)- bundle_path = mthds_files[0]-- if library_dirs is None:- library_dirs = [target_path]- elif target_path not in library_dirs:- library_dirs = [target_path, *library_dirs]-- return BundleTargetResolutionSuccess(- bundle_path=bundle_path,- library_dirs=library_dirs,- auto_detected=True,- )if is_pipelex_file(target_path):return BundleTargetResolutionSuccess(bundle_path=target_path,+ pipe_code=pipe_override,library_dirs=library_dirs,- auto_detected=False,+ method_dir=None,+ method_tree=None,+ entry=None,)- return BundleTargetResolutionError(- kind=BundleTargetResolutionErrorKind.NOT_BUNDLE_TARGET,- input_path=path,- target_path=target_path,- candidate_files=[],- )+ return BundleTargetResolutionError(input_path=path, target_path=target_path)diff --git a/pipelex/cli/commands/build/inputs/_inputs_core.py b/pipelex/cli/commands/build/inputs/_inputs_core.pyindex 7706dfd81..e5c2bd98e 100644--- a/pipelex/cli/commands/build/inputs/_inputs_core.py+++ b/pipelex/cli/commands/build/inputs/_inputs_core.py@@ -38,22 +38,24 @@ async def _generate_inputs_core(pipe_code: str | None = None,bundle_path: Path | None = None,output_path: Path | None = None,+ default_output_dir: Path | None = None,library_dir: list[str] | None = None,template_format: InputsTemplateFormat = InputsTemplateFormat.JSON,explicit: bool = False,) -> None:- """Core logic for generating an inputs template file for a pipe."""- # Set up library so pipes can be found- library_manager = get_library_manager()- library_id, _ = library_manager.open_library()- set_current_library(library_id=library_id)- effective_dirs, _ = resolve_library_dirs(library_dir)- if effective_dirs:- library_manager.load_libraries(library_id=library_id, library_dirs=effective_dirs)+ """Core logic for generating an inputs template file for a pipe.+ The file goes to ``output_path``, else into ``default_output_dir`` (a method's folder, where ``run bundle`` finds+ it), else beside the bundle, else under ``results/``.+ """if bundle_path:try:- validate_bundle_result = await validate_bundle(mthds_file_path=bundle_path)+ # The bundle loads in one library with the method's whole folder and the -L directories, as `run bundle`+ # loads it, so a concept or a pipe it takes from a sibling bundle of its method resolves.+ validate_bundle_result = await validate_bundle(+ mthds_file_path=bundle_path,+ library_dirs=[Path(one_dir) for one_dir in library_dir] if library_dir else None,+ )bundle_blueprint = validate_bundle_result.blueprints[0]if not pipe_code:main_pipe_code = bundle_blueprint.main_pipe@@ -77,9 +79,17 @@ async def _generate_inputs_core(except PipeInputError as exc:typer.secho(f"Failed to load bundle '{bundle_path}': {exc}", fg=typer.colors.RED, err=True)raise typer.Exit(1) from exc- elif not pipe_code:- typer.secho("Failed to run: no pipe code specified", fg=typer.colors.RED, err=True)- raise typer.Exit(1)+ else:+ # No bundle: the pipe named is found in the library directories, a method's folder among them.+ library_manager = get_library_manager()+ library_id, _ = library_manager.open_library()+ set_current_library(library_id=library_id)+ effective_dirs, _ = resolve_library_dirs(library_dir)+ if effective_dirs:+ library_manager.load_libraries(library_id=library_id, library_dirs=effective_dirs)+ if not pipe_code:+ typer.secho("Failed to build inputs: no pipe code specified", fg=typer.colors.RED, err=True)+ raise typer.Exit(1)try:the_pipe = get_required_entry_pipe(pipe_code=pipe_code)@@ -106,11 +116,11 @@ async def _generate_inputs_core(typer.secho(f"Error generating inputs template: {exc}", fg=typer.colors.RED)raise typer.Exit(1) from exc+ output_dir = default_output_dir or (bundle_path.parent if bundle_path else None)if output_path:final_output_path = output_path- elif bundle_path:- bundle_dir = bundle_path.parent- final_output_path = bundle_dir / default_file_name+ elif output_dir:+ final_output_path = output_dir / default_file_nameelse:final_output_path = Path("results") / default_file_name@@ -129,6 +139,7 @@ def execute_generate_inputs(pipe_code: str | None,bundle_path: Path | None,output_path: Path | None,+ default_output_dir: Path | None = None,library_dir: list[str] | None = None,template_format: InputsTemplateFormat = InputsTemplateFormat.JSON,explicit: bool = False,@@ -148,6 +159,7 @@ def execute_generate_inputs(pipe_code=pipe_code,bundle_path=bundle_path,output_path=output_path,+ default_output_dir=default_output_dir,library_dir=library_dir,template_format=template_format,explicit=explicit,diff --git a/pipelex/cli/commands/build/inputs/app.py b/pipelex/cli/commands/build/inputs/app.pyindex 2a7770c82..553e285ae 100644--- a/pipelex/cli/commands/build/inputs/app.py+++ b/pipelex/cli/commands/build/inputs/app.py@@ -6,6 +6,6 @@ from pipelex.cli.commands.build.inputs.pipe_cmd import build_inputs_pipe_cmdbuild_inputs_app = typer.Typer(help="Generate example input JSON for a pipe", no_args_is_help=True)-build_inputs_app.command("bundle", help="Generate inputs from a bundle file or directory")(build_inputs_bundle_cmd)+build_inputs_app.command("bundle", help="Generate inputs from a bundle file or a method's folder")(build_inputs_bundle_cmd)build_inputs_app.command("method", help="Generate inputs for an installed method")(build_inputs_method_cmd)build_inputs_app.command("pipe", help="Generate inputs for a pipe by code")(build_inputs_pipe_cmd)diff --git a/pipelex/cli/commands/build/inputs/bundle_cmd.py b/pipelex/cli/commands/build/inputs/bundle_cmd.pyindex 699980753..bd26ee8bd 100644--- a/pipelex/cli/commands/build/inputs/bundle_cmd.py+++ b/pipelex/cli/commands/build/inputs/bundle_cmd.py@@ -6,15 +6,19 @@ from typing import Annotatedimport typerfrom pipelex.cli.commands.build.inputs._inputs_core import execute_generate_inputs-from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file+from pipelex.cli.commands.bundle_path_resolver import resolve_build_bundle_targetfrom pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat-from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAME++_NOT_A_BUNDLE_HINT = (+ " To generate inputs for a pipe by code, use: pipelex build inputs pipe <code>\n"+ " To use a bundle, pass a .mthds file or directory: pipelex build inputs bundle <path>"+)def build_inputs_bundle_cmd(path: Annotated[str,- typer.Argument(help="Path to a .mthds bundle file or a pipeline directory"),+ typer.Argument(help="Path to a .mthds bundle file, or a method's folder, which starts at its entry pipe unless --pipe names one"),],pipe: Annotated[str | None,@@ -51,61 +55,18 @@ def build_inputs_bundle_cmd(pipelex build inputs bundle pipeline_01/ --format tomlpipelex build inputs bundle pipeline_01/ --explicit"""- target_path = Path(path)- bundle_path: Pathoutput_path_path = Path(output_path) if output_path else None-- if target_path.is_dir():- bundle_file = target_path / DEFAULT_BUNDLE_FILE_NAME- if bundle_file.is_file():- bundle_path = bundle_file- else:- mthds_files = list(target_path.glob(f"*{MTHDS_EXTENSION}"))- if len(mthds_files) == 0:- typer.secho(- f"Failed to run: no .mthds bundle file found in directory '{path}'",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)- if len(mthds_files) > 1:- mthds_names = ", ".join(mthds_file.name for mthds_file in mthds_files)- typer.secho(- f"Failed to run: multiple .mthds files found in '{path}' ({mthds_names}) "- f"and no '{DEFAULT_BUNDLE_FILE_NAME}'. "- f"Pass the .mthds file directly, e.g.: pipelex build inputs bundle {target_path / mthds_files[0].name}",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)- bundle_path = mthds_files[0]-- # Add directory as library dir- target_dir_str = str(target_path)- if library_dir is None:- library_dir = [target_dir_str]- elif target_dir_str not in library_dir:- library_dir = [target_dir_str, *library_dir]-- typer.echo(f"Auto-detected bundle: {bundle_path}")-- elif is_pipelex_file(target_path):- bundle_path = target_path- else:- typer.secho(- f"Failed to run: '{path}' is not a .mthds file or directory.\n"- f" To generate inputs for a pipe by code, use: pipelex build inputs pipe <code>\n"- f" To use a bundle, pass a .mthds file or directory: pipelex build inputs bundle <path>",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)+ # A folder is read as its method tree and acts on the pipe a run of it starts at, as `run bundle` reads it.+ target = resolve_build_bundle_target(+ path=path, library_dir=library_dir, pipe_override=pipe, command="build inputs", not_a_bundle_hint=_NOT_A_BUNDLE_HINT+ )execute_generate_inputs(- pipe_code=pipe,- bundle_path=bundle_path,+ pipe_code=target.pipe_code,+ bundle_path=target.bundle_path,output_path=output_path_path,- library_dir=library_dir,+ default_output_dir=target.default_output_dir,+ library_dir=target.library_dir,template_format=template_format,explicit=explicit,)diff --git a/pipelex/cli/commands/build/output/_output_core.py b/pipelex/cli/commands/build/output/_output_core.pyindex 3b7462ccb..52549b365 100644--- a/pipelex/cli/commands/build/output/_output_core.py+++ b/pipelex/cli/commands/build/output/_output_core.py@@ -38,21 +38,23 @@ async def _generate_output_core(pipe_code: str | None = None,bundle_path: Path | None = None,output_path: Path | None = None,+ default_output_dir: Path | None = None,output_format: ConceptRepresentationFormat = ConceptRepresentationFormat.JSON,library_dir: list[str] | None = None,) -> None:- """Core logic for generating output representation for a pipe."""- # Set up library so pipes can be found- library_manager = get_library_manager()- library_id, _ = library_manager.open_library()- set_current_library(library_id=library_id)- effective_dirs, _ = resolve_library_dirs(library_dir)- if effective_dirs:- library_manager.load_libraries(library_id=library_id, library_dirs=effective_dirs)+ """Core logic for generating output representation for a pipe.+ The file goes to ``output_path``, else into ``default_output_dir`` (a method's folder), else beside the bundle,+ else under ``results/``.+ """if bundle_path:try:- validate_bundle_result = await validate_bundle(mthds_file_path=bundle_path)+ # The bundle loads in one library with the method's whole folder and the -L directories, as `run bundle`+ # loads it, so a concept or a pipe it takes from a sibling bundle of its method resolves.+ validate_bundle_result = await validate_bundle(+ mthds_file_path=bundle_path,+ library_dirs=[Path(one_dir) for one_dir in library_dir] if library_dir else None,+ )bundle_blueprint = validate_bundle_result.blueprints[0]if not pipe_code:main_pipe_code = bundle_blueprint.main_pipe@@ -76,9 +78,17 @@ async def _generate_output_core(except PipeInputError as exc:typer.secho(f"Failed to load bundle '{bundle_path}': {exc}", fg=typer.colors.RED, err=True)raise typer.Exit(1) from exc- elif not pipe_code:- typer.secho("Failed to run: no pipe code specified", fg=typer.colors.RED, err=True)- raise typer.Exit(1)+ else:+ # No bundle: the pipe named is found in the library directories, a method's folder among them.+ library_manager = get_library_manager()+ library_id, _ = library_manager.open_library()+ set_current_library(library_id=library_id)+ effective_dirs, _ = resolve_library_dirs(library_dir)+ if effective_dirs:+ library_manager.load_libraries(library_id=library_id, library_dirs=effective_dirs)+ if not pipe_code:+ typer.secho("Failed to build output: no pipe code specified", fg=typer.colors.RED, err=True)+ raise typer.Exit(1)try:the_pipe = get_required_entry_pipe(pipe_code=pipe_code)@@ -98,17 +108,17 @@ async def _generate_output_core(raise typer.Exit(1) from excfinal_output_path: Path+ output_dir = default_output_dir or (bundle_path.parent if bundle_path else None)if output_path:final_output_path = output_path- elif bundle_path:- bundle_dir = Path(bundle_path).parent+ elif output_dir:match output_format:case ConceptRepresentationFormat.JSON:- final_output_path = bundle_dir / "output.json"+ final_output_path = output_dir / "output.json"case ConceptRepresentationFormat.PYTHON:- final_output_path = bundle_dir / "output.py"+ final_output_path = output_dir / "output.py"case ConceptRepresentationFormat.SCHEMA:- final_output_path = bundle_dir / "output_schema.json"+ final_output_path = output_dir / "output_schema.json"else:match output_format:case ConceptRepresentationFormat.JSON:@@ -134,6 +144,7 @@ def execute_generate_output(bundle_path: Path | None,output_path: Path | None,output_format: ConceptRepresentationFormat,+ default_output_dir: Path | None = None,library_dir: list[str] | None = None,telemetry_command_label: str = f"{COMMAND} {SUB_COMMAND_OUTPUT}",) -> None:@@ -148,7 +159,12 @@ def execute_generate_output(asyncio.run(_generate_output_core(- pipe_code=pipe_code, bundle_path=bundle_path, output_path=output_path, output_format=output_format, library_dir=library_dir+ pipe_code=pipe_code,+ bundle_path=bundle_path,+ output_path=output_path,+ default_output_dir=default_output_dir,+ output_format=output_format,+ library_dir=library_dir,))diff --git a/pipelex/cli/commands/build/output/app.py b/pipelex/cli/commands/build/output/app.pyindex 67996650b..2bd9575e2 100644--- a/pipelex/cli/commands/build/output/app.py+++ b/pipelex/cli/commands/build/output/app.py@@ -6,6 +6,6 @@ from pipelex.cli.commands.build.output.pipe_cmd import build_output_pipe_cmdbuild_output_app = typer.Typer(help="Generate example output representation for a pipe", no_args_is_help=True)-build_output_app.command("bundle", help="Generate output from a bundle file or directory")(build_output_bundle_cmd)+build_output_app.command("bundle", help="Generate output from a bundle file or a method's folder")(build_output_bundle_cmd)build_output_app.command("method", help="Generate output for an installed method")(build_output_method_cmd)build_output_app.command("pipe", help="Generate output for a pipe by code")(build_output_pipe_cmd)diff --git a/pipelex/cli/commands/build/output/bundle_cmd.py b/pipelex/cli/commands/build/output/bundle_cmd.pyindex 7cafc5543..0209b48f1 100644--- a/pipelex/cli/commands/build/output/bundle_cmd.py+++ b/pipelex/cli/commands/build/output/bundle_cmd.py@@ -6,15 +6,19 @@ from typing import Annotatedimport typerfrom pipelex.cli.commands.build.output._output_core import execute_generate_output+from pipelex.cli.commands.bundle_path_resolver import resolve_build_bundle_targetfrom pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormat-from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file-from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAME++_NOT_A_BUNDLE_HINT = (+ " To generate output for a pipe by code, use: pipelex build output pipe <code>\n"+ " To use a bundle, pass a .mthds file or directory: pipelex build output bundle <path>"+)def build_output_bundle_cmd(path: Annotated[str,- typer.Argument(help="Path to a .mthds bundle file or a pipeline directory"),+ typer.Argument(help="Path to a .mthds bundle file, or a method's folder, which starts at its entry pipe unless --pipe names one"),],pipe: Annotated[str | None,@@ -66,60 +70,17 @@ def build_output_bundle_cmd()raise typer.Exit(1)- target_path = Path(path)- bundle_path: Pathoutput_path_path = Path(output_path) if output_path else None-- if target_path.is_dir():- bundle_file = target_path / DEFAULT_BUNDLE_FILE_NAME- if bundle_file.is_file():- bundle_path = bundle_file- else:- mthds_files = list(target_path.glob(f"*{MTHDS_EXTENSION}"))- if len(mthds_files) == 0:- typer.secho(- f"Failed to run: no .mthds bundle file found in directory '{path}'",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)- if len(mthds_files) > 1:- mthds_names = ", ".join(mthds_file.name for mthds_file in mthds_files)- typer.secho(- f"Failed to run: multiple .mthds files found in '{path}' ({mthds_names}) "- f"and no '{DEFAULT_BUNDLE_FILE_NAME}'. "- f"Pass the .mthds file directly, e.g.: pipelex build output bundle {target_path / mthds_files[0].name}",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)- bundle_path = mthds_files[0]-- # Add directory as library dir- target_dir_str = str(target_path)- if library_dir is None:- library_dir = [target_dir_str]- elif target_dir_str not in library_dir:- library_dir = [target_dir_str, *library_dir]-- typer.echo(f"Auto-detected bundle: {bundle_path}")-- elif is_pipelex_file(target_path):- bundle_path = target_path- else:- typer.secho(- f"Failed to run: '{path}' is not a .mthds file or directory.\n"- f" To generate output for a pipe by code, use: pipelex build output pipe <code>\n"- f" To use a bundle, pass a .mthds file or directory: pipelex build output bundle <path>",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)+ # A folder is read as its method tree and acts on the pipe a run of it starts at, as `run bundle` reads it.+ target = resolve_build_bundle_target(+ path=path, library_dir=library_dir, pipe_override=pipe, command="build output", not_a_bundle_hint=_NOT_A_BUNDLE_HINT+ )execute_generate_output(- pipe_code=pipe,- bundle_path=bundle_path,+ pipe_code=target.pipe_code,+ bundle_path=target.bundle_path,output_path=output_path_path,output_format=concept_format,- library_dir=library_dir,+ default_output_dir=target.default_output_dir,+ library_dir=target.library_dir,)diff --git a/pipelex/cli/commands/bundle_path_resolver.py b/pipelex/cli/commands/bundle_path_resolver.pyindex c98794b23..b3176ff36 100644--- a/pipelex/cli/commands/bundle_path_resolver.py+++ b/pipelex/cli/commands/bundle_path_resolver.py@@ -1,22 +1,28 @@"""Path-to-bundle resolution for human CLI bundle commands.-``pipelex validate bundle`` and ``pipelex fix bundle`` must resolve the user's ``path``-argument identically: fix must patch exactly the file validate judged. The shared core owns-the filesystem decision-making; this wrapper owns human text-stream errors.+``pipelex validate bundle`` and ``pipelex fix bundle`` must resolve the user's ``path`` argument identically: fix must+patch exactly what validate judged, a bundle file or a method's whole folder. ``pipelex build inputs bundle`` and+``pipelex build output bundle`` act on the same pipe a run of the same folder starts at. The shared core+(``pipelex.cli.judged_target`` and ``pipelex.cli.bundle_target_resolution``) owns the decision, the one every command+taking a bundle path makes, ``run bundle`` included; this module owns the human text-stream errors."""from pathlib import Path-from typing import NoReturn+from typing import NamedTuple, NoReturnimport typer+from pipelex.base_exceptions import PipelexConfigErrorfrom pipelex.cli.bundle_target_resolution import (BundleTargetResolutionError,- BundleTargetResolutionErrorKind,- BundleTargetResolutionSuccess,+ FolderReading,resolve_bundle_target_core,)-from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAME+from pipelex.cli.error_handlers import handle_pre_boot_config_error+from pipelex.cli.judged_target import JudgedBundleTarget, resolve_judged_target+from pipelex.libraries.exceptions import EmptyMethodTreeError+from pipelex.pipeline.exceptions import MethodEntryError, ValidateBundleError+from pipelex.pipeline.method_entry import MethodEntrydef _stringify_library_dirs(library_dirs: list[Path] | None) -> list[str] | None:@@ -25,46 +31,18 @@ def _stringify_library_dirs(library_dirs: list[Path] | None) -> list[str] | Nonereturn [str(library_dir) for library_dir in library_dirs]-def _handle_resolution_error(- error: BundleTargetResolutionError,- *,- command: str,- not_a_bundle_hint: str,-) -> NoReturn:- match error.kind:- case BundleTargetResolutionErrorKind.NO_MTHDS_FILE:- typer.secho(- f"Failed to {command}: no .mthds bundle file found in directory '{error.input_path}'",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(2)- case BundleTargetResolutionErrorKind.AMBIGUOUS_MTHDS_FILES:- mthds_names = ", ".join(mthds_file.name for mthds_file in error.candidate_files)- example_target = error.target_path / error.candidate_files[0].name- typer.secho(- f"Failed to {command}: multiple .mthds files found in '{error.input_path}' ({mthds_names}) "- f"and no '{DEFAULT_BUNDLE_FILE_NAME}'. "- f"Pass the .mthds file directly, e.g.: pipelex {command} bundle {example_target}",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(2)- case BundleTargetResolutionErrorKind.UNSAFE_AUTO_DETECTED_SYMLINK:- typer.secho(- f"Failed to {command}: refusing to auto-detect symlinked bundle '{error.candidate_files[0]}'. "- "Pass a regular .mthds file inside the directory.",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(2)- case BundleTargetResolutionErrorKind.NOT_BUNDLE_TARGET:- typer.secho(- f"Failed to {command}: '{error.input_path}' is not a .mthds file or directory.\n{not_a_bundle_hint}",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(2)+def _echo_method_entry(*, entry: MethodEntry) -> None:+ """Say which pipe of a method's folder a command acts on, when the protocol's rule selected it."""+ typer.echo(f"Using the method's main pipe {entry.pipe_ref}, in {entry.tree_path}")+++def _refuse_not_a_bundle_target(*, error: BundleTargetResolutionError, command: str, not_a_bundle_hint: str, exit_code: int) -> NoReturn:+ typer.secho(+ f"Failed to {command}: '{error.input_path}' is not a .mthds file or directory.\n{not_a_bundle_hint}",+ fg=typer.colors.RED,+ err=True,+ )+ raise typer.Exit(exit_code)def resolve_bundle_target(@@ -73,35 +51,102 @@ def resolve_bundle_target(library_dir: list[str] | None,command: str,not_a_bundle_hint: str,-) -> tuple[str, list[str] | None]:- """Resolve a ``path`` CLI argument into ``(bundle_path, library_dir)``.+) -> JudgedBundleTarget:+ """Resolve the ``path`` argument of ``validate bundle`` or ``fix bundle`` into what the command judges.++ A folder is read as its method tree and judged whole, every bundle of it, as the MTHDS protocol's validation judges+ a method: it needs no pipe to start at. The folder joins the library directories, ahead of ``library_dir``, so its+ files are in the fix write scope, being user-passed.++ No verdict is produced, exit 2 with a red message on stderr, for a folder holding no bundle, for a path that is+ neither a ``.mthds`` file nor a directory, and for a configuration that does not validate, read for the tree's+ limits before the boot, as the command reports a boot failing on it. A folder whose tree is refused is the invalid+ verdict, which each command reports as its own: ``validate`` as an invalid bundle, ``fix`` as a fix that fails.++ Both ``path`` and each ``library_dir`` entry have ``~`` expanded before resolution, so home-relative inputs behave+ like every other CLI path argument.++ Args:+ path: The user's ``path`` argument (a ``.mthds`` file or a method's folder).+ library_dir: The ``-L/--library-dir`` values as passed, or ``None``.+ command: The human command name (e.g. ``"validate"``, ``"fix"``), used in error messages+ (``Failed to {command}: ...``).+ not_a_bundle_hint: Command-specific usage hint appended when ``path`` is neither a ``.mthds`` file nor a+ directory.++ Raises:+ ValidateBundleError: For a folder, its tree is refused or past this machine's limits: the invalid verdict.+ """+ try:+ result = resolve_judged_target(path=path, library_dir=library_dir)+ except EmptyMethodTreeError as exc:+ typer.secho(f"Failed to {command}: {exc.message}", fg=typer.colors.RED, err=True)+ raise typer.Exit(2) from exc+ except PipelexConfigError as exc:+ handle_pre_boot_config_error(exc=exc, command=command, exit_code=2)++ if isinstance(result, BundleTargetResolutionError):+ _refuse_not_a_bundle_target(error=result, command=command, not_a_bundle_hint=not_a_bundle_hint, exit_code=2)+ return result+++class BuildBundleTarget(NamedTuple):+ """What a ``build`` command reads off a bundle path: the bundle, the pipe, the library, and where it writes."""++ #: The file named, or the bundle defining a folder's entry; None for a folder whose pipe was named, which loads as+ #: the method's library, as ``run bundle`` runs it.+ bundle_path: Path | None+ #: The pipe named, else a folder's entry pipe as ``domain.pipe_code``; None for a file named alone.+ pipe_code: str | None+ #: The folder, then the ``-L`` directories; None for a file named with no ``-L``.+ library_dir: list[str] | None+ #: The folder, where a generated file goes by default (``run bundle`` finds its inputs there); None for a file.+ default_output_dir: Path | None+- Directory mode auto-detects the bundle file — ``DEFAULT_BUNDLE_FILE_NAME`` if present, else- a single ``*.mthds`` — and prepends the directory itself to ``library_dir`` so sibling- files load (and, being user-passed, fall inside the fix write scope). No file / multiple- ambiguous files / not-a-``.mthds`` path exit 2 (no verdict produced) with a red message on- stderr.+def resolve_build_bundle_target(+ *,+ path: str,+ library_dir: list[str] | None,+ pipe_override: str | None,+ command: str,+ not_a_bundle_hint: str,+) -> BuildBundleTarget:+ """Resolve a ``build ... bundle`` command's ``path`` argument, as ``run bundle`` reads the same arguments.- Both ``path`` and each ``library_dir`` entry have ``~`` expanded before resolution, so- home-relative inputs behave like every other CLI path argument.+ A folder is read as its method tree. With no pipe named, the command acts on the pipe the method starts at by the+ MTHDS protocol's rule, in the bundle defining it; with a pipe named, it loads the method as its library. A folder+ with no single pipe to start at, a folder that does not load, a path that is neither a ``.mthds`` file nor a+ directory, and a configuration that does not validate, read for the tree's limits before the boot, exit 1 with a+ red message on stderr naming the command, as every ``build`` failure does.Args:- path: The user's ``path`` argument (a ``.mthds`` file or a bundle directory).+ path: The user's ``path`` argument (a ``.mthds`` file or a method's folder).library_dir: The ``-L/--library-dir`` values as passed, or ``None``.- command: The human command name (e.g. ``"validate"``, ``"fix"``), used in error- messages (``Failed to {command}: ...``, ``pipelex {command} bundle ...``).- not_a_bundle_hint: Command-specific usage hint appended when ``path`` is neither a- ``.mthds`` file nor a directory.-- Returns:- ``(bundle_path, library_dir)`` — the resolved bundle file path, and the possibly- directory-augmented library dirs (``None`` when none apply).+ pipe_override: The ``--pipe`` value, or ``None``.+ command: The human command name (``"build inputs"`` or ``"build output"``), used in error messages+ (``Failed to {command}: ...``).+ not_a_bundle_hint: Command-specific usage hint appended when ``path`` is neither a ``.mthds`` file nor a+ directory."""- result = resolve_bundle_target_core(path, library_dir=library_dir)- if isinstance(result, BundleTargetResolutionSuccess):- bundle_path = str(result.bundle_path)- if result.auto_detected:- typer.echo(f"Auto-detected bundle: {bundle_path}")- return bundle_path, _stringify_library_dirs(result.library_dirs)-- _handle_resolution_error(result, command=command, not_a_bundle_hint=not_a_bundle_hint)+ try:+ result = resolve_bundle_target_core(path, library_dir=library_dir, reading=FolderReading.ENTRY_PIPE, pipe_override=pipe_override)+ except MethodEntryError as exc:+ typer.secho(f"Failed to {command}: {exc.message}", fg=typer.colors.RED, err=True)+ raise typer.Exit(1) from exc+ except ValidateBundleError as exc:+ typer.secho(f"Failed to {command}: the method at '{path}' does not load: {exc.message}", fg=typer.colors.RED, err=True)+ raise typer.Exit(1) from exc+ except PipelexConfigError as exc:+ handle_pre_boot_config_error(exc=exc, command=command, exit_code=1)++ if isinstance(result, BundleTargetResolutionError):+ _refuse_not_a_bundle_target(error=result, command=command, not_a_bundle_hint=not_a_bundle_hint, exit_code=1)+ if result.entry is not None:+ _echo_method_entry(entry=result.entry)+ return BuildBundleTarget(+ bundle_path=result.bundle_path,+ pipe_code=result.pipe_code,+ library_dir=_stringify_library_dirs(result.library_dirs),+ default_output_dir=result.method_dir,+ )diff --git a/pipelex/cli/commands/fix/_diff_sandbox.py b/pipelex/cli/commands/fix/_diff_sandbox.pyindex d39c0df92..d05eb4351 100644--- a/pipelex/cli/commands/fix/_diff_sandbox.py+++ b/pipelex/cli/commands/fix/_diff_sandbox.py@@ -17,6 +17,7 @@ from collections.abc import Sequencefrom pathlib import Pathfrom typing import NamedTuple+from pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.config import get_configfrom pipelex.interpreter_hub import resolve_library_dirs@@ -51,18 +52,18 @@ def _excluded_copy_entries( # kw-only: ignore - shutil.copytree invokes ignoreclass PreviewSandbox(NamedTuple):- """The mirrored bundle a ``--diff`` preview runs against, plus the copy→original mapping."""+ """The mirrored bundle or method folder a ``--diff`` preview runs against, plus the copy→original mapping."""- entry_path: Path- """The sandbox path of the entry bundle file (resolved)."""+ entry_path: Path | None+ """The sandbox path of the entry bundle file (resolved), or None for a method's folder, which has none."""library_dirs: list[Path]"""The complete effective load scope remapped onto canonical sandbox copies."""writable_library_dirs: list[Path]"""The subset of copied library dirs the real invocation authorized for writes."""dir_mappings: list[tuple[Path, Path]]"""``(copy_root, original_root)`` per explicit ``-L`` dir, both resolved."""- entry_mapping: tuple[Path, Path]- """``(entry_copy, entry_original)``, both resolved."""+ entry_mapping: tuple[Path, Path] | None+ """``(entry_copy, entry_original)``, both resolved, or None for a method's folder."""def to_original(self, path_str: str) -> str:"""Map a sandbox file path back to the original it mirrors.@@ -73,9 +74,10 @@ class PreviewSandbox(NamedTuple):dependency's bundle named by its package's address, which resolving would turn into a made-up file."""resolved = Path(path_str).resolve()- entry_copy, entry_original = self.entry_mapping- if resolved == entry_copy:- return str(entry_original)+ if self.entry_mapping is not None:+ entry_copy, entry_original = self.entry_mapping+ if resolved == entry_copy:+ return str(entry_original)for copy_root, original_root in self.dir_mappings:if resolved.is_relative_to(copy_root):return str(original_root / resolved.relative_to(copy_root))@@ -83,14 +85,26 @@ class PreviewSandbox(NamedTuple):return path_strreturn str(resolved)+ def to_copy(self, *, original: Path) -> Path:+ """The sandbox copy of a file or directory under one of the mirrored directories, such as a method's folder."""+ resolved = original.resolve()+ for copy_root, original_root in self.dir_mappings:+ if resolved.is_relative_to(original_root):+ return copy_root / resolved.relative_to(original_root)+ msg = f"'{original}' lies under none of the directories the preview mirrored"+ raise PipelexUnexpectedError(msg)+def mirror_bundle_for_preview(- entry_path: Path,+ entry_path: Path | None,*,library_dirs: Sequence[Path] | None,sandbox_root: Path,) -> PreviewSandbox:- """Mirror the entry file and each explicit ``-L`` dir into ``sandbox_root``.+ """Mirror the entry file, when there is one, and each explicit ``-L`` dir into ``sandbox_root``.++ A method's folder has no entry file: it is one of the ``library_dirs``, and ``PreviewSandbox.to_copy`` finds its+ copy.Each effective dir is copied with the loader's configured directory exclusions (the loadermay read Python files as well as ``.mthds`` files), preserving its internal layout under@@ -99,7 +113,7 @@ def mirror_bundle_for_preview(``sandbox_root/entry``. Equivalent and overlapping roots collapse to one canonical copy;ambient copies are part of load scope but excluded from ``writable_library_dirs``."""- entry_resolved = entry_path.resolve()+ entry_resolved = entry_path.resolve() if entry_path is not None else Noneeffective_dirs, _ = resolve_library_dirs(library_dirs)unique_roots: list[Path] = []for library_dir in effective_dirs:@@ -122,7 +136,7 @@ def mirror_bundle_for_preview(copy_root.mkdir(parents=True, exist_ok=True)dir_mappings.append((copy_root, original_root))remapped_dirs.append(copy_root)- if entry_copy is None and entry_resolved.is_relative_to(original_root):+ if entry_copy is None and entry_resolved is not None and entry_resolved.is_relative_to(original_root):entry_copy = copy_root / entry_resolved.relative_to(original_root)for copy_root, original_root in dir_mappings:@@ -143,6 +157,14 @@ def mirror_bundle_for_preview(copied_link.unlink()copied_link.symlink_to(copied_target, target_is_directory=resolved_target.is_dir())+ if entry_resolved is None:+ return PreviewSandbox(+ entry_path=None,+ library_dirs=remapped_dirs,+ writable_library_dirs=remapped_dirs if library_dirs is not None else [],+ dir_mappings=dir_mappings,+ entry_mapping=None,+ )if entry_copy is None:entry_dir = sandbox_root / "entry"entry_dir.mkdir(parents=True, exist_ok=True)diff --git a/pipelex/cli/commands/fix/_fix_core.py b/pipelex/cli/commands/fix/_fix_core.pyindex aa698305e..afd6b0780 100644--- a/pipelex/cli/commands/fix/_fix_core.py+++ b/pipelex/cli/commands/fix/_fix_core.py@@ -4,7 +4,7 @@ import asyncioimport difflibimport tempfilefrom pathlib import Path-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, NoReturnimport typerfrom posthog import tag@@ -19,10 +19,13 @@ from pipelex.cli.error_handlers import (handle_model_choice_error,print_traceback_if_requested,)+from pipelex.cli.judged_target import fix_judged_targetfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError+from pipelex.libraries.method_trees import method_tree_rootfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import Pipelex-from pipelex.pipeline.fixes.fix_loop import fix_bundle_file+from pipelex.pipeline.fixes.fix_loop import unfixable_method_result+from pipelex.pipeline.validate_bundle import dirs_beside_methodfrom pipelex.runtime_hub import get_console, get_telemetry_managerfrom pipelex.system.runtime import IntegrationModefrom pipelex.system.telemetry.events import EventProperty@@ -34,6 +37,8 @@ if TYPE_CHECKING:from pipelex.base_exceptions import ValidationErrorItemfrom pipelex.cli.commands.fix._diff_sandbox import PreviewSandbox+ from pipelex.cli.judged_target import JudgedBundleTarget+ from pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.fixes.fix_loop import FixBundleResultfrom pipelex.suggested_fix import SuggestedFix@@ -210,11 +215,25 @@ def _print_preview_diffs(*, console: Console, result: FixBundleResult, sandbox:console.print()+def _mirrored_dirs(*, target: JudgedBundleTarget) -> list[Path] | None:+ """The directories the preview mirrors: those the real run loads, a method's folder replaced by its tree's root.++ A folder's tree is rooted at the nearest `METHODS.toml` at or above it, and the real fix may write any bundle of+ that tree, a sibling of the folder named included: the preview mirrors the root, so its copy holds the manifest and+ every bundle of the method, and judges the method the real fix judges.+ """+ if target.method_dir is None:+ return target.library_dirs+ return [+ method_tree_root(handed_over=target.method_dir),+ *dirs_beside_method(method_dir=target.method_dir, library_dirs=target.library_dirs),+ ]++def _run_fix_preview(*,console: Console,- bundle_path: Path,- library_dirs: list[Path] | None,+ target: JudgedBundleTarget,allow_signatures: bool,max_iterations: int | None,select_codes: tuple[str, ...] | None,@@ -222,11 +241,19 @@ def _run_fix_preview() -> None:"""Run the real loop against a temp-copy sandbox (D5.6), render diffs, keep the verdict."""with tempfile.TemporaryDirectory(prefix="pipelex-fix-preview-") as sandbox_root:- sandbox = mirror_bundle_for_preview(bundle_path, library_dirs=library_dirs, sandbox_root=Path(sandbox_root))+ sandbox = mirror_bundle_for_preview(target.bundle_path, library_dirs=_mirrored_dirs(target=target), sandbox_root=Path(sandbox_root))+ # The target in the sandbox: a method's folder is found inside its tree root's copy, and the directories it+ # loads with are the copies of the ones it loads with for real, so the copy is spelled as the original is.+ sandbox_target = target._replace(+ bundle_path=sandbox.entry_path,+ method_dir=sandbox.to_copy(original=target.method_dir) if target.method_dir is not None else None,+ library_dirs=[sandbox.to_copy(original=library_dir) for library_dir in target.library_dirs]+ if target.method_dir is not None and target.library_dirs is not None+ else sandbox.library_dirs,+ )result = asyncio.run(- fix_bundle_file(- sandbox.entry_path,- library_dirs=sandbox.library_dirs,+ fix_judged_target(+ target=sandbox_target,writable_library_dirs=sandbox.writable_library_dirs,allow_signatures=allow_signatures,max_iterations=max_iterations,@@ -237,13 +264,30 @@ def _run_fix_preview(if result.files_written:_print_preview_diffs(console=console, result=result, sandbox=sandbox)display_result = _remap_result_to_originals(result, sandbox=sandbox)- _render_fix_result(console=console, result=display_result, bundle_path=bundle_path, allow_signatures=allow_signatures, preview=True)+ _render_fix_result(console=console, result=display_result, bundle_path=target.judged_path, allow_signatures=allow_signatures, preview=True)+++def render_refused_method(*, error: ValidateBundleError, method_dir: Path, allow_signatures: bool, preview: bool) -> NoReturn:+ """Report a method's folder whose tree is refused before anything of it loads, as the fix that fails, exit 1.++ The verdict is the fix loop's still-invalid one, with nothing applied and the refusal as its remaining errors, so+ the output names the folder and reads as a fix that could not be made, as `validate` names it in its invalid one.+ """+ print_traceback_if_requested(console=get_console())+ _render_fix_result(+ console=get_console(),+ result=unfixable_method_result(error=error),+ bundle_path=method_dir,+ allow_signatures=allow_signatures,+ preview=preview,+ )+ # An invalid verdict always exits 1 in the renderer: this only says so to the type checker.+ raise typer.Exit(1) from errordef execute_fix(- bundle_path: Path,*,- library_dirs: list[Path] | None,+ target: JudgedBundleTarget,allow_signatures: bool = False,max_iterations: int | None = None,select_codes: tuple[str, ...] | None = None,@@ -252,14 +296,16 @@ def execute_fix() -> None:"""Synchronous entry point wrapping the fix loop with Pipelex setup/teardown.- Boots with the same profile ``validate`` uses (no inference, real model specs), runs- ``fix_bundle_file``, renders the verdict for humans, and tears down in ``finally``.+ Boots with the same profile ``validate`` uses (no inference, real model specs), runs the fix loop on what+ ``validate`` judged (``fix_judged_target``: a method's folder, judged whole, else the bundle file), renders the+ verdict for humans, and tears down in ``finally``.Exit codes are presentation: 0 = valid, 1 = negative verdict (still invalid, or valid butnot runnable without ``--allow-signatures``), 2 = no verdict (bad target, boot failure,unexpected exception). ``diff`` previews instead of writing: the same loop runs against atemp-copy sandbox and a unified diff is rendered per would-be-written file, with the sameverdict semantics."""+ judged_path = target.judged_pathtry:make_pipelex_for_cli(context=ErrorContext.FIX, needs_inference=False)with get_telemetry_manager().telemetry_context():@@ -270,8 +316,7 @@ def execute_fix(if diff:_run_fix_preview(console=get_console(),- bundle_path=bundle_path,- library_dirs=library_dirs,+ target=target,allow_signatures=allow_signatures,max_iterations=max_iterations,select_codes=select_codes,@@ -280,19 +325,19 @@ def execute_fix(returnresult = asyncio.run(- fix_bundle_file(- bundle_path,- library_dirs=library_dirs,+ fix_judged_target(+ target=target,+ writable_library_dirs=None,allow_signatures=allow_signatures,max_iterations=max_iterations,select_codes=select_codes,ignore_codes=ignore_codes,))- _render_fix_result(console=get_console(), result=result, bundle_path=bundle_path, allow_signatures=allow_signatures)+ _render_fix_result(console=get_console(), result=result, bundle_path=judged_path, allow_signatures=allow_signatures)except FileNotFoundError as exc:print_traceback_if_requested(console=get_console())- typer.secho(f"Failed to fix: bundle file not found: '{bundle_path}'", fg=typer.colors.RED, err=True)+ typer.secho(f"Failed to fix: bundle file not found: '{judged_path}'", fg=typer.colors.RED, err=True)raise typer.Exit(2) from excexcept PipeOperatorModelChoiceError as exc:handle_model_choice_error(exc, context=ErrorContext.FIX, exit_code=2)diff --git a/pipelex/cli/commands/fix/app.py b/pipelex/cli/commands/fix/app.pyindex 23b28875f..61ed11463 100644--- a/pipelex/cli/commands/fix/app.py+++ b/pipelex/cli/commands/fix/app.py@@ -8,5 +8,5 @@ fix_app = typer.Typer(no_args_is_help=True,)-fix_app.command("bundle", help="Fix a bundle file (.mthds) or pipeline directory in place")(fix_bundle_cmd)+fix_app.command("bundle", help="Fix a bundle file (.mthds) or a method's whole folder in place")(fix_bundle_cmd)fix_app.command("function-names", help="Rewrite a method's flat PipeFunc function names as import paths, without booting")(fix_function_names_cmd)diff --git a/pipelex/cli/commands/fix/bundle_cmd.py b/pipelex/cli/commands/fix/bundle_cmd.pyindex 427364cc4..83bf3fda4 100644--- a/pipelex/cli/commands/fix/bundle_cmd.py+++ b/pipelex/cli/commands/fix/bundle_cmd.py@@ -6,7 +6,8 @@ from typing import Annotatedimport typerfrom pipelex.cli.commands.bundle_path_resolver import resolve_bundle_target-from pipelex.cli.commands.fix._fix_core import COMMAND, execute_fix+from pipelex.cli.commands.fix._fix_core import COMMAND, execute_fix, render_refused_method+from pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.fixes.planner import KNOWN_FIX_CODES_NOT_A_BUNDLE_HINT = " To fix a bundle, pass a .mthds file or directory: pipelex fix bundle <path>"@@ -34,7 +35,7 @@ def _reject_invalid_rule_filters(*, select_codes: tuple[str, ...] | None, ignoredef fix_bundle_cmd(path: Annotated[str,- typer.Argument(help="Path to a .mthds bundle file or a pipeline directory"),+ typer.Argument(help="Path to a .mthds bundle file, or a method's folder, whose every bundle is judged"),],library_dir: Annotated[list[str] | None,@@ -72,14 +73,15 @@ def fix_bundle_cmd(),] = False,) -> None:- """Fix a bundle file (.mthds) or pipeline directory in place.+ """Fix a bundle file (.mthds) or a method's folder in place.Runs the validate → apply safe fixes → re-validate loop until the bundle is valid, out- of fixes, or the iteration cap is reached, and names every change made.+ of fixes, or the iteration cap is reached, and names every change made. A folder is judged+ whole, every bundle of its method tree, as `validate bundle` judges it.Examples:pipelex fix bundle my_bundle.mthds- pipelex fix bundle pipeline_01/+ pipelex fix bundle my_method/pipelex fix bundle my_bundle.mthds --select match-sequence-outputpipelex fix bundle my_bundle.mthds --diff"""@@ -87,17 +89,20 @@ def fix_bundle_cmd(ignore_codes = tuple(ignore_codes_raw) if ignore_codes_raw else None_reject_invalid_rule_filters(select_codes=select_codes, ignore_codes=ignore_codes)- bundle_path, library_dir = resolve_bundle_target(- path,- library_dir=library_dir,- command=COMMAND,- not_a_bundle_hint=_NOT_A_BUNDLE_HINT,- )- library_dirs = [Path(lib_dir) for lib_dir in library_dir] if library_dir else None+ # A folder is judged whole, every bundle of its method tree, as `validate bundle` judges it. A folder whose tree is+ # refused is the fix that fails, with nothing to fix, as `validate bundle` gives it the invalid verdict.+ try:+ target = resolve_bundle_target(+ path,+ library_dir=library_dir,+ command=COMMAND,+ not_a_bundle_hint=_NOT_A_BUNDLE_HINT,+ )+ except ValidateBundleError as exc:+ render_refused_method(error=exc, method_dir=Path(path).expanduser(), allow_signatures=allow_signatures, preview=diff)execute_fix(- Path(bundle_path),- library_dirs=library_dirs,+ target=target,allow_signatures=allow_signatures,max_iterations=max_iterations,select_codes=select_codes,diff --git a/pipelex/cli/commands/run/_method_folder.py b/pipelex/cli/commands/run/_method_folder.pydeleted file mode 100644index 11bd4f37a..000000000--- a/pipelex/cli/commands/run/_method_folder.py+++ /dev/null@@ -1,62 +0,0 @@-"""What `run bundle` runs when it is handed a method's folder or a bundle file: its method tree, and where it starts.--Both CLIs read their target here, so `pipelex run bundle` and `pipelex-agent run bundle` run the same pipe of the same-tree for the same arguments, locally as on the hosted API:--- A folder is the method rooted at the nearest `METHODS.toml` at or above it, else at the folder itself. With no- `--pipe`, the run starts where the MTHDS protocol says a run naming no pipe starts (`pipelex.pipeline.method_entry`):- the manifest's `main_pipe`, else the one `main_pipe` its bundles declare; none or several is refused, the bundles- named by their tree paths.-- A `.mthds` file named alone is the member of its own file's tree: rooted at the nearest `METHODS.toml` at or above- its folder, else the one-file tree of that file, from which a reference to any other file is refused. It starts at- its own `main_pipe`, as it always has.--The tree is listed under this machine's limits (`[interpreter.method_tree_limits]`), and its digest is what a run-records as the method it ran.-"""--from pathlib import Path-from typing import NamedTuple--from mthds.method_tree.models import MethodTree--from pipelex.libraries.method_trees import list_local_method_tree-from pipelex.pipeline.method_entry import MethodEntry, select_method_entry-from pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_error---class MethodFolderRun(NamedTuple):- """A method's folder to run: its tree, the pipe the run starts at, and the bundle defining it when it was selected."""-- tree: MethodTree- #: `--pipe` as given, else the selected entry's `domain.pipe_code`.- pipe_code: str- #: The pipe the protocol's rule selected, or None when `--pipe` named one.- entry: MethodEntry | None- #: The file on this host of the bundle defining the selected entry, or None when `--pipe` named the pipe.- entry_bundle_file: Path | None---def resolve_method_folder_run(*, directory: Path, pipe_override: str | None) -> MethodFolderRun:- """List a method folder's tree and settle the pipe its run starts at.-- Raises:- ValidateBundleError: The tree is refused or past this machine's limits, a bundle does not parse, or the method- has no single pipe to start at, each as the invalid verdict `validate` gives.- """- with translate_to_validate_bundle_error():- tree = list_local_method_tree(handed_over=directory)- if pipe_override:- return MethodFolderRun(tree=tree, pipe_code=pipe_override, entry=None, entry_bundle_file=None)- entry = select_method_entry(tree=tree)- return MethodFolderRun(tree=tree, pipe_code=entry.pipe_ref, entry=entry, entry_bundle_file=tree.file_location(entry.tree_path))---def list_bundle_file_tree(*, bundle_file: Path) -> MethodTree:- """The method tree of a `.mthds` file named alone, as the run loads it.-- Raises:- ValidateBundleError: The tree is refused or past this machine's limits, as the invalid verdict `validate` gives.- """- with translate_to_validate_bundle_error():- return list_local_method_tree(handed_over=bundle_file)diff --git a/pipelex/cli/commands/run/bundle_cmd.py b/pipelex/cli/commands/run/bundle_cmd.pyindex 801027bff..ecb22be79 100644--- a/pipelex/cli/commands/run/bundle_cmd.py+++ b/pipelex/cli/commands/run/bundle_cmd.py@@ -5,15 +5,15 @@ from typing import TYPE_CHECKING, Annotatedimport typer-from pipelex.base_exceptions import PipelexUnexpectedError+from pipelex.base_exceptions import PipelexConfigError, PipelexUnexpectedError+from pipelex.cli.bundle_target_resolution import list_bundle_file_tree, resolve_method_folder_runfrom pipelex.cli.commands.run._hosted_sources import collect_mthds_files, hosted_library_dirsfrom pipelex.cli.commands.run._inputs_file_loader import find_default_inputs_file-from pipelex.cli.commands.run._method_folder import list_bundle_file_tree, resolve_method_folder_runfrom pipelex.cli.commands.run._run_core import COMMAND, execute_run, validate_run_flag_combinationfrom pipelex.cli.commands.run._run_hosted import bundle_main_pipe_code, execute_hosted_run, refuse_local_only_flags, resolve_cli_run_executionfrom pipelex.cli.commands.run._run_output_folder import run_output_labelfrom pipelex.cli.commands.run.exceptions import AmbiguousInputsFilesError-from pipelex.cli.error_handlers import handle_validate_bundle_error+from pipelex.cli.error_handlers import handle_pre_boot_config_error, handle_validate_bundle_errorfrom pipelex.hosted.exceptions import HostedRunSourceErrorfrom pipelex.mthds_parsing.helpers import is_pipelex_filefrom pipelex.pipeline.exceptions import ValidateBundleError@@ -25,7 +25,7 @@ if TYPE_CHECKING:def run_bundle_cmd(path: Annotated[str,- typer.Argument(help="Path to a .mthds bundle file or a pipeline directory"),+ typer.Argument(help="Path to a .mthds bundle file, or a method's folder, which starts at its entry pipe unless --pipe names one"),],pipe: Annotated[str | None,@@ -158,6 +158,9 @@ def run_bundle_cmd(folder_run = resolve_method_folder_run(directory=target_path, pipe_override=pipe)except ValidateBundleError as exc:handle_validate_bundle_error(exc, library_dirs=[Path(one_dir) for one_dir in library_dir] if library_dir else None)+ except PipelexConfigError as exc:+ # Listing the tree reads its limits from the configuration, before the boot would.+ handle_pre_boot_config_error(exc=exc, command=COMMAND, exit_code=1)method_tree = folder_run.treepipe_code = folder_run.pipe_codeif folder_run.entry is not None and folder_run.entry_bundle_file is not None:@@ -191,6 +194,8 @@ def run_bundle_cmd(handle_validate_bundle_error(exc, bundle_path=target_path, library_dirs=[Path(one_dir) for one_dir in library_dir] if library_dir else None)+ except PipelexConfigError as exc:+ handle_pre_boot_config_error(exc=exc, command=COMMAND, exit_code=1)else:typer.secho(f"Failed to run: '{path}' is not a .mthds file or directory.\n"diff --git a/pipelex/cli/commands/validate/_validate_core.py b/pipelex/cli/commands/validate/_validate_core.pyindex 7ed6ea06b..735fb7588 100644--- a/pipelex/cli/commands/validate/_validate_core.py+++ b/pipelex/cli/commands/validate/_validate_core.py@@ -156,18 +156,38 @@ def do_validate_all_libraries_and_dry_run(*, library_dirs: list[Path] | None = Nasync def _validate_pipe_or_bundle(- *, pipe_code: str | None = None, bundle_path: Path | None = None, library_dirs: list[Path] | None = None, allow_signatures: bool = False+ *,+ pipe_code: str | None = None,+ bundle_path: Path | None = None,+ method_dir: Path | None = None,+ library_dirs: list[Path] | None = None,+ allow_signatures: bool = False,) -> None:- """Core async validation logic shared between method and pipe subcommands."""+ """Core async validation logic shared between the bundle, method and pipe subcommands.++ A method's folder is judged whole, every bundle of its method tree, with ``library_dirs`` loaded beside it.+ """with MethodValidationReport() as validation_report:- if bundle_path:+ judged_path = method_dir or bundle_path+ if judged_path:+ judged_label = f"the method at '{method_dir}'" if method_dir else f"bundle '{bundle_path}'"+ judged_subject = f"The method at '{method_dir}'" if method_dir else f"Bundle '{bundle_path}'"try:- bundle_result = await validate_bundle(- mthds_file_path=bundle_path,- library_dirs=library_dirs,- allow_signatures=allow_signatures,- collect_dry_run_warnings=True,- )+ if method_dir:+ bundle_result = await validate_bundle(+ method_dir=method_dir,+ library_dirs=library_dirs,+ library_dirs_are_callers=True,+ allow_signatures=allow_signatures,+ collect_dry_run_warnings=True,+ )+ else:+ bundle_result = await validate_bundle(+ mthds_file_path=bundle_path,+ library_dirs=library_dirs,+ allow_signatures=allow_signatures,+ collect_dry_run_warnings=True,+ )# Advisory lints, printed BEFORE the signature gate below exits non-zero — same ordering# as `validate --all`. A method with an unimplemented placeholder is the state an author# is most often in while building, and it is exactly then that the advisories help.@@ -190,7 +210,7 @@ async def _validate_pipe_or_bundle(if bundle_result.pending_signatures and not allow_signatures:pending = ", ".join(bundle_result.pending_signatures)typer.secho(- f"Bundle '{bundle_path}' is valid but NOT yet runnable — unimplemented PipeSignature placeholder(s): {pending}\n"+ f"{judged_subject} is valid but NOT yet runnable — unimplemented PipeSignature placeholder(s): {pending}\n""Implement them, or re-run with --allow-signatures to accept placeholders.",fg=typer.colors.RED,err=True,@@ -198,19 +218,19 @@ async def _validate_pipe_or_bundle(raise typer.Exit(1)signature_count = sum(1 for pipe in bundle_result.pipes if pipe.is_signature)typer.secho(- f"Successfully validated bundle '{bundle_path}'{_format_signatures_summary_suffix(signature_count=signature_count)}",+ f"Successfully validated {judged_label}{_format_signatures_summary_suffix(signature_count=signature_count)}",fg=typer.colors.GREEN,)except FileNotFoundError as exc:get_console().print(Traceback())typer.secho(- f"Failed to load bundle '{bundle_path}':",+ f"Failed to load {judged_label}:",fg=typer.colors.RED,err=True,)raise typer.Exit(2) from excexcept ValidateBundleError as bundle_error:- handle_validate_bundle_error(bundle_error, bundle_path=bundle_path, library_dirs=library_dirs, allow_signatures=allow_signatures)+ handle_validate_bundle_error(bundle_error, bundle_path=judged_path, library_dirs=library_dirs, allow_signatures=allow_signatures)elif pipe_code:library_manager = get_library_manager()library_id, _ = library_manager.open_library()@@ -263,6 +283,7 @@ def execute_validate(pipe_code: str | None,bundle_path: Path | None,library_dirs: list[Path] | None,+ method_dir: Path | None = None,telemetry_command_label: str = COMMAND,allow_signatures: bool = False,orchestrator: str | None = None,@@ -289,6 +310,7 @@ def execute_validate(_validate_pipe_or_bundle(pipe_code=pipe_code,bundle_path=bundle_path,+ method_dir=method_dir,library_dirs=library_dirs,allow_signatures=allow_signatures,)diff --git a/pipelex/cli/commands/validate/app.py b/pipelex/cli/commands/validate/app.pyindex 33b6c2d37..457e110f0 100644--- a/pipelex/cli/commands/validate/app.py+++ b/pipelex/cli/commands/validate/app.py@@ -53,4 +53,4 @@ validate_app = typer.Typer(validate_app.command("method", help="Validate an installed method by name")(validate_method_cmd)validate_app.command("pipe", help="Validate a pipe by code, or all pipes")(validate_pipe_cmd)-validate_app.command("bundle", help="Validate a bundle file (.mthds) or pipeline directory")(validate_bundle_cmd)+validate_app.command("bundle", help="Validate a bundle file (.mthds) or a method's whole folder")(validate_bundle_cmd)diff --git a/pipelex/cli/commands/validate/bundle_cmd.py b/pipelex/cli/commands/validate/bundle_cmd.pyindex 1fbf3e0cf..1bf408a2d 100644--- a/pipelex/cli/commands/validate/bundle_cmd.py+++ b/pipelex/cli/commands/validate/bundle_cmd.py@@ -7,6 +7,8 @@ import typerfrom pipelex.cli.commands.bundle_path_resolver import resolve_bundle_targetfrom pipelex.cli.commands.validate._validate_core import COMMAND, execute_validate+from pipelex.cli.error_handlers import handle_validate_bundle_error+from pipelex.pipeline.exceptions import ValidateBundleError_NOT_A_BUNDLE_HINT = (" To validate a pipe by code, use: pipelex validate pipe <code>\n"@@ -17,7 +19,7 @@ _NOT_A_BUNDLE_HINT = (def validate_bundle_cmd(path: Annotated[str,- typer.Argument(help="Path to a .mthds bundle file or a pipeline directory"),+ typer.Argument(help="Path to a .mthds bundle file, or a method's folder, whose every bundle is judged"),],library_dir: Annotated[list[str] | None,@@ -43,25 +45,37 @@ def validate_bundle_cmd(),] = None,) -> None:- """Validate a bundle file (.mthds) or pipeline directory.+ """Validate a bundle file (.mthds) or a method's folder.++ A folder is judged whole, every bundle of its method tree, as the MTHDS protocol's validation judges a method: it+ needs no pipe to start at.Examples:pipelex validate bundle my_bundle.mthds- pipelex validate bundle pipeline_01/+ pipelex validate bundle my_method/pipelex validate bundle my_bundle.mthds --allow-signatures"""- bundle_path, library_dir = resolve_bundle_target(- path,- library_dir=library_dir,- command=COMMAND,- not_a_bundle_hint=_NOT_A_BUNDLE_HINT,- )- library_dirs_paths = [Path(lib_dir) for lib_dir in library_dir] if library_dir else None+ try:+ target = resolve_bundle_target(+ path,+ library_dir=library_dir,+ command=COMMAND,+ not_a_bundle_hint=_NOT_A_BUNDLE_HINT,+ )+ except ValidateBundleError as exc:+ # A folder whose tree is refused is the invalid verdict, naming the folder.+ handle_validate_bundle_error(+ exc,+ bundle_path=Path(path).expanduser(),+ library_dirs=[Path(one_dir).expanduser() for one_dir in library_dir] if library_dir else None,+ allow_signatures=allow_signatures,+ )execute_validate(pipe_code=None,- bundle_path=Path(bundle_path),- library_dirs=library_dirs_paths,+ bundle_path=target.bundle_path,+ method_dir=target.method_dir,+ library_dirs=target.library_dirs,telemetry_command_label=f"{COMMAND} bundle",allow_signatures=allow_signatures,orchestrator=orchestrator,diff --git a/pipelex/cli/error_handlers.py b/pipelex/cli/error_handlers.pyindex b4ddd1a0a..346737863 100644--- a/pipelex/cli/error_handlers.py+++ b/pipelex/cli/error_handlers.py@@ -9,7 +9,7 @@ from rich.console import Consolefrom rich.markup import escapefrom rich.traceback import Traceback-from pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem, error_domain_is_input, iter_cause_chain+from pipelex.base_exceptions import PipelexConfigError, ValidationErrorCategory, ValidationErrorItem, error_domain_is_input, iter_cause_chainfrom pipelex.cogt.exceptions import ModelDeckPresetValidatonErrorfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.migration.exceptions import FormerReleaseConfigError@@ -411,6 +411,24 @@ def handle_validate_bundle_error(raise typer.Exit(1) from exc+def handle_pre_boot_config_error(*, exc: PipelexConfigError, command: str, exit_code: int) -> NoReturn:+ """Report a configuration that cannot be read before the boot, as the command reports a boot that fails on it.++ A command handed a method's folder or bundle file lists its method tree before it boots, under the limits the+ configuration sets, so a configuration the boot would refuse is refused there first. It is reported as the+ command's boundary reports the boot's refusal, `Failed to <command>:` and the refusal, which names what to fix and+ the migration that would, never as a traceback.++ Args:+ exc: The configuration's refusal.+ command: The human command name, as the command's other failures name it (e.g. ``"validate"``).+ exit_code: The exit code the command gives a failed boot.+ """+ print_traceback_if_requested(console=get_console())+ typer.secho(f"Failed to {command}: {exc.message}", fg=typer.colors.RED, err=True)+ raise typer.Exit(exit_code) from exc++def handle_telemetry_config_validation_error(exc: TelemetryConfigValidationError) -> NoReturn:"""Handle and display TelemetryConfigValidationError, saying whether the file is old or wrong.diff --git a/pipelex/cli/judged_target.py b/pipelex/cli/judged_target.pynew file mode 100644index 000000000..8d3f3b335--- /dev/null+++ b/pipelex/cli/judged_target.py@@ -0,0 +1,110 @@+"""What `validate bundle` and `fix bundle` judge, on both CLIs, and the one fix loop that fixes it.++Both commands read their `path` argument the same way (`pipelex.cli.bundle_target_resolution`, `FolderReading.WHOLE_TREE`):+a `.mthds` file is judged as a bundle file, a folder as its whole method tree. `fix` must patch exactly what `validate`+judged, so the two CLIs share the target this module defines, the path it names, and the dispatch to the fix loop.+"""++from collections.abc import Sequence+from pathlib import Path+from typing import NamedTuple++from mthds.method_tree.models import MethodTree++from pipelex.base_exceptions import PipelexUnexpectedError+from pipelex.cli.bundle_target_resolution import BundleTargetResolutionError, FolderReading, resolve_bundle_target_core+from pipelex.pipeline.fixes.fix_loop import FixBundleResult, fix_bundle_file, fix_method_folder+++class JudgedBundleTarget(NamedTuple):+ """What `validate` and `fix` judge: one bundle file, or a method's whole folder, and the library loaded with it."""++ #: The file named, or None for a folder.+ bundle_path: Path | None+ #: The folder named, `~` expanded, judged as its whole method tree, or None for a file.+ method_dir: Path | None+ #: The folder's method tree, or None for a file.+ method_tree: MethodTree | None+ #: The folder, then the `-L` directories, `~` expanded; None for a file named with no `-L`.+ library_dirs: list[Path] | None++ @property+ def judged_path(self) -> Path:+ """The path the verdict names: the method's folder, as the caller gave it, or the bundle file.++ Raises:+ PipelexUnexpectedError: The target names neither, which no resolution produces.+ """+ if self.method_dir is not None:+ return self.method_dir+ if self.bundle_path is not None:+ return self.bundle_path+ msg = "A bundle target was resolved to neither a bundle file nor a method's folder."+ raise PipelexUnexpectedError(msg)+++def resolve_judged_target(*, path: str, library_dir: list[str] | None) -> JudgedBundleTarget | BundleTargetResolutionError:+ """Resolve the `path` argument of `validate bundle` or `fix bundle` into what the command judges.++ Args:+ path: The `path` argument, a `.mthds` file or a method's folder, `~` expanded.+ library_dir: The `-L/--library-dir` values as passed, `~` expanded.++ Raises:+ EmptyMethodTreeError: The folder holds no bundle.+ ValidateBundleError: The folder's tree is refused or past this machine's limits, the invalid verdict.+ PipelexConfigError: This machine's configuration, read for the tree's limits, does not validate.+ """+ result = resolve_bundle_target_core(path, library_dir=library_dir, reading=FolderReading.WHOLE_TREE)+ if isinstance(result, BundleTargetResolutionError):+ return result+ return JudgedBundleTarget(+ bundle_path=result.bundle_path,+ method_dir=result.method_dir,+ method_tree=result.method_tree,+ library_dirs=result.library_dirs,+ )+++async def fix_judged_target(+ *,+ target: JudgedBundleTarget,+ writable_library_dirs: Sequence[Path] | None,+ allow_signatures: bool,+ max_iterations: int | None,+ select_codes: Sequence[str] | None,+ ignore_codes: Sequence[str] | None,+) -> FixBundleResult:+ """Run the fix loop on what `validate` judged: a method's folder, judged whole, else a bundle file.++ Args:+ target: The resolved target, or its copy in the `--diff` preview's sandbox.+ writable_library_dirs: The directories the loop may write, as the preview's sandbox gives them, or None for+ the scope a real run derives from the target.+ allow_signatures: Whether `PipeSignature` placeholders pass the exit gate.+ max_iterations: The apply-round cap, or None for the configured one.+ select_codes: The only fix rules to apply, or None for every rule.+ ignore_codes: The fix rules to skip, or None.++ Raises:+ PipelexUnexpectedError: The target names neither a folder nor a file.+ """+ if target.method_dir is not None:+ return await fix_method_folder(+ method_dir=target.method_dir,+ library_dirs=target.library_dirs,+ writable_library_dirs=writable_library_dirs,+ allow_signatures=allow_signatures,+ max_iterations=max_iterations,+ select_codes=select_codes,+ ignore_codes=ignore_codes,+ )+ return await fix_bundle_file(+ target.judged_path,+ library_dirs=target.library_dirs,+ writable_library_dirs=writable_library_dirs,+ allow_signatures=allow_signatures,+ max_iterations=max_iterations,+ select_codes=select_codes,+ ignore_codes=ignore_codes,+ )diff --git a/pipelex/libraries/exceptions.py b/pipelex/libraries/exceptions.pyindex c3b386f5e..edd040b45 100644--- a/pipelex/libraries/exceptions.py+++ b/pipelex/libraries/exceptions.py@@ -102,6 +102,15 @@ class MethodTreeLoadError(LibraryLoadingError):_authors_caller_facing_message = True+class EmptyMethodTreeError(MethodTreeLoadError):+ """Raised when a folder handed over as a method holds no bundle.++ The membership rule keeps every file of the folder out of its method tree, which holds at least one, or none of the+ files it keeps is a bundle. A command handed the folder finds nothing to judge and no pipe to start at: it reports+ the folder as holding no bundle rather than as a method refused.+ """++class HostLibraryTreeError(PipelexError):"""Raised when a library directory of this host, one a load reads beside a caller's bundles, cannot be read as a method tree.diff --git a/pipelex/libraries/method_trees.py b/pipelex/libraries/method_trees.pyindex a9441eb1c..50c065659 100644--- a/pipelex/libraries/method_trees.py+++ b/pipelex/libraries/method_trees.py@@ -50,7 +50,13 @@ from pipelex import logfrom pipelex.core.method_trees.method_file_store import HeldFilefrom pipelex.core.method_trees.tree_bundle import TreeBundlefrom pipelex.hosted.execution import get_or_load_pipelex_config-from pipelex.libraries.exceptions import HostLibraryRequirementsError, HostLibraryTreeError, MethodRequirementsError, MethodTreeLoadError+from pipelex.libraries.exceptions import (+ EmptyMethodTreeError,+ HostLibraryRequirementsError,+ HostLibraryTreeError,+ MethodRequirementsError,+ MethodTreeLoadError,+)from pipelex.libraries.written_trees import WRITTEN_METHOD_TREESLIMITS_ADVICE = (@@ -84,7 +90,8 @@ def list_local_method_tree(*, handed_over: Path, limits: TreeLimits | None = Nonlimits: The limits to list under, read from the configuration when not given.Raises:- MethodTreeLoadError: The standard refused the tree, it passed a limit, or it could not be read.+ EmptyMethodTreeError: The membership rule keeps every file of the directory out of its tree.+ MethodTreeLoadError: The standard refused the tree otherwise, it passed a limit, or it could not be read."""written = WRITTEN_METHOD_TREES.tree_written_at(directory=handed_over)if written is not None:@@ -94,7 +101,59 @@ def list_local_method_tree(*, handed_over: Path, limits: TreeLimits | None = Nonexcept TreeLimitError as exc:msg = f"{exc.message} {LIMITS_ADVICE}"raise MethodTreeLoadError(msg) from exc- except (MethodTreeRefusedError, TreeSourceError) as exc:+ except MethodTreeRefusedError as exc:+ if _is_empty_tree(refusal_error=exc):+ raise EmptyMethodTreeError(exc.message) from exc+ raise MethodTreeLoadError(exc.message) from exc+ except TreeSourceError as exc:+ raise MethodTreeLoadError(exc.message) from exc+++def list_local_method_tree_at_root(*, root: Path, limits: TreeLimits | None = None) -> MethodTree:+ """List the method tree rooted at a directory itself, with no Manifest Discovery, under this machine's limits.++ For a directory that is a method's root whatever lies above it, such as an entry of a corpus shipped inside an+ installed package, whose ancestors (a project above `site-packages`) may hold a `METHODS.toml` of their own.++ Raises:+ EmptyMethodTreeError: The membership rule keeps every file of the directory out of its tree.+ MethodTreeLoadError: The standard refused the tree otherwise, it passed a limit, or it could not be read.+ """+ written = WRITTEN_METHOD_TREES.tree_written_at(directory=root)+ if written is not None:+ return written+ try:+ return list_method_tree_at_root(root, limits=limits or local_tree_limits())+ except TreeLimitError as exc:+ msg = f"{exc.message} {LIMITS_ADVICE}"+ raise MethodTreeLoadError(msg) from exc+ except MethodTreeRefusedError as exc:+ if _is_empty_tree(refusal_error=exc):+ raise EmptyMethodTreeError(exc.message) from exc+ raise MethodTreeLoadError(exc.message) from exc+ except TreeSourceError as exc:+ raise MethodTreeLoadError(exc.message) from exc+++def method_tree_root(*, handed_over: Path) -> Path:+ """The root of the method tree a folder handed over belongs to, resolved, found without listing the tree.++ The nearest directory at or above the folder holding a `METHODS.toml`, else the folder itself, as+ `list_local_method_tree` roots the tree it lists; the directory a host wrote a tree out as is that tree's root.++ Raises:+ MethodTreeLoadError: The folder cannot be resolved, or a directory on the way up cannot be looked into.+ """+ written = WRITTEN_METHOD_TREES.tree_written_at(directory=handed_over)+ if written is not None and written.directory is not None:+ return written.directory+ try:+ directory = handed_over.resolve(strict=True)+ return find_manifest_directory(directory) or directory+ except OSError as exc:+ msg = f"Cannot find the root of the method tree of '{handed_over}': {exc}"+ raise MethodTreeLoadError(msg) from exc+ except TreeSourceError as exc:raise MethodTreeLoadError(exc.message) from excdiff --git a/pipelex/mthds_parsing/pipelex_bundle_blueprint.py b/pipelex/mthds_parsing/pipelex_bundle_blueprint.pyindex 702e40f53..1e2c2a2f8 100644--- a/pipelex/mthds_parsing/pipelex_bundle_blueprint.py+++ b/pipelex/mthds_parsing/pipelex_bundle_blueprint.py@@ -191,9 +191,10 @@ class PipelexBundleBlueprint(BaseModel):@field_validator("main_pipe", mode="before")@classmethod- def validate_main_pipe_syntax(cls, main_pipe: str | None, info: ValidationInfo) -> str | None:- if main_pipe is None:- return None+ def validate_main_pipe_syntax(cls, main_pipe: Any, info: ValidationInfo) -> Any:+ if not isinstance(main_pipe, str):+ # None, or a value of another type, which the field's own type refuses as a located error.+ return main_pipeif not is_pipe_code_valid(main_pipe):msg = f"Invalid main pipe syntax '{main_pipe}'. Must be in snake_case."stripped = _strippable_same_domain_pipe_code(main_pipe, domain=cast("str | None", info.data.get("domain")))diff --git a/pipelex/pipeline/default_file_names.py b/pipelex/pipeline/default_file_names.pyindex 0fa4010b3..944c4563a 100644--- a/pipelex/pipeline/default_file_names.py+++ b/pipelex/pipeline/default_file_names.py@@ -1,11 +1,8 @@-"""The default file names of a method directory: its bundle and its inputs.+"""The default file names of a method directory: its inputs.`pipelex run` and `pipelex-agent run` look for these names when given a directory, and`pipelex build inputs` and `pipelex codegen inputs` write the inputs file under them."""-from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION--DEFAULT_BUNDLE_FILE_NAME = f"bundle{MTHDS_EXTENSION}"DEFAULT_INPUTS_FILE_NAME = "inputs.json"DEFAULT_INPUTS_TOML_FILE_NAME = "inputs.toml"diff --git a/pipelex/pipeline/exceptions.py b/pipelex/pipeline/exceptions.pyindex 5add07780..f80d19936 100644--- a/pipelex/pipeline/exceptions.py+++ b/pipelex/pipeline/exceptions.py@@ -475,18 +475,22 @@ class PipelineInputUrlMissingError(PipelineInputContentError):class MethodEntryError(PipelexError):- """Raised when a method run with no pipe named has no single pipe to start at.-- The rule is the MTHDS protocol's for a run that names no `pipe_code`: the manifest's `main_pipe` when the method's- tree holds a `METHODS.toml` at its root, else the one `main_pipe` its bundles declare. A manifest declaring none or- a pipe no bundle defines, and a method with no manifest whose bundles declare none or several, are refused, with- the bundles named by their tree paths. The method is the caller's own, so the message is theirs to read.+ """Raised when a method has no single pipe to start at, or no single bundle defining the pipe named.++ The rule is the MTHDS protocol's for a run that names no `pipe_code`, and every command acting on one pipe of a+ method's folder applies it to settle that pipe, `run`, `inputs` and `build` among them: the manifest's `main_pipe`+ when the method's tree holds a `METHODS.toml` at its root, else the one `main_pipe` its bundles declare. A manifest+ declaring none or a pipe no bundle defines, and a method with no manifest whose bundles declare none or several, are+ refused, with the bundles named by their tree paths. So is a pipe named for a command that acts on the bundle+ defining it, when no single bundle of the method defines that pipe. A command judging the whole method, such as+ `validate`, needs no pipe to start at and is not refused. The method is the caller's own, so the message is theirs+ to read."""error_domain = ErrorDomain.INPUTretryable = Falseuser_action = UserAction(kind=UserActionKind.CHANGE_INPUT,- detail="Name the pipe to run, or declare the method's one main_pipe: in its METHODS.toml, or in one of its bundles",+ detail="Name the pipe, or declare the method's one main_pipe: in its METHODS.toml, or in one of its bundles",)_authors_caller_facing_message = Truediff --git a/pipelex/pipeline/fixes/applicability.py b/pipelex/pipeline/fixes/applicability.pyindex 0c67c9f41..e4614d4b9 100644--- a/pipelex/pipeline/fixes/applicability.py+++ b/pipelex/pipeline/fixes/applicability.py@@ -13,6 +13,6 @@ def is_safe_fix_for_load_scope(fix: SuggestedFix, *, is_single_file: bool) -> boreturn fix.source is not None or is_single_file-def is_target_in_write_scope(target_path: Path, *, entry_path: Path, writable_dirs: Sequence[Path]) -> bool:- """Whether a target is the entry file or lies under an explicitly writable directory."""+def is_target_in_write_scope(target_path: Path, *, entry_path: Path | None, writable_dirs: Sequence[Path]) -> bool:+ """Whether a target is the entry file, when there is one, or lies under an explicitly writable directory."""return target_path == entry_path or any(target_path.is_relative_to(writable_dir) for writable_dir in writable_dirs)diff --git a/pipelex/pipeline/fixes/fix_loop.py b/pipelex/pipeline/fixes/fix_loop.pyindex 51a8951c2..4051b6fb8 100644--- a/pipelex/pipeline/fixes/fix_loop.py+++ b/pipelex/pipeline/fixes/fix_loop.py@@ -20,10 +20,15 @@ Two scoping rules bound what gets touched:file plus ``.mthds`` files under the per-call ``library_dirs``. Fixes sourced at filesloaded via ambient resolution are excluded; when every fix is out of scope the loop bailsloudly, naming the files and the ``-L`` remedy.++A method's folder is fixed the same way (``fix_method_folder``): the loop validates the whole+method tree, as ``validate_bundle(method_dir=...)`` judges it, with no entry file. The tree is+rooted at the nearest ``METHODS.toml`` at or above the folder, so its root is in the write scope,+not only the folder named, and so are the ``library_dirs`` passed beside it."""import os-from collections.abc import Iterable, Sequence+from collections.abc import Awaitable, Callable, Iterable, Sequencefrom pathlib import Pathfrom typing import Any, NamedTuple, cast@@ -43,10 +48,11 @@ from pipelex.fix_ops.file_transaction import ()from pipelex.interpreter_hub import resolve_library_dirsfrom pipelex.libraries.library_utils import get_pipelex_mthds_files_from_dirs+from pipelex.libraries.method_trees import method_tree_rootfrom pipelex.pipe_machinery.pipe_blueprint import SIGNATURE_ONLY_KEYSfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.fixes.applicability import is_safe_fix_for_load_scope, is_target_in_write_scope-from pipelex.pipeline.validate_bundle import validate_bundle+from pipelex.pipeline.validate_bundle import ValidateBundleResult, dirs_beside_method, validate_bundlefrom pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_errorfrom pipelex.suggested_fix import DeleteKeyOp, DeleteTableOp, EnsureTableOp, FixOp, MoveKeyOp, RemapValueOp, RenameTableKeyOp, SetKeyOp, SuggestedFixfrom pipelex.tools.misc.exceptions import TomlError@@ -106,6 +112,21 @@ def _validation_error_items(exc: ValidateBundleError) -> list[ValidationErrorItereturn exc.validation_error_items()+def unfixable_method_result(*, error: ValidateBundleError) -> FixBundleResult:+ """The fix verdict on a method refused before anything of it loads, such as a folder whose tree is refused.++ Invalid, with nothing applied and nothing to fix: the refusal's items are the remaining errors, as they are when+ the loop itself cannot list the trees it is about to load.+ """+ return FixBundleResult(+ is_valid=False,+ iterations=0,+ fixes_applied=[],+ files_written=[],+ remaining_errors=_validation_error_items(error),+ )++def _pending_signatures_from_validation_result(validation_result: Any) -> list[str]:"""Pending signatures reported by validation, defaulting to none for success-only mocks."""pending_signatures = getattr(validation_result, "pending_signatures", None)@@ -125,14 +146,17 @@ def _absolute_source_path(path: Path) -> Path:return Path(os.path.abspath(path))-def _snapshot_loaded_sources(*, entry_source_path: Path, effective_dirs: Sequence[Path]) -> dict[Path, FileSnapshot]:+def _snapshot_loaded_sources(*, entry_source_path: Path | None, effective_dirs: Sequence[Path]) -> dict[Path, FileSnapshot]:"""Snapshot every source identity validation is about to load.Keys are lexical absolute source names, while each snapshot is pinned to the destinationresolved at the same time. The resolved destination is also an alias when unambiguous, which- accommodates injected managers that already report canonical source paths.+ accommodates injected managers that already report canonical source paths. A method's folder+ has no entry file: its bundles are those of its directory, among ``effective_dirs``."""- source_paths: set[Path] = {_absolute_source_path(entry_source_path)}+ source_paths: set[Path] = set()+ if entry_source_path is not None:+ source_paths.add(_absolute_source_path(entry_source_path))source_paths.update(_absolute_source_path(mthds_path)for mthds_path in get_pipelex_mthds_files_from_dirs(dirs={_absolute_source_path(directory) for directory in effective_dirs})@@ -149,13 +173,24 @@ def _snapshot_loaded_sources(*, entry_source_path: Path, effective_dirs: Sequencdef _bind_fixes_to_snapshots(fixes: list[SuggestedFix],*,- entry_source_path: Path,+ entry_source_path: Path | None,snapshots_by_source: dict[Path, FileSnapshot],) -> list[_BoundFix]:- """Bind each fix once to the pre-validation file identity that supplied its source."""+ """Bind each fix once to the pre-validation file identity that supplied its source.++ A source-less fix targets the entry file. A method's folder has none, but its load is never single-file, so+ ``_safe_fixes`` has already dropped every source-less fix.+ """bound_fixes: list[_BoundFix] = []for fix in fixes:- source_path = entry_source_path if fix.source is None else Path(fix.source)+ source_path: Path+ if fix.source is not None:+ source_path = Path(fix.source)+ elif entry_source_path is not None:+ source_path = entry_source_path+ else:+ msg = f"refusing to apply fix '{fix.fix_code}': it names no file, and a method's folder has no entry file to apply it to"+ raise FixWriteConflictError(msg)absolute_source = _absolute_source_path(source_path)snapshot = snapshots_by_source.get(absolute_source)if snapshot is None:@@ -207,7 +242,7 @@ def _safe_fixes(def _partition_by_write_scope(fixes: list[_BoundFix],*,- entry_path: Path,+ entry_path: Path | None,writable_dirs: Sequence[Path],) -> tuple[list[_BoundFix], list[Path]]:"""Split fixes into (writable, out-of-scope target paths).@@ -398,14 +433,94 @@ async def fix_bundle_file(``fix_loop_max_attempts`` builder config. ``select_codes`` / ``ignore_codes`` filter which fixrules may apply (see ``_safe_fixes``); the CLI validates the codes before calling."""- if max_iterations is None:- max_iterations = get_config().interpreter.builder.fix_loop_max_attemptsentry_source_path = _absolute_source_path(mthds_file_path)- entry_path = entry_source_path.resolve()effective_dirs, _ = resolve_library_dirs(library_dirs)- is_single_file = not effective_dirswrite_scope_dirs = library_dirs if writable_library_dirs is None else writable_library_dirs- writable_dirs: list[Path] = [Path(writable_dir).resolve() for writable_dir in write_scope_dirs] if write_scope_dirs is not None else []++ async def validate_the_bundle() -> ValidateBundleResult:+ return await validate_bundle(mthds_file_path=mthds_file_path, library_dirs=library_dirs, allow_signatures=allow_signatures)++ return await _fix_to_fixed_point(+ validate=validate_the_bundle,+ entry_source_path=entry_source_path,+ effective_dirs=effective_dirs,+ writable_dirs=[Path(writable_dir).resolve() for writable_dir in write_scope_dirs] if write_scope_dirs is not None else [],+ max_iterations=max_iterations,+ select_codes=select_codes,+ ignore_codes=ignore_codes,+ )+++async def fix_method_folder(+ *,+ method_dir: Path,+ library_dirs: Sequence[Path] | None = None,+ writable_library_dirs: Sequence[Path] | None = None,+ allow_signatures: bool = False,+ max_iterations: int | None = None,+ select_codes: Sequence[str] | None = None,+ ignore_codes: Sequence[str] | None = None,+) -> FixBundleResult:+ """Fix a method's folder in place, judged whole, until valid, out of fixes, no progress, or max_iterations.++ The loop of ``fix_bundle_file``, validating every bundle of the folder's method tree as ``validate_bundle``+ judges a method's folder (``method_dir``), with the caller's own ``library_dirs`` loaded beside it. There is no+ entry file: every fix names the file it targets, a source-less one being dropped, since the load is never a single+ file.++ The tree is rooted at the nearest ``METHODS.toml`` at or above the folder, so a fix may target any bundle of it,+ such as a sibling of the folder named: the tree's root and the directories beside it are the write scope, or+ ``writable_library_dirs`` when given, as the ``--diff`` preview's sandbox gives them, having mirrored that root.+ The snapshot taken before each validation lists the same directories the validation loads, the folder's listing+ being its whole tree's, so every file a fix can target was snapshotted under the name the load gives it.+ """+ beside_dirs = dirs_beside_method(method_dir=method_dir, library_dirs=library_dirs)+ loaded_dirs = [method_dir, *beside_dirs]+ write_scope_dirs: Sequence[Path]+ if writable_library_dirs is None:+ try:+ with translate_to_validate_bundle_error():+ tree_root = method_tree_root(handed_over=method_dir)+ except ValidateBundleError as exc:+ return unfixable_method_result(error=exc)+ write_scope_dirs = [tree_root, *beside_dirs]+ else:+ write_scope_dirs = writable_library_dirs++ async def validate_the_method() -> ValidateBundleResult:+ return await validate_bundle(+ method_dir=method_dir,+ library_dirs=library_dirs,+ library_dirs_are_callers=True,+ allow_signatures=allow_signatures,+ )++ return await _fix_to_fixed_point(+ validate=validate_the_method,+ entry_source_path=None,+ effective_dirs=loaded_dirs,+ writable_dirs=[Path(writable_dir).resolve() for writable_dir in write_scope_dirs],+ max_iterations=max_iterations,+ select_codes=select_codes,+ ignore_codes=ignore_codes,+ )+++async def _fix_to_fixed_point(+ *,+ validate: Callable[[], Awaitable[ValidateBundleResult]],+ entry_source_path: Path | None,+ effective_dirs: Sequence[Path],+ writable_dirs: list[Path],+ max_iterations: int | None,+ select_codes: Sequence[str] | None,+ ignore_codes: Sequence[str] | None,+) -> FixBundleResult:+ """The fix loop over what ``validate`` judges: a bundle file and its entry, or a method's folder with none."""+ if max_iterations is None:+ max_iterations = get_config().interpreter.builder.fix_loop_max_attempts+ entry_path = entry_source_path.resolve() if entry_source_path is not None else None+ is_single_file = not effective_dirsseen_fingerprints: set[str] = set()fixes_applied: list[SuggestedFix] = []@@ -428,11 +543,7 @@ async def fix_bundle_file(remaining_errors=_validation_error_items(exc),)try:- validation_result = await validate_bundle(- mthds_file_path=mthds_file_path,- library_dirs=library_dirs,- allow_signatures=allow_signatures,- )+ validation_result = await validate()pending_signatures = _pending_signatures_from_validation_result(validation_result)return FixBundleResult(is_valid=True,@@ -544,11 +655,7 @@ async def fix_bundle_file(# max_iterations apply rounds done — the final verdict comes from one last validation.try:- validation_result = await validate_bundle(- mthds_file_path=mthds_file_path,- library_dirs=library_dirs,- allow_signatures=allow_signatures,- )+ validation_result = await validate()pending_signatures = _pending_signatures_from_validation_result(validation_result)return FixBundleResult(is_valid=True,diff --git a/pipelex/pipeline/method_entry.py b/pipelex/pipeline/method_entry.pyindex 83c5d5c91..5dd200cd9 100644--- a/pipelex/pipeline/method_entry.py+++ b/pipelex/pipeline/method_entry.py@@ -1,16 +1,23 @@-"""Which pipe a method starts at when a run of its folder names none.+"""Which pipe a method starts at when a command handed its folder names none.The rule is the MTHDS protocol's for a request that names no `pipe_code` (`mthds/docs/spec/protocol.md`): a method-tree has no order, so no bundle is "the first" any more. The run starts at the manifest's `main_pipe` when the tree+tree has no order, so no bundle is "the first" any more. The method starts at the manifest's `main_pipe` when the treeholds a `METHODS.toml` at its root, or else, in a method with no manifest, at the one `main_pipe` its bundles declare.A manifest declaring no `main_pipe`, or a method with no manifest whose bundles declare none or several, is refused,with the bundles named by their tree paths.-`select_entry` applies the rule to bundles already parsed, wherever their tree was read from; `select_method_entry`-reads a tree listed from this host's disk.+The rule reads what each bundle declares of where its method starts, its `domain`, its `main_pipe` and the codes of its+pipes, and nothing else: a bundle whose pipes do not validate still says where its method starts, and is refused when+the method loads, by the command that loads it. Only a bundle whose declarations cannot be read, such as one that is+not TOML, is refused here.++`select_entry` applies the rule to bundles already read, wherever their tree was read from; `select_method_entry`+reads a tree listed from this host's disk. `select_named_pipe` finds the bundle defining a pipe the caller named, for a+command that acts on a bundle of the method rather than on the method's whole library."""-from typing import NamedTuple+from pathlib import Path+from typing import Any, NamedTuple, Self, castfrom mthds.method_tree.discovery import BUNDLE_SUFFIX, MANIFEST_NAMEfrom mthds.method_tree.models import MethodTree@@ -19,21 +26,40 @@ from mthds.package.exceptions import ManifestErrorfrom mthds.package.manifest.schema import MethodsManifestfrom pipelex.base_exceptions import PipelexUnexpectedError+from pipelex.core.qualified_ref import QualifiedRef, QualifiedRefErrorfrom pipelex.mthds_parsing.parser import MthdsParserfrom pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprint-from pipelex.pipe_machinery.pipe_factory import PipeFactory+from pipelex.pipe_machinery.validation import is_pipe_code_validfrom pipelex.pipeline.exceptions import MethodEntryError+from pipelex.tools.misc.exceptions import TomlError+from pipelex.tools.misc.toml_utils import load_toml_from_path++_DOMAIN_KEY = "domain"+_MAIN_PIPE_KEY = "main_pipe"+_PIPE_KEY = "pipe"class EntryCandidate(NamedTuple):- """A bundle of the method, named by its tree path, as its text declares it."""+ """A bundle of the method, named by its tree path, by what it declares of where its method starts."""tree_path: str- blueprint: PipelexBundleBlueprint+ domain: str+ main_pipe: str | None+ pipe_codes: frozenset[str]++ @classmethod+ def of_blueprint(cls, *, tree_path: str, blueprint: PipelexBundleBlueprint) -> Self:+ """The candidate a parsed bundle makes."""+ return cls(+ tree_path=tree_path,+ domain=blueprint.domain,+ main_pipe=blueprint.main_pipe,+ pipe_codes=frozenset(blueprint.pipe or {}),+ )class MethodEntry(NamedTuple):- """The pipe a run of a method starts at, and the tree path of the bundle that defines it."""+ """The pipe a command acts on, and the tree path of the bundle that defines it."""tree_path: strpipe_code: str@@ -48,12 +74,97 @@ def _entry_of(*, candidate: EntryCandidate, pipe_code: str) -> MethodEntry:return MethodEntry(tree_path=candidate.tree_path,pipe_code=pipe_code,- pipe_ref=PipeFactory.make_pipe_ref_with_domain(domain_code=candidate.blueprint.domain, pipe_code=pipe_code),+ pipe_ref=QualifiedRef.from_domain_and_code(domain_path=candidate.domain, local_code=pipe_code).full_ref,)+def _declared_candidate(*, tree_path: str, bundle_dict: dict[str, Any]) -> EntryCandidate | None:+ """The candidate a bundle's raw TOML declares, or None when the full parse must say what is wrong with it.++ That is when its domain or pipe table has the wrong type, or its main_pipe is not a pipe code: a `main_pipe` is+ held to the rule the bundle's parse holds it to, so `dom.pipe`, `camelCase` and an empty string are refused as the+ load would refuse them, never read as a pipe to start at nor, for the empty string, as declaring none.+ """+ domain = bundle_dict.get(_DOMAIN_KEY)+ main_pipe = bundle_dict.get(_MAIN_PIPE_KEY)+ pipe_table = bundle_dict.get(_PIPE_KEY)+ if not isinstance(domain, str):+ return None+ if main_pipe is not None and not (isinstance(main_pipe, str) and is_pipe_code_valid(main_pipe)):+ return None+ if pipe_table is not None and not isinstance(pipe_table, dict):+ return None+ pipe_codes = frozenset(cast("dict[str, Any]", pipe_table or {}))+ return EntryCandidate(tree_path=tree_path, domain=domain, main_pipe=main_pipe, pipe_codes=pipe_codes)+++def read_entry_candidate(*, tree_path: str, bundle_file: Path) -> EntryCandidate:+ """What a bundle file declares of where its method starts, read without validating its pipes.++ Raises:+ MthdsParserError: The bundle is not TOML or not UTF-8 text, its domain or pipe table cannot be read, or its+ main_pipe is not a valid pipe code, each located as its full parse locates it.+ """+ try:+ bundle_dict = load_toml_from_path(path=bundle_file)+ except (TomlError, UnicodeDecodeError):+ candidate = None+ else:+ candidate = _declared_candidate(tree_path=tree_path, bundle_dict=bundle_dict)+ if candidate is not None:+ return candidate+ # What the bundle declares cannot be read as it stands: its full parse says why, as the load would.+ blueprint = MthdsParser.make_pipelex_bundle_blueprint(bundle_path=bundle_file)+ return EntryCandidate.of_blueprint(tree_path=tree_path, blueprint=blueprint)+++def tree_method_label(*, tree: MethodTree) -> str:+ """How the entry rule's messages name a method tree listed from this host's disk: by its folder."""+ return f"at '{tree.directory}'"+++def read_method_candidates(*, tree: MethodTree) -> list[EntryCandidate]:+ """The bundles of a method tree listed from this host's disk, in tree path order, by what each declares.++ Raises:+ MethodEntryError: The tree has no directory on this host to read its bundles from.+ MthdsParserError: A bundle's declarations cannot be read (see `read_entry_candidate`).+ """+ if tree.directory is None:+ msg = "A method tree read from a map of file entries has no folder on this host to read its bundles from."+ raise MethodEntryError(msg)+ return [+ read_entry_candidate(tree_path=tree_path, bundle_file=tree.file_location(tree_path))+ for tree_path in tree.tree_paths+ if tree_path.endswith(BUNDLE_SUFFIX)+ ]+++def read_method_manifest(*, tree: MethodTree) -> MethodsManifest | None:+ """The `METHODS.toml` at the root of a method tree listed from this host's disk, or None when it holds none there.++ Raises:+ MethodEntryError: The tree has no directory on this host, or its manifest cannot be read.+ """+ if MANIFEST_NAME not in tree.members:+ return None+ if tree.directory is None:+ msg = "A method tree read from a map of file entries has no folder on this host to read its manifest from."+ raise MethodEntryError(msg)+ method_label = tree_method_label(tree=tree)+ try:+ manifest = read_package_manifest_at(tree.directory)+ except ManifestError as exc:+ msg = f"The {MANIFEST_NAME} of the method {method_label} cannot be read: {exc}"+ raise MethodEntryError(msg) from exc+ if manifest is None:+ msg = f"The method {method_label} lists a {MANIFEST_NAME} at its root that could not be read back."+ raise MethodEntryError(msg)+ return manifest++def select_entry(*, candidates: list[EntryCandidate], manifest: MethodsManifest | None, method_label: str) -> MethodEntry:- """The pipe a run of a method starts at when it names none, by the MTHDS protocol's rule.+ """The pipe a method starts at when the caller names none, by the MTHDS protocol's rule.Args:candidates: The method's bundles, in tree path order.@@ -71,7 +182,7 @@ def select_entry(*, candidates: list[EntryCandidate], manifest: MethodsManifestif manifest is not None:return _manifest_entry(candidates=candidates, manifest=manifest, method_label=method_label, bundle_paths=bundle_paths)- declaring = [candidate for candidate in candidates if candidate.blueprint.main_pipe]+ declaring = [candidate for candidate in candidates if candidate.main_pipe is not None]if not declaring:msg = (f"The method {method_label} has no {MANIFEST_NAME}, and none of its bundles declares a main_pipe "@@ -79,7 +190,7 @@ def select_entry(*, candidates: list[EntryCandidate], manifest: MethodsManifest)raise MethodEntryError(msg)if len(declaring) > 1:- declarations = ", ".join(f"'{candidate.tree_path}' declares '{candidate.blueprint.main_pipe}'" for candidate in declaring)+ declarations = ", ".join(f"'{candidate.tree_path}' declares '{candidate.main_pipe}'" for candidate in declaring)msg = (f"The method {method_label} has no {MANIFEST_NAME}, and several of its bundles declare a main_pipe: {declarations}. "f"A method starts at one pipe: keep one main_pipe, declare the method's main_pipe in a {MANIFEST_NAME} at its root, "@@ -87,7 +198,7 @@ def select_entry(*, candidates: list[EntryCandidate], manifest: MethodsManifest)raise MethodEntryError(msg)entry_candidate = declaring[0]- main_pipe = entry_candidate.blueprint.main_pipe+ main_pipe = entry_candidate.main_pipeif main_pipe is None:# Selected because it declares one: this is a bug of the selection, never the caller's method.msg = f"The bundle '{entry_candidate.tree_path}' was selected for its main_pipe, yet declares none."@@ -110,11 +221,7 @@ def _manifest_entry(*, candidates: list[EntryCandidate], manifest: MethodsManiferaise MethodEntryError(msg)# The manifest refuses a main_pipe no domain exports, so the domains exporting it say which bundles may define it.exporting_domains = {domain for domain, domain_exports in manifest.exports.items() if main_pipe in domain_exports.pipes}- defining = [- candidate- for candidate in candidates- if candidate.blueprint.domain in exporting_domains and candidate.blueprint.pipe is not None and main_pipe in candidate.blueprint.pipe- ]+ defining = [candidate for candidate in candidates if candidate.domain in exporting_domains and main_pipe in candidate.pipe_codes]if not defining:msg = (f"The {MANIFEST_NAME} of the method {method_label} declares the main_pipe '{main_pipe}', exported by "@@ -122,7 +229,7 @@ def _manifest_entry(*, candidates: list[EntryCandidate], manifest: MethodsManife)raise MethodEntryError(msg)if len(defining) > 1:- definitions = ", ".join(f"'{candidate.tree_path}' in domain '{candidate.blueprint.domain}'" for candidate in defining)+ definitions = ", ".join(f"'{candidate.tree_path}' in domain '{candidate.domain}'" for candidate in defining)msg = (f"The {MANIFEST_NAME} of the method {method_label} declares the main_pipe '{main_pipe}', which several of its "f"bundles define: {definitions}. Name the pipe to run as domain.pipe_code."@@ -132,33 +239,50 @@ def _manifest_entry(*, candidates: list[EntryCandidate], manifest: MethodsManifedef select_method_entry(*, tree: MethodTree) -> MethodEntry:- """The pipe a run of a method tree listed from this host's disk starts at when it names none.+ """The pipe a method tree listed from this host's disk starts at when the caller names none.- Each bundle of the tree is parsed to read what it declares, and the manifest at the tree's root, when the tree- holds one, is read.+ Each bundle of the tree is read for what it declares, and the manifest at the tree's root, when the tree holds one,+ is read.Raises:MethodEntryError: The tree has no directory on this host, its manifest cannot be read, or `select_entry`refuses it.- MthdsParserError: A bundle of the tree does not parse.+ MthdsParserError: A bundle's declarations cannot be read (see `read_entry_candidate`)."""- if tree.directory is None:- msg = "A method tree read from a map of file entries has no folder on this host to read its bundles from."+ candidates = read_method_candidates(tree=tree)+ manifest = read_method_manifest(tree=tree)+ return select_entry(candidates=candidates, manifest=manifest, method_label=tree_method_label(tree=tree))+++def select_named_pipe(*, candidates: list[EntryCandidate], pipe_ref: str, method_label: str) -> MethodEntry:+ """The bundle of a method defining the pipe the caller named, as `pipe_code` or `domain.pipe_code`.++ Raises:+ MethodEntryError: The name is a dependency's pipe or not a pipe reference, no bundle of the method defines the+ pipe, or, named by its bare code, bundles of several domains define it.+ """+ bundle_paths = [candidate.tree_path for candidate in candidates]+ if QualifiedRef.has_cross_package_prefix(pipe_ref):+ msg = (+ f"The pipe '{pipe_ref}' belongs to a package the method {method_label} depends on, and no bundle of the method "+ "defines it. Name a pipe of the method, or the bundle file that runs it."+ )raise MethodEntryError(msg)- method_label = f"at '{tree.directory}'"- candidates = [- EntryCandidate(tree_path=tree_path, blueprint=MthdsParser.make_pipelex_bundle_blueprint(bundle_path=tree.file_location(tree_path)))- for tree_path in tree.tree_paths- if tree_path.endswith(BUNDLE_SUFFIX)+ try:+ qualified_ref = QualifiedRef.parse(pipe_ref)+ except QualifiedRefError as exc:+ msg = f"'{pipe_ref}' does not name a pipe of the method {method_label}: {exc}"+ raise MethodEntryError(msg) from exc+ defining = [+ candidate+ for candidate in candidates+ if qualified_ref.local_code in candidate.pipe_codes and (qualified_ref.domain_path is None or candidate.domain == qualified_ref.domain_path)]- manifest: MethodsManifest | None = None- if MANIFEST_NAME in tree.members:- try:- manifest = read_package_manifest_at(tree.directory)- except ManifestError as exc:- msg = f"The {MANIFEST_NAME} of the method {method_label} cannot be read: {exc}"- raise MethodEntryError(msg) from exc- if manifest is None:- msg = f"The method {method_label} lists a {MANIFEST_NAME} at its root that could not be read back."- raise MethodEntryError(msg)- return select_entry(candidates=candidates, manifest=manifest, method_label=method_label)+ if not defining:+ msg = f"No bundle of the method {method_label} defines the pipe '{pipe_ref}'. Its bundles: {_listed(names=bundle_paths)}."+ raise MethodEntryError(msg)+ if len(defining) > 1:+ definitions = ", ".join(f"'{candidate.tree_path}' in domain '{candidate.domain}'" for candidate in defining)+ msg = f"Several bundles of the method {method_label} define the pipe '{pipe_ref}': {definitions}. Name the pipe as domain.pipe_code."+ raise MethodEntryError(msg)+ return _entry_of(candidate=defining[0], pipe_code=qualified_ref.local_code)diff --git a/pipelex/pipeline/validate_bundle.py b/pipelex/pipeline/validate_bundle.pyindex a5641689a..4b76dea80 100644--- a/pipelex/pipeline/validate_bundle.py+++ b/pipelex/pipeline/validate_bundle.py@@ -143,7 +143,9 @@ async def validate_bundle(``method_dir`` is the directory of a method's tree, the caller's own, such as the tree a host wrote out for arequest: every bundle of the tree is loaded as a member of it and dry-run, every refusal is the caller's verdict andnames the tree's files as the tree does, and ``methods_dirs``, laid out like ``.mthds/methods/``, hold the packages- the caller ships with it, searched first for an address-based reference. No other library directory loads beside it.+ the caller ships with it, searched first for an address-based reference. No host's library directory loads beside+ it: only ``library_dirs`` that ``library_dirs_are_callers`` says are the caller's own, as on a command run over the+ caller's own disk, which load with the tree for its bundles to use while only the tree's own pipes are judged.``submitted_files`` are the files submitted with ``mthds_contents`` that their steps read, such as a``PipeDocGen`` step's ``template_file``, keyed by canonical bundle-relative path (see@@ -182,8 +184,8 @@ async def validate_bundle(if provided_params > 1:msg = "Only one of mthds_contents, mthds_file_path or method_dir can be provided to validate_bundle"raise PipelexUnexpectedError(msg)- if method_dir is not None and library_dirs is not None:- msg = "A method's tree validates alone: no library directory loads beside method_dir"+ if method_dir is not None and library_dirs is not None and not library_dirs_are_callers:+ msg = "A method's tree validates beside no host's library directory: only the caller's own directories load beside method_dir"raise PipelexUnexpectedError(msg)if methods_dirs is not None and method_dir is None:msg = "methods_dirs accompany method_dir, the method whose packages they hold"@@ -221,6 +223,7 @@ async def validate_bundle(result = await _validate_method_dir(method_dir=method_dir,methods_dirs=methods_dirs,+ library_dirs=library_dirs,library_id=library_id,allow_signatures=allow_signatures,dry_run_pipe_codes=dry_run_pipe_codes,@@ -380,27 +383,66 @@ def _ensure_tree_python_parses(*, tree: MethodTree) -> None:raise ValidateBundleError(message=" ".join(item.message for item in items), pipelex_bundle_blueprint_validation_errors=items)+def _is_member_blueprint(*, blueprint: PipelexBundleBlueprint, tree: MethodTree) -> bool:+ """Whether a loaded bundle is a file of the method's own tree, by the tree its loader listed it in.++ The tree it was listed in is the method's when it is rooted at the same directory, which tells the method's bundles+ from those of a package nested in it, of a dependency shipped with it, or of a directory loaded beside it, even when+ one of them holds a bundle at the same tree path, as the trees a host writes out name their bundles.+ """+ tree_bundle = blueprint.tree_bundle+ if tree_bundle is None or tree_bundle.tree_path is None or tree_bundle.tree_path not in tree.members:+ return False+ listed_in = tree_bundle.tree.directory+ if listed_in is None or tree.directory is None:+ return False+ return listed_in.resolve() == tree.directory.resolve()+++def dirs_beside_method(*, method_dir: Path, library_dirs: Sequence[Path] | None) -> list[Path]:+ """The caller's library directories that load beside a method's folder, the folder itself left out.++ The directories are compared resolved, so `.`, a trailing slash or a symlink naming the folder never loads it twice.+ Each is kept as the caller gave it, so the files it holds are spelled as the caller spelled the directory.+ """+ resolved_method_dir = method_dir.resolve()+ return [library_dir for library_dir in library_dirs or [] if library_dir.resolve() != resolved_method_dir]++async def _validate_method_dir(*,method_dir: Path,methods_dirs: Sequence[Path] | None,+ library_dirs: Sequence[Path] | None,library_id: str,allow_signatures: bool,dry_run_pipe_codes: list[str] | None,caller_identity: CallerIdentity | None,collect_dry_run_warnings: bool,) -> ValidateBundleResult:- """Load the tree of a caller's method into the open library and dry-run its pipes (see ``validate_bundle``)."""+ """Load the tree of a caller's method into the open library and dry-run its pipes (see ``validate_bundle``).++ The caller's own `library_dirs` load in the same pass as the tree, so the method's bundles and theirs can name one+ another as a run of the folder loads them, but only the pipes of the tree's own bundles are judged.+ """library_manager = get_library_manager()library = library_manager.get_library(library_id=library_id)+ beside_dirs = dirs_beside_method(method_dir=method_dir, library_dirs=library_dirs)with translate_to_validate_bundle_error():- _ensure_tree_python_parses(tree=list_local_method_tree(handed_over=method_dir))+ tree = list_local_method_tree(handed_over=method_dir)+ _ensure_tree_python_parses(tree=tree)loaded_pipes = library_manager.load_libraries(library_id=library_id,- library_dirs=[method_dir],+ library_dirs=[method_dir, *beside_dirs],methods_dirs=list(methods_dirs) if methods_dirs is not None else None,)blueprints = library_manager.get_accumulated_blueprints(library_id)+ # Only the tree's own bundles are the method. The directories beside it, and the packages nested in it that the+ # load reads as their own trees, hold what its bundles use: their pipes load, so the method's can call them, but+ # are not judged, so loading a directory beside the method never changes which of its pipes the verdict covers.+ blueprints = [blueprint for blueprint in blueprints if _is_member_blueprint(blueprint=blueprint, tree=tree)]+ member_pipe_refs = {f"{blueprint.domain}.{pipe_code}" for blueprint in blueprints for pipe_code in blueprint.pipe or {}}+ loaded_pipes = [pipe for pipe in loaded_pipes if pipe.pipe_ref in member_pipe_refs]if not blueprints:msg = "The method holds no .mthds bundle, so it has nothing to validate."raise ValidateBundleError(message=msg)diff --git a/pipelex/pipeline/validation_render.py b/pipelex/pipeline/validation_render.pyindex 9ad99ea38..e17c11474 100644--- a/pipelex/pipeline/validation_render.py+++ b/pipelex/pipeline/validation_render.py@@ -44,7 +44,9 @@ def format_validate_markdown(result: dict[str, Any]) -> str:``validated_pipes`` (a list of ``{pipe_ref, status}``), ``total_pipes``,and an optional ``bundle_path``. ``validate bundle --graph`` / ``--view``also merge ``graph_files`` / ``graphspec`` into the result — those are- surfaced too so markdown mode does not silently drop them.+ surfaced too so markdown mode does not silently drop them — or, for a+ method's folder with no single pipe to draw, ``graph_unavailable``, the+ reason no graph was drawn.Args:result: The JSON-mode result dict for the validation.@@ -116,6 +118,10 @@ def format_validate_markdown(result: dict[str, Any]) -> str:if "graphspec" in result:lines += ["", "_A GraphSpec (structured graph JSON) is included — use `--format json` to retrieve it._"]+ graph_unavailable = result.get("graph_unavailable")+ if graph_unavailable:+ lines += ["", "## Graph", "", str(graph_unavailable)]+return "\n".join(lines)@@ -313,9 +319,13 @@ def count_applicable_fixes(bundle_path: Path,library_dirs: list[Path] | None,) -> int:- """Count safe fixes the displayed command is authorized and able to apply."""- effective_dirs, _ = resolve_library_dirs(library_dirs)- is_single_file = not effective_dirs+ """Count safe fixes the displayed command is authorized and able to apply.++ A method's folder always loads as a library directory, so its load is never a single file's, and that is decided+ without asking the interpreter hub for its default directories: a folder whose tree is refused before the boot is+ reported, with this count, while no hub exists.+ """+ is_single_file = not bundle_path.is_dir() and not resolve_library_dirs(library_dirs)[0]entry_path = bundle_path.resolve()writable_dirs = [library_dir.resolve() for library_dir in library_dirs] if library_dirs is not None else []applicable_count = 0diff --git a/pipelex/test_extras/mthds_corpus/loader.py b/pipelex/test_extras/mthds_corpus/loader.pyindex 347267bd3..53d02a3c6 100644--- a/pipelex/test_extras/mthds_corpus/loader.py+++ b/pipelex/test_extras/mthds_corpus/loader.py@@ -10,10 +10,15 @@ import refrom collections.abc import Iteratorfrom pathlib import Path+from mthds.method_tree.discovery import BUNDLE_SUFFIXfrom pydantic import BaseModel, ConfigDict-from pipelex.cli.bundle_target_resolution import BundleTargetResolutionError, resolve_bundle_target_core+from pipelex.libraries.exceptions import MethodTreeLoadError+from pipelex.libraries.method_trees import list_local_method_tree_at_root+from pipelex.mthds_parsing.exceptions import MthdsParserErrorfrom pipelex.pipeline.default_file_names import DEFAULT_INPUTS_FILE_NAME+from pipelex.pipeline.exceptions import MethodEntryError+from pipelex.pipeline.method_entry import select_method_entryfrom pipelex.test_extras.mthds_corpus.exceptions import CorpusEntryErrorfrom pipelex.test_extras.mthds_corpus.manifest import (ENTRY_NAME_PATTERN,@@ -43,21 +48,39 @@ class CorpusEntry(BaseModel):def _resolve_bundle_path(*, directory: Path) -> Path:- """Pick the entry's bundle file through the very resolution ``pipelex validate bundle <dir>`` runs.+ """Pick the entry's bundle file by the MTHDS protocol's entry rule, the one ``pipelex run bundle <dir>`` starts at.- The contract says an entry directory is a valid CLI argument as it stands — either exactly one- ``.mthds`` file, or several with a ``bundle.mthds`` entry point. That claim is made true by- calling the CLI's own core rather than by keeping a corpus copy of its rules: a copy is how the- two drift, and a hand-rolled glob had already lost the core's refusal to auto-detect a symlinked- bundle. Only the rendering of a failure is ours.+ The contract says an entry directory is a valid CLI argument as it stands: a method's folder whose entry the rule+ selects, the one ``main_pipe`` its bundles declare, so ``run bundle <dir>`` starts at it while ``validate bundle+ <dir>`` judges the folder whole. That claim is made true by calling the rule the CLI calls+ (``select_method_entry`` over the folder's method tree) rather than by keeping a corpus copy of it: a copy is how+ the two drift. The rule reads only the bundles' declarations, so an entry whose bundle is deliberately invalid+ resolves as long as it declares its ``main_pipe``. Only the rendering of a failure is ours.++ The rule refuses a bundle whose declarations it cannot read, a ``main_pipe`` that is no pipe code among them, as+ ``run bundle <dir>`` refuses it. An entry authored to trigger that refusal holds that one bundle, which is the+ bundle the refusal names, so a single-bundle entry the rule cannot read resolves to its bundle.++ The entry directory is listed as its own root, with no Manifest Discovery: the corpus ships inside an installed+ package, and a ``METHODS.toml`` in one of its ancestors, such as a project above ``site-packages``, is no part of it."""- resolved = resolve_bundle_target_core(str(directory), library_dir=None)- if isinstance(resolved, BundleTargetResolutionError):- candidates = ", ".join(candidate.name for candidate in resolved.candidate_files)- detail = f" ({candidates})" if candidates else ""- msg = f"Corpus entry '{directory.name}' does not resolve to a bundle: {resolved.kind}{detail}"- raise CorpusEntryError(msg)- return resolved.bundle_path+ try:+ tree = list_local_method_tree_at_root(root=directory)+ except MethodTreeLoadError as exc:+ msg = f"Corpus entry '{directory.name}' does not resolve to a bundle: {exc.message}"+ raise CorpusEntryError(msg) from exc+ try:+ entry = select_method_entry(tree=tree)+ except MthdsParserError as exc:+ bundle_paths = [tree_path for tree_path in tree.tree_paths if tree_path.endswith(BUNDLE_SUFFIX)]+ if len(bundle_paths) != 1:+ msg = f"Corpus entry '{directory.name}' does not resolve to a bundle: {exc.message}"+ raise CorpusEntryError(msg) from exc+ return tree.file_location(bundle_paths[0])+ except MethodEntryError as exc:+ msg = f"Corpus entry '{directory.name}' does not resolve to a bundle: {exc.message}"+ raise CorpusEntryError(msg) from exc+ return tree.file_location(entry.tree_path)def load_entry(*, directory: Path) -> CorpusEntry:diff --git a/subject_grants.toml b/subject_grants.tomlindex 4c664aa7c..eb53a8f53 100644--- a/subject_grants.toml+++ b/subject_grants.toml@@ -76,14 +76,6 @@ rationale = "Extracts from the exc; single operand."param = "error_format"rationale = "Setter: installs the agent-CLI error format; single operand."-["pipelex/cli/agent_cli/commands/bundle_path_resolver.py::_handle_resolution_error"]-param = "error"-rationale = "Error handler: the resolution error is the single operand handled."--["pipelex/cli/agent_cli/commands/bundle_path_resolver.py::_stringify_library_dirs"]-param = "library_dirs"-rationale = "Single-operand conversion of the dirs list."-["pipelex/cli/agent_cli/commands/bundle_path_resolver.py::resolve_bundle_target"]param = "path"rationale = "Verb-object: resolves the target path; library_dir stays keyword."@@ -188,10 +180,6 @@ rationale = "Validates the pipe identified by pipe_code; single operand."param = "path"rationale = "Verb-object: resolves the target path; library_dir stays keyword."-["pipelex/cli/commands/bundle_path_resolver.py::_handle_resolution_error"]-param = "error"-rationale = "Error handler: the resolution error is the single operand handled."-["pipelex/cli/commands/bundle_path_resolver.py::_stringify_library_dirs"]param = "library_dirs"rationale = "Single-operand conversion of the dirs list."@@ -218,7 +206,7 @@ rationale = "Single-operand conversion: maps a sandbox path back to its original["pipelex/cli/commands/fix/_diff_sandbox.py::mirror_bundle_for_preview"]param = "entry_path"-rationale = "Verb-object: mirrors the bundle at entry_path; the rest is context."+rationale = "Verb-object: mirrors the bundle at entry_path, or a method folder with no entry; the rest is context."["pipelex/cli/commands/fix/_fix_core.py::_remap_result_to_originals"]param = "result"@@ -228,10 +216,6 @@ rationale = "Verb-object: remaps the result; sandbox is context."param = "item"rationale = "Verb-object: remaps the error item; sandbox is context."-["pipelex/cli/commands/fix/_fix_core.py::execute_fix"]-param = "bundle_path"-rationale = "Verb-object: fixes the bundle at bundle_path; options stay keyword."-["pipelex/cli/commands/graph_cmd.py::_do_graph_render"]param = "input_file"rationale = "Renders the input file to a graph; single operand."diff --git a/tests/data/errors/error_identity.txt b/tests/data/errors/error_identity.txtindex ca5dd2bb0..04bc9e6f3 100644--- a/tests/data/errors/error_identity.txt+++ b/tests/data/errors/error_identity.txt@@ -85,6 +85,7 @@ DuplicatePipeFuncPackageOfferError | Duplicate pipe func package offer | https:/DuplicateSecretsProviderError | Duplicate secrets provider | https://docs.pipelex.com/latest/errors/duplicate-secrets-provider-error/DuplicateServiceErrorCodeError | Duplicate service error code | https://docs.pipelex.com/latest/errors/duplicate-service-error-code-error/DuplicateStorageProviderError | Duplicate storage provider | https://docs.pipelex.com/latest/errors/duplicate-storage-provider-error/+EmptyMethodTreeError | Empty method tree | https://docs.pipelex.com/latest/errors/empty-method-tree-error/EntryPipeAmbiguousError | Entry pipe ambiguous | https://docs.pipelex.com/latest/errors/entry-pipe-ambiguous-error/EntryPipeNotFoundError | Entry pipe not found | https://docs.pipelex.com/latest/errors/entry-pipe-not-found-error/EnvVarNotFoundError | Environment variable not set | https://docs.pipelex.com/latest/errors/env-var-not-found-error/diff --git a/tests/e2e/pipelex/cli/test_refused_tree_before_boot.py b/tests/e2e/pipelex/cli/test_refused_tree_before_boot.pynew file mode 100644index 000000000..98ee504c1--- /dev/null+++ b/tests/e2e/pipelex/cli/test_refused_tree_before_boot.py@@ -0,0 +1,85 @@+"""A method's folder whose tree is refused before the boot is reported as a verdict, never as a crash.++`validate bundle` and `fix bundle` list a folder's method tree before they boot, so a tree the listing refuses, here+one holding a symbolic link, is reported while no interpreter hub exists. The report used to count the fixes it could+suggest by asking the hub for its default library directories, which crashed it with a `RuntimeError` after the panel+was printed, exiting 1 by accident. The in-process test session always holds a booted hub, so only the real console+scripts, run with no hub, reproduce what a user meets.+"""++from __future__ import annotations++import subprocess # ruff: ignore[suspicious-subprocess-import] - invokes the real CLI binaries, which run with no hub before the boot+from typing import TYPE_CHECKING++import pytest++from tests.e2e.agent_cli.conftest import PIPELEX_AGENT_BIN, REPO_ROOT++if TYPE_CHECKING:+ from pathlib import Path++_PIPELEX_BIN = REPO_ROOT / ".venv" / "bin" / "pipelex"++_BUNDLE_MTHDS = """domain = "refused_tree"+main_pipe = "say_hello"++[pipe.say_hello]+type = "PipeLLM"+description = "Say hello"+output = "Text"+prompt = "Say hello"+"""++_LINK_NAME = "linked_notes.txt"+++def _write_folder_holding_a_link(*, directory: Path) -> Path:+ method_dir = directory / "method"+ method_dir.mkdir()+ (method_dir / "bundle.mthds").write_text(_BUNDLE_MTHDS, encoding="utf-8")+ outside_file = directory / "notes.txt"+ outside_file.write_text("Notes kept outside the method.\n", encoding="utf-8")+ (method_dir / _LINK_NAME).symlink_to(outside_file)+ return method_dir+++def _command_line(*, surface: str, method_dir: Path) -> list[str]:+ match surface:+ case "pipelex validate":+ return [str(_PIPELEX_BIN), "--no-logo", "validate", "bundle", str(method_dir)]+ case "pipelex fix":+ return [str(_PIPELEX_BIN), "--no-logo", "fix", "bundle", str(method_dir)]+ case "pipelex-agent validate":+ return [str(PIPELEX_AGENT_BIN), "validate", "bundle", str(method_dir)]+ case "pipelex-agent fix":+ return [str(PIPELEX_AGENT_BIN), "fix", "bundle", str(method_dir)]+ case _:+ msg = f"Unknown surface '{surface}'"+ raise ValueError(msg)+++class TestRefusedTreeBeforeBoot:+ @pytest.mark.parametrize("surface", ["pipelex validate", "pipelex fix", "pipelex-agent validate", "pipelex-agent fix"])+ def test_a_folder_refused_before_the_boot_exits_1_without_a_traceback(+ self, tmp_path: Path, offline_subprocess_env: dict[str, str], surface: str+ ) -> None:+ """The refusal names the link and exits with the invalid verdict's code, 1, with no traceback behind it."""+ method_dir = _write_folder_holding_a_link(directory=tmp_path)++ completed = subprocess.run( # ruff: ignore[subprocess-without-shell-equals-true]+ _command_line(surface=surface, method_dir=method_dir),+ env=offline_subprocess_env,+ cwd=str(tmp_path),+ capture_output=True,+ text=True,+ check=False,+ timeout=120,+ )++ output = completed.stdout + completed.stderr+ assert completed.returncode == 1, output+ assert "Traceback" not in output+ assert "RuntimeError" not in output+ assert "InterpreterHub is not initialized" not in output+ assert _LINK_NAME in outputdiff --git a/tests/helpers/method_folders.py b/tests/helpers/method_folders.pynew file mode 100644index 000000000..7cda33d0c--- /dev/null+++ b/tests/helpers/method_folders.py@@ -0,0 +1,103 @@+"""Method folders for the tests of the commands that take one, in each shape the MTHDS protocol's entry rule decides."""++from enum import StrEnum+from pathlib import Path+from typing import NamedTuple+++def entry_bundle_text(*, domain: str, pipe_code: str, main_pipe: str | None) -> str:+ """A bundle of one PipeLLM, declaring `main_pipe` when given."""+ main_pipe_line = f'main_pipe = "{main_pipe}"\n' if main_pipe else ""+ return f"""domain = "{domain}"+{main_pipe_line}+[pipe.{pipe_code}]+type = "PipeLLM"+description = "Summarize the text"+inputs = {{ text = "Text" }}+output = "Text"+prompt = "Summarize $text"+"""+++class FolderEntry(NamedTuple):+ """Where the entry rule starts a folder: the bundle by its tree path, and the pipe as `domain.pipe_code`."""++ tree_path: str+ pipe_ref: str+++class MethodFolderShape(StrEnum):+ """The folders a command taking one must read alike, each named by what the entry rule finds in it."""++ # A METHODS.toml names the entry, in a bundle that is neither `bundle.mthds` nor at the top of the folder.+ MANIFEST_MAIN_PIPE = "manifest_main_pipe"+ # No manifest, and one bundle declares a main_pipe; a `bundle.mthds` beside it declares none.+ ONE_DECLARED_MAIN_PIPE = "one_declared_main_pipe"+ # No manifest, and two bundles declare a main_pipe.+ SEVERAL_MAIN_PIPES = "several_main_pipes"+ # No manifest, and no bundle declares a main_pipe.+ NO_MAIN_PIPE = "no_main_pipe"++ @property+ def files(self) -> dict[str, str]:+ """The folder's files, by tree path."""+ match self:+ case MethodFolderShape.MANIFEST_MAIN_PIPE:+ return {+ "METHODS.toml": (+ '[package]\naddress = "github.com/pipelex-tests/folder"\nversion = "1.0.0"\ndescription = "A method folder"\n'+ 'main_pipe = "extract"\n\n[exports.folder_steps]\npipes = ["extract"]\n'+ ),+ "bundle.mthds": entry_bundle_text(domain="folder_report", pipe_code="write_report", main_pipe="write_report"),+ "steps/extract.mthds": entry_bundle_text(domain="folder_steps", pipe_code="extract", main_pipe=None),+ }+ case MethodFolderShape.ONE_DECLARED_MAIN_PIPE:+ return {+ "bundle.mthds": entry_bundle_text(domain="folder_steps", pipe_code="extract", main_pipe=None),+ "report.mthds": entry_bundle_text(domain="folder_report", pipe_code="write_report", main_pipe="write_report"),+ }+ case MethodFolderShape.SEVERAL_MAIN_PIPES:+ return {+ "a.mthds": entry_bundle_text(domain="folder_a", pipe_code="first", main_pipe="first"),+ "b.mthds": entry_bundle_text(domain="folder_b", pipe_code="second", main_pipe="second"),+ }+ case MethodFolderShape.NO_MAIN_PIPE:+ return {+ "a.mthds": entry_bundle_text(domain="folder_a", pipe_code="first", main_pipe=None),+ "b.mthds": entry_bundle_text(domain="folder_b", pipe_code="second", main_pipe=None),+ }++ @property+ def entry(self) -> FolderEntry | None:+ """Where the entry rule starts the folder, or None when it refuses it."""+ match self:+ case MethodFolderShape.MANIFEST_MAIN_PIPE:+ return FolderEntry(tree_path="steps/extract.mthds", pipe_ref="folder_steps.extract")+ case MethodFolderShape.ONE_DECLARED_MAIN_PIPE:+ return FolderEntry(tree_path="report.mthds", pipe_ref="folder_report.write_report")+ case MethodFolderShape.SEVERAL_MAIN_PIPES | MethodFolderShape.NO_MAIN_PIPE:+ return None++ @property+ def refusal(self) -> str | None:+ """What the refusal of the folder says, or None when the entry rule starts it."""+ match self:+ case MethodFolderShape.MANIFEST_MAIN_PIPE | MethodFolderShape.ONE_DECLARED_MAIN_PIPE:+ return None+ case MethodFolderShape.SEVERAL_MAIN_PIPES:+ return "several of its bundles declare a main_pipe: 'a.mthds' declares 'first', 'b.mthds' declares 'second'"+ case MethodFolderShape.NO_MAIN_PIPE:+ return "none of its bundles declares a main_pipe ('a.mthds', 'b.mthds')"+++#: A pipe a test names with `--pipe` in a folder of several main pipes, and the bundle defining it.+NAMED_PIPE = FolderEntry(tree_path="b.mthds", pipe_ref="folder_b.second")+++def write_method_folder(*, directory: Path, shape: MethodFolderShape) -> Path:+ """Write a folder of this shape into `directory`, and return it."""+ for tree_path, content in shape.files.items():+ file_path = directory / tree_path+ file_path.parent.mkdir(parents=True, exist_ok=True)+ file_path.write_text(content, encoding="utf-8")+ return directorydiff --git a/tests/integration/pipelex/cli/test_build_bundle_folder.py b/tests/integration/pipelex/cli/test_build_bundle_folder.pynew file mode 100644index 000000000..d5f25aa68--- /dev/null+++ b/tests/integration/pipelex/cli/test_build_bundle_folder.py@@ -0,0 +1,89 @@+"""Pin: ``pipelex build inputs`` and ``pipelex build output`` load a method's whole folder, as ``run bundle`` loads it.++A folder's entry bundle may take a concept from a sibling bundle of its method. The build commands used to validate the+entry bundle alone, so that concept did not resolve and the command failed on a method ``run bundle`` runs. These+drive the real build cores on such a folder, through the resolution the commands make.+"""++from __future__ import annotations++import json+from typing import TYPE_CHECKING++import pytest++from pipelex.cli.commands.build.inputs._inputs_core import _generate_inputs_core # pyright: ignore[reportPrivateUsage]+from pipelex.cli.commands.build.output._output_core import _generate_output_core # pyright: ignore[reportPrivateUsage]+from pipelex.cli.commands.bundle_path_resolver import resolve_build_bundle_target+from pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormat++if TYPE_CHECKING:+ from pathlib import Path++_CONCEPTS_MTHDS = """domain = "pantry_concepts"+description = "What a pantry holds"++[concept.ShoppingList]+description = "The groceries to buy this week"++[concept.Recipe]+description = "A recipe to cook from the pantry"+"""++_ENTRY_MTHDS = """domain = "pantry_cooking"+description = "Cook from what the pantry holds"+main_pipe = "plan_recipe"++[pipe.plan_recipe]+type = "PipeLLM"+description = "Plan a recipe from a shopping list"+inputs = { shopping_list = "pantry_concepts.ShoppingList" }+output = "pantry_concepts.Recipe"+prompt = "Plan a recipe from this shopping list: $shopping_list"+"""++_HINT = " To use a bundle, pass a .mthds file or directory"+++def _write_method_folder(*, directory: Path) -> Path:+ directory.mkdir(parents=True)+ (directory / "concepts.mthds").write_text(_CONCEPTS_MTHDS, encoding="utf-8")+ (directory / "cooking.mthds").write_text(_ENTRY_MTHDS, encoding="utf-8")+ return directory++[email protected](loop_scope="class")+class TestBuildBundleFolder:+ async def test_build_inputs_resolves_a_concept_the_entry_takes_from_a_sibling_bundle(self, tmp_path: Path) -> None:+ method_dir = _write_method_folder(directory=tmp_path / "pantry")+ target = resolve_build_bundle_target(+ path=str(method_dir), library_dir=None, pipe_override=None, command="build inputs", not_a_bundle_hint=_HINT+ )++ await _generate_inputs_core(+ pipe_code=target.pipe_code,+ bundle_path=target.bundle_path,+ default_output_dir=target.default_output_dir,+ library_dir=target.library_dir,+ )++ inputs = json.loads((method_dir / "inputs.json").read_text(encoding="utf-8"))+ assert list(inputs) == ["shopping_list"]++ async def test_build_output_resolves_a_concept_the_entry_takes_from_a_sibling_bundle(self, tmp_path: Path) -> None:+ method_dir = _write_method_folder(directory=tmp_path / "pantry")+ target = resolve_build_bundle_target(+ path=str(method_dir), library_dir=None, pipe_override=None, command="build output", not_a_bundle_hint=_HINT+ )+ output_path = tmp_path / "output.json"++ await _generate_output_core(+ pipe_code=target.pipe_code,+ bundle_path=target.bundle_path,+ output_path=output_path,+ default_output_dir=target.default_output_dir,+ output_format=ConceptRepresentationFormat.JSON,+ library_dir=target.library_dir,+ )++ assert output_path.is_file()diff --git a/tests/integration/pipelex/cli/test_fix_bundle_human.py b/tests/integration/pipelex/cli/test_fix_bundle_human.pyindex 9cd87377d..29dd72592 100644--- a/tests/integration/pipelex/cli/test_fix_bundle_human.py+++ b/tests/integration/pipelex/cli/test_fix_bundle_human.py@@ -93,6 +93,39 @@ prompt = "Say hi to $name""""+_ROOT_MANIFEST = """[package]+address = "github.com/pipelex-tests/human-fix-tree"+version = "1.0.0"+description = "A method whose tree is rooted above the folder a fix is handed"+"""++_VALID_SUB_MTHDS = """domain = "human_fix_sub"+main_pipe = "summarize"++[pipe.summarize]+type = "PipeLLM"+description = "Summarize a topic."+inputs = { topic = "Text" }+output = "Text"+prompt = "Summarize $topic"+"""+++def _write_tree_rooted_above(*, directory: Path) -> tuple[Path, Path]:+ """A method tree rooted at a `METHODS.toml`, whose fixable bundle is a sibling of the subfolder a fix is handed.++ Returns:+ The subfolder, and the fixable sibling bundle.+ """+ sub_dir = directory / "sub"+ sub_dir.mkdir(parents=True)+ (directory / "METHODS.toml").write_text(_ROOT_MANIFEST, encoding="utf-8")+ sibling_path = directory / "ideas.mthds"+ sibling_path.write_text(_FIXABLE_SEQUENCE_MTHDS, encoding="utf-8")+ (sub_dir / "summary.mthds").write_text(_VALID_SUB_MTHDS, encoding="utf-8")+ return sub_dir, sibling_path++def _pipes(bundle_path: Path) -> dict[str, Any]:parsed = tomlkit.loads(bundle_path.read_text(encoding="utf-8")).unwrap()return cast("dict[str, Any]", parsed["pipe"])@@ -356,3 +389,51 @@ class TestFixBundleHuman:output = console.export_text()assert "✅ Bundle fixed — valid" in outputassert _pipes(bundle_path)["list_ideas"]["output"] == "Idea[]"++ def test_fixing_a_subfolder_fixes_a_sibling_bundle_of_its_tree(+ self,+ tmp_path: Path,+ mocker: MockerFixture,+ console: Console,+ load_empty_library: Callable[[], str],+ ) -> None:+ """The folder's tree is rooted at the `METHODS.toml` above it, so the fix may write any bundle of it."""+ load_empty_library()+ self._patch_setup(mocker)+ sub_dir, sibling_path = _write_tree_rooted_above(directory=tmp_path / "method")++ fix_bundle_cmd(path=str(sub_dir))++ output = console.export_text()+ assert "✅ Bundle fixed — valid" in output+ assert f"Bundle: {sub_dir}" in output+ assert "outside write scope" not in output+ assert _pipes(sibling_path)["list_ideas"]["output"] == "Idea[]"++ def test_diff_preview_of_a_subfolder_gives_the_verdict_the_real_fix_gives(+ self,+ tmp_path: Path,+ mocker: MockerFixture,+ console: Console,+ load_empty_library: Callable[[], str],+ ) -> None:+ """The preview mirrors the tree's root, manifest and siblings included, so it judges the method the real fix judges."""+ load_empty_library()+ self._patch_setup(mocker)+ sub_dir, sibling_path = _write_tree_rooted_above(directory=tmp_path / "method")+ original_bytes = sibling_path.read_bytes()++ fix_bundle_cmd(path=str(sub_dir), diff=True)++ assert sibling_path.read_bytes() == original_bytes+ output = console.export_text()+ assert "✅ Fix preview — these fixes would make the bundle valid" in output+ assert f"--- {sibling_path.resolve()}" in output+ assert '+output = "Idea[]"' in output+ assert f"- {sibling_path.resolve()}" in output+ assert "pipelex-fix-preview-" not in output++ fix_bundle_cmd(path=str(sub_dir))++ assert "✅ Bundle fixed — valid" in console.export_text()+ assert _pipes(sibling_path)["list_ideas"]["output"] == "Idea[]"diff --git a/tests/integration/pipelex/pipeline/test_validate_method_dir.py b/tests/integration/pipelex/pipeline/test_validate_method_dir.pyindex 58ccac969..6c4466554 100644--- a/tests/integration/pipelex/pipeline/test_validate_method_dir.py+++ b/tests/integration/pipelex/pipeline/test_validate_method_dir.py@@ -5,6 +5,7 @@ import pytestfrom mthds.method_tree.digest import digest_of_contentsfrom mthds.method_tree.models import MethodTree+from pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.libraries.written_trees import WRITTEN_METHOD_TREES, write_method_treefrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import validate_bundle@@ -24,6 +25,17 @@ template = "Hello $text"_SECOND_GREET_MTHDS = _GREET_MTHDS.replace(b'domain = "greeting"', b'domain = "greeting_too"')+_LIBRARY_MTHDS = """\+domain = "shouting"++[pipe.shout]+type = "PipeCompose"+description = "Shout"+inputs = { text = "Text" }+output = "Text"+template = "HEY $text"+"""+_BROKEN_PYTHON = b"def ok():\n return 1\n\n\ndef oops(:\n pass\n"@@ -84,3 +96,50 @@ class TestValidateMethodDir:report = await validate_bundles_in_process(method_dir=method_dir, library_dirs_are_callers=True)assert report.graph_spec is None++ async def test_the_callers_library_loads_beside_the_folder_while_only_the_folders_pipes_are_judged(self, tmp_path: Path) -> None:+ """A command run over the caller's own disk: the ``-L`` directories load with the method, but are not the method."""+ method_dir = tmp_path / "method"+ method_dir.mkdir()+ (method_dir / "greet.mthds").write_bytes(_GREET_MTHDS)+ library_dir = tmp_path / "library"+ library_dir.mkdir()+ (library_dir / "shout.mthds").write_text(_LIBRARY_MTHDS, encoding="utf-8")++ result = await validate_bundle(method_dir=method_dir, library_dirs=[method_dir, library_dir], library_dirs_are_callers=True)++ assert [pipe.code for pipe in result.pipes] == ["greet"]+ assert [Path(blueprint.source or "") for blueprint in result.blueprints] == [method_dir / "greet.mthds"]++ @pytest.mark.parametrize("with_library_dir", [False, True], ids=["alone", "beside_a_library_dir"])+ async def test_a_nested_packages_pipes_load_but_are_never_judged_whatever_loads_beside_the_method(+ self, tmp_path: Path, with_library_dir: bool+ ) -> None:+ """One rule for which pipes are judged: the tree's own, whether or not ``-L`` directories load beside it."""+ method_dir = tmp_path / "method"+ nested_dir = method_dir / "vendored"+ nested_dir.mkdir(parents=True)+ (method_dir / "greet.mthds").write_bytes(_GREET_MTHDS)+ (nested_dir / "METHODS.toml").write_text(+ '[package]\naddress = "github.com/pipelex-tests/vendored"\nversion = "1.0.0"\ndescription = "A package nested in the method"\n',+ encoding="utf-8",+ )+ (nested_dir / "shout.mthds").write_text(_LIBRARY_MTHDS, encoding="utf-8")+ library_dirs: list[Path] | None = None+ if with_library_dir:+ library_dir = tmp_path / "library"+ library_dir.mkdir()+ (library_dir / "whisper.mthds").write_text(_LIBRARY_MTHDS.replace('domain = "shouting"', 'domain = "whispering"'), encoding="utf-8")+ library_dirs = [method_dir, library_dir]++ result = await validate_bundle(method_dir=method_dir, library_dirs=library_dirs, library_dirs_are_callers=with_library_dir)++ assert [pipe.code for pipe in result.pipes] == ["greet"]+ assert [Path(blueprint.source or "") for blueprint in result.blueprints] == [method_dir / "greet.mthds"]++ async def test_a_hosts_library_never_loads_beside_a_method(self, tmp_path: Path) -> None:+ library_dir = tmp_path / "library"+ library_dir.mkdir()++ with pytest.raises(PipelexUnexpectedError, match="only the caller's own directories load beside method_dir"):+ await validate_bundle(method_dir=tmp_path, library_dirs=[library_dir])diff --git a/tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.py b/tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.pyindex 37ad72ec2..a48d71d7f 100644--- a/tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.py+++ b/tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.py@@ -1,18 +1,18 @@-"""Unit tests for resolve_bundle_target: shared path→bundle resolution for agent CLI bundle commands.+"""Unit tests for resolve_bundle_target: shared path resolution for the agent CLI's validate and fix bundle commands.-Pins that ``~`` is expanded for both the ``path`` argument and each ``--library-dir`` entry, so-home-relative inputs resolve like every other CLI path argument instead of being treated as literal-filenames/directories.+Pins that ``~`` is expanded for both the ``path`` argument and each ``--library-dir`` entry, and that a folder is read+whole, as its method tree, whatever its bundles declare of where the method starts."""+import jsonfrom pathlib import Pathimport pytestimport typer-from pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, set_agent_cli_error_formatfrom pipelex.cli.agent_cli.commands.bundle_path_resolver import resolve_bundle_target-from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAME+from pipelex.pipeline.exceptions import ValidateBundleError+from tests.helpers.method_folders import MethodFolderShape, write_method_folderclass TestResolveBundleTarget:@@ -22,24 +22,23 @@ class TestResolveBundleTarget:bundle_file = tmp_path / "foo.mthds"bundle_file.write_text('domain = "x"\n', encoding="utf-8")- bundle_path, library_dir = resolve_bundle_target("~/foo.mthds", library_dir=None)+ target = resolve_bundle_target("~/foo.mthds", library_dir=None)- assert bundle_path == str(bundle_file)- assert "~" not in bundle_path- assert library_dir is None+ assert target.bundle_path == bundle_file+ assert target.method_dir is None+ assert target.method_tree is None+ assert target.library_dirs is Nonedef test_directory_mode_expands_tilde_and_injects_expanded_dir(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """A ``~/pkg`` directory argument resolves its default bundle and injects the expanded dir into library_dir."""+ """A ``~/pkg`` folder resolves to the folder itself, judged whole, and its expanded path joins the library."""monkeypatch.setenv("HOME", str(tmp_path))- pkg_dir = tmp_path / "pkg"- pkg_dir.mkdir()- bundle_file = pkg_dir / DEFAULT_BUNDLE_FILE_NAME- bundle_file.write_text('domain = "x"\n', encoding="utf-8")+ pkg_dir = write_method_folder(directory=tmp_path / "pkg", shape=MethodFolderShape.ONE_DECLARED_MAIN_PIPE)- bundle_path, library_dir = resolve_bundle_target("~/pkg", library_dir=None)+ target = resolve_bundle_target("~/pkg", library_dir=None)- assert bundle_path == str(bundle_file)- assert library_dir == [str(pkg_dir)]+ assert target.bundle_path is None+ assert target.method_dir == pkg_dir+ assert target.library_dirs == [pkg_dir]def test_library_dir_entries_expand_tilde(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:"""A home-relative ``--library-dir`` entry is expanded to its absolute path in the returned list."""@@ -47,38 +46,51 @@ class TestResolveBundleTarget:bundle_file = tmp_path / "foo.mthds"bundle_file.write_text('domain = "x"\n', encoding="utf-8")- _, library_dir = resolve_bundle_target("~/foo.mthds", library_dir=["~/mylibs"])+ target = resolve_bundle_target("~/foo.mthds", library_dir=["~/mylibs"])- assert library_dir == [str(tmp_path / "mylibs")]+ assert target.library_dirs == [tmp_path / "mylibs"]- def test_ambiguous_directory_error_names_candidates_in_sorted_order(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:- """Ambiguous-directory diagnostics are stable across filesystem iteration order."""- set_agent_cli_error_format(CliOutputFormat.MARKDOWN)- try:- (tmp_path / "b.mthds").write_text('domain = "b"\n', encoding="utf-8")- (tmp_path / "a.mthds").write_text('domain = "a"\n', encoding="utf-8")+ @pytest.mark.parametrize("shape", list(MethodFolderShape))+ def test_a_folder_is_read_whole_whatever_its_main_pipes(self, tmp_path: Path, shape: MethodFolderShape) -> None:+ """No pipe to start at is needed: several main pipes, or none, are no refusal, since every bundle is judged."""+ write_method_folder(directory=tmp_path, shape=shape)- with pytest.raises(typer.Exit) as exc_info:- resolve_bundle_target(str(tmp_path), library_dir=None)- finally:- set_agent_cli_error_format(CliOutputFormat.JSON)+ target = resolve_bundle_target(str(tmp_path), library_dir=None)- assert exc_info.value.exit_code == 2- err = capsys.readouterr().err- assert "(a.mthds, b.mthds)" in err+ assert target.bundle_path is None+ assert target.method_dir == tmp_path+ assert target.method_tree is not None+ assert sorted(target.method_tree.tree_paths) == sorted(shape.files)++ @pytest.mark.parametrize("files", [{}, {".DS_Store": "", "notes.md": "# Notes\n"}], ids=["empty", "no_bundle"])+ def test_a_folder_holding_no_bundle_exits_2(self, tmp_path: Path, capsys: pytest.CaptureFixture[str], files: dict[str, str]) -> None:+ for name, content in files.items():+ (tmp_path / name).write_text(content, encoding="utf-8")- def test_directory_refuses_auto_detected_symlink(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:- """Directory mode must not turn an external symlink target into an implicitly writable entry file."""+ with pytest.raises(typer.Exit) as exc_info:+ resolve_bundle_target(str(tmp_path), library_dir=None)++ assert exc_info.value.exit_code == 2+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "EmptyMethodTreeError"+ assert envelope["error_domain"] == "input"+ assert envelope["message"] == f"The folder '{tmp_path}' holds no .mthds bundle."++ def test_a_folder_whose_tree_is_refused_raises_the_verdict_for_the_command(self, tmp_path: Path) -> None:+ """A symbolic link in the tree is the invalid verdict, which each command renders as its surface does."""+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.ONE_DECLARED_MAIN_PIPE)outside_bundle = tmp_path.parent / f"{tmp_path.name}-outside.mthds"outside_bundle.write_text('domain = "outside"\n', encoding="utf-8")- (tmp_path / DEFAULT_BUNDLE_FILE_NAME).symlink_to(outside_bundle)+ (tmp_path / "linked.mthds").symlink_to(outside_bundle)++ with pytest.raises(ValidateBundleError, match=r"linked\.mthds"):+ resolve_bundle_target(str(tmp_path), library_dir=None)- set_agent_cli_error_format(CliOutputFormat.MARKDOWN)- try:- with pytest.raises(typer.Exit) as exc_info:- resolve_bundle_target(str(tmp_path), library_dir=None)- finally:- set_agent_cli_error_format(CliOutputFormat.JSON)+ def test_a_path_that_is_no_bundle_exits_2(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ with pytest.raises(typer.Exit) as exc_info:+ resolve_bundle_target(str(tmp_path / "nope.txt"), library_dir=None)assert exc_info.value.exit_code == 2- assert "Refusing to auto-detect symlinked bundle" in capsys.readouterr().err+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "ArgumentError"+ assert "is not a .mthds file or directory" in envelope["message"]diff --git a/tests/unit/pipelex/cli/agent_cli/test_fix_format.py b/tests/unit/pipelex/cli/agent_cli/test_fix_format.pyindex 03f94e38d..bdba700e7 100644--- a/tests/unit/pipelex/cli/agent_cli/test_fix_format.py+++ b/tests/unit/pipelex/cli/agent_cli/test_fix_format.py@@ -21,6 +21,7 @@ if TYPE_CHECKING:from pytest_mock import MockerFixtureFIX_BUNDLE_MODULE = "pipelex.cli.agent_cli.commands.fix.bundle_cmd"+JUDGED_TARGET_MODULE = "pipelex.cli.judged_target"def _applied_fix(source: str) -> SuggestedFix:@@ -49,7 +50,7 @@ def _patch_command() -> None:mocker.patch(f"{FIX_BUNDLE_MODULE}.make_pipelex_for_agent_cli")mocker.patch(f"{FIX_BUNDLE_MODULE}.Pipelex.teardown_if_needed")- mocker.patch(f"{FIX_BUNDLE_MODULE}.fix_bundle_file", new=mocker.AsyncMock(return_value=result))+ mocker.patch(f"{JUDGED_TARGET_MODULE}.fix_bundle_file", new=mocker.AsyncMock(return_value=result))class TestFixFormat:diff --git a/tests/unit/pipelex/cli/agent_cli/test_folder_entry_commands.py b/tests/unit/pipelex/cli/agent_cli/test_folder_entry_commands.pynew file mode 100644index 000000000..710ce5bf3--- /dev/null+++ b/tests/unit/pipelex/cli/agent_cli/test_folder_entry_commands.py@@ -0,0 +1,291 @@+"""The agent commands taking a method's folder: `validate` and `fix` judge it whole, `inputs` acts on the pipe `run` starts at."""++from __future__ import annotations++import json+from typing import TYPE_CHECKING, Any, NamedTuple++import pytest+import typer++from pipelex.base_exceptions import PipelexConfigError+from pipelex.cli.agent_cli.commands.agent_cli_factory import AGENT_INIT_FAILURE_HINT+from pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat+from pipelex.cli.agent_cli.commands.fix.bundle_cmd import fix_bundle_cmd+from pipelex.cli.agent_cli.commands.inputs.bundle_cmd import inputs_bundle_cmd+from pipelex.cli.agent_cli.commands.run.bundle_cmd import run_bundle_cmd+from pipelex.cli.agent_cli.commands.validate.bundle_cmd import validate_bundle_cmd+from pipelex.cli.bundle_target_resolution import resolve_method_folder_run+from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.fixes.fix_loop import FixBundleResult+from tests.helpers.method_folders import NAMED_PIPE, MethodFolderShape, write_method_folder++if TYPE_CHECKING:+ from pathlib import Path++ from pytest_mock import MockerFixture, MockType++VALIDATE_MODULE = "pipelex.cli.agent_cli.commands.validate.bundle_cmd"+FIX_MODULE = "pipelex.cli.agent_cli.commands.fix.bundle_cmd"+INPUTS_MODULE = "pipelex.cli.agent_cli.commands.inputs.bundle_cmd"+JUDGED_TARGET_MODULE = "pipelex.cli.judged_target"++_RESOLVED_SHAPES = [MethodFolderShape.MANIFEST_MAIN_PIPE, MethodFolderShape.ONE_DECLARED_MAIN_PIPE]+_UNDECIDED_SHAPES = [MethodFolderShape.SEVERAL_MAIN_PIPES, MethodFolderShape.NO_MAIN_PIPE]+_VALID_RESULT: dict[str, Any] = {"success": True, "is_valid": True, "is_runnable": True, "validated_pipes": []}+++def _run_refusal(*, directory: Path) -> str:+ """The message `run bundle` refuses the folder with."""+ with pytest.raises(ValidateBundleError) as exc_info:+ resolve_method_folder_run(directory=directory, pipe_override=None)+ return exc_info.value.message+++class _ValidateMocks(NamedTuple):+ """The validate cores and graph helpers a test reads the calls of."""++ whole: MockType+ sliced: MockType+ folder: MockType+ graph: MockType+ view: MockType+ success: MockType+++def _invoke_validate_or_fix_for_json(*, command: str, path: Path) -> None:+ match command:+ case "validate":+ validate_bundle_cmd(path=str(path), error_format=CliOutputFormat.JSON)+ case "fix":+ fix_bundle_cmd(path=str(path), error_format=CliOutputFormat.JSON)+ case _:+ msg = f"Unknown command '{command}'"+ raise ValueError(msg)+++def _invoke_pre_boot_command(*, command: str, path: Path) -> None:+ """Invoke a command taking a method's folder, its errors in JSON."""+ match command:+ case "validate" | "fix":+ _invoke_validate_or_fix_for_json(command=command, path=path)+ case "inputs":+ inputs_bundle_cmd(path=str(path))+ case "run":+ run_bundle_cmd(path=str(path), error_format=CliOutputFormat.JSON)+ case _:+ msg = f"Unknown command '{command}'"+ raise ValueError(msg)+++def _write_folder_with_a_refused_tree(*, directory: Path) -> None:+ """A method folder whose tree is refused when it is listed: a symbolic link among its files."""+ write_method_folder(directory=directory, shape=MethodFolderShape.ONE_DECLARED_MAIN_PIPE)+ outside_bundle = directory.parent / f"{directory.name}-outside.mthds"+ outside_bundle.write_text('domain = "outside"\n', encoding="utf-8")+ (directory / "linked.mthds").symlink_to(outside_bundle)+++def _patch_validate(mocker: MockerFixture) -> _ValidateMocks:+ """Stub what `validate bundle` boots and runs; return its cores, its graph helpers and its success emitter."""+ mocker.patch(f"{VALIDATE_MODULE}.make_pipelex_for_agent_cli")+ mocker.patch(f"{VALIDATE_MODULE}.Pipelex.teardown_if_needed")+ return _ValidateMocks(+ whole=mocker.patch(f"{VALIDATE_MODULE}.validate_bundle_core", new=mocker.AsyncMock(return_value=dict(_VALID_RESULT))),+ sliced=mocker.patch(f"{VALIDATE_MODULE}.validate_pipe_in_bundle_core", new=mocker.AsyncMock(return_value=dict(_VALID_RESULT))),+ folder=mocker.patch(f"{VALIDATE_MODULE}.validate_method_folder_core", new=mocker.AsyncMock(return_value=dict(_VALID_RESULT))),+ graph=mocker.patch(f"{VALIDATE_MODULE}.generate_graph_for_bundle", new=mocker.AsyncMock(return_value={"graph_files": {}})),+ view=mocker.patch(f"{VALIDATE_MODULE}.generate_view_for_bundle", new=mocker.AsyncMock(return_value={"graphspec": {}})),+ success=mocker.patch(f"{VALIDATE_MODULE}.agent_success_formatted"),+ )+++def _patch_fix(mocker: MockerFixture) -> MockType:+ mocker.patch(f"{FIX_MODULE}.make_pipelex_for_agent_cli")+ mocker.patch(f"{FIX_MODULE}.Pipelex.teardown_if_needed")+ mocker.patch(f"{FIX_MODULE}.agent_success_formatted")+ result = FixBundleResult(is_valid=True, iterations=0, fixes_applied=[], remaining_errors=[], is_runnable=True)+ mocker.patch(f"{JUDGED_TARGET_MODULE}.fix_bundle_file", new=mocker.AsyncMock(return_value=result))+ mock_fix: MockType = mocker.patch(f"{JUDGED_TARGET_MODULE}.fix_method_folder", new=mocker.AsyncMock(return_value=result))+ return mock_fix+++def _patch_inputs(mocker: MockerFixture) -> MockType:+ mocker.patch(f"{INPUTS_MODULE}.make_pipelex_for_agent_cli")+ mocker.patch(f"{INPUTS_MODULE}.Pipelex.teardown_if_needed")+ mocker.patch(f"{INPUTS_MODULE}.emit_inputs_result")+ mock_inputs: MockType = mocker.patch(f"{INPUTS_MODULE}.inputs_core", new=mocker.AsyncMock(return_value={"success": True}))+ return mock_inputs+++class TestAgentFolderEntryCommands:+ @pytest.mark.parametrize("shape", list(MethodFolderShape))+ def test_validate_judges_the_whole_method_whatever_its_main_pipes(self, mocker: MockerFixture, tmp_path: Path, shape: MethodFolderShape) -> None:+ """Every bundle of the folder is judged, as the protocol's validation judges a method, so no pipe to start at is needed."""+ mocks = _patch_validate(mocker)+ write_method_folder(directory=tmp_path, shape=shape)++ validate_bundle_cmd(path=str(tmp_path))++ kwargs = mocks.folder.call_args.kwargs+ assert kwargs["method_dir"] == tmp_path+ assert kwargs["library_dirs"] == [tmp_path]+ assert kwargs["pipe_code"] is None+ mocks.whole.assert_not_called()+ mocks.sliced.assert_not_called()++ def test_validate_naming_its_pipe_narrows_the_dry_run_of_the_whole_method(self, mocker: MockerFixture, tmp_path: Path) -> None:+ mocks = _patch_validate(mocker)+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.SEVERAL_MAIN_PIPES)++ validate_bundle_cmd(path=str(tmp_path), pipe=NAMED_PIPE.pipe_ref)++ assert mocks.folder.call_args.kwargs["method_dir"] == tmp_path+ assert mocks.folder.call_args.kwargs["pipe_code"] == NAMED_PIPE.pipe_ref++ @pytest.mark.parametrize("shape", _RESOLVED_SHAPES)+ def test_validate_draws_the_pipe_the_method_starts_at(self, mocker: MockerFixture, tmp_path: Path, shape: MethodFolderShape) -> None:+ """The view is drawn from the method's main pipe, in the bundle defining it, which need not declare it as its own."""+ mocks = _patch_validate(mocker)+ write_method_folder(directory=tmp_path, shape=shape)+ assert shape.entry is not None++ validate_bundle_cmd(path=str(tmp_path), graph=True, view=True)++ for drawn in (mocks.graph, mocks.view):+ assert drawn.call_args.kwargs["bundle_path"] == tmp_path / shape.entry.tree_path+ assert drawn.call_args.kwargs["pipe_code"] == shape.entry.pipe_ref+ assert "graph_unavailable" not in mocks.success.call_args.args[0]++ @pytest.mark.parametrize("shape", _UNDECIDED_SHAPES)+ def test_validate_says_plainly_when_the_method_has_no_pipe_to_draw(self, mocker: MockerFixture, tmp_path: Path, shape: MethodFolderShape) -> None:+ """The validation stands: the result says why no graph was drawn, and the command exits 0."""+ mocks = _patch_validate(mocker)+ write_method_folder(directory=tmp_path, shape=shape)+ assert shape.refusal is not None++ validate_bundle_cmd(path=str(tmp_path), graph=True, view=True)++ mocks.graph.assert_not_called()+ mocks.view.assert_not_called()+ result = mocks.success.call_args.args[0]+ assert result["is_valid"] is True+ assert result["graph_unavailable"].startswith("No graph was drawn, since a graph is drawn from one pipe: ")+ assert shape.refusal in result["graph_unavailable"]++ @pytest.mark.parametrize("pipe", [NAMED_PIPE.pipe_ref, "second"])+ def test_validate_draws_the_pipe_named_in_the_bundle_defining_it(self, mocker: MockerFixture, tmp_path: Path, pipe: str) -> None:+ mocks = _patch_validate(mocker)+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.SEVERAL_MAIN_PIPES)++ validate_bundle_cmd(path=str(tmp_path), pipe=pipe, view=True)++ assert mocks.view.call_args.kwargs["bundle_path"] == tmp_path / NAMED_PIPE.tree_path+ assert mocks.view.call_args.kwargs["pipe_code"] == NAMED_PIPE.pipe_ref++ @pytest.mark.parametrize("shape", list(MethodFolderShape))+ def test_fix_patches_the_whole_method_validate_judges(self, mocker: MockerFixture, tmp_path: Path, shape: MethodFolderShape) -> None:+ mock_fix = _patch_fix(mocker)+ write_method_folder(directory=tmp_path, shape=shape)++ fix_bundle_cmd(path=str(tmp_path))++ assert mock_fix.call_args.kwargs["method_dir"] == tmp_path+ assert mock_fix.call_args.kwargs["library_dirs"] == [tmp_path]++ def test_fix_reports_a_folder_whose_tree_is_refused_in_the_fix_envelope(+ self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ """The documented FixBundleError envelope, as a fix that could not be made, never a bare refusal."""+ mock_fix = _patch_fix(mocker)+ _write_folder_with_a_refused_tree(directory=tmp_path)++ with pytest.raises(typer.Exit) as exc_info:+ fix_bundle_cmd(path=str(tmp_path), error_format=CliOutputFormat.JSON)++ assert exc_info.value.exit_code == 1+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "FixBundleError"+ assert envelope["is_valid"] is False+ assert envelope["bundle_path"] == str(tmp_path.resolve())+ assert envelope["iterations"] == 0+ assert envelope["fixes_applied"] == []+ assert envelope["files_written"] == []+ assert envelope["remaining_errors"]+ assert any("linked.mthds" in item["message"] for item in envelope["remaining_errors"])+ mock_fix.assert_not_called()++ @pytest.mark.parametrize("command", ["validate", "fix", "inputs", "run"])+ def test_a_configuration_that_does_not_validate_before_the_boot_is_the_failed_boot_envelope(+ self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str], command: str+ ) -> None:+ """Listing the tree reads its limits from the configuration: a refusal there is the envelope a failed boot gives."""+ mocker.patch("pipelex.libraries.method_trees.local_tree_limits", side_effect=PipelexConfigError("the configuration is out of date"))+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.ONE_DECLARED_MAIN_PIPE)++ with pytest.raises(typer.Exit) as exc_info:+ _invoke_pre_boot_command(command=command, path=tmp_path)++ assert exc_info.value.exit_code == 1+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "PipelexConfigError"+ assert envelope["message"] == "Pipelex initialization failed: the configuration is out of date"+ assert envelope["hint"] == AGENT_INIT_FAILURE_HINT++ @pytest.mark.parametrize("command", ["validate", "fix"])+ def test_validate_and_fix_refuse_a_folder_holding_no_bundle_with_no_verdict(+ self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str], command: str+ ) -> None:+ mocks = _patch_validate(mocker)+ mock_fix = _patch_fix(mocker)++ with pytest.raises(typer.Exit) as exc_info:+ _invoke_validate_or_fix_for_json(command=command, path=tmp_path)++ assert exc_info.value.exit_code == 2+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "EmptyMethodTreeError"+ assert envelope["message"] == f"The folder '{tmp_path}' holds no .mthds bundle."+ mocks.folder.assert_not_called()+ mock_fix.assert_not_called()++ @pytest.mark.parametrize("shape", _RESOLVED_SHAPES)+ def test_inputs_is_for_the_pipe_the_method_starts_at(self, mocker: MockerFixture, tmp_path: Path, shape: MethodFolderShape) -> None:+ mock_inputs = _patch_inputs(mocker)+ write_method_folder(directory=tmp_path, shape=shape)+ assert shape.entry is not None++ inputs_bundle_cmd(path=str(tmp_path))++ kwargs = mock_inputs.call_args.kwargs+ assert kwargs["pipe_code"] == shape.entry.pipe_ref+ assert kwargs["bundle_path"] == (tmp_path / shape.entry.tree_path).resolve()+ assert kwargs["library_dirs"] == [tmp_path]++ def test_inputs_naming_its_pipe_loads_the_folder_as_its_library(self, mocker: MockerFixture, tmp_path: Path) -> None:+ """With `--pipe`, several main pipes are no ambiguity, and the pipe is looked up in the method, as a run does."""+ mock_inputs = _patch_inputs(mocker)+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.SEVERAL_MAIN_PIPES)++ inputs_bundle_cmd(path=str(tmp_path), pipe=NAMED_PIPE.pipe_ref)++ kwargs = mock_inputs.call_args.kwargs+ assert kwargs["pipe_code"] == NAMED_PIPE.pipe_ref+ assert kwargs["bundle_path"] is None+ assert kwargs["library_dirs"] == [tmp_path]++ @pytest.mark.parametrize("shape", _UNDECIDED_SHAPES)+ def test_inputs_refuses_a_folder_with_no_single_main_pipe(+ self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str], shape: MethodFolderShape+ ) -> None:+ mock_inputs = _patch_inputs(mocker)+ write_method_folder(directory=tmp_path, shape=shape)++ with pytest.raises(typer.Exit) as exc_info:+ inputs_bundle_cmd(path=str(tmp_path))++ assert exc_info.value.exit_code == 1+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "MethodEntryError"+ assert envelope["message"] == _run_refusal(directory=tmp_path)+ mock_inputs.assert_not_called()diff --git a/tests/unit/pipelex/cli/commands/build/test_inputs_core.py b/tests/unit/pipelex/cli/commands/build/test_inputs_core.pyindex 97c827665..0b71db64a 100644--- a/tests/unit/pipelex/cli/commands/build/test_inputs_core.py+++ b/tests/unit/pipelex/cli/commands/build/test_inputs_core.py@@ -34,6 +34,7 @@ class TestGenerateInputsCore:mocker.patch(f"{MODULE}.resolve_library_dirs", return_value=([], "defaults"))validate_result = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe="bundle_main")])return {+ "library_manager": library_manager,"validate_bundle": mocker.patch(f"{MODULE}.validate_bundle", new=mocker.AsyncMock(return_value=validate_result)),"get_required_entry_pipe": mocker.patch(f"{MODULE}.get_required_entry_pipe", return_value=SimpleNamespace(code="bundle_main")),"render_inputs": mocker.patch(f"{MODULE}.render_inputs", return_value='{\n "topic": "your topic"\n}'),@@ -57,6 +58,15 @@ class TestGenerateInputsCore:core_mocks["get_required_entry_pipe"].assert_called_once_with(pipe_code="my_pipe")+ def test_a_bundle_loads_with_its_whole_method_folder(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:+ """The entry bundle of a folder loads with the folder, as `run bundle` loads it, so a sibling's concept resolves."""+ bundle_path = tmp_path / "entry.mthds"++ asyncio.run(_generate_inputs_core(pipe_code="demo.bundle_main", bundle_path=bundle_path, library_dir=[str(tmp_path)]))++ core_mocks["validate_bundle"].assert_awaited_once_with(mthds_file_path=bundle_path, library_dirs=[tmp_path])+ core_mocks["library_manager"].load_libraries.assert_not_called()+def test_bundle_without_main_pipe_exits(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:"""A bundle without main_pipe and no --pipe is an error."""core_mocks["validate_bundle"].return_value = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe=None)])diff --git a/tests/unit/pipelex/cli/commands/build/test_output_core.py b/tests/unit/pipelex/cli/commands/build/test_output_core.pyindex 33416f442..9eeb7ef1a 100644--- a/tests/unit/pipelex/cli/commands/build/test_output_core.py+++ b/tests/unit/pipelex/cli/commands/build/test_output_core.py@@ -34,6 +34,7 @@ class TestGenerateOutputCore:mocker.patch(f"{MODULE}.resolve_library_dirs", return_value=([], "defaults"))validate_result = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe="bundle_main")])return {+ "library_manager": library_manager,"validate_bundle": mocker.patch(f"{MODULE}.validate_bundle", new=mocker.AsyncMock(return_value=validate_result)),"get_required_entry_pipe": mocker.patch(f"{MODULE}.get_required_entry_pipe", return_value=SimpleNamespace(code="bundle_main")),"render_output": mocker.patch(f"{MODULE}.render_output", return_value='{"answer": 42}'),@@ -77,6 +78,15 @@ class TestGenerateOutputCore:assert target_path.read_text(encoding="utf-8") == '{"answer": 42}'+ def test_a_bundle_loads_with_its_whole_method_folder(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:+ """The entry bundle of a folder loads with the folder, as `run bundle` loads it, so a sibling's concept resolves."""+ bundle_path = tmp_path / "entry.mthds"++ asyncio.run(_generate_output_core(pipe_code="demo.bundle_main", bundle_path=bundle_path, library_dir=[str(tmp_path)]))++ core_mocks["validate_bundle"].assert_awaited_once_with(mthds_file_path=bundle_path, library_dirs=[tmp_path])+ core_mocks["library_manager"].load_libraries.assert_not_called()+def test_bundle_without_main_pipe_exits(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:"""A bundle without main_pipe and no --pipe is an error."""core_mocks["validate_bundle"].return_value = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe=None)])diff --git a/tests/unit/pipelex/cli/commands/fix/test_diff_sandbox.py b/tests/unit/pipelex/cli/commands/fix/test_diff_sandbox.pyindex 636b24189..a6d9baca9 100644--- a/tests/unit/pipelex/cli/commands/fix/test_diff_sandbox.py+++ b/tests/unit/pipelex/cli/commands/fix/test_diff_sandbox.py@@ -4,7 +4,10 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING-from pipelex.cli.commands.fix._diff_sandbox import mirror_bundle_for_preview+import pytest++from pipelex.base_exceptions import PipelexUnexpectedError+from pipelex.cli.commands.fix._diff_sandbox import PreviewSandbox, mirror_bundle_for_previewif TYPE_CHECKING:from pathlib import Path@@ -12,6 +15,11 @@ if TYPE_CHECKING:from pytest_mock import MockerFixture+def _entry_copy(sandbox: PreviewSandbox) -> Path:+ assert sandbox.entry_path is not None+ return sandbox.entry_path++class TestDiffSandbox:def _sandbox_root(self, tmp_path: Path) -> Path:sandbox_root = tmp_path / "sandbox"@@ -24,11 +32,11 @@ class TestDiffSandbox:sandbox = mirror_bundle_for_preview(entry, library_dirs=None, sandbox_root=self._sandbox_root(tmp_path))- assert sandbox.entry_path != entry.resolve()- assert sandbox.entry_path.read_text(encoding="utf-8") == 'domain = "demo"\n'+ assert _entry_copy(sandbox) != entry.resolve()+ assert _entry_copy(sandbox).read_text(encoding="utf-8") == 'domain = "demo"\n'assert sandbox.library_dirs == []assert sandbox.writable_library_dirs == []- assert sandbox.to_original(str(sandbox.entry_path)) == str(entry.resolve())+ assert sandbox.to_original(str(_entry_copy(sandbox))) == str(entry.resolve())def test_explicit_empty_dirs_stay_empty(self, tmp_path: Path) -> None:entry = tmp_path / "bundle.mthds"@@ -98,9 +106,9 @@ class TestDiffSandbox:sandbox = mirror_bundle_for_preview(entry, library_dirs=[libs_dir], sandbox_root=self._sandbox_root(tmp_path))assert sandbox.library_dirs is not None- assert sandbox.entry_path.read_text(encoding="utf-8") == 'domain = "demo"\n'- assert not sandbox.entry_path.is_relative_to(sandbox.library_dirs[0])- assert sandbox.to_original(str(sandbox.entry_path)) == str(entry.resolve())+ assert _entry_copy(sandbox).read_text(encoding="utf-8") == 'domain = "demo"\n'+ assert not _entry_copy(sandbox).is_relative_to(sandbox.library_dirs[0])+ assert sandbox.to_original(str(_entry_copy(sandbox))) == str(entry.resolve())assert sandbox.to_original(str(sandbox.library_dirs[0] / "helper.mthds")) == str((libs_dir / "helper.mthds").resolve())def test_missing_library_dir_mirrors_as_empty_copy_without_crashing(self, tmp_path: Path) -> None:@@ -117,7 +125,7 @@ class TestDiffSandbox:assert copy_dir.is_dir()assert list(copy_dir.iterdir()) == []# The entry lives outside the missing dir, so it gets a standalone copy.- assert sandbox.entry_path.read_text(encoding="utf-8") == 'domain = "demo"\n'+ assert _entry_copy(sandbox).read_text(encoding="utf-8") == 'domain = "demo"\n'assert sandbox.to_original(str(copy_dir / "would_be.mthds")) == str((missing_dir / "would_be.mthds").resolve())def test_paths_outside_the_sandbox_pass_through(self, tmp_path: Path) -> None:@@ -170,3 +178,23 @@ class TestDiffSandbox:copied_link = sandbox.library_dirs[0] / "linked"assert copied_link.is_symlink()assert copied_link.readlink() == external_dir++ def test_a_method_folder_mirrors_with_no_entry_and_finds_its_copy(self, tmp_path: Path) -> None:+ """A folder judged whole has no entry file: it is mirrored as one of the library dirs, found again by ``to_copy``."""+ method_dir = tmp_path / "method"+ (method_dir / "steps").mkdir(parents=True)+ (method_dir / "a.mthds").write_text('domain = "first"\n', encoding="utf-8")+ (method_dir / "steps" / "b.mthds").write_text('domain = "second"\n', encoding="utf-8")++ sandbox = mirror_bundle_for_preview(None, library_dirs=[method_dir], sandbox_root=self._sandbox_root(tmp_path))++ copy_dir = sandbox.to_copy(original=method_dir)+ assert sandbox.entry_path is None+ assert sandbox.entry_mapping is None+ assert sandbox.library_dirs == [copy_dir]+ assert sandbox.writable_library_dirs == [copy_dir]+ assert (copy_dir / "steps" / "b.mthds").read_text(encoding="utf-8") == 'domain = "second"\n'+ assert sandbox.to_copy(original=method_dir / "steps" / "b.mthds") == copy_dir / "steps" / "b.mthds"+ assert sandbox.to_original(str(copy_dir / "a.mthds")) == str((method_dir / "a.mthds").resolve())+ with pytest.raises(PipelexUnexpectedError, match="lies under none of the directories the preview mirrored"):+ sandbox.to_copy(original=tmp_path / "elsewhere")diff --git a/tests/unit/pipelex/cli/commands/fix/test_fix_bundle_human_format.py b/tests/unit/pipelex/cli/commands/fix/test_fix_bundle_human_format.pyindex 149350608..9eb2d1c4b 100644--- a/tests/unit/pipelex/cli/commands/fix/test_fix_bundle_human_format.py+++ b/tests/unit/pipelex/cli/commands/fix/test_fix_bundle_human_format.py@@ -27,6 +27,7 @@ if TYPE_CHECKING:from pytest_mock import MockerFixtureFIX_CORE_MODULE = "pipelex.cli.commands.fix._fix_core"+JUDGED_TARGET_MODULE = "pipelex.cli.judged_target"def _applied_fix(source: str | None) -> SuggestedFix:@@ -74,7 +75,7 @@ class TestFixBundleHumanFormat:mocker.patch(f"{FIX_CORE_MODULE}.Pipelex.teardown_if_needed")mocker.patch(f"{FIX_CORE_MODULE}.get_telemetry_manager", return_value=mocker.MagicMock())mocker.patch(f"{FIX_CORE_MODULE}.tag")- mocker.patch(f"{FIX_CORE_MODULE}.fix_bundle_file", new=mocker.AsyncMock(return_value=result))+ mocker.patch(f"{JUDGED_TARGET_MODULE}.fix_bundle_file", new=mocker.AsyncMock(return_value=result))def _bundle_file(self, tmp_path: Path) -> Path:bundle_path = tmp_path / "bundle.mthds"@@ -269,7 +270,7 @@ class TestFixBundleHumanFormat:mocker.patch(f"{FIX_CORE_MODULE}.Pipelex.teardown_if_needed")mocker.patch(f"{FIX_CORE_MODULE}.get_telemetry_manager", return_value=mocker.MagicMock())mocker.patch(f"{FIX_CORE_MODULE}.tag")- mocker.patch(f"{FIX_CORE_MODULE}.fix_bundle_file", new=mocker.AsyncMock(side_effect=fake_loop))+ mocker.patch(f"{JUDGED_TARGET_MODULE}.fix_bundle_file", new=mocker.AsyncMock(side_effect=fake_loop))with pytest.raises(typer.Exit) as exc_info:fix_bundle_cmd(path=str(bundle_path), diff=True)@@ -325,7 +326,7 @@ class TestFixBundleHumanFormat:mocker.patch(f"{FIX_CORE_MODULE}.Pipelex.teardown_if_needed")mocker.patch(f"{FIX_CORE_MODULE}.get_telemetry_manager", return_value=mocker.MagicMock())mocker.patch(f"{FIX_CORE_MODULE}.tag")- mocker.patch(f"{FIX_CORE_MODULE}.fix_bundle_file", new=mocker.AsyncMock(side_effect=FileNotFoundError("missing")))+ mocker.patch(f"{JUDGED_TARGET_MODULE}.fix_bundle_file", new=mocker.AsyncMock(side_effect=FileNotFoundError("missing")))with pytest.raises(typer.Exit) as exc_info:fix_bundle_cmd(path=str(bundle_path))@@ -340,7 +341,7 @@ class TestFixBundleHumanFormat:mocker.patch(f"{FIX_CORE_MODULE}.Pipelex.teardown_if_needed")mocker.patch(f"{FIX_CORE_MODULE}.get_telemetry_manager", return_value=mocker.MagicMock())mocker.patch(f"{FIX_CORE_MODULE}.tag")- mocker.patch(f"{FIX_CORE_MODULE}.fix_bundle_file", new=mocker.AsyncMock(side_effect=RuntimeError("boom")))+ mocker.patch(f"{JUDGED_TARGET_MODULE}.fix_bundle_file", new=mocker.AsyncMock(side_effect=RuntimeError("boom")))with pytest.raises(typer.Exit) as exc_info:fix_bundle_cmd(path=str(bundle_path))@@ -387,7 +388,7 @@ class TestFixBundleHumanFormat:mocker.patch(f"{FIX_CORE_MODULE}.Pipelex.teardown_if_needed")mocker.patch(f"{FIX_CORE_MODULE}.get_telemetry_manager", return_value=mocker.MagicMock())mocker.patch(f"{FIX_CORE_MODULE}.tag")- mocker.patch(f"{FIX_CORE_MODULE}.fix_bundle_file", new=mocker.AsyncMock(side_effect=fake_loop))+ mocker.patch(f"{JUDGED_TARGET_MODULE}.fix_bundle_file", new=mocker.AsyncMock(side_effect=fake_loop))fix_bundle_cmd(path=str(bundle_path), diff=True)@@ -403,6 +404,38 @@ class TestFixBundleHumanFormat:assert f"- {bundle_path.resolve()}" in outputassert "Files written:" not in output.replace("Files that would be written:", "")+ def test_diff_preview_of_a_subfolder_mirrors_its_tree_root(self, tmp_path: Path, mocker: MockerFixture, console: Console) -> None:+ """The preview copies the tree from its `METHODS.toml` down, and finds the folder handed over inside that copy."""+ root_dir = tmp_path / "method"+ sub_dir = root_dir / "sub"+ sub_dir.mkdir(parents=True)+ (root_dir / "METHODS.toml").write_text('[package]\naddress = "github.com/pipelex-tests/preview"\nversion = "1.0.0"\n', encoding="utf-8")+ sibling_path = root_dir / "ideas.mthds"+ sibling_path.write_text('domain = "fix_human_format"\n', encoding="utf-8")+ (sub_dir / "summary.mthds").write_text('domain = "fix_human_format_sub"\n', encoding="utf-8")+ seen: dict[str, object] = {}+ seen_library_dirs: list[list[Path]] = []++ def fake_loop(*, method_dir: Path, library_dirs: list[Path], writable_library_dirs: list[Path], **_kwargs: object) -> FixBundleResult:+ (root_copy,) = writable_library_dirs+ seen["method_dir_in_root_copy"] = method_dir == root_copy / "sub"+ seen_library_dirs.append(library_dirs)+ seen["manifest_copied"] = (root_copy / "METHODS.toml").is_file()+ seen["sibling_copied"] = (root_copy / "ideas.mthds").is_file()+ return FixBundleResult(is_valid=True, iterations=0, fixes_applied=[], remaining_errors=[], pending_signatures=[], is_runnable=True)++ self._patch_command(mocker, result=FixBundleResult(is_valid=True, iterations=0, fixes_applied=[], remaining_errors=[], is_runnable=True))+ mocker.patch(f"{JUDGED_TARGET_MODULE}.fix_method_folder", new=mocker.AsyncMock(side_effect=fake_loop))++ fix_bundle_cmd(path=str(sub_dir), diff=True)++ assert seen["method_dir_in_root_copy"] is True+ assert seen["manifest_copied"] is True+ assert seen["sibling_copied"] is True+ (library_dirs,) = seen_library_dirs+ assert [library_dir.name for library_dir in library_dirs] == ["sub"]+ assert "✅ Bundle already valid" in console.export_text()+def test_select_and_ignore_are_mutually_exclusive(self, capsys: pytest.CaptureFixture[str]) -> None:with pytest.raises(typer.Exit) as exc_info:fix_bundle_cmd(diff --git a/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.py b/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.pyindex dba23a369..9ce19d217 100644--- a/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.py+++ b/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.py@@ -1,8 +1,9 @@"""Unit tests for the human CLI shared bundle-path resolver.-``pipelex validate bundle`` and ``pipelex fix bundle`` resolve their ``path`` argument through-this one helper — fix must patch exactly the file validate judged — so its semantics are pinned-here once for both commands.+``pipelex validate bundle`` and ``pipelex fix bundle`` resolve their ``path`` argument through ``resolve_bundle_target``,+which reads a folder whole, and ``pipelex build inputs bundle`` and ``pipelex build output bundle`` through+``resolve_build_bundle_target``, which acts on the pipe ``run bundle`` starts the same folder at, so their semantics+are pinned here once for every command."""from __future__ import annotations@@ -12,13 +13,27 @@ from typing import TYPE_CHECKINGimport pytestimport typer-from pipelex.cli.commands.bundle_path_resolver import resolve_bundle_target-from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAME+from pipelex.base_exceptions import PipelexConfigError+from pipelex.cli.bundle_target_resolution import resolve_method_folder_run+from pipelex.cli.commands.bundle_path_resolver import resolve_build_bundle_target, resolve_bundle_target+from pipelex.cli.judged_target import JudgedBundleTarget+from pipelex.pipeline.exceptions import ValidateBundleError+from tests.helpers.method_folders import NAMED_PIPE, MethodFolderShape, write_method_folderif TYPE_CHECKING:from pathlib import Path+ from pytest_mock import MockerFixture+_HINT = " To fix a bundle, pass a .mthds file or directory: pipelex fix bundle <path>"+_METHOD_TREES_MODULE = "pipelex.libraries.method_trees"+++def _run_refusal(*, directory: Path) -> str:+ """The message `run bundle` refuses the folder with."""+ with pytest.raises(ValidateBundleError) as exc_info:+ resolve_method_folder_run(directory=directory, pipe_override=None)+ return exc_info.value.messageclass TestHumanBundlePathResolver:@@ -26,19 +41,19 @@ class TestHumanBundlePathResolver:bundle_file = tmp_path / "my_bundle.mthds"bundle_file.write_text('domain = "demo"\n', encoding="utf-8")- bundle_path, library_dir = resolve_bundle_target(str(bundle_file), library_dir=None, command="fix", not_a_bundle_hint=_HINT)+ target = resolve_bundle_target(str(bundle_file), library_dir=None, command="fix", not_a_bundle_hint=_HINT)- assert bundle_path == str(bundle_file)- assert library_dir is None+ assert target == JudgedBundleTarget(bundle_path=bundle_file, method_dir=None, method_tree=None, library_dirs=None)+ assert target.judged_path == bundle_filedef test_tilde_in_path_is_expanded(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("HOME", str(tmp_path))bundle_file = tmp_path / "my_bundle.mthds"bundle_file.write_text('domain = "demo"\n', encoding="utf-8")- bundle_path, _ = resolve_bundle_target("~/my_bundle.mthds", library_dir=None, command="fix", not_a_bundle_hint=_HINT)+ target = resolve_bundle_target("~/my_bundle.mthds", library_dir=None, command="fix", not_a_bundle_hint=_HINT)- assert bundle_path == str(bundle_file)+ assert target.bundle_path == bundle_filedef test_tilde_in_library_dir_is_expanded(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("HOME", str(tmp_path))@@ -47,77 +62,91 @@ class TestHumanBundlePathResolver:libs_dir = tmp_path / "libs"libs_dir.mkdir()- _, library_dir = resolve_bundle_target(str(bundle_file), library_dir=["~/libs"], command="fix", not_a_bundle_hint=_HINT)-- assert library_dir == [str(libs_dir)]+ target = resolve_bundle_target(str(bundle_file), library_dir=["~/libs"], command="fix", not_a_bundle_hint=_HINT)- def test_directory_with_default_bundle_name_auto_detects_and_injects_dir(self, tmp_path: Path) -> None:- bundle_file = tmp_path / DEFAULT_BUNDLE_FILE_NAME- bundle_file.write_text('domain = "demo"\n', encoding="utf-8")- (tmp_path / "sibling.mthds").write_text('domain = "sibling"\n', encoding="utf-8")-- bundle_path, library_dir = resolve_bundle_target(str(tmp_path), library_dir=None, command="fix", not_a_bundle_hint=_HINT)+ assert target.library_dirs == [libs_dir]- assert bundle_path == str(bundle_file)- assert library_dir == [str(tmp_path)]-- def test_directory_with_single_mthds_falls_back_to_it(self, tmp_path: Path) -> None:- bundle_file = tmp_path / "only_one.mthds"- bundle_file.write_text('domain = "demo"\n', encoding="utf-8")+ @pytest.mark.parametrize("shape", list(MethodFolderShape))+ def test_a_folder_is_judged_whole_whatever_its_main_pipes(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str], shape: MethodFolderShape+ ) -> None:+ """No pipe to start at is needed: several main pipes, or none, are no refusal, since every bundle is judged."""+ write_method_folder(directory=tmp_path, shape=shape)- bundle_path, library_dir = resolve_bundle_target(str(tmp_path), library_dir=None, command="fix", not_a_bundle_hint=_HINT)+ target = resolve_bundle_target(str(tmp_path), library_dir=None, command="validate", not_a_bundle_hint=_HINT)- assert bundle_path == str(bundle_file)- assert library_dir == [str(tmp_path)]-- @pytest.mark.parametrize("bundle_name", [DEFAULT_BUNDLE_FILE_NAME, "only_one.mthds"])- def test_directory_refuses_auto_detected_symlink(self, tmp_path: Path, capsys: pytest.CaptureFixture[str], bundle_name: str) -> None:- outside_bundle = tmp_path.parent / f"{tmp_path.name}-outside.mthds"- outside_bundle.write_text('domain = "outside"\n', encoding="utf-8")- (tmp_path / bundle_name).symlink_to(outside_bundle)-- with pytest.raises(typer.Exit) as exc_info:- resolve_bundle_target(str(tmp_path), library_dir=None, command="fix", not_a_bundle_hint=_HINT)-- assert exc_info.value.exit_code == 2- assert "refusing to auto-detect symlinked bundle" in capsys.readouterr().err+ assert target.bundle_path is None+ assert target.method_dir == tmp_path+ assert target.judged_path == tmp_path+ assert target.library_dirs == [tmp_path]+ assert target.method_tree is not None+ assert target.method_tree.directory == tmp_path.resolve()+ assert "main pipe" not in capsys.readouterr().outdef test_directory_is_prepended_to_existing_library_dirs_without_duplication(self, tmp_path: Path) -> None:- bundle_file = tmp_path / DEFAULT_BUNDLE_FILE_NAME- bundle_file.write_text('domain = "demo"\n', encoding="utf-8")- other_dir = tmp_path / "libs"+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.SEVERAL_MAIN_PIPES)+ other_dir = tmp_path.parent / f"{tmp_path.name}-libs"other_dir.mkdir()- _, library_dir = resolve_bundle_target(str(tmp_path), library_dir=[str(other_dir)], command="fix", not_a_bundle_hint=_HINT)- assert library_dir == [str(tmp_path), str(other_dir)]+ target = resolve_bundle_target(str(tmp_path), library_dir=[str(other_dir)], command="fix", not_a_bundle_hint=_HINT)+ assert target.library_dirs == [tmp_path, other_dir]- _, library_dir_again = resolve_bundle_target(+ target_again = resolve_bundle_target(str(tmp_path),library_dir=[str(tmp_path), str(other_dir)],command="fix",not_a_bundle_hint=_HINT,)- assert library_dir_again == [str(tmp_path), str(other_dir)]+ assert target_again.library_dirs == [tmp_path, other_dir]++ @pytest.mark.parametrize("files", [{}, {".DS_Store": "", "notes.md": "# Notes\n"}], ids=["empty", "no_bundle"])+ def test_a_folder_holding_no_bundle_exits_2(self, tmp_path: Path, capsys: pytest.CaptureFixture[str], files: dict[str, str]) -> None:+ """An empty folder, or one whose tree keeps no bundle, has nothing to judge: no verdict."""+ for name, content in files.items():+ (tmp_path / name).write_text(content, encoding="utf-8")- def test_empty_directory_exits_2(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:with pytest.raises(typer.Exit) as exc_info:- resolve_bundle_target(str(tmp_path), library_dir=None, command="fix", not_a_bundle_hint=_HINT)+ resolve_bundle_target(str(tmp_path), library_dir=None, command="validate", not_a_bundle_hint=_HINT)assert exc_info.value.exit_code == 2- assert "Failed to fix: no .mthds bundle file found" in capsys.readouterr().err+ assert f"Failed to validate: The folder '{tmp_path}' holds no .mthds bundle." in capsys.readouterr().err- def test_ambiguous_directory_exits_2_naming_the_candidates(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:- (tmp_path / "b.mthds").write_text('domain = "b"\n', encoding="utf-8")- (tmp_path / "a.mthds").write_text('domain = "a"\n', encoding="utf-8")+ def test_a_folder_whose_tree_is_refused_is_the_invalid_verdict_each_command_reports(self, tmp_path: Path) -> None:+ """A symbolic link in the tree is refused when the tree is listed: the verdict leaves for the command to report."""+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.ONE_DECLARED_MAIN_PIPE)+ outside_bundle = tmp_path.parent / f"{tmp_path.name}-outside.mthds"+ outside_bundle.write_text('domain = "outside"\n', encoding="utf-8")+ (tmp_path / "linked.mthds").symlink_to(outside_bundle)- with pytest.raises(typer.Exit) as exc_info:+ with pytest.raises(ValidateBundleError) as exc_info:resolve_bundle_target(str(tmp_path), library_dir=None, command="fix", not_a_bundle_hint=_HINT)+ assert "linked.mthds" in exc_info.value.message++ def test_a_configuration_that_does_not_validate_before_the_boot_exits_2_as_a_failed_boot(+ self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ """Listing the tree reads its limits from the configuration: a refusal there is no traceback."""+ mocker.patch(f"{_METHOD_TREES_MODULE}.local_tree_limits", side_effect=PipelexConfigError("the configuration is out of date"))+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.ONE_DECLARED_MAIN_PIPE)++ with pytest.raises(typer.Exit) as exc_info:+ resolve_bundle_target(str(tmp_path), library_dir=None, command="validate", not_a_bundle_hint=_HINT)+assert exc_info.value.exit_code == 2- err = capsys.readouterr().err- assert "multiple .mthds files found" in err- assert "(a.mthds, b.mthds)" in err- assert f"pipelex fix bundle {tmp_path / 'a.mthds'}" in err+ assert "Failed to validate: the configuration is out of date" in capsys.readouterr().err++ def test_a_build_command_reports_a_configuration_that_does_not_validate_before_the_boot(+ self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ mocker.patch(f"{_METHOD_TREES_MODULE}.local_tree_limits", side_effect=PipelexConfigError("the configuration is out of date"))+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.ONE_DECLARED_MAIN_PIPE)++ with pytest.raises(typer.Exit) as exc_info:+ resolve_build_bundle_target(path=str(tmp_path), library_dir=None, pipe_override=None, command="build output", not_a_bundle_hint=_HINT)++ assert exc_info.value.exit_code == 1+ assert "Failed to build output: the configuration is out of date" in capsys.readouterr().errdef test_not_a_bundle_path_exits_2_with_command_hint(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:with pytest.raises(typer.Exit) as exc_info:@@ -128,3 +157,84 @@ class TestHumanBundlePathResolver:assert "Failed to fix:" in errassert "is not a .mthds file or directory" in errassert "pipelex fix bundle <path>" in err++ @pytest.mark.parametrize("shape", [MethodFolderShape.MANIFEST_MAIN_PIPE, MethodFolderShape.ONE_DECLARED_MAIN_PIPE])+ def test_a_build_command_acts_on_the_pipe_a_run_of_the_folder_starts_at(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str], shape: MethodFolderShape+ ) -> None:+ write_method_folder(directory=tmp_path, shape=shape)+ assert shape.entry is not None++ target = resolve_build_bundle_target(+ path=str(tmp_path), library_dir=None, pipe_override=None, command="build inputs", not_a_bundle_hint=_HINT+ )+ assert f"Using the method's main pipe {shape.entry.pipe_ref}, in {shape.entry.tree_path}" in capsys.readouterr().out++ assert target.bundle_path == (tmp_path / shape.entry.tree_path).resolve()+ assert target.pipe_code == shape.entry.pipe_ref+ assert target.library_dir == [str(tmp_path)]+ assert target.default_output_dir == tmp_path++ def test_a_build_command_naming_its_pipe_loads_the_folder_as_its_library(self, tmp_path: Path) -> None:+ """With `--pipe`, several main pipes are no ambiguity, and the pipe is looked up in the method, as a run does."""+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.SEVERAL_MAIN_PIPES)++ target = resolve_build_bundle_target(+ path=str(tmp_path), library_dir=None, pipe_override=NAMED_PIPE.pipe_ref, command="build inputs", not_a_bundle_hint=_HINT+ )++ assert target.bundle_path is None+ assert target.pipe_code == NAMED_PIPE.pipe_ref+ assert target.library_dir == [str(tmp_path)]+ assert target.default_output_dir == tmp_path++ def test_a_build_command_on_a_bundle_file_writes_beside_it(self, tmp_path: Path) -> None:+ bundle_file = tmp_path / "my_bundle.mthds"+ bundle_file.write_text('domain = "demo"\n', encoding="utf-8")++ target = resolve_build_bundle_target(+ path=str(bundle_file), library_dir=None, pipe_override="my_pipe", command="build inputs", not_a_bundle_hint=_HINT+ )++ assert target.bundle_path == bundle_file+ assert target.pipe_code == "my_pipe"+ assert target.library_dir is None+ assert target.default_output_dir is None++ @pytest.mark.parametrize("shape", [MethodFolderShape.SEVERAL_MAIN_PIPES, MethodFolderShape.NO_MAIN_PIPE])+ def test_a_build_command_on_a_folder_with_no_single_main_pipe_exits_1(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str], shape: MethodFolderShape+ ) -> None:+ write_method_folder(directory=tmp_path, shape=shape)+ assert shape.refusal is not None++ with pytest.raises(typer.Exit) as exc_info:+ resolve_build_bundle_target(path=str(tmp_path), library_dir=None, pipe_override=None, command="build inputs", not_a_bundle_hint=_HINT)++ assert exc_info.value.exit_code == 1+ err = capsys.readouterr().err+ assert f"Failed to build inputs: {_run_refusal(directory=tmp_path)}" in err+ assert shape.refusal in err++ def test_a_build_command_on_a_folder_holding_no_bundle_exits_1_with_the_message_run_gives(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ with pytest.raises(typer.Exit) as exc_info:+ resolve_build_bundle_target(path=str(tmp_path), library_dir=None, pipe_override=None, command="build inputs", not_a_bundle_hint=_HINT)++ assert exc_info.value.exit_code == 1+ run_refusal = _run_refusal(directory=tmp_path)+ assert "holds no .mthds bundle, so it has no pipe to start at" in run_refusal+ assert f"Failed to build inputs: {run_refusal}" in capsys.readouterr().err++ def test_a_build_command_on_a_path_that_is_no_bundle_exits_1(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ with pytest.raises(typer.Exit) as exc_info:+ resolve_build_bundle_target(+ path=str(tmp_path / "nope.txt"), library_dir=None, pipe_override=None, command="build inputs", not_a_bundle_hint=_HINT+ )++ assert exc_info.value.exit_code == 1+ err = capsys.readouterr().err+ assert "Failed to build inputs:" in err+ assert "Failed to run:" not in err+ assert "is not a .mthds file or directory" in errdiff --git a/tests/unit/pipelex/cli/commands/test_folder_entry_commands.py b/tests/unit/pipelex/cli/commands/test_folder_entry_commands.pynew file mode 100644index 000000000..8b869aa6f--- /dev/null+++ b/tests/unit/pipelex/cli/commands/test_folder_entry_commands.py@@ -0,0 +1,246 @@+"""The human commands taking a method's folder: `validate` and `fix` judge it whole, `build` acts on the pipe `run` starts at."""++from __future__ import annotations++from typing import TYPE_CHECKING++import pytest+import typer+from rich.console import Console++from pipelex.base_exceptions import PipelexConfigError+from pipelex.cli.bundle_target_resolution import resolve_method_folder_run+from pipelex.cli.commands.build.inputs.bundle_cmd import build_inputs_bundle_cmd+from pipelex.cli.commands.build.output.bundle_cmd import build_output_bundle_cmd+from pipelex.cli.commands.fix.bundle_cmd import fix_bundle_cmd+from pipelex.cli.commands.run.bundle_cmd import run_bundle_cmd+from pipelex.cli.commands.validate.bundle_cmd import validate_bundle_cmd+from pipelex.pipeline.exceptions import ValidateBundleError+from tests.helpers.method_folders import NAMED_PIPE, MethodFolderShape, write_method_folder++if TYPE_CHECKING:+ from pathlib import Path++ from pytest_mock import MockerFixture++_RESOLVED_SHAPES = [MethodFolderShape.MANIFEST_MAIN_PIPE, MethodFolderShape.ONE_DECLARED_MAIN_PIPE]+_REFUSED_SHAPES = [MethodFolderShape.SEVERAL_MAIN_PIPES, MethodFolderShape.NO_MAIN_PIPE]+_BUILD_COMMANDS = ["build_inputs", "build_output"]+++def _run_refusal(*, directory: Path) -> str:+ """The message `run bundle` refuses the folder with."""+ with pytest.raises(ValidateBundleError) as exc_info:+ resolve_method_folder_run(directory=directory, pipe_override=None)+ return exc_info.value.message+++def _invoke_validate_or_fix(*, command: str, path: Path) -> None:+ match command:+ case "validate":+ validate_bundle_cmd(path=str(path))+ case "fix":+ fix_bundle_cmd(path=str(path))+ case _:+ msg = f"Unknown command '{command}'"+ raise ValueError(msg)+++def _invoke_build(*, command: str, path: Path, pipe: str | None) -> None:+ match command:+ case "build_inputs":+ build_inputs_bundle_cmd(path=str(path), pipe=pipe)+ case "build_output":+ build_output_bundle_cmd(path=str(path), pipe=pipe)+ case _:+ msg = f"Unknown build command '{command}'"+ raise ValueError(msg)+++def _invoke_folder_command(*, command: str, path: Path) -> None:+ """Any command reading a folder, with no `--pipe`."""+ match command:+ case "validate" | "fix":+ _invoke_validate_or_fix(command=command, path=path)+ case "run":+ run_bundle_cmd(path=str(path))+ case _:+ _invoke_build(command=command, path=path, pipe=None)+++def _build_command_name(*, command: str) -> str:+ """The command as its failures name it."""+ return command.replace("_", " ")+++def _write_folder_with_a_refused_tree(*, directory: Path) -> None:+ """A method folder whose tree is refused when it is listed: a symbolic link among its files."""+ write_method_folder(directory=directory, shape=MethodFolderShape.ONE_DECLARED_MAIN_PIPE)+ outside_bundle = directory.parent / f"{directory.name}-outside.mthds"+ outside_bundle.write_text('domain = "outside"\n', encoding="utf-8")+ (directory / "linked.mthds").symlink_to(outside_bundle)+++def _build_executor(*, command: str) -> str:+ match command:+ case "build_inputs":+ return "pipelex.cli.commands.build.inputs.bundle_cmd.execute_generate_inputs"+ case "build_output":+ return "pipelex.cli.commands.build.output.bundle_cmd.execute_generate_output"+ case _:+ msg = f"Unknown build command '{command}'"+ raise ValueError(msg)+++class TestHumanFolderEntryCommands:+ @pytest.mark.parametrize("shape", list(MethodFolderShape))+ def test_validate_judges_the_whole_method_whatever_its_main_pipes(self, mocker: MockerFixture, tmp_path: Path, shape: MethodFolderShape) -> None:+ """Every bundle of the folder is judged, as the protocol's validation judges a method, so no pipe to start at is needed."""+ mock_execute = mocker.patch("pipelex.cli.commands.validate.bundle_cmd.execute_validate")+ write_method_folder(directory=tmp_path, shape=shape)++ validate_bundle_cmd(path=str(tmp_path))++ kwargs = mock_execute.call_args.kwargs+ assert kwargs["method_dir"] == tmp_path+ assert kwargs["bundle_path"] is None+ assert kwargs["library_dirs"] == [tmp_path]+ assert kwargs["pipe_code"] is None++ @pytest.mark.parametrize("shape", list(MethodFolderShape))+ def test_fix_patches_the_whole_method_validate_judges(self, mocker: MockerFixture, tmp_path: Path, shape: MethodFolderShape) -> None:+ mock_execute = mocker.patch("pipelex.cli.commands.fix.bundle_cmd.execute_fix")+ write_method_folder(directory=tmp_path, shape=shape)++ fix_bundle_cmd(path=str(tmp_path))++ target = mock_execute.call_args.kwargs["target"]+ assert target.method_dir == tmp_path+ assert target.bundle_path is None+ assert target.library_dirs == [tmp_path]+ assert target.judged_path == tmp_path++ def test_validate_names_the_folder_whose_tree_is_refused_in_its_invalid_verdict(self, mocker: MockerFixture, tmp_path: Path) -> None:+ recorded_console = Console(width=500, record=True, color_system=None)+ mocker.patch("pipelex.cli.error_handlers.get_console", return_value=recorded_console)+ mock_execute = mocker.patch("pipelex.cli.commands.validate.bundle_cmd.execute_validate")+ _write_folder_with_a_refused_tree(directory=tmp_path)++ with pytest.raises(typer.Exit) as exc_info:+ validate_bundle_cmd(path=str(tmp_path))++ assert exc_info.value.exit_code == 1+ output = recorded_console.export_text()+ assert "Bundle validation failed" in output+ assert f"Bundle: {tmp_path}" in output+ assert "linked.mthds" in output+ mock_execute.assert_not_called()++ @pytest.mark.parametrize("diff", [False, True], ids=["fix", "preview"])+ def test_fix_reports_a_folder_whose_tree_is_refused_as_a_fix_that_fails(self, mocker: MockerFixture, tmp_path: Path, diff: bool) -> None:+ recorded_console = Console(width=500, record=True, color_system=None)+ mocker.patch("pipelex.cli.commands.fix._fix_core.get_console", return_value=recorded_console)+ mocker.patch("pipelex.cli.error_handlers.get_console", return_value=recorded_console)+ mock_execute = mocker.patch("pipelex.cli.commands.fix.bundle_cmd.execute_fix")+ _write_folder_with_a_refused_tree(directory=tmp_path)++ with pytest.raises(typer.Exit) as exc_info:+ fix_bundle_cmd(path=str(tmp_path), diff=diff)++ assert exc_info.value.exit_code == 1+ output = recorded_console.export_text()+ assert ("the bundle would still be invalid" if diff else "Bundle could not be fully fixed") in output+ assert "Bundle validation failed" not in output+ assert f"Bundle: {tmp_path}" in output+ assert "linked.mthds" in output+ mock_execute.assert_not_called()++ @pytest.mark.parametrize("command", ["validate", "fix"])+ def test_validate_and_fix_refuse_a_folder_holding_no_bundle_with_no_verdict(+ self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str], command: str+ ) -> None:+ mock_validate = mocker.patch("pipelex.cli.commands.validate.bundle_cmd.execute_validate")+ mock_fix = mocker.patch("pipelex.cli.commands.fix.bundle_cmd.execute_fix")++ with pytest.raises(typer.Exit) as exc_info:+ _invoke_validate_or_fix(command=command, path=tmp_path)++ assert exc_info.value.exit_code == 2+ assert f"Failed to {command}: The folder '{tmp_path}' holds no .mthds bundle." in capsys.readouterr().err+ mock_validate.assert_not_called()+ mock_fix.assert_not_called()++ @pytest.mark.parametrize(("command", "exit_code"), [("validate", 2), ("fix", 2), ("run", 1), ("build_inputs", 1), ("build_output", 1)])+ def test_a_configuration_that_does_not_validate_before_the_boot_is_reported_as_a_failed_boot(+ self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str], command: str, exit_code: int+ ) -> None:+ """Listing the tree reads its limits from the configuration: a refusal there names the command, never a traceback."""+ mocker.patch("pipelex.libraries.method_trees.local_tree_limits", side_effect=PipelexConfigError("the configuration is out of date"))+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.ONE_DECLARED_MAIN_PIPE)++ with pytest.raises(typer.Exit) as exc_info:+ _invoke_folder_command(command=command, path=tmp_path)++ assert exc_info.value.exit_code == exit_code+ assert f"Failed to {_build_command_name(command=command)}: the configuration is out of date" in capsys.readouterr().err++ @pytest.mark.parametrize("shape", _RESOLVED_SHAPES)+ @pytest.mark.parametrize("command", _BUILD_COMMANDS)+ def test_build_acts_on_the_pipe_the_method_starts_at_and_writes_in_the_folder(+ self, mocker: MockerFixture, tmp_path: Path, command: str, shape: MethodFolderShape+ ) -> None:+ mock_execute = mocker.patch(_build_executor(command=command))+ write_method_folder(directory=tmp_path, shape=shape)+ assert shape.entry is not None++ _invoke_build(command=command, path=tmp_path, pipe=None)++ kwargs = mock_execute.call_args.kwargs+ assert kwargs["pipe_code"] == shape.entry.pipe_ref+ assert kwargs["bundle_path"] == (tmp_path / shape.entry.tree_path).resolve()+ assert kwargs["library_dir"] == [str(tmp_path)]+ assert kwargs["default_output_dir"] == tmp_path+ assert kwargs["output_path"] is None++ @pytest.mark.parametrize("command", _BUILD_COMMANDS)+ def test_build_naming_its_pipe_loads_the_folder_as_its_library(self, mocker: MockerFixture, tmp_path: Path, command: str) -> None:+ """With `--pipe`, several main pipes are no ambiguity, and the pipe is looked up in the method, as a run does."""+ mock_execute = mocker.patch(_build_executor(command=command))+ write_method_folder(directory=tmp_path, shape=MethodFolderShape.SEVERAL_MAIN_PIPES)++ _invoke_build(command=command, path=tmp_path, pipe=NAMED_PIPE.pipe_ref)++ kwargs = mock_execute.call_args.kwargs+ assert kwargs["pipe_code"] == NAMED_PIPE.pipe_ref+ assert kwargs["bundle_path"] is None+ assert kwargs["library_dir"] == [str(tmp_path)]+ assert kwargs["default_output_dir"] == tmp_path++ @pytest.mark.parametrize("shape", _REFUSED_SHAPES)+ @pytest.mark.parametrize("command", _BUILD_COMMANDS)+ def test_build_refuses_a_folder_with_no_single_main_pipe(+ self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str], command: str, shape: MethodFolderShape+ ) -> None:+ mock_execute = mocker.patch(_build_executor(command=command))+ write_method_folder(directory=tmp_path, shape=shape)++ with pytest.raises(typer.Exit) as exc_info:+ _invoke_build(command=command, path=tmp_path, pipe=None)++ assert exc_info.value.exit_code == 1+ assert f"Failed to {_build_command_name(command=command)}: {_run_refusal(directory=tmp_path)}" in capsys.readouterr().err+ mock_execute.assert_not_called()++ @pytest.mark.parametrize("command", _BUILD_COMMANDS)+ def test_build_on_a_bundle_file_keeps_its_pipe_and_writes_beside_it(self, mocker: MockerFixture, tmp_path: Path, command: str) -> None:+ mock_execute = mocker.patch(_build_executor(command=command))+ bundle_file = tmp_path / "my_bundle.mthds"+ bundle_file.write_text('domain = "demo"\n', encoding="utf-8")++ _invoke_build(command=command, path=bundle_file, pipe="my_pipe")++ kwargs = mock_execute.call_args.kwargs+ assert kwargs["pipe_code"] == "my_pipe"+ assert kwargs["bundle_path"] == bundle_file+ assert kwargs["library_dir"] is None+ assert kwargs["default_output_dir"] is Nonediff --git a/tests/unit/pipelex/cli/test_judged_target.py b/tests/unit/pipelex/cli/test_judged_target.pynew file mode 100644index 000000000..9de36948a--- /dev/null+++ b/tests/unit/pipelex/cli/test_judged_target.py@@ -0,0 +1,78 @@+from pathlib import Path++import pytest+from pytest_mock import MockerFixture++from pipelex.base_exceptions import PipelexUnexpectedError+from pipelex.cli.judged_target import JudgedBundleTarget, fix_judged_target+from pipelex.pipeline.fixes.fix_loop import FixBundleResult++_MODULE = "pipelex.cli.judged_target"+_RESULT = FixBundleResult(is_valid=True, iterations=0, fixes_applied=[], remaining_errors=[], is_runnable=True)++[email protected](loop_scope="class")+class TestJudgedTarget:+ @pytest.mark.parametrize(+ ("bundle_path", "method_dir", "expected"),+ [+ (Path("my_bundle.mthds"), None, Path("my_bundle.mthds")),+ (None, Path("my_method"), Path("my_method")),+ ],+ ids=["bundle_file", "method_folder"],+ )+ async def test_the_judged_path_is_the_folder_else_the_file(self, bundle_path: Path | None, method_dir: Path | None, expected: Path) -> None:+ target = JudgedBundleTarget(bundle_path=bundle_path, method_dir=method_dir, method_tree=None, library_dirs=None)++ assert target.judged_path == expected++ async def test_a_target_naming_neither_is_unexpected(self) -> None:+ target = JudgedBundleTarget(bundle_path=None, method_dir=None, method_tree=None, library_dirs=None)++ with pytest.raises(PipelexUnexpectedError, match="neither a bundle file nor a method's folder"):+ _ = target.judged_path++ async def test_a_folder_is_fixed_whole(self, mocker: MockerFixture) -> None:+ folder_fix = mocker.patch(f"{_MODULE}.fix_method_folder", new=mocker.AsyncMock(return_value=_RESULT))+ file_fix = mocker.patch(f"{_MODULE}.fix_bundle_file", new=mocker.AsyncMock(return_value=_RESULT))+ method_dir = Path("my_method")+ library_dirs = [method_dir, Path("libs")]+ target = JudgedBundleTarget(bundle_path=None, method_dir=method_dir, method_tree=None, library_dirs=library_dirs)++ result = await fix_judged_target(+ target=target, writable_library_dirs=None, allow_signatures=True, max_iterations=4, select_codes=None, ignore_codes=("strip-namespace",)+ )++ assert result is _RESULT+ folder_fix.assert_awaited_once_with(+ method_dir=method_dir,+ library_dirs=library_dirs,+ writable_library_dirs=None,+ allow_signatures=True,+ max_iterations=4,+ select_codes=None,+ ignore_codes=("strip-namespace",),+ )+ file_fix.assert_not_called()++ async def test_a_bundle_file_is_fixed_as_a_file(self, mocker: MockerFixture) -> None:+ folder_fix = mocker.patch(f"{_MODULE}.fix_method_folder", new=mocker.AsyncMock(return_value=_RESULT))+ file_fix = mocker.patch(f"{_MODULE}.fix_bundle_file", new=mocker.AsyncMock(return_value=_RESULT))+ bundle_path = Path("my_bundle.mthds")+ writable = [Path("copy")]+ target = JudgedBundleTarget(bundle_path=bundle_path, method_dir=None, method_tree=None, library_dirs=None)++ await fix_judged_target(+ target=target, writable_library_dirs=writable, allow_signatures=False, max_iterations=None, select_codes=None, ignore_codes=None+ )++ file_fix.assert_awaited_once_with(+ bundle_path,+ library_dirs=None,+ writable_library_dirs=writable,+ allow_signatures=False,+ max_iterations=None,+ select_codes=None,+ ignore_codes=None,+ )+ folder_fix.assert_not_called()diff --git a/tests/unit/pipelex/cli/test_validate_exit_codes.py b/tests/unit/pipelex/cli/test_validate_exit_codes.pyindex 2bfe9d837..f8f42e970 100644--- a/tests/unit/pipelex/cli/test_validate_exit_codes.py+++ b/tests/unit/pipelex/cli/test_validate_exit_codes.py@@ -73,12 +73,6 @@ class TestValidateExitCodes:bare_validate_bundle_cmd(path=str(empty_dir))assert exc_info.value.exit_code == 2- def test_bare_bundle_directory_with_multiple_mthds_and_no_default_exits_2(self, tmp_path: Path) -> None:- multi_dir = _make_dir(tmp_path, "multi", ["a.mthds", "b.mthds"])- with pytest.raises(typer.Exit) as exc_info:- bare_validate_bundle_cmd(path=str(multi_dir))- assert exc_info.value.exit_code == 2-def test_bare_bundle_path_that_is_neither_file_nor_dir_exits_2(self, tmp_path: Path) -> None:with pytest.raises(typer.Exit) as exc_info:bare_validate_bundle_cmd(path=str(tmp_path / "nope"))@@ -125,12 +119,6 @@ class TestValidateExitCodes:agent_validate_bundle_cmd(path=str(empty_dir), output_format=CliOutputFormat.JSON)assert exc_info.value.exit_code == 2- def test_agent_bundle_directory_with_multiple_mthds_exits_2(self, tmp_path: Path) -> None:- multi_dir = _make_dir(tmp_path, "multi", ["a.mthds", "b.mthds"])- with pytest.raises(typer.Exit) as exc_info:- agent_validate_bundle_cmd(path=str(multi_dir), output_format=CliOutputFormat.JSON)- assert exc_info.value.exit_code == 2-def test_agent_bundle_path_that_is_neither_file_nor_dir_exits_2(self, tmp_path: Path) -> None:with pytest.raises(typer.Exit) as exc_info:agent_validate_bundle_cmd(path=str(tmp_path / "nope"), output_format=CliOutputFormat.JSON)diff --git a/tests/unit/pipelex/pipeline/fixes/test_fix_method_folder.py b/tests/unit/pipelex/pipeline/fixes/test_fix_method_folder.pynew file mode 100644index 000000000..02cc5cc83--- /dev/null+++ b/tests/unit/pipelex/pipeline/fixes/test_fix_method_folder.py@@ -0,0 +1,173 @@+from pathlib import Path++import pytest+import tomlkit+from pytest_mock import MockerFixture++from pipelex.core.exceptions import PipesAndConceptValidationErrorData+from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.fixes import fix_loop+from pipelex.pipeline.fixes.fix_loop import fix_method_folder+from pipelex.validation_error_types import PipeValidationErrorType++_IDEAS_MTHDS = """domain = "folder_fix_ideas"+main_pipe = "list_ideas"++[pipe.list_ideas]+type = "PipeLLM"+description = "Lists ideas, declaring a single Text where its sequence makes several."+inputs = { topic = "Text" }+output = "Text"+prompt = "Write about $topic"+"""++_SUMMARY_MTHDS = """domain = "folder_fix_summary"+main_pipe = "summarize"++[pipe.summarize]+type = "PipeLLM"+description = "A second bundle declaring its own main pipe, so the folder decides no entry."+inputs = { topic = "Text" }+output = "Text"+prompt = "Summarize $topic"+"""+++def _seq_output_error(*, source: str | None) -> ValidateBundleError:+ return ValidateBundleError(+ message="Pipe validation failed",+ pipe_validation_errors=[+ PipesAndConceptValidationErrorData(+ error_type=PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT,+ domain_code="folder_fix_ideas",+ source=source,+ pipe_code="list_ideas",+ message="pipe 'list_ideas' output mismatch",+ field_path=source or "",+ expected_output_ref="Idea[]",+ ),+ ],+ )+++_MANIFEST = """[package]+address = "github.com/pipelex-tests/folder-fix"+version = "1.0.0"+description = "A method whose tree is rooted above the folder a fix is handed"+"""+++def _write_method_folder(*, directory: Path) -> tuple[Path, Path]:+ ideas_path = directory / "ideas.mthds"+ ideas_path.write_text(_IDEAS_MTHDS, encoding="utf-8")+ summary_path = directory / "summary.mthds"+ summary_path.write_text(_SUMMARY_MTHDS, encoding="utf-8")+ return ideas_path, summary_path++[email protected](loop_scope="class")+class TestFixMethodFolder:+ async def test_a_fix_lands_in_the_bundle_it_names_while_the_folder_is_judged_whole(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """Two bundles each declaring a main pipe are no refusal: the whole folder is validated, and the fix lands where it points."""+ method_dir = tmp_path / "method"+ method_dir.mkdir()+ ideas_path, summary_path = _write_method_folder(directory=method_dir)+ validate_mock = mocker.patch(+ "pipelex.pipeline.fixes.fix_loop.validate_bundle",+ side_effect=[_seq_output_error(source=str(ideas_path)), None],+ )++ result = await fix_method_folder(method_dir=method_dir, library_dirs=[method_dir], max_iterations=3)++ assert result.is_valid is True+ assert [fix.fix_code for fix in result.fixes_applied] == ["match-sequence-output"]+ assert [Path(written) for written in result.files_written] == [ideas_path.resolve()]+ fixed = tomlkit.loads(ideas_path.read_text(encoding="utf-8")).unwrap()+ assert fixed["pipe"]["list_ideas"]["output"] == "Idea[]"+ assert summary_path.read_text(encoding="utf-8") == _SUMMARY_MTHDS+ assert validate_mock.await_count == 2+ for call in validate_mock.await_args_list:+ assert call.kwargs == {+ "method_dir": method_dir,+ "library_dirs": [method_dir],+ "library_dirs_are_callers": True,+ "allow_signatures": False,+ }++ async def test_a_sourceless_fix_is_dropped_since_a_folder_has_no_entry_file(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """With no entry file, a fix that names no file has nowhere to land: nothing is written."""+ method_dir = tmp_path / "method"+ method_dir.mkdir()+ ideas_path, summary_path = _write_method_folder(directory=method_dir)+ mocker.patch(+ "pipelex.pipeline.fixes.fix_loop.validate_bundle",+ side_effect=_seq_output_error(source=None),+ )++ result = await fix_method_folder(method_dir=method_dir, max_iterations=3)++ assert result.is_valid is False+ assert result.fixes_applied == []+ assert result.files_written == []+ assert [item.error_type for item in result.remaining_errors] == [PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT]+ assert ideas_path.read_text(encoding="utf-8") == _IDEAS_MTHDS+ assert summary_path.read_text(encoding="utf-8") == _SUMMARY_MTHDS++ async def test_a_fix_outside_the_write_scope_is_not_applied(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """``writable_library_dirs`` narrows the write scope: a fix aimed at a loaded file outside it touches nothing."""+ method_dir = tmp_path / "method"+ method_dir.mkdir()+ ideas_path, _ = _write_method_folder(directory=method_dir)+ elsewhere = tmp_path / "elsewhere"+ elsewhere.mkdir()+ mocker.patch(+ "pipelex.pipeline.fixes.fix_loop.validate_bundle",+ side_effect=_seq_output_error(source=str(ideas_path)),+ )++ result = await fix_method_folder(method_dir=method_dir, writable_library_dirs=[elsewhere], max_iterations=3)++ assert result.is_valid is False+ assert result.fixes_applied == []+ assert result.files_written == []+ assert ideas_path.read_text(encoding="utf-8") == _IDEAS_MTHDS++ async def test_a_fix_of_a_subfolder_lands_in_a_sibling_bundle_of_its_tree(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """The tree is rooted at the `METHODS.toml` above the folder handed over, and a fix may write any bundle of it."""+ root_dir = tmp_path / "method"+ sub_dir = root_dir / "sub"+ sub_dir.mkdir(parents=True)+ (root_dir / "METHODS.toml").write_text(_MANIFEST, encoding="utf-8")+ ideas_path = root_dir / "ideas.mthds"+ ideas_path.write_text(_IDEAS_MTHDS, encoding="utf-8")+ summary_path = sub_dir / "summary.mthds"+ summary_path.write_text(_SUMMARY_MTHDS, encoding="utf-8")+ mocker.patch(+ "pipelex.pipeline.fixes.fix_loop.validate_bundle",+ # A file of the tree outside the folder loaded is named by its absolute location, as the load names it.+ side_effect=[_seq_output_error(source=str(ideas_path.resolve())), None],+ )++ result = await fix_method_folder(method_dir=sub_dir, library_dirs=[sub_dir], max_iterations=3)++ assert result.is_valid is True+ assert result.bail_reason is None+ assert [Path(written) for written in result.files_written] == [ideas_path.resolve()]+ fixed = tomlkit.loads(ideas_path.read_text(encoding="utf-8")).unwrap()+ assert fixed["pipe"]["list_ideas"]["output"] == "Idea[]"+ assert summary_path.read_text(encoding="utf-8") == _SUMMARY_MTHDS++ async def test_a_library_directory_naming_the_folder_otherwise_is_not_loaded_twice(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """The folder is left out of the directories beside it however it is spelled, compared resolved."""+ method_dir = tmp_path / "method"+ method_dir.mkdir()+ _write_method_folder(directory=method_dir)+ linked_dir = tmp_path / "linked"+ linked_dir.symlink_to(method_dir, target_is_directory=True)+ snapshot_spy = mocker.spy(fix_loop, "_snapshot_loaded_sources")+ mocker.patch("pipelex.pipeline.fixes.fix_loop.validate_bundle", return_value=None)++ result = await fix_method_folder(method_dir=method_dir, library_dirs=[linked_dir, method_dir], max_iterations=3)++ assert result.is_valid is True+ assert snapshot_spy.call_args.kwargs["effective_dirs"] == [method_dir]diff --git a/tests/unit/pipelex/pipeline/test_dirs_beside_method.py b/tests/unit/pipelex/pipeline/test_dirs_beside_method.pynew file mode 100644index 000000000..484702bdf--- /dev/null+++ b/tests/unit/pipelex/pipeline/test_dirs_beside_method.py@@ -0,0 +1,25 @@+from pathlib import Path++import pytest++from pipelex.pipeline.validate_bundle import dirs_beside_method+++class TestDirsBesideMethod:+ def test_the_folder_is_left_out_however_it_is_spelled(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Compared resolved: a relative spelling, an absolute one and a symbolic link all name the folder."""+ method_dir = tmp_path / "method"+ method_dir.mkdir()+ other_dir = tmp_path / "libs"+ other_dir.mkdir()+ linked_dir = tmp_path / "linked"+ linked_dir.symlink_to(method_dir, target_is_directory=True)+ monkeypatch.chdir(tmp_path)++ beside = dirs_beside_method(method_dir=Path("method"), library_dirs=[method_dir, linked_dir, Path("libs"), Path("method")])++ assert beside == [Path("libs")]++ @pytest.mark.parametrize("library_dirs", [None, []], ids=["none", "empty"])+ def test_no_library_directory_leaves_nothing_beside(self, tmp_path: Path, library_dirs: list[Path] | None) -> None:+ assert dirs_beside_method(method_dir=tmp_path, library_dirs=library_dirs) == []diff --git a/tests/unit/pipelex/pipeline/test_method_entry.py b/tests/unit/pipelex/pipeline/test_method_entry.pyindex 49ad75ccf..6ce1b505c 100644--- a/tests/unit/pipelex/pipeline/test_method_entry.py+++ b/tests/unit/pipelex/pipeline/test_method_entry.py@@ -3,8 +3,10 @@ from pathlib import Pathimport pytestfrom mthds.method_tree.lister import list_method_tree+from pipelex.mthds_parsing.exceptions import MthdsParserErrorfrom pipelex.pipeline.exceptions import MethodEntryError-from pipelex.pipeline.method_entry import select_method_entry+from pipelex.pipeline.method_entry import read_method_candidates, select_method_entry, select_named_pipe+from pipelex.validation_error_types import PipeValidationErrorTypedef _bundle(*, domain: str, pipe_code: str, main_pipe: str | None) -> str:@@ -132,3 +134,115 @@ class TestMethodEntry:with pytest.raises(MethodEntryError, match=r"The METHODS\.toml of the method at .* cannot be read"):select_method_entry(tree=list_method_tree(tmp_path))++ def test_a_bundle_whose_pipes_do_not_validate_still_says_where_its_method_starts(self, tmp_path: Path) -> None:+ """The rule reads the declarations alone, so `fix` can still reach a method whose pipes it has to repair."""+ _write(+ directory=tmp_path,+ files={+ "broken.mthds": 'domain = "entry_broken"\nmain_pipe = "first"\n\n[pipe.first]\ntype = "PipeNope"\n',+ "steps.mthds": _bundle(domain="entry_steps", pipe_code="extract", main_pipe=None),+ },+ )++ entry = select_method_entry(tree=list_method_tree(tmp_path))++ assert entry.pipe_ref == "entry_broken.first"+ assert entry.tree_path == "broken.mthds"++ @pytest.mark.parametrize(+ ("content", "expected"),+ [+ ('domain = \nmain_pipe = "first"\n', "TOML syntax error at line 1"),+ ('domain = 3\nmain_pipe = "first"\n', "Domain code '3' is not a valid domain code"),+ ('domain = "entry_a"\nmain_pipe = ["first"]\n', "Input should be a valid string"),+ ('domain = "entry_a"\npipe = 3\n', "Input should be a valid dictionary"),+ ],+ ids=["not_toml", "domain_not_a_string", "main_pipe_not_a_string", "pipe_not_a_table"],+ )+ def test_a_bundle_whose_declarations_cannot_be_read_is_refused_as_its_parse_refuses_it(self, tmp_path: Path, content: str, expected: str) -> None:+ _write(directory=tmp_path, files={"a.mthds": content})++ with pytest.raises(MthdsParserError) as exc_info:+ select_method_entry(tree=list_method_tree(tmp_path))++ assert expected in str(exc_info.value)++ @pytest.mark.parametrize("main_pipe", ["dom.pipe", "camelCase", ""], ids=["qualified_ref", "camel_case", "empty_string"])+ def test_a_main_pipe_that_is_no_pipe_code_is_refused_at_entry_selection_naming_its_bundle(self, tmp_path: Path, main_pipe: str) -> None:+ """The bundle's parse holds `main_pipe` to the pipe code syntax, and so does the rule: an empty string declares no pipe and is no absence."""+ _write(+ directory=tmp_path,+ files={+ "a.mthds": _bundle(domain="entry_a", pipe_code="first", main_pipe=None).replace(+ "\n\n[pipe.", f'\nmain_pipe = "{main_pipe}"\n\n[pipe.', 1+ ),+ "b.mthds": _bundle(domain="entry_b", pipe_code="second", main_pipe="second"),+ },+ )++ with pytest.raises(MthdsParserError) as exc_info:+ select_method_entry(tree=list_method_tree(tmp_path))++ assert f"Invalid main pipe syntax '{main_pipe}'" in exc_info.value.message+ items = exc_info.value.validation_errors or []+ assert [item.error_type for item in items] == [PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX]+ assert [Path(item.source or "").name for item in items] == ["a.mthds"]++ @pytest.mark.parametrize(+ ("pipe_ref", "expected_tree_path", "expected_pipe_ref"),+ [+ ("extract", "steps/extract.mthds", "entry_steps.extract"),+ ("entry_report.summarize", "report.mthds", "entry_report.summarize"),+ ("entry_steps.summarize", "steps/extract.mthds", "entry_steps.summarize"),+ ],+ ids=["bare_code", "qualified_ref", "qualified_ref_of_a_shared_code"],+ )+ def test_a_named_pipe_is_found_in_the_bundle_defining_it(+ self, tmp_path: Path, pipe_ref: str, expected_tree_path: str, expected_pipe_ref: str+ ) -> None:+ _write(+ directory=tmp_path,+ files={+ "steps/extract.mthds": _bundle(domain="entry_steps", pipe_code="extract", main_pipe=None)+ + _bundle(domain="entry_steps", pipe_code="summarize", main_pipe=None).split("\n", 2)[2],+ "report.mthds": _bundle(domain="entry_report", pipe_code="summarize", main_pipe="summarize"),+ },+ )+ tree = list_method_tree(tmp_path)++ entry = select_named_pipe(candidates=read_method_candidates(tree=tree), pipe_ref=pipe_ref, method_label="here")++ assert entry.tree_path == expected_tree_path+ assert entry.pipe_ref == expected_pipe_ref++ @pytest.mark.parametrize(+ ("pipe_ref", "expected"),+ [+ ("missing", "No bundle of the method here defines the pipe 'missing'. Its bundles: 'report.mthds', 'steps/extract.mthds'."),+ (+ "summarize",+ (+ "Several bundles of the method here define the pipe 'summarize': 'report.mthds' in domain 'entry_report', "+ "'steps/extract.mthds' in domain 'entry_steps'. Name the pipe as domain.pipe_code."+ ),+ ),+ ("scoring->scoring.compute", "The pipe 'scoring->scoring.compute' belongs to a package the method here depends on"),+ ("entry_steps..summarize", "'entry_steps..summarize' does not name a pipe of the method here"),+ ],+ ids=["undefined", "ambiguous_bare_code", "dependency_pipe", "not_a_pipe_ref"],+ )+ def test_a_named_pipe_no_single_bundle_defines_is_refused(self, tmp_path: Path, pipe_ref: str, expected: str) -> None:+ _write(+ directory=tmp_path,+ files={+ "steps/extract.mthds": _bundle(domain="entry_steps", pipe_code="summarize", main_pipe=None),+ "report.mthds": _bundle(domain="entry_report", pipe_code="summarize", main_pipe="summarize"),+ },+ )+ tree = list_method_tree(tmp_path)++ with pytest.raises(MethodEntryError) as exc_info:+ select_named_pipe(candidates=read_method_candidates(tree=tree), pipe_ref=pipe_ref, method_label="here")++ assert expected in exc_info.value.messagediff --git a/tests/unit/pipelex/pipeline/test_validation_render.py b/tests/unit/pipelex/pipeline/test_validation_render.pyindex 684404fdb..02909a5c3 100644--- a/tests/unit/pipelex/pipeline/test_validation_render.py+++ b/tests/unit/pipelex/pipeline/test_validation_render.py@@ -86,6 +86,22 @@ class TestValidationRender:assert "this method is runnable." in markdownassert "Pending signatures" not in markdown+ def test_says_plainly_why_a_method_folder_drew_no_graph(self):+ """A folder judged whole with no single pipe to start at still passes; the markdown says why no graph was drawn."""+ reason = "No graph was drawn, since a graph is drawn from one pipe: the folder declares several main pipes."+ result: dict[str, Any] = {+ "success": True,+ "bundle_path": "/fake/method",+ "validated_pipes": [{"pipe_ref": "first.one", "status": "SUCCESS"}, {"pipe_ref": "second.two", "status": "SUCCESS"}],+ "total_pipes": 2,+ "graph_unavailable": reason,+ }++ markdown = format_validate_markdown(result)++ assert markdown.startswith("# Validation passed")+ assert markdown.endswith(f"## Graph\n\n{reason}")+def test_omits_runnability_verdict_when_key_absent(self):"""The `validate all` / `validate pipe` shape omits the `pending_signatures` key entirely —so no runnability verdict (positive or negative) leaks onto those non-bundle surfaces.diff --git a/tests/unit/pipelex/test_extras/test_mthds_corpus_loader.py b/tests/unit/pipelex/test_extras/test_mthds_corpus_loader.pyindex 4adaec211..106845d70 100644--- a/tests/unit/pipelex/test_extras/test_mthds_corpus_loader.py+++ b/tests/unit/pipelex/test_extras/test_mthds_corpus_loader.py@@ -7,11 +7,14 @@ The bundles themselves are validated by the integration-tier entry gate; this molayout rules and the filter semantics a consumer selects on."""+from pathlib import Path+import pytestfrom pipelex.test_extras.mthds_corpus.exceptions import CorpusEntryError-from pipelex.test_extras.mthds_corpus.loader import get_entry, iter_entries-from pipelex.test_extras.mthds_corpus.manifest import EntryGranularity, EntryTier, EntryValidity+from pipelex.test_extras.mthds_corpus.loader import get_entry, iter_entries, load_entry+from pipelex.test_extras.mthds_corpus.manifest import MANIFEST_FILE_NAME, EntryGranularity, EntryTier, EntryValidity+from tests.helpers.method_folders import MethodFolderShape, write_method_folderclass TestMthdsCorpusLoader:@@ -25,6 +28,72 @@ class TestMthdsCorpusLoader:assert entry.manifest.name == entry.directory.nameassert entry.bundle_path.is_file()+ @pytest.mark.parametrize("shape", [MethodFolderShape.MANIFEST_MAIN_PIPE, MethodFolderShape.ONE_DECLARED_MAIN_PIPE])+ def test_an_entry_resolves_to_the_bundle_its_method_starts_at(self, tmp_path: Path, shape: MethodFolderShape) -> None:+ """The CLI's own entry rule picks the bundle, so a folder `run bundle` starts at one pipe is an entry as it stands."""+ entry_dir = self._entry_dir(tmp_path=tmp_path, shape=shape)+ assert shape.entry is not None++ entry = load_entry(directory=entry_dir)++ assert entry.bundle_path == (entry_dir / shape.entry.tree_path).resolve()++ @pytest.mark.parametrize("shape", [MethodFolderShape.SEVERAL_MAIN_PIPES, MethodFolderShape.NO_MAIN_PIPE])+ def test_an_entry_with_no_single_main_pipe_is_refused(self, tmp_path: Path, shape: MethodFolderShape) -> None:+ entry_dir = self._entry_dir(tmp_path=tmp_path, shape=shape)+ assert shape.refusal is not None++ with pytest.raises(CorpusEntryError) as exc_info:+ load_entry(directory=entry_dir)++ assert "Corpus entry 'sample_entry' does not resolve to a bundle" in str(exc_info.value)+ assert shape.refusal in str(exc_info.value)++ def test_an_entry_is_its_own_root_whatever_its_ancestors_hold(self, tmp_path: Path) -> None:+ """No Manifest Discovery: a `METHODS.toml` above the entry, as a project above `site-packages` may hold, is no part of it."""+ project_dir = tmp_path / "project"+ project_dir.mkdir()+ (project_dir / "METHODS.toml").write_text(+ '[package]\naddress = "github.com/pipelex-tests/project"\nversion = "1.0.0"\ndescription = "A project above the corpus"\n',+ encoding="utf-8",+ )+ (project_dir / "project.mthds").write_text(+ 'domain = "project_notes"\nmain_pipe = "take_note"\n\n[pipe.take_note]\ntype = "PipeLLM"\ndescription = "Take a note"\n'+ 'inputs = { text = "Text" }\noutput = "Text"\nprompt = "Note $text"\n',+ encoding="utf-8",+ )+ shape = MethodFolderShape.ONE_DECLARED_MAIN_PIPE+ entry_dir = self._entry_dir(tmp_path=project_dir, shape=shape)+ assert shape.entry is not None++ entry = load_entry(directory=entry_dir)++ assert entry.bundle_path == (entry_dir / shape.entry.tree_path).resolve()++ def test_an_entry_whose_one_bundle_the_rule_cannot_read_is_that_bundle(self, tmp_path: Path) -> None:+ """An invalid entry authored to trigger the refusal of its own `main_pipe` resolves to the bundle the refusal names."""+ entry_dir = self._entry_dir(tmp_path=tmp_path, shape=MethodFolderShape.ONE_DECLARED_MAIN_PIPE)+ for bundle_file in entry_dir.rglob("*.mthds"):+ bundle_file.unlink()+ unreadable = entry_dir / "bundle.mthds"+ unreadable.write_text('domain = "laundry_tickets"\nmain_pipe = "Not A Pipe Code"\n', encoding="utf-8")++ entry = load_entry(directory=entry_dir)++ assert entry.bundle_path == unreadable.resolve()++ @staticmethod+ def _entry_dir(*, tmp_path: Path, shape: MethodFolderShape) -> Path:+ entry_dir = write_method_folder(directory=tmp_path / "sample_entry", shape=shape)+ (entry_dir / MANIFEST_FILE_NAME).write_text(+ (+ 'name = "sample_entry"\ndescription = "A sample entry"\nvalidity = "valid"\n'+ 'tier = "dry"\ngranularity = "focused"\ncovers = ["native.text"]\n'+ ),+ encoding="utf-8",+ )+ return entry_dir+def test_entries_are_yielded_in_name_order(self) -> None:names = [entry.name for entry in iter_entries()]assert names == sorted(names)