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 ADDED
@@ -0,0 +1,27 @@
1
+ """AI provenance inspector and quality-preserving transformation system.
2
+
3
+ Inspects files for locally detectable provenance signals (hidden characters,
4
+ embedded metadata, content credentials) and strips them behind proofs that the
5
+ visible content is unchanged. It never claims to detect statistical text
6
+ watermarks; no public detector exists for them.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from .artifact import Artifact, load_bytes, load_path
12
+ from .model import TOOL_VERSION, Report
13
+ from .pipeline import TransformOptions, analyze, inspect, transform
14
+
15
+ __version__ = TOOL_VERSION
16
+
17
+ __all__ = [
18
+ "Artifact",
19
+ "Report",
20
+ "TransformOptions",
21
+ "__version__",
22
+ "analyze",
23
+ "inspect",
24
+ "load_bytes",
25
+ "load_path",
26
+ "transform",
27
+ ]
litmus/artifact.py ADDED
@@ -0,0 +1,179 @@
1
+ """Artifact loading and classification.
2
+
3
+ Loading is deliberately conservative: files are read as bytes, decoding is
4
+ attempted rather than assumed, and a failure to decode downgrades the artifact
5
+ to ``BINARY`` instead of raising or silently mangling content.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import codecs
11
+ import hashlib
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ from .model import ArtifactKind, ArtifactRef
16
+
17
+ MAX_DEFAULT_BYTES = 32 * 1024 * 1024
18
+
19
+ # Extension -> language name. Only languages the project targets are named;
20
+ # anything else stays ``None`` and is treated as generic text.
21
+ _LANGUAGE_BY_SUFFIX: dict[str, str] = {
22
+ ".kt": "kotlin",
23
+ ".kts": "kotlin",
24
+ ".java": "java",
25
+ ".swift": "swift",
26
+ ".ts": "typescript",
27
+ ".tsx": "typescript",
28
+ ".js": "javascript",
29
+ ".jsx": "javascript",
30
+ ".mjs": "javascript",
31
+ ".cjs": "javascript",
32
+ ".py": "python",
33
+ ".pyi": "python",
34
+ }
35
+
36
+ _MEDIA_TYPE_BY_SUFFIX: dict[str, str] = {
37
+ ".png": "image/png",
38
+ ".jpg": "image/jpeg",
39
+ ".jpeg": "image/jpeg",
40
+ ".svg": "image/svg+xml",
41
+ ".webp": "image/webp",
42
+ ".gif": "image/gif",
43
+ ".pdf": "application/pdf",
44
+ ".md": "text/markdown",
45
+ ".txt": "text/plain",
46
+ ".json": "application/json",
47
+ ".html": "text/html",
48
+ ".xml": "text/xml",
49
+ }
50
+
51
+ # Directories that are never worth walking.
52
+ SKIP_DIRS = frozenset(
53
+ {
54
+ ".git",
55
+ ".hg",
56
+ ".svn",
57
+ "node_modules",
58
+ ".gradle",
59
+ "build",
60
+ "out",
61
+ "dist",
62
+ ".venv",
63
+ "venv",
64
+ "__pycache__",
65
+ ".mypy_cache",
66
+ ".pytest_cache",
67
+ ".idea",
68
+ "DerivedData",
69
+ ".build",
70
+ }
71
+ )
72
+
73
+
74
+ class ArtifactError(Exception):
75
+ """Raised when an artifact cannot be loaded at all."""
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class Artifact:
80
+ """An artifact plus its decoded text, when decoding succeeded."""
81
+
82
+ ref: ArtifactRef
83
+ data: bytes
84
+ text: str | None
85
+
86
+ @property
87
+ def is_textual(self) -> bool:
88
+ return self.text is not None
89
+
90
+
91
+ def sha256_hex(data: bytes) -> str:
92
+ return hashlib.sha256(data).hexdigest()
93
+
94
+
95
+ def _decode(data: bytes) -> tuple[str | None, str | None]:
96
+ """Return (text, encoding). UTF-8 only; anything else is treated as binary.
97
+
98
+ Guessing legacy encodings would make offsets and normalization unreliable,
99
+ which is worse than declining to decode.
100
+
101
+ A byte order mark is detected explicitly and **kept** in the decoded text as
102
+ U+FEFF. Decoding with ``utf-8-sig`` would silently swallow it, which both
103
+ hides a real finding and shifts every character offset by one relative to
104
+ the byte stream.
105
+ """
106
+ if b"\x00" in data[:8192]:
107
+ return None, None
108
+ try:
109
+ text = data.decode("utf-8")
110
+ except UnicodeDecodeError:
111
+ return None, None
112
+ return text, "utf-8-sig" if data.startswith(codecs.BOM_UTF8) else "utf-8"
113
+
114
+
115
+ def classify(path: Path | None, data: bytes, text: str | None) -> tuple[ArtifactKind, str | None]:
116
+ language = _LANGUAGE_BY_SUFFIX.get(path.suffix.lower()) if path else None
117
+ if text is None:
118
+ return ArtifactKind.BINARY, None
119
+ if language is not None:
120
+ return ArtifactKind.SOURCE_CODE, language
121
+ return ArtifactKind.TEXT, None
122
+
123
+
124
+ def load_bytes(data: bytes, *, path: Path | None = None) -> Artifact:
125
+ text, encoding = _decode(data)
126
+ kind, language = classify(path, data, text)
127
+ media_type = _MEDIA_TYPE_BY_SUFFIX.get(path.suffix.lower()) if path else None
128
+ ref = ArtifactRef(
129
+ path=str(path) if path else None,
130
+ kind=kind,
131
+ language=language,
132
+ media_type=media_type,
133
+ sha256=sha256_hex(data),
134
+ size_bytes=len(data),
135
+ encoding=encoding,
136
+ decoded=text is not None,
137
+ )
138
+ return Artifact(ref=ref, data=data, text=text)
139
+
140
+
141
+ def load_path(path: Path, *, max_bytes: int = MAX_DEFAULT_BYTES) -> Artifact:
142
+ try:
143
+ size = path.stat().st_size
144
+ except OSError as exc:
145
+ raise ArtifactError(f"cannot stat {path}: {exc}") from exc
146
+ if size > max_bytes:
147
+ raise ArtifactError(f"{path} is {size} bytes, above the {max_bytes} byte limit")
148
+ try:
149
+ data = path.read_bytes()
150
+ except OSError as exc:
151
+ raise ArtifactError(f"cannot read {path}: {exc}") from exc
152
+ return load_bytes(data, path=path)
153
+
154
+
155
+ def walk(root: Path, *, follow_symlinks: bool = False) -> list[Path]:
156
+ """Collect regular files under ``root``, skipping build and VCS directories.
157
+
158
+ Symlinks are not followed by default: a tree scan should not be steerable
159
+ out of the tree it was pointed at.
160
+ """
161
+ if root.is_file():
162
+ return [root]
163
+ found: list[Path] = []
164
+ stack = [root]
165
+ while stack:
166
+ current = stack.pop()
167
+ try:
168
+ entries = sorted(current.iterdir())
169
+ except OSError:
170
+ continue
171
+ for entry in entries:
172
+ if entry.is_symlink() and not follow_symlinks:
173
+ continue
174
+ if entry.is_dir():
175
+ if entry.name not in SKIP_DIRS:
176
+ stack.append(entry)
177
+ elif entry.is_file():
178
+ found.append(entry)
179
+ return sorted(found)
litmus/cli.py ADDED
@@ -0,0 +1,342 @@
1
+ """Command-line interface.
2
+
3
+ Exit codes (stable, CI-suitable):
4
+
5
+ * ``0`` success, nothing at or above the ``--fail-on`` threshold
6
+ * ``1`` findings at or above the threshold, or a rejected transformation
7
+ * ``2`` usage error, unreadable input, or unknown option
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import logging
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import typer
18
+
19
+ from .artifact import Artifact, ArtifactError, load_path, walk
20
+ from .io import SafeWriteError, safe_write
21
+ from .model import TOOL_VERSION, ArtifactKind, BatchReport, Report, Severity
22
+ from .pipeline import TransformOptions, analyze
23
+ from .providers import capabilities as provider_capabilities
24
+ from .reporting import render_batch, render_capabilities, render_report
25
+ from .transform import PROFILES, TRANSFORMS
26
+ from .validate import DEFAULT_MIN_LEXICAL_SIMILARITY, validate_text
27
+
28
+ EXIT_OK = 0
29
+ EXIT_FINDINGS = 1
30
+ EXIT_ERROR = 2
31
+
32
+ _SEVERITY_ORDER = {Severity.INFO: 0, Severity.NOTICE: 1, Severity.WARNING: 2}
33
+
34
+ app = typer.Typer(
35
+ add_completion=False,
36
+ no_args_is_help=True,
37
+ help=(
38
+ "AI provenance inspector and quality-preserving transformation system. "
39
+ "Runs entirely locally; no artifact leaves this machine."
40
+ ),
41
+ )
42
+
43
+
44
+ def _version_callback(value: bool) -> None:
45
+ if value:
46
+ typer.echo(f"litmus {TOOL_VERSION}")
47
+ raise typer.Exit()
48
+
49
+
50
+ @app.callback()
51
+ def _root(
52
+ version: bool = typer.Option(
53
+ False,
54
+ "--version",
55
+ callback=_version_callback,
56
+ is_eager=True,
57
+ help="Show the version and exit.",
58
+ ),
59
+ ) -> None:
60
+ """AI provenance inspector and quality-preserving transformation system."""
61
+
62
+
63
+ def _configure_logging(verbose: bool) -> None:
64
+ logging.basicConfig(
65
+ level=logging.DEBUG if verbose else logging.WARNING,
66
+ format="%(levelname)s %(name)s: %(message)s",
67
+ stream=sys.stderr,
68
+ )
69
+
70
+
71
+ def _collect(paths: list[Path]) -> list[Path]:
72
+ files: list[Path] = []
73
+ for path in paths:
74
+ if not path.exists():
75
+ typer.echo(f"error: no such path: {path}", err=True)
76
+ raise typer.Exit(EXIT_ERROR)
77
+ files.extend(walk(path))
78
+ return files
79
+
80
+
81
+ def _load(path: Path) -> Artifact:
82
+ return load_path(path)
83
+
84
+
85
+ def _threshold_hit(report: Report, fail_on: str) -> bool:
86
+ if fail_on == "never":
87
+ return False
88
+ try:
89
+ minimum = _SEVERITY_ORDER[Severity(fail_on)]
90
+ except ValueError:
91
+ typer.echo(f"error: invalid --fail-on value: {fail_on}", err=True)
92
+ raise typer.Exit(EXIT_ERROR) from None
93
+ return any(_SEVERITY_ORDER[f.severity] >= minimum for f in report.inspection.findings)
94
+
95
+
96
+ def _emit(batch: BatchReport, as_json: bool, verbose: bool) -> None:
97
+ if as_json:
98
+ payload = batch if len(batch.reports) != 1 or batch.errors else batch.reports[0]
99
+ typer.echo(payload.model_dump_json(indent=2))
100
+ else:
101
+ typer.echo(render_batch(batch, verbose=verbose))
102
+
103
+
104
+ @app.command("inspect")
105
+ def inspect_cmd(
106
+ paths: list[Path] = typer.Argument(..., help="Files or directories to inspect."),
107
+ json_output: bool = typer.Option(False, "--json", help="Emit the machine-readable report."),
108
+ fail_on: str = typer.Option(
109
+ "never",
110
+ "--fail-on",
111
+ help="Exit 1 when a finding of this severity or higher exists: info|notice|warning|never.",
112
+ ),
113
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Include locations and details."),
114
+ ) -> None:
115
+ """Inspect artifacts for locally detectable provenance signals."""
116
+ _configure_logging(verbose)
117
+ batch = BatchReport()
118
+ for path in _collect(paths):
119
+ try:
120
+ report, _ = analyze(_load(path))
121
+ except ArtifactError as exc:
122
+ batch.errors.append({"path": str(path), "error": str(exc)})
123
+ continue
124
+ batch.reports.append(report)
125
+
126
+ _emit(batch, json_output, verbose)
127
+ if batch.errors:
128
+ raise typer.Exit(EXIT_ERROR)
129
+ if any(_threshold_hit(r, fail_on) for r in batch.reports):
130
+ raise typer.Exit(EXIT_FINDINGS)
131
+
132
+
133
+ @app.command("transform")
134
+ def transform_cmd(
135
+ paths: list[Path] = typer.Argument(..., help="Files or directories to transform."),
136
+ profile: str = typer.Option(
137
+ "standard", "--profile", help=f"One of: {', '.join(sorted(PROFILES))}."
138
+ ),
139
+ operation: list[str] | None = typer.Option(
140
+ None, "--op", help="Explicit operation id; repeatable. Overrides --profile."
141
+ ),
142
+ in_place: bool = typer.Option(False, "--in-place", help="Rewrite the files on disk."),
143
+ output: Path | None = typer.Option(
144
+ None, "--output", "-o", help="Write the result here. Single input only."
145
+ ),
146
+ backup: bool = typer.Option(
147
+ False, "--backup", help="Write a .bak copy before rewriting in place."
148
+ ),
149
+ force: bool = typer.Option(
150
+ False, "--force", help="Write transformed code even when preservation was not proven."
151
+ ),
152
+ min_similarity: float = typer.Option(
153
+ DEFAULT_MIN_LEXICAL_SIMILARITY,
154
+ "--min-similarity",
155
+ help="Reject the transformation below this lexical similarity.",
156
+ ),
157
+ json_output: bool = typer.Option(False, "--json", help="Emit the machine-readable report."),
158
+ verbose: bool = typer.Option(False, "--verbose", "-v"),
159
+ ) -> None:
160
+ """Apply validated, deterministic normalization.
161
+
162
+ Nothing is written unless validation passed. By default the result is
163
+ printed to stdout for a single file; use --in-place or --output to persist.
164
+ """
165
+ _configure_logging(verbose)
166
+ files = _collect(paths)
167
+ if output is not None and len(files) != 1:
168
+ typer.echo("error: --output requires exactly one input file", err=True)
169
+ raise typer.Exit(EXIT_ERROR)
170
+ if output is not None and in_place:
171
+ typer.echo("error: --output and --in-place are mutually exclusive", err=True)
172
+ raise typer.Exit(EXIT_ERROR)
173
+
174
+ options = TransformOptions(
175
+ profile=profile,
176
+ operations=list(operation) if operation else None,
177
+ min_lexical_similarity=min_similarity,
178
+ force_code=force,
179
+ )
180
+
181
+ batch = BatchReport()
182
+ rejected = False
183
+ for path in files:
184
+ try:
185
+ art = _load(path)
186
+ report, data = analyze(art, options=options)
187
+ except ArtifactError as exc:
188
+ batch.errors.append({"path": str(path), "error": str(exc)})
189
+ continue
190
+ except KeyError as exc:
191
+ typer.echo(f"error: {exc.args[0]}", err=True)
192
+ raise typer.Exit(EXIT_ERROR) from None
193
+ batch.reports.append(report)
194
+
195
+ if not report.transformation.accepted:
196
+ rejected = True
197
+ continue
198
+ try:
199
+ if in_place:
200
+ if data != art.data:
201
+ safe_write(path, data, backup=backup)
202
+ elif output is not None:
203
+ safe_write(output, data, backup=backup)
204
+ elif not json_output and len(files) == 1:
205
+ sys.stdout.buffer.write(data)
206
+ return
207
+ except SafeWriteError as exc:
208
+ batch.errors.append({"path": str(path), "error": str(exc)})
209
+
210
+ _emit(batch, json_output, verbose)
211
+ if batch.errors:
212
+ raise typer.Exit(EXIT_ERROR)
213
+ if rejected:
214
+ raise typer.Exit(EXIT_FINDINGS)
215
+
216
+
217
+ @app.command("validate")
218
+ def validate_cmd(
219
+ before: Path = typer.Argument(..., help="Original text artifact."),
220
+ after: Path = typer.Argument(..., help="Transformed text artifact."),
221
+ min_similarity: float = typer.Option(DEFAULT_MIN_LEXICAL_SIMILARITY, "--min-similarity"),
222
+ json_output: bool = typer.Option(False, "--json"),
223
+ verbose: bool = typer.Option(False, "--verbose", "-v"),
224
+ ) -> None:
225
+ """Validate an existing before/after pair produced by any means."""
226
+ _configure_logging(verbose)
227
+ try:
228
+ a, b = _load(before), _load(after)
229
+ except ArtifactError as exc:
230
+ typer.echo(f"error: {exc}", err=True)
231
+ raise typer.Exit(EXIT_ERROR) from None
232
+ if a.text is None or b.text is None:
233
+ typer.echo("error: both inputs must be decodable UTF-8 text", err=True)
234
+ raise typer.Exit(EXIT_ERROR)
235
+
236
+ result = validate_text(a.text, b.text, min_lexical_similarity=min_similarity)
237
+ if json_output:
238
+ typer.echo(result.model_dump_json(indent=2))
239
+ else:
240
+ typer.echo(f"validation all_passed={result.all_passed}")
241
+ for check in result.checks:
242
+ state = {True: "pass", False: "FAIL", None: "n/a "}[check.passed]
243
+ typer.echo(f" [{state}] {check.name}: {check.detail}")
244
+ if result.all_passed is False:
245
+ raise typer.Exit(EXIT_FINDINGS)
246
+
247
+
248
+ @app.command("capabilities")
249
+ def capabilities_cmd(
250
+ provider: str | None = typer.Option(None, "--provider", help="Filter by provider."),
251
+ kind: str | None = typer.Option(
252
+ None, "--kind", help="Filter by artifact kind: text|source_code|binary."
253
+ ),
254
+ json_output: bool = typer.Option(False, "--json"),
255
+ ) -> None:
256
+ """Show what each provider marks and whether anyone else can verify it."""
257
+ artifact_kind = None
258
+ if kind is not None:
259
+ try:
260
+ artifact_kind = ArtifactKind(kind)
261
+ except ValueError:
262
+ typer.echo(f"error: invalid --kind: {kind}", err=True)
263
+ raise typer.Exit(EXIT_ERROR) from None
264
+ rows = provider_capabilities(provider, artifact_kind)
265
+ if json_output:
266
+ typer.echo(json.dumps([r.model_dump(mode="json") for r in rows], indent=2))
267
+ else:
268
+ typer.echo(render_capabilities(rows))
269
+
270
+
271
+ @app.command("operations")
272
+ def operations_cmd(
273
+ json_output: bool = typer.Option(False, "--json"),
274
+ ) -> None:
275
+ """List the available transformation operations and profiles."""
276
+ if json_output:
277
+ typer.echo(
278
+ json.dumps(
279
+ {
280
+ "operations": {
281
+ t.id: {
282
+ "description": t.description,
283
+ "semantics_preserving": t.semantics_preserving,
284
+ "note": t.note,
285
+ }
286
+ for t in TRANSFORMS.values()
287
+ },
288
+ "profiles": PROFILES,
289
+ },
290
+ indent=2,
291
+ )
292
+ )
293
+ return
294
+ typer.echo("operations")
295
+ for t in TRANSFORMS.values():
296
+ typer.echo(f" {t.id}: {t.description}")
297
+ if t.note:
298
+ typer.echo(f" note: {t.note}")
299
+ typer.echo("")
300
+ typer.echo("profiles")
301
+ for name, ops in PROFILES.items():
302
+ typer.echo(f" {name}: {', '.join(ops)}")
303
+
304
+
305
+ @app.command("report")
306
+ def report_cmd(
307
+ path: Path = typer.Argument(..., help="A JSON report previously written with --json."),
308
+ verbose: bool = typer.Option(False, "--verbose", "-v"),
309
+ ) -> None:
310
+ """Render a saved JSON report as human-readable text."""
311
+ try:
312
+ payload = json.loads(path.read_text(encoding="utf-8"))
313
+ except (OSError, json.JSONDecodeError) as exc:
314
+ typer.echo(f"error: cannot read report: {exc}", err=True)
315
+ raise typer.Exit(EXIT_ERROR) from None
316
+ try:
317
+ if "reports" in payload:
318
+ typer.echo(render_batch(BatchReport.model_validate(payload), verbose=verbose))
319
+ else:
320
+ typer.echo(render_report(Report.model_validate(payload), verbose=verbose))
321
+ except Exception as exc: # noqa: BLE001 - a malformed report is a user error
322
+ typer.echo(f"error: not a valid report: {exc}", err=True)
323
+ raise typer.Exit(EXIT_ERROR) from None
324
+
325
+
326
+ @app.command("serve")
327
+ def serve_cmd(
328
+ host: str = typer.Option("127.0.0.1", "--host", help="Bind address; loopback by default."),
329
+ port: int = typer.Option(8765, "--port", help="Port to listen on."),
330
+ no_browser: bool = typer.Option(False, "--no-browser", help="Do not open a browser."),
331
+ ) -> None:
332
+ """Start a local drag-and-drop web UI. Files are analysed in memory; nothing is uploaded."""
333
+ from .server import serve
334
+
335
+ serve(host=host, port=port, open_browser=not no_browser)
336
+
337
+
338
+ def main() -> None:
339
+ app()
340
+
341
+
342
+ __all__ = ["app", "main"]
@@ -0,0 +1,3 @@
1
+ from .base import DetectionResult, Detector, available_detectors
2
+
3
+ __all__ = ["DetectionResult", "Detector", "available_detectors"]
@@ -0,0 +1,56 @@
1
+ """Detector abstraction for provider provenance detectors.
2
+
3
+ **There are deliberately no implementations in this package.**
4
+
5
+ No public detector exists for Anthropic's text watermark, and SynthID detection
6
+ requires partner access. Shipping a stub that returned a plausible-looking
7
+ result would be fabrication, so the interface is defined and left empty until a
8
+ real detector is available.
9
+
10
+ When one ships, an implementation is added here and the corresponding row in
11
+ ``providers/registry.py`` flips to ``Detectability.PUBLIC_DETECTOR``. Nothing
12
+ else in the pipeline changes.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Protocol, runtime_checkable
18
+
19
+ from pydantic import BaseModel
20
+
21
+ from ..artifact import Artifact
22
+ from ..model import Confidence, EvidenceClass
23
+
24
+
25
+ class DetectionResult(BaseModel):
26
+ detector: str
27
+ provider: str
28
+ signal: str
29
+ evidence_class: EvidenceClass
30
+ input_sha256: str
31
+ detected: bool | None
32
+ confidence: Confidence
33
+ #: Provider-reported score, if and only if the provider returns one.
34
+ provider_score: float | None = None
35
+ minimum_length_met: bool | None = None
36
+ detail: str = ""
37
+ #: True when running this detector transmitted the artifact off the machine.
38
+ network_used: bool = False
39
+
40
+
41
+ @runtime_checkable
42
+ class Detector(Protocol):
43
+ name: str
44
+ provider: str
45
+ #: Detectors that transmit content must declare it so the CLI can require
46
+ #: an explicit opt-in (brief §14).
47
+ requires_network: bool
48
+
49
+ def applies_to(self, artifact: Artifact) -> bool: ...
50
+
51
+ def detect(self, artifact: Artifact, *, timeout_s: float) -> DetectionResult: ...
52
+
53
+
54
+ def available_detectors() -> list[Detector]:
55
+ """No detectors are available. See the module docstring."""
56
+ return []