seo-supervisor 1.2.0 → 2.0.0

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 (207) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +16 -3
  4. package/CHANGELOG.md +430 -0
  5. package/NOTICE +7 -0
  6. package/README.md +230 -25
  7. package/agents/seo-auditor.md +16 -0
  8. package/agents/seo-reviewer.md +16 -0
  9. package/bin/agents.mjs +194 -29
  10. package/bin/extras.mjs +422 -0
  11. package/bin/prompt.mjs +34 -14
  12. package/bin/seo-supervisor.mjs +386 -53
  13. package/commands/seo-audit.md +29 -3
  14. package/commands/seo-brief.md +28 -0
  15. package/commands/seo-connect.md +27 -0
  16. package/commands/seo-fix.md +24 -3
  17. package/commands/seo-grow.md +26 -0
  18. package/commands/seo-launch.md +17 -3
  19. package/commands/seo-review.md +13 -1
  20. package/commands/seo-rewrite.md +25 -0
  21. package/commands/seo-setup.md +17 -1
  22. package/commands/seo-watch.md +28 -0
  23. package/hooks/hooks.json +117 -0
  24. package/package.json +20 -7
  25. package/skills/seo-supervisor/NOTICE +7 -0
  26. package/skills/seo-supervisor/SKILL.md +302 -21
  27. package/skills/seo-supervisor/audience.md +61 -0
  28. package/skills/seo-supervisor/examples/drafts/security.md +41 -0
  29. package/skills/seo-supervisor/examples/hooks/README.md +28 -0
  30. package/skills/seo-supervisor/examples/hooks/claude-code-settings.json +15 -0
  31. package/skills/seo-supervisor/examples/hooks/codex-hooks.json +17 -0
  32. package/skills/seo-supervisor/examples/hooks/copilot-hooks.json +15 -0
  33. package/skills/seo-supervisor/examples/hooks/cursor-hooks.json +11 -0
  34. package/skills/seo-supervisor/examples/hooks/github-actions.yml +21 -0
  35. package/skills/seo-supervisor/examples/hooks/pre-commit +17 -0
  36. package/skills/seo-supervisor/examples/hooks/reading-ease.yml +24 -0
  37. package/skills/seo-supervisor/examples/sample-audit.json +94 -2
  38. package/skills/seo-supervisor/examples/sample-report.html +111 -61
  39. package/skills/seo-supervisor/examples/sample-report.md +147 -44
  40. package/skills/seo-supervisor/examples/scheduled-runs.md +89 -0
  41. package/skills/seo-supervisor/examples/snippets.md +648 -1
  42. package/skills/seo-supervisor/grow.md +342 -0
  43. package/skills/seo-supervisor/og-images.md +85 -0
  44. package/skills/seo-supervisor/page-types.md +124 -0
  45. package/skills/seo-supervisor/planning.md +19 -7
  46. package/skills/seo-supervisor/profile-template.md +41 -0
  47. package/skills/seo-supervisor/report-format.md +177 -10
  48. package/skills/seo-supervisor/rewrite.md +59 -0
  49. package/skills/seo-supervisor/rules/ai-search.md +65 -12
  50. package/skills/seo-supervisor/rules/content.md +33 -9
  51. package/skills/seo-supervisor/rules/crawl-index.md +33 -6
  52. package/skills/seo-supervisor/rules/internal-linking.md +49 -6
  53. package/skills/seo-supervisor/rules/launch-monitoring.md +17 -8
  54. package/skills/seo-supervisor/rules/media.md +13 -1
  55. package/skills/seo-supervisor/rules/metadata.md +41 -9
  56. package/skills/seo-supervisor/rules/performance.md +50 -5
  57. package/skills/seo-supervisor/rules/rendering.md +39 -2
  58. package/skills/seo-supervisor/rules/search-intent.md +32 -0
  59. package/skills/seo-supervisor/rules/sitemaps-robots.md +24 -12
  60. package/skills/seo-supervisor/rules/structured-data.md +37 -14
  61. package/skills/seo-supervisor/rules/trust-security.md +25 -2
  62. package/skills/seo-supervisor/rules/urls.md +10 -2
  63. package/skills/seo-supervisor/scripts/ai-answers.mjs +314 -0
  64. package/skills/seo-supervisor/scripts/backlinks.mjs +412 -0
  65. package/skills/seo-supervisor/scripts/change-check.mjs +281 -0
  66. package/skills/seo-supervisor/scripts/checks/agents.mjs +488 -0
  67. package/skills/seo-supervisor/scripts/checks/assets.mjs +404 -0
  68. package/skills/seo-supervisor/scripts/checks/bots.mjs +146 -0
  69. package/skills/seo-supervisor/scripts/checks/business-type.mjs +193 -0
  70. package/skills/seo-supervisor/scripts/checks/content.mjs +391 -0
  71. package/skills/seo-supervisor/scripts/checks/coverage.mjs +184 -0
  72. package/skills/seo-supervisor/scripts/checks/crawl.mjs +95 -0
  73. package/skills/seo-supervisor/scripts/checks/hreflang.mjs +396 -0
  74. package/skills/seo-supervisor/scripts/checks/hygiene.mjs +227 -0
  75. package/skills/seo-supervisor/scripts/checks/lighthouse.mjs +271 -0
  76. package/skills/seo-supervisor/scripts/checks/link-strength.mjs +59 -0
  77. package/skills/seo-supervisor/scripts/checks/links.mjs +360 -0
  78. package/skills/seo-supervisor/scripts/checks/local.mjs +101 -0
  79. package/skills/seo-supervisor/scripts/checks/media.mjs +194 -0
  80. package/skills/seo-supervisor/scripts/checks/outbound.mjs +53 -0
  81. package/skills/seo-supervisor/scripts/checks/page.mjs +223 -0
  82. package/skills/seo-supervisor/scripts/checks/probes.mjs +130 -0
  83. package/skills/seo-supervisor/scripts/checks/render.mjs +552 -0
  84. package/skills/seo-supervisor/scripts/checks/robots.mjs +144 -0
  85. package/skills/seo-supervisor/scripts/checks/schema.mjs +206 -0
  86. package/skills/seo-supervisor/scripts/checks/site-agents.mjs +79 -0
  87. package/skills/seo-supervisor/scripts/checks/site-content.mjs +135 -0
  88. package/skills/seo-supervisor/scripts/checks/site-hygiene.mjs +202 -0
  89. package/skills/seo-supervisor/scripts/checks/site-pages.mjs +474 -0
  90. package/skills/seo-supervisor/scripts/checks/site-security.mjs +102 -0
  91. package/skills/seo-supervisor/scripts/checks/sitemap.mjs +473 -0
  92. package/skills/seo-supervisor/scripts/checks/speed.mjs +267 -0
  93. package/skills/seo-supervisor/scripts/checks/technical.mjs +368 -0
  94. package/skills/seo-supervisor/scripts/checks/tls.mjs +297 -0
  95. package/skills/seo-supervisor/scripts/checks/trust.mjs +421 -0
  96. package/skills/seo-supervisor/scripts/checks/visual.mjs +1132 -0
  97. package/skills/seo-supervisor/scripts/checks/writing.mjs +192 -0
  98. package/skills/seo-supervisor/scripts/commoncrawl.mjs +452 -0
  99. package/skills/seo-supervisor/scripts/connect-keys.mjs +422 -0
  100. package/skills/seo-supervisor/scripts/content-scan.mjs +515 -158
  101. package/skills/seo-supervisor/scripts/crawl/catalog.mjs +1248 -0
  102. package/skills/seo-supervisor/scripts/crawl/fetch.mjs +362 -0
  103. package/skills/seo-supervisor/scripts/crawl/page.mjs +741 -0
  104. package/skills/seo-supervisor/scripts/crawl/queue.mjs +190 -0
  105. package/skills/seo-supervisor/scripts/dashboard.mjs +140 -0
  106. package/skills/seo-supervisor/scripts/data/ai-bots.json +38 -0
  107. package/skills/seo-supervisor/scripts/data/build-schema-vocab.mjs +57 -0
  108. package/skills/seo-supervisor/scripts/data/business-types.json +338 -0
  109. package/skills/seo-supervisor/scripts/data/google-rich-results.json +79 -0
  110. package/skills/seo-supervisor/scripts/data/schema-vocab.json +1 -0
  111. package/skills/seo-supervisor/scripts/deploy-check.mjs +462 -0
  112. package/skills/seo-supervisor/scripts/disavow.mjs +176 -0
  113. package/skills/seo-supervisor/scripts/doctor.mjs +174 -0
  114. package/skills/seo-supervisor/scripts/geo-grid.mjs +371 -0
  115. package/skills/seo-supervisor/scripts/google/search-console.mjs +151 -0
  116. package/skills/seo-supervisor/scripts/google/session.mjs +167 -0
  117. package/skills/seo-supervisor/scripts/google-updates.mjs +189 -0
  118. package/skills/seo-supervisor/scripts/google.mjs +1341 -0
  119. package/skills/seo-supervisor/scripts/gsc-import.mjs +298 -0
  120. package/skills/seo-supervisor/scripts/guard/adapters/claude-code.mjs +149 -0
  121. package/skills/seo-supervisor/scripts/guard/adapters/cline.mjs +28 -0
  122. package/skills/seo-supervisor/scripts/guard/adapters/codex.mjs +26 -0
  123. package/skills/seo-supervisor/scripts/guard/adapters/copilot.mjs +36 -0
  124. package/skills/seo-supervisor/scripts/guard/adapters/cursor.mjs +33 -0
  125. package/skills/seo-supervisor/scripts/guard/adapters/devin.mjs +25 -0
  126. package/skills/seo-supervisor/scripts/guard/adapters/edits.mjs +124 -0
  127. package/skills/seo-supervisor/scripts/guard/mode.mjs +37 -0
  128. package/skills/seo-supervisor/scripts/guard/rules.mjs +931 -0
  129. package/skills/seo-supervisor/scripts/guard.mjs +74 -0
  130. package/skills/seo-supervisor/scripts/images.mjs +408 -0
  131. package/skills/seo-supervisor/scripts/indexnow.mjs +300 -0
  132. package/skills/seo-supervisor/scripts/issues.mjs +217 -0
  133. package/skills/seo-supervisor/scripts/keys/authority.mjs +135 -0
  134. package/skills/seo-supervisor/scripts/keys/bing.mjs +239 -0
  135. package/skills/seo-supervisor/scripts/keys/clarity.mjs +137 -0
  136. package/skills/seo-supervisor/scripts/keys/dataforseo.mjs +57 -0
  137. package/skills/seo-supervisor/scripts/keys/googleplaces.mjs +26 -0
  138. package/skills/seo-supervisor/scripts/keys/http.mjs +212 -0
  139. package/skills/seo-supervisor/scripts/keys/matomo.mjs +138 -0
  140. package/skills/seo-supervisor/scripts/keys/openai.mjs +26 -0
  141. package/skills/seo-supervisor/scripts/keys/perplexity.mjs +26 -0
  142. package/skills/seo-supervisor/scripts/keys/posthog.mjs +165 -0
  143. package/skills/seo-supervisor/scripts/keys/semrush.mjs +25 -0
  144. package/skills/seo-supervisor/scripts/keys/services.mjs +41 -0
  145. package/skills/seo-supervisor/scripts/keys/store.mjs +140 -0
  146. package/skills/seo-supervisor/scripts/keys/visits.mjs +58 -0
  147. package/skills/seo-supervisor/scripts/keys/youtube.mjs +84 -0
  148. package/skills/seo-supervisor/scripts/keyword-data.mjs +316 -0
  149. package/skills/seo-supervisor/scripts/keyword-ideas.mjs +503 -0
  150. package/skills/seo-supervisor/scripts/lib/args.mjs +56 -0
  151. package/skills/seo-supervisor/scripts/lib/business.mjs +27 -0
  152. package/skills/seo-supervisor/scripts/lib/cdp.mjs +242 -0
  153. package/skills/seo-supervisor/scripts/lib/cli.mjs +56 -0
  154. package/skills/seo-supervisor/scripts/lib/csv.mjs +38 -0
  155. package/skills/seo-supervisor/scripts/lib/findings.mjs +100 -0
  156. package/skills/seo-supervisor/scripts/lib/google-client.mjs +9 -0
  157. package/skills/seo-supervisor/scripts/lib/html.mjs +146 -0
  158. package/skills/seo-supervisor/scripts/lib/http.mjs +28 -0
  159. package/skills/seo-supervisor/scripts/lib/image-size.mjs +78 -0
  160. package/skills/seo-supervisor/scripts/lib/is-main.mjs +13 -0
  161. package/skills/seo-supervisor/scripts/lib/net.mjs +116 -0
  162. package/skills/seo-supervisor/scripts/lib/proxy.mjs +47 -0
  163. package/skills/seo-supervisor/scripts/lib/recheck.mjs +106 -0
  164. package/skills/seo-supervisor/scripts/lib/redact.mjs +78 -0
  165. package/skills/seo-supervisor/scripts/lib/robots.mjs +73 -0
  166. package/skills/seo-supervisor/scripts/lib/score.mjs +266 -0
  167. package/skills/seo-supervisor/scripts/lib/settings-dir.mjs +81 -0
  168. package/skills/seo-supervisor/scripts/links-import.mjs +603 -0
  169. package/skills/seo-supervisor/scripts/log-scan.mjs +597 -0
  170. package/skills/seo-supervisor/scripts/og-card.mjs +273 -0
  171. package/skills/seo-supervisor/scripts/osm.mjs +359 -0
  172. package/skills/seo-supervisor/scripts/rdap.mjs +164 -0
  173. package/skills/seo-supervisor/scripts/render-report.mjs +324 -690
  174. package/skills/seo-supervisor/scripts/report/client.js +37 -0
  175. package/skills/seo-supervisor/scripts/report/diff.mjs +264 -0
  176. package/skills/seo-supervisor/scripts/report/findings.mjs +165 -0
  177. package/skills/seo-supervisor/scripts/report/format.mjs +111 -0
  178. package/skills/seo-supervisor/scripts/report/markdown.mjs +250 -0
  179. package/skills/seo-supervisor/scripts/report/model.mjs +171 -0
  180. package/skills/seo-supervisor/scripts/report/overview-lines.mjs +158 -0
  181. package/skills/seo-supervisor/scripts/report/overview.mjs +224 -0
  182. package/skills/seo-supervisor/scripts/report/page.mjs +127 -0
  183. package/skills/seo-supervisor/scripts/report/panel.mjs +172 -0
  184. package/skills/seo-supervisor/scripts/report/panels/ai.mjs +211 -0
  185. package/skills/seo-supervisor/scripts/report/panels/connections.mjs +139 -0
  186. package/skills/seo-supervisor/scripts/report/panels/content.mjs +204 -0
  187. package/skills/seo-supervisor/scripts/report/panels/data-search.mjs +379 -0
  188. package/skills/seo-supervisor/scripts/report/panels/data-site.mjs +44 -0
  189. package/skills/seo-supervisor/scripts/report/panels/links.mjs +380 -0
  190. package/skills/seo-supervisor/scripts/report/panels/local.mjs +221 -0
  191. package/skills/seo-supervisor/scripts/report/panels/site.mjs +359 -0
  192. package/skills/seo-supervisor/scripts/report/panels/speed-media.mjs +267 -0
  193. package/skills/seo-supervisor/scripts/report/sources.mjs +163 -0
  194. package/skills/seo-supervisor/scripts/report/styles.css +223 -0
  195. package/skills/seo-supervisor/scripts/report/traffic.mjs +264 -0
  196. package/skills/seo-supervisor/scripts/report-plan.mjs +112 -33
  197. package/skills/seo-supervisor/scripts/schema-check.mjs +717 -0
  198. package/skills/seo-supervisor/scripts/seo-crawl.mjs +1086 -638
  199. package/skills/seo-supervisor/scripts/seo-diff.mjs +584 -0
  200. package/skills/seo-supervisor/scripts/update-check.mjs +82 -0
  201. package/skills/seo-supervisor/site-types/content.md +34 -1
  202. package/skills/seo-supervisor/site-types/ecommerce.md +38 -1
  203. package/skills/seo-supervisor/site-types/local-business.md +96 -6
  204. package/skills/seo-supervisor/site-types/services.md +46 -0
  205. package/skills/seo-supervisor/site-types/tools.md +3 -3
  206. package/skills/seo-supervisor/strategy.md +232 -0
  207. package/skills/seo-supervisor/troubleshooting.md +56 -0
@@ -0,0 +1,931 @@
1
+ // @ts-check
2
+ // The guard's rules: what an agent is about to do, checked against the actions that need a yes first. Adapters turn
3
+ // their payloads into { kind: "bash", command } (Bash or PowerShell), { kind: "edit", file, before, after } (whole
4
+ // texts; a new file's before is ""), { kind: "delete", file } (removed or moved) or { kind: "prompt", text }.
5
+ // No network access; the disk is read only to look inside a folder about to be deleted.
6
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
7
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { hideSecrets } from "../lib/redact.mjs";
10
+ import { allowedBy, groupFor, groupOf, parseRobots } from "../lib/robots.mjs";
11
+ import { modeOf } from "./mode.mjs";
12
+
13
+ const ALLOW = Object.freeze({ decision: "allow" });
14
+ const SCRIPTS = dirname(dirname(fileURLToPath(import.meta.url)));
15
+
16
+ /** @param {any} action @param {{ mode?: string, settings?: any, cwd?: string }} [opts] @returns {{ decision: "allow"|"ask"|"deny", reason?: string, rule?: string }} */
17
+ export function checkAction(action, { mode = "ask", settings = {}, cwd = process.cwd() } = {}) {
18
+ if (mode === "off" || !action || typeof action !== "object") return ALLOW;
19
+ const hit =
20
+ action.kind === "bash"
21
+ ? bashHit(String(action.command ?? ""), settings || {}, cwd)
22
+ : action.kind === "edit"
23
+ ? editHit(action, cwd)
24
+ : action.kind === "delete"
25
+ ? deleteHit(String(action.file ?? ""), cwd)
26
+ : action.kind === "prompt"
27
+ ? promptHit(String(action.text ?? ""))
28
+ : null;
29
+ if (!hit) return ALLOW;
30
+ // A key is refused in every mode but off: pausing to ask would leave it in the conversation either way.
31
+ return { decision: hit.rule === "key" || mode === "block" ? "deny" : "ask", reason: hit.reason, rule: hit.rule };
32
+ }
33
+
34
+ // ---------- files ----------
35
+ const posix = f => String(f || "").replace(/\\/g, "/");
36
+ // A path from a shell command. PowerShell accepts \ as a separator on every OS, so app\blog is app/blog on Linux too.
37
+ const shellPath = (base, f) => resolve(base, posix(f));
38
+ // The path as the project sees it: relative to the working folder when it's inside it, so a parent folder named
39
+ // "pages" never makes every file a page.
40
+ const rel = (f, cwd) => {
41
+ const p = isAbsolute(f) ? relative(cwd, f) : f;
42
+ return posix(p.startsWith("..") || isAbsolute(p) ? f : p);
43
+ };
44
+ const nameOf = f => posix(f).split("/").pop().toLowerCase();
45
+
46
+ export const isRobotsFile = f => /^robots\.(txt|[cm]?[jt]sx?)$/.test(nameOf(f));
47
+ // Framework config files that can hold redirects, rewrites, a base path or robots settings (a hand-picked list).
48
+ export const isFrameworkConfig = f =>
49
+ /^((next|astro|nuxt|svelte|remix|vite|docusaurus|gridsome|vue)\.config|gatsby-(node|config))\.[cm]?[jt]s$/.test(
50
+ nameOf(f),
51
+ );
52
+ const JSON_REDIRECTS = new Set(["vercel.json", "firebase.json", "staticwebapp.config.json"]);
53
+ const LINE_REDIRECTS = new Set([
54
+ "_redirects",
55
+ ".htaccess",
56
+ "netlify.toml",
57
+ "web.config",
58
+ "caddyfile",
59
+ "nginx.conf",
60
+ "routes.rb",
61
+ "urls.py",
62
+ ]);
63
+ // Next.js 16 renamed middleware to proxy; both are read line by line.
64
+ // https://nextjs.org/docs/app/api-reference/file-conventions/proxy
65
+ const isMiddleware = f => /^(middleware|proxy)\.[cm]?[jt]s$/.test(nameOf(f));
66
+ export const isRedirectFile = f => {
67
+ const n = nameOf(f);
68
+ return (
69
+ JSON_REDIRECTS.has(n) || LINE_REDIRECTS.has(n) || n.endsWith(".conf") || isFrameworkConfig(f) || isMiddleware(f)
70
+ );
71
+ };
72
+ const BUILT = /(^|\/)(node_modules|\.git|\.next|\.nuxt|\.svelte-kit|\.astro|dist|build|out|coverage|vendor)\//;
73
+ const PAGE_EXT =
74
+ "(?:[cm]?[jt]sx?|mdx?|markdown|vue|svelte|astro|html?|php|erb|liquid|njk|hbs|ejs|twig|pug|jinja|j2|cshtml|tmpl)";
75
+ // Page and route files (a hand-picked list): Next.js app/…/page and route; pages/ or routes/ folders minus pages/api/
76
+ // and _app-style files; Markdown in a content folder; any .html file.
77
+ const PAGE_RES = [
78
+ new RegExp(`(^|/)app/(.+/)?(page|route)\\.${PAGE_EXT}$`),
79
+ new RegExp(`(^|/)(pages|routes)/(?!api/)(.+/)?[^_/][^/]*\\.${PAGE_EXT}$`),
80
+ /(^|\/)(content|_posts|posts|blog|articles|docs)\/.+\.(mdx?|markdown|html?)$/,
81
+ /\.html?$/,
82
+ ];
83
+ export const isPageFile = (f, cwd = process.cwd()) => {
84
+ const p = rel(f, cwd);
85
+ return !BUILT.test(p) && PAGE_RES.some(re => re.test(p));
86
+ };
87
+ const isSitemapFile = f => /^sitemap[\w.-]*\.(xml|[cm]?[jt]s)$/.test(nameOf(f));
88
+
89
+ // ---------- edits ----------
90
+ // The unchanged start and end are skipped and the middle counted as a multiset, so a moved line is neither added nor
91
+ // removed.
92
+ function lineDiff(before, after) {
93
+ const a = before.split("\n"),
94
+ b = after.split("\n");
95
+ let s = 0,
96
+ e = 0;
97
+ while (s < a.length && s < b.length && a[s] === b[s]) s++;
98
+ while (e < a.length - s && e < b.length - s && a[a.length - 1 - e] === b[b.length - 1 - e]) e++;
99
+ const left = new Map(),
100
+ added = [];
101
+ for (const l of a.slice(s, a.length - e)) left.set(l, (left.get(l) || 0) + 1);
102
+ for (const l of b.slice(s, b.length - e)) {
103
+ const n = left.get(l);
104
+ if (n) left.set(l, n - 1);
105
+ else added.push(l);
106
+ }
107
+ return { added, removed: [...left].flatMap(([l, n]) => Array(n).fill(l)) };
108
+ }
109
+ const count = (re, s) => (s.match(re) || []).length;
110
+
111
+ // noindex as search engines read it, never the word in prose: a robots or crawler meta tag saying noindex or none; an
112
+ // X-Robots-Tag header (_headers, Apache, nginx, next.config, setHeader); a robots value or metadata object
113
+ // (`robots: { index: false }`, front matter `robots: noindex`); a noindex prop or key set to true. Header and robots
114
+ // values are cut at their quote or line end before the word is tested, so a long line can't backtrack, and the word
115
+ // must stand as a directive ("Robots: none of them" isn't one). A meta tag ends at > or the next <, so it's read once.
116
+ const META = /<meta\b[^<>]*>/gi,
117
+ META_ROBOTS = /\bname\s*=\s*\{?\s*["'`]?(?:robots|googlebot|googlebot-news|bingbot)\b/i,
118
+ META_NOINDEX = /\bcontent\s*=\s*\{?\s*["'`][^"'`]*\b(?:noindex|none)\b/i;
119
+ const VALUES = [
120
+ /x-robots-tag["'`]?\]?(?:\s*[:=]|\s*,(?:\s*value\s*:)?|\s)\s*["'`]?([^"'`\n]*)/gi,
121
+ /\brobots["']?\s*[:=]\s*["'`]?([^"'`\n{]*)/gi,
122
+ ];
123
+ const NOINDEX_WORD = /\b(?:noindex|none)\s*(?:[,;)}\]]|$|\s+(?:nofollow|follow|noarchive|nosnippet)\b)/i;
124
+ const NOINDEX = [/\brobots\s*:\s*\{[^}]*?\bindex\s*:\s*false\b/gi, /\bnoindex\s*[:=]\s*(?:\{\s*)?true\b/gi];
125
+ const noindexCount = s =>
126
+ (s.match(META) || []).filter(t => META_ROBOTS.test(t) && META_NOINDEX.test(t)).length +
127
+ NOINDEX.reduce((n, re) => n + count(re, s), 0) +
128
+ VALUES.reduce((n, re) => n + [...s.matchAll(re)].filter(m => NOINDEX_WORD.test(m[1])).length, 0);
129
+
130
+ // A canonical in the forms sites set it: <link rel="canonical">, a Link header, Next.js alternates.canonical or
131
+ // { canonical }, front matter canonical/canonical_url/canonicalURL, a head library's { rel: 'canonical' }. Each is
132
+ // compared without spacing, from the < { or line start before it to the > } or line end after (500 characters at most
133
+ // each way), so an edit elsewhere on a one-line page doesn't count. Only the first 200 are read, to stay fast.
134
+ const CANONICAL =
135
+ /rel\s*=\s*\{?\s*["'`]?canonical\b|\bcanonical(?:_?url|URL)?["'`]?\s*[:=]|["'`]canonical["'`]\s*[:,]|\{\s*canonical\s*[,}]|,\s*canonical\s*\}/gi;
136
+ const canonicals = s =>
137
+ [...s.matchAll(CANONICAL)].slice(0, 200).map(m => {
138
+ const from = Math.max(0, m.index - 500),
139
+ head = s.slice(from, m.index),
140
+ z = m.index + m[0].length,
141
+ tail = s.slice(z, z + 500).search(/[>}\n]/);
142
+ return s
143
+ .slice(
144
+ from + Math.max(head.lastIndexOf("<"), head.lastIndexOf("{"), head.lastIndexOf("\n")) + 1,
145
+ tail < 0 ? z + 500 : z + tail + 1,
146
+ )
147
+ .replace(/\s+/g, "");
148
+ });
149
+
150
+ // Redirect and URL rules: in JSON and JS configs, the whole block after one of these keys (Next.js redirects(), Astro
151
+ // redirects, Nuxt routeRules, Gatsby createRedirect, base path, trailing slash); in line-based server files, the lines
152
+ // that name a redirect or rewrite.
153
+ const SECTION_KEYS = /\b(redirects|rewrites|routeRules|createRedirect|trailingSlash|cleanUrls|basePath|i18n)\b/g,
154
+ SCALAR = new Set(["trailingSlash", "cleanUrls", "basePath"]);
155
+ function sections(text) {
156
+ const out = [];
157
+ let seen = 0; // a key inside a block already taken is part of it, so the text is read once
158
+ for (const m of text.matchAll(SECTION_KEYS)) {
159
+ if (m.index < seen) continue;
160
+ const i = m.index + m[0].length,
161
+ nl = text.indexOf("\n", i),
162
+ at = SCALAR.has(m[1]) ? -1 : text.slice(i, i + 200).search(/[{[]/);
163
+ if (at < 0) {
164
+ out.push(m[0] + text.slice(i, nl < 0 ? undefined : nl).replace(/\s+/g, ""));
165
+ continue;
166
+ } // a value on its line
167
+ let depth = 0,
168
+ j = i + at; // plain bracket counting: a bracket inside a string can end a block early
169
+ for (; j < text.length && j - i < 20000; j++) {
170
+ const c = text[j];
171
+ if (c === "{" || c === "[") depth++;
172
+ else if ((c === "}" || c === "]") && --depth === 0) break;
173
+ }
174
+ out.push(m[0] + text.slice(i, j + 1).replace(/\s+/g, ""));
175
+ seen = j;
176
+ }
177
+ return out.join("\n");
178
+ }
179
+ const REDIRECT_LINE = /redirect|rewrite|\breturn\s+30[1278]\b|\bredir\b|^\s*(?:from|to|status|force)\s*=/i;
180
+
181
+ let bots;
182
+ const aiBots = () =>
183
+ (bots ||= JSON.parse(readFileSync(join(SCRIPTS, "data", "ai-bots.json"), "utf8")).map(b => b.name));
184
+ const esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
185
+ const botsIn = lines =>
186
+ aiBots().filter(n => lines.some(l => new RegExp(`(?<![\\w-])${esc(n)}(?![\\w-])`, "i").test(l)));
187
+ const list = a => (a.length > 3 ? `${a.slice(0, 3).join(", ")} and ${a.length - 3} more` : a.join(", "));
188
+
189
+ const GOOGLE_DROP = "Every page would drop out of Google.";
190
+ function robotsHit(file, before, after, added, removed) {
191
+ const name = basename(posix(file)),
192
+ changed = [...added, ...removed];
193
+ if (nameOf(file) === "robots.txt") {
194
+ const b = parseRobots(before),
195
+ a = parseRobots(after),
196
+ blocked = (r, ua) => !allowedBy(groupOf(r, ua), "/");
197
+ if (blocked(a, "*") && !blocked(b, "*"))
198
+ return {
199
+ rule: "robots",
200
+ reason: `This makes ${name} block every crawler from the whole site (Disallow: /). ${GOOGLE_DROP}`,
201
+ };
202
+ if (blocked(a, "googlebot") && !blocked(b, "googlebot"))
203
+ return { rule: "robots", reason: `This makes ${name} block Googlebot from the whole site. ${GOOGLE_DROP}` };
204
+ if (b.sitemaps.some(s => !a.sitemaps.includes(s)))
205
+ return {
206
+ rule: "robots",
207
+ reason: `This removes a Sitemap line from ${name}, so search engines lose the list of pages it points them to.`,
208
+ };
209
+ const ai = aiBots().filter(n => JSON.stringify(groupFor(b, n)) !== JSON.stringify(groupFor(a, n)));
210
+ if (ai.length)
211
+ return {
212
+ rule: "ai-policy",
213
+ reason: `This changes what AI crawlers may read (${list(ai)}). It decides whether AI search tools and assistants can see and cite the site.`,
214
+ };
215
+ const rules = added.map(l => l.trim()).filter(l => /^(dis)?allow\s*:/i.test(l));
216
+ return {
217
+ rule: "robots",
218
+ reason: `This edits ${name}, which tells search engines what they may crawl${rules.length ? `. It adds: ${list(rules)}` : ""}. A wrong line can hide pages from Google.`,
219
+ };
220
+ }
221
+ const ai = botsIn(changed);
222
+ if (ai.length)
223
+ return {
224
+ rule: "ai-policy",
225
+ reason: `This changes the robots rules for AI crawlers (${list(ai)}) in ${name}. It decides whether AI search tools and assistants can see and cite the site.`,
226
+ };
227
+ if (added.some(l => /disallow\s*:\s*\[?\s*["'`]\/["'`]/i.test(l)))
228
+ return {
229
+ rule: "robots",
230
+ reason: `This adds disallow: "/" to the robots rules in ${name}. If it applies to all crawlers, ${GOOGLE_DROP.toLowerCase()}`,
231
+ };
232
+ if (removed.some(l => /sitemap/i.test(l)) && count(/sitemap/gi, after) < count(/sitemap/gi, before))
233
+ return {
234
+ rule: "robots",
235
+ reason: `This removes the sitemap from the robots rules in ${name}, so search engines lose the list of pages it points them to.`,
236
+ };
237
+ return {
238
+ rule: "robots",
239
+ reason: `This changes the code that builds robots.txt (${name}), which tells search engines what they may crawl. A wrong rule can hide pages from Google.`,
240
+ };
241
+ }
242
+
243
+ // seo-audit/settings.json, in any folder, holds the guard's mode and the user's yes for outside checks. An edit asks
244
+ // when the guard ends up lower (off < ask < block; missing or unknown is ask), outside checks turn on, or approved
245
+ // gains a check. Text that isn't JSON counts as {}, as the guard reads it.
246
+ const isGuardSettings = f => /(^|\/)seo-audit\/settings\.json$/i.test(posix(f));
247
+ const LEVEL = { off: 0, ask: 1, block: 2 };
248
+ const parsed = t => {
249
+ try {
250
+ const v = JSON.parse(t);
251
+ return v && typeof v === "object" ? v : {};
252
+ } catch {
253
+ return {};
254
+ }
255
+ };
256
+ const OWNER_ONLY =
257
+ "Only the owner should change this: the file holds the guard's mode and their yes for outside checks.";
258
+ function settingsHit(file, before, after, cwd) {
259
+ const b = parsed(before),
260
+ a = parsed(after),
261
+ was = modeOf(b.guard),
262
+ now = modeOf(a.guard),
263
+ added = approvedIn(a).filter(n => !approvedIn(b).includes(n));
264
+ const what =
265
+ LEVEL[now] < LEVEL[was]
266
+ ? `sets the guard from ${was} to ${now}`
267
+ : outsideOn(a) && !outsideOn(b)
268
+ ? "turns outside checks on"
269
+ : added.length
270
+ ? `adds ${list(added)} to the outside checks the owner approved`
271
+ : "";
272
+ return what ? { rule: "settings", reason: `This ${what} in ${rel(file, cwd)}. ${OWNER_ONLY}` } : null;
273
+ }
274
+ // From the shell, where the new text can't be seen: a > redirect to it; tee, Set-Content, Out-File, Add-Content,
275
+ // New-Item or sed -i on it; or a copy or move onto it.
276
+ const WRITERS = new Set(["tee", "set-content", "sc", "add-content", "ac", "out-file", "new-item", "ni"]),
277
+ COPY = new Set(["cp", "copy", "copy-item", "cpi"]);
278
+ function settingsWrite(words, cmd) {
279
+ if (
280
+ words.some(
281
+ (w, i) =>
282
+ isGuardSettings(w.slice(w.lastIndexOf(">") + 1)) && (w.includes(">") || /^\d*>>?$/.test(words[i - 1] ?? "")),
283
+ )
284
+ )
285
+ return true;
286
+ if (WRITERS.has(cmd) || (cmd === "sed" && words.some(w => /^(-i|--in-place)/.test(w))))
287
+ return words.slice(1).some(isGuardSettings);
288
+ if (COPY.has(cmd) || MOVE.has(cmd)) {
289
+ const p = positional(words.slice(1));
290
+ return isGuardSettings(p.dest ?? p.out.at(-1) ?? "");
291
+ }
292
+ return false;
293
+ }
294
+
295
+ function editHit(action, cwd) {
296
+ if (typeof action.file !== "string" || !action.file) return null;
297
+ const file = action.file,
298
+ before = String(action.before ?? "").replace(/\r\n/g, "\n"),
299
+ after = String(action.after ?? "").replace(/\r\n/g, "\n");
300
+ if (before === after) return null;
301
+ if (isGuardSettings(file)) return settingsHit(file, before, after, cwd);
302
+ // Only robots, config and redirect files need the line diff; a page's edit is read whole.
303
+ const name = basename(posix(file)),
304
+ n = nameOf(file),
305
+ config = isFrameworkConfig(file),
306
+ diff = isRobotsFile(file) || isRedirectFile(file) ? lineDiff(before, after) : null;
307
+ const { added = [], removed = [] } = diff || {},
308
+ changed = [...added, ...removed];
309
+ if (isRobotsFile(file)) return robotsHit(file, before, after, added, removed);
310
+ if (noindexCount(after) > noindexCount(before))
311
+ return {
312
+ rule: "noindex",
313
+ reason: `This adds a noindex rule to ${name}. Every page that uses it would drop out of Google's results.`,
314
+ };
315
+ if (config && changed.some(l => /(?<!x-)\brobots\b/i.test(l))) return robotsHit(file, before, after, added, removed);
316
+ const redirects =
317
+ n === "_redirects"
318
+ ? changed.some(l => l.trim())
319
+ : JSON_REDIRECTS.has(n) || config
320
+ ? sections(before) !== sections(after)
321
+ : isRedirectFile(file) && changed.some(l => REDIRECT_LINE.test(l));
322
+ if (redirects)
323
+ return {
324
+ rule: "redirects",
325
+ reason: `This changes the redirect or URL rules in ${name}. Addresses that people and Google already know could stop working or point somewhere new.`,
326
+ };
327
+ if (before.trim() && !after.trim() && isPageFile(file, cwd))
328
+ return {
329
+ rule: "page-remove",
330
+ reason: `This empties ${name}, which removes that page. Anyone following a link or a Google result to it would get a missing page.`,
331
+ };
332
+ const was = /canonical/i.test(before) ? canonicals(before) : [],
333
+ now = was.length ? canonicals(after) : [];
334
+ if (was.some(c => !now.includes(c)))
335
+ return {
336
+ rule: "canonical",
337
+ reason: `This ${now.length < was.length ? "removes" : "changes"} the canonical in ${name}. Google could then treat another address as the main one, or pick one itself.`,
338
+ };
339
+ return null;
340
+ }
341
+
342
+ // ---------- deletes ----------
343
+ // A folder holds a page if any file in it, up to 2,000 entries, is one (dependency and build folders skipped).
344
+ function folderHasPage(dir, cwd) {
345
+ const stack = [dir];
346
+ let seen = 0;
347
+ while (stack.length && seen < 2000) {
348
+ const d = stack.pop();
349
+ let entries;
350
+ try {
351
+ entries = readdirSync(d, { withFileTypes: true });
352
+ } catch {
353
+ continue;
354
+ }
355
+ for (const e of entries) {
356
+ seen++;
357
+ const p = join(d, e.name);
358
+ if (e.isDirectory()) {
359
+ if (!/^(node_modules|\.git|dist|build|out|\.next)$/.test(e.name)) stack.push(p);
360
+ } else if (isPageFile(p, cwd)) return true;
361
+ }
362
+ }
363
+ return false;
364
+ }
365
+ function deleteHit(file, cwd) {
366
+ if (!file) return null;
367
+ const name = basename(posix(file));
368
+ if (isGuardSettings(file)) {
369
+ let s = {};
370
+ try {
371
+ s = parsed(readFileSync(resolve(cwd, file), "utf8"));
372
+ } catch {}
373
+ return modeOf(s.guard) === "block"
374
+ ? {
375
+ rule: "settings",
376
+ reason: `This removes ${rel(resolve(cwd, file), cwd)}, which sets the guard to block, so the guard would go back to asking. ${OWNER_ONLY}`,
377
+ }
378
+ : null;
379
+ }
380
+ if (isRobotsFile(file))
381
+ return { rule: "robots", reason: `This removes ${name}, and with it every crawl rule and its Sitemap line.` };
382
+ if (isRedirectFile(file) && !isFrameworkConfig(file))
383
+ return {
384
+ rule: "redirects",
385
+ reason: `This removes ${name} and the redirects in it. Old addresses would stop forwarding to the new ones.`,
386
+ };
387
+ const full = resolve(cwd, file);
388
+ let folder = false;
389
+ try {
390
+ folder = existsSync(full) && statSync(full).isDirectory();
391
+ } catch {}
392
+ if (folder ? folderHasPage(full, cwd) : isPageFile(full, cwd))
393
+ return {
394
+ rule: "page-remove",
395
+ reason: `This removes or moves ${posix(rel(full, cwd))}, so that page leaves its address. Anyone following a link or a Google result to it would get a missing page, unless a 301 redirect sends them on.`,
396
+ };
397
+ return null;
398
+ }
399
+
400
+ // ---------- shell commands ----------
401
+ // Splits on unquoted && || ; | & and newlines, then into words with quotes removed. Backslashes stay, since Windows
402
+ // paths use them. $( ) (in double quotes too) and ( ) subshells are read as subcommands, a $( ) leaving "$(…)" in its
403
+ // word. A backtick span is read as a command but also left in place, since PowerShell's backtick is an escape.
404
+ // PIPED maps a subcommand after a single | to the one whose output it reads.
405
+ const closing = (s, i) => {
406
+ let d = 0,
407
+ q = "";
408
+ for (let j = i; j < s.length; j++) {
409
+ const c = s[j];
410
+ if (q) {
411
+ if (c === q) q = "";
412
+ } else if (c === '"' || c === "'") q = c;
413
+ else if (c === "(") d++;
414
+ else if (c === ")" && --d === 0) return j;
415
+ }
416
+ return s.length;
417
+ };
418
+ /** @type {WeakMap<string[], string[]>} */
419
+ const PIPED = new WeakMap();
420
+ function subcommands(cmd, depth = 0) {
421
+ const out = [];
422
+ let words = [],
423
+ cur = "",
424
+ q = "",
425
+ has = false,
426
+ from = null,
427
+ tick = -1;
428
+ const word = () => {
429
+ if (has) words.push(cur);
430
+ cur = "";
431
+ has = false;
432
+ };
433
+ const end = () => {
434
+ word();
435
+ if (words.length) {
436
+ if (from) PIPED.set(words, from);
437
+ out.push(words);
438
+ }
439
+ words = [];
440
+ from = null;
441
+ };
442
+ for (let i = 0; i < cmd.length; i++) {
443
+ const c = cmd[i];
444
+ if (c === "(" && q !== "'" && depth < 8 && (cur.endsWith("$") || (!q && !has))) {
445
+ const j = closing(cmd, i);
446
+ out.push(...subcommands(cmd.slice(i + 1, j), depth + 1));
447
+ if (has) cur += "(…)";
448
+ i = j;
449
+ continue;
450
+ }
451
+ if (c === "`" && q !== "'" && depth < 8 && i > tick && (tick = cmd.indexOf("`", i + 1)) > i)
452
+ out.push(...subcommands(cmd.slice(i + 1, tick), depth + 1));
453
+ if (q) {
454
+ if (c === q) q = "";
455
+ else cur += c;
456
+ continue;
457
+ }
458
+ if (c === '"' || c === "'") {
459
+ q = c;
460
+ has = true;
461
+ } else if (c === "&" || c === "|" || c === ";" || c === "\n") {
462
+ const n = out.length;
463
+ end();
464
+ const two = cmd[i + 1] === c;
465
+ if (two) i++;
466
+ if (c === "|" && !two && out.length > n) from = out.at(-1);
467
+ } else if (/\s/.test(c)) word();
468
+ else {
469
+ cur += c;
470
+ has = true;
471
+ }
472
+ }
473
+ end();
474
+ return out;
475
+ }
476
+ // Also the words that open a { } group or a control-flow body (if, then, do, else), so the command after them is read.
477
+ const WRAPPERS = new Set([
478
+ "sudo",
479
+ "time",
480
+ "nice",
481
+ "nohup",
482
+ "env",
483
+ "command",
484
+ "builtin",
485
+ "exec",
486
+ "npx",
487
+ "bunx",
488
+ "noglob",
489
+ "xargs",
490
+ "{",
491
+ "!",
492
+ "if",
493
+ "then",
494
+ "do",
495
+ "else",
496
+ "elif",
497
+ "while",
498
+ "until",
499
+ ]);
500
+ // A rename (Rename-Item and its aliases rni and ren, cmd's rename) moves a page off its address like mv does.
501
+ const DELETE = new Set(["rm", "del", "erase", "rmdir", "rd", "remove-item", "ri", "unlink"]),
502
+ MOVE = new Set(["mv", "move", "move-item", "mi", "rename-item", "rni", "ren", "rename"]);
503
+ const NAMED = /^-(path|literalpath|lp|destination|dest|newname|include|exclude|filter)$/i;
504
+ // Non-option words; a PowerShell -Destination or -NewName value, and mv's -t or --target-directory, come back as dest.
505
+ function positional(args) {
506
+ const out = [];
507
+ let dest = null;
508
+ for (let i = 0; i < args.length; i++) {
509
+ const a = args[i];
510
+ if (a === "-t" || a === "--target-directory") dest = args[++i];
511
+ else if (a.startsWith("--target-directory=")) dest = a.slice(19);
512
+ else if (NAMED.test(a)) {
513
+ const v = args[++i];
514
+ if (/^-(dest|newname)/i.test(a)) dest = v;
515
+ else if (/^-(path|literalpath|lp)$/i.test(a) && v) out.push(v);
516
+ } else if (!a.startsWith("-")) out.push(a);
517
+ }
518
+ return { out, dest };
519
+ }
520
+ const yes = a => a.some(x => x === "--yes" || x.startsWith("--yes="));
521
+ const outsideOn = s => s?.outsideChecks === true || s?.outsideChecks?.on === true;
522
+ // The approved checks, by the names SKILL.md stores in outsideChecks.approved. A legacy "outsideChecks": true means
523
+ // the first list only.
524
+ const FIRST_LIST = ["speed", "render", "lighthouse", "intent", "brand", "updates"];
525
+ const approvedIn = s =>
526
+ s?.outsideChecks === true
527
+ ? FIRST_LIST
528
+ : Array.isArray(s?.outsideChecks?.approved)
529
+ ? s.outsideChecks.approved.map(String)
530
+ : [];
531
+ /** A flag's value: --name value, --name=value, or "" when it's last; undefined when it isn't there. */
532
+ const flagValue = (a, f) => {
533
+ for (let i = 0; i < a.length; i++) {
534
+ if (a[i] === f) return a[i + 1] ?? "";
535
+ if (a[i].startsWith(`${f}=`)) return a[i].slice(f.length + 1);
536
+ }
537
+ return undefined;
538
+ };
539
+ const hostOf = u => {
540
+ try {
541
+ return new URL(u).hostname;
542
+ } catch {
543
+ return "";
544
+ }
545
+ };
546
+ // The crawler's flags that reach past the site being crawled, each with the check name SKILL.md asks a separate yes
547
+ // for. --outside itself needs outsideChecks.on; --check-live only contacts the site's own --site-origin. A flag=value
548
+ // entry needs that value.
549
+ const CRAWL_OUTSIDE = [
550
+ [
551
+ "outbound-links",
552
+ "--outbound-links",
553
+ "This visits up to 100 other websites the pages link to, to find broken links. Those sites see the visits.",
554
+ ],
555
+ [
556
+ "hreflang-other-sites",
557
+ "--hreflang-other-sites",
558
+ "This visits up to 20 language versions of the pages on other websites, to see whether they link back.",
559
+ ],
560
+ [
561
+ "ai-bot-probe",
562
+ "--ai-bot-probe",
563
+ "This asks up to 3 pages again pretending to be AI search crawlers. A strict firewall may block this computer for a while.",
564
+ ],
565
+ ["desktop", "--desktop", "This sends the sample pages to Google PageSpeed again, for desktop."],
566
+ [
567
+ "render-all",
568
+ "--render=all",
569
+ "This renders every indexable page (up to 200) in a headless browser, where each page's own scripts run, analytics included.",
570
+ ],
571
+ [
572
+ "lighthouse",
573
+ "--lighthouse",
574
+ "This runs Lighthouse on the site's pages, where each page's own scripts run, analytics included.",
575
+ ],
576
+ ];
577
+ const hasFlag = (a, f) => {
578
+ const [k, v] = f.split("="),
579
+ x = flagValue(a, k);
580
+ return v ? x === v : x !== undefined;
581
+ };
582
+ function crawlHit(args, settings) {
583
+ if (args.includes("--outside") && !outsideOn(settings))
584
+ return {
585
+ rule: "outside",
586
+ reason:
587
+ "This turns on outside checks: page addresses go to Google PageSpeed, and a headless browser runs the site's own scripts. seo-audit/settings.json doesn't record the owner's yes for them yet.",
588
+ };
589
+ const ok = approvedIn(settings),
590
+ off = CRAWL_OUTSIDE.find(([name, flag]) => hasFlag(args, flag) && !ok.includes(name));
591
+ if (off)
592
+ return {
593
+ rule: "outside",
594
+ reason: `${off[2]} It needs its own yes: seo-audit/settings.json's outsideChecks.approved doesn't list "${off[0]}" yet.`,
595
+ };
596
+ // A page picked to render needs its own yes each time when it's on another site. The test-only endpoints would
597
+ // receive the PageSpeed key.
598
+ const page = flagValue(args, "--render-page");
599
+ if (
600
+ page !== undefined &&
601
+ ![hostOf(flagValue(args, "--url")), hostOf(flagValue(args, "--site-origin"))].includes(hostOf(page))
602
+ )
603
+ return {
604
+ rule: "outside",
605
+ reason: `This renders ${page || "a page"} in a headless browser. It isn't on the site being crawled, so that other site sees the visit and its own scripts run.`,
606
+ };
607
+ const at = ["--psi-endpoint", "--crux-endpoint"].find(f => flagValue(args, f) !== undefined);
608
+ if (at)
609
+ return {
610
+ rule: "outside",
611
+ reason: `This sends the speed requests, with the PageSpeed key, to ${flagValue(args, at) || "another address"} instead of Google.`,
612
+ };
613
+ return null;
614
+ }
615
+ // What each script does once given --yes, worded for the prompt that asks.
616
+ const OUTSIDE = {
617
+ google: a =>
618
+ a[0] === "submit-sitemap" &&
619
+ yes(a) &&
620
+ "This submits the sitemap to Google Search Console, a change in the owner's Google account.",
621
+ "connect-keys": a =>
622
+ yes(a) &&
623
+ ({
624
+ "submit-bing": "This asks Bing to crawl these addresses, through the owner's Bing Webmaster Tools account.",
625
+ fetch:
626
+ "This sends the site's address and domain names to every connected service that has a key (Bing, Moz and the others).",
627
+ test: "This sends the saved token to Matomo or PostHog to test it.",
628
+ }[a[0]] ||
629
+ "This contacts a connected service with the owner's key."),
630
+ indexnow: a =>
631
+ yes(a) &&
632
+ "This sends the listed addresses to IndexNow, which passes them on to Bing, Yandex and other search engines.",
633
+ issues: a =>
634
+ yes(a) &&
635
+ "This files GitHub issues in the repository with the owner's own gh login. Everyone who can see the repository sees them.",
636
+ "ai-answers": a =>
637
+ yes(a) &&
638
+ "This asks Perplexity or OpenAI the owner's questions with the owner's keys, and each question costs money.",
639
+ "geo-grid": a =>
640
+ yes(a) &&
641
+ "This sends the business's search phrases and map points to Google Places with the owner's key. It can cost money.",
642
+ rdap: a => yes(a) && "This sends the domain names to IANA and to each domain's registry.",
643
+ osm: a => yes(a) && "This sends the business's address to OpenStreetMap, and asks for similar businesses nearby.",
644
+ commoncrawl: a => yes(a) && "This downloads data about links to the site from Common Crawl.",
645
+ backlinks: a => yes(a) && "This visits up to 100 pages on other people's websites. Those sites see the visits.",
646
+ "google-updates": a => yes(a) && "This reads Google's public Search Status Dashboard over the internet.",
647
+ images: a =>
648
+ yes(a) &&
649
+ (a.includes("--label-ai")
650
+ ? "This writes an AI-generated label into these image files."
651
+ : "This writes smaller copies of the site's images into the project. The originals are kept."),
652
+ "log-scan": a => {
653
+ const i = a.indexOf("--verify-ips");
654
+ return (
655
+ i >= 0 &&
656
+ !(a[i + 1] && !a[i + 1].startsWith("-")) &&
657
+ "This downloads the crawler companies' public lists of addresses, and asks this computer's DNS server about addresses that claim to be YandexBot."
658
+ );
659
+ },
660
+ "schema-check": a =>
661
+ a.includes("--allow-remote") && "This lets the structured data check download pages from other websites.",
662
+ };
663
+ const KEY_HINT = key => `node "${join(SCRIPTS, "connect-keys.mjs")}" set ${key}`;
664
+ // Where --yes could hide in an argument: $X, ${X}, $(…), cmd's %X% (not a %-escape like %E2%) and PowerShell's @splat.
665
+ const VARIABLE = /\$[\w{(]|%(?![0-9a-f]{2})[a-z_]\w*%|^@\w+$/i;
666
+ const SHELL = /^(bash|sh|zsh|dash|ksh)$/;
667
+ // The command string another shell is handed: bash -c "…" (or -lc), powershell -Command "…" (any short form), cmd /c ….
668
+ function shellString(cmd, words) {
669
+ const at = SHELL.test(cmd)
670
+ ? words.findIndex((w, i) => i > 0 && /^-[a-z]*c[a-z]*$/i.test(w))
671
+ : /^(powershell|pwsh)$/.test(cmd)
672
+ ? words.findIndex(w => /^[-/]c(o(m(m(a(n(d)?)?)?)?)?)?$/i.test(w))
673
+ : cmd === "cmd"
674
+ ? words.findIndex(w => /^\/[ck]$/i.test(w))
675
+ : -1;
676
+ return at < 1 ? null : SHELL.test(cmd) ? (words[at + 1] ?? "") : words.slice(at + 1).join(" ");
677
+ }
678
+
679
+ // Emptying a file from the shell removes a page just as deleting it does. Forms (a hand-picked list): a > redirect from
680
+ // a command that writes nothing (none, : or true, '' or $null, empty echo or printf, cat or type of /dev/null or nul);
681
+ // truncate to 0; Clear-Content; Set-Content with an empty value; Out-File, Set-Content or tee with nothing piped in; a
682
+ // copy of /dev/null or nul. Real text written with > or >>, and output that can't be known, aren't emptying.
683
+ const NUL = /^(\/dev\/null|nul:?)$/i,
684
+ blank = a => !a.trim() || /^\$null$/i.test(a);
685
+ function writesNothing(words) {
686
+ if (!words.length || (words.length === 1 && blank(words[0]))) return true;
687
+ const cmd = nameOf(words[0]).replace(/\.exe$/, ""),
688
+ args = words.slice(1);
689
+ if (cmd === ":" || cmd === "true") return true;
690
+ if (/^(echo|printf|write-output)$/.test(cmd)) return args.every(a => blank(a) || /^-[neE]+$/.test(a));
691
+ return /^(cat|type|get-content|gc)$/.test(cmd) && args.length > 0 && args.every(a => NUL.test(a));
692
+ }
693
+ // A subcommand's words without its redirects, and the files its > (not >>, not a >&1 copy) truncates. A word with a
694
+ // space in it was quoted, and one with a < before its > is a tag (<h1>Hi</h1>), so neither is a redirect.
695
+ function redirects(words) {
696
+ const targets = [],
697
+ rest = [];
698
+ for (let i = 0; i < words.length; i++) {
699
+ const w = words[i],
700
+ at = w.indexOf(">");
701
+ if (at < 0 || /\s/.test(w) || w.slice(0, at).includes("<")) {
702
+ rest.push(w);
703
+ continue;
704
+ }
705
+ const pre = w.slice(0, at),
706
+ append = w[at + 1] === ">",
707
+ to = w.slice(at + (append ? 2 : 1)) || (words[++i] ?? "");
708
+ if (pre && !/^[\d&]$/.test(pre)) rest.push(pre);
709
+ if (!append && to && !to.startsWith("&")) targets.push(to);
710
+ }
711
+ return { targets, rest };
712
+ }
713
+ // A PowerShell cmdlet's -Name value (or -Name:value) arguments, found by any start of the name (-Val for -Value), and
714
+ // the rest by position. Its switches take no value.
715
+ const PS_SWITCH = /^-(force|nonewline|append|noclobber|whatif|confirm|passthru|verbose|debug)$/i;
716
+ function psArgs(args) {
717
+ const named = [],
718
+ pos = [];
719
+ for (let i = 0; i < args.length; i++) {
720
+ const m = /^-([a-z]\w*)(?::(.*))?$/i.exec(args[i]);
721
+ if (!m) pos.push(args[i]);
722
+ else named.push([m[1].toLowerCase(), m[2] ?? (PS_SWITCH.test(args[i]) ? true : (args[++i] ?? ""))]);
723
+ }
724
+ return { pos, get: (...names) => named.find(([k]) => names.some(n => n.startsWith(k)))?.[1] };
725
+ }
726
+ const EMPTIERS = new Set(["truncate", "clear-content", "clc", "set-content", "sc", "out-file", "tee", ...COPY]);
727
+ /** The files a subcommand leaves empty. @param {string[]} words @param {string[] | undefined} from what's piped into it
728
+ * @param {string} name its command's name, so most commands are passed over at once */
729
+ function emptied(words, from, name) {
730
+ if (!EMPTIERS.has(name) && !words.some(w => w.includes(">"))) return [];
731
+ const { targets, rest } = redirects(words),
732
+ cmd = nameOf(rest[0] ?? "").replace(/\.exe$/, ""),
733
+ out = targets.length && writesNothing(rest) ? targets : [];
734
+ if (!EMPTIERS.has(cmd)) return out;
735
+ const args = rest.slice(1),
736
+ none = !from || writesNothing(from);
737
+ if (cmd === "truncate") {
738
+ const size = args
739
+ .map((a, i) => (/^(-s|--size)$/.test(a) ? args[i + 1] : /^(?:-s|--size=)(.+)$/.exec(a)?.[1]))
740
+ .find(v => v !== undefined);
741
+ if (size === "0")
742
+ out.push(...args.filter((a, i) => !a.startsWith("-") && !/^(-s|--size)$/.test(args[i - 1] ?? "")));
743
+ } else if (cmd === "clear-content" || cmd === "clc") out.push(...positional(args).out);
744
+ else if (/^(set-content|sc|out-file)$/.test(cmd)) {
745
+ // Out-File writes its -InputObject or what's piped in; Set-Content its -Value (or second word) or what's piped in.
746
+ const ps = psArgs(args),
747
+ named =
748
+ cmd === "out-file" ? ps.get("filepath", "literalpath", "lp", "path") : ps.get("path", "literalpath", "lp"),
749
+ path = named ?? ps.pos[0];
750
+ const value = cmd === "out-file" ? ps.get("inputobject") : (ps.get("value") ?? ps.pos[named === undefined ? 1 : 0]);
751
+ const empty =
752
+ typeof value === "string"
753
+ ? blank(value)
754
+ : value === undefined && (cmd === "out-file" ? none : !!from && writesNothing(from));
755
+ if (typeof path === "string" && empty && !ps.get("append") && !ps.get("noclobber")) out.push(path);
756
+ } else if (cmd === "tee" && none && !args.some(a => /^(-a|--append)$/.test(a))) out.push(...positional(args).out);
757
+ else if (COPY.has(cmd)) {
758
+ const p = positional(args),
759
+ to = p.dest ?? p.out.at(-1),
760
+ src = p.dest ? p.out : p.out.slice(0, -1);
761
+ if (to && src.length && src.every(s => NUL.test(s))) out.push(to);
762
+ }
763
+ return out;
764
+ }
765
+
766
+ function bashHit(command, settings, cwd, dir = cwd, depth = 0) {
767
+ for (let words of subcommands(command)) {
768
+ const from = PIPED.get(words);
769
+ // Wrappers that run the rest: sudo, env and the like; timeout with its options and duration; stdbuf with its modes.
770
+ for (let w; (w = words[0]?.toLowerCase()) !== undefined;) {
771
+ if (w === "timeout" || w === "stdbuf") {
772
+ words = words.slice(1);
773
+ while (words[0]?.startsWith("-")) words = words.slice(/^-[skioe]$/.test(words[0]) ? 2 : 1);
774
+ if (w === "timeout") words = words.slice(1);
775
+ } else if (/^\w+=/.test(w) || WRAPPERS.has(w) || w.startsWith("-")) words = words.slice(1);
776
+ else break;
777
+ }
778
+ if (!words.length) continue;
779
+ const cmd = nameOf(words[0]).replace(/\.exe$/, "");
780
+ const inner = shellString(cmd, words);
781
+ if (inner !== null) {
782
+ const hit = depth < 4 && bashHit(inner, settings, cwd, dir, depth + 1);
783
+ if (hit) return hit;
784
+ continue;
785
+ }
786
+ if (settingsWrite(words, cmd))
787
+ return {
788
+ rule: "settings",
789
+ reason: `This writes seo-audit/settings.json from the shell, where the guard can't see what changes. ${OWNER_ONLY}`,
790
+ };
791
+ // A cd earlier in the same command moves where the later paths start.
792
+ if (/^(cd|chdir|pushd|set-location|sl)$/.test(cmd)) {
793
+ const to = positional(words.slice(1)).out.find(w => !/^\/d$/i.test(w));
794
+ if (to && !/^[~$%]/.test(to)) dir = shellPath(dir, to);
795
+ continue;
796
+ }
797
+ // The skill's scripts by file name, run by node, bun or deno or directly. The bin's subcommands (seo-supervisor
798
+ // issues, npx seo-supervisor@1.2.0 issues, node bin/seo-supervisor.mjs issues) run the script of that name.
799
+ let script = null,
800
+ args = [];
801
+ const isScript = w => /^[\w-]+\.mjs$/.test(nameOf(w));
802
+ const at = /^(node|bun|deno)$/.test(cmd)
803
+ ? words.findIndex((w, i) => i > 0 && isScript(w))
804
+ : isScript(words[0])
805
+ ? 0
806
+ : -1;
807
+ if (at >= 0) {
808
+ script = nameOf(words[at]).slice(0, -4);
809
+ args = words.slice(at + 1);
810
+ }
811
+ if (/^seo-supervisor@[\w.^~-]+$/.test(cmd) || cmd === "seo-supervisor") {
812
+ script = "seo-supervisor";
813
+ args = words.slice(1);
814
+ }
815
+ if (script === "seo-supervisor" && /^[a-z][\w-]*$/.test(args[0] ?? "")) {
816
+ script = args[0];
817
+ args = args.slice(1);
818
+ }
819
+ if (script) {
820
+ // connect-keys set <service> <key>, or a key piped into it: the words after set, minus --flag values.
821
+ const setWords =
822
+ script === "connect-keys" && args[0] === "set"
823
+ ? args
824
+ .slice(1)
825
+ .filter(
826
+ (a, i, all) => !a.startsWith("--") && !(all[i - 1]?.startsWith("--") && !all[i - 1].includes("=")),
827
+ )
828
+ : null;
829
+ if (setWords && (setWords.length >= 2 || keyPiece(command) || HEX.test(command)))
830
+ return {
831
+ rule: "key",
832
+ reason: `The key would be on the command line, where it stays in the shell's history and this conversation. In your own terminal, run ${KEY_HINT(setWords[0] || "<service>")} instead: it asks for the key and hides it as you type.`,
833
+ };
834
+ const crawl = script === "seo-crawl" && crawlHit(args, settings);
835
+ if (crawl) return crawl;
836
+ const why = Object.hasOwn(OUTSIDE, script) && OUTSIDE[script](args);
837
+ if (why) return { rule: "outside", reason: why };
838
+ const v = (Object.hasOwn(OUTSIDE, script) || script === "seo-crawl") && args.find(a => VARIABLE.test(a));
839
+ if (v)
840
+ return {
841
+ rule: "outside",
842
+ reason: `One of the script's arguments is a variable (${v}), which could hold --yes or a flag that contacts an outside service. Write the arguments out in full, so the guard can see what it does.`,
843
+ };
844
+ continue;
845
+ }
846
+ for (const f of emptied(words, from, cmd)) {
847
+ const full = shellPath(dir, f),
848
+ hit = deleteHit(full, cwd);
849
+ if (hit)
850
+ return hit.rule !== "page-remove"
851
+ ? hit
852
+ : {
853
+ rule: "page-remove",
854
+ reason: `This empties ${posix(rel(full, cwd))} from the shell, which removes that page. Anyone following a link or a Google result to it would get a missing page.`,
855
+ };
856
+ }
857
+ // Removing or moving files: rm, git rm, del, Remove-Item; mv, git mv, Move-Item (the last word is where it goes).
858
+ let paths = [],
859
+ base = dir;
860
+ if (DELETE.has(cmd)) paths = positional(words.slice(1)).out;
861
+ else if (MOVE.has(cmd)) {
862
+ const p = positional(words.slice(1));
863
+ paths = p.dest ? p.out : p.out.slice(0, -1);
864
+ } else if (cmd === "git") {
865
+ let i = 1;
866
+ while (i < words.length && words[i].startsWith("-")) {
867
+ if (words[i] === "-C") base = shellPath(base, words[i + 1] ?? "");
868
+ i += /^-[Cc]$/.test(words[i]) ? 2 : 1;
869
+ }
870
+ const p = positional(words.slice(i + 1));
871
+ if (words[i] === "rm") paths = p.out;
872
+ else if (words[i] === "mv") paths = p.out.slice(0, -1);
873
+ }
874
+ for (const f of paths) {
875
+ const hit = deleteHit(shellPath(base, f), cwd);
876
+ if (hit) return hit;
877
+ }
878
+ }
879
+ return null;
880
+ }
881
+
882
+ // ---------- prompts ----------
883
+ // redact.mjs's token patterns, tried on each piece between spaces, quotes, brackets and = ? & # ; @, so a key is found
884
+ // inside other text while the patterns that need those characters never fire: "a Bearer token" or ?key=blue in a
885
+ // message isn't a key. Its sk- pattern skips a key right after / or a letter, so /blog/sk-guide-… isn't one either.
886
+ /** @type {[RegExp, string][]} */
887
+ const SERVICE_BY_PREFIX = [
888
+ [/^sk-ant-/, ""],
889
+ [/^sk-/, "openai"],
890
+ [/^pplx-/, "perplexity"],
891
+ [/^phx_/, "posthog"],
892
+ [/^AIza/, "googleplaces"],
893
+ ];
894
+ const keyPiece = text => text.split(/[\s"'`()<>{}[\],=?&#;@|]+/).find(p => p.length > 15 && hideSecrets(p) !== p);
895
+ // A bare 32-character hex key (Bing, Matomo) has no prefix, and commit hashes and MD5s look the same, so in a message
896
+ // it counts only within 20 characters of a key word (a heuristic); in a connect-keys set command, anywhere.
897
+ const HEX = /(?<![0-9a-z])[0-9a-f]{32}(?![0-9a-z])/i,
898
+ HEX_KEY = new RegExp(`\\b(key|api|token|secret|bing|matomo|password|auth)\\w{0,20}[^]{0,20}?${HEX.source}`, "i");
899
+ function promptHit(text) {
900
+ const piece = keyPiece(text),
901
+ hex = piece ? null : HEX_KEY.exec(text);
902
+ if (!piece && !hex) return null;
903
+ const found = !piece
904
+ ? `a 32-character code after "${hex[1]}"`
905
+ : `it starts "${piece.match(/(?:sk-|pplx-|phx_|AIza|gh[pousr]_|github_pat_|xox|ya29|GOCSPX|eyJ|AKIA|ASIA|[sr]k_)[\w-]{0,4}/)?.[0] || piece.slice(0, 4)}…"`;
906
+ const service = piece
907
+ ? SERVICE_BY_PREFIX.find(([re]) => re.test(piece.replace(/^.*?(?=sk-|pplx-|phx_|AIza)/, "")))?.[1]
908
+ : /bing|matomo/i.exec(hex[0])?.[0].toLowerCase();
909
+ return {
910
+ rule: "key",
911
+ reason: `Your message looks like it holds an API key (${found}), so the SEO Supervisor guard stopped it before the AI saw it. Keys in chat stay in the conversation's history. To save a key for SEO Supervisor, run ${KEY_HINT(service || "<service>")} in your own terminal: it asks for the key and hides it as you type. Then send your message again without the key. The message may still be in this computer's prompt history, so if that matters, replace the key.`,
912
+ };
913
+ }
914
+
915
+ // ---------- the Stop note's test ----------
916
+ // Lines that carry SEO (a hand-picked list): titles, meta and link tags, robots, canonicals, hreflang, structured data,
917
+ // sitemaps, Open Graph and the frameworks' head and metadata APIs.
918
+ const SEO_LINE =
919
+ /<title|<meta\b|<link\b[^>]*\brel=|canonical|robots|hreflang|noindex|ld\+json|sitemap|og:|twitter:|generateMetadata|\bmetadata\s*[:=]|<Head\b|useHead|useSeoMeta|<h1\b/i;
920
+ /** True when the action touches what search engines read, for the review reminder. @param {any} action */
921
+ export function seoSensitive(action, cwd = process.cwd()) {
922
+ if (!action || typeof action.file !== "string" || !action.file) return false;
923
+ if (isRobotsFile(action.file) || isSitemapFile(action.file) || isRedirectFile(action.file)) return true;
924
+ if (action.kind === "delete") return !!deleteHit(action.file, cwd);
925
+ if (action.kind !== "edit") return false;
926
+ const { added, removed } = lineDiff(String(action.before ?? ""), String(action.after ?? ""));
927
+ return (
928
+ [...added, ...removed].some(l => SEO_LINE.test(l)) ||
929
+ (!!String(action.before ?? "").trim() && !String(action.after ?? "").trim() && isPageFile(action.file, cwd))
930
+ );
931
+ }