Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
fix/Package-reference-verdict · L-260904-df514c (#1354)
Louis Choquel10988a7ea0a3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 746b536e8..a43d751c1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,7 @@### Changed- **The documentation no longer describes the Pipelex Gateway**: **Configure AI Providers** offers your own provider keys or a local model, says that the shipped defaults run as they are on OpenAI or Azure OpenAI and must be repointed for any other provider, OpenRouter included, and points to the Quick Start for running on the hosted API; the MTHDS language tutorial no longer runs `pipelex login`. The telemetry, logging, feature and under-the-hood pages describe only the telemetry streams you configure yourself and the backends the runtime ships, without the Gateway stream, its backend or its plugin.+- **A call into a method package that cannot be resolved is a verdict item (Breaking)**: when a bundle names a pipe of another package by its address and the package is not installed and cannot be fetched (fetch-on-miss off, an address this runtime cannot fetch, a failed fetch), the load is refused with one item of the new `PipeValidationErrorType` value `unresolved_package_dependency` per package, on the first pipe naming it, with the reference as written in `missing_pipe_code`, where it raised `MethodFetchDisabledError` or `MethodDependencyFetchError` and the API answered a no-verdict `500`. `POST /v1/validate` now answers `200` with `is_valid: false` and the run routes a `422`, every package of the bundle is tried before the refusal, a failed clone's message no longer names the runner's temporary clone directory, and the remedies name no directory on the host. The MTHDS Test Corpus covers it as `invalid_unresolved_package_dependency`.## [v0.75.0] - 2026-10-06diff --git a/api/tests/unit/_constants.py b/api/tests/unit/_constants.pyindex 1afb94668..929656c62 100644--- a/api/tests/unit/_constants.py+++ b/api/tests/unit/_constants.py@@ -291,6 +291,22 @@ model = "no-such-model-in-any-deck"prompt = "@text""""+# A bundle whose sequence calls a pipe of an invented method package by its address. With fetch-on-miss+# off and an empty installed store, the load refuses it as an `unresolved_package_dependency` item+# located on `pipe.echo.steps[0].pipe`. A run or a validation of it used to answer a no-verdict 500.+UNRESOLVED_PACKAGE_REFERENCE = "github.com/invented/probe-lib/probe->probe_dep.entry"+UNRESOLVED_PACKAGE_MTHDS = f"""\+domain = "smoke"+main_pipe = "echo"++[pipe.echo]+type = "PipeSequence"+description = "Call an invented package"+inputs = {{ text = "Text" }}+output = "Text"+steps = [{{ pipe = "{UNRESOLVED_PACKAGE_REFERENCE}", result = "out" }}]+"""+# A bundle that loads but whose run fails one step down, in a live run and a dry run alike since no# pipe calls a model: `review_topic` runs the parallel `analyze_topic`, whose branch `draft_idea` gives# one `Idea` for the field `ideas`, which `TopicReview` declares as a list. The combine of the branchdiff --git a/api/tests/unit/test_unresolved_package_reference.py b/api/tests/unit/test_unresolved_package_reference.pynew file mode 100644index 000000000..39c5d2f0d--- /dev/null+++ b/api/tests/unit/test_unresolved_package_reference.py@@ -0,0 +1,106 @@+"""What the server answers when a bundle calls a method package that cannot be resolved.++The reference is a property of the caller's content, so the answer is the verdict: `/v1/validate` answers `200` with+`is_valid: false`, and the run routes refuse the run with a `422` before anything is dispatched, both carrying one+`unresolved_package_dependency` item that names the reference as written. Fetch-on-miss is off and the installed+store is an empty temporary directory, so the refusal is deterministic and nothing reaches the network.+"""++from pathlib import Path+from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from pipelex.base_exceptions import DisclosureMode, ValidationErrorCategory+from pipelex.pipe_run.delivery_assignment import DeliveryAssignment+from pipelex.pipe_run.pipe_job import PipeJob+from pipelex.plugins.orchestrator_registry import OrchestratorRegistry+from pipelex.runtime_bridge.payloads import PipelexPipeDispatchAck, PipelexPipeRunOutput+from pytest_mock import MockerFixture++from pipelex_api.api_config import ApiConfig+from pipelex_api.exception_handlers import register_exception_handlers+from pipelex_api.routes import router as api_router+from tests.unit._constants import UNRESOLVED_PACKAGE_MTHDS, UNRESOLVED_PACKAGE_REFERENCE++_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"+++class _RecordingOrchestrator:+ """An async-capable orchestrator that records every dispatch; a refused bundle must reach neither arm."""++ supports_fire_and_forget = True++ def __init__(self) -> None:+ self.dispatches: list[str] = []++ async def execute(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeRunOutput: # noqa: ARG002+ self.dispatches.append(pipe_job.pipe.code)+ msg = "A refused bundle must not be dispatched."+ raise AssertionError(msg)++ async def start(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeDispatchAck: # noqa: ARG002+ self.dispatches.append(pipe_job.pipe.code)+ msg = "A refused bundle must not be dispatched."+ raise AssertionError(msg)+++def _build_client(+ mocker: MockerFixture, *, tmp_path: Path, disclosure_mode: DisclosureMode, orchestrator: _RecordingOrchestrator | None = None+) -> TestClient:+ mocker.patch("pipelex.cli.installed_methods.GLOBAL_METHODS_DIR", tmp_path / "global-methods")+ mocker.patch("pipelex.cli.installed_methods.PROJECT_METHODS_DIR", tmp_path / "project-methods")+ mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=False)+ mocker.patch(+ f"{_PIPELINE_NS}.get_api_config", return_value=ApiConfig(orchestration_mode="direct", allow_request_orchestration_mode_override=False)+ )+ if orchestrator is not None:+ mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({"direct": orchestrator}))+ app = FastAPI()+ app.include_router(api_router, prefix="/v1")+ register_exception_handlers(app, disclosure_mode=disclosure_mode)+ return TestClient(app)+++def _assert_the_package_item(items: list[dict[str, Any]]) -> None:+ assert len(items) == 1, items+ item = items[0]+ assert item["category"] == ValidationErrorCategory.PIPE_VALIDATION+ assert item["error_type"] == "unresolved_package_dependency"+ assert item["pipe_code"] == "echo"+ assert item["domain_code"] == "smoke"+ assert item["missing_pipe_code"] == UNRESOLVED_PACKAGE_REFERENCE+ assert item["field_path"] == "pipe.echo.steps[0].pipe"+ assert "github.com/invented/probe-lib/probe" in item["message"]+++class TestUnresolvedPackageReference:+ @pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])+ def test_validate_answers_the_invalid_verdict(self, mocker: MockerFixture, tmp_path: Path, disclosure_mode: DisclosureMode):+ client = _build_client(mocker, tmp_path=tmp_path, disclosure_mode=disclosure_mode)++ response = client.post("/v1/validate", json={"mthds_contents": [UNRESOLVED_PACKAGE_MTHDS]})++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["is_valid"] is False+ _assert_the_package_item(body["validation_errors"])++ @pytest.mark.parametrize("disclosure_mode", [DisclosureMode.VERBOSE, DisclosureMode.STRICT])+ @pytest.mark.parametrize("path", ["/v1/execute", "/v1/start"])+ def test_a_run_is_refused_with_the_verdict(self, mocker: MockerFixture, tmp_path: Path, disclosure_mode: DisclosureMode, path: str):+ orchestrator = _RecordingOrchestrator()+ client = _build_client(mocker, tmp_path=tmp_path, disclosure_mode=disclosure_mode, orchestrator=orchestrator)++ response = client.post(path, json={"pipe_code": "echo", "mthds_contents": [UNRESOLVED_PACKAGE_MTHDS], "inputs": {"text": "hello"}})++ assert response.status_code == 422, response.text+ assert response.headers["content-type"].startswith("application/problem+json")+ body = response.json()+ assert body["error_type"] == "ValidateBundleError"+ assert body["error_domain"] == "input"+ _assert_the_package_item(body["validation_errors"])+ # The caller's own content: STRICT keeps the human summary, which is the item's message.+ assert body["detail"] == body["validation_errors"][0]["message"]+ assert orchestrator.dispatches == []diff --git a/docs/api-server/error-responses.md b/docs/api-server/error-responses.mdindex 60da41009..a30d0b407 100644--- a/docs/api-server/error-responses.md+++ b/docs/api-server/error-responses.md@@ -49,7 +49,7 @@ When a bundle fails validation, the `ValidateBundleError` carries a `validation_| `source` | The owning file of the error, when the runtime could attribute it to one: on `blueprint_validation` and `pipe_validation` items, and on a `dry_run` item, where it is the file of the pipe whose dry run failed. On the in-memory submit path it is the matching `mthds_sources[i]` (see [Sourcing submitted files](pipe-validate.md)), so it is absent when the caller sent no sources. Absent on `pipe_factory` items and on the parse-level residual described below. Beside a server's own library directories, an item never names one of their files. || `pipe_code`, `concept_code`, `domain_code` | The pipe / concept / domain the error is about, when applicable. On a `dry_run` item they name the innermost pipe that failed, not the controller the failure passed through. || `field_path`, `field_name` | The offending field within the bundle, when the error localizes to one. |-| `variable_names`, `missing_concept_code`, `missing_pipe_code`, `declared_concepts` | Extra context for specific failure shapes (undefined variables, an unresolved concept or pipe reference, the set of concepts that were declared). |+| `variable_names`, `missing_concept_code`, `missing_pipe_code`, `declared_concepts` | Extra context for specific failure shapes (undefined variables, an unresolved concept, pipe or package reference, the set of concepts that were declared). On an `unresolved_package_dependency` item, `missing_pipe_code` is the reference as written, `<address>->domain.code`, so the package's address is the part before `->`. || `line`, `column` | The 1-based position where the TOML parser stopped, on a TOML syntax error. || `model_reference`, `model_type`, `suggestions` | On an `unknown_model` item — a pipe naming a model the deployment's model deck does not define — the reference as the bundle wrote it, the kind of model the pipe needs (`llm`, `extract`, …), and the deck's close matches of that kind. With exactly one suggestion the item also carries an `unsafe` `suggested_fix` renaming the model. || `suggested_fix` | A structured, deterministic fix for this error — present only when the fix planner derived one. See [Suggested fixes](#suggested-fixes). |diff --git a/docs/api-server/openapi/pipelex-api.openapi.yaml b/docs/api-server/openapi/pipelex-api.openapi.yamlindex c49a877cc..46284b321 100644--- a/docs/api-server/openapi/pipelex-api.openapi.yaml+++ b/docs/api-server/openapi/pipelex-api.openapi.yaml@@ -5554,6 +5554,7 @@ components:- native_concept_redeclaration- unresolved_concept- unresolved_pipe_dependency+ - unresolved_package_dependency- unexported_pipe_dependency- unknown_model- unknown_validation_errordiff --git a/docs/api-server/pipe-validate.md b/docs/api-server/pipe-validate.mdindex 3bc76f962..354c0a145 100644--- a/docs/api-server/pipe-validate.md+++ b/docs/api-server/pipe-validate.md@@ -104,7 +104,7 @@ The 200 body is one of two arms, discriminated on the mandatory `is_valid` field**Response Fields (invalid arm):**- `is_valid` (`false`): the discriminant of the invalid arm-- `validation_errors` (list): the structured per-error diagnostics a client maps to per-line problems — built by pipelex's one shared builder, so they are byte-for-byte the same items the agent CLI emits. Each item carries a `category` (the closed set `blueprint_validation` | `pipe_factory` | `pipe_validation` | `dry_run`), a `message`, and the locators the runtime can attribute (`error_type`, `pipe_code` / `concept_code` / `domain_code`, `field_path` / `field_name`, and `source`). Absent locators are omitted, not null. An item may also carry a **`suggested_fix`** — a structured, deterministic repair (`fix_code`, `description`, `safety: safe|unsafe`, and the `ops[]` of semantic TOML patch operations to apply). It is present only when the fix planner derived one from the typed error data; a client that ignores it behaves exactly as before. See [Error Responses → Structured validation errors](error-responses.md#structured-validation-errors) and [→ Suggested fixes](error-responses.md#suggested-fixes) for every field. The array is **never empty on an invalid verdict** (the structured-info invariant is total): a failing dry run becomes one `dry_run` item per failing pipe, located at the innermost pipe that failed (its `pipe_code`, `domain_code` and, when known, `source`), a TOML syntax error carries the `line` and `column` the parser stopped at, and a parse-level failure with no attributable locator (an empty blueprint, an elaborator failure) becomes one `blueprint_validation` residual item carrying the message (no `source`). Every refusal of the bundle while it loads is an item of the verdict, an unknown model included (an `unknown_model` item on the pipe's `model` field), never a no-verdict `5xx`+- `validation_errors` (list): the structured per-error diagnostics a client maps to per-line problems — built by pipelex's one shared builder, so they are byte-for-byte the same items the agent CLI emits. Each item carries a `category` (the closed set `blueprint_validation` | `pipe_factory` | `pipe_validation` | `dry_run`), a `message`, and the locators the runtime can attribute (`error_type`, `pipe_code` / `concept_code` / `domain_code`, `field_path` / `field_name`, and `source`). Absent locators are omitted, not null. An item may also carry a **`suggested_fix`** — a structured, deterministic repair (`fix_code`, `description`, `safety: safe|unsafe`, and the `ops[]` of semantic TOML patch operations to apply). It is present only when the fix planner derived one from the typed error data; a client that ignores it behaves exactly as before. See [Error Responses → Structured validation errors](error-responses.md#structured-validation-errors) and [→ Suggested fixes](error-responses.md#suggested-fixes) for every field. The array is **never empty on an invalid verdict** (the structured-info invariant is total): a failing dry run becomes one `dry_run` item per failing pipe, located at the innermost pipe that failed (its `pipe_code`, `domain_code` and, when known, `source`), a TOML syntax error carries the `line` and `column` the parser stopped at, and a parse-level failure with no attributable locator (an empty blueprint, an elaborator failure) becomes one `blueprint_validation` residual item carrying the message (no `source`). Every refusal of the bundle while it loads is an item of the verdict, never a no-verdict `5xx`: an unknown model is an `unknown_model` item on the pipe's `model` field, and a call into a method package this runtime cannot resolve (not installed and not fetchable, or a fetch that failed) is an `unresolved_package_dependency` item on the first pipe naming the package, whose `missing_pipe_code` is the reference as written, `<address>->domain.code`- `pending_signatures` (list[str]): best-effort outstanding signatures (empty on the invalid arm, since no library was assembled)- `is_runnable` (`false`): an invalid bundle is never runnable- `message` (string): the human-readable verdict summary: the lone item's message when there is one item, `N validation errors (first: <the first item's message>)` when there are several, and the parser's own message for a parse-level failurediff --git a/docs/building-methods/packages.md b/docs/building-methods/packages.mdindex c48ed1adb..d5d78d892 100644--- a/docs/building-methods/packages.md+++ b/docs/building-methods/packages.md@@ -135,7 +135,7 @@ An address-based reference resolves against the **installed methods** — `~/.mtA few behaviors worth knowing:- **Installed wins.** Once a method is installed, it is used as-is — including when a reference pins a different `@<tag>` than what is installed (a warning tells you so). Remove the installed directory to re-fetch.-- **A miss that cannot be bridged is a loud diagnostic, never a silent pass**: fetch disabled, an unfetchable address, or a failed fetch each raise an error naming the address and the remedy.+- **A miss that cannot be bridged refuses the bundle, never a silent pass.** Fetch disabled, an address this runtime cannot fetch, or a failed fetch (a repository that does not exist, a `@tag` that is not a tag, a repository holding no package at that address) refuses the load with one `unresolved_package_dependency` item per package, located on the first pipe that calls it, with the reference as written in `missing_pipe_code` and the reason and the remedy in its message. It is the same invalid verdict as any other mistake in the bundle: `pipelex validate` reports it, `POST /v1/validate` answers `200` with `is_valid: false`, and a run is refused with a `422` before any pipe runs. Every package of the bundle is tried before the refusal, so two bad references give two items.- **Hosted parity warning.** A fetched method declaring Python structure classes runs locally but triggers the same warning as a direct CLI fetch: hosted execution accepts MTHDS concepts and sandboxed PipeFuncs, not in-process Python. On a sandbox-hosted deployment the fetch refuses such a package outright, with the same rule-naming error. The refusal is not specific to fetching: a sandbox-hosted deployment refuses every method whose Python declares structure classes, however it arrived (see [Python classes](concepts/python-classes.md)).To **disable network fetches at load time**, set the switch in your `pipelex.toml` (or use the environment variable, which takes precedence):@@ -149,7 +149,7 @@ fetch_on_miss = falseexport PIPELEX_METHODS_FETCH_ON_MISS=0```-With fetching disabled, a miss raises a diagnostic that names the address and how to install the method manually (e.g. `mthds install <address>`, or by copying the package into `~/.mthds/methods/`). See [Methods Configuration](../configuration/config-practical/methods-config.md).+With fetching disabled, a miss refuses the bundle with that item, whose message names the address and says to install the package where the runtime runs (for example with `mthds install <address>`). See [Methods Configuration](../configuration/config-practical/methods-config.md).### Example Layoutdiff --git a/docs/configuration/config-practical/methods-config.md b/docs/configuration/config-practical/methods-config.mdindex 26e63c51b..69f459c64 100644--- a/docs/configuration/config-practical/methods-config.md+++ b/docs/configuration/config-practical/methods-config.md@@ -15,7 +15,7 @@ class MethodsConfig(ConfigModel):### Fields-- `fetch_on_miss`: When a bundle references another method by address (`github.com/...->domain.pipe`) and no installed method matches, fetch the package by address and install it into `~/.mthds/methods/` so the load can proceed. When disabled, such a miss raises a diagnostic naming the address and how to install the method manually, and the network is never touched at load time.+- `fetch_on_miss`: When a bundle references another method by address (`github.com/...->domain.pipe`) and no installed method matches, fetch the package by address and install it into `~/.mthds/methods/` so the load can proceed. When disabled, such a miss refuses the bundle with an `unresolved_package_dependency` item naming the address and how to install the package, and the network is never touched at load time.## Example Configurationdiff --git a/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.py b/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.pyindex 14c3ce0bc..38bb4b017 100644--- a/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.py+++ b/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.py@@ -167,7 +167,7 @@ _ERROR_TYPE_EXCLUSIONS: dict[ValidationErrorType, str] = {"It refuses a reference to a pipe an installed dependency package loads but does not export, so the ""bundle that produces it needs that package installed beside it, with a manifest declaring `[exports]`. ""A focused entry is one self-contained bundle validated where nothing is installed, and an "- "address-based reference to a package that is not installed fails as a missing method instead. "+ "address-based reference to a package that is not installed fails as `unresolved_package_dependency` instead. ""Revisit if an entry can ever carry the packages it depends on."),HintLintErrorType.HINT_UNKNOWN_KEY: _ADVISORY_HINT_LINT_EXCLUSION,diff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.pyindex b2337926b..6e3dbd601 100644--- a/pipelex/libraries/library_manager.py+++ b/pipelex/libraries/library_manager.py@@ -15,7 +15,7 @@ from pydantic import BaseModel, PydanticUserError, ValidationErrorfrom typing_extensions import overridefrom pipelex import log-from pipelex.base_exceptions import PipelexError, SecurityError, error_domain_is_input+from pipelex.base_exceptions import PipelexError, SecurityError, error_domain_is_input, iter_cause_chainfrom pipelex.cogt.exceptions import ModelChoiceNotFoundErrorfrom pipelex.config import is_pipe_func_sandbox_hostedfrom pipelex.core.concepts.concept_blueprint import ConceptBlueprint@@ -24,6 +24,7 @@ from pipelex.core.concepts.helpers import make_qualified_structure_class_namefrom pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.domains.domain_blueprint import DomainBlueprintfrom pipelex.core.domains.domain_factory import DomainFactory+from pipelex.core.exceptions import PipesAndConceptValidationErrorDatafrom pipelex.core.pipes.exceptions import PipeLoadRefusalError, PipeOperatorModelChoiceErrorfrom pipelex.core.qualified_ref import QualifiedReffrom pipelex.core.stuffs.structured_content import StructuredContent@@ -47,18 +48,26 @@ from pipelex.libraries.library_utils import ()from pipelex.libraries.pipe.exceptions import PipeLibraryErrorfrom pipelex.libraries.visibility_utils import check_visibility_for_blueprints, make_visibility_checker+from pipelex.methods.exceptions import MethodDependencyFetchError, MethodFetchDisabledErrorfrom pipelex.methods.fetch_on_miss import resolve_address_based_methodfrom pipelex.methods.structures_check import ensure_no_structured_content_in_library_sources, is_generated_structures_modulefrom pipelex.mthds_parsing.exceptions import MthdsParserErrorfrom pipelex.mthds_parsing.handle_pipe_errors import categorize_pipe_validation_errorfrom pipelex.mthds_parsing.parser import MthdsParser-from pipelex.mthds_parsing.pipelex_bundle_blueprint import ElaborationMetadata, PipeBlueprintUnion, PipelexBundleBlueprint, StepRole+from pipelex.mthds_parsing.pipelex_bundle_blueprint import (+ ElaborationMetadata,+ LocatedPipeReference,+ PipeBlueprintUnion,+ PipelexBundleBlueprint,+ StepRole,+)from pipelex.pipe_machinery.pipe_abstract import PipeAbstractfrom pipelex.pipe_machinery.pipe_factory import PipeFactoryfrom pipelex.runtime_hub import get_class_registryfrom pipelex.system.registries.class_registry_utils import ClassRegistryUtilsfrom pipelex.system.registries.func_registry_utils import FuncRegistryUtilsfrom pipelex.tools.misc.semver import SemVerError, parse_constraint, parse_version, version_satisfies+from pipelex.validation_error_types import PipeValidationErrorTypeif TYPE_CHECKING:from collections.abc import Iterable, Mapping@@ -1408,8 +1417,12 @@ class LibraryManager(LibraryManagerAbstract):alias contains '/' (i.e. a full package address), and loads eachunique address-based dependency. A dependency missing from theinstalled methods is fetched by address (honoring an ``@<tag>`` pin)- and installed when fetch-on-miss is enabled; an unresolvable- dependency raises a diagnostic rather than passing silently.+ and installed when fetch-on-miss is enabled.++ A package that cannot be resolved is the caller's to fix, since the reference is part of their bundle: every+ address is tried, then the load is refused with one ``unresolved_package_dependency`` item per address that+ failed, located on the first pipe naming it. A failure of the host's own store (``MethodInstallError``) and the+ refusal of a package's Python structures (``MethodStructuresRefusedError``) propagate as they are.Also searches for .mthds/methods/ directories relative to the bundlesource path, walking up ancestor directories to find installed methods@@ -1418,36 +1431,62 @@ class LibraryManager(LibraryManagerAbstract):Args:library_id: The library to load intoblueprints: The parsed bundle blueprints to scan++ Raises:+ LibraryLoadingError: One or more referenced packages could not be resolved."""library = self.get_library(library_id=library_id)- # Collect unique address-based aliases from all pipe references- address_aliases: set[str] = set()+ # Each address-based alias, with the first reference naming it and the bundle that makes it, in bundle order.+ first_references: dict[str, tuple[LocatedPipeReference, PipelexBundleBlueprint]] = {}for blueprint in blueprints:- for pipe_ref_str, _context in blueprint.collect_pipe_references():- if QualifiedRef.has_cross_package_prefix(pipe_ref_str):- alias, _remainder = QualifiedRef.split_cross_package_ref(pipe_ref_str)- if QualifiedRef.is_address_based_alias(alias):- address_aliases.add(alias)+ for reference in blueprint.collect_located_pipe_references():+ if QualifiedRef.has_cross_package_prefix(reference.pipe_ref):+ alias, _remainder = QualifiedRef.split_cross_package_ref(reference.pipe_ref)+ if QualifiedRef.is_address_based_alias(alias) and alias not in first_references:+ first_references[alias] = (reference, blueprint)- if not address_aliases:+ if not first_references:return# Derive extra search dirs from bundle source pathsextra_search_dirs = _find_methods_dirs_from_blueprints(blueprints)- for full_address in sorted(address_aliases):+ unresolved_items: list[PipesAndConceptValidationErrorData] = []+ for full_address, (reference, blueprint) in first_references.items():if full_address in library.dependency_libraries:continue- self._load_address_based_dependency(- library=library,- full_address=full_address,- extra_search_dirs=extra_search_dirs,+ try:+ self._load_address_based_dependency(+ library=library,+ full_address=full_address,+ extra_search_dirs=extra_search_dirs,+ )+ except (MethodFetchDisabledError, MethodDependencyFetchError) as exc:+ # The item carries the caller-facing text; the host's log keeps the whole cause chain, git's raw output+ # included, since a cause on the host (git missing, an unwritable clone directory) becomes an item too.+ causes = " <- ".join(f"{type(cause).__name__}: {cause}" for cause in iter_cause_chain(exc))+ log.warning(f"Method package '{full_address}' could not be resolved: {causes}")+ unresolved_items.append(+ PipesAndConceptValidationErrorData(+ error_type=PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY,+ domain_code=blueprint.domain,+ source=blueprint.source,+ pipe_code=reference.referring_pipe_code,+ missing_pipe_code=reference.pipe_ref,+ message=exc.message,+ field_path=reference.field_path,+ )+ )++ if unresolved_items:+ raise LibraryLoadingError(+ message=" ".join(item.message for item in unresolved_items),+ pipe_concept_validation_errors=unresolved_items,)# Wire concept resolver after all deps are loaded- if address_aliases:- library.concept_library.set_concept_resolver(library.resolve_concept)+ library.concept_library.set_concept_resolver(library.resolve_concept)def _load_address_based_dependency(self,diff --git a/pipelex/methods/fetch_on_miss.py b/pipelex/methods/fetch_on_miss.pyindex 9f9f04721..80af720ee 100644--- a/pipelex/methods/fetch_on_miss.py+++ b/pipelex/methods/fetch_on_miss.py@@ -32,7 +32,8 @@ from pipelex.methods.structures_check import (scan_structured_content_classes,)-MANUAL_INSTALL_HINT = "install the method manually (e.g. `mthds install <address>`, or copy the package into ~/.mthds/methods/)"+# The remedy every refusal ends with. It names no directory: on a host, the runtime's own store is not the caller's to write.+MANUAL_INSTALL_HINT = "install the package where this runtime runs (for example with `mthds install <address>`)"def _warn_on_tag_mismatch(*, installed: InstalledMethod, ref: MethodRef | None) -> None:@@ -102,20 +103,21 @@ def resolve_address_based_method(if parse_error is not None:msg = (- f"Method '{full_address}' is not installed and its reference cannot be parsed: {parse_error} Fix the reference, or {MANUAL_INSTALL_HINT}."+ f"Method '{full_address}' is referenced but not installed, and its address cannot be parsed: {parse_error} "+ f"Correct the address, or {MANUAL_INSTALL_HINT}.")raise MethodDependencyFetchError(msg) from parse_errorif ref is None:msg = (- f"Method '{full_address}' is not installed and cannot be fetched (only github.com/... addresses are fetchable). "- f"Install it into ~/.mthds/methods/ or .mthds/methods/."+ f"Method '{full_address}' is referenced but not installed, and this runtime cannot fetch it: only github.com/... addresses "+ f"are fetchable. Correct the address, or {MANUAL_INSTALL_HINT}.")raise MethodDependencyFetchError(msg)if not is_method_fetch_on_miss_enabled():msg = (- f"Method '{ref.ref_str}' is referenced but not installed, and fetch-on-miss is disabled. "- f"Enable it with `fetch_on_miss = true` under [interpreter.methods] in your pipelex.toml "- f"(or {METHODS_FETCH_ON_MISS_ENV_VAR}=1), or {MANUAL_INSTALL_HINT}."+ f"Method '{ref.ref_str}' is referenced but not installed, and fetch-on-miss is disabled on this runtime, so it does not "+ f"fetch it. Correct the address if it is wrong, or {MANUAL_INSTALL_HINT}. Fetch-on-miss is enabled by "+ f"`fetch_on_miss = true` under [interpreter.methods] in the runtime's pipelex.toml, or {METHODS_FETCH_ON_MISS_ENV_VAR}=1.")raise MethodFetchDisabledError(msg)@@ -130,8 +132,8 @@ def resolve_address_based_method(raiseexcept MethodRefError as exc:msg = (- f"Method '{ref.ref_str}' is not installed and fetching it failed: {exc} "- f"Check the address, tag, and network access, or {MANUAL_INSTALL_HINT}."+ f"Method '{ref.ref_str}' is referenced but not installed, and fetching it failed: {exc} "+ f"Correct the address or the tag, or {MANUAL_INSTALL_HINT}.")raise MethodDependencyFetchError(msg) from excdiff --git a/pipelex/methods/fetching.py b/pipelex/methods/fetching.pyindex 166a87cda..382f671a2 100644--- a/pipelex/methods/fetching.py+++ b/pipelex/methods/fetching.py@@ -52,6 +52,27 @@ class FetchedMethodPackage(BaseModel):return MethodProvenance(address=self.full_address, tag=self.ref.tag, commit_sha=self.commit_sha)+CLONE_DIRECTORY_PLACEHOLDER = "<clone directory>"+++def _without_host_directory(*, text: str, directory: Path) -> str:+ """Remove from git's output every mention of `directory`, a clone directory on this host.++ Git's own explanation (`remote: Repository not found.`, `fatal: … not found`) is what the caller can use; the+ directory it names is a temporary directory of the host, gone once the fetch ends. Git's progress fragment+ `Cloning into '<directory>'...` is cut, and any other mention of the directory is replaced by a placeholder, so a+ line whose reason names it (`fatal: could not create work tree dir '<directory>': Permission denied`) keeps the+ reason. Both spellings of the directory are matched, the longer first since macOS reaches its temporary+ directory through a symlink and the resolved spelling contains the other.+ """+ spellings = sorted({str(directory), str(directory.resolve())}, key=len, reverse=True)+ for spelling in spellings:+ text = text.replace(f"Cloning into '{spelling}'...", "")+ for spelling in spellings:+ text = text.replace(spelling, CLONE_DIRECTORY_PLACEHOLDER)+ return "\n".join(line.rstrip() for line in text.splitlines()).strip()++def resolve_head_commit_sha(*, clone_dir: Path) -> str:"""Resolve the commit SHA a clone's HEAD points at.@@ -76,10 +97,10 @@ def resolve_head_commit_sha(*, clone_dir: Path) -> str:msg = "git is not installed or not found on PATH"raise MethodFetchError(msg) from excexcept subprocess.CalledProcessError as exc:- msg = f"Failed to resolve the fetched commit in '{clone_dir}': {exc.stderr.strip()}"+ msg = f"Failed to resolve the fetched commit: {_without_host_directory(text=exc.stderr.strip(), directory=clone_dir)}"raise MethodFetchError(msg) from excexcept subprocess.TimeoutExpired as exc:- msg = f"Timed out resolving the fetched commit in '{clone_dir}'"+ msg = "Timed out resolving the fetched commit"raise MethodFetchError(msg) from excreturn result.stdout.strip()@@ -110,7 +131,7 @@ def ensure_cloned_at_tag(*, clone_dir: Path, ref: MethodRef) -> None:msg = "git is not installed or not found on PATH"raise MethodFetchError(msg) from excexcept subprocess.TimeoutExpired as exc:- msg = f"Timed out verifying tag '{ref.tag}' in '{clone_dir}'"+ msg = f"Timed out verifying tag '{ref.tag}' of method reference '{ref.ref_str}'"raise MethodFetchError(msg) from excif result.returncode != 0:msg = (@@ -201,7 +222,7 @@ def fetch_method_package(else:clone_default_branch(clone_url=effective_clone_url, destination=dest_dir)except VCSFetchError as exc:- msg = f"Failed to fetch method '{ref.ref_str}': {exc.message}"+ msg = f"Failed to fetch method '{ref.ref_str}': {_without_host_directory(text=exc.message, directory=dest_dir)}"raise MethodFetchError(msg) from excif ref.tag:diff --git a/pipelex/mthds_parsing/pipelex_bundle_blueprint.py b/pipelex/mthds_parsing/pipelex_bundle_blueprint.pyindex 0fbdb1b05..f669564b5 100644--- a/pipelex/mthds_parsing/pipelex_bundle_blueprint.py+++ b/pipelex/mthds_parsing/pipelex_bundle_blueprint.py@@ -1,5 +1,5 @@from enum import StrEnum-from typing import Annotated, Any, cast+from typing import Annotated, Any, NamedTuple, castfrom pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator, model_validatorfrom pydantic.json_schema import SkipJsonSchema@@ -32,6 +32,14 @@ from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBlueprifrom pipelex.urls import URLs+class LocatedPipeReference(NamedTuple):+ """A pipe reference a controller makes, with the controller that makes it and where in it the reference is written."""++ pipe_ref: str+ referring_pipe_code: str+ field_path: str++def _strippable_same_domain_pipe_code(code: str, *, domain: str | None, existing_pipe_codes: set[str] | None = None) -> str | None:"""Return the namespace-stripped bare code when ``code`` is a safely-strippable same-domainover-qualification (``<domain>.<bare>``), else ``None`` — the raise-site gate for@@ -213,7 +221,11 @@ class PipelexBundleBlueprint(BaseModel):Returns:List of (pipe_ref_string, context_description) tuples"""- pipe_refs: list[tuple[str, str]] = []+ return [(reference.pipe_ref, reference.field_path) for reference in self.collect_located_pipe_references()]++ def collect_located_pipe_references(self) -> list[LocatedPipeReference]:+ """Collect all pipe references from controller blueprints, each with the controller making it, in declaration order."""+ pipe_refs: list[LocatedPipeReference] = []if not self.pipe:return pipe_refs@@ -222,16 +234,16 @@ class PipelexBundleBlueprint(BaseModel):for step_index, step in enumerate(pipe_blueprint.steps):# A binding step names no pipe, only a path in working memory.if isinstance(step, SubPipeBlueprint):- pipe_refs.append((step.pipe, f"pipe.{pipe_code}.steps[{step_index}].pipe"))+ pipe_refs.append(LocatedPipeReference(step.pipe, pipe_code, f"pipe.{pipe_code}.steps[{step_index}].pipe"))elif isinstance(pipe_blueprint, PipeBatchBlueprint):- pipe_refs.append((pipe_blueprint.branch_pipe_code, f"pipe.{pipe_code}.branch_pipe_code"))+ pipe_refs.append(LocatedPipeReference(pipe_blueprint.branch_pipe_code, pipe_code, f"pipe.{pipe_code}.branch_pipe_code"))elif isinstance(pipe_blueprint, PipeConditionBlueprint):for outcome_key, outcome_pipe in pipe_blueprint.outcomes.items():- pipe_refs.append((outcome_pipe, f"pipe.{pipe_code}.outcomes[{outcome_key}]"))- pipe_refs.append((pipe_blueprint.default_outcome, f"pipe.{pipe_code}.default_outcome"))+ pipe_refs.append(LocatedPipeReference(outcome_pipe, pipe_code, f"pipe.{pipe_code}.outcomes[{outcome_key}]"))+ pipe_refs.append(LocatedPipeReference(pipe_blueprint.default_outcome, pipe_code, f"pipe.{pipe_code}.default_outcome"))elif isinstance(pipe_blueprint, PipeParallelBlueprint):for branch_index, branch in enumerate(pipe_blueprint.branches):- pipe_refs.append((branch.pipe, f"pipe.{pipe_code}.branches[{branch_index}].pipe"))+ pipe_refs.append(LocatedPipeReference(branch.pipe, pipe_code, f"pipe.{pipe_code}.branches[{branch_index}].pipe"))return pipe_refsdiff --git a/pipelex/test_extras/mthds_corpus/entries/invalid_unresolved_package_dependency/bundle.mthds b/pipelex/test_extras/mthds_corpus/entries/invalid_unresolved_package_dependency/bundle.mthdsnew file mode 100644index 000000000..670491d5a--- /dev/null+++ b/pipelex/test_extras/mthds_corpus/entries/invalid_unresolved_package_dependency/bundle.mthds@@ -0,0 +1,12 @@+domain = "harbour_berths"+description = "Allocate a berth to an arriving vessel with a scheduling package published on a host no runtime fetches from"+main_pipe = "allocate_berth"++[pipe.allocate_berth]+type = "PipeSequence"+description = "Allocate a berth to the arriving vessel"+inputs = { arrival = "Text" }+output = "Text"+steps = [+ { pipe = "gitlab.com/harbour-authority/berth-scheduling->berth_scheduling.pick_berth", result = "berth" },+]diff --git a/pipelex/test_extras/mthds_corpus/entries/invalid_unresolved_package_dependency/entry.toml b/pipelex/test_extras/mthds_corpus/entries/invalid_unresolved_package_dependency/entry.tomlnew file mode 100644index 000000000..ab9dd9668--- /dev/null+++ b/pipelex/test_extras/mthds_corpus/entries/invalid_unresolved_package_dependency/entry.toml@@ -0,0 +1,12 @@+name = "invalid_unresolved_package_dependency"+description = "A harbour berth allocation calling a scheduling package by an address on a host no runtime fetches from"++validity = "invalid"+tier = "static"+granularity = "focused"++covers = [+ "error.unresolved_package_dependency",+]++expected_error = "unresolved_package_dependency"diff --git a/pipelex/test_extras/mthds_corpus/vocabulary.toml b/pipelex/test_extras/mthds_corpus/vocabulary.tomlindex fd2df5ca0..dd1df746a 100644--- a/pipelex/test_extras/mthds_corpus/vocabulary.toml+++ b/pipelex/test_extras/mthds_corpus/vocabulary.toml@@ -204,9 +204,13 @@ fails_at = "runtime"code = "unresolved_pipe_dependency"fails_at = "runtime"+[error.unresolved_package_dependency]+code = "unresolved_package_dependency"+fails_at = "runtime"+[error.unexported_pipe_dependency]code = "unexported_pipe_dependency"-excluded = "It refuses a reference to a pipe an installed dependency package loads but does not export, so the bundle that produces it needs that package installed beside it, with a manifest declaring `[exports]`. A focused entry is one self-contained bundle validated where nothing is installed, and an address-based reference to a package that is not installed fails as a missing method instead. Revisit if an entry can ever carry the packages it depends on."+excluded = "It refuses a reference to a pipe an installed dependency package loads but does not export, so the bundle that produces it needs that package installed beside it, with a manifest declaring `[exports]`. A focused entry is one self-contained bundle validated where nothing is installed, and an address-based reference to a package that is not installed fails as `unresolved_package_dependency` instead. Revisit if an entry can ever carry the packages it depends on."[error.unknown_model]code = "unknown_model"diff --git a/pipelex/validation_error_types.py b/pipelex/validation_error_types.pyindex 50677e7ee..77bee856f 100644--- a/pipelex/validation_error_types.py+++ b/pipelex/validation_error_types.py@@ -110,6 +110,10 @@ class PipeValidationErrorType(StrEnum):# merged library (a referenced concept or dependency pipe does not resolve).UNRESOLVED_CONCEPT = "unresolved_concept"UNRESOLVED_PIPE_DEPENDENCY = "unresolved_pipe_dependency"+ # A reference to a pipe of another method package, by its address, when the package cannot be resolved: not+ # installed with fetch-on-miss off, an address this runtime cannot fetch, or a fetch that failed. The item sits on+ # the first pipe naming the package, with the reference as written, `<address>->domain.code`, as its missing pipe.+ UNRESOLVED_PACKAGE_DEPENDENCY = "unresolved_package_dependency"# A reference from outside a dependency package to a pipe the package loads but does not export: the pipe# exists, so the remedy is to export it in the package or to call one of its public pipes.UNEXPORTED_PIPE_DEPENDENCY = "unexported_pipe_dependency"@@ -154,6 +158,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.NATIVE_CONCEPT_REDECLARATION| PipeValidationErrorType.UNRESOLVED_CONCEPT| PipeValidationErrorType.UNRESOLVED_PIPE_DEPENDENCY+ | PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY| PipeValidationErrorType.UNEXPORTED_PIPE_DEPENDENCY| PipeValidationErrorType.UNKNOWN_MODEL| PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR@@ -189,6 +194,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.NATIVE_CONCEPT_REDECLARATION| PipeValidationErrorType.UNRESOLVED_CONCEPT| PipeValidationErrorType.UNRESOLVED_PIPE_DEPENDENCY+ | PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY| PipeValidationErrorType.UNEXPORTED_PIPE_DEPENDENCY| PipeValidationErrorType.UNKNOWN_MODEL| PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR@@ -231,6 +237,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.NATIVE_CONCEPT_REDECLARATION| PipeValidationErrorType.UNRESOLVED_CONCEPT| PipeValidationErrorType.UNRESOLVED_PIPE_DEPENDENCY+ | PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY| PipeValidationErrorType.UNEXPORTED_PIPE_DEPENDENCY| PipeValidationErrorType.UNKNOWN_MODEL| PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR@@ -267,6 +274,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.INPUT_PRESENCE_VACUOUS| PipeValidationErrorType.UNRESOLVED_CONCEPT| PipeValidationErrorType.UNRESOLVED_PIPE_DEPENDENCY+ | PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY| PipeValidationErrorType.UNEXPORTED_PIPE_DEPENDENCY| PipeValidationErrorType.UNKNOWN_MODEL| PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR@@ -308,6 +316,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.NATIVE_CONCEPT_REDECLARATION| PipeValidationErrorType.UNRESOLVED_CONCEPT| PipeValidationErrorType.UNRESOLVED_PIPE_DEPENDENCY+ | PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY| PipeValidationErrorType.UNEXPORTED_PIPE_DEPENDENCY| PipeValidationErrorType.UNKNOWN_MODEL| PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR@@ -349,6 +358,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.NATIVE_CONCEPT_REDECLARATION| PipeValidationErrorType.UNRESOLVED_CONCEPT| PipeValidationErrorType.UNRESOLVED_PIPE_DEPENDENCY+ | PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY| PipeValidationErrorType.UNEXPORTED_PIPE_DEPENDENCY| PipeValidationErrorType.UNKNOWN_MODEL| PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR@@ -386,6 +396,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.NATIVE_CONCEPT_REDECLARATION| PipeValidationErrorType.UNRESOLVED_CONCEPT| PipeValidationErrorType.UNRESOLVED_PIPE_DEPENDENCY+ | PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY| PipeValidationErrorType.UNEXPORTED_PIPE_DEPENDENCY| PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR):diff --git a/tests/integration/pipelex/libraries/test_address_dependency_fetch_on_miss.py b/tests/integration/pipelex/libraries/test_address_dependency_fetch_on_miss.pyindex 220b7f7e5..09c820fc9 100644--- a/tests/integration/pipelex/libraries/test_address_dependency_fetch_on_miss.py+++ b/tests/integration/pipelex/libraries/test_address_dependency_fetch_on_miss.py@@ -13,10 +13,11 @@ from mthds.package.manifest.parser import parse_methods_tomlfrom pipelex.cli.installed_methods import PROVENANCE_FILENAMEfrom pipelex.interpreter_hub import get_library_manager-from pipelex.methods.exceptions import MethodFetchDisabledError+from pipelex.libraries.exceptions import LibraryLoadingErrorfrom pipelex.methods.fetching import FetchedMethodPackagefrom pipelex.methods.method_ref import parse_method_reffrom pipelex.mthds_parsing.parser import MthdsParser+from pipelex.validation_error_types import PipeValidationErrorTypeif TYPE_CHECKING:from pathlib import Path@@ -135,7 +136,7 @@ class TestAddressDependencyFetchOnMiss:@pytest.mark.usefixtures("global_methods_dir")def test_load_miss_with_fetch_disabled_raises_the_diagnostic(self, mocker: MockerFixture) -> None:- """With fetch-on-miss disabled, the former silent-miss warning is now a raised diagnostic."""+ """With fetch-on-miss disabled, a miss refuses the load with the diagnostic as its item, never a silent pass."""mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=False)fetch_mock = mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package")@@ -143,12 +144,14 @@ class TestAddressDependencyFetchOnMiss:library_id, _library = library_manager.open_library()try:blueprint = MthdsParser.make_pipelex_bundle_blueprint(mthds_content=CONSUMER_BUNDLE)- with pytest.raises(MethodFetchDisabledError) as exc_info:+ with pytest.raises(LibraryLoadingError) as exc_info:library_manager.load_from_blueprints(library_id=library_id, blueprints=[blueprint])finally:library_manager.teardown(library_id=library_id)- message = str(exc_info.value)- assert DEP_ALIAS in message- assert "fetch-on-miss is disabled" in message+ (item,) = exc_info.value.pipe_concept_validation_errors or []+ assert item.error_type == PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY+ assert item.missing_pipe_code == f"{DEP_ALIAS}->fom_scoring.fom_compute_score"+ assert DEP_ALIAS in item.message+ assert "fetch-on-miss is disabled" in item.messagefetch_mock.assert_not_called()diff --git a/tests/integration/pipelex/libraries/test_unresolved_package_dependency.py b/tests/integration/pipelex/libraries/test_unresolved_package_dependency.pynew file mode 100644index 000000000..97a779862--- /dev/null+++ b/tests/integration/pipelex/libraries/test_unresolved_package_dependency.py@@ -0,0 +1,227 @@+"""A bundle's reference to a method package that cannot be resolved is a verdict item, never a no-verdict fault.++A consumer calls a pipe of another package by its address (`<address>->domain.code`). When no installed copy matches+and the package cannot be fetched, the load is refused with one `unresolved_package_dependency` item per address,+located on the first pipe that names it, with the reference as written in `missing_pipe_code`. A failure of the host's+own store stays the fault it is, and so does a host library directory's unresolvable reference.++The packages are invented; every test isolates the installed store, and none reaches the network.+"""++import json+import logging+from pathlib import Path++import pytest+from mthds.package.exceptions import VCSFetchError+from mthds.package.manifest.parser import parse_methods_toml+from pytest_mock import MockerFixture++from pipelex.base_exceptions import DisclosureMode, ValidationErrorCategory, ValidationErrorItem+from pipelex.interpreter_hub import get_library_manager+from pipelex.libraries.exceptions import LibraryLoadingError+from pipelex.methods.exceptions import MethodInstallError, MethodPackageNotFoundError+from pipelex.methods.fetching import FetchedMethodPackage, fetch_method_package+from pipelex.methods.method_ref import MethodRef, parse_method_ref+from pipelex.mthds_parsing.parser import MthdsParser+from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.execution_seams import acquire_library+from pipelex.pipeline.validate_bundle import validate_bundle+from pipelex.validation_error_types import PipeValidationErrorType+from tests.integration.pipelex.libraries.installed_packages import isolate_installed_methods, write_consumer+from tests.integration.pipelex.libraries.test_data import ProbePackageTestData++PROBE_REFERENCE = f"{ProbePackageTestData.DEP_ALIAS}->probe_dep.entry"+GITLAB_REFERENCE = "gitlab.com/someone/pkg->other_dep.entry"++TWO_REFERENCES_BUNDLE = f"""domain = "probe_consumer"+description = "A consumer naming two packages, the first one twice"++[pipe.go]+type = "PipeSequence"+description = "Call both packages"+inputs = {{ data = "Text" }}+output = "Text"+steps = [+ {{ pipe = "{PROBE_REFERENCE}", result = "first" }},+ {{ pipe = "{GITLAB_REFERENCE}", result = "second" }},+]++[pipe.again]+type = "PipeSequence"+description = "Call the first package again"+inputs = {{ data = "Text" }}+output = "Text"+steps = [{{ pipe = "{PROBE_REFERENCE}", result = "out" }}]+"""+++def _enable_fetch_on_miss(*, mocker: MockerFixture) -> None:+ mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=True)+++async def _verdict_for(*, mthds_content: str) -> ValidateBundleError:+ with pytest.raises(ValidateBundleError) as exc_info:+ await validate_bundle(mthds_contents=[mthds_content])+ return exc_info.value+++def _package_items(verdict: ValidateBundleError) -> list[ValidationErrorItem]:+ items = verdict.to_error_report().validation_errors or []+ package_items = [item for item in items if item.error_type == PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY]+ assert len(package_items) == len(items), f"Only package items were expected, got {[(item.category, item.error_type) for item in items]}"+ return package_items+++def _strict_dump(verdict: ValidateBundleError) -> str:+ return json.dumps(verdict.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT))+++def _assert_located_on_go(item: ValidationErrorItem, *, reference: str) -> None:+ assert item.category == ValidationErrorCategory.PIPE_VALIDATION+ assert item.pipe_code == "go"+ assert item.domain_code == "probe_consumer"+ assert item.missing_pipe_code == reference+ assert item.field_path == "pipe.go.steps[0].pipe"++[email protected](loop_scope="class")+class TestUnresolvedPackageDependency:+ async def test_a_package_not_installed_with_fetching_off_is_one_item(self, tmp_path: Path, mocker: MockerFixture) -> None:+ isolate_installed_methods(mocker=mocker, root=tmp_path)+ fetch_mock = mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package")++ verdict = await _verdict_for(mthds_content=ProbePackageTestData.CONSUMER_BUNDLE)++ (item,) = _package_items(verdict)+ _assert_located_on_go(item, reference=PROBE_REFERENCE)+ assert ProbePackageTestData.DEP_ALIAS in item.message+ assert "fetch-on-miss is disabled" in item.message+ fetch_mock.assert_not_called()++ async def test_the_library_load_carries_the_item(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """The refusal is raised by the load itself, so every surface that translates a load gets it."""+ isolate_installed_methods(mocker=mocker, root=tmp_path)+ library_manager = get_library_manager()+ library_id, _library = library_manager.open_library()+ try:+ blueprint = MthdsParser.make_pipelex_bundle_blueprint(mthds_content=ProbePackageTestData.CONSUMER_BUNDLE)+ with pytest.raises(LibraryLoadingError) as exc_info:+ library_manager.load_from_blueprints(library_id=library_id, blueprints=[blueprint])+ finally:+ library_manager.teardown(library_id=library_id)+ items = exc_info.value.pipe_concept_validation_errors or []+ assert [(item.error_type, item.pipe_code, item.missing_pipe_code) for item in items] == [+ (PipeValidationErrorType.UNRESOLVED_PACKAGE_DEPENDENCY, "go", PROBE_REFERENCE)+ ]++ async def test_an_address_no_runtime_can_fetch_is_one_item(self, tmp_path: Path, mocker: MockerFixture) -> None:+ isolate_installed_methods(mocker=mocker, root=tmp_path)+ _enable_fetch_on_miss(mocker=mocker)++ verdict = await _verdict_for(mthds_content=ProbePackageTestData.consumer_calling(pipe_ref=GITLAB_REFERENCE))++ (item,) = _package_items(verdict)+ _assert_located_on_go(item, reference=GITLAB_REFERENCE)+ assert "gitlab.com/someone/pkg" in item.message+ assert "github.com/" in item.message++ async def test_a_failed_clone_is_one_item_naming_no_host_path(self, tmp_path: Path, mocker: MockerFixture) -> None:+ isolate_installed_methods(mocker=mocker, root=tmp_path)+ _enable_fetch_on_miss(mocker=mocker)+ unreachable_url = "file:///nonexistent-zz9/no-such-repo-zz9.git"++ def _fetch_from_nowhere(*, ref: MethodRef, dest_dir: Path, refuse_structures: bool) -> FetchedMethodPackage:+ return fetch_method_package(ref=ref, dest_dir=dest_dir, clone_url=unreachable_url, refuse_structures=refuse_structures)++ mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package", side_effect=_fetch_from_nowhere)++ verdict = await _verdict_for(mthds_content=ProbePackageTestData.CONSUMER_BUNDLE)++ (item,) = _package_items(verdict)+ _assert_located_on_go(item, reference=PROBE_REFERENCE)+ # Git's own explanation stays; its progress line naming the runner's clone directory does not.+ assert "does not appear to be a git repository" in item.message+ strict_dump = _strict_dump(verdict)+ assert "does not appear to be a git repository" in strict_dump+ assert "Cloning into" not in strict_dump+ assert "mthds_fetch_on_miss_" not in strict_dump++ async def test_the_host_log_keeps_what_caused_the_item(self, tmp_path: Path, mocker: MockerFixture, caplog: pytest.LogCaptureFixture) -> None:+ """The item carries the caller-facing text; the host's own log keeps the whole cause chain, git's raw output included."""+ isolate_installed_methods(mocker=mocker, root=tmp_path)+ _enable_fetch_on_miss(mocker=mocker)+ mocker.patch(+ "pipelex.methods.fetching.clone_default_branch",+ side_effect=VCSFetchError("Failed to clone 'https://github.com/invented/probe-lib.git': Cloning into '/host/clones/x'...\nfatal: boom"),+ )++ with caplog.at_level(logging.WARNING):+ await _verdict_for(mthds_content=ProbePackageTestData.CONSUMER_BUNDLE)++ warnings = [+ record.message for record in caplog.records if record.levelno == logging.WARNING and ProbePackageTestData.DEP_ALIAS in record.message+ ]+ assert len(warnings) == 1, warnings+ assert "MethodDependencyFetchError" in warnings[0]+ assert "VCSFetchError" in warnings[0]+ assert "Cloning into '/host/clones/x'" in warnings[0]++ async def test_a_repository_without_the_package_is_one_item(self, tmp_path: Path, mocker: MockerFixture) -> None:+ isolate_installed_methods(mocker=mocker, root=tmp_path)+ _enable_fetch_on_miss(mocker=mocker)+ mocker.patch(+ "pipelex.methods.fetch_on_miss.fetch_method_package",+ side_effect=MethodPackageNotFoundError("No package in 'github.com/invented/probe-lib' matches 'probe'; the repository holds: other."),+ )++ verdict = await _verdict_for(mthds_content=ProbePackageTestData.CONSUMER_BUNDLE)++ (item,) = _package_items(verdict)+ _assert_located_on_go(item, reference=PROBE_REFERENCE)+ assert "the repository holds: other" in item.message++ async def test_every_unresolved_address_is_one_item_on_the_first_pipe_naming_it(self, tmp_path: Path, mocker: MockerFixture) -> None:+ isolate_installed_methods(mocker=mocker, root=tmp_path)++ verdict = await _verdict_for(mthds_content=TWO_REFERENCES_BUNDLE)++ items = _package_items(verdict)+ assert [(item.pipe_code, item.missing_pipe_code, item.field_path) for item in items] == [+ ("go", PROBE_REFERENCE, "pipe.go.steps[0].pipe"),+ ("go", GITLAB_REFERENCE, "pipe.go.steps[1].pipe"),+ ]++ async def test_an_install_failure_stays_the_host_s_fault(self, tmp_path: Path, mocker: MockerFixture) -> None:+ isolate_installed_methods(mocker=mocker, root=tmp_path)+ _enable_fetch_on_miss(mocker=mocker)+ package_dir = tmp_path / "fetched"+ package_dir.mkdir()+ (package_dir / "METHODS.toml").write_text(ProbePackageTestData.MANIFEST_EXPORTING_EVERYTHING, encoding="utf-8")+ (package_dir / "probe_dep.mthds").write_text(ProbePackageTestData.DEP_BUNDLE, encoding="utf-8")+ fetched = FetchedMethodPackage(+ ref=parse_method_ref(ProbePackageTestData.DEP_ALIAS),+ full_address=ProbePackageTestData.DEP_ALIAS,+ commit_sha="c" * 40,+ clone_dir=tmp_path,+ package_dir=package_dir,+ manifest=parse_methods_toml(ProbePackageTestData.MANIFEST_EXPORTING_EVERYTHING),+ )+ mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package", return_value=fetched)+ mocker.patch("pipelex.methods.fetch_on_miss.install_method_package", side_effect=MethodInstallError("The install target is occupied."))++ with pytest.raises(MethodInstallError):+ await validate_bundle(mthds_contents=[ProbePackageTestData.CONSUMER_BUNDLE])++ async def test_a_host_library_directory_s_unresolved_reference_is_no_verdict(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """A host's own directories load untranslated: their refusal is the host's fault, never the caller's verdict."""+ isolate_installed_methods(mocker=mocker, root=tmp_path)+ host_dir = tmp_path / "host-library"+ host_dir.mkdir()+ write_consumer(root=host_dir, bundles={"consumer.mthds": ProbePackageTestData.CONSUMER_BUNDLE})++ with pytest.raises(LibraryLoadingError) as exc_info:+ acquire_library(library_id="", library_dirs=[str(host_dir)])++ assert not isinstance(exc_info.value, ValidateBundleError)+ assert exc_info.value.to_error_report().error_domain is Nonediff --git a/tests/unit/pipelex/methods/test_fetch_on_miss.py b/tests/unit/pipelex/methods/test_fetch_on_miss.pyindex 1c71ac4b3..db221a5f4 100644--- a/tests/unit/pipelex/methods/test_fetch_on_miss.py+++ b/tests/unit/pipelex/methods/test_fetch_on_miss.py@@ -104,7 +104,7 @@ class TestResolveAddressBasedMethod:@pytest.mark.usefixtures("isolated_methods_dirs")def test_miss_with_fetch_disabled_raises_the_disabled_diagnostic(self, mocker: MockerFixture) -> None:- """A miss with fetch-on-miss disabled names the address, the switch, and the manual remedy."""+ """A miss with fetch-on-miss disabled names the address, the switch as the runtime's, and a remedy naming no directory."""mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=False)fetch_mock = mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package")@@ -115,7 +115,8 @@ class TestResolveAddressBasedMethod:assert FULL_ADDRESS in messageassert "PIPELEX_METHODS_FETCH_ON_MISS" in messageassert "fetch_on_miss" in message- assert "install the method manually" in message+ assert "install the package where this runtime runs" in message+ assert "~/.mthds" not in messagefetch_mock.assert_not_called()@pytest.mark.usefixtures("isolated_methods_dirs")@@ -132,12 +133,13 @@ class TestResolveAddressBasedMethod:assert f"{FULL_ADDRESS}@v0.1.0" in messageassert "fetching it failed" in messageassert "clone timed out" in message+ assert "Correct the address or the tag" in messageassert exc_info.value.__cause__ is fetch_error@pytest.mark.usefixtures("isolated_methods_dirs")def test_miss_with_unfetchable_address_raises_a_diagnostic(self) -> None:"""An address-based alias that is not a fetchable reference gets a diagnostic, not a silent pass."""- with pytest.raises(MethodDependencyFetchError, match="cannot be fetched"):+ with pytest.raises(MethodDependencyFetchError, match="this runtime cannot fetch it"):resolve_address_based_method(full_address="example.com/foo/bar")def test_miss_fetches_installs_and_returns_the_method(self, isolated_methods_dirs: Path, tmp_path: Path, mocker: MockerFixture) -> None:diff --git a/tests/unit/pipelex/methods/test_fetching.py b/tests/unit/pipelex/methods/test_fetching.pyindex 9cb44e44d..81bfe2bfa 100644--- a/tests/unit/pipelex/methods/test_fetching.py+++ b/tests/unit/pipelex/methods/test_fetching.py@@ -105,6 +105,46 @@ class TestFetchMethodPackage:with pytest.raises(MethodFetchError, match=re.escape("github.com/Pipelex/methods/documents")):fetch_method_package(ref=parse_method_ref("github.com/Pipelex/methods/documents"), dest_dir=tmp_path)+ @pytest.mark.parametrize("spelling", ["as_given", "resolved"])+ def test_clone_failure_names_no_clone_directory(self, mocker: MockerFixture, tmp_path: Path, spelling: str) -> None:+ """Git's progress line naming the clone directory is cut; a line giving git's reason keeps it, the directory masked."""+ dest_dir = tmp_path / "clone"+ named_dir = dest_dir if spelling == "as_given" else dest_dir.resolve()+ git_failure = (+ f"Failed to clone 'https://github.com/Pipelex/methods.git': Cloning into '{named_dir}'...\n"+ f"fatal: could not create work tree dir '{named_dir}': Permission denied\n"+ "remote: Repository not found."+ )+ mocker.patch("pipelex.methods.fetching.clone_default_branch", side_effect=VCSFetchError(git_failure))++ with pytest.raises(MethodFetchError) as exc_info:+ fetch_method_package(ref=parse_method_ref("github.com/Pipelex/methods/documents"), dest_dir=dest_dir)++ message = str(exc_info.value)+ assert str(dest_dir) not in message+ assert str(dest_dir.resolve()) not in message+ assert "Cloning into" not in message+ assert "Failed to clone 'https://github.com/Pipelex/methods.git':" in message+ assert "fatal: could not create work tree dir '<clone directory>': Permission denied" in message+ assert "remote: Repository not found." in message++ def test_a_reason_sharing_the_prefix_line_survives(self, mocker: MockerFixture, tmp_path: Path) -> None:+ """When git's only line names the clone directory, as when it cannot create it, that line is git's whole reason."""+ dest_dir = tmp_path / "clone"+ git_failure = (+ f"Failed to clone 'https://github.com/Pipelex/methods.git': fatal: could not create work tree dir '{dest_dir}': Permission denied"+ )+ mocker.patch("pipelex.methods.fetching.clone_default_branch", side_effect=VCSFetchError(git_failure))++ with pytest.raises(MethodFetchError) as exc_info:+ fetch_method_package(ref=parse_method_ref("github.com/Pipelex/methods/documents"), dest_dir=dest_dir)++ message = str(exc_info.value)+ assert str(dest_dir) not in message+ assert message.endswith(+ "Failed to clone 'https://github.com/Pipelex/methods.git': fatal: could not create work tree dir '<clone directory>': Permission denied"+ )+def test_refusal_fires_before_any_module_import(self, mocker: MockerFixture, tmp_path: Path) -> None:"""Guardrail: a fetched package carrying a StructuredContent subclass is refused with therule-naming error before anything reaches the module-import machinery.