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(content): archive, delete and set a status from the Library's rows (#1328)
Cihan56a4d250d2e1
diff --git a/supabase/migrations/00233_content_drafts_archive.sql b/supabase/migrations/00233_content_drafts_archive.sqlnew file mode 100644index 000000000..4422d28af--- /dev/null+++ b/supabase/migrations/00233_content_drafts_archive.sql@@ -0,0 +1,103 @@+-- ============================================================================+-- 00233: archive and delete Library drafts (Content Editor, CE-002)+-- ============================================================================+-- The Library's rows get a menu (the user's request): a status to pick, Send+-- to Archive, and Delete. Admins and managers archive and delete, as they+-- hide the Plan's rows (00229); every member can still change a status.+--+-- * content_drafts.archived_at / archived_by: an archived draft keeps its+-- status, so Restore puts it back where it was. Archive is not a status:+-- the Agent API, MCP and the editor read the four statuses unchanged.+-- * guard_content_draft_archive: only an admin or a manager of the brand's+-- organization (or the server) sets or clears archived_at; archived_by is+-- the person who archived, set here rather than trusted from the app. A+-- member's new draft is never archived: an insert with either column set+-- is refused (42501), as guard_content_draft_server_columns refuses its+-- columns.+-- * content_drafts_action_work_key (00218), one draft per action, method+-- and page, now counts only drafts not archived. A task's Start skips an+-- archived draft (readActionDrafts), so it writes a new one rather than+-- fail on the old key; restoring the archived one while a newer one does+-- the same work is refused (23505), and the Library says so.+-- * "content_drafts: manager delete": content_drafts had no delete policy,+-- so no member could delete a draft. Its versions, sources and+-- suggestions go with it (on delete cascade); the Action Center task it+-- was sent as stays, and Improve usage keeps its row (set null).++alter table public.content_drafts+ add column if not exists archived_at timestamptz,+ add column if not exists archived_by uuid references public.profiles(id) on delete set null;++comment on column public.content_drafts.archived_at is+ 'When an admin or manager archived the draft (Library › Archived); null when it is not archived. It keeps its status.';+comment on column public.content_drafts.archived_by is+ 'Who archived the draft; set by guard_content_draft_archive.';++create or replace function public.guard_content_draft_archive()+returns trigger+language plpgsql+set search_path = ''+as $$+begin+ if tg_op = 'INSERT' then+ -- A role that bypasses RLS is server-side (service role, migrations).+ if (new.archived_at is not null or new.archived_by is not null)+ and not (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user)+ then+ raise exception 'a new content draft is not archived'+ using errcode = '42501';+ end if;+ return new;+ end if;++ if new.archived_at is not distinct from old.archived_at then+ -- archived_by follows archived_at only.+ new.archived_by := old.archived_by;+ return new;+ end if;++ -- A role that bypasses RLS is server-side (service role, migrations).+ if not (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user)+ and not exists (+ select 1+ from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where b.id = new.brand_id+ and p.id = auth.uid()+ and p.role in ('admin', 'manager')+ )+ then+ raise exception 'only admins and managers archive content drafts'+ using errcode = '42501';+ end if;++ new.archived_by := case when new.archived_at is null then null else auth.uid() end;+ return new;+end;+$$;++create or replace trigger content_drafts_guard_archive+ before insert or update on public.content_drafts+ for each row execute function public.guard_content_draft_archive();++drop index if exists public.content_drafts_action_work_key;+create unique index if not exists content_drafts_action_work_key+ on public.content_drafts (action_id, method, md5(coalesce(source_url, '')))+ where action_id is not null and archived_at is null;++comment on index public.content_drafts_action_work_key is+ 'Content Editor (CE-022, 00233): one draft not archived per action, method and page.';++create policy "content_drafts: manager delete"+ on public.content_drafts+ for delete+ using (+ brand_id in (+ select b.id+ from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ );++grant delete on public.content_drafts to authenticated;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex cd91babaa..31a99d542 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -34207,6 +34207,113 @@ grant execute on function public.prompt_visibility_summaries(uuid, timestamptz,comment on function public.prompt_visibility_summaries(uuid, timestamptz, timestamptz, text) is'Per-prompt visibility/mention aggregates for the All Prompts table. p_region scopes to one tracked location (#691); NULL blends every location. Planned with its arguments and read from idx_prompt_results_brand_created_metrics (00232); security definer, no rows when the caller is not a member of the brand''s organization.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00233_content_drafts_archive.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00233: archive and delete Library drafts (Content Editor, CE-002)+-- ============================================================================+-- The Library's rows get a menu (the user's request): a status to pick, Send+-- to Archive, and Delete. Admins and managers archive and delete, as they+-- hide the Plan's rows (00229); every member can still change a status.+--+-- * content_drafts.archived_at / archived_by: an archived draft keeps its+-- status, so Restore puts it back where it was. Archive is not a status:+-- the Agent API, MCP and the editor read the four statuses unchanged.+-- * guard_content_draft_archive: only an admin or a manager of the brand's+-- organization (or the server) sets or clears archived_at; archived_by is+-- the person who archived, set here rather than trusted from the app. A+-- member's new draft is never archived: an insert with either column set+-- is refused (42501), as guard_content_draft_server_columns refuses its+-- columns.+-- * content_drafts_action_work_key (00218), one draft per action, method+-- and page, now counts only drafts not archived. A task's Start skips an+-- archived draft (readActionDrafts), so it writes a new one rather than+-- fail on the old key; restoring the archived one while a newer one does+-- the same work is refused (23505), and the Library says so.+-- * "content_drafts: manager delete": content_drafts had no delete policy,+-- so no member could delete a draft. Its versions, sources and+-- suggestions go with it (on delete cascade); the Action Center task it+-- was sent as stays, and Improve usage keeps its row (set null).++alter table public.content_drafts+ add column if not exists archived_at timestamptz,+ add column if not exists archived_by uuid references public.profiles(id) on delete set null;++comment on column public.content_drafts.archived_at is+ 'When an admin or manager archived the draft (Library › Archived); null when it is not archived. It keeps its status.';+comment on column public.content_drafts.archived_by is+ 'Who archived the draft; set by guard_content_draft_archive.';++create or replace function public.guard_content_draft_archive()+returns trigger+language plpgsql+set search_path = ''+as $$+begin+ if tg_op = 'INSERT' then+ -- A role that bypasses RLS is server-side (service role, migrations).+ if (new.archived_at is not null or new.archived_by is not null)+ and not (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user)+ then+ raise exception 'a new content draft is not archived'+ using errcode = '42501';+ end if;+ return new;+ end if;++ if new.archived_at is not distinct from old.archived_at then+ -- archived_by follows archived_at only.+ new.archived_by := old.archived_by;+ return new;+ end if;++ -- A role that bypasses RLS is server-side (service role, migrations).+ if not (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user)+ and not exists (+ select 1+ from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where b.id = new.brand_id+ and p.id = auth.uid()+ and p.role in ('admin', 'manager')+ )+ then+ raise exception 'only admins and managers archive content drafts'+ using errcode = '42501';+ end if;++ new.archived_by := case when new.archived_at is null then null else auth.uid() end;+ return new;+end;+$$;++create or replace trigger content_drafts_guard_archive+ before insert or update on public.content_drafts+ for each row execute function public.guard_content_draft_archive();++drop index if exists public.content_drafts_action_work_key;+create unique index if not exists content_drafts_action_work_key+ on public.content_drafts (action_id, method, md5(coalesce(source_url, '')))+ where action_id is not null and archived_at is null;++comment on index public.content_drafts_action_work_key is+ 'Content Editor (CE-022, 00233): one draft not archived per action, method and page.';++create policy "content_drafts: manager delete"+ on public.content_drafts+ for delete+ using (+ brand_id in (+ select b.id+ from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ );++grant delete on public.content_drafts to authenticated;+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00234_getting_started_plan_steps.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex af0b6157a..09f461168 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3217,10 +3217,11 @@"tabsLabel": "Library sections","tabs": {"all": "All",- "draft": "Drafts",+ "draft": "In progress","in_review": "In review","ready": "Ready",- "published": "Published"+ "published": "Published",+ "archived": "Archived"},"columns": {"content": "Content",@@ -3228,9 +3229,30 @@"method": "Method","by": "By","status": "Status",- "score": "AEO score"+ "created": "Created",+ "updated": "Updated",+ "menu": "Row actions"+ },+ "rowMenu": {+ "label": "Actions for {title}",+ "status": "Status",+ "archive": "Send to Archive",+ "restore": "Restore",+ "delete": "Delete",+ "archived": "Archived: {title}",+ "restored": "Restored: {title}",+ "deleted": "Deleted: {title}",+ "undo": "Undo",+ "failed": "Couldn't save that. Try again.",+ "forbidden": "Only admins and managers can archive or delete content.",+ "newerDraft": "A newer draft does this task's work. Archive or delete it first, then restore this one."+ },+ "deleteDialog": {+ "title": "Delete “{title}”?",+ "description": "It leaves the Library for good, with its versions and suggestions. An Action Center task it was sent as stays. This can't be undone.",+ "cancel": "Cancel",+ "confirm": "Delete"},- "scoreHint": "The page's AEO score, before → after the changes","latestOnly": "Showing the {shown} changed most recently of {count}.","untitled": "Untitled","you": "You",@@ -3241,10 +3263,11 @@"body": "Pages you and the Content Agent write or change in Ansvisor show up here."},"emptyTab": {- "draft": "No drafts.",+ "draft": "Nothing in progress.","in_review": "Nothing waiting for review.","ready": "Nothing marked ready.",- "published": "Nothing published yet."+ "published": "Nothing published yet.",+ "archived": "Nothing archived."},"loadError": "Couldn't load the Library.","retry": "Try again",@@ -4038,7 +4061,7 @@}},"status": {- "draft": "Draft",+ "draft": "In progress","in_review": "In review","ready": "Ready","published": "Published"diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsxindex 089c7df27..01e907e98 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx@@ -1,10 +1,27 @@'use client';import { useTranslations } from 'next-intl';-import { Bot, FileText } from 'lucide-react';+import {+ Archive,+ ArchiveRestore,+ Bot,+ Check,+ FileText,+ MoreHorizontal,+ Trash2,+} from 'lucide-react';import { Link } from '@/i18n/navigation';import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';import { Badge } from '@/components/ui/badge';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import {Table,TableBody,@@ -20,20 +37,46 @@ import {} from '@/components/content/draft-badges';import { assigneeLabel, labelInitials } from '@/lib/action-center/display';import {- aeoScoreText,+ DRAFT_STATUSES,contentEditorPath,isPageType,type ContentDraftListItem,+ type DraftStatus,type LibraryTab,} from '@/lib/content/drafts';+import { formatDate, formatMonthDay } from '@/lib/format';++/** A date this year as "Oct 16", an older one with its year, so the table fits at 1024 px. */+function tableDate(iso: string): string {+ return new Date(iso).getFullYear() === new Date().getFullYear()+ ? formatMonthDay(iso)+ : formatDate(iso);+}++export interface LibraryRowActions {+ /** Admins and managers: archive, restore and delete too. */+ canManage: boolean;+ onStatus: (draft: ContentDraftListItem, status: DraftStatus) => void;+ onArchive: (draft: ContentDraftListItem, archived: boolean) => void;+ onDelete: (draft: ContentDraftListItem) => void;+}/*** The Library's list (CE-002): one row per draft, the latest changed first.- * Columns as the spec's: Content · Type · Method (Create / Optimize) · By- * (a person or the Content Agent) · Status · AEO score (before → after).- * A row opens the draft in the editor.+ * Columns: Content · Type · Method (Create / Optimize) · By (a person or the+ * Content Agent) · Status · Created · Updated. A row opens the draft in the+ * editor; its menu sets the status and, for admins and managers, archives+ * or deletes it (00233).*/-export function LibraryTable({ drafts, tab }: { drafts: ContentDraftListItem[]; tab: LibraryTab }) {+export function LibraryTable({+ drafts,+ tab,+ actions,+}: {+ drafts: ContentDraftListItem[];+ tab: LibraryTab;+ actions: LibraryRowActions;+}) {const t = useTranslations('contentEditor.library');const tTypes = useTranslations('contentEditor.pageTypes');@@ -58,17 +101,18 @@ export function LibraryTable({ drafts, tab }: { drafts: ContentDraftListItem[];<TableHead>{t('columns.method')}</TableHead><TableHead>{t('columns.by')}</TableHead><TableHead>{t('columns.status')}</TableHead>- <TableHead className="pr-6 text-right" title={t('scoreHint')}>- {t('columns.score')}+ <TableHead>{t('columns.created')}</TableHead>+ <TableHead>{t('columns.updated')}</TableHead>+ <TableHead className="w-8 pl-0 pr-4">+ <span className="sr-only">{t('columns.menu')}</span></TableHead></TableRow></TableHeader><TableBody>{drafts.map((draft) => {- const score = aeoScoreText(draft.scoreBefore, draft.scoreAfter);return (<TableRow key={draft.id}>- <TableCell className="max-w-[320px] pl-6">+ <TableCell className="max-w-[180px] pl-6 xl:max-w-[320px]"><Linkhref={contentEditorPath(draft.id)}className="block truncate font-medium hover:underline"@@ -100,8 +144,18 @@ export function LibraryTable({ drafts, tab }: { drafts: ContentDraftListItem[];<DraftStatusBadge status={draft.status} />)}</TableCell>- <TableCell className="pr-6 text-right tabular-nums">- {score ?? <span className="text-muted-foreground">—</span>}+ <TableCell className="whitespace-nowrap text-xs text-muted-foreground tabular-nums">+ <time dateTime={draft.createdAt} title={formatDate(draft.createdAt)}>+ {tableDate(draft.createdAt)}+ </time>+ </TableCell>+ <TableCell className="whitespace-nowrap text-xs text-muted-foreground tabular-nums">+ <time dateTime={draft.updatedAt} title={formatDate(draft.updatedAt)}>+ {tableDate(draft.updatedAt)}+ </time>+ </TableCell>+ <TableCell className="pl-0 pr-4">+ <RowMenu draft={draft} actions={actions} /></TableCell></TableRow>);@@ -111,6 +165,61 @@ export function LibraryTable({ drafts, tab }: { drafts: ContentDraftListItem[];);}+/** A row's menu: its status, then archive or restore, and delete (admins and managers). */+function RowMenu({ draft, actions }: { draft: ContentDraftListItem; actions: LibraryRowActions }) {+ const t = useTranslations('contentEditor.library.rowMenu');+ const tStatus = useTranslations('contentEditor.status');+ const title = draft.title.trim() || null;+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ className="rounded p-1 text-muted-foreground hover:bg-muted"+ aria-label={t('label', { title: title ?? '—' })}+ >+ <MoreHorizontal className="h-4 w-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuGroup>+ <DropdownMenuLabel>{t('status')}</DropdownMenuLabel>+ {DRAFT_STATUSES.map((status) => (+ <DropdownMenuItem+ key={status}+ disabled={status === draft.status}+ onClick={() => actions.onStatus(draft, status)}+ >+ <Check+ aria-hidden="true"+ className={status === draft.status ? 'h-4 w-4' : 'h-4 w-4 opacity-0'}+ />+ {tStatus(status)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuGroup>+ {actions.canManage && (+ <>+ <DropdownMenuSeparator />+ {draft.archivedAt ? (+ <DropdownMenuItem onClick={() => actions.onArchive(draft, false)}>+ <ArchiveRestore className="h-4 w-4" />+ {t('restore')}+ </DropdownMenuItem>+ ) : (+ <DropdownMenuItem onClick={() => actions.onArchive(draft, true)}>+ <Archive className="h-4 w-4" />+ {t('archive')}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem variant="destructive" onClick={() => actions.onDelete(draft)}>+ <Trash2 className="h-4 w-4" />+ {t('delete')}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}+/** Who wrote it: the Content Agent, "You", or the member by name. */function DraftAuthorCell({ draft }: { draft: ContentDraftListItem }) {const t = useTranslations('contentEditor.library');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsxindex 25ccd6ba4..69428e59b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx@@ -8,6 +8,10 @@ import ContentLibraryPage from './page';const getContentDrafts = vi.fn();const getContentStartOptions = vi.fn();+const markContentDraftReady = vi.fn();+const setContentDraftStatus = vi.fn();+const archiveContentDraft = vi.fn();+const deleteContentDraft = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({// A list stands for a brand under the cap: its tabs count its rows.getContentDrafts: async (...args: unknown[]) => {@@ -16,7 +20,13 @@ vi.mock('@/lib/actions/content-drafts', () => ({},getContentStartOptions: (...args: unknown[]) => getContentStartOptions(...args),createContentDraft: vi.fn(),+ markContentDraftReady: (...args: unknown[]) => markContentDraftReady(...args),+ setContentDraftStatus: (...args: unknown[]) => setContentDraftStatus(...args),+ archiveContentDraft: (...args: unknown[]) => archiveContentDraft(...args),+ deleteContentDraft: (...args: unknown[]) => deleteContentDraft(...args),}));+const role = vi.hoisted(() => ({ canManage: true }));+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => role }));// Start's Team: its assignee picker reads the team, and the sent task is assigned.vi.mock('@/lib/actions/team', () => ({ listMembers: vi.fn(async () => []) }));vi.mock('@/lib/actions/action-center', () => ({ assignAction: vi.fn() }));@@ -29,7 +39,7 @@ vi.mock('@/i18n/navigation', () => ({),useRouter: () => ({ push }),}));-const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+const toast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));vi.mock('sonner', () => ({ toast }));const brandState = vi.hoisted(() => ({activeBrandId: 'brand-1' as string | null,@@ -54,10 +64,10 @@ const row = (over: Partial<ContentDraftListItem>): ContentDraftListItem => ({author: 'user',createdBy: { id: 'u1', fullName: 'Ada Lovelace', avatarUrl: null },isMine: true,- scoreBefore: 62,- scoreAfter: 78,agentState: null,+ createdAt: '2026-10-18T09:00:00Z',updatedAt: '2026-10-20T10:00:00Z',+ archivedAt: null,...over,});@@ -93,7 +103,14 @@ beforeEach(() => {topics: [],});push.mockReset();+ toast.mockReset();toast.error.mockReset();+ toast.success.mockReset();+ markContentDraftReady.mockReset().mockResolvedValue({ status: 'ready', tasksDone: 0 });+ setContentDraftStatus.mockReset().mockResolvedValue(undefined);+ archiveContentDraft.mockReset().mockResolvedValue(undefined);+ deleteContentDraft.mockReset().mockResolvedValue(undefined);+ role.canManage = true;});afterEach(() => {@@ -103,6 +120,8 @@ afterEach(() => {describe('the Content Library', () => {it('lists the brand’s drafts with who wrote them, and counts each tab', async () => {+ // Dates this year read "Oct 18"; an older one keeps its year.+ vi.useFakeTimers({ now: new Date('2026-10-22T12:00:00Z'), toFake: ['Date'] });getContentDrafts.mockResolvedValue([row({}),row({@@ -113,8 +132,6 @@ describe('the Content Library', () => {author: 'agent',createdBy: null,isMine: false,- scoreBefore: null,- scoreAfter: null,}),row({id: 'd3',@@ -122,11 +139,11 @@ describe('the Content Library', () => {status: 'published',isMine: false,createdBy: { id: 'u2', fullName: null, avatarUrl: null, email: '[email protected]' },- scoreBefore: 81,- scoreAfter: null,+ createdAt: '2025-12-30T10:00:00Z',}),]);await renderPage();+ vi.useRealTimers();expect(getContentDrafts).toHaveBeenCalledWith('brand-1');expect(tab('All').textContent).toBe('All3');@@ -136,26 +153,38 @@ describe('the Content Library', () => {const rows = [...container.querySelectorAll('tbody tr')].map((tr) =>[...tr.querySelectorAll('td')].map((td) => td.textContent),);+ // Created and Updated where the AEO score was; the last cell is the row menu.expect(rows[0]).toEqual(['Pipeline forecasting','Feature page','Optimize','AL' + 'You','In review',- '62 → 78',+ 'Oct 18',+ 'Oct 20',+ '',]);- expect(rows[1]).toEqual([+ expect(rows[1].slice(0, 5)).toEqual(['Northwind vs HubSpot','Comparison','Create','Content Agent','In review',- '—',]);// No title yet; a teammate with no name is named by e-mail.expect(rows[2][0]).toBe('Untitled');expect(rows[2][3]).toBe('[email protected]');- expect(rows[2][5]).toBe('81');+ expect(rows[2][5]).toBe('Dec 30, 2025');+ expect([...container.querySelectorAll('thead th')].map((th) => th.textContent)).toEqual([+ 'Content',+ 'Type',+ 'Method',+ 'By',+ 'Status',+ 'Created',+ 'Updated',+ 'Row actions',+ ]);const link = container.querySelector('tbody a')!;expect(link.getAttribute('href')).toBe('/dashboard/content/editor/d1');@@ -164,7 +193,7 @@ describe('the Content Library', () => {it('counts each tab in all past the cap, and says the list holds the latest', async () => {getContentDrafts.mockResolvedValue({drafts: [row({}), row({ id: 'd2', status: 'published' })],- counts: { all: 812, draft: 300, in_review: 12, ready: 0, published: 500 },+ counts: { all: 812, draft: 300, in_review: 12, ready: 0, published: 500, archived: 3 },});await renderPage();expect(tab('All').textContent).toBe('All812');@@ -273,3 +302,111 @@ describe('the Content Library', () => {expect(container.textContent).toContain('Select a brand to see its content.');});});++describe('a Library row’s menu (00233)', () => {+ const menuItems = async (title: string) => {+ const trigger = container.querySelector<HTMLElement>(`[aria-label="Actions for ${title}"]`)!;+ await act(async () => trigger.click());+ return [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')];+ };+ const pick = async (title: string, item: string) => {+ const found = (await menuItems(title)).find((el) => el.textContent === item)!;+ await act(async () => found.click());+ };++ it('sets a status, Ready as the editor’s Mark ready, and reads the list again', async () => {+ getContentDrafts.mockResolvedValue([row({})]);+ await renderPage();+ const items = await menuItems('Pipeline forecasting');+ expect(items.map((el) => el.textContent)).toEqual([+ 'In progress',+ 'In review',+ 'Ready',+ 'Published',+ 'Send to Archive',+ 'Delete',+ ]);+ // Its own status is the one already set.+ expect(items[1].hasAttribute('data-disabled')).toBe(true);++ await act(async () => items[2].click());+ expect(markContentDraftReady).toHaveBeenCalledWith('d1');+ expect(getContentDrafts).toHaveBeenCalledTimes(2);++ await pick('Pipeline forecasting', 'Published');+ expect(setContentDraftStatus).toHaveBeenCalledWith('d1', 'published');+ });++ it('lets members set a status only', async () => {+ role.canManage = false;+ getContentDrafts.mockResolvedValue([row({})]);+ await renderPage();+ expect((await menuItems('Pipeline forecasting')).map((el) => el.textContent)).toEqual([+ 'In progress',+ 'In review',+ 'Ready',+ 'Published',+ ]);+ });++ it('archives with an Undo, and keeps archived drafts under Archived, to restore', async () => {+ getContentDrafts.mockResolvedValue([+ row({}),+ row({ id: 'd2', title: 'Old pricing page', archivedAt: '2026-10-21T08:00:00Z' }),+ ]);+ await renderPage();+ expect(tab('All').textContent).toBe('All1');+ expect(tab('Archived').textContent).toBe('Archived1');+ expect(container.textContent).not.toContain('Old pricing page');++ await pick('Pipeline forecasting', 'Send to Archive');+ expect(archiveContentDraft).toHaveBeenCalledWith('d1', true);+ expect(toast).toHaveBeenCalledWith('Archived: Pipeline forecasting', {+ action: { label: 'Undo', onClick: expect.any(Function) },+ });+ await act(async () => toast.mock.calls[0][1].action.onClick());+ expect(archiveContentDraft).toHaveBeenLastCalledWith('d1', false);++ await act(async () => tab('Archived').click());+ expect(container.textContent).toContain('Old pricing page');+ await pick('Old pricing page', 'Restore');+ expect(archiveContentDraft).toHaveBeenLastCalledWith('d2', false);+ });++ it('deletes only once confirmed', async () => {+ getContentDrafts.mockResolvedValue([row({})]);+ await renderPage();+ await pick('Pipeline forecasting', 'Delete');+ expect(deleteContentDraft).not.toHaveBeenCalled();+ expect(document.body.textContent).toContain('Delete “Pipeline forecasting”?');++ const confirm = [...document.body.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent === 'Delete',+ )!;+ await act(async () => confirm.click());+ expect(deleteContentDraft).toHaveBeenCalledWith('d1');+ expect(toast.success).toHaveBeenCalledWith('Deleted: Pipeline forecasting');+ expect(getContentDrafts).toHaveBeenCalledTimes(2);+ });++ it('says what to do when a newer draft does the same work as the one restored', async () => {+ archiveContentDraft.mockRejectedValue(new Error('newer_draft'));+ getContentDrafts.mockResolvedValue([row({ archivedAt: '2026-10-21T10:00:00Z' })]);+ window.history.replaceState(null, '', '/dashboard/content/library?tab=archived');+ await renderPage();+ await pick('Pipeline forecasting', 'Restore');+ expect(toast.error).toHaveBeenCalledWith(+ "A newer draft does this task's work. Archive or delete it first, then restore this one.",+ );+ });++ it('says so when the server refuses the archive', async () => {+ archiveContentDraft.mockRejectedValue(new Error('forbidden'));+ getContentDrafts.mockResolvedValue([row({})]);+ await renderPage();+ await pick('Pipeline forecasting', 'Send to Archive');+ expect(toast.error).toHaveBeenCalledWith(+ 'Only admins and managers can archive or delete content.',+ );+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsxindex f5893824b..8f04207f6 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx@@ -2,24 +2,41 @@import { useEffect, useState } from 'react';import { useTranslations } from 'next-intl';+import { toast } from 'sonner';import { Loader2, Plus } from 'lucide-react';import { Button } from '@/components/ui/button';import { Card, CardContent } from '@/components/ui/card';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { NewContentDialog } from '@/components/content/new-content-dialog';-import { getContentDrafts } from '@/lib/actions/content-drafts';+import { useUserRole } from '@/hooks/use-user-role';+import {+ archiveContentDraft,+ deleteContentDraft,+ getContentDrafts,+ markContentDraftReady,+ setContentDraftStatus,+} from '@/lib/actions/content-drafts';import {AGENT_POLL_MS,LIBRARY_TABS,draftsInTab,type ContentDraftListItem,+ type DraftStatus,type LibraryTab,} from '@/lib/content/drafts';import { siteTypeOf } from '@/lib/content/page-types';import { formatNumber } from '@/lib/format';import { readUrlChoice, writeUrlParams } from '@/lib/url-state';import { useBrandStore } from '@/stores/use-brand-store';-import { LibraryTable } from './_library-table';+import { LibraryTable, type LibraryRowActions } from './_library-table';/** A read of the brand's drafts: null until it comes back. */interface LibraryRead {@@ -32,8 +49,10 @@ interface LibraryRead {/*** The Content Library (Content Editor, CE-002): everything a person or the- * Content Agent wrote or changed in Ansvisor, by status. The tab lives in the- * URL (?tab=in_review), so a link can open "Library › In review".+ * Content Agent wrote or changed in Ansvisor, by status, and what was+ * archived (00233). A row's menu sets its status; admins and managers also+ * archive, restore and delete. The tab lives in the URL (?tab=in_review), so+ * a link can open "Library › In review".*/export default function ContentLibraryPage() {const t = useTranslations('contentEditor.library');@@ -43,6 +62,10 @@ export default function ContentLibraryPage() {const [read, setRead] = useState<LibraryRead | null>(null);const [attempt, setAttempt] = useState(0);const [starting, setStarting] = useState(false);+ const { canManage } = useUserRole();+ // The draft whose Delete waits for a confirmation.+ const [deleting, setDeleting] = useState<ContentDraftListItem | null>(null);+ const [deletePending, setDeletePending] = useState(false);useEffect(() => {// eslint-disable-next-line react-hooks/set-state-in-effect -- one read of the URL after mount@@ -76,6 +99,63 @@ export default function ContentLibraryPage() {return () => clearTimeout(timer);}, [agentWriting, read]);+ const reload = () => setAttempt((n) => n + 1);+ const titleOf = (draft: ContentDraftListItem) => draft.title.trim() || t('untitled');+ const failed = (err: unknown) => {+ console.error('Failed to change the Library draft:', err);+ toast.error(+ t(+ err instanceof Error && err.message === 'forbidden'+ ? 'rowMenu.forbidden'+ : err instanceof Error && err.message === 'newer_draft'+ ? 'rowMenu.newerDraft'+ : 'rowMenu.failed',+ ),+ );+ };++ const archive = async (draft: ContentDraftListItem, archived: boolean) => {+ try {+ await archiveContentDraft(draft.id, archived);+ reload();+ toast(t(archived ? 'rowMenu.archived' : 'rowMenu.restored', { title: titleOf(draft) }), {+ action: archived+ ? { label: t('rowMenu.undo'), onClick: () => void archive(draft, false) }+ : undefined,+ });+ } catch (err) {+ failed(err);+ }+ };++ const rowActions: LibraryRowActions = {+ canManage,+ onStatus: (draft: ContentDraftListItem, status: DraftStatus) => {+ // Ready keeps a History version and completes the draft's task, as the editor's Mark ready.+ const change =+ status === 'ready'+ ? markContentDraftReady(draft.id)+ : setContentDraftStatus(draft.id, status);+ change.then(reload, failed);+ },+ onArchive: (draft, archived) => void archive(draft, archived),+ onDelete: setDeleting,+ };++ const confirmDelete = async () => {+ if (!deleting) return;+ setDeletePending(true);+ try {+ await deleteContentDraft(deleting.id);+ toast.success(t('rowMenu.deleted', { title: titleOf(deleting) }));+ setDeleting(null);+ reload();+ } catch (err) {+ failed(err);+ }+ setDeletePending(false);+ };+const changeTab = (next: LibraryTab) => {setTab(next);writeUrlParams({ tab: next }, { tab: 'all' });@@ -147,10 +227,32 @@ export default function ContentLibraryPage() {<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>) : (- <LibraryTable drafts={listed} tab={tab} />+ <LibraryTable drafts={listed} tab={tab} actions={rowActions} />)}</CardContent></Card>+ <Dialog open={deleting !== null} onOpenChange={(open) => !open && setDeleting(null)}>+ <DialogContent className="grid-cols-[minmax(0,1fr)] sm:max-w-md">+ <DialogHeader>+ <DialogTitle className="pr-6 leading-snug [overflow-wrap:anywhere]">+ {t('deleteDialog.title', { title: deleting ? titleOf(deleting) : '' })}+ </DialogTitle>+ <DialogDescription>{t('deleteDialog.description')}</DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button variant="outline" onClick={() => setDeleting(null)} disabled={deletePending}>+ {t('deleteDialog.cancel')}+ </Button>+ <Button+ variant="destructive"+ onClick={() => void confirmDelete()}+ disabled={deletePending}+ >+ {t('deleteDialog.confirm')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>{counts && listed.length < counts[tab] && (<p className="text-xs text-muted-foreground">{t('latestOnly', {diff --git a/web/src/lib/actions/content-drafts-library.test.ts b/web/src/lib/actions/content-drafts-library.test.tsindex 5092c6c49..f58aed753 100644--- a/web/src/lib/actions/content-drafts-library.test.ts+++ b/web/src/lib/actions/content-drafts-library.test.ts@@ -10,6 +10,9 @@ const BRAND = '33333333-3333-3333-3333-333333333333';let rows: Record<string, unknown>[];let counted: Record<string, number>;let countReads: string[];+// The row menu's writes (00233): what each update or delete returns.+let writes: { op: string; value?: unknown; id?: unknown }[];+let writeResult: { data: unknown; error: { code?: string; message: string } | null };vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));@@ -19,14 +22,27 @@ vi.mock('@/lib/supabase/server', () => ({from: () => {let head = false;let status = 'all';+ let archived = false;+ let write: { op: string; value?: unknown; id?: unknown } | null = null;const chain: Record<string, unknown> = {select: (_cols: string, opts?: { head?: boolean }) => ((head = !!opts?.head), chain),- eq: (col: string, v: string) => (col === 'status' && (status = v), chain),+ eq: (col: string, v: string) => {+ if (col === 'status') status = v;+ if (col === 'id' && write) write.id = v;+ return chain;+ },+ is: () => chain,+ not: (col: string) => (col === 'archived_at' && (archived = true), chain),order: () => chain,limit: async () => ({ data: rows, error: null }),+ update: (value: unknown) => ((write = { op: 'update', value }), writes.push(write), chain),+ delete: () => ((write = { op: 'delete' }), writes.push(write), chain),+ maybeSingle: async () => writeResult,then: (resolve: (r: unknown) => void) => {- countReads.push(status);- resolve({ count: head ? counted[status] : null, error: null });+ if (write) return resolve(writeResult);+ const tab = archived ? 'archived' : status;+ countReads.push(tab);+ resolve({ count: head ? counted[tab] : null, error: null });},};return chain;@@ -34,7 +50,9 @@ vi.mock('@/lib/supabase/server', () => ({})),}));-const { getContentDrafts } = await import('./content-drafts');+const { archiveContentDraft, deleteContentDraft, getContentDrafts, setContentDraftStatus } =+ await import('./content-drafts');+const DRAFT = '2f1d1c52-0f7a-4c1e-9b8a-5d6e7f8a9b0c';const row = (i: number, status = 'draft') => ({id: `d${i}`,@@ -48,12 +66,16 @@ const row = (i: number, status = 'draft') => ({score_after: null,agent_state: null,agent_state_at: null,+ created_at: '2026-10-19T08:00:00Z',updated_at: '2026-10-21T10:00:00Z',+ archived_at: null,});beforeEach(() => {countReads = [];- counted = { all: 812, draft: 300, in_review: 12, ready: 0, published: 500 };+ counted = { all: 812, draft: 300, in_review: 12, ready: 0, published: 500, archived: 7 };+ writes = [];+ writeResult = { data: { id: DRAFT }, error: null };});describe('getContentDrafts', () => {@@ -61,15 +83,76 @@ describe('getContentDrafts', () => {rows = [row(1), row(2, 'published')];const { drafts, counts } = await getContentDrafts(BRAND);expect(drafts).toHaveLength(2);- expect(counts).toEqual({ all: 2, draft: 1, in_review: 0, ready: 0, published: 1 });+ expect(counts).toEqual({+ all: 2,+ draft: 1,+ in_review: 0,+ ready: 0,+ published: 1,+ archived: 0,+ });expect(countReads).toEqual([]);});+ it('reads when each draft was created, and sets the archived ones apart', async () => {+ rows = [row(1), { ...row(2, 'published'), archived_at: '2026-10-21T09:00:00Z' }];+ const { drafts, counts } = await getContentDrafts(BRAND);+ expect(drafts.map((d) => [d.createdAt, d.archivedAt])).toEqual([+ ['2026-10-19T08:00:00Z', null],+ ['2026-10-19T08:00:00Z', '2026-10-21T09:00:00Z'],+ ]);+ expect(counts).toMatchObject({ all: 1, published: 0, archived: 1 });+ });+it('counts each tab on its own at the cap', async () => {rows = Array.from({ length: 500 }, (_, i) => row(i));const { drafts, counts } = await getContentDrafts(BRAND);expect(drafts).toHaveLength(500);expect(counts).toEqual(counted);- expect(countReads.sort()).toEqual(['all', 'draft', 'in_review', 'published', 'ready']);+ expect(countReads.sort()).toEqual([+ 'all',+ 'archived',+ 'draft',+ 'in_review',+ 'published',+ 'ready',+ ]);+ });+});++describe('the Library row menu (00233)', () => {+ it('sets a status any member may set', async () => {+ await setContentDraftStatus(DRAFT, 'in_review');+ expect(writes).toEqual([{ op: 'update', value: { status: 'in_review' }, id: DRAFT }]);+ });++ it('refuses Ready (it goes through Mark ready) and a malformed id, writing nothing', async () => {+ await expect(setContentDraftStatus(DRAFT, 'ready' as never)).rejects.toThrow('invalid');+ await expect(setContentDraftStatus('nope', 'draft')).rejects.toThrow('invalid');+ expect(writes).toEqual([]);+ });++ it('archives and restores, and names a refusal by the trigger as forbidden', async () => {+ await archiveContentDraft(DRAFT, true);+ expect((writes[0].value as { archived_at: string }).archived_at).toEqual(expect.any(String));+ await archiveContentDraft(DRAFT, false);+ expect(writes[1].value).toEqual({ archived_at: null });++ writeResult = { data: null, error: { code: '42501', message: 'only admins and managers' } };+ await expect(archiveContentDraft(DRAFT, true)).rejects.toThrow('forbidden');+ });++ it('names a restore refused by the one-draft-per-work key', async () => {+ writeResult = { data: null, error: { code: '23505', message: 'duplicate key' } };+ await expect(archiveContentDraft(DRAFT, false)).rejects.toThrow('newer_draft');+ });++ it('deletes, and calls a delete that removed nothing forbidden', async () => {+ writeResult = { data: [{ id: DRAFT }], error: null };+ await deleteContentDraft(DRAFT);+ expect(writes).toEqual([{ op: 'delete', id: DRAFT }]);++ writeResult = { data: [], error: null };+ await expect(deleteContentDraft(DRAFT)).rejects.toThrow('forbidden');});});diff --git a/web/src/lib/actions/content-drafts-start.test.ts b/web/src/lib/actions/content-drafts-start.test.tsindex 395198ea1..cb626a6a2 100644--- a/web/src/lib/actions/content-drafts-start.test.ts+++ b/web/src/lib/actions/content-drafts-start.test.ts@@ -244,6 +244,8 @@ describe('getOpportunityDrafts', () => {['eq', 'brand_id', BRAND],['in', 'opportunity_id', [OPPORTUNITY]],['in', 'status', ['draft', 'in_review', 'ready']],+ // An archived draft is set aside (00233): Send to Editor again.+ ['is', 'archived_at', null],],},]);@@ -268,6 +270,7 @@ describe('getDraftForPrompt', () => {['eq', 'brand_id', BRAND],['contains', 'prompt_ids', [PROMPT]],['in', 'status', ['draft', 'in_review', 'ready']],+ ['is', 'archived_at', null],],},]);@@ -665,6 +668,12 @@ describe('startDraftFromAction', () => {'deleted_at',null,]);+ // An archived draft is set aside: Start writes a new one rather than reopen it.+ expect(calls.find((call) => call.table === 'content_drafts')!.filters).toContainEqual([+ 'is',+ 'archived_at',+ null,+ ]);expect(admin.inserts).toEqual([{table: 'content_drafts',@@ -788,6 +797,31 @@ describe('startDraftFromAction', () => {expect(admin.inserts).toEqual([]);});+ // The work's draft was archived: the read skips it (as the DB's filter+ // does) and the one-per-work key counts only drafts not archived (00233),+ // so Start writes a new one rather than fail on the archived one's key.+ it('writes a new draft for work whose draft was archived', async () => {+ reads = {+ actions: action({ pages: [] }),+ action_tasks: { id: TASK, task_key: 'create_content_draft', status: 'todo' },+ content_drafts: [],+ brands: null,+ prompts: [],+ content_opportunities: null,+ };+ await expect(start(null)).resolves.toEqual({+ draftId: 'action-draft',+ created: true,+ importFailed: false,+ });+ expect(calls.find((call) => call.table === 'content_drafts')!.filters).toContainEqual([+ 'is',+ 'archived_at',+ null,+ ]);+ expect(admin.inserts).toHaveLength(1);+ });+it('opens the draft another start wrote at the same time', async () => {reads = {actions: action({ pages: [] }),diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex bf767d164..0b694451e 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -118,7 +118,9 @@ async function countLibraryTabs(.from('content_drafts').select('id', { count: 'exact', head: true }).eq('brand_id', brandId);- if (tab !== 'all') query = query.eq('status', tab);+ if (tab === 'archived') query = query.not('archived_at', 'is', null);+ else query = query.is('archived_at', null);+ if (tab !== 'all' && tab !== 'archived') query = query.eq('status', tab);const { count, error } = await query;if (error) throw new Error(error.message);return [tab, count ?? 0] as const;@@ -138,7 +140,7 @@ export async function getContentDrafts(brandId: string): Promise<ContentLibrary>supabase.from('content_drafts').select(- 'id, title, page_type, method, status, author, created_by, score_before, score_after, agent_state, agent_state_at, updated_at',+ 'id, title, page_type, method, status, author, created_by, agent_state, agent_state_at, created_at, updated_at, archived_at',).eq('brand_id', brandId).order('updated_at', { ascending: false })@@ -166,10 +168,10 @@ export async function getContentDrafts(brandId: string): Promise<ContentLibrary>author: row.author === 'agent' ? 'agent' : 'user',createdBy: row.created_by ? (people.get(row.created_by) ?? null) : null,isMine: me !== null && row.created_by === me,- scoreBefore: row.score_before,- scoreAfter: row.score_after,agentState: agentStateOf(row.agent_state, row.agent_state_at),+ createdAt: row.created_at,updatedAt: row.updated_at,+ archivedAt: row.archived_at,}),);// Under the cap the rows are every draft; at it, each tab is counted on its own.@@ -355,6 +357,8 @@ export async function getDraftForPrompt(brandId: string, promptId: string): Prom.eq('brand_id', brandId).contains('prompt_ids', [promptId]).in('status', ['draft', 'in_review', 'ready'])+ // An archived draft isn't the one to open (00233).+ .is('archived_at', null).order('updated_at', { ascending: false }).limit(1).maybeSingle();@@ -385,6 +389,8 @@ export async function getOpportunityDrafts(.eq('brand_id', brandId).in('opportunity_id', ids).in('status', ['draft', 'in_review', 'ready'])+ // Archived is set aside (00233): the row offers Send to Editor again.+ .is('archived_at', null).order('updated_at', { ascending: false });if (error) throw new Error(error.message);const drafts: Record<string, string> = {};@@ -574,6 +580,9 @@ async function readActionDrafts(.select('id, method, source_url, status').eq('brand_id', brandId).eq('action_id', actionId)+ // Archived is set aside, as on the Plan and in MCP: the drawer doesn't+ // list it, and a task's Start writes a new draft rather than reopen it.+ .is('archived_at', null).order('created_at', { ascending: true });if (error) throw new Error(error.message);return (data ?? []).map((row) => ({@@ -1047,6 +1056,67 @@ export async function setContentDraftPageType(id: string, pageType: PageType): Pif (!data) throw new Error('not_found');}+/** The statuses the Library's row menu sets directly; Ready goes through markContentDraftReady. */+const ROW_STATUSES = ['draft', 'in_review', 'published'] as const;++/**+ * Set a draft's status from the Library's row menu (any member, as the+ * editor's own status changes). Ready keeps a History version and completes+ * the draft's task, so it goes through markContentDraftReady instead.+ */+export async function setContentDraftStatus(+ id: string,+ status: (typeof ROW_STATUSES)[number],+): Promise<void> {+ if (!draftId.safeParse(id).success || !(ROW_STATUSES as readonly string[]).includes(status)) {+ throw new Error('invalid');+ }+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('content_drafts')+ .update({ status })+ .eq('id', id)+ .select('id')+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!data) throw new Error('not_found');+}++/**+ * Send a draft to the Library's archive, or restore it (admins and+ * managers; 00233's trigger refuses anyone else). It keeps its status.+ */+export async function archiveContentDraft(id: string, archived: boolean): Promise<void> {+ if (!draftId.safeParse(id).success) throw new Error('invalid');+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('content_drafts')+ .update({ archived_at: archived ? new Date().toISOString() : null })+ .eq('id', id)+ .select('id')+ .maybeSingle();+ if (error) {+ // Restoring one while a newer draft does the same task's work (the+ // one-per-work key, 00233): that one goes to the archive first.+ if (error.code === '23505') throw new Error('newer_draft');+ throw new Error(error.code === '42501' ? 'forbidden' : error.message);+ }+ if (!data) throw new Error('not_found');+}++/**+ * Delete a draft for good (admins and managers; content_drafts' delete+ * policy, 00233). Its versions, sources and suggestions go with it.+ */+export async function deleteContentDraft(id: string): Promise<void> {+ if (!draftId.safeParse(id).success) throw new Error('invalid');+ const supabase = await createClient();+ const { data, error } = await supabase.from('content_drafts').delete().eq('id', id).select('id');+ if (error) throw new Error(error.message);+ // No row: not the member's to delete, or gone already.+ if (!data?.length) throw new Error('forbidden');+}+/*** Mark ready: a draft, or an agent's draft in review, is ready to publish.* Ansvisor never publishes it; the person does (CE-013 records the URL).diff --git a/web/src/lib/actions/content-plan.test.ts b/web/src/lib/actions/content-plan.test.tsindex a3a43a623..eebd00baa 100644--- a/web/src/lib/actions/content-plan.test.ts+++ b/web/src/lib/actions/content-plan.test.ts@@ -34,6 +34,7 @@ vi.mock('@/lib/supabase/server', () => ({if (col === 'id') byId = true;return chain;},+ is: (col: string, v: unknown) => (filters.push([table, 'is', col, v]), chain),order: () => chain,limit: () => chain,upsert: async (value: unknown, options: unknown) => {@@ -191,6 +192,8 @@ describe('getContentPlan', () => {expect(readAssignees).toHaveBeenCalledWith(expect.anything(), BRAND, ['u2']);expect(rpcCalls).toEqual([['content_plan_pages', { p_brand_id: BRAND, p_days: 7 }]]);expect(filters).toContainEqual(['content_opportunities', 'eq', 'type', 'owned']);+ // An archived draft (00233) leaves the Plan: its row starts afresh.+ expect(filters).toContainEqual(['content_drafts', 'is', 'archived_at', null]);expect(filters).toContainEqual(['content_opportunities','in',diff --git a/web/src/lib/actions/content-plan.ts b/web/src/lib/actions/content-plan.tsindex f8ce79aa1..f973328bd 100644--- a/web/src/lib/actions/content-plan.ts+++ b/web/src/lib/actions/content-plan.ts@@ -85,6 +85,8 @@ export async function getContentPlan(.select('id, author, created_by, method, opportunity_id, source_url, action_id').eq('brand_id', brandId).in('status', ['draft', 'in_review', 'ready'])+ // An archived draft (00233) is set aside: the row starts afresh.+ .is('archived_at', null).order('updated_at', { ascending: false }).limit(DRAFT_LIMIT),supabasediff --git a/web/src/lib/content/drafts.test.ts b/web/src/lib/content/drafts.test.tsindex bb9a358f8..ae63129ad 100644--- a/web/src/lib/content/drafts.test.ts+++ b/web/src/lib/content/drafts.test.ts@@ -4,7 +4,6 @@ import {DRAFT_STATUSES,PAGE_TYPES,WRITING_STALE_MS,- aeoScoreText,agentStateOf,contentEditorPath,draftsInTab,@@ -23,10 +22,10 @@ const draft = (id: string, status: DraftStatus): ContentDraftListItem => ({author: 'user',createdBy: null,isMine: true,- scoreBefore: null,- scoreAfter: null,agentState: null,+ createdAt: '2026-10-18T09:00:00Z',updatedAt: '2026-10-20T10:00:00Z',+ archivedAt: null,});const drafts = [@@ -44,26 +43,23 @@ describe('the Library tabs', () => {in_review: 2,ready: 0,published: 1,+ archived: 0,});});it('lists a tab’s drafts in their order, and every draft under All', () => {expect(draftsInTab(drafts, 'in_review').map((d) => d.id)).toEqual(['b', 'c']);expect(draftsInTab(drafts, 'ready')).toEqual([]);- expect(draftsInTab(drafts, 'all')).toBe(drafts);- });-});--describe('aeoScoreText', () => {- it('shows before → after once the changes are scored', () => {- expect(aeoScoreText(62, 78)).toBe('62 → 78');+ expect(draftsInTab(drafts, 'all')).toEqual(drafts);});- it('shows the one score there is, or nothing', () => {- expect(aeoScoreText(54, null)).toBe('54');- expect(aeoScoreText(null, 81)).toBe('81');- expect(aeoScoreText(70, 70)).toBe('70');- expect(aeoScoreText(null, null)).toBeNull();+ it('keeps archived drafts under Archived only, with their status kept for Restore', () => {+ const shelved = { ...draft('e', 'published'), archivedAt: '2026-10-21T08:00:00Z' };+ const all = [...drafts, shelved];+ expect(libraryTabCounts(all)).toMatchObject({ all: 4, published: 1, archived: 1 });+ expect(draftsInTab(all, 'all').map((d) => d.id)).toEqual(['a', 'b', 'c', 'd']);+ expect(draftsInTab(all, 'published').map((d) => d.id)).toEqual(['d']);+ expect(draftsInTab(all, 'archived')).toEqual([shelved]);});});diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.tsindex 9534555b5..897442702 100644--- a/web/src/lib/content/drafts.ts+++ b/web/src/lib/content/drafts.ts@@ -79,8 +79,11 @@ export function contentEditorPath(draftId: string) {return `/dashboard/content/editor/${draftId}`;}-/** The Library's tabs: everything, then one per status. */-export const LIBRARY_TABS = ['all', ...DRAFT_STATUSES] as const;+/**+ * The Library's tabs: everything, one per status, then the archived drafts+ * (00233), which leave every other tab and keep their status for Restore.+ */+export const LIBRARY_TABS = ['all', ...DRAFT_STATUSES, 'archived'] as const;export type LibraryTab = (typeof LIBRARY_TABS)[number];export interface DraftAuthor {@@ -102,11 +105,12 @@ export interface ContentDraftListItem {createdBy: DraftAuthor | null;/** Whether the signed-in member started it ("You"). */isMine: boolean;- scoreBefore: number | null;- scoreAfter: number | null;/** Where the Content Agent is on it (CE-015). */agentState: AgentState;+ createdAt: string;updatedAt: string;+ /** When an admin or manager archived it (00233); null when it isn't archived. */+ archivedAt: string | null;}/**@@ -227,7 +231,9 @@ export interface DraftStartOptions {}export function draftsInTab(drafts: ContentDraftListItem[], tab: LibraryTab) {- return tab === 'all' ? drafts : drafts.filter((d) => d.status === tab);+ if (tab === 'archived') return drafts.filter((d) => d.archivedAt !== null);+ const live = drafts.filter((d) => d.archivedAt === null);+ return tab === 'all' ? live : live.filter((d) => d.status === tab);}export function libraryTabCounts(drafts: ContentDraftListItem[]): Record<LibraryTab, number> {@@ -235,14 +241,13 @@ export function libraryTabCounts(drafts: ContentDraftListItem[]): Record<LibraryLibraryTab,number>;- counts.all = drafts.length;- for (const d of drafts) counts[d.status] += 1;+ for (const d of drafts) {+ if (d.archivedAt !== null) {+ counts.archived += 1;+ } else {+ counts.all += 1;+ counts[d.status] += 1;+ }+ }return counts;}--/** "62 → 78" once the changes are scored, "54" before, null with no score yet. */-export function aeoScoreText(before: number | null, after: number | null): string | null {- if (before !== null && after !== null && after !== before) return `${before} → ${after}`;- const score = after ?? before;- return score === null ? null : String(score);-}diff --git a/web/src/lib/mcp/content.ts b/web/src/lib/mcp/content.tsindex 9c4c02c67..fdd792559 100644--- a/web/src/lib/mcp/content.ts+++ b/web/src/lib/mcp/content.ts@@ -141,6 +141,8 @@ export async function listContentDraftsFor(.from('content_drafts').select('id, title, status, method, page_type, author, source_url, updated_at').eq('brand_id', brandId)+ // Archived drafts (00233) are set aside in the Library, and here.+ .is('archived_at', null).order('updated_at', { ascending: false }).limit(LIST_LIMIT);if (status) query = query.eq('status', status);diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 31a5b8755..9f1a71271 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -890,6 +890,8 @@ export type Database = {action_id: string | nullagent_state: string | nullagent_state_at: string | null+ archived_at: string | null+ archived_by: string | nullauthor: stringbody_html: stringbrief: Json | null@@ -914,6 +916,8 @@ export type Database = {action_id?: string | nullagent_state?: string | nullagent_state_at?: string | null+ archived_at?: string | null+ archived_by?: string | nullauthor?: stringbody_html?: stringbrief?: Json | null@@ -938,6 +942,8 @@ export type Database = {action_id?: string | nullagent_state?: string | nullagent_state_at?: string | null+ archived_at?: string | null+ archived_by?: string | nullauthor?: stringbody_html?: stringbrief?: Json | null