Skip to content

feat(traffic): list the pages that gain Google impressions while losing clicks - #1177

Merged
gkhngyk merged 6 commits into
ansvisor:mainfrom
cihan-gyk:feature/traffic-google-pages
Oct 19, 2026
Merged

gkhngyk merged 6 commits into
ansvisor:mainfrom
cihan-gyk:feature/traffic-google-pages

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

AI Traffic Analytics, spec AT-008 part B (§3.6): a Google Search Console section with "Is AI taking Google clicks?". It lists the 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.

Stacked on #1176 (AT-008 part A). This PR's own change is the last commit, 2ec48a6d. Please merge #1176 first.

Why

Spec §3.6: "Is AI taking Google clicks? Pages with impressions up ≥ 15% and CTR down ≥ 20% vs the previous period, plus their AI Overviews impressions. The next step for each page: open Prompts › Positions to see whether Ansvisor is cited in that AI Overview."

gsc_query_stats holds Search Console by query, which can't say which page lost clicks. It also drops anonymised queries. So this PR syncs Search Console by page too.

What changes

Migration 00181_gsc_page_stats.sql

gsc_page_stats holds Search Console by page and day. It has the same shape and member select policy as gsc_query_stats, with an upsert key on (brand_id, page, date).

ai_traffic_google_pages(brand, since, until, latest, min_impressions = 100, limit = 50) returns jsonb:

  • Pages are keyed by lower(normalize_page_path(...)), like the Pages section (00178).
  • Window: it keeps the range's length. With latest, it ends on the latest day Google has reported, like the Google clicks card (00174, §3.01). All time has no period before.
  • Noise floor: a page needs 100 impressions in the period before. Product chose this so 3 → 4 impressions doesn't read as +33%.
  • Short history: when the page history doesn't reach back to the start of the period before (a property connected lately, or a long custom range), it returns incomplete and no rows. Otherwise every page would read as rising.
  • Order: rows come most clicks lost first: the previous CTR applied to this period's impressions, minus the clicks there were.
  • Positions link: each row names one tracked prompt about the page. That is an active prompt whose target URL is the page, else the one whose answers cited it most over the last 90 days.
  • Access: security definer with an organization check, since citation_urls has no member select policy (as in 00178/00179).

Server: gsc-sync.js

  • The daily sync also pulls ['page', 'date'] into gsc_page_stats.
  • First sync: a brand's first page sync reads 190 days in 28-day steps, so each step stays within the row cap. That covers a 90-day range, the 90 days before it, and Google's delay.
  • Later syncs read the last 28 days, like the query sync.
  • Prune: the daily prune keeps 190 days of page stats.
  • Failures: a failing page step is logged and leaves the query rows synced.

Web

  • GoogleSection (_google-section.tsx), after the Pages card and also on the empty view:
    • Header: "Google Search Console" with the "Needs Google Search Console" tag and "data until Oct 17 (Google reports about two days late)". The card header names the days compared: "Oct 11 – Oct 17 vs Oct 4 – Oct 10".
    • Table: Page | Impr. (+45%, both periods in the tooltip) | CTR (3.1% → 1.4%, red, clicks in the tooltip) | Next step.
    • Next step: Positions links to /dashboard/prompts?positions=<id>. Add prompts opens the AT-006 dialog for the page; tracking prompts reloads the list, so the row turns into Positions.
    • Messages instead of rows: none qualify; page data not synced yet; all time; history too short.
    • Overflow note: "N of M pages · the export has them all".
    • Connection states: without Search Console it shows the state in full (§3.8b). "Needed for" now lists the trend's Google line and this section.
  • lib/traffic-google-pages.ts (pure) holds the window, the % rise and the CTR.
  • Export: sheet "Is AI taking Google clicks" in the whole-page Excel/CSV and the card's own buttons. It carries both periods' impressions, clicks, CTR, the rise and the days compared. With no rows it says why.

Not in this PR

Deploy

  1. Apply 00181.
  2. Deploy the server. The next nightly GSC sync backfills 190 days of page stats per brand: up to 7 windows × the usual paging per brand, once.
  3. Deploy the web. Until the backfill runs, the section says page data arrives with the next daily sync.

Related issue

None. Spec AT-008 (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 00181, then run the GSC sync for an organization with a mapped property (Settings › Integrations, or the daily run). gsc_page_stats fills with 190 days.
  2. Open AI Traffic Analytics on 7d and 30d. The section lists the pages whose impressions rose 15%+ while CTR fell 20%+, with the days compared in the card header.
  3. A page a tracked prompt targets (or whose answers cite it) shows Positions, which opens that prompt's panel. Other pages show Add prompts.
  4. On 90d for a property with less history, or on All, the card says why nothing is compared.
  5. Excel/CSV on the card downloads every qualifying page with both periods.

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/)
  • npm run lint passes (run from server/)
  • npm test passes (run from server/): 1697
  • Changes are focused — one concern per PR

Also run:

  • web: yarn test (1659) and yarn build pass.
  • supabase: bash supabase/build-schema.sh; schema.sql updated.
  • Tests:
    • gsc-sync.test.js: page rows; the 190-day backfill windows, with no gap.
    • traffic-google-pages.test.ts: the window for rolling, custom and all-time ranges; the rise and CTR.
    • traffic-google-pages.test.ts (actions): the RPC call and mapping, incomplete history.
    • _google-section.test.tsx: rows, Positions and Add prompts, the "more" line, every empty reason, the not-connected state.
    • traffic-export.test.ts and route.test.ts: the new sheet and its notes.
    • traffic-sources.test.ts: the "Needed for" list.
  • Browser:
    • Setup: temporary page stats on the demo brand, with one page targeted by a prompt.
    • Checked 7d (1 page), 30d (3 pages, most clicks lost first), 90d (history too short), the unmapped property, the Add prompts dialog and the CSV download, in light and dark.
    • Measured at 1440 and 1024 px: no overflow, and no numeric cell wraps.
    • The temporary data was removed afterwards.

🤖 Generated with Claude Code

cihan-gyk and others added 2 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]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk AT-008 part B is stacked on #1176; please merge that first. This PR's own change is the last commit, 2ec48a6d.

Deploy:

  1. Apply 00181: a new table gsc_page_stats and one security-definer function with the usual organization check.
  2. Deploy the server. On the next nightly GSC sync, each brand's first page sync backfills 190 days in 28-day steps (up to 7 windows of the usual paging per brand, once); after that it reads 28 days a day.
  3. Deploy the web.

If you'd like to see the section before the nightly run, a manual sync from Settings › Integrations fills it for one organization.

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]>

@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.

Tested the whole stack on main: server (1,778) and web (1,714) tests pass. Two things to fix before this merges.

1. ai_traffic_google_pages is too slow on a large brand.

  • Load: in a rolled-back transaction on production I filled gsc_page_stats for the largest Search Console brand with about 110k rows (600 pages × 183 days, within the sync's 25k-rows-per-window cap).
  • Timing: as a member, the 90-day view took 3.9–4.3 s warm and 18.5 s cold, against the 8 s timeout.
  • Cause: most of the time is lower(normalize_page_path(g.page)), called twice per row in by_page. normalize_page_path goes through url_decode_safe, which has an exception block.
  • Fix: normalize_page_path is immutable, so a stored column works: page_key text generated always as (lower(public.normalize_page_path(page))) stored. Then group by page_key and normalize only the ranked rows' display path. The same grouping on that column took 46 ms.

2. The 190-day backfill doesn't resume.

  • syncBrandPages reads PAGE_BACKFILL_DAYS only when the brand has no gsc_page_stats row.
  • If the first sync fails after its first 28-day window, those rows make every later sync read only 28 days. v_first > v_prev_since then returns incomplete for the 90-day range for about five months.
  • Resume from min(date) going back, or keep a backfill marker on the brand. A brand whose gsc_property changes should drop its old page rows too.

Not blocking:

  • Uneven row cap: each 28-day [page, date] pull stops at 25,000 rows ordered by clicks, so on a large site the zero-click page-days are what's dropped. Recent days are re-read daily and keep the union of every pull, while older days are read once. The current period then shows more impressions at a lower CTR than the one before. Pulling a day or a week at a time spreads the cap evenly.
  • Prune: the table-wide date < … delete has no index that starts with date.

…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]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Both fixed in a8da601:

  1. gsc_page_stats.page_key is a stored generated column (lower(normalize_page_path(page))). ai_traffic_google_pages groups by it and normalizes the display path only for the ranked rows. I also added an index on date for the table-wide prune.
  2. The backfill resumes. brands.gsc_pages_backfilled_property names the property whose 190 days a sync got through. Until it matches gsc_property, every sync reads the 190 days again (idempotent upserts). When it names another property, that property's page rows are dropped first. Tested in pagesSyncPlan.

I edited 00181 in place since it's unmerged, and re-applied it on the dev DB. A rolled-back run on sample rows groups /Guides/Espresso/ and /guides/espresso?utm_source=x as one page.

Not done (follow-up): pulling a day or a week at a time to spread the 25k cap.

The fix is merged forward through #1196, no force-push.

@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 stored page_key works. Same synthetic load as before (110k rows on the largest brand, rolled back on production), measured as a member:

  • Warm: the 90-day view takes 0.94 s, down from 3.9 s.
  • Cold: the first call still took 15.5 s.
  • Other organization: gets null.

The resumable backfill and the property change look right.

One thing left: the cited fallback.

  • Why it's slow cold: prompt_result_citations has no prompt_id, so cited joins prompt_results for every citation of the ranked pages in 90 days. On that brand, its own URLs had 35,798 citations in 90 days. Cold, those random prompt_results reads are where the 15 s goes, past the 8 s timeout, and a timeout fails the whole section.
  • Fix: take the prompt of each page's latest citation instead of the most-citing one. That reads one prompt_result_citations row per ranked page (url_id, brand_id is indexed) and one prompt_results row, so at most 50.

Not blocking:

  • Restart rather than resume: the backfill restarts from the newest window. A window that always fails would re-read all seven every day.
  • Deploy order: the brand query in gsc-sync.js now selects gsc_pages_backfilled_property, so the server must deploy after 00181. We apply migrations at merge, so this holds.

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Fixed the cited fallback in a1521b1, as you suggested:

  • Each ranked page now takes the prompt of its latest citation in 90 days: a lateral reads one prompt_result_citations row per page (over all of the page's citation_urls ids, order by created_at desc limit 1), then joins that one answer and its prompt. That is at most 50 citation rows and 50 prompt_results reads, instead of every answer that cited the page.
  • Paused prompts: if the latest citation's prompt is paused, the page gets no prompt (Add prompts instead of Positions). Tracking runs active prompts only, so this should be rare.
  • Unchanged: a prompt whose target URL is the page still wins first.

Checked on the dev DB in a rolled-back transaction: a page with three older citations from one prompt and one newer citation from another now gets the newer one's prompt. Server tests pass (1,709), and schema.sql is rebuilt.

The change is in 00181 only. It is merged forward through the stack without force-push:

PR New head
#1178 11a2aff
#1179 6b3fcba
#1180 e2e28d5
#1181 fa77089
#1182 ccb84c1
#1192 0ee23c2
#1195 96f36f1
#1196 04a2870

Each tree is its old head plus this 00181 change.

I left the backfill restart (instead of resume) as a follow-up, as you noted. The fixes for #1192, #1195 and #1196 come next.

@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.

Only one prompt_results read per page now, thanks. But the citation side still reads every citation of the page. order by prc.created_at desc needs created_at for each row, and prompt_result_citations_url_brand_idx is (url_id, brand_id) only. So every citation is a heap fetch before the sort.

Measured on prod, on the largest brand's most-cited own pages:

  • The 10 the card shows: 30,925 of the brand's 35,798 own citations in 90 days, one page alone 13,523.
  • 50 pages: 35,700 citation rows. Cold, that is about 12,200 pages from disk, and it took about 7.5 s. The 8 s timeout then fails the section, and the export (its row limit) reads them all too.
  • Prompts found: 32 of the 50 pages get one.

Suggested fix: drop the sort, and stop at the first citation in the 90 days whose prompt is active:

cross join lateral (
  select pr.prompt_id
  from public.prompt_result_citations prc
  join public.prompt_results pr on pr.id = prc.prompt_result_id
  join public.prompts p on p.id = pr.prompt_id and p.is_active
  where prc.url_id = any (pk.url_ids)
    and prc.brand_id = p_brand_id
    and prc.created_at >= now() - interval '90 days'
  limit 1
) c

On the same 50 pages:

  • Time: 2.0 s, with about 2,100 pages from disk. The citation rows were already cached, so cold adds up to about 1,650 more.
  • Prompts found: 34 of the 50, the most possible, since a paused prompt is skipped instead of leaving the page without one.

The prompt is then any active prompt that cited the page in 90 days, not the latest. That is enough for the Positions link. If the latest matters, it needs an index on (url_id, brand_id, created_at desc) include (prompt_result_id), a few hundred MB on its 5M rows.

The fixes in #1192, #1195 and #1196 check out, and the stack now waits only on this.

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]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Done in 3349594, as you suggested.

  • The fallback: the cited lateral now has no sort. It stops at the first citation in 90 days whose prompt is active, so the sort no longer has to fetch every citation's created_at from the heap.
  • Comments: the header, the CTE and the function comment now say "an active prompt that cited the page", not "the latest".
  • The index: I left out the (url_id, brand_id, created_at desc) index. Any citing prompt serves the Positions link.

Checked on the dev DB (rolled back):

  • both prompts active: the page gets one;
  • one of them paused: the page gets the other one, rather than none.

The function is re-applied on the dev DB, and schema.sql is rebuilt.

Stack: merged forward without force-push. Each tree is its old head plus this 00181 change.

PR New head
#1178 0869341
#1179 b5a1e8a
#1180 a5f572d
#1181 48d0f6f
#1182 84821ca
#1192 e681d2e
#1195 03a5c33
#1196 65ee46e

@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.

Thanks. Measured on prod with the stack applied (00181–00187):

  • On the largest brand's most-cited own pages, the section's 10 rows take 74 ms, and 6 of them get a prompt.
  • The export of all 90 pages takes 2.8 s.
  • A stranger gets nothing.

Server and web tests pass on main with the whole stack merged.

@gkhngyk
gkhngyk merged commit 80d7116 into ansvisor:main Oct 19, 2026
5 checks passed
gkhngyk added a commit that referenced this pull request Oct 19, 2026
…nd Track all (#1178)

* 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]>

* 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): 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): 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
…within a monthly cap (#1179)

* 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]>

* 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): 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): 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
…bot requests, within a raw cap (#1180)

* 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]>

* 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): 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): 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
…es strip (#1181)

* 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]>

* 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): 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): 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
… search bot read (#1182)

* 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]>

* 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): 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): 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
…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 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 added a commit that referenced this pull request Oct 20, 2026
…their backfill (#1253)

Each 28-day [page, date] pull stopped at the 25,000-row cap ordered by
clicks, so on a large site the dropped rows were zero-click page-days,
and recent days, re-read daily, kept more of them than older days read
once. The page sync now pulls a week at a time (PAGE_WINDOW_DAYS), so the
cap falls evenly.

The 190-day backfill restarted from the newest window on every run until
one got through, so a window that kept failing made every daily run
read the whole history again. 00201 adds brands.gsc_pages_backfill_from,
the oldest day read so far, kept after each window: a sync cut short
resumes after it the next day. gsc_pages_backfilled_property now names
the property the page rows belong to, set once its last 28 days are in;
a brand backfilled before reads as done, and a new property still drops
the old one's pages first.

Follow-up to #1177's review.

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[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