Skip to content

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

Codegen follow-ups from the @pipelex/sdk offline-check port (U1-U5) (#1127)

Louis Choqueldf548ba0ea18
diff --git a/.badges/tests.json b/.badges/tests.json
index 46897d026..bce3ad50b 100644
--- a/.badges/tests.json
+++ b/.badges/tests.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"label": "tests",
- "message": "10538",
+ "message": "10565",
"color": "blue",
"cacheSeconds": 300
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a63899f0..5506ca63b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,17 @@
# Changelog
+## [Unreleased]
+
+### Added
+
+- **`codegen.lock` now declares its format version, so the format can grow without breaking every reader:** the lock is a cross-language interchange format — this CLI writes it, other implementations of the offline check read it — and it validated strictly with no version field at all, so the day it gained any key every consumer pinned to an older reader would have failed CI with an opaque "unknown key" error instead of a drift verdict. Each lock now opens with `lock_version = 1`; a reader refuses a version it does not know and names which side to upgrade, and it reads the version *before* the key set, so a future lock is diagnosed by its version rather than by whichever new key it happens to carry first. A lock written before the field existed is version 1 by definition and needs no migration, but every regeneration rewrites the lock once to add the key — that one-line diff is the change consumers will see. The stamp header stays deliberately unversioned, since it already ignores commented fields it does not recognise.
+
+### Fixed
+
+- **The codegen stamp header is now read strictly:** `pipelex codegen check` verified a generated file as pristine even when a line had been injected between the stamp's fence markers, because the content hash covers only the body *below* the fence — so an executable statement could sit inside a header that says `DO NOT EDIT` and the tree would still report as current. Any line inside the header that does not carry the file's comment prefix now makes the stamp unparseable, which the check already reports as `hand-edited`. The `options` value must also be conformant JSON: Python's non-standard `NaN` / `Infinity` / `-Infinity` literals are refused, so a stamp cannot hold something only a Python reader accepts — the header is a cross-language interchange format, and the second implementation of the offline check (in `@pipelex/sdk`) already rejected them. Commented `key: value` lines a reader does not recognise are still ignored, so the header can gain fields without breaking older readers. One consequence to know: a file whose header was tampered with is no longer one `pipelex codegen types` will overwrite — it now refuses a destination it cannot prove it owns rather than clobbering work, so such a file has to be removed before regenerating, which is what the check's advice already tells you to do.
+- **`pipelex codegen check` now reports drift in one order, whichever half of the report it comes from:** locked artifacts were listed by their full path compared as a string, while stale orphans came out in the order a directory walk found them — a component-by-component order. For a tree holding a `models/` directory beside a `models.py`, the two halves of a single report therefore sorted paths by different rules, and a second implementation could not mirror both with one comparator. Both halves now use the plain full-string sort, and the ordering is written down as a contract: every locked-artifact drift first, then every orphan, each group by path.
+- **Generated files are written with LF line endings on every platform:** `save_text_to_path` let Python translate each newline to `os.linesep`, so a file emitted on Windows landed as CRLF on disk while its recorded content hash had been taken over the LF text it was built from. The verdict survived, because reads translate back, but the promise that regenerating produces byte-identical output held only within one platform — a team mixing Windows and Linux saw generated trees churn in version control with no change of content. Every artifact this writes (generated code, the codegen lock, JSON outputs, input templates) is now the string verbatim.
+
## [v0.46.4] - 2026-08-18
### Changed
diff --git a/docs/under-the-hood/codegen-projections.md b/docs/under-the-hood/codegen-projections.md
index f14834fe4..fdcf28101 100644
--- a/docs/under-the-hood/codegen-projections.md
+++ b/docs/under-the-hood/codegen-projections.md
@@ -68,10 +68,16 @@ Drift — generated code that no longer matches the method it was generated from
The `crate_fingerprint` is the crate's semantic hash, so reformatting or commenting a `.mthds` file never changes a stamp — only a change to the method's effective type surface does. The `content_hash` is a SHA-256 over the body **below** the stamp, so a lone file can testify that it has not been hand-edited, without the engine, the network, or the lock.
+The header itself is read strictly, because the content hash covers only what is *below* it. Every line between the fences must carry the file's comment prefix, so a line injected into the block — an uncommented statement sitting inside a header that says `DO NOT EDIT`, or a blank line — makes the stamp unparseable, which the offline check reports as **hand-edited**. The `options` value must be conformant JSON: Python's non-standard `NaN` / `Infinity` / `-Infinity` literals are refused, since the stamp header is a cross-language interchange format and a stamp only one language can read is not a valid stamp. None of this is a signature — there is no MAC anywhere, and the real defence against a malicious edit is diff review; the rule exists so a file that claims to be pristine cannot quietly carry code that was edited in.
+
+In the other direction the header is deliberately tolerant: a *commented* `key: value` line the reader does not recognise is ignored rather than rejected, so the stamp can gain a field without breaking readers built against an earlier shape.
+
### Lock
`pipelex/codegen/lock.py` writes `codegen.lock` (human-diffable TOML) recording each generated artifact's path and body hash, plus the crate fingerprint and engine version the set was built against. The lock catches the one drift class per-file stamps cannot: a deleted concept whose stale generated file lingers on disk. It is a Pipelex-owned artifact, distinct from the standard's `methods.lock` (which pins remote dependency versions).
+Every lock opens with `lock_version`, and the format has a written evolution policy — because the lock is read by implementations we do not ship, and it validates strictly: an unknown key is a hard no-verdict error, not a drift. That strictness is right *within* a version and unworkable across versions, so any change to the lock's key set or to the meaning of an existing key bumps the version, and a reader refuses a version it does not know with a message naming which side to upgrade. The version is read **before** the key set is validated, so a lock from a newer codegen is diagnosed by its version rather than by whichever new key it happens to carry first — otherwise the strict-key rejection would fire on a key the writer was entitled to add and report something the reader cannot act on. A lock with no `lock_version` key is version 1 by definition (the field was introduced *as* version 1), so nothing already on disk needs migrating; the next regeneration simply rewrites the lock with the key present. Regeneration over a lock it cannot read replaces it rather than failing, exactly as it does over a corrupt one: the run has already rewritten every artifact with this engine, so adopting this engine's lock version is the coherent outcome, and anything the newer engine had emitted surfaces as an orphan on the next check instead of being silently pruned. The **stamp** header needs no equivalent, since it is additive in the other direction — an unrecognised commented field is ignored rather than rejected.
+
### Offline check
`pipelex codegen check [DIR]` (`pipelex/codegen/check.py`) is pure hashing — **no engine, no network, no API key** — so any client (this CLI, an SDK, a short CI script) implements it identically. It reports drift by category:
@@ -81,11 +87,13 @@ The `crate_fingerprint` is the crate's semantic hash, so reformatting or comment
- **hand-edited** — a file's stamp is stripped or its recorded content hash no longer matches the body;
- **orphan** — a stamped generated file on disk that the lock does not track.
+The order of that report is part of the contract, not an implementation detail, so a second implementation can be compared to this one line by line: every locked-artifact drift comes first, ordered by the full relative path compared as a plain string, and then every orphan, ordered by that same rule. One locked path yields at most one drift, and **hand-edited** outranks **modified** when a file is both self-inconsistent and off its locked hash.
+
The verdict rides the exit code (mirroring `resolve` / `validate`): `0` current, `1` drift present, `2` no lock found. Regeneration against the engine is a **dev action**; the offline check is the **CI action** — so template improvements never redden a consumer's CI.
### Idempotent emission
-`pipelex/codegen/emission.py` ties it together in two layers. `build_stamped_projection` is the **pure** core: it stamps each emitted body and assembles the matching `codegen.lock` content — no filesystem access — so it is the single source of truth for what a projection *is* on disk. `write_stamped_projection` rides it to materialize locally: it writes each file only when its content changed (write-if-changed — no mtime churn, clean diffs, watch-mode friendly), removes any previously-tracked stamped file that dropped out of the set, and rewrites the lock. Only files the tool itself stamped are ever removed, so a hand-authored file sharing the output directory is never touched. `codegen inputs` applies the same write-if-changed rule to its single (unstamped) template file, so a full regeneration pass over a committed consumer is a true no-op when everything is current.
+`pipelex/codegen/emission.py` ties it together in two layers. `build_stamped_projection` is the **pure** core: it stamps each emitted body and assembles the matching `codegen.lock` content — no filesystem access — so it is the single source of truth for what a projection *is* on disk. `write_stamped_projection` rides it to materialize locally: it writes each file only when its content changed (write-if-changed — no mtime churn, clean diffs, watch-mode friendly), removes any previously-tracked stamped file that dropped out of the set, and rewrites the lock. Only files the tool itself stamped are ever removed, so a hand-authored file sharing the output directory is never touched. `codegen inputs` applies the same write-if-changed rule to its single (unstamped) template file, so a full regeneration pass over a committed consumer is a true no-op when everything is current. Every artifact is written with LF line endings whatever the platform, because Python would otherwise translate each newline to the host's convention: the same projection emitted on Windows and on Linux would land as different bytes while both recorded the same content hash, and a team mixing the two would watch the generated tree churn in version control with no change of content. Byte-identical regeneration is a promise across machines, not only within one. The ownership test that governs removal governs overwriting too, and it runs before the first byte is written, so a refused run leaves the tree exactly as it found it: the writer declines any destination already holding a file it cannot prove it owns — one neither tracked by the lock nor parseable as stamped. That is where the strict header gate has a visible edge. A stamped file **the lock does not track** still scans as stamped, so the check calls it an **orphan** and advises "remove or regenerate" — but a tampered header no longer *parses*, so regeneration cannot prove it owns the file and declines to reclaim it; removing it is the half of that advice that always applies. A **lock-tracked** file whose header was tampered with is the other case entirely: the lock is the ownership proof, so the check reports it as **hand-edited** and regeneration overwrites it. The writer is deliberately unwilling to clobber a file that may hold real work.
### Lint-clean by construction
diff --git a/pipelex/codegen/check.py b/pipelex/codegen/check.py
index 530fefebc..e56cd0286 100644
--- a/pipelex/codegen/check.py
+++ b/pipelex/codegen/check.py
@@ -77,7 +77,13 @@ class CodegenCheckReport(BaseModel):
def run_codegen_check(*, root: Path) -> CodegenCheckReport:
- """Run the offline drift check over `root` (the directory holding `codegen.lock`)."""
+ """Run the offline drift check over `root` (the directory holding `codegen.lock`).
+
+ The report's drift order is part of the contract, so a second implementation can mirror it exactly:
+ every locked-artifact drift comes first, in ascending order of the full relative path compared as a
+ plain string, then every orphan, ordered by that same rule. A locked path yields at most one drift,
+ and `hand-edited` outranks `modified` when a file is both self-inconsistent and off the locked hash.
+ """
try:
lock_path = resolve_output_path(root=root, relative_path=Path(CODEGEN_LOCK_FILENAME))
safe_root = lock_path.parent
@@ -140,7 +146,7 @@ def _find_orphans(*, root: Path, lock: CodegenLock) -> list[CodegenDrift]:
detail="Stamped generated file not tracked by the lock — stale; remove or regenerate.",
)
)
- return orphans
+ return sorted(orphans, key=lambda drift: drift.path)
def _iter_stampable_files(*, directory: Path) -> Iterator[Path]:
diff --git a/pipelex/codegen/lock.py b/pipelex/codegen/lock.py
index 1795ef789..1b7ef308b 100644
--- a/pipelex/codegen/lock.py
+++ b/pipelex/codegen/lock.py
@@ -10,6 +10,23 @@ the set was generated against, so the offline check can spot a file on disk that
dependency versions): different owner, location, content, and lifecycle — see
the codegen spec → "Lock format". It is encoded as human-diffable TOML, artifacts
sorted by path so version-control diffs stay minimal.
+
+## Evolution policy
+
+The lock is a cross-language interchange format — this CLI writes it, and other implementations of the
+offline check (an SDK, a CI script) read it — so its shape is a contract, and `extra="forbid"` makes any
+unknown key a hard no-verdict error rather than a drift. That strictness is correct *within* a known
+version and unworkable across versions, so the format carries `lock_version`:
+
+- Any change to the lock's key set or to the meaning of an existing key bumps `CODEGEN_LOCK_VERSION`.
+- A reader refuses a version it does not know, before validating the key set, and says which side to
+ upgrade — never an opaque shape complaint about a key the writer had every right to add.
+- A lock with no `lock_version` key is version 1 by definition: the field was introduced with version 1,
+ so every lock written before it existed is already conformant and nothing on disk needs migrating.
+
+The **stamp header** deliberately needs no equivalent, because it is additive in the other direction: an
+unrecognised *commented* `key: value` line is ignored rather than rejected, so it can gain a field
+without a version at all (`pipelex/codegen/stamp.py`).
"""
# tomlkit is not fully typed (`tomlkit.dumps`), so its member access reads as unknown here.
# pyright: reportUnknownMemberType=false
@@ -17,7 +34,7 @@ sorted by path so version-control diffs stay minimal.
import os
from collections.abc import Iterable
from pathlib import Path, PurePosixPath, PureWindowsPath
-from typing import NoReturn
+from typing import Any, NoReturn
from unicodedata import category
import tomlkit
@@ -32,6 +49,9 @@ from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
CODEGEN_LOCK_FILENAME = "codegen.lock"
+CODEGEN_LOCK_VERSION = 1
+"""The lock format version this build writes and is able to read — bumped by any change to the key set."""
+
_LOCK_HEADER = "# codegen.lock — generated artifact set (Pipelex codegen). Do not edit by hand.\n\n"
@@ -49,6 +69,14 @@ class CodegenLock(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid")
+ lock_version: int = 1
+ """The format version this lock was written in — see the module's evolution policy.
+
+ The default is the literal `1`, deliberately *not* `CODEGEN_LOCK_VERSION`: it states that a lock
+ written before the field existed is version 1, which stays true forever. New locks take their
+ version from `build_lock`, so bumping the constant is all a future format change has to do.
+ """
+
crate_fingerprint: str
engine_version: str
artifacts: list[CodegenLockEntry] = Field(default_factory=empty_list_factory_of(CodegenLockEntry))
@@ -145,13 +173,19 @@ def build_lock(*, crate_fingerprint: str, engine_version: str, artifacts: dict[s
"""Assemble a lock from a `{path: content_hash}` map, artifacts sorted by path for a stable diff."""
validate_artifact_paths(artifacts)
entries = [CodegenLockEntry(path=path, content_hash=content_hash) for path, content_hash in sorted(artifacts.items())]
- return CodegenLock(crate_fingerprint=crate_fingerprint, engine_version=engine_version, artifacts=entries)
+ return CodegenLock(
+ lock_version=CODEGEN_LOCK_VERSION,
+ crate_fingerprint=crate_fingerprint,
+ engine_version=engine_version,
+ artifacts=entries,
+ )
def encode_lock(lock: CodegenLock) -> str:
"""Encode the lock as canonical, human-diffable TOML (artifacts already sorted by path)."""
validate_artifact_paths(entry.path for entry in lock.artifacts)
payload = {
+ "lock_version": lock.lock_version,
"crate_fingerprint": lock.crate_fingerprint,
"engine_version": lock.engine_version,
"artifacts": [{"path": entry.path, "content_hash": entry.content_hash} for entry in lock.artifacts],
@@ -166,12 +200,43 @@ def load_lock(lock_path: Path) -> CodegenLock | None:
try:
content = load_text_from_path(lock_path)
data = load_toml_from_content(content)
+ _reject_unknown_lock_version(data=data, lock_path=lock_path)
lock = CodegenLock.model_validate(data)
validate_artifact_paths(entry.path for entry in lock.artifacts)
return lock
+ except CodegenLockError:
+ # The version verdict is already precise and actionable — re-wrapping it as "malformed" would
+ # bury the one thing the reader needs to know.
+ raise
except (CodegenError, TomlError, OSError, ValueError, TypeError) as exc:
# TomlError = malformed TOML; UnicodeDecodeError/ValueError = non-UTF-8 bytes or a pydantic
# ValidationError on a shape mismatch (UnicodeDecodeError is a ValueError subclass);
# OSError = the lock exists but cannot be read.
msg = f"Malformed or unsafe codegen lock at '{lock_path}': {exc}"
raise CodegenLockError(msg) from exc
+
+
+def _reject_unknown_lock_version(*, data: dict[str, Any], lock_path: Path) -> None:
+ """Refuse a lock whose format version this build cannot read, before its key set is validated.
+
+ The ordering is the whole point: `extra="forbid"` would otherwise reject a future lock as a shape
+ error over a key the writer was entitled to add, so the reader would report an opaque complaint
+ instead of naming the version and saying which side to upgrade.
+ """
+ raw_version = data.get("lock_version")
+ if raw_version is None:
+ # No key at all: written before the field existed, which is version 1 by definition. It still goes
+ # through the comparison below rather than returning here, or the day the constant moves every
+ # legacy lock would skip the gate and be validated against a schema it was never written for.
+ raw_version = 1
+ # `bool` is an `int` subclass, and `True == 1`, so a boolean would otherwise read as version 1.
+ is_version_number = isinstance(raw_version, int) and not isinstance(raw_version, bool)
+ if is_version_number and raw_version == CODEGEN_LOCK_VERSION:
+ return
+
+ if is_version_number and raw_version > CODEGEN_LOCK_VERSION:
+ reason = f"it declares lock_version {raw_version} — upgrade pipelex (or your SDK) to a build that reads it"
+ else:
+ reason = f"lock_version {raw_version!r} is not a known codegen lock format version"
+ msg = f"Unsupported codegen lock version at '{lock_path}': this build reads lock_version {CODEGEN_LOCK_VERSION}, but {reason}."
+ raise CodegenLockError(msg)
diff --git a/pipelex/codegen/stamp.py b/pipelex/codegen/stamp.py
index b865f9c00..f14f6fec7 100644
--- a/pipelex/codegen/stamp.py
+++ b/pipelex/codegen/stamp.py
@@ -16,7 +16,7 @@ body byte-exactly and recompute the hash.
import hashlib
import json
from pathlib import Path
-from typing import cast
+from typing import NoReturn, cast
from pydantic import BaseModel, ConfigDict
@@ -136,6 +136,12 @@ def parse_stamped(text: str, *, comment_prefix: str) -> ParsedStamp | None:
header_region = text[len(begin_line) + 1 : end_index]
body = text[end_index + len(end_line) + 2 :]
+ # Every line we ever write inside the fence carries the comment prefix, so anything else in there
+ # was injected by hand — and it would otherwise verify as pristine, since the hash covers only the
+ # body below the fence. An executable line hiding inside a "DO NOT EDIT" block is not a valid stamp.
+ if any(not line.startswith(comment_prefix) for line in header_region.splitlines()):
+ return None
+
fields = _parse_fields(header_region, comment_prefix=comment_prefix)
projection = fields.get("projection")
if projection is None:
@@ -169,7 +175,8 @@ def has_stamp(text: str, *, comment_prefix: str) -> bool:
def _parse_fields(header_region: str, *, comment_prefix: str) -> dict[str, str]:
fields: dict[str, str] = {}
for raw_line in header_region.splitlines():
- stripped = raw_line[len(comment_prefix) :].strip() if raw_line.startswith(comment_prefix) else raw_line.strip()
+ # `parse_stamped` has already rejected any line without the prefix, so stripping it is unconditional.
+ stripped = raw_line[len(comment_prefix) :].strip()
key, separator, value = stripped.partition(":")
if separator:
fields[key.strip()] = value.strip()
@@ -196,10 +203,18 @@ def _target_from_value(value: str) -> CodegenTarget | None:
return next((member for member in CodegenTarget if member == value), None)
+def _reject_json_constant(value: str) -> NoReturn:
+ """Refuse `NaN` / `Infinity` / `-Infinity`: Python's `json` accepts them, conformant parsers do not."""
+ msg = f"Non-standard JSON constant in stamp options: {value}"
+ raise ValueError(msg)
+
+
def _parse_options(options_raw: str) -> dict[str, str] | None:
try:
- loaded = json.loads(options_raw)
- except json.JSONDecodeError:
+ # The stamp header is a cross-language interchange format, so a stamp only Python can read is
+ # not a valid stamp: `parse_constant` turns those literals into the `ValueError` below.
+ loaded = json.loads(options_raw, parse_constant=_reject_json_constant)
+ except ValueError: # JSONDecodeError is a subclass, so this one clause covers malformed JSON too
return None
if not isinstance(loaded, dict):
return None
diff --git a/pipelex/tools/misc/file_utils.py b/pipelex/tools/misc/file_utils.py
index e96f377fb..1422f909c 100644
--- a/pipelex/tools/misc/file_utils.py
+++ b/pipelex/tools/misc/file_utils.py
@@ -58,11 +58,17 @@ def save_bytes_to_binary_file(byte_data: bytes, *, file_path: Path, create_direc
def save_text_to_path(text: str, *, path: Path, create_directory: bool = False):
- """Writes text content to a file at the specified path.
+ r"""Writes text content to a file at the specified path, as UTF-8 with LF line endings.
This function opens a file in write mode and writes the provided text to it.
If the file already exists, it will be overwritten.
+ Newline translation is disabled, so the bytes on disk are the string verbatim on every platform.
+ Without that, Python rewrites each ``\n`` as ``os.linesep``, and the same text saved on Windows and
+ on Linux produces different files: a hash taken over the in-memory string stops describing what is
+ on disk, and a mixed-platform team sees generated trees churn in version control with no change of
+ content. Every caller here writes a product text artifact meant to be platform-independent.
+
Args:
text (str): The text content to write to the file.
path (Path): The file path where the content should be saved.
@@ -77,7 +83,7 @@ def save_text_to_path(text: str, *, path: Path, create_directory: bool = False):
directory = path.parent
ensure_directory_exists(directory)
- path.write_text(text, encoding="utf-8")
+ path.write_text(text, encoding="utf-8", newline="\n")
def load_text_from_path(path: Path) -> str:
diff --git a/subject_grants.toml b/subject_grants.toml
index 094dabf53..b8f8d5f58 100644
--- a/subject_grants.toml
+++ b/subject_grants.toml
@@ -1220,6 +1220,10 @@ rationale = "Parser: the raw options string is the single operand."
param = "projection"
rationale = "Parser: the projection string is the single operand."
+["pipelex/codegen/stamp.py::_reject_json_constant"]
+param = "value"
+rationale = "Callback invoked positionally by json.loads parse_constant; the constant literal is the single operand."
+
["pipelex/codegen/stamp.py::_target_from_value"]
param = "value"
rationale = "Single-operand parse of the value."
diff --git a/tests/unit/pipelex/codegen/test_check.py b/tests/unit/pipelex/codegen/test_check.py
index b2e0966cb..01749ba8b 100644
--- a/tests/unit/pipelex/codegen/test_check.py
+++ b/tests/unit/pipelex/codegen/test_check.py
@@ -5,7 +5,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from pipelex.codegen.check import DriftCategory, run_codegen_check
-from pipelex.codegen.emission import write_stamped_projection
+from pipelex.codegen.emission import build_stamped_projection, write_stamped_projection
from pipelex.codegen.emitters.target import CodegenKind, CodegenTarget, EmittedFile
if TYPE_CHECKING:
@@ -108,3 +108,46 @@ class TestCheck:
(nested / "stray.py").write_text((tmp_path / "models.py").read_text(encoding="utf-8"), encoding="utf-8")
report = run_codegen_check(root=tmp_path)
assert any(d.path == "sub/deep/stray.py" and d.category == DriftCategory.ORPHAN for d in report.drifts)
+
+ def _restamp_without_relocking(self, root: Path, *, filename: str, content: str) -> None:
+ """Write a stamped, self-consistent artifact while leaving the lock alone — i.e. a `modified` drift."""
+ projection = build_stamped_projection(
+ [EmittedFile(filename=filename, content=content)],
+ crate_fingerprint="fp1",
+ engine_version="0.1.0",
+ kind=CodegenKind.TYPES,
+ target=CodegenTarget.PYTHON_PYDANTIC,
+ )
+ (root / filename).write_text(projection.files[0].content, encoding="utf-8")
+
+ def test_uncommented_line_injected_into_the_header_is_hand_edited_drift(self, tmp_path: Path) -> None:
+ self._generate(tmp_path)
+ target = tmp_path / "models.py"
+ # The injected line sits above the end marker, so the body below it — and its hash — are
+ # untouched: without the header gate the file verifies as pristine.
+ target.write_text(target.read_text(encoding="utf-8").replace("# options: {}", "sneaky = 1\n# options: {}"), encoding="utf-8")
+ report = run_codegen_check(root=tmp_path)
+ assert [(d.path, d.category) for d in report.drifts] == [("models.py", DriftCategory.HAND_EDITED)]
+
+ def test_drifts_are_ordered_locked_first_then_orphans_each_by_path(self, tmp_path: Path) -> None:
+ self._generate(tmp_path)
+ # Two locked drifts: a body that no longer matches the lock, and a deleted artifact.
+ self._restamp_without_relocking(tmp_path, filename="models.py", content="# h\nclass B:\n pass\n")
+ (tmp_path / "types.ts").unlink()
+ # Two orphans forming the adversarial pair: component-wise `sub/` precedes `sub.py`, string-wise
+ # `sub.py` precedes `sub/foo.py` because '.' sorts before '/'.
+ stamped = (tmp_path / "models.py").read_text(encoding="utf-8")
+ (tmp_path / "sub").mkdir()
+ (tmp_path / "sub" / "foo.py").write_text(stamped, encoding="utf-8")
+ (tmp_path / "sub.py").write_text(stamped, encoding="utf-8")
+
+ report = run_codegen_check(root=tmp_path)
+
+ # `types.ts` sorts after both orphans yet comes first: the locked loop is reported before the
+ # orphan loop, and each loop is ordered by the plain full-string path sort.
+ assert [(d.path, d.category) for d in report.drifts] == [
+ ("models.py", DriftCategory.MODIFIED),
+ ("types.ts", DriftCategory.MISSING),
+ ("sub.py", DriftCategory.ORPHAN),
+ ("sub/foo.py", DriftCategory.ORPHAN),
+ ]
diff --git a/tests/unit/pipelex/codegen/test_emission.py b/tests/unit/pipelex/codegen/test_emission.py
index beddb0283..f78488d2c 100644
--- a/tests/unit/pipelex/codegen/test_emission.py
+++ b/tests/unit/pipelex/codegen/test_emission.py
@@ -6,10 +6,11 @@ from typing import TYPE_CHECKING
import pytest
+from pipelex.codegen.check import DriftCategory, run_codegen_check
from pipelex.codegen.emission import WriteReport, build_stamped_projection, write_stamped_projection
from pipelex.codegen.emitters.target import CodegenKind, CodegenTarget, EmittedFile
from pipelex.codegen.exceptions import CodegenError
-from pipelex.codegen.lock import CODEGEN_LOCK_FILENAME, load_lock
+from pipelex.codegen.lock import CODEGEN_LOCK_FILENAME, CODEGEN_LOCK_VERSION, load_lock
from pipelex.codegen.stamp import has_stamp
if TYPE_CHECKING:
@@ -109,3 +110,72 @@ class TestEmission:
lock = load_lock(tmp_path / CODEGEN_LOCK_FILENAME)
assert lock is not None
assert lock.paths() == {"models.py", "types.ts"}
+
+ def test_regeneration_over_a_lock_written_before_the_version_field_relocks_it_once(self, tmp_path: Path) -> None:
+ """A tree locked by a pre-`lock_version` build keeps working: the old set is still read (so pruning
+ is not lost), the lock gains the version key on the next write, and the tree checks out current.
+ """
+ self._write(tmp_path)
+ lock_path = tmp_path / CODEGEN_LOCK_FILENAME
+ legacy_content = "".join(line for line in lock_path.read_text(encoding="utf-8").splitlines(keepends=True) if "lock_version" not in line)
+ lock_path.write_text(legacy_content, encoding="utf-8")
+
+ # Regenerate without types.ts: pruning proves the legacy artifact set was read, not discarded.
+ report = self._write(tmp_path, fingerprint="fp2", files=[_FILES[0]])
+
+ assert report.removed == ["types.ts"]
+ lock = load_lock(lock_path)
+ assert lock is not None
+ assert lock.lock_version == CODEGEN_LOCK_VERSION
+ assert lock.paths() == {"models.py"}
+ assert run_codegen_check(root=tmp_path).is_current
+
+ def test_regeneration_replaces_a_lock_written_by_a_newer_codegen(self, tmp_path: Path) -> None:
+ """Deliberate: an unreadable-version lock is replaceable prior state, exactly like a corrupt one.
+
+ Regeneration has already rewritten every artifact with *this* engine, so adopting this engine's
+ lock version is the coherent outcome; refusing would strand the developer on a purely derived
+ file. The one thing lost is pruning (the newer set cannot be trusted), and anything the newer
+ engine emitted that this one does not surfaces loudly as an orphan on the very next check.
+ """
+ self._write(tmp_path)
+ lock_path = tmp_path / CODEGEN_LOCK_FILENAME
+ lock_path.write_text(lock_path.read_text(encoding="utf-8").replace("lock_version = 1", "lock_version = 99"), encoding="utf-8")
+
+ report = self._write(tmp_path, fingerprint="fp2", files=[_FILES[0]])
+
+ assert report.removed == []
+ lock = load_lock(lock_path)
+ assert lock is not None
+ assert lock.lock_version == CODEGEN_LOCK_VERSION
+ assert lock.paths() == {"models.py"}
+ # types.ts survived unpruned and is now reported, rather than silently lingering.
+ assert [(drift.path, drift.category) for drift in run_codegen_check(root=tmp_path).drifts] == [("types.ts", DriftCategory.ORPHAN)]
+
+ def test_a_stamped_file_whose_header_was_tampered_is_an_orphan_the_regenerator_refuses_to_reclaim(self, tmp_path: Path) -> None:
+ """The one seam the strict header gate opens: the check's "remove or regenerate" advice is half true.
+
+ A stamped file the lock does not track is an orphan, and regenerating reclaims an ordinary one by
+ overwriting it. But a file whose header carries an injected uncommented line no longer *parses* as
+ stamped, so the writer cannot prove it owns it and refuses rather than clobbering something that may
+ hold real work — the same conservatism that protects a hand-authored module sharing the output
+ directory. `remove` is the half of the advice that always applies. Refusing is the deliberate
+ direction; this pins it so it stays a decision rather than an accident.
+ """
+ source = tmp_path / "source"
+ source.mkdir()
+ self._write(source)
+ stamped = (source / "models.py").read_text(encoding="utf-8")
+ begin_marker, below = stamped.split("\n", 1)
+ tampered = f'{begin_marker}\nraise SystemExit("injected")\n{below}'
+
+ root = tmp_path / "root"
+ root.mkdir()
+ self._write(root, files=[_FILES[1]])
+ (root / "models.py").write_text(tampered, encoding="utf-8")
+
+ assert [(drift.path, drift.category) for drift in run_codegen_check(root=root).drifts] == [("models.py", DriftCategory.ORPHAN)]
+
+ with pytest.raises(CodegenError, match="Refusing to overwrite unowned file"):
+ self._write(root)
+ assert (root / "models.py").read_text(encoding="utf-8") == tampered
diff --git a/tests/unit/pipelex/codegen/test_lock.py b/tests/unit/pipelex/codegen/test_lock.py
index 6468e8867..e6005aed7 100644
--- a/tests/unit/pipelex/codegen/test_lock.py
+++ b/tests/unit/pipelex/codegen/test_lock.py
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING
import pytest
from pipelex.codegen.exceptions import CodegenLockError
-from pipelex.codegen.lock import CODEGEN_LOCK_FILENAME, build_lock, encode_lock, load_lock
+from pipelex.codegen.lock import CODEGEN_LOCK_FILENAME, CODEGEN_LOCK_VERSION, build_lock, encode_lock, load_lock
if TYPE_CHECKING:
from pathlib import Path
@@ -15,6 +15,21 @@ if TYPE_CHECKING:
from pytest_mock import MockerFixture
+_LEGACY_LOCK_WITHOUT_VERSION = """\
+crate_fingerprint = "fp-abc"
+engine_version = "2.1.0"
+
+[[artifacts]]
+path = "models.py"
+content_hash = "h1"
+
+[[artifacts]]
+path = "types.ts"
+content_hash = "h2"
+"""
+"""A `codegen.lock` exactly as it was written before `lock_version` existed — verbatim, never regenerated."""
+
+
class TestLock:
def test_build_sorts_artifacts_by_path(self) -> None:
lock = build_lock(crate_fingerprint="fp", engine_version="1.0.0", artifacts={"z.ts": "hz", "a.py": "ha"})
@@ -54,3 +69,76 @@ class TestLock:
with pytest.raises(CodegenLockError, match="permission denied"):
load_lock(lock_path)
+
+ def test_encoded_lock_declares_its_format_version_first(self) -> None:
+ """The version must be the first key a reader meets, so a wrong-version lock is diagnosable at a glance."""
+ lock = build_lock(crate_fingerprint="fp", engine_version="1.0.0", artifacts={"a.py": "ha"})
+ encoded = encode_lock(lock)
+ assert f"lock_version = {CODEGEN_LOCK_VERSION}" in encoded
+ assert encoded.index("lock_version") < encoded.index("crate_fingerprint")
+
+ def test_round_trip_preserves_the_format_version(self, tmp_path: Path) -> None:
+ lock = build_lock(crate_fingerprint="fp", engine_version="1.0.0", artifacts={"a.py": "ha"})
+ lock_path = tmp_path / CODEGEN_LOCK_FILENAME
+ lock_path.write_text(encode_lock(lock), encoding="utf-8")
+ loaded = load_lock(lock_path)
+ assert loaded is not None
+ assert loaded.lock_version == CODEGEN_LOCK_VERSION
+
+ def test_a_lock_written_before_the_version_field_loads_as_version_one(self, tmp_path: Path) -> None:
+ """The no-migration guarantee: every lock already on disk predates the field and must still load."""
+ lock_path = tmp_path / CODEGEN_LOCK_FILENAME
+ lock_path.write_text(_LEGACY_LOCK_WITHOUT_VERSION, encoding="utf-8")
+
+ loaded = load_lock(lock_path)
+
+ assert loaded is not None
+ assert loaded.lock_version == 1
+ assert loaded.hash_by_path() == {"models.py": "h1", "types.ts": "h2"}
+
+ def test_a_newer_lock_version_is_refused_with_upgrade_guidance(self, tmp_path: Path) -> None:
+ lock_path = tmp_path / CODEGEN_LOCK_FILENAME
+ lock_path.write_text(f"lock_version = 2\n{_LEGACY_LOCK_WITHOUT_VERSION}", encoding="utf-8")
+
+ with pytest.raises(CodegenLockError, match="upgrade pipelex") as exc_info:
+ load_lock(lock_path)
+ assert "2" in str(exc_info.value)
+ # Reported on its own terms: a lock from a newer build is not malformed, and saying so would
+ # bury the one instruction the reader can act on.
+ assert "Malformed" not in str(exc_info.value)
+
+ def test_a_newer_lock_version_is_refused_even_when_it_carries_unknown_keys(self, tmp_path: Path) -> None:
+ """The whole point of versioning the format: the version verdict must outrank the strict key set.
+
+ `extra="forbid"` would otherwise reject a future lock as a shape error before its version was ever
+ read, so the reader would report an opaque pydantic complaint instead of "upgrade pipelex" — which
+ is precisely the unactionable no-verdict CI failure this field exists to prevent.
+ """
+ lock_path = tmp_path / CODEGEN_LOCK_FILENAME
+ lock_path.write_text(f'lock_version = 2\nfuture_key = "whatever"\n{_LEGACY_LOCK_WITHOUT_VERSION}', encoding="utf-8")
+
+ with pytest.raises(CodegenLockError, match="upgrade pipelex"):
+ load_lock(lock_path)
+
+ @pytest.mark.parametrize("raw_version", ["0", "-1", '"two"', "1.5", "true"])
+ def test_a_lock_version_that_is_not_a_known_version_is_refused(self, tmp_path: Path, raw_version: str) -> None:
+ lock_path = tmp_path / CODEGEN_LOCK_FILENAME
+ lock_path.write_text(f"lock_version = {raw_version}\n{_LEGACY_LOCK_WITHOUT_VERSION}", encoding="utf-8")
+
+ with pytest.raises(CodegenLockError):
+ load_lock(lock_path)
+
+ def test_a_legacy_unversioned_lock_is_refused_once_the_format_moves_on(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """An absent key means version 1, so it must face the same gate as a written one.
+
+ Returning early instead would let every legacy lock skip the gate the day `CODEGEN_LOCK_VERSION`
+ moves: it would be validated against the new schema and either silently accepted as current, or
+ reported as a generic malformed lock — the opaque no-verdict failure the version field exists to
+ prevent. Bumping the constant has to stay the one-line change the evolution policy promises.
+ """
+ mocker.patch("pipelex.codegen.lock.CODEGEN_LOCK_VERSION", 2)
+ lock_path = tmp_path / CODEGEN_LOCK_FILENAME
+ lock_path.write_text(_LEGACY_LOCK_WITHOUT_VERSION, encoding="utf-8")
+
+ with pytest.raises(CodegenLockError, match="lock_version"):
+ load_lock(lock_path)
diff --git a/tests/unit/pipelex/codegen/test_stamp.py b/tests/unit/pipelex/codegen/test_stamp.py
index 98f079571..041e75026 100644
--- a/tests/unit/pipelex/codegen/test_stamp.py
+++ b/tests/unit/pipelex/codegen/test_stamp.py
@@ -73,3 +73,40 @@ class TestStamp:
def test_unstampable_file_type_raises(self) -> None:
with pytest.raises(CodegenStampError):
comment_prefix_for("data.json")
+
+ def test_uncommented_line_inside_the_header_is_rejected(self) -> None:
+ # An executable line hiding between the markers leaves the body — and its hash — untouched,
+ # so only the header gate can catch it.
+ stamped = self._stamp("# a\nclass A:\n pass\n", comment_prefix="#")
+ injected = stamped.replace("# options: {}", 'raise RuntimeError("edited")\n# options: {}')
+ assert parse_stamped(injected, comment_prefix="#") is None
+
+ def test_blank_line_inside_the_header_is_rejected(self) -> None:
+ stamped = self._stamp("# a\nclass A:\n pass\n", comment_prefix="#")
+ injected = stamped.replace("# options: {}", "\n# options: {}")
+ assert parse_stamped(injected, comment_prefix="#") is None
+
+ def test_commented_unknown_field_still_parses(self) -> None:
+ # Additive tolerance, pinned: a stamp gaining a field stays readable by today's parser, which
+ # is why the stamp header carries no version of its own. Over-tightening the gate would break it.
+ stamped = self._stamp("# a\nclass A:\n pass\n", comment_prefix="#")
+ extended = stamped.replace("# options: {}", "# future_field: value\n# options: {}")
+ parsed = parse_stamped(extended, comment_prefix="#")
+ assert parsed is not None
+ assert parsed.stamp.crate_fingerprint == "fp-123"
+
+ @pytest.mark.parametrize("options_value", ['{"x": NaN}', '{"x": Infinity}', '{"x": -Infinity}', "Infinity"])
+ def test_non_standard_json_constants_in_options_are_rejected(self, options_value: str) -> None:
+ # Python's `json` accepts these; no conformant JSON parser does. The stamp header is a
+ # cross-language interchange format, so a stamp only Python can read is not a valid stamp.
+ stamped = self._stamp("# a\nclass A:\n pass\n", comment_prefix="#")
+ tampered = stamped.replace("# options: {}", f"# options: {options_value}")
+ assert parse_stamped(tampered, comment_prefix="#") is None
+
+ def test_standard_options_json_still_parses(self) -> None:
+ empty = parse_stamped(self._stamp("# a\n", comment_prefix="#"), comment_prefix="#")
+ assert empty is not None
+ assert empty.stamp.options == {}
+ populated = parse_stamped(self._stamp("# a\n", comment_prefix="#", options={"explicit": "true", "flavor": "strict"}), comment_prefix="#")
+ assert populated is not None
+ assert populated.stamp.options == {"explicit": "true", "flavor": "strict"}
diff --git a/tests/unit/pipelex/tools/misc/test_save_text_to_path.py b/tests/unit/pipelex/tools/misc/test_save_text_to_path.py
new file mode 100644
index 000000000..0564b0862
--- /dev/null
+++ b/tests/unit/pipelex/tools/misc/test_save_text_to_path.py
@@ -0,0 +1,36 @@
+"""`save_text_to_path` writes LF on every platform, so generated artifacts are byte-identical everywhere."""
+
+from pathlib import Path
+
+from pipelex.tools.misc.file_utils import load_text_from_path, save_text_to_path
+
+
+class TestSaveTextToPath:
+ def test_newlines_are_written_as_lf(self, tmp_path: Path) -> None:
+ r"""No `\r` reaches the disk, whatever `os.linesep` says.
+
+ This is a tripwire, not a discriminating test: on POSIX `os.linesep` is already `\n`, so it
+ passes with or without the fix. It goes red the day a Windows runner appears, or the day the
+ explicit `newline` argument is dropped — which is exactly when the guarantee would break.
+ """
+ target = tmp_path / "artifact.py"
+ save_text_to_path("line one\nline two\n", path=target)
+ assert b"\r" not in target.read_bytes()
+ assert target.read_bytes() == b"line one\nline two\n"
+
+ def test_carriage_returns_in_the_text_survive_verbatim(self, tmp_path: Path) -> None:
+ r"""Text that deliberately carries `\r\n` round-trips byte-for-byte, never doubled to `\r\r\n`.
+
+ With the default translating write, a `\r\n` in the string becomes `\r\r\n` on Windows because
+ only the `\n` is translated. Pinning `newline="\n"` disables translation entirely, so the text is
+ the file.
+ """
+ target = tmp_path / "crlf.txt"
+ save_text_to_path("first\r\nsecond\r\n", path=target)
+ assert target.read_bytes() == b"first\r\nsecond\r\n"
+
+ def test_round_trip_through_the_matching_reader(self, tmp_path: Path) -> None:
+ """What `save_text_to_path` writes, `load_text_from_path` reads back unchanged."""
+ target = tmp_path / "nested" / "artifact.ts"
+ save_text_to_path("export const a = 1;\n", path=target, create_directory=True)
+ assert load_text_from_path(target) == "export const a = 1;\n"
diff --git a/wip/codegen/sdk-followups.md b/wip/codegen/sdk-followups.md
new file mode 100644
index 000000000..14c26db66
--- /dev/null
+++ b/wip/codegen/sdk-followups.md
@@ -0,0 +1,224 @@
+# Codegen follow-ups from the `@pipelex/sdk` `runCodegenCheck` port (PR #31 review triage)
+
+> **ARCHIVED from the repo-root `TODOS.md` on 2026-08-19 — the code work is complete, the release gate is not.** Phases 1 through 5 shipped on `feature/Codegen-followups` (PR #1127): U1–U5 are implemented, tested, documented and swept. What remains open is not code but the `@pipelex/sdk` release gate — until an SDK that tolerates `lock_version` is *published*, the very release that fixes U3 triggers the failure U3 describes in every pinned consumer's CI, because their `rejectUnknownKeys` hard-throws on the new key. Pick that up from the "Cross-repo" and checkpoint sections below rather than re-deriving it. Moved off the repo root because the root tracker belongs to whatever work is currently in flight, and this work is waiting on a publish rather than on a keyboard.
+>
+> **Paths below are relative to the repository root, not to this file's own directory** — they were written while this document sat at the root and are deliberately left as they were.
+
+Source: `../pipelex-sdk-js/wip/pr-31-review-notes.md` → "Upstream follow-ups". The SDK team built a second implementation of the offline codegen check and surfaced five upstream items (U1–U5) plus one spec item (S1). All five upstream claims were **verified against this repo's code on `feature/Codegen-followups` (base `d28e703e3`, v0.46.4) and confirmed accurate** — file/line references, reasoning, and proposed fixes all check out. Every U-item is work in **this repo**; S1 is not (see the cross-repo section at the end).
+
+Triage verdict per item:
+
+| Item | Verdict | Owner | Action |
+|---|---|---|---|
+| U1 — stamp parser accepts uncommented header lines | **Confirmed** | this repo | fix (Phase 1) |
+| U5 — `_parse_options` accepts `NaN`/`Infinity` | **Confirmed** | this repo | fix (Phase 1) |
+| U2 — the two check loops sort by different rules | **Confirmed** | this repo | fix (Phase 2) |
+| U4 — Windows artifacts written CRLF while hashes are over LF | **Confirmed** (by code reading; not reproduced on a Windows host — we have no Windows CI) | this repo | fix (Phase 3) |
+| U3 — any new `codegen.lock` key is a hard break for every pinned client | **Confirmed** | this repo (format owner) | fix: add `lock_version` (Phase 4) |
+| S1 — spec under-specifies what a second implementation needs | **Confirmed** (demonstrated by the SDK port) | workspace `docs/specs/` + `conformance/` — **not this repo** | recorded below, not planned here |
+
+Cross-repo sequencing constraint, stated once: `src/codegen-check.ts` in `pipelex-sdk-js` is a byte-for-byte verdict mirror of `pipelex/codegen/`. Parser **tightenings** (U1, U5) land here first, the SDK follows — the SDK must never be stricter than the CLI it mirrors (their review already defers to us on exactly this ground). The lock **format change** (U3) is the reverse: the SDK's reader must tolerate the new key *before* a pipelex release starts writing it, because `rejectUnknownKeys` turns an unknown lock key into a hard no-verdict throw in every consumer's CI. U2 and U4 need no coordination (U2 converges toward the SDK's existing full-string sort; U4 is invisible to the SDK, which already normalizes newlines).
+
+---
+
+## Cold start — read this first
+
+**Status: Phases 1–5 done and committed (Checkpoint 4 reached). All five upstream items are implemented, tested, documented and swept. What is left is not code: the SDK follow-up must be triaged into `pipelex-sdk-js` and released before this branch's release, and two PR #31 threads want a reply. See the end of Phase 5.**
+
+**Where the work is.** Branch `feature/Codegen-followups` in `pipelex/`, cut from `d28e703e3` (v0.46.4). Phase 1 is one commit, Phases 2–3 a second, Phase 4 a third, Phase 5 a fourth. Nothing is pushed. When this eventually becomes a PR it targets `dev`, never `main`.
+
+**Verify the tree is green before touching anything** (about a minute):
+
+```bash
+git add -A && make agent-check
+.venv/bin/pytest -n auto -m "(dry_runnable or not (inference or llm or img_gen or extract or search)) and not pipelex_api" -o log_level=WARNING --tb=short -q tests/unit/pipelex/codegen/ tests/integration/pipelex/codegen/
+```
+
+**What Phases 1–3 already changed — do not redo any of it:**
+
+| File | What is in it now |
+|---|---|
+| `pipelex/codegen/stamp.py` | the comment-prefix gate in `parse_stamped`, the simplified `_parse_fields`, and `_reject_json_constant` wired into `_parse_options` through `parse_constant` |
+| `tests/unit/pipelex/codegen/test_stamp.py` | new tests at the end of `TestStamp` (one of them parametrized over the non-standard JSON constants) |
+| `tests/unit/pipelex/codegen/test_check.py` | `test_uncommented_line_injected_into_the_header_is_hand_edited_drift` at the end of `TestCheck` |
+| `subject_grants.toml` | the grant for `pipelex/codegen/stamp.py::_reject_json_constant` |
+| `docs/under-the-hood/codegen-projections.md` | two paragraphs under § Stamps — the header-strictness rules and the forward tolerance |
+| `CHANGELOG.md` | one `## [Unreleased]` → `### Fixed` entry — **extend it, do not add a second bullet per phase** |
+| `pipelex/codegen/check.py` | `_find_orphans` returns `sorted(orphans, key=…path)`, and `run_codegen_check`'s docstring states the ordering contract |
+| `pipelex/tools/misc/file_utils.py` | `save_text_to_path` writes `newline="\n"`, with the rationale in its (now raw) docstring |
+| `tests/unit/pipelex/tools/misc/test_save_text_to_path.py` | new module — the LF tripwire, the CRLF-verbatim case, and a reader round-trip |
+| `pipelex/codegen/lock.py` | `CODEGEN_LOCK_VERSION`, the `lock_version` field, `_reject_unknown_lock_version` called **before** `model_validate`, the `except CodegenLockError: raise` passthrough, and the evolution policy in the module docstring |
+| `tests/unit/pipelex/codegen/test_lock.py` | the `_LEGACY_LOCK_WITHOUT_VERSION` fixture and the version tests at the end of `TestLock` |
+| `tests/unit/pipelex/codegen/test_emission.py` | the two regeneration tests (legacy lock relocked; newer-version lock replaced) |
+| `.badges/tests.json` | refreshed to the new collected-test count (repeat after every test-adding phase) |
+
+**Five traps this repo sets, every one of them hit during Phase 1:**
+
+1. **`drift-check` reads the git index, not the working tree.** It runs inside `make agent-check`, so `git add -A` before checking or it reports a false green on unstaged work.
+2. **`make agent-check` runs the keyword-only auto-fixer**, which silently makes an ungranted positional subject keyword-only. Any new function whose first parameter must stay positional — a callback a framework invokes, which is exactly what `_reject_json_constant` is — needs `make subject-grant FUNC="<path>::<qualname>" RATIONALE="…"` recorded **before** the first check run. Put no backticks in the rationale: `make` executes them and they vanish.
+3. **`make check-test-badge` is in no local aggregate.** Any commit that adds tests passes both local gates and fails CI until `.badges/tests.json` is set to what `make test-count` prints.
+4. **Write the tests red first and watch them fail against current code.** Phase 2's ordering test proves nothing unless its fixture holds the adversarial `models/` -beside- `models.py` pair; mutation-test it by reverting the sort.
+5. **Each phase carries its own doc edit and extends the same `## [Unreleased]` entry.** Phase 5 is the sweep that verifies nothing was missed — not the place to write all of it for the first time.
+6. **Ruff `D301` rejects a docstring containing a backslash unless it is raw.** Phase 3's newline docstrings tripped it; prefix them `r"""` and write single backslashes rather than doubling them.
+
+**Pointers below name symbols rather than line numbers, which drift with every edit to these files** (the numbers this document originally carried were all taken against the branch base `d28e703e3`, and this work's own diff moved every one of them): `check.py` → the `sorted(lock.hash_by_path().items())` loop in `_check_locked_artifacts`; `file_utils.py` → the `write_text(..., newline="\n")` call inside `save_text_to_path`; `lock.py` → the two `extra="forbid"` model configs (`CodegenLockEntry` and `CodegenLock`) and the `encode_lock` / `load_lock` pair; `stamp.py` → `_parse_fields` and `_parse_options`. The `stamp.py` pair is cited inside Phase 1 as the code **before** the fix — kept for the record, since that work is done.
+
+---
+
+## Phase 1 — Stamp parser tightenings (U1 + U5) — **DONE**
+
+Both are strictness fixes in `pipelex/codegen/stamp.py`, both turn a malformed stamp into `parse_stamped(...) -> None`, which `_check_present_artifact` already reports as a `hand-edited` drift ("Stamp header is missing or unparseable"). No new error class, so no `gei`/`gep` run needed.
+
+### U1 — reject uncommented lines inside the stamp header
+
+Confirmed: `_parse_fields` (`pipelex/codegen/stamp.py`) has an `else raw_line.strip()` fallback that silently swallows any header line not starting with the comment prefix, and nothing in `parse_stamped` or `check.py` compensates. An artifact with `throw new Error("edited");` injected between the stamp markers parses fine and reports CURRENT, because the body is sliced below the end marker so its hash is untouched. The SDK notes are also right that this is *not* a security boundary (no signature/MAC anywhere; the defence is diff review) — this is a correctness tidy-up, but a cheap and worthwhile one: an executable line hiding inside a `DO NOT EDIT` block should not verify as pristine.
+
+Implementation, in `parse_stamped` immediately after the `header_region` slice:
+
+```python
+if any(not line.startswith(comment_prefix) for line in header_region.splitlines()):
+ return None
+```
+
+Then simplify `_parse_fields`: the `else raw_line.strip()` fallback is dead once the gate exists — drop it, so the function reads `stripped = raw_line[len(comment_prefix):].strip()` unconditionally.
+
+Verified safe on shape: `apply_stamp` emits `[begin] + [f"{prefix} {key}: {value}" ...] + [end]` — every header line carries the prefix, no blank lines. So the gate rejects no stamp we ever wrote. An empty `header_region` passes vacuously and then fails on the missing `projection` field, as today.
+
+Tests (`tests/unit/pipelex/codegen/test_stamp.py`, plus one check-level test in `test_check.py`) — write them red first against current code where possible (TDD):
+
+- An uncommented line injected between the markers → `parse_stamped` returns `None`. (Red today.)
+- A blank line injected inside the header → `None`. (Red today.)
+- A *commented* unknown field line (`# future_field: value`) still parses — pins the additive tolerance of the stamp header in the forward direction, so U3's evolution policy ("stamp additions never need a version") stays true and cannot be silently reversed by a later over-tightening.
+- Check-level: a locked tree whose artifact carries an injected uncommented header line → exactly one drift, category `hand-edited`. (Red today — this is the SDK's reproduction, ported.)
+
+### U5 — reject `NaN` / `Infinity` in the stamp's `options` JSON
+
+Confirmed: `_parse_options` (`pipelex/codegen/stamp.py`) uses a bare `json.loads`, which accepts Python's non-standard `NaN` / `Infinity` / `-Infinity` literals. No conformant JSON parser (JavaScript included) does, so a stamp carrying one is CURRENT to us and `hand-edited` to the SDK — the one differential where the SDK is the stricter side. Unreachable with today's emitter (`options` is `dict[str, str]` and `json.dumps` never emits those literals for string values), but the stamp header is a cross-language interchange format and should not be able to contain something only Python can read. Costs one argument.
+
+Implementation:
+
+```python
+def _reject_json_constant(value: str) -> NoReturn:
+ msg = f"Non-standard JSON constant in stamp options: {value}"
+ raise ValueError(msg)
+```
+
+and in `_parse_options`, `json.loads(options_raw, parse_constant=_reject_json_constant)` with the existing `except` widened from `json.JSONDecodeError` to `ValueError` (its superclass, so the one clause catches both).
+
+Tests: `options: {"x": NaN}` and `options: Infinity` in a stamp → `parse_stamped` returns `None` (red today); a normal `options: {}` and a populated string-valued object still parse (green guard).
+
+**Checkpoint 1 — REACHED (2026-08-19), committed on `feature/Codegen-followups`.** Both tightenings landed with red→green tests. `make agent-check` clean; `tests/unit/pipelex/codegen/`, `tests/integration/pipelex/codegen/` and the whole CLI unit/integration/e2e set green. Full `make agent-test` stays deferred to Checkpoint 2, as planned.
+
+Three things the plan above did not anticipate, all now folded into the cold-start section as reusable traps:
+
+- `_reject_json_constant` is a callback `json.loads` invokes positionally, so it needed a subject grant (trap 2).
+- Phase 1 carried its own doc edit and its own `## [Unreleased]` changelog entry — later phases extend that entry rather than adding one each (trap 5).
+- `.badges/tests.json` needed refreshing for the added tests (trap 3).
+
+One behavior verified and deliberately left alone: `_preflight_destinations` in `emission.py` also calls `parse_stamped`, so an **untracked** file whose header now fails the gate is treated as unowned and refuses to be overwritten. That is the conservative direction, and the same behavior class already existed for other unparseable stamps, so it is not a regression — but it does mean a tampered orphan is reported by the check as "remove or regenerate" while regeneration itself declines to clobber it. Noted here in case Phase 5's sweep wants to say something about it. **It did** — Phase 5 pinned it with a test and named the seam in the docs and the changelog; see there.
+
+Phases 2–4 remain independent of Phase 1 and of each other.
+
+---
+
+## Phase 2 — Unify drift ordering across the check's two loops (U2) — **DONE**
+
+Confirmed: `_check_locked_artifacts` (`pipelex/codegen/check.py`) iterates `sorted(lock.hash_by_path().items())` — a plain `str` sort over the whole relative path — while `_find_orphans` iterates `_iter_stampable_files`, a pre-order DFS doing `sorted(directory.iterdir())` per level, which is a path-*component* sort. For a tree holding `models/` beside `models.py`, the two halves of one report order paths by different rules (`models/foo.py` before `models.py` component-wise; the reverse string-wise). The reference is internally inconsistent, and the SDK cannot mirror both rules with one comparator.
+
+Decision (ours to make, as the reference): **unify on the plain full-string sort**, the rule the locked-artifact loop already uses. Rationale: it matches `build_lock`'s "artifacts sorted by path" ordering in the lock file itself, it is the rule the SDK already implements for both of its loops (so upstream converges toward the mirror instead of forcing a component-wise comparator on every future client), and it is the cheaper spec sentence for S1 to eventually pin.
+
+Implementation: keep `_iter_stampable_files` exactly as is (its DFS order is a *traversal* concern — deterministic pruning and filesystem walking — not a *report* concern); in `_find_orphans`, return `sorted(orphans, key=lambda drift: drift.path)` instead of the raw accumulation order. One line. Then state the now-real guarantee where the SDK had to reverse-engineer it: extend the `run_codegen_check` docstring with the ordering contract — locked-artifact drifts first in path order, then orphans in path order, at most one drift per locked path with `hand-edited` outranking `modified`. (That last property is already structural in `_check_present_artifact`; writing it down is S1 support, zero behavior change.)
+
+Tests (`tests/unit/pipelex/codegen/test_check.py`): `test_drifts_are_ordered_locked_first_then_orphans_each_by_path` asserts the full `[(path, category), ...]` sequence.
+
+⚠ **The fixture this plan originally proposed could not go red**, and the correction is worth keeping. Orphans at `models/foo.py` and `a.py` sort identically under both rules (`a.py` precedes `models/foo.py` either way), so that tree proves nothing. The two rules only diverge on a **directory sitting beside a file whose name extends it**: the DFS descends into `sub/` before reaching `sub.py` because `"sub" < "sub.py"`, while a full-string sort puts `sub.py` first because `.` (0x2E) precedes `/` (0x2F). The adversarial pair must therefore be **two orphans**, `sub.py` and `sub/foo.py` — the locked `models.py` cannot play that role, since a locked path is never an orphan.
+
+The fixture as landed: locked `models.py` restamped-but-not-relocked (a `modified` drift — `_restamp_without_relocking`, a new helper, builds a self-consistent stamp via `build_stamped_projection` and writes the artifact only), locked `types.ts` deleted (`missing`), and the two orphans. `types.ts` sorts *after* both orphans yet is asserted first, so the test pins the loop boundary as well as the sort. Verified red before the fix, failing at exactly index 2 (`sub/foo.py` where `sub.py` belonged) with indices 0–1 already passing.
+
+Worth noting for Phase 5: `modified` had no test coverage at all before this — every prior drift test exercised `missing`, `hand-edited` or `orphan`.
+
+---
+
+## Phase 3 — Emit LF artifacts on every platform (U4) — **DONE**
+
+Confirmed: `save_text_to_path` (`pipelex/tools/misc/file_utils.py`) is `path.write_text(text, encoding="utf-8")`; with the default `newline=None`, Python translates `\n` to `os.linesep`, so on Windows every emitted artifact is CRLF on disk while `compute_content_hash` hashed the in-memory LF string. The *verdict* survives (reads come back through universal-newline translation, and `_write_if_changed` compares translated text on both sides), but `apply_stamp`'s own docstring claim — regeneration "writes byte-identical output" — holds only per-platform: a mixed Windows/Linux team sees the generated tree churn in git when nothing changed. Reasoned from documented `write_text` behavior, not reproduced (macOS `os.linesep` is `\n` and we have no Windows CI); the reasoning is airtight enough to act on.
+
+Decision: fix it **globally in `save_text_to_path`** — `path.write_text(text, encoding="utf-8", newline="\n")` — rather than only at codegen's write site. Every caller (JSON via `json_utils`, the `build` command outputs, codegen inputs templates, codegen artifacts + lock) writes product text artifacts meant to be platform-independent; none wants `os.linesep`. One site, one behavior, no divergent write paths to remember. Update the function's docstring to state the LF guarantee.
+
+Tests: new module `tests/unit/pipelex/tools/misc/test_save_text_to_path.py` (there were none for this function). Three cases — no `\r` reaches the disk; text that deliberately carries `\r\n` round-trips byte-for-byte rather than being doubled to `\r\r\n` (the failure mode of the *default* write, which translates only the `\n`); and a round-trip through `load_text_from_path`.
+
+Stated honestly in the docstrings: **these are tripwires, not discriminating tests.** On POSIX `os.linesep` is already `\n` and CPython's C `TextIOWrapper` has no write-translation path at all, so they pass with or without the fix and cannot be mutation-tested here. They go red the day a Windows runner appears or the `newline` argument is dropped. Swept for platform-newline assumptions elsewhere: no `os.linesep` anywhere in `pipelex/` or `tests/`, and no existing test asserts platform newlines.
+
+**Checkpoint 2 — REACHED (2026-08-19), committed on `feature/Codegen-followups`.** Both phases landed with the ordering test written red first. `make agent-check` clean, `make check-test-badge` refreshed to the new count, and the full `make agent-test` green.
+
+Two things found along the way that the plan did not anticipate:
+
+- **The proposed Phase 2 fixture was not discriminating** — see the ⚠ note in Phase 2 above. Trap 4 in the cold-start section was right that the fixture is where this test lives or dies; it just named the wrong pair.
+- **A sibling of U4 exists outside codegen and is deliberately NOT fixed here** (a pre-existing bug, reported to Louis rather than folded into this diff). `fix_all_violations` in `pipelex/cli/dev_cli/commands/keyword_only_guard.py` reads each source file with `path.read_text(encoding="utf-8")` and writes it back with `path.write_text(...)`, neither passing `newline`. The read translates `\r\n` to `\n`, so the CRLF-preservation logic in `fix_source` — which `test_crlf_line_endings_preserved_and_fixed` pins byte-for-byte, and whose docstring says a regression "would corrupt every Windows-authored file the fixer touches" — is unreachable through the only caller that touches the filesystem: a CRLF file is silently normalized to LF on POSIX, and the write would emit `\r\r\n` on Windows. It is left alone because it is dev-only tooling outside this plan's scope and the fix carries a real design question (genuinely preserve CRLF by reading and writing with `newline=""`, or delete the now-pointless CRLF branch and declare the fixer LF-only). Decide that on its own terms, not inside a codegen change.
+
+---
+
+## Phase 4 — Version the lock format (U3) — the one with real blast radius — **DONE**
+
+Confirmed: `CodegenLock` and `CodegenLockEntry` both carry `extra="forbid"` (`pipelex/codegen/lock.py`), the SDK mirrors that deliberately, and the format has no version field and no written evolution policy. Consequence, correctly identified by the SDK notes: the day we add *any* key to `codegen.lock`, every consumer pinned to an older `@pipelex/sdk` (and every older `pipelex` reading a newer lock) gets a hard `CodegenLockError` no-verdict in CI — not a drift, not a warning. Nothing today makes an additive change safe, and nobody has decided whether that is policy or accident.
+
+Decision: **add `lock_version` now**, while the only two readers are ours and the cost is zero, rather than declaring the format closed. A closed format would make every future addition a coordinated three-repo breaking release *discovered at release time*; a version field makes it a planned one with an actionable error message.
+
+Implementation, all in `pipelex/codegen/lock.py`:
+
+- Module constant `CODEGEN_LOCK_VERSION = 1`.
+- `CodegenLock` gains `lock_version: int = 1`. The default is the compatibility hinge: every existing lock on disk (no key) validates as version 1, so no migration of existing trees is needed. `extra="forbid"` stays — strictness *within* a known version remains correct.
+- `encode_lock` writes `lock_version = 1` as the first key of the payload, before `crate_fingerprint`.
+- `load_lock`, after `model_validate`: if `lock.lock_version != CODEGEN_LOCK_VERSION`, raise `CodegenLockError` with an actionable message distinguishing the direction — a *greater* version means "this lock was written by a newer Pipelex codegen; upgrade pipelex (or the SDK) to read it", anything else is malformed. Reuse `CodegenLockError`; no new error class.
+- Write the evolution policy down as the module docstring's contract paragraph: any change to the lock's key set or semantics bumps `lock_version`; readers reject versions they do not know, loudly and with upgrade guidance; the **stamp header** deliberately needs no version because unknown *commented* `key: value` lines are ignored by every reader (the tolerance Phase 1 pins by test).
+
+Sequencing (this is the part that must not be improvised at release time):
+
+1. Land here on `dev`, unreleased. The lock bytes change (every regeneration rewrites the lock once — expected, `_write_if_changed` sees the new key).
+2. File the SDK follow-up: accept `lock_version`, mirror the reject-unknown-version rule and its message verbatim, refresh the vendored fixtures. **The SDK release must be available before the pipelex release that writes the key** — their `rejectUnknownKeys` hard-throws otherwise, which is precisely the failure mode U3 exists to eliminate. Note it in the release-notes draft for whichever pipelex version first ships this.
+3. The spec's "Lock format" section (workspace `docs/specs/pipelex-codegen.md`) gains the field and the evolution policy — workspace-repo change, listed in the cross-repo section below.
+
+Tests (`tests/unit/pipelex/codegen/test_lock.py`, plus emission round-trip in `test_emission.py`):
+
+- `encode_lock` output contains `lock_version = 1` and `load_lock` round-trips it.
+- A lock **without** the key (yesterday's format, verbatim TOML fixture) loads as version 1 — the no-migration guarantee, pinned.
+- A lock with `lock_version = 2` → `CodegenLockError` whose message names the found version and says to upgrade. Same for a non-integer value (pydantic shape error path, already wrapped).
+- `write_stamped_projection` over a tree locked by the old format rewrites the lock once and reports current on the next check.
+
+**Checkpoint 3 — REACHED (2026-08-19), committed on `feature/Codegen-followups`.** The version field landed with its tests written red first, both load-bearing ones mutation-tested. `make agent-check` clean, badge refreshed, full `make agent-test` green.
+
+⚠ **Still open, and it gates the release:** the SDK follow-up is **filed** at the workspace inbox — `../wip/inbox/2026-08-19-pipelex-sdk-js-codegen-lock-version.md` (it carries the four rules to mirror, the ordering trap, and the fixture refresh). It is *not yet triaged into `pipelex-sdk-js`*, and no SDK PR exists. Record here, before releasing: the `pipelex-sdk-js` issue/PR link and its release status. Until an `@pipelex/sdk` that tolerates `lock_version` is published, a pipelex release carrying this change hard-breaks every consumer pinned to the current SDK — the exact failure U3 exists to eliminate.
+
+**Two corrections to the plan above, both found while implementing:**
+
+- **The version gate must run BEFORE `model_validate`, not after it.** The plan put the check after validation, which is unreachable for the case that matters: `extra="forbid"` rejects a v2 lock that *adds a key* as a pydantic shape error before the version is ever read, so the reader emits an opaque "Extra inputs are not permitted" complaint instead of "upgrade pipelex" — precisely the unactionable no-verdict U3 exists to eliminate. `load_lock` now reads `lock_version` out of the parsed TOML first. Pinned by `test_a_newer_lock_version_is_refused_even_when_it_carries_unknown_keys`, and mutation-tested by moving the call back after `model_validate` (goes red with the pydantic message). The `except CodegenLockError: raise` passthrough (mirroring `run_codegen_check`) keeps the verdict from being re-wrapped as "Malformed or unsafe" — also mutation-tested.
+- **The plan's "reuse `CodegenLockError`, no new error class" has a consequence worth stating explicitly, and it was a real decision.** `_previous_tracked_paths` in `emission.py` discriminates on `exc.__cause__`, so a bare `raise` makes an unreadable-version lock **replaceable prior state during regeneration**, exactly like a corrupt one — `codegen types` overwrites it rather than failing. Deliberate: the run has already rewritten every artifact with this engine, the lock is purely derived, and refusing would strand a developer on a generated file. The cost is that pruning is skipped, so anything the newer engine emitted lingers — but it surfaces loudly as an orphan on the very next check rather than silently. Pinned by `test_regeneration_replaces_a_lock_written_by_a_newer_codegen`. The alternative (a `CodegenLockVersionError` subclass that propagates through regeneration) was rejected as buying little for a derived artifact, at the cost of a new error class plus its `gei`/`gep` runs.
+
+One test in the plan turned out to be untestable and is documented rather than written: `build_lock` passes `lock_version=CODEGEN_LOCK_VERSION` while the field default is the literal `1`. The split is what makes a future bump a one-line change (bump the constant; the "absent key means version 1" statement stays true forever), but with only one version in existence the two values coincide, so no test can distinguish them. The reasoning is in the field's docstring.
+
+---
+
+## Phase 5 — Docs, changelog, and closure — **DONE**
+
+The sweep found one real gap and one loose end, which is what a sweep is for; the rest of the pass confirmed Phases 1–4 had each carried their own doc and changelog edit as intended.
+
+**The gap: Phase 3's LF guarantee never reached `docs/`.** It was written into `save_text_to_path`'s docstring and nowhere else — a grep for line-ending vocabulary across `docs/` returned only unrelated hits in `migration-ledger.md` and `plxt.md`. That mattered because the codegen page is where byte-identical regeneration is *promised* to a reader, and the promise was platform-conditional without saying so. § Idempotent emission now states that every artifact is written LF on every platform, and why: the same projection emitted on Windows and on Linux would otherwise land as different bytes while both recorded the same content hash, so a mixed-platform team would watch the generated tree churn with no change of content.
+
+**The loose end: the `_preflight_destinations` seam Phase 1 flagged for this sweep, now pinned rather than merely noted.** Verified by running it, not by reading it: a stamped file whose header carries an injected uncommented line has `has_stamp() == True` but `parse_stamped() == None`, so the check reports it as an **orphan** advising "remove or regenerate" while `write_stamped_projection` raises `CodegenError: Refusing to overwrite unowned file` and leaves it byte-for-byte intact. Half the advice is wrong. This is a behavior U1 *changed* — before the strict gate such a file parsed, so regeneration silently overwrote it — and nothing guarded it, so `test_a_stamped_file_whose_header_was_tampered_is_an_orphan_the_regenerator_refuses_to_reclaim` in `test_emission.py` now does. It is discriminating: mutating the U1 gate to `if False` leaves the orphan assertion green and turns the refusal assertion red (`DID NOT RAISE`), so the test fails for the reason it exists. The refusal itself is left alone — declining to clobber a file we cannot prove we own is the same conservatism that protects a hand-authored module sharing the output directory — but § Idempotent emission now names the seam, and the changelog's stamp bullet tells a user hitting it to remove the file before regenerating.
+
+Everything else was confirmed already in place: § Stamps carries the header-strictness rules and the forward tolerance, § Offline check carries the drift-ordering contract, § Lock carries `lock_version` and the evolution policy, and `## [Unreleased]` carries one `### Added` entry for the lock version plus three `### Fixed` entries for the stamp tightenings, the unified ordering and the LF writes. Swept the codegen write path too: `emission.py` reaches the disk only through `save_text_to_path`, so the LF fix covers the whole trust chain with no bypass.
+
+`make agent-check` clean, `.badges/tests.json` refreshed to the count the added test produced, and the full `make agent-test` green.
+
+**Checkpoint 4 — REACHED (2026-08-19), committed on `feature/Codegen-followups`.** The code work for U1–U5 is complete. Two items remain, neither of them code, and the first one gates the release:
+
+1. ⚠ **The SDK follow-up is delivered; the release gate is now an SDK *release*, not a filing.** Triaged out of the workspace inbox on 2026-08-19 and delivered into `pipelex-sdk-js` as `wip/upstream-codegen-followups-mirror.md`, committed on `feature/Codegen-follow-ups` (the PR #31 branch) as "docs: record what the upstream codegen landing requires of this SDK". It carries the four rules to mirror, the read-the-version-before-the-key-set ordering trap, the fixture refresh, and a direction table for all five items — the SDK's own `pr-31-review-notes.md` gained per-item status lines in the same commit, since its claim that nothing had been filed upstream was no longer true. **What still blocks a pipelex release is unchanged in substance:** until an `@pipelex/sdk` that tolerates `lock_version` is *published*, the very release that fixes U3 causes the failure U3 describes in every consumer's CI, because their `rejectUnknownKeys` hard-throws on the new key. Record the published `@pipelex/sdk` version here before cutting a pipelex release.
+2. **The open PR #31 threads want a reply** (`chatgpt-codex-connector` and `cubic-dev-ai`, both on item 1 of `../pipelex-sdk-js/wip/pr-31-review-notes.md`, which says explicitly that they stay open until U1 lands upstream). U1 has landed *on this branch* — but the branch is unpushed and unreleased, so a reply can only say "fixed upstream, pending release", not "shipped". Drafts for both were written on 2026-08-19 and are with Louis; nothing has been posted, since posting to a public PR is his call.
+
+ A count correction worth carrying: PR #31 has **five** unresolved threads, not two. Besides the two U1 ones, a third (`cubic-dev-ai`, `src/codegen-check.ts:552`, the drift-ordering deferral) is materially changed by Phase 2 — upstream converged on the SDK's own full-string comparator, closing the reachable ASCII half of that finding — so it got a draft too. The remaining two are SDK-only and untouched by this work: the `WINDOWS_DRIVE = /^.:/u` regex missing U+2028 / U+2029 (verified real from this side — `validate_artifact_path` rejects `\u2028:models.py` as a drive prefix, and U+2028 is `Zl` so the control-character gate does not catch it first, leaving the SDK the permissive side), and a duplicated CRLF test row. Both are recorded at the end of the delivered SDK doc.
+
+## Cross-repo follow-ups (recorded here, **not** work in this repo)
+
+- **`pipelex-sdk-js`** — after U1/U5 release: mirror both tightenings (their notes already carry the ready-to-apply TS patch and test for U1). After U3 lands here (before our release): version-aware lock reader + fixture refresh, per Phase 4 sequencing. After U2: nothing — we converged toward their comparator; their only residual ordering divergence is the practically unreachable UTF-16-vs-code-point case their item 2a documents, which stays deferred on their side.
+- **`docs/specs/pipelex-codegen.md` + `conformance/` (workspace repo pair)** — S1: when the codegen sections de-skeleton, fold in the three load-bearing properties the SDK had to derive by reading `check.py` (at most one drift per locked path with `hand-edited` outranking `modified`; the orphan predicate is `has_stamp`, not the full parse; deterministic drift ordering — locked first, then orphans, both by path), plus the stamp-header text rules (line boundaries, strip set) as part of the hashed contract, plus U3's `lock_version` and evolution policy. Keep the `> Verified by:` ↔ `pytest.mark.spec` links in sync and run `make check-spec-links` in `conformance/`. This is release-gated on a published pipelex shipping codegen, per the existing `unverified` markers.
+- **`pipelex-sdk-python`** — no codegen-check mirror exists today; if one is ever built, S1's spec work is what makes that safe. Nothing to do now.