If you ask ChatGPT the same buying question five times, you can get five different lists of products. So a tracker that asks once and reports "you rank 3rd" is reporting noise.
This post builds the version that doesn't do that. It is a small Node project that stores your questions, runs each one several times, extracts brand mentions and cited URLs, and reports how often you appear with an honest error range. It also checks whether AI crawlers can read your site at all.
It's the hands-on follow-up to our overview of how AI visibility checkers like geo.new and Is Agentic score a website. That post explains what to measure. This one is the code.
What I ran, and what I didn't. The tracker, the extraction, the metrics and the crawler audit ran here, with 6 passing tests and real printed output. The model in the demo is a seeded fake, so the numbers are invented to exercise the code, not measurements of any real assistant. The OpenRouter provider is written against its documented request shape but I did not call it. Treat it as a starting point.
The verdict first
- One answer proves nothing. Run every prompt several times and report a rate with an interval, not a rank.
- Keep three numbers apart: mention rate (you are named), recommendation rate (you are named near the top), and share of voice (your slice of all brand mentions). They answer different questions and move independently.
- Store the raw answer. A score without the answer behind it can't be debugged.
- Cited domains are the most actionable output. They show which sites feed the answers you care about.
- Check crawler access first. If the bots can't read your site, no amount of content work helps.
- Never show an API-only result as "what ChatGPT says". Consumer apps add search, memory and personalisation that a bare API call doesn't.
What we're building
prompts (20 to 200 buyer questions)
│
▼
runner ── each prompt × N attempts × each provider
│
▼
SQLite: prompts → runs → mentions + citations
│
▼
metrics: mention rate ± interval · share of voice · stability · cited domains
│
▼
human review → fix content or access → run againBeside that sits a separate check: can AI crawlers fetch your pages? That one reads your robots.txt.
Stack: plain Node 22 (ES modules), the built-in node:sqlite module, no dependencies. Node marks node:sqlite as experimental, so swap in better-sqlite3 or Postgres if that bothers you. Nothing else in the code depends on it.
Repo: [REPO LINK: add once pushed]
Step 1: Write buyer questions, not keywords
Google keywords and AI prompts are different shapes. People type "best CRM", but they ask an assistant "which CRM should two developers use for a SaaS?". Build your list from real questions: sales calls, support tickets, Reddit threads, review sites and your Search Console queries.
Give each prompt a category and a flag for whether it names your brand:
| Category | Example | Branded? |
|---|---|---|
| Use case | Which CRM should two developers use for a SaaS? | No |
| Alternatives | Cheaper alternative to HubSpot for a small agency? | No |
| Pricing | Best CRM under $50 a month? | No |
| Brand check | What does Acme CRM offer? | Yes |
The branded flag matters. If someone already types your name, that's a different situation from a stranger asking a general question. All the headline metrics below use non-branded prompts only. Branded prompts are for a different check: whether the assistant describes you accurately.
Start with 20 prompts. A few hundred is better, and Ahrefs argues that tracking only 50 to 100 queries is too small for reliable share-of-voice numbers, in its piece on why AI can't be tracked like traditional search.
Step 2: The schema
Four tables. The structure is what keeps the evidence.
// src/db.js
import { DatabaseSync } from "node:sqlite";
export function openDb(path = ":memory:") {
const db = new DatabaseSync(path);
db.exec(`
CREATE TABLE IF NOT EXISTS prompts (
id INTEGER PRIMARY KEY,
question TEXT NOT NULL,
category TEXT NOT NULL,
branded INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS runs (
id INTEGER PRIMARY KEY,
prompt_id INTEGER NOT NULL REFERENCES prompts(id),
provider TEXT NOT NULL,
model TEXT NOT NULL,
attempt INTEGER NOT NULL,
answer TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS mentions (
id INTEGER PRIMARY KEY,
run_id INTEGER NOT NULL REFERENCES runs(id),
brand TEXT NOT NULL,
position INTEGER NOT NULL -- 1 = first brand named in the answer
);
CREATE TABLE IF NOT EXISTS citations (
id INTEGER PRIMARY KEY,
run_id INTEGER NOT NULL REFERENCES runs(id),
url TEXT NOT NULL,
domain TEXT NOT NULL
);
`);
return db;
}Three choices worth copying:
attemptexists because every prompt runs more than once.modelstores the model ID the provider reports back, because providers can change what sits behind a name. Without it, two runs weeks apart may not be comparable.positionrecords the order brands appear in. It's a cheap proxy for "named first", which is a weak form of recommendation.
Step 3: A provider is one small function
The rest of the app shouldn't care which model answers. A provider is an async function that takes a question and returns the model ID and the answer.
// src/providers.js
export function openRouterProvider({ apiKey, model }) {
return async (question) => {
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model,
messages: [{ role: "user", content: question }],
}),
});
if (!res.ok) throw new Error(`OpenRouter ${res.status}`);
const json = await res.json();
return {
model: json.model ?? model,
answer: json.choices?.[0]?.message?.content ?? "",
};
};
}OpenRouter is convenient because one integration reaches many models. For a real run, add retries, rate limits and a token budget. The same signature works for the official OpenAI, Anthropic and Google SDKs.
For tests, use a fake that's seeded so every run is repeatable:
export function fakeProvider({ seed = 1, script }) {
let state = seed;
const rand = () => {
state = (state * 1664525 + 1013904223) % 4294967296;
return state / 4294967296;
};
return async (question) => ({ model: "fake-1", answer: script(question, rand) });
}The limit you can't code around
An API answer is not the same product as the consumer app. The app can add live search, memory and personalisation. Ahrefs makes the same point: assistants tailor answers to location, context and past conversations, and the same prompt can return different brands each time.
So keep two kinds of evidence and label them:
- API runs: repeatable and cheap, good for hundreds of prompts and trend lines.
- Consumer-app checks: a small, periodic, manual sample of what a user actually sees, including the citations shown.
Never publish an API-only number as "what ChatGPT recommends".
Step 4: Run every prompt more than once
// src/runner.js
import { extractMentions, extractCitations } from "./extract.js";
export async function runAll({ db, prompts, provider, providerName, brands, attempts = 5 }) {
const insPrompt = db.prepare(
"INSERT INTO prompts (question, category, branded) VALUES (?, ?, ?) RETURNING id"
);
const insRun = db.prepare(
"INSERT INTO runs (prompt_id, provider, model, attempt, answer) VALUES (?, ?, ?, ?, ?) RETURNING id"
);
const insMention = db.prepare("INSERT INTO mentions (run_id, brand, position) VALUES (?, ?, ?)");
const insCite = db.prepare("INSERT INTO citations (run_id, url, domain) VALUES (?, ?, ?)");
for (const p of prompts) {
const { id: promptId } = insPrompt.get(p.question, p.category, p.branded ? 1 : 0);
for (let attempt = 1; attempt <= attempts; attempt++) {
const { model, answer } = await provider(p.question);
const { id: runId } = insRun.get(promptId, providerName, model, attempt, answer);
for (const m of extractMentions(answer, brands)) insMention.run(runId, m.brand, m.position);
for (const c of extractCitations(answer)) insCite.run(runId, c.url, c.domain);
}
}
}The cost is easy to estimate: prompts × attempts × models × tokens per answer. 100 prompts, 5 attempts and 3 models is 1,500 calls a run. Work out the dollar figure from each provider's current price list, and if you want a quick estimate for the whole stack, the StackBudget calculator turns a repo into a running-cost estimate.
Step 5: Extract mentions and citations without a second LLM call
An LLM extractor is flexible but costs money and can be wrong in ways you can't see. For the basics, a deterministic pass is cheaper and auditable.
// src/extract.js
export function extractMentions(answer, brands) {
const found = [];
for (const brand of brands) {
const re = new RegExp(`\\b${escapeRe(brand.name)}\\b`, "i");
const m = re.exec(answer);
if (m) found.push({ brand: brand.name, index: m.index });
}
found.sort((a, b) => a.index - b.index);
return found.map((f, i) => ({ brand: f.brand, position: i + 1 }));
}
export function extractCitations(answer) {
const urls = answer.match(/https?:\/\/[^\s)\]>"']+/g) ?? [];
const seen = new Set();
const out = [];
for (const raw of urls) {
const url = raw.replace(/[.,;]+$/, "");
if (seen.has(url)) continue;
seen.add(url);
try {
out.push({ url, domain: new URL(url).hostname.replace(/^www\./, "") });
} catch { /* skip malformed */ }
}
return out;
}
function escapeRe(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}The tests check the two things that usually break: word boundaries (so "Nimbus" doesn't match "Nimbuses") and trailing punctuation on URLs.
Use an LLM extractor later for what regex can't see: sentiment, the reason a product was recommended, and whether a stated price or feature is wrong. When you do, validate its output against the stored raw answer.
One caveat. A model can cite sources in its own text, or a search layer can attach sources separately. A plain API response may hold neither. Your citation table is only as complete as what the provider returns.
Step 6: Three metrics, kept apart
This is where simple trackers go wrong. Mention, recommendation and share of voice are different numbers.
| Metric | Question it answers | How the code defines it |
|---|---|---|
| Mention rate | Does the assistant name us at all? | Runs naming the brand ÷ all non-branded runs |
| Named-first rate | Are we at the top of the list? | Same, but only where position = 1 |
| Share of voice | How big is our slice of the conversation? | Our mentions ÷ all tracked-brand mentions |
Named-first is a rough stand-in for recommendation. A real recommendation judgement ("suits a two-person team") needs the LLM extractor from Step 5.
Put error bars on every rate
A rate from 60 runs is not exact. The Wilson score interval gives an honest range for a proportion and behaves well with small samples:
// src/metrics.js
export function wilson(successes, n, z = 1.96) {
if (n === 0) return { rate: 0, low: 0, high: 0 };
const p = successes / n;
const denom = 1 + (z * z) / n;
const centre = (p + (z * z) / (2 * n)) / denom;
const margin = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / denom;
return { rate: p, low: Math.max(0, centre - margin), high: Math.min(1, centre + margin) };
}Then the queries, restricted to non-branded prompts:
export function mentionRate(db, brand, { topN = Infinity } = {}) {
const total = db.prepare(
`SELECT COUNT(*) AS n FROM runs r JOIN prompts p ON p.id = r.prompt_id WHERE p.branded = 0`
).get().n;
const hit = db.prepare(
`SELECT COUNT(DISTINCT r.id) AS n
FROM runs r JOIN prompts p ON p.id = r.prompt_id
JOIN mentions m ON m.run_id = r.id
WHERE p.branded = 0 AND m.brand = ? AND m.position <= ?`
).get(brand, topN).n;
return { hit, total, ...wilson(hit, total) };
}
export function shareOfVoice(db) {
const rows = db.prepare(
`SELECT m.brand AS brand, COUNT(*) AS mentions
FROM mentions m JOIN runs r ON r.id = m.run_id JOIN prompts p ON p.id = r.prompt_id
WHERE p.branded = 0 GROUP BY m.brand ORDER BY mentions DESC`
).all();
const sum = rows.reduce((a, r) => a + r.mentions, 0);
return rows.map((r) => ({ brand: r.brand, mentions: r.mentions, share: sum ? r.mentions / sum : 0 }));
}Run it
The demo uses three made-up brands and a seeded fake model where one brand is named about 40% of the time. 3 non-branded prompts × 20 attempts is 60 runs:
npm run demoMention rate: 25/60 = 42% (95% interval 30% to 54%)
Named first: 15/60 = 25% (95% interval 16% to 37%)
Share of voice: Rivalo 41% | Nimbus 41% | Acme CRM 17%Read that carefully, because it shows why you keep the metrics apart:
- Acme CRM is named in 42% of runs, which sounds decent.
- Its share of voice is only 17%, because each answer also names the other two brands. Appearing often and owning the conversation are different things.
- The interval is wide: "30% to 54%". If next month's number is 48%, that is not evidence of improvement. It's inside the noise.
That last point is the main reason to repeat runs. A single answer, or a small prompt set, can't separate a real change from chance.
The same data also lets you check stability per prompt, meaning how many of the 20 attempts included you:
export function stabilityByPrompt(db, brand) {
return db.prepare(
`SELECT p.question AS question,
COUNT(DISTINCT r.id) AS attempts,
COUNT(DISTINCT m.run_id) AS appeared
FROM prompts p JOIN runs r ON r.prompt_id = p.id
LEFT JOIN mentions m ON m.run_id = r.id AND m.brand = ?
WHERE p.branded = 0 GROUP BY p.id ORDER BY appeared DESC`
).all(brand);
}In the demo, the three prompts showed 9, 9 and 7 appearances out of 20. A prompt where you appear 18 of 20 times is a strength. One where you appear 2 of 20 is a gap worth a page.
Scope matters too. Ahrefs gives an example where one brand held a 92.8% share across a narrow CRM subtopic but only 3.6% across the whole CRM market. So always say which prompt set a share of voice number covers.
[ADD YOUR STORY: run this on ihatereading.in, or one of your own products, with 20 real buyer questions and share what the mention rate and cited domains looked like. Real numbers from you are worth more than any rule here.]
Step 7: Read the cited domains
The citation table answers a question keyword tools can't: which sites does the assistant lean on for the questions my buyers ask?
export function topCitedDomains(db, limit = 5) {
return db.prepare(
`SELECT c.domain AS domain, COUNT(*) AS citations
FROM citations c JOIN runs r ON r.id = c.run_id JOIN prompts p ON p.id = r.prompt_id
WHERE p.branded = 0 GROUP BY c.domain ORDER BY citations DESC LIMIT ?`
).all(limit);
}On the fake data it prints two domains, with 33 and 27 citations. Real data will be messier. Once you have it:
- Group by type: directories, review sites, Reddit, GitHub, docs, comparison blogs.
- Open the top pages. Why is this one cited? A pricing table, a benchmark, a clear comparison?
- Check whether you're on them. If a page that keeps getting cited doesn't mention your product, that's an outreach or listing opportunity.
- Check whether you're accurate on them. An old price on a cited page becomes an old price in the answer.
Don't assume one backlink will change an answer. The aim is for the sources buyers' questions pull from to describe you accurately and completely.
This is also why directories and aggregators matter for AI visibility. If you're launching something, 393 SaaS directories and the agent that has to use them covers the submission side, and the SaaS directories list is where to start.
Step 8: Can AI crawlers read your site?
You can run a thousand prompts and still lose if the bots that feed those assistants are blocked. This is a robots.txt problem, and it's quick to check.
The user agents differ by purpose, and the vendors document them:
| Bot | Vendor | What it does, per the vendor's docs |
|---|---|---|
| OAI-SearchBot | OpenAI | Surfaces sites in ChatGPT's search features. Per OpenAI, opting out means you won't appear in ChatGPT search answers, except as navigational links |
| GPTBot | OpenAI | Crawls content that may be used to train OpenAI's models |
| ChatGPT-User | OpenAI | Fetches pages for user-initiated actions. OpenAI notes robots.txt rules may not apply to it |
| Claude-SearchBot | Anthropic | Crawls to improve search result relevance and accuracy |
| Claude-User | Anthropic | Fetches pages when a person asks Claude something that needs web content |
| ClaudeBot | Anthropic | Collects web content that could help train Anthropic's models |
Sources: OpenAI's bots documentation and Anthropic's crawler article. Each setting is independent, so you can allow search bots and still disallow training bots. OpenAI says search changes can take about 24 hours to apply after a robots.txt update. Perplexity and Google have their own agents that I did not check for this post, so read their docs before you add them.
The distinction is the useful part. Blocking a training bot is a different decision from blocking a search bot. Blocking the search ones is the one that can cost you visibility.
Here is a small parser that answers "may this bot fetch this path?":
// src/robots-audit.js (core)
export function parseRobots(text) {
const groups = [];
let current = null;
let lastWasAgent = false;
for (const raw of text.split(/\r?\n/)) {
const line = raw.replace(/#.*/, "").trim();
if (!line) continue;
const i = line.indexOf(":");
if (i < 0) continue;
const key = line.slice(0, i).trim().toLowerCase();
const value = line.slice(i + 1).trim();
if (key === "user-agent") {
if (!current || !lastWasAgent) {
current = { agents: [], rules: [] };
groups.push(current);
}
current.agents.push(value.toLowerCase());
lastWasAgent = true;
} else if ((key === "allow" || key === "disallow") && current) {
current.rules.push({ allow: key === "allow", path: value });
lastWasAgent = false;
} else {
lastWasAgent = false;
}
}
return groups;
}
export function isAllowed(groups, agent, path = "/") {
const a = agent.toLowerCase();
let group = groups.find((g) => g.agents.includes(a));
if (!group) group = groups.find((g) => g.agents.includes("*"));
if (!group) return true;
let best = null;
for (const r of group.rules) {
if (r.path === "") continue;
if (path.startsWith(r.path) && (!best || r.path.length > best.path.length)) best = r;
}
return best ? best.allow : true;
}It's a simplified reading of the standard: specific group beats *, longest matching path wins, and an empty Disallow: allows everything. It does not handle wildcards inside paths or $ anchors, so don't use it as a full validator. It's good for catching the classic accident, a blanket block.
Run it against a sample robots.txt that blocks only GPTBot:
npm run auditallowed OAI-SearchBot ChatGPT search results
BLOCKED GPTBot OpenAI training
allowed ChatGPT-User user-initiated fetches (robots.txt may not apply)
allowed Claude-SearchBot Claude search indexing
allowed Claude-User Claude fetching a page for a user
allowed ClaudeBot Anthropic trainingThat's a sensible setup if you want to be found in ChatGPT search but stay out of training. To audit your own site, fetch https://yoursite.com/robots.txt and pass the text to audit().
Robots.txt is only the first gate. Also check that important content is in the raw HTML and not only rendered by JavaScript, that status codes and canonicals are correct, and that your pricing and feature limits are written in plain text. A llms.txt file can add context, but it doesn't replace crawlable pages.
Step 9: Agent-readiness tests (for developer tools)
If you sell an SDK or API, the buyer may be a coding agent working for a developer. Google rankings won't help if the agent can't get from your docs to a working call.
Write a repeatable task list and run it in the coding agent of your choice:
| Task | Pass condition |
|---|---|
| Find the official docs from a plain-language ask | Lands on your domain, not a stale blog |
| Find the install command | The command works on a clean project |
| Install the right package version | No deprecated package pulled in |
| Configure auth | Key goes in the right place on the first try |
| Make a first successful request | A 200 response, not a guess |
| Understand an error | The agent reads your error body and fixes the call |
Record where it fails and fix the source: an outdated install line, auth explained across three pages, an old endpoint in an example. I didn't build an automated harness for this step. It's a checklist you run and score by hand. For the thinking behind running agents safely, see Agent harnessing: what is an agent harness.
Step 10: Schedule it, then close the loop
- Run weekly, not daily. Daily runs cost more and mostly add noise.
- Keep the prompt set fixed between runs, and add new prompts as a separate set. Changing the set mid-series breaks comparisons.
- Record country, language and model on every run. Adding "in India" to a prompt isn't the same as asking from India, so label which you did.
- Add a human review step before anything is published. When the tracker finds that an assistant misquotes your pricing, the agent or the person should find the source, propose a fix, and wait for approval. Don't auto-rewrite your pricing page because a model got confused.
- Run the same prompts again after a change. That's the whole loop: measure, fix, remeasure.
If you generate pages from the gaps you find, mind the quality rules. We wrote about how we keep that safe in 100+ SEO blogs a day for under $10 without a scaled content penalty.
Common mistakes
- Asking once. Run each prompt several times and show the interval.
- Mixing branded and non-branded prompts in one headline number.
- Reporting one blended "AI score". Report mention rate, named-first rate and share of voice separately.
- Dropping the raw answers. You will need them the first time a number looks wrong.
- Treating API output as the consumer product.
- Comparing runs across a changed prompt set or a changed model without noting it.
- Chasing one backlink instead of fixing what the cited pages say about you.
FAQ
How do I track whether ChatGPT mentions my brand?
Write 20 or more non-branded buyer questions, run each one several times through an API, and store the answers. Count how often your brand name appears, and report the rate with a confidence interval. Add a small manual sample from the real ChatGPT app to compare.
Why do I get different answers each time?
AI answers are probabilistic. The same prompt can return different brands, citations and formats on each run, and personalisation adds more variation. That is why you aggregate across many runs instead of reading one.
What's the difference between a mention and a recommendation?
A mention means the assistant names you. A recommendation means it presents you as a fit for the user's stated need. Count them separately, because a brand can be named in a list without being the pick.
What is AI share of voice?
Your brand's mentions divided by all tracked-brand mentions across the same prompt set, model and period. State the prompt set, since a share across a narrow topic can look very different from a share across a whole market.
Should I block GPTBot or ClaudeBot?
Those are training crawlers, and blocking them is a content-licensing decision, not a visibility one. The search and user-fetch bots (OAI-SearchBot, Claude-SearchBot, Claude-User) are the ones tied to showing your pages in answers. Check each vendor's documentation before deciding.
How many prompts and attempts do I need?
Start with 20 prompts and 5 attempts to get the pipeline working. For share-of-voice claims, use far more prompts, since small sets are noisy.
Do I need a paid AI visibility tool?
Not to begin. A script like this answers "are we mentioned and what do the cited sources say". Paid tools add scale, scheduling and consumer-app coverage, so look at them once you outgrow the script.
Final thoughts
The useful output of an AI visibility tracker isn't a score. It's a short list: the questions where you're missing, the pages the assistants trust, and the access or accuracy problems you can fix. Everything above is built to produce that list without pretending a single run means more than it does.
Start with 20 real buyer questions. Run each one five times. Save the answers, read the cited domains, and fix the first thing you find.
Launching something? The SaaS directories list covers 390+ places to submit, filterable by fee and category. More build-alongs like this go out in the monthly ihatereading magazine.