Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(demo): give every organization a demo brand with sample data (demo brand, part 1) (#1734)

Cihan9036a6816041
diff --git a/server/src/lib/action-center/competitor-timeline.js b/server/src/lib/action-center/competitor-timeline.js
index f2f6dd31d..8ff5deaec 100644
--- a/server/src/lib/action-center/competitor-timeline.js
+++ b/server/src/lib/action-center/competitor-timeline.js
@@ -292,8 +292,10 @@ export async function sweepCompetitorTimeline({
const rows = await allRows(() =>
supabaseAdmin
.from('competitors')
- .select('id, brand_id, brands!inner(organization_id, is_active)')
+ .select('id, brand_id, brands!inner(organization_id, is_active, is_demo)')
.eq('brands.is_active', true)
+ // A demo brand's answers (00380) are sample data: none of its pages is read.
+ .eq('brands.is_demo', false)
.neq('domain', '')
.order('id'),
);
diff --git a/server/src/lib/action-center/competitor-timeline.test.js b/server/src/lib/action-center/competitor-timeline.test.js
index 495c2ac2d..40dc74b38 100644
--- a/server/src/lib/action-center/competitor-timeline.test.js
+++ b/server/src/lib/action-center/competitor-timeline.test.js
@@ -323,19 +323,19 @@ describe('sweepCompetitorTimeline', () => {
id: 'c1',
brand_id: BRAND,
domain: 'rival.com',
- brands: { organization_id: 'o1', is_active: true },
+ brands: { organization_id: 'o1', is_active: true, is_demo: false },
},
{
id: 'c2',
brand_id: 'brand-2',
domain: 'other.com',
- brands: { organization_id: 'o2', is_active: true },
+ brands: { organization_id: 'o2', is_active: true, is_demo: false },
},
{
id: 'c3',
brand_id: 'brand-3',
domain: '',
- brands: { organization_id: 'o1', is_active: true },
+ brands: { organization_id: 'o1', is_active: true, is_demo: false },
},
];
tables.organizations = [
@@ -353,7 +353,7 @@ describe('sweepCompetitorTimeline', () => {
id: `c${String(i).padStart(4, '0')}`,
brand_id: i < 1_100 ? 'brand-busy' : BRAND,
domain: 'rival.com',
- brands: { organization_id: 'o1', is_active: true },
+ brands: { organization_id: 'o1', is_active: true, is_demo: false },
}));
// The busy brand was read last night; the other never was, so it goes first.
tables.competitor_timeline_scans = Array.from({ length: 1_100 }, (_, i) => ({
@@ -364,4 +364,20 @@ describe('sweepCompetitorTimeline', () => {
await sweepCompetitorTimeline({ now: NOW, read: reader({}), limit: 1 });
expect(rpcCalls[0][1].p_brand_id).toBe(BRAND);
});
+
+ it("never reads a demo brand's competitor pages (00380)", async () => {
+ tables.competitors = [
+ {
+ id: 'c1',
+ brand_id: BRAND,
+ domain: 'rival.com',
+ brands: { organization_id: 'o1', is_active: true, is_demo: true },
+ },
+ ];
+ const read = reader({});
+ const outcome = await sweepCompetitorTimeline({ now: NOW, read });
+ expect(outcome).toMatchObject({ brands: 0, firstCited: 0, changed: 0 });
+ expect(rpcCalls).toEqual([]);
+ expect(read).not.toHaveBeenCalled();
+ });
});
diff --git a/server/src/lib/action-center/execution/run.js b/server/src/lib/action-center/execution/run.js
index 8e512a76f..3c1128191 100644
--- a/server/src/lib/action-center/execution/run.js
+++ b/server/src/lib/action-center/execution/run.js
@@ -307,19 +307,21 @@ export async function sweepTaskExecution({ now = new Date() } = {}) {
// On the cloud, only for organizations still on a plan: a tool reads
// outside services on the organization's behalf. Filtered in the query, so
// the old tasks of an organization whose plan ended can't fill the read.
+ // Never a demo brand's (00380): its tasks are sample data.
// `retry_after`: a tool that found nothing to work on asked to be passed
// over until then (runTask).
let query = supabaseAdmin.from('action_tasks');
query = isCloud()
? query
.select(
- 'id, task_key, action_id, retry_after:output->>retryAfter, actions!inner(status, brands!inner(organizations!inner(subscription_status)))',
+ 'id, task_key, action_id, retry_after:output->>retryAfter, actions!inner(status, brands!inner(is_demo, organizations!inner(subscription_status)))',
)
.in('actions.brands.organizations.subscription_status', ACTIVE_SUBSCRIPTION_STATUSES)
: query.select(
- 'id, task_key, action_id, retry_after:output->>retryAfter, actions!inner(status)',
+ 'id, task_key, action_id, retry_after:output->>retryAfter, actions!inner(status, brands!inner(is_demo))',
);
const { data: rows, error } = await query
+ .eq('actions.brands.is_demo', false)
.in('status', RUNNABLE_STATUSES)
.not('actions.status', 'in', '("completed","dismissed")')
.order('created_at', { ascending: true })
diff --git a/server/src/lib/action-center/execution/run.test.js b/server/src/lib/action-center/execution/run.test.js
index ba50f05c7..00619db89 100644
--- a/server/src/lib/action-center/execution/run.test.js
+++ b/server/src/lib/action-center/execution/run.test.js
@@ -505,7 +505,10 @@ describe('sweepTaskExecution', () => {
if (sweep) asked.select = columns;
return builder;
},
- eq: () => builder,
+ eq: (column, value) => {
+ if (sweep) asked.filters.push([column, value]);
+ return builder;
+ },
in: (column, values) => {
if (sweep) asked.filters.push([column, values]);
return builder;
@@ -569,7 +572,7 @@ describe('sweepTaskExecution', () => {
const summary = await sweepTaskExecution({ now: NOW });
expect(asked.select).toContain(
- 'actions!inner(status, brands!inner(organizations!inner(subscription_status)))',
+ 'actions!inner(status, brands!inner(is_demo, organizations!inner(subscription_status)))',
);
expect(asked.filters).toContainEqual([
'actions.brands.organizations.subscription_status',
@@ -589,7 +592,7 @@ describe('sweepTaskExecution', () => {
const asked = mockPlanSweep(lapsedThenPaying());
await sweepTaskExecution({ now: NOW });
expect(asked.select).toBe(
- 'id, task_key, action_id, retry_after:output->>retryAfter, actions!inner(status)',
+ 'id, task_key, action_id, retry_after:output->>retryAfter, actions!inner(status, brands!inner(is_demo))',
);
expect(asked.filters.map(([column]) => column)).not.toContain(
'actions.brands.organizations.subscription_status',
@@ -598,4 +601,18 @@ describe('sweepTaskExecution', () => {
vi.unstubAllEnvs();
}
});
+
+ it("never reads a demo brand's tasks (00380), on the cloud or self-hosted", async () => {
+ for (const cloud of ['true', 'false']) {
+ vi.stubEnv('IS_CLOUD', cloud);
+ try {
+ const asked = mockPlanSweep([]);
+ await sweepTaskExecution({ now: NOW });
+ expect(asked.select).toContain('brands!inner(is_demo');
+ expect(asked.filters).toContainEqual(['actions.brands.is_demo', false]);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ }
+ });
});
diff --git a/server/src/lib/action-center/improve-outcome.js b/server/src/lib/action-center/improve-outcome.js
index 4d379a894..1334955de 100644
--- a/server/src/lib/action-center/improve-outcome.js
+++ b/server/src/lib/action-center/improve-outcome.js
@@ -209,7 +209,11 @@ export async function refreshImproveOutcome(action, { now = new Date() } = {}) {
export async function sweepImproveOutcomes({ now = new Date() } = {}) {
const { data: actions, error } = await supabaseAdmin
.from('actions')
- .select('id, brand_id, status, payload, baseline, completed_at, position_outcome')
+ .select(
+ 'id, brand_id, status, payload, baseline, completed_at, position_outcome, brands!inner(is_demo)',
+ )
+ // A demo brand's actions (00380) are sample data, measured as written.
+ .eq('brands.is_demo', false)
.eq('kind', 'prompt_improve')
.in('status', [...OPEN, 'completed'])
.or('position_outcome.is.null,position_outcome->>final.neq.true')
diff --git a/server/src/lib/action-center/improve-outcome.test.js b/server/src/lib/action-center/improve-outcome.test.js
index dff867d5b..dfdefb1a7 100644
--- a/server/src/lib/action-center/improve-outcome.test.js
+++ b/server/src/lib/action-center/improve-outcome.test.js
@@ -143,7 +143,10 @@ function mockDb(results, { actions = [] } = {}) {
from.mockImplementation((table) => {
const b = {
select: () => b,
- eq: () => b,
+ eq: (column, value) => {
+ writes.filters.push({ table, eq: [column, value] });
+ return b;
+ },
in: (column, values) => {
writes.filters.push({ table, in: [column, values] });
return b;
@@ -275,4 +278,10 @@ describe('sweepImproveOutcomes', () => {
expect(result).toEqual({ refreshed: 2 });
expect(writes.updated).toHaveLength(2);
});
+
+ it("never reads a demo brand's actions (00380)", async () => {
+ const writes = mockDb([], { actions: [] });
+ await sweepImproveOutcomes({ now: new Date('2026-10-20T06:00:00.000Z') });
+ expect(writes.filters).toContainEqual({ table: 'actions', eq: ['brands.is_demo', false] });
+ });
});
diff --git a/server/src/lib/action-center/task-checks.js b/server/src/lib/action-center/task-checks.js
index 387020baf..11b643216 100644
--- a/server/src/lib/action-center/task-checks.js
+++ b/server/src/lib/action-center/task-checks.js
@@ -737,8 +737,10 @@ export async function sweepTaskChecks({
const { data: rows, error } = await supabaseAdmin
.from('action_tasks')
.select(
- 'id, action_id, task_key, title, status, details, updated_at, actions!inner(brand_id, status, deleted_at)',
+ 'id, action_id, task_key, title, status, details, updated_at, actions!inner(brand_id, status, deleted_at, brands!inner(is_demo))',
)
+ // A demo brand's tasks (00380) are sample data: their pages aren't read.
+ .eq('actions.brands.is_demo', false)
.in('status', OPEN)
.eq('details->>check', 'auto')
.not('details->>url', 'is', null)
diff --git a/server/src/lib/action-center/task-checks.test.js b/server/src/lib/action-center/task-checks.test.js
index 7f40b2b22..efd74fabf 100644
--- a/server/src/lib/action-center/task-checks.test.js
+++ b/server/src/lib/action-center/task-checks.test.js
@@ -987,6 +987,8 @@ describe('sweepTaskChecks', () => {
]);
// A held task (reopened after it passed) is left to the person.
expect(filters).toContainEqual(['is', 'details->autoCheck->>held', null]);
+ // Never a demo brand's (00380): its tasks are sample data.
+ expect(filters).toContainEqual(['actions.brands.is_demo', false]);
});
it('checks at most SWEEP_PER_BRAND of one brand’s tasks a night, the others’ too', async () => {
diff --git a/server/src/lib/action-center/task-writer/index.js b/server/src/lib/action-center/task-writer/index.js
index ff1d8c8d4..b03762e2c 100644
--- a/server/src/lib/action-center/task-writer/index.js
+++ b/server/src/lib/action-center/task-writer/index.js
@@ -512,15 +512,17 @@ const SWEEP_LIMIT = 20;
*/
export async function sweepActionTasks({ brandId, now = new Date(), limit = SWEEP_LIMIT } = {}) {
if (!isTaskWriterEnabled()) return { skipped: 'disabled' };
+ // Never a demo brand's actions (00380): they are sample data.
let query = supabaseAdmin.from('actions');
query = isCloud()
? query
.select(
- 'id, brand_id, kind, status, brands!inner(organizations!inner(subscription_status))',
+ 'id, brand_id, kind, status, brands!inner(is_demo, organizations!inner(subscription_status))',
)
.in('brands.organizations.subscription_status', ACTIVE_SUBSCRIPTION_STATUSES)
- : query.select('id, brand_id, kind, status');
+ : query.select('id, brand_id, kind, status, brands!inner(is_demo)');
query = query
+ .eq('brands.is_demo', false)
.is('tasks_generated_at', null)
.gte('created_at', new Date(now.getTime() - SWEEP_WINDOW_MS).toISOString())
.not('status', 'in', '("completed","dismissed")')
diff --git a/server/src/lib/action-center/task-writer/index.test.js b/server/src/lib/action-center/task-writer/index.test.js
index 893a56f07..ec64edd57 100644
--- a/server/src/lib/action-center/task-writer/index.test.js
+++ b/server/src/lib/action-center/task-writer/index.test.js
@@ -148,6 +148,7 @@ beforeEach(() => {
category: 'recover',
status: 'new',
payload: {},
+ brands: { is_demo: false },
},
],
brands: [{ id: 'b1', name: 'Acme Coffee', description: null, organization_id: 'o1' }],
@@ -544,7 +545,7 @@ describe('sweepActionTasks', () => {
beforeEach(() => vi.stubEnv('IS_CLOUD', 'true'));
afterEach(() => vi.unstubAllEnvs());
- const onPlan = (status) => ({ organizations: { subscription_status: status } });
+ const onPlan = (status) => ({ is_demo: false, organizations: { subscription_status: status } });
it("writes no task for an organization whose plan has ended, and the paying one's still", async () => {
db.actions = [
@@ -560,7 +561,7 @@ describe('sweepActionTasks', () => {
expect(selects).toContainEqual({
table: 'actions',
columns:
- 'id, brand_id, kind, status, brands!inner(organizations!inner(subscription_status))',
+ 'id, brand_id, kind, status, brands!inner(is_demo, organizations!inner(subscription_status))',
});
expect(reserveAiBudget).toHaveBeenCalledTimes(1);
expect(ops.filter((op) => op.table === 'actions' && op.op === 'update')).not.toContainEqual(
@@ -573,12 +574,24 @@ describe('sweepActionTasks', () => {
beforeEach(() => vi.stubEnv('IS_CLOUD', 'false'));
afterEach(() => vi.unstubAllEnvs());
- it('reads every action, unfiltered', async () => {
+ it('reads every action, unfiltered by plan', async () => {
db.action_tasks = [];
generateObject.mockResolvedValue(answer([task()]));
expect(await sweepActionTasks()).toEqual({ written: 1, skipped: 0, failed: 0 });
- expect(selects).toContainEqual({ table: 'actions', columns: 'id, brand_id, kind, status' });
+ expect(selects).toContainEqual({
+ table: 'actions',
+ columns: 'id, brand_id, kind, status, brands!inner(is_demo)',
+ });
+ });
+
+ it("never writes a demo brand's tasks (00380)", async () => {
+ db.actions = [{ ...db.actions[0], id: 'demo', brands: { is_demo: true } }];
+ db.action_tasks = [];
+ generateObject.mockResolvedValue(answer([task()]));
+
+ expect(await sweepActionTasks()).toEqual({ written: 0, skipped: 0, failed: 0 });
+ expect(reserveAiBudget).not.toHaveBeenCalled();
});
});
});
diff --git a/server/src/lib/action-center/validate.js b/server/src/lib/action-center/validate.js
index 1d9ee688e..bac25f32a 100644
--- a/server/src/lib/action-center/validate.js
+++ b/server/src/lib/action-center/validate.js
@@ -762,7 +762,11 @@ export async function sweepActionValidation({ now = new Date() } = {}) {
for (;;) {
let query = supabaseAdmin
.from('actions')
- .select('id, brand_id, kind, payload, kpi_keys, created_at, completed_at, validation')
+ .select(
+ 'id, brand_id, kind, payload, kpi_keys, created_at, completed_at, validation, brands!inner(is_demo)',
+ )
+ // A demo brand's actions (00380) are sample data: their outcomes are written with them.
+ .eq('brands.is_demo', false)
.eq('status', 'completed')
// Never measured, or read but not for the last time yet (learning B1).
// One measured once before the later readings came keeps its result.
diff --git a/server/src/lib/action-center/validate.test.js b/server/src/lib/action-center/validate.test.js
index ddf19ec7a..32317bca4 100644
--- a/server/src/lib/action-center/validate.test.js
+++ b/server/src/lib/action-center/validate.test.js
@@ -1168,3 +1168,26 @@ describe('validateAction', () => {
expect(writes.updated).toHaveLength(0);
});
});
+
+describe('sweepActionValidation', () => {
+ it("never reads a demo brand's actions (00380): their outcomes are written with them", async () => {
+ const asked = [];
+ from.mockImplementation((table) => {
+ const builder = {
+ select: (columns) => (asked.push(['select', table, columns]), builder),
+ eq: (column, value) => (asked.push(['eq', column, value]), builder),
+ or: () => builder,
+ not: () => builder,
+ lte: () => builder,
+ order: () => builder,
+ limit: () => builder,
+ then: (resolve, reject) => Promise.resolve({ data: [], error: null }).then(resolve, reject),
+ };
+ return builder;
+ });
+
+ expect(await sweepActionValidation({ now: NOW })).toEqual({ measured: 0, failed: 0 });
+ expect(asked[0][2]).toContain('brands!inner(is_demo)');
+ expect(asked).toContainEqual(['eq', 'brands.is_demo', false]);
+ });
+});
diff --git a/server/src/lib/active-subscriptions.js b/server/src/lib/active-subscriptions.js
index 813b376b2..6eda2bc54 100644
--- a/server/src/lib/active-subscriptions.js
+++ b/server/src/lib/active-subscriptions.js
@@ -11,8 +11,12 @@
* sites and services send for it (AI-bot logs, traffic beacons, Cloro's
* answers, workflow callbacks) is answered as usual and not stored.
*
- * Self-hosted, everything is let through (billing doesn't apply), and
- * nothing is read.
+ * Self-hosted, every organization is let through (billing doesn't apply),
+ * and nothing is read for them.
+ *
+ * A demo brand (00380) is never let through, on the cloud or self-hosted:
+ * its data is the sample the demo generator writes (lib/demo), and nothing
+ * may track, write or spend for it. So a brand is read even self-hosted.
*/
import supabaseAdmin from '../config/supabase.js';
@@ -58,23 +62,31 @@ export async function activeOrgFilter(orgIds) {
}
/**
- * A test for the ids among `brandIds`: whether the brand's organization has
- * an active or trialing subscription. Throws when the brands can't be read.
+ * A test for the ids among `brandIds`: whether the brand is a real one (not
+ * a demo brand) whose organization has an active or trialing subscription
+ * (any, self-hosted). Throws when the brands can't be read.
*
* @param {string[]} brandIds
* @returns {Promise<(brandId: string) => boolean>}
*/
export async function activeBrandFilter(brandIds) {
- if (!isCloud()) return everyone;
const ids = uniqueIds(brandIds);
if (ids.length === 0) return () => false;
+ const cloud = isCloud();
const { data, error } = await selectInChunks(ids, (chunk) =>
- supabaseAdmin.from('brands').select('id, organizations(subscription_status)').in('id', chunk),
+ supabaseAdmin
+ .from('brands')
+ .select(cloud ? 'id, is_demo, organizations(subscription_status)' : 'id, is_demo')
+ .in('id', chunk),
);
if (error) throw new Error(`brands read: ${error.message}`);
const active = new Set(
(data ?? [])
- .filter((brand) => isSubscriptionActive(brand.organizations?.subscription_status))
+ .filter(
+ (brand) =>
+ !brand.is_demo &&
+ (!cloud || isSubscriptionActive(brand.organizations?.subscription_status)),
+ )
.map((brand) => brand.id),
);
return (brandId) => active.has(brandId);
@@ -94,8 +106,8 @@ export async function isOrgActive(orgId) {
/**
* Whether one brand's organization has an active or trialing subscription
- * (always, self-hosted): for a job, a pass or a callback that starts work
- * for one brand.
+ * (always, self-hosted), and the brand isn't a demo brand: for a job, a pass
+ * or a callback that starts work for one brand.
*
* @param {string} brandId
* @returns {Promise<boolean>}
diff --git a/server/src/lib/active-subscriptions.test.js b/server/src/lib/active-subscriptions.test.js
index c6e5b3af0..230ed58c4 100644
--- a/server/src/lib/active-subscriptions.test.js
+++ b/server/src/lib/active-subscriptions.test.js
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* Which organizations the nightly work may still run for (2026-10-27): on
* the cloud, those with an active or trialing subscription; self-hosted,
- * every one, without a read.
+ * every one, without a read. Never a demo brand (00380), on either.
*/
const reads = [];
@@ -72,6 +72,7 @@ beforeEach(() => {
{ id: 'b-trialing', organizations: { subscription_status: 'trialing' } },
{ id: 'b-canceled', organizations: { subscription_status: 'canceled' } },
{ id: 'b-orphan', organizations: null },
+ { id: 'b-demo', is_demo: true, organizations: { subscription_status: 'active' } },
],
};
});
@@ -83,15 +84,25 @@ afterEach(() => {
describe('self-hosted', () => {
beforeEach(() => vi.stubEnv('IS_CLOUD', 'false'));
- it('lets every organization and brand through without reading anything', async () => {
+ it('lets every organization through without reading anything', async () => {
const isOrgActive = await activeOrgFilter(['canceled', 'anything']);
- const isBrandActive = await activeBrandFilter(['b-canceled']);
expect(isOrgActive('canceled')).toBe(true);
expect(isOrgActive(undefined)).toBe(true);
- expect(isBrandActive('b-canceled')).toBe(true);
expect(reads).toHaveLength(0);
});
+
+ it('lets every brand through but a demo one, reading only which is which', async () => {
+ const isBrandActive = await activeBrandFilter(['b-canceled', 'b-orphan', 'b-demo']);
+
+ expect(['b-canceled', 'b-orphan', 'b-demo'].filter(isBrandActive)).toEqual([
+ 'b-canceled',
+ 'b-orphan',
+ ]);
+ expect(reads).toEqual([
+ { table: 'brands', columns: 'id, is_demo', in: ['id', ['b-canceled', 'b-orphan', 'b-demo']] },
+ ]);
+ });
});
describe('cloud', () => {
@@ -122,16 +133,14 @@ describe('cloud', () => {
]);
});
- it('lets through only the brands whose organization has one', async () => {
- const isActive = await activeBrandFilter(['b-active', 'b-trialing', 'b-canceled', 'b-orphan']);
+ it('lets through only the brands whose organization has one, never a demo brand', async () => {
+ const all = ['b-active', 'b-trialing', 'b-canceled', 'b-orphan', 'b-demo'];
+ const isActive = await activeBrandFilter(all);
- expect(['b-active', 'b-trialing', 'b-canceled', 'b-orphan'].filter(isActive)).toEqual([
- 'b-active',
- 'b-trialing',
- ]);
+ expect(all.filter(isActive)).toEqual(['b-active', 'b-trialing']);
expect(reads[0]).toMatchObject({
table: 'brands',
- columns: 'id, organizations(subscription_status)',
+ columns: 'id, is_demo, organizations(subscription_status)',
});
});
@@ -169,9 +178,14 @@ describe('isBrandActive', () => {
expect(await isBrandActive('b-canceled')).toBe(false);
expect(await isBrandActive('b-orphan')).toBe(false);
vi.stubEnv('IS_CLOUD', 'false');
- reads.length = 0;
expect(await isBrandActive('b-canceled')).toBe(true);
- expect(reads).toHaveLength(0);
+ });
+
+ it('never tells a demo brand active, on the cloud or self-hosted', async () => {
+ vi.stubEnv('IS_CLOUD', 'true');
+ expect(await isBrandActive('b-demo')).toBe(false);
+ vi.stubEnv('IS_CLOUD', 'false');
+ expect(await isBrandActive('b-demo')).toBe(false);
});
});
diff --git a/server/src/lib/audit/auto-audit-sweep.js b/server/src/lib/audit/auto-audit-sweep.js
index be9b84c0a..555cc1037 100644
--- a/server/src/lib/audit/auto-audit-sweep.js
+++ b/server/src/lib/audit/auto-audit-sweep.js
@@ -40,7 +40,9 @@ export async function sweepAutoAudits({ readInbox, startAudits, now = new Date()
let query = supabaseAdmin
.from('brands')
.select('id, name, organization_id')
- .eq('is_active', true);
+ .eq('is_active', true)
+ // A demo brand's site (00380) is a `.example` domain: never audited.
+ .eq('is_demo', false);
if (orgIds) query = query.in('organization_id', orgIds);
return query.order('id', { ascending: true }).range(from, to);
});
diff --git a/server/src/lib/audit/auto-audit-sweep.test.js b/server/src/lib/audit/auto-audit-sweep.test.js
index 4c7f9c9f6..f82b0b1bf 100644
--- a/server/src/lib/audit/auto-audit-sweep.test.js
+++ b/server/src/lib/audit/auto-audit-sweep.test.js
@@ -168,8 +168,12 @@ beforeEach(async () => {
const actual = await importOriginal();
return {
...actual,
- readAllRpcRows: async (name, page) =>
- name === 'brands' ? { data: brandRows, error: null } : actual.readAllRpcRows(name, page),
+ readAllRpcRows: async (name, page) => {
+ if (name !== 'brands') return actual.readAllRpcRows(name, page);
+ // The brands' query is built (and recorded) but answered here.
+ await page(0, 999);
+ return { data: brandRows, error: null };
+ },
};
});
vi.doMock('../plan-guard.js', () => ({
@@ -226,6 +230,12 @@ describe('sweepAutoAudits', () => {
});
expect(claim.opts).toMatchObject({ ignoreDuplicates: true });
expect(ids.update.audit_ids).toHaveLength(5);
+ // Never a demo brand (00380).
+ expect(ops.find((op) => op.table === 'brands').filters).toContainEqual([
+ 'eq',
+ 'is_demo',
+ false,
+ ]);
expect(done.update).toMatchObject({ status: 'completed', finished_at: expect.any(String) });
expect(sendAutoAuditEmail).toHaveBeenCalledWith('org-1', {
diff --git a/server/src/lib/brand-facts-sweep.js b/server/src/lib/brand-facts-sweep.js
index e5bda702f..989847e78 100644
--- a/server/src/lib/brand-facts-sweep.js
+++ b/server/src/lib/brand-facts-sweep.js
@@ -46,9 +46,11 @@ export async function sweepBrandFacts({
const nowIso = new Date(now).toISOString();
const { data: rows, error } = await db
.from('brand_fact_pages')
- .select('brand_id, checked_at, brands!inner(organization_id, is_active)')
+ .select('brand_id, checked_at, brands!inner(organization_id, is_active, is_demo)')
.lt('checked_at', new Date(now - REFRESH_DAYS * DAY_MS).toISOString())
.eq('brands.is_active', true)
+ // A demo brand's site (00380) is a `.example` domain nobody serves.
+ .eq('brands.is_demo', false)
.order('checked_at', { ascending: true })
.limit(limit * 6);
if (error) throw new Error(error.message);
diff --git a/server/src/lib/brand-facts-sweep.test.js b/server/src/lib/brand-facts-sweep.test.js
index b109ff734..bd3a2dddc 100644
--- a/server/src/lib/brand-facts-sweep.test.js
+++ b/server/src/lib/brand-facts-sweep.test.js
@@ -92,6 +92,8 @@ describe('sweepBrandFacts', () => {
expect.arrayContaining([
['lt', 'checked_at', new Date(NOW - REFRESH_DAYS * DAY).toISOString()],
['eq', 'brands.is_active', true],
+ // Never a demo brand (00380).
+ ['eq', 'brands.is_demo', false],
['limit', 12],
]),
);
diff --git a/server/src/lib/catalog/__fixtures__/fake-db.js b/server/src/lib/catalog/__fixtures__/fake-db.js
index d78de08b6..8a218c778 100644
--- a/server/src/lib/catalog/__fixtures__/fake-db.js
+++ b/server/src/lib/catalog/__fixtures__/fake-db.js
@@ -1,9 +1,15 @@
import { randomUUID } from 'node:crypto';
-/** A row's value at a column, or at a JSON path in it as PostgREST reads one (`shopping_path->>builtAt`). */
+/**
+ * A row's value at a column, at a JSON path in it as PostgREST reads one
+ * (`shopping_path->>builtAt`), or at an embedded table's column (`brands.is_demo`).
+ */
function valueAt(row, column) {
const at = column.indexOf('->>');
- if (at < 0) return row[column];
+ if (at < 0) {
+ if (column in row || !column.includes('.')) return row[column];
+ return column.split('.').reduce((value, key) => value?.[key], row);
+ }
const value = row[column.slice(0, at)]?.[column.slice(at + 3)];
if (value == null) return null;
return typeof value === 'string' ? value : JSON.stringify(value);
diff --git a/server/src/lib/catalog/sources.js b/server/src/lib/catalog/sources.js
index 61a6db3f1..984da740a 100644
--- a/server/src/lib/catalog/sources.js
+++ b/server/src/lib/catalog/sources.js
@@ -434,8 +434,10 @@ export async function sweepCatalogSources({
const { data, error } = await db
.from('catalog_sources')
.select(
- 'id, brand_id, kind, format, url, account, last_synced_at, brands!inner(organizations!inner(subscription_status))',
+ 'id, brand_id, kind, format, url, account, last_synced_at, brands!inner(is_demo, organizations!inner(subscription_status))',
)
+ // A demo brand's catalog (00380) is sample data: its sources are never read.
+ .eq('brands.is_demo', false)
.neq('kind', 'upload')
.or(`last_synced_at.is.null,last_synced_at.lt.${due}`)
.order('last_synced_at', { ascending: true, nullsFirst: true })
diff --git a/server/src/lib/catalog/sources.test.js b/server/src/lib/catalog/sources.test.js
index 29e86cb04..e4144e50b 100644
--- a/server/src/lib/catalog/sources.test.js
+++ b/server/src/lib/catalog/sources.test.js
@@ -47,7 +47,9 @@ beforeEach(() => {
format: 'auto',
url: 'https://shop.example/feed.xml',
};
- fake.rows('catalog_sources').push({ ...source, last_synced_at: null });
+ fake
+ .rows('catalog_sources')
+ .push({ ...source, last_synced_at: null, brands: { is_demo: false } });
});
afterEach(() => {
delete process.env.IS_CLOUD;
@@ -472,7 +474,7 @@ describe('sweepCatalogSources', () => {
it("syncs the due feeds, and records that an inactive workspace's were not read", async () => {
process.env.IS_CLOUD = 'true';
const [first] = fake.rows('catalog_sources');
- first.brands = { organizations: { subscription_status: 'active' } };
+ first.brands = { is_demo: false, organizations: { subscription_status: 'active' } };
fake.rows('catalog_sources').push({
id: '1b8d6a1e-2a3c-4d5e-8f90-123456789abc',
brand_id: 'brand-2',
@@ -480,7 +482,7 @@ describe('sweepCatalogSources', () => {
format: 'auto',
url: 'https://other.example/feed.xml',
last_synced_at: null,
- brands: { organizations: { subscription_status: 'canceled' } },
+ brands: { is_demo: false, organizations: { subscription_status: 'canceled' } },
});
const fetch = vi.fn().mockResolvedValue({ html: fixture('google-feed.xml') });
const result = await sweepCatalogSources({ db: fake.db, now: NOW, fetch });
@@ -510,7 +512,7 @@ describe('sweepCatalogSources', () => {
process.env.IS_CLOUD = 'true';
const [first] = fake.rows('catalog_sources');
- first.brands = { organizations: { subscription_status: 'past_due' } };
+ first.brands = { is_demo: false, organizations: { subscription_status: 'past_due' } };
first.last_synced_at = null;
fake.writes.length = 0;
const fetch = vi.fn();
@@ -531,6 +533,7 @@ describe('sweepCatalogSources', () => {
format: 'auto',
url: null,
last_synced_at: null,
+ brands: { is_demo: false },
},
{
id: '4b8d6a1e-2a3c-4d5e-8f90-123456789abc',
@@ -539,6 +542,7 @@ describe('sweepCatalogSources', () => {
format: 'auto',
url: null,
last_synced_at: null,
+ brands: { is_demo: false },
},
);
const fetch = vi.fn().mockResolvedValue({ html: fixture('google-feed.xml') });
@@ -556,6 +560,18 @@ describe('sweepCatalogSources', () => {
['feed_url', 'ok'],
]);
});
+
+ it("never reads a demo brand's sources (00380), nor lets them hold the line", async () => {
+ fake.rows('catalog_sources')[0].brands = { is_demo: true };
+ const fetch = vi.fn();
+ expect(await sweepCatalogSources({ db: fake.db, now: NOW, fetch })).toEqual({
+ due: 0,
+ synced: 0,
+ inactive: 0,
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ expect(kept().last_synced_at).toBeNull();
+ });
});
describe("the plan's product cap (ECOM-019)", () => {
diff --git a/server/src/lib/cloro-result-handler.js b/server/src/lib/cloro-result-handler.js
index 7749ceaa1..200b5ae4e 100644
--- a/server/src/lib/cloro-result-handler.js
+++ b/server/src/lib/cloro-result-handler.js
@@ -59,25 +59,7 @@ export async function handleScraperResult({
const { data: inserted, error } = await supabaseAdmin
.from('prompt_results')
- .insert({
- prompt_id: promptId,
- brand_id: brandId,
- platform: scraperId,
- response: aiResponse.text,
- citations: aiResponse.citations,
- mention_count: metrics.mentionCount,
- citation_count: metrics.citationCount,
- sentiment: sentimentResult.sentiment,
- visibility_score: metrics.visibilityScore,
- model_used: aiResponse.model,
- region: region ?? null,
- competitor_mentions: metrics.competitorMentions,
- mention_position: metrics.mentionPosition,
- mentioned_entity_count: metrics.mentionedEntityCount,
- shopping_cards: aiResponse.shopping_cards ?? [],
- inline_products: aiResponse.inline_products ?? [],
- search_queries: Array.isArray(aiResponse.search_queries) ? aiResponse.search_queries : [],
- })
+ .insert(resultRow({ aiResponse, scraperId, promptId, brandId, region, metrics }))
.select('id, created_at')
.single();
@@ -119,11 +101,45 @@ export async function handleScraperResult({
}
/**
- * Normalize and insert shopping cards into the analytical table.
+ * The prompt_results row for one answer, from the parsed answer and its
+ * metrics (parseResponse). Pure, so the demo brand's sample answers
+ * (lib/demo) are stored in exactly the shape tracking stores.
*
- * Exported so the backfill script can reuse the exact same code path
- * against historical prompt_results rows without duplicating the parse +
- * brand-match logic.
+ * @param {object} args
+ * @param {{ text: string, citations: Array, model: string, shopping_cards?: Array, inline_products?: Array, search_queries?: Array }} args.aiResponse
+ * @param {string} args.scraperId
+ * @param {string} args.promptId
+ * @param {string} args.brandId
+ * @param {string|null} args.region
+ * @param {ReturnType<typeof parseResponse>} args.metrics
+ */
+export function resultRow({ aiResponse, scraperId, promptId, brandId, region, metrics }) {
+ return {
+ prompt_id: promptId,
+ brand_id: brandId,
+ platform: scraperId,
+ response: aiResponse.text,
+ citations: aiResponse.citations,
+ mention_count: metrics.mentionCount,
+ citation_count: metrics.citationCount,
+ sentiment: metrics.sentiment,
+ visibility_score: metrics.visibilityScore,
+ model_used: aiResponse.model,
+ region: region ?? null,
+ competitor_mentions: metrics.competitorMentions,
+ mention_position: metrics.mentionPosition,
+ mentioned_entity_count: metrics.mentionedEntityCount,
+ shopping_cards: aiResponse.shopping_cards ?? [],
+ inline_products: aiResponse.inline_products ?? [],
+ search_queries: Array.isArray(aiResponse.search_queries) ? aiResponse.search_queries : [],
+ };
+}
+
+/**
+ * The prompt_result_shopping_cards rows for one answer's cards, then
+ * ChatGPT's inline products: normalized, matched to the brand or a
+ * competitor, their merchant classified. Pure, for the same reason as
+ * resultRow.
*
* @param {object} args
* @param {string} args.promptResultId
@@ -131,12 +147,12 @@ export async function handleScraperResult({
* @param {string} args.platform
* @param {string|null} args.region
* @param {unknown[]} args.rawCards
- * @param {unknown[]} [args.rawInlineProducts] ChatGPT's in-answer products, stored after the cards
+ * @param {unknown[]} [args.rawInlineProducts]
* @param {{ brandId: string, brandName: string, domains: string[] }} args.brandInfo
* @param {Array<{ id: string, name: string, domain: string|null }>} args.competitors
- * @returns {Promise<number>} number of rows inserted (0 if none / on failure)
+ * @returns {object[]}
*/
-export async function persistShoppingCards({
+export function shoppingCardRows({
promptResultId,
brandId,
platform,
@@ -152,9 +168,8 @@ export async function persistShoppingCards({
...cards,
...normalizeInlineProducts(platform, rawInlineProducts, lastPosition),
];
- if (normalized.length === 0) return 0;
- const rows = normalized.map((card) => {
+ return normalized.map((card) => {
const match = matchCardBrand(card, brandInfo, competitors);
const destination = card.merchant_url
? classifyMerchant(card.merchant_url, { brandDomains: brandInfo.domains })
@@ -182,6 +197,47 @@ export async function persistShoppingCards({
region: region ?? null,
};
});
+}
+
+/**
+ * Normalize and insert shopping cards into the analytical table.
+ *
+ * Exported so the backfill script can reuse the exact same code path
+ * against historical prompt_results rows without duplicating the parse +
+ * brand-match logic.
+ *
+ * @param {object} args
+ * @param {string} args.promptResultId
+ * @param {string} args.brandId
+ * @param {string} args.platform
+ * @param {string|null} args.region
+ * @param {unknown[]} args.rawCards
+ * @param {unknown[]} [args.rawInlineProducts] ChatGPT's in-answer products, stored after the cards
+ * @param {{ brandId: string, brandName: string, domains: string[] }} args.brandInfo
+ * @param {Array<{ id: string, name: string, domain: string|null }>} args.competitors
+ * @returns {Promise<number>} number of rows inserted (0 if none / on failure)
+ */
+export async function persistShoppingCards({
+ promptResultId,
+ brandId,
+ platform,
+ region,
+ rawCards,
+ rawInlineProducts = [],
+ brandInfo,
+ competitors,
+}) {
+ const rows = shoppingCardRows({
+ promptResultId,
+ brandId,
+ platform,
+ region,
+ rawCards,
+ rawInlineProducts,
+ brandInfo,
+ competitors,
+ });
+ if (rows.length === 0) return 0;
// The brand's own cards, matched to its catalog's products (00360): what
// Product Visibility counts on the shelf. The catalog may be unreadable;
diff --git a/server/src/lib/cms/webflow-status.js b/server/src/lib/cms/webflow-status.js
index a10bd2213..894adffa9 100644
--- a/server/src/lib/cms/webflow-status.js
+++ b/server/src/lib/cms/webflow-status.js
@@ -161,7 +161,9 @@ export async function sweepWebflowPublished() {
const started = Date.now();
const { data, error } = await supabaseAdmin
.from('brand_cms_connections')
- .select('brand_id, brands!inner(organizations!inner(subscription_status))')
+ .select('brand_id, brands!inner(is_demo, organizations!inner(subscription_status))')
+ // A demo brand's connection (00380) is shown, never used.
+ .eq('brands.is_demo', false)
.eq('provider', 'webflow')
.eq('status', 'connected')
.not('site_id', 'is', null)
diff --git a/server/src/lib/cms/webflow-status.test.js b/server/src/lib/cms/webflow-status.test.js
index b4c6b1e89..ec9020768 100644
--- a/server/src/lib/cms/webflow-status.test.js
+++ b/server/src/lib/cms/webflow-status.test.js
@@ -5,7 +5,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
* read from the items the sends made, marked published at their address.
*/
-const db = { connection: null, sends: [], brands: [], queries: [], updates: [] };
+const db = {
+ connection: null,
+ sends: [],
+ brands: [],
+ queries: [],
+ updates: [],
+ connectionReads: [],
+};
vi.mock('../../config/supabase.js', () => ({
default: {
from: (table) => {
@@ -16,6 +23,7 @@ vi.mock('../../config/supabase.js', () => ({
return { data: null, error: null };
}
if (table === 'brand_cms_connections') {
+ if (!q.single) db.connectionReads.push(q.filters);
return { data: q.single ? db.connection : db.brands, error: null };
}
db.queries.push(q);
@@ -219,6 +227,8 @@ describe('sweepWebflowPublished', () => {
// The brand that failed (the order is shuffled daily) is logged; the other went on.
expect(logged).toHaveLength(1);
expect(logged[0]).toMatch(/"brandId":"b[13]"/);
+ // Never a demo brand's connection (00380).
+ expect(db.connectionReads.at(-1)).toContainEqual(['eq', 'brands.is_demo', false]);
configured.on = false;
expect(await sweepWebflowPublished()).toEqual({ brands: 0, published: 0 });
});
diff --git a/server/src/lib/demo/brewline.js b/server/src/lib/demo/brewline.js
new file mode 100644
index 000000000..dc26031ce
--- /dev/null
+++ b/server/src/lib/demo/brewline.js
@@ -0,0 +1,427 @@
+/**
+ * Brewline Coffee: the demo brand's facts and its sample world.
+ *
+ * Everything here is made up. The brand, its competitors and every
+ * publisher, forum and shop it is cited on live on `.example` domains, which
+ * can never belong to anyone (RFC 2606), so the demo never names a real
+ * company or points at a real site (privacy first). All of it is English,
+ * like the rest of the demo.
+ */
+
+export const BRAND = {
+ name: 'Brewline Coffee',
+ slug: 'demo-brewline-coffee',
+ domain: 'brewline.example',
+ industry: 'Food & Beverage',
+ description:
+ 'Specialty coffee roaster selling freshly roasted whole beans by the bag and by subscription, shipped within a day of roasting.',
+ region: 'US',
+ language: 'en',
+ siteType: 'ecommerce',
+};
+
+/** The tracked competitors, strongest first; `presence` is how often an answer names one. */
+export const COMPETITORS = [
+ {
+ key: 'northbound',
+ name: 'Northbound Roasters',
+ domain: 'northboundroasters.example',
+ presence: 0.62,
+ traits: [
+ 'is a frequent pick for small-batch single origins',
+ 'gets praise for detailed tasting notes on every bag',
+ 'is known for a wide range of light roasts',
+ ],
+ },
+ {
+ key: 'kettle',
+ name: 'Kettle & Crate',
+ domain: 'kettleandcrate.example',
+ presence: 0.46,
+ traits: [
+ 'offers affordable bundles and frequent discounts',
+ 'is popular for its large variety boxes',
+ 'ships quickly, though roast dates can vary',
+ ],
+ },
+ {
+ key: 'ritual',
+ name: 'Morning Ritual Co.',
+ domain: 'morningritual.example',
+ presence: 0.36,
+ traits: [
+ 'is a favorite for gift boxes and brewing kits',
+ 'pairs its beans with simple brew guides for beginners',
+ 'focuses on smooth, medium roasts',
+ ],
+ },
+ {
+ key: 'daybreak',
+ name: 'Daybreak Beans',
+ domain: 'daybreakbeans.example',
+ presence: 0.27,
+ traits: [
+ 'is a budget-friendly option for everyday drinkers',
+ 'sells large bags at a low price per cup',
+ 'is often mentioned for dark, bold roasts',
+ ],
+ },
+];
+
+/** What an answer says about Brewline, by the sentiment it carries. */
+export const BRAND_TRAITS = {
+ positive: [
+ 'stands out for beans roasted to order and a subscription you can pause or skip anytime',
+ 'is praised for fresh, consistent roasts and clear roast dates on every bag',
+ 'earns strong reviews for flexible plans and friendly customer support',
+ 'is a reliable choice for fresh whole beans shipped within a day of roasting',
+ ],
+ neutral: [
+ 'offers whole-bean and ground subscriptions in several roast levels',
+ 'sells single origins and house blends by the bag or on a schedule',
+ 'has a subscription with weekly, biweekly and monthly deliveries',
+ ],
+ negative: [
+ 'has a solid range, though some reviewers mention slower shipping in busy weeks',
+ 'is well liked, but its prices sit above most supermarket brands',
+ ],
+};
+
+/** The platforms the demo tracks, with how often each names Brewline at the start and end of the month. */
+export const PLATFORMS = [
+ { id: 'chatgpt-web', mention: [0.42, 0.6], citations: [3, 5] },
+ { id: 'perplexity-web', mention: [0.52, 0.7], citations: [4, 6], fanout: 'perplexity' },
+ { id: 'gemini-web', mention: [0.34, 0.5], citations: [2, 4] },
+ { id: 'copilot-web', mention: [0.4, 0.56], citations: [3, 5], fanout: 'copilot' },
+ { id: 'google-aimode', mention: [0.38, 0.54], citations: [3, 5] },
+ { id: 'google-aio', mention: [0.3, 0.46], citations: [2, 3] },
+];
+
+export const TOPICS = [
+ { key: 'subscriptions', name: 'Coffee subscriptions' },
+ { key: 'beans', name: 'Whole bean coffee' },
+ { key: 'buying', name: 'Buying better coffee' },
+];
+
+/**
+ * The tracked prompts. `keywords` are the search volumes the Prompts page
+ * shows ({ keyword: [monthly volume, competition index] }); `shopping` marks
+ * the prompts whose answers carry product cards; `searches` are the searches
+ * the engines that share them ran for it.
+ */
+export const PROMPTS = [
+ {
+ key: 'best-subscriptions',
+ topic: 'subscriptions',
+ text: 'What are the best coffee subscriptions in 2026?',
+ lead: 'A few coffee subscriptions stand out this year for freshness and flexibility.',
+ intent: 'best-top',
+ shopping: true,
+ keywords: {
+ 'best coffee subscription': [8100, 42],
+ 'coffee subscription': [22200, 55],
+ 'coffee subscription box': [2900, 61],
+ 'best coffee subscription 2026': [1300, 38],
+ },
+ searches: [
+ 'best coffee subscription 2026',
+ 'coffee subscription reviews',
+ 'fresh roasted coffee subscription',
+ ],
+ },
+ {
+ key: 'pause-skip',
+ topic: 'subscriptions',
+ text: 'Which coffee subscription lets you pause or skip a delivery?',
+ lead: 'Most specialty roasters now let subscribers change their schedule online.',
+ intent: 'recommendation',
+ keywords: {
+ 'flexible coffee subscription': [480, 33],
+ 'pause coffee subscription': [210, 20],
+ 'coffee subscription skip delivery': [170, 18],
+ },
+ searches: ['coffee subscription pause anytime', 'flexible coffee delivery plan'],
+ },
+ {
+ key: 'gift',
+ topic: 'subscriptions',
+ text: 'What is a good coffee subscription gift for a coffee lover?',
+ lead: 'A prepaid subscription makes an easy gift that keeps arriving for months.',
+ intent: 'recommendation',
+ shopping: true,
+ keywords: {
+ 'coffee subscription gift': [6600, 58],
+ 'coffee gift subscription': [2400, 52],
+ 'gift for coffee lovers': [14800, 70],
+ },
+ searches: ['coffee subscription gift ideas', 'prepaid coffee subscription gift'],
+ },
+ {
+ key: 'worth-it',
+ topic: 'subscriptions',
+ text: 'Is a coffee bean subscription worth it?',
+ lead: 'For people who brew at home every day, a subscription usually pays off in freshness.',
+ intent: 'what-is',
+ keywords: {
+ 'coffee bean subscription': [3600, 47],
+ 'is a coffee subscription worth it': [590, 22],
+ 'coffee subscription vs buying beans': [90, 15],
+ },
+ searches: ['is a coffee subscription worth it', 'coffee subscription cost per cup'],
+ },
+ {
+ key: 'espresso',
+ topic: 'beans',
+ text: 'What are the best whole bean coffees for espresso at home?',
+ lead: 'Espresso rewards fresh beans with a medium or darker roast.',
+ intent: 'best-top',
+ shopping: true,
+ keywords: {
+ 'best espresso beans': [9900, 64],
+ 'best coffee beans for espresso': [5400, 60],
+ 'whole bean espresso': [1600, 49],
+ },
+ searches: ['best espresso beans for home', 'whole bean espresso roast'],
+ },
+ {
+ key: 'buy-online',
+ topic: 'beans',
+ text: 'Where can I buy freshly roasted coffee beans online?',
+ lead: 'Buying straight from a roaster is the surest way to get a recent roast date.',
+ intent: 'recommendation',
+ shopping: true,
+ keywords: {
+ 'buy coffee beans online': [2900, 66],
+ 'fresh roasted coffee beans online': [1300, 51],
+ 'freshly roasted coffee delivery': [720, 44],
+ },
+ searches: ['buy fresh roasted coffee beans online', 'coffee roaster ships same day'],
+ },
+ {
+ key: 'low-acid',
+ topic: 'beans',
+ text: 'Which coffee beans are best for a sensitive stomach?',
+ lead: 'Low-acid beans and darker roasts tend to be gentler on the stomach.',
+ intent: 'best-top',
+ keywords: {
+ 'low acid coffee': [27100, 57],
+ 'low acid coffee beans': [4400, 49],
+ 'best coffee for sensitive stomach': [1900, 41],
+ },
+ searches: ['low acid coffee beans', 'coffee for sensitive stomach'],
+ },
+ {
+ key: 'single-origin',
+ topic: 'beans',
+ text: 'Single-origin or blend: which coffee beans should I buy?',
+ lead: 'Single origins show off one farm or region, while blends aim for balance.',
+ intent: 'comparison',
+ keywords: {
+ 'single origin coffee': [12100, 46],
+ 'single origin vs blend coffee': [480, 25],
+ 'coffee blend vs single origin': [260, 21],
+ },
+ searches: ['single origin vs blend coffee', 'best single origin coffee beans'],
+ },
+ {
+ key: 'fair-trade',
+ topic: 'buying',
+ text: 'Which coffee roasters sell organic, fair trade beans?',
+ lead: 'Several online roasters publish where their beans come from and what farmers are paid.',
+ intent: 'recommendation',
+ keywords: {
+ 'fair trade coffee beans': [2900, 50],
+ 'organic fair trade coffee': [2400, 47],
+ 'organic coffee roasters': [880, 39],
+ },
+ searches: ['organic fair trade coffee roasters', 'direct trade coffee beans'],
+ },
+ {
+ key: 'decaf',
+ topic: 'buying',
+ text: 'What is the best decaf coffee that still tastes good?',
+ lead: 'Decaf has improved a lot, especially beans decaffeinated with water instead of solvents.',
+ intent: 'best-top',
+ shopping: true,
+ keywords: {
+ 'best decaf coffee': [12100, 53],
+ 'swiss water decaf': [3600, 35],
+ 'best decaf coffee beans': [2900, 48],
+ },
+ searches: ['best tasting decaf coffee beans', 'water process decaf coffee'],
+ },
+ {
+ key: 'freshness',
+ topic: 'buying',
+ text: 'How fresh should coffee beans be when they arrive?',
+ lead: 'Beans taste best within a few weeks of their roast date.',
+ intent: 'what-is',
+ keywords: {
+ 'fresh coffee beans': [5400, 43],
+ 'how long do coffee beans stay fresh': [4400, 18],
+ 'coffee roast date': [1000, 16],
+ },
+ searches: ['how long do coffee beans stay fresh', 'coffee roast date explained'],
+ },
+ {
+ key: 'versus',
+ topic: 'buying',
+ text: 'Brewline Coffee vs Northbound Roasters: which subscription is better?',
+ lead: 'Both are well-reviewed online roasters with flexible subscriptions.',
+ intent: 'vs-review',
+ // A prompt that names the brand: the answer always discusses it.
+ namesBrand: true,
+ keywords: {
+ 'northbound roasters review': [170, 12],
+ 'brewline coffee review': [110, 10],
+ 'brewline coffee vs northbound roasters': [40, 8],
+ },
+ searches: ['brewline coffee vs northbound roasters', 'northbound roasters subscription review'],
+ },
+];
+
+/** Closing lines, one per answer. */
+export const CLOSINGS = [
+ 'Check the roast date before you buy, and pick a grind that matches your brewer.',
+ 'Most of these offer a first-order discount, so it is easy to try a few.',
+ 'If you drink a lot of coffee, a subscription usually costs less per cup.',
+ 'Whichever you choose, store the beans airtight and away from light.',
+];
+
+/**
+ * The pages answers cite, by owner. `brand` pages are Brewline's own; the
+ * rest are competitors' and fictional publishers', review sites' and forums'.
+ */
+export const SOURCES = {
+ brand: [
+ { path: '/subscriptions', label: 'Coffee Subscriptions | Brewline Coffee' },
+ {
+ path: '/blog/how-fresh-should-coffee-beans-be',
+ label: 'How Fresh Should Coffee Beans Be? | Brewline',
+ },
+ { path: '/coffee/espresso-roast', label: 'Espresso Roast Whole Beans | Brewline Coffee' },
+ { path: '/coffee/decaf', label: 'Water Process Decaf | Brewline Coffee' },
+ { path: '/gifts', label: 'Coffee Gift Subscriptions | Brewline Coffee' },
+ ],
+ competitor: {
+ northbound: [
+ { path: '/subscribe', label: 'Subscribe | Northbound Roasters' },
+ { path: '/single-origins', label: 'Single Origins | Northbound Roasters' },
+ ],
+ kettle: [{ path: '/bundles', label: 'Coffee Bundles | Kettle & Crate' }],
+ ritual: [{ path: '/gift-boxes', label: 'Gift Boxes | Morning Ritual Co.' }],
+ daybreak: [{ path: '/bulk-coffee', label: 'Bulk Coffee Bags | Daybreak Beans' }],
+ },
+ publishers: [
+ {
+ domain: 'beanbulletin.example',
+ pages: [
+ {
+ path: '/best-coffee-subscriptions-2026',
+ label: 'The Best Coffee Subscriptions of 2026 | Bean Bulletin',
+ },
+ { path: '/best-decaf-coffee', label: 'Decaf That Tastes Like Coffee | Bean Bulletin' },
+ ],
+ },
+ {
+ domain: 'roastnotes.example',
+ pages: [
+ { path: '/guides/espresso-beans', label: 'Choosing Beans for Home Espresso | Roast Notes' },
+ { path: '/guides/single-origin-vs-blend', label: 'Single Origin vs Blend | Roast Notes' },
+ ],
+ },
+ {
+ domain: 'cupcompare.example',
+ pages: [
+ {
+ path: '/coffee-subscriptions-compared',
+ label: 'Coffee Subscriptions Compared | Cup Compare',
+ },
+ { path: '/low-acid-coffee', label: 'Low-Acid Coffee Picks | Cup Compare' },
+ ],
+ },
+ {
+ domain: 'brewersforum.example',
+ pages: [
+ {
+ path: '/t/which-subscription-do-you-use',
+ label: 'Which subscription do you use? | Brewers Forum',
+ },
+ {
+ path: '/t/fresh-beans-online',
+ label: 'Where do you buy fresh beans online? | Brewers Forum',
+ },
+ ],
+ },
+ {
+ domain: 'dailybrewnews.example',
+ pages: [
+ { path: '/fair-trade-roasters', label: 'Roasters Paying Farmers Fairly | Daily Brew News' },
+ { path: '/coffee-gifts', label: 'Coffee Gifts Worth Giving | Daily Brew News' },
+ ],
+ },
+ ],
+};
+
+/**
+ * The product cards answers show for the shopping prompts. Prices in USD;
+ * no images, so the demo loads nothing from outside.
+ */
+export const PRODUCTS = [
+ {
+ owner: 'brand',
+ title: 'Brewline House Blend Subscription',
+ path: '/subscriptions/house-blend',
+ price: 18.0,
+ rating: 4.8,
+ reviews: 412,
+ },
+ {
+ owner: 'brand',
+ title: 'Brewline Espresso Roast, Whole Bean 12 oz',
+ path: '/coffee/espresso-roast',
+ price: 16.5,
+ rating: 4.7,
+ reviews: 238,
+ },
+ {
+ owner: 'brand',
+ title: 'Brewline Water Process Decaf',
+ path: '/coffee/decaf',
+ price: 17.0,
+ rating: 4.6,
+ reviews: 96,
+ },
+ {
+ owner: 'northbound',
+ title: 'Northbound Single Origin Subscription',
+ path: '/subscribe',
+ price: 21.0,
+ rating: 4.7,
+ reviews: 530,
+ },
+ {
+ owner: 'kettle',
+ title: 'Kettle & Crate Variety Box',
+ path: '/bundles/variety',
+ price: 14.0,
+ rating: 4.3,
+ reviews: 865,
+ },
+ {
+ owner: 'ritual',
+ title: 'Morning Ritual Gift Box',
+ path: '/gift-boxes/classic',
+ price: 32.0,
+ rating: 4.5,
+ reviews: 188,
+ },
+ {
+ owner: 'daybreak',
+ title: 'Daybreak Dark Roast 2 lb Bag',
+ path: '/bulk-coffee/dark',
+ price: 19.0,
+ rating: 4.1,
+ reviews: 1204,
+ },
+];
diff --git a/server/src/lib/demo/core.js b/server/src/lib/demo/core.js
new file mode 100644
index 000000000..89b86a79d
--- /dev/null
+++ b/server/src/lib/demo/core.js
@@ -0,0 +1,658 @@
+/**
+ * The demo brand's core (demo-core): the brand itself, its domain, engines,
+ * competitors, topics and tracked prompts with their volumes, and a month of
+ * tracked answers with their citations, product cards and searches.
+ *
+ * The answers go through tracking's own code wherever it is pure: a raw
+ * answer in each engine's own shape is parsed by parseScraperResponse,
+ * scored by parseResponse and stored as resultRow and shoppingCardRows build
+ * it, so Brand Visibility, Prompts, Mentions, Citations and Query Fan-out
+ * read them like any brand's. The rollups those pages read are then rebuilt
+ * by the same functions the nightly run calls; nothing here writes one.
+ *
+ * Lean on purpose, as every no-card signup gets a demo: 12 prompts, 6
+ * engines, a run every 3 days over a month (720 short answers).
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+import { parseScraperResponse } from '../cloro-scraper.js';
+import { resultRow, shoppingCardRows } from '../cloro-result-handler.js';
+import { normalizeCitations } from '../citation-rows.js';
+import { dayChunks, HISTORY_CHUNK_DAYS, refreshCitationsDaily } from '../citations-rollups.js';
+import { AI_VOLUME_MULTIPLIER } from '../intent-extraction.js';
+import { refreshInsightsDaily, utcDay } from '../insights-rollups.js';
+import { refreshMentionsDaily, refreshPerceptionSnapshots } from '../mentions-rollups.js';
+import { parseResponse } from '../response-parser.js';
+import { summarizeVolumes } from '../volume-analysis.js';
+import {
+ BRAND,
+ BRAND_TRAITS,
+ CLOSINGS,
+ COMPETITORS,
+ PLATFORMS,
+ PRODUCTS,
+ PROMPTS,
+ SOURCES,
+ TOPICS,
+} from './brewline.js';
+import { demoId, seededRandom } from './random.js';
+import { allSettledOrThrow, demoWriter } from './write.js';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** Tracked runs, every RUN_EVERY_DAYS days back from the latest. */
+export const RUNS = 10;
+export const RUN_EVERY_DAYS = 3;
+/** When the nightly run starts (UTC hour), as the self-hosted cron's default. */
+const RUN_HOUR_UTC = 6;
+/** Seconds between two answers of a run: 72 answers take half an hour. */
+const ANSWER_GAP_MS = 25_000;
+/** The last runs whose shopping answers carry product cards. */
+const SHOPPING_RUNS = 4;
+/** The engines that show product cards, as they do live. */
+const CARD_PLATFORMS = new Set(['perplexity-web', 'google-aimode', 'copilot-web']);
+const REGION = 'US';
+const LOCATION_CODE = 2840;
+const SEED = 'brewline';
+
+/** How much more (or less) often a prompt's answers name Brewline. */
+const PROMPT_BIAS = {
+ freshness: 0.12,
+ 'buy-online': 0.08,
+ gift: -0.05,
+ 'fair-trade': -0.12,
+ 'low-acid': -0.18,
+};
+
+/** The Brewline page an answer to the prompt cites, and the product it shows. */
+const BRAND_PAGE = {
+ espresso: '/coffee/espresso-roast',
+ decaf: '/coffee/decaf',
+ gift: '/gifts',
+ freshness: '/blog/how-fresh-should-coffee-beans-be',
+ 'worth-it': '/blog/how-fresh-should-coffee-beans-be',
+};
+const BRAND_PRODUCT = {
+ espresso: '/coffee/espresso-roast',
+ 'buy-online': '/coffee/espresso-roast',
+ decaf: '/coffee/decaf',
+};
+
+const url = (domain, path) => `https://${domain}${path}`;
+
+/**
+ * When the latest run started: today's RUN_HOUR_UTC, or yesterday's when
+ * today's would not have finished an hour ago.
+ */
+export function latestRunStart(now) {
+ const day = new Date(now);
+ day.setUTCHours(RUN_HOUR_UTC, 0, 0, 0);
+ if (day.getTime() + 60 * 60 * 1000 > now.getTime()) day.setUTCDate(day.getUTCDate() - 1);
+ return day;
+}
+
+/** When the demo's first answer was given: the first run's first answer. */
+export function firstAnswerAt(now) {
+ return new Date(
+ latestRunStart(now).getTime() - (RUNS - 1) * RUN_EVERY_DAYS * DAY_MS + ANSWER_GAP_MS,
+ );
+}
+
+function priceText(amount) {
+ return `$${amount.toFixed(2)}`;
+}
+
+/** A product card in the engine's own shape (as Cloro returns it). */
+function rawCards(platformId, products) {
+ const owner = (product) =>
+ product.owner === 'brand'
+ ? { name: BRAND.name, domain: BRAND.domain }
+ : COMPETITORS.find((c) => c.key === product.owner);
+ if (platformId === 'perplexity-web') {
+ return products.map((p) => ({
+ title: p.title,
+ brand: owner(p).name,
+ price: priceText(p.price),
+ url: url(owner(p).domain, p.path),
+ rating: p.rating,
+ review_count: p.reviews,
+ }));
+ }
+ if (platformId === 'google-aimode') {
+ return products.map((p) => ({
+ title: p.title,
+ brand: owner(p).name,
+ price: priceText(p.price),
+ url: url(owner(p).domain, p.path),
+ rating: p.rating,
+ reviewCount: p.reviews,
+ }));
+ }
+ // Copilot wraps its products (parseCopilotCard).
+ return [
+ {
+ type: 'shoppingProducts',
+ layout: 'carousel',
+ products: products.map((p, i) => ({
+ position: i + 1,
+ name: p.title,
+ brandName: owner(p).name,
+ seller: owner(p).name,
+ price: priceText(p.price),
+ url: url(owner(p).domain, p.path),
+ rating: { value: p.rating, count: p.reviews },
+ })),
+ },
+ ];
+}
+
+/** The answer's text: a lead, the brands it names in order, a closing line. */
+function answerText(prompt, named, rng) {
+ const lines = named.map(({ name, trait }, i) =>
+ prompt.intent === 'best-top' || prompt.intent === 'recommendation'
+ ? `${i + 1}. **${name}** ${trait}.`
+ : `**${name}** ${trait}.`,
+ );
+ return [prompt.lead, lines.join('\n'), rng.pick(CLOSINGS)].join('\n\n');
+}
+
+/** The pages one answer cites: Brewline's, the named competitors', then publishers'. */
+function answerSources(prompt, platform, { brandNamed, competitorsNamed, progress }, rng) {
+ const count = rng.int(platform.citations[0], platform.citations[1]);
+ const picked = [];
+ if (brandNamed && rng.chance(0.5 + 0.2 * progress)) {
+ const path = BRAND_PAGE[prompt.key] ?? '/subscriptions';
+ const page = SOURCES.brand.find((p) => p.path === path);
+ picked.push({ url: url(BRAND.domain, page.path), label: page.label });
+ }
+ for (const competitor of competitorsNamed) {
+ if (picked.length >= count || !rng.chance(0.35)) continue;
+ const page = rng.pick(SOURCES.competitor[competitor.key]);
+ picked.push({ url: url(competitor.domain, page.path), label: page.label });
+ }
+ const publisherPages = rng.shuffle(
+ SOURCES.publishers.flatMap((p) =>
+ p.pages.map((page) => ({ url: url(p.domain, page.path), label: page.label })),
+ ),
+ );
+ for (const page of publisherPages) {
+ if (picked.length >= count) break;
+ picked.push(page);
+ }
+ return picked;
+}
+
+/** The product cards a shopping answer shows: Brewline's when it is named, then rivals'. */
+function answerProducts(prompt, { brandNamed, competitorsNamed }, rng) {
+ const products = [];
+ if (brandNamed ? rng.chance(0.85) : rng.chance(0.25)) {
+ const path = BRAND_PRODUCT[prompt.key] ?? '/subscriptions/house-blend';
+ products.push(PRODUCTS.find((p) => p.owner === 'brand' && p.path === path));
+ }
+ for (const competitor of rng.shuffle(competitorsNamed)) {
+ if (products.length >= 3) break;
+ products.push(PRODUCTS.find((p) => p.owner === competitor.key));
+ }
+ return products.filter(Boolean);
+}
+
+/**
+ * One tracked answer: what the engine returned, in its own shape, before
+ * tracking parses it.
+ */
+function rawAnswer(prompt, platform, { run, progress }) {
+ const rng = seededRandom(`${SEED}:${run}:${prompt.key}:${platform.id}`);
+
+ const mentionChance =
+ platform.mention[0] +
+ (platform.mention[1] - platform.mention[0]) * progress +
+ (PROMPT_BIAS[prompt.key] ?? 0);
+ const brandNamed = Boolean(prompt.namesBrand) || rng.chance(mentionChance);
+ const competitorsNamed = COMPETITORS.filter(
+ (c) => (prompt.namesBrand && c.key === 'northbound') || rng.chance(c.presence),
+ );
+ // An answer names two brands at least.
+ for (const competitor of COMPETITORS) {
+ if (competitorsNamed.length + (brandNamed ? 1 : 0) >= 2) break;
+ if (!competitorsNamed.includes(competitor)) competitorsNamed.push(competitor);
+ }
+
+ let sentiment = 'neutral';
+ if (brandNamed) {
+ const roll = rng.next();
+ sentiment = roll < 0.66 + 0.1 * progress ? 'positive' : roll > 0.93 ? 'negative' : 'neutral';
+ }
+
+ let named = rng
+ .shuffle(competitorsNamed)
+ .map((c) => ({ name: c.name, trait: rng.pick(c.traits) }));
+ if (brandNamed) {
+ const own = { name: BRAND.name, trait: rng.pick(BRAND_TRAITS[sentiment]) };
+ // Named first more often as the month goes on: the demo's visibility climbs.
+ const at = rng.chance(0.25 + 0.35 * progress) ? 0 : rng.int(0, named.length);
+ named = [...named.slice(0, at), own, ...named.slice(at)];
+ }
+
+ const sources = answerSources(prompt, platform, { brandNamed, competitorsNamed, progress }, rng);
+ const raw = { text: answerText(prompt, named, rng), sources };
+
+ if (platform.fanout) {
+ const searches = rng.shuffle(prompt.searches).slice(0, rng.int(1, prompt.searches.length));
+ if (platform.fanout === 'perplexity') raw.search_model_queries = searches;
+ else raw.searchQueries = searches;
+ }
+
+ if (prompt.shopping && run >= RUNS - SHOPPING_RUNS && CARD_PLATFORMS.has(platform.id)) {
+ const products = rng.chance(0.75)
+ ? answerProducts(prompt, { brandNamed, competitorsNamed }, rng)
+ : [];
+ if (products.length > 0) {
+ const cards = rawCards(platform.id, products);
+ if (platform.id === 'perplexity-web') raw.shopping_cards = cards;
+ else raw.shoppingCards = cards;
+ }
+ }
+
+ // The engines' own envelopes (parseScraperResponse).
+ if (platform.id === 'google-aio') return { raw: { aioverview: raw }, sentiment };
+ if (platform.id === 'google-aimode') return { raw: { result: raw }, sentiment };
+ return { raw, sentiment };
+}
+
+/**
+ * Every core row of the demo brand, built in memory: deterministic but for
+ * the dates, which count back from `now`. Pure, so a test can pin it.
+ *
+ * @param {{ brandId: string, now: Date }} args
+ */
+export function coreRows({ brandId, now }) {
+ const id = (key) => demoId(brandId, key);
+ const latest = latestRunStart(now);
+ const runStarts = Array.from(
+ { length: RUNS },
+ (_, i) => new Date(latest.getTime() - (RUNS - 1 - i) * RUN_EVERY_DAYS * DAY_MS),
+ );
+ // The brand was set up a few days before its first run.
+ const since = new Date(runStarts[0].getTime() - 5 * DAY_MS).toISOString();
+
+ const brand = {
+ name: BRAND.name,
+ industry: BRAND.industry,
+ description: BRAND.description,
+ region: BRAND.region,
+ language: BRAND.language,
+ site_type: BRAND.siteType,
+ shopping_mode_enabled: true,
+ is_active: true,
+ // The app ships the made-up brand's logo (web/public/demo/logos).
+ logo_url: '/demo/logos/brewline.svg',
+ created_at: since,
+ };
+ const brandInfo = { brandName: BRAND.name, domains: [BRAND.domain] };
+
+ const domains = [
+ {
+ id: id('domain'),
+ brand_id: brandId,
+ domain: BRAND.domain,
+ country: REGION,
+ is_primary: true,
+ created_at: since,
+ },
+ ];
+ const competitors = COMPETITORS.map((c) => ({
+ id: id(`competitor:${c.key}`),
+ brand_id: brandId,
+ name: c.name,
+ domain: c.domain,
+ created_at: since,
+ }));
+ const tracked = competitors.map(({ id: competitorId, name, domain }) => ({
+ id: competitorId,
+ name,
+ domain,
+ }));
+ const topics = TOPICS.map((t) => ({
+ id: id(`topic:${t.key}`),
+ brand_id: brandId,
+ name: t.name,
+ is_active: true,
+ created_at: since,
+ }));
+ const promptSetId = id('prompt-set');
+ const promptSets = [{ id: promptSetId, brand_id: brandId, name: 'Default', created_at: since }];
+ const platformIds = PLATFORMS.map((p) => p.id);
+ const prompts = PROMPTS.map((p) => ({
+ id: id(`prompt:${p.key}`),
+ prompt_set_id: promptSetId,
+ text: p.text,
+ category: TOPICS.find((t) => t.key === p.topic).name,
+ topic_id: id(`topic:${p.topic}`),
+ platforms: platformIds,
+ regions: [REGION],
+ models: [],
+ is_active: true,
+ created_at: since,
+ }));
+ const volumes = PROMPTS.map((p) => {
+ const keywords = Object.keys(p.keywords);
+ const summary = summarizeVolumes(
+ keywords,
+ Object.fromEntries(
+ Object.entries(p.keywords).map(([k, [volume, competitionIndex]]) => [
+ k,
+ { volume, competitionIndex },
+ ]),
+ ),
+ );
+ return {
+ prompt_id: id(`prompt:${p.key}`),
+ intent: p.intent,
+ keywords,
+ google_volumes: summary.googleVolumes,
+ total_google_volume: summary.totalGoogleVolume,
+ ai_volume_multiplier: AI_VOLUME_MULTIPLIER,
+ est_ai_volume: summary.estAiVolume,
+ competition_index: summary.competitionIndex,
+ competition: summary.competition,
+ location_code: LOCATION_CODE,
+ language_code: BRAND.language,
+ fetched_at: since,
+ };
+ });
+
+ const runs = [];
+ const results = [];
+ const citations = [];
+ const shoppingCards = [];
+ runStarts.forEach((startedAt, run) => {
+ const progress = run / (RUNS - 1);
+ let at = startedAt.getTime();
+ for (const prompt of PROMPTS) {
+ for (const platform of PLATFORMS) {
+ at += ANSWER_GAP_MS;
+ const createdAt = new Date(at).toISOString();
+ const resultId = id(`result:${run}:${prompt.key}:${platform.id}`);
+ const promptId = id(`prompt:${prompt.key}`);
+ const { raw, sentiment } = rawAnswer(prompt, platform, { run, progress });
+ const aiResponse = parseScraperResponse(raw, platform.id);
+ const metrics = parseResponse(aiResponse, brandInfo, sentiment, tracked);
+ results.push({
+ id: resultId,
+ ...resultRow({
+ aiResponse,
+ scraperId: platform.id,
+ promptId,
+ brandId,
+ region: REGION,
+ metrics,
+ }),
+ created_at: createdAt,
+ });
+ for (const entry of normalizeCitations(aiResponse.citations)) {
+ citations.push({ ...entry, prompt_result_id: resultId, created_at: createdAt });
+ }
+ for (const card of shoppingCardRows({
+ promptResultId: resultId,
+ brandId,
+ platform: platform.id,
+ region: REGION,
+ rawCards: aiResponse.shopping_cards ?? [],
+ brandInfo: { brandId, ...brandInfo },
+ competitors: tracked,
+ })) {
+ shoppingCards.push({ ...card, created_at: createdAt });
+ }
+ }
+ }
+ const completedAt = new Date(at + 2 * 60 * 1000).toISOString();
+ runs.push({
+ id: id(`run:${run}`),
+ brand_id: brandId,
+ source: 'cron',
+ started_at: startedAt.toISOString(),
+ completed_at: completedAt,
+ result_count: PROMPTS.length * PLATFORMS.length,
+ created_at: startedAt.toISOString(),
+ });
+ });
+
+ const lastChecked = runs.at(-1).completed_at;
+ const platforms = PLATFORMS.map((p) => ({
+ id: id(`platform:${p.id}`),
+ brand_id: brandId,
+ platform: p.id,
+ is_enabled: true,
+ check_frequency: 'daily',
+ api_model: null,
+ last_checked_at: lastChecked,
+ created_at: since,
+ }));
+
+ return {
+ brand,
+ domains,
+ platforms,
+ competitors,
+ topics,
+ promptSets,
+ prompts,
+ volumes,
+ runs,
+ results,
+ citations,
+ shoppingCards,
+ };
+}
+
+/** Citation rows per statement: they are small. */
+const CITATION_CHUNK = 1000;
+/** The demo's month of answer terms is refreshed in one call: it is small. */
+const TERM_DAYS = 31;
+
+/** The cited URLs' ids in the shared dictionary (#732), resolved in one call. */
+async function citationUrlIds(db, entries) {
+ const byUrl = new Map();
+ for (const entry of entries) {
+ if (!byUrl.has(entry.url)) byUrl.set(entry.url, entry);
+ }
+ if (byUrl.size === 0) return new Map();
+ const { data, error } = await db.rpc('citation_url_ids', {
+ p_urls: [...byUrl.values()].map(({ url: u, domain, title }) => ({ url: u, domain, title })),
+ });
+ if (error) throw new Error(`demo citation url resolve: ${error.message}`);
+ return new Map((data ?? []).map((row) => [row.url, row.id]));
+}
+
+/** The citation rows, each pointing at its URL's id. */
+function citationRows(brandId, entries, ids) {
+ return entries.map((entry) => ({
+ prompt_result_id: entry.prompt_result_id,
+ position: entry.position,
+ url_id: ids.get(entry.url),
+ brand_id: brandId,
+ created_at: entry.created_at,
+ }));
+}
+
+/** The first UTC day of the brand's rollups, or null without any. */
+async function firstRollupDay(db, brandId) {
+ const { data, error } = await db
+ .from('insights_brand_daily')
+ .select('day')
+ .eq('brand_id', brandId)
+ .order('day')
+ .limit(1);
+ if (error) throw new Error(`demo rollup days read: ${error.message}`);
+ return data?.[0]?.day ?? null;
+}
+
+/**
+ * Rebuild the rollups the pages read, over the demo's whole month, with the
+ * nightly run's own functions; Insights, Citations and Mentions side by side
+ * (each takes its own lock), the Perception views once the Mentions rollups
+ * are in. Each refresh call rewrites its days in one statement, so a page
+ * read meanwhile sees the old days or the new ones, never none. Throws when
+ * one fails: a demo with empty charts is rebuilt on the next visit instead
+ * of shown.
+ */
+async function refreshRollups(brandId, dayFrom, dayTo) {
+ const citations = async () => {
+ for (const [from, to] of dayChunks(dayFrom, dayTo, HISTORY_CHUNK_DAYS)) {
+ if (!(await refreshCitationsDaily(brandId, from, to))) return false;
+ }
+ return true;
+ };
+ const mentions = async () => {
+ const options = { termDays: TERM_DAYS, together: true };
+ if (!(await refreshMentionsDaily(brandId, dayFrom, dayTo, options))) {
+ return false;
+ }
+ await refreshPerceptionSnapshots(brandId);
+ return true;
+ };
+ const [insightsOk, citationsOk, mentionsOk] = await Promise.all([
+ refreshInsightsDaily(brandId, dayFrom, dayTo),
+ citations(),
+ mentions(),
+ ]);
+ if (!insightsOk) throw new Error('demo insights rollups failed');
+ if (!citationsOk) throw new Error('demo citation rollups failed');
+ if (!mentionsOk) throw new Error('demo mention rollups failed');
+}
+
+/** The core module's key columns where a row has no `id` of its own. */
+const KEYS = {
+ prompt_volumes: 'prompt_id',
+ prompt_result_citations: 'prompt_result_id,position',
+ prompt_result_shopping_cards: 'prompt_result_id,position',
+};
+/** Its tables without a brand_id, found through the table they point at. */
+const SCOPES = {
+ prompts: ['prompt_set_id', 'prompt_sets'],
+ prompt_volumes: ['prompt_id', 'prompts'],
+};
+
+/**
+ * The core module: its brand-scoped tables, in the order they are written
+ * (a rebuild of a module that isn't rebuilt in place clears them in
+ * reverse), its build, which writes its rows, and its refresh, which
+ * rebuilds the rollups from them.
+ */
+export const core = {
+ name: 'core',
+ // Rebuilt in place: rows are written over, the ones not written again
+ // deleted after (write.js).
+ inPlace: true,
+ keys: KEYS,
+ scopes: SCOPES,
+ tables: [
+ // Written here.
+ 'brand_domains',
+ 'brand_platforms',
+ 'competitors',
+ 'topics',
+ 'prompt_sets', // and, through it, prompts and prompt_volumes
+ 'tracking_runs',
+ 'prompt_results',
+ 'prompt_result_citations',
+ 'prompt_result_shopping_cards',
+ // Kept by triggers on prompts.
+ 'prompt_usage_counters',
+ // Rebuilt by the rollup functions (refresh).
+ 'insights_brand_daily',
+ 'insights_prompt_daily',
+ 'insights_competitor_daily',
+ 'insights_competitor_prompt_daily',
+ 'citation_result_daily',
+ 'citation_url_daily',
+ 'citation_domain_daily',
+ 'citation_gap_domain_daily',
+ 'citation_gap_competitor_daily',
+ 'mentions_prompt_daily',
+ 'mentions_competitor_daily',
+ 'mentions_entities_daily',
+ 'mentions_answer_terms',
+ 'mentions_terms_daily',
+ 'mentions_perception_snapshots',
+ // Queued by the prompt and domain triggers while the demo is rewritten;
+ // cleared once the rollups above are rebuilt.
+ 'insights_rollup_rebuilds',
+ 'citation_rollup_rebuilds',
+ ],
+
+ /**
+ * Writes the brand, its setup and its month of answers, each step's
+ * independent tables side by side. `write` is the build's writer
+ * (write.js); without one (a test), a writer over `db` for a first build.
+ *
+ * @param {{ brandId: string, now: Date, db?: object, rebuild?: boolean, write?: Function }} ctx
+ */
+ async build({
+ brandId,
+ now,
+ db = supabaseAdmin,
+ rebuild = false,
+ write = demoWriter({ db, brandId, rebuild, keys: KEYS, scopes: SCOPES }).write,
+ }) {
+ const rows = coreRows({ brandId, now });
+
+ const { error: brandError } = await db.from('brands').update(rows.brand).eq('id', brandId);
+ if (brandError) throw new Error(`demo brand update: ${brandError.message}`);
+
+ // What nothing else points into, and the cited URLs' ids.
+ const [urlIds] = await allSettledOrThrow([
+ citationUrlIds(db, rows.citations),
+ write('brand_domains', rows.domains),
+ write('brand_platforms', rows.platforms),
+ write('competitors', rows.competitors),
+ write('topics', rows.topics),
+ write('prompt_sets', rows.promptSets),
+ write('tracking_runs', rows.runs),
+ ]);
+ // The prompts point at their topic and set; their volumes and answers at them.
+ await write('prompts', rows.prompts);
+ await allSettledOrThrow([
+ write('prompt_volumes', rows.volumes),
+ write('prompt_results', rows.results),
+ ]);
+ // What the answers cite and show.
+ await allSettledOrThrow([
+ write('prompt_result_citations', citationRows(brandId, rows.citations, urlIds), {
+ chunk: CITATION_CHUNK,
+ }),
+ write('prompt_result_shopping_cards', rows.shoppingCards),
+ ]);
+
+ return {
+ prompts: rows.prompts.length,
+ results: rows.results.length,
+ citations: rows.citations.length,
+ shoppingCards: rows.shoppingCards.length,
+ };
+ },
+
+ /**
+ * Rebuilds the rollups over the demo's month; on a rebuild, from the old
+ * month's first day on, so the days it no longer covers are emptied.
+ *
+ * @param {{ brandId: string, now: Date, db?: object, rebuild?: boolean }} ctx
+ */
+ async refresh({ brandId, now, db = supabaseAdmin, rebuild = false }) {
+ const dayTo = utcDay(now.toISOString());
+ let dayFrom = utcDay(firstAnswerAt(now).toISOString());
+ if (rebuild) {
+ const previous = await firstRollupDay(db, brandId);
+ if (previous && previous < dayFrom) dayFrom = previous;
+ }
+ await refreshRollups(brandId, dayFrom, dayTo);
+
+ // The rebuilds the triggers queued are done: the rollups were rebuilt whole.
+ await allSettledOrThrow(
+ ['insights_rollup_rebuilds', 'citation_rollup_rebuilds'].map(async (table) => {
+ const { error } = await db.from(table).delete().eq('brand_id', brandId);
+ if (error) throw new Error(`demo ${table} clear: ${error.message}`);
+ }),
+ );
+ },
+};
diff --git a/server/src/lib/demo/core.test.js b/server/src/lib/demo/core.test.js
new file mode 100644
index 000000000..3ddd7c4d9
--- /dev/null
+++ b/server/src/lib/demo/core.test.js
@@ -0,0 +1,352 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../config/supabase.js', () => ({ default: {} }));
+const rollups = vi.hoisted(() => ({
+ refreshInsightsDaily: vi.fn(async () => true),
+ refreshCitationsDaily: vi.fn(async () => true),
+ refreshMentionsDaily: vi.fn(async () => true),
+ refreshPerceptionSnapshots: vi.fn(async () => {}),
+}));
+vi.mock('../insights-rollups.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ refreshInsightsDaily: rollups.refreshInsightsDaily,
+}));
+vi.mock('../citations-rollups.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ refreshCitationsDaily: rollups.refreshCitationsDaily,
+}));
+vi.mock('../mentions-rollups.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ refreshMentionsDaily: rollups.refreshMentionsDaily,
+ refreshPerceptionSnapshots: rollups.refreshPerceptionSnapshots,
+}));
+
+const { RUNS, core, coreRows, firstAnswerAt, latestRunStart } = await import('./core.js');
+const { resultRow } = await import('../cloro-result-handler.js');
+
+/**
+ * The demo brand's core data (demo-core): a month of Brewline Coffee's
+ * tracked answers, in tracking's own shapes, deterministic but for its dates.
+ */
+
+const BRAND_ID = '11111111-2222-4333-8444-555555555555';
+const NOW = new Date('2026-10-28T12:00:00Z');
+const DAY = 86_400_000;
+const rows = coreRows({ brandId: BRAND_ID, now: NOW });
+
+describe('coreRows', () => {
+ it('is lean: 12 prompts in 3 topics, 6 engines, 4 competitors, a run every 3 days', () => {
+ expect(rows.prompts).toHaveLength(12);
+ expect(new Set(rows.prompts.map((p) => p.topic_id)).size).toBe(3);
+ expect(rows.topics).toHaveLength(3);
+ expect(rows.competitors.map((c) => c.name)).toEqual([
+ 'Northbound Roasters',
+ 'Kettle & Crate',
+ 'Morning Ritual Co.',
+ 'Daybreak Beans',
+ ]);
+ expect(rows.platforms.map((p) => p.platform).sort()).toEqual([
+ 'chatgpt-web',
+ 'copilot-web',
+ 'gemini-web',
+ 'google-aimode',
+ 'google-aio',
+ 'perplexity-web',
+ ]);
+ expect(rows.runs).toHaveLength(RUNS);
+ expect(rows.results).toHaveLength(12 * 6 * RUNS);
+ expect(rows.volumes).toHaveLength(12);
+ });
+
+ it('is the same every time but for its dates, and its ids are its brand’s own', () => {
+ const later = coreRows({ brandId: BRAND_ID, now: new Date(NOW.getTime() + 5 * DAY) });
+ const strip = (r) => ({ ...r, created_at: undefined });
+ expect(later.results.map(strip)).toEqual(rows.results.map(strip));
+
+ const other = coreRows({ brandId: '99999999-2222-4333-8444-555555555555', now: NOW });
+ expect(other.results.map((r) => r.response)).toEqual(rows.results.map((r) => r.response));
+ expect(other.results[0].id).not.toBe(rows.results[0].id);
+ expect(rows.results[0].id).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
+ );
+ });
+
+ it('dates its runs back from now, the latest finished within the day', () => {
+ const latest = latestRunStart(NOW);
+ expect(latest.toISOString()).toBe('2026-10-28T06:00:00.000Z');
+ // Before 07:00 UTC, today's run isn't done yet: the latest was yesterday's.
+ expect(latestRunStart(new Date('2026-10-28T06:30:00Z')).toISOString()).toBe(
+ '2026-10-27T06:00:00.000Z',
+ );
+ const times = rows.results.map((r) => Date.parse(r.created_at));
+ expect(Math.max(...times)).toBeLessThan(NOW.getTime());
+ expect(NOW.getTime() - Math.min(...times)).toBeLessThan(31 * DAY);
+ for (const run of rows.runs) {
+ expect(run).toMatchObject({ brand_id: BRAND_ID, source: 'cron', result_count: 72 });
+ expect(Date.parse(run.completed_at)).toBeLessThan(NOW.getTime());
+ }
+ expect(rows.runs.at(-1).started_at).toBe(latest.toISOString());
+ });
+
+ it('stores each answer in the shape tracking stores it', () => {
+ const shape = Object.keys(
+ resultRow({
+ aiResponse: { text: '', citations: [], model: 'm' },
+ scraperId: 's',
+ promptId: 'p',
+ brandId: 'b',
+ region: 'US',
+ metrics: {},
+ }),
+ );
+ for (const result of rows.results) {
+ expect(Object.keys(result).sort()).toEqual([...shape, 'id', 'created_at'].sort());
+ expect(result.brand_id).toBe(BRAND_ID);
+ expect(result.region).toBe('US');
+ }
+ const answer = rows.results.find((r) => r.mention_count > 0);
+ expect(answer.response).toContain('Brewline Coffee');
+ expect(answer.mention_position).toBeGreaterThanOrEqual(1);
+ expect(answer.competitor_mentions).toHaveLength(4);
+ });
+
+ it('names Brewline in about half the answers, more as the month goes on', () => {
+ const named = (list) => list.filter((r) => r.mention_count > 0).length / list.length;
+ const share = named(rows.results);
+ expect(share).toBeGreaterThan(0.4);
+ expect(share).toBeLessThan(0.65);
+ expect(named(rows.results.slice(-72))).toBeGreaterThan(named(rows.results.slice(0, 72)));
+ // Not named: no sentiment of its own, as tracking stores it.
+ for (const r of rows.results.filter((x) => x.mention_count === 0)) {
+ expect(r.sentiment).toBe('neutral');
+ }
+ const sentiments = new Set(rows.results.map((r) => r.sentiment));
+ expect(sentiments).toEqual(new Set(['positive', 'neutral', 'negative']));
+ });
+
+ it('shares searches only on the engines that do, and cards only where they show', () => {
+ const engines = (list) => [...new Set(list.map((r) => r.platform))].sort();
+ expect(engines(rows.results.filter((r) => r.search_queries.length > 0))).toEqual([
+ 'copilot-web',
+ 'perplexity-web',
+ ]);
+ const withCards = rows.results.filter((r) => r.shopping_cards.length > 0);
+ expect(engines(withCards)).toEqual(['copilot-web', 'google-aimode', 'perplexity-web']);
+ expect(rows.shoppingCards.length).toBeGreaterThan(20);
+ expect(new Set(rows.shoppingCards.map((c) => c.matched_brand_role))).toEqual(
+ new Set(['own', 'competitor']),
+ );
+ });
+
+ it('cites Brewline, its competitors and fictional publishers, never a real site', () => {
+ const domains = new Set(rows.citations.map((c) => c.domain));
+ expect(domains.has('brewline.example')).toBe(true);
+ expect(domains.has('northboundroasters.example')).toBe(true);
+ expect(domains.size).toBeGreaterThan(6);
+
+ const hosts = JSON.stringify(rows).match(/https?:\/\/[^/"\s)]+/g);
+ expect(hosts.length).toBeGreaterThan(100);
+ for (const host of new Set(hosts)) expect(host).toMatch(/\.example$/);
+ for (const card of rows.shoppingCards) {
+ expect(card.merchant_domain).toMatch(/\.example$/);
+ expect(card.image_url).toBeNull();
+ }
+ });
+
+ it('gives every prompt its volumes, as the volume analysis computes them', () => {
+ const [first] = rows.volumes;
+ expect(first).toMatchObject({
+ intent: 'best-top',
+ total_google_volume: 5500,
+ est_ai_volume: Math.round(5500 * first.ai_volume_multiplier),
+ location_code: 2840,
+ language_code: 'en',
+ });
+ expect(Object.keys(first.google_volumes)).toEqual(first.keywords);
+ });
+});
+
+/** A recording stand-in for the admin client; `reads` answers its selects, by table. */
+function recordingDb({ reads = {} } = {}) {
+ const calls = [];
+ const db = {
+ calls,
+ from: (table) => {
+ const call = { table };
+ calls.push(call);
+ const chain = {
+ insert: (payload) => ((call.op = 'insert'), (call.rows = payload), chain),
+ upsert: (payload, { onConflict }) => (
+ (call.op = 'upsert'),
+ (call.rows = payload),
+ (call.onConflict = onConflict),
+ chain
+ ),
+ update: (payload) => ((call.op = 'update'), (call.payload = payload), chain),
+ delete: () => ((call.op = 'delete'), chain),
+ select: () => ((call.op ??= 'select'), chain),
+ eq: (column, value) => ((call.eq = [column, value]), chain),
+ order: () => chain,
+ limit: () => chain,
+ then: (resolve) => resolve({ data: reads[table] ?? [], error: null }),
+ };
+ return chain;
+ },
+ rpc: async (fn, args) => {
+ calls.push({ rpc: fn, args });
+ return { data: args.p_urls.map((u, i) => ({ url: u.url, id: i + 1 })), error: null };
+ },
+ };
+ return db;
+}
+
+describe('core.build', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('writes the brand, its setup and its answers', async () => {
+ const db = recordingDb();
+ const built = await core.build({ brandId: BRAND_ID, now: NOW, db });
+
+ expect(built).toMatchObject({ prompts: 12, results: 720 });
+ const [brand] = db.calls;
+ expect(brand).toMatchObject({ table: 'brands', op: 'update', eq: ['id', BRAND_ID] });
+ expect(brand.payload).toMatchObject({ name: 'Brewline Coffee', site_type: 'ecommerce' });
+ expect(brand.payload).not.toHaveProperty('demo_hidden_at');
+
+ const inserted = [...new Set(db.calls.filter((c) => c.op === 'upsert').map((c) => c.table))];
+ // Each step's tables side by side, after the ones they point at.
+ expect(inserted).toEqual([
+ 'brand_domains',
+ 'brand_platforms',
+ 'competitors',
+ 'topics',
+ 'prompt_sets',
+ 'tracking_runs',
+ 'prompts',
+ 'prompt_volumes',
+ 'prompt_results',
+ 'prompt_result_citations',
+ 'prompt_result_shopping_cards',
+ ]);
+ const count = (table) =>
+ db.calls.filter((c) => c.table === table).reduce((n, c) => n + (c.rows?.length ?? 0), 0);
+ expect(count('prompt_results')).toBe(720);
+ expect(count('prompt_result_citations')).toBe(rows.citations.length);
+ // Statements stay small: the answers 250 at a time, the small citation rows 1,000.
+ const largest = (table) =>
+ Math.max(...db.calls.filter((c) => c.table === table).map((c) => c.rows.length));
+ expect(largest('prompt_results')).toBe(250);
+ expect(largest('prompt_result_citations')).toBeLessThanOrEqual(1000);
+
+ // One call resolves every cited URL, and each citation row carries its id.
+ const resolves = db.calls.filter((c) => c.rpc === 'citation_url_ids');
+ expect(resolves).toHaveLength(1);
+ const citationRows = db.calls
+ .filter((c) => c.table === 'prompt_result_citations')
+ .flatMap((c) => c.rows);
+ expect(citationRows.every((r) => Number.isInteger(r.url_id))).toBe(true);
+
+ // Writing rows rebuilds no rollup: refresh does, once they are all in.
+ expect(rollups.refreshInsightsDaily).not.toHaveBeenCalled();
+ expect(db.calls.some((c) => c.op === 'delete')).toBe(false);
+ });
+
+ it('writes over the old rows, by each table’s key', async () => {
+ const db = recordingDb();
+ await core.build({ brandId: BRAND_ID, now: NOW, db, rebuild: true });
+ const writes = db.calls.filter((c) => c.rows);
+ expect(writes.every((c) => c.op === 'upsert')).toBe(true);
+ const keyOf = (table) => writes.find((c) => c.table === table).onConflict;
+ expect(keyOf('prompt_results')).toBe('id');
+ expect(keyOf('prompts')).toBe('id');
+ expect(keyOf('prompt_volumes')).toBe('prompt_id');
+ expect(keyOf('prompt_result_citations')).toBe('prompt_result_id,position');
+ expect(keyOf('prompt_result_shopping_cards')).toBe('prompt_result_id,position');
+ expect(db.calls.some((c) => c.op === 'delete')).toBe(false);
+ });
+
+ it('fails with the table when a write does', async () => {
+ const db = recordingDb();
+ const from = db.from;
+ db.from = (table) => {
+ const chain = from(table);
+ if (table !== 'prompt_results') return chain;
+ return {
+ ...chain,
+ upsert: () => ({ then: (resolve) => resolve({ error: { message: 'full' } }) }),
+ };
+ };
+ await expect(core.build({ brandId: BRAND_ID, now: NOW, db })).rejects.toThrow(
+ 'demo prompt_results insert: full',
+ );
+ // Nothing that points at the answers was written after them.
+ expect(db.calls.some((c) => c.table === 'prompt_result_citations')).toBe(false);
+ });
+});
+
+describe('core.refresh', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("rebuilds the month's rollups side by side, by the nightly run's own functions", async () => {
+ const db = recordingDb();
+ await core.refresh({ brandId: BRAND_ID, now: NOW, db });
+
+ const first = firstAnswerAt(NOW).toISOString().slice(0, 10);
+ expect(first).toBe(rows.results[0].created_at.slice(0, 10));
+ expect(rollups.refreshInsightsDaily).toHaveBeenCalledWith(BRAND_ID, first, '2026-10-28');
+ expect(rollups.refreshCitationsDaily.mock.calls.length).toBeGreaterThanOrEqual(2);
+ // The demo's month of answer terms in one call.
+ expect(rollups.refreshMentionsDaily).toHaveBeenCalledWith(BRAND_ID, first, '2026-10-28', {
+ termDays: 31,
+ together: true,
+ });
+ expect(rollups.refreshPerceptionSnapshots).toHaveBeenCalledWith(BRAND_ID);
+ // A first build reads nothing back.
+ expect(db.calls.some((c) => c.op === 'select')).toBe(false);
+
+ // What the triggers queued while it was rewritten is done.
+ const cleared = db.calls.filter((c) => c.op === 'delete').map((c) => c.table);
+ expect(cleared).toEqual(['insights_rollup_rebuilds', 'citation_rollup_rebuilds']);
+ });
+
+ it('starts the rollups together, the Perception views after the Mentions ones', async () => {
+ const order = [];
+ const slow = (name, ms) => async () => {
+ order.push(`${name}:start`);
+ await new Promise((resolve) => setTimeout(resolve, ms));
+ order.push(`${name}:end`);
+ return true;
+ };
+ rollups.refreshInsightsDaily.mockImplementationOnce(slow('insights', 10));
+ rollups.refreshCitationsDaily.mockImplementation(slow('citations', 5));
+ rollups.refreshMentionsDaily.mockImplementationOnce(slow('mentions', 5));
+ rollups.refreshPerceptionSnapshots.mockImplementationOnce(slow('perception', 1));
+ await core.refresh({ brandId: BRAND_ID, now: NOW, db: recordingDb() });
+ rollups.refreshCitationsDaily.mockImplementation(async () => true);
+
+ expect(order.slice(0, 3).sort()).toEqual([
+ 'citations:start',
+ 'insights:start',
+ 'mentions:start',
+ ]);
+ expect(order.indexOf('mentions:end')).toBeLessThan(order.indexOf('perception:start'));
+ });
+
+ it('on a rebuild also empties the days the old month covered and the new one doesn’t', async () => {
+ const db = recordingDb({ reads: { insights_brand_daily: [{ day: '2026-09-20' }] } });
+ await core.refresh({ brandId: BRAND_ID, now: NOW, db, rebuild: true });
+ expect(rollups.refreshInsightsDaily).toHaveBeenCalledWith(BRAND_ID, '2026-09-20', '2026-10-28');
+ expect(rollups.refreshMentionsDaily.mock.calls[0][1]).toBe('2026-09-20');
+ });
+
+ it('fails, for the next visit to rebuild, when a rollup does', async () => {
+ rollups.refreshInsightsDaily.mockResolvedValueOnce(false);
+ await expect(core.refresh({ brandId: BRAND_ID, now: NOW, db: recordingDb() })).rejects.toThrow(
+ 'demo insights rollups failed',
+ );
+ rollups.refreshMentionsDaily.mockResolvedValueOnce(false);
+ await expect(core.refresh({ brandId: BRAND_ID, now: NOW, db: recordingDb() })).rejects.toThrow(
+ 'demo mention rollups failed',
+ );
+ });
+});
diff --git a/server/src/lib/demo/coverage.js b/server/src/lib/demo/coverage.js
new file mode 100644
index 000000000..4c9594d33
--- /dev/null
+++ b/server/src/lib/demo/coverage.js
@@ -0,0 +1,153 @@
+/**
+ * What the demo brand covers. Every brand-scoped table (one with a
+ * `brand_id` column, as the migrations leave it) is either built by a demo
+ * module (its `tables`), skipped here with the reason, or pending here with
+ * the PR that will build it. coverage.test.js reads the migrations and fails
+ * on a table that is in none of these, so a new feature's table can't ship
+ * without the demo saying what it shows for it.
+ */
+
+/** Tables a demo brand never has rows in, and why. */
+export const SKIPPED = {
+ cloro_pending_tasks: "Tracking's queue of scraper tasks: a demo brand is never tracked.",
+ jobs: 'The tracking and content job queue: no job runs for a demo brand.',
+ sent_pulses: 'Pulse e-mails sent: nobody is mailed about a demo brand.',
+ pulse_settings:
+ 'Pulse e-mail settings: a demo brand is never mailed; its settings show the defaults.',
+ ai_traffic_digests: 'Weekly AI traffic e-mails sent: never for a demo brand.',
+ suggestion_relevance_usage:
+ 'AI spend on suggestion relevance: nothing is spent for a demo brand.',
+ webhook_configs: 'Outgoing webhooks: a demo brand never calls out.',
+ prompt_table_views:
+ "A person's saved Tracked Prompts columns (00363): the demo brand starts on the default ones.",
+ sentiment_overrides:
+ "A person's sentiment corrections on Mentions: the demo's answers carry their own.",
+ chat_activity_log:
+ "Chat's log of the changes it made (00402): Chat's precedence refuses every change on a demo brand, so none is logged.",
+ chat_access_requests:
+ "A person's request to their Admins for a Chat change (00403): theirs, not sample data, and a demo brand's refusal offers no Ask your Admin.",
+};
+
+const WORKFLOWS = 'demo-workflows (PR 2): Action Center, Content, suggestions, reports';
+const SITE = 'demo-site (PR 3): Site Audit, AI traffic, integrations, Product Visibility';
+const CHAT = 'demo Chat, once Chat ships (the demo shows Chat as Soon until then)';
+
+/** Tables a later demo PR builds; listed so the gap stays visible until then. */
+export const PENDING = {
+ actions: WORKFLOWS,
+ action_candidates: WORKFLOWS,
+ action_task_runs: WORKFLOWS,
+ signals: WORKFLOWS,
+ signal_runs: WORKFLOWS,
+ kpi_definitions: WORKFLOWS,
+ getting_started: WORKFLOWS,
+ getting_started_steps: WORKFLOWS,
+ content_opportunities: WORKFLOWS,
+ content_drafts: WORKFLOWS,
+ content_plan_marks: WORKFLOWS,
+ content_author_defaults: WORKFLOWS,
+ content_shopping_checks: WORKFLOWS,
+ prompt_suggestions: WORKFLOWS,
+ prompt_improve_suggestions: WORKFLOWS,
+ prompt_clusters: WORKFLOWS,
+ prompt_cluster_scopes: WORKFLOWS,
+ topic_suggestions: WORKFLOWS,
+ reports: WORKFLOWS,
+
+ site_audits: SITE,
+ site_pages: SITE,
+ site_trust: SITE,
+ site_audit_brand_settings: SITE,
+ site_audit_page_prefs: SITE,
+ brand_facts: SITE,
+ brand_fact_pages: SITE,
+ ai_traffic_logs: SITE,
+ ai_traffic_events: SITE,
+ ai_bot_connections: SITE,
+ ai_bot_daily: SITE,
+ ai_bot_events: SITE,
+ ga_ai_traffic_stats: SITE,
+ ga_channel_stats: SITE,
+ ga_item_stats: SITE,
+ ga_page_stats: SITE,
+ gsc_page_stats: SITE,
+ gsc_query_stats: SITE,
+ page_opportunities: SITE,
+ brand_cms_connections: SITE,
+ content_draft_deliveries: SITE,
+ catalog_sources: SITE,
+ catalog_products: SITE,
+ catalog_variants: SITE,
+ catalog_images: SITE,
+ catalog_categories: SITE,
+ catalog_product_categories: SITE,
+ catalog_category_pages: SITE,
+ catalog_item_issues: SITE,
+
+ cited_page_features:
+ "demo follow-up (PR 7): what the pages a demo answer cites have (learning C1, 00369); never read for a demo brand, whose tasks don't run",
+ competitor_page_events:
+ "demo follow-up (PR 7): a demo competitor's pages over time (learning C3, 00376); the nightly read never runs for a demo brand",
+ competitor_timeline_scans:
+ "demo follow-up (PR 7): when a demo competitor's pages were last read (learning C3, 00376); the nightly read never runs for a demo brand",
+
+ agent_conversations: CHAT,
+ chat_conversations: CHAT,
+ prompt_demand:
+ "demo follow-up (PR 7): each demo prompt's demand level (PROMPT-014, 00370); the nightly read never runs for a demo brand",
+};
+
+const name = (raw) =>
+ raw
+ .replace(/"/g, '')
+ .replace(/^public\./i, '')
+ .toLowerCase();
+
+/** The text of a parenthesized list starting at `open` (the index of its "("). */
+function balanced(sql, open) {
+ let depth = 0;
+ for (let i = open; i < sql.length; i++) {
+ if (sql[i] === '(') depth++;
+ else if (sql[i] === ')' && --depth === 0) return sql.slice(open + 1, i);
+ }
+ return sql.slice(open + 1);
+}
+
+const BRAND_ID_COLUMN = /(^|[\s,(])"?brand_id"?\s+/i;
+
+/**
+ * The tables with a `brand_id` column once the given migrations have run,
+ * in order: created with one, given one (`add column brand_id`), losing it,
+ * renamed or dropped.
+ *
+ * @param {string[]} migrations - each migration's SQL, in order
+ * @returns {Set<string>}
+ */
+export function brandScopedTables(migrations) {
+ const tables = new Map();
+ const statement =
+ /create\s+table\s+(?:if\s+not\s+exists\s+)?([\w."]+)\s*\(|alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?([\w."]+)\s+([^;]*);|drop\s+table\s+(?:if\s+exists\s+)?([\w.",\s]+?)\s*(?:cascade|restrict)?\s*;/gi;
+ for (const migration of migrations) {
+ const sql = migration.replace(/--[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '');
+ for (const m of sql.matchAll(statement)) {
+ if (m[1]) {
+ tables.set(name(m[1]), BRAND_ID_COLUMN.test(balanced(sql, m.index + m[0].length - 1)));
+ } else if (m[2]) {
+ const table = name(m[2]);
+ const rename = m[3].match(/^rename\s+to\s+([\w."]+)/i);
+ if (rename) {
+ const had = tables.get(table);
+ tables.delete(table);
+ tables.set(name(rename[1]), had);
+ } else if (/add\s+column\s+(?:if\s+not\s+exists\s+)?"?brand_id"?\s/i.test(m[3])) {
+ tables.set(table, true);
+ } else if (/drop\s+column\s+(?:if\s+exists\s+)?"?brand_id"?/i.test(m[3])) {
+ tables.set(table, false);
+ }
+ } else if (m[4]) {
+ for (const table of m[4].split(',')) tables.delete(name(table.trim()));
+ }
+ }
+ }
+ return new Set([...tables].filter(([, hasBrandId]) => hasBrandId).map(([table]) => table));
+}
diff --git a/server/src/lib/demo/coverage.test.js b/server/src/lib/demo/coverage.test.js
new file mode 100644
index 000000000..0e1037f69
--- /dev/null
+++ b/server/src/lib/demo/coverage.test.js
@@ -0,0 +1,80 @@
+import { readdirSync, readFileSync } from 'fs';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../config/supabase.js', () => ({ default: {} }));
+
+const { DEMO_MODULES } = await import('./index.js');
+const { PENDING, SKIPPED, brandScopedTables } = await import('./coverage.js');
+
+/**
+ * The demo keeps up with the product (00380): every table with a brand_id is
+ * built by a demo module, skipped with a reason, or pending a later demo PR.
+ * A new brand-scoped table fails this test until the demo says which.
+ */
+
+const dir = new URL('../../../../supabase/migrations/', import.meta.url);
+const migrations = readdirSync(dir)
+ .filter((file) => file.endsWith('.sql'))
+ .sort()
+ .map((file) => readFileSync(new URL(file, dir), 'utf8'));
+const brandTables = brandScopedTables(migrations);
+
+const built = DEMO_MODULES.flatMap((module) => module.tables);
+
+describe('the demo brand covers every brand-scoped table', () => {
+ it('finds the brand-scoped tables in the migrations', () => {
+ expect(brandTables.size).toBeGreaterThan(80);
+ for (const table of ['prompt_results', 'brand_domains', 'actions', 'catalog_products']) {
+ expect(brandTables.has(table), table).toBe(true);
+ }
+ // No brand_id of its own: prompts belong to a brand through their prompt set.
+ expect(brandTables.has('prompts')).toBe(false);
+ });
+
+ it('has every one built, skipped or pending', () => {
+ const missing = [...brandTables].filter(
+ (table) => !built.includes(table) && !(table in SKIPPED) && !(table in PENDING),
+ );
+ // A table here is new: add it to a demo module's `tables` (lib/demo),
+ // or to SKIPPED (with why a demo brand has none) or PENDING in coverage.js.
+ expect(missing).toEqual([]);
+ });
+
+ it('names each table once, and only tables that exist', () => {
+ const named = [...built, ...Object.keys(SKIPPED), ...Object.keys(PENDING)];
+ expect(named.filter((table, i) => named.indexOf(table) !== i)).toEqual([]);
+ expect(named.filter((table) => !brandTables.has(table))).toEqual([]);
+ });
+
+ it('says why a table is skipped, and which PR builds a pending one', () => {
+ for (const [table, reason] of Object.entries(SKIPPED)) {
+ expect(reason.length, table).toBeGreaterThan(20);
+ }
+ for (const [table, by] of Object.entries(PENDING)) {
+ expect(by, table).toMatch(/PR \d|Chat ships/);
+ }
+ });
+
+ it('keeps what costs or mails out of the demo', () => {
+ for (const table of ['cloro_pending_tasks', 'jobs', 'sent_pulses', 'ai_traffic_digests']) {
+ expect(SKIPPED[table], table).toBeTruthy();
+ }
+ });
+});
+
+describe('brandScopedTables', () => {
+ it('follows tables through creates, added columns, renames and drops', () => {
+ const tables = brandScopedTables([
+ `create table public.a (id uuid, brand_id uuid not null references public.brands(id));
+ create table if not exists "public"."b" ("id" uuid, "brand_id" "uuid");
+ create table c (id uuid, note text default 'brand_id');
+ -- create table commented (brand_id uuid);
+ create table d (id uuid, check (length(name) > 0));`,
+ `alter table c add column if not exists brand_id uuid;
+ alter table public.b rename to b2;
+ alter table d add column other uuid;
+ drop table if exists public.a cascade;`,
+ ]);
+ expect([...tables].sort()).toEqual(['b2', 'c']);
+ });
+});
diff --git a/server/src/lib/demo/index.js b/server/src/lib/demo/index.js
new file mode 100644
index 000000000..04b73f02d
--- /dev/null
+++ b/server/src/lib/demo/index.js
@@ -0,0 +1,322 @@
+/**
+ * The demo brand (00380): Brewline Coffee, a fictional brand with sample
+ * data in the real tables, one per organization. People without a plan (or
+ * who just want a look) explore the live product on it: every page reads it
+ * through its own queries. Nothing that costs ever runs for it (the sweeps,
+ * jobs and limits skip `is_demo`).
+ *
+ * It keeps itself current: a brand built with an older DEMO_VERSION, or
+ * whose month of data has grown old, is rebuilt on the next visit, in place
+ * (same brand id, same row ids), so links to it keep working, and over its
+ * old rows, so whoever opens it meanwhile sees last week's data rather than
+ * empty pages (write.js). A product
+ * change that the demo should show is a new module, or a change to one, and
+ * a DEMO_VERSION bump; the coverage test (coverage.test.js) fails until every
+ * brand-scoped table is either built by a module or listed as skipped.
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+import { logger } from '../logger.js';
+import { BRAND } from './brewline.js';
+import { core } from './core.js';
+import { demoWriter } from './write.js';
+
+/** Bump to rebuild every demo brand on its next visit. */
+export const DEMO_VERSION = 1;
+
+/** Data older than this is rebuilt, so the demo's latest run stays recent. */
+export const DEMO_MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000;
+
+/**
+ * How long a build under way holds the demo brand: another server finding it
+ * mid-build waits for it this long, then takes over (a build cut short by a
+ * restart is never finished by anyone else).
+ */
+export const DEMO_BUILD_LEASE_MS = 10 * 60 * 1000;
+
+/** How long a visit waits on another server's build before answering as it stands. */
+export const DEMO_WAIT_MS = 60 * 1000;
+/** How often a visit waiting on another server's build looks again. */
+const WAIT_POLL_MS = 1000;
+
+/**
+ * The modules that build the demo. Each is `{ name, tables, build(ctx),
+ * refresh?(ctx), after?, inPlace?, keys?, scopes? }`:
+ * - `tables`: the brand-scoped tables it owns (written, or rebuilt by what
+ * it calls).
+ * - `build(ctx)` writes its rows; ctx is `{ brandId, now, rebuild, write }`.
+ * `refresh(ctx)` then rebuilds what is derived from them (rollups).
+ * - The first module runs alone; the others run together (with the first
+ * one's refresh), each after the one it names in `after`.
+ * - On a rebuild, a module marked `inPlace` writes every row through
+ * `ctx.write(table, rows)`, which writes over the old rows (`keys` names a
+ * table's key columns when they aren't 'id'; `scopes` how to find the
+ * brand's rows of a table without a brand_id); the rows not written again
+ * are deleted once it is built (on a first build, none are). Any other
+ * module has its `tables` cleared, in reverse, just before it is built.
+ * Action Center, Content, reports, Site Audit, traffic and Product
+ * Visibility follow as modules of their own.
+ */
+export const DEMO_MODULES = [core];
+
+const COLUMNS = 'id, demo_version, demo_built_at, demo_hidden_at';
+
+/** Builds in progress in this process, by organization. */
+const inFlight = new Map();
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+async function readDemoBrand(organizationId) {
+ const { data, error } = await supabaseAdmin
+ .from('brands')
+ .select(COLUMNS)
+ .eq('organization_id', organizationId)
+ .eq('is_demo', true)
+ .maybeSingle();
+ if (error) throw new Error(`demo brand read: ${error.message}`);
+ return data;
+}
+
+/**
+ * Creates the organization's demo brand, holding it for its first build. A
+ * second visit creating it at the same moment hits the one-per-organization
+ * index (23505) and reads the first one's row instead.
+ */
+async function createDemoBrand(organizationId, now) {
+ const { data, error } = await supabaseAdmin
+ .from('brands')
+ .insert({
+ organization_id: organizationId,
+ name: BRAND.name,
+ slug: BRAND.slug,
+ is_demo: true,
+ demo_version: null,
+ demo_built_at: now.toISOString(),
+ })
+ .select(COLUMNS)
+ .single();
+ if (!error) return { brand: data, claimed: true };
+ if (error.code !== '23505') throw new Error(`demo brand insert: ${error.message}`);
+ const existing = await readDemoBrand(organizationId);
+ if (!existing) throw new Error(`demo brand insert: ${error.message}`);
+ return { brand: existing, claimed: false };
+}
+
+/**
+ * Where a demo brand's data stands: 'fresh' (current version, recent),
+ * 'building' (a build started within the lease) or 'stale'.
+ */
+export function demoState(brand, now = new Date()) {
+ const builtAt = brand.demo_built_at ? Date.parse(brand.demo_built_at) : null;
+ const age = builtAt === null ? Infinity : now.getTime() - builtAt;
+ if (brand.demo_version === null || brand.demo_version === undefined) {
+ return age < DEMO_BUILD_LEASE_MS ? 'building' : 'stale';
+ }
+ // A newer server's demo is left to it.
+ if (brand.demo_version > DEMO_VERSION) return 'fresh';
+ if (brand.demo_version < DEMO_VERSION) return 'stale';
+ return age < DEMO_MAX_AGE_MS ? 'fresh' : 'stale';
+}
+
+/**
+ * Takes the build: only if the row is still as read, so of two servers
+ * finding it stale at once, one rebuilds and the other waits.
+ */
+async function claimBuild(brand, now) {
+ let query = supabaseAdmin
+ .from('brands')
+ .update({ demo_version: null, demo_built_at: now.toISOString() })
+ .eq('id', brand.id);
+ query =
+ brand.demo_version === null || brand.demo_version === undefined
+ ? query.is('demo_version', null)
+ : query.eq('demo_version', brand.demo_version);
+ query = brand.demo_built_at
+ ? query.eq('demo_built_at', brand.demo_built_at)
+ : query.is('demo_built_at', null);
+ const { data, error } = await query.select('id');
+ if (error) throw new Error(`demo build claim: ${error.message}`);
+ return (data ?? []).length > 0;
+}
+
+/** Clears every module's tables for the brand, the last module's first. */
+export async function clearDemoData(brandId, modules = DEMO_MODULES) {
+ for (const module of [...modules].reverse()) {
+ for (const table of [...module.tables].reverse()) {
+ const { error } = await supabaseAdmin.from(table).delete().eq('brand_id', brandId);
+ if (error) throw new Error(`demo ${table} clear: ${error.message}`);
+ }
+ }
+}
+
+/**
+ * After a failed build: lets the next visit rebuild at once instead of
+ * waiting out the lease. Best effort; the lease covers a failure here.
+ */
+async function releaseBuild(brandId) {
+ const { error } = await supabaseAdmin
+ .from('brands')
+ .update({ demo_built_at: null })
+ .eq('id', brandId)
+ .is('demo_version', null);
+ if (error) logger.warn({ brandId, err: error }, '[demo] failed build not released');
+}
+
+/**
+ * Writes one module's rows: over the old ones (`inPlace`) or after clearing
+ * its tables (`cleared`, when the clear was started earlier).
+ */
+async function writeModule(module, { brandId, now, rebuild, cleared }, built) {
+ if (!module.inPlace) await (cleared.get(module.name) ?? clearDemoData(brandId, [module]));
+ const writer = demoWriter({
+ db: supabaseAdmin,
+ brandId,
+ rebuild: rebuild && Boolean(module.inPlace),
+ keys: module.keys,
+ scopes: module.scopes,
+ });
+ const ctx = { brandId, now, rebuild, write: writer.write };
+ built[module.name] = await module.build(ctx);
+ const pruned = await writer.prune();
+ if (Object.keys(pruned).length > 0) built[`${module.name}Pruned`] = pruned;
+ return ctx;
+}
+
+/**
+ * Builds the demo brand's data. `rebuild` is false for a brand just created:
+ * no old rows to read back and prune.
+ */
+async function build(brandId, now, modules, { rebuild }) {
+ const started = Date.now();
+ const built = {};
+ // Even a brand just created isn't empty (its insert trigger starts Getting
+ // started): a module not rebuilt in place clears its tables first. On a
+ // first build nobody is looking yet, so every such module starts clearing
+ // at once, alongside the core; on a rebuild each clears just before it is
+ // built, so its old rows stay on show as long as they can.
+ const cleared = new Map();
+ if (!rebuild) {
+ for (const module of modules.filter((m) => !m.inPlace)) {
+ const clear = clearDemoData(brandId, [module]);
+ // Awaited when the module is built; a build failing earlier leaves it.
+ clear.catch(() => {});
+ cleared.set(module.name, clear);
+ }
+ }
+ const args = { brandId, now, rebuild, cleared };
+ try {
+ // The first module (core) lays down what every other one points at; the
+ // rest write their own tables side by side, each after the module it
+ // names in `after`, if any, while the first one's rollups are rebuilt.
+ const [first, ...rest] = modules;
+ const firstCtx = await writeModule(first, args, built);
+ const running = new Map();
+ const run = (module) => {
+ if (!running.has(module.name)) {
+ const before = module.after && rest.find((m) => m.name === module.after);
+ running.set(
+ module.name,
+ (async () => {
+ if (before) await run(before);
+ const ctx = await writeModule(module, args, built);
+ if (module.refresh) await module.refresh(ctx);
+ })(),
+ );
+ }
+ return running.get(module.name);
+ };
+ const results = await Promise.allSettled([
+ first.refresh ? first.refresh(firstCtx) : null,
+ ...rest.map(run),
+ ]);
+ const failed = results.find((r) => r.status === 'rejected');
+ if (failed) throw failed.reason;
+ } catch (err) {
+ await releaseBuild(brandId);
+ throw err;
+ }
+ const { error } = await supabaseAdmin
+ .from('brands')
+ .update({ demo_version: DEMO_VERSION, demo_built_at: now.toISOString() })
+ .eq('id', brandId);
+ if (error) throw new Error(`demo build stamp: ${error.message}`);
+ logger.info({ brandId, built, ms: Date.now() - started }, '[demo] demo brand built');
+}
+
+/** Waits for another server's build of the brand, up to DEMO_WAIT_MS. */
+async function waitForBuild(organizationId) {
+ const since = Date.now();
+ for (;;) {
+ await sleep(WAIT_POLL_MS);
+ const brand = await readDemoBrand(organizationId);
+ if (!brand) return null;
+ if (demoState(brand, new Date()) !== 'building' || Date.now() - since >= DEMO_WAIT_MS) {
+ return brand;
+ }
+ }
+}
+
+async function ensure(organizationId, now, modules) {
+ let brand = await readDemoBrand(organizationId);
+ let claimed = false;
+ let created = false;
+ if (!brand) {
+ ({ brand, claimed } = await createDemoBrand(organizationId, now));
+ created = claimed;
+ }
+
+ if (!claimed) {
+ let state = demoState(brand, now);
+ if (state === 'building') {
+ brand = (await waitForBuild(organizationId)) ?? brand;
+ state = demoState(brand, new Date());
+ }
+ if (state !== 'stale') {
+ return { brandId: brand.id, version: brand.demo_version ?? null, rebuilt: false };
+ }
+ if (!(await claimBuild(brand, now))) {
+ // Another server took it a moment ago.
+ const after = (await waitForBuild(organizationId)) ?? brand;
+ return { brandId: after.id, version: after.demo_version ?? null, rebuilt: false };
+ }
+ }
+
+ // A brand just created has no old data to prune.
+ await build(brand.id, now, modules, { rebuild: !created });
+ return { brandId: brand.id, version: DEMO_VERSION, rebuilt: true };
+}
+
+/**
+ * The organization's demo brand, created or rebuilt when it has to be.
+ * Whether it is hidden (demo_hidden_at) is left as it is. Two calls for one
+ * organization in this process share one build.
+ *
+ * @param {{ organizationId: string, now?: Date, modules?: object[] }} args
+ * @returns {Promise<{ brandId: string, version: number|null, rebuilt: boolean }>}
+ */
+export function ensureDemoBrand({ organizationId, now = new Date(), modules = DEMO_MODULES }) {
+ if (!inFlight.has(organizationId)) {
+ const run = ensure(organizationId, now, modules).finally(() => inFlight.delete(organizationId));
+ inFlight.set(organizationId, run);
+ }
+ return inFlight.get(organizationId);
+}
+
+/**
+ * Hides or shows the organization's demo brand: the organization's choice,
+ * not one person's. Never deletes it.
+ *
+ * @param {{ organizationId: string, hidden: boolean, now?: Date }} args
+ * @returns {Promise<{ brandId: string, hidden: boolean } | null>} null without a demo brand
+ */
+export async function setDemoHidden({ organizationId, hidden, now = new Date() }) {
+ const { data, error } = await supabaseAdmin
+ .from('brands')
+ .update({ demo_hidden_at: hidden ? now.toISOString() : null })
+ .eq('organization_id', organizationId)
+ .eq('is_demo', true)
+ .select('id');
+ if (error) throw new Error(`demo brand hide: ${error.message}`);
+ const brand = data?.[0];
+ return brand ? { brandId: brand.id, hidden } : null;
+}
diff --git a/server/src/lib/demo/index.test.js b/server/src/lib/demo/index.test.js
new file mode 100644
index 000000000..258d95a6e
--- /dev/null
+++ b/server/src/lib/demo/index.test.js
@@ -0,0 +1,445 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The organization's demo brand (00380): created on the first visit, rebuilt
+ * in place when DEMO_VERSION moves on or its data grows old, left alone
+ * otherwise; hidden or shown by the organization, never deleted.
+ */
+
+const state = vi.hoisted(() => ({
+ brands: [],
+ tables: {},
+ cleared: [],
+ log: [],
+ failInsert: null,
+ onRead: null,
+}));
+
+/**
+ * The admin client over `state.brands` and the modules' `state.tables`,
+ * recording each table a rebuild clears (a delete by brand) and, in
+ * `state.log`, each write and delete of a module's table.
+ */
+vi.mock('../../config/supabase.js', () => {
+ const matches = (row, filters) =>
+ filters.every(([op, column, value]) => {
+ if (op === 'is') return (row[column] ?? null) === value;
+ if (op === 'in') return value.includes(row[column]);
+ return row[column] === value;
+ });
+ const tableRun = (table, q) => {
+ const rows = (state.tables[table] ??= []);
+ if (q.op === 'insert' || q.op === 'upsert') {
+ state.log.push(`${q.op} ${table}`);
+ for (const row of q.payload) {
+ const same = q.op === 'upsert' && rows.find((r) => r.id === row.id);
+ if (same) Object.assign(same, row);
+ else rows.push({ ...row });
+ }
+ return { data: null, error: null };
+ }
+ const hit = rows.filter((r) => matches(r, q.filters));
+ if (q.op === 'delete') {
+ if (q.filters.length === 1 && q.filters[0][1] === 'brand_id') {
+ state.cleared.push([table, ...q.filters[0].slice(1)]);
+ }
+ state.log.push(`delete ${table}`);
+ state.tables[table] = rows.filter((r) => !hit.includes(r));
+ return { data: null, error: null };
+ }
+ const [start, end] = q.range ?? [0, hit.length];
+ return { data: hit.slice(start, end + 1).map((r) => ({ id: r.id })), error: null };
+ };
+ const from = (table) => {
+ const q = { op: 'select', filters: [], payload: null, returning: false, range: null };
+ const run = () => {
+ if (table !== 'brands') return tableRun(table, q);
+ if (q.op === 'insert') {
+ if (state.failInsert) return { data: null, error: state.failInsert };
+ const taken = state.brands.some(
+ (b) => b.is_demo && b.organization_id === q.payload.organization_id,
+ );
+ if (taken) return { data: null, error: { code: '23505', message: 'duplicate key' } };
+ const row = { id: `brand-${state.brands.length + 1}`, demo_hidden_at: null, ...q.payload };
+ state.brands.push(row);
+ return { data: { ...row }, error: null };
+ }
+ const rows = state.brands.filter((b) => matches(b, q.filters));
+ if (q.op === 'update') {
+ for (const row of rows) Object.assign(row, q.payload);
+ return { data: q.returning ? rows.map((r) => ({ id: r.id })) : null, error: null };
+ }
+ state.onRead?.();
+ return { data: rows.map((r) => ({ ...r })), error: null };
+ };
+ const chain = {
+ select: () => ((q.returning = true), chain),
+ insert: (payload) => ((q.op = 'insert'), (q.payload = payload), chain),
+ upsert: (payload) => ((q.op = 'upsert'), (q.payload = payload), chain),
+ update: (payload) => ((q.op = 'update'), (q.payload = payload), chain),
+ delete: () => ((q.op = 'delete'), chain),
+ eq: (column, value) => (q.filters.push(['eq', column, value]), chain),
+ is: (column, value) => (q.filters.push(['is', column, value]), chain),
+ in: (column, values) => (q.filters.push(['in', column, values]), chain),
+ order: () => chain,
+ range: (start, end) => ((q.range = [start, end]), chain),
+ maybeSingle: async () => {
+ const { data, error } = run();
+ return { data: data?.[0] ?? null, error };
+ },
+ single: async () => {
+ const { data, error } = run();
+ return { data: Array.isArray(data) ? data[0] : data, error };
+ },
+ then: (resolve, reject) => Promise.resolve(run()).then(resolve, reject),
+ };
+ return chain;
+ };
+ return { default: { from } };
+});
+vi.mock('../logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+
+const {
+ DEMO_BUILD_LEASE_MS,
+ DEMO_MAX_AGE_MS,
+ DEMO_VERSION,
+ demoState,
+ ensureDemoBrand,
+ setDemoHidden,
+} = await import('./index.js');
+
+const NOW = new Date('2026-10-28T12:00:00Z');
+const DAY_MS = 86_400_000;
+const ago = (ms) => new Date(NOW.getTime() - ms).toISOString();
+const build = vi.fn(async () => ({ rows: 1 }));
+const modules = [
+ { name: 'one', tables: ['a', 'b'], build },
+ { name: 'two', tables: ['c'], build },
+];
+const ensure = (organizationId = 'org-1', now = NOW) =>
+ ensureDemoBrand({ organizationId, now, modules });
+
+const demo = (over = {}) => ({
+ id: 'demo-1',
+ organization_id: 'org-1',
+ is_demo: true,
+ demo_version: DEMO_VERSION,
+ demo_built_at: ago(60_000),
+ demo_hidden_at: null,
+ ...over,
+});
+
+beforeEach(() => {
+ state.brands = [{ id: 'real-1', organization_id: 'org-1', is_demo: false }];
+ state.tables = {};
+ state.cleared = [];
+ state.log = [];
+ state.failInsert = null;
+ state.onRead = null;
+ build.mockReset().mockResolvedValue({ rows: 1 });
+});
+afterEach(() => vi.useRealTimers());
+
+describe('ensureDemoBrand', () => {
+ it('creates the demo brand on the first visit and builds it', async () => {
+ expect(await ensure()).toEqual({ brandId: 'brand-2', version: DEMO_VERSION, rebuilt: true });
+ const created = state.brands[1];
+ expect(created).toMatchObject({
+ organization_id: 'org-1',
+ name: 'Brewline Coffee',
+ is_demo: true,
+ demo_version: DEMO_VERSION,
+ demo_built_at: NOW.toISOString(),
+ });
+ const ctx = { brandId: 'brand-2', now: NOW, rebuild: false, write: expect.any(Function) };
+ expect(build.mock.calls.map(([c]) => c)).toEqual([ctx, ctx]);
+ // Every module's tables, each module's in reverse: a new brand already
+ // holds what its triggers made.
+ const cleared = state.cleared.map(([table]) => table);
+ expect(cleared.sort()).toEqual(['a', 'b', 'c']);
+ expect(state.log.indexOf('delete b')).toBeLessThan(state.log.indexOf('delete a'));
+ // The real brand is untouched.
+ expect(state.brands[0]).toEqual({ id: 'real-1', organization_id: 'org-1', is_demo: false });
+ });
+
+ it('leaves a current demo alone', async () => {
+ state.brands.push(demo());
+ expect(await ensure()).toEqual({ brandId: 'demo-1', version: DEMO_VERSION, rebuilt: false });
+ expect(build).not.toHaveBeenCalled();
+ expect(state.cleared).toEqual([]);
+ });
+
+ it('rebuilds in place a demo of an older version, or one whose data grew old', async () => {
+ state.brands.push(demo({ demo_version: DEMO_VERSION - 1 }));
+ expect(await ensure()).toEqual({ brandId: 'demo-1', version: DEMO_VERSION, rebuilt: true });
+ expect(state.brands[1]).toMatchObject({
+ id: 'demo-1',
+ demo_version: DEMO_VERSION,
+ demo_built_at: NOW.toISOString(),
+ });
+
+ build.mockClear();
+ state.brands[1].demo_built_at = ago(DEMO_MAX_AGE_MS + 1);
+ expect((await ensure()).rebuilt).toBe(true);
+ expect(build).toHaveBeenCalledTimes(2);
+ expect(build.mock.calls[0][0]).toMatchObject({ brandId: 'demo-1', rebuild: true });
+ });
+
+ it('clears the tables of a module not rebuilt in place just before building it', async () => {
+ state.brands.push(demo({ demo_version: DEMO_VERSION - 1 }));
+ const logged = (name) =>
+ vi.fn(async () => {
+ state.log.push(`build ${name}`);
+ return { rows: 1 };
+ });
+ const staged = [
+ { name: 'one', tables: ['a', 'b'], build: logged('one') },
+ { name: 'two', tables: ['c'], build: logged('two') },
+ ];
+ await ensureDemoBrand({ organizationId: 'org-1', now: NOW, modules: staged });
+ expect(state.log).toEqual(['delete b', 'delete a', 'build one', 'delete c', 'build two']);
+ });
+
+ it("on a first build clears the other modules' tables while the first one is built", async () => {
+ const logged = (name) =>
+ vi.fn(async () => {
+ state.log.push(`build ${name}:start`);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ state.log.push(`build ${name}:end`);
+ });
+ const staged = [
+ { name: 'core', tables: ['a'], inPlace: true, build: logged('core') },
+ { name: 'two', tables: ['b', 'c'], build: logged('two') },
+ ];
+ await ensureDemoBrand({ organizationId: 'org-1', now: NOW, modules: staged });
+ expect(state.log.indexOf('delete b')).toBeLessThan(state.log.indexOf('build core:end'));
+ expect(state.log.indexOf('delete b')).toBeLessThan(state.log.indexOf('build two:start'));
+ // The in-place core clears nothing.
+ expect(state.cleared.map(([table]) => table)).toEqual(['c', 'b']);
+ });
+
+ it('builds an in-place module over a new brand without reading anything back', async () => {
+ const inPlace = {
+ name: 'core',
+ tables: ['items'],
+ inPlace: true,
+ async build({ write }) {
+ await write('items', [{ id: 'i1', brand_id: 'brand-2' }]);
+ },
+ };
+ await ensureDemoBrand({ organizationId: 'org-1', now: NOW, modules: [inPlace] });
+ expect(state.log).toEqual(['upsert items']);
+ expect(state.cleared).toEqual([]);
+ });
+
+ it('rebuilds an in-place module over its old rows, deleting only the ones not written again', async () => {
+ state.brands.push(demo({ demo_version: DEMO_VERSION - 1 }));
+ state.tables.items = [
+ { id: 'i1', brand_id: 'demo-1', v: 'old' },
+ { id: 'i2', brand_id: 'demo-1', v: 'old' },
+ { id: 'i9', brand_id: 'other', v: 'old' },
+ ];
+ const seen = [];
+ const inPlace = {
+ name: 'core',
+ tables: ['items'],
+ inPlace: true,
+ async build({ write }) {
+ // Mid-build, the old rows are still there to show.
+ seen.push(state.tables.items.length);
+ await write('items', [{ id: 'i1', brand_id: 'demo-1', v: 'new' }]);
+ return { items: 1 };
+ },
+ refresh: vi.fn(async () => {
+ state.log.push('refresh core');
+ }),
+ };
+ await ensureDemoBrand({ organizationId: 'org-1', now: NOW, modules: [inPlace] });
+
+ expect(seen).toEqual([3]);
+ expect(state.cleared).toEqual([]);
+ expect(state.tables.items).toEqual([
+ { id: 'i1', brand_id: 'demo-1', v: 'new' },
+ { id: 'i9', brand_id: 'other', v: 'old' },
+ ]);
+ // Written over, the leftover deleted, and only then the rollups rebuilt.
+ expect(state.log).toEqual(['upsert items', 'delete items', 'refresh core']);
+ expect(inPlace.refresh).toHaveBeenCalledWith(
+ expect.objectContaining({ brandId: 'demo-1', now: NOW, rebuild: true }),
+ );
+ });
+
+ it('keeps the demo hidden or shown as the organization left it', async () => {
+ state.brands.push(demo({ demo_version: 0, demo_hidden_at: ago(DAY_MS) }));
+ await ensure();
+ expect(state.brands[1].demo_hidden_at).toBe(ago(DAY_MS));
+ });
+
+ it('builds once for two visits at the same moment', async () => {
+ const [first, second] = await Promise.all([ensure(), ensure()]);
+ expect(first).toEqual(second);
+ expect(state.brands.filter((b) => b.is_demo)).toHaveLength(1);
+ expect(build).toHaveBeenCalledTimes(2);
+ });
+
+ it("reads another server's demo when its insert lost the race", async () => {
+ state.onRead = () => {
+ // Another server inserts the demo between this one's read and insert.
+ if (!state.brands.some((b) => b.is_demo)) state.brands.push(demo());
+ state.onRead = null;
+ };
+ const result = await ensure();
+ expect(result).toEqual({ brandId: 'demo-1', version: DEMO_VERSION, rebuilt: false });
+ expect(build).not.toHaveBeenCalled();
+ });
+
+ it("waits on another server's build, then answers with it", async () => {
+ vi.useFakeTimers({ now: NOW });
+ state.brands.push(demo({ demo_version: null, demo_built_at: ago(1000) }));
+ const pending = ensure();
+ // The other server finishes.
+ state.brands[1].demo_version = DEMO_VERSION;
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(await pending).toEqual({ brandId: 'demo-1', version: DEMO_VERSION, rebuilt: false });
+ expect(build).not.toHaveBeenCalled();
+ });
+
+ it('takes over a build left unfinished past its lease', async () => {
+ state.brands.push(demo({ demo_version: null, demo_built_at: ago(DEMO_BUILD_LEASE_MS + 1) }));
+ expect((await ensure()).rebuilt).toBe(true);
+ });
+
+ it('lets the next visit rebuild at once after a failed build', async () => {
+ state.brands.push(demo({ demo_version: 0 }));
+ build.mockRejectedValueOnce(new Error('insert failed'));
+ await expect(ensure()).rejects.toThrow('insert failed');
+ expect(state.brands[1]).toMatchObject({ demo_version: null, demo_built_at: null });
+ expect(demoState(state.brands[1], NOW)).toBe('stale');
+
+ expect((await ensure()).rebuilt).toBe(true);
+ expect(state.brands[1].demo_version).toBe(DEMO_VERSION);
+ });
+
+ it('throws when the brand cannot be created', async () => {
+ state.failInsert = { code: '42501', message: 'permission denied' };
+ await expect(ensure()).rejects.toThrow('demo brand insert: permission denied');
+ });
+});
+
+describe('the build order', () => {
+ it('builds the first module alone, the others together, each after the one it names', async () => {
+ const order = [];
+ // Each step ends when its gate opens: the order doesn't hang on timers.
+ const gates = {};
+ const step = (name) =>
+ vi.fn(async () => {
+ order.push(`${name}:start`);
+ await new Promise((resolve) => (gates[name] = resolve));
+ order.push(`${name}:end`);
+ return { rows: 1 };
+ });
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+ const open = async (name) => {
+ gates[name]();
+ await settle();
+ };
+ const staged = [
+ { name: 'core', tables: ['a'], build: step('core'), refresh: step('rollups') },
+ { name: 'slow', tables: ['b'], build: step('slow') },
+ { name: 'actions', tables: ['c'], build: step('actions') },
+ { name: 'drafts', tables: ['d'], after: 'actions', build: step('drafts') },
+ ];
+ const built = ensureDemoBrand({ organizationId: 'org-1', now: NOW, modules: staged });
+ await settle();
+ // The first module alone.
+ expect(order).toEqual(['core:start']);
+ await open('core');
+ // The others together, with the first one's rollups; drafts waits for actions.
+ expect(order.slice(1).sort()).toEqual([
+ 'actions:start',
+ 'core:end',
+ 'rollups:start',
+ 'slow:start',
+ ]);
+ await open('actions');
+ // Drafts starts once actions is done, without waiting for the slow one.
+ expect(order.slice(-2)).toEqual(['actions:end', 'drafts:start']);
+ await open('drafts');
+ await open('rollups');
+ await open('slow');
+ await built;
+ expect(order.at(-1)).toBe('slow:end');
+ });
+
+ it("fails the build when the first module's rollups fail", async () => {
+ const staged = [
+ {
+ name: 'core',
+ tables: ['a'],
+ build,
+ refresh: vi.fn().mockRejectedValue(new Error('rollups')),
+ },
+ { name: 'two', tables: ['b'], build },
+ ];
+ await expect(
+ ensureDemoBrand({ organizationId: 'org-1', now: NOW, modules: staged }),
+ ).rejects.toThrow('rollups');
+ expect(build).toHaveBeenCalledTimes(2);
+ });
+
+ it('fails the build when any module fails, after the others settle', async () => {
+ const fails = vi.fn(async () => {
+ throw new Error('boom');
+ });
+ const staged = [
+ { name: 'core', tables: ['a'], build },
+ { name: 'bad', tables: ['b'], build: fails },
+ { name: 'good', tables: ['c'], build },
+ ];
+ await expect(
+ ensureDemoBrand({ organizationId: 'org-1', now: NOW, modules: staged }),
+ ).rejects.toThrow('boom');
+ expect(build).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('demoState', () => {
+ it('reads fresh, building or stale from the version and when it was built', () => {
+ expect(demoState(demo(), NOW)).toBe('fresh');
+ // A newer server's demo is left to it.
+ expect(
+ demoState(demo({ demo_version: DEMO_VERSION + 1, demo_built_at: ago(30 * DAY_MS) }), NOW),
+ ).toBe('fresh');
+ expect(demoState(demo({ demo_version: DEMO_VERSION - 1 }), NOW)).toBe('stale');
+ expect(demoState(demo({ demo_built_at: ago(DEMO_MAX_AGE_MS) }), NOW)).toBe('stale');
+ expect(demoState(demo({ demo_version: null, demo_built_at: ago(60_000) }), NOW)).toBe(
+ 'building',
+ );
+ expect(demoState(demo({ demo_version: null, demo_built_at: null }), NOW)).toBe('stale');
+ });
+});
+
+describe('setDemoHidden', () => {
+ it("hides and shows the organization's demo brand, never another brand", async () => {
+ state.brands.push(demo(), demo({ id: 'demo-2', organization_id: 'org-2' }));
+ expect(await setDemoHidden({ organizationId: 'org-1', hidden: true, now: NOW })).toEqual({
+ brandId: 'demo-1',
+ hidden: true,
+ });
+ expect(state.brands.map((b) => b.demo_hidden_at ?? null)).toEqual([
+ null,
+ NOW.toISOString(),
+ null,
+ ]);
+
+ expect(await setDemoHidden({ organizationId: 'org-1', hidden: false })).toEqual({
+ brandId: 'demo-1',
+ hidden: false,
+ });
+ expect(state.brands[1].demo_hidden_at).toBeNull();
+ });
+
+ it('answers null when the organization has no demo brand', async () => {
+ expect(await setDemoHidden({ organizationId: 'org-1', hidden: true })).toBeNull();
+ });
+});
diff --git a/server/src/lib/demo/random.js b/server/src/lib/demo/random.js
new file mode 100644
index 000000000..8a3051dfb
--- /dev/null
+++ b/server/src/lib/demo/random.js
@@ -0,0 +1,70 @@
+import { createHash } from 'node:crypto';
+
+/**
+ * Determinism for the demo brand: the same sample every time it is built, so
+ * every organization sees the same demo and a test can pin its shape. Only
+ * the dates move, counted back from the moment it is built.
+ */
+
+/** A 32-bit seed from any string. */
+export function seedOf(text) {
+ const digest = createHash('sha256').update(String(text)).digest();
+ return digest.readUInt32LE(0);
+}
+
+/**
+ * A seeded generator (mulberry32): `next()` in [0, 1), and the few helpers
+ * the generator needs on top of it.
+ *
+ * @param {string} seed
+ */
+export function seededRandom(seed) {
+ let state = seedOf(seed);
+ const next = () => {
+ state = (state + 0x6d2b79f5) | 0;
+ let t = state;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+ return {
+ next,
+ /** True with probability `p`. */
+ chance: (p) => next() < p,
+ /** An integer in [min, max]. */
+ int: (min, max) => min + Math.floor(next() * (max - min + 1)),
+ /** One element of a non-empty list. */
+ pick: (list) => list[Math.floor(next() * list.length)],
+ /** A copy of the list in a seeded order. */
+ shuffle: (list) => {
+ const out = [...list];
+ for (let i = out.length - 1; i > 0; i--) {
+ const j = Math.floor(next() * (i + 1));
+ [out[i], out[j]] = [out[j], out[i]];
+ }
+ return out;
+ },
+ };
+}
+
+/**
+ * A stable id for one demo row: a UUID derived from the demo brand's id and
+ * the row's own key (`prompt:3`, `result:2:5:perplexity-web`). A rebuild
+ * writes the same ids again, so a link to a prompt or an answer of the demo
+ * survives it; two organizations' demos never share one.
+ *
+ * @param {string} brandId
+ * @param {string} key
+ */
+export function demoId(brandId, key) {
+ const hex = createHash('sha256').update(`demo:${brandId}:${key}`).digest('hex');
+ // Version 4 and RFC 4122 variant bits, so it reads as any generated uuid.
+ const variant = ((parseInt(hex[16], 16) & 0x3) | 0x8).toString(16);
+ return [
+ hex.slice(0, 8),
+ hex.slice(8, 12),
+ `4${hex.slice(13, 16)}`,
+ `${variant}${hex.slice(17, 20)}`,
+ hex.slice(20, 32),
+ ].join('-');
+}
diff --git a/server/src/lib/demo/write.js b/server/src/lib/demo/write.js
new file mode 100644
index 000000000..f20095cf1
--- /dev/null
+++ b/server/src/lib/demo/write.js
@@ -0,0 +1,250 @@
+/**
+ * How the demo's modules write their rows: in chunks, a few statements at a
+ * time, and, when a demo is rebuilt, over the rows already there instead of
+ * after clearing them.
+ *
+ * A rebuild keeps the old data on show until the new data is in: every row
+ * is written over the one with the same key (the generators' ids are
+ * deterministic, so a rebuild writes the same rows again with new dates), and
+ * only then are the rows this build didn't write deleted. Someone opening the
+ * demo mid-rebuild sees last week's numbers, never an empty page.
+ *
+ * Other modules write through it too: `insertChunks(db, table, rows)` in
+ * place of a loop of inserts, or, to be rebuilt in place, `ctx.write` (see
+ * DEMO_MODULES in index.js).
+ */
+
+/** Rows per statement. */
+export const CHUNK = 250;
+/** Statements one module has in flight at once. */
+export const CONCURRENCY = 4;
+/** Rows per page when reading which keys a table holds. */
+const PAGE = 1000;
+/** Keys per delete statement (they travel in the URL). */
+const DELETE_CHUNK = 100;
+
+/**
+ * A queue running at most `limit` tasks at once: `run(task)` resolves or
+ * rejects as the task does. After the first failure no queued task starts;
+ * each rejects with that first failure.
+ *
+ * @param {number} [limit]
+ * @returns {(task: () => Promise<any>) => Promise<any>}
+ */
+export function limiter(limit = CONCURRENCY) {
+ let active = 0;
+ let failure = null;
+ const queue = [];
+ const next = () => {
+ while (active < limit && queue.length > 0) {
+ const job = queue.shift();
+ if (failure) {
+ job.reject(failure);
+ continue;
+ }
+ active += 1;
+ Promise.resolve()
+ .then(job.task)
+ .then(job.resolve, (err) => {
+ failure ??= err;
+ job.reject(err);
+ })
+ .finally(() => {
+ active -= 1;
+ next();
+ });
+ }
+ };
+ return (task) =>
+ new Promise((resolve, reject) => {
+ queue.push({ task, resolve, reject });
+ next();
+ });
+}
+
+/**
+ * Like Promise.all, but settles every promise before it rejects: a failed
+ * write never leaves another one still running behind the error.
+ *
+ * @param {Promise<any>[]} promises
+ */
+export async function allSettledOrThrow(promises) {
+ const results = await Promise.allSettled(promises);
+ const failed = results.find((r) => r.status === 'rejected');
+ if (failed) throw failed.reason;
+ return results.map((r) => r.value);
+}
+
+function chunked(rows, size) {
+ const chunks = [];
+ for (let i = 0; i < rows.length; i += size) chunks.push(rows.slice(i, i + size));
+ return chunks;
+}
+
+/**
+ * Writes `rows` into `table`, `chunk` rows per statement, at most
+ * `concurrency` statements at once (or through a shared `run` queue). With
+ * `onConflict` (the key's columns), a row overwrites the one with the same
+ * key instead of failing on it.
+ *
+ * @param {object} db supabase client
+ * @param {string} table
+ * @param {object[]} rows
+ * @param {{ chunk?: number, concurrency?: number, run?: Function, onConflict?: string }} [options]
+ */
+export async function insertChunks(
+ db,
+ table,
+ rows,
+ { chunk = CHUNK, concurrency = CONCURRENCY, run = limiter(concurrency), onConflict } = {},
+) {
+ await allSettledOrThrow(
+ chunked(rows, chunk).map((part) =>
+ run(async () => {
+ const query = db.from(table);
+ const { error } = onConflict
+ ? await query.upsert(part, { onConflict })
+ : await query.insert(part);
+ if (error) throw new Error(`demo ${table} insert: ${error.message}`);
+ }),
+ ),
+ );
+}
+
+const keyOf = (row, columns) => JSON.stringify(columns.map((c) => row[c] ?? null));
+
+/** Every key of `table` under `column` in `values`, page by page. */
+async function readKeys(db, table, columns, column, values) {
+ const keys = [];
+ for (let from = 0; ; from += PAGE) {
+ let query = db.from(table).select(columns.join(', '));
+ query = Array.isArray(values) ? query.in(column, values) : query.eq(column, values);
+ // Ordered by the whole key, so no row falls between two pages.
+ for (const c of columns) query = query.order(c);
+ const { data, error } = await query.range(from, from + PAGE - 1);
+ if (error) throw new Error(`demo ${table} read: ${error.message}`);
+ keys.push(...(data ?? []));
+ if (!data || data.length < PAGE) return keys;
+ }
+}
+
+/** Deletes the rows with the given keys: by the last column, within the others. */
+async function deleteKeys(db, table, columns, rows, run) {
+ const groups = new Map();
+ const last = columns.at(-1);
+ for (const row of rows) {
+ const within = Object.fromEntries(columns.slice(0, -1).map((c) => [c, row[c]]));
+ const group = JSON.stringify(within);
+ if (!groups.has(group)) groups.set(group, { within, values: [] });
+ groups.get(group).values.push(row[last]);
+ }
+ const statements = [...groups.values()].flatMap(({ within, values }) =>
+ chunked(values, DELETE_CHUNK).map((part) => ({ within, part })),
+ );
+ await allSettledOrThrow(
+ statements.map(({ within, part }) =>
+ run(async () => {
+ let query = db.from(table).delete();
+ if (columns.length > 1) query = query.match(within);
+ const { error } = await query.in(last, part);
+ if (error) throw new Error(`demo ${table} prune: ${error.message}`);
+ }),
+ ),
+ );
+}
+
+/**
+ * A module's writer for one build of a demo brand.
+ *
+ * `write(table, rows)` writes over the rows with the same key (`keys[table]`,
+ * the table's key columns, 'id' unless named): on a rebuild the old rows,
+ * on a first build the rows a new brand's triggers may have made. On a
+ * rebuild it remembers what it wrote; `prune()` then deletes the brand's
+ * rows of those tables that this build didn't write, the last table's
+ * first. A table without a brand_id names how to find the brand's
+ * rows in `scopes[table]`: [its column, the written table that column points
+ * at], e.g. prompts: ['prompt_set_id', 'prompt_sets'].
+ *
+ * A table whose rows have no key of their own (an identity id the database
+ * gives, and no other unique columns) is written with
+ * `write(table, rows, { generated: true })`: inserted, then, on a rebuild,
+ * the brand's rows that were there before deleted at once. Nothing is empty
+ * meanwhile; for a moment both are there.
+ *
+ * @param {{ db: object, brandId: string, rebuild?: boolean,
+ * keys?: Record<string, string>, scopes?: Record<string, [string, string]>,
+ * concurrency?: number }} args
+ */
+export function demoWriter({
+ db,
+ brandId,
+ rebuild = false,
+ keys = {},
+ scopes = {},
+ concurrency = CONCURRENCY,
+}) {
+ const run = limiter(concurrency);
+ const columnsOf = (table) => (keys[table] ?? 'id').split(',').map((c) => c.trim());
+ /** Per table written, in the order first written: the keys written. */
+ const written = new Map();
+
+ return {
+ /**
+ * @param {string} table
+ * @param {object[]} rows
+ * @param {{ chunk?: number, generated?: boolean }} [options]
+ */
+ async write(table, rows, { chunk, generated = false } = {}) {
+ if (generated) {
+ const before = rebuild ? await readKeys(db, table, ['id'], 'brand_id', brandId) : [];
+ await insertChunks(db, table, rows, { chunk, run });
+ if (before.length > 0) await deleteKeys(db, table, ['id'], before, run);
+ return;
+ }
+ const columns = columnsOf(table);
+ if (rebuild) {
+ if (!written.has(table)) written.set(table, new Set());
+ const seen = written.get(table);
+ for (const row of rows) seen.add(keyOf(row, columns));
+ }
+ return insertChunks(db, table, rows, { chunk, run, onConflict: columns.join(',') });
+ },
+
+ /** On a rebuild: deletes the rows this build didn't write. Returns how many, by table. */
+ async prune() {
+ if (!rebuild) return {};
+ const tables = [...written.keys()];
+ const existing = new Map();
+ const read = async (table) => {
+ const columns = columnsOf(table);
+ const scope = scopes[table];
+ let rows;
+ if (scope) {
+ const [column, parent] = scope;
+ const parentIds = (existing.get(parent) ?? []).map((r) => r.id);
+ rows =
+ parentIds.length === 0
+ ? []
+ : await readKeys(db, table, [...new Set([...columns, column])], column, parentIds);
+ } else {
+ rows = await readKeys(db, table, columns, 'brand_id', brandId);
+ }
+ existing.set(table, rows);
+ };
+ // The brand's own tables side by side, then those found through them.
+ await allSettledOrThrow(tables.filter((t) => !scopes[t]).map((t) => run(() => read(t))));
+ for (const table of tables.filter((t) => scopes[t])) await read(table);
+
+ const pruned = {};
+ for (const table of [...tables].reverse()) {
+ const columns = columnsOf(table);
+ const keep = written.get(table);
+ const stale = existing.get(table).filter((row) => !keep.has(keyOf(row, columns)));
+ if (stale.length === 0) continue;
+ await deleteKeys(db, table, columns, stale, run);
+ pruned[table] = stale.length;
+ }
+ return pruned;
+ },
+ };
+}
diff --git a/server/src/lib/demo/write.test.js b/server/src/lib/demo/write.test.js
new file mode 100644
index 000000000..9dccd4c41
--- /dev/null
+++ b/server/src/lib/demo/write.test.js
@@ -0,0 +1,320 @@
+import { describe, expect, it } from 'vitest';
+import { allSettledOrThrow, demoWriter, insertChunks, limiter } from './write.js';
+
+/**
+ * How the demo writes its rows: a few statements at a time, and on a
+ * rebuild over the old rows, deleting only the ones not written again.
+ */
+
+const tick = (ms = 1) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * An in-memory stand-in for the admin client: tables of rows, the
+ * statements it ran, and how many were in flight at most.
+ */
+function fakeDb(tables = {}, { failOn = null } = {}) {
+ const db = { tables, statements: [], inFlight: 0, maxInFlight: 0 };
+ const matches = (row, filters) =>
+ filters.every(([op, column, value]) =>
+ op === 'in' ? value.includes(row[column]) : row[column] === value,
+ );
+ db.from = (table) => {
+ const q = { table, op: 'select', filters: [], order: [], range: null };
+ const run = async () => {
+ db.inFlight += 1;
+ db.maxInFlight = Math.max(db.maxInFlight, db.inFlight);
+ await tick();
+ db.inFlight -= 1;
+ db.statements.push(q);
+ if (failOn && failOn(q)) return { data: null, error: { message: 'boom' } };
+ const rows = (tables[table] ??= []);
+ if (q.op === 'insert') {
+ rows.push(...q.payload.map((r) => ({ ...r })));
+ return { data: null, error: null };
+ }
+ if (q.op === 'upsert') {
+ const columns = q.onConflict.split(',');
+ for (const row of q.payload) {
+ const same = rows.find((r) => columns.every((c) => r[c] === row[c]));
+ if (same) Object.assign(same, row);
+ else rows.push({ ...row });
+ }
+ return { data: null, error: null };
+ }
+ const hit = rows.filter((r) => matches(r, q.filters));
+ if (q.op === 'delete') {
+ tables[table] = rows.filter((r) => !hit.includes(r));
+ return { data: null, error: null };
+ }
+ const sorted = [...hit].sort((a, b) => {
+ for (const c of q.order) {
+ if (a[c] !== b[c]) return String(a[c]) < String(b[c]) ? -1 : 1;
+ }
+ return 0;
+ });
+ const [from, to] = q.range ?? [0, sorted.length];
+ const columns = q.columns.split(',').map((c) => c.trim());
+ return {
+ data: sorted
+ .slice(from, to + 1)
+ .map((r) => Object.fromEntries(columns.map((c) => [c, r[c]]))),
+ error: null,
+ };
+ };
+ const chain = {
+ insert: (payload) => ((q.op = 'insert'), (q.payload = payload), chain),
+ upsert: (payload, { onConflict }) => (
+ (q.op = 'upsert'),
+ (q.payload = payload),
+ (q.onConflict = onConflict),
+ chain
+ ),
+ select: (columns) => ((q.columns = columns), chain),
+ delete: () => ((q.op = 'delete'), chain),
+ eq: (column, value) => (q.filters.push(['eq', column, value]), chain),
+ in: (column, values) => (q.filters.push(['in', column, values]), chain),
+ match: (obj) => {
+ for (const [column, value] of Object.entries(obj)) q.filters.push(['eq', column, value]);
+ return chain;
+ },
+ order: (column) => (q.order.push(column), chain),
+ range: (from, to) => ((q.range = [from, to]), chain),
+ then: (resolve, reject) => run().then(resolve, reject),
+ };
+ return chain;
+ };
+ return db;
+}
+
+const rowsOf = (n, make) => Array.from({ length: n }, (_, i) => make(i));
+
+describe('limiter', () => {
+ it('runs at most `limit` tasks at once, each resolving as its task does', async () => {
+ const run = limiter(2);
+ let active = 0;
+ let most = 0;
+ const task = (value) => async () => {
+ active += 1;
+ most = Math.max(most, active);
+ await tick(2);
+ active -= 1;
+ return value;
+ };
+ expect(await Promise.all([1, 2, 3, 4, 5].map((v) => run(task(v))))).toEqual([1, 2, 3, 4, 5]);
+ expect(most).toBe(2);
+ });
+
+ it('starts nothing after a failure; the queued tasks reject with it', async () => {
+ const run = limiter(1);
+ const started = [];
+ const task = (name, fail) => async () => {
+ started.push(name);
+ await tick();
+ if (fail) throw new Error(`${name} failed`);
+ return name;
+ };
+ const results = await Promise.allSettled([
+ run(task('a')),
+ run(task('b', true)),
+ run(task('c')),
+ run(task('d')),
+ ]);
+ expect(started).toEqual(['a', 'b']);
+ expect(results.map((r) => r.value ?? r.reason.message)).toEqual([
+ 'a',
+ 'b failed',
+ 'b failed',
+ 'b failed',
+ ]);
+ });
+});
+
+describe('allSettledOrThrow', () => {
+ it('waits for every write to settle before it throws the failure', async () => {
+ let slowDone = false;
+ const slow = tick(10).then(() => {
+ slowDone = true;
+ });
+ await expect(allSettledOrThrow([Promise.reject(new Error('boom')), slow])).rejects.toThrow(
+ 'boom',
+ );
+ expect(slowDone).toBe(true);
+ expect(await allSettledOrThrow([Promise.resolve(1), 2])).toEqual([1, 2]);
+ });
+});
+
+describe('insertChunks', () => {
+ it('writes every row, a chunk per statement, a few statements at once', async () => {
+ const db = fakeDb();
+ const rows = rowsOf(1000, (i) => ({ id: `r${i}` }));
+ await insertChunks(db, 'items', rows, { chunk: 100, concurrency: 4 });
+ expect(db.tables.items).toHaveLength(1000);
+ expect(db.statements).toHaveLength(10);
+ expect(db.statements.every((s) => s.op === 'insert' && s.payload.length === 100)).toBe(true);
+ expect(db.maxInFlight).toBe(4);
+ });
+
+ it('writes over the rows with the same key when given one', async () => {
+ const db = fakeDb({ items: [{ a: 1, b: 2, v: 'old' }] });
+ await insertChunks(db, 'items', [{ a: 1, b: 2, v: 'new' }], { onConflict: 'a,b' });
+ expect(db.tables.items).toEqual([{ a: 1, b: 2, v: 'new' }]);
+ });
+
+ it("fails with the table's name, after the statements under way settle", async () => {
+ const db = fakeDb({}, { failOn: (q) => q.payload?.[0]?.id === 'r100' });
+ const rows = rowsOf(500, (i) => ({ id: `r${i}` }));
+ await expect(insertChunks(db, 'items', rows, { chunk: 100, concurrency: 2 })).rejects.toThrow(
+ 'demo items insert: boom',
+ );
+ // The chunk beside the failed one finished; none started after it.
+ expect(db.inFlight).toBe(0);
+ expect(db.statements.length).toBeLessThan(5);
+ });
+});
+
+describe('demoWriter', () => {
+ it("writes over what a new brand's triggers made on a first build, and prunes nothing", async () => {
+ const db = fakeDb({ steps: [{ brand_id: 'b1', step: 'visibility', done: false }] });
+ const writer = demoWriter({ db, brandId: 'b1', keys: { steps: 'brand_id,step' } });
+ await writer.write('steps', [
+ { brand_id: 'b1', step: 'visibility', done: true },
+ { brand_id: 'b1', step: 'answers', done: true },
+ ]);
+ expect(await writer.prune()).toEqual({});
+ expect(db.statements.map((s) => s.op)).toEqual(['upsert']);
+ expect(db.tables.steps).toHaveLength(2);
+ });
+
+ it('shares one queue across tables written side by side', async () => {
+ const db = fakeDb();
+ const writer = demoWriter({ db, brandId: 'b1', concurrency: 3 });
+ await Promise.all(
+ ['a', 'b', 'c', 'd'].map((t) =>
+ writer.write(
+ t,
+ rowsOf(500, (i) => ({ id: `${t}${i}` })),
+ { chunk: 100 },
+ ),
+ ),
+ );
+ expect(db.statements).toHaveLength(20);
+ expect(db.maxInFlight).toBe(3);
+ });
+
+ it('on a rebuild writes over the old rows, then deletes only the ones not written again', async () => {
+ const db = fakeDb({
+ results: [
+ { id: 'r1', brand_id: 'b1', v: 'old' },
+ { id: 'r2', brand_id: 'b1', v: 'old' },
+ { id: 'r3', brand_id: 'b1', v: 'old' }, // no longer built
+ { id: 'r9', brand_id: 'b2', v: 'other brand' },
+ ],
+ citations: [
+ { result_id: 'r1', position: 1, brand_id: 'b1', v: 'old' },
+ { result_id: 'r1', position: 2, brand_id: 'b1', v: 'old' }, // no longer built
+ { result_id: 'r2', position: 1, brand_id: 'b1', v: 'old' },
+ { result_id: 'r3', position: 1, brand_id: 'b1', v: 'old' }, // its answer is gone
+ { result_id: 'r9', position: 1, brand_id: 'b2', v: 'other brand' },
+ ],
+ });
+ const writer = demoWriter({
+ db,
+ brandId: 'b1',
+ rebuild: true,
+ keys: { citations: 'result_id,position' },
+ });
+ await writer.write('results', [
+ { id: 'r1', brand_id: 'b1', v: 'new' },
+ { id: 'r2', brand_id: 'b1', v: 'new' },
+ ]);
+ await writer.write('citations', [
+ { result_id: 'r1', position: 1, brand_id: 'b1', v: 'new' },
+ { result_id: 'r2', position: 1, brand_id: 'b1', v: 'new' },
+ ]);
+ // Written over, nothing deleted yet: the old rows stay on show.
+ expect(db.statements.map((s) => s.op)).toEqual(['upsert', 'upsert']);
+ expect(db.statements[1].onConflict).toBe('result_id,position');
+ expect(db.tables.results).toHaveLength(4);
+
+ expect(await writer.prune()).toEqual({ citations: 2, results: 1 });
+ expect(db.tables.results).toEqual([
+ { id: 'r1', brand_id: 'b1', v: 'new' },
+ { id: 'r2', brand_id: 'b1', v: 'new' },
+ { id: 'r9', brand_id: 'b2', v: 'other brand' },
+ ]);
+ expect(db.tables.citations.map((c) => `${c.result_id}:${c.position}:${c.v}`)).toEqual([
+ 'r1:1:new',
+ 'r2:1:new',
+ 'r9:1:other brand',
+ ]);
+ // The children before the parents.
+ const deletes = db.statements.filter((s) => s.op === 'delete').map((s) => s.table);
+ expect(deletes).toEqual(['citations', 'citations', 'results']);
+ });
+
+ it("finds a table's rows through the table it points at when it has no brand_id", async () => {
+ const db = fakeDb({
+ sets: [
+ { id: 's1', brand_id: 'b1' },
+ { id: 's9', brand_id: 'b2' },
+ ],
+ prompts: [
+ { id: 'p1', set_id: 's1' },
+ { id: 'p2', set_id: 's1' }, // no longer built
+ { id: 'p9', set_id: 's9' }, // another brand's
+ ],
+ });
+ const writer = demoWriter({
+ db,
+ brandId: 'b1',
+ rebuild: true,
+ scopes: { prompts: ['set_id', 'sets'] },
+ });
+ await writer.write('sets', [{ id: 's1', brand_id: 'b1' }]);
+ await writer.write('prompts', [{ id: 'p1', set_id: 's1' }]);
+ expect(await writer.prune()).toEqual({ prompts: 1 });
+ expect(db.tables.prompts.map((p) => p.id)).toEqual(['p1', 'p9']);
+ });
+
+ it('replaces the rows of a table whose ids the database gives, old ones after the new', async () => {
+ const db = fakeDb({
+ events: [
+ { id: 1, brand_id: 'b1', v: 'old' },
+ { id: 2, brand_id: 'b1', v: 'old' },
+ { id: 3, brand_id: 'b2', v: 'other brand' },
+ ],
+ });
+ const writer = demoWriter({ db, brandId: 'b1', rebuild: true });
+ await writer.write('events', [{ brand_id: 'b1', v: 'new' }], { generated: true });
+ expect(db.statements.map((s) => `${s.op} ${s.table}`)).toEqual([
+ 'select events',
+ 'insert events',
+ 'delete events',
+ ]);
+ expect(db.tables.events.map((e) => e.v)).toEqual(['other brand', 'new']);
+ // Nothing left for the prune.
+ expect(await writer.prune()).toEqual({});
+ });
+
+ it('only inserts such rows on a first build', async () => {
+ const db = fakeDb();
+ const writer = demoWriter({ db, brandId: 'b1' });
+ await writer.write('events', [{ brand_id: 'b1', v: 'new' }], { generated: true });
+ expect(db.statements.map((s) => s.op)).toEqual(['insert']);
+ });
+
+ it('reads a large table page by page', async () => {
+ const old = rowsOf(2500, (i) => ({ id: `r${String(i).padStart(4, '0')}`, brand_id: 'b1' }));
+ const db = fakeDb({ results: old.map((r) => ({ ...r })) });
+ const writer = demoWriter({ db, brandId: 'b1', rebuild: true });
+ await writer.write('results', old.slice(0, 2000));
+ expect(await writer.prune()).toEqual({ results: 500 });
+ const reads = db.statements.filter((s) => s.op === 'select');
+ expect(reads.map((s) => s.range)).toEqual([
+ [0, 999],
+ [1000, 1999],
+ [2000, 2999],
+ ]);
+ expect(db.tables.results).toHaveLength(2000);
+ });
+});
diff --git a/server/src/lib/ga-sync.js b/server/src/lib/ga-sync.js
index 4adf247e0..29c615fec 100644
--- a/server/src/lib/ga-sync.js
+++ b/server/src/lib/ga-sync.js
@@ -588,6 +588,8 @@ export async function runGaSync({ organizationId, brandId, aiHistory = false } =
.from('brands')
.select('id, organization_id, ga_property_id')
.eq('is_active', true)
+ // A demo brand's figures (00380) are sample data, never synced.
+ .eq('is_demo', false)
.not('ga_property_id', 'is', null)
.in('organization_id', connectedOrgIds);
if (brandId) brandQuery = brandQuery.eq('id', brandId);
diff --git a/server/src/lib/ga-sync.test.js b/server/src/lib/ga-sync.test.js
index a865451a7..ab1b5e918 100644
--- a/server/src/lib/ga-sync.test.js
+++ b/server/src/lib/ga-sync.test.js
@@ -624,6 +624,8 @@ describe('runGaSync', () => {
expect(activeOrgFilter).toHaveBeenCalledWith(['paying', 'lapsed']);
const brands = calls.find((call) => call.table === 'brands');
expect(brands.filters).toContainEqual(['in', 'organization_id', ['paying']]);
+ // Never a demo brand (00380).
+ expect(brands.filters).toContainEqual(['eq', 'is_demo', false]);
});
it('reads no brand when no connected organization is on a plan', async () => {
diff --git a/server/src/lib/gsc-sync.js b/server/src/lib/gsc-sync.js
index ba71f9458..3aa31ecbd 100644
--- a/server/src/lib/gsc-sync.js
+++ b/server/src/lib/gsc-sync.js
@@ -236,6 +236,8 @@ export async function runGscSync({ organizationId, brandId } = {}) {
'id, organization_id, gsc_property, gsc_pages_backfilled_property, gsc_pages_backfill_from',
)
.eq('is_active', true)
+ // A demo brand's figures (00380) are sample data, never synced.
+ .eq('is_demo', false)
.not('gsc_property', 'is', null)
.in('organization_id', connectedOrgIds);
if (brandId) brandQuery = brandQuery.eq('id', brandId);
diff --git a/server/src/lib/gsc-sync.test.js b/server/src/lib/gsc-sync.test.js
index 8d8dac7be..e0df12be6 100644
--- a/server/src/lib/gsc-sync.test.js
+++ b/server/src/lib/gsc-sync.test.js
@@ -272,6 +272,8 @@ describe('runGscSync', () => {
expect(activeOrgFilter).toHaveBeenCalledWith(['paying', 'lapsed']);
const brands = calls.find((call) => call.table === 'brands');
expect(brands.filters).toContainEqual(['in', 'organization_id', ['paying']]);
+ // Never a demo brand (00380).
+ expect(brands.filters).toContainEqual(['eq', 'is_demo', false]);
});
it('reads no brand when no connected organization is on a plan', async () => {
diff --git a/server/src/lib/insights-rollups.js b/server/src/lib/insights-rollups.js
index 6f972cbd8..aff571870 100644
--- a/server/src/lib/insights-rollups.js
+++ b/server/src/lib/insights-rollups.js
@@ -181,7 +181,12 @@ async function drainRebuildQueue() {
* finishing in half a minute instead of five seconds is the right trade.
*/
export async function sweepInsightsRollups({ days = SWEEP_DAYS } = {}) {
- const { data: brands, error } = await supabaseAdmin.from('brands').select('id');
+ // Not a demo brand's (00380): the demo generator refreshes its rollups as
+ // it writes its sample answers, and nothing else writes any.
+ const { data: brands, error } = await supabaseAdmin
+ .from('brands')
+ .select('id')
+ .eq('is_demo', false);
if (error) {
logger.error({ err: error }, '[insights-rollups] sweep could not list brands');
return { refreshed: 0, failed: 0 };
diff --git a/server/src/lib/insights-rollups.test.js b/server/src/lib/insights-rollups.test.js
index f14ec4f77..6550b2cb2 100644
--- a/server/src/lib/insights-rollups.test.js
+++ b/server/src/lib/insights-rollups.test.js
@@ -43,12 +43,20 @@ import {
*/
let brandRows = [];
let brandsError = null;
+const brandFilters = [];
let queueRows = [];
const queueDeletes = [];
function tables() {
from.mockImplementation((table) => {
if (table === 'brands') {
- return { select: () => Promise.resolve({ data: brandRows, error: brandsError }) };
+ return {
+ select: () => ({
+ eq: (...a) => {
+ brandFilters.push(a);
+ return Promise.resolve({ data: brandRows, error: brandsError });
+ },
+ }),
+ };
}
const filters = [];
const chain = {
@@ -171,6 +179,13 @@ describe('sweepInsightsRollups', () => {
brandsError = error;
}
+ it('leaves out demo brands (00380), whose rollups their generator refreshes', async () => {
+ brandsList([]);
+ brandFilters.length = 0;
+ await sweepInsightsRollups();
+ expect(brandFilters).toEqual([['is_demo', false]]);
+ });
+
it('refreshes the trailing window for every brand, today included', async () => {
brandsList([{ id: 'a' }, { id: 'b' }]);
rpc.mockResolvedValue({ error: null });
diff --git a/server/src/lib/mentions-rollups.js b/server/src/lib/mentions-rollups.js
index 55ab619f5..10f267c3d 100644
--- a/server/src/lib/mentions-rollups.js
+++ b/server/src/lib/mentions-rollups.js
@@ -24,19 +24,19 @@ import { dayChunks, resultDayBound } from './citations-rollups.js';
* sentiment correction (00160) refreshes only the rollups: the rollups in
* one, then the terms a day per call, since they read each answer's text
* and a few busy days of the largest brand would near the service role's
- * statement timeout (MENTION_HISTORY_CHUNK_DAYS). Resolves to true when
- * every call succeeds, false at the first that fails; never throws.
+ * statement timeout (MENTION_HISTORY_CHUNK_DAYS). A small brand may pass a
+ * longer `termDays` (the demo brand refreshes its month in one call), and
+ * `together` to refresh the rollups beside the terms rather than before
+ * them (each takes its own lock and writes its own tables). Resolves to true
+ * when every call succeeds, false at the first that fails; never throws.
*/
-export async function refreshMentionsDaily(brandId, dayFrom, dayTo) {
- const calls = [
- ['refresh_mentions_daily', dayFrom, dayTo],
- ...dayChunks(dayFrom, dayTo, MENTION_HISTORY_CHUNK_DAYS).map(([from, to]) => [
- 'refresh_mention_terms',
- from,
- to,
- ]),
- ];
- for (const [fn, from, to] of calls) {
+export async function refreshMentionsDaily(
+ brandId,
+ dayFrom,
+ dayTo,
+ { termDays = MENTION_HISTORY_CHUNK_DAYS, together = false } = {},
+) {
+ const call = async ([fn, from, to]) => {
const { error } = await supabaseAdmin.rpc(fn, {
p_brand_id: brandId,
p_day_from: from,
@@ -49,8 +49,23 @@ export async function refreshMentionsDaily(brandId, dayFrom, dayTo) {
);
return false;
}
- }
- return true;
+ return true;
+ };
+ const inTurn = async (calls) => {
+ for (const args of calls) {
+ if (!(await call(args))) return false;
+ }
+ return true;
+ };
+ const rollups = [['refresh_mentions_daily', dayFrom, dayTo]];
+ const terms = dayChunks(dayFrom, dayTo, termDays).map(([from, to]) => [
+ 'refresh_mention_terms',
+ from,
+ to,
+ ]);
+ if (!together) return inTurn([...rollups, ...terms]);
+ const done = await Promise.all([inTurn(rollups), inTurn(terms)]);
+ return done.every(Boolean);
}
/** The Perception windows precomputed for the tab's default view (00241). */
diff --git a/server/src/lib/mentions-rollups.test.js b/server/src/lib/mentions-rollups.test.js
index f1407ef3c..fda4369a8 100644
--- a/server/src/lib/mentions-rollups.test.js
+++ b/server/src/lib/mentions-rollups.test.js
@@ -53,6 +53,48 @@ describe('refreshMentionsDaily', () => {
]);
});
+ it('refreshes the terms in longer chunks when asked (a small brand)', async () => {
+ rpc.mockResolvedValue({ error: null });
+ await expect(
+ refreshMentionsDaily('brand-1', '2026-10-01', '2026-10-17', { termDays: 31 }),
+ ).resolves.toBe(true);
+ const args = (from, to) => ({ p_brand_id: 'brand-1', p_day_from: from, p_day_to: to });
+ expect(rpc.mock.calls).toEqual([
+ ['refresh_mentions_daily', args('2026-10-01', '2026-10-17')],
+ ['refresh_mention_terms', args('2026-10-01', '2026-10-17')],
+ ]);
+ });
+
+ it('refreshes the rollups beside the terms when asked', async () => {
+ const started = [];
+ let finishRollups = () => {};
+ rpc.mockImplementation((fn) => {
+ started.push(fn);
+ if (fn === 'refresh_mentions_daily') {
+ return new Promise((resolve) => (finishRollups = () => resolve({ error: null })));
+ }
+ return Promise.resolve({ error: null });
+ });
+ const done = refreshMentionsDaily('brand-1', '2026-10-01', '2026-10-17', {
+ termDays: 31,
+ together: true,
+ });
+ await Promise.resolve();
+ // The terms started without waiting for the rollups.
+ expect(started).toEqual(['refresh_mentions_daily', 'refresh_mention_terms']);
+ finishRollups();
+ await expect(done).resolves.toBe(true);
+
+ rpc
+ .mockReset()
+ .mockImplementation(async (fn) =>
+ fn === 'refresh_mention_terms' ? { error: { message: 'x' } } : { error: null },
+ );
+ await expect(
+ refreshMentionsDaily('brand-1', '2026-10-17', '2026-10-17', { together: true }),
+ ).resolves.toBe(false);
+ });
+
// Derived state: a failed refresh costs freshness until the next sweep and
// must never throw into a tracking run's finalize path.
it('reports failure without throwing', async () => {
diff --git a/server/src/lib/page-opportunities.js b/server/src/lib/page-opportunities.js
index 7cb5e81c1..be8175737 100644
--- a/server/src/lib/page-opportunities.js
+++ b/server/src/lib/page-opportunities.js
@@ -338,6 +338,8 @@ export async function runPageOpportunityDetection({ organizationId } = {}) {
.from('brands')
.select('id, organization_id')
.eq('is_active', true)
+ // A demo brand's pages (00380) are sample data: nothing is found for it.
+ .eq('is_demo', false)
.not('ga_property_id', 'is', null);
if (organizationId) brandQuery = brandQuery.eq('organization_id', organizationId);
const { data: rows, error } = await brandQuery;
diff --git a/server/src/lib/page-opportunities.test.js b/server/src/lib/page-opportunities.test.js
index 80f9e4735..c9083d77a 100644
--- a/server/src/lib/page-opportunities.test.js
+++ b/server/src/lib/page-opportunities.test.js
@@ -453,14 +453,16 @@ describe('detectPageOpportunitiesInWindow', () => {
* leaves its brands out: nothing new is found for it.
*/
describe('runPageOpportunityDetection', () => {
+ const brandFilters = [];
const brandsRead = (rows) => {
const tables = [];
+ brandFilters.length = 0;
db.rpc.mockReset();
db.from.mockReset().mockImplementation((table) => {
tables.push(table);
const chain = {
select: () => chain,
- eq: () => chain,
+ eq: (column, value) => (brandFilters.push([column, value]), chain),
not: () => chain,
then: (resolve) => resolve({ data: table === 'brands' ? rows : [], error: null }),
};
@@ -497,5 +499,7 @@ describe('runPageOpportunityDetection', () => {
expect(result.scanned).toBe(1);
expect(result.results.map((r) => r.brandId)).toEqual(['b-paying']);
+ // Never a demo brand (00380).
+ expect(brandFilters).toContainEqual(['is_demo', false]);
});
});
diff --git a/server/src/lib/prompt-demand.js b/server/src/lib/prompt-demand.js
index 338013ba4..73e13d610 100644
--- a/server/src/lib/prompt-demand.js
+++ b/server/src/lib/prompt-demand.js
@@ -920,7 +920,9 @@ export async function sweepPromptDemand({
const { data: brands, error } = await supabaseAdmin
.from('brands')
.select('id, organization_id, gsc_property')
- .eq('is_active', true);
+ .eq('is_active', true)
+ // A demo brand's prompts (00380) are sample data: nothing is read or paid for them.
+ .eq('is_demo', false);
if (error) throw new Error(`brands read failed: ${error.message}`);
const isActive = await activeOrgFilter((brands ?? []).map((b) => b.organization_id));
const active = (brands ?? []).filter((b) => isActive(b.organization_id));
diff --git a/server/src/lib/prompt-demand.test.js b/server/src/lib/prompt-demand.test.js
index a597b279c..379d42d87 100644
--- a/server/src/lib/prompt-demand.test.js
+++ b/server/src/lib/prompt-demand.test.js
@@ -388,7 +388,13 @@ const volume = (promptId, googleVolumes, extra = {}) => ({
beforeEach(() => {
tables = {
brands: [
- { id: 'b1', organization_id: 'o1', gsc_property: 'sc-domain:ansvisor.com', is_active: true },
+ {
+ id: 'b1',
+ organization_id: 'o1',
+ gsc_property: 'sc-domain:ansvisor.com',
+ is_active: true,
+ is_demo: false,
+ },
],
prompts: [
prompt('p1', 'b1', 'What is the best AI search monitoring tool?'),
@@ -889,6 +895,22 @@ describe('sweepPromptDemand', () => {
});
});
+describe('sweepPromptDemand and the demo brand', () => {
+ // 00380: its prompts are sample data, and DataForSEO is paid for.
+ it("never reads, sets or pays for a demo brand's prompts", async () => {
+ vi.stubEnv('DEMAND_SIGNALS', 'true');
+ tables.brands[0].is_demo = true;
+ tables.prompt_volumes = [volume('p1', { 'ai search monitoring': 1900 })];
+
+ const outcome = await sweepPromptDemand({ now: NOW });
+
+ expect(outcome).toMatchObject({ brands: 0, written: 0, posted: 0 });
+ expect(gscReads()).toEqual([]);
+ expect(postTasks).not.toHaveBeenCalled();
+ expect(writes).toEqual([]);
+ });
+});
+
// ─── Setting the tasks: nothing paid for twice, nothing paid for lost ───────
describe('setting the paid tasks', () => {
@@ -1041,6 +1063,7 @@ describe("the night's brands", () => {
organization_id: 'o1',
gsc_property: `sc-domain:${id}.example`,
is_active: true,
+ is_demo: false,
}));
tables.prompts = [
prompt('p1', 'b1', 'ai search monitoring tool'),
diff --git a/server/src/lib/pulse/engine.js b/server/src/lib/pulse/engine.js
index f4af37111..ee829c205 100644
--- a/server/src/lib/pulse/engine.js
+++ b/server/src/lib/pulse/engine.js
@@ -150,10 +150,12 @@ export async function generatePulseForBrand(brandId, { pulseDate: pulseDateOverr
const { data: brand } = await supabaseAdmin
.from('brands')
- .select('id, name, organization_id, is_active')
+ .select('id, name, organization_id, is_active, is_demo')
.eq('id', brandId)
.single();
if (!brand?.is_active) return { skipped: 'brand_inactive' };
+ // A demo brand (00380) is sample data: nobody is mailed about it.
+ if (brand.is_demo) return { skipped: 'demo_brand' };
// Hard requirement: never generate for orgs without an active or
// trialing subscription (self-host always passes — isSubscriptionActive
diff --git a/server/src/lib/pulse/engine.test.js b/server/src/lib/pulse/engine.test.js
index e3279d248..4b2e421fe 100644
--- a/server/src/lib/pulse/engine.test.js
+++ b/server/src/lib/pulse/engine.test.js
@@ -5,7 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const from = vi.fn();
vi.mock('../../config/supabase.js', () => ({ default: { from: (...a) => from(...a) } }));
-import { pulseWindowKey, runPulseCatchUp } from './engine.js';
+import { generatePulseForBrand, pulseWindowKey, runPulseCatchUp } from './engine.js';
/**
* Pulse window dedupe (#701).
@@ -130,3 +130,27 @@ describe('runPulseCatchUp', () => {
expect(queriedTables).toContain('sent_pulses');
});
});
+
+/** A demo brand (00380) is sample data: no pulse is ever written or mailed for it. */
+describe('generatePulseForBrand', () => {
+ beforeEach(() => from.mockReset());
+
+ it('skips a demo brand before reading anything else', async () => {
+ const queried = [];
+ from.mockImplementation((table) => {
+ queried.push(table);
+ const builder = {
+ select: () => builder,
+ eq: () => builder,
+ single: async () => ({
+ data: { id: 'demo', name: 'Brewline Coffee', is_active: true, is_demo: true },
+ error: null,
+ }),
+ };
+ return builder;
+ });
+
+ expect(await generatePulseForBrand('demo')).toEqual({ skipped: 'demo_brand' });
+ expect(queried).toEqual(['brands']);
+ });
+});
diff --git a/server/src/lib/tracking-brands.js b/server/src/lib/tracking-brands.js
new file mode 100644
index 000000000..2c9b097fb
--- /dev/null
+++ b/server/src/lib/tracking-brands.js
@@ -0,0 +1,16 @@
+import supabaseAdmin from '../config/supabase.js';
+
+/**
+ * The brands the nightly run looks at: the active ones (a paused brand,
+ * is_active = false, is the person's own stop: it should not spend Cloro or
+ * LLM credits daily), never a demo brand (00380), whose answers are the
+ * sample the demo generator writes. Their plan and prompts are checked
+ * after, brand by brand. Returns the query's own { data, error }.
+ */
+export function listDailyTrackingBrands() {
+ return supabaseAdmin
+ .from('brands')
+ .select('id, organization_id')
+ .eq('is_active', true)
+ .eq('is_demo', false);
+}
diff --git a/server/src/lib/tracking-brands.test.js b/server/src/lib/tracking-brands.test.js
new file mode 100644
index 000000000..e83c6d9fc
--- /dev/null
+++ b/server/src/lib/tracking-brands.test.js
@@ -0,0 +1,34 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const filters = [];
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ const chain = {
+ select: (columns) => {
+ filters.push(['select', table, columns]);
+ return chain;
+ },
+ eq: (column, value) => {
+ filters.push(['eq', column, value]);
+ return chain;
+ },
+ then: (resolve) => resolve({ data: [], error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+
+const { listDailyTrackingBrands } = await import('./tracking-brands.js');
+
+describe('listDailyTrackingBrands', () => {
+ it('reads the active brands, never a demo brand', async () => {
+ expect(await listDailyTrackingBrands()).toEqual({ data: [], error: null });
+ expect(filters).toEqual([
+ ['select', 'brands', 'id, organization_id'],
+ ['eq', 'is_active', true],
+ ['eq', 'is_demo', false],
+ ]);
+ });
+});
diff --git a/server/src/lib/traffic-digest/engine.js b/server/src/lib/traffic-digest/engine.js
index 476741746..e83f5d7b4 100644
--- a/server/src/lib/traffic-digest/engine.js
+++ b/server/src/lib/traffic-digest/engine.js
@@ -336,6 +336,8 @@ export async function sendTrafficDigests({ now = new Date() } = {}) {
.from('brands')
.select('id')
.eq('is_active', true)
+ // A demo brand (00380) is sample data: nobody is mailed about it.
+ .eq('is_demo', false)
.order('id', { ascending: true })
.range(from, to),
);
diff --git a/server/src/lib/traffic-digest/engine.test.js b/server/src/lib/traffic-digest/engine.test.js
index 07f2f3acb..b3543d2d6 100644
--- a/server/src/lib/traffic-digest/engine.test.js
+++ b/server/src/lib/traffic-digest/engine.test.js
@@ -29,7 +29,10 @@ vi.mock('../../config/supabase.js', () => {
from: (table) => ({
select: () => {
const chain = {
- eq: () => chain,
+ eq: (column, value) => {
+ if (table === 'brands') state.brandFilters.push([column, value]);
+ return chain;
+ },
single: async () => ({
data:
table === 'brands'
@@ -122,6 +125,7 @@ beforeEach(() => {
rpcFailures: 0,
updateFailures: 0,
listBrands: null,
+ brandFilters: [],
rpc: {
ai_traffic_merged: (p) =>
p.p_from === '2026-10-12T00:00:00.000Z'
@@ -363,6 +367,15 @@ describe('sendTrafficDigests', () => {
expect(await sendTrafficDigests({ now: MONDAY })).toEqual({ skipped: 'self_hosted' });
});
+ it('never mails about a demo brand (00380)', async () => {
+ state.listBrands = [];
+ await sendTrafficDigests({ now: MONDAY });
+ expect(state.brandFilters).toEqual([
+ ['is_active', true],
+ ['is_demo', false],
+ ]);
+ });
+
it("sends every active brand's digest and counts them", async () => {
state.listBrands = [{ id: 'b1' }];
const result = await sendTrafficDigests({ now: MONDAY });
diff --git a/server/src/lib/volume-analysis.js b/server/src/lib/volume-analysis.js
index f11bb5c65..3c99f23ca 100644
--- a/server/src/lib/volume-analysis.js
+++ b/server/src/lib/volume-analysis.js
@@ -100,7 +100,7 @@ export function medianVolume(volumes) {
* column is unchanged from when each prompt had the response to itself. Two
* keywords that resolve to the same returned one count once.
*/
-function summarizeVolumes(keywords, volumes) {
+export function summarizeVolumes(keywords, volumes) {
const byKeyword = new Map();
for (const [keyword, data] of Object.entries(volumes)) {
byKeyword.set(keyword.trim().toLowerCase(), [keyword, data]);
@@ -340,7 +340,7 @@ export async function analyzeBrandVolumes(
) {
const { data: brand, error: brandError } = await supabaseAdmin
.from('brands')
- .select('region, language, organization_id')
+ .select('region, language, organization_id, is_demo')
.eq('id', brandId)
.maybeSingle();
@@ -350,6 +350,11 @@ export async function analyzeBrandVolumes(
if (!brand) {
throw new Error(`Brand ${brandId} not found`);
}
+ // A demo brand's volumes (00380) are sample data, written with it.
+ if (brand.is_demo) {
+ logger.info({ brandId }, 'volume analysis skipped: demo brand');
+ return [];
+ }
// Once the plan has ended (2026-10-27), no volume is looked up: every
// prompt is a model call and a DataForSEO request. The internal trigger
// (after a checkout) reaches here without the API's 402.
diff --git a/server/src/lib/volume-analysis.test.js b/server/src/lib/volume-analysis.test.js
index 798c92855..a5fa2ec11 100644
--- a/server/src/lib/volume-analysis.test.js
+++ b/server/src/lib/volume-analysis.test.js
@@ -176,6 +176,17 @@ describe('analyzeBrandVolumes', () => {
expect(queries.map((q) => q.table)).toEqual(['brands']);
});
+ it('looks up nothing for a demo brand (00380), whose volumes are sample data', async () => {
+ const db = seed({ activeCount: 3 });
+ db.brands[0].is_demo = true;
+ const { analyzeBrandVolumes, queries } = await load(db);
+
+ expect(await analyzeBrandVolumes('b1', { onlyMissing: true })).toEqual([]);
+ expect(extractIntentKeywords).not.toHaveBeenCalled();
+ expect(getSearchVolumes).not.toHaveBeenCalled();
+ expect(queries.map((q) => q.table)).toEqual(['brands']);
+ });
+
it("asks about the brand's own organization, and goes on when it is on a plan", async () => {
const { analyzeBrandVolumes } = await load(seed({ activeCount: 2 }));
diff --git a/server/src/middleware/subscription.js b/server/src/middleware/subscription.js
index a123ad15b..31c3d4a1f 100644
--- a/server/src/middleware/subscription.js
+++ b/server/src/middleware/subscription.js
@@ -15,6 +15,8 @@ import logger from '../lib/logger.js';
* - COST_STOPPING: stopping work under way, and taking back the access to
* an outside account (Google, a CMS, a bot log, a store) the person gave us;
* - DATA_REMOVAL: deleting what the person gave us (a brand and its data);
+ * - DEMO_ROUTES: opening, hiding and showing the demo brand (00380),
+ * whose data the server writes as a sample and which costs nothing;
* - ONBOARDING_ROUTES, for an organization that never had a subscription:
* setup suggests the brand's topics, prompts and competitors before the
* plan step, and again when the person comes back from it, up to
@@ -79,6 +81,19 @@ export const DATA_REMOVAL = [
{ method: 'DELETE', path: /^\/brands\/[^/]+\/?$/ },
];
+/**
+ * The demo brand (00380), under /api: open whatever the plan. Opening it
+ * writes the organization's sample brand (no tracking, no AI, no outside
+ * service), and the people it is for are the ones without a plan; hiding
+ * or showing it changes nothing else.
+ */
+export const DEMO_ROUTES = [
+ // Creates or rebuilds the demo brand (demo.js).
+ { method: 'POST', path: /^\/demo\/?$/ },
+ // Hides or shows it (demo.js).
+ { method: 'PATCH', path: /^\/demo\/?$/ },
+];
+
/**
* The writes onboarding asks of this API (web/src/lib/ai-brand-setup.ts):
* open to an organization that never had a subscription, so setup works
@@ -140,7 +155,12 @@ function matches(routes, { method, path }) {
}
function isOpen(req) {
- return matches(BILLING_ROUTES, req) || matches(COST_STOPPING, req) || matches(DATA_REMOVAL, req);
+ return (
+ matches(BILLING_ROUTES, req) ||
+ matches(COST_STOPPING, req) ||
+ matches(DATA_REMOVAL, req) ||
+ matches(DEMO_ROUTES, req)
+ );
}
/**
diff --git a/server/src/middleware/subscription.test.js b/server/src/middleware/subscription.test.js
index cefa2b24f..7a36be31b 100644
--- a/server/src/middleware/subscription.test.js
+++ b/server/src/middleware/subscription.test.js
@@ -35,6 +35,7 @@ const {
BILLING_ROUTES,
COST_STOPPING,
DATA_REMOVAL,
+ DEMO_ROUTES,
MAX_ENTRIES,
ONBOARDING_DAILY_CALLS,
ONBOARDING_LIMIT_REACHED,
@@ -227,6 +228,32 @@ describe('requireActiveSubscription', () => {
expect(DATA_REMOVAL).toHaveLength(1);
});
+ it('lets an organization off a plan, or never on one, open and hide the demo brand', async () => {
+ for (const state of [ended, neverSubscribed]) {
+ org = state;
+ for (const [method, path] of [
+ ['POST', '/demo'],
+ ['POST', '/demo/'],
+ ['PATCH', '/demo'],
+ ]) {
+ const { res, next } = await run({ method, path });
+ expect(next, `${method} ${path}`).toHaveBeenCalledOnce();
+ expect(res.status).not.toHaveBeenCalled();
+ }
+ }
+ org = ended;
+ for (const [method, path] of [
+ ['DELETE', '/demo'],
+ ['POST', '/demo/rebuild'],
+ ['PUT', '/demo'],
+ ]) {
+ const { res, next } = await run({ method, path });
+ expect(next, `${method} ${path}`).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(402);
+ }
+ expect(DEMO_ROUTES).toHaveLength(2);
+ });
+
it("opens onboarding's routes, and only them, to an organization that never subscribed", async () => {
// Setting up, before the plan step; and back from it (onboarding marked
// done, still no subscription): the flag is not read.
diff --git a/server/src/routes/brands.js b/server/src/routes/brands.js
index b0b421d1a..2091eaba1 100644
--- a/server/src/routes/brands.js
+++ b/server/src/routes/brands.js
@@ -16,13 +16,26 @@ const WAIT_MS = 20_000;
/**
* DELETE /api/brands/:id
* Deletes a brand and all its data. Admins only, as the brands delete policy
- * allows. 200 when it is gone, 202 when it is still being deleted.
+ * allows. 200 when it is gone, 202 when it is still being deleted. Never the
+ * demo brand (00380): it is hidden, not deleted (PATCH /api/demo).
*/
router.delete('/:id', async (req, res) => {
try {
const brandId = req.params.id;
await assertBrandAccess(brandId, req.user.id);
+ const { data: target, error: targetError } = await supabaseAdmin
+ .from('brands')
+ .select('is_demo')
+ .eq('id', brandId)
+ .single();
+ if (targetError) throw targetError;
+ if (target?.is_demo) {
+ return res
+ .status(409)
+ .json({ error: 'The demo brand can be hidden, not deleted.', code: 'demo_brand' });
+ }
+
const { data: profile } = await supabaseAdmin
.from('profiles')
.select('role')
diff --git a/server/src/routes/brands.test.js b/server/src/routes/brands.test.js
new file mode 100644
index 000000000..60beaa6f4
--- /dev/null
+++ b/server/src/routes/brands.test.js
@@ -0,0 +1,71 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * Deleting a brand (admins only), never the demo brand (00380): it is
+ * hidden, not deleted.
+ */
+
+let brand;
+let role;
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ single: async () =>
+ table === 'profiles'
+ ? { data: { role }, error: null }
+ : { data: { is_demo: brand.is_demo }, error: null },
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('../lib/access.js', () => ({ assertBrandAccess: vi.fn(async () => ({ orgId: 'o1' })) }));
+const deleteBrand = vi.fn(async () => {});
+vi.mock('../lib/brand-delete.js', () => ({ deleteBrand: (...a) => deleteBrand(...a) }));
+
+const { default: router } = await import('./brands.js');
+
+let server;
+let baseUrl;
+
+beforeEach(async () => {
+ brand = { is_demo: false };
+ role = 'admin';
+ deleteBrand.mockClear();
+ const app = express();
+ app.use((req, _res, next) => {
+ req.user = { id: 'u1' };
+ req.log = { error: vi.fn() };
+ next();
+ });
+ app.use('/api/brands', router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/api/brands`;
+});
+
+afterEach(async () => {
+ await new Promise((resolve) => server.close(resolve));
+});
+
+describe('DELETE /api/brands/:id', () => {
+ it('deletes a brand for an admin', async () => {
+ const res = await fetch(`${baseUrl}/b1`, { method: 'DELETE' });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ deleted: true });
+ expect(deleteBrand).toHaveBeenCalledWith('b1');
+ });
+
+ it('refuses the demo brand, which is hidden instead', async () => {
+ brand = { is_demo: true };
+ const res = await fetch(`${baseUrl}/b1`, { method: 'DELETE' });
+ expect(res.status).toBe(409);
+ expect(await res.json()).toMatchObject({ code: 'demo_brand' });
+ expect(deleteBrand).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/routes/demo.js b/server/src/routes/demo.js
new file mode 100644
index 000000000..cd40f0c42
--- /dev/null
+++ b/server/src/routes/demo.js
@@ -0,0 +1,71 @@
+import { Router } from 'express';
+import { z } from 'zod';
+import supabaseAdmin from '../config/supabase.js';
+import { ensureDemoBrand, setDemoHidden } from '../lib/demo/index.js';
+
+/**
+ * The organization's demo brand (00380): Brewline Coffee with sample data,
+ * in the organization's own brands. Open whatever the plan
+ * (middleware/subscription.js, DEMO_ROUTES): it costs nothing, and the
+ * people it is for are the ones without a plan.
+ */
+
+const router = Router();
+
+const MANAGERS = new Set(['admin', 'manager']);
+
+async function readProfile(userId) {
+ const { data, error } = await supabaseAdmin
+ .from('profiles')
+ .select('organization_id, role')
+ .eq('id', userId)
+ .maybeSingle();
+ if (error) throw new Error(`profiles read: ${error.message}`);
+ return data;
+}
+
+const noOrganization = (res) =>
+ res.status(409).json({ error: 'Set up your workspace first.', code: 'no_organization' });
+
+// POST /api/demo — the demo brand, created on the first visit and rebuilt
+// when the product moved on or its data grew old: { brandId, version,
+// rebuilt }. Any member may open it. Whether it is hidden is left as it is.
+router.post('/', async (req, res) => {
+ try {
+ const profile = await readProfile(req.user.id);
+ if (!profile?.organization_id) return noOrganization(res);
+ const result = await ensureDemoBrand({ organizationId: profile.organization_id });
+ return res.json(result);
+ } catch (err) {
+ req.log.error({ err }, 'demo brand error');
+ return res.status(500).json({ error: 'The demo brand could not be opened.', code: 'failed' });
+ }
+});
+
+// PATCH /api/demo { hidden } — hides or shows the demo brand for the whole
+// organization: { brandId, hidden }. Admins and managers, as for the
+// organization's other brands. Never deletes it.
+router.patch('/', async (req, res) => {
+ const body = z.object({ hidden: z.boolean() }).safeParse(req.body);
+ if (!body.success) return res.status(400).json({ error: 'invalid', code: 'invalid' });
+ try {
+ const profile = await readProfile(req.user.id);
+ if (!profile?.organization_id) return noOrganization(res);
+ if (!MANAGERS.has(profile.role)) {
+ return res
+ .status(403)
+ .json({ error: 'Only admins and managers can hide the demo brand.', code: 'forbidden' });
+ }
+ const result = await setDemoHidden({
+ organizationId: profile.organization_id,
+ hidden: body.data.hidden,
+ });
+ if (!result) return res.status(404).json({ error: 'No demo brand yet.', code: 'no_demo' });
+ return res.json(result);
+ } catch (err) {
+ req.log.error({ err }, 'demo brand hide error');
+ return res.status(500).json({ error: 'The demo brand could not be changed.', code: 'failed' });
+ }
+});
+
+export default router;
diff --git a/server/src/routes/demo.test.js b/server/src/routes/demo.test.js
new file mode 100644
index 000000000..91d508ca1
--- /dev/null
+++ b/server/src/routes/demo.test.js
@@ -0,0 +1,129 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * The organization's demo brand (00380): POST opens it (created or rebuilt
+ * when it has to be), PATCH hides or shows it for admins and managers.
+ */
+
+let profile;
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: () => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ maybeSingle: async () => ({ data: profile, error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+const ensureDemoBrand = vi.fn();
+const setDemoHidden = vi.fn();
+vi.mock('../lib/demo/index.js', () => ({
+ ensureDemoBrand: (...a) => ensureDemoBrand(...a),
+ setDemoHidden: (...a) => setDemoHidden(...a),
+}));
+
+const { default: router } = await import('./demo.js');
+
+let server;
+let baseUrl;
+
+beforeEach(async () => {
+ profile = { organization_id: 'org-1', role: 'admin' };
+ ensureDemoBrand.mockReset().mockResolvedValue({ brandId: 'demo-1', version: 1, rebuilt: true });
+ setDemoHidden
+ .mockReset()
+ .mockImplementation(async ({ hidden }) => ({ brandId: 'demo-1', hidden }));
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.user = { id: 'u1' };
+ req.log = { error: vi.fn() };
+ next();
+ });
+ app.use('/api/demo', router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/api/demo`;
+});
+
+afterEach(async () => {
+ await new Promise((resolve) => server.close(resolve));
+});
+
+const post = () => fetch(baseUrl, { method: 'POST' });
+const patch = (body) =>
+ fetch(baseUrl, {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+describe('POST /api/demo', () => {
+ it("opens the organization's demo brand for any member", async () => {
+ profile = { organization_id: 'org-1', role: 'analyst' };
+ const res = await post();
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ brandId: 'demo-1', version: 1, rebuilt: true });
+ expect(ensureDemoBrand).toHaveBeenCalledWith({ organizationId: 'org-1' });
+ expect(setDemoHidden).not.toHaveBeenCalled();
+ });
+
+ it('needs a workspace', async () => {
+ profile = { organization_id: null, role: 'admin' };
+ const res = await post();
+ expect(res.status).toBe(409);
+ expect(await res.json()).toMatchObject({ code: 'no_organization' });
+ expect(ensureDemoBrand).not.toHaveBeenCalled();
+ });
+
+ it('answers 500 when the demo could not be built', async () => {
+ ensureDemoBrand.mockRejectedValue(new Error('insert failed'));
+ const res = await post();
+ expect(res.status).toBe(500);
+ expect(await res.json()).toEqual({
+ error: 'The demo brand could not be opened.',
+ code: 'failed',
+ });
+ });
+});
+
+describe('PATCH /api/demo', () => {
+ it('hides and shows the demo brand for admins and managers', async () => {
+ let res = await patch({ hidden: true });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ brandId: 'demo-1', hidden: true });
+ expect(setDemoHidden).toHaveBeenLastCalledWith({ organizationId: 'org-1', hidden: true });
+
+ profile = { organization_id: 'org-1', role: 'manager' };
+ res = await patch({ hidden: false });
+ expect(await res.json()).toEqual({ brandId: 'demo-1', hidden: false });
+ });
+
+ it('refuses other roles', async () => {
+ profile = { organization_id: 'org-1', role: 'analyst' };
+ const res = await patch({ hidden: true });
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: 'forbidden' });
+ expect(setDemoHidden).not.toHaveBeenCalled();
+ });
+
+ it('answers 404 without a demo brand', async () => {
+ setDemoHidden.mockResolvedValue(null);
+ const res = await patch({ hidden: true });
+ expect(res.status).toBe(404);
+ expect(await res.json()).toMatchObject({ code: 'no_demo' });
+ });
+
+ it('takes only { hidden: boolean }', async () => {
+ for (const body of [{}, { hidden: 'yes' }, { hidden: null }]) {
+ const res = await patch(body);
+ expect(res.status, JSON.stringify(body)).toBe(400);
+ }
+ expect(setDemoHidden).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/routes/index.js b/server/src/routes/index.js
index a1ea35587..23a862d6d 100644
--- a/server/src/routes/index.js
+++ b/server/src/routes/index.js
@@ -20,6 +20,7 @@ import catalogRoutes from './catalog.js';
import cmsRoutes from './cms.js';
import cmsWordPressRoutes from './cms-wordpress.js';
import cmsFramerRoutes from './cms-framer.js';
+import demoRoutes from './demo.js';
const router = Router();
@@ -44,6 +45,7 @@ router.use('/catalog', catalogRoutes);
router.use('/cms', cmsRoutes);
router.use('/cms', cmsWordPressRoutes);
router.use('/cms', cmsFramerRoutes);
+router.use('/demo', demoRoutes);
router.get('/health', (req, res) => {
res.json({ status: 'ok', user: req.user?.id });
diff --git a/server/src/server.js b/server/src/server.js
index 42b4259a5..e2b94e451 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -27,6 +27,7 @@ import {
cleanupStalePendingTasks,
} from './lib/job-manager.js';
import { runTrackingJob, recoverWaitingJobs } from './lib/job-runner.js';
+import { listDailyTrackingBrands } from './lib/tracking-brands.js';
import { rebuildQueuedInsightsRollups, sweepInsightsRollups } from './lib/insights-rollups.js';
import { rebuildQueuedCitationRollups, REBUILD_QUEUE_SCHEDULE } from './lib/citations-rollups.js';
import { sweepActionValidation } from './lib/action-center/validate.js';
@@ -251,12 +252,8 @@ async function runDailyTracking() {
logger.error({ err }, '[brand-facts] weekly sweep crashed');
});
- // Skip paused brands (is_active = false): the user has explicitly suspended
- // tracking for them, so they should not spend Cloro / LLM credits daily.
- const { data: brands, error } = await supabaseAdmin
- .from('brands')
- .select('id, organization_id')
- .eq('is_active', true);
+ // Skip paused brands (the user's own stop) and demo brands (sample data).
+ const { data: brands, error } = await listDailyTrackingBrands();
if (error || !brands || brands.length === 0) {
return { triggered: 0, total: 0 };
diff --git a/supabase/migrations/00380_demo_brand.sql b/supabase/migrations/00380_demo_brand.sql
new file mode 100644
index 000000000..1f0dd2dd6
--- /dev/null
+++ b/supabase/migrations/00380_demo_brand.sql
@@ -0,0 +1,208 @@
+-- ============================================================================
+-- 00380: a demo brand per organization (demo-core)
+-- ============================================================================
+-- People who sign up without a card, and workspaces whose trial ended or whose
+-- plan was cancelled, can explore a demo brand: Brewline Coffee, a fictional
+-- brand on a `.example` domain, filled with sample data in the real tables.
+-- It is an ordinary brand row in the person's own organization, so every page
+-- reads it through the same queries and policies as any brand. The server
+-- writes its data (server/src/lib/demo/) and rebuilds it when DEMO_VERSION
+-- moves on or the data grows old, keeping the brand's id so links to it hold.
+--
+-- What it must never do is cost anything or count against the plan:
+-- * the nightly sweeps and the jobs skip `is_demo` brands (server code);
+-- * the plan's prompt-location quota and the brand count leave them out
+-- (org_prompt_location_usage, prompt_usage_summary below; the web's
+-- maxBrands check);
+-- * the health report's fan-out share leaves out their answers, which share
+-- their searches every run by construction and would hide a real drop.
+--
+-- Policies: members read the demo brand like any other. Only the server
+-- (service role) writes it: people can't insert a demo brand, mark a brand as
+-- one, change it or delete it. Hiding it (demo_hidden_at) goes through the
+-- server too (PATCH /api/demo), for admins and managers.
+
+alter table public.brands
+ add column if not exists is_demo boolean not null default false,
+ add column if not exists demo_version integer,
+ add column if not exists demo_built_at timestamptz,
+ add column if not exists demo_hidden_at timestamptz;
+
+-- The demo columns mean nothing on a real brand.
+alter table public.brands
+ drop constraint if exists brands_demo_columns_check;
+alter table public.brands
+ add constraint brands_demo_columns_check
+ check (is_demo or (demo_version is null and demo_built_at is null and demo_hidden_at is null));
+
+-- One demo brand per organization. Two first visits at once both try to
+-- create it; the second insert fails here and reads the first one's row.
+create unique index if not exists brands_one_demo_per_org
+ on public.brands (organization_id)
+ where is_demo;
+
+comment on column public.brands.is_demo is
+ 'Demo brand (00380): sample data written by the server (lib/demo), one per organization. Never tracked, audited or synced, never counted against the plan; people read it and can''t change it.';
+comment on column public.brands.demo_version is
+ 'Demo brand (00380): the DEMO_VERSION its data was built with; null while a build is under way or after one failed. A lower version is rebuilt on the next visit.';
+comment on column public.brands.demo_built_at is
+ 'Demo brand (00380): when its data was last built, its dates counted back from then; with a null demo_version, when the build under way started. Data older than a few days is rebuilt on the next visit.';
+comment on column public.brands.demo_hidden_at is
+ 'Demo brand (00380): when the organization hid it (after a purchase, or from the brand switcher); null = shown. Hidden, never deleted: it can be shown again.';
+
+-- ─── Policies ──────────────────────────────────────────────────────────────
+-- Same as before, plus `not is_demo`: a person can't insert a demo brand, turn
+-- a brand into one or back, change one or delete one. The server's writes use
+-- the service role and aren't bound by these.
+
+drop policy if exists "brands: admin/manager insert" on public.brands;
+create policy "brands: admin/manager insert" on public.brands
+ for insert
+ with check (
+ not is_demo
+ and organization_id in (
+ select profiles.organization_id
+ from public.profiles
+ where profiles.id = auth.uid()
+ and profiles.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ );
+
+drop policy if exists "brands: admin/manager update" on public.brands;
+create policy "brands: admin/manager update" on public.brands
+ for update
+ using (
+ not is_demo
+ and organization_id in (
+ select profiles.organization_id
+ from public.profiles
+ where profiles.id = auth.uid()
+ and profiles.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ )
+ with check (
+ not is_demo
+ and organization_id in (
+ select profiles.organization_id
+ from public.profiles
+ where profiles.id = auth.uid()
+ and profiles.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ );
+
+drop policy if exists "brands: admin delete" on public.brands;
+create policy "brands: admin delete" on public.brands
+ for delete
+ using (
+ not is_demo
+ and organization_id in (
+ select profiles.organization_id
+ from public.profiles
+ where profiles.id = auth.uid()
+ and profiles.role = 'admin'::public.user_role
+ )
+ );
+
+-- ─── The plan's prompt-location quota (00128) without the demo brand ───────
+-- savePromptSet, the prompt dialogs and import_prompts all count through this.
+create or replace function public.org_prompt_location_usage(p_organization_id uuid)
+returns table (brand_id uuid, locations bigint)
+language sql
+stable
+set search_path to 'public'
+as $$
+ select b.id, sum(greatest(coalesce(array_length(p.regions, 1), 0), 1))::bigint
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ join public.brands b on b.id = ps.brand_id
+ where b.organization_id = p_organization_id
+ and not b.is_demo
+ and p.is_active
+ group by b.id;
+$$;
+
+revoke all on function public.org_prompt_location_usage(uuid) from public;
+grant execute on function public.org_prompt_location_usage(uuid) to authenticated, service_role;
+
+comment on function public.org_prompt_location_usage(uuid) is
+ 'Active prompt locations per brand for one org (#691, 00128) — the plan-quota unit, one per region entry per active prompt, minimum one; paused prompts and the demo brand (00380) don''t count. Security invoker: RLS scopes it to the caller''s org.';
+
+-- ─── The usage cards' account totals (00139) without the demo brand ────────
+-- The demo brand's own counts stay (its Prompts page shows them); the
+-- account's prompts, brands and locations, which the plan limits, leave it out.
+create or replace function public.prompt_usage_summary(p_brand_id uuid)
+returns table (
+ brand_active integer,
+ brand_paused integer,
+ account_active integer,
+ account_brands integer,
+ account_locations integer
+)
+language sql
+stable
+set search_path = public
+as $$
+ select
+ coalesce(bc.active_prompts, 0),
+ coalesce(bc.paused_prompts, 0),
+ coalesce(acct.active_prompts, 0)::integer,
+ (
+ select count(*)
+ from public.brands b2
+ where b2.organization_id = b.organization_id
+ and not b2.is_demo
+ )::integer,
+ coalesce(acct.active_locations, 0)::integer
+ from public.brands b
+ left join public.prompt_usage_counters bc on bc.brand_id = b.id
+ left join lateral (
+ select sum(c.active_prompts) as active_prompts, sum(c.active_locations) as active_locations
+ from public.prompt_usage_counters c
+ join public.brands cb on cb.id = c.brand_id
+ where c.organization_id = b.organization_id
+ and not cb.is_demo
+ ) acct on true
+ where b.id = p_brand_id;
+$$;
+
+revoke all on function public.prompt_usage_summary(uuid) from public, anon;
+grant execute on function public.prompt_usage_summary(uuid) to authenticated, service_role;
+
+comment on function public.prompt_usage_summary(uuid) is
+ 'One brand''s active/paused prompts and its account''s active prompts, brands and active prompt locations, from prompt_usage_counters only (PROMPT-012); the account totals leave out the demo brand (00380). Security invoker.';
+
+-- ─── The health report's fan-out share (00140) without demo answers ────────
+create or replace function public.fanout_coverage_by_platform(
+ p_since timestamptz,
+ p_until timestamptz
+)
+returns table (platform text, answers bigint, answers_with_fanout bigint)
+language sql
+stable
+security definer
+set search_path = public
+as $$
+ select
+ r.platform,
+ count(*)::bigint,
+ count(*) filter (
+ where case
+ when jsonb_typeof(r.search_queries) = 'array' then jsonb_array_length(r.search_queries)
+ else 0
+ end > 0
+ )::bigint
+ from public.prompt_results r
+ join public.brands b on b.id = r.brand_id
+ where r.created_at >= p_since
+ and r.created_at < p_until
+ and not b.is_demo
+ group by r.platform;
+$$;
+
+revoke all on function public.fanout_coverage_by_platform(timestamptz, timestamptz)
+ from public, anon, authenticated;
+grant execute on function public.fanout_coverage_by_platform(timestamptz, timestamptz)
+ to service_role;
+
+comment on function public.fanout_coverage_by_platform(timestamptz, timestamptz) is
+ 'Answers and answers with observed query fan-out per platform in [p_since, p_until), across all brands but demo ones (00140, 00380). Read by the daily health report.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 18361bb7b..42d0fca10 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -43673,6 +43673,218 @@ create trigger catalog_sources_mark_ecommerce
after insert on public.catalog_sources
for each row execute function public.catalog_source_marks_ecommerce();
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00380_demo_brand.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00380: a demo brand per organization (demo-core)
+-- ============================================================================
+-- People who sign up without a card, and workspaces whose trial ended or whose
+-- plan was cancelled, can explore a demo brand: Brewline Coffee, a fictional
+-- brand on a `.example` domain, filled with sample data in the real tables.
+-- It is an ordinary brand row in the person's own organization, so every page
+-- reads it through the same queries and policies as any brand. The server
+-- writes its data (server/src/lib/demo/) and rebuilds it when DEMO_VERSION
+-- moves on or the data grows old, keeping the brand's id so links to it hold.
+--
+-- What it must never do is cost anything or count against the plan:
+-- * the nightly sweeps and the jobs skip `is_demo` brands (server code);
+-- * the plan's prompt-location quota and the brand count leave them out
+-- (org_prompt_location_usage, prompt_usage_summary below; the web's
+-- maxBrands check);
+-- * the health report's fan-out share leaves out their answers, which share
+-- their searches every run by construction and would hide a real drop.
+--
+-- Policies: members read the demo brand like any other. Only the server
+-- (service role) writes it: people can't insert a demo brand, mark a brand as
+-- one, change it or delete it. Hiding it (demo_hidden_at) goes through the
+-- server too (PATCH /api/demo), for admins and managers.
+
+alter table public.brands
+ add column if not exists is_demo boolean not null default false,
+ add column if not exists demo_version integer,
+ add column if not exists demo_built_at timestamptz,
+ add column if not exists demo_hidden_at timestamptz;
+
+-- The demo columns mean nothing on a real brand.
+alter table public.brands
+ drop constraint if exists brands_demo_columns_check;
+alter table public.brands
+ add constraint brands_demo_columns_check
+ check (is_demo or (demo_version is null and demo_built_at is null and demo_hidden_at is null));
+
+-- One demo brand per organization. Two first visits at once both try to
+-- create it; the second insert fails here and reads the first one's row.
+create unique index if not exists brands_one_demo_per_org
+ on public.brands (organization_id)
+ where is_demo;
+
+comment on column public.brands.is_demo is
+ 'Demo brand (00380): sample data written by the server (lib/demo), one per organization. Never tracked, audited or synced, never counted against the plan; people read it and can''t change it.';
+comment on column public.brands.demo_version is
+ 'Demo brand (00380): the DEMO_VERSION its data was built with; null while a build is under way or after one failed. A lower version is rebuilt on the next visit.';
+comment on column public.brands.demo_built_at is
+ 'Demo brand (00380): when its data was last built, its dates counted back from then; with a null demo_version, when the build under way started. Data older than a few days is rebuilt on the next visit.';
+comment on column public.brands.demo_hidden_at is
+ 'Demo brand (00380): when the organization hid it (after a purchase, or from the brand switcher); null = shown. Hidden, never deleted: it can be shown again.';
+
+-- ─── Policies ──────────────────────────────────────────────────────────────
+-- Same as before, plus `not is_demo`: a person can't insert a demo brand, turn
+-- a brand into one or back, change one or delete one. The server's writes use
+-- the service role and aren't bound by these.
+
+drop policy if exists "brands: admin/manager insert" on public.brands;
+create policy "brands: admin/manager insert" on public.brands
+ for insert
+ with check (
+ not is_demo
+ and organization_id in (
+ select profiles.organization_id
+ from public.profiles
+ where profiles.id = auth.uid()
+ and profiles.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ );
+
+drop policy if exists "brands: admin/manager update" on public.brands;
+create policy "brands: admin/manager update" on public.brands
+ for update
+ using (
+ not is_demo
+ and organization_id in (
+ select profiles.organization_id
+ from public.profiles
+ where profiles.id = auth.uid()
+ and profiles.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ )
+ with check (
+ not is_demo
+ and organization_id in (
+ select profiles.organization_id
+ from public.profiles
+ where profiles.id = auth.uid()
+ and profiles.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ );
+
+drop policy if exists "brands: admin delete" on public.brands;
+create policy "brands: admin delete" on public.brands
+ for delete
+ using (
+ not is_demo
+ and organization_id in (
+ select profiles.organization_id
+ from public.profiles
+ where profiles.id = auth.uid()
+ and profiles.role = 'admin'::public.user_role
+ )
+ );
+
+-- ─── The plan's prompt-location quota (00128) without the demo brand ───────
+-- savePromptSet, the prompt dialogs and import_prompts all count through this.
+create or replace function public.org_prompt_location_usage(p_organization_id uuid)
+returns table (brand_id uuid, locations bigint)
+language sql
+stable
+set search_path to 'public'
+as $$
+ select b.id, sum(greatest(coalesce(array_length(p.regions, 1), 0), 1))::bigint
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ join public.brands b on b.id = ps.brand_id
+ where b.organization_id = p_organization_id
+ and not b.is_demo
+ and p.is_active
+ group by b.id;
+$$;
+
+revoke all on function public.org_prompt_location_usage(uuid) from public;
+grant execute on function public.org_prompt_location_usage(uuid) to authenticated, service_role;
+
+comment on function public.org_prompt_location_usage(uuid) is
+ 'Active prompt locations per brand for one org (#691, 00128) — the plan-quota unit, one per region entry per active prompt, minimum one; paused prompts and the demo brand (00380) don''t count. Security invoker: RLS scopes it to the caller''s org.';
+
+-- ─── The usage cards' account totals (00139) without the demo brand ────────
+-- The demo brand's own counts stay (its Prompts page shows them); the
+-- account's prompts, brands and locations, which the plan limits, leave it out.
+create or replace function public.prompt_usage_summary(p_brand_id uuid)
+returns table (
+ brand_active integer,
+ brand_paused integer,
+ account_active integer,
+ account_brands integer,
+ account_locations integer
+)
+language sql
+stable
+set search_path = public
+as $$
+ select
+ coalesce(bc.active_prompts, 0),
+ coalesce(bc.paused_prompts, 0),
+ coalesce(acct.active_prompts, 0)::integer,
+ (
+ select count(*)
+ from public.brands b2
+ where b2.organization_id = b.organization_id
+ and not b2.is_demo
+ )::integer,
+ coalesce(acct.active_locations, 0)::integer
+ from public.brands b
+ left join public.prompt_usage_counters bc on bc.brand_id = b.id
+ left join lateral (
+ select sum(c.active_prompts) as active_prompts, sum(c.active_locations) as active_locations
+ from public.prompt_usage_counters c
+ join public.brands cb on cb.id = c.brand_id
+ where c.organization_id = b.organization_id
+ and not cb.is_demo
+ ) acct on true
+ where b.id = p_brand_id;
+$$;
+
+revoke all on function public.prompt_usage_summary(uuid) from public, anon;
+grant execute on function public.prompt_usage_summary(uuid) to authenticated, service_role;
+
+comment on function public.prompt_usage_summary(uuid) is
+ 'One brand''s active/paused prompts and its account''s active prompts, brands and active prompt locations, from prompt_usage_counters only (PROMPT-012); the account totals leave out the demo brand (00380). Security invoker.';
+
+-- ─── The health report's fan-out share (00140) without demo answers ────────
+create or replace function public.fanout_coverage_by_platform(
+ p_since timestamptz,
+ p_until timestamptz
+)
+returns table (platform text, answers bigint, answers_with_fanout bigint)
+language sql
+stable
+security definer
+set search_path = public
+as $$
+ select
+ r.platform,
+ count(*)::bigint,
+ count(*) filter (
+ where case
+ when jsonb_typeof(r.search_queries) = 'array' then jsonb_array_length(r.search_queries)
+ else 0
+ end > 0
+ )::bigint
+ from public.prompt_results r
+ join public.brands b on b.id = r.brand_id
+ where r.created_at >= p_since
+ and r.created_at < p_until
+ and not b.is_demo
+ group by r.platform;
+$$;
+
+revoke all on function public.fanout_coverage_by_platform(timestamptz, timestamptz)
+ from public, anon, authenticated;
+grant execute on function public.fanout_coverage_by_platform(timestamptz, timestamptz)
+ to service_role;
+
+comment on function public.fanout_coverage_by_platform(timestamptz, timestamptz) is
+ 'Answers and answers with observed query fan-out per platform in [p_since, p_until), across all brands but demo ones (00140, 00380). Read by the daily health report.';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00400_chat_core.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx
index 7f729d1af..ae57b253e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/page.tsx
@@ -71,7 +71,9 @@ export default async function BrandsPage() {
]);
const maxBrands = plan.limits.maxBrands;
- const canAddBrand = maxBrands === -1 || brands.length < maxBrands;
+ // The demo brand (00380) never counts against the plan.
+ const ownBrands = brands.filter((b) => !b.isDemo).length;
+ const canAddBrand = maxBrands === -1 || ownBrands < maxBrands;
const needsUpgrade = !canAddBrand && checkIsCloud();
return (
diff --git a/web/src/lib/actions/brand.test.ts b/web/src/lib/actions/brand.test.ts
index 931dfb168..bad65dec1 100644
--- a/web/src/lib/actions/brand.test.ts
+++ b/web/src/lib/actions/brand.test.ts
@@ -8,6 +8,7 @@ import { PLANS, type Plan } from '@/config/plans';
*/
let brandCount = 0;
+let countFilters: unknown[][] = [];
let inserted: unknown[] = [];
let updates: Record<string, unknown>[] = [];
let plan: Plan;
@@ -21,7 +22,17 @@ vi.mock('@/lib/guards/plan-guard', () => ({
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
from: (table: string) => ({
- select: () => ({ eq: async () => ({ count: brandCount, error: null }) }),
+ select: () => {
+ const chain = {
+ eq: (...filter: unknown[]) => {
+ countFilters.push(filter);
+ return chain;
+ },
+ then: (resolve: (value: { count: number; error: null }) => void) =>
+ resolve({ count: brandCount, error: null }),
+ };
+ return chain;
+ },
update: (payload: Record<string, unknown>) => {
updates.push(payload);
const row = {
@@ -62,6 +73,19 @@ const capped = (maxBrands: number): Plan => ({
describe('createBrand plan limit', () => {
beforeEach(() => {
inserted = [];
+ countFilters = [];
+ });
+
+ it("counts the organization's own brands, never the demo brand (00380)", async () => {
+ brandCount = 0;
+ plan = capped(5);
+
+ await createBrand(input);
+
+ expect(countFilters).toEqual([
+ ['organization_id', 'org-1'],
+ ['is_demo', false],
+ ]);
});
it('returns a readable plan_limit result and inserts nothing at the limit', async () => {
diff --git a/web/src/lib/actions/brand.ts b/web/src/lib/actions/brand.ts
index 5f47c026f..02db3ab23 100644
--- a/web/src/lib/actions/brand.ts
+++ b/web/src/lib/actions/brand.ts
@@ -44,6 +44,7 @@ function mapBrandRow(brand: Record<string, unknown>, domains: Record<string, unk
conversionsEnabled: brand.conversions_enabled === true,
conversionsConsent: brand.conversions_consent === 'always' ? 'always' : 'wait',
isActive: brand.is_active === undefined ? true : !!brand.is_active,
+ isDemo: brand.is_demo === true,
domains: domains.map(mapDomainRow),
createdAt: brand.created_at as string,
updatedAt: brand.updated_at as string,
@@ -106,10 +107,12 @@ export async function createBrand(input: CreateBrandInput): Promise<CreateBrandR
await assertWritable({ onboarding: true });
const supabase = await createClient();
+ // The demo brand (00380) never counts against the plan.
const { count } = await supabase
.from('brands')
.select('id', { count: 'exact', head: true })
- .eq('organization_id', input.organizationId);
+ .eq('organization_id', input.organizationId)
+ .eq('is_demo', false);
const plan = await getOrgPlan(input.organizationId);
if (!isWithinLimit(plan, 'maxBrands', count ?? 0)) {
diff --git a/web/src/lib/billing/first-run.test.ts b/web/src/lib/billing/first-run.test.ts
index 343f220f9..c758ba53d 100644
--- a/web/src/lib/billing/first-run.test.ts
+++ b/web/src/lib/billing/first-run.test.ts
@@ -69,10 +69,11 @@ describe('startFirstTrackingRun', () => {
expect(calls()).toEqual(['/api/internal/trigger-tracking']);
expect(bodyOf(0)).toEqual({ brandId: 'brand1', since: '2027-01-15T08:00:00.000Z' });
expect(fetchMock.mock.calls[0][1].headers).toMatchObject({ Authorization: 'Bearer secret' });
- // A paused brand is never the one tracked.
+ // A paused brand is never the one tracked, nor the demo brand (00380).
expect(brands.filters).toEqual([
['organization_id', 'org1'],
['is_active', true],
+ ['is_demo', false],
]);
});
diff --git a/web/src/lib/billing/first-run.ts b/web/src/lib/billing/first-run.ts
index 9e4bb67ca..8bf8a22e0 100644
--- a/web/src/lib/billing/first-run.ts
+++ b/web/src/lib/billing/first-run.ts
@@ -7,8 +7,7 @@ const API_TIMEOUT_MS = 5_000;
/**
* The organization's first brand that is not paused: the one onboarding
- * created. Once the demo brand lands (00380, not on main yet), it is skipped
- * too: `.eq('is_demo', false)`.
+ * created. Never the demo brand (00380): it is sample data and never tracked.
*/
async function firstBrandId(orgId: string): Promise<string | null> {
const { data: brand } = await supabaseAdmin
@@ -16,6 +15,7 @@ async function firstBrandId(orgId: string): Promise<string | null> {
.select('id')
.eq('organization_id', orgId)
.eq('is_active', true)
+ .eq('is_demo', false)
.order('created_at', { ascending: true })
.limit(1)
.maybeSingle();
diff --git a/web/src/lib/chat/precedence-context.test.ts b/web/src/lib/chat/precedence-context.test.ts
index 2b65576f4..38ebd48a4 100644
--- a/web/src/lib/chat/precedence-context.test.ts
+++ b/web/src/lib/chat/precedence-context.test.ts
@@ -194,11 +194,6 @@ describe('readPrecedenceContext', () => {
});
});
-// The demo chain (#1734, 00380) adds brands.is_demo. This stops compiling then, so the demo
-// flag gets wired to it (readBrandIsDemo) in the same change.
-type BrandRow = Database['public']['Tables']['brands']['Row'];
-const demoColumnNotYetThere: 'is_demo' extends keyof BrandRow ? never : true = true;
-
// Every table a row looks its brand up in has brand_id; a new one that lacks it doesn't compile.
type Tables = Database['public']['Tables'];
const lookupTablesNameTheirBrand: {
@@ -216,13 +211,18 @@ const BRAND_A = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
const BRAND_ELSEWHERE = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';
const OPPORTUNITY = '44444444-4444-4444-8444-444444444444';
-/** brands: found only for brand A, in ORG. content_opportunities: the opportunity's brand. */
-function seedBrands(opportunityBrand: string | null = BRAND_A) {
+/**
+ * brands: found only for brand A, in ORG (or by its id alone), the demo brand
+ * when `demo`. content_opportunities: the opportunity's brand.
+ */
+function seedBrands(opportunityBrand: string | null = BRAND_A, demo = false) {
const filter = (filters: Filters, column: string) => filters.find(([c]) => c === column)?.[1];
- db.tables.brands = (filters: Filters) =>
- filter(filters, 'id') === BRAND_A && filter(filters, 'organization_id') === ORG
- ? { id: BRAND_A }
+ db.tables.brands = (filters: Filters) => {
+ const org = filter(filters, 'organization_id');
+ return filter(filters, 'id') === BRAND_A && (org === undefined || org === ORG)
+ ? { id: BRAND_A, is_demo: demo }
: null;
+ };
db.tables.content_opportunities = (filters: Filters) =>
filter(filters, 'id') === OPPORTUNITY && opportunityBrand
? { brand_id: opportunityBrand }
@@ -267,15 +267,29 @@ describe("a call's brand", () => {
});
});
- it('reads the demo flag, false until the demo chain merges', async () => {
- expect(demoColumnNotYetThere).toBe(true);
+ it("reads the brand's demo flag (00380): the demo brand is kept to reading", async () => {
expect(Object.values(lookupTablesNameTheirBrand).every(Boolean)).toBe(true);
expect(await readBrandIsDemo(BRAND_A)).toBe(false);
+ expect(await readBrandIsDemo(BRAND_ELSEWHERE)).toBe(false);
const context = (await readPrecedenceContext(request))!;
expect(await readToolCall(context, byInput, { brand_id: BRAND_A }, true)).toEqual({
brandId: BRAND_A,
brandIsDemo: false,
tainted: true,
});
+
+ seedBrands(BRAND_A, true);
+ expect(await readBrandIsDemo(BRAND_A)).toBe(true);
+ const toolCall = await readToolCall(context, byInput, { brand_id: BRAND_A }, false);
+ expect(toolCall).toEqual({ brandId: BRAND_A, brandIsDemo: true, tainted: false });
+ expect(decideToolCall({ ...addPrompts, ...byInput }, context, toolCall)).toEqual({
+ kind: 'deny',
+ denial: { code: 'demo_brand' },
+ });
+ });
+
+ it('decides nothing on a demo flag read that failed', async () => {
+ db.errors.brands = 'timeout';
+ await expect(readBrandIsDemo(BRAND_A)).rejects.toThrow(/timeout/);
});
});
diff --git a/web/src/lib/chat/precedence-context.ts b/web/src/lib/chat/precedence-context.ts
index 280c99927..a552b0f42 100644
--- a/web/src/lib/chat/precedence-context.ts
+++ b/web/src/lib/chat/precedence-context.ts
@@ -78,13 +78,17 @@ export async function readBrandAccess(
}
/**
- * Whether a brand is the demo brand of sample data. Always false for now:
- * TODO wire to brands.is_demo when #1734 merges (the demo chain, 00380),
- * as the server's demo guard reads it.
+ * Whether a brand is the demo brand of sample data (brands.is_demo, 00380),
+ * as the server's demo guard reads it. A brand that isn't found isn't one.
*/
export async function readBrandIsDemo(brandId: string): Promise<boolean> {
- void brandId;
- return false;
+ const { data, error } = await supabaseAdmin
+ .from('brands')
+ .select('is_demo')
+ .eq('id', brandId)
+ .maybeSingle();
+ if (error) throw new Error(`Could not read the call's brand: ${error.message}`);
+ return data?.is_demo === true;
}
/**
diff --git a/web/src/lib/plan-engines.ts b/web/src/lib/plan-engines.ts
index 4691d2794..b03a20ce2 100644
--- a/web/src/lib/plan-engines.ts
+++ b/web/src/lib/plan-engines.ts
@@ -77,10 +77,12 @@ export async function alignPromptsToPlanForOrg(
}
}
+ // Never the demo brand's prompts (00380): they are sample data on every engine.
const { data: brands, error: brandsErr } = await supabaseAdmin
.from('brands')
.select('id')
- .eq('organization_id', orgId);
+ .eq('organization_id', orgId)
+ .eq('is_demo', false);
if (brandsErr) throw new Error(`brands lookup: ${brandsErr.message}`);
const brandIds = (brands ?? []).map((b) => b.id);
diff --git a/web/src/types/index.ts b/web/src/types/index.ts
index 07d230edf..6837bdb51 100644
--- a/web/src/types/index.ts
+++ b/web/src/types/index.ts
@@ -34,6 +34,8 @@ export interface Brand {
/** 'wait' keeps the snippet's visitor id only after the site's consent, 'always' at once. */
conversionsConsent?: 'wait' | 'always';
isActive: boolean;
+ /** The organization's demo brand (00380): sample data, never counted against the plan. */
+ isDemo?: boolean;
domains: BrandDomain[];
createdAt: string;
updatedAt: string;
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 7f4985d2b..13fbc741d 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -761,6 +761,9 @@ export type Database = {
conversions_consent: string
conversions_enabled: boolean
created_at: string
+ demo_built_at: string | null
+ demo_hidden_at: string | null
+ demo_version: number | null
description: string | null
ga_property_id: string | null
gsc_pages_backfill_from: string | null
@@ -770,6 +773,7 @@ export type Database = {
industry: string | null
insights_pinned_competitors: string[]
is_active: boolean
+ is_demo: boolean
kpi_setup_at: string | null
language: string | null
logo_url: string | null
@@ -792,6 +796,9 @@ export type Database = {
conversions_consent?: string
conversions_enabled?: boolean
created_at?: string
+ demo_built_at?: string | null
+ demo_hidden_at?: string | null
+ demo_version?: number | null
description?: string | null
ga_property_id?: string | null
gsc_pages_backfill_from?: string | null
@@ -801,6 +808,7 @@ export type Database = {
industry?: string | null
insights_pinned_competitors?: string[]
is_active?: boolean
+ is_demo?: boolean
kpi_setup_at?: string | null
language?: string | null
logo_url?: string | null
@@ -823,6 +831,9 @@ export type Database = {
conversions_consent?: string
conversions_enabled?: boolean
created_at?: string
+ demo_built_at?: string | null
+ demo_hidden_at?: string | null
+ demo_version?: number | null
description?: string | null
ga_property_id?: string | null
gsc_pages_backfill_from?: string | null
@@ -832,6 +843,7 @@ export type Database = {
industry?: string | null
insights_pinned_competitors?: string[]
is_active?: boolean
+ is_demo?: boolean
kpi_setup_at?: string | null
language?: string | null
logo_url?: string | null