Skip to content

feat(prompts): keep per-brand usage counters for the tracked prompts cards - #1053

Merged
gkhngyk merged 14 commits into
ansvisor:mainfrom
cihan-gyk:feature/prompt-usage-counters
Oct 16, 2026
Merged

gkhngyk merged 14 commits into
ansvisor:mainfrom
cihan-gyk:feature/prompt-usage-counters

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Stacked on #1034 (only active prompt locations count toward the limit). Until #1034 merges, this PR also shows its commits. This part is the last commit, d029650.

Summary

PROMPT-012 replaces the one-line "781 / 1000 prompt locations" meter above the Tracked Prompts table with usage cards:

  • This brand: Active prompts and Total prompts.
  • Account: Active prompts, Prompt locations and Slots left.

This is part 1, the data. Part 2, the cards themselves, follows in its own PR.

The spec requires that a page view never counts the prompts table, with p95 < 100 ms and a payload under 1 KB. So the numbers come from counters kept on every write.

Counters (migration 00139)

  • prompt_usage_counters: one row per brand, holding active prompts, paused prompts and active prompt locations. Locations follow org_prompt_location_usage from feat(prompts): count only active prompt locations toward the plan limit #1034: an active prompt counts greatest(array_length(regions), 1); a paused one counts none.
  • Kept current by triggers: statement-level triggers on prompts and prompt_sets rebuild the affected brands in the same transaction as the write. That covers a prompt added, paused, resumed, edited, moved or deleted, and a set deleted (its prompts cascading) or moved to another brand.
    • Why rebuild instead of adding deltas: a missed case can't leave a row wrong for good.
    • Concurrency: a per-brand advisory lock is taken before the rebuild, so the last of two concurrent writers counts both changes.
    • Bulk writes: a bulk insert or a plan alignment rebuilds each brand once.
  • prompt_usage_actual(): the one place the counts are computed from prompts. The rebuild, the backfill and the nightly check all use it.
  • prompt_usage_summary(brand): the brand's counts plus its account's active prompts, brands and locations, read from the counter rows only. It is security invoker, so a session only gets its own organization's brands. Database time on the demo brand is 0.6 ms, and the plan never touches prompts.
  • New indexes: prompts.prompt_set_id and prompt_sets.brand_id. The rebuild looks prompts up through them, and neither had an index.
  • Backfill: a single statement with no advisory locks (one lock per brand could exhaust the lock table). The CREATE TRIGGERs already hold off writes to these tables until the migration commits.

Nightly check

runDailyTracking now calls checkPromptUsageCounters(), which runs repair_prompt_usage_counters(). That function:

  • compares every row with prompt_usage_actual(), including a brand moved to another organization;
  • rebuilds the rows that differ;
  • returns them for the log ([prompt-usage] counters drifted…).

It runs non-blocking, like the pulse and signal catch-ups.

Endpoint

GET /api/prompts/usage?brandId=… returns the shape from the spec:

{
  "plan": { "key": "enterprise", "name": "Enterprise plan", "locationLimit": 1000, "cta": "contact" },
  "brand": { "active": 702, "paused": 7, "total": 709 },
  "account": { "activePrompts": 1248, "brands": 3, "locationsUsed": 781 },
  "updatedAt": "2026-10-15T09:12:00.000Z"
}
  • Route, not server action: Next.js runs a client's server actions one at a time, so a server action would queue behind the table's data load. The spec says the table must never wait for the cards.
  • One round trip: the brand, its organization's plan columns and the counts are read together.
  • Plan: read from the account on the server (planFromOrgRow, taken out of getOrgPlan so the MCP server can use it), Enterprise overrides included.
    • locationLimit is null when unlimited: self-hosted, or an Enterprise account whose limit isn't set yet.
    • cta is upgrade_growth (Starter), upgrade (Growth), contact (Enterprise), or null (self-hosted).
  • Not cached: the counters are current after every write, and the cards will refresh right after the user's own changes. A 60 s cache would only delay that.
  • Size: 232 bytes.

MCP

The new get_prompt_usage tool, with its REST mirror GET /api/mcp/prompt-usage?brand_id=, returns the same summary, so the Agent Chat can answer "how many prompt slots do we have left?". docs/guides/mcp-server.mdx lists it, and the tool count is now 30.

Product decisions (from the spec's open questions)

Question Answer
Unit of the limit Prompt locations, account-wide (as live).
Starter / Growth limits 50 / 200.
Paused prompts Free their slots (#1034).
Total prompts Active + paused.
Unlimited plans Self-hosted, or Enterprise without a limit set: locationLimit: null. The cards will say "Unlimited".
Custom plan No separate label. Ansvisor sets each Enterprise customer's limit, so the label is always "Enterprise plan".

Review

I ran a code review before opening this. It found 10 things; 6 are fixed:

  • the backfill took one advisory lock per brand;
  • the nightly check ignored a brand that moved to another organization;
  • the route chained avoidable queries;
  • a database error on the brand lookup came back as 404;
  • the route had no test;
  • the count formula was written out three times.

Left as is:

  • Bulk import cost: import_prompts (00122) inserts row by row, so a bulk import rebuilds its brand once per row. For 500 rows into a 1,000-prompt brand, that is well under a second.
  • Old count on the page: the page still calls getLocationQuota (the old count) on every view. Part 2 replaces that meter with these cards.
  • Isolation level: a REPEATABLE READ writer could rebuild from a stale snapshot. PostgREST runs at READ COMMITTED, and the nightly check corrects it.
  • TRUNCATE: it fires no row triggers. The nightly check corrects it.

Related issue

None. Product spec: PROMPT-012 (Tracked Prompts usage cards). Depends on #1034.

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 supabase/migrations/00139_prompt_usage_counters.sql. Then select count(*) from repair_prompt_usage_counters(); should return 0.
  2. Signed in, open /api/prompts/usage?brandId=<your brand>. The brand numbers match the prompts on its Tracked Prompts page; locationsUsed matches the current meter.
  3. Add, pause, resume or delete a prompt, or change its locations, and reload the URL. The numbers follow right away.
  4. With an API key: GET /api/mcp/prompt-usage?brand_id=<brand>, or ask the Agent Chat how many prompt slots are left.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): 0 errors; the 7 warnings are in code this PR doesn't touch
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run:

  • Web, yarn test: 553/553. New:

    • prompt-usage-summary.test.ts: plan names, limits and CTAs; the row shape; the RPC read;
    • api/prompts/usage/route.test.ts: 200 against the org's plan, the Enterprise limit, self-hosted unlimited, 400 / 401 / 404, and 500 on a database error.
  • Web, yarn build: passed.

  • Server, npm run lint and npm test: 1178/1178, including the new prompt-usage-counters.test.js.

  • supabase/build-schema.sh: schema.sql regenerated.

  • On the dev database, rolled back: the migration plus these checks, each giving the expected counts:

    • a prompt added with 2 regions;
    • paused;
    • resumed with 3 regions;
    • deleted;
    • two prompts inserted in one statement;
    • a set deleted with its prompts;
    • a brand deleted with its set and prompts (no error, no row left);
    • a counter knocked off on purpose, which the nightly check reported and rebuilt.

    The counters also equal org_prompt_location_usage (74 = 74 on the demo brand). After that, I applied the migration to the dev database.

  • In the browser: the route returns the demo brand's numbers (57 active, 4 paused, 74 locations), and 400 / 404 for a bad or foreign id. End to end it took ~200–300 ms locally, almost all of it round trips to the remote dev database; the RPC itself took 0.6 ms.

🤖 Generated with Claude Code

cihan-gyk and others added 4 commits October 14, 2026 16:02
Paused prompts don't run, so they no longer take room on the plan
(org_prompt_location_usage now filters on is_active, 00128). Resuming a
paused prompt brings its locations back, so it is metered like adding
them: setPromptActive refuses with a plan_limit value when there is no
room. That closes the pause, add new prompts, resume the old ones way
past the limit. Location edits on paused prompts cost nothing until the
prompt is resumed.

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

Second review pass on the active-only prompt quota:

- the edit dialog shows a plain message for non-plan failures instead of
  the raw database error;
- setPromptActive returns a failed limit check as a value (ansvisor#427) instead
  of throwing;
- the brand Prompts page keeps its last quota when the refresh after a
  toggle fails, so the location pickers don't become uncapped;
- the prompt-usage doc no longer says paused prompts count;
- tests for a missing prompt, a failed limit check, and location edits
  on paused vs active prompts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves the conflicts with the bulk import (ansvisor#1013): prompt.ts keeps both
setPromptActive and importPrompts, and the Prompts page imports both. The
import RPC (00122) counts locations through org_prompt_location_usage, which
00128 limits to active prompts, so imports follow the same count.

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

PROMPT-012 part 1: the data behind the usage cards, read without counting
the prompts table on a page view.

- Migration 00139 adds prompt_usage_counters, one row per brand (active,
  paused, active prompt locations). Statement-level triggers on prompts and
  prompt_sets rebuild the affected brands in the same transaction, under a
  per-brand advisory lock. prompt_usage_actual() is the one place the counts
  are computed; it backs the rebuild, the backfill and the nightly check.
- prompt_usage_summary(brand) returns the brand's counts and its account's
  totals from the counter rows only (security invoker).
- Indexes on prompts.prompt_set_id and prompt_sets.brand_id, which the
  rebuild needs and neither had.
- GET /api/prompts/usage?brandId= returns the summary with the plan's
  location limit and call to action.
- MCP tool get_prompt_usage and its REST mirror /api/mcp/prompt-usage.
- The daily run checks the counters against prompts, rebuilds any that
  drifted and logs them.

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk PROMPT-012 part 1: per-brand usage counters (migration 00139, kept by triggers), GET /api/prompts/usage and the get_prompt_usage MCP tool. Stacked on #1034; the cards come in part 2. Ready for review when you have a moment.

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 15, 2026
…e-counters

# Conflicts:
#	supabase/schema.sql

@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, approving. On the tree merged with main, schema.sql matches build-schema.sh, server tests pass (1249), web tests pass (789) and CI is green.

Checked against production:

  • The counter formula equals org_prompt_location_usage for all 206 brands (7,326 locations).
  • A rebuild of the largest brand takes 3.9 ms, even before the two new indexes. Writes to prompts are rare enough that the statement-level triggers cost little.
  • Neither index exists yet under another name, and the existing triggers on prompts and prompt_sets don't overlap.

@gkhngyk
gkhngyk merged commit 6adc2c3 into ansvisor:main Oct 16, 2026
5 checks passed
gkhngyk pushed a commit that referenced this pull request Oct 16, 2026
* docs(skills): cover all MCP tools and the AI Visibility Score in the AEO coach skills

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

* docs(skills): teach the AEO coach skills about get_prompt_usage

- List the get_prompt_usage MCP tool and its REST mirror GET
  /api/mcp/prompt-usage (#1053): the brand's active, paused and total
  prompts and the account's prompt locations against the plan limit,
  as on the Tracked Prompts usage cards.
- Explain the unit: prompt locations, account-wide; paused prompts use
  no slots, and resuming one needs free slots like adding one.
- In the prompt coverage audit, check the slots left before suggesting
  new prompts; a null limit means unlimited.

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

---------

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants