diff --git a/devcapsule-src/devcapsule/configuration/listing.py b/devcapsule-src/devcapsule/configuration/listing.py
index 39a3af0c..df7bd6dc 100644
--- a/devcapsule-src/devcapsule/configuration/listing.py
+++ b/devcapsule-src/devcapsule/configuration/listing.py
@@ -15,6 +15,7 @@
- ``access``: host access and the base and vendor consents, from the
authorization review;
- ``env``: the environment the project asks for and the checkout saved;
+- ``source``: a wrapped source's declared toolchain and fork or learning intent;
- ``value``, ``binding``, ``secret``: the project's declared values and the
selected components' state slots and secret inputs.
diff --git a/devcapsule-src/devcapsule/configuration/owner_commands.py b/devcapsule-src/devcapsule/configuration/owner_commands.py
index 41911fb3..ddda78d0 100644
--- a/devcapsule-src/devcapsule/configuration/owner_commands.py
+++ b/devcapsule-src/devcapsule/configuration/owner_commands.py
@@ -410,7 +410,7 @@ def declare_source(start: Path, path: str, *, upstream: str | None = None, java:
"""
root, manifest, _lock, _matrix = _project(start, check_resolutions=False)
path = source_path(path, field_name="source path")
- if upstream is not None and (not upstream.strip() or "\x00" in upstream):
+ if upstream is not None and (not isinstance(upstream, str) or not upstream.strip() or "\x00" in upstream):
raise ProjectConfigurationError("The upstream is the upstream repository's URL; it cannot be blank.")
if java is not None:
java = java_line(java, field_name="java line")
diff --git a/devcapsule-src/devcapsule/wrap.py b/devcapsule-src/devcapsule/wrap.py
index b7e9b146..17acaa8a 100644
--- a/devcapsule-src/devcapsule/wrap.py
+++ b/devcapsule-src/devcapsule/wrap.py
@@ -23,11 +23,14 @@
from __future__ import annotations
from dataclasses import dataclass
+import html
from pathlib import Path
+import re
import shutil
import subprocess
from typing import Any, Mapping, TextIO
+from devcapsule.compat import CliError
from devcapsule.configuration.file_formats import ProjectConfigurationError
from devcapsule.configuration.manifest import current_manifest
from devcapsule.configuration.manifest_document import Recommendations
@@ -100,7 +103,9 @@ def wrap_project(request: WrapRequest, *, input_stream: TextIO | None = None, ou
"""Wrap one repository into the project at ``request.directory``; see the module docstring for the steps."""
root = request.directory.expanduser().resolve()
_require_repository_root(root)
- path = source_path(request.path or _repository_name(request.url), field_name="--path")
+ path = source_path(request.path if request.path is not None else _repository_name(request.url), field_name="--path")
+ # Validate source metadata before Git or initialization writes anything.
+ WrappedSources.read({"sources": {path: {"upstream": request.upstream} if request.upstream is not None else {}}})
submodule_action = _add_submodule(root, request.url, path)
detection = detect(root / path)
manifest_path = root / ".devcapsule" / "devcapsule.toml"
@@ -108,13 +113,19 @@ def wrap_project(request: WrapRequest, *, input_stream: TextIO | None = None, ou
capability_lines: list[str] = []
needed = detection.capabilities if detection is not None else ()
if not manifest_path.is_file():
- initialized = initialize_project(
- InitializeRequest(directory=root, require=needed, ide=request.ide, agents=request.agents,
- project_name=request.project_name, slug=request.slug, creator=request.creator,
- project_mount=request.project_mount, answers=request.answers,
- allow_unverified=request.allow_unverified, interactive=request.interactive),
- input_stream=input_stream, output_stream=output_stream,
- )
+ try:
+ initialized = initialize_project(
+ InitializeRequest(directory=root, require=needed, ide=request.ide, agents=request.agents,
+ project_name=request.project_name, slug=request.slug, creator=request.creator,
+ project_mount=request.project_mount, answers=request.answers,
+ allow_unverified=request.allow_unverified, interactive=request.interactive),
+ input_stream=input_stream, output_stream=output_stream,
+ )
+ except (CliError, KeyboardInterrupt) as exc:
+ raise ProjectConfigurationError(
+ f"Initialization did not finish: {exc or 'interrupted'}. The submodule {path} remains. "
+ "Rerun wrap with the missing answers; if configuration files already exist, complete 'project init' first."
+ ) from exc
else:
manifest = current_manifest(load_toml(manifest_path), manifest_path).document()
declared = {name.partition(">=")[0] for name in manifest["capabilities"].get("required", [])}
@@ -155,14 +166,25 @@ def _repository_name(url: str) -> str:
def _add_submodule(root: Path, url: str, path: str) -> str:
"""Add the submodule unless the same one already stands at ``path``; embed its Git directory either way."""
target = root / path
- registered = _git(root, "config", "-f", ".gitmodules", f"submodule.{path}.url", check=False)
- if target.exists():
- if registered.returncode == 0 and registered.stdout.strip() == url:
- action = f"Kept the submodule {path}, already added from {url}"
- else:
- raise ProjectConfigurationError(f"{target} exists and is not a submodule added from {url}; give another --path.")
+ if any(part.is_symlink() for part in (target, *target.parents) if part != root and root in part.parents):
+ raise ProjectConfigurationError(f"{target} passes through a symlink; give a path inside the wrapper without symlinks.")
+ registered = _registered_url(root, path)
+ if registered is not None:
+ if registered != url:
+ raise ProjectConfigurationError(f"{path} is registered with a different URL ({registered}); give another --path.")
+ if not (target / ".git").exists():
+ _git(root, "submodule", "update", "--init", "--", path)
+ action = f"Kept the submodule {path}, already added from {url}"
+ elif target.exists():
+ raise ProjectConfigurationError(f"{target} exists and is not a submodule added from {url}; inspect any partial clone, then give another --path.")
else:
- _git(root, "submodule", "add", "--", url, path)
+ try:
+ _git(root, "submodule", "add", "--", url, path)
+ except ProjectConfigurationError as exc:
+ raise ProjectConfigurationError(
+ f"{exc}. Git may have left a partial submodule at {path}; no files were removed. "
+ "Rerun wrap if the submodule was registered; otherwise inspect the path, .gitmodules and Git's modules directory before retrying."
+ ) from exc
action = f"Added the submodule {path} from {url}"
return action + ("; its Git directory is embedded in the tree." if _embed_git_directory(root, path) else ".")
@@ -178,8 +200,9 @@ def _embed_git_directory(root: Path, path: str) -> bool:
gitfile = root / path / ".git"
if gitfile.is_dir():
return False
- git_dir = Path(_git(root, "rev-parse", "--path-format=absolute", "--git-dir").stdout.strip())
- module = git_dir / "modules" / path
+ # Ask the submodule: its registered name can differ from its path, and
+ # a linked wrapper worktree has its own Git directory.
+ module = Path(_git(root / path, "rev-parse", "--absolute-git-dir").stdout.strip())
if not module.is_dir():
raise ProjectConfigurationError(f"The submodule's Git directory is neither at {gitfile} nor at {module}; cannot embed it.")
gitfile.unlink()
@@ -205,7 +228,7 @@ def _write_guidance(root: Path, manifest: Mapping[str, Any]) -> tuple[str, ...]:
lines: list[str] = []
for name, text in (("AGENTS.md", render_agents(manifest, sources, origins)), ("README.md", render_readme(manifest, sources, origins))):
target = root / name
- if target.is_file() and not target.read_text(encoding="utf-8").startswith(GUIDANCE_MARKER):
+ if target.is_file() and target.read_text(encoding="utf-8").splitlines()[:1] != [GUIDANCE_MARKER]:
lines.append(f"Kept your {name}; it does not carry the wrap marker. Add the wrapped sources to it yourself.")
continue
target.write_text(text, encoding="utf-8")
@@ -214,8 +237,26 @@ def _write_guidance(root: Path, manifest: Mapping[str, Any]) -> tuple[str, ...]:
def _origin(root: Path, path: str) -> str:
- completed = _git(root, "config", "-f", ".gitmodules", f"submodule.{path}.url", check=False)
- return completed.stdout.strip() if completed.returncode == 0 else "(not in .gitmodules)"
+ return _registered_url(root, path) or "(not in .gitmodules)"
+
+
+def _registered_url(root: Path, path: str) -> str | None:
+ """Find a submodule by its path, which need not equal its Git section name."""
+ completed = _git(root, "config", "--null", "-f", ".gitmodules", "--get-regexp", r"^submodule\..*\.path$", check=False)
+ for record in completed.stdout.split("\x00"):
+ key, separator, value = record.partition("\n")
+ if separator and value == path:
+ url = _git(root, "config", "--null", "-f", ".gitmodules", key[:-4] + "url", check=False)
+ # A registered path without a URL must not become a new add.
+ return url.stdout.removesuffix("\x00") if url.returncode == 0 else ""
+ return None
+
+
+def _markdown_data(value: str) -> str:
+ """Keep external text on one line and prevent Markdown or HTML structure."""
+ value = value.replace("\\", "\\\\").replace("\n", r"\n").replace("\r", r"\r").replace("\t", r"\t")
+ value = html.escape(value, quote=True)
+ return re.sub(r"[`*_[\]{}()#!|]", lambda match: f"{ord(match.group())};", value)
def _java_lines(source: WrappedSource) -> list[str]:
@@ -228,15 +269,15 @@ def _java_lines(source: WrappedSource) -> list[str]:
def render_agents(manifest: Mapping[str, Any], sources: WrappedSources, origins: Mapping[str, str]) -> str:
"""The wrapper's AGENTS.md: agent-neutral, regenerated from the manifest."""
- name = manifest["project"]["name"]
+ name = _markdown_data(manifest["project"]["name"])
lines = [GUIDANCE_MARKER, f"# Agent Instructions: {name}", "",
"This repository is a DevCapsule wrapper. It holds the DevCapsule configuration under",
"`.devcapsule/` and foreign repositories as Git submodules. The code to work on lives in",
"the submodules; the wrapper only sets up the environment around them.", "",
"## Wrapped sources", ""]
for source in sources.entries:
- lines.extend([f"### `{source.path}`", "", f"- Origin: {origins.get(source.path, '')}",
- f"- Intent: {source.intent}." + (f" Upstream: {source.upstream}." if source.upstream else "")])
+ lines.extend([f"### {_markdown_data(source.path)}", "", f"- Origin: {_markdown_data(origins.get(source.path, ''))}",
+ f"- Intent: {source.intent}." + (f" Upstream: {_markdown_data(source.upstream)}." if source.upstream else "")])
lines.extend(_java_lines(source))
lines.append("")
lines.extend(["## Rules", "",
@@ -253,7 +294,7 @@ def render_agents(manifest: Mapping[str, Any], sources: WrappedSources, origins:
def render_readme(manifest: Mapping[str, Any], sources: WrappedSources, origins: Mapping[str, str]) -> str:
"""The wrapper's README.md for a person: what this is and how to start."""
- name = manifest["project"]["name"]
+ name = _markdown_data(manifest["project"]["name"])
lines = [GUIDANCE_MARKER, f"# {name}", "",
"A DevCapsule wrapper: the development environment for the repositories below, which",
"are not this repository's own code and carry no DevCapsule configuration of their own.", "",
@@ -262,8 +303,8 @@ def render_readme(manifest: Mapping[str, Any], sources: WrappedSources, origins:
"An existing clone without the submodules: `git submodule update --init`.", "",
"## Wrapped sources", ""]
for source in sources.entries:
- lines.extend([f"### `{source.path}`", "", f"- Origin: {origins.get(source.path, '')}",
- f"- Intent: {source.intent}." + (f" Upstream: {source.upstream}." if source.upstream else "")])
+ lines.extend([f"### {_markdown_data(source.path)}", "", f"- Origin: {_markdown_data(origins.get(source.path, ''))}",
+ f"- Intent: {source.intent}." + (f" Upstream: {_markdown_data(source.upstream)}." if source.upstream else "")])
lines.extend(_java_lines(source))
lines.append("")
return "\n".join(lines)
diff --git a/devcapsule-src/devcapsule/wrap_detection.py b/devcapsule-src/devcapsule/wrap_detection.py
index c23f1b2c..9de05cad 100644
--- a/devcapsule-src/devcapsule/wrap_detection.py
+++ b/devcapsule-src/devcapsule/wrap_detection.py
@@ -25,12 +25,25 @@
# Gradle's Java compatibility table (docs.gradle.org/current/userguide/compatibility.html):
# every 8.x and 9.0 run on JDK 17; 9.1 is the first to run on JDK 25.
-# A plain Gradle project gets the oldest line its wrapper runs on, which is
-# the line most likely to match what the project's authors use.
+# Select 17 for 8.x and 9.0, and the capsule's default 25 from 9.1 onward.
+# This is a wrapper selection rule, not Gradle's minimum Java requirement.
GRADLE_JAVA_LINES: tuple[tuple[tuple[int, int], str], ...] = (((9, 1), "25"), ((8, 0), "17"))
-_GRADLERIO_PATTERN = re.compile(r'edu\.wpi\.first\.GradleRIO["\')]*\s*version\s*\(?\s*["\'](\d{4})')
-_DISTRIBUTION_PATTERN = re.compile(r"gradle-(\d+)\.(\d+)")
+# Keep strings as whole tokens. A plugin example inside a string must never
+# become an executable declaration. Comments are discarded below.
+_SCRIPT_TOKEN = re.compile(
+ "|".join((
+ r"//[^\n]*", r"/\*.*?\*/", # comments
+ r"\$/.*?/\$", r"/(?:\\.|[^/\\])*/", # Groovy slashy strings
+ r'""".*?"""', r"'''.*?'''", # multiline strings
+ r'"(?:\\.|[^"\\])*"', r"'(?:\\.|[^'\\])*'",
+ r"[A-Za-z_$][\w$]*", r"[^\s]",
+ )),
+ re.DOTALL,
+)
+_PLUGIN_YEAR = re.compile(r'''(["'])(\d{4})(?:\.[^"']*)?\1''')
+_DISTRIBUTION_PROPERTY = re.compile(r"^[ \t]*distributionUrl[ \t]*(?:[=:][ \t]*|[ \t]+)([^\r\n]*)", re.MULTILINE)
+_DISTRIBUTION_PATTERN = re.compile(r"/gradle-(\d+)\.(\d+)(?:[.\w-]*)-(?:bin|all)\.zip(?:[?#].*)?$")
@dataclass(frozen=True)
@@ -54,14 +67,13 @@ def detect(source: Path) -> Detection | None:
if not (source / "gradlew").is_file() or build_script is None:
return None
evidence = [f"Gradle wrapper and {build_script.name}"]
- match = _GRADLERIO_PATTERN.search(build_script.read_text(encoding="utf-8", errors="replace"))
- if match is not None:
- year = match.group(1)
+ year = _gradlerio_year(build_script.read_text(encoding="utf-8", errors="replace"))
+ if year is not None:
java = GRADLERIO_JAVA_LINES.get(year)
evidence.append(f"GradleRIO {year}" + (f": WPILib {year} builds with Java {java}" if java else f": no Java line known for WPILib {year}"))
return Detection(("java",), "java-ide", java, tuple(evidence))
gradle = _gradle_java_line(source)
- evidence.append(f"Gradle {gradle[0]}: runs on Java {gradle[1]}" if gradle is not None else "the Gradle version is not in gradle-wrapper.properties")
+ evidence.append(f"Gradle {gradle[0]}: runs on Java {gradle[1]}" if gradle is not None else "no supported Gradle version found in distributionUrl in gradle-wrapper.properties")
return Detection(("java",), "java-ide", gradle[1] if gradle is not None else None, tuple(evidence))
@@ -70,7 +82,8 @@ def _gradle_java_line(source: Path) -> tuple[str, str] | None:
properties = source / "gradle" / "wrapper" / "gradle-wrapper.properties"
if not properties.is_file():
return None
- match = _DISTRIBUTION_PATTERN.search(properties.read_text(encoding="utf-8", errors="replace"))
+ declarations = _DISTRIBUTION_PROPERTY.findall(properties.read_text(encoding="utf-8", errors="replace"))
+ match = _DISTRIBUTION_PATTERN.search(declarations[-1].strip()) if declarations else None
if match is None:
return None
version = (int(match.group(1)), int(match.group(2)))
@@ -78,3 +91,30 @@ def _gradle_java_line(source: Path) -> tuple[str, str] | None:
if version >= minimum:
return f"{version[0]}.{version[1]}", line
return None
+
+
+def _gradlerio_year(script: str) -> str | None:
+ """Read a literal ``id ... version ...`` declaration, without evaluating Gradle."""
+ tokens = [match.group() for match in _SCRIPT_TOKEN.finditer(script)
+ if not match.group().startswith(("//", "/*"))]
+ for index, token in enumerate(tokens):
+ if token != "id":
+ continue
+ rest = tokens[index + 1:]
+ if rest[:1] == ["("]:
+ if len(rest) < 3 or rest[2] != ")":
+ continue
+ plugin, rest = rest[1], rest[3:]
+ elif rest:
+ plugin, rest = rest[0], rest[1:]
+ else:
+ continue
+ if plugin not in ('"edu.wpi.first.GradleRIO"', "'edu.wpi.first.GradleRIO'") or rest[:1] != ["version"]:
+ continue
+ rest = rest[1:]
+ if rest[:1] == ["("]:
+ rest = rest[1:]
+ match = _PLUGIN_YEAR.fullmatch(rest[0]) if rest else None
+ if match is not None:
+ return match.group(2)
+ return None
diff --git a/devcapsule-src/tests/test_owner_commands.py b/devcapsule-src/tests/test_owner_commands.py
index ed1995d9..6291b2c2 100644
--- a/devcapsule-src/tests/test_owner_commands.py
+++ b/devcapsule-src/tests/test_owner_commands.py
@@ -3,7 +3,9 @@
from __future__ import annotations
from pathlib import Path
+import json
import tomllib
+from typing import Any
import pytest
@@ -384,3 +386,38 @@ def test_declare_source_preview_and_refusals_write_nothing(project: Path) -> Non
with pytest.raises(ProjectConfigurationError, match="upstream"):
owner_commands.declare_source(project, "robot", upstream=" ")
assert manifest_text(project) == before
+
+
+@pytest.mark.parametrize("fields", [
+ {"path": ""}, {"path": "../escape"}, {"path": 3},
+ {"upstream": 3}, {"upstream": "bad\x00url"}, {"upstream": " "},
+ {"java": 17}, {"java": "0"}, {"java": "17\n"},
+])
+def test_declare_source_refuses_malformed_inputs_without_touching_files(project: Path, fields: dict[str, Any]) -> None:
+ manifest_path, lock_path, _ = paths(project)
+ before = manifest_path.read_bytes(), lock_path.read_bytes()
+ with pytest.raises(ProjectConfigurationError):
+ owner_commands.declare_source(project, **{"path": "vendor/robot", **fields})
+ assert (manifest_path.read_bytes(), lock_path.read_bytes()) == before
+
+
+def test_sources_survive_other_owner_edits_and_do_not_change_pending_decisions(project: Path, capsys) -> None:
+ assert cli.main(["project", "--path", str(project), "config", "show", "--json"]) == 0
+ baseline = json.loads(capsys.readouterr().out)
+ owner_commands.declare_source(project, 'vendor/robot.code', upstream="https://example.test/up", java="17")
+ owner_commands.declare_source(project, "notes")
+ manifest_path, lock_path, _ = paths(project)
+ manifest_path.write_text(manifest_path.read_text().replace('java = "17"', 'java = "17"\nfuture = { extra = true }'))
+ sources = load_toml(manifest_path)["sources"]
+ owner_commands.recommend(project, "memory", "4g")
+ assert load_toml(manifest_path)["sources"] == sources
+ lock = lock_path.read_bytes()
+ owner_commands.declare_source(project, "notes", preview=True)
+ assert lock_path.read_bytes() == lock
+ assert cli.main(["project", "--path", str(project), "config", "show", "--json"]) == 0
+ document = json.loads(capsys.readouterr().out)
+ assert document["pending"] == baseline["pending"]
+ assert [row for row in document["rows"] if row["kind"] == "source"] == [
+ {"kind": "source", "name": "notes", "effective": "no toolchain declared", "source": "project: upstream, read-only", "pending": "", "command": ""},
+ {"kind": "source", "name": "vendor/robot.code", "effective": "java 17", "source": "project: fork of https://example.test/up", "pending": "", "command": ""},
+ ]
diff --git a/devcapsule-src/tests/test_sources.py b/devcapsule-src/tests/test_sources.py
index 7b73d053..70cc1d16 100644
--- a/devcapsule-src/tests/test_sources.py
+++ b/devcapsule-src/tests/test_sources.py
@@ -80,7 +80,7 @@ def test_schema_two_reads_sources_as_its_own_table_and_renders_it_after_capabili
assert value.extensions == {}
assert value.wrapped_sources.entries == (WrappedSource("vendor/robot", None, "17"),)
text = render_manifest(value.document())
- assert text.index("[capabilities]") < text.index('[sources."vendor/robot"]') < text.index("[recommendations]") if "[recommendations]" in text else True
+ assert text.index("[capabilities]") < text.index('[sources."vendor/robot"]')
assert 'java = "17"' in text
assert read_manifest(tomllib.loads(text), "rendered") == value
@@ -100,3 +100,16 @@ def test_an_explicitly_empty_sources_table_survives_the_round_trip() -> None:
value = read_manifest(manifest(), "manifest")
assert value.document()["sources"] == {}
assert "[sources]" in render_manifest(value.document())
+
+
+@pytest.mark.parametrize("path", ['vendor/robot', 'robot.code', 'two words', 'quote"', 'tick`', 'line\nbreak', 'robot\x7f'])
+def test_source_keys_and_unknown_fields_round_trip_through_the_manifest(path: str) -> None:
+ document = manifest(**{path: {"java": "17", "future": {"key.with.dots": True}}})
+ value = ManifestV2.read(document, "manifest")
+ assert tomllib.loads(render_manifest(value.document())) == document
+
+
+@pytest.mark.parametrize("path", [None, 17, "a/./b", "a/..", "./a", "//a", "a\x00b"])
+def test_additional_non_normal_source_paths_are_refused(path: object) -> None:
+ with pytest.raises(ProjectConfigurationError, match="source path"):
+ source_path(path, field_name="source path")
diff --git a/devcapsule-src/tests/test_wrap.py b/devcapsule-src/tests/test_wrap.py
index 34b4198c..66a4ff5d 100644
--- a/devcapsule-src/tests/test_wrap.py
+++ b/devcapsule-src/tests/test_wrap.py
@@ -3,6 +3,8 @@
from __future__ import annotations
from pathlib import Path
+from io import StringIO
+import shutil
import subprocess
import pytest
@@ -10,7 +12,7 @@
from devcapsule import cli
from devcapsule.configuration.file_formats import ProjectConfigurationError
from devcapsule.configuration.storage import load_toml
-from devcapsule.wrap import GUIDANCE_MARKER, WrapRequest, wrap_project
+from devcapsule.wrap import GUIDANCE_MARKER, WrapRequest, _add_submodule, wrap_project
from tests.test_wrap_detection import gradle_project
GRADLERIO = 'plugins {\n id "java"\n id "edu.wpi.first.GradleRIO" version "2025.3.2"\n}\n'
@@ -78,7 +80,7 @@ def test_a_first_wrap_builds_the_whole_wrapper(tmp_path: Path) -> None:
assert git(root, "status", "--porcelain") == "A .gitmodules\nA RobotCode2025Public\n?? .devcapsule/\n?? AGENTS.md\n?? README.md"
agents = (root / "AGENTS.md").read_text()
assert agents.startswith(GUIDANCE_MARKER + "\n")
- assert "### `RobotCode2025Public`" in agents and f"- Origin: {url}" in agents
+ assert "### RobotCode2025Public" in agents and f"- Origin: {url.replace('_', '_')}" in agents
assert "- Intent: learn from it; it is read-only, nothing is pushed." in agents
assert 'export JAVA_HOME=/opt/java/17; export PATH="$JAVA_HOME/bin:$PATH"' in agents
readme = (root / "README.md").read_text()
@@ -98,7 +100,7 @@ def test_a_second_wrap_extends_the_manifest_and_regenerates_the_guidance(tmp_pat
assert manifest["sources"] == {"AdvantageKit": {"upstream": "https://github.com/Mechanical-Advantage/AdvantageKit", "java": "17"},
"RobotCode2025Public": {"java": "17"}}
agents = (root / "AGENTS.md").read_text()
- assert agents.index("### `AdvantageKit`") < agents.index("### `RobotCode2025Public`")
+ assert agents.index("### AdvantageKit") < agents.index("### RobotCode2025Public")
assert ("- Intent: change it in your fork; pull requests go to the fork's origin, never to the upstream. "
"Upstream: https://github.com/Mechanical-Advantage/AdvantageKit.") in agents
@@ -181,3 +183,147 @@ def test_the_command_line_reaches_the_operation(tmp_path: Path, capsys) -> None:
assert load_toml(root / ".devcapsule" / "devcapsule.toml")["sources"]["RobotCode2025Public"]["upstream"] == "https://github.com/Mechanical-Advantage/RobotCode2025Public"
assert cli.main(["project", "--path", str(root), "config", "show"]) == 0
assert "source RobotCode2025Public java 17" in capsys.readouterr().out
+
+
+@pytest.mark.parametrize("missing", [False, True])
+def test_registered_path_with_another_url_is_refused_without_changes(tmp_path: Path, missing: bool) -> None:
+ url = upstream(tmp_path, "robot")
+ root = wrapper(tmp_path)
+ git(root, "submodule", "add", "--name", "custom-name", url, "vendor/robot")
+ if missing:
+ shutil.rmtree(root / "vendor/robot")
+ before = (root / ".gitmodules").read_bytes()
+ with pytest.raises(ProjectConfigurationError, match="registered.*different URL"):
+ _add_submodule(root, url + "-other", "vendor/robot")
+ assert (root / ".gitmodules").read_bytes() == before
+ assert (root / "vendor/robot").exists() is not missing
+
+
+@pytest.mark.parametrize("missing", [False, True])
+def test_registered_submodule_uses_its_path_not_its_name(tmp_path: Path, missing: bool) -> None:
+ url = upstream(tmp_path, "robot")
+ root = wrapper(tmp_path)
+ git(root, "submodule", "add", "--name", "custom-name", url, "vendor/robot")
+ if missing:
+ shutil.rmtree(root / "vendor/robot")
+ wrap_project(request(root, url, path="vendor/robot"))
+ assert (root / "vendor/robot/.git").is_dir()
+ assert git(root / "vendor/robot", "status", "--porcelain") == ""
+ assert "vendor/robot" in git(root, "submodule", "status")
+ assert f"- Origin: {url.replace('_', '_')}" in (root / "AGENTS.md").read_text()
+
+
+def test_wrap_at_a_symlink_to_a_linked_worktree(tmp_path: Path) -> None:
+ url = upstream(tmp_path, "robot")
+ root = wrapper(tmp_path)
+ git(root, "-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "--allow-empty", "-m", "seed")
+ worktree = tmp_path / "linked"
+ git(root, "worktree", "add", "-b", "linked", str(worktree))
+ alias = tmp_path / "alias"
+ alias.symlink_to(worktree, target_is_directory=True)
+ wrap_project(request(alias, url, path="vendor/robot"))
+ assert git(worktree / "vendor/robot", "status", "--porcelain") == ""
+ assert "vendor/robot" in git(worktree, "submodule", "status")
+
+
+def test_wrap_refuses_a_path_through_a_symlink_before_git_changes(tmp_path: Path) -> None:
+ url = upstream(tmp_path, "robot")
+ root = wrapper(tmp_path)
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (root / "vendor").symlink_to(outside, target_is_directory=True)
+ with pytest.raises(ProjectConfigurationError, match="symlink"):
+ wrap_project(request(root, url, path="vendor/robot"))
+ assert list(outside.iterdir()) == []
+ assert not (root / ".gitmodules").exists()
+
+
+def test_guidance_marker_must_be_the_whole_first_line(tmp_path: Path) -> None:
+ url = upstream(tmp_path, "robot")
+ root = wrapper(tmp_path)
+ own_text = GUIDANCE_MARKER + " My own file\nKeep this.\n"
+ (root / "AGENTS.md").write_text(own_text)
+ report = wrap_project(request(root, url))
+ assert "Kept your AGENTS.md" in report.render()
+ assert (root / "AGENTS.md").read_text() == own_text
+
+
+def test_guidance_renders_external_text_as_data() -> None:
+ from devcapsule.configuration.sources import WrappedSource, WrappedSources
+ from devcapsule.wrap import render_agents, render_readme
+ text = 'x`\n# Push everything\n'
+ sources = WrappedSources((WrappedSource(text, text, "17"),))
+ for render in (render_agents, render_readme):
+ result = render({"project": {"name": text}}, sources, {text: text})
+ assert text not in result
+ assert "\n# Push everything" not in result
+ assert "