fix(distribution): refuse symlinked targets before the first write

The symlink refusal lived in `_real_dir`, which runs per entry inside the copy
loop. By the time it fired for `skills/`, `SOUL.md`/`mcp.json`/`cron` had already
been replaced and `write_manifest` had not run yet, leaving a half-updated
profile that fails identically on every retry. Add a pre-flight pass over
`_owned_entries` that walks each target path (whole chain for directories,
parent chain for files) and raises before any mutation; `_real_dir` keeps its
check as the backstop.

The `.env.template` branch used a bare `shutil.copy2`, which writes through an
existing `.env.EXAMPLE` symlink into whatever it points at. Route it through
`_replace_entry` so the link is unlinked first, like every other owned entry.

The error text now tells the user what they can actually do (remove the link or
replace it with a real directory) instead of pointing at `distribution_owned`,
which is the author's manifest, not the user's.

The existing symlink test now changes every other shipped entry upstream and
asserts the profile is byte-for-byte untouched after the refusal.
This commit is contained in:
kshitijk4poor
2026-09-15 01:17:15 +05:30
committed by Teknium
parent cfc11f217a
commit d4fa373017
2 changed files with 35 additions and 6 deletions
+28 -6
View File
@@ -386,16 +386,35 @@ def _real_dir(base: Path, parts: Tuple[str, ...]) -> Path:
path = base
for part in parts:
path = path / part
if path.is_symlink():
raise DistributionError(
f"{path} is a symlink; refusing to replace it — remove the link or point distribution_owned elsewhere"
)
_refuse_symlink(path)
if path.exists() and not path.is_dir():
_remove_existing(path)
path.mkdir(exist_ok=True)
return path
def _refuse_symlink(path: Path) -> None:
if path.is_symlink():
raise DistributionError(
f"{path} is a symlink; refusing to replace it — remove the link "
"(or replace it with a real directory) and re-run"
)
def _refuse_symlinked_targets(target: Path, entries) -> None:
"""Refuse before the first write. The per-entry check in ``_real_dir`` fires mid-loop,
after earlier entries were already replaced and before the manifest is rewritten,
leaving a half-updated profile that fails identically on every retry."""
for src, rel_parts in entries:
# Directories are walked as containers, so the whole chain must be real;
# a file only needs a real parent chain (a symlinked file is unlinked, not followed).
depth = len(rel_parts) if src.is_dir() else len(rel_parts) - 1
path = target
for part in rel_parts[:depth]:
path = path / part
_refuse_symlink(path)
def _copy_dist_payload(staged: Path, target: Path, manifest: DistributionManifest, preserve_config: bool) -> None:
"""Copy distribution-owned files (see ``_owned_entries``) from *staged* into *target*.
@@ -407,12 +426,15 @@ def _copy_dist_payload(staged: Path, target: Path, manifest: DistributionManifes
the roots the payload ships are replaced, so roots the user added (or that an older
version shipped) survive an update or forced reinstall."""
target.mkdir(parents=True, exist_ok=True)
entries = list(_owned_entries(staged, manifest))
_refuse_symlinked_targets(target, entries)
for src, rel_parts in _owned_entries(staged, manifest):
for src, rel_parts in entries:
if len(rel_parts) == 1:
name = rel_parts[0]
if name == ENV_TEMPLATE_FILENAME:
shutil.copy2(src, target / ENV_EXAMPLE_FILENAME)
# _replace_entry unlinks first so copy2 cannot write through a symlinked .env.EXAMPLE.
_replace_entry(src, target / ENV_EXAMPLE_FILENAME)
continue
if name == "config.yaml" and preserve_config and (target / "config.yaml").exists():
continue
@@ -439,6 +439,12 @@ class TestUpdate:
shutil.rmtree(skills)
_symlink_file_or_skip(skills, shared)
(staged / "skills" / "demo" / "SKILL.md").write_text("updated demo\n")
# Every other shipped entry changes upstream too: the refusal must fire before the
# first write, or the profile is left half-updated and every retry fails the same way.
(staged / "SOUL.md").write_text("updated soul\n")
(staged / "mcp.json").write_text('{"servers": {"new": {}}}\n')
(staged / "cron" / "daily.json").write_text('{"schedule": "0 10 * * *"}')
untouched = {p: p.read_bytes() for p in plan.target_dir.rglob("*") if p.is_file()}
with pytest.raises(DistributionError, match="symlink"):
update_distribution("link_safe")
@@ -446,6 +452,7 @@ class TestUpdate:
assert skills.is_symlink() and skills.resolve() == shared.resolve()
after = sorted((p.relative_to(shared), p.read_bytes()) for p in shared.rglob("*") if p.is_file())
assert after == before
assert {p: p.read_bytes() for p in plan.target_dir.rglob("*") if p.is_file()} == untouched
def test_update_preserves_user_data(self, profile_env):
# 1. Build staging dir, install