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.

Add pipelex update command + deck staleness detection (#845)

Louis Choquel3e6d813b1864
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b29d8fa8e..b886aa142 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,10 +4,17 @@
### Added
+- **`pipelex update` command + model-deck staleness detection.** New top-level command refreshes the installed model deck (`~/.pipelex/inference/deck/`) to match the kit shipped with the running pipelex version. Tracks per-file SHA-256 hashes plus the kit version in a `.kit_manifest.json` written next to the deck files. Supports `--dry-run`, `--yes` (non-interactive), `--no-backup` (skip `.bak` files for locally-modified deck files), and `--local` (project-local deck instead of global).
+- **Boot-time deck staleness warn.** Every `pipelex` CLI invocation prints a one-line yellow advisory when the installed deck's recorded kit version is older than the running pipelex (or when no manifest exists yet). Cost is one file read + one string compare. Suppress with `PIPELEX_NO_DECK_NOTICE=1`. Skipped automatically for `pipelex login`, `init`, `doctor`, `update`, and `which`.
+- **`pipelex doctor` deck section.** Reports per-file deck status (`up_to_date`, `kit_added`, `kit_removed`, `clean_behind`, `locally_modified`) and offers `pipelex update` as an auto-fix under `--fix`.
+- **Manifest written by `pipelex init`.** Fresh installs land with a current `.kit_manifest.json` so future updates can detect drift cleanly.
- **`--dynamic-output-concept` / `-O` flag on `pipelex run`.** All three subcommands (`run bundle`, `run pipe`, `run method`) accept a concept ref (e.g. `document_qa.ReferenceCount`) used to resolve a pipe whose output is declared as `Dynamic`. Threaded through `_run_core.execute_run` to `PipelexRunner.execute_pipeline(dynamic_output_concept_ref=...)`. Until now, Dynamic-output pipes were only callable from the Python runner.
-
- **Line-length-safe wrapping in the structures generator.** `pipelex build structures` now wraps long descriptions so every emitted line stays under the 150-char ruff limit. Long class docstrings become a multi-line triple-quoted block; long Field descriptions become a parenthesized implicit-string-concatenation block (`description=("first chunk " "second chunk")`). Short descriptions still emit the compact single-line form. New unit tests in `tests/unit/pipelex/core/concepts/structure_generation/test_structure_generator_wrapping.py` cover both lengths and the combined long-everything case. Previously, descriptions above ~140 chars produced files that failed `ruff check` with E501.
+### Changed
+
+- **Numbered deck files (`N_*_deck.toml`) are pipelex-managed.** Each file now carries a header banner explaining that customizations belong in `x_custom_*.toml` (which pipelex never tracks or overwrites). Local edits to numbered files are preserved with a timestamped `.bak.<UTC-timestamp>` backup on `pipelex update` but will not survive future updates.
+
### Fixed
- **`PipeLLM` Dynamic-output detection compared the wrong fields.** `pipe_llm.py` checked `self.output.concept.code == "native.Dynamic"`, but `concept.code` is the bare code (`"Dynamic"`) not the qualified ref. The check never matched, so when a caller passed `dynamic_output_concept_ref` for a `Dynamic`-output pipe, the resolver branch was skipped silently: the output structure stayed `DynamicContent` (an empty `StuffContent` subclass), the LLM produced JSON shaped like the requested concept, and the result deserialized to `{}`. Detection now uses `concept.code == NativeConceptCode.DYNAMIC and concept.domain_code == SpecialDomain.NATIVE`.
diff --git a/docs/configuration/config-technical/inference-backend-config.md b/docs/configuration/config-technical/inference-backend-config.md
index 5afd37d4f..19ee809a8 100644
--- a/docs/configuration/config-technical/inference-backend-config.md
+++ b/docs/configuration/config-technical/inference-backend-config.md
@@ -83,6 +83,11 @@ All inference backend configurations are stored in the `.pipelex/inference/` dir
Deck files are loaded in order by their numeric prefix (`1_`, `2_`, `3_`), with custom/override files (`x_` prefix) loaded last.
+!!! tip "Numbered files are pipelex-managed; overrides go in `x_custom_*.toml`"
+ The numbered deck files (`1_llm_deck.toml`...`4_search_deck.toml`) are refreshed by `pipelex update` when a new release ships an updated deck. Local edits to those files are preserved with a timestamped `.bak` backup but will not survive future updates.
+
+ To customize aliases, presets, or default choices without conflict, edit (or create) any file in this directory whose name starts with `x_custom_` — Pipelex never tracks or overwrites those. See [`pipelex update`](../../tools/cli/update.md) for the full workflow.
+
## Pipelex Gateway (Optional & Free)
Pipelex Gateway is a unified inference backend that provides access to all major AI providers through a single API key. This is the **recommended approach for getting started quickly** with Pipelex and **unlocking its full power**—with many models already available and new ones being added constantly. Using Pipelex Gateway is **completely optional**.
diff --git a/docs/features/cli.md b/docs/features/cli.md
index 954ff7c48..8ba0b360c 100644
--- a/docs/features/cli.md
+++ b/docs/features/cli.md
@@ -17,6 +17,7 @@ The `pipelex` CLI is the primary tool for working with Pipelex methods. It cover
|---------|-------------|
| **`pipelex login`** | Authenticate with Pipelex Gateway via the browser and save your API key |
| **`pipelex init`** | Initialize configuration, backends, credentials, routing, and telemetry |
+| **`pipelex update`** | Refresh the model deck to match the installed pipelex version |
| **`pipelex doctor`** | Check configuration health and suggest fixes |
| **`pipelex build`** | AI-powered method generation from natural language requirements |
| **`pipelex validate`** | Check pipeline syntax, structure, and run dry-run validation |
diff --git a/docs/tools/cli/index.md b/docs/tools/cli/index.md
index 9990416e1..61be4e858 100644
--- a/docs/tools/cli/index.md
+++ b/docs/tools/cli/index.md
@@ -14,6 +14,7 @@ The Pipelex CLI is organized into several command groups:
| Command | Description |
|---------|-------------|
| [**init**](init.md) | Initialize Pipelex configuration |
+| [**update**](update.md) | Refresh the model deck to match the installed pipelex version |
| [**validate**](validate.md) | Validate configuration and pipelines |
| [**show**](show.md) | Inspect configuration, pipes, and AI models |
| [**run**](run.md) | Execute pipelines |
diff --git a/docs/tools/cli/update.md b/docs/tools/cli/update.md
new file mode 100644
index 000000000..35144a5b7
--- /dev/null
+++ b/docs/tools/cli/update.md
@@ -0,0 +1,99 @@
+---
+description: "Refresh the installed Pipelex model deck — keep `1_llm_deck.toml` and friends in sync with the kit shipped by your installed pipelex version, while preserving your `x_custom_*.toml` overrides."
+---
+
+# Update Command
+
+Refresh the installed model deck so it matches the kit shipped with your current `pipelex` version.
+
+```bash
+pipelex update [OPTIONS]
+pipelex update --local [OPTIONS]
+```
+
+When a new `pipelex` release ships changes to the model deck — new models, new aliases, retired entries — your previously installed deck under `~/.pipelex/inference/deck/` will fall behind. `pipelex update` brings it up to date without nuking your overrides.
+
+## When to run it
+
+Pipelex prints a one-line yellow advisory at the top of every CLI invocation when it detects that the installed deck is older than the running package, or when no deck manifest is present yet:
+
+```text
+⚠ Pipelex model deck may be out of date — run pipelex update to refresh
+```
+
+Run `pipelex update` to clear the warning. To silence it permanently for a session or environment:
+
+```bash
+export PIPELEX_NO_DECK_NOTICE=1
+```
+
+## What it does
+
+Pipelex tracks the deck install state in a small JSON manifest at `~/.pipelex/inference/deck/.kit_manifest.json` (or `.pipelex/inference/deck/.kit_manifest.json` for project-local installs). The manifest stores the kit version that produced the install and a SHA-256 of each managed deck file at install time.
+
+On `update`, Pipelex compares three states — what the kit ships, what is on disk, what the manifest recorded — and produces a per-file plan:
+
+| Status | Meaning | Action |
+|---|---|---|
+| `up-to-date` | Installed file matches the kit | none |
+| `new` | Kit ships a new managed file not yet installed | install from kit |
+| `behind` | Installed file unchanged from manifest, kit has newer content | overwrite from kit |
+| `locally modified` | Installed file was edited after install — kit version differs | back up + overwrite |
+| `removed upstream` | Kit no longer ships this file | back up + remove |
+
+Locally-modified files are preserved as `<file>.bak.<UTC-timestamp>` before the kit version is written in their place. Removed files get the same backup treatment before deletion. After the run, Pipelex writes a fresh manifest stamped with the new kit version.
+
+## Managed files vs. user overrides
+
+Pipelex draws a sharp line between deck files it owns and deck files you own.
+
+- **Managed (pipelex-owned)** — `1_llm_deck.toml`, `2_img_gen_deck.toml`, `3_extract_deck.toml`, `4_search_deck.toml`. These are refreshed by `pipelex update`. Local edits are preserved with a `.bak.<timestamp>` backup but will not survive future updates.
+- **User overrides** — any file in the deck directory whose name starts with `x_custom_` (e.g. `x_custom_llm_deck.toml`, `x_custom_extract_deck.toml`). Pipelex never tracks, hashes, copies, or removes these. Add new ones whenever you need to override aliases, presets, or default choices for a backend.
+
+The deck loader merges all `*.toml` files under the deck directory in alphabetical order via deep-merge, so your `x_custom_*.toml` always wins over the numbered defaults.
+
+## Options
+
+| Flag | Description |
+|---|---|
+| `--local` / `-l` | Update the project-local `.pipelex/` deck instead of the global `~/.pipelex/` |
+| `--yes` / `-y` | Apply updates non-interactively (skip the confirmation prompt) |
+| `--dry-run` | Show the plan without modifying any file |
+| `--no-backup` | Do not create `.bak` files for locally-modified deck files |
+
+## Examples
+
+```bash
+# Preview what would change
+pipelex update --dry-run
+
+# Interactive update of the global deck
+pipelex update
+
+# Non-interactive update — useful for CI or scripts
+pipelex update --yes
+
+# Project-local deck only
+pipelex update --local --yes
+
+# Skip the .bak backups (advanced — your edits will be lost permanently)
+pipelex update --yes --no-backup
+```
+
+## Migration: existing installs without a manifest
+
+If your deck was installed before the `update` command existed, there will be no `.kit_manifest.json` next to your deck files. The first `pipelex update` run reports each managed file as `locally modified` (no provenance proof) and asks before overwriting. Two ways to migrate cleanly:
+
+1. **Trust the kit** — run `pipelex update --yes` to take the upstream version of every managed file. Anything you want to keep can be moved into an `x_custom_*.toml` afterwards using the `.bak.<timestamp>` files as a reference.
+2. **Move overrides first** — copy any custom aliases, presets, or defaults from your numbered files into a new `x_custom_<area>_deck.toml`, then run `pipelex update --yes`. Your customizations will live in the file Pipelex never touches.
+
+After either path, subsequent updates land cleanly without prompting on the unchanged files.
+
+## Diagnostics
+
+`pipelex doctor` includes a **Model Deck** section that reports the same per-file status as `update`. Run `pipelex doctor --fix` to be offered an interactive `pipelex update` as part of the standard fix flow.
+
+## Related
+
+- [Init Commands](init.md) — first-time setup that materializes the deck and its manifest
+- [LLM Providers & Models Configuration](../../configuration/config-technical/inference-backend-config.md) — what the deck files actually configure
diff --git a/mkdocs.yml b/mkdocs.yml
index 55b6e4af8..71b405b54 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -259,6 +259,7 @@ plugins:
Reference:
- tools/cli/index.md: "CLI Reference Overview"
- tools/cli/init.md: "CLI Init"
+ - tools/cli/update.md: "CLI Update"
- tools/cli/validate.md: "CLI Validate"
- tools/cli/run.md: "CLI Run"
- tools/cli/show.md: "CLI Show"
@@ -435,6 +436,7 @@ nav:
- CLI Reference:
- Overview: tools/cli/index.md
- Init: tools/cli/init.md
+ - Update: tools/cli/update.md
- Validate: tools/cli/validate.md
- Run: tools/cli/run.md
- Show: tools/cli/show.md
diff --git a/pipelex/cli/_cli.py b/pipelex/cli/_cli.py
index de73d1247..e95169d2c 100644
--- a/pipelex/cli/_cli.py
+++ b/pipelex/cli/_cli.py
@@ -14,8 +14,10 @@ from pipelex.cli.commands.init.ui.types import InitFocus
from pipelex.cli.commands.login.command import login_cmd
from pipelex.cli.commands.run.app import run_app
from pipelex.cli.commands.show_cmd import show_app
+from pipelex.cli.commands.update_cmd import update_cmd
from pipelex.cli.commands.validate.app import validate_app
from pipelex.cli.commands.which_cmd import which_cmd
+from pipelex.cli.deck_notice import warn_if_deck_stale
from pipelex.cli.readiness import check_readiness
from pipelex.hub import get_console
from pipelex.tools.misc.package_utils import get_package_version
@@ -27,7 +29,7 @@ class PipelexCLI(TyperGroup):
@override
def list_commands(self, ctx: Context) -> list[str]:
# List the commands in the proper order because natural ordering doesn't work between Typer groups and commands
- return ["login", "init", "doctor", "build", "validate", "run", "graph", "show", "which"]
+ return ["login", "init", "doctor", "update", "build", "validate", "run", "graph", "show", "which"]
@override
def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
@@ -115,13 +117,16 @@ def app_callback(
░██ v[cyan]{package_version}[/cyan]
"""
)
- # Skip checks if no command is being run (e.g., just --help) or if running init/doctor command
- if ctx.invoked_subcommand is None or ctx.invoked_subcommand in {"login", "init", "doctor"}:
+ # Skip checks if no command is being run (e.g., just --help) or if running setup/diagnostic commands
+ if ctx.invoked_subcommand is None or ctx.invoked_subcommand in {"login", "init", "doctor", "update", "which"}:
return
# Check system readiness (dependencies and venv for dev installs)
check_readiness()
+ # Warn if the model deck has fallen behind the installed pipelex version
+ warn_if_deck_stale()
+
@app.command(name="login", help="Log in to Pipelex Gateway via the browser and save your API key")
def login_command() -> None:
@@ -170,6 +175,24 @@ def doctor_command(
doctor_cmd(fix=fix)
[email protected](name="update", help="Update the model deck to match the installed pipelex version")
+def update_command(
+ local: Annotated[
+ bool,
+ typer.Option(
+ "--local",
+ "-l",
+ help="Force the project-local .pipelex/ deck. Default targets the resolved deck dir (project if .pipelex/ exists, else global)",
+ ),
+ ] = False,
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Apply updates without the interactive confirmation prompt")] = False,
+ dry_run: Annotated[bool, typer.Option("--dry-run", help="Show the planned actions without modifying any file")] = False,
+ no_backup: Annotated[bool, typer.Option("--no-backup", help="Skip .bak files when overwriting locally-modified deck files")] = False,
+) -> None:
+ """Refresh the installed deck to match the kit shipped with the running pipelex version."""
+ update_cmd(local=local, yes=yes, dry_run=dry_run, no_backup=no_backup)
+
+
app.add_typer(
build_app, name="build", help="Generate AI methods from natural language requirements: pipelines in .mthds format and python code to run them"
)
diff --git a/pipelex/cli/agent_cli/commands/init_cmd.py b/pipelex/cli/agent_cli/commands/init_cmd.py
index b77d68a67..7f6b98b1e 100644
--- a/pipelex/cli/agent_cli/commands/init_cmd.py
+++ b/pipelex/cli/agent_cli/commands/init_cmd.py
@@ -15,6 +15,7 @@ from pipelex.cli.commands.init.config_files import init_config
from pipelex.cli.commands.init.ui.backends_ui import get_backend_options_from_toml
from pipelex.cogt.model_backends.backend import PipelexBackend
from pipelex.cogt.model_routing.routing_profile import PipelexRoutingProfile
+from pipelex.cogt.models.deck_manifest import compute_kit_manifest, write_manifest
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.system.configuration.config_loader import config_manager
from pipelex.system.pipelex_service.pipelex_service_agreement import (
@@ -116,6 +117,8 @@ def _copy_inference_templates(target_dir: Path) -> None:
if deck_file.endswith(".toml"):
shutil.copy2(template_deck_dir / deck_file, target_deck_dir / deck_file)
+ write_manifest(target_deck_dir, compute_kit_manifest())
+
# Copy routing_profiles.toml
template_routing_path = template_inference_dir / "routing_profiles.toml"
if template_routing_path.exists():
diff --git a/pipelex/cli/commands/doctor_cmd.py b/pipelex/cli/commands/doctor_cmd.py
index 2908015db..6bc8e8289 100644
--- a/pipelex/cli/commands/doctor_cmd.py
+++ b/pipelex/cli/commands/doctor_cmd.py
@@ -19,10 +19,12 @@ from pipelex.base_exceptions import PipelexConfigError
from pipelex.cli.commands.init.command import init_cmd
from pipelex.cli.commands.init.config_files import init_config
from pipelex.cli.commands.init.ui.types import InitFocus
+from pipelex.cli.commands.update_cmd import update_cmd
from pipelex.cogt.exceptions import InferenceBackendLibraryError
from pipelex.cogt.model_backends.backend_credentials import BackendCredentialsErrorMsgFactory
from pipelex.cogt.model_backends.backend_library import BackendCredentialsReport, InferenceBackendLibrary
from pipelex.cogt.model_backends.gateway_config import GatewayConfig
+from pipelex.cogt.models.deck_manifest import DeckFileStatus, DeckSyncReport, compute_deck_sync_report, status_rich_label
from pipelex.cogt.models.model_manager import ModelManager
from pipelex.config import get_config
from pipelex.core.validation import report_validation_error
@@ -409,6 +411,9 @@ def display_health_report(
models_healthy: bool,
models_message: str,
backend_file_reports: dict[str, BackendFileReport],
+ deck_healthy: bool,
+ deck_message: str,
+ deck_report: DeckSyncReport,
config_location: ConfigLocationInfo,
fix_mode: bool = False,
) -> None:
@@ -426,10 +431,13 @@ def display_health_report(
models_healthy: Whether models check passed
models_message: Message about models status
backend_file_reports: Dict of backend file validation reports
+ deck_healthy: Whether the model deck is in sync with the kit shipped by this pipelex version
+ deck_message: Summary message about deck sync status
+ deck_report: Per-file sync status report (used to render the per-file detail when not healthy)
config_location: Resolved configuration location information
fix_mode: Whether we're in interactive fix mode (--fix flag)
"""
- all_healthy = config_healthy and telemetry_healthy and backends_healthy and models_healthy
+ all_healthy = config_healthy and telemetry_healthy and backends_healthy and models_healthy and deck_healthy
# Overall status panel
if all_healthy:
@@ -530,6 +538,20 @@ def display_health_report(
console.print(f" [dim]{error_lines[0][:100]}[/dim]")
console.print()
+ # Model Deck section
+ console.print("[bold]Model Deck[/bold]")
+ if deck_healthy:
+ console.print(f" [green]✓[/green] {deck_message}")
+ else:
+ console.print(f" [yellow]⚠[/yellow] {deck_message}")
+ # Per-file detail when there are pending actions
+ actionable_statuses = {name: status for name, status in deck_report.files.items() if status != DeckFileStatus.UP_TO_DATE}
+ if actionable_statuses:
+ for filename in sorted(actionable_statuses):
+ status = actionable_statuses[filename]
+ console.print(f" [dim]{filename}[/dim] — {status_rich_label(status)}")
+ console.print()
+
# Recommended actions
if not all_healthy:
# Check what can be auto-fixed
@@ -555,12 +577,14 @@ def display_health_report(
has_custom_backend_issues = any(not report.has_kit_template for report in invalid_backends.values())
# Determine if we have any recommendations to show
+ has_deck_drift = not deck_healthy
has_recommendations = (
can_auto_fix_config
or can_auto_fix_telemetry
or has_telemetry_validation_error
or (not backends_healthy and backend_credential_reports)
or has_backend_file_issues
+ or has_deck_drift
)
if has_recommendations:
@@ -576,6 +600,9 @@ def display_health_report(
console.print(f" • Fix validation errors in [cyan]{config_location.config_dir}/telemetry.toml[/cyan]")
console.print(" or run [cyan]pipelex init telemetry[/cyan] to regenerate")
+ if has_deck_drift:
+ console.print(" • Run [cyan]pipelex update[/cyan] to refresh the model deck from the current kit")
+
# Backend file issues
if can_auto_fix_backends:
if fix_mode:
@@ -631,6 +658,39 @@ def display_health_report(
console.print()
+def check_deck_sync(config_dir: Path | None = None) -> tuple[bool, DeckSyncReport, str]:
+ """Check whether the installed model deck is in sync with the kit shipped by this pipelex version.
+
+ Args:
+ config_dir: Explicit config directory override. If None, uses layered resolution.
+
+ Returns:
+ Tuple of (is_healthy, sync_report, summary_message)
+ """
+ effective_config_dir = config_dir or config_manager.pipelex_config_dir
+ deck_dir = Path(effective_config_dir) / "inference" / "deck"
+
+ if not deck_dir.exists():
+ # Match the existing doctor pattern: surface as healthy when the area isn't initialized,
+ # since the missing-init advisory is handled by the config_files / backends checks above.
+ return True, DeckSyncReport(kit_version="", installed_kit_version=None, manifest_present=False, files={}), "Deck directory not present"
+
+ report = compute_deck_sync_report(deck_dir)
+ if report.is_clean():
+ return True, report, f"Deck is up to date with pipelex {report.kit_version}"
+
+ actionable = [name for name, status in report.files.items() if status.needs_action]
+ if not report.manifest_present:
+ return False, report, "Deck manifest missing — run `pipelex update` to materialize a baseline"
+ if report.installed_kit_version != report.kit_version:
+ return (
+ False,
+ report,
+ f"Deck installed for pipelex {report.installed_kit_version}, current is {report.kit_version} ({len(actionable)} file(s) need action)",
+ )
+ return False, report, f"{len(actionable)} deck file(s) need action"
+
+
def check_models(config_dir: Path | None = None) -> tuple[bool, str, dict[str, BackendFileReport]]:
"""Check if models are valid, including backend file validation.
@@ -748,6 +808,7 @@ def do_doctor_cmd(
telemetry_healthy, telemetry_message = check_telemetry_config()
backends_healthy, backend_credential_reports, backends_message = check_backend_credentials()
models_healthy, models_message, backend_file_reports = check_models()
+ deck_healthy, deck_report, deck_message = check_deck_sync()
# Display report
display_health_report(
@@ -762,11 +823,14 @@ def do_doctor_cmd(
models_healthy=models_healthy,
models_message=models_message,
backend_file_reports=backend_file_reports,
+ deck_healthy=deck_healthy,
+ deck_message=deck_message,
+ deck_report=deck_report,
config_location=config_location,
fix_mode=fix,
)
- all_healthy = config_healthy and telemetry_healthy and backends_healthy and models_healthy
+ all_healthy = config_healthy and telemetry_healthy and backends_healthy and models_healthy and deck_healthy
# Exit code: 0 if healthy, 1 if issues found
if all_healthy:
@@ -789,7 +853,9 @@ def do_doctor_cmd(
fixable_backends = [(name, report) for name, report in invalid_backends if report.has_kit_template]
can_fix_backends = len(fixable_backends) > 0
- has_auto_fixable_issues = can_fix_config or can_fix_telemetry or can_fix_backends
+ can_fix_deck = not deck_healthy and deck_report.kit_version != ""
+
+ has_auto_fixable_issues = can_fix_config or can_fix_telemetry or can_fix_backends or can_fix_deck
# Determine what requires manual fixes (excludes auto-fixable issues)
has_config_validation_error = not config_healthy and config_missing_count == 0
@@ -833,6 +899,17 @@ def do_doctor_cmd(
console.print(f"[red]Failed to configure telemetry: {exc!s}[/red]")
console.print()
+ # Fix outdated model deck
+ if can_fix_deck:
+ if Confirm.ask("[bold]Update the model deck now?[/bold]", default=True):
+ try:
+ console.print()
+ update_cmd(yes=True)
+ console.print("[green]✓[/green] Model deck updated")
+ except Exception as exc:
+ console.print(f"[red]Failed to update deck: {exc!s}[/red]")
+ console.print()
+
# Fix outdated backend files
if can_fix_backends and fixable_backends:
console.print("[bold]Outdated Backend Configuration Files[/bold]")
diff --git a/pipelex/cli/commands/init/command.py b/pipelex/cli/commands/init/command.py
index a8b29045e..69abb9867 100644
--- a/pipelex/cli/commands/init/command.py
+++ b/pipelex/cli/commands/init/command.py
@@ -27,6 +27,7 @@ from pipelex.cli.commands.init.ui.gateway_ui import (
from pipelex.cli.commands.init.ui.general_ui import build_initialization_panel
from pipelex.cli.commands.init.ui.types import InitFocus
from pipelex.cogt.model_backends.backend import PipelexBackend
+from pipelex.cogt.models.deck_manifest import compute_kit_manifest, write_manifest
from pipelex.hub import get_console
from pipelex.kit.paths import get_kit_configs_dir
from pipelex.system.configuration.config_loader import config_manager
@@ -254,6 +255,10 @@ def execute_initialization(
dst_path = target_deck_dir / deck_file
shutil.copy2(src_path, dst_path)
+ # Stamp the deck manifest so future updates can detect drift and
+ # `pipelex update` knows the exact kit version this install came from.
+ write_manifest(target_deck_dir, compute_kit_manifest())
+
# Reset routing_profiles.toml
template_routing_path = template_inference_dir / "routing_profiles.toml"
target_routing_path = target_inference_dir / "routing_profiles.toml"
diff --git a/pipelex/cli/commands/update_cmd.py b/pipelex/cli/commands/update_cmd.py
new file mode 100644
index 000000000..f60fd45fc
--- /dev/null
+++ b/pipelex/cli/commands/update_cmd.py
@@ -0,0 +1,186 @@
+"""``pipelex update`` — bring the installed model deck up to date with the kit-shipped templates.
+
+Numbered deck files are managed by pipelex. ``x_custom_*.toml`` files are user-owned and never
+touched. Locally-modified numbered files are backed up to ``<file>.bak.<UTC-timestamp>`` before
+being overwritten, unless ``--no-backup`` is passed.
+"""
+
+from __future__ import annotations
+
+import shutil
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+
+from rich.markup import escape
+from rich.panel import Panel
+from rich.prompt import Confirm
+from rich.table import Table
+
+from pipelex.cogt.models.deck_manifest import (
+ DeckFileStatus,
+ DeckSyncReport,
+ compute_deck_sync_report,
+ compute_kit_manifest,
+ kit_deck_dir,
+ status_rich_label,
+ suggest_x_custom_filename,
+ write_manifest,
+)
+from pipelex.hub import get_console
+from pipelex.system.configuration.config_loader import config_manager
+
+
+def update_cmd(
+ local: bool = False,
+ yes: bool = False,
+ dry_run: bool = False,
+ no_backup: bool = False,
+) -> None:
+ """Apply pending model-deck updates from the running pipelex's kit.
+
+ Args:
+ local: Update the project-local ``.pipelex/`` instead of the resolved layered config dir.
+ yes: Skip the interactive confirmation.
+ dry_run: Print the planned actions without modifying any file.
+ no_backup: Do not create ``.bak`` files for locally-modified numbered deck files.
+ """
+ console = get_console()
+ deck_dir = _resolve_deck_dir(local=local)
+ if not deck_dir.exists():
+ console.print()
+ console.print(f"[red]✗[/red] No deck directory found at [cyan]{escape(str(deck_dir))}[/cyan].\nRun [cyan]pipelex init[/cyan] first.")
+ console.print()
+ sys.exit(1)
+
+ report = compute_deck_sync_report(deck_dir)
+ _print_status_table(report, deck_dir)
+
+ if report.is_clean():
+ console.print(_summary_panel("Model deck is up to date.", style="green"))
+ console.print()
+ return
+
+ if not report.manifest_present:
+ # Migration: surface what we found so the user can review before we materialize a baseline.
+ console.print(
+ "[dim]No deck manifest found — this looks like an existing install. Running [cyan]pipelex update[/cyan] "
+ "will install the latest deck content and write a baseline manifest.[/dim]"
+ )
+ console.print()
+
+ if dry_run:
+ console.print("[dim]Dry run — no changes written.[/dim]")
+ console.print()
+ return
+
+ if not yes and not Confirm.ask("[bold]Apply these updates?[/bold]", default=True):
+ console.print("[yellow]Update cancelled.[/yellow]")
+ console.print()
+ return
+
+ actions_applied = _apply_updates(deck_dir=deck_dir, report=report, no_backup=no_backup)
+ write_manifest(deck_dir, compute_kit_manifest())
+
+ console.print()
+ console.print(_summary_panel(f"Model deck updated ({actions_applied} file change(s) applied).", style="green"))
+ console.print()
+
+
+def _resolve_deck_dir(local: bool) -> Path:
+ """Pick the deck directory to operate on, mirroring the ``--local`` semantics of ``pipelex init``."""
+ if local:
+ project_root = config_manager.project_root
+ base = project_root / ".pipelex" if project_root is not None else Path.cwd() / ".pipelex"
+ else:
+ base = config_manager.pipelex_config_dir
+ return base / "inference" / "deck"
+
+
+def _print_status_table(report: DeckSyncReport, deck_dir: Path) -> None:
+ """Render the per-file sync status as a Rich table."""
+ table = Table(title="Pipelex Model Deck — Update Plan", show_lines=False)
+ table.add_column("File", style="cyan", no_wrap=True)
+ table.add_column("Status", style="bold")
+ table.add_column("Action")
+
+ for filename in sorted(report.files):
+ status = report.files[filename]
+ table.add_row(filename, status_rich_label(status), _action_description(status))
+
+ get_console().print()
+ get_console().print(f"Deck directory: [cyan]{escape(str(deck_dir))}[/cyan]")
+ installed_version_label = report.installed_kit_version or "(none)"
+ get_console().print(
+ f"Installed kit version: [cyan]{escape(installed_version_label)}[/cyan] Kit version: [cyan]{escape(report.kit_version)}[/cyan]"
+ )
+ get_console().print()
+ get_console().print(table)
+ get_console().print()
+
+
+def _action_description(status: DeckFileStatus) -> str:
+ match status:
+ case DeckFileStatus.UP_TO_DATE:
+ return "—"
+ case DeckFileStatus.KIT_ADDED:
+ return "install from kit"
+ case DeckFileStatus.KIT_REMOVED:
+ return "back up + remove"
+ case DeckFileStatus.CLEAN_BEHIND:
+ return "overwrite from kit"
+ case DeckFileStatus.LOCALLY_MODIFIED:
+ return "back up + overwrite from kit"
+
+
+def _apply_updates(deck_dir: Path, report: DeckSyncReport, no_backup: bool) -> int:
+ """Apply the per-file actions described by ``report``. Returns the count of files changed."""
+ kit_dir = kit_deck_dir()
+ timestamp = datetime.now(tz=timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ actions_applied = 0
+
+ for filename in sorted(report.files):
+ status = report.files[filename]
+ installed_path = deck_dir / filename
+ kit_path = kit_dir / filename
+
+ match status:
+ case DeckFileStatus.UP_TO_DATE:
+ continue
+ case DeckFileStatus.KIT_ADDED:
+ deck_dir.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(kit_path, installed_path)
+ get_console().print(f" [green]+[/green] installed [cyan]{escape(filename)}[/cyan]")
+ actions_applied += 1
+ case DeckFileStatus.CLEAN_BEHIND:
+ shutil.copy2(kit_path, installed_path)
+ get_console().print(f" [yellow]↑[/yellow] updated [cyan]{escape(filename)}[/cyan]")
+ actions_applied += 1
+ case DeckFileStatus.LOCALLY_MODIFIED:
+ backup_note = ""
+ if not no_backup:
+ backup_path = installed_path.with_name(f"{filename}.bak.{timestamp}")
+ shutil.copy2(installed_path, backup_path)
+ backup_note = f" (backed up to [dim]{escape(backup_path.name)}[/dim])"
+ shutil.copy2(kit_path, installed_path)
+ get_console().print(f" [red]↑[/red] overwrote local edits in [cyan]{escape(filename)}[/cyan]{backup_note}")
+ suggested_override = suggest_x_custom_filename(filename)
+ get_console().print(
+ f" [dim]Tip: move custom aliases/presets into [cyan]{escape(suggested_override)}[/cyan] "
+ "so future updates leave them in place.[/dim]"
+ )
+ actions_applied += 1
+ case DeckFileStatus.KIT_REMOVED:
+ backup_path = installed_path.with_name(f"{filename}.bak.{timestamp}")
+ shutil.copy2(installed_path, backup_path)
+ installed_path.unlink()
+ get_console().print(
+ f" [yellow]-[/yellow] removed [cyan]{escape(filename)}[/cyan] (backed up to [dim]{escape(backup_path.name)}[/dim])"
+ )
+ actions_applied += 1
+
+ return actions_applied
+
+
+def _summary_panel(message: str, *, style: str) -> Panel:
+ return Panel(message, border_style=style, padding=(1, 2))
diff --git a/pipelex/cli/deck_notice.py b/pipelex/cli/deck_notice.py
new file mode 100644
index 000000000..00fdf1eb6
--- /dev/null
+++ b/pipelex/cli/deck_notice.py
@@ -0,0 +1,38 @@
+"""One-line boot-time warn shown when the installed model deck has fallen behind the kit.
+
+The warn is intentionally cheap (no hashing) so it can fire on every CLI invocation without slowing
+the boot path. ``pipelex update`` and ``pipelex doctor`` perform the deeper hash-based diff.
+"""
+
+from __future__ import annotations
+
+import os
+
+from pipelex.cogt.models.deck_manifest import is_deck_stale_fast
+from pipelex.hub import get_console
+from pipelex.system.configuration.config_loader import config_manager
+
+DECK_NOTICE_SUPPRESS_ENV_VAR = "PIPELEX_NO_DECK_NOTICE"
+
+
+def warn_if_deck_stale() -> None:
+ """Print a one-line yellow advisory when the installed deck appears to be out of date.
+
+ Suppressed entirely when ``PIPELEX_NO_DECK_NOTICE`` is set in the environment.
+ Silent when no deck dir exists yet (init_check elsewhere already prompts the user to run init).
+ """
+ if os.environ.get(DECK_NOTICE_SUPPRESS_ENV_VAR):
+ return
+
+ deck_dir = config_manager.pipelex_config_dir / "inference" / "deck"
+ if not deck_dir.exists():
+ return
+
+ if not is_deck_stale_fast(deck_dir):
+ return
+
+ get_console().print(
+ "[yellow]⚠[/yellow] [dim]Pipelex model deck may be out of date — run [cyan]pipelex update[/cyan] to refresh "
+ f"(set [cyan]{DECK_NOTICE_SUPPRESS_ENV_VAR}=1[/cyan] to silence)[/dim]",
+ highlight=False,
+ )
diff --git a/pipelex/cogt/models/deck_manifest.py b/pipelex/cogt/models/deck_manifest.py
new file mode 100644
index 000000000..468bf20f8
--- /dev/null
+++ b/pipelex/cogt/models/deck_manifest.py
@@ -0,0 +1,278 @@
+"""Model deck manifest: detect when an installed deck has drifted from the kit-shipped templates.
+
+The manifest pins, for one specific deck install, the kit version that produced it and the SHA-256 of
+each managed deck file at install/update time. It enables three independent signals:
+
+- Manifest's ``kit_version`` vs the running ``pipelex`` version → behind upstream.
+- Manifest's per-file hash vs the installed file's actual hash → user has locally edited a numbered file.
+- Kit content vs installed content → upstream changed.
+
+Numbered deck files (``1_llm_deck.toml``...``4_search_deck.toml``) are pipelex-managed.
+``x_custom_*.toml`` files are user-owned and never tracked.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from pipelex.kit.paths import get_kit_configs_dir
+from pipelex.tools.misc.file_utils import path_exists
+from pipelex.tools.misc.package_utils import get_package_version
+from pipelex.types import StrEnum
+
+MANIFEST_FILENAME = ".kit_manifest.json"
+
+
+class DeckFileStatus(StrEnum):
+ """Per-file sync status between the installed deck and the kit-shipped templates."""
+
+ UP_TO_DATE = "up_to_date"
+ KIT_ADDED = "kit_added"
+ KIT_REMOVED = "kit_removed"
+ CLEAN_BEHIND = "clean_behind"
+ LOCALLY_MODIFIED = "locally_modified"
+
+ @property
+ def needs_action(self) -> bool:
+ """True when an `update` run would touch this file."""
+ match self:
+ case DeckFileStatus.UP_TO_DATE:
+ return False
+ case DeckFileStatus.KIT_ADDED | DeckFileStatus.KIT_REMOVED | DeckFileStatus.CLEAN_BEHIND | DeckFileStatus.LOCALLY_MODIFIED:
+ return True
+
+
+class DeckManifest(BaseModel):
+ """Persisted record of the kit version and per-file hashes captured at install/update time."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ kit_version: str
+ files: dict[str, str] = Field(default_factory=dict)
+
+
+class DeckSyncReport(BaseModel):
+ """Result of comparing an installed deck dir to the currently shipping kit."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ kit_version: str
+ installed_kit_version: str | None
+ manifest_present: bool
+ files: dict[str, DeckFileStatus] = Field(default_factory=dict)
+
+ def is_clean(self) -> bool:
+ """True when no file needs any action and the manifest is in sync with the kit version."""
+ if not self.manifest_present:
+ return False
+ if self.installed_kit_version != self.kit_version:
+ return False
+ return all(status == DeckFileStatus.UP_TO_DATE for status in self.files.values())
+
+ def files_with_status(self, status: DeckFileStatus) -> list[str]:
+ return sorted(name for name, file_status in self.files.items() if file_status == status)
+
+
+def compute_sha256(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def compute_file_sha256(path: Path) -> str:
+ return compute_sha256(path.read_bytes())
+
+
+def kit_deck_dir() -> Path:
+ """Return the kit's shipped deck directory as a real filesystem path.
+
+ Mirrors the conversion done in ``pipelex/cli/commands/init/command.py:228`` so we read the same
+ files that ``pipelex init`` copies.
+ """
+ return Path(str(get_kit_configs_dir())) / "inference" / "deck"
+
+
+def _is_managed_deck_filename(filename: str) -> bool:
+ """True for files that pipelex manages (numbered ``*_deck.toml``).
+
+ Excludes any ``x_custom_*.toml`` override (the user-owned escape hatch) and non-TOML files
+ (e.g. an accidental ``.DS_Store``). The ``x_custom_`` prefix is the agreed-upon namespace for
+ user overrides — pipelex never tracks or overwrites those.
+ """
+ if not filename.endswith(".toml"):
+ return False
+ return not filename.startswith("x_custom_")
+
+
+def list_managed_kit_files() -> dict[str, str]:
+ """Hash every managed deck file shipped in the current pipelex wheel."""
+ kit_dir = kit_deck_dir()
+ return {
+ entry.name: compute_file_sha256(entry) for entry in sorted(kit_dir.iterdir()) if entry.is_file() and _is_managed_deck_filename(entry.name)
+ }
+
+
+def list_managed_installed_files(deck_dir: Path) -> dict[str, str]:
+ """Hash every managed deck file present in the user's installed deck dir."""
+ if not deck_dir.is_dir():
+ return {}
+ return {
+ entry.name: compute_file_sha256(entry) for entry in sorted(deck_dir.iterdir()) if entry.is_file() and _is_managed_deck_filename(entry.name)
+ }
+
+
+def compute_kit_manifest() -> DeckManifest:
+ """Build the manifest that should be written after a fresh install or successful update."""
+ return DeckManifest(kit_version=get_package_version(), files=list_managed_kit_files())
+
+
+def manifest_path(deck_dir: Path) -> Path:
+ return deck_dir / MANIFEST_FILENAME
+
+
+def read_manifest(deck_dir: Path) -> DeckManifest | None:
+ """Return the persisted manifest, or ``None`` when absent or unreadable.
+
+ A corrupt manifest is treated as missing — the caller will warn the user and offer to rebuild it.
+ """
+ target = manifest_path(deck_dir)
+ if not path_exists(str(target)):
+ return None
+ try:
+ payload = json.loads(target.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ try:
+ return DeckManifest.model_validate(payload)
+ except ValueError:
+ return None
+
+
+def write_manifest(deck_dir: Path, manifest: DeckManifest) -> None:
+ """Persist the manifest, creating the deck directory if needed."""
+ deck_dir.mkdir(parents=True, exist_ok=True)
+ payload = manifest.model_dump()
+ target = manifest_path(deck_dir)
+ target.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+
+
+def is_deck_stale_fast(deck_dir: Path) -> bool:
+ """Boot-path check: one file read, one string compare. No hashing.
+
+ Returns True (stale) when the manifest is missing or its ``kit_version`` is strictly older than
+ the running ``pipelex``. Two cases must NOT trigger the warn:
+
+ - exact match (incl. when one side carries a pre-release/build suffix and the other doesn't);
+ - downgrade (manifest newer than the installed package) — the user has presumably pinned
+ pipelex deliberately, and updating the deck backwards is rarely what they want.
+ """
+ manifest = read_manifest(deck_dir)
+ if manifest is None:
+ return True
+ return _is_manifest_older(manifest.kit_version, get_package_version())
+
+
+def _is_manifest_older(manifest_version: str, current_version: str) -> bool:
+ """True iff the manifest's recorded core version is strictly older than the installed package.
+
+ Compares semver cores (``X.Y.Z``) ignoring pre-release/build metadata so that an editable build
+ versioned ``0.25.0+localdev`` does not appear stale against a stable ``0.25.0`` manifest. Falls
+ back to literal string inequality on parse failure (rare, conservative).
+ """
+ manifest_parts = _try_parse_version(manifest_version)
+ current_parts = _try_parse_version(current_version)
+ if manifest_parts is None or current_parts is None:
+ return manifest_version != current_version
+ return manifest_parts < current_parts
+
+
+def _try_parse_version(version: str) -> tuple[int, ...] | None:
+ """Parse a SemVer-ish string's core into a comparable tuple. Returns ``None`` on any failure.
+
+ Strips both the pre-release suffix (``-rc1``) and the build metadata suffix (``+localbuild``).
+ """
+ core = version.split("+", 1)[0].split("-", 1)[0]
+ pieces = core.split(".")
+ try:
+ return tuple(int(piece) for piece in pieces)
+ except ValueError:
+ return None
+
+
+def status_rich_label(status: DeckFileStatus) -> str:
+ """Human-friendly Rich-markup label used by both the doctor report and the update plan table."""
+ match status:
+ case DeckFileStatus.UP_TO_DATE:
+ return "[green]up-to-date[/green]"
+ case DeckFileStatus.KIT_ADDED:
+ return "[green]new[/green]"
+ case DeckFileStatus.KIT_REMOVED:
+ return "[yellow]removed upstream[/yellow]"
+ case DeckFileStatus.CLEAN_BEHIND:
+ return "[yellow]behind[/yellow]"
+ case DeckFileStatus.LOCALLY_MODIFIED:
+ return "[red]locally modified[/red]"
+
+
+def suggest_x_custom_filename(numbered_filename: str) -> str:
+ """Suggest the right ``x_custom_*.toml`` companion for a numbered deck file.
+
+ Example: ``2_img_gen_deck.toml`` → ``x_custom_img_gen_deck.toml``. The convention is to drop
+ the leading ``N_`` prefix and prepend ``x_custom_``.
+ """
+ head, _, tail = numbered_filename.partition("_")
+ if not tail or not head.isdigit():
+ return "x_custom_*.toml"
+ return f"x_custom_{tail}"
+
+
+def compute_deck_sync_report(deck_dir: Path) -> DeckSyncReport:
+ """Full per-file diff between the installed deck and the running pipelex's kit.
+
+ This walks every managed file in either side and assigns it a ``DeckFileStatus``. Cost is one
+ SHA-256 per file — only call from ``pipelex update`` and ``pipelex doctor``, never on the boot path.
+ """
+ kit_files = list_managed_kit_files()
+ installed_files = list_managed_installed_files(deck_dir)
+ manifest = read_manifest(deck_dir)
+ manifest_files: dict[str, str] = manifest.files if manifest is not None else {}
+
+ all_filenames = set(kit_files) | set(installed_files)
+ file_statuses: dict[str, DeckFileStatus] = {}
+ for filename in all_filenames:
+ kit_hash = kit_files.get(filename)
+ installed_hash = installed_files.get(filename)
+ manifest_hash = manifest_files.get(filename)
+
+ if kit_hash is not None and installed_hash is None:
+ file_statuses[filename] = DeckFileStatus.KIT_ADDED
+ continue
+ if kit_hash is None and installed_hash is not None:
+ file_statuses[filename] = DeckFileStatus.KIT_REMOVED
+ continue
+
+ # Both present from here on.
+ if manifest_hash is not None:
+ if manifest_hash != installed_hash:
+ file_statuses[filename] = DeckFileStatus.LOCALLY_MODIFIED
+ elif manifest_hash != kit_hash:
+ file_statuses[filename] = DeckFileStatus.CLEAN_BEHIND
+ else:
+ file_statuses[filename] = DeckFileStatus.UP_TO_DATE
+ continue
+
+ # No manifest entry — treat untouched files as up-to-date, divergent ones as locally modified
+ # (we have no provenance proof, so we err on preserving user content via the backup path).
+ if installed_hash == kit_hash:
+ file_statuses[filename] = DeckFileStatus.UP_TO_DATE
+ else:
+ file_statuses[filename] = DeckFileStatus.LOCALLY_MODIFIED
+
+ return DeckSyncReport(
+ kit_version=get_package_version(),
+ installed_kit_version=manifest.kit_version if manifest is not None else None,
+ manifest_present=manifest is not None,
+ files=file_statuses,
+ )
diff --git a/pipelex/kit/configs/inference/deck/1_llm_deck.toml b/pipelex/kit/configs/inference/deck/1_llm_deck.toml
index c11102368..e0603a460 100644
--- a/pipelex/kit/configs/inference/deck/1_llm_deck.toml
+++ b/pipelex/kit/configs/inference/deck/1_llm_deck.toml
@@ -4,6 +4,11 @@
#
# This file defines model defaults, aliases, and presets for LLMs
#
+# Managed by `pipelex update`. To customize without conflict, edit
+# x_custom_llm_deck.toml in this directory — pipelex never tracks or
+# overwrites x_custom_* files. Local edits to this file are backed up
+# to <file>.bak.<timestamp> on update but will not survive future runs.
+#
# Model Reference Syntax:
# - Preset: $preset_name or preset:preset_name
# - Alias: @alias_name or alias:alias_name
diff --git a/pipelex/kit/configs/inference/deck/2_img_gen_deck.toml b/pipelex/kit/configs/inference/deck/2_img_gen_deck.toml
index 33907ae21..a2c73f486 100644
--- a/pipelex/kit/configs/inference/deck/2_img_gen_deck.toml
+++ b/pipelex/kit/configs/inference/deck/2_img_gen_deck.toml
@@ -4,6 +4,11 @@
#
# This file defines model aliases and presets for image generation models
#
+# Managed by `pipelex update`. To customize without conflict, create an
+# x_custom_*.toml file in this directory — pipelex never tracks or
+# overwrites x_custom_* files. Local edits to this file are backed up
+# to <file>.bak.<timestamp> on update but will not survive future runs.
+#
# Model Reference Syntax:
# - Preset: $preset_name or preset:preset_name
# - Alias: @alias_name or alias:alias_name
diff --git a/pipelex/kit/configs/inference/deck/3_extract_deck.toml b/pipelex/kit/configs/inference/deck/3_extract_deck.toml
index eaf3065be..c67d393f1 100644
--- a/pipelex/kit/configs/inference/deck/3_extract_deck.toml
+++ b/pipelex/kit/configs/inference/deck/3_extract_deck.toml
@@ -5,6 +5,11 @@
# This file defines model aliases and presets for Document extraction models, including
# extraction of text and images from documents and OCR and text extraction from images.
#
+# Managed by `pipelex update`. To customize without conflict, edit
+# x_custom_extract_deck.toml in this directory — pipelex never tracks or
+# overwrites x_custom_* files. Local edits to this file are backed up
+# to <file>.bak.<timestamp> on update but will not survive future runs.
+#
# Model Reference Syntax:
# - Preset: $preset_name or preset:preset_name
# - Alias: @alias_name or alias:alias_name
diff --git a/pipelex/kit/configs/inference/deck/4_search_deck.toml b/pipelex/kit/configs/inference/deck/4_search_deck.toml
index 6cc955d7e..230a1ec67 100644
--- a/pipelex/kit/configs/inference/deck/4_search_deck.toml
+++ b/pipelex/kit/configs/inference/deck/4_search_deck.toml
@@ -5,6 +5,11 @@
# This file defines model aliases and presets for Search models, including
# web search providers like Linkup.
#
+# Managed by `pipelex update`. To customize without conflict, create an
+# x_custom_*.toml file in this directory — pipelex never tracks or
+# overwrites x_custom_* files. Local edits to this file are backed up
+# to <file>.bak.<timestamp> on update but will not survive future runs.
+#
# Model Reference Syntax:
# - Preset: $preset_name or preset:preset_name
# - Alias: @alias_name or alias:alias_name
diff --git a/pipelex/system/configuration/config_loader.py b/pipelex/system/configuration/config_loader.py
index f0303b504..87f89748d 100644
--- a/pipelex/system/configuration/config_loader.py
+++ b/pipelex/system/configuration/config_loader.py
@@ -159,6 +159,12 @@ class ConfigLoader:
copy_directory_structure(src_dir=config_template_dir, dst_dir=global_dir)
+ # Stamp the deck manifest so the boot-time staleness check has a baseline.
+ # Imported lazily to avoid a circular import — config_loader is loaded very early.
+ from pipelex.cogt.models.deck_manifest import compute_kit_manifest, write_manifest # noqa: PLC0415
+
+ write_manifest(global_dir / "inference" / "deck", compute_kit_manifest())
+
def load_config(self) -> dict[str, Any]:
"""Load and merge configurations from pipelex and local config files.
diff --git a/tests/unit/pipelex/cli/test_doctor_cmd.py b/tests/unit/pipelex/cli/test_doctor_cmd.py
index 2efe985d6..ce66f587d 100644
--- a/tests/unit/pipelex/cli/test_doctor_cmd.py
+++ b/tests/unit/pipelex/cli/test_doctor_cmd.py
@@ -16,6 +16,7 @@ from pipelex.cli.commands.doctor_cmd import (
check_telemetry_config,
do_doctor_cmd,
)
+from pipelex.cogt.models.deck_manifest import DeckSyncReport
from pipelex.system.configuration.config_loader import ConfigLoader
from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME
@@ -50,6 +51,14 @@ class TestDoctorLayeredResolution:
"pipelex.cli.commands.doctor_cmd.check_models",
return_value=(True, "OK", {}),
)
+ mock_check_deck = mocker.patch(
+ "pipelex.cli.commands.doctor_cmd.check_deck_sync",
+ return_value=(
+ True,
+ DeckSyncReport(kit_version="1.0.0", installed_kit_version="1.0.0", manifest_present=True, files={}),
+ "OK",
+ ),
+ )
mocker.patch("pipelex.cli.commands.doctor_cmd.display_health_report")
with pytest.raises(SystemExit) as exc_info:
@@ -61,6 +70,7 @@ class TestDoctorLayeredResolution:
mock_check_telemetry.assert_called_once_with()
mock_check_backends.assert_called_once_with()
mock_check_models.assert_called_once_with()
+ mock_check_deck.assert_called_once_with()
def test_telemetry_check_falls_back_to_global(self, mocker: MockerFixture, tmp_path: Path) -> None:
"""When project .pipelex/ exists but has no telemetry.toml, fall back to global ~/.pipelex/."""
diff --git a/tests/unit/pipelex/cli/test_update_cmd.py b/tests/unit/pipelex/cli/test_update_cmd.py
new file mode 100644
index 000000000..7767a8cb2
--- /dev/null
+++ b/tests/unit/pipelex/cli/test_update_cmd.py
@@ -0,0 +1,189 @@
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+import pytest
+
+from pipelex.cli.commands import update_cmd as update_cmd_module
+from pipelex.cli.commands.update_cmd import update_cmd
+from pipelex.cogt.models import deck_manifest
+from pipelex.cogt.models.deck_manifest import (
+ MANIFEST_FILENAME,
+ DeckManifest,
+ is_deck_stale_fast,
+ write_manifest,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from pytest_mock import MockerFixture
+
+
+class TestUpdateCmd:
+ @staticmethod
+ def _seed_kit(mocker: MockerFixture, kit_dir: Path, files: dict[str, str]) -> None:
+ kit_dir.mkdir(parents=True, exist_ok=True)
+ for filename, content in files.items():
+ (kit_dir / filename).write_text(content, encoding="utf-8")
+ mocker.patch.object(deck_manifest, "kit_deck_dir", return_value=kit_dir)
+ mocker.patch.object(update_cmd_module, "kit_deck_dir", return_value=kit_dir)
+
+ @staticmethod
+ def _seed_installed(deck_dir: Path, files: dict[str, str]) -> None:
+ deck_dir.mkdir(parents=True, exist_ok=True)
+ for filename, content in files.items():
+ (deck_dir / filename).write_text(content, encoding="utf-8")
+
+ @staticmethod
+ def _patch_resolve_deck_dir(mocker: MockerFixture, deck_dir: Path) -> None:
+ mocker.patch.object(update_cmd_module, "_resolve_deck_dir", return_value=deck_dir)
+
+ @staticmethod
+ def _patch_version(mocker: MockerFixture, version: str) -> None:
+ mocker.patch.object(deck_manifest, "get_package_version", return_value=version)
+
+ @pytest.fixture
+ def kit_and_deck(self, mocker: MockerFixture, tmp_path: Path) -> tuple[Path, Path]:
+ """Materialize a kit with one numbered file and an installed deck dir mirroring it."""
+ kit_dir = tmp_path / "kit"
+ deck_dir = tmp_path / "deck"
+ contents = {"1_llm_deck.toml": "v1-content"}
+ self._seed_kit(mocker, kit_dir, contents)
+ self._seed_installed(deck_dir, contents)
+ self._patch_resolve_deck_dir(mocker, deck_dir)
+ self._patch_version(mocker, "1.0.0")
+ return kit_dir, deck_dir
+
+ def test_dry_run_makes_no_changes(self, mocker: MockerFixture, kit_and_deck: tuple[Path, Path]) -> None:
+ kit_dir, deck_dir = kit_and_deck
+ # Kit has moved on, but the install hasn't yet.
+ (kit_dir / "1_llm_deck.toml").write_text("v2-content", encoding="utf-8")
+ write_manifest(
+ deck_dir, DeckManifest(kit_version="1.0.0", files={"1_llm_deck.toml": deck_manifest.compute_file_sha256(deck_dir / "1_llm_deck.toml")})
+ )
+ self._patch_version(mocker, "1.1.0")
+
+ update_cmd(dry_run=True)
+
+ assert (deck_dir / "1_llm_deck.toml").read_text(encoding="utf-8") == "v1-content"
+
+ def test_clean_state_writes_baseline_manifest(self, kit_and_deck: tuple[Path, Path]) -> None:
+ _, deck_dir = kit_and_deck
+ # No manifest yet — migration baseline should be written.
+ assert not (deck_dir / MANIFEST_FILENAME).exists()
+
+ update_cmd(yes=True)
+
+ assert (deck_dir / MANIFEST_FILENAME).is_file()
+ assert is_deck_stale_fast(deck_dir) is False
+
+ def test_clean_behind_overwrites_without_backup(self, mocker: MockerFixture, kit_and_deck: tuple[Path, Path]) -> None:
+ kit_dir, deck_dir = kit_and_deck
+ write_manifest(
+ deck_dir, DeckManifest(kit_version="1.0.0", files={"1_llm_deck.toml": deck_manifest.compute_file_sha256(deck_dir / "1_llm_deck.toml")})
+ )
+ (kit_dir / "1_llm_deck.toml").write_text("v2-content", encoding="utf-8")
+ self._patch_version(mocker, "1.1.0")
+
+ update_cmd(yes=True)
+
+ assert (deck_dir / "1_llm_deck.toml").read_text(encoding="utf-8") == "v2-content"
+ assert not list(deck_dir.glob("*.bak.*"))
+ assert is_deck_stale_fast(deck_dir) is False
+
+ def test_locally_modified_creates_backup_and_overwrites(self, mocker: MockerFixture, kit_and_deck: tuple[Path, Path]) -> None:
+ kit_dir, deck_dir = kit_and_deck
+ write_manifest(
+ deck_dir, DeckManifest(kit_version="1.0.0", files={"1_llm_deck.toml": deck_manifest.compute_file_sha256(deck_dir / "1_llm_deck.toml")})
+ )
+ (deck_dir / "1_llm_deck.toml").write_text("user-edits", encoding="utf-8")
+ (kit_dir / "1_llm_deck.toml").write_text("v2-content", encoding="utf-8")
+ self._patch_version(mocker, "1.1.0")
+
+ update_cmd(yes=True)
+
+ backups = sorted(deck_dir.glob("1_llm_deck.toml.bak.*"))
+ assert len(backups) == 1
+ assert backups[0].read_text(encoding="utf-8") == "user-edits"
+ assert re.match(r"1_llm_deck\.toml\.bak\.\d{8}T\d{6}Z", backups[0].name) is not None
+ assert (deck_dir / "1_llm_deck.toml").read_text(encoding="utf-8") == "v2-content"
+
+ def test_no_backup_flag_skips_backup(self, mocker: MockerFixture, kit_and_deck: tuple[Path, Path]) -> None:
+ kit_dir, deck_dir = kit_and_deck
+ write_manifest(
+ deck_dir, DeckManifest(kit_version="1.0.0", files={"1_llm_deck.toml": deck_manifest.compute_file_sha256(deck_dir / "1_llm_deck.toml")})
+ )
+ (deck_dir / "1_llm_deck.toml").write_text("user-edits", encoding="utf-8")
+ (kit_dir / "1_llm_deck.toml").write_text("v2-content", encoding="utf-8")
+ self._patch_version(mocker, "1.1.0")
+
+ update_cmd(yes=True, no_backup=True)
+
+ assert not list(deck_dir.glob("*.bak.*"))
+ assert (deck_dir / "1_llm_deck.toml").read_text(encoding="utf-8") == "v2-content"
+
+ def test_kit_added_installs_new_file(self, mocker: MockerFixture, kit_and_deck: tuple[Path, Path]) -> None:
+ kit_dir, deck_dir = kit_and_deck
+ write_manifest(
+ deck_dir, DeckManifest(kit_version="1.0.0", files={"1_llm_deck.toml": deck_manifest.compute_file_sha256(deck_dir / "1_llm_deck.toml")})
+ )
+ (kit_dir / "5_new_deck.toml").write_text("brand-new", encoding="utf-8")
+ self._patch_version(mocker, "1.1.0")
+
+ update_cmd(yes=True)
+
+ assert (deck_dir / "5_new_deck.toml").read_text(encoding="utf-8") == "brand-new"
+
+ def test_kit_removed_backs_up_then_deletes(self, mocker: MockerFixture, kit_and_deck: tuple[Path, Path]) -> None:
+ _, deck_dir = kit_and_deck
+ (deck_dir / "9_retired_deck.toml").write_text("retired-content", encoding="utf-8")
+ write_manifest(
+ deck_dir,
+ DeckManifest(
+ kit_version="1.0.0",
+ files={
+ "1_llm_deck.toml": deck_manifest.compute_file_sha256(deck_dir / "1_llm_deck.toml"),
+ "9_retired_deck.toml": deck_manifest.compute_file_sha256(deck_dir / "9_retired_deck.toml"),
+ },
+ ),
+ )
+ self._patch_version(mocker, "1.1.0")
+
+ update_cmd(yes=True)
+
+ assert not (deck_dir / "9_retired_deck.toml").exists()
+ backups = sorted(deck_dir.glob("9_retired_deck.toml.bak.*"))
+ assert len(backups) == 1
+ assert backups[0].read_text(encoding="utf-8") == "retired-content"
+
+ def test_x_custom_files_are_left_alone(self, mocker: MockerFixture, kit_and_deck: tuple[Path, Path]) -> None:
+ kit_dir, deck_dir = kit_and_deck
+ (deck_dir / "x_custom_llm_deck.toml").write_text("user-overrides", encoding="utf-8")
+ (kit_dir / "1_llm_deck.toml").write_text("v2-content", encoding="utf-8")
+ self._patch_version(mocker, "1.1.0")
+
+ update_cmd(yes=True)
+
+ assert (deck_dir / "x_custom_llm_deck.toml").read_text(encoding="utf-8") == "user-overrides"
+
+ def test_yes_flag_skips_confirm(self, mocker: MockerFixture, kit_and_deck: tuple[Path, Path]) -> None:
+ kit_dir, deck_dir = kit_and_deck
+ write_manifest(
+ deck_dir, DeckManifest(kit_version="1.0.0", files={"1_llm_deck.toml": deck_manifest.compute_file_sha256(deck_dir / "1_llm_deck.toml")})
+ )
+ (kit_dir / "1_llm_deck.toml").write_text("v2-content", encoding="utf-8")
+ self._patch_version(mocker, "1.1.0")
+
+ confirm_spy = mocker.patch.object(update_cmd_module.Confirm, "ask")
+ update_cmd(yes=True)
+
+ confirm_spy.assert_not_called()
+
+ def test_missing_deck_dir_exits_with_error(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ absent = tmp_path / "nope"
+ self._patch_resolve_deck_dir(mocker, absent)
+ with pytest.raises(SystemExit) as exit_info:
+ update_cmd(yes=True)
+ assert exit_info.value.code == 1
diff --git a/tests/unit/pipelex/cogt/models/test_deck_manifest.py b/tests/unit/pipelex/cogt/models/test_deck_manifest.py
new file mode 100644
index 000000000..e7355ca12
--- /dev/null
+++ b/tests/unit/pipelex/cogt/models/test_deck_manifest.py
@@ -0,0 +1,269 @@
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING
+
+import pytest
+
+from pipelex.cogt.models import deck_manifest
+from pipelex.cogt.models.deck_manifest import (
+ MANIFEST_FILENAME,
+ DeckFileStatus,
+ DeckManifest,
+ compute_deck_sync_report,
+ compute_file_sha256,
+ compute_kit_manifest,
+ is_deck_stale_fast,
+ list_managed_installed_files,
+ list_managed_kit_files,
+ manifest_path,
+ read_manifest,
+ suggest_x_custom_filename,
+ write_manifest,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from pytest_mock import MockerFixture
+
+
+class TestDeckManifest:
+ @staticmethod
+ def _seed_kit(mocker: MockerFixture, kit_dir: Path, files: dict[str, str]) -> None:
+ kit_dir.mkdir(parents=True, exist_ok=True)
+ for filename, content in files.items():
+ (kit_dir / filename).write_text(content, encoding="utf-8")
+ mocker.patch.object(deck_manifest, "kit_deck_dir", return_value=kit_dir)
+
+ @staticmethod
+ def _seed_installed(deck_dir: Path, files: dict[str, str]) -> None:
+ deck_dir.mkdir(parents=True, exist_ok=True)
+ for filename, content in files.items():
+ (deck_dir / filename).write_text(content, encoding="utf-8")
+
+ def test_manifest_round_trip(self, tmp_path: Path) -> None:
+ manifest = DeckManifest(kit_version="1.2.3", files={"1_llm_deck.toml": "hash-a", "2_img_gen_deck.toml": "hash-b"})
+ deck_dir = tmp_path / "deck"
+ write_manifest(deck_dir, manifest)
+ assert manifest_path(deck_dir).is_file()
+
+ reloaded = read_manifest(deck_dir)
+ assert reloaded == manifest
+
+ def test_read_manifest_missing(self, tmp_path: Path) -> None:
+ assert read_manifest(tmp_path / "absent") is None
+
+ def test_read_manifest_corrupt(self, tmp_path: Path) -> None:
+ deck_dir = tmp_path / "deck"
+ deck_dir.mkdir()
+ (deck_dir / MANIFEST_FILENAME).write_text("not json {", encoding="utf-8")
+ assert read_manifest(deck_dir) is None
+
+ def test_read_manifest_invalid_schema(self, tmp_path: Path) -> None:
+ deck_dir = tmp_path / "deck"
+ deck_dir.mkdir()
+ (deck_dir / MANIFEST_FILENAME).write_text(json.dumps({"unexpected": "shape"}), encoding="utf-8")
+ assert read_manifest(deck_dir) is None
+
+ def test_compute_file_sha256_is_deterministic(self, tmp_path: Path) -> None:
+ target = tmp_path / "f.toml"
+ target.write_text("hello", encoding="utf-8")
+ first = compute_file_sha256(target)
+ second = compute_file_sha256(target)
+ assert first == second
+ assert len(first) == 64
+
+ def test_x_custom_files_excluded(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ kit_dir = tmp_path / "kit"
+ self._seed_kit(
+ mocker,
+ kit_dir,
+ {
+ "1_llm_deck.toml": "managed",
+ "2_img_gen_deck.toml": "managed",
+ "x_custom_llm_deck.toml": "user-owned",
+ "x_custom_extract_deck.toml": "user-owned",
+ ".DS_Store": "junk",
+ },
+ )
+ kit_files = list_managed_kit_files()
+ assert set(kit_files.keys()) == {"1_llm_deck.toml", "2_img_gen_deck.toml"}
+
+ def test_list_managed_installed_files_filters_same_way(self, tmp_path: Path) -> None:
+ deck_dir = tmp_path / "deck"
+ self._seed_installed(
+ deck_dir,
+ {
+ "1_llm_deck.toml": "a",
+ "x_custom_llm_deck.toml": "b",
+ },
+ )
+ installed = list_managed_installed_files(deck_dir)
+ assert set(installed.keys()) == {"1_llm_deck.toml"}
+
+ def test_list_managed_installed_files_missing_dir(self, tmp_path: Path) -> None:
+ assert list_managed_installed_files(tmp_path / "absent") == {}
+
+ def test_compute_kit_manifest_stamps_version(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ kit_dir = tmp_path / "kit"
+ self._seed_kit(mocker, kit_dir, {"1_llm_deck.toml": "content-a"})
+ mocker.patch.object(deck_manifest, "get_package_version", return_value="9.9.9")
+
+ manifest = compute_kit_manifest()
+ assert manifest.kit_version == "9.9.9"
+ assert "1_llm_deck.toml" in manifest.files
+
+ def test_sync_report_up_to_date(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ kit_dir = tmp_path / "kit"
+ deck_dir = tmp_path / "deck"
+ contents = {"1_llm_deck.toml": "same-everywhere"}
+ self._seed_kit(mocker, kit_dir, contents)
+ self._seed_installed(deck_dir, contents)
+ mocker.patch.object(deck_manifest, "get_package_version", return_value="1.0.0")
+ write_manifest(deck_dir, compute_kit_manifest())
+
+ report = compute_deck_sync_report(deck_dir)
+ assert report.is_clean()
+ assert report.files["1_llm_deck.toml"] == DeckFileStatus.UP_TO_DATE
+
+ def test_sync_report_clean_behind(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ kit_dir = tmp_path / "kit"
+ deck_dir = tmp_path / "deck"
+ self._seed_kit(mocker, kit_dir, {"1_llm_deck.toml": "old"})
+ self._seed_installed(deck_dir, {"1_llm_deck.toml": "old"})
+ mocker.patch.object(deck_manifest, "get_package_version", return_value="1.0.0")
+ write_manifest(deck_dir, compute_kit_manifest())
+
+ # Simulate a kit upgrade — the file content has moved on but the user has not edited theirs.
+ (kit_dir / "1_llm_deck.toml").write_text("new", encoding="utf-8")
+ mocker.patch.object(deck_manifest, "get_package_version", return_value="1.1.0")
+
+ report = compute_deck_sync_report(deck_dir)
+ assert report.files["1_llm_deck.toml"] == DeckFileStatus.CLEAN_BEHIND
+ assert not report.is_clean()
+ assert report.installed_kit_version == "1.0.0"
+
+ def test_sync_report_locally_modified(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ kit_dir = tmp_path / "kit"
+ deck_dir = tmp_path / "deck"
+ self._seed_kit(mocker, kit_dir, {"1_llm_deck.toml": "kit-version"})
+ self._seed_installed(deck_dir, {"1_llm_deck.toml": "kit-version"})
+ mocker.patch.object(deck_manifest, "get_package_version", return_value="1.0.0")
+ write_manifest(deck_dir, compute_kit_manifest())
+
+ # User edits their installed file, kit unchanged.
+ (deck_dir / "1_llm_deck.toml").write_text("user-edited", encoding="utf-8")
+
+ report = compute_deck_sync_report(deck_dir)
+ assert report.files["1_llm_deck.toml"] == DeckFileStatus.LOCALLY_MODIFIED
+
+ def test_sync_report_kit_added(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ kit_dir = tmp_path / "kit"
+ deck_dir = tmp_path / "deck"
+ self._seed_kit(mocker, kit_dir, {"1_llm_deck.toml": "a", "5_new_deck.toml": "fresh"})
+ self._seed_installed(deck_dir, {"1_llm_deck.toml": "a"})
+ mocker.patch.object(deck_manifest, "get_package_version", return_value="1.0.0")
+ # Manifest captures only the file that existed at install time.
+ write_manifest(deck_dir, DeckManifest(kit_version="1.0.0", files={"1_llm_deck.toml": compute_file_sha256(deck_dir / "1_llm_deck.toml")}))
+
+ report = compute_deck_sync_report(deck_dir)
+ assert report.files["5_new_deck.toml"] == DeckFileStatus.KIT_ADDED
+ assert report.files["1_llm_deck.toml"] == DeckFileStatus.UP_TO_DATE
+
+ def test_sync_report_kit_removed(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ kit_dir = tmp_path / "kit"
+ deck_dir = tmp_path / "deck"
+ self._seed_kit(mocker, kit_dir, {"1_llm_deck.toml": "a"})
+ self._seed_installed(deck_dir, {"1_llm_deck.toml": "a", "9_retired_deck.toml": "old"})
+ mocker.patch.object(deck_manifest, "get_package_version", return_value="1.1.0")
+ write_manifest(
+ deck_dir,
+ DeckManifest(
+ kit_version="1.0.0",
+ files={
+ "1_llm_deck.toml": compute_file_sha256(deck_dir / "1_llm_deck.toml"),
+ "9_retired_deck.toml": compute_file_sha256(deck_dir / "9_retired_deck.toml"),
+ },
+ ),
+ )
+
+ report = compute_deck_sync_report(deck_dir)
+ assert report.files["9_retired_deck.toml"] == DeckFileStatus.KIT_REMOVED
+ assert report.files["1_llm_deck.toml"] == DeckFileStatus.UP_TO_DATE
+
+ def test_sync_report_no_manifest_treats_matching_files_as_up_to_date(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ kit_dir = tmp_path / "kit"
+ deck_dir = tmp_path / "deck"
+ contents = {"1_llm_deck.toml": "identical"}
+ self._seed_kit(mocker, kit_dir, contents)
+ self._seed_installed(deck_dir, contents)
+ mocker.patch.object(deck_manifest, "get_package_version", return_value="1.0.0")
+
+ report = compute_deck_sync_report(deck_dir)
+ assert report.manifest_present is False
+ assert report.files["1_llm_deck.toml"] == DeckFileStatus.UP_TO_DATE
+ # No manifest means the report still cannot be considered "clean" — boot warn still fires.
+ assert not report.is_clean()
+
+ def test_sync_report_no_manifest_marks_drift_as_locally_modified(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ kit_dir = tmp_path / "kit"
+ deck_dir = tmp_path / "deck"
+ self._seed_kit(mocker, kit_dir, {"1_llm_deck.toml": "kit"})
+ self._seed_installed(deck_dir, {"1_llm_deck.toml": "drift"})
+ mocker.patch.object(deck_manifest, "get_package_version", return_value="1.0.0")
+
+ report = compute_deck_sync_report(deck_dir)
+ assert report.manifest_present is False
+ assert report.files["1_llm_deck.toml"] == DeckFileStatus.LOCALLY_MODIFIED
+
+ @pytest.mark.parametrize(
+ ("manifest_version", "current_version", "expected_stale"),
+ [
+ ("1.0.0", "1.0.0", False),
+ ("1.0.0", "1.1.0", True),
+ ("1.0.0", "2.0.0", True),
+ # Downgrade: manifest newer than installed — no warn.
+ ("2.0.0", "1.5.0", False),
+ # Editable / dev builds carry build metadata; cores match, so not stale.
+ ("1.0.0", "1.0.0+localdev", False),
+ ("1.0.0+ci.42", "1.0.0", False),
+ # Pre-release suffixes are also ignored for the boot check.
+ ("1.0.0-rc1", "1.0.0", False),
+ ],
+ )
+ def test_is_deck_stale_fast(
+ self,
+ mocker: MockerFixture,
+ tmp_path: Path,
+ manifest_version: str,
+ current_version: str,
+ expected_stale: bool,
+ ) -> None:
+ deck_dir = tmp_path / "deck"
+ deck_dir.mkdir()
+ write_manifest(deck_dir, DeckManifest(kit_version=manifest_version, files={}))
+ mocker.patch.object(deck_manifest, "get_package_version", return_value=current_version)
+
+ assert is_deck_stale_fast(deck_dir) is expected_stale
+
+ def test_is_deck_stale_fast_missing_manifest(self, tmp_path: Path) -> None:
+ deck_dir = tmp_path / "deck"
+ deck_dir.mkdir()
+ # No manifest at all — should be treated as stale so the user gets the migration warn.
+ assert is_deck_stale_fast(deck_dir) is True
+
+ @pytest.mark.parametrize(
+ ("numbered_filename", "expected_override"),
+ [
+ ("1_llm_deck.toml", "x_custom_llm_deck.toml"),
+ ("2_img_gen_deck.toml", "x_custom_img_gen_deck.toml"),
+ ("3_extract_deck.toml", "x_custom_extract_deck.toml"),
+ ("4_search_deck.toml", "x_custom_search_deck.toml"),
+ # Unconventional names fall back to the generic suggestion.
+ ("not_numbered.toml", "x_custom_*.toml"),
+ ("5.toml", "x_custom_*.toml"),
+ ],
+ )
+ def test_suggest_x_custom_filename(self, numbered_filename: str, expected_override: str) -> None:
+ assert suggest_x_custom_filename(numbered_filename) == expected_override