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.
Migrator Phases 0-1: the migration contract, the operation vocabulary, and the schema-1 cut (#1110)
Louis Choquel052b9df067f4
diff --git a/.drift/acks/config-docs.toml b/.drift/acks/config-docs.tomlindex 21909e6af..de3739eb4 100644--- a/.drift/acks/config-docs.toml+++ b/.drift/acks/config-docs.toml@@ -1,8 +1,8 @@contract = "config-docs"-digest = "sha256:f3a7f92e378ea8f12e9ff11e91b6f0f1e377f1d6a9f218f2e6de4d4668cb3d36"+digest = "sha256:71968ad3e732b8e92611a165463e2a9c293772fd07ed2d994a26c6f02548ef1f"reviewed_by = "Louis Choquel"-reviewed_at = "2026-08-14T09:24:56Z"-rationale = "Trigger is Phase 1 of the templating-style plan: PromptingConfig became TemplatingConfig with a single default_templating_style field, mounted as pipelex.templating_config, and the per-target prompting_styles map was deleted from pipelex.toml. Reviewed docs/configuration/: no page documents the prompting_config section or the style map, so nothing there went stale. The one prompting_target hit (inference-backend-config.md default_prompting_target example) still matches the shipped backend TOMLs, which Phase 3 deletes. The user-facing styling page that does document the old config lives under docs/building-methods/ and is replaced in Phase 4. No configuration doc change needed."+reviewed_at = "2026-08-15T12:10:14Z"+rationale = "Reviewed docs/configuration/ against the config-surface read helper, the loader and telemetry wiring, and the PipelexServiceConfig.agreement default. Nothing there went stale: no page documents a reader's tolerance rules, the service-agreement file's location is unchanged, and the telemetry page documents settings rather than the load path. The new reserved meta schema_version key is deliberately NOT added to these pages — nothing writes it, and documenting it where users are told what to put in their files would invite the team-skew breakage the migration contract forbids; it is specified in docs/migration-ledger.md, which is published at Phase 3."[trigger_files]"pipelex/cogt/config_cogt.py" = "blob:ee1ee2d0c1474dcef5e07690268de37ae3ff0987"@@ -10,11 +10,12 @@ rationale = "Trigger is Phase 1 of the templating-style plan: PromptingConfig be"pipelex/pipelex.toml" = "blob:abaf4f65f3096a4625dad8c6887431e952cc4734""pipelex/system/configuration/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc""pipelex/system/configuration/config_check.py" = "blob:efa78599c08e5e003d975cc54978ea5d267214a0"-"pipelex/system/configuration/config_loader.py" = "blob:29fb321ef003c0fd725c87f560a791e8573b82f5"+"pipelex/system/configuration/config_loader.py" = "blob:76f9a66ae1ac28df45b9742677218bee63a37121""pipelex/system/configuration/config_model.py" = "blob:83b29dc6e93393c9b98c4353636caf0135c80339""pipelex/system/configuration/config_root.py" = "blob:c7d43851270912d17413cfc6a511247d3c7cc160"+"pipelex/system/configuration/config_surface.py" = "blob:18dc1521de776dbffaa27630896c0700c9edf100""pipelex/system/configuration/configs.py" = "blob:90b3186c53b431e0c50b73a533685be92ccd94b0""pipelex/system/configuration/pipe_func_config.py" = "blob:df1cbd3698d51c96d8fa8a8c6fdf1c6be57e5771"-"pipelex/system/telemetry/telemetry_config.py" = "blob:b6912e8be8932b65213dab23ac66372b8b45ca58"+"pipelex/system/telemetry/telemetry_config.py" = "blob:db0457ba4214d5b0ecb18db75e1b164054181fed""pipelex/tools/aws/aws_config.py" = "blob:c1aeafeae08d3921464db33795f11a29ff3892ba""pipelex/tools/log/log_config.py" = "blob:7b6d032ffea29d6ce60e8af7106f2d935bc18348"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c63283270..e75581b0c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,12 @@## [Unreleased]+### Added++- **Configuration surfaces now have a migration ledger and a gate that forces one to be written**: Each of the three configuration surfaces — `pipelex.toml` and its tiers, `telemetry.toml`, `pipelex_service.toml` — carries a checked-in ledger at `pipelex/migration/ledgers/<surface-id>.toml` recording, as data, every shape change it has ever undergone, plus a golden chain (`fingerprint@N`, `defaults@N`) that pins what the schema looked like at each version. All three start at schema version 1 with no entries: this release cuts the baseline, it migrates nothing. The new `make check-migration-schemas` (alias `cmig`, in `make check`) recomputes each surface's fingerprint and refuses a change that would break a user's file without recording how to repair it — a removed path or a lost enumerated spelling demands a version bump and an operation accounting for it, a destination the new schema does not know is refused by name, an entry that removes a path the schema still has is refused as over-deletion, and a `safe` value remap whose old spelling is still legal is refused because it would rewrite a deliberate choice. Its counterpart `make up-migration-schemas` (alias `umig`, in `make up`) regenerates the goldens; the regeneration diff is the review artifact. One standing invariant is checked whether or not anything changed: every required path must have a value in its surface's defaults layer, because that is what makes an added key absorbable rather than breaking. The contract the whole thing implements is `docs/migration-ledger.md`.+- **The migration operation vocabulary**: Fix operations became a discriminated union on `kind`, published as two subsets — every kind for the `.mthds` fix path, and the structural kinds only for ledgers, so an operation that would write a value into a user's file fails when the ledger is parsed rather than at review time. Two new kinds land with it: `move_key`, which relocates a key across tables (the whole subtree travels when the key is table-valued, and a missing destination parent is created), and `remap_value`, which rewrites a value against an explicit old-to-new mapping. A `*` segment addresses every entry of an open mapping, expanded over the keys the file actually holds. A new `CONFLICT` outcome separates "this cannot be done without choosing on your behalf" — a rename or move onto an occupied destination, or an `ensure_table` over a key holding something that is not a table — from the benign `SKIPPED` it used to hide inside; a conflicting operation writes nothing at all.+- **`[meta] schema_version` is reserved in configuration files**: Every configuration-surface reader now tolerates and strips it. Nothing writes it — the key exists so a later release can stamp a version into a file without that being a breaking change today.+### Changed- **Templating style is now an authoring decision (Breaking)**: How a pipe's inputs are tagged into a prompt is declared on the pipe — `templating_style` on `PipeLLM`, either a bare tag-style string (`"xml"`, `"ticks"`, `"square_brackets"`, `"no_tag"`) or a full `{ tag_style, text_format }` table — with a single runtime default for everything that declares nothing (`[pipelex.templating_config].default_templating_style`, shipped as `xml`). It is no longer derived from model metadata, so the same method renders the same prompt shape on every model. **Every prompt rendered for an OpenAI-family model changes shape, from back-tick fences to XML tags.** `PipelexKernel.llm_text` and `llm_object` take the same optional argument.diff --git a/Makefile b/Makefileindex 8e3df9ad7..d55d4e4ac 100644--- a/Makefile+++ b/Makefile@@ -102,6 +102,10 @@ make generate-mthds-schema - Generate JSON Schema for .mthds filesmake gms - Shorthand -> generate-mthds-schemamake check-mthds-schema - Check MTHDS JSON Schema is up-to-datemake cms - Shorthand -> check-mthds-schema+make check-migration-schemas - Check configuration surfaces have accounted for their schema changes+make cmig - Shorthand -> check-migration-schemas+make up-migration-schemas - Regenerate the migration fingerprint and defaults goldens+make umig - Shorthand -> up-migration-schemasmake generate-error-pages - Generate one docs page per PipelexError subclass under docs/errors/make gep - Shorthand -> generate-error-pagesmake generate-error-identity - Regenerate the committed PipelexError wire-identity snapshot@@ -114,7 +118,7 @@ make regenerate-test-models - Regenerate test model fixtures from backend confmake rtm - Shorthand -> regenerate-test-modelsmake insert-skeleton - Insert skeleton from $(SKELETON_DIR)-make up - Shorthand -> generate-mthds-schema update-gateway-models up-kit-configs rules+make up - Shorthand -> generate-mthds-schema update-gateway-models up-kit-configs up-migration-schemas rulesmake cleanenv - Remove virtual envmake cleanderived - Remove extraneous compiled files, caches, logs, etc.make cleanall - Remove all -> cleanenv + cleanderived@@ -211,6 +215,7 @@ export HELPli check-unused-imports fix-unused-imports check-TODOs check-uv \docs docs-check docs-serve-versioned docs-list docs-deploy docs-deploy-stable docs-deploy-specific-version docs-delete \generate-mthds-schema generate-mthds-schema-quiet gms check-mthds-schema cms \+ check-migration-schemas cmig up-migration-schemas up-migration-schemas-quiet umig \generate-error-pages generate-error-pages-quiet gep \generate-error-identity generate-error-identity-quiet gei \update-gateway-models update-gateway-models-quiet ugm check-gateway-models cgm up \@@ -409,6 +414,23 @@ check-mthds-schema: envcms: check-mthds-schema@echo "> done: cms = check-mthds-schema"+check-migration-schemas: env+ $(call PRINT_TITLE,"Checking configuration surfaces have accounted for their schema changes")+ $(VENV_PIPELEX_DEV) check-migration-schemas --quiet++cmig: check-migration-schemas+ @echo "> done: cmig = check-migration-schemas"++up-migration-schemas: env+ $(call PRINT_TITLE,"Updating migration fingerprint and defaults goldens")+ $(VENV_PIPELEX_DEV) update-migration-schemas++up-migration-schemas-quiet: env+ $(VENV_PIPELEX_DEV) update-migration-schemas --quiet++umig: up-migration-schemas+ @echo "> done: umig = up-migration-schemas"+generate-error-pages: env$(call PRINT_TITLE,"Generating per-class error documentation pages")$(VENV_PIPELEX_DEV) generate-error-pages@@ -1156,10 +1178,10 @@ c: check-keyword-only format lint pyright mypycc: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet update-gateway-models-quiet c@echo "> done: cc = cleanderived regenerate-test-models generate-mthds-schema update-gateway-models format lint pyright mypy"-up: generate-mthds-schema-quiet update-gateway-models-quiet up-kit-configs rules- @echo "> done: up = generate-mthds-schema update-gateway-models up-kit-configs rules"+up: generate-mthds-schema-quiet update-gateway-models-quiet up-kit-configs up-migration-schemas-quiet rules+ @echo "> done: up = generate-mthds-schema update-gateway-models up-kit-configs up-migration-schemas rules"-check: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet update-gateway-models-quiet check-unused-imports check-config-sync check-rules check-urls check-gateway-models check-mthds-schema check-keyword-only check-hub-layering drift-check format lint pyright mypy pylint+check: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet update-gateway-models-quiet check-unused-imports check-config-sync check-rules check-urls check-gateway-models check-mthds-schema check-migration-schemas check-keyword-only check-hub-layering drift-check format lint pyright mypy pylint@echo "> done: check"agent-check: fix-unused-imports fix-keyword-only format lint pyright mypy check-keyword-only check-hub-layering drift-checkdiff --git a/docs/contribute/configuration-defaults-and-overrides.md b/docs/contribute/configuration-defaults-and-overrides.mdindex dffa3a6a4..8e18ef954 100644--- a/docs/contribute/configuration-defaults-and-overrides.md+++ b/docs/contribute/configuration-defaults-and-overrides.md@@ -55,6 +55,7 @@ Load order:- If you change **defaults**, update `pipelex/pipelex.toml` (and consider whether templates in `pipelex/kit/configs/…` should also be updated).- If you change **templates**, keep them user-focused and stable; avoid adding internal-only details.- If you change **merge order or override semantics**, treat it as a potentially breaking change and document it (changelog + migration notes if needed).+- If you change the **shape** of a configuration model — renaming, moving or removing a key, or dropping an enumerated value — `make check` will stop you until the change is recorded in that surface's migration ledger. Adding a key is not a shape change and needs nothing, provided the key has a default: the defaults layer is what an old file falls back on, and a required key with no default breaks every existing file. The gate is `make check-migration-schemas` (alias `cmig`) and its regenerator is `make up-migration-schemas` (alias `umig`). The contract, including what a ledger may contain and what is guaranteed to a user whose files are migrated, is in [The Migration Ledger](../migration-ledger.md).---diff --git a/docs/errors/index.md b/docs/errors/index.mdindex 1485f6a81..3651f91ac 100644--- a/docs/errors/index.md+++ b/docs/errors/index.md@@ -18,7 +18,7 @@ the error came from:- [Authoring & language](authoring-and-language.md) — MTHDS parsing, Core language, Pipe operators, Pipe controllers, Pipe signatures, Builder, Libraries.- [Execution & runtime](execution-and-runtime.md) — Pipe execution, Pipeline execution, Runtime bridge, Graph, Tracing.- [Inference & providers](inference-and-providers.md) — Inference (Cogt), Provider adapters, Plugin system.-- [Platform & tooling](platform-and-tooling.md) — Base & root errors, Tools, Kit, System & configuration, CLI, Codegen.+- [Platform & tooling](platform-and-tooling.md) — Base & root errors, Tools, Kit, System & configuration, CLI, Codegen, Migration.See [Error Model](../under-the-hood/error-model.md) for the underlying contractand classification rules.diff --git a/docs/errors/migration-error.md b/docs/errors/migration-error.mdnew file mode 100644index 000000000..742fee38e--- /dev/null+++ b/docs/errors/migration-error.md@@ -0,0 +1,21 @@+---+title: "Migration error"+description: "Reference for the `MigrationError` Pipelex error class."+---++<!-- pipelex:generated -->++# Migration error++Base for every failure raised by the configuration-migration engine.++| Field | Value |+|---|---|+| `error_type` | `MigrationError` |+| `title` | Migration error |+| `type_uri` | `https://docs.pipelex.com/latest/errors/migration-error/` |+| `error_domain` | `config` |+| Defined in | `pipelex.migration.exceptions` |+| Parent class | [`PipelexError`](pipelex-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/errors/migration-golden-error.md b/docs/errors/migration-golden-error.mdnew file mode 100644index 000000000..dc942d595--- /dev/null+++ b/docs/errors/migration-golden-error.md@@ -0,0 +1,21 @@+---+title: "Migration golden error"+description: "Reference for the `MigrationGoldenError` Pipelex error class."+---++<!-- pipelex:generated -->++# Migration golden error++A checked-in golden is missing or unreadable, so no verdict can be produced.++| Field | Value |+|---|---|+| `error_type` | `MigrationGoldenError` |+| `title` | Migration golden error |+| `type_uri` | `https://docs.pipelex.com/latest/errors/migration-golden-error/` |+| `error_domain` | _(inherited from parent)_ |+| Defined in | `pipelex.migration.exceptions` |+| Parent class | [`MigrationError`](migration-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/errors/migration-ledger-error.md b/docs/errors/migration-ledger-error.mdnew file mode 100644index 000000000..65a4fafaf--- /dev/null+++ b/docs/errors/migration-ledger-error.md@@ -0,0 +1,21 @@+---+title: "Migration ledger error"+description: "Reference for the `MigrationLedgerError` Pipelex error class."+---++<!-- pipelex:generated -->++# Migration ledger error++A ledger file is missing, unparseable, or internally inconsistent.++| Field | Value |+|---|---|+| `error_type` | `MigrationLedgerError` |+| `title` | Migration ledger error |+| `type_uri` | `https://docs.pipelex.com/latest/errors/migration-ledger-error/` |+| `error_domain` | _(inherited from parent)_ |+| Defined in | `pipelex.migration.exceptions` |+| Parent class | [`MigrationError`](migration-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/errors/migration-registry-error.md b/docs/errors/migration-registry-error.mdnew file mode 100644index 000000000..ecaeec8fc--- /dev/null+++ b/docs/errors/migration-registry-error.md@@ -0,0 +1,21 @@+---+title: "Migration registry error"+description: "Reference for the `MigrationRegistryError` Pipelex error class."+---++<!-- pipelex:generated -->++# Migration registry error++The surface registry is inconsistent, or names a surface that does not exist.++| Field | Value |+|---|---|+| `error_type` | `MigrationRegistryError` |+| `title` | Migration registry error |+| `type_uri` | `https://docs.pipelex.com/latest/errors/migration-registry-error/` |+| `error_domain` | _(inherited from parent)_ |+| Defined in | `pipelex.migration.exceptions` |+| Parent class | [`MigrationError`](migration-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/errors/platform-and-tooling.md b/docs/errors/platform-and-tooling.mdindex 96d08233c..313e98a24 100644--- a/docs/errors/platform-and-tooling.md+++ b/docs/errors/platform-and-tooling.md@@ -102,4 +102,11 @@ own page. Classes are grouped by subsystem.- [`CodegenLockError`](codegen-lock-error.md) — Codegen lock error- [`CodegenStampError`](codegen-stamp-error.md) — Codegen stamp error+## Migration++- [`MigrationError`](migration-error.md) — Migration error+- [`MigrationGoldenError`](migration-golden-error.md) — Migration golden error+- [`MigrationLedgerError`](migration-ledger-error.md) — Migration ledger error+- [`MigrationRegistryError`](migration-registry-error.md) — Migration registry error+[Back to Error Reference](index.md)diff --git a/docs/migration-ledger.md b/docs/migration-ledger.mdnew file mode 100644index 000000000..9b2d078d1--- /dev/null+++ b/docs/migration-ledger.md@@ -0,0 +1,426 @@+# The Migration Ledger++Pipelex configuration files live on users' machines and in users' repositories, and the models that read them keep changing shape. A **migration ledger** is the checked-in record of every shape change a configuration surface has ever undergone, written as data rather than as code, so that a stale file can be repaired mechanically instead of deleted and re-initialized.++This page is the contract: what a ledger may contain, what the engine may do with it, and what is guaranteed to a user whose files are migrated. It is normative. Everything asserted here has, or will have, a test behind it, and where a rule exists to prevent a specific failure the failure is named — a rule whose reason is forgotten is a rule that gets relaxed.++> **Status.** This specification was written before its implementation, deliberately: the guarantees below are what the engine is built against. The data format, the operation vocabulary and the checks land first; `pipelex migrate` and boot tolerance land last. Of the checks, the coverage gate (`make check-migration-schemas`) and its regenerator (`make up-migration-schemas`) exist today; `make check-ledger`, the transform-golden verifier and pre-history entries arrive with the engine. Until the commands exist, this page is built but kept out of the documentation navigation.++## What migrates, and what does not++A **structural** change is a key renamed, moved or removed, or an enumerated value renamed. It breaks a user's file: the model rejects it, and no amount of re-reading helps. That is what the ledger describes and what the engine repairs.++A **content** change is a value or an entry in a package-managed file that should track the package — a new inference backend, a changed default in the model deck. Those files are not broken, they are behind, and merging them without destroying the user's customizations is a different problem with different machinery. Content sync is out of scope here and is not described by this contract.++Everything else this document deliberately does not specify: the language surface (`.mthds` files and the MTHDS standard version), plugin-owned ledgers, and the promotion of this contract into a cross-repository specification. Each is a project of its own, and specifying it in advance would freeze decisions nobody has had to make yet.++## Surfaces++A **surface** is one artifact family with one schema version and one ledger. The in-scope surfaces are the configuration surfaces the `pipelex` package owns:++| Surface id | Base file | Tier files | Model | Defaults layer |+|---|---|---|---|---|+| `pipelex-config` | `pipelex.toml` | `pipelex_*.toml` | `PipelexConfig` | Packaged document (`pipelex/pipelex.toml`) |+| `telemetry-config` | `telemetry.toml` | `telemetry_*.toml` | `TelemetryConfig` | Model defaults |+| `pipelex-service-config` | `pipelex_service.toml` | — | `PipelexServiceConfig` | Model defaults |++File names are relative to a configuration directory, and every surface spans exactly two of them: the global `~/.pipelex/` and the project's `.pipelex/`. `pipelex migrate` walks both, and only those. Two paths that look like configuration are outside the walk by design: the unit-testing tier `./tests/pipelex_{run_mode}.toml`, and any file reached through an explicit `load_config(config_dir=…)`, which is a repository-internal mechanism rather than a user's configuration.++The tier set is **open**. Environment and run-mode names are dynamic, so the tier filenames of `pipelex-config` cannot be enumerated in advance — `pipelex_local.toml`, `pipelex_{environment}.toml`, `pipelex_{run_mode}.toml`, `pipelex_override.toml` and `pipelex_temporary_override.toml` are a description of today, not a closed list. That is why the registry matches tiers with a glob, and the glob is what makes the resolution rule necessary:++> **Exact filenames claim before globs, across all surfaces.** A file matched by any surface's exact pattern belongs to that surface and is excluded from every surface's glob. A file claimed by two globs, or by two exact names, is a registry error and is rejected when the registry loads.++Without the rule, `pipelex_service.toml` is both the base file of one surface and a match for another's `pipelex_*.toml`, and which ledger runs over it becomes an accident of iteration order.++Each surface also declares its **defaults-layer kind**, because the checks need to know where a current-schema default value comes from: a packaged TOML document merged beneath the user's files, or model-level field defaults. The distinction matters twice — for synthesizing the complete reference document of a surface that has no packaged file, and for refusing an added path that has no default anywhere. A model-defaults surface whose model cannot be built with nothing set has no defaults layer at all, and says so when its reference document is asked for rather than surfacing later as a missing value.++The registry and each ledger's `[surface]` block both describe the same thing, and both are read as truth — the ledger's when a migration walks a directory, the registry's when a gate fingerprints a model. A disagreement between them is therefore checked, not trusted: it would otherwise wait silently for the day the two readers meet.++Every surface starts at `schema_version = 1` with an empty ledger. There is no retroactive numbering of changes that predate the ledger; the one case that genuinely needs to reach backwards has its own bounded mechanism, described under [pre-history entries](#pre-history-entries).++## The defaults layer, and why additive changes never migrate++Every in-scope surface has a **defaults layer**: a source of current-schema values that sits beneath the user's files and cannot be stale, because it ships with the package. The consequence is the rule that keeps the whole vocabulary structural:++> **A key we add is supplied by the defaults layer, so an old file that lacks it still validates and still behaves correctly. An additive schema change cannot break anyone, and therefore never has a migration operation.**++The inverse is worth stating with equal force, because it is the tempting mistake. Writing a default value into a user's file is not a neutral repair: it converts an *inherited* value into an *explicitly set* one, pinning it against every future change to that default and changing what the merge produces. That is a semantic edit dressed up as a fix. It is why the materializing operations are excluded from the migration vocabulary outright rather than restricted to some class of files — every user file overrides the packaged defaults, base files included, so an argument that keeps materialization out of an override tier keeps it out of everything.++**If a surface ever appears to need an additive migration, the defect is a missing defaults layer on that surface, and the fix is to give it one.** The rule is enforced rather than trusted: the coverage check refuses an added path that has no value in its surface's defaults layer, and names the only remedy the vocabulary allows.++## Schema versions, and why every run replays everything++Each surface carries a monotonic integer, bumped only when its shape changes. Integers rather than semantic versions, because a schema either changed or it did not. Each entry also records the package version that introduced it, for orientation against the changelog only — nothing branches on it.++Migration is **file-level**. The merged configuration cannot answer "what version is this file at", because the effective value of any key comes from whichever tier wrote last. Every migration reads, plans and rewrites one file at a time, upstream of the loader's deep merge, and tier files are migrated as ordinary members of their surface.++> **No version record ever causes work to be skipped.** Every run plans the full ledger for the surface, and the applier skips each operation whose target is already gone or whose change is already present.++The reasoning is worth keeping. Any side record of "what has already been applied" is untracked state sitting next to files that git, restores, branch switches and copies move independently of it. Anything that skips work based on such a record will eventually report "nothing to do" at the exact moment a user's boot is broken — the worst failure this tool can have. And since the record can never be allowed to cause a skip, it has no remaining reader:++> **There is no state stamp.** No state file, no per-file bookkeeping, no state-transition rules. The report describes what this run observed and did, which it knows exactly, rather than what some earlier run claims to have done.++Two reservations exist so that later projects stay free:++- **`[meta] schema_version`** is a reserved optional in-file key. Every configuration-surface reader tolerates it and strips it before validation; **nothing writes it**. The reason not to write it is not release compatibility, which our principles disclaim, but team skew on tracked files: base configuration files under a project's `.pipelex/` are shared through git right now, so one developer on a newer pipelex writing the key would break a teammate on last week's build the same afternoon.+- **`min_supported_schema_version`** on the surface block, held at zero until a ledger squash ever moves it. Without the floor, a squash silently under-migrates the oldest files in the field, because the applier skips absent targets and reports success. With it, the loader fails loudly instead.++### The downgrade direction++Always-replay covers files *older* than the running pipelex. The same branch switch that motivates it also produces files *newer* than the running pipelex: an untracked override migrated on one branch, then an older branch checked out or the package downgraded. The older model rejects the newer key, and replay finds nothing to do, because every operation's source is absent.++Under the no-backward-compatibility principle this is not repaired, but it must be **named**, because "nothing to do" beside a dead boot is precisely the failure this project exists to kill:++> When validation fails on an unknown path that no ledger entry removes, the report says so: the path is either a typo or was written by a newer pipelex than this one, and the message asks whether the user is on an older branch or build.++That diagnosis is computable from the ledger alone and needs no stamp.++## Replay neutrality++This is the central guarantee, and everything else in the contract exists to keep it true:++> **A full replay of a surface's ledger over any file already valid at the current schema is a byte-level no-op.**++Note the domain. It is not "over the packaged defaults" or "over the template" — it is every document the current models accept, including files carrying values no template ever contains. A witness document can never stand in for that domain, because it carries exactly one value per key.++The guarantee is a theorem, from two premises.++**Premise one: every migration operation's precondition mentions only removed material.** The vocabulary is purely structural — each operation acts only when its source path is present, and every source path is one that some schema version removed. A file valid at the current schema cannot contain a removed path, because the configuration models are `extra="forbid"`, so every operation skips. Two static rules make this mechanical rather than argued: [op legality](#op-legality) and the reserved-path registry, which guarantees that "removed" is permanent — a removed path is never reintroduced with a new meaning that would make it legal again.++**Premise two: the remap legality rule.** A `safe` `remap_value` is legal only when its target path is enum-typed at the current schema and every old value in its mapping falls outside the current member set. Then a current-valid file cannot carry a mapped value, and the remap skips. When an old spelling remains legal — or the path is a free string, where staleness can never be proven from the schema — the entry must be `unsafe`: the migration still exists and is still reported, but it is never applied automatically, because the applier cannot distinguish a stale value from a deliberate choice.++With both premises every operation in a full replay over a current-valid file skips; skipping mutates nothing, and [serialization adds nothing](#serialization-adds-nothing), so the output is byte-identical.++The theorem is checked anyway, twice, because proofs rot where code does not:++- **The convergence witness.** A full replay over each of a surface's reference documents — the complete defaults document and the sparse kit template — must produce zero applied operations. Both are at the current schema by construction, so there is no fixture to maintain. Cheap and exact; it runs in `agent-check`.+- **The neutrality property test.** Generated documents that are valid at the current schema — mutations of the packaged defaults within the schema: other enum members, deleted optional keys, altered scalars, tier-shaped sparse subsets — must replay to byte-identical output. This is the executable form of the theorem over the domain the theorem actually claims. It carries a **vacuity meta-test**: every generated document must validate against its surface's model, or the property is passing on garbage.++Two further properties hold and are tested with it: replay is **idempotent** (applying a ledger twice equals applying it once) and **prefix-coherent** (a file that has already absorbed some entries lands where a replay from zero lands).++## The ledger file++One checked-in TOML file per surface, shipped inside the package that owns the schema, at `pipelex/migration/ledgers/<surface-id>.toml`.++**The ledger is data and never code.** The checks must reason mechanically about what every entry does — which paths it removes, which values it remaps, whether replay converges — and executable steps defeat every one of those checks.++The example below is illustrative — it shows every part of the format on a surface that does not exist. A surface's real entries live in its own ledger file.++```toml+[surface]+id = "example-config"+title = "An example configuration surface"+base_file = "example.toml"+tier_glob = "example_*.toml" # exact names of other surfaces are excluded by the resolver+current_schema_version = 2+min_supported_schema_version = 0++[[migration]]+id = "example-config@2"+to_schema_version = 2+introduced_in = "0.46.0" # the package version that carries this entry; orientation only+breaking = true+safety = "safe"+title = "Short imperative summary of the shape change"+description = "One or two sentences a release note can quote."+guidance = """+Agent-facing Markdown: what a user should understand or decide. Never the mechanism.+"""++[[migration.ops]] # rename a nested table in place, inside its parent+kind = "rename_table_key"+table_path = ["reporting"]+key = "output_config"+new_key = "output"++[[migration.ops]] # move a table-valued key to a parent that has to be created+kind = "move_key"+table_path = ["reporting"]+key = "retention"+new_table_path = ["storage"]+new_key = "retention"++[[migration.ops]] # retire a whole section, and with it its top-level name+kind = "delete_table"+table_path = ["legacy_reporting"]+```++The rules that govern the file:++- **Entries are ordered by `to_schema_version` and replayed in that order.** Versions are contiguous and match their ids. A key renamed at version 2 and moved at version 4 lands correctly for a file coming from version 1, because the entries compose in sequence.+- **`safety` and `guidance` are independent.** `safety` governs whether the applier may act: `safe` means mechanically complete and applied after one confirmation, `unsafe` means reported and never applied. `guidance` is prose any entry may carry, whatever its safety.+- **`guidance` is the explanation, never the mechanism.** Anything expressible as operations must be operations. An entry may legitimately carry no operations at all with `safety = "unsafe"`, for a change only a human can make.+- **Operations target the narrowest path that expresses the change.** A ledger entry is permanent data that outlives the current field census of its parent table, so deleting a parent because it happens to have one field today is wrong — unless the parent itself is what retires, in which case the entry deletes the parent and the parent's name becomes reserved.+- **The parsed ledger is cached per process.** Replaying a surface over many files must not re-parse the TOML per file.++### Pre-history entries++A removal that predates the first fingerprint has no observed diff and no snapshot to compare against. Such an entry may carry `pre_history = true`, in which case it **declares its own removed paths** — the reserved-path registry records them from the declaration rather than from a fingerprint diff — and ships a hand-authored `before` document so the transform check has a pair to verify. Convergence and neutrality then verify it exactly like any other entry.++This exception is bounded to entries carrying the flag, and exists for the changes that shipped before the ledger did. It is not a way to avoid a fingerprint diff for a change that has one.++## The operation vocabulary++The ledger draws on the same operation vocabulary as the `.mthds` fix path, restricted to its structural half. The full union is published as two subsets — **fix operations** (every kind) and **migration operations** (the structural kinds only) — so a ledger containing a non-migration kind fails validation when the ledger is parsed, not later at gate time.++| Kind | In a ledger? | What it does |+|---|---|---|+| `set_key` | **no** | Writes unconditionally. Correct when derived from a typed error about that exact key; wrong under replay, where it would overwrite a user's chosen value on every run. |+| `ensure_table` | **no** | Materializing — absorbed by the defaults layer. |+| `ensure_key` | **no** | Does not exist, and is not built: additive changes never migrate. |+| `delete_key` | yes | Drops a retired key. |+| `delete_table` | yes | Drops a retired section, including every chunk of a table written out of order. |+| `rename_table_key` | yes | Renames a key, or a nested table, in place within its parent. Position is preserved. |+| `move_key` | yes | Relocates a key across tables, optionally renaming it. The moved key may be table-valued, in which case the whole subtree travels. Missing destination parents are created as block tables as part of the operation. |+| `remap_value` | yes | Rewrites a value against an explicit old-to-new mapping, and does nothing when the current value is not in the mapping. `safe` only under the remap legality rule. |++Every operation carries a `table_path`: a list of segments naming the table it acts in, empty for the document root. `delete_table` needs nothing more — its `table_path` *is* its target. Every other kind adds the `key` it acts on, and then whatever its own semantics require: `rename_table_key` a `new_key`, `move_key` a `new_table_path` and a `new_key`, `remap_value` a `mapping` of old value to new value. Each kind declares exactly its own fields, so an entry that names a field the kind does not have is refused when the ledger is parsed.++### `move_key` placement++Moving a key changes its address, and a file has to put the moved material somewhere. The rule, measured against the TOML library rather than assumed:++> **Position is preserved within a parent, never across parents.** A destination parent that already exists receives the moved key at the end of that parent's span — and, when the parent is written out of order across several chunks of the file, at the end of its *first* chunk. A destination parent that has to be created lands at the end of the file.++Both halves are deliberate and neither is wrong, but they differ, and a reviewer reading a migration diff should not be surprised by either.++### The wildcard segment++Some configuration nodes are **open dictionaries** — fields typed as a mapping from arbitrary keys to a value schema, where any key is legal, no fingerprint can enumerate the keys, and `extra="forbid"` says nothing. The keys under such a node belong to the user; the value schema belongs to us. So the fingerprint records value-schema paths beneath a `*` segment, and an operation may use `*` **exactly at an open node**, where the applier expands it over the keys the file actually contains. A field renamed inside every entry of an open mapping, or an enum member remapped across every value of one, is then an ordinary `safe` operation rather than an impossibility.++### Outcomes++The applier reports one outcome per operation:++| Outcome | Meaning |+|---|---|+| `APPLIED` | The file changed. |+| `SKIPPED` | Nothing to do — the target is absent, or the change is already present. |+| `CONFLICT` | The change cannot be made without choosing on the user's behalf. |++`SKIPPED` is the overwhelmingly common outcome under always-replay and is entirely benign; reports suppress it. `CONFLICT` is not benign and must never travel inside `SKIPPED`: it is returned when a rename or move destination is already occupied, typically because a user hand-fixed part of their file. A conflicting step writes nothing, routes into the plan's `blocked` list with the path and both names, and never undermines replay neutrality — a document carrying both names is by definition not valid at the current schema. An operation is one step whatever it expands to: a wildcard operation is checked across every entry it matches before any of them is written, so a conflict in the last matched entry leaves the first untouched.++> **Outcomes are classified by the outcome enum, never by parsing a detail string.** Messages are presentation and are free to change; the outcome is the contract.++## Legality rules++The guarantees above hold only if entries cannot say certain things. These rules are checked statically, before any file is touched.++### Op legality++- **Every operation's source must be a path some schema version removed** — recorded as such in the reserved-path registry by the entry that removes it. An operation whose source is still a live path of the current schema would act on a valid file, and replay neutrality would be false.+- **No operation may address a concrete key beneath an open node.** Those keys are the user's, they are unbounded, and no schema change can remove one.+- **A `*` segment is legal exactly at an open node**, and nowhere else.++### Sequential path state++Legality is defined over an entry's **sequential path state**, not operation by operation in isolation. An entry's operations chain: a parent is renamed and then keys inside it are renamed, so the intermediate paths belong to neither the old fingerprint nor the new one. The check therefore walks the previous fingerprint's path set through the entry's operations symbolically, carrying each surviving path together with the path it originated from, and then compares the end state with the new fingerprint in three ways:++- **Every operation's source must exist in the state when the operation runs, and must be what the operation acts on.** One whose source is absent — or a `delete_table` aimed at a key, which the applier's guarded skip refuses — is a **dead operation**: it skips on every file forever and reports success, which is the quietest way for a migration to be wrong.+- **A `safe` rename or move must not land on a path the state already has.** The applier refuses to clobber an occupied destination, so a file carrying both keys — a perfectly valid file at the previous schema — would come back `CONFLICT` on every run. Such an entry is refused as **destination occupied**; it can be `unsafe`, or choose a destination the previous schema did not have.+- **Every path surviving the walk must be a path of the new fingerprint.** A survivor that is not is either an unaccounted removal or a misspelled destination; the two are the same defect seen from either end, and one containment check catches both.+- **Every path of the new fingerprint that the walk removed must be a genuine addition** — that is, absent from the previous fingerprint. One that was present is **over-deletion**: an entry that dropped a parent table where it meant to drop one child.+- **Every enumerated spelling lost between the two fingerprints must be remapped, following the path through the entry's own renames.** Members are compared by origin — an enumerated path of the previous schema is looked up at the path the walk carried it to — so a member lost by a path the same entry renamed still demands its `remap_value`, and the remap that supplies it addresses the key by its new name.++The end state is deliberately *not* compared as "the new fingerprint minus its additions". That formulation reads a rename's destination as an addition and its source as a removal, so it demands that the destination be absent from the end state — which is exactly where a correct rename puts it. Containment plus the over-deletion check is the same guarantee stated in a form renames satisfy.++No ordering avoids the intermediate state — a nested rename under a moved parent produces one however the operations are sorted — so this is a property of the checker, not a constraint on authors. The `*` wildcard needs no special handling either: the fingerprint records value-schema paths under a literal `*` segment, so an operation addressing an open node matches it by name like any other.++### Destination cross-check++The containment half of the walk above *is* the destination cross-check: a rename to a name the current schema does not know leaves a path the new fingerprint lacks, and is refused with the mismatch named. Without it, a misspelled destination passes both coverage and convergence — the removed path is accounted for, and over a current document the source is absent, so the operation skips — and then migrates every user file to a key `extra="forbid"` rejects, with the tool reporting success.++### Reserved paths and names++The **reserved-path registry** is the record of every path, and every remapped-away enumerated value, that a ledger entry has ever removed. Reuse is refused outright, with no escape-hatch marker: an author who hits the rule picks another name.++**The registry is derived, not stored.** Every path a schema version removed is `fingerprint@N-1` minus `fingerprint@N`, so the whole registry is a walk of the golden chain, plus the declarations of any [pre-history entry](#pre-history-entries). A stored copy would be a second source of truth that could disagree with the chain it summarizes, and the only way to check it would be to recompute it — at which point the stored copy has no reader left.++The registry is diagnostic as much as preventive. When convergence or a transform golden fails, it is what turns the failure into a sentence naming the path and the schema version that reserved it.++> **A retired top-level table name is reserved permanently** (until a ledger squash, which drops entries and the reservations they own together). Reuse would make a removed path legal again and break premise one of replay neutrality directly.++## The fingerprint++The fingerprint is a normalized projection of a surface's model tree, checked in as a golden and recomputed on every pull request. Per TOML-addressable path it records:++- the type;+- whether the path is required;+- the enum member set, where the type is enumerated;+- the value in the surface's defaults layer, where one exists;+- an open-node marker, with the value-schema paths beneath it recorded under a `*` segment.++It is serialized in a stable order and is **deliberately not raw `model_json_schema()` output**, which moves for reasons that have nothing to do with our schema — reference layout, titles, ordering, the validation library's own version. A gate that cries wolf gets regenerated reflexively, and that is how a gate dies.++The same reasoning drives two normalizations that look like information loss and are not. A nested model records its type as `table` and an enumerated one as `enum`, with no class name anywhere: renaming a *Python class* changes nothing in anybody's file and must move nothing, while renaming a *field* or an enum *member* — the things a file actually contains — moves the fingerprint and is caught. Constraint metadata is stripped for the same reason, at every level of an annotation rather than only the outermost one, so a validation-library upgrade that reshapes a constraint object cannot move a golden.++An enumerated member set is collected from both sources that produce one: an enum class and a string literal type. To a TOML file they are the same thing — a closed set of legal spellings — and either can lose one.++Two shapes are recorded as terminal rather than descended into, because no operation can address what lies beneath them: an array of tables, which has no path segment syntax and no wildcard form, and a model reachable from itself, which has no finite path set at all.++What each recorded field is for: requiredness and enum members are load-bearing for coverage and for remap legality; defaults are recorded so that a flipped default is *visible in the regeneration diff*, but a default value **never gates on its own** — it changes no shape and no operation can address it. The one place a default is decisive is [a required path that has none](#coverage-every-schema-change-is-accounted-for).++## The checks++Checks with distinct failure meanings, so that a red gate says which guarantee broke. Placement follows the house rule: anything that regenerates and diffs lives in `make check` only, and anything with one obvious fix per failure joins `make agent-check`.++### Coverage — every schema change is accounted for++Recompute the fingerprint and diff it against the golden for the surface's current schema version:++| Diff | Verdict |+|---|---|+| Unchanged | Pass. |+| Paths or enum members added, or a type or default changed | Regenerate the golden. No version bump and no entry are demanded, because additive changes are absorbed by the defaults layer. |+| Any path or enum member removed or renamed | Require a schema version bump, an operation accounting for every removed path (wildcard paths included), and a remap or an `unsafe` entry for every removed enum member. Destinations are cross-checked against added paths. |++Alongside the diff, one standing invariant is checked on the new fingerprint itself, whether or not anything changed:++> **Every path a document must carry has to have a value beneath it.** A path that is required, and whose ancestors are all required, must have a value in its surface's defaults layer — otherwise it is breaking on the day it lands, and the refusal names the only remedy the vocabulary allows: give it a default. Wildcard paths are exempt by construction, since the keys beneath an open node are the user's and there is no single value to supply.++Stating it over every required path rather than only over newly added ones costs nothing — it holds across all three configuration surfaces today — and it catches the same defect arriving by the other door, a path that becomes required without gaining a default.++**Every entry is re-checked on every run**, not only the one being authored: the walk above runs for each link of the chain, `fingerprint@N-1` against `fingerprint@N`. An entry verified once at bump time and never again would silently stop matching its own diff the first time somebody edited it.++> **There is no escape hatch.** No `no_migration_needed` marker exists. A path that was never shipped to anyone still carries a one-line `delete_key`, which always skips and costs nothing — because "this one does not need an entry" is a judgment the next person cannot re-derive, and one such marker teaches everyone that the gate is negotiable.++### Convergence — replay is neutral on the witnesses++A full replay of a surface's ledger over each of its reference documents produces zero applied operations. The same target checks what else is cheap and unambiguous: the ledger parses into the migration-operation subset, versions are contiguous and match ids, every `safe` remap satisfies the legality rule, and no entry reintroduces a reserved path.++### Transform goldens — the operations say what the schema change did++Coverage proves an entry *exists* for every removal. Convergence proves replay is *harmless* on current files. Neither proves the entry is *right*, which is what the transform goldens close.++The regenerator writes, for each surface, the snapshot of its **current** schema version: `fingerprint@N` and the complete reference document `defaults@N`. A bump simply leaves the previous version's files behind, so the chain accumulates one frozen link per historical version.++> **The head link tracks; every link below it is frozen.** The snapshot for the current version is rewritten from live sources on every regeneration.++Freezing the head instead would rot. An additive change is absorbed by the defaults layer and needs no bump, so a head frozen at the last bump would drift from the live model and eventually stop validating against it — while the whole point of the last link is that it is what the current model reads. Only the sparse kit template is not snapshotted at all: it is a convergence and neutrality witness, and both read it live, so a snapshot of it would have no reader.++The check then asserts, pairwise over the complete-defaults family:++> `paths(apply(entry N, defaults@N−1)) == paths(defaults@N) − added_at_N`, where `added_at_N` is `fingerprint@N` minus `fingerprint@N−1`; plus value equality on every path an operation wrote; plus validation of the last link against the current model.++The comparator is **not byte-exact and not a subset test**, and both exclusions are deliberate. Byte-exactness fails on any honest version bump, because the same commit adds keys, edits comments and flips unrelated defaults. A subset test is blind to over-deletion — deleting a parent table where the entry meant to delete one child would pass. What survives is a comparator that tolerates additions, comment edits and default flips, and is red on wrong destinations, wrong remap targets, wrong order and over-deletion.++The sparse kit template is **not** in the chain: starter-template edits between bumps would go red under equality, and it exercises no operation the complete document does not. It remains a convergence and neutrality witness.++Pairwise checks compose by induction into the full chain — a replay from any historical snapshot lands on the current shape, because prefix entries skip on any snapshot at or past their version, their sources being permanently removed material.++### Testing the gates without coupling them to the configuration models++The surface registry is an **injected parameter, never a module constant**. The gates' own tests point it at small synthetic models with fixture ledgers, fixture fingerprints and fixture golden chains, so gate *behaviour* is tested against something that never moves; a single smoke test asserts that the real registry loads, the real goldens match and the real convergence holds.++Without this, every legitimate configuration change turns the gate's own suite red alongside the gate, and the fix everyone learns is "regenerate the goldens" — which is how a gate goes permanently green while catching nothing.++### The targets, and where the data lives++| Target | Alias | Aggregates | What it does |+|---|---|---|---|+| `make check-ledger` | `cl` | `check`, `agent-check` | The ledger parses into migration operations, versions are contiguous and match ids, legality and remap legality hold, no entry reintroduces a reserved path, and replay over both reference documents applies nothing. Reads checked-in data and regenerates nothing. |+| `make check-migration-schemas` | `cmig` | `check` | Fingerprints every surface, diffs against the goldens, demands a bump and full accounting for every removal, cross-checks destinations, and verifies the pairwise transform-golden chain. |+| `make up-migration-schemas` | `umig` | `up` | Regenerates the fingerprint goldens, and snapshots the reference documents into the transform-golden chain when a schema version bumped. |++Only `check-ledger` joins `agent-check`: it regenerates nothing and each failure has one obvious next action. `check-migration-schemas` is a golden check, and in the loop agents run constantly it would produce a fail-regenerate-fail cycle with no single right answer, so it stays in `check` alone.++The checked-in data it all reads:++```+pipelex/migration/ledgers/<surface-id>.toml the ledgers+pipelex/migration/goldens/<surface-id>/+ [email protected] the fingerprint at schema version N+ [email protected] the complete reference document at schema version N+```++Two files per version and nothing else. The fingerprint the coverage check diffs against is the chain's head link, `fingerprint@<current>`, rather than a separate always-current copy — one file with one writer cannot disagree with itself. The reserved-path registry is [derived from the chain](#reserved-paths-and-names), and the sparse kit template is read live rather than snapshotted.++## What the engine reports++Every surface produces the same plan model:++```+MigrationReport+ └── MigrationPlan (per file)+ surface, file_path+ blocked_reason → set when the file itself could not be processed at all+ steps[] → id, to_schema_version, title, breaking, safety, ops[], changelog+ blocked[] → id, reason, guidance+ unexplained[] → path, note+```++There is no `from_version` and no trusted-version concept: nothing skips, so nothing needs one. Because a replay walks every entry while usually changing little, the report renders what actually changed — it filters on `APPLIED`, routes `CONFLICT` into `blocked`, and carries the downgrade diagnosis in `unexplained`.++Two different things can be blocked, and the report keeps them apart. An **entry** is blocked when it cannot be applied — it is `unsafe`, or one of its operations came back `CONFLICT` — and it lands in `blocked[]` with the reason and its guidance, while the rest of the file's entries proceed. A **file** is blocked when it cannot be processed at all: it is unparseable, it is unwritable, or it changed on disk between the read and the write. That reason sits on the plan itself, and a blocked file never stops its siblings — every other file in the surface is migrated and reported normally.++> **No value read from a user's file is ever rendered** — not in the command's output, not in the structured plan, not in an error. Paths, operation kinds and ledger-supplied values carry everything a plan needs to say.++That is a mechanical rule rather than a list of credential-shaped key names, because such a list is a guess that eventually misses one. The single deliberate exception is the backup file, which contains the user's values by definition and is protected by inheriting the source file's mode rather than the process umask.++When migration is reported through a validation error, the error keeps `error_domain: "config"` and gains a structured `migration` block carrying the plan, the remedy and the diagnosis. Consumers branch on the presence of that block, never on wording. Following the workspace convention: the structured fields are the contract, and Markdown, exit codes and HTTP statuses are presentation.++## Boot tolerance++A stale configuration should warn, not stop the world — but only when the ledger can explain it.++```+load user files → deep-merge → validate (extra="forbid")+ ok → boot; no ledger touched, no tomlkit loaded+ fails, surface S+ → re-load S's user files with tomlkit+ → replay S's `safe` entries in memory, per file (writes nothing)+ → re-merge → re-validate+ ok → WARNING naming the file and the `pipelex migrate` remedy → boot+ fails → unsafe entries, CONFLICT, or unexplained paths → validation error+ with error_domain "config" and the `migration` block+```++The rules this encodes:++- **Boot never writes.** Nothing writes except the explicit `migrate` command; boot, `doctor` and validation detect and report.+- **Boot tolerates only what the ledger explains.** `unsafe` entries, conflicts and unexplained paths still fail the boot. Tolerance widens what starts, never what is silently accepted.+- **The healthy path is untouched.** The replay runs only on the failure path, so a current configuration never loads tomlkit and never reads a ledger. Replay neutrality is what makes the retry free when it does run.+- **One shared helper**, called by each configuration-surface loader — and that helper is also where `[meta] schema_version` is stripped. The strip belongs there and **not** in the generic TOML reader, which also reads `.mthds` files, backend definitions and the kit index, none of which reserve that key.++## Applying++> **Operations apply to the user's file, and a template is never the remedy.** "Delete your configuration and re-initialize it" is the failure this project exists to remove, not a fallback it may reach for: re-initializing throws away every choice the user made, and it is exactly what a structural change should not cost them.++### Serialization adds nothing++> **Migration serializes with `tomlkit.dumps` of the mutated document, and nothing else.**++The `.mthds` fix path follows its applier with a canonical reflow of the whole file. That is right for `.mthds` files, which are canonically formatted by CI, and wrong for a user-owned configuration, where a one-key rename must not also rewrite the user's spacing and layout. It is also load-bearing for the guarantees: byte-level replay neutrality only holds if serialization contributes no changes of its own.++### Backups++Always back up, before writing. Exactly one backup per file — a successful run replaces the previous one — named with a UTC timestamp, inheriting the source file's mode rather than the default umask, and with its path printed in the report. For files tracked in git, git remains the durable history; the backup covers the untracked ones and the moment between two commits.++### Per-file transactions++Each file is written transactionally and independently: snapshot, stage, atomic replace, restore on failure. A file that is unparseable, unwritable or changed during the run is reported as blocked while its siblings proceed. No run leaves a partially rewritten file behind.++## Limits you will meet++These are measured properties of the TOML library the engine uses, not aspirations. They are stated here because a user or an author will run into them, and being surprised by them is worse than being told.++- **Arrays of tables are unaddressable, and reserved.** An `[[entry]]` node is a list, and no `table_path` segment syntax reaches it or anything under it; the `*` wildcard has no array form. No configuration surface contains one today. If one ever appears, addressing it needs a new segment kind and a decision on the day — until then, an operation pointed at one resolves nothing and is reported as a guarded skip rather than raising.+- **A moved table loses its introducing comment.** A comment block written above a table is stored as trailing trivia of the *previous* sibling, not as part of the table it appears to introduce, so it does not travel with a move. Comments *inside* a moved table travel intact, including trailing comments on individual keys. The consequence is real: a file seeded from a heavily-commented template and then migrated ends up with banner comments labelling sections that have moved away. Nothing in the engine may rely on comment fidelity across a move, and the package's own files are corrected by hand rather than by migration.+- **A migration is not byte-minimal.** A rename adds a small amount of whitespace, and a renamed table that was written out of order across several chunks loses its own bare header while a plain table keeps it. Both forms are semantically identical, both are stable under replay, and neither accumulates — but a migration diff is not the minimal diff a human would have written.+- **A guarded skip is never an error.** Every operation whose target does not resolve reports itself skipped rather than raising. That guard is what makes always-replay possible, and it is why a misdirected operation is caught by the checks rather than by a crash on a user's machine.++## Authoring an entry++The gate says what is missing; you should not be composing entries by hand from a diff. The intended loop:++1. Make the schema change.+2. Run the coverage check. It refuses the change and names every removed path and enum member that lacks accounting, every destination that does not match an added path, and every added path that has no default.+3. Write the entry — or have the migration-authoring skill derive it from the fingerprint diff, bump the surface's schema version, regenerate the fingerprint golden and snapshot the transform goldens.+4. Add the changelog entry. The changelog and the ledger are deliberately separate artifacts saying the same thing to different readers; the release process is where they are checked against each other.++A release can never ship a moved schema without its entry: the release procedure runs the coverage check before the version bump, and refuses a bumped schema whose ledger has not moved with it.++## Related++- [Configuration Internals](contribute/configuration-defaults-and-overrides.md) — how the configuration layers merge, which this contract sits upstream of.+- [Drift Contracts](contribute/drift-contracts.md) — why the checks here are derived checks rather than review obligations: anything mechanizable becomes a derived check, and coverage, convergence, transform goldens and reserved-path checking all are.diff --git a/docs/under-the-hood/error-model.md b/docs/under-the-hood/error-model.mdindex c32535966..26c2420f1 100644--- a/docs/under-the-hood/error-model.md+++ b/docs/under-the-hood/error-model.md@@ -111,7 +111,9 @@ When a validation error has a deterministic remedy, its `ValidationErrorItem` ca- `description` — human-readable statement of the change.- `safety` — `safe` fixes may be auto-applied; `unsafe` ones require explicit opt-in.- `source` — the file the ops target, when known (multi-file libraries). An applier must only apply ops to the file they target.-- `ops[]` — the fix itself, as **semantic TOML patch ops** addressed by table path (`FixOpKind`: `set_key`, `ensure_table`, `delete_key`, `delete_table`, `rename_table_key`; each op's `table_path` follows the same conventions as the items' `field_path`). The ops are the machine contract; any rendered diff or `💡 Suggested fix:` line is presentation.+- `ops[]` — the fix itself, as **semantic TOML patch ops** addressed by table path (`FixOpKind`: `set_key`, `ensure_table`, `delete_key`, `delete_table`, `rename_table_key`, `move_key`, `remap_value`; each op's `table_path` follows the same conventions as the items' `field_path`). The ops are the machine contract; any rendered diff or `💡 Suggested fix:` line is presentation.++ The op vocabulary is a **discriminated union on `kind`**: one model per kind, each declaring exactly the fields its own semantics need and forbidding the rest, so `{"kind": "delete_key", …, "new_key": "x"}` is a parse error rather than a stray field the applier silently ignores. Two aliases are published from the same union — `FixOp`, every kind, which is what `ops[]` is typed as, and `MigrationOp`, the structural kinds only (`delete_key`, `delete_table`, `rename_table_key`, `move_key`, `remap_value`), which is what a configuration [migration ledger](../migration-ledger.md) is parsed against. The narrow alias is what keeps a materializing op — one that writes a value the file did not have — out of a ledger that is replayed over every user file on every run.The **fix planner** (`pipelex/pipeline/fixes/planner.py`) translates enriched typed error data into `SuggestedFix` payloads — pure functions keyed strictly on `error_type` + structured fields, never on message strings. Each rule fires only when its enrichment is present (set only at the raise sites that know the correct value), so the same error type raised elsewhere without enrichment is structurally suppressed. The planner runs inside `build_validation_error_items()`, so every consumer of the validation report — CLI, API, MCP — sees fixes with zero extra plumbing.diff --git a/mkdocs.yml b/mkdocs.ymlindex a04f19f66..94ba23f58 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -378,8 +378,13 @@ extra_css:# gotchas) referenced from the root `CLAUDE.md`. They are built and searchable but# intentionally kept out of the user-facing nav so they don't clutter the reading# flow for human readers of the docs site.+# - `migration-ledger.md` is the configuration-migration contract, written ahead of the+# engine it specifies. It stays out of the nav until `pipelex migrate` and boot+# tolerance ship, so the reading flow never advertises a command that does not exist+# yet; move it into the Project section in the same change that ships them.not_in_nav: |CLAUDE.md+ migration-ledger.mderrors/*.md!errors/index.md!errors/authoring-and-language.mddiff --git a/pipelex/cli/dev_cli/_dev_cli.py b/pipelex/cli/dev_cli/_dev_cli.pyindex b62c98d51..75f3b0c55 100644--- a/pipelex/cli/dev_cli/_dev_cli.py+++ b/pipelex/cli/dev_cli/_dev_cli.py@@ -14,6 +14,7 @@ from pipelex.cli.dev_cli.commands.check_config_sync_cmd import LeadingConfig, chfrom pipelex.cli.dev_cli.commands.check_gateway_models_cmd import check_gateway_models_cmdfrom pipelex.cli.dev_cli.commands.check_hub_layering_cmd import check_hub_layering_cmdfrom pipelex.cli.dev_cli.commands.check_keyword_only_cmd import check_keyword_only_cmd+from pipelex.cli.dev_cli.commands.check_migration_schemas_cmd import check_migration_schemas_cmdfrom pipelex.cli.dev_cli.commands.check_mthds_schema_cmd import check_mthds_schema_cmdfrom pipelex.cli.dev_cli.commands.check_rules_sync_cmd import check_rules_sync_cmdfrom pipelex.cli.dev_cli.commands.check_urls_cmd import DEFAULT_TIMEOUT, check_urls_cmd@@ -28,6 +29,7 @@ from pipelex.cli.dev_cli.commands.subject_grant_cmd import subject_grant_cmdfrom pipelex.cli.dev_cli.commands.sync_kit_configs_cmd import sync_kit_configs_cmdfrom pipelex.cli.dev_cli.commands.sync_main_config_cmd import SyncTarget, sync_main_config_cmdfrom pipelex.cli.dev_cli.commands.update_gateway_models_cmd import update_gateway_models_cmd+from pipelex.cli.dev_cli.commands.update_migration_schemas_cmd import update_migration_schemas_cmdfrom pipelex.runtime_hub import get_consolefrom pipelex.tools.misc.package_utils import get_package_version@@ -43,6 +45,7 @@ class PipelexDevCLI(TyperGroup):"check-gateway-models","check-hub-layering","check-keyword-only",+ "check-migration-schemas","check-mthds-schema","check-rules","check-urls",@@ -57,6 +60,7 @@ class PipelexDevCLI(TyperGroup):"sync-kit-configs","sync-main-config","update-gateway-models",+ "update-migration-schemas",]@override@@ -279,6 +283,48 @@ def check_mthds_schema_command(sys.exit(1)[email protected](name="check-migration-schemas", help="Verify that every configuration surface has accounted for its schema changes")+def check_migration_schemas_command(+ quiet: Annotated[+ bool, typer.Option("--quiet", "-q", help="Light output on success (single line); the full issue list still prints on failure")+ ] = False,+) -> None:+ """Verify that every configuration surface's schema changes are accounted for in its ledger."""+ try:+ check_migration_schemas_cmd(quiet=quiet)+ except (typer.Exit, typer.Abort):+ # Typer control-flow exits carry an intended exit code — not a failure. Let them through.+ raise+ except Exception: # noqa: BLE001+ # Dev CLI command root: print a traceback for any unexpected failure and exit non-zero.+ console = get_console()+ console.print()+ console.print("[bold red]Unexpected error occurred[/bold red]")+ console.print()+ console.print(Traceback())+ sys.exit(1)++[email protected](name="update-migration-schemas", help="Regenerate the migration fingerprint and defaults goldens")+def update_migration_schemas_command(+ quiet: Annotated[bool, typer.Option("--quiet", "-q", help="Output only a single status line")] = False,+) -> None:+ """Regenerate the migration golden chain for every configuration surface."""+ try:+ update_migration_schemas_cmd(quiet=quiet)+ except (typer.Exit, typer.Abort):+ # Typer control-flow exits carry an intended exit code — not a failure. Let them through.+ raise+ except Exception: # noqa: BLE001+ # Dev CLI command root: print a traceback for any unexpected failure and exit non-zero.+ console = get_console()+ console.print()+ console.print("[bold red]Unexpected error occurred[/bold red]")+ console.print()+ console.print(Traceback())+ sys.exit(1)++@app.command(name="check-hub-layering", help="Enforce the runtime_hub / interpreter_hub layering boundary")def check_hub_layering_command(quiet: Annotated[diff --git a/pipelex/cli/dev_cli/commands/check_migration_schemas_cmd.py b/pipelex/cli/dev_cli/commands/check_migration_schemas_cmd.pynew file mode 100644index 000000000..0b1abc989--- /dev/null+++ b/pipelex/cli/dev_cli/commands/check_migration_schemas_cmd.py@@ -0,0 +1,62 @@+"""Command to verify that every configuration surface has accounted for its schema changes.++This is the coverage half of the migration gate. It reads the checked-in ledgers and golden+chains, recomputes each surface's fingerprint, and fails when a schema change would leave a user's+file broken with nothing written down about how to repair it.++It lives in `make check` and deliberately **not** in `make agent-check`: it is a golden check, and+in the loop agents run constantly a fail-regenerate-fail cycle with no single right answer is how+a gate goes permanently green while catching nothing.+"""++import sys++from rich.markup import escape++from pipelex.migration.coverage import CoverageIssue, check_registry+from pipelex.migration.exceptions import MigrationError+from pipelex.migration.surfaces import build_config_surface_registry, packaged_migration_dir+from pipelex.runtime_hub import get_console+++def check_migration_schemas_cmd(*, quiet: bool = False) -> None:+ """Verify that every configuration surface's schema changes are accounted for.++ Args:+ quiet: If True, keep the success output to a single line (for Make targets / CI). Quiet+ only trims success output: a failure always lists every issue, because the Make+ targets invoke the check quietly and a red gate has to say what to do.+ """+ console = get_console()++ if not quiet:+ console.print()+ console.print("[bold]Checking migration schema coverage...[/bold]")+ console.print()++ registry = build_config_surface_registry()+ try:+ issues = check_registry(registry=registry, migration_dir=packaged_migration_dir())+ except MigrationError as exc:+ # An error is always loud — quiet only trims success output, never failures.+ console.print(f"[red]✗ Migration schema check: FAILED[/red] - {escape(str(exc))}")+ sys.exit(1)++ if not issues:+ surface_count = len(registry.surfaces)+ console.print(f"[green]✓ Migration schema check: PASSED[/green] - {surface_count} surfaces accounted for")+ return++ _print_issues(issues=issues)+ sys.exit(1)+++def _print_issues(*, issues: list[CoverageIssue]) -> None:+ console = get_console()+ console.print(f"[red]✗ Migration schema check: FAILED[/red] - {len(issues)} issues")+ console.print()+ for issue in issues:+ # Messages quote ledger text and path lists, both of which can look like Rich markup.+ console.print(f" [yellow]{escape(issue.surface_id)}[/yellow] [dim]({issue.kind})[/dim]")+ console.print(f" {escape(issue.message)}")+ console.print()diff --git a/pipelex/cli/dev_cli/commands/update_migration_schemas_cmd.py b/pipelex/cli/dev_cli/commands/update_migration_schemas_cmd.pynew file mode 100644index 000000000..743149edf--- /dev/null+++ b/pipelex/cli/dev_cli/commands/update_migration_schemas_cmd.py@@ -0,0 +1,51 @@+"""Command to regenerate the migration golden chain for every configuration surface.++Writes each surface's fingerprint and complete reference document for the schema version its+ledger currently declares. Older versions are never rewritten — a bump leaves the previous+version's snapshot behind as the frozen history the chain is made of.++The regeneration diff is the point. A fingerprint golden is checked in so that a reviewer sees,+line by line, which paths a change added, removed or renamed; running this command without reading+its diff throws away the only signal it produces.+"""++import sys++from rich.markup import escape++from pipelex.migration.exceptions import MigrationError+from pipelex.migration.snapshot import snapshot_registry+from pipelex.migration.surfaces import build_config_surface_registry, packaged_migration_dir+from pipelex.runtime_hub import get_console+++def update_migration_schemas_cmd(*, quiet: bool = False) -> None:+ """Regenerate the fingerprint and defaults goldens for every configuration surface.++ Args:+ quiet: If True, output only a single status line (for use in Make targets).+ """+ console = get_console()++ if not quiet:+ console.print()+ console.print("[bold]Updating migration schema goldens...[/bold]")+ console.print()++ registry = build_config_surface_registry()+ try:+ snapshots = snapshot_registry(registry=registry, migration_dir=packaged_migration_dir())+ except MigrationError as exc:+ console.print(f"[red]✗ Migration schema update: FAILED[/red] - {escape(str(exc))}")+ sys.exit(1)++ if not quiet:+ for snapshot in snapshots:+ console.print(+ f" [yellow]{escape(snapshot.surface_id)}[/yellow] [dim]schema {snapshot.schema_version}[/dim] - {snapshot.path_count} paths"+ )+ console.print(f" {escape(str(snapshot.fingerprint_path))}")+ console.print(f" {escape(str(snapshot.defaults_path))}")+ console.print()++ console.print(f"[green]✓ Migration schema update: DONE[/green] - {len(snapshots)} surfaces snapshotted")diff --git a/pipelex/migration/__init__.py b/pipelex/migration/__init__.pynew file mode 100644index 000000000..4b8af947e--- /dev/null+++ b/pipelex/migration/__init__.py@@ -0,0 +1,10 @@+"""The configuration-migration engine and the data it reads.++A **surface** is one family of user-owned TOML files with one schema version and one ledger.+This package holds the surface registry, the fingerprint that projects a surface's model tree+into a comparable shape, the ledger data models, and the coverage check that forces a schema+change to record what it did.++The contract this package implements is `docs/migration-ledger.md`, and it is normative — read+it before changing anything here.+"""diff --git a/pipelex/migration/coverage.py b/pipelex/migration/coverage.pynew file mode 100644index 000000000..065630802--- /dev/null+++ b/pipelex/migration/coverage.py@@ -0,0 +1,654 @@+"""The coverage check — the forcing function that makes a schema change record what it did.++This is the half of the gate that needs no applier and no engine: it reads the checked-in ledgers+and golden chains, recomputes each surface's fingerprint, and refuses a change that would leave a+user's file broken with nothing written down about how to repair it.++The centrepiece is the **sequential path state** walk. An entry's operations chain — a parent is+renamed and then keys inside it are renamed — so the intermediate paths belong to neither the old+fingerprint nor the new one, and no ordering avoids that. The walk therefore replays the entry+symbolically over the previous fingerprint's path set and compares the end state with the new+fingerprint. One walk answers every question at once:++- an operation whose source is absent from the state — or a `delete_table` aimed at a key — is+ **dead**: it can never fire, and the applier's guarded skip would report success forever;+- a rename or move onto a path the state already has is a **destination collision**: the applier+ refuses to clobber, so a valid old-schema file carrying both keys conflicts on every run;+- a path surviving the walk that the new fingerprint does not have is either an **unaccounted+ removal** or a **misspelled destination**, which is the failure the destination cross-check+ exists for: without it a typo passes coverage *and* convergence, then migrates every user file+ to a key `extra="forbid"` rejects, with the tool reporting success;+- a path of the new fingerprint that the walk deleted is **over-deletion** — an entry that dropped+ a parent table where it meant to drop one child;+- an enumerated member lost between the two fingerprints is looked up at the path the walk carried+ it to, so a member lost by a path the same entry renamed still demands its remap;+- everything the new fingerprint has and the walk does not is a genuine addition, which needs no+ operation because the defaults layer absorbs it.++See `docs/migration-ledger.md` → "Legality rules" and "The checks".+"""++from collections.abc import Sequence+from enum import StrEnum+from pathlib import Path++from pydantic import BaseModel, ConfigDict, Field++from pipelex.migration.fingerprint import PATH_SEPARATOR, TABLE_TYPE, PathFingerprint, SurfaceFingerprint, compute_fingerprint+from pipelex.migration.goldens import defaults_golden_path, read_fingerprint_golden+from pipelex.migration.ledger import MigrationEntry, MigrationLedger, MigrationSafety, load_ledger+from pipelex.migration.surfaces import Surface, SurfaceRegistry+from pipelex.suggested_fix import (+ WILDCARD_SEGMENT,+ DeleteKeyOp,+ DeleteTableOp,+ MigrationOp,+ MoveKeyOp,+ RemapValueOp,+ RenameTableKeyOp,+)+++class CoverageIssueKind(StrEnum):+ """Why a surface failed the gate. Distinct kinds so a red gate says which guarantee broke."""++ LEDGER_DISAGREES_WITH_REGISTRY = "ledger_disagrees_with_registry"+ GOLDEN_MISSING = "golden_missing"+ SNAPSHOT_PENDING = "snapshot_pending"+ FINGERPRINT_DRIFTED = "fingerprint_drifted"+ REMOVAL_NEEDS_A_BUMP = "removal_needs_a_bump"+ DEAD_OP = "dead_op"+ DESTINATION_OCCUPIED = "destination_occupied"+ UNACCOUNTED_PATH = "unaccounted_path"+ OVER_DELETION = "over_deletion"+ ENUM_MEMBER_NOT_REMAPPED = "enum_member_not_remapped"+ ILLEGAL_REMAP = "illegal_remap"+ REQUIRED_PATH_WITHOUT_DEFAULT = "required_path_without_default"+++class CoverageIssue(BaseModel):+ model_config = ConfigDict(frozen=True, extra="forbid")++ surface_id: str+ kind: CoverageIssueKind = Field(strict=False)+ message: str+++class FingerprintDiff(BaseModel):+ """What moved between two fingerprints of the same surface."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ added_paths: list[str] = Field(default_factory=list[str])+ removed_paths: list[str] = Field(default_factory=list[str])+ changed_paths: list[str] = Field(default_factory=list[str])+ added_enum_members: dict[str, list[str]] = Field(default_factory=dict[str, list[str]])+ removed_enum_members: dict[str, list[str]] = Field(default_factory=dict[str, list[str]])++ @property+ def is_empty(self) -> bool:+ return not (self.added_paths or self.removed_paths or self.changed_paths or self.added_enum_members or self.removed_enum_members)++ @property+ def has_removals(self) -> bool:+ return bool(self.removed_paths or self.removed_enum_members)+++def diff_fingerprints(*, before: SurfaceFingerprint, after: SurfaceFingerprint) -> FingerprintDiff:+ before_paths = before.path_names()+ after_paths = after.path_names()+ shared = sorted(before_paths & after_paths)++ added_enum_members: dict[str, list[str]] = {}+ removed_enum_members: dict[str, list[str]] = {}+ changed_paths: list[str] = []+ for path in shared:+ before_record = before.paths[path]+ after_record = after.paths[path]+ if before_record != after_record:+ changed_paths.append(path)+ before_members = set(before_record.enum_members or [])+ after_members = set(after_record.enum_members or [])+ if added := sorted(after_members - before_members):+ added_enum_members[path] = added+ if removed := sorted(before_members - after_members):+ removed_enum_members[path] = removed++ return FingerprintDiff(+ added_paths=sorted(after_paths - before_paths),+ removed_paths=sorted(before_paths - after_paths),+ changed_paths=changed_paths,+ added_enum_members=added_enum_members,+ removed_enum_members=removed_enum_members,+ )+++class PathState(BaseModel):+ """The symbolic state of a path set part-way through an entry's operations.++ Each live path is carried with the path it *originated from* in the previous fingerprint, so+ that an operation acting on a path some earlier operation renamed can still be attributed to+ the schema path it is really about.+ """++ model_config = ConfigDict(extra="forbid")++ origin_by_current: dict[str, str]++ @classmethod+ def make_from_fingerprint(cls, *, fingerprint: SurfaceFingerprint) -> "PathState":+ return cls(origin_by_current={path: path for path in fingerprint.path_names()})++ def current_paths(self) -> set[str]:+ return set(self.origin_by_current)++ def subtree_of(self, *, path: str) -> list[str]:+ prefix = path + PATH_SEPARATOR+ return [current for current in self.origin_by_current if current == path or current.startswith(prefix)]++ def drop_subtree(self, *, path: str) -> None:+ for current in self.subtree_of(path=path):+ del self.origin_by_current[current]++ def move_subtree(self, *, source: str, destination: str) -> None:+ moved = {destination + current[len(source) :]: self.origin_by_current[current] for current in self.subtree_of(path=source)}+ self.drop_subtree(path=source)+ self.origin_by_current.update(moved)++ def final_path_of_origin(self, *, origin: str) -> str | None:+ for current, recorded_origin in self.origin_by_current.items():+ if recorded_origin == origin:+ return current+ return None+++class RecordedRemap(BaseModel):+ """A remap that fired during the walk, attributed to the schema path it originated from."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ origin_path: str+ old_values: list[str]+ new_values: list[str]+++class EntryWalk(BaseModel):+ """What replaying one entry over the previous fingerprint's path set found out."""++ model_config = ConfigDict(extra="forbid")++ state: PathState+ """The end state."""++ dead_ops: list[str] = Field(default_factory=list[str])+ """Descriptions of operations that can never fire: the source is absent, or the operation+ kind cannot act on what the source is."""++ occupied_destinations: list[str] = Field(default_factory=list[str])+ """Descriptions of renames or moves onto a path the state already had. The applier refuses+ to clobber an occupied destination, so a file carrying both keys — a valid file at the old+ schema — would come back CONFLICT on every run."""++ remaps: list[RecordedRemap] = Field(default_factory=list[RecordedRemap])+ """The remaps that fired, attributed to the schema path they originated from."""+++def _joined(*, segments: Sequence[str]) -> str:+ return PATH_SEPARATOR.join(segments)+++def walk_entry(*, entry: MigrationEntry, before: SurfaceFingerprint) -> EntryWalk:+ """Replay an entry's operations symbolically over the previous fingerprint's path set."""+ walk = EntryWalk(state=PathState.make_from_fingerprint(fingerprint=before))++ for op in entry.ops:+ source = _op_source_path(op=op)+ if source not in walk.state.origin_by_current:+ walk.dead_ops.append(f"{op.kind} on '{source}' — no such path at schema version {before.schema_version}, so it can never fire")+ continue+ origin_record = before.paths[walk.state.origin_by_current[source]]+ if isinstance(op, DeleteTableOp) and not _is_table_like(record=origin_record):+ walk.dead_ops.append(f"{op.kind} on '{source}' — that path is a key, not a table, so the applier would skip it forever; use delete_key")+ continue+ _apply_op_to_state(op=op, source=source, walk=walk)++ return walk+++def _is_table_like(*, record: PathFingerprint) -> bool:+ """Whether the applier's `delete_table` finds a table at this path.++ An open node counts: `dict[str, X]` is a `[table]` in a file, whatever the fingerprint calls+ its value type.+ """+ return record.value_type == TABLE_TYPE or record.open_node+++def _op_source_path(*, op: MigrationOp) -> str:+ match op:+ case DeleteTableOp():+ return _joined(segments=op.table_path)+ case DeleteKeyOp() | RenameTableKeyOp() | MoveKeyOp() | RemapValueOp():+ return _joined(segments=[*op.table_path, op.key])+++def _apply_op_to_state(*, op: MigrationOp, source: str, walk: EntryWalk) -> None:+ match op:+ case DeleteKeyOp() | DeleteTableOp():+ walk.state.drop_subtree(path=source)+ case RenameTableKeyOp():+ _move_in_state(op=op, source=source, destination=_joined(segments=[*op.table_path, op.new_key]), walk=walk)+ case MoveKeyOp():+ _move_in_state(op=op, source=source, destination=_joined(segments=[*op.new_table_path, op.new_key]), walk=walk)+ case RemapValueOp():+ walk.remaps.append(+ RecordedRemap(+ origin_path=walk.state.origin_by_current[source],+ old_values=sorted(op.mapping),+ new_values=sorted(set(op.mapping.values())),+ )+ )+++def _move_in_state(*, op: MigrationOp, source: str, destination: str, walk: EntryWalk) -> None:+ """Move a subtree, recording a collision when the destination is already occupied.++ The move is performed either way, so that the end-state comparison stays meaningful and the+ collision is reported once rather than echoed as an unaccounted source.+ """+ if walk.state.subtree_of(path=destination):+ walk.occupied_destinations.append(+ f"{op.kind} moves '{source}' onto '{destination}', which the previous schema already has — "+ f"a file carrying both is refused as a conflict on every run, so a safe entry cannot do this"+ )+ walk.state.move_subtree(source=source, destination=destination)+++def check_entry_accounting(*, surface_id: str, entry: MigrationEntry, before: SurfaceFingerprint, after: SurfaceFingerprint) -> list[CoverageIssue]:+ """Verify that one entry says exactly what the fingerprint diff shows happened."""+ if entry.pre_history:+ # A removal that predates the first fingerprint has no observed diff to be accounted+ # against — that is what the flag means. Such an entry declares its own removed paths and+ # ships a hand-authored `before` document, and is verified against those by `check-ledger`+ # rather than here. Checking it against a fingerprint pair it never described would+ # produce a failure naming the wrong defect.+ return []++ issues: list[CoverageIssue] = []+ walk = walk_entry(entry=entry, before=before)++ for description in walk.dead_ops:+ issues.append(CoverageIssue(surface_id=surface_id, kind=CoverageIssueKind.DEAD_OP, message=f"entry '{entry.id}': {description}"))+ if entry.safety is MigrationSafety.SAFE:+ # An unsafe entry is reported and never applied, so its operations never conflict.+ for description in walk.occupied_destinations:+ issues.append(+ CoverageIssue(surface_id=surface_id, kind=CoverageIssueKind.DESTINATION_OCCUPIED, message=f"entry '{entry.id}': {description}")+ )++ after_paths = after.path_names()+ before_paths = before.path_names()+ end_paths = walk.state.current_paths()++ for path in sorted(end_paths - after_paths):+ issues.append(+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.UNACCOUNTED_PATH,+ message=(+ f"entry '{entry.id}': after replaying its operations, '{path}' is still there but schema version "+ f"{after.schema_version} has no such path — either a removal with no operation accounting for it, "+ f"or an operation whose destination is misspelled"+ ),+ )+ )++ for path in sorted((after_paths - end_paths) & before_paths):+ issues.append(+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.OVER_DELETION,+ message=(+ f"entry '{entry.id}': its operations remove '{path}', but schema version {after.schema_version} still has it — "+ f"an operation targets a parent where it meant to target one child"+ ),+ )+ )++ issues.extend(_check_enum_accounting(surface_id=surface_id, entry=entry, before=before, after=after, walk=walk))+ issues.extend(_check_remap_legality(surface_id=surface_id, entry=entry, after=after, walk=walk))+ return issues+++def _check_enum_accounting(+ *,+ surface_id: str,+ entry: MigrationEntry,+ before: SurfaceFingerprint,+ after: SurfaceFingerprint,+ walk: EntryWalk,+) -> list[CoverageIssue]:+ """Every enumerated spelling the entry loses must be remapped, following the path through the entry's own renames.++ Members are compared by *origin*: an enumerated path of the previous schema is looked up at+ the path the walk carried it to. A comparison over shared names would never look at a path+ the same entry renamed, and would let a lost member ride into the new schema unremapped.+ """+ if entry.safety is MigrationSafety.UNSAFE:+ # An unsafe entry is reported and never applied, so it is allowed to describe a change no+ # operation can make. That is what `unsafe` is for.+ return []+ remapped_by_origin: dict[str, set[str]] = {}+ for remap in walk.remaps:+ remapped_by_origin.setdefault(remap.origin_path, set()).update(remap.old_values)++ issues: list[CoverageIssue] = []+ for origin, before_record in before.paths.items():+ if not before_record.enum_members:+ continue+ final_path = walk.state.final_path_of_origin(origin=origin)+ after_record = after.paths.get(final_path) if final_path is not None else None+ if after_record is None:+ # The path does not survive into the new schema; the unaccounted-path or over-deletion+ # check has already said so in terms the author can act on.+ continue+ removed_members = set(before_record.enum_members) - set(after_record.enum_members or [])+ unaccounted = sorted(removed_members - remapped_by_origin.get(origin, set()))+ if unaccounted:+ issues.append(+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.ENUM_MEMBER_NOT_REMAPPED,+ message=(+ f"entry '{entry.id}': '{final_path}' no longer accepts {unaccounted} — a file carrying one of those "+ f"values no longer validates, so the entry needs a remap_value for each, or must be marked unsafe"+ ),+ )+ )+ return issues+++def _check_remap_legality(+ *,+ surface_id: str,+ entry: MigrationEntry,+ after: SurfaceFingerprint,+ walk: EntryWalk,+) -> list[CoverageIssue]:+ """A `safe` remap must be provably unable to fire on a current-valid file.++ That holds when the target is enumerated at the new schema and every old spelling in the+ mapping now falls outside its member set. When an old spelling remains legal — or the path is+ a free string, where staleness can never be proven from the schema — the applier cannot tell a+ stale value from a deliberate choice, and the entry has to be `unsafe`.+ """+ if entry.safety is MigrationSafety.UNSAFE:+ return []++ issues: list[CoverageIssue] = []+ for remap in walk.remaps:+ final_path = walk.state.final_path_of_origin(origin=remap.origin_path)+ record = after.paths.get(final_path) if final_path is not None else None+ if record is None:+ # The path the remap targets does not survive into the new schema; the unaccounted-path+ # or over-deletion check above has already said so in terms the author can act on.+ continue+ member_set = set(record.enum_members or [])+ if not member_set:+ issues.append(+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.ILLEGAL_REMAP,+ message=(+ f"entry '{entry.id}': remap_value on '{final_path}' is 'safe', but that path is not enumerated at "+ f"schema version {after.schema_version} — staleness cannot be proven from the schema, so the entry must be unsafe"+ ),+ )+ )+ continue+ still_legal = sorted(set(remap.old_values) & member_set)+ if still_legal:+ issues.append(+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.ILLEGAL_REMAP,+ message=(+ f"entry '{entry.id}': remap_value on '{final_path}' is 'safe', but {still_legal} are still legal values at "+ f"schema version {after.schema_version} — a user who chose one deliberately would have it rewritten"+ ),+ )+ )+ unknown_new = sorted(set(remap.new_values) - member_set)+ if unknown_new:+ issues.append(+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.ILLEGAL_REMAP,+ message=(+ f"entry '{entry.id}': remap_value on '{final_path}' rewrites values to {unknown_new}, which schema version "+ f"{after.schema_version} does not accept — every migrated file would be rejected, with the tool reporting success"+ ),+ )+ )+ return issues+++def check_defaults_layer(*, surface_id: str, fingerprint: SurfaceFingerprint) -> list[CoverageIssue]:+ """Every path a document must carry has to have a value beneath it.++ This is the standing form of the additive rule. A key we add is supplied by the defaults+ layer, so an old file that lacks it still validates — but only if the defaults layer really+ supplies it. A required path with no default is breaking on the day it lands, and the only+ remedy the vocabulary allows is to give it one: writing a value into the user's file is a+ semantic edit dressed up as a fix, which is why the materializing operations are excluded from+ the migration vocabulary outright.++ Wildcard paths are exempt by construction: the keys beneath an open node are the user's, so+ there is no single value for the defaults layer to supply.+ """+ issues: list[CoverageIssue] = []+ for path, record in fingerprint.paths.items():+ if WILDCARD_SEGMENT in path.split(PATH_SEPARATOR):+ continue+ if record.value_type == TABLE_TYPE or record.default is not None:+ continue+ if not fingerprint.is_effectively_required(path=path):+ continue+ issues.append(+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.REQUIRED_PATH_WITHOUT_DEFAULT,+ message=(+ f"'{path}' is required but the defaults layer supplies no value for it, so a file written before it "+ f"existed no longer validates — give it a default rather than writing one into the user's file"+ ),+ )+ )+ return issues+++def check_surface(*, surface: Surface, migration_dir: Path) -> list[CoverageIssue]:+ """Run the whole coverage check over one surface."""+ surface_id = surface.surface_id+ ledger = load_ledger(migration_dir=migration_dir, surface_id=surface_id)+ issues = _check_ledger_agrees_with_registry(surface=surface, ledger=ledger)++ current_version = ledger.surface.current_schema_version+ live = compute_fingerprint(+ surface_id=surface_id,+ schema_version=current_version,+ config_model=surface.config_model,+ defaults_document=surface.read_defaults_document(),+ )+ issues.extend(check_defaults_layer(surface_id=surface_id, fingerprint=live))+ issues.extend(_check_stored_links(surface_id=surface_id, ledger=ledger, live=live, migration_dir=migration_dir))+ issues.extend(_check_head_link(surface_id=surface_id, current_version=current_version, live=live, migration_dir=migration_dir))+ issues.extend(_check_head_defaults_document(surface=surface, current_version=current_version, migration_dir=migration_dir))+ return issues+++def _check_head_defaults_document(*, surface: Surface, current_version: int, migration_dir: Path) -> list[CoverageIssue]:+ """The head link's reference document must still be the document it is a copy of.++ `defaults@<current>.toml` is a checked-in copy of a live source — the packaged TOML, or the+ document the model's own defaults synthesize — and the fingerprint diff cannot see it drift:+ an edited comment or a flipped value inside an unchanged path moves the file and not the path+ set. Left unchecked, two checked-in copies of the same document quietly disagree, and the one+ a later phase applies migrations to is the stale one.+ """+ path = defaults_golden_path(migration_dir=migration_dir, surface_id=surface.surface_id, schema_version=current_version)+ if not path.exists():+ # The head fingerprint check already asks for the snapshot; saying it twice adds nothing.+ return []+ if path.read_text(encoding="utf-8") == surface.render_reference_document():+ return []+ return [+ CoverageIssue(+ surface_id=surface.surface_id,+ kind=CoverageIssueKind.FINGERPRINT_DRIFTED,+ message=(+ f"the reference document at {path.name} no longer matches the surface's defaults layer — "+ f"run `make umig` so the golden records the change"+ ),+ )+ ]+++def _check_ledger_agrees_with_registry(*, surface: Surface, ledger: MigrationLedger) -> list[CoverageIssue]:+ """The ledger's own `[surface]` block must describe the surface the registry declares.++ Both halves are hand-written and both are consumed as truth — the ledger's when a migration+ walks a directory, the registry's when a gate fingerprints a model — so a disagreement between+ them is a silent mis-migration waiting for the day the two readers meet.+ """+ mismatches = [+ (label, declared, recorded)+ for label, declared, recorded in (+ ("id", surface.surface_id, ledger.surface.id),+ ("base_file", surface.base_file, ledger.surface.base_file),+ ("tier_glob", surface.tier_glob, ledger.surface.tier_glob),+ )+ if declared != recorded+ ]+ return [+ CoverageIssue(+ surface_id=surface.surface_id,+ kind=CoverageIssueKind.LEDGER_DISAGREES_WITH_REGISTRY,+ message=f"the ledger says {label} = {recorded!r} but the registry says {declared!r}",+ )+ for label, declared, recorded in mismatches+ ]+++def _check_stored_links(*, surface_id: str, ledger: MigrationLedger, live: SurfaceFingerprint, migration_dir: Path) -> list[CoverageIssue]:+ """Check every entry against the fingerprint pair it claims to explain.++ Every link is re-checked on every run, not only the one being authored. An entry verified once+ at bump time and never again would silently stop matching its own diff the first time somebody+ edited it.+ """+ issues: list[CoverageIssue] = []+ for entry in ledger.migration:+ version = entry.to_schema_version+ before = read_fingerprint_golden(migration_dir=migration_dir, surface_id=surface_id, schema_version=version - 1)+ if before is None:+ issues.append(+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.GOLDEN_MISSING,+ message=f"entry '{entry.id}' has nothing to be checked against: no fingerprint golden for schema version {version - 1}",+ )+ )+ continue+ after = _after_fingerprint_for_link(+ surface_id=surface_id,+ version=version,+ current_version=ledger.surface.current_schema_version,+ live=live,+ migration_dir=migration_dir,+ )+ if after is None:+ issues.append(+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.GOLDEN_MISSING,+ message=(+ f"entry '{entry.id}' cannot be checked: no fingerprint golden for schema version {version}, "+ f"and it is not the current version, so nothing live can stand in for it"+ ),+ )+ )+ continue+ issues.extend(check_entry_accounting(surface_id=surface_id, entry=entry, before=before, after=after))+ return issues+++def _after_fingerprint_for_link(+ *,+ surface_id: str,+ version: int,+ current_version: int,+ live: SurfaceFingerprint,+ migration_dir: Path,+) -> SurfaceFingerprint | None:+ """The fingerprint an entry migrates *to*, stored or live.++ Only the head link may fall back to the live fingerprint, and only because it has no snapshot+ until `update-migration-schemas` runs — which is what makes the gate red *before* a bump is+ snapshotted rather than after. A missing golden anywhere below the head is a broken chain, and+ substituting the live fingerprint there would silently compare an old entry against today's+ models and call the mismatch the entry's fault.+ """+ stored = read_fingerprint_golden(migration_dir=migration_dir, surface_id=surface_id, schema_version=version)+ if stored is not None:+ return stored+ return live if version == current_version else None+++def _check_head_link(*, surface_id: str, current_version: int, live: SurfaceFingerprint, migration_dir: Path) -> list[CoverageIssue]:+ golden = read_fingerprint_golden(migration_dir=migration_dir, surface_id=surface_id, schema_version=current_version)+ if golden is None:+ return [+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.SNAPSHOT_PENDING,+ message=(+ f"schema version {current_version} has never been snapshotted — run `make umig` to write its fingerprint and defaults goldens"+ ),+ )+ ]++ diff = diff_fingerprints(before=golden, after=live)+ if diff.is_empty:+ return []+ if diff.has_removals:+ removed = diff.removed_paths + [f"{path}: {members}" for path, members in diff.removed_enum_members.items()]+ return [+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.REMOVAL_NEEDS_A_BUMP,+ message=(+ f"the models no longer have {removed}, which breaks every file that carries them. Bump "+ f"current_schema_version to {current_version + 1}, add the entry '{surface_id}@{current_version + 1}' "+ f"accounting for each, then run `make umig`"+ ),+ )+ ]+ return [+ CoverageIssue(+ surface_id=surface_id,+ kind=CoverageIssueKind.FINGERPRINT_DRIFTED,+ message=(+ f"the fingerprint moved additively — added {diff.added_paths or '[]'}, changed {diff.changed_paths or '[]'}. "+ f"Nothing breaks and no entry is needed; run `make umig` so the golden records it"+ ),+ )+ ]+++def check_registry(*, registry: SurfaceRegistry, migration_dir: Path) -> list[CoverageIssue]:+ """Run the coverage check over every surface in a registry."""+ issues: list[CoverageIssue] = []+ for surface in registry.surfaces:+ issues.extend(check_surface(surface=surface, migration_dir=migration_dir))+ return issuesdiff --git a/pipelex/migration/exceptions.py b/pipelex/migration/exceptions.pynew file mode 100644index 000000000..3aca4dde3--- /dev/null+++ b/pipelex/migration/exceptions.py@@ -0,0 +1,26 @@+from pipelex.base_exceptions import ErrorDomain, PipelexError+++class MigrationError(PipelexError):+ """Base for every failure raised by the configuration-migration engine."""++ error_domain = ErrorDomain.CONFIG+ _declared_title = "Migration error"+++class MigrationRegistryError(MigrationError):+ """The surface registry is inconsistent, or names a surface that does not exist."""++ _declared_title = "Migration registry error"+++class MigrationLedgerError(MigrationError):+ """A ledger file is missing, unparseable, or internally inconsistent."""++ _declared_title = "Migration ledger error"+++class MigrationGoldenError(MigrationError):+ """A checked-in golden is missing or unreadable, so no verdict can be produced."""++ _declared_title = "Migration golden error"diff --git a/pipelex/migration/fingerprint.py b/pipelex/migration/fingerprint.pynew file mode 100644index 000000000..1aa100eeb--- /dev/null+++ b/pipelex/migration/fingerprint.py@@ -0,0 +1,295 @@+"""The fingerprint — a normalized projection of a surface's model tree.++The fingerprint is what the coverage gate diffs, so what it records and what it deliberately+ignores is the whole design. It records, per TOML-addressable path: the type, whether the path is+required within its parent, the enumerated member set where there is one, the value the surface's+defaults layer supplies, and an open-node marker with the value-schema paths beneath it recorded+under a `*` segment.++It is **deliberately not raw `model_json_schema()` output**, which moves for reasons that have+nothing to do with our schema — reference layout, titles, ordering, the validation library's own+version. A gate that cries wolf gets regenerated reflexively, and that is how a gate dies. The+same reasoning drives two normalizations that look like information loss and are not: a nested+model renders as `table` and an enum as `enum`, so renaming a *Python class* moves nothing, while+renaming a *field* or an enum *member* — the things a user's file actually contains — moves the+fingerprint and is caught.++See `docs/migration-ledger.md` → "The fingerprint".+"""++import types+from collections.abc import Mapping, Sequence+from enum import Enum+from typing import Annotated, Any, Literal, Union, cast, get_args, get_origin++from pydantic import BaseModel, ConfigDict, Field++from pipelex.suggested_fix import WILDCARD_SEGMENT++PATH_SEPARATOR = "."++TABLE_TYPE = "table"+"""The rendering of a nested model. Class names are deliberately not recorded — see the module docstring."""++ENUM_TYPE = "enum"+"""The rendering of an enumerated type. The member set carries the shape; the class name does not."""+++class PathFingerprint(BaseModel):+ """What the fingerprint records about one TOML-addressable path."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ value_type: str+ required: bool+ """Required *within its parent*. Whether the path is required in a document also depends on+ whether its ancestors are present — see `is_effectively_required` on the surface fingerprint."""++ enum_members: list[str] | None = None+ default: Any | None = None+ """The value the surface's defaults layer supplies, or `None` for none recorded. TOML has no+ null, so an absent default and a null default are the same thing and need no distinction."""++ open_node: bool = False+ """A mapping from arbitrary user-owned keys to a value schema. The keys belong to the user;+ the value schema belongs to us and is recorded beneath a `*` segment."""+++class SurfaceFingerprint(BaseModel):+ """A whole surface's model tree, projected and stably ordered."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ surface_id: str+ schema_version: int+ paths: dict[str, PathFingerprint] = Field(default_factory=dict[str, PathFingerprint])++ def path_names(self) -> set[str]:+ return set(self.paths)++ def is_effectively_required(self, *, path: str) -> bool:+ """Whether a document that the defaults layer feeds must carry this path.++ A path nested under an optional table is not required of a document that omits the table,+ so requiredness only propagates through ancestors that are themselves required.+ """+ segments = path.split(PATH_SEPARATOR)+ for depth in range(1, len(segments) + 1):+ ancestor = self.paths.get(PATH_SEPARATOR.join(segments[:depth]))+ if ancestor is None or not ancestor.required:+ return False+ return True+++def compute_fingerprint(+ *,+ surface_id: str,+ schema_version: int,+ config_model: type[BaseModel],+ defaults_document: dict[str, Any],+) -> SurfaceFingerprint:+ """Project a surface's model tree against its defaults document."""+ collected: dict[str, PathFingerprint] = {}+ _walk_model(+ config_model=config_model,+ prefix=(),+ defaults=defaults_document,+ ancestry=(config_model,),+ collected=collected,+ )+ return SurfaceFingerprint(+ surface_id=surface_id,+ schema_version=schema_version,+ paths={path: collected[path] for path in sorted(collected)},+ )+++def _walk_model(+ *,+ config_model: type[BaseModel],+ prefix: tuple[str, ...],+ defaults: dict[str, Any] | None,+ ancestry: tuple[type[BaseModel], ...],+ collected: dict[str, PathFingerprint],+) -> None:+ for field_name, field_info in config_model.model_fields.items():+ _record_field(+ path=(*prefix, field_name),+ annotation=field_info.annotation,+ required=field_info.is_required(),+ defaults_value=_defaults_value(defaults=defaults, key=field_name),+ ancestry=ancestry,+ collected=collected,+ )+++def _record_field(+ *,+ path: tuple[str, ...],+ annotation: Any,+ required: bool,+ defaults_value: Any,+ ancestry: tuple[type[BaseModel], ...],+ collected: dict[str, PathFingerprint],+) -> None:+ resolved = _strip_annotated(annotation=annotation)+ nested_model = _as_nested_model(annotation=resolved)+ open_value_type = _as_open_mapping_value(annotation=resolved)+ dotted = PATH_SEPARATOR.join(path)++ if nested_model is not None:+ # A table's own default is not recorded: every child records its own, and recording the+ # whole subtree again would bloat the golden without making any diff more legible.+ collected[dotted] = PathFingerprint(value_type=TABLE_TYPE, required=required)+ if nested_model in ancestry:+ # A model reachable from itself would walk forever. Nothing in the configuration tree+ # is recursive today; this is the guard that keeps a future one from hanging the gate.+ return+ _walk_model(+ config_model=nested_model,+ prefix=path,+ defaults=_as_mapping(value=defaults_value),+ ancestry=(*ancestry, nested_model),+ collected=collected,+ )+ return++ collected[dotted] = PathFingerprint(+ value_type=_render_type(annotation=resolved),+ required=required,+ enum_members=_collect_enum_members(annotation=resolved),+ default=_json_safe(value=defaults_value),+ open_node=open_value_type is not None,+ )++ if open_value_type is not None:+ # The keys under an open node are the user's and cannot be enumerated; the value schema+ # is ours, and an operation may address it through the `*` segment.+ _record_field(+ path=(*path, WILDCARD_SEGMENT),+ annotation=open_value_type,+ required=True,+ defaults_value=None,+ ancestry=ancestry,+ collected=collected,+ )+++def _defaults_value(*, defaults: dict[str, Any] | None, key: str) -> Any:+ if defaults is None:+ return None+ return defaults.get(key)+++def _as_mapping(*, value: Any) -> dict[str, Any] | None:+ if isinstance(value, dict):+ return value # pyright: ignore[reportUnknownVariableType]+ return None+++def _strip_annotated(*, annotation: Any) -> Any:+ """Remove `Annotated[...]` wrappers and a `| None` union member.++ Optionality is already carried by requiredness, and unwrapping it here is what lets an+ optional nested table (`ndjson: NdjsonTracingConfig | None`) be walked as the table it is.+ """+ while get_origin(annotation) is Annotated:+ annotation = get_args(annotation)[0]+ if _is_union(annotation=annotation):+ members = [member for member in get_args(annotation) if member is not types.NoneType]+ if len(members) == 1:+ return _strip_annotated(annotation=members[0])+ return annotation+++def _is_union(*, annotation: Any) -> bool:+ return get_origin(annotation) in {Union, types.UnionType}+++def _as_nested_model(*, annotation: Any) -> type[BaseModel] | None:+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):+ return annotation+ return None+++def _as_open_mapping_value(*, annotation: Any) -> Any:+ """The value schema of an open mapping, or `None` when the annotation is not one.++ `dict[str, X]` and `Mapping[str, X]` are the same shape to a file — a table whose keys are the+ user's — so both are open nodes.+ """+ if get_origin(annotation) not in {dict, Mapping}:+ return None+ args = get_args(annotation)+ if len(args) != 2:+ return None+ return args[1]+++def _render_type(*, annotation: Any) -> str:+ # Strip at every level, not just the top one: a union member carrying its own constraint+ # (`Annotated[int, Field(ge=1)] | Literal["unbounded"]`) would otherwise render the+ # constraint object into the golden, where a pydantic upgrade could move it.+ annotation = _strip_annotated(annotation=annotation)+ if annotation is Any:+ return "any"+ if annotation is types.NoneType:+ return "none"+ if _is_union(annotation=annotation):+ return " | ".join(_render_type(annotation=member) for member in get_args(annotation))+ if get_origin(annotation) is Literal:+ return "literal"+ origin = get_origin(annotation)+ if origin is not None:+ args = get_args(annotation)+ rendered_args = ", ".join(_render_type(annotation=arg) for arg in args)+ return f"{_render_bare(annotation=origin)}[{rendered_args}]" if rendered_args else _render_bare(annotation=origin)+ return _render_bare(annotation=annotation)+++def _render_bare(*, annotation: Any) -> str:+ if isinstance(annotation, type):+ bare_type: type[Any] = annotation+ if issubclass(bare_type, BaseModel):+ return TABLE_TYPE+ if issubclass(bare_type, Enum):+ return ENUM_TYPE+ return bare_type.__name__.lower()+ name: Any = getattr(annotation, "__name__", None)+ return name.lower() if isinstance(name, str) else "unknown"+++def _collect_enum_members(*, annotation: Any) -> list[str] | None:+ """Every enumerated spelling reachable in the annotation, sorted and deduplicated.++ Both sources count: an `Enum` class and a string `Literal`. They are the same thing to a TOML+ file — a closed set of legal spellings — and either can lose a member, which is the removal+ the coverage gate demands a remap for.+ """+ members: set[str] = set()+ _gather_enum_members(annotation=annotation, members=members)+ return sorted(members) if members else None+++def _gather_enum_members(*, annotation: Any, members: set[str]) -> None:+ if isinstance(annotation, type) and issubclass(annotation, Enum):+ members.update(str(member.value) for member in annotation)+ return+ if get_origin(annotation) is Literal:+ members.update(str(arg) for arg in get_args(annotation) if isinstance(arg, str))+ return+ for arg in get_args(annotation):+ _gather_enum_members(annotation=arg, members=members)+++def _json_safe(*, value: Any) -> Any:+ """Coerce a defaults-layer value into something a golden file can hold verbatim."""+ if value is None or isinstance(value, (str, int, float, bool)):+ return value+ if isinstance(value, dict):+ typed_mapping = cast("dict[Any, Any]", value)+ return {str(key): _json_safe(value=item) for key, item in typed_mapping.items()}+ if isinstance(value, Sequence):+ typed_sequence = cast("Sequence[Any]", value)+ return [_json_safe(value=item) for item in typed_sequence]+ return str(value)diff --git a/pipelex/migration/goldens.py b/pipelex/migration/goldens.pynew file mode 100644index 000000000..8ae09dae7--- /dev/null+++ b/pipelex/migration/goldens.py@@ -0,0 +1,96 @@+"""The golden chain — the checked-in snapshots the coverage gate reads and regenerates.++One directory per surface, holding two files per schema version:++ pipelex/migration/goldens/<surface-id>/[email protected]+ pipelex/migration/goldens/<surface-id>/[email protected]++**The head link tracks; every link below it is frozen.** `update-migration-schemas` rewrites the+snapshot for the surface's *current* version from live sources on every run, and a version bump+simply leaves the previous version's files behind as history. Freezing the head instead would+rot: an additive change absorbed by the defaults layer needs no bump, so a head frozen at the last+bump would drift from the live model and eventually stop validating against it — while the whole+point of the last link is that it is what the current model reads.++There is no separate reserved-path registry file. Every path a schema version removed is+`fingerprint@N-1` minus `fingerprint@N`, so the registry is *derived* from this chain (plus the+declarations of any pre-history entry) rather than stored beside it. A stored copy could disagree+with the chain it summarizes, and the only way to check it would be to recompute it.+"""++import json+from pathlib import Path++from pipelex.migration.exceptions import MigrationGoldenError+from pipelex.migration.fingerprint import SurfaceFingerprint++GOLDENS_DIR_NAME = "goldens"+FINGERPRINT_STEM = "fingerprint"+DEFAULTS_STEM = "defaults"+VERSION_MARKER = "@"+++def goldens_dir(*, migration_dir: Path, surface_id: str) -> Path:+ return migration_dir / GOLDENS_DIR_NAME / surface_id+++def fingerprint_golden_path(*, migration_dir: Path, surface_id: str, schema_version: int) -> Path:+ return goldens_dir(migration_dir=migration_dir, surface_id=surface_id) / f"{FINGERPRINT_STEM}{VERSION_MARKER}{schema_version}.json"+++def defaults_golden_path(*, migration_dir: Path, surface_id: str, schema_version: int) -> Path:+ return goldens_dir(migration_dir=migration_dir, surface_id=surface_id) / f"{DEFAULTS_STEM}{VERSION_MARKER}{schema_version}.toml"+++def read_fingerprint_golden(*, migration_dir: Path, surface_id: str, schema_version: int) -> SurfaceFingerprint | None:+ """The stored fingerprint for one schema version, or `None` when it has never been snapshotted.++ Raises:+ MigrationGoldenError: the file cannot be read as a fingerprint, or its body describes a+ different surface or schema version than its filename claims — a copied or misnamed+ link must not be compared as the link it stands in for.+ """+ path = fingerprint_golden_path(migration_dir=migration_dir, surface_id=surface_id, schema_version=schema_version)+ if not path.exists():+ return None+ try:+ fingerprint = SurfaceFingerprint.model_validate_json(path.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ msg = f"unreadable fingerprint golden at {path}: {exc}"+ raise MigrationGoldenError(msg) from exc+ if fingerprint.surface_id != surface_id or fingerprint.schema_version != schema_version:+ msg = (+ f"fingerprint golden at {path} describes surface '{fingerprint.surface_id}' at schema version "+ f"{fingerprint.schema_version}, not '{surface_id}' at schema version {schema_version} as its name says"+ )+ raise MigrationGoldenError(msg)+ return fingerprint+++def render_fingerprint_golden(*, fingerprint: SurfaceFingerprint) -> str:+ """Serialize a fingerprint for checking in.++ Indented and newline-terminated so that a regeneration produces a diff a reviewer can read+ line by line — the diff *is* the gate's output, and a single-line JSON blob would hide the one+ changed path among two hundred unchanged ones.+ """+ payload = fingerprint.model_dump(mode="json", exclude_none=True)+ return json.dumps(payload, indent=2, ensure_ascii=False) + "\n"+++def write_fingerprint_golden(*, migration_dir: Path, fingerprint: SurfaceFingerprint) -> Path:+ path = fingerprint_golden_path(+ migration_dir=migration_dir,+ surface_id=fingerprint.surface_id,+ schema_version=fingerprint.schema_version,+ )+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(render_fingerprint_golden(fingerprint=fingerprint), encoding="utf-8")+ return path+++def write_defaults_golden(*, migration_dir: Path, surface_id: str, schema_version: int, document: str) -> Path:+ path = defaults_golden_path(migration_dir=migration_dir, surface_id=surface_id, schema_version=schema_version)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(document, encoding="utf-8")+ return pathdiff --git a/pipelex/migration/goldens/pipelex-config/[email protected] b/pipelex/migration/goldens/pipelex-config/[email protected]new file mode 100644index 000000000..abaf4f65f--- /dev/null+++ b/pipelex/migration/goldens/pipelex-config/[email protected]@@ -0,0 +1,452 @@+++[pipelex]++[pipelex.storage_config]+is_fetch_remote_content_enabled = true+is_upload_local_content_enabled = true+method = "local" # local, in_memory, s3, gcp++[pipelex.storage_config.local]+uri_format = "{primary_id}/{secondary_id}/{hash}.{extension}"+local_storage_path = ".pipelex/storage"++[pipelex.storage_config.in_memory]+uri_format = "{primary_id}/{secondary_id}/{hash}.{extension}"++[pipelex.storage_config.s3]+uri_format = "{primary_id}/{secondary_id}/{hash}.{extension}"+bucket_name = ""+region = ""+signed_urls_lifespan_seconds = 3600++[pipelex.storage_config.gcp]+uri_format = "{primary_id}/{secondary_id}/{hash}.{extension}"+bucket_name = ""+project_id = ""+signed_urls_lifespan_seconds = 3600++[pipelex.secrets_config]+method = "env" # env (built-in); an external plugin may add e.g. vault++[pipelex.observer_config]+observer_dir = "results/observer"++[pipelex.scan_config]+excluded_dirs = [+ ".venv",+ "venv",+ "env",+ ".env",+ "virtualenv",+ ".virtualenv",+ ".git",+ "__pycache__",+ ".pytest_cache",+ ".mypy_cache",+ ".ruff_cache",+ "node_modules",+ "results",+]++[pipelex.builder_config]+fix_loop_max_attempts = 10+default_output_dir = "."+default_bundle_file_name = "bundle"+default_directory_base_name = "pipeline"++[pipelex.reporting_config]+is_log_costs_to_console = true+is_generate_cost_report_file_enabled = false+cost_report_dir_path = "reports"+cost_report_base_name = "cost_report"+cost_report_extension = "csv"+cost_report_unit_scale = 1.0++####################################################################################################+# Log config+####################################################################################################++[pipelex.log_config]+default_log_level = "INFO"+# console_log_target controls the RichHandler used by the logging system (log.debug/info/...).+# Logs are diagnostics → stderr.+console_log_target = "stderr"+# console_print_target controls the Console returned by get_console(), used for banners,+# deck notices, and the main `pipelex` CLI's data tables (`show backends`, `show models`,+# `which`, `doctor`). Tables are data the user pipes to a file → stdout.+# Note: the agent CLI (`pipelex-agent`) emits its actual JSON/markdown results via bare+# builtin `print(...)` to sys.stdout, bypassing Rich entirely — so this knob does NOT+# affect the agent CLI data channel. The agent CLI factory additionally forces both+# targets to stderr internally to keep its stdout strictly reserved for the success+# envelope (see `_AGENT_CLI_STDERR_CONSOLE_OVERRIDES` in `agent_cli_factory.py`).+console_print_target = "stdout"+is_console_logging_enabled = true++json_logs_indent = 4+presentation_line_width = 120+silenced_problem_ids = ["azure_openai_no_stream_options"]+caller_info_template = "file_line"+is_caller_info_enabled = false++log_mode = "rich"++poor_loggers = []+generic_poor_logger = "#poor-log"++[pipelex.log_config.package_log_levels]+# for logger names, the dots "." have been replaced by "-" to avoid toml parsing issues+# TODO: use quotes to re-enable names with dots+anthropic = "INFO"+asyncio = "INFO"+botocore = "INFO"+botocore-credentials = "WARNING"+google = "INFO"+httpx = "WARNING"+httpcore = "INFO"+openai = "INFO"+instructor = "INFO"+urllib3-connectionpool = "INFO"+urllib3-util-retry = "INFO"++pipelex = "INFO"+++[pipelex.log_config.rich_log_config]+is_show_time = false+is_show_level = true+is_link_path_enabled = true+is_markup_enabled = true+highlighter_name = "json"+is_rich_tracebacks = true+is_tracebacks_word_wrap = true+is_tracebacks_show_locals = false+tracebacks_suppress = []+keywords_to_hilight = []++[pipelex.aws_config]+api_key_method = "env"+bedrock_access_variant = "aws_access"++####################################################################################################+# Cogt inference config+####################################################################################################++[cogt]+transport_max_retries = 2++[cogt.model_deck_config]+is_model_fallback_enabled = true+missing_presets_reaction = "log"++[cogt.llm_config]+default_max_images = 100+is_structure_prompt_enabled = true+is_dump_text_prompts_enabled = false+is_dump_response_text_enabled = false+schema_reask_max_attempts = 3++[cogt.llm_config.instructor_config]+is_dump_kwargs_enabled = false+is_dump_response_enabled = false+is_dump_error_enabled = false++[cogt.llm_config.openai_config.effort_to_level_map]+none = "none"+minimal = "minimal"+low = "low"+medium = "medium"+high = "high"+xhigh = "xhigh"+max = "xhigh"++[cogt.llm_config.anthropic_config]+structured_output_timeout_seconds = 1200++[cogt.llm_config.anthropic_config.effort_to_level_map]+none = "disabled"+minimal = "low"+low = "low"+medium = "medium"+high = "high"+xhigh = "xhigh"+max = "max"++[cogt.llm_config.google_config.effort_to_level_map]+none = "disabled"+minimal = "minimal"+low = "low"+medium = "medium"+high = "high"+xhigh = "high"+max = "high"++[cogt.llm_config.mistral_config.effort_to_level_map]+none = "disabled"+minimal = "reasoning"+low = "reasoning"+medium = "reasoning"+high = "reasoning"+xhigh = "reasoning"+max = "reasoning"++[cogt.llm_config.effort_to_budget_maps.anthropic]+none = 0 # Required by validator; unreachable at runtime (level map gates NONE as disabled before budget lookup)+minimal = 512+low = 1024+medium = 5000+high = 16384+xhigh = 32768+max = 65536++[cogt.llm_config.effort_to_budget_maps.gemini]+none = 0 # Required by validator; unreachable at runtime (level map gates NONE as disabled before budget lookup)+minimal = 512+low = 1024+medium = 5000+high = 16384+xhigh = 32768+max = 65536++[cogt.llm_config.generic_templates]+output_structure_prompt = """+++---+The instance we want to generate will be for the following class:+{{ class_structure_str }}++DO NOT create information.+If some information is not present for an attribute, output the default value or None according to the attribute definition.+"""++structuring_prompt = """+Read the following text carefully and produce the requested structured output from it.++---+{{ text }}+"""++####################################################################################################+# Image generation config+####################################################################################################++[cogt.img_gen_config.img_gen_job_config]+is_sync_mode = false++[cogt.img_gen_config.img_gen_param_defaults]+nb_steps = 28 # 28 is a good default for Flux, possible values are [1,2,4,8] for SDXL Lightning+quality = "low"+aspect_ratio = "square" # "square", "landscape_4_3", "landscape_3_2", "landscape_16_9", "landscape_21_9", "landscape_4_1", "landscape_8_1", "portrait_3_4", "portrait_2_3", "portrait_9_16", "portrait_9_21", "portrait_1_4", "portrait_1_8"+guidance_scale = 2.5+background = "auto"+is_moderated = true+safety_tolerance = 5+is_raw = false+seed = "auto"++[cogt.img_gen_config.quality_to_steps_maps]+flux = { "low" = 14, "medium" = 28, "high" = 56 }+sdxl_lightning = { "low" = 2, "medium" = 4, "high" = 8 }+qwen_image = { "low" = 10, "medium" = 20, "high" = 28 }++####################################################################################################+# Extract config+####################################################################################################++[cogt.extract_config]+default_page_views_dpi = 72++####################################################################################################+# Gateway test config+####################################################################################################++[cogt.gateway_test_config.config_id_substitutions]+# this is an empty dict, it's only used by Pipelex staff to override the ¨Pipelex Gateway¨ config+# in order to test new model integrations or debug issues with the Gateway++####################################################################################################+# Templating config+####################################################################################################++[pipelex.templating_config]+default_templating_style = { tag_style = "xml" }++####################################################################################################+# Pipe run config+####################################################################################################++[pipelex.pipe_run_config]+pipe_stack_limit = 20++####################################################################################################+# PipeFunc config+####################################################################################################++[pipelex.pipe_func_config]+# PipeFunc execution mode, selected from the PipeFuncExecutorRegistry the plugins populate. "direct"+# (core) imports and runs customer functions in this process; "daytona" (our Daytona sandbox plugin)+# runs them in a remote box. Any non-"direct" mode carries customer PipeFunc code as source text and+# executes it only inside an isolated sandbox, never imported here.+execution_mode = "direct"++####################################################################################################+# Pipeline execution config+####################################################################################################++[pipelex.pipeline_execution_config]+is_normalize_data_urls_to_storage = true+is_mock_inputs = false+is_generate_graph = true+is_generate_usage = true++# Bounded fan-out concurrency for PipeBatch: at most this many branches run at once.+# A modest default keeps a large workload (one pipe over many items) from overwhelming+# asyncio, memory, and provider rate limits. Set to "unbounded" to disable the bound.+max_concurrency = 8++[pipelex.pipeline_execution_config.graph_config]++[pipelex.pipeline_execution_config.graph_config.data_inclusion]+stuff_json_content = true+stuff_text_content = true+stuff_html_content = true+error_stack_traces = true+pipe_and_concept_registry = true++[pipelex.pipeline_execution_config.graph_config.graphs_inclusion]+graphspec_json = true+mermaidflow_mmd = true+mermaidflow_html = true+reactflow_html = true++[pipelex.pipeline_execution_config.graph_config.mermaid_config]+direction = "left_to_right"+is_include_data_edges = true+is_include_contains_edges = false+is_include_selected_outcome_edges = true+is_show_stuff_codes = false++[pipelex.pipeline_execution_config.graph_config.mermaid_config.style]+theme = "dark"++[pipelex.pipeline_execution_config.graph_config.reactflow_config]+is_use_cdn = true+layout_direction = "left_to_right"+nodesep = 50+ranksep = 30+edge_type = "bezier"+initial_zoom = 1.0+pan_to_top = true+default_title = "Pipelex Graph"+# Forwarded to mthds-ui as `showControllers`: when true, controller pipes (PipeSequence,+# PipeParallel, PipeCondition, PipeBatch) render as grouping containers around their children;+# when false, they collapse out of the graph and edges connect stuff nodes directly.+show_batch_controller = true++[pipelex.pipeline_execution_config.graph_config.reactflow_config.style]+theme = "dark"+palette = "dracula"++####################################################################################################+# Tracing config (event log for distributed tracing across workers)+####################################################################################################++[pipelex.tracing_config]+is_enabled = true+backend = "ndjson"++[pipelex.tracing_config.ndjson]+traces_dir = ".pipelex/traces"++[pipelex.tracing_config.dynamodb]+table_name = ""+region = ""++####################################################################################################+# Dry run config+####################################################################################################++[pipelex.dry_run_config]+text_gen_truncate_length = 256+nb_list_items = 3+nb_extract_pages = 4+allowed_to_fail_pipes = [+ "failing_pipelines.infinite_loop_1", # Loop but only for testing purposes — matched on the namespaced pipe_ref+]+image_urls = [+ "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/fashion/fashion_photo_1.jpg",+ "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/fashion/fashion_photo_2.png",+]++####################################################################################################+# MTHDS config+####################################################################################################++[pipelex.mthds_config.inline_tables]+spaces_inside_curly_braces = true++[pipelex.mthds_config.strings]+prefer_literal = false+force_multiline = false+length_limit_to_multiline = 100+ensure_trailing_newline = true+ensure_leading_blank_line = true++[pipelex.mthds_config.concepts]+structure_field_ordering = [+ "type",+ "concept_ref",+ "item_type",+ "item_concept_ref",+ "description",+ "choices",+ "required",+]++[pipelex.mthds_config.pipes]+field_ordering = ["type", "description", "inputs", "output"]++####################################################################################################+# Migration config+####################################################################################################++[migration.migration_maps.config]+definition = "description"+ocr_config = "extract_config"+ocr = "extract"+img_gen = "model"+llm_handle = "model"+llm = "model"+llm_to_structure = "model_to_structure"+task_queue = "default_task_queue"++[migration.migration_maps.mthds]+img_gen = "model"+ocr = "model"+llm_handle = "model"+llm = "model"+llm_to_structure = "model_to_structure"+llm_skill = "llm_talent"+img_gen_skill = "img_gen_talent"+extract_skill = "extract_talent"+parallels = "branches"+++####################################################################################################+# Kit Config+####################################################################################################++[pipelex.kit_config]+# Agent rule files to install (used by `pipelex-dev kit rules`)+# Each entry is one of: "cursor", "agents", "claude"+# - "cursor" installs .cursor/rules/*.mdc files (cannot be combined with others)+# - "agents" / "claude" install AGENTS.md / CLAUDE.md respectively — both can be listed together+preferred_agent_targets = ["claude", "agents"]++[migration.migration_maps.telemetry]++[plugins]+# Names of discovered plugins to skip at startup (a denylist). Discovery is the+# source of truth for which plugins are present; this only turns one off.+disabled = []diff --git a/pipelex/migration/goldens/pipelex-config/[email protected] b/pipelex/migration/goldens/pipelex-config/[email protected]new file mode 100644index 000000000..0e235137f--- /dev/null+++ b/pipelex/migration/goldens/pipelex-config/[email protected]@@ -0,0 +1,1481 @@+{+ "surface_id": "pipelex-config",+ "schema_version": 1,+ "paths": {+ "cogt": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.extract_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.extract_config.default_page_views_dpi": {+ "value_type": "int",+ "required": true,+ "default": 72,+ "open_node": false+ },+ "cogt.gateway_test_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.gateway_test_config.config_id_substitutions": {+ "value_type": "dict[str, str]",+ "required": true,+ "default": {},+ "open_node": true+ },+ "cogt.gateway_test_config.config_id_substitutions.*": {+ "value_type": "str",+ "required": true,+ "open_node": false+ },+ "cogt.img_gen_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_job_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_job_config.is_sync_mode": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults.aspect_ratio": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "landscape_16_9",+ "landscape_21_9",+ "landscape_3_2",+ "landscape_4_1",+ "landscape_4_3",+ "landscape_8_1",+ "portrait_1_4",+ "portrait_1_8",+ "portrait_2_3",+ "portrait_3_4",+ "portrait_9_16",+ "portrait_9_21",+ "square"+ ],+ "default": "square",+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults.background": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "auto",+ "opaque",+ "transparent"+ ],+ "default": "auto",+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults.guidance_scale": {+ "value_type": "float",+ "required": true,+ "default": 2.5,+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults.is_moderated": {+ "value_type": "bool",+ "required": false,+ "default": true,+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults.is_raw": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults.nb_steps": {+ "value_type": "int",+ "required": false,+ "default": 28,+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults.quality": {+ "value_type": "enum",+ "required": false,+ "enum_members": [+ "high",+ "low",+ "medium"+ ],+ "default": "low",+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults.safety_tolerance": {+ "value_type": "int",+ "required": true,+ "default": 5,+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults.seed": {+ "value_type": "int | literal",+ "required": true,+ "enum_members": [+ "auto"+ ],+ "default": "auto",+ "open_node": false+ },+ "cogt.img_gen_config.img_gen_param_defaults.size": {+ "value_type": "enum | table",+ "required": false,+ "enum_members": [+ "0.5k",+ "1k",+ "2k",+ "4k"+ ],+ "open_node": false+ },+ "cogt.img_gen_config.quality_to_steps_maps": {+ "value_type": "dict[str, dict[str, int]]",+ "required": true,+ "default": {+ "flux": {+ "low": 14,+ "medium": 28,+ "high": 56+ },+ "sdxl_lightning": {+ "low": 2,+ "medium": 4,+ "high": 8+ },+ "qwen_image": {+ "low": 10,+ "medium": 20,+ "high": 28+ }+ },+ "open_node": true+ },+ "cogt.img_gen_config.quality_to_steps_maps.*": {+ "value_type": "dict[str, int]",+ "required": true,+ "open_node": true+ },+ "cogt.img_gen_config.quality_to_steps_maps.*.*": {+ "value_type": "int",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.anthropic_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.anthropic_config.effort_to_level_map": {+ "value_type": "dict[str, str]",+ "required": true,+ "default": {+ "none": "disabled",+ "minimal": "low",+ "low": "low",+ "medium": "medium",+ "high": "high",+ "xhigh": "xhigh",+ "max": "max"+ },+ "open_node": true+ },+ "cogt.llm_config.anthropic_config.effort_to_level_map.*": {+ "value_type": "str",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.anthropic_config.structured_output_timeout_seconds": {+ "value_type": "int",+ "required": true,+ "default": 1200,+ "open_node": false+ },+ "cogt.llm_config.default_max_images": {+ "value_type": "int",+ "required": true,+ "default": 100,+ "open_node": false+ },+ "cogt.llm_config.effort_to_budget_maps": {+ "value_type": "dict[str, dict[str, int]]",+ "required": true,+ "default": {+ "anthropic": {+ "none": 0,+ "minimal": 512,+ "low": 1024,+ "medium": 5000,+ "high": 16384,+ "xhigh": 32768,+ "max": 65536+ },+ "gemini": {+ "none": 0,+ "minimal": 512,+ "low": 1024,+ "medium": 5000,+ "high": 16384,+ "xhigh": 32768,+ "max": 65536+ }+ },+ "open_node": true+ },+ "cogt.llm_config.effort_to_budget_maps.*": {+ "value_type": "dict[str, int]",+ "required": true,+ "open_node": true+ },+ "cogt.llm_config.effort_to_budget_maps.*.*": {+ "value_type": "int",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.generic_templates": {+ "value_type": "dict[str, str]",+ "required": true,+ "default": {+ "output_structure_prompt": "\n\n---\nThe instance we want to generate will be for the following class:\n{{ class_structure_str }}\n\nDO NOT create information.\nIf some information is not present for an attribute, output the default value or None according to the attribute definition.\n",+ "structuring_prompt": "Read the following text carefully and produce the requested structured output from it.\n\n---\n{{ text }}\n"+ },+ "open_node": true+ },+ "cogt.llm_config.generic_templates.*": {+ "value_type": "str",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.google_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.google_config.effort_to_level_map": {+ "value_type": "dict[str, str]",+ "required": true,+ "default": {+ "none": "disabled",+ "minimal": "minimal",+ "low": "low",+ "medium": "medium",+ "high": "high",+ "xhigh": "high",+ "max": "high"+ },+ "open_node": true+ },+ "cogt.llm_config.google_config.effort_to_level_map.*": {+ "value_type": "str",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.instructor_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.instructor_config.is_dump_error_enabled": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "cogt.llm_config.instructor_config.is_dump_kwargs_enabled": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "cogt.llm_config.instructor_config.is_dump_response_enabled": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "cogt.llm_config.is_dump_response_text_enabled": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "cogt.llm_config.is_dump_text_prompts_enabled": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "cogt.llm_config.is_structure_prompt_enabled": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "cogt.llm_config.mistral_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.mistral_config.effort_to_level_map": {+ "value_type": "dict[str, str]",+ "required": true,+ "default": {+ "none": "disabled",+ "minimal": "reasoning",+ "low": "reasoning",+ "medium": "reasoning",+ "high": "reasoning",+ "xhigh": "reasoning",+ "max": "reasoning"+ },+ "open_node": true+ },+ "cogt.llm_config.mistral_config.effort_to_level_map.*": {+ "value_type": "str",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.openai_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.openai_config.effort_to_level_map": {+ "value_type": "dict[str, str]",+ "required": true,+ "default": {+ "none": "none",+ "minimal": "minimal",+ "low": "low",+ "medium": "medium",+ "high": "high",+ "xhigh": "xhigh",+ "max": "xhigh"+ },+ "open_node": true+ },+ "cogt.llm_config.openai_config.effort_to_level_map.*": {+ "value_type": "str",+ "required": true,+ "open_node": false+ },+ "cogt.llm_config.schema_reask_max_attempts": {+ "value_type": "int",+ "required": true,+ "default": 3,+ "open_node": false+ },+ "cogt.model_deck_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "cogt.model_deck_config.is_model_fallback_enabled": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "cogt.model_deck_config.missing_presets_reaction": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "log",+ "none",+ "raise"+ ],+ "default": "log",+ "open_node": false+ },+ "cogt.transport_max_retries": {+ "value_type": "int",+ "required": true,+ "default": 2,+ "open_node": false+ },+ "migration": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "migration.migration_maps": {+ "value_type": "dict[str, dict[str, str]]",+ "required": true,+ "default": {+ "config": {+ "definition": "description",+ "ocr_config": "extract_config",+ "ocr": "extract",+ "img_gen": "model",+ "llm_handle": "model",+ "llm": "model",+ "llm_to_structure": "model_to_structure",+ "task_queue": "default_task_queue"+ },+ "mthds": {+ "img_gen": "model",+ "ocr": "model",+ "llm_handle": "model",+ "llm": "model",+ "llm_to_structure": "model_to_structure",+ "llm_skill": "llm_talent",+ "img_gen_skill": "img_gen_talent",+ "extract_skill": "extract_talent",+ "parallels": "branches"+ },+ "telemetry": {}+ },+ "open_node": true+ },+ "migration.migration_maps.*": {+ "value_type": "dict[str, str]",+ "required": true,+ "open_node": true+ },+ "migration.migration_maps.*.*": {+ "value_type": "str",+ "required": true,+ "open_node": false+ },+ "pipelex": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.aws_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.aws_config.api_key_method": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "env",+ "secret_provider"+ ],+ "default": "env",+ "open_node": false+ },+ "pipelex.aws_config.bedrock_access_variant": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "aws_access",+ "bedrock_token"+ ],+ "default": "aws_access",+ "open_node": false+ },+ "pipelex.builder_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.builder_config.default_bundle_file_name": {+ "value_type": "str",+ "required": true,+ "default": "bundle",+ "open_node": false+ },+ "pipelex.builder_config.default_directory_base_name": {+ "value_type": "str",+ "required": true,+ "default": "pipeline",+ "open_node": false+ },+ "pipelex.builder_config.default_output_dir": {+ "value_type": "str",+ "required": true,+ "default": ".",+ "open_node": false+ },+ "pipelex.builder_config.fix_loop_max_attempts": {+ "value_type": "int",+ "required": true,+ "default": 10,+ "open_node": false+ },+ "pipelex.dry_run_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.dry_run_config.allowed_to_fail_pipes": {+ "value_type": "list[str]",+ "required": false,+ "default": [+ "failing_pipelines.infinite_loop_1"+ ],+ "open_node": false+ },+ "pipelex.dry_run_config.image_urls": {+ "value_type": "list[str]",+ "required": true,+ "default": [+ "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/fashion/fashion_photo_1.jpg",+ "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/fashion/fashion_photo_2.png"+ ],+ "open_node": false+ },+ "pipelex.dry_run_config.nb_extract_pages": {+ "value_type": "int",+ "required": true,+ "default": 4,+ "open_node": false+ },+ "pipelex.dry_run_config.nb_list_items": {+ "value_type": "int",+ "required": true,+ "default": 3,+ "open_node": false+ },+ "pipelex.dry_run_config.text_gen_truncate_length": {+ "value_type": "int",+ "required": true,+ "default": 256,+ "open_node": false+ },+ "pipelex.kit_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.kit_config.preferred_agent_targets": {+ "value_type": "list[enum]",+ "required": true,+ "enum_members": [+ "agents",+ "claude",+ "cursor"+ ],+ "default": [+ "claude",+ "agents"+ ],+ "open_node": false+ },+ "pipelex.log_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.log_config.caller_info_template": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "file_func",+ "file_line",+ "file_line_func",+ "func",+ "func_line",+ "func_module",+ "func_module_line"+ ],+ "default": "file_line",+ "open_node": false+ },+ "pipelex.log_config.console_log_target": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "file",+ "stderr",+ "stdout"+ ],+ "default": "stderr",+ "open_node": false+ },+ "pipelex.log_config.console_print_target": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "file",+ "stderr",+ "stdout"+ ],+ "default": "stdout",+ "open_node": false+ },+ "pipelex.log_config.default_log_level": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "CRITICAL",+ "DEBUG",+ "DEV",+ "ERROR",+ "INFO",+ "OFF",+ "VERBOSE",+ "WARNING"+ ],+ "default": "INFO",+ "open_node": false+ },+ "pipelex.log_config.generic_poor_logger": {+ "value_type": "str",+ "required": true,+ "default": "#poor-log",+ "open_node": false+ },+ "pipelex.log_config.is_caller_info_enabled": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "pipelex.log_config.is_console_logging_enabled": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.log_config.json_logs_indent": {+ "value_type": "int",+ "required": true,+ "default": 4,+ "open_node": false+ },+ "pipelex.log_config.log_mode": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "poor",+ "rich"+ ],+ "default": "rich",+ "open_node": false+ },+ "pipelex.log_config.package_log_levels": {+ "value_type": "dict[str, enum]",+ "required": true,+ "enum_members": [+ "CRITICAL",+ "DEBUG",+ "DEV",+ "ERROR",+ "INFO",+ "OFF",+ "VERBOSE",+ "WARNING"+ ],+ "default": {+ "anthropic": "INFO",+ "asyncio": "INFO",+ "botocore": "INFO",+ "botocore-credentials": "WARNING",+ "google": "INFO",+ "httpx": "WARNING",+ "httpcore": "INFO",+ "openai": "INFO",+ "instructor": "INFO",+ "urllib3-connectionpool": "INFO",+ "urllib3-util-retry": "INFO",+ "pipelex": "INFO"+ },+ "open_node": true+ },+ "pipelex.log_config.package_log_levels.*": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "CRITICAL",+ "DEBUG",+ "DEV",+ "ERROR",+ "INFO",+ "OFF",+ "VERBOSE",+ "WARNING"+ ],+ "open_node": false+ },+ "pipelex.log_config.poor_loggers": {+ "value_type": "list[str]",+ "required": true,+ "default": [],+ "open_node": false+ },+ "pipelex.log_config.presentation_line_width": {+ "value_type": "int",+ "required": true,+ "default": 120,+ "open_node": false+ },+ "pipelex.log_config.rich_log_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.log_config.rich_log_config.highlighter_name": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "json",+ "repr"+ ],+ "default": "json",+ "open_node": false+ },+ "pipelex.log_config.rich_log_config.is_link_path_enabled": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.log_config.rich_log_config.is_markup_enabled": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.log_config.rich_log_config.is_rich_tracebacks": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.log_config.rich_log_config.is_show_level": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.log_config.rich_log_config.is_show_time": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "pipelex.log_config.rich_log_config.is_tracebacks_show_locals": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "pipelex.log_config.rich_log_config.is_tracebacks_word_wrap": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.log_config.rich_log_config.keywords_to_hilight": {+ "value_type": "list[str]",+ "required": true,+ "default": [],+ "open_node": false+ },+ "pipelex.log_config.rich_log_config.tracebacks_suppress": {+ "value_type": "list[str]",+ "required": true,+ "default": [],+ "open_node": false+ },+ "pipelex.log_config.silenced_problem_ids": {+ "value_type": "list[str]",+ "required": true,+ "default": [+ "azure_openai_no_stream_options"+ ],+ "open_node": false+ },+ "pipelex.mthds_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.mthds_config.concepts": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.mthds_config.concepts.structure_field_ordering": {+ "value_type": "list[str]",+ "required": true,+ "default": [+ "type",+ "concept_ref",+ "item_type",+ "item_concept_ref",+ "description",+ "choices",+ "required"+ ],+ "open_node": false+ },+ "pipelex.mthds_config.inline_tables": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.mthds_config.inline_tables.spaces_inside_curly_braces": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.mthds_config.pipes": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.mthds_config.pipes.field_ordering": {+ "value_type": "list[str]",+ "required": true,+ "default": [+ "type",+ "description",+ "inputs",+ "output"+ ],+ "open_node": false+ },+ "pipelex.mthds_config.strings": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.mthds_config.strings.ensure_leading_blank_line": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.mthds_config.strings.ensure_trailing_newline": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.mthds_config.strings.force_multiline": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "pipelex.mthds_config.strings.length_limit_to_multiline": {+ "value_type": "int",+ "required": true,+ "default": 100,+ "open_node": false+ },+ "pipelex.mthds_config.strings.prefer_literal": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "pipelex.observer_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.observer_config.observer_dir": {+ "value_type": "str",+ "required": true,+ "default": "results/observer",+ "open_node": false+ },+ "pipelex.pipe_func_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.pipe_func_config.execution_mode": {+ "value_type": "str",+ "required": true,+ "default": "direct",+ "open_node": false+ },+ "pipelex.pipe_run_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.pipe_run_config.pipe_stack_limit": {+ "value_type": "int",+ "required": true,+ "default": 20,+ "open_node": false+ },+ "pipelex.pipeline_execution_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.data_inclusion": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.data_inclusion.error_stack_traces": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.data_inclusion.pipe_and_concept_registry": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.data_inclusion.stuff_html_content": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.data_inclusion.stuff_json_content": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.data_inclusion.stuff_text_content": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.graphs_inclusion": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.graphs_inclusion.graphspec_json": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.graphs_inclusion.mermaidflow_html": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.graphs_inclusion.mermaidflow_mmd": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.graphs_inclusion.reactflow_html": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.mermaid_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.mermaid_config.direction": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "left_to_right",+ "top_down"+ ],+ "default": "left_to_right",+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.mermaid_config.is_include_contains_edges": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.mermaid_config.is_include_data_edges": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.mermaid_config.is_include_selected_outcome_edges": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.mermaid_config.is_show_stuff_codes": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.mermaid_config.style": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.mermaid_config.style.theme": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "base",+ "dark",+ "default",+ "forest",+ "neutral"+ ],+ "default": "dark",+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.default_title": {+ "value_type": "str",+ "required": true,+ "default": "Pipelex Graph",+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.edge_type": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "bezier",+ "smoothstep",+ "step",+ "straight"+ ],+ "default": "bezier",+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.initial_zoom": {+ "value_type": "float",+ "required": true,+ "default": 1.0,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.is_use_cdn": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.layout_direction": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "left_to_right",+ "top_down"+ ],+ "default": "left_to_right",+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.nodesep": {+ "value_type": "int",+ "required": true,+ "default": 50,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.pan_to_top": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.ranksep": {+ "value_type": "int",+ "required": true,+ "default": 30,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.show_batch_controller": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.style": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.style.palette": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "dracula",+ "yellow_blue"+ ],+ "default": "dracula",+ "open_node": false+ },+ "pipelex.pipeline_execution_config.graph_config.reactflow_config.style.theme": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "dark",+ "light",+ "system"+ ],+ "default": "dark",+ "open_node": false+ },+ "pipelex.pipeline_execution_config.is_generate_graph": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.is_generate_usage": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.is_mock_inputs": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.is_normalize_data_urls_to_storage": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.pipeline_execution_config.max_concurrency": {+ "value_type": "int | literal",+ "required": true,+ "enum_members": [+ "unbounded"+ ],+ "default": 8,+ "open_node": false+ },+ "pipelex.reporting_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.reporting_config.cost_report_base_name": {+ "value_type": "str",+ "required": true,+ "default": "cost_report",+ "open_node": false+ },+ "pipelex.reporting_config.cost_report_dir_path": {+ "value_type": "str",+ "required": true,+ "default": "reports",+ "open_node": false+ },+ "pipelex.reporting_config.cost_report_extension": {+ "value_type": "str",+ "required": true,+ "default": "csv",+ "open_node": false+ },+ "pipelex.reporting_config.cost_report_unit_scale": {+ "value_type": "float",+ "required": true,+ "default": 1.0,+ "open_node": false+ },+ "pipelex.reporting_config.is_generate_cost_report_file_enabled": {+ "value_type": "bool",+ "required": true,+ "default": false,+ "open_node": false+ },+ "pipelex.reporting_config.is_log_costs_to_console": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.scan_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.scan_config.excluded_dirs": {+ "value_type": "frozenset[str]",+ "required": true,+ "default": [+ ".venv",+ "venv",+ "env",+ ".env",+ "virtualenv",+ ".virtualenv",+ ".git",+ "__pycache__",+ ".pytest_cache",+ ".mypy_cache",+ ".ruff_cache",+ "node_modules",+ "results"+ ],+ "open_node": false+ },+ "pipelex.secrets_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.secrets_config.method": {+ "value_type": "str",+ "required": true,+ "default": "env",+ "open_node": false+ },+ "pipelex.storage_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.storage_config.gcp": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "pipelex.storage_config.gcp.bucket_name": {+ "value_type": "str",+ "required": true,+ "default": "",+ "open_node": false+ },+ "pipelex.storage_config.gcp.project_id": {+ "value_type": "str",+ "required": true,+ "default": "",+ "open_node": false+ },+ "pipelex.storage_config.gcp.signed_urls_lifespan_seconds": {+ "value_type": "int | literal",+ "required": true,+ "enum_members": [+ "disabled"+ ],+ "default": 3600,+ "open_node": false+ },+ "pipelex.storage_config.gcp.uri_format": {+ "value_type": "str",+ "required": true,+ "default": "{primary_id}/{secondary_id}/{hash}.{extension}",+ "open_node": false+ },+ "pipelex.storage_config.in_memory": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "pipelex.storage_config.in_memory.uri_format": {+ "value_type": "str",+ "required": true,+ "default": "{primary_id}/{secondary_id}/{hash}.{extension}",+ "open_node": false+ },+ "pipelex.storage_config.is_fetch_remote_content_enabled": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.storage_config.is_upload_local_content_enabled": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.storage_config.local": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "pipelex.storage_config.local.local_storage_path": {+ "value_type": "str",+ "required": true,+ "default": ".pipelex/storage",+ "open_node": false+ },+ "pipelex.storage_config.local.uri_format": {+ "value_type": "str",+ "required": true,+ "default": "{primary_id}/{secondary_id}/{hash}.{extension}",+ "open_node": false+ },+ "pipelex.storage_config.method": {+ "value_type": "str",+ "required": true,+ "default": "local",+ "open_node": false+ },+ "pipelex.storage_config.s3": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "pipelex.storage_config.s3.bucket_name": {+ "value_type": "str",+ "required": true,+ "default": "",+ "open_node": false+ },+ "pipelex.storage_config.s3.region": {+ "value_type": "str",+ "required": true,+ "default": "",+ "open_node": false+ },+ "pipelex.storage_config.s3.signed_urls_lifespan_seconds": {+ "value_type": "int | literal",+ "required": true,+ "enum_members": [+ "disabled"+ ],+ "default": 3600,+ "open_node": false+ },+ "pipelex.storage_config.s3.uri_format": {+ "value_type": "str",+ "required": true,+ "default": "{primary_id}/{secondary_id}/{hash}.{extension}",+ "open_node": false+ },+ "pipelex.templating_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.templating_config.default_templating_style": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.templating_config.default_templating_style.tag_style": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "no_tag",+ "square_brackets",+ "ticks",+ "xml"+ ],+ "default": "xml",+ "open_node": false+ },+ "pipelex.templating_config.default_templating_style.text_format": {+ "value_type": "enum",+ "required": false,+ "enum_members": [+ "html",+ "json",+ "markdown",+ "plain"+ ],+ "open_node": false+ },+ "pipelex.tracing_config": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex.tracing_config.backend": {+ "value_type": "enum",+ "required": true,+ "enum_members": [+ "dynamodb",+ "ndjson"+ ],+ "default": "ndjson",+ "open_node": false+ },+ "pipelex.tracing_config.dynamodb": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "pipelex.tracing_config.dynamodb.region": {+ "value_type": "str",+ "required": true,+ "default": "",+ "open_node": false+ },+ "pipelex.tracing_config.dynamodb.table_name": {+ "value_type": "str",+ "required": true,+ "default": "",+ "open_node": false+ },+ "pipelex.tracing_config.is_enabled": {+ "value_type": "bool",+ "required": true,+ "default": true,+ "open_node": false+ },+ "pipelex.tracing_config.ndjson": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "pipelex.tracing_config.ndjson.traces_dir": {+ "value_type": "str",+ "required": true,+ "default": ".pipelex/traces",+ "open_node": false+ },+ "plugins": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "plugins.boot_orchestrator": {+ "value_type": "str",+ "required": false,+ "open_node": false+ },+ "plugins.disabled": {+ "value_type": "list[str]",+ "required": true,+ "default": [],+ "open_node": false+ },+ "session_id": {+ "value_type": "str",+ "required": false,+ "open_node": false+ }+ }+}diff --git a/pipelex/migration/goldens/pipelex-service-config/[email protected] b/pipelex/migration/goldens/pipelex-service-config/[email protected]new file mode 100644index 000000000..6d05c4fd3--- /dev/null+++ b/pipelex/migration/goldens/pipelex-service-config/[email protected]@@ -0,0 +1,5 @@+[agreement]+terms_accepted = false++[onboarding]+inference_setup_completed = falsediff --git a/pipelex/migration/goldens/pipelex-service-config/[email protected] b/pipelex/migration/goldens/pipelex-service-config/[email protected]new file mode 100644index 000000000..de28b24f5--- /dev/null+++ b/pipelex/migration/goldens/pipelex-service-config/[email protected]@@ -0,0 +1,28 @@+{+ "surface_id": "pipelex-service-config",+ "schema_version": 1,+ "paths": {+ "agreement": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "agreement.terms_accepted": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ },+ "onboarding": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "onboarding.inference_setup_completed": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ }+ }+}diff --git a/pipelex/migration/goldens/telemetry-config/[email protected] b/pipelex/migration/goldens/telemetry-config/[email protected]new file mode 100644index 000000000..bc3f3c406--- /dev/null+++ b/pipelex/migration/goldens/telemetry-config/[email protected]@@ -0,0 +1,33 @@+otlp = []++[custom_posthog]+mode = "off"+endpoint = "https://us.i.posthog.com"+geoip = true+debug = false+redact_properties = []++[custom_posthog.tracing]+enabled = false++[custom_posthog.tracing.capture]+content = false+pipe_codes = false+output_class_names = false++[custom_portkey]+force_debug_enabled = false+force_tracing_enabled = false++[langfuse]+enabled = false++[telemetry_allowed_modes]+ci = false+cli = true+docker = true+fastapi = true+mcp = true+n8n = true+pytest = false+python = falsediff --git a/pipelex/migration/goldens/telemetry-config/[email protected] b/pipelex/migration/goldens/telemetry-config/[email protected]new file mode 100644index 000000000..e497e8760--- /dev/null+++ b/pipelex/migration/goldens/telemetry-config/[email protected]@@ -0,0 +1,264 @@+{+ "surface_id": "telemetry-config",+ "schema_version": 1,+ "paths": {+ "custom_portkey": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "custom_portkey.force_debug_enabled": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ },+ "custom_portkey.force_tracing_enabled": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ },+ "custom_posthog": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "custom_posthog.api_key": {+ "value_type": "str",+ "required": false,+ "open_node": false+ },+ "custom_posthog.debug": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ },+ "custom_posthog.endpoint": {+ "value_type": "str",+ "required": false,+ "default": "https://us.i.posthog.com",+ "open_node": false+ },+ "custom_posthog.geoip": {+ "value_type": "bool",+ "required": false,+ "default": true,+ "open_node": false+ },+ "custom_posthog.mode": {+ "value_type": "enum",+ "required": false,+ "enum_members": [+ "anonymous",+ "identified",+ "off"+ ],+ "default": "off",+ "open_node": false+ },+ "custom_posthog.redact_properties": {+ "value_type": "list[str]",+ "required": false,+ "default": [],+ "open_node": false+ },+ "custom_posthog.tracing": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "custom_posthog.tracing.capture": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "custom_posthog.tracing.capture.content": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ },+ "custom_posthog.tracing.capture.content_max_length": {+ "value_type": "int",+ "required": false,+ "open_node": false+ },+ "custom_posthog.tracing.capture.output_class_names": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ },+ "custom_posthog.tracing.capture.pipe_codes": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ },+ "custom_posthog.tracing.enabled": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ },+ "custom_posthog.user_id": {+ "value_type": "str",+ "required": false,+ "open_node": false+ },+ "langfuse": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "langfuse.enabled": {+ "value_type": "bool",+ "required": false,+ "default": false,+ "open_node": false+ },+ "langfuse.endpoint": {+ "value_type": "str",+ "required": false,+ "open_node": false+ },+ "langfuse.public_key": {+ "value_type": "str",+ "required": false,+ "open_node": false+ },+ "langfuse.secret_key": {+ "value_type": "str",+ "required": false,+ "open_node": false+ },+ "otlp": {+ "value_type": "list[table]",+ "required": false,+ "default": [],+ "open_node": false+ },+ "pipelex_gateway": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.portkey": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex_gateway.portkey.force_debug_enabled": {+ "value_type": "bool",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.portkey.force_tracing_enabled": {+ "value_type": "bool",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog": {+ "value_type": "table",+ "required": true,+ "open_node": false+ },+ "pipelex_gateway.posthog.api_key": {+ "value_type": "str",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.debug": {+ "value_type": "bool",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.endpoint": {+ "value_type": "str",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.geoip": {+ "value_type": "bool",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.mode": {+ "value_type": "enum",+ "required": false,+ "enum_members": [+ "anonymous",+ "identified",+ "off"+ ],+ "open_node": false+ },+ "pipelex_gateway.posthog.redact_properties": {+ "value_type": "list[str]",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.tracing": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.tracing.capture": {+ "value_type": "table",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.tracing.capture.content": {+ "value_type": "bool",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.tracing.capture.content_max_length": {+ "value_type": "int",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.tracing.capture.output_class_names": {+ "value_type": "bool",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.tracing.capture.pipe_codes": {+ "value_type": "bool",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.tracing.enabled": {+ "value_type": "bool",+ "required": false,+ "open_node": false+ },+ "pipelex_gateway.posthog.user_id": {+ "value_type": "str",+ "required": false,+ "open_node": false+ },+ "telemetry_allowed_modes": {+ "value_type": "dict[str, bool]",+ "required": false,+ "default": {+ "ci": false,+ "cli": true,+ "docker": true,+ "fastapi": true,+ "mcp": true,+ "n8n": true,+ "pytest": false,+ "python": false+ },+ "open_node": true+ },+ "telemetry_allowed_modes.*": {+ "value_type": "bool",+ "required": true,+ "open_node": false+ }+ }+}diff --git a/pipelex/migration/ledger.py b/pipelex/migration/ledger.pynew file mode 100644index 000000000..e389fc148--- /dev/null+++ b/pipelex/migration/ledger.py@@ -0,0 +1,182 @@+"""The ledger — the checked-in record of every shape change a surface has undergone.++**A ledger is data and never code.** The checks must reason mechanically about what every entry+does — which paths it removes, which values it remaps, whether replay converges — and executable+steps defeat every one of those checks.++The models below are strict on purpose. An entry whose id disagrees with its version, or a ledger+whose versions skip a number, is refused when the file is parsed rather than diagnosed later by a+gate: the earlier a malformed ledger stops, the fewer places have to cope with one.++See `docs/migration-ledger.md` → "The ledger file".+"""++from enum import StrEnum+from pathlib import Path+from typing import Any++from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator+from typing_extensions import Self++from pipelex.migration.exceptions import MigrationLedgerError+from pipelex.suggested_fix import MigrationOp+from pipelex.tools.misc.exceptions import TomlError+from pipelex.tools.misc.toml_utils import load_toml_from_path++LEDGERS_DIR_NAME = "ledgers"+INITIAL_SCHEMA_VERSION = 1+"""Every surface starts here. There is no retroactive numbering of changes that predate the ledger."""+++class MigrationSafety(StrEnum):+ """Whether the applier may act on an entry.++ Independent of `guidance`, which any entry may carry whatever its safety.+ """++ SAFE = "safe"+ """Mechanically complete; applied after one confirmation."""++ UNSAFE = "unsafe"+ """Reported and never applied — the applier cannot tell a stale value from a deliberate one."""+++class SurfaceBlock(BaseModel):+ """The `[surface]` block: what the ledger claims about the surface it governs."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ id: str+ title: str+ base_file: str+ tier_glob: str | None = None+ current_schema_version: int = Field(ge=INITIAL_SCHEMA_VERSION)+ min_supported_schema_version: int = Field(ge=0)+ """Held at zero until a ledger squash ever moves it. Without the floor, a squash silently+ under-migrates the oldest files in the field, because the applier skips absent targets and+ reports success. With it, the loader fails loudly instead."""++ @model_validator(mode="after")+ def check_floor_is_below_the_current_version(self) -> Self:+ if self.min_supported_schema_version > self.current_schema_version:+ msg = (+ f"surface '{self.id}': min_supported_schema_version {self.min_supported_schema_version} "+ f"is above current_schema_version {self.current_schema_version}"+ )+ raise ValueError(msg)+ return self+++class MigrationEntry(BaseModel):+ """One schema version's worth of change, as data."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ id: str+ to_schema_version: int = Field(gt=INITIAL_SCHEMA_VERSION)+ """Above 1: version 1 is the shape a surface starts at, so nothing migrates *to* it."""++ introduced_in: str+ """The package version carrying this entry. Orientation against the changelog only —+ nothing branches on it."""++ breaking: bool+ safety: MigrationSafety = Field(strict=False)+ title: str+ description: str+ guidance: str | None = None+ """Agent-facing Markdown: what a user should understand or decide. Never the mechanism —+ anything expressible as operations must be operations."""++ pre_history: bool = False+ """A removal that predates the first fingerprint has no observed diff to account against, so+ such an entry declares its own removed paths instead."""++ declared_removed_paths: list[str] = Field(default_factory=list[str])+ ops: list[MigrationOp] = Field(default_factory=list[MigrationOp])+ """May legitimately be empty, with `safety = "unsafe"`, for a change only a human can make."""++ @model_validator(mode="after")+ def check_declared_removals_belong_to_pre_history(self) -> Self:+ if self.declared_removed_paths and not self.pre_history:+ msg = (+ f"entry '{self.id}': declared_removed_paths is for pre-history entries only — an entry with an "+ f"observable fingerprint diff is accounted against that diff, not against its own declaration"+ )+ raise ValueError(msg)+ return self++ @model_validator(mode="after")+ def check_an_op_free_entry_is_unsafe(self) -> Self:+ if not self.ops and self.safety is MigrationSafety.SAFE:+ msg = f"entry '{self.id}': an entry with no operations cannot be 'safe' — there is nothing for the applier to do"+ raise ValueError(msg)+ return self+++class MigrationLedger(BaseModel):+ """One surface's whole ledger, as parsed from its checked-in TOML file."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ surface: SurfaceBlock+ migration: list[MigrationEntry] = Field(default_factory=list[MigrationEntry])++ @model_validator(mode="after")+ def check_entries_are_contiguous_and_named_for_their_version(self) -> Self:+ expected_version = INITIAL_SCHEMA_VERSION+ for entry in self.migration:+ expected_version += 1+ if entry.to_schema_version != expected_version:+ msg = (+ f"ledger '{self.surface.id}': entries must be ordered and contiguous — expected an entry for "+ f"schema version {expected_version}, found '{entry.id}' at {entry.to_schema_version}"+ )+ raise ValueError(msg)+ expected_id = f"{self.surface.id}@{entry.to_schema_version}"+ if entry.id != expected_id:+ msg = f"ledger '{self.surface.id}': entry at schema version {entry.to_schema_version} must be named '{expected_id}', not '{entry.id}'"+ raise ValueError(msg)+ if expected_version != self.surface.current_schema_version:+ msg = (+ f"ledger '{self.surface.id}': current_schema_version is {self.surface.current_schema_version} but the entries "+ f"reach {expected_version} — every version above {INITIAL_SCHEMA_VERSION} needs the entry that produced it"+ )+ raise ValueError(msg)+ return self++ def entry_for_version(self, *, schema_version: int) -> MigrationEntry | None:+ for entry in self.migration:+ if entry.to_schema_version == schema_version:+ return entry+ return None+++def ledgers_dir(*, migration_dir: Path) -> Path:+ return migration_dir / LEDGERS_DIR_NAME+++def ledger_path(*, migration_dir: Path, surface_id: str) -> Path:+ return ledgers_dir(migration_dir=migration_dir) / f"{surface_id}.toml"+++def load_ledger(*, migration_dir: Path, surface_id: str) -> MigrationLedger:+ """Read and validate one surface's ledger.++ Raises:+ MigrationLedgerError: the file is missing, unparseable, or internally inconsistent.+ """+ path = ledger_path(migration_dir=migration_dir, surface_id=surface_id)+ try:+ raw: dict[str, Any] = load_toml_from_path(path=path)+ except FileNotFoundError as exc:+ msg = f"no ledger for surface '{surface_id}' at {path}"+ raise MigrationLedgerError(msg) from exc+ except TomlError as exc:+ msg = f"unparseable ledger for surface '{surface_id}' at {path}: {exc}"+ raise MigrationLedgerError(msg) from exc+ try:+ return MigrationLedger.model_validate(raw)+ except ValidationError as exc:+ msg = f"invalid ledger for surface '{surface_id}' at {path}: {exc}"+ raise MigrationLedgerError(msg) from excdiff --git a/pipelex/migration/ledgers/pipelex-config.toml b/pipelex/migration/ledgers/pipelex-config.tomlnew file mode 100644index 000000000..4317c687d--- /dev/null+++ b/pipelex/migration/ledgers/pipelex-config.toml@@ -0,0 +1,16 @@+# The migration ledger for the main Pipelex configuration.+#+# Every shape change this surface undergoes is recorded here as data, in order, and replayed in+# full over every one of the surface's files on every run. See docs/migration-ledger.md — it is+# normative, and it explains why there are no `set_key`-style operations in this vocabulary and+# why no version record ever causes work to be skipped.+#+# Entries are appended by `make umig` through the add-migration skill, never hand-invented.++[surface]+id = "pipelex-config"+title = "The main Pipelex configuration"+base_file = "pipelex.toml"+tier_glob = "pipelex_*.toml"+current_schema_version = 1+min_supported_schema_version = 0diff --git a/pipelex/migration/ledgers/pipelex-service-config.toml b/pipelex/migration/ledgers/pipelex-service-config.tomlnew file mode 100644index 000000000..a6c7411e7--- /dev/null+++ b/pipelex/migration/ledgers/pipelex-service-config.toml@@ -0,0 +1,13 @@+# The migration ledger for the Pipelex service agreement and onboarding state.+#+# This surface has no tier files: there is one `pipelex_service.toml` per configuration directory+# and nothing layers over it.+#+# See docs/migration-ledger.md for the contract this file obeys.++[surface]+id = "pipelex-service-config"+title = "Pipelex service agreement and onboarding state"+base_file = "pipelex_service.toml"+current_schema_version = 1+min_supported_schema_version = 0diff --git a/pipelex/migration/ledgers/telemetry-config.toml b/pipelex/migration/ledgers/telemetry-config.tomlnew file mode 100644index 000000000..4bdb983c7--- /dev/null+++ b/pipelex/migration/ledgers/telemetry-config.toml@@ -0,0 +1,11 @@+# The migration ledger for the telemetry configuration.+#+# See docs/migration-ledger.md for the contract this file obeys.++[surface]+id = "telemetry-config"+title = "Telemetry destinations and capture settings"+base_file = "telemetry.toml"+tier_glob = "telemetry_*.toml"+current_schema_version = 1+min_supported_schema_version = 0diff --git a/pipelex/migration/snapshot.py b/pipelex/migration/snapshot.pynew file mode 100644index 000000000..2153690c6--- /dev/null+++ b/pipelex/migration/snapshot.py@@ -0,0 +1,65 @@+"""Regeneration — writing the golden chain that the coverage check reads.++`update-migration-schemas` writes, for each surface, the snapshot of its *current* schema version:+the fingerprint and the complete reference document. Older versions are never rewritten, so a+bump leaves the previous version's files behind as the frozen history the chain is made of.++The reference document is the defaults layer verbatim: for a packaged-document surface a byte copy+of the shipped TOML, for a model-defaults surface the document synthesized from the model's own+defaults. Neither carries a generated-by banner, because these files are not reports about a+document — they *are* the document, and a later phase applies migration operations to them.+"""++from pathlib import Path++from pydantic import BaseModel, ConfigDict++from pipelex.migration.fingerprint import SurfaceFingerprint, compute_fingerprint+from pipelex.migration.goldens import write_defaults_golden, write_fingerprint_golden+from pipelex.migration.ledger import load_ledger+from pipelex.migration.surfaces import Surface, SurfaceRegistry+++class SurfaceSnapshot(BaseModel):+ """Where one surface's regeneration landed, for reporting."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ surface_id: str+ schema_version: int+ fingerprint_path: Path+ defaults_path: Path+ path_count: int+++def snapshot_surface(*, surface: Surface, migration_dir: Path) -> SurfaceSnapshot:+ ledger = load_ledger(migration_dir=migration_dir, surface_id=surface.surface_id)+ schema_version = ledger.surface.current_schema_version+ fingerprint = compute_surface_fingerprint(surface=surface, schema_version=schema_version)+ fingerprint_path = write_fingerprint_golden(migration_dir=migration_dir, fingerprint=fingerprint)+ defaults_path = write_defaults_golden(+ migration_dir=migration_dir,+ surface_id=surface.surface_id,+ schema_version=schema_version,+ document=surface.render_reference_document(),+ )+ return SurfaceSnapshot(+ surface_id=surface.surface_id,+ schema_version=schema_version,+ fingerprint_path=fingerprint_path,+ defaults_path=defaults_path,+ path_count=len(fingerprint.paths),+ )+++def compute_surface_fingerprint(*, surface: Surface, schema_version: int) -> SurfaceFingerprint:+ return compute_fingerprint(+ surface_id=surface.surface_id,+ schema_version=schema_version,+ config_model=surface.config_model,+ defaults_document=surface.read_defaults_document(),+ )+++def snapshot_registry(*, registry: SurfaceRegistry, migration_dir: Path) -> list[SurfaceSnapshot]:+ return [snapshot_surface(surface=surface, migration_dir=migration_dir) for surface in registry.surfaces]diff --git a/pipelex/migration/surfaces.py b/pipelex/migration/surfaces.pynew file mode 100644index 000000000..e573a0872--- /dev/null+++ b/pipelex/migration/surfaces.py@@ -0,0 +1,225 @@+"""The surface registry — what a configuration surface is, and which ones exist.++The registry is built by a function and passed as a parameter, **never read from a module+constant**. That is deliberate and it is what keeps the gates honest: the gates' own tests point+the registry at small synthetic models, so gate *behaviour* is tested against something that+never moves. Wire the real models into the gate's test suite and every legitimate configuration+change turns the gate's tests red alongside the gate, and the fix everyone learns is "regenerate+the goldens" — which is how a gate goes permanently green while catching nothing.++See `docs/migration-ledger.md` → "Surfaces" and "Testing the gates without coupling them to the+configuration models".+"""++from enum import StrEnum+from pathlib import Path+from typing import Any, cast++import tomlkit+from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator+from typing_extensions import Self++from pipelex.migration.exceptions import MigrationRegistryError+from pipelex.system.configuration.configs import PipelexConfig+from pipelex.system.pipelex_service.pipelex_service_agreement import PIPELEX_SERVICE_CONFIG_FILE_NAME+from pipelex.system.pipelex_service.pipelex_service_config import PipelexServiceConfig+from pipelex.system.telemetry.telemetry_config import TELEMETRY_CONFIG_FILE_NAME, TelemetryConfig+from pipelex.tools.misc.toml_utils import load_toml_from_path++PIPELEX_CONFIG_FILE_NAME = "pipelex.toml"++# The package directory, `pipelex/` — this module sits one level under it.+_PACKAGE_ROOT = Path(__file__).resolve().parent.parent+++def packaged_migration_dir() -> Path:+ """The directory holding the checked-in ledgers and golden chains — this module's own."""+ return Path(__file__).resolve().parent+++class DefaultsLayerKind(StrEnum):+ """Where a surface's current-schema default values come from.++ Every in-scope surface must have one, because the defaults layer is what makes an additive+ schema change absorbable and therefore never a migration.+ """++ PACKAGED_DOCUMENT = "packaged_document"+ """A TOML document shipped in the package and merged beneath the user's files."""++ MODEL_DEFAULTS = "model_defaults"+ """Field-level defaults on the model; the reference document is synthesized from them."""+++class Surface(BaseModel):+ """One artifact family with one schema version and one ledger."""++ model_config = ConfigDict(frozen=True, extra="forbid", arbitrary_types_allowed=True)++ surface_id: str+ title: str+ base_file: str+ tier_glob: str | None = None+ config_model: type[BaseModel]+ defaults_layer_kind: DefaultsLayerKind+ packaged_document_path: Path | None = None++ @model_validator(mode="after")+ def check_defaults_layer_is_reachable(self) -> Self:+ has_packaged_path = self.packaged_document_path is not None+ wants_packaged_path = self.defaults_layer_kind is DefaultsLayerKind.PACKAGED_DOCUMENT+ if has_packaged_path != wants_packaged_path:+ msg = (+ f"surface '{self.surface_id}': defaults_layer_kind '{self.defaults_layer_kind}' and "+ f"packaged_document_path {self.packaged_document_path!r} disagree — a packaged-document "+ f"surface names its document and a model-defaults surface does not"+ )+ raise ValueError(msg)+ return self++ def render_reference_document(self) -> str:+ """The surface's complete reference document as TOML text, ready to check in.++ For a packaged-document surface this is the shipped file verbatim; for a model-defaults+ surface it is the synthesized document serialized. Neither carries a generated-by banner,+ because the snapshot is not a report about a document — it *is* the document, and a later+ phase applies migration operations to it.+ """+ match self.defaults_layer_kind:+ case DefaultsLayerKind.PACKAGED_DOCUMENT:+ # Guaranteed present by the validator above.+ assert self.packaged_document_path is not None+ return self.packaged_document_path.read_text(encoding="utf-8")+ case DefaultsLayerKind.MODEL_DEFAULTS:+ document: str = tomlkit.dumps(self.read_defaults_document()) # pyright: ignore[reportUnknownMemberType]+ return document++ def read_defaults_document(self) -> dict[str, Any]:+ """The surface's complete reference document, as a plain mapping.++ For a packaged-document surface this is the shipped TOML. For a model-defaults surface+ it is synthesized by instantiating the model with nothing set, which is exactly the+ document the defaults layer contributes. Keys whose value is `None` are dropped: TOML+ has no null, so an unset optional is an absent key rather than a written one.+ """+ match self.defaults_layer_kind:+ case DefaultsLayerKind.PACKAGED_DOCUMENT:+ # Guaranteed present by the validator above; the assert keeps the type checker honest.+ assert self.packaged_document_path is not None+ return load_toml_from_path(path=self.packaged_document_path)+ case DefaultsLayerKind.MODEL_DEFAULTS:+ try:+ instance = self.config_model()+ except ValidationError as exc:+ # A model-defaults surface whose model cannot be built from nothing has no+ # defaults layer at all, which is the one condition the whole vocabulary rests+ # on: without it an added key breaks every existing file and no structural+ # operation can repair it.+ msg = (+ f"surface '{self.surface_id}' declares its defaults layer as model defaults, but "+ f"{self.config_model.__name__} cannot be built without arguments, so it supplies no "+ f"defaults at all: {exc}"+ )+ raise MigrationRegistryError(msg) from exc+ return _drop_none_values(mapping=instance.model_dump(mode="json"))+++def _drop_none_values(*, mapping: dict[str, Any]) -> dict[str, Any]:+ """Recursively drop keys whose value is `None`, which TOML cannot express.++ Descends through nested mappings and through lists — a list of nested models is a real shape,+ and a `None` inside one item fails serialization exactly as a top-level one would. Only+ mapping keys are dropped; a list keeps every item.+ """+ kept: dict[str, Any] = {}+ for key, value in mapping.items():+ if value is None:+ continue+ kept[key] = _without_none_values(value=value)+ return kept+++def _without_none_values(*, value: Any) -> Any:+ if isinstance(value, dict):+ return _drop_none_values(mapping=cast("dict[str, Any]", value))+ if isinstance(value, list):+ return [_without_none_values(value=item) for item in cast("list[Any]", value)]+ return value+++class SurfaceRegistry(BaseModel):+ """The set of surfaces a gate or a migration run operates over."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ surfaces: list[Surface] = Field(min_length=1)++ @model_validator(mode="after")+ def check_no_surface_shadows_another(self) -> Self:+ """Reject a registry whose surfaces could claim the same file.++ Which ledger runs over a file must not be an accident of iteration order. Exact+ filenames claim before globs across all surfaces, so a base file matching another+ surface's glob is fine and resolved by that rule — but two surfaces sharing an id, a+ base file or a tier glob have no rule to separate them.+ """+ _reject_duplicates(values=[surface.surface_id for surface in self.surfaces], label="surface id")+ _reject_duplicates(values=[surface.base_file for surface in self.surfaces], label="base file")+ _reject_duplicates(+ values=[surface.tier_glob for surface in self.surfaces if surface.tier_glob is not None],+ label="tier glob",+ )+ return self++ def surface_for_id(self, *, surface_id: str) -> Surface:+ for surface in self.surfaces:+ if surface.surface_id == surface_id:+ return surface+ msg = f"no surface '{surface_id}' in this registry"+ raise MigrationRegistryError(msg)+++def _reject_duplicates(*, values: list[str], label: str) -> None:+ seen: set[str] = set()+ for value in values:+ if value in seen:+ msg = f"registry error: two surfaces share the {label} '{value}'"+ raise ValueError(msg)+ seen.add(value)+++def build_config_surface_registry() -> SurfaceRegistry:+ """The real registry: the configuration surfaces the `pipelex` package owns.++ A function rather than a module constant, so that nothing imports the real configuration+ models by merely importing this module, and so that every consumer has to state which+ registry it means.+ """+ return SurfaceRegistry(+ surfaces=[+ Surface(+ surface_id="pipelex-config",+ title="The main Pipelex configuration",+ base_file=PIPELEX_CONFIG_FILE_NAME,+ tier_glob="pipelex_*.toml",+ config_model=PipelexConfig,+ defaults_layer_kind=DefaultsLayerKind.PACKAGED_DOCUMENT,+ packaged_document_path=_PACKAGE_ROOT / PIPELEX_CONFIG_FILE_NAME,+ ),+ Surface(+ surface_id="telemetry-config",+ title="Telemetry destinations and capture settings",+ base_file=TELEMETRY_CONFIG_FILE_NAME,+ tier_glob="telemetry_*.toml",+ config_model=TelemetryConfig,+ defaults_layer_kind=DefaultsLayerKind.MODEL_DEFAULTS,+ ),+ Surface(+ surface_id="pipelex-service-config",+ title="Pipelex service agreement and onboarding state",+ base_file=PIPELEX_SERVICE_CONFIG_FILE_NAME,+ config_model=PipelexServiceConfig,+ defaults_layer_kind=DefaultsLayerKind.MODEL_DEFAULTS,+ ),+ ]+ )diff --git a/pipelex/pipeline/fixes/applier.py b/pipelex/pipeline/fixes/applier.pyindex 5ba23f14f..d29bb4545 100644--- a/pipelex/pipeline/fixes/applier.py+++ b/pipelex/pipeline/fixes/applier.py@@ -19,8 +19,10 @@ TOML to patch) and against ops targeting a different file than the one being patop is reported, never raised."""+import copy+from collections.abc import Sequencefrom enum import StrEnum-from typing import TYPE_CHECKING, Any, cast+from typing import TYPE_CHECKING, Any, NamedTuple, castimport tomlkitfrom pipelex_tools import format_mthds@@ -30,7 +32,18 @@ from tomlkit.container import Container, OutOfOrderTableProxyfrom tomlkit.items import AbstractTable, Itemfrom pipelex.base_exceptions import PipelexUnexpectedError-from pipelex.suggested_fix import FixOp, FixOpKind, TomlValue+from pipelex.suggested_fix import (+ WILDCARD_SEGMENT,+ DeleteKeyOp,+ DeleteTableOp,+ EnsureTableOp,+ FixOp,+ MoveKeyOp,+ RemapValueOp,+ RenameTableKeyOp,+ SetKeyOp,+ TomlValue,+)if TYPE_CHECKING:# ``Diagnostic`` is a type-only TypedDict from the stub — declared in ``__all__`` but not a@@ -39,17 +52,25 @@ if TYPE_CHECKING:class FixOpOutcome(StrEnum):- """What happened to one op during application."""+ """What happened to one op during application.++ ``SKIPPED`` is benign and, under a migration's always-replay, overwhelmingly the common+ case: the target is gone or the change is already there. ``CONFLICT`` is not benign and+ must never travel inside ``SKIPPED`` — it means the change cannot be made without choosing+ on the user's behalf, typically because they hand-fixed part of the file themselves.+ Consumers classify on this enum and never by parsing ``detail``, which is presentation.+ """APPLIED = "applied"SKIPPED = "skipped"+ CONFLICT = "conflict"@propertydef did_apply(self) -> bool:match self:case FixOpOutcome.APPLIED:return True- case FixOpOutcome.SKIPPED:+ case FixOpOutcome.SKIPPED | FixOpOutcome.CONFLICT:return False@@ -173,7 +194,7 @@ def _render_syntax_diagnostic(diagnostic: "Diagnostic") -> str:return f"{diagnostic['message']} (line {diagnostic_range['start_line']}:{diagnostic_range['start_col']})"-def apply_fix_ops(*, toml_doc: TOMLDocument, ops: list[FixOp]) -> list[FixOpApplication]:+def apply_fix_ops(*, toml_doc: TOMLDocument, ops: Sequence[FixOp]) -> list[FixOpApplication]:"""Apply each op to the DOM in place, returning one application report per op, in order.Idempotent: re-applying an already-applied op sets the same value / finds the key@@ -185,69 +206,225 @@ def apply_fix_ops(*, toml_doc: TOMLDocument, ops: list[FixOp]) -> list[FixOpApplreturn applications+class _OpResult(NamedTuple):+ """One op's effect at one concrete table path, before wildcard expansions are folded."""++ outcome: FixOpOutcome+ detail: str | None = None+++def _expand_table_paths(*, toml_doc: TOMLDocument, table_path: list[str]) -> list[list[str]]:+ """Resolve ``table_path`` into the concrete paths it addresses in this document.++ A path with no wildcard is itself, always — expansion never filters, so a path pointing at+ a table the document does not have still reaches its handler and is reported as a guarded+ skip there, exactly as before wildcards existed.++ A ``*`` segment expands over the table-valued keys present at that node, which is what+ "every entry of this open mapping" means for a file: the keys belong to the user, so the+ document is the only thing that can enumerate them. A wildcard over a node that is absent,+ or that holds no table-valued key, expands to nothing.+ """+ if WILDCARD_SEGMENT not in table_path:+ return [table_path]+ expanded_paths: list[list[str]] = [[]]+ for segment in table_path:+ if segment != WILDCARD_SEGMENT:+ expanded_paths = [[*path, segment] for path in expanded_paths]+ continue+ next_paths: list[list[str]] = []+ for path in expanded_paths:+ node = _resolve_table(toml_doc=toml_doc, table_path=path)+ if node is None:+ continue+ next_paths.extend([*path, key] for key, value in node.items() if isinstance(value, dict))+ expanded_paths = next_paths+ return expanded_paths++def _apply_one_op(*, toml_doc: TOMLDocument, fix_op: FixOp) -> FixOpApplication:- table_path_str = ".".join(fix_op.table_path)- match fix_op.kind:- case FixOpKind.SET_KEY:- if fix_op.key is None or fix_op.value is None:- msg = f"set_key op on '{table_path_str}' requires both key and value — planner bug"- raise PipelexUnexpectedError(msg)- target_table = _resolve_table(toml_doc=toml_doc, table_path=fix_op.table_path)+ """Apply one op at every concrete path it addresses, folded into a single report.++ An op is one step, and a conflicting step writes nothing — including a wildcard op whose+ conflict sits in the *last* matched entry. Every handler decides its own conflict before it+ writes, so a single path is atomic by construction; across several paths the op is first+ rehearsed on a copy of the document, and touches the real one only once no match conflicts.+ """+ concrete_paths = _expand_table_paths(toml_doc=toml_doc, table_path=fix_op.table_path)+ if not concrete_paths:+ detail = f"no table matches '{'.'.join(fix_op.table_path)}' in document"+ return FixOpApplication(op=fix_op, outcome=FixOpOutcome.SKIPPED, detail=detail)+ if len(concrete_paths) == 1:+ result = _apply_at_table_path(toml_doc=toml_doc, fix_op=fix_op, table_path=concrete_paths[0])+ return FixOpApplication(op=fix_op, outcome=result.outcome, detail=result.detail)+ rehearsal = copy.deepcopy(toml_doc)+ rehearsed = [_apply_at_table_path(toml_doc=rehearsal, fix_op=fix_op, table_path=path) for path in concrete_paths]+ if any(result.outcome is FixOpOutcome.CONFLICT for result in rehearsed):+ return _fold_wildcard_results(fix_op=fix_op, results=rehearsed)+ results = [_apply_at_table_path(toml_doc=toml_doc, fix_op=fix_op, table_path=path) for path in concrete_paths]+ return _fold_wildcard_results(fix_op=fix_op, results=results)+++def _fold_wildcard_results(*, fix_op: FixOp, results: list[_OpResult]) -> FixOpApplication:+ """Reduce one wildcard op's per-entry results to the single report the caller sees.++ A conflict anywhere wins, because a conflict is the one outcome a caller must act on and+ burying it under a sibling entry's success would hide exactly what the outcome exists to+ surface. Otherwise any application makes the op applied, and only an op that did nothing+ anywhere is skipped.+ """+ conflicts = [result for result in results if result.outcome is FixOpOutcome.CONFLICT]+ if conflicts:+ return FixOpApplication(+ op=fix_op,+ outcome=FixOpOutcome.CONFLICT,+ detail=f"{len(conflicts)} of {len(results)} matched tables conflict — first: {conflicts[0].detail}",+ )+ applied_count = sum(1 for result in results if result.outcome.did_apply)+ if applied_count:+ return FixOpApplication(+ op=fix_op,+ outcome=FixOpOutcome.APPLIED,+ detail=f"applied in {applied_count} of {len(results)} matched tables",+ )+ return FixOpApplication(op=fix_op, outcome=FixOpOutcome.SKIPPED, detail=f"nothing to do in any of {len(results)} matched tables")+++def _apply_at_table_path(*, toml_doc: TOMLDocument, fix_op: FixOp, table_path: list[str]) -> _OpResult:+ """Dispatch one op to its handler, at one already-expanded concrete table path.++ Matching on the op **type** rather than on its ``kind`` is what removes the shape checks+ this function used to open with: each variant of the union declares exactly the fields its+ handler reads, so "a set_key without a value" is a pydantic error at construction and can no+ longer reach the applier as a runtime "planner bug" raise.+ """+ table_path_str = ".".join(table_path)+ match fix_op:+ case SetKeyOp():+ target_table = _resolve_table(toml_doc=toml_doc, table_path=table_path)if target_table is None:- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.SKIPPED, detail=f"table '{table_path_str}' not found in document")+ return _OpResult(FixOpOutcome.SKIPPED, f"table '{table_path_str}' not found in document")target_table[fix_op.key] = _as_tomlkit_value(fix_op.value)- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.APPLIED)- case FixOpKind.ENSURE_TABLE:- if not fix_op.table_path:- msg = "ensure_table op requires a non-empty table_path — planner bug"- raise PipelexUnexpectedError(msg)- existing_table = _resolve_table(toml_doc=toml_doc, table_path=fix_op.table_path)+ return _OpResult(FixOpOutcome.APPLIED)+ case EnsureTableOp():+ existing_table = _resolve_table(toml_doc=toml_doc, table_path=table_path)if existing_table is not None:- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.SKIPPED, detail=f"table '{table_path_str}' already exists")- parent_table = _resolve_table(toml_doc=toml_doc, table_path=fix_op.table_path[:-1])- table_key = fix_op.table_path[-1]- if parent_table is None or table_key in parent_table:- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.SKIPPED, detail=f"parent of table '{table_path_str}' not found")+ return _OpResult(FixOpOutcome.SKIPPED, f"table '{table_path_str}' already exists")+ parent_table = _resolve_table(toml_doc=toml_doc, table_path=table_path[:-1])+ if parent_table is None:+ return _OpResult(FixOpOutcome.SKIPPED, f"parent of table '{table_path_str}' not found")+ table_key = table_path[-1]+ if table_key in parent_table:+ # The key is there but is not a table — the check above would have resolved it.+ # Creating the table would destroy whatever the user put there, so this is a+ # choice on their behalf, not an absence: a conflict, and not the "parent not+ # found" this branch used to report.+ return _OpResult(FixOpOutcome.CONFLICT, f"'{table_key}' is already present in '{'.'.join(table_path[:-1])}' and is not a table")parent_table[table_key] = tomlkit.inline_table()- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.APPLIED)- case FixOpKind.DELETE_KEY:- if fix_op.key is None:- msg = f"delete_key op on '{table_path_str}' requires a key — planner bug"- raise PipelexUnexpectedError(msg)- target_table = _resolve_table(toml_doc=toml_doc, table_path=fix_op.table_path)+ return _OpResult(FixOpOutcome.APPLIED)+ case DeleteKeyOp():+ target_table = _resolve_table(toml_doc=toml_doc, table_path=table_path)if target_table is None:- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.SKIPPED, detail=f"table '{table_path_str}' not found in document")+ return _OpResult(FixOpOutcome.SKIPPED, f"table '{table_path_str}' not found in document")if fix_op.key not in target_table:- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.SKIPPED, detail=f"key '{fix_op.key}' not found in table '{table_path_str}'")+ return _OpResult(FixOpOutcome.SKIPPED, f"key '{fix_op.key}' not found in table '{table_path_str}'")del target_table[fix_op.key]- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.APPLIED)- case FixOpKind.DELETE_TABLE:- if not fix_op.table_path:- msg = "delete_table op requires a non-empty table_path — planner bug"- raise PipelexUnexpectedError(msg)- parent_table = _resolve_table(toml_doc=toml_doc, table_path=fix_op.table_path[:-1])- table_key = fix_op.table_path[-1]+ return _OpResult(FixOpOutcome.APPLIED)+ case DeleteTableOp():+ parent_table = _resolve_table(toml_doc=toml_doc, table_path=table_path[:-1])+ table_key = table_path[-1]# The final segment must itself be a table — a scalar there is a drifted target# (same guarded-skip contract _resolve_table enforces for every other segment).if parent_table is None or not isinstance(parent_table.get(table_key), dict):- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.SKIPPED, detail=f"table '{table_path_str}' not found in document")+ return _OpResult(FixOpOutcome.SKIPPED, f"table '{table_path_str}' not found in document")del parent_table[table_key]- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.APPLIED)- case FixOpKind.RENAME_TABLE_KEY:- if fix_op.key is None or fix_op.new_key is None:- msg = f"rename_table_key op on '{table_path_str}' requires both key and new_key — planner bug"- raise PipelexUnexpectedError(msg)- parent_table = _resolve_table(toml_doc=toml_doc, table_path=fix_op.table_path)+ return _OpResult(FixOpOutcome.APPLIED)+ case RenameTableKeyOp():+ parent_table = _resolve_table(toml_doc=toml_doc, table_path=table_path)if parent_table is None or fix_op.key not in parent_table:- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.SKIPPED, detail=f"key '{fix_op.key}' not found in table '{table_path_str}'")+ return _OpResult(FixOpOutcome.SKIPPED, f"key '{fix_op.key}' not found in table '{table_path_str}'")if fix_op.new_key in parent_table:# Collision: the bare name is already taken by a separate declaration — renaming- # would clobber it. The raise-site guard suppresses this case, but the applier- # stays defensive (a stale fix from a prior loop iteration could reach here).- return FixOpApplication(- op=fix_op,- outcome=FixOpOutcome.SKIPPED,- detail=f"cannot rename to '{fix_op.new_key}': already present in table '{table_path_str}'",- )+ # would clobber it. The raise-site guard suppresses this case for `.mthds` fixes,+ # but the applier stays defensive (a stale fix from a prior loop iteration, or a+ # user who hand-fixed half of a migration, could reach here).+ return _OpResult(FixOpOutcome.CONFLICT, f"cannot rename to '{fix_op.new_key}': already present in table '{table_path_str}'")_rename_key_in_place(parent_table=parent_table, key=fix_op.key, new_key=fix_op.new_key)- return FixOpApplication(op=fix_op, outcome=FixOpOutcome.APPLIED)+ return _OpResult(FixOpOutcome.APPLIED)+ case MoveKeyOp():+ return _apply_move_key(toml_doc=toml_doc, fix_op=fix_op, table_path=table_path)+ case RemapValueOp():+ target_table = _resolve_table(toml_doc=toml_doc, table_path=table_path)+ if target_table is None or fix_op.key not in target_table:+ return _OpResult(FixOpOutcome.SKIPPED, f"key '{fix_op.key}' not found in table '{table_path_str}'")+ current_value = target_table[fix_op.key]+ if not isinstance(current_value, str):+ return _OpResult(FixOpOutcome.SKIPPED, f"value of '{table_path_str}.{fix_op.key}' is not a string")+ new_value = fix_op.mapping.get(str(current_value))+ if new_value is None:+ # The current value is deliberately not named: a report must never echo a value+ # read from a user's file (docs/migration-ledger.md, "What the engine reports").+ return _OpResult(FixOpOutcome.SKIPPED, f"value of '{table_path_str}.{fix_op.key}' is not in this operation's mapping")+ target_table[fix_op.key] = new_value+ return _OpResult(FixOpOutcome.APPLIED)+++def _apply_move_key(*, toml_doc: TOMLDocument, fix_op: MoveKeyOp, table_path: list[str]) -> _OpResult:+ """Relocate one key, creating whatever destination parents are missing.++ Order matters and is the whole reason this is not inline: everything that can refuse the+ move is decided **before** anything is written, so a conflicting move leaves the document+ byte-identical rather than seeded with the empty parent tables it was about to fill.+ """+ table_path_str = ".".join(table_path)+ destination_path_str = ".".join(fix_op.new_table_path)+ source_table = _resolve_table(toml_doc=toml_doc, table_path=table_path)+ if source_table is None or fix_op.key not in source_table:+ return _OpResult(FixOpOutcome.SKIPPED, f"key '{fix_op.key}' not found in table '{table_path_str}'")++ blocking_segment = _first_non_table_segment(toml_doc=toml_doc, table_path=fix_op.new_table_path)+ if blocking_segment is not None:+ return _OpResult(+ FixOpOutcome.CONFLICT, f"destination '{destination_path_str}' is blocked: '{blocking_segment}' is present and is not a table"+ )+ existing_destination = _resolve_table(toml_doc=toml_doc, table_path=fix_op.new_table_path)+ if existing_destination is not None and fix_op.new_key in existing_destination:+ return _OpResult(FixOpOutcome.CONFLICT, f"cannot move to '{destination_path_str}.{fix_op.new_key}': already present")++ moved_value = cast("Item", source_table[fix_op.key])+ del source_table[fix_op.key]+ destination_table = _create_block_table_path(toml_doc=toml_doc, table_path=fix_op.new_table_path)+ destination_table[fix_op.new_key] = moved_value+ return _OpResult(FixOpOutcome.APPLIED)+++def _first_non_table_segment(*, toml_doc: TOMLDocument, table_path: list[str]) -> str | None:+ """The first segment of ``table_path`` that exists and is not a table, if there is one.++ One walk answers the whole question because absence is terminal: once a segment is missing,+ every deeper segment is missing too and the rest of the path is free to be created.+ """+ node = cast("dict[str, Any]", toml_doc)+ for segment in table_path:+ candidate = node.get(segment)+ if candidate is None:+ return None+ if not isinstance(candidate, dict):+ return segment+ node = cast("dict[str, Any]", candidate)+ return None+++def _create_block_table_path(*, toml_doc: TOMLDocument, table_path: list[str]) -> dict[str, Any]:+ """Walk ``table_path``, creating missing segments as block tables, and return the leaf node.++ Block tables rather than inline ones, because this creates a *section* of a configuration+ file — a destination that will hold moved keys and be read by a human. Callers must have+ ruled out a non-table segment first; this function would silently overwrite one.+ """+ node = cast("dict[str, Any]", toml_doc)+ for segment in table_path:+ if not isinstance(node.get(segment), dict):+ node[segment] = tomlkit.table()+ node = cast("dict[str, Any]", node[segment])+ return nodediff --git a/pipelex/pipeline/fixes/fix_loop.py b/pipelex/pipeline/fixes/fix_loop.pyindex e8cbe592b..9fb420926 100644--- a/pipelex/pipeline/fixes/fix_loop.py+++ b/pipelex/pipeline/fixes/fix_loop.py@@ -43,7 +43,7 @@ from pipelex.pipeline.fixes.applicability import is_safe_fix_for_load_scope, is_from pipelex.pipeline.fixes.applier import apply_fix_ops, serialize_and_formatfrom pipelex.pipeline.validate_bundle import validate_bundlefrom pipelex.pipeline.validation_errors import build_validation_error_items-from pipelex.suggested_fix import FixOp, FixOpKind, SuggestedFix+from pipelex.suggested_fix import DeleteKeyOp, DeleteTableOp, EnsureTableOp, FixOp, MoveKeyOp, RemapValueOp, RenameTableKeyOp, SetKeyOp, SuggestedFixfrom pipelex.tools.misc.exceptions import TomlErrorfrom pipelex.tools.misc.toml_utils import load_toml_from_path@@ -245,12 +245,14 @@ class FixBundleResult(BaseModel):def _fix_fingerprint(fix: SuggestedFix) -> str:- """Stable identity of a fix attempt: fix_code + source + each op's (kind, path, key, value, new_key).+ """Stable identity of a fix attempt: ``fix_code`` + ``source`` + every op serialized whole.- ``new_key`` participates so two ``rename_table_key`` ops that differ only in their target name- are distinct fingerprints (they would otherwise collide and trip the no-progress bail).+ Serializing each op rather than listing chosen fields means every field of every variant+ participates by construction — two ``rename_table_key`` ops differing only in their target+ name stay distinct fingerprints (they would otherwise collide and trip the no-progress+ bail), and a new op kind cannot silently collapse two different fixes into one identity."""- op_parts = [f"{op.kind}:{'.'.join(op.table_path)}:{op.key}:{op.value!r}:{op.new_key}" for op in fix.ops]+ op_parts = [op.model_dump_json() for op in fix.ops]return f"{fix.fix_code}|{fix.source}|{'|'.join(op_parts)}"@@ -459,12 +461,12 @@ def _colliding_op_name(value, the ``main_pipe`` remains bundle-local and safe despite same-named sibling pipes.The categorizer cannot see cross-file state, so this suppression lives here."""- match fix_op.kind:- case FixOpKind.RENAME_TABLE_KEY:- if fix_op.table_path == ["pipe"] and fix_op.new_key is not None and fix_op.new_key in other_file_pipe_codes:+ match fix_op:+ case RenameTableKeyOp():+ if fix_op.table_path == ["pipe"] and fix_op.new_key in other_file_pipe_codes:return fix_op.new_keyreturn None- case FixOpKind.SET_KEY:+ case SetKeyOp():if (not fix_op.table_pathand fix_op.key == _MAIN_PIPE_KEY@@ -474,7 +476,7 @@ def _colliding_op_name():return fix_op.valuereturn None- case FixOpKind.ENSURE_TABLE | FixOpKind.DELETE_KEY | FixOpKind.DELETE_TABLE:+ case EnsureTableOp() | DeleteKeyOp() | DeleteTableOp() | MoveKeyOp() | RemapValueOp():return Nonediff --git a/pipelex/pipeline/fixes/planner.py b/pipelex/pipeline/fixes/planner.pyindex 607c5635a..a2dafb981 100644--- a/pipelex/pipeline/fixes/planner.py+++ b/pipelex/pipeline/fixes/planner.py@@ -6,7 +6,7 @@ of the validation report — CLI, API, MCP — sees fixes with zero extra plumbi"""from pipelex.core.exceptions import PipelexBundleBlueprintValidationErrorData, PipesAndConceptValidationErrorData-from pipelex.suggested_fix import FixOp, FixOpKind, FixSafety, SuggestedFix+from pipelex.suggested_fix import DeleteKeyOp, EnsureTableOp, FixOp, FixSafety, RenameTableKeyOp, SetKeyOp, SuggestedFixMATCH_SEQUENCE_OUTPUT_FIX_CODE = "match-sequence-output"SYNC_CONTROLLER_INPUTS_FIX_CODE = "sync-controller-inputs"@@ -52,8 +52,7 @@ def _plan_match_sequence_output(error_data: PipesAndConceptValidationErrorData)safety=FixSafety.SAFE,source=error_data.source,ops=[- FixOp(- kind=FixOpKind.SET_KEY,+ SetKeyOp(table_path=["pipe", error_data.pipe_code],key="output",value=error_data.expected_output_ref,@@ -79,10 +78,9 @@ def _plan_sync_controller_inputs(error_data: PipesAndConceptValidationErrorData)return Nonevariables = ", ".join(f"'{var_name}'" for var_name in error_data.expected_inputs)inputs_table_path = ["pipe", error_data.pipe_code, "inputs"]- create_ops = [FixOp(kind=FixOpKind.ENSURE_TABLE, table_path=inputs_table_path)]+ create_ops: list[FixOp] = [EnsureTableOp(table_path=inputs_table_path)]create_ops.extend(- FixOp(kind=FixOpKind.SET_KEY, table_path=inputs_table_path, key=var_name, value=expected_ref)- for var_name, expected_ref in error_data.expected_inputs.items()+ SetKeyOp(table_path=inputs_table_path, key=var_name, value=expected_ref) for var_name, expected_ref in error_data.expected_inputs.items())return SuggestedFix(fix_code=SYNC_CONTROLLER_INPUTS_FIX_CODE,@@ -102,11 +100,11 @@ def _plan_sync_controller_inputs(error_data: PipesAndConceptValidationErrorData)if declared_ref == expected_ref:continue(added if declared_ref is None else updated).append(var_name)- ops.append(FixOp(kind=FixOpKind.SET_KEY, table_path=inputs_table_path, key=var_name, value=expected_ref))+ ops.append(SetKeyOp(table_path=inputs_table_path, key=var_name, value=expected_ref))for var_name in error_data.declared_inputs:if var_name not in error_data.expected_inputs:removed.append(var_name)- ops.append(FixOp(kind=FixOpKind.DELETE_KEY, table_path=inputs_table_path, key=var_name))+ ops.append(DeleteKeyOp(table_path=inputs_table_path, key=var_name))if not ops:# The renderings already agree (e.g. two concepts that render to the same relative ref):# an empty diff would be a no-op fix the loop applies forever — suppress instead.@@ -158,8 +156,7 @@ def _plan_strip_native_concept_redecl(error_data: PipelexBundleBlueprintValidatisafety=FixSafety.SAFE,source=error_data.source,ops=[- FixOp(- kind=FixOpKind.DELETE_KEY,+ DeleteKeyOp(table_path=["concept"],key=error_data.concept_code,),@@ -187,8 +184,7 @@ def _plan_strip_namespace(error_data: PipelexBundleBlueprintValidationErrorData)safety=FixSafety.SAFE,source=error_data.source,ops=[- FixOp(- kind=FixOpKind.RENAME_TABLE_KEY,+ RenameTableKeyOp(table_path=["pipe"],key=error_data.pipe_code,new_key=error_data.stripped_pipe_code,@@ -201,8 +197,7 @@ def _plan_strip_namespace(error_data: PipelexBundleBlueprintValidationErrorData)safety=FixSafety.SAFE,source=error_data.source,ops=[- FixOp(- kind=FixOpKind.SET_KEY,+ SetKeyOp(table_path=[],key="main_pipe",value=error_data.stripped_pipe_code,diff --git a/pipelex/suggested_fix.py b/pipelex/suggested_fix.pyindex 0b443c10f..1a3a371d7 100644--- a/pipelex/suggested_fix.py+++ b/pipelex/suggested_fix.py@@ -4,15 +4,22 @@ Each fixable ``ValidationErrorItem`` carries a ``SuggestedFix``: semantic patchby TOML path, translated by the fix planner from enriched typed errors (never from messagestrings). The ops are the machine contract; any rendered diff is presentation.+The op vocabulary is a **discriminated union on ``kind``**: each variant declares exactly the+fields its own semantics need, so a malformed op is refused by pydantic at parse time rather+than by a hand-written shape check deep inside the applier. It is published as two subsets —+:data:`FixOp`, every kind, for the ``.mthds`` fix path, and :data:`MigrationOp`, the structural+kinds only, for configuration migration ledgers. The narrower alias is what makes a ledger+containing a materializing op fail when the ledger is parsed. See ``docs/migration-ledger.md``.+This module is deliberately low-level (stdlib + pydantic only) so that``pipelex.base_exceptions`` — where ``ValidationErrorItem`` lives — can import it withoutcreating an import cycle. Naming is brand-neutral: fixes are a language-level concept."""from enum import StrEnum-from typing import TypeAlias+from typing import Annotated, Literal, TypeAlias, Union-from pydantic import BaseModel, ConfigDict, Field+from pydantic import BaseModel, ConfigDict, Field, field_validator# A TOML-representable value for a set_key op: a scalar (output refs, input refs), or a flat# scalar mapping for fixes that create a whole table at once (written as an inline table —@@ -20,6 +27,13 @@ from pydantic import BaseModel, ConfigDict, FieldTomlScalar: TypeAlias = str | int | float | boolTomlValue: TypeAlias = TomlScalar | dict[str, TomlScalar]+# The wildcard path segment. It stands for "every entry of the open mapping at this node" — a+# field typed as a mapping from arbitrary user-chosen keys to a value schema, where the keys+# belong to the user and the value schema belongs to us. The applier expands it over the keys+# the document actually holds; deciding whether a given node really is open is the migration+# gate's job, since only the fingerprint knows.+WILDCARD_SEGMENT = "*"+class FixOpKind(StrEnum):"""The semantic patch operations a suggested fix is composed of."""@@ -29,6 +43,23 @@ class FixOpKind(StrEnum):DELETE_KEY = "delete_key"DELETE_TABLE = "delete_table"RENAME_TABLE_KEY = "rename_table_key"+ MOVE_KEY = "move_key"+ REMAP_VALUE = "remap_value"++ @property+ def is_structural(self) -> bool:+ """Whether the kind only removes, renames or relocates material already in the file.++ The structural kinds are exactly the ones a migration ledger may contain. The+ materializing kinds write values that were not there, which is right when a typed error+ names the exact key to write and wrong under always-replay, where it would overwrite a+ user's choice on every run.+ """+ match self:+ case FixOpKind.SET_KEY | FixOpKind.ENSURE_TABLE:+ return False+ case FixOpKind.DELETE_KEY | FixOpKind.DELETE_TABLE | FixOpKind.RENAME_TABLE_KEY | FixOpKind.MOVE_KEY | FixOpKind.REMAP_VALUE:+ return Trueclass FixSafety(StrEnum):@@ -46,22 +77,120 @@ class FixSafety(StrEnum):return False-class FixOp(BaseModel):- """One semantic patch op addressed by TOML path.+class FixOpBase(BaseModel):+ """Fields every op shares: the table it acts in.``table_path`` addresses the containing table (e.g. ``["pipe", "my_seq"]``), aligned with- the ``field_path`` conventions of validation errors. For ``ensure_table`` it addresses the- table to create when absent. ``key`` / ``value`` are used by ``set_key`` / ``delete_key``;- ``new_key`` only by ``rename_table_key``.+ the ``field_path`` conventions of validation errors, and is empty for the document root.+ Variants add whatever their own semantics require, and nothing else — ``extra="forbid"``+ turns a field named on the wrong kind into a parse error."""model_config = ConfigDict(frozen=True, extra="forbid")- kind: FixOpKind = Field(strict=False)table_path: list[str]- key: str | None = None- value: TomlValue | None = None- new_key: str | None = None+++class SetKeyOp(FixOpBase):+ """Write ``key = value`` in the addressed table, whatever it currently holds."""++ kind: Literal[FixOpKind.SET_KEY] = FixOpKind.SET_KEY+ key: str+ value: TomlValue+++class EnsureTableOp(FixOpBase):+ """Create the addressed table when it is absent, leaving an existing one untouched.++ Here ``table_path`` addresses the table to create, not its parent, so it cannot be empty:+ the document root always exists.+ """++ kind: Literal[FixOpKind.ENSURE_TABLE] = FixOpKind.ENSURE_TABLE+ table_path: list[str] = Field(min_length=1)+++class DeleteKeyOp(FixOpBase):+ """Drop ``key`` from the addressed table."""++ kind: Literal[FixOpKind.DELETE_KEY] = FixOpKind.DELETE_KEY+ key: str+++class DeleteTableOp(FixOpBase):+ """Drop the addressed table, including every chunk of one written out of order.++ ``table_path`` *is* the target rather than its parent, so it cannot be empty — deleting the+ document root is not a thing an op may express.+ """++ kind: Literal[FixOpKind.DELETE_TABLE] = FixOpKind.DELETE_TABLE+ table_path: list[str] = Field(min_length=1)+++class RenameTableKeyOp(FixOpBase):+ """Rename ``key`` to ``new_key`` in place within the addressed table, keeping its position."""++ kind: Literal[FixOpKind.RENAME_TABLE_KEY] = FixOpKind.RENAME_TABLE_KEY+ key: str+ new_key: str+++class MoveKeyOp(FixOpBase):+ """Relocate ``key`` from the addressed table into ``new_table_path``, under ``new_key``.++ The moved key may be table-valued, in which case the whole subtree travels. Destination+ parents that do not exist are created, as block tables, as part of the operation. Position+ is preserved within a parent and never across parents — see ``docs/migration-ledger.md``+ for the placement rule and for what happens to a moved table's introducing comment.+ """++ kind: Literal[FixOpKind.MOVE_KEY] = FixOpKind.MOVE_KEY+ key: str+ new_table_path: list[str]+ new_key: str++ @field_validator("new_table_path")+ @classmethod+ def refuse_wildcard_destination(cls, new_table_path: list[str]) -> list[str]:+ """A destination cannot be a wildcard: there would be no rule for which entry receives it.++ A wildcard *source* is unambiguous — it means "each of these" — but "move each entry's+ key into *some* entry" names no target. Should a real need for a mirrored source and+ destination appear, it wants an explicit correspondence rule, not this silence.+ """+ if WILDCARD_SEGMENT in new_table_path:+ msg = f"a move_key destination may not contain the wildcard segment '{WILDCARD_SEGMENT}'"+ raise ValueError(msg)+ return new_table_path+++class RemapValueOp(FixOpBase):+ """Rewrite ``key``'s value through ``mapping``, doing nothing when it is not a mapped value.++ Only string values are remapped: the operation exists for renamed enumerated values, whose+ TOML representation is always a string.+ """++ kind: Literal[FixOpKind.REMAP_VALUE] = FixOpKind.REMAP_VALUE+ key: str+ mapping: dict[str, str] = Field(min_length=1)+++# Every kind, for the `.mthds` fix path: a planner derives ops from one typed error about one+# key, so materializing ops are correct there.+FixOp: TypeAlias = Annotated[+ Union[SetKeyOp, EnsureTableOp, DeleteKeyOp, DeleteTableOp, RenameTableKeyOp, MoveKeyOp, RemapValueOp],+ Field(discriminator="kind"),+]++# The structural kinds only, for configuration migration ledgers, where every entry is replayed+# over every file on every run. Validating a ledger against this alias is what turns "a ledger+# must not materialize" from a review rule into a parse error.+MigrationOp: TypeAlias = Annotated[+ Union[DeleteKeyOp, DeleteTableOp, RenameTableKeyOp, MoveKeyOp, RemapValueOp],+ Field(discriminator="kind"),+]class SuggestedFix(BaseModel):diff --git a/pipelex/system/configuration/config_loader.py b/pipelex/system/configuration/config_loader.pyindex 29fb321ef..76f9a66ae 100644--- a/pipelex/system/configuration/config_loader.py+++ b/pipelex/system/configuration/config_loader.py@@ -4,6 +4,7 @@ from typing import Any, TypeVarfrom pydantic import BaseModel+from pipelex.system.configuration.config_surface import strip_reserved_metafrom pipelex.system.runtime import runtime_managerfrom pipelex.tools.misc.json_utils import deep_updatefrom pipelex.tools.misc.toml_utils import load_toml_from_path_and_merge_with_overrides@@ -338,6 +339,7 @@ class ConfigLoader:list_of_configs.append(Path.cwd() / "tests" / f"pipelex_{runtime_manager.run_mode}.toml")merged = load_toml_from_path_and_merge_with_overrides(paths=list_of_configs)+ strip_reserved_meta(config_dict=merged)if extra_overrides:deep_update(merged, updates=extra_overrides)return mergeddiff --git a/pipelex/system/configuration/config_surface.py b/pipelex/system/configuration/config_surface.pynew file mode 100644index 000000000..18dc1521d--- /dev/null+++ b/pipelex/system/configuration/config_surface.py@@ -0,0 +1,41 @@+"""Read-side helper shared by every configuration surface.++A **configuration surface** is one family of user-owned TOML files with one schema and one+migration ledger — today `pipelex.toml` and its tiers, `telemetry.toml`, and+`pipelex_service.toml`. What they share on the read path is the reserved `[meta]` table, and+this module is the one place that knows about it.++The strip lives here and deliberately **not** in the generic TOML reader+(`pipelex.tools.misc.toml_utils`), which also reads `.mthds` files, backend definitions and the+kit index — none of which reserve that key, and all of which should keep rejecting it.++See `docs/migration-ledger.md` → "Schema versions, and why every run replays everything".+"""++from typing import Any, cast++# The reserved in-file table and key. Every configuration-surface reader tolerates them and+# strips them before validation; **nothing writes them**. The reason not to write is team skew+# on tracked files: a project's `.pipelex/pipelex.toml` is shared through git, so one developer+# on a newer pipelex stamping the key would break a teammate on last week's build the same+# afternoon.+RESERVED_META_TABLE = "meta"+RESERVED_SCHEMA_VERSION_KEY = "schema_version"+++def strip_reserved_meta(*, config_dict: dict[str, Any]) -> None:+ """Remove the reserved `[meta] schema_version` from a loaded configuration, in place.++ Only that one key is removed, and `[meta]` itself only when nothing else is left in it — a+ `[meta]` table carrying anything else is not reserved and must keep failing validation+ loudly under `extra="forbid"`, rather than being quietly swallowed along with it.+ """+ meta_table = config_dict.get(RESERVED_META_TABLE)+ if not isinstance(meta_table, dict):+ return+ typed_meta_table = cast("dict[str, Any]", meta_table)+ if RESERVED_SCHEMA_VERSION_KEY not in typed_meta_table:+ return+ del typed_meta_table[RESERVED_SCHEMA_VERSION_KEY]+ if not typed_meta_table:+ del config_dict[RESERVED_META_TABLE]diff --git a/pipelex/system/pipelex_service/pipelex_service_config.py b/pipelex/system/pipelex_service/pipelex_service_config.pyindex 35f97ead0..18dd88fff 100644--- a/pipelex/system/pipelex_service/pipelex_service_config.py+++ b/pipelex/system/pipelex_service/pipelex_service_config.py@@ -6,6 +6,7 @@ from pydantic import Field, ValidationErrorfrom pipelex.cogt.model_backends.backend import PipelexBackendfrom pipelex.system.configuration.config_loader import config_managerfrom pipelex.system.configuration.config_model import ConfigModel+from pipelex.system.configuration.config_surface import strip_reserved_metafrom pipelex.system.pipelex_service.exceptions import PipelexServiceConfigValidationErrorfrom pipelex.system.pipelex_service.pipelex_service_agreement import (PIPELEX_SERVICE_CONFIG_FILE_NAME,@@ -17,7 +18,10 @@ from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_errorclass PipelexServiceConfig(ConfigModel):- agreement: PipelexServiceAgreement+ # A default_factory, not a required field: this is the surface's defaults layer. Every+ # in-scope configuration surface must have one, because it is what makes an additive schema+ # change absorbable and therefore never a migration — see docs/migration-ledger.md.+ agreement: PipelexServiceAgreement = Field(default_factory=PipelexServiceAgreement)onboarding: PipelexServiceOnboarding = Field(default_factory=PipelexServiceOnboarding)@@ -33,6 +37,7 @@ def load_pipelex_service_config_if_exists(config_dir: Path) -> PipelexServiceConconfig_path = config_dir / PIPELEX_SERVICE_CONFIG_FILE_NAMEtry:config_toml = load_toml_from_path(path=config_path)+ strip_reserved_meta(config_dict=config_toml)return PipelexServiceConfig.model_validate(config_toml)except FileNotFoundError:return Nonediff --git a/pipelex/system/telemetry/telemetry_config.py b/pipelex/system/telemetry/telemetry_config.pyindex b6912e8be..db0457ba4 100644--- a/pipelex/system/telemetry/telemetry_config.py+++ b/pipelex/system/telemetry/telemetry_config.py@@ -6,6 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validafrom pipelex.system.configuration.config_loader import config_managerfrom pipelex.system.configuration.config_model import ConfigModel+from pipelex.system.configuration.config_surface import strip_reserved_metafrom pipelex.system.telemetry.exceptions import TelemetryConfigValidationErrorfrom pipelex.tools.misc.dict_utils import apply_to_strings_recursivefrom pipelex.tools.misc.toml_utils import load_toml_from_path_and_merge_with_overrides@@ -277,6 +278,7 @@ def load_telemetry_config(*, secrets_provider: SecretsProviderAbstract) -> Telemtelemetry_config_paths.append(project_config_dir / TELEMETRY_CONFIG_FILE_NAME)telemetry_config_paths.append(project_config_dir / TELEMETRY_CONFIG_OVERRIDE_FILE_NAME)telemetry_config_toml_raw = load_toml_from_path_and_merge_with_overrides(paths=telemetry_config_paths)+ strip_reserved_meta(config_dict=telemetry_config_toml_raw)# Apply variable substitution to all string values (keep placeholders for missing vars)substitute_vars_with_provider = partial(substitute_vars, secrets_provider=secrets_provider, raise_on_missing_var=False)diff --git a/tests/data/errors/error_identity.txt b/tests/data/errors/error_identity.txtindex 300802c42..5dff4acfe 100644--- a/tests/data/errors/error_identity.txt+++ b/tests/data/errors/error_identity.txt@@ -153,6 +153,10 @@ 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/+MigrationError | Migration error | https://docs.pipelex.com/latest/errors/migration-error/+MigrationGoldenError | Migration golden error | https://docs.pipelex.com/latest/errors/migration-golden-error/+MigrationLedgerError | Migration ledger error | https://docs.pipelex.com/latest/errors/migration-ledger-error/+MigrationRegistryError | Migration registry error | https://docs.pipelex.com/latest/errors/migration-registry-error/MissingBundleValidatorError | Missing bundle validator | https://docs.pipelex.com/latest/errors/missing-bundle-validator-error/MissingDependencyError | Missing dependency | https://docs.pipelex.com/latest/errors/missing-dependency-error/MissingOrchestratorError | Missing orchestrator | https://docs.pipelex.com/latest/errors/missing-orchestrator-error/diff --git a/tests/unit/pipelex/migration/test_coverage_gate.py b/tests/unit/pipelex/migration/test_coverage_gate.pynew file mode 100644index 000000000..27c3f0451--- /dev/null+++ b/tests/unit/pipelex/migration/test_coverage_gate.py@@ -0,0 +1,587 @@+"""Unit tests for the coverage gate — the forcing function that makes a schema change say what it did.++Every test here points the gate at a **synthetic** surface with a fixture ledger and a fixture+golden chain in a temporary directory. That is not incidental: the surface registry is an injected+parameter precisely so gate *behaviour* can be tested against something that never moves. Wire the+real configuration models in here and every legitimate configuration change turns this suite red+alongside the gate, and the fix everyone learns is "regenerate the goldens" — which is how a gate+goes permanently green while catching nothing. The real surfaces get one smoke test, and it lives+in `test_real_surfaces.py`.++The shape of each test is the same: describe schema 1 and schema 2 as two synthetic models, write+the golden the gate will compare against, hand it a ledger entry, and assert which guarantee broke.+"""++from enum import StrEnum+from pathlib import Path++from pydantic import BaseModel++from pipelex.migration.coverage import CoverageIssue, CoverageIssueKind, check_surface, diff_fingerprints+from pipelex.migration.fingerprint import compute_fingerprint+from pipelex.migration.goldens import write_defaults_golden, write_fingerprint_golden+from pipelex.migration.ledger import ledgers_dir+from pipelex.migration.surfaces import DefaultsLayerKind, Surface++SURFACE_ID = "synthetic-config"+++class _Tier(StrEnum):+ BASIC = "basic"+ PREMIUM = "premium"+++class _TierWithoutBasic(StrEnum):+ PREMIUM = "premium"+ STANDARD = "standard"+++class _SchemaOne(BaseModel):+ """The starting shape: a section with two keys, one of them enumerated."""++ label: str = "hello"+ tier: _Tier = _Tier.BASIC+++class _SchemaTwoRenamed(BaseModel):+ """`label` renamed to `title`."""++ title: str = "hello"+ tier: _Tier = _Tier.BASIC+++class _SchemaTwoRemoved(BaseModel):+ """`label` dropped outright."""++ tier: _Tier = _Tier.BASIC+++class _SchemaTwoEnumMemberGone(BaseModel):+ """`basic` is no longer a legal spelling of `tier`."""++ label: str = "hello"+ tier: _TierWithoutBasic = _TierWithoutBasic.PREMIUM+++class _SchemaTwoTierRenamedAndMemberGone(BaseModel):+ """`tier` renamed to `level` *and* `basic` dropped, in the same schema version."""++ label: str = "hello"+ level: _TierWithoutBasic = _TierWithoutBasic.PREMIUM+++class _SchemaOneWithBothNames(BaseModel):+ """A starting shape that already has `title`, so a rename of `label` onto it collides."""++ label: str = "hello"+ title: str = "world"+ tier: _Tier = _Tier.BASIC+++def _surface(*, config_model: type[BaseModel]) -> Surface:+ return Surface(+ surface_id=SURFACE_ID,+ title="A synthetic surface",+ base_file="synthetic.toml",+ tier_glob="synthetic_*.toml",+ config_model=config_model,+ defaults_layer_kind=DefaultsLayerKind.MODEL_DEFAULTS,+ )+++def _write_ledger(*, migration_dir: Path, current_schema_version: int, entries: str = "") -> None:+ directory = ledgers_dir(migration_dir=migration_dir)+ directory.mkdir(parents=True, exist_ok=True)+ body = f"""+[surface]+id = "{SURFACE_ID}"+title = "A synthetic surface"+base_file = "synthetic.toml"+tier_glob = "synthetic_*.toml"+current_schema_version = {current_schema_version}+min_supported_schema_version = 0+{entries}+"""+ (directory / f"{SURFACE_ID}.toml").write_text(body, encoding="utf-8")+++def _snapshot(*, migration_dir: Path, config_model: type[BaseModel], schema_version: int) -> None:+ surface = _surface(config_model=config_model)+ write_fingerprint_golden(+ migration_dir=migration_dir,+ fingerprint=compute_fingerprint(+ surface_id=SURFACE_ID,+ schema_version=schema_version,+ config_model=config_model,+ defaults_document=surface.read_defaults_document(),+ ),+ )+++def _kinds(issues: list[CoverageIssue]) -> list[CoverageIssueKind]:+ return [issue.kind for issue in issues]+++def _rename_entry(*, new_key: str = "title", safety: str = "safe") -> str:+ return f"""+[[migration]]+id = "{SURFACE_ID}@2"+to_schema_version = 2+introduced_in = "0.46.0"+breaking = true+safety = "{safety}"+title = "Rename label to title"+description = "The key was renamed."++[[migration.ops]]+kind = "rename_table_key"+table_path = []+key = "label"+new_key = "{new_key}"+"""+++class TestTheSteadyState:+ def test_a_surface_whose_golden_matches_its_models_passes(self, tmp_path: Path) -> None:+ """The overwhelmingly common state: nothing changed, so nothing is owed."""+ _write_ledger(migration_dir=tmp_path, current_schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ assert check_surface(surface=_surface(config_model=_SchemaOne), migration_dir=tmp_path) == []++ def test_a_surface_with_no_snapshot_at_all_asks_for_one(self, tmp_path: Path) -> None:+ """The bootstrap state, and the only one with no diff to show."""+ _write_ledger(migration_dir=tmp_path, current_schema_version=1)+ issues = check_surface(surface=_surface(config_model=_SchemaOne), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.SNAPSHOT_PENDING]+++class TestTheHeadLink:+ def test_an_additive_change_asks_for_a_regeneration_and_demands_no_entry(self, tmp_path: Path) -> None:+ """A key we add is supplied by the defaults layer, so an old file still validates."""+ _write_ledger(migration_dir=tmp_path, current_schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoRemoved, schema_version=1)+ issues = check_surface(surface=_surface(config_model=_SchemaOne), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.FINGERPRINT_DRIFTED]+ assert "label" in issues[0].message++ def test_a_removal_without_a_bump_is_refused(self, tmp_path: Path) -> None:+ """The whole point of the gate: this is the change that breaks a user's boot."""+ _write_ledger(migration_dir=tmp_path, current_schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoRemoved), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.REMOVAL_NEEDS_A_BUMP]+ assert f"{SURFACE_ID}@2" in issues[0].message++ def test_a_lost_enum_member_without_a_bump_is_refused_too(self, tmp_path: Path) -> None:+ """A renamed enumerated value breaks a file exactly as a renamed key does."""+ _write_ledger(migration_dir=tmp_path, current_schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoEnumMemberGone), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.REMOVAL_NEEDS_A_BUMP]+ assert "basic" in issues[0].message++ def test_a_stale_reference_document_is_caught_even_when_the_fingerprint_matches(self, tmp_path: Path) -> None:+ """`[email protected]` is a checked-in copy of a live document, and the fingerprint diff+ cannot see it drift — an edited value inside an unchanged path moves the file, not the+ path set. Left unchecked, two copies of the same document quietly disagree.+ """+ _write_ledger(migration_dir=tmp_path, current_schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ write_defaults_golden(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=1, document='label = "stale"\n')+ issues = check_surface(surface=_surface(config_model=_SchemaOne), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.FINGERPRINT_DRIFTED]+ assert "[email protected]" in issues[0].message++ def test_a_bump_whose_snapshot_has_not_been_taken_says_so(self, tmp_path: Path) -> None:+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=_rename_entry())+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoRenamed), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.SNAPSHOT_PENDING]++ def test_a_gap_in_the_golden_chain_is_reported_not_papered_over(self, tmp_path: Path) -> None:+ """Only the head link may fall back to the live fingerprint.++ Substituting it for a missing golden lower down would compare an old entry against today's+ models and blame the entry for the mismatch.+ """+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=_rename_entry())+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoRenamed, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoRenamed), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.GOLDEN_MISSING]+ assert "schema version 1" in issues[0].message+++class TestEntryAccounting:+ def test_a_correct_rename_entry_is_green(self, tmp_path: Path) -> None:+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=_rename_entry())+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoRenamed, schema_version=2)+ assert check_surface(surface=_surface(config_model=_SchemaTwoRenamed), migration_dir=tmp_path) == []++ def test_a_misspelled_destination_is_caught(self, tmp_path: Path) -> None:+ """Without the cross-check this passes coverage *and* convergence, then migrates every+ user file to a key `extra="forbid"` rejects, with the tool reporting success.+ """+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=_rename_entry(new_key="titel"))+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoRenamed, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoRenamed), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.UNACCOUNTED_PATH]+ assert "titel" in issues[0].message++ def test_a_removal_with_no_operation_accounting_for_it_is_caught(self, tmp_path: Path) -> None:+ entry = f"""+[[migration]]+id = "{SURFACE_ID}@2"+to_schema_version = 2+introduced_in = "0.46.0"+breaking = true+safety = "unsafe"+title = "Drop label"+description = "The key is gone, and this entry forgot to say so."+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=entry)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoRemoved, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoRemoved), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.UNACCOUNTED_PATH]+ assert "label" in issues[0].message++ def test_over_deletion_is_caught(self, tmp_path: Path) -> None:+ """An entry that deletes a path the new schema still has would destroy live configuration."""+ entry = f"""+[[migration]]+id = "{SURFACE_ID}@2"+to_schema_version = 2+introduced_in = "0.46.0"+breaking = true+safety = "safe"+title = "Drop too much"+description = "Deletes tier as well, which schema 2 still has."++[[migration.ops]]+kind = "delete_key"+table_path = []+key = "label"++[[migration.ops]]+kind = "delete_key"+table_path = []+key = "tier"+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=entry)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoRemoved, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoRemoved), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.OVER_DELETION]+ assert "tier" in issues[0].message++ def test_an_operation_whose_source_never_existed_is_caught(self, tmp_path: Path) -> None:+ """A dead operation is silent forever: it skips on every file and reports success."""+ entry = f"""+[[migration]]+id = "{SURFACE_ID}@2"+to_schema_version = 2+introduced_in = "0.46.0"+breaking = true+safety = "safe"+title = "Rename a key that was never there"+description = "A typo in the source name."++[[migration.ops]]+kind = "rename_table_key"+table_path = []+key = "lable"+new_key = "title"+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=entry)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoRenamed, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoRenamed), migration_dir=tmp_path)+ assert CoverageIssueKind.DEAD_OP in _kinds(issues)+ assert "lable" in issues[0].message++ def test_a_delete_table_aimed_at_a_key_is_dead(self, tmp_path: Path) -> None:+ """The applier deletes a table only where the path *is* a table; on a key it skips forever.++ The walk has to say the same, or an entry that never fires passes the gate — and the+ key it meant to remove is then reported unaccounted for, which is exactly right.+ """+ entry = f"""+[[migration]]+id = "{SURFACE_ID}@2"+to_schema_version = 2+introduced_in = "0.46.0"+breaking = true+safety = "safe"+title = "Drop label with the wrong operation"+description = "label is a key, not a table."++[[migration.ops]]+kind = "delete_table"+table_path = ["label"]+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=entry)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoRemoved, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoRemoved), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.DEAD_OP, CoverageIssueKind.UNACCOUNTED_PATH]+ assert "delete_key" in issues[0].message++ def test_a_safe_rename_onto_a_path_the_old_schema_already_had_is_refused(self, tmp_path: Path) -> None:+ """The applier refuses to clobber an occupied destination, so a file carrying both keys —+ a perfectly valid schema-1 file — would come back CONFLICT on every run. The walk must not+ quietly overwrite what the applier will not.+ """+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=_rename_entry())+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOneWithBothNames, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoRenamed, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoRenamed), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.DESTINATION_OCCUPIED]+ assert "title" in issues[0].message++ def test_an_unsafe_rename_onto_an_occupied_path_is_allowed(self, tmp_path: Path) -> None:+ """An unsafe entry is reported and never applied, so its operations never conflict."""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=_rename_entry(safety="unsafe"))+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOneWithBothNames, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoRenamed, schema_version=2)+ assert check_surface(surface=_surface(config_model=_SchemaTwoRenamed), migration_dir=tmp_path) == []+++class TestEnumAccounting:+ def _entry_with_ops(self, *, safety: str, ops: str) -> str:+ return f"""+[[migration]]+id = "{SURFACE_ID}@2"+to_schema_version = 2+introduced_in = "0.46.0"+breaking = true+safety = "{safety}"+title = "Retire the basic tier"+description = "The spelling changed."+{ops}+"""++ def test_a_removed_member_with_no_remap_is_caught(self, tmp_path: Path) -> None:+ """A `safe` entry needs at least one operation, and no live one exists for this schema+ pair, so the fixture carries a filler `delete_key` on a path that never existed. That is+ a dead operation by construction and is reported as one; the member loss is the finding.+ """+ ops = """+[[migration.ops]]+kind = "delete_key"+table_path = []+key = "nothing_relevant"+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=self._entry_with_ops(safety="safe", ops=ops))+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoEnumMemberGone, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoEnumMemberGone), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.DEAD_OP, CoverageIssueKind.ENUM_MEMBER_NOT_REMAPPED]+ assert "basic" in issues[1].message++ def test_a_member_lost_by_a_renamed_path_is_still_caught(self, tmp_path: Path) -> None:+ """Enum accounting follows the path through the entry's own renames.++ The old and new fingerprints share no name for this path — `tier` became `level` — so a+ comparison over shared names would never look at it, and a file carrying `basic` would+ be migrated to a key that rejects it.+ """+ ops = """+[[migration.ops]]+kind = "rename_table_key"+table_path = []+key = "tier"+new_key = "level"+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=self._entry_with_ops(safety="safe", ops=ops))+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoTierRenamedAndMemberGone, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoTierRenamedAndMemberGone), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.ENUM_MEMBER_NOT_REMAPPED]+ assert "basic" in issues[0].message++ def test_a_remap_after_the_rename_accounts_for_the_lost_member(self, tmp_path: Path) -> None:+ """Operations chain: the remap addresses the key by its *new* name, and is attributed to the origin."""+ ops = """+[[migration.ops]]+kind = "rename_table_key"+table_path = []+key = "tier"+new_key = "level"++[[migration.ops]]+kind = "remap_value"+table_path = []+key = "level"+mapping = { basic = "standard" }+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=self._entry_with_ops(safety="safe", ops=ops))+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoTierRenamedAndMemberGone, schema_version=2)+ assert check_surface(surface=_surface(config_model=_SchemaTwoTierRenamedAndMemberGone), migration_dir=tmp_path) == []++ def test_a_removed_member_with_a_matching_remap_is_green(self, tmp_path: Path) -> None:+ ops = """+[[migration.ops]]+kind = "remap_value"+table_path = []+key = "tier"+mapping = { basic = "standard" }+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=self._entry_with_ops(safety="safe", ops=ops))+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoEnumMemberGone, schema_version=2)+ assert check_surface(surface=_surface(config_model=_SchemaTwoEnumMemberGone), migration_dir=tmp_path) == []++ def test_an_unsafe_entry_may_leave_a_removed_member_unremapped(self, tmp_path: Path) -> None:+ """`unsafe` means reported and never applied, so it is allowed to describe what no operation can do."""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=self._entry_with_ops(safety="unsafe", ops=""))+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoEnumMemberGone, schema_version=2)+ assert check_surface(surface=_surface(config_model=_SchemaTwoEnumMemberGone), migration_dir=tmp_path) == []++ def test_a_safe_remap_of_a_value_that_is_still_legal_is_refused(self, tmp_path: Path) -> None:+ """The remap legality rule, and the reason replay neutrality holds.++ `premium` is still a legal tier at schema 2, so a user who chose it deliberately would+ have it rewritten on every run — and replay over a current-valid file would not be a no-op.+ """+ ops = """+[[migration.ops]]+kind = "remap_value"+table_path = []+key = "tier"+mapping = { basic = "standard", premium = "standard" }+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=self._entry_with_ops(safety="safe", ops=ops))+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoEnumMemberGone, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoEnumMemberGone), migration_dir=tmp_path)+ assert CoverageIssueKind.ILLEGAL_REMAP in _kinds(issues)+ assert "premium" in " ".join(issue.message for issue in issues)++ def test_a_remap_to_a_spelling_the_new_schema_rejects_is_refused(self, tmp_path: Path) -> None:+ """The value-side twin of the misspelled rename destination.++ Rewriting to a spelling the new schema does not accept migrates every file to something+ the model rejects, with the tool reporting success.+ """+ ops = """+[[migration.ops]]+kind = "remap_value"+table_path = []+key = "tier"+mapping = { basic = "standrad" }+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=self._entry_with_ops(safety="safe", ops=ops))+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaTwoEnumMemberGone, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaTwoEnumMemberGone), migration_dir=tmp_path)+ assert CoverageIssueKind.ILLEGAL_REMAP in _kinds(issues)+ assert "standrad" in " ".join(issue.message for issue in issues)++ def test_a_safe_remap_of_a_free_string_is_refused(self, tmp_path: Path) -> None:+ """Where the schema does not enumerate, staleness cannot be proven and the entry must be unsafe."""+ ops = """+[[migration.ops]]+kind = "remap_value"+table_path = []+key = "label"+mapping = { hello = "hi" }+"""+ _write_ledger(migration_dir=tmp_path, current_schema_version=2, entries=self._entry_with_ops(safety="safe", ops=ops))+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=2)+ issues = check_surface(surface=_surface(config_model=_SchemaOne), migration_dir=tmp_path)+ assert CoverageIssueKind.ILLEGAL_REMAP in _kinds(issues)+++class TestTheDefaultsLayerRule:+ def test_a_required_path_with_no_defaults_layer_value_is_refused(self, tmp_path: Path) -> None:+ """The rule that keeps the whole vocabulary structural.++ Writing the value into the user's file instead would convert an inherited value into an+ explicitly set one, pinning it against every future change to that default — a semantic+ edit dressed up as a fix.+ """++ class _NeedsAValue(BaseModel):+ label: str++ packaged = tmp_path / "packaged.toml"+ packaged.write_text("", encoding="utf-8")+ surface = Surface(+ surface_id=SURFACE_ID,+ title="A synthetic surface",+ base_file="synthetic.toml",+ tier_glob="synthetic_*.toml",+ config_model=_NeedsAValue,+ defaults_layer_kind=DefaultsLayerKind.PACKAGED_DOCUMENT,+ packaged_document_path=packaged,+ )+ _write_ledger(migration_dir=tmp_path, current_schema_version=1)+ issues = check_surface(surface=surface, migration_dir=tmp_path)+ assert CoverageIssueKind.REQUIRED_PATH_WITHOUT_DEFAULT in _kinds(issues)+ assert "give it a default" in issues[0].message++ def test_a_wildcard_path_is_exempt(self, tmp_path: Path) -> None:+ """The keys beneath an open node are the user's, so there is no value to supply."""++ class _OpenNode(BaseModel):+ deck: dict[str, str] = {}++ packaged = tmp_path / "packaged.toml"+ packaged.write_text("", encoding="utf-8")+ surface = Surface(+ surface_id=SURFACE_ID,+ title="A synthetic surface",+ base_file="synthetic.toml",+ tier_glob="synthetic_*.toml",+ config_model=_OpenNode,+ defaults_layer_kind=DefaultsLayerKind.PACKAGED_DOCUMENT,+ packaged_document_path=packaged,+ )+ _write_ledger(migration_dir=tmp_path, current_schema_version=1)+ issues = check_surface(surface=surface, migration_dir=tmp_path)+ assert CoverageIssueKind.REQUIRED_PATH_WITHOUT_DEFAULT not in _kinds(issues)+++class TestTheLedgerAgreesWithTheRegistry:+ def test_a_ledger_describing_another_file_is_refused(self, tmp_path: Path) -> None:+ """Both halves are hand-written and both are read as truth; a disagreement mis-migrates silently."""+ directory = ledgers_dir(migration_dir=tmp_path)+ directory.mkdir(parents=True, exist_ok=True)+ (directory / f"{SURFACE_ID}.toml").write_text(+ f"""+[surface]+id = "{SURFACE_ID}"+title = "A synthetic surface"+base_file = "elsewhere.toml"+tier_glob = "synthetic_*.toml"+current_schema_version = 1+min_supported_schema_version = 0+""",+ encoding="utf-8",+ )+ _snapshot(migration_dir=tmp_path, config_model=_SchemaOne, schema_version=1)+ issues = check_surface(surface=_surface(config_model=_SchemaOne), migration_dir=tmp_path)+ assert _kinds(issues) == [CoverageIssueKind.LEDGER_DISAGREES_WITH_REGISTRY]+ assert "elsewhere.toml" in issues[0].message+++class TestTheDiff:+ def test_a_renamed_key_reads_as_one_removal_and_one_addition(self) -> None:+ """The diff is deliberately naive about renames — the ledger entry is what interprets it."""+ surface = _surface(config_model=_SchemaOne)+ before = compute_fingerprint(+ surface_id=SURFACE_ID, schema_version=1, config_model=_SchemaOne, defaults_document=surface.read_defaults_document()+ )+ renamed = _surface(config_model=_SchemaTwoRenamed)+ after = compute_fingerprint(+ surface_id=SURFACE_ID, schema_version=2, config_model=_SchemaTwoRenamed, defaults_document=renamed.read_defaults_document()+ )+ diff = diff_fingerprints(before=before, after=after)+ assert diff.removed_paths == ["label"]+ assert diff.added_paths == ["title"]+ assert diff.has_removals is Truediff --git a/tests/unit/pipelex/migration/test_fingerprint.py b/tests/unit/pipelex/migration/test_fingerprint.pynew file mode 100644index 000000000..95315fbae--- /dev/null+++ b/tests/unit/pipelex/migration/test_fingerprint.py@@ -0,0 +1,180 @@+"""Unit tests for the fingerprint — the projection the coverage gate diffs.++The tests are written against small synthetic models rather than the real configuration tree, on+purpose. What matters here is that the projection records the things a user's TOML file actually+contains — paths, requiredness, enumerated spellings, the value beneath the file — and ignores the+things it does not, such as which Python class a table happens to be. A real-model test would go+red on every legitimate configuration change and teach everyone to regenerate rather than read.+"""++from collections.abc import Mapping+from enum import StrEnum+from typing import Annotated, Any, Literal++from pydantic import BaseModel, Field++from pipelex.migration.fingerprint import ENUM_TYPE, TABLE_TYPE, compute_fingerprint+++class _Mode(StrEnum):+ FAST = "fast"+ SLOW = "slow"+++class _Leaf(BaseModel):+ name: str+ count: int = 3+++class _Synthetic(BaseModel):+ mode: _Mode+ leaf: _Leaf+ optional_leaf: _Leaf | None = None+ deck: dict[str, _Leaf]+ labels: dict[str, str]+ tags: list[str]+ bounded: Annotated[int, Field(ge=1)] | Literal["unbounded"] = 1+++class _SelfReferential(BaseModel):+ value: str = "x"+ child: "_SelfReferential | None" = None+++_DEFAULTS: dict[str, Any] = {+ "mode": "fast",+ "leaf": {"name": "written"},+ "labels": {"a": "b"},+ "tags": ["one"],+}+++def _fingerprint(*, defaults: dict[str, Any] | None = None):+ return compute_fingerprint(+ surface_id="synthetic",+ schema_version=1,+ config_model=_Synthetic,+ defaults_document=_DEFAULTS if defaults is None else defaults,+ )+++class TestFingerprintPaths:+ def test_every_addressable_path_is_recorded_and_nothing_else_is(self) -> None:+ """The path set is the vocabulary every ledger operation is written in."""+ assert _fingerprint().path_names() == {+ "mode",+ "leaf",+ "leaf.name",+ "leaf.count",+ "optional_leaf",+ "optional_leaf.name",+ "optional_leaf.count",+ "deck",+ "deck.*",+ "deck.*.name",+ "deck.*.count",+ "labels",+ "labels.*",+ "tags",+ "bounded",+ }++ def test_paths_are_stably_ordered(self) -> None:+ """The golden's line order must not depend on field declaration order or dict iteration.++ A fingerprint is checked in and read as a diff; ordering that moved for its own reasons+ would bury the one real change among two hundred reordered lines.+ """+ paths = list(_fingerprint().paths)+ assert paths == sorted(paths)++ def test_an_open_mapping_is_marked_and_its_value_schema_lands_under_a_wildcard(self) -> None:+ """The keys belong to the user; the value schema belongs to us and is addressable."""+ fingerprint = _fingerprint()+ assert fingerprint.paths["deck"].open_node is True+ assert fingerprint.paths["deck.*"].value_type == TABLE_TYPE+ assert fingerprint.paths["deck.*.name"].value_type == "str"++ def test_an_abstract_mapping_is_an_open_node_too(self) -> None:+ """`Mapping[str, X]` is the same shape to a file as `dict[str, X]`; the gate must see it as open,+ or a wildcard operation over it would be refused as addressing a path the fingerprint lacks.+ """++ class _WithMapping(BaseModel):+ entries: Mapping[str, _Leaf]++ fingerprint = compute_fingerprint(surface_id="synthetic", schema_version=1, config_model=_WithMapping, defaults_document={})+ assert fingerprint.paths["entries"].open_node is True+ assert fingerprint.paths["entries.*.name"].value_type == "str"++ def test_a_scalar_mapping_gets_a_wildcard_leaf_and_no_deeper_paths(self) -> None:+ fingerprint = _fingerprint()+ assert fingerprint.paths["labels"].open_node is True+ assert fingerprint.paths["labels.*"].value_type == "str"+ assert not [path for path in fingerprint.path_names() if path.startswith("labels.*.")]++ def test_an_optional_table_is_walked_as_the_table_it_is(self) -> None:+ """`X | None` is unwrapped: the keys inside it are perfectly addressable when present."""+ fingerprint = _fingerprint()+ assert fingerprint.paths["optional_leaf"].value_type == TABLE_TYPE+ assert fingerprint.paths["optional_leaf"].required is False+ assert fingerprint.paths["optional_leaf.name"].required is True++ def test_a_self_referential_model_terminates(self) -> None:+ """Nothing in the configuration tree is recursive today; this is what stops the next one hanging the gate.++ A recursive model has no finite path set, so the walk records the repeating table and+ stops descending into it. The paths beneath it are unaddressable, which is the honest+ answer — and it is the same answer the applier gives for an array of tables.+ """+ fingerprint = compute_fingerprint(+ surface_id="recursive",+ schema_version=1,+ config_model=_SelfReferential,+ defaults_document={},+ )+ assert fingerprint.path_names() == {"value", "child"}+++class TestFingerprintRecords:+ def test_an_enumerated_path_records_its_members_and_not_its_class_name(self) -> None:+ """Renaming a Python enum class changes no user's file, so it must move nothing."""+ record = _fingerprint().paths["mode"]+ assert record.value_type == ENUM_TYPE+ assert record.enum_members == ["fast", "slow"]++ def test_a_string_literal_counts_as_an_enumerated_spelling(self) -> None:+ """A `Literal` and an `Enum` are the same thing to a TOML file: a closed set of spellings."""+ assert _fingerprint().paths["bounded"].enum_members == ["unbounded"]++ def test_a_constraint_object_is_not_rendered_into_the_type(self) -> None:+ """`Annotated[int, Field(ge=1)]` renders as `int` — a pydantic upgrade must not move the golden."""+ assert _fingerprint().paths["bounded"].value_type == "int | literal"++ def test_a_nested_model_renders_as_a_table(self) -> None:+ assert _fingerprint().paths["leaf"].value_type == TABLE_TYPE++ def test_the_defaults_layer_value_is_recorded_where_one_exists(self) -> None:+ fingerprint = _fingerprint()+ assert fingerprint.paths["leaf.name"].default == "written"+ assert fingerprint.paths["mode"].default == "fast"+ assert fingerprint.paths["tags"].default == ["one"]++ def test_a_path_the_defaults_document_omits_records_no_value(self) -> None:+ assert _fingerprint().paths["leaf.count"].default is None++ def test_a_table_records_no_default_of_its_own(self) -> None:+ """Its children each record theirs; repeating the subtree would bloat the golden for nothing."""+ assert _fingerprint().paths["leaf"].default is None+++class TestEffectiveRequiredness:+ def test_a_required_path_under_required_ancestors_is_effectively_required(self) -> None:+ assert _fingerprint().is_effectively_required(path="leaf.name") is True++ def test_a_required_path_under_an_optional_table_is_not(self) -> None:+ """A document that omits the whole table owes nothing to the keys inside it."""+ assert _fingerprint().is_effectively_required(path="optional_leaf.name") is False++ def test_an_optional_path_is_not(self) -> None:+ assert _fingerprint().is_effectively_required(path="leaf.count") is Falsediff --git a/tests/unit/pipelex/migration/test_goldens.py b/tests/unit/pipelex/migration/test_goldens.pynew file mode 100644index 000000000..c22823060--- /dev/null+++ b/tests/unit/pipelex/migration/test_goldens.py@@ -0,0 +1,64 @@+"""Unit tests for reading the golden chain — what a stored fingerprint has to be before the gate trusts it.++The chain is checked-in history that the coverage check reads as truth, link by link. A link that+is unreadable, or that describes a different surface or version than its filename claims, must+stop the check with a named error rather than be compared as if it were the link it stands in for.+"""++from pathlib import Path++import pytest+from pydantic import BaseModel++from pipelex.migration.exceptions import MigrationGoldenError+from pipelex.migration.fingerprint import compute_fingerprint+from pipelex.migration.goldens import fingerprint_golden_path, read_fingerprint_golden, write_fingerprint_golden++SURFACE_ID = "synthetic-config"+++class _Schema(BaseModel):+ label: str = "hello"+++def _fingerprint(*, surface_id: str = SURFACE_ID, schema_version: int = 1):+ return compute_fingerprint(surface_id=surface_id, schema_version=schema_version, config_model=_Schema, defaults_document={})+++class TestReadingTheGoldenChain:+ def test_a_written_golden_reads_back_as_itself(self, tmp_path: Path) -> None:+ fingerprint = _fingerprint()+ write_fingerprint_golden(migration_dir=tmp_path, fingerprint=fingerprint)+ assert read_fingerprint_golden(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=1) == fingerprint++ def test_a_link_that_was_never_snapshotted_is_none(self, tmp_path: Path) -> None:+ assert read_fingerprint_golden(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=1) is None++ def test_a_golden_whose_body_disagrees_with_its_filename_is_refused(self, tmp_path: Path) -> None:+ """A copied or misnamed link would otherwise be compared as the version it stands in for, and pass."""+ path = fingerprint_golden_path(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=2)+ path.parent.mkdir(parents=True)+ path.write_text(_fingerprint(schema_version=1).model_dump_json(), encoding="utf-8")+ with pytest.raises(MigrationGoldenError, match="schema version 1"):+ read_fingerprint_golden(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=2)++ def test_a_golden_describing_another_surface_is_refused(self, tmp_path: Path) -> None:+ path = fingerprint_golden_path(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=1)+ path.parent.mkdir(parents=True)+ path.write_text(_fingerprint(surface_id="other-config").model_dump_json(), encoding="utf-8")+ with pytest.raises(MigrationGoldenError, match="other-config"):+ read_fingerprint_golden(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=1)++ def test_a_golden_that_is_not_a_fingerprint_is_refused_by_name(self, tmp_path: Path) -> None:+ path = fingerprint_golden_path(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=1)+ path.parent.mkdir(parents=True)+ path.write_text("{not json", encoding="utf-8")+ with pytest.raises(MigrationGoldenError, match="unreadable fingerprint golden"):+ read_fingerprint_golden(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=1)++ def test_a_golden_that_cannot_be_read_from_disk_is_refused_by_name(self, tmp_path: Path) -> None:+ """A directory where the file should be: exists, but is not readable as a file."""+ path = fingerprint_golden_path(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=1)+ path.mkdir(parents=True)+ with pytest.raises(MigrationGoldenError, match="unreadable fingerprint golden"):+ read_fingerprint_golden(migration_dir=tmp_path, surface_id=SURFACE_ID, schema_version=1)diff --git a/tests/unit/pipelex/migration/test_ledger_models.py b/tests/unit/pipelex/migration/test_ledger_models.pynew file mode 100644index 000000000..e108d729f--- /dev/null+++ b/tests/unit/pipelex/migration/test_ledger_models.py@@ -0,0 +1,153 @@+"""Unit tests for the ledger models — what a ledger file may say, refused at parse time.++A ledger is permanent data that the engine, the gate and a future human all read as truth, so the+invariants that make it readable are enforced when the file is parsed rather than diagnosed later+by whichever consumer happened to trip over them. The tests below are the inventory of what "the+ledger parses" is actually worth.+"""++from pathlib import Path++import pytest+from pydantic import ValidationError++from pipelex.migration.exceptions import MigrationLedgerError+from pipelex.migration.ledger import MigrationLedger, MigrationSafety, ledgers_dir, load_ledger+from pipelex.suggested_fix import DeleteKeyOp++_SURFACE_BLOCK = {+ "id": "example-config",+ "title": "An example surface",+ "base_file": "example.toml",+ "tier_glob": "example_*.toml",+ "current_schema_version": 1,+ "min_supported_schema_version": 0,+}+++def _entry(**overrides: object) -> dict[str, object]:+ entry: dict[str, object] = {+ "id": "example-config@2",+ "to_schema_version": 2,+ "introduced_in": "0.46.0",+ "breaking": True,+ "safety": "safe",+ "title": "Drop a retired key",+ "description": "It is gone.",+ "ops": [{"kind": "delete_key", "table_path": ["reporting"], "key": "legacy"}],+ }+ entry.update(overrides)+ return entry+++class TestTheSurfaceBlock:+ def test_a_ledger_with_no_entries_is_valid_at_schema_one(self) -> None:+ """Every surface starts here, and starting empty must not need a placeholder entry."""+ ledger = MigrationLedger.model_validate({"surface": _SURFACE_BLOCK})+ assert ledger.surface.current_schema_version == 1+ assert ledger.migration == []++ def test_a_floor_above_the_current_version_is_refused(self) -> None:+ """The floor exists so a squash fails loudly; above the current version it would fail everything."""+ surface = {**_SURFACE_BLOCK, "min_supported_schema_version": 2}+ with pytest.raises(ValidationError, match="is above current_schema_version"):+ MigrationLedger.model_validate({"surface": surface})++ def test_an_unknown_key_in_the_surface_block_is_refused(self) -> None:+ """A misspelled setting that parses is a setting that silently does nothing."""+ surface = {**_SURFACE_BLOCK, "tier_globs": "example_*.toml"}+ with pytest.raises(ValidationError):+ MigrationLedger.model_validate({"surface": surface})+++class TestEntryInvariants:+ def test_a_well_formed_entry_parses_into_typed_operations(self) -> None:+ surface = {**_SURFACE_BLOCK, "current_schema_version": 2}+ ledger = MigrationLedger.model_validate({"surface": surface, "migration": [_entry()]})+ assert ledger.migration[0].safety is MigrationSafety.SAFE+ assert isinstance(ledger.migration[0].ops[0], DeleteKeyOp)++ def test_a_materializing_operation_is_refused_at_parse_time(self) -> None:+ """The migration subset is what makes "a ledger never writes a value" a parse error.++ Writing a default into a user's file converts an inherited value into an explicitly set+ one, and no amount of review discipline catches that as reliably as the type does.+ """+ surface = {**_SURFACE_BLOCK, "current_schema_version": 2}+ entry = _entry(ops=[{"kind": "set_key", "table_path": ["reporting"], "key": "enabled", "value": True}])+ with pytest.raises(ValidationError):+ MigrationLedger.model_validate({"surface": surface, "migration": [entry]})++ def test_an_entry_named_for_the_wrong_version_is_refused(self) -> None:+ surface = {**_SURFACE_BLOCK, "current_schema_version": 2}+ entry = _entry(id="example-config@3")+ with pytest.raises(ValidationError, match="must be named 'example-config@2'"):+ MigrationLedger.model_validate({"surface": surface, "migration": [entry]})++ def test_a_gap_in_the_versions_is_refused(self) -> None:+ """Entries compose in sequence, so a missing version means a file from before it lands nowhere."""+ surface = {**_SURFACE_BLOCK, "current_schema_version": 3}+ entry = _entry(id="example-config@3", to_schema_version=3)+ with pytest.raises(ValidationError, match="expected an entry for schema version 2"):+ MigrationLedger.model_validate({"surface": surface, "migration": [entry]})++ def test_a_bump_with_no_entry_to_explain_it_is_refused(self) -> None:+ surface = {**_SURFACE_BLOCK, "current_schema_version": 2}+ with pytest.raises(ValidationError, match="needs the entry that produced it"):+ MigrationLedger.model_validate({"surface": surface, "migration": []})++ def test_an_entry_with_no_operations_must_be_unsafe(self) -> None:+ """`safe` means the applier acts; with nothing to do there is nothing to act on."""+ surface = {**_SURFACE_BLOCK, "current_schema_version": 2}+ with pytest.raises(ValidationError, match="cannot be 'safe'"):+ MigrationLedger.model_validate({"surface": surface, "migration": [_entry(ops=[])]})++ def test_an_op_free_entry_is_legitimate_when_unsafe(self) -> None:+ """A change only a human can make is still a change the ledger should record."""+ surface = {**_SURFACE_BLOCK, "current_schema_version": 2}+ ledger = MigrationLedger.model_validate({"surface": surface, "migration": [_entry(ops=[], safety="unsafe")]})+ assert ledger.migration[0].ops == []++ def test_declared_removed_paths_belong_to_a_pre_history_entry(self) -> None:+ """An entry with an observable diff is accounted against that diff, never its own claim."""+ surface = {**_SURFACE_BLOCK, "current_schema_version": 2}+ entry = _entry(declared_removed_paths=["reporting.legacy"])+ with pytest.raises(ValidationError, match="pre-history entries only"):+ MigrationLedger.model_validate({"surface": surface, "migration": [entry]})++ def test_nothing_migrates_to_schema_version_one(self) -> None:+ """Version 1 is the shape a surface starts at; there is no earlier shape to come from."""+ surface = {**_SURFACE_BLOCK, "current_schema_version": 1}+ entry = _entry(id="example-config@1", to_schema_version=1)+ with pytest.raises(ValidationError):+ MigrationLedger.model_validate({"surface": surface, "migration": [entry]})+++class TestLoadingFromDisk:+ def test_a_missing_ledger_names_the_surface_and_the_path(self, tmp_path: Path) -> None:+ with pytest.raises(MigrationLedgerError, match="no ledger for surface 'absent-config'"):+ load_ledger(migration_dir=tmp_path, surface_id="absent-config")++ def test_an_inconsistent_ledger_fails_the_load_rather_than_a_later_consumer(self, tmp_path: Path) -> None:+ directory = ledgers_dir(migration_dir=tmp_path)+ directory.mkdir(parents=True, exist_ok=True)+ (directory / "broken-config.toml").write_text(+ """+[surface]+id = "broken-config"+title = "Broken"+base_file = "broken.toml"+current_schema_version = 4+min_supported_schema_version = 0+""",+ encoding="utf-8",+ )+ with pytest.raises(MigrationLedgerError, match="invalid ledger for surface 'broken-config'"):+ load_ledger(migration_dir=tmp_path, surface_id="broken-config")++ def test_a_ledger_that_is_not_toml_fails_as_a_ledger_error_not_a_parser_traceback(self, tmp_path: Path) -> None:+ directory = ledgers_dir(migration_dir=tmp_path)+ directory.mkdir(parents=True, exist_ok=True)+ (directory / "garbled-config.toml").write_text("[surface\nid = = 'nope'\n", encoding="utf-8")+ with pytest.raises(MigrationLedgerError, match="unparseable ledger for surface 'garbled-config'"):+ load_ledger(migration_dir=tmp_path, surface_id="garbled-config")diff --git a/tests/unit/pipelex/migration/test_real_surfaces.py b/tests/unit/pipelex/migration/test_real_surfaces.pynew file mode 100644index 000000000..1abab1938--- /dev/null+++ b/tests/unit/pipelex/migration/test_real_surfaces.py@@ -0,0 +1,48 @@+"""The one test that points the gate at the real configuration surfaces.++Everything else about gate behaviour is tested against synthetic models, deliberately. What is+left for this module is the question those tests cannot answer: does the apparatus actually load+*our* models, *our* ledgers and *our* goldens, and do they agree today?++That question is worth exactly this much coverage. Assert more here — the number of paths, a+specific key, a particular default — and every legitimate configuration change goes red in a test+that is not about configuration, which teaches the reflex the whole design exists to prevent.+"""++from pipelex.migration.coverage import check_registry+from pipelex.migration.ledger import INITIAL_SCHEMA_VERSION, load_ledger+from pipelex.migration.surfaces import build_config_surface_registry, packaged_migration_dir+++class TestTheRealRegistry:+ def test_the_registry_loads(self) -> None:+ registry = build_config_surface_registry()+ assert [surface.surface_id for surface in registry.surfaces] == [+ "pipelex-config",+ "telemetry-config",+ "pipelex-service-config",+ ]++ def test_every_surface_has_a_reachable_defaults_layer(self) -> None:+ """The premise the whole vocabulary rests on: without it, an added key breaks every file."""+ for surface in build_config_surface_registry().surfaces:+ assert surface.read_defaults_document(), f"surface '{surface.surface_id}' supplies no defaults"++ def test_every_surface_has_a_ledger(self) -> None:+ migration_dir = packaged_migration_dir()+ for surface in build_config_surface_registry().surfaces:+ ledger = load_ledger(migration_dir=migration_dir, surface_id=surface.surface_id)+ assert ledger.surface.id == surface.surface_id+ assert ledger.surface.current_schema_version >= INITIAL_SCHEMA_VERSION+++class TestTheCheckedInGoldens:+ def test_the_real_surfaces_pass_the_coverage_check(self) -> None:+ """The checked-in goldens match today's models.++ When this fails, it is not this test that is wrong: a configuration model moved, and the+ gate is telling you to either regenerate the golden (`make umig`) or record the migration+ that repairs the files the change broke.+ """+ issues = check_registry(registry=build_config_surface_registry(), migration_dir=packaged_migration_dir())+ assert issues == [], "\n".join(f"{issue.surface_id}: {issue.message}" for issue in issues)diff --git a/tests/unit/pipelex/migration/test_surface_registry.py b/tests/unit/pipelex/migration/test_surface_registry.pynew file mode 100644index 000000000..85b2530f6--- /dev/null+++ b/tests/unit/pipelex/migration/test_surface_registry.py@@ -0,0 +1,159 @@+"""Unit tests for the surface registry — what a registry may declare, refused when it loads.++Which ledger runs over a file must never be an accident of iteration order, and a surface whose+defaults layer does not exist has no business claiming one. Both are load-time refusals rather+than run-time diagnoses, because by the time a migration is walking a user's directory it is too+late to discover that two surfaces both want the file it is holding.+"""++from pathlib import Path++import pytest+from pydantic import BaseModel, ValidationError++from pipelex.migration.exceptions import MigrationRegistryError+from pipelex.migration.surfaces import DefaultsLayerKind, Surface, SurfaceRegistry+++class _Defaulted(BaseModel):+ label: str = "hello"+++class _Required(BaseModel):+ label: str+++def _surface(*, surface_id: str, base_file: str, tier_glob: str | None = None) -> Surface:+ return Surface(+ surface_id=surface_id,+ title=surface_id,+ base_file=base_file,+ tier_glob=tier_glob,+ config_model=_Defaulted,+ defaults_layer_kind=DefaultsLayerKind.MODEL_DEFAULTS,+ )+++class TestSurfaceDeclarations:+ def test_a_packaged_document_surface_must_name_its_document(self) -> None:+ with pytest.raises(ValidationError, match="disagree"):+ Surface(+ surface_id="x",+ title="x",+ base_file="x.toml",+ config_model=_Defaulted,+ defaults_layer_kind=DefaultsLayerKind.PACKAGED_DOCUMENT,+ )++ def test_a_model_defaults_surface_must_not_name_one(self) -> None:+ with pytest.raises(ValidationError, match="disagree"):+ Surface(+ surface_id="x",+ title="x",+ base_file="x.toml",+ config_model=_Defaulted,+ defaults_layer_kind=DefaultsLayerKind.MODEL_DEFAULTS,+ packaged_document_path=Path("somewhere.toml"),+ )++ def test_a_model_defaults_surface_whose_model_needs_arguments_has_no_defaults_layer(self) -> None:+ """The failure is named where it happens rather than surfacing later as a missing value.++ A model that cannot be built from nothing supplies no defaults at all, and without a+ defaults layer an added key breaks every existing file with no structural operation able+ to repair it.+ """+ surface = Surface(+ surface_id="x",+ title="x",+ base_file="x.toml",+ config_model=_Required,+ defaults_layer_kind=DefaultsLayerKind.MODEL_DEFAULTS,+ )+ with pytest.raises(MigrationRegistryError, match="supplies no defaults at all"):+ surface.read_defaults_document()++ def test_a_synthesized_document_drops_keys_toml_cannot_express(self) -> None:+ class _WithOptional(BaseModel):+ label: str = "hello"+ absent: str | None = None++ surface = Surface(+ surface_id="x",+ title="x",+ base_file="x.toml",+ config_model=_WithOptional,+ defaults_layer_kind=DefaultsLayerKind.MODEL_DEFAULTS,+ )+ assert surface.read_defaults_document() == {"label": "hello"}++ def test_a_synthesized_document_drops_nulls_inside_lists_of_tables_too(self) -> None:+ """A list of nested models is a real shape (telemetry's OTLP exporters); a `None` inside one+ item would fail TOML serialization exactly as a top-level one would.+ """++ class _Exporter(BaseModel):+ endpoint: str = "http://localhost"+ headers: str | None = None++ class _WithExporters(BaseModel):+ exporters: list[_Exporter] = [_Exporter()]++ surface = Surface(+ surface_id="x",+ title="x",+ base_file="x.toml",+ config_model=_WithExporters,+ defaults_layer_kind=DefaultsLayerKind.MODEL_DEFAULTS,+ )+ assert surface.read_defaults_document() == {"exporters": [{"endpoint": "http://localhost"}]}+ assert "headers" not in surface.render_reference_document()+++class TestRegistryConsistency:+ def test_two_surfaces_sharing_an_id_are_refused(self) -> None:+ with pytest.raises(ValidationError, match="share the surface id"):+ SurfaceRegistry(+ surfaces=[+ _surface(surface_id="same", base_file="a.toml"),+ _surface(surface_id="same", base_file="b.toml"),+ ]+ )++ def test_two_surfaces_sharing_a_base_file_are_refused(self) -> None:+ with pytest.raises(ValidationError, match="share the base file"):+ SurfaceRegistry(+ surfaces=[+ _surface(surface_id="a", base_file="same.toml"),+ _surface(surface_id="b", base_file="same.toml"),+ ]+ )++ def test_two_surfaces_sharing_a_tier_glob_are_refused(self) -> None:+ """A file claimed by two globs has no rule to separate them, unlike a glob and an exact name."""+ with pytest.raises(ValidationError, match="share the tier glob"):+ SurfaceRegistry(+ surfaces=[+ _surface(surface_id="a", base_file="a.toml", tier_glob="shared_*.toml"),+ _surface(surface_id="b", base_file="b.toml", tier_glob="shared_*.toml"),+ ]+ )++ def test_a_base_file_matching_another_surfaces_glob_is_fine(self) -> None:+ """This is the real configuration: `pipelex_service.toml` matches `pipelex_*.toml`.++ Exact filenames claim before globs across all surfaces, so the resolution rule separates+ them — which is exactly why it exists, and why this is not a registry error.+ """+ registry = SurfaceRegistry(+ surfaces=[+ _surface(surface_id="a", base_file="pipelex.toml", tier_glob="pipelex_*.toml"),+ _surface(surface_id="b", base_file="pipelex_service.toml"),+ ]+ )+ assert len(registry.surfaces) == 2++ def test_an_unknown_surface_id_is_named_in_the_error(self) -> None:+ registry = SurfaceRegistry(surfaces=[_surface(surface_id="a", base_file="a.toml")])+ with pytest.raises(MigrationRegistryError, match="no surface 'nope'"):+ registry.surface_for_id(surface_id="nope")diff --git a/tests/unit/pipelex/pipeline/fixes/test_blueprint_fix_planner.py b/tests/unit/pipelex/pipeline/fixes/test_blueprint_fix_planner.pyindex 7e6643dfb..381e3b530 100644--- a/tests/unit/pipelex/pipeline/fixes/test_blueprint_fix_planner.py+++ b/tests/unit/pipelex/pipeline/fixes/test_blueprint_fix_planner.py@@ -11,7 +11,7 @@ all normalize to a ``concept.<Code>`` key).from pipelex.core.exceptions import PipelexBundleBlueprintValidationErrorDatafrom pipelex.core.pipes.exceptions import PipeValidationErrorTypefrom pipelex.pipeline.fixes.planner import plan_fix_for_blueprint_validation_error-from pipelex.suggested_fix import FixOpKind, FixSafety+from pipelex.suggested_fix import DeleteKeyOp, FixSafety, RenameTableKeyOp, SetKeyOpdef _blueprint_error_data(@@ -53,19 +53,14 @@ class TestBlueprintFixPlanner:assert fix.fix_code == "strip-native-concept-redecl"assert fix.safety == FixSafety.SAFEassert fix.source == "main.mthds"- assert len(fix.ops) == 1- the_op = fix.ops[0]- assert the_op.kind == FixOpKind.DELETE_KEY- assert the_op.table_path == ["concept"]- assert the_op.key == "Text"- assert the_op.value is None+ assert fix.ops == [DeleteKeyOp(table_path=["concept"], key="Text")]assert "Text" in fix.descriptiondef test_fix_carries_the_offending_concept_code(self) -> None:"""The deleted key is exactly the offending code, whatever it is."""fix = plan_fix_for_blueprint_validation_error(_blueprint_error_data(concept_code="Number"))assert fix is not None- assert fix.ops[0].key == "Number"+ assert fix.ops == [DeleteKeyOp(table_path=["concept"], key="Number")]def test_source_is_threaded_onto_the_fix(self) -> None:"""A blueprint error's ``source`` rides the fix so the loop can target the declaring file."""@@ -101,12 +96,7 @@ class TestBlueprintFixPlanner:assert fix is not Noneassert fix.fix_code == "strip-namespace"assert fix.safety == FixSafety.SAFE- assert len(fix.ops) == 1- op = fix.ops[0]- assert op.kind == FixOpKind.RENAME_TABLE_KEY- assert op.table_path == ["pipe"]- assert op.key == "greetings.hello"- assert op.new_key == "hello"+ assert fix.ops == [RenameTableKeyOp(table_path=["pipe"], key="greetings.hello", new_key="hello")]def test_dotted_main_pipe_yields_root_set_key(self) -> None:"""A strippable main_pipe strip (no pipe_code) yields a set_key of main_pipe at the root."""@@ -114,12 +104,7 @@ class TestBlueprintFixPlanner:fix = plan_fix_for_blueprint_validation_error(error_data)assert fix is not Noneassert fix.fix_code == "strip-namespace"- assert len(fix.ops) == 1- op = fix.ops[0]- assert op.kind == FixOpKind.SET_KEY- assert op.table_path == []- assert op.key == "main_pipe"- assert op.value == "hello"+ assert fix.ops == [SetKeyOp(table_path=[], key="main_pipe", value="hello")]def test_unstrippable_syntax_error_yields_none(self) -> None:"""An INVALID_PIPE_CODE_SYNTAX error without ``stripped_pipe_code`` is not fixable."""diff --git a/tests/unit/pipelex/pipeline/fixes/test_fix_applier.py b/tests/unit/pipelex/pipeline/fixes/test_fix_applier.pyindex 626aa64cf..807c3e191 100644--- a/tests/unit/pipelex/pipeline/fixes/test_fix_applier.py+++ b/tests/unit/pipelex/pipeline/fixes/test_fix_applier.py@@ -16,7 +16,7 @@ from pytest_mock import MockerFixturefrom pipelex.base_exceptions import PipelexUnexpectedErrorfrom pipelex.pipeline.fixes.applier import FixOpOutcome, apply_fix_ops, serialize_and_format-from pipelex.suggested_fix import FixOp, FixOpKind+from pipelex.suggested_fix import DeleteKeyOp, DeleteTableOp, FixOp, SetKeyOp_FIXTURE_PATH = Path("tests/data/fixes/sequence_wrong_output.mthds")_GOLDEN_PATH = Path("tests/data/fixes/sequence_wrong_output.golden.mthds")@@ -28,7 +28,7 @@ def _dumps(toml_doc: tomlkit.TOMLDocument) -> str:def _set_output_op(*, pipe_code: str = "list_ideas", value: str = "Idea[]") -> FixOp:- return FixOp(kind=FixOpKind.SET_KEY, table_path=["pipe", pipe_code], key="output", value=value)+ return SetKeyOp(table_path=["pipe", pipe_code], key="output", value=value)class TestFixApplier:@@ -61,7 +61,7 @@ class TestFixApplier:def test_delete_key_removes_key_preserving_rest(self) -> None:"""delete_key removes exactly the addressed key; everything else survives byte-for-byte."""toml_doc = tomlkit.loads(_FIXTURE_PATH.read_text(encoding="utf-8"))- delete_op = FixOp(kind=FixOpKind.DELETE_KEY, table_path=["pipe", "gen_ideas"], key="prompt")+ delete_op = DeleteKeyOp(table_path=["pipe", "gen_ideas"], key="prompt")applications = apply_fix_ops(toml_doc=toml_doc, ops=[delete_op])assert [application.outcome for application in applications] == [FixOpOutcome.APPLIED]dumped = _dumps(toml_doc)@@ -72,7 +72,7 @@ class TestFixApplier:def test_delete_key_missing_is_skipped(self) -> None:"""delete_key on an absent key is skipped and reported, not raised."""toml_doc = tomlkit.loads(_FIXTURE_PATH.read_text(encoding="utf-8"))- delete_op = FixOp(kind=FixOpKind.DELETE_KEY, table_path=["pipe", "gen_ideas"], key="not_a_key")+ delete_op = DeleteKeyOp(table_path=["pipe", "gen_ideas"], key="not_a_key")applications = apply_fix_ops(toml_doc=toml_doc, ops=[delete_op])assert [application.outcome for application in applications] == [FixOpOutcome.SKIPPED]@@ -80,7 +80,7 @@ class TestFixApplier:"""delete_table whose final segment names a scalar (a drifted target) is skipped, not deleted."""toml_doc = tomlkit.loads(_FIXTURE_PATH.read_text(encoding="utf-8"))source_bytes = _dumps(toml_doc)- delete_op = FixOp(kind=FixOpKind.DELETE_TABLE, table_path=["pipe", "gen_ideas", "prompt"])+ delete_op = DeleteTableOp(table_path=["pipe", "gen_ideas", "prompt"])applications = apply_fix_ops(toml_doc=toml_doc, ops=[delete_op])assert [application.outcome for application in applications] == [FixOpOutcome.SKIPPED]assert applications[0].detail is not None@@ -89,7 +89,7 @@ class TestFixApplier:def test_delete_table_removes_whole_table(self) -> None:"""delete_table removes the addressed table and its keys; sibling tables survive."""toml_doc = tomlkit.loads(_FIXTURE_PATH.read_text(encoding="utf-8"))- delete_op = FixOp(kind=FixOpKind.DELETE_TABLE, table_path=["pipe", "gen_ideas"])+ delete_op = DeleteTableOp(table_path=["pipe", "gen_ideas"])applications = apply_fix_ops(toml_doc=toml_doc, ops=[delete_op])assert [application.outcome for application in applications] == [FixOpOutcome.APPLIED]dumped = _dumps(toml_doc)diff --git a/tests/unit/pipelex/pipeline/fixes/test_fix_applier_config_surface_shapes.py b/tests/unit/pipelex/pipeline/fixes/test_fix_applier_config_surface_shapes.pynew file mode 100644index 000000000..8ba53bc6d--- /dev/null+++ b/tests/unit/pipelex/pipeline/fixes/test_fix_applier_config_surface_shapes.py@@ -0,0 +1,297 @@+"""Characterization tests for the fix applier's path model against the real configuration files.++Migration reuses the ``.mthds`` fix applier to rewrite user-owned ``.toml`` configuration, and that+reuse rests on assumptions the ``.mthds`` tests never exercise: that ``table_path`` addresses every+table a configuration file actually contains, that an untouched round-trip is byte-identical (the+migration checks are byte-level claims), and that tomlkit's ``OutOfOrderTableProxy`` — which the+packaged defaults document produces, being written out of order — survives every op rather than only+the rename that handles it explicitly.++These tests pin the measured behaviour of the applier *and* of tomlkit underneath it, so a tomlkit+bump that changes comment attachment, header re-rendering, or proxy handling fails here rather than+silently corrupting somebody's configuration file. The reachability test deliberately probes through+the public ``apply_fix_ops`` — a ``delete_key`` for an absent key reports "table not found" when the+path model cannot reach the table and "key not found" when it can — so it characterizes the contract+rather than the private resolver.++Where a behaviour is a hazard rather than a guarantee, the test says so in its name and docstring:+``test_moved_table_leaves_its_banner_comment_behind`` pins a *limitation* that the migration contract+has to state, not something to rely on.+"""++from pathlib import Path+from typing import Any, cast++import pytest+import tomlkit+from tomlkit import TOMLDocument++from pipelex.pipeline.fixes.applier import FixOpOutcome, apply_fix_ops+from pipelex.suggested_fix import DeleteKeyOp, DeleteTableOp, EnsureTableOp, RenameTableKeyOp++# Every configuration file this repository owns and tracks. The packaged defaults are the complete+# witness (every path present); the kit templates are the sparse shape real user files have — and+# `ensure_global_config_exists` seeds every `~/.pipelex/` as a copy of them. `plxt.toml` is not a+# migration surface; it is here because it is the only tracked config file containing an array of+# tables, which is the one shape the path model cannot address.+_TRACKED_CONFIG_FILES = [+ Path("pipelex/pipelex.toml"),+ Path("pipelex/kit/configs/pipelex.toml"),+ Path("pipelex/kit/configs/telemetry.toml"),+ Path("pipelex/kit/configs/telemetry.project.toml"),+ Path("pipelex/kit/configs/pipelex_service.toml"),+ Path("pipelex/kit/configs/plxt.toml"),+ Path(".pipelex/pipelex.toml"),+ Path(".pipelex/telemetry.toml"),+ Path("tests/pipelex_unit_test.toml"),+]++_PACKAGED_DEFAULTS = Path("pipelex/pipelex.toml")+_KIT_TEMPLATE = Path("pipelex/kit/configs/pipelex.toml")+_ARRAY_OF_TABLES_FILE = Path("pipelex/kit/configs/plxt.toml")++_ABSENT_KEY = "key_that_no_configuration_file_declares"+++def _dumps(toml_doc: TOMLDocument) -> str:+ """One typed funnel over tomlkit's weakly-typed ``dumps`` (narrow ignore, not file-level)."""+ return tomlkit.dumps(toml_doc) # pyright: ignore[reportUnknownMemberType]+++def _parse(path: Path) -> TOMLDocument:+ return tomlkit.parse(path.read_text(encoding="utf-8"))+++def _as_mapping(node: Any) -> dict[str, Any]:+ """One typed funnel over tomlkit's dict-like nodes, which the stubs type as bare ``Item``."""+ return cast("dict[str, Any]", node)+++def _table_paths(node: object, prefix: list[str]) -> list[list[str]]:+ """Every dict-addressable table path in the document, depth-first, in document order.++ Array-of-tables elements are deliberately not descended into: they are ``list`` nodes, which the+ ``table_path`` model has no segment syntax for — the very fact the reachability test asserts.+ """+ collected: list[list[str]] = []+ if not isinstance(node, dict):+ return collected+ mapping = _as_mapping(node)+ for key in mapping:+ value: Any = mapping[key]+ path = [*prefix, str(key)]+ if isinstance(value, dict):+ collected.append(path)+ collected.extend(_table_paths(_as_mapping(value), path))+ return collected+++def _probe_reachability(*, toml_doc: TOMLDocument, table_path: list[str]) -> str | None:+ """Ask the applier whether it can reach ``table_path``, without changing the document.++ A ``delete_key`` for a key no configuration file declares always skips; *why* it skipped is the+ measurement — "table … not found" means the path model could not walk there.+ """+ applications = apply_fix_ops(toml_doc=toml_doc, ops=[DeleteKeyOp(table_path=table_path, key=_ABSENT_KEY)])+ assert applications[0].outcome == FixOpOutcome.SKIPPED+ return applications[0].detail+++class TestFixApplierConfigSurfaceShapes:+ @pytest.mark.parametrize("config_path", _TRACKED_CONFIG_FILES, ids=str)+ def test_untouched_round_trip_is_byte_identical(self, config_path: Path) -> None:+ """Parsing and re-dumping an untouched configuration file returns the exact input bytes.++ Migration serializes with ``tomlkit.dumps`` and no canonical reflow, so replay neutrality and+ the transform goldens are byte-level claims that rest entirely on this holding.+ """+ text = config_path.read_text(encoding="utf-8")+ assert _dumps(tomlkit.parse(text)) == text++ @pytest.mark.parametrize("config_path", _TRACKED_CONFIG_FILES, ids=str)+ def test_every_table_is_addressable_by_table_path(self, config_path: Path) -> None:+ """Every table in every tracked configuration file is reachable by its ``table_path``."""+ toml_doc = _parse(config_path)+ unreachable = [+ table_path+ for table_path in _table_paths(toml_doc, [])+ if "not found in document" in (_probe_reachability(toml_doc=toml_doc, table_path=table_path) or "")+ ]+ assert unreachable == []++ @pytest.mark.parametrize("config_path", _TRACKED_CONFIG_FILES, ids=str)+ def test_reachability_probing_leaves_the_document_untouched(self, config_path: Path) -> None:+ """Probing every path with a skipping op changes no bytes — the guarded-skip contract."""+ toml_doc = _parse(config_path)+ source_bytes = _dumps(toml_doc)+ for table_path in _table_paths(toml_doc, []):+ _probe_reachability(toml_doc=toml_doc, table_path=table_path)+ assert _dumps(toml_doc) == source_bytes++ def test_array_of_tables_is_not_addressable(self) -> None:+ """An array of tables is a ``list``, so no ``table_path`` reaches it — reported, never raised.++ No migration surface contains one today; the guarded skip is what keeps that from being a+ latent crash if one ever appears.+ """+ toml_doc = _parse(_ARRAY_OF_TABLES_FILE)+ assert isinstance(toml_doc["rule"], list)+ detail = _probe_reachability(toml_doc=toml_doc, table_path=["rule"])+ assert detail is not None+ assert "not found in document" in detail++ def test_inline_table_key_renames_in_place(self) -> None:+ """A key inside an inline table is addressable and renames without disturbing its siblings."""+ toml_doc = _parse(_PACKAGED_DEFAULTS)+ before = _dumps(toml_doc).splitlines()+ applications = apply_fix_ops(+ toml_doc=toml_doc,+ ops=[+ RenameTableKeyOp(+ table_path=["cogt", "img_gen_config", "quality_to_steps_maps", "flux"],+ key="low",+ new_key="lowest",+ )+ ],+ )+ assert [application.outcome for application in applications] == [FixOpOutcome.APPLIED]+ after = _dumps(toml_doc).splitlines()+ changed = [line for expected, line in zip(before, after, strict=True) if expected != line]+ assert changed == ['flux = { lowest = 14, "medium" = 28, "high" = 56 }']++ def test_dotted_key_assignment_is_addressable_and_renames(self) -> None:+ """``a.b = 1`` is a table to tomlkit, so it is addressable and stays a dotted key on rename."""+ toml_doc = tomlkit.parse("[section]\nnested.leaf = 1\nother = 2\n")+ applications = apply_fix_ops(toml_doc=toml_doc, ops=[RenameTableKeyOp(table_path=["section", "nested"], key="leaf", new_key="renamed")])+ assert [application.outcome for application in applications] == [FixOpOutcome.APPLIED]+ assert _dumps(toml_doc) == "[section]\nnested.renamed = 1\nother = 2\n"++ def test_quoted_key_containing_a_dot_is_one_path_segment(self) -> None:+ """A quoted key with a dot inside is a single segment, and stays quoted when renamed."""+ toml_doc = tomlkit.parse('["outer.inner"]\nvalue = 1\n')+ detail = _probe_reachability(toml_doc=toml_doc, table_path=["outer.inner"])+ assert detail is not None+ assert "not found in table" in detail++ def test_packaged_defaults_produce_out_of_order_proxies(self) -> None:+ """The packaged document is written out of order, so two of its root tables are proxies.++ This is the premise of every proxy test below; if a reordering of ``pipelex.toml`` ever makes+ it false, those tests stop measuring what they claim to.+ """+ toml_doc = _parse(_PACKAGED_DEFAULTS)+ proxy_roots = [str(key) for key in toml_doc if type(toml_doc[key]).__name__ == "OutOfOrderTableProxy"]+ assert proxy_roots == ["pipelex", "migration"]++ @pytest.mark.parametrize(+ "table_path",+ [+ pytest.param(["pipelex", "log_config"], id="table-inside-a-proxy"),+ pytest.param(["migration"], id="the-proxy-itself"),+ pytest.param(["pipelex"], id="the-other-proxy-itself"),+ ],+ )+ def test_delete_table_removes_every_chunk_of_an_out_of_order_table(self, table_path: list[str]) -> None:+ """``delete_table`` removes all of an out-of-order table, leaving no orphaned header behind."""+ toml_doc = _parse(_PACKAGED_DEFAULTS)+ applications = apply_fix_ops(toml_doc=toml_doc, ops=[DeleteTableOp(table_path=table_path)])+ assert [application.outcome for application in applications] == [FixOpOutcome.APPLIED]+ rendered = _dumps(toml_doc)+ header_prefix = f"[{'.'.join(table_path)}"+ assert [line for line in rendered.splitlines() if line.startswith(header_prefix)] == []+ reparsed = tomlkit.parse(rendered)+ assert table_path[0] not in reparsed or table_path[-1] not in _as_mapping(reparsed[table_path[0]])++ def test_root_level_proxy_rename_rewrites_every_chunk(self) -> None:+ """Renaming a root table that is split into chunks rewrites every child header, content intact.++ This is the configuration reshape's hardest shape (``[pipelex]`` becomes ``[interpreter]``)+ and it goes through ``Container._replace``, a tomlkit internal — so this test is the tripwire.+ """+ toml_doc = _parse(_PACKAGED_DEFAULTS)+ original = _parse(_PACKAGED_DEFAULTS)+ applications = apply_fix_ops(toml_doc=toml_doc, ops=[RenameTableKeyOp(table_path=[], key="pipelex", new_key="interpreter")])+ assert [application.outcome for application in applications] == [FixOpOutcome.APPLIED]+ rendered = _dumps(toml_doc)+ assert [line for line in rendered.splitlines() if line.startswith("[pipelex")] == []+ reparsed = tomlkit.parse(rendered)+ assert reparsed["interpreter"] == original["pipelex"]++ def test_rename_is_replay_neutral_once_applied(self) -> None:+ """Re-applying a rename over an already-migrated document skips and changes no bytes.++ Replay neutrality is the migration engine's central guarantee: every entry is replayed on+ every run, so an entry that has already been applied must be a byte-level no-op.+ """+ rename_op = RenameTableKeyOp(table_path=[], key="cogt", new_key="inference")+ toml_doc = _parse(_PACKAGED_DEFAULTS)+ apply_fix_ops(toml_doc=toml_doc, ops=[rename_op])+ once = _dumps(toml_doc)++ replayed_doc = tomlkit.parse(once)+ applications = apply_fix_ops(toml_doc=replayed_doc, ops=[rename_op])+ assert [application.outcome for application in applications] == [FixOpOutcome.SKIPPED]+ assert _dumps(replayed_doc) == once++ def test_ensure_table_emits_an_inline_table(self) -> None:+ """``ensure_table`` creates ``key = {}``, an inline table, and that is deliberate.++ The migration plan carried this down as a bug to fix — "the wrong shape for a config+ section" — but ``ensure_table`` is not a migration op and never touches a config+ section. Its one producer is the ``sync-controller-inputs`` fix, where the inline form+ is the dominant `.mthds` authoring form and keeps the mapping attached to its pipe; a+ block table would detach it into a ``[pipe.x.inputs]`` section after the pipe's body.+ The block-table shape landed in ``move_key``, which is where a migration actually needs+ to create a destination section.+ """+ toml_doc = _parse(_PACKAGED_DEFAULTS)+ applications = apply_fix_ops(toml_doc=toml_doc, ops=[EnsureTableOp(table_path=["pipelex", "freshly_ensured"])])+ assert [application.outcome for application in applications] == [FixOpOutcome.APPLIED]+ assert "freshly_ensured = {}" in _dumps(toml_doc)++ def test_a_created_root_parent_lands_at_the_end_of_the_file(self) -> None:+ """A table moved under a parent that does not exist yet lands at the end of the document.++ Position is preserved *within* a parent, never *across* parents — the placement rule the+ migration contract has to state, because a migrated file will not look like the original.+ """+ toml_doc = _parse(_KIT_TEMPLATE)+ pipelex_table = _as_mapping(toml_doc["pipelex"])+ moved = pipelex_table["storage_config"]+ del pipelex_table["storage_config"]+ created_parent = tomlkit.table()+ created_parent["storage"] = moved+ toml_doc["runtime"] = created_parent++ rendered_lines = _dumps(toml_doc).splitlines()+ header_indexes = [index for index, line in enumerate(rendered_lines) if line.startswith("[runtime.storage]")]+ assert len(header_indexes) == 1+ remaining_headers = [line for line in rendered_lines[header_indexes[0] :] if line.startswith("[") and not line.startswith("[runtime")]+ assert remaining_headers == []++ def test_moved_table_leaves_its_banner_comment_behind(self) -> None:+ """A comment block *preceding* a table does not travel with it — a documented limitation.++ tomlkit stores such a block as trailing trivia of the *previous* sibling, not as anything+ attached to the table, so a moved table arrives bare and the banner stays put, now labelling+ whatever followed it. The migration contract states this; nothing in the engine relies on+ comment fidelity across a move.+ """+ toml_doc = _parse(_KIT_TEMPLATE)+ banner = "# Storage Config"+ source_lines = _dumps(toml_doc).splitlines()+ banner_index = source_lines.index(banner)+ assert source_lines[banner_index + 2 : banner_index + 4] == ["", "[pipelex.storage_config]"]++ pipelex_table = _as_mapping(toml_doc["pipelex"])+ moved = pipelex_table["storage_config"]+ del pipelex_table["storage_config"]+ created_parent = tomlkit.table()+ created_parent["storage"] = moved+ toml_doc["runtime"] = created_parent++ migrated_lines = _dumps(toml_doc).splitlines()+ migrated_banner_index = migrated_lines.index(banner)+ assert migrated_lines[migrated_banner_index + 2] != "[runtime.storage]"+ destination_index = migrated_lines.index("[runtime.storage]")+ assert banner not in migrated_lines[destination_index - 3 : destination_index]diff --git a/tests/unit/pipelex/pipeline/fixes/test_fix_applier_inputs_sync.py b/tests/unit/pipelex/pipeline/fixes/test_fix_applier_inputs_sync.pyindex 183383621..8124255e9 100644--- a/tests/unit/pipelex/pipeline/fixes/test_fix_applier_inputs_sync.py+++ b/tests/unit/pipelex/pipeline/fixes/test_fix_applier_inputs_sync.py@@ -13,7 +13,7 @@ from pathlib import Pathimport tomlkitfrom pipelex.pipeline.fixes.applier import FixOpOutcome, apply_fix_ops, serialize_and_format-from pipelex.suggested_fix import FixOp, FixOpKind+from pipelex.suggested_fix import DeleteKeyOp, EnsureTableOp, FixOp, SetKeyOp_FIXES_DIR = Path("tests/data/fixes")_INPUTS_TABLE_PATH = ["pipe", "make_summary", "inputs"]@@ -32,20 +32,20 @@ def _golden(name: str) -> str:return (_FIXES_DIR / f"{name}.golden.mthds").read_text(encoding="utf-8")-_INLINE_OPS = [- FixOp(kind=FixOpKind.SET_KEY, table_path=_INPUTS_TABLE_PATH, key="text", value="Text"),- FixOp(kind=FixOpKind.SET_KEY, table_path=_INPUTS_TABLE_PATH, key="style", value="Text"),- FixOp(kind=FixOpKind.DELETE_KEY, table_path=_INPUTS_TABLE_PATH, key="note"),+_INLINE_OPS: list[FixOp] = [+ SetKeyOp(table_path=_INPUTS_TABLE_PATH, key="text", value="Text"),+ SetKeyOp(table_path=_INPUTS_TABLE_PATH, key="style", value="Text"),+ DeleteKeyOp(table_path=_INPUTS_TABLE_PATH, key="note"),]-_BLOCK_OPS = [- FixOp(kind=FixOpKind.SET_KEY, table_path=_INPUTS_TABLE_PATH, key="text", value="Text"),- FixOp(kind=FixOpKind.DELETE_KEY, table_path=_INPUTS_TABLE_PATH, key="note"),+_BLOCK_OPS: list[FixOp] = [+ SetKeyOp(table_path=_INPUTS_TABLE_PATH, key="text", value="Text"),+ DeleteKeyOp(table_path=_INPUTS_TABLE_PATH, key="note"),]-_MISSING_TABLE_OPS = [- FixOp(kind=FixOpKind.ENSURE_TABLE, table_path=_INPUTS_TABLE_PATH),- FixOp(kind=FixOpKind.SET_KEY, table_path=_INPUTS_TABLE_PATH, key="text", value="Text"),+_MISSING_TABLE_OPS: list[FixOp] = [+ EnsureTableOp(table_path=_INPUTS_TABLE_PATH),+ SetKeyOp(table_path=_INPUTS_TABLE_PATH, key="text", value="Text"),]@@ -116,7 +116,7 @@ output = "Text""""source = '[pipe.make_summary]\ntype = "PipeSequence"\ninputs = { "cv.name" = "Text", cv = "Curriculum", note = "Text" }\n'toml_doc = tomlkit.loads(source)- applications = apply_fix_ops(toml_doc=toml_doc, ops=[FixOp(kind=FixOpKind.DELETE_KEY, table_path=_INPUTS_TABLE_PATH, key="note")])+ applications = apply_fix_ops(toml_doc=toml_doc, ops=[DeleteKeyOp(table_path=_INPUTS_TABLE_PATH, key="note")])assert [application.outcome for application in applications] == [FixOpOutcome.APPLIED]formatted = serialize_and_format(toml_doc)assert '"cv.name" = "Text"' in formatteddiff --git a/tests/unit/pipelex/pipeline/fixes/test_fix_applier_migration_ops.py b/tests/unit/pipelex/pipeline/fixes/test_fix_applier_migration_ops.pynew file mode 100644index 000000000..529431650--- /dev/null+++ b/tests/unit/pipelex/pipeline/fixes/test_fix_applier_migration_ops.py@@ -0,0 +1,202 @@+"""Unit tests for the applier's migration-only behaviour: ``move_key``, ``remap_value``,+the ``*`` wildcard segment, and the ``CONFLICT`` outcome.++Everything here is exercised on plain TOML strings rather than on ``.mthds`` fixtures, and+compared as serialized bytes without the MTHDS formatter — because that is exactly how a+configuration migration runs. Migration serializes with ``tomlkit.dumps`` and nothing else, so+a rename must not also reflow the user's spacing, and the byte compare is what pins it.+"""++from typing import Any, cast++import tomlkit++from pipelex.pipeline.fixes.applier import FixOpOutcome, apply_fix_ops+from pipelex.suggested_fix import (+ DeleteKeyOp,+ EnsureTableOp,+ FixOp,+ MoveKeyOp,+ RemapValueOp,+ RenameTableKeyOp,+)++_DOC = """\+# A configuration file with a user's own spacing.+root_key = "kept"++[reporting]+enabled = true+output_config = { path = "out.json" }++[reporting.retention]+days = 30++[deck]++[deck.gpt]+provider = "openai"+tier = "premium"++[deck.claude]+provider = "anthropic"+tier = "legacy"+"""+++def _value_at(*, text: str, path: list[str]) -> Any:+ """Read one value out of serialized TOML by path — one typed funnel over tomlkit's ``Item``."""+ node = cast("dict[str, Any]", tomlkit.parse(text))+ for segment in path[:-1]:+ node = cast("dict[str, Any]", node[segment])+ return node[path[-1]]+++def _table_at(*, text: str, path: list[str]) -> dict[str, Any]:+ """The table at ``path`` in serialized TOML, as a plain mapping."""+ return cast("dict[str, Any]", _value_at(text=text, path=path))+++def _apply(*, text: str, ops: list[FixOp]) -> tuple[str, list[FixOpOutcome]]:+ """Apply ops to a parsed document and return (serialized bytes, outcomes)."""+ toml_doc = tomlkit.parse(text)+ applications = apply_fix_ops(toml_doc=toml_doc, ops=ops)+ dumped: str = tomlkit.dumps(toml_doc) # pyright: ignore[reportUnknownMemberType]+ return dumped, [application.outcome for application in applications]+++class TestFixApplierMigrationOps:+ def test_move_key_into_a_parent_that_has_to_be_created(self) -> None:+ """A table-valued key travels whole, and its missing destination parent is created."""+ text, outcomes = _apply(+ text=_DOC,+ ops=[MoveKeyOp(table_path=["reporting"], key="retention", new_table_path=["storage"], new_key="retention")],+ )+ assert outcomes == [FixOpOutcome.APPLIED]+ assert "retention" not in _table_at(text=text, path=["reporting"])+ assert _value_at(text=text, path=["storage", "retention", "days"]) == 30++ def test_move_key_replays_to_a_no_op(self) -> None:+ """Replaying a move over the already-migrated document changes nothing — no bytes, no ops.++ This is replay neutrality in miniature, and it is the property that lets a migration run+ every entry on every file on every run without a state stamp to tell it what to skip.+ """+ move_op: FixOp = MoveKeyOp(table_path=["reporting"], key="retention", new_table_path=["storage"], new_key="retention")+ migrated, _ = _apply(text=_DOC, ops=[move_op])+ replayed, outcomes = _apply(text=migrated, ops=[move_op])+ assert outcomes == [FixOpOutcome.SKIPPED]+ assert replayed == migrated++ def test_move_key_leaves_untouched_lines_byte_identical(self) -> None:+ """Only the moved key's lines change; the user's own spacing survives everywhere else."""+ text, _ = _apply(+ text=_DOC,+ ops=[MoveKeyOp(table_path=["reporting"], key="output_config", new_table_path=["reporting"], new_key="output")],+ )+ assert "# A configuration file with a user's own spacing." in text+ assert "enabled = true" in text+ assert "output_config" not in text++ def test_move_key_onto_an_occupied_destination_conflicts_and_writes_nothing(self) -> None:+ """A conflicting move leaves the document byte-identical — including no created parents."""+ occupied = _DOC + '\n[storage]\nretention = "already mine"\n'+ text, outcomes = _apply(+ text=occupied,+ ops=[MoveKeyOp(table_path=["reporting"], key="retention", new_table_path=["storage"], new_key="retention")],+ )+ assert outcomes == [FixOpOutcome.CONFLICT]+ assert text == occupied++ def test_move_key_blocked_by_a_scalar_destination_parent_conflicts(self) -> None:+ """A destination parent occupied by a scalar is a conflict, not a silently created table."""+ # The scalar goes in the root's own span, above the first header — a bare key written+ # after one would belong to that table, not to the root.+ blocked = _DOC.replace('root_key = "kept"', 'root_key = "kept"\nstorage = "not a table"')+ text, outcomes = _apply(+ text=blocked,+ ops=[MoveKeyOp(table_path=["reporting"], key="retention", new_table_path=["storage", "policy"], new_key="retention")],+ )+ assert outcomes == [FixOpOutcome.CONFLICT]+ assert text == blocked++ def test_move_key_with_an_absent_source_skips(self) -> None:+ """The guarded skip that makes always-replay possible: no source, no work, no error."""+ text, outcomes = _apply(+ text=_DOC,+ ops=[MoveKeyOp(table_path=["reporting"], key="never_existed", new_table_path=["storage"], new_key="x")],+ )+ assert outcomes == [FixOpOutcome.SKIPPED]+ assert text == _DOC++ def test_remap_value_rewrites_only_mapped_values(self) -> None:+ """A mapped value is rewritten; an unmapped one is left exactly as the user wrote it."""+ text, outcomes = _apply(+ text=_DOC,+ ops=[+ RemapValueOp(table_path=["deck", "claude"], key="tier", mapping={"legacy": "standard"}),+ RemapValueOp(table_path=["deck", "gpt"], key="tier", mapping={"legacy": "standard"}),+ ],+ )+ assert outcomes == [FixOpOutcome.APPLIED, FixOpOutcome.SKIPPED]+ assert _value_at(text=text, path=["deck", "claude", "tier"]) == "standard"+ assert _value_at(text=text, path=["deck", "gpt", "tier"]) == "premium"++ def test_remap_value_on_a_non_string_skips(self) -> None:+ """Remapping exists for renamed enumerated values, which are always strings."""+ _, outcomes = _apply(text=_DOC, ops=[RemapValueOp(table_path=["reporting"], key="enabled", mapping={"true": "yes"})])+ assert outcomes == [FixOpOutcome.SKIPPED]++ def test_remap_value_detail_never_echoes_the_users_value(self) -> None:+ """A report may name paths and ledger-supplied values, never a value read from the file."""+ toml_doc = tomlkit.parse(_DOC)+ applications = apply_fix_ops(+ toml_doc=toml_doc,+ ops=[RemapValueOp(table_path=["deck", "gpt"], key="provider", mapping={"nope": "other"})],+ )+ assert applications[0].outcome is FixOpOutcome.SKIPPED+ assert applications[0].detail is not None+ assert "openai" not in applications[0].detail++ def test_wildcard_applies_to_every_entry_of_an_open_mapping(self) -> None:+ """One op renames a field inside every entry the document happens to contain."""+ text, outcomes = _apply(text=_DOC, ops=[RenameTableKeyOp(table_path=["deck", "*"], key="tier", new_key="quality")])+ assert outcomes == [FixOpOutcome.APPLIED]+ assert _value_at(text=text, path=["deck", "gpt", "quality"]) == "premium"+ assert _value_at(text=text, path=["deck", "claude", "quality"]) == "legacy"++ def test_wildcard_conflict_in_one_entry_wins_over_siblings_and_writes_nothing(self) -> None:+ """A conflict anywhere surfaces: burying it under a sibling's success is what it exists to prevent.++ And it writes nothing anywhere: `deck.gpt` would rename cleanly, but a conflicting operation+ leaves the document byte-identical, matched entries included — the operation is one step.+ """+ occupied = _DOC.replace('[deck.claude]\nprovider = "anthropic"', '[deck.claude]\nquality = "taken"\nprovider = "anthropic"')+ text, outcomes = _apply(text=occupied, ops=[RenameTableKeyOp(table_path=["deck", "*"], key="tier", new_key="quality")])+ assert outcomes == [FixOpOutcome.CONFLICT]+ assert text == occupied++ def test_wildcard_over_an_absent_node_skips(self) -> None:+ """Nothing matches, so nothing happens — and the document is untouched."""+ text, outcomes = _apply(text=_DOC, ops=[DeleteKeyOp(table_path=["no_such_section", "*"], key="anything")])+ assert outcomes == [FixOpOutcome.SKIPPED]+ assert text == _DOC++ def test_rename_onto_an_occupied_key_is_a_conflict_not_a_skip(self) -> None:+ """The outcome that used to hide inside SKIPPED, where no caller could act on it."""+ _, outcomes = _apply(text=_DOC, ops=[RenameTableKeyOp(table_path=["reporting"], key="output_config", new_key="enabled")])+ assert outcomes == [FixOpOutcome.CONFLICT]++ def test_ensure_table_over_a_non_table_key_is_a_conflict(self) -> None:+ """The second of ``ensure_table``'s reported bugs: this used to claim the parent was missing.++ The parent is right there — it is the *key* that is occupied by something that is not a+ table, and creating the table would destroy whatever the user put there.+ """+ _, outcomes = _apply(text=_DOC, ops=[EnsureTableOp(table_path=["reporting", "output_config", "path"])])+ assert outcomes == [FixOpOutcome.CONFLICT]++ def test_ensure_table_with_a_genuinely_missing_parent_still_skips(self) -> None:+ """The absence case keeps its guarded skip — only the misreported case changed."""+ _, outcomes = _apply(text=_DOC, ops=[EnsureTableOp(table_path=["no_such_section", "child"])])+ assert outcomes == [FixOpOutcome.SKIPPED]diff --git a/tests/unit/pipelex/pipeline/fixes/test_fix_applier_native_concept.py b/tests/unit/pipelex/pipeline/fixes/test_fix_applier_native_concept.pyindex dfc9475a4..f883faef9 100644--- a/tests/unit/pipelex/pipeline/fixes/test_fix_applier_native_concept.py+++ b/tests/unit/pipelex/pipeline/fixes/test_fix_applier_native_concept.py@@ -14,7 +14,7 @@ import pytestimport tomlkitfrom pipelex.pipeline.fixes.applier import FixOpOutcome, apply_fix_ops, serialize_and_format-from pipelex.suggested_fix import FixOp, FixOpKind+from pipelex.suggested_fix import DeleteKeyOp, FixOp_DATA = Path("tests/data/fixes")@@ -25,7 +25,7 @@ def _dumps(toml_doc: tomlkit.TOMLDocument) -> str:def _delete_concept_op(*, key: str) -> FixOp:- return FixOp(kind=FixOpKind.DELETE_KEY, table_path=["concept"], key=key)+ return DeleteKeyOp(table_path=["concept"], key=key)class TestFixApplierNativeConcept:diff --git a/tests/unit/pipelex/pipeline/fixes/test_fix_applier_strip_namespace.py b/tests/unit/pipelex/pipeline/fixes/test_fix_applier_strip_namespace.pyindex ec3b91829..bffb0b15f 100644--- a/tests/unit/pipelex/pipeline/fixes/test_fix_applier_strip_namespace.py+++ b/tests/unit/pipelex/pipeline/fixes/test_fix_applier_strip_namespace.py@@ -14,7 +14,7 @@ from typing import Any, castimport tomlkitfrom pipelex.pipeline.fixes.applier import FixOpOutcome, apply_fix_ops, serialize_and_format-from pipelex.suggested_fix import FixOp, FixOpKind+from pipelex.suggested_fix import FixOp, RenameTableKeyOp, SetKeyOp_DATA = Path("tests/data/fixes")@@ -25,11 +25,11 @@ def _dumps(toml_doc: tomlkit.TOMLDocument) -> str:def _rename_op(*, key: str, new_key: str) -> FixOp:- return FixOp(kind=FixOpKind.RENAME_TABLE_KEY, table_path=["pipe"], key=key, new_key=new_key)+ return RenameTableKeyOp(table_path=["pipe"], key=key, new_key=new_key)def _strip_main_pipe_op(*, value: str) -> FixOp:- return FixOp(kind=FixOpKind.SET_KEY, table_path=[], key="main_pipe", value=value)+ return SetKeyOp(table_path=[], key="main_pipe", value=value)_STRIP_OPS = [@@ -139,11 +139,16 @@ class TestFixApplierStripNamespace:assert [application.outcome for application in second] == [FixOpOutcome.SKIPPED, FixOpOutcome.APPLIED]assert serialize_and_format(toml_doc) == once- def test_rename_skips_on_collision(self) -> None:- """Renaming to a key already declared separately is skipped, not applied (no clobber)."""+ def test_rename_conflicts_on_collision(self) -> None:+ """Renaming onto a key already declared separately is a CONFLICT, and clobbers nothing.++ It was reported as a plain SKIPPED, which is the outcome for "nothing to do" — so a+ caller had no way to tell a benign no-op from a change it could not make on the user's+ behalf without parsing the detail string.+ """toml_doc = tomlkit.loads(_COLLISION_MTHDS)applications = apply_fix_ops(toml_doc=toml_doc, ops=[_rename_op(key="coll.hello", new_key="hello")])- assert [application.outcome for application in applications] == [FixOpOutcome.SKIPPED]+ assert [application.outcome for application in applications] == [FixOpOutcome.CONFLICT]dumped = _dumps(toml_doc)# Both declarations survive untouched — nothing was clobbered.assert '[pipe."coll.hello"]' in dumped@@ -168,12 +173,12 @@ class TestFixApplierStripNamespace:# The whole document still formats cleanly (no malformed TOML out of the proxy rename).assert "[pipe.hello]" in serialize_and_format(toml_doc)- def test_rename_skips_on_collision_across_interleaved_sections(self) -> None:- """A collision with a bare key living in a *different* ``[pipe.*]`` section is still a skip."""+ def test_rename_conflicts_on_collision_across_interleaved_sections(self) -> None:+ """A collision with a bare key living in a *different* ``[pipe.*]`` section conflicts too."""interleaved_collision = _INTERLEAVED_MTHDS.replace("[pipe.other]", "[pipe.hello]")toml_doc = tomlkit.loads(interleaved_collision)applications = apply_fix_ops(toml_doc=toml_doc, ops=[_rename_op(key="inter.hello", new_key="hello")])- assert [application.outcome for application in applications] == [FixOpOutcome.SKIPPED]+ assert [application.outcome for application in applications] == [FixOpOutcome.CONFLICT]dumped = _dumps(toml_doc)assert '[pipe."inter.hello"]' in dumpeddiff --git a/tests/unit/pipelex/pipeline/fixes/test_fix_planner.py b/tests/unit/pipelex/pipeline/fixes/test_fix_planner.pyindex 69a36a739..1f406deff 100644--- a/tests/unit/pipelex/pipeline/fixes/test_fix_planner.py+++ b/tests/unit/pipelex/pipeline/fixes/test_fix_planner.py@@ -13,7 +13,10 @@ import pytestfrom pipelex.core.exceptions import PipesAndConceptValidationErrorDatafrom pipelex.core.pipes.exceptions import PipeValidationErrorTypefrom pipelex.pipeline.fixes.planner import plan_fix_for_pipe_validation_error-from pipelex.suggested_fix import FixOpKind, FixSafety+from pipelex.suggested_fix import DeleteKeyOp, EnsureTableOp, FixSafety, SetKeyOp++# The inputs table of the pipe every input-drift case below is built around.+_INPUTS_TABLE_PATH = ["pipe", "make_summary", "inputs"]def _error_data(@@ -62,12 +65,7 @@ class TestFixPlanner:assert fix.fix_code == "match-sequence-output"assert fix.safety == FixSafety.SAFEassert fix.source == "main.mthds"- assert len(fix.ops) == 1- the_op = fix.ops[0]- assert the_op.kind == FixOpKind.SET_KEY- assert the_op.table_path == ["pipe", "list_ideas"]- assert the_op.key == "output"- assert the_op.value == "Idea[]"+ assert fix.ops == [SetKeyOp(table_path=["pipe", "list_ideas"], key="output", value="Idea[]")]def test_multiplicity_mismatch_yields_fix_with_expected_ref_value(self) -> None:"""An enriched INADEQUATE_OUTPUT_MULTIPLICITY yields the same fix, carrying the expected ref."""@@ -76,7 +74,7 @@ class TestFixPlanner:)assert fix is not Noneassert fix.fix_code == "match-sequence-output"- assert fix.ops[0].value == "Idea[3]"+ assert fix.ops == [SetKeyOp(table_path=["pipe", "list_ideas"], key="output", value="Idea[3]")]def test_missing_expected_ref_yields_none(self) -> None:"""No enriched expected ref (PipeParallel / PipeCondition / operator raise sites) → no fix."""@@ -120,12 +118,7 @@ class TestFixPlanner:assert fix.fix_code == "sync-controller-inputs"assert fix.safety == FixSafety.SAFEassert fix.source == "main.mthds"- assert len(fix.ops) == 1- the_op = fix.ops[0]- assert the_op.kind == FixOpKind.SET_KEY- assert the_op.table_path == ["pipe", "make_summary", "inputs"]- assert the_op.key == "text"- assert the_op.value == "Text"+ assert fix.ops == [SetKeyOp(table_path=_INPUTS_TABLE_PATH, key="text", value="Text")]def test_input_drift_diff_adds_updates_and_deletes(self) -> None:"""The fix is a diff: set_key for added/changed variables, delete_key for extraneous ones."""@@ -136,13 +129,11 @@ class TestFixPlanner:))assert fix is not None- op_shapes = [(op.kind, op.key, op.value) for op in fix.ops]- assert op_shapes == [- (FixOpKind.SET_KEY, "text", "Text"),- (FixOpKind.SET_KEY, "doc", "Doc"),- (FixOpKind.DELETE_KEY, "note", None),+ assert fix.ops == [+ SetKeyOp(table_path=_INPUTS_TABLE_PATH, key="text", value="Text"),+ SetKeyOp(table_path=_INPUTS_TABLE_PATH, key="doc", value="Doc"),+ DeleteKeyOp(table_path=_INPUTS_TABLE_PATH, key="note"),]- assert all(op.table_path == ["pipe", "make_summary", "inputs"] for op in fix.ops)for var_name in ("text", "doc", "note"):assert var_name in fix.description@@ -156,7 +147,7 @@ class TestFixPlanner:))assert fix is not None- assert [(op.kind, op.key) for op in fix.ops] == [(FixOpKind.SET_KEY, "note")]+ assert fix.ops == [SetKeyOp(table_path=_INPUTS_TABLE_PATH, key="note", value="Text")]def test_no_declared_inputs_ensures_table_then_sets_each_key(self) -> None:"""The same ops create a missing table or preserve an explicitly empty block table."""@@ -167,12 +158,11 @@ class TestFixPlanner:))assert fix is not None- assert [(op.kind, op.key, op.value) for op in fix.ops] == [- (FixOpKind.ENSURE_TABLE, None, None),- (FixOpKind.SET_KEY, "text", "Text"),- (FixOpKind.SET_KEY, "doc", "Doc?"),+ assert fix.ops == [+ EnsureTableOp(table_path=_INPUTS_TABLE_PATH),+ SetKeyOp(table_path=_INPUTS_TABLE_PATH, key="text", value="Text"),+ SetKeyOp(table_path=_INPUTS_TABLE_PATH, key="doc", value="Doc?"),]- assert all(op.table_path == ["pipe", "make_summary", "inputs"] for op in fix.ops)def test_equal_mappings_yield_none(self) -> None:"""An empty diff (renderings already agree) must not produce a no-op fix."""diff --git a/tests/unit/pipelex/pipeline/test_validation_errors.py b/tests/unit/pipelex/pipeline/test_validation_errors.pyindex b4880ae09..4fe38ecc1 100644--- a/tests/unit/pipelex/pipeline/test_validation_errors.py+++ b/tests/unit/pipelex/pipeline/test_validation_errors.py@@ -16,7 +16,7 @@ from pipelex.core.exceptions import PipeFactoryErrorData, PipelexBundleBlueprintfrom pipelex.core.pipes.exceptions import PipeFactoryErrorType, PipeValidationErrorTypefrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validation_errors import build_validation_error_items-from pipelex.suggested_fix import FixOpKind+from pipelex.suggested_fix import DeleteKeyOp, RenameTableKeyOp, SetKeyOpdef _build_items(exc: ValidateBundleError) -> list[ValidationErrorItem]:@@ -292,8 +292,7 @@ class TestBuildValidationErrorItems:suggested_fix = items[0].suggested_fixassert suggested_fix is not Noneassert suggested_fix.fix_code == "match-sequence-output"- assert suggested_fix.ops[0].table_path == ["pipe", "list_ideas"]- assert suggested_fix.ops[0].value == "Idea[]"+ assert suggested_fix.ops == [SetKeyOp(table_path=["pipe", "list_ideas"], key="output", value="Idea[]")]def test_input_drift_error_rides_a_sync_controller_inputs_fix(self) -> None:"""An enriched controller input-drift error data yields an item carrying the multi-op fix."""@@ -318,9 +317,10 @@ class TestBuildValidationErrorItems:assert suggested_fix is not Noneassert suggested_fix.fix_code == "sync-controller-inputs"assert suggested_fix.source == "main.mthds"- assert [(op.kind, op.key) for op in suggested_fix.ops] == [- (FixOpKind.SET_KEY, "text"),- (FixOpKind.DELETE_KEY, "note"),+ inputs_table_path = ["pipe", "make_summary", "inputs"]+ assert suggested_fix.ops == [+ SetKeyOp(table_path=inputs_table_path, key="text", value="Text"),+ DeleteKeyOp(table_path=inputs_table_path, key="note"),]def test_blueprint_native_redeclaration_rides_a_strip_fix(self) -> None:@@ -347,7 +347,7 @@ class TestBuildValidationErrorItems:assert suggested_fix is not Noneassert suggested_fix.fix_code == "strip-native-concept-redecl"assert suggested_fix.source == "main.mthds"- assert [(op.kind, op.table_path, op.key) for op in suggested_fix.ops] == [(FixOpKind.DELETE_KEY, ["concept"], "Text")]+ assert suggested_fix.ops == [DeleteKeyOp(table_path=["concept"], key="Text")]def test_blueprint_strip_namespace_rides_a_rename_fix(self) -> None:"""An enriched same-domain dotted declaration carries a strip-namespace rename through the builder."""@@ -369,9 +369,7 @@ class TestBuildValidationErrorItems:suggested_fix = items[0].suggested_fixassert suggested_fix is not Noneassert suggested_fix.fix_code == "strip-namespace"- assert [(op.kind, op.table_path, op.key, op.new_key) for op in suggested_fix.ops] == [- (FixOpKind.RENAME_TABLE_KEY, ["pipe"], "greetings.hello", "hello"),- ]+ assert suggested_fix.ops == [RenameTableKeyOp(table_path=["pipe"], key="greetings.hello", new_key="hello")]def test_non_fixable_blueprint_error_has_no_suggested_fix(self) -> None:"""An un-enriched INVALID_PIPE_CODE_SYNTAX (no ``stripped_pipe_code``) keeps ``suggested_fix`` unset."""diff --git a/tests/unit/pipelex/system/configuration/test_config_surface.py b/tests/unit/pipelex/system/configuration/test_config_surface.pynew file mode 100644index 000000000..76a5fe786--- /dev/null+++ b/tests/unit/pipelex/system/configuration/test_config_surface.py@@ -0,0 +1,41 @@+"""Unit tests for the reserved `[meta]` strip shared by every configuration surface.++The key is reserved so a later project can stamp a schema version into a file without that+being a breaking change today. Nothing writes it, but every configuration-surface reader must+already tolerate it — otherwise the first file that carries one fails an `extra="forbid"`+model and takes the boot with it.+"""++from typing import Any++from pipelex.system.configuration.config_surface import strip_reserved_meta+++class TestStripReservedMeta:+ def test_the_reserved_key_is_removed_with_its_now_empty_table(self) -> None:+ """The whole `[meta]` goes when `schema_version` was all it held."""+ config_dict: dict[str, Any] = {"meta": {"schema_version": 3}, "pipelex": {"kept": True}}+ strip_reserved_meta(config_dict=config_dict)+ assert config_dict == {"pipelex": {"kept": True}}++ def test_a_meta_table_with_other_keys_keeps_them(self) -> None:+ """Only the reserved key is ours to strip.++ Anything else under `[meta]` is not reserved, so it must go on failing validation+ loudly rather than being swallowed along with the key that is.+ """+ config_dict: dict[str, Any] = {"meta": {"schema_version": 3, "something_else": "x"}}+ strip_reserved_meta(config_dict=config_dict)+ assert config_dict == {"meta": {"something_else": "x"}}++ def test_a_configuration_without_the_key_is_untouched(self) -> None:+ """The overwhelmingly common case — nothing writes the key — costs nothing."""+ config_dict: dict[str, Any] = {"pipelex": {"kept": True}}+ strip_reserved_meta(config_dict=config_dict)+ assert config_dict == {"pipelex": {"kept": True}}++ def test_a_non_table_meta_is_left_for_validation_to_reject(self) -> None:+ """`meta = "oops"` is not the reserved shape, so it is not this helper's to remove."""+ config_dict: dict[str, Any] = {"meta": "oops"}+ strip_reserved_meta(config_dict=config_dict)+ assert config_dict == {"meta": "oops"}diff --git a/tests/unit/pipelex/test_fix_op_union.py b/tests/unit/pipelex/test_fix_op_union.pynew file mode 100644index 000000000..d1b8ef61a--- /dev/null+++ b/tests/unit/pipelex/test_fix_op_union.py@@ -0,0 +1,132 @@+"""Unit tests for the ``FixOp`` discriminated union (``pipelex/suggested_fix.py``).++The union is what replaces the applier's hand-written shape checks: a malformed op must be+refused when it is parsed, not discovered halfway through a file rewrite. These tests pin the+three things that has to mean — the tag selects the variant, a variant refuses a field it does+not have, and a variant refuses to be built without the fields its handler reads — plus the+narrower ``MigrationOp`` alias, which is the whole mechanism keeping materializing operations+out of a migration ledger.+"""++import pytest+from pydantic import BaseModel, ValidationError++from pipelex.suggested_fix import (+ DeleteKeyOp,+ DeleteTableOp,+ EnsureTableOp,+ FixOp,+ FixOpKind,+ MigrationOp,+ MoveKeyOp,+ RemapValueOp,+ RenameTableKeyOp,+ SetKeyOp,+)+++class _FixOpHolder(BaseModel):+ """A parse target for the wide alias — the shape ``SuggestedFix.ops`` has."""++ op: FixOp+++class _MigrationOpHolder(BaseModel):+ """A parse target for the narrow alias — the shape a ledger entry's ops have."""++ op: MigrationOp+++class TestFixOpUnion:+ @pytest.mark.parametrize(+ ("payload", "expected_type"),+ [+ ({"kind": "set_key", "table_path": ["pipe"], "key": "output", "value": "Text"}, SetKeyOp),+ ({"kind": "ensure_table", "table_path": ["pipe", "x", "inputs"]}, EnsureTableOp),+ ({"kind": "delete_key", "table_path": ["concept"], "key": "Text"}, DeleteKeyOp),+ ({"kind": "delete_table", "table_path": ["legacy"]}, DeleteTableOp),+ ({"kind": "rename_table_key", "table_path": [], "key": "old", "new_key": "new"}, RenameTableKeyOp),+ ({"kind": "move_key", "table_path": ["a"], "key": "k", "new_table_path": ["b"], "new_key": "k"}, MoveKeyOp),+ ({"kind": "remap_value", "table_path": ["a"], "key": "k", "mapping": {"old": "new"}}, RemapValueOp),+ ],+ )+ def test_kind_string_selects_the_variant(self, payload: dict[str, object], expected_type: type[BaseModel]) -> None:+ """A raw ``kind`` string — how an op arrives from JSON or from a ledger — picks its class."""+ assert isinstance(_FixOpHolder.model_validate({"op": payload}).op, expected_type)++ def test_a_field_the_kind_does_not_have_is_refused(self) -> None:+ """``extra="forbid"`` per variant: a ``new_key`` on a ``delete_key`` is a parse error.++ Under the flat model every op carried every optional field, so this payload parsed+ happily and the stray ``new_key`` was silently ignored at application time.+ """+ with pytest.raises(ValidationError):+ _FixOpHolder.model_validate({"op": {"kind": "delete_key", "table_path": [], "key": "x", "new_key": "y"}})++ def test_a_field_the_handler_reads_cannot_be_omitted(self) -> None:+ """A ``set_key`` without a value is refused at parse time, not raised at apply time."""+ with pytest.raises(ValidationError):+ _FixOpHolder.model_validate({"op": {"kind": "set_key", "table_path": [], "key": "x"}})++ @pytest.mark.parametrize("kind", [FixOpKind.ENSURE_TABLE, FixOpKind.DELETE_TABLE])+ def test_a_table_addressing_op_refuses_an_empty_path(self, kind: FixOpKind) -> None:+ """These two kinds address the table itself, and the document root is not a valid target."""+ with pytest.raises(ValidationError):+ _FixOpHolder.model_validate({"op": {"kind": kind, "table_path": []}})++ @pytest.mark.parametrize(+ "payload",+ [+ {"kind": "set_key", "table_path": ["section"], "key": "k", "value": "v"},+ {"kind": "ensure_table", "table_path": ["section"]},+ ],+ )+ def test_migration_alias_refuses_materializing_kinds(self, payload: dict[str, object]) -> None:+ """The narrow alias is what makes "a ledger never materializes" a parse error.++ Both kinds write material the file did not have, which is right when a typed error names+ the key and wrong under always-replay, where it would overwrite a user's own value on+ every single run. The op is well-formed — the wide alias accepts it — so the refusal is+ the alias choosing, not the payload being broken.+ """+ assert isinstance(_FixOpHolder.model_validate({"op": payload}).op, SetKeyOp | EnsureTableOp)+ with pytest.raises(ValidationError):+ _MigrationOpHolder.model_validate({"op": payload})++ def test_migration_alias_accepts_every_structural_kind(self) -> None:+ """Whatever ``is_structural`` claims is exactly what the narrow alias parses.++ Asserting the two against each other rather than against a hand-written list is what+ keeps a newly added kind from being classified in one place and forgotten in the other.+ """+ structural_kinds = {kind for kind in FixOpKind if kind.is_structural}+ payloads: dict[FixOpKind, dict[str, object]] = {+ FixOpKind.DELETE_KEY: {"kind": "delete_key", "table_path": ["s"], "key": "k"},+ FixOpKind.DELETE_TABLE: {"kind": "delete_table", "table_path": ["s"]},+ FixOpKind.RENAME_TABLE_KEY: {"kind": "rename_table_key", "table_path": ["s"], "key": "k", "new_key": "n"},+ FixOpKind.MOVE_KEY: {"kind": "move_key", "table_path": ["s"], "key": "k", "new_table_path": ["t"], "new_key": "k"},+ FixOpKind.REMAP_VALUE: {"kind": "remap_value", "table_path": ["s"], "key": "k", "mapping": {"old": "new"}},+ }+ assert set(payloads) == structural_kinds+ for payload in payloads.values():+ assert _MigrationOpHolder.model_validate({"op": payload}).op.kind.is_structural++ def test_a_wildcard_destination_is_refused(self) -> None:+ """A wildcard source means "each of these"; a wildcard destination names no target at all."""+ with pytest.raises(ValidationError):+ _FixOpHolder.model_validate(+ {"op": {"kind": "move_key", "table_path": ["deck", "*"], "key": "k", "new_table_path": ["deck", "*"], "new_key": "k"}}+ )++ def test_a_wildcard_source_is_accepted(self) -> None:+ """The source side is the whole point of the segment, and stays legal."""+ op = _FixOpHolder.model_validate(+ {"op": {"kind": "move_key", "table_path": ["deck", "*"], "key": "k", "new_table_path": ["storage"], "new_key": "k"}}+ ).op+ assert isinstance(op, MoveKeyOp)+ assert op.table_path == ["deck", "*"]++ def test_a_remap_needs_a_non_empty_mapping(self) -> None:+ """An empty mapping is an operation that can never do anything — an authoring mistake."""+ with pytest.raises(ValidationError):+ _FixOpHolder.model_validate({"op": {"kind": "remap_value", "table_path": ["a"], "key": "k", "mapping": {}}})diff --git a/tests/unit/pipelex/test_suggested_fix.py b/tests/unit/pipelex/test_suggested_fix.pyindex e3878ca1c..1ea4d4a21 100644--- a/tests/unit/pipelex/test_suggested_fix.py+++ b/tests/unit/pipelex/test_suggested_fix.py@@ -9,7 +9,7 @@ what it was before the field existed.import jsonfrom pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem-from pipelex.suggested_fix import FixOp, FixOpKind, FixSafety, SuggestedFix+from pipelex.suggested_fix import FixOpKind, FixSafety, SetKeyOp, SuggestedFixdef _sample_fix() -> SuggestedFix:@@ -19,8 +19,7 @@ def _sample_fix() -> SuggestedFix:safety=FixSafety.SAFE,source="main.mthds",ops=[- FixOp(- kind=FixOpKind.SET_KEY,+ SetKeyOp(table_path=["pipe", "list_ideas"],key="output",value="Idea[]",@@ -72,7 +71,12 @@ class TestSuggestedFixModels:sort_keys=True,)- def test_unset_op_fields_drop_from_wire(self) -> None:- """A set_key op's unused fields (new_key) drop out of the exclude_none projection."""- dumped = _sample_fix().model_dump(mode="json", exclude_none=True)- assert "new_key" not in dumped["ops"][0]+ def test_op_wire_shape_is_exactly_its_variant_fields(self) -> None:+ """An op carries its own fields and no others — no ``exclude_none`` projection needed.++ Under the flat model this needed ``exclude_none=True`` to keep a ``set_key``'s unused+ ``new_key`` off the wire. The union removes the question: ``SetKeyOp`` has no such field,+ so the plain dump is already the minimal shape.+ """+ dumped = _sample_fix().model_dump(mode="json")+ assert set(dumped["ops"][0]) == {"kind", "table_path", "key", "value"}diff --git a/wip/migrator-phase0-spike.md b/wip/migrator-phase0-spike.mdnew file mode 100644index 000000000..b4f33c56a--- /dev/null+++ b/wip/migrator-phase0-spike.md@@ -0,0 +1,93 @@+# Migrator Phase 0 — the spike result++> Session S0 of the Migrator v3 runbook (`wip/migrator-3/sequencing.md` in the workspace-root repo). Read-only investigation: nothing in `pipelex/` was changed. Measured on 2026-08-15 against `dev` at `d2d666419` (v0.45.0 plus #1104/#1106/#1109), tomlkit 0.14.0, Python 3.12.+>+> Everything below is a measurement, not a prediction. Each one is pinned by a checked-in test in `tests/unit/pipelex/pipeline/fixes/test_fix_applier_config_surface_shapes.py`, which replaces the throwaway probe the plan carried (`wip/migrator-3/probe_tomlkit_reshape_shapes.py` in the workspace repo) — so a tomlkit bump that changes any of it fails CI instead of silently corrupting somebody's configuration file.++## The answer Phase 1 was waiting for: extend, do not widen++**Phase 1 extends the applier's op vocabulary. It does not need to widen the addressing model first.**++The charter's premise was that `table_path` might not reach what our configuration files actually contain, because `_resolve_table` walks dict-likes only. Measured across every configuration file this repository tracks, that premise does not hold: every table in every file is addressable today. The one shape the model cannot reach — an element of an array of tables — appears in exactly one tracked file, `plxt.toml`, which is not a migration surface and is not in any surface's file glob. It is also handled safely rather than dangerously: the path simply fails to resolve and the op is reported as skipped, never raised.++So the work in Phase 1 is what the plan already lists — the `FixOp` discriminated union, `move_key` and `remap_value`, the `*` wildcard, the `CONFLICT` outcome, the `ensure_table` fixes — with no addressing-model detour ahead of it.++## The charter, item by item++### The path model against real configuration files++Every table in every tracked configuration file is reachable by its `table_path`. This was measured through the public applier rather than by calling the private resolver: a `delete_key` for a key no configuration file declares always skips, and the *reason* it gives is the measurement — "table … not found in document" means the path model could not walk there, "key … not found in table …" means it could. Every table path in every file reports the latter.++The exotic shapes, each measured:++- **Inline tables are ordinary tables to the path model.** `default_templating_style = { tag_style = "xml" }` and the `quality_to_steps_maps` entries resolve and accept a rename, and the rename touches exactly the one line it should. tomlkit drops the quoting on the key it rewrites (`flux = { lowest = 14, "medium" = 28, … }`), which is harmless because the key is changing anyway.+- **Dotted-key assignments are tables.** `nested.leaf = 1` gives a real table node at `nested`, so `["section", "nested"]` addresses it, and a rename of `leaf` re-renders as a dotted key rather than exploding into a block table.+- **A quoted key containing a dot is one path segment.** `["outer.inner"]` is addressed as the single segment `outer.inner`, and a renamed key that needs quoting keeps it.+- **Arrays of tables are invisible to the model, and that is safe.** An `[[rule]]` node is a `list`, so no `table_path` reaches it or anything under it. The guarded-skip contract turns this into a report rather than a crash. No migration surface contains one; if one ever appears, the `*` wildcard has no array syntax and the ledger would need a new segment kind — a decision for that day, not this one.+- **Comment attachment is the one real limitation.** See its own section below.++### Byte-identity of an untouched round trip++`tomlkit.dumps(tomlkit.parse(text)) == text` holds for every tracked configuration file: the packaged defaults, all the kit templates, the repository's own `.pipelex/` files, and the unit-test config. Replay neutrality and the transform goldens are byte-level claims that rest entirely on this, so it is now a parametrized test rather than an assumption.++### The out-of-order table proxy++The packaged defaults document is written out of order, and this is worse than the plan recorded: **two** root tables resolve to `OutOfOrderTableProxy`, not one. `pipelex` is split into three chunks and `migration` into two, because `[pipelex.kit_config]` and `[migration.migration_maps.telemetry]` sit near the end of the file after `[cogt]` and each other. Every proxy question the plan left open is now answered, and all of them answer favourably:++- **`delete_table` works on a proxy**, both for a table nested inside one (`pipelex.log_config`) and for a whole multi-chunk proxy addressed at the root (`migration`, `pipelex`). Every chunk goes; no orphaned header is left behind; the result reparses.+- **A root-level rename of a proxy works.** Renaming `pipelex` to `interpreter` rewrote every child header across all three chunks and the content compares equal to the original subtree. This is the configuration reshape's hardest shape and it goes through `Container._replace`, a tomlkit internal — which is precisely why it now has a dedicated test.+- **Inserting a new block table into a proxy lands it at the end of the proxy's first chunk**, not at the end of the file. Inserting into a plain table lands it at the end of that table's span. Neither placement is wrong, but they differ, and `move_key`'s placement rule has to describe both.+- **`ensure_table` still emits `key = {}`**, an inline table, confirmed on a proxy as well. That is the known `.mthds` bug the plan already schedules for Phase 1; it is pinned by a test now so the fix is a visible change to an expectation rather than a silent one.++### The reshape's three shapes, and then the whole entry++The three shapes the reshape needs — a root super-table rename, a table-valued cross-parent move, and renames inside the out-of-order proxy — all behave. Rather than stop there, the spike ran **the reshape's complete ledger entry as written in `reshape.md`**, in order, with a throwaway `move_key` built the obvious way (pop the value, create missing destination parents as block tables, re-add), over the packaged defaults, the kit template, the repository's project config and override, and the unit-test config.++It works. On the packaged defaults nearly every op applies; the two that skip are the two the entry itself predicts will skip on a file that never set them (`plugins.boot_orchestrator` and the root `session_id`). The result reparses, the root tables are exactly `runtime`, `inference`, `interpreter` and `kit`, and on the sparser files each op skips or applies exactly according to what that file happens to contain. Most importantly: **replaying the whole entry over the already-migrated document applies nothing and changes no bytes**, on every file tried. Replay neutrality — the engine's central guarantee — holds against the real entry on real documents, before a line of the engine exists.++This does not retire any of Phase 2's checks; it is one witness, not the convergence check, and the ledger entry it exercised is still hand-written prose in a plan document. What it does is remove the risk that the reshape turns out to be unexpressible in the vocabulary Phase 1 is about to build.++### Repeated application and whitespace++Applying an op twice to the same DOM, and re-applying it to the reparsed output, both leave the bytes unchanged; the second application reports itself skipped because its source is gone. So the blank line the earlier probe noticed does not accumulate.++It is worth being exact about what a *first* application does to whitespace, because a migrated file will not be byte-minimal and users will notice:++- Renaming a plain root table adds one line.+- Renaming a three-chunk proxy adds four lines and **drops the table's own bare header** — the empty `[pipelex]` line at the top of the packaged file has no `[interpreter]` counterpart afterwards. A plain table keeps its bare header (`[cogt]` renames to a still-present `[inference]`). Both are semantically identical, since a parent with only sub-tables is implicit in TOML, but the asymmetry should not surprise a reviewer reading a migration diff.+- Renaming inside a proxy adds one line.++All three are stable under replay.++### Comment attachment on moved nodes — the one thing that does not work++**A comment block preceding a table does not travel when the table moves, and this cannot be fixed by being cleverer with the move.** tomlkit does not attach such a block to the table it appears to introduce; it stores it as trailing trivia of the *previous sibling*, inside that sibling's serialized string. Measured directly: in the kit template, the `# Storage Config` banner is part of `tracing_config`'s rendering, not of `storage_config`'s. Carrying it would mean string surgery on a neighbour's tail plus a heuristic for which comments "belong" to what follows.++The consequence is real and user-visible. `ensure_global_config_exists` seeds every `~/.pipelex/pipelex.toml` as a full copy of the kit template, and that template is heavily commented — a banner block per section plus per-key explanations. Running the reshape entry over it leaves the banners in place while their sections move away, so the migrated file ends up with `# Log Config` above `[inference.model_deck]` and `# Plugins` above `[runtime.storage]`. The TOML is correct; the comments now lie.++Comments *inside* a moved table are fine — the whole body travels, including trailing inline comments on individual keys. It is only the introducing banner that stays behind.++Three things follow, and they are for S1 and S4 rather than for this session:++1. **The contract must state it** (S1): a moved table arrives without its introducing comment, and comments near a move may end up labelling the wrong section. Nothing in the engine may rely on comment fidelity across a move.+2. **The reshape should not inherit the damage in the files it owns** (S4): `reshape.md` already rewrites the packaged defaults by hand and regenerates the kit template through the sync, so both come out correctly commented. That is now a requirement rather than a convenience.+3. **The `migrate` command should say so** (S6): a user whose global config was seeded from the template will see mislabelled banners, and the report is the place to tell them, since we will not be rewriting their comments for them.++### The tomlkit-bump tripwire++The existing golden byte-compare in the `.mthds` fix tests is a real tripwire but not a sufficient one for this project: it exercises `set_key` and `delete_key` on one `.mthds` fixture, downstream of the MTHDS formatter's whole-file reflow — which is exactly the step migration does not use. It would not notice a tomlkit change to proxy handling, to header re-rendering under `Container._replace`, or to comment attachment.++The recommendation is not to make the transform goldens byte-exact — `design.md` is right that they compare paths and op-written values, and a byte-exact golden over a reflowing dependency would be a maintenance tax that teaches nothing. Put the byte-level tripwire where byte-level behaviour is actually claimed:++- The characterization test added by this spike, which pins round-trip identity, proxy behaviour, the root-level proxy rename and the comment limitation against the real files.+- The convergence check (Phase 2), which replays each entry over the real reference documents and asserts the bytes do not move — the strongest byte-level signal in the project, because it runs on real documents rather than a fixture.++Together those two fail loudly on a tomlkit change; the transform goldens stay parsed-level, as designed.++## What this changes downstream++Nothing in the plan needs restructuring. Three items get sharper:++- **S1, the contract.** Add: arrays of tables are unaddressable and reserved (no `table_path` segment syntax reaches them, and no surface has one today); a moved table loses its introducing comment; a migration is not byte-minimal — expect small whitespace growth and possibly a dropped empty parent header; and the placement rule needs both halves measured here (a created root parent lands at the end of the file, while a table inserted into an existing out-of-order parent lands at the end of that parent's first chunk).+- **S2, Phase 1.** No addressing work. The `ensure_table` block-table fix now has a failing-on-change expectation waiting for it in the new test module.+- **S4, the reshape.** The hand-written packaged defaults and the regenerated kit template are the mechanism that keeps our own files correctly commented; the entry as written in `reshape.md` needs no changes — it was executed end to end here.diff --git a/wip/pr-1110-review-notes.md b/wip/pr-1110-review-notes.mdnew file mode 100644index 000000000..7971e8dd4--- /dev/null+++ b/wip/pr-1110-review-notes.md@@ -0,0 +1,55 @@+# PR #1110 review — deferred items++Deferred findings from the SWE-agent review triage of PR #1110 (Migrator Phases 0–1: the migration contract, the operation vocabulary and the schema-1 cut). Each was verified against the code; the ones below are deferred as design calls or as work that belongs to a later migrator phase (see `wip/migrator-3/sequencing.md` at the workspace root), not dismissed. Everything else the bots raised was fixed on the branch: wildcard operations are now atomic on `CONFLICT`, the coverage walk detects occupied destinations and `delete_table` aimed at a key, enum-member accounting follows a path through the entry's own renames, malformed ledgers and misnamed goldens fail as migration errors, `Mapping[...]` is an open node, list items are cleaned of nulls before TOML serialization, and the dev commands escape Rich markup and follow the quiet-mode convention.++## Value-domain narrowing is classified as additive (the one to take up first)++**Reporter:** Codex (two P1 threads, `pipelex/migration/coverage.py` head-link classification and `pipelex/migration/fingerprint.py` `_strip_annotated`). **Verified:** real.++A change that keeps every path and every enum member but narrows what a value may be — `int → str`, `str → SomeEnum`, `list[int] → list[str]`, or a tightened constraint such as `Field(gt=0) → Field(gt=10)` — appears in the fingerprint diff only as a `changed_paths` entry (or, for a constraint, not at all: constraint metadata is stripped at every level). `_check_head_link` classifies that as additive and asks for a golden regeneration, so a valid old file whose value falls outside the new domain fails strict validation with a green gate.++**Why deferred:** both behaviours are stated in the contract (`docs/migration-ledger.md` → "Coverage": *a type or default changed → regenerate the golden*; → "The fingerprint": *constraint metadata is stripped … at every level*, deliberately, so a validation-library upgrade cannot move a golden). Changing them is a contract decision, and no operation in the vocabulary can repair an out-of-domain value — the only remedy is an `unsafe` entry with guidance. So the fix is a new rule, not a patch: **value-domain narrowing demands a bump and an entry, and that entry must be `unsafe`** (or carry a `remap_value` when the narrowing is `str → enum` and the old free-string spellings can be enumerated). It needs a compatibility notion the fingerprint can decide: a rendered type whose union members are a superset of the old ones is a widening (safe); `enum`/`literal → str` is a widening; anything else is a narrowing. Constraints would need a stable projection (the `annotated_types` objects — `Gt`, `Ge`, `Lt`, `Le`, `MinLen`, `MaxLen`, `MultipleOf` — are stable across pydantic versions; `Field(pattern=…)` is a string) recorded per path, with "tightened" defined per constraint kind.++**Revisit when:** Phase 2 (S5, "the checks that prove them"), after a ruling on the two contract sentences. Until then, a maintainer narrowing a type must notice the `changed_paths` line in the `umig` diff by eye — which is exactly the reliance on review the gate exists to remove, so this should not wait past S5.++## `pre_history` entries bypass coverage++**Reporter:** cubic (two P1 threads, `pipelex/migration/ledger.py:90`, `pipelex/migration/coverage.py:228`). **Verified:** the flag is accepted by the model and `check_entry_accounting` returns `[]` for it.++**Why deferred:** designed that way, for now. A pre-history entry removes paths that predate `fingerprint@1`, so no fingerprint pair describes its diff; the contract has it verified by `check-ledger` against its own `declared_removed_paths` and a hand-authored `before` document. Both `check-ledger` and the first such entry (the telemetry back-entry) are Phase 2 (S5) deliverables; no entry carries the flag today, and the coverage gate would flag any op of such an entry as dead if it were checked against `fingerprint@1`.++**Revisit when:** S5 — the check must land in the same pull request as the first `pre_history` entry, and until it does the flag is an escape hatch the contract says must not exist. If S5 slips, the cheap interim is to have coverage report a `pre_history` entry as an issue ("verified by check-ledger, which does not exist yet") so the bypass is loud.++## A required table with only optional children escapes the defaults-layer rule++**Reporter:** cubic (P1, `pipelex/migration/coverage.py:387`). **Verified:** real; `check_defaults_layer` skips `TABLE_TYPE` records, and a table's presence in the defaults document is not recorded in the fingerprint.++**Why deferred:** boot-redundant for the only packaged-document surface. `pipelex/pipelex.toml` is merged beneath every load, so a required table absent from it fails the repository's own boot (`make tb`), long before the gate. Model-defaults surfaces synthesize their reference document from the model, which cannot be built without the table. Fixing it properly means recording table presence in the fingerprint (a golden format change) or handing the defaults document to `check_defaults_layer` separately.++**Revisit when:** a second packaged-document surface appears, or the defaults layer stops being merged beneath every boot.++## Overlapping tier globs are accepted by the registry++**Reporter:** cubic (P2, `pipelex/migration/surfaces.py:159`). **Verified:** only identical glob strings are rejected; `pipelex_*.toml` and `*_local.toml` would both load.++**Why deferred:** deciding whether two glob languages overlap is not cheap in general, and the contract's sentence — *a file claimed by two globs is a registry error* — is naturally enforced where files exist: the directory walk of `pipelex migrate`. That is Phase 3 (S6). Today's registry has one glob per surface family and none overlap.++**Revisit when:** S6 builds the walk — a file matched by two globs should stop the run by name.++## Partial golden regeneration when a later surface fails++**Reporter:** cubic (P2, `pipelex/cli/dev_cli/commands/update_migration_schemas_cmd.py:35`). **Verified:** `snapshot_registry` writes per surface, so a ledger error on the second surface leaves the first's snapshot written.++**Declined:** it is a developer regeneration tool over three surfaces whose whole output is a reviewed `git diff`; a partial state is visible there and re-running after fixing the ledger converges. A stage-then-write restructure buys nothing a `git diff` does not already show.++## `sort_keys=True` on the fingerprint JSON++**Reporter:** cubic (P2, `pipelex/migration/goldens.py:65`). **Verified:** a dict-valued default copied from the packaged TOML keeps that TOML's key order, so reordering keys inside such a value moves the golden.++**Declined:** `paths` is already sorted at compute time and the record fields are fixed. The only order-sensitive material is a default copied out of `pipelex/pipelex.toml`, and any byte change to that file is already flagged by `_check_head_defaults_document` and regenerated in the same `umig` — the "false diff" is the same event seen twice, by design.++## `strip_reserved_meta` runs before `extra_overrides` are merged++**Reporter:** cubic (P3, confidence 4, `pipelex/system/configuration/config_loader.py:342`). **Verified:** a `[meta] schema_version` passed programmatically through `extra_overrides` reaches model validation.++**Declined:** `extra_overrides` is a repository-internal programmatic layer, not a configuration file the migrator ever walks or stamps. A `[meta]` table arriving that way is a caller bug and should keep failing loudly under `extra="forbid"` rather than being swallowed.