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/office.py ADDED
@@ -0,0 +1,198 @@
1
+ """Shared helpers for Office Open XML documents (DOCX / XLSX / PPTX).
2
+
3
+ An OOXML file is a ZIP archive of XML parts. Author, company, revision count,
4
+ timestamps and custom properties live in the ``docProps/`` parts; the visible
5
+ document content lives elsewhere (``word/``, ``xl/``, ``ppt/`` …). That split is
6
+ what makes metadata removal *provable*: we touch only ``docProps/`` and can show
7
+ every other archive member is byte-for-byte unchanged.
8
+
9
+ Standard library only (``zipfile`` + ``xml.etree``); deterministic; offline.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import io
15
+ import zipfile
16
+
17
+ # docProps parts that carry metadata. Order matters only for readability.
18
+ CORE_PART = "docProps/core.xml"
19
+ APP_PART = "docProps/app.xml"
20
+ CUSTOM_PART = "docProps/custom.xml"
21
+ METADATA_PARTS = frozenset({CORE_PART, APP_PART, CUSTOM_PART})
22
+
23
+ # Central-directory members that prove the file is genuinely OOXML.
24
+ _CONTENT_TYPES = "[Content_Types].xml"
25
+ _OOXML_ROOTS = ("word/", "xl/", "ppt/")
26
+
27
+ # Human labels for the personal fields we surface, keyed by local XML tag name.
28
+ CORE_FIELDS = {
29
+ "creator": "author",
30
+ "lastModifiedBy": "last modified by",
31
+ "title": "title",
32
+ "subject": "subject",
33
+ "keywords": "keywords",
34
+ "description": "description",
35
+ "category": "category",
36
+ "revision": "revision number",
37
+ "created": "created timestamp",
38
+ "modified": "modified timestamp",
39
+ "lastPrinted": "last printed",
40
+ "contentStatus": "content status",
41
+ }
42
+ APP_FIELDS = {
43
+ "Company": "company",
44
+ "Manager": "manager",
45
+ "Application": "application",
46
+ "AppVersion": "application version",
47
+ "Template": "template",
48
+ "TotalTime": "total edit time",
49
+ "LastModifiedBy": "last modified by",
50
+ }
51
+
52
+
53
+ def is_ooxml(data: bytes) -> bool:
54
+ """True when ``data`` is a ZIP that looks like a DOCX/XLSX/PPTX."""
55
+ if not data.startswith(b"PK\x03\x04"):
56
+ return False
57
+ try:
58
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
59
+ names = set(zf.namelist())
60
+ except (zipfile.BadZipFile, OSError):
61
+ return False
62
+ if _CONTENT_TYPES not in names:
63
+ return False
64
+ return any(n.startswith(_OOXML_ROOTS) for n in names)
65
+
66
+
67
+ def ooxml_kind(data: bytes) -> str:
68
+ """Best-effort document type label from the archive layout."""
69
+ try:
70
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
71
+ names = zf.namelist()
72
+ except (zipfile.BadZipFile, OSError):
73
+ return "ooxml"
74
+ if any(n.startswith("word/") for n in names):
75
+ return "docx"
76
+ if any(n.startswith("xl/") for n in names):
77
+ return "xlsx"
78
+ if any(n.startswith("ppt/") for n in names):
79
+ return "pptx"
80
+ return "ooxml"
81
+
82
+
83
+ def _localname(tag: str) -> str:
84
+ return tag.rsplit("}", 1)[-1]
85
+
86
+
87
+ def read_properties(data: bytes) -> dict[str, dict[str, str]]:
88
+ """Return non-empty metadata values grouped by part.
89
+
90
+ ``{"core": {...}, "app": {...}, "custom": {...}}``. Missing parts and
91
+ malformed XML degrade to empty dicts rather than raising.
92
+ """
93
+ import xml.etree.ElementTree as ET
94
+
95
+ result: dict[str, dict[str, str]] = {"core": {}, "app": {}, "custom": {}}
96
+ try:
97
+ zf = zipfile.ZipFile(io.BytesIO(data))
98
+ except (zipfile.BadZipFile, OSError):
99
+ return result
100
+
101
+ with zf:
102
+ for part, bucket, allowed in (
103
+ (CORE_PART, "core", CORE_FIELDS),
104
+ (APP_PART, "app", APP_FIELDS),
105
+ ):
106
+ try:
107
+ root = ET.fromstring(zf.read(part))
108
+ except (KeyError, ET.ParseError):
109
+ continue
110
+ for child in root:
111
+ name = _localname(child.tag)
112
+ if name in allowed and child.text and child.text.strip():
113
+ result[bucket][name] = child.text.strip()
114
+ try:
115
+ custom_root = ET.fromstring(zf.read(CUSTOM_PART))
116
+ except (KeyError, ET.ParseError):
117
+ custom_root = None
118
+ if custom_root is not None:
119
+ for prop in custom_root:
120
+ prop_name = prop.get("name")
121
+ value = "".join(prop.itertext()).strip()
122
+ if prop_name and value:
123
+ result["custom"][prop_name] = value
124
+ return result
125
+
126
+
127
+ def _clean_fields(xml_bytes: bytes, fields: frozenset[str] | dict[str, str]) -> bytes:
128
+ """Remove every child whose local tag is in ``fields``, preserving the rest."""
129
+ import xml.etree.ElementTree as ET
130
+
131
+ root = ET.fromstring(xml_bytes)
132
+ for child in list(root):
133
+ if _localname(child.tag) in fields:
134
+ root.remove(child)
135
+ result = ET.tostring(root, encoding="UTF-8", xml_declaration=True)
136
+ return result if isinstance(result, bytes) else result.encode("utf-8")
137
+
138
+
139
+ def strip_office_metadata(data: bytes) -> tuple[bytes, list[str]]:
140
+ """Return (new_bytes, removed_parts).
141
+
142
+ Rewrites the archive dropping ``docProps/custom.xml`` entirely and clearing
143
+ the metadata fields in ``core.xml`` / ``app.xml``. Every other member is
144
+ copied verbatim (same name, order, compression and timestamp), so the
145
+ document content is provably untouched — see ``validate/office.py``.
146
+ """
147
+ src = zipfile.ZipFile(io.BytesIO(data))
148
+ removed: list[str] = []
149
+ out = io.BytesIO()
150
+ with src, zipfile.ZipFile(out, "w") as dst:
151
+ for info in src.infolist():
152
+ payload = src.read(info.filename)
153
+ if info.filename == CUSTOM_PART:
154
+ removed.append(CUSTOM_PART)
155
+ continue # drop the whole custom-properties part
156
+ if info.filename == CORE_PART:
157
+ new = _clean_fields(payload, CORE_FIELDS)
158
+ if new != payload:
159
+ removed.append(CORE_PART)
160
+ payload = new
161
+ elif info.filename == APP_PART:
162
+ new = _clean_fields(payload, APP_FIELDS)
163
+ if new != payload:
164
+ removed.append(APP_PART)
165
+ payload = new
166
+ # Preserve the member's own compression and timestamp for stability.
167
+ new_info = zipfile.ZipInfo(info.filename, date_time=info.date_time)
168
+ new_info.compress_type = info.compress_type
169
+ new_info.external_attr = info.external_attr
170
+ new_info.internal_attr = info.internal_attr
171
+ new_info.create_system = info.create_system
172
+ dst.writestr(new_info, payload)
173
+ return out.getvalue(), removed
174
+
175
+
176
+ def content_members(data: bytes) -> dict[str, bytes] | None:
177
+ """Decompressed bytes of every member that is *not* metadata.
178
+
179
+ Returns ``None`` if the archive cannot be read. Used by the validator to
180
+ prove the document content is identical before and after stripping. The
181
+ ``[Content_Types].xml`` part still lists custom.xml after removal is
182
+ harmless, but to keep the proof exact it is compared as content too only
183
+ when present in both, so it is excluded here.
184
+ """
185
+ try:
186
+ zf = zipfile.ZipFile(io.BytesIO(data))
187
+ except (zipfile.BadZipFile, OSError):
188
+ return None
189
+ members: dict[str, bytes] = {}
190
+ with zf:
191
+ for name in zf.namelist():
192
+ if name in METADATA_PARTS or name == _CONTENT_TYPES:
193
+ continue
194
+ try:
195
+ members[name] = zf.read(name)
196
+ except (KeyError, OSError):
197
+ return None
198
+ return members
litmus/pipeline.py ADDED
@@ -0,0 +1,464 @@
1
+ """Orchestration: inspect -> transform -> validate -> report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import difflib
6
+ import logging
7
+ from dataclasses import dataclass
8
+
9
+ from .artifact import Artifact, sha256_hex
10
+ from .inspectors import Inspector, default_inspectors
11
+ from .model import (
12
+ ArtifactKind,
13
+ Check,
14
+ Confidence,
15
+ EvidenceClass,
16
+ InspectionReport,
17
+ InspectorStatus,
18
+ OperationResult,
19
+ ProvenanceSummary,
20
+ Report,
21
+ TransformationReport,
22
+ ValidationReport,
23
+ )
24
+ from .office import is_ooxml, ooxml_kind, strip_office_metadata
25
+ from .providers import undetectable_signals
26
+ from .transform import STRUCTURAL_CODE_OPS, Transform, resolve_operations
27
+ from .transform.file_strip import (
28
+ JPEG_SOI,
29
+ PNG_SIGNATURE,
30
+ strip_jpeg_metadata,
31
+ strip_png_metadata,
32
+ strip_svg_metadata,
33
+ )
34
+ from .validate import DEFAULT_MIN_LEXICAL_SIMILARITY, validate_text
35
+ from .validate.binary import validate_image_strip
36
+ from .validate.code import validate_code
37
+ from .validate.office import validate_office_strip
38
+ from .validate.structural import validate_python_import_removal
39
+
40
+ log = logging.getLogger("litmus")
41
+
42
+ CODE_UNPROVEN_REFUSAL = (
43
+ "Refusing to write transformed source code whose behaviour could not be proven "
44
+ "unchanged. No structural validator was available for this language in this "
45
+ "environment (compile/test-based validation is planned). Re-run with --force to "
46
+ "write it anyway; the report will record that semantic preservation was not proven."
47
+ )
48
+ CODE_CHANGED_REFUSAL = (
49
+ "Refusing to write transformed source code that provably changed the program "
50
+ "(the abstract syntax tree differs - a change landed inside a string or another "
51
+ "semantic node). Re-run with --force to write it anyway."
52
+ )
53
+ CODE_BROKEN_REJECTION = (
54
+ "Transformed source code no longer parses; refusing to write broken code. "
55
+ "This is never overridable."
56
+ )
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class TransformOptions:
61
+ profile: str | None = None
62
+ operations: list[str] | None = None
63
+ min_lexical_similarity: float = DEFAULT_MIN_LEXICAL_SIMILARITY
64
+ force_code: bool = False
65
+
66
+
67
+ def inspect(artifact: Artifact, inspectors: list[Inspector] | None = None) -> InspectionReport:
68
+ chosen = inspectors if inspectors is not None else default_inspectors()
69
+ report = InspectionReport()
70
+
71
+ for inspector in chosen:
72
+ if not inspector.applies_to(artifact):
73
+ report.inspectors.append(
74
+ InspectorStatus(
75
+ name=inspector.name,
76
+ ran=False,
77
+ reason=f"not applicable to a {artifact.ref.kind.value} artifact",
78
+ )
79
+ )
80
+ continue
81
+ try:
82
+ outcome = inspector.inspect(artifact)
83
+ except Exception as exc: # noqa: BLE001 - one broken inspector must not lose the rest
84
+ log.exception("inspector %s failed", inspector.name)
85
+ report.inspectors.append(
86
+ InspectorStatus(
87
+ name=inspector.name, ran=False, reason=f"{type(exc).__name__}: {exc}"
88
+ )
89
+ )
90
+ continue
91
+ report.inspectors.append(
92
+ InspectorStatus(name=inspector.name, ran=outcome.ran, reason=outcome.reason)
93
+ )
94
+ report.findings.extend(outcome.findings)
95
+
96
+ report.provenance = _summarize(artifact, report)
97
+ return report
98
+
99
+
100
+ def _summarize(artifact: Artifact, report: InspectionReport) -> ProvenanceSummary:
101
+ detected = sorted({f"{f.detector}:{f.category}" for f in report.findings})
102
+
103
+ unknown = [
104
+ f"{row.provider}:{row.signal} ({row.detectability.value})"
105
+ for row in undetectable_signals(artifact.ref.kind)
106
+ ]
107
+
108
+ signed = [f for f in report.findings if f.evidence_class is EvidenceClass.SIGNED_PROVENANCE]
109
+ verified_provenance = [f for f in signed if f.details.get("verification") == "performed"]
110
+ unverified_provenance = [f for f in signed if f.details.get("verification") != "performed"]
111
+
112
+ notes: list[str] = []
113
+ if verified_provenance:
114
+ confidence = Confidence.SIGNAL_PRESENT
115
+ notes.append(
116
+ "A C2PA manifest was found and its signature was verified. This attests to "
117
+ "the signer's claim of involvement; it does not establish authorship."
118
+ )
119
+ elif unverified_provenance:
120
+ confidence = Confidence.INSUFFICIENT_EVIDENCE
121
+ notes.append(
122
+ "A C2PA manifest structure was found but its signature was NOT verified. "
123
+ "Presence alone proves nothing: install the 'c2pa' extra to verify."
124
+ )
125
+ else:
126
+ confidence = Confidence.INSUFFICIENT_EVIDENCE
127
+
128
+ if unknown:
129
+ notes.append(
130
+ "One or more provenance signals that may be present cannot be checked by "
131
+ "this tool because no public detector exists. Absence of findings is NOT "
132
+ "evidence of absence, and no finding here speaks to authorship."
133
+ )
134
+ if any(f.evidence_class is EvidenceClass.EMBEDDED_METADATA for f in report.findings):
135
+ notes.append(
136
+ "Embedded-metadata findings (invisible characters, file metadata) are "
137
+ "unsigned and trivially forged or stripped. They are not a provider "
138
+ "watermark and do not indicate AI generation."
139
+ )
140
+
141
+ return ProvenanceSummary(
142
+ known_signals_detected=detected,
143
+ unknown_signals=unknown,
144
+ confidence=confidence,
145
+ notes=notes,
146
+ )
147
+
148
+
149
+ def transform(
150
+ artifact: Artifact, options: TransformOptions
151
+ ) -> tuple[TransformationReport, ValidationReport, bytes]:
152
+ """Route to the right transform and validator. Returns (report, validation, bytes).
153
+
154
+ The returned bytes are the **original** bytes unless the transformation was
155
+ accepted, so an unaccepted transformation can never be written by accident.
156
+ """
157
+ media = artifact.ref.media_type
158
+ if artifact.ref.kind is ArtifactKind.BINARY:
159
+ if is_ooxml(artifact.data):
160
+ return _transform_office(artifact)
161
+ return _transform_image(artifact)
162
+ if media == "image/svg+xml" and artifact.text is not None:
163
+ return _transform_svg(artifact)
164
+ if artifact.text is None:
165
+ tr = TransformationReport()
166
+ tr.rejected_reason = "artifact is not decodable text and is not a supported image"
167
+ return tr, ValidationReport(), artifact.data
168
+ return _transform_text(artifact, options)
169
+
170
+
171
+ def _finish(
172
+ tr: TransformationReport, vr: ValidationReport, output: bytes, original: bytes
173
+ ) -> tuple[TransformationReport, ValidationReport, bytes]:
174
+ if not tr.accepted:
175
+ return tr, vr, original
176
+ tr.output_sha256 = sha256_hex(output)
177
+ tr.output_size_bytes = len(output)
178
+ return tr, vr, output
179
+
180
+
181
+ def _transform_image(
182
+ artifact: Artifact,
183
+ ) -> tuple[TransformationReport, ValidationReport, bytes]:
184
+ tr = TransformationReport()
185
+ data = artifact.data
186
+ if data.startswith(PNG_SIGNATURE):
187
+ new_data, removed, _ = strip_png_metadata(data)
188
+ container = "png"
189
+ elif data.startswith(JPEG_SOI):
190
+ new_data, removed, _ = strip_jpeg_metadata(data)
191
+ container = "jpeg"
192
+ else:
193
+ tr.rejected_reason = (
194
+ "unsupported binary type; only PNG and JPEG metadata stripping is implemented"
195
+ )
196
+ return tr, ValidationReport(), data
197
+
198
+ tr.performed = True
199
+ tr.operations.append(
200
+ OperationResult(
201
+ operation="strip_image_metadata",
202
+ description=f"Remove metadata chunks/segments from the {container} container",
203
+ semantics_preserving=True,
204
+ applied=new_data != data,
205
+ changes=len(data) - len(new_data),
206
+ details={"removed": removed, "container": container},
207
+ )
208
+ )
209
+ vr = validate_image_strip(data, new_data)
210
+ tr.accepted = vr.all_passed is True
211
+ if not tr.accepted:
212
+ tr.rejected_reason = "image validation failed: " + "; ".join(
213
+ c.name for c in vr.checks if c.passed is False
214
+ )
215
+ return _finish(tr, vr, new_data, data)
216
+
217
+
218
+ def _transform_office(
219
+ artifact: Artifact,
220
+ ) -> tuple[TransformationReport, ValidationReport, bytes]:
221
+ tr = TransformationReport()
222
+ data = artifact.data
223
+ new_data, removed = strip_office_metadata(data)
224
+ kind = ooxml_kind(data)
225
+ tr.performed = True
226
+ tr.operations.append(
227
+ OperationResult(
228
+ operation="strip_office_metadata",
229
+ description=f"Remove author/company/custom metadata from the {kind} document",
230
+ semantics_preserving=True,
231
+ applied=new_data != data,
232
+ changes=len(data) - len(new_data),
233
+ details={"removed_parts": removed, "container": kind},
234
+ )
235
+ )
236
+ vr = validate_office_strip(data, new_data)
237
+ tr.accepted = vr.all_passed is True
238
+ if not tr.accepted:
239
+ tr.rejected_reason = "office validation failed: " + "; ".join(
240
+ c.name for c in vr.checks if c.passed is False
241
+ )
242
+ return _finish(tr, vr, new_data, data)
243
+
244
+
245
+ def _transform_svg(
246
+ artifact: Artifact,
247
+ ) -> tuple[TransformationReport, ValidationReport, bytes]:
248
+ tr = TransformationReport()
249
+ assert artifact.text is not None
250
+ before = artifact.text
251
+ after, removed = strip_svg_metadata(before)
252
+ tr.performed = True
253
+ tr.operations.append(
254
+ OperationResult(
255
+ operation="strip_svg_metadata",
256
+ description="Remove <metadata>, XMP and xpacket blocks from SVG",
257
+ semantics_preserving=True,
258
+ applied=after != before,
259
+ changes=len(before) - len(after),
260
+ details={"blocks_removed": removed},
261
+ )
262
+ )
263
+ vr = _validate_svg(before, after)
264
+ tr.accepted = vr.all_passed is True
265
+ if not tr.accepted:
266
+ tr.rejected_reason = "svg validation failed: " + "; ".join(
267
+ c.name for c in vr.checks if c.passed is False
268
+ )
269
+ return _finish(tr, vr, after.encode("utf-8"), artifact.data)
270
+
271
+
272
+ def _validate_svg(before: str, after: str) -> ValidationReport:
273
+ import xml.etree.ElementTree as ET
274
+
275
+ checks: list[Check] = []
276
+ try:
277
+ ET.fromstring(after)
278
+ parses = True
279
+ detail = "Output still parses as XML."
280
+ except ET.ParseError as exc:
281
+ parses = False
282
+ detail = f"Output no longer parses as XML: {exc}"
283
+ checks.append(Check(name="svg_parses_after", passed=parses, detail=detail))
284
+
285
+ # Drawing element counts must be untouched; only metadata was targeted.
286
+ def draw_count(text: str) -> int:
287
+ return sum(text.count(f"<{tag}") for tag in ("path", "rect", "circle", "g", "polygon"))
288
+
289
+ same = draw_count(before) == draw_count(after)
290
+ checks.append(
291
+ Check(
292
+ name="drawing_elements_preserved",
293
+ passed=same,
294
+ detail="Drawing-element counts are unchanged."
295
+ if same
296
+ else "Drawing-element counts changed; the strip removed more than metadata.",
297
+ )
298
+ )
299
+ decided = [c.passed for c in checks if c.passed is not None]
300
+ return ValidationReport(
301
+ performed=True, all_passed=all(decided) if decided else None, checks=checks
302
+ )
303
+
304
+
305
+ def _apply_structural(
306
+ t: Transform, text: str, artifact: Artifact, tr: TransformationReport, checks: list[Check]
307
+ ) -> str:
308
+ """Apply one structural operation behind its dedicated proof.
309
+
310
+ The change is kept only when the proof passes in full; otherwise it is
311
+ discarded and the operation is recorded as not applied. ``--force`` never
312
+ reaches here by design: an unproven structural edit is simply not made.
313
+ """
314
+ details: dict[str, object] = {"note": t.note} if t.note else {}
315
+ applied = False
316
+ result = text
317
+ if artifact.ref.language != "python":
318
+ details["skipped"] = "structural operations are implemented for Python only"
319
+ else:
320
+ candidate = t.apply(text)
321
+ if candidate != text:
322
+ proof = validate_python_import_removal(text, candidate)
323
+ if proof.all_passed is True:
324
+ checks.extend(proof.checks)
325
+ result = candidate
326
+ applied = True
327
+ else:
328
+ details["discarded"] = (
329
+ "the change could not be proven safe and was not applied "
330
+ "(not overridable with --force); failing: "
331
+ + "; ".join(c.name for c in proof.checks if c.passed is not True)
332
+ )
333
+ tr.operations.append(
334
+ OperationResult(
335
+ operation=t.id,
336
+ description=t.description,
337
+ semantics_preserving=t.semantics_preserving,
338
+ applied=applied,
339
+ changes=_change_count(text, result) if applied else 0,
340
+ details=details,
341
+ )
342
+ )
343
+ return result
344
+
345
+
346
+ def _transform_text(
347
+ artifact: Artifact, options: TransformOptions
348
+ ) -> tuple[TransformationReport, ValidationReport, bytes]:
349
+ tr = TransformationReport()
350
+ assert artifact.text is not None
351
+ transforms: list[Transform] = resolve_operations(options.profile, options.operations)
352
+ structural = [t for t in transforms if t.id in STRUCTURAL_CODE_OPS]
353
+ normalizing = [t for t in transforms if t.id not in STRUCTURAL_CODE_OPS]
354
+
355
+ # Structural operations run first, each gated by its own proof. `mid` is
356
+ # the proven-safe structural result; the character-level proofs below then
357
+ # compare against `mid`, not the original, because token/AST equality with
358
+ # the original is impossible once a structural edit has (provenly) landed.
359
+ structural_checks: list[Check] = []
360
+ mid = artifact.text
361
+ for t in structural:
362
+ mid = _apply_structural(t, mid, artifact, tr, structural_checks)
363
+
364
+ current = mid
365
+ for t in normalizing:
366
+ result = t.apply(current)
367
+ tr.operations.append(
368
+ OperationResult(
369
+ operation=t.id,
370
+ description=t.description,
371
+ semantics_preserving=t.semantics_preserving,
372
+ applied=result != current,
373
+ changes=0 if result == current else _change_count(current, result),
374
+ details={"note": t.note} if t.note else {},
375
+ )
376
+ )
377
+ current = result
378
+
379
+ tr.performed = True
380
+ vr = validate_text(mid, current, min_lexical_similarity=options.min_lexical_similarity)
381
+ is_code = artifact.ref.kind is ArtifactKind.SOURCE_CODE
382
+
383
+ if is_code:
384
+ code_vr = validate_code(mid, current, artifact.ref.language)
385
+ # Structural proof leads, then the code verdict, then text checks.
386
+ vr.checks = structural_checks + code_vr.checks + vr.checks
387
+ tr.accepted, tr.rejected_reason, vr.all_passed = _decide_code(
388
+ code_vr, text_ok=vr.all_passed is not False, force=options.force_code
389
+ )
390
+ else:
391
+ vr.checks = structural_checks + vr.checks
392
+ tr.accepted = vr.all_passed is not False
393
+ if not tr.accepted:
394
+ tr.rejected_reason = "validation failed: " + "; ".join(
395
+ c.name for c in vr.checks if c.passed is False
396
+ )
397
+
398
+ return _finish(tr, vr, current.encode("utf-8"), artifact.data)
399
+
400
+
401
+ def _check(vr: ValidationReport, name: str) -> bool | None:
402
+ for c in vr.checks:
403
+ if c.name == name:
404
+ return c.passed
405
+ return None
406
+
407
+
408
+ def _decide_code(
409
+ code_vr: ValidationReport, *, text_ok: bool, force: bool
410
+ ) -> tuple[bool, str | None, bool | None]:
411
+ """Return (accepted, rejected_reason, all_passed) for a code transform.
412
+
413
+ Acceptance is driven by whether behaviour was *proven* unchanged, never by
414
+ treating "unproven" as "safe". ``all_passed`` reports validation truth
415
+ independent of ``force``.
416
+ """
417
+ parses = _check(code_vr, "code_parses_after")
418
+ preserved = _check(code_vr, "code_semantics_preserved")
419
+
420
+ if parses is False:
421
+ return False, CODE_BROKEN_REJECTION, False
422
+ if preserved is True and text_ok:
423
+ return True, None, True
424
+ if preserved is False:
425
+ return (True, None, False) if force else (False, CODE_CHANGED_REFUSAL, False)
426
+ # preserved is None (unproven), or text validation flagged something.
427
+ if force:
428
+ return True, None, None
429
+ return False, CODE_UNPROVEN_REFUSAL, None
430
+
431
+
432
+ #: Above this size, exact diffing is not worth the quadratic worst case.
433
+ _DIFF_LIMIT_CHARS = 200_000
434
+
435
+
436
+ def _change_count(before: str, after: str) -> int:
437
+ """Characters affected by an operation, as a transformation-magnitude measure.
438
+
439
+ Falls back to the length delta on very large inputs so that a big file
440
+ cannot make the tool appear to hang.
441
+ """
442
+ if max(len(before), len(after)) > _DIFF_LIMIT_CHARS:
443
+ return abs(len(before) - len(after))
444
+ matcher = difflib.SequenceMatcher(a=before, b=after, autojunk=False)
445
+ return sum(
446
+ max(i2 - i1, j2 - j1) for tag, i1, i2, j1, j2 in matcher.get_opcodes() if tag != "equal"
447
+ )
448
+
449
+
450
+ def analyze(
451
+ artifact: Artifact,
452
+ *,
453
+ options: TransformOptions | None = None,
454
+ inspectors: list[Inspector] | None = None,
455
+ ) -> tuple[Report, bytes]:
456
+ """Full pipeline. Returns the report and the bytes that should be written."""
457
+ inspection = inspect(artifact, inspectors)
458
+ report = Report(artifact=artifact.ref, inspection=inspection)
459
+ output = artifact.data
460
+ if options is not None:
461
+ tr, vr, output = transform(artifact, options)
462
+ report.transformation = tr
463
+ report.validation = vr
464
+ return report, output
@@ -0,0 +1,17 @@
1
+ from .registry import (
2
+ CAPABILITIES,
3
+ Capability,
4
+ Detectability,
5
+ capabilities,
6
+ providers,
7
+ undetectable_signals,
8
+ )
9
+
10
+ __all__ = [
11
+ "CAPABILITIES",
12
+ "Capability",
13
+ "Detectability",
14
+ "capabilities",
15
+ "providers",
16
+ "undetectable_signals",
17
+ ]