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.
Pipe-refs — a bare pipe reference resolves inside its own domain (breaking) (#1099)
Louis Choquel86019fe16f44
diff --git a/.claude/skills/drift-review/SKILL.md b/.claude/skills/drift-review/SKILL.mdindex 11c40b024..54b2224c9 100644--- a/.claude/skills/drift-review/SKILL.md+++ b/.claude/skills/drift-review/SKILL.md@@ -2,8 +2,9 @@name: drift-reviewdescription: >Resolve open drift contracts — the review obligations between code and docs- declared in drift.toml. Use whenever `make drift-check` (or the `make check`- aggregate, or the CI lint-drift job) fails with open contracts, when the user+ declared in drift.toml. Use whenever `make drift-check` (or the `make+ agent-check` / `make check` aggregates, or the CI lint-drift job) fails with+ open contracts, when the usersays "drift check failed", "resolve the drift contract", "ack the drift","run drift plan", or after any change that touches drift trigger files (theconfig model / pipelex.toml, CLI code, the keyword-only guard). Also use whendiff --git a/.drift/acks/cli-docs.toml b/.drift/acks/cli-docs.tomlindex d2ae63d64..f5a505fd2 100644--- a/.drift/acks/cli-docs.toml+++ b/.drift/acks/cli-docs.toml@@ -1,8 +1,8 @@contract = "cli-docs"-digest = "sha256:447e5b76aca175977a2001577a3499453d659641d94c5807ef1dbe23c46f9909"+digest = "sha256:37ba3d59b8016e418d82b22c4a7a735c142d19bafd2fbbe856536d1a176de065"reviewed_by = "Louis Choquel"-reviewed_at = "2026-08-12T12:00:19Z"-rationale = "Trigger is a docstring-pointer removal across seven CLI modules: each ended with a see-the-spec tail naming a path in a private sibling repo that does not exist in this one, so every line was both a leak and a dead pointer for an OSS reader. They now say 'the codegen spec' and keep the section name, so the reader still learns which concept governs. No option, default, exit code, output contract or behavior changed - the diff is comment-only. Reviewed both targets: docs/tools/cli/ and pipelex/cli/agent_cli/CLAUDE.md carry no reference to that private path, to any private repo, or to any of the removed pointers (grepped), and nothing they document about resolve/codegen/build was touched. Neither target is stale; no doc change needed. (Re-recorded 2026-08-12: the original rationale was written with backticked paths, which the shell command-substituted away, and it quoted the private path verbatim.)"+reviewed_at = "2026-08-13T11:03:30Z"+rationale = "Review-fix round: the four edited CLI files only change a stderr failure-message prefix from a wrong 'not found'/'Could not find' verdict to a verdict-neutral one so ambiguity failures read truthfully. Reviewed both targets: docs/tools/cli (incl. build/runner|inputs|output pages and codegen surface) documents no error-message text for these commands, and the agent-CLI CLAUDE.md covers only the agent CLI these bare-CLI edits do not touch. No doc change needed."[trigger_files]"pipelex/cli/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"@@ -46,7 +46,7 @@ rationale = "Trigger is a docstring-pointer removal across seven CLI modules: ea"pipelex/cli/agent_cli/commands/run/pipe_cmd.py" = "blob:5e6f706722a884f1df51eb86695507d02f5b8064""pipelex/cli/agent_cli/commands/run/stdin_resolver.py" = "blob:4bc7f4e91ddb3900a75356f8f8e6ba5a586a3690""pipelex/cli/agent_cli/commands/validate/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/agent_cli/commands/validate/_validate_core.py" = "blob:c07252202265806ebe3512370152d2ebce8a7e78"+"pipelex/cli/agent_cli/commands/validate/_validate_core.py" = "blob:cd1dd07661fc5ce60971ed0d2c7579cba6da7861""pipelex/cli/agent_cli/commands/validate/app.py" = "blob:d2d0ed19288c2d1c25be1650dd962189fcdb3b86""pipelex/cli/agent_cli/commands/validate/bundle_cmd.py" = "blob:fd751a2176bc9d62f164b293ec83006d22947d89""pipelex/cli/agent_cli/commands/validate/method_cmd.py" = "blob:24ddeef224fa2d88781141467ef80c414d34f77a"@@ -57,19 +57,19 @@ rationale = "Trigger is a docstring-pointer removal across seven CLI modules: ea"pipelex/cli/commands/build/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/build/app.py" = "blob:0a96edab273c838aa9e0fae23646805c3a775e9d""pipelex/cli/commands/build/inputs/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/build/inputs/_inputs_core.py" = "blob:08b160de803a28126c1fafa1dc9fd9016d50b30d"+"pipelex/cli/commands/build/inputs/_inputs_core.py" = "blob:50317e058df75070722d2e29edab4537e6b7b438""pipelex/cli/commands/build/inputs/app.py" = "blob:2a7770c8294b8c2c1b4420ac00d6ffdfa50609bf""pipelex/cli/commands/build/inputs/bundle_cmd.py" = "blob:0cd99e9d307f46b8e8899bf7d5f3813563fcdf10""pipelex/cli/commands/build/inputs/method_cmd.py" = "blob:668e0b66e1c4df0451eeae7e57c2afac8706ad5b""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:8fb53146353cc5ecc27f95cb7b1aea9eeba81e47"+"pipelex/cli/commands/build/output/_output_core.py" = "blob:9ba47b88a3c0b6cbf3f8de5f9a4939373f64ceb8""pipelex/cli/commands/build/output/app.py" = "blob:67996650b99551fbd58be30e692688204d16935a""pipelex/cli/commands/build/output/bundle_cmd.py" = "blob:54c07aedb123eaaf2049965859e82b6d4800560d""pipelex/cli/commands/build/output/method_cmd.py" = "blob:2625da8d562ba4f66cf17890772c7a1a674c3bb9""pipelex/cli/commands/build/output/pipe_cmd.py" = "blob:eb0db8279c93fcff9d5fe4546f593d753282acb5""pipelex/cli/commands/build/runner/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/build/runner/_runner_core.py" = "blob:c8f2777f8d23bfde1d65d219d7bed8e82fc78721"+"pipelex/cli/commands/build/runner/_runner_core.py" = "blob:e4745231cb46547de93d83d1ac7a6db28ae81494""pipelex/cli/commands/build/runner/app.py" = "blob:b5aa321ed93dc2cb9b138e4a26bae9eb75c732b7""pipelex/cli/commands/build/runner/bundle_cmd.py" = "blob:5b5ca0628f0595a0c3aae9b539ae4e7e0c92a853""pipelex/cli/commands/build/runner/method_cmd.py" = "blob:0f497ffcae50d89483d8cf953c6dc03599bc2a5f"@@ -78,7 +78,7 @@ rationale = "Trigger is a docstring-pointer removal across seven CLI modules: ea"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"-"pipelex/cli/commands/codegen/inputs_cmd.py" = "blob:5e7c2025682d2cfab3b15deb03ef2b468d1e69e3"+"pipelex/cli/commands/codegen/inputs_cmd.py" = "blob:20738a9e42f0e5ef7ffc489093348af3cb4643a0""pipelex/cli/commands/codegen/types_cmd.py" = "blob:b7c9c7a3664c9fbe66f9b4c3c5ebf9ea1322445c""pipelex/cli/commands/crate_loading.py" = "blob:3d7d651931ecf1a15a3e2d72411b3212b55d74ef""pipelex/cli/commands/doctor_cmd.py" = "blob:3cc70c2844c48aa73b91cdf085864589f30bc7f8"@@ -115,15 +115,15 @@ rationale = "Trigger is a docstring-pointer removal across seven CLI modules: ea"pipelex/cli/commands/run/exceptions.py" = "blob:e9552226e597922b6ac0757f7b52eb880a2e1472""pipelex/cli/commands/run/method_cmd.py" = "blob:828bd9b9c72a0e1132e54241817e388c97d9adad""pipelex/cli/commands/run/pipe_cmd.py" = "blob:f92fcb94e3ad55cf5aeec366a59fa7a74bcc9667"-"pipelex/cli/commands/show_cmd.py" = "blob:73eca220d97e0d3bac3b713b109b477b9e6fd4c8"+"pipelex/cli/commands/show_cmd.py" = "blob:7974d91404ea93f05b16b05b9aef3c1a540b965d""pipelex/cli/commands/update_cmd.py" = "blob:06100ec3b9d6c66ca89a8c1536aa27983ae409ca""pipelex/cli/commands/validate/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/validate/_validate_core.py" = "blob:14cfbee9fc73a45fb5bc10486ced641d346e3424"+"pipelex/cli/commands/validate/_validate_core.py" = "blob:ac7133943c4d217d6afa4d84742d2d5551d9b9bc""pipelex/cli/commands/validate/app.py" = "blob:309061423af13f2f6c496a024306ad696af567ab""pipelex/cli/commands/validate/bundle_cmd.py" = "blob:1fbf3e0cf695db39101c83160a724df6468988e9""pipelex/cli/commands/validate/method_cmd.py" = "blob:2cb68d5c371a5b45841fce9c26da5e4622e6b042""pipelex/cli/commands/validate/pipe_cmd.py" = "blob:d67267571559006459628180f2c8b216ba7fee31"-"pipelex/cli/commands/which_cmd.py" = "blob:95fe153d65364449e26e9408c53441aa5fb4cf06"+"pipelex/cli/commands/which_cmd.py" = "blob:68661d4bab22e2c4dab183d59bd9f2c6dd573472""pipelex/cli/deck_notice.py" = "blob:542877125e89e35b02bc969cfee952155b0d7c2c""pipelex/cli/error_handlers.py" = "blob:ec4005ac908fac151275db3b28cc1685edd585b0""pipelex/cli/exceptions.py" = "blob:1d51c3a53ddd3f6cf8de566fa2ade3fa75ab7a3a"diff --git a/.drift/acks/hub-layering-convention.toml b/.drift/acks/hub-layering-convention.tomlindex 44d247599..bdd702774 100644--- a/.drift/acks/hub-layering-convention.toml+++ b/.drift/acks/hub-layering-convention.toml@@ -1,10 +1,10 @@contract = "hub-layering-convention"-digest = "sha256:3e934627754b382f5fc30bb5ebc920c258d7f8056283b4d7b1cdcd748710fb21"+digest = "sha256:cd4c268d3557cedc0f5594d73f3db9f9c6eea5781baa184fb29c82cb93c9b5b9"reviewed_by = "Louis Choquel"-reviewed_at = "2026-08-10T12:22:31Z"-rationale = "Trigger is a one-word rename leftover in hub_layering_guard.py's module-entry comment: it called pipelex.runtime_boot 'the runtime layer's composition root' while the same sentence went on to say what 'boot the kernel layer' costs — two names for one boundary in one sentence, in the file that defines the boundary. It survived the A0 sweep because the phrase spans a line break, so a line-oriented grep for 'runtime layer' could not see it. Reviewed docs/contribute/hub-layering.md end to end against the guard. The page carries no stale layer vocabulary (verified: zero hits for 'runtime layer' / 'runtime-layer'), and its declared-package list still matches KERNEL_LAYER_PACKAGES. One substantive edit, and it was a genuine contradiction rather than vocabulary: the paragraph on external plugins stated they are 'discovered through the pipelex.plugins entry-point group — a group identifier, not a module path, and unchanged', which is now false twice over (that group is retired and fails startup, and plugins declare their layer by choosing between two successors). The A3 doc sweep had deliberately left pipelex.plugins alone on this page because it is also the kernel-layer package name, and that carve-out over-applied to the one sentence that was explicitly about the group. Rewrote it to name both successor groups and added a parenthetical warning the reader that every OTHER mention of pipelex.plugins on the page is the package sense, since the collision is exactly the trap the carve-out was protecting against."+reviewed_at = "2026-08-13T09:17:09Z"+rationale = "Trigger is interpreter_hub.py arriving at this merge changed on both sides: the branch added the two public entry accessors get_required_entry_pipe and get_optional_entry_pipe, and dev renamed the layer vocabulary from runtime to kernel in two of its comments. Verified the page mechanically rather than by eye, because the staleness this contract exists to catch is an enumeration going quietly out of date: parsed both hub modules with ast for public module-level functions and checked every one against the doc -- 33 on interpreter_hub, 33 on runtime_hub, zero untabulated. The library-lookups row already lists both new accessors and the page already carries the paragraph on choosing between the strict in-body pair and the entry pair, plus the cross-package alias caveat; all of that merged in cleanly from this branch alongside dev's rename, so the tables and the prose agree with the merged modules. Zero occurrences of the stale runtime layer or runtime-layer vocabulary remain on the page. No layer boundary moved: both new symbols are interpreter-layer, live beside their siblings, and add no kernel-layer import, and check-hub-layering passes on the merged tree. Reviewed end to end; no doc change needed."[trigger_files]"pipelex/cli/dev_cli/commands/hub_layering_guard.py" = "blob:2dbadcbab7d44364a7b5f1d16268b23b26700a00"-"pipelex/interpreter_hub.py" = "blob:5db8f932bfb7161c86c4a3ea68e2a918b40b0b67"+"pipelex/interpreter_hub.py" = "blob:b8c35e37814f0e94c3bf1c364b06a98d0c22ee93""pipelex/runtime_hub.py" = "blob:7f538d2acb10f263d7e1b6907b42d37199cbc654"diff --git a/.drift/acks/pipelex-kernel-docs.toml b/.drift/acks/pipelex-kernel-docs.tomlindex 8c515e542..c729aa4c7 100644--- a/.drift/acks/pipelex-kernel-docs.toml+++ b/.drift/acks/pipelex-kernel-docs.toml@@ -1,8 +1,8 @@contract = "pipelex-kernel-docs"-digest = "sha256:6a613fed0ff7873b3e1e61fe9aee1d7b8c033bc2f6f7c886273a66294a0aa944"-reviewed_by = "Louis Choquel"-reviewed_at = "2026-08-12T12:00:30Z"-rationale = "Trigger is a comment-only pointer removal in compose_ops.py, func_ops.py and test_kernel_boot_contract.py: all three ended a paragraph with a see-also tail naming a wip/ doc that has since moved out of this repo, so the tails were dangling. Each comment already stated its own conclusion, so only the tail was dropped - the compose/func placement rationale and the distributed-orchestrator paragraph read exactly as before. No kernel entry point, signature or behavior changed. Reviewed docs/under-the-hood/pipelex-kernel.md: it cites neither moved doc, carries no private-repo reference, and its module table, completeness claim and Enforcement-table citation of test_kernel_boot_contract.py all still hold (that citation describes the test coverage, which this edit did not touch). Reviewed, no doc change needed. (Re-recorded 2026-08-12: the original rationale was written with backticked paths, which the shell command-substituted away.)"+digest = "sha256:73aafaa2a6d3151a0d8f775cd90e8648f4b8b57ac9808cdb94579a2ae59fd0f8"+reviewed_by = "Claude (Fable 5)"+reviewed_at = "2026-08-13T12:05:20Z"+rationale = "Trigger is the search_domain_codes to search_scope rename passing through shape_inputs (memory_ops.py) and the boot-contract mock swapping get_required_concept_from_concept_ref_or_code for get_required_entry_concept. Reviewed docs/under-the-hood/pipelex-kernel.md: its shape_inputs paragraph and code example name neither the renamed parameter nor the replaced provider method, and the smallest-provider description does not enumerate resolver method names, so every claim still holds. Reviewed, no doc change needed."[trigger_files]"pipelex/kernel/__init__.py" = "blob:c4f1b0fe2ccc17db9110733f71b612f4ac1ba4ce"@@ -19,9 +19,9 @@ rationale = "Trigger is a comment-only pointer removal in compose_ops.py, func_o"pipelex/kernel/llm_ops.py" = "blob:36a2e2f3a002e0c50ef4f645937b66573e46aa51""pipelex/kernel/llm_prompt_content.py" = "blob:26dfce734de582320c0ea7b9a09b01f2d1ca8627""pipelex/kernel/llm_results.py" = "blob:6e3b8a2878b5bb284ece5fac10262fb59ac2029d"-"pipelex/kernel/memory_ops.py" = "blob:c4d7fee0a5ac2c1292ad39d2c188b2a02b47d15b"+"pipelex/kernel/memory_ops.py" = "blob:f6a5745e804ac08f19c70f1beb1f78baf50d51cd""pipelex/kernel/pipelex_kernel.py" = "blob:ad13e02168590a1173d7db1e210b3cecd7059651""pipelex/kernel/prompt_references.py" = "blob:03ec9ef67ae84f141d072ca2d2c3ef888549ccc0""pipelex/kernel/search_ops.py" = "blob:01be4bef28f98342678cba16ac8c4b21fadcaae1""pipelex/kernel/search_results.py" = "blob:101b70dc96cc5ee1721c9f6b1cb725a5ca78ff70"-"tests/unit/pipelex/kernel/test_kernel_boot_contract.py" = "blob:b33847de92e0bb277e307b7c6bbd7b4d82cb839c"+"tests/unit/pipelex/kernel/test_kernel_boot_contract.py" = "blob:54910cb0569792d8ed654f183f0c2733abb1e88e"diff --git a/.test_durations b/.test_durationsindex 56f024b9d..0cd178889 100644--- a/.test_durations+++ b/.test_durations@@ -3,6 +3,10 @@"tests/e2e/pipelex/cli/test_csv_run.py::TestCsvRun::test_run_command_declares_save_csv[run_bundle_cmd]": 0.0004091669979970902,"tests/e2e/pipelex/cli/test_csv_run.py::TestCsvRun::test_run_command_declares_save_csv[run_method_cmd]": 0.0007009999972069636,"tests/e2e/pipelex/cli/test_csv_run.py::TestCsvRun::test_run_command_declares_save_csv[run_pipe_cmd]": 4.824598626015359,+ "tests/e2e/pipelex/cli/test_entry_bare_code_cmd.py::TestEntryBareCodeCommands::test_qualified_code_still_works": 0.04393037399995592,+ "tests/e2e/pipelex/cli/test_entry_bare_code_cmd.py::TestEntryBareCodeCommands::test_show_resolves_a_bare_code_from_another_domain": 0.04244987500010211,+ "tests/e2e/pipelex/cli/test_entry_bare_code_cmd.py::TestEntryBareCodeCommands::test_unknown_bare_code_still_reports_not_found": 0.0374195829999735,+ "tests/e2e/pipelex/cli/test_entry_bare_code_cmd.py::TestEntryBareCodeCommands::test_which_resolves_a_bare_code_from_another_domain": 0.40161554099995556,"tests/e2e/pipelex/cli/test_init_cmd_edge_cases.py::TestEdgeCases::test_pipelex_gateway_sets_all_pipelex_gateway": 5.124064292991534,"tests/e2e/pipelex/cli/test_init_cmd_edge_cases.py::TestEdgeCases::test_reset_all_with_flag": 0.9061137079988839,"tests/e2e/pipelex/cli/test_init_cmd_edge_cases.py::TestEdgeCases::test_single_non_pipelex_backend": 0.8590015010122443,@@ -437,6 +441,10 @@"tests/integration/pipelex/libraries/test_pipe_namespace.py::TestPipeNamespace::test_multi_bundle_same_domain": 0.44658504099061247,"tests/integration/pipelex/libraries/test_pipe_namespace.py::TestPipeNamespace::test_same_pipe_code_different_domains": 1.3240529159957077,"tests/integration/pipelex/libraries/test_pipe_namespace.py::TestPipeNamespace::test_wrong_domain_lookup_returns_not_found": 0.5623093320027692,+ "tests/integration/pipelex/libraries/test_unresolved_pipe_ref_message.py::TestUnresolvedPipeRefMessage::test_names_the_qualified_ref_and_explains_the_rule": 0.09353629200018077,+ "tests/integration/pipelex/libraries/test_unresolved_pipe_ref_message.py::TestUnresolvedPipeRefMessage::test_no_candidate_means_no_suggestion": 0.024905751000233067,+ "tests/integration/pipelex/libraries/test_unresolved_pipe_ref_message.py::TestUnresolvedPipeRefMessage::test_suggests_the_sibling_that_actually_declares_the_code": 0.030942874999936976,+ "tests/integration/pipelex/libraries/test_unresolved_pipe_ref_message.py::TestUnresolvedPipeRefMessage::test_two_domains_declaring_the_same_code_each_bind_their_own": 0.03714929200009465,"tests/integration/pipelex/phase1_hierarchical_domains/test_hierarchical_domains.py::TestHierarchicalDomainsAndPipeNamespacing::test_cross_domain_concept_ref_with_hierarchical_domain": 1.384776624996448,"tests/integration/pipelex/phase1_hierarchical_domains/test_hierarchical_domains.py::TestHierarchicalDomainsAndPipeNamespacing::test_cross_domain_pipe_ref_in_sequence": 1.3874971240002196,"tests/integration/pipelex/phase1_hierarchical_domains/test_hierarchical_domains.py::TestHierarchicalDomainsAndPipeNamespacing::test_deep_hierarchical_domain": 1.3844063340075081,@@ -541,8 +549,8 @@"tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_optional_sequence_boundary_converges_in_one_iteration": 1.3738710829929914,"tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_same_pipe_code_across_domains_patches_the_declaring_file_only": 1.6604569570044987,"tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_single_iteration_fixes_and_revalidates": 2.2543266249995213,- "tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_strip_namespace_bails_on_cross_file_collision[domain = \"nsfix_xfile\"\\n\\n[pipe.hola]\\ntype = \"PipeLLM\"\\ndescription = \"Bare hola, declared in a sibling bundle of the same domain.\"\\noutput = \"Text\"\\nprompt = \"Say hola\"\\n]": 2.3784738749964163,- "tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_strip_namespace_bails_on_cross_file_collision[domain = \"nsfix_xfile_other\"\\n\\n[pipe.hola]\\ntype = \"PipeLLM\"\\ndescription = \"Bare hola in another domain.\"\\noutput = \"Text\"\\nprompt = \"Say hola\"\\n]": 0.5152457909862278,+ "tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_strip_namespace_applies_despite_other_domain_sibling": 0.5152457909862278,+ "tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_strip_namespace_bails_on_same_domain_cross_file_collision": 2.3784738749964163,"tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_strip_namespace_converges_leaving_qualified_refs": 1.3183065819903277,"tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_strip_namespace_proceeds_past_sibling_signature_header": 2.061267416982446,"tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_strip_namespace_proceeds_past_unrelated_sibling": 1.6817289590107976,@@ -572,7 +580,7 @@"tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.py::TestPipelineRunSetupCharacterization::test_failure_after_acquire_restores_outer_current_library": 0.18409779197827447,"tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.py::TestPipelineRunSetupCharacterization::test_failure_when_outer_is_run_library_clears_instead_of_dangling": 0.3939949159976095,"tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.py::TestPipelineRunSetupCharacterization::test_load_failure_tears_down_library": 0.1400926240021363,- "tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.py::TestPipelineRunSetupCharacterization::test_search_domain_codes_list_is_mutated_in_place": 0.2934885819850024,+ "tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.py::TestPipelineRunSetupCharacterization::test_search_scope_is_derived_from_the_entry_pipe": 0.2934885819850024,"tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.py::TestPipelineRunSetupCharacterization::test_success_path_builds_dry_job_and_leaves_library_open": 1.3923876250046305,"tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.py::TestPipelineRunSetupCharacterization::test_success_path_leaves_no_per_run_reporting_state": 1.1907806250092108,"tests/integration/pipelex/pipeline/test_pipeline_run_setup_emit_gates.py::TestPipelineRunSetupEmitGates::test_costs_only_registers_usage_log_and_sets_flags": 1.3904512090084609,@@ -628,7 +636,7 @@"tests/integration/pipelex/pipeline/test_validate_bundle_library_lifecycle.py::TestValidateBundleLibraryLifecycle::test_validate_bundles_from_directory_tears_down_library_on_translated_error": 0.4914957089931704,"tests/integration/pipelex/pipeline/test_validate_bundle_library_lifecycle.py::TestValidateBundleRestoresOuterLibraryOnFailure::test_validate_bundle_restores_previous_current_library": 0.29557849999400787,"tests/integration/pipelex/pipeline/test_validate_bundle_library_lifecycle.py::TestValidateBundleRestoresOuterLibraryOnFailure::test_validate_bundles_from_directory_restores_previous_current_library": 0.7135502500022994,- "tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.py::TestValidateBundleLoadedOnSuccess::test_get_required_pipe_works_after_successful_validation": 1.734181040985277,+ "tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.py::TestValidateBundleLoadedOnSuccess::test_entry_pipe_resolves_after_successful_validation": 1.734181040985277,"tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.py::TestValidateBundleLoadedOnSuccess::test_runner_code_ops_resolves_pipe_after_inner_sweep": 0.9875382080062991,"tests/integration/pipelex/pipeline/test_validate_bundle_return_placement.py::TestValidateBundleResultConstructionErrorTranslation::test_validate_bundle_translates_result_construction_error": 1.4922394989989698,"tests/integration/pipelex/pipeline/test_validate_bundle_return_placement.py::TestValidateBundleResultConstructionErrorTranslation::test_validate_bundles_from_directory_translates_result_construction_error": 0.7523452490131604,@@ -653,6 +661,7 @@"tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py::TestValidateBundleStructuredErrors::test_unresolved_concept_is_a_categorized_pipe_validation_item": 1.1809741260076407,"tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py::TestValidateBundleStructuredErrors::test_unresolved_pipe_dependency_is_a_categorized_pipe_validation_item": 0.12183566601015627,"tests/integration/pipelex/pipeline/test_validate_graph_registry_sources.py::TestValidateGraphRegistrySources::test_registry_entries_include_source_from_mthds_sources": 2.517247125011636,+ "tests/integration/pipelex/pipes/controller/pipe_batch/test_batch_adhoc_pipe_ref.py::TestBatchAdhocPipeRef::test_batching_a_qualified_sub_pipe_warns_about_nothing": 0.15122933399970862,"tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_branch_dispatch.py::TestPipeBatchBranchDispatch::test_branches_dispatch_through_the_hook": 2.0623111670138314,"tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_branch_dispatch.py::TestPipeBatchBranchDispatch::test_fan_out_bound_comes_off_the_payload_not_live_config": 1.3012292920029722,"tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_compaction.py::TestPipeBatchCompaction::test_absent_branch_results_are_dropped": 3.745481167003163,@@ -5058,23 +5067,23 @@"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemory::test_implicit_memory_case[case-2.7-dictstuff-instance-simple-stuff_content_or_data16-stuff_name-stuff_code-expected_stuff16]": 0.12995875100023113,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemory::test_implicit_memory_case[case-2.8-dictstuff-instance-native-stuff_content_or_data17-stuff_name-stuff_code-expected_stuff17]": 0.11922091599262785,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemory::test_implicit_memory_case[case-2.9-dictstuff-instance-list-dicts-stuff_content_or_data18-stuff_name-stuff_code-expected_stuff18]": 0.15332654198573437,- "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-bool-for-non-yes-no-concept-stuff_content_or_data9-stuff_name-stuff_code-search_domain_codes9-Exception-native.YesNo]": 0.10343462499440648,+ "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-bool-for-non-yes-no-concept-stuff_content_or_data9-stuff_name-stuff_code-test_domain-Exception-native.YesNo]": 0.10343462499440648,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-concept-not-found-stuff_content_or_data4-stuff_name-stuff_code-None-Exception-not found]": 0.13274066598387435,- "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-date-object-for-non-date-concept-stuff_content_or_data11-stuff_name-stuff_code-search_domain_codes11-Exception-native.Date]": 0.11409341600665357,+ "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-date-object-for-non-date-concept-stuff_content_or_data11-stuff_name-stuff_code-test_domain-Exception-native.Date]": 0.11409341600665357,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-dict-with-extra-keys-stuff_content_or_data7-stuff_name-stuff_code-None-Exception-exactly keys]": 0.14210591699520592,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-dict-without-concept-stuff_content_or_data5-stuff_name-stuff_code-None-Exception-'concept' key]": 0.11270716700528283,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-dict-without-content-stuff_content_or_data6-stuff_name-stuff_code-None-Exception-'content' key]": 0.10964433399203699,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-empty-list-content-stuff_content_or_data1-stuff_name-stuff_code-None-Exception-empty ListContent]": 0.13320783301605843,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-empty-list-stuff_content_or_data0-stuff_name-stuff_code-None-Exception-empty list]": 0.5606422490091063,- "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-incompatible-concept-for-string-stuff_content_or_data8-stuff_name-stuff_code-search_domain_codes8-Exception-not compatible]": 0.17798224999569356,+ "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-incompatible-concept-for-string-stuff_content_or_data8-stuff_name-stuff_code-test_domain-Exception-not compatible]": 0.17798224999569356,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-mixed-types-in-list-content-stuff_content_or_data3-stuff_name-stuff_code-None-Exception-items are not of the same type]": 0.12971208400267642,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-mixed-types-in-list-stuff_content_or_data2-stuff_name-stuff_code-None-Exception-items are not of the same type]": 0.09897070900478866,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-non-iso-string-for-date-concept-stuff_content_or_data12-stuff_name-stuff_code-None-Exception-ISO 8601]": 0.2983442090044264,"tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryErrors::test_error_case[error-string-for-yes-no-concept-stuff_content_or_data10-stuff_name-stuff_code-None-Exception-not compatible]": 0.1418805830180645,- "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryWithSearchDomains::test_search_domain_case[search-domain-dict-stuff_content_or_data3-stuff_name-stuff_code-search_domain_codes3-expected_stuff3]": 0.17483416800678242,- "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryWithSearchDomains::test_search_domain_case[search-domain-list-content-stuff_content_or_data2-stuff_name-stuff_code-search_domain_codes2-expected_stuff2]": 0.18126750100054778,- "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryWithSearchDomains::test_search_domain_case[search-domain-list-stuff-content-stuff_content_or_data1-stuff_name-stuff_code-search_domain_codes1-expected_stuff1]": 0.11008366700843908,- "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryWithSearchDomains::test_search_domain_case[search-domain-stuff-content-stuff_content_or_data0-stuff_name-stuff_code-search_domain_codes0-expected_stuff0]": 0.4796880420180969,+ "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryWithSearchDomains::test_search_domain_case[search-domain-dict-stuff_content_or_data3-stuff_name-stuff_code-test_domain-expected_stuff3]": 0.17483416800678242,+ "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryWithSearchDomains::test_search_domain_case[search-domain-list-content-stuff_content_or_data2-stuff_name-stuff_code-test_domain-expected_stuff2]": 0.18126750100054778,+ "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryWithSearchDomains::test_search_domain_case[search-domain-list-stuff-content-stuff_content_or_data1-stuff_name-stuff_code-test_domain-expected_stuff1]": 0.11008366700843908,+ "tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py::TestStuffFactoryImplicitMemoryWithSearchDomains::test_search_domain_case[search-domain-stuff-content-stuff_content_or_data0-stuff_name-stuff_code-test_domain-expected_stuff0]": 0.4796880420180969,"tests/unit/pipelex/core/stuffs/test_stuff_verify_content_type.py::TestVerifyContentType::test_verify_content_type_with_list_content_generic_raises_helpful_error": 1.0396008329989854,"tests/unit/pipelex/core/stuffs/test_stuff_verify_content_type.py::TestVerifyContentType::test_verify_content_type_with_matching_type_works": 0.0010795830166898668,"tests/unit/pipelex/core/stuffs/test_stuff_verify_content_type.py::TestVerifyContentType::test_verify_content_type_with_mismatched_type_raises_error": 0.11256000101275276,@@ -5746,33 +5755,53 @@"tests/unit/pipelex/libraries/test_contract_match.py::TestContractsMatchPresenceMarkers::test_differing_output_markers_do_not_match": 0.00103570798819419,"tests/unit/pipelex/libraries/test_contract_match.py::TestContractsMatchPresenceMarkers::test_equivalent_spellings_with_same_marker_match": 0.8389882500050589,"tests/unit/pipelex/libraries/test_contract_match.py::TestContractsMatchPresenceMarkers::test_multiplicity_suffixes_stay_distinct": 0.10154887600219809,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_ambiguous_bare_pipe_ref_raises": 0.001828584005124867,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_bare_cross_domain_pipe_refs_resolve_to_the_declaring_domain": 0.003480582992779091,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_deep_reverse_refinement_chain_flattens_without_recursion": 0.03602812498866115,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_fingerprint_recomputed_and_version_stamped": 0.0032820839987834916,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_in_body_concept_refs_fully_qualified": 0.0016918320179684088,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_multi_hop_native_backed_chain_keeps_refines": 0.0014170000213198364,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_non_domain_qualified_key_raises": 0.11562333400070202,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_normalization_is_idempotent": 0.0031348749907920137,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_normalized_crate_is_closed_over_its_pipe_refs[_authored_crate]": 0.00290529198537115,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_normalized_crate_is_closed_over_its_pipe_refs[_cross_domain_crate]": 0.0031649169977754354,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_pipe_io_refs_qualified_with_multiplicity_preserved": 0.0030084580066613853,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_referenced_natives_are_materialized": 0.004105959014850669,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_refinement_cycle_has_explicit_diagnostic": 0.0008503739954903722,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_refinement_resolution_work_is_linear_in_chain_length": 0.022476247992017306,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_refinement_with_structured_base_is_flattened": 0.0019546670228010044,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_refinement_with_structured_native_base_keeps_refines": 0.0012551649997476488,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_refinement_with_structureless_native_base_keeps_refines": 0.0024196669983211905,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_sequence_step_pipe_refs_qualified": 0.0032190830097533762,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_special_outcomes_are_left_alone": 0.003210958995623514,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_string_concept_promoted_to_blueprint": 0.8847133749950444,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_unreferenced_natives_absent": 0.0020662089809775352,- "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_unresolvable_bare_pipe_ref_raises": 0.0012112080003134906,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_bare_pipe_ref_matching_nothing_is_qualified_not_raised": 0.0003327090000766475,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_bare_pipe_refs_qualify_to_their_own_domain_not_a_siblings": 0.001124790999938341,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_deep_reverse_refinement_chain_flattens_without_recursion": 0.028149707999773455,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_fingerprint_recomputed_and_version_stamped": 0.0010681669998575671,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_in_body_concept_refs_fully_qualified": 0.0010402499999599968,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_multi_hop_native_backed_chain_keeps_refines": 0.0014465409997228562,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_non_domain_qualified_key_raises": 0.002191458000197599,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_normalization_is_idempotent": 0.0017361259999688627,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_normalized_crate_is_closed_over_its_pipe_refs[_authored_crate]": 0.0010898749999341817,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_normalized_crate_is_closed_over_its_pipe_refs[_closed_all_kinds_crate]": 0.00144262499998149,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_own_domain_ref_resolves": 0.0010170010000365437,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_own_domain_wins_when_two_domains_declare_the_code": 0.0014532090001466713,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_pipe_io_refs_qualified_with_multiplicity_preserved": 0.0010415829999601556,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_referenced_natives_are_materialized": 0.00109350100001393,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_refinement_cycle_has_explicit_diagnostic": 0.0003127919999315054,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_refinement_resolution_work_is_linear_in_chain_length": 0.014211998999826392,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_refinement_with_structured_base_is_flattened": 0.0009928340000442404,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_refinement_with_structured_native_base_keeps_refines": 0.0015555840002434707,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_refinement_with_structureless_native_base_keeps_refines": 0.0009893339999962336,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_sequence_step_pipe_refs_qualified": 0.001029916999868874,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_special_outcomes_are_left_alone": 0.0011395839999295276,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_string_concept_promoted_to_blueprint": 0.05888304099994457,+ "tests/unit/pipelex/libraries/test_crate_normalization.py::TestCrateNormalization::test_unreferenced_natives_absent": 0.0010303750000275613,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_a_second_domain_declaring_the_code_is_not_an_ambiguity": 0.0006256259998735914,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_a_step_naming_a_pipe_called_continue_is_still_qualified": 0.0005879999998796848,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_bare_pipe_ref_is_the_owner_domains_even_when_only_a_sibling_declares_it": 0.000636709000218616,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_batch_branch_ref": 0.000549291000197627,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_concept_refines": 0.06094649799979379,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_condition_outcome_refs": 0.0005489590002980549,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_cross_package_refs_pass_through_untouched": 0.0006193339997935254,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_input_crate_is_not_mutated": 0.0005854159996943054,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_is_idempotent": 0.0009227490002103877,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_multiplicity_markers_survive_qualification": 0.0005945409998275863,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_parallel_branch_refs": 0.0005362510000850307,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_pipe_io_refs": 0.0005614170001990715,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_rejects[unqualified-concept-key]": 0.0003953750001528533,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_rejects[unqualified-pipe-key]": 0.001894374999892534,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_sequence_step_refs": 0.0005342499998732819,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_special_outcomes_pass_through_untouched": 0.0006327920002604515,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_string_described_concept_passes_through": 0.000549832999922728,+ "tests/unit/pipelex/libraries/test_crate_qualification.py::TestCrateQualification::test_structure_field_refs": 0.0006574169999566948,"tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py::TestDependencyMultiFileReconciliation::test_signature_and_concrete_sibling_reconcile_to_concrete": 0.9443139590002829,"tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py::TestDependencyMultiFileReconciliation::test_two_concrete_definitions_raise": 0.17803333299525548,"tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py::TestDependencyMultiFileReconciliation::test_typeless_header_and_concrete_sibling_reconcile_to_concrete": 0.14340691598772537,"tests/unit/pipelex/libraries/test_dependency_preliminary_text_export.py::TestDependencyPreliminaryTextExport::test_synthetic_helpers_are_filtered_when_parent_is_not_exported": 0.14782650100823957,"tests/unit/pipelex/libraries/test_dependency_preliminary_text_export.py::TestDependencyPreliminaryTextExport::test_synthetic_helpers_load_when_parent_is_exported": 0.8725465410097968,+ "tests/unit/pipelex/libraries/test_dependency_ref_qualification.py::TestDependencyRefQualification::test_dependency_in_body_ref_is_qualified_to_its_own_domain": 0.06925670900022851,"tests/unit/pipelex/libraries/test_domain_library.py::TestDomainLibrary::test_add_different_domains": 0.0002433329791529104,"tests/unit/pipelex/libraries/test_domain_library.py::TestDomainLibrary::test_add_domain_idempotent": 0.7598033750109607,"tests/unit/pipelex/libraries/test_domain_library.py::TestDomainLibrary::test_conflict_keeps_first_and_warns": 0.23275487500359304,@@ -5849,27 +5878,33 @@"tests/unit/pipelex/libraries/test_mthds_version_warning.py::TestMthdsVersionWarning::test_warning_emitted_for_dependency_mthds_version": 0.13626654198742472,"tests/unit/pipelex/libraries/test_mthds_version_warning.py::TestMthdsVersionWarning::test_warning_emitted_when_version_unsatisfied": 0.7355622489994857,"tests/unit/pipelex/libraries/test_mthds_version_warning.py::TestMthdsVersionWarning::test_warning_on_unparseable_constraint": 0.0016234170034294948,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_add_new_pipe_multi_domain": 0.0009828749898588285,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_bare_code_ambiguous_raises": 0.0006290009914664552,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_bare_code_no_match_returns_none": 0.00030287601111922413,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_bare_code_unambiguous": 0.0013705420133192092,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_cross_package_ref_bare_code_unambiguous": 0.0004964159888913855,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_cross_package_ref_with_pipe_ref": 0.0004695830139098689,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_cross_package_ref_wrong_domain": 0.0003642499796114862,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_get_required_pipe_domain_mismatch_raises_not_found": 0.0009385410085087642,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_get_required_pipe_malformed_raises_not_found": 0.000591250995057635,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_cross_package_ref_returns_none[lib->.foo]": 0.000934750001761131,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_cross_package_ref_returns_none[lib->foo..bar]": 0.0007999579975148663,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_cross_package_ref_returns_none[lib->foo.]": 0.0016567079874221236,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_dotted_ref_returns_none[.foo]": 0.0006850009958725423,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_dotted_ref_returns_none[foo..bar]": 0.0007668740145163611,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_dotted_ref_returns_none[foo.]": 0.000806458992883563,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_multi_domain_coexistence": 0.00126787499175407,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_pipe_ref_lookup": 0.7205511260108324,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_pipe_ref_wrong_domain_returns_none": 0.0015808750031283125,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_remove_pipes_by_refs": 0.0700712910038419,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_same_code_different_domains_no_collision": 0.0010602920083329082,- "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_same_pipe_ref_collision_raises": 0.0011310409900033846,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_add_new_pipe_multi_domain": 0.0003558339999472082,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_bare_code_does_not_resolve_in_body": 0.0003102499999840802,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_bare_code_no_match_returns_none": 0.00023737500009701762,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_cross_package_ref_bare_code_unambiguous": 0.00030137599992485775,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_cross_package_ref_with_pipe_ref": 0.0006563340000411699,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_cross_package_ref_wrong_domain": 0.0003095409997513343,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_entry_pipe_ambiguous_bare_code_raises": 0.00041162500019709114,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_entry_pipe_bare_code_matches_across_domains": 0.0003436670001519815,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_entry_pipe_exact_ref_hits_directly": 0.0003250829997796245,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_entry_pipe_ignores_aliased_dependency_entries": 0.0003399590000299213,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_entry_pipe_no_match_returns_none": 0.00022049899985177035,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_entry_pipe_reaches_a_pipe_no_export_released": 0.0003337509999710164,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_entry_pipe_required_raises_not_found": 0.00025987499998336716,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_get_required_pipe_domain_mismatch_raises_not_found": 0.00030854199962959683,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_get_required_pipe_malformed_raises_not_found": 0.00025945699985641113,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_cross_package_ref_returns_none[lib->.foo]": 0.0002692089999527525,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_cross_package_ref_returns_none[lib->foo..bar]": 0.00030795799989391526,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_cross_package_ref_returns_none[lib->foo.]": 0.0002730000001065491,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_dotted_ref_returns_none[.foo]": 0.0002583759999197355,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_dotted_ref_returns_none[foo..bar]": 0.0002717919999213336,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_malformed_dotted_ref_returns_none[foo.]": 0.0002549160001308337,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_multi_domain_coexistence": 0.00033766699993975635,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_pipe_ref_lookup": 0.05808500000011918,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_pipe_ref_wrong_domain_returns_none": 0.00032816599991747353,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_remove_pipes_by_refs": 0.0018525399998452485,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_same_code_different_domains_no_collision": 0.00034733200004666287,+ "tests/unit/pipelex/libraries/test_pipe_library_lookup.py::TestPipeLibraryLookup::test_same_pipe_ref_collision_raises": 0.0004021659997306415,"tests/unit/pipelex/libraries/test_standalone_reserved_domains.py::TestStandaloneReservedDomains::test_manifest_error_non_reserved_domain_passes": 0.15459591599937994,"tests/unit/pipelex/libraries/test_standalone_reserved_domains.py::TestStandaloneReservedDomains::test_manifest_error_still_checks_reserved_domains[mthds]": 0.05167237500427291,"tests/unit/pipelex/libraries/test_standalone_reserved_domains.py::TestStandaloneReservedDomains::test_manifest_error_still_checks_reserved_domains[native]": 0.05466820900619496,diff --git a/AGENTS.md b/AGENTS.mdindex 44aef9088..568c783a3 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -9,7 +9,7 @@```bashmake agent-check# If the current system doesn't have the `make` command,- # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format generate-mthds-schema lint pyright mypy check-keyword-only)+ # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-keyword-only check-hub-layering drift-check)```This runs multiple code quality tools:@@ -17,6 +17,7 @@- Ruff: Fix unused imports, lint, format- Mypy: Static type checker- plxt: Format and lint TOML, MTHDS, and PLX files+ - Drift contracts: open code↔docs review obligations fail the gate (note the digest reads the git index, so stage your changes for the check to see them)Always fix any issues reported by these tools before proceeding.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ac6778e2a..5207a8fee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,20 @@## [Unreleased]+### Changed++- **A bare pipe reference resolves inside its own domain (Breaking)**: An in-body pipe reference — a sequence step, a parallel branch, a condition outcome, a `batch_over` target — written without a domain now means the referring pipe's own domain, and is never searched for elsewhere. Previously `PipeLibrary` resolved a bare code by scanning every domain, so a pipe could reach a pipe in a domain nobody named; because the MTHDS visibility rules deliberately exempt bare references from the `[exports]` check (they were never supposed to leave home), that search made `[exports]` unenforceable through the one reference form exempt from checking it. Referencing another domain now requires writing that domain out, and validation names the reference it actually tried, explains the rule, and suggests the qualified spelling when some other domain declares the code. Across every `.mthds` tree in this workspace, two references need that one-word fix. This supersedes v0.43.0's *Cross-domain pipe refs in normalized crates*: the two readers still agree, but they now agree on owner-domain qualification rather than on a crate-wide search, and a single shared pass — not a rule restated per consumer — is what keeps them from diverging.+- **Bare pipe codes you type yourself keep working**: `pipelex run`/`show`/`which`, the builder operations, and the pipe code on an API request go through a named entry affordance (`get_optional_entry_pipe` / `get_required_entry_pipe`, exposed on `interpreter_hub`) that still matches a bare code across domains — you are pointing at a pipe, not writing a reference — and raises naming the candidates when two domains declare it. It deliberately ignores `[exports]`, since package visibility governs what one method may reference from inside another, not what a human may invoke. Installed dependency packages are excluded from that search, so adding a dependency cannot make one of your own codes ambiguous. `pipelex validate pipe` and `pipelex show pipe` report that ambiguity as a clean error naming the candidates (like `pipelex which` does) instead of letting it escape as a traceback.+- **Two domains may reuse a pipe code again**: The standard blesses this as a no-conflict case, and the crate-wide search had turned it into a load failure the moment anything referenced the code bare. Reusing a code across domains is a working configuration once more.+- **Concept codes in inputs resolve through an entry affordance, and `search_domain_codes` is gone (Breaking)**: A bare concept code a caller supplies in an input envelope (`{"concept": "Memo", ...}`) now prefers the entry pipe's own domain, then falls back to a unique library-wide match; a code two domains declare raises an error naming the candidates instead of silently depending on load order, and installed dependency packages are excluded from the search so adding one cannot make a host code ambiguous. When the entry pipe itself comes from a dependency package, the preference is package-scoped (`alias->domain`) and the rest of that package is searched before the host crate, so a multi-domain dependency's concepts stay reachable from any of its entry pipes; dotted refs obey the same scope-wins precedence, and `alias->Concept` explicitly searches the named package. The `search_domain_codes: list[str]` parameter is removed from the public surface (`PipelexMTHDSProtocol`, `pipeline_run_setup`, `prepare_pipe_job`, `shape_inputs`, `WorkingMemoryFactory.make_from_pipeline_inputs`, `StuffFactory.make_stuff_from_stuff_content_or_data` — replaced by `search_scope: str | None` derived from the entry pipe), and `ConceptProviderAbstract.get_required_concept_from_concept_ref_or_code` is replaced by `get_required_entry_concept`. This also removes latent defects in the old multi-domain walk: it died on the first domain that lacked the code, and the miss escaped as `ConceptLibraryError` — a class the input-shaping handlers do not catch; every entry-lookup refusal — invalid string, miss, ambiguity — is now `ConceptLibraryConceptNotFoundError`.+- **`pipelex fix` rename collisions are scoped per-domain**: The fix loop's cross-file collision guard dropped a `strip-namespace` rename whenever ANY loaded bundle declared the same bare code — but the library keys pipes by `domain.code`, so only a same-domain sibling can actually collide. Two same-named pipes in different domains now rename independently; a same-domain duplicate still bails loudly.+- **`make agent-check` now runs the drift-contracts gate**: An open code↔docs review obligation fails the agent quality gate locally instead of surfacing only in `make check` or CI. The digest reads the git index, so stage changes for the gate to see them; resolve open contracts with the documented drift workflow.+- **`missing_pipe_code` on an unresolved-dependency validation item is now the qualified ref (Breaking)**: The structured error field carries the reference that was actually tried (`marketing.render_html`), not the bare spelling the author wrote. Machine consumers branching on this field see a domain-qualified value where they previously saw a bare code.++### Fixed++- **Pipe-lookup CLI failures no longer claim "not found" for every failure**: `pipelex codegen inputs` and the `build runner`/`build inputs`/`build output` commands printed a "not found"/"Could not find" prefix on any lookup failure, including an ambiguous bare code — contradicting the ambiguity message printed underneath. The prefix is now verdict-neutral and the underlying error states whether the code was missing or ambiguous.+## [v0.43.1] - 2026-08-12### Changeddiff --git a/CLAUDE.md b/CLAUDE.mdindex c8d8f21a7..a47ff0dbf 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -9,7 +9,7 @@```bashmake agent-check# If the current system doesn't have the `make` command,- # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format generate-mthds-schema lint pyright mypy check-keyword-only)+ # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-keyword-only check-hub-layering drift-check)```This runs multiple code quality tools:@@ -17,6 +17,7 @@- Ruff: Fix unused imports, lint, format- Mypy: Static type checker- plxt: Format and lint TOML, MTHDS, and PLX files+ - Drift contracts: open code↔docs review obligations fail the gate (note the digest reads the git index, so stage your changes for the check to see them; resolve with the drift workflow below)Always fix any issues reported by these tools before proceeding.@@ -143,7 +144,7 @@.venv/bin/pipelex-dev refresh-graph-ui-sri --mthds-ui-version 0.6.3 --elkjs-version 0.11.1```- - **`drift`**: Drift contracts — deterministic review obligations between code and docs, declared in the root `drift.toml` (see `docs/contribute/drift-contracts.md`). When `make drift-check` (part of `make check` and CI) reports an open contract: run `make drift-plan` to see what changed and what to review, actually review the targets and fix what is stale, `git add` the trigger files (the digest reads the git index, not the working tree), then record the review with `make drift-ack CONTRACT=<id> RATIONALE="…"`. The rationale is the on-the-record review decision — write an honest sentence. There is no bypass flag; "reviewed, no doc change needed" is a legitimate rationale.+ - **`drift`**: Drift contracts — deterministic review obligations between code and docs, declared in the root `drift.toml` (see `docs/contribute/drift-contracts.md`). When `make drift-check` (part of `make agent-check`, `make check`, and CI) reports an open contract: run `make drift-plan` to see what changed and what to review, actually review the targets and fix what is stale, `git add` the trigger files (the digest reads the git index, not the working tree), then record the review with `make drift-ack CONTRACT=<id> RATIONALE="…"`. The rationale is the on-the-record review decision — write an honest sentence. There is no bypass flag; "reviewed, no doc change needed" is a legitimate rationale.```bashmake drift-plandiff --git a/Makefile b/Makefileindex bd56d9d3e..8e3df9ad7 100644--- a/Makefile+++ b/Makefile@@ -1162,7 +1162,7 @@ up: generate-mthds-schema-quiet update-gateway-models-quiet up-kit-configs rulescheck: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet update-gateway-models-quiet check-unused-imports check-config-sync check-rules check-urls check-gateway-models check-mthds-schema check-keyword-only check-hub-layering drift-check format lint pyright mypy pylint@echo "> done: check"-agent-check: fix-unused-imports fix-keyword-only format lint pyright mypy check-keyword-only check-hub-layering+agent-check: fix-unused-imports fix-keyword-only format lint pyright mypy check-keyword-only check-hub-layering drift-check@echo "> done: agent-check"v: validatediff --git a/TODOS.md b/TODOS.mdnew file mode 100644index 000000000..1a703391a--- /dev/null+++ b/TODOS.md@@ -0,0 +1,286 @@+# Pipe-refs build-time qualification — implementation plan++Source of truth for the design: [wip/pipe-refs/build-time-qualification.md](wip/pipe-refs/build-time-qualification.md) (decided 2026-08-11). Evidence and pre-change state: [wip/pipe-refs/README.md](wip/pipe-refs/README.md). Venue: the `_refs` worktree — treat this worktree as the repo root.++**What we are doing in one sentence:** bare in-body references (pipe steps, branches, outcomes, batch refs, concept I/O refs) get qualified to their owner domain once, at library build time, via one shared crate pass consumed by both the normalizer and `library_manager`; the live library lookup becomes strict; the crate-wide bare search survives only as an explicitly-named entry-point affordance for user-supplied codes.++**Why it matters beyond tidiness:** no-fall-through is what makes `[exports]` enforceable. A visibility rule the resolver can reach around is not a visibility rule. Keep that argument at the front of every discussion about this change — it is the reason the blast radius is worth paying.++## The resolution rule, in one picture++```+in-body ref encountered+ |+ +-- contains "alias->" ? --YES--> cross-package: pass leaves it ALONE+ | (resolved against the child library)+ NO+ |+ +-- already qualified "d.c" ? --YES--> unchanged (pass is idempotent)+ |+ NO (bare code "c")+ |+ v+ qualify to the OWNER domain of the declaring pipe --> "own_domain.c"+ |+ | existence is NOT checked here+ v+ ordinary dependency validation+ |+ +-- resolves ? --YES--> done+ |+ NO+ v+ error names the ref that was tried, and suggests a crate-wide+ candidate when one exists (diagnostic scan, FAILURE PATH ONLY —+ this is not a resolution fallback)+```++Entry-shaped lookups (a human typing a pipe code at a CLI) do NOT follow that rule. They go through the entry affordance, which searches crate-wide, refuses ambiguity, and deliberately ignores `[exports]` — a hand-invoked pipe is not an in-body reference, so package visibility does not apply.++## Rules of engagement++- **Checkpoints are mandatory stops.** At each ⛔ CHECKPOINT below, the agent MUST stop working, complete the checkpoint checklist (status updates, gates, commit), and end the session. Do not roll into the next phase in the same session, even if context feels fresh. The next session cold-starts from this file's Status block plus the design doc.+- **Update this file as you go.** Tick checkboxes when items complete; record decisions in the Status block the moment they are taken, not at the end.+- **Open questions from the design** are folded into the phase tasks below as explicit decision items (marked OQ1/OQ2/OQ3). Record each ruling in the Status block and in the design doc. OQ1 is a go/no-go gate in Phase 0, not an implementation task.++### Gates — the full checklist, run at every checkpoint++`make agent-check` and `make agent-test` do not cover everything this plan disturbs. Three of the gaps fail silently, which is why this is a checklist and not a sentence.++1. `make agent-check` clean.+2. Full `make agent-test` green.+3. **`git add` the work, THEN `make drift-check`.** `agent-check` does not run `drift-check`, so a contract never opens "along the way" under the other gates. And `drift-check` reads the git *index*, so unstaged work reads as a false green. If a contract opens, resolve it via the drift-review flow — no bypassing.+4. **Reconcile `.test_durations`** after any test file, class, or function is renamed or repurposed. This plan repurposes named tests in both the normalizer and lookup suites. Orphan node ids are silent — pytest-split treats an unknown id as average duration. Collect with `.venv/bin/pytest --collect-only -q -m ""`; the marker filter in `addopts` hides a large slice of the suite (mostly `tests/e2e`) and makes every e2e entry look like an orphan.+5. **Record the subject grant BEFORE the first `agent-check` on the new module.** `agent-check` runs `fix-keyword-only`, which silently rewrites an ungranted positional subject to keyword-only. If the pass is meant to read as a verb–object sentence (`qualify_crate(crate)`), `make subject-grant` has to land first or the shape is gone before anyone decides.++## Status++- **Current phase:** Phase 4a item 1 DONE (2026-08-13); 4a item 2 (transport-boundary spec edit) deliberately HELD to land together with its 4b verifying conformance test. **Phase 4b is blocked on user action:** merge PR #1099 (`fix/Pipe-refs-3` → dev), then cut a `pipelex` release carrying the `interpreter_hub` entry-pipe accessors — every 4b item needs that release installable by the sibling repos. The transport spec/test pair to touch in 4b: `docs/specs/pipelex-transport-boundary.md` §"The allowed import surface" (workspace root) + `conformance/tests/pipelex_transport/test_provider_surface.py` (the allowed-surface list lives in `test_data.py::TransportBoundaryContract.ALLOWED_SURFACE`; the workspace CLAUDE.md note claiming `conformance/tests/pipelex_transport/` does not exist is stale — the suite exists and runs).+- **Last completed item:** Phase 4a item 1 — the `mthds/` spec clarification (details on the 4a checklist line). Before that: C3 — the concept side landed as the `get_optional_entry_concept` / `get_required_entry_concept` pair with a package-aware `search_scope` (the entry pipe's domain, `alias->domain` for a dependency entry pipe) replacing the `search_domain_codes` list across the whole public chain; both README §4 latent defects deleted structurally; `fix_loop` rename collisions relaxed to per-domain. §4 marked HISTORICAL with a re-measured matrix (probe rewritten against the new affordance).+- **Phase 3 rulings.** (1) **Concept ambiguity raises, naming the candidates — but only after the scope preference has had its chance.** The old own-domain `insert(0)` was dead code; the preference now fires *before* the crate-wide scan. (2) **Both refusals (miss and ambiguity) raise `ConceptLibraryConceptNotFoundError`** — the class the `stuff_factory` handlers actually catch, which is what deletes the wrong-exception-class defect rather than patching around it; the four handler messages now say "could not be resolved: {exc}" so an ambiguity is not mislabeled "not found". (3) **The concept twin of OQ1 was paid in full here, unlike the pipe side** — the concept lookup is entry-only and its one call site holds the alias, so package scope is a string prefix, not an execution-path threading project. (4) The `search_domain_codes` parameter is deleted from `PipelexMTHDSProtocol` (public, breaking) rather than kept as an override — nothing supplied it in production and a caller-supplied list is exactly the contextual instability this branch removes.+- **Phase 3 surprises.** (1) Two integration tests pinned the crate-wide `fix_loop` collision scope and had to flip — the parametrized other-domain arm of `test_strip_namespace_bails_on_cross_file_collision` asserted a bail that is no longer correct behavior, and the rebuild-between-rounds pin only kept its purpose by moving to a same-domain fixture. (2) The stuff-factory param-id entries in `.test_durations` changed shape twice over: the rename changed the *argname* ids (`search_domain_codesN`), and the list→str change made the new ids embed the literal value (`test_domain`) instead of a positional placeholder — the reconciliation needed the full `-m ""` collection to map them. (3) `mocker.patch.object(module, "prepare_pipe_job", wraps=...)` on the run-setup module is enough to pin the scope wiring without touching the seam itself — the wiring mutation reddens both that pin and the end-to-end test.+- **Decisions taken:** phase structure reworked so no checkpoint rests on a self-contradicting tree; OQ1 promoted to a Phase 0 go/no-go gate; breaking-change posture held (no deprecation period) but preceded by a bounded corpus measurement. **OQ1 ruled GO** — owner-domain qualification is neutral-to-better for dependency packages; the dependency lookup-scope defect it exposed is pre-existing and deferred to the packaging project (`wip/pipe-refs/dependency-subpipe-scope-deferred.md`). **Crate envelope ruled: the pass does not deal in crates at all** — it returns a `QualifiedCrateContent` (just `concepts` and `pipes`), never a `LibraryCrate`, because it cannot pick the right digest scheme for a `fingerprint`. Each consumer makes the fingerprint correct at its own boundary (rationale in the design doc's Phase 1 outcome). *(This bullet previously read "the pass is envelope-preserving", describing the first cut that returned a crate; review changed the return type and the wording was stale in three places until a PR bot caught one of them.)*+- **Surprises / fallout:** (1) the dependency execution path has **no** child-library scoping at all — a dependency package using a controller internally either fails to load or silently binds a host pipe of the same bare code; the child-library special case in `Library.validate_pipe_library_with_libraries`'s first loop is neutralized by `pipe.validate_with_libraries()` in the second. Worse in the shape a package actually ships: with a manifest `[exports]`, the authored helper is dropped from the dependency's own child library and the load fails earlier still. (2) README §5's corpus scan used a hardcoded repo list that reached under a fifth of the bundles outside this repo; the widened scan is in `wip/pipe-refs/corpus-measurement.md`, and the second breaking reference lives in `cocode` — a shipped CLI, not an examples directory.+- **Open risks carried in:** four latent defects surfaced by the outside-voice pass are folded into Phases 1–3 below (batched sub-pipe code derivation, transported `PipeFunc` bare codes, the crate fingerprint contract — now ruled, aliased dependency keys polluting the crate-wide search). None of them is speculative; each names a file.+- **Phase 1 findings that change how Phase 2 must be tested:** (1) **this repo's entire bundle corpus is blind to the rule flip** — applying Phase 2's owner-domain rule to all 54 crates buildable here produces byte-identical output, so the two-domain fixture is not a nicety and the mutation check is what makes the resolution-row tests mean anything; (2) **a differential harness whose inputs each carry at most one defect cannot see an error-precedence change** — that is how Phase 1's own precedence shift got past it and had to be caught in review; Phase 2 moves far more error surface, so its equivalence inputs need multi-defect crates; (3) **a fixture full of bare refs proves nothing unless a test reads a ref back out of the result** — Phase 1's first test module passed intact against a no-op pass for exactly that reason; (4) nothing writes a normalized crate back over a `.mthds` file, so the flip does not rewrite user source — but the stamped `codegen.lock` `crate_fingerprint` moves on every committed projection; (5) `_qualify_io_ref`'s cross-package guard looks unreachable through a constructed blueprint (the io-ref validator rejects `alias->` refs outright) — preserved verbatim, flagged for whichever phase owns cross-package forms.+- **Phase 2 rulings.** **OQ2 — the entry affordance is a `get_optional_entry_pipe` / `get_required_entry_pipe` pair** on `PipeLibraryAbstract` + `PipeLibrary`, mirrored as hub accessors. A pair rather than one method because the migration found exactly one caller (`pipelex which`) that needs the optional form and eleven that want the required one; "entry" rather than the working name `find_pipe_by_bare_code` because it also takes fully-qualified refs, and because the name should say *why* the lookup differs, not *how*. **OQ3 — the cross-package bare-remainder search stays.** The qualification pass leaves `alias->…` refs alone (it cannot know a dependency's domain layout), so deleting the search would break every `alias->bare_code` ref with no canonical spelling to migrate to. It is alias-scoped and cannot reach a host pipe; the comment in `get_optional_pipe` says so and points at the packaging design. **DRY — the pipe and concept affordances stay separate**, written up with the reasoning in [wip/pipe-refs/entry-affordance-share-vs-duplicate.md](wip/pipe-refs/entry-affordance-share-vs-duplicate.md) so Phase 3 inherits a decision rather than making an accidental copy. The *rule* is shared (one `qualify_crate`); the affordance is the deliberate exception to it, and the two should not be conflated.+- **Phase 2 surprises.** (1) **The batched sub-pipe defect was real but not what the review said.** The plan (from Codex) predicted the invalid code `domain.foo_batch`; in fact `PipeAbstract` has a `code` validator that strips a namespace prefix, so the built ref was correct all along. What the wrong derivation actually produced was a `log.warning` on **every** batched run, about a code no user wrote. The fix stands; the first test written for it asserted on the ref and passed against the bug, and had to be rewritten to assert on the warning. (2) **Two call sites the plan did not enumerate** turned up by running the suite rather than grepping: `validate_bundle.py` resolved a bundle's own `[pipe.<code>]` keys as bare codes (now qualified with the bundle's domain — precise, not routed through the affordance), and `dry_run_in_process.best_effort_graph_spec` resolved a caller-supplied graph target (entry-shaped, now on the affordance). The second silently degrades to "no graph" on a miss, so it would never have failed loudly. (3) **`missing_pipe_code` changed value** — a structured, machine-read field, so a wire-visible change, recorded in the changelog. (4) The test sweep's own derivation over-reached twice and both were caught by verification rather than by the suite: a `.pipe_code ==` assertion resolved against the wrong source (that field is the *referring* pipe's local code and does not change), and a ref inside a `PipelexBundleBlueprint` fixture was hand-qualified when the product qualifies it — the new break message diagnosed that one itself.+- **Phase 2 PR review (cubic, 9 findings; greptile clean).** Two were real defects and both are fixed: the `SpecialOutcome` exemption applied to *every* controller kind, though `continue` / `fail` are legal snake_case pipe codes — so a sequence step naming a pipe called `continue` was left unqualified, which the strict lookup then fails to resolve (a Phase 2 regression: the fall-through used to rescue it); and `make-demos.sh`'s `mktemp -d -t` is BSD-only, so the README's own reproduction command aborted on Linux before writing a demo. **Four findings were claims of mine that had gone false**, which is the half worth remembering: the `python_sources` deferral credited `model_copy` for envelope preservation (true of the pass's *first* cut, which returned a crate — the same stale claim was in three places, and the bot found one), "no fix op writes a pipe ref" is wrong (`strip-namespace` plans a root `main_pipe` SET_KEY), and three line-number pointers had gone stale *inside this branch* between Phase 1 and Phase 2. Those were fixed by **removing** the line numbers, not correcting them — a pointer into code the same branch edits re-stales itself every phase.+- **The `_domain_of` / `CrateNormalizationError` debt, split and settled.** Phase 1 left two things wrong-sounding once `library_manager` became a second caller of the pass, and parked both on Phase 2. **Only one of them was Phase 2's to pay**, which the plan did not say clearly enough — a PR bot caught the bullet still assigning both to a phase declared complete. Settled: the **message** is fixed here (it now says "this pass expects…" rather than blaming the normalizer, which is no longer even the busier caller). The **error-class rename is deliberately re-deferred to Phase 4b**, where it belongs: `error_type` is a wire string, so a rename needs `make generate-error-identity`, `make generate-error-pages`, and the TypeScript-consumer sweep — all of which are already Phase 4b's "error-surface sweep" line items. Doing it here would open a cross-repo surface inside a runtime-only phase.++---++## Phase 0 — answer the questions that can invalidate the design++Nothing here writes product code. Both items exist because their answers can change what gets built, and both are cheaper now than later.++- [x] **OQ1 — dependency-pipe lookup scoping (GO/NO-GO).** **Answered: GO.** Measured with `wip/pipe-refs/probes/dep-subpipe-scope.py` across three package shapes. Execution consults the **host** library unconditionally, and its bare-code fall-through skips `alias->` entries — so a dependency's own bare sub-pipe ref never reaches the dependency's own pipe *today*: a plain host fails to load, a host declaring the same bare code loads and silently binds the host's pipe, and a dependency with a real `[exports]` manifest fails earlier still because the export filter drops the authored helper from the child library. Owner-domain qualification does not regress that (the qualified ref resolves to `None` in the host exactly as the bare one does), converts the silent capture into a deterministic not-found, and makes the eventual package-scoped lookup a direct key hit in the child library. The pre-existing defect is written up in `wip/pipe-refs/dependency-subpipe-scope-deferred.md` and deferred to the packaging project.+- [x] **Measure the fall-through corpus.** **Two bare pipe refs break across every `.mthds` tree in the workspace**, each fixed by one qualified spelling. Recorded with the full table, the reproduction command and the denominator's caveats in `wip/pipe-refs/corpus-measurement.md`. README §5's scan used a hardcoded ten-repo list and missed most of the workspace; enumerating instead multiplies the corpus several times over and finds a second `sibling-only` case in `cocode` — a shipped CLI, not a sample. The `sibling-only` *concept* refs found are vscode-pipelex editor fixtures that already fail to load today, so they are not new breakage.++### ⛔ CHECKPOINT C0 — MANDATORY STOP++- [x] Record the OQ1 ruling and the corpus number in the Status block and the design doc.+- [x] If OQ1 came back negative, do not proceed — write up what broke the premise and end the session for a design conversation. *(Came back positive — proceeding.)*+- [x] Commit the investigation notes.+- [x] STOP. Next session starts at Phase 1.++---++## Phase 1 — extract the pass (pure refactor, behavior-identical)++This phase moves code and changes nothing. That is the point: the checkpoint at the end is the safest handoff state in the whole plan, provable by an unchanged test suite. The rule flip does not happen here.++- [x] Read the design doc and README end-to-end; skim `pipelex/libraries/crate_normalization.py` (`_qualify_concept_ref`, `_qualify_pipe_ref`, `_qualify_io_ref`, `_normalize_pipe`) and `pipelex/libraries/library_crate_factory.py` to confirm the insertion point still matches the design.+- [x] **Record the subject grant first if the pass takes a positional subject** (see Gates item 5). Done — nine grants recorded before the first check. The `PostToolUse` hook blocked the write and named every ungranted subject, so the auto-fixer never got the chance to rewrite them; the gate's hazard is real but the hook catches it at edit time, not only at `agent-check` time.+- [x] Extract the in-body reference qualification step out of `crate_normalization.py` into a standalone pass over a `LibraryCrate`. Landed as `pipelex/libraries/crate_qualification.py::qualify_crate`. Covers pipe refs (steps, branches, outcomes, batch refs), concept I/O refs, `refines`, and structure-field refs. **Rule unchanged** — crate-wide search stays.+- [x] Make `normalize_crate` consume the extracted pass. No test flips. **Behavior-identical with one known, deliberate exception — error precedence between two independent defects.** HEAD's implementation was loaded beside the working tree's and both run over the same inputs, comparing full serialized output: identical across every crate buildable from this repo's `.mthds` files and across ten hand-built crates covering the branches the corpus cannot reach. The comparison was mutation-checked so its green means something: dropping structure-field qualification reddens one case, applying the Phase 2 rule reddens three.++ ⚠ **The exception, and how it was missed.** Qualification now runs as one complete phase ahead of refinement flattening, where HEAD interleaved them (concepts → flatten → pipes). A crate carrying *both* a refinement cycle and an ambiguous bare pipe ref used to report the cycle and now reports the ref. **The differential harness could not see this: every crate it compares carries at most one defect.** A single-defect corpus cannot detect a precedence change by construction — the finding came from review, not from the harness, and that is the lesson worth carrying into Phase 2, where far more error paths move. Accepted rather than fixed: restoring the old order would mean splitting the pass in two so the normalizer could interleave it, and Phase 2 runs the pass with no flattening at all. Both errors are `CrateNormalizationError`, the crate is invalid either way, and which of two independent defects is named first is not a contract. Recorded in `normalize_crate`'s docstring.+- [x] **Inventory every consumer of normalized crate output before the flip phase.** Recorded in [wip/pipe-refs/normalized-crate-consumers.md](wip/pipe-refs/normalized-crate-consumers.md). **The feared write-back does not exist** — no path writes a normalized crate back over a `.mthds` source file. `pipelex fix` rewrites user files but never through a crate, and no fix op writes a pipe ref (re-check in Phase 2 rather than assume). What does move is the stamped `codegen.lock` `crate_fingerprint` on every committed projection.+- [x] **Settle the crate envelope / fingerprint contract.** **Ruled: the pass does not deal in fingerprints at all** — it returns a `QualifiedCrateContent` (the rewritten `concepts` and `pipes`), not a `LibraryCrate`. Returning a crate would force it to supply a `fingerprint` it cannot get right, since a crate does not record which digest scheme produced its value; the pass would have to guess or carry over a digest that no longer describes its own content, contradicting `LibraryCrate.fingerprint`'s own docstring. Returning the two mappings makes that unrepresentable and costs the callers nothing — both already hold a crate to read the envelope from, and `normalize_crate` builds a fresh one anyway. Phase 2's `load_from_crate` keys idempotency on the incoming crate's fingerprint, which is what external callers pass to `is_crate_loaded`. *(First cut returned a crate with the envelope carried over and a paragraph excusing the stale digest; review pushed back and the smaller surface is plainly better — a paragraph of excuse is a design smell.)* The related `python_sources` drop in `normalize_crate` is real, untouched here, and deferred in [wip/pipe-refs/normalize-crate-drops-python-sources-deferred.md](wip/pipe-refs/normalize-crate-drops-python-sources-deferred.md) — the one-line fix moves customer Python source into a CLI stdout stream and an HTTP response body.+- [x] Gates checklist clean (all items).++### ⛔ CHECKPOINT C1 — MANDATORY STOP++A pure refactor has landed. The tree is fully self-consistent and the suite is unchanged — this is a genuinely safe place to walk away from.++- [x] Update the Status block (phase done, the consumer inventory, the fingerprint ruling).+- [x] Record status in the design doc's Phase 1 section.+- [x] Commit with a clear message. ⚠ **This item's own wording had to change:** it said "say plainly that this commit changes no behavior", and that turned out not to be true. The message states the extraction is behavior-preserving *with one documented exception* and names it. An instruction to assert a property is not a licence to assert it unverified.+- [x] Gates run at the checkpoint: `agent-check` clean, full `agent-test` green, `drift-check` passed against the staged index, `.test_durations` N/A (path-existence gate; nothing renamed or moved), subject grants recorded ahead of the first check.+- [x] Reviewed by a no-context `/code-review` fan-out; findings triaged and verified individually rather than deferred to. Three of the reviewer's claims held up, two against claims I had written down myself.++---++## Phase 2 — flip the rule and make the lookup strict (these land together)++The normalizer and the live library must never disagree in a committed state, so the rule flip and the strict lookup are one phase. This is the phase that justifies the branch.++### The rule++- [x] Switch the pipe rule inside the pass from crate-wide search to **owner-domain qualification** — the exact twin of `_qualify_concept_ref`. Existence is NOT checked by the pass; the ordinary dependency validation catches missing refs afterwards (that is the standard's step 3 by construction).+- [x] Leave cross-package refs (`alias->…`) untouched by the pass, exactly as the normalizer already does.+- [x] **Fix the batched sub-pipe code derivation.** `SubPipe.pipe_code` becomes `domain.foo`, and the runtime derives `f"{self.pipe_code}_batch"` (`pipe_batch_adhoc_pipe_code` in `pipelex/pipe_controllers/sub_pipe.py`). Use the resolved sub-pipe's local code for that derivation. ⚠ **The predicted consequence turned out to be wrong** — see the Phase 2 surprises above: `PipeAbstract`'s `code` validator strips a namespace prefix, so the built ref was correct all along and what the bug really produced was a warning on every batched run.+- [x] Run the qualification pass in `pipelex/libraries/library_manager.py` on **all** crate→pipes paths — main load, secondary loads, dependency-package loads — before pipes are constructed via `PipeFactory.make_from_blueprint`.++### The strict lookup and the entry affordance++- [x] Strip the step-3 bare-code crate-wide fallback from `PipeLibrary.get_optional_pipe` (`pipelex/libraries/pipe/pipe_library.py`), including the `domain_hint` TODO. What remains: direct key lookup and cross-package (`alias->`) handling. `get_required_pipe`'s signature does not move (transport-pinned).+- [x] **OQ3 — decide** whether `get_optional_pipe` keeps the cross-package bare-remainder search (`alias->` + bare code). It is alias-scoped so it does not reopen the cross-domain hole; the design leans toward keeping it until the packaging design rules on cross-package reference forms. Record the ruling, and pin it with a test either way.+- [x] Close [wip/parity/d1-domain-hint-deferred.md](wip/parity/d1-domain-hint-deferred.md) as subsumed by this change (status note in that file).+- [x] **OQ2 — settle the entry affordance's final name and shape** (working name `find_pipe_by_bare_code`; one method or a required/optional pair; where the ambiguity error message lives).+- [x] Implement the entry affordance on the pipe library (+ its abstract): exact ref hits directly; a bare code matches crate-wide; ambiguity raises an error asking the user to qualify. Docstring states explicitly that it deliberately does NOT consult `[exports]` — a hand-invoked pipe is not an in-body reference, so package visibility does not apply.+- [x] **Exclude aliased dependency keys from the crate-wide bare search.** `PipeLibrary.root` also holds `alias->…` dependency entries (added by `add_dependency_pipe`), so "crate-wide" is not "every value in root". Without this exclusion, installing an unrelated dependency package can make a host pipe ambiguous — reintroducing, through the new affordance, exactly the contextual instability this branch exists to eliminate. Applies to the concept affordance in Phase 3 too.+- [x] **Decide and record the share-vs-duplicate question** between this pipe affordance and the concept affordance built in Phase 3. They are near-twins — the concept one adds a domain-preference step, and its spec currently stops at "unique match" without saying what happens when the match is not unique. Decide now whether they share a helper or stay deliberately separate, and settle whether the concept one raises on ambiguity. A written "separate, because X" is a valid answer; an accidental copy discovered in Phase 3 is not.+- [x] Expose the affordance through a new `pipelex/interpreter_hub.py` accessor (additive; the transport spec/conformance update for it happens in Phase 4b).+- [x] Migrate the in-repo entry-shaped call sites to the affordance: the CLI commands (`which`, `show`, `validate`, the `build`/`codegen` groups), `pipeline_run_setup`, and the builder operations. Controllers, `sub_pipe`, `signature_walk`, and `library` validation need NO edit — they look up refs stored on built objects, which now arrive qualified. ⚠ That is true *only because this phase lands as one change*: `Library.validate_pipe_library_with_libraries`'s first loop looks up a bare sub-pipe code against the child library, whose keys are qualified, so it is served today solely by the step-3 fall-through being deleted below. Deleting the fall-through without qualifying the dependency load path breaks it.+- [x] **Qualify the transported `PipeFunc` code.** `PipeFunc` used to send its bare code and the sandbox later calls the now-strict lookup with it (`pipelex/pipe_operators/func/pipe_func.py` → `pipelex/pipe_operators/func/direct_pipe_func_executor.py`). Under the strict lookup **every** transported `PipeFunc` fails, not merely ambiguous ones. The DTO must carry a qualified ref — it now transports `pipe_code=self.pipe_ref`.++### The break message++- [x] Spec the not-found message in **dependency validation** — that is where users actually meet it, not in the lookup. It names the qualified ref that was tried, and when a crate-wide candidate exists it suggests it and states the new rule. Without this, the user reads `advisory.present_as_markdown` while staring at a file that says `present_as_markdown`, and has no way to know the compiler added the prefix.+- [x] Mark the diagnostic crate-wide scan **failure-path only** in code and comment. It is the same scan being deleted from the resolution path, and an implementer in a hurry can reintroduce the fallback by accident.+- [x] Build the crate-wide bare-code index **once per validation run** and share it across every missing-ref diagnostic. Per-error scanning goes quadratic on the mass-breakage run — which is precisely the first-run-after-upgrade this feature exists to improve.++### Tests++- [x] **Build a two-domain fixture.** In a single-domain crate, owner-domain qualification and crate-wide search give identical answers, so every resolution-row test below would pass just as happily under the rule being deleted. The rows only discriminate when a sibling domain declares the same pipe code. ⚠ **Measured in Phase 1, not merely suspected:** applying this phase's rule to all 54 crates buildable from this repo's `.mthds` files changes nothing — every normalized output is byte-identical under both rules. The repo's own corpus is blind to the flip, so the fixture must be hand-built, and the mutation check below is what proves it discriminates.+- [x] Flip the normalizer test that pins the old rule: `tests/unit/pipelex/libraries/test_crate_normalization.py::test_bare_cross_domain_pipe_refs_resolve_to_the_declaring_domain` becomes a test of owner-domain qualification.+- [x] Flip the lookup tests that pin the old rule: `tests/unit/pipelex/libraries/test_pipe_library_lookup.py::test_bare_code_ambiguous_raises` and `::test_bare_code_unambiguous` become tests of the strict lookup + entry affordance split.+- [x] Qualify the refs in tests that construct pipes directly with bare sub-refs (bypassing the crate pass) — they hit the strict lookup now. Find them by running the suite, not by grepping alone.+- [x] Conformance-shaped unit coverage for the resolution rows on the two-domain fixture: own-only resolves; sibling-only errors; both-declare resolves to own; nowhere errors. ⚠ **The export-bypass closure case is NOT covered by a test here** — only by re-running the demo probe by hand (recorded in README §3). Its *behaviour* is covered: a bare in-body ref cannot reach **any** sibling domain, exported or not, which is pinned at library level by `test_unresolved_pipe_ref_message.py::test_names_the_qualified_ref_and_explains_the_rule`, and export-bypass is a strict subcase of that. What has no test is the `[exports]`/`METHODS.toml` machinery *interacting* with the new rule, which needs a package fixture and is conformance-shaped — it is already scheduled in Phase 4b's spec-suite line item. Do not tick that 4b item without it.+- [x] **Mutation-check the rows.** Done for sibling-only (restoring the crate-wide search reddens the two rule tests and both message tests) and per-controller-kind for the closure walk. **Not done for export-bypass**, because there is no export-bypass test to mutate — see the item above.+- [x] Coverage for the entry affordance semantics: exact hit, crate-wide unique bare match, ambiguity error message, and no-match.+- [x] Pin the stated invariants that currently have no test: `alias->` refs pass through the pass untouched; all four ref kinds are covered (steps, branches, outcomes, batch refs — branches and batch refs are the ones a hand-written pass forgets); the pass is idempotent (`d.c` must not become `d.d.c`, and it now runs in two places); the pass runs on **all three** load paths (a miss on the secondary or dependency path is invisible for any single-domain library); the OQ3 ruling; and that the affordance reaches a **non-exported** pipe (the twin of the export-bypass closure — the docstring claim needs enforcement).+- [x] Execution test for `batch_over` covering the derived batch code.+- [x] Coverage for both branches of the new validation message: candidate exists, and no candidate exists.+- [x] Audit existing CLI coverage for the migrated surfaces, then add a bare-code end-to-end test wherever there is not one. A perfectly-tested affordance can still be perfectly mis-called, and `pipelex which <bare_code>` is the invocation the affordance exists to preserve.+- [x] Re-run the README's demo probes (`wip/pipe-refs/probes/make-demos.sh`) and move the closures accordingly: `fallthrough` and `export-bypass` must now FAIL resolve; `ambiguous` must resolve to the own domain. Update whatever the probes/README record as expected outcomes.+- [x] Gates checklist clean (all items).++### ⛔ CHECKPOINT C2 — MANDATORY STOP++The pipe rule is complete and self-consistent: canonical form and runtime agree, and hand-typed codes still work through a named door.++- [x] Update the Status block (OQ2/OQ3 rulings, the DRY ruling, surprises, corpus fallout).+- [x] Record status in the design doc's Phase 2 section (`build-time-qualification.md` → "Phase 2 outcome (C2)").+- [x] Update README §2's table — marked HISTORICAL with a banner rather than rewritten, and §3 gained a re-measured table.+- [x] Update the `docs/` pages that describe bare-ref resolution, pipe lookup, or the entry surfaces touched here. `docs/building-methods/libraries.md` gained a "How a pipe reference resolves" section; `docs/contribute/hub-layering.md` gained the two new hub symbols and the in-body-vs-entry guidance (that page is a drift contract target and was reviewed and acked).+- [x] Changelog entry under `[Unreleased]` noting the breaking language-behavior change. Also **removed** the superseded `[Unreleased]` entry describing the crate-wide rule this phase deletes — it never shipped, so leaving both would have published two contradictory claims.+- [x] Commit — landed on a stacked branch (PR #1092) rather than the base one, since PR #1091 carries Phase 0+1 and the two merge together.+- [x] STOP. Next session starts at Phase 3.++⚠ **These boxes sat unticked while the Status block above declared C2 passed** — caught by a PR bot, not by me. A checkpoint that reports itself complete from one place while its own checklist says otherwise is exactly the contradiction a cold-starting session cannot resolve. Tick the checklist in the same edit that updates the Status block.++---++## Phase 3 — the concept side and the footprint cleanups++Same root cause as Phase 2 — crate-wide search where owner scope was meant — but an independent surface with its own caller sweep. Kept separate so the pipe fix has a finish line that does not depend on it.++- [x] Collapse `ConceptLibrary.get_required_concept_from_concept_ref_or_code`'s `search_domain_codes` machinery (`pipelex/libraries/concept/concept_library.py` + `concept_provider_abstract.py`) into the entry-affordance shape decided in Phase 2. Landed as the `get_optional_entry_concept` / `get_required_entry_concept` pair; the required form replaces the old method on `ConceptProviderAbstract` 1:1.+- [x] **Scope the concept lookup by package, not just domain.** `search_scope` is a single string derived from the resolved entry pipe — its domain, prefixed `alias->domain` when the caller invoked a dependency pipe. Dependency concepts are keyed `alias->domain.Concept`, so the scoped preference is a direct key construction; no child-library machinery needed. Unlike pipe-side OQ1 (deferred to packaging), the concept lookup is entry-only and its one call site holds the alias, so this was paid in full here.+- [x] Exclude aliased dependency keys from the concept crate-wide search too (same reasoning as Phase 2). Mutation-checked.+- [x] Delete the latent defects README §4 documents: both gone structurally — there is no per-domain walk left to die on a miss, and every escape is `ConceptLibraryConceptNotFoundError` (the class the `stuff_factory` handlers catch), ambiguity included. §4 marked HISTORICAL with the re-measured matrix appended (probe rewritten against the new affordance).+- [x] Decide whether `pipeline_run_setup`'s own-domain-first ordering becomes meaningful or gets deleted along with the list parameter — **it became meaningful**: the scope preference fires BEFORE the crate-wide scan, so the entry pipe's own domain wins outright instead of being collected into an ambiguity raise. The list parameter is deleted from the whole public chain (`runner.py` constructor included — breaking, in the changelog); callers were swept, none supplied it in production.+- [x] Relax `_pipe_codes_by_file`'s rename collision scope in `pipelex/pipeline/fixes/fix_loop.py` from crate-wide to per-domain. Files now carry their declared domain (`_FilePipeCodes`); a file with an unreadable domain conservatively collides with everything. ⚠ Two integration tests pinned the crate-wide scope and flipped: the rebuild-between-rounds pin moved to a same-domain fixture, and `test_strip_namespace_bails_on_cross_file_collision`'s other-domain arm became a convergence test.+- [x] Tests: the resolution rows for concepts on the two-domain fixture (unit, `test_concept_library_entry_lookup.py`); ambiguity raises naming candidates; the package-scoped dependency-concept case (bare + dotted + exclusion); fix_loop independent renames across domains; an end-to-end wiring test (`test_entry_concept_scope.py`) that reddens if the scope threading is dropped anywhere in the chain; a characterization pin that `pipeline_run_setup` derives the scope from the entry pipe.+- [x] Gates checklist clean (all items). Grants for the new entry-concept defs recorded before the first check; `.test_durations` reconciled against a full `-m ""` collection (renamed node ids and remapped param ids; the remaining orphans predate this branch).++**Carry these forward from Phase 2 — each cost real time to learn:**++- **A single-domain fixture cannot discriminate this rule.** Owner-scope and the crate-wide search agree on every input where only one domain exists, so a concept test without a competing sibling declaration passes just as happily under the rule being deleted. Mutation-check every resolution row: put the old rule back and confirm the row goes red.+- **Mutate the wiring, not just the rule.** Removing the qualification from the *dependency* load path reddened nothing in the entire suite — every other test loads a single-domain library. Assume the same blind spot exists on the concept side and go looking for it deliberately.+- **Run the whole suite, including `tests/e2e`.** Phase 2's fixture sweep collected failures from `tests/unit` + `tests/integration` only and shipped two e2e failures into a "green" checkpoint.+- **A review finding that names a file and a line is a claim to verify.** Phase 2's batched-derivation item predicted the wrong consequence, and the first test written for it passed against the bug.+- **Do not touch the working tree while `agent-test` runs**, and read the run's log rather than the harness's exit-code summary — one reported success over a log ending in `Error 1`.++### ⛔ CHECKPOINT C3 — MANDATORY STOP++The runtime is fully spec-compliant and self-consistent; only cross-repo work remains.++- [x] Update the Status block and the design doc's Phase 3 section (`build-time-qualification.md` → "Phase 3 outcome (C3)").+- [x] Re-run the README's probes and demos and confirm the post-change behavior matches the design's predictions. The concept-lookup-matrix probe was rewritten against the new affordance (the method it measured no longer exists) and its re-measured table appended to README §4, which is now marked HISTORICAL.+- [x] Changelog entry for the concept-side behavior change (breaking: the `search_domain_codes` public parameter and the `ConceptProviderAbstract` method rename) and the `fix_loop` per-domain relaxation.+- [x] Commit.+- [x] STOP. End the session. Next session starts at Phase 4a.++**Post-C3 review round (2026-08-13):** a medium code review of the C3 commit surfaced real gaps in the new affordance, fixed in a follow-up commit on the branch. A multi-domain dependency package's own concepts are now reachable by bare code from any of its entry pipes — the scoped preference probed exactly one key and the crate-wide scan excludes aliased keys, so the sibling-domain shape was unreachable; the pipe side's alias-scoped package search was ported over, with `alias->Concept` as its explicit spelling. Dotted refs now obey the same scope-wins precedence under a dependency scope instead of binding host-first (a host/dep domain-name collision would have bound the host concept silently, since compatibility short-circuits on equal `concept_ref`). The invalid-string escape joined miss and ambiguity on `ConceptLibraryConceptNotFoundError`, making the one-class claim actually true. The copy-paste `stuff_factory` handlers collapsed into one `_resolve_entry_concept` helper; `pipeline_run_setup` captures the caller's raw entry ref in its own local so the scope derivation no longer depends on `pipe_code`'s rebind order; the `fix_loop` bail message hedges the unreadable-domain case. Each behavioral fix mutation-checked.++---++## Phase 4a — cross-repo, release-independent++These need no published `pipelex`. They can land as soon as Phase 3 is committed.++- [x] `mthds/` — additive clarification at § *Resolution Order for Bare Pipe References*: no-fall-through is what makes `[exports]` enforceable, so the next reader does not mistake the rule for a lookup convenience. No normative change. Landed 2026-08-13 in `mthds/` on branch `docs/bare-pipe-ref-no-fall-through` (off `dev`): an admonition note in `docs/spec/namespace-resolution.md` + a changelog entry; `make docs-check` (strict) passes. Not pushed — no PR opened without being asked. *(The design doc's "mthds/ last" ordering came from deferred-review-observations §4, whose constraint was D-1's domain_hint question — answered and subsumed in Phase 2, so the ordering dissolved and this plan's 4a placement governs.)*+- [ ] Add the new hub accessor to the transport boundary spec (workspace-level; exact path in the workspace private notes). The prose spec is a doc edit; its verifying test lands in 4b, and the two must land together per the spec/conformance sync rule — so hold this until 4b is ready to go with it.++## Phase 4b — cross-repo, gated on a published `pipelex`++**Gate:** every item below needs a `pipelex` release carrying the new `interpreter_hub` accessor, installable by the sibling repo. Cut that release first. Opening these PRs beforehand produces red CI for a reason unrelated to the change.++- [ ] our cross-repo spec suite — executable conformance cases for the resolution rows (own-only, sibling-only, both-declare, nowhere) and the export-bypass closure, on a two-domain fixture. Reuse the fixture built in Phase 2.+- [ ] our cross-repo spec suite — add the new hub accessor to the transport allowed-surface test, landing together with the spec doc edit from 4a (exact paths and the current state of that test in the workspace private notes).+- [ ] Run the spec suite's spec-link checker — must pass.+- [ ] the transport layer that is not open core — migrate its host-side bridge's payload-supplied lookup to the new accessor (that code is entry-shaped; `get_required_pipe`'s pinned signature is untouched).+- [ ] `pipelex-cookbook/` — qualify the first reference that leans on fall-through: `presentation.present_as_markdown` in `examples/wip/advisory_board/bundle.mthds`. Verify the example still validates and runs against the updated runtime.+- [ ] `cocode/` — qualify the second: `changelog.format_changelog_as_markdown` in `cocode/pipelines/swe_diff/changelog_enhanced.mthds` (a shipped CLI — see `wip/pipe-refs/corpus-measurement.md`). Verify the pipeline still validates against the updated runtime.+- [ ] **`search_domain_codes` consumer sweep beyond the transport bridge.** Found by enumerating the workspace (the transport item above covers only `pipelex-server/transport/`): `pipelex-api/api/routes/pipelex/pipeline.py` still passes the deleted `search_domain_codes=` kwarg to `pipeline_run_setup` — a `TypeError` on every execution request the moment the pin moves (and remember: its openapi-check runs under `make check` only, so an agent-gate-green bump still fails CI); `pipelex-js` mirrors the lookup semantics in `packages/runtime/src/library/live-library.ts` and drives it from `scripts/python-live-library-oracle.py` (semantic parity, not just a kwarg); `pipelex-mistralai-workflows` names it in integration tests; the demo repos (`pipelex-demo-mistral`, `pipelex-demo-vibe`) use it in example workflows. Each needs the entry-affordance/`search_scope` migration or the kwarg dropped.+- [ ] **Aliased-entry `search_scope` wiring test.** The package-fixture conformance work above must also pin the run-setup wiring: invoke a dependency pipe as the entry via `alias->domain.pipe`, supply a bare envelope concept declared only in the dependency, and assert it resolves. Today no test invokes an entry pipe through an alias end-to-end, so deleting the `has_cross_package_prefix` branch in `pipeline_run_setup` (or capturing `raw_entry_ref` after `pipe_code` rebinds) reddens nothing.+- [ ] **Error-surface sweep.** Run `make generate-error-identity` and `make generate-error-pages`, review the identity diff, and grep the TypeScript consumers for any changed or newly-introduced `error_type` literal — `mthds-starter-js/src/lib/errors.ts`, `pipelex-starter-js/src/lib/errors.ts`, `vscode-pipelex`'s `cliValidationBackend.test.ts`, and the internal playground app's graph route. The class name is a wire string; those repos switch on the literal and fall through to a generic branch without failing to compile. No Python tool will point at this.+- [ ] Changelog entries in each touched repo noting the breaking language-behavior change, per each repo's convention (skip `wip/` docs in changelogs).++### ⛔ CHECKPOINT C4 — MANDATORY STOP (final)++- [ ] Update the Status block; all phases complete.+- [ ] Close `wip/pipe-refs/` with a final status note in the design doc and README.+- [ ] Fold the outcome into the parity track's records (`wip/parity/`).+- [ ] Commit; prepare PRs per repo as instructed by the user — do not push or open PRs without being asked.+- [ ] STOP. The work is done; anything further (release sequencing before the packaging system) is a separate track.++---++## Phase dependency map++```+Phase 0 (OQ1 gate + corpus measurement)+ |+ | a negative OQ1 stops everything+ v+Phase 1 (extract the pass — pure refactor) <-- safe handoff point+ |+ v+Phase 2 (flip the rule + strict lookup, together) <-- the branch's reason to exist+ |+ +----------------------------++ | |+ v v+Phase 3 (concept side, Phase 4a (mthds/ clarification —+ fix_loop) release-independent)+ | |+ +----------------------------++ |+ v requires a published pipelex carrying the accessor+ Phase 4b (spec suite + transport + cookbook/cocode + error sweep)+```++Lane A: Phase 0 → 1 → 2 → 3 (sequential — all touch `pipelex/libraries/`). Lane B: Phase 4a (independent once Phase 2 lands; touches `mthds/` and the workspace-level boundary spec). Lanes A and B share no module directory. Phase 4b joins both and is gated on a release, so it cannot run in parallel with anything.++## GSTACK REVIEW REPORT++| Review | Trigger | Why | Runs | Status | Findings |+|--------|---------|-----|------|--------|----------|+| CEO Review | `/plan-ceo-review` | Scope & strategy | 0 | — | — |+| Codex Review | `/codex review` | Independent 2nd opinion | 0 | — | — |+| Eng Review | `/plan-eng-review` | Architecture & tests (required) | 1 | CLEAR (PLAN) | 16 issues, 0 critical gaps left open |+| Design Review | `/plan-design-review` | UI/UX gaps | 0 | — | — |+| DX Review | `/plan-devex-review` | Developer experience gaps | 0 | — | — |++**CODEX:** outside voice ran with repo access and surfaced findings the plan-text review could not reach — batched sub-pipe code derivation producing `domain.foo_batch`, transported `PipeFunc` carrying bare codes into the strict lookup, an undefined crate fingerprint contract, dependency concepts losing package identity, aliased dependency keys polluting the crate-wide search, and a stale `(done)` marker on the final checkpoint. All folded into the phases above.++**CROSS-MODEL:** one tension. The eng review treated the repo's written no-backward-compatibility principle as settling the breaking-change question and invested in the error message as the migration path; Codex argued the decision was unevidenced because the fall-through corpus excludes customer bundles. Resolved by holding the no-deprecation posture while adding a bounded Phase 0 corpus measurement — the principle governs whether to break, the measurement governs how well the break is communicated.++**VERDICT:** ENG CLEARED — ready to implement, starting at Phase 0.++NO UNRESOLVED DECISIONSdiff --git a/docs/building-methods/libraries.md b/docs/building-methods/libraries.mdindex e69907e6c..b41310666 100644--- a/docs/building-methods/libraries.md+++ b/docs/building-methods/libraries.md@@ -37,6 +37,28 @@ Libraries enforce specific uniqueness constraints to maintain consistency:Pipes are identified by their domain-qualified reference (e.g. `marketing.generate_tagline`), so different domains within the same library can have pipes with the same code.+## How a pipe reference resolves++A reference written **inside** a pipe — a sequence step, a parallel branch, a condition outcome, a `batch_over` target — resolves within its own domain:++- `generate_tagline` written inside a `marketing` pipe means `marketing.generate_tagline`.+- To reference a pipe in another domain, write that domain out: `sales.generate_tagline`.++A bare reference never reaches another domain. This is what makes a domain a real boundary: adding a pipe to one domain cannot change what a pipe in another domain means, and `[exports]` — which deliberately exempts bare references from its check, because they were never supposed to leave home — is enforceable through every reference form.++If a bare reference names nothing in its own domain, validation says so, names the reference it actually tried, and points at the domain that does declare that code:++```+Pipe 'marketing.run_campaign' references 'marketing.render_html', which does not exist. A pipe+reference resolves inside its own domain, so 'render_html' is looked for in domain 'marketing'.+Referencing a pipe in another domain requires writing that domain out. 'render_html' is declared+elsewhere in this library — did you mean 'presentation.render_html'?+```++**Pipe codes you type yourself are a different matter.** `pipelex run generate_tagline`, `pipelex show generate_tagline`, `pipelex which generate_tagline`, and the pipe code in an API request all accept a bare code and find it in whichever domain declares it — you are pointing at a pipe, not writing a reference. If two domains declare the same code, these commands ask you to say which one rather than picking for you.++**Concept codes you supply in inputs follow the same entry rule.** A bare code in an input envelope (`{"concept": "Memo", "content": ...}`) is resolved against the entry pipe's own domain first; if that domain does not declare it, a code unique across the library is found wherever it lives, and a code two domains declare raises an error asking you to qualify it (`marketing.Memo`). Concept references written **inside** a bundle never search at all — they are qualified to their own domain when the library is built, exactly like pipe references.+## Local vs Remote Libraries### Local Libraries (Current)diff --git a/docs/contribute/drift-contracts.md b/docs/contribute/drift-contracts.mdindex 1f8e0a734..5481ee24b 100644--- a/docs/contribute/drift-contracts.md+++ b/docs/contribute/drift-contracts.md@@ -20,7 +20,7 @@ Three pieces:- **`drift.toml`** (repo root, human-authored) declares the contracts: `triggers` (globs over tracked files), optional `exclude`, `review` targets, and optional `verify_commands`.- **`.drift/acks/<contract-id>.toml`** (tool-written, committed) records the last fulfilled review: a content digest, the reviewer, a timestamp, a rationale, and the per-file trigger snapshot.-- **`pipelex-dev drift plan|check|ack`** computes obligations, checks them, and records acks. Make wrappers: `make drift-plan`, `make drift-check` (in the `make check` aggregate; in CI it currently runs as an **advisory** job that is visible on the PR but does not block merges — it will be promoted to a required check), `make drift-ack CONTRACT=… RATIONALE="…"`.+- **`pipelex-dev drift plan|check|ack`** computes obligations, checks them, and records acks. Make wrappers: `make drift-plan`, `make drift-check` (in the `make agent-check` and `make check` aggregates; in CI it currently runs as an **advisory** job that is visible on the PR but does not block merges — it will be promoted to a required check), `make drift-ack CONTRACT=… RATIONALE="…"`.The validity rule is a single equality, with no base ref, no git diff, and no timestamps:@@ -35,7 +35,7 @@ One view of every surface the contract system touches, from the working tree to| Surface | What happens there ||---|---|| **Make targets** | `make drift-check` (alias `dc`) is the pass/fail gate; `make drift-plan` (`dp`) is the read-only diagnosis; `make drift-ack CONTRACT=… RATIONALE="…"` (`da`, optional `BY=` for agents) records the review. All three wrap `pipelex-dev drift`. |-| **Quality checks** | `drift-check` runs inside the `make check` aggregate, alongside the other repo gates — a full local check cannot pass with an open contract or a rotten manifest. |+| **Quality checks** | `drift-check` runs inside the `make agent-check` and `make check` aggregates, alongside the other repo gates — a local check cannot pass with an open contract or a rotten manifest, so an open contract surfaces before CI. Mind the index: the digest reads staged content, so unstaged trigger edits are invisible to the gate until `git add`. || **Commits** | The digest is computed from the **git index**, and `drift ack` stages the ack file it writes — so the ack, the code change, and any doc fix land in the same commit, reviewed as one diff. || **Branches / merges** | After a merge, `drift check` recomputes the digest over the merged tree. An ack that was valid on either side but does not cover the merged trigger content fails the check until the merged state is reviewed and re-acked (see [Merges](#merges)). || **PRs / CI** | The `lint-drift` CI job runs `make drift-check` on every PR — currently advisory (visible, not merge-blocking; promotion to a required check is planned). The committed ack file appears in the PR diff, so the reviewer sees the rationale next to the change it covers. |diff --git a/docs/contribute/hub-layering.md b/docs/contribute/hub-layering.mdindex fe5502fc2..deebc2ec5 100644--- a/docs/contribute/hub-layering.md+++ b/docs/contribute/hub-layering.md@@ -57,7 +57,7 @@ There is deliberately **no** `pipelex.hub`. It was deleted rather than kept as a| --- | --- || container | `InterpreterHub`, `get_interpreter_hub`, `set_interpreter_hub` || library manager | `get_library_manager`, `get_library` |-| library lookups | `get_concept_library`, `get_required_concept`, `get_native_concept`, `get_required_domain`, `get_optional_domain`, `get_pipe_library`, `get_pipes`, `get_required_pipe`, `get_optional_pipe`, `get_pipe_source` |+| library lookups | `get_concept_library`, `get_required_concept`, `get_native_concept`, `get_required_domain`, `get_optional_domain`, `get_pipe_library`, `get_pipes`, `get_required_pipe`, `get_optional_pipe`, `get_required_entry_pipe`, `get_optional_entry_pipe`, `get_pipe_source` || current-library contextvar | `set_current_library`, `get_current_library`, `get_current_library_id_or_none`, `clear_current_library`, `scoped_current_library` || library dirs | `resolve_library_dirs`, `get_default_library_dirs` || pipe router | `get_pipe_router`, `set_pipe_router`, `teardown_current_pipe_router`, `scoped_pipe_router` |@@ -143,6 +143,10 @@ It is **read-side only**. Managing a library — adding, removing, listing, setu**There is deliberately no pipe counterpart.** Nothing in core's kernel half resolves a pipe. The two places that follow a pipe reference found *inside* a pipe graph — a condition's mapped pipes, a sequence's last step — live in `pipe_machinery/rendering/`, which is interpreter-layer and calls `interpreter_hub.get_required_pipe` directly; a provider parameter there would buy no closure property. `get_required_pipe` therefore stays on `PipeLibraryAbstract`. Split a read half out when a kernel-layer caller actually needs one, not for symmetry with concepts.+Pipe resolution comes in two flavours on this hub, and picking the wrong one is a correctness bug rather than a style choice. `get_required_pipe` / `get_optional_pipe` resolve an **in-body** reference — one pipe naming another from inside a method — and are strict: the ref names its own domain or it names nothing. `get_required_entry_pipe` / `get_optional_entry_pipe` resolve a code a **human** supplied at an entry point (a CLI argument, an API request field), where a bare code is still matched across domains. A CLI command on the strict pair is needlessly strict; a controller on the entry pair reopens the cross-domain hole that makes `[exports]` unenforceable.++One caveat on "strict", so nobody relies on it absolutely: a **cross-package** `alias->bare_code` ref is still resolved by searching the aliased entries, because the qualification pass leaves `alias->…` refs alone — it cannot know a dependency's domain layout, so there would be no canonical spelling to migrate such a ref to. That search is alias-scoped and cannot reach a host pipe, so it does not reopen the hole; it is a deferral to the packaging design, not an exception to the rule.+The injection point is the interpreter layer. `pipe_factory`, `input_renderer` and `output_renderer` — already interpreter-bound, so nothing is lost — resolve the concept library themselves and pass it down; `pipeline/execution_seams.py` does the same for `WorkingMemoryFactory`. That is the one-way arrow the whole design rests on, applied inside `core/`: **the half that knows about a loaded method resolves the collaborator and hands it downward.**When you add a core data-model function that needs a concept — or a concept's structure class — add a `concept_provider` parameter. Do not add a hub import, and do not reach for `get_class_registry()`: the guard will reject the first, and the second is the coupling this section exists to describe.diff --git a/pipelex/builder/operations/inputs_ops.py b/pipelex/builder/operations/inputs_ops.pyindex 398220869..ded4e5dd8 100644--- a/pipelex/builder/operations/inputs_ops.py+++ b/pipelex/builder/operations/inputs_ops.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport jsonfrom typing import TYPE_CHECKING, Any-from pipelex.interpreter_hub import get_library_manager, get_required_pipe, resolve_library_dirs, set_current_library+from pipelex.interpreter_hub import get_library_manager, get_required_entry_pipe, resolve_library_dirs, set_current_libraryfrom pipelex.pipe_machinery.pipe_factory import PipeFactoryfrom pipelex.pipe_machinery.rendering.input_renderer import build_concept_comments, render_inputsfrom pipelex.pipeline.blueprint_selection import select_primary_blueprint@@ -78,7 +78,7 @@ async def build_inputs_for_pipe(msg = "No pipe code specified"raise ValueError(msg)- the_pipe = get_required_pipe(pipe_code=pipe_code)+ the_pipe = get_required_entry_pipe(pipe_code=pipe_code)inputs_json_str = render_inputs(the_pipe, indent=2, explicit=explicit)inputs_dict = json.loads(inputs_json_str)diff --git a/pipelex/builder/operations/output_ops.py b/pipelex/builder/operations/output_ops.pyindex f63af7e19..2e5207cc3 100644--- a/pipelex/builder/operations/output_ops.py+++ b/pipelex/builder/operations/output_ops.py@@ -6,7 +6,7 @@ import jsonfrom typing import Anyfrom pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormat-from pipelex.interpreter_hub import get_required_pipe+from pipelex.interpreter_hub import get_required_entry_pipefrom pipelex.pipe_machinery.rendering.output_renderer import render_outputfrom pipelex.pipeline.validate_bundle import validate_bundle@@ -35,7 +35,7 @@ async def build_output_for_pipe(# not a fully runnable pipeline — an in-progress bundle with PipeSignature placeholders is fine.await validate_bundle(mthds_contents=mthds_contents, allow_signatures=True)- the_pipe = get_required_pipe(pipe_code=pipe_code)+ the_pipe = get_required_entry_pipe(pipe_code=pipe_code)output_str = render_output(the_pipe, output_format=output_format)match output_format:diff --git a/pipelex/builder/operations/runner_code_ops.py b/pipelex/builder/operations/runner_code_ops.pyindex d7275b16c..418cc0694 100644--- a/pipelex/builder/operations/runner_code_ops.py+++ b/pipelex/builder/operations/runner_code_ops.py@@ -3,7 +3,13 @@from __future__ import annotationsfrom pipelex.builder.runner_code import generate_runner_code-from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_pipe, set_current_library+from pipelex.interpreter_hub import (+ clear_current_library,+ get_current_library_id_or_none,+ get_library_manager,+ get_required_entry_pipe,+ set_current_library,+)from pipelex.mthds_parsing.parser import MthdsParserfrom pipelex.pipeline.bundle_validator import BundleValidator@@ -50,7 +56,7 @@ async def build_runner_code_for_pipe(await BundleValidator().validate_pipes(pipes=pipes, library_id=library_id)# Get the required pipe and generate runner code- pipe = get_required_pipe(pipe_code)+ pipe = get_required_entry_pipe(pipe_code)runner_code = generate_runner_code(pipe=pipe)success = Truereturn runner_codediff --git a/pipelex/builder/operations/validate_ops.py b/pipelex/builder/operations/validate_ops.pyindex 1516c76f5..1bcd0528c 100644--- a/pipelex/builder/operations/validate_ops.py+++ b/pipelex/builder/operations/validate_ops.py@@ -8,7 +8,7 @@ from pipelex.interpreter_hub import (clear_current_library,get_current_library_id_or_none,get_library_manager,- get_required_pipe,+ get_required_entry_pipe,resolve_library_dirs,set_current_library,)@@ -151,7 +151,7 @@ async def validate_pipe(if effective_dirs:library_manager.load_libraries(library_id=library_id, library_dirs=effective_dirs)- the_pipe = get_required_pipe(pipe_code=pipe_code)+ the_pipe = get_required_entry_pipe(pipe_code=pipe_code)dry_run_results = await BundleValidator().validate_pipes(pipes=[the_pipe], library_id=library_id)return {diff --git a/pipelex/cli/agent_cli/commands/validate/_validate_core.py b/pipelex/cli/agent_cli/commands/validate/_validate_core.pyindex c07252202..cd1dd0766 100644--- a/pipelex/cli/agent_cli/commands/validate/_validate_core.py+++ b/pipelex/cli/agent_cli/commands/validate/_validate_core.py@@ -9,7 +9,7 @@ from pipelex.interpreter_hub import (get_current_library_id_or_none,get_library_manager,get_pipe_library,- get_required_pipe,+ get_required_entry_pipe,resolve_library_dirs,set_current_library,)@@ -156,7 +156,7 @@ async def validate_pipe_core(if effective_dirs:library_manager.load_libraries(library_id=library_id, library_dirs=effective_dirs)- the_pipe = get_required_pipe(pipe_code=pipe_code)+ the_pipe = get_required_entry_pipe(pipe_code=pipe_code)dry_run_results = await BundleValidator().validate_pipes(pipes=[the_pipe], library_id=library_id, allow_signatures=allow_signatures)return {diff --git a/pipelex/cli/commands/build/inputs/_inputs_core.py b/pipelex/cli/commands/build/inputs/_inputs_core.pyindex 08b160de8..50317e058 100644--- a/pipelex/cli/commands/build/inputs/_inputs_core.py+++ b/pipelex/cli/commands/build/inputs/_inputs_core.py@@ -15,7 +15,7 @@ from pipelex.cli.error_handlers import ()from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.core.pipes.inputs.exceptions import PipeInputError-from pipelex.interpreter_hub import get_library_manager, get_required_pipe, resolve_library_dirs, set_current_library+from pipelex.interpreter_hub import get_library_manager, get_required_entry_pipe, resolve_library_dirs, set_current_libraryfrom pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat, NoInputsRequiredError, render_inputs, render_inputs_tomlfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import PACKAGE_VERSION@@ -82,10 +82,10 @@ async def _generate_inputs_core(raise typer.Exit(1)try:- the_pipe = get_required_pipe(pipe_code=pipe_code)+ the_pipe = get_required_entry_pipe(pipe_code=pipe_code)except Exception as exc:# CLI command boundary: any failure resolving the pipe is reported to the user and exits via typer.Exit.- typer.secho(f"Error: Could not find pipe '{pipe_code}': {exc}", fg=typer.colors.RED)+ typer.secho(f"Error: Failed to resolve pipe '{pipe_code}': {exc}", fg=typer.colors.RED)raise typer.Exit(1) from excinputs_template_str: strdiff --git a/pipelex/cli/commands/build/output/_output_core.py b/pipelex/cli/commands/build/output/_output_core.pyindex 8fb531463..9ba47b88a 100644--- a/pipelex/cli/commands/build/output/_output_core.py+++ b/pipelex/cli/commands/build/output/_output_core.py@@ -15,7 +15,7 @@ from pipelex.cli.error_handlers import (from pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormatfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.core.pipes.inputs.exceptions import PipeInputError-from pipelex.interpreter_hub import get_library_manager, get_required_pipe, resolve_library_dirs, set_current_library+from pipelex.interpreter_hub import get_library_manager, get_required_entry_pipe, resolve_library_dirs, set_current_libraryfrom pipelex.pipe_machinery.rendering.output_renderer import render_outputfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import PACKAGE_VERSION@@ -81,10 +81,10 @@ async def _generate_output_core(raise typer.Exit(1)try:- the_pipe = get_required_pipe(pipe_code=pipe_code)+ the_pipe = get_required_entry_pipe(pipe_code=pipe_code)except Exception as exc:# CLI command boundary: any failure resolving the pipe is reported to the user and exits via typer.Exit.- typer.secho(f"Error: Could not find pipe '{pipe_code}': {exc}", fg=typer.colors.RED)+ typer.secho(f"Error: Failed to resolve pipe '{pipe_code}': {exc}", fg=typer.colors.RED)raise typer.Exit(1) from exctry:diff --git a/pipelex/cli/commands/build/runner/_runner_core.py b/pipelex/cli/commands/build/runner/_runner_core.pyindex c8f2777f8..e4745231c 100644--- a/pipelex/cli/commands/build/runner/_runner_core.py+++ b/pipelex/cli/commands/build/runner/_runner_core.py@@ -22,7 +22,7 @@ from pipelex.codegen.resolved_concepts import resolve_concepts_from_cratefrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.core.pipes.inputs.exceptions import PipeInputErrorfrom pipelex.core.pipes.variable_multiplicity import parse_concept_with_multiplicity-from pipelex.interpreter_hub import get_current_library_id_or_none, get_library_manager, get_required_pipe+from pipelex.interpreter_hub import get_current_library_id_or_none, get_library_manager, get_required_entry_pipefrom pipelex.libraries.crate_normalization import normalize_cratefrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import PACKAGE_VERSION@@ -83,10 +83,10 @@ async def _prepare_runner_core(raise typer.Exit(1)try:- the_pipe = get_required_pipe(pipe_code=pipe_code)+ the_pipe = get_required_entry_pipe(pipe_code=pipe_code)except Exception as exc:# CLI command boundary: any failure resolving the pipe is reported to the user and exits via typer.Exit.- typer.secho(f"Error: Could not find pipe '{pipe_code}': {exc}", fg=typer.colors.RED)+ typer.secho(f"Error: Failed to resolve pipe '{pipe_code}': {exc}", fg=typer.colors.RED)raise typer.Exit(1) from excif output_path:diff --git a/pipelex/cli/commands/codegen/inputs_cmd.py b/pipelex/cli/commands/codegen/inputs_cmd.pyindex 5e7c20256..20738a9e4 100644--- a/pipelex/cli/commands/codegen/inputs_cmd.py+++ b/pipelex/cli/commands/codegen/inputs_cmd.py@@ -18,7 +18,7 @@ from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTSfrom pipelex.cli.cli_factory import make_pipelex_for_clifrom pipelex.cli.commands.crate_loading import load_normalized_crate_or_exitfrom pipelex.cli.error_handlers import ErrorContext-from pipelex.interpreter_hub import get_required_pipe+from pipelex.interpreter_hub import get_required_entry_pipefrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.libraries.pipe.exceptions import PipeLibraryErrorfrom pipelex.pipe_machinery.pipe_abstract import PipeAbstract@@ -76,9 +76,9 @@ def codegen_inputs_cmd(pipe_ref = pipe or _default_main_pipe_ref(crate=crate)try:- the_pipe = get_required_pipe(pipe_code=pipe_ref)+ the_pipe = get_required_entry_pipe(pipe_code=pipe_ref)except PipeLibraryError as exc:- typer.secho(f"Cannot project inputs — pipe '{pipe_ref}' not found:\n{exc}", fg=typer.colors.RED, err=True)+ typer.secho(f"Cannot project inputs for pipe '{pipe_ref}':\n{exc}", fg=typer.colors.RED, err=True)raise typer.Exit(1) from exctry:diff --git a/pipelex/cli/commands/show_cmd.py b/pipelex/cli/commands/show_cmd.pyindex 73eca220d..7974d9140 100644--- a/pipelex/cli/commands/show_cmd.py+++ b/pipelex/cli/commands/show_cmd.py@@ -19,7 +19,8 @@ from pipelex.cli.error_handlers import ErrorContextfrom pipelex.cli.exceptions import PipelexCLIErrorfrom pipelex.cogt.model_backends.backend_library import InferenceBackendLibraryfrom pipelex.cogt.model_backends.model_lists import ModelLister-from pipelex.interpreter_hub import get_library_manager, get_pipe_library, get_required_pipe, resolve_library_dirs, set_current_library+from pipelex.interpreter_hub import get_library_manager, get_pipe_library, get_required_entry_pipe, resolve_library_dirs, set_current_library+from pipelex.libraries.pipe.exceptions import PipeLibraryErrorfrom pipelex.pipelex import Pipelexfrom pipelex.runtime_hub import get_console, get_models_manager, get_secrets_provider, get_telemetry_managerfrom pipelex.system.configuration.config_loader import config_manager@@ -55,7 +56,7 @@ def do_list_pipes() -> None:def do_show_pipe(pipe_code: str) -> None:"""Show a single pipe definition from the library."""- pipe = get_required_pipe(pipe_code=pipe_code)+ pipe = get_required_entry_pipe(pipe_code=pipe_code)get_telemetry_manager().track_event(EventName.PIPE_SHOW, properties={EventProperty.PIPE_TYPE: pipe.type})pretty_print(pipe, title=f"Pipe '{pipe_code}'")@@ -248,6 +249,15 @@ def show_pipe_cmd(else:assert pipe_code is not Nonedo_show_pipe(pipe_code=pipe_code)+ except PipeLibraryError as exc:+ # Entry-lookup failure on a user-supplied code (unknown, or a bare code declared in+ # several domains): report cleanly instead of letting the traceback escape.+ typer.secho(+ f"Failed to show pipe: {exc}",+ fg=typer.colors.RED,+ err=True,+ )+ raise typer.Exit(1) from excfinally:Pipelex.teardown_if_needed()diff --git a/pipelex/cli/commands/validate/_validate_core.py b/pipelex/cli/commands/validate/_validate_core.pyindex 14cfbee9f..ac7133943 100644--- a/pipelex/cli/commands/validate/_validate_core.py+++ b/pipelex/cli/commands/validate/_validate_core.py@@ -15,8 +15,15 @@ from pipelex.cli.error_handlers import (handle_validate_bundle_error,)from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError-from pipelex.interpreter_hub import get_library_manager, get_pipe_library, get_pipes, get_required_pipe, resolve_library_dirs, set_current_library-from pipelex.libraries.pipe.exceptions import PipeNotFoundError+from pipelex.interpreter_hub import (+ get_library_manager,+ get_pipe_library,+ get_pipes,+ get_required_entry_pipe,+ resolve_library_dirs,+ set_current_library,+)+from pipelex.libraries.pipe.exceptions import PipeLibraryError, PipeNotFoundErrorfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipe_signature.signature_walk import collect_signature_refsfrom pipelex.pipelex import Pipelex@@ -167,7 +174,7 @@ async def _validate_pipe_or_bundle(if effective_dirs:library_manager.load_libraries(library_id=library_id, library_dirs=effective_dirs)- pipe = get_required_pipe(pipe_code=pipe_code)+ pipe = get_required_entry_pipe(pipe_code=pipe_code)typer.echo(f"Validating pipe '{pipe_code}'...")# Signatures are never an error (D-B): a single-pipe validation reaching a PipeSignature# dry-runs trivially (the placeholder mints a mock). validate pipe makes no library-wide@@ -236,6 +243,15 @@ def execute_validate(err=True,)raise typer.Exit(2) from exc+ except PipeLibraryError as exc:+ # After the PipeNotFoundError arm (subclass ordering): reached by e.g. an ambiguous bare+ # code declared in several domains. An unresolvable target is a no-verdict exit 2.+ typer.secho(+ f"Failed to validate: {exc}",+ fg=typer.colors.RED,+ err=True,+ )+ raise typer.Exit(2) from excexcept PipeOperatorModelChoiceError as exc:handle_model_choice_error(exc, context=ErrorContext.VALIDATION, exit_code=2)except PipeOperatorModelAvailabilityError as exc:diff --git a/pipelex/cli/commands/which_cmd.py b/pipelex/cli/commands/which_cmd.pyindex 95fe153d6..68661d4ba 100644--- a/pipelex/cli/commands/which_cmd.py+++ b/pipelex/cli/commands/which_cmd.py@@ -6,11 +6,13 @@ from typing import TYPE_CHECKING, Annotatedimport typerfrom posthog import tag+from rich.markup import escapefrom pipelex import logfrom pipelex.cli.cli_factory import make_pipelex_for_clifrom pipelex.cli.error_handlers import ErrorContext-from pipelex.interpreter_hub import get_library_manager, get_optional_pipe, get_pipe_source, resolve_library_dirs, set_current_library+from pipelex.interpreter_hub import get_library_manager, get_optional_entry_pipe, get_pipe_source, resolve_library_dirs, set_current_library+from pipelex.libraries.pipe.exceptions import PipeLibraryErrorfrom pipelex.pipelex import Pipelexfrom pipelex.runtime_hub import get_console, get_telemetry_managerfrom pipelex.system.runtime import IntegrationMode@@ -27,8 +29,9 @@ def do_which_pipe(pipe_code: str, *, library_dirs: list[Path], source_label: str"""Locate where a pipe is defined."""console = get_console()- # Show search path- console.print(f"\n[bold]Search path for '[cyan]{pipe_code}[/cyan]':[/bold]")+ # Show search path. `pipe_code` is a raw CLI argument: escape it everywhere it meets markup,+ # so a code containing brackets renders literally instead of raising a MarkupError.+ console.print(f"\n[bold]Search path for '[cyan]{escape(pipe_code)}[/cyan]':[/bold]")if not library_dirs:console.print(" [dim](no directories configured)[/dim]")else:@@ -38,11 +41,19 @@ def do_which_pipe(pipe_code: str, *, library_dirs: list[Path], source_label: strconsole.print("")- # Try to find the pipe- pipe = get_optional_pipe(pipe_code=pipe_code)+ # Try to find the pipe. An ambiguous bare code raises rather than guessing, and `which` is+ # precisely the command someone runs to sort that out — so report the candidates instead of+ # letting the error escape as a traceback.+ try:+ pipe = get_optional_entry_pipe(pipe_code=pipe_code)+ except PipeLibraryError as exc:+ console.print(f"[red]Ambiguous:[/red] [bold]{escape(pipe_code)}[/bold]")+ console.print(f" {escape(str(exc))}")+ console.print("")+ return Falseif pipe:- console.print(f"[green]Found:[/green] [bold]{pipe_code}[/bold]")+ console.print(f"[green]Found:[/green] [bold]{escape(pipe_code)}[/bold]")console.print(f" Type: [cyan]{pipe.pipe_type}[/cyan]")console.print(f" Domain: [cyan]{pipe.domain_code}[/cyan]")source_path = get_pipe_source(pipe_code=pipe_code)@@ -52,7 +63,7 @@ def do_which_pipe(pipe_code: str, *, library_dirs: list[Path], source_label: strconsole.print("")return Trueelse:- console.print(f"[red]Not found:[/red] [bold]{pipe_code}[/bold]")+ console.print(f"[red]Not found:[/red] [bold]{escape(pipe_code)}[/bold]")console.print("\n[dim]Tip: Check that the pipe code is correct and that the containing[/dim]")console.print("[dim]directory is in PIPELEXPATH or passed via --library-dir[/dim]")console.print("")diff --git a/pipelex/core/concepts/concept_provider_abstract.py b/pipelex/core/concepts/concept_provider_abstract.pyindex 798f5f0a7..0233aad96 100644--- a/pipelex/core/concepts/concept_provider_abstract.py+++ b/pipelex/core/concepts/concept_provider_abstract.py@@ -30,8 +30,16 @@ class ConceptProviderAbstract(ABC):"""Resolve one of the native concepts."""@abstractmethod- def get_required_concept_from_concept_ref_or_code(self, concept_ref_or_code: str, *, search_domain_codes: list[str] | None = None) -> Concept:- """Resolve a ref *or* a bare code, optionally restricting the domains searched for a bare code."""+ def get_required_entry_concept(self, concept_ref_or_code: str, *, search_scope: str | None = None) -> Concept:+ """Resolve a concept string a *human* supplied — an input payload's `concept` field, a CLI argument.++ Entry-shaped lookup, not in-body reference resolution: natives resolve first, a+ fully-specified ref is a direct hit, and a bare code prefers `search_scope` (the entry+ pipe's own domain, `alias->domain` when the entry pipe came from a dependency package —+ in which case the rest of that package is searched next) before falling back to a+ crate-wide unique match. Every refusal — invalid string, no match, ambiguous bare code —+ raises the same exception class, so entry boundaries catch one thing.+ """@abstractmethoddef is_compatible(self, *, tested_concept: Concept, wanted_concept: Concept, strict: bool = False) -> bool:diff --git a/pipelex/core/memory/input_shaper.py b/pipelex/core/memory/input_shaper.pyindex c3a9f71de..902cbd041 100644--- a/pipelex/core/memory/input_shaper.py+++ b/pipelex/core/memory/input_shaper.py@@ -99,7 +99,7 @@ class InputShaper:*,concept_provider: ConceptProviderAbstract,input_specs: InputStuffSpecs,- search_domain_codes: list[str] | None = None,+ search_scope: str | None = None,inputs_base_dir: Path | None = None,) -> WorkingMemory:"""Shape every provided input against its declared ``StuffSpec`` and return a WorkingMemory.@@ -110,7 +110,8 @@ class InputShaper:than looked up so this module stays out of the method interpreter's import closure(see hub-layering); the caller holds the loaded method's library.input_specs: The entry pipe's declared inputs (name -> StuffSpec).- search_domain_codes: Domain codes used to resolve envelope/object concepts.+ search_scope: The entry pipe's own scope (its domain, `alias->domain` for a dependency+ entry pipe), preferred when resolving a bare envelope/object concept code.inputs_base_dir: Directory that bare *relative local* file paths resolve against (D3) —the inputs file's parent when the inputs were loaded from a file (threaded from theCLI). ``None`` (in-process / inline-JSON callers) leaves relative paths untouched@@ -130,7 +131,7 @@ class InputShaper:concept_provider=concept_provider,stuff_spec=stuff_spec,variable_name=variable_name,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,inputs_base_dir=inputs_base_dir,)working_memory.add_new_stuff(name=variable_name, stuff=stuff)@@ -153,7 +154,7 @@ class InputShaper:concept_provider: ConceptProviderAbstract,stuff_spec: StuffSpec,variable_name: str,- search_domain_codes: list[str] | None,+ search_scope: str | None,inputs_base_dir: Path | None,) -> Stuff:declared_concept = stuff_spec.concept@@ -167,7 +168,7 @@ class InputShaper:declared_concept=declared_concept,stuff_spec=stuff_spec,variable_name=variable_name,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,)# (D9) A top-level null is never a value — absence is expressed by omitting the key.@@ -188,7 +189,7 @@ class InputShaper:stuff_content_or_data=value,concept_provider=concept_provider,name=variable_name,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,)case (InputKind.TEXT@@ -206,7 +207,7 @@ class InputShaper:stuff_spec=stuff_spec,input_kind=input_kind,variable_name=variable_name,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,inputs_base_dir=inputs_base_dir,)return StuffFactory.make_stuff(concept=declared_concept, content=content, name=variable_name)@@ -265,7 +266,7 @@ class InputShaper:stuff_spec: StuffSpec,input_kind: InputKind,variable_name: str,- search_domain_codes: list[str] | None,+ search_scope: str | None,inputs_base_dir: Path | None,) -> StuffContent:"""Peel the declared multiplicity (D2), then build the item content(s)."""@@ -297,7 +298,7 @@ class InputShaper:input_kind=input_kind,variable_name=variable_name,fixed_count=fixed_count,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,inputs_base_dir=inputs_base_dir,)@@ -315,7 +316,7 @@ class InputShaper:input_kind=input_kind,stuff_spec=stuff_spec,variable_name=variable_name,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,inputs_base_dir=inputs_base_dir,)@@ -371,7 +372,7 @@ class InputShaper:input_kind: InputKind,variable_name: str,fixed_count: int | None,- search_domain_codes: list[str] | None,+ search_scope: str | None,inputs_base_dir: Path | None,) -> ListContent[StuffContent]:"""Shape a declared-multiple input element-wise into a ListContent (D2)."""@@ -392,7 +393,7 @@ class InputShaper:input_kind=input_kind,stuff_spec=stuff_spec,variable_name=variable_name,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,inputs_base_dir=inputs_base_dir,)for item_value in item_values@@ -408,7 +409,7 @@ class InputShaper:input_kind: InputKind,stuff_spec: StuffSpec,variable_name: str,- search_domain_codes: list[str] | None,+ search_scope: str | None,inputs_base_dir: Path | None,) -> StuffContent:"""Build one item's ``StuffContent`` from a value, dispatched on the declared kind (D5).@@ -423,7 +424,7 @@ class InputShaper:concept = stuff_spec.conceptif isinstance(value, StuffContent):built = StuffFactory.make_stuff_from_stuff_content_or_data(- stuff_content_or_data=value, concept_provider=concept_provider, name=variable_name, search_domain_codes=search_domain_codes+ stuff_content_or_data=value, concept_provider=concept_provider, name=variable_name, search_scope=search_scope)if not concept_provider.is_compatible(tested_concept=built.concept, wanted_concept=concept):raise ExplicitConceptIncompatibleError.make(@@ -577,7 +578,7 @@ class InputShaper:declared_concept: Concept,stuff_spec: StuffSpec,variable_name: str,- search_domain_codes: list[str] | None,+ search_scope: str | None,) -> Stuff:"""Build an explicit form bottom-up, then compat-check the built concept against declared (D6).@@ -590,7 +591,7 @@ class InputShaper:stuff_content_or_data=cast("StuffContentOrData", value),concept_provider=concept_provider,name=variable_name,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,)if not concept_provider.is_compatible(tested_concept=stuff.concept, wanted_concept=declared_concept):raise ExplicitConceptIncompatibleError.make(diff --git a/pipelex/core/memory/working_memory_factory.py b/pipelex/core/memory/working_memory_factory.pyindex 3a652706e..079a7bfb4 100644--- a/pipelex/core/memory/working_memory_factory.py+++ b/pipelex/core/memory/working_memory_factory.py@@ -75,7 +75,7 @@ class WorkingMemoryFactory(BaseModel):*,concept_provider: ConceptProviderAbstract,input_specs: InputStuffSpecs | None = None,- search_domain_codes: list[str] | None = None,+ search_scope: str | None = None,inputs_base_dir: Path | None = None,) -> WorkingMemory:"""Create a WorkingMemory from a pipeline inputs dictionary.@@ -93,7 +93,8 @@ class WorkingMemoryFactory(BaseModel):than looked up so this module stays out of the method interpreter's import closure(see hub-layering); the caller holds the loaded method's library.input_specs: The entry pipe's declared inputs; ``None`` disables signature-driven shaping- search_domain_codes: List of domain codes to search for concepts+ search_scope: The entry pipe's own scope (its domain, `alias->domain` for a dependency+ entry pipe), preferred when resolving a bare concept codeinputs_base_dir: Directory that bare *relative local* file paths resolve against (D3);the inputs file's parent when inputs were file-loaded by a CLI. ``None`` for API/SDKand in-process callers (they pass absolute urls / storage uris). Only consulted by@@ -108,7 +109,7 @@ class WorkingMemoryFactory(BaseModel):pipeline_inputs,concept_provider=concept_provider,input_specs=input_specs,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,inputs_base_dir=inputs_base_dir,)@@ -119,7 +120,7 @@ class WorkingMemoryFactory(BaseModel):name=stuff_key,stuff_content_or_data=stuff_content_or_data,concept_provider=concept_provider,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,)working_memory.add_new_stuff(name=stuff_key, stuff=stuff)return working_memorydiff --git a/pipelex/core/stuffs/stuff_factory.py b/pipelex/core/stuffs/stuff_factory.pyindex 43118e3a3..be51e5466 100644--- a/pipelex/core/stuffs/stuff_factory.py+++ b/pipelex/core/stuffs/stuff_factory.py@@ -244,6 +244,26 @@ class StuffFactory:raise CsvError(msg) from excreturn list_content_from_csv(Path(resolved.path), row_model=row_model)+ @classmethod+ def _resolve_entry_concept(+ cls,+ *,+ concept_provider: ConceptProviderAbstract,+ concept_ref_or_code: str,+ search_scope: str | None,+ context_msg: str,+ ) -> Concept:+ """Resolve a human-supplied concept string, wrapping any refusal with the caller's context.++ The one place the entry-concept boundary is caught: every input shape funnels through+ here, so a change to what the lookup raises or how the failure reads is a single edit.+ """+ try:+ return concept_provider.get_required_entry_concept(concept_ref_or_code=concept_ref_or_code, search_scope=search_scope)+ except ConceptLibraryConceptNotFoundError as exc:+ msg = f"{context_msg} the concept of name '{concept_ref_or_code}' could not be resolved: {exc}"+ raise StuffFactoryError(msg) from exc+@classmethoddef make_stuff_from_stuff_content_or_data(cls,@@ -252,7 +272,7 @@ class StuffFactory:concept_provider: ConceptProviderAbstract,name: str | None = None,code: str | None = None,- search_domain_codes: list[str] | None = None,+ search_scope: str | None = None,) -> Stuff:"""Create a Stuff from StuffContentOrData covering all pipeline inputs cases.@@ -329,16 +349,12 @@ class StuffFactory:):concept = concept_provider.get_native_concept(native_concept=NativeConceptCode(content_class_name.split("Content")[0]))else:- try:- concept = concept_provider.get_required_concept_from_concept_ref_or_code(- concept_ref_or_code=content_class_name, search_domain_codes=search_domain_codes- )- except ConceptLibraryConceptNotFoundError as exc:- msg = (- f"Trying to create a Stuff '{name}' from a ListContent but "- f"the concept of name '{content_class_name}' is not found in the library"- )- raise StuffFactoryError(msg) from exc+ concept = cls._resolve_entry_concept(+ concept_provider=concept_provider,+ concept_ref_or_code=content_class_name,+ search_scope=search_scope,+ context_msg=f"Trying to create a Stuff '{name}' from a ListContent but",+ )return cls.make_stuff(concept=concept,@@ -360,16 +376,12 @@ class StuffFactory:concept = concept_provider.get_native_concept(native_concept=NativeConceptCode(content_class_name.split("Content")[0]))else:# It's a StructuredContent, try to find the concept- try:- concept = concept_provider.get_required_concept_from_concept_ref_or_code(- concept_ref_or_code=content_class_name, search_domain_codes=search_domain_codes- )- except ConceptLibraryConceptNotFoundError as exc:- msg = (- f"Trying to create a Stuff '{name}' from a StuffContent '{content_class_name}' "- f"but the concept of name '{content_class_name}' is not found in the library"- )- raise StuffFactoryError(msg) from exc+ concept = cls._resolve_entry_concept(+ concept_provider=concept_provider,+ concept_ref_or_code=content_class_name,+ search_scope=search_scope,+ context_msg=f"Trying to create a Stuff '{name}' from a StuffContent '{content_class_name}' but",+ )return cls.make_stuff(concept=concept,@@ -425,16 +437,12 @@ class StuffFactory:):concept = concept_provider.get_native_concept(native_concept=NativeConceptCode(content_class_name.split("Content")[0]))else:- try:- concept = concept_provider.get_required_concept_from_concept_ref_or_code(- concept_ref_or_code=content_class_name, search_domain_codes=search_domain_codes- )- except ConceptLibraryConceptNotFoundError as exc:- msg = (- f"Trying to create a Stuff '{name}' from a list of StuffContent but "- f"the concept of name '{content_class_name}' is not found in the library"- )- raise StuffFactoryError(msg) from exc+ concept = cls._resolve_entry_concept(+ concept_provider=concept_provider,+ concept_ref_or_code=content_class_name,+ search_scope=search_scope,+ context_msg=f"Trying to create a Stuff '{name}' from a list of StuffContent but",+ )return cls.make_stuff(concept=concept,@@ -476,16 +484,12 @@ class StuffFactory:content = stuff_content_or_data["content"]# Get the concept from the library- try:- concept = concept_provider.get_required_concept_from_concept_ref_or_code(- concept_ref_or_code=concept_ref, search_domain_codes=search_domain_codes- )- except ConceptLibraryConceptNotFoundError as exc:- msg = (- f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a dict that should represent a StuffContentOrData "- f"but the concept of name '{concept_ref}' is not found in the library"- )- raise StuffFactoryError(msg) from exc+ concept = cls._resolve_entry_concept(+ concept_provider=concept_provider,+ concept_ref_or_code=concept_ref,+ search_scope=search_scope,+ context_msg=f"Trying to create a Stuff '{name}' in the inputs of your pipe, from a dict that should represent a StuffContentOrData but",+ )# Case 2.1d: content is a bool → YesNoContent for a YesNo-compatible concept.# Checked BEFORE the str/int-ish arms (bool is a subclass of int) so a boolean never falls through todiff --git a/pipelex/interpreter_hub.py b/pipelex/interpreter_hub.pyindex 5db8f932b..b8c35e378 100644--- a/pipelex/interpreter_hub.py+++ b/pipelex/interpreter_hub.py@@ -350,6 +350,20 @@ def get_optional_pipe(pipe_code: str) -> PipeAbstract | None:return get_interpreter_hub().get_required_pipe_library().get_optional_pipe(pipe_code=pipe_code)+def get_required_entry_pipe(pipe_code: str) -> PipeAbstract:+ """Resolve a pipe code a human supplied at an entry point (CLI argument, API field).++ Use this — not `get_required_pipe` — whenever the code came from outside the method rather than+ from inside another pipe. It matches a bare code across domains and ignores `[exports]`.+ """+ return get_interpreter_hub().get_required_pipe_library().get_required_entry_pipe(pipe_code=pipe_code)+++def get_optional_entry_pipe(pipe_code: str) -> PipeAbstract | None:+ """`get_required_entry_pipe`'s optional twin, for callers that report a miss themselves."""+ return get_interpreter_hub().get_required_pipe_library().get_optional_entry_pipe(pipe_code=pipe_code)++def get_pipe_source(pipe_code: str) -> str | None:"""Get the source identifier for a pipe.diff --git a/pipelex/kernel/memory_ops.py b/pipelex/kernel/memory_ops.pyindex c4d7fee0a..f6a5745e8 100644--- a/pipelex/kernel/memory_ops.py+++ b/pipelex/kernel/memory_ops.py@@ -34,7 +34,7 @@ def shape_inputs(inputs: PipelineInputs,concept_provider: ConceptProviderAbstract,input_specs: InputStuffSpecs,- search_domain_codes: list[str] | None = None,+ search_scope: str | None = None,inputs_base_dir: Path | None = None,) -> WorkingMemory:"""Interpret a caller's raw inputs against their declared specs and return the memory to run on.@@ -60,7 +60,7 @@ def shape_inputs(inputs,concept_provider=concept_provider,input_specs=input_specs,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,inputs_base_dir=inputs_base_dir,)diff --git a/pipelex/kit/agent_rules/codex_commands.md b/pipelex/kit/agent_rules/codex_commands.mdindex f3bf73bac..7461088f4 100644--- a/pipelex/kit/agent_rules/codex_commands.md+++ b/pipelex/kit/agent_rules/codex_commands.md@@ -7,7 +7,7 @@```bashmake agent-check# If the current system doesn't have the `make` command,- # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format generate-mthds-schema lint pyright mypy check-keyword-only)+ # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-keyword-only check-hub-layering drift-check)```This runs multiple code quality tools:@@ -15,6 +15,7 @@- Ruff: Fix unused imports, lint, format- Mypy: Static type checker- plxt: Format and lint TOML, MTHDS, and PLX files+ - Drift contracts: open code↔docs review obligations fail the gate (note the digest reads the git index, so stage your changes for the check to see them)Always fix any issues reported by these tools before proceeding.diff --git a/pipelex/kit/agent_rules/commands.md b/pipelex/kit/agent_rules/commands.mdindex 39d9f763b..52eba80c6 100644--- a/pipelex/kit/agent_rules/commands.md+++ b/pipelex/kit/agent_rules/commands.md@@ -7,7 +7,7 @@```bashmake agent-check# If the current system doesn't have the `make` command,- # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format generate-mthds-schema lint pyright mypy check-keyword-only)+ # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-keyword-only check-hub-layering drift-check)```This runs multiple code quality tools:@@ -15,6 +15,7 @@- Ruff: Fix unused imports, lint, format- Mypy: Static type checker- plxt: Format and lint TOML, MTHDS, and PLX files+ - Drift contracts: open code↔docs review obligations fail the gate (note the digest reads the git index, so stage your changes for the check to see them; resolve with the drift workflow below)Always fix any issues reported by these tools before proceeding.@@ -141,7 +142,7 @@.venv/bin/pipelex-dev refresh-graph-ui-sri --mthds-ui-version 0.6.3 --elkjs-version 0.11.1```- - **`drift`**: Drift contracts — deterministic review obligations between code and docs, declared in the root `drift.toml` (see `docs/contribute/drift-contracts.md`). When `make drift-check` (part of `make check` and CI) reports an open contract: run `make drift-plan` to see what changed and what to review, actually review the targets and fix what is stale, `git add` the trigger files (the digest reads the git index, not the working tree), then record the review with `make drift-ack CONTRACT=<id> RATIONALE="…"`. The rationale is the on-the-record review decision — write an honest sentence. There is no bypass flag; "reviewed, no doc change needed" is a legitimate rationale.+ - **`drift`**: Drift contracts — deterministic review obligations between code and docs, declared in the root `drift.toml` (see `docs/contribute/drift-contracts.md`). When `make drift-check` (part of `make agent-check`, `make check`, and CI) reports an open contract: run `make drift-plan` to see what changed and what to review, actually review the targets and fix what is stale, `git add` the trigger files (the digest reads the git index, not the working tree), then record the review with `make drift-ack CONTRACT=<id> RATIONALE="…"`. The rationale is the on-the-record review decision — write an honest sentence. There is no bypass flag; "reviewed, no doc change needed" is a legitimate rationale.```bashmake drift-plandiff --git a/pipelex/libraries/concept/concept_library.py b/pipelex/libraries/concept/concept_library.pyindex ea78c49df..7389616b4 100644--- a/pipelex/libraries/concept/concept_library.py+++ b/pipelex/libraries/concept/concept_library.py@@ -178,49 +178,129 @@ class ConceptLibrary(RootModel[ConceptLibraryRoot], ConceptLibraryAbstract):"""Create all native concepts from the hardcoded data"""return [self.get_native_concept(native_concept=native_concept) for native_concept in NativeConceptCode.values_list()]- @override- def get_required_concept_from_concept_ref_or_code(self, concept_ref_or_code: str, *, search_domain_codes: list[str] | None = None) -> Concept:+ def get_optional_entry_concept(self, concept_ref_or_code: str, *, search_scope: str | None = None) -> Concept | None:+ """Resolve a concept string a **human** supplied — an input payload's `concept` field, a CLI argument.++ Entry-shaped lookup, the concept twin of `PipeLibrary.get_optional_entry_pipe` — kept a+ deliberate near-copy rather than a shared helper (see+ wip/pipe-refs/entry-affordance-share-vs-duplicate.md). Natives resolve first, per the+ standard's own step 1. A fully-specified ref (`domain.Concept`, `alias->domain.Concept`)+ is a direct hit or a miss. A bare code prefers `search_scope` — the entry pipe's own+ domain, carried as `alias->domain` when the entry pipe came from a dependency package —+ then, under an aliased scope, the rest of that dependency package (which may span several+ domains, all keyed under its one alias), then a crate-wide unique match. Dotted refs obey+ the same precedence: under an aliased scope the dependency's own `domain.Concept` wins+ over a host concept spelled identically. An ambiguous bare code raises rather than+ picking a winner.++ Aliased dependency entries are excluded from the crate-wide search: installing an+ unrelated package must not make a host concept's bare code ambiguous. They stay reachable+ through `search_scope` (the dependency the entry pipe belongs to) or an explicit+ `alias->…` ref.++ Raises:+ ConceptLibraryConceptNotFoundError: the string is not a valid concept ref or code,+ or a bare code matches concepts in several domains. One class for every refusal,+ so entry boundaries catch a single exception.+ """try:validate_concept_ref_or_code(concept_ref_or_code=concept_ref_or_code)except ConceptStringError as exc:msg = f"Could not validate concept string or code '{concept_ref_or_code}': {exc}"- raise ConceptLibraryError(msg) from exc+ raise ConceptLibraryConceptNotFoundError(msg) from exc- # Cross-package refs are looked up via get_required_concept which handles them+ # Aliased ref: resolve within that package only. `alias->domain.Concept` is a direct hit;+ # `alias->Concept` searches the package the way a bare code searches the host crate.if QualifiedRef.has_cross_package_prefix(concept_ref_or_code):- return self.get_required_concept(concept_ref=concept_ref_or_code)+ the_concept = self.root.get(concept_ref_or_code)+ if the_concept is not None:+ return the_concept+ ref_alias, remainder = QualifiedRef.split_cross_package_ref(concept_ref_or_code)+ if "." not in remainder:+ return self._search_dependency_package(alias=ref_alias, concept_code=remainder)+ return Noneif NativeConceptCode.is_native_concept_ref_or_code(concept_ref_or_code=concept_ref_or_code):native_concept_ref = NativeConceptCode.get_validated_native_concept_ref(concept_ref_or_code=concept_ref_or_code)return self.get_native_concept(native_concept=NativeConceptCode(native_concept_ref.split(".")[1]))- elif "." in concept_ref_or_code:- return self.get_required_concept(concept_ref=concept_ref_or_code)- else:- found_concepts: list[Concept] = []- if search_domain_codes is None:- for concept in self.root.values():- if concept_ref_or_code == concept.code:- found_concepts.append(concept)- if len(found_concepts) == 0:- msg = f"Concept '{concept_ref_or_code}' not found in the library and no search domains were provided"- raise ConceptLibraryConceptNotFoundError(msg)- if len(found_concepts) > 1:- msg = f"Multiple concepts found for '{concept_ref_or_code}': {found_concepts}. Please specify the domain."- raise ConceptLibraryConceptNotFoundError(msg)- return found_concepts[0]++ scope_alias: str | None = None+ scope_domain: str | None = None+ if search_scope:+ if QualifiedRef.has_cross_package_prefix(search_scope):+ scope_alias, scope_domain = QualifiedRef.split_cross_package_ref(search_scope)else:- for domain_code in search_domain_codes:- if found_concept := self.get_required_concept(- concept_ref=ConceptFactory.make_concept_ref_with_domain(domain_code=domain_code, concept_code=concept_ref_or_code),- ):- found_concepts.append(found_concept)- if len(found_concepts) == 0:- msg = f"Concept '{concept_ref_or_code}' not found in the library and no search domains were provided"- raise ConceptLibraryConceptNotFoundError(msg)- if len(found_concepts) > 1:- msg = f"Multiple concepts found for '{concept_ref_or_code}': {found_concepts}. Please specify the domain."- raise ConceptLibraryConceptNotFoundError(msg)- return found_concepts[0]+ scope_domain = search_scope++ if "." in concept_ref_or_code:+ if scope_alias:+ # Scope wins for dotted refs too: the entry pipe came from a dependency package+ # whose concepts are keyed under the alias, so a ref naming one of that package's+ # own domains reaches the package's concept even when the host declares the same+ # `domain.Concept` spelling — same precedence as the bare-code arm below.+ the_concept = self.root.get(f"{scope_alias}->{concept_ref_or_code}")+ if the_concept is not None:+ return the_concept+ return self.root.get(concept_ref_or_code)++ # Bare code: the entry pipe's own scope wins before any search.+ if scope_domain:+ scoped_ref = ConceptFactory.make_concept_ref_with_domain(domain_code=scope_domain, concept_code=concept_ref_or_code)+ if scope_alias:+ scoped_ref = f"{scope_alias}->{scoped_ref}"+ the_concept = self.root.get(scoped_ref)+ if the_concept is not None:+ return the_concept++ # A dependency entry pipe then searches the rest of its own package: a multi-domain+ # dependency keys every concept under its one alias, so the bare code may be declared in+ # a sibling domain of the same package.+ if scope_alias:+ the_concept = self._search_dependency_package(alias=scope_alias, concept_code=concept_ref_or_code)+ if the_concept is not None:+ return the_concept++ matches = [+ concept for key, concept in self.root.items() if not QualifiedRef.has_cross_package_prefix(key) and concept.code == concept_ref_or_code+ ]+ if len(matches) == 1:+ return matches[0]+ if len(matches) > 1:+ candidates = sorted(match.concept_ref for match in matches)+ msg = f"Concept code '{concept_ref_or_code}' is ambiguous — it is declared by {candidates}. Name one of them explicitly."+ raise ConceptLibraryConceptNotFoundError(msg)+ return None++ @override+ def get_required_entry_concept(self, concept_ref_or_code: str, *, search_scope: str | None = None) -> Concept:+ the_concept = self.get_optional_entry_concept(concept_ref_or_code=concept_ref_or_code, search_scope=search_scope)+ if not the_concept:+ msg = f"Concept '{concept_ref_or_code}' not found in the library. Check for typos and make sure its bundle is loaded."+ raise ConceptLibraryConceptNotFoundError(msg)+ return the_concept++ def _search_dependency_package(self, *, alias: str, concept_code: str) -> Concept | None:+ """Search one dependency package's aliased entries for a bare concept code.++ The package-scoped twin of the crate-wide bare-code search: a dependency may span several+ domains, all keyed under its one alias. Alias-scoped by construction, so it can never+ reach a host concept.++ Raises:+ ConceptLibraryConceptNotFoundError: the code is declared in several of the package's domains.+ """+ prefix = f"{alias}->"+ matches = [concept for key, concept in self.root.items() if key.startswith(prefix) and concept.code == concept_code]+ if len(matches) == 1:+ return matches[0]+ if len(matches) > 1:+ candidates = sorted(f"{prefix}{match.concept_ref}" for match in matches)+ msg = (+ f"Concept code '{concept_code}' is ambiguous within dependency '{alias}' — it is declared by {candidates}. "+ "Name one of them explicitly."+ )+ raise ConceptLibraryConceptNotFoundError(msg)+ return Nonedef add_dependency_concept(self, *, alias: str, concept: Concept) -> None:"""Add a concept from a dependency package with an aliased key.diff --git a/pipelex/libraries/concept_reference_validation.py b/pipelex/libraries/concept_reference_validation.pyindex f7c63a10c..e6daf5007 100644--- a/pipelex/libraries/concept_reference_validation.py+++ b/pipelex/libraries/concept_reference_validation.py@@ -88,7 +88,7 @@ def validate_concept_references_in_blueprints(# `native.Text` only) — not a bare local-code match — so a same-domain ref that merely# *shares* a native local code (e.g. `mydomain.Text`) is NOT mistaken for native and still# gets the membership check. This matches how the concept actually resolves- # (ConceptLibrary.get_required_concept_from_concept_ref_or_code) and contract_match.+ # (ConceptLibrary.get_optional_entry_concept) and contract_match.if NativeConceptCode.is_native_concept_ref_or_code(concept_ref_or_code=concept_ref_or_code):continueconcept_ref = ConceptFactory.make_concept_ref_with_domain(domain_code=domain_code, concept_code=ref.local_code)diff --git a/pipelex/libraries/crate_normalization.py b/pipelex/libraries/crate_normalization.pyindex 7e18534a3..b55cf62e5 100644--- a/pipelex/libraries/crate_normalization.py+++ b/pipelex/libraries/crate_normalization.py@@ -7,9 +7,8 @@ is closed, canonical, and explicit:1. merge — already done upstream (keys are `domain.Code` / `domain.code`);2. fully qualify every *in-body* reference — pipe `inputs` / `output` concept refs, pipe-step / branch/ outcome / batch pipe refs, concept `refines`, and structure-field `concept_ref` / `item_concept_ref`.- A bare *pipe* ref resolves crate-wide (`_qualify_pipe_ref`), the way `PipeLibrary.get_optional_pipe`- does, so the normalized ref names the pipe an interpreted run would call — including when the callee- is declared in a sibling domain;+ Delegated to `qualify_crate` (see `crate_qualification`), which owns the reference-resolution rule+ so it is stated once rather than mirrored per consumer;3. flatten refinement — a refining concept adopts its **in-crate structured** base's effectivestructure (the `refines` link is dropped once the structure is materialized). A concept whoserefinement chain bottoms out at a **native** keeps its `refines` link: the native is materialized@@ -25,7 +24,7 @@ Deferred normalization steps (the spec's [Library Crate Format] "Normalization Pare not yet applied here, mirroring the spec's own "Specification Status" callout):- materialize defaults and multiplicity (spec step 5): multiplicity markers already present on a ref are- preserved (`_render_ref_with_markers`), but a bare singular ref is not rewritten to an explicit form,+ preserved by the qualification pass, but a bare singular ref is not rewritten to an explicit form,and default values are not yet materialized;- cross-package (`alias->…`) references: the referenced dependency content is not folded into this crateyet, so those refs are left intact rather than rewritten to a canonical ref that would dangle. A@@ -34,25 +33,19 @@ are not yet applied here, mirroring the spec's own "Specification Status" callou[Library Crate Format]: mthds/docs/spec/library-crate.md"""-from collections import defaultdictfrom typing import NamedTuplefrom pipelex.codegen.native_expansion import collect_native_refs_from_structure, materialize_native_conceptfrom pipelex.core.concepts.concept_blueprint import ConceptBlueprint-from pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprintfrom pipelex.core.concepts.helpers import normalize_structure_blueprintfrom pipelex.core.concepts.native.concept_native import NativeConceptCode-from pipelex.core.pipes.variable_multiplicity import MultiplicityParseResult, parse_concept_with_multiplicity+from pipelex.core.pipes.variable_multiplicity import parse_concept_with_multiplicityfrom pipelex.core.qualified_ref import QualifiedRef+from pipelex.libraries.crate_qualification import qualify_cratefrom pipelex.libraries.exceptions import CrateNormalizationErrorfrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.mthds_parsing.pipelex_bundle_blueprint import PipeBlueprintUnion-from pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint-from pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprint-from pipelex.pipe_controllers.condition.special_outcome import SpecialOutcome-from pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprint-from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint_ConceptEntry = ConceptBlueprint | str@@ -67,19 +60,29 @@ def normalize_crate(crate: LibraryCrate, *, mthds_version: str) -> LibraryCrate:The input crate must already be assembled and key-qualified (e.g. from`LibraryCrateFactory.make_from_blueprints` over a validated library, per D6). The output carries- the normalized `fingerprint` (D2 scope) and the `mthds_version` stamp.+ the normalized `fingerprint` (D2 scope) and the `mthds_version` stamp; `qualify_crate` returns+ content only, so the envelope is assembled here.++ Qualification runs as one complete phase up front, over concepts *and* pipes, rather than+ interleaved with the steps below. So a crate carrying two independent defects — say a refinement+ cycle *and* an unqualified crate key — reports the key first, where the interleaved version could+ report the cycle. Both are `CrateNormalizationError` and the crate is invalid either way; which+ defect is named first is not a contract.++ The pass qualifies but does not resolve, so a normalized crate is closed over its pipe refs only+ because the library it came from validated first. Feed this an unvalidated crate whose pipe+ references a sibling domain by bare code and you get a crate naming a pipe that does not exist —+ which is the point: that ref was never resolvable by the rule, and validation is where it is+ reported."""+ qualified = qualify_crate(crate)+concepts: dict[str, _ConceptEntry] = {- concept_ref: _normalize_concept(value, owner_domain=_domain_of(concept_ref), source=crate.source_map.get(concept_ref))- for concept_ref, value in crate.concepts.items()+ concept_ref: _normalize_concept(value, source=crate.source_map.get(concept_ref)) for concept_ref, value in qualified.concepts.items()}_flatten_refinement(concepts)- pipe_refs_by_code = _index_pipe_refs_by_code(pipes=crate.pipes)- pipes: dict[str, PipeBlueprintUnion] = {- pipe_ref: _normalize_pipe(blueprint, owner_domain=_domain_of(pipe_ref), pipe_refs_by_code=pipe_refs_by_code)- for pipe_ref, blueprint in crate.pipes.items()- }+ pipes = qualified.pipes_expand_natives(concepts=concepts, pipes=pipes)@@ -94,48 +97,21 @@ def normalize_crate(crate: LibraryCrate, *, mthds_version: str) -> LibraryCrate:)-def _domain_of(qualified_ref: str) -> str:- domain_path = QualifiedRef.parse(qualified_ref).domain_path- if domain_path is None:- msg = f"Crate key '{qualified_ref}' is not domain-qualified; the normalizer expects a merged, key-qualified crate."- raise CrateNormalizationError(msg)- return domain_path--# --------------------------------------------------------------------------------------------------# Concepts# ---------------------------------------------------------------------------------------------------def _normalize_concept(value: _ConceptEntry, *, owner_domain: str, source: str | None) -> _ConceptEntry:+def _normalize_concept(value: _ConceptEntry, *, source: str | None) -> _ConceptEntry:+ """Materialize the authoring shorthands. In-body refs are already qualified by `qualify_crate`."""# String-described concept -> explicit description-only ConceptBlueprint (structureless).if isinstance(value, str):return ConceptBlueprint(source=source, description=value)- updates: dict[str, object] = {}- if value.refines:- updates["refines"] = ConceptFactory.make_refine(value.refines, domain_code=owner_domain)- if isinstance(value.structure, dict):- normalized_structure = normalize_structure_blueprint(value.structure)- updates["structure"] = {- field_name: _qualify_structure_field(field_blueprint, domain=owner_domain) for field_name, field_blueprint in normalized_structure.items()- }- return value.model_copy(update=updates) if updates else value---def _qualify_structure_field(field_blueprint: ConceptStructureBlueprint, *, domain: str) -> ConceptStructureBlueprint:- field_updates: dict[str, object] = {}- if field_blueprint.concept_ref:- field_updates["concept_ref"] = _qualify_concept_ref(field_blueprint.concept_ref, domain=domain)- if field_blueprint.item_concept_ref:- field_updates["item_concept_ref"] = _qualify_concept_ref(field_blueprint.item_concept_ref, domain=domain)- return field_blueprint.model_copy(update=field_updates) if field_updates else field_blueprint---def _qualify_concept_ref(concept_ref_or_code: str, *, domain: str) -> str:- # make_concept_ref_with_domain_from_concept_ref_or_code resolves natives to `native.<Code>`,- # bare refs to `domain.<Code>`, and preserves cross-package `alias->domain.Code` as-is (deferred).- return ConceptFactory.make_concept_ref_with_domain_from_concept_ref_or_code(domain_code=domain, concept_ref_or_code=concept_ref_or_code)+ if not isinstance(value.structure, dict):+ return value+ # String structure fields -> explicit `text` fields.+ return value.model_copy(update={"structure": normalize_structure_blueprint(value.structure)})def _flatten_refinement(concepts: dict[str, _ConceptEntry]) -> None:@@ -221,99 +197,6 @@ def _native_effective_structure(native_ref: str) -> dict[str, ConceptStructureBlreturn {field_name: field for field_name, field in materialized.structure.items() if isinstance(field, ConceptStructureBlueprint)}-# ---------------------------------------------------------------------------------------------------# Pipes-# -----------------------------------------------------------------------------------------------------def _index_pipe_refs_by_code(*, pipes: dict[str, PipeBlueprintUnion]) -> dict[str, list[str]]:- """Group the crate's own pipe refs by bare code — the index a bare in-body ref resolves against.-- Cross-package entries are excluded, mirroring `PipeLibrary.get_optional_pipe`, whose bare-code- fallback searches only the entries that are not `alias->…` prefixed.- """- by_code: dict[str, list[str]] = defaultdict(list)- for pipe_ref in pipes:- if QualifiedRef.has_cross_package_prefix(pipe_ref):- continue- by_code[QualifiedRef.parse(pipe_ref).local_code].append(pipe_ref)- return by_code---def _normalize_pipe(blueprint: PipeBlueprintUnion, *, owner_domain: str, pipe_refs_by_code: dict[str, list[str]]) -> PipeBlueprintUnion:- updates: dict[str, object] = {}- if blueprint.inputs:- updates["inputs"] = {name: _qualify_io_ref(ref, domain=owner_domain) for name, ref in blueprint.inputs.items()}- if blueprint.output:- updates["output"] = _qualify_io_ref(blueprint.output, domain=owner_domain)-- def qualify(*, pipe_ref: str) -> str:- return _qualify_pipe_ref(pipe_ref, owner_domain=owner_domain, pipe_refs_by_code=pipe_refs_by_code)-- match blueprint:- case PipeSequenceBlueprint():- updates["steps"] = [step.model_copy(update={"pipe": qualify(pipe_ref=step.pipe)}) for step in blueprint.steps]- case PipeParallelBlueprint():- updates["branches"] = [branch.model_copy(update={"pipe": qualify(pipe_ref=branch.pipe)}) for branch in blueprint.branches]- case PipeConditionBlueprint():- if blueprint.outcomes:- updates["outcomes"] = {key: qualify(pipe_ref=pipe_ref) for key, pipe_ref in blueprint.outcomes.items()}- if blueprint.default_outcome:- updates["default_outcome"] = qualify(pipe_ref=blueprint.default_outcome)- case PipeBatchBlueprint():- if blueprint.branch_pipe_code:- updates["branch_pipe_code"] = qualify(pipe_ref=blueprint.branch_pipe_code)- case _:- pass-- return blueprint.model_copy(update=updates)---def _qualify_io_ref(io_ref: str, *, domain: str) -> str:- if QualifiedRef.has_cross_package_prefix(io_ref):- return io_ref # cross-package deferred- parsed = parse_concept_with_multiplicity(io_ref)- qualified = _qualify_concept_ref(parsed.concept_ref_or_code, domain=domain)- return _render_ref_with_markers(qualified, parsed=parsed)---def _render_ref_with_markers(concept_ref: str, *, parsed: MultiplicityParseResult) -> str:- if parsed.multiplicity is True:- suffix = "[]"- elif isinstance(parsed.multiplicity, int):- suffix = f"[{parsed.multiplicity}]"- else:- suffix = ""- return f"{concept_ref}{suffix}{parsed.presence.symbol}"---def _qualify_pipe_ref(pipe_ref: str, *, owner_domain: str, pipe_refs_by_code: dict[str, list[str]]) -> str:- """Qualify one in-body pipe ref against the crate, the way the live library resolves it.-- A bare code is **not** the owner domain's by assumption: `PipeLibrary.get_optional_pipe` resolves- it by searching every domain, so a pipe legitimately calls a sibling domain's pipe by bare code.- Prefixing the owner domain here would name a pipe absent from `crate.pipes` — a crate that- fingerprints the wrong content and dies with `PipeNotFoundError` on round-trip, with nothing- raised on the way in. The crate-wide search is the same lookup, so the two readers agree; on- ambiguity the library raises and so does this, rather than silently picking a winner.- """- if QualifiedRef.has_cross_package_prefix(pipe_ref):- return pipe_ref # cross-package deferred- if pipe_ref in SpecialOutcome.value_list():- return pipe_ref- if "." in pipe_ref:- return pipe_ref-- matches = pipe_refs_by_code.get(pipe_ref, [])- if len(matches) == 1:- return matches[0]- if not matches:- msg = f"Pipe ref '{pipe_ref}' (in domain '{owner_domain}') resolves to no pipe in the crate."- raise CrateNormalizationError(msg)- msg = f"Ambiguous pipe ref '{pipe_ref}' (in domain '{owner_domain}') matches {sorted(matches)} in the crate. Use a domain-qualified ref."- raise CrateNormalizationError(msg)--# --------------------------------------------------------------------------------------------------# Native expansion# --------------------------------------------------------------------------------------------------diff --git a/pipelex/libraries/crate_qualification.py b/pipelex/libraries/crate_qualification.pynew file mode 100644index 000000000..ab65f9c4e--- /dev/null+++ b/pipelex/libraries/crate_qualification.py@@ -0,0 +1,216 @@+"""Qualification pass: in-body references -> fully-qualified refs, over a library crate.++Given a merged, key-qualified crate (keys are `domain.Code` / `domain.code`, as produced by+`LibraryCrateFactory.make_from_blueprints`), this pass rewrites every *in-body* reference into the+form the rest of the system can resolve by key:++- concept `refines` and structure-field `concept_ref` / `item_concept_ref`;+- pipe `inputs` / `output` concept refs, preserving multiplicity and presence markers;+- pipe-step / branch / outcome / batch pipe refs.++**A bare ref names its own domain.** Both halves follow the same rule — a bare pipe code resolves to+the domain of the pipe that wrote it, exactly as a bare concept code does. Nothing is searched for+across the crate. An in-body reference that can silently land in a domain the author never named is+a reference no `[exports]` rule can constrain, and a visibility rule the resolver reaches around is+not a visibility rule.++**Existence is deliberately not checked here.** The pass runs once per load batch, and a batch may+legitimately reference a pipe that a *prior* batch loaded into the same domain — a `-L` library+directory, a secondary load. Only ordinary dependency validation sees the whole live library, so+that is where a genuinely missing ref is reported, with the qualified ref it tried.++Two kinds of ref are deliberately left alone: cross-package (`alias->…`) refs, whose canonical form+is the packaging project's design work, and `SpecialOutcome` values (`fail` / `continue`), which are+condition outcomes rather than pipe refs.++The pass is idempotent: an already-qualified ref is returned unchanged, so running it twice over the+same crate is the same as running it once. It does not mutate the crate it is given.++**It returns only what it computed** — the rewritten `concepts` and `pipes`, not a `LibraryCrate`.+Handing back a crate would force the pass to supply a `fingerprint` it has no way to get right: a+crate does not record which digest scheme produced its value (`compute_fingerprint_from_content` for+a merged crate, `compute_normalized_fingerprint` for a normalized one), so the pass would either+guess or carry over a digest that no longer describes its own content. Returning the two mappings+makes that contradiction unrepresentable and costs the callers nothing — both of them already own a+crate to read the envelope from, and `normalize_crate` builds a fresh one anyway.+"""++from typing import NamedTuple++from pipelex.core.concepts.concept_blueprint import ConceptBlueprint, ConceptStructureBlueprintType+from pipelex.core.concepts.concept_factory import ConceptFactory+from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint+from pipelex.core.pipes.variable_multiplicity import MultiplicityParseResult, parse_concept_with_multiplicity+from pipelex.core.qualified_ref import QualifiedRef+from pipelex.libraries.exceptions import CrateNormalizationError+from pipelex.libraries.library_crate import LibraryCrate+from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipeBlueprintUnion+from pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint+from pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprint+from pipelex.pipe_controllers.condition.special_outcome import SpecialOutcome+from pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprint+from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint++_ConceptEntry = ConceptBlueprint | str+++class QualifiedCrateContent(NamedTuple):+ """A crate's `concepts` and `pipes` with every in-body reference qualified."""++ concepts: dict[str, _ConceptEntry]+ pipes: dict[str, PipeBlueprintUnion]+++def qualify_crate(crate: LibraryCrate) -> QualifiedCrateContent:+ """Qualify every in-body reference of a merged, key-qualified crate.++ Raises:+ CrateNormalizationError: A crate key is not domain-qualified — the pass was handed something+ that is not a merged, key-qualified crate.+ """+ concepts: dict[str, _ConceptEntry] = {+ concept_ref: _qualify_concept_entry(value, owner_domain=_domain_of(concept_ref)) for concept_ref, value in crate.concepts.items()+ }++ pipes: dict[str, PipeBlueprintUnion] = {+ pipe_ref: _qualify_pipe_blueprint(blueprint, owner_domain=_domain_of(pipe_ref)) for pipe_ref, blueprint in crate.pipes.items()+ }++ return QualifiedCrateContent(concepts=concepts, pipes=pipes)+++def _domain_of(qualified_ref: str) -> str:+ domain_path = QualifiedRef.parse(qualified_ref).domain_path+ if domain_path is None:+ # Both the normalizer and the library build call this pass, so the message names the pass+ # rather than either caller.+ msg = f"Crate key '{qualified_ref}' is not domain-qualified; this pass expects a merged, key-qualified crate."+ raise CrateNormalizationError(msg)+ return domain_path+++# --------------------------------------------------------------------------------------------------+# Concepts+# --------------------------------------------------------------------------------------------------+++def _qualify_concept_entry(value: _ConceptEntry, *, owner_domain: str) -> _ConceptEntry:+ # A string-described concept is a description, so it holds no references to qualify.+ if isinstance(value, str):+ return value++ updates: dict[str, object] = {}+ if value.refines:+ updates["refines"] = ConceptFactory.make_refine(value.refines, domain_code=owner_domain)+ if isinstance(value.structure, dict):+ qualified_structure: dict[str, ConceptStructureBlueprintType] = {}+ for field_name, field in value.structure.items():+ # A string field is a shorthand description, materialized into an explicit text field by+ # the normalizer; it carries no concept ref either way.+ if isinstance(field, ConceptStructureBlueprint):+ qualified_structure[field_name] = _qualify_structure_field(field, domain=owner_domain)+ else:+ qualified_structure[field_name] = field+ updates["structure"] = qualified_structure+ return value.model_copy(update=updates) if updates else value+++def _qualify_structure_field(field_blueprint: ConceptStructureBlueprint, *, domain: str) -> ConceptStructureBlueprint:+ field_updates: dict[str, object] = {}+ if field_blueprint.concept_ref:+ field_updates["concept_ref"] = _qualify_concept_ref(field_blueprint.concept_ref, domain=domain)+ if field_blueprint.item_concept_ref:+ field_updates["item_concept_ref"] = _qualify_concept_ref(field_blueprint.item_concept_ref, domain=domain)+ return field_blueprint.model_copy(update=field_updates) if field_updates else field_blueprint+++def _qualify_concept_ref(concept_ref_or_code: str, *, domain: str) -> str:+ # make_concept_ref_with_domain_from_concept_ref_or_code resolves natives to `native.<Code>`,+ # bare refs to `domain.<Code>`, and preserves cross-package `alias->domain.Code` as-is (deferred).+ return ConceptFactory.make_concept_ref_with_domain_from_concept_ref_or_code(domain_code=domain, concept_ref_or_code=concept_ref_or_code)+++# --------------------------------------------------------------------------------------------------+# Pipes+# --------------------------------------------------------------------------------------------------+++def _qualify_pipe_blueprint(blueprint: PipeBlueprintUnion, *, owner_domain: str) -> PipeBlueprintUnion:+ updates: dict[str, object] = {}+ if blueprint.inputs:+ updates["inputs"] = {name: _qualify_io_ref(ref, domain=owner_domain) for name, ref in blueprint.inputs.items()}+ if blueprint.output:+ updates["output"] = _qualify_io_ref(blueprint.output, domain=owner_domain)++ def qualify(*, pipe_ref: str) -> str:+ return _qualify_pipe_ref(pipe_ref, owner_domain=owner_domain)++ def qualify_outcome(*, outcome: str) -> str:+ """A condition outcome may be a `SpecialOutcome` instead of a pipe ref.++ The exemption belongs *here* and nowhere else. `fail` and `continue` are legal snake_case pipe+ codes, so a sequence step, a parallel branch or a batch target may genuinely name a pipe+ called `continue` — exempting those too would leave a real ref unqualified, and under the+ strict lookup it would then resolve to nothing.+ """+ if outcome in SpecialOutcome.value_list():+ return outcome+ return _qualify_pipe_ref(outcome, owner_domain=owner_domain)++ match blueprint:+ case PipeSequenceBlueprint():+ updates["steps"] = [step.model_copy(update={"pipe": qualify(pipe_ref=step.pipe)}) for step in blueprint.steps]+ case PipeParallelBlueprint():+ updates["branches"] = [branch.model_copy(update={"pipe": qualify(pipe_ref=branch.pipe)}) for branch in blueprint.branches]+ case PipeConditionBlueprint():+ if blueprint.outcomes:+ updates["outcomes"] = {key: qualify_outcome(outcome=outcome) for key, outcome in blueprint.outcomes.items()}+ if blueprint.default_outcome:+ updates["default_outcome"] = qualify_outcome(outcome=blueprint.default_outcome)+ case PipeBatchBlueprint():+ if blueprint.branch_pipe_code:+ updates["branch_pipe_code"] = qualify(pipe_ref=blueprint.branch_pipe_code)+ case _:+ # Every controller kind that embeds a pipe ref is named above; operators embed none, so+ # they fall through with only their inputs/output rewritten. A NEW controller kind lands+ # here silently — `test_normalized_crate_is_closed_over_its_pipe_refs` is what catches it,+ # by walking `pipe_dependencies` rather than the kinds this match enumerates.+ pass++ return blueprint.model_copy(update=updates)+++def _qualify_io_ref(io_ref: str, *, domain: str) -> str:+ if QualifiedRef.has_cross_package_prefix(io_ref):+ return io_ref # cross-package deferred+ parsed = parse_concept_with_multiplicity(io_ref)+ qualified = _qualify_concept_ref(parsed.concept_ref_or_code, domain=domain)+ return _render_ref_with_markers(qualified, parsed=parsed)+++def _render_ref_with_markers(concept_ref: str, *, parsed: MultiplicityParseResult) -> str:+ if parsed.multiplicity is True:+ suffix = "[]"+ elif isinstance(parsed.multiplicity, int):+ suffix = f"[{parsed.multiplicity}]"+ else:+ suffix = ""+ return f"{concept_ref}{suffix}{parsed.presence.symbol}"+++def _qualify_pipe_ref(pipe_ref: str, *, owner_domain: str) -> str:+ """Qualify one in-body pipe ref to the domain of the pipe that wrote it.++ The exact twin of `_qualify_concept_ref`, and unconditional: a bare code is the owner domain's,+ whether or not the owner domain declares it. Nothing is searched for, so nothing can be found+ somewhere the author did not name — which is what makes `[exports]` mean something.++ A ref that names nothing is not this function's problem. It cannot be: the pass sees one load+ batch, and a batch may reference a pipe a prior batch put in the same domain. Dependency+ validation sees the whole live library and reports the miss there, naming the qualified ref.+ """+ if QualifiedRef.has_cross_package_prefix(pipe_ref):+ return pipe_ref # cross-package deferred+ if "." in pipe_ref:+ return pipe_ref+ return f"{owner_domain}.{pipe_ref}"diff --git a/pipelex/libraries/library.py b/pipelex/libraries/library.pyindex 6be577b6b..4c0a7d530 100644--- a/pipelex/libraries/library.py+++ b/pipelex/libraries/library.py@@ -1,3 +1,4 @@+from collections import defaultdictfrom pathlib import Pathfrom typing import TYPE_CHECKING@@ -8,12 +9,12 @@ from pipelex import logfrom pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.core.exceptions import PipesAndConceptValidationErrorDatafrom pipelex.core.pipes.exceptions import PipeValidationErrorType-from pipelex.core.qualified_ref import QualifiedRef+from pipelex.core.qualified_ref import QualifiedRef, QualifiedRefErrorfrom pipelex.libraries.concept.concept_library import ConceptLibraryfrom pipelex.libraries.concept.exceptions import ConceptLibraryErrorfrom pipelex.libraries.domain.domain_library import DomainLibraryfrom pipelex.libraries.exceptions import LibraryError, LibraryLoadingError-from pipelex.libraries.pipe.exceptions import PipeLibraryError+from pipelex.libraries.pipe.exceptions import PipeLibraryError, PipeNotFoundErrorfrom pipelex.libraries.pipe.pipe_library import PipeLibraryfrom pipelex.pipe_controllers.pipe_controller import PipeControllerfrom pipelex.tools.typing.pydantic_utils import empty_list_factory_of@@ -22,6 +23,64 @@ if TYPE_CHECKING:from pipelex.core.concepts.concept import Concept+def _describe_unresolved_pipe_dependency(+ *,+ referring_pipe_ref: str,+ missing_ref: str,+ candidates: dict[str, list[str]],+ cause: PipeLibraryError,+) -> str:+ """Explain an unresolved in-body pipe reference to the person who wrote it.++ The hard part is that the ref named here is not the ref they typed. They wrote a bare code; the+ compiler qualified it to their own domain. Without saying so, the message names a pipe that+ appears nowhere in their file and reads like a compiler bug.++ `candidates` comes from the failure-path-only scan in `_index_pipe_refs_by_bare_code`. A hit is a+ suggestion to a human, never a resolution — reaching a pipe in a domain nobody named is the+ behaviour this rule removed.+ """+ # Not every lookup failure is a miss. An ambiguous cross-package code raises here too, and for it+ # "does not exist" is false and the qualification story below never happened — so hand back the+ # real reason rather than a well-written wrong one.+ if not isinstance(cause, PipeNotFoundError):+ return f"Pipe '{referring_pipe_ref}' could not resolve its dependency '{missing_ref}': {cause}"++ lines = [f"Pipe '{referring_pipe_ref}' references '{missing_ref}', which does not exist."]++ # Everything below explains a rewrite, so it must only run on refs that could actually have been+ # rewritten. Three ways a ref reaches here without that being true:+ # - a cross-package `alias->…` ref, which the pass leaves untouched;+ # - a ref the author qualified themselves to ANOTHER domain — telling them their bare code was+ # read as `beta.foo` when they typed `beta.foo` is a fiction, and the candidate scan holds+ # host pipes that are the wrong thing to suggest for it;+ # - a malformed ref, which does not parse at all. Parsing it to build a nicer message would+ # replace a categorized validation error with a raw QualifiedRefError, turning bad user input+ # into a crash on the way to reporting bad user input.+ if QualifiedRef.has_cross_package_prefix(missing_ref):+ return " ".join(lines)+ try:+ parsed = QualifiedRef.parse(missing_ref)+ except QualifiedRefError:+ return " ".join(lines)++ referring_domain = QualifiedRef.parse(referring_pipe_ref).domain_path+ if parsed.domain_path is not None and parsed.domain_path == referring_domain:+ # After qualification a bare ref and an explicitly-written same-domain ref are+ # indistinguishable, so the wording must not claim which one the author typed.+ local_code = parsed.local_code+ lines.append(+ f"A pipe reference resolves inside its own domain, so '{local_code}' is looked for in domain '{referring_domain}'. "+ "Referencing a pipe in another domain requires writing that domain out."+ )+ elsewhere = sorted(ref for ref in candidates.get(local_code, []) if ref != missing_ref)+ if elsewhere:+ suggestion = "' or '".join(elsewhere)+ lines.append(f"'{local_code}' is declared elsewhere in this library — did you mean '{suggestion}'?")++ return " ".join(lines)++class Library(BaseModel):"""A Library bundles together domain, concept, and pipe libraries for a specific context.@@ -103,6 +162,15 @@ class Library(BaseModel):self.validate_pipe_library_with_libraries()def validate_pipe_library_with_libraries(self) -> None:+ # Diagnostic index of bare code -> qualified refs, built at most once per validation run and+ # ONLY once something has already failed to resolve. This is the same crate-wide scan that was+ # deleted from `PipeLibrary.get_optional_pipe`; it lives on the FAILURE PATH ONLY and must stay+ # there. It suggests a spelling to a human — it never resolves a reference. Wiring it into a+ # lookup would restore the cross-domain fall-through and make `[exports]` unenforceable again.+ # Built once because the run this matters on is the mass-breakage one right after an upgrade,+ # where per-error scanning would go quadratic.+ bare_code_candidates: dict[str, list[str]] | None = None+for pipe_key, pipe in self.pipe_library.root.items():# Determine if this pipe comes from a dependency (aliased key like "alias->pipe_code")dep_alias: str | None = None@@ -138,7 +206,14 @@ class Library(BaseModel):try:self.pipe_library.get_required_pipe(pipe_code=sub_pipe_code)except PipeLibraryError as pipe_error:- msg = f"Error validating pipe '{pipe.code}' dependency pipe '{sub_pipe_code}' because of: {pipe_error}"+ if bare_code_candidates is None:+ bare_code_candidates = self._index_pipe_refs_by_bare_code()+ msg = _describe_unresolved_pipe_dependency(+ referring_pipe_ref=pipe.pipe_ref,+ missing_ref=sub_pipe_code,+ candidates=bare_code_candidates,+ cause=pipe_error,+ )# Carry a structured item so an unresolved dependency surfaces as a categorized# `pipe_validation` item: `pipe_code` is the referencing controller and# `missing_pipe_code` is the dependency that does not resolve, so a machine@@ -160,6 +235,19 @@ class Library(BaseModel):continuepipe.validate_with_libraries()+ def _index_pipe_refs_by_bare_code(self) -> dict[str, list[str]]:+ """Group every pipe ref in this library by its bare code, for failure-path diagnostics only.++ Aliased dependency entries are excluded: suggesting a pipe that only exists because some+ unrelated package happens to be installed is worse than suggesting nothing.+ """+ by_code: dict[str, list[str]] = defaultdict(list)+ for pipe_ref in self.pipe_library.root:+ if QualifiedRef.has_cross_package_prefix(pipe_ref):+ continue+ by_code[QualifiedRef.parse(pipe_ref).local_code].append(pipe_ref)+ return by_code+def _has_unresolved_cross_package_deps(self, pipe: PipeController) -> bool:"""Check if a pipe controller has cross-package dependencies that aren't loaded.diff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.pyindex f27d0efa8..698192c84 100644--- a/pipelex/libraries/library_manager.py+++ b/pipelex/libraries/library_manager.py@@ -28,6 +28,7 @@ from pipelex.interpreter_hub import get_current_library, get_current_library_id_from pipelex.libraries.collision_messages import duplicate_ref_msgfrom pipelex.libraries.concept.exceptions import ConceptLibraryErrorfrom pipelex.libraries.concept_reference_validation import validate_concept_references_in_blueprints+from pipelex.libraries.crate_qualification import qualify_cratefrom pipelex.libraries.exceptions import (LibraryError,LibraryLoadingError,@@ -446,13 +447,11 @@ class LibraryManager(LibraryManagerAbstract):# Detect cycles in concept references (A -> B -> A is forbidden)self._detect_concept_cycles(all_concepts)- # Precompute domain -> concept local codes mapping (avoids O(N*M) re-parsing per pipe).- # Sourced from the LIVE library (native concepts + concepts from prior load batches + this- # batch's concepts, already added above), not just this crate — so a pipe can reference, by- # bare code, a same-domain concept that a prior batch (e.g. a -L library directory) loaded.- # This is the pipe-factory counterpart to the loader's cross-batch concept-reference check:- # without it, that check would pass a bare cross-batch ref only for the factory to reject- # it. Cross-package aliased entries ('alias->...') are skipped — they resolve through the+ # Precompute domain -> concept local codes mapping. VESTIGIAL on this path — see the note+ # on the qualification pass below: every io ref reaching PipeFactory is dotted, and the+ # factory only consults this parameter for dot-free refs. Kept until the PipeFactory+ # signature change that removes it (deferred with the concept-side work).+ # Cross-package aliased entries ('alias->...') are skipped — they resolve through the# dependency resolver, not by bare code, and would not parse as a concept ref.domain_concept_codes: dict[str, list[str]] = {}for concept_ref in library.concept_library.root:@@ -462,9 +461,21 @@ class LibraryManager(LibraryManagerAbstract):if parsed_concept.domain_path is not None:domain_concept_codes.setdefault(parsed_concept.domain_path, []).append(parsed_concept.local_code)+ # Qualify in-body refs before constructing pipes, so a built pipe's sub-pipe refs are the+ # same qualified refs the normalizer would produce — one rule, stated once, read by both.+ #+ # Note what this does to `concept_codes_from_the_same_domain` below: the pass also rewrites+ # each pipe's inputs/output into `domain.Code` form, and PipeFactory only runs its+ # declared-in-this-domain check for refs with NO dot — so on this path that parameter is+ # now never consulted. Nothing is lost: an undeclared same-domain concept is still caught,+ # earlier, by `validate_concept_references_in_blueprints`, which runs on the blueprints+ # before this. The parameter is vestigial here rather than load-bearing; removing it is a+ # signature change across PipeFactory and belongs with the concept-side work.+ qualified_pipes = qualify_crate(crate).pipes+# Load pipes with domain-filtered concept codesall_pipes: list[PipeAbstract] = []- for pipe_ref, pipe_blueprint in crate.pipes.items():+ for pipe_ref, pipe_blueprint in qualified_pipes.items():parsed = QualifiedRef.parse_pipe_ref(raw=pipe_ref)if parsed.domain_path is None:msg = f"Crate pipe_ref '{pipe_ref}' must be domain-qualified"@@ -1032,8 +1043,10 @@ class LibraryManager(LibraryManagerAbstract):library.concept_library.add_new_concept(concept=concept)temp_concept_refs.append(concept.concept_ref)- # Per-domain concept codes let a pipe resolve a same-domain concept by bare code, mirroring- # load_from_crate. A multi-file dependency may span several domains.+ # Per-domain concept codes, mirroring load_from_crate — and VESTIGIAL for the same reason:+ # the qualification pass below rewrites every io ref to dotted form, and PipeFactory only+ # consults this parameter for dot-free refs. Kept until the deferred PipeFactory signature+ # change removes it on both paths together.domain_concept_codes: dict[str, list[str]] = {}for concept in dep_concepts:parsed_concept = QualifiedRef.parse_concept_ref(raw=concept.concept_ref)@@ -1043,7 +1056,12 @@ class LibraryManager(LibraryManagerAbstract):# Load exported pipes (reconciled by the crate) into child library, ensuring temp concepts# are always cleaned up even if an unexpected exception occurstry:- for pipe_ref, pipe_blueprint in crate.pipes.items():+ # Same qualification the main load path applies: a dependency package's own in-body refs+ # are its own domain's, and its child library is keyed by qualified pipe_ref. Inside the+ # try: qualification can raise on malformed refs, and the temp concepts must still be+ # removed from the main library.+ qualified_dep_pipes = qualify_crate(crate).pipes+ for pipe_ref, pipe_blueprint in qualified_dep_pipes.items():parsed_pipe = QualifiedRef.parse_pipe_ref(raw=pipe_ref)if parsed_pipe.domain_path is None:msg = f"Crate pipe_ref '{pipe_ref}' must be domain-qualified"diff --git a/pipelex/libraries/pipe/pipe_library.py b/pipelex/libraries/pipe/pipe_library.pyindex 9a7e31ba6..a0028f58b 100644--- a/pipelex/libraries/pipe/pipe_library.py+++ b/pipelex/libraries/pipe/pipe_library.py@@ -54,12 +54,27 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):@overridedef get_optional_pipe(self, pipe_code: str) -> PipeAbstract | None:+ """Resolve an **in-body** pipe reference: a ref names its own domain, or it names nothing.++ In-body refs arrive here already qualified — `crate_qualification.qualify_crate` runs on+ every crate-to-pipes path before pipes are built — so this is a key lookup. There is+ deliberately no bare-code search across domains: a reference that can find a pipe in a+ domain its author never named is a reference `[exports]` cannot constrain, and a visibility+ rule the resolver reaches around is not a visibility rule.++ A code a *human* typed is a different question and gets a different answer — see+ `get_optional_entry_pipe`.+ """# 1. Direct lookup — handles pipe_ref keys (domain.code) and cross-package keys (alias->domain.code)pipe = self.root.get(pipe_code)if pipe is not None:return pipe- # 2. Cross-package refs+ # 2. Cross-package refs. The bare-remainder search below survives the strictness change on+ # purpose (OQ3): the qualification pass leaves `alias->…` refs alone — it cannot know the+ # dependency's domain layout — so removing it would break every `alias->bare_code` ref with+ # no canonical spelling to migrate to. It is alias-scoped, so it cannot reach a host pipe;+ # revisit when the packaging design rules on cross-package reference forms.if QualifiedRef.has_cross_package_prefix(pipe_code):alias, remainder = QualifiedRef.split_cross_package_ref(pipe_code)# Try domain-qualified remainder as direct key@@ -78,22 +93,54 @@ class PipeLibrary(RootModel[PipeLibraryRoot], PipeLibraryAbstract):raise PipeLibraryError(msg)return None- # 3. Bare code fallback — search across domains (excluding cross-package entries)- # TODO: add domain_hint parameter so controllers can prefer their own domain when bare code is ambiguous.- # Currently, controllers resolve sub-pipes by bare code; if two domains share a pipe code the lookup- # raises PipeLibraryError instead of preferring the caller's domain. See PR #779 review.- if "." not in pipe_code:- matches = [val for key, val in self.root.items() if not QualifiedRef.has_cross_package_prefix(key) and val.code == pipe_code]- if len(matches) == 1:- return matches[0]- if len(matches) > 1:- domains = [match.domain_code for match in matches]- msg = f"Ambiguous pipe code '{pipe_code}' found in domains: {domains}. Use domain-qualified ref."- raise PipeLibraryError(msg)+ return None++ @override+ def get_optional_entry_pipe(self, pipe_code: str) -> PipeAbstract | None:+ """Resolve a pipe code a **human** supplied — a CLI argument, an API request field.++ This is an entry-shaped lookup, not in-body reference resolution, and the two differ on+ purpose. `pipelex run summarize` should keep working without making the user recite a domain+ they can see in their own file, so a bare code here is matched across every domain the+ library holds. An ambiguous bare code raises rather than picking a winner.++ It deliberately does **not** consult `[exports]`. Package visibility governs what one method+ may reference from inside another; a pipe someone names by hand at an entry point is not an+ in-body reference, so the rule does not apply to it.++ Aliased dependency entries are excluded from the search. Without that, installing an+ unrelated package could make a host pipe's bare code ambiguous — reintroducing, through this+ door, exactly the contextual instability the strict in-body rule exists to remove.+ """+ pipe = self.get_optional_pipe(pipe_code=pipe_code)+ if pipe is not None:+ return pipe++ # Anything dotted or aliased was fully specified and simply did not resolve; only a bare code+ # is a request to search.+ if "." in pipe_code or QualifiedRef.has_cross_package_prefix(pipe_code):return None+ matches = [val for key, val in self.root.items() if not QualifiedRef.has_cross_package_prefix(key) and val.code == pipe_code]+ if len(matches) == 1:+ return matches[0]+ if len(matches) > 1:+ candidates = sorted(match.pipe_ref for match in matches)+ msg = f"Pipe code '{pipe_code}' is ambiguous — it is declared by {candidates}. Name one of them explicitly."+ raise PipeLibraryError(msg)return None+ @override+ def get_required_entry_pipe(self, pipe_code: str) -> PipeAbstract:+ the_pipe = self.get_optional_entry_pipe(pipe_code=pipe_code)+ if not the_pipe:+ msg = (+ f"Pipe '{pipe_code}' could not be resolved. Check for typos and make sure its bundle is loaded. "+ "A bare code only matches this library's own domains — a pipe from a dependency package must be named 'alias->pipe_code'."+ )+ raise PipeNotFoundError(msg)+ return the_pipe+def add_dependency_pipe(self, *, alias: str, pipe: PipeAbstract) -> None:"""Add a pipe from a dependency package with an aliased key.diff --git a/pipelex/libraries/pipe/pipe_library_abstract.py b/pipelex/libraries/pipe/pipe_library_abstract.pyindex 3a844eaba..5e24831c6 100644--- a/pipelex/libraries/pipe/pipe_library_abstract.py+++ b/pipelex/libraries/pipe/pipe_library_abstract.py@@ -12,11 +12,25 @@ class PipeLibraryAbstract(ABC):pipe graph — a condition's mapped pipes and a sequence's last step, both in`pipe_machinery/rendering/` — are interpreter-layer and call `interpreter_hub.get_required_pipe`directly. Split the read half out if and when a kernel-layer caller needs it.++ One caveat before the split: "strict" describes same-package refs. A cross-package+ `alias->bare_code` ref is still resolved by searching that alias's entries, because the+ qualification pass leaves `alias->…` refs untouched and there is no canonical spelling to point+ an author at yet. It is alias-scoped, so it cannot reach a host pipe.++ Two resolution surfaces live here and the split is the point. `get_optional_pipe` /+ `get_required_pipe` resolve an **in-body** reference — one pipe naming another from inside a+ method — and are strict: the ref names its own domain or it names nothing. `get_optional_entry_pipe`+ / `get_required_entry_pipe` resolve a code a **human** supplied at an entry point, where a bare+ code is still matched across domains because the user is not writing a reference, they are+ pointing at a pipe. Reaching for the in-body pair to serve a hand-typed code makes the CLI stricter+ than it should be; reaching for the entry pair from inside a controller reopens the cross-domain+ hole the strict rule closes."""@abstractmethoddef get_required_pipe(self, pipe_code: str) -> PipeAbstract:- """Resolve a pipe code, raising when it is not known."""+ """Resolve an in-body pipe reference, raising when it is not known."""@abstractmethoddef setup(self) -> None:@@ -33,7 +47,18 @@ class PipeLibraryAbstract(ABC):@abstractmethoddef get_optional_pipe(self, pipe_code: str) -> PipeAbstract | None:- pass+ """Resolve an in-body pipe reference, returning None when it is not known."""++ @abstractmethod+ def get_optional_entry_pipe(self, pipe_code: str) -> PipeAbstract | None:+ """Resolve a human-supplied pipe code, returning None when nothing matches.++ Matches a bare code across domains and raises on ambiguity; ignores `[exports]`.+ """++ @abstractmethod+ def get_required_entry_pipe(self, pipe_code: str) -> PipeAbstract:+ """Resolve a human-supplied pipe code, raising when nothing matches."""@abstractmethoddef get_pipes(self) -> list[PipeAbstract]:diff --git a/pipelex/pipe_controllers/sub_pipe.py b/pipelex/pipe_controllers/sub_pipe.pyindex c79feecfd..0505fbcc4 100644--- a/pipelex/pipe_controllers/sub_pipe.py+++ b/pipelex/pipe_controllers/sub_pipe.py@@ -161,7 +161,10 @@ class SubPipe(BaseModel):pipe_batch_blueprint = PipeBatchBlueprint(description=f"Batch processing for {self.pipe_code}",branch_pipe_code=self.pipe_code,- output=sub_pipe.output.concept.code,+ # The full concept_ref, not the bare code: the factory resolves a bare code in+ # `domain_code` below (the sub-pipe's own domain), so a sub-pipe whose output concept+ # lives in another domain would resolve to the wrong concept — or to nothing.+ output=sub_pipe.output.concept.concept_ref,input_list_name=batch_params.input_list_stuff_name,input_item_name=batch_params.input_item_stuff_name,inputs={@@ -169,7 +172,10 @@ class SubPipe(BaseModel):},)- pipe_batch_adhoc_pipe_code = f"{self.pipe_code}_batch"+ # Derived from the resolved pipe's LOCAL code, not from `self.pipe_code` — that is a+ # qualified ref (`domain.foo`), and suffixing it would name `domain.foo_batch` while+ # `domain_code` below adds the domain a second time.+ pipe_batch_adhoc_pipe_code = f"{sub_pipe.code}_batch"pipe_batch = PipeFactory[PipeBatch].make_from_blueprint(domain_code=sub_pipe.domain_code,pipe_code=pipe_batch_adhoc_pipe_code,diff --git a/pipelex/pipe_operators/func/pipe_func.py b/pipelex/pipe_operators/func/pipe_func.pyindex a907039c5..6fa15b4cb 100644--- a/pipelex/pipe_operators/func/pipe_func.py+++ b/pipelex/pipe_operators/func/pipe_func.py@@ -196,7 +196,9 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):try:execution_result = await get_pipe_func_executor().run_pipe_func(job_metadata=job_metadata,- pipe_code=self.code,+ # Qualified: the executor resolves this against the transported library, which is+ # keyed by pipe_ref. A bare code no longer resolves there.+ pipe_code=self.pipe_ref,function_name=self.function_name,working_memory=working_memory,pipe_run_params=pipe_run_params,diff --git a/pipelex/pipe_run/dry_run_in_process.py b/pipelex/pipe_run/dry_run_in_process.pyindex 4de720a69..ccd9a17a4 100644--- a/pipelex/pipe_run/dry_run_in_process.py+++ b/pipelex/pipe_run/dry_run_in_process.py@@ -57,7 +57,10 @@ async def best_effort_graph_spec(*, pipe_ref: str | None, library_id: str | Noneif not pipe_ref or not library_id:return Nonetry:- pipe = get_library_manager().get_library(library_id=library_id).pipe_library.get_required_pipe(pipe_code=pipe_ref)+ # Entry-shaped: `pipe_ref` is either a caller-supplied graph target (a protocol request+ # field) or a bundle's already-qualified main_pipe_ref. Both are pipes someone pointed at,+ # not in-body references, so a bare code must still resolve.+ pipe = get_library_manager().get_library(library_id=library_id).pipe_library.get_required_entry_pipe(pipe_code=pipe_ref)return await dry_run_pipe_in_process(pipe=pipe, library_id=library_id)except (PipelexError, FactoryException, ValueError) as graph_error:log.warning(diff --git a/pipelex/pipeline/execution_seams.py b/pipelex/pipeline/execution_seams.pyindex fd042fc0f..6151b2edf 100644--- a/pipelex/pipeline/execution_seams.py+++ b/pipelex/pipeline/execution_seams.py@@ -163,7 +163,7 @@ async def prepare_pipe_job(pipeline_run_id: str,user_id: str,inputs: PipelineInputs | WorkingMemory | None = None,- search_domain_codes: list[str] | None = None,+ search_scope: str | None = None,trace_context: "TraceContext | None" = None,otel_context: OtelContext | None = None,output_name: str | None = None,@@ -206,7 +206,7 @@ async def prepare_pipe_job(inputs=inputs,concept_provider=get_concept_library(),input_specs=pipe.inputs,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,inputs_base_dir=inputs_base_dir,)diff --git a/pipelex/pipeline/fixes/fix_loop.py b/pipelex/pipeline/fixes/fix_loop.pyindex 77c9283d3..e8cbe592b 100644--- a/pipelex/pipeline/fixes/fix_loop.py+++ b/pipelex/pipeline/fixes/fix_loop.py@@ -394,35 +394,47 @@ def _is_signature_pipe_section(pipe_section: Any) -> bool:return "type" not in typed_section and all(key in SIGNATURE_ONLY_KEYS for key in typed_section)-def _pipe_codes_by_file(*, entry_path: Path, effective_dirs: Sequence[Path]) -> dict[Path, set[str]]:- """Concrete pipe declaration keys of every loaded bundle file, keyed by resolved path.-- Cross-domain on purpose: a bare pipe code must resolve unambiguously across the loaded- library — ``PipeLibrary.get_optional_pipe`` raises on a bare code declared by two domains —- so a rename target colliding with a same-named declaration in ANY other loaded file would- leave the library unloadable. Signature-only headers are excluded: a matching concrete- definition is allowed to replace a ``PipeSignature`` during crate merge, so treating the- header as a hard collision would block a valid fix. Rebuilt each iteration: multiple files- can now mutate per round. A file that fails to parse contributes nothing here — its own- problems surface through validation, not this scan.+class _FilePipeCodes(NamedTuple):+ """One loaded bundle file's declared domain and its concrete pipe declaration keys."""++ domain: str | None+ codes: set[str]+++def _pipe_codes_by_file(*, entry_path: Path, effective_dirs: Sequence[Path]) -> dict[Path, _FilePipeCodes]:+ """Concrete pipe declaration keys (with the declaring domain) of every loaded bundle file.++ The domain is recorded because the collision scope is **per-domain**: in-body refs resolve+ within their own domain and the library keys pipes by ``domain.code``, so a same-named+ declaration in another domain is not a collision at all — only two files of the same domain+ writing the same bare code can create a state the loop cannot repair. A file whose ``domain``+ cannot be read keeps the conservative cross-domain behavior (``None`` collides with+ everything). Signature-only headers are excluded: a matching concrete definition is allowed+ to replace a ``PipeSignature`` during crate merge, so treating the header as a hard collision+ would block a valid fix. Rebuilt each iteration: multiple files can now mutate per round. A+ file that fails to parse contributes nothing here — its own problems surface through+ validation, not this scan."""all_paths: set[Path] = {entry_path}all_paths.update(mthds_path.resolve() for mthds_path in get_pipelex_mthds_files_from_dirs(dirs=set(effective_dirs)))- codes_by_file: dict[Path, set[str]] = {}+ codes_by_file: dict[Path, _FilePipeCodes] = {}for mthds_path in all_paths:try:toml_doc = load_toml_from_path(mthds_path)except TomlError:continue+ raw_domain = toml_doc.get("domain")+ file_domain = raw_domain if isinstance(raw_domain, str) else Nonepipe_section = toml_doc.get("pipe")if isinstance(pipe_section, dict):- codes_by_file[mthds_path] = {+ file_codes = {keyfor key, section in cast("dict[Any, Any]", pipe_section).items()if isinstance(key, str) and not _is_signature_pipe_section(section)}else:- codes_by_file[mthds_path] = set()+ file_codes = set[str]()+ codes_by_file[mthds_path] = _FilePipeCodes(domain=file_domain, codes=file_codes)return codes_by_file@@ -434,11 +446,12 @@ def _colliding_op_name() -> str | None:"""The pipe code this op would collide with across files, or ``None`` when it cannot.- Two op shapes can write a bare pipe code that another loaded file already declares:+ Two op shapes can write a bare pipe code that another loaded file of the same domain already+ declares (``other_file_pipe_codes`` is built domain-scoped by the caller — see+ ``_split_cross_file_collisions``):- a ``[pipe]`` ``rename_table_key`` whose ``new_key`` is declared elsewhere — applying it- would create a duplicate declaration (same domain) or a bare-code ambiguity (another- domain) that the loop can never repair;+ would create a duplicate declaration (same domain) that the loop can never repair;- a root ``main_pipe`` ``set_key`` whose value is declared elsewhere while the target filedoes NOT declare that value — its paired declaration rename is exactly the case above(dropped), so applying the ``set_key`` alone would write an orphaned ``main_pipe``@@ -468,28 +481,38 @@ def _colliding_op_name(def _split_cross_file_collisions(fixes: list[_BoundFix],*,- codes_by_file: dict[Path, set[str]],+ codes_by_file: dict[Path, _FilePipeCodes],) -> tuple[list[_BoundFix], list[str]]:"""Split ``fixes`` into (kept, colliding pipe codes of the dropped ones).The raise-site collision gate only sees the one file being validated; in a multi-file run a- bare pipe of the same name may live in another loaded file, where writing it (as a ``[pipe]``- key rename or a ``main_pipe`` value) would create a state the loop can never repair. Each- fix is checked against the pipe codes of every loaded file OTHER than its own target.- Dropped fixes simply leave their error unfixed (still reported in ``remaining_errors``).+ bare pipe of the same name may live in another loaded file **of the same domain**, where+ writing it (as a ``[pipe]`` key rename or a ``main_pipe`` value) would create a duplicate+ declaration the loop can never repair. Each fix is checked against the pipe codes of every+ loaded same-domain file OTHER than its own target — a same-named pipe in another domain is+ not a collision, since the library keys pipes by ``domain.code`` and in-body refs never+ search across domains. A file whose domain could not be read is checked against every file+ (conservative). Dropped fixes simply leave their error unfixed (still reported in+ ``remaining_errors``)."""kept: list[_BoundFix] = []colliding_names: list[str] = []other_codes_cache: dict[Path, set[str]] = {}for fix in fixes:target_path = fix.target_path- target_codes = codes_by_file.get(target_path, set())+ target_entry = codes_by_file.get(target_path)+ target_codes = target_entry.codes if target_entry else set[str]()+ target_domain = target_entry.domain if target_entry else Noneother_codes = other_codes_cache.get(target_path)if other_codes is None:other_codes = set[str]()- for file_path, file_codes in codes_by_file.items():- if file_path != target_path:- other_codes.update(file_codes)+ for file_path, file_entry in codes_by_file.items():+ if file_path == target_path:+ continue+ same_domain = file_entry.domain == target_domain+ domain_unknown = file_entry.domain is None or target_domain is None+ if same_domain or domain_unknown:+ other_codes.update(file_entry.codes)other_codes_cache[target_path] = other_codesfix_collisions = [name@@ -604,7 +627,10 @@ async def fix_bundle_file(in_scope_fixes, colliding_names = _split_cross_file_collisions(in_scope_fixes, codes_by_file=codes_by_file)if not in_scope_fixes:colliding = ", ".join(f"'{name}'" for name in sorted(set(colliding_names)))- bail_reason = f"cross-file collision: every remaining fix would write a pipe code ({colliding}) already declared in a sibling bundle"+ bail_reason = (+ f"cross-file collision: every remaining fix would write a pipe code ({colliding}) "+ "already declared in a same-domain sibling bundle (or a sibling whose domain could not be read)"+ )return FixBundleResult(is_valid=False,iterations=apply_rounds,diff --git a/pipelex/pipeline/pipeline_run_setup.py b/pipelex/pipeline/pipeline_run_setup.pyindex 0ae55b939..3d34705f7 100644--- a/pipelex/pipeline/pipeline_run_setup.py+++ b/pipelex/pipeline/pipeline_run_setup.py@@ -6,12 +6,14 @@ from mthds.protocol.pipeline_inputs import PipelineInputsfrom pipelex import logfrom pipelex.config import get_configfrom pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.qualified_ref import QualifiedReffrom pipelex.graph.graph_tracer_manager import GraphTracerManagerfrom pipelex.interpreter_hub import (clear_current_library,get_current_library_id_or_none,get_library_manager,get_pipeline_manager,+ get_required_entry_pipe,get_required_pipe,set_current_library,)@@ -52,7 +54,6 @@ async def pipeline_run_setup(dynamic_output_concept_ref: str | None = None,pipe_run_mode: PipeRunMode | None = None,is_mock_usage: bool = False,- search_domain_codes: list[str] | None = None,user_id: str | None = None,pipeline_run_id: str | None = None,request_id: str | None = None,@@ -113,9 +114,6 @@ async def pipeline_run_setup(the cheap, deterministic cross-worker cost-report validation affordance. Threaded onto:attr:`CogtRunParams.is_mock_usage`, which rides every assignment to the leaf in bothdirect and Temporal modes. Requires a DRY run; setting it on a LIVE run fails validation.- search_domain_codes:- List of domain codes to search for pipes. The executed pipe's domain is automatically- added if not already present.user_id:Unique identifier for the user (optional).pipeline_run_id:@@ -179,11 +177,17 @@ async def pipeline_run_setup()library_acquired = True- # Resolve the pipe to execute against the now-open library.+ # Resolve the pipe to execute against the now-open library. A caller-supplied `pipe_code` is+ # entry-shaped — it comes from a CLI argument or an API request field, not from inside a+ # method — so a bare code still resolves across domains. `qualified_main_pipe` is already+ # domain-qualified and goes through the strict lookup.+ # Captured now because `pipe_code` is rebound to the resolved pipe's own code below, and+ # only the raw form carries a dependency alias prefix (`alias->…`).+ raw_entry_ref: str | None = pipe_codepipe: PipeAbstractif mthds_contents:if pipe_code:- pipe = get_required_pipe(pipe_code=pipe_code)+ pipe = get_required_entry_pipe(pipe_code=pipe_code)elif qualified_main_pipe:# main_pipe is validated as snake_case (no dots), so acquire_library returns it already# domain-qualified. See PipelexBundleBlueprint.validate_main_pipe_syntax.@@ -192,16 +196,20 @@ async def pipeline_run_setup(msg = "No pipe_code provided and no main_pipe found in any of the MTHDS contents."raise PipeExecutionError(message=msg)elif pipe_code:- pipe = get_required_pipe(pipe_code=pipe_code)+ pipe = get_required_entry_pipe(pipe_code=pipe_code)else:msg = "Either provide pipe_code or mthds_contents to the pipeline API."raise PipeExecutionError(message=msg)- pipe_code = pipe.code+ # The entry pipe's own scope, preferred when input shaping resolves a bare concept code.+ # When the caller invoked a dependency pipe (`alias->…`), the scope carries the package+ # alias too, so the dependency's own concepts — keyed under the alias — stay reachable.+ search_scope: str = pipe.domain_code+ if raw_entry_ref and QualifiedRef.has_cross_package_prefix(raw_entry_ref):+ entry_alias, _ = QualifiedRef.split_cross_package_ref(raw_entry_ref)+ search_scope = f"{entry_alias}->{pipe.domain_code}"- search_domain_codes = search_domain_codes or []- if pipe.domain_code not in search_domain_codes:- search_domain_codes.insert(0, pipe.domain_code)+ pipe_code = pipe.code# Initialize the tracing context if graph OR cost reporting is requested (after pipe is loaded so we# have domain info). The two concerns share one event-log transport and one in-memory tracer; the@@ -276,7 +284,7 @@ async def pipeline_run_setup(pipeline_run_id=pipeline_run_id,user_id=user_id,inputs=inputs,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,trace_context=trace_context,otel_context=otel_context,output_name=output_name,diff --git a/pipelex/pipeline/runner.py b/pipelex/pipeline/runner.pyindex 1550bdda1..b5d85721d 100644--- a/pipelex/pipeline/runner.py+++ b/pipelex/pipeline/runner.py@@ -112,7 +112,6 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):bundle_uris: list[str] | None = None,pipe_run_mode: PipeRunMode | None = None,is_mock_usage: bool = False,- search_domain_codes: list[str] | None = None,user_id: str | None = None,execution_config: PipelineExecutionConfig | None = None,pipe_run: PipeRunProtocol | None = None,@@ -123,7 +122,6 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):self.bundle_uris = bundle_urisself.pipe_run_mode = pipe_run_modeself.is_mock_usage = is_mock_usage- self.search_domain_codes = search_domain_codesself.user_id = user_idself.execution_config = execution_configself._pipe_run = pipe_run@@ -223,7 +221,6 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):dynamic_output_concept_ref=dynamic_output_concept_ref,pipe_run_mode=self.pipe_run_mode,is_mock_usage=self.is_mock_usage,- search_domain_codes=self.search_domain_codes,user_id=self.user_id,inputs_base_dir=self.inputs_base_dir,)diff --git a/pipelex/pipeline/validate_bundle.py b/pipelex/pipeline/validate_bundle.pyindex 5ac8445d2..21a8799ab 100644--- a/pipelex/pipeline/validate_bundle.py+++ b/pipelex/pipeline/validate_bundle.py@@ -100,8 +100,8 @@ def _backfill_pipe_error_source(pipe_error: PipeValidationError) -> None:runs. Intercepting once at this catch boundary covers every raise site, present and future.Lookup is by the full ``domain.pipe_code`` ref only — never the bare-code suffix fallback- (bare codes are ambiguous across domains, exactly what the fix loop's cross-file guard- defends against). A miss leaves ``file_path`` as ``None``: the fix stays source-less and+ (under the strict own-domain resolution rule, a bare-code suffix match would guess a file+ where the qualified ref did not resolve). A miss leaves ``file_path`` as ``None``: the fix stays source-less andfalls under the conservative single-file rule, which is the safe direction."""if pipe_error.file_path is not None:@@ -322,9 +322,11 @@ async def validate_bundle(# File not yet loaded - load it from the blueprintloaded_pipes = library_manager.load_from_blueprints(library_id=library_id, blueprints=[blueprint])else:- # File already loaded - get existing pipes from library by their codes+ # File already loaded - get existing pipes from library by their refs. A bundle's+ # `[pipe.<code>]` keys are bare and belong to the bundle's own domain, so they are+ # qualified here rather than searched for: the library is keyed by qualified ref.pipe_codes = list(blueprint.pipe.keys()) if blueprint.pipe else []- loaded_pipes = [library.pipe_library.get_required_pipe(pipe_code=code) for code in pipe_codes]+ loaded_pipes = [library.pipe_library.get_required_pipe(pipe_code=f"{blueprint.domain}.{code}") for code in pipe_codes]dry_run_results = await BundleValidator().validate_pipes(pipes=_pipes_to_dry_run(loaded_pipes, dry_run_pipe_codes=dry_run_pipe_codes),diff --git a/subject_grants.toml b/subject_grants.tomlindex 181acbb02..65172f3e6 100644--- a/subject_grants.toml+++ b/subject_grants.toml@@ -2420,9 +2420,9 @@ rationale = "Resolver getter: the native concept being fetched; single operand."param = "concept_ref"rationale = "Resolver getter keyed by the concept ref; single operand."-["pipelex/core/concepts/concept_provider_abstract.py::ConceptProviderAbstract.get_required_concept_from_concept_ref_or_code"]+["pipelex/core/concepts/concept_provider_abstract.py::ConceptProviderAbstract.get_required_entry_concept"]param = "concept_ref_or_code"-rationale = "Resolver getter keyed by the ref-or-code; single operand."+rationale = "Entry affordance keyed by the human-supplied concept string; single operand, the concept twin of get_required_entry_pipe."["pipelex/core/concepts/concept_representation_generator.py::ConceptRepresentationGenerator._format_python_value"]param = "value"@@ -3396,6 +3396,10 @@ rationale = "Hub getter: the native concept being fetched; single operand."param = "domain_code"rationale = "Hub getter keyed by the domain code; single operand."+["pipelex/interpreter_hub.py::get_optional_entry_pipe"]+param = "pipe_code"+rationale = "Hub accessor keyed by the human-supplied pipe code; single operand, mirroring get_optional_pipe."+["pipelex/interpreter_hub.py::get_optional_pipe"]param = "pipe_code"rationale = "Hub getter keyed by the pipe code; single operand."@@ -3416,6 +3420,10 @@ rationale = "Hub getter keyed by the concept ref; single operand."param = "domain_code"rationale = "Hub getter keyed by the domain code; single operand."+["pipelex/interpreter_hub.py::get_required_entry_pipe"]+param = "pipe_code"+rationale = "Hub accessor keyed by the human-supplied pipe code; single operand, mirroring get_required_pipe."+["pipelex/interpreter_hub.py::get_required_pipe"]param = "pipe_code"rationale = "Hub getter keyed by the pipe code; single operand."@@ -3580,6 +3588,10 @@ rationale = "Verb-object: formats the text; formatting options stay keyword."param = "concept_ref"rationale = "Library getter keyed by the concept ref; single operand."+["pipelex/libraries/concept/concept_library.py::ConceptLibrary.get_optional_entry_concept"]+param = "concept_ref_or_code"+rationale = "Entry affordance keyed by the human-supplied concept string; single operand, mirroring get_optional_entry_pipe."+["pipelex/libraries/concept/concept_library.py::ConceptLibrary.is_concept_exists"]param = "concept_ref"rationale = "Predicate on the concept named by the ref; single operand."@@ -3616,10 +3628,6 @@ rationale = "Verb-object: validates refs within the blueprints; single operand."param = "spec"rationale = "Derivation: canonicalizes the spec; single operand."-["pipelex/libraries/crate_normalization.py::_domain_of"]-param = "qualified_ref"-rationale = "Noun-named derivation: parses the domain out of the qualified ref."-["pipelex/libraries/crate_normalization.py::_flatten_refinement"]param = "concepts"rationale = "Verb-object: flattens the concepts mapping in place; single operand."@@ -3636,37 +3644,49 @@ rationale = "Noun-named derivation: the effective structure for the native ref;param = "value"rationale = "Single-operand normalization of the concept entry; the rest is context."-["pipelex/libraries/crate_normalization.py::_normalize_pipe"]-param = "blueprint"-rationale = "Single-operand normalization of the pipe blueprint; owner_domain is context."+["pipelex/libraries/crate_normalization.py::_resolve_refinement"]+param = "concept_ref"+rationale = "Verb-object: resolves the concept ref; concepts and cache are context."++["pipelex/libraries/crate_normalization.py::normalize_crate"]+param = "crate"+rationale = "Verb-object: normalizes the crate; mthds_version stays keyword."-["pipelex/libraries/crate_normalization.py::_qualify_concept_ref"]+["pipelex/libraries/crate_qualification.py::_domain_of"]+param = "qualified_ref"+rationale = "Noun-named derivation: parses the domain out of the qualified ref."++["pipelex/libraries/crate_qualification.py::_qualify_concept_entry"]+param = "value"+rationale = "Single-operand qualification of the concept entry; owner_domain is context."++["pipelex/libraries/crate_qualification.py::_qualify_concept_ref"]param = "concept_ref_or_code"rationale = "Single-operand transformation of the ref; domain is context."-["pipelex/libraries/crate_normalization.py::_qualify_io_ref"]+["pipelex/libraries/crate_qualification.py::_qualify_io_ref"]param = "io_ref"rationale = "Single-operand transformation of the ref; domain is context."-["pipelex/libraries/crate_normalization.py::_qualify_pipe_ref"]+["pipelex/libraries/crate_qualification.py::_qualify_pipe_blueprint"]+param = "blueprint"+rationale = "Single-operand qualification of the pipe blueprint; owner_domain is context."++["pipelex/libraries/crate_qualification.py::_qualify_pipe_ref"]param = "pipe_ref"rationale = "Single-operand transformation of the ref; domain is context."-["pipelex/libraries/crate_normalization.py::_qualify_structure_field"]+["pipelex/libraries/crate_qualification.py::_qualify_structure_field"]param = "field_blueprint"rationale = "Single-operand transformation of the field blueprint; domain is context."-["pipelex/libraries/crate_normalization.py::_render_ref_with_markers"]+["pipelex/libraries/crate_qualification.py::_render_ref_with_markers"]param = "concept_ref"rationale = "Verb-object: renders the ref; parsed markers stay keyword."-["pipelex/libraries/crate_normalization.py::_resolve_refinement"]-param = "concept_ref"-rationale = "Verb-object: resolves the concept ref; concepts and cache are context."--["pipelex/libraries/crate_normalization.py::normalize_crate"]+["pipelex/libraries/crate_qualification.py::qualify_crate"]param = "crate"-rationale = "Verb-object: normalizes the crate; mthds_version stays keyword."+rationale = "Verb-object: qualifies the crate's in-body refs; single operand."["pipelex/libraries/domain/domain_library.py::DomainLibrary.add_domain"]param = "domain"@@ -3840,10 +3860,18 @@ rationale = "Verb-object: adds the pipe; single operand."param = "pipes"rationale = "Verb-object: adds the pipes; single operand."+["pipelex/libraries/pipe/pipe_library_abstract.py::PipeLibraryAbstract.get_optional_entry_pipe"]+param = "pipe_code"+rationale = "Entry-point getter keyed by the human-supplied pipe code; single operand."+["pipelex/libraries/pipe/pipe_library_abstract.py::PipeLibraryAbstract.get_optional_pipe"]param = "pipe_code"rationale = "Library getter keyed by the pipe code; single operand."+["pipelex/libraries/pipe/pipe_library_abstract.py::PipeLibraryAbstract.get_required_entry_pipe"]+param = "pipe_code"+rationale = "Entry-point resolver keyed by the human-supplied pipe code; single operand."+["pipelex/libraries/pipe/pipe_library_abstract.py::PipeLibraryAbstract.get_required_pipe"]param = "pipe_code"rationale = "Resolver getter keyed by the pipe code; single operand."diff --git a/tests/e2e/pipelex/cli/test_entry_bare_code_cmd.py b/tests/e2e/pipelex/cli/test_entry_bare_code_cmd.pynew file mode 100644index 000000000..df496e998--- /dev/null+++ b/tests/e2e/pipelex/cli/test_entry_bare_code_cmd.py@@ -0,0 +1,74 @@+"""A hand-typed bare pipe code still works at the CLI, end to end.++A perfectly-tested affordance can still be perfectly mis-called. The unit tests around+`get_optional_entry_pipe` prove the affordance behaves; these prove the commands actually reach it,+against a real loaded library rather than a mock. `pipelex which summarize_it` is precisely the+invocation the affordance exists to preserve while in-body resolution became strict, so if a command+were left on the strict lookup, the affordance would be right and the product still broken.++The sibling-domain case is the discriminating one: it is where the entry affordance and in-body+resolution genuinely disagree, so it fails if a command is wired to the wrong door.+"""++import tempfile+from collections.abc import Callable, Generator+from pathlib import Path++import pytest++from pipelex.cli.commands.show_cmd import do_show_pipe+from pipelex.cli.commands.which_cmd import do_which_pipe+from pipelex.libraries.pipe.exceptions import PipeNotFoundError++_TWO_DOMAIN_MTHDS = """+domain = "reporting"+description = "Owns the summarizer."++[pipe.summarize_it]+type = "PipeLLM"+description = "Summarize the input."+inputs = { doc = "Text" }+output = "Text"+prompt = "Summarize $doc"+"""++_CALLER_MTHDS = """+domain = "orchestration"+description = "A second domain, so a bare code is not trivially unique to one."++[pipe.kick_off]+type = "PipeLLM"+description = "Does its own thing."+inputs = { doc = "Text" }+output = "Text"+prompt = "Do something with $doc"+"""+++def two_domain_dir(load_test_library: Callable[[list[Path]], None]) -> Generator[Path, None, None]:+ with tempfile.TemporaryDirectory() as tmp_dir:+ library_dir = Path(tmp_dir)+ (library_dir / "reporting.mthds").write_text(_TWO_DOMAIN_MTHDS, encoding="utf-8")+ (library_dir / "orchestration.mthds").write_text(_CALLER_MTHDS, encoding="utf-8")+ load_test_library([library_dir])+ yield library_dir+++class TestEntryBareCodeCommands:+ def test_which_resolves_a_bare_code_from_another_domain(self, two_domain_dir: Path):+ """`pipelex which summarize_it` — the user is pointing at a pipe, not writing a reference."""+ assert do_which_pipe(pipe_code="summarize_it", library_dirs=[two_domain_dir], source_label="test")++ @pytest.mark.usefixtures("two_domain_dir")+ def test_show_resolves_a_bare_code_from_another_domain(self):+ do_show_pipe(pipe_code="summarize_it")++ @pytest.mark.usefixtures("two_domain_dir")+ def test_qualified_code_still_works(self):+ do_show_pipe(pipe_code="reporting.summarize_it")++ @pytest.mark.usefixtures("two_domain_dir")+ def test_unknown_bare_code_still_reports_not_found(self):+ with pytest.raises(PipeNotFoundError):+ do_show_pipe(pipe_code="no_such_pipe_anywhere")diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_1.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_1.pyindex 4e6ec4513..6f6f7cdba 100644--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_1.py+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_1.py@@ -7,7 +7,7 @@ from pipelex import pretty_printfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.stuff_factory import StuffFactory-from pipelex.interpreter_hub import get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_pipe_router, get_required_entry_pipefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.system.job_metadata import JobMetadata@@ -52,7 +52,7 @@ class TestPipeConditionExpressionTemplate:# Run the pipepipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="basic_condition_by_category_2"),+ pipe=get_required_entry_pipe(pipe_code="basic_condition_by_category_2"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_2.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_2.pyindex 997984929..e39f3eba0 100644--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_2.py+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_2.py@@ -7,7 +7,7 @@ from pipelex import pretty_printfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.stuff_factory import StuffFactory-from pipelex.interpreter_hub import get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_pipe_router, get_required_entry_pipefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.system.job_metadata import JobMetadata@@ -52,7 +52,7 @@ class TestPipeConditionExpression:# Run the pipepipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="basic_condition_by_category"),+ pipe=get_required_entry_pipe(pipe_code="basic_condition_by_category"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.pyindex 19d480dda..944c350a5 100644--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_condition/test_pipe_condition_simple.py@@ -35,8 +35,12 @@ class TestPipeConditionSimple:inputs={"user_category": "test_pipe_condition.CategoryInput"},output=f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}",expression_template="{{ user_category.category }}",- outcomes={"small": "process_small", "medium": "process_medium", "large": "process_large"},- default_outcome="process_small",+ outcomes={+ "small": "test_pipe_condition.process_small",+ "medium": "test_pipe_condition.process_medium",+ "large": "test_pipe_condition.process_large",+ },+ default_outcome="test_pipe_condition.process_small",)pipe_condition = PipeFactory[PipeCondition].make_from_blueprint(@@ -73,8 +77,12 @@ class TestPipeConditionSimple:inputs={"user_status": "test_pipe_condition.CategoryInput"},output=f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}",expression_template="{{ user_status.category }}",- outcomes={"active": "process_small", "inactive": "process_medium", "pending": "process_large"},- default_outcome="process_small",+ outcomes={+ "active": "test_pipe_condition.process_small",+ "inactive": "test_pipe_condition.process_medium",+ "pending": "test_pipe_condition.process_large",+ },+ default_outcome="test_pipe_condition.process_small",)pipe_condition = PipeFactory[PipeCondition].make_from_blueprint(diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_parallel/test_pipe_parallel_1.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_parallel/test_pipe_parallel_1.pyindex ea72f539b..142928639 100644--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_parallel/test_pipe_parallel_1.py+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_parallel/test_pipe_parallel_1.py@@ -7,7 +7,7 @@ from pipelex import pretty_printfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.stuff_factory import StuffFactory-from pipelex.interpreter_hub import get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_pipe_router, get_required_entry_pipefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.system.job_metadata import JobMetadata@@ -56,7 +56,7 @@ class TestPipeParallelDocumentAnalysis:# Run the pipepipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="parallel_document_analysis"),+ pipe=get_required_entry_pipe(pipe_code="parallel_document_analysis"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_batching.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_batching.pyindex 005f54846..d54cc17a0 100644--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_batching.py+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_batching.py@@ -10,7 +10,7 @@ from pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.pipes.inputs.input_stuff_specs import TypedNamedStuffSpecfrom pipelex.core.stuffs.stuff_factory import StuffFactory-from pipelex.interpreter_hub import get_required_pipe+from pipelex.interpreter_hub import get_required_entry_pipefrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.system.job_metadata import JobMetadata@@ -42,7 +42,7 @@ async def test_review_analysis_sequence_with_batching(),],)- pipe = get_required_pipe(pipe_code="analyze_reviews_sequence")+ pipe = get_required_entry_pipe(pipe_code="analyze_reviews_sequence")pipe_output = await pipe.run_pipe(job_metadata=job_metadata,pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),diff --git a/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_simple.py b/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_simple.pyindex 69e937a6b..63d2ab326 100644--- a/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_simple.py+++ b/tests/e2e/pipelex/pipes/pipe_controller/pipe_sequence/test_pipe_sequence_simple.py@@ -10,7 +10,7 @@ from pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.interpreter_hub import get_required_pipe+from pipelex.interpreter_hub import get_required_entry_pipefrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.system.job_metadata import JobMetadatafrom pipelex.system.pipe_run_mode import PipeRunMode@@ -38,7 +38,7 @@ class TestPipeSequenceSimple:# Create working memory with the required input for dry runworking_memory = WorkingMemoryFactory.make_from_multiple_stuffs([raw_text_stuff])- pipe = get_required_pipe(pipe_code="simple_text_sequence")+ pipe = get_required_entry_pipe(pipe_code="simple_text_sequence")pipe_output = await pipe.run_pipe(job_metadata=job_metadata,working_memory=working_memory,diff --git a/tests/e2e/pipelex/pipes/smart_inputs/test_smart_inputs_light_roundtrip.py b/tests/e2e/pipelex/pipes/smart_inputs/test_smart_inputs_light_roundtrip.pyindex 536e2a6cb..50f1d21d2 100644--- a/tests/e2e/pipelex/pipes/smart_inputs/test_smart_inputs_light_roundtrip.py+++ b/tests/e2e/pipelex/pipes/smart_inputs/test_smart_inputs_light_roundtrip.py@@ -18,7 +18,13 @@ from typing import TYPE_CHECKING, Anyimport pytest-from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_pipe, set_current_library+from pipelex.interpreter_hub import (+ clear_current_library,+ get_current_library_id_or_none,+ get_library_manager,+ get_required_entry_pipe,+ set_current_library,+)from pipelex.pipe_machinery.rendering.input_renderer import render_inputsfrom pipelex.pipeline.pipeline_response import RunStatefrom pipelex.pipeline.runner import PipelexMTHDSProtocol@@ -47,7 +53,7 @@ class TestSmartInputsLightRoundTrip:outer_library_id = load_empty_library()try:await validate_bundle(mthds_file_path=_BUNDLE)- the_pipe = get_required_pipe(pipe_code="smart_inputs_demo.triage_case")+ the_pipe = get_required_entry_pipe(pipe_code="smart_inputs_demo.triage_case")light_inputs: dict[str, Any] = json.loads(render_inputs(the_pipe))finally:_teardown_validation_library(outer_library_id)diff --git a/tests/integration/pipelex/fixtures/pipe_job_helpers.py b/tests/integration/pipelex/fixtures/pipe_job_helpers.pyindex 643a696d1..c80692585 100644--- a/tests/integration/pipelex/fixtures/pipe_job_helpers.py+++ b/tests/integration/pipelex/fixtures/pipe_job_helpers.py@@ -4,7 +4,7 @@ from pathlib import Pathfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactory-from pipelex.interpreter_hub import clear_current_library, get_library_manager, get_required_pipe, set_current_library+from pipelex.interpreter_hub import clear_current_library, get_library_manager, get_required_entry_pipe, set_current_libraryfrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.mthds_parsing.parser import MthdsParserfrom pipelex.pipe_machinery.pipe_abstract import PipeAbstract@@ -100,7 +100,7 @@ def pipe_job_from_library(try:load_fn(library_id)- pipe = get_required_pipe(pipe_code=pipe_code)+ pipe = get_required_entry_pipe(pipe_code=pipe_code)library_crate = library_manager.get_crate(library_id=library_id)pipe_job = build_pipe_job(pipe=pipe, library_crate=library_crate, pipe_run_mode=pipe_run_mode, pipeline_run_id=pipeline_run_id)if working_memory_builder is not None:diff --git a/tests/integration/pipelex/libraries/test_pipe_namespace.py b/tests/integration/pipelex/libraries/test_pipe_namespace.pyindex 97fbe9b75..ca4769cac 100644--- a/tests/integration/pipelex/libraries/test_pipe_namespace.py+++ b/tests/integration/pipelex/libraries/test_pipe_namespace.py@@ -152,9 +152,13 @@ class TestPipeNamespace:assert analytics_pipe.code == "process"assert analytics_pipe.domain_code == "analytics"- # Bare code is ambiguous- with pytest.raises(PipeLibraryError, match="Ambiguous pipe code"):- library.pipe_library.get_optional_pipe("process")+ # A bare code is not an in-body reference the library will chase across domains, so it+ # simply does not resolve there. Ambiguity is now the entry affordance's problem, because+ # searching is the only thing that can produce it.+ assert library.pipe_library.get_optional_pipe("process") is None++ with pytest.raises(PipeLibraryError, match="is ambiguous"):+ library.pipe_library.get_optional_entry_pipe("process")def test_multi_bundle_same_domain(self, load_test_library: Callable[[list[Path]], None]):"""Multiple .mthds files contributing to the same domain load successfully."""@@ -207,7 +211,10 @@ class TestPipeNamespace:)def test_bare_code_lookup_from_mthds(self, load_test_library: Callable[[list[Path]], None]):- """Bare code lookup works when pipe code is unambiguous (single domain)."""+ """A hand-typed bare code still reaches the pipe — through the entry affordance, not the+ in-body resolver. `pipelex which compute_score` must keep working; a pipe reaching another+ domain by bare code must not.+ """with tempfile.TemporaryDirectory() as tmp_dir:(Path(tmp_dir) / "scoring.mthds").write_text(SINGLE_DOMAIN_MTHDS, encoding="utf-8")@@ -215,13 +222,15 @@ class TestPipeNamespace:library = get_library_manager().get_current_library()- # Both bare code and pipe_ref lookup workpipe_by_ref = library.pipe_library.get_required_pipe("scoring.compute_score")- pipe_by_code = library.pipe_library.get_required_pipe("compute_score")+ pipe_by_code = library.pipe_library.get_required_entry_pipe("compute_score")assert pipe_by_ref is pipe_by_codeassert pipe_by_ref.pipe_ref == "scoring.compute_score"+ # The in-body resolver does not accept the bare form at all.+ assert library.pipe_library.get_optional_pipe("compute_score") is None+def test_wrong_domain_lookup_returns_not_found(self, load_test_library: Callable[[list[Path]], None]):"""Looking up a pipe with the wrong domain raises PipeNotFoundError."""with tempfile.TemporaryDirectory() as tmp_dir:diff --git a/tests/integration/pipelex/libraries/test_unresolved_pipe_ref_message.py b/tests/integration/pipelex/libraries/test_unresolved_pipe_ref_message.pynew file mode 100644index 000000000..ff580eed6--- /dev/null+++ b/tests/integration/pipelex/libraries/test_unresolved_pipe_ref_message.py@@ -0,0 +1,151 @@+"""The message a user meets when a bare in-body pipe ref stops resolving.++This is the migration path for the whole owner-domain change, so it is worth a test of its own. The+hard part is that the ref named in the error is not the ref the author typed: they wrote a bare code+and the compiler qualified it to their own domain. A message that only names the qualified ref points+at a pipe that appears nowhere in their file, and reads like a compiler bug rather than a fix list.++Both branches matter — with a candidate elsewhere in the library, and with none — because the+suggestion arm is the one that comes from a crate-wide scan, and that scan must stay strictly on the+failure path. It suggests; it never resolves.+"""++import tempfile+from collections.abc import Callable+from pathlib import Path++import pytest++from pipelex.interpreter_hub import get_library_manager+from pipelex.libraries.exceptions import LibraryLoadingError++_SIBLING_DOMAIN_MTHDS = """+domain = "orchestrator"+description = "Calls a pipe that lives in another domain, by bare code."++[pipe.run_all]+type = "PipeSequence"+description = "Runs the presentation step."+inputs = { data = "Text" }+output = "Text"+steps = [{ pipe = "present_as_markdown", result = "presented" }]+"""++_PRESENTATION_MTHDS = """+domain = "presentation"+description = "Owns the presenter."++[pipe.present_as_markdown]+type = "PipeLLM"+description = "Present as markdown."+inputs = { data = "Text" }+output = "Text"+prompt = "Present $data as markdown"+"""++_NO_CANDIDATE_MTHDS = """+domain = "orchestrator"+description = "Calls a pipe that exists nowhere at all."++[pipe.run_all]+type = "PipeSequence"+description = "Runs a step that does not exist."+inputs = { data = "Text" }+output = "Text"+steps = [{ pipe = "nowhere_to_be_found", result = "presented" }]+"""++_MALFORMED_REF_MTHDS = """+domain = "orchestrator"+description = "Calls a pipe through a ref that does not even parse."++[pipe.run_all]+type = "PipeSequence"+description = "Runs a step whose ref is malformed."+inputs = { data = "Text" }+output = "Text"+steps = [{ pipe = "a..b", result = "presented" }]+"""+++class TestUnresolvedPipeRefMessage:+ def _load_and_capture(self, *, sources: dict[str, str], load_test_library: Callable[[list[Path]], None]) -> str:+ with tempfile.TemporaryDirectory() as tmp_dir:+ for name, text in sources.items():+ (Path(tmp_dir) / name).write_text(text, encoding="utf-8")+ with pytest.raises(LibraryLoadingError) as exc_info:+ load_test_library([Path(tmp_dir)])+ return str(exc_info.value)++ def test_names_the_qualified_ref_and_explains_the_rule(self, load_test_library: Callable[[list[Path]], None]):+ """The author wrote `present_as_markdown`; the compiler tried `orchestrator.present_as_markdown`.++ Saying only the second is what makes this look like a compiler bug, so the message has to+ carry both plus the rule that connects them.+ """+ message = self._load_and_capture(+ sources={"orchestrator.mthds": _SIBLING_DOMAIN_MTHDS, "presentation.mthds": _PRESENTATION_MTHDS},+ load_test_library=load_test_library,+ )+ assert "orchestrator.present_as_markdown" in message+ assert "present_as_markdown" in message+ assert "own domain" in message++ def test_suggests_the_sibling_that_actually_declares_the_code(self, load_test_library: Callable[[list[Path]], None]):+ """The fix is one qualified spelling away, so the message says which one."""+ message = self._load_and_capture(+ sources={"orchestrator.mthds": _SIBLING_DOMAIN_MTHDS, "presentation.mthds": _PRESENTATION_MTHDS},+ load_test_library=load_test_library,+ )+ assert "presentation.present_as_markdown" in message++ def test_no_candidate_means_no_suggestion(self, load_test_library: Callable[[list[Path]], None]):+ """A plain typo gets the rule but no invented fix.++ The suggestion arm reads a crate-wide scan; with nothing to find it must stay silent rather+ than pad the message. This is also the branch that proves the scan is consulted per failure+ rather than assumed non-empty.+ """+ message = self._load_and_capture(+ sources={"orchestrator.mthds": _NO_CANDIDATE_MTHDS},+ load_test_library=load_test_library,+ )+ assert "orchestrator.nowhere_to_be_found" in message+ assert "did you mean" not in message.lower()++ def test_malformed_ref_stays_a_categorized_error(self, load_test_library: Callable[[list[Path]], None]):+ """A ref that does not parse must surface as the categorized load error, never a crash.++ The message builder parses the missing ref to explain the qualification rule; on a+ malformed ref that parse would replace the categorized error with a raw QualifiedRefError+ on the way to reporting bad user input. The guard falls back to the short message instead —+ `_load_and_capture`'s `pytest.raises(LibraryLoadingError)` is what pins the exception class.+ """+ message = self._load_and_capture(+ sources={"orchestrator.mthds": _MALFORMED_REF_MTHDS},+ load_test_library=load_test_library,+ )+ assert "a..b" in message+ assert "does not exist" in message+ assert "did you mean" not in message.lower()++ def test_two_domains_declaring_the_same_code_each_bind_their_own(self, load_test_library: Callable[[list[Path]], None]):+ """The end-to-end payoff, through the real load path: same bare code, two domains, no ambiguity.++ Under the deleted crate-wide search this library did not load at all — the bare ref matched+ two pipes and the lookup raised. Now each domain's ref means that domain's pipe, so adding a+ `present_as_markdown` somewhere else cannot change what an existing method does.+ """+ second_presenter = _PRESENTATION_MTHDS.replace('domain = "presentation"', 'domain = "alt_presentation"')+ with tempfile.TemporaryDirectory() as tmp_dir:+ (Path(tmp_dir) / "presentation.mthds").write_text(_PRESENTATION_MTHDS, encoding="utf-8")+ (Path(tmp_dir) / "alt_presentation.mthds").write_text(second_presenter, encoding="utf-8")+ (Path(tmp_dir) / "caller.mthds").write_text(+ _SIBLING_DOMAIN_MTHDS.replace('domain = "orchestrator"', 'domain = "presentation"').replace("[pipe.run_all]", "[pipe.run_all_here]"),+ encoding="utf-8",+ )+ load_test_library([Path(tmp_dir)])++ library = get_library_manager().get_current_library()+ sequence = library.pipe_library.get_required_pipe("presentation.run_all_here")+ assert sequence.pipe_dependencies() == {"presentation.present_as_markdown"}diff --git a/tests/integration/pipelex/pipe_machinery/test_input_renderer_light_golden.py b/tests/integration/pipelex/pipe_machinery/test_input_renderer_light_golden.pyindex 2bb2f7657..460038f09 100644--- a/tests/integration/pipelex/pipe_machinery/test_input_renderer_light_golden.py+++ b/tests/integration/pipelex/pipe_machinery/test_input_renderer_light_golden.py@@ -21,7 +21,13 @@ from typing import TYPE_CHECKING, Any, castimport pytestimport tomli-from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_pipe, set_current_library+from pipelex.interpreter_hub import (+ clear_current_library,+ get_current_library_id_or_none,+ get_library_manager,+ get_required_entry_pipe,+ set_current_library,+)from pipelex.pipe_machinery.rendering.input_renderer import render_inputs, render_inputs_tomlfrom pipelex.pipeline.validate_bundle import validate_bundle@@ -51,7 +57,7 @@ class TestInputRendererLightGolden:async def _load_pipe(self, bundle_path: Path, *, pipe_ref: str, load_empty_library: Callable[[], str]) -> tuple[Any, str]:outer_library_id = load_empty_library()await validate_bundle(mthds_file_path=bundle_path)- the_pipe = get_required_pipe(pipe_code=pipe_ref)+ the_pipe = get_required_entry_pipe(pipe_code=pipe_ref)return the_pipe, outer_library_idasync def test_triage_light_json_default(self, load_empty_library: Callable[[], str]) -> None:diff --git a/tests/integration/pipelex/pipe_signature/test_collect_signature_refs.py b/tests/integration/pipelex/pipe_signature/test_collect_signature_refs.pyindex e3fa8f3f4..4e8a61b0d 100644--- a/tests/integration/pipelex/pipe_signature/test_collect_signature_refs.py+++ b/tests/integration/pipelex/pipe_signature/test_collect_signature_refs.py@@ -72,7 +72,7 @@ class TestCollectSignatureRefs:description="Sequence containing a signature step.",inputs={"doc": "SigTestDoc"},output="SigTestSummary",- steps=[SubPipeBlueprint(pipe="seq_sig_step", result="summary")],+ steps=[SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.seq_sig_step", result="summary")],)seq_pipe = PipeFactory[PipeSequence].make_from_blueprint(domain_code=SIGNATURES_DOMAIN_CODE,@@ -103,7 +103,7 @@ class TestCollectSignatureRefs:description="Parallel with a signature branch.",inputs={"doc": "SigTestDoc"},output="SigTestSummary",- branches=[SubPipeBlueprint(pipe="par_sig_branch", result="summary")],+ branches=[SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.par_sig_branch", result="summary")],add_each_output=True,)par_pipe = PipeFactory[PipeParallel].make_from_blueprint(@@ -143,8 +143,8 @@ class TestCollectSignatureRefs:inputs={"doc": "SigTestDoc"},output="SigTestSummary",expression="doc",- outcomes={"A": "cond_sig_a"},- default_outcome="cond_sig_b",+ outcomes={"A": f"{SIGNATURES_DOMAIN_CODE}.cond_sig_a"},+ default_outcome=f"{SIGNATURES_DOMAIN_CODE}.cond_sig_b",)cond_pipe = PipeFactory[PipeCondition].make_from_blueprint(domain_code=SIGNATURES_DOMAIN_CODE,@@ -175,7 +175,7 @@ class TestCollectSignatureRefs:description="Batch over a signature branch.",inputs={"docs": "SigTestDoc[]"},output="SigTestSummary[]",- branch_pipe_code="batch_sig_branch",+ branch_pipe_code=f"{SIGNATURES_DOMAIN_CODE}.batch_sig_branch",input_list_name="docs",input_item_name="doc",)@@ -210,7 +210,7 @@ class TestCollectSignatureRefs:description="Inner sequence calling signature.",inputs={"doc": "SigTestDoc"},output="SigTestSummary",- steps=[SubPipeBlueprint(pipe="nested_sig", result="summary")],+ steps=[SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.nested_sig", result="summary")],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],)@@ -223,7 +223,7 @@ class TestCollectSignatureRefs:description="Outer sequence calling inner sequence.",inputs={"doc": "SigTestDoc"},output="SigTestSummary",- steps=[SubPipeBlueprint(pipe="inner_seq", result="summary")],+ steps=[SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.inner_seq", result="summary")],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],)@@ -254,8 +254,8 @@ class TestCollectSignatureRefs:inputs={"doc": "SigTestDoc"},output="SigTestSummary",steps=[- SubPipeBlueprint(pipe="cycle_sig", result="summary_via_sig"),- SubPipeBlueprint(pipe="seq_cycle_a", result="summary_recurse"),+ SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.cycle_sig", result="summary_via_sig"),+ SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.seq_cycle_a", result="summary_recurse"),],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],@@ -288,7 +288,7 @@ class TestCollectSignatureRefs:inputs={"doc": "SigTestDoc"},output="SigTestSummary",steps=[- SubPipeBlueprint(pipe="reachable_sig", result="summary"),+ SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.reachable_sig", result="summary"),SubPipeBlueprint(pipe="missing_pkg->some.unknown_pipe", result="ignored"),],),@@ -323,7 +323,7 @@ class TestCollectSignatureRefs:description="Short branch straight to the signature.",inputs={"doc": "SigTestDoc"},output="SigTestSummary",- steps=[SubPipeBlueprint(pipe="diamond_sig", result="summary")],+ steps=[SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.diamond_sig", result="summary")],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],)@@ -334,7 +334,7 @@ class TestCollectSignatureRefs:description="Last hop of the long branch before the signature.",inputs={"doc": "SigTestDoc"},output="SigTestSummary",- steps=[SubPipeBlueprint(pipe="diamond_sig", result="summary")],+ steps=[SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.diamond_sig", result="summary")],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],)@@ -347,7 +347,7 @@ class TestCollectSignatureRefs:description="First hop of the long branch.",inputs={"doc": "SigTestDoc"},output="SigTestSummary",- steps=[SubPipeBlueprint(pipe="d_seq", result="summary")],+ steps=[SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.d_seq", result="summary")],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],)@@ -361,8 +361,8 @@ class TestCollectSignatureRefs:inputs={"doc": "SigTestDoc"},output="SigTestSummary",steps=[- SubPipeBlueprint(pipe="b_seq", result="via_short"),- SubPipeBlueprint(pipe="c_seq", result="via_long"),+ SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.b_seq", result="via_short"),+ SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.c_seq", result="via_long"),],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],@@ -396,8 +396,8 @@ class TestCollectSignatureRefs:inputs={"doc": "SigTestDoc"},output="SigTestSummary",steps=[- SubPipeBlueprint(pipe="paths_cycle_sig", result="summary_via_sig"),- SubPipeBlueprint(pipe="paths_seq_cycle", result="summary_recurse"),+ SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.paths_cycle_sig", result="summary_via_sig"),+ SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.paths_seq_cycle", result="summary_recurse"),],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],diff --git a/tests/integration/pipelex/pipe_signature/test_dry_run_strict_mode.py b/tests/integration/pipelex/pipe_signature/test_dry_run_strict_mode.pyindex d2285cb58..524cc4888 100644--- a/tests/integration/pipelex/pipe_signature/test_dry_run_strict_mode.py+++ b/tests/integration/pipelex/pipe_signature/test_dry_run_strict_mode.py@@ -37,6 +37,8 @@ def _make_bundle_with_signature() -> PipelexBundleBlueprint:description="Sequence step calling the signature.",inputs={"doc": "BundleDoc"},output="BundleSummary",+ # Bare on purpose: this is a bundle blueprint, so it goes through the crate+ # qualification pass and picks up this bundle's own domain, not SIGNATURES_DOMAIN_CODE.steps=[SubPipeBlueprint(pipe="bundle_sig_step", result="summary")],),},@@ -79,7 +81,7 @@ class TestDryRunStrictMode:description="Pure-operator sequence.",inputs={"doc": "SigTestDoc"},output="SigTestSummary",- steps=[SubPipeBlueprint(pipe="strict_real_step", result="summary")],+ steps=[SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.strict_real_step", result="summary")],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],)@@ -111,7 +113,7 @@ class TestDryRunStrictMode:description="Sequence containing a signature.",inputs={"doc": "SigTestDoc"},output="SigTestSummary",- steps=[SubPipeBlueprint(pipe="strict_sig_step", result="summary")],+ steps=[SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.strict_sig_step", result="summary")],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],)@@ -142,7 +144,7 @@ class TestDryRunStrictMode:description="Sequence with a signature, but lenient mode.",inputs={"doc": "SigTestDoc"},output="SigTestSummary",- steps=[SubPipeBlueprint(pipe="lenient_sig_step", result="summary")],+ steps=[SubPipeBlueprint(pipe=f"{SIGNATURES_DOMAIN_CODE}.lenient_sig_step", result="summary")],),concept_codes_from_the_same_domain=["SigTestDoc", "SigTestSummary"],)diff --git a/tests/integration/pipelex/pipeline/test_bundle_validator.py b/tests/integration/pipelex/pipeline/test_bundle_validator.pyindex a2d8fe2dd..8d6d00cb1 100644--- a/tests/integration/pipelex/pipeline/test_bundle_validator.py+++ b/tests/integration/pipelex/pipeline/test_bundle_validator.py@@ -17,7 +17,7 @@ from pytest_mock import MockerFixturefrom typing_extensions import overridefrom pipelex.core.pipes.pipe_output import PipeOutput-from pipelex.interpreter_hub import clear_current_library, get_interpreter_hub, get_library_manager, get_required_pipe+from pipelex.interpreter_hub import clear_current_library, get_interpreter_hub, get_library_manager, get_required_entry_pipefrom pipelex.observer.observer_protocol import ObserverNoOpfrom pipelex.pipe_run.pipe_job import PipeJobfrom pipelex.pipe_run.pipe_router import PipeRouter@@ -144,7 +144,7 @@ class TestBundleValidatorIntegration:_, qualified_main_pipe = acquire_library(library_id=library_id, mthds_contents=[_BV_MTHDS])try:assert qualified_main_pipe is not None- pipe = get_required_pipe(pipe_code=qualified_main_pipe)+ pipe = get_required_entry_pipe(pipe_code=qualified_main_pipe)results = await BundleValidator().validate_pipes([pipe], library_id=library_id)assert results[pipe.pipe_ref].status.is_successassert results[pipe.pipe_ref].pipe_ref == f"{_BV_DOMAIN}.echo_topic"@@ -164,7 +164,7 @@ class TestBundleValidatorIntegration:_, qualified_main_pipe = acquire_library(library_id=library_id, mthds_contents=[_BV_MTHDS])try:assert qualified_main_pipe is not None- pipe = get_required_pipe(pipe_code=qualified_main_pipe)+ pipe = get_required_entry_pipe(pipe_code=qualified_main_pipe)validator = BundleValidator()first = await validator.validate_pipes([pipe], library_id=library_id)second = await validator.validate_pipes([pipe], library_id=library_id)@@ -217,7 +217,7 @@ class TestBundleValidatorIntegration:_, qualified_main_pipe = acquire_library(library_id=library_id, mthds_contents=[_BV_MTHDS])try:assert qualified_main_pipe is not None- pipe = get_required_pipe(pipe_code=qualified_main_pipe)+ pipe = get_required_entry_pipe(pipe_code=qualified_main_pipe)first, second = await asyncio.gather(BundleValidator().validate_pipes([pipe], library_id=library_id),BundleValidator().validate_pipes([pipe], library_id=library_id),@@ -240,8 +240,8 @@ class TestBundleValidatorIntegration:library_id = "bv_xpkg_skip_lib"acquire_library(library_id=library_id, mthds_contents=[_BV_XPKG_MTHDS])try:- leaf = get_required_pipe(pipe_code=f"{_BV_XPKG_DOMAIN}.implemented_leaf")- controller = get_required_pipe(pipe_code=f"{_BV_XPKG_DOMAIN}.cross_parallel")+ leaf = get_required_entry_pipe(pipe_code=f"{_BV_XPKG_DOMAIN}.implemented_leaf")+ controller = get_required_entry_pipe(pipe_code=f"{_BV_XPKG_DOMAIN}.cross_parallel")results = await BundleValidator().validate_pipes([controller, leaf], library_id=library_id)assert results[f"{_BV_XPKG_DOMAIN}.cross_parallel"].status == DryRunStatus.SKIPPEDassert results[f"{_BV_XPKG_DOMAIN}.implemented_leaf"].status.is_success@@ -264,8 +264,8 @@ class TestBundleValidatorIntegration:acquire_library(library_id=library_id, mthds_contents=[_BV_BATCH_MTHDS])hub.set_pipe_router(pipe_router=sentinel)try:- batch_pipe = get_required_pipe(pipe_code=f"{_BV_BATCH_DOMAIN}.summarize_items")- leaf_pipe = get_required_pipe(pipe_code=f"{_BV_BATCH_DOMAIN}.summarize_item")+ batch_pipe = get_required_entry_pipe(pipe_code=f"{_BV_BATCH_DOMAIN}.summarize_items")+ leaf_pipe = get_required_entry_pipe(pipe_code=f"{_BV_BATCH_DOMAIN}.summarize_item")results = await BundleValidator().validate_pipes([batch_pipe, leaf_pipe], library_id=library_id)assert results[f"{_BV_BATCH_DOMAIN}.summarize_items"].status.is_successassert results[f"{_BV_BATCH_DOMAIN}.summarize_item"].status.is_success@@ -281,7 +281,7 @@ class TestBundleValidatorIntegration:_, qualified_main_pipe = acquire_library(library_id=library_id, mthds_contents=[_BV_MTHDS])try:assert qualified_main_pipe is not None- pipe = get_required_pipe(pipe_code=qualified_main_pipe)+ pipe = get_required_entry_pipe(pipe_code=qualified_main_pipe)track_event_spy = mocker.spy(get_telemetry_manager(), "track_event")await BundleValidator().validate_pipes([pipe], library_id=library_id)diff --git a/tests/integration/pipelex/pipeline/test_entry_concept_scope.py b/tests/integration/pipelex/pipeline/test_entry_concept_scope.pynew file mode 100644index 000000000..509ddbeed--- /dev/null+++ b/tests/integration/pipelex/pipeline/test_entry_concept_scope.py@@ -0,0 +1,60 @@+"""End-to-end pin of the entry concept scope: input shaping prefers the entry pipe's own domain.++This is the wiring test, not the rule test — the rule rows live in+tests/unit/pipelex/libraries/test_concept_library_entry_lookup.py. Here a real run through+``PipelexMTHDSProtocol.execute`` loads TWO bundles whose domains both declare ``Memo``, and the+caller's input envelope names the bare code. Without the scope threading+(pipeline_run_setup → prepare_pipe_job → shape_inputs → StuffFactory →+get_required_entry_concept), the bare code is ambiguous and the run fails; with it, the entry+pipe's own domain wins deterministically.+"""++import pytest++from pipelex.config import get_config+from pipelex.pipeline.runner import PipelexMTHDSProtocol+from pipelex.system.pipe_run_mode import PipeRunMode++_ALPHA_MTHDS = """+domain = "ecs_alpha"+description = "Entry domain declaring its own Memo"++[concept.Memo]+description = "An alpha memo"+refines = "Text"++[pipe.write_memo]+type = "PipeLLM"+description = "Rewrite a memo"+inputs = { memo = "Memo" }+output = "Text"+prompt = "Rewrite $memo"+"""++_BETA_MTHDS = """+domain = "ecs_beta"+description = "Sibling domain declaring a same-named Memo"++[concept.Memo]+description = "A beta memo"+refines = "Text"+"""++[email protected](loop_scope="class")+class TestEntryConceptScope:+ async def test_bare_envelope_concept_resolves_to_the_entry_pipe_domain(self) -> None:+ execution_config = get_config().pipelex.pipeline_execution_config.with_execution_overrides(+ generate_graph=False,+ mock_inputs=False,+ )+ runner = PipelexMTHDSProtocol(pipe_run_mode=PipeRunMode.DRY, execution_config=execution_config)++ response = await runner.execute(+ pipe_code="write_memo",+ mthds_contents=[_ALPHA_MTHDS, _BETA_MTHDS],+ inputs={"memo": {"concept": "Memo", "content": "quarterly numbers"}},+ )++ shaped_memo = response.pipe_output.working_memory.get_stuff("memo")+ assert shaped_memo.concept.concept_ref == "ecs_alpha.Memo"diff --git a/tests/integration/pipelex/pipeline/test_execution_seams.py b/tests/integration/pipelex/pipeline/test_execution_seams.pyindex 3b08bbfa4..4f8a4014f 100644--- a/tests/integration/pipelex/pipeline/test_execution_seams.py+++ b/tests/integration/pipelex/pipeline/test_execution_seams.py@@ -11,7 +11,7 @@ from mthds.protocol.pipeline_inputs import PipelineInputsfrom pytest_mock import MockerFixturefrom pipelex.config import get_config-from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_pipe+from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_entry_pipefrom pipelex.pipeline import execution_seams as execution_seams_modulefrom pipelex.pipeline.execution_seams import acquire_library, prepare_pipe_jobfrom pipelex.system.configuration.configs import PipelineExecutionConfig@@ -59,7 +59,7 @@ class TestExecutionSeams:assert qualified_main_pipe == f"{_SEAMS_DOMAIN}.echo_topic"# Library is left open + current; the loaded pipe is resolvable.assert get_current_library_id_or_none() == library_id- assert get_required_pipe(pipe_code=qualified_main_pipe).code == "echo_topic"+ assert get_required_entry_pipe(pipe_code=qualified_main_pipe).code == "echo_topic"finally:library_manager.teardown(library_id=library_id)clear_current_library()@@ -101,7 +101,7 @@ class TestExecutionSeams:assert qualified_main_pipe == f"{_SEAMS_DOMAIN}.echo_topic"# The returned id is the one left open + current and holding the loaded pipe.assert get_current_library_id_or_none() == returned_id- assert get_required_pipe(pipe_code=qualified_main_pipe).code == "echo_topic"+ assert get_required_entry_pipe(pipe_code=qualified_main_pipe).code == "echo_topic"finally:library_manager.teardown(library_id=returned_id)clear_current_library()@@ -141,7 +141,7 @@ class TestExecutionSeams:_, qualified_main_pipe = acquire_library(library_id=library_id, mthds_contents=[_SEAMS_MTHDS])try:assert qualified_main_pipe is not None- pipe = get_required_pipe(pipe_code=qualified_main_pipe)+ pipe = get_required_entry_pipe(pipe_code=qualified_main_pipe)pipe_job = await prepare_pipe_job(pipe=pipe,library_id=library_id,@@ -173,7 +173,7 @@ class TestExecutionSeams:_, qualified_main_pipe = acquire_library(library_id=library_id, mthds_contents=[_SEAMS_MTHDS])try:assert qualified_main_pipe is not None- pipe = get_required_pipe(pipe_code=qualified_main_pipe)+ pipe = get_required_entry_pipe(pipe_code=qualified_main_pipe)normalize_spy = mocker.spy(execution_seams_module, "normalize_data_urls_to_storage")normalize_config = (get_config()diff --git a/tests/integration/pipelex/pipeline/test_fix_convergence_loop.py b/tests/integration/pipelex/pipeline/test_fix_convergence_loop.pyindex 468971a2f..f2868da1c 100644--- a/tests/integration/pipelex/pipeline/test_fix_convergence_loop.py+++ b/tests/integration/pipelex/pipeline/test_fix_convergence_loop.py@@ -637,27 +637,22 @@ class TestFixConvergenceLoop:# The qualified step reference survives untouched (it resolves to the renamed bare pipe).assert pipes["run_seq"]["steps"][0]["pipe"] == "nsfix_loop.hello"- @pytest.mark.parametrize(- "sibling_mthds",- [_XFILE_SIBLING_SAME_DOMAIN_MTHDS, _XFILE_SIBLING_OTHER_DOMAIN_MTHDS],- )- async def test_strip_namespace_bails_on_cross_file_collision(+ async def test_strip_namespace_bails_on_same_domain_cross_file_collision(self,tmp_path: Path,load_empty_library: Callable[[], str],- sibling_mthds: str,) -> None:- """A rename whose bare code is declared by ANY sibling bundle is never applied.+ """A rename whose bare code is declared by a SAME-DOMAIN sibling bundle is never applied.The raise-site collision gate only sees the target file, so the loop's cross-file guard- must drop the fix — same domain (duplicate declaration) and other domain (bare-code- ambiguity) alike. The loop bails loudly with the collision reason and the target file's- bytes are untouched — no unrepairable state is ever written.+ must drop the fix: applying it would write a duplicate ``domain.code`` declaration the+ loop can never repair. The loop bails loudly with the collision reason and the target+ file's bytes are untouched — no unrepairable state is ever written."""load_empty_library()bundle_path = tmp_path / "target.mthds"bundle_path.write_text(_XFILE_TARGET_MTHDS, encoding="utf-8")- (tmp_path / "sibling.mthds").write_text(sibling_mthds, encoding="utf-8")+ (tmp_path / "sibling.mthds").write_text(_XFILE_SIBLING_SAME_DOMAIN_MTHDS, encoding="utf-8")result = await fix_bundle_file(bundle_path, library_dirs=[tmp_path])@@ -669,6 +664,32 @@ class TestFixConvergenceLoop:assert result.remaining_errorsassert bundle_path.read_text(encoding="utf-8") == _XFILE_TARGET_MTHDS+ async def test_strip_namespace_applies_despite_other_domain_sibling(+ self,+ tmp_path: Path,+ load_empty_library: Callable[[], str],+ ) -> None:+ """A same-named pipe in ANOTHER domain is not a collision: the rename applies and converges.++ The library keys pipes by ``domain.code`` and in-body refs never search across domains,+ so ``nsfix_xfile.hola`` and ``nsfix_xfile_other.hola`` coexist. The old crate-wide+ collision scope dropped this fix; the per-domain scope lets the bundle heal.+ """+ load_empty_library()+ bundle_path = tmp_path / "target.mthds"+ bundle_path.write_text(_XFILE_TARGET_MTHDS, encoding="utf-8")+ (tmp_path / "sibling.mthds").write_text(_XFILE_SIBLING_OTHER_DOMAIN_MTHDS, encoding="utf-8")++ result = await fix_bundle_file(bundle_path, library_dirs=[tmp_path])++ assert result.is_valid is True+ assert [fix.fix_code for fix in result.fixes_applied] == ["strip-namespace"]+ assert result.bail_reason is None+ parsed = tomlkit.loads(bundle_path.read_text(encoding="utf-8")).unwrap()+ pipes = cast("dict[str, Any]", parsed["pipe"])+ assert "hola" in pipes+ assert "nsfix_xfile.hola" not in pipes+async def test_typoed_main_pipe_tail_is_never_stripped(self,tmp_path: Path,diff --git a/tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.py b/tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.pyindex 38c0ddab6..00515c006 100644--- a/tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.py+++ b/tests/integration/pipelex/pipeline/test_pipeline_run_setup_characterization.py@@ -13,10 +13,10 @@ What is pinned here:does *not* tear down on success — the caller, ``execute``, ownsteardown); exactly one ``PIPELINE_EXECUTE`` telemetry event is emitted; and thepipeline is registered in the pipeline manager.-- **``search_domain_codes`` in-place mutation (trap at the domain-insert block):**- a non-empty caller list is mutated in place — the pipe's domain is inserted at- the front. Pinned so the extraction preserves it consciously (a "pure" builder- would be tempted to copy the list, which would be a behavior change).+- **``search_scope`` derivation:** the concept-shaping scope handed to+ ``prepare_pipe_job`` is derived from the resolved entry pipe (its domain), not+ supplied by the caller — the old caller-supplied ``search_domain_codes`` list+ is gone.- **Empty inputs behave like no inputs:** an empty ``PipelineInputs`` with``mock_inputs=False`` yields an empty working memory, identical to``inputs=None``. This characterizes the end-to-end behavior but does *not*@@ -60,6 +60,7 @@ from pipelex.interpreter_hub import (set_current_library,)from pipelex.libraries.pipe.exceptions import PipeNotFoundError+from pipelex.pipeline import pipeline_run_setup as pipeline_run_setup_modulefrom pipelex.pipeline.pipeline_run_setup import pipeline_run_setupfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.reporting.reporting_manager import ReportingManager@@ -141,18 +142,23 @@ class TestPipelineRunSetupCharacterization:library_manager.teardown(library_id=library_id)clear_current_library()- async def test_search_domain_codes_list_is_mutated_in_place(self) -> None:- caller_domains = ["zzz_other_domain"]+ async def test_search_scope_is_derived_from_the_entry_pipe(self, mocker: MockerFixture) -> None:+ # The concept-shaping scope is the resolved entry pipe's own domain — computed here, not+ # caller-supplied (the old search_domain_codes list parameter is gone).+ seam_spy = mocker.patch.object(+ pipeline_run_setup_module,+ "prepare_pipe_job",+ wraps=pipeline_run_setup_module.prepare_pipe_job,+ )_, _, library_id = await pipeline_run_setup(execution_config=_dry_mock_config(),mthds_contents=[_CHAR_MTHDS],pipe_code="echo_topic",pipe_run_mode=PipeRunMode.DRY,- search_domain_codes=caller_domains,)try:- # The pipe's domain is inserted at the front of the caller's (non-empty) list, in place.- assert caller_domains == [_CHAR_DOMAIN, "zzz_other_domain"]+ assert seam_spy.call_count == 1+ assert seam_spy.call_args.kwargs["search_scope"] == _CHAR_DOMAINfinally:get_library_manager().teardown(library_id=library_id)clear_current_library()diff --git a/tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.py b/tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.pyindex 699e062b0..c8b0c1bec 100644--- a/tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.py+++ b/tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.py@@ -2,7 +2,7 @@The build/inputs/output CLIs and builder operations (``inputs_ops``, ``output_ops``,``runner_code_ops``, ``validate_pipe_in_bundle``) call ``validate_bundle`` (or ``validate_pipes``-directly) and then immediately ``get_required_pipe(...)`` against the library it left open. The+directly) and then immediately ``get_required_entry_pipe(...)`` against the library it left open. Themigration to ``BundleValidator.validate_pipes`` — the public inner sweep, which deliberately nevertears the library down — must preserve this: a sweep that tore the library down on success wouldstrand every one of those callers with ``No current library set`` / ``PipeNotFoundError``.@@ -13,7 +13,7 @@ from __future__ import annotationsimport pytestfrom pipelex.builder.operations.runner_code_ops import build_runner_code_for_pipe-from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_pipe+from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_entry_pipefrom pipelex.pipeline.validate_bundle import validate_bundle_LOADED_DOMAIN = "loaded_on_success"@@ -35,14 +35,14 @@ prompt = "Summarize $doc"@pytest.mark.asyncio(loop_scope="class")class TestValidateBundleLoadedOnSuccess:- async def test_get_required_pipe_works_after_successful_validation(self) -> None:+ async def test_entry_pipe_resolves_after_successful_validation(self) -> None:# The inner sweep never tears down on success: the library stays open + current, so a caller can# resolve the just-validated pipe without re-opening anything.result = await validate_bundle(mthds_contents=[_LOADED_MTHDS])library_id = get_current_library_id_or_none()try:assert library_id is not None, "validate_bundle must leave the library current on success"- pipe = get_required_pipe(pipe_code=f"{_LOADED_DOMAIN}.summarize_doc")+ pipe = get_required_entry_pipe(pipe_code=f"{_LOADED_DOMAIN}.summarize_doc")assert pipe.pipe_ref == f"{_LOADED_DOMAIN}.summarize_doc"assert result.dry_run_result[f"{_LOADED_DOMAIN}.summarize_doc"].status.is_successfinally:diff --git a/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py b/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.pyindex 7ae31b531..ecd713514 100644--- a/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py+++ b/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py@@ -185,6 +185,13 @@ class TestValidateBundleStructuredErrors:self,load_empty_library: Callable[[], str],) -> None:+ """`missing_pipe_code` names the ref that was actually tried — the QUALIFIED one.++ The author wrote `second_step_missing`; the compiler read it as+ `structured_missing_dep.second_step_missing`, because a bare ref names its own domain. Reporting+ the bare spelling back would hide the only interesting part. This field is a structured field+ machine consumers read, so its value changing is a wire-visible change, not a cosmetic one.+ """load_empty_library()items = await _validation_errors_for(_MISSING_DEPENDENCY_MTHDS)dependency_items = [item for item in items if item.error_type == PipeValidationErrorType.UNRESOLVED_PIPE_DEPENDENCY]@@ -192,8 +199,11 @@ class TestValidateBundleStructuredErrors:item = dependency_items[0]assert item.category == ValidationErrorCategory.PIPE_VALIDATIONassert item.pipe_code == "do_two_steps"- assert item.missing_pipe_code == "second_step_missing"- assert "second_step_missing" in item.message+ assert item.missing_pipe_code == "structured_missing_dep.second_step_missing"+ # The message has to bridge the gap between what they wrote and what was tried, or it names a+ # pipe that appears nowhere in their file and reads like a compiler bug.+ assert "structured_missing_dep.second_step_missing" in item.message+ assert "own domain" in item.messageasync def test_unknown_pipe_type_is_a_categorized_blueprint_item(self,diff --git a/tests/integration/pipelex/pipes/controller/pipe_batch/cross_domain_output.mthds b/tests/integration/pipelex/pipes/controller/pipe_batch/cross_domain_output.mthdsnew file mode 100644index 000000000..6b550b45a--- /dev/null+++ b/tests/integration/pipelex/pipes/controller/pipe_batch/cross_domain_output.mthds@@ -0,0 +1,17 @@+domain = "test_integration_batch_xdom"+description = "A pipe whose output concept lives in ANOTHER domain, for the ad-hoc batch output test"++[pipe]++[pipe.cross_domain_reporter]+type = "PipeLLM"+description = "Produce an uppercase report typed by a concept from a sibling domain"+inputs = { text_item = "Text" }+output = "test_integration1.UppercaseText"+prompt = """+Transform the following text to uppercase:++@text_item++Just return the transformed text, nothing else.+"""diff --git a/tests/integration/pipelex/pipes/controller/pipe_batch/test_batch_adhoc_pipe_ref.py b/tests/integration/pipelex/pipes/controller/pipe_batch/test_batch_adhoc_pipe_ref.pynew file mode 100644index 000000000..617f07263--- /dev/null+++ b/tests/integration/pipelex/pipes/controller/pipe_batch/test_batch_adhoc_pipe_ref.py@@ -0,0 +1,139 @@+"""The ad-hoc PipeBatch that `batch_over` synthesizes derives its code from the LOCAL code.++`SubPipe.pipe_code` is an in-body reference, so it is qualified (`domain.foo`), while+`PipeFactory.make_from_blueprint` takes `domain_code` separately. Suffixing the qualified ref hands+the factory `domain.foo_batch` as a *code*.++That does not corrupt the resulting ref, and it is worth being precise about why: `PipeAbstract` has a+`code` validator that strips a namespace prefix, so the built pipe ends up correct either way. What+the wrong derivation produces is a `log.warning` on **every batched run** — a permanent false alarm+telling the user their pipe code has a namespace prefix, about a code no user wrote.++So this test asserts on the warning, not on the ref: the ref is identical under both derivations, and+a test that asserted on it would pass against the bug it was written to catch.+"""++from collections.abc import Callable+from pathlib import Path+from typing import Any++import pytest+from pytest_mock import MockerFixture++from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory+from pipelex.core.stuffs.list_content import ListContent+from pipelex.core.stuffs.stuff_factory import StuffFactory+from pipelex.core.stuffs.text_content import TextContent+from pipelex.interpreter_hub import get_required_entry_pipe+from pipelex.pipe_controllers.sub_pipe import SubPipe+from pipelex.pipe_run.pipe_job_factory import PipeJobFactory+from pipelex.pipe_run.pipe_run_params import BatchParams+from pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactory+from pipelex.system.job_metadata import JobMetadata+from pipelex.system.pipe_run_mode import PipeRunMode++[email protected]_runnable[email protected](loop_scope="class")+class TestBatchAdhocPipeRef:+ async def test_batching_a_qualified_sub_pipe_warns_about_nothing(+ self,+ caplog: pytest.LogCaptureFixture,+ mocker: MockerFixture,+ job_metadata: JobMetadata,+ load_test_library: Callable[[list[Path]], None],+ ):+ load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_batch")])++ branch_pipe = get_required_entry_pipe(pipe_code="uppercase_transformer")+ item_spec = branch_pipe.inputs.get_required_stuff_spec(variable_name="text_item")+ items_stuff = StuffFactory.make_stuff(+ concept=item_spec.concept,+ content=ListContent[TextContent](items=[TextContent(text="one"), TextContent(text="two")]),+ name="texts",+ )+ working_memory = WorkingMemoryFactory.make_from_single_stuff(stuff=items_stuff)++ # The synthesized batch pipe is never registered anywhere and never returned, so the only way+ # to read its ref is to intercept the job it is handed to.+ captured: list[Any] = []+ real_make_pipe_job = PipeJobFactory.make_pipe_job++ def capture(**kwargs: Any) -> Any:+ captured.append(kwargs["pipe"])+ return real_make_pipe_job(**kwargs)++ mocker.patch.object(PipeJobFactory, "make_pipe_job", side_effect=capture)++ sub_pipe = SubPipe(+ pipe_code=branch_pipe.pipe_ref,+ output_name="uppercased",+ batch_params=BatchParams(input_list_stuff_name="texts", input_item_stuff_name="text_item"),+ )+ with caplog.at_level("WARNING", logger="pipelex"):+ await sub_pipe.run_pipe(+ calling_pipe_code="test_caller",+ working_memory=working_memory,+ job_metadata=job_metadata,+ sub_pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),+ )++ assert captured, "SubPipe did not build a batch job"+ batch_pipe = captured[0]+ assert batch_pipe.code == "uppercase_transformer_batch"+ assert batch_pipe.pipe_ref == "test_integration1.uppercase_transformer_batch"++ # The discriminating assertion. Deriving from the qualified ref hands the factory+ # `test_integration1.uppercase_transformer_batch` as a code; the `PipeAbstract.code` validator+ # strips it back and warns — every batched run, about a code the user never wrote.+ assert "namespace prefix" not in caplog.text++ async def test_batching_a_pipe_with_a_cross_domain_output_keeps_the_output_concept(+ self,+ mocker: MockerFixture,+ job_metadata: JobMetadata,+ load_test_library: Callable[[list[Path]], None],+ ):+ """The ad-hoc batch blueprint carries the output as a full concept_ref, not a bare code.++ The blueprint is built with the sub-pipe's own ``domain_code``, so a bare output code would+ be re-resolved in that domain — a `StuffSpecFactoryError` when the concept only exists in+ the sibling domain, or silently the WRONG concept when the sub-pipe's domain happens to+ declare the same code. This test reddens under `output=sub_pipe.output.concept.code`.+ """+ load_test_library([Path("tests/integration/pipelex/pipes/controller/pipe_batch")])++ branch_pipe = get_required_entry_pipe(pipe_code="cross_domain_reporter")+ item_spec = branch_pipe.inputs.get_required_stuff_spec(variable_name="text_item")+ items_stuff = StuffFactory.make_stuff(+ concept=item_spec.concept,+ content=ListContent[TextContent](items=[TextContent(text="one"), TextContent(text="two")]),+ name="texts",+ )+ working_memory = WorkingMemoryFactory.make_from_single_stuff(stuff=items_stuff)++ captured: list[Any] = []+ real_make_pipe_job = PipeJobFactory.make_pipe_job++ def capture(**kwargs: Any) -> Any:+ captured.append(kwargs["pipe"])+ return real_make_pipe_job(**kwargs)++ mocker.patch.object(PipeJobFactory, "make_pipe_job", side_effect=capture)++ sub_pipe = SubPipe(+ pipe_code=branch_pipe.pipe_ref,+ output_name="reported",+ batch_params=BatchParams(input_list_stuff_name="texts", input_item_stuff_name="text_item"),+ )+ await sub_pipe.run_pipe(+ calling_pipe_code="test_caller",+ working_memory=working_memory,+ job_metadata=job_metadata,+ sub_pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=PipeRunMode.DRY),+ )++ assert captured, "SubPipe did not build a batch job"+ batch_pipe = captured[0]+ assert batch_pipe.output.concept.concept_ref == "test_integration1.UppercaseText"diff --git a/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_branch_dispatch.py b/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_branch_dispatch.pyindex 9ba0ce58a..4e1e779b5 100644--- a/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_branch_dispatch.py+++ b/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_branch_dispatch.py@@ -79,7 +79,9 @@ def _build_batch() -> PipeBatch:pipe_code="branch_dispatch_batch",blueprint=PipeBatchBlueprint(description="Batch the shout over the items",- branch_pipe_code="branch_dispatch_shout",+ # Domain-qualified: this blueprint is hand-built, so it never goes through the crate+ # qualification pass, and `branch_pipe_code` is an in-body ref — the strict lookup.+ branch_pipe_code=f"{_DOMAIN_CODE}.branch_dispatch_shout",output="Text",input_list_name="items",input_item_name="item",diff --git a/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_compaction.py b/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_compaction.pyindex 02f2edd63..8582c6c9f 100644--- a/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_compaction.py+++ b/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_compaction.py@@ -70,7 +70,7 @@ def _build_compacting_batch() -> PipeBatch:inputs={"item": "Text"},output="Text?",expression_template="{% if item.text.startswith('good') %}keep{% else %}reject{% endif %}",- outcomes={"keep": "opt_batch_shout"},+ outcomes={"keep": "test_optionals_batch.opt_batch_shout"},default_outcome=SpecialOutcome.CONTINUE,),)@@ -83,7 +83,7 @@ def _build_compacting_batch() -> PipeBatch:pipe_code="opt_batch_compact",blueprint=PipeBatchBlueprint(description="Batch the gate over the items",- branch_pipe_code="opt_batch_gate",+ branch_pipe_code="test_optionals_batch.opt_batch_gate",output="Text",input_list_name="items",input_item_name="item",diff --git a/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_simple.py b/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_simple.pyindex df9cbd5cd..3d10c1bb1 100644--- a/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_simple.py+++ b/tests/integration/pipelex/pipes/controller/pipe_batch/test_pipe_batch_simple.py@@ -50,7 +50,7 @@ class TestPipeBatchSimple:pipe_batch_blueprint = PipeBatchBlueprint(description="Simple batch processing test",- branch_pipe_code="uppercase_transformer", # This exists in the MTHDS file+ branch_pipe_code="test_integration1.uppercase_transformer", # This exists in the MTHDS fileinputs={"text_list": concept_1.concept_ref,},@@ -84,7 +84,7 @@ class TestPipeBatchSimple:assert pipe_batch is not Noneassert pipe_batch.domain_code == domain_codeassert pipe_batch.code == "simple_batch"- assert pipe_batch.branch_pipe_code == "uppercase_transformer"+ assert pipe_batch.branch_pipe_code == "test_integration1.uppercase_transformer"assert pipe_batch.batch_params is not Noneassert pipe_batch.batch_params.input_list_stuff_name == "text_list"assert pipe_batch.batch_params.input_item_stuff_name == "text_item"diff --git a/tests/integration/pipelex/pipes/controller/pipe_batch_dotted_path/test_dotted_batch.py b/tests/integration/pipelex/pipes/controller/pipe_batch_dotted_path/test_dotted_batch.pyindex ce86b18bc..1763d5247 100644--- a/tests/integration/pipelex/pipes/controller/pipe_batch_dotted_path/test_dotted_batch.py+++ b/tests/integration/pipelex/pipes/controller/pipe_batch_dotted_path/test_dotted_batch.py@@ -13,7 +13,7 @@ from pipelex.core.stuffs.document_content import DocumentContentfrom pipelex.core.stuffs.search_result_content import SearchResultContentfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.interpreter_hub import get_required_pipe+from pipelex.interpreter_hub import get_required_entry_pipefrom pipelex.pipe_controllers.sub_pipe import SubPipefrom pipelex.pipe_run.pipe_run_params import BatchParamsfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactory@@ -60,9 +60,10 @@ class TestDottedBatchOver:)working_memory = WorkingMemoryFactory.make_from_single_stuff(stuff=search_result_stuff)- # Build SubPipe with dotted-path batch_params+ # Build SubPipe with dotted-path batch_params. `pipe_code` on a SubPipe is an in-body ref, so+ # it carries the domain — this is what the crate qualification pass produces for a built pipe.sub_pipe = SubPipe(- pipe_code="process_document",+ pipe_code="dotted_batch_test.process_document",output_name="processed_docs",batch_params=BatchParams(input_list_stuff_name="search_result.sources",@@ -71,7 +72,7 @@ class TestDottedBatchOver:)# Get the branch pipe to verify it exists- branch_pipe = get_required_pipe(pipe_code="process_document")+ branch_pipe = get_required_entry_pipe(pipe_code="process_document")log.info(f"Branch pipe: {branch_pipe.code}, inputs: {branch_pipe.inputs}")# Run SubPipediff --git a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.py b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.pyindex fe13224be..63dc0e349 100644--- a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.py+++ b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_complex.py@@ -12,7 +12,7 @@ from pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.pipes.inputs.exceptions import PipeRunInputsErrorfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.interpreter_hub import get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_pipe_router, get_required_entry_pipefrom pipelex.pipe_run.exceptions import PipeRouterErrorfrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactory@@ -64,7 +64,7 @@ class TestPipeConditionComplex:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="complex_document_processor"),+ pipe=get_required_entry_pipe(pipe_code="complex_document_processor"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -115,7 +115,7 @@ class TestPipeConditionComplex:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="complex_document_processor"),+ pipe=get_required_entry_pipe(pipe_code="complex_document_processor"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -163,7 +163,7 @@ class TestPipeConditionComplex:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="complex_document_processor"),+ pipe=get_required_entry_pipe(pipe_code="complex_document_processor"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -219,7 +219,7 @@ class TestPipeConditionComplex:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="complex_document_processor"),+ pipe=get_required_entry_pipe(pipe_code="complex_document_processor"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -268,7 +268,7 @@ class TestPipeConditionComplex:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="complex_document_processor"),+ pipe=get_required_entry_pipe(pipe_code="complex_document_processor"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -303,7 +303,7 @@ class TestPipeConditionComplex:with pytest.raises(PipeRouterError) as exc_info:await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="complex_document_processor"),+ pipe=get_required_entry_pipe(pipe_code="complex_document_processor"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -385,7 +385,7 @@ class TestPipeConditionComplex:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="complex_document_processor"),+ pipe=get_required_entry_pipe(pipe_code="complex_document_processor"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,diff --git a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_continue_output_type.py b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_continue_output_type.pyindex efead687b..6c51482ec 100644--- a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_continue_output_type.py+++ b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_continue_output_type.py@@ -19,7 +19,7 @@ from pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.stuff_factory import StuffFactory-from pipelex.interpreter_hub import get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_pipe_router, get_required_entry_pipefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.system.job_metadata import JobMetadata@@ -82,7 +82,7 @@ class TestPipeConditionContinueOutputType:# Run the batch pipepipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="process_verified_links"),+ pipe=get_required_entry_pipe(pipe_code="process_verified_links"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,diff --git a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.py b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.pyindex 7019109e2..93301feff 100644--- a/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.py+++ b/tests/integration/pipelex/pipes/controller/pipe_condition/test_pipe_condition_simple.py@@ -11,7 +11,7 @@ from pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.pipes.inputs.exceptions import PipeRunInputsErrorfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.interpreter_hub import get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_pipe_router, get_required_entry_pipefrom pipelex.pipe_controllers.condition.pipe_condition import PipeConditionfrom pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprintfrom pipelex.pipe_controllers.condition.special_outcome import SpecialOutcome@@ -38,7 +38,7 @@ class TestPipeConditionSimple:inputs={"input_text": f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}"},output=f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}?",expression_template="{% if input_text.text|length > 5 %}long{% else %}short{% endif %}",- outcomes={"long": "capitalize_long_text", "short": "add_prefix_short_text"},+ outcomes={"long": "test_integration2.capitalize_long_text", "short": "test_integration2.add_prefix_short_text"},default_outcome=SpecialOutcome.CONTINUE,)@@ -57,7 +57,10 @@ class TestPipeConditionSimple:assert pipe_condition.domain_code == "test_integration"assert pipe_condition.code == "text_length_condition"- assert pipe_condition.outcome_map == {"long": "capitalize_long_text", "short": "add_prefix_short_text"}+ assert pipe_condition.outcome_map == {+ "long": "test_integration2.capitalize_long_text",+ "short": "test_integration2.add_prefix_short_text",+ }input_text = working_memory.get_stuff("input_text")assert input_text is not None@@ -114,7 +117,7 @@ class TestPipeConditionSimple:inputs={"input_text": f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}"},output=f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}?",expression_template="{% if input_text.text|length > 5 %}long{% else %}short{% endif %}",- outcomes={"long": "capitalize_long_text", "short": "add_prefix_short_text"},+ outcomes={"long": "test_integration2.capitalize_long_text", "short": "test_integration2.add_prefix_short_text"},default_outcome=SpecialOutcome.CONTINUE,)@@ -202,7 +205,7 @@ class TestPipeConditionSimple:# Run dry run using the real pipe - this should succeedpipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="basic_condition_by_category_2"),+ pipe=get_required_entry_pipe(pipe_code="basic_condition_by_category_2"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -240,7 +243,7 @@ class TestPipeConditionSimple:with pytest.raises(PipeRouterError) as exc_info:await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="basic_condition_by_category_2"),+ pipe=get_required_entry_pipe(pipe_code="basic_condition_by_category_2"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=empty_working_memory,job_metadata=job_metadata,@@ -281,7 +284,7 @@ class TestPipeConditionSimple:# Run dry run using the real pipe - this should succeed and validate the 'medium' branchpipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="basic_condition_by_category_2"),+ pipe=get_required_entry_pipe(pipe_code="basic_condition_by_category_2"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,diff --git a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_absence.py b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_absence.pyindex 1712ecf2d..15f17f41b 100644--- a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_absence.py+++ b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_absence.py@@ -120,8 +120,8 @@ def _build_parallel(*, output_ref: str, structure_class_names: list[str], add_eainputs={"source": "Text?", "topic": "Text"},output=output_ref,branches=[- SubPipeBlueprint(pipe="opt_par_find", result="found_result"),- SubPipeBlueprint(pipe="opt_par_base", result="base_result"),+ SubPipeBlueprint(pipe="test_optionals_par.opt_par_find", result="found_result"),+ SubPipeBlueprint(pipe="test_optionals_par.opt_par_base", result="base_result"),],add_each_output=add_each_output,),diff --git a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_branch_type_validation.py b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_branch_type_validation.pyindex 763353d62..bd010e417 100644--- a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_branch_type_validation.py+++ b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_branch_type_validation.py@@ -89,8 +89,8 @@ class TestPipeParallelBranchTypeValidation:inputs={"input_text": "Text"},output=f"{DOMAIN_CODE}.BtvCombinedResult",branches=[- SubPipeBlueprint(pipe="btv_summarize", result="summary"),- SubPipeBlueprint(pipe="btv_scoring", result="score"),+ SubPipeBlueprint(pipe=f"{DOMAIN_CODE}.btv_summarize", result="summary"),+ SubPipeBlueprint(pipe=f"{DOMAIN_CODE}.btv_scoring", result="score"),],),concept_codes_from_the_same_domain=["BtvSummary", "BtvScore", "BtvCombinedResult"],diff --git a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_final_stuff_code.py b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_final_stuff_code.pyindex f8a673226..d731245b0 100644--- a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_final_stuff_code.py+++ b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_final_stuff_code.py@@ -40,8 +40,8 @@ class TestPipeParallelFinalStuffCode:inputs={"input_text": f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}"},output=f"{SpecialDomain.NATIVE}.{NativeConceptCode.COMPOSITE}",branches=[- SubPipeBlueprint(pipe="analyze_sentiment", result="sentiment_result"),- SubPipeBlueprint(pipe="count_words", result="word_count_result"),+ SubPipeBlueprint(pipe="test_integration3.analyze_sentiment", result="sentiment_result"),+ SubPipeBlueprint(pipe="test_integration3.count_words", result="word_count_result"),],add_each_output=True,)diff --git a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_simple.py b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_simple.pyindex 71eac4213..18e0ec221 100644--- a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_simple.py+++ b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_simple.py@@ -34,9 +34,9 @@ class TestPipeParallelSimple:inputs={"input_text": f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}"},output=f"{SpecialDomain.NATIVE}.{NativeConceptCode.COMPOSITE}",branches=[- SubPipeBlueprint(pipe="analyze_sentiment", result="sentiment_result"),- SubPipeBlueprint(pipe="count_words", result="word_count_result"),- SubPipeBlueprint(pipe="extract_keywords", result="keywords_result"),+ SubPipeBlueprint(pipe="test_integration3.analyze_sentiment", result="sentiment_result"),+ SubPipeBlueprint(pipe="test_integration3.count_words", result="word_count_result"),+ SubPipeBlueprint(pipe="test_integration3.extract_keywords", result="keywords_result"),],add_each_output=True,)@@ -63,11 +63,11 @@ class TestPipeParallelSimple:assert pipe_parallel.add_each_output is True# Verify sub-pipes configuration- assert pipe_parallel.parallel_sub_pipes[0].pipe_code == "analyze_sentiment"+ assert pipe_parallel.parallel_sub_pipes[0].pipe_code == "test_integration3.analyze_sentiment"assert pipe_parallel.parallel_sub_pipes[0].output_name == "sentiment_result"- assert pipe_parallel.parallel_sub_pipes[1].pipe_code == "count_words"+ assert pipe_parallel.parallel_sub_pipes[1].pipe_code == "test_integration3.count_words"assert pipe_parallel.parallel_sub_pipes[1].output_name == "word_count_result"- assert pipe_parallel.parallel_sub_pipes[2].pipe_code == "extract_keywords"+ assert pipe_parallel.parallel_sub_pipes[2].pipe_code == "test_integration3.extract_keywords"assert pipe_parallel.parallel_sub_pipes[2].output_name == "keywords_result"# Verify the working memory has the correct structure@@ -152,9 +152,9 @@ class TestPipeParallelSimple:inputs={"input_text": f"{SpecialDomain.NATIVE}.{NativeConceptCode.TEXT}"},output=f"{SpecialDomain.NATIVE}.{NativeConceptCode.COMPOSITE}",branches=[- SubPipeBlueprint(pipe="analyze_sentiment", result="sentiment_result"),- SubPipeBlueprint(pipe="count_words", result="word_count_result"),- SubPipeBlueprint(pipe="extract_keywords", result="keywords_result"),+ SubPipeBlueprint(pipe="test_integration3.analyze_sentiment", result="sentiment_result"),+ SubPipeBlueprint(pipe="test_integration3.count_words", result="word_count_result"),+ SubPipeBlueprint(pipe="test_integration3.extract_keywords", result="keywords_result"),],add_each_output=True,)diff --git a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_unresolvable_structure_class.py b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_unresolvable_structure_class.pyindex 84a01c9b2..374be481c 100644--- a/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_unresolvable_structure_class.py+++ b/tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_unresolvable_structure_class.py@@ -68,7 +68,7 @@ class TestPipeParallelUnresolvableStructureClass:inputs={"input_text": "Text"},output=f"{DOMAIN_CODE}.{output_concept_code}",branches=[- SubPipeBlueprint(pipe="usc_branch", result="summary"),+ SubPipeBlueprint(pipe="test_usc.usc_branch", result="summary"),],),concept_codes_from_the_same_domain=[output_concept_code, branch_output_concept_code],diff --git a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.pyindex 6f4c9a485..c5a44e2e1 100644--- a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py+++ b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_dry_run.py@@ -9,7 +9,7 @@ from pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.stuff import Stufffrom pipelex.core.stuffs.stuff_factory import StuffFactory-from pipelex.interpreter_hub import get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_pipe_router, get_required_entry_pipefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.system.job_metadata import JobMetadata@@ -59,7 +59,7 @@ class TestPipeSequenceDryRun:# Run the Discord newsletter pipeline in dry run modepipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="write_discord_newsletter"),+ pipe=get_required_entry_pipe(pipe_code="write_discord_newsletter"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,diff --git a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_list_output_bug.py b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_list_output_bug.pyindex efb863e32..7c6eca8df 100644--- a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_list_output_bug.py+++ b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_list_output_bug.py@@ -13,7 +13,7 @@ from typing import ClassVarimport pytest-from pipelex.interpreter_hub import get_current_library, get_required_pipe+from pipelex.interpreter_hub import get_current_library, get_required_entry_pipefrom pipelex.pipeline.bundle_validator import BundleValidatorfrom pipelex.pipeline.validate_bundle import validate_bundle@@ -99,7 +99,7 @@ class TestPipeSequenceListOutputBug:assert len(result.pipes) > 0# Get the main sequence pipe (without domain prefix since it's loaded into the library)- main_sequence = get_required_pipe("main_sequence")+ main_sequence = get_required_entry_pipe("main_sequence")# Run dry run - this should NOT fail# BUG: Currently fails with "Content of 'items' is of type 'Item', it should be 'ListContent'"@@ -128,7 +128,7 @@ class TestPipeSequenceListOutputBug:)# Get the generate_items pipe (without domain prefix since it's loaded into the library)- generate_items_pipe = get_required_pipe("generate_items")+ generate_items_pipe = get_required_entry_pipe("generate_items")# Verify the pipe has the correct output multiplicityassert generate_items_pipe.output.multiplicity is True, (@@ -267,7 +267,7 @@ class TestNestedPipeSequenceListOutputBug:assert len(result.pipes) > 0# Get the main sequence pipe- main_sequence = get_required_pipe("generate_expense_dataset")+ main_sequence = get_required_entry_pipe("generate_expense_dataset")# Run dry run - this should NOT fail# BUG: Currently may fail with "Content of 'expenses' is of type 'Expense', it should be 'ListContent'"@@ -292,7 +292,7 @@ class TestNestedPipeSequenceListOutputBug:)# Get the inner sequence pipe- inner_sequence = get_required_pipe("generate_employee_report")+ inner_sequence = get_required_entry_pipe("generate_employee_report")# Run dry run on the inner sequencedry_run_results = await BundleValidator().validate_pipes([inner_sequence], library_id=get_current_library())diff --git a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_output_multiplicity.py b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_output_multiplicity.pyindex c56e15663..e29c4906e 100644--- a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_output_multiplicity.py+++ b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_output_multiplicity.py@@ -53,7 +53,7 @@ class TestPipeSequenceOutputMultiplicity:inputs={"input_text": "Text"},output="Text", # Single output - MISMATCH!steps=[- SubPipeBlueprint(pipe="llm_multiple_output", result="result"),+ SubPipeBlueprint(pipe=f"{domain_code}.llm_multiple_output", result="result"),],)sequence_pipe = PipeFactory[PipeSequence].make_from_blueprint(@@ -113,7 +113,7 @@ class TestPipeSequenceOutputMultiplicity:inputs={"input_text": "Text"},output="Text", # Single output - MATCHES!steps=[- SubPipeBlueprint(pipe="llm_single_output", result="result"),+ SubPipeBlueprint(pipe=f"{domain_code}.llm_single_output", result="result"),],)sequence_pipe = PipeFactory[PipeSequence].make_from_blueprint(@@ -162,7 +162,7 @@ class TestPipeSequenceOutputMultiplicity:inputs={"input_text": "Text"},output="Text[]", # Variable multiplicity - MATCHES!steps=[- SubPipeBlueprint(pipe="llm_variable_output", result="result"),+ SubPipeBlueprint(pipe=f"{domain_code}.llm_variable_output", result="result"),],)sequence_pipe = PipeFactory[PipeSequence].make_from_blueprint(@@ -211,7 +211,7 @@ class TestPipeSequenceOutputMultiplicity:inputs={"input_text": "Text"},output="Text", # No multiplicity - MISMATCH!steps=[- SubPipeBlueprint(pipe="llm_variable", result="result"),+ SubPipeBlueprint(pipe=f"{domain_code}.llm_variable", result="result"),],)sequence_pipe = PipeFactory[PipeSequence].make_from_blueprint(@@ -267,7 +267,7 @@ class TestPipeSequenceOutputMultiplicity:inputs={"input_text": "Text"},output="Text[]", # Variable multiplicity - compatible with fixedsteps=[- SubPipeBlueprint(pipe="llm_fixed_3", result="result"),+ SubPipeBlueprint(pipe=f"{domain_code}.llm_fixed_3", result="result"),],)sequence_pipe = PipeFactory[PipeSequence].make_from_blueprint(@@ -318,7 +318,7 @@ class TestPipeSequenceOutputMultiplicity:inputs={"input_text": "Text"},output="Text[3]", # Fixed multiplicity - cannot be fulfilled by variablesteps=[- SubPipeBlueprint(pipe="llm_variable", result="result"),+ SubPipeBlueprint(pipe=f"{domain}.llm_variable", result="result"),],)sequence_pipe = PipeFactory[PipeSequence].make_from_blueprint(@@ -375,7 +375,7 @@ class TestPipeSequenceOutputMultiplicity:output="Text[]", # Variable multiplicity output - should match batch_over effectsteps=[SubPipeBlueprint(- pipe="process_cv",+ pipe=f"{domain}.process_cv",result="match_analyses",batch_over="cvs",batch_as="cv_pdf",@@ -432,7 +432,7 @@ class TestPipeSequenceOutputMultiplicity:output="Text", # No multiplicity - MISMATCH with batch effect!steps=[SubPipeBlueprint(- pipe="process_cv_single",+ pipe=f"{domain}.process_cv_single",result="match_analyses",batch_over="cvs",batch_as="cv_pdf",@@ -493,7 +493,7 @@ class TestPipeSequenceOutputMultiplicity:output="Text[6]", # Fixed multiplicity - should match nb_outputsteps=[SubPipeBlueprint(- pipe="process_cv_fixed",+ pipe=f"{domain}.process_cv_fixed",result="match_analyses",batch_over="cvs",batch_as="cv_pdf",@@ -548,7 +548,7 @@ class TestPipeSequenceOutputMultiplicity:output="Text[5]", # Fixed multiplicity - should match nb_outputsteps=[SubPipeBlueprint(- pipe="single_output_llm",+ pipe=f"{domain}.single_output_llm",result="results",nb_output=5, # Fixed output count, no batch_over/batch_as),@@ -601,7 +601,7 @@ class TestPipeSequenceOutputMultiplicity:output="Text[]", # Variable multiplicity - should match multiple_output=Truesteps=[SubPipeBlueprint(- pipe="single_output_llm_mult",+ pipe=f"{domain}.single_output_llm_mult",result="results",multiple_output=True, # Variable output, no nb_output, no batch_over/batch_as),diff --git a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_simple.py b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_simple.pyindex 777be12e9..0f359ff83 100644--- a/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_simple.py+++ b/tests/integration/pipelex/pipes/controller/pipe_sequence/test_pipe_sequence_simple.py@@ -47,8 +47,8 @@ class TestPipeSequenceSimple:inputs={"input_text": concept_1.concept_ref},output=concept_2.concept_ref,steps=[- SubPipeBlueprint(pipe="capitalize_text", result="capitalized_text"),- SubPipeBlueprint(pipe="add_prefix", result="final_text"),+ SubPipeBlueprint(pipe="test_integration4.capitalize_text", result="capitalized_text"),+ SubPipeBlueprint(pipe="test_integration4.add_prefix", result="final_text"),],)@@ -72,9 +72,9 @@ class TestPipeSequenceSimple:assert pipe_sequence.domain_code == "test_integration"assert pipe_sequence.code == "simple_sequence"assert len(pipe_sequence.sequential_sub_pipes) == 2- assert pipe_sequence.sequential_sub_pipes[0].pipe_code == "capitalize_text"+ assert pipe_sequence.sequential_sub_pipes[0].pipe_code == "test_integration4.capitalize_text"assert pipe_sequence.sequential_sub_pipes[0].output_name == "capitalized_text"- assert pipe_sequence.sequential_sub_pipes[1].pipe_code == "add_prefix"+ assert pipe_sequence.sequential_sub_pipes[1].pipe_code == "test_integration4.add_prefix"assert pipe_sequence.sequential_sub_pipes[1].output_name == "final_text"# Verify the working memory has the correct structurediff --git a/tests/integration/pipelex/pipes/llm_prompt_inputs/test_image_inputs_inference.py b/tests/integration/pipelex/pipes/llm_prompt_inputs/test_image_inputs_inference.pyindex 456436aff..5f7b33f03 100644--- a/tests/integration/pipelex/pipes/llm_prompt_inputs/test_image_inputs_inference.py+++ b/tests/integration/pipelex/pipes/llm_prompt_inputs/test_image_inputs_inference.py@@ -14,7 +14,7 @@ from pipelex.core.stuffs.page_content import PageContentfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_and_images_content import TextAndImagesContentfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.interpreter_hub import get_native_concept, get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_native_concept, get_pipe_router, get_required_entry_pipefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.system.job_metadata import JobMetadata@@ -49,7 +49,7 @@ class TestImageInputsInference:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="extract_article_from_image"),+ pipe=get_required_entry_pipe(pipe_code="extract_article_from_image"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -92,7 +92,7 @@ class TestImageInputsInference:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="describe_page"),+ pipe=get_required_entry_pipe(pipe_code="describe_page"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -136,7 +136,7 @@ class TestImageInputsInference:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="analyze_image_collection"),+ pipe=get_required_entry_pipe(pipe_code="analyze_image_collection"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -187,7 +187,7 @@ class TestImageInputsInference:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="compare_two_image_collections"),+ pipe=get_required_entry_pipe(pipe_code="compare_two_image_collections"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -223,7 +223,7 @@ class TestImageInputsInference:pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="describe_image"),+ pipe=get_required_entry_pipe(pipe_code="describe_image"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,diff --git a/tests/integration/pipelex/pipes/operator/pipe_structure/test_pipe_structure_in_batch.py b/tests/integration/pipelex/pipes/operator/pipe_structure/test_pipe_structure_in_batch.pyindex f4d935236..ee3ec90fd 100644--- a/tests/integration/pipelex/pipes/operator/pipe_structure/test_pipe_structure_in_batch.py+++ b/tests/integration/pipelex/pipes/operator/pipe_structure/test_pipe_structure_in_batch.py@@ -55,7 +55,7 @@ class TestPipeStructureInBatch:batch_blueprint = PipeBatchBlueprint(description="Run PipeStructure over a list of free-form review texts",- branch_pipe_code="structure_one_restaurant_review",+ branch_pipe_code="test_pipe_structure_seq.structure_one_restaurant_review",inputs={"review_texts": NativeConceptCode.TEXT},output="RestaurantReview",input_list_name="review_texts",diff --git a/tests/integration/pipelex/pipes/operator/pipe_structure/test_pipe_structure_in_sequence.py b/tests/integration/pipelex/pipes/operator/pipe_structure/test_pipe_structure_in_sequence.pyindex 3cf98dda6..251464e21 100644--- a/tests/integration/pipelex/pipes/operator/pipe_structure/test_pipe_structure_in_sequence.py+++ b/tests/integration/pipelex/pipes/operator/pipe_structure/test_pipe_structure_in_sequence.py@@ -58,8 +58,8 @@ class TestPipeStructureInSequence:inputs={"restaurant_brief": NativeConceptCode.TEXT},output="RestaurantReview",steps=[- SubPipeBlueprint(pipe="draft_restaurant_review_text", result="draft_text"),- SubPipeBlueprint(pipe="structure_restaurant_review", result="restaurant_review"),+ SubPipeBlueprint(pipe="test_pipe_structure_seq.draft_restaurant_review_text", result="draft_text"),+ SubPipeBlueprint(pipe="test_pipe_structure_seq.structure_restaurant_review", result="restaurant_review"),],)sequence_pipe = PipeFactory[PipeSequence].make_from_blueprint(diff --git a/tests/integration/pipelex/pipes/operator/pipe_structure/test_preliminary_text_e2e.py b/tests/integration/pipelex/pipes/operator/pipe_structure/test_preliminary_text_e2e.pyindex c7e30376c..d85685cf9 100644--- a/tests/integration/pipelex/pipes/operator/pipe_structure/test_preliminary_text_e2e.py+++ b/tests/integration/pipelex/pipes/operator/pipe_structure/test_preliminary_text_e2e.py@@ -10,7 +10,7 @@ from pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.interpreter_hub import get_native_concept, get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_native_concept, get_pipe_router, get_required_entry_pipefrom pipelex.pipe_controllers.sequence.pipe_sequence import PipeSequencefrom pipelex.pipe_operators.structure.pipe_structure import PipeStructurefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactory@@ -93,13 +93,13 @@ class TestPreliminaryTextE2E:) -> None:load_test_library([Path("tests/integration/pipelex/pipes/operator/pipe_structure")])- user_facing_pipe = get_required_pipe(pipe_code=pipe_code)+ user_facing_pipe = get_required_entry_pipe(pipe_code=pipe_code)assert isinstance(user_facing_pipe, PipeSequence)assert len(user_facing_pipe.sequential_sub_pipes) == 2- assert user_facing_pipe.sequential_sub_pipes[0].pipe_code == f"{pipe_code}__draft_text"- assert user_facing_pipe.sequential_sub_pipes[1].pipe_code == f"{pipe_code}__structure"+ assert user_facing_pipe.sequential_sub_pipes[0].pipe_code == f"test_preliminary_text_e2e.{pipe_code}__draft_text"+ assert user_facing_pipe.sequential_sub_pipes[1].pipe_code == f"test_preliminary_text_e2e.{pipe_code}__structure"- structure_step = get_required_pipe(pipe_code=f"{pipe_code}__structure")+ structure_step = get_required_entry_pipe(pipe_code=f"{pipe_code}__structure")assert isinstance(structure_step, PipeStructure)working_memory = WorkingMemoryFactory.make_from_single_stuff(diff --git a/tests/integration/pipelex/pipes/operator/pipe_structure/test_preliminary_text_inline_e2e.py b/tests/integration/pipelex/pipes/operator/pipe_structure/test_preliminary_text_inline_e2e.pyindex 4d823b655..60cc071ac 100644--- a/tests/integration/pipelex/pipes/operator/pipe_structure/test_preliminary_text_inline_e2e.py+++ b/tests/integration/pipelex/pipes/operator/pipe_structure/test_preliminary_text_inline_e2e.py@@ -11,7 +11,7 @@ from pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.stuffs.structured_content import StructuredContentfrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContent-from pipelex.interpreter_hub import get_native_concept, get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_native_concept, get_pipe_router, get_required_entry_pipefrom pipelex.pipe_controllers.sequence.pipe_sequence import PipeSequencefrom pipelex.pipe_operators.structure.pipe_structure import PipeStructurefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactory@@ -91,13 +91,13 @@ class TestPreliminaryTextInlineE2E:) -> None:load_test_library([Path("tests/integration/pipelex/pipes/operator/pipe_structure")])- user_facing_pipe = get_required_pipe(pipe_code=pipe_code)+ user_facing_pipe = get_required_entry_pipe(pipe_code=pipe_code)assert isinstance(user_facing_pipe, PipeSequence)assert len(user_facing_pipe.sequential_sub_pipes) == 2- assert user_facing_pipe.sequential_sub_pipes[0].pipe_code == f"{pipe_code}__draft_text"- assert user_facing_pipe.sequential_sub_pipes[1].pipe_code == f"{pipe_code}__structure"+ assert user_facing_pipe.sequential_sub_pipes[0].pipe_code == f"test_preliminary_text_inline_e2e.{pipe_code}__draft_text"+ assert user_facing_pipe.sequential_sub_pipes[1].pipe_code == f"test_preliminary_text_inline_e2e.{pipe_code}__structure"- structure_step = get_required_pipe(pipe_code=f"{pipe_code}__structure")+ structure_step = get_required_entry_pipe(pipe_code=f"{pipe_code}__structure")assert isinstance(structure_step, PipeStructure)working_memory = WorkingMemoryFactory.make_from_single_stuff(diff --git a/tests/integration/pipelex/pipes/optionals/test_condition_optional_output_validation.py b/tests/integration/pipelex/pipes/optionals/test_condition_optional_output_validation.pyindex de22b1bd5..56b8b8a07 100644--- a/tests/integration/pipelex/pipes/optionals/test_condition_optional_output_validation.py+++ b/tests/integration/pipelex/pipes/optionals/test_condition_optional_output_validation.py@@ -88,7 +88,7 @@ class TestConditionOptionalOutputValidation:def test_continue_default_outcome_with_plain_output_is_rejected(self, load_empty_library: Callable[[], str]):load_empty_library()with pytest.raises(ValidationError) as exc_info:- _make_condition(output_ref="Text", outcomes={"go": "target_pipe"}, default_outcome="continue")+ _make_condition(output_ref="Text", outcomes={"go": "test_optionals_cond.target_pipe"}, default_outcome="continue")wrapped = extract_wrapped_pipe_validation_error(exc_info.value.errors()[0])assert wrapped is not Noneassert wrapped.error_type == PipeValidationErrorType.OPTIONAL_OUTPUT_REQUIRED@@ -100,7 +100,7 @@ class TestConditionOptionalOutputValidation:def test_no_continue_with_plain_output_is_accepted(self, load_empty_library: Callable[[], str]):load_empty_library()- condition = _make_condition(output_ref="Text", outcomes={"go": "target_pipe"}, default_outcome="fail")+ condition = _make_condition(output_ref="Text", outcomes={"go": "test_optionals_cond.target_pipe"}, default_outcome="fail")assert condition.output.presence.is_plain# ---- Condition boundary taint (with library) ----@@ -108,7 +108,7 @@ class TestConditionOptionalOutputValidation:def test_mapped_pipe_with_optional_output_requires_optional_condition_output(self, load_empty_library: Callable[[], str]):load_empty_library()_register_target_pipe(pipe_code="maybe_target", output_ref="Text?")- condition = _make_condition(output_ref="Text", outcomes={"go": "maybe_target"}, default_outcome="fail")+ condition = _make_condition(output_ref="Text", outcomes={"go": "test_optionals_cond.maybe_target"}, default_outcome="fail")get_pipe_library().add_new_pipe(pipe=condition)with pytest.raises(PipeValidationError) as exc_info:@@ -119,13 +119,13 @@ class TestConditionOptionalOutputValidation:def test_mapped_optional_output_accepted_when_condition_output_is_optional(self, load_empty_library: Callable[[], str]):load_empty_library()_register_target_pipe(pipe_code="maybe_target", output_ref="Text?")- condition = _make_condition(output_ref="Text?", outcomes={"go": "maybe_target"}, default_outcome="fail")+ condition = _make_condition(output_ref="Text?", outcomes={"go": "test_optionals_cond.maybe_target"}, default_outcome="fail")get_pipe_library().add_new_pipe(pipe=condition)condition.validate_with_libraries()def test_mapped_plain_outputs_keep_todays_rules(self, load_empty_library: Callable[[], str]):load_empty_library()_register_target_pipe(pipe_code="plain_target", output_ref="Text")- condition = _make_condition(output_ref="Text", outcomes={"go": "plain_target"}, default_outcome="fail")+ condition = _make_condition(output_ref="Text", outcomes={"go": "test_optionals_cond.plain_target"}, default_outcome="fail")get_pipe_library().add_new_pipe(pipe=condition)condition.validate_with_libraries()diff --git a/tests/integration/pipelex/pipes/optionals/test_lift_sequence.py b/tests/integration/pipelex/pipes/optionals/test_lift_sequence.pyindex 4130554ce..f5dc7bcc8 100644--- a/tests/integration/pipelex/pipes/optionals/test_lift_sequence.py+++ b/tests/integration/pipelex/pipes/optionals/test_lift_sequence.py@@ -103,9 +103,9 @@ def _build_lift_sequence() -> PipeSequence:inputs={"source": "Text?", "topic": "Text"},output="Text",steps=[- SubPipeBlueprint(pipe="opt_seq_step_a", result="a_out"),- SubPipeBlueprint(pipe="opt_seq_step_b", result="b_out"),- SubPipeBlueprint(pipe="opt_seq_sink_c", result="final_report"),+ SubPipeBlueprint(pipe="test_optionals_seq.opt_seq_step_a", result="a_out"),+ SubPipeBlueprint(pipe="test_optionals_seq.opt_seq_step_b", result="b_out"),+ SubPipeBlueprint(pipe="test_optionals_seq.opt_seq_sink_c", result="final_report"),],),)diff --git a/tests/integration/pipelex/pipes/optionals/test_liftable_pipes_inventory.py b/tests/integration/pipelex/pipes/optionals/test_liftable_pipes_inventory.pyindex 0f5020452..46212605e 100644--- a/tests/integration/pipelex/pipes/optionals/test_liftable_pipes_inventory.py+++ b/tests/integration/pipelex/pipes/optionals/test_liftable_pipes_inventory.py@@ -87,9 +87,9 @@ def _build_lift_chain_pipes() -> list[str]:inputs={"source": "Text?"},output="Text",steps=[- SubPipeBlueprint(pipe="inv_step_a", result="a_out"),- SubPipeBlueprint(pipe="inv_step_b", result="b_out"),- SubPipeBlueprint(pipe="inv_sink_c", result="final_report"),+ SubPipeBlueprint(pipe="test_optionals_inventory.inv_step_a", result="a_out"),+ SubPipeBlueprint(pipe="test_optionals_inventory.inv_step_b", result="b_out"),+ SubPipeBlueprint(pipe="test_optionals_inventory.inv_sink_c", result="final_report"),],),)@@ -112,7 +112,7 @@ class TestLiftablePipesInventory:def test_sequence_lift_chain_is_inventoried(self, load_empty_library: Callable[[], str]):load_empty_library()pipe_codes = _build_lift_chain_pipes()- pipes = [get_pipe_library().get_required_pipe(pipe_code=pipe_code) for pipe_code in pipe_codes]+ pipes = [get_pipe_library().get_required_entry_pipe(pipe_code=pipe_code) for pipe_code in pipe_codes]entries = build_liftable_pipes(collect_controller_taint_analyses(pipes))@@ -160,8 +160,8 @@ class TestLiftablePipesInventory:inputs={"source": "Text?", "topic": "Text"},output="Composite",branches=[- SubPipeBlueprint(pipe="inv_par_find", result="found_result"),- SubPipeBlueprint(pipe="inv_par_base", result="base_result"),+ SubPipeBlueprint(pipe="test_optionals_inventory.inv_par_find", result="found_result"),+ SubPipeBlueprint(pipe="test_optionals_inventory.inv_par_base", result="base_result"),],add_each_output=False,),diff --git a/tests/integration/pipelex/pipes/optionals/test_lifted_parallel_companion_slots.py b/tests/integration/pipelex/pipes/optionals/test_lifted_parallel_companion_slots.pyindex 63be0fc1c..f9c14989a 100644--- a/tests/integration/pipelex/pipes/optionals/test_lifted_parallel_companion_slots.py+++ b/tests/integration/pipelex/pipes/optionals/test_lifted_parallel_companion_slots.py@@ -97,8 +97,8 @@ def _build_sequence_with_liftable_parallel() -> PipeSequence:inputs={"source": "Text"},output="Composite",branches=[- SubPipeBlueprint(pipe="comp_find", result="a_out"),- SubPipeBlueprint(pipe="comp_find_many", result="many_out"),+ SubPipeBlueprint(pipe="test_optionals_companion.comp_find", result="a_out"),+ SubPipeBlueprint(pipe="test_optionals_companion.comp_find_many", result="many_out"),],add_each_output=True,),@@ -114,8 +114,8 @@ def _build_sequence_with_liftable_parallel() -> PipeSequence:inputs={"source": "Text?"},output="Text",steps=[- SubPipeBlueprint(pipe="comp_parallel", result="combined"),- SubPipeBlueprint(pipe="comp_sink", result="final_report"),+ SubPipeBlueprint(pipe="test_optionals_companion.comp_parallel", result="combined"),+ SubPipeBlueprint(pipe="test_optionals_companion.comp_sink", result="final_report"),],),)diff --git a/tests/integration/pipelex/pipes/optionals/test_optional_gate_tolerates_missing.py b/tests/integration/pipelex/pipes/optionals/test_optional_gate_tolerates_missing.pyindex 6b8f725eb..b871ea1a4 100644--- a/tests/integration/pipelex/pipes/optionals/test_optional_gate_tolerates_missing.py+++ b/tests/integration/pipelex/pipes/optionals/test_optional_gate_tolerates_missing.py@@ -64,7 +64,7 @@ class TestOptionalGateToleratesMissing:description="Single guarded step",inputs={"topic": "Text", "maybe_note": "Text?"},output="Text",- steps=[SubPipeBlueprint(pipe="gate_compose_sink", result="final_report")],+ steps=[SubPipeBlueprint(pipe="test_optionals_gate.gate_compose_sink", result="final_report")],),)get_pipe_library().add_new_pipe(pipe=sequence)@@ -92,7 +92,7 @@ class TestOptionalGateToleratesMissing:inputs={"topic": "Text", "maybe_note": "Text?"},output="Text",expression="'go'",- outcomes={"go": "gate_compose_sink"},+ outcomes={"go": "test_optionals_gate.gate_compose_sink"},default_outcome="fail",),)diff --git a/tests/integration/pipelex/pipes/optionals/test_parallel_optional_combine_validation.py b/tests/integration/pipelex/pipes/optionals/test_parallel_optional_combine_validation.pyindex 8a603bc4c..2e48d33c1 100644--- a/tests/integration/pipelex/pipes/optionals/test_parallel_optional_combine_validation.py+++ b/tests/integration/pipelex/pipes/optionals/test_parallel_optional_combine_validation.py@@ -96,8 +96,8 @@ def _build_parallel(*, output_ref: str, structure_class_names: list[str], inputsinputs=inputs,output=output_ref,branches=[- SubPipeBlueprint(pipe="par_static_find", result="found_result"),- SubPipeBlueprint(pipe="par_static_base", result="base_result"),+ SubPipeBlueprint(pipe="test_optionals_par_static.par_static_find", result="found_result"),+ SubPipeBlueprint(pipe="test_optionals_par_static.par_static_base", result="base_result"),],add_each_output=False,),diff --git a/tests/integration/pipelex/pipes/optionals/test_redundant_force_warning.py b/tests/integration/pipelex/pipes/optionals/test_redundant_force_warning.pyindex 859390597..6410ab5ed 100644--- a/tests/integration/pipelex/pipes/optionals/test_redundant_force_warning.py+++ b/tests/integration/pipelex/pipes/optionals/test_redundant_force_warning.py@@ -75,8 +75,8 @@ def _build_force_pipes() -> tuple[PipeSequence, PipeSequence]:inputs={"topic": "Text"},output="Text",steps=[- SubPipeBlueprint(pipe="rf_step_make", result="a_out"),- SubPipeBlueprint(pipe="rf_step_force", result="final"),+ SubPipeBlueprint(pipe="test_redundant_force.rf_step_make", result="a_out"),+ SubPipeBlueprint(pipe="test_redundant_force.rf_step_force", result="final"),],),)@@ -88,7 +88,7 @@ def _build_force_pipes() -> tuple[PipeSequence, PipeSequence]:inputs={"a_out": "Text?"},output="Text",steps=[- SubPipeBlueprint(pipe="rf_step_force", result="final"),+ SubPipeBlueprint(pipe="test_redundant_force.rf_step_force", result="final"),],),)diff --git a/tests/integration/pipelex/pipes/optionals/test_taint_sequence_validation.py b/tests/integration/pipelex/pipes/optionals/test_taint_sequence_validation.pyindex bdab85bf4..42de46c0f 100644--- a/tests/integration/pipelex/pipes/optionals/test_taint_sequence_validation.py+++ b/tests/integration/pipelex/pipes/optionals/test_taint_sequence_validation.py@@ -119,8 +119,8 @@ class TestSequenceTaintValidation:output_ref="Text",inputs={"source": "Text?"},steps=[- SubPipeBlueprint(pipe="taint_step_a", result="a_out"),- SubPipeBlueprint(pipe="taint_step_b", result="b_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_a", result="a_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_b", result="b_out"),],)@@ -142,8 +142,8 @@ class TestSequenceTaintValidation:output_ref="Text?",inputs={"source": "Text?"},steps=[- SubPipeBlueprint(pipe="taint_step_a", result="a_out"),- SubPipeBlueprint(pipe="taint_step_b", result="b_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_a", result="a_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_b", result="b_out"),],)sequence.validate_with_libraries()@@ -156,9 +156,9 @@ class TestSequenceTaintValidation:output_ref="Text",inputs={"source": "Text?"},steps=[- SubPipeBlueprint(pipe="taint_step_a", result="a_out"),- SubPipeBlueprint(pipe="taint_step_b", result="b_out"),- SubPipeBlueprint(pipe="taint_sink_c", result="final_report"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_a", result="a_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_b", result="b_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_sink_c", result="final_report"),],)sequence.validate_with_libraries()@@ -171,8 +171,8 @@ class TestSequenceTaintValidation:output_ref="Text",inputs={"source": "Text?"},steps=[- SubPipeBlueprint(pipe="taint_step_a", result="a_out"),- SubPipeBlueprint(pipe="taint_step_b", result="b_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_a", result="a_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_b", result="b_out"),],)sequence.validate_with_libraries()@@ -184,8 +184,8 @@ class TestSequenceTaintValidation:output_ref="Text",inputs={"source": "Text"},steps=[- SubPipeBlueprint(pipe="taint_step_a", result="a_out"),- SubPipeBlueprint(pipe="taint_step_b", result="b_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_a", result="a_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_b", result="b_out"),],)sequence.validate_with_libraries()@@ -213,8 +213,8 @@ class TestSequenceTaintValidation:output_ref="Text",inputs={"topic": "Text"},steps=[- SubPipeBlueprint(pipe="taint_gate", result="source"),- SubPipeBlueprint(pipe="taint_step_a", result="a_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_gate", result="source"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_a", result="a_out"),],)@@ -254,8 +254,8 @@ class TestSequenceTaintValidation:output_ref="Text",inputs={"items": "Text[]"},steps=[- SubPipeBlueprint(pipe="taint_item_finder", result="found_items", batch_over="items", batch_as="item"),- SubPipeBlueprint(pipe="taint_list_sink", result="summary"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_item_finder", result="found_items", batch_over="items", batch_as="item"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_list_sink", result="summary"),],)sequence.validate_with_libraries()@@ -285,8 +285,8 @@ class TestSequenceTaintValidation:inputs={"source": "Text?", "topic": "Text"},output="Composite",branches=[- SubPipeBlueprint(pipe="taint_step_a", result="a_out"),- SubPipeBlueprint(pipe="taint_par_base", result="base_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_a", result="a_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_par_base", result="base_out"),],add_each_output=True,),@@ -296,9 +296,9 @@ class TestSequenceTaintValidation:output_ref="Text",inputs={"source": "Text?", "topic": "Text"},steps=[- SubPipeBlueprint(pipe="taint_parallel", result="combined"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_parallel", result="combined"),# Consumes the liftable branch's slot plain, and ends the sequence.- SubPipeBlueprint(pipe="taint_step_b", result="b_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_b", result="b_out"),],)@@ -317,10 +317,10 @@ class TestSequenceTaintValidation:inputs={"source": "Text?", "a_out": "Text"},steps=[# Step A consumes the optional source and writes b_out (tainted)...- SubPipeBlueprint(pipe="taint_step_a", result="b_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_a", result="b_out"),# ...then step B (consuming the guaranteed a_out) overwrites b_out with a# guaranteed value, so the sequence output is guaranteed.- SubPipeBlueprint(pipe="taint_step_b", result="b_out"),+ SubPipeBlueprint(pipe="test_optionals_taint_seq.taint_step_b", result="b_out"),],)sequence.validate_with_libraries()diff --git a/tests/integration/pipelex/pipes/test_image_out_in.py b/tests/integration/pipelex/pipes/test_image_out_in.pyindex 7de156265..7725e2dd0 100644--- a/tests/integration/pipelex/pipes/test_image_out_in.py+++ b/tests/integration/pipelex/pipes/test_image_out_in.py@@ -3,7 +3,7 @@ from typing import Callableimport pytest-from pipelex.interpreter_hub import get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_pipe_router, get_required_entry_pipefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.system.job_metadata import JobMetadata@@ -19,7 +19,7 @@ class TestImageOutIn:load_test_library([Path("tests/integration/pipelex/pipes/pipelines")])pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code="image_out_in"),+ pipe=get_required_entry_pipe(pipe_code="image_out_in"),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),job_metadata=job_metadata,),diff --git a/tests/integration/pipelex/pipes/test_pipe_running_variants.py b/tests/integration/pipelex/pipes/test_pipe_running_variants.pyindex d375ed312..0f7d2bf33 100644--- a/tests/integration/pipelex/pipes/test_pipe_running_variants.py+++ b/tests/integration/pipelex/pipes/test_pipe_running_variants.py@@ -7,7 +7,7 @@ from pipelex import log, pretty_printfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactoryfrom pipelex.core.pipes.variable_multiplicity import VariableMultiplicityfrom pipelex.core.stuffs.stuff import Stuff-from pipelex.interpreter_hub import get_pipe_router, get_required_pipe+from pipelex.interpreter_hub import get_pipe_router, get_required_entry_pipefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactoryfrom pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactoryfrom pipelex.pipeline.exceptions import PipeStackOverflowError@@ -37,7 +37,7 @@ class TestPipeRunningVariants:working_memory = WorkingMemoryFactory.make_from_single_stuff(stuff=stuff)_ = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code=pipe_code),+ pipe=get_required_entry_pipe(pipe_code=pipe_code),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=working_memory,job_metadata=job_metadata,@@ -57,7 +57,7 @@ class TestPipeRunningVariants:log.verbose(f"{topic}: just run pipe '{pipe_code}'")pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code=pipe_code),+ pipe=get_required_entry_pipe(pipe_code=pipe_code),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),working_memory=WorkingMemoryFactory.make_empty(),job_metadata=job_metadata,@@ -83,7 +83,7 @@ class TestPipeRunningVariants:log.verbose(f"{topic}: just run pipe '{pipe_code}'")pipe_output = await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code=pipe_code),+ pipe=get_required_entry_pipe(pipe_code=pipe_code),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode,output_multiplicity=output_multiplicity,@@ -113,7 +113,7 @@ class TestPipeRunningVariants:with pytest.raises(PipeStackOverflowError) as exc:await get_pipe_router().run(pipe_job=PipeJobFactory.make_pipe_job(- pipe=get_required_pipe(pipe_code=pipe_code),+ pipe=get_required_entry_pipe(pipe_code=pipe_code),pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_stack_limit=6,pipe_run_mode=pipe_run_mode,diff --git a/tests/unit/pipelex/builder/operations/test_inputs_ops.py b/tests/unit/pipelex/builder/operations/test_inputs_ops.pyindex 309db68bb..7a67602a4 100644--- a/tests/unit/pipelex/builder/operations/test_inputs_ops.py+++ b/tests/unit/pipelex/builder/operations/test_inputs_ops.py@@ -30,8 +30,8 @@ class TestBuildInputsForPipe:"set_current_library": mocker.patch(f"{MODULE}.set_current_library"),"resolve_library_dirs": mocker.patch(f"{MODULE}.resolve_library_dirs", return_value=([], "defaults")),"validate_bundle": mocker.patch(f"{MODULE}.validate_bundle", new=mocker.AsyncMock(return_value=validate_result)),- "get_required_pipe": mocker.patch(- f"{MODULE}.get_required_pipe", return_value=SimpleNamespace(code="bundle_main", inputs=SimpleNamespace(root={}))+ "get_required_entry_pipe": mocker.patch(+ f"{MODULE}.get_required_entry_pipe", return_value=SimpleNamespace(code="bundle_main", inputs=SimpleNamespace(root={}))),"render_inputs": mocker.patch(f"{MODULE}.render_inputs", return_value='{\n "topic": "your topic"\n}'),}@@ -48,7 +48,7 @@ class TestBuildInputsForPipe:result = asyncio.run(build_inputs_for_pipe(mthds_contents=["mthds content"]))- ops_mocks["get_required_pipe"].assert_called_once_with(pipe_code="domain.main")+ ops_mocks["get_required_entry_pipe"].assert_called_once_with(pipe_code="domain.main")assert result["pipe_code"] == "domain.main"def test_mthds_contents_validates_with_allow_signatures(self, ops_mocks: dict[str, Any]) -> None:@@ -79,7 +79,7 @@ class TestBuildInputsForPipe:"""An explicit pipe code is used verbatim, ignoring the blueprints' main_pipe declarations."""result = asyncio.run(build_inputs_for_pipe(pipe_code="explicit_pipe", mthds_contents=["mthds content"]))- ops_mocks["get_required_pipe"].assert_called_once_with(pipe_code="explicit_pipe")+ ops_mocks["get_required_entry_pipe"].assert_called_once_with(pipe_code="explicit_pipe")assert result["pipe_code"] == "explicit_pipe"def test_bundle_path_validates_file_and_qualifies_main_pipe(self, ops_mocks: dict[str, Any], tmp_path: Path) -> None:@@ -93,7 +93,7 @@ class TestBuildInputsForPipe:library_dirs=None,allow_signatures=True,)- ops_mocks["get_required_pipe"].assert_called_once_with(pipe_code="demo_domain.bundle_main")+ ops_mocks["get_required_entry_pipe"].assert_called_once_with(pipe_code="demo_domain.bundle_main")assert result["pipe_code"] == "demo_domain.bundle_main"def test_bundle_path_without_main_pipe_raises_with_path(self, ops_mocks: dict[str, Any], tmp_path: Path) -> None:@@ -110,7 +110,7 @@ class TestBuildInputsForPipe:"""With a bundle path, an explicit pipe code overrides the bundle's main_pipe."""result = asyncio.run(build_inputs_for_pipe(pipe_code="explicit_pipe", bundle_path=tmp_path / "demo.mthds"))- ops_mocks["get_required_pipe"].assert_called_once_with(pipe_code="explicit_pipe")+ ops_mocks["get_required_entry_pipe"].assert_called_once_with(pipe_code="explicit_pipe")assert result["pipe_code"] == "explicit_pipe"def test_no_bundle_loads_libraries_from_resolved_dirs(self, ops_mocks: dict[str, Any]) -> None:@@ -138,13 +138,13 @@ class TestBuildInputsForPipe:with pytest.raises(ValueError, match="No pipe code specified"):asyncio.run(build_inputs_for_pipe())- ops_mocks["get_required_pipe"].assert_not_called()+ ops_mocks["get_required_entry_pipe"].assert_not_called()def test_happy_path_return_shape(self, ops_mocks: dict[str, Any]) -> None:"""The result carries success, the resolved pipe code, and the parsed inputs dict from render_inputs."""result = asyncio.run(build_inputs_for_pipe(pipe_code="my_pipe"))- the_pipe = ops_mocks["get_required_pipe"].return_value+ the_pipe = ops_mocks["get_required_entry_pipe"].return_valueops_mocks["render_inputs"].assert_called_once_with(the_pipe, indent=2, explicit=False)assert result == {"success": True,diff --git a/tests/unit/pipelex/cli/commands/build/test_inputs_core.py b/tests/unit/pipelex/cli/commands/build/test_inputs_core.pyindex 7f9a72313..ffcec7f72 100644--- a/tests/unit/pipelex/cli/commands/build/test_inputs_core.py+++ b/tests/unit/pipelex/cli/commands/build/test_inputs_core.py@@ -33,7 +33,7 @@ class TestGenerateInputsCore:validate_result = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe="bundle_main")])return {"validate_bundle": mocker.patch(f"{MODULE}.validate_bundle", new=mocker.AsyncMock(return_value=validate_result)),- "get_required_pipe": mocker.patch(f"{MODULE}.get_required_pipe", return_value=SimpleNamespace(code="bundle_main")),+ "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}'),}@@ -43,7 +43,7 @@ class TestGenerateInputsCore:asyncio.run(_generate_inputs_core(pipe_code=None, bundle_path=bundle_path))- core_mocks["get_required_pipe"].assert_called_once_with(pipe_code="bundle_main")+ core_mocks["get_required_entry_pipe"].assert_called_once_with(pipe_code="bundle_main")inputs_file = tmp_path / "inputs.json"assert inputs_file.read_text(encoding="utf-8") == '{\n "topic": "your topic"\n}'@@ -53,7 +53,7 @@ class TestGenerateInputsCore:asyncio.run(_generate_inputs_core(pipe_code="my_pipe", bundle_path=bundle_path))- core_mocks["get_required_pipe"].assert_called_once_with(pipe_code="my_pipe")+ core_mocks["get_required_entry_pipe"].assert_called_once_with(pipe_code="my_pipe")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."""diff --git a/tests/unit/pipelex/cli/commands/build/test_inputs_core_toml.py b/tests/unit/pipelex/cli/commands/build/test_inputs_core_toml.pyindex 703ca9feb..49908a658 100644--- a/tests/unit/pipelex/cli/commands/build/test_inputs_core_toml.py+++ b/tests/unit/pipelex/cli/commands/build/test_inputs_core_toml.py@@ -33,7 +33,7 @@ class TestGenerateInputsCoreToml:validate_result = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe="bundle_main")])return {"validate_bundle": mocker.patch(f"{MODULE}.validate_bundle", new=mocker.AsyncMock(return_value=validate_result)),- "get_required_pipe": mocker.patch(f"{MODULE}.get_required_pipe", return_value=SimpleNamespace(code="bundle_main")),+ "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}'),"render_inputs_toml": mocker.patch(f"{MODULE}.render_inputs_toml", return_value=TOML_TEMPLATE),}diff --git a/tests/unit/pipelex/cli/commands/build/test_output_core.py b/tests/unit/pipelex/cli/commands/build/test_output_core.pyindex 7a2291cc6..1e5811756 100644--- a/tests/unit/pipelex/cli/commands/build/test_output_core.py+++ b/tests/unit/pipelex/cli/commands/build/test_output_core.py@@ -33,7 +33,7 @@ class TestGenerateOutputCore:validate_result = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe="bundle_main")])return {"validate_bundle": mocker.patch(f"{MODULE}.validate_bundle", new=mocker.AsyncMock(return_value=validate_result)),- "get_required_pipe": mocker.patch(f"{MODULE}.get_required_pipe", return_value=SimpleNamespace(code="bundle_main")),+ "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}'),}@@ -41,7 +41,7 @@ class TestGenerateOutputCore:"""Without --pipe, the bundle's main_pipe is used and output.json lands next to the bundle."""asyncio.run(_generate_output_core(pipe_code=None, bundle_path=tmp_path / "demo.mthds"))- core_mocks["get_required_pipe"].assert_called_once_with(pipe_code="bundle_main")+ core_mocks["get_required_entry_pipe"].assert_called_once_with(pipe_code="bundle_main")assert (tmp_path / "output.json").read_text(encoding="utf-8") == '{"answer": 42}'@pytest.mark.usefixtures("core_mocks")diff --git a/tests/unit/pipelex/cli/commands/build/test_runner_core.py b/tests/unit/pipelex/cli/commands/build/test_runner_core.pyindex 0d89d8c30..c5b4bb54d 100644--- a/tests/unit/pipelex/cli/commands/build/test_runner_core.py+++ b/tests/unit/pipelex/cli/commands/build/test_runner_core.py@@ -38,7 +38,7 @@ class TestPrepareRunnerCore:return {"library_manager": library_manager,"validate_bundle": mocker.patch(f"{MODULE}.validate_bundle", new=mocker.AsyncMock(return_value=validate_result)),- "get_required_pipe": mocker.patch(f"{MODULE}.get_required_pipe", return_value=SimpleNamespace(code="bundle_main")),+ "get_required_entry_pipe": mocker.patch(f"{MODULE}.get_required_entry_pipe", return_value=SimpleNamespace(code="bundle_main")),"normalize_crate": mocker.patch(f"{MODULE}.normalize_crate"),"emit_types": mocker.patch(f"{MODULE}.emit_types", return_value=[]),"write_stamped_projection": mocker.patch(@@ -54,7 +54,7 @@ class TestPrepareRunnerCore:"""Without --pipe, the bundle's main_pipe names the default run_<pipe>.py file."""asyncio.run(_prepare_runner_core(pipe_code=None, bundle_path=tmp_path / "demo.mthds"))- core_mocks["get_required_pipe"].assert_called_once_with(pipe_code="bundle_main")+ core_mocks["get_required_entry_pipe"].assert_called_once_with(pipe_code="bundle_main")runner_file = tmp_path / "run_bundle_main.py"assert runner_file.read_text(encoding="utf-8") == "# runner code\n"codegen_kwargs = core_mocks["generate_runner_code"].call_args.kwargsdiff --git a/tests/unit/pipelex/cli/test_codegen_cli.py b/tests/unit/pipelex/cli/test_codegen_cli.pyindex 4fa08a12b..2c12d9262 100644--- a/tests/unit/pipelex/cli/test_codegen_cli.py+++ b/tests/unit/pipelex/cli/test_codegen_cli.py@@ -73,7 +73,7 @@ class TestCodegenCli:else:crate = LibraryCrate(domains={"scoring": DomainBlueprint(code="scoring", description="d", main_pipe="run_scoring")})mocker.patch(f"{INPUTS}.load_normalized_crate_or_exit", return_value=crate)- mocker.patch(f"{INPUTS}.get_required_pipe")+ mocker.patch(f"{INPUTS}.get_required_entry_pipe")mocker.patch(f"{INPUTS}.render_inputs", return_value="{}")codegen_inputs_cmd(pipe=None,@@ -111,14 +111,14 @@ class TestCodegenCli:self._neutralize_boot(mocker, module=INPUTS)crate = LibraryCrate(domains={"scoring": DomainBlueprint(code="scoring", description="d", main_pipe="run_scoring")})mocker.patch(f"{INPUTS}.load_normalized_crate_or_exit", return_value=crate)- get_required_pipe = mocker.patch(f"{INPUTS}.get_required_pipe")+ get_required_entry_pipe = mocker.patch(f"{INPUTS}.get_required_entry_pipe")mocker.patch(f"{INPUTS}.render_inputs", return_value='{"topic": "x"}')destination = tmp_path / "inputs.json"codegen_inputs_cmd(pipe=None, paths=None, template_format=InputsTemplateFormat.JSON, explicit=False, output=str(destination), library_dir=None)# The single declared main_pipe was selected (qualified) and rendered to the output file.- assert get_required_pipe.call_args.kwargs["pipe_code"] == "scoring.run_scoring"+ assert get_required_entry_pipe.call_args.kwargs["pipe_code"] == "scoring.run_scoring"assert destination.read_text(encoding="utf-8") == '{"topic": "x"}'def test_inputs_write_if_changed_leaves_identical_file_untouched(self, mocker: MockerFixture, tmp_path: Path) -> None:@@ -128,7 +128,7 @@ class TestCodegenCli:self._neutralize_boot(mocker, module=INPUTS)crate = LibraryCrate(domains={"scoring": DomainBlueprint(code="scoring", description="d", main_pipe="run_scoring")})mocker.patch(f"{INPUTS}.load_normalized_crate_or_exit", return_value=crate)- mocker.patch(f"{INPUTS}.get_required_pipe")+ mocker.patch(f"{INPUTS}.get_required_entry_pipe")mocker.patch(f"{INPUTS}.render_inputs", return_value='{"topic": "x"}')destination = tmp_path / "inputs.json"destination.write_text('{"topic": "x"}', encoding="utf-8")@@ -162,7 +162,7 @@ class TestCodegenCli:def test_inputs_unknown_explicit_pipe_is_exit_1(self, mocker: MockerFixture) -> None:self._neutralize_boot(mocker, module=INPUTS)mocker.patch(f"{INPUTS}.load_normalized_crate_or_exit", return_value=LibraryCrate())- mocker.patch(f"{INPUTS}.get_required_pipe", side_effect=PipeLibraryError("no such pipe"))+ mocker.patch(f"{INPUTS}.get_required_entry_pipe", side_effect=PipeLibraryError("no such pipe"))with pytest.raises(typer.Exit) as exc_info:codegen_inputs_cmd(pipe="scoring.missing", paths=None, template_format=InputsTemplateFormat.JSON, explicit=False, output=None, library_dir=Nonediff --git a/tests/unit/pipelex/cli/test_show_cmd.py b/tests/unit/pipelex/cli/test_show_cmd.pyindex 7cfb09c56..4e09fabc4 100644--- a/tests/unit/pipelex/cli/test_show_cmd.py+++ b/tests/unit/pipelex/cli/test_show_cmd.py@@ -102,12 +102,12 @@ class TestShowCmd:def test_do_show_pipe_pretty_prints_pipe(self, mocker: MockerFixture, telemetry: Any) -> None:"""Showing a pipe fetches it from the hub and pretty-prints it."""fake_pipe = SimpleNamespace(type="PipeLLM")- get_required_pipe_mock = mocker.patch("pipelex.cli.commands.show_cmd.get_required_pipe", return_value=fake_pipe)+ get_required_entry_pipe_mock = mocker.patch("pipelex.cli.commands.show_cmd.get_required_entry_pipe", return_value=fake_pipe)pretty_print_mock = mocker.patch("pipelex.cli.commands.show_cmd.pretty_print")do_show_pipe(pipe_code="my_pipe")- get_required_pipe_mock.assert_called_once_with(pipe_code="my_pipe")+ get_required_entry_pipe_mock.assert_called_once_with(pipe_code="my_pipe")pretty_print_mock.assert_called_once_with(fake_pipe, title="Pipe 'my_pipe'")telemetry.track_event.assert_called_once()diff --git a/tests/unit/pipelex/cli/test_validate_exit_codes.py b/tests/unit/pipelex/cli/test_validate_exit_codes.pyindex d6159f9f4..f123dc1c5 100644--- a/tests/unit/pipelex/cli/test_validate_exit_codes.py+++ b/tests/unit/pipelex/cli/test_validate_exit_codes.py@@ -24,6 +24,7 @@ from pipelex.cli.agent_cli.commands.validate.bundle_cmd import validate_bundle_cfrom pipelex.cli.agent_cli.commands.validate.pipe_cmd import validate_pipe_cmd as agent_validate_pipe_cmdfrom pipelex.cli.commands.validate.bundle_cmd import validate_bundle_cmd as bare_validate_bundle_cmdfrom pipelex.cli.commands.validate.pipe_cmd import validate_pipe_cmd as bare_validate_pipe_cmd+from pipelex.libraries.pipe.exceptions import PipeLibraryErrorfrom pipelex.pipe_run.exceptions import DryRunErrorfrom pipelex.pipeline.exceptions import ValidateBundleError@@ -34,6 +35,7 @@ if TYPE_CHECKING:AGENT_BUNDLE_MODULE = "pipelex.cli.agent_cli.commands.validate.bundle_cmd"AGENT_PIPE_MODULE = "pipelex.cli.agent_cli.commands.validate.pipe_cmd"+BARE_VALIDATE_CORE = "pipelex.cli.commands.validate._validate_core"def _make_dir(tmp_path: Path, name: str, mthds_files: list[str]) -> Path:@@ -87,6 +89,24 @@ class TestValidateExitCodes:bare_validate_pipe_cmd(pipe_code="my_bundle.mthds")assert exc_info.value.exit_code == 2+ def test_bare_pipe_ambiguous_code_is_no_verdict_exit_2(self, mocker: MockerFixture) -> None:+ """A bare code declared by several domains is an unresolvable target: clean exit 2, not a traceback."""+ mocker.patch("pipelex.cli.commands.validate.pipe_cmd.resolve_pipe_from_exports", return_value=[])+ mocker.patch(f"{BARE_VALIDATE_CORE}.make_pipelex_for_cli")+ mocker.patch(f"{BARE_VALIDATE_CORE}.Pipelex.teardown_if_needed")+ library_manager = mocker.Mock()+ library_manager.open_library.return_value = ("lib-id", mocker.Mock())+ mocker.patch(f"{BARE_VALIDATE_CORE}.get_library_manager", return_value=library_manager)+ mocker.patch(f"{BARE_VALIDATE_CORE}.set_current_library")+ mocker.patch(f"{BARE_VALIDATE_CORE}.resolve_library_dirs", return_value=([], "defaults"))+ mocker.patch(+ f"{BARE_VALIDATE_CORE}.get_required_entry_pipe",+ side_effect=PipeLibraryError("Pipe code 'my_pipe' is ambiguous: declared by ['a.my_pipe', 'b.my_pipe']"),+ )+ with pytest.raises(typer.Exit) as exc_info:+ bare_validate_pipe_cmd(pipe_code="my_pipe")+ assert exc_info.value.exit_code == 2+# --- agent CLI: bad args / unresolvable targets exit 2 (no verdict), pre-boot ---def test_agent_bundle_directory_without_mthds_exits_2(self, tmp_path: Path) -> None:diff --git a/tests/unit/pipelex/cli/test_which_cmd.py b/tests/unit/pipelex/cli/test_which_cmd.pyindex 5c38da323..d66d319c1 100644--- a/tests/unit/pipelex/cli/test_which_cmd.py+++ b/tests/unit/pipelex/cli/test_which_cmd.py@@ -9,6 +9,7 @@ import pytestfrom rich.console import Consolefrom pipelex.cli.commands.which_cmd import do_which_pipe+from pipelex.libraries.pipe.exceptions import PipeLibraryErrorif TYPE_CHECKING:from pathlib import Path@@ -26,7 +27,7 @@ class TestWhichCmd:def test_pipe_found_with_source(self, mocker: MockerFixture, console: Console, tmp_path: Path) -> None:"""A found pipe reports type, domain and source, and returns True."""fake_pipe = SimpleNamespace(pipe_type="PipeLLM", domain_code="demo")- mocker.patch("pipelex.cli.commands.which_cmd.get_optional_pipe", return_value=fake_pipe)+ mocker.patch("pipelex.cli.commands.which_cmd.get_optional_entry_pipe", return_value=fake_pipe)mocker.patch("pipelex.cli.commands.which_cmd.get_pipe_source", return_value=str(tmp_path / "demo.mthds"))found = do_which_pipe(pipe_code="demo.my_pipe", library_dirs=[tmp_path], source_label="--library-dir")@@ -45,7 +46,7 @@ class TestWhichCmd:def test_pipe_found_without_source(self, mocker: MockerFixture, console: Console, tmp_path: Path) -> None:"""A found pipe with no known source path omits the Source line."""fake_pipe = SimpleNamespace(pipe_type="PipeLLM", domain_code="demo")- mocker.patch("pipelex.cli.commands.which_cmd.get_optional_pipe", return_value=fake_pipe)+ mocker.patch("pipelex.cli.commands.which_cmd.get_optional_entry_pipe", return_value=fake_pipe)mocker.patch("pipelex.cli.commands.which_cmd.get_pipe_source", return_value=None)found = do_which_pipe(pipe_code="demo.my_pipe", library_dirs=[tmp_path], source_label="PIPELEXPATH")@@ -55,7 +56,7 @@ class TestWhichCmd:def test_pipe_not_found(self, mocker: MockerFixture, console: Console, tmp_path: Path) -> None:"""A missing pipe returns False and prints the search tip."""- mocker.patch("pipelex.cli.commands.which_cmd.get_optional_pipe", return_value=None)+ mocker.patch("pipelex.cli.commands.which_cmd.get_optional_entry_pipe", return_value=None)found = do_which_pipe(pipe_code="ghost_pipe", library_dirs=[tmp_path], source_label="PIPELEXPATH")@@ -64,9 +65,35 @@ class TestWhichCmd:assert "Not found: ghost_pipe" in outputassert "PIPELEXPATH or passed via --library-dir" in output+ def test_ambiguous_bare_code_reports_candidates(self, mocker: MockerFixture, console: Console, tmp_path: Path) -> None:+ """An ambiguous bare code names the candidate domains and returns False instead of escaping as a traceback."""+ mocker.patch(+ "pipelex.cli.commands.which_cmd.get_optional_entry_pipe",+ side_effect=PipeLibraryError("Pipe code 'compute_score' is ambiguous: declared by ['analytics.compute_score', 'scoring.compute_score']"),+ )++ found = do_which_pipe(pipe_code="compute_score", library_dirs=[tmp_path], source_label="PIPELEXPATH")++ assert found is False+ output = console.export_text()+ assert "Ambiguous: compute_score" in output+ assert "analytics.compute_score" in output+ assert "scoring.compute_score" in output++ def test_bracketed_pipe_code_renders_literally(self, mocker: MockerFixture, console: Console, tmp_path: Path) -> None:+ """A pipe code containing Rich markup characters is printed literally, not parsed as markup."""+ mocker.patch("pipelex.cli.commands.which_cmd.get_optional_entry_pipe", return_value=None)++ found = do_which_pipe(pipe_code="[/foo]", library_dirs=[tmp_path], source_label="PIPELEXPATH")++ assert found is False+ output = console.export_text()+ assert "Search path for '[/foo]':" in output+ assert "Not found: [/foo]" in output+def test_empty_library_dirs(self, mocker: MockerFixture, console: Console) -> None:"""An empty search path is reported explicitly."""- mocker.patch("pipelex.cli.commands.which_cmd.get_optional_pipe", return_value=None)+ mocker.patch("pipelex.cli.commands.which_cmd.get_optional_entry_pipe", return_value=None)found = do_which_pipe(pipe_code="any_pipe", library_dirs=[], source_label="defaults")@@ -75,7 +102,7 @@ class TestWhichCmd:def test_nonexistent_directory_marked(self, mocker: MockerFixture, console: Console, tmp_path: Path) -> None:"""Directories missing on disk are marked with a red cross but still listed."""- mocker.patch("pipelex.cli.commands.which_cmd.get_optional_pipe", return_value=None)+ mocker.patch("pipelex.cli.commands.which_cmd.get_optional_entry_pipe", return_value=None)missing_dir = tmp_path / "does-not-exist"do_which_pipe(pipe_code="any_pipe", library_dirs=[tmp_path, missing_dir], source_label="defaults")diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_explicit_forms.py b/tests/unit/pipelex/core/memory/input_shaper/test_explicit_forms.pyindex c120d20c1..89ba5b56f 100644--- a/tests/unit/pipelex/core/memory/input_shaper/test_explicit_forms.py+++ b/tests/unit/pipelex/core/memory/input_shaper/test_explicit_forms.py@@ -72,7 +72,7 @@ class TestInputShaperExplicitForms:provided = ShaperInvoice(invoice_number="INV-002", amount=99.0)working_memory = InputShaper.shape(- {"invoice": provided}, input_specs=input_specs, search_domain_codes=["shaper_test"], concept_provider=get_concept_library()+ {"invoice": provided}, input_specs=input_specs, search_scope="shaper_test", concept_provider=get_concept_library())stuff = working_memory.root["invoice"]@@ -90,7 +90,7 @@ class TestInputShaperExplicitForms:provided = [Question(text="a"), Question(text="b")]working_memory = InputShaper.shape(- {"questions": provided}, input_specs=input_specs, search_domain_codes=["shaper_test"], concept_provider=get_concept_library()+ {"questions": provided}, input_specs=input_specs, search_scope="shaper_test", concept_provider=get_concept_library())stuff = working_memory.root["questions"]@@ -104,9 +104,7 @@ class TestInputShaperExplicitForms:provided = [Question(text="a")]with pytest.raises(ExplicitConceptIncompatibleError, match="not compatible"):- InputShaper.shape(- {"priorities": provided}, input_specs=input_specs, search_domain_codes=["shaper_test"], concept_provider=get_concept_library()- )+ InputShaper.shape({"priorities": provided}, input_specs=input_specs, search_scope="shaper_test", concept_provider=get_concept_library())def test_explicit_list_into_singular_raises(self) -> None:"""D2: an explicit ListContent (or envelope-with-list) must not fill a singular-declared slot.@@ -118,9 +116,7 @@ class TestInputShaperExplicitForms:provided: ListContent[Question] = ListContent(items=[Question(text="a"), Question(text="b")])with pytest.raises(ListWhereSingularError, match="declares a single"):- InputShaper.shape(- {"question": provided}, input_specs=input_specs, search_domain_codes=["shaper_test"], concept_provider=get_concept_library()- )+ InputShaper.shape({"question": provided}, input_specs=input_specs, search_scope="shaper_test", concept_provider=get_concept_library())def test_explicit_list_wrong_fixed_count_raises(self) -> None:"""D2: an explicit ListContent whose length differs from a declared [N] count is a D4 error."""@@ -128,9 +124,7 @@ class TestInputShaperExplicitForms:provided: ListContent[Question] = ListContent(items=[Question(text="only-one")])with pytest.raises(MultiplicityCountMismatchError, match="exactly 2 items"):- InputShaper.shape(- {"questions": provided}, input_specs=input_specs, search_domain_codes=["shaper_test"], concept_provider=get_concept_library()- )+ InputShaper.shape({"questions": provided}, input_specs=input_specs, search_scope="shaper_test", concept_provider=get_concept_library())def test_explicit_list_into_list_slot_ok(self) -> None:"""D2/D6: an explicit ListContent whose length matches a declared list slot shapes cleanly."""@@ -138,7 +132,7 @@ class TestInputShaperExplicitForms:provided: ListContent[Question] = ListContent(items=[Question(text="a"), Question(text="b")])working_memory = InputShaper.shape(- {"questions": provided}, input_specs=input_specs, search_domain_codes=["shaper_test"], concept_provider=get_concept_library()+ {"questions": provided}, input_specs=input_specs, search_scope="shaper_test", concept_provider=get_concept_library())stuff = working_memory.root["questions"]@@ -152,7 +146,7 @@ class TestInputShaperExplicitForms:provided: ListContent[Question] = ListContent(items=[Question(text="a"), Question(text="b")])working_memory = InputShaper.shape(- {"payload": provided}, input_specs=input_specs, search_domain_codes=["shaper_test"], concept_provider=get_concept_library()+ {"payload": provided}, input_specs=input_specs, search_scope="shaper_test", concept_provider=get_concept_library())stuff = working_memory.root["payload"]diff --git a/tests/unit/pipelex/core/stuffs/data.py b/tests/unit/pipelex/core/stuffs/data.pyindex 8a83f3c85..c5e1f2cc0 100644--- a/tests/unit/pipelex/core/stuffs/data.py+++ b/tests/unit/pipelex/core/stuffs/data.py@@ -660,14 +660,14 @@ TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str | None, str, Stu# Test cases with search_domains - format: (test_name, stuff_content_or_data, stuff_name, stuff_code, search_domains, expected_stuff)-SEARCH_DOMAIN_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str | None, str, list[str], Stuff]] = [+SEARCH_DOMAIN_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str | None, str, str, Stuff]] = [# Case with search_domains: StuffContent object("search-domain-stuff-content",AnotherConcept(name="test", value=42),"stuff_name","stuff_code",- ["test_domain"],+ "test_domain",Stuff(stuff_name="stuff_name",stuff_code="stuff_code",@@ -689,7 +689,7 @@ SEARCH_DOMAIN_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str |],"stuff_name","stuff_code",- ["test_domain"],+ "test_domain",Stuff(stuff_name="stuff_name",stuff_code="stuff_code",@@ -718,7 +718,7 @@ SEARCH_DOMAIN_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str |),"stuff_name","stuff_code",- ["test_domain"],+ "test_domain",Stuff(stuff_name="stuff_name",stuff_code="stuff_code",@@ -745,7 +745,7 @@ SEARCH_DOMAIN_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str |},"stuff_name","stuff_code",- ["test_domain"],+ "test_domain",Stuff(stuff_name="stuff_name",stuff_code="stuff_code",@@ -762,7 +762,7 @@ SEARCH_DOMAIN_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str |# Error test cases - these should raise exceptions-ERROR_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str | None, str, list[str] | None, type[Exception], str]] = [+ERROR_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str | None, str, str | None, type[Exception], str]] = [# Format: (test_name, stuff_content_or_data, stuff_name, stuff_code, search_domains, expected_exception, error_match)# Empty list - should fail(@@ -860,7 +860,7 @@ ERROR_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str | None, st{"concept": "test_domain.MyConcept", "content": "plain text"},"stuff_name","stuff_code",- ["test_domain"],+ "test_domain",Exception,"not compatible",),@@ -870,7 +870,7 @@ ERROR_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str | None, st{"concept": "test_domain.MyConcept", "content": True},"stuff_name","stuff_code",- ["test_domain"],+ "test_domain",Exception,"native.YesNo",),@@ -890,7 +890,7 @@ ERROR_TEST_CASES: list[tuple[str, StuffContentOrData | DictStuff, str | None, st{"concept": "test_domain.MyConcept", "content": datetime.date(2026, 7, 7)},"stuff_name","stuff_code",- ["test_domain"],+ "test_domain",Exception,"native.Date",),diff --git a/tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py b/tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.pyindex 985b0182d..8cf9426c5 100644--- a/tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py+++ b/tests/unit/pipelex/core/stuffs/test_stuff_factory_implicit_memory.py@@ -142,13 +142,13 @@ class TestStuffFactoryImplicitMemory:class TestStuffFactoryImplicitMemoryWithSearchDomains:- """Test StuffFactory with search_domains parameter.+ """Test StuffFactory with the search_scope parameter.- This tests that search_domain_codes correctly resolves concepts.+ This tests that search_scope correctly resolves concepts."""@pytest.mark.parametrize(- ("test_name", "stuff_content_or_data", "stuff_name", "stuff_code", "search_domain_codes", "expected_stuff"),+ ("test_name", "stuff_content_or_data", "stuff_name", "stuff_code", "search_scope", "expected_stuff"),SEARCH_DOMAIN_TEST_CASES,)def test_search_domain_case(@@ -158,7 +158,7 @@ class TestStuffFactoryImplicitMemoryWithSearchDomains:stuff_content_or_data: StuffContentOrData,stuff_name: str | None,stuff_code: str,- search_domain_codes: list[str],+ search_scope: str,expected_stuff: Stuff,):log.info(f"Testing search domain case: {test_name}")@@ -167,7 +167,7 @@ class TestStuffFactoryImplicitMemoryWithSearchDomains:name=stuff_name,code=stuff_code,stuff_content_or_data=stuff_content_or_data,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,concept_provider=get_concept_library(),)@@ -184,7 +184,7 @@ class TestStuffFactoryImplicitMemoryErrors:"""@pytest.mark.parametrize(- ("test_name", "stuff_content_or_data", "stuff_name", "stuff_code", "search_domain_codes", "expected_exception", "error_match"),+ ("test_name", "stuff_content_or_data", "stuff_name", "stuff_code", "search_scope", "expected_exception", "error_match"),ERROR_TEST_CASES,)def test_error_case(@@ -194,7 +194,7 @@ class TestStuffFactoryImplicitMemoryErrors:stuff_content_or_data: StuffContentOrData,stuff_name: str | None,stuff_code: str,- search_domain_codes: list[str] | None,+ search_scope: str | None,expected_exception: type[Exception],error_match: str,):@@ -206,6 +206,6 @@ class TestStuffFactoryImplicitMemoryErrors:name=stuff_name,code=stuff_code,stuff_content_or_data=stuff_content_or_data,- search_domain_codes=search_domain_codes,+ search_scope=search_scope,concept_provider=get_concept_library(),)diff --git a/tests/unit/pipelex/kernel/test_kernel_boot_contract.py b/tests/unit/pipelex/kernel/test_kernel_boot_contract.pyindex b33847de9..54910cb05 100644--- a/tests/unit/pipelex/kernel/test_kernel_boot_contract.py+++ b/tests/unit/pipelex/kernel/test_kernel_boot_contract.py@@ -154,7 +154,7 @@ _KERNEL_CALL_SCRIPT = textwrap.dedent(return ConceptFactory.make_native_concept(native_concept_code=native_concept)@override- def get_required_concept_from_concept_ref_or_code(self, concept_ref_or_code, *, search_domain_codes=None):+ def get_required_entry_concept(self, concept_ref_or_code, *, search_scope=None):return self.get_required_concept(concept_ref_or_code)@overridediff --git a/tests/unit/pipelex/libraries/test_concept_library_entry_lookup.py b/tests/unit/pipelex/libraries/test_concept_library_entry_lookup.pynew file mode 100644index 000000000..0b2f96e1a--- /dev/null+++ b/tests/unit/pipelex/libraries/test_concept_library_entry_lookup.py@@ -0,0 +1,175 @@+"""The concept entry affordance: how a human-supplied concept string resolves.++Mirrors the pipe-side entry affordance deliberately without sharing code with it (see+wip/pipe-refs/entry-affordance-share-vs-duplicate.md). The rows only discriminate against the+old crate-wide rule when a sibling domain declares the same code — a single-domain fixture+passes under either rule — so most cases here build the two-domain `alpha`/`beta` fixture.+"""++import pytest++from pipelex.core.concepts.concept import Concept+from pipelex.core.concepts.concept_factory import ConceptFactory+from pipelex.core.concepts.exceptions import ConceptLibraryConceptNotFoundError+from pipelex.libraries.concept.concept_library import ConceptLibrary+++def _make_concept(*, code: str, domain_code: str) -> Concept:+ return ConceptFactory.make(+ concept_code=code,+ domain_code=domain_code,+ description=f"{domain_code} {code}",+ structure_class_name="TextContent",+ )+++class TestConceptLibraryEntryLookup:+ # ── Fully-specified refs ────────────────────────────────────────++ def test_exact_ref_hits_directly(self):+ library = ConceptLibrary.make_empty()+ memo_alpha = _make_concept(code="Memo", domain_code="alpha")+ library.add_new_concept(concept=memo_alpha)+ assert library.get_optional_entry_concept("alpha.Memo") is memo_alpha++ def test_exact_ref_wrong_domain_returns_none(self):+ library = ConceptLibrary.make_empty()+ library.add_new_concept(concept=_make_concept(code="Memo", domain_code="alpha"))+ assert library.get_optional_entry_concept("beta.Memo") is None++ def test_cross_package_ref_is_a_direct_hit(self):+ library = ConceptLibrary.make_empty()+ dep_memo = _make_concept(code="Memo", domain_code="dep_domain")+ library.add_dependency_concept(alias="lib", concept=dep_memo)+ assert library.get_optional_entry_concept("lib->dep_domain.Memo") is dep_memo+ assert library.get_optional_entry_concept("other->dep_domain.Memo") is None++ # ── Natives resolve first (the standard's step 1) ───────────────++ def test_native_wins_over_a_domain_declared_same_code(self):+ library = ConceptLibrary.make_empty_with_native_concepts()+ library.root["alpha.Text"] = _make_concept(code="Text", domain_code="alpha")+ resolved = library.get_required_entry_concept("Text", search_scope="alpha")+ assert resolved.concept_ref == "native.Text"++ # ── Bare codes: scope preference, then crate-wide unique match ──++ def test_bare_code_own_only_resolves_through_scope(self):+ library = ConceptLibrary.make_empty()+ memo_alpha = _make_concept(code="Memo", domain_code="alpha")+ library.add_new_concept(concept=memo_alpha)+ assert library.get_optional_entry_concept("Memo", search_scope="alpha") is memo_alpha++ def test_bare_code_sibling_only_falls_back_crate_wide(self):+ """A scope that lacks the code no longer kills the lookup (the old multi-domain walk+ raised the first miss as a ConceptLibraryError that bypassed every caller's handler).+ """+ library = ConceptLibrary.make_empty()+ memo_beta = _make_concept(code="Memo", domain_code="beta")+ library.add_new_concept(concept=memo_beta)+ assert library.get_optional_entry_concept("Memo", search_scope="alpha") is memo_beta++ def test_bare_code_both_declare_prefers_the_scope(self):+ """The entry pipe's own domain wins over a same-named sibling — the preference the old+ code expressed with an insert(0) that could never fire, now actually deciding.+ """+ library = ConceptLibrary.make_empty()+ memo_alpha = _make_concept(code="Memo", domain_code="alpha")+ memo_beta = _make_concept(code="Memo", domain_code="beta")+ library.add_new_concept(concept=memo_alpha)+ library.add_new_concept(concept=memo_beta)+ assert library.get_optional_entry_concept("Memo", search_scope="alpha") is memo_alpha+ assert library.get_optional_entry_concept("Memo", search_scope="beta") is memo_beta++ def test_bare_code_ambiguous_without_scope_raises_naming_candidates(self):+ library = ConceptLibrary.make_empty()+ library.add_new_concept(concept=_make_concept(code="Memo", domain_code="alpha"))+ library.add_new_concept(concept=_make_concept(code="Memo", domain_code="beta"))+ with pytest.raises(ConceptLibraryConceptNotFoundError, match="ambiguous") as exc_info:+ library.get_optional_entry_concept("Memo")+ assert "alpha.Memo" in str(exc_info.value)+ assert "beta.Memo" in str(exc_info.value)++ def test_bare_code_nowhere_returns_none_and_required_raises(self):+ library = ConceptLibrary.make_empty()+ assert library.get_optional_entry_concept("Memo") is None+ with pytest.raises(ConceptLibraryConceptNotFoundError, match="not found"):+ library.get_required_entry_concept("Memo")++ def test_invalid_string_raises_the_one_catchable_class(self):+ """Every entry refusal — invalid string included — is ConceptLibraryConceptNotFoundError,+ so the input-shaping boundary catches a single exception class.+ """+ library = ConceptLibrary.make_empty()+ with pytest.raises(ConceptLibraryConceptNotFoundError, match="not a valid"):+ library.get_optional_entry_concept("not_pascal_case")++ # ── Aliased dependency entries ──────────────────────────────────++ def test_crate_wide_search_ignores_aliased_dependency_entries(self):+ """An installed package must not make a host concept's bare code ambiguous."""+ library = ConceptLibrary.make_empty()+ host_memo = _make_concept(code="Memo", domain_code="alpha")+ library.add_new_concept(concept=host_memo)+ library.add_dependency_concept(alias="lib", concept=_make_concept(code="Memo", domain_code="vendor"))+ assert library.get_optional_entry_concept("Memo") is host_memo++ def test_bare_code_with_aliased_scope_reaches_the_dependency_concept(self):+ """Package-scoped preference: when the entry pipe came from a dependency, its scope+ carries the alias (`lib->dep_domain`), so the dependency's own concept — keyed under+ the alias and invisible to the crate-wide scan — is a direct scoped hit.+ """+ library = ConceptLibrary.make_empty()+ dep_memo = _make_concept(code="Memo", domain_code="dep_domain")+ library.add_dependency_concept(alias="lib", concept=dep_memo)+ assert library.get_optional_entry_concept("Memo", search_scope="lib->dep_domain") is dep_memo+ # Without the aliased scope, the aliased entry stays out of reach of a bare code.+ assert library.get_optional_entry_concept("Memo") is None++ def test_dotted_ref_with_aliased_scope_reaches_the_dependency_domain(self):+ """A dependency package can span several domains: a dotted ref naming one of them+ resolves through the scope's alias — and the scope wins even when the host declares the+ same `domain.Concept` spelling, mirroring the bare-code arm's precedence. Without an+ aliased scope, the host concept is the only reachable one.+ """+ library = ConceptLibrary.make_empty()+ dep_note = _make_concept(code="Note", domain_code="dep_other")+ library.add_dependency_concept(alias="lib", concept=dep_note)+ assert library.get_optional_entry_concept("dep_other.Note", search_scope="lib->dep_domain") is dep_note+ host_note = _make_concept(code="Note", domain_code="dep_other")+ library.add_new_concept(concept=host_note)+ assert library.get_optional_entry_concept("dep_other.Note", search_scope="lib->dep_domain") is dep_note+ assert library.get_optional_entry_concept("dep_other.Note") is host_note++ def test_bare_code_reaches_a_sibling_domain_of_the_dependency_package(self):+ """A multi-domain dependency keys every concept under its one alias: an entry pipe in one+ of its domains can still resolve a bare code declared in a sibling domain of the same+ package — the package search that the alias-excluding crate-wide scan cannot perform.+ """+ library = ConceptLibrary.make_empty()+ dep_memo = _make_concept(code="Memo", domain_code="dep_b")+ library.add_dependency_concept(alias="lib", concept=dep_memo)+ assert library.get_optional_entry_concept("Memo", search_scope="lib->dep_a") is dep_memo+ # A same-code host concept does not shadow the package's own concept under an aliased scope.+ library.add_new_concept(concept=_make_concept(code="Memo", domain_code="host_domain"))+ assert library.get_optional_entry_concept("Memo", search_scope="lib->dep_a") is dep_memo++ def test_bare_code_ambiguous_within_the_dependency_package_raises(self):+ library = ConceptLibrary.make_empty()+ library.add_dependency_concept(alias="lib", concept=_make_concept(code="Memo", domain_code="dep_a"))+ library.add_dependency_concept(alias="lib", concept=_make_concept(code="Memo", domain_code="dep_b"))+ with pytest.raises(ConceptLibraryConceptNotFoundError, match="ambiguous") as exc_info:+ library.get_optional_entry_concept("Memo", search_scope="lib->dep_c")+ assert "lib->dep_a.Memo" in str(exc_info.value)+ assert "lib->dep_b.Memo" in str(exc_info.value)++ def test_aliased_bare_ref_searches_that_package_only(self):+ """`alias->Concept` is the explicit spelling of the package search: it resolves a bare+ code within the named dependency and never reaches a host concept.+ """+ library = ConceptLibrary.make_empty()+ dep_memo = _make_concept(code="Memo", domain_code="dep_b")+ library.add_dependency_concept(alias="lib", concept=dep_memo)+ library.add_new_concept(concept=_make_concept(code="Memo", domain_code="host_domain"))+ assert library.get_optional_entry_concept("lib->Memo") is dep_memo+ assert library.get_optional_entry_concept("other->Memo") is Nonediff --git a/tests/unit/pipelex/libraries/test_crate_normalization.py b/tests/unit/pipelex/libraries/test_crate_normalization.pyindex 75e97b996..e68e0fe86 100644--- a/tests/unit/pipelex/libraries/test_crate_normalization.py+++ b/tests/unit/pipelex/libraries/test_crate_normalization.py@@ -155,6 +155,46 @@ def _cross_domain_crate() -> LibraryCrate:)+def _closed_all_kinds_crate() -> LibraryCrate:+ """Every controller kind calling a pipe in its OWN domain, so the crate is closed.++ `_cross_domain_crate` used to carry the closure test's coverage of parallel / condition / batch,+ but it stopped being closed the moment bare refs started qualifying to their own domain — that is+ the whole point of it. Dropping it from the parametrize would have quietly narrowed the closure+ walk to sequences, so this fixture takes over: same four kinds, all resolvable in-domain.+ """+ return LibraryCrate(+ pipes={+ "solo.leaf": PipeLLMBlueprint(description="The callee", inputs={"data": "Text"}, output="Text", prompt="Handle $data"),+ "solo.other_leaf": PipeLLMBlueprint(description="A second callee", inputs={"data": "Text"}, output="Text", prompt="Handle $data"),+ "solo.run_all": PipeSequenceBlueprint(description="seq", output="Text", steps=[SubPipeBlueprint(pipe="leaf")]),+ "solo.fan_out": PipeParallelBlueprint(+ description="par",+ inputs={"data": "Text"},+ output="Composite",+ branches=[SubPipeBlueprint(pipe="leaf", result="one"), SubPipeBlueprint(pipe="other_leaf", result="two")],+ ),+ "solo.route": PipeConditionBlueprint(+ description="cond",+ inputs={"data": "Text"},+ output="Text",+ expression="format",+ outcomes={"a": "leaf"},+ default_outcome="other_leaf",+ ),+ "solo.batch_all": PipeBatchBlueprint(+ description="batch",+ inputs={"docs": "Text[]"},+ output="Text[]",+ branch_pipe_code="leaf",+ input_list_name="docs",+ input_item_name="doc",+ ),+ },+ domains={"solo": DomainBlueprint(code="solo", description="Solo domain")},+ )++def _reverse_refinement_chain_crate(size: int) -> LibraryCrate:concepts: dict[str, ConceptBlueprint | str] = {f"scale.Node{index:04d}": ConceptBlueprint(description=f"Node {index}", refines=f"Node{index + 1:04d}") for index in range(size - 1)@@ -203,14 +243,15 @@ class TestCrateNormalization:assert isinstance(pipeline, PipeSequenceBlueprint)assert pipeline.steps[0].pipe == "scoring.compute_score"- @pytest.mark.parametrize("crate_factory", [_authored_crate, _cross_domain_crate])+ @pytest.mark.parametrize("crate_factory", [_authored_crate, _closed_all_kinds_crate])def test_normalized_crate_is_closed_over_its_pipe_refs(self, crate_factory: Callable[[], LibraryCrate]):"""Every in-body pipe ref of a normalized crate names a pipe the crate actually holds.Driven off `pipe_dependencies` rather than a hand-walk of the controller kinds, so a new kind —- or a new `_qualify_pipe_ref` call site on an existing one — is covered the day it lands. An open- ref is silent: the crate hashes content nobody can resolve, and a round-trip through- `load_from_crate` dies with `PipeNotFoundError` at run time instead of at normalization.+ or a new `crate_qualification._qualify_pipe_ref` call site on an existing one — is covered the+ day it lands. An open ref is silent: the crate hashes content nobody can resolve, and a+ round-trip through `load_from_crate` dies with `PipeNotFoundError` at run time instead of at+ normalization."""result = normalize_crate(crate_factory(), mthds_version=MTHDS_TEST_VERSION)dangling = {@@ -221,29 +262,47 @@ class TestCrateNormalization:}assert not dangling- def test_bare_cross_domain_pipe_refs_resolve_to_the_declaring_domain(self):- """A bare ref to a sibling domain's pipe is the shape the live `PipeLibrary` resolves.+ def test_bare_pipe_refs_qualify_to_their_own_domain_not_a_siblings(self):+ """Resolution row `sibling-only`: the ref qualifies to its OWN domain even when only a sibling+ declares the code — every controller kind, since branches and batch refs are the ones a+ hand-written pass forgets.- `get_optional_pipe` falls back to a search across every domain, so this bundle runs. Prefixing- the owner domain would name `orchestrator.present_as_markdown`, which does not exist.+ This crate is the authored shape that used to work by falling through to another domain. It+ now produces refs naming pipes that do not exist, and that is the intended answer: the ref was+ never resolvable under the rule, and dependency validation is where the user is told so. The+ fixture needs two domains to say anything at all — in a single-domain crate, owner-domain+ qualification and the deleted crate-wide search agree on every input."""result = normalize_crate(_cross_domain_crate(), mthds_version=MTHDS_TEST_VERSION)sequence = result.pipes["orchestrator.run_all"]assert isinstance(sequence, PipeSequenceBlueprint)- assert sequence.steps[0].pipe == "presentation.present_as_markdown"+ assert sequence.steps[0].pipe == "orchestrator.present_as_markdown"parallel = result.pipes["orchestrator.fan_out"]assert isinstance(parallel, PipeParallelBlueprint)- assert [branch.pipe for branch in parallel.branches] == ["presentation.present_as_markdown", "presentation.render_html"]+ assert [branch.pipe for branch in parallel.branches] == ["orchestrator.present_as_markdown", "orchestrator.render_html"]condition = result.pipes["orchestrator.route"]assert isinstance(condition, PipeConditionBlueprint)- assert condition.outcomes == {"markdown": "presentation.present_as_markdown"}- assert condition.default_outcome == "presentation.render_html"+ assert condition.outcomes == {"markdown": "orchestrator.present_as_markdown"}+ assert condition.default_outcome == "orchestrator.render_html"batch = result.pipes["orchestrator.batch_all"]assert isinstance(batch, PipeBatchBlueprint)- assert batch.branch_pipe_code == "presentation.present_as_markdown"+ assert batch.branch_pipe_code == "orchestrator.present_as_markdown"++ # The sibling's own pipes are untouched: qualification is per declaring pipe, not global.+ assert "presentation.present_as_markdown" in result.pipes++ def test_own_domain_ref_resolves(self):+ """Resolution row `own-only`: a bare ref to a pipe the owner domain declares still resolves,+ and the resulting crate is closed over it.+ """+ result = normalize_crate(_authored_crate(), mthds_version=MTHDS_TEST_VERSION)+ pipeline = result.pipes["scoring.pipeline"]+ assert isinstance(pipeline, PipeSequenceBlueprint)+ assert pipeline.steps[0].pipe == "scoring.compute_score"+ assert "scoring.compute_score" in result.pipesdef test_special_outcomes_are_left_alone(self):"""`fail` / `continue` are outcomes, not pipe refs — they must survive un-qualified."""@@ -253,26 +312,59 @@ class TestCrateNormalization:assert condition.outcomes == {"stop": SpecialOutcome.FAIL}assert condition.default_outcome == SpecialOutcome.CONTINUE- def test_ambiguous_bare_pipe_ref_raises(self):- """Two domains declaring the same code: the live library raises, so normalization raises too.+ def test_own_domain_wins_when_two_domains_declare_the_code(self):+ """Resolution row `both-declare`: the owner's own pipe, with no ambiguity error.- Silently preferring the owner domain would produce a crate that resolves while an interpreted- run of the same library dies on the ambiguity — a new disagreement, not a fix.+ Ambiguity was a *consequence* of searching. Nothing is searched for now, so a second domain+ declaring the same code is simply irrelevant to how the first domain's refs resolve — which is+ the contextual stability this rule buys: installing or writing an unrelated `present_as_markdown`+ elsewhere cannot change what an existing pipe means."""crate = _cross_domain_crate()- crate.pipes["duplicates.present_as_markdown"] = PipeLLMBlueprint(- description="A second pipe sharing the callee's code",+ crate.pipes["orchestrator.present_as_markdown"] = PipeLLMBlueprint(+ description="The orchestrator's own presenter",inputs={"data": "Text"},output="Text",prompt="Present $data",)- crate.domains["duplicates"] = DomainBlueprint(code="duplicates", description="Duplicates domain")+ crate.pipes["orchestrator.render_html"] = PipeLLMBlueprint(+ description="The orchestrator's own renderer",+ inputs={"data": "Text"},+ output="Text",+ prompt="Render $data",+ )+ result = normalize_crate(crate, mthds_version=MTHDS_TEST_VERSION)- with pytest.raises(CrateNormalizationError, match="Ambiguous pipe ref 'present_as_markdown'"):- normalize_crate(crate, mthds_version=MTHDS_TEST_VERSION)+ # All four kinds, matching the sibling-only row: a cross-domain fall-through would hide in a+ # branch, an outcome or a batch ref just as readily as in a step, so a row that checks only+ # steps is a row that only half-holds.+ sequence = result.pipes["orchestrator.run_all"]+ assert isinstance(sequence, PipeSequenceBlueprint)+ assert sequence.steps[0].pipe == "orchestrator.present_as_markdown"++ parallel = result.pipes["orchestrator.fan_out"]+ assert isinstance(parallel, PipeParallelBlueprint)+ assert [branch.pipe for branch in parallel.branches] == ["orchestrator.present_as_markdown", "orchestrator.render_html"]- def test_unresolvable_bare_pipe_ref_raises(self):- """A bare ref matching no pipe in the crate is surfaced, not silently qualified into a dangling ref."""+ condition = result.pipes["orchestrator.route"]+ assert isinstance(condition, PipeConditionBlueprint)+ assert condition.outcomes == {"markdown": "orchestrator.present_as_markdown"}+ assert condition.default_outcome == "orchestrator.render_html"++ batch = result.pipes["orchestrator.batch_all"]+ assert isinstance(batch, PipeBatchBlueprint)+ assert batch.branch_pipe_code == "orchestrator.present_as_markdown"++ # And the sibling's own pipes are untouched — qualification is per declaring pipe.+ assert "presentation.present_as_markdown" in result.pipes++ def test_bare_pipe_ref_matching_nothing_is_qualified_not_raised(self):+ """Resolution row `nowhere`: the pass qualifies and moves on; it does not check existence.++ It cannot: it sees one load batch, and a batch may legitimately reference a pipe a prior batch+ put in the same domain (a `-L` directory, a secondary load). Only dependency validation, which+ sees the whole live library, can tell a forward reference from a typo.+ """crate = LibraryCrate(pipes={"orchestrator.run_all": PipeSequenceBlueprint(@@ -283,8 +375,10 @@ class TestCrateNormalization:},domains={"orchestrator": DomainBlueprint(code="orchestrator", description="Orchestrator domain")},)- with pytest.raises(CrateNormalizationError, match="resolves to no pipe in the crate"):- normalize_crate(crate, mthds_version=MTHDS_TEST_VERSION)+ result = normalize_crate(crate, mthds_version=MTHDS_TEST_VERSION)+ sequence = result.pipes["orchestrator.run_all"]+ assert isinstance(sequence, PipeSequenceBlueprint)+ assert sequence.steps[0].pipe == "orchestrator.nowhere_to_be_found"def test_refinement_with_structured_base_is_flattened(self):"""Refining a concept with a structure adopts that (qualified) structure and drops `refines`."""diff --git a/tests/unit/pipelex/libraries/test_crate_qualification.py b/tests/unit/pipelex/libraries/test_crate_qualification.pynew file mode 100644index 000000000..02ebd6f3b--- /dev/null+++ b/tests/unit/pipelex/libraries/test_crate_qualification.py@@ -0,0 +1,269 @@+"""Unit tests for `qualify_crate` — that it rewrites what it claims to, and only that.++The *resolution rule* (which pipe a bare ref resolves to when several domains declare the code, which+refs are left alone) is covered through `normalize_crate` in `test_crate_normalization.py` and stays+there. What lives here is the standalone pass's own contract: that every ref kind it advertises+actually comes back rewritten, that it does not touch its input, and that meeting it twice is the+same as meeting it once.++That first one is not a formality. A test module built around a fixture full of bare refs can assert+nothing about the *output* and still go green against a pass that does nothing at all — the envelope+looks right, the input is untouched, and two no-ops compare equal. Every test below reads a+qualified ref out of the result for that reason.+"""++import pytest++from pipelex.core.concepts.concept_blueprint import ConceptBlueprint+from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint, ConceptStructureBlueprintFieldType+from pipelex.core.domains.domain_blueprint import DomainBlueprint+from pipelex.libraries.crate_qualification import QualifiedCrateContent, qualify_crate+from pipelex.libraries.exceptions import CrateNormalizationError+from pipelex.libraries.library_crate import LibraryCrate+from pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint+from pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprint+from pipelex.pipe_controllers.condition.special_outcome import SpecialOutcome+from pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprint+from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint+from pipelex.pipe_controllers.sub_pipe_blueprint import SubPipeBlueprint+from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint+++def _crate() -> LibraryCrate:+ """A crate carrying one bare ref of every kind the pass advertises."""+ return LibraryCrate(+ concepts={+ "alpha.Category": "a category",+ "alpha.Report": ConceptBlueprint(+ description="a report",+ structure={+ "label": ConceptStructureBlueprint(+ description="the label",+ type=ConceptStructureBlueprintFieldType.CONCEPT,+ concept_ref="Category",+ ),+ "tags": ConceptStructureBlueprint(+ description="the tags",+ type=ConceptStructureBlueprintFieldType.LIST,+ item_type=ConceptStructureBlueprintFieldType.CONCEPT,+ item_concept_ref="Category",+ ),+ },+ ),+ "alpha.Detailed": ConceptBlueprint(description="a detailed report", refines="Report"),+ },+ pipes={+ "alpha.leaf": PipeLLMBlueprint(description="leaf", inputs={"item": "Category"}, output="Report", prompt="use $item"),+ "alpha.seq": PipeSequenceBlueprint(description="seq", output="Report", steps=[SubPipeBlueprint(pipe="leaf")]),+ "alpha.par": PipeParallelBlueprint(+ description="par",+ output="Composite",+ branches=[SubPipeBlueprint(pipe="leaf", result="one")],+ ),+ "alpha.cond": PipeConditionBlueprint(+ description="cond",+ output="Report",+ expression="x",+ outcomes={"hit": "leaf"},+ default_outcome="leaf",+ ),+ "alpha.batched": PipeBatchBlueprint(+ description="batch",+ inputs={"items": "Category[]"},+ output="Report[]",+ branch_pipe_code="leaf",+ input_list_name="items",+ input_item_name="item",+ ),+ },+ domains={"alpha": DomainBlueprint(code="alpha", description="alpha domain")},+ )+++def _report_structure(result: QualifiedCrateContent) -> dict[str, ConceptStructureBlueprint]:+ report = result.concepts["alpha.Report"]+ assert isinstance(report, ConceptBlueprint)+ assert isinstance(report.structure, dict)+ return {name: field for name, field in report.structure.items() if isinstance(field, ConceptStructureBlueprint)}+++class TestCrateQualification:+ # --- every ref kind the pass advertises, read back out of the result ---++ def test_concept_refines(self):+ detailed = qualify_crate(_crate()).concepts["alpha.Detailed"]+ assert isinstance(detailed, ConceptBlueprint)+ assert detailed.refines == "alpha.Report"++ def test_structure_field_refs(self):+ structure = _report_structure(qualify_crate(_crate()))+ assert structure["label"].concept_ref == "alpha.Category"+ assert structure["tags"].item_concept_ref == "alpha.Category"++ def test_pipe_io_refs(self):+ leaf = qualify_crate(_crate()).pipes["alpha.leaf"]+ assert leaf.inputs == {"item": "alpha.Category"}+ assert leaf.output == "alpha.Report"++ def test_multiplicity_markers_survive_qualification(self):+ batched = qualify_crate(_crate()).pipes["alpha.batched"]+ assert batched.inputs == {"items": "alpha.Category[]"}+ assert batched.output == "alpha.Report[]"++ def test_sequence_step_refs(self):+ sequence = qualify_crate(_crate()).pipes["alpha.seq"]+ assert isinstance(sequence, PipeSequenceBlueprint)+ assert [step.pipe for step in sequence.steps] == ["alpha.leaf"]++ def test_parallel_branch_refs(self):+ parallel = qualify_crate(_crate()).pipes["alpha.par"]+ assert isinstance(parallel, PipeParallelBlueprint)+ assert [branch.pipe for branch in parallel.branches] == ["alpha.leaf"]++ def test_condition_outcome_refs(self):+ condition = qualify_crate(_crate()).pipes["alpha.cond"]+ assert isinstance(condition, PipeConditionBlueprint)+ assert condition.outcomes == {"hit": "alpha.leaf"}+ assert condition.default_outcome == "alpha.leaf"++ def test_batch_branch_ref(self):+ batched = qualify_crate(_crate()).pipes["alpha.batched"]+ assert isinstance(batched, PipeBatchBlueprint)+ assert batched.branch_pipe_code == "alpha.leaf"++ def test_string_described_concept_passes_through(self):+ """A description holds no refs — it must come back as the same string, not a blueprint."""+ assert qualify_crate(_crate()).concepts["alpha.Category"] == "a category"++ # --- the rule itself: a bare ref is its own domain's, whoever else declares the code ---++ def test_bare_pipe_ref_is_the_owner_domains_even_when_only_a_sibling_declares_it(self):+ """The single-domain fixture above cannot fail this — it needs a competing sibling declaration.++ Owner-domain qualification and the crate-wide search it replaced agree on every input where+ only one domain exists, so every other test in this module would pass just as happily under+ the deleted rule. This one is what pins the rule that was actually chosen.+ """+ crate = _crate()+ crate.pipes["beta.only_here"] = PipeLLMBlueprint(description="beta's pipe", output="Text", prompt="go")+ crate.pipes["alpha.calls_sibling"] = PipeSequenceBlueprint(+ description="calls a code only beta declares",+ output="Text",+ steps=[SubPipeBlueprint(pipe="only_here")],+ )+ crate.domains["beta"] = DomainBlueprint(code="beta", description="beta domain")++ sequence = qualify_crate(crate).pipes["alpha.calls_sibling"]+ assert isinstance(sequence, PipeSequenceBlueprint)+ assert sequence.steps[0].pipe == "alpha.only_here"++ def test_a_second_domain_declaring_the_code_is_not_an_ambiguity(self):+ """Ambiguity was a consequence of searching. Nothing is searched for, so nothing is ambiguous —+ an unrelated domain declaring `leaf` cannot change what `alpha.seq` means.+ """+ crate = _crate()+ crate.pipes["beta.leaf"] = PipeLLMBlueprint(description="beta's own leaf", output="Text", prompt="go")+ crate.domains["beta"] = DomainBlueprint(code="beta", description="beta domain")++ sequence = qualify_crate(crate).pipes["alpha.seq"]+ assert isinstance(sequence, PipeSequenceBlueprint)+ assert sequence.steps[0].pipe == "alpha.leaf"++ def test_cross_package_refs_pass_through_untouched(self):+ """`alias->…` refs are the packaging project's to canonicalize; this pass must not touch them."""+ crate = _crate()+ crate.pipes["alpha.calls_dependency"] = PipeSequenceBlueprint(+ description="calls into a dependency",+ output="Text",+ steps=[SubPipeBlueprint(pipe="dep->helper")],+ )++ sequence = qualify_crate(crate).pipes["alpha.calls_dependency"]+ assert isinstance(sequence, PipeSequenceBlueprint)+ assert sequence.steps[0].pipe == "dep->helper"++ def test_a_step_naming_a_pipe_called_continue_is_still_qualified(self):+ """`continue` is a legal snake_case pipe code, so it is only special in a condition outcome.++ Exempting it everywhere — which is what the pass did until a review caught it — leaves a real+ reference unqualified, and under the strict lookup an unqualified ref resolves to nothing.+ """+ crate = _crate()+ crate.pipes["alpha.continue"] = PipeLLMBlueprint(description="a pipe genuinely named continue", output="Text", prompt="go")+ crate.pipes["alpha.calls_continue"] = PipeSequenceBlueprint(+ description="a step naming that pipe",+ output="Text",+ steps=[SubPipeBlueprint(pipe="continue")],+ )++ sequence = qualify_crate(crate).pipes["alpha.calls_continue"]+ assert isinstance(sequence, PipeSequenceBlueprint)+ assert sequence.steps[0].pipe == "alpha.continue"++ def test_special_outcomes_pass_through_untouched(self):+ """`fail` / `continue` are outcomes, not pipe refs — in a condition, and only there."""+ crate = _crate()+ crate.pipes["alpha.route_special"] = PipeConditionBlueprint(+ description="route to special outcomes",+ inputs={"data": "Category"},+ output="Report",+ expression="x",+ outcomes={"stop": SpecialOutcome.FAIL},+ default_outcome=SpecialOutcome.CONTINUE,+ )++ condition = qualify_crate(crate).pipes["alpha.route_special"]+ assert isinstance(condition, PipeConditionBlueprint)+ assert condition.outcomes == {"stop": SpecialOutcome.FAIL}+ assert condition.default_outcome == SpecialOutcome.CONTINUE++ # --- purity ---++ def test_input_crate_is_not_mutated(self):+ """The pass runs on a crate the caller still holds — in the library build, one it has cached."""+ crate = _crate()+ qualify_crate(crate)++ sequence = crate.pipes["alpha.seq"]+ assert isinstance(sequence, PipeSequenceBlueprint)+ assert sequence.steps[0].pipe == "leaf"+ assert crate.pipes["alpha.leaf"].output == "Report"+ detailed = crate.concepts["alpha.Detailed"]+ assert isinstance(detailed, ConceptBlueprint)+ assert detailed.refines == "Report"++ def test_is_idempotent(self):+ """Qualifying an already-qualified ref must be a no-op — `alpha.leaf` must not become+ `alpha.alpha.leaf`. The pass runs in more than one place, so a crate can meet it twice.+ """+ once = qualify_crate(_crate())+ twice = qualify_crate(_crate().model_copy(update={"concepts": once.concepts, "pipes": once.pipes}))+ assert twice.concepts == once.concepts+ assert twice.pipes == once.pipes+ # Anti-vacuity: two no-ops would also compare equal, so pin that the compared value is the+ # qualified one rather than whatever went in.+ second_pass_sequence = twice.pipes["alpha.seq"]+ assert isinstance(second_pass_sequence, PipeSequenceBlueprint)+ assert second_pass_sequence.steps[0].pipe == "alpha.leaf"++ # --- rejections, raised by the pass itself rather than through the normalizer ---++ @pytest.mark.parametrize(+ ("crate", "expected_message"),+ [+ pytest.param(+ LibraryCrate(concepts={"Bare": "an unqualified key"}),+ "not domain-qualified",+ id="unqualified-concept-key",+ ),+ pytest.param(+ LibraryCrate(pipes={"bare": PipeLLMBlueprint(description="bare", output="Text", prompt="go")}),+ "not domain-qualified",+ id="unqualified-pipe-key",+ ),+ ],+ )+ def test_rejects(self, crate: LibraryCrate, expected_message: str):+ """The pass raises on its own, not only through the normalizer that used to host it."""+ with pytest.raises(CrateNormalizationError, match=expected_message):+ qualify_crate(crate)diff --git a/tests/unit/pipelex/libraries/test_dependency_ref_qualification.py b/tests/unit/pipelex/libraries/test_dependency_ref_qualification.pynew file mode 100644index 000000000..3bf5d93ed--- /dev/null+++ b/tests/unit/pipelex/libraries/test_dependency_ref_qualification.py@@ -0,0 +1,104 @@+"""A dependency package's own in-body refs are qualified to the dependency's own domain.++The dependency loader builds its own crate and its own child library — it does not go through+`load_from_crate` — so it is a second, independent crate-to-pipes path, and the qualification pass+has to be wired into both. A miss on this one is invisible: every other test in this suite loads a+single-domain library, where a bare ref and an owner-qualified ref name the same pipe, so nothing+observes the difference. Removing the pass from the dependency path reddens *nothing* in the whole+suite without this module — which is exactly why it exists.++What this does NOT claim: that a dependency's bare sub-pipe ref *resolves* at run time. It does not,+and that is a pre-existing defect deferred to the packaging project (execution consults the host+library unconditionally, with no package scope). The claim here is narrower and is the part this+change owns — the ref stored on the built pipe is the dependency's own qualified ref, which is what+makes the eventual package-scoped lookup a direct key hit in the child library.+"""++from pathlib import Path++from mthds.package.dependency_resolver import ResolvedDependency+from mthds.package.manifest.schema import MethodsManifest+from pytest_mock import MockerFixture++from pipelex.interpreter_hub import get_library_manager+from pipelex.libraries.library_factory import LibraryFactory+from pipelex.libraries.library_manager import LibraryManager++# A dependency whose sequence names its own helper by bare code — the shape a package is authored in.+DEP_WITH_BARE_REF_MTHDS = """\+domain = "charts_dep"+description = "Dependency whose entry pipe calls its own helper by bare code"++[pipe.render_chart]+type = "PipeSequence"+description = "Render a chart."+inputs = { data = "Text" }+output = "Text"+steps = [{ pipe = "prepare_series", result = "series" }]++[pipe.prepare_series]+type = "PipeLLM"+description = "Prepare the series."+inputs = { data = "Text" }+output = "Text"+prompt = "Prepare $data"+"""++# A second domain in the same package, declaring the SAME helper code. Without this the test could+# not tell owner-domain qualification from the crate-wide search it replaced.+DEP_SIBLING_DOMAIN_MTHDS = """\+domain = "tables_dep"+description = "A sibling domain declaring the same helper code"++[pipe.prepare_series]+type = "PipeLLM"+description = "The tables domain's own preparer."+inputs = { data = "Text" }+output = "Text"+prompt = "Prepare $data differently"+"""+++class TestDependencyRefQualification:+ def _load_dependency(self, *, mocker: MockerFixture, tmp_path: Path, file_contents: list[tuple[str, str]]):+ library_manager = get_library_manager()+ library = LibraryFactory.make_empty()+ mocker.patch.object(library_manager, "get_current_library", return_value=library)++ mthds_files: list[Path] = []+ for file_name, content in file_contents:+ mthds_file = tmp_path / file_name+ mthds_file.write_text(content, encoding="utf-8")+ mthds_files.append(mthds_file)++ manager = LibraryManager()+ manager._load_single_dependency( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]+ library=library,+ resolved_dep=ResolvedDependency(+ alias="charts_dep",+ address="github.com/org/charts-dep",+ manifest=MethodsManifest(+ address="github.com/org/charts-dep",+ version="1.0.0",+ description="A charting dep package",+ ),+ package_root=tmp_path,+ mthds_files=mthds_files,+ exported_pipe_codes=None,+ ),+ )+ return library++ def test_dependency_in_body_ref_is_qualified_to_its_own_domain(self, mocker: MockerFixture, tmp_path: Path):+ library = self._load_dependency(+ mocker=mocker,+ tmp_path=tmp_path,+ file_contents=[("charts.mthds", DEP_WITH_BARE_REF_MTHDS), ("tables.mthds", DEP_SIBLING_DOMAIN_MTHDS)],+ )++ child_library = library.dependency_libraries["charts_dep"]+ render_chart = child_library.pipe_library.get_required_pipe("charts_dep.render_chart")++ # Its own domain's helper — not the sibling's, and not a bare code the strict lookup would+ # never resolve.+ assert render_chart.pipe_dependencies() == {"charts_dep.prepare_series"}diff --git a/tests/unit/pipelex/libraries/test_pipe_library_lookup.py b/tests/unit/pipelex/libraries/test_pipe_library_lookup.pyindex 3dde744b8..51b179f8b 100644--- a/tests/unit/pipelex/libraries/test_pipe_library_lookup.py+++ b/tests/unit/pipelex/libraries/test_pipe_library_lookup.py@@ -37,25 +37,18 @@ class TestPipeLibraryLookup:result = library.get_optional_pipe("wrong_domain.compute_score")assert result is None- # ── Bare code fallback ──────────────────────────────────────────+ # ── In-body resolution is strict: no bare-code search ────────────- def test_bare_code_unambiguous(self, mocker: MockerFixture):- """Bare code lookup works when only one pipe has that code."""+ def test_bare_code_does_not_resolve_in_body(self, mocker: MockerFixture):+ """A bare code is not an in-body reference the library will chase across domains.++ In-body refs arrive qualified, so a bare one reaching here is not a lookup to be helped along.+ Searching for it is what let a pipe reach a pipe no `[exports]` rule had released.+ """library = PipeLibrary.make_empty()mock_pipe = _make_stub_pipe(mocker, code="compute_score", domain_code="scoring")library.root["scoring.compute_score"] = mock_pipe- result = library.get_optional_pipe("compute_score")- assert result is mock_pipe-- def test_bare_code_ambiguous_raises(self, mocker: MockerFixture):- """Bare code lookup raises PipeLibraryError when multiple domains have the same code."""- library = PipeLibrary.make_empty()- pipe_scoring = _make_stub_pipe(mocker, code="compute_score", domain_code="scoring")- pipe_analytics = _make_stub_pipe(mocker, code="compute_score", domain_code="analytics")- library.root["scoring.compute_score"] = pipe_scoring- library.root["analytics.compute_score"] = pipe_analytics- with pytest.raises(PipeLibraryError, match="Ambiguous pipe code"):- library.get_optional_pipe("compute_score")+ assert library.get_optional_pipe("compute_score") is Nonedef test_bare_code_no_match_returns_none(self):"""Bare code lookup returns None when no pipe has that code."""@@ -63,6 +56,73 @@ class TestPipeLibraryLookup:result = library.get_optional_pipe("nonexistent")assert result is None+ # ── The entry affordance: a code a human typed ───────────────────++ def test_entry_pipe_exact_ref_hits_directly(self, mocker: MockerFixture):+ """A fully-qualified code goes straight through, no search."""+ library = PipeLibrary.make_empty()+ mock_pipe = _make_stub_pipe(mocker, code="compute_score", domain_code="scoring")+ library.root["scoring.compute_score"] = mock_pipe+ assert library.get_optional_entry_pipe("scoring.compute_score") is mock_pipe++ def test_entry_pipe_bare_code_matches_across_domains(self, mocker: MockerFixture):+ """`pipelex run compute_score` keeps working: the user is pointing at a pipe, not writing a ref.++ The library holds a second domain with a different code, so the search genuinely has to look+ past a non-match in another domain rather than find the only pipe there is.+ """+ library = PipeLibrary.make_empty()+ mock_pipe = _make_stub_pipe(mocker, code="compute_score", domain_code="scoring")+ library.root["scoring.compute_score"] = mock_pipe+ library.root["analytics.summarize"] = _make_stub_pipe(mocker, code="summarize", domain_code="analytics")+ assert library.get_optional_entry_pipe("compute_score") is mock_pipe++ def test_entry_pipe_ambiguous_bare_code_raises(self, mocker: MockerFixture):+ """Two domains declaring the code: refuse to guess, and name both so the user can pick."""+ library = PipeLibrary.make_empty()+ library.root["scoring.compute_score"] = _make_stub_pipe(mocker, code="compute_score", domain_code="scoring")+ library.root["analytics.compute_score"] = _make_stub_pipe(mocker, code="compute_score", domain_code="analytics")+ with pytest.raises(PipeLibraryError, match="is ambiguous") as exc_info:+ library.get_optional_entry_pipe("compute_score")+ assert "analytics.compute_score" in str(exc_info.value)+ assert "scoring.compute_score" in str(exc_info.value)++ def test_entry_pipe_no_match_returns_none(self):+ library = PipeLibrary.make_empty()+ assert library.get_optional_entry_pipe("nonexistent") is None++ def test_entry_pipe_required_raises_not_found(self):+ library = PipeLibrary.make_empty()+ with pytest.raises(PipeNotFoundError):+ library.get_required_entry_pipe("nonexistent")++ def test_entry_pipe_ignores_aliased_dependency_entries(self, mocker: MockerFixture):+ """An installed package must not make a host pipe's bare code ambiguous.++ Otherwise the entry affordance reintroduces, through its own door, exactly the contextual+ instability the strict in-body rule removes: `pipelex run compute_score` would start failing+ because someone added an unrelated dependency that happens to ship the same code.+ """+ library = PipeLibrary.make_empty()+ host_pipe = _make_stub_pipe(mocker, code="compute_score", domain_code="scoring")+ library.root["scoring.compute_score"] = host_pipe+ library.add_dependency_pipe(alias="lib", pipe=_make_stub_pipe(mocker, code="compute_score", domain_code="vendor"))++ assert library.get_optional_entry_pipe("compute_score") is host_pipe++ def test_entry_pipe_reaches_a_pipe_no_export_released(self, mocker: MockerFixture):+ """The affordance deliberately does not consult `[exports]`.++ Package visibility governs what one method may reference from inside another. A pipe someone+ names by hand at an entry point is not an in-body reference, so the rule does not apply — and+ the docstring says so, which is worth more with a test under it.+ """+ library = PipeLibrary.make_empty()+ unexported = _make_stub_pipe(mocker, code="internal_helper", domain_code="scoring")+ library.root["scoring.internal_helper"] = unexported++ assert library.get_optional_entry_pipe("internal_helper") is unexported+# ── Multi-domain coexistence ────────────────────────────────────def test_multi_domain_coexistence(self, mocker: MockerFixture):diff --git a/tests/unit/pipelex/libraries/test_unresolved_dependency_message_arms.py b/tests/unit/pipelex/libraries/test_unresolved_dependency_message_arms.pynew file mode 100644index 000000000..e4eb18f06--- /dev/null+++ b/tests/unit/pipelex/libraries/test_unresolved_dependency_message_arms.py@@ -0,0 +1,58 @@+"""The guarded arms of ``_describe_unresolved_pipe_dependency`` that the integration pins skip.++``test_unresolved_pipe_ref_message.py`` covers the bare-qualified, suggestion, no-candidate, and+malformed arms through real library loads. Two arms remained unpinned, and both exist to STOP the+message from telling a fiction:++- a lookup failure that is not a miss (an ambiguous cross-package code) must hand back the real+ cause, not a well-written "does not exist";+- a ref the author explicitly qualified to ANOTHER domain was never rewritten, so the+ qualification-rule explanation and the candidate suggestion must both stay silent for it.+"""++from pipelex.libraries.library import (+ _describe_unresolved_pipe_dependency, # noqa: PLC2701 # pyright: ignore[reportPrivateUsage]+)+from pipelex.libraries.pipe.exceptions import PipeLibraryError, PipeNotFoundError+++class TestUnresolvedDependencyMessageArms:+ def test_non_miss_cause_hands_back_the_real_reason(self):+ """An ambiguity is not a miss: no 'does not exist', no qualification story — the cause verbatim."""+ cause = PipeLibraryError(+ "Pipe code 'helper' is ambiguous — it is declared by ['dep->a.helper', 'dep->b.helper']. Name one of them explicitly."+ )+ msg = _describe_unresolved_pipe_dependency(+ referring_pipe_ref="orchestrator.run_all",+ missing_ref="dep->helper",+ candidates={"helper": ["orchestrator.helper"]},+ cause=cause,+ )+ assert "does not exist" not in msg+ assert "resolves inside its own domain" not in msg+ assert "could not resolve its dependency 'dep->helper'" in msg+ assert "is ambiguous" in msg++ def test_author_qualified_other_domain_gets_no_rewrite_story(self):+ """A ref explicitly written to another domain was never rewritten — no rule text, no suggestion."""+ cause = PipeNotFoundError("Pipe 'beta.typo_pipe' not found")+ msg = _describe_unresolved_pipe_dependency(+ referring_pipe_ref="alpha.run_all",+ missing_ref="beta.typo_pipe",+ candidates={"typo_pipe": ["gamma.typo_pipe"]},+ cause=cause,+ )+ assert msg.startswith("Pipe 'alpha.run_all' references 'beta.typo_pipe', which does not exist.")+ assert "resolves inside its own domain" not in msg+ assert "did you mean" not in msg++ def test_cross_package_ref_gets_the_plain_sentence_only(self):+ """An `alias->…` ref is untouched by the pass, so the message must not explain a rewrite."""+ cause = PipeNotFoundError("Pipe 'dep->beta.helper' not found")+ msg = _describe_unresolved_pipe_dependency(+ referring_pipe_ref="alpha.run_all",+ missing_ref="dep->beta.helper",+ candidates={"helper": ["alpha.helper"]},+ cause=cause,+ )+ assert msg == "Pipe 'alpha.run_all' references 'dep->beta.helper', which does not exist."diff --git a/tests/unit/pipelex/pipe_controllers/condition/test_pipe_condition_needed_inputs.py b/tests/unit/pipelex/pipe_controllers/condition/test_pipe_condition_needed_inputs.pyindex 7d5acf47e..2fbde9f6e 100644--- a/tests/unit/pipelex/pipe_controllers/condition/test_pipe_condition_needed_inputs.py+++ b/tests/unit/pipelex/pipe_controllers/condition/test_pipe_condition_needed_inputs.py@@ -117,7 +117,7 @@ class TestPipeConditionNeededInputs:inputs={"selector": "native.Text"},output=f"{analysis_concept.concept_ref}?",expression="selector",- outcomes={"option_a": "pipe_a", "option_b": "pipe_b"},+ outcomes={"option_a": "test_domain.pipe_a", "option_b": "test_domain.pipe_b"},default_outcome=SpecialOutcome.CONTINUE,)@@ -184,7 +184,7 @@ class TestPipeConditionNeededInputs:inputs={"mode": "native.Text"},output=f"{result_concept.concept_ref}?",expression="mode",- outcomes={"batch": "pipe_with_list"},+ outcomes={"batch": "test_domain.pipe_with_list"},default_outcome=SpecialOutcome.CONTINUE,)@@ -269,7 +269,7 @@ class TestPipeConditionOutputValidation:inputs={"selector": "native.Text"},output=f"{output_concept.concept_ref}?",expression="selector",- outcomes={"a": "pipe_a", "b": "pipe_b"},+ outcomes={"a": "test_domain.pipe_a", "b": "test_domain.pipe_b"},default_outcome=SpecialOutcome.CONTINUE,)@@ -337,7 +337,7 @@ class TestPipeConditionOutputValidation:inputs={"selector": "native.Text"},output=f"{NativeConceptCode.DYNAMIC.concept_ref}?",expression="selector",- outcomes={"a": "pipe_a", "b": "pipe_b"},+ outcomes={"a": "test_domain.pipe_a", "b": "test_domain.pipe_b"},default_outcome=SpecialOutcome.CONTINUE,)@@ -396,7 +396,7 @@ class TestPipeConditionOutputValidation:inputs={"selector": "native.Text"},output=f"{NativeConceptCode.ANYTHING.concept_ref}?",expression="selector",- outcomes={"a": "pipe_a"},+ outcomes={"a": "test_domain.pipe_a"},default_outcome=SpecialOutcome.CONTINUE,)@@ -472,7 +472,7 @@ class TestPipeConditionOutputValidation:inputs={"selector": "native.Text"},output=f"{NativeConceptCode.ANYTHING.concept_ref}?",expression="selector",- outcomes={"a": "pipe_a", "b": "pipe_b"},+ outcomes={"a": "test_domain.pipe_a", "b": "test_domain.pipe_b"},default_outcome=SpecialOutcome.CONTINUE,)@@ -545,7 +545,7 @@ class TestPipeConditionOutputValidation:inputs={"selector": "native.Text"},output=f"{output_a.concept_ref}?",expression="selector",- outcomes={"a": "pipe_a", "b": "pipe_b"},+ outcomes={"a": "test_domain.pipe_a", "b": "test_domain.pipe_b"},default_outcome=SpecialOutcome.CONTINUE,)@@ -622,7 +622,7 @@ class TestPipeConditionOutputValidation:inputs={"selector": "native.Text"},output=f"{NativeConceptCode.TEXT.concept_ref}?",expression="selector",- outcomes={"a": "pipe_a", "b": "pipe_b"},+ outcomes={"a": "test_domain.pipe_a", "b": "test_domain.pipe_b"},default_outcome=SpecialOutcome.CONTINUE,)@@ -746,7 +746,7 @@ class TestPipeConditionSpecialOutcomes:output=f"{output_concept.concept_ref}?",expression="action",outcomes={- "process": "process_pipe", # Actual pipe+ "process": "test_domain.process_pipe", # Actual pipe"skip": SpecialOutcome.CONTINUE, # Special outcome},default_outcome=SpecialOutcome.CONTINUE,@@ -809,7 +809,7 @@ class TestPipeConditionSpecialOutcomes:output=output_concept.concept_ref,expression="status",outcomes={- "success": "success_pipe", # Actual pipe+ "success": "test_domain.success_pipe", # Actual pipe"error": SpecialOutcome.FAIL, # Special outcome},default_outcome=SpecialOutcome.FAIL,@@ -893,7 +893,7 @@ class TestPipeConditionSpecialOutcomes:output=f"{output_concept.concept_ref}?",expression="mode",outcomes={- "run": "real_pipe",+ "run": "test_domain.real_pipe","skip": SpecialOutcome.CONTINUE,"abort": SpecialOutcome.FAIL,},@@ -907,7 +907,7 @@ class TestPipeConditionSpecialOutcomes:)# pipe_dependencies() should only contain actual pipes, not special outcomes- assert pipe_condition.pipe_dependencies() == {"real_pipe"}+ assert pipe_condition.pipe_dependencies() == {"test_domain.real_pipe"}assert SpecialOutcome.CONTINUE not in pipe_condition.pipe_dependencies()assert SpecialOutcome.FAIL not in pipe_condition.pipe_dependencies()diff --git a/tests/unit/pipelex/pipe_operators/pipe_func/test_direct_executor_workdir.py b/tests/unit/pipelex/pipe_operators/pipe_func/test_direct_executor_workdir.pyindex c74f06ae5..36aedc440 100644--- a/tests/unit/pipelex/pipe_operators/pipe_func/test_direct_executor_workdir.py+++ b/tests/unit/pipelex/pipe_operators/pipe_func/test_direct_executor_workdir.py@@ -136,7 +136,9 @@ class TestDirectExecutorWorkdir:request = PipeFuncExecutionRequest(crate=crate_with_func,working_memory_raw=WorkingMemoryFactory.make_empty().dump_for_transport(),- pipe_code="greet",+ # Qualified, as PipeFunc now sends it: the transported library is keyed by pipe_ref and+ # its lookup is strict, so a bare code would not resolve on the far side.+ pipe_code="greet_demo.greet",function_name="greet_it",job_metadata=JobMetadata(user_id="user", pipeline_run_id="run"),pipe_run_params=PipeRunParams(run_mode=PipeRunMode.DRY, pipe_stack_limit=10, batch_max_concurrency=None),diff --git a/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_transported_ref.py b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_transported_ref.pynew file mode 100644index 000000000..0022236b9--- /dev/null+++ b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_transported_ref.py@@ -0,0 +1,65 @@+"""The PipeFunc operator hands its executor the QUALIFIED ref, never the bare code.++The transported path (Daytona sandbox, Temporal activity) resolves that value against the+transported library, which is keyed by ``pipe_ref`` — under the strict lookup a bare code resolves+to nothing there. The in-process ``DirectPipeFuncExecutor`` ignores the argument entirely, so no+end-to-end test in this repo reddens if the operator regresses to sending ``self.code``: this pin is+the only in-repo guard on the producer side of that contract.+"""++from collections.abc import Callable++import pytest+from pytest_mock import MockerFixture++from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory+from pipelex.core.stuffs.text_content import TextContent+from pipelex.pipe_machinery.pipe_factory import PipeFactory+from pipelex.pipe_operators.func.pipe_func import PipeFunc+from pipelex.pipe_operators.func.pipe_func_blueprint import PipeFuncBlueprint+from pipelex.pipe_operators.func.pipe_func_executor_protocol import PipeFuncExecutionResult+from pipelex.pipe_run.pipe_run_params import PipeRunParams+from pipelex.system.job_metadata import JobMetadata+from pipelex.system.pipe_run_mode import PipeRunMode+from pipelex.system.registries.func_registry import func_registry+++def transported_ref_probe_func(working_memory: WorkingMemory) -> TextContent: # noqa: ARG001 # pyright: ignore[reportUnusedParameter]+ """Registered in the test so the PipeFunc validators accept the blueprint in local mode."""+ return TextContent(text="probe")+++class TestPipeFuncTransportedRef:+ @pytest.mark.asyncio+ async def test_live_run_transports_the_qualified_ref(+ self,+ load_empty_library: Callable[[], str],+ mocker: MockerFixture,+ ):+ load_empty_library()+ func_registry.register_function(transported_ref_probe_func, name="transported_ref_probe_func")+ blueprint = PipeFuncBlueprint(+ description="Producer-side pin: the executor must receive the qualified ref.",+ inputs={},+ output="native.Text",+ function_name="transported_ref_probe_func",+ )+ the_pipe_func = PipeFactory[PipeFunc].make_from_blueprint(+ domain_code="func_probe_domain",+ pipe_code="probe_pipe",+ blueprint=blueprint,+ )++ executor = mocker.Mock()+ executor.run_pipe_func = mocker.AsyncMock(return_value=PipeFuncExecutionResult(content=TextContent(text="probe")))+ mocker.patch("pipelex.pipe_operators.func.pipe_func.get_pipe_func_executor", return_value=executor)++ await the_pipe_func._live_run_operator_pipe( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]+ job_metadata=JobMetadata(user_id="user", pipeline_run_id="run"),+ working_memory=WorkingMemoryFactory.make_empty(),+ pipe_run_params=PipeRunParams(run_mode=PipeRunMode.LIVE, pipe_stack_limit=10, batch_max_concurrency=None),+ )++ # The discriminating assertion: `self.code` would send the bare 'probe_pipe'.+ assert executor.run_pipe_func.call_args.kwargs["pipe_code"] == "func_probe_domain.probe_pipe"diff --git a/tests/unit/pipelex/pipeline/fixes/test_fix_loop_multi_file_scoping.py b/tests/unit/pipelex/pipeline/fixes/test_fix_loop_multi_file_scoping.pyindex c5271f1ba..30c81528c 100644--- a/tests/unit/pipelex/pipeline/fixes/test_fix_loop_multi_file_scoping.py+++ b/tests/unit/pipelex/pipeline/fixes/test_fix_loop_multi_file_scoping.py@@ -78,6 +78,35 @@ output = "Text"prompt = "Write about $topic""""+_DOTTED_SAME_DOMAIN_A_MTHDS = """domain = "rebuild_same"++[pipe."rebuild_same.shared"]+type = "PipeLLM"+description = "A dotted declaration that strips to a bare shared code."+inputs = { topic = "Text" }+output = "Text"+prompt = "Write about $topic"+"""++_DOTTED_SAME_DOMAIN_B_MTHDS = """domain = "rebuild_same"++[pipe."rebuild_same.shared"]+type = "PipeLLM"+description = "The same dotted declaration in a second file of the SAME domain."+inputs = { topic = "Text" }+output = "Text"+prompt = "Write about $topic"+"""++_DOMAINLESS_SHARED_MTHDS = """+[pipe.shared]+type = "PipeLLM"+description = "Declares the colliding code in a file whose domain cannot be read."+inputs = { topic = "Text" }+output = "Text"+prompt = "Write about $topic"+"""+def _seq_output_error_data(*, pipe_code: str, source: str | None) -> PipesAndConceptValidationErrorData:"""One enriched output-mismatch error datum — plans a ``match-sequence-output`` fix."""@@ -414,24 +443,26 @@ class TestFixLoopMultiFileScoping:tmp_path: Path,mocker: MockerFixture,) -> None:- """A rename from round one blocks a sibling rename proposed in round two.+ """A rename from round one blocks a same-domain sibling rename proposed in round two.If the cross-file map were cached before the loop, the second ``strip-namespace`` fix- would not see that round one already created ``[pipe.shared]`` in a sibling bundle.+ would not see that round one already created ``[pipe.shared]`` in a same-domain sibling+ bundle. Both files declare the SAME domain — since the collision scope became+ per-domain, only a same-domain sibling can collide at all."""bundle_path = tmp_path / "entry.mthds"bundle_path.write_text(_MINIMAL_MTHDS, encoding="utf-8")libs_dir = tmp_path / "libs"libs_dir.mkdir()first_path = libs_dir / "a_first.mthds"- first_path.write_text(_DOTTED_SHARED_A_MTHDS, encoding="utf-8")+ first_path.write_text(_DOTTED_SAME_DOMAIN_A_MTHDS, encoding="utf-8")second_path = libs_dir / "b_second.mthds"- second_path.write_text(_DOTTED_SHARED_B_MTHDS, encoding="utf-8")+ second_path.write_text(_DOTTED_SAME_DOMAIN_B_MTHDS, encoding="utf-8")validate_mock = mocker.patch("pipelex.pipeline.fixes.fix_loop.validate_bundle",side_effect=[- _strip_namespace_error(pipe_code="rebuild_a.shared", stripped_pipe_code="shared", source=str(first_path)),- _strip_namespace_error(pipe_code="rebuild_b.shared", stripped_pipe_code="shared", source=str(second_path)),+ _strip_namespace_error(pipe_code="rebuild_same.shared", stripped_pipe_code="shared", source=str(first_path)),+ _strip_namespace_error(pipe_code="rebuild_same.shared", stripped_pipe_code="shared", source=str(second_path)),],)@@ -448,8 +479,84 @@ class TestFixLoopMultiFileScoping:fixed_first = tomlkit.loads(first_path.read_text(encoding="utf-8")).unwrap()unchanged_second = tomlkit.loads(second_path.read_text(encoding="utf-8")).unwrap()assert "shared" in fixed_first["pipe"]- assert "rebuild_a.shared" not in fixed_first["pipe"]- assert "rebuild_b.shared" in unchanged_second["pipe"]+ assert "rebuild_same.shared" not in fixed_first["pipe"]+ assert "rebuild_same.shared" in unchanged_second["pipe"]++ async def test_same_named_renames_in_different_domains_both_apply(+ self,+ tmp_path: Path,+ mocker: MockerFixture,+ ) -> None:+ """Two files in DIFFERENT domains renaming to the same bare code do not collide.++ The library keys pipes by ``domain.code`` and in-body refs never search across domains,+ so ``rebuild_a.shared`` and ``rebuild_b.shared`` coexist. Under the old crate-wide+ collision scope the second rename was dropped and the loop bailed; per-domain scope lets+ both land.+ """+ bundle_path = tmp_path / "entry.mthds"+ bundle_path.write_text(_MINIMAL_MTHDS, encoding="utf-8")+ libs_dir = tmp_path / "libs"+ libs_dir.mkdir()+ first_path = libs_dir / "a_first.mthds"+ first_path.write_text(_DOTTED_SHARED_A_MTHDS, encoding="utf-8")+ second_path = libs_dir / "b_second.mthds"+ second_path.write_text(_DOTTED_SHARED_B_MTHDS, encoding="utf-8")+ validate_mock = mocker.patch(+ "pipelex.pipeline.fixes.fix_loop.validate_bundle",+ side_effect=[+ _strip_namespace_error(pipe_code="rebuild_a.shared", stripped_pipe_code="shared", source=str(first_path)),+ _strip_namespace_error(pipe_code="rebuild_b.shared", stripped_pipe_code="shared", source=str(second_path)),+ None,+ ],+ )++ result = await fix_bundle_file(bundle_path, library_dirs=[libs_dir], max_iterations=3)++ assert result.is_valid is True+ assert result.iterations == 2+ assert validate_mock.await_count == 3+ assert [fix.fix_code for fix in result.fixes_applied] == ["strip-namespace", "strip-namespace"]+ assert [Path(written) for written in result.files_written] == [first_path.resolve(), second_path.resolve()]+ fixed_first = tomlkit.loads(first_path.read_text(encoding="utf-8")).unwrap()+ fixed_second = tomlkit.loads(second_path.read_text(encoding="utf-8")).unwrap()+ assert "shared" in fixed_first["pipe"]+ assert "shared" in fixed_second["pipe"]++ async def test_sibling_without_a_readable_domain_still_collides(+ self,+ tmp_path: Path,+ mocker: MockerFixture,+ ) -> None:+ """A sibling whose ``domain`` cannot be read keeps the conservative cross-domain behavior.++ Per-domain collision scope only relaxes when BOTH files' domains are known: a domainless+ sibling declaring the rename target must still drop the fix (``None`` collides with+ everything). This reddens if the ``domain_unknown`` arm in+ ``_split_cross_file_collisions`` regresses to never-collide.+ """+ bundle_path = tmp_path / "entry.mthds"+ bundle_path.write_text(_MINIMAL_MTHDS, encoding="utf-8")+ libs_dir = tmp_path / "libs"+ libs_dir.mkdir()+ rename_target_path = libs_dir / "a_rename.mthds"+ rename_target_path.write_text(_DOTTED_SHARED_A_MTHDS, encoding="utf-8")+ domainless_path = libs_dir / "b_domainless.mthds"+ domainless_path.write_text(_DOMAINLESS_SHARED_MTHDS, encoding="utf-8")+ mocker.patch(+ "pipelex.pipeline.fixes.fix_loop.validate_bundle",+ side_effect=[+ _strip_namespace_error(pipe_code="rebuild_a.shared", stripped_pipe_code="shared", source=str(rename_target_path)),+ ],+ )++ result = await fix_bundle_file(bundle_path, library_dirs=[libs_dir], max_iterations=3)++ assert result.is_valid is False+ assert result.fixes_applied == []+ assert result.bail_reason is not None+ assert "cross-file collision" in result.bail_reason+ assert "'shared'" in result.bail_reasonasync def test_max_iterations_none_reads_the_config_default(self,diff --git a/wip/drift-contracts/dogfood-log.md b/wip/drift-contracts/dogfood-log.mdindex 5771dedf8..ecbf62c2e 100644--- a/wip/drift-contracts/dogfood-log.md+++ b/wip/drift-contracts/dogfood-log.md@@ -76,3 +76,6 @@ Worth recording as a manifest-rot shape the reference doesn't list. `drift checkThe review proper then ran on rename-only trigger diffs, and the page had already been swept in the same commit. But the page carries a standing rule — *every kernel entry point owes the boot-contract subprocess an arm* — so it was checked by enumerating the package rather than by reading the table: 29 public module-level functions across 18 modules. **Three of the four mechanical checks I wrote produced false positives, and that is the entry's most transferable content.** `__all__` was empty, so the first check compared an empty list and reported a vacuous "none missing" — a green that proved nothing. The second flagged 15 functions as lacking a boot-contract arm; the test imports the operator entry points (`run_*`, `build_*`, `assemble_*`) and the façade, and the rest are internal helpers reached transitively. The third flagged seven modules as absent from the table; the table covers them with a `*_results` glob row and a shorthand (`resolve_llm_setting_for_text` / `_for_object`). Every one of those would have been a fabricated finding had it been reported without opening the file it accused. A mechanical check over prose is a *lead generator*, never a verdict — the opposite failure from the one `hub-layering-convention` keeps logging, where the mechanical checks are blind rather than noisy.The surviving finding is real and small: the table under "What a programmatic caller imports" had a row for every kernel module except `prompt_references`, while `assemble_llm_prompt` and `assemble_img_gen_prompt` both oblige the caller to construct `ImageReference` / `DocumentReference` values. A table that states what a caller imports, omitting a module its own listed entry points force the caller to import, is wrong by its own claim. Pre-existing rather than trigger-induced — it survived the 2026-08-03 review — which is the same lesson `hub-layering-convention` logged on 2026-07-27: a review target's value is bounded by what the reviewer reads, not by what opened the contract.++- **2026-08-13 · cli-docs · clean-pass** — opened by the PR #1099 review fixes to `validate pipe` / `show pipe` (ambiguity now a clean exit instead of a traceback) and `which` (markup escaping). Reviewed both targets: `docs/tools/cli/` documents no exit codes or error rendering for these commands and has no `which` page, and the agent-CLI contract doc covers only the agent CLI, untouched here. The one user-visible behavior (ambiguous codes refused, naming candidates) was already documented in `docs/building-methods/libraries.md` by this branch — the fixes make the code honor the doc, the pleasant inverse of drift. Second consecutive clean-pass on cli-docs from the same underlying fact (the targets simply do not document the surfaces this branch keeps touching); not yet friction — the contract opened on genuine CLI-surface edits and the review was cheap.+- **2026-08-13 · pipelex-kernel-docs · clean-pass** — Opened on the `search_domain_codes`→`search_scope` rename threading through `shape_inputs` and the boot-contract mock swapping to `get_required_entry_concept`; the kernel doc names neither the parameter nor the resolver method, so nothing was stale.diff --git a/wip/parity/d1-domain-hint-deferred.md b/wip/parity/d1-domain-hint-deferred.mdindex d5d75278b..226c06878 100644--- a/wip/parity/d1-domain-hint-deferred.md+++ b/wip/parity/d1-domain-hint-deferred.md@@ -1,6 +1,16 @@# D-1 follow-up — the `domain_hint` conversation, deferred-**Status:** deferred, deliberately. Raised at 1.1 (Phase 1), not taken.+**Status: CLOSED — subsumed, not implemented.** The `domain_hint` parameter will never be built, because the question it was going to answer stopped existing.++`domain_hint` was a way to make a *search* prefer the caller's domain when a bare code matched several. In-body pipe refs are now qualified to their owner domain at library build time and `PipeLibrary.get_optional_pipe` no longer searches across domains — only the alias-scoped cross-package remainder search survives, per the OQ3 ruling — so a bare in-body code never reaches a lookup that could be ambiguous. The `TODO` quoted below is gone with the fall-through it described.++Note which row of the table settled it: the "both `A.foo` and `B.foo` exist" case now resolves to `A.foo` — the answer the `own-domain-first` column proposed and this note argued against. The argument was sound at the time and its conclusion has been overtaken: own-domain-first was wrong *while* the live library still searched, because it would have made the normalizer disagree with the runtime. Moving both readers together is what made it right. Ambiguity survives in the entry affordance (`get_optional_entry_pipe`), where a human typed the code and guessing on their behalf would be the wrong favour — there it raises and names the candidates — and in the alias-scoped cross-package search `get_optional_pipe` deliberately keeps (OQ3), where an `alias->bare_code` ref matching several domains inside that dependency raises too.++Everything below is the original note, preserved.++---++**Status (original):** deferred, deliberately. Raised at 1.1 (Phase 1), not taken.## What 1.1 actually landed, and how it differs from the plan's recommendationdiff --git a/wip/pipe-refs/README.md b/wip/pipe-refs/README.mdnew file mode 100644index 000000000..ee6322c2c--- /dev/null+++ b/wip/pipe-refs/README.md@@ -0,0 +1,292 @@+# Bare references resolve across domains; the standard says they must not++**Status (2026-08-11).** Decided: tighten the runtime to the standard, implemented via build-time qualification of in-body references. The design and phased plan are in [build-time-qualification.md](build-time-qualification.md); §7 below was its starting sketch and is superseded by that document. The evidence in §1–§6 remains the record of why.++**What this is.** A decision brief for the divergence recorded in [`../parity/bare-pipe-ref-spec-divergence.md`](../parity/bare-pipe-ref-spec-divergence.md), which closed with *"the direction of the fix is genuinely open"* and deferred it. This directory re-opens it with measurements instead of priors, and adds two things that note does not contain: the rule turns out to be **load-bearing for `[exports]`**, and the same divergence is **still live for concepts**, one file over from the pipes that were fixed.++**Everything below is reproducible from this checkout.** Two probe scripts and a demo generator live in [`probes/`](probes/); every number and every quoted error in this document was produced by them against this tree. Nothing here is inferred from reading code alone.++**What is being asked of the reader.** Confirm or refute the claims in §1–§5 (each names the file, the line, and the command), then plan the change sketched in §7. Do not treat §7 as settled — it is a proposal, and §8 lists what would have to be true for it to be right.++---++## 1. The rule++The normative text is in the sibling `mthds/` repo (the open standard, published to mthds.ai), not here, so a fresh clone cannot resolve the path. From `mthds/docs/spec/namespace-resolution.md`:++> ## Resolution Order for Bare Pipe References+>+> 1. **Current bundle** — check pipes declared in the same `.mthds` file.+> 2. **Same domain, other bundles** — if the bundle is part of a package, check pipes in other bundles that declare the same domain.+> 3. **Error** — if not found, the reference is invalid.+>+> Bare pipe references do NOT fall through to other domains or other packages.++The same page states the identical rule for concepts (§ *Resolution Order for Bare Concept References*, with natives taking priority at step 1).++Two other sections of that same page **depend** on this rule. They are quoted in §3, because they are the part of the argument the deferred note does not have.++## 2. What this repository does today++> **HISTORICAL as of the pipe-side fix.** The table below records the state that motivated this work, and it is kept as written rather than rewritten — the argument only makes sense against the disagreement it describes. What changed: the pipe readers now qualify a bare in-body ref to its **owner domain** and the live `PipeLibrary` lookup no longer searches across domains for a bare in-body ref, so the two pipe rows agree with each other *and* with the standard. One search survives on purpose: a cross-package `alias->bare_code` ref is still matched across the aliased dependency's domains — alias-scoped, so it can never reach a host pipe; OQ3 in [build-time-qualification.md](build-time-qualification.md) records why. Bare codes a human types at an entry point keep working through a separate, explicitly-named affordance (`get_optional_entry_pipe`), which searches crate-wide and refuses ambiguity. **The concept rows are still accurate** — the concept-side work is not done. Re-measured outcomes are in §3.++Four readers of one authored fact. They do not agree, and only one of them agrees with the standard.++| Reader | Where | Bare ref behaviour |+| --- | --- | --- |+| `PipeLibrary.get_optional_pipe` | `pipelex/libraries/pipe/pipe_library.py` (step 3, since deleted) | Searches **every** domain (`# 3. Bare code fallback — search across domains`); one match wins, several raise `PipeLibraryError` |+| `_qualify_pipe_ref` | then `crate_normalization.py`, now `crate_qualification.py` | Same crate-wide search, **deliberately** mirrored onto the normalizer so the two readers agree (PR #1085) |+| `_qualify_concept_ref` | then `crate_normalization.py`, now `crate_qualification.py` | Qualifies as `<owner domain>.<Code>`, no search — **this one matches the standard** |+| `ConceptLibrary.get_required_concept_from_concept_ref_or_code` | `pipelex/libraries/concept/concept_library.py` | With `search_domain_codes=None`, walks every concept in the library and raises on a collision — the same shape as the pipe fallback |++So: **pipes** agree with each other and disagree with the standard. **Concepts** disagree with each other — the normalizer complies, the live library does not. The pipe fix chose which reader to move; it moved the normalizer *away* from the standard, and it did not touch concepts.++Note also where normalization runs: `normalize_crate` is called from `pipelex/pipeline/resolve_bundle.py:86`, `pipelex/cli/commands/crate_loading.py:43` and `pipelex/cli/commands/build/runner/_runner_core.py:107` — the `resolve` / `codegen` / `build` paths. The ordinary library load that backs `pipelex run` does **not** normalize, so the live `PipeLibrary` really does see bare in-body refs at run time. Any plan that hopes to fix this purely in the normalizer has to deal with that first.++## 3. The rule is a visibility boundary, not a lookup convenience++This is the argument that changes the question, and it is checkable in one run.++The standard exempts bare references from the export check **because** they cannot leave their domain (`mthds/docs/spec/namespace-resolution.md` § *Visibility Rules (Intra-Package)*):++> - **Cross-domain references** (within the same package) — the target pipe MUST be exported. […]+> - **Bare references** — always allowed at the visibility level (they resolve within the same domain).++The visibility checker implements the exemption literally. `mthds/package/visibility.py:82-84` (the installed `mthds` package, reached from `pipelex/libraries/visibility_utils.py:53`, called at `pipelex/libraries/library_manager.py:847`):++```python+# Bare ref -> always allowed (no domain check)+if not pipe_ref.is_qualified:+ return True+```++Combine that with a resolver that *does* let bare refs leave their domain and you get an **export bypass**: the reference form that skips the check is the one that reaches the other domain. Measured, on this tree:++```sh+DEMOS=$(./wip/pipe-refs/probes/make-demos.sh | tail -1)+( cd "$DEMOS/export-bypass" && pipelex resolve . ) # bare `helper`+( cd "$DEMOS/export-bypass-control" && pipelex resolve . ) # qualified `beta.helper`+```++One package, one manifest, `beta.helper` deliberately absent from `[exports]`. The two runs differ only in how `alpha.run_flow` spells its step:++| Step written as | Exit | Result |+| --- | --- | --- |+| `helper` (bare) | `0` | normalizes to **`"pipe": "beta.helper"`** — the non-exported pipe, reached |+| `beta.helper` (qualified) | `1` | `Pipe 'beta.helper' referenced in pipe.run_flow.steps[0].pipe (domain 'alpha') is not exported by domain 'beta'. Add it to [exports.beta] pipes in METHODS.toml.` |++`[exports]` is unenforceable through the one reference form that is exempt from checking it. That is not a convenience the corpus happens to rely on; it is a hole, and it exists precisely because the resolver and the visibility checker read the same sentence differently.++The same page's § *Conflict Rules* carries the second casualty:++> | Different domains (same package) | Same concept or pipe code | No conflict — different namespaces. |++Crate-wide resolution converts that blessed no-conflict case into an ambiguity error. Two domains reusing a code — explicitly allowed by the standard — becomes a load failure the moment anything names it bare:++```sh+( cd "$DEMOS/ambiguous" && pipelex resolve . )+```++```+exit=1+Cannot resolve — the library is invalid:+Error validating pipe 'run_flow' dependency pipe 'summarize' because of: Ambiguous pipe code+'summarize' found in domains: ['alpha', 'beta']. Use domain-qualified ref.+```++Under the standard that bundle loads: `alpha.run_flow` names a bare `summarize`, `alpha` declares one, the search stops there. The error is not "the author was ambiguous" — the author was not; the resolver made them ambiguous by widening the search past the point where the standard stops it.++And the fall-through itself, for completeness:++```sh+( cd "$DEMOS/fallthrough" && pipelex resolve . ) # exit 0, step normalizes to "beta.present"+```++Three demos, three rows of the divergence table, all reproducible in about ten seconds.++### Re-measured after the pipe-side fix++Same three closures, same commands, on the fixed tree. Every prediction in this section held:++| Closure | Before | After |+| --- | --- | --- |+| `export-bypass` | exit `0`, bare `helper` reached the non-exported `beta.helper` | exit `1` — **the hole is closed**; the bare form no longer reaches another domain, so `[exports]` is enforceable through every reference form |+| `fallthrough` | exit `0`, step normalized to `beta.present` | exit `1`, naming the ref that was tried and suggesting the qualified spelling |+| `ambiguous` | exit `1`, `Ambiguous pipe code 'summarize' found in domains: ['alpha', 'beta']` | exit `0`, normalizes to **`alpha.summarize`** — the standard's answer. Two domains reusing a code is a no-conflict case again |++`export-bypass-control` is unchanged (exit `1`, the export error) — as it must be: that arm never depended on the resolver.++Both failures take the same shape; the codes differ because the demos reference different pipes. `fallthrough`'s reads:++```+Pipe 'alpha.run_flow' references 'alpha.present', which does not exist. A pipe reference+resolves inside its own domain, so 'present' is looked for in domain 'alpha'. Referencing a pipe in+another domain requires writing that domain out. 'present' is declared elsewhere in this library —+did you mean 'beta.present'?+```++`export-bypass` is the same sentence with its own codes — `'helper'` looked for in `'alpha'`, suggesting `'beta.helper'` — because the message is pieced together from the specific ref that failed rather than being a fixed string. (The wording stays origin-neutral on purpose: after qualification, a bare `present` and an explicitly-written `alpha.present` are indistinguishable.)++The suggestion comes from a crate-wide scan that runs **only** on the failure path. It suggests a spelling to a human; it never resolves a reference. Wiring it into a lookup would restore the bypass this section exists to document.++## 4. The same divergence is still live for concepts — and that reader is separately broken++> **HISTORICAL — closed by Phase 3 (2026-08-13).** The table below measures the `search_domain_codes` machinery this section was written about, which no longer exists: `get_required_concept_from_concept_ref_or_code` was replaced by the entry affordance `get_required_entry_concept(code, search_scope=...)`, taking both defects (2) and (3) with it. The probe was rewritten against the replacement; its re-measured table is at the end of this section. The wording below is preserved as the record of what was wrong.++`probes/concept-lookup-matrix.py` built a two-domain library in memory and asked for a bare code under each shape of `search_domain_codes`. Measured output at the time, verbatim:++| Library | `search_domain_codes` | Result |+| --- | --- | --- |+| `alpha.Memo` + `beta.Memo` | `None` | `ConceptLibraryConceptNotFoundError: Multiple concepts found for 'Memo'` |+| `beta.Memo` only | `None` | resolved **`beta.Memo`** — fall-through, from any domain |+| `alpha.Memo` + `beta.Memo` | `["alpha", "beta"]` | `ConceptLibraryConceptNotFoundError: Multiple concepts found for 'Memo'` |+| `beta.Memo` only | `["alpha", "beta"]` | `ConceptLibraryError: Concept 'alpha.Memo' not found in the library` |+| `beta.Memo` only | `["beta", "alpha"]` | `ConceptLibraryError: Concept 'alpha.Memo' not found in the library` |+| `alpha.Memo` + `beta.Memo` | `["alpha"]` | resolved `alpha.Memo` |++Three things fall out of that table, and the last two are defects nobody has filed:++1. **Rows 1–2 are the pipe divergence, verbatim, for concepts.** Fall-through where the standard errors; an ambiguity raise where the standard quietly succeeds. Meanwhile `_qualify_concept_ref` in the normalizer answers the *same authored text* the standard's way — confirm with `( cd "$DEMOS/concept-collision" && pipelex resolve . )`, which qualifies `alpha`'s bare `Note` to `alpha.Note` and `beta`'s to `beta.Note` and exits 0. Two readers, one fact, disagreeing — the exact defect class the parity track exists to remove, still open one file over from where it was closed for pipes.++2. **Rows 4–5: a multi-domain search list cannot survive a domain that lacks the code.** The `search_domain_codes` loop in `ConceptLibrary.get_required_concept_from_concept_ref_or_code` calls `get_required_concept`, which *raises* rather than returning `None`, so the walrus `if found_concept := …` never sees a falsy value — the first miss escapes the method. Worse, it escapes as `ConceptLibraryError`, and `ConceptLibraryError` is **not** a subclass of the `ConceptLibraryConceptNotFoundError` that every caller in `pipelex/core/stuffs/stuff_factory.py` catches (`pipelex/libraries/concept/exceptions.py` extends `LibraryLoadingError`; `pipelex/core/concepts/exceptions.py` extends `PipelexError` — sibling branches). So the error bypasses the handler that exists to contextualize it.++3. **Row 3 makes the deliberate ordering in `pipeline_run_setup` — the `search_domain_codes.insert(0, pipe.domain_code)` — dead code.** That insert puts the running pipe's domain at position `0` so it wins; the loop then collects *all* matches and raises on `len > 1` before `found_concepts[0]` is ever returned. The own-domain preference it was written to express cannot fire.++**How live is (2) and (3)?** Latent, not live, today: the `pipeline_run_setup` insert produces a single-element list, and no production call site passes a longer one (`grep -rn "search_domain_codes=\[" pipelex tests` finds only test call sites). That is worth stating plainly rather than dressing up — but it also means the multi-domain list is unusable the moment anyone reaches for it, and the standard's rule is exactly what makes the whole `search_domain_codes` parameter unnecessary.++**One thing to confirm rather than assume:** `search_domain_codes` is fixed once from the *entry* pipe's domain and carried on the runner (the `search_domain_codes` constructor field in `pipelex/pipeline/runner.py` and its pass-through into the pipe job). Whether a sub-pipe in another domain can reach a concept-shaping path with the entry domain in hand — and therefore fail to resolve its own bare concept ref — was not established here. It is a good first question for whoever picks this up. *(Answered during the design phase: it cannot — sub-pipe concept refs are qualified or rejected at build, so the defects were latent, entry-only. See the design doc's "The concept side".)*++**Re-measured after Phase 3 (2026-08-13).** The lookup is now `get_required_entry_concept(code, search_scope=...)`, where the scope is derived from the resolved entry pipe (its domain, `alias->domain` when the entry pipe came from a dependency package) instead of being a caller-supplied list. Same probe, same library shapes:++| Library | `search_scope` | Result |+| --- | --- | --- |+| `alpha.Memo` + `beta.Memo` | `None` | `ConceptLibraryConceptNotFoundError: Concept code 'Memo' is ambiguous — it is declared by ['alpha.Memo', 'beta.Memo']. Name one of them explicitly.` |+| `beta.Memo` only | `None` | resolved `beta.Memo` — unique crate-wide match |+| `alpha.Memo` + `beta.Memo` | `alpha` | resolved **`alpha.Memo`** — the entry pipe's own domain wins (row 3's dead preference, now live) |+| `beta.Memo` only | `alpha` | resolved `beta.Memo` — a scope lacking the code falls back instead of dying on the miss |+| `beta.Memo` only | `beta` | resolved `beta.Memo` |+| empty library | `alpha` | `ConceptLibraryConceptNotFoundError: Concept 'Memo' not found in the library. …` |++Every escape is `ConceptLibraryConceptNotFoundError` — the class the `stuff_factory` handlers actually catch — so defect (2)'s wrong-exception-class bypass is structurally gone, and the walk cannot die mid-scan because there is no scan-per-domain walk left. Note this is the **entry** affordance: a hand-supplied code deliberately still searches crate-wide (excluding aliased dependency entries) when the scope misses, because a human pointing at a concept is not an in-body reference. In-body concept refs were already owner-domain-qualified at build time before this branch.++## 5. The corpus — which direction is actually expensive++> **Superseded and widened (2026-08-11).** The scan below passes a hardcoded list of ten sibling repos, which turns out to reach under a fifth of the bundles outside this repo. Enumerating the workspace instead multiplies the corpus several times over and finds a **second** breaking reference, in `cocode` — a shipped CLI, not a samples directory. The numbers in this section remain accurate *for the roots it scanned*; read [corpus-measurement.md](corpus-measurement.md) for the current figures, what inflates them, and the reproduction command.++The deferred note's decisive reason was migration cost: *"Every `.mthds` in the wild that leans on cross-domain bare resolution stops loading."* That is the claim the probe was written to check.++`probes/classify-bare-refs.py` reads TOML and nothing else — no `pipelex` import, no library load — so it classifies what the corpus **asks for**, independent of what any resolver does with it. For each merge unit it builds `code -> {domains that declare it}` and sorts every bare in-body reference into four buckets.++```sh+python wip/pipe-refs/probes/classify-bare-refs.py .+python wip/pipe-refs/probes/classify-bare-refs.py \+ ../pipelex-cookbook ../pipelex-starter-python ../mthds ../pipelex-api ../mthds-js+# …plus the rest of the workspace's .mthds trees as extra roots (the probe takes roots+# as argv). Several of those repos are not open core, so the full root list lives in the+# workspace-level private notes.+```++| | this repo | every other `.mthds` tree in the workspace |+| --- | --- | --- |+| bundles read | 124 | 90 |+| merge units | 57 | 36 |+| **bare in-body pipe refs** | **142** | **158** |+| `own-only` — the referring domain declares it, nobody else. Standard and runtime agree | 136 | 153 |+| `sibling-only` — ONLY another domain declares it. Standard: error. Runtime: resolves | **0** | **1** |+| `both` — the referring domain *and* another declare it. Standard: the own one. Runtime: **raises** | 6 | 1 |+| `nowhere` — nobody declares it. Both error | 0 | 3 |+| **bare in-body concept refs** | **283** | **367** |+| `own-only` | 255 | 341 |+| `sibling-only` | **0** | **0** |+| `both` | 27 | 22 |+| `nowhere` | 1 | 4 |++**One bare pipe reference out of 300 leans on cross-domain resolution**, and it is `pipelex-cookbook/examples/wip/advisory_board/bundle.mthds` — `advisory_orchestrator.master_advisory_orchestrator` naming a bare `present_as_markdown` that only the `presentation` domain declares. It is fixed by writing `presentation.present_as_markdown`. **Zero** bare *concept* references lean on it, anywhere. Widening the scan to every `.mthds` tree in the workspace finds a second breaking pipe reference, in `cocode` — a shipped CLI; see [corpus-measurement.md](corpus-measurement.md).++That is the entire migration cost of tightening, across every `.mthds` either repo can see. The cost argument that carried the deferral does not survive contact with the corpus.++**What this measurement does not cover — read before quoting it.**++- **A directory is not always a merge unit.** The probe treats a package (a tree with `METHODS.toml`) as one unit and otherwise groups by containing directory, which is how a `-L <dir>` load behaves. Test-fixture directories whose bundles are loaded *one at a time* are therefore over-grouped: most of the `both` rows are fixture pairs that never actually meet in one library, so the `both` column is an upper bound on "would start working", not a count of live breakage. **The `sibling-only` figure is the robust one.** Grouping is not monotone in general — a coarser unit can promote a `nowhere` ref into `sibling-only` — but every `nowhere` ref in the corpus is a *deliberately invalid* fixture (`missing_pipe_ref.do_two_steps -> 'second_step_missing'`, in three copies; the probe prints them), so none of them can become a real cross-domain reference under any grouping. One is one.+- **In-body references only.** `main_pipe` and `[exports]` entries are not classified.+- **Bare concept refs exclude natives**, which take priority by the standard's own step 1.+- **Customer bundles are out of reach by construction.** But "one in 300, in an `examples/wip/` directory" is a very different prior from "every `.mthds` in the wild".+- **Do not materialize the demos inside this tree.** `make-demos.sh` writes to a `mktemp` directory by default for exactly this reason — the demo bundles are pathological, and dropping them into the repo would move the counts above.++## 6. Answering the deferral's three reasons++> **1. It is a behavior change to the language, not to a reader.**++True, and the measurement is what sizes it: two references across every `.mthds` tree in the workspace — one in a cookbook `examples/wip/` bundle, one in `cocode`, a shipped CLI ([corpus-measurement.md](corpus-measurement.md)). Worth adding that the *current* state is also a behaviour change to the language — an undeclared one, made by a resolver rather than by a spec edit, which took away two guarantees (§3) the standard still advertises.++> **2. It is cross-repo.**++True, and it stays cross-repo whichever way it settles. That is an argument about how to land it, not about which way.++> **3. The direction of the fix is genuinely open […] cross-domain bare resolution inside a single crate is convenient and has evidently been relied on.**++"Evidently been relied on" is the assumption the numbers contradict: two references in the entire workspace, each fixed by one qualified spelling. And loosening the standard is not a one-line edit either — it means deleting the bare-reference exemption from § *Visibility Rules*, rewriting the § *Conflict Rules* row for different domains in one package, and answering what `[exports]` is for once bare refs route around it (§3). Of the three positions in play — the standard, this runtime's pipe readers, this runtime's concept readers — the standard is the only one that is internally consistent today.++## 7. Proposed shape of the fix++A proposal, not a decision. The deferred note's closing rule — *"Do not fix one reader and not the other"* — is right and extends one step further than it was applied: not one reader and not the other, and **not pipes and not concepts**.++**In this repository:**++- `PipeLibrary.get_optional_pipe` takes the caller's domain and stops at it: own bundle → own domain → not found. The permissive crate-wide search is arguably still right for *entry-point* lookups (a user typing `pipelex run my_pipe` with no domain in hand); if so, keep it there and make it an explicit, separately-named affordance rather than the resolution rule for in-body references. **Deciding that split is the first design question.**+- `ConceptLibrary.get_required_concept_from_concept_ref_or_code` does the same, which also deletes the `search_domain_codes` machinery's reason to exist and takes the two defects in §4 with it.+- `_qualify_pipe_ref` in `crate_normalization.py` reverts to owner-domain qualification — becoming the twin of `_qualify_concept_ref` sitting beside it — so the two readers agree by moving the one that is wrong about the standard, rather than the one that is right.+- **The real work is the call sites** (`grep -rn "get_optional_pipe\|get_required_pipe(" pipelex | grep -v "def get_"`), which today pass a bare code with no domain. Most are inside a `Pipe*` instance and so already hold `self.domain_code` (`PipeAbstract.domain_code`), but the `interpreter_hub` lookup accessors are the funnel and their signature has to change. Scope this before committing to the change.++**Tests that pin today's behaviour and must flip** (they are correct tests of the current rule; they become tests of the new one):++- `tests/unit/pipelex/libraries/test_crate_normalization.py::test_bare_cross_domain_pipe_refs_resolve_to_the_declaring_domain` — its docstring states the fall-through as the intended contract.+- `tests/unit/pipelex/libraries/test_pipe_library_lookup.py::test_bare_code_ambiguous_raises` and `::test_bare_code_unambiguous` — same, for the library.+- `pipelex/pipeline/fixes/fix_loop.py:401` carries a comment describing the ambiguity raise as a fact about the library; check whether the surrounding logic depends on it.++**Outside this repository** (each is somebody else's merge, so land them in a coordinated set):++- `mthds/` — **no normative change**. One additive clarification is worth making, because this round is evidence it is needed: say at § *Resolution Order for Bare Pipe References* that no-fall-through is what makes `[exports]` enforceable, so the next reader does not take it for a lookup convenience.+- our cross-repo spec suite — the four rows of §5's table as executable cases (own-only resolves; sibling-only errors; both resolves to the referring domain's own; nowhere errors), plus the export-bypass case from §3, which is the one nobody would think to write without the visibility argument.+- `pipelex-cookbook` — qualify one reference in `examples/wip/advisory_board/bundle.mthds`.+- `cocode` — qualify one reference in `cocode/pipelines/swe_diff/changelog_enhanced.mthds`: write `changelog.format_changelog_as_markdown`.++## 8. What to verify before building++The claims above are measured, but a plan should not rest on someone else's measurements. Re-run them — `probes/` is two scripts and a shell generator, and the whole set takes under a minute — and settle these before writing code:++1. **Does the export bypass reproduce?** It is the load-bearing claim. If it does not, §3 collapses and the question really is open.+2. **Is the entry-point lookup genuinely a different concern from in-body resolution?** If yes, the fix is two functions rather than one, and the corpus numbers in §5 (which count *in-body* references only) are the right ones to reason from. If no, `pipelex run <bare code>` gets stricter and that is a UX change worth naming.+3. **Can a sub-pipe in a non-entry domain reach a concept-shaping path?** (§4, last paragraph.) It decides whether the concept side has a live bug or only a latent one.+4. **What does threading the caller's domain through `interpreter_hub` actually cost?** 63 call sites is a count, not a scope. Some are validation walks, some are hot-path execution; they may not all have a caller domain to offer.+5. **Are there `.mthds` consumers outside this workspace** — customer bundles, published packages — that the §5 corpus cannot see, and is there any way to sample them?++---++## Reproducing everything in this document++```sh+# corpus classification (§5)+python wip/pipe-refs/probes/classify-bare-refs.py .+python wip/pipe-refs/probes/classify-bare-refs.py \+ ../pipelex-cookbook ../pipelex-starter-python ../mthds ../pipelex-api ../mthds-js+# …plus the rest of the workspace's .mthds trees as extra roots — see the note in §5.++# concept lookup matrix (§4)+.venv/bin/python wip/pipe-refs/probes/concept-lookup-matrix.py # needs the venv: this probe imports pipelex++# the five demo closures (§3, §4)+DEMOS=$(./wip/pipe-refs/probes/make-demos.sh | tail -1)+for case in ambiguous fallthrough export-bypass export-bypass-control concept-collision; do+ printf '\n===== %s =====\n' "$case"+ ( cd "$DEMOS/$case" && pipelex resolve . )+done+```++Run these from the repository root with this checkout's environment active, so that `python` and `pipelex` are the ones installed from this tree (`.venv/bin/python`, `.venv/bin/pipelex`) rather than whatever is on `PATH` — the point of every number here is that it describes *this* code. Set `PIPELEX_NO_DECK_NOTICE=1` to silence the model-deck banner; none of these commands needs credentials or reaches an inference backend.++## See also++- [`../parity/bare-pipe-ref-spec-divergence.md`](../parity/bare-pipe-ref-spec-divergence.md) — the deferral this document answers.+- [`../parity/d1-domain-hint-deferred.md`](../parity/d1-domain-hint-deferred.md) — the narrower `domain_hint` question. Compliance subsumes it: if bare refs never leave their domain, cross-domain ambiguity cannot arise.+- [`../parity/deferred-review-observations.md`](../parity/deferred-review-observations.md) § 4 — the ordering dependency noted there (settle the resolution rule before writing the spec paragraph) is the reason §7 puts the `mthds/` edit last.diff --git a/wip/pipe-refs/build-time-qualification.md b/wip/pipe-refs/build-time-qualification.mdnew file mode 100644index 000000000..82f04f9ad--- /dev/null+++ b/wip/pipe-refs/build-time-qualification.md@@ -0,0 +1,154 @@+# Decided design: in-body references qualify at build time++**Status.** Decided 2026-08-11; Phases 1, 2 and 3 have landed (outcomes recorded below); only the cross-repo Phases 4a/4b remain. This settles the two questions [README.md](README.md) left open: the **direction** — tighten the runtime to the MTHDS standard's resolution rule — and the **mechanism** — qualify in-body references once, at library build time, rather than threading the caller's domain through the lookup API. The README carries the evidence for the direction (the export bypass, the corpus measurement, the concept-side defects); this document records the mechanism, why it won, and the implementation plan.++## The decision in one paragraph++Bare in-body references (pipe steps, branches, outcomes, batch refs, concept I/O refs) are qualified to their **owner domain** when the library is built, exactly as the standard's resolution order prescribes and exactly as `_qualify_concept_ref` in the crate normalizer already does. After the build, the live library only ever sees fully-qualified in-body refs, so lookups are direct key hits and the resolution rule lives in one shared function instead of at every call site. The crate-wide bare search survives only as an explicitly-named **entry-point affordance** for user-supplied codes (`pipelex run my_pipe`, CLI commands, API payloads), which is outside the standard's scope — the standard governs references written in bundles, not what a user may invoke by hand.++## Why build-time qualification won over domain-threading++Three facts, established by reading the code after the README was written:++1. **The ordinary load path already builds a `LibraryCrate`.** The README worried that the run path "does not normalize" and any normalizer-based fix would have to deal with that first. In fact `library_manager` assembles a crate from the parsed blueprints (`LibraryCrateFactory.make_from_blueprints`) on every load path — main, secondary, and dependency loads — and builds each pipe by iterating `crate.pipes`, already asserting the keys are domain-qualified, before calling `PipeFactory.make_from_blueprint` with the owner `domain_code` in hand. What the run path skips is the *normalization pass over that crate*, not the crate itself. The insertion point exists.+2. **Concepts already follow the spec rule at build time — pipes are the one anomaly.** `PipeFactory.make_from_blueprint` rejects any bare input/output concept ref that is not native or declared in the pipe's own domain, and `StuffSpecFactory` builds the stuff spec against the owner domain. This is why the corpus probe found zero cross-domain bare concept refs anywhere: the build refuses them. Sub-pipe refs are the outlier — `SubPipe.pipe_code` stores the authored string verbatim and resolves it lazily, crate-wide, on every lookup. The change is therefore "make pipe refs do what concept refs already do", not a new architectural layer.+3. **`get_required_pipe(pipe_code)` is part of the pinned transport boundary.** Its signature is pinned by our cross-repo spec suite's allowed-surface list and it is called with a payload-supplied code by the host-side bridge in the transport layer that is not open core. Threading a caller-domain parameter through the hub accessors changes that pinned signature and drags the boundary spec and its verifying test into the change. Build-time qualification leaves the signature untouched: in-body refs stop needing the fallback because they arrive qualified, and the bridge's call — a payload-supplied code — is an entry-point lookup anyway.++Domain-threading loses on every axis examined: it changes a Protocol, the `interpreter_hub` free functions, and a transport-pinned signature; it keeps authored bare refs live at run time and re-resolves them (with a full library scan) on every lookup; and it distributes the resolution rule across every present and future call site, so the normalizer and the runtime agree by discipline rather than by construction. No scenario was found where threading holds an advantage — the one that would (no crate on the load path, refs needed in authored form at run time) turned out not to exist.++## The design++### One shared qualification pass++Extract the in-body reference qualification step out of `crate_normalization.py` (the application of `_qualify_pipe_ref` / `_qualify_io_ref` inside `_normalize_pipe`, plus the concept-side qualification) into a standalone pass over a `LibraryCrate`, and change the pipe rule from crate-wide search to **owner-domain qualification** — the exact twin of `_qualify_concept_ref` sitting beside it. Both consumers call the same function:++- `normalize_crate` (the `resolve` / `codegen` / `build` paths) — unchanged in shape, now spec-compliant in rule.+- The library build in `library_manager` — the pass runs on the crate before pipes are constructed, on **all** crate→pipes paths (main load, secondary loads, dependency-package loads).++The normalizer and the live library then cannot disagree about what an authored reference means, structurally rather than by mirrored implementations — the parity track's goal achieved by construction. Note that owner-domain qualification implements the standard's full resolution order on its own: existence is checked afterwards by the ordinary dependency validation, so "bare `foo` from domain `alpha` when only `beta.foo` exists" qualifies to `alpha.foo` and then fails validation with a missing-pipe error, which is exactly the standard's step 3.++Cross-package refs (`alias->…`) are left intact by the pass, as the normalizer already leaves them — canonical cross-package resolution is the packaging project's design work (see the sequencing section).++### The library lookup becomes strict; entry lookups get a named affordance++- `PipeLibrary.get_optional_pipe` drops its step-3 bare-code crate-wide fallback (and with it the `domain_hint` TODO — [d1-domain-hint-deferred](../parity/d1-domain-hint-deferred.md) closes as subsumed). What remains: direct key lookup and the cross-package (`alias->`) handling.+- The crate-wide unique-match search moves to a separately-named entry affordance on the library (working name `find_pipe_by_bare_code`; final name to be settled at implementation), exposed through a new `interpreter_hub` accessor. Its semantics: exact ref hits directly; a bare code matches crate-wide; ambiguity raises an error that asks the user to qualify. Its docstring states explicitly that it deliberately does **not** consult `[exports]` — a user invoking a pipe by hand is not an in-body reference, so package visibility does not apply.+- The genuinely entry-shaped call sites migrate to it: the CLI commands (`which`, `show`, `validate`, the `build`/`codegen` groups), `pipeline_run_setup`, the builder operations, and the host-side bridge in the not-open-core transport layer. Everything else — controllers, `sub_pipe`, `signature_walk`, `library` validation — looks up refs that are stored on built objects, which arrive qualified after this change, and needs no edit at all.+- **Transport boundary:** adding the new hub accessor is an additive change to the pinned surface. Update the transport boundary spec and its verifying allowed-surface test in our cross-repo spec suite in the same change, per the spec/conformance sync rule; exact paths and the current state of that test live in the workspace-level private notes. `get_required_pipe`'s signature does not move.++### The concept side++- `ConceptLibrary.get_required_concept_from_concept_ref_or_code`'s `search_domain_codes` machinery serves only user-supplied codes during run-setup input shaping (`stuff_factory` ← `working_memory_factory` / `input_shaper` / `kernel/memory_ops`) — in-body concept refs never reach it after (indeed, already before) this change. Collapse it into the same entry-affordance shape: prefer the entry pipe's domain, else crate-wide unique match. This deletes the latent defects the README's §4 documents (the multi-domain list dying on the first miss, and escaping as the wrong exception class) and either makes `pipeline_run_setup`'s own-domain-first ordering meaningful or deletes it along with the list parameter.+- README §8's open question 3 answered itself during this investigation: sub-pipes in non-entry domains cannot hit a bare-concept path at run time, because their concept refs were qualified (or rejected) at build. The defects are confirmed latent, entry-only.++### Consequences inside this repo++- **Perf**: the removed fallback scanned every library entry per bare lookup at execution time; qualified refs are dict hits.+- **`fix_loop._pipe_codes_by_file`** blocks renames on cross-domain code collisions because the library raises on them; under the spec rule the collision scope shrinks to the domain. Relax it in the same change — it can only over-block today, but it is part of the rule's footprint.+- **Tests that pin the crate-wide rule flip** (they are correct tests of the old rule; they become tests of the new one): `test_crate_normalization.py::test_bare_cross_domain_pipe_refs_resolve_to_the_declaring_domain`, `test_pipe_library_lookup.py::test_bare_code_ambiguous_raises` and `::test_bare_code_unambiguous`. Tests that construct pipes directly with bare sub-refs (bypassing the crate pass) need their refs qualified once the strict lookup lands.+- **User-facing surfaces that echo refs** (errors, graphs, `show`) print qualified refs where the author wrote bare — same as the normalized crate already does; arguably clearer.+- **New conformance-shaped unit coverage** in this repo: the four corpus rows (own-only resolves; sibling-only errors; both-declare resolves to own; nowhere errors) plus the export-bypass closure.++## Deliberate non-goals++- **No full normalization on the load path.** Refinement flattening, native expansion, and string-concept materialization stay crate-only — running them at load would change live library semantics and is not needed for this fix. Only the qualification step is shared.+- **No cross-package resolution design.** `alias->` refs stay untouched; how a cloned remote package's refs are addressed, folded, and fingerprinted is the packaging project's own question. This change clears the ground so that is the *only* open resolution layer left.+- **No `mthds/` normative change.** One additive clarification only (see the cross-repo set).++## Why this sequences before the packaging system++The upcoming remote-methods system (GitHub addressing, cloning, version management, integrity checksums) depends on properties the current rule destroys and the spec rule provides:++- **Checksums and lockfiles need a package's meaning to be a function of its content.** Owner-domain qualification makes resolution a local computation — bundle plus its domain — so the publisher's normalized crate and fingerprint equal what any consumer computes, regardless of install context. Crate-wide resolution makes meaning depend on the merge unit: the same file can resolve differently, or stop loading, depending on its neighbors, which is fatal for content-addressed integrity. And once lockfiles pin fingerprints in the wild, changing the canonical form invalidates all of them — settle it first.+- **Installing a package must never change the meaning of methods already present.** The standard's conflict rule (different domains, same code — no conflict) is what makes composition scale. The current rule inverts it: every added package raises the probability that an unrelated bare ref becomes ambiguous and a working method stops loading, and that failure mode grows with exactly the dimension a catalog is built to grow. After this change, installing a package can affect at most a bare CLI invocation (contained, asks to qualify), never the execution of a loaded method.+- **`[exports]` becomes the versionable API contract.** Semver-style reasoning about method packages needs an enforceable boundary for "what may a consumer depend on". The measured export bypass means that boundary is currently fiction. Closing it while the migration cost is two references is cheap; closing it after unknown remote consumers lean on fall-through is the ecosystem break the original deferral feared. The cost of tightening is at its all-time minimum and only grows.+- **Remote execution threads less context.** With lazy bare refs, executing a dependency's pipe correctly needs the caller's domain *and* package carried into every lookup. With refs qualified at load, the domain half is baked into the stored ref; only the package scope remains, which is what `alias->` already expresses.++## Cross-repo set (land as one coordinated change)++- our cross-repo spec suite — executable cases for the four resolution rows and the export-bypass closure (the case nobody would think to write without the visibility argument), plus the additive transport-surface update.+- `pipelex-cookbook/` — qualify the first reference that leans on fall-through: `presentation.present_as_markdown` in `examples/wip/advisory_board/bundle.mthds`.+- `cocode/` — qualify the second: `changelog.format_changelog_as_markdown` in `cocode/pipelines/swe_diff/changelog_enhanced.mthds` (a shipped CLI, not a sample — see [corpus-measurement.md](corpus-measurement.md)).+- `mthds/` — **last**, per the ordering noted in [deferred-review-observations](../parity/deferred-review-observations.md) §4: an additive clarification at § *Resolution Order for Bare Pipe References* saying that no-fall-through is what makes `[exports]` enforceable, so the next reader does not mistake the rule for a lookup convenience.++## Open questions to settle during implementation++1. **Dependency-pipe lookup scoping today. — ANSWERED 2026-08-11, GO.** Measured with [`probes/dep-subpipe-scope.py`](probes/dep-subpipe-scope.py). The execution-time lookup consults the **host** library unconditionally (`sub_pipe.py` → `interpreter_hub.get_required_pipe` → the ambient current library); there is no child-library scoping on that path, and — at measurement time, before Phase 2 — the host's bare-code fall-through explicitly skipped `alias->` entries (Phase 2 has since deleted that fall-through; the host lookup is now strict, so a bare code matches nothing there — same outcome by a different mechanism). So a dependency's own bare sub-pipe ref never reaches the dependency's own pipe: with a plain host the package **fails to load**, and with a host that happens to declare the same bare code it loads and **silently binds the host's pipe**. In the shape a package actually ships — a manifest `[exports]` naming only the entry pipe — it fails earlier and for a second reason: the export filter drops the authored helper from the dependency's own child library, carving out only *synthetic* helpers. That is a pre-existing defect, written up in [dependency-subpipe-scope-deferred.md](dependency-subpipe-scope-deferred.md) and deferred to the packaging project — the fix needs package scope threaded through the lookup **and** export filtering that carries authored helpers, neither of which this change designs.++ The go/no-go turns on whether owner-domain qualification makes that worse, and it does not. The qualified ref (`dep_domain.helper`) resolves to `None` in the host exactly as the bare one does, so nothing regresses; the silent host-capture becomes a deterministic not-found naming the scope that should have been searched; and once the lookup is package-scoped, a qualified ref is a direct key hit in the child library, whose own keys are already `dep_domain.helper`. **Proceed.** The Phase 2 item "run the pass on the dependency load path" must not be read as making dependency sub-pipe refs resolve — it cannot, until the lookup is package-scoped.++ **Ordering constraint this measurement imposes on Phase 2.** `Library.validate_pipe_library_with_libraries`'s first loop looks up a **bare** sub-pipe code against the child library, whose keys are qualified — so that lookup is served today *only* by the crate-wide fall-through the strict lookup deletes. Running the pass on the dependency load path and deleting the fall-through therefore have to land in the same change; that co-landing is also what makes "`library` validation needs no edit" true.+2. **Final name and exact semantics of the entry affordance. — ANSWERED 2026-08-11.** A **required/optional pair**, `get_required_entry_pipe` / `get_optional_entry_pipe`, on `PipeLibraryAbstract` + `PipeLibrary` and mirrored as `interpreter_hub` accessors. The pair (rather than one method) is what the migration actually asked for: of the twelve entry-shaped call sites, exactly one — `pipelex which` — wants the optional form and reports the miss itself. The name dropped the working title `find_pipe_by_bare_code` for two reasons: the affordance also accepts fully-qualified refs, so "by bare code" describes only one of its inputs; and the name should carry *why* this lookup differs (it serves an entry point) rather than *how* it searches, since the how is the part most likely to change. The ambiguity message lives in `get_optional_entry_pipe` — the function doing the searching is the only one that knows the candidates.+3. **Whether `get_optional_pipe` keeps the cross-package bare-remainder search. — ANSWERED 2026-08-11: it keeps it.** The decisive argument is not that it is harmless (though it is — being alias-scoped, it cannot reach a host pipe) but that **there is no migration for the alternative**. The qualification pass deliberately leaves `alias->…` refs alone, because it cannot know a dependency's domain layout; so if the search were deleted, every `alias->bare_code` reference would break with no canonical spelling for its author to move to. Deleting a fall-through is only reasonable when you can tell people what to write instead. Revisit when the packaging design rules on cross-package reference forms — the comment in `get_optional_pipe` says exactly this, so the next reader inherits the reason rather than the conclusion.++## Implementation phases++The executable plan — phases, checkpoints, and per-phase task lists — lives in [../../TODOS.md](../../TODOS.md) and is the plan of record. It was restructured after the engineering review into C0–C4, splitting what this document originally described as one "Phase 1" into a pure-refactor extraction (Phase 1) and the rule flip (Phase 2), so that no checkpoint rests on a tree where the normalizer and the live library disagree. Do not maintain a second phase list here; record **outcomes** below as each checkpoint passes.++### Phase 1 outcome (C1)++**The extraction landed, behavior-identical except for one deliberate change.** The in-body qualification step now lives in `pipelex/libraries/crate_qualification.py` as `qualify_crate(crate) -> QualifiedCrateContent`, and `normalize_crate` consumes it. The rule is unchanged: bare pipe refs still resolve crate-wide.++Equivalence was established by running the committed implementation (loaded from HEAD) beside the working-tree one over the same inputs and comparing the full serialized output, not just the fingerprint:++- every crate buildable from this repo's `.mthds` files — identical, including the crates that raise;+- ten hand-built crates covering what the repo corpus cannot reach — identical, including all four error paths (ambiguous ref, unresolvable ref, unqualified concept key, unqualified pipe key).++The harness was then mutation-checked, because a comparison that is green on its first run proves nothing. Dropping structure-field qualification turns one case red; applying the Phase 2 owner-domain rule turns three red. Both mutations were reverted and the tree confirmed byte-identical.++**The exception: error precedence between two independent defects.** Qualification now runs as one complete phase ahead of refinement flattening, where HEAD interleaved them (concepts → flatten → pipes). A crate carrying *both* a refinement cycle and an ambiguous bare pipe ref used to report the cycle and now reports the ref.++The differential harness above could not have found this, and it is worth being precise about why: every crate it compares carries at most one defect, so a precedence change between two error paths is invisible to it by construction. The finding came from review. Phase 2 moves considerably more error surface, so its own equivalence checks need at least one multi-defect input.++Accepted rather than fixed. Restoring the old order would mean splitting the pass into a concept half and a pipe half so the normalizer could interleave them — which contradicts "one shared qualification pass" and buys nothing, because Phase 2 runs the pass with no flattening at all. Both errors are `CrateNormalizationError`, the crate is invalid either way, and which of two independent defects is named first is not a contract. It is recorded in `normalize_crate`'s docstring so the next reader meets a decision rather than a surprise.++**The corpus cannot see the Phase 2 flip.** That second mutation *is* the rule Phase 2 installs, and against all 54 crates built from this repo it produces byte-identical output. Every bare in-body pipe ref in this repo already resolves within its own domain. This is exactly the trap the plan's two-domain-fixture item names, now measured: a test grounded in this repo's bundles passes identically under both rules, so the discriminating fixtures must be hand-built and mutation-checked.++**Fingerprint / envelope ruling — the pass does not deal in fingerprints at all.** `qualify_crate` returns a `QualifiedCrateContent` NamedTuple carrying the rewritten `concepts` and `pipes`. It takes a crate and returns content.++The first cut returned a `LibraryCrate` with the envelope carried over verbatim and a paragraph of module docstring explaining why the `fingerprint` it handed back described pre-qualification content. The reasoning was sound as far as it went — a crate does not record which of the two digest schemes produced its value (`compute_fingerprint_from_content` for a merged crate, `compute_normalized_fingerprint` for a normalized one), so the pass cannot recompute correctly and must not guess. But the conclusion was wrong: a return type that needs a paragraph of excuse is the wrong return type. `LibraryCrate.fingerprint` documents itself as "SHA-256 hex digest of the serialized concepts + pipes content", and handing back a crate that violates its own field docstring is a trap for whoever reads it next.++Returning the two mappings makes the contradiction unrepresentable, and it costs the callers nothing — both of them already hold the crate they passed in, so the envelope is right there, and `normalize_crate` constructs a fresh crate anyway. Phase 2's `load_from_crate` keys idempotency on the **incoming** crate's fingerprint, which is what external callers pass to `is_crate_loaded`; nothing downstream ever wanted a fingerprint from the pass. It also dissolves a second issue for free: with no envelope to carry, there is no question of whether `source_map` / `domains` / `python_sources` come back aliased or copied.++The neighbouring bug this originally guarded against is unaffected and still real: `normalize_crate` builds its result field by field and drops `python_sources` (deferred, [normalize-crate-drops-python-sources-deferred.md](normalize-crate-drops-python-sources-deferred.md) — the one-line fix moves customer Python source into a CLI stdout stream and an HTTP response body, which is a disclosure decision, not a typo correction).++**A test-design trap worth carrying into Phase 2.** The pass's own test module was first written around a fixture full of bare refs, asserting the envelope, non-mutation, and idempotency — and every one of those tests passed against a `qualify_crate` replaced by a no-op, because none of them read a ref *out of the result*. The envelope looked right, the input was untouched, and two no-ops compared equal. The rule itself was covered (a no-op reddens fifteen tests in the normalizer suite), so nothing was actually unguarded — but the module that existed to state the pass's contract could not tell the pass from a stub. It now reads a qualified ref back out in every test, and a no-op reddens twelve of fourteen.++The shape of that mistake — a fixture rich enough to look thorough, assertions that never touch the transformed value — is exactly what Phase 2's resolution-row tests are exposed to, on top of the single-domain blindness already noted. Both are only caught by mutating the thing under test.++**Consumer inventory:** [normalized-crate-consumers.md](normalized-crate-consumers.md). The headline is that the plan's worst case does not exist — nothing writes a normalized crate back over a `.mthds` source file. `pipelex fix` rewrites user files but never through a crate, and no fix op writes a pipe ref at all (a property Phase 2 should re-check rather than assume). What does move is the stamped `codegen.lock` fingerprint, on every committed projection.++**Observation for a later phase, not acted on:** `_qualify_io_ref`'s cross-package guard appears unreachable through a constructed blueprint — the io-ref validator rejects `alias->domain.Concept` in `inputs` and `output` outright. The guard is preserved verbatim by this refactor; whether it is genuinely dead is a question for the phase that owns cross-package reference forms.++### Phase 2 outcome (C2)++**The branch's reason to exist, landed.** The pipe rule is now owner-domain qualification, `PipeLibrary.get_optional_pipe` no longer searches, and hand-typed codes go through the entry affordance. OQ2 and OQ3 are answered above.++**The export bypass is closed, and it was measured rather than argued.** Re-running the README's demo closures on the fixed tree: `export-bypass` now fails to resolve where it used to reach a non-exported `beta.helper` by bare code; `fallthrough` fails with the new message; `ambiguous` now resolves to `alpha.summarize` — the standard's own answer — where it used to be a load failure. The re-measured table is in [README.md](README.md) §3, and §2's divergence table is marked historical rather than rewritten.++**What the corpus warning was worth.** Phase 1 measured that this repo's bundles are blind to the flip, and that held: the whole `.mthds` corpus needed no edit. The breakage landed instead in *test fixtures that hand-build pipes*, bypassing the crate pass — 137 failures across 31 files, every one of them a test constructing what the compiler now constructs differently. Worth stating plainly because it is the shape of the change: a rule enforced at build time moves work onto anything that skips the build.++**Two call sites the plan never listed**, both found by running the suite rather than grepping, as the plan itself instructed:++- `validate_bundle.py` resolved a bundle's own `[pipe.<code>]` keys as bare codes. Fixed by qualifying with the bundle's domain — precise, and deliberately *not* routed through the entry affordance: these keys are declarations with a known domain, not something a human pointed at.+- `dry_run_in_process.best_effort_graph_spec` resolved a caller-supplied graph target. Entry-shaped, now on the affordance. This one is worth remembering: it swallows `PipelexError` and degrades to "no graph" with a warning, so under the strict lookup it would have silently stopped producing graphs rather than failing. A test caught it; nothing else would have.++**A review finding that was directionally right and factually wrong.** The plan carried, from the outside-voice pass, that the batched sub-pipe derivation "produces the invalid code `domain.foo_batch`". The derivation was indeed wrong, but the consequence was not: `PipeAbstract` has a `code` field validator that strips a namespace prefix, so the built ref was correct all along. What the bug actually produced was a `log.warning` on **every** batched run, about a code no user wrote. This matters twice over — the first test written for the fix asserted on the resulting ref, passed against the bug, and had to be rewritten to assert on the warning. **A finding that names a file and a line is still a claim to verify, not a fact to implement.**++**`missing_pipe_code` is now the qualified ref.** A structured field machine consumers branch on, so this is wire-visible and is in the changelog as breaking. It is the right value: the field should name what was tried, not what was typed, or the error describes a lookup nobody performed.++**Mutation-checked.** Restoring the crate-wide search in the pass reddens exactly the discriminating rule tests and both message tests; restoring the deleted fall-through in `get_optional_pipe` reddens the strict-lookup tests; reverting the batch derivation reddens the warning test; putting one CLI command back on the strict lookup reddens the bare-code end-to-end test. Each mutation reddens its own guard and nothing else.++### Phase 3 outcome (C3)++**The concept side landed as an entry affordance, not a lookup parameter.** `ConceptLibrary.get_required_concept_from_concept_ref_or_code` and its `search_domain_codes: list[str]` are gone; the replacement is the pair `get_optional_entry_concept` / `get_required_entry_concept(concept_ref_or_code, *, search_scope: str | None)` — kept deliberately separate from the pipe pair per the share-vs-duplicate ruling, and different from it in exactly the two ways that ruling predicted: natives resolve first (the standard's own step 1), and there is a scope-preference step the pipe side does not have.++**The ambiguity question is settled: raise, naming the candidates — but only after the scope preference has had its chance.** The old own-domain-first `insert(0)` in `pipeline_run_setup` was dead code (README §4 row 3: the walk collected all matches and raised before position 0 could win). The preference is now real and sits *before* the crate-wide scan: the entry pipe's own domain wins outright; only when it lacks the code does the scan run, serving a unique match and refusing an ambiguous one. Every refusal — invalid string, ambiguity, genuine miss — raises `ConceptLibraryConceptNotFoundError`, the class the `stuff_factory` handlers actually catch (funneled through one `_resolve_entry_concept` helper since the post-C3 review round, which also moved the invalid-string escape onto that class), which deletes §4's defect (2) (the wrong-class escape) structurally rather than by patching the walk; defect (3)'s first-miss death is gone because there is no per-domain walk left. The re-measured matrix is in README §4.++**The scope is package-scoped, not just domain-scoped — the concept twin of OQ1, answered the cheap way.** `search_scope` is a single string derived from the resolved entry pipe: its domain, prefixed `alias->domain` when the caller invoked a dependency pipe (`pipeline_run_setup` reads the alias off the caller-supplied ref before it is normalized away). Dependency concepts are keyed `alias->domain.Concept`, so the scoped preference is a direct key construction — no child-library machinery needed. Aliased entries are excluded from the crate-wide scan (an installed package must not make a host code ambiguous), and stay reachable through the scope or an explicit `alias->` ref. The post-C3 review round found the scoped preference alone insufficient for a *multi-domain* dependency — it probed exactly one key while the crate-wide scan excluded the whole package — so the affordance gained the pipe side's alias-scoped package search: when the scoped key misses, the rest of the entry pipe's package is searched before the host crate, `alias->Concept` is that search's explicit spelling, and dotted refs obey the same scope-wins precedence (host-first binding would have been silent on a host/dep domain-name collision, since compatibility short-circuits on equal `concept_ref`). Unlike the pipe-side OQ1 — where package scope has to travel through the whole execution path and is deferred to the packaging project — the concept lookup is entry-only and its one call site holds the alias, so this phase could pay it in full.++**The caller sweep deleted the parameter from the public surface.** `PipelexMTHDSProtocol` (constructor), `pipeline_run_setup`, `prepare_pipe_job`, `shape_inputs` (kernel), `WorkingMemoryFactory.make_from_pipeline_inputs`, `InputShaper.shape` and `StuffFactory.make_stuff_from_stuff_content_or_data` all now thread `search_scope: str | None`; no caller supplies it from outside — `pipeline_run_setup` derives it. Breaking, in the changelog.++**`fix_loop` collisions are per-domain.** `_pipe_codes_by_file` records each file's declared domain and `_split_cross_file_collisions` only checks a rename against same-domain siblings (unknown domain stays conservative, colliding with everything). Two integration tests that pinned the crate-wide scope flipped: the rebuild-between-rounds pin moved to a same-domain fixture (the only shape that still collides), and the other-domain arm became a convergence test — the rename applies and the bundle heals.++**Mutation-checked again.** Removing the scope-preference block reddens the both-declare row, the aliased-scope row and the end-to-end wiring test; letting aliased keys into the crate-wide scan reddens the exclusion row; dropping `search_scope` at the one wiring point (`pipeline_run_setup` → `prepare_pipe_job`) reddens the integration test and the characterization pin; restoring the crate-wide collision scope in `fix_loop` reddens the different-domains-both-apply test. The review-round refinements got the same treatment: removing the package search, reverting dotted refs to host-first, reverting the invalid-string class, and dropping the `alias->Concept` branch each redden exactly their own rows. Every mutation reddened its own guards and nothing else, measured live.diff --git a/wip/pipe-refs/corpus-measurement.md b/wip/pipe-refs/corpus-measurement.mdnew file mode 100644index 000000000..22ff8c821--- /dev/null+++ b/wip/pipe-refs/corpus-measurement.md@@ -0,0 +1,68 @@+# The fall-through corpus, measured across the whole workspace++**Status.** Measured 2026-08-11 for Phase 0 of [../../TODOS.md](../../TODOS.md). This widens [README.md](README.md) §5, which scoped its scan to a hand-written list of ten sibling repos. It does **not** gate shipping — the repo's no-backward-compatibility principle stands and there is no deprecation period. It calibrates the changelog wording and how much to invest in the error message.++This is a dated snapshot with a reproduction command, which is why it carries raw counts. Other documents should point here rather than restate them.++## How this scan differs from README §5++README §5 passed a hardcoded list of roots. Enumerating the workspace instead finds `.mthds` files in far more places, and a repo in neither column of a hardcoded list looks checked when it was never opened. Reproduce:++```bash+cd .. && ROOTS=(); for d in */; do+ case "$d" in _*|pipelex/) continue;; esac # _* are worktrees of this repo; pipelex/ is its main checkout+ n=$(find "$d" -name "*.mthds" -type f -not -path "*/node_modules/*" -not -path "*/.venv/*" | wc -l)+ [ "$n" -ne 0 ] && ROOTS+=("$d")+done; cd _refs+.venv/bin/python wip/pipe-refs/probes/classify-bare-refs.py "${ROOTS[@]/#/../}"+.venv/bin/python wip/pipe-refs/probes/classify-bare-refs.py .+```++Requires bash or zsh — the array syntax is not POSIX `sh`. Use `-ne 0`, not `!= "0"`: BSD `wc -l` pads its output, so a string comparison never filters anything and the roots list silently differs between macOS and Linux.++## Numbers++| | this repo | every other `.mthds` tree in the workspace | README §5's narrower scan (ten sibling repos) |+| --- | --- | --- | --- |+| bundles read | 124 | 506 | 90 |+| merge units | 57 | 336 | 36 |+| **bare in-body pipe refs** | **142** | **1360** | 158 |+| `own-only` | 136 | 1331 | 153 |+| **`sibling-only`** — the column that breaks | **0** | **2** | 1 |+| `both` | 6 | 16 | 1 |+| `nowhere` | 0 | 11 | 3 |+| **bare in-body concept refs** | **283** | **2389** | 367 |+| `own-only` | 255 | 2197 | 341 |+| **`sibling-only`** | **0** | **3** | 0 |+| `both` | 27 | 135 | 22 |+| `nowhere` | 1 | 54 | 4 |++Read the columns as scopes, not as a total: the whole workspace is **630 bundles and 1502 bare pipe refs** (this repo plus every other tree). Like for like, widening the scan takes the corpus from README §5's 300 bare pipe refs (its ten repos' 158, plus this repo's 142) to 1502. Of the bundles outside this repo, §5's ten-repo list reached 90 of 506 — under a fifth.++## What the denominator is, and is not++The caveats in README §5 ("What this measurement does not cover") all still apply — in particular, a directory is not always a merge unit, so `both` is an upper bound and **`sibling-only` is the robust column**. Two more apply to this wider scan specifically, both inflating the denominator:++- **Duplicates.** The enumerated roots hold 510 `.mthds` files with only 360 distinct contents: 256 files sit in one of 106 byte-identical groups, spread across roots (starters, demos and fixtures copy bundles wholesale). The scan counts files, not distinct bundles.+- **Scratch trees.** Enumeration reaches material README §5 deliberately fenced off — the workspace's internal scratch, demo, and container-session trees (none of them open core; the list lives in the workspace-level private notes) — 67 files in all. §5 called the demo bundles pathological and kept them out; enumerating by definition cannot.++So the denominator is an upper bound and the breakage *ratio* is a floor. That does not touch the finding: the two breaking references are named files in neither category, and no scratch tree or duplicate contributed one.++## The two pipe references that break++Both are real, and one of them is not in an examples directory:++1. `pipelex-cookbook/examples/wip/advisory_board/bundle.mthds` — `advisory_orchestrator.master_advisory_orchestrator` names a bare `present_as_markdown` declared only by the `presentation` domain. Already scheduled for qualification in Phase 4b.+2. `cocode/cocode/pipelines/swe_diff/changelog_enhanced.mthds` — `changelog_enhanced.write_changelog_enhanced` names a bare `format_changelog_as_markdown` declared only by the `changelog` domain, in `changelog.mthds` in the same directory. **`cocode` is a shipped CLI, not a sample**, and README §5 never scanned it. Fix by writing `changelog.format_changelog_as_markdown`.++ This one is not an artifact of the probe's directory grouping: `cocode/common.py` sets `PIPELINE_LIBRARY_DIRS = [<package>/pipelines]`, so the whole tree loads as a single library and the two domains genuinely coexist in one merge unit.++Two references, and the fix for each is one qualified spelling.++## The three concept references are not new breakage++All three are in `vscode-pipelex/test-data/mthds/` (`pipe-definitions.mthds` referencing concepts declared in `concept-tables.mthds`). They are editor fixtures for the extension's goto-definition tests, and they **already** fail to load under today's runtime: the concept side qualifies to the owner domain at build time (`_qualify_concept_ref`), and `PipeFactory.make_from_blueprint` rejects a bare non-native concept ref that the pipe's own domain does not declare. README §5 reported zero simply because `vscode-pipelex/` was not one of its ten roots — its classifier reads TOML and is resolver-independent, so it would have counted these fixtures too had it opened them. The concept side of this change tightens the *library lookup*, which these fixtures never reach.++## What this means for the changelog++Say what breaks, not that something might: **a bare in-body pipe reference no longer resolves into another domain**, and across every `.mthds` tree in this workspace that is two references, both fixed by qualifying the spelling. Name the resolution rule and point at the error message, which suggests the crate-wide candidate when one exists.diff --git a/wip/pipe-refs/dependency-subpipe-scope-deferred.md b/wip/pipe-refs/dependency-subpipe-scope-deferred.mdnew file mode 100644index 000000000..d0c1044e7--- /dev/null+++ b/wip/pipe-refs/dependency-subpipe-scope-deferred.md@@ -0,0 +1,50 @@+# Deferred: a dependency pipe's own sub-pipe refs resolve against the HOST library++**Status.** Measured 2026-08-11 while answering OQ1 of [build-time-qualification.md](build-time-qualification.md). Pre-existing, independent of the pipe-refs change, and deliberately **not** fixed on this branch — the fix needs package scope threaded through the lookup, which is the packaging project's design work. Reproduce with [`probes/dep-subpipe-scope.py`](probes/dep-subpipe-scope.py).++Code is cited by symbol, not by line: this note is written to outlive the branch, which itself edits several of these regions.++## What is broken++A dependency package is loaded into an isolated *child* `Library` and its pipes are **also** registered in the host library under aliased keys (`alias->domain.code`). When a dependency's own controller pipe names a same-domain sub-pipe, three readers disagree about which library to search:++| Reader | Where | Scope it searches |+| --- | --- | --- |+| dependency-dep loop | `Library.validate_pipe_library_with_libraries`, its first loop | the **child** library — explicitly special-cased for an aliased pipe key |+| per-pipe validation | same method's second loop → `PipeAbstract.generic_validate_inputs_with_library` → `PipeSequence.needed_inputs` | the **host** library, via `interpreter_hub.get_required_pipe` — no special case |+| execution | `SubPipe.run_pipe` | the **host** library, via the same hub accessor — no special case |++The child-library special case is neutralized by the second loop in the very same method. And the host lookup cannot reach the dependency's own pipe either: `PipeLibrary.get_optional_pipe` is a strict key lookup, so a bare code matches nothing there. (Before this branch it instead ended in a crate-wide bare-code fall-through that explicitly **skipped** `alias->` entries — same outcome, different mechanism; that fall-through is what row 2 of the baseline table below measured.)++## A second defect, in the shape a real package ships++The child library is built from the crate under an export filter (`if has_exports and pipe_code not in all_exported: continue`, in `LibraryManager._load_single_dependency`). It carves out *synthetic* helpers — the comment right above it states the hazard exactly: "When the parent is exported, its helpers must travel with it — otherwise the wrapping PipeSequence references unresolved pipe codes at runtime." It does **not** carve out **authored** ones. So a controller's own private helper is dropped from its own package's library, and the failure lands before the scope disagreement above can even be reached.++## Measured behaviour++The table below is the **pre-Phase-2 baseline** — measured before the qualification pass landed on the dependency load path. Re-running the probe on this tree shows the post-change verdicts the next section describes: shapes 1 and 3 still fail, and row 2's silent capture is now a deterministic load failure.++A dependency whose exported entry is a `PipeSequence` calling a bare same-domain helper, under three shapes:++| Shape | Load verdict | What the execution reader resolves the helper to |+| --- | --- | --- |+| no manifest exports; host declares nothing | **fails** in the *second* loop — `PipeNotFoundError: Pipe 'probe_helper' not found` | `None` |+| no manifest exports; host declares its own unrelated pipe under the same bare code | **valid** | the **HOST's** pipe — a silent cross-package capture |+| manifest `[exports]` names only the entry pipe — *the published shape* | **fails** in the *first* loop — `LibraryLoadingError: Error validating pipe 'probe_entry' dependency pipe 'probe_helper'` | `None`; the helper is absent from the child library too |++So today a dependency package that uses a controller internally either does not load at all, or loads and binds to whatever the host happens to have named the same way. Neither is the dependency's own helper. No fixture in `tests/data/packages/` exercises this — every dependency there exports a leaf `PipeLLM`, which is why it has never surfaced.++## Why the pipe-refs change does not fix it, and does not worsen it++Owner-domain qualification rewrites the authored bare `helper` to `dep_domain.helper`. Measured against the same host library, that ref also resolves to `None` — the host holds it as `alias->dep_domain.helper`. So:++- **not a regression, but only because the two edits co-landed.** Reader row 1 *was* served by the bare fall-through: the child library's keys are `dep_domain.helper`, and the first loop looked up a **bare** code against it, which only succeeded via that fall-through. Deleting the fall-through alone would have broken row 1. Both edits landed in the same phase — the qualification pass on the dependency load path (`LibraryManager._load_single_dependency`) and the strict lookup — so the first loop's lookup is qualified now that the fall-through is gone. That co-landing was load-bearing, not incidental — it is also what makes "`library` validation needs no edit" true.+- **strictly better on the capture.** The silent host-capture in row 2 becomes a deterministic not-found. A bundle that loads today and runs the wrong pipe will stop loading — loudly, naming `dep_domain.helper`, which points at the scope that should have been searched.+- **it moves the eventual fix closer.** The child library's own keys are exactly `dep_domain.helper`. Once the lookup is package-scoped, a qualified ref is a direct key hit in the child library; a bare one would still need a search.++## What the fix requires (packaging project)++Two independent pieces, both needed:++1. **Scope.** The caller's **package** must reach the lookup, the way its domain now does. Either the resolved sub-pipe ref carries its alias (`alias->dep_domain.helper`) when the referring pipe came from a dependency, or the run scopes the current library to the child while executing inside that package. Both are contract decisions about cross-package reference form, which [build-time-qualification.md](build-time-qualification.md) explicitly defers ("No cross-package resolution design"). Whichever is chosen, the two validation readers and the execution reader must end up on the same one — that is the parity requirement this note exists to preserve.+2. **Export filtering.** A pipe an exported pipe depends on must travel with it, whether the helper is synthetic or authored. Scope alone does not fix the published shape: the helper is not in the child library to be found.diff --git a/wip/pipe-refs/entry-affordance-share-vs-duplicate.md b/wip/pipe-refs/entry-affordance-share-vs-duplicate.mdnew file mode 100644index 000000000..d13d8ff67--- /dev/null+++ b/wip/pipe-refs/entry-affordance-share-vs-duplicate.md@@ -0,0 +1,33 @@+# The pipe entry affordance and the concept one: separate, deliberately++**Ruling: keep them separate. Do not extract a shared helper.** Recorded during the pipe-side work so that Phase 3 inherits a decision rather than a discovery — an accidental copy found later is not the same thing as a chosen duplication.++## What is actually shared++Reduced to their skeletons, the two look like twins:++```+exact ref -> direct hit+bare code -> scan entries, excluding aliased dependency keys+ 1 match -> return it+ >1 match -> raise, naming the candidates+ 0 match -> None / raise+```++That is roughly six lines of list comprehension and two error messages. If that were the whole story, sharing would be obvious.++## Why they are not twins++**1. The concept side has a step the pipe side does not, and cannot have.** Natives. `Text` is not a bare code to be searched for — it resolves to `native.Text` before any scan, by the standard's own step 1 (`NativeConceptCode.is_native_concept_ref_or_code`). There is no pipe equivalent. A shared helper would either carry a native branch that is dead for pipes, or take a "resolve specials first" callback, which is a worse thing than two small functions.++**2. The two live on different objects with different roots.** `PipeLibrary.root` is `dict[str, PipeAbstract]`; `ConceptLibrary.root` is `dict[str, Concept]`. Sharing means a generic over a protocol exposing `.code` and `.pipe_ref`/`.concept_ref` — the two ref properties are not even named the same. The generic machinery would outweigh the code it factors out.++**3. Their ambiguity answers are not obviously the same question.** For pipes, an ambiguous hand-typed code must raise: guessing which `summarize` the user meant is a coin flip with a silent wrong answer. The concept side *currently* has `search_domain_codes` and an own-domain-first preference, and its spec stops at "unique match" without saying what happens otherwise. Phase 3 has to settle whether that preference is meaningful or vestigial. **Binding the two together before that question is answered would smuggle the pipe answer into the concept surface** rather than deciding it.++## What to do instead++Phase 3 should copy the *shape* and the *reasoning* — including the aliased-dependency exclusion, which is a correctness requirement on both sides for the same reason (an installed package must not make a host code ambiguous) — and write the concept version against the concept library's own facts. If, after Phase 3 lands and the concept ambiguity question is settled, the two really have converged to the same six lines, extracting then is cheap and the decision will be informed. Extracting now would be guessing.++## The part that must not be duplicated++The *rule* — that in-body refs qualify to their owner domain and are never searched for — has exactly one implementation, `crate_qualification.qualify_crate`, and both readers consume it. That was the whole point of Phase 1. The entry affordances are the deliberate exception to no-fall-through, not a second copy of the resolution rule, and it is worth keeping the two ideas apart when reading this: sharing the *rule* is mandatory, sharing the *affordance* is not.diff --git a/wip/pipe-refs/normalize-crate-drops-python-sources-deferred.md b/wip/pipe-refs/normalize-crate-drops-python-sources-deferred.mdnew file mode 100644index 000000000..84034f922--- /dev/null+++ b/wip/pipe-refs/normalize-crate-drops-python-sources-deferred.md@@ -0,0 +1,30 @@+# Deferred: `normalize_crate` drops `python_sources`++**Status.** Noticed 2026-08-11 during Phase 1 of [../../TODOS.md](../../TODOS.md), while auditing the crate copy path for dropped fields (the plan asks for that audit precisely so a new pass does not reproduce the bug). Pre-existing, unrelated to the pipe-refs change, and deliberately **not** fixed on `fix/Pipe-refs` — the fix is a one-line addition whose *consequences* need a decision this branch is not the place to take.++## What happens++`normalize_crate` builds its result with an explicit `LibraryCrate(...)` constructor listing the fields it carries over. `python_sources` is not among them, so a crate that arrived carrying customer Python source returns without it. Every other envelope field (`domains`, `source_map`) is carried explicitly; `python_sources` is the one omission, which reads like an oversight rather than a decision — there is no comment claiming the drop is intended.++It is reachable, not theoretical: all three `normalize_crate` call sites take their crate from `LibraryManager.get_crate`, which populates `python_sources` from `_library_sources`. Whenever a library was loaded in sandbox-hosted mode, the input crate has the field and the output does not.++## Why the obvious fix is not a drive-by++Adding `python_sources=crate.python_sources` changes what three surfaces emit:++- `pipelex resolve` prints the encoded crate to stdout. Today the customer's `.py` source is not in that output; after the fix it would be.+- The `/resolve` API route returns the normalized crate in its response body.+- `emit_types` reads it (harmless — it only projects concepts), but the stamped `codegen.lock` records `crate_fingerprint`, which is unaffected either way: `python_sources` is deliberately excluded from both digest schemes.++So the fix moves customer Python source into a CLI stdout stream and an HTTP response body. That may well be correct — the field exists precisely so source can travel with the method — but it is a disclosure-surface decision, not a typo correction, and it belongs with whoever owns the sandbox-hosted transport contract.++## Why Phase 1 could leave it alone safely++The extracted qualification pass does **not** reproduce the bug, and for a stronger reason than the one first written here: `qualify_crate` returns a `QualifiedCrateContent` — just the rewritten `concepts` and `pipes` — never a `LibraryCrate`. There is no envelope for it to rebuild, so there is no field for it to drop. The class of bug is unrepresentable in the pass rather than merely avoided by it, which is why this note is a deferral and not a blocker.++*(An earlier draft of this paragraph credited `crate.model_copy(update=…)` for preserving the envelope. That described the pass's first cut, which returned a crate; review pushed back on that return type and it changed. The claim is recorded here as corrected rather than silently swapped, because "why the pass is safe" is exactly the sentence a future reader will lean on.)*++## What a fix would need++1. Rule on whether the normalized crate is allowed to carry customer source, per surface (CLI stdout, `/resolve` response, in-process consumers). The answer may differ by surface, in which case the field is dropped at the *presentation* boundary rather than in `normalize_crate`.+2. Whichever way it goes, state it in `normalize_crate`'s docstring, so the next reader finds a decision instead of an omission.diff --git a/wip/pipe-refs/normalized-crate-consumers.md b/wip/pipe-refs/normalized-crate-consumers.mdnew file mode 100644index 000000000..acd17e3d1--- /dev/null+++ b/wip/pipe-refs/normalized-crate-consumers.md@@ -0,0 +1,36 @@+# Who consumes normalized-crate output++**Status.** Inventoried 2026-08-11 for Phase 1 of [../../TODOS.md](../../TODOS.md). The plan asks for this before the Phase 2 rule flip, because the flip changes what a normalized in-body ref *says*: a bare `present_as_markdown` that today normalizes to the sibling domain's `presentation.present_as_markdown` will normalize to the owner's `orchestrator.present_as_markdown`. Anything that persists, stamps, or compares that output moves with it.++## The headline: nothing writes a normalized crate back to `.mthds`++This was the plan's stated worry — "if formatting persists a qualified ref into a user's source file, the flip rewrites their code, not just its in-memory form". It does not happen. No code path encodes a crate into `.mthds` and writes it over a source file. The crate encoder is used for stdout only (`pipelex resolve`); the codegen projections consume a normalized crate but encode a **lock**, not a crate.++The one command that *does* rewrite user `.mthds` files is `pipelex fix`, and it does not go through a crate at all: `fix_loop` edits a tomlkit DOM of the user's own file, applying ops planned from validation-error data. Two properties keep it clear of this change:++- The ops that write a ref (`SET_KEY` into `["pipe", <code>, "inputs"]`) write **concept** refs, which are already qualified at build time today and are unaffected by Phase 2.+- **No fix op writes an *in-body* pipe ref.** `RENAME_TABLE_KEY` renames a pipe's own table key; nothing sets a `steps[].pipe`, a branch, an outcome, or a `branch_pipe_code`. One fix op *does* write a pipe ref, and it is worth naming rather than glossing: `strip-namespace` plans a root `SET_KEY` of `main_pipe`. That is an **entry-point** ref, not an in-body one, and it *strips* a same-domain prefix rather than adding one — so it cannot rewrite an author's bare in-body spelling into a qualified one, which is the hazard this section is actually about. (`planner.py`'s `_plan_strip_namespace` says so in its own docstring: only the declaration key and `main_pipe` are ever stripped, because internal refs keep resolving without a rewrite.)++That second property is load-bearing and worth restating in Phase 2: it holds today, and a new fix kind that writes a pipe ref would newly rewrite an author's bare spelling into a qualified one. It is a property to re-check, not an invariant to assume.++## The consumers++Three entry points call `normalize_crate`; everything else is downstream of them.++| Call site | What it feeds | What the flip does to it |+| --- | --- | --- |+| `pipelex/cli/commands/crate_loading.py` → `load_normalized_crate` | `pipelex resolve` (encodes to stdout), the `pipelex codegen` family (`types`, `inputs`), and their agent-CLI twins | `resolve` prints qualified refs where the author wrote bare — already true today for concept refs and for cross-domain pipe refs; the flip changes *which* domain a bare pipe ref prints as |+| `pipelex/pipeline/resolve_bundle.py` → `resolve_crate_from_contents` | the `/resolve` API route and the agent-CLI resolve path | same, over the wire |+| `pipelex/cli/commands/build/runner/_runner_core.py` | `emit_types` → `write_stamped_projection` into `structures/` | the stamp is the concern, see below |++## The stamped artifacts are the thing that actually churns++`write_stamped_projection` records `crate_fingerprint` (the normalized, D2-scope digest) into `codegen.lock` beside the emitted `structures.py`. Qualification is part of the hashed content, so **every** stamped projection in the repo and in downstream repos gets a new fingerprint the moment the rule flips — even for a library whose emitted Python is byte-identical, because the digest covers pipes and domains, not just the concepts the types projection reads.++Practical consequence for Phase 2: expect lock-file churn wherever a stamped projection is committed, and regenerate rather than hand-edit. This is also the mechanism by which the flip reaches `pipelex-cookbook` and any starter repo carrying a committed `codegen.lock`.++## What the corpus says about all this++Measured while proving the Phase 1 extraction behavior-identical: applying the Phase 2 rule to all 54 crates buildable from this repo's `.mthds` files changes **nothing** — every normalized output is byte-identical under both rules. Every bare in-body pipe ref in this repo already resolves within its own domain.++That is a useful de-risking result for the *repo's* artifacts, and simultaneously the sharpest possible argument for the plan's two-domain fixture requirement: a test suite grounded in this corpus cannot tell the two rules apart, so it would pass just as happily under the rule being deleted. The discriminating cases have to be built by hand.diff --git a/wip/pipe-refs/plan-docs-have-no-drift-contract.md b/wip/pipe-refs/plan-docs-have-no-drift-contract.mdnew file mode 100644index 000000000..39be2ede8--- /dev/null+++ b/wip/pipe-refs/plan-docs-have-no-drift-contract.md@@ -0,0 +1,61 @@+# Plan and `wip/` docs go stale the way `docs/` used to, and nothing catches it++**Status: an observation with a concrete proposal, deliberately not acted on in this branch.** Recorded because the evidence for it was collected by accident and would be expensive to reconstruct.++## The evidence++Across three PR-review rounds on the pipe-refs branch, review found four documentation claims that were **true when written and went false when something downstream changed**. None was careless writing; each described a real thing accurately at the time.++| Claim | What made it false |+|---|---|+| "`qualify_crate` copies the envelope with `crate.model_copy(update=…)`" | The pass's return type changed from `LibraryCrate` to `QualifiedCrateContent` after a review push-back. The sentence described the first cut. **It was stale in three places; the bot found one.** |+| "No fix op writes a pipe ref" | Never true, but written from a partial read of the fix planner — `strip-namespace` plans a root `main_pipe` `SET_KEY`. |+| `crate_normalization.py:290` / `:135`, `sub_pipe.py:161`, `pipe_library.py:81` | Line-number pointers into code **this same branch was editing**. Two of them went stale between Phase 1 and Phase 2 — inside one branch, in one sitting. |+| "Deliberately left for Phase 2: …" | Survived Phase 2's completion, so the plan simultaneously declared a phase complete and assigned it unfinished work. |++Plus one structural version of the same failure: the Status block declared checkpoint C2 passed while C2's own checklist sat entirely unticked. Every item was in fact done — the two statements were written at different moments and never reconciled.++## Why this is a systems observation and not a scolding++`docs/` has a mechanism for exactly this: **drift contracts** (`drift.toml`, `docs/contribute/drift-contracts.md`). A contract binds a set of trigger files to a set of review targets; when the triggers change, the contract opens and the change cannot land until someone reviews the targets and records an honest rationale. It works — on this very branch it opened twice, and the `hub-layering` one caught a symbol table that really had gone stale.++**`TODOS.md` and `wip/` are not under any contract.** They are precisely the documents that describe code in motion, written while the code is still moving, and they are the only prose in the repo with no staleness gate at all. The failure rate above is what that predicts.++## The proposal++A `plan-docs` drift contract, roughly:++- **triggers:** the source files a plan names as its subject — for the pipe-refs work, `pipelex/libraries/crate_qualification.py`, `crate_normalization.py`, `pipe/pipe_library.py`, `library.py`.+- **targets:** `TODOS.md` and the feature's `wip/<feature>/` directory.++The rationale requirement is the useful part, not the mechanism: it forces someone to re-read the plan against the code it claims to describe, at the moment the code moves.++## Why it is NOT being done here++Three honest reasons, in order of weight:++1. **It is out of scope.** This branch changes reference resolution. Adding repo-wide review machinery to it would be exactly the over-engineering the maintainer asked to avoid, and it would arrive bundled with a breaking language change where it cannot be evaluated on its own merits.+2. **The trigger set is per-feature, and that is a design question.** A generic "any `pipelex/` change opens the plan contract" would fire on every commit and be acked reflexively, which is worse than nothing — a gate that is always open teaches people to close it without looking. Getting it right means deciding how a plan declares its own subject, and that deserves its own thinking.+3. **Two cheaper habits capture most of the value**, and both are already recorded in `TODOS.md`'s Phase 3 section:+ - **Do not write line numbers into prose about code you are editing.** Name the symbol. A line number is a fact with a half-life measured in commits; a function name survives a refactor and is what the reader greps for anyway.+ - **Tick a checklist in the same edit that updates the summary claiming it is done.** The two statements are only worth something when they cannot disagree, and they can only disagree if they are written at different times.++## If someone picks this up++Start with the second habit rather than the machinery — a `plan-docs` contract that fires on a plan whose checkboxes and Status block already agree is catching a much rarer bug.++### Already measured++Across `wip/**/*.md` plus `TODOS.md`, counting only pointers whose file exists in this repo:++- **123** in-repo `path.py:NNN` pointers.+- **4** point past the end of the file they name, so they are *provably* stale:+ - `wip/refactoring/modularity-refactors.md` → `pipelex/pipelex.py:500` (file has 352 lines)+ - `wip/inputs/yesno-implementation-plan.md` and `wip/inputs/datetime-implementation-plan.md` → `pipelex/core/registry_models.py:92` (57 lines)+ - `wip/inputs/smart-inputs-implementation-plan.md` → `pipelex/cli/commands/run/_inputs_path_resolver.py:75` (69 lines)++**4 is a floor, not the count.** Out-of-range is the only staleness a script can prove cheaply; a pointer that has drifted to the wrong line *within* the file looks perfectly healthy to this check and is the more common case — the pipe-refs pointers that a reviewer caught were all in range and all wrong. Read the number as "at least 4 of 123, and the real figure needs a human or a symbol-resolving check".++These four belong to other features and are left alone here; the point of measuring was to establish whether the pattern is local to one plan (it is not) before proposing repo-wide machinery for it.++A cheaper variant worth considering before the full contract: have the check resolve the *symbol* named next to the pointer rather than the line, which turns "is this line still there" into "is this still where that function lives" — the question the reader actually has.diff --git a/wip/pipe-refs/probes/classify-bare-refs.py b/wip/pipe-refs/probes/classify-bare-refs.pynew file mode 100644index 000000000..18c82c7af--- /dev/null+++ b/wip/pipe-refs/probes/classify-bare-refs.py@@ -0,0 +1,287 @@+# ruff: noqa: INP001 - a standalone probe script, deliberately not a package+"""Classify every bare in-body reference in a corpus of `.mthds` bundles.++Reads TOML and nothing else — no `pipelex` import, no library load — so the classification is a+property of the authored text, not of any resolver's behaviour. That is the point: it measures what+the corpus *asks for*, which is what decides how expensive each direction of the bare-ref fix is.++For every merge unit (see `merge_unit_of`), the probe builds `code -> {domains that declare it}` and+puts each bare in-body reference in one of four buckets:++ own-only the referring domain declares it, nobody else spec and runtime agree+ sibling-only ONLY some other domain declares it spec: ERROR, runtime: resolves+ both the referring domain AND another declare it spec: the own one, runtime: RAISES+ nowhere nobody declares it both error++`sibling-only` counts the references that would BREAK if the runtime were tightened to the spec.+`both` counts the references that are broken TODAY and would START WORKING under the spec.++Usage:++ python wip/pipe-refs/probes/classify-bare-refs.py <root> [<root> ...]++Each root is a directory tree to walk. Pass `.` for this repository's own corpus; pass sibling+checkouts to widen it.+"""++import pathlib+import sys+import tomllib+from collections import defaultdict+from typing import Any, NamedTuple++# Native concept codes take priority over any declaration (mthds/docs/spec/namespace-resolution.md+# § "Resolution Order for Bare Concept References", step 1), so a bare `Text` is never a lookup.+NATIVE_CONCEPT_CODES = frozenset(+ {+ "Dynamic",+ "Text",+ "Image",+ "Document",+ "Html",+ "TextAndImages",+ "Number",+ "YesNo",+ "Date",+ "Time",+ "Page",+ "JSON",+ "SearchResult",+ "Anything",+ "Composite",+ }+)++# pipelex/pipe_controllers/condition/special_outcome.py+SPECIAL_OUTCOMES = frozenset({"fail", "continue"})+# The only fields where `fail`/`continue` are special outcomes rather than pipe refs.+OUTCOME_FIELDS = frozenset({"outcome", "default_outcome"})++MANIFEST_NAME = "METHODS.toml"+SKIPPED_DIR_NAMES = frozenset({".git", ".venv", "node_modules", "__pycache__", "dist", "build"})+BUCKETS = ("own-only", "sibling-only", "both", "nowhere")+REPORTED_BUCKETS = ("sibling-only", "both", "nowhere")+++class Bundle(NamedTuple):+ path: pathlib.Path+ domain: str+ pipes: dict[str, Any]+ concepts: dict[str, Any]+++class Reference(NamedTuple):+ code: str+ where: str+++def merge_unit_of(path: pathlib.Path, *, root: pathlib.Path) -> pathlib.Path:+ """The directory whose bundles share one namespace with this one.++ A package (a tree with a `METHODS.toml` manifest) merges as a whole; a loose bundle merges with+ the other bundles sitting beside it, which is how a `-L <dir>` load behaves. This is an+ approximation of the loader, and it is the probe's main limitation — see the doc's "What this+ measurement does not cover".+ """+ for ancestor in [path.parent, *path.parent.parents]:+ if (ancestor / MANIFEST_NAME).is_file():+ return ancestor+ if ancestor == root:+ break+ return path.parent+++def strip_multiplicity(ref: str) -> str:+ """Drop the presence and multiplicity markers a concept ref may carry (`Foo[]?` -> `Foo`)."""+ bare = ref.strip()+ while bare.endswith(("?", "!")):+ bare = bare[:-1]+ if bare.endswith("]") and "[" in bare:+ bare = bare[: bare.rindex("[")]+ return bare+++def bare_pipe_references(pipe_body: dict[str, Any]) -> list[Reference]:+ """Every in-body pipe reference this pipe names, in the blueprints' authored field names."""+ found: list[Reference] = []+ for step in pipe_body.get("steps") or []:+ if isinstance(step, dict) and isinstance(step.get("pipe"), str):+ found.append(Reference(code=step["pipe"], where="step"))+ for branch in pipe_body.get("branches") or []:+ if isinstance(branch, dict) and isinstance(branch.get("pipe"), str):+ found.append(Reference(code=branch["pipe"], where="branch"))+ outcomes = pipe_body.get("outcomes")+ if isinstance(outcomes, dict):+ for outcome_ref in outcomes.values():+ if isinstance(outcome_ref, str):+ found.append(Reference(code=outcome_ref, where="outcome"))+ for field_name in ("default_outcome", "branch_pipe_code"):+ field_value = pipe_body.get(field_name)+ if isinstance(field_value, str):+ found.append(Reference(code=field_value, where=field_name))+ # The fail/continue exemption belongs to outcome fields only (see crate_qualification.qualify_outcome):+ # a step, branch or batch target may genuinely name a pipe called `continue`.+ return [ref for ref in found if not (ref.where in OUTCOME_FIELDS and ref.code in SPECIAL_OUTCOMES)]+++def _structure_field_references(field_value: Any, *, where: str) -> list[Reference]:+ if not isinstance(field_value, dict):+ return []+ found: list[Reference] = []+ for key in ("concept_ref", "item_concept_ref"):+ nested = field_value.get(key)+ if isinstance(nested, str):+ found.append(Reference(code=nested, where=where))+ return found+++def bare_concept_references(bundle: Bundle) -> list[Reference]:+ """Every in-body concept reference the bundle names: pipe inputs/output, refines, structures."""+ found: list[Reference] = []+ for pipe_code, pipe_body in bundle.pipes.items():+ if not isinstance(pipe_body, dict):+ continue+ inputs = pipe_body.get("inputs")+ if isinstance(inputs, dict):+ for input_ref in inputs.values():+ if isinstance(input_ref, str):+ found.append(Reference(code=input_ref, where=f"{pipe_code}.inputs"))+ output = pipe_body.get("output")+ if isinstance(output, str):+ found.append(Reference(code=output, where=f"{pipe_code}.output"))+ for concept_code, concept_body in bundle.concepts.items():+ if not isinstance(concept_body, dict):+ continue+ refines = concept_body.get("refines")+ if isinstance(refines, str):+ found.append(Reference(code=refines, where=f"{concept_code}.refines"))+ structure = concept_body.get("structure")+ if isinstance(structure, dict):+ for field_name, field_value in structure.items():+ found.extend(_structure_field_references(field_value, where=f"{concept_code}.{field_name}"))+ return found+++def read_bundles(root: pathlib.Path) -> dict[pathlib.Path, list[Bundle]]:+ """Group every readable `.mthds` bundle under `root` by the merge unit it belongs to."""+ by_unit: dict[pathlib.Path, list[Bundle]] = defaultdict(list)+ for path in sorted(root.rglob("*.mthds")):+ # Root-relative parts only: a root that itself sits under a dir named `build`/`dist`/…+ # must not silently skip every bundle.+ if any(part in SKIPPED_DIR_NAMES for part in path.relative_to(root).parts):+ continue+ try:+ document = tomllib.loads(path.read_text(encoding="utf-8"))+ except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError):+ # A bundle this probe cannot parse is not this measurement's subject.+ continue+ domain = document.get("domain")+ if not isinstance(domain, str):+ continue+ pipes = document.get("pipe")+ concepts = document.get("concept")+ by_unit[merge_unit_of(path, root=root)].append(+ Bundle(+ path=path,+ domain=domain,+ pipes=pipes if isinstance(pipes, dict) else {},+ concepts=concepts if isinstance(concepts, dict) else {},+ )+ )+ return by_unit+++class Tally:+ def __init__(self, *, label: str) -> None:+ self.label = label+ self.counts: dict[str, int] = defaultdict(int)+ self.hits: dict[str, list[str]] = defaultdict(list)++ def record(self, *, bucket: str, detail: str) -> None:+ self.counts[bucket] += 1+ if bucket in REPORTED_BUCKETS:+ self.hits[bucket].append(detail)++ def total(self) -> int:+ return sum(self.counts.values())++ def report(self) -> None:+ print(f"\n{self.label}: {self.total()}")+ for bucket in BUCKETS:+ print(f" {bucket:14} {self.counts[bucket]}")+ for bucket in REPORTED_BUCKETS:+ print(f" --- {bucket} ---")+ for detail in self.hits[bucket] or ["(none)"]:+ print(f" {detail}")+++def classify(*, declared: dict[str, set[str]], domain: str, code: str) -> str:+ owners = declared.get(code, set())+ if not owners:+ return "nowhere"+ if owners == {domain}:+ return "own-only"+ if domain in owners:+ return "both"+ return "sibling-only"+++def main(roots: list[str]) -> None:+ pipe_tally = Tally(label="bare in-body PIPE refs")+ concept_tally = Tally(label="bare in-body CONCEPT refs")+ units_read = 0+ bundles_read = 0++ for raw_root in roots:+ root = pathlib.Path(raw_root).resolve()+ if not root.is_dir():+ msg = f"root '{raw_root}' is not a directory"+ raise SystemExit(msg)+ by_unit = read_bundles(root)+ units_read += len(by_unit)+ for bundles in (by_unit[unit_dir] for unit_dir in sorted(by_unit)):+ bundles_read += len(bundles)+ declared_pipes: dict[str, set[str]] = defaultdict(set)+ declared_concepts: dict[str, set[str]] = defaultdict(set)+ for bundle in bundles:+ for pipe_code in bundle.pipes:+ declared_pipes[pipe_code].add(bundle.domain)+ for concept_code in bundle.concepts:+ declared_concepts[concept_code].add(bundle.domain)++ for bundle in bundles:+ location = bundle.path.relative_to(root) if root in bundle.path.parents else bundle.path+ for pipe_code, pipe_body in bundle.pipes.items():+ if not isinstance(pipe_body, dict):+ continue+ for reference in bare_pipe_references(pipe_body):+ if "->" in reference.code or "." in reference.code:+ continue+ bucket = classify(declared=declared_pipes, domain=bundle.domain, code=reference.code)+ owners = sorted(declared_pipes.get(reference.code, set()))+ pipe_tally.record(+ bucket=bucket,+ detail=f"{location}: {bundle.domain}.{pipe_code} -> '{reference.code}' declared in {owners}",+ )+ for reference in bare_concept_references(bundle):+ code = strip_multiplicity(reference.code)+ if "->" in code or "." in code or code in NATIVE_CONCEPT_CODES:+ continue+ bucket = classify(declared=declared_concepts, domain=bundle.domain, code=code)+ owners = sorted(declared_concepts.get(code, set()))+ concept_tally.record(+ bucket=bucket,+ detail=f"{location}: {bundle.domain}.{reference.where} -> '{code}' declared in {owners}",+ )++ print(f"roots: {', '.join(roots)}")+ print(f"merge units: {units_read}")+ print(f"bundles read: {bundles_read}")+ pipe_tally.report()+ concept_tally.report()+++if __name__ == "__main__":+ if len(sys.argv) < 2:+ raise SystemExit(__doc__)+ main(sys.argv[1:])diff --git a/wip/pipe-refs/probes/concept-lookup-matrix.py b/wip/pipe-refs/probes/concept-lookup-matrix.pynew file mode 100644index 000000000..7d64ba191--- /dev/null+++ b/wip/pipe-refs/probes/concept-lookup-matrix.py@@ -0,0 +1,64 @@+# ruff: noqa: INP001 - a standalone probe script, deliberately not a package+"""What the concept entry lookup actually does with a bare code.++Originally written against `ConceptLibrary.get_required_concept_from_concept_ref_or_code` and its+`search_domain_codes` list — the reader README §4 documents as broken (the multi-domain walk died+on its first miss and escaped as the wrong exception class). Phase 3 replaced that method with the+entry affordance `get_required_entry_concept(code, search_scope=...)`; this probe now measures the+replacement over the same library shapes, so the §4 table can be re-measured after the change.++Builds a two-domain library in memory and asks for a bare concept code under each shape of+`search_scope`. No bundle files, no runtime boot — the library object is enough, because the+lookup is pure.++ .venv/bin/python wip/pipe-refs/probes/concept-lookup-matrix.py # needs the venv: this probe imports pipelex++Read the output against the entry-affordance semantics (a hand-supplied code is NOT an in-body+reference): the entry pipe's own scope wins, an unambiguous crate-wide match is served, ambiguity+refuses to guess, and a genuine miss raises the class every caller actually catches.+"""++from pipelex.core.concepts.concept import Concept+from pipelex.libraries.concept.concept_library import ConceptLibrary++STRUCTURE_CLASS_NAME = "TextContent"+++def library_declaring(*declarations: tuple[str, str]) -> ConceptLibrary:+ library = ConceptLibrary.make_empty()+ for domain_code, concept_code in declarations:+ library.add_new_concept(+ Concept(+ code=concept_code,+ domain_code=domain_code,+ description="probe concept",+ structure_class_name=STRUCTURE_CLASS_NAME,+ )+ )+ return library+++def attempt(*, label: str, library: ConceptLibrary, code: str, search_scope: str | None) -> None:+ try:+ found = library.get_required_entry_concept(code, search_scope=search_scope)+ except BaseException as exc: # noqa: BLE001 - naming *which* error escapes IS the measurement here+ print(f"{label:46} -> {type(exc).__name__}: {exc}")+ else:+ print(f"{label:46} -> resolved {found.concept_ref}")+++def main() -> None:+ both = library_declaring(("alpha", "Memo"), ("beta", "Memo"))+ only_beta = library_declaring(("beta", "Memo"))++ print("bare code 'Memo'; the entry pipe is in domain 'alpha'\n")+ attempt(label="both declare | scope=None", library=both, code="Memo", search_scope=None)+ attempt(label="only beta | scope=None", library=only_beta, code="Memo", search_scope=None)+ attempt(label="both declare | scope=alpha", library=both, code="Memo", search_scope="alpha")+ attempt(label="only beta | scope=alpha", library=only_beta, code="Memo", search_scope="alpha")+ attempt(label="only beta | scope=beta", library=only_beta, code="Memo", search_scope="beta")+ attempt(label="nowhere | scope=alpha", library=ConceptLibrary.make_empty(), code="Memo", search_scope="alpha")+++if __name__ == "__main__":+ main()diff --git a/wip/pipe-refs/probes/dep-subpipe-scope.py b/wip/pipe-refs/probes/dep-subpipe-scope.pynew file mode 100644index 000000000..00fe9a3bb--- /dev/null+++ b/wip/pipe-refs/probes/dep-subpipe-scope.py@@ -0,0 +1,193 @@+# ruff: noqa: INP001 - a standalone probe script, deliberately not a package+"""OQ1: which library does a dependency pipe's bare sub-pipe ref resolve against?++A dependency package is loaded into an isolated *child* library, and its pipes are ALSO registered+in the host library under aliased keys (`alias->domain.code`). Two readers then look up the same+authored bare sub-pipe ref, and the question this probe answers is whether they agree:++- **validation** (`Library.validate_pipe_library_with_libraries`) special-cases a dependency pipe:+ for an aliased key, a bare sub-pipe code is looked up in the CHILD library;+- **execution** (`SubPipe.run_pipe` -> `interpreter_hub.get_required_pipe`) has no such+ special-case: it asks the ambient current library — the HOST — with a strict key lookup and no+ fallback, so a bare code matches nothing there. (When this probe was first run, the host lookup+ instead ended in a crate-wide bare-code fall-through that explicitly SKIPPED `alias->` entries —+ same outcome for a dependency's bare ref, different mechanism.)++The probe builds a dependency whose exported entry is a `PipeSequence` calling a bare same-domain+helper, loads it through the real dependency loader, and asks both readers. It runs three shapes:++1. no manifest exports (every dependency pipe public), host declares nothing;+2. no manifest exports, host declares its OWN pipe under the same bare code — the case that decides+ between "fails loudly" and "silently runs the wrong pipe";+3. manifest `[exports]` naming only the entry pipe — what a published package actually ships. The+ export filter drops the authored helper from the dependency's OWN child library, so this shape+ fails differently, and earlier, than shape 1.++It also asks the host for the ref the build-time qualification pass WOULD produce+(`dep_domain.helper`), which is the OQ1 go/no-go question.++ .venv/bin/python wip/pipe-refs/probes/dep-subpipe-scope.py # needs the venv: this probe imports pipelex++No credentials and no inference backend are needed; nothing is executed, only resolved.+"""++from pathlib import Path+from tempfile import TemporaryDirectory++from mthds.package.dependency_resolver import ResolvedDependency+from mthds.package.manifest.schema import MethodsManifest++from pipelex.interpreter_hub import get_library_manager, scoped_current_library+from pipelex.libraries.library import Library+from pipelex.libraries.library_manager import LibraryManager+from pipelex.mthds_parsing.parser import MthdsParser+from pipelex.pipe_machinery.pipe_abstract import PipeAbstract+from pipelex.pipelex import Pipelex++ALIAS = "helper_dep"+DEP_DOMAIN = "probe_dep_domain"+HOST_DOMAIN = "probe_host_domain"+BARE_HELPER_CODE = "probe_helper"++# The dependency: an exported entry sequence whose only step is a BARE same-domain helper ref.+DEP_MTHDS = f"""\+domain = "{DEP_DOMAIN}"+description = "Dependency whose entry pipe calls a bare same-domain helper"++[pipe.probe_entry]+type = "PipeSequence"+description = "Entry point, calling a bare same-domain helper"+inputs = {{ doc = "Text" }}+output = "Text"+steps = [{{ pipe = "{BARE_HELPER_CODE}", result = "helped" }}]++[pipe.{BARE_HELPER_CODE}]+type = "PipeLLM"+description = "the DEPENDENCY's own helper"+inputs = {{ doc = "Text" }}+output = "Text"+prompt = "Help with $doc, the dependency way"+"""++# A host that declares its own pipe under the SAME bare code as the dependency's helper.+HOST_COLLIDING_MTHDS = f"""\+domain = "{HOST_DOMAIN}"+description = "Host declaring its own pipe under the dependency helper's bare code"++[pipe.{BARE_HELPER_CODE}]+type = "PipeLLM"+description = "the HOST's unrelated pipe, which happens to share the bare code"+inputs = {{ doc = "Text" }}+output = "Text"+prompt = "Help with $doc, the host way"+"""+++def describe(pipe: PipeAbstract | None) -> str:+ if pipe is None:+ return "None"+ return f"{pipe.pipe_ref} <- {pipe.description}"+++def build_resolved_dep(dep_dir: Path, *, exported_pipe_codes: set[str] | None) -> ResolvedDependency:+ """`exported_pipe_codes=None` means no manifest exports — every pipe public."""+ dep_file = dep_dir / "dep.mthds"+ dep_file.write_text(DEP_MTHDS, encoding="utf-8")+ manifest = MethodsManifest(+ address="github.com/org/probe-helper-dep",+ version="1.0.0",+ description="Probe dependency package",+ )+ return ResolvedDependency(+ alias=ALIAS,+ address="github.com/org/probe-helper-dep",+ manifest=manifest,+ package_root=dep_dir,+ mthds_files=[dep_file],+ exported_pipe_codes=exported_pipe_codes,+ )+++def ask(*, label: str, library: Library, pipe_code: str) -> None:+ try:+ found = library.pipe_library.get_optional_pipe(pipe_code=pipe_code)+ except BaseException as exc: # noqa: BLE001 - naming *which* error escapes IS the measurement here+ print(f" {label:<58} -> {type(exc).__name__}: {exc}")+ else:+ print(f" {label:<58} -> {describe(found)}")+++def report(*, title: str, library: Library, library_id: str) -> None:+ print(f"\n===== {title} =====")+ print(" host pipe_library keys :", sorted(library.pipe_library.root))+ child_library = library.dependency_libraries[ALIAS]+ print(" child pipe_library keys:", sorted(child_library.pipe_library.root))+ print()+ print(" LOAD-TIME VERDICT — library.validate_library()")+ try:+ with scoped_current_library(library_id=library_id):+ library.validate_library()+ except BaseException as exc: # noqa: BLE001 - naming *which* error escapes IS the measurement here+ print(f" {'':<58} -> {type(exc).__name__}: {exc}")+ else:+ print(f" {'':<58} -> valid")+ print()+ print(f" VALIDATION reader — child library ({BARE_HELPER_CODE!r}: authored spelling; qualified: what validation asks post-pass)")+ ask(label="child.get_optional_pipe(bare) [pre-qualification spelling]", library=child_library, pipe_code=BARE_HELPER_CODE)+ ask(+ label=f"child.get_optional_pipe('{DEP_DOMAIN}.{BARE_HELPER_CODE}') [after the pass]",+ library=child_library,+ pipe_code=f"{DEP_DOMAIN}.{BARE_HELPER_CODE}",+ )+ print()+ print(" EXECUTION reader — host library (what SubPipe.run_pipe asks)")+ ask(label=f"host.get_optional_pipe({BARE_HELPER_CODE!r}) [pre-qualification spelling]", library=library, pipe_code=BARE_HELPER_CODE)+ ask(+ label=f"host.get_optional_pipe('{DEP_DOMAIN}.{BARE_HELPER_CODE}') [after the pass]",+ library=library,+ pipe_code=f"{DEP_DOMAIN}.{BARE_HELPER_CODE}",+ )+++def main() -> None:+ Pipelex.make(needs_inference=False)+ manager = get_library_manager()+ assert isinstance(manager, LibraryManager)++ with TemporaryDirectory(prefix="dep-subpipe-scope-") as temp_dir:+ dep_dir = Path(temp_dir) / "dep"+ dep_dir.mkdir()+ resolved_dep = build_resolved_dep(dep_dir, exported_pipe_codes=None)++ bare_library_id, bare_library = manager.open_library()+ with scoped_current_library(library_id=bare_library_id):+ manager._load_single_dependency(library=bare_library, resolved_dep=resolved_dep) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]+ report(title="host declares nothing", library=bare_library, library_id=bare_library_id)++ host_file = Path(temp_dir) / "host.mthds"+ host_file.write_text(HOST_COLLIDING_MTHDS, encoding="utf-8")+ colliding_library_id, colliding_library = manager.open_library()+ with scoped_current_library(library_id=colliding_library_id):+ manager._load_single_dependency(library=colliding_library, resolved_dep=resolved_dep) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]+ # load_from_blueprints validates the whole library, dependency entries included — since the+ # strict lookup landed, that validation raises here. The host pipe is registered before the+ # validation runs, so the shape-2 library is intact; catch and keep measuring.+ try:+ manager.load_from_blueprints(+ library_id=colliding_library_id,+ blueprints=[MthdsParser.make_pipelex_bundle_blueprint(bundle_path=host_file)],+ )+ except BaseException as exc: # noqa: BLE001 - naming *which* error escapes IS the measurement here+ print(f"\n load_from_blueprints(host) -> {type(exc).__name__}: {exc}")+ report(title="host declares its OWN pipe under the same bare code", library=colliding_library, library_id=colliding_library_id)++ # The published shape: a manifest exporting only the entry pipe.+ exporting_dep = build_resolved_dep(dep_dir, exported_pipe_codes={"probe_entry"})+ exporting_library_id, exporting_library = manager.open_library()+ with scoped_current_library(library_id=exporting_library_id):+ manager._load_single_dependency(library=exporting_library, resolved_dep=exporting_dep) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]+ report(title="dependency manifest exports only the entry pipe", library=exporting_library, library_id=exporting_library_id)+++if __name__ == "__main__":+ main()diff --git a/wip/pipe-refs/probes/make-demos.sh b/wip/pipe-refs/probes/make-demos.shnew file mode 100755index 000000000..b797dad5c--- /dev/null+++ b/wip/pipe-refs/probes/make-demos.sh@@ -0,0 +1,180 @@+#!/usr/bin/env bash+# Materialize the five bare-reference demo closures used by ../README.md.+#+# Writes OUTSIDE the repository by default (a fresh mktemp dir), on purpose: these bundles are+# deliberately pathological, and dropping them into the tree would move the corpus counts that+# classify-bare-refs.py reports over `.`.+#+# Usage: ./wip/pipe-refs/probes/make-demos.sh [target_dir]+# Prints the target directory on stdout as its last line.++set -euo pipefail++# POSIX-portable form. `mktemp -d -t bare-ref-demos` works on BSD/macOS but GNU coreutils reads the+# argument as a template needing X's and aborts — which, under `set -e`, kills the script before it+# writes a single demo.+TARGET="${1:-$(mktemp -d "${TMPDIR:-/tmp}/bare-ref-demos.XXXXXX")}"+mkdir -p "$TARGET"++# --- 1. ambiguous: two domains declare `summarize`; alpha calls it bare -----------------------+# Standard: resolves to alpha.summarize (found in the own domain, the search stops).+# Runtime: PipeLibraryError, ambiguous.+mkdir -p "$TARGET/ambiguous"+cat >"$TARGET/ambiguous/alpha.mthds" <<'EOF'+domain = "alpha"+description = "Alpha domain"++[concept]+Note = "A short note"++[pipe.run_flow]+type = "PipeSequence"+description = "Alpha's entry point, calling a bare 'summarize' that alpha itself declares"+inputs = { note = "Note" }+output = "Note"+steps = [{ pipe = "summarize", result = "summary" }]++[pipe.summarize]+type = "PipeLLM"+description = "Alpha's own summarize"+inputs = { note = "Note" }+output = "Note"+prompt = "Summarize $note the alpha way"+EOF+cat >"$TARGET/ambiguous/beta.mthds" <<'EOF'+domain = "beta"+description = "Beta domain, which happens to reuse the pipe code 'summarize'"++[concept]+Memo = "A short memo"++[pipe.summarize]+type = "PipeLLM"+description = "Beta's own summarize"+inputs = { memo = "Memo" }+output = "Memo"+prompt = "Summarize $memo the beta way"+EOF++# --- 2. fallthrough: only beta declares `present`; alpha calls it bare ------------------------+# Standard: error, no fall-through. Runtime: resolves to beta.present.+mkdir -p "$TARGET/fallthrough"+cat >"$TARGET/fallthrough/alpha.mthds" <<'EOF'+domain = "alpha"+description = "Alpha domain"++[concept]+Note = "A short note"++[pipe.run_flow]+type = "PipeSequence"+description = "Alpha's entry point, calling a bare 'present' it does not declare"+inputs = { note = "Note" }+output = "Note"+steps = [{ pipe = "present", result = "presented" }]+EOF+cat >"$TARGET/fallthrough/beta.mthds" <<'EOF'+domain = "beta"+description = "Beta domain, the only declarer of 'present'"++[pipe.present]+type = "PipeLLM"+description = "Beta's present"+inputs = { note = "alpha.Note" }+output = "alpha.Note"+prompt = "Present $note"+EOF++# --- 3 & 4. export bypass, and its control ----------------------------------------------------+# One package. `beta.helper` is NOT exported. The bare form reaches it; the qualified form is+# rejected. Same pipe, same manifest, same run.+for variant in export-bypass export-bypass-control; do+ mkdir -p "$TARGET/$variant/alpha" "$TARGET/$variant/beta"+ cat >"$TARGET/$variant/METHODS.toml" <<'EOF'+[package]+address = "github.com/example/bypass-demo"+display_name = "Bypass Demo"+version = "1.0.0"+description = "Two domains; beta exports nothing"+authors = ["Example"]+license = "MIT"+mthds_version = "1.0.0"++[exports.alpha]+pipes = ["run_flow"]+EOF+ cat >"$TARGET/$variant/beta/beta.mthds" <<'EOF'+domain = "beta"+description = "Beta domain; 'helper' is NOT listed in [exports]"++[pipe.helper]+type = "PipeLLM"+description = "Beta's private helper"+inputs = { note = "alpha.Note" }+output = "alpha.Note"+prompt = "Help with $note"+EOF+done+cat >"$TARGET/export-bypass/alpha/alpha.mthds" <<'EOF'+domain = "alpha"+description = "Alpha domain"++[concept]+Note = "A short note"++[pipe.run_flow]+type = "PipeSequence"+description = "Reaches beta's non-exported 'helper' by bare code"+inputs = { note = "Note" }+output = "Note"+steps = [{ pipe = "helper", result = "helped" }]+EOF+cat >"$TARGET/export-bypass-control/alpha/alpha.mthds" <<'EOF'+domain = "alpha"+description = "Alpha domain"++[concept]+Note = "A short note"++[pipe.run_flow]+type = "PipeSequence"+description = "Names the same non-exported pipe, qualified"+inputs = { note = "Note" }+output = "Note"+steps = [{ pipe = "beta.helper", result = "helped" }]+EOF++# --- 5. concept-collision: two domains declare `Note`; each references it bare -----------------+# The crate normalizer qualifies each to its own domain; the live ConceptLibrary's bare search+# (search_domain_codes=None) raises "Multiple concepts found" for the same authored text.+mkdir -p "$TARGET/concept-collision"+cat >"$TARGET/concept-collision/alpha.mthds" <<'EOF'+domain = "alpha"+description = "Alpha domain"++[concept]+Note = "Alpha's note"++[pipe.alpha_summarize]+type = "PipeLLM"+description = "Uses a bare 'Note'"+inputs = { note = "Note" }+output = "Note"+prompt = "Summarize $note"+EOF+cat >"$TARGET/concept-collision/beta.mthds" <<'EOF'+domain = "beta"+description = "Beta domain, which also declares 'Note'"++[concept]+Note = "Beta's note"++[pipe.beta_summarize]+type = "PipeLLM"+description = "Uses a bare 'Note'"+inputs = { note = "Note" }+output = "Note"+prompt = "Summarize $note"+EOF++echo "$TARGET"diff --git a/wip/pr-1099-review-notes.md b/wip/pr-1099-review-notes.mdnew file mode 100644index 000000000..a24cf5d9b--- /dev/null+++ b/wip/pr-1099-review-notes.md@@ -0,0 +1,44 @@+# PR #1099 review — deferred items++Deferred findings from the SWE-agent review triage of PR #1099 (Pipe-refs). Each was verified as real; they are deferred as judgment calls, not dismissed.++## Hardcoded domain literals in test blueprints (all-or-none sweep)++**Reporter:** cubic-dev-ai (three threads). **Verified:** confirmed, cosmetic.++Three PR-touched test files qualify `SubPipeBlueprint(pipe=...)` refs with a hardcoded domain literal even though the module defines a domain constant used elsewhere in the same file:++- `tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_absence.py` — `"test_optionals_par.opt_par_find"` / `.opt_par_base` vs `_DOMAIN_CODE`+- `tests/integration/pipelex/pipes/optionals/test_liftable_pipes_inventory.py` — two hunks (sequence steps and parallel branches) vs `_DOMAIN_CODE`+- `tests/integration/pipelex/pipes/controller/pipe_parallel/test_pipe_parallel_unresolvable_structure_class.py` — `"test_usc.usc_branch"` vs `DOMAIN_CODE`++**Why deferred:** a verification sweep found the same pattern in six more PR-touched files that define a domain constant — `test_lift_sequence.py`, `test_lifted_parallel_companion_slots.py`, `test_optional_gate_tolerates_missing.py`, `test_parallel_optional_combine_validation.py`, `test_redundant_force_warning.py`, and `test_taint_sequence_validation.py` (the last with ~20 refs). Fixing only the three flagged files would make the tree *less* consistent than it is now; fixing all of them is a purely cosmetic sweep of dozens of edits on an already-large PR. All-or-none, in a dedicated cleanup — not piecemeal in review follow-ups.++**Recommendation:** if the sweep is done, interpolate the module constant everywhere (`f"{_DOMAIN_CODE}.xxx"`), matching the pattern in `test_pipe_parallel_branch_type_validation.py`. Note `test_pipe_structure_in_sequence.py` also hardcodes a domain prefix but defines no constant — it is not part of this pattern.++## Ambiguity as a first-class CLI outcome (design decision, round 2)++**Reporter:** cubic-dev-ai (two threads, both judged false positives on their stated claim). **Verified:** no authored contract is violated today.++The bot demanded exit 2 for ambiguous bare codes in `pipelex which`/`show`; that requirement exists only in cubic's auto-generated PR-summary block. The authored contract (changelog, `docs/building-methods/libraries.md`) promises a clean error naming the candidates, which holds and is test-pinned. But the triage surfaced a real open design question: `which` and `show` collapse *not found* and *ambiguous* into exit 1, so a script cannot tell the two apart; and there is no ambiguity-specific exception class for pipes — callers distinguish "a `PipeLibraryError` that is not a `PipeNotFoundError`", relying on subclass ordering (see `_validate_core.py`'s two arms). The workspace rule prefers structured verdicts over message-matching.++**If ever decided yes:** add `PipeCodeAmbiguousError(PipeLibraryError)` in `pipelex/libraries/pipe/exceptions.py` (mirroring `AmbiguousInputsFilesError`), raise it at both ambiguity sites in `pipe_library.py`, regenerate the error-identity snapshot and error pages (`make gei` / `make gep`), give `which`/`show` a dedicated exit-2 arm, and state the exit code in the changelog and docs (today neither does). It is a product decision about CLI contract, not a bug — exit 0/1/2 semantics are currently scoped to verdict-producing commands (`validate`/`fix`/`resolve`).++## Pre-ship review round (Claude + Codex adversarial, 2026-08-13) — deferred with reasons++Each verified against the code; deferred as design/architecture calls, not dismissed.++- **Host/dep concept-collision split brain (Codex P0, verified mechanically real).** When a dependency declares the same unaliased `domain.Concept` as the host, dep construction skips the temp registration (`library_manager.py` `is_concept_exists` guard), so the dep pipe's I/O binds the HOST concept — while the post-C3 entry lookup, under an aliased scope, binds the DEP concept for the same spelling. `Concept.is_compatible` short-circuits on equal `concept_ref` strings before comparing structure classes, so input shaping can instantiate the dep structure class against a pipe validated with the host's. Requires a dependency that redeclares a host domain name — the same collision shape in which dependency *pipes* already misbehave (see `wip/pipe-refs/dependency-subpipe-scope-deferred.md`). **Ruled 2026-08-13 (pre-ship review): defer to the packaging project** — the C3 scope-wins precedence stands; the collision shape belongs to the packaging design alongside the deferred dependency-execution defects. Not a merge blocker for PR #1099. Related: the same precedence means an explicitly-typed host `domain.Concept` input is shadowable by a dependency reusing that domain name, with no syntax that forces host resolution under an aliased scope.+- **`dynamic_output_concept_ref` bypasses the entry-concept semantics (parity gap, not a regression).** `pipe_llm.py` owner-qualifies a bare dynamic-output ref and calls the strict `get_required_concept`; `search_scope` is not threaded into `PipeRunParams`. Untouched by this branch — but a bare sibling-domain concept that now works in an input envelope still fails as a dynamic output, and a dependency entry pipe's bare dynamic output resolves without its alias. Align when the dynamic-output params-key TODO in `pipe_llm.py` is paid.+- **Library load is non-transactional (pre-existing, more visible now).** `load_from_blueprints` records the batch and `load_from_crate` mutates domains/concepts/source maps before strict dependency validation runs; a strict-ref failure leaves the mutations in place (only the fingerprint is withheld). Fresh CLI flows tear down; long-lived managers retry into duplicate-declaration errors. The strict rule makes first-load failures more common (that is the migration path), so the cleanup story may deserve a look in the packaging/loading project.+- **`add_new_pipe` does not enforce the qualification invariant.** The strict lookup assumes every controller's sub-refs were qualified by the crate pass, but a programmatic caller can `PipeFactory.make_from_blueprint` + `add_new_pipe` a controller with bare refs — it loads fine and fails only at validation/execution. In-repo paths all go through the pass; a boundary assert (or a docstring warning) on `add_new_pipe` would make the invariant explicit for plugin authors.+- **Spec-less input shaping has no compat check on the crate-wide arm.** `WorkingMemoryFactory.make_from_pipeline_inputs` without `input_specs` (the transport-bridge path) resolves a bare envelope concept via the crate-wide unique match with no `is_compatible` check afterward — a caller's `{"concept": "Invoice"}` that used to error (entry domain lacked it) can now bind a unique `other_domain.Invoice`. Deliberate widening per the changelog; recording the spec-less-path nuance for the 4b bridge migration.+- **Perf, both linear and bounded (performance specialist):** (1) `qualify_crate(crate).pipes` on the two library-load paths qualifies all concepts then discards them — a pipes-only entry point would halve the pass on loads; (2) `get_optional_entry_concept`'s crate-wide scan re-runs per list-input item on the same bare code — a per-run memo or index would make repeats dict hits. Both smallest-correct-surface calls, neither quadratic.+- **`pipe_code`-named holders of qualified refs (maintainability).** `SubPipe.pipe_code`, `PipeBatch.branch_pipe_code`, and `run_pipe_func`'s `pipe_code` parameter now carry `domain.code` refs while named `code` — the exact trap the batch-suffix bug fell into. A rename sweep (`pipe_ref`) is breaking-but-allowed; do it as its own change, not piecemeal.++## Observations recorded in passing (no action decided)++- `pipelex/libraries/crate_qualification.py` — the module contract ("a merged, key-qualified crate") does not say whether aliased keys (`alias->dom.code`) are in scope. `_domain_of` would parse one to `domain_path="alias->dom"` and a bare in-body ref would be rewritten to `alias->dom.foo`; `parse_pipe_ref` downstream rejects that loudly, and merged crates carry no aliased keys today. A guard (or one docstring line placing aliased keys out of scope) would close the ambiguity.++- `pipelex/libraries/crate_qualification.py` — the cross-package **io**-ref deferral branch in `_qualify_io_ref` (`QualifiedRef.has_cross_package_prefix(io_ref) → return io_ref`) looks unreachable: `PipeBlueprint.generic_validate_inputs`/`generic_validate_output` reject any io ref that does not match `MULTIPLICITY_PATTERN`, and `alias->dom.Concept` cannot match it. Either cross-package concept refs in pipe io are intentionally illegal (making the branch and the module-docstring line about it dead) or the blueprint validator has a gap. Worth a one-line clarification when someone is next in that file.+- `pipelex/pipe_machinery/pipe_abstract.py` — `PipeAbstract.domain_code` is the one identity field with no validator (`code` has one). A `field_validator` calling `validate_domain_code` would make the `f"{domain_code}.{code}"` pipe-library key invariant structural instead of assumed, and would make the diagnostics-path `QualifiedRef.parse` calls in `pipelex/libraries/library.py` provably safe. Deliberately not done in review follow-ups — it widens the change surface for a state the loader already makes unreachable.