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(mcp): review the tasks waiting for review: list, approve and dismiss (#1713)

Cihan92e45247ae2f
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdx
index 9f63d26d7..bdd009c4a 100644
--- a/docs/guides/mcp-server.mdx
+++ b/docs/guides/mcp-server.mdx
@@ -220,7 +220,7 @@ instead.
## Available tools
-The MCP server exposes **62 tools**. Descriptions below match
+The MCP server exposes **65 tools**. Descriptions below match
[`web/src/lib/mcp/server.ts`](https://github.com/ansvisor/ansvisor/blob/main/web/src/lib/mcp/server.ts).
Tools that change data are marked **writes** — only call them on explicit user
intent, not during exploratory queries. A write that needs a particular role
@@ -375,9 +375,13 @@ The Shelf, Readiness and What AI says need a plan with Product Visibility (Growt
| `list_action_history` | Closed actions with measured outcomes and before/after validation results, each with `net_of_control` (its change net of the brand's prompts it didn't touch, so a market-wide swing doesn't read as its effect) and `dismiss_reason` (`not_relevant`, `already_done`, `wrong_data` or `not_now`). | |
| `get_action_scorecard` | What each kind of action did at the brand, as the History tab's scorecard shows it: completed and their results, `success_rate` (from three verdicts), `median_change_percent`, and dismissals by reason. Optional `date_from`. | |
| `update_task_status` | Record progress on a task (`in_progress`, `completed`, `skipped`, `failed`); does not execute the task. | **yes** |
+| `list_task_reviews` | Tasks waiting for review, as the **Needs review** tab shows them: tasks an AI writer gave without the exact page, the change, Done when or how it is checked, each with `missing` (the fields to fill). Admins and managers only. | |
+| `approve_task_review` | Approve one onto its action's task list, as the tab's **Approve** does: the fields given (`url`, `change`, `done_when`, `check`, and optionally `title`, `where`, `why`, `how`) replace what was written, and all four must be filled. | **yes** (admin, manager) |
+| `dismiss_task_review` | Dismiss one, as the tab's **Dismiss** does: it never reaches its action. | **yes** (admin, manager) |
| `create_improve_action` | Send a prompt's Improve suggestions to Action Center as a `prompt_improve` action (needs a generated suggestion set for the range and a plan with Improve; idempotent on `idempotency_key`). | **yes** |
The scorecard is also available over REST: `GET /api/mcp/action-scorecard?brand_id=<brand_id>&date_from=2026-09-01`.
+The review queue is also available over REST: `GET /api/mcp/task-reviews?brand_id=<brand_id>`, and `POST /api/mcp/task-reviews/<id>/approve` (the fields as JSON) or `/dismiss`.
#### Export an action
@@ -415,8 +419,8 @@ answers in plain English using the returned data.
A key acts as the person who created it, with their role in the
organization. `get_me` returns it. Day-to-day work is open to every role:
reading, drafts and suggestions in the Content Editor, briefs, Site Audits,
-task progress and an opportunity's progress. Adding prompts or topics and
-dismissing are for admins and managers. Dismissing a prompt suggestion is open
+task progress and an opportunity's progress. Adding prompts or topics,
+reviewing tasks and dismissing are for admins and managers. Dismissing a prompt suggestion is open
to analysts too. The tools marked with roles above refuse anyone else before
they change anything. The call fails with text like this:
diff --git a/supabase/migrations/00375_task_review_approve_api.sql b/supabase/migrations/00375_task_review_approve_api.sql
new file mode 100644
index 000000000..94f17683d
--- /dev/null
+++ b/supabase/migrations/00375_task_review_approve_api.sql
@@ -0,0 +1,111 @@
+-- ============================================================================
+-- 00375: approving a task waiting for review over the API and MCP (AC-010)
+-- ============================================================================
+-- approve_action_task_review (00293) takes the reviewer from auth.uid(), so
+-- it only works for a signed-in admin or manager. The MCP tools authenticate
+-- with an API key and reach the database as the service role, where
+-- auth.uid() is null.
+--
+-- Restated with p_user_id: the person the service role approves for, the API
+-- key's owner. It counts only for the service role; a signed-in caller is
+-- always auth.uid(), whatever it passes. Either way the person must be an
+-- admin or manager of the review's organization, and the trail says they
+-- added the task, as from the dashboard. Nothing else changes.
+--
+-- The 3-argument function is dropped rather than overloaded: a call with
+-- three arguments would match both, and the dashboard's call keeps working
+-- through p_user_id's default.
+
+drop function if exists public.approve_action_task_review(uuid, text, jsonb);
+
+create or replace function public.approve_action_task_review(
+ p_review_id uuid,
+ p_title text,
+ p_details jsonb,
+ p_user_id uuid default null
+)
+returns uuid
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_review public.action_task_reviews%rowtype;
+ v_title text := btrim(coalesce(p_title, ''));
+ v_task_id uuid;
+ -- Who approves: the API key's owner for the service role, else the caller.
+ v_person uuid := case when auth.role() = 'service_role' then p_user_id else auth.uid() end;
+begin
+ -- The person's role first, before any row is read or locked.
+ if not exists (
+ select 1 from public.profiles p
+ where p.id = v_person and p.role in ('admin', 'manager')
+ ) then
+ raise exception 'not allowed' using errcode = '42501';
+ end if;
+
+ -- Only a row of the person's own organization: another's reads as not there.
+ select r.* into v_review
+ from public.action_task_reviews r
+ join public.actions a on a.id = r.action_id
+ join public.brands b on b.id = a.brand_id
+ join public.profiles p on p.organization_id = b.organization_id
+ where r.id = p_review_id
+ and p.id = v_person
+ for update of r;
+ if not found then
+ return null;
+ end if;
+
+ if exists (
+ select 1 from public.actions a
+ where a.id = v_review.action_id
+ and (a.deleted_at is not null or a.status in ('completed', 'dismissed'))
+ ) then
+ raise exception 'action closed' using errcode = '55000';
+ end if;
+
+ if char_length(v_title) not between 1 and 200
+ or jsonb_typeof(p_details) is distinct from 'object'
+ or nullif(btrim(coalesce(p_details->>'url', '')), '') is null
+ or nullif(btrim(coalesce(p_details->'change'->>'after', '')), '') is null
+ or nullif(btrim(coalesce(p_details->>'doneWhen', '')), '') is null
+ or coalesce(p_details->>'check', '') not in ('auto', 'rerun', 'manual')
+ then
+ raise exception 'incomplete task' using errcode = '22023';
+ end if;
+
+ insert into public.action_tasks (action_id, position, title, status, mode, permission, details)
+ select
+ v_review.action_id,
+ coalesce(max(t.position), 0) + 1,
+ v_title,
+ 'todo',
+ 'human',
+ 'read',
+ -- The reviewer's task now: Regenerate keeps it (task-writer keepsTask).
+ p_details || jsonb_build_object('source', 'reviewed')
+ from public.action_tasks t
+ where t.action_id = v_review.action_id
+ returning id into v_task_id;
+
+ delete from public.action_task_reviews where id = v_review.id;
+
+ insert into public.action_events (action_id, event, data, actor_id)
+ values (v_review.action_id, 'task_added', jsonb_build_object('title', v_title), v_person);
+
+ update public.actions set updated_at = now() where id = v_review.action_id;
+
+ return v_task_id;
+end;
+$$;
+
+revoke all on function public.approve_action_task_review(uuid, text, jsonb, uuid)
+ from public, anon;
+grant execute on function public.approve_action_task_review(uuid, text, jsonb, uuid)
+ to authenticated, service_role;
+
+comment on function public.approve_action_task_review(uuid, text, jsonb, uuid) is
+ 'Action Center (AC-010): a task waiting for review (action_task_reviews) onto its action''s task list, after its last task, with the exact page, the change, Done when and how it is checked filled, as the reviewer''s (source reviewed); the review row goes and the trail says a task was added. Admins and managers of the brand''s organization only, on an action neither deleted nor closed; p_user_id is the person the service role approves for (00375), a signed-in caller is always auth.uid(). Null when the row is gone or another organization''s.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index bd53aa388..12ccd9670 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -43322,6 +43322,121 @@ update public.profiles set work_areas_asked_at = now() where work_areas_asked_at
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00375_task_review_approve_api.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00375: approving a task waiting for review over the API and MCP (AC-010)
+-- ============================================================================
+-- approve_action_task_review (00293) takes the reviewer from auth.uid(), so
+-- it only works for a signed-in admin or manager. The MCP tools authenticate
+-- with an API key and reach the database as the service role, where
+-- auth.uid() is null.
+--
+-- Restated with p_user_id: the person the service role approves for, the API
+-- key's owner. It counts only for the service role; a signed-in caller is
+-- always auth.uid(), whatever it passes. Either way the person must be an
+-- admin or manager of the review's organization, and the trail says they
+-- added the task, as from the dashboard. Nothing else changes.
+--
+-- The 3-argument function is dropped rather than overloaded: a call with
+-- three arguments would match both, and the dashboard's call keeps working
+-- through p_user_id's default.
+
+drop function if exists public.approve_action_task_review(uuid, text, jsonb);
+
+create or replace function public.approve_action_task_review(
+ p_review_id uuid,
+ p_title text,
+ p_details jsonb,
+ p_user_id uuid default null
+)
+returns uuid
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ v_review public.action_task_reviews%rowtype;
+ v_title text := btrim(coalesce(p_title, ''));
+ v_task_id uuid;
+ -- Who approves: the API key's owner for the service role, else the caller.
+ v_person uuid := case when auth.role() = 'service_role' then p_user_id else auth.uid() end;
+begin
+ -- The person's role first, before any row is read or locked.
+ if not exists (
+ select 1 from public.profiles p
+ where p.id = v_person and p.role in ('admin', 'manager')
+ ) then
+ raise exception 'not allowed' using errcode = '42501';
+ end if;
+
+ -- Only a row of the person's own organization: another's reads as not there.
+ select r.* into v_review
+ from public.action_task_reviews r
+ join public.actions a on a.id = r.action_id
+ join public.brands b on b.id = a.brand_id
+ join public.profiles p on p.organization_id = b.organization_id
+ where r.id = p_review_id
+ and p.id = v_person
+ for update of r;
+ if not found then
+ return null;
+ end if;
+
+ if exists (
+ select 1 from public.actions a
+ where a.id = v_review.action_id
+ and (a.deleted_at is not null or a.status in ('completed', 'dismissed'))
+ ) then
+ raise exception 'action closed' using errcode = '55000';
+ end if;
+
+ if char_length(v_title) not between 1 and 200
+ or jsonb_typeof(p_details) is distinct from 'object'
+ or nullif(btrim(coalesce(p_details->>'url', '')), '') is null
+ or nullif(btrim(coalesce(p_details->'change'->>'after', '')), '') is null
+ or nullif(btrim(coalesce(p_details->>'doneWhen', '')), '') is null
+ or coalesce(p_details->>'check', '') not in ('auto', 'rerun', 'manual')
+ then
+ raise exception 'incomplete task' using errcode = '22023';
+ end if;
+
+ insert into public.action_tasks (action_id, position, title, status, mode, permission, details)
+ select
+ v_review.action_id,
+ coalesce(max(t.position), 0) + 1,
+ v_title,
+ 'todo',
+ 'human',
+ 'read',
+ -- The reviewer's task now: Regenerate keeps it (task-writer keepsTask).
+ p_details || jsonb_build_object('source', 'reviewed')
+ from public.action_tasks t
+ where t.action_id = v_review.action_id
+ returning id into v_task_id;
+
+ delete from public.action_task_reviews where id = v_review.id;
+
+ insert into public.action_events (action_id, event, data, actor_id)
+ values (v_review.action_id, 'task_added', jsonb_build_object('title', v_title), v_person);
+
+ update public.actions set updated_at = now() where id = v_review.action_id;
+
+ return v_task_id;
+end;
+$$;
+
+revoke all on function public.approve_action_task_review(uuid, text, jsonb, uuid)
+ from public, anon;
+grant execute on function public.approve_action_task_review(uuid, text, jsonb, uuid)
+ to authenticated, service_role;
+
+comment on function public.approve_action_task_review(uuid, text, jsonb, uuid) is
+ 'Action Center (AC-010): a task waiting for review (action_task_reviews) onto its action''s task list, after its last task, with the exact page, the change, Done when and how it is checked filled, as the reviewer''s (source reviewed); the review row goes and the trail says a task was added. Admins and managers of the brand''s organization only, on an action neither deleted nor closed; p_user_id is the person the service role approves for (00375), a signed-in caller is always auth.uid(). Null when the row is gone or another organization''s.';
+
+notify pgrst, 'reload schema';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00376_competitor_page_timeline.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/src/app/api/mcp/task-reviews/[id]/approve/route.ts b/web/src/app/api/mcp/task-reviews/[id]/approve/route.ts
new file mode 100644
index 000000000..6d9dcb795
--- /dev/null
+++ b/web/src/app/api/mcp/task-reviews/[id]/approve/route.ts
@@ -0,0 +1,47 @@
+import { NextResponse } from 'next/server';
+import { z } from 'zod';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { failedCallResponse } from '@/lib/mcp/subscription-gate';
+import {
+ TASK_REVIEW_ERROR_STATUS,
+ approveTaskReviewFor,
+ taskReviewEditShape,
+} from '@/lib/mcp/task-reviews';
+
+/**
+ * POST /api/mcp/task-reviews/[id]/approve — REST mirror of the
+ * `approve_task_review` MCP tool, its fields in the JSON body.
+ */
+export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+
+ const { id } = await params;
+ // No body approves the task as written; a body it can't read approves nothing.
+ const text = await req.text();
+ let json: unknown = {};
+ if (text.trim()) {
+ try {
+ json = JSON.parse(text);
+ } catch {
+ return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
+ }
+ }
+ const body = z.object(taskReviewEditShape).safeParse(json);
+ if (!body.success) {
+ return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
+ }
+
+ try {
+ const result = await approveTaskReviewFor(auth, id, body.data);
+ if ('error' in result) {
+ return NextResponse.json(
+ { error: result.message, code: result.error },
+ { status: TASK_REVIEW_ERROR_STATUS[result.error] },
+ );
+ }
+ return NextResponse.json(result, { status: 201 });
+ } catch (err) {
+ return failedCallResponse(err);
+ }
+}
diff --git a/web/src/app/api/mcp/task-reviews/[id]/dismiss/route.ts b/web/src/app/api/mcp/task-reviews/[id]/dismiss/route.ts
new file mode 100644
index 000000000..58373bdc7
--- /dev/null
+++ b/web/src/app/api/mcp/task-reviews/[id]/dismiss/route.ts
@@ -0,0 +1,24 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { failedCallResponse } from '@/lib/mcp/subscription-gate';
+import { TASK_REVIEW_ERROR_STATUS, dismissTaskReviewFor } from '@/lib/mcp/task-reviews';
+
+/** POST /api/mcp/task-reviews/[id]/dismiss — REST mirror of the `dismiss_task_review` MCP tool. */
+export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+
+ const { id } = await params;
+ try {
+ const result = await dismissTaskReviewFor(auth, id);
+ if ('error' in result) {
+ return NextResponse.json(
+ { error: result.message, code: result.error },
+ { status: TASK_REVIEW_ERROR_STATUS[result.error] },
+ );
+ }
+ return NextResponse.json(result);
+ } catch (err) {
+ return failedCallResponse(err);
+ }
+}
diff --git a/web/src/app/api/mcp/task-reviews/route.test.ts b/web/src/app/api/mcp/task-reviews/route.test.ts
new file mode 100644
index 000000000..271044819
--- /dev/null
+++ b/web/src/app/api/mcp/task-reviews/route.test.ts
@@ -0,0 +1,143 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The REST mirrors of the task review tools: GET /api/mcp/task-reviews,
+ * POST /api/mcp/task-reviews/[id]/approve and /dismiss, with a status for
+ * each refusal.
+ */
+
+const reviews = vi.hoisted(() => ({
+ listTaskReviewsFor: vi.fn(),
+ approveTaskReviewFor: vi.fn(),
+ dismissTaskReviewFor: vi.fn(),
+}));
+vi.mock('@/lib/mcp-auth', () => ({
+ authenticateMcpRequest: vi.fn(async () => ({
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ role: 'manager',
+ apiKeyId: 'key-1',
+ })),
+}));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+vi.mock('@/lib/mcp/task-reviews', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/mcp/task-reviews')>()),
+ ...reviews,
+}));
+
+const list = await import('./route');
+const { RoleRequiredError, MANAGER_ROLES } = await import('@/lib/mcp/role-gate');
+const approve = await import('./[id]/approve/route');
+const dismiss = await import('./[id]/dismiss/route');
+
+const params = { params: Promise.resolve({ id: 'review-1' }) };
+const post = (path: string, body?: unknown) =>
+ new Request(`http://localhost/api/mcp/task-reviews/review-1/${path}`, {
+ method: 'POST',
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('GET /api/mcp/task-reviews', () => {
+ it("answers the brand's reviews, 403 for a member who can't review, 404 for another brand", async () => {
+ const get = () =>
+ list.GET(new Request('http://localhost/api/mcp/task-reviews?brand_id=brand-1'));
+ reviews.listTaskReviewsFor.mockResolvedValue([{ id: 'review-1' }]);
+ expect(await (await get()).json()).toEqual({ reviews: [{ id: 'review-1' }] });
+ reviews.listTaskReviewsFor.mockRejectedValue(new RoleRequiredError(MANAGER_ROLES, 'analyst'));
+ expect((await get()).status).toBe(403);
+ reviews.listTaskReviewsFor.mockReset();
+ reviews.listTaskReviewsFor.mockResolvedValue(null);
+ expect((await get()).status).toBe(404);
+ });
+
+ it('asks for a brand', async () => {
+ const res = await list.GET(new Request('http://localhost/api/mcp/task-reviews'));
+ expect(res.status).toBe(400);
+ });
+});
+
+describe('POST /api/mcp/task-reviews/[id]/approve', () => {
+ it('approves with the fields in the body', async () => {
+ reviews.approveTaskReviewFor.mockResolvedValue({ task_id: 'task-9' });
+ const res = await approve.POST(
+ post('approve', { url: '/pricing', change: { after: 'FAQ' }, check: 'auto' }),
+ params,
+ );
+ expect(res.status).toBe(201);
+ expect(reviews.approveTaskReviewFor).toHaveBeenCalledWith(expect.anything(), 'review-1', {
+ url: '/pricing',
+ change: { after: 'FAQ' },
+ check: 'auto',
+ });
+ });
+
+ it('refuses a body it cannot read, before approving', async () => {
+ const res = await approve.POST(post('approve', { check: 'sometimes' }), params);
+ expect(res.status).toBe(400);
+ expect(reviews.approveTaskReviewFor).not.toHaveBeenCalled();
+ });
+
+ it('approves as written without a body, and refuses JSON it cannot read', async () => {
+ reviews.approveTaskReviewFor.mockResolvedValue({ task_id: 'task-9' });
+ expect((await approve.POST(post('approve'), params)).status).toBe(201);
+ expect(reviews.approveTaskReviewFor).toHaveBeenCalledWith(expect.anything(), 'review-1', {});
+ reviews.approveTaskReviewFor.mockClear();
+ const broken = new Request('http://localhost/api/mcp/task-reviews/review-1/approve', {
+ method: 'POST',
+ body: '{"url": "/pricing"',
+ });
+ const res = await approve.POST(broken, params);
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: 'Invalid JSON body' });
+ expect(reviews.approveTaskReviewFor).not.toHaveBeenCalled();
+ });
+
+ it('answers each refusal with its status', async () => {
+ for (const [error, status] of [
+ ['forbidden', 403],
+ ['missing', 404],
+ ['closed', 409],
+ ['incomplete', 422],
+ ] as const) {
+ reviews.approveTaskReviewFor.mockResolvedValue({ error, message: error });
+ const res = await approve.POST(post('approve', {}), params);
+ expect(res.status, error).toBe(status);
+ expect(await res.json()).toEqual({ error, code: error });
+ }
+ });
+});
+
+describe('a key whose user may not review', () => {
+ it('answers 403 role_required on every route', async () => {
+ const refusal = new RoleRequiredError(MANAGER_ROLES, 'analyst');
+ reviews.listTaskReviewsFor.mockRejectedValue(refusal);
+ reviews.approveTaskReviewFor.mockRejectedValue(refusal);
+ reviews.dismissTaskReviewFor.mockRejectedValue(refusal);
+ for (const res of [
+ await list.GET(new Request('http://localhost/api/mcp/task-reviews?brand_id=brand-1')),
+ await approve.POST(post('approve', {}), params),
+ await dismiss.POST(post('dismiss'), params),
+ ]) {
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ error: 'forbidden', code: 'role_required' });
+ }
+ });
+});
+
+describe('POST /api/mcp/task-reviews/[id]/dismiss', () => {
+ it('dismisses, or says why not', async () => {
+ reviews.dismissTaskReviewFor.mockResolvedValue({ id: 'review-1', dismissed: true });
+ expect(await (await dismiss.POST(post('dismiss'), params)).json()).toEqual({
+ id: 'review-1',
+ dismissed: true,
+ });
+ reviews.dismissTaskReviewFor.mockResolvedValue({ error: 'forbidden', message: 'No' });
+ expect((await dismiss.POST(post('dismiss'), params)).status).toBe(403);
+ });
+});
diff --git a/web/src/app/api/mcp/task-reviews/route.ts b/web/src/app/api/mcp/task-reviews/route.ts
new file mode 100644
index 000000000..b86f2463a
--- /dev/null
+++ b/web/src/app/api/mcp/task-reviews/route.ts
@@ -0,0 +1,34 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { failedCallResponse } from '@/lib/mcp/subscription-gate';
+import { listTaskReviewsFor } from '@/lib/mcp/task-reviews';
+
+/**
+ * GET /api/mcp/task-reviews — REST mirror of the `list_task_reviews` MCP tool.
+ * 403 role_required unless the key's user is an admin or a manager.
+ */
+export async function GET(req: Request) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+
+ const url = new URL(req.url);
+ const brandId = url.searchParams.get('brand_id');
+ if (!brandId) {
+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });
+ }
+ const limitRaw = url.searchParams.get('limit');
+ const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;
+
+ try {
+ const reviews = await listTaskReviewsFor(auth, {
+ brandId,
+ limit: Number.isFinite(limit) ? limit : undefined,
+ });
+ if (reviews === null) {
+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
+ }
+ return NextResponse.json({ reviews });
+ } catch (err) {
+ return failedCallResponse(err);
+ }
+}
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 3b75fd5fe..3a713e046 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -3077,7 +3077,7 @@ const templateDoneWhen = (taskKey: string) =>
doneWhenT.has(taskKey as never) ? doneWhenT(taskKey as never) : null;
/** A task's details in the snake_case the rest of the MCP output uses. */
-function mcpTaskDetails(raw: unknown, taskKey: string | null = null) {
+export function mcpTaskDetails(raw: unknown, taskKey: string | null = null) {
const d = withTemplateCheck(
withTemplateDoneWhen(parseTaskDetails(raw), taskKey, templateDoneWhen),
taskKey,
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index e00867bd4..d9e67753e 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -90,6 +90,12 @@ import {
getShoppingShelfFor,
} from './product-visibility';
import { getPromptLocationsFor } from './prompt-locations';
+import {
+ approveTaskReviewFor,
+ dismissTaskReviewFor,
+ listTaskReviewsFor,
+ taskReviewEditShape,
+} from './task-reviews';
/**
* Build a fresh MCP server bound to a single authenticated request.
@@ -2329,5 +2335,82 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
},
);
+ // ─── Tasks waiting for review (AC-010, B4): the Needs review tab ───
+
+ /** A review tool's refusal, as text the assistant can act on. */
+ const refused = (message: string) => ({
+ content: [{ type: 'text' as const, text: message }],
+ isError: true,
+ });
+
+ server.registerTool(
+ 'list_task_reviews',
+ {
+ title: 'Tasks waiting for review',
+ description:
+ "List the brand's tasks waiting for review, as the Action Center's Needs review tab shows them, oldest first: tasks an AI writer gave without the exact page (url), the change (change.after), Done when (done_when) or how it is checked (check: auto, rerun or manual). Each has its action (action_id, action_no), its title, `missing` (the fields to fill), `details` as written (get_action's task shape) and who wrote it (`source`). They aren't tasks yet: approve_task_review puts one on its action's list, dismiss_task_review drops it. Only for an admin or a manager of the brand's organization.",
+ inputSchema: {
+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(200)
+ .optional()
+ .describe('Row cap (default 50, max 200).'),
+ },
+ annotations: { readOnlyHint: true, openWorldHint: false },
+ },
+ async (args) => {
+ const reviews = await listTaskReviewsFor(auth, { brandId: args.brand_id, limit: args.limit });
+ return reviews ? json(reviews) : notFound('Brand');
+ },
+ );
+
+ server.registerTool(
+ 'approve_task_review',
+ {
+ title: 'Approve a task waiting for review',
+ description:
+ "Approve a task waiting for review onto its action's task list, as the Needs review tab's Approve does: the fields given here replace what was written, the rest stays, and it needs all four — url (the exact page), change.after (the change to make), done_when and check — filled once merged. Title optional (the written one stays). The task goes after the action's last task, as the key's user's (the trail says they added it). Refused on an action that is closed or deleted. Only for an admin or a manager of the brand's organization. It is a write — only on the user's explicit decision for this review, never as part of exploring.",
+ inputSchema: {
+ review_id: relaxedUuid.describe('Task review UUID, from list_task_reviews.'),
+ ...taskReviewEditShape,
+ },
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: false,
+ },
+ },
+ async ({ review_id, ...edit }) => {
+ const result = await approveTaskReviewFor(auth, review_id, edit);
+ return 'error' in result ? refused(result.message) : json(result);
+ },
+ );
+
+ server.registerTool(
+ 'dismiss_task_review',
+ {
+ title: 'Dismiss a task waiting for review',
+ description:
+ "Dismiss a task waiting for review, as the Needs review tab's Dismiss does: it never reaches its action, and can't be brought back. Only for an admin or a manager of the brand's organization. It is a write — only on the user's explicit decision for this review.",
+ inputSchema: {
+ review_id: relaxedUuid.describe('Task review UUID, from list_task_reviews.'),
+ },
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: true,
+ idempotentHint: true,
+ openWorldHint: false,
+ },
+ },
+ async (args) => {
+ const result = await dismissTaskReviewFor(auth, args.review_id);
+ return 'error' in result ? refused(result.message) : json(result);
+ },
+ );
+
return server;
}
diff --git a/web/src/lib/mcp/subscription-gate.test.ts b/web/src/lib/mcp/subscription-gate.test.ts
index cac1e3e05..3239a5342 100644
--- a/web/src/lib/mcp/subscription-gate.test.ts
+++ b/web/src/lib/mcp/subscription-gate.test.ts
@@ -79,14 +79,16 @@ describe('the MCP tools on a read-only workspace', () => {
const client = await connect();
const { tools } = await client.listTools();
const names = tools.map((tool) => tool.name);
- expect(names.filter(isReadTool)).toHaveLength(47);
+ expect(names.filter(isReadTool)).toHaveLength(48);
expect(names.filter((name) => !isReadTool(name)).sort()).toEqual([
'accept_prompt_suggestion',
'accept_topic_suggestion',
'add_content_source',
+ 'approve_task_review',
'create_content_draft',
'create_improve_action',
'dismiss_prompt_suggestion',
+ 'dismiss_task_review',
'dismiss_topic_suggestion',
'generate_content_brief',
'mark_content_draft_published',
@@ -114,7 +116,7 @@ describe('the MCP tools on a read-only workspace', () => {
}
)._registeredTools;
const gated = Object.keys(registered).filter((name) => !isReadTool(name));
- expect(gated).toHaveLength(15);
+ expect(gated).toHaveLength(17);
for (const name of gated) {
const result = (await registered[name].handler({}, {})) as {
isError?: boolean;
diff --git a/web/src/lib/mcp/task-reviews.test.ts b/web/src/lib/mcp/task-reviews.test.ts
new file mode 100644
index 000000000..465d259f4
--- /dev/null
+++ b/web/src/lib/mcp/task-reviews.test.ts
@@ -0,0 +1,319 @@
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+
+/**
+ * Tasks waiting for review over MCP (AC-010, B4): the Needs review tab's
+ * list, Approve and Dismiss, for an admin or a manager of the brand's
+ * organization only. Approve fills the fields given over what was written,
+ * needs all four, and goes through approve_action_task_review as the key's
+ * user (00375).
+ */
+
+let brandFound = true;
+let reviewRows: Record<string, unknown>[] = [];
+/** The review as ownedReview reads it; null for none of the organization's. */
+let owned: Record<string, unknown> | null = null;
+let rpcResult: { data: unknown; error: { code: string; message: string } | null } = {
+ data: 'task-9',
+ error: null,
+};
+const rpcCalls: [string, Record<string, unknown>][] = [];
+const deleted: string[] = [];
+/** Whether the review is still there when dismiss deletes it. */
+let stillThere = true;
+const filters: [string, string, unknown][] = [];
+
+function builder(table: string) {
+ const chain = {
+ select: () => chain,
+ eq: (column: string, value: unknown) => {
+ filters.push([table, column, value]);
+ return chain;
+ },
+ is: () => chain,
+ not: () => chain,
+ order: () => chain,
+ limit: async () => ({ data: reviewRows, error: null }),
+ maybeSingle: async () => ({
+ data: table === 'brands' ? brandFound && { id: 'brand-1' } : owned,
+ error: null,
+ }),
+ delete: () => ({
+ eq: (_column: string, id: string) => ({
+ select: async () => {
+ if (stillThere) deleted.push(id);
+ return { data: stillThere ? [{ id }] : [], error: null };
+ },
+ }),
+ }),
+ };
+ return chain;
+}
+
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: (table: string) => builder(table),
+ rpc: async (fn: string, args: Record<string, unknown>) => {
+ rpcCalls.push([fn, args]);
+ return rpcResult;
+ },
+ },
+}));
+
+const { listTaskReviewsFor, approveTaskReviewFor, dismissTaskReviewFor } =
+ await import('./task-reviews');
+const { createMcpServer } = await import('./server');
+const { RoleRequiredError } = await import('./role-gate');
+
+const manager: McpAuthContext = {
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ role: 'manager',
+ apiKeyId: 'key-1',
+};
+let auth = manager;
+
+const WRITTEN = {
+ where: 'Pricing page',
+ why: 'Lost two citations on ChatGPT',
+ url: null,
+ change: null,
+ how: ['Open the page', 'Add the FAQ'],
+ doneWhen: 'FAQ block present',
+ check: null,
+ evidence: ['signal-1'],
+};
+
+beforeEach(() => {
+ auth = manager;
+ brandFound = true;
+ reviewRows = [];
+ owned = { id: 'review-1', action_id: 'action-1', title: 'Add an FAQ', details: WRITTEN };
+ rpcResult = { data: 'task-9', error: null };
+ rpcCalls.length = 0;
+ deleted.length = 0;
+ stillThere = true;
+ filters.length = 0;
+});
+
+describe('listTaskReviewsFor', () => {
+ it("lists the brand's reviews with what they miss, in the MCP's names", async () => {
+ reviewRows = [
+ {
+ id: 'review-1',
+ action_id: 'action-1',
+ title: 'Add an FAQ',
+ details: WRITTEN,
+ missing: ['url', 'change', 'doneWhen', 'check', 'other'],
+ source: 'ai',
+ created_at: '2026-10-28T09:00:00Z',
+ actions: { action_no: 52 },
+ },
+ ];
+ const reviews = await listTaskReviewsFor(auth, { brandId: 'brand-1' });
+ expect(reviews).toEqual([
+ expect.objectContaining({
+ id: 'review-1',
+ action_id: 'action-1',
+ action_no: 52,
+ title: 'Add an FAQ',
+ missing: ['url', 'change', 'done_when', 'check'],
+ source: 'ai',
+ details: expect.objectContaining({ where: 'Pricing page', done_when: 'FAQ block present' }),
+ }),
+ ]);
+ expect(filters).toContainEqual(['action_task_reviews', 'actions.brand_id', 'brand-1']);
+ });
+
+ it("answers null for another organization's brand", async () => {
+ brandFound = false;
+ expect(await listTaskReviewsFor(auth, { brandId: 'brand-2' })).toBeNull();
+ });
+
+ it('refuses anyone but an admin or a manager', async () => {
+ for (const role of ['analyst', 'agency_partner', null] as const) {
+ auth = { ...manager, role };
+ await expect(listTaskReviewsFor(auth, { brandId: 'brand-1' })).rejects.toThrow(
+ RoleRequiredError,
+ );
+ }
+ auth = { ...manager, role: 'admin' };
+ expect(await listTaskReviewsFor(auth, { brandId: 'brand-1' })).toEqual([]);
+ });
+});
+
+describe('approveTaskReviewFor', () => {
+ it('fills the fields given over what was written, and approves as the key’s user', async () => {
+ const result = await approveTaskReviewFor(auth, 'review-1', {
+ url: 'https://acme.example/pricing',
+ change: { after: '<h2>FAQ</h2>' },
+ check: 'auto',
+ });
+ expect(result).toEqual({ task_id: 'task-9', action_id: 'action-1', title: 'Add an FAQ' });
+ expect(rpcCalls).toEqual([
+ [
+ 'approve_action_task_review',
+ {
+ p_review_id: 'review-1',
+ p_title: 'Add an FAQ',
+ p_details: expect.objectContaining({
+ url: 'https://acme.example/pricing',
+ change: { before: null, after: '<h2>FAQ</h2>' },
+ doneWhen: 'FAQ block present',
+ check: 'auto',
+ where: 'Pricing page',
+ how: ['Open the page', 'Add the FAQ'],
+ // What the writer stored beside them stays.
+ evidence: ['signal-1'],
+ }),
+ p_user_id: 'user-1',
+ },
+ ],
+ ]);
+ });
+
+ it('says what is still missing, without calling the database', async () => {
+ const result = await approveTaskReviewFor(auth, 'review-1', { url: '/pricing' });
+ expect(result).toEqual({
+ error: 'incomplete',
+ message: 'The task still misses: change, check',
+ });
+ expect(rpcCalls).toEqual([]);
+ });
+
+ const complete = {
+ url: '/pricing',
+ change: { after: 'FAQ' },
+ check: 'manual' as const,
+ };
+
+ it('refuses anyone but an admin or a manager, before reading the review', async () => {
+ auth = { ...manager, role: 'analyst' };
+ await expect(approveTaskReviewFor(auth, 'review-1', complete)).rejects.toThrow(
+ RoleRequiredError,
+ );
+ expect(filters).toEqual([]);
+ expect(rpcCalls).toEqual([]);
+ });
+
+ it('answers forbidden when the database refuses the approval', async () => {
+ rpcResult = { data: null, error: { code: '42501', message: 'not allowed' } };
+ expect(await approveTaskReviewFor(auth, 'review-1', complete)).toMatchObject({
+ error: 'forbidden',
+ });
+ });
+
+ it("reads the review within the key's organization", async () => {
+ await approveTaskReviewFor(auth, 'review-1', complete);
+ expect(filters).toContainEqual([
+ 'action_task_reviews',
+ 'actions.brands.organization_id',
+ 'org-1',
+ ]);
+ });
+
+ it("reads another organization's review, or one gone, as missing", async () => {
+ owned = null;
+ expect(await approveTaskReviewFor(auth, 'review-1', complete)).toMatchObject({
+ error: 'missing',
+ });
+ owned = { id: 'review-1', action_id: 'action-1', title: 'T', details: WRITTEN };
+ rpcResult = { data: null, error: null };
+ expect(await approveTaskReviewFor(auth, 'review-1', complete)).toMatchObject({
+ error: 'missing',
+ });
+ });
+
+ it("says so when the review's action is closed", async () => {
+ rpcResult = { data: null, error: { code: '55000', message: 'action closed' } };
+ expect(await approveTaskReviewFor(auth, 'review-1', complete)).toMatchObject({
+ error: 'closed',
+ });
+ });
+
+ it('passes on any other database failure', async () => {
+ rpcResult = { data: null, error: { code: '57014', message: 'statement timeout' } };
+ await expect(approveTaskReviewFor(auth, 'review-1', complete)).rejects.toThrow(
+ 'statement timeout',
+ );
+ });
+});
+
+describe('dismissTaskReviewFor', () => {
+ it("drops the organization's review", async () => {
+ expect(await dismissTaskReviewFor(auth, 'review-1')).toEqual({
+ id: 'review-1',
+ dismissed: true,
+ });
+ expect(deleted).toEqual(['review-1']);
+ expect(filters).toContainEqual([
+ 'action_task_reviews',
+ 'actions.brands.organization_id',
+ 'org-1',
+ ]);
+ });
+
+ it('says missing when the review went meanwhile', async () => {
+ stillThere = false;
+ expect(await dismissTaskReviewFor(auth, 'review-1')).toMatchObject({ error: 'missing' });
+ });
+
+ it("refuses an analyst, and leaves another organization's review alone", async () => {
+ auth = { ...manager, role: 'analyst' };
+ await expect(dismissTaskReviewFor(auth, 'review-1')).rejects.toThrow(RoleRequiredError);
+ expect(deleted).toEqual([]);
+ auth = { ...manager, role: 'admin' };
+ owned = null;
+ expect(await dismissTaskReviewFor(auth, 'review-1')).toMatchObject({ error: 'missing' });
+ expect(deleted).toEqual([]);
+ });
+});
+
+describe('the task review tools', () => {
+ it('list with a title, the list as a read and the others as writes', async () => {
+ const server = createMcpServer(auth);
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ const client = new Client({ name: 'test', version: '1.0.0' });
+ await client.connect(clientTransport);
+ const { tools } = await client.listTools();
+ const tool = (name: string) => tools.find((t) => t.name === name);
+ expect(tool('list_task_reviews')?.annotations).toMatchObject({ readOnlyHint: true });
+ expect(tool('approve_task_review')?.annotations).toMatchObject({
+ readOnlyHint: false,
+ destructiveHint: false,
+ });
+ expect(tool('dismiss_task_review')?.annotations).toMatchObject({
+ readOnlyHint: false,
+ destructiveHint: true,
+ });
+ for (const name of ['list_task_reviews', 'approve_task_review', 'dismiss_task_review']) {
+ expect(tool(name)?.title, name).toBeTruthy();
+ }
+ });
+
+ it("answer an analyst's call with the role refusal, as a tool error", async () => {
+ const server = createMcpServer({ ...manager, role: 'analyst' });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ const client = new Client({ name: 'test', version: '1.0.0' });
+ await client.connect(clientTransport);
+ for (const [name, args] of [
+ ['list_task_reviews', { brand_id: '11111111-1111-4111-8111-111111111111' }],
+ ['approve_task_review', { review_id: '11111111-1111-4111-8111-111111111111' }],
+ ['dismiss_task_review', { review_id: '11111111-1111-4111-8111-111111111111' }],
+ ] as const) {
+ const result = (await client.callTool({ name, arguments: args })) as {
+ isError?: boolean;
+ content: { text: string }[];
+ };
+ expect(result.isError, name).toBe(true);
+ expect(result.content[0].text, name).toContain('Only an admin or a manager can do this');
+ }
+ expect(rpcCalls).toEqual([]);
+ expect(deleted).toEqual([]);
+ });
+});
diff --git a/web/src/lib/mcp/task-reviews.ts b/web/src/lib/mcp/task-reviews.ts
new file mode 100644
index 000000000..06e1e5eb3
--- /dev/null
+++ b/web/src/lib/mcp/task-reviews.ts
@@ -0,0 +1,277 @@
+import { z } from 'zod';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+import {
+ TASK_CHECKS,
+ TASK_DETAIL_LIMITS,
+ cleanTaskDetailsEdit,
+ parseTaskDetails,
+ type TaskDetailsEdit,
+} from '@/lib/action-center/task-details';
+import { brandInOrg, mcpTaskDetails } from './data';
+import { requireManager } from './role-gate';
+
+/**
+ * Tasks waiting for review (AC-010, 00293) for the MCP tools
+ * list_task_reviews, approve_task_review and dismiss_task_review and their
+ * REST mirrors: tasks an agent wrote without the exact page, the change, Done
+ * when or how it is checked. An admin or a manager fills what they miss and
+ * approves them onto their action's list, or dismisses them, as on the
+ * Action Center's Needs review tab. The key's user must be one
+ * (requireManager): everyone else reads and changes none, as the table's RLS
+ * has it.
+ *
+ * TODO(demo-brand-mcp): approve_task_review and dismiss_task_review find
+ * their brand through action_task_reviews → actions.brand_id. When
+ * feature/demo-brand-mcp merges, add them to WRITE_TOOL_BRANDS
+ * (lib/mcp/demo-gate.ts) and call assertNotDemoBrand in
+ * approveTaskReviewFor and dismissTaskReviewFor, so the REST mirrors refuse
+ * a demo brand too: they write as the service role, which the demo trigger
+ * (00381) lets through.
+ */
+
+/** A field a task waiting for review was written without, as the MCP names it. */
+export type McpReviewField = 'url' | 'change' | 'done_when' | 'check';
+
+const FIELD_NAMES: Record<string, McpReviewField> = {
+ url: 'url',
+ change: 'change',
+ doneWhen: 'done_when',
+ check: 'check',
+};
+
+export interface McpTaskReview {
+ id: string;
+ action_id: string;
+ action_no: number | null;
+ title: string;
+ /** What it was written without: fill these to approve it. */
+ missing: McpReviewField[];
+ /** The task as it was written, in get_action's task shape. */
+ details: ReturnType<typeof mcpTaskDetails>;
+ /** Who wrote it: the AI task writer or an agent. */
+ source: string;
+ created_at: string;
+}
+
+export type TaskReviewError = {
+ error: 'forbidden' | 'missing' | 'closed' | 'incomplete';
+ message: string;
+};
+
+/** The REST status for each refusal. */
+export const TASK_REVIEW_ERROR_STATUS: Record<TaskReviewError['error'], number> = {
+ forbidden: 403,
+ missing: 404,
+ closed: 409,
+ incomplete: 422,
+};
+
+const FORBIDDEN: TaskReviewError = {
+ error: 'forbidden',
+ message: "Only an admin or a manager of the brand's organization reviews tasks",
+};
+const MISSING: TaskReviewError = {
+ error: 'missing',
+ message: 'Task review not found: approved or dismissed already, or not in this organization',
+};
+
+/** A review of the key's organization, with what is stored for it; null when there is none. */
+async function ownedReview(auth: McpAuthContext, reviewId: string) {
+ if (!auth.organizationId) return null;
+ const { data, error } = await supabaseAdmin
+ .from('action_task_reviews')
+ .select('id, action_id, title, details, actions!inner(brands!inner(organization_id))')
+ .eq('id', reviewId)
+ .eq('actions.brands.organization_id', auth.organizationId as string)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ return data as { id: string; action_id: string; title: string; details: unknown } | null;
+}
+
+const LIST_DEFAULT = 50;
+const LIST_MAX = 200;
+
+/**
+ * The brand's tasks waiting for review, the oldest first; none of an action
+ * that is deleted or closed, which can't take them. Null for a brand outside
+ * the key's organization. Throws RoleRequiredError for anyone but an admin
+ * or a manager.
+ */
+export async function listTaskReviewsFor(
+ auth: McpAuthContext,
+ params: { brandId: string; limit?: number },
+): Promise<McpTaskReview[] | null> {
+ if (!(await brandInOrg(auth, params.brandId))) return null;
+ requireManager(auth);
+
+ const limit = Math.min(Math.max(params.limit ?? LIST_DEFAULT, 1), LIST_MAX);
+ const { data, error } = await supabaseAdmin
+ .from('action_task_reviews')
+ .select(
+ 'id, action_id, title, details, missing, source, created_at, actions!inner(action_no, brand_id, status, deleted_at)',
+ )
+ .eq('actions.brand_id', params.brandId)
+ .is('actions.deleted_at', null)
+ .not('actions.status', 'in', '(completed,dismissed)')
+ .order('created_at', { ascending: true })
+ .limit(limit);
+ if (error) throw new Error(error.message);
+
+ return (data ?? []).map((row) => {
+ const action = (Array.isArray(row.actions) ? row.actions[0] : row.actions) as {
+ action_no: number | null;
+ } | null;
+ return {
+ id: row.id as string,
+ action_id: row.action_id as string,
+ action_no: action?.action_no ?? null,
+ title: row.title as string,
+ missing: ((row.missing ?? []) as string[])
+ .map((field) => FIELD_NAMES[field])
+ .filter((field): field is McpReviewField => field !== undefined),
+ details: mcpTaskDetails(row.details),
+ source: row.source as string,
+ created_at: row.created_at as string,
+ };
+ });
+}
+
+/**
+ * What approve_task_review takes, shared by the MCP tool and its REST mirror:
+ * the fields to fill or change; the rest stays as written.
+ */
+export const taskReviewEditShape = {
+ title: z.string().trim().min(1).max(200).optional().describe('The task title.'),
+ url: z
+ .string()
+ .max(TASK_DETAIL_LIMITS.url)
+ .optional()
+ .describe('The exact page the change is made on: a path or a full URL.'),
+ change: z
+ .object({
+ before: z.string().max(TASK_DETAIL_LIMITS.change).optional(),
+ after: z.string().min(1).max(TASK_DETAIL_LIMITS.change),
+ })
+ .optional()
+ .describe('The change to make there: the text before (none when it adds text) and after.'),
+ done_when: z
+ .string()
+ .max(TASK_DETAIL_LIMITS.doneWhen)
+ .optional()
+ .describe('The measurable check that closes it.'),
+ check: z
+ .enum(TASK_CHECKS)
+ .optional()
+ .describe(
+ 'How it is checked: auto (the page fetched again), rerun (the prompts run again) or manual (a person confirms).',
+ ),
+ where: z.string().max(TASK_DETAIL_LIMITS.where).optional(),
+ why: z.string().max(TASK_DETAIL_LIMITS.why).optional(),
+ how: z
+ .array(z.string().max(TASK_DETAIL_LIMITS.step))
+ .max(TASK_DETAIL_LIMITS.steps)
+ .optional()
+ .describe('The steps, in order.'),
+};
+
+export type TaskReviewEdit = z.infer<z.ZodObject<typeof taskReviewEditShape>>;
+
+/** The four fields a task needs to be approved, as the database checks them (00293). */
+function stillMissing(details: Record<string, unknown>): McpReviewField[] {
+ const filled = (value: unknown) => typeof value === 'string' && value.trim() !== '';
+ const change = (details.change ?? null) as { after?: unknown } | null;
+ return [
+ ...(filled(details.url) ? [] : (['url'] as const)),
+ ...(filled(change?.after) ? [] : (['change'] as const)),
+ ...(filled(details.doneWhen) ? [] : (['done_when'] as const)),
+ ...(details.check === 'auto' || details.check === 'rerun' || details.check === 'manual'
+ ? []
+ : (['check'] as const)),
+ ];
+}
+
+/**
+ * A reviewed task onto its action's list, as the Needs review tab's Approve
+ * does (approve_action_task_review, 00293 and 00375): the fields given
+ * replace the written ones, the rest stays, and the four it needs must be
+ * filled. The trail says the key's user added it. Throws RoleRequiredError
+ * for anyone but an admin or a manager, before reading the review.
+ */
+export async function approveTaskReviewFor(
+ auth: McpAuthContext,
+ reviewId: string,
+ input: TaskReviewEdit,
+): Promise<{ task_id: string; action_id: string; title: string } | TaskReviewError> {
+ requireManager(auth);
+ const review = await ownedReview(auth, reviewId);
+ if (!review) return MISSING;
+
+ const stored =
+ review.details && typeof review.details === 'object' && !Array.isArray(review.details)
+ ? (review.details as Record<string, unknown>)
+ : {};
+ const current = parseTaskDetails(stored);
+ const edit: TaskDetailsEdit = {
+ url: input.url ?? current?.url ?? '',
+ where: input.where ?? current?.where ?? '',
+ why: input.why ?? current?.why ?? '',
+ before: input.change ? (input.change.before ?? '') : (current?.change?.before ?? ''),
+ after: input.change ? input.change.after : (current?.change?.after ?? ''),
+ how: input.how ?? current?.how ?? [],
+ doneWhen: input.done_when ?? current?.doneWhen ?? '',
+ check: input.check ?? current?.check ?? null,
+ type: current?.type ?? null,
+ effort: current?.effort ?? '',
+ role: current?.role ?? '',
+ };
+ // What the writer stored beside them (its evidence refs) stays, as on the tab.
+ const details = { ...stored, ...cleanTaskDetailsEdit(edit) };
+ const missing = stillMissing(details);
+ if (missing.length) {
+ return { error: 'incomplete', message: `The task still misses: ${missing.join(', ')}` };
+ }
+ const title = (input.title ?? review.title).trim().slice(0, 200);
+
+ const { data, error } = await supabaseAdmin.rpc('approve_action_task_review', {
+ p_review_id: reviewId,
+ p_title: title,
+ p_details: details,
+ p_user_id: auth.userId,
+ });
+ if (error) {
+ if (error.code === '42501') return FORBIDDEN;
+ if (error.code === '55000') {
+ return { error: 'closed', message: 'Its action is closed or deleted: it takes no tasks' };
+ }
+ if (error.code === '22023') {
+ return { error: 'incomplete', message: 'The task needs a title and its four fields' };
+ }
+ throw new Error(error.message);
+ }
+ if (!data) return MISSING;
+ return { task_id: data as string, action_id: review.action_id, title };
+}
+
+/**
+ * A task waiting for review dropped, as the tab's Dismiss does: it never
+ * reaches the action. Throws RoleRequiredError for anyone but an admin or a
+ * manager.
+ */
+export async function dismissTaskReviewFor(
+ auth: McpAuthContext,
+ reviewId: string,
+): Promise<{ id: string; dismissed: true } | TaskReviewError> {
+ requireManager(auth);
+ const review = await ownedReview(auth, reviewId);
+ if (!review) return MISSING;
+ const { data, error } = await supabaseAdmin
+ .from('action_task_reviews')
+ .delete()
+ .eq('id', reviewId)
+ .select('id');
+ if (error) throw new Error(error.message);
+ // Approved or dismissed meanwhile: nothing was dropped.
+ if (!data?.length) return MISSING;
+ return { id: reviewId, dismissed: true };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 603d19ed4..16d3275cb 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -5215,7 +5215,12 @@ export type Database = {
}
apply_prompt_locations: { Args: { p_updates: Json }; Returns: number }
approve_action_task_review: {
- Args: { p_details: Json; p_review_id: string; p_title: string }
+ Args: {
+ p_details: Json
+ p_review_id: string
+ p_title: string
+ p_user_id?: string
+ }
Returns: string
}
brand_ai_conversions: {