Skip to content

feat(tracking): capture & store observed query fan-out (Cloro searchQueries) - #341

Merged
gkhngyk merged 2 commits into
mainfrom
feature/fanout-capture
Jul 4, 2026
Merged

gkhngyk merged 2 commits into
mainfrom
feature/fanout-capture

Conversation

@gkhngyk

@gkhngyk gkhngyk commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Capture and store the observed query fan-out — the sub-queries an AI answer engine actually ran to build its answer — which Cloro already returns in the poll/webhook response but we discarded at every layer. This is the storage/capture foundation; the product surface (a "Query Fan-out" tab) is #333.

No extra AI/scraper spend — the data is already in the response we poll.

Changes

  • Migration 00021 — prompt_results.search_queries jsonb NOT NULL DEFAULT '[]'::jsonb. Applied to the hosted DB; all 40,607 existing rows defaulted to [] (verified). supabase/schema.sql regenerated.
  • cloro-scraper.js
    • buildRequestBody: opt in with include.searchQueries: true for the ChatGPT-family task (free; ChatGPT usually returns it empty, harmless).
    • new normalizeSearchQueries(result, scraperId) → rich, engine-labelled array [{ query, engine?, source_platform }]:
      • Perplexity search_model_queries → keeps its engine label
      • Copilot / ChatGPT / Grok / Gemini searchQueries (string[]) → mapped
      • blank / non-string entries dropped; anything else → []
    • parseScraperResponse returns search_queries on the default (web-engine) branch.
  • Persist search_queries in both insert sites: cloro-result-handler.js (webhook path) and tracking-worker.js (polling path).
  • +4 parser tests (Copilot string[], Perplexity engine preserved, blanks dropped, empty/absent → []).

Verified end to end (live Cloro, real module)

Ran the actual cloro-scraper.js module against live Cloro:

  • Copilot → [{ query: "…", source_platform: "copilot-web" }]
  • Perplexity → [{ query: "…", engine: "web", source_platform: "perplexity-web" }]

Matches the per-platform shape/reliability established in #332 (Copilot primary; Perplexity secondary/web; ChatGPT usually empty).

Related issue

Closes #332. UI surface is #333 (depends on this).

Type of change

  • feat — New feature (data capture)

How to test

  1. From server/: npm run lint, npm run format:check, npm run test (97 tests) pass.
  2. Run tracking for a brand with a Copilot or Perplexity prompt (needs this branch's code to process the result insert — in webhook mode that's whichever server owns /cloro/callback).
  3. SELECT platform, search_queries FROM prompt_results WHERE search_queries <> '[]' ORDER BY created_at DESC LIMIT 5; → Copilot rows carry [{query, source_platform}], Perplexity [{query, engine, source_platform}]; ChatGPT may stay empty (expected).

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • npm run lint passes (from server/)
  • npm run format:check passes (from server/)
  • Migration applied + schema.sql regenerated
  • Changes are focused — one concern per PR

Answer engines run their own sub-queries to build an answer; Cloro
returns these in the poll/webhook response but we discarded them at every
layer. Persist the OBSERVED fan-out (straight from the engine, no extra
AI/scraper spend) so #333 can surface it. (#332)

- migration 00021: prompt_results.search_queries jsonb NOT NULL DEFAULT
  '[]' (existing rows default to []); schema.sql regenerated.
- cloro-scraper.js: opt in with include.searchQueries: true for the
  ChatGPT-family task; new normalizeSearchQueries() returns a rich,
  engine-labelled array [{ query, engine?, source_platform }] —
  Perplexity's search_model_queries keeps its `engine`, Copilot/ChatGPT/
  Grok/Gemini map their string[] searchQueries, blanks dropped.
- persist search_queries in both insert sites: cloro-result-handler.js
  (webhook path) and tracking-worker.js (polling path).
- +4 parser tests.

Verified end to end against live Cloro with the real module: Copilot →
[{ query, source_platform }], Perplexity → [{ query, engine: 'web',
source_platform }]. No new AI/scraper spend — the data is already in the
existing poll/webhook response.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR adds first-class capture and persistence of Cloro’s observed query fan-out (the sub-queries engines actually ran) by introducing a new prompt_results.search_queries JSONB column and wiring the Cloro parser + tracking ingestion paths to populate it.

Changes:

  • Adds prompt_results.search_queries jsonb NOT NULL DEFAULT '[]'::jsonb via migration 00021 and regenerates supabase/schema.sql.
  • Extends cloro-scraper to request and normalize fan-out into a rich shape [{ query, engine?, source_platform }] and returns it as search_queries.
  • Persists search_queries in both polling (tracking-worker.js) and webhook (cloro-result-handler.js) insert paths, with parser tests covering key shapes.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
supabase/schema.sql Regenerated schema to include new prompt_results.search_queries column + comment.
supabase/migrations/00021_prompt_results_search_queries.sql Adds the search_queries JSONB column with default [] and documentation.
server/src/workers/tracking-worker.js Persists search_queries on the polling insert path.
server/src/lib/cloro-scraper.test.js Adds parser tests for search_queries normalization cases.
server/src/lib/cloro-scraper.js Enables include.searchQueries and normalizes fan-out into rich items.
server/src/lib/cloro-result-handler.js Persists search_queries on the webhook/central handler insert path.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 305 to 309
model_used: aiResponse.model,
region: meta.region,
competitor_mentions: metrics.competitorMentions,
search_queries: aiResponse.search_queries ?? [],
});
Comment on lines 64 to 69
region: region ?? null,
competitor_mentions: metrics.competitorMentions,
shopping_cards: aiResponse.shopping_cards ?? [],
inline_products: aiResponse.inline_products ?? [],
search_queries: aiResponse.search_queries ?? [],
})
Comment on lines +98 to +105
if (Array.isArray(result.search_model_queries)) {
return result.search_model_queries
.filter((q) => typeof q?.query === 'string' && q.query.trim() !== '')
.map((q) => ({
query: q.query,
...(q.engine ? { engine: q.engine } : {}),
source_platform: scraperId,
}));
Comment on lines +108 to +112
if (Array.isArray(result.searchQueries)) {
return result.searchQueries
.filter((q) => typeof q === 'string' && q.trim() !== '')
.map((q) => ({ query: q, source_platform: scraperId }));
}
… review)

- normalizeSearchQueries trims each stored `query` (both the Copilot
  string[] and Perplexity paths) so the same sub-query can't fragment into
  whitespace variants — the #333 aggregation groups by query string.
- Perplexity `engine` is now kept only when it's a non-empty string (and
  trimmed), never a stray non-string value.
- Both insert sites (cloro-result-handler webhook path, tracking-worker
  polling path) coerce with `Array.isArray(...) ? ... : []` instead of
  `?? []`, so a malformed non-array value can't be persisted into the jsonb
  column that downstream unnest/jsonb_array_length assume is an array.
- +2 parser tests (trim canonicalization, non-string/blank engine dropped).

Addresses the Copilot review on #341.
@gkhngyk
gkhngyk merged commit 0cb11b4 into main Jul 4, 2026
4 checks passed
@gkhngyk
gkhngyk deleted the feature/fanout-capture branch July 4, 2026 16:40
gkhngyk added a commit that referenced this pull request Jul 6, 2026
…e) (#351)

Migrate the last console.* calls (lib/cloro-scraper.js) to the module-level
pino logger. This file was deliberately held back from the earlier slices
to avoid churn with the query fan-out work (#341, now merged).

- submit/poll per-task chatter (task submitted, completed, polling) →
  logger.debug({ taskId, scraperId, ... }); operational start → logger.info
  ({ taskType, scraperId, region }); failures/timeouts → logger.error
  ({ ..., status/reason }). Customer prompt text is no longer written to the
  submit log — taskType/scraperId/region identify the task instead.

Closes #303: every non-script console.* in server/src now routes through the
structured logger. Phase 2 of #245 is complete (parts: #330, #334, #335,
#336, #337, and this).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(tracking): capture & store observed query fan-out (Cloro searchQueries / search_model_queries)

2 participants