Skip to content

feat(traffic): report which AI bots read the site, and cited pages no search bot read - #1182

Merged
gkhngyk merged 49 commits into
ansvisor:mainfrom
cihan-gyk:feature/traffic-bot-report
Oct 19, 2026
Merged

gkhngyk merged 49 commits into
ansvisor:mainfrom
cihan-gyk:feature/traffic-bot-report

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

AI Traffic Analytics, spec AT-011 (§3.7, §7): the "AI bots reading your site" section. It reports the verified AI-bot requests a brand's Cloudflare or Vercel sends (AT-010) in three ways:

  • by type: training, search index and user fetch;
  • per page, with when each type last read it;
  • an alert for pages AI answers cited that no search bot read in 30 days.

Stacked on #1181 (→ #1180 → … → #1176). This PR's own change is the last commit, 898ff2a7. Web plus one migration; no server change.

Why

  • Spec §3.7: training crawlers, search crawlers and user fetches reported separately, the last crawl per page, and the alert "cited pages not read by any search bot in 30 days".
  • Spec §7: "AI bot report: Starter Locked (sample data + Upgrade); Growth ✓".

What changes

  • 00185_ai_bot_report.sql: ai_bot_report(brand, since, until, limit) reads the bot × page × day counters from 00183. Those counters hold every request, even past the month's cap. It returns:
    • types: hits, pages read, last seen and the bots seen, for each of training, search and user;
    • bots: the same per bot (used by the export);
    • pages: the most read pages (limit) plus their total, with each type's last read;
    • uncrawled: pages cited by tracked AI answers in the last 30 days (ai_traffic_page_citations, keyed like the Pages section) that no search bot read in those 30 days. This window is fixed whatever range is picked. It is null until the first bot request is 30 days old, and alert_from says when the alert starts.
    • Access: security definer, since citation_urls has no member select policy. It checks that the caller belongs to the brand's organization; a caller from elsewhere gets null.
  • _bots-report.tsx: the section sits after the Google Search Console section and follows the page's date range. It has two cards, side by side from xl:
    • By bot type: a table with the bots under each type. Below it:
      • the amber alert, listing up to 10 pages with their citation counts;
      • "Every page … was read by a search bot";
      • or "The search-bot alert starts on …".
    • Pages AI bots read: hits and the last read per type. "10 of N pages · the export has them all".
    • States (botReportState in lib/ai-bots.ts):
      • Locked: Starter, maxBotEventsPerMonth 0. It shows blurred sample data with Upgrade (/dashboard/settings?tab=billing).
      • Not connected: the same overlay with Connect, which opens AT-010's dialog, and Preview with sample data.
      • Waiting: connected but no request yet.
      • Data, and failed ("Couldn't load the AI bot report.").
    • Refresh: connecting or revoking in the dialog refreshes the section, and the strip's card, through a shared revision.
  • Export: two sheets:
    • "AI bots": per bot, with type, hits, pages read and last seen.
    • "Pages AI bots read": every page, up to the export cap, with the last read per type.
    • When there is nothing: a range with no bot data gets the note "No AI-bot requests in this range".
  • lib/ai-bot-names.ts: the bot types and display names. A test keeps them in step with the server's ai-bots.json.

Deploy

Apply 00185 (one function), then deploy the web.

Related issue

None. Spec AT-011 (AI Traffic Analytics plan, approved by product).

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply 00185 and open AI Traffic Analytics for a brand with an AI-bot connection that has received requests (AT-010).
  2. AI bots reading your site: the types table, then the pages with their last read per type. Change the date range and the numbers follow it.
  3. If the first request is under 30 days old, the card says when the search-bot alert starts. After that it lists cited pages no search bot read, or says every cited page was read.
  4. Export to Excel: the "AI bots" and "Pages AI bots read" sheets.
  5. Without a connection: Connect and the sample preview appear. On Starter: blurred sample data with Upgrade.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): no errors; 6 warnings, all in files this PR does not touch
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run:

  • Web: yarn test (1693) and yarn build pass. No server change.
  • supabase: bash supabase/build-schema.sh; schema.sql updated.
  • Tests:
    • _bots-report.test.tsx:
      • types, pages and the alert;
      • "all crawled" and "alert starts";
      • the locked, not-connected and waiting states;
      • a failed report.
    • actions/traffic-bots.test.ts: the RPC arguments and mapping.
    • ai-bots.test.ts: the report states and sample data.
    • ai-bot-names.test.ts: names match ai-bots.json.
    • Export and route tests: the two sheets and the empty note.
  • Browser (local server and web against the dev database, with temporary bot counters and two cited pages for the demo brand):
    • The types, pages and alert showed for 7 days and other ranges; the alert listed the cited page no search bot read.
    • Starter, with IS_CLOUD=true and the demo org temporarily on Starter: blurred sample data with Upgrade. The plan and its update time were restored.
    • Light and dark; 1440 px (two cards side by side) and 1024 px (stacked) with no overflow.
    • The temporary rows were removed afterwards.

🤖 Generated with Claude Code

cihan-gyk and others added 7 commits October 19, 2026 11:35
…l Trend card

AT-008 part A (spec §3.3): the trend card gets a "vs Google clicks" tab.
It draws AI visits and Google organic clicks, each indexed to 100 on its
first day with data, with markers on the days actions entered the Action
Center or prompts were added.

- 00180 ai_traffic_google_trend: Search Console clicks per UTC day, the
  first and latest day it has rows for the brand, and the markers.
  Security invoker; RLS decides the brand.
- The Google line is blank (not 0) before Search Console's history and
  after Google's latest reported day, which the view names.
- A range that starts mid-day leaves out its partial first day so it
  doesn't set a misleading 100.
- The 24-hour range offers "Show last 7 days" (Google reports by day).
- Without Search Console the view keeps the AI line and says what the
  Google line needs (§3.8b). The view shows the "Needs Google Search
  Console" tag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ng clicks

AT-008 part B (spec §3.6): a Google Search Console section with "Is AI
taking Google clicks?" — pages whose impressions rose 15% or more while
their CTR fell 20% or more against the period before, most clicks lost
first. Each row's next step is the Positions panel of a tracked prompt
about the page, or Add prompts when there is none.

- 00181: gsc_page_stats (Search Console by page and day, member select
  policy) and ai_traffic_google_pages. The window keeps the range's
  length and ends on Google's latest reported day (§3.01). Pages need 100
  impressions in the period before. When the page history doesn't reach
  back to that period, it says so rather than reading every page as
  rising. Security definer with an organization check (citations).
- Server: the daily GSC sync also pulls pages. A brand's first page sync
  reads 190 days in 28-day steps, later ones the last 28, and the prune
  keeps 190 days. A failed page step leaves the query rows synced.
- Web: the section with its connection states (§3.8b), the "Needed for"
  list, and the export sheet "Is AI taking Google clicks".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd Track all

AT-009 (spec §3.6): beside "Is AI taking Google clicks?", a card with the
top Search Console queries by clicks that no tracked prompt covers. Track
adds a query as a prompt; Track all adds the listed ones within the plan's
prompt slots (PROMPT-012). The summary line states their number while
Search Console is connected (§3.1, §3.8b rule 5).

- 00182 ai_traffic_google_queries: queries with clicks between two days,
  most clicks first, ending on Google's latest reported day (§3.01).
- Server: GET /api/prompts/untracked-queries/:brandId drops the queries
  an active prompt covers, by the rule Prompt Suggestions uses for Google
  queries, so the two pages agree. Prompts are tokenized once and read
  past the 1,000-row page.
- Web: UntrackedQueriesCard, the summary line's count (counted again after
  tracking), the export sheet "Untracked Google queries" and the "Needed
  for" list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…within a monthly cap

AT-010 part A (spec §3.7, §6): the ingestion behind the AI bot report.

- 00183: ai_bot_connections (one secret per sender, stored as its
  SHA-256, hidden from members), ai_bot_events (verified rows, 90 days),
  ai_bot_daily (bot x page x day counters), ai_bot_usage (per organization
  and month) and ai_bot_ingest, which stores rows while the month has room
  and always adds counters, locking the usage row so concurrent batches
  can't pass the cap. Pages are keyed like the Pages section's.
- ai-bots.json: OpenAI, Anthropic and Perplexity's training crawlers,
  search crawlers and user fetchers. A request counts only when its user
  agent names one and its IP is in the operator's published ranges, read
  daily. No IP is kept.
- POST /bots/ingest (public, by connection secret) and
  /api/bots/connections/:brandId (list with this month's use, create with
  the secret shown once and the Cloudflare Worker, revoke). Admins and
  managers only; Starter has the report locked.
- Plan caps: Growth 2M stored events a month, Enterprise 20M (overridable),
  Starter 0, self-hosted no cap. Crossing 80% logs the internal alert once
  a month; past the cap only counters are written.
- The daily run prunes rows past their retention.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…bot requests, within a raw cap

AT-010 part B (spec §6.1 options B and C, §6.3): /bots/ingest reads the
body by the connection's kind.

- Cloudflare Logpush: gzipped NDJSON of the http_requests dataset (any
  timestamp format); the job's test upload reads as no requests.
- Vercel drain: a JSON array or NDJSON of log entries; only those with a
  proxy object are requests, build and function output is skipped.
- 00184: ai_bot_usage gains raw_records, and ai_bot_count_raw counts a log
  sender's batch under the usage row's lock. Batches are read while the
  month is under the plan's raw cap (Growth 20M, Enterprise 200M), only
  counted after. Verified events from a whole file are written in chunks
  of 500.
- Creating a Logpush or Vercel connection returns what to copy: a Logpush
  job filtered at the edge to the bot list with the secret as a header,
  or a drain's endpoint, header and format.
- The sender body is read raw before the app's JSON and form parsers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es strip

AT-010 part C (spec §6.1, §6.4, §7): the sources strip's AI bots card
opens a dialog to connect the brand's own Cloudflare Worker, Logpush job
or Vercel drain.

- The card is locked with Upgrade on a plan without the bot report
  (Starter), offers Connect, then waits for the first request, then shows
  the last one; Manage opens the same dialog.
- The dialog says what each way costs on the customer's own Cloudflare or
  Vercel bill before connecting. After it, it shows the settings to copy
  (the Worker, a Logpush job, or a drain's endpoint and header), with the
  secret in them once. It lists connections with their last request,
  revokes one in two steps, and shows the month's use and when the cap
  paused detailed rows.
- Server actions in lib/actions/ai-bots.ts and card state helpers in
  lib/ai-bots.ts. SourceCard moves to its own file.
- The dialog's content can't widen past it: long code scrolls inside its
  box.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk AT-011 is ready for review: the "AI bots reading your site" section, built on AT-010's counters. It is stacked on #1181, so it merges after #1176 → … → #1181. Only the last commit, 898ff2a7, is this PR's own.

  • Deploy: apply 00185 (one function), then deploy the web.
  • One question: the "cited pages no search bot read" alert always looks at the last 30 days, whatever range is picked, and it starts once the first bot request is 30 days old. Is a fixed 30-day window right, or should it follow the page's range?

cihan-gyk and others added 6 commits October 19, 2026 16:13
main now has ansvisor#1176 (squash a98c35c, identical to this branch's 27f2ad2)
and ansvisor#1193. The conflicts are the files ansvisor#1177 extends after ansvisor#1176: this
branch's side kept; schema.sql rebuilt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…raffic-untracked-queries

main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193;
merged through feature/traffic-google-pages, which carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ure/traffic-bot-ingest

main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193;
merged through feature/traffic-untracked-queries, which carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ffic-bot-logs

main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193;
merged through feature/traffic-bot-ingest, which carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…affic-bot-report

main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193;
merged through feature/traffic-bot-connect, which carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ic-bot-connect

main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193;
merged through feature/traffic-bot-logs, which carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three things to fix:

1. Connecting from the report section loses the secret.

  • What happens: in _bots-report.tsx, BotsDialog's create() calls setCreated(result), then onChanged(). The page bumps botsRevision, so the section's key changes and current becomes null. {info && <BotsDialog/>} then unmounts the dialog.
  • Result: when the dialog remounts after the refetch, created is gone. The person never sees the Worker, Logpush or drain settings, and the connection stays live with a secret nobody can recover.
  • Why the sources strip works: its load() keeps info while it refetches.
  • Fix: keep the last loaded state while refetching, or hold onChanged until the dialog closes. A test for this flow would catch it.

2. Stale bot data reads as "no search bot read these pages".

  • Cause: the uncrawled list gates on v_first, the first bot day ever.
  • Effect: when every connection is revoked, or a sender stops (Worker removed, Logpush disabled, raw cap reached), the 30-day set of pages search bots read drains, and every cited page gets listed. Since #1195 this also raises cited_page_uncrawled.
  • Fix: return null unless a live connection sent within about two days and the data covers the whole 30-day window.

3. ai_bot_report on "All time".

  • Cause: min(day) and max(last_seen) scan every row the brand has. With p_since null, the d CTE covers all 400 days and sorts three times for count(distinct page).
  • Scale: a site crawled at 10k+ pages a day reaches millions of rows.
  • Fix:
    • read the first and last day from the index ends (order by day limit 1);
    • cap the window, or add a bot × day rollup;
    • use not exists instead of not in for the pages search bots read.
  • Export: it calls the report with p_limit 100000 inside Promise.all without a .catch, so a timeout fails the whole export.

Not blocking:

  • On the 24h range, utcDay(from) starts yesterday, so the section shows up to 48 hours under "Last 24 hours".
  • The "By bot type" card has one row per type, but its export sheet has one row per bot. The uncrawled list isn't exported.

cihan-gyk and others added 9 commits October 19, 2026 18:49
…ap its counters

Review of ansvisor#1179:
- The endpoint written into a Worker, Logpush job or drain came from the
  request's Host. It now comes from PUBLIC_SERVER_URL (https; http only on
  localhost outside production), and no connection is made without it.
- ai_bot_daily grew by about a row an event past the month's cap. Hits past
  it now go on one '(other)' row per bot and day, and /bots/ingest has a
  per-connection limit (600 a minute, keyed by the secret's hash).
- Also: the Worker passes requests through on its own errors and sends the
  page without its query string, and ingest errors go to the app logger.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…backfill

Review of ansvisor#1177:
- ai_traffic_google_pages spent its time on normalize_page_path, twice a
  row (4 s warm, 18 s cold on 110k rows). gsc_page_stats now stores
  page_key as a generated column and the function groups by it; only the
  ranked rows work out their display path. Plus an index on date for the
  table-wide prune.
- A first page sync cut short left 28 days of history for months. The sync
  now reads the 190 days until one gets through them all for the property
  (brands.gsc_pages_backfilled_property), and drops the old property's
  pages when it changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of ansvisor#1180:
- gunzipSync on up to 64 MB and a synchronous parse could hold up the API.
  Files are now inflated asynchronously to at most 16 MB, hold at most
  20,000 lines (413 otherwise), and are parsed 1,000 lines at a time; the
  Logpush job we suggest sends at most 10,000 records a file.
- A file retried after a timeout was counted twice. Each connection's
  files are claimed by the SHA-256 of their body (ai_bot_ingested_files,
  kept 7 days) and a resent one is answered without reading it; a read that
  fails gives its claim back.
- Also: a line with an unreadable time is dropped, not the whole file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…alert honest

Review of ansvisor#1182:
- Connecting from the report section lost the secret: the page's revision
  bump took the dialog down. It now keeps the connections it was opened
  with while the section reads again (with a test of the flow).
- Stale bot data listed every cited page. ai_bot_report now gives the list
  only while a live connection sent within 2 days and no search hits went
  past the month's cap in the 30 days (alert_state 'on'); otherwise the
  section says the alert is paused. '(other)' rows aren't pages.
- "All time" scanned every row: it covers the last 90 days here (labelled
  so), the first and last day come from the index's ends, the rows are
  added up once by bot and page, and the uncrawled check uses not exists.
  An export whose bot report fails keeps its other sheets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	server/src/lib/bot-ingest.test.js
#	server/src/routes/bot-ingest.js
#	server/src/routes/bots.js
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk All three fixed in 559a0ea:

  1. Secret lost: The dialog keeps the connections it was opened with while the section reads again after the revision bump, so the new connection's settings stay up. A test drives the flow, Connect → Create → rerender with revision 1; it fails without the fix.

  2. Stale data: ai_bot_report returns alert_state:

    • waiting: under 30 days of data;
    • stale: no unrevoked connection with last_event_at in the last 2 days, or any search (other) row in the 30 days, i.e. past the cap;
    • on.

    uncrawled is only filled when it's on, and the section says the alert is paused otherwise. (other) rows are left out of pages and page counts.

  3. All time:

    • First and last day are read from the (brand_id, day) index ends.
    • The rows are aggregated once by bot type, bot and page, instead of three count(distinct) sorts over day rows.
    • The uncrawled check uses not exists.
    • "All time" is capped at the last 90 days in this section, and the badge says "last 90 days".
    • The export's getTrafficBots has a .catch(() => null).

Not done (follow-ups): the 24h-shows-48h note and the export sheet shapes.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The secret now survives the refetch. The "All time" cap, not exists, the stale gate and the export .catch all look right.

Not blocking, for here or a follow-up:

  • 30-day coverage: the gate doesn't check that bot data covers the whole 30 days. Suppose a connection is revoked on day −25 and a new one is created yesterday, as the dialog suggests. The new connection is live and v_first is old, so the gate reads on, and every page crawled less than about every five days is listed as uncrawled. Requiring about 28 days with rows in the last 30, or a live connection at least 29 days old, would cover it.
  • Dialog unmount: if the refetch's getBotConnections fails, loaded.info becomes null and the dialog still unmounts. Keep the last non-null info in a ref.
  • (other) check: the exists scans the brand's 30 days on every call. A partial index (brand_id, day) where page = '(other)' makes it cheap.
  • 24h range: it still starts at yesterday 00:00 UTC.

The fallback prompt for a page in "Is AI taking Google clicks?" counted every citation of the page over 90 days, which read every answer that cited it (35,798 on the largest brand, 15 s cold, past the 8 s timeout). It now reads the page's latest citation and that one answer, at most one each per ranked page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cihan-gyk and others added 19 commits October 19, 2026 22:49

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

00185 is applied on prod. ai_bot_report reads in 6 ms on the largest brand (waiting, no bot data yet), and a stranger gets null. Tests pass on main with the whole stack. The coverage, dialog, (other) index and 24h notes stay as follow-ups.

@gkhngyk
gkhngyk merged commit 9a877a6 into ansvisor:main Oct 19, 2026
5 checks passed
gkhngyk added a commit that referenced this pull request Oct 19, 2026
…edirect to suggest (#1192)

* feat(traffic): compare AI visits with Google clicks on the AI Referral Trend card

AT-008 part A (spec §3.3): the trend card gets a "vs Google clicks" tab.
It draws AI visits and Google organic clicks, each indexed to 100 on its
first day with data, with markers on the days actions entered the Action
Center or prompts were added.

- 00180 ai_traffic_google_trend: Search Console clicks per UTC day, the
  first and latest day it has rows for the brand, and the markers.
  Security invoker; RLS decides the brand.
- The Google line is blank (not 0) before Search Console's history and
  after Google's latest reported day, which the view names.
- A range that starts mid-day leaves out its partial first day so it
  doesn't set a misleading 100.
- The 24-hour range offers "Show last 7 days" (Google reports by day).
- Without Search Console the view keeps the AI line and says what the
  Google line needs (§3.8b). The view shows the "Needs Google Search
  Console" tag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list the pages that gain Google impressions while losing clicks

AT-008 part B (spec §3.6): a Google Search Console section with "Is AI
taking Google clicks?" — pages whose impressions rose 15% or more while
their CTR fell 20% or more against the period before, most clicks lost
first. Each row's next step is the Positions panel of a tracked prompt
about the page, or Add prompts when there is none.

- 00181: gsc_page_stats (Search Console by page and day, member select
  policy) and ai_traffic_google_pages. The window keeps the range's
  length and ends on Google's latest reported day (§3.01). Pages need 100
  impressions in the period before. When the page history doesn't reach
  back to that period, it says so rather than reading every page as
  rising. Security definer with an organization check (citations).
- Server: the daily GSC sync also pulls pages. A brand's first page sync
  reads 190 days in 28-day steps, later ones the last 28, and the prune
  keeps 190 days. A failed page step leaves the query rows synced.
- Web: the section with its connection states (§3.8b), the "Needed for"
  list, and the export sheet "Is AI taking Google clicks".

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list the Google queries no prompt tracks, with Track and Track all

AT-009 (spec §3.6): beside "Is AI taking Google clicks?", a card with the
top Search Console queries by clicks that no tracked prompt covers. Track
adds a query as a prompt; Track all adds the listed ones within the plan's
prompt slots (PROMPT-012). The summary line states their number while
Search Console is connected (§3.1, §3.8b rule 5).

- 00182 ai_traffic_google_queries: queries with clicks between two days,
  most clicks first, ending on Google's latest reported day (§3.01).
- Server: GET /api/prompts/untracked-queries/:brandId drops the queries
  an active prompt covers, by the rule Prompt Suggestions uses for Google
  queries, so the two pages agree. Prompts are tokenized once and read
  past the 1,000-row page.
- Web: UntrackedQueriesCard, the summary line's count (counted again after
  tracking), the export sheet "Untracked Google queries" and the "Needed
  for" list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): receive verified AI-bot requests from a brand's edge, within a monthly cap

AT-010 part A (spec §3.7, §6): the ingestion behind the AI bot report.

- 00183: ai_bot_connections (one secret per sender, stored as its
  SHA-256, hidden from members), ai_bot_events (verified rows, 90 days),
  ai_bot_daily (bot x page x day counters), ai_bot_usage (per organization
  and month) and ai_bot_ingest, which stores rows while the month has room
  and always adds counters, locking the usage row so concurrent batches
  can't pass the cap. Pages are keyed like the Pages section's.
- ai-bots.json: OpenAI, Anthropic and Perplexity's training crawlers,
  search crawlers and user fetchers. A request counts only when its user
  agent names one and its IP is in the operator's published ranges, read
  daily. No IP is kept.
- POST /bots/ingest (public, by connection secret) and
  /api/bots/connections/:brandId (list with this month's use, create with
  the secret shown once and the Cloudflare Worker, revoke). Admins and
  managers only; Starter has the report locked.
- Plan caps: Growth 2M stored events a month, Enterprise 20M (overridable),
  Starter 0, self-hosted no cap. Crossing 80% logs the internal alert once
  a month; past the cap only counters are written.
- The daily run prunes rows past their retention.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): read Cloudflare Logpush files and Vercel drains of AI-bot requests, within a raw cap

AT-010 part B (spec §6.1 options B and C, §6.3): /bots/ingest reads the
body by the connection's kind.

- Cloudflare Logpush: gzipped NDJSON of the http_requests dataset (any
  timestamp format); the job's test upload reads as no requests.
- Vercel drain: a JSON array or NDJSON of log entries; only those with a
  proxy object are requests, build and function output is skipped.
- 00184: ai_bot_usage gains raw_records, and ai_bot_count_raw counts a log
  sender's batch under the usage row's lock. Batches are read while the
  month is under the plan's raw cap (Growth 20M, Enterprise 200M), only
  counted after. Verified events from a whole file are written in chunks
  of 500.
- Creating a Logpush or Vercel connection returns what to copy: a Logpush
  job filtered at the edge to the bot list with the secret as a header,
  or a drain's endpoint, header and format.
- The sender body is read raw before the app's JSON and form parsers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): connect AI bots from Cloudflare or Vercel in the sources strip

AT-010 part C (spec §6.1, §6.4, §7): the sources strip's AI bots card
opens a dialog to connect the brand's own Cloudflare Worker, Logpush job
or Vercel drain.

- The card is locked with Upgrade on a plan without the bot report
  (Starter), offers Connect, then waits for the first request, then shows
  the last one; Manage opens the same dialog.
- The dialog says what each way costs on the customer's own Cloudflare or
  Vercel bill before connecting. After it, it shows the settings to copy
  (the Worker, a Logpush job, or a drain's endpoint and header), with the
  secret in them once. It lists connections with their last request,
  revokes one in two steps, and shows the month's use and when the cap
  paused detailed rows.
- Server actions in lib/actions/ai-bots.ts and card state helpers in
  lib/ai-bots.ts. SourceCard moves to its own file.
- The dialog's content can't widen past it: long code scrolls inside its
  box.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): report which AI bots read the site, and cited pages no search bot read

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list AI visits that landed on a missing page, with a redirect to suggest

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): build the bot ingest endpoint from the public URL and cap its counters

Review of #1179:
- The endpoint written into a Worker, Logpush job or drain came from the
  request's Host. It now comes from PUBLIC_SERVER_URL (https; http only on
  localhost outside production), and no connection is made without it.
- ai_bot_daily grew by about a row an event past the month's cap. Hits past
  it now go on one '(other)' row per bot and day, and /bots/ingest has a
  per-connection limit (600 a minute, keyed by the secret's hash).
- Also: the Worker passes requests through on its own errors and sends the
  page without its query string, and ingest errors go to the app logger.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): group Google pages by a stored key and resume the page backfill

Review of #1177:
- ai_traffic_google_pages spent its time on normalize_page_path, twice a
  row (4 s warm, 18 s cold on 110k rows). gsc_page_stats now stores
  page_key as a generated column and the function groups by it; only the
  ranked rows work out their display path. Plus an index on date for the
  table-wide prune.
- A first page sync cut short left 28 days of history for months. The sync
  now reads the 190 days until one gets through them all for the property
  (brands.gsc_pages_backfilled_property), and drops the old property's
  pages when it changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): read log files without blocking, and each one once

Review of #1180:
- gunzipSync on up to 64 MB and a synchronous parse could hold up the API.
  Files are now inflated asynchronously to at most 16 MB, hold at most
  20,000 lines (413 otherwise), and are parsed 1,000 lines at a time; the
  Logpush job we suggest sends at most 10,000 records a file.
- A file retried after a timeout was counted twice. Each connection's
  files are claimed by the SHA-256 of their body (ai_bot_ingested_files,
  kept 7 days) and a resent one is answered without reading it; a read that
  fails gives its claim back.
- Also: a line with an unreadable time is dropped, not the whole file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): keep the bot connection's secret up and the search-bot alert honest

Review of #1182:
- Connecting from the report section lost the secret: the page's revision
  bump took the dialog down. It now keeps the connections it was opened
  with while the section reads again (with a test of the flow).
- Stale bot data listed every cited page. ai_bot_report now gives the list
  only while a live connection sent within 2 days and no search hits went
  past the month's cap in the 30 days (alert_state 'on'); otherwise the
  section says the alert is paused. '(other)' rows aren't pages.
- "All time" scanned every row: it covers the last 90 days here (labelled
  so), the first and last day come from the index's ends, the rows are
  added up once by bot and page, and the uncrawled check uses not exists.
  An export whose bot report fails keeps its other sheets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): count only the visits that found a page missing, per full address

Review of #1192:
- Visits counted pageviews from before the page broke. They now count only
  404, 410, or no status with a not-found title.
- Pages that differ only by query string were merged, so a deleted
  /index.php?route=product&id=42 could suggest redirecting /index.php, the
  whole site. The status is decided per address (path plus query, utm_*
  left out), and a path is broken only when none of its addresses last
  answered 2xx or 3xx.
- Also: the tab count comes with the Pages read (no broken-links pipeline on
  every load, and the card stays up if that list fails), and the column
  change gives up after 3 s instead of queueing beacon inserts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): take each Google page's prompt from its latest citation

The fallback prompt for a page in "Is AI taking Google clicks?" counted every citation of the page over 90 days, which read every answer that cited it (35,798 on the largest brand, 15 s cold, past the 8 s timeout). It now reads the page's latest citation and that one answer, at most one each per ranked page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): list title-only broken pages and stop suggesting redirects for query routes

ai_traffic_broken_pages read a page with no status at all as unknown rather than not working, so the Safari title rule never listed one; it now coalesces to false. It scans only the pageviews with a status or a not-found title, normalizes each URL once, works out the query part only when there is one, leaves click ids (gclid, fbclid, ...) out of the address, and drops pages the nightly read found working after their last miss. A page whose missing addresses all carry a query gets no redirect (reason query), and redirect targets count only a page's own address.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): stop at the first active prompt that cited a Google page

Ordering a page's citations by created_at still read every one of them from the heap, since the (url_id, brand_id) index has no created_at: 35,700 rows and 7.5 s cold on the largest brand's 50 pages. The lateral now stops at the first citation in 90 days whose prompt is active (2 s there, gkhngyk's measure), which also skips a paused prompt instead of leaving the page without one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 19, 2026
… new platform, broken links, unread cited pages (#1195)

* feat(traffic): compare AI visits with Google clicks on the AI Referral Trend card

AT-008 part A (spec §3.3): the trend card gets a "vs Google clicks" tab.
It draws AI visits and Google organic clicks, each indexed to 100 on its
first day with data, with markers on the days actions entered the Action
Center or prompts were added.

- 00180 ai_traffic_google_trend: Search Console clicks per UTC day, the
  first and latest day it has rows for the brand, and the markers.
  Security invoker; RLS decides the brand.
- The Google line is blank (not 0) before Search Console's history and
  after Google's latest reported day, which the view names.
- A range that starts mid-day leaves out its partial first day so it
  doesn't set a misleading 100.
- The 24-hour range offers "Show last 7 days" (Google reports by day).
- Without Search Console the view keeps the AI line and says what the
  Google line needs (§3.8b). The view shows the "Needs Google Search
  Console" tag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list the pages that gain Google impressions while losing clicks

AT-008 part B (spec §3.6): a Google Search Console section with "Is AI
taking Google clicks?" — pages whose impressions rose 15% or more while
their CTR fell 20% or more against the period before, most clicks lost
first. Each row's next step is the Positions panel of a tracked prompt
about the page, or Add prompts when there is none.

- 00181: gsc_page_stats (Search Console by page and day, member select
  policy) and ai_traffic_google_pages. The window keeps the range's
  length and ends on Google's latest reported day (§3.01). Pages need 100
  impressions in the period before. When the page history doesn't reach
  back to that period, it says so rather than reading every page as
  rising. Security definer with an organization check (citations).
- Server: the daily GSC sync also pulls pages. A brand's first page sync
  reads 190 days in 28-day steps, later ones the last 28, and the prune
  keeps 190 days. A failed page step leaves the query rows synced.
- Web: the section with its connection states (§3.8b), the "Needed for"
  list, and the export sheet "Is AI taking Google clicks".

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list the Google queries no prompt tracks, with Track and Track all

AT-009 (spec §3.6): beside "Is AI taking Google clicks?", a card with the
top Search Console queries by clicks that no tracked prompt covers. Track
adds a query as a prompt; Track all adds the listed ones within the plan's
prompt slots (PROMPT-012). The summary line states their number while
Search Console is connected (§3.1, §3.8b rule 5).

- 00182 ai_traffic_google_queries: queries with clicks between two days,
  most clicks first, ending on Google's latest reported day (§3.01).
- Server: GET /api/prompts/untracked-queries/:brandId drops the queries
  an active prompt covers, by the rule Prompt Suggestions uses for Google
  queries, so the two pages agree. Prompts are tokenized once and read
  past the 1,000-row page.
- Web: UntrackedQueriesCard, the summary line's count (counted again after
  tracking), the export sheet "Untracked Google queries" and the "Needed
  for" list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): receive verified AI-bot requests from a brand's edge, within a monthly cap

AT-010 part A (spec §3.7, §6): the ingestion behind the AI bot report.

- 00183: ai_bot_connections (one secret per sender, stored as its
  SHA-256, hidden from members), ai_bot_events (verified rows, 90 days),
  ai_bot_daily (bot x page x day counters), ai_bot_usage (per organization
  and month) and ai_bot_ingest, which stores rows while the month has room
  and always adds counters, locking the usage row so concurrent batches
  can't pass the cap. Pages are keyed like the Pages section's.
- ai-bots.json: OpenAI, Anthropic and Perplexity's training crawlers,
  search crawlers and user fetchers. A request counts only when its user
  agent names one and its IP is in the operator's published ranges, read
  daily. No IP is kept.
- POST /bots/ingest (public, by connection secret) and
  /api/bots/connections/:brandId (list with this month's use, create with
  the secret shown once and the Cloudflare Worker, revoke). Admins and
  managers only; Starter has the report locked.
- Plan caps: Growth 2M stored events a month, Enterprise 20M (overridable),
  Starter 0, self-hosted no cap. Crossing 80% logs the internal alert once
  a month; past the cap only counters are written.
- The daily run prunes rows past their retention.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): read Cloudflare Logpush files and Vercel drains of AI-bot requests, within a raw cap

AT-010 part B (spec §6.1 options B and C, §6.3): /bots/ingest reads the
body by the connection's kind.

- Cloudflare Logpush: gzipped NDJSON of the http_requests dataset (any
  timestamp format); the job's test upload reads as no requests.
- Vercel drain: a JSON array or NDJSON of log entries; only those with a
  proxy object are requests, build and function output is skipped.
- 00184: ai_bot_usage gains raw_records, and ai_bot_count_raw counts a log
  sender's batch under the usage row's lock. Batches are read while the
  month is under the plan's raw cap (Growth 20M, Enterprise 200M), only
  counted after. Verified events from a whole file are written in chunks
  of 500.
- Creating a Logpush or Vercel connection returns what to copy: a Logpush
  job filtered at the edge to the bot list with the secret as a header,
  or a drain's endpoint, header and format.
- The sender body is read raw before the app's JSON and form parsers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): connect AI bots from Cloudflare or Vercel in the sources strip

AT-010 part C (spec §6.1, §6.4, §7): the sources strip's AI bots card
opens a dialog to connect the brand's own Cloudflare Worker, Logpush job
or Vercel drain.

- The card is locked with Upgrade on a plan without the bot report
  (Starter), offers Connect, then waits for the first request, then shows
  the last one; Manage opens the same dialog.
- The dialog says what each way costs on the customer's own Cloudflare or
  Vercel bill before connecting. After it, it shows the settings to copy
  (the Worker, a Logpush job, or a drain's endpoint and header), with the
  secret in them once. It lists connections with their last request,
  revokes one in two steps, and shows the month's use and when the cap
  paused detailed rows.
- Server actions in lib/actions/ai-bots.ts and card state helpers in
  lib/ai-bots.ts. SourceCard moves to its own file.
- The dialog's content can't widen past it: long code scrolls inside its
  box.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): report which AI bots read the site, and cited pages no search bot read

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list AI visits that landed on a missing page, with a redirect to suggest

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(action-center): raise AI Traffic alerts as signals: weekly drop, new platform, broken links, unread cited pages

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): build the bot ingest endpoint from the public URL and cap its counters

Review of #1179:
- The endpoint written into a Worker, Logpush job or drain came from the
  request's Host. It now comes from PUBLIC_SERVER_URL (https; http only on
  localhost outside production), and no connection is made without it.
- ai_bot_daily grew by about a row an event past the month's cap. Hits past
  it now go on one '(other)' row per bot and day, and /bots/ingest has a
  per-connection limit (600 a minute, keyed by the secret's hash).
- Also: the Worker passes requests through on its own errors and sends the
  page without its query string, and ingest errors go to the app logger.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): group Google pages by a stored key and resume the page backfill

Review of #1177:
- ai_traffic_google_pages spent its time on normalize_page_path, twice a
  row (4 s warm, 18 s cold on 110k rows). gsc_page_stats now stores
  page_key as a generated column and the function groups by it; only the
  ranked rows work out their display path. Plus an index on date for the
  table-wide prune.
- A first page sync cut short left 28 days of history for months. The sync
  now reads the 190 days until one gets through them all for the property
  (brands.gsc_pages_backfilled_property), and drops the old property's
  pages when it changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): read log files without blocking, and each one once

Review of #1180:
- gunzipSync on up to 64 MB and a synchronous parse could hold up the API.
  Files are now inflated asynchronously to at most 16 MB, hold at most
  20,000 lines (413 otherwise), and are parsed 1,000 lines at a time; the
  Logpush job we suggest sends at most 10,000 records a file.
- A file retried after a timeout was counted twice. Each connection's
  files are claimed by the SHA-256 of their body (ai_bot_ingested_files,
  kept 7 days) and a resent one is answered without reading it; a read that
  fails gives its claim back.
- Also: a line with an unreadable time is dropped, not the whole file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): keep the bot connection's secret up and the search-bot alert honest

Review of #1182:
- Connecting from the report section lost the secret: the page's revision
  bump took the dialog down. It now keeps the connections it was opened
  with while the section reads again (with a test of the flow).
- Stale bot data listed every cited page. ai_bot_report now gives the list
  only while a live connection sent within 2 days and no search hits went
  past the month's cap in the 30 days (alert_state 'on'); otherwise the
  section says the alert is paused. '(other)' rows aren't pages.
- "All time" scanned every row: it covers the last 90 days here (labelled
  so), the first and last day come from the index's ends, the rows are
  added up once by bot and page, and the uncrawled check uses not exists.
  An export whose bot report fails keeps its other sheets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): count only the visits that found a page missing, per full address

Review of #1192:
- Visits counted pageviews from before the page broke. They now count only
  404, 410, or no status with a not-found title.
- Pages that differ only by query string were merged, so a deleted
  /index.php?route=product&id=42 could suggest redirecting /index.php, the
  whole site. The status is decided per address (path plus query, utm_*
  left out), and a path is broken only when none of its addresses last
  answered 2xx or 3xx.
- Also: the tab count comes with the Pages read (no broken-links pipeline on
  every load, and the card stays up if that list fails), and the column
  change gives up after 3 s instead of queueing beacon inserts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(signals): read Analytics days as a list, end weeks at their last second, let F02 run without Site Audit

Review of #1195:
- analytics_days is a jsonb array of days, so Number() made it 0 and every
  alert said "from AI results". It's counted by length now, with fixtures
  of the real shape.
- Midnight bounds with p_to_inclusive false put a boundary day's Analytics
  in both weeks. The weeks are read to their last second, inclusive.
- cited_page_uncrawled couldn't become an action without Site Audit: F02
  requires only tracking now; its audit tasks still need an audit and the
  planner drops them for a brand without one.
- The uncrawled-page signal is raised only while the bot data is whole
  (ai_bot_report's alert_state 'on').
- Also: a new AI platform needs 3 visits and a source on the list, since the
  beacon is public.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): take each Google page's prompt from its latest citation

The fallback prompt for a page in "Is AI taking Google clicks?" counted every citation of the page over 90 days, which read every answer that cited it (35,798 on the largest brand, 15 s cold, past the 8 s timeout). It now reads the page's latest citation and that one answer, at most one each per ranked page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): list title-only broken pages and stop suggesting redirects for query routes

ai_traffic_broken_pages read a page with no status at all as unknown rather than not working, so the Safari title rule never listed one; it now coalesces to false. It scans only the pageviews with a status or a not-found title, normalizes each URL once, works out the query part only when there is one, leaves click ids (gclid, fbclid, ...) out of the address, and drops pages the nightly read found working after their last miss. A page whose missing addresses all carry a query gets no redirect (reason query), and redirect targets count only a page's own address.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(signals): keep uncrawled-page signals open while the bot data is stale

The aiBots family returned no findings on alert_state 'stale', which the recorder read as checked and recovered: a sender that stopped for two days resolved every open cited_page_uncrawled signal and its F02 task, and they came back as new once data returned. A stale report now throws DataNotWhole, so the kind is reported unread (logged as info, not an error) and open signals stay open; 'waiting' still finds nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): stop at the first active prompt that cited a Google page

Ordering a page's citations by created_at still read every one of them from the heap, since the (url_id, brand_id) index has no created_at: 35,700 rows and 7.5 s cold on the largest brand's 50 pages. The lateral now stops at the first citation in 90 days whose prompt is active (2 s there, gkhngyk's measure), which also skips a paused prompt instead of leaving the page without one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 19, 2026
…e and the top three changes (#1196)

* feat(traffic): compare AI visits with Google clicks on the AI Referral Trend card

AT-008 part A (spec §3.3): the trend card gets a "vs Google clicks" tab.
It draws AI visits and Google organic clicks, each indexed to 100 on its
first day with data, with markers on the days actions entered the Action
Center or prompts were added.

- 00180 ai_traffic_google_trend: Search Console clicks per UTC day, the
  first and latest day it has rows for the brand, and the markers.
  Security invoker; RLS decides the brand.
- The Google line is blank (not 0) before Search Console's history and
  after Google's latest reported day, which the view names.
- A range that starts mid-day leaves out its partial first day so it
  doesn't set a misleading 100.
- The 24-hour range offers "Show last 7 days" (Google reports by day).
- Without Search Console the view keeps the AI line and says what the
  Google line needs (§3.8b). The view shows the "Needs Google Search
  Console" tag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list the pages that gain Google impressions while losing clicks

AT-008 part B (spec §3.6): a Google Search Console section with "Is AI
taking Google clicks?" — pages whose impressions rose 15% or more while
their CTR fell 20% or more against the period before, most clicks lost
first. Each row's next step is the Positions panel of a tracked prompt
about the page, or Add prompts when there is none.

- 00181: gsc_page_stats (Search Console by page and day, member select
  policy) and ai_traffic_google_pages. The window keeps the range's
  length and ends on Google's latest reported day (§3.01). Pages need 100
  impressions in the period before. When the page history doesn't reach
  back to that period, it says so rather than reading every page as
  rising. Security definer with an organization check (citations).
- Server: the daily GSC sync also pulls pages. A brand's first page sync
  reads 190 days in 28-day steps, later ones the last 28, and the prune
  keeps 190 days. A failed page step leaves the query rows synced.
- Web: the section with its connection states (§3.8b), the "Needed for"
  list, and the export sheet "Is AI taking Google clicks".

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list the Google queries no prompt tracks, with Track and Track all

AT-009 (spec §3.6): beside "Is AI taking Google clicks?", a card with the
top Search Console queries by clicks that no tracked prompt covers. Track
adds a query as a prompt; Track all adds the listed ones within the plan's
prompt slots (PROMPT-012). The summary line states their number while
Search Console is connected (§3.1, §3.8b rule 5).

- 00182 ai_traffic_google_queries: queries with clicks between two days,
  most clicks first, ending on Google's latest reported day (§3.01).
- Server: GET /api/prompts/untracked-queries/:brandId drops the queries
  an active prompt covers, by the rule Prompt Suggestions uses for Google
  queries, so the two pages agree. Prompts are tokenized once and read
  past the 1,000-row page.
- Web: UntrackedQueriesCard, the summary line's count (counted again after
  tracking), the export sheet "Untracked Google queries" and the "Needed
  for" list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): receive verified AI-bot requests from a brand's edge, within a monthly cap

AT-010 part A (spec §3.7, §6): the ingestion behind the AI bot report.

- 00183: ai_bot_connections (one secret per sender, stored as its
  SHA-256, hidden from members), ai_bot_events (verified rows, 90 days),
  ai_bot_daily (bot x page x day counters), ai_bot_usage (per organization
  and month) and ai_bot_ingest, which stores rows while the month has room
  and always adds counters, locking the usage row so concurrent batches
  can't pass the cap. Pages are keyed like the Pages section's.
- ai-bots.json: OpenAI, Anthropic and Perplexity's training crawlers,
  search crawlers and user fetchers. A request counts only when its user
  agent names one and its IP is in the operator's published ranges, read
  daily. No IP is kept.
- POST /bots/ingest (public, by connection secret) and
  /api/bots/connections/:brandId (list with this month's use, create with
  the secret shown once and the Cloudflare Worker, revoke). Admins and
  managers only; Starter has the report locked.
- Plan caps: Growth 2M stored events a month, Enterprise 20M (overridable),
  Starter 0, self-hosted no cap. Crossing 80% logs the internal alert once
  a month; past the cap only counters are written.
- The daily run prunes rows past their retention.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): read Cloudflare Logpush files and Vercel drains of AI-bot requests, within a raw cap

AT-010 part B (spec §6.1 options B and C, §6.3): /bots/ingest reads the
body by the connection's kind.

- Cloudflare Logpush: gzipped NDJSON of the http_requests dataset (any
  timestamp format); the job's test upload reads as no requests.
- Vercel drain: a JSON array or NDJSON of log entries; only those with a
  proxy object are requests, build and function output is skipped.
- 00184: ai_bot_usage gains raw_records, and ai_bot_count_raw counts a log
  sender's batch under the usage row's lock. Batches are read while the
  month is under the plan's raw cap (Growth 20M, Enterprise 200M), only
  counted after. Verified events from a whole file are written in chunks
  of 500.
- Creating a Logpush or Vercel connection returns what to copy: a Logpush
  job filtered at the edge to the bot list with the secret as a header,
  or a drain's endpoint, header and format.
- The sender body is read raw before the app's JSON and form parsers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): connect AI bots from Cloudflare or Vercel in the sources strip

AT-010 part C (spec §6.1, §6.4, §7): the sources strip's AI bots card
opens a dialog to connect the brand's own Cloudflare Worker, Logpush job
or Vercel drain.

- The card is locked with Upgrade on a plan without the bot report
  (Starter), offers Connect, then waits for the first request, then shows
  the last one; Manage opens the same dialog.
- The dialog says what each way costs on the customer's own Cloudflare or
  Vercel bill before connecting. After it, it shows the settings to copy
  (the Worker, a Logpush job, or a drain's endpoint and header), with the
  secret in them once. It lists connections with their last request,
  revokes one in two steps, and shows the month's use and when the cap
  paused detailed rows.
- Server actions in lib/actions/ai-bots.ts and card state helpers in
  lib/ai-bots.ts. SourceCard moves to its own file.
- The dialog's content can't widen past it: long code scrolls inside its
  box.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): report which AI bots read the site, and cited pages no search bot read

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list AI visits that landed on a missing page, with a redirect to suggest

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(action-center): raise AI Traffic alerts as signals: weekly drop, new platform, broken links, unread cited pages

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): e-mail a weekly AI Traffic digest with the summary line and the top three changes

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): lay out the weekly digest in the brand's style, with cards, daily and platform bars

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): build the bot ingest endpoint from the public URL and cap its counters

Review of #1179:
- The endpoint written into a Worker, Logpush job or drain came from the
  request's Host. It now comes from PUBLIC_SERVER_URL (https; http only on
  localhost outside production), and no connection is made without it.
- ai_bot_daily grew by about a row an event past the month's cap. Hits past
  it now go on one '(other)' row per bot and day, and /bots/ingest has a
  per-connection limit (600 a minute, keyed by the secret's hash).
- Also: the Worker passes requests through on its own errors and sends the
  page without its query string, and ingest errors go to the app logger.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): group Google pages by a stored key and resume the page backfill

Review of #1177:
- ai_traffic_google_pages spent its time on normalize_page_path, twice a
  row (4 s warm, 18 s cold on 110k rows). gsc_page_stats now stores
  page_key as a generated column and the function groups by it; only the
  ranked rows work out their display path. Plus an index on date for the
  table-wide prune.
- A first page sync cut short left 28 days of history for months. The sync
  now reads the 190 days until one gets through them all for the property
  (brands.gsc_pages_backfilled_property), and drops the old property's
  pages when it changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): read log files without blocking, and each one once

Review of #1180:
- gunzipSync on up to 64 MB and a synchronous parse could hold up the API.
  Files are now inflated asynchronously to at most 16 MB, hold at most
  20,000 lines (413 otherwise), and are parsed 1,000 lines at a time; the
  Logpush job we suggest sends at most 10,000 records a file.
- A file retried after a timeout was counted twice. Each connection's
  files are claimed by the SHA-256 of their body (ai_bot_ingested_files,
  kept 7 days) and a resent one is answered without reading it; a read that
  fails gives its claim back.
- Also: a line with an unreadable time is dropped, not the whole file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): keep the bot connection's secret up and the search-bot alert honest

Review of #1182:
- Connecting from the report section lost the secret: the page's revision
  bump took the dialog down. It now keeps the connections it was opened
  with while the section reads again (with a test of the flow).
- Stale bot data listed every cited page. ai_bot_report now gives the list
  only while a live connection sent within 2 days and no search hits went
  past the month's cap in the 30 days (alert_state 'on'); otherwise the
  section says the alert is paused. '(other)' rows aren't pages.
- "All time" scanned every row: it covers the last 90 days here (labelled
  so), the first and last day come from the index's ends, the rows are
  added up once by bot and page, and the uncrawled check uses not exists.
  An export whose bot report fails keeps its other sheets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): count only the visits that found a page missing, per full address

Review of #1192:
- Visits counted pageviews from before the page broke. They now count only
  404, 410, or no status with a not-found title.
- Pages that differ only by query string were merged, so a deleted
  /index.php?route=product&id=42 could suggest redirecting /index.php, the
  whole site. The status is decided per address (path plus query, utm_*
  left out), and a path is broken only when none of its addresses last
  answered 2xx or 3xx.
- Also: the tab count comes with the Pages read (no broken-links pipeline on
  every load, and the card stays up if that list fails), and the column
  change gives up after 3 s instead of queueing beacon inserts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(signals): read Analytics days as a list, end weeks at their last second, let F02 run without Site Audit

Review of #1195:
- analytics_days is a jsonb array of days, so Number() made it 0 and every
  alert said "from AI results". It's counted by length now, with fixtures
  of the real shape.
- Midnight bounds with p_to_inclusive false put a boundary day's Analytics
  in both weeks. The weeks are read to their last second, inclusive.
- cited_page_uncrawled couldn't become an action without Site Audit: F02
  requires only tracking now; its audit tasks still need an audit and the
  planner drops them for a brand without one.
- The uncrawled-page signal is raised only while the bot data is whole
  (ai_bot_report's alert_state 'on').
- Also: a new AI platform needs 3 visits and a source on the list, since the
  beacon is public.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): skip the digest where the pulse is off and retry a week left unsent

Review of #1196:
- Brands whose Daily Pulse is off got the digest. It's skipped for them
  (no settings row still gets it), and Settings shows it off with why.
- The boundary Monday's Analytics counted in both weeks: the weeks are read
  to their last second, inclusive.
- A week was lost to one failed Monday. The sweep runs Monday to
  Wednesday, retries a failing read, gives a week back when Resend refuses
  the e-mail, and takes over a claim older than an hour that never sent
  (ai_traffic_digests.sent_at).
- Also: the brand list is paged past 1,000, a page or platform back after a
  quiet week isn't called "its first AI visit", and members get select on
  ai_traffic_digests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): take each Google page's prompt from its latest citation

The fallback prompt for a page in "Is AI taking Google clicks?" counted every citation of the page over 90 days, which read every answer that cited it (35,798 on the largest brand, 15 s cold, past the 8 s timeout). It now reads the page's latest citation and that one answer, at most one each per ranked page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): list title-only broken pages and stop suggesting redirects for query routes

ai_traffic_broken_pages read a page with no status at all as unknown rather than not working, so the Safari title rule never listed one; it now coalesces to false. It scans only the pageviews with a status or a not-found title, normalizes each URL once, works out the query part only when there is one, leaves click ids (gclid, fbclid, ...) out of the address, and drops pages the nightly read found working after their last miss. A page whose missing addresses all carry a query gets no redirect (reason query), and redirect targets count only a page's own address.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(signals): keep uncrawled-page signals open while the bot data is stale

The aiBots family returned no findings on alert_state 'stale', which the recorder read as checked and recovered: a sender that stopped for two days resolved every open cited_page_uncrawled signal and its F02 task, and they came back as new once data returned. A stale report now throws DataNotWhole, so the kind is reported unread (logged as info, not an error) and open signals stay open; 'waiting' still finds nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): never send a week's AI traffic digest twice

The week is now marked sent just before the e-mail goes, so a failed sent_at update or a stop after the send no longer leaves a claim the next day's sweep takes over and mails again; both writes are checked and retried, and a record that still fails is logged with the claim kept. deliverEmail tells Resend's answers apart: an error response gives the week back for the next sweep, while no answer (the 15 s timeout) keeps it, since Resend may have sent it and its idempotency keys don't reach the next day. sendEmail keeps its yes or no for the other callers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): stop at the first active prompt that cited a Google page

Ordering a page's citations by created_at still read every one of them from the heap, since the (url_id, brand_id) index has no created_at: 35,700 rows and 7.5 s cold on the largest brand's 50 pages. The lateral now stops at the first citation in 90 days whose prompt is active (2 s there, gkhngyk's measure), which also skips a paused prompt instead of leaving the page without one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk pushed a commit that referenced this pull request Oct 20, 2026
…s 30 days (#1225)

* fix(traffic): hold the uncrawled-pages alert until bot data covers its 30 days

The "cited pages no search bot read in 30 days" list checked only the
ends of its window: the first bot day 30 days back, and a live connection
that sent in the last 2 days. A connection revoked on day -25 with a new
one made yesterday passed both, and every page crawled less often than the
new data's one day was listed. 00190 redefines ai_bot_report so the alert
also needs rows on 28 of the 30 days, or a live connection made 29+ days
ago that still sends (a site bots don't read every day); otherwise it is
'stale', which also pauses the cited_page_uncrawled signals. A partial
index on the '(other)' rows makes the gate's other check a probe.

The connect dialog kept the last connections only while a read was in
flight; a read that failed after a change took it down with the new
secret. The section now keeps the last connections read without an error.

The bot counters are by UTC day, so the 24h range reads yesterday and
today; the section says so instead of "last 24 hours".

Follow-up to #1182's review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): pause the uncrawled alert on any week-long hole in the bot data

00190's exception for a live connection made 29+ days ago let every
long-lived connection skip the 28-of-30 check, so a sender past the
month's raw cap, a Worker route taken down for weeks or a paused Logpush
job reopened the gap the gate was meant to close. The gate now finds the
longest run of days without rows over the same 30 probes and reads
'stale' past 7: a site bots read once a week still passes, a hole of
weeks doesn't.

The sources strip's AI bots card also keeps the last connections it
read when a later read fails, as the report section does, so a failed
read after a create no longer takes down the dialog with the new
connection's one-time secret.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 20, 2026
…ne spinner (#1216)

* feat(traffic): compare AI visits with Google clicks on the AI Referral Trend card

AT-008 part A (spec §3.3): the trend card gets a "vs Google clicks" tab.
It draws AI visits and Google organic clicks, each indexed to 100 on its
first day with data, with markers on the days actions entered the Action
Center or prompts were added.

- 00180 ai_traffic_google_trend: Search Console clicks per UTC day, the
  first and latest day it has rows for the brand, and the markers.
  Security invoker; RLS decides the brand.
- The Google line is blank (not 0) before Search Console's history and
  after Google's latest reported day, which the view names.
- A range that starts mid-day leaves out its partial first day so it
  doesn't set a misleading 100.
- The 24-hour range offers "Show last 7 days" (Google reports by day).
- Without Search Console the view keeps the AI line and says what the
  Google line needs (§3.8b). The view shows the "Needs Google Search
  Console" tag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list the pages that gain Google impressions while losing clicks

AT-008 part B (spec §3.6): a Google Search Console section with "Is AI
taking Google clicks?" — pages whose impressions rose 15% or more while
their CTR fell 20% or more against the period before, most clicks lost
first. Each row's next step is the Positions panel of a tracked prompt
about the page, or Add prompts when there is none.

- 00181: gsc_page_stats (Search Console by page and day, member select
  policy) and ai_traffic_google_pages. The window keeps the range's
  length and ends on Google's latest reported day (§3.01). Pages need 100
  impressions in the period before. When the page history doesn't reach
  back to that period, it says so rather than reading every page as
  rising. Security definer with an organization check (citations).
- Server: the daily GSC sync also pulls pages. A brand's first page sync
  reads 190 days in 28-day steps, later ones the last 28, and the prune
  keeps 190 days. A failed page step leaves the query rows synced.
- Web: the section with its connection states (§3.8b), the "Needed for"
  list, and the export sheet "Is AI taking Google clicks".

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list the Google queries no prompt tracks, with Track and Track all

AT-009 (spec §3.6): beside "Is AI taking Google clicks?", a card with the
top Search Console queries by clicks that no tracked prompt covers. Track
adds a query as a prompt; Track all adds the listed ones within the plan's
prompt slots (PROMPT-012). The summary line states their number while
Search Console is connected (§3.1, §3.8b rule 5).

- 00182 ai_traffic_google_queries: queries with clicks between two days,
  most clicks first, ending on Google's latest reported day (§3.01).
- Server: GET /api/prompts/untracked-queries/:brandId drops the queries
  an active prompt covers, by the rule Prompt Suggestions uses for Google
  queries, so the two pages agree. Prompts are tokenized once and read
  past the 1,000-row page.
- Web: UntrackedQueriesCard, the summary line's count (counted again after
  tracking), the export sheet "Untracked Google queries" and the "Needed
  for" list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): receive verified AI-bot requests from a brand's edge, within a monthly cap

AT-010 part A (spec §3.7, §6): the ingestion behind the AI bot report.

- 00183: ai_bot_connections (one secret per sender, stored as its
  SHA-256, hidden from members), ai_bot_events (verified rows, 90 days),
  ai_bot_daily (bot x page x day counters), ai_bot_usage (per organization
  and month) and ai_bot_ingest, which stores rows while the month has room
  and always adds counters, locking the usage row so concurrent batches
  can't pass the cap. Pages are keyed like the Pages section's.
- ai-bots.json: OpenAI, Anthropic and Perplexity's training crawlers,
  search crawlers and user fetchers. A request counts only when its user
  agent names one and its IP is in the operator's published ranges, read
  daily. No IP is kept.
- POST /bots/ingest (public, by connection secret) and
  /api/bots/connections/:brandId (list with this month's use, create with
  the secret shown once and the Cloudflare Worker, revoke). Admins and
  managers only; Starter has the report locked.
- Plan caps: Growth 2M stored events a month, Enterprise 20M (overridable),
  Starter 0, self-hosted no cap. Crossing 80% logs the internal alert once
  a month; past the cap only counters are written.
- The daily run prunes rows past their retention.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): read Cloudflare Logpush files and Vercel drains of AI-bot requests, within a raw cap

AT-010 part B (spec §6.1 options B and C, §6.3): /bots/ingest reads the
body by the connection's kind.

- Cloudflare Logpush: gzipped NDJSON of the http_requests dataset (any
  timestamp format); the job's test upload reads as no requests.
- Vercel drain: a JSON array or NDJSON of log entries; only those with a
  proxy object are requests, build and function output is skipped.
- 00184: ai_bot_usage gains raw_records, and ai_bot_count_raw counts a log
  sender's batch under the usage row's lock. Batches are read while the
  month is under the plan's raw cap (Growth 20M, Enterprise 200M), only
  counted after. Verified events from a whole file are written in chunks
  of 500.
- Creating a Logpush or Vercel connection returns what to copy: a Logpush
  job filtered at the edge to the bot list with the secret as a header,
  or a drain's endpoint, header and format.
- The sender body is read raw before the app's JSON and form parsers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): connect AI bots from Cloudflare or Vercel in the sources strip

AT-010 part C (spec §6.1, §6.4, §7): the sources strip's AI bots card
opens a dialog to connect the brand's own Cloudflare Worker, Logpush job
or Vercel drain.

- The card is locked with Upgrade on a plan without the bot report
  (Starter), offers Connect, then waits for the first request, then shows
  the last one; Manage opens the same dialog.
- The dialog says what each way costs on the customer's own Cloudflare or
  Vercel bill before connecting. After it, it shows the settings to copy
  (the Worker, a Logpush job, or a drain's endpoint and header), with the
  secret in them once. It lists connections with their last request,
  revokes one in two steps, and shows the month's use and when the cap
  paused detailed rows.
- Server actions in lib/actions/ai-bots.ts and card state helpers in
  lib/ai-bots.ts. SourceCard moves to its own file.
- The dialog's content can't widen past it: long code scrolls inside its
  box.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): report which AI bots read the site, and cited pages no search bot read

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): list AI visits that landed on a missing page, with a redirect to suggest

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(action-center): raise AI Traffic alerts as signals: weekly drop, new platform, broken links, unread cited pages

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): e-mail a weekly AI Traffic digest with the summary line and the top three changes

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(traffic): lay out the weekly digest in the brand's style, with cards, daily and platform bars

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): build the bot ingest endpoint from the public URL and cap its counters

Review of #1179:
- The endpoint written into a Worker, Logpush job or drain came from the
  request's Host. It now comes from PUBLIC_SERVER_URL (https; http only on
  localhost outside production), and no connection is made without it.
- ai_bot_daily grew by about a row an event past the month's cap. Hits past
  it now go on one '(other)' row per bot and day, and /bots/ingest has a
  per-connection limit (600 a minute, keyed by the secret's hash).
- Also: the Worker passes requests through on its own errors and sends the
  page without its query string, and ingest errors go to the app logger.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): group Google pages by a stored key and resume the page backfill

Review of #1177:
- ai_traffic_google_pages spent its time on normalize_page_path, twice a
  row (4 s warm, 18 s cold on 110k rows). gsc_page_stats now stores
  page_key as a generated column and the function groups by it; only the
  ranked rows work out their display path. Plus an index on date for the
  table-wide prune.
- A first page sync cut short left 28 days of history for months. The sync
  now reads the 190 days until one gets through them all for the property
  (brands.gsc_pages_backfilled_property), and drops the old property's
  pages when it changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): read log files without blocking, and each one once

Review of #1180:
- gunzipSync on up to 64 MB and a synchronous parse could hold up the API.
  Files are now inflated asynchronously to at most 16 MB, hold at most
  20,000 lines (413 otherwise), and are parsed 1,000 lines at a time; the
  Logpush job we suggest sends at most 10,000 records a file.
- A file retried after a timeout was counted twice. Each connection's
  files are claimed by the SHA-256 of their body (ai_bot_ingested_files,
  kept 7 days) and a resent one is answered without reading it; a read that
  fails gives its claim back.
- Also: a line with an unreadable time is dropped, not the whole file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): keep the bot connection's secret up and the search-bot alert honest

Review of #1182:
- Connecting from the report section lost the secret: the page's revision
  bump took the dialog down. It now keeps the connections it was opened
  with while the section reads again (with a test of the flow).
- Stale bot data listed every cited page. ai_bot_report now gives the list
  only while a live connection sent within 2 days and no search hits went
  past the month's cap in the 30 days (alert_state 'on'); otherwise the
  section says the alert is paused. '(other)' rows aren't pages.
- "All time" scanned every row: it covers the last 90 days here (labelled
  so), the first and last day come from the index's ends, the rows are
  added up once by bot and page, and the uncrawled check uses not exists.
  An export whose bot report fails keeps its other sheets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): count only the visits that found a page missing, per full address

Review of #1192:
- Visits counted pageviews from before the page broke. They now count only
  404, 410, or no status with a not-found title.
- Pages that differ only by query string were merged, so a deleted
  /index.php?route=product&id=42 could suggest redirecting /index.php, the
  whole site. The status is decided per address (path plus query, utm_*
  left out), and a path is broken only when none of its addresses last
  answered 2xx or 3xx.
- Also: the tab count comes with the Pages read (no broken-links pipeline on
  every load, and the card stays up if that list fails), and the column
  change gives up after 3 s instead of queueing beacon inserts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(signals): read Analytics days as a list, end weeks at their last second, let F02 run without Site Audit

Review of #1195:
- analytics_days is a jsonb array of days, so Number() made it 0 and every
  alert said "from AI results". It's counted by length now, with fixtures
  of the real shape.
- Midnight bounds with p_to_inclusive false put a boundary day's Analytics
  in both weeks. The weeks are read to their last second, inclusive.
- cited_page_uncrawled couldn't become an action without Site Audit: F02
  requires only tracking now; its audit tasks still need an audit and the
  planner drops them for a brand without one.
- The uncrawled-page signal is raised only while the bot data is whole
  (ai_bot_report's alert_state 'on').
- Also: a new AI platform needs 3 visits and a source on the list, since the
  beacon is public.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): skip the digest where the pulse is off and retry a week left unsent

Review of #1196:
- Brands whose Daily Pulse is off got the digest. It's skipped for them
  (no settings row still gets it), and Settings shows it off with why.
- The boundary Monday's Analytics counted in both weeks: the weeks are read
  to their last second, inclusive.
- A week was lost to one failed Monday. The sweep runs Monday to
  Wednesday, retries a failing read, gives a week back when Resend refuses
  the e-mail, and takes over a claim older than an hour that never sent
  (ai_traffic_digests.sent_at).
- Also: the brand list is paged past 1,000, a page or platform back after a
  quiet week isn't called "its first AI visit", and members get select on
  ai_traffic_digests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): take each Google page's prompt from its latest citation

The fallback prompt for a page in "Is AI taking Google clicks?" counted every citation of the page over 90 days, which read every answer that cited it (35,798 on the largest brand, 15 s cold, past the 8 s timeout). It now reads the page's latest citation and that one answer, at most one each per ranked page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): list title-only broken pages and stop suggesting redirects for query routes

ai_traffic_broken_pages read a page with no status at all as unknown rather than not working, so the Safari title rule never listed one; it now coalesces to false. It scans only the pageviews with a status or a not-found title, normalizes each URL once, works out the query part only when there is one, leaves click ids (gclid, fbclid, ...) out of the address, and drops pages the nightly read found working after their last miss. A page whose missing addresses all carry a query gets no redirect (reason query), and redirect targets count only a page's own address.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(signals): keep uncrawled-page signals open while the bot data is stale

The aiBots family returned no findings on alert_state 'stale', which the recorder read as checked and recovered: a sender that stopped for two days resolved every open cited_page_uncrawled signal and its F02 task, and they came back as new once data returned. A stale report now throws DataNotWhole, so the kind is reported unread (logged as info, not an error) and open signals stay open; 'waiting' still finds nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): never send a week's AI traffic digest twice

The week is now marked sent just before the e-mail goes, so a failed sent_at update or a stop after the send no longer leaves a claim the next day's sweep takes over and mails again; both writes are checked and retried, and a record that still fails is logged with the claim kept. deliverEmail tells Resend's answers apart: an error response gives the week back for the next sweep, while no answer (the 15 s timeout) keeps it, since Resend may have sent it and its idempotency keys don't reach the next day. sendEmail keeps its yes or no for the other callers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): stop at the first active prompt that cited a Google page

Ordering a page's citations by created_at still read every one of them from the heap, since the (url_id, brand_id) index has no created_at: 35,700 rows and 7.5 s cold on the largest brand's 50 pages. The lateral now stops at the first citation in 90 days whose prompt is active (2 s there, gkhngyk's measure), which also skips a paused prompt instead of leaving the page without one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* perf(traffic): read the AI Traffic page's data side by side, behind one spinner

A range change asked a dozen sections for data through server actions, which Next runs one at a time: each read waited for the one before it (7 reads, 2.1 s locally; far more on production). The page's reads now go through POST /api/traffic/read (lib/traffic-reads.ts keeps each action's name and arguments; the route runs it with the member's session), so the browser sends them together. Until the page and every section have the new range (_range-ready.tsx), only a spinner shows under the header, at most 20 s; a settled range stays shown when a section reads again for a tab. The four sections shown with or without visits now sit in one place, so an empty range doesn't remount them and read their data twice.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): keep only the latest range's reads, and read each range once

gkhngyk's review of #1216:

- The page's own reads run side by side now, so they could land out of
  order: 90d then 24h showed 90d's numbers under "Last 24 Hours", and the
  visit search's "pri" could land after "pricing". loadSummary and
  loadLogs keep only their latest request (useLatestRequest), and the
  effect is split so a visit-list page or filter reads only the list.
- The range gate waits anew on every range change, so All time → 7d →
  All time no longer reads as settled at once; its cap is 10 s, about
  the reads' statement timeout.
- No early spinner return: the gate shows the spinner and the sections,
  mounted behind it, read alongside the summary on the first open.
- Fewer statements per range change: the summary line's Cited, not
  clicked and untracked-queries counts take the Pages card's and the
  Google section's reads (getTrafficPageCounts, getUntrackedQueryCount),
  and the bot connections and prompt quota are read only when they can
  change, not per range.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk pushed a commit that referenced this pull request Oct 20, 2026
…d match the AI bots sheets to the report (#1244)

* fix(traffic): keep the export going without the untracked queries, and match the AI bots sheets to the report

Follow-ups from gkhngyk's AI Traffic reviews:

- #1178: the export read the untracked Google queries without a .catch,
  so an API 5xx failed the whole file. It now leaves that sheet with its
  note and exports the rest, as the AI bot report already does.
- #1182: the AI bots sheet had one row per bot while the By bot type card
  has one row per type; it now has one per type, with its bots. The cited
  pages no search bot read in 30 days get their own sheet, as the report
  lists them (the most cited, then how many more), with a note while the
  bot data is under 30 days or not whole.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(traffic): say an export section couldn't be read instead of that it's empty

When the untracked-queries read or the AI bot report failed, the export
left it out so the rest still exported, but its sheets then said "No
query data from Google Search Console yet" or "No AI-bot requests in
this range", which wasn't true. The route now notes those sections as
unread, and their sheets say "Couldn't read this section; export again
to include it". The uncrawled-pages sheet also tells a paused alert
(stale) from one still waiting for 30 days of data, as the report does.

Review on #1244.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants