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): write an action's tasks from its evidence (#1081)

Cihan912cac8797d7
diff --git a/server/.env.example b/server/.env.example
index ef6f36f0b..3382bcc37 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -49,6 +49,13 @@ COMPETITOR_SUGGESTION_MODEL=google/gemini-3-flash-preview
# (improveMonthlyBudgetUsd). Falls back to
# DEFAULT_SUGGESTION_MODEL, then google/gemini-3-flash-preview.
# IMPROVE_SUGGESTION_MODEL=google/gemini-3-flash-preview
+# Action Center: write each new action's tasks from its evidence (AC-004) —
+# one task per page or domain, with where, why, how and done-when. Off unless
+# "true"; turn on after product has reviewed a sample
+# (node src/scripts/review-action-tasks.js). Metered from the Improve budget.
+# ACTION_TASKS_AI=
+# The model that writes them. Falls back to IMPROVE_SUGGESTION_MODEL.
+# ACTION_TASKS_MODEL=
# How alike two content opportunities' prompt and fan-out baskets must be to
# count as one (0-1, default 0.6). A new suggestion above it is skipped and
# uses no quota (CONTENT-004). Raise it if distinct work is being dropped.
diff --git a/server/src/lib/action-center/task-writer/evidence.js b/server/src/lib/action-center/task-writer/evidence.js
new file mode 100644
index 000000000..7df186d04
--- /dev/null
+++ b/server/src/lib/action-center/task-writer/evidence.js
@@ -0,0 +1,370 @@
+/**
+ * What an action's tasks can be about (AC-004): the pages, prompts, domains,
+ * competitors and topics its signals name, with what each signal recorded
+ * about them. The task writer gives the model this and nothing else, and a
+ * written task must point back into it — a task with no target here is not
+ * concrete, whatever it says.
+ *
+ * Read from the signals' payloads as the evidence steps write them
+ * (signals/record.js): a lost citation's lost and cited-now pages, a
+ * competitor's positions and winning sources, uncited mentions, AI-traffic
+ * referrals, and a library finding's targets. The web's Affected tab reads the
+ * same fields (web/src/lib/action-center/affected.ts).
+ *
+ * Every entity gets a short ref ("page:1", "prompt:3") the model cites.
+ */
+
+import { extractHostname } from '../../response-parser.js';
+import { IMPROVE_PLATFORM_LABELS } from '../../prompt-improve.js';
+
+/** How many of each kind the model is shown: the first ones, most evidence first. */
+export const EVIDENCE_LIMITS = Object.freeze({
+ pages: 15,
+ prompts: 25,
+ domains: 12,
+ competitors: 6,
+ topics: 6,
+});
+
+const str = (value) => (typeof value === 'string' ? value.trim() : '');
+const num = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : null);
+const list = (value) => (Array.isArray(value) ? value : []);
+
+/** A URL without its scheme and "www.": "acme.example/pricing". */
+export function bareUrl(url) {
+ return str(url)
+ .replace(/^https?:\/\/(www\.)?/i, '')
+ .replace(/\/$/, '');
+}
+
+/** The path of an absolute URL, or the value itself. */
+function pathOf(url) {
+ try {
+ const { pathname, search } = new URL(url);
+ return `${pathname}${search}`;
+ } catch {
+ return str(url);
+ }
+}
+
+/** A prompt's first words, lower case and without punctuation: how a task is
+ * told to name it, and how the quality rule recognises it. */
+export const PROMPT_LABEL_WORDS = 5;
+
+export function promptWords(text) {
+ return str(text)
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}\s]/gu, ' ')
+ .split(/\s+/)
+ .filter(Boolean);
+}
+
+/** "ChatGPT" for "chatgpt-web"; the slug when it has no name. */
+export function platformLabel(slug) {
+ return IMPROVE_PLATFORM_LABELS[slug] ?? slug;
+}
+
+/**
+ * The entities an action's signals name.
+ *
+ * @param {Array<{ id: string, kind: string, payload: Record<string, unknown> | null }>} signals
+ * @param {{ domains?: string[] }} [brand] the brand's domains, so a page named by
+ * its path ("/pricing") and by its URL is one page
+ * @returns {{
+ * pages: object[], prompts: object[], domains: object[], competitors: object[],
+ * topics: object[], byRef: Map<string, object>
+ * }}
+ */
+export function buildEvidence(signals, { domains: brandDomains = [] } = {}) {
+ const pages = new Map();
+ const prompts = new Map();
+ const domains = new Map();
+ const competitors = new Map();
+ const topics = new Map();
+
+ const home = bareUrl(brandDomains[0] ?? '').toLowerCase();
+ const page = (url) => {
+ const bare = bareUrl(url).toLowerCase();
+ if (!bare) return null;
+ // A path is the brand's own page: keyed as its URL would be.
+ const key = bare.startsWith('/') && home ? `${home}${bare}` : bare;
+ let entry = pages.get(key);
+ if (entry && entry.url.startsWith('/') && !str(url).startsWith('/')) entry.url = str(url);
+ if (!entry) {
+ entry = {
+ url: str(url),
+ prompts: new Set(),
+ platforms: new Set(),
+ citedInstead: new Set(),
+ issues: new Set(),
+ lostPosition: null,
+ sessions: null,
+ before: null,
+ evidence: 0,
+ };
+ pages.set(key, entry);
+ }
+ entry.evidence += 1;
+ return entry;
+ };
+ const prompt = (id, text) => {
+ const key = str(id) || (str(text) ? `text:${str(text)}` : '');
+ if (!key) return null;
+ let entry = prompts.get(key);
+ if (!entry) {
+ entry = {
+ id: str(id) || null,
+ text: str(text),
+ platforms: new Set(),
+ lostPages: new Set(),
+ citedInstead: new Set(),
+ leaders: [],
+ mentionedOn: new Set(),
+ evidence: 0,
+ };
+ prompts.set(key, entry);
+ } else if (!entry.text && str(text)) {
+ entry.text = str(text);
+ }
+ entry.evidence += 1;
+ return entry;
+ };
+ const domain = (name) => {
+ const key = str(name)
+ .toLowerCase()
+ .replace(/^www\./, '');
+ if (!key) return null;
+ let entry = domains.get(key);
+ if (!entry) {
+ entry = { domain: key, prompts: new Set(), urls: new Set(), answers: 0, evidence: 0 };
+ domains.set(key, entry);
+ }
+ entry.evidence += 1;
+ return entry;
+ };
+ const competitor = (name) => {
+ const key = str(name);
+ if (!key) return null;
+ let entry = competitors.get(key.toLowerCase());
+ if (!entry) {
+ entry = { name: key, prompts: new Set(), sources: new Set(), evidence: 0 };
+ competitors.set(key.toLowerCase(), entry);
+ }
+ entry.evidence += 1;
+ return entry;
+ };
+ const topic = (name) => {
+ const key = str(name);
+ if (!key) return null;
+ let entry = topics.get(key.toLowerCase());
+ if (!entry) {
+ entry = { name: key, evidence: 0 };
+ topics.set(key.toLowerCase(), entry);
+ }
+ entry.evidence += 1;
+ return entry;
+ };
+
+ for (const signal of signals) {
+ const p = signal.payload ?? {};
+ const mine = [];
+
+ // One prompt, as a lost citation names it.
+ const single = prompt(p.promptId, p.promptText);
+ if (single) mine.push(single);
+ const platforms = list(p.platforms).map(str).filter(Boolean);
+
+ // The brand's pages that stopped being cited, and who is cited instead.
+ const lostPages = [];
+ for (const lost of list(p.lostUrls)) {
+ const entry = page(lost?.url);
+ if (!entry) continue;
+ lostPages.push(entry);
+ for (const slug of [...list(lost.platforms), ...platforms]) entry.platforms.add(str(slug));
+ entry.lostPosition ??= num(lost.position);
+ for (const row of mine) {
+ entry.prompts.add(row);
+ row.lostPages.add(entry);
+ }
+ }
+ for (const cited of list(p.citedNow)) {
+ const entry = domain(cited?.domain || extractHostname(cited?.url));
+ if (!entry) continue;
+ if (str(cited.url)) entry.urls.add(str(cited.url));
+ entry.answers += num(cited.answers) ?? 0;
+ for (const row of mine) {
+ entry.prompts.add(row);
+ row.citedInstead.add(entry);
+ }
+ for (const lost of lostPages) lost.citedInstead.add(entry);
+ }
+ for (const row of mine) for (const slug of platforms) row.platforms.add(slug);
+
+ // A competitor ahead, prompt by prompt, and the sources it wins with.
+ const rival = competitor(p.competitorName);
+ for (const pos of list(p.positions)) {
+ const row = prompt(pos?.promptId, pos?.promptText);
+ if (!row) continue;
+ if (str(pos.platform)) row.platforms.add(str(pos.platform));
+ if (rival) {
+ rival.prompts.add(row);
+ row.leaders.push({
+ competitor: rival.name,
+ platform: str(pos.platform),
+ them: num(pos.competitor?.now),
+ you: num(pos.you?.now),
+ });
+ }
+ }
+ for (const source of list(p.winningSources)) {
+ const entry = domain(source?.domain);
+ if (!entry) continue;
+ entry.answers += num(source.answers) ?? 0;
+ rival?.sources.add(entry);
+ }
+
+ // Answers that name the brand without citing it.
+ for (const mention of list(p.mentions)) {
+ const row = prompt(mention?.promptId, mention?.promptText);
+ if (!row) continue;
+ for (const slug of list(mention.platforms)) {
+ row.platforms.add(str(slug));
+ row.mentionedOn.add(str(slug));
+ }
+ }
+
+ // AI visits to pages.
+ for (const referral of list(p.referrals)) {
+ const entry = page(referral?.page);
+ if (!entry) continue;
+ entry.sessions ??= num(referral.sessions);
+ entry.before ??= num(referral.before);
+ for (const visit of list(referral.platforms)) {
+ if (str(visit?.platform)) entry.platforms.add(str(visit.platform));
+ }
+ }
+
+ // A library finding's targets, by what they are.
+ const entity = str(p.entity);
+ for (const target of list(p.targets)) {
+ const label = str(target?.label) || str(target?.id);
+ if (!label) continue;
+ if (entity === 'prompts') {
+ prompt(target.id, target.label);
+ } else if (entity === 'pages') {
+ if (str(target.id) === 'site') continue;
+ const entry = page(label);
+ if (!entry) continue;
+ entry.sessions ??= num(target.now);
+ entry.before ??= num(target.before);
+ const issues = list(target.issues).length
+ ? list(target.issues).map((i) => str(i?.label) || str(i?.check))
+ : list(target.checks).map(str);
+ for (const issue of issues) if (issue) entry.issues.add(issue);
+ } else if (entity === 'competitors') {
+ competitor(label);
+ } else if (entity === 'topics') {
+ topic(label);
+ } else if (entity === 'domains' || entity === 'sources') {
+ domain(extractHostname(label) ?? label);
+ }
+ }
+ }
+
+ const ranked = (map, limit) =>
+ [...map.values()].sort((a, b) => b.evidence - a.evidence).slice(0, limit);
+
+ const out = {
+ pages: ranked(pages, EVIDENCE_LIMITS.pages),
+ prompts: ranked(prompts, EVIDENCE_LIMITS.prompts).filter((row) => row.text),
+ domains: ranked(domains, EVIDENCE_LIMITS.domains),
+ competitors: ranked(competitors, EVIDENCE_LIMITS.competitors),
+ topics: ranked(topics, EVIDENCE_LIMITS.topics),
+ byRef: new Map(),
+ };
+ out.pages.forEach((entry, i) => {
+ entry.ref = `page:${i + 1}`;
+ entry.labels = [bareUrl(entry.url), pathOf(entry.url)].filter((l) => l && l !== '/');
+ });
+ out.prompts.forEach((entry, i) => {
+ entry.ref = `prompt:${i + 1}`;
+ entry.words = promptWords(entry.text).slice(0, PROMPT_LABEL_WORDS);
+ entry.labels = [];
+ });
+ out.domains.forEach((entry, i) => {
+ entry.ref = `domain:${i + 1}`;
+ entry.labels = [entry.domain];
+ });
+ out.competitors.forEach((entry, i) => {
+ entry.ref = `competitor:${i + 1}`;
+ entry.labels = [entry.name];
+ });
+ out.topics.forEach((entry, i) => {
+ entry.ref = `topic:${i + 1}`;
+ entry.labels = [entry.name];
+ });
+ for (const kind of ['pages', 'prompts', 'domains', 'competitors', 'topics']) {
+ for (const entry of out[kind]) out.byRef.set(entry.ref, entry);
+ }
+ return out;
+}
+
+/** Whether there is anything to write a concrete task about. */
+export function hasTargets(evidence) {
+ return evidence.byRef.size > 0;
+}
+
+const refsOf = (set) => [...set].map((entry) => entry.ref).filter(Boolean);
+
+/**
+ * The evidence as the model reads it: plain objects, refs instead of
+ * cross-links, platform names instead of slugs.
+ */
+export function evidenceForPrompt(evidence) {
+ const names = (set) => [...set].filter(Boolean).map(platformLabel);
+ return {
+ pages: evidence.pages.map((entry) => ({
+ ref: entry.ref,
+ url: bareUrl(entry.url),
+ ...(entry.prompts.size ? { lostOnPrompts: refsOf(entry.prompts) } : {}),
+ ...(entry.platforms.size ? { platforms: names(entry.platforms) } : {}),
+ ...(entry.lostPosition !== null ? { citedAtBefore: entry.lostPosition } : {}),
+ ...(entry.citedInstead.size ? { citedInstead: refsOf(entry.citedInstead) } : {}),
+ ...(entry.sessions !== null ? { aiVisitsNow: entry.sessions } : {}),
+ ...(entry.before !== null ? { aiVisitsBefore: entry.before } : {}),
+ ...(entry.issues.size ? { auditIssues: [...entry.issues] } : {}),
+ })),
+ prompts: evidence.prompts.map((entry) => ({
+ ref: entry.ref,
+ text: entry.text,
+ ...(entry.platforms.size ? { platforms: names(entry.platforms) } : {}),
+ ...(entry.lostPages.size ? { lostPages: refsOf(entry.lostPages) } : {}),
+ ...(entry.citedInstead.size ? { citedInstead: refsOf(entry.citedInstead) } : {}),
+ ...(entry.leaders.length
+ ? {
+ competitorsAhead: entry.leaders.map((l) => ({
+ competitor: l.competitor,
+ platform: platformLabel(l.platform),
+ theirPosition: l.them,
+ yourPosition: l.you,
+ })),
+ }
+ : {}),
+ ...(entry.mentionedOn.size ? { namedWithoutCitationOn: names(entry.mentionedOn) } : {}),
+ })),
+ domains: evidence.domains.map((entry) => ({
+ ref: entry.ref,
+ domain: entry.domain,
+ ...(entry.urls.size ? { citedUrls: [...entry.urls].slice(0, 3).map(bareUrl) } : {}),
+ ...(entry.answers ? { answers: entry.answers } : {}),
+ ...(entry.prompts.size ? { citedOnPrompts: refsOf(entry.prompts) } : {}),
+ })),
+ competitors: evidence.competitors.map((entry) => ({
+ ref: entry.ref,
+ name: entry.name,
+ ...(entry.prompts.size ? { aheadOnPrompts: refsOf(entry.prompts) } : {}),
+ ...(entry.sources.size ? { winsWith: refsOf(entry.sources) } : {}),
+ })),
+ topics: evidence.topics.map((entry) => ({ ref: entry.ref, name: entry.name })),
+ };
+}
diff --git a/server/src/lib/action-center/task-writer/evidence.test.js b/server/src/lib/action-center/task-writer/evidence.test.js
new file mode 100644
index 000000000..ec094b34b
--- /dev/null
+++ b/server/src/lib/action-center/task-writer/evidence.test.js
@@ -0,0 +1,157 @@
+import { describe, expect, it } from 'vitest';
+import { buildEvidence, evidenceForPrompt, hasTargets } from './evidence.js';
+
+const lost = (over = {}) => ({
+ id: 's1',
+ kind: 'lost_citations',
+ payload: {
+ promptId: 'p1',
+ promptText: 'Which coffee subscriptions ship internationally?',
+ platforms: ['chatgpt-web', 'gemini-web'],
+ lostUrls: [{ url: 'https://acme.example/blog/shipping', position: 2 }],
+ citedNow: [{ url: 'https://www.seriouseats.com/best', domain: 'seriouseats.com', answers: 4 }],
+ ...over,
+ },
+});
+
+describe('buildEvidence', () => {
+ it("links a lost citation's prompt, the page it lost and who is cited instead", () => {
+ const evidence = buildEvidence([lost()]);
+ const [page] = evidence.pages;
+ const [prompt] = evidence.prompts;
+ const [domain] = evidence.domains;
+
+ expect(page).toMatchObject({ ref: 'page:1', lostPosition: 2 });
+ expect(page.labels).toEqual(['acme.example/blog/shipping', '/blog/shipping']);
+ expect([...page.platforms]).toEqual(['chatgpt-web', 'gemini-web']);
+ expect([...page.citedInstead]).toEqual([domain]);
+ expect([...prompt.lostPages]).toEqual([page]);
+ expect(domain).toMatchObject({ ref: 'domain:1', domain: 'seriouseats.com', answers: 4 });
+ expect(evidence.byRef.get('prompt:1')).toBe(prompt);
+ });
+
+ it('names a competitor ahead, prompt by prompt, and the sources it wins with', () => {
+ const evidence = buildEvidence([
+ {
+ id: 's2',
+ kind: 'competitor_leads',
+ payload: {
+ competitorName: 'Trade Coffee',
+ positions: [
+ {
+ promptId: 'p4',
+ promptText: 'Best espresso machines under $500?',
+ platform: 'chatgpt-web',
+ competitor: { now: 1 },
+ you: { now: 4 },
+ },
+ ],
+ winningSources: [{ domain: 'g2.com', answers: 3 }],
+ },
+ },
+ ]);
+ expect(evidence.competitors[0]).toMatchObject({ ref: 'competitor:1', name: 'Trade Coffee' });
+ expect(evidence.prompts[0].leaders).toEqual([
+ { competitor: 'Trade Coffee', platform: 'chatgpt-web', them: 1, you: 4 },
+ ]);
+ expect(evidence.domains[0].domain).toBe('g2.com');
+ });
+
+ it("reads AI-traffic pages and an audit finding's checks", () => {
+ const evidence = buildEvidence([
+ {
+ id: 's3',
+ kind: 'ai_traffic_drop',
+ payload: {
+ referrals: [
+ {
+ page: '/subscriptions',
+ sessions: 32,
+ before: 40,
+ platforms: [{ platform: 'chatgpt.com' }],
+ },
+ ],
+ },
+ },
+ {
+ id: 's4',
+ kind: 'crawler_blocked',
+ payload: {
+ entity: 'pages',
+ targets: [
+ {
+ id: 'https://acme.example/pricing',
+ label: 'https://acme.example/pricing',
+ issues: [{ check: 'robots_ai_bots', label: 'robots.txt blocks AI bots' }],
+ },
+ { id: 'site', label: 'Whole site' },
+ ],
+ },
+ },
+ ]);
+ expect(evidence.pages.map((p) => [p.url, p.sessions, p.before, [...p.issues]])).toEqual([
+ ['/subscriptions', 32, 40, []],
+ ['https://acme.example/pricing', null, null, ['robots.txt blocks AI bots']],
+ ]);
+ });
+
+ it('merges what several signals say about one page and ranks by evidence', () => {
+ const evidence = buildEvidence([
+ lost(),
+ lost({ promptId: 'p2', promptText: 'Second prompt' }),
+ lost({
+ promptId: 'p3',
+ promptText: 'Third',
+ lostUrls: [{ url: 'https://acme.example/other' }],
+ }),
+ ]);
+ expect(evidence.pages.map((p) => p.url)).toEqual([
+ 'https://acme.example/blog/shipping',
+ 'https://acme.example/other',
+ ]);
+ expect(evidence.pages[0].prompts.size).toBe(2);
+ });
+
+ it("reads a path and the brand's URL for it as one page", () => {
+ const evidence = buildEvidence(
+ [
+ lost({ lostUrls: [{ url: 'https://www.acme.example/subscriptions', position: 1 }] }),
+ {
+ id: 's5',
+ kind: 'ai_traffic_drop',
+ payload: { referrals: [{ page: '/subscriptions', sessions: 3, before: 9 }] },
+ },
+ ],
+ { domains: ['acme.example'] },
+ );
+ expect(evidence.pages).toHaveLength(1);
+ expect(evidence.pages[0]).toMatchObject({
+ url: 'https://www.acme.example/subscriptions',
+ sessions: 3,
+ lostPosition: 1,
+ });
+ });
+
+ it('has nothing to write about without targets', () => {
+ expect(hasTargets(buildEvidence([{ id: 's', kind: 'sharp_drop', payload: {} }]))).toBe(false);
+ });
+});
+
+describe('evidenceForPrompt', () => {
+ it('gives the model refs and names, not links and slugs', () => {
+ const shown = evidenceForPrompt(buildEvidence([lost()]));
+ expect(shown.pages[0]).toEqual({
+ ref: 'page:1',
+ url: 'acme.example/blog/shipping',
+ lostOnPrompts: ['prompt:1'],
+ platforms: ['ChatGPT', 'Gemini'],
+ citedAtBefore: 2,
+ citedInstead: ['domain:1'],
+ });
+ expect(shown.prompts[0]).toMatchObject({
+ ref: 'prompt:1',
+ lostPages: ['page:1'],
+ citedInstead: ['domain:1'],
+ });
+ });
+});
diff --git a/server/src/lib/action-center/task-writer/index.js b/server/src/lib/action-center/task-writer/index.js
new file mode 100644
index 000000000..cdda81857
--- /dev/null
+++ b/server/src/lib/action-center/task-writer/index.js
@@ -0,0 +1,457 @@
+/**
+ * The task writer (AC-004): an action's tasks written from its evidence.
+ *
+ * A library plan gives "Refresh content for 7 prompts". This reads the
+ * pages, prompts, domains and competitors the action's signals name
+ * (evidence.js), asks a model for at most six tasks — one per target, each
+ * saying where, why, how and when it is done — keeps only the ones that pass
+ * the quality rule (quality.js), asks once more for replacements of the rest,
+ * and writes them in place of the template tasks.
+ *
+ * Off unless ACTION_TASKS_AI=true: product reviews a sample of written tasks
+ * (scripts/review-action-tasks.js) before any brand gets them. Metered like
+ * the Improve tab, from the same monthly budget. A night that cannot write
+ * an action's tasks — the budget is spent, the model failed — leaves its
+ * template tasks, and the next sweep tries again.
+ */
+
+import { NoObjectGeneratedError, generateObject } from 'ai';
+import supabaseAdmin from '../../../config/supabase.js';
+import { logger } from '../../logger.js';
+import { resolveModel } from '../../ai-provider.js';
+import { withRetry } from '../../retry.js';
+import { generationCostUsd } from '../../improve-cost.js';
+import { PlanLimitError, enforceImproveQuota } from '../../plan-guard.js';
+import { loadDefinitions } from '../definitions/index.js';
+import { getTask } from '../tasks/registry.js';
+import { IMPROVE_ACTION_KIND } from '../from-prompt-improve.js';
+import { OPPORTUNITY_ACTION_KIND } from '../from-opportunity.js';
+import { buildEvidence, evidenceForPrompt, hasTargets } from './evidence.js';
+import { MAX_TASKS, sameTask, taskProblems } from './quality.js';
+import { buildRetryPrompt, buildTaskWriterPrompt, taskWriterSchema } from './prompt.js';
+
+/** Whether this deployment writes tasks at all. */
+export function isTaskWriterEnabled() {
+ return process.env.ACTION_TASKS_AI === 'true';
+}
+
+/** The model, as the Improve tab's unless set apart. */
+export function taskWriterModelId() {
+ return (
+ process.env.ACTION_TASKS_MODEL ||
+ process.env.IMPROVE_SUGGESTION_MODEL ||
+ process.env.DEFAULT_SUGGESTION_MODEL ||
+ 'google/gemini-3-flash-preview'
+ );
+}
+
+/** Actions a person sent carry the tasks they were sent with. */
+const SENT_KINDS = new Set([IMPROVE_ACTION_KIND, OPPORTUNITY_ACTION_KIND]);
+const CLOSED = new Set(['completed', 'dismissed']);
+
+/**
+ * How long one model call may take. Two calls (the second for refused
+ * tasks), each tried twice, stay inside the dashboard's 200 s wait.
+ */
+const CALL_TIMEOUT_MS = 40_000;
+
+/** A claim older than this is a writer that died; another may take over. */
+const CLAIM_TTL_MS = 5 * 60 * 1000;
+
+/**
+ * Analysis the product does itself: what the library plans as system work or
+ * names as analysis, legacy keys included. Never kept on a rewrite, done or
+ * not — its result is in the Affected tab, not on anyone's list.
+ */
+const ANALYSIS_KEY =
+ /^(?:analy|identify|validate|revalidate|measure|review|compare|diagnose|coverage|map_|cluster|prioritize|define|competitor_pressure|page_readiness)/;
+
+export function isAnalysisTask(row) {
+ if (!row.task_key) return false;
+ return getTask(row.task_key)?.mode === 'system' || ANALYSIS_KEY.test(row.task_key);
+}
+
+/**
+ * Whether a rewrite keeps a task: one done or under way, and one a person
+ * added — no template, not written by the model. Everything else is replaced.
+ */
+export function keepsTask(row) {
+ if (isAnalysisTask(row)) return false;
+ if (row.status === 'completed' || row.status === 'in_progress') return true;
+ return !row.task_key && row.details?.source !== 'ai';
+}
+
+/**
+ * Why a rewrite was refused or wrote nothing. `code` is what the dashboard
+ * words in the reader's language; `message` is for logs and the API.
+ */
+export class TaskWriterError extends Error {
+ constructor(code, message, status = 422) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ }
+}
+
+async function recordUsage({ organizationId, actionId, modelId, usage }) {
+ const { error } = await supabaseAdmin.from('prompt_improve_usage').insert({
+ organization_id: organizationId,
+ action_id: actionId,
+ model: modelId,
+ input_tokens: usage?.inputTokens ?? null,
+ output_tokens: usage?.outputTokens ?? null,
+ cost_usd: generationCostUsd(modelId, usage),
+ });
+ if (error) logger.error({ err: error, actionId }, '[task-writer] usage insert failed');
+}
+
+/** What the writer needs: the action, its brand, its signals. */
+async function loadAction(actionId) {
+ const { data: action, error } = await supabaseAdmin
+ .from('actions')
+ .select('id, brand_id, kind, category, status, payload')
+ .eq('id', actionId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!action) throw new TaskWriterError('not_found', 'Action not found', 404);
+
+ const [brandRes, domainsRes, signalsRes, definitions] = await Promise.all([
+ supabaseAdmin
+ .from('brands')
+ .select('id, name, description, organization_id')
+ .eq('id', action.brand_id)
+ .single(),
+ supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', action.brand_id),
+ supabaseAdmin
+ .from('signals')
+ .select('id, kind, status, payload, action_id, action_signals!inner(action_id)')
+ .eq('brand_id', action.brand_id)
+ .eq('action_signals.action_id', actionId),
+ loadDefinitions(),
+ ]);
+ if (brandRes.error) throw new Error(brandRes.error.message);
+ if (signalsRes.error) throw new Error(signalsRes.error.message);
+
+ // The signals that support it now (AC-007); all it took once none do.
+ const all = signalsRes.data ?? [];
+ const supporting = all.filter(
+ (s) => ['new', 'acknowledged'].includes(s.status) && s.action_id === actionId,
+ );
+ const definition = definitions.find((d) => d.id === action.kind);
+ return {
+ action,
+ brand: brandRes.data,
+ domains: (domainsRes.data ?? []).map((row) => row.domain),
+ signals: supporting.length > 0 ? supporting : all,
+ name: definition?.name ?? action.kind,
+ };
+}
+
+/**
+ * One model call, charged at its real cost on every attempt — the ones the
+ * retry repeats after a schema miss included — unless it is a dry run.
+ */
+async function callModel({ modelId, system, prompt, charge }) {
+ const { object } = await withRetry(
+ async () => {
+ try {
+ const result = await generateObject({
+ model: resolveModel(modelId),
+ schema: taskWriterSchema,
+ system,
+ prompt,
+ abortSignal: AbortSignal.timeout(CALL_TIMEOUT_MS),
+ });
+ await charge(result.usage);
+ return result;
+ } catch (err) {
+ if (NoObjectGeneratedError.isInstance(err) && err.usage) await charge(err.usage);
+ throw err;
+ }
+ },
+ { attempts: 2, baseDelayMs: 500, label: 'action-task-writer' },
+ );
+ return object.tasks ?? [];
+}
+
+/** Sorts a batch into the tasks kept and the ones refused, with why. */
+function sift(tasks, evidence, kept) {
+ const accepted = [...kept];
+ const refused = [];
+ for (const task of tasks) {
+ const problems = taskProblems(task, evidence);
+ if (problems.length === 0 && accepted.some((other) => sameTask(other, task))) {
+ problems.push('it repeats another task');
+ }
+ if (problems.length === 0 && accepted.length < MAX_TASKS) accepted.push(task);
+ else if (problems.length > 0) refused.push({ task, problems });
+ }
+ return { accepted: accepted.slice(kept.length), refused };
+}
+
+/**
+ * Whether anyone has worked on the action's tasks: moved one on, added one,
+ * renamed or edited one. The night writes only untouched plans; a person
+ * rewrites theirs with "Regenerate tasks".
+ */
+export function isTouched(rows) {
+ return rows.some(
+ (row) =>
+ row.status !== 'todo' ||
+ (!row.task_key && row.details?.source !== 'ai') ||
+ (row.task_key && (row.title || row.details)),
+ );
+}
+
+/** Take the action for this writer, or say another writer has it. */
+async function claim(actionId, now) {
+ const stale = new Date(now.getTime() - CLAIM_TTL_MS).toISOString();
+ const { data, error } = await supabaseAdmin
+ .from('actions')
+ .update({ tasks_writing_since: now.toISOString() })
+ .eq('id', actionId)
+ .or(`tasks_writing_since.is.null,tasks_writing_since.lt.${stale}`)
+ .select('id');
+ if (error) throw new Error(error.message);
+ if (!data?.length) {
+ throw new TaskWriterError('busy', 'Tasks for this action are already being written.', 409);
+ }
+}
+
+async function release(actionId) {
+ const { error } = await supabaseAdmin
+ .from('actions')
+ .update({ tasks_writing_since: null })
+ .eq('id', actionId);
+ if (error) logger.error({ err: error, actionId }, '[task-writer] could not release the claim');
+}
+
+/**
+ * Write an action's tasks from its evidence.
+ *
+ * @param {string} actionId
+ * @param {{ trigger?: 'auto' | 'regenerate' | 'review', userId?: string | null,
+ * dryRun?: boolean, now?: Date }} [options] a dry run writes and charges
+ * nothing: it returns what it would write, for the review script.
+ * @returns {Promise<{ status: 'written' | 'skipped' | 'preview', reason?: string,
+ * tasks?: object[], refused?: object[], kept?: number, costUsd: number, evidence?: object }>}
+ */
+export async function writeTasksForAction(
+ actionId,
+ { trigger = 'auto', userId = null, dryRun = false, now = new Date() } = {},
+) {
+ const { action, brand, domains, signals, name } = await loadAction(actionId);
+ if (SENT_KINDS.has(action.kind)) {
+ throw new TaskWriterError('sent', 'This action carries the tasks it was sent with.');
+ }
+ if (CLOSED.has(action.status)) throw new TaskWriterError('closed', 'This action is closed.');
+ if (dryRun) return compose({ action, brand, domains, signals, name, dryRun, now });
+
+ await claim(actionId, now);
+ try {
+ return await compose({ action, brand, domains, signals, name, trigger, userId, now });
+ } finally {
+ await release(actionId);
+ }
+}
+
+/** The writing itself, once the action is this writer's. */
+async function compose({ action, brand, domains, signals, name, trigger, userId, dryRun, now }) {
+ const actionId = action.id;
+ if (!dryRun && trigger === 'auto') {
+ // The night leaves alone a plan someone is already working through.
+ const { data: rows, error } = await supabaseAdmin
+ .from('action_tasks')
+ .select('task_key, title, status, details')
+ .eq('action_id', actionId);
+ if (error) throw new Error(error.message);
+ if (isTouched(rows ?? [])) {
+ await markWritten(actionId, now);
+ return { status: 'skipped', reason: 'in_use', costUsd: 0 };
+ }
+ }
+
+ const evidence = buildEvidence(signals, { domains });
+ if (!hasTargets(evidence)) {
+ if (!dryRun) await markWritten(actionId, now);
+ return { status: 'skipped', reason: 'no_targets', costUsd: 0 };
+ }
+
+ const modelId = taskWriterModelId();
+ if (!dryRun) await enforceImproveQuota(brand.organization_id, modelId);
+
+ let costUsd = 0;
+ const charge = async (usage) => {
+ costUsd += generationCostUsd(modelId, usage);
+ if (!dryRun) {
+ await recordUsage({ organizationId: brand.organization_id, actionId, modelId, usage });
+ }
+ };
+
+ const shown = evidenceForPrompt(evidence);
+ const base = buildTaskWriterPrompt({
+ action: { name, category: action.category },
+ brand: { name: brand.name, description: brand.description, domains },
+ evidence: shown,
+ });
+ const first = sift(await callModel({ modelId, ...base, charge }), evidence, []);
+ let tasks = first.accepted;
+ let refused = first.refused;
+
+ // Refused tasks come back once, with their reasons.
+ const missing = Math.min(refused.length, MAX_TASKS - tasks.length);
+ if (missing > 0) {
+ const retry = buildRetryPrompt({ base, kept: tasks, refused, count: missing });
+ const second = sift(await callModel({ modelId, ...retry, charge }), evidence, tasks);
+ tasks = [...tasks, ...second.accepted];
+ // Both rounds' refusals, so a review sees how often the first answer misses.
+ refused = [...refused, ...second.refused];
+ }
+
+ if (dryRun) return { status: 'preview', tasks, refused, costUsd, evidence: shown };
+ if (tasks.length === 0) {
+ await markWritten(actionId, now);
+ return { status: 'skipped', reason: 'no_valid_tasks', refused, costUsd };
+ }
+
+ const kept = await replaceTasks(actionId, tasks, { now });
+ await markWritten(actionId, now, { changed: true });
+ await supabaseAdmin.from('action_events').insert({
+ action_id: actionId,
+ event: 'tasks_generated',
+ data: { count: tasks.length, kept, trigger },
+ actor_id: userId,
+ });
+ return { status: 'written', tasks, refused, kept, costUsd };
+}
+
+/** Record the writing; the action counts as updated only when its tasks changed. */
+async function markWritten(actionId, now, { changed = false } = {}) {
+ const { error } = await supabaseAdmin
+ .from('actions')
+ .update({
+ tasks_generated_at: now.toISOString(),
+ ...(changed ? { updated_at: now.toISOString() } : {}),
+ })
+ .eq('id', actionId);
+ if (error) throw new Error(error.message);
+}
+
+/**
+ * Put the written tasks in place of the replaced ones. The new rows go in
+ * first, numbered after everything, so a failure halfway leaves the old list
+ * whole rather than a gap; then the replaced ones go and the rest are
+ * numbered again, kept tasks first in their order.
+ *
+ * @returns {Promise<number>} how many tasks were kept
+ */
+export async function replaceTasks(actionId, tasks, { now = new Date() } = {}) {
+ const { data: rows, error } = await supabaseAdmin
+ .from('action_tasks')
+ .select('id, position, task_key, status, details')
+ .eq('action_id', actionId)
+ .order('position');
+ if (error) throw new Error(error.message);
+ const existing = rows ?? [];
+ const kept = existing.filter(keepsTask);
+ const replaced = existing.filter((row) => !keepsTask(row));
+ const offset = existing.reduce((max, row) => Math.max(max, row.position), 0);
+
+ const { data: inserted, error: insertError } = await supabaseAdmin
+ .from('action_tasks')
+ .insert(
+ tasks.map((task, i) => ({
+ action_id: actionId,
+ position: offset + i + 1,
+ task_key: null,
+ title: task.title.trim(),
+ mode: 'human',
+ permission: 'read',
+ details: {
+ where: task.where.trim(),
+ why: task.why.trim(),
+ how: task.how.map((step) => step.trim()).filter(Boolean),
+ doneWhen: task.doneWhen.trim(),
+ type: task.type,
+ effort: task.effort.trim(),
+ role: task.role.trim(),
+ source: 'ai',
+ refs: task.refs,
+ },
+ })),
+ )
+ .select('id, position');
+ if (insertError) throw new Error(insertError.message);
+
+ if (replaced.length > 0) {
+ const { error: deleteError } = await supabaseAdmin
+ .from('action_tasks')
+ .delete()
+ .in(
+ 'id',
+ replaced.map((row) => row.id),
+ );
+ if (deleteError) throw new Error(deleteError.message);
+ }
+
+ const order = [...kept, ...[...(inserted ?? [])].sort((a, b) => a.position - b.position)];
+ for (const [i, row] of order.entries()) {
+ if (row.position === i + 1) continue;
+ const { error: moveError } = await supabaseAdmin
+ .from('action_tasks')
+ .update({ position: i + 1, updated_at: now.toISOString() })
+ .eq('id', row.id);
+ if (moveError) throw new Error(moveError.message);
+ }
+ return kept.length;
+}
+
+/** The nightly sweep's reach: actions raised in the last three days. */
+const SWEEP_WINDOW_MS = 3 * 24 * 60 * 60 * 1000;
+/** Actions one sweep writes, so a night's model spend has a ceiling. */
+const SWEEP_LIMIT = 20;
+
+/**
+ * Write the tasks of recent actions that have none written yet. Runs after
+ * a brand's signal pass and once a day for the ones it missed. An
+ * organization whose budget is spent is skipped for the rest of the sweep.
+ *
+ * @param {{ brandId?: string, now?: Date, limit?: number }} [options]
+ */
+export async function sweepActionTasks({ brandId, now = new Date(), limit = SWEEP_LIMIT } = {}) {
+ if (!isTaskWriterEnabled()) return { skipped: 'disabled' };
+ let query = supabaseAdmin
+ .from('actions')
+ .select('id, brand_id, kind, status')
+ .is('tasks_generated_at', null)
+ .gte('created_at', new Date(now.getTime() - SWEEP_WINDOW_MS).toISOString())
+ .not('status', 'in', '("completed","dismissed")')
+ .not('kind', 'in', `("${IMPROVE_ACTION_KIND}","${OPPORTUNITY_ACTION_KIND}")`)
+ .order('created_at', { ascending: false })
+ .limit(limit);
+ if (brandId) query = query.eq('brand_id', brandId);
+ const { data: actions, error } = await query;
+ if (error) throw new Error(error.message);
+
+ const spent = new Set();
+ const outcome = { written: 0, skipped: 0, failed: 0 };
+ for (const action of actions ?? []) {
+ if (spent.has(action.brand_id)) continue;
+ try {
+ const result = await writeTasksForAction(action.id, { trigger: 'auto', now });
+ if (result.status === 'written') outcome.written += 1;
+ else outcome.skipped += 1;
+ } catch (err) {
+ if (err instanceof PlanLimitError) {
+ spent.add(action.brand_id);
+ } else if (err instanceof TaskWriterError && err.code === 'busy') {
+ // Another writer has it — a person's Regenerate, most likely.
+ } else {
+ logger.warn({ err, actionId: action.id }, '[task-writer] could not write tasks');
+ }
+ outcome.failed += 1;
+ }
+ }
+ logger.info({ brandId, ...outcome }, '[task-writer] sweep');
+ return outcome;
+}
diff --git a/server/src/lib/action-center/task-writer/index.test.js b/server/src/lib/action-center/task-writer/index.test.js
new file mode 100644
index 000000000..6b31424c5
--- /dev/null
+++ b/server/src/lib/action-center/task-writer/index.test.js
@@ -0,0 +1,322 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The task writer end to end (AC-004), on an in-memory database and a
+ * scripted model: which tasks a rewrite keeps, the one retry for refused
+ * tasks, metering, dry runs and a spent budget.
+ */
+
+let db;
+let ops;
+
+/** A query builder over `db`, recording every write. */
+function table(name) {
+ const q = {
+ name,
+ op: 'select',
+ filters: [],
+ payload: null,
+ single: false,
+ returning: false,
+ free: false,
+ };
+ const rows = () =>
+ (db[name] ?? [])
+ .filter((row) => (q.free ? !row.tasks_writing_since : true))
+ .filter((row) =>
+ q.filters.every(([col, value]) =>
+ col === 'action_signals.action_id'
+ ? true
+ : Array.isArray(value)
+ ? value.includes(row[col])
+ : row[col] === value,
+ ),
+ );
+ const run = () => {
+ if (q.op === 'select') {
+ const data = rows();
+ return { data: q.single ? (data[0] ?? null) : data, error: null };
+ }
+ ops.push({ table: name, op: q.op, payload: q.payload, filters: q.filters });
+ if (q.op === 'insert' && name === 'action_tasks') {
+ const inserted = q.payload.map((row, i) => ({ id: `new-${i + 1}`, ...row }));
+ db.action_tasks.push(...inserted);
+ return { data: inserted, error: null };
+ }
+ if (q.op === 'delete') {
+ const ids = q.filters.find(([col]) => col === 'id')?.[1] ?? [];
+ db[name] = db[name].filter((row) => !ids.includes(row.id));
+ }
+ if (q.op === 'update') {
+ const matched = rows();
+ for (const row of matched) Object.assign(row, q.payload);
+ return { data: q.returning ? matched.map((row) => ({ id: row.id })) : null, error: null };
+ }
+ return { data: null, error: null };
+ };
+ const chain = {
+ select: () => ((q.returning = q.op !== 'select'), chain),
+ // Only the claim uses or(): a free action, or one whose writer died.
+ or: () => ((q.free = true), chain),
+ eq: (col, value) => (q.filters.push([col, value]), chain),
+ in: (col, value) => (q.filters.push([col, value]), chain),
+ is: () => chain,
+ gte: () => chain,
+ not: () => chain,
+ order: () => chain,
+ limit: () => chain,
+ insert: (payload) => ((q.op = 'insert'), (q.payload = payload), chain),
+ update: (payload) => ((q.op = 'update'), (q.payload = payload), chain),
+ delete: () => ((q.op = 'delete'), chain),
+ maybeSingle: async () => ((q.single = true), run()),
+ single: async () => ((q.single = true), run()),
+ then: (resolve, reject) => Promise.resolve(run()).then(resolve, reject),
+ };
+ return chain;
+}
+
+vi.mock('../../../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));
+
+const generateObject = vi.fn();
+vi.mock('ai', () => ({
+ generateObject: (...args) => generateObject(...args),
+ NoObjectGeneratedError: { isInstance: () => false },
+}));
+vi.mock('../../ai-provider.js', () => ({ resolveModel: () => ({}) }));
+vi.mock('../../logger.js', () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));
+
+const enforceImproveQuota = vi.fn();
+class PlanLimitError extends Error {}
+vi.mock('../../plan-guard.js', () => ({
+ enforceImproveQuota: (...args) => enforceImproveQuota(...args),
+ PlanLimitError,
+}));
+vi.mock('../definitions/index.js', () => ({
+ loadDefinitions: async () => [{ id: 'recover_lost_citations', name: 'Recover Lost Citations' }],
+}));
+vi.mock('../from-prompt-improve.js', () => ({ IMPROVE_ACTION_KIND: 'prompt_improve' }));
+vi.mock('../from-opportunity.js', () => ({ OPPORTUNITY_ACTION_KIND: 'content_opportunity' }));
+
+const { isTouched, keepsTask, sweepActionTasks, writeTasksForAction } = await import('./index.js');
+
+const task = (over = {}) => ({
+ title: 'Add a 2026 shipping table to /blog/shipping',
+ where: 'acme.example/blog/shipping · lost on ChatGPT',
+ why: 'Cited #2 until Oct 12.',
+ how: ['Add a table.', 'Put "2026" in the title.'],
+ doneWhen: 'Cited again within 14 days.',
+ type: 'content',
+ effort: '~2h',
+ role: 'Content writer',
+ refs: ['page:1'],
+ ...over,
+});
+const answer = (tasks) => ({ object: { tasks }, usage: { inputTokens: 1000, outputTokens: 500 } });
+
+beforeEach(() => {
+ ops = [];
+ generateObject.mockReset();
+ enforceImproveQuota.mockReset();
+ process.env.ACTION_TASKS_AI = 'true';
+ db = {
+ actions: [
+ {
+ id: 'a1',
+ brand_id: 'b1',
+ kind: 'recover_lost_citations',
+ category: 'recover',
+ status: 'new',
+ payload: {},
+ },
+ ],
+ brands: [{ id: 'b1', name: 'Acme Coffee', description: null, organization_id: 'o1' }],
+ brand_domains: [{ brand_id: 'b1', domain: 'acme.example' }],
+ signals: [
+ {
+ id: 's1',
+ brand_id: 'b1',
+ kind: 'lost_citations',
+ status: 'new',
+ action_id: 'a1',
+ payload: {
+ promptId: 'p1',
+ promptText: 'Which coffee subscriptions ship internationally?',
+ lostUrls: [{ url: 'https://acme.example/blog/shipping', position: 2 }],
+ citedNow: [{ url: 'https://seriouseats.com/best', domain: 'seriouseats.com' }],
+ },
+ },
+ ],
+ action_tasks: [
+ {
+ id: 't1',
+ action_id: 'a1',
+ position: 1,
+ task_key: 'analyze_citations',
+ status: 'completed',
+ details: null,
+ },
+ {
+ id: 't2',
+ action_id: 'a1',
+ position: 2,
+ task_key: 'refresh_content',
+ status: 'in_progress',
+ details: null,
+ },
+ {
+ id: 't3',
+ action_id: 'a1',
+ position: 3,
+ task_key: 'prepare_outreach',
+ status: 'todo',
+ details: null,
+ },
+ { id: 't4', action_id: 'a1', position: 4, task_key: null, status: 'todo', details: null },
+ ],
+ };
+});
+
+describe('keepsTask', () => {
+ it('keeps work done or under way and what a person added; never the analysis', () => {
+ expect(keepsTask({ task_key: 'refresh_content', status: 'completed' })).toBe(true);
+ expect(keepsTask({ task_key: 'refresh_content', status: 'in_progress' })).toBe(true);
+ expect(keepsTask({ task_key: 'refresh_content', status: 'todo' })).toBe(false);
+ expect(keepsTask({ task_key: null, status: 'todo', details: null })).toBe(true);
+ expect(keepsTask({ task_key: null, status: 'todo', details: { source: 'ai' } })).toBe(false);
+ expect(keepsTask({ task_key: 'analyze_citations', status: 'completed' })).toBe(false);
+ expect(keepsTask({ task_key: 'validate_citations', status: 'in_progress' })).toBe(false);
+ });
+});
+
+describe('isTouched', () => {
+ it('reads a plan as untouched until someone works on it', () => {
+ const template = { task_key: 'refresh_content', title: null, status: 'todo', details: null };
+ expect(isTouched([template])).toBe(false);
+ expect(isTouched([{ ...template, status: 'in_progress' }])).toBe(true);
+ expect(isTouched([{ ...template, title: 'Refresh /pricing' }])).toBe(true);
+ expect(isTouched([{ task_key: null, title: 'Call G2', status: 'todo', details: null }])).toBe(
+ true,
+ );
+ expect(
+ isTouched([{ task_key: null, title: 'x', status: 'todo', details: { source: 'ai' } }]),
+ ).toBe(false);
+ });
+});
+
+describe('writeTasksForAction', () => {
+ it('asks once more for the refused tasks, then writes the kept and the written in order', async () => {
+ generateObject
+ .mockResolvedValueOnce(
+ answer([
+ task(),
+ task({ title: 'Refresh content for 7 prompts', refs: ['page:1'] }),
+ task({
+ title: 'Pitch acme to seriouseats.com',
+ where: 'seriouseats.com/best',
+ refs: ['domain:1'],
+ type: 'outreach',
+ }),
+ ]),
+ )
+ .mockResolvedValueOnce(
+ answer([task({ title: 'Link /blog/shipping from the pricing page', type: 'on_page' })]),
+ );
+
+ const result = await writeTasksForAction('a1', { trigger: 'regenerate', userId: 'u1' });
+
+ expect(result).toMatchObject({ status: 'written', kept: 2 });
+ expect(result.tasks.map((t) => t.title)).toEqual([
+ 'Add a 2026 shipping table to /blog/shipping',
+ 'Pitch acme to seriouseats.com',
+ 'Link /blog/shipping from the pricing page',
+ ]);
+ // The retry named what was refused and why.
+ expect(generateObject.mock.calls[1][0].prompt).toContain(
+ '"Refresh content for 7 prompts": the title counts prompts or pages instead of naming one',
+ );
+
+ const tasks = [...db.action_tasks].sort((a, b) => a.position - b.position);
+ expect(tasks.map((t) => [t.position, t.task_key ?? t.title ?? t.id])).toEqual([
+ [1, 'refresh_content'],
+ [2, 't4'],
+ [3, 'Add a 2026 shipping table to /blog/shipping'],
+ [4, 'Pitch acme to seriouseats.com'],
+ [5, 'Link /blog/shipping from the pricing page'],
+ ]);
+ expect(tasks[2].details).toMatchObject({ source: 'ai', type: 'content', refs: ['page:1'] });
+
+ const usage = ops.filter((op) => op.table === 'prompt_improve_usage');
+ expect(usage).toHaveLength(2);
+ expect(usage[0].payload).toMatchObject({ organization_id: 'o1', action_id: 'a1' });
+ expect(ops.find((op) => op.table === 'action_events').payload).toMatchObject({
+ event: 'tasks_generated',
+ data: { count: 3, kept: 2, trigger: 'regenerate' },
+ actor_id: 'u1',
+ });
+ expect(db.actions[0].tasks_generated_at).toEqual(expect.any(String));
+ });
+
+ it('writes and charges nothing on a dry run', async () => {
+ generateObject.mockResolvedValueOnce(answer([task()]));
+ const result = await writeTasksForAction('a1', { dryRun: true });
+ expect(result.status).toBe('preview');
+ expect(result.costUsd).toBeGreaterThan(0);
+ expect(ops).toEqual([]);
+ expect(enforceImproveQuota).not.toHaveBeenCalled();
+ });
+
+ it('calls no model when the signals name nothing to work on', async () => {
+ db.signals[0].payload = {};
+ const result = await writeTasksForAction('a1', { trigger: 'regenerate' });
+ expect(result).toMatchObject({ status: 'skipped', reason: 'no_targets' });
+ expect(generateObject).not.toHaveBeenCalled();
+ expect(db.actions[0].tasks_generated_at).toEqual(expect.any(String));
+ });
+
+ it('leaves the tasks as they are once the budget is spent', async () => {
+ enforceImproveQuota.mockRejectedValueOnce(new PlanLimitError('Budget used up'));
+ await expect(writeTasksForAction('a1', { trigger: 'regenerate' })).rejects.toThrow(
+ 'Budget used up',
+ );
+ expect(generateObject).not.toHaveBeenCalled();
+ expect(ops.filter((op) => op.table !== 'actions')).toEqual([]);
+ expect(db.actions[0].tasks_writing_since).toBeNull();
+ });
+
+ it('leaves a plan someone is working through to the night, and releases its claim', async () => {
+ const result = await writeTasksForAction('a1', { trigger: 'auto' });
+ expect(result).toMatchObject({ status: 'skipped', reason: 'in_use' });
+ expect(generateObject).not.toHaveBeenCalled();
+ expect(db.actions[0].tasks_writing_since).toBeNull();
+ });
+
+ it('refuses while another writer has the action', async () => {
+ db.actions[0].tasks_writing_since = new Date().toISOString();
+ await expect(writeTasksForAction('a1', { trigger: 'regenerate' })).rejects.toMatchObject({
+ code: 'busy',
+ status: 409,
+ });
+ expect(generateObject).not.toHaveBeenCalled();
+ });
+
+ it('refuses an action a person sent, which carries its own tasks', async () => {
+ db.actions[0].kind = 'prompt_improve';
+ await expect(writeTasksForAction('a1')).rejects.toThrow('carries the tasks it was sent with');
+ });
+});
+
+describe('sweepActionTasks', () => {
+ it('does nothing unless the deployment writes tasks', async () => {
+ process.env.ACTION_TASKS_AI = '';
+ expect(await sweepActionTasks()).toEqual({ skipped: 'disabled' });
+ });
+
+ it('skips the rest of a brand once its budget is spent', async () => {
+ db.actions.push({ ...db.actions[0], id: 'a2' });
+ db.action_tasks = [];
+ enforceImproveQuota.mockRejectedValue(new PlanLimitError('Budget used up'));
+ const outcome = await sweepActionTasks();
+ expect(outcome).toEqual({ written: 0, skipped: 0, failed: 1 });
+ expect(enforceImproveQuota).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/src/lib/action-center/task-writer/prompt.js b/server/src/lib/action-center/task-writer/prompt.js
new file mode 100644
index 000000000..8e0edaf8a
--- /dev/null
+++ b/server/src/lib/action-center/task-writer/prompt.js
@@ -0,0 +1,94 @@
+/**
+ * What the task writer asks the model for (AC-004), and the shape it must
+ * answer in. The rules mirror the quality check (quality.js): the model is
+ * told what will be refused, and refused tasks are asked for again with the
+ * reasons.
+ */
+
+import { z } from 'zod';
+import { MAX_TASKS } from './quality.js';
+
+/**
+ * Looser than the quality rule on purpose: a schema miss throws and costs a
+ * retry for the whole set, while a task that fails the rule is replaced on
+ * its own.
+ */
+export const writtenTaskSchema = z.object({
+ title: z.string().min(1).max(200),
+ where: z.string().max(300),
+ why: z.string().max(600),
+ how: z.array(z.string().max(300)).max(8),
+ doneWhen: z.string().max(300),
+ // A string, not the enum: one unknown type is one refused task (quality.js),
+ // not a schema miss that throws the whole answer away.
+ type: z.string().max(20),
+ effort: z.string().max(40),
+ role: z.string().max(60),
+ refs: z.array(z.string()).max(8),
+});
+
+export const taskWriterSchema = z.object({
+ tasks: z.array(writtenTaskSchema).max(MAX_TASKS + 2),
+});
+
+const SYSTEM = `You turn an AI-visibility action into a short list of concrete tasks a person can do this week.
+
+Every task answers five questions:
+- title (What): an imperative sentence naming its target, e.g. "Add a 2026 comparison table to /blog/best-tools". Never "… for 7 prompts" or "across 3 pages": one task, one target.
+- where: the exact page URL, prompt, platform, domain or competitor, from the evidence.
+- why: the evidence behind it, with its numbers (positions, dates, visits), from the evidence only.
+- how: 2 to 5 short steps, in order.
+- doneWhen: a measurable check, e.g. "the citation returns on 2 of 3 platforms within 14 days".
+Also: type (content, on_page, technical, outreach, pr or product), effort (e.g. "~2h") and role (e.g. "Content writer").
+
+Rules:
+- One task per page or domain. Prefer the targets with the most evidence.
+- Do not write analysis tasks (analyze, identify, review, validate, measure, monitor): the product already did that work and shows it to the user.
+- refs lists the evidence refs the task rests on (e.g. "page:1", "domain:2"). Use only refs that exist. The title or Where must name the target itself: a page by its URL or path, a domain or competitor by name, a prompt by quoting it.
+- Use only facts from the evidence. No placeholders, no generic SEO advice.
+- Write in English. At most ${MAX_TASKS} tasks.`;
+
+/**
+ * @param {{
+ * action: { name: string, category: string, title?: string },
+ * brand: { name: string, description?: string | null, domains: string[] },
+ * evidence: object,
+ * }} input evidence as `evidenceForPrompt` gives it
+ */
+export function buildTaskWriterPrompt({ action, brand, evidence }) {
+ const prompt = [
+ `Brand: ${brand.name}${brand.domains.length ? ` (${brand.domains.join(', ')})` : ''}`,
+ brand.description ? `About the brand: ${brand.description}` : null,
+ `Action: ${action.name} (category: ${action.category})`,
+ '',
+ 'Evidence (JSON):',
+ JSON.stringify(evidence),
+ '',
+ `Write up to ${MAX_TASKS} tasks.`,
+ ]
+ .filter((line) => line !== null)
+ .join('\n');
+ return { system: SYSTEM, prompt };
+}
+
+/**
+ * The second ask: replacements for the tasks the quality rule refused,
+ * without repeating the ones kept.
+ *
+ * @param {{ base: { system: string, prompt: string }, kept: object[],
+ * refused: { task: object, problems: string[] }[], count: number }} input
+ */
+export function buildRetryPrompt({ base, kept, refused, count }) {
+ const prompt = [
+ base.prompt,
+ '',
+ 'These tasks are already accepted; do not repeat them:',
+ ...kept.map((task) => `- ${task.title}`),
+ '',
+ 'These tasks were refused, with the reasons:',
+ ...refused.map(({ task, problems }) => `- "${task.title}": ${problems.join('; ')}`),
+ '',
+ `Write ${count} replacement task${count === 1 ? '' : 's'} that keep every rule.`,
+ ].join('\n');
+ return { system: base.system, prompt };
+}
diff --git a/server/src/lib/action-center/task-writer/quality.js b/server/src/lib/action-center/task-writer/quality.js
new file mode 100644
index 000000000..090ed0b5a
--- /dev/null
+++ b/server/src/lib/action-center/task-writer/quality.js
@@ -0,0 +1,90 @@
+/**
+ * The task writer's quality rule (AC-004).
+ *
+ * A written task is kept only when it is concrete: it names a target the
+ * action's evidence has, says where, how and when it is done, and is work a
+ * person does. A task that fails comes back with its reasons, so the model
+ * can be asked once more for a replacement (task-writer/index.js).
+ */
+
+import { promptWords } from './evidence.js';
+
+/** The most tasks an action gets. */
+export const MAX_TASKS = 6;
+
+export const TASK_TYPES = Object.freeze([
+ 'content',
+ 'on_page',
+ 'technical',
+ 'outreach',
+ 'pr',
+ 'product',
+]);
+
+/** "… for 7 prompts", "across 3 pages": a count where a target should be. */
+const COUNT_IN_TITLE =
+ /\b(?:for|across|on|in|to)\s+\d+\s+(?:prompts?|pages?|topics?|platforms?|competitors?|domains?|queries)\b/i;
+
+/** Analysis the product does itself and shows in the Affected tab. */
+const ANALYSIS_VERB =
+ /^(?:analy[sz]e|identify|validate|measure|monitor|review|investigate|assess|audit|evaluate|research|track|determine|look into)\b/i;
+
+const text = (value) => (typeof value === 'string' ? value.trim() : '');
+
+/**
+ * Why a task is not kept; empty when it is.
+ *
+ * @param {object} task as the model wrote it
+ * @param {{ byRef: Map<string, { labels: string[] }> }} evidence
+ * @returns {string[]}
+ */
+export function taskProblems(task, evidence) {
+ const problems = [];
+ const title = text(task?.title);
+ const where = text(task?.where);
+ const steps = (Array.isArray(task?.how) ? task.how : []).map(text).filter(Boolean);
+
+ if (!title) problems.push('it has no title');
+ if (!where) problems.push('Where is empty');
+ if (steps.length < 2 || steps.length > 5) problems.push('How needs 2 to 5 steps');
+ if (!text(task?.doneWhen)) problems.push('Done when is empty');
+ if (!TASK_TYPES.includes(task?.type)) problems.push('its type is not one of the six');
+ if (COUNT_IN_TITLE.test(title)) {
+ problems.push('the title counts prompts or pages instead of naming one');
+ }
+ if (ANALYSIS_VERB.test(title)) {
+ problems.push('it is analysis, which the product does itself; write the change to make');
+ }
+
+ const refs = (Array.isArray(task?.refs) ? task.refs : []).map(text);
+ const known = refs.filter((ref) => evidence.byRef.has(ref));
+ if (known.length === 0) {
+ problems.push('it cites none of the evidence refs');
+ } else if (known.length < refs.length) {
+ problems.push(
+ `it cites refs the evidence does not have (${refs.filter((r) => !evidence.byRef.has(r)).join(', ')})`,
+ );
+ } else if (!known.some((ref) => names(`${title} ${where}`, evidence.byRef.get(ref)))) {
+ problems.push('neither the title nor Where names its target');
+ }
+ return problems;
+}
+
+/**
+ * Whether a text names an entity: a page by its URL or path, a domain or a
+ * competitor by name, a prompt by its first words in order (quoted or not,
+ * whatever the punctuation).
+ */
+function names(text, entity) {
+ if (entity.words?.length) {
+ return ` ${promptWords(text).join(' ')} `.includes(` ${entity.words.join(' ')} `);
+ }
+ const lower = text.toLowerCase();
+ return (entity.labels ?? []).some((label) => label && lower.includes(label.toLowerCase()));
+}
+
+/** Tasks that say the same thing twice are one task. */
+export function sameTask(a, b) {
+ const norm = (value) => text(value).toLowerCase().replace(/\s+/g, ' ');
+ return norm(a.title) === norm(b.title);
+}
diff --git a/server/src/lib/action-center/task-writer/quality.test.js b/server/src/lib/action-center/task-writer/quality.test.js
new file mode 100644
index 000000000..00e46627f
--- /dev/null
+++ b/server/src/lib/action-center/task-writer/quality.test.js
@@ -0,0 +1,121 @@
+import { describe, expect, it } from 'vitest';
+import { buildEvidence } from './evidence.js';
+import { sameTask, taskProblems } from './quality.js';
+
+const evidence = buildEvidence([
+ {
+ id: 's1',
+ kind: 'lost_citations',
+ payload: {
+ promptId: 'p1',
+ promptText: 'Which coffee subscriptions ship internationally?',
+ lostUrls: [{ url: 'https://acme.example/blog/shipping', position: 2 }],
+ citedNow: [{ url: 'https://seriouseats.com/best', domain: 'seriouseats.com' }],
+ },
+ },
+]);
+
+const good = {
+ title: 'Add a 2026 shipping table to /blog/shipping',
+ where: 'acme.example/blog/shipping · lost on ChatGPT',
+ why: 'Cited #2 until Oct 12; seriouseats.com now has a dated table.',
+ how: ['Add a table of countries and costs.', 'Put "2026" in the title.'],
+ doneWhen: 'Cited again on ChatGPT within 14 days.',
+ type: 'content',
+ effort: '~2h',
+ role: 'Content writer',
+ refs: ['page:1', 'domain:1'],
+};
+
+describe('taskProblems', () => {
+ it('keeps a concrete task', () => {
+ expect(taskProblems(good, evidence)).toEqual([]);
+ });
+
+ it('refuses a title that counts instead of naming', () => {
+ expect(taskProblems({ ...good, title: 'Refresh content for 7 prompts' }, evidence)).toContain(
+ 'the title counts prompts or pages instead of naming one',
+ );
+ expect(
+ taskProblems({ ...good, title: 'Improve /blog/shipping across 3 pages' }, evidence),
+ ).toContain('the title counts prompts or pages instead of naming one');
+ });
+
+ it('refuses analysis the product does itself', () => {
+ expect(
+ taskProblems({ ...good, title: 'Analyze citations on /blog/shipping' }, evidence),
+ ).toContain('it is analysis, which the product does itself; write the change to make');
+ });
+
+ it('needs where, 2 to 5 steps, done-when and a known type', () => {
+ expect(
+ taskProblems(
+ { ...good, where: ' ', how: ['One step.'], doneWhen: '', type: 'marketing' },
+ evidence,
+ ),
+ ).toEqual([
+ 'Where is empty',
+ 'How needs 2 to 5 steps',
+ 'Done when is empty',
+ 'its type is not one of the six',
+ ]);
+ });
+
+ it('needs refs the evidence has, and its target named', () => {
+ expect(taskProblems({ ...good, refs: [] }, evidence)).toEqual([
+ 'it cites none of the evidence refs',
+ ]);
+ expect(taskProblems({ ...good, refs: ['page:1', 'page:9'] }, evidence)).toEqual([
+ 'it cites refs the evidence does not have (page:9)',
+ ]);
+ expect(
+ taskProblems({ ...good, title: 'Rewrite the shipping guide', where: 'Your blog' }, evidence),
+ ).toEqual(['neither the title nor Where names its target']);
+ });
+});
+
+describe('a task aimed at a prompt', () => {
+ const prompts = buildEvidence([
+ {
+ id: 's2',
+ kind: 'uncited_mentions',
+ payload: {
+ mentions: [
+ {
+ promptId: 'p9',
+ promptText: 'What are the best coffee subscriptions in 2026?',
+ platforms: ['gemini-web'],
+ },
+ ],
+ },
+ },
+ ]);
+ const aimed = {
+ ...good,
+ title: 'Publish a buyer guide that cites acme.example',
+ refs: ['prompt:1'],
+ };
+
+ it('names the prompt by its first words, whatever the quotes and case', () => {
+ expect(
+ taskProblems(
+ { ...aimed, where: 'Gemini · "what are the BEST coffee subscriptions" prompt' },
+ prompts,
+ ),
+ ).toEqual([]);
+ });
+
+ it('does not count a paraphrase as naming it', () => {
+ expect(
+ taskProblems({ ...aimed, where: 'Gemini · prompts about coffee subscriptions' }, prompts),
+ ).toEqual(['neither the title nor Where names its target']);
+ });
+});
+
+describe('sameTask', () => {
+ it('reads two titles that differ only in case and spacing as one', () => {
+ expect(
+ sameTask(good, { ...good, title: ' add a 2026 SHIPPING table to /blog/shipping ' }),
+ ).toBe(true);
+ });
+});
diff --git a/server/src/lib/signals/pass.js b/server/src/lib/signals/pass.js
index 490c53771..a74887184 100644
--- a/server/src/lib/signals/pass.js
+++ b/server/src/lib/signals/pass.js
@@ -22,6 +22,7 @@ import supabaseAdmin from '../../config/supabase.js';
import { logger } from '../logger.js';
import { recordSignalsForBrand } from './record.js';
import { generateActionsForBrand } from '../action-center/generate.js';
+import { sweepActionTasks } from '../action-center/task-writer/index.js';
/**
* How far back the sweep looks. Long enough to cover a missed night plus the
@@ -81,6 +82,14 @@ export async function runSignalPass(brandId, { runAt, now = new Date() } = {}) {
);
if (error) throw new Error(error.message);
+ // Tonight's new actions get their tasks written (AC-004) without holding up
+ // the pass: a slow or failed model call costs only the template tasks.
+ if (generated?.created > 0) {
+ sweepActionTasks({ brandId, now }).catch((err) => {
+ logger.error({ err, brandId }, '[task-writer] sweep after the pass crashed');
+ });
+ }
+
return { trackingRunAt, signals: recorded, actions: generated };
}
diff --git a/server/src/routes/action-center-tasks.test.js b/server/src/routes/action-center-tasks.test.js
new file mode 100644
index 000000000..a09f7c0a8
--- /dev/null
+++ b/server/src/routes/action-center-tasks.test.js
@@ -0,0 +1,91 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * "Regenerate tasks" (AC-004): off unless the deployment writes tasks,
+ * checked against the caller's organization first, and a rewrite that wrote
+ * nothing says why.
+ */
+
+let action;
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: () => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ maybeSingle: async () => ({ data: action, error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+
+const assertBrandAccess = vi.fn();
+vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => assertBrandAccess(...args) }));
+vi.mock('../lib/action-center/priority-data.js', () => ({ rescoreActionsForSignal: vi.fn() }));
+
+let enabled;
+const writeTasksForAction = vi.fn();
+class TaskWriterError extends Error {
+ constructor(code, message, status = 422) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ }
+}
+class PlanLimitError extends Error {}
+vi.mock('../lib/plan-guard.js', () => ({ PlanLimitError }));
+vi.mock('../lib/action-center/task-writer/index.js', () => ({
+ TaskWriterError,
+ isTaskWriterEnabled: () => enabled,
+ writeTasksForAction: (...args) => writeTasksForAction(...args),
+}));
+
+const { regenerateTasks } = await import('./action-center.js');
+
+beforeEach(() => {
+ enabled = true;
+ action = { id: 'a1', brand_id: 'b1' };
+ assertBrandAccess.mockReset();
+ writeTasksForAction.mockReset();
+});
+
+describe('regenerateTasks', () => {
+ it('is not found while the deployment does not write tasks', async () => {
+ enabled = false;
+ await expect(regenerateTasks('a1', 'u1')).rejects.toMatchObject({
+ status: 404,
+ code: 'disabled',
+ });
+ expect(writeTasksForAction).not.toHaveBeenCalled();
+ });
+
+ it("checks the caller's access before writing anything", async () => {
+ assertBrandAccess.mockRejectedValueOnce(Object.assign(new Error('Forbidden'), { status: 403 }));
+ await expect(regenerateTasks('a1', 'u1')).rejects.toThrow('Forbidden');
+ expect(assertBrandAccess).toHaveBeenCalledWith('b1', 'u1');
+ expect(writeTasksForAction).not.toHaveBeenCalled();
+ });
+
+ it('writes as the caller and says how many were written and kept', async () => {
+ writeTasksForAction.mockResolvedValueOnce({ status: 'written', tasks: [{}, {}, {}], kept: 2 });
+ expect(await regenerateTasks('a1', 'u1')).toEqual({ written: 3, kept: 2 });
+ expect(writeTasksForAction).toHaveBeenCalledWith('a1', { trigger: 'regenerate', userId: 'u1' });
+ });
+
+ it('says why nothing was written', async () => {
+ writeTasksForAction.mockResolvedValueOnce({ status: 'skipped', reason: 'no_targets' });
+ await expect(regenerateTasks('a1', 'u1')).rejects.toMatchObject({
+ status: 422,
+ code: 'no_targets',
+ });
+ });
+
+ it('says the budget is spent, as a code the drawer words', async () => {
+ writeTasksForAction.mockRejectedValueOnce(new PlanLimitError('Budget used up'));
+ await expect(regenerateTasks('a1', 'u1')).rejects.toMatchObject({
+ status: 429,
+ code: 'budget',
+ });
+ });
+});
diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.js
index f648e5a4a..7d8f13734 100644
--- a/server/src/routes/action-center.js
+++ b/server/src/routes/action-center.js
@@ -3,6 +3,12 @@ import { z } from 'zod';
import supabaseAdmin from '../config/supabase.js';
import { assertBrandAccess } from '../lib/access.js';
import { rescoreActionsForSignal } from '../lib/action-center/priority-data.js';
+import { PlanLimitError } from '../lib/plan-guard.js';
+import {
+ TaskWriterError,
+ isTaskWriterEnabled,
+ writeTasksForAction,
+} from '../lib/action-center/task-writer/index.js';
const router = Router();
@@ -46,4 +52,58 @@ router.post('/signals/:id/rescore', async (req, res) => {
}
});
+/** Why a rewrite wrote nothing, for logs and the API; the drawer words the code. */
+const NOTHING_WRITTEN = {
+ no_targets: 'This action names no page, prompt or domain to write tasks about.',
+ no_valid_tasks: "The written tasks didn't pass the quality check.",
+};
+
+/**
+ * Writes an action's tasks again from its evidence (AC-004), keeping the done,
+ * under-way and hand-added ones. Off unless the deployment writes tasks.
+ *
+ * @returns {Promise<{ written: number, kept: number }>}
+ */
+export async function regenerateTasks(actionId, userId) {
+ if (!isTaskWriterEnabled()) {
+ throw new TaskWriterError('disabled', 'Writing tasks is not turned on.', 404);
+ }
+ const { data: action } = await supabaseAdmin
+ .from('actions')
+ .select('id, brand_id')
+ .eq('id', actionId)
+ .maybeSingle();
+ if (!action) throw new TaskWriterError('not_found', 'Action not found', 404);
+ await assertBrandAccess(action.brand_id, userId);
+
+ let result;
+ try {
+ result = await writeTasksForAction(actionId, { trigger: 'regenerate', userId });
+ } catch (err) {
+ // The month's AI budget, shared with the Improve tab, is spent.
+ if (err instanceof PlanLimitError) throw new TaskWriterError('budget', err.message, 429);
+ throw err;
+ }
+ if (result.status !== 'written') {
+ throw new TaskWriterError(result.reason, NOTHING_WRITTEN[result.reason]);
+ }
+ return { written: result.tasks.length, kept: result.kept };
+}
+
+/** POST /api/action-center/actions/:id/tasks/regenerate */
+router.post('/actions/:id/tasks/regenerate', async (req, res) => {
+ const id = signalIdSchema.safeParse(req.params.id);
+ if (!id.success) return res.status(400).json({ error: 'Invalid action id' });
+ try {
+ return res.json(await regenerateTasks(id.data, req.user.id));
+ } catch (error) {
+ const status = error.status;
+ if (!status) req.log.error({ err: error }, 'regenerate action tasks error');
+ return res.status(status || 500).json({
+ error: status ? error.message : 'Failed to write the tasks.',
+ code: error.code ?? null,
+ });
+ }
+});
+
export default router;
diff --git a/server/src/scripts/review-action-tasks.js b/server/src/scripts/review-action-tasks.js
new file mode 100644
index 000000000..c30c36bd8
--- /dev/null
+++ b/server/src/scripts/review-action-tasks.js
@@ -0,0 +1,90 @@
+/**
+ * The AC-004 review set: what the task writer would write for recent
+ * actions, as one Markdown file product can read before any brand gets
+ * written tasks (ACTION_TASKS_AI stays off until then).
+ *
+ * A dry run: nothing is written to an action and nothing is charged to an
+ * organization's budget. The model calls are real, so the run costs what the
+ * report's total says.
+ *
+ * Run: node src/scripts/review-action-tasks.js [--limit 20] [--brand <brandId>] [--out file.md]
+ */
+import 'dotenv/config';
+import { writeFileSync } from 'node:fs';
+import supabaseAdmin from '../config/supabase.js';
+import { IMPROVE_ACTION_KIND } from '../lib/action-center/from-prompt-improve.js';
+import { OPPORTUNITY_ACTION_KIND } from '../lib/action-center/from-opportunity.js';
+import { taskWriterModelId, writeTasksForAction } from '../lib/action-center/task-writer/index.js';
+
+const arg = (name) => {
+ const i = process.argv.indexOf(`--${name}`);
+ return i > 0 ? process.argv[i + 1] : undefined;
+};
+const limit = Number(arg('limit') ?? 20);
+const brandId = arg('brand');
+const out = arg('out') ?? `action-task-review-${new Date().toISOString().slice(0, 10)}.md`;
+
+let query = supabaseAdmin
+ .from('actions')
+ .select('id, action_no, kind, category, brands!inner(name)')
+ .not('status', 'in', '("completed","dismissed")')
+ .not('kind', 'in', `("${IMPROVE_ACTION_KIND}","${OPPORTUNITY_ACTION_KIND}")`)
+ .order('created_at', { ascending: false })
+ .limit(limit);
+if (brandId) query = query.eq('brand_id', brandId);
+const { data: actions, error } = await query;
+if (error) throw new Error(error.message);
+
+const lines = [
+ `# AC-004 review set`,
+ '',
+ `Model: ${taskWriterModelId()} · ${actions.length} actions · ${new Date().toISOString()}`,
+ '',
+];
+let total = 0;
+
+for (const action of actions) {
+ process.stdout.write(`AC-${action.action_no} ${action.kind} … `);
+ lines.push(`## AC-${action.action_no} · ${action.brands.name} · ${action.kind}`, '');
+ try {
+ const result = await writeTasksForAction(action.id, { dryRun: true, trigger: 'review' });
+ total += result.costUsd;
+ if (result.status === 'skipped') {
+ lines.push(`_Nothing written: ${result.reason}._`, '');
+ console.log(result.reason);
+ continue;
+ }
+ console.log(`${result.tasks.length} tasks, ${result.refused.length} refused`);
+ const e = result.evidence;
+ lines.push(
+ `Evidence: ${e.pages.length} pages, ${e.prompts.length} prompts, ${e.domains.length} domains, ${e.competitors.length} competitors · $${result.costUsd.toFixed(4)}`,
+ '',
+ );
+ result.tasks.forEach((task, i) => {
+ lines.push(
+ `${i + 1}. **${task.title}** · ${task.type}`,
+ ` - Where: ${task.where}`,
+ ` - Why: ${task.why}`,
+ ` - How: ${task.how.map((step, n) => `${n + 1}) ${step}`).join(' ')}`,
+ ` - Done when: ${task.doneWhen}`,
+ ` - Effort: ${[task.effort, task.role].filter(Boolean).join(' · ')}`,
+ ` - Refs: ${task.refs.join(', ')}`,
+ );
+ });
+ if (result.refused.length) {
+ lines.push('', 'Refused:');
+ for (const { task, problems } of result.refused) {
+ lines.push(`- ~~${task.title}~~: ${problems.join('; ')}`);
+ }
+ }
+ lines.push('');
+ } catch (err) {
+ console.log(`failed: ${err.message}`);
+ lines.push(`_Failed: ${err.message}_`, '');
+ }
+}
+
+lines.splice(3, 0, `Total model cost: $${total.toFixed(4)}`, '');
+writeFileSync(out, lines.join('\n'));
+console.log(`\nWrote ${out} · $${total.toFixed(4)}`);
+process.exit(0);
diff --git a/server/src/server.js b/server/src/server.js
index 5dd7942ec..cd46e68ea 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -41,6 +41,7 @@ import { runPageOpportunityDetection } from './lib/page-opportunities.js';
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 { sendHealthReport } from './lib/health/report.js';
import { checkPromptUsageCounters } from './lib/prompt-usage-counters.js';
@@ -156,6 +157,13 @@ async function runDailyTracking() {
logger.error({ err }, '[task-run] sweep crashed');
});
+ // Write the tasks of recent actions whose writing a pass missed (AC-004):
+ // the budget was spent, the model failed, or the process restarted.
+ // Bounded per sweep; a no-op unless ACTION_TASKS_AI is on.
+ sweepActionTasks().catch((err) => {
+ logger.error({ err }, '[task-writer] 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/supabase/migrations/00150_action_task_writer.sql b/supabase/migrations/00150_action_task_writer.sql
new file mode 100644
index 000000000..2d0442741
--- /dev/null
+++ b/supabase/migrations/00150_action_task_writer.sql
@@ -0,0 +1,35 @@
+-- AC-004: an action's tasks written by a model from the action's evidence.
+--
+-- The writing is metered like the Improve tab's suggestions, from the same
+-- monthly budget: each attempt is a prompt_improve_usage row, which now says
+-- which action it wrote tasks for. And an action records when its tasks were
+-- written, so the nightly sweep writes each one once.
+
+alter table public.prompt_improve_usage
+ add column if not exists action_id uuid references public.actions(id) on delete set null;
+
+comment on column public.prompt_improve_usage.action_id is
+ 'The action whose tasks this generation wrote (AC-004). Null for an Improve tab generation, which names its prompt.';
+
+alter table public.actions
+ add column if not exists tasks_generated_at timestamptz;
+
+comment on column public.actions.tasks_generated_at is
+ 'When a model last wrote this action''s tasks from its evidence (AC-004), or found nothing it could write. Null until then; the nightly sweep writes the ones still null.';
+
+-- Held while a writer works on an action, so the nightly sweep and a
+-- person's "Regenerate tasks" never write the same action at once. A claim
+-- older than a few minutes is a writer that died and may be taken over.
+alter table public.actions
+ add column if not exists tasks_writing_since timestamptz;
+
+comment on column public.actions.tasks_writing_since is
+ 'When a task writer (AC-004) started on this action; null when none is. Claimed and released by the writer.';
+
+-- The sweep's read: recent actions still waiting for their tasks.
+create index if not exists actions_tasks_pending_idx
+ on public.actions (created_at)
+ where tasks_generated_at is null;
+
+comment on column public.action_tasks.details is
+ 'What a task carries beyond its title: where, why, how, doneWhen, type, effort and role (AC-004), and for a task sent from the Improve tab its body, platform, platformLabel and sources (PROMPT-004). A written task also records source = ''ai'' and the evidence refs it rests on.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index c86f7f33b..d5d4728e9 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -18992,6 +18992,45 @@ grant execute on function public.insights_same_prompt_compare(
uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid
) to authenticated, service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00150_action_task_writer.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- AC-004: an action's tasks written by a model from the action's evidence.
+--
+-- The writing is metered like the Improve tab's suggestions, from the same
+-- monthly budget: each attempt is a prompt_improve_usage row, which now says
+-- which action it wrote tasks for. And an action records when its tasks were
+-- written, so the nightly sweep writes each one once.
+
+alter table public.prompt_improve_usage
+ add column if not exists action_id uuid references public.actions(id) on delete set null;
+
+comment on column public.prompt_improve_usage.action_id is
+ 'The action whose tasks this generation wrote (AC-004). Null for an Improve tab generation, which names its prompt.';
+
+alter table public.actions
+ add column if not exists tasks_generated_at timestamptz;
+
+comment on column public.actions.tasks_generated_at is
+ 'When a model last wrote this action''s tasks from its evidence (AC-004), or found nothing it could write. Null until then; the nightly sweep writes the ones still null.';
+
+-- Held while a writer works on an action, so the nightly sweep and a
+-- person's "Regenerate tasks" never write the same action at once. A claim
+-- older than a few minutes is a writer that died and may be taken over.
+alter table public.actions
+ add column if not exists tasks_writing_since timestamptz;
+
+comment on column public.actions.tasks_writing_since is
+ 'When a task writer (AC-004) started on this action; null when none is. Claimed and released by the writer.';
+
+-- The sweep's read: recent actions still waiting for their tasks.
+create index if not exists actions_tasks_pending_idx
+ on public.actions (created_at)
+ where tasks_generated_at is null;
+
+comment on column public.action_tasks.details is
+ 'What a task carries beyond its title: where, why, how, doneWhen, type, effort and role (AC-004), and for a task sent from the Improve tab its body, platform, platformLabel and sources (PROMPT-004). A written task also records source = ''ai'' and the evidence refs it rests on.';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00152_insights_topic_competitors_definer.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/.env.example b/web/.env.example
index 8709e3c70..55e182ac1 100644
--- a/web/.env.example
+++ b/web/.env.example
@@ -53,6 +53,12 @@ NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
# -----------------------------------------------------------------------------
NEXT_PUBLIC_IS_CLOUD=false
+# -----------------------------------------------------------------------------
+# Action Center: show "Regenerate tasks" in an action's Tasks tab (AC-004).
+# Set to "true" together with the server's ACTION_TASKS_AI.
+# -----------------------------------------------------------------------------
+NEXT_PUBLIC_ACTION_TASKS_AI=
+
# -----------------------------------------------------------------------------
# AEO Server (backend API)
# -----------------------------------------------------------------------------
diff --git a/web/messages/en.json b/web/messages/en.json
index a72a830f2..a8405f183 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1145,6 +1145,7 @@
"task_renamed": "Task renamed to “{title}”",
"task_deleted": "Task deleted",
"task_edited": "Task edited",
+ "tasks_generated": "{count, plural, one {# task} other {# tasks}} written from the action's evidence",
"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",
@@ -1160,6 +1161,27 @@
"skipReasonPlaceholder": "e.g. handled elsewhere, no longer relevant",
"skipConfirm": "Skip task",
"skipCancel": "Cancel",
+ "regenerate": {
+ "button": "Regenerate tasks",
+ "confirm": "Write this action's tasks again from its evidence? Done, under-way and hand-added tasks stay.",
+ "confirmButton": "Regenerate",
+ "cancel": "Cancel",
+ "busy": "Writing tasks…",
+ "done": "{count, plural, one {# task written} other {# tasks written}}",
+ "timeout": "Writing the tasks took too long. Please try again.",
+ "unreachable": "Couldn't reach the server. Please try again.",
+ "unauthenticated": "Your session has ended. Please sign in again.",
+ "errors": {
+ "disabled": "Writing tasks isn't turned on for this workspace.",
+ "not_found": "This action no longer exists.",
+ "sent": "This action keeps the tasks it was sent with.",
+ "closed": "This action is closed.",
+ "busy": "This action's tasks are already being written. Try again in a minute.",
+ "no_targets": "This action names no page, prompt or domain to write tasks about.",
+ "no_valid_tasks": "None of the written tasks passed the quality check. Please try again.",
+ "budget": "Writing tasks uses this month's AI budget, which is used up or not part of your plan."
+ }
+ },
"task": {
"showDetails": "Show details",
"hideDetails": "Hide details",
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index c16e44a6c..7e4807ef4 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -75,6 +75,7 @@ import { ImproveContext } from './improve-context';
import { TopicGapContext } from './topic-gap-context';
import { TopicOpportunityContext } from './topic-opportunity-context';
import { TaskDetailForm, TaskDetailView, TaskTypeBadge } from './task-detail';
+import { RegenerateTasks, taskWriterEnabled } from './regenerate-tasks';
import { hasTaskSpec, type TaskDetailsEdit } from '@/lib/action-center/task-details';
import { ImproveOutcomeCard } from './improve-outcome-card';
import { improvePlatformLabels } from '@/lib/improve-outcome';
@@ -545,6 +546,24 @@ export function ActionDrawer({
t={t}
onAdd={(title) => void mutate(() => addTask(brandId, action.id, title))}
/>
+ {/* Written from the action's evidence (AC-004): not for an
+ action a person sent, which carries its own, nor a closed one. */}
+ {taskWriterEnabled() &&
+ action.kind !== 'prompt_improve' &&
+ !opportunityId &&
+ action.status !== 'completed' &&
+ action.status !== 'dismissed' &&
+ detail.signals.length > 0 && (
+ <RegenerateTasks
+ actionId={action.id}
+ disabled={isBusy}
+ onBusyChange={setIsBusy}
+ onDone={async () => {
+ await load();
+ onChanged();
+ }}
+ />
+ )}
</section>
) : tab === 'signals' ? (
<section className="space-y-2">
diff --git a/web/src/components/action-center/regenerate-tasks.test.tsx b/web/src/components/action-center/regenerate-tasks.test.tsx
new file mode 100644
index 000000000..d8057a49c
--- /dev/null
+++ b/web/src/components/action-center/regenerate-tasks.test.tsx
@@ -0,0 +1,107 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+
+const { toast, regenerate } = vi.hoisted(() => ({
+ toast: { success: vi.fn(), error: vi.fn() },
+ regenerate: vi.fn(),
+}));
+vi.mock('sonner', () => ({ toast }));
+vi.mock('@/lib/actions/action-task-writer', () => ({ regenerateActionTasks: regenerate }));
+
+const { RegenerateTasks } = await import('./regenerate-tasks');
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+function render(node: React.ReactNode) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ {node}
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const button = (name: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === name)!;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ regenerate.mockReset();
+ toast.success.mockReset();
+ toast.error.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('RegenerateTasks', () => {
+ it('asks first, saying what stays, then writes and reloads', async () => {
+ regenerate.mockResolvedValueOnce({ written: 4, kept: 1 });
+ const onDone = vi.fn();
+ const onBusyChange = vi.fn();
+ render(
+ <RegenerateTasks
+ actionId="a1"
+ disabled={false}
+ onBusyChange={onBusyChange}
+ onDone={onDone}
+ />,
+ );
+
+ act(() => button('Regenerate tasks').click());
+ expect(container.textContent).toContain('Done, under-way and hand-added tasks stay.');
+ expect(regenerate).not.toHaveBeenCalled();
+
+ await act(async () => button('Regenerate').click());
+ expect(regenerate).toHaveBeenCalledWith('a1');
+ expect(toast.success).toHaveBeenCalledWith('4 tasks written');
+ expect(onDone).toHaveBeenCalled();
+ // The rest of the tab waited while the tasks were rewritten.
+ expect(onBusyChange.mock.calls).toEqual([[true], [false]]);
+ });
+
+ it("words the server's reason, and a timeout", async () => {
+ render(
+ <RegenerateTasks actionId="a1" disabled={false} onBusyChange={() => {}} onDone={() => {}} />,
+ );
+
+ regenerate.mockResolvedValueOnce({
+ error: 'server',
+ code: 'budget',
+ message: 'Budget used up',
+ });
+ act(() => button('Regenerate tasks').click());
+ await act(async () => button('Regenerate').click());
+ expect(toast.error).toHaveBeenCalledWith(
+ "Writing tasks uses this month's AI budget, which is used up or not part of your plan.",
+ );
+
+ // A reason this build has no words for reads as the server wrote it.
+ regenerate.mockResolvedValueOnce({ error: 'server', code: null, message: 'Server error: 502' });
+ act(() => button('Regenerate tasks').click());
+ await act(async () => button('Regenerate').click());
+ expect(toast.error).toHaveBeenLastCalledWith('Server error: 502');
+
+ regenerate.mockResolvedValueOnce({ error: 'timeout' });
+ act(() => button('Regenerate tasks').click());
+ await act(async () => button('Regenerate').click());
+ expect(toast.error).toHaveBeenLastCalledWith(
+ 'Writing the tasks took too long. Please try again.',
+ );
+ });
+});
diff --git a/web/src/components/action-center/regenerate-tasks.tsx b/web/src/components/action-center/regenerate-tasks.tsx
new file mode 100644
index 000000000..d69a12afb
--- /dev/null
+++ b/web/src/components/action-center/regenerate-tasks.tsx
@@ -0,0 +1,123 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Loader2, RefreshCw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { regenerateActionTasks } from '@/lib/actions/action-task-writer';
+
+/** Whether this deployment writes tasks (AC-004); the server has its own switch. */
+export function taskWriterEnabled(): boolean {
+ return process.env.NEXT_PUBLIC_ACTION_TASKS_AI === 'true';
+}
+
+/** Server reasons this build has words for (actionsPage.drawer.regenerate.errors). */
+const KNOWN_ERRORS = [
+ 'disabled',
+ 'not_found',
+ 'sent',
+ 'closed',
+ 'busy',
+ 'no_targets',
+ 'no_valid_tasks',
+ 'budget',
+];
+
+/**
+ * "Regenerate tasks" (AC-004): the action's tasks written again from its
+ * evidence. It replaces work on the list, so it asks first, and it says what
+ * stays.
+ */
+export function RegenerateTasks({
+ actionId,
+ disabled,
+ onBusyChange,
+ onDone,
+}: {
+ actionId: string;
+ disabled: boolean;
+ /** The rest of the tab waits while the tasks are rewritten: an edit made meanwhile would be lost. */
+ onBusyChange: (busy: boolean) => void;
+ /** Called once the new tasks are written, to reload them. */
+ onDone: () => void | Promise<void>;
+}) {
+ const t = useTranslations('actionCenter.actionsPage.drawer.regenerate');
+ const [confirming, setConfirming] = useState(false);
+ const [busy, setBusy] = useState(false);
+
+ const run = async () => {
+ setBusy(true);
+ onBusyChange(true);
+ try {
+ const result = await regenerateActionTasks(actionId);
+ if ('written' in result) {
+ toast.success(t('done', { count: result.written }));
+ await onDone();
+ } else {
+ toast.error(
+ result.error !== 'server'
+ ? t(result.error)
+ : result.code && KNOWN_ERRORS.includes(result.code)
+ ? t(`errors.${result.code}`)
+ : result.message,
+ );
+ }
+ } finally {
+ setBusy(false);
+ setConfirming(false);
+ onBusyChange(false);
+ }
+ };
+
+ if (busy) {
+ return (
+ <p className="mt-3 flex items-center justify-center gap-1.5 text-xs text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ {t('busy')}
+ </p>
+ );
+ }
+
+ if (confirming) {
+ return (
+ <div className="mt-3 space-y-2 rounded-md border bg-muted/30 px-3 py-2">
+ <p className="text-xs">{t('confirm')}</p>
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ size="sm"
+ disabled={disabled}
+ onClick={() => void run()}
+ className="h-7 text-xs"
+ >
+ {t('confirmButton')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ onClick={() => setConfirming(false)}
+ className="h-7 text-xs"
+ >
+ {t('cancel')}
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={() => setConfirming(true)}
+ className="mt-2 h-8 w-full text-xs"
+ >
+ <RefreshCw className="mr-1.5 h-3.5 w-3.5" />
+ {t('button')}
+ </Button>
+ );
+}
diff --git a/web/src/lib/actions/action-task-writer.test.ts b/web/src/lib/actions/action-task-writer.test.ts
new file mode 100644
index 000000000..56342ec5e
--- /dev/null
+++ b/web/src/lib/actions/action-task-writer.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+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 { regenerateActionTasks } = await import('./action-task-writer');
+
+const respond = (status: number, body: unknown) =>
+ vi.fn(async () => new Response(JSON.stringify(body), { status }));
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ session = { access_token: 'token' };
+});
+
+describe('regenerateActionTasks', () => {
+ it('posts as the user and returns what was written and kept', async () => {
+ const fetch = respond(200, { written: 5, kept: 2 });
+ vi.stubGlobal('fetch', fetch);
+ expect(await regenerateActionTasks('a1')).toEqual({ written: 5, kept: 2 });
+ const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit];
+ expect(url).toBe('https://api.example/api/action-center/actions/a1/tasks/regenerate');
+ expect(init.headers).toEqual({ Authorization: 'Bearer token' });
+ });
+
+ it("returns the server's reason rather than throwing", async () => {
+ vi.stubGlobal('fetch', respond(429, { error: 'Budget used up', code: 'budget' }));
+ expect(await regenerateActionTasks('a1')).toEqual({
+ error: 'server',
+ code: 'budget',
+ message: 'Budget used up',
+ });
+ });
+
+ it('tells a timeout from a server it could not reach', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw Object.assign(new Error('slow'), { name: 'TimeoutError' });
+ }),
+ );
+ expect(await regenerateActionTasks('a1')).toEqual({ error: 'timeout' });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new TypeError('fetch failed');
+ }),
+ );
+ expect(await regenerateActionTasks('a1')).toEqual({ error: 'unreachable' });
+ });
+
+ it('asks for a session first', async () => {
+ session = null;
+ expect(await regenerateActionTasks('a1')).toEqual({ error: 'unauthenticated' });
+ });
+});
diff --git a/web/src/lib/actions/action-task-writer.ts b/web/src/lib/actions/action-task-writer.ts
new file mode 100644
index 000000000..aae942c7e
--- /dev/null
+++ b/web/src/lib/actions/action-task-writer.ts
@@ -0,0 +1,52 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+import { API_BASE_URL } from '@/config/api';
+
+/**
+ * What a rewrite of an action's tasks came to (AC-004). A failure comes back
+ * as a value, not a throw, so the drawer can say why — the budget is spent,
+ * nothing passed the quality check — instead of the masked production
+ * digest. `code` is the server's reason, which the drawer words; `message`
+ * is its English text, for a reason this build has no words for.
+ */
+export type RegenerateTasksResult =
+ | { written: number; kept: number }
+ | { error: 'server'; code: string | null; message: string }
+ | { error: 'timeout' | 'unreachable' | 'unauthenticated' };
+
+/** Write the action's tasks again from its evidence, on the server. */
+export async function regenerateActionTasks(actionId: string): Promise<RegenerateTasksResult> {
+ 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/actions/${actionId}/tasks/regenerate`,
+ {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${session.access_token}` },
+ cache: 'no-store',
+ // Up to two model calls (the second for refused tasks), each tried
+ // twice at 40 s: inside this wait, so the server never writes after it.
+ signal: AbortSignal.timeout(200_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}`,
+ };
+ }
+ return { written: Number(data.written ?? 0), kept: Number(data.kept ?? 0) };
+ } catch (err) {
+ return {
+ error: err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'unreachable',
+ };
+ }
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 61d915d84..d2e2e869e 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -177,6 +177,8 @@ export type Database = {
priority_score: number | null
priority_updated_at: string | null
status: string
+ tasks_generated_at: string | null
+ tasks_writing_since: string | null
updated_at: string
validated_at: string | null
validation: Json | null
@@ -203,6 +205,8 @@ export type Database = {
priority_score?: number | null
priority_updated_at?: string | null
status?: string
+ tasks_generated_at?: string | null
+ tasks_writing_since?: string | null
updated_at?: string
validated_at?: string | null
validation?: Json | null
@@ -229,6 +233,8 @@ export type Database = {
priority_score?: number | null
priority_updated_at?: string | null
status?: string
+ tasks_generated_at?: string | null
+ tasks_writing_since?: string | null
updated_at?: string
validated_at?: string | null
validation?: Json | null