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): plan a task list instead of copying one (#830)
Gökhan Geyikde562707cf9d
diff --git a/server/src/lib/action-center/definitions/capture-ai-traffic.js b/server/src/lib/action-center/definitions/capture-ai-traffic.jsindex ef0d97da4..e95d39a03 100644--- a/server/src/lib/action-center/definitions/capture-ai-traffic.js+++ b/server/src/lib/action-center/definitions/capture-ai-traffic.js@@ -12,7 +12,7 @@ export default {signalKinds: ['page_opportunity'],requires: ['analytics'],optional: ['site_audits'],- tasks: ['review_pages', 'coverage_gaps', 'optimize_content', 'validate'],+ tasks: ['review_pages', 'page_readiness', 'coverage_gaps', 'optimize_content', 'validate'],payload(byKind) {return { pageCount: (byKind.get('page_opportunity') ?? []).length };diff --git a/server/src/lib/action-center/definitions/protect-visibility.js b/server/src/lib/action-center/definitions/protect-visibility.jsindex 7879df2b6..78c591b3e 100644--- a/server/src/lib/action-center/definitions/protect-visibility.js+++ b/server/src/lib/action-center/definitions/protect-visibility.js@@ -13,7 +13,13 @@ export default {requires: ['tracking'],// Who is taking the ground is context, not a precondition.optional: ['competitors'],- tasks: ['diagnose_slip', 'review_responses', 'reinforce_content', 'validate'],+ tasks: [+ 'diagnose_slip',+ 'competitor_pressure',+ 'review_responses',+ 'reinforce_content',+ 'validate',+ ],payload(byKind) {const slip = (byKind.get('visibility_slipping') ?? [])[0];diff --git a/server/src/lib/action-center/definitions/recover-visibility.js b/server/src/lib/action-center/definitions/recover-visibility.jsindex 75eee17c6..1f7f8ea24 100644--- a/server/src/lib/action-center/definitions/recover-visibility.js+++ b/server/src/lib/action-center/definitions/recover-visibility.js@@ -14,7 +14,16 @@ export default {// Traffic is not needed to raise the action, but with it connected the plan// can show what the drop cost in sessions rather than only in points.optional: ['analytics'],- tasks: ['analyze_losses', 'coverage_gaps', 'update_content', 'internal_links', 'validate'],+ // measure_traffic_impact requires the analytics source, so it is planned+ // only for a brand that has one — the difference the planner exists for.+ tasks: [+ 'analyze_losses',+ 'measure_traffic_impact',+ 'coverage_gaps',+ 'update_content',+ 'internal_links',+ 'validate',+ ],payload(byKind) {const out = { promptCount: (byKind.get('lost_citations') ?? []).length };diff --git a/server/src/lib/action-center/generate.js b/server/src/lib/action-center/generate.jsindex a88bbd7e6..6c551488e 100644--- a/server/src/lib/action-center/generate.js+++ b/server/src/lib/action-center/generate.js@@ -40,6 +40,7 @@ import { logger } from '../logger.js';import { resolve } from '../../config/action-engine.js';import { isEligible, loadDefinitions } from './definitions/index.js';import { resolveBrandSources } from './sources.js';+import { planTasks } from './tasks/plan.js';const DAY_MS = 86_400_000;@@ -110,7 +111,9 @@ function startOfUtcDay(now) {return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());}-async function openCycle({ brandId, definition, signals, impact }) {+async function openCycle({ brandId, definition, signals, impact, available }) {+ const payload = { signalCount: signals.length, ...definition.payload(groupByKind(signals)) };+const { data: inserted, error } = await supabaseAdmin.from('actions').insert({@@ -119,7 +122,7 @@ async function openCycle({ brandId, definition, signals, impact }) {kind: definition.id,definition_version: definition.version,impact,- payload: { signalCount: signals.length, ...definition.payload(groupByKind(signals)) },+ payload,kpi_keys: [...new Set(signals.flatMap((signal) => signal.kpi_keys ?? []))],baseline: buildBaseline(signals),dedup_key: definition.id,@@ -128,11 +131,20 @@ async function openCycle({ brandId, definition, signals, impact }) {.single();if (error) throw new Error(error.message);+ // The plan follows from what this brand has and what this action is about+ // — not from the kind alone (#818 phase 5). Two brands with the same+ // problem and different integrations get different lists here.+ const plan = planTasks(definition, { sources: available, payload });const { error: tasksErr } = await supabaseAdmin.from('action_tasks').insert(- definition.tasks.map((taskKey, index) => ({+ plan.map((item) => ({action_id: inserted.id,- position: index + 1,- task_key: taskKey,+ position: item.position,+ task_key: item.taskKey,+ task_version: item.version,+ mode: item.mode,+ permission: item.permission,+ depends_on: item.dependsOn,+ title_params: item.titleParams,})),);if (tasksErr) throw new Error(tasksErr.message);@@ -141,6 +153,7 @@ async function openCycle({ brandId, definition, signals, impact }) {impact,signalCount: signals.length,definitionVersion: definition.version,+ taskCount: plan.length,});await linkSignals(inserted.id, signals);}@@ -257,7 +270,7 @@ export async function generateActionsForBrand(brandId, { now = new Date(), sourcconst opening = candidates.slice(0, room);for (const candidate of opening) {- await openCycle({ brandId, ...candidate });+ await openCycle({ brandId, available, ...candidate });}const summary = {diff --git a/server/src/lib/action-center/generate.test.js b/server/src/lib/action-center/generate.test.jsindex b58d4e94f..ff5bc6a2b 100644--- a/server/src/lib/action-center/generate.test.js+++ b/server/src/lib/action-center/generate.test.js@@ -384,3 +384,70 @@ describe('the definition version', () => {expect(Number.isInteger(row.definition_version)).toBe(true);});});++/**+ * Phase 5's exit condition (#818), through the writer rather than the+ * planner: two brands with the same problem, one with an integration+ * connected and one without, are given different work.+ */+describe('the task plan the action is created with', () => {+ const taskRows = (writes) =>+ (writes.inserted.find((w) => w.table === 'action_tasks')?.rows ?? []).map(+ (row) => row.task_key,+ );++ it('asks a brand with analytics what the drop cost in sessions', async () => {+ const writes = mockDb({ signals: [signal()] });++ await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });++ expect(taskRows(writes)).toContain('measure_traffic_impact');+ });++ it('does not ask a brand that has no analytics connected', async () => {+ const writes = mockDb({ signals: [signal()] });++ await generateActionsForBrand(BRAND, { now: NOW, sources: new Set(['tracking']) });++ expect(taskRows(writes)).not.toContain('measure_traffic_impact');+ expect(taskRows(writes).length).toBeGreaterThan(0);+ });++ it('records how each task may be carried out, and what it waits on', async () => {+ const writes = mockDb({ signals: [signal()] });++ await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });++ const rows = writes.inserted.find((w) => w.table === 'action_tasks').rows;+ for (const row of rows) {+ expect(['manual', 'agent']).toContain(row.mode);+ expect(['none', 'approval']).toContain(row.permission);+ expect(Array.isArray(row.depends_on)).toBe(true);+ expect(row.task_version).toBeGreaterThanOrEqual(1);+ }+ // Positions are contiguous whatever the plan dropped.+ expect(rows.map((row) => row.position)).toEqual(rows.map((_, i) => i + 1));+ });++ it('names the target on a task whose payload resolves one', async () => {+ const writes = mockDb({+ signals: [+ signal({+ kind: 'platform_gap',+ impact: 'medium',+ payload: { platform: 'gemini-web', bestPlatform: 'chatgpt-web' },+ }),+ ],+ });++ await generateActionsForBrand(BRAND, { now: NOW, sources: ALL_SOURCES });++ const compare = writes.inserted+ .find((w) => w.table === 'action_tasks')+ .rows.find((row) => row.task_key === 'compare_platforms');+ expect(compare.title_params).toEqual({+ platform: 'gemini-web',+ bestPlatform: 'chatgpt-web',+ });+ });+});diff --git a/server/src/lib/action-center/tasks/plan.js b/server/src/lib/action-center/tasks/plan.jsnew file mode 100644index 000000000..424fe760f--- /dev/null+++ b/server/src/lib/action-center/tasks/plan.js@@ -0,0 +1,84 @@+/**+ * The task planner (#818, phase 5).+ *+ * Turns a definition's task spec into the rows one action actually gets,+ * given what the brand has and what the action is about. Two brands with the+ * same problem no longer receive the same list: a brand with analytics+ * connected is asked what the drop cost in sessions; a brand without is not+ * asked a question it cannot answer.+ *+ * Three things happen here, and nothing else — the planner decides the plan,+ * it does not write it. `generate.js` owns the writing, which keeps this+ * testable without a database.+ *+ * 1. **Eligibility.** A task whose required sources the brand lacks is+ * dropped. Definition-level `requires` on a spec entry narrows further,+ * which is how a task that exists for every brand can still be optional+ * inside one particular plan.+ * 2. **Dependencies.** A dropped task takes its name out of everyone's+ * `dependsOn`. A dependency that is not in the plan is not a dependency —+ * leaving the name behind would block a task on work nobody was asked to+ * do.+ * 3. **Targets.** A task that can name what it is about does, from the+ * action's payload. The values travel as parameters rather than as+ * resolved text, so the plan stays translatable.+ */++import { getTask } from './registry.js';++/**+ * Payload values a task's text may name, normalised.+ *+ * `competitorNames` is stored as a list because an action can consolidate+ * several; a task title names the one that leads. Everything else is passed+ * through as it was stored.+ */+function titleValues(payload) {+ const names = Array.isArray(payload.competitorNames) ? payload.competitorNames : [];+ return { ...payload, competitor: names[0] };+}++/** A spec entry is a bare task id, or an id with extra conditions. */+function normalise(entry) {+ return typeof entry === 'string' ? { id: entry, requires: [] } : { requires: [], ...entry };+}++/**+ * The tasks one action should be given.+ *+ * @param {{ id: string, tasks: readonly (string|object)[] }} definition+ * @param {{ sources: Set<string>, payload?: Record<string, unknown> }} context+ * @returns {Array<{ taskKey: string, version: number, mode: string, permission: string,+ * dependsOn: string[], titleParams: Record<string, unknown>, position: number }>}+ */+export function planTasks(definition, { sources, payload = {} }) {+ const values = titleValues(payload);++ const chosen = [];+ for (const entry of definition.tasks.map(normalise)) {+ const primitive = getTask(entry.id);+ if (!primitive) continue;+ const needed = [...primitive.requires, ...entry.requires];+ if (!needed.every((source) => sources.has(source))) continue;+ chosen.push(primitive);+ }++ const planned = new Set(chosen.map((primitive) => primitive.id));++ return chosen.map((primitive, index) => {+ const named = primitive.titleKeys.every(+ (key) => values[key] !== undefined && values[key] !== null,+ );+ return {+ taskKey: primitive.id,+ version: primitive.version,+ mode: primitive.mode,+ permission: primitive.permission,+ dependsOn: primitive.dependsOn.filter((id) => planned.has(id)),+ titleParams: named+ ? Object.fromEntries(primitive.titleKeys.map((key) => [key, values[key]]))+ : {},+ position: index + 1,+ };+ });+}diff --git a/server/src/lib/action-center/tasks/plan.test.js b/server/src/lib/action-center/tasks/plan.test.jsnew file mode 100644index 000000000..073445d95--- /dev/null+++ b/server/src/lib/action-center/tasks/plan.test.js@@ -0,0 +1,227 @@+import { readFileSync } from 'node:fs';+import { describe, expect, it, vi } from 'vitest';++// loadDefinitions reaches sources.js, which imports the admin client; its+// config hard-exits without SUPABASE_* env, as in CI. Nothing here touches it.+vi.mock('../../../config/supabase.js', () => ({ default: { from: vi.fn(), rpc: vi.fn() } }));++import { planTasks } from './plan.js';+import { TASKS, listTasks, validateTask } from './registry.js';+import { loadDefinitions } from '../definitions/index.js';++const ALL = new Set(['tracking', 'competitors', 'site_audits', 'analytics']);+const BARE = new Set(['tracking']);++const keys = (plan) => plan.map((item) => item.taskKey);++/**+ * Phase 5's exit condition, stated as a test: the same action kind, two+ * brands, different plans. Everything else here is the machinery that makes+ * that safe to do.+ */+describe('planTasks', () => {+ const definition = {+ id: 'recover_visibility',+ tasks: ['analyze_losses', 'measure_traffic_impact', 'coverage_gaps', 'update_content'],+ };++ it('gives a brand with analytics the task that reads it', () => {+ expect(keys(planTasks(definition, { sources: ALL }))).toContain('measure_traffic_impact');+ });++ it('does not ask a brand without analytics a question it cannot answer', () => {+ const plan = planTasks(definition, { sources: BARE });+ expect(keys(plan)).not.toContain('measure_traffic_impact');+ expect(keys(plan)).toEqual(['analyze_losses', 'coverage_gaps', 'update_content']);+ });++ it('numbers positions over the tasks that survived, leaving no gap', () => {+ const plan = planTasks(definition, { sources: BARE });+ expect(plan.map((item) => item.position)).toEqual([1, 2, 3]);+ });++ /**+ * A dependency that was never planned is not a dependency. Leaving the name+ * behind would block a task on work nobody was asked to do.+ */+ it('drops a dependency on a task the brand did not get', () => {+ const plan = planTasks(+ { id: 'x', tasks: ['diagnose_slip', 'competitor_pressure', 'review_responses'] },+ { sources: BARE },+ );+ expect(keys(plan)).not.toContain('competitor_pressure');+ const reinforce = plan.find((item) => item.taskKey === 'review_responses');+ expect(reinforce.dependsOn).toEqual(['diagnose_slip']);+ });++ it('keeps a dependency that is in the plan', () => {+ const plan = planTasks(+ { id: 'x', tasks: ['diagnose_slip', 'competitor_pressure'] },+ { sources: ALL },+ );+ expect(plan.find((i) => i.taskKey === 'competitor_pressure').dependsOn).toEqual([+ 'diagnose_slip',+ ]);+ });++ it('carries the task primitive’s mode, permission and version onto the row', () => {+ const plan = planTasks(+ { id: 'x', tasks: ['strengthen_sources', 'validate'] },+ { sources: ALL },+ );+ expect(plan[0]).toMatchObject({ mode: 'manual', permission: 'approval', version: 1 });+ expect(plan[1]).toMatchObject({ mode: 'agent', permission: 'none' });+ });++ it('ignores a task id that no longer exists in the registry', () => {+ expect(+ keys(planTasks({ id: 'x', tasks: ['validate', 'retired_task'] }, { sources: ALL })),+ ).toEqual(['validate']);+ });++ describe('naming what the task is about', () => {+ it('carries the values as parameters, not as resolved text', () => {+ const plan = planTasks(+ { id: 'x', tasks: ['compare_platforms'] },+ { sources: ALL, payload: { platform: 'gemini-web', bestPlatform: 'chatgpt-web' } },+ );+ expect(plan[0].titleParams).toEqual({+ platform: 'gemini-web',+ bestPlatform: 'chatgpt-web',+ });+ });++ it('names the competitor that leads, out of however many the action holds', () => {+ const plan = planTasks(+ { id: 'x', tasks: ['analyze_competitor'] },+ { sources: ALL, payload: { competitorNames: ['Acme', 'Globex'] } },+ );+ expect(plan[0].titleParams).toEqual({ competitor: 'Acme' });+ });++ /**+ * Half a title is worse than none: "Compare coverage against undefined"+ * is what a partially filled payload produces if the planner does not+ * insist on all of it.+ */+ it('names nothing when the payload is missing a value the text needs', () => {+ const plan = planTasks(+ { id: 'x', tasks: ['compare_platforms'] },+ { sources: ALL, payload: { platform: 'gemini-web' } },+ );+ expect(plan[0].titleParams).toEqual({});+ });++ it('names nothing for a task that names nothing', () => {+ const plan = planTasks({ id: 'x', tasks: ['validate'] }, { sources: ALL, payload: { a: 1 } });+ expect(plan[0].titleParams).toEqual({});+ });+ });+});++describe('the task registry', () => {+ it.each(listTasks().map((entry) => [entry.id, entry]))('%s is well formed', (_id, entry) => {+ expect(validateTask(entry)).toEqual([]);+ });++ it('keys every entry by its own id', () => {+ for (const [key, entry] of Object.entries(TASKS)) expect(entry.id).toBe(key);+ });++ /** A cycle would make the plan unorderable and is easy to write by accident. */+ it('has no dependency cycles', () => {+ const seen = new Map();+ const walk = (id, trail) => {+ if (trail.includes(id)) throw new Error(`cycle: ${[...trail, id].join(' -> ')}`);+ if (seen.get(id)) return;+ for (const next of TASKS[id].dependsOn) walk(next, [...trail, id]);+ seen.set(id, true);+ };+ expect(() => listTasks().forEach((entry) => walk(entry.id, []))).not.toThrow();+ });++ /**+ * A definition naming a task that does not exist would silently produce a+ * shorter plan — the planner skips what it cannot find, by design, because+ * a retired task must not break every action that still lists it. That+ * makes a typo invisible at runtime, so it is caught here instead.+ */+ it('backs every task the shipped definitions ask for', async () => {+ const definitions = await loadDefinitions();+ for (const definition of definitions) {+ for (const entry of definition.tasks) {+ const id = typeof entry === 'string' ? entry : entry.id;+ expect({ definition: definition.id, id, known: Boolean(TASKS[id]) }).toEqual({+ definition: definition.id,+ id,+ known: true,+ });+ }+ }+ });++ /**+ * The web renders a task from its id. A task with no message shows its own+ * key to the user, and a target-aware task with no `_target` variant shows+ * the key the moment a payload resolves — which is exactly when the text+ * mattered most. Both are silent until someone sees them, so they are+ * caught here, against the file the web actually ships.+ */+ it('has a message for every task, and a target variant for every task that names one', () => {+ const messages = JSON.parse(+ readFileSync(new URL('../../../../../web/messages/en.json', import.meta.url), 'utf8'),+ ).actionCenter.actionTasks;++ for (const entry of listTasks()) {+ expect({ id: entry.id, message: typeof messages[entry.id] }).toEqual({+ id: entry.id,+ message: 'string',+ });+ if (entry.titleKeys.length > 0) {+ expect({ id: entry.id, target: typeof messages[`${entry.id}_target`] }).toEqual({+ id: entry.id,+ target: 'string',+ });+ }+ }+ });++ /** A message naming a value the planner never supplies renders as an ICU+ * error in the user's face. */+ it('only names values the planner puts in the parameters', () => {+ const messages = JSON.parse(+ readFileSync(new URL('../../../../../web/messages/en.json', import.meta.url), 'utf8'),+ ).actionCenter.actionTasks;++ for (const entry of listTasks()) {+ if (entry.titleKeys.length === 0) continue;+ // Only the top-level ICU arguments: `{promptCount, plural, ...}` names+ // one, `one {1 prompt}` nested inside it names nothing.+ const named = [...messages[`${entry.id}_target`].matchAll(/\{\s*(\w+)\s*[,}]/g)].map(+ (m) => m[1],+ );+ for (const name of named) {+ expect({ id: entry.id, name, declared: entry.titleKeys.includes(name) }).toEqual({+ id: entry.id,+ name,+ declared: true,+ });+ }+ }+ });++ /**+ * The registry says a task can produce structured output; the planner is+ * what has to keep the declaration reachable. A task declaring outputs+ * nobody consumes is fine — one consuming an output nothing declares is a+ * chain that silently breaks.+ */+ it('has a producer for every output a task depends on reading', () => {+ const produced = new Set(listTasks().flatMap((entry) => entry.outputs));+ for (const entry of listTasks()) {+ for (const id of entry.dependsOn) {+ for (const output of TASKS[id].outputs) expect(produced.has(output)).toBe(true);+ }+ }+ });+});diff --git a/server/src/lib/action-center/tasks/registry.js b/server/src/lib/action-center/tasks/registry.jsnew file mode 100644index 000000000..2a107b603--- /dev/null+++ b/server/src/lib/action-center/tasks/registry.js@@ -0,0 +1,186 @@+/**+ * The task registry (#818, phase 5).+ *+ * Every action of a given kind got the same task list, inline in its+ * definition, regardless of what the brand actually has. Both specifications+ * rule that out: a plan should follow from the action's targets and the data+ * the workspace holds, not from the kind alone.+ *+ * So the task text stops being a string in a definition and becomes a+ * primitive with an identity. Each one declares:+ *+ * - `requires` — the sources a brand needs before this task is worth+ * planning. A task asking someone to read their analytics is noise for a+ * brand with no analytics connected;+ * - `mode` — who can carry it out. `agent` means the work is reading and+ * reasoning over data we already hold, which is the half a tool could do;+ * `manual` means it changes something we do not own — a page, a CMS, a+ * relationship;+ * - `permission` — whether carrying it out reaches outside Ansvisor. Nothing+ * executes yet (phase 7), but the declaration is what phase 7 reads, and+ * deciding it task by task now is safer than deciding it in a hurry later;+ * - `dependsOn` — what must be finished first. Ordering was previously+ * implied by array position and nothing enforced it;+ * - `outputs` — the keys this task's result carries, so one task's finding+ * can feed the next rather than living in someone's head.+ *+ * `version` belongs to the task, bumped when what it asks for changes. An+ * action's tasks record the version they were planned from, for the same+ * reason actions record their definition's.+ */++/** A brand source, as resolved by action-center/sources.js. */+const SOURCES = ['tracking', 'competitors', 'site_audits', 'analytics'];++/** Who carries the task out. */+export const MODES = Object.freeze(['manual', 'agent']);++/** Whether carrying it out reaches outside Ansvisor. */+export const PERMISSIONS = Object.freeze(['none', 'approval']);++const task = (id, spec) =>+ Object.freeze({+ id,+ version: 1,+ mode: 'manual',+ permission: 'none',+ ...spec,+ requires: Object.freeze(spec.requires ?? []),+ dependsOn: Object.freeze(spec.dependsOn ?? []),+ outputs: Object.freeze(spec.outputs ?? []),+ /** Payload keys whose values the task's text can name. When every one is+ * present the planner stores them and the web renders the `_target`+ * variant of the task's message; otherwise the plain one. */+ titleKeys: Object.freeze(spec.titleKeys ?? []),+ });++/**+ * Every task primitive, keyed by id. The id is what `action_tasks.task_key`+ * stores and what the web resolves its text from, so it is permanent.+ */+export const TASKS = Object.freeze({+ // ── Reading what happened ────────────────────────────────────────────────+ analyze_losses: task('analyze_losses', {+ mode: 'agent',+ titleKeys: ['promptCount'],+ outputs: ['lostPrompts', 'competitorSources'],+ }),+ diagnose_slip: task('diagnose_slip', { mode: 'agent', outputs: ['slippingPrompts'] }),+ review_responses: task('review_responses', {+ mode: 'agent',+ dependsOn: ['diagnose_slip'],+ outputs: ['weakAnswers'],+ }),+ review_pages: task('review_pages', {+ mode: 'agent',+ titleKeys: ['pageCount'],+ outputs: ['pages'],+ }),+ review_audits: task('review_audits', {+ mode: 'agent',+ requires: ['site_audits'],+ titleKeys: ['pageCount'],+ outputs: ['failingSignals'],+ }),+ identify_prompts: task('identify_prompts', {+ mode: 'agent',+ titleKeys: ['promptCount'],+ outputs: ['prompts'],+ }),+ compare_platforms: task('compare_platforms', {+ mode: 'agent',+ titleKeys: ['platform', 'bestPlatform'],+ outputs: ['platformRates'],+ }),+ compare_citations: task('compare_citations', {+ mode: 'agent',+ requires: ['competitors'],+ titleKeys: ['competitor'],+ outputs: ['competitorSources'],+ }),+ analyze_competitor: task('analyze_competitor', {+ mode: 'agent',+ requires: ['competitors'],+ titleKeys: ['competitor'],+ outputs: ['competitorPrompts'],+ }),+ coverage_gaps: task('coverage_gaps', { mode: 'agent', outputs: ['gaps'] }),+ identify_sources: task('identify_sources', {+ mode: 'agent',+ dependsOn: ['compare_citations'],+ outputs: ['sources'],+ }),++ // ── Reading what it cost, when the brand has the data to say ─────────────+ // The three tasks that exist only for a connected source. They are what+ // makes two brands' plans for the same action differ — see plan.js.+ measure_traffic_impact: task('measure_traffic_impact', {+ mode: 'agent',+ requires: ['analytics'],+ dependsOn: ['analyze_losses'],+ outputs: ['sessionsLost'],+ }),+ competitor_pressure: task('competitor_pressure', {+ mode: 'agent',+ requires: ['competitors'],+ dependsOn: ['diagnose_slip'],+ outputs: ['gainingCompetitors'],+ }),+ page_readiness: task('page_readiness', {+ mode: 'agent',+ requires: ['site_audits'],+ dependsOn: ['review_pages'],+ outputs: ['failingSignals'],+ }),++ // ── Changing something we do not own ─────────────────────────────────────+ update_content: task('update_content', { dependsOn: ['coverage_gaps'] }),+ optimize_content: task('optimize_content', { dependsOn: ['coverage_gaps'] }),+ reinforce_content: task('reinforce_content', { dependsOn: ['review_responses'] }),+ strengthen_content: task('strengthen_content', { dependsOn: ['coverage_gaps'] }),+ create_citable_content: task('create_citable_content', { dependsOn: ['identify_prompts'] }),+ internal_links: task('internal_links', { dependsOn: ['update_content'] }),+ fix_issues: task('fix_issues', { requires: ['site_audits'], dependsOn: ['review_audits'] }),++ // ── Reaching outside ─────────────────────────────────────────────────────+ // Manual today, but declared as needing approval: whoever makes this+ // executable in phase 7 should not have to decide that under deadline.+ strengthen_sources: task('strengthen_sources', {+ permission: 'approval',+ dependsOn: ['identify_sources'],+ }),++ // ── Checking whether it worked ───────────────────────────────────────────+ validate: task('validate', { mode: 'agent' }),+ revalidate: task('revalidate', { mode: 'agent', requires: ['site_audits'] }),+});++export function getTask(id) {+ return TASKS[id] ?? null;+}++export function listTasks() {+ return Object.values(TASKS);+}++/**+ * Everything a task must get right. Called by the registry's own test rather+ * than at import time: the registry is a literal in this file, so a mistake+ * is caught by CI, not by production starting up.+ */+export function validateTask(entry) {+ const problems = [];+ if (!entry.id || !/^[a-z][a-z0-9_]*$/.test(entry.id))+ problems.push('id must be lower_snake_case');+ if (!Number.isInteger(entry.version) || entry.version < 1) problems.push('version must be >= 1');+ if (!MODES.includes(entry.mode)) problems.push(`unknown mode "${entry.mode}"`);+ if (!PERMISSIONS.includes(entry.permission))+ problems.push(`unknown permission "${entry.permission}"`);+ for (const source of entry.requires) {+ if (!SOURCES.includes(source)) problems.push(`unknown source "${source}"`);+ }+ for (const dependency of entry.dependsOn) {+ if (!TASKS[dependency]) problems.push(`depends on unknown task "${dependency}"`);+ }+ return problems;+}diff --git a/supabase/migrations/00088_action_task_plan.sql b/supabase/migrations/00088_action_task_plan.sqlnew file mode 100644index 000000000..227def0d9--- /dev/null+++ b/supabase/migrations/00088_action_task_plan.sql@@ -0,0 +1,63 @@+-- Action Engine, phase 5 (#818): a task is planned, not copied.+--+-- Every action of a given kind was given the same task list, inline in its+-- definition, regardless of what the brand had. A brand with no analytics+-- connection was still told to check what a visibility drop cost in sessions.+-- The task registry (server/src/lib/action-center/tasks) turns each task into+-- a primitive with an identity and a data contract, and the planner selects+-- from it per action. These columns are what the plan needs to survive the+-- trip through the database.+--+-- Every one is additive with a default that reproduces today's behaviour, so+-- the 111 tasks already out there stay exactly as they are: a manual task+-- needing no approval, depending on nothing, naming nothing.++alter table public.action_tasks+ -- Which version of the task primitive planned this row, for the same+ -- reason an action records its definition's (00086): a task that is+ -- reworded or re-scoped must not rewrite what someone was already asked.+ add column if not exists task_version integer not null default 1,++ -- Who can carry it out. 'agent' is work over data we already hold;+ -- 'manual' changes something we do not own.+ add column if not exists mode text not null default 'manual',++ -- Whether carrying it out reaches outside Ansvisor. Nothing executes yet+ -- (phase 7) — this is the declaration phase 7 reads before it does.+ add column if not exists permission text not null default 'none',++ -- Task keys that must finish first. Ordering used to be implied by+ -- `position` and enforced by nobody.+ add column if not exists depends_on text[] not null default '{}',++ -- Values the task's text names — the platform, the competitor, the count.+ -- Parameters rather than resolved text, so the plan stays translatable.+ add column if not exists title_params jsonb not null default '{}'::jsonb,++ -- What the task produced, so one task's finding can feed the next instead+ -- of living in someone's head. Null until something fills it.+ add column if not exists output jsonb;++alter table public.action_tasks+ drop constraint if exists action_tasks_mode_check;+alter table public.action_tasks+ add constraint action_tasks_mode_check check (mode in ('manual', 'agent'));++alter table public.action_tasks+ drop constraint if exists action_tasks_permission_check;+alter table public.action_tasks+ add constraint action_tasks_permission_check check (permission in ('none', 'approval'));++alter table public.action_tasks+ drop constraint if exists action_tasks_task_version_check;+alter table public.action_tasks+ add constraint action_tasks_task_version_check check (task_version >= 1);++comment on column public.action_tasks.mode is+ 'Who carries the task out: manual (a person) or agent (work over data we hold).';+comment on column public.action_tasks.permission is+ 'approval when carrying it out reaches outside Ansvisor; none otherwise.';+comment on column public.action_tasks.depends_on is+ 'Task keys within the same action that must finish first. Only keys actually planned appear here.';+comment on column public.action_tasks.title_params is+ 'Values the task text names, as i18n parameters. Empty when the task names nothing specific.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 7a4198bdc..8a26e94f3 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -10502,3 +10502,70 @@ alter table public.signal_runs enable row level security;comment on table public.signal_runs is'One row per completed nightly signal pass. Drives the catch-up sweep and answers whether the pass ran for a given tracking run.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00088_action_task_plan.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Action Engine, phase 5 (#818): a task is planned, not copied.+--+-- Every action of a given kind was given the same task list, inline in its+-- definition, regardless of what the brand had. A brand with no analytics+-- connection was still told to check what a visibility drop cost in sessions.+-- The task registry (server/src/lib/action-center/tasks) turns each task into+-- a primitive with an identity and a data contract, and the planner selects+-- from it per action. These columns are what the plan needs to survive the+-- trip through the database.+--+-- Every one is additive with a default that reproduces today's behaviour, so+-- the 111 tasks already out there stay exactly as they are: a manual task+-- needing no approval, depending on nothing, naming nothing.++alter table public.action_tasks+ -- Which version of the task primitive planned this row, for the same+ -- reason an action records its definition's (00086): a task that is+ -- reworded or re-scoped must not rewrite what someone was already asked.+ add column if not exists task_version integer not null default 1,++ -- Who can carry it out. 'agent' is work over data we already hold;+ -- 'manual' changes something we do not own.+ add column if not exists mode text not null default 'manual',++ -- Whether carrying it out reaches outside Ansvisor. Nothing executes yet+ -- (phase 7) — this is the declaration phase 7 reads before it does.+ add column if not exists permission text not null default 'none',++ -- Task keys that must finish first. Ordering used to be implied by+ -- `position` and enforced by nobody.+ add column if not exists depends_on text[] not null default '{}',++ -- Values the task's text names — the platform, the competitor, the count.+ -- Parameters rather than resolved text, so the plan stays translatable.+ add column if not exists title_params jsonb not null default '{}'::jsonb,++ -- What the task produced, so one task's finding can feed the next instead+ -- of living in someone's head. Null until something fills it.+ add column if not exists output jsonb;++alter table public.action_tasks+ drop constraint if exists action_tasks_mode_check;+alter table public.action_tasks+ add constraint action_tasks_mode_check check (mode in ('manual', 'agent'));++alter table public.action_tasks+ drop constraint if exists action_tasks_permission_check;+alter table public.action_tasks+ add constraint action_tasks_permission_check check (permission in ('none', 'approval'));++alter table public.action_tasks+ drop constraint if exists action_tasks_task_version_check;+alter table public.action_tasks+ add constraint action_tasks_task_version_check check (task_version >= 1);++comment on column public.action_tasks.mode is+ 'Who carries the task out: manual (a person) or agent (work over data we hold).';+comment on column public.action_tasks.permission is+ 'approval when carrying it out reaches outside Ansvisor; none otherwise.';+comment on column public.action_tasks.depends_on is+ 'Task keys within the same action that must finish first. Only keys actually planned appear here.';+comment on column public.action_tasks.title_params is+ 'Values the task text names, as i18n parameters. Empty when the task names nothing specific.';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 0175d7fbb..d08fe0a99 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -571,7 +571,17 @@"reinforce_content": "Reinforce the content behind the affected prompts","compare_platforms": "Compare how each engine answers the affected prompts","compare_citations": "Compare which sources cite the competitor and not you",- "identify_sources": "Identify the sources worth earning a citation from"+ "identify_sources": "Identify the sources worth earning a citation from",+ "analyze_losses_target": "Analyze lost citations across {promptCount, plural, one {1 prompt} other {# prompts}}",+ "review_pages_target": "Review the {pageCount, plural, one {1 affected page} other {# affected pages}}",+ "review_audits_target": "Review the failing findings on {pageCount, plural, one {1 page} other {# pages}}",+ "identify_prompts_target": "Identify the {promptCount, plural, one {1 prompt} other {# prompts}} mentioning you without citation",+ "compare_platforms_target": "Compare how {platform} answers the affected prompts against {bestPlatform}",+ "compare_citations_target": "Compare which sources cite {competitor} and not you",+ "analyze_competitor_target": "Analyze what {competitor} gained visibility with",+ "measure_traffic_impact": "Measure what the drop cost in AI referral sessions",+ "competitor_pressure": "Identify which competitors are gaining the ground you are losing",+ "page_readiness": "Check the affected pages against their audit findings"},"taskStatus": {"todo": "To Do",diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex 7e2e0ed6a..0bf407a72 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -1,20 +1,24 @@import { describe, expect, it } from 'vitest';-import { actionGoal, actionTexts, humanizeKind } from './display';+import { actionGoal, actionTexts, humanizeKind, taskText } from './display';import { ACTION_KINDS } from './registry';import type { ActionItem } from '@/lib/actions/action-center';import messages from '../../../messages/en.json';/** Resolves an actionCenter.actionTexts key the way next-intl would, minus* the ICU formatting — enough to prove a key exists and is reached. */-const t = (key: string) => {+const t = (key: string, values?: Record<string, string | number>) => {+ const scope: Record<string, unknown> = key.includes('.')+ ? (messages.actionCenter.actionTexts as unknown as Record<string, unknown>)+ : (messages.actionCenter.actionTasks as unknown as Record<string, unknown>);const value = key.split('.')- .reduce<unknown>(- (node, part) => (node as Record<string, unknown> | undefined)?.[part],- messages.actionCenter.actionTexts,- );+ .reduce<unknown>((node, part) => (node as Record<string, unknown> | undefined)?.[part], scope);if (typeof value !== 'string') throw new Error(`missing message: ${key}`);- return value;+ // Enough ICU to prove the value reached the message; next-intl does the+ // real formatting at runtime.+ return value.replace(/\{\s*(\w+)\s*\}/g, (match, name) =>+ values && name in values ? String(values[name]) : match,+ );};const action = (over: Partial<ActionItem>) =>@@ -56,3 +60,44 @@ describe('humanizeKind', () => {expect(humanizeKind('recover')).toBe('Recover');});});++describe('taskText', () => {+ /** Nothing about a planned task's text is stored — only which message it+ * is and what it names — so the plan survives translation. */+ it('renders the target variant when the planner resolved one', () => {+ const text = taskText(+ {+ taskKey: 'compare_platforms',+ title: null,+ titleParams: { platform: 'gemini-web', bestPlatform: 'chatgpt-web' },+ },+ t,+ );++ expect(text).toContain('gemini-web');+ expect(text).toContain('chatgpt-web');+ });++ it('falls back to the plain message when nothing was resolvable', () => {+ expect(taskText({ taskKey: 'compare_platforms', title: null, titleParams: {} }, t)).toBe(+ messages.actionCenter.actionTasks.compare_platforms,+ );+ });++ it('treats a task with no params at all like one with empty params', () => {+ expect(taskText({ taskKey: 'validate', title: null }, t)).toBe(+ messages.actionCenter.actionTasks.validate,+ );+ });++ /** A title someone typed wins over any template, params or not. */+ it('prefers what the user wrote', () => {+ expect(+ taskText({ taskKey: 'validate', title: 'Ask the agency', titleParams: { a: 1 } }, t),+ ).toBe('Ask the agency');+ });++ it('renders nothing for a task with neither a title nor a key', () => {+ expect(taskText({ taskKey: null, title: null }, t)).toBe('');+ });+});diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex dee77dd44..07c8a24f7 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -206,10 +206,22 @@ export function memberLabel(member: { fullName: string | null; email: string }):* the key stays behind so which template a task grew from is still answerable.*/export function taskText(- task: { taskKey: string | null; title: string | null },+ task: {+ taskKey: string | null;+ title: string | null;+ titleParams?: Record<string, string | number>;+ },t: Translator,): string {const title = task.title?.trim();if (title) return title;- return task.taskKey ? t(task.taskKey) : '';+ if (!task.taskKey) return '';++ // A planned task that knows what it is about carries the values as+ // parameters and is rendered from the `_target` variant of its message —+ // "Compare gemini-web coverage against chatgpt-web" rather than "Compare+ // platform coverage". No parameters means no target was resolvable, and+ // the plain message is the honest one.+ const params = task.titleParams ?? {};+ return Object.keys(params).length > 0 ? t(`${task.taskKey}_target`, params) : t(task.taskKey);}diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex 81ebb960b..6b1871a2e 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -150,6 +150,14 @@ export interface ActionTask {/** User-supplied text. Takes precedence over the template when present. */title: string | null;status: TaskStatus;+ /**+ * Values the task's text names — the platform, the competitor, the count.+ * Parameters rather than resolved text, so a planned task stays+ * translatable; empty when the task names nothing specific.+ */+ titleParams: Record<string, string | number>;+ /** Task keys within the same action that must finish first. */+ dependsOn: string[];/** Why the task was skipped; null for every other status. */skipReason: string | null;}@@ -183,7 +191,7 @@ export async function getActionDetail(brandId: string, actionId: string): Promisconst [tasksRes, signalsRes, eventsRes, kpisRes] = await Promise.all([supabase.from('action_tasks')- .select('id, position, task_key, title, status, skip_reason')+ .select('id, position, task_key, title, status, skip_reason, title_params, depends_on').eq('action_id', actionId).order('position'),supabase@@ -215,6 +223,8 @@ export async function getActionDetail(brandId: string, actionId: string): PromistaskKey: task.task_key,title: task.title,status: task.status as TaskStatus,+ titleParams: (task.title_params ?? {}) as Record<string, string | number>,+ dependsOn: (task.depends_on ?? []) as string[],skipReason: task.skip_reason,})),signals: mapSignalRows((signalsRes.data ?? []) as SignalRow[]),diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex f1a189801..8a21ec040 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -60,34 +60,52 @@ export type Database = {Row: {action_id: stringcreated_at: string+ depends_on: string[]id: string+ mode: string+ output: Json | null+ permission: stringposition: numberskip_reason: string | nullstatus: stringtask_key: string | null+ task_version: numbertitle: string | null+ title_params: Jsonupdated_at: string}Insert: {action_id: stringcreated_at?: string+ depends_on?: string[]id?: string+ mode?: string+ output?: Json | null+ permission?: stringposition: numberskip_reason?: string | nullstatus?: stringtask_key?: string | null+ task_version?: numbertitle?: string | null+ title_params?: Jsonupdated_at?: string}Update: {action_id?: stringcreated_at?: string+ depends_on?: string[]id?: string+ mode?: string+ output?: Json | null+ permission?: stringposition?: numberskip_reason?: string | nullstatus?: stringtask_key?: string | null+ task_version?: numbertitle?: string | null+ title_params?: Jsonupdated_at?: string}Relationships: [