Skip to content

Commit 4a46543

Browse files
fix: use missing_ok for temp file cleanup to avoid masking errors (#3803)
* fix(agent-context): recurse for nested plans in Python mtime fallback The Python port's mtime fallback discovered plans with a one-level specs/*/plan.md glob, so a scoped layout created via SPECIFY_FEATURE_DIRECTORY (specs/<scope>/<feature>/plan.md) was missed when feature.json is absent — the fallback returned no plan and the managed context section omitted the 'at <plan>' line. The bash and PowerShell twins were already fixed to recurse (#3024); the Python twin was left behind. Switch to specs.rglob('plan.md') with the same symlink-safe containment check the bash twin uses (resolve each candidate and confirm it stays within the project root before ranking by mtime), so a plan reached through a specs/ symlink pointing outside the project is not selected. Adds parity regression tests (vs bash and vs PowerShell) covering a nested specs/<scope>/<feature>/plan.md; both fail on the pre-fix one-level glob. Fixes #3733 * test(agent-context): cover symlink containment in the mtime fallback The recursive fallback resolves each candidate before the relative_to() containment check, but nothing exercised that path. Add a parity test for a plan reachable only through a specs/ symlink pointing outside the project: relative_to() is lexical and would accept it, emitting an in-project-looking path for an out-of-project file. Both the bash twin and the Python port skip it, so the "at <plan>" line is omitted. Also correct the module docstring, which still described the fallback as scanning specs/*/plan.md one level deep. * fix: use missing_ok for temp file cleanup to avoid masking errors
1 parent 204d94f commit 4a46543

5 files changed

Lines changed: 99 additions & 24 deletions

File tree

‎extensions/agent-context/scripts/python/update_agent_context.py‎

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
1212
When ``plan_path`` is omitted, the script derives it from
1313
``.specify/feature.json`` (written by /speckit-specify). Falls back to the most
14-
recently modified ``plan.md`` anywhere under ``specs/`` (including nested scoped
15-
layouts such as ``specs/<scope>/<feature>/plan.md``) only when feature.json is
14+
recently modified ``plan.md`` found anywhere under ``specs/`` — scoped layouts
15+
nest it as ``specs/<scope>/<feature>/plan.md`` — only when feature.json is
1616
absent or its plan does not exist yet.
1717
"""
1818

@@ -173,16 +173,31 @@ def _resolve_plan_path(project_root: str) -> str:
173173

174174
if not plan_path:
175175
root = Path(project_root).resolve()
176-
plans = sorted(
177-
(root / "specs").rglob("plan.md"),
178-
key=lambda p: p.stat().st_mtime,
179-
reverse=True,
180-
)
181-
if plans:
176+
specs = root / "specs"
177+
178+
def _resolved_rel(p: Path) -> Path | None:
179+
# Resolve symlinks before checking containment: relative_to() is
180+
# lexical and would otherwise accept a plan reached through a specs/
181+
# symlink that points outside the project, emitting an
182+
# in-project-looking path for an out-of-project file (or picking it
183+
# as "most recent").
182184
try:
183-
plan_path = plans[0].relative_to(root).as_posix()
184-
except ValueError:
185-
plan_path = ""
185+
return p.resolve().relative_to(root)
186+
except (OSError, ValueError):
187+
return None
188+
189+
# Recurse (rather than the old one-level specs/*/plan.md glob) so scoped
190+
# layouts created via SPECIFY_FEATURE_DIRECTORY, e.g.
191+
# specs/<scope>/<feature>/plan.md, are still discovered when
192+
# feature.json is absent (#3024). Mirrors the bash and PowerShell twins.
193+
candidates = []
194+
for p in specs.rglob("plan.md"):
195+
rel = _resolved_rel(p)
196+
if rel is not None:
197+
candidates.append((p, rel))
198+
candidates.sort(key=lambda pr: pr[0].stat().st_mtime, reverse=True)
199+
if candidates:
200+
plan_path = candidates[0][1].as_posix()
186201
return plan_path
187202

188203

‎src/specify_cli/_utils.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,8 +192,8 @@ def atomic_write_json(target_file: Path, payload: dict[str, Any]) -> None:
192192

193193
os.replace(temp_path, target_file)
194194
except Exception:
195-
if temp_path and temp_path.exists():
196-
temp_path.unlink()
195+
if temp_path:
196+
temp_path.unlink(missing_ok=True)
197197
raise
198198

199199
try:

‎src/specify_cli/integrations/manifest.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -451,8 +451,7 @@ def save(self) -> Path:
451451
_ensure_safe_manifest_destination(self.project_root, path)
452452
os.replace(temp_path, path)
453453
finally:
454-
if temp_path.exists():
455-
temp_path.unlink()
454+
temp_path.unlink(missing_ok=True)
456455
return path
457456

458457
@classmethod

‎src/specify_cli/shared_infra.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -278,8 +278,7 @@ def _write_shared_bytes(
278278
_ensure_safe_shared_destination(project_path, dest)
279279
os.replace(temp_path, dest)
280280
finally:
281-
if temp_path.exists():
282-
temp_path.unlink()
281+
temp_path.unlink(missing_ok=True)
283282

284283

285284
_BASH_FORMAT_COMMAND_RE = re.compile(

‎tests/extensions/test_update_agent_context_python_parity.py‎

Lines changed: 69 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -344,14 +344,19 @@ def test_python_mtime_fallback_matching_bash(tmp_path: Path) -> None:
344344

345345

346346
@requires_posix_bash
347-
def test_python_mtime_fallback_finds_nested_plan_matching_bash(tmp_path: Path) -> None:
348-
# Regression: the mtime fallback must discover plan.md in nested scoped
349-
# layouts (specs/<scope>/<feature>/plan.md), matching the Bash/PowerShell
350-
# ports and the documented recursive-discovery contract (see #3024). A
351-
# one-level scan (specs/*/plan.md) would miss this and omit the plan link.
347+
def test_python_mtime_fallback_finds_nested_plan_matching_bash(
348+
tmp_path: Path,
349+
) -> None:
350+
"""The mtime fallback must recurse into scoped layouts.
351+
352+
A plan created under specs/<scope>/<feature>/plan.md (as produced via
353+
SPECIFY_FEATURE_DIRECTORY) is more than one level below specs/. The old
354+
Python port used a one-level specs/*/plan.md glob and missed it, while the
355+
bash/PowerShell twins recurse (#3024). This locks in the parity.
356+
"""
352357
repo_a, repo_b = twin_projects(tmp_path, context_file="AGENTS.md")
353358
for repo in (repo_a, repo_b):
354-
plan = repo / "specs" / "scope-a" / "002-nested" / "plan.md"
359+
plan = repo / "specs" / "backend" / "001-nested" / "plan.md"
355360
plan.parent.mkdir(parents=True, exist_ok=True)
356361
plan.write_text("# plan\n", encoding="utf-8")
357362

@@ -361,7 +366,39 @@ def test_python_mtime_fallback_finds_nested_plan_matching_bash(tmp_path: Path) -
361366
assert_parity(bash, py, repo_a, repo_b)
362367
content = (repo_b / "AGENTS.md").read_bytes()
363368
assert content == (repo_a / "AGENTS.md").read_bytes()
364-
assert b"at specs/scope-a/002-nested/plan.md" in content
369+
assert b"at specs/backend/001-nested/plan.md" in content
370+
371+
372+
@requires_posix_bash
373+
def test_python_mtime_fallback_skips_plan_reached_through_escaping_symlink(
374+
tmp_path: Path,
375+
) -> None:
376+
"""A plan reached via a specs/ symlink out of the project is not selected.
377+
378+
``relative_to()`` is lexical, so ``specs/linked/001-x/plan.md`` looks
379+
in-project even when ``specs/linked`` points outside the tree. Resolving
380+
before the containment check rejects it, so the fallback finds nothing and
381+
the ``at <plan>`` line is omitted rather than naming an out-of-project file
382+
with an in-project-looking path. Mirrors the bash twin's ``_resolved_rel``.
383+
"""
384+
repo_a, repo_b = twin_projects(tmp_path, context_file="AGENTS.md")
385+
for repo in (repo_a, repo_b):
386+
outside = repo.parent / f"outside-{repo.name}" / "001-x"
387+
outside.mkdir(parents=True, exist_ok=True)
388+
(outside / "plan.md").write_text("# plan\n", encoding="utf-8")
389+
specs = repo / "specs"
390+
specs.mkdir(parents=True, exist_ok=True)
391+
(specs / "linked").symlink_to(outside.parent, target_is_directory=True)
392+
# Sanity: the plan really is reachable through the symlink.
393+
assert (specs / "linked" / "001-x" / "plan.md").is_file()
394+
395+
bash = run_bash(repo_a)
396+
py = run_python(repo_b)
397+
398+
assert_parity(bash, py, repo_a, repo_b)
399+
content = (repo_b / "AGENTS.md").read_bytes()
400+
assert content == (repo_a / "AGENTS.md").read_bytes()
401+
assert b"\nat " not in content
365402

366403

367404
@requires_posix_bash
@@ -508,6 +545,31 @@ def test_python_fresh_context_file_matches_powershell(tmp_path: Path) -> None:
508545
assert (repo_a / "AGENTS.md").read_bytes() == (repo_b / "AGENTS.md").read_bytes()
509546

510547

548+
@pytest.mark.skipif(not POWERSHELL, reason="no PowerShell available")
549+
def test_python_mtime_fallback_finds_nested_plan_matches_powershell(
550+
tmp_path: Path,
551+
) -> None:
552+
"""Python's mtime fallback must recurse like the PowerShell twin.
553+
554+
With no feature.json, discovery falls back to scanning under specs/. A plan
555+
at specs/<scope>/<feature>/plan.md sits more than one level deep; the old
556+
Python one-level glob missed it while PowerShell already recurses (#3024).
557+
"""
558+
repo_a = make_project(tmp_path / "proj-ps", context_file="AGENTS.md")
559+
repo_b = make_project(tmp_path / "proj-py", context_file="AGENTS.md")
560+
for repo in (repo_a, repo_b):
561+
plan = repo / "specs" / "backend" / "001-nested" / "plan.md"
562+
plan.parent.mkdir(parents=True, exist_ok=True)
563+
plan.write_text("# plan\n", encoding="utf-8")
564+
565+
ps = run_powershell(repo_a)
566+
py = run_python(repo_b)
567+
568+
assert ps.returncode == py.returncode == 0, ps.stderr + py.stderr
569+
assert (repo_a / "AGENTS.md").read_bytes() == (repo_b / "AGENTS.md").read_bytes()
570+
assert b"at specs/backend/001-nested/plan.md" in (repo_b / "AGENTS.md").read_bytes()
571+
572+
511573
@pytest.mark.skipif(not POWERSHELL, reason="no PowerShell available")
512574
def test_python_upsert_matches_powershell(tmp_path: Path) -> None:
513575
repo_a = make_project(tmp_path / "proj-ps", context_file="AGENTS.md")

0 commit comments

Comments
 (0)