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.
- omnirank/__init__.py +14 -0
- omnirank/__main__.py +6 -0
- omnirank/adapters/__init__.py +202 -0
- omnirank/adapters/astro.py +338 -0
- omnirank/adapters/base.py +372 -0
- omnirank/adapters/html.py +561 -0
- omnirank/adapters/jsx.py +340 -0
- omnirank/adapters/nextjs.py +692 -0
- omnirank/aeo/__init__.py +9 -0
- omnirank/aeo/extract.py +383 -0
- omnirank/aeo/propose.py +84 -0
- omnirank/aeo/rules.py +964 -0
- omnirank/aeo/runner.py +148 -0
- omnirank/applicability.py +98 -0
- omnirank/apply/__init__.py +23 -0
- omnirank/apply/engine.py +1254 -0
- omnirank/apply/journal.py +139 -0
- omnirank/apply/patch.py +144 -0
- omnirank/audit.py +185 -0
- omnirank/bands.py +106 -0
- omnirank/brief/__init__.py +0 -0
- omnirank/brief/analyze.py +197 -0
- omnirank/brief/constants.py +89 -0
- omnirank/brief/cost.py +62 -0
- omnirank/brief/egress.py +23 -0
- omnirank/brief/fetchpages.py +239 -0
- omnirank/brief/render.py +151 -0
- omnirank/brief/runner.py +369 -0
- omnirank/brief/serp.py +274 -0
- omnirank/brief/text.py +181 -0
- omnirank/cli.py +844 -0
- omnirank/clock.py +22 -0
- omnirank/cms/__init__.py +1 -0
- omnirank/cms/runner.py +170 -0
- omnirank/cms/wordpress.py +495 -0
- omnirank/cms/wordpress_apply.py +508 -0
- omnirank/cms/wordpress_plan.py +280 -0
- omnirank/config.py +81 -0
- omnirank/connect/__init__.py +4 -0
- omnirank/connect/bing.py +284 -0
- omnirank/connect/cloud_setup.py +43 -0
- omnirank/connect/confirm.py +242 -0
- omnirank/connect/constants.py +226 -0
- omnirank/connect/doctor.py +270 -0
- omnirank/connect/ga4.py +749 -0
- omnirank/connect/ga4_ai.py +123 -0
- omnirank/connect/google_auth.py +657 -0
- omnirank/connect/gsc.py +630 -0
- omnirank/connect/gsc_reports.py +169 -0
- omnirank/connect/http.py +310 -0
- omnirank/connect/indexnow.py +373 -0
- omnirank/connect/naver.py +536 -0
- omnirank/connect/runner.py +515 -0
- omnirank/connect/runner_ga4_ai.py +59 -0
- omnirank/connect/runner_more.py +489 -0
- omnirank/connect/runner_regional.py +260 -0
- omnirank/connect/secrets.py +190 -0
- omnirank/connect/urlcheck.py +41 -0
- omnirank/connect/yandex.py +350 -0
- omnirank/crawl/__init__.py +11 -0
- omnirank/crawl/analyze.py +493 -0
- omnirank/crawl/crawler.py +491 -0
- omnirank/crawl/custom.py +175 -0
- omnirank/crawl/export.py +67 -0
- omnirank/crawl/fetcher.py +212 -0
- omnirank/crawl/parse.py +102 -0
- omnirank/crawl/render.py +148 -0
- omnirank/crawl/robotsgate.py +198 -0
- omnirank/crawl/runner.py +295 -0
- omnirank/crawl/sitemap.py +99 -0
- omnirank/crawl/text.py +20 -0
- omnirank/crawl/urls.py +100 -0
- omnirank/crawlers.py +564 -0
- omnirank/data/ai_crawlers.json +269 -0
- omnirank/data/ai_referrers.json +42 -0
- omnirank/fetch.py +107 -0
- omnirank/fixes/__init__.py +92 -0
- omnirank/fixes/base.py +232 -0
- omnirank/fixes/canonical.py +243 -0
- omnirank/fixes/schema.py +126 -0
- omnirank/formats.py +134 -0
- omnirank/framework.py +223 -0
- omnirank/gates/__init__.py +48 -0
- omnirank/gates/aeo.py +114 -0
- omnirank/gates/contradictions.py +280 -0
- omnirank/gates/crawler_policy.py +85 -0
- omnirank/gates/geo.py +152 -0
- omnirank/gates/hygiene.py +81 -0
- omnirank/gates/jsonld.py +282 -0
- omnirank/gates/onpage.py +177 -0
- omnirank/gates/perf.py +115 -0
- omnirank/gates/security.py +264 -0
- omnirank/gates/seo.py +118 -0
- omnirank/gates/site.py +248 -0
- omnirank/geo_artifacts.py +199 -0
- omnirank/html.py +79 -0
- omnirank/keywords/__init__.py +5 -0
- omnirank/keywords/constants.py +69 -0
- omnirank/keywords/engine.py +384 -0
- omnirank/keywords/report.py +143 -0
- omnirank/keywords/runner.py +160 -0
- omnirank/keywords/source.py +60 -0
- omnirank/keywords/text.py +45 -0
- omnirank/locator.py +480 -0
- omnirank/logs/__init__.py +0 -0
- omnirank/logs/analyze.py +127 -0
- omnirank/logs/bots.py +69 -0
- omnirank/logs/ipranges.py +191 -0
- omnirank/logs/parse.py +452 -0
- omnirank/logs/paths.py +22 -0
- omnirank/logs/privacy.py +105 -0
- omnirank/logs/runner.py +179 -0
- omnirank/mcp_server.py +1480 -0
- omnirank/netguard.py +525 -0
- omnirank/packs/__init__.py +6 -0
- omnirank/packs/backlinks.py +535 -0
- omnirank/packs/blog.py +544 -0
- omnirank/packs/blog_cross.py +468 -0
- omnirank/packs/crawlers.py +23 -0
- omnirank/packs/entity.py +492 -0
- omnirank/packs/feeds.py +150 -0
- omnirank/packs/frontmatter.py +59 -0
- omnirank/packs/gsc.py +421 -0
- omnirank/packs/local.py +879 -0
- omnirank/packs/mdscan.py +326 -0
- omnirank/packs/miniyaml.py +378 -0
- omnirank/packs/model.py +46 -0
- omnirank/packs/product.py +979 -0
- omnirank/packs/refresh.py +165 -0
- omnirank/packs/runner.py +277 -0
- omnirank/packs/sitescan.py +294 -0
- omnirank/packs/textsafe.py +79 -0
- omnirank/packs/xmlsafe.py +92 -0
- omnirank/page.py +42 -0
- omnirank/registry.py +302 -0
- omnirank/report.py +251 -0
- omnirank/report_cmd/__init__.py +7 -0
- omnirank/report_cmd/delta.py +58 -0
- omnirank/report_cmd/files.py +64 -0
- omnirank/report_cmd/model.py +208 -0
- omnirank/report_cmd/notify.py +195 -0
- omnirank/report_cmd/pdf.py +83 -0
- omnirank/report_cmd/portfolio.py +342 -0
- omnirank/report_cmd/render.py +379 -0
- omnirank/report_cmd/runner.py +267 -0
- omnirank/robots.py +172 -0
- omnirank/scanner/__init__.py +10 -0
- omnirank/scanner/badge.py +90 -0
- omnirank/scanner/cache.py +69 -0
- omnirank/scanner/cli.py +96 -0
- omnirank/scanner/engine.py +289 -0
- omnirank/scanner/limits.py +98 -0
- omnirank/scanner/server.py +143 -0
- omnirank/scanner/service.py +328 -0
- omnirank/schema/__init__.py +13 -0
- omnirank/schema/catalog.py +679 -0
- omnirank/schema/catalog_specs.py +350 -0
- omnirank/schema/core.py +306 -0
- omnirank/schema/extract.py +396 -0
- omnirank/schema/gate.py +121 -0
- omnirank/schema/runner.py +213 -0
- omnirank/schema/validate.py +504 -0
- omnirank/schema/vocab.py +305 -0
- omnirank/schemas/omnirank.config.schema.json +268 -0
- omnirank/track/__init__.py +0 -0
- omnirank/track/ai_prompts.py +207 -0
- omnirank/track/analysis.py +197 -0
- omnirank/track/constants.py +155 -0
- omnirank/track/cost.py +229 -0
- omnirank/track/discover.py +277 -0
- omnirank/track/discover_cli.py +309 -0
- omnirank/track/discover_constants.py +95 -0
- omnirank/track/engines.py +216 -0
- omnirank/track/estimate_view.py +212 -0
- omnirank/track/history.py +261 -0
- omnirank/track/runner.py +586 -0
- omnirank/track/stats.py +138 -0
- omnirank/track/storage.py +128 -0
- omnirank-0.5.0.dist-info/METADATA +47 -0
- omnirank-0.5.0.dist-info/RECORD +183 -0
- omnirank-0.5.0.dist-info/WHEEL +5 -0
- omnirank-0.5.0.dist-info/entry_points.txt +2 -0
- omnirank-0.5.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"""HTML, Markdown and CSV renderings of a sweep report (+ optional before/after delta).
|
|
2
|
+
|
|
3
|
+
Rules every renderer follows:
|
|
4
|
+
|
|
5
|
+
* Text from audited pages (URLs, observed values, fixes, the site name) is untrusted. HTML
|
|
6
|
+
escapes it with ``html.escape`` and never puts it in an attribute or a link; Markdown puts
|
|
7
|
+
it in code spans (which also keeps ``@mentions`` and raw HTML inert); CSV neutralises
|
|
8
|
+
spreadsheet formulas.
|
|
9
|
+
* The HTML is one self-contained file: inline CSS only, no script, no external asset, and a
|
|
10
|
+
``Content-Security-Policy`` meta that allows nothing but that one stylesheet (by hash).
|
|
11
|
+
* Branding is removable (``white_label`` / ``no_branding``) and only branding: findings,
|
|
12
|
+
scores, evidence legend and limits are identical either way.
|
|
13
|
+
* The consulting CTA is a plain footer line, on by default, off with ``cta=False``. It is
|
|
14
|
+
never written into machine formats (JSON, SARIF, JUnit, CSV).
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import base64
|
|
19
|
+
import csv
|
|
20
|
+
import hashlib
|
|
21
|
+
import io
|
|
22
|
+
import re
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from html import escape
|
|
25
|
+
|
|
26
|
+
from .. import __version__
|
|
27
|
+
from .delta import Delta
|
|
28
|
+
from .model import clean
|
|
29
|
+
|
|
30
|
+
CTA_TEXT = "Want us to implement it?"
|
|
31
|
+
CTA_URL = "https://cal.com/ticonsys/meeting"
|
|
32
|
+
# Spec section 19 Q8 (is the consulting footer on by default?) is an OPEN owner question.
|
|
33
|
+
# ON is the controller's ruling pending owner confirmation. To flip the default, set this to
|
|
34
|
+
# False: `report.cta: true` in the config or a future --cta flag then opts in.
|
|
35
|
+
CTA_DEFAULT_ON = True
|
|
36
|
+
MAX_GROUPS = 200
|
|
37
|
+
MAX_EXAMPLES = 3
|
|
38
|
+
SEVERITY_RANK = {"error": 0, "warning": 1, "info": 2}
|
|
39
|
+
SEVERITY_LABEL = {"error": "Error", "warning": "Warning", "info": "Info"}
|
|
40
|
+
|
|
41
|
+
# [experimental] example: llms.txt, which is not a ranking or citation lever
|
|
42
|
+
_EXPERIMENTAL_TEXT = "no solid evidence (for example llms.txt, not a ranking or citation lever)."
|
|
43
|
+
EVIDENCE = (
|
|
44
|
+
("[standard]", ("required by a spec or search-engine documentation (robots, sitemap, "
|
|
45
|
+
"canonical, valid JSON-LD).")),
|
|
46
|
+
("[guideline]", "stated in official docs but advisory."),
|
|
47
|
+
("[correlational]", ("studies show association only (freshness, semantic HTML, brand "
|
|
48
|
+
"mentions); not a proven cause of ranking or citation.")),
|
|
49
|
+
("[experimental]", _EXPERIMENTAL_TEXT),
|
|
50
|
+
)
|
|
51
|
+
EVIDENCE_NOTE = ("The sweep report does not store an evidence tag per finding, so none is "
|
|
52
|
+
"assigned to individual rows here. Read the tags as how much weight a "
|
|
53
|
+
"rationale deserves; a [correlational] or [experimental] item is never a "
|
|
54
|
+
"cause of ranking or AI citation.")
|
|
55
|
+
|
|
56
|
+
CSS = """
|
|
57
|
+
:root{color-scheme:light dark;--fg:#1b1f24;--bg:#fff;--mut:#59636e;--line:#d0d7de;
|
|
58
|
+
--err:#b42318;--warn:#a15c00;--info:#175cd3;--ok:#067647}
|
|
59
|
+
@media (prefers-color-scheme:dark){:root{--fg:#e6edf3;--bg:#0d1117;--mut:#9198a1;
|
|
60
|
+
--line:#30363d;--err:#ff7b72;--warn:#e3b341;--info:#79c0ff;--ok:#56d364}}
|
|
61
|
+
body{margin:0 auto;max-width:56rem;padding:1rem 16px 3rem;background:var(--bg);color:var(--fg);
|
|
62
|
+
font:16px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
|
|
63
|
+
h1{font-size:1.6rem;margin:.2em 0}h2{font-size:1.2rem;margin-top:2rem;
|
|
64
|
+
border-bottom:1px solid var(--line);padding-bottom:.2rem}
|
|
65
|
+
.mut{color:var(--mut)}.num{font-variant-numeric:tabular-nums}
|
|
66
|
+
table{border-collapse:collapse;width:100%;font-size:.95rem}
|
|
67
|
+
th,td{border-bottom:1px solid var(--line);padding:.35rem .5rem;text-align:left;
|
|
68
|
+
vertical-align:top;overflow-wrap:anywhere}
|
|
69
|
+
.error{color:var(--err)}.warning{color:var(--warn)}.info{color:var(--info)}.good{color:var(--ok)}
|
|
70
|
+
code{font:.9em ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
|
|
71
|
+
.grp{border:1px solid var(--line);border-radius:6px;padding:.6rem .8rem;margin:.6rem 0}
|
|
72
|
+
.tbl{overflow-x:auto}footer{margin-top:2.5rem;color:var(--mut);font-size:.9rem}
|
|
73
|
+
@page{margin:16mm}
|
|
74
|
+
@media print{body{max-width:none;padding:0;font-size:11pt}.grp{break-inside:avoid}
|
|
75
|
+
h2{break-after:avoid}a{color:inherit}}
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class Options:
|
|
81
|
+
white_label: str | None = None
|
|
82
|
+
no_branding: bool = False
|
|
83
|
+
cta: bool = CTA_DEFAULT_ON
|
|
84
|
+
generated: str = ""
|
|
85
|
+
|
|
86
|
+
def prepared_by(self) -> str | None:
|
|
87
|
+
"""The only line branding controls: who the report says produced it."""
|
|
88
|
+
if self.no_branding:
|
|
89
|
+
return None
|
|
90
|
+
if self.white_label:
|
|
91
|
+
return f"Prepared by {clean(self.white_label, 80)}"
|
|
92
|
+
return f"Generated by OmniRank {__version__}"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# ---- shared view model -------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
def layer_rows(report: dict, delta: Delta | None) -> list[dict]:
|
|
98
|
+
counts: dict[str, dict[str, int]] = {}
|
|
99
|
+
for f in report["findings"]:
|
|
100
|
+
c = counts.setdefault(f["layer"], {"error": 0, "warning": 0, "info": 0})
|
|
101
|
+
c[f["severity"]] += 1
|
|
102
|
+
rows = []
|
|
103
|
+
for layer in sorted(k for k in report["score"] if k != "overall"):
|
|
104
|
+
c = counts.get(layer, {"error": 0, "warning": 0, "info": 0})
|
|
105
|
+
change = delta.score_changes.get(layer) if delta and delta.previous else None
|
|
106
|
+
rows.append({"layer": layer, "score": report["score"][layer], "change": change,
|
|
107
|
+
"errors": c["error"], "warnings": c["warning"], "info": c["info"]})
|
|
108
|
+
return rows
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def groups(findings: list[dict]) -> list[dict]:
|
|
112
|
+
by_id: dict[str, dict] = {}
|
|
113
|
+
for f in findings:
|
|
114
|
+
g = by_id.get(f["id"])
|
|
115
|
+
if g is None:
|
|
116
|
+
g = by_id[f["id"]] = {
|
|
117
|
+
"id": f["id"], "severity": f["severity"], "layer": f["layer"],
|
|
118
|
+
"gate": f["gate"], "expected": f["expected"], "fix": f["fix"],
|
|
119
|
+
"observed": f["observed"], "urls": []}
|
|
120
|
+
elif SEVERITY_RANK[f["severity"]] < SEVERITY_RANK[g["severity"]]:
|
|
121
|
+
g["severity"] = f["severity"]
|
|
122
|
+
g["urls"].append(f["url"])
|
|
123
|
+
return sorted(by_id.values(),
|
|
124
|
+
key=lambda g: (SEVERITY_RANK[g["severity"]], -len(g["urls"]), g["id"]))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def limits(report: dict) -> list[str]:
|
|
128
|
+
checked = report.get("urlsChecked")
|
|
129
|
+
items = [
|
|
130
|
+
"Findings come from automated checks on the URLs that were sampled"
|
|
131
|
+
+ (f" ({checked} URLs checked)" if checked is not None else "")
|
|
132
|
+
+ "; this is not an exhaustive crawl and a clean result is not a guarantee.",
|
|
133
|
+
("Nothing here guarantees rankings or citations by search engines or AI answer "
|
|
134
|
+
"engines. No such guarantee can be made."),
|
|
135
|
+
("Scores are reported per layer. The overall number is the plain mean of the layers "
|
|
136
|
+
"that ran; it is a convenience, not a visibility or AI score."),
|
|
137
|
+
"Gates that could not run are listed as not evaluated. They did not pass.",
|
|
138
|
+
"Text taken from audited pages is shown as data, escaped, and was not verified.",
|
|
139
|
+
]
|
|
140
|
+
return items
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _fmt_change(change: int | None) -> str:
|
|
144
|
+
if change is None:
|
|
145
|
+
return "n/a"
|
|
146
|
+
return f"{change:+d}" if change else "0"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _fmt_score(report: dict) -> str:
|
|
150
|
+
return str(report["score"].get("overall", "n/a"))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _site_and_date(report: dict, options: Options) -> tuple[str, str]:
|
|
154
|
+
return report["site"], report["generatedAt"] or options.generated
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# ---- HTML --------------------------------------------------------------------------
|
|
158
|
+
|
|
159
|
+
def _e(text: object) -> str:
|
|
160
|
+
return escape(clean(text), quote=True)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def to_html(report: dict, delta: Delta | None, options: Options) -> str:
|
|
164
|
+
site, when = _site_and_date(report, options)
|
|
165
|
+
out: list[str] = []
|
|
166
|
+
add = out.append
|
|
167
|
+
add(f"<h1>Site readiness report</h1>") # noqa: F541
|
|
168
|
+
add(f'<p class="mut"><code>{_e(site)}</code> · sweep run {_e(when)} '
|
|
169
|
+
f"· report written {_e(options.generated)}</p>")
|
|
170
|
+
by = options.prepared_by()
|
|
171
|
+
if by:
|
|
172
|
+
add(f'<p class="mut">{_e(by)}</p>')
|
|
173
|
+
|
|
174
|
+
add("<h2>Readiness by layer</h2>")
|
|
175
|
+
add(f'<p>Overall <strong class="num">{_e(_fmt_score(report))}</strong>/100 '
|
|
176
|
+
'<span class="mut">(mean of the layers that ran, not an AI-visibility score)</span></p>')
|
|
177
|
+
add('<div class="tbl"><table><thead><tr><th>Layer</th><th>Score</th><th>Change</th>'
|
|
178
|
+
"<th>Errors</th><th>Warnings</th><th>Info</th></tr></thead><tbody>")
|
|
179
|
+
for r in layer_rows(report, delta):
|
|
180
|
+
add(f'<tr><td>{_e(r["layer"])}</td><td class="num">{r["score"]}</td>'
|
|
181
|
+
f'<td class="num">{_e(_fmt_change(r["change"]))}</td><td class="num error">'
|
|
182
|
+
f'{r["errors"]}</td><td class="num warning">{r["warnings"]}</td>'
|
|
183
|
+
f'<td class="num info">{r["info"]}</td></tr>')
|
|
184
|
+
add("</tbody></table></div>")
|
|
185
|
+
|
|
186
|
+
add("<h2>Evidence legend</h2><ul>")
|
|
187
|
+
for tag, text in EVIDENCE:
|
|
188
|
+
add(f"<li><code>{_e(tag)}</code> {_e(text)}</li>")
|
|
189
|
+
add(f'</ul><p class="mut">{_e(EVIDENCE_NOTE)}</p>')
|
|
190
|
+
|
|
191
|
+
add("<h2>Prioritized findings</h2>")
|
|
192
|
+
grouped = groups(report["findings"])
|
|
193
|
+
if not grouped:
|
|
194
|
+
add('<p class="good">No findings in this run.</p>')
|
|
195
|
+
for g in grouped[:MAX_GROUPS]:
|
|
196
|
+
sev = g["severity"]
|
|
197
|
+
add('<div class="grp">'
|
|
198
|
+
f'<strong class="{sev}">{_e(SEVERITY_LABEL[sev])}</strong> '
|
|
199
|
+
f'<code>{_e(g["id"])}</code> · {_e(g["layer"])} · '
|
|
200
|
+
f'{len(g["urls"])} URL(s)'
|
|
201
|
+
f'<br>Expected: {_e(g["expected"])}<br>Observed: {_e(g["observed"])}'
|
|
202
|
+
f'<br>Fix: {_e(g["fix"])}<br><span class="mut">e.g. '
|
|
203
|
+
+ ", ".join(f"<code>{_e(u)}</code>" for u in g["urls"][:MAX_EXAMPLES])
|
|
204
|
+
+ ("" if len(g["urls"]) <= MAX_EXAMPLES
|
|
205
|
+
else f" and {len(g['urls']) - MAX_EXAMPLES} more")
|
|
206
|
+
+ "</span></div>")
|
|
207
|
+
if len(grouped) > MAX_GROUPS:
|
|
208
|
+
add(f'<p class="mut">{len(grouped) - MAX_GROUPS} more finding groups are in the '
|
|
209
|
+
"JSON report.</p>")
|
|
210
|
+
|
|
211
|
+
add("<h2>Changes since the previous run</h2>")
|
|
212
|
+
if delta is None or delta.previous is None:
|
|
213
|
+
add("<p>No previous report was available, so no before/after comparison is shown.</p>")
|
|
214
|
+
else:
|
|
215
|
+
add(f"<p>{len(delta.new_findings)} new finding(s), {len(delta.resolved)} resolved, "
|
|
216
|
+
f'<strong class="{"error" if delta.has_regression else "good"}">'
|
|
217
|
+
f'{"regression detected" if delta.has_regression else "no regression"}'
|
|
218
|
+
"</strong>.</p>")
|
|
219
|
+
if delta.new_layers:
|
|
220
|
+
add("<p class=\"mut\">Layers with no earlier score (not compared): "
|
|
221
|
+
+ _e(", ".join(delta.new_layers)) + ".</p>")
|
|
222
|
+
for title, items in (("New", delta.new_findings), ("Resolved", delta.resolved)):
|
|
223
|
+
if items:
|
|
224
|
+
add(f"<h3>{title}</h3><ul>")
|
|
225
|
+
for f in items[:MAX_GROUPS]:
|
|
226
|
+
add(f'<li><span class="{f["severity"]}">{_e(f["severity"])}</span> '
|
|
227
|
+
f'<code>{_e(f["id"])}</code> <code>{_e(f["url"])}</code></li>')
|
|
228
|
+
add("</ul>")
|
|
229
|
+
|
|
230
|
+
add("<h2>Limits of this report</h2><ul>")
|
|
231
|
+
for item in limits(report):
|
|
232
|
+
add(f"<li>{_e(item)}</li>")
|
|
233
|
+
add("</ul>")
|
|
234
|
+
if report["notEvaluated"]:
|
|
235
|
+
add(f"<h3>Not evaluated ({len(report['notEvaluated'])})</h3><ul>")
|
|
236
|
+
for e in report["notEvaluated"][:MAX_GROUPS]:
|
|
237
|
+
add(f"<li><code>{_e(e['gate'])}</code> {_e(e['reason'])} "
|
|
238
|
+
f"<code>{_e(e['target'])}</code></li>")
|
|
239
|
+
add("</ul>")
|
|
240
|
+
|
|
241
|
+
foot = []
|
|
242
|
+
if options.cta:
|
|
243
|
+
foot.append(f'<p>{_e(CTA_TEXT)} → <a href="{CTA_URL}">{CTA_URL}</a></p>')
|
|
244
|
+
if foot:
|
|
245
|
+
add("<footer>" + "".join(foot) + "</footer>")
|
|
246
|
+
|
|
247
|
+
digest = base64.b64encode(hashlib.sha256(CSS.encode("utf-8")).digest()).decode("ascii")
|
|
248
|
+
csp = (f"default-src 'none'; style-src 'sha256-{digest}'; base-uri 'none'; "
|
|
249
|
+
"form-action 'none'")
|
|
250
|
+
head = ('<!doctype html>\n<html lang="en"><head><meta charset="utf-8">'
|
|
251
|
+
'<meta name="viewport" content="width=device-width,initial-scale=1">'
|
|
252
|
+
f'<meta http-equiv="Content-Security-Policy" content="{csp}">'
|
|
253
|
+
'<meta name="referrer" content="no-referrer">'
|
|
254
|
+
f"<title>Site readiness report</title><style>{CSS}</style></head><body>")
|
|
255
|
+
return head + "\n".join(out) + "</body></html>\n"
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# ---- Markdown ----------------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
def md_code(text: object) -> str:
|
|
261
|
+
"""A Markdown code span that cannot be broken out of (and so cannot ping @users,
|
|
262
|
+
open links or inject HTML)."""
|
|
263
|
+
t = clean(text)
|
|
264
|
+
longest = run = 0
|
|
265
|
+
for ch in t:
|
|
266
|
+
run = run + 1 if ch == "`" else 0
|
|
267
|
+
longest = max(longest, run)
|
|
268
|
+
fence = "`" * (longest + 1)
|
|
269
|
+
pad = " " if t.startswith("`") or t.endswith("`") else ""
|
|
270
|
+
return f"{fence}{pad}{t}{pad}{fence}" if t else "``"
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def md_text(text: object) -> str:
|
|
274
|
+
"""Escaped plain text for tool-authored strings and layer names."""
|
|
275
|
+
t = clean(text)
|
|
276
|
+
for ch in "\\`*_[]<>|~@&#":
|
|
277
|
+
t = t.replace(ch, "\\" + ch)
|
|
278
|
+
# a bare URL or www. host would be auto-linked by GitHub/GFM renderers
|
|
279
|
+
t = t.replace("://", "\\://")
|
|
280
|
+
return re.sub(r"(?i)\bwww\.", lambda m: m.group()[:-1] + "\\.", t)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def to_markdown(report: dict, delta: Delta | None, options: Options) -> str:
|
|
284
|
+
site, when = _site_and_date(report, options)
|
|
285
|
+
L: list[str] = ["# Site readiness report", "",
|
|
286
|
+
(f"{md_code(site)} · sweep run {md_code(when)} · "
|
|
287
|
+
f"report written {md_code(options.generated)}")]
|
|
288
|
+
by = options.prepared_by()
|
|
289
|
+
if by:
|
|
290
|
+
L += ["", md_text(by)]
|
|
291
|
+
L += ["", "## Readiness by layer", "",
|
|
292
|
+
(f"Overall **{_fmt_score(report)}**/100 (mean of the layers that ran, not an "
|
|
293
|
+
"AI-visibility score)"), "",
|
|
294
|
+
"| Layer | Score | Change | Errors | Warnings | Info |",
|
|
295
|
+
"| --- | ---: | ---: | ---: | ---: | ---: |"]
|
|
296
|
+
for r in layer_rows(report, delta):
|
|
297
|
+
L.append(f"| {md_text(r['layer'])} | {r['score']} | {_fmt_change(r['change'])} | "
|
|
298
|
+
f"{r['errors']} | {r['warnings']} | {r['info']} |")
|
|
299
|
+
L += ["", "## Evidence legend", ""]
|
|
300
|
+
L += [f"- {md_code(tag)} {text}" for tag, text in EVIDENCE]
|
|
301
|
+
L += ["", EVIDENCE_NOTE, "", "## Prioritized findings", ""]
|
|
302
|
+
grouped = groups(report["findings"])
|
|
303
|
+
if not grouped:
|
|
304
|
+
L.append("No findings in this run.")
|
|
305
|
+
for g in grouped[:MAX_GROUPS]:
|
|
306
|
+
L.append(f"- **{SEVERITY_LABEL[g['severity']]}** {md_code(g['id'])} · "
|
|
307
|
+
f"{md_text(g['layer'])} · {len(g['urls'])} URL(s)")
|
|
308
|
+
L.append(f" - expected: {md_code(g['expected'])}")
|
|
309
|
+
L.append(f" - observed: {md_code(g['observed'])}")
|
|
310
|
+
L.append(f" - fix: {md_code(g['fix'])}")
|
|
311
|
+
ex = ", ".join(md_code(u) for u in g["urls"][:MAX_EXAMPLES])
|
|
312
|
+
more = len(g["urls"]) - MAX_EXAMPLES
|
|
313
|
+
L.append(f" - e.g. {ex}" + (f" and {more} more" if more > 0 else ""))
|
|
314
|
+
if len(grouped) > MAX_GROUPS:
|
|
315
|
+
L.append(f"- … {len(grouped) - MAX_GROUPS} more finding groups are in the JSON report.")
|
|
316
|
+
L += ["", "## Changes since the previous run", ""]
|
|
317
|
+
if delta is None or delta.previous is None:
|
|
318
|
+
L.append("No previous report was available, so no before/after comparison is shown.")
|
|
319
|
+
else:
|
|
320
|
+
L.append(f"{len(delta.new_findings)} new finding(s), {len(delta.resolved)} resolved, "
|
|
321
|
+
+ ("**regression detected**." if delta.has_regression else "no regression."))
|
|
322
|
+
if delta.new_layers:
|
|
323
|
+
L.append("")
|
|
324
|
+
L.append("Layers with no earlier score (not compared): "
|
|
325
|
+
+ ", ".join(md_code(x) for x in delta.new_layers) + ".")
|
|
326
|
+
for title, items in (("New", delta.new_findings), ("Resolved", delta.resolved)):
|
|
327
|
+
if items:
|
|
328
|
+
L += ["", f"### {title}", ""]
|
|
329
|
+
L += [f"- {f['severity']} {md_code(f['id'])} {md_code(f['url'])}"
|
|
330
|
+
for f in items[:MAX_GROUPS]]
|
|
331
|
+
L += ["", "## Limits of this report", ""]
|
|
332
|
+
L += [f"- {item}" for item in limits(report)]
|
|
333
|
+
if report["notEvaluated"]:
|
|
334
|
+
L += ["", f"### Not evaluated ({len(report['notEvaluated'])})", ""]
|
|
335
|
+
L += [f"- {md_code(e['gate'])} {md_code(e['reason'])} {md_code(e['target'])}"
|
|
336
|
+
for e in report["notEvaluated"][:MAX_GROUPS]]
|
|
337
|
+
if options.cta:
|
|
338
|
+
L += ["", "---", "", f"{CTA_TEXT} → {CTA_URL}"]
|
|
339
|
+
return "\n".join(L) + "\n"
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
# ---- CSV (Looker Studio ready) -----------------------------------------------------
|
|
343
|
+
|
|
344
|
+
def csv_cell(value: object) -> object:
|
|
345
|
+
"""Strings are cleaned and made inert as spreadsheet formulas; numbers pass through."""
|
|
346
|
+
if isinstance(value, bool) or not isinstance(value, str):
|
|
347
|
+
return value
|
|
348
|
+
t = clean(value)
|
|
349
|
+
if t.lstrip()[:1] in ("=", "+", "-", "@"):
|
|
350
|
+
return "'" + t
|
|
351
|
+
return t
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _csv(rows: list[list[object]]) -> str:
|
|
355
|
+
buf = io.StringIO()
|
|
356
|
+
w = csv.writer(buf, lineterminator="\n")
|
|
357
|
+
for row in rows:
|
|
358
|
+
w.writerow([csv_cell(c) for c in row])
|
|
359
|
+
return buf.getvalue()
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def to_csv_findings(report: dict) -> str:
|
|
363
|
+
rows: list[list[object]] = [["generated", "site", "layer", "severity", "gate", "id",
|
|
364
|
+
"url", "observed", "expected", "fix", "fixTier"]]
|
|
365
|
+
for f in report["findings"]:
|
|
366
|
+
rows.append([report["generatedAt"], report["site"], f["layer"], f["severity"],
|
|
367
|
+
f["gate"], f["id"], f["url"], f["observed"], f["expected"], f["fix"],
|
|
368
|
+
f["fixTier"]])
|
|
369
|
+
return _csv(rows)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def to_csv_scores(report: dict) -> str:
|
|
373
|
+
rows: list[list[object]] = [["generated", "site", "layer", "score"]]
|
|
374
|
+
for layer in sorted(k for k in report["score"] if k != "overall"):
|
|
375
|
+
rows.append([report["generatedAt"], report["site"], layer, report["score"][layer]])
|
|
376
|
+
if "overall" in report["score"]:
|
|
377
|
+
rows.append([report["generatedAt"], report["site"], "overall",
|
|
378
|
+
report["score"]["overall"]])
|
|
379
|
+
return _csv(rows)
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""CLI handlers for `omnirank report`, `omnirank monitor` and `omnirank portfolio`.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 done (monitor: also when there is no regression); 1 only where the user asked
|
|
4
|
+
for it (`--fail-on-regression`) or a confirmed write was declined; 2 usage error, unusable
|
|
5
|
+
input, refused output path, missing converter or credential, or a failed write. Every
|
|
6
|
+
message passes through ``redact()`` and control-character stripping.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import sys
|
|
12
|
+
import tempfile
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from .. import clock
|
|
16
|
+
from ..config import ConfigError, load_config
|
|
17
|
+
from ..connect.confirm import ActionLog, ConfirmError, confirm_and_run
|
|
18
|
+
from ..connect.secrets import redact
|
|
19
|
+
from . import delta as deltamod
|
|
20
|
+
from . import files, model, notify, pdf, portfolio, render
|
|
21
|
+
from .model import clean
|
|
22
|
+
|
|
23
|
+
FORMATS = ("html", "md", "pdf", "csv")
|
|
24
|
+
EXT = {"html": "html", "md": "md", "pdf": "pdf", "csv": "csv"}
|
|
25
|
+
MAX_WHITE_LABEL = 80
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _err(message: object) -> None:
|
|
29
|
+
print(f"omnirank: {redact(clean(message, 600))}", file=sys.stderr)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _positive_int(maximum: int):
|
|
33
|
+
def parse(text: str) -> int:
|
|
34
|
+
try:
|
|
35
|
+
value = int(text)
|
|
36
|
+
except ValueError:
|
|
37
|
+
raise argparse.ArgumentTypeError(f"{text!r} is not a whole number") from None
|
|
38
|
+
if not 1 <= value <= maximum:
|
|
39
|
+
raise argparse.ArgumentTypeError(f"must be from 1 to {maximum}")
|
|
40
|
+
return value
|
|
41
|
+
return parse
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _positive_float(text: str) -> float:
|
|
45
|
+
try:
|
|
46
|
+
value = float(text)
|
|
47
|
+
except ValueError:
|
|
48
|
+
raise argparse.ArgumentTypeError(f"{text!r} is not a number") from None
|
|
49
|
+
if not 0 < value <= 86400:
|
|
50
|
+
raise argparse.ArgumentTypeError("must be above 0 and at most 86400")
|
|
51
|
+
return value
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def add_parsers(sub) -> None:
|
|
55
|
+
rep = sub.add_parser(
|
|
56
|
+
"report", help="Render a sweep report as a single-file HTML, Markdown, PDF or "
|
|
57
|
+
"Looker-Studio CSV report (local; writes one file)")
|
|
58
|
+
rep.add_argument("--input", default=".", metavar="DIR|report.json",
|
|
59
|
+
help="A sweep report JSON, or a directory holding them (default .; the "
|
|
60
|
+
"newest is used and the one before it is the 'before')")
|
|
61
|
+
rep.add_argument("--previous", metavar="report.json",
|
|
62
|
+
help="Report to compare with (default: the next-newest in --input)")
|
|
63
|
+
rep.add_argument("--format", choices=FORMATS, default="html",
|
|
64
|
+
help="html (default, print-optimized), md, pdf (needs weasyprint or "
|
|
65
|
+
"wkhtmltopdf) or csv (findings + scores for Looker Studio)")
|
|
66
|
+
rep.add_argument("--out", metavar="PATH",
|
|
67
|
+
help="Output path inside --root, or - for stdout (default "
|
|
68
|
+
".omnirank/reports/<date>-report.<ext>)")
|
|
69
|
+
rep.add_argument("--root", default=".", help="Project root; output is confined to it")
|
|
70
|
+
rep.add_argument("--config", help="Config file (default <root>/omnirank.config.json "
|
|
71
|
+
"when present; reads report.cta)")
|
|
72
|
+
brand = rep.add_mutually_exclusive_group()
|
|
73
|
+
brand.add_argument("--white-label", metavar="NAME",
|
|
74
|
+
help="Show NAME instead of OmniRank branding (branding only; "
|
|
75
|
+
"findings and evidence are unchanged)")
|
|
76
|
+
brand.add_argument("--no-branding", action="store_true",
|
|
77
|
+
help="Remove OmniRank branding entirely (findings are unchanged)")
|
|
78
|
+
rep.add_argument("--no-cta", action="store_true",
|
|
79
|
+
help="Omit the consulting footer line")
|
|
80
|
+
|
|
81
|
+
mon = sub.add_parser(
|
|
82
|
+
"monitor", help="Compare the latest sweep with the previous one and, on a "
|
|
83
|
+
"regression, print an issue body or (with --send) open a GitHub "
|
|
84
|
+
"issue / post to a Slack webhook")
|
|
85
|
+
mon.add_argument("--input", default=".", metavar="DIR|report.json")
|
|
86
|
+
mon.add_argument("--previous", metavar="report.json")
|
|
87
|
+
mon.add_argument("--root", default=".", help="Project root (action log, --issue-body)")
|
|
88
|
+
mon.add_argument("--issue-body", metavar="PATH",
|
|
89
|
+
help="Write the issue body to PATH inside --root, or - for stdout")
|
|
90
|
+
mon.add_argument("--github-issue", action="store_true",
|
|
91
|
+
help="Open a GitHub issue (GITHUB_TOKEN, GITHUB_REPOSITORY or --repo)")
|
|
92
|
+
mon.add_argument("--repo", metavar="OWNER/NAME")
|
|
93
|
+
mon.add_argument("--slack", action="store_true",
|
|
94
|
+
help="Post to the Slack incoming webhook in OMNIRANK_SLACK_WEBHOOK")
|
|
95
|
+
mon.add_argument("--send", action="store_true",
|
|
96
|
+
help="Actually send (default is a dry run that prints the request)")
|
|
97
|
+
mon.add_argument("--yes", action="store_true",
|
|
98
|
+
help="With --send: confirm in advance (required when stdin is not a "
|
|
99
|
+
"terminal, as in CI)")
|
|
100
|
+
mon.add_argument("--fail-on-regression", action="store_true",
|
|
101
|
+
help="Exit 1 when a regression was found")
|
|
102
|
+
mon.add_argument("--min-drop", type=_positive_int(100), default=1, metavar="N",
|
|
103
|
+
help="A layer score must fall by at least N points to count as a "
|
|
104
|
+
"regression by itself (default 1); new error/warning findings "
|
|
105
|
+
"always count")
|
|
106
|
+
|
|
107
|
+
port = sub.add_parser(
|
|
108
|
+
"portfolio", help="Roll up many sites into one table (config file: sweeps run one "
|
|
109
|
+
"after another under caps; directory: reads existing reports)")
|
|
110
|
+
port.add_argument("source", metavar="DIR|CONFIG.json")
|
|
111
|
+
port.add_argument("--format", choices=("table", "json", "csv"), default="table")
|
|
112
|
+
port.add_argument("--root", help="Where per-site history is kept (default: the config "
|
|
113
|
+
"file's directory)")
|
|
114
|
+
port.add_argument("--max-sites", type=_positive_int(portfolio.MAX_SITES),
|
|
115
|
+
default=portfolio.DEFAULT_MAX_SITES)
|
|
116
|
+
port.add_argument("--max-seconds", type=_positive_float,
|
|
117
|
+
default=portfolio.DEFAULT_MAX_SECONDS,
|
|
118
|
+
help="Total time budget for all sweeps")
|
|
119
|
+
port.add_argument("--sample-size", type=_positive_int(portfolio.MAX_SAMPLE_SIZE),
|
|
120
|
+
default=portfolio.DEFAULT_SAMPLE_SIZE,
|
|
121
|
+
help="Pages sampled per site (ceiling 200)")
|
|
122
|
+
port.add_argument("--min-drop", type=_positive_int(100), default=1, metavar="N",
|
|
123
|
+
help="Score points a layer must lose to count as a regression "
|
|
124
|
+
"(default 1)")
|
|
125
|
+
port.add_argument("--fail-on-regression", action="store_true",
|
|
126
|
+
help="Exit 1 when any site regressed or broke its policy")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _pair(args) -> model.PairInfo:
|
|
130
|
+
"""Load current/previous and tell the operator, on stderr, exactly which files were
|
|
131
|
+
used and which were skipped (a silently skipped newest report must never look fine)."""
|
|
132
|
+
info = model.load_pair_info(args.input, args.previous)
|
|
133
|
+
if Path(args.input).is_dir():
|
|
134
|
+
cur = info.current_path.name if info.current_path else "?"
|
|
135
|
+
prev = info.previous_path.name if info.previous_path else "none"
|
|
136
|
+
print(f"omnirank: using current={clean(cur, 120)} previous={clean(prev, 120)}",
|
|
137
|
+
file=sys.stderr)
|
|
138
|
+
for w in info.warnings():
|
|
139
|
+
print(f"omnirank: WARNING: {w}", file=sys.stderr)
|
|
140
|
+
return info
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def run_command(args) -> int:
|
|
144
|
+
try:
|
|
145
|
+
return {"report": run_report, "monitor": run_monitor,
|
|
146
|
+
"portfolio": run_portfolio}[args.command](args)
|
|
147
|
+
except (model.ReportError, files.WriteRefused, pdf.PdfError, notify.NotifyError,
|
|
148
|
+
portfolio.PortfolioError, ConfigError, ConfirmError) as exc:
|
|
149
|
+
_err(exc)
|
|
150
|
+
return 2
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _cta_enabled(args) -> bool:
|
|
154
|
+
if args.no_cta:
|
|
155
|
+
return False
|
|
156
|
+
cfg_path = Path(args.config) if args.config else Path(args.root) / "omnirank.config.json"
|
|
157
|
+
if args.config or cfg_path.is_file():
|
|
158
|
+
cta = load_config(cfg_path).raw.get("report", {}).get("cta", render.CTA_DEFAULT_ON)
|
|
159
|
+
return cta is not False
|
|
160
|
+
return render.CTA_DEFAULT_ON
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def run_report(args) -> int:
|
|
164
|
+
name = args.white_label
|
|
165
|
+
if name is not None and (not name or len(name) > MAX_WHITE_LABEL or clean(name) != name):
|
|
166
|
+
_err(f"--white-label must be 1 to {MAX_WHITE_LABEL} printable characters")
|
|
167
|
+
return 2
|
|
168
|
+
info = _pair(args)
|
|
169
|
+
current, previous = info.current, info.previous
|
|
170
|
+
d = deltamod.compute(previous, current)
|
|
171
|
+
today = clock.today().isoformat()
|
|
172
|
+
options = render.Options(white_label=name, no_branding=args.no_branding,
|
|
173
|
+
cta=_cta_enabled(args), generated=today)
|
|
174
|
+
fmt = args.format
|
|
175
|
+
rel = args.out or f".omnirank/reports/{today}-report.{EXT[fmt]}"
|
|
176
|
+
to_stdout = rel == "-"
|
|
177
|
+
if fmt == "pdf":
|
|
178
|
+
if to_stdout:
|
|
179
|
+
_err("--format pdf cannot be written to stdout; give --out PATH")
|
|
180
|
+
return 2
|
|
181
|
+
target = files.checked_path(args.root, rel)
|
|
182
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
183
|
+
html = render.to_html(current, d, options)
|
|
184
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
185
|
+
src = Path(tmp) / "report.html"
|
|
186
|
+
src.write_text(html, encoding="utf-8")
|
|
187
|
+
used = pdf.convert(src, target)
|
|
188
|
+
print(f"wrote {target} (via {used})")
|
|
189
|
+
return 0
|
|
190
|
+
if fmt == "csv":
|
|
191
|
+
if to_stdout:
|
|
192
|
+
print(render.to_csv_findings(current), end="")
|
|
193
|
+
return 0
|
|
194
|
+
findings_path = files.write_text(args.root, rel, render.to_csv_findings(current))
|
|
195
|
+
scores_rel = str(Path(rel).with_name(Path(rel).stem + "-scores.csv"))
|
|
196
|
+
scores_path = files.write_text(args.root, scores_rel, render.to_csv_scores(current))
|
|
197
|
+
print(f"wrote {findings_path}\nwrote {scores_path}")
|
|
198
|
+
return 0
|
|
199
|
+
text = (render.to_html if fmt == "html" else render.to_markdown)(current, d, options)
|
|
200
|
+
if to_stdout:
|
|
201
|
+
print(text, end="")
|
|
202
|
+
return 0
|
|
203
|
+
print(f"wrote {files.write_text(args.root, rel, text)}")
|
|
204
|
+
return 0
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def run_monitor(args) -> int:
|
|
208
|
+
info = _pair(args)
|
|
209
|
+
if info.newest_broken:
|
|
210
|
+
_err("the newest report could not be used, so this run was NOT compared; fix or "
|
|
211
|
+
"remove it (see the warning above). Not reporting 'no regression'.")
|
|
212
|
+
return 2
|
|
213
|
+
current, previous = info.current, info.previous
|
|
214
|
+
d = deltamod.compute(previous, current, args.min_drop)
|
|
215
|
+
if previous is None:
|
|
216
|
+
print("monitor: no previous run to compare with; this run is the baseline.")
|
|
217
|
+
return 0
|
|
218
|
+
if not d.has_regression:
|
|
219
|
+
print("monitor: no regression since the previous run.")
|
|
220
|
+
return 0
|
|
221
|
+
body = notify.issue_body(d)
|
|
222
|
+
print(f"monitor: regression detected: {len(d.regressions)} new error/warning "
|
|
223
|
+
f"finding(s), {len(d.score_drops)} layer score drop(s).")
|
|
224
|
+
channels = args.github_issue or args.slack
|
|
225
|
+
actions = []
|
|
226
|
+
if args.github_issue: # validate every channel BEFORE anything is written
|
|
227
|
+
repo = notify.validate_repo(args.repo) if args.repo else notify.repo_from_env()
|
|
228
|
+
actions.append((notify.github_action(repo, notify.issue_title(d), body),
|
|
229
|
+
notify.execute_github))
|
|
230
|
+
if args.slack:
|
|
231
|
+
actions.append((notify.slack_action(notify.webhook_from_env(), notify.slack_text(d)),
|
|
232
|
+
notify.execute_slack))
|
|
233
|
+
if args.issue_body == "-" or (not channels and not args.issue_body):
|
|
234
|
+
print(body)
|
|
235
|
+
elif args.issue_body:
|
|
236
|
+
print(f"wrote {files.write_text(args.root, args.issue_body, body)}")
|
|
237
|
+
rc = 0
|
|
238
|
+
log = ActionLog(args.root)
|
|
239
|
+
for action, execute in actions:
|
|
240
|
+
rc = max(rc, confirm_and_run(action, send=args.send, yes=args.yes, log=log,
|
|
241
|
+
execute=lambda a=action, e=execute: e(a)))
|
|
242
|
+
if rc == 0 and args.fail_on_regression:
|
|
243
|
+
return 1
|
|
244
|
+
return rc
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def run_portfolio(args) -> int:
|
|
248
|
+
source = Path(args.source)
|
|
249
|
+
if source.is_dir():
|
|
250
|
+
rows = portfolio.from_directory(source, max_sites=args.max_sites,
|
|
251
|
+
min_drop=args.min_drop)
|
|
252
|
+
else:
|
|
253
|
+
cfg = portfolio.load_config(source)
|
|
254
|
+
rows = portfolio.run_sweeps(
|
|
255
|
+
cfg, sweep=portfolio.default_sweep, state_root=args.root or cfg.base_dir,
|
|
256
|
+
max_sites=args.max_sites, max_seconds=args.max_seconds,
|
|
257
|
+
sample_size=args.sample_size, min_drop=args.min_drop)
|
|
258
|
+
out = {"table": portfolio.to_table, "json": portfolio.to_json,
|
|
259
|
+
"csv": portfolio.to_csv}[args.format](rows)
|
|
260
|
+
print(out, end="")
|
|
261
|
+
if args.fail_on_regression and any(r["status"] == "regression" or r["policy_failed"]
|
|
262
|
+
for r in rows):
|
|
263
|
+
return 1
|
|
264
|
+
return 0
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
|