{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "seo-routes",
  "title": "AgentBlog SEO routes",
  "description": "sitemap.xml built from real content dates rather than the build clock, an environment-guarded robots.txt that declares your AI access preferences, an RSS 2.0 feed, and a 404 that returns a real 404.",
  "registryDependencies": [
    "@agentblog/blog-core"
  ],
  "files": [
    {
      "path": "registry/blog/app/sitemap.ts",
      "content": "/**\n * `/sitemap.xml` for the whole site.\n *\n * ---------------------------------------------------------------------------\n * READ THIS BEFORE YOU CHANGE ANYTHING (human or agent)\n * ---------------------------------------------------------------------------\n * THIS IS A CACHED ROUTE HANDLER. The Next.js docs say it plainly: \"sitemap.js\n * is a special Route Handler that is cached by default unless it uses a\n * Request-time API or dynamic config option.\" So a post published without a\n * rebuild does NOT appear here until something invalidates the cache.\n *\n * That is why `app/api/publish/route.ts` calls `revalidatePath('/sitemap.xml')`\n * explicitly. If you delete that line, the publish webhook will keep pinging\n * IndexNow for URLs that this file does not list, which is a crawl-quality\n * signal you are paying for and getting nothing back from. The `revalidate`\n * export below is the backstop for when nobody calls the webhook at all.\n *\n * ---------------------------------------------------------------------------\n * THE THREE RULES THIS FILE ENFORCES\n * ---------------------------------------------------------------------------\n * 1. `lastModified` comes from real content dates, never `new Date()`. A sitemap\n *    that claims every page changed today is a false freshness signal, and it is\n *    spent for nothing: crawlers learn that this site's `lastmod` carries no\n *    information and stop reading it. Bing has said `lastmod` is one of the few\n *    sitemap fields it actually uses, so it is worth keeping honest.\n * 2. A noindexed URL is never listed. Listing a URL here says \"please index\n *    this\" while the page says \"do not index this\". Contradicting yourself in\n *    two machine-readable surfaces is worse than saying nothing in either.\n *    Concretely: tag pages below `config.noindexTagsBelow` are excluded, and so\n *    are drafts (which `getAllPosts()` already filters out).\n * 3. Hero images are emitted through the native `images` field. In Next.js\n *    16.3.0 `MetadataRoute.Sitemap` genuinely declares `images?: string[]`\n *    (verified in `next/dist/lib/metadata/types/metadata-interface.d.ts`), so no\n *    cast is needed. This is free image-sitemap coverage.\n * 4. **Every string this file returns is XML-escaped, with no exceptions.**\n *    Next.js does the serialization and does no escaping of its own. From\n *    `next/dist/build/webpack/loaders/metadata/resolve-route-data.js@16.3.0`:\n *\n *        content += `<loc>${item.url}</loc>\\n`\n *        content += `<image:loc>${image}</image:loc>\\n`\n *\n *    Straight interpolation, so a raw `&` from a perfectly ordinary CDN URL\n *    (`?w=1200&h=630&fit=crop`) makes the whole document not well-formed and the\n *    site silently has no sitemap at all. Measured before this was added: one\n *    hero image, `ParseError: not well-formed (invalid token): line 24`. The\n *    same hole let a crafted `heroImage` close `<image:loc>` and add an\n *    attacker's `<url>` element; `ImageRef` in `lib/schemas.ts` now refuses the\n *    characters that do that, and this escape is the second layer.\n *    `app/feed.xml/route.ts` has carried the same rule since it was written.\n *\n * @see https://docs.agentblog.dev/reference/files\n */\nimport type { MetadataRoute } from 'next'\n\nimport {\n  absoluteUrl,\n  authorUrl,\n  categoryUrl,\n  config,\n  escapeXml,\n  postUrl,\n  tagSlug,\n  tagUrl,\n} from '@/lib/config'\nimport { getAllAuthors, getAllCategories, getAllPosts, getAllTags } from '@/lib/posts'\nimport type { PublishedPost } from '@/lib/types'\n\n/**\n * ISR backstop. The publish webhook is the fast path; this is what keeps the\n * sitemap from going stale on a site whose webhook is never wired up.\n *\n * Hardcoded rather than read from `config.revalidate` because route segment\n * config has to be statically analysable, and an imported binding is not.\n */\nexport const revalidate = 3600\n\n/**\n * `changeFrequency` and `priority` are set conservatively on purpose.\n *\n * Google has stated repeatedly that it largely ignores both, and `priority` is\n * relative within one sitemap rather than a global ranking dial. Setting\n * everything to `always` / `1.0` buys nothing and costs credibility with the\n * crawlers that do read them. These values describe how the site actually\n * behaves: an evergreen post changes rarely, the index changes when you publish.\n */\nconst FREQUENCY = {\n  home: 'weekly',\n  index: 'weekly',\n  post: 'monthly',\n  category: 'monthly',\n  tag: 'yearly',\n  author: 'yearly',\n  policy: 'yearly',\n} as const\n\nconst PRIORITY = {\n  home: 1.0,\n  index: 0.9,\n  post: 0.7,\n  category: 0.6,\n  author: 0.5,\n  policy: 0.4,\n  tag: 0.3,\n} as const\n\n/** Newest `dateModified` in a set, compared as instants because offsets are not lexicographic. */\nfunction newestModified(posts: readonly PublishedPost[]): string | undefined {\n  let newest: string | undefined\n  for (const post of posts) {\n    if (newest === undefined || Date.parse(post.dateModified) > Date.parse(newest)) {\n      newest = post.dateModified\n    }\n  }\n  return newest\n}\n\n/**\n * Group posts by a key so every hub page gets a real `lastModified`.\n *\n * One pass over `getAllPosts()` rather than a `getPostsByCategory()` call per\n * category, because that would be an N+1 against the content source at exactly\n * the moment the site has the most content in it.\n */\nfunction groupBy(\n  posts: readonly PublishedPost[],\n  key: (post: PublishedPost) => readonly string[],\n): Map<string, PublishedPost[]> {\n  const groups = new Map<string, PublishedPost[]>()\n  for (const post of posts) {\n    for (const value of key(post)) {\n      const bucket = groups.get(value)\n      if (bucket) bucket.push(post)\n      else groups.set(value, [post])\n    }\n  }\n  return groups\n}\n\n/**\n * Escape the two string-valued fields of an entry, applied to every entry on the\n * way out.\n *\n * One place rather than seven call sites, and it runs last, so an entry added\n * later cannot forget. See rule 4 in the header for why this is not optional.\n */\nfunction escapeEntry(entry: MetadataRoute.Sitemap[number]): MetadataRoute.Sitemap[number] {\n  return {\n    ...entry,\n    url: escapeXml(entry.url),\n    ...(entry.images ? { images: entry.images.map(escapeXml) } : {}),\n  }\n}\n\nexport default async function sitemap(): Promise<MetadataRoute.Sitemap> {\n  const [posts, categories, authors, tags] = await Promise.all([\n    getAllPosts(),\n    getAllCategories(),\n    getAllAuthors(),\n    getAllTags(),\n  ])\n\n  const byCategory = groupBy(posts, (post) => [post.category.slug])\n  const byAuthor = groupBy(posts, (post) => [post.author.slug])\n  // Keyed by slug, which is the same key `getAllTags()` counts on and the same\n  // one the tag route resolves. Grouping on the raw string would miss posts that\n  // wrote the same tag with different casing or spacing.\n  const byTag = groupBy(posts, (post) => post.tags.map((tag) => tagSlug(tag)))\n\n  const siteLastModified = newestModified(posts)\n\n  const entries: MetadataRoute.Sitemap = [\n    {\n      url: absoluteUrl('/'),\n      lastModified: siteLastModified,\n      changeFrequency: FREQUENCY.home,\n      priority: PRIORITY.home,\n    },\n    {\n      url: absoluteUrl('/blog'),\n      lastModified: siteLastModified,\n      changeFrequency: FREQUENCY.index,\n      priority: PRIORITY.index,\n    },\n    /**\n     * The editorial policy page ships in `@agentblog/eeat-pages`. If you removed\n     * that page, remove this entry too: a 404 in a sitemap is a crawl-quality\n     * signal exactly like a noindexed URL in a sitemap is.\n     */\n    {\n      url: absoluteUrl('/editorial-policy'),\n      lastModified: siteLastModified,\n      changeFrequency: FREQUENCY.policy,\n      priority: PRIORITY.policy,\n    },\n  ]\n\n  for (const post of posts) {\n    const hero = post.heroImage\n    entries.push({\n      url: postUrl(post.slug),\n      // From the content, never from the clock. See rule 1 in the header.\n      lastModified: post.dateModified,\n      changeFrequency: FREQUENCY.post,\n      priority: PRIORITY.post,\n      // Conditional spread rather than `images: undefined`, so the shape stays\n      // valid under `exactOptionalPropertyTypes`.\n      ...(hero ? { images: [absoluteUrl(hero)] } : {}),\n    })\n  }\n\n  for (const category of categories) {\n    entries.push({\n      url: categoryUrl(category.slug),\n      // Computed from the posts in the hub, with the source's own value as a\n      // fallback. The computed one cannot disagree with what the page renders.\n      lastModified: newestModified(byCategory.get(category.slug) ?? []) ?? category.latestPostDate,\n      changeFrequency: FREQUENCY.category,\n      priority: PRIORITY.category,\n    })\n  }\n\n  /**\n   * Only authors who have actually published something.\n   *\n   * `app/authors/[slug]/page.tsx` sets `robots: { index: false }` on an author\n   * with no posts, so the same rule has to gate this list. An author record\n   * added before their first post ships is a real page (it still 200s, and every\n   * Article graph's `author` link needs it to) with nothing on it, and listing a\n   * noindexed URL here is the site telling a crawler \"please index this\" in one\n   * machine-readable surface and \"do not index this\" in another. If you change\n   * one, change both.\n   */\n  for (const author of authors) {\n    const authored = byAuthor.get(author.slug) ?? []\n    if (authored.length === 0) continue\n    entries.push({\n      url: authorUrl(author.slug),\n      lastModified: newestModified(authored),\n      changeFrequency: FREQUENCY.author,\n      priority: PRIORITY.author,\n    })\n  }\n\n  /**\n   * Only tags the tag route actually lets search engines index.\n   *\n   * `app/blog/tag/[slug]/page.tsx` sets `robots: { index: false }` below\n   * `config.noindexTagsBelow`, so the same threshold has to gate this list. If\n   * you change one, change both, or the sitemap starts advertising URLs that\n   * tell the crawler to go away when it arrives.\n   */\n  for (const { tag, count } of tags) {\n    if (count < config.noindexTagsBelow) continue\n    entries.push({\n      url: tagUrl(tag),\n      lastModified: newestModified(byTag.get(tagSlug(tag)) ?? []),\n      changeFrequency: FREQUENCY.tag,\n      priority: PRIORITY.tag,\n    })\n  }\n\n  /**\n   * Deliberately absent: paginated index pages (`/blog/page/2` and friends).\n   * They are reachable through real `<a href>` links from `/blog`, they carry no\n   * content of their own, and listing them adds URLs that compete with the hub.\n   *\n   * Also deliberately absent: any URL count management. Google's limit is 50,000\n   * URLs per sitemap. Past that, split with `generateSitemaps()` and point\n   * `robots.ts` at the index. Almost no blog reaches it.\n   */\n  return entries.map(escapeEntry)\n}\n",
      "type": "registry:page",
      "target": "app/sitemap.ts"
    },
    {
      "path": "registry/blog/app/robots.ts",
      "content": "/**\n * `/robots.txt`.\n *\n * ---------------------------------------------------------------------------\n * THE MOST IMPORTANT THING ON THIS PAGE IS NOT IN THIS FILE\n * ---------------------------------------------------------------------------\n * robots.txt is the innermost layer of crawler access control, and it is the\n * last one a request reaches. A CDN sitting in front of your origin can refuse\n * an AI crawler before this file is ever read, and when that happens everything\n * here is correct and completely inert.\n *\n * This is not hypothetical. Cloudflare's default for new domains, for new sites\n * on existing accounts, and for Free-tier accounts that have not changed their\n * settings blocks Training and Agent crawlers. And blocking \"Training\" also\n * blocks multi-purpose crawlers, which per Cloudflare's own announcement\n * includes Googlebot, Applebot, and BingBot. So a perfect install can lose\n * organic search, silently, because of a setting in a different product.\n *\n * Nothing in this repository can detect that from the inside. The only check\n * that catches it fetches your live URL from outside your deployment's network:\n *\n *     npx agentblog doctor --url https://your-live-site.com\n *\n * Run it after your first deploy. It is the single highest-value check in the\n * whole tool, and it is the reason \"my robots.txt is open but I get no ChatGPT\n * citations\" is such a common complaint.\n *\n * ---------------------------------------------------------------------------\n * NON-VERCEL DEPLOYMENTS: READ THIS OR YOUR SITE WILL BE BLOCKED\n * ---------------------------------------------------------------------------\n * The environment guard below fails closed. Vercel sets `VERCEL_ENV` for you;\n * nothing else does. If you deploy anywhere else, set `AGENTBLOG_PUBLIC_SITE=true`\n * in your production environment or this file emits a blanket `Disallow: /`.\n *\n * Failing closed is deliberate. Guessing wrong in the permissive direction gets\n * a staging site indexed and competing with production, which takes weeks to\n * undo. Guessing wrong in the restrictive direction is one environment variable\n * and is visible the moment anyone opens `/robots.txt`.\n *\n * @see https://docs.agentblog.dev/troubleshooting/cdn-blocking-crawlers\n */\nimport type { MetadataRoute } from 'next'\n\nimport { absoluteUrl, config } from '@/lib/config'\nimport { AI_CRAWLERS } from '@/lib/preflight-checks'\nimport type { AiCrawler } from '@/lib/preflight-checks'\n\n/** One entry of the array form of `MetadataRoute.Robots['rules']`, derived rather than retyped. */\ntype RobotsRule = Extract<MetadataRoute.Robots['rules'], unknown[]>[number]\n\n/**\n * Anthropic honours the non-standard `Crawl-delay` directive, which most\n * crawlers ignore. One second is a courtesy, not a throttle: a large value on a\n * crawler you want citations from is a self-inflicted wound.\n *\n * Note that `crawlDelay` is a first-class field on a robots rule, so it does not\n * need the `other` escape hatch. `other` is used further down for a directive\n * the Next.js API genuinely does not model.\n */\nconst ANTHROPIC_CRAWL_DELAY_SECONDS = 1\n\n/**\n * Paths that never belong in a search index.\n *\n * Note what is NOT here: the noindexed tag pages. Blocking a URL in robots.txt\n * stops the crawler from fetching it, which means it never reads the `noindex`\n * on the page, which means the URL can still surface as a bare listing. If you\n * want a page out of the index, let it be crawled and let it say `noindex`.\n */\nconst PRIVATE_PATHS = ['/api/']\n\n/** Crawlers of one purpose, split by whether Anthropic operates them. */\nfunction crawlersFor(purpose: AiCrawler['purpose'], anthropic: boolean): string[] {\n  return AI_CRAWLERS.filter(\n    (crawler) => crawler.purpose === purpose && (crawler.operator === 'Anthropic') === anthropic,\n  ).map((crawler) => crawler.ua)\n}\n\n/** `Allow: /` or `Disallow: /`, as a spreadable fragment. */\nfunction access(allowed: boolean): { allow: string } | { disallow: string } {\n  return allowed ? { allow: '/' } : { disallow: '/' }\n}\n\nexport default function robots(): MetadataRoute.Robots {\n  const isProduction =\n    process.env.VERCEL_ENV === 'production' || process.env.AGENTBLOG_PUBLIC_SITE === 'true'\n\n  /**\n   * Preview and development deployments block everything.\n   *\n   * This is the cheapest possible defence against the most common self-inflicted\n   * SEO wound there is: a preview URL that ranks against production, splits its\n   * own signals, and shows a half-finished draft to real users. Three lines.\n   */\n  if (!isProduction) {\n    return { rules: [{ userAgent: '*', disallow: '/' }] }\n  }\n\n  const rules: RobotsRule[] = [{ userAgent: '*', allow: '/', disallow: PRIVATE_PATHS }]\n\n  /**\n   * Split AI access rules, driven by `config.aiAccess`.\n   *\n   * The three purposes are genuinely different decisions and you are entitled to\n   * make them separately:\n   *\n   *   search  the crawler that fetches you so an assistant can cite you\n   *   agent   the crawler that fetches you because a user asked, right now\n   *   train   the crawler that fetches you to put you in a model's weights\n   *\n   * `train: false` is a real tradeoff and not a free one. Vendor documentation\n   * draws the boundary between \"training\" and \"retrieval\" more cleanly than\n   * reality does, and some crawlers serve both. Opting out of training can opt\n   * you out of the index that would have cited you.\n   *\n   * This is also the seam for the AI-access standards currently converging on\n   * robots.txt (Cloudflare Content Signals, RSL, the IETF AIPREF draft). When\n   * one of them lands, it is emitted from this same config object and no\n   * consumer has to touch `agentblog.config.ts`.\n   */\n  const purposes = [\n    ['search', config.aiAccess.search],\n    ['agent', config.aiAccess.agent],\n    ['train', config.aiAccess.train],\n  ] as const\n\n  for (const [purpose, allowed] of purposes) {\n    const others = crawlersFor(purpose, false)\n    if (others.length > 0) {\n      rules.push({ userAgent: others, ...access(allowed) })\n    }\n\n    // Anthropic's bots get their own group so `Crawl-delay` lands only on the\n    // agents that read it. Same allow/disallow decision, one extra directive.\n    const anthropic = crawlersFor(purpose, true)\n    if (anthropic.length > 0) {\n      rules.push({\n        userAgent: anthropic,\n        ...access(allowed),\n        crawlDelay: ANTHROPIC_CRAWL_DELAY_SECONDS,\n      })\n    }\n  }\n\n  /**\n   * A worked example of the per-rule `other` field, new in Next.js 16.3.0.\n   *\n   * `Clean-param` tells Yandex that these query parameters do not change the\n   * page, so `?utm_source=x` and the bare URL are one document rather than two.\n   * The Next.js robots API does not model it, values in `other` are passed\n   * through verbatim and unvalidated, and the type is\n   * `Record<string, string | number | Array<string | number>>` per rule.\n   *\n   * Safe to delete if you do not care about Yandex. It is here because it is a\n   * real directive with real syntax, which is more useful to copy from than an\n   * invented one.\n   */\n  rules.push({\n    userAgent: 'Yandex',\n    allow: '/',\n    other: { 'Clean-param': 'utm_source&utm_medium&utm_campaign&ref /' },\n  })\n\n  /**\n   * Not modelled above: OpenAI's `OAI-AdsBot`, which validates ad landing pages\n   * and, per OpenAI's own documentation, does not respect robots.txt. It falls\n   * under the `*` rule. Writing a directive for a crawler that documents itself\n   * as ignoring directives would be decoration.\n   */\n\n  return {\n    rules,\n    sitemap: absoluteUrl('/sitemap.xml'),\n    host: config.siteUrl,\n  }\n}\n",
      "type": "registry:page",
      "target": "app/robots.ts"
    },
    {
      "path": "registry/blog/app/feed.xml/route.ts",
      "content": "/**\n * `/feed.xml`: RSS 2.0.\n *\n * ---------------------------------------------------------------------------\n * THIS IS A CACHED ROUTE HANDLER\n * ---------------------------------------------------------------------------\n * Same mechanism as `app/sitemap.ts`: a route handler with no request-time API\n * is cached, so a post published without a rebuild does not appear in the feed\n * until something invalidates it. `app/api/publish/route.ts` calls\n * `revalidatePath('/feed.xml')` for exactly this reason. The `revalidate` export\n * below is the backstop for installs whose webhook is never wired up.\n *\n * ---------------------------------------------------------------------------\n * ESCAPING IS A CORRECTNESS REQUIREMENT HERE, NOT A STYLE ONE\n * ---------------------------------------------------------------------------\n * Every interpolated value goes through `escapeXml` or `cdata`. A single `&` in\n * a post title produces a feed that every strict parser rejects outright, and\n * the failure is invisible from the site itself: the page renders, the sitemap\n * is fine, and the feed is simply broken for everyone subscribed to it. If you\n * add a field below, escape it. There are no exceptions in this file.\n *\n * ---------------------------------------------------------------------------\n * WHY THERE IS NO `content:encoded`\n * ---------------------------------------------------------------------------\n * `post.body` is MDX source, not HTML. Emitting it raw would ship JSX component\n * tags to feed readers, and compiling it here would mean a second MDX pipeline\n * outside `lib/render-mdx.tsx`, which is the one place in the block that is\n * allowed to compile MDX. A duplicate pipeline drifts, and a drifting HTML\n * serializer that feeds untrusted-ish markup into other people's readers is not\n * a small risk to take for a summary field.\n *\n * So the feed carries `description` only, and it is a real description rather\n * than a truncated first paragraph. If you want full content, render it through\n * `renderMdx` to a string and add `content:encoded` here, escaped as CDATA.\n *\n * @see https://docs.agentblog.dev/reference/files\n */\nimport {\n  absoluteUrl,\n  bcp47Locale,\n  config,\n  escapeXml,\n  postUrl,\n  stripInvalidXmlChars,\n} from '@/lib/config'\nimport { getAllPosts } from '@/lib/posts'\nimport type { PublishedPost } from '@/lib/types'\n\n/**\n * ISR backstop. Hardcoded rather than read from `config.revalidate` because\n * route segment config must be statically analysable.\n */\nexport const revalidate = 3600\n\n/**\n * Feed readers poll; they do not paginate. Fifty recent posts is the usual\n * ceiling and keeps the document small enough to fetch cheaply.\n */\nconst MAX_ITEMS = 50\n\nconst FEED_PATH = '/feed.xml'\n\n/**\n * Wrap a value in CDATA.\n *\n * The `]]>` split is the whole point: a description that happens to contain the\n * CDATA terminator would otherwise close the section early and produce a\n * document that is malformed in a way that looks like a content bug.\n */\nfunction cdata(value: string): string {\n  // `stripInvalidXmlChars` runs here too. CDATA suspends markup parsing, not the\n  // rule about which code points may appear in a document at all, so a control\n  // character inside a CDATA section is just as fatal as one outside it.\n  const safe = stripInvalidXmlChars(value)\n  return `<![CDATA[${safe.replace(/]]>/g, ']]]]><![CDATA[>')}]]>`\n}\n\n/**\n * RFC 822 date, which RSS 2.0 requires for `pubDate` and `lastBuildDate`.\n *\n * `toUTCString()` produces exactly the shape the spec wants\n * (`Wed, 06 Aug 2026 09:30:00 GMT`), which is why there is no hand-rolled month\n * table here. Input dates always carry an offset (the `IsoDateTime` brand\n * guarantees it), so the conversion to UTC is unambiguous.\n */\nfunction toRfc822(isoDate: string): string {\n  return new Date(isoDate).toUTCString()\n}\n\n/** Newest `dateModified` in the set, compared as instants rather than strings. */\nfunction newestModified(posts: readonly PublishedPost[]): string | undefined {\n  let newest: string | undefined\n  for (const post of posts) {\n    if (newest === undefined || Date.parse(post.dateModified) > Date.parse(newest)) {\n      newest = post.dateModified\n    }\n  }\n  return newest\n}\n\nfunction renderItem(post: PublishedPost): string {\n  const url = postUrl(post.slug)\n  return [\n    '    <item>',\n    `      <title>${escapeXml(post.title)}</title>`,\n    `      <link>${escapeXml(url)}</link>`,\n    // `isPermaLink=\"true\"` says the guid is the canonical URL, which it is.\n    // Readers use it for deduplication, so it must never change for a post.\n    `      <guid isPermaLink=\"true\">${escapeXml(url)}</guid>`,\n    `      <pubDate>${escapeXml(toRfc822(post.datePublished))}</pubDate>`,\n    // `dc:creator` rather than `<author>`: RSS 2.0's `author` element is defined\n    // as an email address, and most authors have a name but no public address.\n    `      <dc:creator>${cdata(post.author.name)}</dc:creator>`,\n    `      <category>${escapeXml(post.category.name)}</category>`,\n    `      <description>${cdata(post.description)}</description>`,\n    '    </item>',\n  ].join('\\n')\n}\n\nexport async function GET(): Promise<Response> {\n  const all = await getAllPosts()\n\n  // Newest first. The source is not contractually required to sort, and a feed\n  // in arbitrary order is a feed that shows subscribers the wrong post first.\n  const posts = [...all]\n    .sort((a, b) => Date.parse(b.datePublished) - Date.parse(a.datePublished))\n    .slice(0, MAX_ITEMS)\n\n  const selfUrl = absoluteUrl(FEED_PATH)\n  const lastBuildDate = newestModified(posts)\n\n  const xml = [\n    '<?xml version=\"1.0\" encoding=\"utf-8\"?>',\n    '<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">',\n    '  <channel>',\n    `    <title>${escapeXml(config.brand.name)}</title>`,\n    `    <link>${escapeXml(absoluteUrl('/blog'))}</link>`,\n    `    <description>${cdata(`Latest posts from ${config.brand.name}.`)}</description>`,\n    // BCP-47 for XML, while `config.locale` is stored in the underscore form\n    // Open Graph wants. `bcp47Locale` is the one place that conversion happens:\n    // a local `.replace('_', '-')` rewrites only the FIRST underscore, so an\n    // extended tag such as `zh_Hans_CN` comes out as `zh-Hans_CN`, which is not\n    // a valid language tag.\n    `    <language>${escapeXml(bcp47Locale())}</language>`,\n    // `atom:link rel=\"self\"` is what tells a reader (and a validator) the\n    // canonical address of this document. Feeds without it get mirrored under\n    // whatever URL happened to serve them.\n    `    <atom:link href=\"${escapeXml(selfUrl)}\" rel=\"self\" type=\"application/rss+xml\" />`,\n    ...(lastBuildDate\n      ? [`    <lastBuildDate>${escapeXml(toRfc822(lastBuildDate))}</lastBuildDate>`]\n      : []),\n    ...posts.map(renderItem),\n    '  </channel>',\n    '</rss>',\n    '',\n  ].join('\\n')\n\n  return new Response(xml, {\n    headers: {\n      'Content-Type': 'application/rss+xml; charset=utf-8',\n      // Advisory only. The authoritative cache lifetime is the `revalidate`\n      // export plus whatever the publish webhook invalidates.\n      'Cache-Control': 'public, max-age=0, must-revalidate',\n    },\n  })\n}\n",
      "type": "registry:page",
      "target": "app/feed.xml/route.ts"
    },
    {
      "path": "registry/blog/app/llms.txt/route.ts",
      "content": "/**\n * `/llms.txt`: the blog as one Markdown index, for agents that ask for it.\n *\n * ---------------------------------------------------------------------------\n * WHAT THIS IS WORTH, HONESTLY\n * ---------------------------------------------------------------------------\n * It is not an SEO lever and nothing here pretends otherwise. Google has said\n * no Search system reads `llms.txt`, and OpenAI's and Google's crawlers do not\n * request it in meaningful volume. If that were the whole picture this file\n * would not exist, because a route that only looks like an optimisation is\n * worse than no route.\n *\n * It exists because two consumers do read it. Perplexity has confirmed it\n * fetches `llms.txt` and uses it to decide which pages are worth retrieving,\n * and Anthropic recommends publishing one and honours it in Claude's retrieval.\n * Those are the two ends of this product's whole thesis: an assistant deciding\n * what to fetch, and an assistant deciding what to cite.\n *\n * So treat it as an agent-readable table of contents, not as a ranking signal.\n * The cost is one cached route generated from the same content source that\n * already produces `sitemap.xml` and `feed.xml`, and the benefit is that a\n * retrieval agent gets titles, URLs, and one-line descriptions in a single\n * request instead of crawling for them.\n *\n * ---------------------------------------------------------------------------\n * THIS IS A CACHED ROUTE HANDLER\n * ---------------------------------------------------------------------------\n * Same mechanism as `app/feed.xml/route.ts` and `app/sitemap.ts`: no\n * request-time API means the response is cached, so a post published without a\n * rebuild does not appear here until something invalidates it.\n * `app/api/publish/route.ts` revalidates this path for that reason, and the\n * `revalidate` export below is the backstop for installs whose webhook was\n * never wired up.\n *\n * @see https://llmstxt.org\n * @see https://docs.agentblog.dev/reference/files\n */\nimport { absoluteUrl, config, postUrl } from '@/lib/config'\nimport { getAllPosts } from '@/lib/posts'\nimport type { PublishedPost } from '@/lib/types'\n\n/**\n * ISR backstop. Hardcoded rather than read from `config.revalidate` because\n * route segment config must be statically analysable.\n */\nexport const revalidate = 3600\n\n/**\n * Markdown is a link label, not a document, so only the characters that would\n * break `[text](url)` are escaped. Escaping more would put backslashes into\n * prose that a model then reads as content.\n */\nfunction escapeLinkText(value: string): string {\n  return value.replace(/([[\\]])/g, '\\\\$1')\n}\n\n/** One line per post, in the `- [title](url): description` form the spec uses. */\nfunction renderPost(post: PublishedPost): string {\n  return `- [${escapeLinkText(post.title)}](${postUrl(post.slug)}): ${collapse(post.description)}`\n}\n\n/**\n * Newlines inside a description would end the list item and silently truncate\n * everything after them, so they are folded to spaces rather than trusted.\n */\nfunction collapse(value: string): string {\n  return value.replace(/\\s+/g, ' ').trim()\n}\n\n/** Posts grouped under their category, categories in first-appearance order. */\nfunction byCategory(posts: readonly PublishedPost[]): Map<string, PublishedPost[]> {\n  const groups = new Map<string, PublishedPost[]>()\n  for (const post of posts) {\n    const existing = groups.get(post.category.name)\n    if (existing) existing.push(post)\n    else groups.set(post.category.name, [post])\n  }\n  return groups\n}\n\nexport async function GET(): Promise<Response> {\n  const all = await getAllPosts()\n\n  // Newest first, exactly as the feed sorts. The source is not contractually\n  // required to sort, and an index whose order changes between requests is an\n  // index a retrieval agent cannot cache.\n  const posts = [...all].sort((a, b) => Date.parse(b.datePublished) - Date.parse(a.datePublished))\n\n  const lines: string[] = [\n    `# ${config.brand.name}`,\n    '',\n    `> ${collapse(`Blog posts from ${config.brand.name}. Every entry below links to a page whose full article text is in the server rendered HTML.`)}`,\n    '',\n  ]\n\n  for (const [category, group] of byCategory(posts)) {\n    lines.push(`## ${category}`, '')\n    for (const post of group) lines.push(renderPost(post))\n    lines.push('')\n  }\n\n  if (posts.length === 0) {\n    lines.push('## Posts', '', 'No posts have been published yet.', '')\n  }\n\n  // `Optional` is the one section name the spec assigns meaning to: it marks\n  // links a consumer may skip when it is short of context. Machine readable\n  // indexes belong there, because they duplicate what is already above.\n  lines.push(\n    '## Optional',\n    '',\n    `- [Sitemap](${absoluteUrl('/sitemap.xml')}): every indexable URL on this site.`,\n    `- [RSS feed](${absoluteUrl('/feed.xml')}): the most recent posts as RSS 2.0.`,\n    `- [Editorial policy](${absoluteUrl('/editorial-policy')}): how these posts are written, reviewed, and corrected.`,\n    '',\n  )\n\n  return new Response(lines.join('\\n'), {\n    headers: {\n      // Plain text, because the path ends in `.txt` and a consumer that sniffs\n      // the extension and the type disagreeing is a consumer that skips it.\n      'Content-Type': 'text/plain; charset=utf-8',\n      // Advisory only. The authoritative cache lifetime is the `revalidate`\n      // export plus whatever the publish webhook invalidates.\n      'Cache-Control': 'public, max-age=0, must-revalidate',\n    },\n  })\n}\n",
      "type": "registry:page",
      "target": "app/llms.txt/route.ts"
    },
    {
      "path": "registry/blog/app/not-found.tsx",
      "content": "/**\n * The 404 page.\n *\n * ---------------------------------------------------------------------------\n * WHY THIS PAGE EXPORTS `metadata` AT ALL\n * ---------------------------------------------------------------------------\n * Because a page that exports nothing inherits everything.\n *\n * With no `metadata` here, Next.js resolved this route against the root layout\n * and shipped the homepage's entire head on every unmatched URL on the site:\n * `<link rel=\"canonical\" href=\"https://yoursite.dev\">`, `og:url` pointing at\n * the homepage, and `og:title` claiming to be it. A 404 that declares itself\n * canonical to the homepage is a consolidation signal, and it is one the HTTP\n * status does not cancel, because a canonical is a statement about identity\n * rather than about availability.\n *\n * The status code is still the primary signal, and it is still the reason this\n * page must never become a \"soft 404\": a page that returns 200 and says \"not\n * found\" in the body. Google treats those as thin content and they are one of\n * the more common causes of a crawl budget quietly draining away.\n *\n * The `metadata` export below is written the way it is for one reason each:\n *\n *   - `robots` carries a `googleBot` block that also says `index: false`.\n *     Metadata merges SHALLOWLY, so writing `robots: { index: false }` on its\n *     own would replace the root layout's whole object, and writing it while\n *     spreading `robotsDefaults` unchanged would leave `googleBot` saying\n *     `index: true`. Googlebot obeys the more specific directive, so that\n *     version reads as noindex to everyone except the crawler it matters most\n *     to. `googleBotDefaults` is spread so `max-snippet: -1` and the preview\n *     limits survive. See https://docs.agentblog.dev/reference/files. This is the same shape\n *     `buildListMetadata` uses for a thin tag page; keep them in step.\n *   - `follow: true` stays on. The recovery links below are the point of the\n *     page, and telling a crawler that reached a dead link to ignore the way\n *     out wastes the one useful thing a 404 can do.\n *   - `alternates: null` and `openGraph: null` are explicit. `undefined` is not\n *     the same thing: an absent key inherits, and only `null` clears. Without\n *     them the canonical and the homepage `og:url` come straight back.\n *   - `title` and `description` are set, and they are load bearing for the Open\n *     Graph tags rather than only for the tab. Next.js re-derives `og:title` and\n *     `og:description` from `title` and `description` in `postProcessMetadata`,\n *     after a file-based `app/opengraph-image.*` has put an `openGraph` object\n *     back on a page that cleared it. So `openGraph: null` alone still shipped a\n *     404 announcing the homepage's headline to every social scraper. Naming the\n *     page here is what stops that.\n *\n *     The block itself no longer writes a card into your app root, so the file\n *     that triggers this is now yours rather than ours. That makes it more\n *     likely to be present, not less: a site with its own social card has one\n *     there by definition.\n *\n * One thing the export does not control: Next.js emits its own\n * `<meta name=\"robots\" content=\"noindex\">` for the not-found route, so the built\n * page carries two robots tags. Crawlers take the union of them and the two\n * agree, so this is untidy rather than wrong. Do not try to remove the first\n * one; it is generated below application code.\n *\n * ---------------------------------------------------------------------------\n * WHY THE PAGE BODY IS A `<div>` AND NOT A `<main>`\n * ---------------------------------------------------------------------------\n * This route renders inside the host application's shell like every other route\n * in the block, so a `<main>` here nests inside the host's `<main>`: invalid\n * HTML, and two `main` landmarks on the page. The block never renders `<main>`\n * anywhere. The contract, and what your root layout owes in return, is written\n * at the top of `app/blog/layout.tsx`.\n *\n * ---------------------------------------------------------------------------\n * WHY IT LISTS RECENT POSTS AND WHY THAT IS WRAPPED IN A TRY\n * ---------------------------------------------------------------------------\n * A 404 that offers nothing is a dead end for a reader who followed a stale\n * link. A handful of real, current posts is the cheapest useful recovery path,\n * and it needs no search box to build.\n *\n * The read is wrapped because this file also renders for every unmatched URL on\n * the site. If the content source is unreachable, an unhandled throw here turns\n * a 404 into a 500, which is a strictly worse answer to the same request.\n *\n * @see https://docs.agentblog.dev/reference/files\n */\nimport type { Metadata } from 'next'\nimport Link from 'next/link'\n\nimport { formatPostDate } from '@/components/blog/byline'\nimport { DISPLAY, EYEBROW, SECTION_HEADING } from '@/components/blog/type-scale'\nimport { blogPath, postPath, sitePath } from '@/lib/config'\nimport { googleBotDefaults } from '@/lib/metadata'\nimport { getAllPosts } from '@/lib/posts'\nimport type { PublishedPost } from '@/lib/types'\nimport { cn } from '@/lib/utils'\n\nexport const metadata: Metadata = {\n  title: 'Page not found',\n  description: 'The page you asked for does not exist. Here is the way back.',\n  robots: { index: false, follow: true, googleBot: { ...googleBotDefaults, index: false } },\n  // `null`, not omitted. See the header: an absent key inherits the root\n  // layout's canonical and the homepage `og:url` onto every 404.\n  alternates: null,\n  openGraph: null,\n}\n\n/** Enough to be a real recovery path, few enough to stay scannable. */\nconst SUGGESTION_COUNT = 5\n\nasync function recentPosts(): Promise<PublishedPost[]> {\n  try {\n    const posts = await getAllPosts()\n    return [...posts]\n      .sort((a, b) => Date.parse(b.datePublished) - Date.parse(a.datePublished))\n      .slice(0, SUGGESTION_COUNT)\n  } catch {\n    // A broken content source must not upgrade a 404 into a 500.\n    return []\n  }\n}\n\nexport default async function NotFound() {\n  const posts = await recentPosts()\n\n  return (\n    // A `<div>`, and it must stay one. See \"WHY THE PAGE BODY IS A `<div>`\" above.\n    <div className=\"mx-auto w-full max-w-(--agentblog-measure) px-6 py-20 lg:py-28\">\n      <p className={EYEBROW}>Error 404</p>\n\n      <h1 className={cn(DISPLAY, 'mt-4')}>We could not find that page</h1>\n\n      <p className=\"text-muted-foreground mt-5 text-lg leading-relaxed text-pretty\">\n        The link may be out of date, or the page may have moved. Everything below still works.\n      </p>\n\n      {/*\n       * Internal hrefs come from the `@/lib/config` path helpers, which are what\n       * apply `config.trailingSlash`. A hardcoded `/blog` on a site configured\n       * with `trailingSlash: true` links to a URL that 308s to `/blog/`, and a\n       * 404 page whose recovery links all redirect is a poor recovery path.\n       *\n       * `/`, `/feed.xml`, and `/sitemap.xml` are literals on purpose: the root is\n       * exempt from the trailing-slash policy, and the helpers never append a\n       * slash to a last segment that looks like a file, so all three are already\n       * in final form. `/editorial-policy` has no helper of its own, so it is the\n       * one href here that a `trailingSlash: true` site has to fix by hand.\n       */}\n      <nav aria-label=\"Primary recovery links\" className=\"mt-10 flex flex-wrap gap-3\">\n        <Link\n          href={blogPath()}\n          className=\"bg-primary text-primary-foreground focus-visible:ring-ring inline-flex items-center rounded-md px-4 py-2 text-sm font-medium focus-visible:ring-2 focus-visible:outline-none\"\n        >\n          Read the blog\n        </Link>\n        <Link\n          href=\"/\"\n          className=\"border-border bg-background text-foreground hover:bg-accent focus-visible:ring-ring inline-flex items-center rounded-md border px-4 py-2 text-sm font-medium focus-visible:ring-2 focus-visible:outline-none\"\n        >\n          Go to the homepage\n        </Link>\n      </nav>\n\n      {posts.length > 0 ? (\n        <section className=\"border-border mt-14 border-t pt-8\">\n          <h2 className={SECTION_HEADING}>Recent posts</h2>\n          <ul className=\"mt-6 flex flex-col gap-5\">\n            {posts.map((post) => (\n              <li key={post.slug}>\n                <Link\n                  href={postPath(post.slug)}\n                  className=\"text-foreground hover:text-primary text-base font-medium underline-offset-4 hover:underline\"\n                >\n                  {post.title}\n                </Link>\n                <p className=\"text-muted-foreground mt-1 text-sm leading-relaxed\">\n                  {post.description}\n                </p>\n                {/* The shared formatter, not a local `toISOString().slice()`.\n                    `toISOString` converts to UTC first, so a post dated\n                    `2026-08-06T22:00:00-05:00` printed that way reads\n                    `2026-08-07` while the `dateTime` attribute beside it still\n                    says the 6th, and the visible text disagrees with the machine\n                    readable one by a day. `formatPostDate` is the one place a\n                    post date becomes a string anywhere in the block. */}\n                <time\n                  dateTime={post.datePublished}\n                  className=\"text-muted-foreground mt-1 block text-xs\"\n                >\n                  {formatPostDate(post.datePublished)}\n                </time>\n              </li>\n            ))}\n          </ul>\n        </section>\n      ) : null}\n\n      <section className=\"border-border mt-14 border-t pt-8\">\n        <h2 className={SECTION_HEADING}>Other places to look</h2>\n        <ul className=\"text-muted-foreground mt-6 flex flex-col gap-3 text-sm\">\n          <li>\n            <Link href=\"/feed.xml\" className=\"hover:text-foreground underline underline-offset-4\">\n              Subscribe to the RSS feed\n            </Link>\n          </li>\n          <li>\n            <Link\n              href={sitePath('/editorial-policy')}\n              className=\"hover:text-foreground underline underline-offset-4\"\n            >\n              Read our editorial policy\n            </Link>\n          </li>\n          <li>\n            <Link\n              href=\"/sitemap.xml\"\n              className=\"hover:text-foreground underline underline-offset-4\"\n            >\n              Browse the full sitemap\n            </Link>\n          </li>\n        </ul>\n      </section>\n    </div>\n  )\n}\n",
      "type": "registry:page",
      "target": "app/not-found.tsx"
    }
  ],
  "categories": [
    "blog",
    "seo"
  ],
  "type": "registry:block"
}