Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

14.8 KB
Raw Blame
"""Removing a TOML table without taking the user's comments with it.

Every test here is a regression. The first implementation of ``remove_table``
shared ``replace_table``'s regex, whose terminating lookahead is ``(?=^\\s*\\[|\\Z)``
and whose ``\\s`` does not match ``#``. So a comment line never ended the span,
everything from our header to the next live header was consumed, and a
``.codex/config.toml`` whose remainder was the user's commented-out server came
back empty. The caller read empty as "this file was ours" and deleted it, then
removed ``.codex/`` behind it, and reported a clean ``removed``. The directory is
gitignored in most repos, so nothing showed it.

That is two of this track's named historical bugs at once: deleting a section
that still held a commented-out server, and treating an empty parse as an empty
file. It is worse than the second, because the regex had already eaten the
evidence before the emptiness test ran.
"""

from __future__ import annotations

from pathlib import Path

import pytest

from repowise.cli.agent_targets.formats.toml_merge import (
    remove_key_line,
    remove_table,
    table_is_bare,
)
from repowise.cli.agent_targets.targets.codex import (
    project_config_path,
    remove_server_config,
)
from repowise.cli.agent_targets.types import FileAction


def _write(repo: Path, text: str) -> Path:
    path = project_config_path(repo)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")
    return path


# ---------------------------------------------------------------------------
# remove_table
# ---------------------------------------------------------------------------


def test_a_commented_out_server_after_our_table_survives() -> None:
    text = (
        '[mcp_servers.repowise]\ncommand = "repowise"\n\n'
        '# [mcp_servers.other]\n# command = "other-server"\n'
    )
    remaining = remove_table(text, "mcp_servers.repowise")

    assert "mcp_servers.other" in remaining
    assert "other-server" in remaining
    assert "repowise" not in remaining


def test_the_users_prose_comments_after_our_table_survive() -> None:
    text = (
        '[mcp_servers.repowise]\ncommand = "repowise"\n\n'
        "# my notes about codex\n# remember sandbox mode\n"
    )
    remaining = remove_table(text, "mcp_servers.repowise")

    assert "my notes about codex" in remaining
    assert "remember sandbox mode" in remaining


def test_a_warning_comment_before_a_live_sibling_survives() -> None:
    text = (
        '[mcp_servers.repowise]\ncommand = "repowise"\n\n'
        "# this one talks to prod, do not remove\n"
        '[mcp_servers.prod]\ncommand = "p"\n'
    )
    remaining = remove_table(text, "mcp_servers.repowise")

    assert "do not remove" in remaining
    assert "[mcp_servers.prod]" in remaining


def test_comments_annotating_our_own_keys_go_with_the_table() -> None:
    """Only the *trailing* run is ambiguous. Comments inside the table are ours."""
    text = (
        "[mcp_servers.repowise]\n# generated by repowise\n"
        'command = "repowise"\n[mcp_servers.prod]\nc = 1\n'
    )
    remaining = remove_table(text, "mcp_servers.repowise")

    assert "generated by repowise" not in remaining
    assert "[mcp_servers.prod]" in remaining


def test_a_file_holding_only_our_table_really_does_empty() -> None:
    assert remove_table('[mcp_servers.repowise]\ncommand = "repowise"\n', "mcp_servers.repowise") == ""


def test_a_sibling_with_our_name_as_a_prefix_is_untouched() -> None:
    text = '[mcp_servers.repowiseX]\ncommand = "x"\n'
    assert remove_table(text, "mcp_servers.repowise") == text


def test_crlf_endings_are_not_mixed_on_the_last_line() -> None:
    text = '[mcp_servers.repowise]\r\nc = 1\r\n[mcp_servers.b]\r\nc = 2\r\n'
    remaining = remove_table(text, "mcp_servers.repowise")

    assert "\n" not in remaining.replace("\r\n", "")


# ---------------------------------------------------------------------------
# remove_key_line and table_is_bare
# ---------------------------------------------------------------------------


def test_dropping_one_key_keeps_the_rest_of_the_table_verbatim() -> None:
    text = "[features]\n# why this is on\nhooks = true\nretries = [1, 2, 3]\n"
    remaining = remove_key_line(text, "features", "hooks")

    assert "hooks = true" not in remaining
    assert "retries = [1, 2, 3]" in remaining
    assert "why this is on" in remaining


def test_a_multi_line_value_is_declined_rather_than_cut_at_the_newline() -> None:
    """Cutting the first line orphans the rest into text that is not TOML.

    The caller's own validation then raised, from a helper whose message reads
    "no changes were written", over a file already rewritten and a hooks file
    already deleted.
    """
    text = '[features]\nhooks = [\n  "a",\n  "b",\n]\nother = 1\n'
    assert remove_key_line(text, "features", "hooks") == text


def test_a_single_line_collection_value_is_still_removed() -> None:
    text = "[features]\nhooks = [1, 2]\nother = 1\n"
    remaining = remove_key_line(text, "features", "hooks")

    assert "hooks" not in remaining
    assert "other = 1" in remaining


def test_a_bracket_inside_a_string_does_not_look_like_a_continuation() -> None:
    text = '[features]\nhooks = "a [ b"\nother = 1\n'
    assert "hooks" not in remove_key_line(text, "features", "hooks")


@pytest.mark.parametrize(
    ("value", "complete"),
    [
        ('"plain"', True),
        ("true", True),
        ("[1, 2]", True),
        ("{ a = 1 }", True),
        ('"a # b"', True),
        ('"a [ b"', True),
        ('"a \\" b"', True),
        ("42 # a trailing comment", True),
        ("[", False),
        ("{", False),
        ("[1,", False),
        ('"unterminated', False),
        ('"""', False),
        ("'''", False),
    ],
)
def test_value_completeness_is_judged_per_shape(value: str, complete: bool) -> None:
    """The guard itself, not merely the behaviour given a guard exists.

    Without this, deleting `_value_is_complete` outright left the suite green:
    the surrounding tests all pass whether or not the multi-line refusal is
    reached, because the caller catches the resulting validation failure.
    """
    from repowise.cli.agent_targets.formats.toml_merge import _value_is_complete

    assert _value_is_complete(value) is complete


def test_a_key_line_inside_a_multi_line_string_is_not_a_key() -> None:
    """It is text in someone else's value, and cutting it edited that value."""
    text = '[features]\nbanner = """\nhooks = true\n"""\nother = 1\n'
    assert remove_key_line(text, "features", "hooks") == text


def test_a_key_that_merely_shares_a_prefix_is_left_alone() -> None:
    text = "[features]\nhooks_extra = 1\n"
    assert remove_key_line(text, "features", "hooks") == text


def test_a_feature_value_we_cannot_cut_does_not_abandon_the_server_removal(
    tmp_path: Path,
) -> None:
    """The two edits are independent, and coupling them was the worse bug.

    Accumulating both into one string and gating the write on "did either fail"
    meant a multi-line ``features.hooks`` (Codex's own key, nothing to do with
    us) threw away a clean removal of ``[mcp_servers.repowise]`` and blamed it
    on the repowise entry using an unmatched key spelling. Codex went on
    launching our MCP server while the report said ``kept``.
    """
    import tomllib

    from repowise.cli.agent_targets.registry import get_target
    from repowise.cli.agent_targets.types import Scope

    repo = tmp_path / "repo"
    repo.mkdir()
    config = _write(
        repo,
        '[mcp_servers.repowise]\ncommand = "repowise"\n'
        '[features]\nhooks = [\n  "a",\n]\nother = 1\n',
    )
    hooks = repo / ".codex" / "hooks.json"
    hooks.write_text(
        '{"hooks": {"SessionStart": [{"hooks": [{"command": "repowise-augment"}]}]}}',
        encoding="utf-8",
    )

    get_target("codex").uninstall(Scope.PROJECT, repo_path=repo)

    body = config.read_text(encoding="utf-8")
    tomllib.loads(body)
    # The server entry is gone even though the feature line could not be cut.
    assert "mcp_servers.repowise" not in body
    # And the value we declined to cut is untouched, in full.
    assert "other = 1" in body
    assert '"a",' in body


def test_a_half_refused_removal_is_not_reported_as_clean(tmp_path: Path) -> None:
    """The action is what the runner counts, so it has to carry the bad news.

    A ``REMOVED`` row with a "left in place" reason was counted as clean, so
    ``uninstall --all`` exited 0 under "everything selected is gone" while Codex
    went on launching our MCP server from an entry still in the file. The reason
    text was accurate and nothing read it.
    """
    repo = tmp_path / "repo"
    repo.mkdir()
    # The inline spelling `remove_table`'s regex cannot match, beside a feature
    # flag that removes cleanly, so one half succeeds and one half does not.
    _write(
        repo,
        '[mcp_servers]\nrepowise = { command = "repowise" }\n[features]\nhooks = true\n',
    )

    write = remove_server_config(repo, drop_hooks_feature=True)

    assert write.action is FileAction.KEPT
    assert write.reason and "server entry" in write.reason


def test_both_refusals_are_named_not_just_the_first(tmp_path: Path) -> None:
    repo = tmp_path / "repo"
    repo.mkdir()
    _write(
        repo,
        '[mcp_servers]\nrepowise = { command = "repowise" }\n'
        '[features]\nhooks = [\n  "a",\n]\n',
    )

    write = remove_server_config(repo, drop_hooks_feature=True)

    assert write.action is FileAction.KEPT
    assert "server entry" in (write.reason or "")
    assert "features.hooks" in (write.reason or "")


def test_one_row_per_file(tmp_path: Path) -> None:
    """Two passes over config.toml put two rows for one path in the report."""
    from repowise.cli.agent_targets.registry import get_target
    from repowise.cli.agent_targets.types import Scope

    repo = tmp_path / "repo"
    repo.mkdir()
    _write(repo, '[mcp_servers.repowise]\ncommand = "repowise"\n[features]\nhooks = true\n')

    result = get_target("codex").uninstall(Scope.PROJECT, repo_path=repo)

    paths = [w.path for w in result.files]
    assert len(paths) == len(set(paths)), paths


def test_a_table_holding_a_comment_is_not_bare() -> None:
    assert not table_is_bare("[features]\n# a note\n", "features")
    assert table_is_bare("[features]\n\n", "features")


# ---------------------------------------------------------------------------
# through the target
# ---------------------------------------------------------------------------


def test_uninstall_does_not_delete_a_config_holding_the_users_comments(tmp_path: Path) -> None:
    """The end-to-end form of the critical bug."""
    repo = tmp_path / "repo"
    repo.mkdir()
    path = _write(
        repo,
        '[mcp_servers.repowise]\ncommand = "repowise"\n\n'
        '# [mcp_servers.other]\n# command = "other-server"\n',
    )

    write = remove_server_config(repo, drop_hooks_feature=False)

    assert write.action is FileAction.REMOVED
    assert path.exists(), "the file held the user's commented-out server and was deleted"
    body = path.read_text(encoding="utf-8")
    assert "other-server" in body
    assert "mcp_servers.repowise" not in body


def test_uninstall_still_deletes_a_config_that_was_only_ours(tmp_path: Path) -> None:
    repo = tmp_path / "repo"
    repo.mkdir()
    path = _write(repo, '[mcp_servers.repowise]\ncommand = "repowise"\n')

    write = remove_server_config(repo, drop_hooks_feature=False)

    assert write.action is FileAction.REMOVED
    assert not path.exists()


def test_an_unencodable_value_in_the_users_features_table_does_not_raise(tmp_path: Path) -> None:
    """``[features]`` is Codex's table, so it is dropped a line at a time, not re-rendered."""
    repo = tmp_path / "repo"
    repo.mkdir()
    path = _write(
        repo,
        '[mcp_servers.repowise]\ncommand = "repowise"\n[features]\nhooks = true\nretries = [1, 2, 3]\n',
    )

    write = remove_server_config(repo, drop_hooks_feature=True)

    assert write.action is FileAction.REMOVED
    body = path.read_text(encoding="utf-8")
    assert "hooks = true" not in body
    assert "retries = [1, 2, 3]" in body


def test_an_array_of_tables_spelling_is_refused_rather_than_missed(tmp_path: Path) -> None:
    repo = tmp_path / "repo"
    repo.mkdir()
    _write(repo, '[[mcp_servers.repowise]]\ncommand = "repowise"\n')

    write = remove_server_config(repo, drop_hooks_feature=False)

    assert write.action is FileAction.KEPT
    assert write.reason


def test_an_unparseable_config_declines_instead_of_raising(tmp_path: Path) -> None:
    """It used to raise out of the middle of a batch, after deleting hooks.json.

    ``agents remove --target=all`` reaches codex second of six, so the abort
    took the other four targets with it, and the exception's own text said "no
    changes were written" over a hooks file that had already gone.
    """
    repo = tmp_path / "repo"
    repo.mkdir()
    config = _write(repo, "bad = = toml [[[\n")
    hooks = repo / ".codex" / "hooks.json"
    hooks.write_text(
        '{"hooks": {"SessionStart": [{"hooks": [{"command": "repowise-augment"}]}]}}',
        encoding="utf-8",
    )

    from repowise.cli.agent_targets.registry import get_target
    from repowise.cli.agent_targets.types import Scope

    result = get_target("codex").uninstall(Scope.PROJECT, repo_path=repo)

    kept = [w for w in result.files if w.action is FileAction.KEPT and w.path == config]
    assert kept and kept[0].reason
    assert config.read_text(encoding="utf-8") == "bad = = toml [[[\n"


def test_an_empty_codex_dir_holding_nothing_of_ours_is_not_deleted(tmp_path: Path) -> None:
    """Pruning ran unconditionally, so it removed a directory it never wrote in."""
    from repowise.cli.agent_targets.registry import get_target
    from repowise.cli.agent_targets.types import Scope

    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / ".codex").mkdir()

    result = get_target("codex").uninstall(Scope.PROJECT, repo_path=repo)

    assert all(w.action is not FileAction.REMOVED for w in result.files)
    assert (repo / ".codex").exists()


def test_an_empty_vscode_dir_holding_nothing_of_ours_is_not_deleted(tmp_path: Path) -> None:
    from repowise.cli.agent_targets.registry import get_target
    from repowise.cli.agent_targets.types import Scope

    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / ".vscode").mkdir()

    get_target("vscode").uninstall(Scope.PROJECT, repo_path=repo)

    assert (repo / ".vscode").exists()


@pytest.mark.parametrize(
    "text",
    [
        '[mcp_servers.repowise]\ncommand = "repowise"\n[mcp_servers.repowise.env]\nA = "1"\n',
        '[mcp_servers.repowise] # trailing comment\ncommand = "repowise"\n',
    ],
)
def test_a_spelling_the_remover_cannot_match_is_kept_with_a_reason(
    tmp_path: Path, text: str
) -> None:
    repo = tmp_path / "repo"
    repo.mkdir()
    _write(repo, text)

    write = remove_server_config(repo, drop_hooks_feature=False)

    assert write.action is FileAction.KEPT
    assert write.reason