From 803dcad64d2dea9c93972322bff4de6a00611e93 Mon Sep 17 00:00:00 2001 From: "Craig C." Date: Fri, 27 Nov 2026 15:41:08 +0200 Subject: [PATCH] fix(dox): one permanent hop to each page, and search crawlers skip the `.md` twins and query URLs (DOX-G17, #559) - The Worker turns the assets binding's trailing-slash 307 into a 308, and the old-host 301 lands on the slash URL. The workers.dev copy answers X-Robots-Tag: noindex. - A new `rendered-links` gate, tier pr, fails a slashless page link that a mount renders at run time. The slash predicate moves to scripts/lib/page-links.mjs, shared with test:dist. - robots-policy.mjs checks the landing robots.txt against a policy table with robots-parser 3.0.1. deploy-smoke checks the live file, and its slash rows expect 308. - The Cloudflare runbook gains the Search Console steps and the pages to inspect again. --- apps/dox/package.json | 1 + apps/dox/scripts/build-utils/dist-base.ts | 30 +-- apps/dox/scripts/deploy-smoke.mjs | 131 ++++++++++++-- apps/dox/scripts/dist-base.test.ts | 15 +- apps/dox/scripts/gates/registry.mjs | 9 + apps/dox/scripts/gates/registry.test.ts | 10 +- apps/dox/scripts/lib/built-pages.mjs | 30 +++ apps/dox/scripts/lib/page-links.mjs | 52 ++++++ apps/dox/scripts/lib/page-links.test.ts | 65 +++++++ apps/dox/scripts/lib/table-pages.mjs | 29 +-- apps/dox/scripts/lib/widget-pages.mjs | 19 ++ apps/dox/scripts/lib/widget-pages.test.ts | 41 +++++ apps/dox/scripts/rendered-links.mjs | 69 +++++++ apps/dox/scripts/robots-policy.mjs | 162 +++++++++++++++++ apps/dox/scripts/robots-policy.test.ts | 86 +++++++++ apps/dox/src/assets-root/_headers | 5 + apps/dox/worker/index.test.ts | 107 +++++++++-- apps/dox/worker/index.ts | 31 +++- context/dox/built/tier-0-1-site.md | 23 ++- context/dox/built/tier-2-gates.md | 3 +- context/dox/cloudflare-runbook.md | 73 ++++++++ context/dox/specs/dox-g17/index.md | 127 +++++++++++++ .../dox/specs/dox-g17/s1-permanent-slash.md | 171 ++++++++++++++++++ .../dox/specs/dox-g17/s2-rendered-links.md | 108 +++++++++++ .../specs/dox-g17/s3-search-crawlers-skip.md | 163 +++++++++++++++++ .../dox-g17/s4-triage-and-search-console.md | 109 +++++++++++ context/dox/specs/index.md | 1 + context/dox/tracker.md | 1 + pnpm-lock.yaml | 9 + 29 files changed, 1591 insertions(+), 89 deletions(-) create mode 100644 apps/dox/scripts/lib/built-pages.mjs create mode 100644 apps/dox/scripts/lib/page-links.mjs create mode 100644 apps/dox/scripts/lib/page-links.test.ts create mode 100644 apps/dox/scripts/lib/widget-pages.mjs create mode 100644 apps/dox/scripts/lib/widget-pages.test.ts create mode 100644 apps/dox/scripts/rendered-links.mjs create mode 100644 apps/dox/scripts/robots-policy.mjs create mode 100644 apps/dox/scripts/robots-policy.test.ts create mode 100644 context/dox/specs/dox-g17/index.md create mode 100644 context/dox/specs/dox-g17/s1-permanent-slash.md create mode 100644 context/dox/specs/dox-g17/s2-rendered-links.md create mode 100644 context/dox/specs/dox-g17/s3-search-crawlers-skip.md create mode 100644 context/dox/specs/dox-g17/s4-triage-and-search-console.md diff --git a/apps/dox/package.json b/apps/dox/package.json index 6a148a09d..ebeaf722f 100644 --- a/apps/dox/package.json +++ b/apps/dox/package.json @@ -114,6 +114,7 @@ "pngjs": "7.0.0", "postcss": "8.5.31", "postcss-html": "1.8.1", + "robots-parser": "3.0.1", "stylelint": "17.16.0", "stylelint-config-standard": "40.0.0", "stylelint-declaration-strict-value": "1.12.1", diff --git a/apps/dox/scripts/build-utils/dist-base.ts b/apps/dox/scripts/build-utils/dist-base.ts index ace02e0b5..f52f5de6c 100644 --- a/apps/dox/scripts/build-utils/dist-base.ts +++ b/apps/dox/scripts/build-utils/dist-base.ts @@ -8,23 +8,22 @@ * Every scanner is pure: text in, failures out. None reads the file system. */ +import { + BASE, + isPageLinkWithoutSlash, + ORIGIN, + underBase, +} from "../lib/page-links.mjs"; + export interface BaseFailure { value: string; where: string; } -const ORIGIN = "https://northguild.dev"; -const BASE = "/gmt"; /** The header's NorthGuild link (#424); equal to `LANDING_URL` in `src/lib/site.ts`. */ export const LANDING = `${ORIGIN}/`; const LEGACY_HOST = "gmt-dox.northguild.workers.dev"; -/** `/gmt` or `/gmt/…`, and not a doubled `/gmt/gmt`. */ -function underBase(pathname: string): boolean { - if (pathname !== BASE && !pathname.startsWith(`${BASE}/`)) return false; - return !(pathname === `${BASE}/gmt` || pathname.startsWith(`${BASE}/gmt/`)); -} - /** * The reason a URL fails the rule, or `null` when it passes. Relative URLs, hashes, non-http * schemes and other hosts pass. @@ -144,21 +143,6 @@ export function badUrlsInHtml(html: string): BaseFailure[] { return dedupe(out); } -/** - * Whether a URL links to a Dox page without the trailing slash: root-absolute or on the site's - * origin, under `/gmt`, and with no dot in its last path segment (a dot names a file). - */ -function isPageLinkWithoutSlash(value: string): boolean { - let pathname: string; - if (value.startsWith("/") && !value.startsWith("//")) - pathname = value.split(/[?#]/)[0]; - else if (value.startsWith(`${ORIGIN}/`)) - pathname = value.slice(ORIGIN.length).split(/[?#]/)[0]; - else return false; - if (!underBase(pathname) || pathname.endsWith("/")) return false; - return !pathname.slice(pathname.lastIndexOf("/") + 1).includes("."); -} - /** * Every link (`` or `` href) to a Dox page that lacks the trailing slash the static host * serves the page at. Such a link costs a redirect, and search engines crawl and report the page diff --git a/apps/dox/scripts/deploy-smoke.mjs b/apps/dox/scripts/deploy-smoke.mjs index 29874ad90..b446ddffc 100644 --- a/apps/dox/scripts/deploy-smoke.mjs +++ b/apps/dox/scripts/deploy-smoke.mjs @@ -6,8 +6,10 @@ * * node apps/dox/scripts/deploy-smoke.mjs * - * Node 22+, no dependencies. Rows 26-29 (the landing page, the zone and the landing's - * robots.txt) belong to the landing repo's deploy and are checked by hand after a deploy. + * Node 22+, one devDependency (`robots-parser`, through `robots-policy.mjs`). Rows 26-28 (the + * landing page and the zone) belong to the landing repo's deploy and are checked by hand after a + * deploy. The landing's robots.txt is checked here ("robots policy") against the table in + * `robots-policy.mjs`. * * Requests go through `node:https`, not `fetch`: undici adds its own `sec-fetch-mode` * header, and the (N) rows must send exactly the headers a browser following a link sends. @@ -18,11 +20,14 @@ * * `DOX_SMOKE_LOCAL=http://localhost:8787` runs only the crawl-hygiene rows (`_headers` and the 404 * page) against a local `wrangler dev` that serves the built `dist`. The redirect rows need the - * live hosts and are skipped. + * live hosts and are skipped, the slash rows (6a, 6b) among them, which check the 308 the Worker + * makes from the assets binding's 307. The workers.dev + * `noindex` rows (6c) match a host name, which `localhost` is not. */ import { readFileSync } from "node:fs"; import { request as httpRequest } from "node:http"; import { request as httpsRequest } from "node:https"; +import { checkRobots } from "./robots-policy.mjs"; const LOCAL = process.env.DOX_SMOKE_LOCAL?.replace(/\/$/, ""); const ND = LOCAL ?? "https://northguild.dev"; @@ -122,6 +127,40 @@ const hop = (rows, label, from, to, { headers, final = 200 } = {}) => steps: [{ status: 301, location: to }, { status: final }], }); +/** + * A row for a page path without its slash: one permanent hop (308) to the slash URL with the query + * kept, then the page. The one place the expected status of that hop is written. + */ +const slashHop = (rows, label, url) => { + const at = url.search(/[?#]/); + const path = at === -1 ? url : url.slice(0, at); + rows.push({ + label, + url, + steps: [ + { + status: 308, + location: `${path}/${at === -1 ? "" : url.slice(at)}`, + }, + { status: 200 }, + ], + }); +}; + +/** + * The first page URL in the live sitemap that matches `re`: the first `` of the index, then the + * first match in that child sitemap. `undefined` when there is none, so a row can fail by name. + */ +async function firstSitemapUrl(re) { + const index = await send("GET", `${ND}/gmt/sitemap-index.xml`); + const child = /([^<]+)<\/loc>/.exec(index.body)?.[1]; + if (child === undefined) return undefined; + const sitemap = await send("GET", child); + return [...sitemap.body.matchAll(/([^<]+)<\/loc>/g)] + .map((m) => m[1]) + .find((loc) => re.test(loc)); +} + /** The meta tag that asks a crawler not to index a page. */ const NOINDEX_META = /]*name="robots"[^>]*content="[^"]*noindex/i; @@ -296,15 +335,57 @@ async function buildRows() { } hop(rows, "3", `${WD}/reference/`, `${ND}/gmt/reference/`); - add({ - label: "6", - url: `${WD}/reference`, - steps: [ - { status: 301, location: `${ND}/gmt/reference` }, - { status: 307, location: `${ND}/gmt/reference/` }, - { status: 200 }, - ], - }); + // The old host adds the page slash in its one 301, so an old link never chains. + hop(rows, "6", `${WD}/reference`, `${ND}/gmt/reference/`); + slashHop(rows, "6a", `${ND}/gmt/reference`); + // A function page from the live sitemap, never a name typed here: pages get renamed. + const fnPage = await firstSitemapUrl( + /\/gmt\/reference\/[^/]+\/[^/]+\/[^/]+\/$/, + ); + if (fnPage === undefined) { + add({ + label: "6b", + url: `${ND}/gmt/sitemap-index.xml`, + steps: [{ status: 200, check: () => "no function page in the sitemap" }], + }); + } else { + const slashless = fnPage.slice(0, -1); + slashHop(rows, "6b", `${slashless}?a=1`); + hop( + rows, + "6d", + `${WD}${slashless.slice(`${ND}/gmt`.length)}?a=1`, + `${fnPage}?a=1`, + ); + // The old host serves the same pages under `/gmt/`; only `northguild.dev` may be indexed. + // `wrangler dev` serves on `localhost`, where the host rule cannot match, so these are live only. + add({ + label: "6c workers.dev noindex", + url: `${WD}${fnPage.slice(ND.length)}`, + steps: [ + { + status: 200, + check: ({ headers }) => + String(headers["x-robots-tag"] ?? "").includes("noindex") + ? undefined + : `x-robots-tag is ${headers["x-robots-tag"]}, not noindex`, + }, + ], + }); + add({ + label: "6c canonical host", + url: fnPage, + steps: [ + { + status: 200, + check: ({ headers }) => + headers["x-robots-tag"] === undefined + ? undefined + : `x-robots-tag is ${headers["x-robots-tag"]}`, + }, + ], + }); + } hop(rows, "7 install.md", `${WD}/install.md`, `${ND}/gmt/install.md`); hop(rows, "7 llms.txt", `${WD}/llms.txt`, `${ND}/gmt/llms.txt`); hop( @@ -343,6 +424,22 @@ async function buildRows() { url: `${WD}/robots.txt`, steps: [{ status: 301, location: `${ND}/robots.txt` }], }); + add({ + label: "robots policy", + url: `${ND}/robots.txt`, + steps: [ + { + status: 200, + type: "text/plain", + check: ({ body }) => { + const failures = checkRobots(body); + return failures.length === 0 + ? undefined + : failures.map((f) => `${f.value}: ${f.where}`).join("; "); + }, + }, + ], + }); add({ label: "13", url: `${WD}/reference/duty.md`, @@ -352,13 +449,13 @@ async function buildRows() { { status: 200 }, ], }); - // A moved page without its slash: no dot and no slash, so the Worker runs and hands it to the - // assets binding, and only `_redirects` stands between it and the 404 page. + // A moved page without its slash: the old host's 301 adds the slash, and only `_redirects` + // stands between that URL and the 404 page. add({ label: "13 no slash", url: `${WD}/reference/duty`, steps: [ - { status: 301, location: `${ND}/gmt/reference/duty` }, + { status: 301, location: `${ND}/gmt/reference/duty/` }, { status: 301, location: `${ND}/gmt/reference/workforce/` }, { status: 200 }, ], @@ -411,7 +508,7 @@ async function buildRows() { url: `${ND}/gmt/nope`, headers, steps: [ - { status: 307, location: `${ND}/gmt/nope/`, optional: true }, + { status: 308, location: `${ND}/gmt/nope/`, optional: true }, { status: 404, type: "text/html" }, ], }); @@ -843,7 +940,7 @@ async function buildRows() { add({ label: "25", url: `${ND}/gmtx`, - steps: [{ status: 301, location: `${ND}/gmt/gmtx` }, { status: 404 }], + steps: [{ status: 301, location: `${ND}/gmt/gmtx/` }, { status: 404 }], }); add({ label: "30", diff --git a/apps/dox/scripts/dist-base.test.ts b/apps/dox/scripts/dist-base.test.ts index 2f3cda46f..58636877d 100644 --- a/apps/dox/scripts/dist-base.test.ts +++ b/apps/dox/scripts/dist-base.test.ts @@ -90,7 +90,20 @@ describe("the built site keeps the /gmt base", () => { .split("\n") .filter((line) => line !== "" && !/^\s/.test(line) && line[0] !== "#"); expect(paths.length).toBeGreaterThan(0); - expect(paths.filter((path) => !path.startsWith("/gmt/"))).toEqual([]); + // One absolute rule is allowed: the old host, which keeps its copy of the pages out of search. + const OLD_HOST = "https://gmt-dox.northguild.workers.dev"; + expect( + paths.filter((path) => !path.replace(OLD_HOST, "").startsWith("/gmt/")), + ).toEqual([]); + }); + + it("_headers keeps the old workers.dev host's /gmt/ pages out of search results", () => { + const b = built(); + if (b === null) return; + const headers = readFileSync(resolve(b.root, "_headers"), "utf8"); + expect(headers).toMatch( + /^https:\/\/gmt-dox\.northguild\.workers\.dev\/gmt\/\*\n\s+X-Robots-Tag: noindex$/m, + ); }); it("every file under _astro/ has a content hash in its name, so its immutable header is true", () => { diff --git a/apps/dox/scripts/gates/registry.mjs b/apps/dox/scripts/gates/registry.mjs index 1686cd99e..4a0bba64d 100644 --- a/apps/dox/scripts/gates/registry.mjs +++ b/apps/dox/scripts/gates/registry.mjs @@ -141,6 +141,15 @@ export const GATES = [ themes: false, needs: null, }, + { + id: "rendered-links", + script: "rendered-links.mjs", + tier: "pr", + browsers: ["chromium"], + fullBrowsers: ["chromium"], + themes: false, + needs: null, + }, { id: "frame-check", script: "frame-check.mjs", diff --git a/apps/dox/scripts/gates/registry.test.ts b/apps/dox/scripts/gates/registry.test.ts index 9aaf24884..6e6b9e510 100644 --- a/apps/dox/scripts/gates/registry.test.ts +++ b/apps/dox/scripts/gates/registry.test.ts @@ -40,6 +40,7 @@ describe("the gate registry", () => { "sound-check", "rail-stored-still", "canada-layout-check", + "rendered-links", "frame-check", "slides-check", "a11y-axe", @@ -78,10 +79,15 @@ describe("the gate registry", () => { }); // `a11y-tab-walk` lists a subset of the built pages, `table-fit` lists the built pages that hold a -// table and `plate-fit` lists the built tool pages, so +// table, `plate-fit` lists the built tool pages and `rendered-links` the pages that hold a widget, so // without `dist` each exits 2 before it reads a flag: its list fails, and its unknown-page case // passes for the wrong reason. -const LISTS_FROM_DIST = new Set(["a11y-tab-walk", "table-fit", "plate-fit"]); +const LISTS_FROM_DIST = new Set([ + "a11y-tab-walk", + "table-fit", + "plate-fit", + "rendered-links", +]); // Each gate answers the page contract without a browser: a JSON list of site paths, and an unknown // page is a usage error (exit 2), so a typo never passes as an empty run. diff --git a/apps/dox/scripts/lib/built-pages.mjs b/apps/dox/scripts/lib/built-pages.mjs new file mode 100644 index 000000000..39edffc09 --- /dev/null +++ b/apps/dox/scripts/lib/built-pages.mjs @@ -0,0 +1,30 @@ +/** + * The built pages whose HTML holds something. + * + * `listBuiltPages(distRoot, holds)` reads `/gmt/**\/index.html` and returns the site path + * (`/compare/behaviour/`, no `/gmt` prefix) of every page whose HTML `holds` accepts, sorted. The + * list is read from the build, never typed in, so a page that gains what the check looks for is + * covered without anyone adding it. `distRoot` is `apps/dox/dist`. `listTablePages` and + * `listWidgetPages` are two uses of it. + */ +import { readFileSync, readdirSync } from "node:fs"; +import path from "node:path"; + +export function listBuiltPages(distRoot, holds) { + const site = path.join(distRoot, "gmt"); + const out = []; + const walk = (dir, rel) => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.isDirectory()) { + walk(path.join(dir, entry.name), `${rel}${entry.name}/`); + } else if ( + entry.name === "index.html" && + holds(readFileSync(path.join(dir, entry.name), "utf8")) + ) { + out.push(rel); + } + } + }; + walk(site, "/"); + return out.sort(); +} diff --git a/apps/dox/scripts/lib/page-links.mjs b/apps/dox/scripts/lib/page-links.mjs new file mode 100644 index 000000000..420d731c4 --- /dev/null +++ b/apps/dox/scripts/lib/page-links.mjs @@ -0,0 +1,52 @@ +/** + * The rule for a link to a Dox page: it ends in a slash. + * + * The static host serves a page at `/gmt//`. A link without the slash costs a redirect, and a + * search engine crawls and reports the page under both URLs. The build scanners + * (`scripts/build-utils/dist-base.ts`) and the `rendered-links` gate (`scripts/rendered-links.mjs`) + * use this one predicate, so the two checks cannot disagree. + */ + +/** The site's origin; equal to `SITE_ORIGIN` in `src/lib/site.ts`. */ +export const ORIGIN = "https://northguild.dev"; +/** The site's base path; equal to `SITE_BASE` in `src/lib/site.ts`. */ +export const BASE = "/gmt"; + +/** `/gmt` or `/gmt/…`, and not a doubled `/gmt/gmt`. */ +export function underBase(pathname) { + if (pathname !== BASE && !pathname.startsWith(`${BASE}/`)) return false; + return !(pathname === `${BASE}/gmt` || pathname.startsWith(`${BASE}/gmt/`)); +} + +/** + * Whether a URL links to a Dox page without the trailing slash: root-absolute or on the site's + * origin, under `/gmt`, and with no dot in its last path segment (a dot names a file). + */ +export function isPageLinkWithoutSlash(value) { + let pathname; + if (value.startsWith("/") && !value.startsWith("//")) + pathname = value.split(/[?#]/)[0]; + else if (value.startsWith(`${ORIGIN}/`)) + pathname = value.slice(ORIGIN.length).split(/[?#]/)[0]; + else return false; + if (!underBase(pathname) || pathname.endsWith("/")) return false; + return !pathname.slice(pathname.lastIndexOf("/") + 1).includes("."); +} + +/** + * An `href` attribute as written, made a root-absolute path when it is relative (`./x`, `../x`, `x`, + * `?q`) by resolving it against the URL of the page that holds it. A root-absolute, protocol- + * relative, absolute-URL or hash-only value is returned as it is. + */ +export function resolveHref(value, pageUrl) { + if ( + value === "" || + value.startsWith("/") || + value.startsWith("#") || + /^[a-z][a-z0-9+.-]*:/i.test(value) + ) { + return value; + } + const resolved = new URL(value, pageUrl); + return resolved.pathname + resolved.search + resolved.hash; +} diff --git a/apps/dox/scripts/lib/page-links.test.ts b/apps/dox/scripts/lib/page-links.test.ts new file mode 100644 index 000000000..22a6f1203 --- /dev/null +++ b/apps/dox/scripts/lib/page-links.test.ts @@ -0,0 +1,65 @@ +import { + isPageLinkWithoutSlash, + resolveHref, + underBase, +} from "./page-links.mjs"; + +describe("isPageLinkWithoutSlash", () => { + it.each([ + ["/gmt/reference", true], + ["/gmt", true], + ["/gmt/reference/", false], + ["/gmt/llms.txt", false], + ["/gmt/reference/x.md", false], + ["https://northguild.dev/gmt/tools/x?w=1#a", true], + ["https://northguild.dev/gmt/tools/x/?w=1", false], + ["https://northguild.dev/", false], + ["/other", false], + ["//cdn/x", false], + ["https://example.com/gmt/x", false], + ["#top", false], + ["/gmt/gmt/x", false], + ])("%s -> %s", (value, expected) => { + expect(isPageLinkWithoutSlash(value)).toBe(expected); + }); +}); + +describe("underBase", () => { + it("is the base and what sits under it, never a doubled base", () => { + expect(underBase("/gmt")).toBe(true); + expect(underBase("/gmt/x")).toBe(true); + expect(underBase("/gmtx")).toBe(false); + expect(underBase("/gmt/gmt")).toBe(false); + }); +}); + +describe("resolveHref", () => { + const page = "http://127.0.0.1:4321/gmt/tools/dst-inspector/"; + + it("resolves a relative value against the page, keeping query and hash", () => { + expect(resolveHref("./x", page)).toBe("/gmt/tools/dst-inspector/x"); + expect(resolveHref("../x", page)).toBe("/gmt/tools/x"); + expect(resolveHref("x?a=1#h", page)).toBe( + "/gmt/tools/dst-inspector/x?a=1#h", + ); + expect(resolveHref("?w=1", page)).toBe("/gmt/tools/dst-inspector/?w=1"); + }); + + it("leaves a root-absolute, protocol-relative, absolute or hash value as written", () => { + for (const value of [ + "/gmt/x", + "//cdn/x", + "https://northguild.dev/gmt/x", + "mailto:a@b.c", + "#top", + "", + ]) { + expect(resolveHref(value, page)).toBe(value); + } + }); + + it("lets the predicate judge a resolved relative link", () => { + expect(isPageLinkWithoutSlash(resolveHref("../x", page))).toBe(true); + expect(isPageLinkWithoutSlash(resolveHref("../x/", page))).toBe(false); + }); +}); diff --git a/apps/dox/scripts/lib/table-pages.mjs b/apps/dox/scripts/lib/table-pages.mjs index 22f800714..a078d6df9 100644 --- a/apps/dox/scripts/lib/table-pages.mjs +++ b/apps/dox/scripts/lib/table-pages.mjs @@ -1,29 +1,10 @@ /** * The built pages that hold a table. * - * `listTablePages(distRoot)` reads `/gmt/**\/index.html` and returns the site path - * (`/compare/behaviour/`, no `/gmt` prefix) of every page whose HTML has a ` { - for (const entry of readdirSync(dir, { withFileTypes: true })) { - if (entry.isDirectory()) { - walk(path.join(dir, entry.name), `${rel}${entry.name}/`); - } else if ( - entry.name === "index.html" && - readFileSync(path.join(dir, entry.name), "utf8").includes(" + listBuiltPages(distRoot, (html) => html.includes("]*\sdata-widget=/i; +/** Script and style bodies and comments: text, never markup. */ +const NOT_MARKUP = /<(script|style)\b[\s\S]*?<\/\1>|/gi; + +export const listWidgetPages = (distRoot) => + listBuiltPages(distRoot, (html) => + WIDGET_TAG.test(html.replace(NOT_MARKUP, "")), + ); diff --git a/apps/dox/scripts/lib/widget-pages.test.ts b/apps/dox/scripts/lib/widget-pages.test.ts new file mode 100644 index 000000000..d2b1cda57 --- /dev/null +++ b/apps/dox/scripts/lib/widget-pages.test.ts @@ -0,0 +1,41 @@ +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { listWidgetPages } from "./widget-pages.mjs"; + +let dist: string; + +function page(slug: string, html: string) { + const dir = path.join(dist, "gmt", slug); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, "index.html"), html); +} + +beforeEach(() => { + dist = mkdtempSync(path.join(tmpdir(), "widget-pages-")); +}); + +afterEach(() => { + rmSync(dist, { recursive: true, force: true }); +}); + +describe("listWidgetPages", () => { + it("lists only the pages whose markup holds a data-widget element", () => { + page("tools/a", '
'); + page("tools/b", "

no widget

"); + page( + "tools/c", + '

data-widget="c"

', + ); + expect(listWidgetPages(dist)).toEqual(["/tools/a/"]); + }); + + it("returns the paths sorted and is empty for a dist with no site", () => { + page("z", ''); + page("a", ''); + expect(listWidgetPages(dist)).toEqual(["/a/", "/z/"]); + rmSync(path.join(dist, "gmt"), { recursive: true }); + mkdirSync(path.join(dist, "gmt")); + expect(listWidgetPages(dist)).toEqual([]); + }); +}); diff --git a/apps/dox/scripts/rendered-links.mjs b/apps/dox/scripts/rendered-links.mjs new file mode 100644 index 000000000..5795fd39a --- /dev/null +++ b/apps/dox/scripts/rendered-links.mjs @@ -0,0 +1,69 @@ +#!/usr/bin/env node +/** + * Rendered-links gate: every link a built page holds once its widgets have mounted ends in the page + * slash. `test:dist` reads the built HTML; a widget adds links at run time, and a search engine + * that renders the page follows them. A link without the slash costs a redirect and is crawled + * under two URLs. + * + * The page list is every built page with a `data-widget` element (`listWidgetPages`). On each page, + * at 1440 x 900, the gate reads the `href` attribute of every `a[href]` and `area[href]` as written + * (a relative value is resolved against the page, never read as `.href`) and files a finding for + * each one `isPageLinkWithoutSlash` fails. Links that appear only after a click are out of scope: + * each tool's own tests drive its states. + * + * Usage (a built site served, as `pnpm --filter dox gates --only rendered-links` does): + * node scripts/rendered-links.mjs [--base http://127.0.0.1:48291/gmt] [--browsers chromium] + * [--pages /a/,/b/] [--list-pages] + * + * The runner's contract is `lib/a11y-sweep.mjs`'s: `--list-pages` prints the pages and exits (2 when + * `dist` is missing); with `GATE_REPORT` set every bad link is a finding. Exit 0 pass, 1 any + * finding or nothing measured, 2 usage. + */ +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { distPages, parseSweep, sweep } from "./lib/a11y-sweep.mjs"; +import { isPageLinkWithoutSlash, resolveHref } from "./lib/page-links.mjs"; +import { listWidgetPages } from "./lib/widget-pages.mjs"; + +const GATE = "rendered-links"; +const DIST = path.join( + path.dirname(fileURLToPath(import.meta.url)), + "..", + "dist", +); + +// `distPages` stops with exit 2 when `dist` is not built; the list itself is the widget pages. +distPages(GATE); +const run = await parseSweep({ + gate: GATE, + pages: listWidgetPages(DIST), + defaults: { widths: "1440" }, +}); + +/** Every link of the page: its `href` as written, and the name of the widget that holds it. */ +function readLinks(page) { + return page.evaluate(() => + [...document.querySelectorAll("a[href], area[href]")].map((el) => ({ + href: el.getAttribute("href") ?? "", + widget: + el.closest("[data-widget]")?.getAttribute("data-widget") ?? "page", + })), + ); +} + +await sweep({ + gate: GATE, + run, + check: async ({ page }) => { + await page.waitForSelector("[data-widget]", { state: "attached" }); + const pageUrl = page.url(); + return (await readLinks(page)) + .filter(({ href }) => isPageLinkWithoutSlash(resolveHref(href, pageUrl))) + .map(({ href, widget }) => ({ + rule: "page-link-without-slash", + target: "page", + selector: widget, + message: `${href} (in ${widget}) is a page link without its trailing slash`, + })); + }, +}); diff --git a/apps/dox/scripts/robots-policy.mjs b/apps/dox/scripts/robots-policy.mjs new file mode 100644 index 000000000..7c4b97bce --- /dev/null +++ b/apps/dox/scripts/robots-policy.mjs @@ -0,0 +1,162 @@ +/** + * The crawl policy of https://northguild.dev/robots.txt, as data and a check. + * + * The file has two groups. `*` (with Applebot) leaves everything open except the API paths, so AI + * agents read the `.md` twins and `llms*.txt`. `Googlebot` and `Bingbot` have a group of their own + * that also skips the `.md` twins and every page URL with a query, which are crawls that never + * reach the index. A crawler with its own group ignores `*` entirely (RFC 9309 §2.2.1; Google, + * "Order of precedence for user agents"), so that group repeats every `*` rule and the + * `Content-Signal` line. Applebot follows the `Googlebot` group when no group names it (Apple, + * "About Applebot"), so the `*` group names it. + * + * Used by `deploy-smoke.mjs` (the live file) and `robots-policy.test.ts` (fixtures). + * Matching is `robots-parser`'s: groups, `*`, `$` and the longest match (RFC 9309 §2.2.2-2.2.3). + */ +import robotsParser from "robots-parser"; + +const ORIGIN = "https://northguild.dev"; + +const SEARCH = ["Googlebot", "Bingbot"]; +const OPEN = [ + "*", + "ClaudeBot", + "GPTBot", + "OAI-SearchBot", + "PerplexityBot", + "Applebot", +]; + +/** One `{ agent, path, allowed }` row per agent and path; `path` is under https://northguild.dev. */ +function rows(agents, paths, allowed) { + return agents.flatMap((agent) => + paths.map((path) => ({ agent, path, allowed })), + ); +} + +const blockedForSearch = [ + "/gmt/install.md", + "/gmt/reference/plain/calculate/addDays.md", + "/gmt/tools/zone-planner/?w=planner&wa=x", + "/gmt/tools/zone-planner/?tz=a,b&t=1", + "/gmt/?w=x", +]; +const allowedEverywhere = [ + "/gmt/llms.txt", + "/gmt/llms-full.txt", + "/gmt/", + "/gmt/reference/", + "/gmt/reference/plain/calculate/addDays/", + "/gmt/reference/gnss", + "/gmt/_astro/x.js", + "/gmt/og/x.png?v=1", + "/", + "/worktree/", +]; +const blockedEverywhere = ["/gmt/api/chat", "/api/x", "/mcp/x"]; + +export const ROBOTS_POLICY = [ + ...rows(SEARCH, blockedForSearch, false), + ...rows(OPEN, blockedForSearch, true), + ...rows([...SEARCH, ...OPEN], allowedEverywhere, true), + ...rows([...SEARCH, ...OPEN], blockedEverywhere, false), +]; + +/** The groups of a robots.txt: `{ agents, lines }`, where `lines` are the non-agent records. */ +function groupsOf(text) { + const groups = []; + let group; + let ruled = false; + for (const raw of text.split(/\r?\n/)) { + const line = raw.replace(/#.*$/, "").trim(); + const colon = line.indexOf(":"); + if (colon === -1) continue; + const field = line.slice(0, colon).trim().toLowerCase(); + const value = line.slice(colon + 1).trim(); + if (field === "user-agent") { + // Consecutive User-agent lines share a group; one after a rule opens the next (§2.2.1). + if (!group || ruled) { + group = { agents: [], lines: [] }; + groups.push(group); + ruled = false; + } + group.agents.push(value); + } else if (field === "sitemap") { + continue; + } else if (group) { + group.lines.push({ field, value }); + // A `Content-Signal` sits inside a group without ending it (§2.2.4). + if (field === "allow" || field === "disallow") ruled = true; + } + } + return groups; +} + +const named = (groups, agent) => + groups.some((g) => + g.agents.some((a) => a.toLowerCase() === agent.toLowerCase()), + ); + +/** + * Check a robots.txt body against the policy. Returns `{ value, where }` failures, empty when it + * holds: `value` is the offending row, line or group, `where` the reason. + */ +export function checkRobots(text) { + const failures = []; + const robots = robotsParser(`${ORIGIN}/robots.txt`, text); + const groups = groupsOf(text); + // Apple reads the `Googlebot` group when nothing names Applebot. + const appleFallsBack = !named(groups, "Applebot"); + + for (const { agent, path, allowed } of ROBOTS_POLICY) { + const asked = agent === "Applebot" && appleFallsBack ? "Googlebot" : agent; + const got = robots.isAllowed(`${ORIGIN}${path}`, asked); + if (got !== allowed) { + failures.push({ + value: `${agent} ${path}`, + where: `policy row does not hold: expected ${allowed ? "allowed" : "blocked"}, got ${got ? "allowed" : "blocked"}`, + }); + } + } + + const star = groups.find((g) => g.agents.includes("*")); + const signals = (g) => + g.lines.filter((l) => l.field === "content-signal").map((l) => l.value); + const disallows = (g) => + g.lines.filter((l) => l.field === "disallow").map((l) => l.value); + + if (!star) { + failures.push({ value: "*", where: "no `*` group" }); + return failures; + } + for (const g of groups) { + if (g === star) continue; + const label = g.agents.join(", "); + for (const signal of signals(star)) { + if (!signals(g).includes(signal)) { + failures.push({ + value: label, + where: `group lacks the \`*\` group's Content-Signal line: ${signal}`, + }); + } + } + for (const rule of disallows(star)) { + if (!disallows(g).includes(rule)) { + failures.push({ + value: label, + where: `group lacks the \`*\` group's Disallow: ${rule}`, + }); + } + } + } + for (const g of groups) { + for (const signal of signals(g)) { + if (!/\bai-train=yes\b/.test(signal)) { + failures.push({ + value: signal, + where: "Content-Signal without ai-train=yes", + }); + } + } + } + return failures; +} diff --git a/apps/dox/scripts/robots-policy.test.ts b/apps/dox/scripts/robots-policy.test.ts new file mode 100644 index 000000000..c27111b04 --- /dev/null +++ b/apps/dox/scripts/robots-policy.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from "vitest"; +import { checkRobots, ROBOTS_POLICY } from "./robots-policy.mjs"; + +const SIGNAL = "Content-Signal: search=yes, ai-input=yes, ai-train=yes"; +const API = ["Disallow: /api/", "Disallow: /mcp/", "Disallow: /gmt/api/"]; + +const GOOD = `User-agent: * +User-agent: Applebot +${SIGNAL} +Allow: / +${API.join("\n")} + +User-agent: Googlebot +User-agent: Bingbot +${SIGNAL} +Allow: / +${API.join("\n")} +Disallow: /gmt/*.md$ +Disallow: /gmt/? +Disallow: /gmt/*/? + +Sitemap: https://northguild.dev/sitemap-index.xml +Sitemap: https://northguild.dev/gmt/sitemap-index.xml +Sitemap: https://northguild.dev/worktree/sitemap-index.xml +`; + +const wheres = (text: string) => + checkRobots(text).map((f: { where: string }) => f.where); + +describe("checkRobots", () => { + it("passes the served file", () => { + expect(checkRobots(GOOD)).toEqual([]); + }); + + it("covers every agent and path of the policy", () => { + expect(ROBOTS_POLICY.length).toBeGreaterThan(100); + }); + + it("fails `.md` rules in `*`, which cuts off AI agents", () => { + const bad = GOOD.replace( + "Disallow: /gmt/api/\n\nUser-agent: Googlebot", + "Disallow: /gmt/api/\nDisallow: /gmt/*.md$\n\nUser-agent: Googlebot", + ); + const reasons = wheres(bad); + expect(reasons).toContain( + "policy row does not hold: expected allowed, got blocked", + ); + }); + + it("fails a Googlebot group without `Disallow: /api/`", () => { + const [star, rest] = GOOD.split("User-agent: Googlebot"); + const bad = `${star}User-agent: Googlebot${rest.replace("Disallow: /api/\n", "")}`; + expect(wheres(bad)).toContain( + "group lacks the `*` group's Disallow: /api/", + ); + }); + + it("fails a Googlebot group without `Content-Signal`", () => { + const [star, rest] = GOOD.split("User-agent: Googlebot"); + const bad = `${star}User-agent: Googlebot${rest.replace(`${SIGNAL}\n`, "")}`; + expect(wheres(bad)).toContain( + `group lacks the \`*\` group's Content-Signal line: ${SIGNAL.slice("Content-Signal: ".length)}`, + ); + }); + + it("fails `ai-train=no`", () => { + const bad = GOOD.replaceAll("ai-train=yes", "ai-train=no"); + expect(wheres(bad)).toContain("Content-Signal without ai-train=yes"); + }); + + it("fails when Applebot is not named, because it then follows the Googlebot group", () => { + const bad = GOOD.replace("User-agent: Applebot\n", ""); + const failures = checkRobots(bad); + expect(failures.map((f: { value: string }) => f.value)).toContain( + "Applebot /gmt/install.md", + ); + }); + + it("fails `Disallow: /gmt/*?`, which blocks the `?v=` png", () => { + const bad = GOOD.replace("Disallow: /gmt/*/?", "Disallow: /gmt/*?"); + const failures = checkRobots(bad); + expect(failures.map((f: { value: string }) => f.value)).toContain( + "Googlebot /gmt/og/x.png?v=1", + ); + }); +}); diff --git a/apps/dox/src/assets-root/_headers b/apps/dox/src/assets-root/_headers index 5892a59b0..648fa411b 100644 --- a/apps/dox/src/assets-root/_headers +++ b/apps/dox/src/assets-root/_headers @@ -12,3 +12,8 @@ # `llms.txt`, `llms-full.txt` and the per-namespace `llms.txt` files repeat the pages; they are for agents, not for a results page. /gmt/*.txt X-Robots-Tag: noindex + +# The old `workers.dev` host serves the same pages, because assets answer `/gmt/*` on every host. +# Only `northguild.dev` is for a results page, so this keeps the old host out of search results. +https://gmt-dox.northguild.workers.dev/gmt/* + X-Robots-Tag: noindex diff --git a/apps/dox/worker/index.test.ts b/apps/dox/worker/index.test.ts index e8921adf9..7f893002c 100644 --- a/apps/dox/worker/index.test.ts +++ b/apps/dox/worker/index.test.ts @@ -172,8 +172,9 @@ describe("worker entry — /api/chat", () => { }); }); -/** A fake `ASSETS` that serves a small fixture map by pathname and 404s the rest. - * It applies no `_redirects` and no `html_handling`. */ +/** A fake `ASSETS` that serves a small fixture map by pathname and 404s the rest. A path that is + * the folder of a served `/` page answers 307 with a relative Location and the query kept, + * as the live binding's `auto-trailing-slash` handling does. It applies no `_redirects`. */ function fixtureAssets(files: Record = {}) { const calls: string[] = []; return { @@ -187,10 +188,19 @@ function fixtureAssets(files: Record = {}) { ? input.href : input.url; calls.push(href); - const body = files[new URL(href).pathname]; - return body === undefined - ? new Response("Dox 404 page", { status: 404 }) - : new Response(body, { status: 200 }); + const { pathname, search } = new URL(href); + const body = files[pathname]; + if (body !== undefined) return new Response(body, { status: 200 }); + if (files[`${pathname}/`] !== undefined) { + return new Response(null, { + status: 307, + headers: { + location: `${pathname}/${search}`, + "cache-control": "public, max-age=0, must-revalidate", + }, + }); + } + return new Response("Dox 404 page", { status: 404 }); }, }, }; @@ -227,7 +237,17 @@ describe("worker entry — the legacy host (matrix rows 1-17, 31-33)", () => { "/guides/concepts/dst-disambiguation/", "https://northguild.dev/gmt/guides/concepts/dst-disambiguation/", ], - ["row 6", "/reference", "https://northguild.dev/gmt/reference"], + ["row 6", "/reference", "https://northguild.dev/gmt/reference/"], + [ + "row 6d", + "/reference/types/RoundingOptions?a=1", + "https://northguild.dev/gmt/reference/types/RoundingOptions/?a=1", + ], + [ + "row 6e: a dev key is dropped", + "/reference?key=k&a=1", + "https://northguild.dev/gmt/reference/?a=1", + ], [ "row 7 install.md", "/install.md", @@ -388,15 +408,76 @@ describe("worker entry — northguild.dev/gmt (matrix rows 19-25, 34)", () => { expect(assets.calls).toEqual(["https://northguild.dev/gmt/nope/"]); }); - it("hands a page path to the assets binding untouched, base included", async () => { + it("a page path without its slash is a 308 to the slash URL, the request handed on untouched", async () => { + const assets = fixtureAssets({ "/gmt/reference/": "page" }); + const response = await worker.fetch( + nd("/gmt/reference"), + makeEnv({ ASSETS: assets.binding }), + ); + expect(response.status).toBe(308); + expect(response.headers.get("location")).toBe("/gmt/reference/"); + expect(response.headers.get("cache-control")).toBe( + "public, max-age=0, must-revalidate", + ); + expect(assets.calls).toEqual(["https://northguild.dev/gmt/reference"]); + }); + + it("keeps the query on the 308, and answers HEAD like GET", async () => { + const assets = fixtureAssets({ + "/gmt/reference/duration/calculate/totalDuration/": "page", + }); + const path = "/gmt/reference/duration/calculate/totalDuration"; + const get = await worker.fetch( + nd(`${path}?a=1`), + makeEnv({ ASSETS: assets.binding }), + ); + expect(get.status).toBe(308); + expect(get.headers.get("location")).toBe(`${path}/?a=1`); + const head = await worker.fetch( + nd("/gmt/reference", { method: "HEAD" }), + makeEnv({ + ASSETS: fixtureAssets({ "/gmt/reference/": "page" }).binding, + }), + ); + expect(head.status).toBe(308); + }); + + it("passes a 307 that is not the same path plus a slash through as a 307", async () => { + for (const location of [ + "/gmt/other/", + "https://example.com/gmt/reference/", + "/gmt/reference/?b=2", + ]) { + const response = await worker.fetch( + nd("/gmt/reference?a=1"), + makeEnv({ + ASSETS: { + fetch: async () => + new Response(null, { status: 307, headers: { location } }), + }, + }), + ); + expect(response.status).toBe(307); + expect(response.headers.get("location")).toBe(location); + } + }); + + it("passes a 200 from the binding through unchanged", async () => { const assets = fixtureAssets({ "/gmt/reference": "page" }); - const request = nd("/gmt/reference"); const response = await worker.fetch( - request, + nd("/gmt/reference"), makeEnv({ ASSETS: assets.binding }), ); expect(response.status).toBe(200); - expect(assets.calls).toEqual(["https://northguild.dev/gmt/reference"]); + expect(await response.text()).toBe("page"); + }); + + it("a missing page without its slash is the binding's own 404, never a 308", async () => { + const response = await worker.fetch( + nd("/gmt/nope"), + makeEnv({ ASSETS: fixtureAssets().binding }), + ); + expect(response.status).toBe(404); }); it("row 22: GET /gmt/api/brains is 200 JSON", async () => { @@ -459,11 +540,11 @@ describe("worker entry — northguild.dev/gmt (matrix rows 19-25, 34)", () => { expect(next.headers.get("location")).toBe("https://northguild.dev/gmt/"); }); - it("row 25: /gmtx is not under the base; it is a 301 to /gmt/gmtx", async () => { + it("row 25: /gmtx is not under the base; it is a 301 to /gmt/gmtx/", async () => { const response = await worker.fetch(nd("/gmtx"), makeEnv()); expect(response.status).toBe(301); expect(response.headers.get("location")).toBe( - "https://northguild.dev/gmt/gmtx", + "https://northguild.dev/gmt/gmtx/", ); }); diff --git a/apps/dox/worker/index.ts b/apps/dox/worker/index.ts index e8337f9f1..449abfcc5 100644 --- a/apps/dox/worker/index.ts +++ b/apps/dox/worker/index.ts @@ -7,6 +7,7 @@ import { SITE_URL, isUnderBase, stripBase, + withPageSlash, } from "../src/lib/site"; import { brainsPayload } from "./brains-payload"; import { getUnixNow } from "@northguild/gmt/unix/get"; @@ -248,6 +249,27 @@ function redirect(location: string): Response { return new Response(null, { status: 301, headers: { location } }); } +/** + * The assets binding answers a page path without its slash with a 307, and the code cannot be set. + * A 307 is temporary, so a search engine may keep the slashless URL as the page's canonical. This + * turns that one hop into a 308, which is permanent (RFC 9110 §15.4.9). Any other response, and a + * 307 that goes anywhere but the same path plus `/` with the same query, is returned as it is. + */ +function permanentSlash(res: Response, url: URL): Response { + if (res.status !== 307) return res; + const location = res.headers.get("location"); + if (location === null) return res; + const target = new URL(location, url); + if ( + target.origin !== url.origin || + target.pathname !== `${url.pathname}/` || + target.search !== url.search + ) { + return res; + } + return new Response(res.body, { status: 308, headers: res.headers }); +} + /* * Branches are by path, never by hostname, so `wrangler dev` runs the code * production runs. @@ -256,7 +278,8 @@ function redirect(location: string): Response { * The two API routes are served in place — a 301 turns a `fetch` POST into * a GET, and the hop to another origin has no CORS, so a tab opened before * the move would lose its chat. Everything else is a 301 into the base. - * A `key` is dropped from the query, never carried to a page URL. + * A `key` is dropped from the query, never carried to a page URL. The 301 adds the page + * slash, so an old link lands in one hop. * 2. The dev key, anywhere under the base (`/gmt` included). * 3. Exactly `/gmt`: a 301 to `/gmt/`. * 4. Under the base: the API, then the assets binding. @@ -279,7 +302,7 @@ export default { .split("&") .filter((pair) => pair !== "" && !/^key(?:=|$)/.test(pair)); const search = kept.length > 0 ? `?${kept.join("&")}` : ""; - return redirect(`${SITE_URL}${url.pathname}${search}`); + return redirect(withPageSlash(`${SITE_URL}${url.pathname}${search}`)); } // Ahead of the `/gmt` branch: `/gmt?key=` would otherwise be a 301 to the @@ -298,7 +321,7 @@ export default { // Only a page path without its slash, or a missing extension-less path, // gets here. Assets mirror the full path (`dist/gmt/…`), `html_handling` // adds the slash and `404-page` finds `dist/gmt/404.html`. The request - // is passed on unmodified. - return env.ASSETS.fetch(request); + // is passed on unmodified; the slash hop is made permanent here. + return permanentSlash(await env.ASSETS.fetch(request), url); }, }; diff --git a/context/dox/built/tier-0-1-site.md b/context/dox/built/tier-0-1-site.md index 45cbf2de6..34d8886b2 100644 --- a/context/dox/built/tier-0-1-site.md +++ b/context/dox/built/tier-0-1-site.md @@ -33,16 +33,29 @@ Rules, traps and runbooks for the site shell. Index: [index.md](index.md). - **Worker order** under the base: `?key=` dev exchange, 301 from bare `/gmt` to `/gmt/`, `/gmt/api/*`, then `ASSETS`. On the legacy `workers.dev` host every path 301s to `northguild.dev/gmt…` except `/api/brains` and `/api/chat` (a redirect turns a POST into a GET). + That 301 adds the page slash (`withPageSlash`), so an old link lands in one hop; a path with a + dot keeps its form. +- **A page path without its slash answers 308** to the slash URL, query kept. The assets binding's + `auto-trailing-slash` handling answers 307 and its code cannot be set; the Worker's + `permanentSlash` turns that one hop into a 308, because a permanent redirect is the canonical + signal Google honours (RFC 9110 §15.4.9). It changes only a 307 to the same path plus `/` with + the same query, so a missing page stays a 404. +- **The `workers.dev` host serves its `/gmt/` pages with `X-Robots-Tag: noindex`** (an absolute + host rule in `_headers`), because assets answer them there too and only `northguild.dev` may be + indexed. The host stays on for the 301s above. - **`_redirects` and `_headers`** must sit at the assets root. The generator writes `src/generated/_redirects`; `src/assets-root/_headers` is tracked; the `astro:build:done` hook in - `src/lib/copy-redirects.ts` copies both to `dist/`. Every `_headers` rule sits under `/gmt/` - (`scripts/dist-base.test.ts`). Cloudflare serves assets before the Worker, so these rules set + `src/lib/copy-redirects.ts` copies both to `dist/`. Every `_headers` rule sits under `/gmt/`, + the `workers.dev` host rule included (`scripts/dist-base.test.ts`). Cloudflare serves assets before the Worker, so these rules set headers: `/gmt/_astro/*` is `immutable` (the test fails on a file there without a content hash); `/gmt/*.md` and `/gmt/*.txt` are `X-Robots-Tag: noindex` (the test fails on any `.txt` other than `llms.txt` and `llms-full.txt`). - `scripts/deploy-smoke.mjs` checks the redirect matrix and crawl rows after each deploy. `DOX_SMOKE_LOCAL=http://localhost:8787` runs only the crawl rows against `wrangler dev`. -- `robots.txt` is served by the landing Worker. Zone and dashboard setup is in +- `robots.txt` is served by the landing Worker. Googlebot and Bingbot have a group of their own that + skips the `.md` twins and page URLs with a query; every other agent reads them. + `scripts/robots-policy.mjs` holds the policy table, and `deploy-smoke` checks the live file + against it. Zone and dashboard setup is in [`context/dox/cloudflare-runbook.md`](../cloudflare-runbook.md). - Web Analytics: the Cloudflare beacon loads from `src/components/Head.astro` in production only. Automatic injection stays off, so it is never loaded twice. @@ -61,7 +74,9 @@ Rules, traps and runbooks for the site shell. Index: [index.md](index.md). - **Page links end in `/`.** `rehype-base-links` adds the slash to every page link (an `href` whose last segment has no dot); file links keep their form. A component that builds an `href` uses `pageHref` from `site.ts`. `pageLinksWithoutSlash` and `pageLinksWithoutSlashInMarkdown` - in `dist-base.ts` fail `test:dist`. + in `dist-base.ts` fail `test:dist`. They share one predicate, `isPageLinkWithoutSlash`, with + `resolveHref` for relative values, in `scripts/lib/page-links.mjs`. The `rendered-links` gate + runs the same predicate over the links widgets render at run time. - The NorthGuild mark in the header links to `LANDING_URL`; the dist guard allows exactly that URL. ## Head tags and share cards diff --git a/context/dox/built/tier-2-gates.md b/context/dox/built/tier-2-gates.md index 4917cee25..9374eedf6 100644 --- a/context/dox/built/tier-2-gates.md +++ b/context/dox/built/tier-2-gates.md @@ -15,6 +15,7 @@ Part of [built/index.md](index.md). Operator steps (run, baseline, weekly sweep, - `a11y-media` proves `prefers-contrast` applied before reading the border: a probe property under `@media (prefers-contrast: more)` must read `1`, mid-page and in a fresh context with `contrast: "more"`. An unset probe is `emulation-not-applied` (the engine, not the page); a set probe with a weak border token is `contrast-border-token`. - `scripts/html-diff.mjs` compares built widget markup (a changed widget, a changed page around it, a new widget page with no baseline). `visual:diff` is the pixel gate. `html-diff.mjs` finds a widget root with or without `not-content`. - `frame-check` (`scripts/frame-check.mjs`, tier `pr`, three engines) serves `dist` itself and checks at 1440 and 390 px: the `/install/` code frame corners, each `/upstream/` card head's icon and badge within 2 px of the title's first-line middle, and Markdown list dashes and ticks within 2 px of the first-line middle (no component list item has a dash). A page with nothing to measure fails. +- `rendered-links` (`scripts/rendered-links.mjs`, tier `pr`, Chromium, one theme) opens every built page with a `data-widget` element (`listWidgetPages` in `scripts/lib/widget-pages.mjs`, a use of the `listBuiltPages` walker in `scripts/lib/built-pages.mjs` that `listTablePages` shares, read from `dist`, never a fixed list) at 1440 x 900, waits for a widget root and `settle`, then reads the `href` attribute of every `a[href]` and `area[href]` as written. A relative value is resolved against the page with `resolveHref`, and `isPageLinkWithoutSlash` (`scripts/lib/page-links.mjs`, the predicate `test:dist` uses) judges it. Rule `page-link-without-slash` names the page, the value and the widget that holds the link; rule `check-crashed` is a page that would not load. A run that measures no page fails. Links that appear only after a click are left to each tool's own tests. Takes `--base`, `--browsers`, `--pages`, `--list-pages` and `--shard /`. - `table-fit` (`scripts/table-fit.mjs`, tier `weekly`, three engines) opens every built page with a `` open and every tab shown. It fails a scroll box wider than it shows; a table with no scroll box fails against its block and against `main`'s content box and by `scrollWidth` against `clientWidth`. Rule `table-scrolls`. `measureCells` (`scripts/lib/cell-overflow.mjs`, 1440 and a fresh 390 px load) fails a cell that is too small for its content or whose text reaches more than 1.5 px past it (rule `cell-overflows`); it skips visually hidden headers and `.gmt-sr-only` content. A run that measures no table fails. `--shard /` keeps every n-th page of the sorted list (`shardOf` in `scripts/gates/contract.mjs`, also used by the weekly sweep's legs); `--list-pages` still prints every page. - `plate-fit` (`scripts/plate-fit.mjs`, tier `weekly`, three engines, both themes) opens every built tool page (`listToolPages` in `scripts/lib/tool-pages.mjs`, read from `dist`) once per browser, then resizes the viewport from 320 to 1920 px in `--step` 20 px steps (`--from`, `--to`; fine enough to catch a 60 px band, because the stage is not monotonic in viewport width: the sidebar, the right contents column and the full-bleed main each change it). At each width `measurePlates` (`scripts/lib/plate-overflow.mjs`) walks the text of every plate (an element in `main` whose class ends in `plate` or `Plate`) with Range rects and fails any text more than 1.5 px past the plate's padding edge. It skips `display: none`, `visibility: hidden`, `aria-hidden` and sr-only content. Rule `plate-text-overflows` is text a reader can see. Rule `plate-sample-overflows` is the hidden reserved samples (a class containing `ghost`): a sample is the widest reading the plate can show, so one past the edge means a reading would be too, even when the page now shows a short one. Rule `check-crashed` is a page that would not measure. A run that measures no plate fails. Takes `--base`, `--pages`, `--list-pages` and `--shard /`; `recordMeasured` counts pages times widths. - `contrast-measure` is Chromium only. It clips a glyph rect to each scroller's client box, never its border box. Its disabled-field border check measures the visible element: for a switch, whose input is transparent, that is the track beside it (`.track`, a dashed `--gmt-ice-dim` edge at 3:1). `a11y-media`'s `forced-colors-boundary` does the same. Both match the switch's own markup (an `input[role="switch"]` at opacity 0 with an `aria-hidden` track after it); any other transparent control is judged on itself. @@ -23,7 +24,7 @@ Part of [built/index.md](index.md). Operator steps (run, baseline, weekly sweep, ## The runner - `pnpm --filter dox gates` (`scripts/gates.mjs`) runs every gate from one build and one static server and prints one screen. Gates are data in `scripts/gates/registry.mjs` (`id`, `script`, `tier`, `browsers`, `fullBrowsers`, `themes`, `needs`, plus `args`, `base`, `browserArg`, `pages`). `select.mjs` turns changed files and the import graph (`graph.mjs`) into pages; `screen.mjs` prints. -- Tiers nest. `pr`: contrast-measure, grow-measure, readout-still, data-credits-check, esc-cascade, hero-phone, sound-check, rail-stored-still, canada-layout-check, frame-check, a11y-axe, a11y-tab-walk, a11y-media. `weekly` adds canada-clock-still, canada-stored-still, table-fit, plate-fit. `local` adds globe-smoke, html-diff, visual-diff (they need a GPU or a baseline). +- Tiers nest. `pr`: contrast-measure, grow-measure, readout-still, data-credits-check, esc-cascade, hero-phone, sound-check, rail-stored-still, canada-layout-check, rendered-links, frame-check, a11y-axe, a11y-tab-walk, a11y-media. `weekly` adds canada-clock-still, canada-stored-still, table-fit, plate-fit. `local` adds globe-smoke, html-diff, visual-diff (they need a GPU or a baseline). - Page contract: every gate script answers `--list-pages` (a JSON array of site paths without `/gmt`, no browser, printed whole however long, since the runner reads it through a pipe), takes `--pages ` (an unknown path exits 2) and, when it loads pages, `--base `. With `GATE_REPORT` set, each failure goes through `recordFinding` as `{ gate, rule, page, selector, browser, width, theme, message }` (`rule` is a short stable id such as `readout-moved`, never prose), and the run ends with `recordMeasured(gate, n)` (`scripts/gates/findings.mjs`, `contract.mjs`). Exit 0 without that line, or with `n = 0`, is `FAIL measured nothing`; exit 0 with findings is FAIL. - `hero-phone` (`hero-phone-check.mjs`, Chromium and WebKit; pages `/` and `/guides/`; zone pinned to Africa/Nairobi) holds the stacked landing on six phone sizes (`hero-phone-check.mjs` lists them), in `?globe=canvas2d`: title, buttons, then the Earth on the first screen; the atmosphere whole; no carousel, hidden or scrolling pane; headings clear of the header; a tap on "Find a zone" that does not scroll and keeps the field in view; 44 px targets, failing on fewer than expected (sheet buttons, field, three options; four zoom buttons); a tap on the Earth that leaves the sheet shut; the zone card, dragged toward each edge, inside the stage and above the open sheet; a still disc under a drag; no sideways scroll; zero layout shift (engines that report it); stars smaller than at 1440 x 900; and the header rule (title not clipped, wordmark and name ≥ 12px, no Dox, GitHub or Discord link below 50rem, the hero row only "Get started" and "Ask Dox", no eyebrow, the h1 kept). At 1440 x 900 the carousel is wired; a stacked-to-locked resize shows only the pane the reader had scrolled to, with no entrance motion. CI runs the Chromium leg (`other`); WebKit runs locally with `--browsers webkit`. - Page costs: a gate whose pages differ a lot in run time is `costs: true` in the registry and also answers `--list-page-costs` (each path's minutes). `readout-still` is the one: its costs are the `minutes` on each `TOOLS` entry, one WebKit run of that tool on one machine, since only the ratios matter. A page with no cost stops a sharded run. diff --git a/context/dox/cloudflare-runbook.md b/context/dox/cloudflare-runbook.md index 9475df371..d47be5a68 100644 --- a/context/dox/cloudflare-runbook.md +++ b/context/dox/cloudflare-runbook.md @@ -35,6 +35,10 @@ the Domains list does not show it. | Crawler Hints | Caching → Configuration | On | sends IndexNow pings when cached content changes. Nothing in the repo depends on it; switch it off if Bing Webmaster Tools → IndexNow never lists received URLs | | Web Analytics | Analytics & Logs → Web Analytics | site `northguild.dev`, **JS snippet** setup, automatic injection **off** | the tag is already in `Head.astro`; injection would load the beacon twice | +`robots.txt` has two groups: `*` (with Applebot) and a `Googlebot`/`Bingbot` group that also skips +the `.md` twins and page URLs with a query. The policy is in +[`apps/dox/scripts/robots-policy.mjs`](../../apps/dox/scripts/robots-policy.mjs). + Checks: ```sh @@ -83,6 +87,8 @@ redirect matrix; a red run means a row failed, and its table names it. Then by h h $ND/; h $ND/api/x; h $ND/mcp/x # 200 404 404 (landing) h $ND/gmt; h "$ND/gmt?a=1" # 3xx to /gmt/ and /gmt/?a=1 h $ND/gmt/; h $ND/gmt/reference/ # 200 200 +h $ND/gmt/reference # 308 /gmt/reference/ +curl -sI $WD/gmt/ | grep -i x-robots # noindex h $WD/; h "$WD/tools/dst-inspector/?zone=Europe/Paris" # 301 $ND/gmt/…, query kept h -L "$WD/reference/duty/?a=1" # ends 200 at /gmt/reference/workforce/?a=1 # as a browser follows a link — curl alone can pass while browsers get a 404 @@ -115,6 +121,73 @@ rollback does not remove the Route, and an older build may lack the `/gmt/` file switches stay as §1 sets them. Check: counts for GPTBot, OAI-SearchBot, ChatGPT-User, ClaudeBot, Claude-SearchBot, Claude-User, PerplexityBot, Google-Extended and Bingbot, and no blocked requests. +4. **Reindexing steps** after a change to redirects, the `workers.dev` host rule or `robots.txt` + reaches production: + 1. **robots.txt report** (Settings → robots.txt). Check that it shows the fetch with the + `Googlebot` group. If the fetch is older, choose "Request a recrawl". Google caches + robots.txt for up to 24 hours. + 2. **Sitemaps.** Resubmit `https://northguild.dev/gmt/sitemap-index.xml`. In Bing Webmaster + Tools, resubmit the same sitemap. + 3. **Validate Fix**, per reason, in the Page indexing report: "Duplicate, Google chose + different canonical than user", "Crawled – currently not indexed", "Discovered – currently + not indexed" and "Alternate page with proper canonical tag". Do **not** validate "Page with + redirect" or "Excluded by 'noindex' tag": those URLs stay excluded as intended, and + validation would only report them as failing. + 4. **URL Inspection → Request indexing** for the pages in the list below, nine requests inside + the daily quota. The pages under "Crawled – currently not indexed" are substantial, 200, + self-canonical and in the sitemap, so the report needs no change on the site; Google says + the state needs no action and can change on a later crawl. + +**Pages to inspect again** (URL Inspection → "Google-selected canonical"). Paths are under +`https://northguild.dev/gmt/`. + +*Duplicate, Google chose different canonical* (each page has a self canonical, a sitemap entry and +a 200): + +| Page | Google-selected canonical | Referring pages | Last crawl | Cause | +| --- | --- | --- | --- | --- | +| `reference/duration/calculate/totalDuration/` | N/A | `gmt-dox.northguild.workers.dev/reference/duration/calculate/totalDuration/`; `/gmt/tools/interval-visualizer/` | 2026-11-17 | the `workers.dev` copy; its `noindex` rule and one hop fix it | +| `reference/calendar/hours/operatingIntervals/` | N/A | `/gmt/reference/zoned/calculate/endOfQuarterForZoned` (no slash, 307); `/gmt/tools/interval-visualizer/` | 2026-11-16 | the slashless 307; the 308 fixes it | +| `reference/types/RoundingOptions/` | `https://gmt-dox.northguild.workers.dev/reference/types/RoundingOptions/` | the old host without the slash; `/gmt/tools/interval-visualizer/` | 2026-11-03 | the old host; one 301 and `noindex` fix it | + +The Sitemaps line for `RoundingOptions` reads "Temporary processing error"; step 2 covers it. + +*Crawled – currently not indexed*, the six HTML pages: + +| Page | Words | Verdict | +| --- | --- | --- | +| `guides/recurrence-and-cron/` | 2,903 | substantial, linked from every sidebar | +| `guides/splitting-and-counting/` | 2,324 | same | +| `guides/workforce-hours-of-work/` | 7,525 | same | +| `guides/mistakes/transport/` | 3,031 | same | +| `guides/durations/` | 2,344 | same | +| `reference/plain/parse/parseMonthFromDateTime/` | 127 | thin, the same shape as about 1,000 indexed generated reference pages | + +What "Google-selected canonical" means for those pages: + +| Google-selected canonical | Meaning | Action | +| --- | --- | --- | +| the same URL without the slash | the 307 source | Validate Fix after the 308 is live | +| the `.md` twin | the twin outranked the page | none; the `robots.txt` group skips the twins | +| a `?w=` or `?tz=` URL | a permalink outranked the page | none; the `robots.txt` group skips them | +| a `gmt-dox.northguild.workers.dev` URL, or N/A with that host as referring page | the duplicate host | none; inspect again after the host's `noindex` is live | +| the page itself | resolved | none | + +**Timeline and shape:** + +| When | Expect | +| --- | --- | +| 1 day | the robots.txt report shows the new file | +| 1–2 weeks | about 242 `.md` twins and 134 query URLs move to "Blocked by robots.txt" (expected, no action); validation of the four reasons reports progress | +| 2–4 weeks | the slashless 307 URLs consolidate to their slash pages; "Page with redirect" stops growing (it does not empty: the 301s and `http://` URLs stay) | +| 4–8 weeks | "Discovered – currently not indexed" falls as the freed crawl reaches the 331 pages | + +Check the report at 2, 4 and 8 weeks. + +**Watch for "Indexed, though blocked by robots.txt".** If a `?w=` or `?tz=` URL or a `.md` twin +appears there, Google is indexing it from links alone. Report it with the URLs. The answer is a +decision about the policy in `robots-policy.mjs`, not a `robots.txt` edit, because unblocking +would undo the block. ## 5. GitHub diff --git a/context/dox/specs/dox-g17/index.md b/context/dox/specs/dox-g17/index.md new file mode 100644 index 000000000..5de70e8c0 --- /dev/null +++ b/context/dox/specs/dox-g17/index.md @@ -0,0 +1,127 @@ +--- +story: DOX-G17 +issue: 559 +status: approved +dox: none +--- + +# DOX-G17: Search Console's unindexed pages + +Search Console (2026-11-23) lists 887 URLs as not indexed and 1,136 as indexed. Most of the 887 +are URLs we never want indexed. Google keeps fetching them while 331 real pages wait in +"Discovered – currently not indexed". This story stops Google spending its crawl on those URLs. It +makes the slash redirect permanent and adds a gate for each fix, so no bucket can grow back. Site +work only: there is no tool, no Dox button and no `packages/gmt` change. + +## Buckets and what this story does + +| GSC reason (count) | What is in it | Cause | Slice | +| --- | --- | --- | --- | +| Crawled – currently not indexed (251) | ~242 `.md` twins, 2 slashless URLs, 6 HTML pages | `.md` twins are crawlable and only `X-Robots-Tag: noindex` keeps them out, so Google still fetches each one | [3](./s3-search-crawlers-skip.md), [4](./s4-triage-and-search-console.md) | +| Alternate page with proper canonical tag (134) | `?w=…&wa=…` and `?tz=…&t=…` permalinks | example links on tool and scenario pages are plain `
`; the canonical tag is correct | [3](./s3-search-crawlers-skip.md) | +| Page with redirect (166) | ~155 slashless pages (307), ~6 renamed pages (301), 2 `?tz=` links, `http://` | slashless page links in our own HTML until DOX-G8 (#488, 2026-11-09); Cloudflare answers them with 307 | [1](./s1-permanent-slash.md), [2](./s2-rendered-links.md) | +| Discovered – currently not indexed (331) | clean sitemap URLs, never fetched | crawl scheduling on a young site, made worse by the URLs above | indirect: 1 and 3 free the crawl | +| Duplicate, Google chose different canonical (3) | `totalDuration`, `operatingIntervals`, `RoundingOptions` | no sibling is a canonical (URL Inspection); the old `gmt-dox.northguild.workers.dev` host and the slashless 307 | [1](./s1-permanent-slash.md), [4](./s4-triage-and-search-console.md) | +| Excluded by noindex (2) | `/gmt/llms-full.txt`, `/gmt/dox/` | intended | none | + +**Where the slashless URLs came from (re-verified).** Before `29e8010c` (DOX-G8, 2026-11-09), +992 page links in the built HTML lacked the slash. GSC's oldest crawl dates for these URLs are +10-20 to 10-24. The two named examples, `/reference/gnss` (2026-10-17) and +`/reference/types/TwoDigitYearOptions` (2026-10-10), date from before that fix. The live HTML, +`llms*.txt`, the `.md` bodies, the sampled bundles and `packages/gmt` all link with the slash. +`_redirects` targets all end in `/` (`build-utils/redirects.ts`). One source is still unguarded: +links that a mount renders at run time. Googlebot renders pages and follows those links, and +`pageLinksWithoutSlash` reads only the built HTML. Slice 2 closes that gap. + +## Slices + +| # | Slice | Repo | Gate that stops the bucket regrowing | +| --- | --- | --- | --- | +| 1 | [One permanent hop to a page; the workers.dev copy is noindex](./s1-permanent-slash.md) | gmt | `worker/index.test.ts`; `dist-base.test.ts`; `deploy-smoke` slash and host rows | +| 2 | [Links a page renders end in a slash](./s2-rendered-links.md) | gmt | new `rendered-links` gate, tier `pr` | +| 3 | [Search crawlers skip `.md` twins and query states](./s3-search-crawlers-skip.md) | northguild.dev **and** gmt | `robots-policy.test.ts`; `deploy-smoke` robots rows (daily) | +| 4 | [Canonical and crawled-not-indexed triage, Search Console steps](./s4-triage-and-search-console.md) | gmt (docs only) | none: owner steps; URL Inspection results recorded | + +Order: 1, 2, then 3, then 4. Each slice runs only its own tests, lint and `astro check`. The full +gates ([Run the gates](../../built/tier-6-runbooks.md#run-the-gates)), `pnpm run validate` and +`dox-tester` run once, after slice 4. + +**Merge order across repos.** Slice 3's `robots.txt` lives in `northguild/northguild.dev` +(`apps/site/public/robots.txt`), which deploys on every push to its `main`. That PR merges and +deploys **before** the gmt PR. Otherwise the new `deploy-smoke` robots rows fail the Dox deploy. +Slice 3 is built in a `northguild.dev.worktrees/` worktree, never in the gmt tree. + +## Files + +| File | Slice | Change | +| --- | --- | --- | +| `apps/dox/worker/index.ts` | 1 | turn the assets binding's trailing-slash 307 into 308; old-host 301 adds the page slash (`withPageSlash`) | +| `apps/dox/worker/index.test.ts` | 1 | 308 rows; missing page stays 404 | +| `apps/dox/src/assets-root/_headers`, `scripts/dist-base.test.ts` | 1 | `noindex` for `https://gmt-dox.northguild.workers.dev/gmt/*`; the test allows that one host | +| `apps/dox/scripts/deploy-smoke.mjs` | 1, 3 | 308 slash rows; workers.dev `noindex` pair; robots row | +| `apps/dox/scripts/lib/page-links.mjs` (new) | 2 | the slash predicate moves here from `dist-base.ts` | +| `apps/dox/scripts/build-utils/dist-base.ts` | 2 | imports the predicate; behaviour unchanged | +| `apps/dox/scripts/rendered-links.mjs` (new) + `gates/registry.mjs` | 2 | the gate | +| `apps/dox/scripts/robots-policy.mjs` (new) + `robots-policy.test.ts` | 3 | the crawler policy table and its checker | +| `apps/dox/package.json`, `pnpm-lock.yaml` | 3 | `robots-parser` `3.0.1`, exact, devDependency | +| `northguild.dev`: `apps/site/public/robots.txt`, `CLAUDE.md` | 3 | the search-crawler group; the rule line | +| `context/dox/built/tier-0-1-site.md`, `cloudflare-runbook.md` | 1, 3, 4 | present-tense rules; Search Console steps | +| `context/dox/specs/index.md` | — | lists this spec while in progress; the finalizer removes the line | + +No `packages/` file changes, so the gmt PR carries no changeset. No page's canonical is a sibling +(slice 4 Results), so there is no JSDoc or content fix. + +## Authority + +| Choice | Source | +| --- | --- | +| A search-crawler group replaces `*` for that crawler, so it repeats every `*` rule | RFC 9309 §2.2.1; Google, *How Google interprets the robots.txt specification* ("Order of precedence for user agents": groups for a named crawler and `*` are not combined) | +| One group may name several crawlers | RFC 9309 §2.2.1 and §2.1 grammar (`startgroupline` repeats) | +| Longest match wins, so `Disallow: /gmt/*.md$` beats `Allow: /` | RFC 9309 §2.2.2 | +| `*` and `$`; a rule's `*` also matches the query (`/*.php` matches `/f.php?parameters`) | RFC 9309 §2.2.3; Google robots spec, "URL matching based on path values" | +| `Content-Signal` sits inside a group and does not end it | RFC 9309 §2.2.4; contentsignals.org (the signal applies to the group it is in) | +| Block crawl with robots.txt, not noindex, when the aim is to save crawls | Google, *Crawl budget management for large sites* ("Don't use noindex, as Google will still request…") | +| Query states of a page: disallow in robots.txt; canonical and `nofollow` are "less effective in the long term" | Google, *Managing crawling of faceted navigation URLs* | +| Applebot follows the `Googlebot` group unless robots.txt names Applebot | Apple, *About Applebot* (support.apple.com/en-us/119829) | +| Bingbot obeys its own group and supports `*` and `$` | Bing Webmaster Guidelines, robots.txt section | +| 307 is temporary, 308 is permanent and keeps the method | RFC 9110 §15.4.8, §15.4.9 | +| 301/308 are a strong canonical signal for the target; 307 is a weak one | Google, *Redirects and Google Search* | +| `_headers` accepts an absolute `https:///…` rule; `X-Robots-Tag: noindex` on a workers.dev host | Cloudflare Workers, *Static assets → Headers* (custom headers, absolute URLs) | +| A page served on a second host is a duplicate; `noindex` keeps it out | Google, *Block Search indexing with noindex* | +| Cloudflare's `auto-trailing-slash` answers `/folder` with 307 only when `/folder/index.html` exists, and the code cannot be set | Cloudflare Workers, *Static assets → HTML handling* | +| Validation, reasons and timing in the Page indexing report | Google Search Console Help, *Page indexing report*; *robots.txt report* (cache up to 24 h) | + +## Owner decisions + +1. **Crawl block.** The `northguild.dev` robots.txt gains a `Googlebot` + `Bingbot` group that + repeats every `*` rule and the `Content-Signal` line. It blocks `/gmt/*.md$`, `/gmt/?` and + `/gmt/*/?`. `Applebot` is named in the `*` group. The exact text is approved and is in + [slice 3](./s3-search-crawlers-skip.md#the-file-northguilddevappssitepublicrobotstxt). +2. **Keep the existing hints.** Pages keep `` and the + `.md` twins keep `X-Robots-Tag: noindex`. +3. **Slice 2 is in.** The `rendered-links` gate runs at tier `pr` in Chromium. +4. **Parser.** `robots-parser` `3.0.1` is pinned exactly, as a devDependency. If it gets any + policy row wrong, the builder stops and reports. +5. **Cross-repo order.** dox-builder writes slice 3's robots.txt in a + `northguild.dev.worktrees/` worktree. That PR merges and deploys before the gmt PR, and + the deploy-smoke robots row checks the live file. Nothing is committed, pushed or opened as a PR + without the owner's word. +6. **The six crawled-not-indexed HTML pages** get no code change. Once slice 3 is live, the + runbook lists them for Request indexing. +7. **The three canonical pages.** URL Inspection (slice 4 Results) shows no sibling canonical, so + there is no JSDoc or content fix. The causes are the old workers.dev host and the slashless + 307, both fixed in slice 1, with slice 3 freeing the crawl. After the deploy, the owner inspects + the three pages again and requests indexing. +8. **Where the slashless URLs came from.** The full "Page with redirect" export puts every crawl + of a slashless URL between 10-20 and 10-24, before DOX-G8. The generated corpus's slashless + paths (`functionUrl`, `typePageUrl`) reach no crawlable response. They become `_redirects` + sources, and the chat's citations pass through `pageHref` (`ask/resolve-href.ts`). + +## Definition of done (story) + +- Each slice's definition of done holds; the full gates, `pnpm run validate` and `dox-tester` + are green once, after slice 4. +- Duplication pass: rule 10's size check, and `git grep -n "status: 30[78]"` in + `apps/dox/scripts` shows the slash expectation in one row helper only. +- `context/dox/built/tier-0-1-site.md` and `cloudflare-runbook.md` describe what is built, in the present tense. + This spec folder stays until the finalizer folds it. diff --git a/context/dox/specs/dox-g17/s1-permanent-slash.md b/context/dox/specs/dox-g17/s1-permanent-slash.md new file mode 100644 index 000000000..3b4e5dd35 --- /dev/null +++ b/context/dox/specs/dox-g17/s1-permanent-slash.md @@ -0,0 +1,171 @@ +# Slice 1: one permanent hop to a page; the workers.dev copy is noindex + +[Story](./index.md) · repo: gmt · gate: `worker/index.test.ts`, `dist-base.test.ts`, `deploy-smoke` +slash, legacy and host rows + +## Why + +`/gmt/reference/gnss` answers `307 location: /gmt/reference/gnss/` (probed live; the query is kept). +That 307 comes from the assets binding's `auto-trailing-slash` html handling, which always uses 307 +(Cloudflare *Static assets → HTML handling*). RFC 9110 §15.4.8 makes 307 temporary. Google treats +a temporary redirect as a weak canonical signal, so the slashless source URL may stay canonical +(*Redirects and Google Search*). That keeps about 155 URLs in "Page with redirect" and is the likely +cause of the three "Google chose different canonical" pages (slice 4). A 308 (RFC 9110 §15.4.9) is +permanent, keeps the method and is a strong signal. + +The Worker already sees every slashless request. `run_worker_first` holds `/*` minus `/gmt/`, +`/gmt/*/` and `/gmt/*.*` (`apps/dox/wrangler.jsonc`; `worker/static-routing.test.ts` proves +`/gmt/reference` reaches the Worker). Its last line hands the request to `env.ASSETS.fetch`. + +## Change: the 308 + +`apps/dox/worker/index.ts`, at the last step only: + +1. `const res = await env.ASSETS.fetch(request);` The request stays unmodified, as the comment says. +2. Turn `res` into a 308 only when all of these hold: + - `res.status === 307`; + - `new URL(res.headers.get("location"), url)` has the same origin as `url`; + - its pathname is `url.pathname + "/"`; + - its search is `url.search`. + Return `new Response(res.body, { status: 308, headers: res.headers })`. The Location is copied + unchanged; RFC 9110 §10.2.2 allows a relative reference. +3. Return any other response as it is. A 404, a 200 and any other 307 pass through. +4. Put the test in a small named function, `permanentSlash(res, url)`, beside `redirect()`, with one + JSDoc line that cites RFC 9110 §15.4.9. Rewrite the last-step comment to say that the slash hop + is made permanent here. + +Do not add the slash in the Worker or check whether the page exists. Assets already know whether +`/folder/index.html` exists, so their 307 is the only proof that the page is real. A missing path +keeps its direct 404 (probed: `/gmt/nope` → 404). + +## Change: the old host lands in one hop + +**Finding (probed 2026-11-27).** `gmt-dox.northguild.workers.dev/reference/types/RoundingOptions` +answers 301 to `northguild.dev/gmt/reference/types/RoundingOptions`, which then answers 307 (308 +after this slice). Old links take two hops. Google still keeps that old URL as the page's canonical +(slice 4 Results). + +In the not-under-the-base branch (step 1 in the Worker's header comment), wrap the 301 target with +`withPageSlash` from `src/lib/site.ts`. The Worker already imports `SITE_URL` from that module, and +`withPageSlash` is the site's one page-path rule: no dot in the last segment, slash added before the +query. So `redirect(withPageSlash(\`${SITE_URL}${url.pathname}${search}\`))`. Then: + +- `/reference/types/RoundingOptions?a=1` → 301 `https://northguild.dev/gmt/reference/types/RoundingOptions/?a=1`; +- `/install.md`, `/llms.txt`, `/robots.txt` and any path with a dot are unchanged. `/robots.txt` + keeps its own branch; +- the API routes are still served in place before this line, so nothing under the old `/api/` + changes, and `/gmt/api/` is under the base and never reaches this branch; +- a missing path gets one 301 to its slash URL, then a 404 there, never a chain; +- the `key` filter runs first, as now, so the key is still dropped. + +Add one sentence to the header comment's step 1: the 301 adds the page slash, so an old link lands +in one hop. + +## Tests: `apps/dox/worker/index.test.ts` + +Reuse `fixtureAssets()` and its `assets.calls`. Add a fixture answer that returns 307 with a +relative Location, as the live binding does. + +- `/gmt/reference` → 308, `location` `/gmt/reference/`; `assets.calls` holds the request unmodified. + Update the existing test "hands a page path to the assets binding untouched, base included" to + this expectation; do not add a second test for the same thing. +- `/gmt/reference/duration/calculate/totalDuration?a=1` → 308, location keeps `?a=1`. +- Body and headers other than the status are the binding's own (check `cache-control` and `location`). +- A 307 whose Location is not the same path plus `/` (another path, another origin, or a query that + differs) → passed through as 307. +- A missing page → 404 straight from the binding, never 308 (row 21 stays as it is). +- A 200 from the binding is passed through unchanged. +- Legacy host: `/reference/types/RoundingOptions?a=1` → one 301 to + `${SITE_URL}/reference/types/RoundingOptions/?a=1`. `/reference?key=k&a=1` → 301 to + `${SITE_URL}/reference/?a=1`. `/install.md` → 301 to `${SITE_URL}/install.md` (no slash). Update + the existing legacy-redirect rows that expect a slashless target; do not duplicate them. + +No timers or listeners start, so no teardown is needed. The tests never touch the network +([rule](../../built/index.md)). + +## Tests: `apps/dox/scripts/deploy-smoke.mjs` + +- Row "6" becomes one hop: `WD/reference` → `301 ${ND}/gmt/reference/` → `200`. +- New row "6a": `${ND}/gmt/reference` → `308 ${ND}/gmt/reference/` → `200`. +- Row "36 /gmt/nope": keep the optional first step, but as `status: 308`. That hop exists only if + assets ever answers a missing folder with a slash redirect. A 307 there must now fail. +- New row "6b": a slashless function page with a query. Take the first `/gmt/reference////` + URL from the live sitemap: the script already requests `${ND}/gmt/sitemap-index.xml` (row near + line 850). Follow its first `` to the child sitemap with one small `firstSitemapUrl(re)` + helper built on `send()`. Request it without the slash and with + `?a=1`, and expect `308` to the slash URL with `?a=1`, then `200`. Never hard-code a function name, + because pages get renamed. +- New row "6d": the same sitemap page on the old host without `/gmt`, without its slash and with + `?a=1` → exactly one `301` whose Location ends in `/?a=1`, then `200`. The existing `hop` rows + for `WD/install.md` and `WD/llms.txt` stay, and they prove a file path keeps its form. +- Write the 308 rows (6a, 6b) with one helper, `slashHop(rows, label, url)`, so the expected status sits in + one place. The story's duplication grep relies on that. +- `DOX_SMOKE_LOCAL`: run `wrangler dev` on the built `dist` once and check whether + `/gmt/reference` answers 307 or 308 there. If it does, add rows "6a" and "6b" to the local crawl rows. If + `wrangler dev` does not reproduce the binding's 307, leave the row live-only, and say why in the + header comment. + +## The workers.dev host: `noindex` + +**Finding (probed 2026-11-27).** `https://gmt-dox.northguild.workers.dev/gmt//` answers 200 +with the full page and no `X-Robots-Tag`. `run_worker_first` leaves out `/gmt/*/`, so the assets +binding serves the page on every host. The page's canonical points to `northguild.dev`, but the +copy is still crawlable and indexable. URL Inspection for `…/totalDuration/` names this copy as the +referring page. The paths without `/gmt` on that host answer 301 to `northguild.dev/gmt/…` +(CORE-86) and stay as they are, so `workers_dev: true` stays. + +**Change.** Add one rule to `apps/dox/src/assets-root/_headers`, with a comment saying it keeps +the old host out of search results: + +```text +https://gmt-dox.northguild.workers.dev/gmt/* + X-Robots-Tag: noindex +``` + +Cloudflare's `_headers` accepts an absolute `https` URL, matched by host. Its own example is +`https://myworker.mysubdomain.workers.dev/*` with `X-Robots-Tag: noindex` (Workers *Static assets → +Headers*). The rule names the host literally, because this Worker has one name and no preview URLs. +The path stays `/gmt/*`: only assets answer there, and the rule then fits the house rule that every +`_headers` rule sits under `/gmt/`. A `.md` or `.txt` file on that host gets both rules. Cloudflare +joins the values, so the header reads `noindex, noindex`, which is harmless. + +**Tests.** + +- `apps/dox/scripts/dist-base.test.ts`, "every _headers rule sits under /gmt/": strip an optional + `https://gmt-dox.northguild.workers.dev` prefix before the check, and allow no other host. Add + one case asserting that this host rule is present. +- `deploy-smoke.mjs`: a live-only row pair, built on the page `firstSitemapUrl` returns: + - "6c workers.dev noindex": `WD/gmt//` answers 200 with an `x-robots-tag` that holds + `noindex`; + - "6c canonical host": `ND/gmt//` answers 200 with no `x-robots-tag`. + `wrangler dev` serves on `localhost`, where the host rule cannot match, so both rows are skipped + under `DOX_SMOKE_LOCAL`. + +## Traps + +- Do not read `res.url`. It is the asset URL, not the Location. +- A `Response` from the binding may have immutable headers. Pass `res.headers` into the new + `Response` and never mutate them. +- `HEAD` must behave like `GET`, so add a test with `HEAD /gmt/reference` → 308. +- The workers.dev host (`WD`) answers `301` to `ND` with the slash already added, so a 308 only + happens on `ND`. Rows 6 and 6d prove the old host never chains. + +## Close-out (in this slice) + +- `context/dox/built/tier-0-1-site.md`, Deploy section: add one line in the present tense. A page + path without its slash answers 308 to the slash URL, query kept. The Worker upgrades the assets + binding's 307 because a permanent redirect is the canonical signal Google honours (RFC 9110 + §15.4.9). An old `workers.dev` path is one 301 to the page URL with its slash (`withPageSlash`). +- Same section: the workers.dev host serves its `/gmt/` pages with `X-Robots-Tag: noindex` + (a host rule in `_headers`), because assets answer them there too and only `northguild.dev` may + be indexed. The host stays on for the CORE-86 301s. +- `context/dox/cloudflare-runbook.md` §3: add `h $ND/gmt/reference # 308 /gmt/reference/` beside + the existing `$ND/gmt` lines, plus `curl -sI $WD/gmt/ | grep -i x-robots # noindex`. + +## Definition of done + +- `pnpm --filter dox exec vitest run worker/` passes; `pnpm --filter dox lint` and `check` are clean. +- `git grep -n "status: 307" apps/dox/scripts/deploy-smoke.mjs` prints nothing. +- `pnpm --filter dox exec vitest run scripts/dist-base.test.ts` passes after a build. +- After the deploy, `node apps/dox/scripts/deploy-smoke.mjs` passes against production. The + deploy workflow runs it, and so does the daily schedule. diff --git a/context/dox/specs/dox-g17/s2-rendered-links.md b/context/dox/specs/dox-g17/s2-rendered-links.md new file mode 100644 index 000000000..71393035b --- /dev/null +++ b/context/dox/specs/dox-g17/s2-rendered-links.md @@ -0,0 +1,108 @@ +# Slice 2: links a page renders end in a slash + +[Story](./index.md) · repo: gmt · gate: new `rendered-links` (tier `pr`, Chromium) + +## Why + +`test:dist` fails a page link without its slash in the built HTML (`pageLinksWithoutSlash`) and in +Markdown (`pageLinksWithoutSlashInMarkdown`). Both live in `apps/dox/scripts/build-utils/dist-base.ts` +(DOX-G8). Widgets add more links at run time: about 20 modules under `src/lib/` and +`src/components/` set an `href`. Today they all build hrefs with `withBase("/…/")`, so none of them +lacks the slash. But no check holds them to it, and Googlebot renders the page and follows those +links. A slashless link added later would grow "Page with redirect" again with no gate to catch it. +Slice 1 makes such a hop permanent, but every hop still costs a crawl. + +## Reuse + +| Piece | Path | Use | +| --- | --- | --- | +| Slash predicate | `scripts/build-utils/dist-base.ts` (`isPageLinkWithoutSlash`, private) | **moves** to `scripts/lib/page-links.mjs`, exported; `dist-base.ts` imports it. One check, one home. | +| Gate contract | `scripts/gates/contract.mjs`, `scripts/lib/gate-cli.mjs` (`--list-pages`, `--pages`, `--base`, `recordFinding`, `recordMeasured`) | the new gate's CLI and report | +| Browser launch | `scripts/lib/browser-launch.mjs` | Chromium | +| Page list from `dist` | pattern of `scripts/lib/tool-pages.mjs` (`listToolPages(distRoot)`) | new `listWidgetPages(distRoot)` in `scripts/lib/widget-pages.mjs` | +| Registry | `scripts/gates/registry.mjs` | one row; it lands in the `other` CI leg on its own (`ci-legs.test.ts`) | + +New files and their layer: + +- `scripts/lib/page-links.mjs` (shared). Exports `isPageLinkWithoutSlash(value)` and the `ORIGIN` + and `underBase` it needs. `dist-base.ts` imports all three instead of defining them, so the base + rule exists once. +- `scripts/lib/widget-pages.mjs` (shared). `listWidgetPages(distRoot)` returns the site path of every + built page whose HTML holds a `data-widget=` element, sorted. The list is read from `dist`, never + typed in. +- `scripts/rendered-links.mjs` (the gate). +- `scripts/lib/page-links.test.ts` and `widget-pages.test.ts`: unit tests. + +**Second-instance test.** A second rendered-link rule, such as no `http://` links, would add one +predicate to `page-links.mjs` and one call in the gate. It would need no second gate and no second +page list. + +## The gate: `scripts/rendered-links.mjs` + +- Pages: `listWidgetPages(distRoot)`. `--list-pages` prints them, and `--pages` narrows them. +- For each page, in Chromium at 1440 × 900: + 1. Load the page and wait for `load`, then for each `[data-widget]` root to be attached. Reuse the + wait an existing Chromium gate uses (`a11y-axe.mjs`), not a fixed sleep. + 2. Read `href` from every `a[href]` and `area[href]` **attribute** in the document + (`getAttribute`, not the resolved `.href`), so a relative or base-less value is judged as + written. + 3. Record a finding (rule `page-link-without-slash`) for each value where + `isPageLinkWithoutSlash` is true. The finding names the page, the value and the closest + `[data-widget]` name. + 4. `recordMeasured` the number of links checked. A page with no widget root fails as + `measured nothing`, as every gate does. +- A static link is checked again here, and that is fine: one predicate makes the same verdict in + both checks, and `test:dist` stays the fast check. +- Close the page and the browser in `finally`, so a failed assertion still tears down. + +Registry row: + +```js +{ id: "rendered-links", script: "rendered-links.mjs", tier: "pr", + browsers: ["chromium"], fullBrowsers: ["chromium"], themes: false, needs: null } +``` + +The link logic does not depend on the theme, so `themes: false` (as 18 gates already use) halves the run. + +## Tests + +- `page-links.test.ts`. The cases `dist-base.test.ts` already covers for the HTML scan move here as + table cases for the predicate: + - `/gmt/reference` → true; `/gmt/reference/` → false; `/gmt/llms.txt` → false; + - `https://northguild.dev/gmt/tools/x?w=1#a` → true; `/other` → false; `//cdn/x` → false. + `dist-base.test.ts` keeps its HTML-scanning tests. Delete any case that only exercised the + predicate there. +- `widget-pages.test.ts`: a temporary `dist` with three pages: one holding `data-widget="a"`, one + without, and one with `data-widget` only inside a `