Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(action-center): show the task writer the brand's earlier rounds of an action (learning B5, part 1) (#1697)
Cihan8c6849ec4f50
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdxindex fe6f8bd65..d30182e2c 100644--- a/docs/guides/action-center.mdx+++ b/docs/guides/action-center.mdx@@ -102,7 +102,7 @@ From a task you can also:- **Send to Content** — send a content task to Content as an opportunity, where a brief can be written for it.- **Send to webhook** — post the task to the brand's webhook, for a workflow outside Ansvisor. The webhook is set up under **Content → Webhook Settings**, with the **Action Center task sent** event selected.-Where AI task writing is on for your workspace, **Regenerate tasks** writes the action's tasks again from its evidence. Done, under-way and hand-added tasks stay. It uses your plan's monthly AI allowance.+Where AI task writing is on for your workspace, **Regenerate tasks** writes the action's tasks again from its evidence. Done, under-way and hand-added tasks stay. It uses your plan's monthly AI allowance. The AI also reads this brand's last three closed rounds of the same action: which tasks were done and what the result read, or why a round was dismissed. It builds on what improved results here and doesn't hand out again a task that was done without effect. Only this brand's own actions are read.A task the AI writes without its **URL**, its **Change**, **Done when** or **How we check** doesn't reach your list. It waits on the **Needs review** tab, which admins and managers see, with what it misses. Click **Edit**, fill the missing fields and click **Approve** to add it after the action's other tasks, or **Dismiss** it.diff --git a/server/src/lib/action-center/task-writer/history.js b/server/src/lib/action-center/task-writer/history.jsnew file mode 100644index 000000000..ae2f5d459--- /dev/null+++ b/server/src/lib/action-center/task-writer/history.js@@ -0,0 +1,110 @@+/**+ * Earlier rounds of an action (learning B5): the brand's closed actions of+ * the same kind, with the tasks each one carried, which were done, and what+ * its result read. The writer is shown them so it builds on what improved+ * results here and doesn't hand out again what was done for nothing. A+ * dismissed round says why it was turned down. The brand's own actions only,+ * never another brand's.+ */++import supabaseAdmin from '../../../config/supabase.js';++/** Earlier rounds the writer is shown, newest first. */+export const PAST_ROUNDS = 3;++/** Tasks of a round it is shown, done and not done each. */+const TASKS_PER_ROUND = 6;++const str = (value) => (typeof value === 'string' ? value.trim() : '');+const num = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : null);++/** "refresh_content" → "Refresh content": a template task, by its key. */+function keyWords(key) {+ const words = str(key).replace(/_/g, ' ');+ return words.charAt(0).toUpperCase() + words.slice(1);+}++/**+ * One earlier round as the writer reads it.+ *+ * @param {{ status: string, outcome?: string | null, validation?: object | null,+ * dismiss_reason?: string | null, completed_at?: string | null, updated_at?: string | null }} row+ * @param {Array<{ task_key?: string | null, title?: string | null, status: string }>} tasks+ */+export function pastRound(row, tasks) {+ if (row.status === 'dismissed') {+ return {+ closed: str(row.updated_at).slice(0, 10) || null,+ dismissed: true,+ reason: row.dismiss_reason ?? null,+ };+ }+ const named = tasks+ .map((task) => ({ title: str(task.title) || keyWords(task.task_key), status: task.status }))+ .filter((task) => task.title);+ const titles = (keep) =>+ named+ .filter(keep)+ .map((task) => task.title)+ .slice(0, TASKS_PER_ROUND);++ // Its main metric before it was raised and after it closed (learning A4).+ const validation = row.validation ?? {};+ const main = (Array.isArray(validation.metrics) ? validation.metrics : []).find(+ (m) => m?.metric === validation.primary && num(m.before) !== null && num(m.after) !== null,+ );+ return {+ closed: str(row.completed_at).slice(0, 10) || null,+ result: row.outcome ?? 'pending_measurement',+ // Read for the last time, a month on (learning B1), or measured once+ // before readings began, which the sweep never reads again (as History+ // and the MCP read it); a reading so far otherwise.+ final:+ validation.final === true ||+ (row.outcome != null &&+ row.outcome !== 'pending_measurement' &&+ !Array.isArray(validation.readings)),+ mainMetric: main ? { metric: main.metric, before: main.before, after: main.after } : null,+ done: titles((task) => task.status === 'completed'),+ notDone: titles((task) => task.status !== 'completed'),+ };+}++/**+ * The brand's last closed rounds of this action's kind, newest first.+ *+ * @param {{ id: string, brand_id: string, kind: string }} action+ * @param {{ skip?: (task: { task_key?: string | null }) => boolean, limit?: number }} [options]+ * skip: tasks to leave out, such as the product's own analysis steps+ */+export async function loadPastRounds(action, { skip = () => false, limit = PAST_ROUNDS } = {}) {+ const { data, error } = await supabaseAdmin+ .from('actions')+ .select('id, status, outcome, validation, dismiss_reason, completed_at, updated_at')+ .eq('brand_id', action.brand_id)+ .eq('kind', action.kind)+ .in('status', ['completed', 'dismissed'])+ .is('deleted_at', null)+ .order('updated_at', { ascending: false })+ .limit(limit + 1);+ if (error) throw new Error(`past rounds read failed: ${error.message}`);+ const rows = (data ?? []).filter((row) => row.id !== action.id).slice(0, limit);+ if (rows.length === 0) return [];++ const { data: tasks, error: tasksError } = await supabaseAdmin+ .from('action_tasks')+ .select('action_id, position, task_key, title, status')+ .in(+ 'action_id',+ rows.map((row) => row.id),+ )+ .order('position');+ if (tasksError) throw new Error(`past rounds' tasks read failed: ${tasksError.message}`);+ const byAction = new Map();+ for (const task of tasks ?? []) {+ if (skip(task)) continue;+ if (!byAction.has(task.action_id)) byAction.set(task.action_id, []);+ byAction.get(task.action_id).push(task);+ }+ return rows.map((row) => pastRound(row, byAction.get(row.id) ?? []));+}diff --git a/server/src/lib/action-center/task-writer/history.test.js b/server/src/lib/action-center/task-writer/history.test.jsnew file mode 100644index 000000000..9f2c1f04e--- /dev/null+++ b/server/src/lib/action-center/task-writer/history.test.js@@ -0,0 +1,75 @@+import { describe, expect, it, vi } from 'vitest';+import { pastRound } from './history.js';++// pastRound reads nothing; the client only has to load without credentials.+vi.mock('../../../config/supabase.js', () => ({ default: {} }));++/**+ * An earlier round as the task writer reads it (learning B5): what was done,+ * what was left, and what the result read; a dismissed one, why.+ */+describe('pastRound', () => {+ it('reads a completed round: its result, its main metric and its tasks', () => {+ expect(+ pastRound(+ {+ status: 'completed',+ outcome: 'improved',+ validation: {+ primary: 'citations',+ readings: [{ day: 7, outcome: 'improved' }],+ metrics: [+ { metric: 'mentions', before: 1, after: 2 },+ { metric: 'citations', before: 4, after: 9 },+ ],+ },+ completed_at: '2026-09-12T08:00:00Z',+ },+ [+ { task_key: 'refresh_content', title: null, status: 'completed' },+ { task_key: null, title: 'Pitch seriouseats.com', status: 'skipped' },+ { task_key: null, title: ' ', status: 'todo' },+ ],+ ),+ ).toEqual({+ closed: '2026-09-12',+ result: 'improved',+ final: false,+ mainMetric: { metric: 'citations', before: 4, after: 9 },+ done: ['Refresh content'],+ notDone: ['Pitch seriouseats.com'],+ });+ });++ it('reads a round not measured yet, and one with no main metric read', () => {+ expect(+ pastRound({ status: 'completed', outcome: null, validation: null, completed_at: null }, []),+ ).toEqual({+ closed: null,+ result: 'pending_measurement',+ final: false,+ mainMetric: null,+ done: [],+ notDone: [],+ });+ });++ it('reads a round as final once read on day 30, or measured once before readings began', () => {+ const round = (validation) =>+ pastRound({ status: 'completed', outcome: 'declined', validation, completed_at: null }, []);+ expect(round({ readings: [{ day: 30, outcome: 'declined' }], final: true }).final).toBe(true);+ // Measured before readings began (learning B1): the sweep never reads it+ // again, so History and the MCP take it as the result too.+ expect(round({ primary: 'citations', metrics: [] }).final).toBe(true);+ expect(round({ readings: [{ day: 14, outcome: 'declined' }] }).final).toBe(false);+ });++ it('reads a dismissed round as why it was turned down', () => {+ expect(+ pastRound(+ { status: 'dismissed', dismiss_reason: 'wrong_data', updated_at: '2026-08-02T00:00:00Z' },+ [{ task_key: 'refresh_content', status: 'todo' }],+ ),+ ).toEqual({ closed: '2026-08-02', dismissed: true, reason: 'wrong_data' });+ });+});diff --git a/server/src/lib/action-center/task-writer/index.js b/server/src/lib/action-center/task-writer/index.jsindex 21bc7e341..49e2e6008 100644--- a/server/src/lib/action-center/task-writer/index.js+++ b/server/src/lib/action-center/task-writer/index.js@@ -29,6 +29,7 @@ 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 { loadPastRounds } from './history.js';import {MAX_TASKS,TASK_CHECKS,@@ -299,10 +300,19 @@ async function compose({ action, brand, domains, signals, name, trigger, userId,};const shown = evidenceForPrompt(evidence);+ // Its earlier rounds here (learning B5), the product's own analysis steps+ // left out. Without them it is still written, as before.+ let history = [];+ try {+ history = await loadPastRounds(action, { skip: isAnalysisTask });+ } catch (err) {+ logger.warn({ actionId, err: err.message }, '[task-writer] past rounds unavailable');+ }const base = buildTaskWriterPrompt({action: { name, category: action.category },brand: { name: brand.name, description: brand.description, domains },evidence: shown,+ history,});const first = sift(await callModel({ modelId, ...base, charge }), evidence, []);let tasks = first.accepted;@@ -331,7 +341,9 @@ async function compose({ action, brand, domains, signals, name, trigger, userId,reviews.push(task);}- if (dryRun) return { status: 'preview', tasks, reviews, refused, costUsd, evidence: shown };+ if (dryRun) {+ return { status: 'preview', tasks, reviews, refused, costUsd, evidence: shown, history };+ }if (tasks.length === 0 && reviews.length === 0) {await markWritten(actionId, now);return { status: 'skipped', reason: 'no_valid_tasks', refused, costUsd };diff --git a/server/src/lib/action-center/task-writer/index.test.js b/server/src/lib/action-center/task-writer/index.test.jsindex 2758e32d8..5ebebec8e 100644--- a/server/src/lib/action-center/task-writer/index.test.js+++ b/server/src/lib/action-center/task-writer/index.test.js@@ -391,6 +391,70 @@ describe('writeTasksForAction', () => {expect(reserveAiBudget).not.toHaveBeenCalled();});+ /** Its earlier rounds here (learning B5): what was done, and what it moved. */+ it("shows the model the brand's earlier rounds of the action, without the analysis steps", async () => {+ db.actions.push(+ {+ id: 'a0',+ brand_id: 'b1',+ kind: 'recover_lost_citations',+ status: 'completed',+ outcome: 'no_meaningful_change',+ validation: {+ primary: 'citations',+ final: true,+ metrics: [{ metric: 'citations', before: 3, after: 3 }],+ },+ completed_at: '2026-09-01T10:00:00Z',+ updated_at: '2026-09-01T10:00:00Z',+ },+ // Another brand's round is never shown.+ { id: 'x0', brand_id: 'b2', kind: 'recover_lost_citations', status: 'completed' },+ );+ db.action_tasks.push(+ {+ id: 'p1',+ action_id: 'a0',+ position: 1,+ task_key: 'analyze_citations',+ status: 'completed',+ },+ {+ id: 'p2',+ action_id: 'a0',+ position: 2,+ task_key: null,+ title: 'Add a FAQ to /blog/shipping',+ status: 'completed',+ },+ );+ generateObject.mockResolvedValueOnce(answer([task()]));++ const result = await writeTasksForAction('a1', { dryRun: true });++ expect(result.history).toEqual([+ {+ closed: '2026-09-01',+ result: 'no_meaningful_change',+ final: true,+ mainMetric: { metric: 'citations', before: 3, after: 3 },+ done: ['Add a FAQ to /blog/shipping'],+ notDone: [],+ },+ ]);+ const { prompt } = generateObject.mock.calls[0][0];+ expect(prompt).toContain('Earlier rounds of this action at this brand');+ expect(prompt).toContain('Add a FAQ to /blog/shipping');+ expect(prompt).not.toContain('Analyze citations');+ });++ it('says nothing of earlier rounds when there are none', async () => {+ generateObject.mockResolvedValueOnce(answer([task()]));+ const result = await writeTasksForAction('a1', { dryRun: true });+ expect(result.history).toEqual([]);+ expect(generateObject.mock.calls[0][0].prompt).not.toContain('Earlier rounds');+ });+it('calls no model when the signals name nothing to work on', async () => {db.signals[0].payload = {};const result = await writeTasksForAction('a1', { trigger: 'regenerate' });diff --git a/server/src/lib/action-center/task-writer/prompt.js b/server/src/lib/action-center/task-writer/prompt.jsindex 6861e1972..088d6ea5e 100644--- a/server/src/lib/action-center/task-writer/prompt.js+++ b/server/src/lib/action-center/task-writer/prompt.js@@ -60,9 +60,10 @@ Rules:* action: { name: string, category: string, title?: string },* brand: { name: string, description?: string | null, domains: string[] },* evidence: object,- * }} input evidence as `evidenceForPrompt` gives it+ * history?: object[],+ * }} input evidence as `evidenceForPrompt` gives it; history as `loadPastRounds` does*/-export function buildTaskWriterPrompt({ action, brand, evidence }) {+export function buildTaskWriterPrompt({ action, brand, evidence, history = [] }) {const prompt = [`Brand: ${brand.name}${brand.domains.length ? ` (${brand.domains.join(', ')})` : ''}`,brand.description ? `About the brand: ${brand.description}` : null,@@ -70,6 +71,16 @@ export function buildTaskWriterPrompt({ action, brand, evidence }) {'','Evidence (JSON):',JSON.stringify(evidence),+ // Earlier rounds of this action here (learning B5): what was done, and+ // what the result read.+ ...(history.length+ ? [+ '',+ 'Earlier rounds of this action at this brand, newest first (JSON). result is improved, mixed, no_meaningful_change, declined, not_measurable or pending_measurement; final is false while it is a reading so far:',+ JSON.stringify(history),+ 'Build on what the rounds that improved results did. Do not give again a task a round did without improvement, unless the evidence shows something new. A dismissed round says why it was turned down.',+ ]+ : []),'',`Write up to ${MAX_TASKS} tasks.`,]diff --git a/server/src/scripts/review-action-tasks.js b/server/src/scripts/review-action-tasks.jsindex d4fad3131..b443f1914 100644--- a/server/src/scripts/review-action-tasks.js+++ b/server/src/scripts/review-action-tasks.js@@ -62,6 +62,20 @@ for (const action of actions) {`Evidence: ${e.pages.length} pages, ${e.prompts.length} prompts, ${e.domains.length} domains, ${e.competitors.length} competitors · $${result.costUsd.toFixed(4)}`,'',);+ // The earlier rounds it was shown (learning B5), so a reviewer can tell+ // whether the tasks built on them.+ if (result.history?.length) {+ lines.push(+ `Earlier rounds: ${result.history+ .map((round) =>+ round.dismissed+ ? `${round.closed} dismissed (${round.reason ?? 'no reason'})`+ : `${round.closed} ${round.result}${round.final ? '' : ' so far'}, ${round.done.length} done`,+ )+ .join(' · ')}`,+ '',+ );+ }result.tasks.forEach((task, i) => {lines.push(`${i + 1}. **${task.title}** · ${task.type}`,