Repository navigation
feat(chat): add the counts Why did it move reads (00423 chat_why_cells) - #1871
Conversation
…iles, Help and add-on packs Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC: nothing reads or writes them while the flag is off. Tables, types and the demo's coverage only; the code that uses them comes in the Wave 1 PRs. - 00407: chat_conversations gets shared_at (Share with team: every member of the workspace reads it), last_read_at (unread results), deleted_at (Delete with Undo; deleted chats are hidden from every member) and a title search column; chat_messages gets context_json (what a person's message was scoped to) and a text search column. 'simple' text search, so a chat in any language is found. The author policy now leaves deleted chats out, and a shared policy reads shared ones. - 00408: chat_user_prefs gets the rest of Settings › General and the one-time notices: rail_open, panel_size, default_mode, answer_language, notify_via, show_thought, panel_on_pages, focus_prompted_at, usage_notice_period, legacy_imported_at. - 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file, the composer's 11 types, 5 a message (a trigger backs the server's check), kept 90 days. - 00410: chat_tool_cache (a chat's read results by tool and scope, server only) and each step's and model call's measure: latency, cache hit, truncation, result tokens on chat_run_steps (never granted to members), prompt cache read/write tokens and latency on the ledger. - 00411: chat_files (filed deliverables and saved answers, the workspace's, kept a year, searchable by title, summary and tags), chat_file_task_links, chat_storage_usage kept by a trigger, and the private bucket chat-files. - 00412: help_answer_cache and help_gaps (server only, no workspace or person ids). - 00413: add_on_products seeded with the owner's packs (AI credits $10, $50, $250, $1,000 at half their price in budget, 12 months; storage +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked), add_on_purchases (Admins read), ai_credit_grants and storage_grants (server only), and prompt_improve_usage.grant_id. Members only ever read; every write is the server's. Tool names, tool results and dollars stay server only. web/src/types/supabase.ts carries the new tables and columns; schema.test.ts checks the policies, the server-only tables, the limits and the seeded packs from the SQL; steps.test.ts keeps the step measure out of the member columns. The demo coverage skips chat_files and chat_tool_cache (a person's own Chat work). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pact and suggestions (00417–00422) Chat's Wave 2 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC: nothing reads or writes them while the flag is off. Tables, types, tests and the demo's coverage only; the code that uses them comes in the Wave 2 PRs. Every new table has row level security on; members only ever read, and every write is the server's. - 00417: chat_asks (a run's question cards, at most 4 a run, 2–4 options with exactly one Recommended, checked by chat_ask_options_valid; the answer once) and chat_next_moves (2–4 ranked moves, prompts up to 80 characters, each with its action class and a ghost_ok mark); both readable where their run is. chat_messages.shortcut_id on a person's message only (CHAT-08). - 00418: chat_task_state, the task strip: Chat's own status per Action Center task (queued, writing, ready_for_review, done), the run and the deliverable. action_tasks is not changed. - 00419: chat_agents (status, pause reason, owner, private or workspace visibility, current version, caps per run and month as shares of the AI limit), chat_agent_versions (immutable: skills, instructions, mode, connections, model, scope), chat_agent_triggers (schedule, Signal, KPI, watch rule; at most 5) and chat_agent_runs (queue, statuses, trigger evidence, acting person, brand, action, outcome, cap and use as shares). One run at a time per agent and brand; chat_start_next_agent_run() starts the next queued one under the workspace's limit, Run now and Run agent first. An agent run's chat (chat_conversations.agent_run_id, origin agent) is readable with the run. Agent ids on the Activity log, and the agent settings in chat_settings. CHAT-27: subtasks as child runs (chat_runs.parent_run_id, subtask_title; no message of their own; one level, at most 10), agent_id / agent_run_id / parent_run_id on the ledger, reserve_chat_ai_usage taking the agent run and its cap (old calls still match), and chat_agent_usage_shares() returning shares only (server only, since the budget is its argument). - 00420: chat_why_analyses (the explain_change result per analysis, readable where its chat is) and chat_user_prefs.home_seen_at for "Since you left". - 00421: the impact ledger: ship_events, impact_measurements (one per ship event; the one outcome vocabulary; d7/d14/d30/d90 checkpoints) and impact_control_sets (per checkpoint). Every member reads them. - 00422: chat_suggestion_feeds and chat_suggestions (CHAT-26): one a day per person and brand, own rows only. web/src/types/supabase.ts carries the new tables, columns and functions; schema.test.ts checks the Wave 2 policies, limits, vocabularies and the server-only functions from the SQL. The demo coverage skips the five new brand-scoped tables (a demo brand runs no agent, ships nothing and gets no suggestions). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…runs' places Review fixes for Wave 2's tables, before they ship: - reserve_chat_ai_usage reads the agent run from the chat (chat_conversations.agent_run_id), so a subtask's step counts toward its parent's run; a p_agent_run_id that isn't the chat's is refused, and p_run_cap is always the whole run's cap. search_path is now ''. - chat_start_next_agent_run needs a workspace limit, never starts a run of an archived agent or a deleted brand, and starts a triggered run only while its agent is active (Run now and Run agent also on a paused or draft one). - A run paused at its AI cap keeps its agent and brand place, so an Admin's Continue can't collide with the next run. - ship_events.agent_run_id, for an agent run's Outcome (CHAT-21 §I 43). Co-Authored-By: Claude Opus 5.5 <[email protected]>
explain_change (CHAT-22 §1) compares a metric prompt × engine by prompt × engine between two periods. chat_why_cells sums the Insights rollups for it in one call: per prompt, platform, model, location and period, the tracked day rows and those where the brand was named or cited, answers, mentions, citations, positions and the answers naming a tracked competitor; and the same sums per day for the change point. The competitors' counts are grouped on their own before they meet the brand's, so no join repeats a row. Server only (service role; revoked from public, anon and authenticated), stable, security invoker, search_path ''. Each period and the series is 92 days at most, a before b, so one call stays small. The web checks the brand is the caller's workspace's before it calls. schema.sql rebuilt. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`prompt_id = any ((select ids …))` reads the subquery as rows of uuid[] and fails with "operator does not exist: uuid = uuid[]" when the function runs (plpgsql checks it only then). Found by calling it on the dev database; a topic now narrows the demo brand's 47 cells to 32. Co-Authored-By: Claude Opus 5.5 <[email protected]>
chat_why_cells now sums the brand's total_mentions and the competitors' mention_count (share of voice as the Insights card counts it), gives each day its prompts named or cited and those tracked (visibility as Insights counts it), and says complete: false while a row read predates 00130/00131's columns, as insights_kpi_series does. schema.sql rebuilt. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts: web/src/lib/chat/schema.test.ts (kept the PR's 00423 additions on main's file), supabase/schema.sql (rebuilt with build-schema.sh).
…y_cells Insights' Visibility card is the AI visibility score, whose position factor is the sum of 1/position over the positions. chat_why_cells returned only the sum of positions, so Why could not compute the same Visibility as Insights. Return sum_inv_position per cell and per day. Also read each rollup on one day range of its (brand_id, day) index; the periods still narrow it.
gkhngyk
left a comment
There was a problem hiding this comment.
Looks good with c3a4ba8: current main merged in and one fix commit, described below. Migration 00423 is applied on production before the merge.
Fix (on this branch)
chat_why_cells now returns the Visibility score's position factor. On Insights, the Visibility card is the AI visibility score: 0.6 × mention rate + 0.25 × citation rate + 0.15 × position factor. The position factor is sum_inv_position / position_count (ai_visibility_aggregates_daily, computeAiVisibilityScore). The function returned sum_position but not sum_inv_position. Without it, Why could compute coverage (visible prompts ÷ tracked prompts), but not the number the Visibility card shows.
- Each cell and each day now also returns
sum_inv_position. Nothing else in the payload changes. - Both rollup reads also get one day range,
day between least(p_a_from, p_series_from) and p_b_to, ahead of the three-periodor. Now the(brand_id, day)index takes the range as its index condition. Before, it read every day the brand has and filtered them. Results don't change. - Two new
schema.test.tscases cover these. Both fail without the change.
What we checked
- Number: 00423 is in the Chat block (00400–00449). Neither main nor any open PR uses it.
- Who can call it:
- The function is
security invoker,stable, withsearch_path = ''and schema-qualified names. - Execute is revoked from
public,anonandauthenticatedand granted toservice_roleonly. That's the same pattern aschat_agent_usage_shares. - It reads only. There's no new table, view or policy.
- The function is
- The counts match Insights. Called next to the Insights functions on real data (7 days against the 7 before, the whole brand and with one topic), all of these were equal:
- brand and competitor mentions (
share_of_voice_aggregates_daily) - visible and tracked prompts (
visible_prompt_stats_daily,tracked_prompt_count_daily) - answers, answers naming the brand, answers citing it, and the position factor (
ai_visibility_aggregates_daily, with the fix) - position sum and count (
insights_aggregates_daily) - every day of
dailyagainstinsights_kpi_series.
- brand and competitor mentions (
- The competitor join: no competitor mentions fall outside a brand cell, so the left join drops nothing.
- The guards (92 days, a before b, required arguments) each raise 22023.
- Embeds: none. This PR has no web code.
Follow-ups (not blocking)
- Size and time on a large brand. For the largest brand we track:
- 7 days against 7, with a 30-day series: about 0.5 s and 1.1 MB of JSON (about 2,700 cells).
- The 92-day maximum: about 2.2 s and 2.8 MB (about 7,400 cells).
- Building the JSON takes most of that time. A larger
work_memdidn't help. - It's fine for W2-18 as written. If explain_change only needs the cells that moved, W2-18 could narrow the call by engine or topic, or compact the payload (for example, leaving out
last_atper cell).
- The
citationsmetric.chat_why_analysesallows acitationsmetric. The function returnscitation_answers(for citation rate), nottotal_citations. If Why's "citations" should match the Citations count on Insights rather than Citation rate, it needstotal_citationstoo. - The header comment says "from scheduled tracking only". The rollups include manual runs, as Insights does. The comment could say "as Insights counts it" instead.
Base and tests
this branch = this PR's head abb976f6e + a merge of current main 703a68600, then the fix.
schema.test.tsconflicted, because #1853 landed on main as a squash. I kept the PR's 00423 additions.schema.sqlwas rebuilt withbuild-schema.sh, and a second run leaves it unchanged.- this branch merges clean on current main.
Tests run on this branch:
lib/chat/schema.test.ts: 48 pass, including the 2 new ones, which fail without the fix.lib/guards/plan-row.test.ts: passes.tsc --noEmit, plus eslint and prettier on the changed test file: clean.
gkhngyk
left a comment
There was a problem hiding this comment.
Merging in order with the other approved PRs. This head merges current main; its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build.
Summary
One read-only database function for Chat's "Why did it move" (
explain_change, CHAT-22 §1, W2-18). Stacked on #1853 (Wave 2's tables); behindCHAT_AGENTIC. Nothing calls it yet; W2-18 does.Why a function: the analysis compares a metric between two periods cell by cell (prompt × engine × location). For a brand with 500 prompts on 6 engines over 14 days, that's about 42,000 day rows. Supabase returns at most 1,000 rows per query (
max_rows), so reading them from the web would take 40+ requests.chat_why_cellssums them in the database in one call.00423
chat_why_cells(brand, a_from, a_to, b_from, b_to, series_from, models?, region?, topic?) → jsonbcells: one entry per prompt, platform, model, location and period (aorb), with:runs(tracked days) andvisible_runs(days the brand was named or cited);answers,mention_answers,citation_answers;sum_positionandposition_count;brand_mentions(total_mentions) andcompetitor_mentions(the competitors'mention_count), so share of voice counts mentions as the Insights cards do (insights-kpis.ts);last_at.daily: the same sums per day, fromseries_fromtob_to, for the change point, plusvisible_promptsandactive_prompts(distinct prompts named or cited, and tracked), so visibility follows the app's visible-prompts definition.complete: false when a row in the range still has NULLmention_answersornegative_count(not yet rewritten byrefresh_insights_daily), asinsights_kpi_seriesflags it.insights_prompt_dailyandinsights_competitor_prompt_dailyon their(brand_id, day)index.{"cells": [], "daily": [], "complete": true}.security invoker,stable,search_path = '';revoke all … from public, anon, authenticatedandgrant execute … to service_role, aschat_agent_usage_sharesin 00419;plpgsqlrather thansql, only for the guards; it reads and writes nothing else.supabase/schema.sqlwas rebuilt withbuild-schema.sh.schema.test.tscovers:chat_why_cellsamong the server-only functions;search_path, and no writes;[].Related issue
None. Chat Wave 2 (W2-18, CHAT-22).
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
psql -1 -f supabase/migrations/00423_chat_why_cells.sql).select public.chat_why_cells('<brand>', current_date-14, current_date-8, current_date-7, current_date-1, current_date-30);. It should returncellsanddaily, with numbers as numbers.a_to >= b_from, raises 22023.has_function_privilege('anon' | 'authenticated', …, 'execute')is false.yarn vitest run src/lib/chat/schema.test.ts(46 tests).Applied on the dev database and called with the demo brand, using a = 3–9 Oct, b = 10–16 Oct and the series from 17 Sep:
{"cells": [], "daily": [], "complete": true};completeis true, and the new mention and prompt counts come back as numbers;anonandauthenticatedcan't execute it.Calling it found one bug that the static tests couldn't see, now fixed in the second commit.
= any ((select …))failed withuuid = uuid[], so the topic filter is now aninsubquery. The third commit makes share of voice and visibility match the Insights cards (found in W2-18's review) and addscomplete.Checklist
yarn lintpasses (run fromweb/): eslint clean on the changed test fileyarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)help/(or no user-visible change): no user-visible changeFor production (@gkhngyk): apply 00423 after 00417–00422 (#1853), in one transaction. No bucket, cron or env.
Note on old days:
mention_answersin both rollups can be NULL on days written before 00130, untilrefresh_insights_dailyrewrites them.complete: false.🤖 Generated with Claude Code