Skip to content

feat(action-center): check a task on its page by itself, close it when it passes and say what's still missing (AC-010, part 4) - #1565

Merged
gkhngyk merged 8 commits into
ansvisor:mainfrom
cihan-gyk:feature/ac-010-auto-checks
Oct 27, 2026
Merged

gkhngyk merged 8 commits into
ansvisor:mainfrom
cihan-gyk:feature/ac-010-auto-checks

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

AC-010 ("Done when" on every task), part 4 of 4: automatic checks.

Stacked on #1564, which is stacked on #1561.

AC-010 asks that an automatic check close a task by itself and show when it was checked, and that a failed check say what is still missing. A task whose How we check is auto is now checked on its page, fetched again with the free reader (safe-fetch, never the paid scraper), by what it changes:

Task Passes when
fix_broken_target the page answers again
publish_content the page answers where it didn't (4xx before), or changed since its first look. A page already live at the first look isn't passed by itself
fix_structured_data it has valid JSON-LD
fix_crawler_access robots.txt doesn't block the AI crawlers, and the page isn't noindex
optimize_content, refresh_content, strengthen_*, improve_cta_path the page's visible words changed since its first look
a written task (no task_key) with a change its after text is on the page, as whole words, in the content, the title or the meta description

How the first look and the page are read:

  • The first look keeps a fingerprint of the page's visible words: content, title and meta description, entities read as characters, never scripts. A JSON-LD date or price that changes with no one's work doesn't pass the task.
  • The fingerprint is kept with the URL it read. A URL edited since starts a new first look. A page that answers with a 4xx keeps the fingerprint it had.
  • A 5xx, a timeout or no answer says nothing: only the try's time is kept.
  • robots.txt: none (4xx), or a page served instead of one, lets every crawler in. A 5xx says nothing.

The Site Audit fixes aren't checked here: a new audit is a paid run.

Server (action-center/task-checks.js).

  • runTaskCheck keeps what it found on the task as details.autoCheck (at, triedAt, url, passed, missing, the fingerprint).
  • A task that passes is completed. It's written only if the task is as it was read, its status and its updated_at both, so neither a move nor an edit made meanwhile is lost. History gets task_checked with actor_id null, the product's own work, and the action's updated_at moves.
  • When nothing was checked, it says why: not_checkable, not_open, no_answer or changed.
  • A failed check leaves the task open with what's missing. A page that can't be read at all (a timeout) keeps nothing.
  • The template's source stays on the details, so a check is no one's edit (the task writer's isTouched).
  • A path is put on the brand's first domain.
  • sweepTaskChecks runs nightly from runDailyTracking, after the task writer's sweep:
    • it reads only tasks it can check: a library task with a check, or a written one with its new text, and a URL, of open actions;
    • the least recently tried first (details.autoCheck.triedAt, nulls first), so a page that can't be read never holds the others back;
    • none tried in the last 20 hours;
    • one page at a time, 200 at most.
  • POST /api/action-center/tasks/:id/check (Check now):
    • checks the caller's access to the task's brand first;
    • uses the page-read rate limiter;
    • returns reason: 'closed' for a closed or deleted action.
  • loadTask also reads the task's updated_at and the action's deleted_at.

Web.

  • task-details.ts reads the check as lastCheck.
  • The task card shows Last check: "Checked Oct 22 · passed", or "Checked Oct 22 · robots.txt blocks AI crawlers, the page asks not to be indexed". A first look reads "first look kept: it passes once the page changes".
  • It has a Check now button only on an open task checked auto that has a URL.
  • The drawer tells the result in a toast, or why nothing was checked (a Site Audit fix is checked by the next audit, done already, closed action, …), and reloads.
  • checkActionTask is the server action.
  • History reads "Checked automatically and done: …".
  • Strings are in en.json (actionCenter.taskCheckMissing, drawer.task, drawer.events.task_checked).
  • Docs: the Action Center guide.

Related issue

AC-010 (roadmap), part 4 of 4. Stacked on #1564 (and #1561).

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. cd server && npx vitest run src/lib/action-center/task-checks.test.js src/routes/action-center-tasks.test.js
  2. cd web && yarn vitest run src/lib/actions/action-task-check.test.ts src/components/action-center/task-detail.test.tsx src/lib/action-center
  3. On a local stack, open an action whose "Publish the approved content" task has a URL on the brand's site, and click Check now. The task is completed, and History says it was checked. Then give a task a URL that answers 404: Last check says the page didn't open.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run: npm run format, npm run lint and npm test in server/ (2,920 tests), and yarn format, yarn lint (0 errors), yarn typecheck, yarn test and yarn build in web/. Files outside this change timed out under the machine's heavy load in the full run (6 in server/, 4 in web/). All pass on their own but one: the content editor's page.test.tsx, which this change doesn't touch, ran 18 minutes alone (one test took 16) and 11 of its 257 tests timed out. CI runs it on a quieter machine.

The card's Last check row and Check now button are covered by task-detail.test.tsx; a screenshot follows from the next local test session.

🤖 Generated with Claude Code

cihan-gyk and others added 3 commits October 26, 2026 21:37
…d how we check it, and have the task writer fill them (AC-010)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…en, how they're checked and their page (AC-010, part 3)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n it passes and say what's still missing (AC-010, part 4)

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

mintlify Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit c787f87.

Approve preview

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs changes: the checks can close tasks that aren't done, a task someone reopens is closed again, and the page read needs a scope and a bound. The rest are follow-ups.

What I checked:

  • The fetch. Every page and robots.txt goes through fetchPage: http(s) on the standard ports only, every address the name resolves to must be public (checked inside the connection's own lookup), redirects re-checked (at most 5), 10 s for the whole read, 3 MB at most, HTML only (robots.txt: text/plain). No paid scraper is called.
  • Who can check. checkTaskNow loads the task, then checks the caller's access to its action's brand before anything is read or fetched (routes/action-center.js:233-242), and refuses a closed or deleted action. The sweep reads only open tasks of open, undeleted actions.
  • What closes. Only a task whose How we check is auto, open (todo/in_progress), with a URL, and a library key in CHECKS or a written task with after text. Manual and Re-run tasks are never touched. The write is conditional on the task's status and updated_at, so a move or an edit made meanwhile wins. Every other writer of a task's status or details bumps updated_at. History gets task_checked with no actor, and only after that write lands, so two checks at once log one line.
  • Counts and webhooks. No trigger reads action_tasks.status (00244/00245 count an action's entities, not its tasks), the action's own status doesn't change, and no webhook fires on a task's status (action_task.sent is the only task event). A closed task can be reopened from its status menu, but see item 4.
  • Pass rules. I ran each kind on pages built for it (results below).
  • Tests. The server tests (23) and the web tests for the server action, the card, task-details and the History line pass on this head. Without the change they fail: task-checks.js and checkTaskNow don't exist, and the card has no check prop.
  • Merge. On today's main, with #1561 and then #1564 squashed first, this merges clean and its change is byte-identical to origin/pr/1564..origin/pr/1565. If #1562 is squashed before #1564, #1564 conflicts in en.json (both add a block before taskChecks), and this one then conflicts in display.test.ts (both add a test at the same place). Keep both in each.
  • Before the API deploy. The web goes out on merge.
    • The card's Last check row needs a check the new server writes, so it shows nothing until then.
    • Check now shows on an open task someone set to Automatic with a URL in #1561's form. A click gets a 404 from the old API, and the toast says "Couldn't check the task. Try again." Nothing that works today breaks.
    • Once the API is deployed, the sweep runs from the next night on every open Automatic task with a URL.

Before merge:

  1. Structured data and crawler access can pass with nothing fixed (server/src/lib/action-center/task-checks.js:151-176).
    • jsonLd().valid counts the blocks that parse as JSON. So any page with one parseable block passes:

      • a site-wide Organization block passes a "FAQ schema" fix;
      • {"foo":1} passes;
      • a broken block next to a good one passes.

      F03 is raised by the audit's json-ld-presence, json-ld-validity, json-ld-relevance and faq-schema failures. A page that fails faq-schema, json-ld-relevance or json-ld-validity but has one parseable block passes the first night.

    • F02 is raised by the audit's ai-bot-access or by cited_page_uncrawled, which comes from the bot logs. A one-page action from the logs passes the first night: robots.txt never blocked that page.

    • Also, a robots.txt served as anything but text/plain is read as no rules. Crawlers read it whatever its type.

    • Fix: pass when the audit checks that raised the action pass on the fetched page, using the audit's own evaluators. They need only $ and robotsTxt. The action's target keeps which checks failed (payload.targets[].checks). Copy them into the task's details when it's planned (beside url in templateDetails), or read them for the task's page.

      import { jsonLdPresence, jsonLdValidity, jsonLdRelevance, faqSchema } from '../audit/signals/structure.js';
      
      const AUDIT_CHECKS = {
        'json-ld-presence': jsonLdPresence,
        'json-ld-validity': jsonLdValidity,
        'json-ld-relevance': jsonLdRelevance,
        'faq-schema': faqSchema,
        'ai-bot-access': aiBotAccess,
      };
      // structuredData / crawlers: the target's checks, else ['json-ld-validity'] for structured data
      const failing = checks.filter((key) => AUDIT_CHECKS[key]?.evaluate({ $, robotsTxt }).status === 'fail');

      A crawler task with no ai-bot-access among its checks (the bot-log signal) isn't checked here. For robots.txt, take any text type, and treat only an HTML page as no robots.txt.

  2. "Changed since its first look" passes on a page that changes by itself (task-checks.js:96, :110-118).
    • One word, number or character is enough. Each of these passed on a page built for it:

      • a date and a reader count moved;
      • a price and a stock count moved;
      • a rotating testimonial.
    • This is the rule for optimize, refresh, the two strengthen tasks and the call to action. It is also the rule for publish once the page was live at the first look.

    • Fix: measure how much changed. Keep a small sketch of the first look (the 64 smallest hashes of its 4-word runs, about 1 KB), and pass when the estimated share in common drops below 0.9:

      function sketch(visible) {
        const w = words(visible).trim().split(' ').filter(Boolean);
        const seen = new Set();
        for (let i = 0; i + 4 <= w.length; i += 1) {
          seen.add(createHash('sha1').update(w.slice(i, i + 4).join(' ')).digest('hex').slice(0, 12));
        }
        return [...seen].sort().slice(0, 64);
      }
      function similarity(a, b) {
        const A = new Set(a);
        const B = new Set(b);
        const union = [...new Set([...a, ...b])].sort().slice(0, 64);
        return union.length ? union.filter((h) => A.has(h) && B.has(h)).length / union.length : 1;
      }
    • On an 800-word page this scored:

      Change Score
      The date, a count and a price moved 0.98
      A testimonial rotated 0.97
      One sentence rewritten 1.00
      A 150-word FAQ added 0.84
      Two paragraphs rewritten 0.75
      40% rewritten 0.36
    • A one-sentence fix then doesn't close by itself; the person completes it, which is the safe side.

  3. Two smaller false passes (task-checks.js:143-145, :179-187).
    • published passes on any 4xx followed by a 200:

      • a 403 or 429 from bot protection at the first look, then the same live page;
      • a live page that answered 404 once during a deploy, since its wasMissing is kept beside its fingerprint.

      Only 404 and 410 should say "not there"; take any other 4xx as no answer. Pass on "answers now" only when the page never answered before:

      if (previous?.wasMissing && !previous.fingerprint && previous.url === url) return { passed: true, missing: [] };
    • text passes when after is anywhere on the page:

      • a short one already there before the edit ("Free shipping") passes at the first look;
      • a replacement passes while before is still on the page.

      When before is given and isn't inside after, require it gone too.

  4. A task someone reopens is closed again the next night (task-checks.js:246-273). Nothing records that a person reopened it. The next check passes it again and completes it, for every kind but changed. Reopening is the way to correct the items above, so it has to stick. An open task whose last check passed on the same page can only have been reopened:
    const reopened = previous?.passed === true && previous.url === url;
    // ...
    ...(found?.passed && !reopened ? { status: 'completed', skip_reason: null } : {}),
    // and the History line only when it completed
    The card then shows "Checked … · passed" and leaves the call to the person. A URL edited since counts as a new page.
  5. Check only the brand's own pages, and bound the work per page (task-checks.js:139, :178, :219-229).
    • The URL is whatever a member types (the form takes any text up to 500 characters). Today any public host is read: on demand, and every night while the task is open.
    • The URL import reads only the brand's domains and refuses a redirect off them (routes/content-pages.js:63-80). Do the same here: check onBrandDomain(url, domains) against all the brand's domains before the fetch, and against page.url after it, else missing: ['off_site'] with a line on the card. Read a bare host/path as https://, as the import does.
    • Bound the work: read at most 512 KB (maxBytes: 512 * 1024, truncate: true). Take the visible words in one pass over the body instead of extractPageContent plus an .after(' ') per block, since those two don't stay linear on every page shape. This runs on the API's process, from the sweep and from Check now. An iterative walk also never runs out of stack:
      const SKIP = new Set(['script', 'style', 'noscript', 'template', 'iframe', 'svg', 'nav', 'header', 'footer', 'aside', 'form', 'button']);
      function bodyText($) {
        const out = [];
        const stack = [...($('body')[0] ?? $.root()[0]).children].reverse();
        while (stack.length) {
          const node = stack.pop();
          if (node.type === 'text') out.push(node.data);
          else if (node.type === 'tag' && !SKIP.has(node.name) && !isFurniture(node.attribs)) {
            out.push(' ');
            for (let i = node.children.length - 1; i >= 0; i -= 1) stack.push(node.children[i]);
          }
        }
        return out.join('');
      }
      isFurniture reads the class and id words against page-content.js's FURNITURE_WORDS (export it): related, comments, share, ads and the rest. The walk itself is linear; on 3 MB of plain blocks or paragraphs it took 0.3–0.5 s here.

Follow-ups:
6. Tasks the sweep can't check stay at the head of its queue (task-checks.js:225-226, :309-325). Nothing is written in two cases:

  • when no address can be made (a URL typed as acme.example/pricing, or a path on a brand with no domain);
  • when reading the page throws.

Those rows keep a null or old triedAt, come first every night (nulls first), and take places out of the 200. Write triedAt on every outcome. Writing it before the fetch, as a claim, also keeps two runs from checking the same task.
7. One brand can take the night, and the sweep doesn't wait for the task writer (server.js:183-193).

  • 200 tasks a night across all brands, untried first: a brand with many new Automatic tasks holds the others back for nights. Cap each brand per night (say 20), and read more rows to fill the 200.
  • The PR says the sweep runs after the task writer, but both start at once. The writer can delete a task a check just completed (task-writer/index.js:393-401). Start the checks when the writer's sweep settles.
  1. Check now.
    • It shares pageReadLimiter with Quality's page read, an AI-cost route, so clicks here use up the editor's reads. Give it its own bucket.
    • not_checkable says "a Site Audit fix is checked by your next audit" also for a written task without new text, and for a URL that isn't an address (en.json:1361). Give those their own reasons.
    • The button shows on every open Automatic task with a URL (action-drawer.tsx:730-736). Show it where the server checks: a key in CHECKS, or a written task with after.
  2. The call-to-action task can't pass. The content area leaves out a CTA block outside <main>: a rewritten hero and CTA band read "not changed" here. Under item 2's rule a CTA edit is also too small to pass. Check it by its after text, or make it Manual in the template.
  3. Small ones.
    • The History line {task}{title} runs both names together for a renamed library task. Send task only when there's no title.
    • brandHost drops www. (normStoredDomain), so a path goes on the bare domain. A site served only on www doesn't answer there. Keep the stored host.
    • Docs (docs/guides/action-center.mdx:86): "every night" is up to 200 tasks a night. Say a reopened task stays open once item 4 is in.
  4. Run the sweep once against the local stack. Its query is tested against a mock only: the or with a JSON path, and the order on details->autoCheck->>triedAt. A query PostgREST refuses would only log "daily sweep crashed" each night.

cihan-gyk and others added 2 commits October 27, 2026 10:51
…-checks

# Conflicts:
#	docs/guides/action-center.mdx
#	server/src/lib/action-center/task-writer/index.js
#	server/src/lib/action-center/task-writer/quality.js
#	server/src/lib/action-center/task-writer/quality.test.js
#	web/messages/en.json
#	web/src/components/action-center/task-detail.test.tsx
#	web/src/components/action-center/task-detail.tsx
#	web/src/lib/action-center/display.test.ts
#	web/src/lib/action-center/task-details.test.ts
#	web/src/lib/action-center/task-details.ts
…it's own checks, a change by how much changed, and only the brand's pages, and hold a task someone reopened (ansvisor#1565 review)

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

Copy link
Copy Markdown
Collaborator Author

Thanks. Before merge 1–5 are done in d51ed43, after merging main in (751dc4f). #1561, #1562 and #1564 are squashed on main; their files kept main's side. en.json and display.test.ts kept both, as you said. The merged branch's diff against main is byte-identical to this PR's own change before the fixes.

1. Structured data and crawler access.

  • A structured data fix passes when the audit checks that raised it pass on the fetched page, by the audit's own evaluators (json-ld-presence, json-ld-validity, json-ld-relevance, faq-schema, all reading { $ }).
    • The checks come from the action's target for the page (payload.targets[].checks, read with targets:payload->targets). I read them at check time rather than copying them into the details, so tasks already planned get them too.
    • The page is matched however its address was written: http or https, www. or not, a trailing slash or not.
    • With no target for the page, the checks of every target together are used, the stricter side.
    • With none named, the page needs valid schema.org JSON-LD (json-ld-validity).
    • Each failing check has its own line on the card. The new missing keys are structured_data_invalid, structured_data_irrelevant and no_faq_schema.
  • A crawler fix is checked only when ai-bot-access is among its checks. Raised from the bot logs, it answers not_checkable with nothing fetched.
    • It passes on aiBotAccess.evaluate(…).status !== 'fail'.
    • robots.txt is read whatever its type, since S3 serves it as octet-stream. Only an HTML page served in its place counts as no robots.txt. A 429 for it is no answer.
  • One thing I left as the audit has it: a broken JSON-LD block next to a good one makes json-ld-validity a warn, not a fail, so the task passes. The audit raises the action on fail only, so the check closes it on the same terms. Say if you'd rather the check ask for pass on validity and relevance.

2. Changed since the first look.

  • The first look keeps a sketch: the 256 smallest 10-hex sha1s of the page's 4-word runs (about 2.5 KB), and how many runs the page has.
  • A page passes when both hold:
    • similarity(first, now) < 0.9 (CHANGED_BELOW);
    • at least 40 runs changed (MIN_CHANGED_RUNS), estimated as (runsA + runsB)(1 − J)/(1 + J).
  • The second rule is for short pages. A date and a price moving on a 60-word page is a large share of its runs, below 0.9 on its own, but only a handful of runs. On an 800-word page it changes nothing: a 150-word FAQ is about 150 runs.
  • A 256-hash sketch also makes a nightly re-read of the same first look less noisy than 64 did.
  • A page with fewer than 20 visible words isn't read: it's no answer, and no sketch is kept. That covers an empty shell, or bot protection's 200.
  • One that doesn't pass keeps its first look, so small changes add up.
  • fingerprint is gone. No check has been written yet, so there's nothing to read back.
  • Tests on essays of 60, 200, 400 and 800 words:
    • A date, a count and a price moved: under 40 runs on every length.
    • A 150-word FAQ added to 800 words: below 0.9, and over 40 runs.
    • 40% rewritten: below 0.5.

3. The smaller false passes.

  • Only 404 and 410 are "not there". Another 4xx is no answer (403, 429 tested).
  • published passes on "answers now" only when the page was never seen live (wasMissing && !previous.sketch, same URL). A live page that answered 404 once keeps its first look.
  • text: when before is given and isn't inside after, it must be gone from the page too (old_text_still_there).

4. A reopened task stays open. An open task whose last check passed on the same URL is read as reopened, and is then held: autoCheck.held: true, kept for that URL whatever later checks find.

  • A failed check in between doesn't forget it. Without that, changed would read not_changed the next night, against the page it passed on, and then pass again later.
  • A held task is never completed by a check, and History gets no line.
  • The sweep leaves held tasks (details->autoCheck->>held is null). Check now still reads one and shows what it finds.
  • A URL edited since is a new page.

5. The brand's own pages, bounded.

  • onBrandDomain(url, domains) runs against all the brand's domains before the fetch (off_site, nothing read), and again on page.url after it.
  • A bare host/path is read as https://, as the import does.
  • A path goes on the primary domain's stored host, www. kept (your item 10).
  • A bare value is parsed as https:// + it, and needs a dotted host with a real last label. So pricing.html isn't a domain, //host/path gets https:, and an IDN like çiçek.com/x reads as its punycode.
  • Reads are capped at maxBytes: 512 * 1024, truncate: true, for robots.txt too. The page is parsed once.
  • The visible words come from your iterative walk over the body:
    • It always skips code: script, style, noscript, template, iframe and svg.
    • It skips nav, header, footer, aside, form and button, and furniture by class and id. page-content.js now exports furnitureNamed(attribs), on its FURNITURE_WORDS.
    • These are skipped only when they hold at most half the body's text, as page-content.js's MAX_FURNITURE_SHARE does. WordPress and Ghost put classes like category-social-media or tag-newsletter on the <article>, and ASP.NET wraps the whole page in a <form>. Without that, those pages read as nearly empty.
    • Subtree text lengths come from one bottom-up pass first, also as a stack. A test reads a page nested 10,000 deep.

Docs. The Action Center guide now lists what each kind passes on, says it's up to 200 tasks a night, that only the brand's own pages are read, and that a reopened task stays open.

Tests. task-checks.test.js is 27 cases. Each fix's case fails without it. I checked that by reverting each one:

  • the audit evaluators, and the target matched however written;
  • the 0.9 threshold, and the 40 runs;
  • the 20-word floor;
  • a block that holds most of the page read;
  • 404/410 only, and robots.txt's 429;
  • robots.txt of any type;
  • never seen live;
  • the old text gone;
  • reopened, held through a failed check, and left by the sweep;
  • off the site before the fetch, and after a redirect;
  • the 512 KB read.

A crawler task raised from the bot logs answers not_checkable, and now keeps its try (triedAt). That part of item 6 was already in the branch this PR adds, so it doesn't sit at the head of the sweep.

Also run: server npm run lint and npm test (2,963 tests); web yarn lint (0 errors), yarn typecheck, yarn test (4,133 tests) and yarn build. The web ran before the review's second round, which changed only the server and the docs.

Before pushing, a review of my own fixes found what's folded in above: the run count beside the share, the 20-word floor, the furniture share, the held flag, the target match, and robots.txt's type and 429.

Follow-ups 6–11 go in a follow-up PR once this one is merged:

  • triedAt on every outcome, as a claim;
  • a per-brand cap, and starting after the writer's sweep settles;
  • Check now's own limiter, its reasons, and the button only where the server checks;
  • the CTA task (Manual in the template, or by its after);
  • the History line's {task}{title};
  • a sweep run with checks against the local stack. For now, the sweep's query (the or with the JSON path, and the order on details->autoCheck->>triedAt) and the targets:payload->targets read both run against the dev DB through PostgREST without an error. The dev DB has no open Automatic task with a URL and no action with targets, so they returned nothing.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs changes: one thing before merge. The 512 KB cap bounds the read but not the parse. Items 1–5 are otherwise done. My answer to your question is below, and the rest are follow-ups.

What I checked:

  • The change. The merge-base with main is 55b49e7, so this PR's change is origin/main..origin/pr/1565. The merge of main (751dc4f) hides nothing. Its change against main matches round 36's change byte for byte. The only differences are two context lines that #1562 added on main (tasks_generated in en.json, one line in display.test.ts).

  • Merge. It merges clean on 55b49e7, and the merged tree is the PR's own.

  • Tests.

    • On this head, task-checks.test.js (27), the route tests and page-content.test.js pass. The full server suite fails only where main fails too in the same scratch copy: files outside server/ and timing tests.
    • Run against 751dc4f's task-checks.js, 22 of the 27 fail.
    • The web tests for the card, the server action, task-details and display pass. CI is green.
  • Only the brand's pages (task-checks.js:500-510, :327).

    • The address is checked against all the brand's domains before anything is fetched, from Check now and from the sweep alike. Another host gets off_site, and nothing is read.
    • The final address after redirects is checked again. That's the import's rule; each hop is still checked by fetchPage.
    • www. and subdomains match as in the import: a stored www.acme.example covers acme.example and its subdomains.
    • These all read as off the site:
      • acme.example.evil.test;
      • evilacme.example;
      • a brand domain only in the query, the fragment or the user part;
      • acme.example. with a trailing dot;
      • an IP.
    • A non-standard port passes the domain check, but fetchPage refuses it, so nothing is read.
    • robots.txt is fetched from the checked page's own host. Its redirects aren't held to the brand's domains, which is what crawlers do too.
  • The first look. It's 256 ten-character hashes plus a run count: 3.4 KB as stored. That's bounded. It's replaced only when a check passes or the URL changes.

  • Reopened. An open task whose last check passed on the same URL is held:

    • the hold survives a failed check in between;
    • it's never completed and writes no History line;
    • the sweep leaves it (:511-529, :579).

    A URL edited since is a new page. The drawer's Edit merges into details, so it keeps the hold.

  • Before the API deploy. Same as round 36: the web goes out on merge, Check now gets a 404 from the old API ("Couldn't check the task"), and nothing that works today breaks.

Before merge:

  1. Bound the parse, not just the read (task-checks.js:330).
    • The read stops at 512 KB, and the walk over the body is linear.
    • cheerio.load (parse5) isn't linear in how deep a page nests. A deeply nested page at the cap still takes over a minute to parse on the API's process, from Check now and from the sweep.
    • Real pages rarely nest past a few dozen elements, and browsers stop nesting at 512.
    • Fix: before cheerio.load, count the nesting in one pass that stops at a limit. Treat a page past the limit as no answer. htmlparser2 (already installed under cheerio; add it to server/package.json) counts open elements, implied closes included. It stays linear because it stops at the limit:
      import { Parser } from 'htmlparser2';
      
      /** Deeper than this, a page isn't read: browsers stop nesting at 512. */
      const MAX_DEPTH = 1000;
      const TOO_DEEP = new Error('too deep');
      
      /** Whether a page nests deeper than MAX_DEPTH: one pass, stopped at the limit. */
      export function tooDeep(html) {
        let depth = 0;
        const parser = new Parser(
          {
            onopentag() {
              depth += 1;
              if (depth > MAX_DEPTH) throw TOO_DEEP;
            },
            onclosetag() {
              depth -= 1;
            },
          },
          { decodeEntities: false },
        );
        try {
          parser.end(html);
          return false;
        } catch (err) {
          if (err === TOO_DEEP) return true;
          throw err;
        }
      }
      
      // checkPage, before cheerio.load:
      if (tooDeep(page.html)) return null;
    • Here, the count takes under 0.1 s at the cap. The worst pages that stay just under a 1,000 limit parse in 0.6–1.3 s at 512 KB. A limit of 500 roughly halves that.
    • The count reads a little high on sloppy markup, such as an unclosed <p> in each unclosed <li>. That only makes such a page no answer.
    • Add a test: a 3 MB page of nested blocks comes back null, quickly.

Your question: should json-ld-validity ask for pass?

  • Yes, for validity. Keep "not fail" for relevance.
  • Validity's warn means a block on the page still doesn't parse (structure.js:121-129).
    • Validity raised the action when every block failed, or when none was schema.org.
    • A page that now has a good block next to a broken one most likely still carries the block the audit named. Crawlers drop that block, so whatever it described (a Product, say) is still missing.
    • "The page has valid structured data" isn't done yet, and round 36 listed this exact case. Asking for pass costs nothing when the fix is whole. When it isn't, the card already says what's wrong.
  • Relevance's warn is different: the page has types, but none from the high-value list. The action was raised on fail, which means no types at all, and the card's line is "no type that describes the page". Asking for pass there would hold tasks the audit itself calls fixed, for types the action never asked for.
  • It's one line, so fold it into this PR:
    /** Checks whose warn is still the problem: a block that doesn't parse. */
    const PASS_ONLY = new Set(['json-ld-validity']);
    const failing = (named.length ? named : DEFAULT_STRUCTURED).filter((key) => {
      const { status } = STRUCTURED_CHECKS[key].evaluate({ $ });
      return status === 'fail' || (PASS_ONLY.has(key) && status !== 'pass');
    });

Items 1–5:

  1. Structured data and crawler access. Done. One case is left: your question above.
    • The checks that raised the action come from the target for the page, matched however the address was written; otherwise every target's checks are used (:406-439). They're run through the audit's own evaluators (:331-337).
    • With none named, the page needs json-ld-validity.
    • A crawler fix is read only when ai-bot-access raised it (:490-497).
    • robots.txt is read whatever its type. An HTML page served in its place counts as no robots.txt, and a 429 is no answer (:339-359).
    • On test pages:
      • a FAQ fix with only an Organization block fails;
      • {"foo":1} fails;
      • GPTBot disallowed site-wide fails.
  2. Changed since the first look. Done.
    • The first look keeps 256 hashes and the run count. A page passes when its similarity is below 0.9 and at least 40 runs changed (:230-281). A page under 20 words is no answer (:363).
    • I ran the rule on realistic text, 60–3,000 words, through checkPage:
      • Never passed: a date, a count and a price moving; one sentence rewritten; a CTA band rewritten. That held at every length.
      • Passed: a rewritten 60-word paragraph, up to 1,500 words; a 150-word FAQ, up to 800 words.
      • Longer pages: past those lengths, both stay open. That's the safe side.
    • Short pages still pass on a block that changes by itself (follow-up A).
  3. The smaller false passes. Done.
    • Only 404 and 410 count as "not there" (:319-325). 401, 403, 429 and 500 at the first look, followed by the live page, now give a first look, not a pass.
    • "Answers now" passes only for a page never seen live (:376).
    • A replacement fails while the old text is on the page (:367-371).
    • An addition whose text is already on the page passes at the first look. That matches its Done when.
  4. A reopened task stays open. Done, as described above, and tested through a failed check and a URL edit.
  5. The brand's pages, and a bound per page. Done, except the parse (item 1 above).
    • The domain checks are in, and a bare host/path is read as https (:130-144).
    • Page and robots.txt reads stop at 512 KB (:61, :314).
    • The visible words come from two linear passes, done with stacks (:162-219). Skipping a furniture block only while it holds at most half the page is a good addition.

Follow-ups:

  • A. Short pages that change by themselves (:69-81, :153-156).
    • On pages of 60–400 words, each of these passed here:
      • a rotated testimonial of about 28 words;
      • a new 50-word customer review;
      • a "Latest posts" list in a <div class="sidebar"> (only <aside> is skipped) with two new posts.
    • Each is 41–66 changed runs. A rewritten 60-word paragraph is 117 or more, and a 150-word FAQ is 146 or more.
    • With MIN_CHANGED_RUNS = 80, and sidebar, widget, promo, announcement, pagination, tags, testimonial(s), latest, recent, popular and trending skipped by class or id (with the same half-the-page guard), none of them passed here. Every real edit that passed before still passed.
  • B. Structured data under other actions, and @graph.
    • F06 (raised by brand-entity / entity-coverage) also has an Automatic fix_structured_data. None of its checks is a structured data check, so it falls back to validity. A page that already had one valid block (a site-wide Organization block) passes the first night. With no structured data check named, pass only after a check that failed (keep it on the check, as wasMissing is kept).
    • json-ld-validity reads a @graph's nodes without the wrapper's @context (audit/signals/helpers.js:26-36). A page whose JSON-LD is one @graph, as WordPress SEO plugins write it, fails validity even when it's valid. That's on main too. Since the check uses the evaluator, such a task never closes by itself. Give each graph node the wrapper's @context when it has none, in its own PR.
  • C. Round 36's 6–11, for the follow-up PR you planned:
    • 6 is partly done. The bot-log crawler case keeps its try. A task with no address (:483) and a read that throws still write nothing.
    • 7, 8 and 9 aren't done yet. The CTA band rewritten reads not_changed at every length here.
    • 10: www. kept and the docs are done. The History line's {task}{title} isn't.
    • 11 is partly done: the queries ran against the dev DB with no rows to return. One sweep over a seeded task is still worth a run.

…ask JSON-LD validity for a pass (ansvisor#1565 review)

- tooDeep counts a page's nesting in one htmlparser2 pass that stops at
  MAX_DEPTH (1,000). A page past it gets no answer instead of a parse
  that isn't linear in its depth. htmlparser2 is now in package.json, at
  the version cheerio already installs.
- json-ld-validity passes only on 'pass': its warn is a block that still
  doesn't parse. Relevance keeps "not fail".

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Thanks. Both before-merge items are in cc805a9.

  1. The parse is bounded (task-checks.js).

    • tooDeep(html) is your count with htmlparser2: one pass that stops at MAX_DEPTH = 1000, with decodeEntities: false.
    • checkPage runs it just before cheerio.load and gives a page past the limit no answer (null), as an unreadable page gets.
    • htmlparser2 is now in server/package.json (^10.1.0). That's the version cheerio already installs, so nothing new is downloaded. package-lock.json gains only that line in the root's dependencies.
    • The tests:
      • exactly 1,000 levels are read, and 1,001 aren't;
      • 1,001 unclosed <div>s count as too deep;
      • 5,000 unclosed <p>s don't, since each one closes the one before;
      • a page over 3 MB, nested 300,000 deep, comes back null for all five check kinds in under 2 s in total;
      • a 500-level page is still read (first_look).
  2. json-ld-validity asks for pass. Your PASS_ONLY line is in, and relevance keeps "not fail". Tested with a valid block beside a broken one:

    • validity is warn and the task stays open, both when validity is named and when no check is named;
    • a relevance warn passes.

    With the line taken out, the new test fails.

Follow-ups A, B and C go in the follow-up PR after this merges, with round 36's 6–11.

Checks on this head, in server/: npm run format, npm run lint and npm test (2,967 tests pass).

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs changes: one thing before merge. The count is in and does what it was asked to do. But the parser behind it can still build a tree far deeper than the count sees, so parse with the parser the count follows. The validity rule is right. The rest are follow-ups.

What I checked:

  • The change. cc805a9 sits on d51ed43 and touches four files: task-checks.js, its test, server/package.json and the lockfile's root. Nothing else changed since round 37.
  • Merge. It merges clean on 5bbd162. The merged tree's change against main is this PR's own change, byte for byte. None of main's five merges since 55b49e7 touches a file this PR depends on.
  • The dependency. htmlparser2 ^10.1.0 matches the lockfile's top-level node_modules/htmlparser2 (10.1.0), the copy cheerio already uses. Nothing new is installed.
  • Tests.
    • CI is green.
    • Here, the new tests pass. One older test (task-checks.test.js:162, the 10,000-deep visibleText page) takes 5–10 s on parse5 on a busy machine, which is past vitest's 5 s limit. With the change below it takes milliseconds.
    • Run against d51ed43's task-checks.js:
      • the validity test fails (a warn passed);
      • both tooDeep tests fail;
      • the 3 MB nested page doesn't come back within 10 minutes.
  • Before the API deploy. Same as round 37. This commit is server only.

Before merge:

  1. Bound the parse: partly done (task-checks.js:289-315, :365-367).
    • The count is in as asked. It's one pass and stops at 1,000. A page past the limit is null before cheerio.load, for all five kinds, and answers never parses.
    • Round 37's deep pages now come back null in well under a second at the cap. crawlers gives no answer on such a page, which is right: it needs the page's robots meta.
    • What's left comes from my round 37 suggestion. The count follows htmlparser2's tree, but cheerio.load parses with parse5. parse5 reopens formatting elements (<b>, <em>, <font>…) that a closed block left open. So its tree can go far deeper than the count sees, and some pages under the limit, well under the cap, still take far longer than their length warrants.
    • Fix: parse with htmlparser2, the parser the count follows. Then the count bounds the parser's own stack, and the time stays near the page's length times the limit:
      /**
       * A page parsed by htmlparser2, as tooDeep counts it: its tree is never
       * deeper than the count. parse5 (cheerio's default) reopens formatting
       * elements a closed block left open, so its tree can go deeper.
       */
      const loadPage = (html) => cheerio.load(html, { xml: { xmlMode: false } });
      
      export function visibleText(html, $ = loadPage(html)) {
      
      // checkPage
      if (tooDeep(page.html)) return null;
      const $ = loadPage(page.html);
    • Here, with that change:
      • the 31 tests pass unchanged;
      • every page shape I tried at 512 KB takes at most 2–3× as long as a plain page of paragraphs;
      • ordinary and sloppy pages give the same structured data and crawler answers. The words are the same too, except text after </html> (parse5 moves it into the body) and the run-together case in D below.
      • No first look is stored yet, so nothing needs migrating.
    • Use 512 for MAX_DEPTH, as #1595 does (it's also what browsers keep). Then nothing changes when the two meet. The 500-level test still reads its page.
    • Add a test with a page the count passes but parse5 is slow on. I'll send you the shape.

Your question, json-ld-validity asking for pass: done (:103-104, :368-375).

  • Validity's warn (a block that doesn't parse beside a good one) keeps the task open, both when validity is named and by default.
  • Relevance's warn passes. Presence and FAQ have no warn.
  • pass still needs every block to parse and one schema.org node with a type. A block that parses but isn't schema.org doesn't hold the task open while another block is.
  • The test fails without the line.

With #1595.

  • #1595 (mine) adds the same count as server/src/lib/html-depth.js (nestsTooDeep, limit 512). fetchPage refuses a page past it with PageFetchError('too_deep') (safe-fetch.js:299-300 there). Only the default HTML types are counted, so your robots.txt read (types: /(?:)/) isn't.
  • The two merge clean together on main:
    • htmlparser2 is listed once, and #1595's css-select sits beside it;
    • page-content.js keeps #1595's rewrite and your furnitureNamed.
  • Order: this PR first, once it parses with htmlparser2. #1595 follows and does the folding:
    • task-checks.js drops tooDeep, MAX_DEPTH, TOO_DEEP and the Parser import.
      • Check now and the sweep both read through fetchPage, which then refuses the page first.
      • checkPage's catch (:353-360) already reads every code but a 404/410 as null, so too_deep is no answer with no code change. A comment there will name it.
    • loadPage stays: the count only bounds htmlparser2's parse.
    • The tests:
      • the tooDeep cases move to html-depth.test.js, which already has them;
      • the 3 MB test becomes a fetch that rejects with PageFetchError('too_deep'), giving null for every kind;
      • the 500-level page is still read.
  • If #1595 lands first instead, this PR makes the same changes when it merges main.

Follow-ups:

  • A–C from round 37 go in your follow-up PR, as you said.
  • D. A block's last word runs into the text after it (:220-222).
    • <h2>Pricing</h2>Plans reads "PricingPlans", though the comment says they never run together.
    • For changed it's harmless: every look reads the page the same way.
    • For a written task, new text that starts right after a heading or a closed block, with no element of its own, is never found.
    • Fix: read a space after each element's children as well as before them. With const AFTER = { type: 'text', data: ' ' }; at module level, push it just before the children:
      out.push(' ');
      stack.push(AFTER);
      for (let i = node.children.length - 1; i >= 0; i -= 1) stack.push(node.children[i]);

@gkhngyk

gkhngyk commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Taking this one over to save a round trip: I'll merge main in (#1595 landed first), parse with htmlparser2 as the review says, fold the depth count into fetchPage's too_deep, and add follow-up D. Please don't push to the branch meanwhile; I'll note here when it's done.

…the depth limit to fetchPage

fetchPage now turns away a page nested too deep (too_deep), which checkPage
reads as no answer, so the check's own count goes. The page is parsed with
htmlparser2, whose tree that count follows. A block's last word no longer
runs into the text after it.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. I took the before-merge item over in c787f87 (after merging main in, 86b1050):

  • The page is parsed with htmlparser2 (loadPage), the parser whose tree fetchPage's depth count (#1595, html-depth.js) follows, so the count bounds the parse.
  • tooDeep, MAX_DEPTH and the Parser import are gone: fetchPage turns such a page away with too_deep, which checkPage's catch already reads as no answer (the comment names it). The 3 MB test became a fetch that rejects with too_deep, null for every kind; the 500-level page is still read.
  • Follow-up D: a block's last word no longer runs into the text after it (<h2>Pricing</h2>Plans reads "Pricing Plans").
  • Two new tests (D, and blocks that each leave a different formatting element open); both fail on the previous head.

Server suite, lint and format pass. Follow-ups A–C stay for your follow-up PR.

@gkhngyk
gkhngyk merged commit 9e12105 into ansvisor:main Oct 27, 2026
6 checks passed
cihan-gyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 27, 2026
…nd main's other new actions while the plan has ended

main's new writes, with C3's guard pattern and labels:
- Merchant Center (ansvisor#1583): picking and adding an account open the plan
  dialog ("Connecting a store needs a plan"); the server's 'subscription'
  refusal on Add opens it too, instead of looking up a missing
  settings.catalog.stores.errors.subscription message.
- Category pages (ansvisor#1587): Change, Save, No page and Use the match are
  guarded; the catalog client reads the server's 402
  subscription_inactive as 'subscription', which opens the dialog
  instead of the generic failure.
- Brief › Shopping path (ansvisor#1591): Pick from the catalog, Pick again, Add
  product, Lock, Swap and Remove are guarded.
- Action Center Check now (AC-010, ansvisor#1565) is guarded.

New labels: changeCategoryPages, changeShoppingPath, checkTasks.
Insert › Products (ansvisor#1607) already goes through the toolbar's guard and
the read-only editor shows no insert menu; a test now says so. The
Shopping rules (ansvisor#1610) change through the rules hook, already guarded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
gkhngyk pushed a commit that referenced this pull request Oct 28, 2026
…by its title when it has one (#1685)

Follow-up C (round 36's item 10) from #1565's round 37. The History line
"Checked automatically and done: {task}{title}" ran both names together
for a library task someone renamed ("Refresh outdated contentRefresh the
pricing page").

- The API's task_checked event sends `task` only when there's no title.
- The web names it by its title when the line has one, so lines written
  before carry one name too.

The round's other two parts of item 10 (www kept, the docs) were done in
#1565.

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 28, 2026
…1681)

* fix(audit): read a JSON-LD @graph's nodes in the wrapper's @context

Follow-up B (second half) from #1565's round 37. jsonLd() flattened a
@graph into its nodes without the wrapper's @context, so a page whose
JSON-LD is one @graph with the context on the wrapper alone (as
WordPress's SEO plugins write it) failed json-ld-validity though it's
valid: no node "declares" schema.org. That's on main too, and since the
Action Center's structured data check uses the same evaluator, such a
task never closed by itself.

A @graph's node now takes the wrapper's @context when it has none of its
own, as JSON-LD reads it; a node's own context is kept, and a @graph with
no context anywhere still fails. The new structure.test.js fails on main.

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

* fix(audit): read each JSON-LD context once in json-ld-validity

A @graph's nodes now carry their wrapper's context, so the same context
was turned into a string once per node. Keep each context's answer in a
Map keyed by the value, and test a large shared context with thousands
of nodes.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 28, 2026
…ter a check found the page failing (#1680)

* fix(action-center): pass another action's structured data fix only after a check found the page failing

Follow-up B (first half) from #1565's round 37. F06 (raised by
brand-entity / entity-coverage) also has an Automatic fix_structured_data.
None of its checks is a structured data check, so the check falls back to
json-ld-validity, and a page that already had one valid block (a
site-wide Organization) passed the first night with nothing fixed.

With no structured data check named, the check now passes only after a
check on the same page found it failing: that check keeps `sawFailing`
on the task's autoCheck (as `wasMissing` is kept), carried through later
checks of the page. Until then a valid page reads `valid_before`, worded
on the card as "the structured data was already valid at the first
check: mark the task done once it's fixed". A check named by the audit
works as before.

The other half of B (a @graph's nodes read without the wrapper's
@context) is its own PR, as asked.

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

* fix(action-center): one colon in the valid-before check line

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 28, 2026
…, cap each brand's night, and check after the task writer (#1682)

* fix(action-center): mark a task tried before its check reads anything, cap each brand's night, and check after the task writer

Follow-ups C (round 36's items 6, 7 and 11) from #1565's round 37.

Item 6: tasks the sweep can't check stayed at the head of its queue.
Nothing was written when no address could be made (a URL typed as
`acme.example pricing`, a path on a brand with no domain) or when reading
threw, so those rows kept a null or old triedAt and came first every
night. runTaskCheck now writes triedAt first, as a claim on the task as
it was read (the bot-log crawler case's own write goes, the claim keeps
its try); the result is written on the claim. A run that read the task
before another claimed it gets 'changed' and reads nothing, so two runs
never check one task.

Item 7: one brand could take the night, and the checks didn't wait for the
task writer.
- The sweep checks at most SWEEP_PER_BRAND (20) of one brand's tasks a
  night, and reads up to 5 pages of 1,000 rows (ordered by triedAt, then
  id) to fill its 200.
- server.js starts the checks once sweepActionTasks settles: the writer
  can delete a task a check just completed.

Item 11: the sweep's query (the `or` with a JSON path, the order on
details->autoCheck->>triedAt, the range) ran against the dev DB, over a
seeded demo-brand task with a stub page: claimed, checked, completed,
one History line; the temp action and task were deleted after.

The guide's Automatic line says 20 of one brand's, least recently tried
first.

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

* test(action-center): a read that throws still leaves the task tried

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 28, 2026
… for each task it can't check, and show it only where the API checks (#1683)

* fix(action-center): mark a task tried before its check reads anything, cap each brand's night, and check after the task writer

Follow-ups C (round 36's items 6, 7 and 11) from #1565's round 37.

Item 6: tasks the sweep can't check stayed at the head of its queue.
Nothing was written when no address could be made (a URL typed as
`acme.example pricing`, a path on a brand with no domain) or when reading
threw, so those rows kept a null or old triedAt and came first every
night. runTaskCheck now writes triedAt first, as a claim on the task as
it was read (the bot-log crawler case's own write goes, the claim keeps
its try); the result is written on the claim. A run that read the task
before another claimed it gets 'changed' and reads nothing, so two runs
never check one task.

Item 7: one brand could take the night, and the checks didn't wait for the
task writer.
- The sweep checks at most SWEEP_PER_BRAND (20) of one brand's tasks a
  night, and reads up to 5 pages of 1,000 rows (ordered by triedAt, then
  id) to fill its 200.
- server.js starts the checks once sweepActionTasks settles: the writer
  can delete a task a check just completed.

Item 11: the sweep's query (the `or` with a JSON path, the order on
details->autoCheck->>triedAt, the range) ran against the dev DB, over a
seeded demo-brand task with a stub page: claimed, checked, completed,
one History line; the temp action and task were deleted after.

The guide's Automatic line says 20 of one brand's, least recently tried
first.

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

* fix(action-center): give Check now its own rate bucket, its own words for each task it can't check, and show it only where the API checks

Follow-up C (round 36's item 8) from #1565's round 37. Stacked on
fix/task-check-sweep-queue: both change runTaskCheck's first lines.

- Check now shared pageReadLimiter with Quality's page read, an AI-cost
  route, so clicks here used up the editor's reads. It has its own
  taskCheckLimiter (30 per 15 minutes).
- "not_checkable" said "a Site Audit fix is checked by your next audit"
  for every task without a check. runTaskCheck now names why:
  no_address (no URL, or one that isn't a page's address),
  no_change_text (a written task with no new text to look for),
  from_bot_logs (a crawler fix raised from the bot logs, which robots.txt
  can't show done), and not_checkable for a library task checked
  elsewhere, as before. Each has its line in checkNot.
- The drawer showed Check now on every open Automatic task with a URL.
  It shows it where the API checks (pageCheckable): a library task in its
  CHECKS, or a written task with its new text. PAGE_CHECKED_TASKS copies
  the CHECKS keys; a test reads the server file and fails if they drift.

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

* test(action-center): a read that throws still leaves the task tried

* fix(action-center): keep Check now on the shopping links task

The drawer's pageCheckable allowed only a library task it checks on its
page or a written task with new text, so the shopping links task (no task
key, no new text) lost Check now. Pass the action's kind and allow a
shopping_links action's task.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 28, 2026
… page (#1684)

* fix(action-center): mark a task tried before its check reads anything, cap each brand's night, and check after the task writer

Follow-ups C (round 36's items 6, 7 and 11) from #1565's round 37.

Item 6: tasks the sweep can't check stayed at the head of its queue.
Nothing was written when no address could be made (a URL typed as
`acme.example pricing`, a path on a brand with no domain) or when reading
threw, so those rows kept a null or old triedAt and came first every
night. runTaskCheck now writes triedAt first, as a claim on the task as
it was read (the bot-log crawler case's own write goes, the claim keeps
its try); the result is written on the claim. A run that read the task
before another claimed it gets 'changed' and reads nothing, so two runs
never check one task.

Item 7: one brand could take the night, and the checks didn't wait for the
task writer.
- The sweep checks at most SWEEP_PER_BRAND (20) of one brand's tasks a
  night, and reads up to 5 pages of 1,000 rows (ordered by triedAt, then
  id) to fill its 200.
- server.js starts the checks once sweepActionTasks settles: the writer
  can delete a task a check just completed.

Item 11: the sweep's query (the `or` with a JSON path, the order on
details->autoCheck->>triedAt, the range) ran against the dev DB, over a
seeded demo-brand task with a stub page: claimed, checked, completed,
one History line; the temp action and task were deleted after.

The guide's Automatic line says 20 of one brand's, least recently tried
first.

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

* fix(action-center): give Check now its own rate bucket, its own words for each task it can't check, and show it only where the API checks

Follow-up C (round 36's item 8) from #1565's round 37. Stacked on
fix/task-check-sweep-queue: both change runTaskCheck's first lines.

- Check now shared pageReadLimiter with Quality's page read, an AI-cost
  route, so clicks here used up the editor's reads. It has its own
  taskCheckLimiter (30 per 15 minutes).
- "not_checkable" said "a Site Audit fix is checked by your next audit"
  for every task without a check. runTaskCheck now names why:
  no_address (no URL, or one that isn't a page's address),
  no_change_text (a written task with no new text to look for),
  from_bot_logs (a crawler fix raised from the bot logs, which robots.txt
  can't show done), and not_checkable for a library task checked
  elsewhere, as before. Each has its line in checkNot.
- The drawer showed Check now on every open Automatic task with a URL.
  It shows it where the API checks (pageCheckable): a library task in its
  CHECKS, or a written task with its new text. PAGE_CHECKED_TASKS copies
  the CHECKS keys; a test reads the server file and fails if they drift.

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

* fix(action-center): make the call-to-action task Manual, as no re-fetch can tell it's done

Follow-up C (round 36's item 9) from #1565's round 37. improve_cta_path
was checked Automatic as "changed since the first look", and it couldn't
pass: the content area leaves out a CTA band outside <main> (a rewritten
hero and CTA band read "not changed"), and a CTA edit is too few words for
the change rule anyway. Its template tasks carry no new text to look for
either.

Its template is now Manual, on the action's page (the URL still shows),
it's out of the API's CHECKS (and the web's PAGE_CHECKED_TASKS, so Check
now doesn't show), and its Done when reads "The call to action is live on
the page: you confirm it". Stacked on fix/task-check-now-reasons for the
web list. Tasks already planned keep check: auto; the sweep and Check now
now leave them, and they're marked done by hand.

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

* test(action-center): mock the supabase client in the templates test, which now reads task-checks

templates.test.js imports CHECKS from task-checks.js, which reaches the
supabase admin client at import time; its config hard-exits when the
SUPABASE_* env is absent, as in CI, so the whole file failed there. The
test mocks the client, as the other action-center tests do.

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

* fix(action-center): show a call-to-action task planned as Automatic as Manual, with no automatic check

A follow-up to the call-to-action task made Manual. Tasks planned before
keep check: auto in their details: the drawer said "How we check:
Automatic: we fetch the page again" and their old Last check, beside a
Done when that reads "you confirm it". No migration: the web reads them as
their template has them now.

- task-details.ts's MANUAL_TASKS lists the templates' Manual tasks (a test
  reads them from server tasks/templates.js, as PAGE_CHECKED_TASKS is read
  from CHECKS). withTemplateCheck gives such a task's details check:
  manual and no Last check; a page-checked task, a Site Audit fix
  (fix_technical_issue) and a written task keep theirs.
- The drawer's task (view and edit form), the exports (Copy Data, CSV,
  Excel, Word) and the MCP's get_action read them through it. Check now
  already left the task (pageCheckable).
- task-checks.js's header no longer lists the call to action among the
  "changed" checks.

Tests: an improve_cta_path task with check: auto and a failed last check
shows "Manual: you confirm it", no Automatic, no Last check, no Check now
(it failed before); refresh_content keeps all three; the export and MCP
give it manual; MANUAL_TASKS matches the server's templates.

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

* test(action-center): a read that throws still leaves the task tried

* fix(action-center): keep Check now on the shopping links task

The drawer's pageCheckable allowed only a library task it checks on its
page or a written task with new text, so the shopping links task (no task
key, no new text) lost Check now. Pass the action's kind and allow a
shopping_links action's task.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 28, 2026
…ge, and take a bigger one to pass (#1679)

* fix(action-center): don't pass a short page's "changed" check on blocks that change by themselves

Follow-up A from #1565's round 37. On pages of 60–400 words, a rotated
testimonial of about 28 words, a new 50-word review, and a "Latest posts"
list in a <div class="sidebar"> each passed "changed since its first
look": 41–66 changed runs, over MIN_CHANGED_RUNS (40). A rewritten 60-word
paragraph is 117 or more, a 150-word FAQ 146.

- MIN_CHANGED_RUNS is 80.
- The words a change is measured on (visibleText's new `steady`) leave out
  blocks whose class or id names what changes by itself: sidebar,
  widget(s), promo, announcement, pagination, tags, testimonial(s),
  latest, recent, popular, trending, with furniture's guard (a block
  holding more than half the page is the page). Only for "changed" and
  "published": a written task's text is still looked for everywhere, a
  testimonial included. The words are task-checks.js's own, so the
  editor's page import (page-content.js FURNITURE_WORDS) reads as before;
  page-content.js only exports classIdWords.
- A sketch now carries SKETCH_VERSION (2). A first look kept before this
  (no version) gets a new first look instead of a comparison, so a
  sidebar left out now never reads as the change. Such a task's first
  look restarts once.

Tests: each of the three blocks above leaves the page unchanged; a
rewritten 60-word paragraph passes; a task's text in a testimonial is
found; an unversioned first look is replaced. With the old threshold and
no blocks left out, the first fails. The guide's "Optimizing,
refreshing" line says so.

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

* fix(action-center): count page builders' widgets and a "Most popular" plan in the "changed" check

"widget", "widgets" and "popular" in a block's class or id left it out of
the words a change is measured on. Elementor puts elementor-widget on each
of the page's blocks, HubSpot widget-span: a page rewritten in full read
"not_changed" for good. A pricing page's class="popular" plan was left
out too.

- They are no longer such words alone. Two words one after the other
  still are: a theme's widget area (widget-area, Divi's et_pb_widget_area),
  footer widgets, popular posts or articles. A sidebar is left out as
  before (its "sidebar", or <aside>).

Tests: an Elementor and a HubSpot page rewritten in their widgets pass
(both read "not_changed" before); a class="popular" plan's text is read,
an <aside class="sidebar">, a widget-area and a popular-posts block aren't.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 28, 2026
…d from every way to add a brand, while the plan has ended (#1612)

* feat(web): let a workspace whose plan ended browse read-only, with one "Choose a plan" dialog

On the cloud, an ended trial, a cancel during the trial and a cancel
after the first payment can now sign in and look around. They used to
see a full-screen "subscription expired" notice that only signed out.
Onboarding is unchanged: an admin who never started a trial still goes
to the plan step.

- The dashboard layout lets these workspaces in, read-only. A thin
  banner says so, with "See plans".
- UpgradeDialogProvider and useUpgradeGate ({ guard, isLocked,
  openUpgrade }) open one "Choose a plan to keep going" dialog, with the
  action that was clicked as a label.
  - Admins go to Billing; members are told to ask their admin.
  - A failed payment (past_due, unpaid) says so and opens Stripe's
    portal.
  - A 402 subscription_inactive from the API opens the dialog
    (use-failure-toast, api-failure's subscription class, and the
    Webflow, catalog, publish and Send to CMS clients).
- Automatic calls (Library's Webflow status, the editor's link, source,
  claim and page reads, Improve's read) aren't sent while locked.
- Billing: an ended subscription starts a new Checkout ("Choose
  {plan}", monthly or annual). The checkout route takes admins only,
  refuses a second live subscription (409), and validates its body.
  Billing reads again after a change.
- MCP: list_ and get_ tools stay open; every other tool, and REST
  writes, answer subscription_inactive. Chat and new conversations
  answer 402, and runSiteAuditFor, generateBriefFor and
  createImproveActionFor check too. A chat message refused by a 402
  goes back to the input.

Self-hosted is unchanged.

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

* feat(web): open the plan dialog from the Prompts area's actions while the plan has ended

Read-only, part C1. On an ended plan, every action in Prompts, Prompt
Suggestions, Topics, Query Fan-out, Brand Visibility and Competitors
opens the "Choose a plan" dialog with the action named, and runs
nothing. On an active plan they run as before. Buttons aren't disabled.
- Tracked Prompts: add, import, edit, analyze and refresh volumes, the
  bulk bar, work status and the row menu.
- Prompt and topic suggestions: generate, add, accept, dismiss.
- Manage prompts and topics: add, generate, locations, analyze, edit,
  delete.
- Query Fan-out's Track; Brand Visibility's Run All, Test Single Prompt,
  Opportunities' Track and Send, and pinning a competitor.
- Competitors: suggest (its dialog calls AI on opening), add, delete.
- The Positions panel: Improve's Generate and Regenerate, Send Actions,
  and Create or Optimize content.
- The labels live in readOnly.actions.* ("Adding prompts needs a plan").
- volumes.ts tells the API's 402 subscription_inactive from a feature
  the plan lacks, so a refused analysis opens the dialog instead of "not
  part of your current plan".
- While locked, Tracked Prompts doesn't warn that volume data is
  unavailable, and Query Fan-out doesn't send its intent classification.

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

* feat(web): open the plan dialog from the content area's actions, and keep the editor read-only, while the plan has ended

Read-only, part C2. On an ended plan, every action that writes or costs
in Content Opportunities, the opportunity panel, Content Plan, Library,
New content and the Content Editor opens the "Choose a plan" dialog,
naming the action, and runs nothing.
- Opportunities: New, the bulk bar (send, done, dismiss and delete open
  the dialog instead of their confirm), the row menu, the webhook
  settings' Test and Save, and the panel's sends, brief, Reviewed,
  Restore and Dismiss.
- Plan: New content, Start, Assign, Priority, Hide and Show. A ?start=
  link starts nothing while locked.
- Library: New content (and ?new=1), status changes, archive, delete,
  and single and bulk Send to CMS.
- The editor:
  - Run Agent, Rewrite, Fix rules, hand-off;
  - accepting or rejecting suggestions;
  - Mark ready, Ready back to review, Mark published, Send to CMS,
    History Restore;
  - page and site type, author and reviewer;
  - Quality's confirms, sources and images, and Add line or Remove;
  - renaming, dropping files, the toolbar;
  - the Brief's run, rewrite and edit; the Sources and Rules changes;
    Your input.
- The editor itself is read-only while locked (editable: false, the
  HTML view readOnly), and autosave is off (useDraftAutosave { off }):
  nothing is saved, and leaving doesn't warn.
- Reading, filters, exports, Copy HTML and Stop stay open.

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

* feat(web): open the plan dialog from the remaining areas' actions, and from every way to add a brand, while the plan has ended

Site Audit, Action Center, Mentions, Citations, AI Referral Traffic,
Shopping, Reports, Chat, brand settings and Settings now guard their
actions with useUpgradeGate, as Prompts (#1606) and Content (#1609) do.
Every way to add a brand (sidebar, /dashboard/brands, brand guard,
/dashboard/brands/new) opens the dialog. Disconnects, key revokes and
API key creation stay open.

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

* fix(web): keep removing members, revoking invitations and disconnecting stores open while read-only, and stop the site trust card's automatic re-read

From the pre-push review: ending an access stays open, as disconnects
do; a partial site trust result isn't re-read while the plan has ended,
since that read scrapes. Adds tests for the audit page's Run audit and
the integrations' property mapping, resets shared mocks between tests,
closes the mobile menu before the dialog, and words the KPI preview for
a read-only workspace.

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

* fix(web): open the plan dialog from Add Brand at the plan's brand limit too, while read-only

At the limit, /dashboard/brands' Add Brand links to Billing; a read-only
workspace now gets the dialog there as on every other way to add a brand.

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

* feat(web): let a read-only workspace delete a brand

Ansvisor's decision (2026-10-27): deleting a brand only removes what the
person gave us, so it stays open while the plan has ended. The API opens
DELETE /brands/:id in #1611.

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

* fix(web): leave the plan dialog's store error out of the every-code message test

main's catalog-client test (#1583) asks for words for every StoreError
code; 'subscription' opens the upgrade dialog instead of saying one, so
the test leaves it out, as #1613 does.

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

* fix(web): open the plan dialog from Merchant Center, category pages and main's other new actions while the plan has ended

main's new writes, with C3's guard pattern and labels:
- Merchant Center (#1583): picking and adding an account open the plan
  dialog ("Connecting a store needs a plan"); the server's 'subscription'
  refusal on Add opens it too, instead of looking up a missing
  settings.catalog.stores.errors.subscription message.
- Category pages (#1587): Change, Save, No page and Use the match are
  guarded; the catalog client reads the server's 402
  subscription_inactive as 'subscription', which opens the dialog
  instead of the generic failure.
- Brief › Shopping path (#1591): Pick from the catalog, Pick again, Add
  product, Lock, Swap and Remove are guarded.
- Action Center Check now (AC-010, #1565) is guarded.

New labels: changeCategoryPages, changeShoppingPath, checkTasks.
Insert › Products (#1607) already goes through the toolbar's guard and
the read-only editor shows no insert menu; a test now says so. The
Shopping rules (#1610) change through the rules hook, already guarded.

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

* fix(web): check the plan inside Merchant Center's Add, not by wrapping it during render

React's refs rule refuses passing add, which reads addingRef, to guard
while rendering. add now opens the plan dialog itself on a read-only
workspace.

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

* test(web): keep brand setup's limits in the new brand page test's mock

main's new brand page now reads BRAND_SETUP_LIMITS from ai-brand-setup
(#1661), which the test's mock left out.

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

* fix(web): keep deleting a chat open on a read-only workspace

The API (#1613) leaves deleting a conversation open and the FAQ (#1631)
lists it among what still works, so the chat page asks before deleting
instead of opening the plan dialog. It costs nothing, and people can
always remove their own conversations.

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

* test(web): delete a chat conversation on a read-only workspace through its confirm

The test opened the confirm only; it now presses Delete and expects the
DELETE request, with no plan dialog. The file's header says deleting
stays open.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 28, 2026
… plan has ended, and keep the buttons opening the plan dialog (#1614)

* feat(web): let a workspace whose plan ended browse read-only, with one "Choose a plan" dialog

On the cloud, an ended trial, a cancel during the trial and a cancel
after the first payment can now sign in and look around. They used to
see a full-screen "subscription expired" notice that only signed out.
Onboarding is unchanged: an admin who never started a trial still goes
to the plan step.

- The dashboard layout lets these workspaces in, read-only. A thin
  banner says so, with "See plans".
- UpgradeDialogProvider and useUpgradeGate ({ guard, isLocked,
  openUpgrade }) open one "Choose a plan to keep going" dialog, with the
  action that was clicked as a label.
  - Admins go to Billing; members are told to ask their admin.
  - A failed payment (past_due, unpaid) says so and opens Stripe's
    portal.
  - A 402 subscription_inactive from the API opens the dialog
    (use-failure-toast, api-failure's subscription class, and the
    Webflow, catalog, publish and Send to CMS clients).
- Automatic calls (Library's Webflow status, the editor's link, source,
  claim and page reads, Improve's read) aren't sent while locked.
- Billing: an ended subscription starts a new Checkout ("Choose
  {plan}", monthly or annual). The checkout route takes admins only,
  refuses a second live subscription (409), and validates its body.
  Billing reads again after a change.
- MCP: list_ and get_ tools stay open; every other tool, and REST
  writes, answer subscription_inactive. Chat and new conversations
  answer 402, and runSiteAuditFor, generateBriefFor and
  createImproveActionFor check too. A chat message refused by a 402
  goes back to the input.

Self-hosted is unchanged.

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

* feat(web): open the plan dialog from the Prompts area's actions while the plan has ended

Read-only, part C1. On an ended plan, every action in Prompts, Prompt
Suggestions, Topics, Query Fan-out, Brand Visibility and Competitors
opens the "Choose a plan" dialog with the action named, and runs
nothing. On an active plan they run as before. Buttons aren't disabled.
- Tracked Prompts: add, import, edit, analyze and refresh volumes, the
  bulk bar, work status and the row menu.
- Prompt and topic suggestions: generate, add, accept, dismiss.
- Manage prompts and topics: add, generate, locations, analyze, edit,
  delete.
- Query Fan-out's Track; Brand Visibility's Run All, Test Single Prompt,
  Opportunities' Track and Send, and pinning a competitor.
- Competitors: suggest (its dialog calls AI on opening), add, delete.
- The Positions panel: Improve's Generate and Regenerate, Send Actions,
  and Create or Optimize content.
- The labels live in readOnly.actions.* ("Adding prompts needs a plan").
- volumes.ts tells the API's 402 subscription_inactive from a feature
  the plan lacks, so a refused analysis opens the dialog instead of "not
  part of your current plan".
- While locked, Tracked Prompts doesn't warn that volume data is
  unavailable, and Query Fan-out doesn't send its intent classification.

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

* feat(web): open the plan dialog from the content area's actions, and keep the editor read-only, while the plan has ended

Read-only, part C2. On an ended plan, every action that writes or costs
in Content Opportunities, the opportunity panel, Content Plan, Library,
New content and the Content Editor opens the "Choose a plan" dialog,
naming the action, and runs nothing.
- Opportunities: New, the bulk bar (send, done, dismiss and delete open
  the dialog instead of their confirm), the row menu, the webhook
  settings' Test and Save, and the panel's sends, brief, Reviewed,
  Restore and Dismiss.
- Plan: New content, Start, Assign, Priority, Hide and Show. A ?start=
  link starts nothing while locked.
- Library: New content (and ?new=1), status changes, archive, delete,
  and single and bulk Send to CMS.
- The editor:
  - Run Agent, Rewrite, Fix rules, hand-off;
  - accepting or rejecting suggestions;
  - Mark ready, Ready back to review, Mark published, Send to CMS,
    History Restore;
  - page and site type, author and reviewer;
  - Quality's confirms, sources and images, and Add line or Remove;
  - renaming, dropping files, the toolbar;
  - the Brief's run, rewrite and edit; the Sources and Rules changes;
    Your input.
- The editor itself is read-only while locked (editable: false, the
  HTML view readOnly), and autosave is off (useDraftAutosave { off }):
  nothing is saved, and leaving doesn't warn.
- Reading, filters, exports, Copy HTML and Stop stay open.

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

* feat(web): open the plan dialog from the remaining areas' actions, and from every way to add a brand, while the plan has ended

Site Audit, Action Center, Mentions, Citations, AI Referral Traffic,
Shopping, Reports, Chat, brand settings and Settings now guard their
actions with useUpgradeGate, as Prompts (#1606) and Content (#1609) do.
Every way to add a brand (sidebar, /dashboard/brands, brand guard,
/dashboard/brands/new) opens the dialog. Disconnects, key revokes and
API key creation stay open.

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

* fix(web): keep removing members, revoking invitations and disconnecting stores open while read-only, and stop the site trust card's automatic re-read

From the pre-push review: ending an access stays open, as disconnects
do; a partial site trust result isn't re-read while the plan has ended,
since that read scrapes. Adds tests for the audit page's Run audit and
the integrations' property mapping, resets shared mocks between tests,
closes the mobile menu before the dialog, and words the KPI preview for
a read-only workspace.

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

* fix(web): open the plan dialog from Add Brand at the plan's brand limit too, while read-only

At the limit, /dashboard/brands' Add Brand links to Billing; a read-only
workspace now gets the dialog there as on every other way to add a brand.

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

* feat(web): let a read-only workspace delete a brand

Ansvisor's decision (2026-10-27): deleting a brand only removes what the
person gave us, so it stays open while the plan has ended. The API opens
DELETE /brands/:id in #1611.

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

* feat(web): show "No active plan" instead of a used-up quota while the plan has ended, and keep the buttons opening the plan dialog

With #1611, an ended workspace's quota reads come back as `noPlan` with
0 limits. isNoPlan(quota, isLocked) keeps those from reading as used up:
Site Audit, Prompts, the content usage card, Improve and the opportunity
panel say "No active plan" instead of a red 0/0 or "limit reached", and
their buttons stay clickable so the guard opens the dialog. The AI bot
report shows the workspace's own data instead of the Starter upsell.
Setup's suggestions name the onboarding daily limit (429) on their own.

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

* fix(web): keep a saved content suggestion reachable, the Starter bot upsell and one lock rule while the plan has ended

From the pre-push review: the Prompts row menu still looks up an open
content suggestion with no plan; an ended Starter workspace keeps the
bot report's upsell (its old plan has no report), read from the plan
the web already knows; auditBlock, bulkSuggestBlock and the bot states
take isLocked as the pages do; the audit settings and the content usage
tooltip don't speak of a plan that renews; setup's prompt step keeps its
own "add your own" line. Improve's unreachable no-plan branch is gone.
Tests for the onboarding limit and the quota meter.

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

* fix(web): leave the plan dialog's store error out of the every-code message test

main's catalog-client test (#1583) asks for words for every StoreError
code; 'subscription' opens the upgrade dialog instead of saying one, so
the test leaves it out, as #1613 does.

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

* fix(web): open the plan dialog from Merchant Center, category pages and main's other new actions while the plan has ended

main's new writes, with C3's guard pattern and labels:
- Merchant Center (#1583): picking and adding an account open the plan
  dialog ("Connecting a store needs a plan"); the server's 'subscription'
  refusal on Add opens it too, instead of looking up a missing
  settings.catalog.stores.errors.subscription message.
- Category pages (#1587): Change, Save, No page and Use the match are
  guarded; the catalog client reads the server's 402
  subscription_inactive as 'subscription', which opens the dialog
  instead of the generic failure.
- Brief › Shopping path (#1591): Pick from the catalog, Pick again, Add
  product, Lock, Swap and Remove are guarded.
- Action Center Check now (AC-010, #1565) is guarded.

New labels: changeCategoryPages, changeShoppingPath, checkTasks.
Insert › Products (#1607) already goes through the toolbar's guard and
the read-only editor shows no insert menu; a test now says so. The
Shopping rules (#1610) change through the rules hook, already guarded.

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

* fix(web): check the plan inside Merchant Center's Add, not by wrapping it during render

React's refs rule refuses passing add, which reads addingRef, to guard
while rendering. add now opens the plan dialog itself on a read-only
workspace.

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

* test(web): keep brand setup's limits in the new brand page test's mock

main's new brand page now reads BRAND_SETUP_LIMITS from ai-brand-setup
(#1661), which the test's mock left out.

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

* fix(web): keep deleting a chat open on a read-only workspace

The API (#1613) leaves deleting a conversation open and the FAQ (#1631)
lists it among what still works, so the chat page asks before deleting
instead of opening the plan dialog. It costs nothing, and people can
always remove their own conversations.

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

* test(web): delete a chat conversation on a read-only workspace through its confirm

The test opened the confirm only; it now presses Delete and expects the
DELETE request, with no plan dialog. The file's header says deleting
stays open.

* test(onboarding): mock the menu access actions in the onboarding page test

Main's "What do you work on?" step brought menu access's server actions
into the onboarding page, and with them the service client, which the test
can't build without its keys: the file failed to load.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 29, 2026
…ying or a free trial (demo brand, part 5) (#1738)

* feat(web): let a workspace whose plan ended browse read-only, with one "Choose a plan" dialog

On the cloud, an ended trial, a cancel during the trial and a cancel
after the first payment can now sign in and look around. They used to
see a full-screen "subscription expired" notice that only signed out.
Onboarding is unchanged: an admin who never started a trial still goes
to the plan step.

- The dashboard layout lets these workspaces in, read-only. A thin
  banner says so, with "See plans".
- UpgradeDialogProvider and useUpgradeGate ({ guard, isLocked,
  openUpgrade }) open one "Choose a plan to keep going" dialog, with the
  action that was clicked as a label.
  - Admins go to Billing; members are told to ask their admin.
  - A failed payment (past_due, unpaid) says so and opens Stripe's
    portal.
  - A 402 subscription_inactive from the API opens the dialog
    (use-failure-toast, api-failure's subscription class, and the
    Webflow, catalog, publish and Send to CMS clients).
- Automatic calls (Library's Webflow status, the editor's link, source,
  claim and page reads, Improve's read) aren't sent while locked.
- Billing: an ended subscription starts a new Checkout ("Choose
  {plan}", monthly or annual). The checkout route takes admins only,
  refuses a second live subscription (409), and validates its body.
  Billing reads again after a change.
- MCP: list_ and get_ tools stay open; every other tool, and REST
  writes, answer subscription_inactive. Chat and new conversations
  answer 402, and runSiteAuditFor, generateBriefFor and
  createImproveActionFor check too. A chat message refused by a 402
  goes back to the input.

Self-hosted is unchanged.

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

* feat(billing): show the plans in the read-only dialog, with Monthly or Annual and a promo code

The "Choose a plan to keep going" dialog for an ended plan now carries
the plans, as the approved design has them.
- Starter and Growth (Popular) have "Choose {plan}"; Custom has "Starting
  at $499/mo" and "Contact us". Each lists the Billing cards' features,
  through a shared usePlanFeatures.
- Monthly or Annual ("Save 20%"): an annual price shows its struck 12×
  price and what it is a month.
- A promo code is checked by the API (POST /api/stripe/promo-code, admins
  only), through the same Stripe lookup #1300 uses (findPromotionCode,
  takesPromoCode: monthly plans only).
  - A valid code shows its chip, the first month's price on each card and
    in the button ("Choose Growth · $124.50 today").
  - A bad one says so; on Annual a note offers Switch to Monthly.
- Choose opens Stripe Checkout for that plan and period, with the code
  applied as a discount. The checkout route checks the code again and
  refuses it on an annual plan.
- Members see "Ask your admin to choose a plan", with no code field.
- The footer reads "Prices in USD." with a link to the pricing page.
- A failed payment keeps its "Update payment method" dialog.

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

* fix(billing): word the dialog's custom AI usage "from 10x", as Billing does after #1598

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

* feat(web): open the plan dialog from the Prompts area's actions while the plan has ended

Read-only, part C1. On an ended plan, every action in Prompts, Prompt
Suggestions, Topics, Query Fan-out, Brand Visibility and Competitors
opens the "Choose a plan" dialog with the action named, and runs
nothing. On an active plan they run as before. Buttons aren't disabled.
- Tracked Prompts: add, import, edit, analyze and refresh volumes, the
  bulk bar, work status and the row menu.
- Prompt and topic suggestions: generate, add, accept, dismiss.
- Manage prompts and topics: add, generate, locations, analyze, edit,
  delete.
- Query Fan-out's Track; Brand Visibility's Run All, Test Single Prompt,
  Opportunities' Track and Send, and pinning a competitor.
- Competitors: suggest (its dialog calls AI on opening), add, delete.
- The Positions panel: Improve's Generate and Regenerate, Send Actions,
  and Create or Optimize content.
- The labels live in readOnly.actions.* ("Adding prompts needs a plan").
- volumes.ts tells the API's 402 subscription_inactive from a feature
  the plan lacks, so a refused analysis opens the dialog instead of "not
  part of your current plan".
- While locked, Tracked Prompts doesn't warn that volume data is
  unavailable, and Query Fan-out doesn't send its intent classification.

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

* feat(web): open the plan dialog from the content area's actions, and keep the editor read-only, while the plan has ended

Read-only, part C2. On an ended plan, every action that writes or costs
in Content Opportunities, the opportunity panel, Content Plan, Library,
New content and the Content Editor opens the "Choose a plan" dialog,
naming the action, and runs nothing.
- Opportunities: New, the bulk bar (send, done, dismiss and delete open
  the dialog instead of their confirm), the row menu, the webhook
  settings' Test and Save, and the panel's sends, brief, Reviewed,
  Restore and Dismiss.
- Plan: New content, Start, Assign, Priority, Hide and Show. A ?start=
  link starts nothing while locked.
- Library: New content (and ?new=1), status changes, archive, delete,
  and single and bulk Send to CMS.
- The editor:
  - Run Agent, Rewrite, Fix rules, hand-off;
  - accepting or rejecting suggestions;
  - Mark ready, Ready back to review, Mark published, Send to CMS,
    History Restore;
  - page and site type, author and reviewer;
  - Quality's confirms, sources and images, and Add line or Remove;
  - renaming, dropping files, the toolbar;
  - the Brief's run, rewrite and edit; the Sources and Rules changes;
    Your input.
- The editor itself is read-only while locked (editable: false, the
  HTML view readOnly), and autosave is off (useDraftAutosave { off }):
  nothing is saved, and leaving doesn't warn.
- Reading, filters, exports, Copy HTML and Stop stay open.

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

* feat(web): open the plan dialog from the remaining areas' actions, and from every way to add a brand, while the plan has ended

Site Audit, Action Center, Mentions, Citations, AI Referral Traffic,
Shopping, Reports, Chat, brand settings and Settings now guard their
actions with useUpgradeGate, as Prompts (#1606) and Content (#1609) do.
Every way to add a brand (sidebar, /dashboard/brands, brand guard,
/dashboard/brands/new) opens the dialog. Disconnects, key revokes and
API key creation stay open.

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

* feat(web): refuse direct database writes from a workspace whose plan has ended, on the server

Server actions and Next routes that write to Supabase without going
through the API now call assertWritable() first: on the cloud, an
organization without an active plan gets SubscriptionInactiveError
(routes: 402 subscription_inactive), so the read-only rule holds even if
a guarded button is bypassed. Setup's writes stay open to an
organization that never subscribed, as the API's onboarding routes do.
Profile, invitations accepted, revokes, removals, API keys and billing
stay open. A static test pins every writing action to the check or to
the open list.

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

* fix(web): keep removing members, revoking invitations and disconnecting stores open while read-only, and stop the site trust card's automatic re-read

From the pre-push review: ending an access stays open, as disconnects
do; a partial site trust result isn't re-read while the plan has ended,
since that read scrapes. Adds tests for the audit page's Run audit and
the integrations' property mapping, resets shared mocks between tests,
closes the mobile menu before the dialog, and words the KPI preview for
a read-only workspace.

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

* fix(web): open the plan dialog from Add Brand at the plan's brand limit too, while read-only

At the limit, /dashboard/brands' Add Brand links to Billing; a read-only
workspace now gets the dialog there as on every other way to add a brand.

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

* feat(web): let a read-only workspace delete a brand

Ansvisor's decision (2026-10-27): deleting a brand only removes what the
person gave us, so it stays open while the plan has ended. The API opens
DELETE /brands/:id in #1611.

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

* fix(web): keep setup's Shopping mode working for a new workspace, read the plan in one query, and pin the write check's place

From the pre-push review: markBrandAsEcommerce no longer goes through
the strictly guarded setBrandShoppingMode (a shared applyShoppingMode
does the writes), so a setup detected as e-commerce turns Shopping on
again. assertWritable reads the profile and its organization in one
query. The coverage test now requires the check as each writer's first
await, sees writers kept in variables and signed upload URLs, refuses a
setup-open function that reaches a strictly guarded one, and keeps brand
deletion open (Ansvisor, 2026-10-27). main's saveDraftShoppingPath is
guarded; catalog-client's every-code test leaves out 'subscription',
which opens the plan dialog instead of a message.

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

* feat(web): show "No active plan" instead of a used-up quota while the plan has ended, and keep the buttons opening the plan dialog

With #1611, an ended workspace's quota reads come back as `noPlan` with
0 limits. isNoPlan(quota, isLocked) keeps those from reading as used up:
Site Audit, Prompts, the content usage card, Improve and the opportunity
panel say "No active plan" instead of a red 0/0 or "limit reached", and
their buttons stay clickable so the guard opens the dialog. The AI bot
report shows the workspace's own data instead of the Starter upsell.
Setup's suggestions name the onboarding daily limit (429) on their own.

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

* fix(web): keep a saved content suggestion reachable, the Starter bot upsell and one lock rule while the plan has ended

From the pre-push review: the Prompts row menu still looks up an open
content suggestion with no plan; an ended Starter workspace keeps the
bot report's upsell (its old plan has no report), read from the plan
the web already knows; auditBlock, bulkSuggestBlock and the bot states
take isLocked as the pages do; the audit settings and the content usage
tooltip don't speak of a plan that renews; setup's prompt step keeps its
own "add your own" line. Improve's unreachable no-plan branch is gone.
Tests for the onboarding limit and the quota meter.

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

* fix(web): leave the plan dialog's store error out of the every-code message test

main's catalog-client test (#1583) asks for words for every StoreError
code; 'subscription' opens the upgrade dialog instead of saying one, so
the test leaves it out, as #1613 does.

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

* fix(web): open the plan dialog from Merchant Center, category pages and main's other new actions while the plan has ended

main's new writes, with C3's guard pattern and labels:
- Merchant Center (#1583): picking and adding an account open the plan
  dialog ("Connecting a store needs a plan"); the server's 'subscription'
  refusal on Add opens it too, instead of looking up a missing
  settings.catalog.stores.errors.subscription message.
- Category pages (#1587): Change, Save, No page and Use the match are
  guarded; the catalog client reads the server's 402
  subscription_inactive as 'subscription', which opens the dialog
  instead of the generic failure.
- Brief › Shopping path (#1591): Pick from the catalog, Pick again, Add
  product, Lock, Swap and Remove are guarded.
- Action Center Check now (AC-010, #1565) is guarded.

New labels: changeCategoryPages, changeShoppingPath, checkTasks.
Insert › Products (#1607) already goes through the toolbar's guard and
the read-only editor shows no insert menu; a test now says so. The
Shopping rules (#1610) change through the rules hook, already guarded.

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

* fix(web): check the plan inside Merchant Center's Add, not by wrapping it during render

React's refs rule refuses passing add, which reads addingRef, to guard
while rendering. add now opens the plan dialog itself on a read-only
workspace.

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

* test(web): keep brand setup's limits in the new brand page test's mock

main's new brand page now reads BRAND_SETUP_LIMITS from ai-brand-setup
(#1661), which the test's mock left out.

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

* feat(demo): open the plan dialog with the demo's offer on a demo brand

The selected brand being the organization's demo brand (brands.is_demo,
sample data) locks the dashboard as a read-only workspace is locked, with
its own reason: guarded actions open the plan dialog with the demo's offer.
A workspace that never subscribed is offered the free trial, then 50% off
("Start free trial"); one whose plan ended gets 50% off its first month
("Choose {plan}"). The label names what was clicked as something that
works on your own brand, and an admin finds SAVE50 applied (quietly left
empty when Stripe refuses it). With a plan active, the dialog points back
to the workspace's own brand; a payment being retried still asks for the
payment method. The server's 402 demo_brand opens the same dialog.

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

* feat(demo): show a band across the dashboard while the demo brand is open

Where the read-only band sits, and instead of it: "You're exploring
{brand}, a demo brand with sample data", with a small button to the plan
dialog's offer ("Try it on your brand · 50% off" for a workspace that never
subscribed, "Use it for your brand · 50% off" once its plan ended), or back
to the own brand while a plan is active. The band asks the API once per page
load to bring the demo brand up to date (POST /api/demo) and reads the
pages again when its sample data was written anew, so the demo follows the
product by itself.

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

* feat(demo): add a demo brand per organization, kept out of the plan's counts

Migration 00380 adds brands.is_demo, demo_version, demo_built_at and
demo_hidden_at, one demo brand per organization (partial unique index) and
policies that let members read it but never insert, change or delete one.
The plan's prompt-location quota, the usage cards' account totals and the
web's brand limit leave the demo brand out; the health report's fan-out
share leaves out its answers. The brand delete route refuses it: the demo
brand is hidden, not deleted.

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

* feat(demo): skip demo brands in every nightly sweep and job

The daily tracking list, the job claim and recovery (activeBrandFilter /
isBrandActive), the signal catch-up, the pulse, the task writer, executor
and checks, action validation and Improve outcomes, the Insights sweep,
brand facts, Search Console and Analytics syncs, page opportunities, the
traffic digest, auto-audits, catalog feeds, Webflow status and volume
analysis all leave demo brands out: their data is sample data and nothing
may track, write or spend for it.

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

* feat(demo): mark the demo brand in the brand switcher, with Show or Hide

The demo brand reads "Demo · sample data" under its name, in place of a
domain, and a brand of a workspace that never had a plan reads "Not tracked
yet". For an admin or a manager, the menu ends with "Hide the demo brand"
(PATCH /api/demo), or "Show the demo brand" once it is hidden, which brings
it back and opens it: the demo brand is hidden after a purchase, never
deleted. A hidden demo brand stays out of the dashboard's brand list and
the brands page, and the demo brand never counts toward the plan's brands,
there or when a brand is added.

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

* feat(demo): show Chat as coming next week on the demo brand, with its v2 preview

On the demo brand, the menu's Chat item carries "Soon (next week)" in its
badge, ahead of "Set up" (the badge rule now lives in dashboardNavBadge, for
the sidebar and the mobile menu alike), and /dashboard/agent shows the Chat
v2 mockups themselves in a full-height frame, opening on Home, under a thin
line that Chat arrives next week. The five mockup files are copied as they
are into public/demo/chat (about 720 KB), outside Prettier's scope. On any
other brand, Chat is unchanged.

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

* feat(demo): show the demo brand's integrations connected, and those to come as coming soon

On the demo brand, Settings › Integrations shows the real cards with the
demo's states, kept in one list (lib/demo/integrations.ts): Google Search
Console, Google Analytics and Webflow as connected, the way they look with
a live connection, marked "Sample data", the demo brand mapped to a sample
property and Webflow sending to a sample collection, with nothing read from
the API or Composio and no set-up lines. Disconnect and Replace token open
the plan dialog. Merchant Center shows Coming soon on its own card, and
Shopify, WordPress, Framer and Wix, which have no card yet, a Coming soon
row in their group. When one goes live, its line in the list turns
connected.

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

* feat(demo): build the Brewline Coffee demo brand's core data

lib/demo/ builds an organization's demo brand in its own brands: Brewline
Coffee (brewline.example) with fictional `.example` competitors and
publishers, 12 prompts in 3 topics, 6 engines and a run every 3 days over
a month (720 short answers) with citations, product cards, searches and
volumes. Answers are raw engine responses run through tracking's own
parseScraperResponse, parseResponse and the result and shopping card rows
(now pure resultRow and shoppingCardRows in cloro-result-handler.js), and
the rollups are rebuilt by the nightly run's own functions.

ensureDemoBrand creates it, rebuilds it in place (same ids) when
DEMO_VERSION moves on or its data is three days old, and leaves it alone
otherwise; concurrent visits share one build (one-per-org index, a
compare-and-set claim, a lease). Modules are { name, tables, build }, and
a coverage test fails on any brand_id table the demo neither builds nor
lists as skipped or pending.

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

* feat(demo): open and hide the demo brand through /api/demo

POST /api/demo creates or rebuilds the organization's demo brand for any
member and returns { brandId, version, rebuilt }; PATCH /api/demo
{ hidden } hides or shows it for admins and managers ({ brandId, hidden },
404 no_demo without one). Both stay open once a plan has ended.

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

* feat(demo): let a workspace with no plan explore the demo brand

Onboarding's plan step gets a second way in under the plan cards: "Not
ready to add a card? Explore a demo brand", whose button makes the demo
brand (POST /api/demo), selects it and opens the Action Center, the
person's own brand kept as set up. An admin who never subscribed used to be
sent back to that step from the dashboard; with a demo brand in the
organization, they now browse read-only instead (evaluateSubscriptionAccess
takes hasDemoBrand). The read-only band of an ended or canceled plan gets
"See the demo", for an admin or a manager, or anyone once the demo brand is
listed: the same flow, which shows a hidden demo brand again. The plan
step's preview reads the own brand, never the demo brand.

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

* feat(demo): offer the free trial on the own brand of a workspace that never had a plan

A workspace that never subscribed now gets the trial offer on its own
brand too, not only on the demo brand: the read-only band says the brand
isn't tracked yet ("Start your 14-day free trial, then get 50% off your
first month") with Start free trial for admins, and the dialog's title is
"Start your 14-day free trial: then 50% off your first month", with SAVE50
applied and Start free trial on each plan. Members are asked to have an
admin start it. ChoosePlanDialog takes the offer as a `pitch` (from the
demo brand, or the own brand).

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

* feat(demo): show what is paid today on the demo's first-month offer

With SAVE50 applied, the demo's 50%-off-first-month offer words its
buttons as the plan dialog does everywhere else: "Choose Starter · $24.50
today"; "Choose {plan}" alone when the code didn't apply.

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

* feat(demo): say the demo brand is hidden, not deleted, in its Danger tab

On the demo brand, brand settings' Danger tab says "The demo brand can't
be deleted; hide it from the brand menu instead." in place of the name to
confirm, and Delete brand stays disabled. The server refuses the delete
too.

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

* feat(demo): cancel a demo brand's jobs as demo_brand, not as an ended plan

A job claimed for a demo brand ("Run now", the internal trigger, a retry
or the recovery) was cancelled as subscription_inactive, as if the plan had
ended. It now says demo_brand: brandStopReasons tells why no work may start
for a brand, and activeBrandFilter is built on it. Nothing is tracked,
generated or counted before the cancel: the on-demand cap counts the
brand's own jobs, and AI usage is recorded by the workers, which never run.

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

* feat(demo): refuse the web app's own writes on the demo brand

assertWritable takes the brand an action writes for and refuses the demo
brand (DemoBrandError, digest demo_brand), whatever the plan, reading the
brand beside the plan through the person's session. Every gated server
action that takes a brand id hands it over (52 of them, the brand's own id
in updateBrand); actions that name no brand, such as the profile or the
organization, read nothing more. A route's refusal answers 402 demo_brand,
and the browser reads the digest as it reads subscription_inactive: an
uncaught refusal opens the plan dialog. The read-only coverage test now
also fails a gated action that takes a brand id without handing it to the
check.

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

* feat(demo): refuse writes and costs on the demo brand with 402 demo_brand

The demo brand's data is sample data, so nothing asked of it may change it
or start a cost. A middleware after decodeToken (before the plan's check,
so the answer is the same with a plan or without) refuses every write that
names a demo brand: in the path, the body, the query, or through the row it
acts on (a draft, an opportunity, a prompt, a task...). Every write route
under /api is named, guarded or open with its reason (onboarding, the
organization's own integrations, stopping work, the demo routes, brand
delete's own 409); a test reads the route files and fails on one that
isn't. Reads and exports stay open; brand facts are read only as kept on a
demo brand, so its site is never fetched.

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

* feat(demo): hide the demo brand once a plan is bought

When a subscription starts (Stripe's checkout.session.completed, trial
included, and the return from Checkout, whichever comes first), the
organization's demo brand gets demo_hidden_at, through the service role:
hidden, never deleted. Only a demo brand still shown is touched, and
subscription updates, renewals and payments never touch it, so one an admin
shows again stays shown. A first payment still open hides nothing, and a
failed write never fails the purchase. Hidden before the dashboard opens,
the demo brand leaves the brand list, so the person lands on their own
brand.

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

* feat(demo): refuse people's writes to a demo brand's rows in the database

Members can write a brand's rows straight through Supabase, under RLS,
past the API's 402. Migration 00381 adds refuse_demo_brand_writes(), a
BEFORE INSERT/UPDATE/DELETE row trigger that raises 42501 'demo_brand' for
a demo brand's row unless the role bypasses RLS (the service role the
server and the demo generator write with). It is attached to the 24 tables
people can write that carry a brand_id, and, through their parent row, to
the 13 that reach their brand another way (prompts through prompt_sets,
prompt notes and target URLs through prompts, a draft's inputs and sources
through content_drafts, tasks and events through actions...). A test reads
the policies and triggers from the migrations and fails on a table people
can write that belongs to a brand and lacks it.

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

* feat(demo): refuse the MCP's brief, audit and Improve endpoints on a demo brand

The internal endpoints the MCP calls (a content brief, a Site Audit, an
Improve action) trust CRON_SECRET and never meet the API's middleware.
Each now answers a demo brand with 402 demo_brand before it calls the
model, starts an audit or writes an action; the MCP relays the message.

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

* feat(demo): clear demo brands nobody opened for two weeks, nightly

Every organization gets a demo brand, so its sample rows would pile up
for workspaces that left. The daily run now clears the data of demo brands
built over 14 days ago (a visit rebuilds every few days, so these weren't
opened since), 200 a night at most: through clearDemoData, the path a
rebuild takes, so rows go in the modules' reverse order. The brand row
stays with no version and no build time, and the next visit builds it
again in place, with the same ids. The clear holds the brand as a build
does, so a visit at the same moment waits for it.

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

* test(demo): look rows up by a set in the demo guard's fake database

The cache test reads 10,000 brands; filtering them with includes() took
seconds and timed out under a full run.

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

* feat(demo): build the demo brand's Action Center, Content, suggestions and reports

Four demo modules over core's answers: signals and a month of actions
(tasks, trail, measured outcomes, a task waiting for review, ready-made
KPIs, Getting started with its page steps opened), prompt clusters,
content opportunities, Editor drafts and Plan marks, prompt, topic and
Improve suggestions, and two saved reports. Numbers are counted from the
demo's own answers; shapes come from the engine's own functions. detect.js
exports single and promptTarget so the demo writes signals in their shape.

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

* feat(demo): register the workflow modules and rebuild demos at version 2

DEMO_MODULES runs core, suggestions, actionCenter, content and reports;
DEMO_VERSION 2 rebuilds existing demo brands on their next visit. The
coverage lists move the workflow tables to built, skip the engine's
internal queues and logs and the org-level author default, and leave the
draft shopping check to demo-site with the catalog.

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

* refactor(audit): read a page already fetched into the audit context with auditContextOf

buildAuditContext fetches the page, robots.txt and llms.txt, then hands
them to auditContextOf, which parses the HTML once and extracts its text
as before. A page that isn't fetched (the demo brand's) is read exactly as
a fetched one.

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

* feat(demo): build the demo brand's AI Referral Traffic over a quarter

Brewline's website (site-world.js) and its traffic: 90 days of Google
Analytics as GA4 reports mapped by ga-sync.js (AI sessions by source and
page, ChatGPT Shopping's feed visits, pages, channels, items), Search
Console's query and page rows mapped by gsc-sync.js, four weeks of snippet
visits (a removed guide's 404s for Broken AI links) and journeys made by
traffic-events.js's eventRow, a month of AI crawler counts with a
Cloudflare Worker connection whose secret hash matches no secret, and the
page opportunities detectPageOpportunities finds in them. The brand maps
the sample GA4 and Search Console properties and has conversions on.

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

* feat(demo): build the demo brand's Site Audit from the audit engine's own verdicts

Brewline's pages are rendered as HTML round by round and scored by
runSignals and scoreAudit: six key pages audited three times as fixes
land, every page in the latest auto-audit. The model-judged signals,
Wikidata's brand entity and the recommendations are written in the shapes
those steps store. The page inventory goes through selectPages and
parseHead, site trust through site-trust.js's checks (4/5: no editorial
policy), and the brand facts through factText and keptFacts.

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

* feat(demo): fill the demo brand's catalog from its product feed

A Google XML feed of 22 products read by the feed parser and kept as
catalogRecords and hashOf keep them, with stable demo ids: a removed
seasonal blend, an out-of-stock size, a sale, no images. The products the
demo's AI answers show as cards are the same page, title and price. Two
categories get their page by hand; the rest match their collection pages.

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

* feat(demo): classify the demo's fan-out searches ahead in the intent cache

The demo writes the intent of each search its answers ran into
fanout_query_intents, keyed as the route keys it (normalizeIntentQuery,
moved to intent-extraction.js), adding only what the shared cache lacks,
so Query Fan-out never needs a model for the demo.

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

* feat(demo): build traffic, Site Audit, the catalog and fan-out intents with the demo brand (version 3)

The demo-site modules join the core in DEMO_MODULES, and DEMO_VERSION is
3, so every demo brand is rebuilt with them on its next visit. Their
tables leave the coverage test's pending list; a CMS connection, sent
drafts, product images and Merchant Center item issues are skipped, with
why.

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

* test(demo): audit the demo's pages once more, not twice, to check its rows stay the same

One rebuild for another brand two days later checks both that only the
ids and dates change, with room past the default 5 s on a busy machine.

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

* feat(demo): give the demo brand its own logo

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

* fix(web): read a new sign-up's free plan as Starter's

A new sign-up's organization holds plan 'free' until it picks one. With the
demo brand it reaches the dashboard, where PLANS[planId].limits threw on the
Prompts page. toPlanId maps an unknown plan to Starter's.

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

* feat(demo): give the demo's made-up sites real-looking logos

.example is reserved, so no favicon service knows the demo's brand,
competitors or cited sites. Their logos ship in public/demo/logos; any
other .example site gets a letter mark, so no page asks Google for one.

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

* feat(billing): offer two ways to start a plan: buy now at 50% off the first month, or the free trial

Every plan choice now offers two ways to start, each with a card. Buy now
bills the full plan from day one, with the first-month offer on a monthly
plan ("$24.50 first month, then $49/month", a Limited offer mark); a year
up front is the plain "Choose {plan}". The 14-day free trial comes without
the offer, with limited AI usage ("Free for 14 days, then $49/month"), and
only for an organization that never had a subscription. Checkout takes the
way explicitly (mode: 'buy' | 'trial'): buying never starts a trial, the
trial takes no promotion code and is refused (409 trial_unavailable) to an
organization that had a subscription, and both collect a card. The offer
is one setting, FIRST_MONTH_OFFER in config/plans.ts, turned off with
NEXT_PUBLIC_FIRST_MONTH_OFFER=off; its code no longer redeemable falls back
to the plain price.

The plan dialog (demo, a brand not tracked yet, a plan that ended), the
demo band and the "not tracked yet" band ("Start a 14-day free trial, or
get 50% off your first month." with See plans) and onboarding's plan step
("Choose how to start", two buttons per plan, the demo card below) say it
this way; the "14 days free, then 50% off" wording is gone. Billing's
Checkout for a plan that ended buys now.

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

* feat(demo): start the demo brand's setup ahead, where the demo is offered

The demo brand's first setup takes a while, and "Explore the demo" waited
for all of it. Onboarding's plan step, for an organization with no demo
brand yet, and the read-only band's "See the demo", for an admin or a
manager with none yet, now start POST /api/demo in the background once, as
they show (failures stay quiet). The click waits for that same request,
done at once when it is (prepareDemoBrand, asked once per page, again
after a failure), and its button says "Setting up the demo…" meanwhile.

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

* fix(billing): show the first-month offer when its code can't be checked

Stripe unreachable, or not set up on a local server: the plan dialog still
shows the configured offer; checkout applies the code and says so by the
field if Stripe turns it down.

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

* perf(demo): build the demo's modules side by side after the core

The first module lays down what the others point at; the rest write their
own tables together, each after the module it names in `after`.

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

* feat(demo): tell Chat's preview story with Google AI Overviews

The Chat preview's running example (citations that dropped, why, and the
fix) now follows Google AI Overviews instead of Perplexity. Engine lists,
the logo map and the mockup's own matching rules are unchanged.

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

* feat(demo): show Chat preview's citation changes as small pills

Since you left's drop and win were big bold numbers with ▼/▲; they are now
small pills with a thin arrow on a soft red or green ground.

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

* feat(demo): show the demo brand with Growth, the whole product

While the demo brand is the brand on screen, the plan context reads
Growth whatever the workspace's plan (or none): Product Visibility and
the AI bot report open, every engine shows in the Positions panel and
column, and the Growth marks go. One rule, effectivePlanIdForBrand,
feeds the client's plan context and the server actions' position
reads. Billing keeps reading the organization's own plan (ownPlanId).
Writes and costs are unchanged: on the demo brand they still open the
plan dialog.

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

* fix(billing): show the first month's price once on the plan dialog's cards

With the first-month offer, the card's price already reads "$24.50 first
month, then $49/mo"; the same line under Buy now said it again. Only
"Full plan from day one" stays there, beside the free trial. The
upgrade dialog's test now answers the offer's code check itself, so it
no longer depends on the network to read "Choose Starter".

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

* perf(demo): build the demo faster and rebuild it over its old rows

A first build no longer clears 70 empty tables, and the core writes each
step's independent tables side by side through a shared queue of four
statements (write.js: insertChunks, demoWriter). Its rollups move to a
refresh step that runs alongside the other modules, Insights, Citations and
Mentions together, the month's answer terms in one call (refreshMentionsDaily
takes an optional termDays). The core alone went from about 17 s to 7 s on
the dev database.

A rebuild (new DEMO_VERSION, or data older than three days) no longer
deletes the demo first: an `inPlace` module writes over its rows by key
(ids are deterministic) and deletes only the rows it didn't write again,
then rebuilds the rollups over the old and new days, each refresh call
rewriting its days in one statement. Someone opening the demo meanwhile sees
last week's data, not empty pages. Modules not marked `inPlace` still have
their tables cleared, now just before they are built.

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

* feat(billing): start a plan from Billing the way the plan dialog does

With no plan active, Settings › Billing's cards now offer the plan
dialog's ways to start: Buy now, at 50% off the first month on a monthly
plan while the offer runs, and, for a workspace that never had a plan,
the 14-day free trial. A plan that ended gets Buy now alone. The cards'
price and buttons, the first-month code check and Checkout are one set
of parts (billing/plan-start.tsx) that the dialog and Billing share.

A workspace that never started a plan reads "No plan yet" under Current
Plan, with "Choose how to start" over the cards, instead of
"Starter incomplete".

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

* fix(demo): write over what a new brand's triggers made

A brand just created isn't empty: its insert trigger starts Getting started,
so skipping every clear on a first build made the Action Center's insert hit
getting_started_pkey. An in-place module now always writes over by key (the
first build only skips reading back and pruning); a module that isn't
rebuilt in place clears its own tables just before it is built, on a first
build too, alongside the other modules rather than all up front.

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

* perf(demo): clear the other modules' tables alongside the core on a first build

Nobody looks at a demo being built for the first time, so every module not
rebuilt in place starts clearing what the new brand's triggers made at once,
while the core writes, instead of each in turn later, when its deletes queue
behind the rollups. A rebuild still clears each module just before it is
built, so its old rows stay on show as long as they can.

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

* feat(demo): build a new workspace's demo brand while onboarding goes on

As soon as onboarding has the organization (step 2 on a new account, at
once on a resume), an admin of a workspace without a plan and without a
demo brand starts its setup in the background (wantsDemoAhead +
usePreloadDemo): the first build takes a few seconds, the topics, prompts
and competitors steps longer, so "Explore the demo" on the plan step opens
at once. The plan step's own preload stays. The resume step now reads the
person's own brand only (is_demo false): the demo brand may exist by then.

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

* feat(demo): show the demo being prepared, step by step, while it builds

"Explore the demo" and "See the demo" open the demo at once when its setup
is done. While it is still being prepared, a setup screen (DemoSetupDialog)
shows what the server writes, in its order, as the Content Agent's card
shows a run: the steps done with a check, the one under way with the
agent's sweep and dots and its count going up (720 sample answers from 6
platforms, 2,694 sources, 18 pages audited, 9 actions, 10 opportunities, 2
reports: the generator's own counts). It starts from where a setup asked
ahead already is (demoPreparation), holds on the last step until the
answer comes, then runs through the rest quickly and opens the Action
Center. A failure says so in the screen, with Try again and Close; closing
it lets the setup finish in the background. Counts show whole at once with
reduced motion; the sweep and dots stop. StepSweep moves to components/ui,
shared with the editor's agent card.

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

* fix(demo): drop the Chat preview's own copy of the app menu

The Chat preview sits beside the app's left menu; the mockup's icon rail
(and the governance and signature screens' app menus) showed the same menu
twice, so the demo copies hide them.

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

* feat(demo): replace a table's rows whose ids the database gives

A table with an identity id and no other unique columns (ai_bot_events)
can't be written over by key. write(table, rows, { generated: true })
inserts the new rows and, on a rebuild, deletes the brand's rows that were
there before right after: never empty, both there for a moment.

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

* perf(demo): rebuild the Action Center, Content, suggestions and reports in place

The four workflow modules write through the build's writer (ctx.write):
each step's independent tables side by side, and on a rebuild over their
old rows by key, deleting only what isn't written again, so their pages
never empty while the demo is rebuilt. Keys where a row has no id:
getting_started (brand_id, also what a new brand's trigger made),
getting_started_steps, action_signals, the cluster members, searches and
scopes, and the plan marks; the action and cluster children are found
through their parent (scopes).

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

* test(demo): pin the build order with gates instead of timers

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

* perf(demo): rebuild AI traffic, Site Audit and the catalog in place

The three site modules write through the build's writer (ctx.write): their
independent tables side by side (traffic's thirteen at once, a visit before
its pageviews), and on a rebuild over their old rows by key, deleting only
what isn't written again, so their pages never empty while the demo is
rebuilt. Google Analytics and Search Console rows are keyed by their day and
what they count (their unique columns, as their syncs write them), the
audits' signals by audit and signal (found through their audit), the
single-row settings by brand. ai_bot_events has an identity id and no other
key: its rows are replaced, the old ones deleted right after the new are in.
site-common's insertRows goes.

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

* perf(demo): refresh the demo's mention rollups beside its answer terms

refreshMentionsDaily takes `together`: the rollups (refresh_mentions_daily)
and the answer terms (refresh_mention_terms) take their own locks and write
their own tables, so the demo runs them side by side instead of one after
the other, a second off the longest step of its build. The nightly run
keeps them in turn.

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

* feat(demo): move the Chat preview's inbox into the chat menu and add archived chats

Home keeps the composer in view: Inbox gets its own screen in the chat
menu, the skill cards are shorter with the description on hover, Home to
Files fold under a Menu header, and All chats has Active/Archived tabs.

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

* feat(demo): show Brewline Coffee in the Chat preview, raise its Home and add skill creation

The preview now tracks the demo brand: its pages, rivals, prompts and
sources come from the demo data, and Ansvisor stays only where it names
the product. Home starts higher with more room above the composer, both
cards say when their change happened, One win lists its citations, and
Create a skill opens the chat, upload and URL import flows from CHAT-13.

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

* fix(web): name the profiles→organizations relationship so the plan check reads again

The read-only check before every write embedded organizations from
profiles without naming the relationship. A second foreign key between the
two tables made the embed ambiguous, so the check failed and every write
returned 500 for every workspace, active plans included. Same fix for
getMyProfile.

(cherry picked from commit 62eb7b7658388c1614b38dea93fbe316b8910311)

* test(web): read the demo brand's plan check with the named relationship

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

* feat(billing): start a plan from one choice that fits on one screen

The plan dialog, Settings › Billing with no plan active and onboarding's
plan step now share the same start flow (components/billing/plan-start):

- One choice above the cards: 14-day trial / Monthly, 50% off the first
  month / Yearly, Save 20%. Each card then has one button, one "Due
  today" line (the trial says when it ends and what follows, "Free until
  Nov 11, then $49/month") and "Secure checkout with Stripe · Cancel any
  time" beside the button. The promo code field sits behind "Have a
  code?".
- The first-month offer shows from the first frame, from the config: no
  $49 → $24.50 jump once Stripe answers. A code Stripe can't redeem takes
  it away; one that couldn't be checked keeps it as configured.
- Onboarding's plan step drops its own copy (PLAN_STEP_COPY) for the
  shared cards and Billing's features, with the discounted price large,
  and says what is ready to track for the brand, from its real prompt,
  topic and competitor counts.
- Everything fits 1024×768 and up without scrolling: the plans' features
  open behind "Show plan details" inside the cards, which keep their
  height; on Billing the plan choice comes first while no plan is active.
- A Checkout that doesn't open (Stripe down or not set up, no answer in
  30 s, a refusal) says why by the plan's button instead of spinning.

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

* feat(demo): name the workspace's own brand in the demo band and plan dialog

On the demo brand the band says "Start tracking Acme Coffee with a
14-day free trial…" and, with a plan active, "Switch to Acme Coffee"; the
plan dialog's demo and new-brand pitches name the brand too. Before the
workspace has a brand of its own, the general wording stays.

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

* fix(demo): wait for the brand on screen before showing a page or a band

In a new browser the brand store starts empty until BrandLoader puts the
layout's brands in it, just after the first render. Until then BrandGuard
read the empty list as "No brands yet", the read-only band showed the
workspace's own state before the demo brand's band, and the brand switcher
offered Add Brand. The store now says when it holds the server's list
(loaded, never persisted); pages wait on the skeleton, the read-only band
and Add Brand wait for it, and leaving the dashboard clears it.

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

* fix(demo): keep the nightly prompt demand read off demo brands and cover main's new tables

sweepPromptDemand chose brands by their organization's plan only, so an
active workspace's demo brand would have had its sample prompts read and
DataForSEO's paid tasks set for them. It now leaves demo brands out, as
the other sweeps do. The demo coverage list names the two brand tables
main added: prompt_table_views (skipped: the demo starts on the default
columns) and prompt_demand (pending a demo follow-up).

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

* fix(demo): refuse main's new write routes on a demo brand and keep column layouts open

Main added write routes that name a brand: Action Center's audits and
products, WordPress and Framer connections, and their publish-status
checks. Each now answers 402 demo_brand on a demo brand, as the Webflow
ones do. The Tracked Prompts column layouts (prompt_table_views, 00363)
stay writable on a demo brand: they change no sample data and cost
nothing, and the web keeps them open while read-only too.

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

* feat(demo): follow the app's dark theme in the Chat preview

The preview reads the app's .dark class from its parent page and follows it live; standalone it follows the system setting. Its colours moved to variables with a dark palette close to the app's.

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

* fix(demo): check a topic write once, with its brand, now that the check comes first

Merging main left createTopics, createTopic and updateTopic with two
plan checks each: main's, moved ahead of the name check, and the demo's,
which hands the brand over. Each now checks once, first, with its brand
where it has one.

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

* feat(demo): answer the Chat preview's shortcuts from anywhere on its page

⌘ or Ctrl with ⇧O (new chat), K (search), J (side panel) or \ (menu)
reach the preview while the app around it has the focus: the page hands
them to the frame, which answers them as it does inside. The frame takes
the focus when it opens, and on a Mac the preview shows ⌘ for Ctrl.

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

* fix(demo): keep the competitor timeline off demo brands and cover main's new tables

sweepCompetitorTimeline (learning C3, on main) chose brands by their
organization's plan only, so a demo brand's sample answers would have had
their cited pages read every night. It now leaves demo brands out, as the
other sweeps do. The demo coverage list names the brand tables main added:
cited_page_features, competitor_page_events and competitor_timeline_scans
(pending a demo follow-up) and chat_conversations (with Chat).

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

* feat(chat): read a call's demo flag from brands.is_demo

Chat's precedence (#1776) left readBrandIsDemo false until the demo chain
added brands.is_demo, with a type check that stops compiling once the
column exists. It now reads the column, as the server's demo guard does,
so a tool that changes or spends on the demo brand is refused with
demo_brand; a brand that isn't found isn't one, and a failed read throws.

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

* fix(demo): guard the brand site type detection on the demo brand

POST /brands/:id/detect-site-type (#1761, on main) reads the brand's home
page and may ask AI for its kind. The demo guard's coverage test fails on a
write route in neither list, so it is now guarded by the brand in its path.

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

* fix(demo): name main's new Chat tables in the demo write guard's lists

chat_user_prefs (00400) and chat_auto_choices (00401) are a person's own
rows, not a brand's: the write guard's coverage test fails on a writable
table in no list, so both are named as no brand's rows.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 29, 2026
…rand, part 6) (#1739)

* feat(web): let a workspace whose plan ended browse read-only, with one "Choose a plan" dialog

On the cloud, an ended trial, a cancel during the trial and a cancel
after the first payment can now sign in and look around. They used to
see a full-screen "subscription expired" notice that only signed out.
Onboarding is unchanged: an admin who never started a trial still goes
to the plan step.

- The dashboard layout lets these workspaces in, read-only. A thin
  banner says so, with "See plans".
- UpgradeDialogProvider and useUpgradeGate ({ guard, isLocked,
  openUpgrade }) open one "Choose a plan to keep going" dialog, with the
  action that was clicked as a label.
  - Admins go to Billing; members are told to ask their admin.
  - A failed payment (past_due, unpaid) says so and opens Stripe's
    portal.
  - A 402 subscription_inactive from the API opens the dialog
    (use-failure-toast, api-failure's subscription class, and the
    Webflow, catalog, publish and Send to CMS clients).
- Automatic calls (Library's Webflow status, the editor's link, source,
  claim and page reads, Improve's read) aren't sent while locked.
- Billing: an ended subscription starts a new Checkout ("Choose
  {plan}", monthly or annual). The checkout route takes admins only,
  refuses a second live subscription (409), and validates its body.
  Billing reads again after a change.
- MCP: list_ and get_ tools stay open; every other tool, and REST
  writes, answer subscription_inactive. Chat and new conversations
  answer 402, and runSiteAuditFor, generateBriefFor and
  createImproveActionFor check too. A chat message refused by a 402
  goes back to the input.

Self-hosted is unchanged.

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

* feat(billing): show the plans in the read-only dialog, with Monthly or Annual and a promo code

The "Choose a plan to keep going" dialog for an ended plan now carries
the plans, as the approved design has them.
- Starter and Growth (Popular) have "Choose {plan}"; Custom has "Starting
  at $499/mo" and "Contact us". Each lists the Billing cards' features,
  through a shared usePlanFeatures.
- Monthly or Annual ("Save 20%"): an annual price shows its struck 12×
  price and what it is a month.
- A promo code is checked by the API (POST /api/stripe/promo-code, admins
  only), through the same Stripe lookup #1300 uses (findPromotionCode,
  takesPromoCode: monthly plans only).
  - A valid code shows its chip, the first month's price on each card and
    in the button ("Choose Growth · $124.50 today").
  - A bad one says so; on Annual a note offers Switch to Monthly.
- Choose opens Stripe Checkout for that plan and period, with the code
  applied as a discount. The checkout route checks the code again and
  refuses it on an annual plan.
- Members see "Ask your admin to choose a plan", with no code field.
- The footer reads "Prices in USD." with a link to the pricing page.
- A failed payment keeps its "Update payment method" dialog.

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

* fix(billing): word the dialog's custom AI usage "from 10x", as Billing does after #1598

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

* feat(web): open the plan dialog from the Prompts area's actions while the plan has ended

Read-only, part C1. On an ended plan, every action in Prompts, Prompt
Suggestions, Topics, Query Fan-out, Brand Visibility and Competitors
opens the "Choose a plan" dialog with the action named, and runs
nothing. On an active plan they run as before. Buttons aren't disabled.
- Tracked Prompts: add, import, edit, analyze and refresh volumes, the
  bulk bar, work status and the row menu.
- Prompt and topic suggestions: generate, add, accept, dismiss.
- Manage prompts and topics: add, generate, locations, analyze, edit,
  delete.
- Query Fan-out's Track; Brand Visibility's Run All, Test Single Prompt,
  Opportunities' Track and Send, and pinning a competitor.
- Competitors: suggest (its dialog calls AI on opening), add, delete.
- The Positions panel: Improve's Generate and Regenerate, Send Actions,
  and Create or Optimize content.
- The labels live in readOnly.actions.* ("Adding prompts needs a plan").
- volumes.ts tells the API's 402 subscription_inactive from a feature
  the plan lacks, so a refused analysis opens the dialog instead of "not
  part of your current plan".
- While locked, Tracked Prompts doesn't warn that volume data is
  unavailable, and Query Fan-out doesn't send its intent classification.

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

* feat(web): open the plan dialog from the content area's actions, and keep the editor read-only, while the plan has ended

Read-only, part C2. On an ended plan, every action that writes or costs
in Content Opportunities, the opportunity panel, Content Plan, Library,
New content and the Content Editor opens the "Choose a plan" dialog,
naming the action, and runs nothing.
- Opportunities: New, the bulk bar (send, done, dismiss and delete open
  the dialog instead of their confirm), the row menu, the webhook
  settings' Test and Save, and the panel's sends, brief, Reviewed,
  Restore and Dismiss.
- Plan: New content, Start, Assign, Priority, Hide and Show. A ?start=
  link starts nothing while locked.
- Library: New content (and ?new=1), status changes, archive, delete,
  and single and bulk Send to CMS.
- The editor:
  - Run Agent, Rewrite, Fix rules, hand-off;
  - accepting or rejecting suggestions;
  - Mark ready, Ready back to review, Mark published, Send to CMS,
    History Restore;
  - page and site type, author and reviewer;
  - Quality's confirms, sources and images, and Add line or Remove;
  - renaming, dropping files, the toolbar;
  - the Brief's run, rewrite and edit; the Sources and Rules changes;
    Your input.
- The editor itself is read-only while locked (editable: false, the
  HTML view readOnly), and autosave is off (useDraftAutosave { off }):
  nothing is saved, and leaving doesn't warn.
- Reading, filters, exports, Copy HTML and Stop stay open.

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

* feat(web): open the plan dialog from the remaining areas' actions, and from every way to add a brand, while the plan has ended

Site Audit, Action Center, Mentions, Citations, AI Referral Traffic,
Shopping, Reports, Chat, brand settings and Settings now guard their
actions with useUpgradeGate, as Prompts (#1606) and Content (#1609) do.
Every way to add a brand (sidebar, /dashboard/brands, brand guard,
/dashboard/brands/new) opens the dialog. Disconnects, key revokes and
API key creation stay open.

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

* feat(web): refuse direct database writes from a workspace whose plan has ended, on the server

Server actions and Next routes that write to Supabase without going
through the API now call assertWritable() first: on the cloud, an
organization without an active plan gets SubscriptionInactiveError
(routes: 402 subscription_inactive), so the read-only rule holds even if
a guarded button is bypassed. Setup's writes stay open to an
organization that never subscribed, as the API's onboarding routes do.
Profile, invitations accepted, revokes, removals, API keys and billing
stay open. A static test pins every writing action to the check or to
the open list.

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

* fix(web): keep removing members, revoking invitations and disconnecting stores open while read-only, and stop the site trust card's automatic re-read

From the pre-push review: ending an access stays open, as disconnects
do; a partial site trust result isn't re-read while the plan has ended,
since that read scrapes. Adds tests for the audit page's Run audit and
the integrations' property mapping, resets shared mocks between tests,
closes the mobile menu before the dialog, and words the KPI preview for
a read-only workspace.

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

* fix(web): open the plan dialog from Add Brand at the plan's brand limit too, while read-only

At the limit, /dashboard/brands' Add Brand links to Billing; a read-only
workspace now gets the dialog there as on every other way to add a brand.

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

* feat(web): let a read-only workspace delete a brand

Ansvisor's decision (2026-10-27): deleting a brand only removes what the
person gave us, so it stays open while the plan has ended. The API opens
DELETE /brands/:id in #1611.

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

* fix(web): keep setup's Shopping mode working for a new workspace, read the plan in one query, and pin the write check's place

From the pre-push review: markBrandAsEcommerce no longer goes through
the strictly guarded setBrandShoppingMode (a shared applyShoppingMode
does the writes), so a setup detected as e-commerce turns Shopping on
again. assertWritable reads the profile and its organization in one
query. The coverage test now requires the check as each writer's first
await, sees writers kept in variables and signed upload URLs, refuses a
setup-open function that reaches a strictly guarded one, and keeps brand
deletion open (Ansvisor, 2026-10-27). main's saveDraftShoppingPath is
guarded; catalog-client's every-code test leaves out 'subscription',
which opens the plan dialog instead of a message.

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

* feat(web): show "No active plan" instead of a used-up quota while the plan has ended, and keep the buttons opening the plan dialog

With #1611, an ended workspace's quota reads come back as `noPlan` with
0 limits. isNoPlan(quota, isLocked) keeps those from reading as used up:
Site Audit, Prompts, the content usage card, Improve and the opportunity
panel say "No active plan" instead of a red 0/0 or "limit reached", and
their buttons stay clickable so the guard opens the dialog. The AI bot
report shows the workspace's own data instead of the Starter upsell.
Setup's suggestions name the onboarding daily limit (429) on their own.

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

* fix(web): keep a saved content suggestion reachable, the Starter bot upsell and one lock rule while the plan has ended

From the pre-push review: the Prompts row menu still looks up an open
content suggestion with no plan; an ended Starter workspace keeps the
bot report's upsell (its old plan has no report), read from the plan
the web already knows; auditBlock, bulkSuggestBlock and the bot states
take isLocked as the pages do; the audit settings and the content usage
tooltip don't speak of a plan that renews; setup's prompt step keeps its
own "add your own" line. Improve's unreachable no-plan branch is gone.
Tests for the onboarding limit and the quota meter.

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

* fix(web): leave the plan dialog's store error out of the every-code message test

main's catalog-client test (#1583) asks for words for every StoreError
code; 'subscription' opens the upgrade dialog instead of saying one, so
the test leaves it out, as #1613 does.

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

* fix(web): open the plan dialog from Merchant Center, category pages and main's other new actions while the plan has ended

main's new writes, with C3's guard pattern and labels:
- Merchant Center (#1583): picking and adding an account open the plan
  dialog ("Connecting a store needs a plan"); the server's 'subscription'
  refusal on Add opens it too, instead of looking up a missing
  settings.catalog.stores.errors.subscription message.
- Category pages (#1587): Change, Save, No page and Use the match are
  guarded; the catalog client reads the server's 402
  subscription_inactive as 'subscription', which opens the dialog
  instead of the generic failure.
- Brief › Shopping path (#1591): Pick from the catalog, Pick again, Add
  product, Lock, Swap and Remove are guarded.
- Action Center Check now (AC-010, #1565) is guarded.

New labels: changeCategoryPages, changeShoppingPath, checkTasks.
Insert › Products (#1607) already goes through the toolbar's guard and
the read-only editor shows no insert menu; a test now says so. The
Shopping rules (#1610) change through the rules hook, already guarded.

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

* fix(web): check the plan inside Merchant Center's Add, not by wrapping it during render

React's refs rule refuses passing add, which reads addingRef, to guard
while rendering. add now opens the plan dialog itself on a read-only
workspace.

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

* test(web): keep brand setup's limits in the new brand page test's mock

main's new brand page now reads BRAND_SETUP_LIMITS from ai-brand-setup
(#1661), which the test's mock left out.

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

* feat(demo): open the plan dialog with the demo's offer on a demo brand

The selected brand being the organization's demo brand (brands.is_demo,
sample data) locks the dashboard as a read-only workspace is locked, with
its own reason: guarded actions open the plan dialog with the demo's offer.
A workspace that never subscribed is offered the free trial, then 50% off
("Start free trial"); one whose plan ended gets 50% off its first month
("Choose {plan}"). The label names what was clicked as something that
works on your own brand, and an admin finds SAVE50 applied (quietly left
empty when Stripe refuses it). With a plan active, the dialog points back
to the workspace's own brand; a payment being retried still asks for the
payment method. The server's 402 demo_brand opens the same dialog.

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

* feat(demo): show a band across the dashboard while the demo brand is open

Where the read-only band sits, and instead of it: "You're exploring
{brand}, a demo brand with sample data", with a small button to the plan
dialog's offer ("Try it on your brand · 50% off" for a workspace that never
subscribed, "Use it for your brand · 50% off" once its plan ended), or back
to the own brand while a plan is active. The band asks the API once per page
load to bring the demo brand up to date (POST /api/demo) and reads the
pages again when its sample data was written anew, so the demo follows the
product by itself.

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

* feat(demo): add a demo brand per organization, kept out of the plan's counts

Migration 00380 adds brands.is_demo, demo_version, demo_built_at and
demo_hidden_at, one demo brand per organization (partial unique index) and
policies that let members read it but never insert, change or delete one.
The plan's prompt-location quota, the usage cards' account totals and the
web's brand limit leave the demo brand out; the health report's fan-out
share leaves out its answers. The brand delete route refuses it: the demo
brand is hidden, not deleted.

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

* feat(demo): skip demo brands in every nightly sweep and job

The daily tracking list, the job claim and recovery (activeBrandFilter /
isBrandActive), the signal catch-up, the pulse, the task writer, executor
and checks, action validation and Improve outcomes, the Insights sweep,
brand facts, Search Console and Analytics syncs, page opportunities, the
traffic digest, auto-audits, catalog feeds, Webflow status and volume
analysis all leave demo brands out: their data is sample data and nothing
may track, write or spend for it.

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

* feat(demo): mark the demo brand in the brand switcher, with Show or Hide

The demo brand reads "Demo · sample data" under its name, in place of a
domain, and a brand of a workspace that never had a plan reads "Not tracked
yet". For an admin or a manager, the menu ends with "Hide the demo brand"
(PATCH /api/demo), or "Show the demo brand" once it is hidden, which brings
it back and opens it: the demo brand is hidden after a purchase, never
deleted. A hidden demo brand stays out of the dashboard's brand list and
the brands page, and the demo brand never counts toward the plan's brands,
there or when a brand is added.

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

* feat(demo): show Chat as coming next week on the demo brand, with its v2 preview

On the demo brand, the menu's Chat item carries "Soon (next week)" in its
badge, ahead of "Set up" (the badge rule now lives in dashboardNavBadge, for
the sidebar and the mobile menu alike), and /dashboard/agent shows the Chat
v2 mockups themselves in a full-height frame, opening on Home, under a thin
line that Chat arrives next week. The five mockup files are copied as they
are into public/demo/chat (about 720 KB), outside Prettier's scope. On any
other brand, Chat is unchanged.

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

* feat(demo): show the demo brand's integrations connected, and those to come as coming soon

On the demo brand, Settings › Integrations shows the real cards with the
demo's states, kept in one list (lib/demo/integrations.ts): Google Search
Console, Google Analytics and Webflow as connected, the way they look with
a live connection, marked "Sample data", the demo brand mapped to a sample
property and Webflow sending to a sample collection, with nothing read from
the API or Composio and no set-up lines. Disconnect and Replace token open
the plan dialog. Merchant Center shows Coming soon on its own card, and
Shopify, WordPress, Framer and Wix, which have no card yet, a Coming soon
row in their group. When one goes live, its line in the list turns
connected.

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

* feat(demo): build the Brewline Coffee demo brand's core data

lib/demo/ builds an organization's demo brand in its own brands: Brewline
Coffee (brewline.example) with fictional `.example` competitors and
publishers, 12 prompts in 3 topics, 6 engines and a run every 3 days over
a month (720 short answers) with citations, product cards, searches and
volumes. Answers are raw engine responses run through tracking's own
parseScraperResponse, parseResponse and the result and shopping card rows
(now pure resultRow and shoppingCardRows in cloro-result-handler.js), and
the rollups are rebuilt by the nightly run's own functions.

ensureDemoBrand creates it, rebuilds it in place (same ids) when
DEMO_VERSION moves on or its data is three days old, and leaves it alone
otherwise; concurrent visits share one build (one-per-org index, a
compare-and-set claim, a lease). Modules are { name, tables, build }, and
a coverage test fails on any brand_id table the demo neither builds nor
lists as skipped or pending.

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

* feat(demo): open and hide the demo brand through /api/demo

POST /api/demo creates or rebuilds the organization's demo brand for any
member and returns { brandId, version, rebuilt }; PATCH /api/demo
{ hidden } hides or shows it for admins and managers ({ brandId, hidden },
404 no_demo without one). Both stay open once a plan has ended.

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

* feat(demo): let a workspace with no plan explore the demo brand

Onboarding's plan step gets a second way in under the plan cards: "Not
ready to add a card? Explore a demo brand", whose button makes the demo
brand (POST /api/demo), selects it and opens the Action Center, the
person's own brand kept as set up. An admin who never subscribed used to be
sent back to that step from the dashboard; with a demo brand in the
organization, they now browse read-only instead (evaluateSubscriptionAccess
takes hasDemoBrand). The read-only band of an ended or canceled plan gets
"See the demo", for an admin or a manager, or anyone once the demo brand is
listed: the same flow, which shows a hidden demo brand again. The plan
step's preview reads the own brand, never the demo brand.

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

* feat(demo): offer the free trial on the own brand of a workspace that never had a plan

A workspace that never subscribed now gets the trial offer on its own
brand too, not only on the demo brand: the read-only band says the brand
isn't tracked yet ("Start your 14-day free trial, then get 50% off your
first month") with Start free trial for admins, and the dialog's title is
"Start your 14-day free trial: then 50% off your first month", with SAVE50
applied and Start free trial on each plan. Members are asked to have an
admin start it. ChoosePlanDialog takes the offer as a `pitch` (from the
demo brand, or the own brand).

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

* feat(demo): show what is paid today on the demo's first-month offer

With SAVE50 applied, the demo's 50%-off-first-month offer words its
buttons as the plan dialog does everywhere else: "Choose Starter · $24.50
today"; "Choose {plan}" alone when the code didn't apply.

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

* feat(demo): say the demo brand is hidden, not deleted, in its Danger tab

On the demo brand, brand settings' Danger tab says "The demo brand can't
be deleted; hide it from the brand menu instead." in place of the name to
confirm, and Delete brand stays disabled. The server refuses the delete
too.

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

* feat(demo): cancel a demo brand's jobs as demo_brand, not as an ended plan

A job claimed for a demo brand ("Run now", the internal trigger, a retry
or the recovery) was cancelled as subscription_inactive, as if the plan had
ended. It now says demo_brand: brandStopReasons tells why no work may start
for a brand, and activeBrandFilter is built on it. Nothing is tracked,
generated or counted before the cancel: the on-demand cap counts the
brand's own jobs, and AI usage is recorded by the workers, which never run.

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

* feat(demo): refuse the web app's own writes on the demo brand

assertWritable takes the brand an action writes for and refuses the demo
brand (DemoBrandError, digest demo_brand), whatever the plan, reading the
brand beside the plan through the person's session. Every gated server
action that takes a brand id hands it over (52 of them, the brand's own id
in updateBrand); actions that name no brand, such as the profile or the
organization, read nothing more. A route's refusal answers 402 demo_brand,
and the browser reads the digest as it reads subscription_inactive: an
uncaught refusal opens the plan dialog. The read-only coverage test now
also fails a gated action that takes a brand id without handing it to the
check.

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

* feat(demo): refuse writes and costs on the demo brand with 402 demo_brand

The demo brand's data is sample data, so nothing asked of it may change it
or start a cost. A middleware after decodeToken (before the plan's check,
so the answer is the same with a plan or without) refuses every write that
names a demo brand: in the path, the body, the query, or through the row it
acts on (a draft, an opportunity, a prompt, a task...). Every write route
under /api is named, guarded or open with its reason (onboarding, the
organization's own integrations, stopping work, the demo routes, brand
delete's own 409); a test reads the route files and fails on one that
isn't. Reads and exports stay open; brand facts are read only as kept on a
demo brand, so its site is never fetched.

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

* feat(demo): hide the demo brand once a plan is bought

When a subscription starts (Stripe's checkout.session.completed, trial
included, and the return from Checkout, whichever comes first), the
organization's demo brand gets demo_hidden_at, through the service role:
hidden, never deleted. Only a demo brand still shown is touched, and
subscription updates, renewals and payments never touch it, so one an admin
shows again stays shown. A first payment still open hides nothing, and a
failed write never fails the purchase. Hidden before the dashboard opens,
the demo brand leaves the brand list, so the person lands on their own
brand.

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

* feat(demo): refuse people's writes to a demo brand's rows in the database

Members can write a brand's rows straight through Supabase, under RLS,
past the API's 402. Migration 00381 adds refuse_demo_brand_writes(), a
BEFORE INSERT/UPDATE/DELETE row trigger that raises 42501 'demo_brand' for
a demo brand's row unless the role bypasses RLS (the service role the
server and the demo generator write with). It is attached to the 24 tables
people can write that carry a brand_id, and, through their parent row, to
the 13 that reach their brand another way (prompts through prompt_sets,
prompt notes and target URLs through prompts, a draft's inputs and sources
through content_drafts, tasks and events through actions...). A test reads
the policies and triggers from the migrations and fails on a table people
can write that belongs to a brand and lacks it.

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

* feat(demo): refuse the MCP's brief, audit and Improve endpoints on a demo brand

The internal endpoints the MCP calls (a content brief, a Site Audit, an
Improve action) trust CRON_SECRET and never meet the API's middleware.
Each now answers a demo brand with 402 demo_brand before it calls the
model, starts an audit or writes an action; the MCP relays the message.

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

* feat(demo): clear demo brands nobody opened for two weeks, nightly

Every organization gets a demo brand, so its sample rows would pile up
for workspaces that left. The daily run now clears the data of demo brands
built over 14 days ago (a visit rebuilds every few days, so these weren't
opened since), 200 a night at most: through clearDemoData, the path a
rebuild takes, so rows go in the modules' reverse order. The brand row
stays with no version and no build time, and the next visit builds it
again in place, with the same ids. The clear holds the brand as a build
does, so a visit at the same moment waits for it.

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

* test(demo): look rows up by a set in the demo guard's fake database

The cache test reads 10,000 brands; filtering them with includes() took
seconds and timed out under a full run.

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

* feat(demo): build the demo brand's Action Center, Content, suggestions and reports

Four demo modules over core's answers: signals and a month of actions
(tasks, trail, measured outcomes, a task waiting for review, ready-made
KPIs, Getting started with its page steps opened), prompt clusters,
content opportunities, Editor drafts and Plan marks, prompt, topic and
Improve suggestions, and two saved reports. Numbers are counted from the
demo's own answers; shapes come from the engine's own functions. detect.js
exports single and promptTarget so the demo writes signals in their shape.

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

* feat(demo): register the workflow modules and rebuild demos at version 2

DEMO_MODULES runs core, suggestions, actionCenter, content and reports;
DEMO_VERSION 2 rebuilds existing demo brands on their next visit. The
coverage lists move the workflow tables to built, skip the engine's
internal queues and logs and the org-level author default, and leave the
draft shopping check to demo-site with the catalog.

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

* refactor(audit): read a page already fetched into the audit context with auditContextOf

buildAuditContext fetches the page, robots.txt and llms.txt, then hands
them to auditContextOf, which parses the HTML once and extracts its text
as before. A page that isn't fetched (the demo brand's) is read exactly as
a fetched one.

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

* feat(demo): build the demo brand's AI Referral Traffic over a quarter

Brewline's website (site-world.js) and its traffic: 90 days of Google
Analytics as GA4 reports mapped by ga-sync.js (AI sessions by source and
page, ChatGPT Shopping's feed visits, pages, channels, items), Search
Console's query and page rows mapped by gsc-sync.js, four weeks of snippet
visits (a removed guide's 404s for Broken AI links) and journeys made by
traffic-events.js's eventRow, a month of AI crawler counts with a
Cloudflare Worker connection whose secret hash matches no secret, and the
page opportunities detectPageOpportunities finds in them. The brand maps
the sample GA4 and Search Console properties and has conversions on.

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

* feat(demo): build the demo brand's Site Audit from the audit engine's own verdicts

Brewline's pages are rendered as HTML round by round and scored by
runSignals and scoreAudit: six key pages audited three times as fixes
land, every page in the latest auto-audit. The model-judged signals,
Wikidata's brand entity and the recommendations are written in the shapes
those steps store. The page inventory goes through selectPages and
parseHead, site trust through site-trust.js's checks (4/5: no editorial
policy), and the brand facts through factText and keptFacts.

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

* feat(demo): fill the demo brand's catalog from its product feed

A Google XML feed of 22 products read by the feed parser and kept as
catalogRecords and hashOf keep them, with stable demo ids: a removed
seasonal blend, an out-of-stock size, a sale, no images. The products the
demo's AI answers show as cards are the same page, title and price. Two
categories get their page by hand; the rest match their collection pages.

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

* feat(demo): classify the demo's fan-out searches ahead in the intent cache

The demo writes the intent of each search its answers ran into
fanout_query_intents, keyed as the route keys it (normalizeIntentQuery,
moved to intent-extraction.js), adding only what the shared cache lacks,
so Query Fan-out never needs a model for the demo.

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

* feat(demo): build traffic, Site Audit, the catalog and fan-out intents with the demo brand (version 3)

The demo-site modules join the core in DEMO_MODULES, and DEMO_VERSION is
3, so every demo brand is rebuilt with them on its next visit. Their
tables leave the coverage test's pending list; a CMS connection, sent
drafts, product images and Merchant Center item issues are skipped, with
why.

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

* test(demo): audit the demo's pages once more, not twice, to check its rows stay the same

One rebuild for another brand two days later checks both that only the
ids and dates change, with room past the default 5 s on a busy machine.

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

* feat(demo): read the demo brand over MCP, and write, run or spend nothing on it

The MCP tools run in the web app, so the API's demo_brand refusal didn't
reach them. Now, on Ansvisor Cloud, every tool that writes, runs or spends
answers the demo brand with the web app's DEMO_BRAND body. That happens
whatever the plan, and before the read-only check, in gateWriteTools.
- lib/mcp/demo-gate.ts names how each of the 14 tools finds the brand it
  acts on: a suggestion, opportunity, task, prompt, answer or draft read
  back to its brand.
- A test fails on a new such tool until it is added there.
- Reading stays open.

The costly calls also refuse it inside their data functions, beside
assertSubscriptionActive, so their REST routes (402 demo_brand) and the
in-product agent do too: a brief, a Site Audit, an Improve action.

list_brands marks the demo brand (is_demo) and leaves it out once the
organization hid it, and its description tells the agent what that means.

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

* feat(demo): give the demo brand its own logo

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

* fix(web): read a new sign-up's free plan as Starter's

A new sign-up's organization holds plan 'free' until it picks one. With the
demo brand it reaches the dashboard, where PLANS[planId].limits threw on the
Prompts page. toPlanId maps an unknown plan to Starter's.

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

* feat(demo): give the demo's made-up sites real-looking logos

.example is reserved, so no favicon service knows the demo's brand,
competitors or cited sites. Their logos ship in public/demo/logos; any
other .example site gets a letter mark, so no page asks Google for one.

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

* feat(billing): offer two ways to start a plan: buy now at 50% off the first month, or the free trial

Every plan choice now offers two ways to start, each with a card. Buy now
bills the full plan from day one, with the first-month offer on a monthly
plan ("$24.50 first month, then $49/month", a Limited offer mark); a year
up front is the plain "Choose {plan}". The 14-day free trial comes without
the offer, with limited AI usage ("Free for 14 days, then $49/month"), and
only for an organization that never had a subscription. Checkout takes the
way explicitly (mode: 'buy' | 'trial'): buying never starts a trial, the
trial takes no promotion code and is refused (409 trial_unavailable) to an
organization that had a subscription, and both collect a card. The offer
is one setting, FIRST_MONTH_OFFER in config/plans.ts, turned off with
NEXT_PUBLIC_FIRST_MONTH_OFFER=off; its code no longer redeemable falls back
to the plain price.

The plan dialog (demo, a brand not tracked yet, a plan that ended), the
demo band and the "not tracked yet" band ("Start a 14-day free trial, or
get 50% off your first month." with See plans) and onboarding's plan step
("Choose how to start", two buttons per plan, the demo card below) say it
this way; the "14 days free, then 50% off" wording is gone. Billing's
Checkout for a plan that ended buys now.

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

* feat(demo): start the demo brand's setup ahead, where the demo is offered

The demo brand's first setup takes a while, and "Explore the demo" waited
for all of it. Onboarding's plan step, for an organization with no demo
brand yet, and the read-only band's "See the demo", for an admin or a
manager with none yet, now start POST /api/demo in the background once, as
they show (failures stay quiet). The click waits for that same request,
done at once when it is (prepareDemoBrand, asked once per page, again
after a failure), and its button says "Setting up the demo…" meanwhile.

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

* fix(billing): show the first-month offer when its code can't be checked

Stripe unreachable, or not set up on a local server: the plan dialog still
shows the configured offer; checkout applies the code and says so by the
field if Stripe turns it down.

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

* perf(demo): build the demo's modules side by side after the core

The first module lays down what the others point at; the rest write their
own tables together, each after the module it names in `after`.

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

* feat(demo): tell Chat's preview story with Google AI Overviews

The Chat preview's running example (citations that dropped, why, and the
fix) now follows Google AI Overviews instead of Perplexity. Engine lists,
the logo map and the mockup's own matching rules are unchanged.

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

* feat(demo): show Chat preview's citation changes as small pills

Since you left's drop and win were big bold numbers with ▼/▲; they are now
small pills with a thin arrow on a soft red or green ground.

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

* feat(demo): show the demo brand with Growth, the whole product

While the demo brand is the brand on screen, the plan context reads
Growth whatever the workspace's plan (or none): Product Visibility and
the AI bot report open, every engine shows in the Positions panel and
column, and the Growth marks go. One rule, effectivePlanIdForBrand,
feeds the client's plan context and the server actions' position
reads. Billing keeps reading the organization's own plan (ownPlanId).
Writes and costs are unchanged: on the demo brand they still open the
plan dialog.

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

* fix(billing): show the first month's price once on the plan dialog's cards

With the first-month offer, the card's price already reads "$24.50 first
month, then $49/mo"; the same line under Buy now said it again. Only
"Full plan from day one" stays there, beside the free trial. The
upgrade dialog's test now answers the offer's code check itself, so it
no longer depends on the network to read "Choose Starter".

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

* perf(demo): build the demo faster and rebuild it over its old rows

A first build no longer clears 70 empty tables, and the core writes each
step's independent tables side by side through a shared queue of four
statements (write.js: insertChunks, demoWriter). Its rollups move to a
refresh step that runs alongside the other modules, Insights, Citations and
Mentions together, the month's answer terms in one call (refreshMentionsDaily
takes an optional termDays). The core alone went from about 17 s to 7 s on
the dev database.

A rebuild (new DEMO_VERSION, or data older than three days) no longer
deletes the demo first: an `inPlace` module writes over its rows by key
(ids are deterministic) and deletes only the rows it didn't write again,
then rebuilds the rollups over the old and new days, each refresh call
rewriting its days in one statement. Someone opening the demo meanwhile sees
last week's data, not empty pages. Modules not marked `inPlace` still have
their tables cleared, now just before they are built.

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

* feat(billing): start a plan from Billing the way the plan dialog does

With no plan active, Settings › Billing's cards now offer the plan
dialog's ways to start: Buy now, at 50% off the first month on a monthly
plan while the offer runs, and, for a workspace that never had a plan,
the 14-day free trial. A plan that ended gets Buy now alone. The cards'
price and buttons, the first-month code check and Checkout are one set
of parts (billing/plan-start.tsx) that the dialog and Billing share.

A workspace that never started a plan reads "No plan yet" under Current
Plan, with "Choose how to start" over the cards, instead of
"Starter incomplete".

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

* fix(demo): write over what a new brand's triggers made

A brand just created isn't empty: its insert trigger starts Getting started,
so skipping every clear on a first build made the Action Center's insert hit
getting_started_pkey. An in-place module now always writes over by key (the
first build only skips reading back and pruning); a module that isn't
rebuilt in place clears its own tables just before it is built, on a first
build too, alongside the other modules rather than all up front.

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

* perf(demo): clear the other modules' tables alongside the core on a first build

Nobody looks at a demo being built for the first time, so every module not
rebuilt in place starts clearing what the new brand's triggers made at once,
while the core writes, instead of each in turn later, when its deletes queue
behind the rollups. A rebuild still clears each module just before it is
built, so its old rows stay on show as long as they can.

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

* feat(demo): build a new workspace's demo brand while onboarding goes on

As soon as onboarding has the organization (step 2 on a new account, at
once on a resume), an admin of a workspace without a plan and without a
demo brand starts its setup in the background (wantsDemoAhead +
usePreloadDemo): the first build takes a few seconds, the topics, prompts
and competitors steps longer, so "Explore the demo" on the plan step opens
at once. The plan step's own preload stays. The resume step now reads the
person's own brand only (is_demo false): the demo brand may exist by then.

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

* feat(demo): show the demo being prepared, step by step, while it builds

"Explore the demo" and "See the demo" open the demo at once when its setup
is done. While it is still being prepared, a setup screen (DemoSetupDialog)
shows what the server writes, in its order, as the Content Agent's card
shows a run: the steps done with a check, the one under way with the
agent's sweep and dots and its count going up (720 sample answers from 6
platforms, 2,694 sources, 18 pages audited, 9 actions, 10 opportunities, 2
reports: the generator's own counts). It starts from where a setup asked
ahead already is (demoPreparation), holds on the last step until the
answer comes, then runs through the rest quickly and opens the Action
Center. A failure says so in the screen, with Try again and Close; closing
it lets the setup finish in the background. Counts show whole at once with
reduced motion; the sweep and dots stop. StepSweep moves to components/ui,
shared with the editor's agent card.

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

* fix(demo): drop the Chat preview's own copy of the app menu

The Chat preview sits beside the app's left menu; the mockup's icon rail
(and the governance and signature screens' app menus) showed the same menu
twice, so the demo copies hide them.

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

* feat(demo): replace a table's rows whose ids the database gives

A table with an identity id and no other unique columns (ai_bot_events)
can't be written over by key. write(table, rows, { generated: true })
inserts the new rows and, on a rebuild, deletes the brand's rows that were
there before right after: never empty, both there for a moment.

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

* perf(demo): rebuild the Action Center, Content, suggestions and reports in place

The four workflow modules write through the build's writer (ctx.write):
each step's independent tables side by side, and on a rebuild over their
old rows by key, deleting only what isn't written again, so their pages
never empty while the demo is rebuilt. Keys where a row has no id:
getting_started (brand_id, also what a new brand's trigger made),
getting_started_steps, action_signals, the cluster members, searches and
scopes, and the plan marks; the action and cluster children are found
through their parent (scopes).

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

* test(demo): pin the build order with gates instead of timers

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

* perf(demo): rebuild AI traffic, Site Audit and the catalog in place

The three site modules write through the build's writer (ctx.write): their
independent tables side by side (traffic's thirteen at once, a visit before
its pageviews), and on a rebuild over their old rows by key, deleting only
what isn't written again, so their pages never empty while the demo is
rebuilt. Google Analytics and Search Console rows are keyed by their day and
what they count (their unique columns, as their syncs write them), the
audits' signals by audit and signal (found through their audit), the
single-row settings by brand. ai_bot_events has an identity id and no other
key: its rows are replaced, the old ones deleted right after the new are in.
site-common's insertRows goes.

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

* perf(demo): refresh the demo's mention rollups beside its answer terms

refreshMentionsDaily takes `together`: the rollups (refresh_mentions_daily)
and the answer terms (refresh_mention_terms) take their own locks and write
their own tables, so the demo runs them side by side instead of one after
the other, a second off the longest step of its build. The nightly run
keeps them in turn.

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

* feat(demo): move the Chat preview's inbox into the chat menu and add archived chats

Home keeps the composer in view: Inbox gets its own screen in the chat
menu, the skill cards are shorter with the description on hover, Home to
Files fold under a Menu header, and All chats has Active/Archived tabs.

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

* feat(demo): show Brewline Coffee in the Chat preview, raise its Home and add skill creation

The preview now tracks the demo brand: its pages, rivals, prompts and
sources come from the demo data, and Ansvisor stays only where it names
the product. Home starts higher with more room above the composer, both
cards say when their change happened, One win lists its citations, and
Create a skill opens the chat, upload and URL import flows from CHAT-13.

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

* fix(web): name the profiles→organizations relationship so the plan check reads again

The read-only check before every write embedded organizations from
profiles without naming the relationship. A second foreign key between the
two tables made the embed ambiguous, so the check failed and every write
returned 500 for every workspace, active plans included. Same fix for
getMyProfile.

(cherry picked from commit 62eb7b7658388c1614b38dea93fbe316b8910311)

* test(web): read the demo brand's plan check with the named relationship

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

* feat(billing): start a plan from one choice that fits on one screen

The plan dialog, Settings › Billing with no plan active and onboarding's
plan step now share the same start flow (components/billing/plan-start):

- One choice above the cards: 14-day trial / Monthly, 50% off the first
  month / Yearly, Save 20%. Each card then has one button, one "Due
  today" line (the trial says when it ends and what follows, "Free until
  Nov 11, then $49/month") and "Secure checkout with Stripe · Cancel any
  time" beside the button. The promo code field sits behind "Have a
  code?".
- The first-month offer shows from the first frame, from the config: no
  $49 → $24.50 jump once Stripe answers. A code Stripe can't redeem takes
  it away; one that couldn't be checked keeps it as configured.
- Onboarding's plan step drops its own copy (PLAN_STEP_COPY) for the
  shared cards and Billing's features, with the discounted price large,
  and says what is ready to track for the brand, from its real prompt,
  topic and competitor counts.
- Everything fits 1024×768 and up without scrolling: the plans' features
  open behind "Show plan details" inside the cards, which keep their
  height; on Billing the plan choice comes first while no plan is active.
- A Checkout that doesn't open (Stripe down or not set up, no answer in
  30 s, a refusal) says why by the plan's button instead of spinning.

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

* feat(demo): name the workspace's own brand in the demo band and plan dialog

On the demo brand the band says "Start tracking Acme Coffee with a
14-day free trial…" and, with a plan active, "Switch to Acme Coffee"; the
plan dialog's demo and new-brand pitches name the brand too. Before the
workspace has a brand of its own, the general wording stays.

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

* fix(demo): wait for the brand on screen before showing a page or a band

In a new browser the brand store starts empty until BrandLoader puts the
layout's brands in it, just after the first render. Until then BrandGuard
read the empty list as "No brands yet", the read-only band showed the
workspace's own state before the demo brand's band, and the brand switcher
offered Add Brand. The store now says when it holds the server's list
(loaded, never persisted); pages wait on the skeleton, the read-only band
and Add Brand wait for it, and leaving the dashboard clears it.

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

* fix(demo): keep the nightly prompt demand read off demo brands and cover main's new tables

sweepPromptDemand chose brands by their organization's plan only, so an
active workspace's demo brand would have had its sample prompts read and
DataForSEO's paid tasks set for them. It now leaves demo brands out, as
the other sweeps do. The demo coverage list names the two brand tables
main added: prompt_table_views (skipped: the demo starts on the default
columns) and prompt_demand (pending a demo follow-up).

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

* fix(demo): refuse main's new write routes on a demo brand and keep column layouts open

Main added write routes that name a brand: Action Center's audits and
products, WordPress and Framer connections, and their publish-status
checks. Each now answers 402 demo_brand on a demo brand, as the Webflow
ones do. The Tracked Prompts column layouts (prompt_table_views, 00363)
stay writable on a demo brand: they change no sample data and cost
nothing, and the web keeps them open while read-only too.

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

* feat(demo): follow the app's dark theme in the Chat preview

The preview reads the app's .dark class from its parent page and follows it live; standalone it follows the system setting. Its colours moved to variables with a dark palette close to the app's.

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

* fix(demo): check a topic write once, with its brand, now that the check comes first

Merging main left createTopics, createTopic and updateTopic with two
plan checks each: main's, moved ahead of the name check, and the demo's,
which hands the brand over. Each now checks once, first, with its brand
where it has one.

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

* feat(demo): answer the Chat preview's shortcuts from anywhere on its page

⌘ or Ctrl with ⇧O (new chat), K (search), J (side panel) or \ (menu)
reach the preview while the app around it has the focus: the page hands
them to the frame, which answers them as it does inside. The frame takes
the focus when it opens, and on a Mac the preview shows ⌘ for Ctrl.

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

* fix(demo): keep the competitor timeline off demo brands and cover main's new tables

sweepCompetitorTimeline (learning C3, on main) chose brands by their
organization's plan only, so a demo brand's sample answers would have had
their cited pages read every night. It now leaves demo brands out, as the
other sweeps do. The demo coverage list names the brand tables main added:
cited_page_features, competitor_page_events and competitor_timeline_scans
(pending a demo follow-up) and chat_conversations (with Chat).

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

* feat(chat): read a call's demo flag from brands.is_demo

Chat's precedence (#1776) left readBrandIsDemo false until the demo chain
added brands.is_demo, with a type check that stops compiling once the
column exists. It now reads the column, as the server's demo guard does,
so a tool that changes or spends on the demo brand is refused with
demo_brand; a brand that isn't found isn't one, and a failed read throws.

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

* fix(demo): guard the brand site type detection on the demo brand

POST /brands/:id/detect-site-type (#1761, on main) reads the brand's home
page and may ask AI for its kind. The demo guard's coverage test fails on a
write route in neither list, so it is now guarded by the brand in its path.

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

* fix(demo): name main's new Chat tables in the demo write guard's lists

chat_user_prefs (00400) and chat_auto_choices (00401) are a person's own
rows, not a brand's: the write guard's coverage test fails on a writable
table in no list, so both are named as no brand's rows.

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

* fix(mcp): refuse main's new write tools on the demo brand

approve_task_review, dismiss_task_review (#1713) and
mark_content_draft_published (#1715) write a brand's data, and the demo
gate's test fails on a write tool WRITE_TOOL_BRANDS doesn't name. A task
review finds its brand through its action; a draft through its own row.
The test's API key now carries the role main's McpAuthContext requires.

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

* fix(mcp): refuse the demo brand on the REST mirrors that write, as their tools do

The tools refused a write on the demo brand in their gate, but the REST
mirrors call the same data functions with no gate in front, and those write
with the service role. Each mirror that writes now asks demoBrandRefusal with
its tool's name and arguments first, and answers 402 demo_brand. A test fails
on a REST write route that checks neither this nor a data function that
refuses the demo brand itself.

* fix(mcp): refuse the demo brand on the REST mirrors of main's new write tools

The task review approve and dismiss routes and the draft published route
call demoBrandRefusal before their data functions, as their tools do. The
routes test's auth carries main's role, and the notes that waited for
this part say where the demo brand is refused.

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 29, 2026
…and, part 7) (#1740)

* feat(web): let a workspace whose plan ended browse read-only, with one "Choose a plan" dialog

On the cloud, an ended trial, a cancel during the trial and a cancel
after the first payment can now sign in and look around. They used to
see a full-screen "subscription expired" notice that only signed out.
Onboarding is unchanged: an admin who never started a trial still goes
to the plan step.

- The dashboard layout lets these workspaces in, read-only. A thin
  banner says so, with "See plans".
- UpgradeDialogProvider and useUpgradeGate ({ guard, isLocked,
  openUpgrade }) open one "Choose a plan to keep going" dialog, with the
  action that was clicked as a label.
  - Admins go to Billing; members are told to ask their admin.
  - A failed payment (past_due, unpaid) says so and opens Stripe's
    portal.
  - A 402 subscription_inactive from the API opens the dialog
    (use-failure-toast, api-failure's subscription class, and the
    Webflow, catalog, publish and Send to CMS clients).
- Automatic calls (Library's Webflow status, the editor's link, source,
  claim and page reads, Improve's read) aren't sent while locked.
- Billing: an ended subscription starts a new Checkout ("Choose
  {plan}", monthly or annual). The checkout route takes admins only,
  refuses a second live subscription (409), and validates its body.
  Billing reads again after a change.
- MCP: list_ and get_ tools stay open; every other tool, and REST
  writes, answer subscription_inactive. Chat and new conversations
  answer 402, and runSiteAuditFor, generateBriefFor and
  createImproveActionFor check too. A chat message refused by a 402
  goes back to the input.

Self-hosted is unchanged.

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

* feat(billing): show the plans in the read-only dialog, with Monthly or Annual and a promo code

The "Choose a plan to keep going" dialog for an ended plan now carries
the plans, as the approved design has them.
- Starter and Growth (Popular) have "Choose {plan}"; Custom has "Starting
  at $499/mo" and "Contact us". Each lists the Billing cards' features,
  through a shared usePlanFeatures.
- Monthly or Annual ("Save 20%"): an annual price shows its struck 12×
  price and what it is a month.
- A promo code is checked by the API (POST /api/stripe/promo-code, admins
  only), through the same Stripe lookup #1300 uses (findPromotionCode,
  takesPromoCode: monthly plans only).
  - A valid code shows its chip, the first month's price on each card and
    in the button ("Choose Growth · $124.50 today").
  - A bad one says so; on Annual a note offers Switch to Monthly.
- Choose opens Stripe Checkout for that plan and period, with the code
  applied as a discount. The checkout route checks the code again and
  refuses it on an annual plan.
- Members see "Ask your admin to choose a plan", with no code field.
- The footer reads "Prices in USD." with a link to the pricing page.
- A failed payment keeps its "Update payment method" dialog.

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

* fix(billing): word the dialog's custom AI usage "from 10x", as Billing does after #1598

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

* feat(web): open the plan dialog from the Prompts area's actions while the plan has ended

Read-only, part C1. On an ended plan, every action in Prompts, Prompt
Suggestions, Topics, Query Fan-out, Brand Visibility and Competitors
opens the "Choose a plan" dialog with the action named, and runs
nothing. On an active plan they run as before. Buttons aren't disabled.
- Tracked Prompts: add, import, edit, analyze and refresh volumes, the
  bulk bar, work status and the row menu.
- Prompt and topic suggestions: generate, add, accept, dismiss.
- Manage prompts and topics: add, generate, locations, analyze, edit,
  delete.
- Query Fan-out's Track; Brand Visibility's Run All, Test Single Prompt,
  Opportunities' Track and Send, and pinning a competitor.
- Competitors: suggest (its dialog calls AI on opening), add, delete.
- The Positions panel: Improve's Generate and Regenerate, Send Actions,
  and Create or Optimize content.
- The labels live in readOnly.actions.* ("Adding prompts needs a plan").
- volumes.ts tells the API's 402 subscription_inactive from a feature
  the plan lacks, so a refused analysis opens the dialog instead of "not
  part of your current plan".
- While locked, Tracked Prompts doesn't warn that volume data is
  unavailable, and Query Fan-out doesn't send its intent classification.

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

* feat(web): open the plan dialog from the content area's actions, and keep the editor read-only, while the plan has ended

Read-only, part C2. On an ended plan, every action that writes or costs
in Content Opportunities, the opportunity panel, Content Plan, Library,
New content and the Content Editor opens the "Choose a plan" dialog,
naming the action, and runs nothing.
- Opportunities: New, the bulk bar (send, done, dismiss and delete open
  the dialog instead of their confirm), the row menu, the webhook
  settings' Test and Save, and the panel's sends, brief, Reviewed,
  Restore and Dismiss.
- Plan: New content, Start, Assign, Priority, Hide and Show. A ?start=
  link starts nothing while locked.
- Library: New content (and ?new=1), status changes, archive, delete,
  and single and bulk Send to CMS.
- The editor:
  - Run Agent, Rewrite, Fix rules, hand-off;
  - accepting or rejecting suggestions;
  - Mark ready, Ready back to review, Mark published, Send to CMS,
    History Restore;
  - page and site type, author and reviewer;
  - Quality's confirms, sources and images, and Add line or Remove;
  - renaming, dropping files, the toolbar;
  - the Brief's run, rewrite and edit; the Sources and Rules changes;
    Your input.
- The editor itself is read-only while locked (editable: false, the
  HTML view readOnly), and autosave is off (useDraftAutosave { off }):
  nothing is saved, and leaving doesn't warn.
- Reading, filters, exports, Copy HTML and Stop stay open.

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

* feat(web): open the plan dialog from the remaining areas' actions, and from every way to add a brand, while the plan has ended

Site Audit, Action Center, Mentions, Citations, AI Referral Traffic,
Shopping, Reports, Chat, brand settings and Settings now guard their
actions with useUpgradeGate, as Prompts (#1606) and Content (#1609) do.
Every way to add a brand (sidebar, /dashboard/brands, brand guard,
/dashboard/brands/new) opens the dialog. Disconnects, key revokes and
API key creation stay open.

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

* feat(web): refuse direct database writes from a workspace whose plan has ended, on the server

Server actions and Next routes that write to Supabase without going
through the API now call assertWritable() first: on the cloud, an
organization without an active plan gets SubscriptionInactiveError
(routes: 402 subscription_inactive), so the read-only rule holds even if
a guarded button is bypassed. Setup's writes stay open to an
organization that never subscribed, as the API's onboarding routes do.
Profile, invitations accepted, revokes, removals, API keys and billing
stay open. A static test pins every writing action to the check or to
the open list.

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

* fix(web): keep removing members, revoking invitations and disconnecting stores open while read-only, and stop the site trust card's automatic re-read

From the pre-push review: ending an access stays open, as disconnects
do; a partial site trust result isn't re-read while the plan has ended,
since that read scrapes. Adds tests for the audit page's Run audit and
the integrations' property mapping, resets shared mocks between tests,
closes the mobile menu before the dialog, and words the KPI preview for
a read-only workspace.

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

* fix(web): open the plan dialog from Add Brand at the plan's brand limit too, while read-only

At the limit, /dashboard/brands' Add Brand links to Billing; a read-only
workspace now gets the dialog there as on every other way to add a brand.

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

* feat(web): let a read-only workspace delete a brand

Ansvisor's decision (2026-10-27): deleting a brand only removes what the
person gave us, so it stays open while the plan has ended. The API opens
DELETE /brands/:id in #1611.

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

* fix(web): keep setup's Shopping mode working for a new workspace, read the plan in one query, and pin the write check's place

From the pre-push review: markBrandAsEcommerce no longer goes through
the strictly guarded setBrandShoppingMode (a shared applyShoppingMode
does the writes), so a setup detected as e-commerce turns Shopping on
again. assertWritable reads the profile and its organization in one
query. The coverage test now requires the check as each writer's first
await, sees writers kept in variables and signed upload URLs, refuses a
setup-open function that reaches a strictly guarded one, and keeps brand
deletion open (Ansvisor, 2026-10-27). main's saveDraftShoppingPath is
guarded; catalog-client's every-code test leaves out 'subscription',
which opens the plan dialog instead of a message.

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

* feat(web): show "No active plan" instead of a used-up quota while the plan has ended, and keep the buttons opening the plan dialog

With #1611, an ended workspace's quota reads come back as `noPlan` with
0 limits. isNoPlan(quota, isLocked) keeps those from reading as used up:
Site Audit, Prompts, the content usage card, Improve and the opportunity
panel say "No active plan" instead of a red 0/0 or "limit reached", and
their buttons stay clickable so the guard opens the dialog. The AI bot
report shows the workspace's own data instead of the Starter upsell.
Setup's suggestions name the onboarding daily limit (429) on their own.

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

* fix(web): keep a saved content suggestion reachable, the Starter bot upsell and one lock rule while the plan has ended

From the pre-push review: the Prompts row menu still looks up an open
content suggestion with no plan; an ended Starter workspace keeps the
bot report's upsell (its old plan has no report), read from the plan
the web already knows; auditBlock, bulkSuggestBlock and the bot states
take isLocked as the pages do; the audit settings and the content usage
tooltip don't speak of a plan that renews; setup's prompt step keeps its
own "add your own" line. Improve's unreachable no-plan branch is gone.
Tests for the onboarding limit and the quota meter.

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

* fix(web): leave the plan dialog's store error out of the every-code message test

main's catalog-client test (#1583) asks for words for every StoreError
code; 'subscription' opens the upgrade dialog instead of saying one, so
the test leaves it out, as #1613 does.

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

* fix(web): open the plan dialog from Merchant Center, category pages and main's other new actions while the plan has ended

main's new writes, with C3's guard pattern and labels:
- Merchant Center (#1583): picking and adding an account open the plan
  dialog ("Connecting a store needs a plan"); the server's 'subscription'
  refusal on Add opens it too, instead of looking up a missing
  settings.catalog.stores.errors.subscription message.
- Category pages (#1587): Change, Save, No page and Use the match are
  guarded; the catalog client reads the server's 402
  subscription_inactive as 'subscription', which opens the dialog
  instead of the generic failure.
- Brief › Shopping path (#1591): Pick from the catalog, Pick again, Add
  product, Lock, Swap and Remove are guarded.
- Action Center Check now (AC-010, #1565) is guarded.

New labels: changeCategoryPages, changeShoppingPath, checkTasks.
Insert › Products (#1607) already goes through the toolbar's guard and
the read-only editor shows no insert menu; a test now says so. The
Shopping rules (#1610) change through the rules hook, already guarded.

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

* fix(web): check the plan inside Merchant Center's Add, not by wrapping it during render

React's refs rule refuses passing add, which reads addingRef, to guard
while rendering. add now opens the plan dialog itself on a read-only
workspace.

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

* test(web): keep brand setup's limits in the new brand page test's mock

main's new brand page now reads BRAND_SETUP_LIMITS from ai-brand-setup
(#1661), which the test's mock left out.

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

* feat(demo): open the plan dialog with the demo's offer on a demo brand

The selected brand being the organization's demo brand (brands.is_demo,
sample data) locks the dashboard as a read-only workspace is locked, with
its own reason: guarded actions open the plan dialog with the demo's offer.
A workspace that never subscribed is offered the free trial, then 50% off
("Start free trial"); one whose plan ended gets 50% off its first month
("Choose {plan}"). The label names what was clicked as something that
works on your own brand, and an admin finds SAVE50 applied (quietly left
empty when Stripe refuses it). With a plan active, the dialog points back
to the workspace's own brand; a payment being retried still asks for the
payment method. The server's 402 demo_brand opens the same dialog.

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

* feat(demo): show a band across the dashboard while the demo brand is open

Where the read-only band sits, and instead of it: "You're exploring
{brand}, a demo brand with sample data", with a small button to the plan
dialog's offer ("Try it on your brand · 50% off" for a workspace that never
subscribed, "Use it for your brand · 50% off" once its plan ended), or back
to the own brand while a plan is active. The band asks the API once per page
load to bring the demo brand up to date (POST /api/demo) and reads the
pages again when its sample data was written anew, so the demo follows the
product by itself.

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

* feat(demo): add a demo brand per organization, kept out of the plan's counts

Migration 00380 adds brands.is_demo, demo_version, demo_built_at and
demo_hidden_at, one demo brand per organization (partial unique index) and
policies that let members read it but never insert, change or delete one.
The plan's prompt-location quota, the usage cards' account totals and the
web's brand limit leave the demo brand out; the health report's fan-out
share leaves out its answers. The brand delete route refuses it: the demo
brand is hidden, not deleted.

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

* feat(demo): skip demo brands in every nightly sweep and job

The daily tracking list, the job claim and recovery (activeBrandFilter /
isBrandActive), the signal catch-up, the pulse, the task writer, executor
and checks, action validation and Improve outcomes, the Insights sweep,
brand facts, Search Console and Analytics syncs, page opportunities, the
traffic digest, auto-audits, catalog feeds, Webflow status and volume
analysis all leave demo brands out: their data is sample data and nothing
may track, write or spend for it.

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

* feat(demo): mark the demo brand in the brand switcher, with Show or Hide

The demo brand reads "Demo · sample data" under its name, in place of a
domain, and a brand of a workspace that never had a plan reads "Not tracked
yet". For an admin or a manager, the menu ends with "Hide the demo brand"
(PATCH /api/demo), or "Show the demo brand" once it is hidden, which brings
it back and opens it: the demo brand is hidden after a purchase, never
deleted. A hidden demo brand stays out of the dashboard's brand list and
the brands page, and the demo brand never counts toward the plan's brands,
there or when a brand is added.

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

* feat(demo): show Chat as coming next week on the demo brand, with its v2 preview

On the demo brand, the menu's Chat item carries "Soon (next week)" in its
badge, ahead of "Set up" (the badge rule now lives in dashboardNavBadge, for
the sidebar and the mobile menu alike), and /dashboard/agent shows the Chat
v2 mockups themselves in a full-height frame, opening on Home, under a thin
line that Chat arrives next week. The five mockup files are copied as they
are into public/demo/chat (about 720 KB), outside Prettier's scope. On any
other brand, Chat is unchanged.

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

* feat(demo): show the demo brand's integrations connected, and those to come as coming soon

On the demo brand, Settings › Integrations shows the real cards with the
demo's states, kept in one list (lib/demo/integrations.ts): Google Search
Console, Google Analytics and Webflow as connected, the way they look with
a live connection, marked "Sample data", the demo brand mapped to a sample
property and Webflow sending to a sample collection, with nothing read from
the API or Composio and no set-up lines. Disconnect and Replace token open
the plan dialog. Merchant Center shows Coming soon on its own card, and
Shopify, WordPress, Framer and Wix, which have no card yet, a Coming soon
row in their group. When one goes live, its line in the list turns
connected.

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

* feat(demo): build the Brewline Coffee demo brand's core data

lib/demo/ builds an organization's demo brand in its own brands: Brewline
Coffee (brewline.example) with fictional `.example` competitors and
publishers, 12 prompts in 3 topics, 6 engines and a run every 3 days over
a month (720 short answers) with citations, product cards, searches and
volumes. Answers are raw engine responses run through tracking's own
parseScraperResponse, parseResponse and the result and shopping card rows
(now pure resultRow and shoppingCardRows in cloro-result-handler.js), and
the rollups are rebuilt by the nightly run's own functions.

ensureDemoBrand creates it, rebuilds it in place (same ids) when
DEMO_VERSION moves on or its data is three days old, and leaves it alone
otherwise; concurrent visits share one build (one-per-org index, a
compare-and-set claim, a lease). Modules are { name, tables, build }, and
a coverage test fails on any brand_id table the demo neither builds nor
lists as skipped or pending.

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

* feat(demo): open and hide the demo brand through /api/demo

POST /api/demo creates or rebuilds the organization's demo brand for any
member and returns { brandId, version, rebuilt }; PATCH /api/demo
{ hidden } hides or shows it for admins and managers ({ brandId, hidden },
404 no_demo without one). Both stay open once a plan has ended.

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

* feat(demo): let a workspace with no plan explore the demo brand

Onboarding's plan step gets a second way in under the plan cards: "Not
ready to add a card? Explore a demo brand", whose button makes the demo
brand (POST /api/demo), selects it and opens the Action Center, the
person's own brand kept as set up. An admin who never subscribed used to be
sent back to that step from the dashboard; with a demo brand in the
organization, they now browse read-only instead (evaluateSubscriptionAccess
takes hasDemoBrand). The read-only band of an ended or canceled plan gets
"See the demo", for an admin or a manager, or anyone once the demo brand is
listed: the same flow, which shows a hidden demo brand again. The plan
step's preview reads the own brand, never the demo brand.

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

* feat(demo): offer the free trial on the own brand of a workspace that never had a plan

A workspace that never subscribed now gets the trial offer on its own
brand too, not only on the demo brand: the read-only band says the brand
isn't tracked yet ("Start your 14-day free trial, then get 50% off your
first month") with Start free trial for admins, and the dialog's title is
"Start your 14-day free trial: then 50% off your first month", with SAVE50
applied and Start free trial on each plan. Members are asked to have an
admin start it. ChoosePlanDialog takes the offer as a `pitch` (from the
demo brand, or the own brand).

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

* feat(demo): show what is paid today on the demo's first-month offer

With SAVE50 applied, the demo's 50%-off-first-month offer words its
buttons as the plan dialog does everywhere else: "Choose Starter · $24.50
today"; "Choose {plan}" alone when the code didn't apply.

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

* feat(demo): say the demo brand is hidden, not deleted, in its Danger tab

On the demo brand, brand settings' Danger tab says "The demo brand can't
be deleted; hide it from the brand menu instead." in place of the name to
confirm, and Delete brand stays disabled. The server refuses the delete
too.

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

* feat(demo): cancel a demo brand's jobs as demo_brand, not as an ended plan

A job claimed for a demo brand ("Run now", the internal trigger, a retry
or the recovery) was cancelled as subscription_inactive, as if the plan had
ended. It now says demo_brand: brandStopReasons tells why no work may start
for a brand, and activeBrandFilter is built on it. Nothing is tracked,
generated or counted before the cancel: the on-demand cap counts the
brand's own jobs, and AI usage is recorded by the workers, which never run.

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

* feat(demo): refuse the web app's own writes on the demo brand

assertWritable takes the brand an action writes for and refuses the demo
brand (DemoBrandError, digest demo_brand), whatever the plan, reading the
brand beside the plan through the person's session. Every gated server
action that takes a brand id hands it over (52 of them, the brand's own id
in updateBrand); actions that name no brand, such as the profile or the
organization, read nothing more. A route's refusal answers 402 demo_brand,
and the browser reads the digest as it reads subscription_inactive: an
uncaught refusal opens the plan dialog. The read-only coverage test now
also fails a gated action that takes a brand id without handing it to the
check.

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

* feat(demo): refuse writes and costs on the demo brand with 402 demo_brand

The demo brand's data is sample data, so nothing asked of it may change it
or start a cost. A middleware after decodeToken (before the plan's check,
so the answer is the same with a plan or without) refuses every write that
names a demo brand: in the path, the body, the query, or through the row it
acts on (a draft, an opportunity, a prompt, a task...). Every write route
under /api is named, guarded or open with its reason (onboarding, the
organization's own integrations, stopping work, the demo routes, brand
delete's own 409); a test reads the route files and fails on one that
isn't. Reads and exports stay open; brand facts are read only as kept on a
demo brand, so its site is never fetched.

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

* docs(demo): explain the demo brand, and keep it covered in CONTRIBUTING

A new guide, Demo brand, covers:
- who sees Brewline Coffee: a sign-up without a card, a workspace whose
  plan ended, everyone once it exists;
- what it shows: the live product with fictional sample data on `.example`
  domains, Chat as Soon, integrations with sample data;
- what it can't do, and the offers the plans dialog makes from it;
- hiding and showing it, never deleting it;
- how it stays current: DEMO_VERSION, the 3-day rebuild, the 14-day
  clear-out;
- that it's an Ansvisor Cloud feature.

The FAQ gets "Can I try Ansvisor without a card?".

CONTRIBUTING: a migration that adds a brand-scoped table says what the demo
shows for it (a module under server/src/lib/demo/, or SKIPPED in
coverage.js with the reason); a change to the demo data's shape bumps
DEMO_VERSION.

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

* feat(demo): hide the demo brand once a plan is bought

When a subscription starts (Stripe's checkout.session.completed, trial
included, and the return from Checkout, whichever comes first), the
organization's demo brand gets demo_hidden_at, through the service role:
hidden, never deleted. Only a demo brand still shown is touched, and
subscription updates, renewals and payments never touch it, so one an admin
shows again stays shown. A first payment still open hides nothing, and a
failed write never fails the purchase. Hidden before the dashboard opens,
the demo brand leaves the brand list, so the person lands on their own
brand.

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

* feat(demo): refuse people's writes to a demo brand's rows in the database

Members can write a brand's rows straight through Supabase, under RLS,
past the API's 402. Migration 00381 adds refuse_demo_brand_writes(), a
BEFORE INSERT/UPDATE/DELETE row trigger that raises 42501 'demo_brand' for
a demo brand's row unless the role bypasses RLS (the service role the
server and the demo generator write with). It is attached to the 24 tables
people can write that carry a brand_id, and, through their parent row, to
the 13 that reach their brand another way (prompts through prompt_sets,
prompt notes and target URLs through prompts, a draft's inputs and sources
through content_drafts, tasks and events through actions...). A test reads
the policies and triggers from the migrations and fails on a table people
can write that belongs to a brand and lacks it.

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

* feat(demo): refuse the MCP's brief, audit and Improve endpoints on a demo brand

The internal endpoints the MCP calls (a content brief, a Site Audit, an
Improve action) trust CRON_SECRET and never meet the API's middleware.
Each now answers a demo brand with 402 demo_brand before it calls the
model, starts an audit or writes an action; the MCP relays the message.

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

* feat(demo): clear demo brands nobody opened for two weeks, nightly

Every organization gets a demo brand, so its sample rows would pile up
for workspaces that left. The daily run now clears the data of demo brands
built over 14 days ago (a visit rebuilds every few days, so these weren't
opened since), 200 a night at most: through clearDemoData, the path a
rebuild takes, so rows go in the modules' reverse order. The brand row
stays with no version and no build time, and the next visit builds it
again in place, with the same ids. The clear holds the brand as a build
does, so a visit at the same moment waits for it.

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

* test(demo): look rows up by a set in the demo guard's fake database

The cache test reads 10,000 brands; filtering them with includes() took
seconds and timed out under a full run.

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

* feat(demo): build the demo brand's Action Center, Content, suggestions and reports

Four demo modules over core's answers: signals and a month of actions
(tasks, trail, measured outcomes, a task waiting for review, ready-made
KPIs, Getting started with its page steps opened), prompt clusters,
content opportunities, Editor drafts and Plan marks, prompt, topic and
Improve suggestions, and two saved reports. Numbers are counted from the
demo's own answers; shapes come from the engine's own functions. detect.js
exports single and promptTarget so the demo writes signals in their shape.

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

* feat(demo): register the workflow modules and rebuild demos at version 2

DEMO_MODULES runs core, suggestions, actionCenter, content and reports;
DEMO_VERSION 2 rebuilds existing demo brands on their next visit. The
coverage lists move the workflow tables to built, skip the engine's
internal queues and logs and the org-level author default, and leave the
draft shopping check to demo-site with the catalog.

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

* refactor(audit): read a page already fetched into the audit context with auditContextOf

buildAuditContext fetches the page, robots.txt and llms.txt, then hands
them to auditContextOf, which parses the HTML once and extracts its text
as before. A page that isn't fetched (the demo brand's) is read exactly as
a fetched one.

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

* feat(demo): build the demo brand's AI Referral Traffic over a quarter

Brewline's website (site-world.js) and its traffic: 90 days of Google
Analytics as GA4 reports mapped by ga-sync.js (AI sessions by source and
page, ChatGPT Shopping's feed visits, pages, channels, items), Search
Console's query and page rows mapped by gsc-sync.js, four weeks of snippet
visits (a removed guide's 404s for Broken AI links) and journeys made by
traffic-events.js's eventRow, a month of AI crawler counts with a
Cloudflare Worker connection whose secret hash matches no secret, and the
page opportunities detectPageOpportunities finds in them. The brand maps
the sample GA4 and Search Console properties and has conversions on.

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

* feat(demo): build the demo brand's Site Audit from the audit engine's own verdicts

Brewline's pages are rendered as HTML round by round and scored by
runSignals and scoreAudit: six key pages audited three times as fixes
land, every page in the latest auto-audit. The model-judged signals,
Wikidata's brand entity and the recommendations are written in the shapes
those steps store. The page inventory goes through selectPages and
parseHead, site trust through site-trust.js's checks (4/5: no editorial
policy), and the brand facts through factText and keptFacts.

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

* feat(demo): fill the demo brand's catalog from its product feed

A Google XML feed of 22 products read by the feed parser and kept as
catalogRecords and hashOf keep them, with stable demo ids: a removed
seasonal blend, an out-of-stock size, a sale, no images. The products the
demo's AI answers show as cards are the same page, title and price. Two
categories get their page by hand; the rest match their collection pages.

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

* feat(demo): classify the demo's fan-out searches ahead in the intent cache

The demo writes the intent of each search its answers ran into
fanout_query_intents, keyed as the route keys it (normalizeIntentQuery,
moved to intent-extraction.js), adding only what the shared cache lacks,
so Query Fan-out never needs a model for the demo.

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

* feat(demo): build traffic, Site Audit, the catalog and fan-out intents with the demo brand (version 3)

The demo-site modules join the core in DEMO_MODULES, and DEMO_VERSION is
3, so every demo brand is rebuilt with them on its next visit. Their
tables leave the coverage test's pending list; a CMS connection, sent
drafts, product images and Merchant Center item issues are skipped, with
why.

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

* test(demo): audit the demo's pages once more, not twice, to check its rows stay the same

One rebuild for another brand two days later checks both that only the
ids and dates change, with room past the default 5 s on a busy machine.

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

* feat(demo): read the demo brand over MCP, and write, run or spend nothing on it

The MCP tools run in the web app, so the API's demo_brand refusal didn't
reach them. Now, on Ansvisor Cloud, every tool that writes, runs or spends
answers the demo brand with the web app's DEMO_BRAND body. That happens
whatever the plan, and before the read-only check, in gateWriteTools.
- lib/mcp/demo-gate.ts names how each of the 14 tools finds the brand it
  acts on: a suggestion, opportunity, task, prompt, answer or draft read
  back to its brand.
- A test fails on a new such tool until it is added there.
- Reading stays open.

The costly calls also refuse it inside their data functions, beside
assertSubscriptionActive, so their REST routes (402 demo_brand) and the
in-product agent do too: a brief, a Site Audit, an Improve action.

list_brands marks the demo brand (is_demo) and leaves it out once the
organization hid it, and its description tells the agent what that means.

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

* feat(demo): give the demo brand its own logo

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

* fix(web): read a new sign-up's free plan as Starter's

A new sign-up's organization holds plan 'free' until it picks one. With the
demo brand it reaches the dashboard, where PLANS[planId].limits threw on the
Prompts page. toPlanId maps an unknown plan to Starter's.

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

* feat(demo): give the demo's made-up sites real-looking logos

.example is reserved, so no favicon service knows the demo's brand,
competitors or cited sites. Their logos ship in public/demo/logos; any
other .example site gets a letter mark, so no page asks Google for one.

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

* feat(billing): offer two ways to start a plan: buy now at 50% off the first month, or the free trial

Every plan choice now offers two ways to start, each with a card. Buy now
bills the full plan from day one, with the first-month offer on a monthly
plan ("$24.50 first month, then $49/month", a Limited offer mark); a year
up front is the plain "Choose {plan}". The 14-day free trial comes without
the offer, with limited AI usage ("Free for 14 days, then $49/month"), and
only for an organization that never had a subscription. Checkout takes the
way explicitly (mode: 'buy' | 'trial'): buying never starts a trial, the
trial takes no promotion code and is refused (409 trial_unavailable) to an
organization that had a subscription, and both collect a card. The offer
is one setting, FIRST_MONTH_OFFER in config/plans.ts, turned off with
NEXT_PUBLIC_FIRST_MONTH_OFFER=off; its code no longer redeemable falls back
to the plain price.

The plan dialog (demo, a brand not tracked yet, a plan that ended), the
demo band and the "not tracked yet" band ("Start a 14-day free trial, or
get 50% off your first month." with See plans) and onboarding's plan step
("Choose how to start", two buttons per plan, the demo card below) say it
this way; the "14 days free, then 50% off" wording is gone. Billing's
Checkout for a plan that ended buys now.

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

* feat(demo): start the demo brand's setup ahead, where the demo is offered

The demo brand's first setup takes a while, and "Explore the demo" waited
for all of it. Onboarding's plan step, for an organization with no demo
brand yet, and the read-only band's "See the demo", for an admin or a
manager with none yet, now start POST /api/demo in the background once, as
they show (failures stay quiet). The click waits for that same request,
done at once when it is (prepareDemoBrand, asked once per page, again
after a failure), and its button says "Setting up the demo…" meanwhile.

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

* docs(demo): say how a plan starts from the demo: buy now, or the free trial, both with a card

The pricing changed. Each plan now starts one of two ways, both with a card:
- Buy now: the full plan from day one, 50% off the first month on a monthly
  plan while the offer runs.
- The 14-day free trial: limited AI usage, no discount, only for a
  workspace that never had a plan.

A workspace whose plan ended can buy now.

The demo brand guide and the FAQ say so. "14 days free, then 50% off" is
gone, and the sign-up step is "Choose how to start". The demo brand is
hidden when a workspace first starts a plan.

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

* fix(billing): show the first-month offer when its code can't be checked

Stripe unreachable, or not set up on a local server: the plan dialog still
shows the configured offer; checkout applies the code and says so by the
field if Stripe turns it down.

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

* perf(demo): build the demo's modules side by side after the core

The first module lays down what the others point at; the rest write their
own tables together, each after the module it names in `after`.

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

* feat(demo): tell Chat's preview story with Google AI Overviews

The Chat preview's running example (citations that dropped, why, and the
fix) now follows Google AI Overviews instead of Perplexity. Engine lists,
the logo map and the mockup's own matching rules are unchanged.

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

* feat(demo): show Chat preview's citation changes as small pills

Since you left's drop and win were big bold numbers with ▼/▲; they are now
small pills with a thin arrow on a soft red or green ground.

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

* feat(demo): show the demo brand with Growth, the whole product

While the demo brand is the brand on screen, the plan context reads
Growth whatever the workspace's plan (or none): Product Visibility and
the AI bot report open, every engine shows in the Positions panel and
column, and the Growth marks go. One rule, effectivePlanIdForBrand,
feeds the client's plan context and the server actions' position
reads. Billing keeps reading the organization's own plan (ownPlanId).
Writes and costs are unchanged: on the demo brand they still open the
plan dialog.

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

* fix(billing): show the first month's price once on the plan dialog's cards

With the first-month offer, the card's price already reads "$24.50 first
month, then $49/mo"; the same line under Buy now said it again. Only
"Full plan from day one" stays there, beside the free trial. The
upgrade dialog's test now answers the offer's code check itself, so it
no longer depends on the network to read "Choose Starter".

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

* perf(demo): build the demo faster and rebuild it over its old rows

A first build no longer clears 70 empty tables, and the core writes each
step's independent tables side by side through a shared queue of four
statements (write.js: insertChunks, demoWriter). Its rollups move to a
refresh step that runs alongside the other modules, Insights, Citations and
Mentions together, the month's answer terms in one call (refreshMentionsDaily
takes an optional termDays). The core alone went from about 17 s to 7 s on
the dev database.

A rebuild (new DEMO_VERSION, or data older than three days) no longer
deletes the demo first: an `inPlace` module writes over its rows by key
(ids are deterministic) and deletes only the rows it didn't write again,
then rebuilds the rollups over the old and new days, each refresh call
rewriting its days in one statement. Someone opening the demo meanwhile sees
last week's data, not empty pages. Modules not marked `inPlace` still have
their tables cleared, now just before they are built.

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

* feat(billing): start a plan from Billing the way the plan dialog does

With no plan active, Settings › Billing's cards now offer the plan
dialog's ways to start: Buy now, at 50% off the first month on a monthly
plan while the offer runs, and, for a workspace that never had a plan,
the 14-day free trial. A plan that ended gets Buy now alone. The cards'
price and buttons, the first-month code check and Checkout are one set
of parts (billing/plan-start.tsx) that the dialog and Billing share.

A workspace that never started a plan reads "No plan yet" under Current
Plan, with "Choose how to start" over the cards, instead of
"Starter incomplete".

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

* fix(demo): write over what a new brand's triggers made

A brand just created isn't empty: its insert trigger starts Getting started,
so skipping every clear on a first build made the Action Center's insert hit
getting_started_pkey. An in-place module now always writes over by key (the
first build only skips reading back and pruning); a module that isn't
rebuilt in place clears its own tables just before it is built, on a first
build too, alongside the other modules rather than all up front.

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

* perf(demo): clear the other modules' tables alongside the core on a first build

Nobody looks at a demo being built for the first time, so every module not
rebuilt in place starts clearing what the new brand's triggers made at once,
while the core writes, instead of each in turn later, when its deletes queue
behind the rollups. A rebuild still clears each module just before it is
built, so its old rows stay on show as long as they can.

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

* feat(demo): build a new workspace's demo brand while onboarding goes on

As soon as onboarding has the organization (step 2 on a new account, at
once on a resume), an admin of a workspace without a plan and without a
demo brand starts its setup in the background (wantsDemoAhead +
usePreloadDemo): the first build takes a few seconds, the topics, prompts
and competitors steps longer, so "Explore the demo" on the plan step opens
at once. The plan step's own preload stays. The resume step now reads the
person's own brand only (is_demo false): the demo brand may exist by then.

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

* feat(demo): show the demo being prepared, step by step, while it builds

"Explore the demo" and "See the demo" open the demo at once when its setup
is done. While it is still being prepared, a setup screen (DemoSetupDialog)
shows what the server writes, in its order, as the Content Agent's card
shows a run: the steps done with a check, the one under way with the
agent's sweep and dots and its count going up (720 sample answers from 6
platforms, 2,694 sources, 18 pages audited, 9 actions, 10 opportunities, 2
reports: the generator's own counts). It starts from where a setup asked
ahead already is (demoPreparation), holds on the last step until the
answer comes, then runs through the rest quickly and opens the Action
Center. A failure says so in the screen, with Try again and Close; closing
it lets the setup finish in the background. Counts show whole at once with
reduced motion; the sweep and dots stop. StepSweep moves to components/ui,
shared with the editor's agent card.

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

* fix(demo): drop the Chat preview's own copy of the app menu

The Chat preview sits beside the app's left menu; the mockup's icon rail
(and the governance and signature screens' app menus) showed the same menu
twice, so the demo copies hide them.

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

* feat(demo): replace a table's rows whose ids the database gives

A table with an identity id and no other unique columns (ai_bot_events)
can't be written over by key. write(table, rows, { generated: true })
inserts the new rows and, on a rebuild, deletes the brand's rows that were
there before right after: never empty, both there for a moment.

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

* perf(demo): rebuild the Action Center, Content, suggestions and reports in place

The four workflow modules write through the build's writer (ctx.write):
each step's independent tables side by side, and on a rebuild over their
old rows by key, deleting only what isn't written again, so their pages
never empty while the demo is rebuilt. Keys where a row has no id:
getting_started (brand_id, also what a new brand's trigger made),
getting_started_steps, action_signals, the cluster members, searches and
scopes, and the plan marks; the action and cluster children are found
through their parent (scopes).

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

* test(demo): pin the build order with gates instead of timers

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

* perf(demo): rebuild AI traffic, Site Audit and the catalog in place

The three site modules write through the build's writer (ctx.write): their
independent tables side by side (traffic's thirteen at once, a visit before
its pageviews), and on a rebuild over their old rows by key, deleting only
what isn't written again, so their pages never empty while the demo is
rebuilt. Google Analytics and Search Console rows are keyed by their day and
what they count (their unique columns, as their syncs write them), the
audits' signals by audit and signal (found through their audit), the
single-row settings by brand. ai_bot_events has an identity id and no other
key: its rows are replaced, the old ones deleted right after the new are in.
site-common's insertRows goes.

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

* perf(demo): refresh the demo's mention rollups beside its answer terms

refreshMentionsDaily takes `together`: the rollups (refresh_mentions_daily)
and the answer terms (refresh_mention_terms) take their own locks and write
their own tables, so the demo runs them side by side instead of one after
the other, a second off the longest step of its build. The nightly run
keeps them in turn.

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

* feat(demo): move the Chat preview's inbox into the chat menu and add archived chats

Home keeps the composer in view: Inbox gets its own screen in the chat
menu, the skill cards are shorter with the description on hover, Home to
Files fold under a Menu header, and All chats has Active/Archived tabs.

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

* feat(demo): show Brewline Coffee in the Chat preview, raise its Home and add skill creation

The preview now tracks the demo brand: its pages, rivals, prompts and
sources come from the demo data, and Ansvisor stays only where it names
the product. Home starts higher with more room above the composer, both
cards say when their change happened, One win lists its citations, and
Create a skill opens the chat, upload and URL import flows from CHAT-13.

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

* fix(web): name the profiles→organizations relationship so the plan check reads again

The read-only check before every write embedded organizations from
profiles without naming the relationship. A second foreign key between the
two tables made the embed ambiguous, so the check failed and every write
returned 500 for every workspace, active plans included. Same fix for
getMyProfile.

(cherry picked from commit 62eb7b7658388c1614b38dea93fbe316b8910311)

* test(web): read the demo brand's plan check with the named relationship

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

* feat(billing): start a plan from one choice that fits on one screen

The plan dialog, Settings › Billing with no plan active and onboarding's
plan step now share the same start flow (components/billing/plan-start):

- One choice above the cards: 14-day trial / Monthly, 50% off the first
  month / Yearly, Save 20%. Each card then has one button, one "Due
  today" line (the trial says when it ends and what follows, "Free until
  Nov 11, then $49/month") and "Secure checkout with Stripe · Cancel any
  time" beside the button. The promo code field sits behind "Have a
  code?".
- The first-month offer shows from the first frame, from the config: no
  $49 → $24.50 jump once Stripe answers. A code Stripe can't redeem takes
  it away; one that couldn't be checked keeps it as configured.
- Onboarding's plan step drops its own copy (PLAN_STEP_COPY) for the
  shared cards and Billing's features, with the discounted price large,
  and says what is ready to track for the brand, from its real prompt,
  topic and competitor counts.
- Everything fits 1024×768 and up without scrolling: the plans' features
  open behind "Show plan details" inside the cards, which keep their
  height; on Billing the plan choice comes first while no plan is active.
- A Checkout that doesn't open (Stripe down or not set up, no answer in
  30 s, a refusal) says why by the plan's button instead of spinning.

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

* feat(demo): name the workspace's own brand in the demo band and plan dialog

On the demo brand the band says "Start tracking Acme Coffee with a
14-day free trial…" and, with a plan active, "Switch to Acme Coffee"; the
plan dialog's demo and new-brand pitches name the brand too. Before the
workspace has a brand of its own, the general wording stays.

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

* fix(demo): wait for the brand on screen before showing a page or a band

In a new browser the brand store starts empty until BrandLoader puts the
layout's brands in it, just after the first render. Until then BrandGuard
read the empty list as "No brands yet", the read-only band showed the
workspace's own state before the demo brand's band, and the brand switcher
offered Add Brand. The store now says when it holds the server's list
(loaded, never persisted); pages wait on the skeleton, the read-only band
and Add Brand wait for it, and leaving the dashboard clears it.

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

* fix(demo): keep the nightly prompt demand read off demo brands and cover main's new tables

sweepPromptDemand chose brands by their organization's plan only, so an
active workspace's demo brand would have had its sample prompts read and
DataForSEO's paid tasks set for them. It now leaves demo brands out, as
the other sweeps do. The demo coverage list names the two brand tables
main added: prompt_table_views (skipped: the demo starts on the default
columns) and prompt_demand (pending a demo follow-up).

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

* fix(demo): refuse main's new write routes on a demo brand and keep column layouts open

Main added write routes that name a brand: Action Center's audits and
products, WordPress and Framer connections, and their publish-status
checks. Each now answers 402 demo_brand on a demo brand, as the Webflow
ones do. The Tracked Prompts column layouts (prompt_table_views, 00363)
stay writable on a demo brand: they change no sample data and cost
nothing, and the web keeps them open while read-only too.

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

* feat(demo): follow the app's dark theme in the Chat preview

The preview reads the app's .dark class from its parent page and follows it live; standalone it follows the system setting. Its colours moved to variables with a dark palette close to the app's.

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

* docs(demo): say which integrations the demo brand shows connected, now that WordPress and Framer are live

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

* fix(demo): check a topic write once, with its brand, now that the check comes first

Merging main left createTopics, createTopic and updateTopic with two
plan checks each: main's, moved ahead of the name check, and the demo's,
which hands the brand over. Each now checks once, first, with its brand
where it has one.

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

* feat(demo): answer the Chat preview's shortcuts from anywhere on its page

⌘ or Ctrl with ⇧O (new chat), K (search), J (side panel) or \ (menu)
reach the preview while the app around it has the focus: the page hands
them to the frame, which answers them as it does inside. The frame takes
the focus when it opens, and on a Mac the preview shows ⌘ for Ctrl.

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

* fix(demo): keep the competitor timeline off demo brands and cover main's new tables

sweepCompetitorTimeline (learning C3, on main) chose brands by their
organization's plan only, so a demo brand's sample answers would have had
their cited pages read every night. It now leaves demo brands out, as the
other sweeps do. The demo coverage list names the brand tables main added:
cited_page_features, competitor_page_events and competitor_timeline_scans
(pending a demo follow-up) and chat_conversations (with Chat).

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

* feat(chat): read a call's demo flag from brands.is_demo

Chat's precedence (#1776) left readBrandIsDemo false until the demo chain
added brands.is_demo, with a type check that stops compiling once the
column exists. It now reads the column, as the server's demo guard does,
so a tool that changes or spends on the demo brand is refused with
demo_brand; a brand that isn't found isn't one, and a failed read throws.

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

* fix(demo): guard the brand site type detection on the demo brand

POST /brands/:id/detect-site-type (#1761, on main) reads the brand's home
page and may ask AI for its kind. The demo guard's coverage test fails on a
write route in neither list, so it is now guarded by the brand in its path.

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

* fix(demo): name main's new Chat tables in the demo write guard's lists

chat_user_prefs (00400) and chat_auto_choices (00401) are a person's own
rows, not a brand's: the write guard's coverage test fails on a writable
table in no list, so both are named as no brand's rows.

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

* fix(mcp): refuse main's new write tools on the demo brand

approve_task_review, dismiss_task_review (#1713) and
mark_content_draft_published (#1715) write a brand's data, and the demo
gate's test fails on a write tool WRITE_TOOL_BRANDS doesn't name. A task
review finds its brand through its action; a draft through its own row.
The test's API key now carries the role main's McpAuthContext requires.

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

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants