🤯 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(goal): unstick goals held by retired prerequisites and unreadable metric gates (#21181)
Arvin Xu3fe83d0cb37e
diff --git a/apps/cli/src/commands/goal/index.ts b/apps/cli/src/commands/goal/index.tsindex 3f797de1c37..fab908400fa 100644--- a/apps/cli/src/commands/goal/index.ts+++ b/apps/cli/src/commands/goal/index.ts@@ -20,6 +20,13 @@ import { confirm, outputJson, printTable, truncate } from '../../utils/format';import { log } from '../../utils/logger';import { resolveAppUrlBuilder } from '../task/url';import { registerGoalGraphEditCommands } from './graphEdit';+import {+ type GoalMetricState,+ printMetricState,+ readMetricState,+ registerGoalMetricCommands,+} from './metric';+import { goalReads, hasOperationToken } from './reads';import { missingSeedDependencies, parseTaskFile } from './seedTasks';// Typed rather than inferred: an `as const` map is indexable by a widened@@ -144,7 +151,7 @@ const isSameWaitingState = (previous: GoalRunTickResult | undefined, current: Goprevious.nodeId === current.nodeId &&previous.taskId === current.taskId;-function printGraph(graph: GoalGraphSnapshot) {+function printGraph(graph: GoalGraphSnapshot, metrics?: GoalMetricState) {const { goal } = graph;console.log(`\n${pc.bold(goal.title)} ${pc.dim(goal.id)} [${goal.status}${@@ -163,6 +170,7 @@ function printGraph(graph: GoalGraphSnapshot) {: 'no planning turn'}${pending > 0 ? pc.yellow(` · ${pending} decision(s) need you`) : ''}`,);+ if (metrics) printMetricState(metrics);const incoming = new Map<string, typeof graph.edges>();for (const edge of graph.edges) {const list = incoming.get(edge.targetNodeId) ?? [];@@ -409,49 +417,6 @@ async function explainPlanRefusal(}}-/**- * Whether this process runs with a server-minted operation token (device and- * gateway runs) rather than the user's own login. Operation tokens are refused- * on ordinary routes, so commands that act for the running conversation pick- * the operation-authenticated endpoint instead.- */-const hasOperationToken = () => {- const injectedJwt = process.env.LOBEHUB_JWT;- if (!injectedJwt) return false;- try {- return (- JSON.parse(Buffer.from(injectedJwt.split('.')[1], 'base64url').toString()).purpose ===- 'hetero-operation'- );- } catch {- return false;- }-};--/**- * The Goal reads `lh goal show` / `state` / `events` use, picked by credential.- *- * A device or gateway planning run holds a `hetero-operation` JWT, and the- * server's ordinary authed routes refuse that by design — so the same reads have- * an operation-authenticated twin. Runs holding one are exactly the runs whose- * refusal these commands exist to explain, so they must not be the ones that- * cannot read.- */-const goalReads = async () => {- const client = await getTrpcClient();- return hasOperationToken()- ? {- events: client.goal.eventsOperation,- graph: client.goal.graphOperation,- planContext: client.goal.planContextOperation,- }- : {- events: client.goal.events,- graph: client.goal.graph,- planContext: client.goal.planContext,- };-};-/*** Builds goal page links. Best-effort: a read must not fail over a link, and an* operation-token run may be refused the workspace lookup behind it.@@ -942,8 +907,10 @@ export function registerGoalCommand(program: Command) {const reads = await goalReads();const result = await reads.graph.query({ id });const url = (await goalUrlBuilder())(result.data.goal.id);- if (options.json !== undefined) return outputJson({ ...result.data, url }, options.json);- printGraph(result.data);+ const metrics = await readMetricState(reads, result.data);+ if (options.json !== undefined)+ return outputJson({ ...result.data, metrics, url }, options.json);+ printGraph(result.data, metrics);if (url) console.log(`${pc.bold('goal')}: ${url}`);};goal@@ -1358,4 +1325,5 @@ export function registerGoalCommand(program: Command) {});registerGoalGraphEditCommands(goal);+ registerGoalMetricCommands(goal);}diff --git a/apps/cli/src/commands/goal/metric.test.ts b/apps/cli/src/commands/goal/metric.test.tsnew file mode 100644index 00000000000..be05810b173--- /dev/null+++ b/apps/cli/src/commands/goal/metric.test.ts@@ -0,0 +1,175 @@+import { Buffer } from 'node:buffer';++import { TRPCClientError } from '@trpc/client';+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../utils/logger';+import { registerGoalCommand } from '.';++const { mockClient } = vi.hoisted(() => ({+ mockClient: {+ goal: {+ graph: { query: vi.fn() },+ graphOperation: { query: vi.fn() },+ metricState: { query: vi.fn() },+ metricStateOperation: { query: vi.fn() },+ recordObservation: { mutate: vi.fn() },+ removeMetricCriteria: { mutate: vi.fn() },+ setMetricCriteria: { mutate: vi.fn() },+ },+ },+}));++vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));+vi.mock('../task/url', () => ({+ resolveAppUrlBuilder: vi+ .fn()+ .mockResolvedValue((pathname: string) => `https://app.lobehub.com${pathname}`),+}));++const run = (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerGoalCommand(program);+ return program.parseAsync(['node', 'test', 'goal', ...args]);+};++const operationToken = () =>+ vi.stubEnv(+ 'LOBEHUB_JWT',+ `header.${Buffer.from(JSON.stringify({ purpose: 'hetero-operation' })).toString('base64url')}.signature`,+ );++const measuredGraph = {+ decisions: [],+ edges: [],+ goal: {+ config: { acceptance: { metrics: [{ key: 'latency_ms', op: 'lte', target: 16.7 }] } },+ id: 'goal-1',+ requirement: null,+ status: 'running',+ title: 'Measured',+ },+ nodes: [],+};++const recordedState = {+ allMet: true,+ criteria: [{ key: 'latency_ms', met: true, op: 'lte', target: 16.7, value: 5 }],+};++describe('goal measured acceptance', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ });+ afterEach(() => {+ vi.unstubAllEnvs();+ vi.mocked(console.log).mockRestore();+ });++ it('shows the value the gate reads, so a recorded clause is not read as unmeasured', async () => {+ // A planner that saw only the declaration reported "no observation" a+ // minute after the owner recorded 5 ms, and kept the goal waiting.+ operationToken();+ mockClient.goal.graphOperation.query.mockResolvedValue({ data: measuredGraph });+ mockClient.goal.metricStateOperation.query.mockResolvedValue({ data: recordedState });++ await run('show', 'goal-1', '--json');++ expect(mockClient.goal.metricStateOperation.query).toHaveBeenCalledWith({ id: 'goal-1' });+ const output = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]));+ expect(output.metrics).toEqual(recordedState);+ });++ it('prints each clause with its reading', async () => {+ mockClient.goal.graph.query.mockResolvedValue({ data: measuredGraph });+ mockClient.goal.metricState.query.mockResolvedValue({+ data: {+ allMet: false,+ criteria: [{ key: 'latency_ms', met: false, op: 'lte', target: 16.7, value: null }],+ },+ });++ await run('show', 'goal-1');++ const printed = vi+ .mocked(console.log)+ .mock.calls.map((call) => String(call[0]))+ .join('\n');+ expect(printed).toContain('latency_ms ≤ 16.7');+ expect(printed).toContain('no observation');+ });++ it('skips the metric read for a goal that declares no clauses', async () => {+ mockClient.goal.graph.query.mockResolvedValue({+ data: { ...measuredGraph, goal: { ...measuredGraph.goal, config: {} } },+ });++ await run('show', 'goal-1', '--json');++ expect(mockClient.goal.metricState.query).not.toHaveBeenCalled();+ });++ it('still shows the goal when the server cannot report metric values', async () => {+ mockClient.goal.graph.query.mockResolvedValue({ data: measuredGraph });+ mockClient.goal.metricState.query.mockRejectedValue(+ new TRPCClientError('No procedure found on path "goal.metricState"', {+ result: { error: { data: { code: 'NOT_FOUND' } } } as never,+ }),+ );++ await run('show', 'goal-1', '--json');++ const output = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]));+ expect(output.goal.id).toBe('goal-1');+ expect(output.metrics).toBeUndefined();+ });++ it('fails the show when the metric read fails for any other reason', async () => {+ // Swallowing an expired login or a server error would print the goal as if+ // nothing were recorded — the unreadable gate this read exists to fix.+ mockClient.goal.graph.query.mockResolvedValue({ data: measuredGraph });+ mockClient.goal.metricState.query.mockRejectedValue(new Error('fetch failed'));++ await expect(run('show', 'goal-1', '--json')).rejects.toThrow('fetch failed');+ });++ it('records, declares and removes clauses with the owner login', async () => {+ vi.spyOn(log, 'info').mockImplementation(() => {});+ mockClient.goal.recordObservation.mutate.mockResolvedValue({ message: 'Observation recorded' });+ mockClient.goal.setMetricCriteria.mutate.mockResolvedValue({ message: 'Updated' });+ mockClient.goal.removeMetricCriteria.mutate.mockResolvedValue({ message: 'Removed' });++ await run('metric', 'record', 'goal-1', 'latency_ms', '5', '--unit', 'ms');+ await run('metric', 'set', 'goal-1', 'latency_ms', '--op', 'lte', '--target', '16.6');+ await run('metric', 'remove', 'goal-1', 'latency_ms');++ expect(mockClient.goal.recordObservation.mutate).toHaveBeenCalledWith({+ id: 'goal-1',+ key: 'latency_ms',+ title: undefined,+ unit: 'ms',+ value: 5,+ });+ expect(mockClient.goal.setMetricCriteria.mutate).toHaveBeenCalledWith({+ id: 'goal-1',+ metrics: [{ key: 'latency_ms', op: 'lte', target: 16.6, title: undefined }],+ mode: 'merge',+ });+ expect(mockClient.goal.removeMetricCriteria.mutate).toHaveBeenCalledWith({+ id: 'goal-1',+ keys: ['latency_ms'],+ });+ });++ it('refuses to let a planning run write the number that clears its own gate', async () => {+ operationToken();++ await expect(run('metric', 'record', 'goal-1', 'latency_ms', '5')).rejects.toThrow(+ 'written by the goal owner',+ );+ expect(mockClient.goal.recordObservation.mutate).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/commands/goal/metric.ts b/apps/cli/src/commands/goal/metric.tsnew file mode 100644index 00000000000..58167a8a3d9--- /dev/null+++ b/apps/cli/src/commands/goal/metric.ts@@ -0,0 +1,146 @@+import type { GoalGraphSnapshot, GoalMetricComparison } from '@lobechat/types';+import { TRPCClientError } from '@trpc/client';+import { type Command, Option } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../api/client';+import { outputJson } from '../../utils/format';+import { log } from '../../utils/logger';+import { type GoalReads, goalReads, hasOperationToken } from './reads';++export interface GoalMetricState {+ allMet: boolean;+ criteria: {+ key: string;+ met: boolean;+ observedAt?: number;+ op: string;+ target: number;+ title?: string;+ value: number | null;+ }[];+}++const comparisons = ['gte', 'lte', 'gt', 'lt', 'eq'] as const satisfies GoalMetricComparison[];++const opSymbol: Record<string, string> = { eq: '=', gt: '>', gte: '≥', lt: '<', lte: '≤' };++/**+ * The measured clauses beside the values the acceptance gate reads, or+ * undefined for a goal that declares none. The graph carries only the+ * declarations, so without this a reader cannot tell a clause nobody measured+ * from one a person already recorded.+ */+export const readMetricState = async (+ reads: GoalReads,+ graph: GoalGraphSnapshot,+): Promise<GoalMetricState | undefined> => {+ if (!graph.goal.config?.acceptance?.metrics?.length) return undefined;+ try {+ return (await reads.metricState.query({ id: graph.goal.id })).data;+ } catch (error) {+ // The CLI ships apart from the server: one without this read must not take+ // `lh goal show` down with it. Any other failure is a real one — a show+ // that silently omits the values would read as "nothing recorded".+ if (isMissingProcedure(error)) return undefined;+ throw error;+ }+};++/** The server predates this read: tRPC answers an unknown path with NOT_FOUND. */+const isMissingProcedure = (error: unknown) =>+ error instanceof TRPCClientError &&+ error.data?.code === 'NOT_FOUND' &&+ error.message.includes('No procedure found');++export const describeMetric = (criterion: GoalMetricState['criteria'][number]) => {+ const reading =+ criterion.value === null+ ? pc.yellow('no observation')+ : `${criterion.value}${criterion.met ? pc.green(' (met)') : pc.yellow(' (not met)')}`;+ const name = criterion.title ? `${criterion.key} ${pc.dim(criterion.title)}` : criterion.key;+ return `${name} ${opSymbol[criterion.op] ?? criterion.op} ${criterion.target}: ${reading}`;+};++export const printMetricState = (state: GoalMetricState) => {+ console.log(pc.dim('Measured acceptance:'));+ for (const criterion of state.criteria) console.log(` ${describeMetric(criterion)}`);+};++/**+ * Writes go through the owner's login only. A planning run holding an+ * operation token must not record the number that clears its own gate.+ */+const ownerClient = async () => {+ if (hasOperationToken())+ throw new Error(+ 'Measured acceptance is written by the goal owner. Ask the owner to record or remove it on the goal page, or with their own `lh goal metric` login.',+ );+ return getTrpcClient();+};++/** Measured acceptance: numeric clauses the goal is only achieved once they hold. */+export function registerGoalMetricCommands(goal: Command) {+ const metric = goal+ .command('metric')+ .description('Measured acceptance: list, record, declare or remove numeric clauses');++ metric+ .command('list <id>')+ .description('Show each measured clause with the latest observation the gate reads')+ .option('--json [fields]', 'Output JSON')+ .action(async (id: string, options: { json?: boolean | string }) => {+ const { data } = await (await goalReads()).metricState.query({ id });+ if (options.json !== undefined) return outputJson(data, options.json);+ if (data.criteria.length === 0) return log.info('This goal declares no measured clauses.');+ printMetricState(data);+ });++ metric+ .command('record <id> <key> <value>')+ .description('Record an observation for a measured clause')+ .option('--title <text>', 'Human-facing series name')+ .option('--unit <unit>', 'Unit of the value, e.g. ms')+ .action(async (id: string, key: string, raw: string, options) => {+ const value = Number(raw);+ if (!Number.isFinite(value)) throw new Error(`<value> must be a number; got ${raw}`);+ const result = await (+ await ownerClient()+ ).goal.recordObservation.mutate({ id, key, title: options.title, unit: options.unit, value });+ log.info(`${result.message}: ${key} = ${value}`);+ });++ metric+ .command('set <id> <key>')+ .description('Declare or update one measured clause; other clauses are kept')+ .requiredOption('--target <n>', 'Threshold the latest observation is compared with')+ .addOption(new Option('--op <op>', 'Comparison').choices(comparisons).default('gte'))+ .option('--title <text>', 'Human-facing name')+ .action(+ async (+ id: string,+ key: string,+ options: { op: GoalMetricComparison; target: string; title?: string },+ ) => {+ const target = Number(options.target);+ if (!Number.isFinite(target))+ throw new Error(`--target must be a number; got ${options.target}`);+ const result = await (+ await ownerClient()+ ).goal.setMetricCriteria.mutate({+ id,+ metrics: [{ key, op: options.op, target, title: options.title }],+ mode: 'merge',+ });+ log.info(`${result.message}: ${key} ${opSymbol[options.op]} ${target}`);+ },+ );++ metric+ .command('remove <id> <keys...>')+ .description('Remove measured clauses so they no longer gate acceptance')+ .action(async (id: string, keys: string[]) => {+ const result = await (await ownerClient()).goal.removeMetricCriteria.mutate({ id, keys });+ log.info(`${result.message}: ${keys.join(', ')}`);+ });+}diff --git a/apps/cli/src/commands/goal/reads.ts b/apps/cli/src/commands/goal/reads.tsnew file mode 100644index 00000000000..799037568b7--- /dev/null+++ b/apps/cli/src/commands/goal/reads.ts@@ -0,0 +1,49 @@+import { getTrpcClient } from '../../api/client';++/**+ * Whether this process runs with a server-minted operation token (device and+ * gateway runs) rather than the user's own login. Operation tokens are refused+ * on ordinary routes, so commands that act for the running conversation pick+ * the operation-authenticated endpoint instead.+ */+export const hasOperationToken = () => {+ const injectedJwt = process.env.LOBEHUB_JWT;+ if (!injectedJwt) return false;+ try {+ return (+ JSON.parse(Buffer.from(injectedJwt.split('.')[1], 'base64url').toString()).purpose ===+ 'hetero-operation'+ );+ } catch {+ return false;+ }+};++/**+ * The Goal reads `lh goal show` / `state` / `events` / `metric list` use,+ * picked by credential.+ *+ * A device or gateway planning run holds a `hetero-operation` JWT, and the+ * server's ordinary authed routes refuse that by design — so the same reads have+ * an operation-authenticated twin. Runs holding one are exactly the runs whose+ * refusal these commands exist to explain, so they must not be the ones that+ * cannot read.+ */+export const goalReads = async () => {+ const client = await getTrpcClient();+ return hasOperationToken()+ ? {+ events: client.goal.eventsOperation,+ graph: client.goal.graphOperation,+ metricState: client.goal.metricStateOperation,+ planContext: client.goal.planContextOperation,+ }+ : {+ events: client.goal.events,+ graph: client.goal.graph,+ metricState: client.goal.metricState,+ planContext: client.goal.planContext,+ };+};++export type GoalReads = Awaited<ReturnType<typeof goalReads>>;diff --git a/apps/server/src/routers/lambda/goal/configuration.ts b/apps/server/src/routers/lambda/goal/configuration.tsindex 774436d0b76..1bfd72e7c56 100644--- a/apps/server/src/routers/lambda/goal/configuration.ts+++ b/apps/server/src/routers/lambda/goal/configuration.ts@@ -45,6 +45,27 @@ export const configurationRouter = router({mapGoalError(error, 'setMetricCriteria');}}),+ /** Drop declared clauses by key, against the server's current list. */+ removeMetricCriteria: goalWriteProcedure+ .input(idInput.extend({ keys: z.array(z.string().min(1).max(255)).min(1) }))+ .mutation(async ({ ctx, input }) => {+ try {+ const goal = await ctx.goalModel.findById(input.id);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');+ const data = await ctx.goalService.removeMetricCriteria(input.id, input.keys);+ // Dropping the last unmet clause frees a goal parked short of acceptance.+ await scheduleGoalAdvance({+ goalId: input.id,+ trigger: 'observe',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ return { data, message: 'Metric criteria removed', success: true };+ } catch (error) {+ mapGoalError(error, 'removeMetricCriteria');+ }+ }),/*** Record a measurement against this goal and let the coordinator react.*diff --git a/apps/server/src/routers/lambda/goal/index.procedures.test.ts b/apps/server/src/routers/lambda/goal/index.procedures.test.tsindex dbafccd2f78..627ead52414 100644--- a/apps/server/src/routers/lambda/goal/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/goal/index.procedures.test.ts@@ -41,6 +41,8 @@ function expected(): Array<['graph', 'query', 12],['graphOperation', 'query', 9],['list', 'query', 12],+ ['metricState', 'query', 12],+ ['metricStateOperation', 'query', 9],['pause', 'mutation', 13],['pendingClarifications', 'query', 11],['pendingForIsland', 'query', 11],@@ -48,6 +50,7 @@ function expected(): Array<['planContextOperation', 'query', 9],['recordObservation', 'mutation', 13],['removeEdge', 'mutation', 13],+ ['removeMetricCriteria', 'mutation', 13],['restart', 'mutation', 13],['resume', 'mutation', 13],['retireNodes', 'mutation', 13],diff --git a/apps/server/src/routers/lambda/goal/reads.ts b/apps/server/src/routers/lambda/goal/reads.tsindex 7301e5b5dff..20446a72f65 100644--- a/apps/server/src/routers/lambda/goal/reads.ts+++ b/apps/server/src/routers/lambda/goal/reads.ts@@ -185,6 +185,17 @@ export const readRouter = router({mapGoalError(error, 'graph');}}),+ /**+ * Each declared measured clause with the value the acceptance gate reads for+ * it now. `lh goal show` / `lh goal metric list` render it.+ */+ metricState: goalProcedure.input(idInput).query(async ({ ctx, input }) => {+ try {+ return { data: await ctx.goalService.metricState(input.id), success: true };+ } catch (error) {+ mapGoalError(error, 'read the metrics of');+ }+ }),/*** Why `submitPlan` would accept or refuse a plan right now, without writing.*@@ -216,7 +227,7 @@ export const readRouter = router({}}),- // The same three reads for a planning run that holds an operation token, which+ // The same reads for a planning run that holds an operation token, which// the ordinary `goalProcedure` above refuses — see `goalOperationReadProcedure`.graphOperation: goalOperationReadProcedure.input(idInput).query(async ({ ctx, input }) => {try {@@ -226,6 +237,14 @@ export const readRouter = router({mapGoalError(error, 'graph');}}),+ metricStateOperation: goalOperationReadProcedure.input(idInput).query(async ({ ctx, input }) => {+ try {+ await ctx.goalManager.assertOperationOwnsTurn(input.id, ctx.heteroOperationId);+ return { data: await ctx.goalService.metricState(input.id), success: true };+ } catch (error) {+ mapGoalError(error, 'read the metrics of');+ }+ }),planContextOperation: goalOperationReadProcedure.input(planContextInput).query(async ({ ctx, input }) => {diff --git a/apps/server/src/services/goal/GoalService/__tests__/measurement.test.ts b/apps/server/src/services/goal/GoalService/__tests__/measurement.test.tsindex f4886fa5bd3..1553a0630a8 100644--- a/apps/server/src/services/goal/GoalService/__tests__/measurement.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/measurement.test.ts@@ -317,4 +317,69 @@ describe('GoalService', () => {criteria: [{ key: 'churn', met: false, op: 'lte', target: 5, value: 9 }],});});++ it('reports each clause with the value the gate reads, before the terminal phase', async () => {+ // The graph carries only declarations: without this read a planning Agent+ // could not tell an unmeasured clause from one a person already recorded.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: {+ acceptance: {+ metrics: [+ { key: 'latency_ms', op: 'lte', target: 16.7, title: 'Input latency' },+ { key: 'accuracy', target: 99 },+ ],+ },+ },+ tasks: ['Measure'],+ title: 'Metric state',+ });+ await service.recordObservation(graph.goal.id, { key: 'latency_ms', value: 5 });++ expect(await service.metricState(graph.goal.id)).toMatchObject({+ allMet: false,+ criteria: [+ { key: 'latency_ms', met: true, title: 'Input latency', value: 5 },+ { key: 'accuracy', met: false, value: null },+ ],+ });+ });++ it('removes a clause by key and reopens a goal it alone was parking', async () => {+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const goalId = await parkedOnGate(service);+ await service.setMetricCriteria(goalId, [{ key: 'churn', op: 'lte', target: 5 }], 'merge');++ await service.removeMetricCriteria(goalId, ['followers']);+ const kept = await goalModel.findById(goalId);+ expect(kept?.config?.acceptance?.metrics).toEqual([{ key: 'churn', op: 'lte', target: 5 }]);+ expect(kept?.status).toBe('paused');++ await service.removeMetricCriteria(goalId, ['churn']);+ const cleared = await goalModel.findById(goalId);+ expect(cleared?.config?.acceptance?.metrics).toBeUndefined();+ expect(cleared?.status).toBe('running');+ });++ it('applies concurrent clause edits one after the other', async () => {+ // Both edits read the list before either wrote it: one removing "followers"+ // and one declaring "churn" must end as just "churn", never resurrecting+ // the removed clause or losing the new one.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },+ tasks: ['Grow'],+ title: 'Concurrent clause edits',+ });++ await Promise.all([+ service.removeMetricCriteria(graph.goal.id, ['followers']),+ service.setMetricCriteria(graph.goal.id, [{ key: 'churn', op: 'lte', target: 5 }], 'merge'),+ ]);++ const goal = await new GoalModel(serverDB, userId).findById(graph.goal.id);+ expect(goal?.config?.acceptance?.metrics).toEqual([{ key: 'churn', op: 'lte', target: 5 }]);+ });});diff --git a/apps/server/src/services/goal/GoalService/__tests__/recovery.test.ts b/apps/server/src/services/goal/GoalService/__tests__/recovery.test.tsindex 46f2a851cf8..f60808a5d23 100644--- a/apps/server/src/services/goal/GoalService/__tests__/recovery.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/recovery.test.ts@@ -5,9 +5,10 @@ import { describe, expect, it, vi } from 'vitest';import { getTestDB } from '@/database/core/getTestDB';import { AgentOperationModel } from '@/database/models/agentOperation';import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';-import { agentOperations, tasks } from '@/database/schemas';+import { agentOperations, goalNodes, tasks } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';@@ -42,6 +43,112 @@ describe('GoalService', () => {expect(achieved.outcome).toBe('achieved');});+ it('retiring a failed task from its gate retires the tasks that depend on it', async () => {+ // A prerequisite only counts as met once `resolved`, so a gate that+ // retired just the failed node left its dependent blocked forever and+ // the goal paused on `no eligible task to advance`.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ tasks: ['Measure latency', 'Write summary', 'Unrelated'],+ title: 'Gate retire cascade',+ });+ const [measure, summary, unrelated] = ['Measure latency', 'Write summary', 'Unrelated'].map(+ (title) => graph.nodes.find((node) => node.kind === 'task' && node.title === title)!,+ );+ await service.addEdge(graph.goal.id, summary.id, measure.id, 'depends_on');+ await serverDB.update(goalNodes).set({ priority: 10 }).where(eq(goalNodes.id, measure.id));++ const created = await service.tick(graph.goal.id);+ expect(created.nodeId).toBe(measure.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Attempt budget exhausted' });+ await service.tick(graph.goal.id);++ const gated = await service.graph(graph.goal.id);+ const retire = gated.decisions[0].options?.find((option) => option.id === 'retire');+ expect(retire?.alsoRetires).toEqual([{ nodeId: summary.id, title: 'Write summary' }]);+ // Coordinator options carry ids and data only; the client words them.+ expect(retire?.description).toBeUndefined();++ await service.decide(graph.goal.id, gated.decisions[0].id, 'retire');++ const after = await service.graph(graph.goal.id);+ const status = (id: string) => after.nodes.find((node) => node.id === id)?.status;+ expect(status(measure.id)).toBe('retired');+ expect(status(summary.id)).toBe('retired');+ expect(status(unrelated.id)).not.toBe('retired');++ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const next = await service.tick(graph.goal.id);+ expect(next.nodeId).toBe(unrelated.id);+ expect((await service.graph(graph.goal.id)).goal.status).not.toBe('paused');+ });++ /** A goal whose failed "Measure" task gates "Summary", parked on its recovery gate. */+ const gatedWithDependent = async (title: string) => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Measure', 'Summary', 'Other'], title });+ const [measure, summary, other] = ['Measure', 'Summary', 'Other'].map((name) =>+ graph.nodes.find((node) => node.kind === 'task' && node.title === name)!,+ );+ await service.addEdge(graph.goal.id, summary.id, measure.id, 'depends_on');+ await serverDB.update(goalNodes).set({ priority: 10 }).where(eq(goalNodes.id, measure.id));+ const created = await service.tick(graph.goal.id);+ await new TaskModel(serverDB, userId).updateStatus(created.taskId!, 'paused', {+ error: 'Attempt budget exhausted',+ });+ await service.tick(graph.goal.id);+ const decision = (await service.graph(graph.goal.id)).decisions[0];+ return { decision, goalId: graph.goal.id, measure, other, service, summary };+ };++ it('asks again instead of retiring a dependent added after the gate was shown', async () => {+ // The Retire button named one dependent; a second one appearing while the+ // gate waited must not be canceled on an answer that never mentioned it.+ const { decision, goalId, measure, other, service, summary } =+ await gatedWithDependent('Cascade drift');+ await service.addEdge(goalId, other.id, measure.id, 'depends_on');++ await expect(service.decide(goalId, decision.id, 'retire')).rejects.toThrow(+ 'review the updated choice',+ );+ const asked = await service.graph(goalId);+ expect(asked.decisions[0].status).toBe('pending');+ expect(asked.nodes.find((node) => node.id === other.id)?.status).not.toBe('retired');+ const retire = asked.decisions[0].options?.find((option) => option.id === 'retire');+ expect(retire?.alsoRetires?.map((item) => item.nodeId).sort()).toEqual(+ [summary.id, other.id].sort(),+ );++ await service.decide(goalId, decision.id, 'retire');+ const after = await service.graph(goalId);+ expect(after.nodes.find((node) => node.id === other.id)?.status).toBe('retired');+ expect(after.nodes.find((node) => node.id === summary.id)?.status).toBe('retired');+ });++ it('lists the cascade on a retire option the main Agent wrote before applying it', async () => {+ const { decision, goalId, service, summary } = await gatedWithDependent('Agent retire');+ await new GoalGraphModel(serverDB, userId).updatePendingDecisionOptions(goalId, decision.id, [+ { id: 'measure_again', label: 'Measure again', effect: 'retry' },+ { description: 'Skip the measurement', effect: 'retire', id: 'skip', label: 'Skip it' },+ ]);++ await expect(service.decide(goalId, decision.id, 'skip')).rejects.toThrow(+ 'review the updated choice',+ );+ const asked = await service.graph(goalId);+ expect(asked.nodes.find((node) => node.id === summary.id)?.status).not.toBe('retired');+ expect(asked.decisions[0].options?.find((option) => option.id === 'skip')).toMatchObject({+ alsoRetires: [{ nodeId: summary.id, title: 'Summary' }],+ description: 'Skip the measurement',+ });++ await service.decide(goalId, decision.id, 'skip');+ expect((await service.graph(goalId)).nodes.find((node) => node.id === summary.id)?.status).toBe(+ 'retired',+ );+ });+it('reports the effects a tick actually produced, not just its outcome', async () => {// The rollup counts gates and findings from these effects, so a branch that// forgets to report one reads as "no human was ever involved" — silently,diff --git a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts b/apps/server/src/services/goal/GoalService/__tests__/surface.test.tsindex cace3cdbd60..44931d82640 100644--- a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts@@ -73,6 +73,7 @@ const METHODS = ['isParkedOnMeasuredGate','listEvents','markRunLostToOfflineDevice',+ 'metricState','openFailureDecision','openFailureDecisionLocked','openPatternBreakGate',@@ -87,6 +88,7 @@ const METHODS = ['recoverAbandonedTask','recoverAfterVerification','recoverLostRun',+ 'removeMetricCriteria','reopenForChanges','reopenIfMeasurementCleared','requestSignOff',diff --git a/apps/server/src/services/goal/GoalService/decisions.ts b/apps/server/src/services/goal/GoalService/decisions.tsindex 9c6e818988a..4d7f5ca9519 100644--- a/apps/server/src/services/goal/GoalService/decisions.ts+++ b/apps/server/src/services/goal/GoalService/decisions.ts@@ -8,6 +8,7 @@ import {} from '@lobechat/const/goal';import type {GoalDecisionOption,+ GoalGraphNode,GoalGraphSnapshot,GoalManagerAsk,GoalTickResult,@@ -19,7 +20,7 @@ import { GoalModel } from '@/database/models/goal';import { GoalGraphModel } from '@/database/models/goalGraph';import { TaskModel } from '@/database/models/task';-import { GOAL_ACCEPTANCE_TASK_TITLE } from '../decideNextMove';+import { collectStrandedDependents, GOAL_ACCEPTANCE_TASK_TITLE } from '../decideNextMove';import { answeredProblem, GoalManagerService, problemKey } from '../manager';import { GoalSupervisorService } from '../supervisor';import type { GoalServiceContext } from './types';@@ -45,6 +46,30 @@ const decisionOptionEffect = (return undefined;};+/**+ * Put on every option that retires the task what it would take along: the+ * unfinished tasks that wait on it. The Retire button says so, and an option+ * the main Agent wrote for its own question carries it the same way.+ */+const withRetireCascade = (+ options: GoalDecisionOption[],+ sourceTitle: string | undefined,+ stranded: GoalGraphNode[],+): GoalDecisionOption[] =>+ options.map((option) => {+ if (decisionOptionEffect(option, sourceTitle) !== 'retire') return option;+ const { alsoRetires: _previous, ...rest } = option;+ return stranded.length > 0+ ? { ...rest, alsoRetires: stranded.map((node) => ({ nodeId: node.id, title: node.title })) }+ : rest;+ });++/** Whether the person was shown exactly the tasks this retire would take along. */+const confirmedCascade = (option: GoalDecisionOption | undefined, stranded: GoalGraphNode[]) => {+ const confirmed = new Set(option?.alsoRetires?.map((item) => item.nodeId) ?? []);+ return confirmed.size === stranded.length && stranded.every((node) => confirmed.has(node.id));+};+/*** The comment a retried Task carries into its next attempt. A bare "retry"* adds nothing the run does not already know; a chosen direction or a note is@@ -128,6 +153,31 @@ export const decide = async (});}const chosen = decision.options?.find((option) => option.id === optionId);+ const incoming = graph.edges.find(+ (edge) => edge.targetNodeId === decision.nodeId && edge.kind === 'leads_to',+ );+ const source = incoming && graph.nodes.find((node) => node.id === incoming.sourceNodeId);+ // Retiring takes the unfinished dependents along, so the answer only stands+ // for the set the person was shown. A dependent added while the gate waited,+ // or an option that never listed them, gets the gate rewritten and asked+ // again instead of quietly canceling work nobody confirmed.+ const stranded =+ source?.kind === 'task' &&+ source.title !== GOAL_ACCEPTANCE_TASK_TITLE &&+ decisionOptionEffect(chosen, source.title) === 'retire'+ ? collectStrandedDependents(graph, [source.id])+ : [];+ if (stranded.length > 0 && !confirmedCascade(chosen, stranded)) {+ await ctx.graphModel.updatePendingDecisionOptions(+ goalId,+ decisionId,+ withRetireCascade(decision.options ?? [], source?.title, stranded),+ );+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'The tasks this retire would take along changed; review the updated choice',+ });+ }// R5: a person answering a batch gate IS the intervention, and an// intervention rolls the class back to canary. Open the next recipe round// automatically — revise the same mould, or fork it as a new class — rather@@ -161,10 +211,6 @@ export const decide = async (if (!resolved)throw new TRPCError({ code: 'CONFLICT', message: 'Decision was already resolved' });- const incoming = graph.edges.find(- (edge) => edge.targetNodeId === decision.nodeId && edge.kind === 'leads_to',- );- const source = incoming && graph.nodes.find((node) => node.id === incoming.sourceNodeId);if (source?.kind === 'task') {if (source.taskId)await new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).recordProgress(@@ -189,6 +235,19 @@ export const decide = async (});} else if (effect === 'retire') {await ctx.graphModel.updateNodeStatus(goalId, source.id, 'retired', resolution);+ // Same rule `retireNodes` enforces: whatever still waits on the retired+ // node leaves with it, or it would block the goal on a prerequisite+ // that can no longer resolve. This is the set confirmed above.+ for (const node of stranded) {+ await ctx.graphModel.updateNodeStatus(+ goalId,+ node.id,+ 'retired',+ `Retired with its prerequisite "${source.title}"`,+ );+ }+ if (stranded.length > 0)+ await ctx.stopFencedTasks(goalId, new Set(stranded.map((node) => node.id)));}}// Ending the terminal acceptance ends the Goal: `fail` is a verdict that@@ -415,6 +474,15 @@ export const openFailureDecisionLocked = async (// Goal is a verdict even when a machine problem is what stopped it.const machine = !!gate.machine && !terminalAcceptance;const { ask } = gate;+ // Retiring this node retires what waits on it too. The tasks travel as+ // data so the page can say so in the reader's language.+ const source = graph.nodes.find((candidate) => candidate.id === nodeId);+ const stranded = terminalAcceptance ? [] : collectStrandedDependents(graph, [nodeId]);+ const retireTask = withRetireCascade(+ [{ id: 'retire', label: 'Retire task' }],+ source?.title,+ stranded,+ )[0];const node = await ctx.coordinatorGraph.createNode(graph.goal.id, {// What the gate stands on: the main Agent's diagnosis when it asked,// else the coordinator's own reason for stopping.@@ -433,7 +501,7 @@ export const openFailureDecisionLocked = async (ask? {authority: 'user',- options: ask.options,+ options: withRetireCascade(ask.options, source?.title, stranded),question: ask.question,recommendedOptionId: ask.recommendedOptionId,requestedUserId: ctx.userId,@@ -441,10 +509,7 @@ export const openFailureDecisionLocked = async (: {authority: 'user',options: machine- ? [- { id: 'retry', label: 'I fixed it — retry' },- { id: 'retire', label: 'Retire task' },- ]+ ? [{ id: 'retry', label: 'I fixed it — retry' }, retireTask]: terminalAcceptance? [{ id: 'retry', label: 'Retry goal acceptance' },@@ -453,10 +518,7 @@ export const openFailureDecisionLocked = async ({ id: 'retire', label: 'Abandon goal acceptance' },{ id: 'fail', label: 'Fail goal' },]- : [- { id: 'retry', label: 'Retry task' },- { id: 'retire', label: 'Retire task' },- ],+ : [{ id: 'retry', label: 'Retry task' }, retireTask],question: machine? `${reason}. Fix it, then retry or retire this task node?`: terminalAcceptancediff --git a/apps/server/src/services/goal/GoalService/index.ts b/apps/server/src/services/goal/GoalService/index.tsindex 52ed6d44a75..679cc0dc80c 100644--- a/apps/server/src/services/goal/GoalService/index.ts+++ b/apps/server/src/services/goal/GoalService/index.ts@@ -62,7 +62,9 @@ import {evaluateBudget,evaluateMetricCriteria,isParkedOnMeasuredGate,+ metricState,recordObservation,+ removeMetricCriteria,reopenIfMeasurementCleared,resolveSpend,setAcceptanceCriteria,@@ -323,6 +325,11 @@ export class GoalService {setMetricCriteria = (...args: MethodArgs<typeof setMetricCriteria>) =>setMetricCriteria(this.context, ...args);+ removeMetricCriteria = (...args: MethodArgs<typeof removeMetricCriteria>) =>+ removeMetricCriteria(this.context, ...args);++ metricState = (...args: MethodArgs<typeof metricState>) => metricState(this.context, ...args);+setAcceptanceCriteria = (...args: MethodArgs<typeof setAcceptanceCriteria>) =>setAcceptanceCriteria(this.context, ...args);diff --git a/apps/server/src/services/goal/GoalService/measurement.ts b/apps/server/src/services/goal/GoalService/measurement.tsindex 364c19f84c0..771baadf128 100644--- a/apps/server/src/services/goal/GoalService/measurement.ts+++ b/apps/server/src/services/goal/GoalService/measurement.ts@@ -8,6 +8,7 @@ import type {} from '@lobechat/types';import { TRPCError } from '@trpc/server';+import { GoalModel } from '@/database/models/goal';import { MetricModel } from '@/database/models/metric';import {@@ -204,30 +205,79 @@ export const setMetricCriteria = async (* concurrent editor or agent declared since that snapshot was read.*/mode: 'merge' | 'replace' = 'replace',+) =>+ updateMetricCriteria(ctx, goalId, (current) =>+ mode === 'merge'+ ? [...current.filter((item) => !metrics.some((m) => m.key === item.key)), ...metrics]+ : metrics,+ );++/**+ * Drop clauses by key, against the list as it stands on the server — for the+ * same reason `merge` exists: a client filtering its own snapshot would put+ * back whatever was removed or declared since it read.+ */+export const removeMetricCriteria = async (+ ctx: GoalServiceContext,+ goalId: string,+ keys: string[],+) =>+ updateMetricCriteria(ctx, goalId, (current) =>+ current.filter((item) => !keys.includes(item.key)),+ );++const updateMetricCriteria = async (+ ctx: GoalServiceContext,+ goalId: string,+ edit: (current: GoalMetricCriterion[]) => GoalMetricCriterion[],) => {const before = await ctx.coordinatorGraph.getGraph(goalId);if (!before) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });const parkedOnGate = ctx.isParkedOnMeasuredGate(before);- const goal = before.goal;- const current = goal.config?.acceptance?.metrics ?? [];- const next =- mode === 'merge'- ? [...current.filter((item) => !metrics.some((m) => m.key === item.key)), ...metrics]- : metrics;- await ctx.goalModel.update(goalId, {- config: {- ...goal.config,- acceptance: {- ...goal.config?.acceptance,- metrics: next.length > 0 ? next : undefined,+ // Read and write the list under the goal's row lock: two editors deriving+ // their list from the same snapshot would otherwise race, resurrecting a+ // removed clause or dropping a newly declared one.+ await ctx.db.transaction(async (tx) => {+ const model = new GoalModel(tx, ctx.userId, ctx.workspaceId);+ const goal = await model.lockById(goalId);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ const next = edit(goal.config?.acceptance?.metrics ?? []);+ await model.update(goalId, {+ config: {+ ...goal.config,+ acceptance: {+ ...goal.config?.acceptance,+ metrics: next.length > 0 ? next : undefined,+ },},- },+ });});// Relaxing or dropping a clause can clear a gate the goal is parked on.await ctx.reopenIfMeasurementCleared(goalId, parkedOnGate);return ctx.graph(goalId);};+/**+ * Every declared clause beside the value the gate would read for it right now.+ *+ * The graph carries only the declarations, so a reader of it — a planning+ * Agent above all — could not tell a clause nobody measured from one already+ * met, and kept resubmitting verification against a gate that had cleared.+ */+export const metricState = async (ctx: GoalServiceContext, goalId: string) => {+ const graph = await ctx.requireGraph(goalId);+ const declared = graph.goal.config?.acceptance?.metrics ?? [];+ if (declared.length === 0) return { allMet: true, criteria: [] };+ const state = await ctx.evaluateMetricCriteria(graph);+ return {+ allMet: state.allMet,+ criteria: state.criteria.map((criterion) => ({+ ...criterion,+ title: declared.find((item) => item.key === criterion.key)?.title,+ })),+ };+};+export const setAcceptanceCriteria = async (ctx: GoalServiceContext,goalId: string,diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.tsindex 9b4010ed479..01430bf4825 100644--- a/apps/server/src/services/goal/decideNextMove.ts+++ b/apps/server/src/services/goal/decideNextMove.ts@@ -65,6 +65,40 @@ export interface FrontierSelection {* before deciding, and exported so a trace keeps the whole ranking rather than* only the winner — "why not that node" is unanswerable from the winner alone.*/+/**+ * Every unfinished Task that would wait forever once `rootIds` stop short of+ * `resolved` — directly or through another such Task. A prerequisite only+ * counts as met when it resolves, so these have to leave with the roots or+ * the goal parks on `no_frontier`. The Goal acceptance is never among them:+ * ending it ends the Goal, which belongs to its own gate.+ */+export const collectStrandedDependents = (+ graph: GoalGraphSnapshot,+ rootIds: Iterable<string>,+): GoalGraphNode[] => {+ const closed = new Set(rootIds);+ const stranded: GoalGraphNode[] = [];+ for (let grew = true; grew;) {+ grew = false;+ for (const edge of graph.edges) {+ if (edge.kind !== 'depends_on' || !closed.has(edge.targetNodeId)) continue;+ if (closed.has(edge.sourceNodeId)) continue;+ const node = graph.nodes.find((candidate) => candidate.id === edge.sourceNodeId);+ if (+ !node ||+ node.kind !== 'task' ||+ node.title === GOAL_ACCEPTANCE_TASK_TITLE ||+ TERMINAL_NODE_STATUSES.has(node.status)+ )+ continue;+ closed.add(node.id);+ stranded.push(node);+ grew = true;+ }+ }+ return stranded;+};+export const selectFrontier = (graph: GoalGraphSnapshot): FrontierSelection => {const resolvedNodeIds = new Set(graph.nodes.filter((node) => node.status === 'resolved').map((node) => node.id),diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex c82e09d08b0..954ed81d45d 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -764,11 +764,14 @@"goalProcess.decision.context.decision": "Your call","goalProcess.decision.context.task": "Task","goalProcess.decision.effect.abandonAcceptance": "Stop acceptance and end the goal without a verdict.",+ "goalProcess.decision.effect.alsoRetires": "Also drops the tasks that depend on it: {{tasks}}.","goalProcess.decision.effect.fail": "End the goal and record it as failed.","goalProcess.decision.effect.fixedRetry": "Run the task again once the setup is fixed.","goalProcess.decision.effect.newClassBatch": "Fork a fresh recipe for the units that broke; the rest of the batch continues once the new gate passes.",+ "goalProcess.decision.effect.quotedTask": "\"{{title}}\"","goalProcess.decision.effect.releaseBatch": "Release the next wave on the current recipe. Each later wave goes to the main Agent, which releases it or brings it back to you.","goalProcess.decision.effect.retire": "Drop this task. The goal moves on without it.",+ "goalProcess.decision.effect.retireWithDependents": "Drop this task and the tasks that depend on it ({{tasks}}). The goal moves on without them.","goalProcess.decision.effect.retry": "Send the task back for another attempt. Your note is written into its instructions.","goalProcess.decision.effect.retryAcceptance": "Run the goal-level acceptance again.","goalProcess.decision.effect.reviseBatch": "Write a correction to the recipe, then re-probe this batch under it.",@@ -1001,6 +1004,9 @@"goalProcess.northStar.record.submit": "Record","goalProcess.northStar.record.title": "Record observation","goalProcess.northStar.record.valueLabel": "Current value of {{key}}",+ "goalProcess.northStar.remove.confirm": "Remove \"{{name}}\"? It will no longer gate this goal's acceptance. Recorded observations are kept.",+ "goalProcess.northStar.remove.failed": "Failed to remove the metric",+ "goalProcess.northStar.remove.title": "Remove metric","goalProcess.northStar.staleWarning": "data may be outdated","goalProcess.northStar.unmeasured": "Never measured — the clause counts as unmet until a value lands","goalProcess.pause": "Pause",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex bd63d45a2be..eb4459d0930 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -764,11 +764,14 @@"goalProcess.decision.context.decision": "需要你决定","goalProcess.decision.context.task": "任务","goalProcess.decision.effect.abandonAcceptance": "停止验收,目标结束但不下结论",+ "goalProcess.decision.effect.alsoRetires": "依赖它的{{tasks}}也会一起放弃。","goalProcess.decision.effect.fail": "结束目标,记为未达成","goalProcess.decision.effect.fixedRetry": "确认环境修好后重新执行这项任务","goalProcess.decision.effect.newClassBatch": "为失败的单元另起一份配方;新闸门通过后,这一批的其余单元继续推进",+ "goalProcess.decision.effect.quotedTask": "「{{title}}」","goalProcess.decision.effect.releaseBatch": "按当前配方放出下一批。之后每一批交给主 Agent 决定放行,或再交回给你确认。","goalProcess.decision.effect.retire": "放弃这项任务,目标在没有它的情况下继续推进",+ "goalProcess.decision.effect.retireWithDependents": "放弃这项任务,依赖它的{{tasks}}也会一起放弃,目标在没有它们的情况下继续推进","goalProcess.decision.effect.retry": "把任务退回重做,补充说明会写进下一次执行的指令","goalProcess.decision.effect.retryAcceptance": "重新跑一次目标验收","goalProcess.decision.effect.reviseBatch": "写下对配方的修正,然后按修订后的配方重探这一批",@@ -1001,6 +1004,9 @@"goalProcess.northStar.record.submit": "记录","goalProcess.northStar.record.title": "记录观测","goalProcess.northStar.record.valueLabel": "{{key}} 的当前值",+ "goalProcess.northStar.remove.confirm": "移除「{{name}}」?移除后它不再作为这个目标的验收条件,已录入的观测值会保留。",+ "goalProcess.northStar.remove.failed": "移除指标失败",+ "goalProcess.northStar.remove.title": "移除指标","goalProcess.northStar.staleWarning": "数据可能已过期","goalProcess.northStar.unmeasured": "尚未测量——在第一个观测值到来前按未达标处理","goalProcess.pause": "暂停",diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex 8155db88a11..ffc9c95a074 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -971,6 +971,41 @@ export class GoalGraphModel {return decision;});+ /**+ * Rewrite the options of a still-pending decision, for when what an answer+ * would do changed after the question was asked. A settled decision keeps+ * the options it was answered against.+ */+ updatePendingDecisionOptions = async (+ goalId: string,+ decisionId: string,+ options: GoalDecisionOption[],+ ) =>+ this.db.transaction(async (tx) => {+ if (!(await this.ownedGoal(goalId, tx))) return undefined;+ const [ownedDecision] = await tx+ .select({ id: goalNodeDecisions.id })+ .from(goalNodeDecisions)+ .innerJoin(goalNodes, eq(goalNodeDecisions.nodeId, goalNodes.id))+ .where(+ and(+ eq(goalNodeDecisions.id, decisionId),+ eq(goalNodeDecisions.status, 'pending'),+ eq(goalNodes.goalId, goalId),+ ),+ )+ .limit(1);+ if (!ownedDecision) return undefined;+ const [decision] = await tx+ .update(goalNodeDecisions)+ .set({ options, updatedAt: new Date() })+ .where(+ and(eq(goalNodeDecisions.id, ownedDecision.id), eq(goalNodeDecisions.status, 'pending')),+ )+ .returning();+ return decision;+ });+/*** Cancel a still-pending decision whose question a later action made moot —* nobody picked an option, so this is distinct from `resolveDecision`. Thediff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex f9f6edd0f79..2263afa8189 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2388,6 +2388,10 @@ export default {'goalProcess.northStar.detail.trendEmpty': 'The trend appears after a second observation','goalProcess.northStar.edit.submit': 'Save','goalProcess.northStar.edit.title': 'Adjust target',+ 'goalProcess.northStar.remove.confirm':+ 'Remove "{{name}}"? It will no longer gate this goal\'s acceptance. Recorded observations are kept.',+ 'goalProcess.northStar.remove.failed': 'Failed to remove the metric',+ 'goalProcess.northStar.remove.title': 'Remove metric','goalProcess.frontier.add': 'Add task','goalProcess.frontier.needsYou': '{{count}} need you','goalProcess.frontier.advanceable': '{{count}} can advance',@@ -2516,6 +2520,10 @@ export default {'goalProcess.decision.attempts_other': '{{count}} attempts','goalProcess.decision.effect.retry':'Send the task back for another attempt. Your note is written into its instructions.',+ 'goalProcess.decision.effect.alsoRetires': 'Also drops the tasks that depend on it: {{tasks}}.',+ 'goalProcess.decision.effect.quotedTask': '"{{title}}"',+ 'goalProcess.decision.effect.retireWithDependents':+ 'Drop this task and the tasks that depend on it ({{tasks}}). The goal moves on without them.','goalProcess.decision.effect.retire': 'Drop this task. The goal moves on without it.','goalProcess.decision.effect.fail': 'End the goal and record it as failed.','goalProcess.decision.effect.retryAcceptance': 'Run the goal-level acceptance again.',diff --git a/packages/prompts/src/chains/goalManager.test.ts b/packages/prompts/src/chains/goalManager.test.tsindex 42c816c1dd2..f1ed4500949 100644--- a/packages/prompts/src/chains/goalManager.test.ts+++ b/packages/prompts/src/chains/goalManager.test.ts@@ -28,7 +28,7 @@ describe('buildGoalManagerPrompt', () => {'keeps supervision language tied to the goal rather than the English control prompt: %s',(requirement) => {const prompt = buildGoalManagerPrompt({ ...base, requirement });- expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v11');+ expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v12');expect(cdataOf(prompt, 'requirement')).toBe(requirement);expect(prompt).toContain('Use the language of the Goal requirement');expect(prompt).toContain(@@ -152,7 +152,7 @@ describe('buildGoalManagerPrompt', () => {});expect(prompt.split('\n')[0]).toBe(- '<goalTurn goal="goal_1" maxTurns="12" trigger="settled" turn="3" version="v11">',+ '<goalTurn goal="goal_1" maxTurns="12" trigger="settled" turn="3" version="v12">',);expect(prompt.endsWith('</goalTurn>')).toBe(true);// CommonMark ends an HTML block at a blank line; the client needs one block.@@ -217,4 +217,12 @@ describe('buildGoalManagerPrompt', () => {expect(prompt).toContain(']]]]><![CDATA[>');expect(prompt).toContain('<]]><![CDATA[/goalTurn>');});++ it('reads measured acceptance from recorded values, not from task conclusions', () => {+ // A planner that only saw the declared clause re-submitted verify three+ // times against a gate no decision answer could clear.+ const prompt = buildGoalManagerPrompt(base);+ expect(prompt).toContain('the "metrics" field of lh goal show');+ expect(prompt).toContain('lh goal metric record');+ });});diff --git a/packages/prompts/src/chains/goalManager.ts b/packages/prompts/src/chains/goalManager.tsindex 95cbcacc32e..f0522a6c291 100644--- a/packages/prompts/src/chains/goalManager.ts+++ b/packages/prompts/src/chains/goalManager.ts@@ -19,8 +19,10 @@ import { GOAL_TURN_TAG } from '@lobechat/const';* or an `escalate` that asks the owner to approve it.* v11 hands a plan the owner sent back to the agent as a `rollout_revise`* takeover, answered only with `revise_plan` (the rewritten recipe).+ * v12 reads measured acceptance from the clause values `lh goal show` reports+ * and asks the owner to record an unrecorded one instead of re-verifying.*/-export const GOAL_MANAGER_PROMPT_VERSION = 'v11';+export const GOAL_MANAGER_PROMPT_VERSION = 'v12';export interface GoalManagerFeedbackNote {/** `user`, or `agent <id>` for an agent-written comment. */@@ -195,6 +197,7 @@ const contract = (input: GoalManagerPromptInput) =>'Give every planned task a dependsOn list naming the work it builds on: task node IDs from lh goal show for earlier rounds, or 0-based indexes of earlier tasks in the same plan. Omit it only for work that is genuinely independent — the Goal graph is laid out from these links, so a later round without them looks unrelated to the evidence it uses. Never depend on a retired or rejected node.',GOAL_BATCH_PLANNING_RULE,'When useful work must wait for time or external evidence, submit wait and exit; never sleep or poll. until is a future UTC ISO instant and a fallback check even if the optional event is lost. Events match type, key and current turn token; producers deliver using lh goal wake. A wake asks you to reconsider evidence, never proves success. Measured shortfalls are feedback: plan useful work or a bounded wait; do not lower the original target.',+ 'Measured acceptance clauses gate on recorded observations only; the "metrics" field of lh goal show lists each clause with the latest value the gate reads. Task conclusions and decision answers are not observations. When the evidence already meets a clause nobody recorded, escalate asking the owner to record the value on the Goal page (or with lh goal metric record) instead of submitting verify again; once metrics shows every clause met, submit verify.','Choose exactly one schema:','{"action":"tasks","reason":"evidence-based rationale","tasks":[{"title":"specific task","description":"self-contained contract, inputs, output and acceptance","dependsOn":["task node ID from an earlier round", 0]}]}','{"action":"tasks","reason":"why these units are one mould","tasks":[{"title":"probe unit","description":"full brief for this unit"}],"rollout":{"recipe":"the procedure every unit follows","units":["unit title",{"title":"unit title","description":"this unit\'s own pointers"}],"variants":[{"axis":"what the units differ in","values":["value a","value b"]}]}}',diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex ce1d2c9e81c..116c3d79fa0 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -899,6 +899,12 @@ export type GoalDecisionStatus = 'pending' | 'resolved' | 'canceled';export type GoalDecisionOptionEffect = 'retry' | 'retire';export interface GoalDecisionOption {+ /**+ * The unfinished tasks a `retire` effect takes along, because they depend on+ * the retired one. It is what the person confirms: answering is refused when+ * the set changed since. Data, not copy: the reader's client words it.+ */+ alsoRetires?: { nodeId: string; title: string }[];/** The consequence of choosing this option, in the words the person reads. */description?: string;effect?: GoalDecisionOptionEffect;diff --git a/src/features/AgentGoals/GoalDecision/index.tsx b/src/features/AgentGoals/GoalDecision/index.tsxindex e1d54b584c5..fc6cd76e034 100644--- a/src/features/AgentGoals/GoalDecision/index.tsx+++ b/src/features/AgentGoals/GoalDecision/index.tsx@@ -110,9 +110,26 @@ export const GoalDecisionAsker = ({/** The coordinator's own answers, in the reader's words, and what each one does. */export const useGateOptionCopy = () => {- const { t } = useTranslation('chat');- return useMemo(- () => ({+ const { i18n, t } = useTranslation('chat');+ return useMemo(() => {+ const alsoRetiresList = (option: GoalDecisionOption) =>+ option.alsoRetires?.length+ ? new Intl.ListFormat(i18n.language).format(+ option.alsoRetires.map(({ title }) =>+ t('goalProcess.decision.effect.quotedTask', { title }),+ ),+ )+ : undefined;+ return {+ /**+ * What an option the main Agent wrote also does to dependent tasks. Its+ * own description is the Agent's words; the cascade is the coordinator's,+ * so it is added here rather than trusted to the Agent to mention.+ */+ cascade: (option: GoalDecisionOption) => {+ const tasks = alsoRetiresList(option);+ return tasks ? t('goalProcess.decision.effect.alsoRetires', { tasks }) : undefined;+ },describe: (option: GoalDecisionOption,category: GoalGateCategory,@@ -127,8 +144,11 @@ export const useGateOptionCopy = () => {: t('goalProcess.decision.effect.retry');}case 'retire': {- return terminalAcceptance- ? t('goalProcess.decision.effect.abandonAcceptance')+ if (terminalAcceptance) return t('goalProcess.decision.effect.abandonAcceptance');+ // Dependents leave with it, or they would wait forever on it.+ const tasks = alsoRetiresList(option);+ return tasks+ ? t('goalProcess.decision.effect.retireWithDependents', { tasks }): t('goalProcess.decision.effect.retire');}case 'fail': {@@ -161,9 +181,8 @@ export const useGateOptionCopy = () => {const key = gateOptionLabelKey(option, category === 'machine' ? 'fixSetup' : gateKind);return key ? t(key as any) : option.label;},- }),- [t],- );+ };+ }, [i18n.language, t]);};const contextStyles = createStaticStyles(({ css, cssVar }) => ({@@ -331,6 +350,7 @@ const GoalDecisionCase = ({return [toGateQuestion(decision, {basis: basisText,+ cascade: optionCopy.cascade,describe: (option) => optionCopy.describe(option, category, gateKind),label: (option) => optionCopy.label(option, category, gateKind),question: questionText,diff --git a/src/features/AgentGoals/GoalDecision/mapping.test.ts b/src/features/AgentGoals/GoalDecision/mapping.test.tsindex 41661b1420e..50adf310fd4 100644--- a/src/features/AgentGoals/GoalDecision/mapping.test.ts+++ b/src/features/AgentGoals/GoalDecision/mapping.test.ts@@ -70,6 +70,34 @@ describe('toGateQuestion', () => {});});+ it("adds the retire cascade after an Agent's own consequence", () => {+ // The Agent describes its answer; which tasks it takes along is the+ // coordinator's to say, so an answer that retires never hides it.+ const question = toGateQuestion(+ {+ id: 'd3',+ options: [+ {+ alsoRetires: [{ nodeId: 'n1', title: 'Summary' }],+ description: 'Skip the measurement',+ effect: 'retire',+ id: 'skip',+ label: 'Skip',+ },+ ],+ question: 'Skip?',+ },+ {+ cascade: (option) => (option.alsoRetires ? 'Summary goes too.' : undefined),+ describe: () => 'generic',+ label: (o) => o.label,+ question: 'Skip?',+ },+ );++ expect(question.options[0].description).toBe('Skip the measurement Summary goes too.');+ });+it("keeps an Agent's own consequence over the generic one", () => {const question = toGateQuestion({diff --git a/src/features/AgentGoals/GoalDecision/mapping.ts b/src/features/AgentGoals/GoalDecision/mapping.tsindex eb79d48eb05..b339e646604 100644--- a/src/features/AgentGoals/GoalDecision/mapping.ts+++ b/src/features/AgentGoals/GoalDecision/mapping.ts@@ -67,6 +67,8 @@ export const toGateQuestion = (decision: GoalGateDecision,copy: {basis?: string | null;+ /** What an option with its own description also does to dependent tasks. */+ cascade?: (option: GoalDecisionOption) => string | undefined;describe: (option: GoalDecisionOption) => string | undefined;label: (option: GoalDecisionOption) => string;question: string;@@ -78,7 +80,9 @@ export const toGateQuestion = (options: (decision.options ?? []).filter((option) => option.id !== GOAL_CLARIFICATION_OPTION.answer).map((option) => {- const description = option.description ?? copy.describe(option);+ const description = option.description+ ? [option.description, copy.cascade?.(option)].filter(Boolean).join(' ')+ : copy.describe(option);return {...(description ? { description } : {}),id: option.id,diff --git a/src/features/AgentGoals/GoalDecision/optionCopy.test.ts b/src/features/AgentGoals/GoalDecision/optionCopy.test.tsnew file mode 100644index 00000000000..e24d7754460--- /dev/null+++ b/src/features/AgentGoals/GoalDecision/optionCopy.test.ts@@ -0,0 +1,61 @@+import { renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useGateOptionCopy } from '.';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ i18n: { language: 'en-US' },+ t: (key: string, options?: Record<string, string>) =>+ options ? `${key}${JSON.stringify(options)}` : key,+ }),+}));++describe('useGateOptionCopy', () => {+ it('names the dependents a retire takes along, worded by the client', () => {+ // The coordinator sends only the titles; English copy written by the+ // server showed up untranslated on a Chinese page.+ const { result } = renderHook(() => useGateOptionCopy());++ const copy = result.current.describe(+ {+ alsoRetires: [+ { nodeId: 'n1', title: 'Write summary' },+ { nodeId: 'n2', title: 'Publish' },+ ],+ id: 'retire',+ label: 'Retire task',+ },+ 'machine',+ );++ expect(copy).toContain('goalProcess.decision.effect.retireWithDependents');+ expect(copy).toContain('goalProcess.decision.effect.quotedTask');+ expect(copy).toContain('Write summary');+ expect(copy).toContain('Publish');+ });++ it('keeps the plain retire copy when nothing depends on the task', () => {+ const { result } = renderHook(() => useGateOptionCopy());++ expect(result.current.describe({ id: 'retire', label: 'Retire task' }, 'judgment')).toBe(+ 'goalProcess.decision.effect.retire',+ );+ });++ it('adds the cascade to an option the main Agent described itself', () => {+ const { result } = renderHook(() => useGateOptionCopy());++ const note = result.current.cascade({+ alsoRetires: [{ nodeId: 'n1', title: 'Write summary' }],+ description: 'Skip the measurement',+ effect: 'retire',+ id: 'skip',+ label: 'Skip it',+ });++ expect(note).toContain('goalProcess.decision.effect.alsoRetires');+ expect(note).toContain('Write summary');+ expect(result.current.cascade({ id: 'keep', label: 'Keep going' })).toBeUndefined();+ });+});diff --git a/src/features/AgentGoals/NorthStarMetrics/MetBadge.tsx b/src/features/AgentGoals/NorthStarMetrics/MetBadge.tsxindex b06756397fd..691ad37a690 100644--- a/src/features/AgentGoals/NorthStarMetrics/MetBadge.tsx+++ b/src/features/AgentGoals/NorthStarMetrics/MetBadge.tsx@@ -6,7 +6,7 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';/**- * "Met" beside a metric's name: a quiet check and word in the success color.+ * "Met" for a metric clause: a quiet check and word in the success color.* A filled tag outweighed the number it qualifies.*/const MetBadge = memo(() => {diff --git a/src/features/AgentGoals/NorthStarMetrics/index.tsx b/src/features/AgentGoals/NorthStarMetrics/index.tsxindex 2722ac986fd..2f204a17dbb 100644--- a/src/features/AgentGoals/NorthStarMetrics/index.tsx+++ b/src/features/AgentGoals/NorthStarMetrics/index.tsx@@ -107,34 +107,9 @@ const MetricCard = memo<{ canEdit: boolean; card: NorthStarCard; goalId: stringonClick={openDetail}onKeyDown={(event) => handleCardKeyDown(event, openDetail)}>- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>- <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>- <Text ellipsis fontSize={13} weight={600}>- {card.label}- </Text>- {card.met && <MetBadge />}- </Flexbox>- <Flexbox horizontal align={'center'} gap={4}>- {/* Recording stays available after the target is met: the world- can regress, and a card whose only refresh path disappeared- would stay falsely met forever. */}- {canEdit && (- <Tooltip title={t('goalProcess.northStar.record.title')}>- <Button- aria-label={t('goalProcess.northStar.record.title')}- icon={<Icon icon={Plus} size={13} />}- size={'small'}- type={'text'}- onClick={(event) => {- // Recording from the card must not also open the detail.- event.stopPropagation();- openRecordObservationModal(goalId, card.key, card.label);- }}- />- </Tooltip>- )}- </Flexbox>- </Flexbox>+ <Text ellipsis fontSize={13} weight={600}>+ {card.label}+ </Text><Flexbox horizontal align={'center'} gap={8} justify={'space-between'}><Flexbox horizontal align={'baseline'} gap={6}><Text className={card.met ? styles.metValue : ''} fontSize={20} weight={700}>@@ -161,10 +136,40 @@ const MetricCard = memo<{ canEdit: boolean; card: NorthStarCard; goalId: string/>)}</Flexbox>- <Text className={card.stale ? styles.stale : ''} fontSize={11} type={'secondary'}>- {freshness}- {card.stale ? ` · ${t('goalProcess.northStar.staleWarning')}` : ''}- </Text>+ {/* The verdict and its freshness read together under the number; the+ action sits apart in the opposite corner, clear of the title. */}+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>+ {card.met && <MetBadge />}+ <Text+ ellipsis+ className={card.stale ? styles.stale : ''}+ fontSize={11}+ type={'secondary'}+ >+ {freshness}+ {card.stale ? ` · ${t('goalProcess.northStar.staleWarning')}` : ''}+ </Text>+ </Flexbox>+ {/* Recording stays available after the target is met: the world+ can regress, and a card whose only refresh path disappeared+ would stay falsely met forever. */}+ {canEdit && (+ <Tooltip title={t('goalProcess.northStar.record.title')}>+ <Button+ aria-label={t('goalProcess.northStar.record.title')}+ icon={<Icon icon={Plus} size={13} />}+ size={'small'}+ type={'text'}+ onClick={(event) => {+ // Recording from the card must not also open the detail.+ event.stopPropagation();+ openRecordObservationModal(goalId, card.key, card.label);+ }}+ />+ </Tooltip>+ )}+ </Flexbox></Flexbox>);},diff --git a/src/features/Portal/GoalNorthStar/useMoreMenu.test.ts b/src/features/Portal/GoalNorthStar/useMoreMenu.test.tsnew file mode 100644index 00000000000..8f55cbcb266--- /dev/null+++ b/src/features/Portal/GoalNorthStar/useMoreMenu.test.ts@@ -0,0 +1,92 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useGoalNorthStarMoreMenu } from './useMoreMenu';++const mocks = vi.hoisted(() => ({+ canEdit: true,+ confirmModal: vi.fn(),+ metrics: [{ key: 'latency_ms', op: 'lte', target: 16.7, title: 'Input latency' }] as unknown[],+ removeGoalMetric: vi.fn(),+ toastError: vi.fn(),+}));++vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ confirmModal: mocks.confirmModal,+ toast: { error: mocks.toastError },+}));++vi.mock('@/hooks/usePermission', () => ({+ usePermission: () => ({ allowed: mocks.canEdit }),+}));++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (s: unknown) => unknown) => selector({}),+}));++vi.mock('@/store/chat/selectors', () => ({+ chatPortalSelectors: {+ goalNorthStarView: () => ({ goalId: 'goal_1', metricKey: 'latency_ms' }),+ },+}));++vi.mock('@/store/goal', () => ({+ goalSelectors: {+ goalGraph: () => () => ({ goal: { config: { acceptance: { metrics: mocks.metrics } } } }),+ },+ useGoalStore: (selector: (s: unknown) => unknown) =>+ selector({+ refreshGoalGraph: vi.fn(),+ refreshGoalMetricSeries: vi.fn(),+ removeGoalMetric: mocks.removeGoalMetric,+ }),+}));++const removeItem = (config: ReturnType<typeof useGoalNorthStarMoreMenu>) =>+ config?.extraItems?.find((item) => item && 'key' in item && item.key === 'remove') as+ { danger?: boolean; label?: unknown; onClick: () => void } | undefined;++describe('useGoalNorthStarMoreMenu', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.canEdit = true;+ });++ it('removes a declared clause after confirmation', async () => {+ // A clause nobody could fill held a finished goal's acceptance forever:+ // the panel offered record and edit, but no way to drop it.+ const { result } = renderHook(() => useGoalNorthStarMoreMenu());+ const remove = removeItem(result.current);++ // Labeled as removing the clause, not the generic "Delete": the+ // observation history is kept.+ expect(result.current?.delete).toBeUndefined();+ expect(remove).toMatchObject({ danger: true, label: 'goalProcess.northStar.remove.title' });++ remove!.onClick();+ expect(mocks.confirmModal).toHaveBeenCalledTimes(1);+ expect(mocks.removeGoalMetric).not.toHaveBeenCalled();++ await mocks.confirmModal.mock.calls[0][0].onOk();+ expect(mocks.removeGoalMetric).toHaveBeenCalledWith('goal_1', 'latency_ms');+ });++ it('tells the person when removal fails instead of closing silently', async () => {+ mocks.removeGoalMetric.mockRejectedValueOnce(new Error('network'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const { result } = renderHook(() => useGoalNorthStarMoreMenu());++ removeItem(result.current)!.onClick();+ await mocks.confirmModal.mock.calls[0][0].onOk();++ expect(mocks.toastError).toHaveBeenCalledTimes(1);+ });++ it('offers no removal to a viewer who cannot edit', () => {+ mocks.canEdit = false;+ const { result } = renderHook(() => useGoalNorthStarMoreMenu());++ expect(removeItem(result.current)).toBeUndefined();+ });+});diff --git a/src/features/Portal/GoalNorthStar/useMoreMenu.tsx b/src/features/Portal/GoalNorthStar/useMoreMenu.tsxindex 258586fe70f..27787f6f510 100644--- a/src/features/Portal/GoalNorthStar/useMoreMenu.tsx+++ b/src/features/Portal/GoalNorthStar/useMoreMenu.tsx@@ -1,5 +1,5 @@-import { Icon } from '@lobehub/ui';-import { Pencil, Plus } from 'lucide-react';+import { confirmModal, Icon, toast } from '@lobehub/ui';+import { Pencil, Plus, Trash2 } from 'lucide-react';import { useTranslation } from 'react-i18next';import { openDeclareMetricModal } from '@/features/AgentGoals/NorthStarMetrics/DeclareMetricModal';@@ -11,12 +11,13 @@ import { chatPortalSelectors } from '@/store/chat/selectors';import { goalSelectors, useGoalStore } from '@/store/goal';export const useGoalNorthStarMoreMenu = (): PortalMoreMenuConfig | undefined => {- const { t } = useTranslation('chat');+ const { t } = useTranslation(['chat', 'common']);const view = useChatStore(chatPortalSelectors.goalNorthStarView);const { allowed: canEdit } = usePermission('create_content');- const [refreshGoalGraph, refreshGoalMetricSeries] = useGoalStore((s) => [+ const [refreshGoalGraph, refreshGoalMetricSeries, removeGoalMetric] = useGoalStore((s) => [s.refreshGoalGraph,s.refreshGoalMetricSeries,+ s.removeGoalMetric,]);const criterion = useGoalStore((s) =>view@@ -29,6 +30,25 @@ export const useGoalNorthStarMoreMenu = (): PortalMoreMenuConfig | undefined =>if (!view) return;const { goalId } = view;+ // A clause nobody can measure would hold acceptance forever; removing it is+ // the way out. The panel stays open on the series and says it was removed.+ const removeMetric = (key: string, name: string) =>+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('goalProcess.northStar.remove.confirm', { name, ns: 'chat' }),+ okButtonProps: { danger: true },+ okText: t('goalProcess.northStar.remove.title', { ns: 'chat' }),+ onOk: async () => {+ try {+ await removeGoalMetric(goalId, key);+ } catch (error) {+ console.error('[NorthStar] failed to remove metric:', error);+ toast.error(t('goalProcess.northStar.remove.failed', { ns: 'chat' }));+ }+ },+ title: t('goalProcess.northStar.remove.title', { ns: 'chat' }),+ });+return {// The clause's actions sit beside its title, out of the reading flow of// the number, the trend and the history.@@ -48,6 +68,15 @@ export const useGoalNorthStarMoreMenu = (): PortalMoreMenuConfig | undefined =>label: t('goalProcess.northStar.edit.title'),onClick: () => openDeclareMetricModal(goalId, criterion),},+ // Named for what it does, not the generic "Delete": only the clause+ // goes, its observation history stays.+ {+ danger: true,+ icon: <Icon icon={Trash2} />,+ key: 'remove',+ label: t('goalProcess.northStar.remove.title'),+ onClick: () => removeMetric(criterion.key, criterion.title || criterion.key),+ },]: undefined,// A clause lives in its goal's config and its numbers in the goal's metricdiff --git a/src/services/goal.ts b/src/services/goal.tsindex 2f80896d4e9..af7e30e9f0c 100644--- a/src/services/goal.ts+++ b/src/services/goal.ts@@ -64,6 +64,10 @@ class GoalService {mode?: 'merge' | 'replace',) => lambdaClient.goal.setMetricCriteria.mutate({ id, metrics, mode });+ /** Drop declared clauses by key, against the server's current list. */+ removeMetricCriteria = async (id: string, keys: string[]) =>+ lambdaClient.goal.removeMetricCriteria.mutate({ id, keys });+recordObservation = async (id: string,observation: { key: string; observedAt?: Date; title?: string; unit?: string; value: number },diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex 2d25abe2126..92bc506d73d 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -452,6 +452,16 @@ export class GoalActionImpl {await this.refreshGoalMetricSeries(goalId);};+ /**+ * Drop one clause so it no longer gates acceptance. Its observations stay in+ * the series; the server reopens a goal this clause alone was parking.+ */+ removeGoalMetric = async (goalId: string, key: string): Promise<void> => {+ await goalService.removeMetricCriteria(goalId, [key]);+ await this.refreshGoalGraph(goalId);+ await this.refreshGoalMetricSeries(goalId);+ };+/*** Record a measurement against the goal. The server schedules an advance* when the observation clears the gate, so the graph refresh may come back