🤯 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
🐛 fix(acceptance): resolve supersedes written with authored plan ids (#20813)
Arvin Xucaa9cb73a5d0
diff --git a/apps/cli/src/commands/acceptanceRun.test.ts b/apps/cli/src/commands/acceptanceRun.test.tsindex 217eb463569..4ec68b77237 100644--- a/apps/cli/src/commands/acceptanceRun.test.ts+++ b/apps/cli/src/commands/acceptanceRun.test.ts@@ -543,6 +543,42 @@ describe('acceptance publication with missing evidence', () => {expect(process.exitCode).toBe(1);});+ it('warns when supersedes names no check of the acceptance', async () => {+ client.acceptance.attachRun.mutate.mockResolvedValue({+ id: 'run-1',+ roundIndex: 2,+ unresolvedSupersedes: ['typo-id'],+ });+ await writeFile(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [{ evidence: ['output.txt'], id: 'response', name: '收到回复', status: 'passed' }],+ plan: [{ id: 'response', supersedes: ['typo-id'], title: '收到回复' }],+ summary: { passed: 1, total: 1, verdict: 'passed' },+ }),+ );++ await run('ingest', dir, '--json');++ expect(result()).toMatchObject({ unresolvedSupersedes: ['typo-id'] });+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('typo-id'));+ });++ it('reports no unresolved supersedes when an older server omits the field', async () => {+ await writeFile(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [{ evidence: ['output.txt'], id: 'response', name: '收到回复', status: 'passed' }],+ plan: [{ id: 'response', title: '收到回复' }],+ summary: { passed: 1, total: 1, verdict: 'passed' },+ }),+ );++ await run('ingest', dir, '--json');++ expect(result()).toMatchObject({ unresolvedSupersedes: [] });+ });+it('accounts for draft-only checks and incoming checks using the folded plan', async () => {client.acceptance.attachRun.mutate.mockResolvedValue({id: 'draft-run',diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.tsindex 0471c19fb74..d4e5c7b0b41 100644--- a/apps/cli/src/commands/acceptanceRun.ts+++ b/apps/cli/src/commands/acceptanceRun.ts@@ -852,6 +852,15 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption// The chained round's index — `?r=<roundIndex>` on the acceptance URL// deep-links this round's report as the fixed snapshot view.const roundIndex = attached?.roundIndex ?? null;+ // A `supersedes` entry that names no check of this acceptance folds nothing:+ // the old row would stay on the page as if never replaced. An older server+ // does not report these, so treat the field as optional.+ const unresolvedSupersedes: string[] = attached?.unresolvedSupersedes ?? [];+ if (unresolvedSupersedes.length > 0) {+ log.warn(+ `supersedes names no check of this acceptance, so nothing was replaced: ${unresolvedSupersedes.join(', ')}. Name it by a plan item id from an earlier round or a check id from \`lh acceptance view --json\`.`,+ );+ }const acceptanceUrl = new URL(`/acceptance/${encodeURIComponent(acceptanceId)}`,resolveServerUrl(),@@ -1058,6 +1067,7 @@ async function ingestReportAction(reportDir: string, options: IngestReportOptionsubject: subject!.ref,unexecuted: unexecuted.map((item) => item.id),unplanned,+ unresolvedSupersedes,verifyRunId: runId,},typeof options.json === 'string' ? options.json : undefined,diff --git a/apps/server/src/services/verify/__tests__/acceptanceMerge.test.ts b/apps/server/src/services/verify/__tests__/acceptanceMerge.test.tsindex 2a46de83b3f..466d6246e05 100644--- a/apps/server/src/services/verify/__tests__/acceptanceMerge.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceMerge.test.ts@@ -12,6 +12,7 @@ import type { LobeChatDatabase } from '@/database/type';import {collectCheckIds,countLogicalChecks,+ findUnresolvedSupersedes,mergeAcceptanceRounds,planCheckIdRemap,remapPlanItem,@@ -137,6 +138,60 @@ describe('collectCheckIds', () => {});});+describe('findUnresolvedSupersedes', () => {+ const prior = [+ run('run-1', 1, [planItem('old', { sourceCriterionId: 'crit-old' })]),+ run('run-2', 2, [planItem('older-flow', {})]),+ ];++ it('accepts an earlier plan item id, a row id, or an item of the same round', () => {+ expect(+ findUnresolvedSupersedes(+ [+ planItem('new', { supersedes: ['old', 'crit-old', 'older-flow'] }),+ planItem('newer', { supersedes: ['new'] }),+ ],+ prior,+ ),+ ).toEqual([]);+ });++ it('accepts a result-only check id from an earlier direct ingest', () => {+ expect(+ findUnresolvedSupersedes([planItem('new', { supersedes: ['result-only'] })], prior, [+ 'result-only',+ ]),+ ).toEqual([]);+ });++ it("accepts a same-round item's criterion id", () => {+ expect(+ findUnresolvedSupersedes(+ [planItem('a', { sourceCriterionId: 'crit-a' }), planItem('b', { supersedes: ['crit-a'] })],+ prior,+ ),+ ).toEqual([]);+ });++ it('reports an item that supersedes itself, which folds nothing', () => {+ expect(+ findUnresolvedSupersedes(+ [+ planItem('check-a', { supersedes: ['check-a'] }),+ planItem('check-b', { sourceCriterionId: 'crit-b', supersedes: ['crit-b'] }),+ ],+ prior,+ ),+ ).toEqual(['check-a', 'crit-b']);+ });++ it('reports an id that names no check of the acceptance', () => {+ expect(+ findUnresolvedSupersedes([planItem('new', { supersedes: ['old', 'typo-id'] })], prior),+ ).toEqual(['typo-id']);+ });+});+describe('countLogicalChecks', () => {it('counts one check once even when it carries a separate criterion id', () => {// `collectCheckIds` holds both ids for collision purposes — the user-facing@@ -156,6 +211,16 @@ describe('countLogicalChecks', () => {expect(countLogicalChecks(runs, [])).toBe(1);});+ it('does not count a generation folded away by its authored plan id', () => {+ // Rows are keyed by criterion; `supersedes` names the old plan item id.+ const runs = [+ run('run-1', 1, [planItem('old', { sourceCriterionId: 'crit-old' })]),+ run('run-2', 2, [planItem('new', { sourceCriterionId: 'crit-new', supersedes: ['old'] })]),+ ];++ expect(countLogicalChecks(runs, [])).toBe(1);+ });+it('counts a result that names an item no plan carries', () => {expect(countLogicalChecks(diff --git a/apps/server/src/services/verify/__tests__/acceptanceSettledCheck.test.ts b/apps/server/src/services/verify/__tests__/acceptanceSettledCheck.test.tsindex dcf518b74b6..216f7398a86 100644--- a/apps/server/src/services/verify/__tests__/acceptanceSettledCheck.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceSettledCheck.test.ts@@ -162,6 +162,37 @@ describe('attaching a round that targets an accepted check', () => {expect(mocks.attachToAcceptance).not.toHaveBeenCalled();});+ it('refuses a new id that supersedes the settled check by its authored plan id', async () => {+ // Authored ingests keep the harness's plan id but key the row by a minted+ // criterion. Naming the settled check by that plan id still folds it.+ mocks.listByAcceptance.mockResolvedValue([+ {+ acceptanceId: 'acc-1',+ id: 'run-1',+ plan: [{ id: 'settled-check', index: 0, sourceCriterionId: 'crit-s', title: 'settled' }],+ roundIndex: 1,+ },+ ]);+ mocks.listByRuns.mockResolvedValue([acceptedResult('settled-check', 'run-1')]);+ mocks.runFindById.mockResolvedValue({+ acceptanceId: null,+ id: 'run-2',+ plan: [+ {+ id: 'replacement',+ index: 0,+ sourceCriterionId: 'crit-r',+ supersedes: ['settled-check'],+ title: 'replacement',+ },+ ],+ userId: 'u1',+ });++ await expect(service().attachRun('run-2', 'acc-1')).rejects.toThrow(/replacement/);+ expect(mocks.attachToAcceptance).not.toHaveBeenCalled();+ });+it('attaches a round that only touches unreviewed or brand-new checks', async () => {mocks.runFindById.mockResolvedValue({acceptanceId: null,@@ -173,4 +204,57 @@ describe('attaching a round that targets an accepted check', () => {await expect(service().attachRun('run-2', 'acc-1')).resolves.toMatchObject({ roundIndex: 2 });expect(mocks.attachToAcceptance).toHaveBeenCalledOnce();});++ it('reports unresolved supersedes again when an already-attached run is re-attached', async () => {+ // The first attach committed but its response was lost; the retry takes+ // the idempotent path and must still carry the warning.+ mocks.runFindById.mockResolvedValue({+ acceptanceId: 'acc-1',+ id: 'run-2',+ plan: [{ id: 'replacement', index: 0, supersedes: ['typo-id'], title: 'replacement' }],+ roundIndex: 2,+ userId: 'u1',+ });+ mocks.listByAcceptance.mockResolvedValue([+ { acceptanceId: 'acc-1', id: 'run-1', plan: planned('settled-check'), roundIndex: 1 },+ {+ acceptanceId: 'acc-1',+ id: 'run-2',+ plan: [{ id: 'replacement', index: 0, supersedes: ['typo-id'], title: 'replacement' }],+ roundIndex: 2,+ },+ ]);++ await expect(service().attachRun('run-2', 'acc-1')).resolves.toMatchObject({+ id: 'run-2',+ unresolvedSupersedes: ['typo-id'],+ });+ expect(mocks.attachToAcceptance).not.toHaveBeenCalled();+ });++ it("resolves a supersedes that names the attached run's own result-only check", async () => {+ // An executed run carries a result for `result-only` without a plan item,+ // and another item replaces it; the union folds that row, so no warning.+ mocks.runFindById.mockResolvedValue({+ acceptanceId: null,+ id: 'run-2',+ plan: [{ id: 'replacement', index: 0, supersedes: ['result-only'], title: 'replacement' }],+ userId: 'u1',+ });+ mocks.listByRuns.mockImplementation(async (runIds: string[]) =>+ runIds.includes('run-2')+ ? [+ {+ ...acceptedResult('result-only', 'run-2'),+ userDecision: null,+ userDecisionDetail: null,+ },+ ]+ : [],+ );++ const attached = await service().attachRun('run-2', 'acc-1');++ expect(attached).not.toHaveProperty('unresolvedSupersedes');+ });});diff --git a/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts b/apps/server/src/services/verify/__tests__/acceptanceUnion.test.tsindex 642e57ca6b0..da4fb717665 100644--- a/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts@@ -400,6 +400,56 @@ describe('buildAcceptanceCheckUnion', () => {expect(rows[0].fixed).toBe(true);});+ it('folds a generation named by its authored plan id when rows are keyed by criterion', () => {+ // An authored ingest keeps the harness's plan id (`edit-modal`) but the+ // server mints a criterion per item, and the union keys rows by that+ // criterion. A `supersedes` written with the authored id must still fold.+ const rows = buildAcceptanceCheckUnion([+ {+ results: [result('edit-modal', 'passed')],+ run: run('r10', 10, [+ planItem('edit-modal', { sourceCriterionId: 'crit-20', title: '弹窗编辑' }),+ ]),+ },+ {+ results: [result('inline-edit', 'passed')],+ run: run('r11', 11, [+ planItem('inline-edit', {+ sourceCriterionId: 'crit-22',+ supersedes: ['edit-modal'],+ title: '原地编辑',+ }),+ ]),+ },+ ]);++ expect(rows).toHaveLength(1);+ expect(rows[0].id).toBe('crit-22');+ expect(rows[0].supersededIds).toEqual(['crit-20']);+ expect(rows[0].timeline.map((entry) => entry.title)).toEqual(['弹窗编辑', '原地编辑']);+ });++ it('folds a whole chain written with authored plan ids', () => {+ const rows = buildAcceptanceCheckUnion([+ {+ results: [result('a', 'failed')],+ run: run('r1', 1, [planItem('a', { sourceCriterionId: 'crit-a' })]),+ },+ {+ results: [result('b', 'failed')],+ run: run('r2', 2, [planItem('b', { sourceCriterionId: 'crit-b', supersedes: ['a'] })]),+ },+ {+ results: [result('c', 'passed')],+ run: run('r3', 3, [planItem('c', { sourceCriterionId: 'crit-c', supersedes: ['b'] })]),+ },+ ]);++ expect(rows).toHaveLength(1);+ expect(rows[0].id).toBe('crit-c');+ expect(rows[0].supersededIds.sort()).toEqual(['crit-a', 'crit-b']);+ });+it('reads the grouping category from the latest plan snapshot', () => {const rows = buildAcceptanceCheckUnion([{ results: [], run: run('r1', 1, [planItem('x', { category: '未读区' })]) },diff --git a/apps/server/src/services/verify/acceptanceMerge.ts b/apps/server/src/services/verify/acceptanceMerge.tsindex 71b04ca3515..38f8ae5ec73 100644--- a/apps/server/src/services/verify/acceptanceMerge.ts+++ b/apps/server/src/services/verify/acceptanceMerge.ts@@ -80,11 +80,51 @@ export const countLogicalChecks = (for (const result of results) {logical.add(logicalByItemId.get(result.checkItemId) ?? result.checkItemId);}- for (const id of superseded) logical.delete(id);+ // `supersedes` may name the plan item id the author wrote, while the row is+ // keyed by its criterion — resolve through the plan ids seen above.+ for (const id of superseded)+ logical.delete(logical.has(id) ? id : (logicalByItemId.get(id) ?? id));return logical.size;};+/**+ * `supersedes` ids in an incoming plan that name no check the acceptance has+ * seen — no plan item id or row id an earlier round wrote, no result-only check+ * id, no item of the incoming round itself — or the item itself, which the union+ * never folds into its own row. Such an entry folds nothing, so+ * the author is told instead of the old row silently staying on the page.+ */+export const findUnresolvedSupersedes = (+ plan: VerifyCheckItem[] | null | undefined,+ priorRuns: Pick<VerifyRunItem, 'plan'>[],+ /** Result check ids of earlier rounds and the incoming run; a direct ingest may carry no plan item. */+ priorResultCheckItemIds: Iterable<string> = [],+): string[] => {+ const identities = (item: VerifyCheckItem) => [+ item.id,+ item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id),+ ];+ const known = new Set<string>(priorResultCheckItemIds);+ for (const run of priorRuns) {+ for (const item of (run.plan ?? []) as VerifyCheckItem[]) {+ for (const id of identities(item)) known.add(id);+ }+ }+ // An item may also replace another item of the same incoming round.+ for (const item of plan ?? []) for (const id of identities(item)) known.add(id);++ const unresolved = new Set<string>();+ for (const item of plan ?? []) {+ // The union never folds a row into itself, so naming yourself replaces nothing.+ const self = new Set(identities(item));+ for (const id of item.supersedes ?? []) {+ if (id && (self.has(id) || !known.has(id))) unresolved.add(id);+ }+ }+ return [...unresolved];+};+/*** Assign a fresh id to every source check id the target already uses.*diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.tsindex 99e3e9e52eb..17ef052931f 100644--- a/apps/server/src/services/verify/acceptanceService.ts+++ b/apps/server/src/services/verify/acceptanceService.ts@@ -45,7 +45,11 @@ import type { LobeChatDatabase } from '@/database/type';import { notTrashed } from '@/database/utils/softDelete';import { ExpertiseRejectionWorkflow } from '@/server/workflows/expertiseRejection';-import { type AcceptanceMergeSummary, mergeAcceptanceRounds } from './acceptanceMerge';+import {+ type AcceptanceMergeSummary,+ findUnresolvedSupersedes,+ mergeAcceptanceRounds,+} from './acceptanceMerge';import { computeFalseFlags } from './feedbackService';const log = debug('lobe-server:verify-acceptance');@@ -143,6 +147,12 @@ const itemSurface = (item: VerifyCheckItem | undefined): VerifySurface | null =>return typeof raw === 'string' ? normalizeVerifySurface(raw) : null;};+/** A run chained onto an acceptance, with anything the author should fix. */+export type AttachedRun = VerifyRunItem & {+ /** `supersedes` ids naming no check of this acceptance; they fold nothing. */+ unresolvedSupersedes?: string[];+};+/*** Merge a whole round chain into the union check list.*@@ -161,6 +171,10 @@ export const buildAcceptanceCheckUnion = (const rows = new Map<string, AcceptanceCheckRow>();// Last round whose PLAN named each item — drives the carried-forward flag.const lastPlannedRound = new Map<string, number>();+ // A `supersedes` entry names the check the author knew: often the plan item id+ // they wrote, while the row is keyed by the criterion minted for it. Remember+ // every plan item id's row so the fold below resolves either spelling.+ const logicalIdByPlanItemId = new Map<string, string>();const ensureRow = (id: string, roundIndex: number): AcceptanceCheckRow => {const existing = rows.get(id);@@ -199,6 +213,7 @@ export const buildAcceptanceCheckUnion = (for (const item of plan) {const logicalId = item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);const row = ensureRow(logicalId, roundIndex);+ logicalIdByPlanItemId.set(item.id, logicalId);// The latest snapshot wins: repair rounds may refine method/expected.if (item.sourceFlowNode) {// A rerun is a fresh execution; historical evidence stays in the timeline.@@ -239,7 +254,9 @@ export const buildAcceptanceCheckUnion = (// order so a chain (C replaced by B replaced by A) collapses fully into A.const foldOrder = [...rows.values()].sort((a, b) => a.introducedAtRound - b.introducedAtRound);for (const row of foldOrder) {- const supersedes = (row.planItem?.supersedes ?? []).map((id) => rows.get(id)?.id ?? id);+ const supersedes = (row.planItem?.supersedes ?? []).map((id) =>+ rows.has(id) ? id : (logicalIdByPlanItemId.get(id) ?? id),+ );for (const oldId of supersedes) {const old = rows.get(oldId);if (!old || old === row) continue;@@ -648,7 +665,7 @@ export class AcceptanceService {* Chain a run onto an acceptance as its next round, then re-derive the* aggregate status (a new round re-opens a rejected loop).*/- attachRun = async (runId: string, acceptanceId: string): Promise<VerifyRunItem> => {+ attachRun = async (runId: string, acceptanceId: string): Promise<AttachedRun> => {const acceptance = await this.acceptanceModel.findById(acceptanceId);if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);@@ -656,7 +673,7 @@ export class AcceptanceService {};/** Attach a Task run using policy scope while preserving report visibility. */- attachPolicyRun = async (runId: string, acceptanceId: string): Promise<VerifyRunItem> => {+ attachPolicyRun = async (runId: string, acceptanceId: string): Promise<AttachedRun> => {const acceptance = await this.acceptanceModel.findPolicyById(acceptanceId);if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);@@ -727,6 +744,14 @@ export class AcceptanceService {blocked.add(check.id);for (const superseded of check.supersededIds ?? []) blocked.add(superseded);}+ // Rows are keyed by criterion, but an author names a check by the plan item+ // id they wrote — in `supersedes` as much as in a re-run. Block those too.+ for (const { plan } of runs) {+ for (const item of (plan ?? []) as VerifyCheckItem[]) {+ const logicalId = item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);+ if (blocked.has(logicalId)) blocked.add(item.id);+ }+ }// Report the plan item the author has to change, not the internal identity// it collided through — those can differ, and only the former is editable.@@ -748,14 +773,17 @@ export class AcceptanceService {private attachResolvedRun = async (runId: string,acceptance: AcceptanceItem,- ): Promise<VerifyRunItem> => {+ ): Promise<AttachedRun> => {const acceptanceId = acceptance.id;// Idempotent for the re-ingest path (the CLI sidecar remembers the run):// an already-chained round keeps its index instead of being re-appended.const existing = await this.runModel.findById(runId);if (!existing) throw new Error(`Verify run "${runId}" not found in the current workspace`);- if (existing.acceptanceId === acceptanceId) return existing;+ // A retried attach (the response of the first one was lost) still reports+ // the warnings the first one did.+ if (existing.acceptanceId === acceptanceId)+ return this.withUnresolvedSupersedes(existing, acceptanceId);if (existing.acceptanceId) {throw new Error('This verify run already belongs to another acceptance');}@@ -772,6 +800,9 @@ export class AcceptanceService {// Only the newest round counts — `listByAcceptance` is ascending, and an// older draft the chain has moved past is an abandoned ledger position.const latest = (await this.runModel.listByAcceptance(acceptanceId)).at(-1);+ // Resolved against the chain as it stood before this run joined it.+ const withWarnings = (attached: VerifyRunItem): Promise<AttachedRun> =>+ this.withUnresolvedSupersedes(attached, acceptanceId, existing);// A run that already executed cannot fold (`foldIntoRound` refuses any source// with results): its verdicts belong to its own round. It is appended after// the draft instead — the path a verification driven by the CLI takes, since@@ -789,7 +820,7 @@ export class AcceptanceService {folded.roundIndex,acceptanceId,);- return folded;+ return await withWarnings(folded);}// Rounds inherit the aggregate's visibility so a private acceptance's new@@ -803,7 +834,37 @@ export class AcceptanceService {// reviewing".if (latest) this.distilSettledRound(acceptanceId, latest.id);- return run;+ return await withWarnings(run);+ };++ /**+ * Attach `unresolvedSupersedes` — `supersedes` ids of `source`'s plan that+ * name no check of the acceptance — to the run handed back to the caller.+ * The source run itself is excluded from the chain it is resolved against.+ */+ private withUnresolvedSupersedes = async (+ attached: VerifyRunItem,+ acceptanceId: string,+ source: VerifyRunItem = attached,+ ): Promise<AttachedRun> => {+ const plan = (source.plan ?? []) as VerifyCheckItem[];+ if (!plan.some((item) => item.supersedes?.length)) return attached;++ const priorRuns = (await this.runModel.listByAcceptance(acceptanceId)).filter(+ (run) => run.id !== source.id,+ );+ // Results of the earlier rounds and of the source run itself: an executed+ // run may supersede one of its own result-only checks.+ const priorResults = await this.resultModel.listByRuns([+ ...priorRuns.map((run) => run.id),+ source.id,+ ]);+ const unresolvedSupersedes = findUnresolvedSupersedes(+ plan,+ priorRuns,+ priorResults.map((result) => result.checkItemId),+ );+ return unresolvedSupersedes.length ? { ...attached, unresolvedSupersedes } : attached;};/**