🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(cli): add `lh acceptance delete` to remove an acceptance shell (#23081)
Bryan5a04f3b839ad
diff --git a/apps/cli/src/commands/acceptance/delete.test.ts b/apps/cli/src/commands/acceptance/delete.test.tsnew file mode 100644index 00000000000..548efd4c975--- /dev/null+++ b/apps/cli/src/commands/acceptance/delete.test.ts@@ -0,0 +1,121 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTrpcClient } from '../../api/client';+import type * as format from '../../utils/format';+import { confirm } from '../../utils/format';+import { registerAcceptanceCommands } from '.';++vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn() }));+vi.mock('../../utils/format', async (importOriginal) => ({+ ...(await importOriginal<typeof format>()),+ confirm: vi.fn(),+}));++const idA = '598ebab1-74a3-4a7f-9bcb-9bfa71c654cb';+const idB = '7f1c2d3e-0000-4a7f-9bcb-9bfa71c654cc';+const remove = vi.fn();+const removeBatch = vi.fn();+const purgePreview = vi.fn();+const getBySubject = vi.fn();+let output: ReturnType<typeof vi.spyOn>;++const run = async (args: string[]) => {+ const program = new Command().exitOverride().configureOutput({ writeErr: () => {} });+ registerAcceptanceCommands(program);+ await program.parseAsync(['node', 'lh', 'acceptance', ...args]);+};++const lastLine = () => String(output.mock.calls.at(-1)?.[0]);++beforeEach(() => {+ vi.clearAllMocks();+ process.exitCode = undefined;+ output = vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(getTrpcClient).mockResolvedValue({+ acceptance: {+ getBySubject: { query: getBySubject },+ purgePreview: { query: purgePreview },+ remove: { mutate: remove },+ removeBatch: { mutate: removeBatch },+ },+ } as unknown as Awaited<ReturnType<typeof getTrpcClient>>);+ remove.mockResolvedValue({ success: true });+ purgePreview.mockResolvedValue({+ bytes: 3 * 1024 * 1024,+ fileCount: 4,+ files: { images: 3, other: 0, videos: 1 },+ rounds: 2,+ });+});++afterEach(() => {+ vi.restoreAllMocks();+ process.exitCode = undefined;+});++describe('acceptance delete', () => {+ it('deletes only the shell by default, keeping rounds as reports', async () => {+ vi.mocked(confirm).mockResolvedValue(true);++ await run(['delete', idA]);++ expect(vi.mocked(confirm).mock.calls[0][0]).toContain('kept as standalone reports');+ expect(purgePreview).not.toHaveBeenCalled();+ expect(remove).toHaveBeenCalledExactlyOnceWith({ id: idA, purge: false });+ expect(lastLine()).toContain('rounds kept as standalone reports');+ });++ it('does not delete when the prompt is declined', async () => {+ vi.mocked(confirm).mockResolvedValue(false);++ await run(['delete', idA]);++ expect(remove).not.toHaveBeenCalled();+ expect(lastLine()).toBe('Aborted.');+ });++ it('shows what --purge frees before removing rounds and evidence', async () => {+ vi.mocked(confirm).mockResolvedValue(true);++ await run(['delete', idA, '--purge']);++ expect(purgePreview).toHaveBeenCalledExactlyOnceWith({ ids: [idA] });+ const prompt = vi.mocked(confirm).mock.calls[0][0];+ expect(prompt).toContain('2 round(s), 4 evidence file(s)');+ expect(prompt).toContain('3.0 MB freed');+ expect(remove).toHaveBeenCalledExactlyOnceWith({ id: idA, purge: true });+ });++ it('still asks when the purge preview is unavailable', async () => {+ vi.mocked(confirm).mockResolvedValue(true);+ purgePreview.mockRejectedValue(new Error('Acceptance not found'));++ await run(['delete', idA, '--purge']);++ expect(vi.mocked(confirm).mock.calls[0][0]).toContain('cannot be undone');+ expect(remove).toHaveBeenCalledOnce();+ });++ it('resolves a subject reference and skips the prompt with --yes', async () => {+ getBySubject.mockResolvedValue({ id: idA });++ await run(['delete', 'task:T-12', '--yes']);++ expect(getBySubject).toHaveBeenCalledOnce();+ expect(confirm).not.toHaveBeenCalled();+ expect(remove).toHaveBeenCalledExactlyOnceWith({ id: idA, purge: false });+ });++ it('deletes several in one batch and fails the command for ids it could not remove', async () => {+ removeBatch.mockResolvedValue({ deleted: 1, failedIds: [idB] });++ await run(['rm', idA, idB, idA, '--yes', '--json']);++ expect(removeBatch).toHaveBeenCalledExactlyOnceWith({ ids: [idA, idB], purge: false });+ expect(remove).not.toHaveBeenCalled();+ expect(JSON.parse(lastLine())).toEqual({ deleted: 1, failedIds: [idB], purged: false });+ expect(process.exitCode).toBe(1);+ });+});diff --git a/apps/cli/src/commands/acceptance/delete.ts b/apps/cli/src/commands/acceptance/delete.tsnew file mode 100644index 00000000000..3e21770fbd4--- /dev/null+++ b/apps/cli/src/commands/acceptance/delete.ts@@ -0,0 +1,138 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient, type TrpcClient } from '../../api/client';+import { confirm, outputJson } from '../../utils/format';+import { log } from '../../utils/logger';++/** Mirrors the server's `removeBatch` / `purgePreview` input caps. */+const REMOVE_BATCH_LIMIT = 200;+const PURGE_PREVIEW_LIMIT = 20;++type PurgePreview = Awaited<ReturnType<TrpcClient['acceptance']['purgePreview']['query']>>;++interface DeleteOptions {+ json?: boolean | string;+ purge?: boolean;+ yes?: boolean;+}++const formatBytes = (bytes: number): string => {+ if (bytes < 1024) return `${bytes} B`;+ const units = ['KB', 'MB', 'GB', 'TB'];+ let value = bytes / 1024;+ let unit = 0;+ while (value >= 1024 && unit < units.length - 1) {+ value /= 1024;+ unit += 1;+ }+ return `${value.toFixed(value >= 10 ? 0 : 1)} ${units[unit]}`;+};++const describePurge = (preview: PurgePreview): string =>+ `${preview.rounds} round(s), ${preview.fileCount} evidence file(s) ` ++ `(screenshots ${preview.files.images} · recordings ${preview.files.videos} · other ${preview.files.other}), ` ++ `${formatBytes(preview.bytes)} freed`;++/**+ * The purge preview only answers up to its cap and fails on an id the caller+ * cannot read; a missing preview never blocks the delete, the prompt just+ * says less.+ */+async function loadPurgePreview(client: TrpcClient, ids: string[]) {+ if (ids.length > PURGE_PREVIEW_LIMIT) return;+ try {+ return await client.acceptance.purgePreview.query({ ids });+ } catch {+ return;+ }+}++async function confirmDelete(client: TrpcClient, ids: string[], purge: boolean) {+ const target = ids.length === 1 ? `acceptance ${pc.bold(ids[0])}` : `${ids.length} acceptances`;+ if (!purge) {+ return confirm(+ `Delete ${target}? Its verification rounds are kept as standalone reports (use --purge to remove them too).`,+ );+ }+ const preview = await loadPurgePreview(client, ids);+ const detail = preview ? ` This removes ${describePurge(preview)}.` : '';+ return confirm(+ `Permanently delete ${target} with every round, report and evidence file?${detail} This cannot be undone.`,+ );+}++async function removeAll(client: TrpcClient, ids: string[], purge: boolean) {+ // One id goes through `remove`, so a refusal (not found, no permission, a+ // goal still waiting on this acceptance) surfaces as its own error message+ // instead of a bare failed id.+ if (ids.length === 1) {+ await client.acceptance.remove.mutate({ id: ids[0], purge });+ return { deleted: 1, failedIds: [] as string[] };+ }++ let deleted = 0;+ const failedIds: string[] = [];+ for (let i = 0; i < ids.length; i += REMOVE_BATCH_LIMIT) {+ const result = await client.acceptance.removeBatch.mutate({+ ids: ids.slice(i, i + REMOVE_BATCH_LIMIT),+ purge,+ });+ deleted += result.deleted;+ failedIds.push(...result.failedIds);+ }+ return { deleted, failedIds };+}++/**+ * `lh acceptance delete` — remove the acceptance aggregate (the review shell+ * around its rounds). By default the rounds detach and stay reachable as+ * standalone reports; `--purge` also deletes the rounds and the evidence files+ * only they referenced, matching the Web delete dialog.+ */+export function attachDeleteCommand(+ acceptance: Command,+ resolveAcceptanceId: (ref: string) => Promise<string>,+) {+ acceptance+ .command('delete <idOrSubject...>')+ .alias('rm')+ .description(+ 'Delete acceptances (uuid or type:id); rounds are kept as standalone reports unless --purge',+ )+ .option('--purge', 'Also permanently delete every round, report and evidence file')+ .option('-y, --yes', 'Skip the confirmation prompt')+ .option('--json [fields]', 'Output JSON')+ .action(async (refs: string[], options: DeleteOptions) => {+ const ids: string[] = [];+ for (const ref of refs) ids.push(await resolveAcceptanceId(ref));+ const uniqueIds = [...new Set(ids)];+ const purge = Boolean(options.purge);+ const client = await getTrpcClient();++ if (!options.yes && !(await confirmDelete(client, uniqueIds, purge))) {+ console.log('Aborted.');+ return;+ }++ const result = await removeAll(client, uniqueIds, purge);+ if (result.failedIds.length > 0) process.exitCode = 1;++ if (options.json !== undefined) {+ outputJson(+ { ...result, purged: purge },+ typeof options.json === 'string' ? options.json : undefined,+ );+ return;+ }++ if (result.deleted > 0) {+ const what =+ uniqueIds.length === 1 ? `acceptance ${uniqueIds[0]}` : `${result.deleted} acceptance(s)`;+ console.log(+ `${pc.green('✓')} Deleted ${what}${purge ? ' with rounds and evidence' : ' — rounds kept as standalone reports'}`,+ );+ }+ for (const id of result.failedIds) log.error(`Could not delete ${id}`);+ });+}diff --git a/apps/cli/src/commands/acceptance/index.ts b/apps/cli/src/commands/acceptance/index.tsindex 887d54eade3..2c14a9487c5 100644--- a/apps/cli/src/commands/acceptance/index.ts+++ b/apps/cli/src/commands/acceptance/index.ts@@ -18,6 +18,7 @@ import { log } from '../../utils/logger';import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from '../resourceUrl';import { collectCommentFeedback } from './commentFeedback';import { attachCriterionCommands } from './criterion';+import { attachDeleteCommand } from './delete';import { attachAcceptanceFlowCommands } from './flow';import {assertReportLanguage,@@ -779,6 +780,7 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat// trees hang off the first-class command only; the legacy `lh verify acceptance`// alias stays a thin decision surface (the rest keep their `lh verify …` aliases).if (options?.deprecated) return;+ attachDeleteCommand(acceptance, resolveAcceptanceId);attachAcceptanceRunCommands(acceptance);attachPlanCommands(acceptance);attachCriterionCommands(acceptance);