Repository navigation
feat(demo): keep the demo brand's sample data from changing or costing anything (demo brand, part 4) - #1737
Conversation
… counts Migration 00380 adds brands.is_demo, demo_version, demo_built_at and demo_hidden_at, one demo brand per organization (partial unique index) and policies that let members read it but never insert, change or delete one. The plan's prompt-location quota, the usage cards' account totals and the web's brand limit leave the demo brand out; the health report's fan-out share leaves out its answers. The brand delete route refuses it: the demo brand is hidden, not deleted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The daily tracking list, the job claim and recovery (activeBrandFilter / isBrandActive), the signal catch-up, the pulse, the task writer, executor and checks, action validation and Improve outcomes, the Insights sweep, brand facts, Search Console and Analytics syncs, page opportunities, the traffic digest, auto-audits, catalog feeds, Webflow status and volume analysis all leave demo brands out: their data is sample data and nothing may track, write or spend for it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
lib/demo/ builds an organization's demo brand in its own brands: Brewline
Coffee (brewline.example) with fictional `.example` competitors and
publishers, 12 prompts in 3 topics, 6 engines and a run every 3 days over
a month (720 short answers) with citations, product cards, searches and
volumes. Answers are raw engine responses run through tracking's own
parseScraperResponse, parseResponse and the result and shopping card rows
(now pure resultRow and shoppingCardRows in cloro-result-handler.js), and
the rollups are rebuilt by the nightly run's own functions.
ensureDemoBrand creates it, rebuilds it in place (same ids) when
DEMO_VERSION moves on or its data is three days old, and leaves it alone
otherwise; concurrent visits share one build (one-per-org index, a
compare-and-set claim, a lease). Modules are { name, tables, build }, and
a coverage test fails on any brand_id table the demo neither builds nor
lists as skipped or pending.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
POST /api/demo creates or rebuilds the organization's demo brand for any
member and returns { brandId, version, rebuilt }; PATCH /api/demo
{ hidden } hides or shows it for admins and managers ({ brandId, hidden },
404 no_demo without one). Both stay open once a plan has ended.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… plan
A job claimed for a demo brand ("Run now", the internal trigger, a retry
or the recovery) was cancelled as subscription_inactive, as if the plan had
ended. It now says demo_brand: brandStopReasons tells why no work may start
for a brand, and activeBrandFilter is built on it. Nothing is tracked,
generated or counted before the cancel: the on-demand cap counts the
brand's own jobs, and AI usage is recorded by the workers, which never run.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rand The demo brand's data is sample data, so nothing asked of it may change it or start a cost. A middleware after decodeToken (before the plan's check, so the answer is the same with a plan or without) refuses every write that names a demo brand: in the path, the body, the query, or through the row it acts on (a draft, an opportunity, a prompt, a task...). Every write route under /api is named, guarded or open with its reason (onboarding, the organization's own integrations, stopping work, the demo routes, brand delete's own 409); a test reads the route files and fails on one that isn't. Reads and exports stay open; brand facts are read only as kept on a demo brand, so its site is never fetched. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…base Members can write a brand's rows straight through Supabase, under RLS, past the API's 402. Migration 00381 adds refuse_demo_brand_writes(), a BEFORE INSERT/UPDATE/DELETE row trigger that raises 42501 'demo_brand' for a demo brand's row unless the role bypasses RLS (the service role the server and the demo generator write with). It is attached to the 24 tables people can write that carry a brand_id, and, through their parent row, to the 13 that reach their brand another way (prompts through prompt_sets, prompt notes and target URLs through prompts, a draft's inputs and sources through content_drafts, tasks and events through actions...). A test reads the policies and triggers from the migrations and fails on a table people can write that belongs to a brand and lacks it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…demo brand The internal endpoints the MCP calls (a content brief, a Site Audit, an Improve action) trust CRON_SECRET and never meet the API's middleware. Each now answers a demo brand with 402 demo_brand before it calls the model, starts an audit or writes an action; the MCP relays the message. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every organization gets a demo brand, so its sample rows would pile up for workspaces that left. The daily run now clears the data of demo brands built over 14 days ago (a visit rebuilds every few days, so these weren't opened since), 200 a night at most: through clearDemoData, the path a rebuild takes, so rows go in the modules' reverse order. The brand row stays with no version and no build time, and the next visit builds it again in place, with the same ids. The clear holds the brand as a build does, so a visit at the same moment waits for it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The cache test reads 10,000 brands; filtering them with includes() took seconds and timed out under a full run. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s and reports Four demo modules over core's answers: signals and a month of actions (tasks, trail, measured outcomes, a task waiting for review, ready-made KPIs, Getting started with its page steps opened), prompt clusters, content opportunities, Editor drafts and Plan marks, prompt, topic and Improve suggestions, and two saved reports. Numbers are counted from the demo's own answers; shapes come from the engine's own functions. detect.js exports single and promptTarget so the demo writes signals in their shape. Co-Authored-By: Claude Opus 5.5 <[email protected]>
DEMO_MODULES runs core, suggestions, actionCenter, content and reports; DEMO_VERSION 2 rebuilds existing demo brands on their next visit. The coverage lists move the workflow tables to built, skip the engine's internal queues and logs and the org-level author default, and leave the draft shopping check to demo-site with the catalog. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ith auditContextOf buildAuditContext fetches the page, robots.txt and llms.txt, then hands them to auditContextOf, which parses the HTML once and extracts its text as before. A page that isn't fetched (the demo brand's) is read exactly as a fetched one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brewline's website (site-world.js) and its traffic: 90 days of Google Analytics as GA4 reports mapped by ga-sync.js (AI sessions by source and page, ChatGPT Shopping's feed visits, pages, channels, items), Search Console's query and page rows mapped by gsc-sync.js, four weeks of snippet visits (a removed guide's 404s for Broken AI links) and journeys made by traffic-events.js's eventRow, a month of AI crawler counts with a Cloudflare Worker connection whose secret hash matches no secret, and the page opportunities detectPageOpportunities finds in them. The brand maps the sample GA4 and Search Console properties and has conversions on. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… own verdicts Brewline's pages are rendered as HTML round by round and scored by runSignals and scoreAudit: six key pages audited three times as fixes land, every page in the latest auto-audit. The model-judged signals, Wikidata's brand entity and the recommendations are written in the shapes those steps store. The page inventory goes through selectPages and parseHead, site trust through site-trust.js's checks (4/5: no editorial policy), and the brand facts through factText and keptFacts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A Google XML feed of 22 products read by the feed parser and kept as catalogRecords and hashOf keep them, with stable demo ids: a removed seasonal blend, an out-of-stock size, a sale, no images. The products the demo's AI answers show as cards are the same page, title and price. Two categories get their page by hand; the rest match their collection pages. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cache The demo writes the intent of each search its answers ran into fanout_query_intents, keyed as the route keys it (normalizeIntentQuery, moved to intent-extraction.js), adding only what the shared cache lacks, so Query Fan-out never needs a model for the demo. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s with the demo brand (version 3) The demo-site modules join the core in DEMO_MODULES, and DEMO_VERSION is 3, so every demo brand is rebuilt with them on its next visit. Their tables leave the coverage test's pending list; a CMS connection, sent drafts, product images and Merchant Center item issues are skipped, with why. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… rows stay the same One rebuild for another brand two days later checks both that only the ids and dates change, with room past the default 5 s on a busy machine. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # server/src/lib/demo/coverage.js # server/src/lib/demo/index.js
The first module lays down what the others point at; the rest write their own tables together, each after the module it names in `after`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # server/src/lib/demo/index.js
# Conflicts: # server/src/lib/demo/index.js
A first build no longer clears 70 empty tables, and the core writes each step's independent tables side by side through a shared queue of four statements (write.js: insertChunks, demoWriter). Its rollups move to a refresh step that runs alongside the other modules, Insights, Citations and Mentions together, the month's answer terms in one call (refreshMentionsDaily takes an optional termDays). The core alone went from about 17 s to 7 s on the dev database. A rebuild (new DEMO_VERSION, or data older than three days) no longer deletes the demo first: an `inPlace` module writes over its rows by key (ids are deterministic) and deletes only the rows it didn't write again, then rebuilds the rollups over the old and new days, each refresh call rewriting its days in one statement. Someone opening the demo meanwhile sees last week's data, not empty pages. Modules not marked `inPlace` still have their tables cleared, now just before they are built. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A brand just created isn't empty: its insert trigger starts Getting started, so skipping every clear on a first build made the Action Center's insert hit getting_started_pkey. An in-place module now always writes over by key (the first build only skips reading back and pruning); a module that isn't rebuilt in place clears its own tables just before it is built, on a first build too, alongside the other modules rather than all up front. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…irst build Nobody looks at a demo being built for the first time, so every module not rebuilt in place starts clearing what the new brand's triggers made at once, while the core writes, instead of each in turn later, when its deletes queue behind the rollups. A rebuild still clears each module just before it is built, so its old rows stay on show as long as they can. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…core # Conflicts: # server/src/lib/action-center/task-checks.js # server/src/lib/action-center/validate.js # server/src/routes/index.js # supabase/schema.sql
…ver main's new tables sweepPromptDemand chose brands by their organization's plan only, so an active workspace's demo brand would have had its sample prompts read and DataForSEO's paid tasks set for them. It now leaves demo brands out, as the other sweeps do. The demo coverage list names the two brand tables main added: prompt_table_views (skipped: the demo starts on the default columns) and prompt_demand (pending a demo follow-up). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lumn layouts open Main added write routes that name a brand: Action Center's audits and products, WordPress and Framer connections, and their publish-status checks. Each now answers 402 demo_brand on a demo brand, as the Webflow ones do. The Tracked Prompts column layouts (prompt_table_views, 00363) stay writable on a demo brand: they change no sample data and cost nothing, and the web keeps them open while read-only too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…core # Conflicts: # server/src/lib/action-center/execution/run.js # server/src/lib/action-center/execution/run.test.js # supabase/schema.sql
…n's new tables sweepCompetitorTimeline (learning C3, on main) chose brands by their organization's plan only, so a demo brand's sample answers would have had their cited pages read every night. It now leaves demo brands out, as the other sweeps do. The demo coverage list names the brand tables main added: cited_page_features, competitor_page_events and competitor_timeline_scans (pending a demo follow-up) and chat_conversations (with Chat). Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # supabase/schema.sql
Chat's precedence (ansvisor#1776) left readBrandIsDemo false until the demo chain added brands.is_demo, with a type check that stops compiling once the column exists. It now reads the column, as the server's demo guard does, so a tool that changes or spends on the demo brand is refused with demo_brand; a brand that isn't found isn't one, and a failed read throws. Co-Authored-By: Claude Opus 5.5 <[email protected]>
POST /brands/:id/detect-site-type (ansvisor#1761, on main) reads the brand's home page and may ask AI for its kind. The demo guard's coverage test fails on a write route in neither list, so it is now guarded by the brand in its path. Co-Authored-By: Claude Opus 5.5 <[email protected]>
chat_user_prefs (00400) and chat_auto_choices (00401) are a person's own rows, not a brand's: the write guard's coverage test fails on a writable table in no list, so both are named as no brand's rows. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged main forward through #1736's updated branch (conflict in Two follow-up commits for routes and tables main added:
Typecheck and the conflicted files' tests pass (plus the guard, demo and middleware tests); server lint clean. |
A SECURITY DEFINER function runs as its owner, so the guard now reads the role the request took as well: a person's call (authenticated or anon) is checked like their own write, and a write from inside another trigger, as a cascade, passes as before.
…nd bound a bulk request's ids The demo guard matched ids in the lowercase hyphenated form only; a route passes others (upper case, braces, no hyphens) to Postgres, which reads them as the same uuid. They are now put in that form before the check. A bulk request names at most 500 ids, all of them checked; more is refused with 400, where only the first 500 were read before.
The MCP's mark_content_draft_published reaches the API through /api/internal/content-drafts/:draftId/publish, which writes with the service role and never meets the demo guard. It now answers 402 demo_brand for a demo brand's draft before marking it published, as the other internal endpoints do.
gkhngyk
left a comment
There was a problem hiding this comment.
Looks good with 2872dc41: the database's guard now checks a person's write wherever it comes from, and the API's guard reads a brand or row id in every form the database takes. Branch take-1737: this head b466d9b plus two commits. The follow-ups below stay open, and the merge with main needs the three changes listed under "Merge".
What I changed:
- 00381's guard (cf122adc). The trigger now tells the server's own writes from a person's by the session's role as well as the current one, so writes that reach these tables through a database function are checked as the person's. The service role, migrations and cascades pass as before.
write-guard.test.jspins the condition.schema.sqlis rebuilt. - The API's id check (2872dc41,
middleware/demo-brand.js). The guard now reads each brand or row id in its usual form before checking it (guidOf), and the cache is keyed by that form. - Bulk ids. A guarded route with more than 500 ids in one request now gets a 400; the routes' own
.in('id', ids)couldn't serve that many in one URL anyway. Both changes have tests.
What I checked:
- 00381. No rows written, no rewrite. It creates one function and 37
before insert or update or deleterow triggers (create or replace trigger, PG 14+). The function issecurity invokerwithsearch_path = '', and every name is schema-qualified. Its brand and parent reads run as the person, under RLS, so another organization's row is refused by RLS before the trigger matters. An update is checked on old and new, so a row can't be moved into or out of the demo brand. A brand that can't be read leaves the decision to RLS. A trigger function can't be called directly, so the missingrevokedoesn't matter. The(column, table)paths match main's schema:prompts → prompt_sets,prompt_notes/prompt_target_urls → prompts → prompt_sets, theaction_*tables →actions, thecontent_draft_*tables →content_drafts,agent_messages → agent_conversations,audit_signal_results → site_audits. No clash: 00381 isn't on main or in any other open PR. - Cost of the trigger. A server write pays one
pg_roleslookup per row. A person's write pays abrandslookup, plus one per hop. Fine for the UI's writes, a 1,000-prompt import included. - The API guard. It runs after
decodeTokenand beforerequireActiveSubscription, so the demo brand answers 402demo_brandwith or without a plan. Reads pass without a query.demo-brand.test.jsfails on a write route that's in neither list. If the brand can't be read, the request gets a 500 and doesn't go through. The three MCP internal endpoints (brief,site-audits,improve/action) check the brand before any work starts.brand-factsGET reads only what's kept on a demo brand. - Jobs. Every claim and every recovery goes through
brandStopReasons, and a demo brand's job is cancelled asdemo_brandbefore anything is spent. A brand that's missing reads assubscription_inactive, so it's never run. - Idle sweep. It claims a brand with a compare-and-set on
(demo_version, demo_built_at), so a visit that started a build meanwhile keeps it. At most 200 brands a night. A cleared brand ends withdemo_built_atnull, so it isn't picked up again. A failed clear is held as a failed build and comes back 14 days later. - Embeds.
prompts → prompt_sets!inner(one FK,prompts_prompt_set_id_fkey),action_tasks → actions!inner(one FK),brands → organizations(one FK,brands_organization_id_fkey). - Tests. On
take-1737, the full server suite has 3,929 passing. The 8 failing files importframer-api, which my scratchnode_moduleslacks; they fail the same way on main. Prettier and eslint are clean on the changed files.
Merge (with main 3b7611c, through the earlier parts): run.js/run.test.js and schema.sql conflict from the earlier parts. On the merged tree three of this part's checks fail, as they should:
demo-brand.test.js: main'sPOST /brands/:id/detect-site-type(#1761) is in neither list. It reads the home page and may ask the AI, then writes the brand's type:guard('POST /brands/:id/detect-site-type', brandIn('path', 'id')).write-guard.test.js:chat_user_prefsandchat_auto_choices(00400/00401) are a person's and an organization's, with no brand. Add them toNOT_A_BRAND_ROW.coverage.test.js(part 1's test):cited_page_features,competitor_page_events,competitor_timeline_scansandchat_conversationsneed a module orSKIPPED.
Follow-ups:
- Lock wait. The 37
create triggerstatements each take a SHARE ROW EXCLUSIVE lock and hold it until the migration commits. Behind a long write onpromptsoractions, the migration waits, and everything queues behind it. Start it withset lock_timeout = '5s'and run it off-peak. - Self-hosted. The web's
assertWritable({ brandId })returns early when not on the cloud, so a demo brand there is guarded only by this API and the trigger. Docs say self-hosted never offers the demo, so this only matters if a row is made by hand. - The guard's 402 tells any signed-in caller whether some brand id is a demo brand. It runs before the access check. Ids are random, so nothing to do now.
Summary
Demo brand, part 4 of 7 (server + database). Nothing anyone asks of the demo brand may change its sample data or start a cost, whatever the plan. Reads and exports stay open.
demo_brandon every write route that names a demo brand (middleware/demo-brand.js). It applies on the cloud and self-hosted alike: the web opens the plan dialog with the demo's offer./apiis listed, route by route:DEMO_GUARDEDsays where it names its brand (path, body, query, or a row of the brand it acts on);DEMO_OPENsays why a route stays open (the organization's own, onboarding, stopping work,/api/demoitself).demo-brand.test.jsreads the route files and fails on a write route that is in neither list.auditsandproducts, WordPress and Framer connect/disconnect, and their publish-status checks (b466d9b).refuse_demo_brand_writes()is a BEFORE INSERT/UPDATE/DELETE trigger on every table members can write under RLS that belongs to a brand (37 tables).demo_brand; an update is checked on its old and new row.brand_idnames its way to the brand, e.g.prompt_notes:prompt_id → prompts → prompt_sets.write-guard.test.jsreads the migrations and fails on a writable brand table without the trigger.prompt_table_views(00363), a person's own column layout. It changes no sample data, costs nothing, and the web keeps it open while read-only too.demo_brand, not as an ended plan (brandStopReasons).CRON_SECRETand never meet the middleware. Each answers a demo brand with 402demo_brandbefore calling a model, starting an audit or writing an action.lib/demo/idle-sweep.js, daily): a demo brand nobody opened for 14 days loses its sample rows. The brand row stays, with no version or build time, and the next visit builds it again in place with the same ids, so links still work. A clear holds the brand as a build does, so a visit at that moment waits instead of reading half the data.Migration / deploy notes
demo_brand.Related issue
None (demo brand).
Stacked on #1736 (demo brand, part 3: site).
Type of change
feat— New featurefix— main's newer write routes refused on a demo brandHow to test
POST /api/prompts/suggestions/<demo brand id>/refresh(or any route inDEMO_GUARDED): 402 withcode: "demo_brand", and nothing runs. The same call for your own brand behaves as before.authenticateduser (or from the web app's client), update a demo brand's prompt: refused withdemo_brand. The server's own rebuild (POST /api/demoafter settingdemo_versionto 0) still writes.demo_built_atto 15 days ago and run the idle sweep: its rows are cleared and the brand row stays. The next visit rebuilds it.Checklist
eslint srcpasses. Tests:src/lib/demo,src/middleware,src/routes,active-subscriptions, Pulse andjob-runner(74 files, 762 tests) pass.yarn typecheckpasses; billing andsubscription-guardtests pass.bash supabase/build-schema.sh:schema.sqlis current🤖 Generated with Claude Code