318 lines
16 KiB
Python
318 lines
16 KiB
Python
# #region Test.Tooling.EvidenceLinkMigration [C:3] [TYPE Module] [SEMANTICS evidence,migration,negative,git]
|
|
# @TEST_INVARIANT A pinned synthetic Git source admits only whole reviewed units; any stale or ambiguous unit writes nothing.
|
|
import hashlib
|
|
import importlib.util
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
|
|
import pytest
|
|
|
|
ROOT = Path(__file__).resolve().parents[3]
|
|
spec = importlib.util.spec_from_file_location("evidence_link_migration", ROOT / "scripts/migrate_evidence_links.py")
|
|
migration = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(migration)
|
|
DOC = "docs/synthetic.md"
|
|
TEXT = "Кириллица: [old](../specs/050-mcp-interface/evidence/old.json)\n"
|
|
INDEX_TEXT = '<a id="evidence-synthetic"></a>\n'
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Digest [C:1] [TYPE Function]
|
|
def sha(value):
|
|
return hashlib.sha256(value.encode()).hexdigest()
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Digest
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Git [C:1] [TYPE Function]
|
|
def git(repo, *args):
|
|
return subprocess.check_output(["git", "-C", str(repo), *args], stderr=subprocess.PIPE, text=True).strip()
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Git
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Repository [C:3] [TYPE Function]
|
|
@pytest.fixture
|
|
def repository(tmp_path):
|
|
git(tmp_path, "init", "-q")
|
|
git(tmp_path, "config", "user.name", "Synthetic migration")
|
|
git(tmp_path, "config", "user.email", "synthetic@example.invalid")
|
|
for path, content in ((DOC, TEXT), (migration.INDEX, INDEX_TEXT)):
|
|
target = tmp_path / path
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
target.write_text(content)
|
|
git(tmp_path, "add", "-A")
|
|
git(tmp_path, "commit", "-qm", "synthetic source")
|
|
commit = git(tmp_path, "rev-parse", "HEAD")
|
|
original = "../specs/050-mcp-interface/evidence/old.json"
|
|
start = TEXT.index(original)
|
|
mapping = {"schema_version": 1, "source_head": commit, "peeled_tag_commit": "a" * 40,
|
|
"offset_unit": "unicode_codepoints_in_utf8_decoded_document",
|
|
"index": {"path": migration.INDEX, "sha256": sha(INDEX_TEXT), "anchor_count": 1},
|
|
"documents": {DOC: {"sha256": sha(TEXT)}},
|
|
"counts": {"documents": 1, "edit_units": 1, "occurrences": 1},
|
|
"references": [{"doc": DOC, "span_start": start, "span_end": start + len(original),
|
|
"original_target_sha256": sha(original)}],
|
|
"edit_units": [{"doc": DOC, "source_sha256": sha(TEXT), "span_start": start,
|
|
"span_end": start + len(original), "original_sha256": sha(original),
|
|
"action": "rewrite_link_destination_only", "reference_anchors": ["evidence-synthetic"],
|
|
"replacement": "../specs/050-mcp-interface/evidence-index.md#evidence-synthetic",
|
|
"original_reference_spans": [{"start": start, "end": start + len(original), "sha256": sha(original)}]}]}
|
|
return tmp_path, commit, mapping
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Repository
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Prepare [C:1] [TYPE Function]
|
|
def prepare(repository):
|
|
repo, commit, mapping = repository
|
|
raw = json.dumps(mapping, ensure_ascii=False)
|
|
path = repo / "mapping.json"
|
|
path.write_text(raw)
|
|
return migration.prepare(repo, path, sha(raw), commit, migration.INDEX)
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Prepare
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Valid [C:2] [TYPE Function]
|
|
def test_exact_unicode_span_check_is_inert_and_apply_preserves_label(repository):
|
|
repo, _, _ = repository
|
|
outputs, counts = prepare(repository)
|
|
assert (repo / DOC).read_text() == TEXT
|
|
assert outputs == {DOC: "Кириллица: [old](../specs/050-mcp-interface/evidence-index.md#evidence-synthetic)\n".encode()}
|
|
assert counts == {"documents": 1, "edit_units": 1, "occurrences": 1}
|
|
migration.apply(repo, outputs, sha(INDEX_TEXT), {"evidence-synthetic"})
|
|
assert (repo / DOC).read_text() == "Кириллица: [old](../specs/050-mcp-interface/evidence-index.md#evidence-synthetic)\n"
|
|
assert (repo / migration.INDEX).read_text() == INDEX_TEXT
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Valid
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Invalid [C:3] [TYPE Function]
|
|
@pytest.mark.parametrize("mutation,code", [
|
|
("stale_commit", "EVIDENCE_MIGRATION_CONTRACT_INVALID"),
|
|
("stale_source", "EVIDENCE_MIGRATION_SOURCE_CONFLICT"),
|
|
("stale_span", "EVIDENCE_MIGRATION_SPAN_CONFLICT"),
|
|
("byte_offsets", "EVIDENCE_MIGRATION_SPAN_INVALID"),
|
|
("orphan", "EVIDENCE_MIGRATION_REFERENCE_CONFLICT"),
|
|
("duplicate", "EVIDENCE_MIGRATION_REFERENCE_CONFLICT"),
|
|
("unknown_anchor", "EVIDENCE_MIGRATION_REPLACEMENT_INVALID"),
|
|
("arbitrary_destination", "EVIDENCE_MIGRATION_REPLACEMENT_INVALID"),
|
|
("unknown_action", "EVIDENCE_MIGRATION_REPLACEMENT_INVALID"),
|
|
("wrong_count", "EVIDENCE_MIGRATION_COUNTS_CONFLICT"),
|
|
])
|
|
def test_invalid_mapping_refuses_without_mutating_document(repository, mutation, code):
|
|
repo, _, mapping = repository
|
|
unit = mapping["edit_units"][0]
|
|
if mutation == "stale_commit":
|
|
mapping["source_head"] = "0" * 40
|
|
elif mutation == "stale_source":
|
|
(repo / DOC).write_text(TEXT + "unreviewed\n")
|
|
elif mutation == "stale_span":
|
|
unit["original_sha256"] = "0" * 64
|
|
elif mutation == "byte_offsets":
|
|
unit["span_start"] += 9
|
|
unit["span_end"] += 9
|
|
elif mutation == "orphan":
|
|
mapping["references"] = []
|
|
elif mutation == "duplicate":
|
|
mapping["references"] *= 2
|
|
elif mutation == "unknown_anchor":
|
|
unit["reference_anchors"] = ["evidence-foreign"]
|
|
elif mutation == "arbitrary_destination":
|
|
unit["replacement"] = "../../foreign.md#evidence-synthetic"
|
|
elif mutation == "unknown_action":
|
|
unit["action"] = "guess_latest"
|
|
else:
|
|
mapping["counts"]["documents"] = 2
|
|
before = (repo / DOC).read_bytes()
|
|
with pytest.raises(migration.MigrationRefusal) as refusal:
|
|
prepare(repository)
|
|
assert refusal.value.code == code
|
|
assert (repo / DOC).read_bytes() == before
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Invalid
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.DigestMismatch [C:2] [TYPE Function]
|
|
def test_external_mapping_digest_and_exact_head_are_mandatory(repository):
|
|
repo, commit, mapping = repository
|
|
path = repo / "mapping.json"
|
|
path.write_text(json.dumps(mapping))
|
|
with pytest.raises(migration.MigrationRefusal, match="EVIDENCE_MIGRATION_MAPPING_CONFLICT"):
|
|
migration.prepare(repo, path, "0" * 64, commit, migration.INDEX)
|
|
with pytest.raises(migration.MigrationRefusal, match="EVIDENCE_MIGRATION_COMMIT_CONFLICT"):
|
|
migration.prepare(repo, path, "0" * 64, commit[:8], migration.INDEX)
|
|
assert (repo / DOC).read_text() == TEXT
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.DigestMismatch
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Symlink [C:2] [TYPE Function]
|
|
def test_uncommitted_symlink_cannot_redirect_reviewed_document_write(repository):
|
|
repo, _, _ = repository
|
|
target = repo / DOC
|
|
target.unlink()
|
|
external = repo.parent / "external.md"
|
|
external.write_text(TEXT)
|
|
target.symlink_to(external)
|
|
with pytest.raises(migration.MigrationRefusal, match="EVIDENCE_MIGRATION_PATH_INVALID"):
|
|
prepare(repository)
|
|
assert external.read_text() == TEXT
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Symlink
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.CompleteValidation [C:3] [TYPE Function]
|
|
def test_apply_cli_validates_every_document_before_first_write(repository):
|
|
repo, commit, mapping = repository
|
|
second = "docs/second.md"
|
|
(repo / second).write_text(TEXT)
|
|
git(repo, "add", second)
|
|
git(repo, "commit", "-qm", "second independently authored document")
|
|
commit = git(repo, "rev-parse", "HEAD")
|
|
mapping["source_head"] = commit
|
|
mapping["documents"][second] = {"sha256": "0" * 64}
|
|
raw = json.dumps(mapping)
|
|
packet = repo / "mapping.json"
|
|
packet.write_text(raw)
|
|
result = subprocess.run([sys.executable, str(ROOT / "scripts/migrate_evidence_links.py"),
|
|
"--mapping", str(packet), "--mapping-sha256", sha(raw), "--commit", commit,
|
|
"--index", migration.INDEX, "--apply"], cwd=repo, capture_output=True, text=True)
|
|
assert result.returncode == 2
|
|
assert json.loads(result.stdout) == {"status": "REFUSED", "error_code": "EVIDENCE_MIGRATION_SOURCE_CONFLICT"}
|
|
assert (repo / DOC).read_text() == TEXT
|
|
assert (repo / second).read_text() == TEXT
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.CompleteValidation
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.WholeUnits [C:3] [TYPE Function]
|
|
@pytest.mark.parametrize("original,action,replacement", [
|
|
("`evidence/old.json`", "replace_whole_backticked_reference_with_index_link",
|
|
"[`evidence/old.json`](../specs/050-mcp-interface/evidence-index.md#evidence-synthetic)"),
|
|
("```sh\npython capture.py --output evidence/old.json\n```\n",
|
|
"replace_whole_code_unit_with_index_link_outside_code",
|
|
"Historical unexecuted command: [original](https://git.bebesh.ru/busya/ss-tools/src/tag/stage1-go/docs/synthetic.md); "
|
|
"[evidence](../specs/050-mcp-interface/evidence-index.md#evidence-synthetic).\n"),
|
|
])
|
|
def test_whole_inline_and_command_units_are_replaced_without_links_inside_code(repository, original, action, replacement):
|
|
repo, _, mapping = repository
|
|
source_text = "Пример:\n" + original + "End\n"
|
|
(repo / DOC).write_text(source_text)
|
|
git(repo, "add", DOC)
|
|
git(repo, "commit", "-qm", "synthetic whole unit")
|
|
mapping["source_head"] = git(repo, "rev-parse", "HEAD")
|
|
mapping["documents"][DOC]["sha256"] = sha(source_text)
|
|
token = "evidence/old.json"
|
|
start = source_text.index(token)
|
|
reference = {"start": start, "end": start + len(token), "sha256": sha(token)}
|
|
mapping["references"] = [{"doc": DOC, "span_start": reference["start"], "span_end": reference["end"],
|
|
"original_target_sha256": reference["sha256"]}]
|
|
mapping["edit_units"] = [{"doc": DOC, "source_sha256": sha(source_text), "span_start": len("Пример:\n"),
|
|
"span_end": len("Пример:\n") + len(original), "original_sha256": sha(original), "action": action,
|
|
"replacement": replacement, "reference_anchors": ["evidence-synthetic"], "original_reference_spans": [reference]}]
|
|
if action == "replace_whole_code_unit_with_index_link_outside_code":
|
|
mapping["edit_units"][0].update(original_command_source_commit="a" * 40, original_command_source_path=DOC)
|
|
outputs, _ = prepare((repo, mapping["source_head"], mapping))
|
|
assert outputs[DOC].decode() == "Пример:\n" + replacement + "End\n"
|
|
assert (repo / DOC).read_text() == source_text
|
|
assert "```" not in outputs[DOC].decode()
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.WholeUnits
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Overlap [C:3] [TYPE Function]
|
|
def test_overlapping_valid_hashed_units_refuse_even_with_complete_distinct_reference_join(repository):
|
|
repo, _, mapping = repository
|
|
outer = mapping["edit_units"][0]
|
|
inner = json.loads(json.dumps(outer))
|
|
inner["span_end"] -= 1
|
|
selected = TEXT[inner["span_start"]:inner["span_end"]]
|
|
inner["original_sha256"] = sha(selected)
|
|
inner["original_reference_spans"][0].update(end=inner["span_end"], sha256=sha(selected))
|
|
mapping["edit_units"].append(inner)
|
|
mapping["references"].append({"doc": DOC, "span_start": inner["span_start"], "span_end": inner["span_end"],
|
|
"original_target_sha256": sha(selected)})
|
|
mapping["counts"].update(edit_units=2, occurrences=2)
|
|
with pytest.raises(migration.MigrationRefusal, match="EVIDENCE_MIGRATION_SPAN_OVERLAP"):
|
|
prepare(repository)
|
|
assert (repo / DOC).read_text() == TEXT
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Overlap
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Index [C:2] [TYPE Function]
|
|
def test_committed_duplicate_index_anchor_refuses_before_document_write(repository):
|
|
repo, _, mapping = repository
|
|
duplicate = INDEX_TEXT * 2
|
|
(repo / migration.INDEX).write_text(duplicate)
|
|
git(repo, "add", migration.INDEX)
|
|
git(repo, "commit", "-qm", "synthetic duplicate index")
|
|
mapping["source_head"] = git(repo, "rev-parse", "HEAD")
|
|
mapping["index"]["sha256"] = sha(duplicate)
|
|
mapping["index"]["anchor_count"] = 2
|
|
with pytest.raises(migration.MigrationRefusal, match="EVIDENCE_MIGRATION_INDEX_INVALID"):
|
|
prepare((repo, mapping["source_head"], mapping))
|
|
assert (repo / DOC).read_text() == TEXT
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Index
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.ActualDestinations [C:3] [TYPE Function]
|
|
@pytest.mark.parametrize("action,replacement", [
|
|
("replace_whole_backticked_reference_with_index_link", "[`old`](../../foreign.md) #evidence-synthetic"),
|
|
("replace_whole_code_unit_with_index_link_outside_code",
|
|
"[original](https://git.bebesh.ru/busya/ss-tools/src/tag/stage1-go/docs/foreign.md) "
|
|
"[result](../specs/050-mcp-interface/evidence-index.md#evidence-synthetic)"),
|
|
("replace_whole_code_unit_with_index_link_outside_code",
|
|
"[original](https://git.bebesh.ru/busya/ss-tools/src/tag/stage1-go/docs/synthetic.md) "
|
|
"[result](../../foreign.md) #evidence-synthetic"),
|
|
])
|
|
def test_anchor_text_cannot_authorize_foreign_inline_or_command_destinations(action, replacement):
|
|
original = "`old`"
|
|
unit = {"doc": DOC, "action": action, "replacement": replacement, "span_start": 0,
|
|
"span_end": len(original), "original_sha256": sha(original), "reference_anchors": ["evidence-synthetic"],
|
|
"original_command_source_commit": "a" * 40, "original_command_source_path": DOC,
|
|
"original_reference_spans": [{"start": 1, "end": 4, "sha256": sha("old")}]}
|
|
with pytest.raises(migration.MigrationRefusal, match="EVIDENCE_MIGRATION_REPLACEMENT_INVALID"):
|
|
migration.validate_unit(unit, original, {"evidence-synthetic"}, "a" * 40)
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.ActualDestinations
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Post [C:2] [TYPE Function]
|
|
@pytest.mark.parametrize("text,code", [
|
|
("[old](../specs/050-mcp-interface/evidence/old.json)", "EVIDENCE_MIGRATION_POST_RAW_TARGET"),
|
|
("`evidence/old.json`", "EVIDENCE_MIGRATION_POST_RAW_TARGET"),
|
|
("```sh\ncapture --output specs/050-mcp-interface/evidence/old.json\n```", "EVIDENCE_MIGRATION_POST_RAW_TARGET"),
|
|
("[index](../specs/050-mcp-interface/evidence-index.md#foreign)", "EVIDENCE_MIGRATION_POST_INDEX_INVALID"),
|
|
])
|
|
def test_post_scan_refuses_stale_local_targets_and_unresolved_index_anchors(text, code):
|
|
with pytest.raises(migration.MigrationRefusal, match=code):
|
|
migration.post_scan(DOC, text, {"evidence-synthetic"})
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Post
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.Readback [C:2] [TYPE Function]
|
|
def test_apply_readback_rejects_failed_replacement_instead_of_emitting_applied(repository, monkeypatch):
|
|
repo, _, _ = repository
|
|
outputs, _ = prepare(repository)
|
|
monkeypatch.setattr(migration.os, "replace", lambda *args: None)
|
|
with pytest.raises(migration.MigrationRefusal, match="EVIDENCE_MIGRATION_POST_READBACK_CONFLICT"):
|
|
migration.apply(repo, outputs, sha(INDEX_TEXT), {"evidence-synthetic"})
|
|
assert (repo / DOC).read_text() == TEXT
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.Readback
|
|
|
|
|
|
# #region Test.Tooling.EvidenceLinkMigration.IndexDrift [C:3] [TYPE Function]
|
|
def test_main_cannot_adopt_index_modified_after_pinned_preflight(repository, monkeypatch, capsys):
|
|
repo, commit, mapping = repository
|
|
raw = json.dumps(mapping)
|
|
packet = repo / "mapping.json"
|
|
packet.write_text(raw)
|
|
original_prepare = migration.prepare
|
|
|
|
def index_drift(*args):
|
|
result = original_prepare(*args)
|
|
(repo / migration.INDEX).write_text(INDEX_TEXT + "unreviewed index mutation\n")
|
|
return result
|
|
|
|
monkeypatch.setattr(migration, "prepare", index_drift)
|
|
monkeypatch.chdir(repo)
|
|
monkeypatch.setattr(sys, "argv", ["migration", "--mapping", str(packet), "--mapping-sha256", sha(raw),
|
|
"--commit", commit, "--index", migration.INDEX, "--apply"])
|
|
assert migration.main() == 2
|
|
assert json.loads(capsys.readouterr().out) == {"status": "REFUSED", "error_code": "EVIDENCE_MIGRATION_POST_INDEX_INVALID"}
|
|
assert (repo / DOC).read_text() == TEXT
|
|
# #endregion Test.Tooling.EvidenceLinkMigration.IndexDrift
|
|
# #endregion Test.Tooling.EvidenceLinkMigration
|