litmus-cli 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- litmus/__init__.py +27 -0
- litmus/artifact.py +179 -0
- litmus/cli.py +342 -0
- litmus/detectors/__init__.py +3 -0
- litmus/detectors/base.py +56 -0
- litmus/exif.py +158 -0
- litmus/inspectors/__init__.py +32 -0
- litmus/inspectors/base.py +36 -0
- litmus/inspectors/c2pa.py +159 -0
- litmus/inspectors/file_metadata.py +210 -0
- litmus/inspectors/office_metadata.py +54 -0
- litmus/inspectors/text_markers.py +75 -0
- litmus/inspectors/unicode_scan.py +308 -0
- litmus/io.py +54 -0
- litmus/model.py +173 -0
- litmus/office.py +198 -0
- litmus/pipeline.py +464 -0
- litmus/providers/__init__.py +17 -0
- litmus/providers/registry.py +239 -0
- litmus/reporting.py +150 -0
- litmus/server.py +176 -0
- litmus/transform/__init__.py +12 -0
- litmus/transform/base.py +30 -0
- litmus/transform/code_structural.py +119 -0
- litmus/transform/file_strip.py +148 -0
- litmus/transform/text_normalize.py +257 -0
- litmus/validate/__init__.py +3 -0
- litmus/validate/binary.py +75 -0
- litmus/validate/code.py +165 -0
- litmus/validate/office.py +73 -0
- litmus/validate/structural.py +136 -0
- litmus/validate/text.py +158 -0
- litmus/validate/treesitter_code.py +129 -0
- litmus/web_ui.py +728 -0
- litmus_cli-0.3.0.dist-info/METADATA +108 -0
- litmus_cli-0.3.0.dist-info/RECORD +39 -0
- litmus_cli-0.3.0.dist-info/WHEEL +4 -0
- litmus_cli-0.3.0.dist-info/entry_points.txt +2 -0
- litmus_cli-0.3.0.dist-info/licenses/LICENSE +21 -0
litmus/validate/code.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Validation for source-code transformation.
|
|
2
|
+
|
|
3
|
+
This is the tool's differentiator. A metadata/whitespace transform on code is
|
|
4
|
+
only safe if it did not change program behaviour, and most tools in this space
|
|
5
|
+
merely *assert* that. We try to *prove* it, per language, with whatever
|
|
6
|
+
toolchain is genuinely available:
|
|
7
|
+
|
|
8
|
+
* **Python** — parse both versions to an AST and compare ``ast.dump`` with
|
|
9
|
+
attributes excluded. Line/column positions move when whitespace changes but
|
|
10
|
+
the tree does not, so an equal dump is a proof that the program structure is
|
|
11
|
+
identical. If a change lands inside a string literal (e.g. a zero-width
|
|
12
|
+
character that was *inside* a string), the dump differs and we report a
|
|
13
|
+
proven change rather than pretending it was safe. Stdlib only; always runs.
|
|
14
|
+
* **JavaScript** — ``node --check`` proves the result still parses. It cannot
|
|
15
|
+
prove structural equivalence, so semantic preservation stays ``unproven``.
|
|
16
|
+
* **Everything else** — no toolchain here, so both checks are ``unproven``.
|
|
17
|
+
|
|
18
|
+
``passed`` semantics: ``True`` proven, ``False`` proven-not, ``None`` could not
|
|
19
|
+
be determined. The pipeline decides acceptance from these; it never treats
|
|
20
|
+
``None`` as ``True``.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import ast
|
|
26
|
+
import shutil
|
|
27
|
+
import subprocess
|
|
28
|
+
import tempfile
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from ..model import Check, ValidationReport
|
|
32
|
+
from .treesitter_code import validate_code_treesitter
|
|
33
|
+
|
|
34
|
+
_NODE_CHECK_TIMEOUT_S = 10.0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _python_report(before: str, after: str) -> ValidationReport:
|
|
38
|
+
checks: list[Check] = []
|
|
39
|
+
try:
|
|
40
|
+
after_tree = ast.parse(after)
|
|
41
|
+
parses = True
|
|
42
|
+
except SyntaxError as exc:
|
|
43
|
+
after_tree = None
|
|
44
|
+
parses = False
|
|
45
|
+
parse_detail = f"Output does not parse as Python: {exc}"
|
|
46
|
+
else:
|
|
47
|
+
parse_detail = "Output parses as valid Python."
|
|
48
|
+
|
|
49
|
+
checks.append(Check(name="code_parses_after", passed=parses, detail=parse_detail))
|
|
50
|
+
|
|
51
|
+
preserved: bool | None
|
|
52
|
+
if not parses or after_tree is None:
|
|
53
|
+
preserved = None
|
|
54
|
+
detail = "Cannot compare structure because the output does not parse."
|
|
55
|
+
else:
|
|
56
|
+
try:
|
|
57
|
+
before_dump = ast.dump(ast.parse(before), include_attributes=False)
|
|
58
|
+
after_dump = ast.dump(after_tree, include_attributes=False)
|
|
59
|
+
except SyntaxError:
|
|
60
|
+
preserved = None
|
|
61
|
+
detail = "Original does not parse as Python; structural equivalence is unprovable."
|
|
62
|
+
else:
|
|
63
|
+
preserved = before_dump == after_dump
|
|
64
|
+
detail = (
|
|
65
|
+
"Abstract syntax trees are identical: the transform provably preserved "
|
|
66
|
+
"program structure."
|
|
67
|
+
if preserved
|
|
68
|
+
else "Abstract syntax trees differ: the transform changed the program "
|
|
69
|
+
"(a change likely landed inside a string or comment-bearing node)."
|
|
70
|
+
)
|
|
71
|
+
checks.append(
|
|
72
|
+
Check(
|
|
73
|
+
name="code_semantics_preserved",
|
|
74
|
+
passed=preserved,
|
|
75
|
+
detail=detail,
|
|
76
|
+
measurements={"language": "python", "method": "ast.dump equality"},
|
|
77
|
+
)
|
|
78
|
+
)
|
|
79
|
+
decided = [c.passed for c in checks if c.passed is not None]
|
|
80
|
+
return ValidationReport(
|
|
81
|
+
performed=True, all_passed=all(decided) if decided else None, checks=checks
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _node_check(after: str, suffix: str) -> bool | None:
|
|
86
|
+
node = shutil.which("node")
|
|
87
|
+
if node is None:
|
|
88
|
+
return None
|
|
89
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
90
|
+
target = Path(tmp) / f"check{suffix}"
|
|
91
|
+
target.write_text(after, encoding="utf-8")
|
|
92
|
+
try:
|
|
93
|
+
result = subprocess.run( # noqa: S603 - fixed argv, no shell
|
|
94
|
+
[node, "--check", str(target)],
|
|
95
|
+
capture_output=True,
|
|
96
|
+
timeout=_NODE_CHECK_TIMEOUT_S,
|
|
97
|
+
check=False,
|
|
98
|
+
)
|
|
99
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
100
|
+
return None
|
|
101
|
+
return result.returncode == 0
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _javascript_report(after: str, suffix: str) -> ValidationReport:
|
|
105
|
+
parses = _node_check(after, suffix)
|
|
106
|
+
checks = [
|
|
107
|
+
Check(
|
|
108
|
+
name="code_parses_after",
|
|
109
|
+
passed=parses,
|
|
110
|
+
detail={
|
|
111
|
+
True: "Output still parses under `node --check`.",
|
|
112
|
+
False: "Output no longer parses under `node --check`.",
|
|
113
|
+
None: "`node` is unavailable; parse validity could not be checked.",
|
|
114
|
+
}[parses],
|
|
115
|
+
),
|
|
116
|
+
Check(
|
|
117
|
+
name="code_semantics_preserved",
|
|
118
|
+
passed=None,
|
|
119
|
+
detail=(
|
|
120
|
+
"Not proven. `node --check` confirms syntax only; no JavaScript AST "
|
|
121
|
+
"comparison is available, so structural equivalence is unproven."
|
|
122
|
+
),
|
|
123
|
+
measurements={"language": "javascript", "method": "node --check (syntax only)"},
|
|
124
|
+
),
|
|
125
|
+
]
|
|
126
|
+
decided = [c.passed for c in checks if c.passed is not None]
|
|
127
|
+
return ValidationReport(
|
|
128
|
+
performed=True, all_passed=all(decided) if decided else None, checks=checks
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _unsupported_report(language: str | None) -> ValidationReport:
|
|
133
|
+
return ValidationReport(
|
|
134
|
+
performed=True,
|
|
135
|
+
all_passed=None,
|
|
136
|
+
checks=[
|
|
137
|
+
Check(
|
|
138
|
+
name="code_semantics_preserved",
|
|
139
|
+
passed=None,
|
|
140
|
+
detail=(
|
|
141
|
+
f"No structural validator is available for {language or 'this language'} "
|
|
142
|
+
"in this environment; semantic preservation is unproven. Review the diff, "
|
|
143
|
+
"or supply a toolchain (compile/test-based validation is planned)."
|
|
144
|
+
),
|
|
145
|
+
measurements={"language": language or "unknown", "method": "none"},
|
|
146
|
+
)
|
|
147
|
+
],
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def validate_code(before: str, after: str, language: str | None) -> ValidationReport:
|
|
152
|
+
# Python's stdlib AST is the most precise and needs no optional dependency,
|
|
153
|
+
# so it stays primary. Everything else prefers tree-sitter (the `code`
|
|
154
|
+
# extra) and falls back to a weaker per-language check or a refusal.
|
|
155
|
+
if language == "python":
|
|
156
|
+
return _python_report(before, after)
|
|
157
|
+
|
|
158
|
+
treesitter = validate_code_treesitter(before, after, language)
|
|
159
|
+
if treesitter is not None:
|
|
160
|
+
return treesitter
|
|
161
|
+
|
|
162
|
+
if language == "javascript":
|
|
163
|
+
# Syntax-only fallback when the `code` extra is not installed.
|
|
164
|
+
return _javascript_report(after, ".js")
|
|
165
|
+
return _unsupported_report(language)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Validation for Office Open XML metadata stripping.
|
|
2
|
+
|
|
3
|
+
The proof mirrors the image pixel-identity proof: metadata was removed *and the
|
|
4
|
+
document content is provably unchanged*. We show it by comparing the
|
|
5
|
+
decompressed bytes of every non-metadata archive member before and after. If
|
|
6
|
+
any content part differs, the strip touched more than metadata and is rejected.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from ..model import Check, ValidationReport
|
|
12
|
+
from ..office import content_members, is_ooxml
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def validate_office_strip(before: bytes, after: bytes) -> ValidationReport:
|
|
16
|
+
checks: list[Check] = []
|
|
17
|
+
|
|
18
|
+
parses = is_ooxml(after)
|
|
19
|
+
checks.append(
|
|
20
|
+
Check(
|
|
21
|
+
name="office_parses_after",
|
|
22
|
+
passed=parses,
|
|
23
|
+
detail="Output is still a valid Office Open XML document."
|
|
24
|
+
if parses
|
|
25
|
+
else "Output no longer reads as an Office document; the strip corrupted it.",
|
|
26
|
+
)
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
before_members = content_members(before)
|
|
30
|
+
after_members = content_members(after)
|
|
31
|
+
if not parses or before_members is None or after_members is None:
|
|
32
|
+
preserved: bool | None = None
|
|
33
|
+
detail = "Cannot compare content because an archive could not be read."
|
|
34
|
+
measurements: dict[str, object] = {}
|
|
35
|
+
else:
|
|
36
|
+
same_names = set(before_members) == set(after_members)
|
|
37
|
+
same_bytes = same_names and all(
|
|
38
|
+
before_members[name] == after_members[name] for name in before_members
|
|
39
|
+
)
|
|
40
|
+
preserved = same_bytes
|
|
41
|
+
changed = sorted(
|
|
42
|
+
name
|
|
43
|
+
for name in set(before_members) & set(after_members)
|
|
44
|
+
if before_members[name] != after_members[name]
|
|
45
|
+
)
|
|
46
|
+
detail = (
|
|
47
|
+
"Every document part (text, sheets, slides, media) is byte-for-byte "
|
|
48
|
+
"identical; only metadata was removed."
|
|
49
|
+
if preserved
|
|
50
|
+
else "A document part changed; the strip altered more than metadata."
|
|
51
|
+
)
|
|
52
|
+
measurements = {
|
|
53
|
+
"content_parts": len(before_members),
|
|
54
|
+
"changed_parts": changed[:10],
|
|
55
|
+
"added_or_removed_parts": sorted(
|
|
56
|
+
set(before_members).symmetric_difference(after_members)
|
|
57
|
+
)[:10],
|
|
58
|
+
}
|
|
59
|
+
checks.append(
|
|
60
|
+
Check(
|
|
61
|
+
name="document_content_identical",
|
|
62
|
+
passed=preserved,
|
|
63
|
+
detail=detail,
|
|
64
|
+
measurements=measurements,
|
|
65
|
+
)
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
decided = [c.passed for c in checks if c.passed is not None]
|
|
69
|
+
return ValidationReport(
|
|
70
|
+
performed=True,
|
|
71
|
+
all_passed=all(decided) if decided else None,
|
|
72
|
+
checks=checks,
|
|
73
|
+
)
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Proof for structural code transforms.
|
|
2
|
+
|
|
3
|
+
Token/AST equality cannot gate a transform whose purpose is to change the
|
|
4
|
+
tree, so each structural operation gets its own validator. The proof is
|
|
5
|
+
computed from the before/after pair alone — it does not trust the transform's
|
|
6
|
+
account of what it did.
|
|
7
|
+
|
|
8
|
+
For Python import removal the obligations are:
|
|
9
|
+
|
|
10
|
+
1. the output parses;
|
|
11
|
+
2. the top-level AST delta is *exactly* the removal of whole
|
|
12
|
+
``import``/``from-import`` statements: every surviving statement is
|
|
13
|
+
structurally identical and in order, and nothing was added. A change
|
|
14
|
+
nested anywhere else would alter its enclosing top-level statement's
|
|
15
|
+
``ast.dump`` and fail this check;
|
|
16
|
+
3. every removed statement is neither a ``__future__`` import nor a star
|
|
17
|
+
import, and every name it bound is unreferenced in the original — where
|
|
18
|
+
"referenced" includes identifiers inside string literals (``__all__``,
|
|
19
|
+
quoted annotations, dynamic lookups).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import ast
|
|
25
|
+
|
|
26
|
+
from ..model import Check, ValidationReport
|
|
27
|
+
from ..transform.code_structural import import_bindings, referenced_names
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _parse(source: str) -> ast.Module | None:
|
|
31
|
+
try:
|
|
32
|
+
return ast.parse(source)
|
|
33
|
+
except SyntaxError:
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def validate_python_import_removal(before: str, after: str) -> ValidationReport:
|
|
38
|
+
checks: list[Check] = []
|
|
39
|
+
|
|
40
|
+
after_tree = _parse(after)
|
|
41
|
+
checks.append(
|
|
42
|
+
Check(
|
|
43
|
+
name="structural_output_parses",
|
|
44
|
+
passed=after_tree is not None,
|
|
45
|
+
detail="Output parses as valid Python."
|
|
46
|
+
if after_tree is not None
|
|
47
|
+
else "Output does not parse as Python.",
|
|
48
|
+
)
|
|
49
|
+
)
|
|
50
|
+
before_tree = _parse(before)
|
|
51
|
+
|
|
52
|
+
removed: list[ast.Import | ast.ImportFrom] = []
|
|
53
|
+
delta_ok: bool | None
|
|
54
|
+
if after_tree is None or before_tree is None:
|
|
55
|
+
delta_ok = None
|
|
56
|
+
delta_detail = "Cannot compare structure: the {} does not parse.".format(
|
|
57
|
+
"output" if after_tree is None else "original"
|
|
58
|
+
)
|
|
59
|
+
else:
|
|
60
|
+
after_dumps = [ast.dump(s, include_attributes=False) for s in after_tree.body]
|
|
61
|
+
i = 0
|
|
62
|
+
problem: str | None = None
|
|
63
|
+
for stmt in before_tree.body:
|
|
64
|
+
if i < len(after_dumps) and ast.dump(stmt, include_attributes=False) == after_dumps[i]:
|
|
65
|
+
i += 1
|
|
66
|
+
elif isinstance(stmt, ast.Import | ast.ImportFrom):
|
|
67
|
+
removed.append(stmt)
|
|
68
|
+
else:
|
|
69
|
+
problem = f"a non-import statement changed or disappeared (line {stmt.lineno})"
|
|
70
|
+
break
|
|
71
|
+
if problem is None and i != len(after_dumps):
|
|
72
|
+
problem = "the output contains statements that are not in the original"
|
|
73
|
+
delta_ok = problem is None
|
|
74
|
+
delta_detail = (
|
|
75
|
+
f"The only top-level difference is the removal of {len(removed)} whole "
|
|
76
|
+
"import statement(s); every other statement is structurally identical."
|
|
77
|
+
if delta_ok
|
|
78
|
+
else f"The delta is not import removal only: {problem}."
|
|
79
|
+
)
|
|
80
|
+
checks.append(
|
|
81
|
+
Check(
|
|
82
|
+
name="structural_delta_is_import_removal_only",
|
|
83
|
+
passed=delta_ok,
|
|
84
|
+
detail=delta_detail,
|
|
85
|
+
measurements={"removed_statements": len(removed)},
|
|
86
|
+
)
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
removed_bindings: list[str] = []
|
|
90
|
+
unreferenced: bool | None
|
|
91
|
+
if delta_ok is not True or before_tree is None:
|
|
92
|
+
unreferenced = None
|
|
93
|
+
unref_detail = "Not evaluated: the delta was not proven to be import removal only."
|
|
94
|
+
else:
|
|
95
|
+
referenced = referenced_names(before_tree)
|
|
96
|
+
problems: list[str] = []
|
|
97
|
+
for stmt in removed:
|
|
98
|
+
if isinstance(stmt, ast.ImportFrom) and stmt.module == "__future__":
|
|
99
|
+
problems.append(
|
|
100
|
+
f"line {stmt.lineno}: __future__ imports change compilation "
|
|
101
|
+
"and are never removable"
|
|
102
|
+
)
|
|
103
|
+
continue
|
|
104
|
+
bindings = import_bindings(stmt)
|
|
105
|
+
if bindings is None:
|
|
106
|
+
problems.append(f"line {stmt.lineno}: star-import bindings are unknowable")
|
|
107
|
+
continue
|
|
108
|
+
removed_bindings.extend(bindings)
|
|
109
|
+
problems.extend(
|
|
110
|
+
f"'{name}' (line {stmt.lineno}) is referenced elsewhere in the file"
|
|
111
|
+
for name in bindings
|
|
112
|
+
if name in referenced
|
|
113
|
+
)
|
|
114
|
+
unreferenced = not problems
|
|
115
|
+
unref_detail = (
|
|
116
|
+
f"All {len(removed_bindings)} removed binding(s) are unreferenced anywhere "
|
|
117
|
+
"in the original, including inside string literals."
|
|
118
|
+
if unreferenced
|
|
119
|
+
else "; ".join(problems)
|
|
120
|
+
)
|
|
121
|
+
checks.append(
|
|
122
|
+
Check(
|
|
123
|
+
name="removed_imports_unreferenced",
|
|
124
|
+
passed=unreferenced,
|
|
125
|
+
detail=unref_detail,
|
|
126
|
+
measurements={
|
|
127
|
+
"removed_bindings": sorted(removed_bindings),
|
|
128
|
+
"method": "top-level AST delta + identifier/string reference scan",
|
|
129
|
+
},
|
|
130
|
+
)
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
decided = [c.passed for c in checks if c.passed is not None]
|
|
134
|
+
return ValidationReport(
|
|
135
|
+
performed=True, all_passed=all(decided) if decided else None, checks=checks
|
|
136
|
+
)
|
litmus/validate/text.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Local, deterministic validation of a text transformation.
|
|
2
|
+
|
|
3
|
+
Every check here runs offline with no model and no randomness, so a validation
|
|
4
|
+
result is reproducible from the artifact pair alone.
|
|
5
|
+
|
|
6
|
+
Naming is deliberate: the similarity metric is called **lexical** similarity,
|
|
7
|
+
not semantic similarity, because ``difflib`` measures token overlap and nothing
|
|
8
|
+
about meaning. True semantic similarity is reported as an explicitly
|
|
9
|
+
unperformed check rather than approximated by a proxy and mislabelled.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import difflib
|
|
15
|
+
import re
|
|
16
|
+
import unicodedata
|
|
17
|
+
|
|
18
|
+
from ..model import Check, ValidationReport
|
|
19
|
+
|
|
20
|
+
DEFAULT_MIN_LEXICAL_SIMILARITY = 0.98
|
|
21
|
+
|
|
22
|
+
_WORD = re.compile(r"\S+")
|
|
23
|
+
_MD_HEADING = re.compile(r"^\s{0,3}#{1,6}\s", re.MULTILINE)
|
|
24
|
+
_MD_FENCE = re.compile(r"^\s*(```|~~~)", re.MULTILINE)
|
|
25
|
+
_MD_LIST = re.compile(r"^\s*([-*+]|\d+\.)\s", re.MULTILINE)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _visible_skeleton(text: str) -> str:
|
|
29
|
+
"""Text reduced to its visible content: no format/control chars, whitespace collapsed.
|
|
30
|
+
|
|
31
|
+
Two texts with the same skeleton render the same words in the same order.
|
|
32
|
+
"""
|
|
33
|
+
kept = [
|
|
34
|
+
ch
|
|
35
|
+
for ch in unicodedata.normalize("NFC", text)
|
|
36
|
+
if unicodedata.category(ch) not in {"Cf", "Cc"} or ch in "\n\t"
|
|
37
|
+
]
|
|
38
|
+
return " ".join("".join(kept).split())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _words(text: str) -> list[str]:
|
|
42
|
+
return _WORD.findall(_visible_skeleton(text))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _line_structure_view(text: str) -> str:
|
|
46
|
+
"""Line structure with format/control characters removed.
|
|
47
|
+
|
|
48
|
+
Markdown structure must be counted on this view rather than on the raw
|
|
49
|
+
text. Otherwise an invisible character sitting in front of a ``#`` hides
|
|
50
|
+
the heading from the "before" count, and removing that character - which
|
|
51
|
+
repairs the document - is misreported as a structural change.
|
|
52
|
+
"""
|
|
53
|
+
kept = [ch for ch in text if unicodedata.category(ch) not in {"Cf", "Cc"} or ch in "\n\t"]
|
|
54
|
+
return "".join(kept).replace("\r\n", "\n").replace("\r", "\n")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def validate_text(
|
|
58
|
+
before: str,
|
|
59
|
+
after: str,
|
|
60
|
+
*,
|
|
61
|
+
min_lexical_similarity: float = DEFAULT_MIN_LEXICAL_SIMILARITY,
|
|
62
|
+
) -> ValidationReport:
|
|
63
|
+
checks: list[Check] = []
|
|
64
|
+
|
|
65
|
+
skeleton_before = _visible_skeleton(before)
|
|
66
|
+
skeleton_after = _visible_skeleton(after)
|
|
67
|
+
checks.append(
|
|
68
|
+
Check(
|
|
69
|
+
name="visible_content_preserved",
|
|
70
|
+
passed=skeleton_before == skeleton_after,
|
|
71
|
+
detail=(
|
|
72
|
+
"Visible content is byte-identical after removing format/control "
|
|
73
|
+
"characters and collapsing whitespace."
|
|
74
|
+
if skeleton_before == skeleton_after
|
|
75
|
+
else "Visible content changed."
|
|
76
|
+
),
|
|
77
|
+
measurements={
|
|
78
|
+
"skeleton_chars_before": len(skeleton_before),
|
|
79
|
+
"skeleton_chars_after": len(skeleton_after),
|
|
80
|
+
},
|
|
81
|
+
)
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
words_before, words_after = _words(before), _words(after)
|
|
85
|
+
added = sorted(set(words_after) - set(words_before))
|
|
86
|
+
removed = sorted(set(words_before) - set(words_after))
|
|
87
|
+
checks.append(
|
|
88
|
+
Check(
|
|
89
|
+
name="no_unintended_additions",
|
|
90
|
+
passed=not added,
|
|
91
|
+
detail="No word appears in the output that was absent from the input."
|
|
92
|
+
if not added
|
|
93
|
+
else f"{len(added)} word form(s) introduced.",
|
|
94
|
+
measurements={"added_examples": added[:10], "removed_examples": removed[:10]},
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
ratio = difflib.SequenceMatcher(a=words_before, b=words_after, autojunk=False).ratio()
|
|
99
|
+
checks.append(
|
|
100
|
+
Check(
|
|
101
|
+
name="lexical_similarity",
|
|
102
|
+
passed=ratio >= min_lexical_similarity,
|
|
103
|
+
detail=(
|
|
104
|
+
f"Word-sequence similarity {ratio:.4f} "
|
|
105
|
+
f"(threshold {min_lexical_similarity:.2f}). "
|
|
106
|
+
"This measures token overlap, not meaning."
|
|
107
|
+
),
|
|
108
|
+
measurements={
|
|
109
|
+
"ratio": round(ratio, 6),
|
|
110
|
+
"words_before": len(words_before),
|
|
111
|
+
"words_after": len(words_after),
|
|
112
|
+
},
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
struct_before, struct_after = _line_structure_view(before), _line_structure_view(after)
|
|
117
|
+
structure = {
|
|
118
|
+
"headings": (
|
|
119
|
+
len(_MD_HEADING.findall(struct_before)),
|
|
120
|
+
len(_MD_HEADING.findall(struct_after)),
|
|
121
|
+
),
|
|
122
|
+
"code_fences": (
|
|
123
|
+
len(_MD_FENCE.findall(struct_before)),
|
|
124
|
+
len(_MD_FENCE.findall(struct_after)),
|
|
125
|
+
),
|
|
126
|
+
"list_items": (len(_MD_LIST.findall(struct_before)), len(_MD_LIST.findall(struct_after))),
|
|
127
|
+
}
|
|
128
|
+
structure_ok = all(b == a for b, a in structure.values())
|
|
129
|
+
checks.append(
|
|
130
|
+
Check(
|
|
131
|
+
name="structure_preserved",
|
|
132
|
+
passed=structure_ok,
|
|
133
|
+
detail="Markdown heading, code-fence and list-item counts are unchanged."
|
|
134
|
+
if structure_ok
|
|
135
|
+
else "Markdown structure counts changed.",
|
|
136
|
+
measurements={k: {"before": b, "after": a} for k, (b, a) in structure.items()},
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
checks.append(
|
|
141
|
+
Check(
|
|
142
|
+
name="semantic_similarity",
|
|
143
|
+
passed=None,
|
|
144
|
+
detail=(
|
|
145
|
+
"Not measured. A genuine semantic-similarity score needs an embedding "
|
|
146
|
+
"model, which the default profile excludes to keep validation local, "
|
|
147
|
+
"deterministic and offline. Lexical similarity is reported instead and "
|
|
148
|
+
"is not a substitute."
|
|
149
|
+
),
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
decided = [c.passed for c in checks if c.passed is not None]
|
|
154
|
+
return ValidationReport(
|
|
155
|
+
performed=True,
|
|
156
|
+
all_passed=all(decided) if decided else None,
|
|
157
|
+
checks=checks,
|
|
158
|
+
)
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Language-agnostic structural code validation via tree-sitter.
|
|
2
|
+
|
|
3
|
+
Extends the Python-only AST proof (``validate/code.py``) to JavaScript,
|
|
4
|
+
TypeScript, Java, Kotlin and Swift without needing each language's compiler.
|
|
5
|
+
It is optional: installing the ``code`` extra enables it; without it the
|
|
6
|
+
loader returns ``None`` and the caller degrades to refuse-unless-forced.
|
|
7
|
+
|
|
8
|
+
**The proof.** We parse both versions and compare their *significant token
|
|
9
|
+
streams*: every leaf token, in order, with its source text, **excluding
|
|
10
|
+
comments**. Whitespace is not a token in tree-sitter, so reformatting leaves
|
|
11
|
+
the stream unchanged. A comment edit is excluded, so it is safe. A change to a
|
|
12
|
+
string literal or identifier changes that leaf's text, so it is caught. This is
|
|
13
|
+
the same guarantee ``ast.dump`` gives for Python, generalized.
|
|
14
|
+
|
|
15
|
+
A parse that yields any ERROR node is treated as "does not parse", so syntax
|
|
16
|
+
the transform broke is rejected rather than silently compared.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from ..model import Check, ValidationReport
|
|
24
|
+
|
|
25
|
+
# Our language name -> tree-sitter-language-pack name. Identity today, but kept
|
|
26
|
+
# explicit so a divergence (e.g. "c#" vs "c_sharp") has one place to live.
|
|
27
|
+
_LANG_MAP = {
|
|
28
|
+
"python": "python",
|
|
29
|
+
"javascript": "javascript",
|
|
30
|
+
"typescript": "typescript",
|
|
31
|
+
"java": "java",
|
|
32
|
+
"kotlin": "kotlin",
|
|
33
|
+
"swift": "swift",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def treesitter_available() -> bool:
|
|
38
|
+
try:
|
|
39
|
+
import tree_sitter_language_pack # noqa: F401
|
|
40
|
+
except ImportError:
|
|
41
|
+
return False
|
|
42
|
+
return True
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _load_parser(language: str | None) -> Any | None:
|
|
46
|
+
ts_name = _LANG_MAP.get(language or "")
|
|
47
|
+
if ts_name is None:
|
|
48
|
+
return None
|
|
49
|
+
try:
|
|
50
|
+
from tree_sitter_language_pack import get_parser
|
|
51
|
+
except ImportError:
|
|
52
|
+
return None
|
|
53
|
+
try:
|
|
54
|
+
return get_parser(ts_name)
|
|
55
|
+
except Exception: # noqa: BLE001 - a missing/broken grammar is "unavailable", not a crash
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _significant_tokens(root: Any) -> list[tuple[str, bytes]]:
|
|
60
|
+
"""Leaf tokens in document order, with text, excluding comments."""
|
|
61
|
+
tokens: list[tuple[str, bytes]] = []
|
|
62
|
+
stack: list[Any] = [root]
|
|
63
|
+
while stack:
|
|
64
|
+
node = stack.pop()
|
|
65
|
+
if "comment" in node.type:
|
|
66
|
+
continue
|
|
67
|
+
if node.child_count == 0:
|
|
68
|
+
tokens.append((node.type, node.text or b""))
|
|
69
|
+
else:
|
|
70
|
+
stack.extend(reversed(node.children))
|
|
71
|
+
return tokens
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def validate_code_treesitter(
|
|
75
|
+
before: str, after: str, language: str | None
|
|
76
|
+
) -> ValidationReport | None:
|
|
77
|
+
"""Return a report, or ``None`` if tree-sitter cannot handle this language."""
|
|
78
|
+
parser = _load_parser(language)
|
|
79
|
+
if parser is None:
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
before_tree = parser.parse(before.encode("utf-8"))
|
|
83
|
+
after_tree = parser.parse(after.encode("utf-8"))
|
|
84
|
+
before_ok = not before_tree.root_node.has_error
|
|
85
|
+
after_ok = not after_tree.root_node.has_error
|
|
86
|
+
|
|
87
|
+
checks = [
|
|
88
|
+
Check(
|
|
89
|
+
name="code_parses_after",
|
|
90
|
+
passed=after_ok,
|
|
91
|
+
detail="Output parses cleanly (no tree-sitter ERROR nodes)."
|
|
92
|
+
if after_ok
|
|
93
|
+
else "Output contains parse errors; the transform broke the syntax.",
|
|
94
|
+
)
|
|
95
|
+
]
|
|
96
|
+
|
|
97
|
+
preserved: bool | None
|
|
98
|
+
if not after_ok:
|
|
99
|
+
preserved = None
|
|
100
|
+
detail = "Cannot compare structure because the output does not parse."
|
|
101
|
+
elif not before_ok:
|
|
102
|
+
preserved = None
|
|
103
|
+
detail = "Original does not parse cleanly; structural equivalence is unprovable."
|
|
104
|
+
else:
|
|
105
|
+
preserved = _significant_tokens(before_tree.root_node) == _significant_tokens(
|
|
106
|
+
after_tree.root_node
|
|
107
|
+
)
|
|
108
|
+
detail = (
|
|
109
|
+
"Significant token streams are identical (comments and whitespace aside): "
|
|
110
|
+
"the transform provably preserved the program."
|
|
111
|
+
if preserved
|
|
112
|
+
else "Significant token streams differ: the transform changed a string, "
|
|
113
|
+
"identifier or other token, not just whitespace or comments."
|
|
114
|
+
)
|
|
115
|
+
checks.append(
|
|
116
|
+
Check(
|
|
117
|
+
name="code_semantics_preserved",
|
|
118
|
+
passed=preserved,
|
|
119
|
+
detail=detail,
|
|
120
|
+
measurements={
|
|
121
|
+
"language": language or "unknown",
|
|
122
|
+
"method": "tree-sitter significant-token equality",
|
|
123
|
+
},
|
|
124
|
+
)
|
|
125
|
+
)
|
|
126
|
+
decided = [c.passed for c in checks if c.passed is not None]
|
|
127
|
+
return ValidationReport(
|
|
128
|
+
performed=True, all_passed=all(decided) if decided else None, checks=checks
|
|
129
|
+
)
|