Skip to content

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

Fetch-on-miss for address-based method references (Phase 6, local half) (#1163)

Louis Choquelc81d6857feeb
diff --git a/.drift/acks/cli-docs.toml b/.drift/acks/cli-docs.toml
index 66075a5f9..10e3b7177 100644
--- a/.drift/acks/cli-docs.toml
+++ b/.drift/acks/cli-docs.toml
@@ -1,8 +1,8 @@
contract = "cli-docs"
-digest = "sha256:39e793b298f79da4dbc094804492f81fb91057e696ab1440d4197c3df7bdf44c"
+digest = "sha256:440d54e77c7ab292acb88632345fedf82ad29e2d7c35cc7149fa95f7d12c7b4f"
reviewed_by = "Louis Choquel"
-reviewed_at = "2026-08-29T01:58:32Z"
-rationale = "Reviewed the targets against the build-runner materialization change: build/runner.md and run-by-address.md now document that a fetched target's package is copied beside the generated script and the script references the copy; the agent-CLI contract doc is unaffected (main-CLI-only change)."
+reviewed_at = "2026-08-29T02:36:21Z"
+rationale = "Rebase of the fetch-on-miss branch onto v0.55.0: installed_methods.py now carries the install write path plus the review hardening (occupied-target identity check, unique mkdtemp staging with rename-race tolerance) on top of dev's method_resolver changes. No CLI command, flag, or help text changed; run-by-address.md documents both sides (build-runner materialization from dev, symlink refusal from this branch); the agent-CLI contract doc is unaffected."
[trigger_files]
"pipelex/cli/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"
@@ -129,6 +129,6 @@ rationale = "Reviewed the targets against the build-runner materialization chang
"pipelex/cli/deck_notice.py" = "blob:542877125e89e35b02bc969cfee952155b0d7c2c"
"pipelex/cli/error_handlers.py" = "blob:7a925ef0517bf9b01c3ca4b91ae54a70f57123a6"
"pipelex/cli/exceptions.py" = "blob:1d51c3a53ddd3f6cf8de566fa2ade3fa75ab7a3a"
-"pipelex/cli/installed_methods.py" = "blob:565b08fdd10efa0682d17619cfd7df252dbf61b5"
+"pipelex/cli/installed_methods.py" = "blob:09197f47baf8d7251d28d148a0544b4a23ee7365"
"pipelex/cli/method_resolver.py" = "blob:1230dde5f89ac28bbdcbcbbd0c1d485c71803caf"
"pipelex/cli/readiness.py" = "blob:6d185324ed0784663e1dc78d1194a28312c54798"
diff --git a/.drift/acks/config-docs.toml b/.drift/acks/config-docs.toml
index f5b63ccf9..eca205d35 100644
--- a/.drift/acks/config-docs.toml
+++ b/.drift/acks/config-docs.toml
@@ -1,20 +1,20 @@
contract = "config-docs"
-digest = "sha256:b23e603b819c383878a1ddab23614497d506f4bc77f4b6ea5e71d388bbd77c9c"
+digest = "sha256:da6430dd97584b9c51121406bc427b52d2bd26de47dc23e81ebfa851c635d6f7"
reviewed_by = "Louis Choquel"
-reviewed_at = "2026-08-21T09:19:21Z"
-rationale = "Trigger fired on a lint-comment migration only. config_loader.py and config_surface.py changed by three lines between them, every one a '# noqa: CODE' suppression rewritten into the new '# ruff: ignore[rule-name]' spelling that ruff 0.16 prefers; filtering their diff for any changed line that is not such a comment returns nothing. No config key was added, removed, renamed or narrowed, and none of the four validator sites this contract names (KitConfig._validate_targets, DryRunConfig.validate_image_urls, ImgGenConfig.validate_quality_mapping, LLMConfig.validate_effort_to_budget_mapping) was touched, so no value domain moved. docs/configuration/**, configs.py and config_cogt.py need no edit, and no migration-ledger entry is owed: a comment carries no schema, so there is nothing a ledger could remap."
+reviewed_at = "2026-08-29T01:23:56Z"
+rationale = "Added the [interpreter.methods] section with fetch_on_miss (new MethodsConfig model on InterpreterConfig, default true in pipelex.toml and the kit template). Documented in the new docs/configuration/config-practical/methods-config.md (added to both mkdocs nav sites) and cross-linked from packages.md and run-by-address.md. No existing key was removed, renamed or narrowed and none of the four named validator sites was touched, so no migration-ledger entry is owed: old override files without the new section keep booting on the shipped default."
[trigger_files]
"pipelex/cogt/config_cogt.py" = "blob:02f71cb4a6b01aebda59c2e31f262ef9c865e17b"
"pipelex/cogt/img_gen/img_gen_job_components.py" = "blob:084985080413fd8d6c3b1b9b0747020cb0161858"
-"pipelex/pipelex.toml" = "blob:a82dbc5011d2ceba5eb3ef2a463bc720ee0f169c"
+"pipelex/pipelex.toml" = "blob:37e48515b6d69d39cefb46ba1cda5c1cbb323a30"
"pipelex/system/configuration/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"
"pipelex/system/configuration/config_check.py" = "blob:efa78599c08e5e003d975cc54978ea5d267214a0"
"pipelex/system/configuration/config_loader.py" = "blob:86856b64aeff095a77f0c038fded2ee4dd948d00"
"pipelex/system/configuration/config_model.py" = "blob:83b29dc6e93393c9b98c4353636caf0135c80339"
"pipelex/system/configuration/config_root.py" = "blob:c7d43851270912d17413cfc6a511247d3c7cc160"
"pipelex/system/configuration/config_surface.py" = "blob:96f685656a3f4355e8a073e8bf6184e020fea8f5"
-"pipelex/system/configuration/configs.py" = "blob:60f346ba1205b762d4b6cff63494b0b34171e6ad"
+"pipelex/system/configuration/configs.py" = "blob:d0ceb14c35ebc5311c30e2eaf3d58af0bccd9077"
"pipelex/system/configuration/pipe_func_config.py" = "blob:dc8890e914fbcdb611147e42eaa0cd87b32288a5"
"pipelex/system/telemetry/telemetry_config.py" = "blob:7070951a6d3e4c10cb7d59822ce168c6590c53be"
"pipelex/tools/aws/aws_config.py" = "blob:c1aeafeae08d3921464db33795f11a29ff3892ba"
diff --git a/.pipelex/pipelex.toml b/.pipelex/pipelex.toml
index 1a9242f26..8b90d0275 100644
--- a/.pipelex/pipelex.toml
+++ b/.pipelex/pipelex.toml
@@ -159,6 +159,17 @@ is_dump_kwargs_enabled = false
is_dump_response_enabled = false
is_dump_error_enabled = false
+####################################################################################################
+# Methods Config
+####################################################################################################
+
+[interpreter.methods]
+# Fetch address-referenced methods (github.com/...->domain.pipe) on a miss and install them into
+# ~/.mthds/methods/. Set to false to forbid network fetches at load time — a miss then raises a
+# diagnostic naming the address and how to install it manually. The PIPELEX_METHODS_FETCH_ON_MISS
+# environment variable (1/0, true/false) overrides this setting when set.
+fetch_on_miss = true
+
####################################################################################################
# Scan Config
####################################################################################################
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e9399393e..1ac75e59f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## [Unreleased]
+
+### Added
+
+- **Include a method by address — fetch-on-miss**: a bundle referencing another method by address (`github.com/...->domain.pipe`) that misses the installed methods now fetches the package by reference — honoring an `@<tag>` pin, through the same grammar, bounds, and tags-only rules as a direct fetch, with the same hosted-parity warning for Python structure classes locally and a hard refusal on sandbox-hosted deployments — installs it into `~/.mthds/methods/` (atomic staging write, `.git/` stripped, fetch provenance recorded beside the manifest in a `.provenance.json` sidecar: address, tag, and the resolved commit SHA), and loads it so resolution proceeds. Once installed, the method is reused and the network is never touched again — including for a reference pinning a different tag, which warns and uses the installed copy. The former silent-miss warning in the library manager is now a real diagnostic: a miss that cannot be bridged (fetch disabled via the new `[interpreter.methods] fetch_on_miss` config or the `PIPELEX_METHODS_FETCH_ON_MISS` environment variable, an unfetchable address, or a failed fetch) raises an error naming the address and the remedy, never a silent pass. The install target is guarded by identity: two packages sharing a bare directory name but coming from different addresses collide with a loud error naming both addresses (never a silent load of the wrong package, never an overwrite), a concurrent install of the same package is tolerated (each attempt stages under a unique dot-prefixed directory, and losing the final rename race to a matching occupant uses the winner's copy), and a fetched package containing a symlink is refused outright, since a link's target would bypass the content scans. Installed-method lookup by full address is now case-insensitive, matching GitHub's owner/repository semantics and the fetch path's manifest-identity matching, and discovery skips dot-prefixed directories. See [Packages → Include by Address](building-methods/packages.md) and [Methods Configuration](configuration/config-practical/methods-config.md).
+
## [v0.55.0] - 2026-08-29
### Added
diff --git a/docs/building-methods/packages.md b/docs/building-methods/packages.md
index 6b3030e73..647c64f67 100644
--- a/docs/building-methods/packages.md
+++ b/docs/building-methods/packages.md
@@ -95,6 +95,43 @@ steps = [
This runtime-level capability exists separately from the current public `mthds package` CLI workflow documented on this page. If you rely on cross-package references, validate them against the specific runtime setup you are using.
+### Include by Address: Fetch-on-Miss
+
+The alias can also be a **full package address**, so a bundle can reference a method from a public GitHub repository directly — the same reference grammar as [running a method by address](../tools/cli/run-by-address.md):
+
+```toml
+[pipe.summarize_report]
+type = "PipeSequence"
+description = "Extract a document then summarize it"
+inputs = { doc = "PDF" }
+output = "Summary"
+steps = [
+ { pipe = "github.com/Pipelex/methods/documents->documents.extract_page_contents_and_views", result = "pages" },
+ { pipe = "summarize_pages" },
+]
+```
+
+An address-based reference resolves against the **installed methods** — `~/.mthds/methods/` (global) and `.mthds/methods/` (project-local), matched by the manifest's `address` + `name`, case-insensitively. When no installed method matches, Pipelex **fetches on miss**: it fetches the package by address — honoring an `@<tag>` pin, through the same grammar, bounds, and tags-only rules as a direct fetch — installs it into `~/.mthds/methods/`, records the fetch provenance (address, tag, and the commit SHA of what was actually cloned) in a `.provenance.json` sidecar beside the manifest, and loads it so resolution proceeds. The next load finds the installed copy and never touches the network again.
+
+A 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.
+- **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.
+
+To **disable network fetches at load time**, set the switch in your `pipelex.toml` (or use the environment variable, which takes precedence):
+
+```toml
+[interpreter.methods]
+fetch_on_miss = false
+```
+
+```bash
+export 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).
+
### Example Layout
```text
diff --git a/docs/configuration/config-practical/methods-config.md b/docs/configuration/config-practical/methods-config.md
new file mode 100644
index 000000000..26e63c51b
--- /dev/null
+++ b/docs/configuration/config-practical/methods-config.md
@@ -0,0 +1,45 @@
+---
+description: "Control whether Pipelex fetches address-referenced method packages from the network when they are missing from the installed methods."
+---
+
+# Methods Configuration
+
+The `MethodsConfig` class controls the behavior of installed and fetched method packages.
+
+## Configuration Options
+
+```python
+class MethodsConfig(ConfigModel):
+ fetch_on_miss: bool
+```
+
+### 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.
+
+## Example Configuration
+
+```toml
+[interpreter.methods]
+fetch_on_miss = true
+```
+
+## Environment Variable Override
+
+The `PIPELEX_METHODS_FETCH_ON_MISS` environment variable overrides the config when set: `1`/`true`/`yes`/`on` enables fetching, `0`/`false`/`no`/`off` disables it. An unrecognized value is warned about and ignored in favor of the config.
+
+```bash
+# Force-disable network fetches at load time for this shell
+export PIPELEX_METHODS_FETCH_ON_MISS=0
+```
+
+## When to Disable It
+
+- Offline or air-gapped environments, where a fetch could only hang or fail.
+- Deployments that must never pull code from the network at load time.
+- Reproducibility-sensitive runs where every dependency must be pre-installed and reviewed.
+
+## Related Documentation
+
+- [Packages](../../building-methods/packages.md) — Cross-package references and include by address
+- [Run a Method by Address](../../tools/cli/run-by-address.md) — The reference grammar, bounds, and provenance
diff --git a/docs/errors/method-dependency-fetch-error.md b/docs/errors/method-dependency-fetch-error.md
new file mode 100644
index 000000000..2b22e681f
--- /dev/null
+++ b/docs/errors/method-dependency-fetch-error.md
@@ -0,0 +1,21 @@
+---
+title: "Method dependency fetch"
+description: "Reference for the `MethodDependencyFetchError` Pipelex error class."
+---
+
+<!-- pipelex:generated -->
+
+# Method dependency fetch
+
+An address-referenced method is not installed and fetching it failed (or its address is not fetchable).
+
+| Field | Value |
+|---|---|
+| `error_type` | `MethodDependencyFetchError` |
+| `title` | Method dependency fetch |
+| `type_uri` | `https://docs.pipelex.com/latest/errors/method-dependency-fetch-error/` |
+| `error_domain` | _(inherited from parent)_ |
+| Defined in | `pipelex.methods.exceptions` |
+| Parent class | [`MethodRefError`](method-ref-error.md) |
+
+[Back to Error Reference](index.md)
diff --git a/docs/errors/method-fetch-disabled-error.md b/docs/errors/method-fetch-disabled-error.md
new file mode 100644
index 000000000..0e3379028
--- /dev/null
+++ b/docs/errors/method-fetch-disabled-error.md
@@ -0,0 +1,21 @@
+---
+title: "Method fetch disabled"
+description: "Reference for the `MethodFetchDisabledError` Pipelex error class."
+---
+
+<!-- pipelex:generated -->
+
+# Method fetch disabled
+
+An address-referenced method is not installed and fetch-on-miss is disabled, so it cannot be fetched.
+
+| Field | Value |
+|---|---|
+| `error_type` | `MethodFetchDisabledError` |
+| `title` | Method fetch disabled |
+| `type_uri` | `https://docs.pipelex.com/latest/errors/method-fetch-disabled-error/` |
+| `error_domain` | _(inherited from parent)_ |
+| Defined in | `pipelex.methods.exceptions` |
+| Parent class | [`MethodRefError`](method-ref-error.md) |
+
+[Back to Error Reference](index.md)
diff --git a/docs/errors/method-fetch-error.md b/docs/errors/method-fetch-error.md
index d5697506a..53aa04d88 100644
--- a/docs/errors/method-fetch-error.md
+++ b/docs/errors/method-fetch-error.md
@@ -7,7 +7,7 @@ description: "Reference for the `MethodFetchError` Pipelex error class."
# Method fetch
-Fetching the repository behind a method reference failed (clone or commit resolution).
+Fetching the repository behind a method reference failed (clone, tag verification, or commit resolution).
| Field | Value |
|---|---|
diff --git a/docs/errors/method-install-error.md b/docs/errors/method-install-error.md
new file mode 100644
index 000000000..387e15955
--- /dev/null
+++ b/docs/errors/method-install-error.md
@@ -0,0 +1,21 @@
+---
+title: "Method install"
+description: "Reference for the `MethodInstallError` Pipelex error class."
+---
+
+<!-- pipelex:generated -->
+
+# Method install
+
+Installing a fetched method package into the installed-methods directory failed (occupied target, path escape, or copy failure).
+
+| Field | Value |
+|---|---|
+| `error_type` | `MethodInstallError` |
+| `title` | Method install |
+| `type_uri` | `https://docs.pipelex.com/latest/errors/method-install-error/` |
+| `error_domain` | _(inherited from parent)_ |
+| Defined in | `pipelex.methods.exceptions` |
+| Parent class | [`MethodRefError`](method-ref-error.md) |
+
+[Back to Error Reference](index.md)
diff --git a/docs/errors/method-package-symlink-error.md b/docs/errors/method-package-symlink-error.md
new file mode 100644
index 000000000..0e0457ab8
--- /dev/null
+++ b/docs/errors/method-package-symlink-error.md
@@ -0,0 +1,21 @@
+---
+title: "Method package symlink"
+description: "Reference for the `MethodPackageSymlinkError` Pipelex error class."
+---
+
+<!-- pipelex:generated -->
+
+# Method package symlink
+
+The fetched package contains a symlink, which fetched packages must not carry (it would bypass the content scans).
+
+| Field | Value |
+|---|---|
+| `error_type` | `MethodPackageSymlinkError` |
+| `title` | Method package symlink |
+| `type_uri` | `https://docs.pipelex.com/latest/errors/method-package-symlink-error/` |
+| `error_domain` | _(inherited from parent)_ |
+| Defined in | `pipelex.methods.exceptions` |
+| Parent class | [`MethodRefError`](method-ref-error.md) |
+
+[Back to Error Reference](index.md)
diff --git a/docs/errors/method-package-too-large-error.md b/docs/errors/method-package-too-large-error.md
index 7044b1a21..877d5e073 100644
--- a/docs/errors/method-package-too-large-error.md
+++ b/docs/errors/method-package-too-large-error.md
@@ -7,7 +7,7 @@ description: "Reference for the `MethodPackageTooLargeError` Pipelex error class
# Method package too large
-The selected package exceeds the fetched-package ceilings (file count or total bytes).
+Fetched content exceeds a ceiling: the selected package's file count or total bytes, or the repository's manifest scan.
| Field | Value |
|---|---|
diff --git a/docs/errors/platform-and-tooling.md b/docs/errors/platform-and-tooling.md
index 3ee83506a..9bd913c05 100644
--- a/docs/errors/platform-and-tooling.md
+++ b/docs/errors/platform-and-tooling.md
@@ -104,9 +104,13 @@ own page. Classes are grouped by subsystem.
## Methods
+- [`MethodDependencyFetchError`](method-dependency-fetch-error.md) — Method dependency fetch
+- [`MethodFetchDisabledError`](method-fetch-disabled-error.md) — Method fetch disabled
- [`MethodFetchError`](method-fetch-error.md) — Method fetch
+- [`MethodInstallError`](method-install-error.md) — Method install
- [`MethodPackageAmbiguityError`](method-package-ambiguity-error.md) — Method package ambiguity
- [`MethodPackageNotFoundError`](method-package-not-found-error.md) — Method package not found
+- [`MethodPackageSymlinkError`](method-package-symlink-error.md) — Method package symlink
- [`MethodPackageTooLargeError`](method-package-too-large-error.md) — Method package too large
- [`MethodRefError`](method-ref-error.md) — Method reference error
- [`MethodRefParseError`](method-ref-parse-error.md) — Method ref parse
diff --git a/docs/tools/cli/run-by-address.md b/docs/tools/cli/run-by-address.md
index 9cb7d4e2d..a76151538 100644
--- a/docs/tools/cli/run-by-address.md
+++ b/docs/tools/cli/run-by-address.md
@@ -60,10 +60,15 @@ What decides whether Python in a method is acceptable is **where it would execut
## Bounds
-Fetched packages are bounded: the clone has a fixed timeout, and the selected package is capped in file count and total bytes (tunable via the `PIPELEX_MAX_FETCHED_PACKAGE_FILES` and `PIPELEX_MAX_FETCHED_PACKAGE_TOTAL_KIB` environment variables). The manifest scan that locates the package is bounded too: at most `PIPELEX_MAX_SCANNED_MANIFESTS` manifests are considered per repository, and a `METHODS.toml` larger than `PIPELEX_MAX_MANIFEST_FILE_KIB` is skipped and reported rather than read. Content exceeding the caps is rejected with a clear error.
+Fetched packages are bounded: the clone has a fixed timeout, and the selected package is capped in file count and total bytes (tunable via the `PIPELEX_MAX_FETCHED_PACKAGE_FILES` and `PIPELEX_MAX_FETCHED_PACKAGE_TOTAL_KIB` environment variables). The manifest scan that locates the package is bounded too: at most `PIPELEX_MAX_SCANNED_MANIFESTS` manifests are considered per repository, and a `METHODS.toml` larger than `PIPELEX_MAX_MANIFEST_FILE_KIB` is skipped and reported rather than read. Content exceeding the caps is rejected with a clear error. Symlinks are refused outright: a fetched package containing one (file or directory) is rejected, because a link's target would bypass the content scans.
+
+## Referencing a Method by Address from Your Own Method
+
+The same addresses work *inside* a bundle: a pipe step can reference another method's pipe as `github.com/...->domain.pipe_code`, and a reference that misses the installed methods is fetched and installed automatically (fetch-on-miss). See [Packages → Include by Address](../../building-methods/packages.md#include-by-address-fetch-on-miss).
## Related Documentation
- [CLI Run](run.md)
- [CLI Validate](validate.md)
- [Methods & Packages](../../building-methods/packages.md)
+- [Methods Configuration](../../configuration/config-practical/methods-config.md)
diff --git a/mkdocs.yml b/mkdocs.yml
index 570d2622c..64afc887c 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -293,6 +293,7 @@ plugins:
- configuration/index.md: "Configuration Overview"
- configuration/config-pipeline-validation/dry-run-config.md: "Dry Run Configuration"
- configuration/config-practical/logging-config.md: "Logging Configuration"
+ - configuration/config-practical/methods-config.md: "Methods Configuration"
- configuration/config-practical/pipe-run-config.md: "Pipe Run Configuration"
- configuration/config-practical/reporting-config.md: "Reporting Configuration"
- configuration/config-practical/telemetry-config.md: "Telemetry Configuration"
@@ -547,6 +548,7 @@ nav:
- Dry Run: configuration/config-pipeline-validation/dry-run-config.md
- Practical Configuration:
- Logging: configuration/config-practical/logging-config.md
+ - Methods: configuration/config-practical/methods-config.md
- Pipe Run: configuration/config-practical/pipe-run-config.md
- Reporting: configuration/config-practical/reporting-config.md
- Telemetry: configuration/config-practical/telemetry-config.md
diff --git a/pipelex/cli/installed_methods.py b/pipelex/cli/installed_methods.py
index 565b08fdd..09197f47b 100644
--- a/pipelex/cli/installed_methods.py
+++ b/pipelex/cli/installed_methods.py
@@ -1,21 +1,32 @@
-"""Discovery and lookup of installed methods from the filesystem.
+"""Discovery, lookup, and installation of installed methods on the filesystem.
Scans ~/.mthds/methods/ (global) and .mthds/methods/ (project-local) for
-installed method packages.
+installed method packages, and owns the write path that installs a fetched
+package into that store (one directory per method, `METHODS.toml` at its root —
+the same layout the `mthds` CLI's installer writes).
"""
+import shutil
+import tempfile
from pathlib import Path
from mthds.package.discovery import MANIFEST_FILENAME
from mthds.package.manifest.parser import parse_methods_toml
from mthds.package.manifest.schema import MethodsManifest
-from pydantic import BaseModel
+from pydantic import BaseModel, ValidationError
+from pipelex.methods.exceptions import MethodInstallError
from pipelex.methods.fetching import MethodProvenance
GLOBAL_METHODS_DIR = Path.home() / ".mthds" / "methods"
PROJECT_METHODS_DIR = Path(".mthds") / "methods"
+# Written beside METHODS.toml when a method is installed by fetch: the address, the tag when one
+# was named, and the commit SHA of what was actually cloned — tags can move, the SHA explains runs.
+PROVENANCE_FILENAME = ".provenance.json"
+
+_STAGING_SUFFIX = ".staging"
+
class MethodNotFoundError(Exception):
"""Raised when no installed method matches the given name."""
@@ -47,6 +58,20 @@ class InstalledMethod(BaseModel):
provenance: MethodProvenance | None = None
+def _read_provenance(*, method_dir: Path) -> MethodProvenance | None:
+ """Read the fetch provenance sidecar of an installed method, if present and parseable."""
+ provenance_path = method_dir / PROVENANCE_FILENAME
+ if not provenance_path.is_file():
+ return None
+ content = provenance_path.read_text(encoding="utf-8")
+ try:
+ return MethodProvenance.model_validate_json(content)
+ except ValidationError:
+ # A hand-edited or stale sidecar must not break discovery — the method is still usable,
+ # it just has no recorded provenance.
+ return None
+
+
def discover_installed_methods(
*,
include_global: bool = True,
@@ -93,6 +118,10 @@ def discover_installed_methods(
for subdir in sorted(methods_dir.iterdir()):
if not subdir.is_dir():
continue
+ if subdir.name.startswith("."):
+ # Dot-prefixed directories are never methods — this also keeps a leftover
+ # install-staging directory out of discovery.
+ continue
manifest_path = subdir / MANIFEST_FILENAME
if not manifest_path.is_file():
continue
@@ -110,6 +139,7 @@ def discover_installed_methods(
path=subdir,
manifest=manifest,
mthds_files=mthds_files,
+ provenance=_read_provenance(method_dir=subdir),
)
)
@@ -143,6 +173,7 @@ def discover_method_at(method_dir: Path, *, seen_dirs: set[Path]) -> InstalledMe
path=resolved,
manifest=manifest,
mthds_files=mthds_files,
+ provenance=_read_provenance(method_dir=resolved),
)
@@ -199,7 +230,9 @@ def find_method_by_full_address(
The full address is computed as ``manifest.address + "/" + name`` for each
discovered installed method. For example, a package with
``address = "github.com/Pipelex/methods"`` and ``name = "documents"`` has
- the full address ``"github.com/Pipelex/methods/documents"``.
+ the full address ``"github.com/Pipelex/methods/documents"``. Matching is
+ case-insensitive, mirroring GitHub's own owner/repository semantics (and the
+ fetch path's manifest-identity matching).
Args:
full_address: The full package address to search for
@@ -212,9 +245,10 @@ def find_method_by_full_address(
if methods is None:
methods = discover_installed_methods(extra_search_dirs=extra_search_dirs)
+ folded = full_address.casefold()
for method in methods:
candidate_address = f"{method.manifest.address}/{method.name}"
- if candidate_address == full_address:
+ if candidate_address.casefold() == folded:
return method
return None
@@ -263,3 +297,102 @@ def find_method_by_name(
raise DuplicateMethodNameError(msg)
return matches[0]
+
+
+def _resolve_occupied_install_target(*, final_dir: Path, name: str, full_address: str | None) -> InstalledMethod:
+ """Decide what an already-occupied install target means: the same package, or a collision.
+
+ When the occupant is a method package whose full address matches *full_address* (another
+ process won the install race), the occupant is returned and used as-is. Anything else — a
+ package with a different address (two packages sharing the bare name *name*), or content
+ that is not a method package — is a loud collision error; the wrong package is never
+ silently loaded and the occupant is never silently overwritten.
+
+ Raises:
+ MethodInstallError: The occupant is not the same package.
+ """
+ occupant = discover_method_at(final_dir, seen_dirs=set())
+ occupant_address = f"{occupant.manifest.address}/{occupant.name}" if occupant is not None else None
+ if occupant is not None and full_address is not None and occupant_address is not None and occupant_address.casefold() == full_address.casefold():
+ return occupant
+ requested = full_address or name
+ occupant_desc = f"method '{occupant_address}'" if occupant_address else "content that is not a method package"
+ msg = (
+ f"Cannot install method '{requested}': '{final_dir}' is already occupied by {occupant_desc} — "
+ f"two method packages share the directory name '{name}'. Remove '{final_dir}' to let this package install there."
+ )
+ raise MethodInstallError(msg)
+
+
+def install_method_package(
+ *,
+ package_dir: Path,
+ name: str,
+ full_address: str | None = None,
+ provenance: MethodProvenance | None = None,
+ methods_dir: Path | None = None,
+) -> InstalledMethod:
+ """Install a method package directory into the installed-methods store.
+
+ Copies *package_dir* into ``<methods_dir>/<name>/`` (the global
+ ``~/.mthds/methods/`` by default) using a per-attempt unique staging directory
+ and an atomic rename, stripping any ``.git/`` and writing the fetch provenance
+ sidecar when one is given — so a partially-written install is never discovered
+ and concurrent installers never share staging state.
+
+ An already-occupied target is resolved by identity, before and after the copy:
+ an occupant whose full address matches *full_address* (a concurrent install of
+ the same package) is returned and used as-is; any other occupant is a loud
+ collision error — bare directory names are not unique across addresses, and
+ the wrong package must never be silently loaded or overwritten.
+
+ Args:
+ package_dir: The package directory to copy from (e.g. inside a fresh clone).
+ name: The method name — becomes the install directory's name.
+ full_address: The package's full address, used to verify an occupant's identity
+ and to name the package in collision errors.
+ provenance: The fetch provenance to record beside the manifest, if any.
+ methods_dir: Override for the installed-methods root (tests, project-local installs).
+
+ Returns:
+ The installed method, discovered from its final location — freshly written, or a
+ matching occupant a concurrent installer put there first.
+
+ Raises:
+ MethodInstallError: If *name* escapes the methods directory, the target is
+ occupied by a different package, or the copy fails.
+ """
+ target_root = (methods_dir or GLOBAL_METHODS_DIR).resolve()
+ target_root.mkdir(parents=True, exist_ok=True)
+
+ final_dir = (target_root / name).resolve()
+ if final_dir == target_root or final_dir.parent != target_root or name.startswith("."):
+ msg = f"Cannot install method '{name}': the name escapes the methods directory '{target_root}' or is not a valid method directory name."
+ raise MethodInstallError(msg)
+ if final_dir.exists():
+ return _resolve_occupied_install_target(final_dir=final_dir, name=name, full_address=full_address)
+
+ staging_dir = Path(tempfile.mkdtemp(dir=target_root, prefix=f".{name}{_STAGING_SUFFIX}-"))
+ try:
+ shutil.copytree(package_dir, staging_dir, dirs_exist_ok=True)
+ git_dir = staging_dir / ".git"
+ if git_dir.exists():
+ shutil.rmtree(git_dir)
+ if provenance is not None:
+ (staging_dir / PROVENANCE_FILENAME).write_text(provenance.model_dump_json(indent=2) + "\n", encoding="utf-8")
+ staging_dir.rename(final_dir)
+ except OSError as exc:
+ shutil.rmtree(staging_dir, ignore_errors=True)
+ if final_dir.exists():
+ # The rename lost a race: someone installed into the target between our existence
+ # check and our rename. Resolve the occupant by identity, exactly as above.
+ return _resolve_occupied_install_target(final_dir=final_dir, name=name, full_address=full_address)
+ msg = f"Failed to install method '{name}' into '{target_root}': {exc}"
+ raise MethodInstallError(msg) from exc
+
+ installed = discover_method_at(final_dir, seen_dirs=set())
+ if installed is None:
+ shutil.rmtree(final_dir, ignore_errors=True)
+ msg = f"Installed method '{name}' at '{final_dir}' carries no {MANIFEST_FILENAME} — the source package was not a method package."
+ raise MethodInstallError(msg)
+ return installed
diff --git a/pipelex/config.py b/pipelex/config.py
index b117c3abf..4debc3eee 100644
--- a/pipelex/config.py
+++ b/pipelex/config.py
@@ -1,6 +1,13 @@
+from pipelex import log
from pipelex.plugins.pipe_func_executor_registry import DIRECT_PIPE_FUNC_EXECUTION_MODE
from pipelex.runtime_hub import get_optional_config, get_required_config
from pipelex.system.configuration.configs import PipelexConfig
+from pipelex.system.environment import get_optional_env
+
+METHODS_FETCH_ON_MISS_ENV_VAR = "PIPELEX_METHODS_FETCH_ON_MISS"
+
+_ENV_TRUTHY = {"1", "true", "yes", "on"}
+_ENV_FALSY = {"0", "false", "no", "off"}
def get_config() -> PipelexConfig:
@@ -27,6 +34,29 @@ def get_pipe_func_execution_mode() -> str:
return optional_config.interpreter.pipe_func.execution_mode
+def is_method_fetch_on_miss_enabled() -> bool:
+ """Whether a missed address-based method reference may be fetched from the network (non-raising).
+
+ The ``PIPELEX_METHODS_FETCH_ON_MISS`` environment variable overrides the config when set
+ (``1``/``true``/``yes``/``on`` enables, ``0``/``false``/``no``/``off`` disables; an
+ unrecognized value is warned about and ignored). Otherwise the answer is the config's
+ ``interpreter.methods.fetch_on_miss``, defaulting to enabled when no config is set — safe to
+ call from loading paths that may run before the global config exists.
+ """
+ raw_env = get_optional_env(METHODS_FETCH_ON_MISS_ENV_VAR)
+ if raw_env is not None:
+ normalized = raw_env.strip().lower()
+ if normalized in _ENV_TRUTHY:
+ return True
+ if normalized in _ENV_FALSY:
+ return False
+ log.warning(f"Unrecognized {METHODS_FETCH_ON_MISS_ENV_VAR}={raw_env!r} (expected 1/0, true/false); falling back to the config")
+ optional_config = get_optional_config()
+ if not isinstance(optional_config, PipelexConfig):
+ return True
+ return optional_config.interpreter.methods.fetch_on_miss
+
+
def is_pipe_func_sandbox_hosted() -> bool:
"""Whether PipeFunc runs out-of-process in this process (non-raising; defaults to local).
diff --git a/pipelex/kit/configs/pipelex.toml b/pipelex/kit/configs/pipelex.toml
index 1a9242f26..8b90d0275 100644
--- a/pipelex/kit/configs/pipelex.toml
+++ b/pipelex/kit/configs/pipelex.toml
@@ -159,6 +159,17 @@ is_dump_kwargs_enabled = false
is_dump_response_enabled = false
is_dump_error_enabled = false
+####################################################################################################
+# Methods Config
+####################################################################################################
+
+[interpreter.methods]
+# Fetch address-referenced methods (github.com/...->domain.pipe) on a miss and install them into
+# ~/.mthds/methods/. Set to false to forbid network fetches at load time — a miss then raises a
+# diagnostic naming the address and how to install it manually. The PIPELEX_METHODS_FETCH_ON_MISS
+# environment variable (1/0, true/false) overrides this setting when set.
+fetch_on_miss = true
+
####################################################################################################
# Scan Config
####################################################################################################
diff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.py
index ca5789faa..db4ced3b4 100644
--- a/pipelex/libraries/library_manager.py
+++ b/pipelex/libraries/library_manager.py
@@ -14,7 +14,6 @@ from typing_extensions import override
import pipelex.builder as builder_pkg # package import — used for __file__ path
from pipelex import log
-from pipelex.cli.installed_methods import find_method_by_full_address
from pipelex.config import is_pipe_func_sandbox_hosted
from pipelex.core.concepts.concept_blueprint import ConceptBlueprint
from pipelex.core.concepts.concept_factory import ConceptFactory
@@ -43,6 +42,7 @@ from pipelex.libraries.library_utils import (
)
from pipelex.libraries.pipe.exceptions import PipeLibraryError
from pipelex.libraries.visibility_utils import check_visibility_for_blueprints, make_visibility_checker
+from pipelex.methods.fetch_on_miss import resolve_address_based_method
from pipelex.mthds_parsing.exceptions import MthdsParserError
from pipelex.mthds_parsing.handle_pipe_errors import categorize_pipe_validation_error
from pipelex.mthds_parsing.parser import MthdsParser
@@ -1131,7 +1131,10 @@ class LibraryManager(LibraryManagerAbstract):
Collects all cross-package pipe references from controller blueprints
(sequences, batches, conditions, parallels), identifies those whose
alias contains '/' (i.e. a full package address), and loads each
- unique address-based dependency.
+ unique address-based dependency. A dependency missing from the
+ installed 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.
Also searches for .mthds/methods/ directories relative to the bundle
source path, walking up ancestor directories to find installed methods
@@ -1177,25 +1180,25 @@ class LibraryManager(LibraryManagerAbstract):
*,
full_address: str,
extra_search_dirs: list[Path] | None = None,
- ) -> bool:
- """Load an installed method package on demand using its full address.
+ ) -> None:
+ """Load a method package on demand using its full address, fetching it on a miss.
- Discovers the matching installed method, builds a ResolvedDependency,
- and delegates to _load_single_dependency() to load it as a child
- library with the full address as alias.
+ Resolves the address to an installed method — fetching and installing the package
+ (honoring an ``@<tag>`` pin) when no installed method matches and fetch-on-miss is
+ enabled — builds a ResolvedDependency, and delegates to _load_single_dependency()
+ to load it as a child library with the full address as alias.
Args:
library: The main library to load into
full_address: The full package address (e.g. "github.com/Pipelex/methods/documents")
extra_search_dirs: Additional .mthds/methods/ directories to scan
- Returns:
- True if the dependency was successfully loaded, False otherwise
+ Raises:
+ MethodRefError: The address resolves to no installed method and could not be
+ fetched — fetch-on-miss disabled, an unfetchable address, a failed fetch,
+ or a failed install. Never a silent pass.
"""
- installed = find_method_by_full_address(full_address=full_address, extra_search_dirs=extra_search_dirs)
- if installed is None:
- log.warning(f"No installed method found for address '{full_address}'")
- return False
+ installed = resolve_address_based_method(full_address=full_address, extra_search_dirs=extra_search_dirs)
exported_pipe_codes = determine_exported_pipes(manifest=installed.manifest)
@@ -1213,8 +1216,6 @@ class LibraryManager(LibraryManagerAbstract):
resolved_dep=resolved_dep,
)
- return True
-
def _remove_pipes_from_blueprint(self, blueprint: PipelexBundleBlueprint) -> None:
library = self.get_current_library()
if blueprint.pipe is not None:
diff --git a/pipelex/methods/exceptions.py b/pipelex/methods/exceptions.py
index 3ca7d6e3d..342251214 100644
--- a/pipelex/methods/exceptions.py
+++ b/pipelex/methods/exceptions.py
@@ -34,5 +34,21 @@ class MethodPackageTooLargeError(MethodRefError):
"""Fetched content exceeds a ceiling: the selected package's file count or total bytes, or the repository's manifest scan."""
+class MethodPackageSymlinkError(MethodRefError):
+ """The fetched package contains a symlink, which fetched packages must not carry (it would bypass the content scans)."""
+
+
class MethodStructuresRefusedError(MethodRefError):
"""The fetched package declares in-process Python structure classes, which hosted execution refuses."""
+
+
+class MethodInstallError(MethodRefError):
+ """Installing a fetched method package into the installed-methods directory failed (occupied target, path escape, or copy failure)."""
+
+
+class MethodFetchDisabledError(MethodRefError):
+ """An address-referenced method is not installed and fetch-on-miss is disabled, so it cannot be fetched."""
+
+
+class MethodDependencyFetchError(MethodRefError):
+ """An address-referenced method is not installed and fetching it failed (or its address is not fetchable)."""
diff --git a/pipelex/methods/fetch_on_miss.py b/pipelex/methods/fetch_on_miss.py
new file mode 100644
index 000000000..b6fe18162
--- /dev/null
+++ b/pipelex/methods/fetch_on_miss.py
@@ -0,0 +1,161 @@
+"""Fetch-on-miss for address-based method references.
+
+When a bundle references another method by address (``github.com/...->domain.pipe``) and no
+installed method matches, this module bridges the miss: it fetches the package by reference
+(honoring ``@<tag>``, through the same grammar, bounds, and tag-only rules as a direct CLI
+fetch), installs it into the installed-methods store (``~/.mthds/methods/``) with its fetch
+provenance recorded, and hands it back so library loading can proceed. A miss that cannot be
+bridged — fetch disabled, an unfetchable address, a failed fetch — raises a diagnostic that
+names the address and the remedy; it is never a silent pass.
+"""
+
+import shutil
+import tempfile
+from pathlib import Path
+
+from pipelex import log
+from pipelex.cli.installed_methods import InstalledMethod, find_method_by_full_address, install_method_package
+from pipelex.config import METHODS_FETCH_ON_MISS_ENV_VAR, is_method_fetch_on_miss_enabled, is_pipe_func_sandbox_hosted
+from pipelex.methods.exceptions import (
+ MethodDependencyFetchError,
+ MethodFetchDisabledError,
+ MethodRefError,
+ MethodRefParseError,
+ MethodStructuresRefusedError,
+)
+from pipelex.methods.fetching import fetch_method_package
+from pipelex.methods.method_ref import MethodRef, looks_like_method_ref, parse_method_ref
+from pipelex.methods.structures_check import (
+ STRUCTURES_REFUSAL_RULE,
+ describe_structured_content_violations,
+ scan_structured_content_classes,
+)
+
+MANUAL_INSTALL_HINT = "install the method manually (e.g. `mthds install <address>`, or copy the package into ~/.mthds/methods/)"
+
+
+def _warn_on_tag_mismatch(*, installed: InstalledMethod, ref: MethodRef | None) -> None:
+ """Warn when a tag-pinned reference resolves to an installed copy that is not that tag."""
+ if ref is None or ref.tag is None:
+ return
+ if installed.provenance is not None and installed.provenance.tag == ref.tag:
+ return
+ if installed.provenance is None:
+ installed_desc = "of unrecorded provenance"
+ else:
+ installed_desc = f"fetched at tag '{installed.provenance.tag}'" if installed.provenance.tag else "fetched with no tag"
+ log.warning(
+ f"Method '{ref.address}' is already installed at '{installed.path}' ({installed_desc}) while the reference pins "
+ f"'@{ref.tag}'; using the installed copy. Remove '{installed.path}' to re-fetch at the pinned tag."
+ )
+
+
+def resolve_address_based_method(
+ *,
+ full_address: str,
+ extra_search_dirs: list[Path] | None = None,
+ methods_dir: Path | None = None,
+) -> InstalledMethod:
+ """Resolve an address-based method reference to an installed method, fetching on a miss.
+
+ Looks the address up among installed methods first (with any ``@<tag>`` stripped for the
+ lookup — the installed store is keyed by address alone). On a miss, when fetch-on-miss is
+ enabled and the address is fetchable, fetches the package by reference and installs it
+ into the installed-methods store, recording the fetch provenance (address, tag, commit
+ SHA) beside the manifest.
+
+ Args:
+ full_address: The address-based alias as written in the bundle, e.g.
+ ``github.com/Pipelex/methods/documents`` or ``[email protected]``.
+ extra_search_dirs: Additional ``.mthds/methods/`` directories to scan for the lookup.
+ methods_dir: Override for the installed-methods root the fetch installs into
+ (defaults to the global ``~/.mthds/methods/``).
+
+ Returns:
+ The installed method the reference resolves to.
+
+ Raises:
+ MethodFetchDisabledError: The method is not installed and fetch-on-miss is disabled.
+ MethodDependencyFetchError: The method is not installed and its address cannot be
+ parsed or fetched, or the fetch failed.
+ MethodStructuresRefusedError: On a sandbox-hosted deployment, the fetched package
+ declares in-process Python structure classes (locally this is a warning instead).
+ MethodInstallError: The fetch succeeded but installing the package failed — including
+ the install target being occupied by a different package that shares the bare
+ directory name (never silently loaded, never silently overwritten).
+ """
+ ref: MethodRef | None = None
+ parse_error: MethodRefParseError | None = None
+ lookup_address = full_address
+ if looks_like_method_ref(full_address):
+ try:
+ ref = parse_method_ref(full_address)
+ lookup_address = ref.address
+ except MethodRefParseError as exc:
+ parse_error = exc
+
+ installed = find_method_by_full_address(lookup_address, extra_search_dirs=extra_search_dirs)
+ if installed is not None:
+ _warn_on_tag_mismatch(installed=installed, ref=ref)
+ return installed
+
+ 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}."
+ )
+ raise MethodDependencyFetchError(msg) from parse_error
+ if 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/."
+ )
+ 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}."
+ )
+ raise MethodFetchDisabledError(msg)
+
+ clone_dir = Path(tempfile.mkdtemp(prefix="mthds_fetch_on_miss_"))
+ try:
+ try:
+ # Sandbox-hosted deployments hard-refuse fetched packages that declare in-process
+ # Python structure classes (the security seam); locally the scan below warns instead.
+ fetched = fetch_method_package(ref=ref, dest_dir=clone_dir, refuse_structures=is_pipe_func_sandbox_hosted())
+ except MethodStructuresRefusedError:
+ # Already the rule-naming refusal — surface it as-is, not as a generic fetch failure.
+ raise
+ except 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}."
+ )
+ raise MethodDependencyFetchError(msg) from exc
+
+ violations = scan_structured_content_classes(package_dir=fetched.package_dir)
+ if violations:
+ details = describe_structured_content_violations(violations=violations)
+ log.warning(
+ f"Method '{fetched.full_address}' declares Python structure classes ({details}). It runs locally, but "
+ f"{STRUCTURES_REFUSAL_RULE} — hosted execution would refuse it. Express the types as MTHDS concepts "
+ f"to keep the method hosted-runnable."
+ )
+
+ name = fetched.manifest.name or fetched.package_dir.name
+ # An occupied install target is resolved by identity inside install_method_package: a
+ # concurrent install of the same package (by full address) is returned and used, while a
+ # different occupant — two packages sharing the bare name — is a loud collision error.
+ installed = install_method_package(
+ package_dir=fetched.package_dir,
+ name=name,
+ full_address=fetched.full_address,
+ provenance=fetched.provenance,
+ methods_dir=methods_dir,
+ )
+ finally:
+ shutil.rmtree(clone_dir, ignore_errors=True)
+
+ log.info(f"Fetched method '{fetched.full_address}' at commit {fetched.commit_sha} and installed it into '{installed.path}'")
+ return installed
diff --git a/pipelex/methods/fetching.py b/pipelex/methods/fetching.py
index 54f9b971e..166a87cda 100644
--- a/pipelex/methods/fetching.py
+++ b/pipelex/methods/fetching.py
@@ -14,7 +14,7 @@ from mthds.package.manifest.schema import MethodsManifest
from mthds.package.vcs_resolver import clone_at_version, clone_default_branch
from pydantic import BaseModel, ConfigDict
-from pipelex.methods.exceptions import MethodFetchError, MethodPackageTooLargeError
+from pipelex.methods.exceptions import MethodFetchError, MethodPackageSymlinkError, MethodPackageTooLargeError
from pipelex.methods.fetch_limits import MAX_FETCHED_PACKAGE_FILES, MAX_FETCHED_PACKAGE_TOTAL_BYTES
from pipelex.methods.method_ref import MethodRef
from pipelex.methods.package_locator import locate_package_in_clone
@@ -121,7 +121,12 @@ def ensure_cloned_at_tag(*, clone_dir: Path, ref: MethodRef) -> None:
def ensure_package_within_bounds(*, package_dir: Path, package_address: str) -> None:
- """Reject a selected package that exceeds the fetched-package ceilings.
+ """Reject a selected package that exceeds the fetched-package ceilings or carries a symlink.
+
+ Symlinks are refused outright: the structures scan and these bounds walk the tree without
+ following links, while a later copy would copy the link's *target* — a scan bypass, and a way
+ to exfiltrate host files into the installed store. Fetched packages have no legitimate use
+ for symlinks.
Args:
package_dir: The selected package directory.
@@ -129,13 +134,21 @@ def ensure_package_within_bounds(*, package_dir: Path, package_address: str) ->
Raises:
MethodPackageTooLargeError: If the package exceeds the file-count or total-bytes cap.
+ MethodPackageSymlinkError: If the package directory, or anything inside it, is a symlink.
"""
+ if package_dir.is_symlink():
+ msg = f"Method package '{package_address}' is a symlink — fetched packages must not contain symlinks."
+ raise MethodPackageSymlinkError(msg)
file_count = 0
total_bytes = 0
for file_path in package_dir.rglob("*"):
relative_parts = file_path.relative_to(package_dir).parts
if any(part in _SKIPPED_DIR_NAMES for part in relative_parts):
continue
+ if file_path.is_symlink():
+ relative = "/".join(relative_parts)
+ msg = f"Method package '{package_address}' contains a symlink ('{relative}') — fetched packages must not contain symlinks."
+ raise MethodPackageSymlinkError(msg)
if not file_path.is_file():
continue
file_count += 1
@@ -177,6 +190,7 @@ def fetch_method_package(
MethodPackageNotFoundError: If no package matches the requested address.
MethodPackageAmbiguityError: If more than one package matches.
MethodPackageTooLargeError: If the selected package exceeds the ceilings.
+ MethodPackageSymlinkError: If the selected package contains a symlink.
MethodStructuresRefusedError: If *refuse_structures* is set and the package
declares structure classes.
"""
diff --git a/pipelex/methods/methods_config.py b/pipelex/methods/methods_config.py
new file mode 100644
index 000000000..76ca9a0e6
--- /dev/null
+++ b/pipelex/methods/methods_config.py
@@ -0,0 +1,13 @@
+from pipelex.system.configuration.config_model import ConfigModel
+
+
+class MethodsConfig(ConfigModel):
+ """Behavior of installed and fetched method packages.
+
+ ``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 the global methods directory so the load can proceed. When
+ disabled, such a miss raises a diagnostic instead of touching the network.
+ """
+
+ fetch_on_miss: bool
diff --git a/pipelex/migration/goldens/pipelex-config/[email protected] b/pipelex/migration/goldens/pipelex-config/[email protected]
index a82dbc501..37e48515b 100644
--- a/pipelex/migration/goldens/pipelex-config/[email protected]
+++ b/pipelex/migration/goldens/pipelex-config/[email protected]
@@ -321,6 +321,18 @@ structure_field_ordering = [
[interpreter.mthds.pipes]
field_ordering = ["type", "description", "inputs", "output"]
+####################################################################################################
+# Methods config
+####################################################################################################
+
+[interpreter.methods]
+# 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. Set to false to forbid network fetches at load time — a miss then raises a diagnostic
+# telling you the address and how to install it manually. The PIPELEX_METHODS_FETCH_ON_MISS
+# environment variable (1/0, true/false) overrides this setting when set.
+fetch_on_miss = true
+
####################################################################################################
# Pipe run config
####################################################################################################
diff --git a/pipelex/migration/goldens/pipelex-config/[email protected] b/pipelex/migration/goldens/pipelex-config/[email protected]
index cde871cdf..b4319bb47 100644
--- a/pipelex/migration/goldens/pipelex-config/[email protected]
+++ b/pipelex/migration/goldens/pipelex-config/[email protected]
@@ -543,6 +543,17 @@
"default": 10,
"open_node": false
},
+ "interpreter.methods": {
+ "value_type": "table",
+ "required": true,
+ "open_node": false
+ },
+ "interpreter.methods.fetch_on_miss": {
+ "value_type": "bool",
+ "required": true,
+ "default": true,
+ "open_node": false
+ },
"interpreter.mthds": {
"value_type": "table",
"required": true,
diff --git a/pipelex/pipelex.toml b/pipelex/pipelex.toml
index a82dbc501..37e48515b 100644
--- a/pipelex/pipelex.toml
+++ b/pipelex/pipelex.toml
@@ -321,6 +321,18 @@ structure_field_ordering = [
[interpreter.mthds.pipes]
field_ordering = ["type", "description", "inputs", "output"]
+####################################################################################################
+# Methods config
+####################################################################################################
+
+[interpreter.methods]
+# 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. Set to false to forbid network fetches at load time — a miss then raises a diagnostic
+# telling you the address and how to install it manually. The PIPELEX_METHODS_FETCH_ON_MISS
+# environment variable (1/0, true/false) overrides this setting when set.
+fetch_on_miss = true
+
####################################################################################################
# Pipe run config
####################################################################################################
diff --git a/pipelex/system/configuration/configs.py b/pipelex/system/configuration/configs.py
index 60f346ba1..d0ceb14c3 100644
--- a/pipelex/system/configuration/configs.py
+++ b/pipelex/system/configuration/configs.py
@@ -6,6 +6,7 @@ from pydantic import Field, field_validator, model_validator
from pipelex.cogt.config_cogt import InferenceConfig
from pipelex.graph.graph_config import GraphConfig
from pipelex.language.mthds_config import MthdsConfig
+from pipelex.methods.methods_config import MethodsConfig
from pipelex.system.configuration.config_model import ConfigModel
from pipelex.system.configuration.config_root import ConfigRoot
from pipelex.system.configuration.pipe_func_config import PipeFuncConfig
@@ -201,6 +202,7 @@ class InterpreterConfig(ConfigModel):
"""
mthds: MthdsConfig
+ methods: MethodsConfig
pipe_run: PipeRunConfig
pipe_func: PipeFuncConfig
pipeline_execution: PipelineExecutionConfig
diff --git a/tests/data/errors/error_identity.txt b/tests/data/errors/error_identity.txt
index b9cd4ca6d..0b921f572 100644
--- a/tests/data/errors/error_identity.txt
+++ b/tests/data/errors/error_identity.txt
@@ -153,9 +153,13 @@ LinkupError | Linkup | https://docs.pipelex.com/latest/errors/linkup-error/
LinkupSearchEmptyResultError | Linkup search empty result | https://docs.pipelex.com/latest/errors/linkup-search-empty-result-error/
LinkupSearchResponseError | Linkup search response | https://docs.pipelex.com/latest/errors/linkup-search-response-error/
ListWhereSingularError | List where singular | https://docs.pipelex.com/latest/errors/list-where-singular-error/
+MethodDependencyFetchError | Method dependency fetch | https://docs.pipelex.com/latest/errors/method-dependency-fetch-error/
+MethodFetchDisabledError | Method fetch disabled | https://docs.pipelex.com/latest/errors/method-fetch-disabled-error/
MethodFetchError | Method fetch | https://docs.pipelex.com/latest/errors/method-fetch-error/
+MethodInstallError | Method install | https://docs.pipelex.com/latest/errors/method-install-error/
MethodPackageAmbiguityError | Method package ambiguity | https://docs.pipelex.com/latest/errors/method-package-ambiguity-error/
MethodPackageNotFoundError | Method package not found | https://docs.pipelex.com/latest/errors/method-package-not-found-error/
+MethodPackageSymlinkError | Method package symlink | https://docs.pipelex.com/latest/errors/method-package-symlink-error/
MethodPackageTooLargeError | Method package too large | https://docs.pipelex.com/latest/errors/method-package-too-large-error/
MethodRefError | Method reference error | https://docs.pipelex.com/latest/errors/method-ref-error/
MethodRefParseError | Method ref parse | https://docs.pipelex.com/latest/errors/method-ref-parse-error/
diff --git a/tests/e2e/pipelex/cli/test_migrate_commands.py b/tests/e2e/pipelex/cli/test_migrate_commands.py
index 5d47ac0a3..c0418a2af 100644
--- a/tests/e2e/pipelex/cli/test_migrate_commands.py
+++ b/tests/e2e/pipelex/cli/test_migrate_commands.py
@@ -42,8 +42,10 @@ import subprocess # ruff: ignore[suspicious-subprocess-import] - invokes the re
from typing import TYPE_CHECKING, Any
from pipelex.migration.backup import existing_backups_of
+from pipelex.migration.documents import document_paths
+from pipelex.migration.engine import apply_ops_over_text
from pipelex.migration.goldens import defaults_golden_path, pre_history_document_path
-from pipelex.migration.ledger import packaged_migration_dir
+from pipelex.migration.ledger import load_ledger, packaged_migration_dir
from pipelex.migration.surfaces import build_config_surface_registry
from pipelex.system.configuration.config_loader import BACKENDS_DIR_NAME, BACKENDS_FILE_NAME, INFERENCE_DIR_NAME
from pipelex.system.configuration.config_surface import (
@@ -51,7 +53,7 @@ from pipelex.system.configuration.config_surface import (
PIPELEX_CONFIG_SURFACE_ID,
TELEMETRY_CONFIG_SURFACE_ID,
)
-from pipelex.tools.misc.toml_utils import load_toml_from_path
+from pipelex.tools.misc.toml_utils import load_toml_from_content, load_toml_from_path
from tests.e2e.agent_cli.conftest import REPO_ROOT
if TYPE_CHECKING:
@@ -191,6 +193,38 @@ def _todays_pipelex_config_document() -> dict[str, Any]:
return registry.surface_for_id(surface_id=PIPELEX_CONFIG_SURFACE_ID).read_defaults_document()
+def _engine_replay_of_pipelex_config(*, planted_text: str) -> dict[str, Any]:
+ """The packaged ledger's operations, replayed in order over *planted_text*, as a document.
+
+ This is the engine's own answer for what a migration of that text must produce — the reference
+ the command's output is held to. It is deliberately *not* today's packaged document: additive
+ changes never migrate (a key we add is supplied by the defaults layer, see
+ `docs/migration-ledger.md`), so a key added since the chain's last entry is legitimately absent
+ from a migrated file while present in today's document. What the migrated file must NOT carry
+ is any path today's shape does not have — asserted separately, by containment.
+ """
+ ledger = load_ledger(migration_dir=packaged_migration_dir(), surface_id=PIPELEX_CONFIG_SURFACE_ID)
+ text = planted_text
+ for entry in ledger.migration:
+ text = apply_ops_over_text(text=text, ops=entry.ops).text
+ return load_toml_from_content(text)
+
+
+def _assert_migrated_global_file_lands_on_todays_shape(*, global_file: Path, planted_text: str) -> None:
+ """The two halves of the strong assertion on a migrated full-tier file.
+
+ Equality with the engine's own replay proves the *command* did exactly what the engine is
+ already proven (by `make check-migration-schemas`) to do. Path containment in today's packaged
+ document proves the result carries nothing today's shape lacks — a stray table nothing reads
+ would fail here. Today's document may carry more: keys added since the chain's last entry are
+ supplied by the defaults layer, never by a migration.
+ """
+ migrated_document: dict[str, Any] = load_toml_from_path(path=global_file)
+ assert migrated_document == _engine_replay_of_pipelex_config(planted_text=planted_text)
+ stray_paths = document_paths(document=migrated_document) - document_paths(document=_todays_pipelex_config_document())
+ assert stray_paths == set(), f"the migrated file carries paths today's shape does not have: {sorted(stray_paths)}"
+
+
def _project_config_dir(*, hermetic_home: Path) -> Path:
"""The `.pipelex/` of a project rooted inside the hermetic HOME, created if it is not there.
@@ -514,7 +548,9 @@ class TestAPreReshapeMachine:
) -> None:
"""The whole loop through `pipelex migrate`, with the strong assertion on the global file.
- Migrated, it says exactly what the package's own `pipelex.toml` says today.
+ Migrated, it says exactly what the engine's own replay of the ledger says, and carries no
+ path today's packaged `pipelex.toml` lacks (keys added since the chain's last entry are
+ supplied by the defaults layer, never by a migration — so today's document may say more).
`make check-migration-schemas` already proves the *engine* turns the reference document the
reshape starts from into the one it lands on; what is proved here is that the *command*
does — walking two directories,
@@ -537,7 +573,7 @@ class TestAPreReshapeMachine:
assert str(global_file) in report
assert str(project_file) in report
- assert load_toml_from_path(path=global_file) == _todays_pipelex_config_document()
+ _assert_migrated_global_file_lands_on_todays_shape(global_file=global_file, planted_text=originals[global_file])
# The tier keeps its four settings and nothing else — a migration that had quietly folded
# the package defaults into a user's override would satisfy the assertion above and ruin
# the layering, since an override is read as "only these, on top of whatever is beneath".
@@ -739,10 +775,11 @@ class TestAPrePromptingStyleMachine:
assert migrated.returncode == 0, migrated.stdout + migrated.stderr
assert str(global_file) in migrated.stdout + migrated.stderr
- # The whole document, against the live packaged one: the tuned per-target map is gone, the
- # default it sat beside travels to where the reshape puts templating, and nothing else about
- # a file that crossed two entries in one run came out different.
- assert load_toml_from_path(path=global_file) == _todays_pipelex_config_document()
+ # The whole document, against the engine's own replay of both entries, plus containment in
+ # the live packaged shape: the tuned per-target map is gone, the default it sat beside
+ # travels to where the reshape puts templating, and nothing else about a file that crossed
+ # two entries in one run came out different.
+ _assert_migrated_global_file_lands_on_todays_shape(global_file=global_file, planted_text=original)
backups = existing_backups_of(path=global_file)
assert len(backups) == 1, f"expected exactly one backup of {global_file}, found {backups}"
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.py
new file mode 100644
index 000000000..220b7f7e5
--- /dev/null
+++ b/tests/integration/pipelex/libraries/test_address_dependency_fetch_on_miss.py
@@ -0,0 +1,154 @@
+"""Load-path integration for fetch-on-miss: an address-referenced dependency missing from the
+installed methods is fetched (mocked to a local fixture package), installed into the (redirected)
+global methods directory, and loaded so pipe resolution proceeds — and a miss with fetch disabled
+raises the diagnostic instead of passing silently.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import pytest
+from mthds.package.manifest.parser import parse_methods_toml
+
+from pipelex.cli.installed_methods import PROVENANCE_FILENAME
+from pipelex.interpreter_hub import get_library_manager
+from pipelex.methods.exceptions import MethodFetchDisabledError
+from pipelex.methods.fetching import FetchedMethodPackage
+from pipelex.methods.method_ref import parse_method_ref
+from pipelex.mthds_parsing.parser import MthdsParser
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from pytest_mock import MockerFixture
+
+DEP_ALIAS = "github.com/pipelex-tests/fom-dep-methods/scoring"
+COMMIT_SHA = "c" * 40
+
+DEP_MANIFEST = """\
+[package]
+name = "scoring"
+address = "github.com/pipelex-tests/fom-dep-methods"
+version = "0.1.0"
+description = "Scoring dependency for the fetch-on-miss load test"
+
+[exports.fom_scoring]
+pipes = ["fom_compute_score"]
+"""
+
+DEP_BUNDLE = """\
+domain = "fom_scoring"
+main_pipe = "fom_compute_score"
+
+[concept.FomWeightedScore]
+description = "A weighted score result"
+
+[pipe.fom_compute_score]
+type = "PipeLLM"
+description = "Compute a weighted score"
+output = "FomWeightedScore"
+prompt = "Compute a weighted score for: {{ item }}"
+
+[pipe.fom_compute_score.inputs]
+item = "Text"
+"""
+
+CONSUMER_BUNDLE = """\
+domain = "fom_consumer"
+
+[concept.FomAnalysisResult]
+description = "Analysis result combining scoring"
+
+[pipe.fom_analyze_item]
+type = "PipeSequence"
+description = "Analyze an item using the scoring dependency"
+output = "FomAnalysisResult"
+steps = [
+ { pipe = "__DEP_ALIAS__->fom_scoring.fom_compute_score" },
+ { pipe = "fom_summarize" },
+]
+
+[pipe.fom_analyze_item.inputs]
+item = "Text"
+
+[pipe.fom_summarize]
+type = "PipeLLM"
+description = "Summarize the analysis"
+output = "FomAnalysisResult"
+prompt = "Summarize the analysis for: {{ item }}"
+
+[pipe.fom_summarize.inputs]
+item = "Text"
+""".replace("__DEP_ALIAS__", DEP_ALIAS)
+
+
[email protected](name="global_methods_dir")
+def global_methods_dir_fixture(tmp_path: Path, mocker: MockerFixture) -> Path:
+ """Point the global and project methods directories at empty tmp locations."""
+ global_dir = tmp_path / "global-methods"
+ mocker.patch("pipelex.cli.installed_methods.GLOBAL_METHODS_DIR", global_dir)
+ mocker.patch("pipelex.cli.installed_methods.PROJECT_METHODS_DIR", tmp_path / "project-methods")
+ return global_dir
+
+
+def _make_fetched_dep(tmp_path: Path) -> FetchedMethodPackage:
+ """Build the dependency package on disk and wrap it as a fetch result."""
+ package_dir = tmp_path / "fetched-dep"
+ package_dir.mkdir(parents=True)
+ (package_dir / "METHODS.toml").write_text(DEP_MANIFEST, encoding="utf-8")
+ (package_dir / "scoring.mthds").write_text(DEP_BUNDLE, encoding="utf-8")
+ return FetchedMethodPackage(
+ ref=parse_method_ref(DEP_ALIAS),
+ full_address=DEP_ALIAS,
+ commit_sha=COMMIT_SHA,
+ clone_dir=tmp_path,
+ package_dir=package_dir,
+ manifest=parse_methods_toml(DEP_MANIFEST),
+ )
+
+
+class TestAddressDependencyFetchOnMiss:
+ def test_load_fetches_missing_dependency_and_resolution_proceeds(self, global_methods_dir: Path, tmp_path: Path, mocker: MockerFixture) -> None:
+ """A missed address dependency is fetched, installed, and loaded — the aliased pipe resolves."""
+ mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=True)
+ fetched = _make_fetched_dep(tmp_path)
+ fetch_mock = mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package", return_value=fetched)
+
+ library_manager = get_library_manager()
+ library_id, library = library_manager.open_library()
+ try:
+ blueprint = MthdsParser.make_pipelex_bundle_blueprint(mthds_content=CONSUMER_BUNDLE)
+ loaded_pipes = library_manager.load_from_blueprints(library_id=library_id, blueprints=[blueprint])
+
+ assert {pipe.code for pipe in loaded_pipes} == {"fom_analyze_item", "fom_summarize"}
+ assert DEP_ALIAS in library.dependency_libraries
+ aliased_pipe = library.pipe_library.get_required_pipe(pipe_code=f"{DEP_ALIAS}->fom_scoring.fom_compute_score")
+ assert aliased_pipe.code == "fom_compute_score"
+ assert fetch_mock.call_count == 1
+
+ installed_dir = global_methods_dir / "scoring"
+ assert (installed_dir / "scoring.mthds").is_file()
+ assert (installed_dir / PROVENANCE_FILENAME).is_file()
+ finally:
+ library_manager.teardown(library_id=library_id)
+
+ @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."""
+ 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")
+
+ library_manager = get_library_manager()
+ 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:
+ 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
+ fetch_mock.assert_not_called()
diff --git a/tests/integration/pipelex/methods/test_fetch_on_miss_git.py b/tests/integration/pipelex/methods/test_fetch_on_miss_git.py
new file mode 100644
index 000000000..1742420e0
--- /dev/null
+++ b/tests/integration/pipelex/methods/test_fetch_on_miss_git.py
@@ -0,0 +1,111 @@
+"""Integration tests for fetch-on-miss against a real local git repository.
+
+Builds a git repository in tmp_path with a library-repo layout, tags it, moves the default
+branch past the tag, and resolves an address-based reference through
+`resolve_address_based_method` — exercising the real clone machinery (with the clone URL
+redirected to a `file://` fixture), the tag pin, the install into the (redirected) global
+methods directory, and the provenance sidecar. No network.
+"""
+
+from __future__ import annotations
+
+import subprocess # ruff: ignore[suspicious-subprocess-import]
+from typing import TYPE_CHECKING
+
+import pytest
+
+from pipelex.cli.installed_methods import PROVENANCE_FILENAME
+from pipelex.methods.fetch_on_miss import resolve_address_based_method
+from pipelex.methods.fetching import FetchedMethodPackage, MethodProvenance, fetch_method_package
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from pytest_mock import MockerFixture
+
+ from pipelex.methods.method_ref import MethodRef
+
+FULL_ADDRESS = "github.com/pipelex-tests/fom-git-methods/scoring"
+
+MANIFEST_V1 = """\
+[package]
+name = "scoring"
+address = "github.com/pipelex-tests/fom-git-methods"
+version = "0.1.0"
+description = "A test package."
+main_pipe = "compute"
+
+[exports.scoring]
+pipes = ["compute"]
+"""
+
+
+def _git(repo_dir: Path, *args: str) -> str:
+ result = subprocess.run( # ruff: ignore[subprocess-without-shell-equals-true]
+ ["git", "-C", str(repo_dir), *args], # ruff: ignore[start-process-with-partial-path]
+ capture_output=True,
+ text=True,
+ check=True,
+ timeout=30,
+ )
+ return result.stdout.strip()
+
+
[email protected](name="seed_repo")
+def seed_repo_fixture(tmp_path: Path) -> tuple[Path, str, str]:
+ """A local git repo with one package, a v0.1.0 tag, and a later commit on the default branch.
+
+ Returns (repo_dir, tagged_commit_sha, head_commit_sha).
+ """
+ repo_dir = tmp_path / "seed-repo"
+ package_dir = repo_dir / "methods" / "scoring"
+ package_dir.mkdir(parents=True)
+ (package_dir / "METHODS.toml").write_text(MANIFEST_V1, encoding="utf-8")
+ (package_dir / "scoring.mthds").write_text("# v1 placeholder", encoding="utf-8")
+
+ _git(repo_dir, "init", "--initial-branch=main")
+ _git(repo_dir, "config", "user.email", "[email protected]")
+ _git(repo_dir, "config", "user.name", "Test")
+ _git(repo_dir, "add", "-A")
+ _git(repo_dir, "commit", "-m", "v1")
+ _git(repo_dir, "tag", "-a", "v0.1.0", "-m", "release v0.1.0")
+ tagged_sha = _git(repo_dir, "rev-parse", "HEAD")
+
+ (package_dir / "scoring.mthds").write_text("# v2 placeholder", encoding="utf-8")
+ _git(repo_dir, "add", "-A")
+ _git(repo_dir, "commit", "-m", "v2")
+ head_sha = _git(repo_dir, "rev-parse", "HEAD")
+
+ return repo_dir, tagged_sha, head_sha
+
+
+class TestFetchOnMissWithRealGit:
+ def test_miss_fetches_at_tag_installs_and_reuses(self, seed_repo: tuple[Path, str, str], tmp_path: Path, mocker: MockerFixture) -> None:
+ """A tag-pinned miss clones the tagged state, installs it with SHA provenance, and later resolves reuse the install."""
+ repo_dir, tagged_sha, head_sha = seed_repo
+ global_dir = tmp_path / "global-methods"
+ mocker.patch("pipelex.cli.installed_methods.GLOBAL_METHODS_DIR", global_dir)
+ 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=True)
+
+ def fetch_via_fixture(*, ref: MethodRef, dest_dir: Path, refuse_structures: bool = False) -> FetchedMethodPackage:
+ return fetch_method_package(ref=ref, dest_dir=dest_dir, clone_url=f"file://{repo_dir}", refuse_structures=refuse_structures)
+
+ fetch_spy = mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package", side_effect=fetch_via_fixture)
+
+ resolved = resolve_address_based_method(full_address=f"{FULL_ADDRESS}@v0.1.0")
+
+ assert resolved.path == (global_dir / "scoring").resolve()
+ assert (resolved.path / "scoring.mthds").read_text(encoding="utf-8") == "# v1 placeholder"
+ assert not (resolved.path / ".git").exists()
+ provenance = MethodProvenance.model_validate_json((resolved.path / PROVENANCE_FILENAME).read_text(encoding="utf-8"))
+ assert provenance.commit_sha == tagged_sha
+ assert provenance.commit_sha != head_sha
+ assert provenance.tag == "v0.1.0"
+ assert provenance.address == FULL_ADDRESS
+ assert fetch_spy.call_count == 1
+
+ # A later resolve — tagless this time — hits the install and never fetches again.
+ resolved_again = resolve_address_based_method(full_address=FULL_ADDRESS)
+ assert resolved_again.path == resolved.path
+ assert fetch_spy.call_count == 1
diff --git a/tests/integration/pipelex/pipeline/test_resolve_bundle.py b/tests/integration/pipelex/pipeline/test_resolve_bundle.py
index c0cb60c47..86660073c 100644
--- a/tests/integration/pipelex/pipeline/test_resolve_bundle.py
+++ b/tests/integration/pipelex/pipeline/test_resolve_bundle.py
@@ -139,8 +139,8 @@ class TestResolveCrateFromContents:
def test_address_dependency_is_rejected_without_filesystem_discovery(self, load_empty_library: Callable[[], str], mocker: MockerFixture) -> None:
load_empty_library()
discovery = mocker.patch(
- "pipelex.libraries.library_manager.find_method_by_full_address",
- side_effect=AssertionError("in-memory resolve must not discover installed methods"),
+ "pipelex.libraries.library_manager.resolve_address_based_method",
+ side_effect=AssertionError("in-memory resolve must not discover installed methods or fetch by address"),
)
with pytest.raises(ValidateBundleError, match="address-based dependency"):
diff --git a/tests/unit/pipelex/cli/test_install_method_package.py b/tests/unit/pipelex/cli/test_install_method_package.py
new file mode 100644
index 000000000..68e6e9902
--- /dev/null
+++ b/tests/unit/pipelex/cli/test_install_method_package.py
@@ -0,0 +1,184 @@
+"""Unit tests for install_method_package and the provenance-aware discovery around it."""
+
+from __future__ import annotations
+
+import shutil
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import pytest
+from mthds.package.discovery import MANIFEST_FILENAME
+
+from pipelex.cli.installed_methods import (
+ PROVENANCE_FILENAME,
+ discover_installed_methods,
+ find_method_by_full_address,
+ install_method_package,
+)
+from pipelex.methods.exceptions import MethodInstallError
+from pipelex.methods.fetching import MethodProvenance
+
+if TYPE_CHECKING:
+ from pytest_mock import MockerFixture
+
+FULL_ADDRESS = "github.com/pipelex-tests/fom-methods/scoring"
+OTHER_REPO_ADDRESS = "github.com/other-org/other-methods"
+
+MANIFEST = """\
+[package]
+name = "scoring"
+address = "github.com/pipelex-tests/fom-methods"
+version = "0.1.0"
+description = "A test package for install tests"
+main_pipe = "compute"
+
+[exports.scoring]
+pipes = ["compute"]
+"""
+
+PROVENANCE = MethodProvenance(
+ address="github.com/pipelex-tests/fom-methods/scoring",
+ tag="v0.1.0",
+ commit_sha="a" * 40,
+)
+
+
+def _make_package_dir(base: Path) -> Path:
+ """Build a source package directory with a manifest, a bundle, and a fake .git/."""
+ package_dir = base / "source-pkg"
+ package_dir.mkdir(parents=True)
+ (package_dir / MANIFEST_FILENAME).write_text(MANIFEST, encoding="utf-8")
+ (package_dir / "scoring.mthds").write_text("# placeholder", encoding="utf-8")
+ git_dir = package_dir / ".git"
+ git_dir.mkdir()
+ (git_dir / "HEAD").write_text("ref: refs/heads/main", encoding="utf-8")
+ return package_dir
+
+
+class TestInstallMethodPackage:
+ def test_install_copies_files_writes_provenance_and_strips_git(self, tmp_path: Path) -> None:
+ """A successful install lands the package files, the provenance sidecar, and no .git or staging leftovers."""
+ package_dir = _make_package_dir(tmp_path)
+ methods_dir = tmp_path / "methods"
+
+ installed = install_method_package(package_dir=package_dir, name="scoring", provenance=PROVENANCE, methods_dir=methods_dir)
+
+ assert installed.name == "scoring"
+ assert installed.path == (methods_dir / "scoring").resolve()
+ assert (installed.path / MANIFEST_FILENAME).is_file()
+ assert (installed.path / "scoring.mthds").read_text(encoding="utf-8") == "# placeholder"
+ assert not (installed.path / ".git").exists()
+ assert installed.provenance == PROVENANCE
+ assert MethodProvenance.model_validate_json((installed.path / PROVENANCE_FILENAME).read_text(encoding="utf-8")) == PROVENANCE
+ leftovers = [entry.name for entry in methods_dir.iterdir() if entry.name != "scoring"]
+ assert leftovers == []
+
+ def test_install_without_provenance_writes_no_sidecar(self, tmp_path: Path) -> None:
+ """Installing without provenance records nothing and discovery reports None."""
+ package_dir = _make_package_dir(tmp_path)
+ methods_dir = tmp_path / "methods"
+
+ installed = install_method_package(package_dir=package_dir, name="scoring", methods_dir=methods_dir)
+
+ assert installed.provenance is None
+ assert not (installed.path / PROVENANCE_FILENAME).exists()
+
+ def test_install_refuses_a_target_occupied_by_a_non_package(self, tmp_path: Path) -> None:
+ """An existing target directory that is not a method package is never overwritten."""
+ package_dir = _make_package_dir(tmp_path)
+ methods_dir = tmp_path / "methods"
+ (methods_dir / "scoring").mkdir(parents=True)
+
+ with pytest.raises(MethodInstallError, match="already occupied"):
+ install_method_package(package_dir=package_dir, name="scoring", full_address=FULL_ADDRESS, methods_dir=methods_dir)
+
+ def test_install_refuses_a_target_occupied_by_a_different_address(self, tmp_path: Path) -> None:
+ """Two packages sharing the bare name collide loudly, naming both addresses and the directory."""
+ package_dir = _make_package_dir(tmp_path)
+ methods_dir = tmp_path / "methods"
+ install_method_package(package_dir=package_dir, name="scoring", full_address=FULL_ADDRESS, methods_dir=methods_dir)
+
+ other_source = tmp_path / "other-pkg"
+ other_source.mkdir()
+ (other_source / MANIFEST_FILENAME).write_text(MANIFEST.replace("github.com/pipelex-tests/fom-methods", OTHER_REPO_ADDRESS), encoding="utf-8")
+ (other_source / "scoring.mthds").write_text("# other", encoding="utf-8")
+
+ with pytest.raises(MethodInstallError) as exc_info:
+ install_method_package(package_dir=other_source, name="scoring", full_address=f"{OTHER_REPO_ADDRESS}/scoring", methods_dir=methods_dir)
+
+ message = str(exc_info.value)
+ assert f"{OTHER_REPO_ADDRESS}/scoring" in message
+ assert FULL_ADDRESS in message
+ assert str(methods_dir / "scoring") in message
+ assert (methods_dir / "scoring" / "scoring.mthds").read_text(encoding="utf-8") == "# placeholder", "the occupant was not overwritten"
+
+ def test_install_over_a_matching_occupant_returns_theirs(self, tmp_path: Path) -> None:
+ """A target already holding the same package (by full address) is used as-is, never rewritten."""
+ package_dir = _make_package_dir(tmp_path)
+ methods_dir = tmp_path / "methods"
+ first = install_method_package(package_dir=package_dir, name="scoring", full_address=FULL_ADDRESS, methods_dir=methods_dir)
+ (package_dir / "second-attempt.marker").write_text("mine", encoding="utf-8")
+
+ second = install_method_package(package_dir=package_dir, name="scoring", full_address=FULL_ADDRESS, methods_dir=methods_dir)
+
+ assert second.path == first.path
+ assert not (second.path / "second-attempt.marker").exists(), "the occupant was kept, not overwritten"
+
+ def test_rename_race_lost_to_a_matching_occupant_returns_theirs(self, tmp_path: Path, mocker: MockerFixture) -> None:
+ """Losing the final-rename race to a concurrent install of the same package uses the winner's copy."""
+ package_dir = _make_package_dir(tmp_path)
+ methods_dir = tmp_path / "methods"
+ winner_source = tmp_path / "winner-pkg"
+ shutil.copytree(package_dir, winner_source)
+ (winner_source / "winner.marker").write_text("won", encoding="utf-8")
+
+ real_rename = Path.rename
+
+ def racing_rename(self_path: Path, target: str | Path) -> Path:
+ target_path = Path(target)
+ if target_path.name == "scoring" and not target_path.exists():
+ # The concurrent installer lands between our existence check and our rename.
+ shutil.copytree(winner_source, target_path)
+ return real_rename(self_path, target)
+
+ mocker.patch.object(Path, "rename", autospec=True, side_effect=racing_rename)
+
+ installed = install_method_package(package_dir=package_dir, name="scoring", full_address=FULL_ADDRESS, methods_dir=methods_dir)
+
+ assert installed.path == (methods_dir / "scoring").resolve()
+ assert (installed.path / "winner.marker").is_file(), "the winner's install was used"
+ leftovers = [entry.name for entry in methods_dir.iterdir() if entry.name != "scoring"]
+ assert leftovers == [], "the loser's staging directory was cleaned up"
+
+ @pytest.mark.parametrize("bad_name", ["../evil", ".hidden", ""])
+ def test_install_refuses_an_escaping_or_hidden_name(self, tmp_path: Path, bad_name: str) -> None:
+ """A name that escapes the methods directory or would be skipped by discovery is refused."""
+ package_dir = _make_package_dir(tmp_path)
+ methods_dir = tmp_path / "methods"
+
+ with pytest.raises(MethodInstallError):
+ install_method_package(package_dir=package_dir, name=bad_name, methods_dir=methods_dir)
+
+ def test_installed_method_is_found_by_full_address_case_insensitively(self, tmp_path: Path) -> None:
+ """The installed method resolves by its full address, mirroring GitHub's case semantics."""
+ package_dir = _make_package_dir(tmp_path)
+ methods_dir = tmp_path / "methods"
+ install_method_package(package_dir=package_dir, name="scoring", provenance=PROVENANCE, methods_dir=methods_dir)
+
+ methods = discover_installed_methods(include_global=False, include_project=False, extra_search_dirs=[methods_dir])
+ found = find_method_by_full_address("github.com/Pipelex-Tests/FOM-Methods/scoring", methods=methods)
+
+ assert found is not None
+ assert found.path == (methods_dir / "scoring").resolve()
+ assert found.provenance == PROVENANCE
+
+ def test_discovery_skips_dot_prefixed_directories(self, tmp_path: Path) -> None:
+ """A dot-prefixed directory (e.g. a leftover staging dir) is never discovered as a method."""
+ methods_dir = tmp_path / "methods"
+ stale_staging = methods_dir / ".scoring.staging"
+ stale_staging.mkdir(parents=True)
+ (stale_staging / MANIFEST_FILENAME).write_text(MANIFEST, encoding="utf-8")
+
+ methods = discover_installed_methods(include_global=False, include_project=False, extra_search_dirs=[methods_dir])
+
+ assert methods == []
diff --git a/tests/unit/pipelex/methods/test_fetch_on_miss.py b/tests/unit/pipelex/methods/test_fetch_on_miss.py
new file mode 100644
index 000000000..e3781a81a
--- /dev/null
+++ b/tests/unit/pipelex/methods/test_fetch_on_miss.py
@@ -0,0 +1,211 @@
+"""Unit tests for resolve_address_based_method: hit, miss-and-fetch, disabled, and failure diagnostics."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import pytest
+from mthds.package.discovery import MANIFEST_FILENAME
+from mthds.package.manifest.parser import parse_methods_toml
+
+from pipelex.cli.installed_methods import PROVENANCE_FILENAME, install_method_package
+from pipelex.methods.exceptions import (
+ MethodDependencyFetchError,
+ MethodFetchDisabledError,
+ MethodFetchError,
+ MethodInstallError,
+ MethodStructuresRefusedError,
+)
+from pipelex.methods.fetch_on_miss import resolve_address_based_method
+from pipelex.methods.fetching import FetchedMethodPackage, MethodProvenance
+from pipelex.methods.method_ref import parse_method_ref
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from pytest_mock import MockerFixture
+
+FULL_ADDRESS = "github.com/pipelex-tests/fom-methods/scoring"
+COMMIT_SHA = "b" * 40
+
+MANIFEST = """\
+[package]
+name = "scoring"
+address = "github.com/pipelex-tests/fom-methods"
+version = "0.1.0"
+description = "A test package for fetch-on-miss tests"
+main_pipe = "compute"
+
+[exports.scoring]
+pipes = ["compute"]
+"""
+
+
+def _make_package_dir(base: Path) -> Path:
+ package_dir = base / "fetched-pkg"
+ package_dir.mkdir(parents=True)
+ (package_dir / MANIFEST_FILENAME).write_text(MANIFEST, encoding="utf-8")
+ (package_dir / "scoring.mthds").write_text("# placeholder", encoding="utf-8")
+ return package_dir
+
+
+def _make_fetched(package_dir: Path, *, ref_str: str = f"{FULL_ADDRESS}@v0.1.0") -> FetchedMethodPackage:
+ ref = parse_method_ref(ref_str)
+ return FetchedMethodPackage(
+ ref=ref,
+ full_address=FULL_ADDRESS,
+ commit_sha=COMMIT_SHA,
+ clone_dir=package_dir.parent,
+ package_dir=package_dir,
+ manifest=parse_methods_toml(MANIFEST),
+ )
+
+
[email protected](name="isolated_methods_dirs")
+def isolated_methods_dirs_fixture(tmp_path: Path, mocker: MockerFixture) -> Path:
+ """Point the global and project methods directories at empty tmp locations."""
+ global_dir = tmp_path / "global-methods"
+ mocker.patch("pipelex.cli.installed_methods.GLOBAL_METHODS_DIR", global_dir)
+ mocker.patch("pipelex.cli.installed_methods.PROJECT_METHODS_DIR", tmp_path / "project-methods")
+ return global_dir
+
+
+class TestResolveAddressBasedMethod:
+ def test_installed_hit_returns_without_fetching(self, isolated_methods_dirs: Path, tmp_path: Path, mocker: MockerFixture) -> None:
+ """An installed method short-circuits the fetch entirely."""
+ package_dir = _make_package_dir(tmp_path)
+ install_method_package(package_dir=package_dir, name="scoring", methods_dir=isolated_methods_dirs)
+ fetch_mock = mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package")
+
+ resolved = resolve_address_based_method(full_address=FULL_ADDRESS)
+
+ assert resolved.path == (isolated_methods_dirs / "scoring").resolve()
+ fetch_mock.assert_not_called()
+
+ def test_tag_pinned_reference_uses_the_installed_copy(self, isolated_methods_dirs: Path, tmp_path: Path, mocker: MockerFixture) -> None:
+ """A `@tag` reference resolves against the installed store by tagless address (installed wins)."""
+ package_dir = _make_package_dir(tmp_path)
+ install_method_package(package_dir=package_dir, name="scoring", methods_dir=isolated_methods_dirs)
+ fetch_mock = mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package")
+
+ resolved = resolve_address_based_method(full_address=f"{FULL_ADDRESS}@v9.9.9")
+
+ assert resolved.path == (isolated_methods_dirs / "scoring").resolve()
+ fetch_mock.assert_not_called()
+
+ @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."""
+ 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")
+
+ with pytest.raises(MethodFetchDisabledError) as exc_info:
+ resolve_address_based_method(full_address=FULL_ADDRESS)
+
+ message = str(exc_info.value)
+ assert FULL_ADDRESS in message
+ assert "PIPELEX_METHODS_FETCH_ON_MISS" in message
+ assert "fetch_on_miss" in message
+ assert "install the method manually" in message
+ fetch_mock.assert_not_called()
+
+ @pytest.mark.usefixtures("isolated_methods_dirs")
+ def test_miss_with_failing_fetch_raises_the_failure_diagnostic(self, mocker: MockerFixture) -> None:
+ """A failed fetch surfaces as a diagnostic naming the address, with the fetch error as cause."""
+ mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=True)
+ fetch_error = MethodFetchError("Failed to fetch method 'github.com/...': clone timed out")
+ mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package", side_effect=fetch_error)
+
+ with pytest.raises(MethodDependencyFetchError) as exc_info:
+ resolve_address_based_method(full_address=f"{FULL_ADDRESS}@v0.1.0")
+
+ message = str(exc_info.value)
+ assert f"{FULL_ADDRESS}@v0.1.0" in message
+ assert "fetching it failed" in message
+ assert "clone timed out" in message
+ assert 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"):
+ 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:
+ """The full miss path: fetch, install with provenance, return — and the next resolve hits the install."""
+ mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=True)
+ package_dir = _make_package_dir(tmp_path)
+ fetched = _make_fetched(package_dir)
+ fetch_mock = mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package", return_value=fetched)
+
+ resolved = resolve_address_based_method(full_address=f"{FULL_ADDRESS}@v0.1.0")
+
+ assert resolved.path == (isolated_methods_dirs / "scoring").resolve()
+ assert (resolved.path / "scoring.mthds").read_text(encoding="utf-8") == "# placeholder"
+ assert resolved.provenance is not None
+ assert resolved.provenance.commit_sha == COMMIT_SHA
+ assert resolved.provenance.tag == "v0.1.0"
+ assert (resolved.path / PROVENANCE_FILENAME).is_file()
+ assert fetch_mock.call_count == 1
+
+ resolved_again = resolve_address_based_method(full_address=FULL_ADDRESS)
+ assert resolved_again.path == resolved.path
+ assert fetch_mock.call_count == 1
+
+ def test_bare_name_collision_across_addresses_is_a_loud_error(self, isolated_methods_dirs: Path, tmp_path: Path, mocker: MockerFixture) -> None:
+ """Two packages sharing the bare name never silently load or overwrite each other — the collision names both addresses."""
+ package_dir = _make_package_dir(tmp_path)
+ install_method_package(package_dir=package_dir, name="scoring", full_address=FULL_ADDRESS, methods_dir=isolated_methods_dirs)
+
+ other_address = "github.com/other-org/other-methods/scoring"
+ other_manifest = MANIFEST.replace("github.com/pipelex-tests/fom-methods", "github.com/other-org/other-methods")
+ other_dir = tmp_path / "other-pkg"
+ other_dir.mkdir()
+ (other_dir / MANIFEST_FILENAME).write_text(other_manifest, encoding="utf-8")
+ (other_dir / "scoring.mthds").write_text("# other", encoding="utf-8")
+ other_fetched = FetchedMethodPackage(
+ ref=parse_method_ref(other_address),
+ full_address=other_address,
+ commit_sha=COMMIT_SHA,
+ clone_dir=tmp_path,
+ package_dir=other_dir,
+ manifest=parse_methods_toml(other_manifest),
+ )
+ mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=True)
+ mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package", return_value=other_fetched)
+
+ with pytest.raises(MethodInstallError) as exc_info:
+ resolve_address_based_method(full_address=other_address)
+
+ message = str(exc_info.value)
+ assert other_address in message
+ assert FULL_ADDRESS in message
+ assert str(isolated_methods_dirs / "scoring") in message
+ installed_bundle = (isolated_methods_dirs / "scoring" / "scoring.mthds").read_text(encoding="utf-8")
+ assert installed_bundle == "# placeholder", "the first package's install was not overwritten"
+
+ @pytest.mark.usefixtures("isolated_methods_dirs")
+ def test_sandbox_hosted_fetch_refuses_structures_and_the_refusal_surfaces_unwrapped(self, mocker: MockerFixture) -> None:
+ """On a sandbox-hosted deployment the fetch hard-refuses structure-declaring packages, and the rule-naming error is not swallowed."""
+ mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=True)
+ mocker.patch("pipelex.methods.fetch_on_miss.is_pipe_func_sandbox_hosted", return_value=True)
+ refusal = MethodStructuresRefusedError("hosted execution accepts MTHDS concepts and sandboxed PipeFuncs, not in-process Python")
+ fetch_mock = mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package", side_effect=refusal)
+
+ with pytest.raises(MethodStructuresRefusedError) as exc_info:
+ resolve_address_based_method(full_address=FULL_ADDRESS)
+
+ assert exc_info.value is refusal
+ assert fetch_mock.call_args.kwargs["refuse_structures"] is True
+
+ @pytest.mark.usefixtures("isolated_methods_dirs")
+ def test_fetched_provenance_records_the_bare_address_fetch(self, tmp_path: Path, mocker: MockerFixture) -> None:
+ """A bare-address fetch records provenance with no tag."""
+ mocker.patch("pipelex.methods.fetch_on_miss.is_method_fetch_on_miss_enabled", return_value=True)
+ package_dir = _make_package_dir(tmp_path)
+ fetched = _make_fetched(package_dir, ref_str=FULL_ADDRESS)
+ mocker.patch("pipelex.methods.fetch_on_miss.fetch_method_package", return_value=fetched)
+
+ resolved = resolve_address_based_method(full_address=FULL_ADDRESS)
+
+ assert resolved.provenance == MethodProvenance(address=FULL_ADDRESS, tag=None, commit_sha=COMMIT_SHA)
diff --git a/tests/unit/pipelex/methods/test_fetching.py b/tests/unit/pipelex/methods/test_fetching.py
index 29d5861cd..9cb44e44d 100644
--- a/tests/unit/pipelex/methods/test_fetching.py
+++ b/tests/unit/pipelex/methods/test_fetching.py
@@ -8,7 +8,12 @@ from typing import TYPE_CHECKING
import pytest
from mthds.package.exceptions import VCSFetchError
-from pipelex.methods.exceptions import MethodFetchError, MethodPackageTooLargeError, MethodStructuresRefusedError
+from pipelex.methods.exceptions import (
+ MethodFetchError,
+ MethodPackageSymlinkError,
+ MethodPackageTooLargeError,
+ MethodStructuresRefusedError,
+)
from pipelex.methods.fetching import ensure_package_within_bounds, fetch_method_package
from pipelex.methods.method_ref import parse_method_ref
@@ -170,3 +175,39 @@ class TestFetchMethodPackage:
(package_dir / "core.mthds").write_text("# placeholder", encoding="utf-8")
ensure_package_within_bounds(package_dir=package_dir, package_address="github.com/acme/small")
+
+ def test_a_symlinked_file_is_refused(self, tmp_path: Path) -> None:
+ """A package carrying a file symlink is refused — a link's target would bypass the content scans."""
+ package_dir = tmp_path / "pkg"
+ package_dir.mkdir()
+ (package_dir / "core.mthds").write_text("# placeholder", encoding="utf-8")
+ outside_file = tmp_path / "outside.txt"
+ outside_file.write_text("host content", encoding="utf-8")
+ (package_dir / "sneaky.txt").symlink_to(outside_file)
+
+ with pytest.raises(MethodPackageSymlinkError, match=re.escape("sneaky.txt")):
+ ensure_package_within_bounds(package_dir=package_dir, package_address="github.com/acme/sneaky")
+
+ def test_a_symlinked_directory_is_refused(self, tmp_path: Path) -> None:
+ """A package carrying a directory symlink is refused too."""
+ package_dir = tmp_path / "pkg"
+ package_dir.mkdir()
+ (package_dir / "core.mthds").write_text("# placeholder", encoding="utf-8")
+ outside_dir = tmp_path / "outside-dir"
+ outside_dir.mkdir()
+ (outside_dir / "secret.txt").write_text("host content", encoding="utf-8")
+ (package_dir / "vendored").symlink_to(outside_dir, target_is_directory=True)
+
+ with pytest.raises(MethodPackageSymlinkError, match="vendored"):
+ ensure_package_within_bounds(package_dir=package_dir, package_address="github.com/acme/linked")
+
+ def test_a_symlinked_package_dir_is_refused(self, tmp_path: Path) -> None:
+ """A package directory that is itself a symlink is refused before any walk."""
+ real_dir = tmp_path / "real-pkg"
+ real_dir.mkdir()
+ (real_dir / "core.mthds").write_text("# placeholder", encoding="utf-8")
+ linked_dir = tmp_path / "linked-pkg"
+ linked_dir.symlink_to(real_dir, target_is_directory=True)
+
+ with pytest.raises(MethodPackageSymlinkError, match="is a symlink"):
+ ensure_package_within_bounds(package_dir=linked_dir, package_address="github.com/acme/aliased")
diff --git a/tests/unit/pipelex/test_method_fetch_on_miss_config.py b/tests/unit/pipelex/test_method_fetch_on_miss_config.py
new file mode 100644
index 000000000..25e46ce12
--- /dev/null
+++ b/tests/unit/pipelex/test_method_fetch_on_miss_config.py
@@ -0,0 +1,44 @@
+"""Unit tests for the fetch-on-miss switch: config default, config override, and env-var precedence."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import pytest
+
+from pipelex.config import METHODS_FETCH_ON_MISS_ENV_VAR, get_config, is_method_fetch_on_miss_enabled
+
+if TYPE_CHECKING:
+ from pytest_mock import MockerFixture
+
+
+class TestIsMethodFetchOnMissEnabled:
+ def test_default_is_enabled(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """With no env override, the shipped config default enables fetch-on-miss."""
+ monkeypatch.delenv(METHODS_FETCH_ON_MISS_ENV_VAR, raising=False)
+ assert is_method_fetch_on_miss_enabled() is True
+
+ def test_config_can_disable(self, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture) -> None:
+ """Setting interpreter.methods.fetch_on_miss = false disables fetching."""
+ monkeypatch.delenv(METHODS_FETCH_ON_MISS_ENV_VAR, raising=False)
+ mocker.patch.object(get_config().interpreter.methods, "fetch_on_miss", False)
+ assert is_method_fetch_on_miss_enabled() is False
+
+ @pytest.mark.parametrize("env_value", ["0", "false", "False", "no", "off"])
+ def test_env_var_disables(self, monkeypatch: pytest.MonkeyPatch, env_value: str) -> None:
+ """A falsy env value disables fetching regardless of the config."""
+ monkeypatch.setenv(METHODS_FETCH_ON_MISS_ENV_VAR, env_value)
+ assert is_method_fetch_on_miss_enabled() is False
+
+ @pytest.mark.parametrize("env_value", ["1", "true", "True", "yes", "on"])
+ def test_env_var_enables(self, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture, env_value: str) -> None:
+ """A truthy env value enables fetching even when the config disables it."""
+ monkeypatch.setenv(METHODS_FETCH_ON_MISS_ENV_VAR, env_value)
+ mocker.patch.object(get_config().interpreter.methods, "fetch_on_miss", False)
+ assert is_method_fetch_on_miss_enabled() is True
+
+ def test_unrecognized_env_value_falls_back_to_config(self, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture) -> None:
+ """An unparseable env value is ignored in favor of the config."""
+ monkeypatch.setenv(METHODS_FETCH_ON_MISS_ENV_VAR, "maybe")
+ mocker.patch.object(get_config().interpreter.methods, "fetch_on_miss", False)
+ assert is_method_fetch_on_miss_enabled() is False