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): carry out a task through a tool, with a record of it (#833)

Gökhan Geyikdca74c2a6762
diff --git a/server/src/lib/action-center/execution/run.js b/server/src/lib/action-center/execution/run.js
new file mode 100644
index 000000000..55db5ba5e
--- /dev/null
+++ b/server/src/lib/action-center/execution/run.js
@@ -0,0 +1,206 @@
+/**
+ * Carrying out a task automatically (#818, phase 7).
+ *
+ * Phase 5 marked every task with who could carry it out and whether carrying
+ * it out reaches outside Ansvisor; nothing acted on either. This does, under
+ * four rules that are the whole point of the layer:
+ *
+ * 1. **Nothing reaches outside except through a tool.** The tool registry is
+ * the enumerable surface; a task without a tool is not runnable, and says
+ * so rather than improvising.
+ * 2. **Nothing changes outside Ansvisor without approval.** A tool that
+ * writes to a third-party system is blocked until a person has
+ * authorised that task, and the authorisation is recorded on the task
+ * rather than inferred from whoever happened to trigger the run. Reading
+ * a system the brand connected is not a change and needs no approval —
+ * asking for one before every read teaches people to approve blindly.
+ * 3. **Every attempt is recorded** — inputs, tool, result, error. Never the
+ * model's reasoning: that is not evidence, and storing it invites people
+ * to read it as explanation.
+ * 4. **A failed run fails its task, not its action.** A tool that throws
+ * costs one step. The action stays open, the other tasks stay as they
+ * were, and somebody can do that step by hand.
+ *
+ * Deliberately not wired to the nightly cron. The engine underneath it spent
+ * six days failing silently before anyone noticed (#829); an execution layer
+ * that runs unattended belongs after the verification that the thing it
+ * executes for is running at all, not before.
+ */
+
+import supabaseAdmin from '../../../config/supabase.js';
+import { logger } from '../../logger.js';
+import { getTask } from '../tasks/registry.js';
+import { resolveBrandSources } from '../sources.js';
+import { getTool } from './tools.js';
+
+/** A task can only be carried out from the statuses that mean "not done". */
+const RUNNABLE_STATUSES = ['todo', 'in_progress', 'waiting_approval'];
+
+async function record(row) {
+ const { error } = await supabaseAdmin.from('action_task_runs').insert(row);
+ if (error) throw new Error(error.message);
+}
+
+/**
+ * Why this task cannot be carried out right now, or null.
+ *
+ * Every answer is a sentence an operator can act on. "blocked" with no reason
+ * is the failure mode this function exists to avoid.
+ */
+export function blockedReason({ task, primitive, tool, sources, siblings }) {
+ if (!RUNNABLE_STATUSES.includes(task.status)) {
+ return `task is ${task.status}`;
+ }
+ if (!primitive) return `no task primitive named ${task.task_key}`;
+ if (primitive.mode !== 'agent') return 'task is carried out by a person, not automatically';
+ if (!tool) return `no tool implements ${task.task_key} yet`;
+ if (!sources.has(tool.source)) return `brand has no ${tool.source} source`;
+
+ if (tool.writesExternally && !task.approved_by) {
+ return 'changes something outside Ansvisor and has not been approved';
+ }
+
+ const unfinished = (task.depends_on ?? []).filter((key) => {
+ const sibling = siblings.find((row) => row.task_key === key);
+ return sibling && sibling.status !== 'completed' && sibling.status !== 'skipped';
+ });
+ if (unfinished.length > 0) return `waits on ${unfinished.join(', ')}`;
+
+ return null;
+}
+
+/**
+ * What a tool is given: the action's own payload, and the structured output
+ * of the tasks this one waits on.
+ *
+ * Upstream outputs travel by task key so a tool reads `inputs.coverage_gaps`
+ * rather than positionally — a plan that drops a task (phase 5) must not
+ * shift what the next one reads.
+ */
+function buildInput({ action, siblings, dependsOn }) {
+ const inputs = {};
+ for (const key of dependsOn ?? []) {
+ const sibling = siblings.find((row) => row.task_key === key);
+ if (sibling?.output) inputs[key] = sibling.output;
+ }
+ return { payload: action.payload ?? {}, inputs };
+}
+
+/**
+ * Carry out one task.
+ *
+ * Never throws for an ordinary refusal — a blocked task is an outcome, not an
+ * error, and callers running a list of them should not stop at the first one
+ * that is waiting on something.
+ *
+ * @param {string} taskId
+ * @param {{ now?: Date, sources?: Set<string> }} [options]
+ */
+export async function runTask(taskId, { now = new Date(), sources } = {}) {
+ const { data: task, error: taskErr } = await supabaseAdmin
+ .from('action_tasks')
+ .select('id, action_id, task_key, status, depends_on, approved_by')
+ .eq('id', taskId)
+ .single();
+ if (taskErr) throw new Error(taskErr.message);
+
+ const { data: action, error: actionErr } = await supabaseAdmin
+ .from('actions')
+ .select('id, brand_id, payload')
+ .eq('id', task.action_id)
+ .single();
+ if (actionErr) throw new Error(actionErr.message);
+
+ const { data: siblings, error: siblingErr } = await supabaseAdmin
+ .from('action_tasks')
+ .select('task_key, status, output')
+ .eq('action_id', task.action_id);
+ if (siblingErr) throw new Error(siblingErr.message);
+
+ const primitive = getTask(task.task_key);
+ const tool = primitive?.tool ? getTool(primitive.tool) : null;
+ const available = sources ?? (await resolveBrandSources(action.brand_id));
+
+ const refusal = blockedReason({
+ task,
+ primitive,
+ tool,
+ sources: available,
+ siblings: siblings ?? [],
+ });
+ if (refusal) {
+ await record({
+ task_id: task.id,
+ action_id: action.id,
+ brand_id: action.brand_id,
+ tool_id: tool?.id ?? null,
+ tool_version: tool?.version ?? null,
+ status: 'blocked',
+ error: refusal,
+ started_at: now.toISOString(),
+ finished_at: now.toISOString(),
+ });
+ // A task held for approval says so in its own status, so the person who
+ // has to decide can find it without reading the run log.
+ if (tool?.writesExternally && !task.approved_by && task.status !== 'waiting_approval') {
+ await supabaseAdmin
+ .from('action_tasks')
+ .update({ status: 'waiting_approval', updated_at: now.toISOString() })
+ .eq('id', task.id);
+ }
+ logger.info({ taskId, reason: refusal }, '[task-run] blocked');
+ return { status: 'blocked', reason: refusal };
+ }
+
+ const input = buildInput({ action, siblings: siblings ?? [], dependsOn: task.depends_on });
+ const startedAt = new Date();
+
+ try {
+ const output = await tool.run({ brandId: action.brand_id, payload: input.payload, input, now });
+
+ await record({
+ task_id: task.id,
+ action_id: action.id,
+ brand_id: action.brand_id,
+ tool_id: tool.id,
+ tool_version: tool.version,
+ status: 'succeeded',
+ input,
+ output,
+ started_at: startedAt.toISOString(),
+ finished_at: new Date().toISOString(),
+ });
+
+ const { error } = await supabaseAdmin
+ .from('action_tasks')
+ .update({ status: 'completed', output, updated_at: new Date().toISOString() })
+ .eq('id', task.id);
+ if (error) throw new Error(error.message);
+
+ logger.info({ taskId, tool: tool.id }, '[task-run] completed');
+ return { status: 'succeeded', output };
+ } catch (err) {
+ // The action is deliberately untouched. One step failing is one step to
+ // do by hand, not a recovery plan cancelled.
+ await record({
+ task_id: task.id,
+ action_id: action.id,
+ brand_id: action.brand_id,
+ tool_id: tool.id,
+ tool_version: tool.version,
+ status: 'failed',
+ input,
+ error: err.message,
+ started_at: startedAt.toISOString(),
+ finished_at: new Date().toISOString(),
+ });
+
+ await supabaseAdmin
+ .from('action_tasks')
+ .update({ status: 'failed', updated_at: new Date().toISOString() })
+ .eq('id', task.id);
+
+ logger.error({ err, taskId, tool: tool.id }, '[task-run] failed');
+ return { status: 'failed', error: err.message };
+ }
+}
diff --git a/server/src/lib/action-center/execution/run.test.js b/server/src/lib/action-center/execution/run.test.js
new file mode 100644
index 000000000..8743aecfb
--- /dev/null
+++ b/server/src/lib/action-center/execution/run.test.js
@@ -0,0 +1,276 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const from = vi.fn();
+const rpc = vi.fn();
+vi.mock('../../../config/supabase.js', () => ({
+ default: { from: (...a) => from(...a), rpc: (...a) => rpc(...a) },
+}));
+vi.mock('../../logger.js', () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+vi.mock('../../composio.js', () => ({ runGaReport: vi.fn() }));
+
+import { blockedReason, runTask } from './run.js';
+import { TOOLS } from './tools.js';
+
+const TASK = 'task-1';
+const ACTION = 'action-1';
+const BRAND = 'brand-1';
+const NOW = new Date('2026-09-25T06:00:00Z');
+const ALL = new Set(['tracking', 'competitors', 'site_audits', 'analytics']);
+
+/**
+ * Enough PostgREST to drive one run. Tables answer from fixtures; every write
+ * is recorded so a test can assert what the attempt actually left behind.
+ */
+function mockDb({ task, action, siblings = [] }) {
+ const writes = { inserted: [], updated: [] };
+ from.mockImplementation((table) => {
+ const builder = {
+ select: () => builder,
+ eq: () => builder,
+ // `.single()` fetches one row — the task, or its action. Awaiting the
+ // builder without it is the sibling list.
+ single: () => Promise.resolve({ data: table === 'actions' ? action : task, error: null }),
+ insert: (row) => {
+ writes.inserted.push({ table, row });
+ return Promise.resolve({ error: null });
+ },
+ update: (patch) => {
+ writes.updated.push({ table, patch });
+ return builder;
+ },
+ then: (resolve, reject) =>
+ Promise.resolve({
+ data: table === 'action_tasks' ? siblings : [],
+ error: null,
+ }).then(resolve, reject),
+ };
+ return builder;
+ });
+ return writes;
+}
+
+const task = (over = {}) => ({
+ id: TASK,
+ action_id: ACTION,
+ task_key: 'validate',
+ status: 'todo',
+ depends_on: [],
+ approved_by: null,
+ ...over,
+});
+
+const action = { id: ACTION, brand_id: BRAND, payload: { promptCount: 4 } };
+
+beforeEach(() => {
+ from.mockReset();
+ rpc.mockReset();
+ rpc.mockResolvedValue({
+ data: { answers: 100, mention_answers: 20, citation_answers: 8 },
+ error: null,
+ });
+});
+
+describe('runTask', () => {
+ it('carries out a task through its tool and stores the result', async () => {
+ const writes = mockDb({ task: task(), action });
+
+ const result = await runTask(TASK, { now: NOW, sources: ALL });
+
+ expect(result.status).toBe('succeeded');
+ const run = writes.inserted.find((w) => w.table === 'action_task_runs');
+ expect(run.row).toMatchObject({
+ task_id: TASK,
+ action_id: ACTION,
+ brand_id: BRAND,
+ tool_id: 'visibility_window',
+ status: 'succeeded',
+ });
+ expect(run.row.finished_at).toBeTruthy();
+
+ const completed = writes.updated.find((w) => w.table === 'action_tasks');
+ expect(completed.patch.status).toBe('completed');
+ expect(completed.patch.output.answers).toBe(100);
+ });
+
+ /**
+ * The rule the whole layer exists for. No tool that writes to a
+ * third-party system ships yet, so this stands one in — the gate has to be
+ * provable before there is something for it to hold back, not afterwards.
+ */
+ describe('changing something outside Ansvisor', () => {
+ const outreach = { id: 'outreach', version: 1, writesExternally: true, source: 'tracking' };
+ const primitive = { mode: 'agent', tool: 'outreach' };
+
+ it('refuses to run without an approval', () => {
+ expect(
+ blockedReason({
+ task: task({ approved_by: null }),
+ primitive,
+ tool: outreach,
+ sources: ALL,
+ siblings: [],
+ }),
+ ).toMatch(/not been approved/);
+ });
+
+ it('runs once a person has approved it', () => {
+ expect(
+ blockedReason({
+ task: task({ approved_by: 'user-1' }),
+ primitive,
+ tool: outreach,
+ sources: ALL,
+ siblings: [],
+ }),
+ ).toBeNull();
+ });
+
+ /** Reading a system the brand connected is not a change. Requiring
+ * approval for it would teach people to approve without reading. */
+ it('does not ask for approval to read', () => {
+ expect(
+ blockedReason({
+ task: task({ approved_by: null }),
+ primitive: { mode: 'agent', tool: 'visibility_window' },
+ tool: TOOLS.visibility_window,
+ sources: ALL,
+ siblings: [],
+ }),
+ ).toBeNull();
+ });
+ });
+
+ /** One step failing is one step to do by hand, not a plan cancelled. */
+ it('fails the task and leaves the action alone', async () => {
+ rpc.mockRejectedValue(new Error('statement timeout'));
+ const writes = mockDb({ task: task(), action });
+
+ const result = await runTask(TASK, { now: NOW, sources: ALL });
+
+ expect(result.status).toBe('failed');
+ expect(writes.updated.find((w) => w.table === 'action_tasks').patch.status).toBe('failed');
+ expect(writes.updated.some((w) => w.table === 'actions')).toBe(false);
+ const run = writes.inserted.find((w) => w.table === 'action_task_runs');
+ expect(run.row).toMatchObject({ status: 'failed' });
+ expect(run.row.error).toContain('timeout');
+ });
+
+ it('records a blocked attempt rather than passing over it in silence', async () => {
+ const writes = mockDb({ task: task({ task_key: 'update_content' }), action });
+
+ const result = await runTask(TASK, { now: NOW, sources: ALL });
+
+ expect(result.status).toBe('blocked');
+ expect(writes.inserted.find((w) => w.table === 'action_task_runs').row).toMatchObject({
+ status: 'blocked',
+ });
+ });
+
+ it('never stores the model’s reasoning, because nothing may put it there', async () => {
+ const writes = mockDb({ task: task(), action });
+
+ await runTask(TASK, { now: NOW, sources: ALL });
+
+ const run = writes.inserted.find((w) => w.table === 'action_task_runs').row;
+ expect(Object.keys(run)).toEqual(
+ expect.not.arrayContaining(['reasoning', 'thoughts', 'chain_of_thought']),
+ );
+ });
+});
+
+describe('blockedReason', () => {
+ const primitive = { mode: 'agent', tool: 'visibility_window' };
+ const tool = TOOLS.visibility_window;
+
+ it('lets a runnable task through', () => {
+ expect(blockedReason({ task: task(), primitive, tool, sources: ALL, siblings: [] })).toBeNull();
+ });
+
+ it('stops a task a person owns', () => {
+ expect(
+ blockedReason({
+ task: task(),
+ primitive: { mode: 'manual', tool: null },
+ tool: null,
+ sources: ALL,
+ siblings: [],
+ }),
+ ).toMatch(/by a person/);
+ });
+
+ /** Fourteen agent-mode tasks have no tool yet. Saying so is the difference
+ * between an honest gap and a silent one. */
+ it('names the gap when a task is meant to be automated and is not yet', () => {
+ expect(
+ blockedReason({
+ task: task({ task_key: 'coverage_gaps' }),
+ primitive: { mode: 'agent', tool: null },
+ tool: null,
+ sources: ALL,
+ siblings: [],
+ }),
+ ).toMatch(/no tool implements coverage_gaps/);
+ });
+
+ it('stops a tool whose source the brand does not have', () => {
+ expect(
+ blockedReason({
+ task: task(),
+ primitive,
+ tool: { ...tool, source: 'analytics' },
+ sources: new Set(['tracking']),
+ siblings: [],
+ }),
+ ).toMatch(/no analytics source/);
+ });
+
+ it('waits for the tasks this one depends on', () => {
+ expect(
+ blockedReason({
+ task: task({ depends_on: ['analyze_losses'] }),
+ primitive,
+ tool,
+ sources: ALL,
+ siblings: [{ task_key: 'analyze_losses', status: 'todo' }],
+ }),
+ ).toMatch(/waits on analyze_losses/);
+ });
+
+ it('treats a skipped dependency as finished, because nobody is going to do it', () => {
+ expect(
+ blockedReason({
+ task: task({ depends_on: ['analyze_losses'] }),
+ primitive,
+ tool,
+ sources: ALL,
+ siblings: [{ task_key: 'analyze_losses', status: 'skipped' }],
+ }),
+ ).toBeNull();
+ });
+
+ it('ignores a dependency that was never planned', () => {
+ expect(
+ blockedReason({
+ task: task({ depends_on: ['a_task_this_plan_does_not_have'] }),
+ primitive,
+ tool,
+ sources: ALL,
+ siblings: [],
+ }),
+ ).toBeNull();
+ });
+
+ it('does not re-run a task that is already done', () => {
+ expect(
+ blockedReason({
+ task: task({ status: 'completed' }),
+ primitive,
+ tool,
+ sources: ALL,
+ siblings: [],
+ }),
+ ).toMatch(/is completed/);
+ });
+});
diff --git a/server/src/lib/action-center/execution/tools.js b/server/src/lib/action-center/execution/tools.js
new file mode 100644
index 000000000..19fb62c7f
--- /dev/null
+++ b/server/src/lib/action-center/execution/tools.js
@@ -0,0 +1,168 @@
+/**
+ * The tool registry (#818, phase 7).
+ *
+ * A task that runs automatically does so through exactly one tool, and a tool
+ * is the only way anything automated reaches data or a third-party system.
+ * That is the point of having a registry rather than letting each task call
+ * whatever it likes: what the engine can touch is enumerable, and what it can
+ * touch *outside Ansvisor* is a property declared on the tool rather than a
+ * fact discovered afterwards in a log.
+ *
+ * Each tool declares:
+ *
+ * - `source` — the brand source it needs, the same vocabulary the definition
+ * registry and the planner already use. A brand without it never has the
+ * task planned, and the runner refuses anyway;
+ * - `writesExternally` — whether running it *changes* something outside
+ * Ansvisor. Reading a third-party system is not that: the brand
+ * authorised the analytics connection and we already read it nightly, and
+ * asking for approval before every read would teach people to approve
+ * without looking. What needs a person is a change they would have to
+ * undo. Neither tool here writes, so the flag is false on both — but the
+ * runner enforces it now, while there is nothing to gate, rather than
+ * leaving it to be written later under deadline;
+ * - `version` — bumped when what the tool does changes, recorded on every
+ * run so an old result stays readable against the rules it ran under.
+ *
+ * Arguments are built by the tool from the action's own payload. Nothing here
+ * takes a query, a URL or a property id from anywhere a model could reach —
+ * the same rule the GA sync already follows, and the reason this layer can be
+ * audited at all.
+ */
+
+import supabaseAdmin from '../../../config/supabase.js';
+import { runGaReport } from '../../composio.js';
+import { resolve } from '../../../config/action-engine.js';
+
+const DAY_MS = 86_400_000;
+
+const { validation } = resolve();
+
+function utcDay(date) {
+ return date.toISOString().slice(0, 10);
+}
+
+/** One connection per organization per provider (#577). */
+function entityIdFor(organizationId) {
+ return `org_${organizationId}`;
+}
+
+const tool = (id, spec) => Object.freeze({ id, version: 1, writesExternally: false, ...spec });
+
+export const TOOLS = Object.freeze({
+ /**
+ * The AI Visibility Score over the validation window and the one before it
+ * — what `validate` asks for, read from the daily rollups rather than the
+ * raw scan, for the reason #829 exists.
+ */
+ visibility_window: tool('visibility_window', {
+ source: 'tracking',
+ description: "The brand's AI Visibility over the last window and the one before it.",
+
+ async run({ brandId, now }) {
+ const length = validation.windowDays;
+ const to = utcDay(now);
+ const from = utcDay(new Date(now.getTime() - (length - 1) * DAY_MS));
+ const previousTo = utcDay(new Date(Date.parse(from) - DAY_MS));
+ const previousFrom = utcDay(new Date(Date.parse(from) - length * DAY_MS));
+
+ const read = async (dayFrom, dayTo) => {
+ const { data, error } = await supabaseAdmin.rpc('ai_visibility_aggregates_daily', {
+ p_brand_id: brandId,
+ p_day_from: dayFrom,
+ p_day_to: dayTo,
+ });
+ if (error) throw new Error(error.message);
+ return data ?? {};
+ };
+
+ const [current, previous] = await Promise.all([
+ read(from, to),
+ read(previousFrom, previousTo),
+ ]);
+
+ return {
+ window: { from, to },
+ previousWindow: { from: previousFrom, to: previousTo },
+ answers: current.answers ?? 0,
+ mentionAnswers: current.mention_answers ?? 0,
+ citationAnswers: current.citation_answers ?? 0,
+ previousAnswers: previous.answers ?? 0,
+ previousMentionAnswers: previous.mention_answers ?? 0,
+ previousCitationAnswers: previous.citation_answers ?? 0,
+ };
+ },
+ }),
+
+ /**
+ * Sessions on the action's own pages, before and after, from the brand's
+ * analytics property through the connection they authorised.
+ *
+ * Read live rather than from `ga_page_stats`: the sync stores the top pages
+ * of each day and says so when it truncates, which is the right trade for a
+ * dashboard and the wrong one for a measurement of *these* pages. A page
+ * outside that day's ceiling is absent from the table but present in the
+ * property, and reporting zero sessions for it would be a wrong answer
+ * rather than a missing one.
+ */
+ ga_traffic_window: tool('ga_traffic_window', {
+ source: 'analytics',
+ description: "Sessions on the action's pages over the last window and the one before it.",
+
+ async run({ brandId, payload, now }) {
+ const { data: brand, error } = await supabaseAdmin
+ .from('brands')
+ .select('organization_id, ga_property_id')
+ .eq('id', brandId)
+ .single();
+ if (error) throw new Error(error.message);
+ if (!brand?.ga_property_id) throw new Error('brand has no analytics property configured');
+
+ const length = validation.windowDays;
+ const startDate = utcDay(new Date(now.getTime() - (length - 1) * DAY_MS));
+ const endDate = utcDay(now);
+ const previousEnd = utcDay(new Date(Date.parse(startDate) - DAY_MS));
+ const previousStart = utcDay(new Date(Date.parse(startDate) - length * DAY_MS));
+
+ const report = await runGaReport(entityIdFor(brand.organization_id), brand.ga_property_id, {
+ dateRanges: [
+ { startDate, endDate, name: 'current' },
+ { startDate: previousStart, endDate: previousEnd, name: 'previous' },
+ ],
+ dimensions: [{ name: 'landingPagePlusQueryString' }],
+ metrics: [{ name: 'sessions' }],
+ limit: 200,
+ });
+
+ const sessions = { current: {}, previous: {} };
+ for (const row of report?.rows ?? []) {
+ const page = row.dimensionValues?.[0]?.value;
+ const range = row.dimensionValues?.[1]?.value ?? 'current';
+ const value = Number(row.metricValues?.[0]?.value ?? 0);
+ if (page) sessions[range === 'previous' ? 'previous' : 'current'][page] = value;
+ }
+
+ // Only the pages this action is about. A page the action never named is
+ // not evidence about it, however much traffic it has.
+ const pages = Array.isArray(payload?.urls) ? payload.urls : [];
+ const named = pages.length > 0 ? pages : Object.keys(sessions.current);
+ const total = (bucket) => named.reduce((sum, page) => sum + (bucket[page] ?? 0), 0);
+
+ return {
+ window: { from: startDate, to: endDate },
+ previousWindow: { from: previousStart, to: previousEnd },
+ pages: named.length,
+ sessions: total(sessions.current),
+ previousSessions: total(sessions.previous),
+ };
+ },
+ }),
+});
+
+export function getTool(id) {
+ return TOOLS[id] ?? null;
+}
+
+export function listTools() {
+ return Object.values(TOOLS);
+}
diff --git a/server/src/lib/action-center/tasks/plan.test.js b/server/src/lib/action-center/tasks/plan.test.js
index 073445d95..0b0470519 100644
--- a/server/src/lib/action-center/tasks/plan.test.js
+++ b/server/src/lib/action-center/tasks/plan.test.js
@@ -8,6 +8,7 @@ vi.mock('../../../config/supabase.js', () => ({ default: { from: vi.fn(), rpc: v
import { planTasks } from './plan.js';
import { TASKS, listTasks, validateTask } from './registry.js';
import { loadDefinitions } from '../definitions/index.js';
+import { TOOLS } from '../execution/tools.js';
const ALL = new Set(['tracking', 'competitors', 'site_audits', 'analytics']);
const BARE = new Set(['tracking']);
@@ -210,6 +211,37 @@ describe('the task registry', () => {
}
});
+ /**
+ * A task naming a tool that does not exist is not runnable and nothing
+ * would say why — the runner would report "no tool implements this", which
+ * is true and misleading. Caught here instead.
+ */
+ it('names a real tool wherever it names one', () => {
+ for (const entry of listTasks()) {
+ if (!entry.tool) continue;
+ expect({ id: entry.id, tool: entry.tool, exists: Boolean(TOOLS[entry.tool]) }).toEqual({
+ id: entry.id,
+ tool: entry.tool,
+ exists: true,
+ });
+ }
+ });
+
+ /**
+ * A tool can only be given to a task that is meant to be automated, and the
+ * brand needs the tool's source as well as the task's own — otherwise a
+ * task is planned that can never run.
+ */
+ it('only gives tools to agent tasks, whose requirements cover the tool’s', () => {
+ for (const entry of listTasks()) {
+ if (!entry.tool) continue;
+ expect({ id: entry.id, mode: entry.mode }).toEqual({ id: entry.id, mode: 'agent' });
+ const source = TOOLS[entry.tool].source;
+ const covered = source === 'tracking' || entry.requires.includes(source);
+ expect({ id: entry.id, source, covered }).toEqual({ id: entry.id, source, covered: true });
+ }
+ });
+
/**
* The registry says a task can produce structured output; the planner is
* what has to keep the declaration reachable. A task declaring outputs
diff --git a/server/src/lib/action-center/tasks/registry.js b/server/src/lib/action-center/tasks/registry.js
index 2a107b603..e38840b13 100644
--- a/server/src/lib/action-center/tasks/registry.js
+++ b/server/src/lib/action-center/tasks/registry.js
@@ -52,6 +52,10 @@ const task = (id, spec) =>
* 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 ?? []),
+ /** The tool that carries this task out, if one does yet. A task with a
+ * mode of `agent` and no tool is one we mean to automate and have not —
+ * the runner says exactly that rather than improvising. */
+ tool: spec.tool ?? null,
});
/**
@@ -119,6 +123,7 @@ export const TASKS = Object.freeze({
requires: ['analytics'],
dependsOn: ['analyze_losses'],
outputs: ['sessionsLost'],
+ tool: 'ga_traffic_window',
}),
competitor_pressure: task('competitor_pressure', {
mode: 'agent',
@@ -151,7 +156,10 @@ export const TASKS = Object.freeze({
}),
// ── Checking whether it worked ───────────────────────────────────────────
- validate: task('validate', { mode: 'agent' }),
+ // The two tasks a tool carries out today. `mode: 'agent'` says a task
+ // could be automated; `tool` says it is. The rest keep the mode and wait
+ // for a tool, the same way definitions waited for detectors.
+ validate: task('validate', { mode: 'agent', tool: 'visibility_window' }),
revalidate: task('revalidate', { mode: 'agent', requires: ['site_audits'] }),
});
diff --git a/server/src/scripts/run-action-task.js b/server/src/scripts/run-action-task.js
new file mode 100644
index 000000000..f59111264
--- /dev/null
+++ b/server/src/scripts/run-action-task.js
@@ -0,0 +1,62 @@
+/**
+ * Carry out one action task automatically (#818, phase 7).
+ *
+ * Deliberately a script rather than a cron step. The nightly engine that
+ * produces these tasks spent six days failing silently before anyone noticed
+ * (#829); an execution layer that runs unattended belongs after the
+ * verification that the thing it executes for is running, not before. When
+ * that verification exists, this function is what a schedule or a button
+ * calls — the decision is about when to pull the trigger, not about whether
+ * the mechanism works.
+ *
+ * `--dry` reports what would happen and why, without running anything: the
+ * same refusal the runner would give, which is the useful half when the
+ * question is "why has this task not run".
+ *
+ * Run: node src/scripts/run-action-task.js <taskId> [--dry]
+ */
+import 'dotenv/config';
+import supabaseAdmin from '../config/supabase.js';
+import { getTask } from '../lib/action-center/tasks/registry.js';
+import { getTool } from '../lib/action-center/execution/tools.js';
+import { blockedReason, runTask } from '../lib/action-center/execution/run.js';
+import { resolveBrandSources } from '../lib/action-center/sources.js';
+
+const taskId = process.argv[2];
+const dry = process.argv.includes('--dry');
+
+if (!taskId) {
+ console.error('Usage: node src/scripts/run-action-task.js <taskId> [--dry]');
+ process.exit(1);
+}
+
+if (dry) {
+ const { data: task, error } = await supabaseAdmin
+ .from('action_tasks')
+ .select('id, action_id, task_key, status, depends_on, approved_by')
+ .eq('id', taskId)
+ .single();
+ if (error) throw new Error(error.message);
+
+ const { data: action } = await supabaseAdmin
+ .from('actions')
+ .select('brand_id')
+ .eq('id', task.action_id)
+ .single();
+ const { data: siblings } = await supabaseAdmin
+ .from('action_tasks')
+ .select('task_key, status, output')
+ .eq('action_id', task.action_id);
+
+ const primitive = getTask(task.task_key);
+ const tool = primitive?.tool ? getTool(primitive.tool) : null;
+ const sources = await resolveBrandSources(action.brand_id);
+
+ const reason = blockedReason({ task, primitive, tool, sources, siblings: siblings ?? [] });
+ console.log(`${task.task_key}: ${reason ? `blocked — ${reason}` : `would run via ${tool.id}`}`);
+ process.exit(0);
+}
+
+const result = await runTask(taskId);
+console.log(JSON.stringify(result, null, 2));
+process.exit(result.status === 'failed' ? 1 : 0);
diff --git a/supabase/migrations/00090_action_task_runs.sql b/supabase/migrations/00090_action_task_runs.sql
new file mode 100644
index 000000000..eb64ecf4d
--- /dev/null
+++ b/supabase/migrations/00090_action_task_runs.sql
@@ -0,0 +1,73 @@
+-- Action Engine, phase 7 (#818): what an automated task actually did.
+--
+-- Phase 5 marked every task with who could carry it out and whether carrying
+-- it out reaches outside Ansvisor. Nothing acted on either. This is the layer
+-- that does, and the first thing it needs is a record — because an automated
+-- step nobody can audit is worse than a manual one nobody automated.
+--
+-- One row per attempt, successful or not. Attempts are kept rather than
+-- overwritten: a task that failed twice and then worked is a different story
+-- from one that worked first time, and the difference is the one an operator
+-- needs.
+--
+-- What is deliberately NOT stored: the model's reasoning. Inputs, the tool
+-- called, its arguments, its result and any error — those are the record.
+-- Chain-of-thought is not evidence, it is not reliable as explanation, and
+-- exposing it invites people to treat it as either. Anything a run wants to
+-- claim it must claim in `output`, where the next task can read it.
+
+create table if not exists public.action_task_runs (
+ id uuid primary key default gen_random_uuid(),
+
+ task_id uuid not null references public.action_tasks(id) on delete cascade,
+ -- Denormalised so a brand's whole execution history is one query, and so a
+ -- run survives in context when its task is read on its own.
+ action_id uuid not null references public.actions(id) on delete cascade,
+ brand_id uuid not null references public.brands(id) on delete cascade,
+
+ -- The tool the task was carried out with, and the version of it. A tool
+ -- whose behaviour changes gets a new version, so an old run stays readable
+ -- against the rules it ran under — as actions and tasks already do.
+ tool_id text,
+ tool_version integer,
+
+ -- 'succeeded' — the tool ran and its result was stored
+ -- 'failed' — it threw; the task fails, the action does not
+ -- 'blocked' — it was not allowed to run: awaiting approval, a source the
+ -- brand does not have, a dependency not finished, or no tool
+ -- for this task yet. `error` says which.
+ status text not null check (status in ('succeeded', 'failed', 'blocked')),
+
+ -- What the tool was given and what it returned. Both are structured and
+ -- both are the audit trail; `output` is also what the task stores and what
+ -- downstream tasks read.
+ input jsonb not null default '{}'::jsonb,
+ output jsonb,
+ error text,
+
+ started_at timestamptz not null default now(),
+ finished_at timestamptz
+);
+
+create index if not exists action_task_runs_task_idx
+ on public.action_task_runs (task_id, started_at desc);
+
+create index if not exists action_task_runs_brand_idx
+ on public.action_task_runs (brand_id, started_at desc);
+
+-- Who authorised a task that reaches outside Ansvisor, and when.
+--
+-- Separate from the run so the authorisation survives the attempt: a run that
+-- failed on a network error must not need a second human decision, and an
+-- approval that was given must stay auditable even if every attempt failed.
+alter table public.action_tasks
+ add column if not exists approved_by uuid references public.profiles(id) on delete set null,
+ add column if not exists approved_at timestamptz;
+
+comment on column public.action_tasks.approved_by is
+ 'Who authorised this task to reach outside Ansvisor. Required before a task whose permission is ''approval'' may run; null means it has not been authorised.';
+
+alter table public.action_task_runs enable row level security;
+
+comment on table public.action_task_runs is
+ 'One row per attempt to carry out a task automatically. Inputs, tool, result and error — never the model''s reasoning.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index a74695839..675cc61d3 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -10650,3 +10650,80 @@ comment on table public.action_candidates is
comment on column public.action_candidates.priority is
'Score at the last pass. Impact, weight of evidence, and how long it has waited — see config/action-engine.js.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00090_action_task_runs.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Action Engine, phase 7 (#818): what an automated task actually did.
+--
+-- Phase 5 marked every task with who could carry it out and whether carrying
+-- it out reaches outside Ansvisor. Nothing acted on either. This is the layer
+-- that does, and the first thing it needs is a record — because an automated
+-- step nobody can audit is worse than a manual one nobody automated.
+--
+-- One row per attempt, successful or not. Attempts are kept rather than
+-- overwritten: a task that failed twice and then worked is a different story
+-- from one that worked first time, and the difference is the one an operator
+-- needs.
+--
+-- What is deliberately NOT stored: the model's reasoning. Inputs, the tool
+-- called, its arguments, its result and any error — those are the record.
+-- Chain-of-thought is not evidence, it is not reliable as explanation, and
+-- exposing it invites people to treat it as either. Anything a run wants to
+-- claim it must claim in `output`, where the next task can read it.
+
+create table if not exists public.action_task_runs (
+ id uuid primary key default gen_random_uuid(),
+
+ task_id uuid not null references public.action_tasks(id) on delete cascade,
+ -- Denormalised so a brand's whole execution history is one query, and so a
+ -- run survives in context when its task is read on its own.
+ action_id uuid not null references public.actions(id) on delete cascade,
+ brand_id uuid not null references public.brands(id) on delete cascade,
+
+ -- The tool the task was carried out with, and the version of it. A tool
+ -- whose behaviour changes gets a new version, so an old run stays readable
+ -- against the rules it ran under — as actions and tasks already do.
+ tool_id text,
+ tool_version integer,
+
+ -- 'succeeded' — the tool ran and its result was stored
+ -- 'failed' — it threw; the task fails, the action does not
+ -- 'blocked' — it was not allowed to run: awaiting approval, a source the
+ -- brand does not have, a dependency not finished, or no tool
+ -- for this task yet. `error` says which.
+ status text not null check (status in ('succeeded', 'failed', 'blocked')),
+
+ -- What the tool was given and what it returned. Both are structured and
+ -- both are the audit trail; `output` is also what the task stores and what
+ -- downstream tasks read.
+ input jsonb not null default '{}'::jsonb,
+ output jsonb,
+ error text,
+
+ started_at timestamptz not null default now(),
+ finished_at timestamptz
+);
+
+create index if not exists action_task_runs_task_idx
+ on public.action_task_runs (task_id, started_at desc);
+
+create index if not exists action_task_runs_brand_idx
+ on public.action_task_runs (brand_id, started_at desc);
+
+-- Who authorised a task that reaches outside Ansvisor, and when.
+--
+-- Separate from the run so the authorisation survives the attempt: a run that
+-- failed on a network error must not need a second human decision, and an
+-- approval that was given must stay auditable even if every attempt failed.
+alter table public.action_tasks
+ add column if not exists approved_by uuid references public.profiles(id) on delete set null,
+ add column if not exists approved_at timestamptz;
+
+comment on column public.action_tasks.approved_by is
+ 'Who authorised this task to reach outside Ansvisor. Required before a task whose permission is ''approval'' may run; null means it has not been authorised.';
+
+alter table public.action_task_runs enable row level security;
+
+comment on table public.action_task_runs is
+ 'One row per attempt to carry out a task automatically. Inputs, tool, result and error — never the model''s reasoning.';
+