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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(demo): fill the demo brand's Action Center, content, suggestions and reports (demo brand, part 2) (#1735)
Cihan58b7426825b6
diff --git a/server/src/lib/demo/action-center.js b/server/src/lib/demo/action-center.jsnew file mode 100644index 000000000..36c53f0f4--- /dev/null+++ b/server/src/lib/demo/action-center.js@@ -0,0 +1,985 @@+/**+ * The demo brand's Action Center (demo-workflows): its signals, the actions+ * the nightly engine raised from them over the month with their tasks,+ * trail and measured outcomes, the KPI framework, a task waiting for review+ * and Getting started.+ *+ * Each signal is what the detectors would have recorded from the demo's own+ * answers: its numbers are counted from core's rows (stats.js), its shape is+ * the detectors' own (group, single), and the classifiers that decide a+ * slipping engine or a source gap are the real ones. Each+ * action is then built as generate.js builds one: the definition's payload+ * from its signals, planTasks for its tasks, scorePriority for its priority;+ * a closed one is measured as validate.js measures it, on the same windows,+ * with basketValues and deriveOutcome.+ */++import supabaseAdmin from '../../config/supabase.js';+import { resolve } from '../../config/action-engine.js';+import { BASKET_KPIS, basketValues } from '../action-center/basket-metrics.js';+import { loadDefinitions } from '../action-center/definitions/index.js';+import {+ actionTargets,+ combinedTasks,+ initialTaskStatus,+ OPPORTUNITY_ACTION_KIND,+ opportunityAssets,+ WHOLE,+} from '../action-center/from-opportunity.js';+import { priorityColumns, scorePriority } from '../action-center/priority.js';+import { planTasks } from '../action-center/tasks/plan.js';+import { deriveOutcome, MEASUREMENT_WINDOW_DAYS } from '../action-center/validate.js';+import { KIND_META } from '../signals/record.js';+import { classifyRateFall, classifySource } from '../signals/library/classify.js';+import { group, promptTarget, single } from '../signals/library/detect.js';+import { BRAND, SOURCES } from './brewline.js';+import { contentRows, SENT_OPPORTUNITY } from './content.js';+import { demoId } from './random.js';+import { allSettledOrThrow, demoWriter } from './write.js';+import * as S from './stats.js';++const { library: T } = resolve();+const AI = ['ai_results'];++/** What the demo brand has, as resolveBrandSources would find it (core's data). */+export const DEMO_SOURCES = new Set(['tracking', 'competitors', 'topics', 'volumes']);++/** The engine's own measured KPIs and their units (validate.js MEASURABLE_KPIS). */+const BRAND_KPI_UNITS = {+ ai_visibility: 'percent',+ citations: 'count',+ mentions: 'count',+ share_of_voice: 'percent',+};++/** The latest week of answers as of one run: that run and the two before it. */+const weekTo = (ctx, run) =>+ S.runResults(+ ctx.rows.results,+ [run - 2, run - 1, run].filter((r) => r >= 0),+ );++/** A prompt finding's rows, as the prompts family groups them: most demand first. */+function promptRows(ctx, keys) {+ return keys+ .map((key) => ctx.promptId(key))+ .map((id) => ({ prompt_id: id, volume: ctx.volume(id)?.est_ai_volume ?? 0 }))+ .sort((a, b) => b.volume - a.volume);+}++const texts = (ctx) => new Map(ctx.rows.prompts.map((p) => [p.id, p.text]));++/** Per-platform answers and mentions over a set of answers (dims.platforms). */+function platformRows(results) {+ return [...S.groupBy(results, 'platform')].map(([key, rows]) => ({+ key,+ answers: rows.length,+ mentions: rows.filter((r) => r.mention_count > 0).length,+ }));+}++/** Third-party domains cited in a set of answers, as ae_citation_sources counts them. */+function citedSources(results) {+ const own = new Set([BRAND.domain]);+ const byDomain = new Map();+ for (const r of results) {+ const domains = new Set((r.citations ?? []).map((c) => new URL(c.url).hostname));+ for (const domain of domains) {+ const d = byDomain.get(domain) ?? {+ domain,+ owned: own.has(domain),+ results: 0,+ with_brand: 0,+ competitor_only: 0,+ prompts: new Set(),+ };+ d.results += 1;+ if (r.mention_count > 0) d.with_brand += 1;+ else if ((r.competitor_mentions ?? []).some((c) => c.mention_count > 0)) {+ d.competitor_only += 1;+ }+ d.prompts.add(r.prompt_id);+ byDomain.set(domain, d);+ }+ }+ return [...byDomain.values()]+ .map((d) => ({ ...d, prompts: d.prompts.size }))+ .sort((a, b) => b.results - a.results || a.domain.localeCompare(b.domain));+}++const publisher = (domain) => SOURCES.publishers.some((p) => p.domain === domain);++/**+ * The demo's signals, keyed for the actions below: each `candidate` in the+ * detectors' shape, found at run `run` (the night after it) and last seen+ * at `seen`.+ */+export function signalCandidates(ctx) {+ const latest = ctx.starts.length - 1;+ const found = {};++ // The strongest rival out-mentions Brewline this week (competitors family).+ {+ const week = weekTo(ctx, latest);+ const brand = S.brandStats(week).mentionAnswers;+ const leader = [...S.competitorStats(week).values()].sort(+ (a, b) => b.mentionAnswers - a.mentionAnswers,+ )[0];+ found.leads = {+ run: latest - 2,+ seen: latest,+ candidate: single(+ 'competitor_leads',+ leader.id,+ 'competitors',+ { id: leader.id, label: leader.name },+ AI,+ { previous: brand, current: leader.mentionAnswers, change: leader.mentionAnswers - brand },+ { competitorName: leader.name, competitorId: leader.id },+ ),+ };+ }++ // An engine whose mention rate fell against the week before (dimensions family).+ {+ const prev = new Map(platformRows(weekTo(ctx, latest - 4)).map((p) => [p.key, p]));+ const slipping = platformRows(weekTo(ctx, latest - 1))+ .map((cur) => {+ const before = prev.get(cur.key);+ const row = {+ key: cur.key,+ prev_mentions: before.mentions,+ prev_answers: before.answers,+ cur_mentions: cur.mentions,+ cur_answers: cur.answers,+ };+ return {+ row,+ kind: classifyRateFall(row, T, { slip: 'platform_slipping', drop: 'platform_drop' }),+ };+ })+ .filter((p) => p.kind)+ .sort(+ (a, b) => a.row.cur_mentions / a.row.cur_answers - b.row.cur_mentions / b.row.cur_answers,+ )[0];+ if (slipping) {+ const { row, kind } = slipping;+ const prev1 = Math.round((row.prev_mentions / row.prev_answers) * 1000) / 10;+ const cur1 = Math.round((row.cur_mentions / row.cur_answers) * 1000) / 10;+ found.platformSlip = {+ run: latest - 1,+ seen: latest - 1,+ candidate: single(+ kind,+ row.key,+ 'platforms',+ { id: row.key, label: row.key },+ AI,+ { previous: prev1, current: cur1, change: Math.round((cur1 - prev1) * 10) / 10 },+ { platform: row.key },+ ),+ };+ }+ }++ // A publisher cited often, mostly beside rivals (sources family): this+ // week's, and the one the brand set aside early in the month.+ const sourceSignal = (run, skip) => {+ const d = citedSources(weekTo(ctx, run)).find(+ (x) => publisher(x.domain) && x.domain !== skip && classifySource(x, T),+ );+ if (!d) return null;+ return {+ run,+ seen: run,+ candidate: single(+ classifySource(d, T),+ d.domain,+ 'sources',+ { id: d.domain, label: d.domain },+ AI,+ { current: d.results, previous: d.with_brand, change: d.competitor_only },+ { domain: d.domain, prompts: d.prompts, results: d.results },+ ),+ };+ };+ found.source = sourceSignal(latest, null);+ found.oldSource = sourceSignal(2, found.source?.candidate.payload.domain);++ // Early in the month: prompts that stopped naming Brewline from one run to+ // the next (prompts family), and its visibility slipping (Daily Pulse).+ {+ const before = S.groupBy(S.runResults(ctx.rows.results, [0]), 'prompt_id');+ const after = S.groupBy(S.runResults(ctx.rows.results, [1]), 'prompt_id');+ const lost = [...after]+ .filter(+ ([id, rows]) =>+ S.brandStats(rows).mentionAnswers === 0 &&+ S.brandStats(before.get(id)).mentionAnswers > 0,+ )+ .map(([id]) => ctx.promptKey(id));+ found.lostMentions = {+ run: 1,+ seen: 1,+ candidate: group(+ 'lost_mentions',+ 'prompts',+ promptRows(ctx, lost),+ promptTarget(texts(ctx)),+ AI,+ ),+ };++ const rate = (run) => {+ const b = S.brandStats(S.runResults(ctx.rows.results, [run]));+ return Math.round((b.visibleAnswers / b.answers) * 1000) / 10;+ };+ const from = rate(0);+ const to = rate(1);+ found.visibilitySlip = {+ run: 1,+ seen: 1,+ candidate: {+ kind: 'visibility_slipping',+ dedupKey: 'visibility_slipping',+ source: AI,+ payload: {},+ previousValue: from,+ currentValue: to,+ changeValue: -Math.round((from - to) * 10) / 10,+ },+ };+ }++ // Two of the weakest prompts a week later (prompts family).+ found.weakPrompts = {+ run: 3,+ seen: 3,+ candidate: group(+ 'prompt_visibility_gap',+ 'prompts',+ promptRows(ctx, ['best-subscriptions', 'low-acid']),+ promptTarget(texts(ctx)),+ AI,+ ),+ };++ // A prompt that came alive from one run to the next (Daily Pulse prompt_gain).+ {+ const id = ctx.promptId('fair-trade');+ const rateAt = (run) => {+ const rows = S.runResults(ctx.rows.results, [run]).filter((r) => r.prompt_id === id);+ return Math.round((S.brandStats(rows).mentionAnswers / rows.length) * 100);+ };+ const run = latest - 2;+ found.gain = {+ run,+ seen: run,+ candidate: {+ kind: 'prompt_gain',+ dedupKey: `prompt_gain:${id}`,+ source: AI,+ payload: { promptText: ctx.promptText(id), promptId: id },+ previousValue: null,+ currentValue: null,+ changeValue: rateAt(run) - rateAt(run - 1),+ },+ };+ }++ return Object.fromEntries(Object.entries(found).filter(([, s]) => s));+}++/**+ * The actions, as the nights raised them. `created`, `started` and `closed`+ * are [run, hours after that run started]; `done` is how many of its tasks+ * are completed while it is in progress; `review` adds a task waiting for+ * review (AC-010).+ */+export const ACTION_PLAN = [+ {+ key: 'lost-mentions',+ signals: ['lostMentions'],+ created: [1, 1],+ started: [1, 4],+ closed: [2, 6],+ status: 'completed',+ },+ {+ key: 'visibility-slip',+ signals: ['visibilitySlip'],+ created: [1, 1],+ started: [2, 3],+ closed: [3, 6],+ status: 'completed',+ },+ {+ key: 'weak-prompts',+ signals: ['weakPrompts'],+ created: [3, 1],+ started: [3, 5],+ closed: [4, 6],+ status: 'completed',+ },+ {+ key: 'old-source',+ signals: ['oldSource'],+ created: [2, 1],+ closed: [3, 3],+ status: 'dismissed',+ },+ {+ key: 'competitor-gap',+ signals: ['leads'],+ created: [7, 1],+ started: [8, 4],+ status: 'in_progress',+ done: 2,+ review: true,+ },+ {+ key: 'emerging',+ signals: ['gain'],+ created: [7, 1],+ started: [7, 6],+ closed: [8, 6],+ status: 'completed',+ },+ { key: 'platform-slip', signals: ['platformSlip'], created: [8, 1], status: 'new' },+ { key: 'source', signals: ['source'], created: [9, 1], status: 'new' },+];++const IMPACT_RANK = { high: 3, medium: 2, low: 1 };++function groupByKind(signals) {+ const byKind = new Map();+ for (const signal of signals)+ byKind.set(signal.kind, [...(byKind.get(signal.kind) ?? []), signal]);+ return byKind;+}++/** The measured values of a set of answers for a basket (opportunity_basket_metrics). */+function basketOf(results) {+ const brand = S.brandStats(results);+ const rivals = [...S.competitorStats(results).values()];+ return basketValues(+ {+ cells: brand.answers,+ visible: brand.mentionAnswers,+ competitor_visible_total: rivals.reduce((s, c) => s + c.mentionAnswers, 0),+ top_competitor_visible: Math.max(0, ...rivals.map((c) => c.mentionAnswers)),+ mention_answers: brand.mentionAnswers,+ },+ { pageCount: 0 },+ );+}++/** The brand-wide KPIs over a set of answers (measureKpis). */+function brandKpis(results) {+ const b = S.brandStats(results);+ return {+ ai_visibility: b.score,+ citations: b.citations,+ mentions: b.mentions,+ share_of_voice: S.shareOfVoice(results),+ };+}++/**+ * What validate.js stores for a closed action once its after window is+ * over: on its prompts when it names some, the brand-wide KPIs beside.+ */+function measure(ctx, action, signalRows, closedAt) {+ const beforeWindow = S.windowBefore(new Date(action.created_at), MEASUREMENT_WINDOW_DAYS);+ const afterWindow = S.windowAfter(closedAt, MEASUREMENT_WINDOW_DAYS);+ const measuredAt = new Date(`${afterWindow.to}T00:00:00.000Z`);+ measuredAt.setUTCDate(measuredAt.getUTCDate() + 1);+ measuredAt.setUTCHours(7, 30, 0, 0);+ if (measuredAt > ctx.now) return null;++ const window = ({ from, to }) => S.between(ctx.rows.results, from, to);+ const counts = { total: signalRows.length, ended: 0, replaced: 0, dismissed: 0, open: 0 };+ for (const s of signalRows) {+ if (s.status === 'resolved') counts.ended += 1;+ else if (s.status === 'dismissed') counts.dismissed += 1;+ else counts.open += 1;+ }+ const kpiKeys = action.kpi_keys.filter((k) => k in BRAND_KPI_UNITS);+ const brandBefore = brandKpis(window(beforeWindow));+ const brandAfter = brandKpis(window(afterWindow));+ const brandWide = kpiKeys.map((metric) => ({+ metric,+ unit: BRAND_KPI_UNITS[metric],+ before: brandBefore[metric] ?? null,+ after: brandAfter[metric] ?? null,+ }));++ const promptIds =+ action.payload.targetEntity === 'prompts'+ ? (action.payload.targets ?? []).map((t) => t.id).filter(Boolean)+ : [];+ let validation;+ let metrics;+ if (promptIds.length) {+ const ids = new Set(promptIds);+ const asked = action.kpi_keys.filter((k) => k in BASKET_KPIS);+ const keys = asked.length ? asked : Object.keys(BASKET_KPIS);+ const before = basketOf(window(beforeWindow).filter((r) => ids.has(r.prompt_id)));+ const after = basketOf(window(afterWindow).filter((r) => ids.has(r.prompt_id)));+ metrics = keys.map((metric) => ({+ metric,+ unit: BASKET_KPIS[metric],+ before: before[metric] ?? null,+ after: after[metric] ?? null,+ }));+ validation = {+ measuredAt: measuredAt.toISOString(),+ beforeWindow,+ afterWindow,+ metrics,+ scope: { kind: 'targets', entity: 'prompts', prompts: promptIds.length, pages: 0 },+ ...(brandWide.length ? { brandWide } : {}),+ };+ } else {+ metrics = brandWide;+ validation = { measuredAt: measuredAt.toISOString(), beforeWindow, afterWindow, metrics };+ }+ return {+ validation: { ...validation, signals: counts },+ outcome: deriveOutcome(metrics),+ measuredAt,+ };+}++/**+ * Every Action Center row of the demo brand, built in memory. Deterministic+ * but for the dates, which follow core's runs.+ *+ * @param {{ brandId: string, now: Date }} args+ */+export async function actionCenterRows({ brandId, now }) {+ const ctx = S.demoContext(brandId, now);+ const id = (key) => demoId(brandId, key);+ const at = ([run, hours]) => S.afterRun(ctx.starts, run, hours);+ const latestScore = at([ctx.starts.length - 1, 1]);+ const definitions = await loadDefinitions();+ const demand = new Map(+ ctx.rows.volumes.map((v) => [v.prompt_id, { volume: v.est_ai_volume, intent: v.intent }]),+ );+ const found = signalCandidates(ctx);++ const signals = [];+ const actions = [];+ const tasks = [];+ const events = [];+ const links = [];+ const reviews = [];++ for (const plan of ACTION_PLAN) {+ const picked = plan.signals.map((key) => ({ key, ...found[key] })).filter((s) => s.candidate);+ if (picked.length === 0) continue;+ const definition = definitions.find((d) => d.signalKinds.includes(picked[0].candidate.kind));+ const actionId = id(`action:${plan.key}`);+ const createdAt = at(plan.created);+ const closedAt = plan.closed ? at(plan.closed) : null;+ const open = plan.status === 'new' || plan.status === 'in_progress';++ // The signals behind it, as the recorder wrote them and as they stand now.+ const signalRows = picked.map(({ key, run, seen, candidate }) => {+ const meta = KIND_META[candidate.kind];+ const detectedAt = S.afterRun(ctx.starts, run, 0.5);+ const lastAt = S.afterRun(ctx.starts, seen, 0.5);+ // A closed cycle's findings ended once the work landed; a dismissed one's were set aside.+ const status = open+ ? plan.status === 'new'+ ? 'new'+ : 'acknowledged'+ : plan.status === 'dismissed'+ ? 'dismissed'+ : 'resolved';+ const resolvedAt =+ status === 'resolved' ? S.afterRun(ctx.starts, plan.closed[0] + 1, 0.5) : null;+ return {+ id: id(`signal:${key}`),+ brand_id: brandId,+ category: meta.category,+ kind: candidate.kind,+ impact: meta.impact,+ status,+ source: candidate.source,+ dedup_key: candidate.dedupKey,+ detected_at: detectedAt.toISOString(),+ last_detected_at: lastAt.toISOString(),+ resolved_at: resolvedAt?.toISOString() ?? null,+ previous_value: candidate.previousValue,+ current_value: candidate.currentValue,+ change_value: candidate.changeValue,+ payload: candidate.payload,+ kpi_keys: meta.kpiKeys,+ action_id: actionId,+ created_at: detectedAt.toISOString(),+ updated_at: (resolvedAt ?? (plan.status === 'dismissed' ? closedAt : lastAt)).toISOString(),+ };+ });+ signals.push(...signalRows);++ const impact = signalRows+ .map((s) => s.impact)+ .sort((a, b) => IMPACT_RANK[b] - IMPACT_RANK[a])[0];+ const payload = {+ signalCount: signalRows.length,+ ...definition.payload(groupByKind(signalRows)),+ };+ const action = {+ id: actionId,+ brand_id: brandId,+ category: definition.category,+ kind: definition.id,+ definition_version: definition.version,+ impact,+ status: plan.status,+ payload,+ kpi_keys: [...new Set(signalRows.flatMap((s) => s.kpi_keys))],+ baseline: {+ capturedAt: createdAt.toISOString(),+ signals: signalRows.map((s) => ({+ id: s.id,+ kind: s.kind,+ previousValue: s.previous_value,+ currentValue: s.current_value,+ changeValue: s.change_value,+ })),+ },+ dedup_key: definition.id,+ created_at: createdAt.toISOString(),+ updated_at: (closedAt ?? (plan.started ? at(plan.started) : createdAt)).toISOString(),+ completed_at: plan.status === 'completed' ? closedAt.toISOString() : null,+ outcome: 'pending_measurement',+ };+ // Scored as the engine last scored it: tonight for an open one, on the+ // night it closed for a closed one, from the evidence open then.+ const scoredAt = open ? latestScore : closedAt;+ Object.assign(+ action,+ priorityColumns(+ scorePriority(+ {+ action,+ signals: signalRows.map((s) => ({ ...s, detected_at: s.detected_at })),+ prompts: demand,+ },+ scoredAt,+ ),+ scoredAt,+ ),+ );++ // Its tasks, as planTasks lays them out for what the brand has.+ const plannedTasks = planTasks(definition, { sources: DEMO_SOURCES, payload });+ const done =+ plan.status === 'completed'+ ? plannedTasks.length+ : plan.status === 'in_progress'+ ? (plan.done ?? 0)+ : 0;+ const taskTimes = (i) => {+ const from = (plan.started ? at(plan.started) : createdAt).getTime();+ const to = (closedAt ?? latestScore).getTime();+ return new Date(from + ((to - from) * (i + 1)) / (plannedTasks.length + 1));+ };+ plannedTasks.forEach((item, i) => {+ const status =+ i < done+ ? 'completed'+ : plan.status === 'in_progress' && i === done+ ? 'in_progress'+ : 'todo';+ const updatedAt = status === 'todo' ? createdAt : taskTimes(i);+ tasks.push({+ id: id(`task:${plan.key}:${item.taskKey}`),+ action_id: actionId,+ position: item.position,+ task_key: item.taskKey,+ task_version: item.version,+ mode: item.mode,+ permission: item.permission,+ depends_on: item.dependsOn,+ title_params: item.titleParams,+ details: item.details,+ status,+ created_at: createdAt.toISOString(),+ updated_at: updatedAt.toISOString(),+ });+ if (status === 'completed') {+ events.push({+ id: id(`event:${plan.key}:task:${item.taskKey}`),+ action_id: actionId,+ event: 'task_status',+ data: { taskId: id(`task:${plan.key}:${item.taskKey}`), to: 'completed' },+ actor_id: null,+ created_at: updatedAt.toISOString(),+ });+ }+ });++ // The trail: raised, worked on, closed, measured.+ const event = (name, when, data) =>+ events.push({+ id: id(`event:${plan.key}:${name}`),+ action_id: actionId,+ event: name,+ data,+ actor_id: null,+ created_at: when.toISOString(),+ });+ event('created', createdAt, {+ impact,+ signalCount: signalRows.length,+ definitionVersion: definition.version,+ taskCount: plannedTasks.length,+ });+ if (plan.started) event('status_changed', at(plan.started), { to: 'in_progress' });+ if (plan.status === 'completed' || plan.status === 'dismissed') {+ events.push({+ id: id(`event:${plan.key}:closed`),+ action_id: actionId,+ event: 'status_changed',+ data: { to: plan.status },+ actor_id: null,+ created_at: closedAt.toISOString(),+ });+ }+ if (plan.status === 'completed') {+ const measured = measure(ctx, action, signalRows, closedAt);+ if (measured) {+ Object.assign(action, {+ validation: measured.validation,+ outcome: measured.outcome,+ validated_at: measured.measuredAt.toISOString(),+ });+ event('outcome_measured', measured.measuredAt, { outcome: measured.outcome });+ }+ }++ for (const s of signalRows) {+ links.push({ action_id: actionId, signal_id: s.id, linked_at: createdAt.toISOString() });+ }++ // A task the agent wrote without the page or its Done when (AC-010).+ if (plan.review) {+ reviews.push({+ id: id(`review:${plan.key}`),+ action_id: actionId,+ title: 'Publish a Brewline vs Northbound Roasters comparison page',+ details: {+ why: 'Northbound Roasters is named in more answers to the subscription prompts, and answers comparing the two cite its pages, not Brewline’s.',+ how: [+ 'Compare roast dates, delivery schedules and pause or skip options side by side.',+ 'Answer the questions people ask before switching subscriptions.',+ ],+ },+ missing: ['url', 'doneWhen'],+ source: 'ai',+ created_at: at(plan.started).toISOString(),+ updated_at: at(plan.started).toISOString(),+ });+ }++ actions.push(action);+ }++ // An opportunity someone sent over from Content, now being written in the Editor.+ const sent = sentOpportunityAction(ctx, { demand, scoredAt: latestScore });+ actions.push(sent.action);+ tasks.push(...sent.tasks);+ events.push(...sent.events);++ return {+ signals,+ actions,+ tasks,+ events: events.sort((a, b) => a.created_at.localeCompare(b.created_at)),+ links,+ reviews,+ kpis: kpiRows(ctx, brandId),+ ...gettingStartedRows(ctx, brandId),+ };+}++/** The KPIs an action sent from Content is judged by (from-opportunity.js). */+const OPPORTUNITY_KPI_KEYS = ['ai_visibility', 'citations', 'mentions'];++/**+ * The action sendToActionCenter makes of the whole opportunity: its assets'+ * work (combinedTasks), its prompts kept, scored as priorityOnCreate scores+ * a hand-sent action. Its brief is done and the Content Agent's draft is+ * being worked on in the Editor (content.js links the draft to it).+ */+function sentOpportunityAction(ctx, { demand, scoredAt }) {+ const { brandId } = ctx;+ const id = (key) => demoId(brandId, key);+ const rows = contentRows({ brandId, now: ctx.now });+ const opportunity = rows.opportunities.find(+ (o) => o.id === id(`opportunity:${SENT_OPPORTUNITY}`),+ );+ const chosen = opportunityAssets(opportunity);+ const promptIds = rows.members+ .filter((m) => m.cluster_id === opportunity.cluster_id)+ .map((m) => m.prompt_id);+ const payload = {+ source: OPPORTUNITY_ACTION_KIND,+ opportunityId: opportunity.id,+ assetKey: null,+ title: opportunity.title,+ decision: chosen[0].decision,+ assets: chosen.map(({ key, type, channel, decision, title }) => ({+ key,+ type,+ channel,+ decision,+ title,+ })),+ pages: [...new Set(chosen.flatMap((a) => (a.pages || []).map((p) => p.url)))],+ promptIds,+ targetEntity: 'prompts',+ ...actionTargets(promptIds, opportunity.source_data.prompts),+ contentExists: chosen.some((a) => a.decision !== 'create'),+ };+ const createdAt = S.afterRun(ctx.starts, 8, 3);+ const startedAt = S.afterRun(ctx.starts, 8, 4);+ const actionId = id(`action:opportunity:${SENT_OPPORTUNITY}`);+ const base = {+ kind: OPPORTUNITY_ACTION_KIND,+ category: 'growth',+ impact: opportunity.impact,+ payload,+ created_at: createdAt.toISOString(),+ };+ const action = {+ id: actionId,+ brand_id: brandId,+ ...base,+ definition_version: 1,+ status: 'in_progress',+ kpi_keys: OPPORTUNITY_KPI_KEYS,+ baseline: {},+ dedup_key: `opportunity:${opportunity.id}:${WHOLE}`,+ updated_at: startedAt.toISOString(),+ completed_at: null,+ outcome: 'pending_measurement',+ ...priorityColumns(+ scorePriority({ action: base, signals: [], prompts: demand }, scoredAt),+ scoredAt,+ ),+ };++ const planned = planTasks(+ { id: OPPORTUNITY_ACTION_KIND, tasks: combinedTasks(chosen) },+ { sources: DEMO_SOURCES, payload },+ );+ // The brief came with the agent's draft; the draft is the work under way.+ const progress = { create_content_brief: 'completed', create_content_draft: 'in_progress' };+ const tasks = planned.map((item) => ({+ id: id(`task:opportunity:${item.taskKey}`),+ action_id: actionId,+ position: item.position,+ task_key: item.taskKey,+ task_version: item.version,+ mode: item.mode,+ permission: item.permission,+ depends_on: item.dependsOn,+ title_params: item.titleParams,+ details: item.details,+ status: progress[item.taskKey] ?? initialTaskStatus(item.taskKey, opportunity),+ created_at: createdAt.toISOString(),+ updated_at: (progress[item.taskKey] ? startedAt : createdAt).toISOString(),+ }));+ const event = (name, when, data) => ({+ id: id(`event:opportunity:${name}`),+ action_id: actionId,+ event: name,+ data,+ actor_id: null,+ created_at: when.toISOString(),+ });+ const events = [+ event('created', createdAt, {+ source: OPPORTUNITY_ACTION_KIND,+ opportunityId: opportunity.id,+ assetKey: null,+ impact: opportunity.impact,+ taskCount: planned.length,+ }),+ event('status_changed', startedAt, { to: 'in_progress' }),+ ...tasks+ .filter((t) => t.status === 'completed')+ .map((t) => ({+ ...event(`task:${t.task_key}`, startedAt, { taskId: t.id, to: 'completed' }),+ event: 'task_status',+ })),+ ];+ return { action, tasks, events };+}++/**+ * The ready-made KPIs the KPI tab sets up for a brand that has none+ * (web/src/lib/kpis/presets.ts PRESET_KPIS; AI Referral Traffic only with+ * Analytics, which the demo's core has not).+ */+export const PRESET_KPIS = [+ 'ai_visibility',+ 'mentions',+ 'citations',+ 'share_of_voice',+ 'positive_sentiment',+];+const PERCENT_KPIS = new Set(['ai_visibility', 'share_of_voice', 'positive_sentiment']);++/** A preset's target: its month 20% up (presets.ts presetTarget). */+export function presetTarget(key, value) {+ const raised = value * 1.2;+ if (PERCENT_KPIS.has(key)) return Math.min(100, Math.max(0.1, Math.round(raised * 10) / 10));+ return Math.ceil(raised);+}++/**+ * The brand's KPI framework (00078), as seed_kpi_presets (00163) leaves it:+ * the ready-made set, each target its month 20% up. Built in advance, so the+ * KPI tab finds the brand set up and never seeds it (a demo brand can't be+ * written to from the page).+ */+function kpiRows(ctx, brandId) {+ const month = ctx.rows.results;+ const b = S.brandStats(month);+ const setAt = gettingStartedDay(ctx, 0, 1).toISOString();+ const values = {+ ai_visibility: b.score,+ mentions: b.mentions,+ citations: b.citations,+ share_of_voice: S.shareOfVoice(month),+ positive_sentiment: Math.round((b.positive / b.mentionAnswers) * 1000) / 10,+ };+ return PRESET_KPIS.map((key) => ({+ id: demoId(brandId, `kpi:${key}`),+ brand_id: brandId,+ kpi_key: key,+ target: presetTarget(key, values[key]),+ timeframe: 'monthly',+ is_active: true,+ created_at: setAt,+ updated_at: setAt,+ }));+}++/** A moment `n` days after the brand was set up. */+function gettingStartedDay(ctx, n, hours = 10) {+ return new Date(Date.parse(ctx.rows.brand.created_at) + n * S.DAY_MS + hours * S.HOUR_MS);+}++/**+ * The explore steps that are done once their page is opened+ * (web/src/lib/getting-started/steps.ts PAGE_STEPS), all opened already:+ * getting_started_page_opened then has nothing to record on a visit.+ */+export const PAGE_STEPS = ['visibility', 'answers', 'mentions', 'citations', 'traffic'];++/**+ * Getting started (00196) under way: the brand started it when it was set+ * up, set its KPIs and has opened every page an explore step asks for.+ */+function gettingStartedRows(ctx, brandId) {+ const since = new Date(ctx.rows.brand.created_at);+ const steps = [+ ['kpis', 'done', gettingStartedDay(ctx, 0, 1)],+ ...PAGE_STEPS.map((step, i) => [step, 'opened', gettingStartedDay(ctx, 5 + i, 10)]),+ ];+ return {+ kpiSetupAt: gettingStartedDay(ctx, 0, 1).toISOString(),+ gettingStarted: [+ {+ brand_id: brandId,+ started_at: since.toISOString(),+ confirmed_at: since.toISOString(),+ dismissed_at: null,+ },+ ],+ gettingStartedSteps: steps.map(([step, state, when]) => ({+ brand_id: brandId,+ step,+ state,+ updated_at: when.toISOString(),+ })),+ };+}++/** Its tables' key columns where a row has no `id` of its own. */+const KEYS = {+ getting_started: 'brand_id',+ getting_started_steps: 'brand_id,step',+ action_signals: 'action_id,signal_id',+};+/** Its tables without a brand_id, found through their action. */+const SCOPES = {+ action_signals: ['action_id', 'actions'],+ action_tasks: ['action_id', 'actions'],+ action_events: ['action_id', 'actions'],+ action_task_reviews: ['action_id', 'actions'],+};++/**+ * The Action Center module. Tasks, events, signal links and task reviews+ * hang off the actions (no brand_id of their own) and go with them; the+ * actions' entity lists (00244) are written by their insert trigger.+ */+export const actionCenter = {+ name: 'actionCenter',+ // Rebuilt in place (write.js): written over, what isn't written again deleted after.+ inPlace: true,+ keys: KEYS,+ scopes: SCOPES,+ tables: ['kpi_definitions', 'getting_started', 'getting_started_steps', 'actions', 'signals'],++ /**+ * Each step's independent tables side by side, through the build's+ * writer (a writer over `db` for a first build without one).+ *+ * @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 = await actionCenterRows({ brandId, now });+ // Set up when its KPIs were: the KPI tab reads the brand as set up and+ // Getting started its KPI step as done, without writing either.+ const { error } = await db+ .from('brands')+ .update({ kpi_setup_at: rows.kpiSetupAt })+ .eq('id', brandId);+ if (error) throw new Error(`demo brand kpi setup: ${error.message}`);+ await allSettledOrThrow([+ write('kpi_definitions', rows.kpis),+ // A new brand's trigger has started Getting started: written over by brand.+ write('getting_started', rows.gettingStarted),+ write('getting_started_steps', rows.gettingStartedSteps),+ write('actions', rows.actions),+ ]);+ // Signals, tasks, events and reviews point at their action; the links at+ // both an action and a signal.+ await allSettledOrThrow([+ write('signals', rows.signals),+ write('action_tasks', rows.tasks),+ write('action_events', rows.events),+ write('action_task_reviews', rows.reviews),+ ]);+ await write('action_signals', rows.links);+ return {+ signals: rows.signals.length,+ actions: rows.actions.length,+ tasks: rows.tasks.length,+ };+ },+};diff --git a/server/src/lib/demo/action-center.test.js b/server/src/lib/demo/action-center.test.jsnew file mode 100644index 000000000..119d86eec--- /dev/null+++ b/server/src/lib/demo/action-center.test.js@@ -0,0 +1,194 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('../../config/supabase.js', () => ({ default: {} }));++const { ACTION_PLAN, actionCenter, actionCenterRows, PAGE_STEPS, PRESET_KPIS, presetTarget } =+ await import('./action-center.js');+const { coreRows } = await import('./core.js');+const { demoId } = await import('./random.js');+const { loadDefinitions } = await import('../action-center/definitions/index.js');++/**+ * The demo brand's Action Center (demo-workflows): a month of actions raised+ * from signals counted on the demo's own answers, in the engine's shapes.+ */++const BRAND_ID = '11111111-2222-4333-8444-555555555555';+const NOW = new Date('2026-10-28T12:00:00Z');+const DAY = 86_400_000;+const rows = await actionCenterRows({ brandId: BRAND_ID, now: NOW });+const core = coreRows({ brandId: BRAND_ID, now: NOW });+const count = (list, key) =>+ list.reduce((acc, row) => ({ ...acc, [row[key]]: (acc[row[key]] ?? 0) + 1 }), {});++describe('actionCenterRows', () => {+ it('raises nine actions across the families, in every status', () => {+ expect(rows.actions).toHaveLength(ACTION_PLAN.length + 1);+ expect(count(rows.actions, 'status')).toEqual({+ new: 2,+ in_progress: 2,+ completed: 4,+ dismissed: 1,+ });+ expect(new Set(rows.actions.map((a) => a.category))).toEqual(+ new Set(['growth', 'protect', 'recover', 'compete']),+ );+ for (const a of rows.actions) {+ expect(a.priority_score).toBeGreaterThanOrEqual(0);+ expect(a.priority_score).toBeLessThanOrEqual(100);+ expect(['critical', 'high', 'medium', 'low']).toContain(a.priority_level);+ }+ });++ it('measures what it closed: improved, no meaningful change, and one still pending', () => {+ const closed = rows.actions.filter((a) => a.status === 'completed');+ expect(count(closed, 'outcome')).toEqual({+ improved: 2,+ no_meaningful_change: 1,+ pending_measurement: 1,+ });+ for (const a of closed.filter((x) => x.outcome !== 'pending_measurement')) {+ expect(a.validation.metrics.length).toBeGreaterThan(0);+ expect(a.validation.afterWindow.to < a.validated_at.slice(0, 10)).toBe(true);+ expect(a.validation.signals).toMatchObject({ total: 1, ended: 1 });+ expect(rows.events).toContainEqual(+ expect.objectContaining({ action_id: a.id, event: 'outcome_measured' }),+ );+ }+ });++ it('builds each action from a real definition, with its planned tasks', async () => {+ const definitions = await loadDefinitions();+ for (const a of rows.actions) {+ if (a.kind === 'content_opportunity') continue;+ const definition = definitions.find((d) => d.id === a.kind);+ expect(definition, a.kind).toBeTruthy();+ expect(a.category).toBe(definition.category);+ expect(a.definition_version).toBe(definition.version);+ }+ for (const a of rows.actions) {+ const tasks = rows.tasks.filter((t) => t.action_id === a.id);+ expect(tasks.length, a.kind).toBeGreaterThan(3);+ expect(tasks.map((t) => t.position)).toEqual(tasks.map((_, i) => i + 1));+ if (a.status === 'completed') expect(tasks.every((t) => t.status === 'completed')).toBe(true);+ if (a.status === 'new') expect(tasks.every((t) => t.status === 'todo')).toBe(true);+ if (a.status === 'in_progress') {+ expect(tasks.filter((t) => t.status === 'in_progress')).toHaveLength(1);+ }+ }+ });++ it('ties its signals, prompts and competitors to the core rows', () => {+ const actionIds = new Set(rows.actions.map((a) => a.id));+ const promptIds = new Set(core.prompts.map((p) => p.id));+ for (const s of rows.signals) {+ expect(s.brand_id).toBe(BRAND_ID);+ expect(actionIds.has(s.action_id)).toBe(true);+ expect(rows.links).toContainEqual(+ expect.objectContaining({ action_id: s.action_id, signal_id: s.id }),+ );+ }+ const promptTargets = rows.actions+ .filter((a) => a.payload.targetEntity === 'prompts')+ .flatMap((a) => [+ ...(a.payload.targets ?? []).filter((t) => typeof t === 'object').map((t) => t.id),+ ...(a.payload.promptIds ?? []),+ ]);+ expect(promptTargets.length).toBeGreaterThan(0);+ for (const id of promptTargets) expect(promptIds.has(id)).toBe(true);++ const leads = rows.signals.find((s) => s.kind === 'competitor_leads');+ expect(leads.payload.competitorId).toBe(core.competitors[0].id);+ expect(leads.current_value).toBeGreaterThan(leads.previous_value);+ for (const t of rows.tasks) expect(actionIds.has(t.action_id)).toBe(true);+ for (const e of rows.events) expect(actionIds.has(e.action_id)).toBe(true);+ expect(rows.reviews).toHaveLength(1);+ expect(actionIds.has(rows.reviews[0].action_id)).toBe(true);+ });++ it('dates everything within the demo’s month, before now', () => {+ const stamps = [+ ...rows.actions.flatMap((a) => [a.created_at, a.updated_at, a.completed_at]),+ ...rows.signals.flatMap((s) => [s.detected_at, s.last_detected_at, s.resolved_at]),+ ...rows.tasks.map((t) => t.updated_at),+ ...rows.events.map((e) => e.created_at),+ ].filter(Boolean);+ for (const at of stamps) {+ expect(Date.parse(at)).toBeLessThanOrEqual(NOW.getTime());+ expect(NOW.getTime() - Date.parse(at)).toBeLessThan(31 * DAY);+ }+ });++ it('is the same every time but for its dates, under its own brand’s ids', async () => {+ const later = await actionCenterRows({+ brandId: BRAND_ID,+ now: new Date(NOW.getTime() + 2 * DAY + 5 * 3_600_000),+ });+ const shape = (list) =>+ list.map(({ kind, status, outcome, payload }) => ({ kind, status, outcome, payload }));+ expect(shape(later.actions)).toEqual(shape(rows.actions));+ expect(rows.actions[0].id).toBe(demoId(BRAND_ID, `action:${ACTION_PLAN[0].key}`));+ });++ it('sets up the ready-made KPIs, so the KPI tab never seeds them', () => {+ expect(rows.kpis.map((k) => k.kpi_key)).toEqual(PRESET_KPIS);+ for (const k of rows.kpis) {+ expect(k).toMatchObject({ brand_id: BRAND_ID, timeframe: 'monthly', is_active: true });+ expect(k.target).toBeGreaterThan(0);+ }+ expect(presetTarget('ai_visibility', 50.24)).toBe(60.3);+ expect(presetTarget('positive_sentiment', 90)).toBe(100);+ expect(presetTarget('mentions', 391)).toBe(470);+ expect(Date.parse(rows.kpiSetupAt)).toBeLessThan(NOW.getTime());+ });++ it('runs Getting started with its KPI step done and every page step opened', () => {+ expect(rows.gettingStarted).toEqual([+ expect.objectContaining({ brand_id: BRAND_ID, dismissed_at: null }),+ ]);+ expect(rows.gettingStarted[0].confirmed_at).toBeTruthy();+ const states = Object.fromEntries(rows.gettingStartedSteps.map((s) => [s.step, s.state]));+ expect(states.kpis).toBe('done');+ for (const step of PAGE_STEPS) expect(states[step], step).toBe('opened');+ for (const s of rows.gettingStartedSteps) expect(s.step).toMatch(/^[a-z_]{1,40}$/);+ });+});++describe('actionCenter.build', () => {+ it('writes actions before the signals pointing at them, then what hangs off them', async () => {+ const written = [];+ const keys = {};+ const db = {+ from: (table) => ({+ upsert: async (list, { onConflict }) => {+ written.push([table, list.length]);+ keys[table] = onConflict;+ return { error: null };+ },+ update: (patch) => ({+ eq: async (column, value) => {+ written.push([`${table}:update`, { patch, [column]: value }]);+ return { error: null };+ },+ }),+ }),+ };+ const built = await actionCenter.build({ brandId: BRAND_ID, now: NOW, db });+ const order = written.map(([table]) => table);+ // The brand reads as set up before its KPIs land.+ expect(order[0]).toBe('brands:update');+ expect(written[0][1]).toEqual({ patch: { kpi_setup_at: rows.kpiSetupAt }, id: BRAND_ID });+ expect(order.indexOf('actions')).toBeLessThan(order.indexOf('signals'));+ expect(order.indexOf('signals')).toBeLessThan(order.indexOf('action_signals'));+ expect(order).toContain('action_task_reviews');+ expect(built).toEqual({ signals: 8, actions: 9, tasks: rows.tasks.length });+ for (const table of actionCenter.tables) expect(order).toContain(table);+ // Written over by key: what a new brand's trigger made, and an old build's rows.+ expect(keys).toMatchObject({+ actions: 'id',+ getting_started: 'brand_id',+ getting_started_steps: 'brand_id,step',+ action_signals: 'action_id,signal_id',+ });+ });+});diff --git a/server/src/lib/demo/content-pages.js b/server/src/lib/demo/content-pages.jsnew file mode 100644index 000000000..7ad0990f2--- /dev/null+++ b/server/src/lib/demo/content-pages.js@@ -0,0 +1,123 @@+/**+ * The demo's three Content Editor drafts, as their pages read: one the+ * Content Agent wrote from an opportunity, one page being optimized, one+ * published. Made up like everything in the demo (brewline.js): Brewline+ * Coffee and its products don't exist, and every link stays on `.example`.+ */++export const DRAFTS = [+ {+ key: 'low-acid-guide',+ opportunity: 'sensitive-stomach',+ prompts: ['low-acid'],+ title: 'Low-Acid Coffee: How to Choose Beans That Are Gentle on Your Stomach',+ pageType: 'buying_guide',+ method: 'create',+ status: 'draft',+ author: 'agent',+ created: [8, 4],+ updated: [9, 0.5],+ bodyHtml: `<h1>Low-Acid Coffee: How to Choose Beans That Are Gentle on Your Stomach</h1>+<p>If coffee leaves you with heartburn or an upset stomach, you don’t have to give it up. The beans you buy, how dark they are roasted and how you brew them all change how acidic your cup tastes and feels. This guide explains what “low-acid coffee” really means and how to pick beans that suit a sensitive stomach.</p>+<h2>What makes coffee acidic?</h2>+<p>Coffee naturally contains chlorogenic acids, citric acid and malic acid. They give a cup its brightness, but they are also what some people react to. Three things decide how much of them ends up in your mug:</p>+<ul>+<li><strong>Origin and altitude.</strong> Beans grown at lower altitudes, such as many from Brazil and Sumatra, tend to be less acidic than high-grown Kenyan or Ethiopian coffees.</li>+<li><strong>Roast level.</strong> Longer, darker roasts break down more of the chlorogenic acids, so a medium-dark roast is usually gentler than a light one.</li>+<li><strong>Brewing method.</strong> Cold brew extracts noticeably fewer acids than hot methods, and a coarser grind helps too.</li>+</ul>+<h2>How to choose low-acid coffee beans</h2>+<ol>+<li>Look for medium-dark or dark roasts from low-altitude origins.</li>+<li>Check the roast date. Fresh beans taste smoother, while stale beans turn sour and harsh.</li>+<li>Try a water-process decaf if caffeine also bothers you: it is one of the mildest cups you can brew.</li>+<li>Buy whole beans and grind just before brewing, so the cup tastes balanced rather than bitter.</li>+</ol>+<h2>Our gentlest roasts</h2>+<p>At Brewline we roast to order and print the roast date on every bag. For a sensitive stomach we recommend our <a href="https://brewline.example/coffee/espresso-roast">Espresso Roast</a>, a medium-dark blend of Brazilian and Sumatran beans, and our <a href="https://brewline.example/coffee/decaf">Water Process Decaf</a>. Both ship within a day of roasting.</p>+<h2>Frequently asked questions</h2>+<h3>Is dark roast coffee less acidic?</h3>+<p>Generally, yes. Darker roasts contain fewer chlorogenic acids than light roasts, which is why many people with acid reflux find them easier to drink.</p>+<h3>Does cold brew reduce acidity?</h3>+<p>Cold brew is often described as up to two thirds less acidic than hot coffee made from the same beans, because cold water extracts fewer acids.</p>+<h3>Is decaf easier on the stomach?</h3>+<p>For many people it is. Decaf still contains acids, but without caffeine it stimulates less stomach acid of its own.</p>`,+ },+ {+ key: 'freshness-update',+ opportunity: 'freshness',+ prompts: ['freshness'],+ title: 'How Fresh Should Coffee Beans Be?',+ pageType: 'guide',+ method: 'optimize',+ status: 'in_review',+ author: 'user',+ sourcePath: '/blog/how-fresh-should-coffee-beans-be',+ created: [6, 5],+ updated: [7, 3],+ bodyHtml: `<h1>How Fresh Should Coffee Beans Be?</h1>+<p><strong>Short answer:</strong> whole beans taste best between 4 and 21 days after their roast date. Ground coffee loses its aroma within an hour or two, so grind just before you brew.</p>+<h2>Why freshness matters</h2>+<p>Roasting fills coffee beans with carbon dioxide and aromatic oils. In the first few days the beans release that gas quickly, which can make a cup taste flat or sharp. After about a week the flavor settles and peaks. From around the third week the oils start to oxidize, and the coffee slowly turns dull and woody.</p>+<h2>The freshness timeline</h2>+<table>+<thead><tr><th>Days after roasting</th><th>What to expect</th></tr></thead>+<tbody>+<tr><td>1–3</td><td>Still degassing. Good for cold brew, uneven for espresso.</td></tr>+<tr><td>4–21</td><td>Peak flavor for filter coffee and espresso.</td></tr>+<tr><td>22–45</td><td>Still drinkable, with fading aroma and sweetness.</td></tr>+<tr><td>45+</td><td>Noticeably stale. Best used for cold brew or baking.</td></tr>+</tbody>+</table>+<h2>How to read a roast date</h2>+<p>Look for a “roasted on” date rather than a “best before” date. A best-before date can sit a year after roasting and tells you little about flavor. Every Brewline bag shows the day it was roasted, and we ship within 24 hours of roasting.</p>+<h2>How to keep beans fresh</h2>+<ul>+<li>Store them in an airtight, opaque container at room temperature.</li>+<li>Keep them away from heat, light and moisture. The fridge adds moisture, so skip it.</li>+<li>Buy amounts you’ll finish in two to three weeks. A <a href="https://brewline.example/subscriptions">subscription</a> makes this easy.</li>+</ul>+<h2>Frequently asked questions</h2>+<h3>Can you freeze coffee beans?</h3>+<p>Yes, if you portion them into airtight bags and only take out what you’ll use within a week. Don’t refreeze them.</p>+<h3>Do fresh beans make better espresso?</h3>+<p>Espresso is the most sensitive to freshness. Beans 7 to 21 days off roast give the most even extraction.</p>`,+ },+ {+ key: 'pause-skip-help',+ opportunity: 'flexible-plans',+ prompts: ['pause-skip'],+ title: 'How to Pause, Skip or Reschedule Your Coffee Subscription',+ pageType: 'help_faq',+ method: 'create',+ status: 'published',+ author: 'user',+ slug: 'pause-or-skip-a-delivery',+ publishedPath: '/help/pause-or-skip-a-delivery',+ metaTitle: 'Pause or Skip a Coffee Delivery | Brewline Coffee',+ metaDescription:+ 'Pause, skip or reschedule your Brewline coffee subscription anytime from your account, with no fees and no minimum number of deliveries.',+ created: [3, 6],+ updated: [5, 8],+ published: [5, 8],+ bodyHtml: `<h1>How to Pause, Skip or Reschedule Your Coffee Subscription</h1>+<p>Your Brewline subscription works around your schedule. You can pause it, skip a delivery or change how often it arrives at any time, with no fees and no minimum number of deliveries.</p>+<h2>Skip a single delivery</h2>+<ol>+<li>Sign in to your account and open <strong>Subscriptions</strong>.</li>+<li>Choose the upcoming delivery and select <strong>Skip this delivery</strong>.</li>+<li>Your next bag ships on the following scheduled date.</li>+</ol>+<h2>Pause your subscription</h2>+<p>Going away or still working through a bag? Select <strong>Pause</strong> and pick a date to restart, from one week to three months away. We’ll email you three days before it resumes.</p>+<h2>Change your delivery schedule</h2>+<p>Switch between weekly, every two weeks and monthly deliveries whenever you like. Changes made at least two days before roasting apply to the next bag.</p>+<h2>Frequently asked questions</h2>+<h3>Is there a fee to pause or skip?</h3>+<p>No. Pausing, skipping and rescheduling are always free.</p>+<h3>Can I cancel anytime?</h3>+<p>Yes. You can cancel from the same page, and there is no minimum commitment.</p>+<h3>What if my bag has already been roasted?</h3>+<p>Once a bag is roasted it ships the same day. Any change you make then applies to the delivery after it.</p>`,+ },+];diff --git a/server/src/lib/demo/content.js b/server/src/lib/demo/content.jsnew file mode 100644index 000000000..5b12192f0--- /dev/null+++ b/server/src/lib/demo/content.js@@ -0,0 +1,585 @@+/**+ * The demo brand's Content (demo-workflows): its prompt clusters, the+ * content opportunities written for them, its Content Editor drafts and its+ * Plan marks.+ *+ * Clusters are stored as replace_prompt_clusters stores them, with the+ * fan-out searches the demo's own answers ran (clusterQueries) and the scope+ * fingerprint the clusterer checks (scopeFingerprint), so nothing reads them+ * as stale. Each opportunity carries what opportunity-generator.js writes:+ * its cluster's metrics (clusterMetrics over the demo's month), its score+ * (scoreComponents, opportunityScore) and its assets (buildAssets). Only+ * the titles and descriptions, the model's part, are written here.+ */++import supabaseAdmin from '../../config/supabase.js';+import { OPPORTUNITY_ACTION_KIND, WHOLE } from '../action-center/from-opportunity.js';+import { assetTypes, buildAssets } from '../page-matching.js';+import {+ clusterMetrics,+ OPPORTUNITY_WINDOW_DAYS,+ opportunityScore,+ scoreComponents,+} from '../opportunity-limits.js';+import { clusterQueries, MAX_QUERIES_PER_CLUSTER, scopeFingerprint } from '../prompt-clusters.js';+import { BRAND, SOURCES, TOPICS } from './brewline.js';+import { DRAFTS } from './content-pages.js';+import { demoId } from './random.js';+import { allSettledOrThrow, demoWriter } from './write.js';+import * as S from './stats.js';++/** The fan-out queries a cluster keeps: run in two answers at least (FANOUT_MIN_ANSWERS). */+const MIN_QUERY_ANSWERS = 2;+/** Included queries an opportunity keeps, most searched first (opportunity-generator.js). */+const QUERIES_KEPT = 15;++const brandUrl = (path) => `https://${BRAND.domain}${path}`;++/** The demo's prompt clusters: what one piece of content can answer. */+export const CLUSTERS = [+ {+ key: 'choosing-subscription',+ topic: 'subscriptions',+ prompts: ['best-subscriptions', 'worth-it'],+ label: 'Choosing a coffee subscription',+ intent: 'Compare coffee subscriptions and decide whether one is worth it',+ secondary: ['Compare subscription prices', 'Cost per cup of a subscription'],+ },+ {+ key: 'flexible-plans',+ topic: 'subscriptions',+ prompts: ['pause-skip'],+ label: 'Flexible subscription plans',+ intent: 'Find a coffee subscription that can be paused or skipped',+ secondary: [],+ },+ {+ key: 'subscription-gifts',+ topic: 'subscriptions',+ prompts: ['gift'],+ label: 'Coffee subscription gifts',+ intent: 'Pick a coffee subscription to give as a gift',+ secondary: ['Prepaid gift plans'],+ },+ {+ key: 'espresso-beans',+ topic: 'beans',+ prompts: ['espresso'],+ label: 'Espresso beans for home',+ intent: 'Choose whole beans for espresso at home',+ secondary: [],+ },+ {+ key: 'buying-online',+ topic: 'beans',+ prompts: ['buy-online'],+ label: 'Buying fresh beans online',+ intent: 'Find a roaster that ships freshly roasted beans',+ secondary: [],+ },+ {+ key: 'sensitive-stomach',+ topic: 'beans',+ prompts: ['low-acid'],+ label: 'Coffee for sensitive stomachs',+ intent: 'Find low-acid coffee that is gentle on the stomach',+ secondary: [],+ },+ {+ key: 'origin-vs-blend',+ topic: 'beans',+ prompts: ['single-origin'],+ label: 'Single origin vs blends',+ intent: 'Decide between single-origin coffee and a blend',+ secondary: [],+ },+ {+ key: 'ethical-sourcing',+ topic: 'buying',+ prompts: ['fair-trade'],+ label: 'Ethically sourced coffee',+ intent: 'Find roasters selling organic, fair trade beans',+ secondary: [],+ },+ {+ key: 'decaf',+ topic: 'buying',+ prompts: ['decaf'],+ label: 'Decaf that tastes good',+ intent: 'Find a decaf coffee that still tastes good',+ secondary: [],+ },+ {+ key: 'freshness',+ topic: 'buying',+ prompts: ['freshness'],+ label: 'Coffee bean freshness',+ intent: 'Understand how fresh coffee beans should be',+ secondary: [],+ },+ {+ key: 'brand-comparison',+ topic: 'buying',+ prompts: ['versus'],+ label: 'Brewline vs Northbound Roasters',+ intent: 'Compare Brewline Coffee and Northbound Roasters subscriptions',+ secondary: [],+ },+];++const pct = (n) => `${Math.round(n)}%`;+const searches = (n) => n.toLocaleString('en-US');++/**+ * The opportunities, one per cluster that has one, oldest first. `asset`+ * is the model's pick (type, decision, pages by path); `created` is+ * [run, hours] for when the nightly run wrote it.+ */+export const OPPORTUNITIES = [+ {+ cluster: 'choosing-subscription',+ created: [2, 2],+ status: 'new',+ impact: 'high',+ type: 'owned',+ asset: { type: 'buying_guide', decision: 'optimize', pages: ['/subscriptions'] },+ supporting: [+ {+ type: 'comparison',+ channel: 'owned',+ decision: 'create',+ pages: [],+ title: 'Coffee subscriptions compared side by side',+ },+ ],+ title: 'Turn the subscriptions page into a guide to choosing a coffee subscription',+ description: (m) =>+ `Answers comparing coffee subscriptions name Brewline in ${pct(m.visibility)} of cases, while ${m.competitorsCited[0]} reaches ${pct(m.topCompetitorVisibility)}. About ${searches(m.demand)} AI searches a month ask which subscription to pick and whether it is worth it.`,+ priority: true,+ },+ {+ cluster: 'subscription-gifts',+ created: [2, 2],+ status: 'reviewed',+ impact: 'medium',+ type: 'owned',+ asset: { type: 'collection_page', decision: 'expand', pages: ['/gifts'] },+ supporting: [],+ title: 'Expand the gifts page with prepaid subscription plans and gift notes',+ description: (m) =>+ `Gift answers lean on ${m.competitorsCited[0]}, visible in ${pct(m.topCompetitorVisibility)} of them against Brewline’s ${pct(m.visibility)}. The gifts page lists bags but not how a prepaid subscription works as a present.`,+ },+ {+ cluster: 'espresso-beans',+ created: [2, 2],+ status: 'new',+ impact: 'high',+ type: 'owned',+ asset: { type: 'product_page', decision: 'optimize', pages: ['/coffee/espresso-roast'] },+ supporting: [],+ title: 'Add brewing specs and a dose guide to the Espresso Roast page',+ description: (m) =>+ `With ${searches(m.demand)} AI searches a month, espresso beans is one of the busiest needs. Brewline is named in ${pct(m.visibility)} of answers; adding grind, dose and roast-date details gives engines a reason to cite the product page.`,+ priority: true,+ },+ {+ cluster: 'sensitive-stomach',+ created: [5, 2],+ status: 'in_progress',+ impact: 'high',+ type: 'owned',+ asset: { type: 'buying_guide', decision: 'create', pages: [] },+ supporting: [],+ title: 'Write a buying guide to low-acid coffee for sensitive stomachs',+ description: (m) =>+ `People asking for coffee that is gentle on the stomach rarely see Brewline (${pct(m.visibility)} of answers), and no Brewline page covers low-acid beans. ${m.competitorsCited[0]} is named in ${pct(m.topCompetitorVisibility)} of them.`,+ },+ {+ cluster: 'origin-vs-blend',+ created: [5, 2],+ status: 'new',+ impact: 'medium',+ type: 'owned',+ asset: { type: 'comparison', decision: 'create', pages: [] },+ supporting: [],+ title: 'Explain single origin vs blends with a side-by-side tasting chart',+ description: (m) =>+ `${m.competitorsCited[0]} owns this comparison at ${pct(m.topCompetitorVisibility)} visibility; Brewline is at ${pct(m.visibility)} and has no page comparing the two.`,+ },+ {+ cluster: 'ethical-sourcing',+ created: [5, 2],+ status: 'new',+ impact: 'medium',+ type: 'earned',+ asset: { type: 'third_party_article', decision: 'create', pages: [] },+ supporting: [],+ title: 'Get Brewline into the roundups of fair trade and organic roasters',+ description: (m) =>+ `Answers about ethically sourced coffee cite publishers’ roundups, and Brewline appears in ${pct(m.visibility)} of them. A sourcing story placed with those publishers can put it on their lists.`,+ },+ {+ cluster: 'decaf',+ created: [8, 2],+ status: 'new',+ impact: 'medium',+ type: 'owned',+ asset: { type: 'product_page', decision: 'optimize', pages: ['/coffee/decaf'] },+ supporting: [+ {+ type: 'help_faq',+ channel: 'owned',+ decision: 'create',+ pages: [],+ title: 'How water-process decaf is made',+ },+ ],+ title: 'Add tasting notes and process details to the Water Process Decaf page',+ description: (m) =>+ `The decaf page is already cited, yet Brewline is named in ${pct(m.visibility)} of decaf answers against ${pct(m.topCompetitorVisibility)} for ${m.competitorsCited[0]}. Detail on how the beans are decaffeinated and how they taste gives engines more to quote.`,+ },+ {+ cluster: 'freshness',+ created: [5, 2],+ status: 'in_progress',+ impact: 'medium',+ type: 'owned',+ asset: {+ type: 'guide',+ decision: 'refresh',+ pages: ['/blog/how-fresh-should-coffee-beans-be'],+ },+ supporting: [],+ title: 'Refresh the coffee freshness guide with a roast-date timeline',+ description: (m) =>+ `The freshness guide is Brewline’s most cited page for this need, with Brewline visible in ${pct(m.visibility)} of answers. A clear day-by-day timeline answers the question engines are asked directly.`,+ },+ {+ cluster: 'flexible-plans',+ created: [2, 2],+ status: 'done',+ impact: 'medium',+ type: 'owned',+ asset: { type: 'help_faq', decision: 'create', pages: [] },+ supporting: [],+ title: 'Publish a help page on pausing and skipping deliveries',+ description: (m) =>+ `People ask which subscriptions can be paused or skipped. Brewline offers both, yet it is named in only ${pct(m.visibility)} of these answers and no page explains how.`,+ },+ {+ cluster: 'buying-online',+ created: [8, 2],+ status: 'dismissed',+ impact: 'low',+ type: 'earned',+ asset: { type: 'backlink', decision: 'create', pages: [] },+ supporting: [],+ title: 'Earn a link from forum threads about buying fresh beans online',+ description: (m) =>+ `Forum threads are cited in answers about buying beans online, where Brewline appears in ${pct(m.visibility)} of cases.`,+ dismissReason: 'not_relevant',+ },+];++/** What brand_prompt_opportunity_metrics reads for one prompt over the window. */+function promptMetrics(results) {+ const brand = S.brandStats(results);+ const rivals = [...S.competitorStats(results).values()]+ .filter((c) => c.mentionAnswers > 0)+ .sort((a, b) => b.mentionAnswers - a.mentionAnswers);+ const rate = (n) => (results.length ? Math.round((n / results.length) * 1000) / 10 : 0);+ return {+ cells: results.length,+ visibility: rate(brand.visibleAnswers),+ top_competitor_visibility: rate(rivals[0]?.mentionAnswers ?? 0),+ competitors: rivals.map((c) => c.name),+ };+}++/** The brand's pages an opportunity can work on, as site_pages would list them. */+function candidatePages(ctx, windowResults) {+ const cited = new Map();+ for (const r of windowResults) {+ for (const c of r.citations ?? []) {+ if (c.url.startsWith(brandUrl(''))) cited.set(c.url, (cited.get(c.url) ?? 0) + 1);+ }+ }+ return SOURCES.brand.map((p) => ({+ url: brandUrl(p.path),+ title: p.label,+ h1: null,+ ai_citations: cited.get(brandUrl(p.path)) ?? 0,+ ga_sessions: null,+ lastmod: null,+ }));+}++/**+ * Every Content row of the demo brand, built in memory: clusters with their+ * members and searches, opportunities, drafts and Plan marks.+ *+ * @param {{ brandId: string, now: Date }} args+ * @param {{ actionFor?: (opportunityKey: string) => string|null }} [links]+ * The action each opportunity was sent to the Action Center as, if any.+ */+export function contentRows({ brandId, now }, { actionFor = () => null } = {}) {+ const ctx = S.demoContext(brandId, now);+ const id = (key) => demoId(brandId, key);+ const at = ([run, hours]) => S.afterRun(ctx.starts, run, hours);+ const latest = ctx.starts.length - 1;+ const since = ctx.rows.brand.created_at;+ const windowFrom = S.utcDay(new Date(now.getTime() - OPPORTUNITY_WINDOW_DAYS * S.DAY_MS));+ const month = S.between(ctx.rows.results, windowFrom, S.utcDay(now));++ // Clusters, as replace_prompt_clusters writes them.+ const clusterId = (key) => id(`cluster:${key}`);+ const clusteredAt = S.afterRun(ctx.starts, 0, 1).toISOString();+ const clusters = CLUSTERS.map((c) => ({+ id: clusterId(c.key),+ brand_id: brandId,+ topic_id: id(`topic:${c.topic}`),+ label: c.label,+ primary_intent: c.intent,+ secondary_intents: c.secondary,+ created_at: clusteredAt,+ updated_at: clusteredAt,+ }));+ const members = CLUSTERS.flatMap((c) =>+ c.prompts.map((key) => ({ prompt_id: ctx.promptId(key), cluster_id: clusterId(c.key) })),+ );+ const scopes = TOPICS.map((t) => ({+ brand_id: brandId,+ topic_id: id(`topic:${t.key}`),+ fingerprint: scopeFingerprint(+ ctx.rows.prompts+ .filter((p) => p.topic_id === id(`topic:${t.key}`))+ .map((p) => ({ id: p.id, text: p.text })),+ ),+ clustered_at: clusteredAt,+ }));++ // The searches engines ran for each cluster's prompts this month (refreshBaskets).+ const searched = new Map();+ for (const r of month) {+ for (const q of r.search_queries ?? []) {+ const key = `${r.prompt_id}\n${q.query}`;+ searched.set(key, (searched.get(key) ?? 0) + 1);+ }+ }+ const clusterOf = new Map(members.map((m) => [m.prompt_id, m.cluster_id]));+ const byCluster = clusterQueries(+ [...searched]+ .filter(([, times]) => times >= MIN_QUERY_ANSWERS)+ .map(([key, times]) => [...key.split('\n'), times]),+ clusterOf,+ );+ const judgedAt = S.afterRun(ctx.starts, latest, 1).toISOString();+ const queries = [...byCluster].flatMap(([cluster, list]) =>+ list.slice(0, MAX_QUERIES_PER_CLUSTER).map(({ query, times }) => ({+ cluster_id: cluster,+ query,+ times_searched: times,+ included: true,+ reason: '',+ judged_at: judgedAt,+ last_seen_at: judgedAt,+ })),+ );++ // The opportunities, measured as the generator measures them.+ const byPrompt = new Map(+ ctx.rows.prompts.map((p) => {+ const v = ctx.volume(p.id);+ return [+ p.id,+ {+ text: p.text,+ volume: v && { est_ai_volume: v.est_ai_volume, intent: v.intent, keywords: v.keywords },+ metrics: promptMetrics(month.filter((r) => r.prompt_id === p.id)),+ },+ ];+ }),+ );+ const pages = candidatePages(ctx, month);+ const types = assetTypes('ecommerce');+ const topicName = (key) => TOPICS.find((t) => t.key === key).name;++ const opportunities = OPPORTUNITIES.map((o) => {+ const cluster = CLUSTERS.find((c) => c.key === o.cluster);+ const promptIds = cluster.prompts.map((key) => ctx.promptId(key));+ const metrics = clusterMetrics(promptIds, byPrompt);+ const components = scoreComponents(metrics);+ const pageIndex = (path) => pages.findIndex((p) => p.url === brandUrl(path));+ const assets = buildAssets(+ {+ type: o.asset.type,+ channel: o.type,+ decision: o.asset.decision,+ pageIndexes: o.asset.pages.map(pageIndex),+ title: o.title,+ },+ o.supporting.map((a) => ({ ...a, pageIndexes: a.pages.map(pageIndex) })),+ pages,+ types,+ );+ const list = byCluster.get(clusterId(cluster.key)) ?? [];+ const createdAt = at(o.created).toISOString();+ const actionId = actionFor(o.cluster);+ return {+ id: id(`opportunity:${o.cluster}`),+ brand_id: brandId,+ cluster_id: clusterId(cluster.key),+ related_cluster_ids: [],+ prompt_id: metrics.representative?.id ?? null,+ title: o.title,+ description: o.description(metrics),+ type: o.type,+ impact: o.impact,+ opportunity_score: opportunityScore(components),+ status: o.status,+ source: 'system',+ decision: assets[0].decision,+ source_data: {+ promptText: metrics.representative?.text,+ clusterLabel: cluster.label,+ topicName: topicName(cluster.topic),+ relatedTopics: [],+ prompts: promptIds.map((pid) => byPrompt.get(pid).text),+ estAiVolume: metrics.demand,+ visibilityScore: metrics.visibility,+ topCompetitorVisibility: metrics.topCompetitorVisibility,+ competitorGap: metrics.competitorGap,+ intent: metrics.intent,+ keywords: metrics.keywords,+ competitorsCited: metrics.competitorsCited,+ queries: {+ included: list.length,+ excluded: 0,+ top: list.slice(0, QUERIES_KEPT).map((q) => ({ query: q.query, timesSearched: q.times })),+ },+ scoreComponents: components,+ windowDays: OPPORTUNITY_WINDOW_DAYS,+ targetPages: assets[0].pages,+ assets,+ ...(o.dismissReason ? { dismissReason: o.dismissReason } : {}),+ ...(actionId ? { actions: { [WHOLE]: actionId } } : {}),+ },+ created_at: createdAt,+ updated_at: createdAt,+ };+ });++ // The drafts the Library lists and the Editor opens.+ const opportunityId = (key) => id(`opportunity:${key}`);+ const drafts = DRAFTS.map((d) => ({+ id: id(`draft:${d.key}`),+ brand_id: brandId,+ title: d.title,+ page_type: d.pageType,+ page_type_source: 'detected',+ method: d.method,+ status: d.status,+ body_html: d.bodyHtml,+ author: d.author,+ created_by: null,+ opportunity_id: opportunityId(d.opportunity),+ prompt_ids: d.prompts.map((key) => ctx.promptId(key)),+ source_url: d.sourcePath ? brandUrl(d.sourcePath) : null,+ action_id: actionFor(d.opportunity),+ slug: d.slug ?? null,+ meta_title: d.metaTitle ?? null,+ meta_description: d.metaDescription ?? null,+ published_url: d.publishedPath ? brandUrl(d.publishedPath) : null,+ published_at: d.published ? at(d.published).toISOString() : null,+ created_at: at(d.created).toISOString(),+ updated_at: at(d.updated).toISOString(),+ }));++ // Plan's priority marks (CE: "Send to Plan").+ const marks = OPPORTUNITIES.filter((o) => o.priority).map((o) => ({+ brand_id: brandId,+ row_key: `opportunity:${opportunityId(o.cluster)}`,+ priority: true,+ hidden_at: null,+ updated_by: null,+ updated_at: since,+ }));++ return { clusters, members, scopes, queries, opportunities, drafts, marks };+}++/** The opportunity sent to the Action Center (from-opportunity.js), for the action built from it. */+export const SENT_OPPORTUNITY = 'sensitive-stomach';+export { OPPORTUNITY_ACTION_KIND };++/** Its tables' key columns where a row has no `id` of its own. */+const KEYS = {+ prompt_cluster_members: 'prompt_id',+ prompt_cluster_queries: 'cluster_id,query',+ prompt_cluster_scopes: 'brand_id,topic_id',+ content_plan_marks: 'brand_id,row_key',+};+/** Its tables without a brand_id, found through their cluster. */+const SCOPES = {+ prompt_cluster_members: ['cluster_id', 'prompt_clusters'],+ prompt_cluster_queries: ['cluster_id', 'prompt_clusters'],+};++/**+ * The Content module. Cluster members and searches hang off the clusters+ * (no brand_id of their own) and go with them.+ */+export const content = {+ name: 'content',+ // A draft points at the action its opportunity was sent as.+ after: 'actionCenter',+ // Rebuilt in place (write.js): written over, what isn't written again deleted after.+ inPlace: true,+ keys: KEYS,+ scopes: SCOPES,+ tables: [+ 'prompt_cluster_scopes',+ 'prompt_clusters',+ 'content_opportunities',+ 'content_drafts',+ 'content_plan_marks',+ ],++ /**+ * Each step's independent tables side by side, through the build's+ * writer (a writer over `db` for a first build without one).+ *+ * @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 sent = demoId(brandId, `action:opportunity:${SENT_OPPORTUNITY}`);+ const rows = contentRows(+ { brandId, now },+ { actionFor: (key) => (key === SENT_OPPORTUNITY ? sent : null) },+ );+ await allSettledOrThrow([+ write('prompt_clusters', rows.clusters),+ write('prompt_cluster_scopes', rows.scopes),+ write('content_plan_marks', rows.marks),+ ]);+ // Members, searches and opportunities point at their cluster; the drafts+ // at their opportunity.+ await allSettledOrThrow([+ write('prompt_cluster_members', rows.members),+ write('prompt_cluster_queries', rows.queries),+ write('content_opportunities', rows.opportunities),+ ]);+ await write('content_drafts', rows.drafts);+ return {+ clusters: rows.clusters.length,+ opportunities: rows.opportunities.length,+ drafts: rows.drafts.length,+ };+ },+};diff --git a/server/src/lib/demo/content.test.js b/server/src/lib/demo/content.test.jsnew file mode 100644index 000000000..119804d6d--- /dev/null+++ b/server/src/lib/demo/content.test.js@@ -0,0 +1,146 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('../../config/supabase.js', () => ({ default: {} }));++const { content, contentRows, OPPORTUNITIES, SENT_OPPORTUNITY } = await import('./content.js');+const { actionCenterRows } = await import('./action-center.js');+const { coreRows } = await import('./core.js');+const { demoId } = await import('./random.js');+const { scopeFingerprint } = await import('../prompt-clusters.js');+const { VALID_OPPORTUNITY_STATUSES } = await import('../opportunity-status.js');++/**+ * The demo brand's Content (demo-workflows): clusters over its prompts,+ * opportunities measured on its answers, Editor drafts and Plan marks.+ */++const BRAND_ID = '11111111-2222-4333-8444-555555555555';+const NOW = new Date('2026-10-28T12:00:00Z');+const DAY = 86_400_000;+const core = coreRows({ brandId: BRAND_ID, now: NOW });+const sentAction = demoId(BRAND_ID, `action:opportunity:${SENT_OPPORTUNITY}`);+const rows = contentRows(+ { brandId: BRAND_ID, now: NOW },+ { actionFor: (key) => (key === SENT_OPPORTUNITY ? sentAction : null) },+);++describe('contentRows', () => {+ it('clusters every tracked prompt once, within its own topic', () => {+ expect(rows.members.map((m) => m.prompt_id).sort()).toEqual(+ core.prompts.map((p) => p.id).sort(),+ );+ const clusterTopic = new Map(rows.clusters.map((c) => [c.id, c.topic_id]));+ for (const m of rows.members) {+ expect(clusterTopic.get(m.cluster_id)).toBe(+ core.prompts.find((p) => p.id === m.prompt_id).topic_id,+ );+ }+ expect(rows.scopes).toHaveLength(core.topics.length);+ for (const s of rows.scopes) {+ const inTopic = core.prompts.filter((p) => p.topic_id === s.topic_id);+ expect(s.fingerprint).toBe(scopeFingerprint(inTopic.map(({ id, text }) => ({ id, text }))));+ }+ const clusterIds = new Set(rows.clusters.map((c) => c.id));+ expect(rows.queries.length).toBeGreaterThan(0);+ for (const q of rows.queries) {+ expect(clusterIds.has(q.cluster_id)).toBe(true);+ expect(q.times_searched).toBeGreaterThanOrEqual(2);+ }+ });++ it('writes ten opportunities in the generator’s shape, across their statuses', () => {+ expect(rows.opportunities).toHaveLength(OPPORTUNITIES.length);+ expect(OPPORTUNITIES.length).toBeGreaterThanOrEqual(8);+ expect(new Set(rows.opportunities.map((o) => o.status))).toEqual(+ new Set(['new', 'reviewed', 'in_progress', 'done', 'dismissed']),+ );+ const clusterIds = new Set(rows.clusters.map((c) => c.id));+ for (const o of rows.opportunities) {+ expect(VALID_OPPORTUNITY_STATUSES).toContain(o.status);+ expect(clusterIds.has(o.cluster_id)).toBe(true);+ expect(core.prompts.some((p) => p.id === o.prompt_id)).toBe(true);+ expect(o.opportunity_score).toBeGreaterThan(0);+ expect(o.opportunity_score).toBeLessThanOrEqual(100);+ expect(o.description).not.toMatch(/undefined|NaN/);+ expect(o.source_data).toMatchObject({+ windowDays: 30,+ assets: expect.any(Array),+ scoreComponents: expect.any(Object),+ });+ expect(o.decision).toBe(o.source_data.assets[0].decision);+ for (const page of o.source_data.targetPages)+ expect(page.url).toMatch(/^https:\/\/brewline\.example\//);+ }+ expect(rows.opportunities.filter((o) => o.type === 'earned')).toHaveLength(2);+ });++ it('opens the agent’s draft in the Editor, linked to the action its opportunity was sent as', () => {+ expect(rows.drafts).toHaveLength(3);+ const agent = rows.drafts.find((d) => d.author === 'agent');+ expect(agent).toMatchObject({ status: 'draft', method: 'create', action_id: sentAction });+ expect(agent.body_html).toMatch(/^<h1>/);+ expect(agent.opportunity_id).toBe(demoId(BRAND_ID, `opportunity:${SENT_OPPORTUNITY}`));+ const sent = rows.opportunities.find((o) => o.id === agent.opportunity_id);+ expect(sent).toMatchObject({+ status: 'in_progress',+ source_data: { actions: { all: sentAction } },+ });++ const published = rows.drafts.find((d) => d.status === 'published');+ expect(published.published_url).toMatch(/^https:\/\/brewline\.example\//);+ for (const d of rows.drafts) {+ for (const id of d.prompt_ids) expect(core.prompts.some((p) => p.id === id)).toBe(true);+ expect(d.body_html).not.toMatch(/https?:\/\/(?![\w.-]+\.example\b)/);+ }+ });++ it('marks its priorities on Plan by opportunity, and dates it all in the month', () => {+ const ids = new Set(rows.opportunities.map((o) => o.id));+ expect(rows.marks.length).toBeGreaterThan(0);+ for (const m of rows.marks) expect(ids.has(m.row_key.replace('opportunity:', ''))).toBe(true);+ for (const at of [...rows.opportunities, ...rows.drafts].map((r) => r.created_at)) {+ expect(Date.parse(at)).toBeLessThanOrEqual(NOW.getTime());+ expect(NOW.getTime() - Date.parse(at)).toBeLessThan(31 * DAY);+ }+ });++ it('matches the action the Action Center sends the opportunity as', async () => {+ const ac = await actionCenterRows({ brandId: BRAND_ID, now: NOW });+ const action = ac.actions.find((a) => a.id === sentAction);+ expect(action).toMatchObject({ kind: 'content_opportunity', status: 'in_progress' });+ expect(action.payload.opportunityId).toBe(demoId(BRAND_ID, `opportunity:${SENT_OPPORTUNITY}`));+ expect(action.payload.promptIds).toEqual([+ core.prompts.find((p) => p.text.includes('sensitive')).id,+ ]);+ });+});++describe('content.build', () => {+ it('writes clusters before what points at them, the drafts after their opportunities', async () => {+ const written = [];+ const keys = {};+ const db = {+ from: (table) => ({+ upsert: async (list, { onConflict }) => {+ written.push([table, list]);+ keys[table] = onConflict;+ return { error: null };+ },+ }),+ };+ const built = await content.build({ brandId: BRAND_ID, now: NOW, db });+ expect(keys).toMatchObject({+ prompt_clusters: 'id',+ prompt_cluster_members: 'prompt_id',+ prompt_cluster_queries: 'cluster_id,query',+ prompt_cluster_scopes: 'brand_id,topic_id',+ content_plan_marks: 'brand_id,row_key',+ });+ const order = written.map(([table]) => table);+ expect(order.indexOf('prompt_clusters')).toBeLessThan(order.indexOf('prompt_cluster_members'));+ expect(order.indexOf('content_opportunities')).toBeLessThan(order.indexOf('content_drafts'));+ expect(built).toEqual({ clusters: 11, opportunities: 10, drafts: 3 });+ const drafts = written.find(([table]) => table === 'content_drafts')[1];+ expect(drafts.find((d) => d.author === 'agent').action_id).toBe(sentAction);+ });+});diff --git a/server/src/lib/demo/coverage.js b/server/src/lib/demo/coverage.jsindex 4c9594d33..455f406f1 100644--- a/server/src/lib/demo/coverage.js+++ b/server/src/lib/demo/coverage.js@@ -22,38 +22,25 @@ export const SKIPPED = {"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.",+ action_candidates:+ "The nightly engine's queue of findings not yet raised as actions: no page reads it, and the engine never runs for a demo brand.",+ action_task_runs:+ "The audit trail of the agent's tool runs on a task: no page reads it, and no agent runs for a demo brand.",+ signal_runs:+ "The nightly signal pass's run log (one row per tracking run it covered): no page reads it, and the pass never runs for a demo brand.",+ content_author_defaults:+ "A brand's default author points at one of the organization's own content_authors: the demo adds no people to the person's organization, so its drafts name no author.",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,@@ -75,6 +62,8 @@ export const PENDING = {page_opportunities: SITE,brand_cms_connections: SITE,content_draft_deliveries: SITE,+ // A draft's shopping path check reads the products it links to: the catalog demo-site builds.+ content_shopping_checks: SITE,catalog_sources: SITE,catalog_products: SITE,catalog_variants: SITE,diff --git a/server/src/lib/demo/coverage.test.js b/server/src/lib/demo/coverage.test.jsindex 0e1037f69..5403de3ad 100644--- a/server/src/lib/demo/coverage.test.js+++ b/server/src/lib/demo/coverage.test.js@@ -55,6 +55,14 @@ describe('the demo brand covers every brand-scoped table', () => {}});+ it('builds in an order its rows can point back in', () => {+ const names = DEMO_MODULES.map((module) => module.name);+ expect(names[0]).toBe('core');+ // A Content draft points at the action its opportunity was sent as.+ expect(names.indexOf('actionCenter')).toBeGreaterThan(0);+ expect(names.indexOf('actionCenter')).toBeLessThan(names.indexOf('content'));+ });+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();diff --git a/server/src/lib/demo/index.js b/server/src/lib/demo/index.jsindex 04b73f02d..daf40fce9 100644--- a/server/src/lib/demo/index.js+++ b/server/src/lib/demo/index.js@@ -17,12 +17,19 @@import supabaseAdmin from '../../config/supabase.js';import { logger } from '../logger.js';+import { actionCenter } from './action-center.js';import { BRAND } from './brewline.js';+import { content } from './content.js';import { core } from './core.js';+import { reports } from './reports.js';+import { suggestions } from './suggestions.js';import { demoWriter } from './write.js';-/** Bump to rebuild every demo brand on its next visit. */-export const DEMO_VERSION = 1;+/**+ * Bump to rebuild every demo brand on its next visit.+ * 2: Action Center, Content, suggestions and reports (demo-workflows).+ */+export const DEMO_VERSION = 2;/** 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;@@ -54,10 +61,11 @@ const WAIT_POLL_MS = 1000;* 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.+ * (Content after the Action Center: a draft points at the action its+ * opportunity was sent as.) Site Audit, traffic and Product Visibility+ * follow as modules of their own.*/-export const DEMO_MODULES = [core];+export const DEMO_MODULES = [core, suggestions, actionCenter, content, reports];const COLUMNS = 'id, demo_version, demo_built_at, demo_hidden_at';diff --git a/server/src/lib/demo/reports.js b/server/src/lib/demo/reports.jsnew file mode 100644index 000000000..1b028da66--- /dev/null+++ b/server/src/lib/demo/reports.js@@ -0,0 +1,352 @@+/**+ * The demo brand's saved reports (demo-workflows): a weekly visibility+ * summary and a competitor benchmark, as the Reports page lists them and+ * the detail page renders them, purely from the stored payload (00023).+ *+ * A report is gathered by the web app (web/src/lib/actions/reports.ts) and+ * stored whole, so the server has no builder to call: the payload here+ * follows its ReportPayload shape section by section, with every number+ * counted from the demo's answers over the report's window (stats.js), and+ * a summary written from those numbers where the web asks a model for one.+ */++import supabaseAdmin from '../../config/supabase.js';+import { IMPROVE_PLATFORM_LABELS } from '../prompt-improve.js';+import { BRAND, TOPICS } from './brewline.js';+import { demoId } from './random.js';+import { demoWriter } from './write.js';+import * as S from './stats.js';++const TEMPLATE_TITLES = {+ weekly_visibility: 'Weekly Visibility Summary',+ competitor_benchmark: 'Competitor Benchmark',+};++const round1 = (n) => Math.round(n * 10) / 10;+const mean = (xs) => (xs.length ? xs.reduce((s, x) => s + x, 0) / xs.length : 0);+const percentChange = (cur, prev) => (prev > 0 ? Math.round(((cur - prev) / prev) * 100) : null);++/** The answers in [from, to), by their timestamps. */+const within = (results, from, to) =>+ results.filter((r) => r.created_at >= from.toISOString() && r.created_at < to.toISOString());++/** The Insights KPIs over a window and the one before it (getInsightsSummary). */+function insights(cur, prev) {+ const c = S.brandStats(cur);+ const p = S.brandStats(prev);+ const avgVis = (rows) => round1(mean(rows.map((r) => r.visibility_score ?? 0)));+ const positivePct = (b) =>+ b.mentionAnswers ? Math.round((b.positive / b.mentionAnswers) * 100) : 0;+ const rates = (rows, b) => {+ const positions = rows.map((r) => r.mention_position).filter((x) => x > 0);+ return {+ citationRate: b.answers ? round1((b.citationAnswers / b.answers) * 100) : null,+ netSentiment: b.mentionAnswers+ ? round1(((b.positive - b.negative) / b.mentionAnswers) * 100)+ : null,+ avgPosition: positions.length ? round1(mean(positions)) : null,+ };+ };+ const cr = rates(cur, c);+ const pr = rates(prev, p);+ // Changes need answers on both sides, as the Insights page asks.+ const both = cur.length > 0 && prev.length > 0;+ const diff = (a, b) => (!both || a === null || b === null ? null : round1(a - b));+ return {+ avgVisibilityScore: avgVis(cur),+ totalMentions: c.mentions,+ totalCitations: c.citations,+ positiveSentimentPct: positivePct(c),+ totalResults: c.answers,+ lastCheckedAt: cur.at(-1)?.created_at ?? null,+ platformBreakdown: [...S.groupBy(cur, 'model_used')].map(([platform, rows]) => ({+ platform,+ avgScore: Math.round(mean(rows.map((r) => r.visibility_score ?? 0))),+ resultCount: rows.length,+ })),+ visibilityChange: both ? round1(avgVis(cur) - avgVis(prev)) : null,+ mentionsChange: both ? percentChange(c.mentions, p.mentions) : null,+ citationsChange: both ? percentChange(c.citations, p.citations) : null,+ prevMentions: both ? p.mentions : null,+ prevCitations: both ? p.citations : null,+ sentimentChange: both ? positivePct(c) - positivePct(p) : null,+ citationRate: cr.citationRate,+ citationRateChange: diff(cr.citationRate, pr.citationRate),+ negativeSentimentPct: c.mentionAnswers ? Math.round((c.negative / c.mentionAnswers) * 100) : 0,+ netSentiment: cr.netSentiment,+ netSentimentChange: diff(cr.netSentiment, pr.netSentiment),+ avgPosition: cr.avgPosition,+ avgPositionChange: diff(cr.avgPosition, pr.avgPosition),+ mentioningResults: c.mentionAnswers,+ positionedResults: cur.filter((r) => r.mention_position > 0).length,+ };+}++/** The prompt-level Visibility Rate and the AI Visibility Score (getReportVisibilityRate). */+function visibilityRate(rows) {+ const b = S.brandStats(rows);+ const prompts = new Set(rows.map((r) => r.prompt_id));+ const visible = new Set(+ rows.filter((r) => r.mention_count > 0 || r.citation_count > 0).map((r) => r.prompt_id),+ );+ return {+ visiblePrompts: visible.size,+ promptCount: prompts.size,+ ratePct: prompts.size ? round1((visible.size / prompts.size) * 100) : 0,+ score: b.score,+ mentionAnswers: b.mentionAnswers,+ citationAnswers: b.citationAnswers,+ positionFactor: b.positionFactor,+ };+}++/** One point a tracked day: the brand's score and its rivals' average. */+function trend(rows) {+ return [+ ...S.groupBy(+ rows.map((r) => ({ ...r, day: S.utcDay(r.created_at) })),+ 'day',+ ),+ ]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([date, dayRows]) => {+ const rivals = [...S.competitorStats(dayRows).values()].map((c) => c.score);+ return {+ date,+ score: S.brandStats(dayRows).score ?? 0,+ competitors: rivals.length ? round1(mean(rivals)) : null,+ };+ });+}++/** Share of voice, overall and by engine, against the window before. */+function shareOfVoice(cur, prev) {+ const overall = S.shareOfVoice(cur) ?? 0;+ const before = S.shareOfVoice(prev);+ return {+ overallSov: overall,+ overallSovChange: before === null ? null : round1(overall - before),+ byPlatform: [...S.groupBy(cur, 'platform')].map(([provider, rows]) => {+ const brandMentions = S.brandStats(rows).mentionAnswers;+ const competitorMentions = [...S.competitorStats(rows).values()].reduce(+ (s, c) => s + c.mentionAnswers,+ 0,+ );+ return {+ provider,+ brandMentions,+ competitorMentions,+ sov: S.shareOfVoice(rows) ?? 0,+ };+ }),+ };+}++/** The brand beside each rival (getCompetitorComparison). */+function competitors(cur, prev) {+ const promptCount = new Set(cur.map((r) => r.prompt_id)).size;+ const visiblePrompts = (rows, named) => new Set(rows.filter(named).map((r) => r.prompt_id)).size;+ const rate = (n) => (promptCount ? round1((n / promptCount) * 100) : 0);++ const b = S.brandStats(cur);+ const pb = S.brandStats(prev);+ const ownVisible = visiblePrompts(cur, (r) => r.mention_count > 0);+ const ownPrevVisible = visiblePrompts(prev, (r) => r.mention_count > 0);+ const own = {+ name: BRAND.name,+ avgVisibilityScore: round1(mean(cur.map((r) => r.visibility_score ?? 0))),+ visibilityRate: rate(ownVisible),+ visiblePrompts: ownVisible,+ promptCount,+ change: prev.length ? round1(rate(ownVisible) - rate(ownPrevVisible)) : null,+ score: b.score,+ scoreChange: pb.score === null ? null : round1(b.score - pb.score),+ mentionAnswers: b.mentionAnswers,+ citationAnswers: b.citationAnswers,+ positionFactor: b.positionFactor,+ totalMentions: b.mentions,+ totalCitations: b.citations,+ resultCount: b.answers,+ isOwnBrand: true,+ };++ const before = S.competitorStats(prev);+ const rivals = [...S.competitorStats(cur).values()].map((c) => {+ const named = (r) =>+ (r.competitor_mentions ?? []).some((m) => m.name === c.name && m.mention_count > 0);+ const visible = visiblePrompts(cur, named);+ const prevVisible = visiblePrompts(prev, named);+ const p = before.get(c.name);+ const scores = cur.flatMap((r) =>+ (r.competitor_mentions ?? [])+ .filter((m) => m.name === c.name)+ .map((m) => m.visibility_score ?? 0),+ );+ return {+ name: c.name,+ avgVisibilityScore: round1(mean(scores)),+ visibilityRate: rate(visible),+ visiblePrompts: visible,+ promptCount,+ change: prev.length ? round1(rate(visible) - rate(prevVisible)) : null,+ score: c.score,+ scoreChange: p?.score == null ? null : round1(c.score - p.score),+ mentionAnswers: c.mentionAnswers,+ citationAnswers: c.citationAnswers,+ positionFactor: Math.round(c.positionFactor * 1000) / 1000,+ totalMentions: c.mentions,+ totalCitations: cur.reduce(+ (s, r) =>+ s ++ (r.competitor_mentions ?? [])+ .filter((m) => m.name === c.name)+ .reduce((n, m) => n + (m.citation_count ?? 0), 0),+ 0,+ ),+ resultCount: cur.length,+ isOwnBrand: false,+ competitorId: c.id,+ };+ });+ return [own, ...rivals.sort((a, b2) => b2.score - a.score)];+}++/** Each topic's visibility against the window before (getTopicPerformance). */+function topicPerformance(ctx, cur, prev) {+ return TOPICS.map((t) => {+ const ids = new Set(+ ctx.rows.prompts+ .filter((p) => p.topic_id === demoId(ctx.brandId, `topic:${t.key}`))+ .map((p) => p.id),+ );+ const rows = cur.filter((r) => ids.has(r.prompt_id));+ const before = prev.filter((r) => ids.has(r.prompt_id));+ const b = S.brandStats(rows);+ const pb = S.brandStats(before);+ return {+ name: t.name,+ avgVisibility: round1(mean(rows.map((r) => r.visibility_score ?? 0))),+ visibilityRate: b.answers ? round1((b.visibleAnswers / b.answers) * 100) : 0,+ score: b.score,+ change: pb.score === null || b.score === null ? null : round1(b.score - pb.score),+ results: b.answers,+ };+ });+}++const signed = (n, unit = '') => `${n > 0 ? '+' : ''}${n}${unit}`;++/** The prose the summary model writes, from the same numbers. */+function weeklySummary(payload) {+ const { insights: i, visibilityRate: v, shareOfVoice: sov } = payload;+ const best = [...sov.byPlatform].sort((a, b) => b.sov - a.sov)[0];+ return [+ `${BRAND.name} appeared in answers to ${v.visiblePrompts} of its ${v.promptCount} tracked prompts this week, with an AI Visibility Score of ${v.score}.`,+ `Mentions ${i.mentionsChange === null ? 'held steady' : `moved ${signed(i.mentionsChange, '%')}`} against the week before, and ${i.positiveSentimentPct}% of the answers naming the brand were positive.`,+ `Share of voice stands at ${sov.overallSov}%${sov.overallSovChange === null ? '' : ` (${signed(sov.overallSovChange, ' pts')})`}, strongest on ${IMPROVE_PLATFORM_LABELS[best.provider] ?? best.provider}.`,+ ].join(' ');+}++function benchmarkSummary(payload) {+ const [own, ...rivals] = payload.competitors;+ const leader = rivals[0];+ const topics = [...payload.topicPerformance].sort((a, b) => (b.score ?? 0) - (a.score ?? 0));+ return [+ `${leader.name} leads the tracked set with a score of ${leader.score}, against ${own.score} for ${BRAND.name}.`,+ `${BRAND.name} is visible on ${own.visiblePrompts} of ${own.promptCount} prompts and holds ${payload.shareOfVoice.overallSov}% share of voice.`,+ `By topic it scores highest in ${topics[0].name} (${topics[0].score}) and lowest in ${topics.at(-1).name} (${topics.at(-1).score}).`,+ ].join(' ');+}++/**+ * The demo's saved reports, built in memory.+ *+ * @param {{ brandId: string, now: Date }} args+ */+export function reportRows({ brandId, now }) {+ const ctx = S.demoContext(brandId, now);+ const latest = ctx.starts.length - 1;+ const results = ctx.rows.results;++ const make = (template, key, to, days, build) => {+ const from = new Date(to.getTime() - days * S.DAY_MS);+ const prevFrom = new Date(from.getTime() - days * S.DAY_MS);+ const cur = within(results, from, to);+ const prev = within(results, prevFrom, from);+ const payload = build(cur, prev);+ return {+ id: demoId(brandId, `report:${key}`),+ brand_id: brandId,+ title: `${BRAND.name} — ${TEMPLATE_TITLES[template]} (${S.utcDay(from)} → ${S.utcDay(to)})`,+ template,+ date_from: from.toISOString(),+ date_to: to.toISOString(),+ payload,+ created_by: null,+ created_at: to.toISOString(),+ };+ };++ const weekly = make(+ 'weekly_visibility',+ 'weekly',+ // Made before the morning's run, so the week compares two runs with two.+ S.afterRun(ctx.starts, latest, -1),+ 7,+ (cur, prev) => {+ const payload = {+ brandName: BRAND.name,+ insights: insights(cur, prev),+ visibilityRate: visibilityRate(cur),+ visibilityTrend: trend(cur),+ shareOfVoice: shareOfVoice(cur, prev),+ };+ return { ...payload, summaryText: weeklySummary(payload) };+ },+ );++ const benchmark = make(+ 'competitor_benchmark',+ 'benchmark',+ S.afterRun(ctx.starts, latest - 1, 3),+ 30,+ (cur, prev) => {+ const payload = {+ brandName: BRAND.name,+ insights: insights(cur, prev),+ visibilityRate: visibilityRate(cur),+ shareOfVoice: shareOfVoice(cur, prev),+ competitors: competitors(cur, prev),+ topicPerformance: topicPerformance(ctx, cur, prev),+ };+ return { ...payload, summaryText: benchmarkSummary(payload) };+ },+ );++ return [benchmark, weekly];+}++/** The reports module. */+export const reports = {+ name: 'reports',+ // Rebuilt in place (write.js): written over, what isn't written again deleted after.+ inPlace: true,+ tables: ['reports'],++ /**+ * Through the build's writer (a writer over `db` for a first build without one).+ *+ * @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 }).write,+ }) {+ const rows = reportRows({ brandId, now });+ await write('reports', rows);+ return { reports: rows.length };+ },+};diff --git a/server/src/lib/demo/reports.test.js b/server/src/lib/demo/reports.test.jsnew file mode 100644index 000000000..1f77b5358--- /dev/null+++ b/server/src/lib/demo/reports.test.js@@ -0,0 +1,83 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('../../config/supabase.js', () => ({ default: {} }));++const { reportRows, reports } = await import('./reports.js');+const { coreRows } = await import('./core.js');++/**+ * The demo brand's saved reports (demo-workflows): a weekly visibility+ * summary and a competitor benchmark, counted from the demo's answers.+ */++const BRAND_ID = '11111111-2222-4333-8444-555555555555';+const NOW = new Date('2026-10-28T12:00:00Z');+const DAY = 86_400_000;+const core = coreRows({ brandId: BRAND_ID, now: NOW });+const [benchmark, weekly] = reportRows({ brandId: BRAND_ID, now: NOW });++describe('reportRows', () => {+ it('saves the two reports with their templates’ sections', () => {+ expect(weekly.template).toBe('weekly_visibility');+ expect(Object.keys(weekly.payload).sort()).toEqual(+ [+ 'brandName',+ 'insights',+ 'shareOfVoice',+ 'summaryText',+ 'visibilityRate',+ 'visibilityTrend',+ ].sort(),+ );+ expect(benchmark.template).toBe('competitor_benchmark');+ expect(benchmark.payload).toHaveProperty('competitors');+ expect(benchmark.payload).toHaveProperty('topicPerformance');+ for (const r of [weekly, benchmark]) {+ expect(r.title).toMatch(/^Brewline Coffee — .+ \(\d{4}-\d{2}-\d{2} → \d{4}-\d{2}-\d{2}\)$/);+ expect(r.payload.summaryText.length).toBeGreaterThan(80);+ expect(JSON.stringify(r.payload)).not.toMatch(/undefined|NaN/);+ }+ });++ it('spans its window, ending before now', () => {+ expect(Date.parse(weekly.date_to) - Date.parse(weekly.date_from)).toBe(7 * DAY);+ expect(Date.parse(benchmark.date_to) - Date.parse(benchmark.date_from)).toBe(30 * DAY);+ for (const r of [weekly, benchmark]) {+ expect(Date.parse(r.created_at)).toBeLessThanOrEqual(NOW.getTime());+ }+ });++ it('counts what the demo’s answers say over the window', () => {+ const inWeek = core.results.filter(+ (r) => r.created_at >= weekly.date_from && r.created_at < weekly.date_to,+ );+ expect(weekly.payload.insights.totalResults).toBe(inWeek.length);+ expect(weekly.payload.visibilityRate.promptCount).toBe(12);+ expect(weekly.payload.visibilityTrend.length).toBeGreaterThan(1);++ const [own, ...rivals] = benchmark.payload.competitors;+ expect(own).toMatchObject({ name: 'Brewline Coffee', isOwnBrand: true });+ expect(rivals.map((r) => r.competitorId).sort()).toEqual(+ core.competitors.map((c) => c.id).sort(),+ );+ expect(benchmark.payload.topicPerformance.map((t) => t.name)).toEqual(+ core.topics.map((t) => t.name),+ );+ });+});++describe('reports.build', () => {+ it('writes both reports', async () => {+ let written = null;+ const db = {+ from: (table) => ({+ upsert: async (list) => {+ written = [table, list.length];+ return { error: null };+ },+ }),+ };+ expect(await reports.build({ brandId: BRAND_ID, now: NOW, db })).toEqual({ reports: 2 });+ expect(written).toEqual(['reports', 2]);+ });+});diff --git a/server/src/lib/demo/stats.js b/server/src/lib/demo/stats.jsnew file mode 100644index 000000000..cc07580de--- /dev/null+++ b/server/src/lib/demo/stats.js@@ -0,0 +1,207 @@+/**+ * The demo's own numbers, read from its core rows in memory: what the+ * Action Center, Content and Reports modules say about Brewline Coffee+ * (a signal's "from 34% to 27%", an opportunity's visibility, a report's+ * KPIs) is counted from the same answers the pages read, the way the daily+ * rollups count them (insights_brand_daily, 00164): an answer is mentioning+ * when its mention_count > 0, citing when its citation_count > 0, and its+ * position factor is the mean of 1 / mention_position.+ */++import { computeAiVisibilityScore } from '../../config/visibility-score.js';+import { PROMPTS } from './brewline.js';+import { coreRows, latestRunStart, RUN_EVERY_DAYS, RUNS } from './core.js';++export const DAY_MS = 24 * 60 * 60 * 1000;+export const HOUR_MS = 60 * 60 * 1000;++const round1 = (n) => Math.round(n * 10) / 10;++let cached = null;++/**+ * The core rows a module builds on, with the lookups every module needs.+ * Built once per demo build (same brand, same moment), not once per module.+ *+ * @param {string} brandId+ * @param {Date} now+ */+export function demoContext(brandId, now) {+ if (cached && cached.brandId === brandId && cached.at === now.getTime()) return cached.ctx;+ const rows = coreRows({ brandId, now });+ const promptIds = new Map(PROMPTS.map((p, i) => [p.key, rows.prompts[i].id]));+ const keys = new Map(PROMPTS.map((p, i) => [rows.prompts[i].id, p.key]));+ const volumes = new Map(rows.volumes.map((v) => [v.prompt_id, v]));+ const ctx = {+ brandId,+ now,+ rows,+ starts: runStarts(now),+ /** A prompt's id from its key in brewline.js. */+ promptId: (key) => promptIds.get(key),+ /** A prompt's key from its id. */+ promptKey: (id) => keys.get(id),+ /** A prompt's text from its id. */+ promptText: (id) => rows.prompts.find((p) => p.id === id)?.text ?? '',+ /** A prompt's prompt_volumes row. */+ volume: (id) => volumes.get(id) ?? null,+ competitorId: (name) => rows.competitors.find((c) => c.name === name)?.id ?? null,+ };+ cached = { brandId, at: now.getTime(), ctx };+ return ctx;+}++/** `YYYY-MM-DD` of a date or an ISO string. */+export function utcDay(value) {+ return (typeof value === 'string' ? value : value.toISOString()).slice(0, 10);+}++/** When each of the demo's runs started, oldest first (core's dates). */+export function runStarts(now) {+ const latest = latestRunStart(now);+ return Array.from(+ { length: RUNS },+ (_, i) => new Date(latest.getTime() - (RUNS - 1 - i) * RUN_EVERY_DAYS * DAY_MS),+ );+}++/**+ * A moment counted from one run's start: `afterRun(starts, 7, 2)` is two+ * hours after the eighth run began, when the nightly engine has read it.+ */+export function afterRun(starts, run, hours = 1) {+ return new Date(starts[run].getTime() + hours * HOUR_MS);+}++/** The answers of the given runs (core writes 72 a run, in run order). */+export function runResults(results, runs) {+ const perRun = results.length / RUNS;+ return runs.flatMap((run) => results.slice(run * perRun, (run + 1) * perRun));+}++/** The answers whose day falls in [from, to], both `YYYY-MM-DD`. */+export function between(results, from, to) {+ return results.filter((r) => {+ const day = utcDay(r.created_at);+ return day >= from && day <= to;+ });+}++/** The `days` whole days before `date`'s day (validate.js windowEndingBefore). */+export function windowBefore(date, days) {+ const to = new Date(date.getTime() - DAY_MS);+ return { from: utcDay(new Date(to.getTime() - (days - 1) * DAY_MS)), to: utcDay(to) };+}++/** The `days` whole days after `date`'s day (validate.js windowStartingAfter). */+export function windowAfter(date, days) {+ const from = new Date(date.getTime() + DAY_MS);+ return { from: utcDay(from), to: utcDay(new Date(from.getTime() + (days - 1) * DAY_MS)) };+}++/**+ * What a set of answers says about the brand, as the rollups count it, and+ * its AI Visibility Score (config/visibility-score.js).+ */+export function brandStats(results) {+ const answers = results.length;+ const mentioning = results.filter((r) => r.mention_count > 0);+ const citationAnswers = results.filter((r) => r.citation_count > 0).length;+ const visibleAnswers = results.filter((r) => r.mention_count > 0 || r.citation_count > 0).length;+ const positions = mentioning.map((r) => r.mention_position).filter((p) => p > 0);+ const positionFactor = positions.length+ ? positions.reduce((sum, p) => sum + 1 / p, 0) / positions.length+ : 0;+ return {+ answers,+ mentionAnswers: mentioning.length,+ mentions: mentioning.reduce((sum, r) => sum + r.mention_count, 0),+ citationAnswers,+ citations: results.reduce((sum, r) => sum + (r.citation_count ?? 0), 0),+ visibleAnswers,+ positionFactor: Math.round(positionFactor * 1000) / 1000,+ positive: mentioning.filter((r) => r.sentiment === 'positive').length,+ negative: mentioning.filter((r) => r.sentiment === 'negative').length,+ score: answers+ ? computeAiVisibilityScore({+ answers,+ mentionAnswers: mentioning.length,+ citationAnswers,+ positionFactor,+ })+ : null,+ /** Share of answers naming the brand, in percent. */+ mentionRate: answers ? round1((mentioning.length / answers) * 100) : null,+ };+}++/** The same for each tracked competitor, by name, from the answers' competitor_mentions. */+export function competitorStats(results) {+ const byName = new Map();+ for (const r of results) {+ for (const c of r.competitor_mentions ?? []) {+ const s = byName.get(c.name) ?? {+ id: c.competitor_id,+ name: c.name,+ mentionAnswers: 0,+ mentions: 0,+ citationAnswers: 0,+ inverse: 0,+ positioned: 0,+ };+ if (c.mention_count > 0) {+ s.mentionAnswers += 1;+ s.mentions += c.mention_count;+ }+ if (c.citation_count > 0) s.citationAnswers += 1;+ if (c.mention_position > 0) {+ s.inverse += 1 / c.mention_position;+ s.positioned += 1;+ }+ byName.set(c.name, s);+ }+ }+ const answers = results.length;+ return new Map(+ [...byName].map(([name, s]) => {+ const positionFactor = s.positioned ? s.inverse / s.positioned : 0;+ return [+ name,+ {+ id: s.id,+ name,+ mentionAnswers: s.mentionAnswers,+ mentions: s.mentions,+ citationAnswers: s.citationAnswers,+ positionFactor,+ score: answers+ ? computeAiVisibilityScore({+ answers,+ mentionAnswers: s.mentionAnswers,+ citationAnswers: s.citationAnswers,+ positionFactor,+ })+ : null,+ mentionRate: answers ? round1((s.mentionAnswers / answers) * 100) : null,+ },+ ];+ }),+ );+}++/** Answers grouped by a key of theirs (`prompt_id`, `platform`). */+export function groupBy(results, key) {+ const groups = new Map();+ for (const r of results) {+ if (!groups.has(r[key])) groups.set(r[key], []);+ groups.get(r[key]).push(r);+ }+ return groups;+}++/** Share of voice in percent: the brand's mentioning answers against all named. */+export function shareOfVoice(results) {+ const brand = brandStats(results).mentionAnswers;+ const rivals = [...competitorStats(results).values()].reduce((s, c) => s + c.mentionAnswers, 0);+ return brand + rivals > 0 ? round1((brand / (brand + rivals)) * 100) : null;+}diff --git a/server/src/lib/demo/suggestions.js b/server/src/lib/demo/suggestions.jsnew file mode 100644index 000000000..a40096f72--- /dev/null+++ b/server/src/lib/demo/suggestions.js@@ -0,0 +1,338 @@+/**+ * The demo brand's suggestions (demo-workflows): prompts and topics to track+ * next, and the Improve tab's suggestions on two of its weakest prompts.+ *+ * Prompt and topic suggestions are stored as the suggestion routes store a+ * model's picks. The Improve sets are built as POST /prompts/:id/improve+ * builds them: each engine's state from the demo's answers (classifyPlatform),+ * its evidence (collectEvidence), and suggestions kept only where they cite+ * that evidence (sanitizeSuggestions). The suggestion wording, the model's+ * part, is written from the evidence here.+ */++import supabaseAdmin from '../../config/supabase.js';+import {+ ACTIONABLE_STATES,+ classifyPlatform,+ collectEvidence,+ IMPROVE_PLATFORM_LABELS,+ improveRangeKey,+ sanitizeSuggestions,+} from '../prompt-improve.js';+import { BRAND, TOPICS } from './brewline.js';+import { demoId } from './random.js';+import { allSettledOrThrow, demoWriter } from './write.js';+import * as S from './stats.js';++/**+ * How long the suggestions stay new. The routes give them 48 hours; the+ * demo's outlive its own rebuild (DEMO_MAX_AGE_MS, three days), so the+ * list never asks to be generated again, which a demo brand can't do.+ */+const FRESH_MS = 4 * S.DAY_MS;++/** Prompts the demo suggests tracking next, by topic. */+export const PROMPT_SUGGESTIONS = [+ {+ topic: 'subscriptions',+ text: 'Which coffee subscription ships the freshest beans?',+ reason:+ 'Freshness is the reason answers give most often for recommending a subscription, and Brewline roasts to order.',+ volume: 880,+ relevance: 0.93,+ },+ {+ topic: 'subscriptions',+ text: 'How much does a coffee subscription cost per month?',+ reason: 'Price comparisons decide many subscription choices, and answers quote rivals’ prices.',+ volume: 1600,+ relevance: 0.86,+ },+ {+ topic: 'subscriptions',+ text: 'Can I change the grind size on my coffee subscription?',+ reason:+ 'A question asked before signing up, close to the flexible-plan prompts already tracked.',+ volume: 140,+ relevance: 0.72,+ },+ {+ topic: 'beans',+ text: 'What are the best coffee beans for a French press?',+ reason: 'A brewing method with steady demand that the tracked espresso prompt doesn’t cover.',+ volume: 3600,+ relevance: 0.81,+ },+ {+ topic: 'beans',+ text: 'Which medium roast coffee beans taste the smoothest?',+ reason: 'Answers about smooth medium roasts name Morning Ritual Co. and rarely Brewline.',+ volume: 1300,+ relevance: 0.78,+ },+ {+ topic: 'buying',+ text: 'What does the roast date on a bag of coffee mean?',+ reason:+ 'Engines cite Brewline’s freshness guide for related questions; this one has demand of its own.',+ volume: 1000,+ relevance: 0.88,+ },+ {+ topic: 'buying',+ text: 'How long does freshly roasted coffee take to ship?',+ reason: 'Shipping speed comes up in answers comparing online roasters.',+ volume: 390,+ relevance: 0.83,+ },+ {+ topic: 'buying',+ text: 'Is direct trade coffee worth paying more for?',+ reason:+ 'Follows the fair trade prompt, where publishers’ roundups decide which roasters appear.',+ volume: 720,+ relevance: 0.69,+ },+];++/** Topics the demo suggests adding. */+export const TOPIC_SUGGESTIONS = [+ {+ name: 'Cold brew coffee',+ reason:+ 'People ask which beans and grinds suit cold brew, and answers name subscription roasters.',+ },+ {+ name: 'Home brewing equipment',+ reason: 'Questions about grinders and brewers often end with which beans to buy.',+ },+ {+ name: 'Office coffee delivery',+ reason: 'Teams compare coffee subscriptions for the office, a need none of the topics covers.',+ },+];++/** The prompts whose Improve tab is filled, and the ranges it is filled for. */+export const IMPROVE_PROMPTS = ['pause-skip', 'buy-online'];+export const IMPROVE_PRESETS = { '30d': 30, '7d': 7 };+/** What the Improve route builds with unless configured otherwise. */+const IMPROVE_MODEL = 'google/gemini-3-flash-preview';++const host = (url) => new URL(url).hostname;++/**+ * One engine's suggestions, worded from its evidence the way the model is+ * asked to: an imperative title, what to do and why, and the evidence it+ * rests on. Only what the evidence holds survives sanitizeSuggestions.+ */+function suggestionsFor(platform, competitors) {+ const { id, label, state, evidence } = platform;+ const rivalDomains = new Set(competitors.map((c) => c.domain));+ const fanout = evidence.fanouts[0]?.query;+ // A publisher, forum or review site: not the brand's, not a rival's.+ const domain = evidence.citedDomains.find((d) => !d.own && !rivalDomains.has(d.domain))?.domain;+ // The rival ranked above, with its own page the engine cites when it has one.+ const rivalUrl = evidence.competitorUrls.find((u) =>+ evidence.competitors.some(+ (c) => competitors.find((x) => x.name === c.name)?.domain === host(u.url),+ ),+ )?.url;+ const rival = rivalUrl+ ? competitors.find((c) => c.domain === host(rivalUrl)).name+ : evidence.competitors[0]?.name;+ const ownPage = evidence.brandPages[0]?.url;+ const out = [];+ if (state === 'not_mentioned') {+ if (fanout) {+ out.push({+ platform: id,+ title: `Answer “${fanout}” on a Brewline page`,+ body: `${label} searched “${fanout}” for this prompt and built its answer from other sites. A page that answers that search directly gives it a Brewline source to use.`,+ sources: [{ type: 'fanout', ref: fanout }],+ confidence: 'high',+ });+ }+ if (domain) {+ out.push({+ platform: id,+ title: `Get listed on ${domain}`,+ body: `${domain} is the site ${label} cites most for this prompt, and its page doesn’t mention Brewline. A product listing or a contributed tip there puts Brewline in the source it trusts.`,+ sources: [{ type: 'domain', ref: domain }],+ confidence: 'medium',+ });+ }+ }+ if (state === 'mentioned_late' && rival) {+ out.push({+ platform: id,+ title: `Lead with what puts ${rival} first`,+ body: `${label} names ${rival} before Brewline here${rivalUrl ? `, citing ${host(rivalUrl)}` : ''}. Say early on the page it cites that every bag ships within a day of roasting and plans can be paused anytime.`,+ sources: rivalUrl+ ? [{ type: 'competitor_url', ref: rivalUrl }]+ : domain+ ? [{ type: 'domain', ref: domain }]+ : [],+ confidence: 'medium',+ });+ }+ if ((state === 'not_cited' || state === 'mentioned_late') && ownPage) {+ out.push({+ platform: id,+ title: 'Make this Brewline page the one it cites',+ body: `${label} names Brewline but rarely cites ${ownPage.replace(/^https?:\/\//, '')}. A short answer to the prompt at the top of that page, with a FAQ below, makes it the source to quote.`,+ sources: [{ type: 'brand_page', ref: ownPage }],+ confidence: 'medium',+ });+ }+ return out;+}++/** One prompt's Improve set over a range, as the route stores it. */+function improveSet(ctx, key, preset, days, generatedAt) {+ const promptId = ctx.promptId(key);+ const from = new Date(ctx.now.getTime() - days * S.DAY_MS).toISOString();+ const rows = ctx.rows.results+ .filter((r) => r.prompt_id === promptId && r.created_at >= from)+ .sort((a, b) => b.created_at.localeCompare(a.created_at));+ const byPlatform = S.groupBy(rows, 'platform');+ const prompt = ctx.rows.prompts.find((p) => p.id === promptId);+ const brandDomains = [BRAND.domain];+ const competitors = ctx.rows.competitors.map((c) => ({ name: c.name, domain: c.domain }));++ const states = Object.keys(IMPROVE_PLATFORM_LABELS)+ .filter((id) => byPlatform.has(id) || prompt.platforms.includes(id))+ .map((id) => ({+ id,+ label: IMPROVE_PLATFORM_LABELS[id],+ ...classifyPlatform(byPlatform.get(id) ?? [], brandDomains),+ }));+ const withEvidence = states+ .filter((p) => ACTIONABLE_STATES.includes(p.state))+ .map((p) => ({+ ...p,+ evidence: collectEvidence(byPlatform.get(p.id) ?? [], {+ brandName: BRAND.name,+ brandDomains,+ competitors,+ latestResponse: byPlatform.get(p.id)[0].response,+ }),+ }));+ const suggestions = sanitizeSuggestions(+ withEvidence.flatMap((p) => suggestionsFor(p, competitors)),+ withEvidence,+ );+ const evidenceById = new Map(withEvidence.map((p) => [p.id, p.evidence]));++ return {+ id: demoId(ctx.brandId, `improve:${key}:${preset}`),+ prompt_id: promptId,+ brand_id: ctx.brandId,+ range_key: improveRangeKey({ preset }),+ region: '',+ platform_states: states.map((p) => {+ const ev = evidenceById.get(p.id);+ return {+ ...p,+ inputs: ev+ ? {+ fanouts: ev.fanouts.length,+ citedDomains: ev.citedDomains.length,+ competitorUrls: ev.competitorUrls.length,+ answer: !!ev.excerpt,+ }+ : null,+ };+ }),+ suggestions,+ sent_actions: [],+ latest_result_at: rows[0]?.created_at ?? null,+ model: withEvidence.length > 0 ? IMPROVE_MODEL : null,+ generated_at: generatedAt.toISOString(),+ };+}++/**+ * Every suggestion row of the demo brand, built in memory.+ *+ * @param {{ brandId: string, now: Date }} args+ */+export function suggestionRows({ brandId, now }) {+ const ctx = S.demoContext(brandId, now);+ const latest = ctx.starts.length - 1;+ // Generated the morning of the latest run, once its answers were in.+ const generatedAt = S.afterRun(ctx.starts, latest, 1);+ const topicId = (key) => demoId(brandId, `topic:${key}`);+ const topicName = (key) => TOPICS.find((t) => t.key === key).name;++ const prompts = PROMPT_SUGGESTIONS.map((s, i) => ({+ id: demoId(brandId, `prompt-suggestion:${i}`),+ brand_id: brandId,+ suggested_text: s.text,+ topic_name: topicName(s.topic),+ topic_id: topicId(s.topic),+ reason: s.reason,+ est_volume: s.volume,+ relevance: s.relevance,+ source: 'llm',+ source_data: null,+ status: 'new',+ generated_at: generatedAt.toISOString(),+ expires_at: new Date(generatedAt.getTime() + FRESH_MS).toISOString(),+ created_at: generatedAt.toISOString(),+ updated_at: generatedAt.toISOString(),+ }));++ const topics = TOPIC_SUGGESTIONS.map((s, i) => ({+ id: demoId(brandId, `topic-suggestion:${i}`),+ brand_id: brandId,+ name: s.name,+ reason: s.reason,+ source: 'llm',+ status: 'new',+ generated_at: generatedAt.toISOString(),+ created_at: generatedAt.toISOString(),+ updated_at: generatedAt.toISOString(),+ }));++ const improve = IMPROVE_PROMPTS.flatMap((key) =>+ Object.entries(IMPROVE_PRESETS).map(([preset, days]) =>+ improveSet(ctx, key, preset, days, generatedAt),+ ),+ );++ return { prompts, topics, improve };+}++/** The suggestions module. */+export const suggestions = {+ name: 'suggestions',+ // Rebuilt in place (write.js): written over, what isn't written again deleted after.+ inPlace: true,+ tables: ['prompt_suggestions', 'topic_suggestions', 'prompt_improve_suggestions'],++ /**+ * Its three tables side by side, through the build's writer (a writer over+ * `db` for a first build without one).+ *+ * @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 }).write,+ }) {+ const rows = suggestionRows({ brandId, now });+ await allSettledOrThrow([+ write('prompt_suggestions', rows.prompts),+ write('topic_suggestions', rows.topics),+ write('prompt_improve_suggestions', rows.improve),+ ]);+ return {+ promptSuggestions: rows.prompts.length,+ topicSuggestions: rows.topics.length,+ improveSuggestions: rows.improve.reduce((n, s) => n + s.suggestions.length, 0),+ };+ },+};diff --git a/server/src/lib/demo/suggestions.test.js b/server/src/lib/demo/suggestions.test.jsnew file mode 100644index 000000000..82c5534c0--- /dev/null+++ b/server/src/lib/demo/suggestions.test.js@@ -0,0 +1,96 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('../../config/supabase.js', () => ({ default: {} }));++const { IMPROVE_PRESETS, IMPROVE_PROMPTS, suggestionRows, suggestions } =+ await import('./suggestions.js');+const { DEMO_MAX_AGE_MS } = await import('./index.js');+const { coreRows } = await import('./core.js');+const { ACTIONABLE_STATES, isKnownSource } = await import('../prompt-improve.js');++/**+ * The demo brand's suggestions (demo-workflows): prompts and topics to add,+ * and Improve suggestions built from the demo's own answers.+ */++const BRAND_ID = '11111111-2222-4333-8444-555555555555';+const NOW = new Date('2026-10-28T12:00:00Z');+const core = coreRows({ brandId: BRAND_ID, now: NOW });+const rows = suggestionRows({ brandId: BRAND_ID, now: NOW });++describe('suggestionRows', () => {+ it('suggests new prompts and topics under the brand’s own topics', () => {+ expect(rows.prompts).toHaveLength(8);+ expect(rows.topics).toHaveLength(3);+ const topicIds = new Set(core.topics.map((t) => t.id));+ const tracked = new Set(core.prompts.map((p) => p.text));+ for (const s of rows.prompts) {+ expect(topicIds.has(s.topic_id)).toBe(true);+ expect(tracked.has(s.suggested_text)).toBe(false);+ expect(s).toMatchObject({ brand_id: BRAND_ID, status: 'new', source: 'llm' });+ expect(s.relevance).toBeGreaterThan(0);+ expect(s.relevance).toBeLessThanOrEqual(1);+ }+ for (const t of rows.topics) {+ expect(core.topics.some((x) => x.name === t.name)).toBe(false);+ }+ });++ it('stays new until the demo is rebuilt, generated after its latest run', () => {+ for (const s of rows.prompts) {+ expect(Date.parse(s.generated_at)).toBeLessThanOrEqual(NOW.getTime());+ expect(Date.parse(s.expires_at)).toBeGreaterThan(NOW.getTime() + DEMO_MAX_AGE_MS);+ }+ });++ it('builds the Improve tab for its weakest prompts from their answers', () => {+ expect(rows.improve).toHaveLength(IMPROVE_PROMPTS.length * Object.keys(IMPROVE_PRESETS).length);+ for (const set of rows.improve) {+ const answers = core.results.filter((r) => r.prompt_id === set.prompt_id);+ expect(answers.length).toBeGreaterThan(0);+ // Not stale: built from the prompt's newest answer.+ expect(set.latest_result_at).toBe(+ answers+ .map((r) => r.created_at)+ .sort()+ .at(-1),+ );+ expect(set.region).toBe('');+ expect(set.platform_states).toHaveLength(6);+ expect(set.suggestions.length).toBeGreaterThan(0);+ for (const s of set.suggestions) {+ const state = set.platform_states.find((p) => p.id === s.platform);+ expect(ACTIONABLE_STATES).toContain(state.state);+ expect(s.sources.length).toBeGreaterThan(0);+ expect(s.title).not.toMatch(/undefined/);+ }+ }+ });++ it('cites only evidence the engine’s answers hold', () => {+ const set = rows.improve[0];+ expect(+ set.suggestions.every((s) =>+ s.sources.every((src) => typeof src.ref === 'string' && src.ref.length > 0),+ ),+ ).toBe(true);+ // Shape check on the helper the route trusts.+ expect(isKnownSource({ type: 'fanout', ref: 'x' }, { fanouts: [{ query: 'x' }] })).toBe(true);+ });+});++describe('suggestions.build', () => {+ it('writes the three tables it owns', async () => {+ const written = [];+ const db = {+ from: (table) => ({+ upsert: async (list) => {+ written.push([table, list.length]);+ return { error: null };+ },+ }),+ };+ await suggestions.build({ brandId: BRAND_ID, now: NOW, db });+ expect(written.map(([t]) => t)).toEqual(suggestions.tables);+ });+});diff --git a/server/src/lib/signals/library/detect.js b/server/src/lib/signals/library/detect.jsindex 3118c497a..c3733dd31 100644--- a/server/src/lib/signals/library/detect.js+++ b/server/src/lib/signals/library/detect.js@@ -128,7 +128,7 @@ export function group(kind, entity, rows, toTarget, source, extra = {}) {}/** A finding about one thing — a topic, a platform, a source, a competitor. */-function single(kind, key, entity, target, source, values = {}, extra = {}) {+export function single(kind, key, entity, target, source, values = {}, extra = {}) {return {kind,dedupKey: `${kind}:${key}`,@@ -301,7 +301,7 @@ function trafficTarget(p) {};}-const promptTarget = (texts) => (p) => ({+export const promptTarget = (texts) => (p) => ({id: p.prompt_id,label: String(texts.get(p.prompt_id) ?? '').slice(0, 160),volume: p.volume ?? 0,