Skip to content

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

feat(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)

Cihan9e1210551b94
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdx
index db9456f9d..bb61de07a 100644
--- a/docs/guides/action-center.mdx
+++ b/docs/guides/action-center.mdx
@@ -83,6 +83,17 @@ Click a row to open the action. Under its title you set **Status**, **Assignee**
Each action comes with tasks: concrete steps such as "Refresh content for these prompts" or "Add structured data to these pages". Open a task to see its details: **What**, **URL** (the exact page), **Where**, **Why**, **Change** (the text before and after, or the text to add), **How** (one step per line), **Done when**, **How we check** (Automatic: we fetch the page again; Re-run: the prompts run again; Manual: you confirm it), **Type** (Content, On-page, Technical, Outreach, PR or Product), **Effort** and **Role**. Click **Edit** to change any of them. A task from the Action Center's own plan comes with its **Done when**, with **How we check** for most of them (not for a task measured over a GA4 or Search Console window), and with its **URL** when it changes a page and the action is about one page.
+A task checked **Automatic** is checked on its page, fetched again (up to 200 tasks a night, and when you click **Check now**), by what it changes:
+
+- **A broken page:** the page answers again.
+- **Publishing:** the page answers where it wasn't before. A page already live at the first check passes once it changes.
+- **Structured data:** the audit checks that raised the action now pass on the page, such as a FAQ schema with at least two questions.
+- **Crawler access:** robots.txt lets the AI crawlers in, and the page isn't noindex. Only when the audit raised it; a page found uncrawled in the bot logs isn't checked here.
+- **Optimizing, refreshing:** the page has changed since it was first checked, by more than a date, a price or a rotating quote moving. On a short page that takes more than a few words.
+- **A task written with its new text:** that text is on the page, and the text it replaces is gone.
+
+Only pages on the brand's own site are read. One that passes is completed by itself, and History says so; one that doesn't shows **Last check** with what is still missing. A task you reopen after it passed stays open: its checks still show what they find, the nightly check leaves it, and the call is yours. Site Audit fixes are checked by your next audit.
+
A task's status is **To Do**, **In Progress**, **Completed** or **Skipped** (with a reason). Skipped tasks leave the count, so they don't hold an action short of done. Use **Add task** for work of your own, and delete tasks you don't need.
From a task you can also:
diff --git a/server/src/lib/action-center/task-checks.js b/server/src/lib/action-center/task-checks.js
new file mode 100644
index 000000000..aea6cc395
--- /dev/null
+++ b/server/src/lib/action-center/task-checks.js
@@ -0,0 +1,622 @@
+/**
+ * Automatic checks (AC-010): a task whose How we check is `auto` is checked
+ * on its page, on the brand's own site, fetched again with the free reader
+ * (safe-fetch, never the paid scraper), by what the task changes:
+ *
+ * - a broken page answers again (fix_broken_target);
+ * - a page is published: it answers where it never did, or changed since
+ * the first look (publish_content: the page may be live already);
+ * - the audit checks that raised a structured data fix pass on the page
+ * now (fix_structured_data), by the audit's own evaluators;
+ * - robots.txt lets the AI crawlers in, and the page isn't noindex
+ * (fix_crawler_access raised by the audit's ai-bot-access);
+ * - it changed since the first look, by more than a date, a price or a
+ * rotating quote moving (optimize, refresh, strengthen, the call to
+ * action): the first look keeps a sketch of the page's words, and
+ * enough of them must have changed;
+ * - a written task's new text is on it, and the text it replaces gone.
+ *
+ * A task that passes is completed, with the check kept on it and a line in
+ * the action's History; one that doesn't keeps what is missing, for its
+ * card. A task someone reopened after it passed stays open, held: the
+ * sweep leaves it, and no check closes it while its page is the same. A
+ * page that can't be read keeps only when it was tried. Site Audit fixes aren't
+ * checked here: a new audit is a paid run.
+ */
+
+import { createHash } from 'crypto';
+import * as cheerio from 'cheerio';
+import supabaseAdmin from '../../config/supabase.js';
+import { logger } from '../logger.js';
+import { fetchPage } from '../safe-fetch.js';
+import { furnitureNamed } from '../page-content.js';
+import { onBrandDomain } from '../audit/host.js';
+import { aiBotAccess } from '../audit/signals/trust.js';
+import {
+ faqSchema,
+ jsonLdPresence,
+ jsonLdRelevance,
+ jsonLdValidity,
+} from '../audit/signals/structure.js';
+
+/** What each library task's check reads. */
+export const CHECKS = Object.freeze({
+ publish_content: 'published',
+ fix_broken_target: 'answers',
+ fix_structured_data: 'structuredData',
+ fix_crawler_access: 'crawlers',
+ optimize_content: 'changed',
+ refresh_content: 'changed',
+ strengthen_reference_asset: 'changed',
+ strengthen_entity_content: 'changed',
+ improve_cta_path: 'changed',
+});
+
+/** The most open tasks one nightly sweep checks: pages are fetched one at a time. */
+export const SWEEP_LIMIT = 200;
+/** A task tried this recently isn't tried again by the sweep. */
+const RECHECK_AFTER_MS = 20 * 60 * 60 * 1000;
+const FETCH_TIMEOUT_MS = 10_000;
+/** The most of a page or a robots.txt read: the check runs on the API's process. */
+const MAX_PAGE_BYTES = 512 * 1024;
+const OPEN = ['todo', 'in_progress'];
+
+/**
+ * A page changed when the share of its 4-word runs it has in common with
+ * its first look falls below this: a date, a count, a price or a rotating
+ * testimonial leave it near 0.97; a 150-word FAQ added, 0.84…
+ */
+export const CHANGED_BELOW = 0.9;
+/**
+ * …and at least this many of its runs changed: on a short page a date and
+ * a price moving are a large share, never this many runs (each word is in
+ * up to four).
+ */
+export const MIN_CHANGED_RUNS = 40;
+/** The 4-word runs' hashes a sketch keeps, the smallest: about 2.5 KB. */
+const SKETCH_SIZE = 256;
+/** A page with fewer visible words than this isn't read: an empty shell, or bot protection's page. */
+const MIN_WORDS = 20;
+/** A block named as furniture, or a menu, header, footer or form, holding more than this share of the body's words is the page itself. */
+const MAX_SKIPPED_SHARE = 0.5;
+
+/** The audit's structured data checks, by the key the audit raised a fix with. */
+const STRUCTURED_CHECKS = {
+ 'json-ld-presence': jsonLdPresence,
+ 'json-ld-validity': jsonLdValidity,
+ 'json-ld-relevance': jsonLdRelevance,
+ 'faq-schema': faqSchema,
+};
+/** What the card says for a structured data check still failing (en.json taskCheckMissing). */
+const STRUCTURED_MISSING = {
+ 'json-ld-presence': 'no_structured_data',
+ 'json-ld-validity': 'structured_data_invalid',
+ 'json-ld-relevance': 'structured_data_irrelevant',
+ 'faq-schema': 'no_faq_schema',
+};
+/** A fix raised without the audit's checks named: its JSON-LD must at least be valid. */
+const DEFAULT_STRUCTURED = ['json-ld-validity'];
+/** Checks whose warn is still the problem: a block that doesn't parse. */
+const PASS_ONLY = new Set(['json-ld-validity']);
+
+const text = (value) => (typeof value === 'string' ? value.trim() : '');
+
+/** What a task's check reads, or null when it has none here. */
+export function checkKind(task) {
+ const d = task.details ?? {};
+ if (d.check !== 'auto' || !text(d.url)) return null;
+ if (task.task_key) return CHECKS[task.task_key] ?? null;
+ return text(d.change?.after) ? 'text' : null;
+}
+
+/** A name's last label that is a file's, not a domain's: "pricing.html" is a page. */
+const FILE_ENDINGS = new Set([
+ 'html',
+ 'htm',
+ 'php',
+ 'asp',
+ 'aspx',
+ 'jsp',
+ 'cfm',
+ 'shtml',
+ 'xml',
+ 'pdf',
+]);
+
+/**
+ * The task's page as an address: a full one as it is; "//host/path" and a
+ * bare host and path ("acme.example/pricing", "çiçek.com/x") as https, as
+ * the URL import reads it; a path on the brand's first domain. Null when
+ * none can be made.
+ */
+export function pageAddress(url, host) {
+ const value = text(url);
+ if (/^https?:\/\//i.test(value)) return value;
+ if (value.startsWith('//')) return `https:${value}`;
+ if (value.startsWith('/')) return host ? `https://${host}${value}` : null;
+ if (/\s/.test(value)) return null;
+ try {
+ const parsed = new URL(`https://${value}`);
+ const last = parsed.hostname.split('.').pop() ?? '';
+ const domain = parsed.hostname.includes('.') && /^([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(last);
+ return domain && !FILE_ENDINGS.has(last.toLowerCase()) ? parsed.href : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Words as compared: lower case, letters and digits only, a space around each. */
+const words = (value) =>
+ ` ${String(value ?? '')
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}]+/gu, ' ')
+ .trim()} `;
+
+/** Elements whose words are never the page's: code and frames. */
+const CODE = new Set(['script', 'style', 'noscript', 'template', 'iframe', 'svg']);
+/** Elements whose words aren't the page's own unless they hold most of them: menus, header, footer, forms. */
+const AROUND = new Set(['nav', 'header', 'footer', 'aside', 'form', 'button']);
+/** Read after an element's children: its last word ends with it. */
+const AFTER = { type: 'text', data: ' ' };
+
+/**
+ * A page, parsed by htmlparser2: fetchPage's depth count (html-depth.js)
+ * follows its tree, so the count bounds the parse. parse5, cheerio's default,
+ * reopens formatting elements a closed block left open, so its tree can grow
+ * far past the page's own nesting.
+ */
+const loadPage = (html) => cheerio.load(html, { xml: { xmlMode: false } });
+
+/**
+ * Each element's text length under `start`, code left out: one pass, children
+ * before their parent, as a stack.
+ */
+function textLengths(start) {
+ const lengths = new Map();
+ const stack = [[start, false]];
+ while (stack.length) {
+ const [node, done] = stack.pop();
+ if (node.type === 'text') continue;
+ if (!done) {
+ stack.push([node, true]);
+ for (const child of node.children ?? []) stack.push([child, false]);
+ continue;
+ }
+ let length = 0;
+ if (!(node.type === 'tag' && CODE.has(node.name))) {
+ for (const child of node.children ?? []) {
+ length += child.type === 'text' ? child.data.length : (lengths.get(child) ?? 0);
+ }
+ }
+ lengths.set(node, length);
+ }
+ return lengths;
+}
+
+/**
+ * A page's visible words: its body's text outside its menus, header,
+ * footer, forms and furniture (author box, share, related, ads…), with its
+ * title and meta description; entities read as their characters, no
+ * script's or style's (a JSON-LD date or price changes with no one's work).
+ * A block left out as furniture, or a form, that holds most of the body's
+ * words is the page (an <article class="category-social-media">, a page in
+ * one <form>), and is read. Two passes over the body, as stacks: linear on
+ * any page, never out of stack.
+ *
+ * @param {string} html
+ * @param {import('cheerio').CheerioAPI} [$] the page, when it is parsed already
+ */
+export function visibleText(html, $ = loadPage(html)) {
+ const head = [$('title').first().text(), $('meta[name="description"]').attr('content')];
+ const start = $('body')[0] ?? $.root()[0];
+ if (!start) return head.filter(Boolean).join(' ');
+ const lengths = textLengths(start);
+ const most = (lengths.get(start) ?? 0) * MAX_SKIPPED_SHARE;
+ const out = [];
+ const stack = [...(start.children ?? [])].reverse();
+ while (stack.length) {
+ const node = stack.pop();
+ if (node.type === 'text') {
+ out.push(node.data);
+ continue;
+ }
+ if (node.type !== 'tag' || CODE.has(node.name)) continue;
+ const aside = AROUND.has(node.name) || furnitureNamed(node.attribs);
+ if (aside && (lengths.get(node) ?? 0) <= most) continue;
+ // A block's words start and end with it: "Pricing" and "Plans" never run together.
+ out.push(' ');
+ stack.push(AFTER);
+ for (let i = node.children.length - 1; i >= 0; i -= 1) stack.push(node.children[i]);
+ }
+ return [...head, out.join('')].filter(Boolean).join(' ');
+}
+
+const hash = (value) => createHash('sha1').update(value).digest('hex').slice(0, 10);
+
+/** A page's words, as compared. */
+const wordList = (visible) => words(visible).trim().split(' ').filter(Boolean);
+
+/**
+ * A page's sketch: the SKETCH_SIZE smallest hashes of its 4-word runs, and
+ * how many runs it has (`runs`).
+ */
+export function sketch(visible) {
+ const w = wordList(visible);
+ const seen = new Set();
+ for (let i = 0; i + 4 <= w.length; i += 1)
+ seen.add(hash(`${w[i]} ${w[i + 1]} ${w[i + 2]} ${w[i + 3]}`));
+ return { hashes: [...seen].sort().slice(0, SKETCH_SIZE), runs: seen.size };
+}
+
+/** The share two pages' 4-word runs have in common, estimated from their sketches. */
+export function similarity(a, b) {
+ const A = new Set(a);
+ const B = new Set(b);
+ const union = [...new Set([...a, ...b])].sort().slice(0, SKETCH_SIZE);
+ return union.length ? union.filter((h) => A.has(h) && B.has(h)).length / union.length : 1;
+}
+
+/** Whether a page asks not to be indexed (its robots meta tags). */
+function noindex($) {
+ return $('meta[name="robots"], meta[name="googlebot"]')
+ .map((_, el) => String($(el).attr('content') ?? '').toLowerCase())
+ .get()
+ .some((content) => /\bnoindex\b/.test(content));
+}
+
+/**
+ * The 4-word runs two pages don't share, estimated from their sketches'
+ * similarity J and run counts: |A Δ B| = (|A| + |B|)(1 − J)/(1 + J).
+ */
+export function changedRuns(first, now) {
+ const j = similarity(first.hashes, now.hashes);
+ return ((first.runs + now.runs) * (1 - j)) / (1 + j);
+}
+
+/**
+ * What the page's words say against the first look: the first look (or one
+ * of another page) keeps them; a change of more than CHANGED_BELOW's share,
+ * and of at least MIN_CHANGED_RUNS runs, passes. A page that didn't change
+ * enough keeps its first look, so small changes add up.
+ */
+function changedSince(previous, url, visible) {
+ const now = sketch(visible);
+ const first = previous?.sketch;
+ if (!Array.isArray(first?.hashes) || !Number.isFinite(first?.runs) || previous.url !== url) {
+ return { passed: false, missing: ['first_look'], sketch: now };
+ }
+ const changed =
+ similarity(first.hashes, now.hashes) < CHANGED_BELOW &&
+ changedRuns(first, now) >= MIN_CHANGED_RUNS;
+ return changed
+ ? { passed: true, missing: [], sketch: now }
+ : { passed: false, missing: ['not_changed'], sketch: first };
+}
+
+/** An HTML page served where robots.txt should be: no robots.txt. */
+const isHtml = (body) => /^\s*(<!doctype\s+html|<html[\s>])/i.test(body ?? '');
+
+/**
+ * A task's check on its page: `{ passed, missing, sketch?, wasMissing? }`,
+ * or null when the page couldn't be read (no answer, a timeout, a server
+ * error, a 4xx other than "not there", a page nested too deep to parse):
+ * nothing but the try is kept then.
+ * `missing` names what stands between the task and done, as the card words
+ * it (en.json actionCenter.taskCheckMissing).
+ *
+ * @param {string} kind checkKind's
+ * @param {string} url the page's address, on the brand's site
+ * @param {{ previous?: object|null, after?: string, before?: string|null, auditChecks?: string[],
+ * domains?: string[]|null, fetch?: Function }} [options]
+ * `previous`: the last check kept on the task; `after`, `before`: a
+ * written task's change; `auditChecks`: the audit checks that raised the
+ * action on this page; `domains`: the brand's, a redirect off them is off
+ * the site
+ */
+export async function checkPage(
+ kind,
+ url,
+ {
+ previous = null,
+ after = '',
+ before = null,
+ auditChecks = [],
+ domains = null,
+ fetch = fetchPage,
+ } = {},
+) {
+ const read = { timeoutMs: FETCH_TIMEOUT_MS, maxBytes: MAX_PAGE_BYTES, truncate: true };
+ let page;
+ try {
+ page = await fetch(url, read);
+ } catch (err) {
+ // "Not there" (404, 410) is an answer. Another 4xx (bot protection, a
+ // rate limit), a server error, none at all or a page nested too deep to
+ // parse ('too_deep') says nothing.
+ if (err?.code === 'http_error' && (err.status === 404 || err.status === 410)) {
+ return { passed: false, missing: ['page_error'], wasMissing: true };
+ }
+ return null;
+ }
+ // A redirect off the brand's site isn't the brand's page.
+ if (domains && !onBrandDomain(page.url, domains)) return { passed: false, missing: ['off_site'] };
+ if (kind === 'answers') return { passed: true, missing: [] };
+
+ const $ = loadPage(page.html);
+ if (kind === 'structuredData') {
+ const named = auditChecks.filter((key) => STRUCTURED_CHECKS[key]);
+ const failing = (named.length ? named : DEFAULT_STRUCTURED).filter((key) => {
+ const { status } = STRUCTURED_CHECKS[key].evaluate({ $ });
+ return status === 'fail' || (PASS_ONLY.has(key) && status !== 'pass');
+ });
+ return { passed: !failing.length, missing: failing.map((key) => STRUCTURED_MISSING[key]) };
+ }
+
+ if (kind === 'crawlers') {
+ let robotsTxt = '';
+ try {
+ const robots = await fetch(new URL('/robots.txt', page.url).href, {
+ ...read,
+ // Crawlers read it whatever its type (S3 serves it as octet-stream).
+ types: /(?:)/,
+ accept: 'text/plain',
+ });
+ robotsTxt = isHtml(robots.html) ? '' : robots.html;
+ } catch (err) {
+ // None (4xx): no rules, every crawler in. Asked to wait (429), a
+ // server error or no answer says nothing.
+ const none = err?.code === 'http_error' && err.status < 500 && err.status !== 429;
+ if (!none) return null;
+ }
+ const missing = [];
+ if (aiBotAccess.evaluate({ robotsTxt }).status === 'fail') missing.push('crawlers_blocked');
+ if (noindex($)) missing.push('noindex');
+ return { passed: missing.length === 0, missing };
+ }
+
+ const visible = visibleText(page.html, $);
+ // An empty shell, or bot protection's page, isn't the page.
+ if (wordList(visible).length < MIN_WORDS) return null;
+ if (kind === 'text') {
+ const onPage = words(visible);
+ if (!onPage.includes(words(after))) return { passed: false, missing: ['change_not_found'] };
+ // A replacement: the text it replaces gone too, unless the new text holds it.
+ const old = text(before);
+ if (old && !words(after).includes(words(old)) && onPage.includes(words(old))) {
+ return { passed: false, missing: ['old_text_still_there'] };
+ }
+ return { passed: true, missing: [] };
+ }
+ if (kind === 'published') {
+ // Not there before, never seen live, and answers now: published.
+ if (previous?.wasMissing && !previous.sketch && previous.url === url) {
+ return { passed: true, missing: [] };
+ }
+ return changedSince(previous, url, visible);
+ }
+ if (kind === 'changed') return changedSince(previous, url, visible);
+ return null;
+}
+
+/** A stored domain's host, as the site is served: www kept. */
+const storedHost = (domain) =>
+ String(domain ?? '')
+ .trim()
+ .replace(/^[a-z][a-z0-9+.-]*:\/\//i, '')
+ .replace(/[/?#].*$/, '')
+ .toLowerCase() || null;
+
+/** The brand's domains, its primary first. */
+async function brandDomains(brandId) {
+ const { data, error } = await supabaseAdmin
+ .from('brand_domains')
+ .select('domain')
+ .eq('brand_id', brandId)
+ .order('is_primary', { ascending: false })
+ .order('created_at', { ascending: true });
+ if (error) throw new Error(error.message);
+ return (data ?? []).map((row) => row.domain).filter(Boolean);
+}
+
+/** An address as compared with a target's: its host without www, its path without a trailing slash. */
+function samePage(address) {
+ try {
+ const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(address) ? address : `https://${address}`);
+ return `${url.hostname.replace(/^www\./, '')}${url.pathname.replace(/\/+$/, '')}${url.search}`.toLowerCase();
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The audit checks the task's page failed when its action was raised
+ * (payload.targets[].checks): the page's own target (http or https, www or
+ * not, a trailing slash or not), else the action's only one, else every
+ * target's together (the stricter side).
+ */
+async function auditChecksFor(actionId, url) {
+ const { data, error } = await supabaseAdmin
+ .from('actions')
+ .select('targets:payload->targets')
+ .eq('id', actionId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ const targets = (Array.isArray(data?.targets) ? data.targets : []).filter(Boolean);
+ const page = samePage(url);
+ const own = targets.find((t) => typeof t.id === 'string' && samePage(t.id) === page);
+ const read = own ? [own] : targets;
+ return [
+ ...new Set(
+ read
+ .flatMap((t) => (Array.isArray(t.checks) ? t.checks : []))
+ .filter((c) => typeof c === 'string'),
+ ),
+ ];
+}
+
+/**
+ * Writes the task's details as checked, only if the task is as it was read
+ * (its status and its last change): neither a move nor an edit meanwhile is
+ * lost. Whether it was written.
+ */
+async function writeCheck(task, details, { completes = false, now }) {
+ let write = supabaseAdmin
+ .from('action_tasks')
+ .update({
+ details,
+ ...(completes ? { status: 'completed', skip_reason: null } : {}),
+ updated_at: now.toISOString(),
+ })
+ .eq('id', task.id)
+ .eq('status', task.status);
+ if (task.updated_at) write = write.eq('updated_at', task.updated_at);
+ const { data: updated, error } = await write.select('id');
+ if (error) throw new Error(error.message);
+ return Boolean(updated?.length);
+}
+
+/**
+ * Checks one task and keeps what it found on it (`details.autoCheck`, with
+ * the page it read): passed, it is completed and the action's History says
+ * so. A task someone reopened after it passed on this page is held: its
+ * checks are kept, never close it while its page is the same, and the
+ * sweep leaves it (the call is theirs). Returns `{ autoCheck }`, or
+ * `{ reason }` when nothing was checked: 'not_checkable' (no check here),
+ * 'not_open' (done or skipped), 'no_answer' (the page couldn't be read),
+ * 'changed' (someone changed the task meanwhile).
+ *
+ * @param {{ id: string, action_id: string, task_key: string|null, title?: string|null,
+ * status: string, details: object|null, updated_at?: string }} task
+ * @param {{ brand_id: string }} action
+ */
+export async function runTaskCheck(task, action, { fetch = fetchPage, now = new Date() } = {}) {
+ const kind = checkKind(task);
+ if (!kind) return { reason: 'not_checkable' };
+ if (!OPEN.includes(task.status)) return { reason: 'not_open' };
+ const d = task.details ?? {};
+ const domains = await brandDomains(action.brand_id);
+ const url = pageAddress(d.url, storedHost(domains[0]));
+ if (!url) return { reason: 'not_checkable' };
+ const previous = d.autoCheck ?? null;
+ let auditChecks = [];
+ if (kind === 'structuredData' || kind === 'crawlers') {
+ auditChecks = await auditChecksFor(task.action_id, url);
+ // Raised from the bot logs (a cited page crawlers never read): robots.txt
+ // can't say it's fixed. Its try is kept, so the sweep goes on to others.
+ if (kind === 'crawlers' && !auditChecks.includes('ai-bot-access')) {
+ await writeCheck(
+ task,
+ { ...d, autoCheck: { ...(previous ?? {}), triedAt: now.toISOString() } },
+ { now },
+ );
+ return { reason: 'not_checkable' };
+ }
+ }
+
+ // Only the brand's own pages are read.
+ const found = onBrandDomain(url, domains)
+ ? await checkPage(kind, url, {
+ previous,
+ after: d.change?.after,
+ before: d.change?.before,
+ auditChecks,
+ domains,
+ fetch,
+ })
+ : { passed: false, missing: ['off_site'] };
+ const samePageAsBefore = previous?.url === url;
+ // An open task whose last check passed on this page can only have been
+ // reopened: held from then on, for this page, whatever later checks find.
+ const held = samePageAsBefore && (previous?.held === true || previous?.passed === true);
+ const completes = Boolean(found?.passed) && !held;
+ // A first look is kept for the page it was taken of, through a read that found nothing to keep.
+ const kept = found?.sketch ?? (samePageAsBefore ? previous?.sketch : undefined);
+ const autoCheck = found
+ ? {
+ at: now.toISOString(),
+ triedAt: now.toISOString(),
+ url,
+ passed: found.passed,
+ missing: found.missing,
+ ...(kept ? { sketch: kept } : {}),
+ ...(found.wasMissing ? { wasMissing: true } : {}),
+ ...(held ? { held: true } : {}),
+ }
+ : { ...(previous ?? {}), triedAt: now.toISOString() };
+
+ if (!(await writeCheck(task, { ...d, autoCheck }, { completes, now }))) {
+ return { reason: 'changed' };
+ }
+ if (!found) return { reason: 'no_answer' };
+
+ if (completes) {
+ const { error: eventError } = await supabaseAdmin.from('action_events').insert({
+ action_id: task.action_id,
+ event: 'task_checked',
+ data: { taskId: task.id, task: task.task_key ?? null, title: task.title ?? null },
+ actor_id: null,
+ });
+ if (eventError) logger.warn({ err: eventError }, '[task-checks] History line not written');
+ await supabaseAdmin
+ .from('actions')
+ .update({ updated_at: now.toISOString() })
+ .eq('id', task.action_id);
+ }
+ return { autoCheck };
+}
+
+/**
+ * The nightly sweep: open tasks checked `auto` that can be checked here (a
+ * library task with a check, or a written one with its new text) and have a
+ * page, of open actions, not held (reopened after they passed), the least
+ * recently tried first, none tried in the last day, one page at a time, at
+ * most SWEEP_LIMIT. A failure on one task
+ * is logged and the rest go on.
+ *
+ * @returns {Promise<{ checked: number, passed: number }>}
+ */
+export async function sweepTaskChecks({
+ limit = SWEEP_LIMIT,
+ fetch = fetchPage,
+ now = new Date(),
+} = {}) {
+ const { data: rows, error } = await supabaseAdmin
+ .from('action_tasks')
+ .select(
+ 'id, action_id, task_key, title, status, details, updated_at, actions!inner(brand_id, status, deleted_at)',
+ )
+ .in('status', OPEN)
+ .eq('details->>check', 'auto')
+ .not('details->>url', 'is', null)
+ .or(
+ `task_key.in.(${Object.keys(CHECKS).join(',')}),and(task_key.is.null,details->change->>after.not.is.null)`,
+ )
+ // A task reopened after it passed is the person's call: Check now still reads it.
+ .is('details->autoCheck->>held', null)
+ .is('actions.deleted_at', null)
+ .not('actions.status', 'in', '(completed,dismissed)')
+ .order('details->autoCheck->>triedAt', { ascending: true, nullsFirst: true })
+ .limit(limit);
+ if (error) throw new Error(error.message);
+
+ const since = now.getTime() - RECHECK_AFTER_MS;
+ const due = (rows ?? []).filter(
+ (row) => checkKind(row) && !(Date.parse(row.details?.autoCheck?.triedAt ?? '') >= since),
+ );
+ let checked = 0;
+ let passed = 0;
+ for (const row of due) {
+ const action = Array.isArray(row.actions) ? row.actions[0] : row.actions;
+ try {
+ const result = await runTaskCheck(row, action, { fetch, now });
+ if (result.autoCheck) {
+ checked += 1;
+ if (result.autoCheck.passed) passed += 1;
+ }
+ } catch (err) {
+ logger.warn({ err, taskId: row.id }, '[task-checks] check failed');
+ }
+ }
+ logger.info({ checked, passed }, '[task-checks] sweep done');
+ return { checked, passed };
+}
diff --git a/server/src/lib/action-center/task-checks.test.js b/server/src/lib/action-center/task-checks.test.js
new file mode 100644
index 000000000..7a4be556e
--- /dev/null
+++ b/server/src/lib/action-center/task-checks.test.js
@@ -0,0 +1,704 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Automatic checks (AC-010): a task checked `auto` read on its page, fetched
+ * again, by what it changes; passed, it is completed and History says so.
+ */
+
+let db;
+let ops;
+let reads;
+
+function table(name) {
+ const q = { op: 'select', filters: [], payload: null };
+ const run = () => {
+ if (q.op === 'select') {
+ reads.push({ table: name, filters: q.filters });
+ return { data: db[name] ?? [], error: null };
+ }
+ ops.push({ table: name, op: q.op, payload: q.payload, filters: q.filters });
+ if (q.op === 'update' && name === 'action_tasks') {
+ return { data: db.moved ? [] : [{ id: 't1' }], error: null };
+ }
+ return { data: null, error: null };
+ };
+ const filter =
+ (kind) =>
+ (...args) => (q.filters.push([kind, ...args]), chain);
+ const chain = {
+ select: () => chain,
+ eq: (col, value) => (q.filters.push([col, value]), chain),
+ in: filter('in'),
+ is: filter('is'),
+ not: filter('not'),
+ or: filter('or'),
+ order: filter('order'),
+ limit: () => chain,
+ maybeSingle: async () => {
+ reads.push({ table: name, filters: q.filters });
+ const row = db[name];
+ return { data: Array.isArray(row) ? (row[0] ?? null) : (row ?? null), error: null };
+ },
+ insert: (payload) => ((q.op = 'insert'), (q.payload = payload), chain),
+ update: (payload) => ((q.op = 'update'), (q.payload = payload), chain),
+ then: (resolve, reject) => Promise.resolve(run()).then(resolve, reject),
+ };
+ return chain;
+}
+
+vi.mock('../../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));
+vi.mock('../logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+
+const {
+ CHANGED_BELOW,
+ MIN_CHANGED_RUNS,
+ changedRuns,
+ checkKind,
+ checkPage,
+ pageAddress,
+ runTaskCheck,
+ similarity,
+ sketch,
+ sweepTaskChecks,
+ visibleText,
+} = await import('./task-checks.js');
+
+/**
+ * A fetch that answers each address with a page, or fails as the reader
+ * does; `{ redirect, html }` answers from another address.
+ */
+const fetchOf = (pages) =>
+ vi.fn(async (url) => {
+ const page = pages[url];
+ if (page === undefined) throw Object.assign(new Error('timeout'), { code: 'timeout' });
+ if (page === 'not_html') throw Object.assign(new Error('html'), { code: 'not_html' });
+ if (typeof page === 'number') {
+ throw Object.assign(new Error('http'), { code: 'http_error', status: page });
+ }
+ if (typeof page === 'object') return { url: page.redirect, status: 200, html: page.html };
+ return { url, status: 200, html: page };
+ });
+
+const PAGE = 'https://acme.example/pricing';
+const ROBOTS = 'https://acme.example/robots.txt';
+/** Words enough for a page to be read (MIN_WORDS), none a test looks for. */
+const FILLER = Array.from({ length: 24 }, (_, i) => `filler${i}`).join(' ');
+const html = (body, head = '') =>
+ `<html><head><title>Pricing</title>${head}</head><body><main><h1>Pricing</h1><p>${body}</p><p>${FILLER}</p></main></body></html>`;
+
+/** An essay of `n` words, word i reading `w{i}`, with `changes` swapped in at their places. */
+const essay = (n, changes = {}) =>
+ Array.from({ length: n }, (_, i) => changes[i] ?? `w${i}`).join(' ');
+
+beforeEach(() => {
+ db = {
+ brand_domains: [{ domain: 'acme.example' }],
+ action_tasks: [],
+ actions: null,
+ moved: false,
+ };
+ ops = [];
+ reads = [];
+});
+
+describe('checkKind', () => {
+ it('reads a library task by its key, a written one by its new text, only checked auto with a page', () => {
+ const auto = { check: 'auto', url: '/pricing' };
+ expect(checkKind({ task_key: 'publish_content', details: auto })).toBe('published');
+ expect(checkKind({ task_key: 'fix_broken_target', details: auto })).toBe('answers');
+ expect(checkKind({ task_key: 'fix_structured_data', details: auto })).toBe('structuredData');
+ expect(checkKind({ task_key: 'fix_crawler_access', details: auto })).toBe('crawlers');
+ expect(checkKind({ task_key: 'optimize_content', details: auto })).toBe('changed');
+ expect(checkKind({ task_key: null, details: { ...auto, change: { after: 'New FAQ' } } })).toBe(
+ 'text',
+ );
+ // A Site Audit task, a re-run, no page, no new text: no check here.
+ expect(checkKind({ task_key: 'fix_technical_issue', details: auto })).toBeNull();
+ expect(
+ checkKind({ task_key: 'validate_citations', details: { ...auto, check: 'rerun' } }),
+ ).toBeNull();
+ expect(checkKind({ task_key: 'publish_content', details: { check: 'auto' } })).toBeNull();
+ expect(checkKind({ task_key: null, details: auto })).toBeNull();
+ });
+
+ it('puts a path on the brand’s domain, and reads a bare host and path as https', () => {
+ expect(pageAddress('/pricing', 'acme.example')).toBe(PAGE);
+ expect(pageAddress('/pricing', 'www.acme.example')).toBe('https://www.acme.example/pricing');
+ expect(pageAddress(PAGE, null)).toBe(PAGE);
+ expect(pageAddress('acme.example/pricing', null)).toBe(PAGE);
+ expect(pageAddress('//acme.example/pricing', null)).toBe(PAGE);
+ expect(pageAddress('çiçek.com/x', null)).toBe(new URL('https://çiçek.com/x').href);
+ expect(pageAddress('/pricing', null)).toBeNull();
+ expect(pageAddress('pricing', 'acme.example')).toBeNull();
+ expect(pageAddress('the pricing page', 'acme.example')).toBeNull();
+ // A file's name isn't a domain.
+ expect(pageAddress('pricing.html', 'acme.example')).toBeNull();
+ });
+});
+
+describe('visibleText', () => {
+ it('reads the body’s own words, not its menus, footer, forms or furniture', () => {
+ const page = `<html><head><title>Pricing</title><meta name="description" content="Plans."></head>
+ <body><nav>Home Blog</nav><header>Logo</header><main><h1>Plans</h1><p>Start&nbsp;at $9</p>
+ <div class="related-posts">Read next</div><div id="shareButtons">Tweet</div></main>
+ <form><button>Buy</button></form><aside>Ad</aside><footer>© 2026</footer>
+ <script>var x = 1;</script></body></html>`;
+ const read = visibleText(page).replace(/\s+/g, ' ').trim();
+ expect(read).toBe('Pricing Plans. Plans Start at $9');
+ });
+
+ it('reads a block named as furniture, or a form, that holds most of the page', () => {
+ const article = `<html><body><nav>Home</nav><article class="post category-social-media tag-newsletter">
+ <h1>Social media plans</h1><p>${FILLER}</p></article><div class="share">Tweet</div></body></html>`;
+ const read = visibleText(article);
+ expect(read).toContain('Social media plans');
+ expect(read).not.toContain('Tweet');
+ const form = `<html><body><form id="aspnetForm"><h1>Plans</h1><p>${FILLER}</p></form></body></html>`;
+ expect(visibleText(form)).toContain('Plans');
+ });
+
+ it('reads a page nested ten thousand deep without running out of stack', () => {
+ const deep = `<html><body>${'<div>'.repeat(10_000)}deep words${'</div>'.repeat(10_000)}</body></html>`;
+ expect(visibleText(deep)).toContain('deep words');
+ });
+
+ it('ends a block’s words with it, before the text after it', () => {
+ const read = visibleText('<html><body><h2>Pricing</h2>Plans</body></html>');
+ expect(read.replace(/\s+/g, ' ').trim()).toBe('Pricing Plans');
+ });
+
+ it('reads blocks that each leave a different formatting element open in time', () => {
+ const blocks = Array.from({ length: 2_000 }, (_, i) => `<div><b c${i}>word${i}</div>`);
+ const page = `<html><body>${blocks.join('')}</body></html>`;
+ const started = Date.now();
+ expect(visibleText(page)).toContain('word1999');
+ expect(Date.now() - started).toBeLessThan(2_000);
+ });
+});
+
+describe('sketch and similarity', () => {
+ it('keep a page that moved a date, a count or a price near its first look, and one rewritten far', () => {
+ const first = sketch(essay(800));
+ expect(first.hashes.length).toBe(256);
+ expect(first.runs).toBe(797);
+ // A date, a reader count and a price moved.
+ const moved = sketch(essay(800, { 10: '2027', 300: 'readers512', 600: 'usd19' }));
+ expect(similarity(first.hashes, moved.hashes)).toBeGreaterThanOrEqual(CHANGED_BELOW);
+ expect(changedRuns(first, moved)).toBeLessThan(MIN_CHANGED_RUNS);
+ // A 150-word FAQ added.
+ const faq = sketch(
+ `${essay(800)} ${Array.from({ length: 150 }, (_, i) => `faq${i}`).join(' ')}`,
+ );
+ expect(similarity(first.hashes, faq.hashes)).toBeLessThan(CHANGED_BELOW);
+ expect(changedRuns(first, faq)).toBeGreaterThanOrEqual(MIN_CHANGED_RUNS);
+ // 40% rewritten.
+ const rewritten = sketch(
+ essay(800, Object.fromEntries(Array.from({ length: 320 }, (_, i) => [i * 2, `n${i}`]))),
+ );
+ expect(similarity(first.hashes, rewritten.hashes)).toBeLessThan(0.5);
+ expect(similarity(first.hashes, first.hashes)).toBe(1);
+ });
+
+ it('never call a short page changed by a number or two moving', () => {
+ // On a 60-word page one number is a large share of its runs, never MIN_CHANGED_RUNS of them.
+ const first = sketch(essay(60));
+ const moved = sketch(essay(60, { 30: '2027' }));
+ expect(similarity(first.hashes, moved.hashes)).toBeLessThan(CHANGED_BELOW);
+ expect(changedRuns(first, moved)).toBeLessThan(MIN_CHANGED_RUNS);
+ for (const n of [200, 400]) {
+ const a = sketch(essay(n));
+ const b = sketch(essay(n, { 5: '2027', [n - 10]: 'usd19', [Math.floor(n / 2)]: 'readers9' }));
+ expect(changedRuns(a, b)).toBeLessThan(MIN_CHANGED_RUNS);
+ }
+ });
+});
+
+describe('checkPage', () => {
+ it('passes a broken page that answers again; only "not there" is an answer', async () => {
+ const read = (page) => checkPage('answers', PAGE, { fetch: fetchOf({ [PAGE]: page }) });
+ expect(await read(html('x'))).toEqual({ passed: true, missing: [] });
+ for (const status of [404, 410]) {
+ expect(await read(status)).toEqual({
+ passed: false,
+ missing: ['page_error'],
+ wasMissing: true,
+ });
+ }
+ // Bot protection, a rate limit, a server error or no answer says nothing.
+ for (const status of [403, 429, 503]) expect(await read(status)).toBeNull();
+ expect(await checkPage('answers', PAGE, { fetch: fetchOf({}) })).toBeNull();
+ });
+
+ it('reads a page redirected off the brand’s site as off the site', async () => {
+ const fetch = fetchOf({ [PAGE]: { redirect: 'https://other.example/', html: html('x') } });
+ expect(await checkPage('answers', PAGE, { domains: ['acme.example'], fetch })).toEqual({
+ passed: false,
+ missing: ['off_site'],
+ });
+ });
+
+ it('passes a published page that was never there before, never one live once', async () => {
+ const missing = await checkPage('published', PAGE, { fetch: fetchOf({ [PAGE]: 404 }) });
+ const live = fetchOf({ [PAGE]: html(essay(300)) });
+ expect(
+ await checkPage('published', PAGE, { previous: { ...missing, url: PAGE }, fetch: live }),
+ ).toEqual({ passed: true, missing: [] });
+ // Live at the first look: kept, and passed once it changes.
+ const first = await checkPage('published', PAGE, { fetch: live });
+ expect(first).toMatchObject({ passed: false, missing: ['first_look'] });
+ // A live page that answered 404 once (a deploy) keeps its first look: no pass.
+ const flaky = { ...first, wasMissing: true, url: PAGE };
+ expect(await checkPage('published', PAGE, { previous: flaky, fetch: live })).toMatchObject({
+ passed: false,
+ missing: ['not_changed'],
+ });
+ });
+
+ it('passes structured data by the audit checks that raised it', async () => {
+ const ld = (json) => `<script type="application/ld+json">${json}</script>`;
+ const ORG = ld('{"@context":"https://schema.org","@type":"Organization","name":"Acme"}');
+ const FAQ = ld(
+ '{"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"a"},{"@type":"Question","name":"b"}]}',
+ );
+ const check = (head, auditChecks) =>
+ checkPage('structuredData', PAGE, {
+ auditChecks,
+ fetch: fetchOf({ [PAGE]: html('x', head) }),
+ });
+ // A FAQ schema fix isn't passed by the site's Organization block.
+ expect(await check(ORG, ['faq-schema'])).toEqual({
+ passed: false,
+ missing: ['no_faq_schema'],
+ });
+ expect(await check(`${ORG}${FAQ}`, ['faq-schema'])).toEqual({ passed: true, missing: [] });
+ // No checks named: the JSON-LD must be valid schema.org; {"foo":1} isn't.
+ expect(await check(ORG, [])).toEqual({ passed: true, missing: [] });
+ expect(await check(ld('{"foo":1}'), [])).toEqual({
+ passed: false,
+ missing: ['structured_data_invalid'],
+ });
+ expect(await check('', ['json-ld-presence', 'json-ld-validity'])).toEqual({
+ passed: false,
+ missing: ['no_structured_data', 'structured_data_invalid'],
+ });
+ });
+
+ it('asks validity for a pass, and relevance only not to fail', async () => {
+ const ld = (json) => `<script type="application/ld+json">${json}</script>`;
+ const ORG = ld('{"@context":"https://schema.org","@type":"Organization","name":"Acme"}');
+ const check = (head, auditChecks) =>
+ checkPage('structuredData', PAGE, {
+ auditChecks,
+ fetch: fetchOf({ [PAGE]: html('x', head) }),
+ });
+ // A good block beside one that doesn't parse: validity's warn, still open.
+ const broken = `${ORG}${ld('{"@type":"Product",')}`;
+ for (const auditChecks of [['json-ld-validity'], []]) {
+ expect(await check(broken, auditChecks)).toEqual({
+ passed: false,
+ missing: ['structured_data_invalid'],
+ });
+ }
+ expect(await check(ORG, ['json-ld-validity'])).toEqual({ passed: true, missing: [] });
+ // Types, none from the high-value list: relevance's warn, passed.
+ expect(await check(ORG, ['json-ld-relevance'])).toEqual({ passed: true, missing: [] });
+ });
+
+ it('reads robots.txt for the AI crawlers, and the page for noindex', async () => {
+ const check = (pages) => checkPage('crawlers', PAGE, { fetch: fetchOf(pages) });
+ const allowed = { passed: true, missing: [] };
+ expect(await check({ [PAGE]: html('x'), [ROBOTS]: 'User-agent: *\nDisallow: /admin' })).toEqual(
+ allowed,
+ );
+ // None (4xx), or a page served in its place: every crawler in.
+ expect(await check({ [PAGE]: html('x'), [ROBOTS]: 404 })).toEqual(allowed);
+ expect(await check({ [PAGE]: html('x'), [ROBOTS]: '<!DOCTYPE html><html>App</html>' })).toEqual(
+ allowed,
+ );
+ expect(
+ await check({
+ [PAGE]: html('x', '<meta name="robots" content="noindex, follow">'),
+ [ROBOTS]: 'User-agent: GPTBot\nDisallow: /',
+ }),
+ ).toEqual({ passed: false, missing: ['crawlers_blocked', 'noindex'] });
+ // Asked to wait, a server error, or no answer, says nothing.
+ expect(await check({ [PAGE]: html('x'), [ROBOTS]: 429 })).toBeNull();
+ expect(await check({ [PAGE]: html('x'), [ROBOTS]: 503 })).toBeNull();
+ expect(await check({ [PAGE]: html('x') })).toBeNull();
+ // Robots.txt read whatever its type (S3 serves it as octet-stream), at most 512 KB.
+ const fetch = fetchOf({ [PAGE]: html('x'), [ROBOTS]: '' });
+ await checkPage('crawlers', PAGE, { fetch });
+ const options = fetch.mock.calls[1][1];
+ expect(options).toMatchObject({ maxBytes: 512 * 1024, truncate: true });
+ expect(options.types.test('application/octet-stream')).toBe(true);
+ expect(options.types.test('')).toBe(true);
+ });
+
+ it('keeps the first look, passes a page rewritten, never one that changed by itself', async () => {
+ const look = (body, previous = null, head = '') =>
+ checkPage('changed', PAGE, { previous, fetch: fetchOf({ [PAGE]: html(body, head) }) });
+ const first = await look(essay(400));
+ expect(first).toMatchObject({ passed: false, missing: ['first_look'] });
+ expect(first.sketch.hashes).toHaveLength(256);
+ const kept = { ...first, url: PAGE };
+ // A date and a price moved, and a JSON-LD date: not changed, the first look kept.
+ const ld = '<script type="application/ld+json">{"dateModified":"2026-10-27"}</script>';
+ expect(await look(essay(400, { 3: '2027', 200: 'usd19' }), kept, ld)).toEqual({
+ passed: false,
+ missing: ['not_changed'],
+ sketch: first.sketch,
+ });
+ // Two thirds rewritten: passed.
+ const rewritten = essay(
+ 400,
+ Object.fromEntries(Array.from({ length: 270 }, (_, i) => [i, `new${i}`])),
+ );
+ expect((await look(rewritten, kept)).passed).toBe(true);
+ // A first look of another page (the URL edited since): a first look again.
+ expect(await look(rewritten, { ...kept, url: 'https://acme.example/old' })).toMatchObject({
+ missing: ['first_look'],
+ });
+ });
+
+ it('never passes a short page that changed by itself: a date and a price aren’t enough runs', async () => {
+ const look = (body, previous = null) =>
+ checkPage('changed', PAGE, { previous, fetch: fetchOf({ [PAGE]: html(body) }) });
+ const first = await look(essay(12));
+ const moved = await look(essay(12, { 3: '2027', 9: 'usd19' }), { ...first, url: PAGE });
+ // A large share of a short page's runs moved, but far fewer than MIN_CHANGED_RUNS.
+ expect(moved).toMatchObject({ passed: false, missing: ['not_changed'] });
+ });
+
+ it('reads a page with too few words as no answer: an empty shell, or bot protection’s', async () => {
+ const empty =
+ '<html><head><title>Just a moment</title></head><body><p>Checking your browser</p></body></html>';
+ expect(await checkPage('changed', PAGE, { fetch: fetchOf({ [PAGE]: empty }) })).toBeNull();
+ expect(
+ await checkPage('text', PAGE, { after: 'x', fetch: fetchOf({ [PAGE]: empty }) }),
+ ).toBeNull();
+ });
+
+ it('reads a page the reader turns away as nested too deep as no answer', async () => {
+ const fetch = vi.fn(async () => {
+ throw Object.assign(new Error('deep'), { code: 'too_deep' });
+ });
+ for (const kind of ['answers', 'changed', 'published', 'structuredData', 'crawlers']) {
+ expect(await checkPage(kind, PAGE, { fetch })).toBeNull();
+ }
+ expect(await checkPage('text', PAGE, { after: 'w1', fetch })).toBeNull();
+ // Nested as deep as real pages go, it's read.
+ const nested = `<html><body>${'<div>'.repeat(500)}<p>${essay(300)}</p>${'</div>'.repeat(500)}</body></html>`;
+ expect(await checkPage('changed', PAGE, { fetch: fetchOf({ [PAGE]: nested }) })).toMatchObject({
+ passed: false,
+ missing: ['first_look'],
+ });
+ });
+
+ it('finds a written task’s new text on the page, its entities read and whole words only', async () => {
+ const check = (after, body, head = '', before = null) =>
+ checkPage('text', PAGE, { after, before, fetch: fetchOf({ [PAGE]: html(body, head) }) });
+ expect(await check('plans start at $9 a month', 'Plans start at $9 a month.')).toEqual({
+ passed: true,
+ missing: [],
+ });
+ expect((await check('Tom & Jerry plans', 'Tom &amp; Jerry&nbsp;plans')).passed).toBe(true);
+ // A word inside another isn't it.
+ expect(await check('art', 'Start here')).toEqual({
+ passed: false,
+ missing: ['change_not_found'],
+ });
+ // The title and the meta description are read too.
+ expect(
+ (await check('Plans for teams', 'x', '<meta name="description" content="Plans for teams.">'))
+ .passed,
+ ).toBe(true);
+ });
+
+ it('passes a replacement only once the text it replaces is gone', async () => {
+ const check = (body) =>
+ checkPage('text', PAGE, {
+ after: 'Plans from $9',
+ before: 'Plans from $12',
+ fetch: fetchOf({ [PAGE]: html(body) }),
+ });
+ expect(await check('Plans from $9. Plans from $12.')).toEqual({
+ passed: false,
+ missing: ['old_text_still_there'],
+ });
+ expect(await check('Plans from $9.')).toEqual({ passed: true, missing: [] });
+ // New text that holds the old: an addition, passed.
+ const added = await checkPage('text', PAGE, {
+ after: 'Free shipping on every order',
+ before: 'Free shipping',
+ fetch: fetchOf({ [PAGE]: html('Free shipping on every order') }),
+ });
+ expect(added.passed).toBe(true);
+ });
+});
+
+describe('runTaskCheck', () => {
+ const action = { brand_id: 'b1' };
+ const task = (over = {}) => ({
+ id: 't1',
+ action_id: 'a1',
+ task_key: 'fix_broken_target',
+ title: null,
+ status: 'todo',
+ updated_at: '2026-10-26T10:00:00Z',
+ details: { check: 'auto', url: '/pricing', source: 'template' },
+ ...over,
+ });
+ const now = new Date('2026-10-27T03:00:00Z');
+ const at = now.toISOString();
+
+ it('completes a task that passes, keeps the check on it and tells History', async () => {
+ const fetch = fetchOf({ [PAGE]: html('x') });
+ const result = await runTaskCheck(task(), action, { fetch, now });
+ expect(result).toEqual({
+ autoCheck: { at, triedAt: at, url: PAGE, passed: true, missing: [] },
+ });
+ // A page read up to 512 KB.
+ expect(fetch.mock.calls[0][1]).toMatchObject({ maxBytes: 512 * 1024, truncate: true });
+ const update = ops.find((op) => op.table === 'action_tasks');
+ expect(update.payload).toMatchObject({
+ status: 'completed',
+ // The template's mark stays: a check is no one's edit.
+ details: { source: 'template', autoCheck: { passed: true } },
+ });
+ // Only if no one moved or edited it meanwhile.
+ expect(update.filters).toContainEqual(['status', 'todo']);
+ expect(update.filters).toContainEqual(['updated_at', '2026-10-26T10:00:00Z']);
+ expect(ops.find((op) => op.table === 'action_events').payload).toMatchObject({
+ action_id: 'a1',
+ event: 'task_checked',
+ data: { taskId: 't1', task: 'fix_broken_target' },
+ actor_id: null,
+ });
+ });
+
+ it('holds a task someone reopened: open, its checks kept, never closed again on that page', async () => {
+ const reopened = task({
+ details: {
+ check: 'auto',
+ url: '/pricing',
+ autoCheck: { at: 'x', url: PAGE, passed: true, missing: [] },
+ },
+ });
+ const result = await runTaskCheck(reopened, action, {
+ fetch: fetchOf({ [PAGE]: html('x') }),
+ now,
+ });
+ expect(result.autoCheck).toMatchObject({ passed: true, url: PAGE, held: true });
+ expect(ops.find((op) => op.table === 'action_tasks').payload).not.toHaveProperty('status');
+ expect(ops.some((op) => op.table === 'action_events')).toBe(false);
+ // A check that fails meanwhile keeps it held; one that passes again doesn't close it.
+ ops = [];
+ const failed = await runTaskCheck(
+ task({ details: { check: 'auto', url: '/pricing', autoCheck: result.autoCheck } }),
+ action,
+ { fetch: fetchOf({ [PAGE]: 404 }), now },
+ );
+ expect(failed.autoCheck).toMatchObject({ passed: false, held: true });
+ ops = [];
+ const again = await runTaskCheck(
+ task({ details: { check: 'auto', url: '/pricing', autoCheck: failed.autoCheck } }),
+ action,
+ { fetch: fetchOf({ [PAGE]: html('x') }), now },
+ );
+ expect(again.autoCheck).toMatchObject({ passed: true, held: true });
+ expect(ops.find((op) => op.table === 'action_tasks').payload).not.toHaveProperty('status');
+ // Its URL edited since: a new page, checked as one.
+ ops = [];
+ await runTaskCheck(
+ task({ details: { check: 'auto', url: '/plans', autoCheck: again.autoCheck } }),
+ action,
+ { fetch: fetchOf({ 'https://acme.example/plans': html('x') }), now },
+ );
+ expect(ops.find((op) => op.table === 'action_tasks').payload.status).toBe('completed');
+ });
+
+ it('reads only the brand’s own pages', async () => {
+ const fetch = fetchOf({ 'https://other.example/pricing': html('x') });
+ const result = await runTaskCheck(
+ task({ details: { check: 'auto', url: 'https://other.example/pricing' } }),
+ action,
+ { fetch, now },
+ );
+ expect(result.autoCheck).toMatchObject({ passed: false, missing: ['off_site'] });
+ expect(fetch).not.toHaveBeenCalled();
+ // A bare host on the brand's site is read, as https.
+ const own = fetchOf({ [PAGE]: html('x') });
+ await runTaskCheck(task({ details: { check: 'auto', url: 'acme.example/pricing' } }), action, {
+ fetch: own,
+ now,
+ });
+ expect(own).toHaveBeenCalledWith(PAGE, expect.anything());
+ });
+
+ it('puts a path on the brand’s stored host, www kept', async () => {
+ db.brand_domains = [{ domain: 'https://www.acme.example/' }];
+ const fetch = fetchOf({ 'https://www.acme.example/pricing': html('x') });
+ expect((await runTaskCheck(task(), action, { fetch, now })).autoCheck.passed).toBe(true);
+ });
+
+ it('checks structured data by the checks its page failed, and a crawler fix only from the audit', async () => {
+ db.actions = { targets: [{ id: PAGE, checks: ['faq-schema'] }] };
+ const fix = task({ task_key: 'fix_structured_data' });
+ const result = await runTaskCheck(fix, action, { fetch: fetchOf({ [PAGE]: html('x') }), now });
+ expect(result.autoCheck.missing).toEqual(['no_faq_schema']);
+ expect(reads.find((r) => r.table === 'actions').filters).toContainEqual(['id', 'a1']);
+ // The target's address written another way is the same page.
+ db.actions = {
+ targets: [
+ { id: 'http://www.acme.example/pricing/', checks: ['json-ld-presence'] },
+ { id: 'https://acme.example/other', checks: ['faq-schema'] },
+ ],
+ };
+ const other = await runTaskCheck(fix, action, { fetch: fetchOf({ [PAGE]: html('x') }), now });
+ expect(other.autoCheck.missing).toEqual(['no_structured_data']);
+ // No target for the page: every target's checks, the stricter side.
+ db.actions = {
+ targets: [
+ { id: 'https://acme.example/a', checks: ['json-ld-presence'] },
+ { id: 'https://acme.example/b', checks: ['faq-schema'] },
+ ],
+ };
+ const none = await runTaskCheck(fix, action, { fetch: fetchOf({ [PAGE]: html('x') }), now });
+ expect(none.autoCheck.missing).toEqual(['no_structured_data', 'no_faq_schema']);
+ // From the bot logs (a cited page crawlers never read): not checked here, its try kept.
+ db.actions = { targets: [{ id: PAGE, checks: [] }] };
+ const crawl = task({ task_key: 'fix_crawler_access' });
+ const fetch = fetchOf({ [PAGE]: html('x') });
+ ops = [];
+ expect(await runTaskCheck(crawl, action, { fetch, now })).toEqual({
+ reason: 'not_checkable',
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ expect(ops.find((op) => op.table === 'action_tasks').payload.details.autoCheck).toEqual({
+ triedAt: at,
+ });
+ db.actions = { targets: [{ id: PAGE, checks: ['ai-bot-access'] }] };
+ expect(
+ (
+ await runTaskCheck(crawl, action, {
+ fetch: fetchOf({ [PAGE]: html('x'), [ROBOTS]: 404 }),
+ now,
+ })
+ ).autoCheck.passed,
+ ).toBe(true);
+ });
+
+ it('keeps what is missing on a task that fails, and its first look through a 404', async () => {
+ const changed = task({
+ task_key: 'optimize_content',
+ details: {
+ check: 'auto',
+ url: '/pricing',
+ autoCheck: {
+ at: 'x',
+ url: PAGE,
+ sketch: { hashes: ['aa'], runs: 1 },
+ passed: false,
+ missing: [],
+ },
+ },
+ });
+ const result = await runTaskCheck(changed, action, { fetch: fetchOf({ [PAGE]: 404 }), now });
+ expect(result.autoCheck).toMatchObject({
+ passed: false,
+ missing: ['page_error'],
+ sketch: { hashes: ['aa'], runs: 1 },
+ });
+ const update = ops.find((op) => op.table === 'action_tasks');
+ expect(update.payload).not.toHaveProperty('status');
+ expect(ops.some((op) => op.table === 'action_events')).toBe(false);
+ // Another page's first look isn't kept for this one.
+ ops = [];
+ const moved = await runTaskCheck(
+ task({
+ task_key: 'optimize_content',
+ details: { ...changed.details, url: '/plans' },
+ }),
+ action,
+ { fetch: fetchOf({ 'https://acme.example/plans': 404 }), now },
+ );
+ expect(moved.autoCheck).not.toHaveProperty('sketch');
+ });
+
+ it('keeps only the try when the page can’t be read', async () => {
+ const tried = task({
+ details: {
+ check: 'auto',
+ url: '/pricing',
+ autoCheck: { at: 'x', passed: false, missing: ['page_error'] },
+ },
+ });
+ expect(await runTaskCheck(tried, action, { fetch: fetchOf({}), now })).toEqual({
+ reason: 'no_answer',
+ });
+ expect(ops.find((op) => op.table === 'action_tasks').payload.details.autoCheck).toEqual({
+ at: 'x',
+ passed: false,
+ missing: ['page_error'],
+ triedAt: at,
+ });
+ });
+
+ it('says why nothing was checked: no check here, done, or changed meanwhile', async () => {
+ const fetch = fetchOf({ [PAGE]: html('x') });
+ expect(
+ await runTaskCheck(task({ task_key: 'fix_technical_issue' }), action, { fetch }),
+ ).toEqual({ reason: 'not_checkable' });
+ expect(await runTaskCheck(task({ status: 'completed' }), action, { fetch })).toEqual({
+ reason: 'not_open',
+ });
+ db.moved = true;
+ expect(await runTaskCheck(task(), action, { fetch })).toEqual({ reason: 'changed' });
+ expect(ops.some((op) => op.table === 'action_events')).toBe(false);
+ });
+});
+
+describe('sweepTaskChecks', () => {
+ const now = new Date('2026-10-27T03:00:00Z');
+ const row = (id, over = {}) => ({
+ id,
+ action_id: 'a1',
+ task_key: 'fix_broken_target',
+ title: null,
+ status: 'todo',
+ updated_at: 'u',
+ details: { check: 'auto', url: PAGE },
+ actions: { brand_id: 'b1', status: 'new', deleted_at: null },
+ ...over,
+ });
+
+ it('reads only tasks it can check, the least recently tried first', async () => {
+ await sweepTaskChecks({ fetch: fetchOf({}), now });
+ const filters = reads.find((r) => r.table === 'action_tasks').filters;
+ expect(filters).toContainEqual(['not', 'details->>url', 'is', null]);
+ expect(filters).toContainEqual([
+ 'or',
+ expect.stringContaining('task_key.in.(publish_content,fix_broken_target'),
+ ]);
+ expect(filters).toContainEqual([
+ 'order',
+ 'details->autoCheck->>triedAt',
+ { ascending: true, nullsFirst: true },
+ ]);
+ // A held task (reopened after it passed) is left to the person.
+ expect(filters).toContainEqual(['is', 'details->autoCheck->>held', null]);
+ });
+
+ it('checks the open tasks not tried in the last day, one at a time', async () => {
+ db.action_tasks = [
+ row('t1'),
+ // Tried an hour ago: not again tonight.
+ row('t2', {
+ details: { check: 'auto', url: PAGE, autoCheck: { triedAt: '2026-10-27T02:00:00Z' } },
+ }),
+ ];
+ const fetch = fetchOf({ [PAGE]: html('x') });
+ expect(await sweepTaskChecks({ fetch, now })).toEqual({ checked: 1, passed: 1 });
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/src/lib/action-center/task-send.js b/server/src/lib/action-center/task-send.js
index 345a8f46b..b9ffadb79 100644
--- a/server/src/lib/action-center/task-send.js
+++ b/server/src/lib/action-center/task-send.js
@@ -54,7 +54,7 @@ const changeOf = (value) => {
export async function loadTask(taskId) {
const { data: task, error } = await supabaseAdmin
.from('action_tasks')
- .select('id, action_id, task_key, title, status, details')
+ .select('id, action_id, task_key, title, status, details, updated_at')
.eq('id', taskId)
.maybeSingle();
if (error) throw new Error(error.message);
@@ -62,7 +62,7 @@ export async function loadTask(taskId) {
const { data: action, error: actionError } = await supabaseAdmin
.from('actions')
.select(
- 'id, action_no, brand_id, kind, category, impact, status, priority_score, priority_level',
+ 'id, action_no, brand_id, kind, category, impact, status, priority_score, priority_level, deleted_at',
)
.eq('id', task.action_id)
.single();
diff --git a/server/src/lib/page-content.js b/server/src/lib/page-content.js
index 30b767b5c..939fe9627 100644
--- a/server/src/lib/page-content.js
+++ b/server/src/lib/page-content.js
@@ -159,16 +159,29 @@ function clean(text) {
return (text ?? '').replace(/\s+/g, ' ').trim();
}
-/** A block's class and id, as lower-case words: "authorBox ans-trk__i" → author, box, ans, trk, i. */
-function wordsOf($el) {
- const names = `${$el.attr('class') ?? ''} ${$el.attr('id') ?? ''}`;
- return names
+/** A class and id, as lower-case words: "authorBox ans-trk__i" → author, box, ans, trk, i. */
+function nameWords(className, id) {
+ return `${className ?? ''} ${id ?? ''}`
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.toLowerCase()
.split(/[^a-z0-9]+/)
.filter(Boolean);
}
+/** A block's class and id, as lower-case words. */
+function wordsOf($el) {
+ return nameWords($el.attr('class'), $el.attr('id'));
+}
+
+/**
+ * Whether an element's class or id names furniture anywhere on a page
+ * (author box, share buttons, related posts, ads…), from its attributes:
+ * the Action Center's page checks read a page's words without it.
+ */
+export function furnitureNamed(attribs = {}) {
+ return nameWords(attribs.class, attribs.id).some((word) => FURNITURE_WORDS.has(word));
+}
+
function named($el, words) {
return wordsOf($el).some((word) => words.has(word));
}
diff --git a/server/src/routes/action-center-tasks.test.js b/server/src/routes/action-center-tasks.test.js
index 5da00a59f..253bbf652 100644
--- a/server/src/routes/action-center-tasks.test.js
+++ b/server/src/routes/action-center-tasks.test.js
@@ -56,7 +56,12 @@ vi.mock('../lib/action-center/task-send.js', () => ({
sendTaskToWebhook: (...args) => sendTaskToWebhook(...args),
}));
-const { regenerateTasks, sendTask } = await import('./action-center.js');
+const runTaskCheck = vi.fn();
+vi.mock('../lib/action-center/task-checks.js', () => ({
+ runTaskCheck: (...args) => runTaskCheck(...args),
+}));
+
+const { checkTaskNow, regenerateTasks, sendTask } = await import('./action-center.js');
beforeEach(() => {
enabled = true;
@@ -122,6 +127,45 @@ describe('regenerateTasks', () => {
});
});
+describe('checkTaskNow', () => {
+ beforeEach(() => {
+ loadTask
+ .mockReset()
+ .mockResolvedValue({ task: { id: 't1' }, action: { brand_id: 'b1', status: 'new' } });
+ runTaskCheck
+ .mockReset()
+ .mockResolvedValue({ autoCheck: { at: 'x', passed: true, missing: [] } });
+ });
+
+ it("checks the caller's access to the task's brand, then the task (AC-010)", async () => {
+ assertBrandAccess.mockRejectedValueOnce(Object.assign(new Error('Forbidden'), { status: 403 }));
+ await expect(checkTaskNow('t1', 'u1')).rejects.toThrow('Forbidden');
+ expect(runTaskCheck).not.toHaveBeenCalled();
+ expect(await checkTaskNow('t1', 'u1')).toEqual({
+ checked: { at: 'x', passed: true, missing: [] },
+ reason: null,
+ });
+ expect(runTaskCheck).toHaveBeenCalledWith({ id: 't1' }, { brand_id: 'b1', status: 'new' });
+ // Nothing checked: why.
+ runTaskCheck.mockResolvedValueOnce({ reason: 'not_checkable' });
+ expect(await checkTaskNow('t1', 'u1')).toEqual({ checked: null, reason: 'not_checkable' });
+ });
+
+ it('checks nothing on a closed or deleted action', async () => {
+ loadTask.mockResolvedValueOnce({
+ task: { id: 't1' },
+ action: { brand_id: 'b1', status: 'completed' },
+ });
+ expect(await checkTaskNow('t1', 'u1')).toEqual({ checked: null, reason: 'closed' });
+ loadTask.mockResolvedValueOnce({
+ task: { id: 't1' },
+ action: { brand_id: 'b1', status: 'new', deleted_at: '2026-10-26' },
+ });
+ expect(await checkTaskNow('t1', 'u1')).toEqual({ checked: null, reason: 'closed' });
+ expect(runTaskCheck).not.toHaveBeenCalled();
+ });
+});
+
describe('sendTask', () => {
beforeEach(() => {
loadTask.mockReset().mockResolvedValue({ task: { id: 't1' }, action: { brand_id: 'b1' } });
diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.js
index 8a25f9815..1d4f6a96e 100644
--- a/server/src/routes/action-center.js
+++ b/server/src/routes/action-center.js
@@ -21,6 +21,8 @@ import {
sendTrafficPagesToActionCenter,
} from '../lib/action-center/from-traffic-pages.js';
import { sendContentDraftToActionCenter } from '../lib/action-center/from-content-draft.js';
+import { runTaskCheck } from '../lib/action-center/task-checks.js';
+import { pageReadLimiter } from '../middleware/rate-limiter.js';
const router = Router();
@@ -228,6 +230,38 @@ router.post('/tasks/:id/send', async (req, res) => {
}
});
+/**
+ * Checks a task now (AC-010), as the nightly sweep does: its page fetched
+ * again by what the task changes. Returns the check kept on the task, or
+ * `checked: null` with why nothing was checked (runTaskCheck's reasons, and
+ * 'closed' for a closed or deleted action).
+ */
+export async function checkTaskNow(taskId, userId) {
+ const { task, action } = await loadTask(taskId);
+ await assertBrandAccess(action.brand_id, userId);
+ if (action.deleted_at || ['completed', 'dismissed'].includes(action.status)) {
+ return { checked: null, reason: 'closed' };
+ }
+ const result = await runTaskCheck(task, action);
+ return { checked: result.autoCheck ?? null, reason: result.reason ?? null };
+}
+
+/** POST /api/action-center/tasks/:id/check */
+router.post('/tasks/:id/check', pageReadLimiter, async (req, res) => {
+ const id = signalIdSchema.safeParse(req.params.id);
+ if (!id.success) return res.status(400).json({ error: 'Invalid task id' });
+ try {
+ return res.json(await checkTaskNow(id.data, req.user.id));
+ } catch (error) {
+ const status = error.status;
+ if (!status) req.log.error({ err: error }, 'check action task error');
+ return res.status(status || 500).json({
+ error: status ? error.message : 'Failed to check the task.',
+ code: error instanceof TaskSendError ? error.code : null,
+ });
+ }
+});
+
const trafficPagesSchema = z.object({
// guid, not uuid: seeded ids aren't RFC 4122 versions.
brandId: z.guid(),
diff --git a/server/src/server.js b/server/src/server.js
index dd784c5ed..1742c3447 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -51,6 +51,7 @@ import { runPulseCatchUp } from './lib/pulse/engine.js';
import { runSignalCatchUp } from './lib/signals/pass.js';
import { sweepTaskExecution } from './lib/action-center/execution/run.js';
import { sweepActionTasks } from './lib/action-center/task-writer/index.js';
+import { sweepTaskChecks } from './lib/action-center/task-checks.js';
import { sendHealthReport } from './lib/health/report.js';
import { checkPromptUsageCounters } from './lib/prompt-usage-counters.js';
@@ -182,6 +183,13 @@ async function runDailyTracking() {
logger.error({ err }, '[task-writer] daily sweep crashed');
});
+ // Check the open tasks checked `auto` on their pages (AC-010): a page
+ // fetched again with the free reader, one at a time, bounded per night. A
+ // task that passes is completed. Fire-and-forget like the rest.
+ sweepTaskChecks().catch((err) => {
+ logger.error({ err }, '[task-checks] daily sweep crashed');
+ });
+
// Insights rollup backstop (00066). Re-refreshes the trailing days for
// every brand, so days whose run never stamped (partial, crashed) and
// out-of-run writes (a prompt analyzed right after being added) appear the
diff --git a/web/messages/en.json b/web/messages/en.json
index 270416616..96cc00403 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1280,6 +1280,7 @@
"task_edited": "Task edited",
"tasks_generated": "{count, plural, one {# task} other {# tasks}} written from the action's evidence{reviews, plural, =0 {} one {; # waits for review} other {; # wait for review}}",
"task_sent": "{to, select, content {Sent to Content} webhook {Sent to the webhook} other {Sent}}: {title}",
+ "task_checked": "Checked automatically and done: {task}{title}",
"task_ran": "{task} — carried out automatically ({tool})",
"task_run_failed": "{task} — the automatic attempt failed; it needs doing by hand",
"task_awaiting_approval": "{task} — waiting for your approval before it reaches outside Ansvisor",
@@ -1352,6 +1353,21 @@
"doneWhen": "Done when",
"check": "How we check",
"noCheck": "Not set",
+ "lastCheck": "Last check",
+ "checkedPassed": "Checked {date} · passed",
+ "checkedMissing": "Checked {date} · {missing}",
+ "checkNow": "Check now",
+ "checking": "Checking…",
+ "checkPassed": "Checked: done. The task is completed.",
+ "checkMissing": "Checked: {missing}",
+ "checkNot": {
+ "not_checkable": "This task isn't checked on its page: a Site Audit fix is checked by your next audit.",
+ "not_open": "This task is already done or skipped.",
+ "no_answer": "Couldn't read the page. Try again later.",
+ "changed": "The task changed while it was checked. Try again.",
+ "closed": "This action is closed."
+ },
+ "checkFailed": "Couldn't check the task. Try again.",
"type": "Type",
"noType": "No type",
"effort": "Effort",
@@ -2445,6 +2461,20 @@
"validate_gsc": "Search Console clicks in the window are above their baseline",
"validate_ga4": "Key events in the window are above their baseline"
},
+ "taskCheckMissing": {
+ "page_error": "the page didn't open",
+ "no_structured_data": "no structured data on the page",
+ "structured_data_invalid": "the structured data isn't valid schema.org JSON-LD",
+ "structured_data_irrelevant": "the structured data has no type that describes the page",
+ "no_faq_schema": "no FAQ schema with at least two questions",
+ "crawlers_blocked": "robots.txt blocks AI crawlers",
+ "noindex": "the page asks not to be indexed",
+ "first_look": "first look kept: it passes once the page changes",
+ "not_changed": "the page hasn't changed since the first look",
+ "change_not_found": "the new text isn't on the page",
+ "old_text_still_there": "the text it replaces is still on the page",
+ "off_site": "the page isn't on the brand's site"
+ },
"taskChecks": {
"auto": "Automatic: we fetch the page again",
"rerun": "Re-run: the prompts run again",
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index f01605eaf..ef7ac7992 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -79,9 +79,12 @@ import {
TaskDetailView,
TaskTypeBadge,
type TaskDraftWork,
+ type TaskCheckOptions,
type TaskSendOptions,
+ useMissingText,
} from './task-detail';
import { hasActiveWebhook, sendActionTask } from '@/lib/actions/action-task-send';
+import { checkActionTask } from '@/lib/actions/action-task-check';
import { getActionDrafts, startDraftFromAction } from '@/lib/actions/content-drafts';
import { actionPages, draftMethodForTask, type ActionDraft } from '@/lib/content/action-drafts';
import { contentEditorPath } from '@/lib/content/drafts';
@@ -148,6 +151,10 @@ export function ActionDrawer({
const [detail, setDetail] = useState<ActionDetail | null>(null);
const [isBusy, setIsBusy] = useState(false);
const tSend = useTranslations('actionCenter.actionsPage.drawer.send');
+ // Check now (AC-010): the task being checked, and the card's words.
+ const tTaskCard = useTranslations('actionCenter.actionsPage.drawer.task');
+ const missingText = useMissingText();
+ const [checking, setChecking] = useState<string | null>(null);
// The drafts written for the action's writing tasks (CE-022), once read.
const [drafts, setDrafts] = useState<ActionDraft[]>([]);
@@ -285,6 +292,28 @@ export function ActionDrawer({
}
};
+ /**
+ * Check a task on its page now (AC-010), as the nightly sweep does: done,
+ * it's completed; else the card says what is missing. Then reload.
+ */
+ const checkTask = async (taskId: string) => {
+ setChecking(taskId);
+ try {
+ const result = await checkActionTask(taskId);
+ if ('error' in result) {
+ toast.error(tTaskCard('checkFailed'));
+ return;
+ }
+ if (!result.checked) toast(tTaskCard(`checkNot.${result.reason ?? 'no_answer'}`));
+ else if (result.checked.passed) toast.success(tTaskCard('checkPassed'));
+ else toast(tTaskCard('checkMissing', { missing: missingText(result.checked.missing) }));
+ await load();
+ onChanged();
+ } finally {
+ setChecking(null);
+ }
+ };
+
/**
* Create content / Optimize page (CE-022): the draft for the task's work,
* linked to the action, opened in the Content Editor.
@@ -697,6 +726,14 @@ export function ActionDrawer({
webhook: webhookReady,
onSend: (to) => void sendTask(task.id, taskText(task, tTasks), to),
}}
+ // An open task checked automatically, with its page (AC-010).
+ check={
+ (task.status === 'todo' || task.status === 'in_progress') &&
+ task.details?.check === 'auto' &&
+ task.details.url
+ ? { onCheck: () => void checkTask(task.id), busy: checking === task.id }
+ : undefined
+ }
draftWork={draftWork}
/>
);
@@ -817,6 +854,7 @@ function TaskRow({
onEdit,
onDelete,
send,
+ check,
draftWork,
}: {
task: ActionTask;
@@ -829,6 +867,8 @@ function TaskRow({
onEdit: (edit: TaskDetailsEdit & { title: string | null }) => Promise<boolean>;
onDelete: () => void;
send: TaskSendOptions;
+ /** Check now, for an open task checked automatically (AC-010). */
+ check?: TaskCheckOptions;
draftWork?: TaskDraftWork;
}) {
// A task sent from the Improve tab opens on its suggestion, as it always
@@ -936,6 +976,7 @@ function TaskRow({
disabled={disabled || skipDraft !== null}
onEdit={() => setEditing(true)}
send={send}
+ check={check}
draftWork={draftWork}
/>
))}
diff --git a/web/src/components/action-center/task-detail.test.tsx b/web/src/components/action-center/task-detail.test.tsx
index 208316e89..4717bab19 100644
--- a/web/src/components/action-center/task-detail.test.tsx
+++ b/web/src/components/action-center/task-detail.test.tsx
@@ -129,6 +129,47 @@ describe('TaskDetailView', () => {
expect(container.textContent).not.toContain('Before:');
});
+ it('shows the last automatic check, and checks now on a click (AC-010)', () => {
+ const onCheck = vi.fn();
+ render(
+ <TaskDetailView
+ details={parseTaskDetails({
+ url: '/pricing',
+ check: 'auto',
+ autoCheck: {
+ at: '2026-10-22T03:00:00Z',
+ passed: false,
+ missing: ['crawlers_blocked', 'noindex'],
+ },
+ })}
+ disabled={false}
+ onEdit={() => {}}
+ check={{ onCheck, busy: false }}
+ />,
+ );
+ expect(container.textContent).toContain(
+ 'Checked Oct 22 · robots.txt blocks AI crawlers, the page asks not to be indexed',
+ );
+ act(() => button('Check now').click());
+ expect(onCheck).toHaveBeenCalled();
+ });
+
+ it('says a passed check, and offers no Check now for a task checked otherwise', () => {
+ render(
+ <TaskDetailView
+ details={parseTaskDetails({
+ check: 'rerun',
+ autoCheck: { at: '2026-10-22T03:00:00Z', passed: true, missing: [] },
+ })}
+ disabled={false}
+ onEdit={() => {}}
+ check={{ onCheck: () => {}, busy: false }}
+ />,
+ );
+ expect(container.textContent).toContain('Checked Oct 22 · passed');
+ expect(button('Check now')).toBeUndefined();
+ });
+
it('asks for details when a task has none, and opens the editor', () => {
const onEdit = vi.fn();
render(<TaskDetailView details={null} disabled={false} onEdit={onEdit} />);
diff --git a/web/src/components/action-center/task-detail.tsx b/web/src/components/action-center/task-detail.tsx
index af6cbe4e1..e6ccd60b7 100644
--- a/web/src/components/action-center/task-detail.tsx
+++ b/web/src/components/action-center/task-detail.tsx
@@ -52,6 +52,13 @@ export interface TaskSendOptions {
onSend: (to: 'content' | 'webhook') => void;
}
+/** Checking a task on its page now (AC-010), for a task checked automatically. */
+export interface TaskCheckOptions {
+ onCheck: () => void;
+ /** A check is under way. */
+ busy: boolean;
+}
+
/** A writing task's work in the Content Editor (CE-022), and starting it. */
export interface TaskDraftWork {
method: DraftMethod;
@@ -125,6 +132,7 @@ export function TaskDetailView({
onEdit,
send,
draftWork,
+ check,
}: {
details: ActionTaskDetails | null;
disabled: boolean;
@@ -132,9 +140,13 @@ export function TaskDetailView({
send?: TaskSendOptions;
/** A writing task's draft (CE-022). */
draftWork?: TaskDraftWork;
+ /** Check now, for a task checked automatically (AC-010). */
+ check?: TaskCheckOptions;
}) {
const t = useTranslations('actionCenter.actionsPage.drawer.task');
const tChecks = useTranslations('actionCenter.taskChecks');
+ const missingText = useMissingText();
+ const lastCheck = details?.lastCheck ?? null;
const format = useFormatter();
const effort = [details?.effort, details?.role].filter(Boolean).join(' · ');
const sentContent = details?.sent.content ?? null;
@@ -216,6 +228,19 @@ export function TaskDetailView({
)}
{details.doneWhen && <Field label={t('doneWhen')}>{details.doneWhen}</Field>}
{details.check && <Field label={t('check')}>{tChecks(details.check)}</Field>}
+ {lastCheck && (
+ <Field label={t('lastCheck')}>
+ {(() => {
+ const date = format.dateTime(new Date(lastCheck.at), {
+ month: 'short',
+ day: 'numeric',
+ });
+ return lastCheck.passed
+ ? t('checkedPassed', { date })
+ : t('checkedMissing', { date, missing: missingText(lastCheck.missing) });
+ })()}
+ </Field>
+ )}
{effort && <Field label={t('effort')}>{effort}</Field>}
</dl>
) : (
@@ -261,6 +286,18 @@ export function TaskDetailView({
>
{t('edit')}
</Button>
+ {check && details?.check === 'auto' && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled || check.busy}
+ onClick={check.onCheck}
+ className="h-7 text-xs"
+ >
+ {check.busy ? t('checking') : t('checkNow')}
+ </Button>
+ )}
{/* A writing task is written in the Content Editor: Create content / Optimize page. */}
{send?.content && !sentContent && !draftWork && (
<Button
@@ -291,6 +328,13 @@ export function TaskDetailView({
);
}
+/** What an automatic check found missing (AC-010), in words: "the page didn't open, …". */
+export function useMissingText() {
+ const tMissing = useTranslations('actionCenter.taskCheckMissing');
+ return (codes: string[]) =>
+ codes.map((code) => (tMissing.has(code) ? tMissing(code) : code)).join(', ');
+}
+
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<>
diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.ts
index 76fbbd05c..d331b4c17 100644
--- a/web/src/lib/action-center/display.test.ts
+++ b/web/src/lib/action-center/display.test.ts
@@ -463,6 +463,13 @@ describe('History events', () => {
);
});
+ /** A task its automatic check closed, named as the drawer names it (AC-010). */
+ it('says a task passed its automatic check', () => {
+ expect(eventText('task_checked', { task: 'Refresh outdated content', title: '' })).toBe(
+ 'Checked automatically and done: Refresh outdated content',
+ );
+ });
+
/** The validation sweep records one of four verdicts, and each reads in
* words — "after this action closed", never "because of it". */
it.each([
diff --git a/web/src/lib/action-center/export.test.ts b/web/src/lib/action-center/export.test.ts
index d52eb79c0..efc8c6f18 100644
--- a/web/src/lib/action-center/export.test.ts
+++ b/web/src/lib/action-center/export.test.ts
@@ -439,6 +439,7 @@ describe('a task with AC-004 fields', () => {
effort: '~2h',
role: 'Content writer',
sent: { content: null, webhook: null },
+ lastCheck: null,
},
},
],
diff --git a/web/src/lib/action-center/task-details.test.ts b/web/src/lib/action-center/task-details.test.ts
index 89d6b237a..05bf0ebd3 100644
--- a/web/src/lib/action-center/task-details.test.ts
+++ b/web/src/lib/action-center/task-details.test.ts
@@ -24,6 +24,7 @@ const empty = {
effort: null,
role: null,
sent: { content: null, webhook: null },
+ lastCheck: null,
};
describe('parseTaskDetails', () => {
@@ -107,6 +108,19 @@ describe('parseTaskDetails', () => {
});
});
+describe('the last automatic check (AC-010)', () => {
+ it('reads what the server kept, and nothing malformed', () => {
+ expect(
+ parseTaskDetails({
+ check: 'auto',
+ autoCheck: { at: '2026-10-27T03:00:00Z', passed: false, missing: ['page_error', 7] },
+ })?.lastCheck,
+ ).toEqual({ at: '2026-10-27T03:00:00Z', passed: false, missing: ['page_error'] });
+ expect(parseTaskDetails({ check: 'auto', autoCheck: { at: 'x' } })?.lastCheck).toBeNull();
+ expect(parseTaskDetails({ check: 'auto', autoCheck: 'passed' })?.lastCheck).toBeNull();
+ });
+});
+
describe('withTemplateDoneWhen', () => {
const doneWhenOf = (key: string) => (key === 'refresh_content' ? 'Refreshed and live' : null);
diff --git a/web/src/lib/action-center/task-details.ts b/web/src/lib/action-center/task-details.ts
index cd5d1f05b..4094224a7 100644
--- a/web/src/lib/action-center/task-details.ts
+++ b/web/src/lib/action-center/task-details.ts
@@ -51,6 +51,16 @@ export interface ActionTaskDetails {
role: string | null;
/** Where the task was sent (AC-004): the Content opportunity it became, the webhook. */
sent: TaskSent;
+ /** Its last automatic check (AC-010): when, whether it passed, and what was missing. */
+ lastCheck: TaskLastCheck | null;
+}
+
+/** What an automatic check (AC-010) found, as the server keeps it (task-checks.js). */
+export interface TaskLastCheck {
+ at: string;
+ passed: boolean;
+ /** Codes, worded by en.json actionCenter.taskCheckMissing. */
+ missing: string[];
}
export interface TaskSent {
@@ -143,6 +153,7 @@ export function parseTaskDetails(raw: unknown): ActionTaskDetails | null {
: null,
webhook: text(webhook.at) ? { at: text(webhook.at)! } : null,
},
+ lastCheck: parseLastCheck(r.autoCheck),
};
return hasTaskDetails(details) ? details : null;
}
@@ -179,6 +190,17 @@ export function withoutTemplateDoneWhen<T extends TaskDetailsEdit>(
return template && edit.doneWhen.trim() === template ? { ...edit, doneWhen: '' } : edit;
}
+function parseLastCheck(raw: unknown): TaskLastCheck | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const c = raw as Record<string, unknown>;
+ const at = text(c.at);
+ if (!at || typeof c.passed !== 'boolean') return null;
+ const missing = Array.isArray(c.missing)
+ ? c.missing.filter((code): code is string => typeof code === 'string' && code.length > 0)
+ : [];
+ return { at, passed: c.passed, missing };
+}
+
/** Whether any field says something. */
export function hasTaskDetails(details: ActionTaskDetails): boolean {
return (
@@ -187,6 +209,7 @@ export function hasTaskDetails(details: ActionTaskDetails): boolean {
details.sources.length > 0 ||
details.sent.content !== null ||
details.sent.webhook !== null ||
+ details.lastCheck !== null ||
hasTaskSpec(details)
);
}
diff --git a/web/src/lib/actions/action-task-check.test.ts b/web/src/lib/actions/action-task-check.test.ts
new file mode 100644
index 000000000..1fa59b4a5
--- /dev/null
+++ b/web/src/lib/actions/action-task-check.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+/** Check a task now (AC-010): the server's check, or why there's none. */
+
+let session: { access_token: string } | null = { access_token: 'token' };
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({ auth: { getSession: async () => ({ data: { session } }) } }),
+}));
+vi.mock('@/config/api', () => ({ API_BASE_URL: 'https://api.example' }));
+
+const { checkActionTask } = await import('./action-task-check');
+
+const respond = (status: number, body: unknown) =>
+ vi.fn(async () => new Response(JSON.stringify(body), { status }));
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ session = { access_token: 'token' };
+});
+
+describe('checkActionTask', () => {
+ it('posts as the user and returns the check kept on the task', async () => {
+ const fetch = respond(200, {
+ checked: { at: '2026-10-27T03:00:00Z', passed: false, missing: ['page_error'] },
+ });
+ vi.stubGlobal('fetch', fetch);
+ expect(await checkActionTask('t1')).toEqual({
+ checked: { at: '2026-10-27T03:00:00Z', passed: false, missing: ['page_error'] },
+ reason: null,
+ });
+ const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit];
+ expect(url).toBe('https://api.example/api/action-center/tasks/t1/check');
+ expect(init.headers).toEqual({ Authorization: 'Bearer token' });
+ });
+
+ it('says why nothing was checked, and returns the server’s error rather than throwing', async () => {
+ vi.stubGlobal('fetch', respond(200, { checked: null, reason: 'not_checkable' }));
+ expect(await checkActionTask('t1')).toEqual({ checked: null, reason: 'not_checkable' });
+ vi.stubGlobal('fetch', respond(200, { checked: null, reason: 'something new' }));
+ expect(await checkActionTask('t1')).toEqual({ checked: null, reason: 'no_answer' });
+ vi.stubGlobal('fetch', respond(404, { error: 'Task not found', code: 'not_found' }));
+ expect(await checkActionTask('t1')).toEqual({
+ error: 'server',
+ code: 'not_found',
+ message: 'Task not found',
+ });
+ session = null;
+ expect(await checkActionTask('t1')).toEqual({ error: 'unauthenticated' });
+ });
+});
diff --git a/web/src/lib/actions/action-task-check.ts b/web/src/lib/actions/action-task-check.ts
new file mode 100644
index 000000000..e99777bee
--- /dev/null
+++ b/web/src/lib/actions/action-task-check.ts
@@ -0,0 +1,72 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+import { API_BASE_URL } from '@/config/api';
+import type { TaskLastCheck } from '@/lib/action-center/task-details';
+
+/** Why nothing was checked: no check here, done, the page didn't answer, changed meanwhile, a closed action. */
+export type CheckSkippedReason = 'not_checkable' | 'not_open' | 'no_answer' | 'changed' | 'closed';
+
+/**
+ * What checking a task now came to (AC-010): the check kept on it, or why
+ * there's none. A failure comes back as a value, as the other task actions'
+ * do, so the drawer can say why.
+ */
+export type CheckTaskResult =
+ | { checked: TaskLastCheck; reason: null }
+ | { checked: null; reason: CheckSkippedReason }
+ | { error: 'server'; code: string | null; message: string }
+ | { error: 'timeout' | 'unreachable' | 'unauthenticated' };
+
+/** Check a task on its page now, on the server, as the nightly sweep does. */
+export async function checkActionTask(taskId: string): Promise<CheckTaskResult> {
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) return { error: 'unauthenticated' };
+
+ try {
+ const res = await fetch(`${API_BASE_URL}/api/action-center/tasks/${taskId}/check`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ cache: 'no-store',
+ // The page and, for crawler access, its robots.txt: 10 s each.
+ signal: AbortSignal.timeout(30_000),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ return {
+ error: 'server',
+ code: typeof data.code === 'string' ? data.code : null,
+ message: data.error || `Server error: ${res.status}`,
+ };
+ }
+ const checked = data.checked;
+ if (checked && typeof checked === 'object') {
+ return {
+ checked: {
+ at: String(checked.at),
+ passed: Boolean(checked.passed),
+ missing: Array.isArray(checked.missing) ? checked.missing.map(String) : [],
+ },
+ reason: null,
+ };
+ }
+ const reasons: CheckSkippedReason[] = [
+ 'not_checkable',
+ 'not_open',
+ 'no_answer',
+ 'changed',
+ 'closed',
+ ];
+ return {
+ checked: null,
+ reason: reasons.includes(data.reason) ? data.reason : 'no_answer',
+ };
+ } catch (err) {
+ return {
+ error: err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'unreachable',
+ };
+ }
+}