HomeTutorialsFail the deploy that hides your site from AI search

Tutorial · Intermediate

Fail the deploy that hides your site from AI search

After every production deploy and every Monday, this job audits your live pages and fails with a readable report when an AI answer engine is blocked in robots.txt, a page turns noindex, llms.txt disappears or the content stops rendering without JavaScript. One JSON policy file and one dependency-free Node script.

15 minNode 20+GitHub Actions$0.25 per audited page

What you get

A red check on the deploy, one annotation per problem, and a scorecard in the job summary. Here a release shipped a robots.txt rule that shuts out OpenAI's search crawler and a homepage with noindex:

An example site; the messages are exactly what the script prints.

Why a gate, and why after the deploy

None of these regressions show up in code review, because most of them do not live in your code:

  • A robots.txt from staging ships to production, Disallow: / for everyone.
  • Someone blocks OAI-SearchBot while meaning to block GPTBot, OpenAI's training crawler.
  • A CDN or firewall setting starts blocking AI crawlers, or challenges every client that is not a browser.
  • A CMS plugin update puts noindex on the homepage.
  • A frontend migration moves the main content into client-side JavaScript, and fetchers that do not run it see an empty shell.

AI answer engines cite what their crawlers can read. A blocked crawler raises no error anywhere; you only see fewer citations weeks later. These are properties of the live site, so the check runs against production: after each deploy, and every Monday for the changes that never go through git.

What the gate checks

The AI Readiness Audit actor fetches each page the way an AI crawler does, without running JavaScript, and returns every check with its evidence. Your policy decides which results fail the build:

Policy keyFails when
allowrobots.txt disallows a listed crawler for the page's path (RFC 9309 matching, per user-agent group)
blocka listed crawler may crawl although the policy says it must not, for teams that opt out of AI training
mustNotFaila listed audit check fails: home-reachable, robots-reachable, indexable (noindex), content-without-js
requireLlmsTxt/llms.txt is missing
allowBotProtected(when false) the page answers with a bot challenge instead of content
minScorethe 0–100 score drops below the floor
Answer engines are not training crawlers

OAI-SearchBot, ChatGPT-User, Claude-SearchBot, Claude-User, PerplexityBot and Perplexity-User fetch pages to answer people and cite them. GPTBot, ClaudeBot and CCBot collect training data. Blocking the second group keeps you out of training sets; blocking the first keeps you out of the answers.

1Write the policy

Save it as .github/ai-readiness.json:

.github/ai-readiness.jsonJSONDownload
{
  "urls": ["https://www.example.com/", "https://www.example.com/docs/"],
  "allow": [
    "OAI-SearchBot", "ChatGPT-User", "Claude-SearchBot", "Claude-User",
    "PerplexityBot", "Perplexity-User", "Googlebot", "Bingbot"
  ],
  "block": [],
  "mustNotFail": [
    "home-reachable", "robots-reachable", "indexable", "content-without-js"
  ],
  "requireLlmsTxt": true,
  "allowBotProtected": false,
  "minScore": 70,
  "maxChargeUsd": 1
}
  • urls: the homepage and one page per template that matters, for example a docs page and a blog post. Robots rules are matched per path, so a rule that only hits /docs/ is caught only if a /docs/ page is in the list.
  • allow: the crawlers that must reach you: the answer engines above plus the search engines. block stays empty unless you opt out of training, as in ["GPTBot", "CCBot"].
  • mustNotFail: only the checks that mean a real regression. Warnings, such as a long meta description, stay in the report and never fail the build.
  • maxChargeUsd: a hard cap per run. Keep it at or above $0.25 times the number of URLs.

2Add the gate script

Save it as scripts/ai-readiness-gate.mjs. It needs Node 20 or later and nothing else: no package.json, no install step, and it fits any repository whatever its language.

ai-readiness-gate.mjsJavaScriptDownload
#!/usr/bin/env node
// AI-readiness gate: audits your live pages with agentsgearbox/ai-readiness-audit on
// Apify and fails the build when they break your policy file. Node 20+, no dependencies.
// Env: APIFY_TOKEN, optional POLICY (default .github/ai-readiness.json). In GitHub
// Actions it also writes the job summary and one ::error annotation per problem.
import { appendFileSync, readFileSync } from 'node:fs';

const API = 'https://api.apify.com/v2';
const ACTOR = 'agentsgearbox~ai-readiness-audit';
const policyFile = process.env.POLICY ?? '.github/ai-readiness.json';
const policy = JSON.parse(readFileSync(policyFile, 'utf8'));
const token = process.env.APIFY_TOKEN;
if (!token || !policy.urls?.length) {
  console.error('Set APIFY_TOKEN and list at least one URL under "urls" in the policy.');
  process.exit(2);
}
const headers = { authorization: `Bearer ${token}`, 'content-type': 'application/json' };

/** One Apify API call. GETs are retried on rate limits, server errors and network
 *  failures; the POST that starts the run is not, since a retry could pay twice. */
async function api(path, init = {}) {
  const attempts = init.method === 'POST' ? 1 : 4;
  for (let i = 1; ; i++) {
    const res = await fetch(API + path, { ...init, headers })
      .catch((error) => ({ ok: false, status: 0, text: async () => error.message }));
    if (res.ok) return res.json();
    const transient = res.status === 0 || res.status === 429 || res.status >= 500;
    if (i >= attempts || !transient) {
      const where = `${init.method ?? 'GET'} ${path.split('?')[0]}`;
      throw new Error(`${where}: HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);
    }
    await new Promise((resolve) => setTimeout(resolve, 2000 * i));
  }
}

// 1. Run the audit with a spending cap and a run timeout. The API holds each request
//    for up to 60 s while it waits, so the loop below polls without spinning.
const bots = [...new Set([...(policy.allow ?? []), ...(policy.block ?? [])])];
const input = {
  urls: policy.urls,
  checkLlmsLinks: true,
  includeFixes: true,
  ...(bots.length ? { aiBots: bots } : {}),
};
const query = new URLSearchParams({
  maxTotalChargeUsd: String(policy.maxChargeUsd ?? 1),
  timeout: '600',
  waitForFinish: '60',
});
const body = JSON.stringify(input);
let { data: run } = await api(`/actors/${ACTOR}/runs?${query}`, { method: 'POST', body });
while (run.status === 'READY' || run.status === 'RUNNING') {
  ({ data: run } = await api(`/actor-runs/${run.id}?waitForFinish=60`));
}
const runUrl = `https://console.apify.com/actors/${run.actId}/runs/${run.id}`;
if (run.status !== 'SUCCEEDED') {
  console.error(`The audit run ended ${run.status}: ${runUrl}`);
  process.exit(2);
}
const rows = await api(`/datasets/${run.defaultDatasetId}/items?clean=true`);

// 2. Hold every page to the policy. Only failures and hard rules count; warnings stay
//    in the report.
const results = new Map(rows
  .filter((r) => r.type === 'audit' || r.type === 'error')
  .map((r) => [r.requestedUrl, r]));
const problems = [];
for (const url of policy.urls) {
  const audit = results.get(url);
  const flag = (message) => problems.push({ url, message });
  if (!audit) {
    flag('not audited: a duplicate of another URL in the list, '
      + 'or the run hit maxChargeUsd');
    continue;
  }
  if (audit.type === 'error') {
    flag(`audit failed: ${audit.error}`);
    continue;
  }
  // A bot challenge hides the page itself; robots.txt and llms.txt usually stay
  // readable and are still checked.
  const challenged = audit.status === 'BOT_PROTECTED';
  if (challenged && !policy.allowBotProtected) {
    flag('the page answers with a bot challenge, so AI fetchers without '
      + 'a verified-bot exemption get nothing');
  }
  const robots = audit.facts.robots.bots;
  for (const bot of policy.allow ?? []) {
    const rule = robots[bot];
    if (rule && !rule.allowed) {
      flag(`${bot} is blocked by robots.txt `
        + `("${rule.rule}", group "${rule.matchedGroup}")`);
    }
  }
  for (const bot of policy.block ?? []) {
    if (robots[bot]?.allowed) {
      flag(`${bot} may crawl, but the policy says it must be blocked`);
    }
  }
  for (const id of policy.mustNotFail ?? []) {
    const check = audit.checks.find((c) => c.id === id);
    if (check?.status === 'fail' && !(challenged && id === 'home-reachable')) {
      const evidence = check.evidence ? ` (${clip(check.evidence, 160)})` : '';
      flag(`${check.label}: ${check.value}${evidence}`);
    }
  }
  if (policy.requireLlmsTxt && audit.llmsTxt === 'missing') flag('llms.txt is missing');
  const floor = policy.minScore ?? 0;
  if (!challenged && audit.score != null && audit.score < floor) {
    flag(`score ${audit.score} is below the policy minimum of ${floor}`);
  }
}

// 3. Report: a table in the job summary, annotations on the run, a short text in the
//    log, and the exit code.
const n = problems.length;
const audited = policy.urls.map((url) => [url, results.get(url)]);
const summary = [
  `### AI-readiness gate: ${n ? `❌ ${plural(n, 'problem')}` : '✅ passed'}`,
  '',
  '| Page | Score | Answer engines allowed | llms.txt | Text without JS | JSON-LD |',
  '|---|---:|---|---|---|---|',
  ...audited.map(([url, a]) => tableRow(url, a)),
  ...(n ? ['', ...problems.map((p) => `- ❌ ${p.url}: ${p.message}`)] : []),
  '',
  `<sub>[AI Readiness Audit](https://apify.com/agentsgearbox/ai-readiness-audit) · `
    + `[Apify run](${runUrl})</sub>`,
].join('\n');
const { GITHUB_ACTIONS, GITHUB_STEP_SUMMARY } = process.env;
if (GITHUB_STEP_SUMMARY) appendFileSync(GITHUB_STEP_SUMMARY, `${summary}\n`);
if (GITHUB_ACTIONS) {
  for (const p of problems) {
    const message = escapeData(`${p.url}: ${p.message}`);
    console.log(`::error title=AI-readiness gate::${message}`);
  }
}
for (const [url, a] of audited) {
  const mine = problems.filter((p) => p.url === url);
  const facts = a?.type === 'audit'
    ? `  score ${a.score ?? '–'} ${a.grade ?? ''}`
      + ` · answer engines ${a.aiSearchBotsAllowed} · llms.txt ${a.llmsTxt}`
    : '';
  console.log(`${mine.length ? '✗' : '✓'} ${url}${facts}`);
  for (const p of mine) console.log(`    ${p.message}`);
}
console.log(`\n${n ? `Failed: ${plural(n, 'problem')}.` : 'Passed.'} Run: ${runUrl}`);
process.exitCode = n ? 1 : 0;

function tableRow(url, a) {
  if (a?.type !== 'audit') return `| ${url} | – | – | – | – | – |`;
  const words = a.facts.readability?.words;
  const shown = words == null ? '–' : `${words.toLocaleString('en-US')} words`;
  const jsonLd = a.facts.structure.jsonLdTypes.join(', ') || 'none';
  return `| ${url} | ${a.score ?? '–'} ${a.grade ?? ''} | ${a.aiSearchBotsAllowed} `
    + `| ${a.llmsTxt} | ${a.jsOnly ? 'no' : shown} | ${jsonLd} |`;
}
function plural(count, noun) {
  return `${count} ${noun}${count === 1 ? '' : 's'}`;
}
function clip(text, limit) {
  return text.length <= limit ? text : `${text.slice(0, limit - 1)}…`;
}
function escapeData(text) { // workflow commands need %, CR and LF encoded
  return text.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');
}

The parts worth a second look

Starting and waiting. The run starts with a spending cap and a timeout of its own, then the script polls with waitForFinish=60, which holds each request for up to a minute instead of spinning. Reads are retried on rate limits, server errors and network failures. The POST that starts the run is not, because a retried POST could start, and pay for, a second audit.

ai-readiness-gate.mjs · 1. run the auditJavaScript
// 1. Run the audit with a spending cap and a run timeout. The API holds each request
//    for up to 60 s while it waits, so the loop below polls without spinning.
const bots = [...new Set([...(policy.allow ?? []), ...(policy.block ?? [])])];
const input = {
  urls: policy.urls,
  checkLlmsLinks: true,
  includeFixes: true,
  ...(bots.length ? { aiBots: bots } : {}),
};
const query = new URLSearchParams({
  maxTotalChargeUsd: String(policy.maxChargeUsd ?? 1),
  timeout: '600',
  waitForFinish: '60',
});
const body = JSON.stringify(input);
let { data: run } = await api(`/actors/${ACTOR}/runs?${query}`, { method: 'POST', body });
while (run.status === 'READY' || run.status === 'RUNNING') {
  ({ data: run } = await api(`/actor-runs/${run.id}?waitForFinish=60`));
}
const runUrl = `https://console.apify.com/actors/${run.actId}/runs/${run.id}`;
if (run.status !== 'SUCCEEDED') {
  console.error(`The audit run ended ${run.status}: ${runUrl}`);
  process.exit(2);
}
const rows = await api(`/datasets/${run.defaultDatasetId}/items?clean=true`);

Judging. Results are matched to your URLs by requestedUrl, so a URL that never got audited is a failure, not a silent pass. Only failures and hard policy rules count. A page behind a bot challenge gets one clear message rather than a cascade, and its score is skipped, because a page the audit could not read has no meaningful score.

ai-readiness-gate.mjs · 2. judge each pageJavaScript
// 2. Hold every page to the policy. Only failures and hard rules count; warnings stay
//    in the report.
const results = new Map(rows
  .filter((r) => r.type === 'audit' || r.type === 'error')
  .map((r) => [r.requestedUrl, r]));
const problems = [];
for (const url of policy.urls) {
  const audit = results.get(url);
  const flag = (message) => problems.push({ url, message });
  if (!audit) {
    flag('not audited: a duplicate of another URL in the list, '
      + 'or the run hit maxChargeUsd');
    continue;
  }
  if (audit.type === 'error') {
    flag(`audit failed: ${audit.error}`);
    continue;
  }
  // A bot challenge hides the page itself; robots.txt and llms.txt usually stay
  // readable and are still checked.
  const challenged = audit.status === 'BOT_PROTECTED';
  if (challenged && !policy.allowBotProtected) {
    flag('the page answers with a bot challenge, so AI fetchers without '
      + 'a verified-bot exemption get nothing');
  }
  const robots = audit.facts.robots.bots;
  for (const bot of policy.allow ?? []) {
    const rule = robots[bot];
    if (rule && !rule.allowed) {
      flag(`${bot} is blocked by robots.txt `
        + `("${rule.rule}", group "${rule.matchedGroup}")`);
    }
  }
  for (const bot of policy.block ?? []) {
    if (robots[bot]?.allowed) {
      flag(`${bot} may crawl, but the policy says it must be blocked`);
    }
  }
  for (const id of policy.mustNotFail ?? []) {
    const check = audit.checks.find((c) => c.id === id);
    if (check?.status === 'fail' && !(challenged && id === 'home-reachable')) {
      const evidence = check.evidence ? ` (${clip(check.evidence, 160)})` : '';
      flag(`${check.label}: ${check.value}${evidence}`);
    }
  }
  if (policy.requireLlmsTxt && audit.llmsTxt === 'missing') flag('llms.txt is missing');
  const floor = policy.minScore ?? 0;
  if (!challenged && audit.score != null && audit.score < floor) {
    flag(`score ${audit.score} is below the policy minimum of ${floor}`);
  }
}

Exit codes. 0 passed, 1 the policy failed, 2 the gate could not run (missing token, a run that did not succeed). CI treats all non-zero codes as failures; the difference tells a person where to look.

3Run it once by hand

TerminalShell
export APIFY_TOKEN=apify_api_...  # Console > Settings > API & Integrations
node scripts/ai-readiness-gate.mjs

On this site, with the policy above (URLs changed to ours), the gate passes:

✓ https://agentsgearbox.com/  score 100 A · answer engines 8/8 · llms.txt valid
✓ https://agentsgearbox.com/scrapers/  score 100 A · answer engines 8/8 · llms.txt valid

Passed. Run: https://console.apify.com/actors/ymMCRXrfOKJowYOzn/runs/kQ3vN8xR2pLm7TzYw

Add "block": ["GPTBot", "CCBot"] to the policy and it fails, correctly: this site lets training crawlers in.

✗ https://agentsgearbox.com/  score 100 A · answer engines 8/8 · llms.txt valid
    GPTBot may crawl, but the policy says it must be blocked
    CCBot may crawl, but the policy says it must be blocked
✗ https://agentsgearbox.com/scrapers/  score 100 A · answer engines 8/8 · llms.txt valid
    GPTBot may crawl, but the policy says it must be blocked
    CCBot may crawl, but the policy says it must be blocked

Failed: 4 problems. Run: https://console.apify.com/actors/ymMCRXrfOKJowYOzn/runs/Tz7wYq2LmB9xKp4Rc

4Wire it into GitHub Actions

Save the workflow as .github/workflows/ai-readiness.yml and change Deploy to the name of the workflow that deploys production:

.github/workflows/ai-readiness.ymlYAMLDownload
name: AI readiness

on:
  workflow_run:
    workflows: [Deploy]  # the name of your production deploy workflow
    types: [completed]
    branches: [main]
  schedule:
    - cron: "41 6 * * 1"  # Mondays: changes made outside git (CDN, CMS plugins)
  workflow_dispatch:

concurrency: ai-readiness  # one audit at a time; a newer deploy waits its turn

jobs:
  gate:
    if: >-
      github.event_name != 'workflow_run' ||
      github.event.workflow_run.conclusion == 'success'
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 24
      - run: node scripts/ai-readiness-gate.mjs
        env:
          APIFY_TOKEN: ${{ secrets.APIFY_TOKEN }}
TerminalShell
gh secret set APIFY_TOKEN       # paste the token when asked
gh workflow run "AI readiness"  # first audit now, without waiting for a deploy
  • workflow_run starts the gate after your deploy workflow finishes on main, and the if: skips deploys that failed.
  • The Monday schedule catches what never goes through git: a CDN toggle, a CMS plugin update, a robots.txt edited on the server.
  • A CDN that caches HTML or robots.txt can serve the previous version for a few minutes after a deploy. If yours does, add a sleep 120 step before the gate.

If the deploy runs as a job in the same workflow, add the gate as a job after it instead:

in your deploy workflowYAML
  ai-readiness:  # add to the jobs of the workflow that deploys
    needs: deploy
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: node scripts/ai-readiness-gate.mjs  # Node comes preinstalled
        env:
          APIFY_TOKEN: ${{ secrets.APIFY_TOKEN }}

Hosts that deploy outside Actions, such as Vercel, Netlify or Cloudflare Pages, report deployments back to GitHub. Trigger on deployment_status and run the job only when github.event.deployment_status.state is success for your production environment.

What it costs

The audit costs $0.25 per page, and the first audit each month is free for every Apify account. Two URLs on twenty production deploys and four Mondays make 48 audits, about $12 a month. To spend less, keep the deploy trigger on the homepage only and audit the full list on Mondays, or gate only the deploys that touch robots.txt, headers or rendering. Paid Apify plans pay less per audit, up to 40% less on Gold.

Running it for real

  • Fail on failures, report the rest. A gate that fails on warnings teaches people to ignore it. The policy only fails on regressions; everything else stays readable in the job summary.
  • Bot protection. The audit fetches from a datacenter, like most AI crawlers. If your firewall challenges it, the gate fails, because crawlers without an exemption hit the same wall. If you deliberately let verified AI crawlers through, set allowBotProtected to true: robots.txt and llms.txt are still checked.
  • Not on previews. Preview deployments usually send noindex on purpose. Point this policy at production only.
  • One more cheap layer. A pull-request check that lints the robots.txt in your repository catches the obvious mistakes before they deploy; this gate catches everything that only exists on the live site.

Troubleshooting

"not audited: a duplicate of another URL in the list"

The actor audits each host and path once, so https://example.com and https://example.com/ count as one page. Keep one spelling per page. If the URLs are distinct, the run hit maxChargeUsd: raise it.

"audit failed: Site unreachable: timeout"

The page did not answer within 20 seconds from Apify's datacenter. If it is up for you, check whether your firewall rate-limits or blocks datacenter traffic: AI crawlers come from datacenters too.

"the page answers with a bot challenge"

See bot protection above. A 403 with a challenge page means plain HTTPS clients cannot read the page; decide whether that is your policy, then set allowBotProtected to match.

Exit code 2: "The audit run ended TIMED-OUT"

A page took longer than the run's ten-minute limit. Check the run linked in the log; it usually means one URL in the list hangs.