omnirank 0.5.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.
Files changed (183) hide show
  1. omnirank/__init__.py +14 -0
  2. omnirank/__main__.py +6 -0
  3. omnirank/adapters/__init__.py +202 -0
  4. omnirank/adapters/astro.py +338 -0
  5. omnirank/adapters/base.py +372 -0
  6. omnirank/adapters/html.py +561 -0
  7. omnirank/adapters/jsx.py +340 -0
  8. omnirank/adapters/nextjs.py +692 -0
  9. omnirank/aeo/__init__.py +9 -0
  10. omnirank/aeo/extract.py +383 -0
  11. omnirank/aeo/propose.py +84 -0
  12. omnirank/aeo/rules.py +964 -0
  13. omnirank/aeo/runner.py +148 -0
  14. omnirank/applicability.py +98 -0
  15. omnirank/apply/__init__.py +23 -0
  16. omnirank/apply/engine.py +1254 -0
  17. omnirank/apply/journal.py +139 -0
  18. omnirank/apply/patch.py +144 -0
  19. omnirank/audit.py +185 -0
  20. omnirank/bands.py +106 -0
  21. omnirank/brief/__init__.py +0 -0
  22. omnirank/brief/analyze.py +197 -0
  23. omnirank/brief/constants.py +89 -0
  24. omnirank/brief/cost.py +62 -0
  25. omnirank/brief/egress.py +23 -0
  26. omnirank/brief/fetchpages.py +239 -0
  27. omnirank/brief/render.py +151 -0
  28. omnirank/brief/runner.py +369 -0
  29. omnirank/brief/serp.py +274 -0
  30. omnirank/brief/text.py +181 -0
  31. omnirank/cli.py +844 -0
  32. omnirank/clock.py +22 -0
  33. omnirank/cms/__init__.py +1 -0
  34. omnirank/cms/runner.py +170 -0
  35. omnirank/cms/wordpress.py +495 -0
  36. omnirank/cms/wordpress_apply.py +508 -0
  37. omnirank/cms/wordpress_plan.py +280 -0
  38. omnirank/config.py +81 -0
  39. omnirank/connect/__init__.py +4 -0
  40. omnirank/connect/bing.py +284 -0
  41. omnirank/connect/cloud_setup.py +43 -0
  42. omnirank/connect/confirm.py +242 -0
  43. omnirank/connect/constants.py +226 -0
  44. omnirank/connect/doctor.py +270 -0
  45. omnirank/connect/ga4.py +749 -0
  46. omnirank/connect/ga4_ai.py +123 -0
  47. omnirank/connect/google_auth.py +657 -0
  48. omnirank/connect/gsc.py +630 -0
  49. omnirank/connect/gsc_reports.py +169 -0
  50. omnirank/connect/http.py +310 -0
  51. omnirank/connect/indexnow.py +373 -0
  52. omnirank/connect/naver.py +536 -0
  53. omnirank/connect/runner.py +515 -0
  54. omnirank/connect/runner_ga4_ai.py +59 -0
  55. omnirank/connect/runner_more.py +489 -0
  56. omnirank/connect/runner_regional.py +260 -0
  57. omnirank/connect/secrets.py +190 -0
  58. omnirank/connect/urlcheck.py +41 -0
  59. omnirank/connect/yandex.py +350 -0
  60. omnirank/crawl/__init__.py +11 -0
  61. omnirank/crawl/analyze.py +493 -0
  62. omnirank/crawl/crawler.py +491 -0
  63. omnirank/crawl/custom.py +175 -0
  64. omnirank/crawl/export.py +67 -0
  65. omnirank/crawl/fetcher.py +212 -0
  66. omnirank/crawl/parse.py +102 -0
  67. omnirank/crawl/render.py +148 -0
  68. omnirank/crawl/robotsgate.py +198 -0
  69. omnirank/crawl/runner.py +295 -0
  70. omnirank/crawl/sitemap.py +99 -0
  71. omnirank/crawl/text.py +20 -0
  72. omnirank/crawl/urls.py +100 -0
  73. omnirank/crawlers.py +564 -0
  74. omnirank/data/ai_crawlers.json +269 -0
  75. omnirank/data/ai_referrers.json +42 -0
  76. omnirank/fetch.py +107 -0
  77. omnirank/fixes/__init__.py +92 -0
  78. omnirank/fixes/base.py +232 -0
  79. omnirank/fixes/canonical.py +243 -0
  80. omnirank/fixes/schema.py +126 -0
  81. omnirank/formats.py +134 -0
  82. omnirank/framework.py +223 -0
  83. omnirank/gates/__init__.py +48 -0
  84. omnirank/gates/aeo.py +114 -0
  85. omnirank/gates/contradictions.py +280 -0
  86. omnirank/gates/crawler_policy.py +85 -0
  87. omnirank/gates/geo.py +152 -0
  88. omnirank/gates/hygiene.py +81 -0
  89. omnirank/gates/jsonld.py +282 -0
  90. omnirank/gates/onpage.py +177 -0
  91. omnirank/gates/perf.py +115 -0
  92. omnirank/gates/security.py +264 -0
  93. omnirank/gates/seo.py +118 -0
  94. omnirank/gates/site.py +248 -0
  95. omnirank/geo_artifacts.py +199 -0
  96. omnirank/html.py +79 -0
  97. omnirank/keywords/__init__.py +5 -0
  98. omnirank/keywords/constants.py +69 -0
  99. omnirank/keywords/engine.py +384 -0
  100. omnirank/keywords/report.py +143 -0
  101. omnirank/keywords/runner.py +160 -0
  102. omnirank/keywords/source.py +60 -0
  103. omnirank/keywords/text.py +45 -0
  104. omnirank/locator.py +480 -0
  105. omnirank/logs/__init__.py +0 -0
  106. omnirank/logs/analyze.py +127 -0
  107. omnirank/logs/bots.py +69 -0
  108. omnirank/logs/ipranges.py +191 -0
  109. omnirank/logs/parse.py +452 -0
  110. omnirank/logs/paths.py +22 -0
  111. omnirank/logs/privacy.py +105 -0
  112. omnirank/logs/runner.py +179 -0
  113. omnirank/mcp_server.py +1480 -0
  114. omnirank/netguard.py +525 -0
  115. omnirank/packs/__init__.py +6 -0
  116. omnirank/packs/backlinks.py +535 -0
  117. omnirank/packs/blog.py +544 -0
  118. omnirank/packs/blog_cross.py +468 -0
  119. omnirank/packs/crawlers.py +23 -0
  120. omnirank/packs/entity.py +492 -0
  121. omnirank/packs/feeds.py +150 -0
  122. omnirank/packs/frontmatter.py +59 -0
  123. omnirank/packs/gsc.py +421 -0
  124. omnirank/packs/local.py +879 -0
  125. omnirank/packs/mdscan.py +326 -0
  126. omnirank/packs/miniyaml.py +378 -0
  127. omnirank/packs/model.py +46 -0
  128. omnirank/packs/product.py +979 -0
  129. omnirank/packs/refresh.py +165 -0
  130. omnirank/packs/runner.py +277 -0
  131. omnirank/packs/sitescan.py +294 -0
  132. omnirank/packs/textsafe.py +79 -0
  133. omnirank/packs/xmlsafe.py +92 -0
  134. omnirank/page.py +42 -0
  135. omnirank/registry.py +302 -0
  136. omnirank/report.py +251 -0
  137. omnirank/report_cmd/__init__.py +7 -0
  138. omnirank/report_cmd/delta.py +58 -0
  139. omnirank/report_cmd/files.py +64 -0
  140. omnirank/report_cmd/model.py +208 -0
  141. omnirank/report_cmd/notify.py +195 -0
  142. omnirank/report_cmd/pdf.py +83 -0
  143. omnirank/report_cmd/portfolio.py +342 -0
  144. omnirank/report_cmd/render.py +379 -0
  145. omnirank/report_cmd/runner.py +267 -0
  146. omnirank/robots.py +172 -0
  147. omnirank/scanner/__init__.py +10 -0
  148. omnirank/scanner/badge.py +90 -0
  149. omnirank/scanner/cache.py +69 -0
  150. omnirank/scanner/cli.py +96 -0
  151. omnirank/scanner/engine.py +289 -0
  152. omnirank/scanner/limits.py +98 -0
  153. omnirank/scanner/server.py +143 -0
  154. omnirank/scanner/service.py +328 -0
  155. omnirank/schema/__init__.py +13 -0
  156. omnirank/schema/catalog.py +679 -0
  157. omnirank/schema/catalog_specs.py +350 -0
  158. omnirank/schema/core.py +306 -0
  159. omnirank/schema/extract.py +396 -0
  160. omnirank/schema/gate.py +121 -0
  161. omnirank/schema/runner.py +213 -0
  162. omnirank/schema/validate.py +504 -0
  163. omnirank/schema/vocab.py +305 -0
  164. omnirank/schemas/omnirank.config.schema.json +268 -0
  165. omnirank/track/__init__.py +0 -0
  166. omnirank/track/ai_prompts.py +207 -0
  167. omnirank/track/analysis.py +197 -0
  168. omnirank/track/constants.py +155 -0
  169. omnirank/track/cost.py +229 -0
  170. omnirank/track/discover.py +277 -0
  171. omnirank/track/discover_cli.py +309 -0
  172. omnirank/track/discover_constants.py +95 -0
  173. omnirank/track/engines.py +216 -0
  174. omnirank/track/estimate_view.py +212 -0
  175. omnirank/track/history.py +261 -0
  176. omnirank/track/runner.py +586 -0
  177. omnirank/track/stats.py +138 -0
  178. omnirank/track/storage.py +128 -0
  179. omnirank-0.5.0.dist-info/METADATA +47 -0
  180. omnirank-0.5.0.dist-info/RECORD +183 -0
  181. omnirank-0.5.0.dist-info/WHEEL +5 -0
  182. omnirank-0.5.0.dist-info/entry_points.txt +2 -0
  183. omnirank-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1254 @@
1
+ """`omnirank apply` and `omnirank undo`: the only code that writes user files.
2
+
3
+ Built to refuse rather than to guess. The fix generators in `omnirank.fixes`
4
+ never write; they return unified diffs. This module decides which of those
5
+ diffs may be written, writes them, and can put them back. The contracts are
6
+ the write guarantees in docs/research/2026-08-04-automation-architecture.md
7
+ SS2.5-2.6 and spec SS18:
8
+
9
+ - Dry run is the default; `write()` is only reached behind `--write`.
10
+ - Only `exact` locator confidence is written (`inferred` with
11
+ --allow-inferred, which lifts nothing else: tier, blast radius and protected
12
+ surfaces still cap applicability).
13
+ - Never outside --root, never through a symlink, never `.env*`, key files,
14
+ lockfiles, VCS/dependency directories, and only the file types the
15
+ generators edit (.html/.htm) -- plus, for a file a framework adapter
16
+ (`omnirank.adapters`) produced the edit for AND the locator found with
17
+ confidence `exact`, that adapter's own types (.tsx/.jsx/.ts/.js, .astro).
18
+ - Never over uncommitted work: a dirty, untracked or git-ignored target is
19
+ skipped unless --force. A merge/rebase/cherry-pick in progress refuses
20
+ everything, --force or not. A non-git project refuses unless --force.
21
+ - Hash-checked: a patch applies only when every context line matches the file
22
+ byte for byte at its exact line, the file's bytes are unchanged since the
23
+ generator read them, and the whole patch round-trips to the very diff that
24
+ was shown. Bytes outside the hunks are never touched (G2).
25
+ - All or nothing across files: every file is re-hashed and staged to a temp
26
+ file next to it before ANY file is replaced; a failure while replacing rolls
27
+ back the files already replaced.
28
+ - Atomic per file: temp file in the same directory, fsync, original mode,
29
+ `os.replace`. Line endings and encoding are preserved because the bytes are
30
+ decoded as strict UTF-8 and re-encoded unchanged; nothing is normalised.
31
+ - Journaled and reversible: `.omnirank/journal/<id>.json` records each file's
32
+ before/after SHA-256, mode, the fixes applied, a reverse patch and the
33
+ pre-image; `undo()` refuses when the user edited a file since (G5).
34
+ - Idempotent: generators detect existing shape, so a second run produces no
35
+ diff and writes nothing -- not even a journal (G3).
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import hashlib
40
+ import json
41
+ import os
42
+ import stat
43
+ import subprocess
44
+ import tempfile
45
+ from collections.abc import Callable, Iterable, Sequence
46
+ from dataclasses import dataclass
47
+ from datetime import UTC, datetime
48
+ from functools import cached_property
49
+ from pathlib import Path, PurePosixPath
50
+
51
+ from bs4 import BeautifulSoup
52
+
53
+ from .. import __version__
54
+ from ..adapters import BY_NAME as ADAPTERS
55
+ from ..adapters import Edit, suffixes_for
56
+ from ..adapters import plan as adapter_plan
57
+ from ..fixes import FixOutcome, generate
58
+ from ..fixes.base import newline_style, unified_diff
59
+ from ..framework import Detection, detect
60
+ from ..html import find_ldjson_scripts
61
+ from ..locator import Location, blast_radius, locate
62
+ from ..report import Finding
63
+ from . import journal, patch
64
+
65
+ # The file types the generators actually edit. A wider allow-list would be
66
+ # write access nothing has earned yet.
67
+ WRITABLE_SUFFIXES = (".html", ".htm")
68
+
69
+ LOCKFILES = frozenset({
70
+ "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml",
71
+ "bun.lock", "bun.lockb", "deno.lock", "poetry.lock", "pipfile.lock", "pdm.lock",
72
+ "uv.lock", "cargo.lock", "gemfile.lock", "composer.lock", "go.sum", "go.work.sum",
73
+ "mix.lock", "pubspec.lock", "podfile.lock", "packages.lock.json", "flake.lock",
74
+ })
75
+ SECRET_NAMES = frozenset({
76
+ ".npmrc", ".pypirc", ".netrc", ".htpasswd", ".git-credentials", ".dockercfg",
77
+ "credentials", "credentials.json", "secrets.json", "secrets.yml", "secrets.yaml",
78
+ "service-account.json", "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519",
79
+ "id_rsa.pub", "id_dsa.pub", "id_ecdsa.pub", "id_ed25519.pub",
80
+ })
81
+ SECRET_SUFFIXES = (".pem", ".key", ".p12", ".pfx", ".jks", ".keystore", ".crt", ".cer",
82
+ ".der", ".csr", ".gpg", ".asc", ".kdbx", ".ppk", ".p8")
83
+ PROTECTED_DIRS = frozenset({".git", ".hg", ".svn", ".omnirank", "node_modules"})
84
+ IN_PROGRESS = (("MERGE_HEAD", "merge"), ("CHERRY_PICK_HEAD", "cherry-pick"),
85
+ ("REVERT_HEAD", "revert"), ("REBASE_HEAD", "rebase"),
86
+ ("rebase-merge", "rebase"), ("rebase-apply", "rebase or am"))
87
+
88
+ UP_TO_DATE = "already in the desired state; nothing to write"
89
+ TEMP_PREFIX = ".omnirank-"
90
+
91
+
92
+ class ApplyAborted(Exception):
93
+ """The write was refused or failed; the message says what is on disk."""
94
+
95
+
96
+ class UndoRefused(Exception):
97
+ """The undo was refused; nothing was restored."""
98
+
99
+
100
+ class UndoIncomplete(Exception):
101
+ """Files WERE restored, but the journal could not be marked undone."""
102
+
103
+ def __init__(self, restored: list[str], error: OSError):
104
+ self.restored = restored
105
+ self.error = error
106
+ super().__init__(f"restored {', '.join(restored) or 'nothing'}, but the journal "
107
+ f"could not be updated ({error})")
108
+
109
+
110
+ class Interrupted(KeyboardInterrupt):
111
+ """Ctrl-C, re-raised with what is actually on disk.
112
+
113
+ `state` is one of:
114
+ - "nothing": interrupted before any file was replaced;
115
+ - "rolled-back": every replaced file was verified back at its old bytes;
116
+ - "partial": the rollback did not complete; `detail` says which files;
117
+ - "written": every file was written (apply) or restored (undo) before
118
+ the interrupt; only the bookkeeping after it was cut short.
119
+ """
120
+
121
+ def __init__(self, state: str, journal_id: str | None = None, detail: str = ""):
122
+ self.state = state
123
+ self.journal_id = journal_id
124
+ self.detail = detail
125
+ super().__init__(state)
126
+
127
+
128
+ def _sha(data: bytes) -> str:
129
+ return hashlib.sha256(data).hexdigest()
130
+
131
+
132
+ # --- planning --------------------------------------------------------------------
133
+
134
+
135
+ @dataclass(frozen=True)
136
+ class Candidate:
137
+ """One generator outcome plus the file bytes it was computed from.
138
+
139
+ `stable` is False when the file's bytes differed before and after the
140
+ generator read it -- the diff may describe neither version.
141
+ """
142
+
143
+ finding: Finding | None # None for an adapter edit (plan_edits)
144
+ location: Location
145
+ outcome: FixOutcome
146
+ snapshot: bytes | None
147
+ stable: bool
148
+
149
+
150
+ def _read(root: Path, rel: str | None) -> bytes | None:
151
+ if rel is None:
152
+ return None
153
+ try:
154
+ return (Path(root) / rel).read_bytes()
155
+ except OSError:
156
+ return None
157
+
158
+
159
+ def make_candidate(finding: Finding, location: Location, *, root: str | Path,
160
+ routes_served: int | None, findings: Sequence[Finding],
161
+ allow_inferred: bool, detection: Detection | None = None) -> Candidate:
162
+ before = _read(Path(root), location.path)
163
+ outcome = generate(finding, location, root=root, routes_served=routes_served,
164
+ findings=findings, allow_inferred=allow_inferred,
165
+ detection=detection)
166
+ after = _read(Path(root), location.path)
167
+ return Candidate(finding=finding, location=location, outcome=outcome,
168
+ snapshot=before, stable=before == after)
169
+
170
+
171
+ def plan(config, root: str | Path, *, audit: Callable, only: Iterable[str] | None = None,
172
+ allow_inferred: bool = False) -> tuple[Detection, list[Candidate]]:
173
+ """The same fix plan `prescribe` computes, keeping each file's snapshot."""
174
+ selected = set(only) if only else None
175
+ report = audit(config)
176
+ detection = detect(root)
177
+ candidates: list[Candidate] = []
178
+ for finding in report.findings:
179
+ if finding.fix_tier != "mechanical":
180
+ continue
181
+ if selected is not None and finding.id not in selected:
182
+ continue
183
+ location = locate(finding.url, detection=detection, root=root)
184
+ candidates.append(make_candidate(
185
+ finding, location, root=root,
186
+ routes_served=blast_radius(location, detection=detection, root=root),
187
+ findings=report.findings, allow_inferred=allow_inferred,
188
+ detection=detection))
189
+ return detection, candidates
190
+
191
+
192
+ def plan_edits(root: str | Path, url: str, edits: Sequence[Edit], *,
193
+ detection: Detection | None = None) -> tuple[Detection, list[Candidate]]:
194
+ """Candidates for abstract page edits (`omnirank.adapters`) on `url`.
195
+
196
+ One candidate carries every edit the adapter could make (one diff, id
197
+ `edit.title,edit.description,...`); each refused edit becomes its own
198
+ declined candidate with the adapter's reason. `decide()` and `write()`
199
+ then apply exactly the same checks as for a generated fix.
200
+ """
201
+ root = Path(root)
202
+ planned = adapter_plan(root, url, edits, detection=detection)
203
+ location = planned.location
204
+ rel = location.path
205
+ before = _read(root, rel)
206
+ candidates: list[Candidate] = []
207
+
208
+ def declined(edit_id: str, reason: str) -> Candidate:
209
+ out = FixOutcome(finding_id=edit_id, url=url, fix_tier="mechanical",
210
+ applicability="display-only", path=rel, diff=None,
211
+ reason=reason, adapter=planned.adapter)
212
+ return Candidate(None, location, out, before, True)
213
+
214
+ for edit, reason in planned.refused:
215
+ candidates.append(declined(edit.id, reason))
216
+ rendered = planned.rendered
217
+ if rendered is not None:
218
+ after = _read(root, rel)
219
+ stable = after == before and before is not None and \
220
+ before.decode("utf-8", "replace") == planned.before
221
+ for edit in rendered.unchanged:
222
+ candidates.append(declined(edit.id, UP_TO_DATE))
223
+ if rendered.applied:
224
+ out = FixOutcome(
225
+ finding_id=",".join(edit.id for edit in rendered.applied), url=url,
226
+ fix_tier="mechanical", applicability="safe", path=rel,
227
+ diff=planned.diff, reason=None, adapter=planned.adapter)
228
+ candidates.append(Candidate(None, location, out, before, stable))
229
+ return planned.detection, candidates
230
+
231
+
232
+ # --- path safety -------------------------------------------------------------------
233
+
234
+
235
+ def _name_refusal(rel: str, suffixes: tuple[str, ...] = WRITABLE_SUFFIXES) -> str | None:
236
+ pure = PurePosixPath(rel)
237
+ if not rel or pure.is_absolute() or any(p in ("", ".", "..") for p in rel.split("/")):
238
+ return f"refused: {rel!r} is outside the project root or not a plain relative path"
239
+ for part in pure.parts[:-1]:
240
+ if part.lower() in PROTECTED_DIRS:
241
+ return f"refused: {rel} is inside {part}/, which OmniRank never edits"
242
+ name = pure.name.lower()
243
+ if name == ".env" or name.startswith(".env.") or name.endswith(".env"):
244
+ return f"refused: {pure.name} is an environment file; OmniRank never edits .env files"
245
+ if name in LOCKFILES or name.endswith(".lock"):
246
+ return f"refused: {pure.name} is a lockfile; OmniRank never edits lockfiles"
247
+ if name in SECRET_NAMES or name.endswith(SECRET_SUFFIXES):
248
+ return (f"refused: {pure.name} looks like a key or credential file; "
249
+ "OmniRank never edits those")
250
+ if not name.endswith(suffixes):
251
+ if suffixes == WRITABLE_SUFFIXES:
252
+ return (f"refused: {rel} is not an .html/.htm file; apply only writes the "
253
+ "file types its generators edit (.html, .htm)")
254
+ return (f"refused: {rel} is not a file type this adapter writes "
255
+ f"({', '.join(suffixes)})")
256
+ return None
257
+
258
+
259
+ def check_target(root: str | Path, rel: str,
260
+ suffixes: tuple[str, ...] = WRITABLE_SUFFIXES) -> str | None:
261
+ """None when `rel` may be written, else the refusal reason.
262
+
263
+ `suffixes` widens the file-type allow-list beyond .html/.htm ONLY for a
264
+ file an adapter edits (see `_suffixes`); every other refusal still applies.
265
+
266
+ Walks every component with lstat: a symlink anywhere below the root --
267
+ file or directory, pointing inside or outside -- is refused, never
268
+ followed. Then requires a single-link regular file whose resolved path is
269
+ still inside the resolved root.
270
+ """
271
+ reason = _name_refusal(rel, suffixes)
272
+ if reason is not None:
273
+ return reason
274
+ try:
275
+ real_root = Path(root).resolve(strict=True)
276
+ except OSError:
277
+ return f"refused: project root {root} does not exist"
278
+ current = real_root
279
+ for part in PurePosixPath(rel).parts:
280
+ parent = current
281
+ current = current / part
282
+ try:
283
+ info = os.lstat(current)
284
+ names = os.listdir(parent)
285
+ except FileNotFoundError:
286
+ return f"refused: {rel} does not exist"
287
+ except OSError as exc:
288
+ return f"refused: {rel} cannot be inspected ({exc.strerror})"
289
+ if part not in names:
290
+ # A case-insensitive filesystem resolved `part` to an entry spelled
291
+ # differently: the file the locator named is not the one on disk.
292
+ return (f"refused: {rel} does not match the on-disk name's case "
293
+ f"(no entry named exactly {part!r} in "
294
+ f"{parent.relative_to(real_root) or '.'})")
295
+ if stat.S_ISLNK(info.st_mode):
296
+ return (f"refused: {rel} goes through a symlink "
297
+ f"({current.relative_to(real_root)}); apply never writes through "
298
+ "symlinks, so it cannot be steered outside the project root")
299
+ if not stat.S_ISREG(info.st_mode):
300
+ return f"refused: {rel} is not a regular file"
301
+ if hasattr(os, "getuid") and info.st_uid != os.getuid():
302
+ return (f"refused: {rel} is owned by another user; replacing it would "
303
+ "silently change its owner")
304
+ if info.st_nlink > 1:
305
+ return (f"refused: {rel} is hard-linked ({info.st_nlink} links); replacing it "
306
+ "would silently split it from its other names")
307
+ if not current.resolve().is_relative_to(real_root):
308
+ return f"refused: {rel} resolves outside the project root"
309
+ return None
310
+
311
+
312
+ def readonly_reason(root: str | Path, rel: str) -> str | None:
313
+ """A refusal for a target without its owner write bit (lifted by --force)."""
314
+ try:
315
+ mode = os.stat(Path(root) / rel).st_mode
316
+ except OSError as exc:
317
+ return f"refused: {rel} cannot be inspected ({exc.strerror})"
318
+ if not mode & stat.S_IWUSR:
319
+ return (f"refused: {rel} is read-only (mode {oct(stat.S_IMODE(mode))}); pass "
320
+ "--force to write it anyway (its mode is kept)")
321
+ return None
322
+
323
+
324
+ # --- git ------------------------------------------------------------------------
325
+
326
+
327
+ class _Git:
328
+ """Read-only git queries. Never changes the repository."""
329
+
330
+ def __init__(self, root: Path):
331
+ self.root = root
332
+
333
+ def run(self, *args: str, literal: bool = True,
334
+ stdin: bytes | None = None) -> subprocess.CompletedProcess | None:
335
+ # --literal-pathspecs: a file named ":(glob)*" is that file, never a
336
+ # pattern. Only plumbing that never consults filter, diff or merge
337
+ # drivers is run (no `git status`: it runs a repository's clean filter
338
+ # on any stat-dirty file); fsmonitor and hooks are off and a partial
339
+ # clone never lazily fetches, so no repository-configured program runs.
340
+ env = {**os.environ, "GIT_OPTIONAL_LOCKS": "0", "LC_ALL": "C",
341
+ "GIT_NO_LAZY_FETCH": "1", "GIT_TERMINAL_PROMPT": "0"}
342
+ flags = ["--literal-pathspecs"] if literal else []
343
+ try:
344
+ return subprocess.run(
345
+ ["git", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null",
346
+ "-c", "log.showSignature=false", "-c", "protocol.allow=never", *flags,
347
+ "-C", str(self.root), *args],
348
+ input=stdin, stdin=None if stdin is not None else subprocess.DEVNULL,
349
+ check=False, capture_output=True, env=env, timeout=60)
350
+ except (OSError, subprocess.TimeoutExpired):
351
+ return None
352
+
353
+ @cached_property
354
+ def toplevel(self) -> Path | None:
355
+ result = self.run("rev-parse", "--show-toplevel")
356
+ if result is None or result.returncode != 0:
357
+ return None
358
+ return Path(result.stdout.decode("utf-8", "replace").strip())
359
+
360
+ def in_progress(self) -> str | None:
361
+ result = self.run("rev-parse", "--absolute-git-dir")
362
+ if result is None or result.returncode != 0:
363
+ return None
364
+ git_dir = Path(result.stdout.decode("utf-8", "replace").strip())
365
+ for marker, name in IN_PROGRESS:
366
+ if (git_dir / marker).exists():
367
+ return name
368
+ return None
369
+
370
+ def dirty_reason(self, rel: str) -> str | None:
371
+ """Ask the repository that OWNS the file, not the one at --root.
372
+
373
+ `git -C root status -- sub/x.html` reports nothing for a file inside a
374
+ submodule or a nested repository, so the query runs from the file's
375
+ own directory: whichever repository git finds there is the one that
376
+ can (or cannot) restore it.
377
+ """
378
+ if self.toplevel is None:
379
+ return None # preflight() already refused unless --force
380
+ target = self.root / rel
381
+ own = _Git(target.parent)
382
+ if own.toplevel is None:
383
+ return (f"refused: no git repository could be found for {rel}, so it "
384
+ "cannot be proven free of uncommitted work (pass --force)")
385
+ if own.toplevel != self.toplevel:
386
+ operation = own.in_progress()
387
+ if operation is not None:
388
+ return (f"refused: a git {operation} is in progress in the repository "
389
+ f"that owns {rel}")
390
+ return own._file_state(rel, target)
391
+
392
+ def _file_state(self, rel: str, target: Path) -> str | None:
393
+ """Index vs HEAD vs the raw working-tree bytes, from plumbing only."""
394
+ name = target.name
395
+ failed = (f"refused: git could not read the state of {rel}, so it cannot be "
396
+ "proven free of uncommitted work (pass --force to override)")
397
+ listed = self.run("ls-files", "-z", "--stage", "--", name)
398
+ if listed is None or listed.returncode != 0:
399
+ return failed
400
+ entries = [entry for entry in listed.stdout.split(b"\0") if entry]
401
+ if not entries:
402
+ # check-ignore rejects --literal-pathspecs; "./" keeps a leading ":"
403
+ # in the name from being read as pathspec magic.
404
+ ignored = self.run("check-ignore", "-q", "--", "./" + name, literal=False)
405
+ if ignored is not None and ignored.returncode == 0:
406
+ return (f"refused: {rel} is ignored by git, so git cannot restore it "
407
+ "(pass --force to override)")
408
+ return (f"refused: {rel} is untracked -- uncommitted work git cannot "
409
+ "restore (commit it first, or pass --force)")
410
+ dirty = (f"refused: {rel} has uncommitted changes (commit or stash them "
411
+ "first, or pass --force)")
412
+ meta = entries[0].split(b"\t", 1)[0].split(b" ")
413
+ if len(entries) != 1 or len(meta) != 3 or meta[2] != b"0":
414
+ return dirty # unmerged
415
+ mode, oid = meta[0], meta[1]
416
+ head = self.run("ls-tree", "-z", "HEAD", "--", name)
417
+ if head is None or head.returncode != 0 or not head.stdout:
418
+ return dirty # staged, never committed
419
+ head_meta = head.stdout.split(b"\t", 1)[0].split(b" ")
420
+ if len(head_meta) != 3 or (head_meta[0], head_meta[2]) != (mode, oid):
421
+ return dirty # staged change
422
+ # The working tree is hashed as raw bytes (--no-filters): a filter or
423
+ # line-ending conversion is never run, so a file that only differs from
424
+ # its blob through a filter reads as changed (refused, fail-closed).
425
+ if self._raw_matches(target, oid):
426
+ return None
427
+ return dirty
428
+
429
+ @staticmethod
430
+ def _raw_matches(target: Path, oid: bytes) -> bool:
431
+ """True when the file's raw bytes ARE the blob `oid` (hashed here, so no
432
+ filter or conversion can run). A CRLF checkout of an LF blob
433
+ (core.autocrlf) also matches: line endings alone are not work."""
434
+ try:
435
+ data = target.read_bytes()
436
+ except OSError:
437
+ return False
438
+ algo = hashlib.sha256 if len(oid) == 64 else hashlib.sha1
439
+ bodies = [data] + ([data.replace(b"\r\n", b"\n")] if b"\r\n" in data else [])
440
+ return any(algo(b"blob %d\0" % len(body) + body).hexdigest().encode() == oid
441
+ for body in bodies)
442
+
443
+ def dirty_elsewhere(self, exclude: Iterable[str]) -> bool:
444
+ """True when the repository has uncommitted changes outside `exclude`
445
+ (paths relative to self.root). Ignored files do not count."""
446
+ if self.toplevel is None:
447
+ return False
448
+ paths = self._changed_paths()
449
+ if paths is None:
450
+ return False
451
+ skip = set()
452
+ for rel in exclude:
453
+ try:
454
+ skip.add(str((self.root.resolve() / rel).relative_to(self.toplevel.resolve())))
455
+ except ValueError:
456
+ pass
457
+ skip |= {".gitignore", ".omnirank/"}
458
+ # A dirty submodule shows up as the submodule's own path; when that is
459
+ # the directory a target lives in, it is not "elsewhere".
460
+ prefixes = tuple(path.rstrip("/") + "/" for path in skip)
461
+ for path in paths:
462
+ if path in skip or path.startswith(".omnirank/"):
463
+ continue
464
+ if any(prefix.startswith(path.rstrip("/") + "/") for prefix in prefixes):
465
+ continue
466
+ return True
467
+ return False
468
+
469
+ def _changed_paths(self) -> list[str] | None:
470
+ """Repository-relative paths that differ from HEAD, plus untracked ones
471
+ (directories collapsed, "dir/"), without `git status` or any other
472
+ command that re-hashes the working tree through a filter.
473
+
474
+ Staged changes come from the index alone (`diff-index --cached`). The
475
+ working tree is compared here: a file whose size matches its blob and
476
+ whose mtime predates the index is taken as unchanged, any other is
477
+ hashed as raw bytes. A file with a filter attribute cannot be compared
478
+ without running the filter, so it is not counted (this is a note, not
479
+ a refusal: dirty_reason() refuses such a target)."""
480
+ if self.toplevel is None:
481
+ return None
482
+ top = _Git(self.toplevel)
483
+ staged = top.run("diff-index", "--cached", "-z", "--name-only", "--no-renames",
484
+ "--ignore-submodules=dirty", "HEAD")
485
+ listed = top.run("ls-files", "-z", "--full-name",
486
+ "--format=%(objectmode) %(objectname) %(objectsize) %(stage) %(path)")
487
+ others = top.run("ls-files", "-z", "--others", "--exclude-standard", "--directory",
488
+ "--no-empty-directory", "--full-name")
489
+ index = top.run("rev-parse", "--git-path", "index")
490
+ if any(r is None or r.returncode != 0 for r in (staged, listed, others, index)):
491
+ return None
492
+ try:
493
+ index_mtime = os.stat(top.root / index.stdout.decode("utf-8", "replace").strip()
494
+ ).st_mtime
495
+ except OSError:
496
+ index_mtime = 0.0
497
+ paths = [p.decode("utf-8", "replace") for p in staged.stdout.split(b"\0") if p]
498
+ paths += [p.decode("utf-8", "replace") for p in others.stdout.split(b"\0") if p]
499
+ suspects: list[tuple[str, bytes]] = []
500
+ for record in listed.stdout.split(b"\0"):
501
+ fields = record.split(b" ", 4)
502
+ if len(fields) != 5:
503
+ continue
504
+ mode, oid, size, stage, raw_path = fields
505
+ path = raw_path.decode("utf-8", "replace")
506
+ if stage != b"0":
507
+ paths.append(path) # unmerged
508
+ continue
509
+ if mode not in (b"100644", b"100755"):
510
+ continue # symlinks and submodules
511
+ try:
512
+ info = os.lstat(top.root / path)
513
+ except OSError:
514
+ paths.append(path) # deleted
515
+ continue
516
+ if (size.isdigit() and info.st_size == int(size)
517
+ and info.st_mtime < index_mtime):
518
+ continue
519
+ suspects.append((path, oid))
520
+ if suspects:
521
+ attrs = top.run("check-attr", "-z", "--stdin", "filter",
522
+ stdin=b"".join(p.encode() + b"\0" for p, _ in suspects))
523
+ filtered: set[str] = set()
524
+ if attrs is not None and attrs.returncode == 0:
525
+ out = attrs.stdout.split(b"\0")
526
+ for path_b, _attr, value in zip(out[0::3], out[1::3], out[2::3],
527
+ strict=False):
528
+ if value not in (b"unspecified", b"unset"):
529
+ filtered.add(path_b.decode("utf-8", "replace"))
530
+ paths += [path for path, oid in suspects if path not in filtered
531
+ and not self._raw_matches(top.root / path, oid)]
532
+ return paths
533
+
534
+ def is_ignored(self, rel: str) -> bool | None:
535
+ # check-ignore rejects --literal-pathspecs; only ever called with a
536
+ # fixed, magic-free path.
537
+ result = self.run("check-ignore", "-q", "--no-index", "--", rel, literal=False)
538
+ if result is None or result.returncode not in (0, 1):
539
+ return None
540
+ return result.returncode == 0
541
+
542
+
543
+ def preflight(root: str | Path, *, force: bool) -> str | None:
544
+ """A refusal that applies to the whole write, or None."""
545
+ root = Path(root)
546
+ if not root.is_dir():
547
+ return f"refused: project root {root} is not a directory"
548
+ git = _Git(root)
549
+ if git.toplevel is None:
550
+ if force:
551
+ return None
552
+ return (f"refused: {root} is not a git repository, so git cannot restore "
553
+ "what apply writes. The journal (`omnirank undo`) would be the only "
554
+ "recovery; pass --force to accept that.")
555
+ operation = git.in_progress()
556
+ if operation is not None:
557
+ return (f"refused: a git {operation} is in progress in {root}; finish or "
558
+ "abort it first. --force does not override this.")
559
+ return None
560
+
561
+
562
+ def dirty_elsewhere(root: str | Path, targets: Iterable[str]) -> bool:
563
+ """True when the repository has uncommitted changes outside `targets`."""
564
+ return _Git(Path(root)).dirty_elsewhere(targets)
565
+
566
+
567
+ # --- deciding -----------------------------------------------------------------------
568
+
569
+
570
+ @dataclass(frozen=True)
571
+ class Skip:
572
+ finding_id: str
573
+ url: str
574
+ path: str | None
575
+ reason: str
576
+ # True when a real diff existed and the ENGINE refused or deferred it (dirty
577
+ # file, unsafe path, ambiguity, overlap): work left undone, which apply
578
+ # reports with exit 1. False for generator declines and up-to-date files.
579
+ blocked: bool = False
580
+
581
+
582
+ @dataclass(frozen=True)
583
+ class FileChange:
584
+ path: str
585
+ before: bytes
586
+ after: bytes
587
+ fixes: tuple[tuple[str, str], ...]
588
+ adapter: str | None = None # set when a framework adapter made the edit
589
+
590
+ @property
591
+ def diff(self) -> str:
592
+ return unified_diff(self.path, self.before.decode("utf-8"),
593
+ self.after.decode("utf-8"))
594
+
595
+
596
+ @dataclass(frozen=True)
597
+ class Decision:
598
+ changes: list[FileChange]
599
+ skipped: list[Skip]
600
+
601
+
602
+ def _suffixes(adapter: str | None, confidence: str) -> tuple[str, ...] | None:
603
+ """The writable file types for one outcome.
604
+
605
+ The generic generators: .html/.htm. An adapter's edit: that adapter's own
606
+ types, but ONLY for an `exact` location -- `--allow-inferred` never widens
607
+ the file types. None means "refuse" (an inferred adapter location).
608
+ """
609
+ if adapter is None:
610
+ return WRITABLE_SUFFIXES
611
+ own = suffixes_for(adapter)
612
+ if own is None:
613
+ return WRITABLE_SUFFIXES
614
+ if confidence != "exact":
615
+ return None if set(own) - set(WRITABLE_SUFFIXES) else WRITABLE_SUFFIXES
616
+ return tuple(dict.fromkeys(WRITABLE_SUFFIXES + own))
617
+
618
+
619
+ def _jsonld_health(text: str) -> tuple[int, int]:
620
+ """(JSON-LD blocks, blocks that parse) -- the G1 well-formedness probe."""
621
+ blocks = find_ldjson_scripts(BeautifulSoup(text, "lxml"))
622
+ ok = 0
623
+ for block in blocks:
624
+ try:
625
+ json.loads(block.string or "")
626
+ ok += 1
627
+ except (json.JSONDecodeError, RecursionError):
628
+ pass
629
+ return len(blocks), ok
630
+
631
+
632
+ def _overlaps(a: patch.Hunk, b: patch.Hunk) -> bool:
633
+ # Touching counts: two hunks sharing a boundary line are coupled edits.
634
+ return a.old_index <= b.old_end and b.old_index <= a.old_end
635
+
636
+
637
+ def _merge(rel: str, accepted: list, skipped: list[Skip]) -> dict | None:
638
+ """Combine the accepted fixes for one file, refusing anything ambiguous.
639
+
640
+ - The same fix id with the SAME diff (two URLs served by one file, both
641
+ needing the identical edit) is one edit, recorded under both URLs.
642
+ - The same fix id with DIFFERENT diffs (e.g. `/` and `/index.html` both
643
+ wanting their own canonical in one file) is a genuine ambiguity: every
644
+ candidate for that id is refused rather than letting order pick.
645
+ - Different ids whose hunks overlap or touch: the first wins, the rest
646
+ are deferred to the next run (re-queue, never merge).
647
+ """
648
+ by_id: dict[str, list] = {}
649
+ for item in accepted:
650
+ by_id.setdefault(item[0].outcome.finding_id, []).append(item)
651
+ snapshot = accepted[0][0].snapshot
652
+ text = accepted[0][2]
653
+ hunks: list[patch.Hunk] = []
654
+ fixes: list[tuple[str, str]] = []
655
+ for finding_id, items in by_id.items():
656
+ if len({item[0].outcome.diff for item in items}) > 1:
657
+ urls = ", ".join(item[0].outcome.url for item in items)
658
+ for item in items:
659
+ skipped.append(Skip(finding_id, item[0].outcome.url, rel, blocked=True, reason=(
660
+ f"refused: {len(items)} URLs ({urls}) are served by {rel} and "
661
+ f"each needs a different {finding_id} edit; which one is right "
662
+ "cannot be decided here")))
663
+ continue
664
+ _, parsed, _ = items[0]
665
+ if any(item[0].snapshot != snapshot for item in items):
666
+ for item in items:
667
+ skipped.append(Skip(finding_id, item[0].outcome.url, rel,
668
+ "the file changed between two fixes' plans; "
669
+ "re-run apply", True))
670
+ continue
671
+ if any(_overlaps(new, old) for new in parsed.hunks for old in hunks):
672
+ for item in items:
673
+ skipped.append(Skip(finding_id, item[0].outcome.url, rel, blocked=True, reason=(
674
+ f"overlaps another fix to {rel} in this run; re-run apply "
675
+ "afterwards to pick it up")))
676
+ continue
677
+ hunks.extend(parsed.hunks)
678
+ for item in items:
679
+ pair = (finding_id, item[0].outcome.url)
680
+ if pair not in fixes:
681
+ fixes.append(pair)
682
+ if not hunks:
683
+ return None
684
+ return {"before": snapshot, "text": text, "hunks": hunks, "fixes": fixes}
685
+
686
+
687
+ def decide(root: str | Path, candidates: Sequence[Candidate], *, force: bool = False,
688
+ allow_inferred: bool = False) -> Decision:
689
+ """Which candidates may be written. Reads only; writes nothing."""
690
+ root = Path(root)
691
+ git = _Git(root)
692
+ dirty_cache: dict[str, str | None] = {}
693
+ files: dict[str, list] = {}
694
+ skipped: list[Skip] = []
695
+
696
+ for cand in candidates:
697
+ out = cand.outcome
698
+ rel = cand.location.path
699
+
700
+ def skip(reason: str, *, _out=out, _rel=rel, blocked: bool = True) -> None:
701
+ skipped.append(Skip(_out.finding_id, _out.url, _rel, reason, blocked))
702
+
703
+ if not out.fixed:
704
+ skip(out.reason or "no diff", blocked=False)
705
+ continue
706
+ if out.diff == "":
707
+ skip(UP_TO_DATE, blocked=False)
708
+ continue
709
+ confidence = cand.location.confidence
710
+ if not (confidence == "exact" or (confidence == "inferred" and allow_inferred)):
711
+ skip(f"locator confidence is {confidence}; only exact locations are written "
712
+ "(inferred ones with --allow-inferred)")
713
+ continue
714
+ if rel is None or out.path != rel:
715
+ skip("the fix does not name the located file; refusing")
716
+ continue
717
+ suffixes = _suffixes(out.adapter, confidence)
718
+ if suffixes is None:
719
+ skip(f"refused: the {out.adapter} adapter's file types are written only "
720
+ f"when the locator found the file exactly (confidence: {confidence})")
721
+ continue
722
+ reason = check_target(root, rel, suffixes)
723
+ if reason is not None:
724
+ skip(reason)
725
+ continue
726
+ if not cand.stable or cand.snapshot is None:
727
+ skip("the file changed while the fix plan was being computed; re-run apply")
728
+ continue
729
+ if _read(root, rel) != cand.snapshot:
730
+ skip("the file changed after the fix plan was computed; re-run apply")
731
+ continue
732
+ if not force:
733
+ if rel not in dirty_cache:
734
+ dirty_cache[rel] = readonly_reason(root, rel) or git.dirty_reason(rel)
735
+ if dirty_cache[rel] is not None:
736
+ skip(dirty_cache[rel])
737
+ continue
738
+ try:
739
+ text = cand.snapshot.decode("utf-8")
740
+ except UnicodeDecodeError:
741
+ skip(f"refused: {rel} is not valid UTF-8; it is never re-encoded")
742
+ continue
743
+ try:
744
+ parsed = patch.parse(out.diff)
745
+ if parsed.path != rel:
746
+ raise patch.PatchError(f"patch names {parsed.path}, not {rel}")
747
+ alone = patch.apply(text, parsed)
748
+ if unified_diff(rel, text, alone) != out.diff:
749
+ raise patch.PatchError("patch does not round-trip to the diff shown")
750
+ except patch.PatchError as exc:
751
+ skip(f"refused: the diff does not apply cleanly to {rel} ({exc})")
752
+ continue
753
+
754
+ files.setdefault(rel, []).append((cand, parsed, text))
755
+
756
+ changes: list[FileChange] = []
757
+ for rel, accepted in files.items():
758
+ names = {item[0].outcome.adapter for item in accepted} - {None}
759
+ if len(names) > 1:
760
+ for item in accepted:
761
+ skip_item = item[0].outcome
762
+ skipped.append(Skip(skip_item.finding_id, skip_item.url, rel, blocked=True,
763
+ reason=f"refused: two adapters ({', '.join(sorted(names))}) "
764
+ f"planned edits to {rel}"))
765
+ continue
766
+ adapter = next(iter(names), None)
767
+ entry = _merge(rel, accepted, skipped)
768
+ if entry is None:
769
+ continue
770
+ after = patch.apply_hunks(entry["text"], entry["hunks"])
771
+ if adapter is None:
772
+ blocks_before, ok_before = _jsonld_health(entry["text"])
773
+ blocks_after, ok_after = _jsonld_health(after)
774
+ broken = blocks_after != blocks_before or ok_after < ok_before
775
+ else:
776
+ # An adapter may ADD a JSON-LD block by design; it must never add a
777
+ # broken one or break an existing one.
778
+ health = ADAPTERS[adapter].jsonld_health
779
+ blocks_before, ok_before = health(entry["text"])
780
+ blocks_after, ok_after = health(after)
781
+ broken = (blocks_after < 0 or ok_after < ok_before
782
+ or blocks_after - ok_after > blocks_before - ok_before)
783
+ if adapter is not None and min(blocks_before, blocks_after) < 0:
784
+ for finding_id, url in entry["fixes"]:
785
+ skipped.append(Skip(finding_id, url, rel, blocked=True, reason=(
786
+ f"refused: the {adapter} adapter cannot read {rel} reliably, so "
787
+ "the edit cannot be proven to leave its JSON-LD blocks intact")))
788
+ continue
789
+ if broken:
790
+ for finding_id, url in entry["fixes"]:
791
+ skipped.append(Skip(finding_id, url, rel, blocked=True, reason=(
792
+ "refused: the combined edit would break a JSON-LD block in "
793
+ f"{rel}; reverting every change to that file (an OmniRank bug "
794
+ "-- please report it)")))
795
+ continue
796
+ changes.append(FileChange(path=rel, before=entry["before"],
797
+ after=after.encode("utf-8"),
798
+ fixes=tuple(entry["fixes"]), adapter=adapter))
799
+ return Decision(changes=changes, skipped=skipped)
800
+
801
+
802
+ # --- writing ----------------------------------------------------------------------
803
+
804
+
805
+ @dataclass
806
+ class _Staged:
807
+ rel: str
808
+ target: Path
809
+ expected: bytes
810
+ new: bytes
811
+ mode: int
812
+ tmp: str | None = None
813
+
814
+
815
+ def _stage(item: _Staged) -> None:
816
+ fd, tmp = tempfile.mkstemp(prefix=TEMP_PREFIX, suffix=".tmp", dir=item.target.parent)
817
+ item.tmp = tmp
818
+ with os.fdopen(fd, "wb") as handle:
819
+ handle.write(item.new)
820
+ handle.flush()
821
+ os.fchmod(handle.fileno(), item.mode)
822
+ os.fsync(handle.fileno())
823
+
824
+
825
+ def _discard(items: Iterable[_Staged]) -> None:
826
+ for item in items:
827
+ if item.tmp is not None:
828
+ try:
829
+ os.unlink(item.tmp)
830
+ except FileNotFoundError:
831
+ pass
832
+ item.tmp = None
833
+
834
+
835
+ def _fsync_dir(path: Path) -> None:
836
+ try:
837
+ fd = os.open(path, os.O_RDONLY)
838
+ except OSError:
839
+ return
840
+ try:
841
+ os.fsync(fd)
842
+ except OSError:
843
+ pass
844
+ finally:
845
+ os.close(fd)
846
+
847
+
848
+ def _prepare(root: Path,
849
+ entries: Iterable[tuple[str, bytes, bytes, int | None, tuple[str, ...]]],
850
+ error: type[Exception], *, force: bool = True) -> list[_Staged]:
851
+ """Re-check every target and stage every temp file. Replaces nothing.
852
+
853
+ `entries` is (rel, expected current bytes, new bytes, mode or None to keep
854
+ the file's current mode, writable suffixes). Raises `error` -- with every
855
+ temp file removed -- if any target fails any check; any other exception (KeyboardInterrupt
856
+ included) also removes every temp file before propagating.
857
+ `force=False` additionally refuses read-only targets.
858
+ """
859
+ items: list[_Staged] = []
860
+ try:
861
+ for rel, expected, new, mode, suffixes in entries:
862
+ reason = check_target(root, rel, suffixes) or (
863
+ None if force else readonly_reason(root, rel))
864
+ if reason is not None:
865
+ raise error(f"{reason}; nothing was written")
866
+ target = root / rel
867
+ current = target.read_bytes()
868
+ if current != expected:
869
+ raise error(
870
+ f"{rel} changed since the plan was computed (expected sha256 "
871
+ f"{_sha(expected)[:12]}, found {_sha(current)[:12]}); nothing "
872
+ "was written -- re-run to see a fresh diff")
873
+ item = _Staged(rel, target, expected, new,
874
+ stat.S_IMODE(target.stat().st_mode) if mode is None else mode)
875
+ items.append(item)
876
+ _stage(item)
877
+ except OSError as exc:
878
+ _discard(items)
879
+ raise error(f"could not stage the write ({exc}); nothing was written") from exc
880
+ except BaseException:
881
+ _discard(items)
882
+ raise
883
+ return items
884
+
885
+
886
+ def _rollback(attempted: list[_Staged]) -> list[str]:
887
+ """Put every attempted target back to its `expected` bytes, VERIFIED.
888
+
889
+ `attempted` holds every item whose `os.replace` was started -- including
890
+ one interrupted right after the replace returned, before anything could
891
+ record it. Each target is re-hashed rather than trusted:
892
+ - still `expected`: never replaced (or already restored); left alone;
893
+ - equals `new`: ours; restored from the pre-image;
894
+ - anything else: someone else's bytes; left alone and reported.
895
+ Returns the failures; empty means every target was verified back at
896
+ `expected`.
897
+ """
898
+ failures: list[str] = []
899
+ for item in reversed(attempted):
900
+ restore = _Staged(item.rel, item.target, item.new, item.expected, item.mode)
901
+ try:
902
+ current = item.target.read_bytes()
903
+ if current == item.expected:
904
+ continue
905
+ if current != item.new:
906
+ failures.append(f"{item.rel}: changed by someone else during the write; "
907
+ "left as it is")
908
+ continue
909
+ _stage(restore)
910
+ os.replace(restore.tmp, restore.target)
911
+ restore.tmp = None
912
+ if item.target.read_bytes() != item.expected:
913
+ failures.append(f"{item.rel}: restore could not be verified")
914
+ except BaseException as exc: # noqa: BLE001 -- keep restoring the others
915
+ _discard([restore])
916
+ failures.append(f"{item.rel}: {exc!r}")
917
+ if not failures:
918
+ return []
919
+ # The verdict is the disk, not the exceptions: a restore interrupted right
920
+ # after its replace returned DID restore the file.
921
+ try:
922
+ if all(item.target.read_bytes() == item.expected for item in attempted):
923
+ return []
924
+ except OSError:
925
+ pass
926
+ return failures
927
+
928
+
929
+ def _commit(items: list[_Staged]) -> tuple[BaseException, list[str]] | None:
930
+ """Replace every target; on ANY failure roll back what may have been replaced.
931
+
932
+ Returns None on success, else (the exception, rollback failures). Every
933
+ temp file is removed either way. The caller re-raises non-OSError
934
+ exceptions (KeyboardInterrupt, ...) after recording them in the journal.
935
+ """
936
+ attempted: list[_Staged] = []
937
+ try:
938
+ for item in items:
939
+ if item.target.read_bytes() != item.expected:
940
+ raise OSError(f"{item.rel} changed while the write was in progress")
941
+ # Registered BEFORE the replace: an interrupt that lands right after
942
+ # os.replace returns must still be rolled back.
943
+ attempted.append(item)
944
+ os.replace(item.tmp, item.target)
945
+ item.tmp = None
946
+ except BaseException as exc: # noqa: BLE001 -- Ctrl-C must roll back too; re-raised
947
+ failures = _rollback(attempted)
948
+ _discard(items)
949
+ return exc, failures
950
+ for parent in {item.target.parent for item in items}:
951
+ _fsync_dir(parent)
952
+ return None
953
+
954
+
955
+ @dataclass(frozen=True)
956
+ class WriteResult:
957
+ journal_id: str
958
+ journal_path: Path
959
+ files: list[str]
960
+ notes: list[str]
961
+
962
+
963
+ def _now() -> str:
964
+ return datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
965
+
966
+
967
+ def ensure_gitignored(root: Path) -> str | None:
968
+ """Make sure `.omnirank/` is git-ignored. Returns a note for the user.
969
+
970
+ Only in a git repository, only by appending `.omnirank/` to the root's
971
+ `.gitignore` (created if absent), and only when the entry is missing.
972
+ Nothing else in the file changes.
973
+ """
974
+ git = _Git(root)
975
+ if git.toplevel is None:
976
+ return None
977
+ probe = ".omnirank/journal/probe.json"
978
+ ignored = git.is_ignored(probe)
979
+ if ignored:
980
+ return None
981
+ if ignored is None:
982
+ return ("warning: could not ask git whether `.omnirank/` is ignored; make "
983
+ "sure it is before committing")
984
+ path = root / ".gitignore"
985
+ if path.is_symlink() or (path.exists() and not path.is_file()):
986
+ return ("warning: .gitignore is not a regular file; add `.omnirank/` to it "
987
+ "yourself so journals are never committed")
988
+ existed = path.exists()
989
+ try:
990
+ before = path.read_bytes() if existed else b""
991
+ text = before.decode("utf-8")
992
+ except (OSError, UnicodeDecodeError):
993
+ return ("warning: .gitignore could not be read as UTF-8; add `.omnirank/` "
994
+ "to it yourself")
995
+ eol = newline_style(text)
996
+ sep = "" if not text or text.endswith(("\n", "\r")) else eol
997
+ after = (text + sep + ".omnirank/" + eol).encode("utf-8")
998
+ if existed:
999
+ mode = stat.S_IMODE(path.stat().st_mode)
1000
+ else:
1001
+ mask = os.umask(0)
1002
+ os.umask(mask)
1003
+ mode = 0o666 & ~mask
1004
+ item = _Staged(".gitignore", path, before, after, mode)
1005
+ try:
1006
+ _stage(item)
1007
+ # Re-check right before the replace: never clobber an edit made since.
1008
+ current = path.read_bytes() if path.exists() else None
1009
+ if current != (before if existed else None):
1010
+ _discard([item])
1011
+ return ("warning: .gitignore changed while apply ran; add `.omnirank/` "
1012
+ "to it yourself")
1013
+ os.replace(item.tmp, path)
1014
+ except BaseException as exc:
1015
+ _discard([item])
1016
+ if not isinstance(exc, OSError):
1017
+ raise
1018
+ return f"warning: could not add `.omnirank/` to .gitignore ({exc})"
1019
+ if git.is_ignored(probe) is False:
1020
+ return ("warning: added `.omnirank/` to .gitignore but git still does not "
1021
+ "ignore it (a negation rule?); check before committing")
1022
+ return "added `.omnirank/` to .gitignore"
1023
+
1024
+
1025
+ def write(root: str | Path, changes: Sequence[FileChange], *, site: str,
1026
+ force: bool = False) -> WriteResult:
1027
+ """Write `changes` all-or-nothing, journaled.
1028
+
1029
+ Raises ApplyAborted when nothing was left changed -- or, only when a
1030
+ rollback itself failed, with the `omnirank undo` command to run. A
1031
+ KeyboardInterrupt is rolled back, recorded and re-raised. An OSError from
1032
+ the final journal save propagates: the files ARE written and the journal
1033
+ is left `pending`, which `omnirank undo --last` still handles.
1034
+ `.gitignore` is only touched after every file was written.
1035
+ """
1036
+ if not changes:
1037
+ raise ValueError("nothing to write")
1038
+ root = Path(root).resolve()
1039
+ try:
1040
+ journal.journal_dir(root, create=False)
1041
+ except journal.JournalError as exc:
1042
+ raise ApplyAborted(f"{exc}; nothing was written") from exc
1043
+ items = _prepare(root, ((c.path, c.before, c.after, None,
1044
+ _suffixes(c.adapter, "exact") or WRITABLE_SUFFIXES)
1045
+ for c in changes),
1046
+ ApplyAborted, force=force)
1047
+ notes: list[str] = []
1048
+ try:
1049
+ record = {
1050
+ "version": journal.VERSION,
1051
+ "tool": {"name": "omnirank", "version": __version__},
1052
+ "createdAt": _now(),
1053
+ "status": "pending",
1054
+ "root": str(root),
1055
+ "site": site,
1056
+ "files": [{
1057
+ "path": c.path,
1058
+ "beforeSha256": _sha(c.before),
1059
+ "afterSha256": _sha(c.after),
1060
+ "mode": oct(item.mode),
1061
+ "fixes": [{"id": fid, "url": url} for fid, url in c.fixes],
1062
+ **({"adapter": c.adapter} if c.adapter else {}),
1063
+ "reversePatch": unified_diff(c.path, c.after.decode("utf-8"),
1064
+ c.before.decode("utf-8")),
1065
+ "preimage": c.before.decode("utf-8"),
1066
+ } for c, item in zip(changes, items, strict=True)],
1067
+ }
1068
+ journal_id, journal_path = journal.create(root, record)
1069
+ record["id"] = journal_id
1070
+ except (OSError, journal.JournalError) as exc:
1071
+ _discard(items)
1072
+ raise ApplyAborted(f"could not write the journal ({exc}); nothing was "
1073
+ "written") from exc
1074
+ except BaseException:
1075
+ _discard(items)
1076
+ raise
1077
+
1078
+ try:
1079
+ failed = _commit(items)
1080
+ except KeyboardInterrupt as exc: # only possible after _commit returned
1081
+ raise Interrupted("written", journal_id) from exc
1082
+ if failed is not None:
1083
+ exc, rollback_failures = failed
1084
+ detail = "; ".join(rollback_failures)
1085
+ # rolled-back ONLY when every target was verified back at its old bytes.
1086
+ record["status"] = "pending" if rollback_failures else "rolled-back"
1087
+ record["error"] = repr(exc) + (f"; ROLLBACK FAILED for {detail}"
1088
+ if rollback_failures else "")
1089
+ journal_note = ""
1090
+ try:
1091
+ journal.save(journal_path, record)
1092
+ except OSError as save_exc:
1093
+ journal_note = (f" The journal could not be updated ({save_exc}); on disk "
1094
+ "it still says pending.")
1095
+ if not isinstance(exc, OSError):
1096
+ raise Interrupted("partial" if rollback_failures else "rolled-back",
1097
+ journal_id, detail + journal_note) from exc
1098
+ if rollback_failures:
1099
+ raise ApplyAborted(
1100
+ f"the write failed part-way ({exc}) and could not be fully rolled back "
1101
+ f"({detail}). Run `omnirank undo {journal_id}` to restore what was "
1102
+ "written." + journal_note)
1103
+ raise ApplyAborted(f"the write failed ({exc}); every file already replaced "
1104
+ "was rolled back and verified, so nothing changed."
1105
+ + journal_note)
1106
+
1107
+ try:
1108
+ record["status"] = "applied"
1109
+ record["appliedAt"] = _now()
1110
+ journal.save(journal_path, record)
1111
+ gitignore_note = ensure_gitignored(root)
1112
+ except KeyboardInterrupt as exc:
1113
+ raise Interrupted("written", journal_id) from exc
1114
+ if gitignore_note:
1115
+ notes.append(gitignore_note)
1116
+ for item in items:
1117
+ if _read(root, item.rel) != item.new:
1118
+ notes.append(f"warning: {item.rel} changed again right after it was "
1119
+ "written; check it")
1120
+ return WriteResult(journal_id=journal_id, journal_path=journal_path,
1121
+ files=[item.rel for item in items], notes=notes)
1122
+
1123
+
1124
+ # --- undo ---------------------------------------------------------------------------
1125
+
1126
+
1127
+ @dataclass(frozen=True)
1128
+ class UndoResult:
1129
+ journal_id: str
1130
+ restored: list[str]
1131
+ already: list[str]
1132
+
1133
+
1134
+ def _undoable(data: dict) -> bool:
1135
+ return data.get("status") in ("applied", "pending")
1136
+
1137
+
1138
+ def undo(root: str | Path, journal_id: str | None = None, *, last: bool = False,
1139
+ force: bool = False) -> UndoResult:
1140
+ """Restore the files one journal wrote. Raises UndoRefused."""
1141
+ root = Path(root).resolve()
1142
+ try:
1143
+ if last:
1144
+ data = None
1145
+ for candidate in reversed(journal.list_ids(root)):
1146
+ loaded = journal.load(root, candidate)
1147
+ if _undoable(loaded):
1148
+ data = loaded
1149
+ break
1150
+ if data is None:
1151
+ raise UndoRefused(f"nothing to undo: no applied journal under "
1152
+ f"{root / journal.JOURNAL_DIR}")
1153
+ else:
1154
+ if journal_id is None or not journal.is_valid_id(journal_id):
1155
+ raise UndoRefused(f"{journal_id!r} is not a journal id (expected "
1156
+ "something like 20261129T153012123456Z)")
1157
+ data = journal.load(root, journal_id)
1158
+ except journal.JournalError as exc:
1159
+ raise UndoRefused(str(exc)) from exc
1160
+
1161
+ journal_id = data["id"]
1162
+ status = data.get("status")
1163
+ if status == "undone":
1164
+ raise UndoRefused(f"journal {journal_id} was already undone")
1165
+ if not _undoable(data):
1166
+ raise UndoRefused(f"journal {journal_id} has status {status!r}; nothing it "
1167
+ "describes is applied")
1168
+ git = _Git(root)
1169
+ operation = git.in_progress() if git.toplevel is not None else None
1170
+ if operation is not None:
1171
+ raise UndoRefused(f"a git {operation} is in progress; finish or abort it first")
1172
+
1173
+ entries: list[tuple[str, bytes, bytes, int | None, tuple[str, ...]]] = []
1174
+ restored: list[str] = []
1175
+ already: list[str] = []
1176
+ conflicts: list[str] = []
1177
+ for entry in data["files"]:
1178
+ try:
1179
+ rel = entry["path"]
1180
+ before_sha, after_sha = entry["beforeSha256"], entry["afterSha256"]
1181
+ reverse, preimage = entry["reversePatch"], entry["preimage"]
1182
+ if not all(isinstance(v, str) for v in (rel, before_sha, after_sha,
1183
+ reverse, preimage)):
1184
+ raise TypeError
1185
+ except (KeyError, TypeError) as exc:
1186
+ raise UndoRefused(f"journal {journal_id} has a malformed file entry") from exc
1187
+ adapter = entry.get("adapter")
1188
+ if adapter is not None and (not isinstance(adapter, str)
1189
+ or suffixes_for(adapter) is None):
1190
+ raise UndoRefused(f"journal {journal_id} names an unknown adapter "
1191
+ f"{adapter!r} for {rel}; nothing was restored")
1192
+ suffixes = _suffixes(adapter, "exact") or WRITABLE_SUFFIXES
1193
+ reason = check_target(root, rel, suffixes)
1194
+ if reason is not None:
1195
+ raise UndoRefused(f"{reason}; nothing was restored")
1196
+ original = preimage.encode("utf-8")
1197
+ if _sha(original) != before_sha:
1198
+ raise UndoRefused(f"journal {journal_id} is inconsistent for {rel} (its "
1199
+ "pre-image does not match its before-hash); nothing "
1200
+ "was restored")
1201
+ current = (root / rel).read_bytes()
1202
+ if _sha(current) == before_sha:
1203
+ already.append(rel)
1204
+ continue
1205
+ if _sha(current) == after_sha:
1206
+ try:
1207
+ reverted = patch.apply(current.decode("utf-8"),
1208
+ patch.parse(reverse)).encode("utf-8")
1209
+ except (patch.PatchError, UnicodeDecodeError) as exc:
1210
+ raise UndoRefused(f"the reverse patch for {rel} does not apply "
1211
+ f"({exc}); nothing was restored") from exc
1212
+ if reverted != original:
1213
+ raise UndoRefused(f"the reverse patch for {rel} does not reproduce the "
1214
+ "recorded pre-image; nothing was restored")
1215
+ elif force:
1216
+ reverted = original
1217
+ else:
1218
+ conflicts.append(rel)
1219
+ continue
1220
+ entries.append((rel, current, reverted, None, suffixes))
1221
+ restored.append(rel)
1222
+
1223
+ if conflicts:
1224
+ raise UndoRefused(
1225
+ f"refused: {', '.join(conflicts)} changed since apply wrote it (its "
1226
+ "sha256 matches neither the journal's after-hash nor its before-hash); "
1227
+ "nothing was restored. Pass --force to overwrite those edits with the "
1228
+ "pre-apply content.")
1229
+
1230
+ if entries:
1231
+ items = _prepare(root, entries, UndoRefused)
1232
+ failed = _commit(items)
1233
+ if failed is not None:
1234
+ exc, rollback_failures = failed
1235
+ if not isinstance(exc, OSError):
1236
+ raise Interrupted("partial" if rollback_failures else "rolled-back",
1237
+ journal_id, "; ".join(rollback_failures)) from exc
1238
+ if rollback_failures:
1239
+ raise UndoRefused(
1240
+ f"the restore failed part-way ({exc}) and could not be rolled "
1241
+ f"back ({'; '.join(rollback_failures)}); the journal is unchanged, "
1242
+ "so run the same undo again once the cause is fixed")
1243
+ raise UndoRefused(f"the restore failed ({exc}); files already restored "
1244
+ "were rolled back, so nothing changed")
1245
+
1246
+ data["status"] = "undone"
1247
+ data["undoneAt"] = _now()
1248
+ try:
1249
+ journal.save(journal.path_for(root, journal_id), data)
1250
+ except OSError as exc:
1251
+ raise UndoIncomplete(restored, exc) from exc
1252
+ except KeyboardInterrupt as exc:
1253
+ raise Interrupted("written", journal_id) from exc
1254
+ return UndoResult(journal_id=journal_id, restored=restored, already=already)