@capagents/forgeqe 3.3.7 → 3.3.9

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 (132) hide show
  1. package/HOW_TO_USE.md +92 -0
  2. package/dist/a11y-runtime.mjs +3204 -0
  3. package/dist/docs-site/docs/area-quality/index.html +90 -2
  4. package/dist/docs-site/docs/overview/index.html +1 -1
  5. package/dist/docs-site/docs/search.js +1 -1
  6. package/dist/forgeqe.js +2215 -2094
  7. package/dist/template.html +69 -70
  8. package/dist/web/assets/{3d-force-graph-Bsispdm1.js → 3d-force-graph-BPsVSYjw.js} +1 -1
  9. package/dist/web/assets/Agent-DY6pRvcD.js +10 -0
  10. package/dist/web/assets/{AgentWork-BugEUl60.js → AgentWork-Brch_Mn3.js} +1 -1
  11. package/dist/web/assets/ApiTests-BtWKVPw5.js +17 -0
  12. package/dist/web/assets/{Browse-Dl2Lneca.js → Browse-DbIFxsy8.js} +1 -1
  13. package/dist/web/assets/Chat-BWiH0XGV.js +3 -0
  14. package/dist/web/assets/{CommandPalette-B7YPDCOk.js → CommandPalette-DfoEUEL6.js} +1 -1
  15. package/dist/web/assets/{Compare-D6XsFmmb.js → Compare-DTZ_BW1P.js} +1 -1
  16. package/dist/web/assets/Cost-DDghPWch.js +1 -0
  17. package/dist/web/assets/Data-DZlKsTwA.js +6 -0
  18. package/dist/web/assets/Desktop-DTIZ62Pi.js +1 -0
  19. package/dist/web/assets/DesktopReview-B8-dSGJH.js +2 -0
  20. package/dist/web/assets/Evidence-BYw_Q4Ul.js +1 -0
  21. package/dist/web/assets/Explore-BL_c5WK1.js +2 -0
  22. package/dist/web/assets/{Features-N3_77mz-.js → Features-DrFNrvbh.js} +1 -1
  23. package/dist/web/assets/Flags-CHrDwhqG.js +2 -0
  24. package/dist/web/assets/Flaky-DtcLf8h6.js +1 -0
  25. package/dist/web/assets/Impact-CMU_ijo2.js +3 -0
  26. package/dist/web/assets/Jobs-BjybdQb_.js +5 -0
  27. package/dist/web/assets/KindPage-VK-Vgkzv.js +6 -0
  28. package/dist/web/assets/{LiveDevice-j7NZXIJZ.js → LiveDevice-BqL1P33F.js} +1 -1
  29. package/dist/web/assets/Migration-7BI7iXIv.js +8 -0
  30. package/dist/web/assets/Mobile-AgAhvlVL.js +1 -0
  31. package/dist/web/assets/Observability-5r36Xf3d.js +1 -0
  32. package/dist/web/assets/{OwnItems-BdiPfdTw.js → OwnItems-CqCOuvba.js} +4 -4
  33. package/dist/web/assets/PageAgent-00NQxK49.js +1 -0
  34. package/dist/web/assets/Product-B75ztJFn.js +6 -0
  35. package/dist/web/assets/Production-lIUlcjf0.js +1 -0
  36. package/dist/web/assets/Quality-BlRpB6mx.js +1 -0
  37. package/dist/web/assets/Readiness-CesaSDtp.js +1 -0
  38. package/dist/web/assets/Record-CLy9jQ5N.js +1 -0
  39. package/dist/web/assets/Regression-BjpZrkfK.js +5 -0
  40. package/dist/web/assets/{RelationGraph-Blfs7PhK.js → RelationGraph-ClPBGuMw.js} +1 -1
  41. package/dist/web/assets/{Reports-HQkTX4Kr.js → Reports-Du8SNiHM.js} +2 -2
  42. package/dist/web/assets/Requirements-Dr1iLoMc.js +2 -0
  43. package/dist/web/assets/Responsive-DcD6MLzG.js +3 -0
  44. package/dist/web/assets/{RunDiff-75a-smeg.js → RunDiff-cLSFOsfC.js} +1 -1
  45. package/dist/web/assets/{Settings-BaodIliH.js → Settings-CUT5ggDd.js} +16 -16
  46. package/dist/web/assets/SiteScan-iUfWBeLV.js +5 -0
  47. package/dist/web/assets/{Steps-ZPH_rTJh.js → Steps-DJYwIiDu.js} +2 -2
  48. package/dist/web/assets/{TestData-DUlTo5qt.js → TestData-DqEcL5o4.js} +2 -2
  49. package/dist/web/assets/TestManagement-mBcfWTVH.js +4 -0
  50. package/dist/web/assets/{WhatsNew-BrVNacPl.js → WhatsNew-DrPf6l9-.js} +1 -1
  51. package/dist/web/assets/{agentSettingsSheet-UCqUtdjq.js → agentSettingsSheet-DyaVNewv.js} +1 -1
  52. package/dist/web/assets/api-Dr3U7W5w.js +1 -0
  53. package/dist/web/assets/{choice-C4-yW2x9.js → choice-W0qOx_1k.js} +1 -1
  54. package/dist/web/assets/{coverage-pqIlfEP0.js → coverage-DbHm8BUP.js} +3 -3
  55. package/dist/web/assets/{dataParts-C0C67bVQ.js → dataParts-Bdf97ZOD.js} +3 -3
  56. package/dist/web/assets/{desktopAppPath-B89LKvjx.js → desktopAppPath-kQmQOW6a.js} +1 -1
  57. package/dist/web/assets/{flowTheme-BNKwRxun.js → flowTheme-CVnIjV_m.js} +1 -1
  58. package/dist/web/assets/frame-CavkQick.js +13 -0
  59. package/dist/web/assets/index-BaEsXdFc.css +2 -0
  60. package/dist/web/assets/index-C1kXcI0E.js +57 -0
  61. package/dist/web/assets/line-icons-Cwj9OmCz.js +1 -0
  62. package/dist/web/assets/{logos-P2LOMyTK.js → logos-Cf-Wf5ex.js} +1 -1
  63. package/dist/web/assets/{markdown-CxsWgpYs.js → markdown-Bvv6oj4v.js} +3 -3
  64. package/dist/web/assets/{nav-DYgvAJu-.js → nav-DVPiPhOy.js} +1 -1
  65. package/dist/web/assets/pageBack-Blig1Uqs.js +3 -0
  66. package/dist/web/assets/{palette-BgJTq_Ot.js → palette-DwrGI2Fp.js} +1 -1
  67. package/dist/web/assets/{paletteCommands-Isq1rLs-.js → paletteCommands-DOF2o-rv.js} +1 -1
  68. package/dist/web/assets/parts-DgJ2y_ic.js +1 -0
  69. package/dist/web/assets/{productParts-ZEi0sPIk.js → productParts-B78jij3z.js} +1 -1
  70. package/dist/web/assets/qualityParts-t5t9kEKG.js +2 -0
  71. package/dist/web/assets/{recordTest-Bz5ryzpS.js → recordTest-BbXVOuGZ.js} +1 -1
  72. package/dist/web/assets/{route-oDy8sV6H.js → route-9BkoTWUE.js} +1 -1
  73. package/dist/web/assets/{sectionList-B651VPon.js → sectionList-DMyhAqst.js} +1 -1
  74. package/dist/web/assets/{step-mark-CaKf4dAR.js → step-mark-Bu6fNKW8.js} +1 -1
  75. package/dist/web/assets/stepper-CE4yOLqn.js +1 -0
  76. package/dist/web/assets/wizardParts-Bxb9UG5k.js +1 -0
  77. package/dist/web/index.html +11 -11
  78. package/docs/ForgeQE-Static-Analysis-Report-4008e9ee.html +207 -0
  79. package/docs/ForgeQE-Static-Analysis-Report-4008e9ee.pdf +0 -0
  80. package/docs/{ForgeQE-Static-Analysis-Report-5bbf0da7.html → ForgeQE-Static-Analysis-Report-ccbdac00.html} +33 -33
  81. package/docs/ForgeQE-Static-Analysis-Report-ccbdac00.pdf +0 -0
  82. package/docs/user-guide.html +89 -1
  83. package/forgeqe.example.yaml +1 -1
  84. package/package.json +2 -2
  85. package/prompts/brain.md +7 -0
  86. package/py/forgeqe_engine/cli.py +57 -0
  87. package/py/forgeqe_engine/diagnostics.py +32 -2
  88. package/py/forgeqe_engine/logins.py +11 -0
  89. package/py/forgeqe_engine/persona.py +90 -1
  90. package/py/forgeqe_engine/scan.py +202 -0
  91. package/py/forgeqe_engine/seo.py +95 -0
  92. package/py/forgeqe_engine/seo_analytics.mjs +59 -0
  93. package/py/forgeqe_engine/seo_facts.mjs +63 -0
  94. package/py/forgeqe_engine/seo_site.mjs +36 -0
  95. package/py/forgeqe_engine/service.py +3 -2
  96. package/dist/web/assets/Agent-39FbaH7G.js +0 -10
  97. package/dist/web/assets/ApiTests-B9rtwCbe.js +0 -17
  98. package/dist/web/assets/Chat-DocT7FlH.js +0 -3
  99. package/dist/web/assets/Cost-DvbuXS6u.js +0 -1
  100. package/dist/web/assets/Data-BmZHJkfj.js +0 -6
  101. package/dist/web/assets/Desktop-DD3F69ih.js +0 -1
  102. package/dist/web/assets/DesktopReview-BR0LtVFw.js +0 -2
  103. package/dist/web/assets/Evidence-OqAiYzrl.js +0 -1
  104. package/dist/web/assets/Explore-QNyusEFo.js +0 -2
  105. package/dist/web/assets/Flags-Yv4Ttmmh.js +0 -2
  106. package/dist/web/assets/Flaky-Bg2f2K1U.js +0 -1
  107. package/dist/web/assets/Impact-CpxvVnKj.js +0 -3
  108. package/dist/web/assets/Jobs-_gZTxoaG.js +0 -5
  109. package/dist/web/assets/KindPage-Amr6R7Ym.js +0 -6
  110. package/dist/web/assets/Migration-DfPYzTfk.js +0 -8
  111. package/dist/web/assets/Mobile-fIhhQPsp.js +0 -1
  112. package/dist/web/assets/Observability-13DkrRp2.js +0 -1
  113. package/dist/web/assets/PageAgent-CC8Ha6vu.js +0 -1
  114. package/dist/web/assets/Product-CnXkqwQm.js +0 -6
  115. package/dist/web/assets/Production-5mTIt4sr.js +0 -1
  116. package/dist/web/assets/Quality-DbLcbP1X.js +0 -1
  117. package/dist/web/assets/Readiness-BG1xmC09.js +0 -1
  118. package/dist/web/assets/Record-sFth-2I1.js +0 -1
  119. package/dist/web/assets/Regression-Dd4y8I1z.js +0 -5
  120. package/dist/web/assets/Requirements-DmhUNCIP.js +0 -2
  121. package/dist/web/assets/Responsive-D18eYdCh.js +0 -3
  122. package/dist/web/assets/TestManagement-DUMGdHDw.js +0 -4
  123. package/dist/web/assets/api-D8-lxyQi.js +0 -1
  124. package/dist/web/assets/frame-C8sL1yo-.js +0 -13
  125. package/dist/web/assets/index-BFG13fbg.js +0 -55
  126. package/dist/web/assets/index-DBnWgocz.css +0 -2
  127. package/dist/web/assets/line-icons-CwCZidXs.js +0 -1
  128. package/dist/web/assets/pageBack-BefA2rh7.js +0 -3
  129. package/dist/web/assets/parts-BNpm4gXC.js +0 -1
  130. package/dist/web/assets/qualityParts-DtsD70Qh.js +0 -1
  131. package/dist/web/assets/stepper-CONWT_tv.js +0 -1
  132. package/dist/web/assets/wizardParts-CulZqqjz.js +0 -1
@@ -0,0 +1,202 @@
1
+ """
2
+ forgeqe scan: open each address in ForgeQE's browser, one after another in one tab, and check what is there, with no
3
+ model and no step on the page (nothing clicked, typed or submitted): the rule engine's accessibility checks, the Core
4
+ Web Vitals, and what the page tells search engines and which analytics tags it loads (seo.py). The browser starts as a
5
+ run's does (the same providers, saved signed-in sessions of the logins given), only on the hosts allowed.
6
+
7
+ stdin line 1: {urls, out_dir, browser, headed, axe | ibm, logins, allowed_hosts}; a later "stop" ends it, keeping what
8
+ it checked. Each page is a "page" event; the last line is {"type": "done", "result": {...}}.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import json
14
+ import logging
15
+ import re
16
+ import time
17
+ from urllib.parse import urlsplit
18
+ from pathlib import Path
19
+ from typing import Any, Callable, Dict, List, Optional
20
+
21
+ from .browser import (
22
+ _shutdown_browser_instance,
23
+ browser_launch_kwargs,
24
+ browser_name,
25
+ explain_browser_start,
26
+ local_launch_candidates,
27
+ settle_page,
28
+ start_local_browser,
29
+ window_launch_kwargs,
30
+ )
31
+ from .diagnostics import Diagnostics, _page_key
32
+ from .logins import load_sessions, parse_logins
33
+ from .settings import resolve_browser_headless
34
+ from .urls import _allowed_hosts_violation_for_url, _parse_allowed_domains, normalize_http_base_url
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ MAX_URLS = 25
39
+ _HOST = re.compile(r"\[[0-9a-f:.]+\]|[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*", re.I)
40
+ # After the page settles: time for late scripts, analytics hits and the largest paint before it is read.
41
+ LINGER_SECONDS = 2.5
42
+ NAVIGATE_SECONDS = 45.0
43
+
44
+ Emit = Callable[[Dict[str, Any]], None]
45
+
46
+
47
+ def scan_urls(raw: Any, allowed: Optional[List[str]]) -> "tuple[List[str], List[str]]":
48
+ """The addresses to open, http(s) only, each once, at most MAX_URLS; and why each other one was left out."""
49
+ urls: List[str] = []
50
+ skipped: List[str] = []
51
+ for item in raw if isinstance(raw, list) else []:
52
+ # Written with its scheme and a host name of a host name's shape: never a bare word made into an address.
53
+ u = normalize_http_base_url(item) if isinstance(item, str) and re.match(r"^https?://", item.strip(), re.I) else None
54
+ host = urlsplit(u).hostname if u else None
55
+ if u and (not host or not _HOST.fullmatch(host) or urlsplit(u).username or urlsplit(u).password):
56
+ u = None
57
+ if not u:
58
+ skipped.append(f"{str(item)[:120]}: not an http(s) address")
59
+ continue
60
+ why = _allowed_hosts_violation_for_url(u, allowed)
61
+ if why:
62
+ skipped.append(why)
63
+ continue
64
+ if u not in urls:
65
+ urls.append(u)
66
+ if len(urls) > MAX_URLS:
67
+ skipped.append(f"{len(urls) - MAX_URLS} more addresses: a scan opens at most {MAX_URLS}")
68
+ urls = urls[:MAX_URLS]
69
+ return urls, skipped
70
+
71
+
72
+ async def run_scan(payload: Dict[str, Any], emit: Emit, cancel: asyncio.Event) -> Dict[str, Any]:
73
+ from browser_use import Browser
74
+
75
+ allowed = _parse_allowed_domains(payload.get("allowed_hosts"))
76
+ urls, skipped = scan_urls(payload.get("urls"), allowed)
77
+ for s in skipped:
78
+ emit({"type": "log", "level": "warn", "text": f"Not scanned: {s}"})
79
+ if not urls:
80
+ return {"success": False, "error": "No address to scan.", "pages": []}
81
+ out_dir = Path(str(payload.get("out_dir") or ""))
82
+ if not str(payload.get("out_dir") or "") or not out_dir.is_dir():
83
+ return {"success": False, "error": "No output folder.", "pages": []}
84
+
85
+ axe = payload.get("axe") if isinstance(payload.get("axe"), dict) else None
86
+ ibm = payload.get("ibm") if isinstance(payload.get("ibm"), dict) else None
87
+ diag = Diagnostics(accessibility=True, network=False, axe=axe, ibm=ibm, vitals=True, visual=None, seo=True)
88
+
89
+ headless = resolve_browser_headless(payload.get("headed") is True)
90
+ cfg = payload.get("browser") if isinstance(payload.get("browser"), dict) else {}
91
+ provider = str(cfg.get("provider") or "local")
92
+ remote = cfg.get("remote") if isinstance(cfg.get("remote"), dict) else {}
93
+ kw = browser_launch_kwargs(provider=provider, remote=remote, headless=headless)
94
+ kw.update(window_launch_kwargs(cfg, headless=headless))
95
+ if allowed is not None:
96
+ kw["allowed_domains"] = allowed
97
+ # Signed-in pages: the saved sessions of the logins given, never a password typed (a scan signs in to nothing).
98
+ stored = load_sessions(parse_logins(payload.get("logins")))
99
+ if stored:
100
+ kw["storage_state"] = stored
101
+ emit({"type": "log", "level": "info", "progress": True, "text": f"Starting the browser to scan {len(urls)} page{'s' if len(urls) != 1 else ''}"})
102
+
103
+ try:
104
+ if provider == "local":
105
+ browser, _ = await start_local_browser(
106
+ [{**c, **{k: v for k, v in kw.items() if k not in ("channel", "executable_path")}} for c in local_launch_candidates(headless=headless, choice=cfg.get("local_browser"), method=cfg.get("launch"), port=cfg.get("attach_port"))],
107
+ make=lambda k: Browser(**k),
108
+ on_fallback=lambda failed, nxt, reason: emit({"type": "log", "level": "warn", "text": f"{browser_name(failed)} did not start ({reason}); trying {browser_name(nxt)}"}),
109
+ )
110
+ else:
111
+ browser = Browser(**kw)
112
+ await browser.start()
113
+ except Exception as e:
114
+ return {"success": False, "error": explain_browser_start(str(e)), "pages": []}
115
+
116
+ pages: List[Dict[str, Any]] = []
117
+ try:
118
+ await diag.start(browser)
119
+ for i, url in enumerate(urls, 1):
120
+ if cancel.is_set():
121
+ emit({"type": "log", "level": "warn", "text": f"Stopped: {len(urls) - i + 1} page(s) not scanned"})
122
+ break
123
+ emit({"type": "log", "level": "info", "progress": True, "text": f"Scanning page {i} of {len(urls)}: {url}"})
124
+ t0 = time.monotonic()
125
+ page: Dict[str, Any] = {"url": url}
126
+ try:
127
+ await asyncio.wait_for(browser.navigate_to(url), timeout=NAVIGATE_SECONDS)
128
+ await settle_page(browser)
129
+ await asyncio.sleep(LINGER_SECONDS)
130
+ page["final_url"] = str(await browser.get_current_page_url() or "")[:600]
131
+ await diag.sample(browser)
132
+ page["checked"] = _page_key(page["final_url"]) in diag.pages
133
+ except Exception as e:
134
+ page["error"] = str(e).splitlines()[0][:300] if str(e) else type(e).__name__
135
+ page["seconds"] = round(time.monotonic() - t0, 1)
136
+ pages.append(page)
137
+ emit({"type": "page", **page})
138
+ finally:
139
+ files = [f for f in (diag.write(out_dir), diag.write_perf(out_dir), diag.write_seo(out_dir)) if f]
140
+ (out_dir / "scan.json").write_text(json.dumps({"urls": urls, "skipped": skipped, "pages": pages}, indent=2), encoding="utf-8")
141
+ files.append(str((out_dir / "scan.json").resolve()))
142
+ try:
143
+ await _shutdown_browser_instance(browser)
144
+ except Exception:
145
+ logger.debug("browser not shut down", exc_info=True)
146
+ ok = [p for p in pages if not p.get("error")]
147
+ return {"success": bool(ok), "pages": pages, "files": files, **({} if ok else {"error": "No page could be opened."})}
148
+
149
+
150
+ async def print_pdf(payload: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
151
+ """
152
+ A report ForgeQE wrote, printed to PDF by the local browser: an .html file of ForgeQE's own report app, whose own
153
+ inline scripts draw it (its data is embedded as JSON it only reads), written as the .pdf named once the app says it
154
+ has drawn (``document.body.dataset.ready``). Nothing outside the file is loaded: every http(s) and websocket address
155
+ is blocked (Network.setBlockedURLs). Both paths come from ForgeQE, never from a page.
156
+ """
157
+ import base64
158
+
159
+ from browser_use import Browser
160
+
161
+ html = Path(str(payload.get("html") or ""))
162
+ pdf = Path(str(payload.get("pdf") or ""))
163
+ if html.suffix.lower() != ".html" or not html.is_file() or html.is_symlink() or pdf.suffix.lower() != ".pdf" or not pdf.parent.is_dir():
164
+ return {"success": False, "error": "A report .html and a .pdf in an existing folder are needed."}
165
+ cfg = payload.get("browser") if isinstance(payload.get("browser"), dict) else {}
166
+ try:
167
+ browser, _ = await start_local_browser(
168
+ local_launch_candidates(headless=True, choice=cfg.get("local_browser"), method=cfg.get("launch"), port=None),
169
+ make=lambda k: Browser(**k),
170
+ )
171
+ except Exception as e:
172
+ return {"success": False, "error": explain_browser_start(str(e))}
173
+ try:
174
+ session = await browser.get_or_create_cdp_session()
175
+ send = session.cdp_client.send
176
+ own = html.resolve().as_uri()
177
+ sid = session.session_id
178
+
179
+ # Nothing on the network: every http(s) and websocket address is blocked, so only the file and data: load.
180
+ await send.Network.enable(params={}, session_id=sid)
181
+ await send.Network.setBlockedURLs(params={"urls": ["http://*", "https://*", "ws://*", "wss://*"]}, session_id=sid)
182
+ await send.Page.navigate(params={"url": own}, session_id=sid)
183
+ await settle_page(browser)
184
+ # The report app marks the page drawn after its first render; a page that never does is printed as it is.
185
+ for _ in range(60):
186
+ r = await send.Runtime.evaluate(params={"expression": "document.body && document.body.dataset.ready === '1'", "returnByValue": True}, session_id=sid)
187
+ if ((r or {}).get("result") or {}).get("value") is True:
188
+ break
189
+ await asyncio.sleep(0.25)
190
+ await asyncio.sleep(0.5)
191
+ r = await send.Page.printToPDF(params={"printBackground": True, "preferCSSPageSize": True}, session_id=session.session_id)
192
+ data = base64.b64decode((r or {}).get("data") or "")
193
+ if not data.startswith(b"%PDF"):
194
+ return {"success": False, "error": "The browser did not print a PDF."}
195
+ pdf.write_bytes(data)
196
+ emit({"type": "log", "level": "info", "text": f"PDF written: {pdf.name}"})
197
+ return {"success": True, "pdf": str(pdf.resolve()), "bytes": len(data)}
198
+ finally:
199
+ try:
200
+ await _shutdown_browser_instance(browser)
201
+ except Exception:
202
+ logger.debug("browser not shut down", exc_info=True)
@@ -0,0 +1,95 @@
1
+ """
2
+ What a page tells search engines and which analytics tags it loads, read by two fixed scripts in the page (no page code
3
+ is run by name, nothing is clicked or typed): the page's own facts (title, description, headings, canonical, robots,
4
+ Open Graph, structured data, links) and, from its scripts, globals and resource timing, the analytics tools it loads,
5
+ their ids, the hits they sent and whether a consent banner was there. ForgeQE judges them (src/seo/checks.ts); here
6
+ they are only collected, clipped and made plain. robots.txt and the sitemap are read once per site, from the page's own
7
+ origin, without credentials.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import re
13
+ from pathlib import Path
14
+ from typing import Any, Dict, List, Optional
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ MAX_PAGES = 25
19
+
20
+ def _script(name: str) -> str:
21
+ """One of the fixed page scripts shipped beside this file (seo_*.mjs), which the generated JavaScript tests run too."""
22
+ return (Path(__file__).with_name(f"{name}.mjs")).read_text(encoding="utf-8")
23
+
24
+
25
+ PAGE_FACTS_JS = _script("seo_facts")
26
+ # The analytics tools: what loads them (a script or a global) and the hits they send, matched on resource and script
27
+ # addresses inside the page. Only a tool's name, its ids of their own shape and counts leave the page, never an address.
28
+ ANALYTICS_JS = _script("seo_analytics")
29
+ SITE_JS = _script("seo_site")
30
+
31
+ _ID = re.compile(r"^[A-Za-z0-9-]{1,30}$")
32
+ _TOOLS = {
33
+ "Google Analytics 4", "Universal Analytics", "Google Tag Manager", "Google Ads", "Adobe Analytics", "Meta Pixel", "Microsoft Clarity",
34
+ "Hotjar", "Segment", "Mixpanel", "Amplitude", "Heap", "Matomo", "Plausible", "PostHog", "LinkedIn Insight", "TikTok Pixel",
35
+ "Microsoft Advertising UET", "Piano Analytics",
36
+ }
37
+
38
+
39
+ def clean_analytics(raw: Any) -> Dict[str, Any]:
40
+ """The page's answer in its shape only: known tools, ids of an id's shape, counts."""
41
+ raw = raw if isinstance(raw, dict) else {}
42
+ tools: List[Dict[str, Any]] = []
43
+ for t in raw.get("tools") or []:
44
+ if not isinstance(t, dict) or t.get("tool") not in _TOOLS:
45
+ continue
46
+ tools.append({
47
+ "tool": t["tool"],
48
+ "ids": [str(i) for i in (t.get("ids") or []) if isinstance(i, str) and _ID.fullmatch(i)][:10],
49
+ "loaded": t.get("loaded") is True,
50
+ "scripts": int(t.get("scripts") or 0) if isinstance(t.get("scripts"), (int, float)) else 0,
51
+ "hits": int(t.get("hits") or 0) if isinstance(t.get("hits"), (int, float)) else 0,
52
+ "consent_mode": t.get("consent_mode") if t.get("consent_mode") in ("granted", "denied", "mixed") else None,
53
+ })
54
+ cmp = raw.get("consent_manager")
55
+ dl = raw.get("data_layer")
56
+ return {"tools": tools, "data_layer": int(dl) if isinstance(dl, (int, float)) else None, "consent_manager": str(cmp)[:40] if isinstance(cmp, str) else None}
57
+
58
+
59
+ class SeoCollector:
60
+ """Each page's facts and analytics, and each site's robots.txt and sitemap, for seo.json."""
61
+
62
+ def __init__(self) -> None:
63
+ self.pages: Dict[str, Dict[str, Any]] = {}
64
+ self.sites: Dict[str, Dict[str, Any]] = {}
65
+
66
+ async def collect(self, evaluate: Any, key: str) -> None:
67
+ """`evaluate(expression, await_promise)` runs a fixed script in the page and returns its value."""
68
+ if key in self.pages or len(self.pages) >= MAX_PAGES:
69
+ return
70
+ try:
71
+ facts = await evaluate(PAGE_FACTS_JS, False)
72
+ except Exception:
73
+ logger.debug("page facts not read", exc_info=True)
74
+ return
75
+ if not isinstance(facts, dict) or not str(facts.get("url") or "").startswith("http"):
76
+ return
77
+ try:
78
+ analytics = clean_analytics(await evaluate(ANALYTICS_JS, False))
79
+ except Exception:
80
+ logger.debug("analytics not read", exc_info=True)
81
+ analytics = clean_analytics(None)
82
+ self.pages[key] = {**facts, "analytics": analytics}
83
+ origin = re.match(r"^https?://[^/]+", str(facts["url"]))
84
+ if origin and origin.group(0) not in self.sites:
85
+ try:
86
+ site = await evaluate(SITE_JS, True)
87
+ if isinstance(site, dict):
88
+ self.sites[origin.group(0)] = site
89
+ except Exception:
90
+ logger.debug("robots.txt and sitemap not read", exc_info=True)
91
+
92
+ def result(self) -> Optional[Dict[str, Any]]:
93
+ if not self.pages:
94
+ return None
95
+ return {"pages": list(self.pages.values()), "sites": list(self.sites.values())}
@@ -0,0 +1,59 @@
1
+ // A fixed script ForgeQE runs in a page under test (py/forgeqe_engine/seo.py, and the JavaScript tests src/a11y/suitetests.ts writes).
2
+ // One expression; it reads the page and changes nothing.
3
+ (() => {
4
+ const TOOLS = [
5
+ { tool: 'Google Analytics 4', load: /googletagmanager\.com\/gtag\/js\?(?:[^#]*&)?id=G-/i, hit: /(?:google-analytics\.com|analytics\.google\.com|\/g\/collect)\b.*[?&]tid=G-|\/g\/collect\?/i, id: /\b(G-[A-Z0-9]{4,12})\b/g, globals: [] },
6
+ { tool: 'Universal Analytics', load: /google-analytics\.com\/(?:analytics|ga)\.js/i, hit: /google-analytics\.com\/(?:r\/)?collect\?(?!.*tid=G-)/i, id: /\b(UA-\d{4,10}-\d{1,4})\b/g, globals: ['ga'] },
7
+ { tool: 'Google Tag Manager', load: /googletagmanager\.com\/gtm\.js/i, hit: null, id: /\b(GTM-[A-Z0-9]{4,10})\b/g, globals: ['google_tag_manager'] },
8
+ { tool: 'Google Ads', load: /googletagmanager\.com\/gtag\/js\?(?:[^#]*&)?id=AW-/i, hit: /googleadservices\.com\/pagead\/conversion|google\.com\/pagead\/1p-conversion/i, id: /\b(AW-\d{6,12})\b/g, globals: [] },
9
+ { tool: 'Adobe Analytics', load: /assets\.adobedtm\.com|\/AppMeasurement(?:\.min)?\.js/i, hit: /\.(?:omtrdc\.net|2o7\.net)\/b\/ss\/|\/b\/ss\/[^/]+\/\d/i, id: null, globals: ['_satellite', 's_c_il'] },
10
+ { tool: 'Meta Pixel', load: /connect\.facebook\.net\/[^/]+\/fbevents\.js/i, hit: /facebook\.com\/tr\/?\?/i, id: /[?&]id=(\d{10,20})\b/g, globals: ['fbq'] },
11
+ { tool: 'Microsoft Clarity', load: /clarity\.ms\/tag\//i, hit: /\.clarity\.ms\/collect/i, id: /clarity\.ms\/tag\/([a-z0-9]{6,14})\b/gi, globals: ['clarity'] },
12
+ { tool: 'Hotjar', load: /static\.hotjar\.com\/c\/hotjar-/i, hit: /(?:in|vc|metrics)\.hotjar\.(?:com|io)/i, id: /hotjar-(\d{5,10})\.js/g, globals: ['hj'] },
13
+ { tool: 'Segment', load: /cdn\.segment\.com\/analytics\.js/i, hit: /api\.segment\.io\/v1\//i, id: null, globals: [] },
14
+ { tool: 'Mixpanel', load: /cdn\.mxpnl\.com|mixpanel-[\d.]+(?:\.min)?\.js/i, hit: /api(?:-js)?\.mixpanel\.com\/(?:track|engage)/i, id: null, globals: ['mixpanel'] },
15
+ { tool: 'Amplitude', load: /cdn\.amplitude\.com/i, hit: /api2?\.amplitude\.com\/(?:2\/)?httpapi|api2\.amplitude\.com/i, id: null, globals: ['amplitude'] },
16
+ { tool: 'Heap', load: /cdn\.heapanalytics\.com/i, hit: /heapanalytics\.com\/h\?/i, id: null, globals: ['heap'] },
17
+ { tool: 'Matomo', load: /\/(?:matomo|piwik)\.js/i, hit: /\/(?:matomo|piwik)\.php\?/i, id: /[?&]idsite=(\d{1,6})\b/g, globals: ['_paq', 'Matomo'] },
18
+ { tool: 'Plausible', load: /plausible\.io\/js\//i, hit: /plausible\.io\/api\/event/i, id: null, globals: ['plausible'] },
19
+ { tool: 'PostHog', load: /posthog(?:-js)?[./]|\/static\/array\.js/i, hit: /(?:i\.)?posthog\.com\/(?:e|batch|i\/v0\/e)\//i, id: null, globals: ['posthog'] },
20
+ { tool: 'LinkedIn Insight', load: /snap\.licdn\.com\/li\.lms-analytics/i, hit: /px\.ads\.linkedin\.com/i, id: null, globals: ['_linkedin_data_partner_ids'] },
21
+ { tool: 'TikTok Pixel', load: /analytics\.tiktok\.com\/i18n\/pixel/i, hit: /analytics\.tiktok\.com\/api\/v2\/pixel/i, id: null, globals: ['ttq'] },
22
+ { tool: 'Microsoft Advertising UET', load: /bat\.bing\.com\/bat\.js/i, hit: /bat\.bing\.com\/action\//i, id: null, globals: ['uetq'] },
23
+ { tool: 'Piano Analytics', load: /tag\.aticdn\.net|\/piano-analytics(?:\.min)?\.js|\/smarttag\.js/i, hit: /\.xiti\.com\/hit\.xiti|\.pa-cd\.com\/(?:event|hit)/i, id: /[?&]s=(\d{4,10})\b/g, globals: ['ATInternet'] },
24
+ ];
25
+ const CMPS = [
26
+ ['OneTrust', () => window.OneTrust || window.OptanonWrapper || document.getElementById('onetrust-banner-sdk')],
27
+ ['Cookiebot', () => window.Cookiebot || document.getElementById('CybotCookiebotDialog')],
28
+ ['Didomi', () => window.Didomi || document.getElementById('didomi-host')],
29
+ ['Usercentrics', () => window.UC_UI || document.getElementById('usercentrics-root')],
30
+ ['TrustArc', () => window.truste || document.getElementById('truste-consent-track')],
31
+ ['Osano', () => window.Osano || document.querySelector('.osano-cm-window')],
32
+ ['CookieYes', () => document.querySelector('.cky-consent-container')],
33
+ ['iubenda', () => window._iub || document.getElementById('iubenda-cs-banner')],
34
+ ['Termly', () => window.Termly || document.getElementById('termly-code-snippet-support')],
35
+ ['Quantcast Choice', () => document.querySelector('.qc-cmp2-container')],
36
+ ['TCF consent API', () => typeof window.__tcfapi === 'function'],
37
+ ];
38
+ // A script tag counts once per tag (two tags of one tool load it twice); an address counts once, however it was seen.
39
+ const tags = [...document.scripts].map((s) => s.src).filter(Boolean).slice(0, 1000);
40
+ const urls = [...new Set(tags.concat(performance.getEntriesByType('resource').map((r) => r.name)))].slice(0, 3000);
41
+ const inline = [...document.scripts].filter((s) => !s.src).map((s) => (s.textContent || '').slice(0, 20000)).join('\n').slice(0, 400000);
42
+ const found = [];
43
+ for (const t of TOOLS) {
44
+ const loads = urls.filter((u) => t.load.test(u));
45
+ const hits = t.hit ? urls.filter((u) => t.hit.test(u)) : [];
46
+ const global = t.globals.some((g) => { try { return typeof window[g] !== 'undefined'; } catch (e) { return false; } });
47
+ if (!loads.length && !hits.length && !global) continue;
48
+ const ids = new Set();
49
+ if (t.id) for (const s of [...loads, ...hits, ...(t.tool === 'Google Tag Manager' || t.tool === 'Google Analytics 4' ? [inline] : [])]) for (const m of s.matchAll(t.id)) ids.add(m[1]);
50
+ // Google's consent mode says in each hit what the person allowed: gcs=G1xy, x for ads and y for analytics storage.
51
+ const gcs = [...new Set(hits.map((u) => { const m = /[?&]gcs=G1([01])([01])/.exec(u); return m ? (m[2] === '1' ? 'granted' : 'denied') : null; }).filter(Boolean))];
52
+ found.push({ tool: t.tool, ids: [...ids].slice(0, 10), loaded: loads.length > 0 || global, scripts: tags.filter((u) => t.load.test(u)).length, hits: hits.length, consent_mode: gcs.length === 1 ? gcs[0] : gcs.length ? 'mixed' : null });
53
+ }
54
+ let dataLayer = null;
55
+ try { if (Array.isArray(window.dataLayer)) dataLayer = window.dataLayer.length; } catch (e) {}
56
+ let cmp = null;
57
+ for (const [name, test] of CMPS) { try { if (test()) { cmp = name; break; } } catch (e) {} }
58
+ return { tools: found, data_layer: dataLayer, consent_manager: cmp };
59
+ })()
@@ -0,0 +1,63 @@
1
+ // A fixed script ForgeQE runs in a page under test (py/forgeqe_engine/seo.py, and the JavaScript tests src/a11y/suitetests.ts writes).
2
+ // One expression; it reads the page and changes nothing.
3
+ (() => {
4
+ const clip = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
5
+ const metaName = (n) => { const m = [...document.querySelectorAll('meta[name]')].find((x) => (x.getAttribute('name') || '').toLowerCase() === n); return m ? clip(m.getAttribute('content'), 600) : null; };
6
+ const metaProp = (n) => { const m = document.querySelector('meta[property="' + n + '"]') || document.querySelector('meta[name="' + n + '"]'); return m ? clip(m.getAttribute('content'), 600) : null; };
7
+ const nav = performance.getEntriesByType('navigation')[0] || {};
8
+ const heads = [...document.querySelectorAll('h1,h2,h3,h4,h5,h6')].map((h) => Number(h.tagName[1]));
9
+ let skips = 0;
10
+ for (let i = 1; i < heads.length; i++) if (heads[i] > heads[i - 1] + 1) skips++;
11
+ const here = location.origin;
12
+ let internal = 0, external = 0, nofollow = 0, emptyText = 0;
13
+ for (const a of document.querySelectorAll('a[href]')) {
14
+ let u; try { u = new URL(a.getAttribute('href'), location.href); } catch (e) { continue; }
15
+ if (!/^https?:$/.test(u.protocol)) continue;
16
+ if (u.origin === here) internal++; else external++;
17
+ if (/\bnofollow\b/i.test(a.getAttribute('rel') || '')) nofollow++;
18
+ if (!clip(a.innerText || a.textContent, 5) && !a.getAttribute('aria-label') && !a.querySelector('img[alt]:not([alt=""])')) emptyText++;
19
+ }
20
+ const types = [], ldErrors = [];
21
+ for (const s of document.querySelectorAll('script[type="application/ld+json"]')) {
22
+ try {
23
+ const walk = (v) => { if (Array.isArray(v)) v.forEach(walk); else if (v && typeof v === 'object') { const t = v['@type']; (Array.isArray(t) ? t : [t]).forEach((x) => typeof x === 'string' && types.push(clip(x, 60))); if (v['@graph']) walk(v['@graph']); } };
24
+ walk(JSON.parse(s.textContent || ''));
25
+ } catch (e) { ldErrors.push(clip(e && e.message, 120)); }
26
+ }
27
+ const imgs = [...document.images];
28
+ const resources = performance.getEntriesByType('resource');
29
+ return {
30
+ url: location.href,
31
+ status: Number(nav.responseStatus || 0),
32
+ title: clip(document.title, 300),
33
+ titles: document.querySelectorAll('head title').length,
34
+ description: metaName('description'),
35
+ descriptions: [...document.querySelectorAll('meta[name]')].filter((x) => (x.getAttribute('name') || '').toLowerCase() === 'description').length,
36
+ robots: metaName('robots'),
37
+ googlebot: metaName('googlebot'),
38
+ viewport: metaName('viewport'),
39
+ charset: clip(document.characterSet, 40),
40
+ lang: clip(document.documentElement.getAttribute('lang'), 40),
41
+ canonical: [...document.querySelectorAll('link[rel]')].filter((l) => /\bcanonical\b/i.test(l.getAttribute('rel') || '')).map((l) => clip(l.href, 600)).slice(0, 5),
42
+ h1: [...document.querySelectorAll('h1')].map((h) => clip(h.innerText || h.textContent, 150)).slice(0, 10),
43
+ h1_count: document.querySelectorAll('h1').length,
44
+ headings: heads.length,
45
+ heading_skips: skips,
46
+ words: clip(document.body ? document.body.innerText : '', 200000).split(' ').filter(Boolean).length,
47
+ images: imgs.length,
48
+ images_no_alt: imgs.filter((i) => !i.hasAttribute('alt')).length,
49
+ links_internal: internal,
50
+ links_external: external,
51
+ links_nofollow: nofollow,
52
+ links_empty: emptyText,
53
+ og: { title: metaProp('og:title'), description: metaProp('og:description'), image: metaProp('og:image'), url: metaProp('og:url'), type: metaProp('og:type') },
54
+ twitter: { card: metaProp('twitter:card'), title: metaProp('twitter:title'), image: metaProp('twitter:image') },
55
+ jsonld_types: [...new Set(types)].slice(0, 30),
56
+ jsonld_errors: ldErrors.slice(0, 5),
57
+ hreflang: [...document.querySelectorAll('link[rel="alternate"][hreflang]')].map((l) => ({ lang: clip(l.getAttribute('hreflang'), 20), href: clip(l.href, 600) })).slice(0, 50),
58
+ favicon: Boolean(document.querySelector('link[rel~="icon" i]')),
59
+ mixed: location.protocol === 'https:' ? resources.filter((r) => /^http:/i.test(r.name)).length : 0,
60
+ bytes: Math.round(resources.reduce((a, r) => a + (r.transferSize || 0), 0) + (nav.transferSize || 0)),
61
+ requests: resources.length + 1,
62
+ };
63
+ })()
@@ -0,0 +1,36 @@
1
+ // A fixed script ForgeQE runs in a page under test (py/forgeqe_engine/seo.py, and the JavaScript tests src/a11y/suitetests.ts writes).
2
+ // One expression; it reads the page and changes nothing.
3
+ (async () => {
4
+ const get = async (path, max) => {
5
+ try {
6
+ const ctl = new AbortController();
7
+ const t = setTimeout(() => ctl.abort(), 8000);
8
+ const r = await fetch(path, { credentials: 'omit', redirect: 'follow', signal: ctl.signal, cache: 'no-store' });
9
+ clearTimeout(t);
10
+ const text = r.ok ? (await r.text()).slice(0, max) : '';
11
+ return { status: r.status, text, type: (r.headers.get('content-type') || '').slice(0, 80) };
12
+ } catch (e) { return { status: 0, text: '', type: '' }; }
13
+ };
14
+ const robots = await get('/robots.txt', 200000);
15
+ const lines = robots.text.split(/\r?\n/).map((l) => l.replace(/#.*/, '').trim()).filter(Boolean);
16
+ const disallow = [], sitemaps = [];
17
+ // Groups: user-agent lines in a row, then their rules; the rules for every crawler are the group naming *.
18
+ let star = false, agents = [], lastUa = false;
19
+ for (const l of lines) {
20
+ const m = /^([A-Za-z-]+)\s*:\s*(.*)$/.exec(l);
21
+ if (!m) continue;
22
+ const k = m[1].toLowerCase(), v = m[2].trim();
23
+ if (k === 'user-agent') { if (!lastUa) agents = []; agents.push(v); if (v === '*') star = true; lastUa = true; continue; }
24
+ lastUa = false;
25
+ if (k === 'sitemap' && /^https?:\/\//i.test(v)) sitemaps.push(v.slice(0, 600));
26
+ if (agents.includes('*') && k === 'disallow' && v) disallow.push(v.slice(0, 200));
27
+ }
28
+ let mapUrl = sitemaps.find((s) => { try { return new URL(s).origin === location.origin; } catch (e) { return false; } }) || '/sitemap.xml';
29
+ const map = await get(mapUrl, 5000000);
30
+ const isXml = /<(urlset|sitemapindex)\b/i.test(map.text.slice(0, 2000));
31
+ return {
32
+ origin: location.origin,
33
+ robots: { status: robots.status, user_agent_star: star, disallow: disallow.slice(0, 100), sitemaps: sitemaps.slice(0, 20) },
34
+ sitemap: { url: new URL(mapUrl, location.href).href.slice(0, 600), status: map.status, xml: isXml, index: /<sitemapindex\b/i.test(map.text.slice(0, 2000)), urls: isXml ? (map.text.match(/<loc>/gi) || []).length : 0 },
35
+ };
36
+ })()
@@ -22,7 +22,7 @@ from typing import Any, Callable, Dict, List, Optional, Set, Tuple
22
22
 
23
23
  from . import brand, userlike
24
24
  from .diagnostics import Diagnostics, box_for
25
- from .logins import _host_matches, can_sign_in, code_logins, guard_secrets, load_sessions, parse_logins, passkey_logins, prompt_block, push_logins, register_code_action, register_mfa_actions, save_sessions, use_env_secrets, use_logins
25
+ from .logins import login_values_by_env, _host_matches, can_sign_in, code_logins, guard_secrets, load_sessions, parse_logins, passkey_logins, prompt_block, push_logins, register_code_action, register_mfa_actions, save_sessions, use_env_secrets, use_logins
26
26
  from .memory import READ_ONLY_ACTIONS, UNSAVED_SECRET, MemoryStore, compact_step, flow_step, page_id, unsaved_secret_steps
27
27
  from .prompts import CONVENTIONS, text as prompt_text, use_prompts
28
28
  from .report import CASE_REPORT_INSTRUCTION, CaseReport, build_timeline, case_report_from_history
@@ -1484,7 +1484,8 @@ async def run_browser_task(req: RunRequest, emit: Emit, cancel_event: asyncio.Ev
1484
1484
  agent_tools = Tools()
1485
1485
  captured["task_urls"] = task_urls(req.goal)
1486
1486
  if persona:
1487
- personas.register_persona_tools(agent_tools, persona, persona_findings, req.out_dir)
1487
+ # Typed text holding a login's value is kept in the journey as that value's name (persona.Journey).
1488
+ personas.register_persona_tools(agent_tools, persona, persona_findings, req.out_dir, login_values_by_env(sensitive or {}))
1488
1489
  personas.save_findings(req.out_dir, persona, persona_findings)
1489
1490
  if personas.no_pointer(persona):
1490
1491
  personas.exclude_mouse(agent_tools)