recheck-ai 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joshua Almeida
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: recheck-ai
3
+ Version: 0.1.0
4
+ Summary: Re-fetch AI source URLs live and verify quoted claims still appear on the page.
5
+ Author-email: Joshua Almeida <192924532+fitzyracing1@users.noreply.github.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/fitzyracing1/recheck
8
+ Project-URL: Issues, https://github.com/fitzyracing1/recheck/issues
9
+ Project-URL: PyPI, https://pypi.org/project/recheck-ai/
10
+ Keywords: ai,citations,sources,verification,mcp
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Internet :: WWW/HTTP
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: httpx>=0.27
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=8; extra == "dev"
23
+ Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
24
+ Requires-Dist: respx>=0.21; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # recheck
28
+
29
+ Re-fetch every URL an AI looked at and check that the quotes in its answer still appear on the live page.
30
+
31
+ Built after stale cached copies of a changelog produced bad drafts: the model quoted a page that had already changed (or a cached snapshot that no longer matched production). `recheck` is meant to be called *while an answer is still being written* so those misses get flagged before anyone ships the draft.
32
+
33
+ ## 30-second example
34
+
35
+ ```bash
36
+ pip install recheck-ai
37
+ # or: pip install git+https://github.com/fitzyracing1/recheck
38
+
39
+ recheck https://fitzyracing1.github.io/x-algorithm-changelog/ \
40
+ --quote 'VideoOpenWeight' \
41
+ --quote 'this-quote-is-definitely-not-here-xyz'
42
+ ```
43
+
44
+ The PyPI package is named `recheck-ai` because the name `recheck` is already taken. The commands remain `recheck` and `recheck-mcp`.
45
+
46
+ You should see the first quote marked found (`✓`, exact or compact, score `1.00`) and the second marked missing (`✗`). Exit status is `1` whenever any source failed or any quote was not found; pass `--json` for a machine-readable report.
47
+
48
+ JSON input (what a bot should send mid-answer):
49
+
50
+ ```bash
51
+ recheck examples/sources.json
52
+ recheck examples/sources.json --json
53
+ ```
54
+
55
+ ```json
56
+ [
57
+ {
58
+ "url": "https://fitzyracing1.github.io/x-algorithm-changelog/",
59
+ "quotes": ["VideoOpenWeight", "this-quote-is-definitely-not-here-xyz"],
60
+ "snapshot_hash": "optional-sha256-of-the-body-you-already-fetched",
61
+ "fetched_at": "2026-11-26T08:00:00Z"
62
+ }
63
+ ]
64
+ ```
65
+
66
+ `snapshot_hash` is the SHA-256 hex digest of the raw response body (optionally prefixed with `sha256:`). If you pass one and the live body hashes differently, the source is flagged `changed` even when the quotes are still present.
67
+
68
+ ## Statuses
69
+
70
+ | Status | Meaning |
71
+ |------------|------------------------------------------------------|
72
+ | `ok` | Fetched, optional snapshot matches |
73
+ | `changed` | Fetched, but `snapshot_hash` does not match the live body |
74
+ | `gone` | HTTP 404 or 410 |
75
+ | `blocked` | HTTP 401, 403, 407, or 429 |
76
+ | `timeout` | The request exceeded `--timeout` (default 15s) |
77
+ | `error` | Other network or HTTP failures |
78
+
79
+ Each quote is checked against the live body after normalizing whitespace and case. If that misses, a compact alphanumeric comparison runs (so `Video Open Weight` still matches `VideoOpenWeight`). If that also misses, a windowed fuzzy score is reported; scores at or above `--fuzzy-threshold` (default `0.8`) count as found.
80
+
81
+ ## MCP
82
+
83
+ A tiny stdio MCP server is included so any bot can call this mid-answer. It has no dependency beyond `httpx`.
84
+
85
+ ```bash
86
+ recheck-mcp
87
+ # or: python -m recheck.mcp_server
88
+ ```
89
+
90
+ The server exposes one tool, `recheck_sources`, with the same JSON shape as the CLI. Point your MCP client at the `recheck-mcp` command on stdio.
91
+
92
+ Example Cursor / Claude-style config:
93
+
94
+ ```json
95
+ {
96
+ "mcpServers": {
97
+ "recheck": {
98
+ "command": "recheck-mcp"
99
+ }
100
+ }
101
+ }
102
+ ```
103
+
104
+ ## Library
105
+
106
+ ```python
107
+ from recheck import SourceInput, recheck_sources_sync
108
+
109
+ report = recheck_sources_sync([
110
+ SourceInput(
111
+ url="https://fitzyracing1.github.io/x-algorithm-changelog/",
112
+ quotes=["VideoOpenWeight"],
113
+ )
114
+ ])
115
+ print(report.ok, report.to_dict())
116
+ ```
117
+
118
+ Async callers can `await recheck_sources(...)` instead.
119
+
120
+ ## Install / develop
121
+
122
+ ```bash
123
+ python3 -m venv .venv
124
+ source .venv/bin/activate
125
+ pip install -e ".[dev]"
126
+ pytest
127
+ ```
128
+
129
+ Requires Python 3.11+.
130
+
131
+ ## Limits (v0)
132
+
133
+ - Fetches the raw HTTP response. It does not execute JavaScript, so quotes that exist only in a client-rendered app will look missing.
134
+ - Bodies are capped at 5 MB.
135
+ - `snapshot_hash` is a hash of the raw bytes. Pages with dynamic ads, timestamps, or CSRF tokens will show up as `changed` even when the quoted text is unchanged.
136
+ - Fuzzy matching samples windows on long pages, so it can miss a near-match or report a softer score than a full scan.
137
+ - No cookies, auth, or robots-txt handling. This is a verifier for URLs the model already opened, not a crawler.
138
+ - Concurrent fetches are capped (default 8) so a long source list cannot hammer a site.
139
+
140
+ ## License
141
+
142
+ MIT.
@@ -0,0 +1,116 @@
1
+ # recheck
2
+
3
+ Re-fetch every URL an AI looked at and check that the quotes in its answer still appear on the live page.
4
+
5
+ Built after stale cached copies of a changelog produced bad drafts: the model quoted a page that had already changed (or a cached snapshot that no longer matched production). `recheck` is meant to be called *while an answer is still being written* so those misses get flagged before anyone ships the draft.
6
+
7
+ ## 30-second example
8
+
9
+ ```bash
10
+ pip install recheck-ai
11
+ # or: pip install git+https://github.com/fitzyracing1/recheck
12
+
13
+ recheck https://fitzyracing1.github.io/x-algorithm-changelog/ \
14
+ --quote 'VideoOpenWeight' \
15
+ --quote 'this-quote-is-definitely-not-here-xyz'
16
+ ```
17
+
18
+ The PyPI package is named `recheck-ai` because the name `recheck` is already taken. The commands remain `recheck` and `recheck-mcp`.
19
+
20
+ You should see the first quote marked found (`✓`, exact or compact, score `1.00`) and the second marked missing (`✗`). Exit status is `1` whenever any source failed or any quote was not found; pass `--json` for a machine-readable report.
21
+
22
+ JSON input (what a bot should send mid-answer):
23
+
24
+ ```bash
25
+ recheck examples/sources.json
26
+ recheck examples/sources.json --json
27
+ ```
28
+
29
+ ```json
30
+ [
31
+ {
32
+ "url": "https://fitzyracing1.github.io/x-algorithm-changelog/",
33
+ "quotes": ["VideoOpenWeight", "this-quote-is-definitely-not-here-xyz"],
34
+ "snapshot_hash": "optional-sha256-of-the-body-you-already-fetched",
35
+ "fetched_at": "2026-11-26T08:00:00Z"
36
+ }
37
+ ]
38
+ ```
39
+
40
+ `snapshot_hash` is the SHA-256 hex digest of the raw response body (optionally prefixed with `sha256:`). If you pass one and the live body hashes differently, the source is flagged `changed` even when the quotes are still present.
41
+
42
+ ## Statuses
43
+
44
+ | Status | Meaning |
45
+ |------------|------------------------------------------------------|
46
+ | `ok` | Fetched, optional snapshot matches |
47
+ | `changed` | Fetched, but `snapshot_hash` does not match the live body |
48
+ | `gone` | HTTP 404 or 410 |
49
+ | `blocked` | HTTP 401, 403, 407, or 429 |
50
+ | `timeout` | The request exceeded `--timeout` (default 15s) |
51
+ | `error` | Other network or HTTP failures |
52
+
53
+ Each quote is checked against the live body after normalizing whitespace and case. If that misses, a compact alphanumeric comparison runs (so `Video Open Weight` still matches `VideoOpenWeight`). If that also misses, a windowed fuzzy score is reported; scores at or above `--fuzzy-threshold` (default `0.8`) count as found.
54
+
55
+ ## MCP
56
+
57
+ A tiny stdio MCP server is included so any bot can call this mid-answer. It has no dependency beyond `httpx`.
58
+
59
+ ```bash
60
+ recheck-mcp
61
+ # or: python -m recheck.mcp_server
62
+ ```
63
+
64
+ The server exposes one tool, `recheck_sources`, with the same JSON shape as the CLI. Point your MCP client at the `recheck-mcp` command on stdio.
65
+
66
+ Example Cursor / Claude-style config:
67
+
68
+ ```json
69
+ {
70
+ "mcpServers": {
71
+ "recheck": {
72
+ "command": "recheck-mcp"
73
+ }
74
+ }
75
+ }
76
+ ```
77
+
78
+ ## Library
79
+
80
+ ```python
81
+ from recheck import SourceInput, recheck_sources_sync
82
+
83
+ report = recheck_sources_sync([
84
+ SourceInput(
85
+ url="https://fitzyracing1.github.io/x-algorithm-changelog/",
86
+ quotes=["VideoOpenWeight"],
87
+ )
88
+ ])
89
+ print(report.ok, report.to_dict())
90
+ ```
91
+
92
+ Async callers can `await recheck_sources(...)` instead.
93
+
94
+ ## Install / develop
95
+
96
+ ```bash
97
+ python3 -m venv .venv
98
+ source .venv/bin/activate
99
+ pip install -e ".[dev]"
100
+ pytest
101
+ ```
102
+
103
+ Requires Python 3.11+.
104
+
105
+ ## Limits (v0)
106
+
107
+ - Fetches the raw HTTP response. It does not execute JavaScript, so quotes that exist only in a client-rendered app will look missing.
108
+ - Bodies are capped at 5 MB.
109
+ - `snapshot_hash` is a hash of the raw bytes. Pages with dynamic ads, timestamps, or CSRF tokens will show up as `changed` even when the quoted text is unchanged.
110
+ - Fuzzy matching samples windows on long pages, so it can miss a near-match or report a softer score than a full scan.
111
+ - No cookies, auth, or robots-txt handling. This is a verifier for URLs the model already opened, not a crawler.
112
+ - Concurrent fetches are capped (default 8) so a long source list cannot hammer a site.
113
+
114
+ ## License
115
+
116
+ MIT.
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "recheck-ai"
7
+ version = "0.1.0"
8
+ description = "Re-fetch AI source URLs live and verify quoted claims still appear on the page."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ authors = [{ name = "Joshua Almeida", email = "192924532+fitzyracing1@users.noreply.github.com" }]
14
+ keywords = ["ai", "citations", "sources", "verification", "mcp"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Topic :: Internet :: WWW/HTTP",
22
+ ]
23
+ dependencies = [
24
+ "httpx>=0.27",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ dev = [
29
+ "pytest>=8",
30
+ "pytest-asyncio>=0.24",
31
+ "respx>=0.21",
32
+ ]
33
+
34
+ [project.scripts]
35
+ recheck = "recheck.cli:main"
36
+ recheck-mcp = "recheck.mcp_server:main"
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/fitzyracing1/recheck"
40
+ Issues = "https://github.com/fitzyracing1/recheck/issues"
41
+ PyPI = "https://pypi.org/project/recheck-ai/"
42
+
43
+ [tool.setuptools.package-dir]
44
+ "" = "src"
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["src"]
48
+
49
+ [tool.pytest.ini_options]
50
+ testpaths = ["tests"]
51
+ asyncio_mode = "auto"
52
+ asyncio_default_fixture_loop_scope = "function"
53
+ addopts = "-q"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,14 @@
1
+ """Recheck: re-fetch source URLs live and verify quoted claims still appear."""
2
+
3
+ from .check import recheck_sources, recheck_sources_sync
4
+ from .models import QuoteMatch, RecheckReport, SourceInput, SourceResult
5
+
6
+ __version__ = "0.1.0"
7
+ __all__ = [
8
+ "QuoteMatch",
9
+ "RecheckReport",
10
+ "SourceInput",
11
+ "SourceResult",
12
+ "recheck_sources",
13
+ "recheck_sources_sync",
14
+ ]
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,127 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from datetime import datetime, timezone
5
+ from typing import Iterable, Sequence
6
+
7
+ import httpx
8
+
9
+ from .fetch import (
10
+ DEFAULT_MAX_BYTES,
11
+ DEFAULT_TIMEOUT,
12
+ DEFAULT_USER_AGENT,
13
+ fetch_url,
14
+ normalize_hash,
15
+ )
16
+ from .match import DEFAULT_FUZZY_THRESHOLD, match_quote
17
+ from .models import RecheckReport, SourceInput, SourceResult, SourceStatus
18
+
19
+
20
+ def parse_sources(raw: object) -> list[SourceInput]:
21
+ """Accept a list of URLs, a list of source objects, or a wrapping document."""
22
+ if raw is None:
23
+ raise ValueError("no sources provided")
24
+ if isinstance(raw, (str, bytes)):
25
+ raise ValueError("sources must be a list or an object with a 'sources' key")
26
+ if isinstance(raw, dict):
27
+ if "sources" in raw:
28
+ raw = raw["sources"]
29
+ elif "urls" in raw:
30
+ raw = raw["urls"]
31
+ else:
32
+ # A single source object.
33
+ return [SourceInput.from_obj(raw)]
34
+ if not isinstance(raw, list):
35
+ raise ValueError("sources must be a list of URLs or source objects")
36
+ if not raw:
37
+ return []
38
+ return [SourceInput.from_obj(item) for item in raw]
39
+
40
+
41
+ def _status_for(fetch, snapshot_hash: str | None) -> SourceStatus:
42
+ if fetch.timed_out:
43
+ return "timeout"
44
+ if fetch.http_status in {404, 410}:
45
+ return "gone"
46
+ if fetch.blocked or fetch.http_status in {401, 403, 407, 429}:
47
+ return "blocked"
48
+ if fetch.http_status is None:
49
+ return "error"
50
+ if fetch.http_status >= 400:
51
+ return "error"
52
+ expected = normalize_hash(snapshot_hash)
53
+ actual = normalize_hash(fetch.content_hash)
54
+ if expected and actual and expected != actual:
55
+ return "changed"
56
+ return "ok"
57
+
58
+
59
+ async def recheck_sources(
60
+ sources: Sequence[SourceInput] | Iterable[SourceInput],
61
+ *,
62
+ concurrency: int = 8,
63
+ timeout: float = DEFAULT_TIMEOUT,
64
+ fuzzy_threshold: float = DEFAULT_FUZZY_THRESHOLD,
65
+ user_agent: str = DEFAULT_USER_AGENT,
66
+ max_bytes: int = DEFAULT_MAX_BYTES,
67
+ client: httpx.AsyncClient | None = None,
68
+ ) -> RecheckReport:
69
+ items = list(sources)
70
+ sem = asyncio.Semaphore(max(1, concurrency))
71
+ timeout_cfg = httpx.Timeout(timeout)
72
+
73
+ async def _one(source: SourceInput, http: httpx.AsyncClient) -> SourceResult:
74
+ started = asyncio.get_running_loop().time()
75
+ async with sem:
76
+ fetched = await fetch_url(http, source.url, max_bytes=max_bytes)
77
+ elapsed_ms = int((asyncio.get_running_loop().time() - started) * 1000)
78
+ status = _status_for(fetched, source.snapshot_hash)
79
+ quotes = []
80
+ if fetched.body:
81
+ quotes = [
82
+ match_quote(q, fetched.body, fuzzy_threshold=fuzzy_threshold)
83
+ for q in source.quotes
84
+ ]
85
+ elif source.quotes:
86
+ quotes = [
87
+ match_quote(q, "", fuzzy_threshold=fuzzy_threshold) for q in source.quotes
88
+ ]
89
+ snapshot_match: bool | None = None
90
+ expected = normalize_hash(source.snapshot_hash)
91
+ actual = normalize_hash(fetched.content_hash)
92
+ if expected and actual:
93
+ snapshot_match = expected == actual
94
+ return SourceResult(
95
+ url=source.url,
96
+ status=status,
97
+ http_status=fetched.http_status,
98
+ final_url=fetched.final_url,
99
+ content_hash=fetched.content_hash,
100
+ snapshot_hash=source.snapshot_hash,
101
+ snapshot_match=snapshot_match,
102
+ fetched_at=source.fetched_at,
103
+ elapsed_ms=elapsed_ms,
104
+ error=fetched.error,
105
+ quotes=quotes,
106
+ )
107
+
108
+ async def _run(http: httpx.AsyncClient) -> list[SourceResult]:
109
+ return list(await asyncio.gather(*(_one(s, http) for s in items)))
110
+
111
+ if client is not None:
112
+ results = await _run(client)
113
+ else:
114
+ headers = {"User-Agent": user_agent, "Accept": "text/html,application/json,text/plain,*/*"}
115
+ async with httpx.AsyncClient(
116
+ headers=headers,
117
+ timeout=timeout_cfg,
118
+ follow_redirects=True,
119
+ ) as http:
120
+ results = await _run(http)
121
+
122
+ checked_at = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
123
+ return RecheckReport(checked_at=checked_at, sources=results)
124
+
125
+
126
+ def recheck_sources_sync(*args, **kwargs) -> RecheckReport:
127
+ return asyncio.run(recheck_sources(*args, **kwargs))
@@ -0,0 +1,174 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import Any, Sequence, TextIO
8
+
9
+ from . import __version__
10
+ from .check import parse_sources, recheck_sources_sync
11
+ from .fetch import DEFAULT_TIMEOUT
12
+ from .match import DEFAULT_FUZZY_THRESHOLD
13
+ from .models import RecheckReport, SourceInput
14
+
15
+
16
+ def _looks_like_url(value: str) -> bool:
17
+ lowered = value.lower()
18
+ return lowered.startswith(("http://", "https://"))
19
+
20
+
21
+ def _load_json(text: str) -> Any:
22
+ return json.loads(text)
23
+
24
+
25
+ def load_inputs(values: Sequence[str], quotes: Sequence[str]) -> list[SourceInput]:
26
+ if not values:
27
+ raise ValueError("provide a JSON file, '-' for stdin, or one or more URLs")
28
+
29
+ # A single '-' or an existing file is treated as JSON input.
30
+ if len(values) == 1 and (values[0] == "-" or Path(values[0]).is_file()):
31
+ if values[0] == "-":
32
+ raw_text = sys.stdin.read()
33
+ else:
34
+ raw_text = Path(values[0]).read_text(encoding="utf-8")
35
+ raw = _load_json(raw_text)
36
+ sources = parse_sources(raw)
37
+ if quotes:
38
+ for source in sources:
39
+ source.quotes.extend(quotes)
40
+ return sources
41
+
42
+ # A single JSON literal (e.g. '[{"url":"..."}]' or '{"sources":[...]}').
43
+ if len(values) == 1 and values[0].lstrip().startswith(("[", "{")):
44
+ sources = parse_sources(_load_json(values[0]))
45
+ if quotes:
46
+ for source in sources:
47
+ source.quotes.extend(quotes)
48
+ return sources
49
+
50
+ if all(_looks_like_url(v) for v in values):
51
+ return [SourceInput(url=v, quotes=list(quotes)) for v in values]
52
+
53
+ # If the path was typo'd, say so clearly instead of treating it as a URL.
54
+ if len(values) == 1 and not _looks_like_url(values[0]):
55
+ raise ValueError(
56
+ f"not a URL or existing JSON file: {values[0]!r}"
57
+ )
58
+ raise ValueError("mix of URLs and non-URLs; pass only URLs or a single JSON file")
59
+
60
+
61
+ def format_table(report: RecheckReport) -> str:
62
+ lines: list[str] = []
63
+ if not report.sources:
64
+ return "no sources"
65
+ for source in report.sources:
66
+ hash_bit = f" hash={source.content_hash[:12]}…" if source.content_hash else ""
67
+ http_bit = f" HTTP {source.http_status}" if source.http_status is not None else ""
68
+ time_bit = f" {source.elapsed_ms}ms" if source.elapsed_ms is not None else ""
69
+ snap = ""
70
+ if source.snapshot_match is True:
71
+ snap = " snapshot=match"
72
+ elif source.snapshot_match is False:
73
+ snap = " snapshot=mismatch"
74
+ lines.append(
75
+ f"{source.url} {source.status}{http_bit}{time_bit}{hash_bit}{snap}"
76
+ )
77
+ if source.final_url and source.final_url != source.url:
78
+ lines.append(f" → {source.final_url}")
79
+ if source.error:
80
+ lines.append(f" error: {source.error}")
81
+ if not source.quotes:
82
+ lines.append(" (no quotes to check)")
83
+ continue
84
+ for match in source.quotes:
85
+ mark = "✓" if match.found else "✗"
86
+ preview = match.quote.replace("\n", " ")
87
+ if len(preview) > 80:
88
+ preview = preview[:77] + "…"
89
+ lines.append(
90
+ f" {mark} {preview} {match.method} {match.score:.2f}"
91
+ )
92
+ overall = "PASS" if report.ok else "FAIL"
93
+ lines.append(f"\n{overall} {len(report.sources)} source(s) checked_at={report.checked_at}")
94
+ return "\n".join(lines)
95
+
96
+
97
+ def build_parser() -> argparse.ArgumentParser:
98
+ parser = argparse.ArgumentParser(
99
+ prog="recheck",
100
+ description=(
101
+ "Re-fetch source URLs live and check that quoted claims still appear "
102
+ "on the page. Flags stale, changed, blocked, or dead sources."
103
+ ),
104
+ )
105
+ parser.add_argument(
106
+ "sources",
107
+ nargs="*",
108
+ help="JSON file, JSON literal, '-' for stdin, or one or more URLs",
109
+ )
110
+ parser.add_argument(
111
+ "-q",
112
+ "--quote",
113
+ action="append",
114
+ default=[],
115
+ help="Quote/claim to look for (repeatable). Added to every source.",
116
+ )
117
+ parser.add_argument(
118
+ "--json",
119
+ action="store_true",
120
+ help="Print a machine-readable JSON report",
121
+ )
122
+ parser.add_argument(
123
+ "--concurrency",
124
+ type=int,
125
+ default=8,
126
+ help="Max parallel fetches (default: 8)",
127
+ )
128
+ parser.add_argument(
129
+ "--timeout",
130
+ type=float,
131
+ default=DEFAULT_TIMEOUT,
132
+ help=f"Per-request timeout in seconds (default: {DEFAULT_TIMEOUT:g})",
133
+ )
134
+ parser.add_argument(
135
+ "--fuzzy-threshold",
136
+ type=float,
137
+ default=DEFAULT_FUZZY_THRESHOLD,
138
+ help=f"Minimum fuzzy score to count as found (default: {DEFAULT_FUZZY_THRESHOLD})",
139
+ )
140
+ parser.add_argument(
141
+ "--version",
142
+ action="version",
143
+ version=f"recheck {__version__}",
144
+ )
145
+ return parser
146
+
147
+
148
+ def main(argv: Sequence[str] | None = None, out: TextIO | None = None) -> int:
149
+ parser = build_parser()
150
+ args = parser.parse_args(argv)
151
+ stream = out or sys.stdout
152
+ try:
153
+ sources = load_inputs(args.sources, args.quote)
154
+ except ValueError as exc:
155
+ parser.error(str(exc))
156
+ except json.JSONDecodeError as exc:
157
+ parser.error(f"invalid JSON: {exc}")
158
+
159
+ report = recheck_sources_sync(
160
+ sources,
161
+ concurrency=args.concurrency,
162
+ timeout=args.timeout,
163
+ fuzzy_threshold=args.fuzzy_threshold,
164
+ )
165
+ if args.json:
166
+ json.dump(report.to_dict(), stream, indent=2, ensure_ascii=False)
167
+ stream.write("\n")
168
+ else:
169
+ stream.write(format_table(report) + "\n")
170
+ return 0 if report.ok else 1
171
+
172
+
173
+ if __name__ == "__main__":
174
+ raise SystemExit(main())