Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/3713.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `apm compile` validates the file path of a relative Markdown link independently of a `#fragment`, `?query` or combined suffix, so an existing file no longer produces a false `Referenced file not found` warning; a missing target is still reported, using the path without the suffix. -- by @bodapatisaikrishna (#3713)
3 changes: 3 additions & 0 deletions docs/src/content/docs/producer/write-primitives.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,9 @@ harness folder, it rewrites the link so it still points at the file, now inside
`apm_modules/`. Links inside one skill folder are not rewritten, because the
folder is copied whole.

`#fragment` and `?query` suffixes are kept. `apm compile` checks only the file
path, so it does not verify that the heading or query exists in the target.

**Gotcha:** APM rewrites a link when the target file exists and stays inside
your package. A link to another package, an absolute path or a missing
file is left as written, and breaks for consumers. Install your package into a
Expand Down
14 changes: 11 additions & 3 deletions src/apm_cli/compilation/link_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,13 +628,21 @@ def validate_link_targets(content: str, base_path: Path) -> builtins.list[str]:
if path.startswith(("http://", "https://", "ftp://", "mailto:")) or path.startswith("#"):
continue

# A markdown target may carry a ``#fragment``, ``?query``, or both.
# Those address part of the target; they are not part of the filename.
# Reuse the resolver's existing split so validation agrees with the
# rewriting path instead of looking for ``file.md#fragment``.
path_part, _suffix = UnifiedLinkResolver._split_link_target(path)
if not path_part:
continue

# Resolve and check path
full_path = _resolve_path(path, base_path)
full_path = _resolve_path(path_part, base_path)
if not full_path or not full_path.exists():
errors.append(f"Referenced file not found: {path} (in link '{text}')")
errors.append(f"Referenced file not found: {path_part} (in link '{text}')")
elif not full_path.is_file() and not full_path.is_dir():
errors.append(
f"Referenced path is neither a file nor directory: {path} (in link '{text}')"
f"Referenced path is neither a file nor directory: {path_part} (in link '{text}')"
)

return errors
Expand Down
82 changes: 82 additions & 0 deletions tests/integration/test_compile_suffixed_link_validation_e2e.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""Installed-CLI coverage for compile-time validation of suffixed links (#3255).

A relative Markdown link may carry a ``#fragment``, ``?query`` or both. The
installed ``apm compile`` must validate the file path without the suffix: an
existing file is not reported missing, a missing file is reported by its path
alone, the emitted link keeps its suffix, and ``--dry-run`` writes nothing.
"""

from __future__ import annotations

import subprocess
from pathlib import Path

import pytest

pytestmark = [
pytest.mark.integration,
pytest.mark.e2e,
pytest.mark.requires_apm_binary,
pytest.mark.requires_e2e_mode,
pytest.mark.promise("P-OWN-compiled-output-writes"),
]

_SUFFIXES = ("#template", "?view=full", "?view=full#template")


def _create_project(project: Path) -> None:
(project / "apm.yml").write_text(
"name: suffixed-links\nversion: 0.1.0\ntargets:\n - codex\n", encoding="ascii"
)
instructions = project / ".apm" / "instructions"
instructions.mkdir(parents=True)
links = []
for index, suffix in enumerate(_SUFFIXES):
links.append(f"[present{index}](references/standards.md{suffix})")
links.append(f"[absent{index}](references/missing.md{suffix})")
(instructions / "links.instructions.md").write_text(
"---\ndescription: Suffixed links\napplyTo: '**'\n---\n# Links\n" + "\n".join(links) + "\n",
encoding="ascii",
)
references = instructions / "references"
references.mkdir()
(references / "standards.md").write_text("# Template\n", encoding="ascii")


def _compile(apm_binary_path: Path, project: Path, *extra: str) -> str:
result = subprocess.run(
(str(apm_binary_path), "compile", *extra),
cwd=project,
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 0, result.stdout + result.stderr
return " ".join((result.stdout + result.stderr).split())


@pytest.mark.parametrize("dry_run", [False, True], ids=["write", "dry-run"])
def test_installed_compile_validates_suffixed_link_paths(
tmp_path: Path, apm_binary_path: Path, dry_run: bool
) -> None:
project = tmp_path / "project"
project.mkdir()
_create_project(project)

output = _compile(apm_binary_path, project, *(("--dry-run",) if dry_run else ()))

assert "Referenced file not found: references/standards.md" not in output
for index in range(len(_SUFFIXES)):
assert (
f"Referenced file not found: references/missing.md (in link 'absent{index}')" in output
)
assert "missing.md#" not in output
assert "missing.md?" not in output

agents_md = project / "AGENTS.md"
if dry_run:
assert not agents_md.exists()
return
emitted = agents_md.read_text(encoding="utf-8")
for suffix in _SUFFIXES:
assert f"standards.md{suffix})" in emitted
37 changes: 37 additions & 0 deletions tests/unit/compilation/test_link_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
from urllib.parse import urlparse

import pytest
from click.testing import CliRunner

from apm_cli.cli import cli
from apm_cli.compilation.link_resolver import (
LinkResolutionContext,
UnifiedLinkResolver,
Expand Down Expand Up @@ -1275,3 +1277,38 @@ def test_absolute_path_returned_as_is(self, tmp_path: Path) -> None:
def test_relative_path_resolved_against_base(self, base_dir: Path) -> None:
result = _resolve_path("sub/file.md", base_dir)
assert result == base_dir / "sub" / "file.md"


class TestCompileValidatesSuffixedLinks:
"""#3255: ``apm compile`` validates the file path, not ``file.md#fragment``."""

def test_compile_dry_run_validates_suffixed_links_by_path(
self, tmp_path: Path, monkeypatch
) -> None:
monkeypatch.chdir(tmp_path)
(tmp_path / "apm.yml").write_text("name: test-project\nversion: 0.1.0\n", encoding="utf-8")
instruction = tmp_path / ".apm" / "instructions" / "test.instructions.md"
instruction.parent.mkdir(parents=True)
instruction.write_text(
"""---
description: suffixed link fixture
applyTo: "**/*.py"
---
See [template](references/standards.md#template),
[query](references/standards.md?view=full),
[combined](references/standards.md?view=full#template), and
[missing](references/missing.md#template).
""",
encoding="utf-8",
)
references = instruction.parent / "references"
references.mkdir()
(references / "standards.md").write_text("# Template\n", encoding="utf-8")

result = CliRunner().invoke(cli, ["compile", "--dry-run"])
Comment thread
danielmeppiel marked this conversation as resolved.
Resolved

assert result.exit_code == 0, result.output
output = " ".join(result.output.split())
assert "Referenced file not found: references/standards.md" not in output
assert "Referenced file not found: references/missing.md (in link 'missing')" in output
assert not (tmp_path / "AGENTS.md").exists()
22 changes: 22 additions & 0 deletions tests/unit/compilation/test_link_resolver_resolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- _is_rewritable_relative_link (empty, fragment, //, /, scheme, relative)
- _split_link_target (no delimiter, fragment, query, both)
- _remove_frontmatter
- validate_link_targets with #fragment / ?query suffixes (#3255)
"""

from __future__ import annotations
Expand All @@ -17,6 +18,7 @@
from apm_cli.compilation.link_resolver import (
UnifiedLinkResolver,
_remove_frontmatter,
validate_link_targets,
)

pytestmark = pytest.mark.unit
Expand Down Expand Up @@ -170,3 +172,23 @@ def test_empty_frontmatter_is_stripped(self) -> None:
def test_content_without_leading_dashes_unchanged(self) -> None:
content = "# No frontmatter\n\nBody text"
assert _remove_frontmatter(content) == content


# ---------------------------------------------------------------------------
# validate_link_targets with suffixes (#3255)
# ---------------------------------------------------------------------------


class TestValidateLinkTargetsSuffixes:
@pytest.mark.parametrize("suffix", ["#template", "?view=full", "?view=full#template"])
def test_existing_file_with_suffix_no_errors(self, tmp_path: Path, suffix: str) -> None:
(tmp_path / "standards.md").write_text("content")
errors = validate_link_targets(f"[Standards](standards.md{suffix})", tmp_path)
assert errors == []

@pytest.mark.parametrize("suffix", ["#template", "?view=full", "?view=full#template"])
def test_missing_file_with_suffix_reports_path_without_suffix(
self, tmp_path: Path, suffix: str
) -> None:
errors = validate_link_targets(f"[Standards](missing.md{suffix})", tmp_path)
assert errors == ["Referenced file not found: missing.md (in link 'Standards')"]
Loading