🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): marks between runs and evaluator-scored objectives (#23108)
Arvin Xu1a49740448eb
diff --git a/apps/cli/src/commands/goal/graphGlyphs.ts b/apps/cli/src/commands/goal/graphGlyphs.tsnew file mode 100644index 00000000000..212a6eeeba1--- /dev/null+++ b/apps/cli/src/commands/goal/graphGlyphs.ts@@ -0,0 +1,37 @@+import type { GoalEdgeKind, GoalNodeKind } from '@lobechat/types';++/** The glyph `lh goal show` prints before each node of the graph. */+export const nodeIcon: Record<GoalNodeKind, string> = {+ batch: '▦',+ dead_end: '✕',+ decision: '◆',+ experiment: '⚗',+ finding: '●',+ hazard: '⚠',+ pattern: '↻',+ problem: '◇',+ task: '▣',+ template: '▤',+ tool: '⚒',+};++/**+ * Every edge kind reads `source <kind> target`, so a row listing its INCOMING+ * edges by kind states the relationship backwards: an incoming `depends_on`+ * means the other node depends on THIS one, not the reverse. Render the inverse+ * verb instead, so each entry is a true sentence about the row it sits on.+ */+export const inverseEdgeLabel: Record<GoalEdgeKind, string> = {+ answers: 'answered by',+ confirms: 'confirmed by',+ contains: 'inside',+ contradicts: 'contradicted by',+ decomposes: 'part of',+ depends_on: 'blocks',+ derived_from: 'ancestor of',+ investigates: 'investigated by',+ leads_to: 'follows',+ produces: 'produced by',+ refutes: 'refuted by',+ supports: 'supported by',+};diff --git a/apps/cli/src/commands/goal/index.ts b/apps/cli/src/commands/goal/index.tsindex 6b078c6ede4..b1c33e04cd7 100644--- a/apps/cli/src/commands/goal/index.ts+++ b/apps/cli/src/commands/goal/index.ts@@ -1,13 +1,11 @@import { readFile } from 'node:fs/promises';import type {- GoalEdgeKind,GoalEventEntityType,GoalEventType,GoalGraphDecision,GoalGraphEvent,GoalGraphSnapshot,- GoalNodeKind,GoalPlanContext,GoalTickResult,} from '@lobechat/types';@@ -28,12 +26,15 @@ import {} from './assignment';import { registerGoalConfigurationCommands } from './configuration';import { registerGoalGraphEditCommands } from './graphEdit';+import { inverseEdgeLabel, nodeIcon } from './graphGlyphs';+import { registerGoalMarkCommands } from './mark';import {type GoalMetricState,printMetricState,readMetricState,registerGoalMetricCommands,} from './metric';+import { registerGoalObjectiveCommands } from './objective';import { goalReads, hasOperationToken } from './reads';import { registerGoalReportCommand } from './report';import { missingSeedDependencies, parseTaskFile } from './seedTasks';@@ -54,33 +55,6 @@ const parseVariant = (raw: string) => {return { axis, values };};-const nodeIcon: Record<GoalNodeKind, string> = {- batch: '▦',- decision: '◆',- experiment: '⚗',- finding: '●',- problem: '◇',- task: '▣',-};-/**- * Every edge kind reads `source <kind> target`, so a row listing its INCOMING- * edges by kind states the relationship backwards: an incoming `depends_on`- * means the other node depends on THIS one, not the reverse. Render the inverse- * verb instead, so each entry is a true sentence about the row it sits on.- */-const inverseEdgeLabel: Record<GoalEdgeKind, string> = {- answers: 'answered by',- contains: 'inside',- contradicts: 'contradicted by',- decomposes: 'part of',- depends_on: 'blocks',- derived_from: 'ancestor of',- investigates: 'investigated by',- leads_to: 'follows',- produces: 'produced by',- supports: 'supported by',-};-const terminalOutcomes = new Set(['achieved', 'waiting_human', 'no_progress', 'failed']);/** Backoff bounds for a transient `goal tick` failure. */@@ -1238,5 +1212,7 @@ export function registerGoalCommand(program: Command) {});registerGoalGraphEditCommands(goal);+ registerGoalMarkCommands(goal);registerGoalMetricCommands(goal);+ registerGoalObjectiveCommands(goal);}diff --git a/apps/cli/src/commands/goal/mark.test.ts b/apps/cli/src/commands/goal/mark.test.tsnew file mode 100644index 00000000000..77d17ce19e2--- /dev/null+++ b/apps/cli/src/commands/goal/mark.test.ts@@ -0,0 +1,120 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../utils/logger';+import { registerGoalMarkCommands } from './mark';++const { mockClient, operationToken } = vi.hoisted(() => ({+ mockClient: {+ goal: {+ addMark: { mutate: vi.fn() },+ addMarkOperation: { mutate: vi.fn() },+ judgeMarkOperation: { mutate: vi.fn() },+ marks: { query: vi.fn() },+ marksOperation: { query: vi.fn() },+ retireMark: { mutate: vi.fn() },+ },+ },+ operationToken: { value: false },+}));++vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));+vi.mock('./reads', () => ({ hasOperationToken: () => operationToken.value }));++const markId = '11111111-1111-4111-8111-111111111111';++const run = (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerGoalMarkCommands(program.command('goal'));+ return program.parseAsync(['node', 'test', 'goal', 'mark', ...args]);+};++describe('lh goal mark', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(log, 'info').mockImplementation(() => {});+ operationToken.value = false;+ });+ afterEach(() => vi.restoreAllMocks());++ describe('inside a Goal Task run', () => {+ beforeEach(() => {+ operationToken.value = true;+ });++ it('leaves a mark for the run’s own goal without naming it', async () => {+ mockClient.goal.addMarkOperation.mutate.mockResolvedValue({ data: { id: markId } });++ await run('add', 'pattern', 'tsc fails → mock', '-d', 'details');++ expect(mockClient.goal.addMarkOperation.mutate).toHaveBeenCalledWith({+ description: 'details',+ kind: 'pattern',+ title: 'tsc fails → mock',+ });+ expect(mockClient.goal.addMark.mutate).not.toHaveBeenCalled();+ });++ it('lists the run’s goal marks', async () => {+ mockClient.goal.marksOperation.query.mockResolvedValue({ data: [] });++ await run('list');++ expect(mockClient.goal.marksOperation.query).toHaveBeenCalled();+ expect(log.info).toHaveBeenCalledWith('No marks yet.');+ });++ it('records a refutation for a mark the run relied on', async () => {+ mockClient.goal.judgeMarkOperation.mutate.mockResolvedValue({+ data: { confirms: 0, refutes: 1 },+ });++ await run('refute', markId);++ expect(mockClient.goal.judgeMarkOperation.mutate).toHaveBeenCalledWith({+ markId,+ verdict: 'refutes',+ });+ });+ });++ describe('with a person’s login', () => {+ it('needs the goal named to leave a mark', async () => {+ await expect(run('add', 'hazard', 'do not touch')).rejects.toThrow(/goal id/);++ mockClient.goal.addMark.mutate.mockResolvedValue({ data: { id: markId } });+ await run('add', 'hazard', 'do not touch', '--goal', 'goal_1');+ expect(mockClient.goal.addMark.mutate).toHaveBeenCalledWith({+ description: undefined,+ id: 'goal_1',+ kind: 'hazard',+ title: 'do not touch',+ });+ });++ it('cannot judge a mark, since no run relied on it', async () => {+ await expect(run('confirm', markId)).rejects.toThrow(/Only a Goal Task run/);+ expect(mockClient.goal.judgeMarkOperation.mutate).not.toHaveBeenCalled();+ });++ it('retires a mark on the named goal', async () => {+ mockClient.goal.retireMark.mutate.mockResolvedValue({ message: 'Mark retired' });++ await run('retire', 'goal_1', markId, '--reason', 'superseded');++ expect(mockClient.goal.retireMark.mutate).toHaveBeenCalledWith({+ id: 'goal_1',+ markId,+ reason: 'superseded',+ });+ });+ });++ it('refuses an unknown kind and names the valid ones', async () => {+ operationToken.value = true;+ await expect(run('add', 'finding', 'x')).rejects.toThrow(+ 'Unknown mark kind "finding". Kinds: pattern, tool, hazard, dead_end.',+ );+ });+});diff --git a/apps/cli/src/commands/goal/mark.ts b/apps/cli/src/commands/goal/mark.tsnew file mode 100644index 00000000000..b12b1a4a1a7--- /dev/null+++ b/apps/cli/src/commands/goal/mark.ts@@ -0,0 +1,136 @@+import { GOAL_MARK_KINDS } from '@lobechat/const/goal';+import type { GoalMarkKind } from '@lobechat/types';+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../api/client';+import { outputJson } from '../../utils/format';+import { log } from '../../utils/logger';+import { hasOperationToken } from './reads';++interface MarkRow {+ confidence: number;+ confirms: number;+ description: string | null;+ id: string;+ kind: string;+ refutes: number;+ status: string;+ title: string;+}++const KINDS_HELP = `Kinds: ${GOAL_MARK_KINDS.join(', ')}.`;++const parseKind = (kind: string): GoalMarkKind => {+ if (!(GOAL_MARK_KINDS as readonly string[]).includes(kind))+ throw new Error(`Unknown mark kind "${kind}". ${KINDS_HELP}`);+ return kind as GoalMarkKind;+};++const describeMark = (mark: MarkRow) => {+ const record =+ mark.confirms || mark.refutes ? `+${mark.confirms}/-${mark.refutes}` : pc.dim('unconfirmed');+ const retired = mark.status === 'retired' ? pc.dim(' (retired)') : '';+ const lines = [+ `${pc.bold(`[${mark.kind}]`)} ${mark.title} ${record}${retired}`,+ pc.dim(` id: ${mark.id}`),+ ];+ if (mark.description) lines.push(` ${mark.description.replaceAll('\n', '\n ')}`);+ return lines.join('\n');+};++/** Outside a Goal Task run there is no run to stand for, so the goal must be named. */+const requireGoalId = (goalId: string | undefined, command: string) => {+ if (!goalId)+ throw new Error(+ `Pass the goal id: \`lh goal ${command}\` outside a Goal Task run cannot tell which goal you mean.`,+ );+ return goalId;+};++const RUN_ONLY =+ 'Only a Goal Task run judges a mark: it records that this run relied on the mark. Run it from inside the Task run.';++/**+ * Marks: the notes runs of one Goal leave for each other.+ *+ * Inside a Goal Task run (an operation token), every command acts for that+ * run's Goal and Task, so no ids are needed. With a person's login, `list`,+ * `add` and `retire` take the goal id; judging is for runs only.+ */+export function registerGoalMarkCommands(goal: Command) {+ const mark = goal+ .command('mark')+ .summary('Notes runs of a goal leave for each other')+ .description(+ [+ 'Marks are short notes one run of a goal leaves for every later run: a fix for a pitfall',+ '(pattern), a reusable script (tool), something not to touch (hazard), or an approach',+ 'that failed (dead_end). Every Task run of the goal is handed the trusted ones.',+ KINDS_HELP,+ ].join('\n'),+ );++ mark+ .command('add <kind> <title>')+ .description(`Leave a mark for later runs. ${KINDS_HELP}`)+ .option('-d, --description <text>', 'The details: exact error, cause, fix, path, usage')+ .option('--goal <id>', 'The goal, when not run from inside one of its Task runs')+ .action(+ async (kind: string, title: string, options: { description?: string; goal?: string }) => {+ const input = { description: options.description, kind: parseKind(kind), title };+ const client = await getTrpcClient();+ const result = hasOperationToken()+ ? await client.goal.addMarkOperation.mutate(input)+ : await client.goal.addMark.mutate({+ ...input,+ id: requireGoalId(options.goal, 'mark add --goal <id>'),+ });+ log.info(`Left ${input.kind} mark ${result.data.id}`);+ },+ );++ mark+ .command('list [goal-id]')+ .description('List the marks of a goal, newest first')+ .option('--json', 'Output JSON')+ .action(async (goalId: string | undefined, options: { json?: boolean }) => {+ const client = await getTrpcClient();+ const marks: MarkRow[] = hasOperationToken()+ ? (await client.goal.marksOperation.query()).data+ : (await client.goal.marks.query({ id: requireGoalId(goalId, 'mark list <goal-id>') }))+ .data;+ if (options.json) return outputJson(marks);+ if (marks.length === 0) return log.info('No marks yet.');+ console.log(marks.map(describeMark).join('\n\n'));+ });++ for (const [command, verdict, summary] of [+ ['confirm', 'confirms', 'Record that a mark this run relied on held'],+ ['refute', 'refutes', 'Record that a mark this run relied on was wrong'],+ ] as const) {+ mark+ .command(`${command} <mark-id>`)+ .description(summary)+ .action(async (markId: string) => {+ if (!hasOperationToken()) throw new Error(RUN_ONLY);+ const result = await (+ await getTrpcClient()+ ).goal.judgeMarkOperation.mutate({ markId, verdict });+ log.info(+ `Recorded: ${verdict} ${markId} (now +${result.data.confirms}/-${result.data.refutes})`,+ );+ });+ }++ mark+ .command('retire <goal-id> <mark-id>')+ .description('Take a mark out of every later run; it stays on the goal graph')+ .option('--reason <text>', 'Why, kept on the audit trail')+ .action(async (goalId: string, markId: string, options: { reason?: string }) => {+ const result = await (+ await getTrpcClient()+ ).goal.retireMark.mutate({ id: goalId, markId, reason: options.reason });+ log.info(result.message);+ });+}diff --git a/apps/cli/src/commands/goal/objective.test.ts b/apps/cli/src/commands/goal/objective.test.tsnew file mode 100644index 00000000000..1c7d2c78ebe--- /dev/null+++ b/apps/cli/src/commands/goal/objective.test.ts@@ -0,0 +1,282 @@+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../utils/logger';+import {+ registerGoalObjectiveCommands,+ runEvaluator,+ splitEvaluatorCommand,+ withMachineLock,+} from './objective';++const { mockClient, operationToken } = vi.hoisted(() => ({+ mockClient: {+ goal: {+ objective: { query: vi.fn() },+ objectiveOperation: { query: vi.fn() },+ recordEvaluation: { mutate: vi.fn() },+ recordEvaluationOperation: { mutate: vi.fn() },+ setObjective: { mutate: vi.fn() },+ },+ },+ operationToken: { value: false },+}));++vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));+vi.mock('./reads', () => ({ hasOperationToken: () => operationToken.value }));++const run = (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerGoalObjectiveCommands(program.command('goal'));+ return program.parseAsync(['node', 'test', 'goal', ...args]);+};++const board = (evaluator: string) => ({+ best: undefined,+ lanes: [],+ objective: { direction: 'max', evaluator },+});++describe('lh goal objective commands', () => {+ let cwd: string;+ let output: string[];++ beforeEach(async () => {+ vi.clearAllMocks();+ operationToken.value = false;+ output = [];+ vi.spyOn(log, 'info').mockImplementation((message: string) => void output.push(message));+ vi.spyOn(console, 'log').mockImplementation(+ (message?: unknown) => void output.push(String(message)),+ );+ cwd = await mkdtemp(path.join(tmpdir(), 'lh-objective-'));+ vi.spyOn(process, 'cwd').mockReturnValue(cwd);+ process.exitCode = undefined;+ });+ afterEach(() => {+ vi.restoreAllMocks();+ process.exitCode = undefined;+ });++ it('sets an objective with its evaluator and direction', async () => {+ mockClient.goal.setObjective.mutate.mockResolvedValue({ message: 'Objective set' });++ await run(+ 'set-objective',+ 'goal_1',+ '--evaluator',+ './score.sh',+ '--direction',+ 'min',+ '--timeout',+ '600',+ );++ expect(mockClient.goal.setObjective.mutate).toHaveBeenCalledWith({+ id: 'goal_1',+ objective: {+ direction: 'min',+ evaluator: './score.sh',+ key: undefined,+ timeoutSeconds: 600,+ title: undefined,+ },+ });+ });++ it('refuses set-objective without an evaluator or --clear', async () => {+ await expect(run('set-objective', 'goal_1')).rejects.toThrow(/--evaluator/);+ });++ it('runs the evaluator in a Goal Task run and records the score for its lane', async () => {+ operationToken.value = true;+ await writeFile(+ path.join(cwd, 'score.sh'),+ 'echo "training"; echo \'{"score": 41.5, "summary": "ok", "metrics": {"M1": 0.8}}\'\n',+ );+ mockClient.goal.objectiveOperation.query.mockResolvedValue({ data: board('sh score.sh') });+ mockClient.goal.recordEvaluationOperation.mutate.mockResolvedValue({+ data: {+ lane: 'lane_a',+ leaderboard: {+ lanes: [{ best: 41.5, evaluations: 1, lane: 'lane_a', latest: 41.5, title: 'Lane A' }],+ objective: { direction: 'max', evaluator: 'sh score.sh' },+ },+ newBest: true,+ recorded: true,+ },+ });++ await run('evaluate');++ expect(mockClient.goal.recordEvaluationOperation.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ metrics: { M1: 0.8 }, score: 41.5, summary: 'ok', valid: true }),+ );+ expect(output.join('\n')).toContain('Score: 41.5');+ expect(output.join('\n')).toContain('Lane A (your lane)');+ expect(process.exitCode).toBeUndefined();+ });++ it('records nothing and fails when the evaluator prints no score', async () => {+ operationToken.value = true;+ mockClient.goal.objectiveOperation.query.mockResolvedValue({+ // No shell any more: the exit code has to come from the program itself.+ data: board(`node -e "console.log('boom'); process.exit(3)"`),+ });++ await run('evaluate');++ expect(mockClient.goal.recordEvaluationOperation.mutate).not.toHaveBeenCalled();+ expect(output.join('\n')).toContain('Evaluator printed no score (exit code 3)');+ expect(process.exitCode).toBe(1);+ });++ it('needs the goal id outside a Goal Task run', async () => {+ await expect(run('evaluate')).rejects.toThrow(/goal id/);+ await expect(run('objective')).rejects.toThrow(/goal id/);+ });+});++describe('withMachineLock', () => {+ it('runs one holder at a time and frees the lock after a failure', async () => {+ const dir = path.join(await mkdtemp(path.join(tmpdir(), 'lh-lock-')), 'lock');+ const order: string[] = [];+ let release!: () => void;+ const first = withMachineLock(+ 60,+ () => {+ order.push('first:start');+ return new Promise<void>((resolve) => (release = resolve)).then(() =>+ order.push('first:end'),+ );+ },+ { dir },+ );+ await vi.waitFor(() => expect(order).toEqual(['first:start']));+ const waited = vi.fn();+ const second = withMachineLock(60, async () => void order.push('second'), {+ dir,+ onWait: waited,+ });+ await vi.waitFor(() => expect(waited).toHaveBeenCalled());+ release();+ await Promise.all([first, second]);+ expect(order).toEqual(['first:start', 'first:end', 'second']);++ await expect(+ withMachineLock(+ 60,+ async () => {+ throw new Error('x');+ },+ { dir },+ ),+ ).rejects.toThrow('x');+ await expect(withMachineLock(60, async () => 'free', { dir })).resolves.toBe('free');+ });+});++describe('withMachineLock ownership', () => {+ const makeDir = async () => path.join(await mkdtemp(path.join(tmpdir(), 'lh-lock-')), 'lock');++ it('does not expire a live holder on the waiter’s shorter timeout', async () => {+ const dir = await makeDir();+ const order: string[] = [];+ let release!: () => void;+ const holder = withMachineLock(+ 1800,+ () => new Promise<void>((resolve) => (release = resolve)).then(() => order.push('holder')),+ { dir },+ );+ await vi.waitFor(async () =>+ expect(await readFile(path.join(dir, 'owner'), 'utf8')).toBeTruthy(),+ );++ // A waiter that gives up after one second must still leave the 30-minute evaluation alone.+ const waiter = withMachineLock(1, async () => void order.push('waiter'), { dir, pollMs: 20 });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(order).toEqual([]);++ release();+ await Promise.all([holder, waiter]);+ expect(order).toEqual(['holder', 'waiter']);+ });++ it('takes over a lock whose holder deadline has passed', async () => {+ const dir = await makeDir();+ await mkdir(dir, { recursive: true });+ await writeFile(path.join(dir, 'pid'), String(process.pid));+ await writeFile(path.join(dir, 'owner'), 'someone-else');+ await writeFile(path.join(dir, 'deadline'), String(Date.now() - 1000));++ await expect(withMachineLock(60, async () => 'taken', { dir, pollMs: 20 })).resolves.toBe(+ 'taken',+ );+ });++ it('leaves a replacement lock alone when the previous holder finishes', async () => {+ const dir = await makeDir();+ let release!: () => void;+ const first = withMachineLock(60, () => new Promise<void>((resolve) => (release = resolve)), {+ dir,+ });+ await vi.waitFor(async () =>+ expect(await readFile(path.join(dir, 'owner'), 'utf8')).toBeTruthy(),+ );+ // Simulate a takeover: someone else now owns the directory.+ await writeFile(path.join(dir, 'owner'), 'someone-else');+ release();+ await first;+ expect(await readFile(path.join(dir, 'owner'), 'utf8')).toBe('someone-else');+ await rm(dir, { force: true, recursive: true });+ });+});++describe('runEvaluator', () => {+ const makeCwd = async () => mkdtemp(path.join(tmpdir(), 'lh-eval-'));++ it('splits quoted arguments without a shell', () => {+ expect(splitEvaluatorCommand(`node eval.js --label "a b" 'c d'`)).toEqual([+ 'node',+ 'eval.js',+ '--label',+ 'a b',+ 'c d',+ ]);+ // Metacharacters stay literal; nothing is interpreted.+ expect(splitEvaluatorCommand('node x.js; rm -rf /')).toEqual([+ 'node',+ 'x.js;',+ 'rm',+ '-rf',+ '/',+ ]);+ expect(() => splitEvaluatorCommand(`node "unbalanced`)).toThrow(/Unbalanced/);+ });++ it('runs a command and collects its output', async () => {+ const cwd = await makeCwd();+ const result = await runEvaluator(`node -e "console.log(0.75)"`, cwd, 20);+ expect(result.timedOut).toBe(false);+ expect(result.code).toBe(0);+ expect(result.output.trim()).toBe('0.75');+ });++ it('settles on timeout instead of waiting for inherited pipes', async () => {+ const cwd = await makeCwd();+ const started = Date.now();+ // The child leaves a grandchild holding the pipes; the promise must still settle at the timeout.+ const result = await runEvaluator(+ `node -e "const {spawn}=require('node:child_process');spawn('sleep',['30'],{stdio:'inherit'});setInterval(()=>{},1000)"`,+ cwd,+ 0.4,+ );+ expect(result.timedOut).toBe(true);+ expect(Date.now() - started).toBeLessThan(5000);+ });+});diff --git a/apps/cli/src/commands/goal/objective.ts b/apps/cli/src/commands/goal/objective.tsnew file mode 100644index 00000000000..b5f1fdad741--- /dev/null+++ b/apps/cli/src/commands/goal/objective.ts@@ -0,0 +1,401 @@+import { spawn, spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { type EvaluatorResult, parseEvaluatorOutput } from '@lobechat/utils/goalObjective';+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../api/client';+import { outputJson } from '../../utils/format';+import { log } from '../../utils/logger';+import { hasOperationToken } from './reads';++const DEFAULT_TIMEOUT_SECONDS = 1800;+const OUTPUT_TAIL_LINES = 60;+const LOCK_POLL_MS = 2000;+/** Only for locks written before a holder's deadline was recorded next to its pid. */+const LOCK_STALE_GRACE_MS = 300;++interface Lane {+ best: number;+ evaluations: number;+ lane: string;+ latest: number;+ title: string;+}++interface Leaderboard {+ best?: number;+ lanes: Lane[];+ leader?: string;+ objective: {+ direction: 'max' | 'min';+ evaluator: string;+ timeoutSeconds?: number;+ title?: string;+ };+ you?: string;+}++const formatScore = (value: number) => String(Number(value.toFixed(4)));++export const printLeaderboard = (board: Leaderboard) => {+ const { direction, evaluator, title } = board.objective;+ console.log(+ `${pc.bold(title || 'Objective')} — ${direction === 'max' ? 'higher' : 'lower'} is better · evaluator: ${pc.dim(evaluator)}`,+ );+ if (board.lanes.length === 0) return console.log(pc.dim(' No evaluation recorded yet.'));+ board.lanes.forEach((lane, index) => {+ const you = lane.lane === board.you ? pc.cyan(' (your lane)') : '';+ console.log(+ ` ${index + 1}. ${lane.title}${you} best ${pc.bold(formatScore(lane.best))} · latest ${formatScore(lane.latest)} · ${lane.evaluations} eval(s)`,+ );+ });+};++/** Outside a Goal Task run there is no run to stand for, so the goal must be named. */+const requireGoalId = (goalId: string | undefined, command: string) => {+ if (!goalId)+ throw new Error(+ `Pass the goal id: \`lh goal ${command}\` outside a Goal Task run cannot tell which goal you mean.`,+ );+ return goalId;+};++const readLeaderboard = async (goalId?: string): Promise<Leaderboard | null> => {+ const client = await getTrpcClient();+ return hasOperationToken()+ ? (await client.goal.objectiveOperation.query()).data+ : (await client.goal.objective.query({ id: requireGoalId(goalId, 'objective <goal-id>') }))+ .data;+};++/**+ * One evaluation at a time per machine: evaluators are often heavy (a judge+ * that trains or replays a model), and lanes of one goal on the same host+ * would otherwise starve each other. A directory is the lock because `mkdir`+ * is atomic everywhere; a holder that died is detected by its pid or age.+ */+export const withMachineLock = async <T>(+ timeoutSeconds: number,+ run: () => Promise<T>,+ {+ dir = path.join(tmpdir(), 'lobehub-goal-evaluate.lock'),+ onWait = () => {},+ pollMs = LOCK_POLL_MS,+ } = {},+): Promise<T> => {+ // Who holds the lock is recorded, so a waiter that took over an expired lock cannot be evicted+ // by the previous holder's `finally`.+ const owner = `${process.pid}-${Date.now().toString(36)}`;+ const staged = `${dir}.staging-${owner}`;+ let waited = false;+ for (;;) {+ // Built off to the side and renamed into place: a lock directory that exists always carries+ // its owner files, so a waiter never reads a half-written lock as a dead one.+ await mkdir(staged, { recursive: true });+ await writeFile(path.join(staged, 'pid'), String(process.pid));+ await writeFile(path.join(staged, 'owner'), owner);+ // The holder's own deadline, not the waiter's timeout, decides when the lock may be taken.+ await writeFile(path.join(staged, 'deadline'), String(Date.now() + timeoutSeconds * 1000));+ try {+ await rename(staged, dir);+ break;+ } catch (error) {+ await rm(staged, { force: true, recursive: true });+ const code = (error as NodeJS.ErrnoException).code;+ if (code !== 'EEXIST' && code !== 'ENOTEMPTY' && code !== 'ENOTDIR') throw error;++ const holder = Number(await readFile(path.join(dir, 'pid'), 'utf8').catch(() => '0'));+ const deadline = Number(await readFile(path.join(dir, 'deadline'), 'utf8').catch(() => '0'));+ const age = Date.now() - (await stat(dir).catch(() => ({ mtimeMs: Date.now() }))).mtimeMs;+ const alive =+ holder > 0 &&+ (() => {+ try {+ process.kill(holder, 0);+ return true;+ } catch {+ return false;+ }+ })();+ // A live holder keeps the lock for as long as it said it would, whatever this waiter's own+ // timeout is. Locks written before `deadline` existed fall back to pid plus age.+ const expired = deadline > 0 ? Date.now() > deadline : age > LOCK_STALE_GRACE_MS * 1000;+ if (!alive || expired) {+ await rm(dir, { force: true, recursive: true });+ continue;+ }+ if (!waited) onWait();+ waited = true;+ await new Promise((resolve) => setTimeout(resolve, pollMs));+ }+ }+ try {+ return await run();+ } finally {+ const current = await readFile(path.join(dir, 'owner'), 'utf8').catch(() => '');+ if (current === owner) await rm(dir, { force: true, recursive: true });+ }+};++/** Hash of the working tree's committed state plus its uncommitted changes, in a git repo. */+export const workingTreeFingerprint = (cwd: string): string | undefined => {+ const git = (...args: string[]) =>+ spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });+ const head = git('rev-parse', 'HEAD');+ if (head.status !== 0) return undefined;+ const diff = git('diff', 'HEAD');+ const untracked = git('ls-files', '--others', '--exclude-standard', '-z');+ return createHash('sha256')+ .update(head.stdout)+ .update(diff.stdout ?? '')+ .update(untracked.stdout ?? '')+ .digest('hex')+ .slice(0, 16);+};++/**+ * Splits an evaluator command into an executable and its arguments.+ *+ * The evaluator string is stored on the goal and read back from the server, so other lane members+ * can write it. It is never handed to a shell: metacharacters stay literal, and only quoting (so+ * one argument can contain a space) keeps its meaning.+ */+export const splitEvaluatorCommand = (command: string): string[] => {+ const tokens: string[] = [];+ let current = '';+ let quoted: '"' | "'" | undefined;+ let started = false;+ for (const char of command) {+ if (quoted) {+ if (char === quoted) quoted = undefined;+ else current += char;+ continue;+ }+ if (char === '"' || char === "'") {+ quoted = char;+ started = true;+ continue;+ }+ if (/\s/.test(char)) {+ if (started) tokens.push(current);+ current = '';+ started = false;+ continue;+ }+ current += char;+ started = true;+ }+ if (quoted) throw new Error(`Unbalanced ${quoted} in the evaluator command: ${command}`);+ if (started) tokens.push(current);++ return tokens;+};++/** Kills the evaluator and everything it started, not just the process we spawned. */+const killEvaluatorTree = (child: { kill: (signal: NodeJS.Signals) => boolean; pid?: number }) => {+ const { pid } = child;+ if (pid && process.platform !== 'win32') {+ try {+ // `detached` below makes the child its own process group leader, so the group id is its pid.+ process.kill(-pid, 'SIGKILL');+ return;+ } catch {+ // Fall through to the plain kill below.+ }+ }+ if (pid && process.platform === 'win32') {+ const killed = spawnSync('taskkill', ['/pid', String(pid), '/T', '/F']);+ if (killed.status === 0) return;+ }+ try {+ child.kill('SIGKILL');+ } catch {+ // Already gone.+ }+};++/**+ * Run the evaluator in `cwd`; resolves with its combined output and whether it timed out.+ *+ * The timeout settles on its own: a helper that inherited stdout/stderr can keep the pipes open+ * long after the evaluator is gone, and waiting for `close` would hold the machine lock past the+ * deadline the user asked for.+ */+export const runEvaluator = (command: string, cwd: string, timeoutSeconds: number) =>+ new Promise<{ code: number | null; output: string; timedOut: boolean }>((resolve) => {+ const [executable, ...args] = splitEvaluatorCommand(command);+ if (!executable) {+ resolve({ code: null, output: '', timedOut: false });+ return;+ }+ const child = spawn(executable, args, {+ cwd,+ detached: process.platform !== 'win32',+ shell: false,+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ let output = '';+ let timedOut = false;+ let settled = false;+ const finish = (code: number | null) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ child.stdout.destroy();+ child.stderr.destroy();+ resolve({ code, output, timedOut });+ };+ child.stdout.on('data', (chunk) => (output += chunk));+ child.stderr.on('data', (chunk) => (output += chunk));+ const timer = setTimeout(() => {+ timedOut = true;+ killEvaluatorTree(child);+ finish(null);+ }, timeoutSeconds * 1000);+ child.on('error', (error) => {+ output += `${error.message}\n`;+ finish(null);+ });+ child.on('close', (code) => finish(code));+ });++const tail = (text: string, lines: number) => text.trimEnd().split('\n').slice(-lines).join('\n');++const printResult = (result: EvaluatorResult) => {+ console.log('========================================');+ if (!result.valid) console.log(` Valid: ${pc.yellow('no (this evaluation does not count)')}`);+ console.log(` Score: ${pc.bold(formatScore(result.score))}`);+ if (result.summary) console.log(` Summary: ${result.summary}`);+ if (result.metrics) {+ console.log(' Metrics:');+ for (const [key, value] of Object.entries(result.metrics)) console.log(` ${key}: ${value}`);+ }+ console.log('========================================');+};++/**+ * Objectives: the score a goal optimises and the command that measures it.+ *+ * Inside a Goal Task run (an operation token) `evaluate` and `objective` act+ * for that run's goal and lane. With a person's login they take the goal id,+ * and an evaluation is recorded in the `manual` lane.+ */+export function registerGoalObjectiveCommands(goal: Command) {+ goal+ .command('set-objective <goal-id>')+ .description('Set the score this goal optimises and the command that measures it')+ .option(+ '--evaluator <command>',+ 'Command that prints the score, run in the working directory (no shell; quote arguments with spaces)',+ )+ .option('--direction <max|min>', 'Whether higher or lower is better', 'max')+ .option('--key <key>', 'Metric series key (default: objective)')+ .option('--title <title>', 'Name of the score')+ .option('--timeout <seconds>', 'Seconds before an evaluation is abandoned')+ .option('--clear', 'Remove the objective')+ .action(+ async (+ goalId: string,+ options: {+ clear?: boolean;+ direction: string;+ evaluator?: string;+ key?: string;+ timeout?: string;+ title?: string;+ },+ ) => {+ if (!options.clear && !options.evaluator)+ throw new Error('Pass --evaluator <command>, or --clear to remove the objective.');+ if (options.direction !== 'max' && options.direction !== 'min')+ throw new Error('--direction must be max or min');+ const result = await (+ await getTrpcClient()+ ).goal.setObjective.mutate({+ id: goalId,+ objective: options.clear+ ? null+ : {+ direction: options.direction,+ evaluator: options.evaluator!,+ key: options.key,+ timeoutSeconds: options.timeout ? Number.parseInt(options.timeout, 10) : undefined,+ title: options.title,+ },+ });+ log.info(result.message);+ },+ );++ goal+ .command('objective [goal-id]')+ .description("Show a goal's objective and the leaderboard of its lanes")+ .option('--json', 'Output JSON')+ .action(async (goalId: string | undefined, options: { json?: boolean }) => {+ const board = await readLeaderboard(goalId);+ if (options.json) return outputJson(board);+ if (!board) return log.info('This goal has no objective.');+ printLeaderboard(board);+ });++ goal+ .command('evaluate')+ .description(+ "Run the goal's evaluator in the current directory, record the score for your lane, and print it",+ )+ .option('-d, --details', 'Also print the tail of the evaluator output')+ .option('--goal <id>', 'The goal, when not run from inside one of its Task runs')+ .option('--timeout <seconds>', "Override the objective's evaluation timeout")+ .action(async (options: { details?: boolean; goal?: string; timeout?: string }) => {+ const board = await readLeaderboard(options.goal);+ if (!board)+ throw new Error('This goal has no objective; set one with `lh goal set-objective`.');+ const timeoutSeconds = options.timeout+ ? Number.parseInt(options.timeout, 10)+ : (board.objective.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS);+ const cwd = process.cwd();+ const started = Date.now();+ const run = await withMachineLock(+ timeoutSeconds,+ () => runEvaluator(board.objective.evaluator, cwd, timeoutSeconds),+ { onWait: () => log.info('Waiting for another evaluation on this machine to finish...') },+ );+ const durationMs = Date.now() - started;+ const result = run.timedOut ? undefined : parseEvaluatorOutput(run.output);+ if (!result) {+ console.log(+ run.timedOut+ ? `Evaluator timed out after ${timeoutSeconds}s.`+ : `Evaluator printed no score (exit code ${run.code}).`,+ );+ console.log(tail(run.output, OUTPUT_TAIL_LINES));+ process.exitCode = 1;+ return;+ }+ printResult(result);+ if (options.details) console.log(pc.dim(tail(run.output, OUTPUT_TAIL_LINES)));++ const input = {+ durationMs,+ fingerprint: workingTreeFingerprint(cwd),+ metrics: result.metrics,+ score: result.score,+ summary: result.summary,+ valid: result.valid,+ };+ const client = await getTrpcClient();+ const recorded = hasOperationToken()+ ? (await client.goal.recordEvaluationOperation.mutate(input)).data+ : (await client.goal.recordEvaluation.mutate({ ...input, id: options.goal! })).data;+ if (recorded.recorded) {+ if (recorded.newBest) log.info(pc.green('New best score for this goal.'));+ else if (recorded.newLaneBest) log.info(pc.green('New best score for your lane.'));+ }+ if (recorded.leaderboard) printLeaderboard({ ...recorded.leaderboard, you: recorded.lane });+ });+}diff --git a/apps/server/src/routers/lambda/__tests__/goal.marksOperation.test.ts b/apps/server/src/routers/lambda/__tests__/goal.marksOperation.test.tsnew file mode 100644index 00000000000..e7fcce28ea3--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/goal.marksOperation.test.ts@@ -0,0 +1,100 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++// The operation token is classified by the real middleware; only the claim+// validator is stubbed, so `heteroAuthKind` is decided the way production does.+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ validateHeteroOperationClaims: vi.fn((claims: Record<string, unknown> | undefined) =>+ claims?.purpose === 'hetero-operation'+ ? { capabilities: ['hetero:ingest'], operation_id: 'op_1', sub: claims.sub }+ : undefined,+ ),+}));++const mockResolve = vi.fn();+vi.mock('@/server/services/heterogeneousAgent/operationPrincipal', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ resolveActiveHeteroOperationPrincipal: mockResolve,+}));++const mockRunNode = vi.fn();+const mockAdd = vi.fn();+const mockJudge = vi.fn();+vi.mock('@/database/models/goalMark', () => ({+ GoalMarkModel: vi.fn(function () {+ return { findRunNode: mockRunNode };+ }),+}));+vi.mock('@/server/services/goal/marks', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ GoalMarkService: vi.fn(function () {+ return { add: mockAdd, judge: mockJudge };+ }),+}));++const { goalRouter } = await import('../goal');++const caller = (authKind: 'operation' | 'user') =>+ goalRouter.createCaller({+ jwtPayload: { userId: 'user-1' },+ oidcAuth: {+ ...(authKind === 'operation' ? { purpose: 'hetero-operation' } : {}),+ sub: 'user-1',+ },+ serverDB: {},+ userId: 'user-1',+ } as never);++const markId = '11111111-1111-4111-8111-111111111111';++describe('goalRouter marks for a Goal Task run', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockResolve.mockResolvedValue({ operationId: 'op_1', userId: 'user-1', workspaceId: 'ws-1' });+ mockRunNode.mockResolvedValue({ agentId: 'agt_1', goalId: 'goal_1', nodeId: 'node_1' });+ mockAdd.mockResolvedValue({ id: markId });+ });++ it('refuses an ordinary user token', async () => {+ await expect(+ caller('user').addMarkOperation({ kind: 'pattern', title: 'fix' }),+ ).rejects.toThrow('An operation-bound token is required');+ });++ it('marks the goal of the token’s own run, authored by that run', async () => {+ await caller('operation').addMarkOperation({ kind: 'hazard', title: 'Do not touch index.ts' });++ expect(mockResolve).toHaveBeenCalledWith(+ expect.objectContaining({ capability: 'hetero:ingest', operationId: 'op_1' }),+ );+ expect(mockRunNode).toHaveBeenCalledWith('op_1');+ expect(mockAdd).toHaveBeenCalledWith(+ 'goal_1',+ { kind: 'hazard', title: 'Do not touch index.ts' },+ { agentId: 'agt_1', nodeId: 'node_1' },+ );+ });++ it('refuses a run that works for no Goal Task, before writing anything', async () => {+ mockRunNode.mockResolvedValue(undefined);++ await expect(+ caller('operation').judgeMarkOperation({ markId, verdict: 'confirms' }),+ ).rejects.toThrow('does not work for a Goal Task');+ expect(mockJudge).not.toHaveBeenCalled();+ });++ it('rejects a kind that is not a mark', async () => {+ await expect(+ caller('operation').addMarkOperation({ kind: 'finding' as never, title: 'x' }),+ ).rejects.toThrow();+ expect(mockAdd).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/goal.objectiveOperation.test.ts b/apps/server/src/routers/lambda/__tests__/goal.objectiveOperation.test.tsnew file mode 100644index 00000000000..7f1b74b9935--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/goal.objectiveOperation.test.ts@@ -0,0 +1,103 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++// The operation token is classified by the real middleware; only the claim+// validator is stubbed, so `heteroAuthKind` is decided the way production does.+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ validateHeteroOperationClaims: vi.fn((claims: Record<string, unknown> | undefined) =>+ claims?.purpose === 'hetero-operation'+ ? { capabilities: ['hetero:ingest'], operation_id: 'op_1', sub: claims.sub }+ : undefined,+ ),+}));++const mockResolve = vi.fn();+vi.mock('@/server/services/heterogeneousAgent/operationPrincipal', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ resolveActiveHeteroOperationPrincipal: mockResolve,+}));++const mockRunNode = vi.fn();+vi.mock('@/database/models/goalMark', () => ({+ GoalMarkModel: vi.fn(function () {+ return { findRunNode: mockRunNode };+ }),+}));++const mockRecord = vi.fn();+const mockLeaderboard = vi.fn();+vi.mock('@/server/services/goal/objective', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ GoalObjectiveService: vi.fn(function () {+ return { leaderboard: mockLeaderboard, recordEvaluation: mockRecord };+ }),+}));++const { goalRouter } = await import('../goal');++const caller = (authKind: 'operation' | 'user') =>+ goalRouter.createCaller({+ jwtPayload: { userId: 'user-1' },+ oidcAuth: {+ ...(authKind === 'operation' ? { purpose: 'hetero-operation' } : {}),+ sub: 'user-1',+ },+ serverDB: {},+ userId: 'user-1',+ } as never);++describe('goalRouter objective for a Goal Task run', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockResolve.mockResolvedValue({ operationId: 'op_1', userId: 'user-1', workspaceId: 'ws-1' });+ mockRunNode.mockResolvedValue({+ agentId: 'agt_1',+ goalId: 'goal_1',+ nodeId: 'node_1',+ taskId: 'task_1',+ });+ mockRecord.mockResolvedValue({ lane: 'node_1', recorded: true });+ mockLeaderboard.mockResolvedValue({ lanes: [] });+ });++ it('refuses an ordinary user token', async () => {+ await expect(+ caller('user').recordEvaluationOperation({ score: 1, valid: true }),+ ).rejects.toThrow('An operation-bound token is required');+ });++ it('records the evaluation for the token’s own run, with its operation', async () => {+ await caller('operation').recordEvaluationOperation({+ fingerprint: 'abc',+ score: 37.5,+ valid: true,+ });++ expect(mockRecord).toHaveBeenCalledWith(+ 'goal_1',+ { fingerprint: 'abc', score: 37.5, valid: true },+ { agentId: 'agt_1', nodeId: 'node_1', operationId: 'op_1', taskId: 'task_1' },+ );+ });++ it('reads the leaderboard naming the run’s lane', async () => {+ const result = await caller('operation').objectiveOperation();++ expect(mockLeaderboard).toHaveBeenCalledWith('goal_1', 'node_1');+ expect(result).toMatchObject({ data: { lanes: [] }, goalId: 'goal_1' });+ });++ it('rejects a score that is not a finite number before recording', async () => {+ await expect(+ caller('operation').recordEvaluationOperation({ score: Number.NaN, valid: true }),+ ).rejects.toThrow();+ expect(mockRecord).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/goal/index.procedures.test.ts b/apps/server/src/routers/lambda/goal/index.procedures.test.tsindex 919c9d2e9a1..31fdc4cc24e 100644--- a/apps/server/src/routers/lambda/goal/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/goal/index.procedures.test.ts@@ -26,6 +26,8 @@ function expected(): Array<> {return [['addEdge', 'mutation', 13],+ ['addMark', 'mutation', 13],+ ['addMarkOperation', 'mutation', 10],['addNode', 'mutation', 13],['advance', 'mutation', 13],['answerClarifications', 'mutation', 13],@@ -45,27 +47,36 @@ function expected(): Array<['eventsOperation', 'query', 9],['graph', 'query', 12],['graphOperation', 'query', 9],+ ['judgeMarkOperation', 'mutation', 10],['list', 'query', 12],['listSubscriptions', 'query', 12],+ ['marks', 'query', 12],+ ['marksOperation', 'query', 9],['metricState', 'query', 12],['metricStateOperation', 'query', 9],+ ['objective', 'query', 12],+ ['objectiveOperation', 'query', 9],['pause', 'mutation', 13],['pendingClarifications', 'query', 11],['pendingForIsland', 'query', 11],['planContext', 'query', 12],['planContextOperation', 'query', 9],['rebindSubscription', 'mutation', 13],+ ['recordEvaluation', 'mutation', 13],+ ['recordEvaluationOperation', 'mutation', 10],['recordObservation', 'mutation', 13],['removeEdge', 'mutation', 13],['removeMetricCriteria', 'mutation', 13],['restart', 'mutation', 13],['resume', 'mutation', 13],+ ['retireMark', 'mutation', 13],['retireNodes', 'mutation', 13],['setAcceptanceCriteria', 'mutation', 13],['setAgent', 'mutation', 13],['setBudget', 'mutation', 13],['setMetricCriteria', 'mutation', 13],['setModel', 'mutation', 13],+ ['setObjective', 'mutation', 13],['setTaskAgent', 'mutation', 13],['setTaskModel', 'mutation', 13],['setVisibility', 'mutation', 13],diff --git a/apps/server/src/routers/lambda/goal/index.ts b/apps/server/src/routers/lambda/goal/index.tsindex e846c003103..25825f9d0d4 100644--- a/apps/server/src/routers/lambda/goal/index.ts+++ b/apps/server/src/routers/lambda/goal/index.ts@@ -4,6 +4,8 @@ import { goalGraphEditProcedures } from '../goalGraphEdit';import { configurationRouter } from './configuration';import { creationRouter } from './creation';import { lifecycleRouter } from './lifecycle';+import { markRouter } from './marks';+import { objectiveRouter } from './objective';import { planningRouter } from './planning';import { readRouter } from './reads';import { subscriptionRouter } from './subscriptions';@@ -11,6 +13,8 @@ import { transferRouter } from './transfer';export const goalRouter = mergeRouters(lifecycleRouter,+ markRouter,+ objectiveRouter,planningRouter,creationRouter,configurationRouter,diff --git a/apps/server/src/routers/lambda/goal/marks.ts b/apps/server/src/routers/lambda/goal/marks.tsnew file mode 100644index 00000000000..a73d5386ba6--- /dev/null+++ b/apps/server/src/routers/lambda/goal/marks.ts@@ -0,0 +1,114 @@+import { GOAL_MARK_KINDS } from '@lobechat/const/goal';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';+import {+ GoalMarkError,+ GoalMarkService,+ MARK_DESCRIPTION_MAX,+ MARK_TITLE_MAX,+} from '@/server/services/goal/marks';++import { goalProcedure, goalWriteProcedure, idInput, mapGoalError } from '../goalProcedures';+import { goalRunOperationProcedure } from './runOperation';++const markInput = z.object({+ description: z.string().max(MARK_DESCRIPTION_MAX).optional(),+ kind: z.enum(GOAL_MARK_KINDS),+ title: z.string().min(1).max(MARK_TITLE_MAX),+});++const mapMarkError = (error: unknown, operation: string): never => {+ if (error instanceof GoalMarkError)+ throw new TRPCError({ cause: error, code: error.code, message: error.message });+ return mapGoalError(error, operation);+};++const markServiceFor = (ctx: {+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}) => new GoalMarkService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);++const markOperationProcedure = goalRunOperationProcedure.use(async (opts) =>+ opts.next({+ ctx: {+ markService: new GoalMarkService(+ opts.ctx.serverDB,+ opts.ctx.principal.userId,+ opts.ctx.principal.workspaceId,+ ),+ },+ }),+);++export const markRouter = router({+ addMark: goalWriteProcedure+ .input(idInput.merge(markInput))+ .mutation(async ({ ctx, input: { id, ...input } }) => {+ try {+ return { data: await markServiceFor(ctx).add(id, input), success: true };+ } catch (error) {+ mapMarkError(error, 'add a mark to');+ }+ }),++ addMarkOperation: markOperationProcedure.input(markInput).mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.markService.add(ctx.run.goalId, input, {+ agentId: ctx.run.agentId,+ nodeId: ctx.run.nodeId,+ });+ return { data, success: true };+ } catch (error) {+ mapMarkError(error, 'add a mark to');+ }+ }),++ judgeMarkOperation: markOperationProcedure+ .input(z.object({ markId: z.string().uuid(), verdict: z.enum(['confirms', 'refutes']) }))+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.markService.judge(ctx.run.goalId, input.markId, input.verdict, {+ agentId: ctx.run.agentId,+ nodeId: ctx.run.nodeId,+ });+ return { data, success: true };+ } catch (error) {+ mapMarkError(error, 'judge a mark of');+ }+ }),++ marks: goalProcedure.input(idInput).query(async ({ ctx, input }) => {+ try {+ return { data: await markServiceFor(ctx).list(input.id), success: true };+ } catch (error) {+ mapMarkError(error, 'list the marks of');+ }+ }),++ marksOperation: markOperationProcedure.query(async ({ ctx }) => {+ try {+ return {+ data: await ctx.markService.list(ctx.run.goalId),+ goalId: ctx.run.goalId,+ success: true,+ };+ } catch (error) {+ mapMarkError(error, 'list the marks of');+ }+ }),++ retireMark: goalWriteProcedure+ .input(idInput.extend({ markId: z.string().uuid(), reason: z.string().optional() }))+ .mutation(async ({ ctx, input }) => {+ try {+ await markServiceFor(ctx).retire(input.id, input.markId, input.reason);+ return { message: 'Mark retired', success: true };+ } catch (error) {+ mapMarkError(error, 'retire a mark of');+ }+ }),+});diff --git a/apps/server/src/routers/lambda/goal/objective.ts b/apps/server/src/routers/lambda/goal/objective.tsnew file mode 100644index 00000000000..694bfa428b7--- /dev/null+++ b/apps/server/src/routers/lambda/goal/objective.ts@@ -0,0 +1,120 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';+import { GoalObjectiveError, GoalObjectiveService } from '@/server/services/goal/objective';++import { goalProcedure, goalWriteProcedure, idInput, mapGoalError } from '../goalProcedures';+import { goalRunOperationProcedure } from './runOperation';++const objectiveInput = z.object({+ direction: z.enum(['max', 'min']),+ evaluator: z.string().min(1).max(4000),+ key: z+ .string()+ .regex(/^[\w.-]{1,100}$/)+ .optional(),+ timeoutSeconds: z.number().int().min(10).max(86_400).optional(),+ title: z.string().max(200).optional(),+});++const evaluationInput = z.object({+ durationMs: z.number().int().min(0).optional(),+ fingerprint: z.string().max(128).optional(),+ metrics: z.record(z.string().max(100), z.number().finite()).optional(),+ score: z.number().finite(),+ summary: z.string().max(4000).optional(),+ valid: z.boolean(),+});++const mapObjectiveError = (error: unknown, operation: string): never => {+ if (error instanceof GoalObjectiveError)+ throw new TRPCError({ cause: error, code: error.code, message: error.message });+ return mapGoalError(error, operation);+};++const objectiveServiceFor = (ctx: {+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}) => new GoalObjectiveService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);++const operationObjectiveProcedure = goalRunOperationProcedure.use(async (opts) =>+ opts.next({+ ctx: {+ objectiveService: new GoalObjectiveService(+ opts.ctx.serverDB,+ opts.ctx.principal.userId,+ opts.ctx.principal.workspaceId,+ ),+ },+ }),+);++export const objectiveRouter = router({+ /** The objective and its leaderboard; `data` is null when the goal has none. */+ objective: goalProcedure.input(idInput).query(async ({ ctx, input }) => {+ try {+ return {+ data: (await objectiveServiceFor(ctx).leaderboard(input.id)) ?? null,+ success: true,+ };+ } catch (error) {+ mapObjectiveError(error, 'read the objective of');+ }+ }),++ /** The same read for a Goal Task run, for its own goal. */+ objectiveOperation: operationObjectiveProcedure.query(async ({ ctx }) => {+ try {+ return {+ data: (await ctx.objectiveService.leaderboard(ctx.run.goalId, ctx.run.nodeId)) ?? null,+ goalId: ctx.run.goalId,+ success: true,+ };+ } catch (error) {+ mapObjectiveError(error, 'read the objective of');+ }+ }),++ /** A person records an evaluation they ran themselves (lane `manual`). */+ recordEvaluation: goalWriteProcedure+ .input(idInput.merge(evaluationInput))+ .mutation(async ({ ctx, input: { id, ...input } }) => {+ try {+ return { data: await objectiveServiceFor(ctx).recordEvaluation(id, input), success: true };+ } catch (error) {+ mapObjectiveError(error, 'record an evaluation on');+ }+ }),++ /** A Goal Task run records the evaluation of its working directory, in its lane. */+ recordEvaluationOperation: operationObjectiveProcedure+ .input(evaluationInput)+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.objectiveService.recordEvaluation(ctx.run.goalId, input, {+ agentId: ctx.run.agentId,+ nodeId: ctx.run.nodeId,+ operationId: ctx.run.operationId,+ taskId: ctx.run.taskId,+ });+ return { data, success: true };+ } catch (error) {+ mapObjectiveError(error, 'record an evaluation on');+ }+ }),++ /** Set the objective, or clear it with `objective: null`. */+ setObjective: goalWriteProcedure+ .input(idInput.extend({ objective: objectiveInput.nullable() }))+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await objectiveServiceFor(ctx).setObjective(input.id, input.objective);+ return { data, message: data ? 'Objective set' : 'Objective cleared', success: true };+ } catch (error) {+ mapObjectiveError(error, 'set the objective of');+ }+ }),+});diff --git a/apps/server/src/routers/lambda/goal/runOperation.ts b/apps/server/src/routers/lambda/goal/runOperation.tsnew file mode 100644index 00000000000..ee7a8012792--- /dev/null+++ b/apps/server/src/routers/lambda/goal/runOperation.ts@@ -0,0 +1,64 @@+import { TRPCError } from '@trpc/server';++import { GoalMarkModel } from '@/database/models/goalMark';+import { heteroAuthedProcedure } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import {+ HeteroOperationPrincipalError,+ resolveActiveHeteroOperationPrincipal,+} from '@/server/services/heterogeneousAgent/operationPrincipal';++/**+ * The run a device or gateway Task holds an operation token for, and the Goal+ * Task node it works for.+ *+ * Marks and evaluations come from inside a run, from exactly the runs that hold+ * operation tokens — and `oidcAuth` refuses those on ordinary routes. The Goal+ * is never an input: it is the one whose Task node the operation runs, so a+ * token reaches its own Goal and no other. `hetero:ingest` is what every such+ * run already carries.+ */+export const goalRunOperationProcedure = heteroAuthedProcedure+ .use(serverDatabase)+ .use(async (opts) => {+ if (opts.ctx.heteroAuthKind !== 'operation' || !opts.ctx.heteroOperation) {+ throw new TRPCError({+ code: 'UNAUTHORIZED',+ message: 'An operation-bound token is required',+ });+ }+ let principal;+ try {+ principal = await resolveActiveHeteroOperationPrincipal({+ capability: 'hetero:ingest',+ claims: opts.ctx.heteroOperation,+ db: opts.ctx.serverDB,+ operationId: opts.ctx.heteroOperation.operation_id,+ });+ } catch (error) {+ if (!(error instanceof HeteroOperationPrincipalError)) throw error;+ throw new TRPCError({+ cause: error,+ code:+ error.status === 401 ? 'UNAUTHORIZED' : error.status === 409 ? 'CONFLICT' : 'FORBIDDEN',+ message: error.message,+ });+ }+ const run = await new GoalMarkModel(+ opts.ctx.serverDB,+ principal.userId,+ principal.workspaceId,+ ).findRunNode(principal.operationId);+ if (!run) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'This run does not work for a Goal Task',+ });+ }+ return opts.next({+ ctx: {+ principal: { userId: principal.userId, workspaceId: principal.workspaceId },+ run: { ...run, operationId: principal.operationId },+ },+ });+ });diff --git a/apps/server/src/services/goal/GoalService/__tests__/planning.test.ts b/apps/server/src/services/goal/GoalService/__tests__/planning.test.tsindex 71bb03a4cf5..1f9a390bad0 100644--- a/apps/server/src/services/goal/GoalService/__tests__/planning.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/planning.test.ts@@ -193,7 +193,9 @@ describe('GoalService', () => {// ① Only the K probes exist as Tasks — the whole 50-unit fan-out never lands.expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(5);expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(1);- expect(after.nodes.filter((n) => n.kind === 'finding')).toHaveLength(1);+ // The recipe is a `template` node now, no longer a `finding` with its title.+ expect(after.nodes.filter((n) => n.kind === 'template')).toHaveLength(1);+ expect(after.nodes.filter((n) => n.kind === 'finding')).toHaveLength(0);expect(after.nodes.filter((n) => n.kind === 'decision')).toHaveLength(1);const state = after.goal.config?.rolloutState;@@ -212,7 +214,7 @@ describe('GoalService', () => {// Five probes inside the batch — never the whole 50-unit roster.expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'task')).toHaveLength(5);// Plus the one Template and the one Assay that make the batch a batch.- expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'finding')).toHaveLength(+ expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'template')).toHaveLength(1,);expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'decision')).toHaveLength(diff --git a/apps/server/src/services/goal/GoalService/completion.ts b/apps/server/src/services/goal/GoalService/completion.tsindex 5e21f032234..b906e68ad0e 100644--- a/apps/server/src/services/goal/GoalService/completion.ts+++ b/apps/server/src/services/goal/GoalService/completion.ts@@ -431,8 +431,13 @@ export const consumeCompletedTask = async (taskId,};}+ // Only a finding counts: a mark the run left also hangs off the node by+ // `produces`, and must not stand in for the outcome.const existingFinding = graph.edges.some(- (edge) => edge.sourceNodeId === nodeId && edge.kind === 'produces',+ (edge) =>+ edge.sourceNodeId === nodeId &&+ edge.kind === 'produces' &&+ graph.nodes.find((node) => node.id === edge.targetNodeId)?.kind === 'finding',);// The newest row by seq can be a retry that was canceled when verification// accepted an earlier delivery — the settle path cancels the in-flightdiff --git a/apps/server/src/services/goal/GoalService/rollout.ts b/apps/server/src/services/goal/GoalService/rollout.tsindex 704710c45c7..5435137efc6 100644--- a/apps/server/src/services/goal/GoalService/rollout.ts+++ b/apps/server/src/services/goal/GoalService/rollout.ts@@ -10,6 +10,7 @@ import {ROLLOUT_MAX_CANARY_SIZE,} from '@lobechat/const/goal';import type { GoalGraphSnapshot, GoalTickResult } from '@lobechat/types';+import { isBatchTemplate } from '@lobechat/utils/goalGraph';import { type ExpertiseCarrier, ExpertiseModel } from '@/database/models/expertise';import { GoalGraphModel } from '@/database/models/goalGraph';@@ -278,7 +279,7 @@ export const restartRolloutLoop = async (// 1. A new recipe revision, or a forked new class (no `revises` chain).const template = await writer.createNode(goalId, {description: revisedOutline || baseOutline,- kind: 'finding',+ kind: 'template',scopeId: batchId,title: GOAL_BATCH_TEMPLATE_TITLE,});@@ -323,12 +324,7 @@ export const restartRolloutLoop = async (.map((edge) => edge.targetNodeId),);const earlier = graph.nodes- .filter(- (node) =>- node.kind === 'finding' &&- node.title === GOAL_BATCH_TEMPLATE_TITLE &&- inBatch.has(node.id),- )+ .filter((node) => isBatchTemplate(node) && inBatch.has(node.id)).sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()).map((node) => node.description?.trim() ?? '');planSkill = await inSavepoint('plan skill adoption', (db) =>diff --git a/apps/server/src/services/goal/SWARM.md b/apps/server/src/services/goal/SWARM.mdnew file mode 100644index 00000000000..a6e43c72fad--- /dev/null+++ b/apps/server/src/services/goal/SWARM.md@@ -0,0 +1,236 @@+# Swarm Goals — design++Status: design, not built. Builds on Goal marks (`marks.ts`, commit 0f5d9bb672a).++## Why++A Goal today plans a task graph and verifies each Task. That fits building and migrating;+it fits badly when the work is *optimising one score against an evaluator* — tune a model,+raise a benchmark, cut a latency — where progress is "submit, read the score, change,+submit again".++We measured it on EdgeBench (`k12_math_recommendation`, Kimi Code, 2 h wall clock; harness+and raw data in `~/CodeProjects/edgebench-eval`, see its `RESULTS.md`):++| Shape | runs | score @2h (mean) | @30m | output tokens |+|---|---|---|---|---|+| Single Kimi session | 7 | 33.6 (sd 4.5) | — | 133k |+| Today's Goal (planner splits into serial tasks) | 1 | 21.8 | 16.2 | 219k |+| 3 independent sessions, keep the best | 2 | 37.0 | 34.2 | 607k |+| 3 lanes + marks (no coordination) | 1 | 34.7 | 34.2 | 374k |+| 3 lanes + marks + coordinator | 3 | 37.4 | 26.5 | 409k |++What this says:++1. **Parallel lanes scored against an evaluator are the win** (+3.5–4 over one session):+ a single agent's result varies a lot, and keeping the best of several removes the bad+ draws.+2. **Marks plus a coordinator matched best-of-N on score at about two thirds of the+ tokens.** Lanes stopped re-debugging each other's pitfalls and reused what worked. They+ did not raise the score beyond the noise at 2 h.+3. **Serial decomposition is the wrong shape here.** Splitting by component broke the+ submit loop, and per-Task acceptance spent the time budget on evidence.+4. **Uncoordinated sharing collapses diversity.** Lanes copied the leader and ended on+ identical code.+5. **Forcing different approaches from minute 0 costs the early score** (26.5 vs 34.2 at+ 30 min), because slow approaches start late.++Swarm mode is the shape that matched those results, built into Goals.++## Scope++A Swarm Goal is an optimisation Goal:++- an **evaluator**: a command that scores the current deliverables;+- an **objective**: maximise or minimise that score;+- a **timebox**: a deadline, or a token / cost budget;+- **N lanes**: parallel copies of the workspace, one long-running Task each.++It is not a replacement for planned Goals. Builds, migrations and anything without a+scoring command keep today's planner. A planner may *propose* swarm mode when the+requirement names a metric and an evaluator.++## Concepts++| Concept | What it is | Built on |+|---|---|---|+| Lane | An independent copy of the workspace, plus the time-boxed Task that works in it | `experiment` container node; per-topic working directory |+| Evaluator | A command run inside a lane that prints a score (plain number, `TOTAL_SCORE n`, or JSON `{score, valid, summary, metrics}`) | new `lh goal evaluate` |+| Objective series | One metric series per Goal; each evaluation is a point tagged with lane, run and code fingerprint | metric series and observations (`metric` router, north-star criteria) |+| Leaderboard | Each lane's best and latest valid score, the leader, time since the last new best | derived from the objective series |+| Directive | A coordinator instruction addressed to one lane | new mark kind `directive` |+| Champion | The best-scoring lane state when the run ends; promoted back to the root workspace | — |++## User flow++```sh+lh goal create "Raise k12 score" \+ --swarm 3 \+ --workspace ~/proj/k12 \+ --evaluator './.eb/submit' \+ --objective max \+ --deadline 2h \+ --task-agent <kimi-or-cc-agent>+```++- The Goal page shows the leaderboard: one row per lane, with its best score, a sparkline,+ and its current direction. Below that come directives and marks, and the champion with+ a "promote" action.+- Each lane run sees the usual `<goal_marks>`. Directives addressed to that lane come+ first, then the leaderboard.+- An agent calls `lh goal evaluate` instead of the raw evaluator. It runs the configured+ command in the lane, records the point, and prints the score and feedback.++## Architecture++### 1. Lanes and workspaces++- Lanes are `experiment` container nodes, one lane Task inside each; `config.swarm` records+ the lanes. This reuses containment, collapse and drill-down in the graph UI.+- **Where a lane runs** decides how it gets its own workspace:+ - **Device**: a plain directory copy, no git worktree. On the lane's first run+ `lh hetero exec` copies the workspace into `<workspace>/.lanes/<lane>` — `cp -c`+ (APFS clone) / `cp --reflink=auto`, falling back to a normal copy — `.git` included, so+ each lane is a self-contained repo that nothing else writes to. The coordinator+ dispatches the lane Task with `initialTopicMetadata.workingDirectory` set to that+ directory; topic metadata already wins over the agent's per-device default+ (`topicWorkingDirectory.ts`), so cwd resolution is unchanged.+ - **Sandbox**: nothing to split. Every lane is its own sandbox started from the same+ workspace source, so isolation comes for free.+- **Sharing between lanes goes through the server, never through another lane's files.**+ Each `lh goal evaluate` uploads the archive of the deliverables it just graded (the+ evaluator's declared paths, small by construction) as a Work version linked to the lane.+ `lh goal lane adopt <lane>` downloads that lane's latest valid archive into the calling+ lane, keeping a local snapshot for rollback. Devices and sandboxes use the same path, and+ the champion is simply the best valid archive.++### 2. Evaluator and objective++`lh goal evaluate [-d]` does the following in order:++1. Takes the lane from the run's operation token. That resolution path is the one marks+ already use: operation → task → goal node, here also → lane container.+2. Runs `config.swarm.evaluator` in the lane directory. Evaluations are serialised per+ device by a lock, because evaluators are often heavy.+3. Parses the score.+4. Uploads the graded deliverables archive as a Work version on the lane (what `lane adopt`+ and the champion read).+5. Writes a metric point on the Goal's objective series:+ - `actorType: agent`, `sourceType: probe`;+ - `metadata: {lane, taskId, operationId, fingerprint, valid, summary}`;+ - `fingerprint` is a hash of the evaluator's declared deliverable paths, or of+ `git diff HEAD` in the lane.+6. Prints the score and feedback to the agent.++The objective is a north-star criterion, so the existing metric gate (#19133) and the+metric UI apply without new storage. The leaderboard is a read model over the series+grouped by `metadata.lane`.++Trust: the evaluator runs in the agent's environment, so a determined agent can forge a+score. That is acceptable for a user's own optimisation work, and the prompt forbids it as+the benchmark prompt did. For anything public, the evaluator can be bound to a sandbox or+remote judge later; the series format does not change.++### 3. Timeboxed lane Tasks++- A lane Task is complete only at the deadline.+- A lane run that ends early is re-dispatched immediately with a continuation brief. It+ goes through no verification and charges no attempt. The benchmark harness did this by+ making acceptance fail before the deadline; this replaces that trick with real+ semantics.+- Lane Tasks carry no per-Task acceptance. The objective is the acceptance.+- At the deadline the coordinator:+ 1. stops lane runs (operation cancel);+ 2. runs one final evaluation per lane;+ 3. picks the champion — the best valid point, tie-broken by recency;+ 4. marks the Goal achieved if the objective criterion is met, otherwise `paused` with+ the champion recorded.+- A token or cost budget ends the run the same way when it runs out first. It reuses+ `evaluateBudget`.++### 4. Coordinator policy++The policy is a pure function over the leaderboard, the lane fingerprints and the marks.+It runs in the goal tick every 10 minutes, or on each new point, rate-limited. It was+prototyped as `harness/coordinator.py` in `~/CodeProjects/edgebench-eval`.++| Signal | Condition (defaults) | Action |+|---|---|---|+| Leaderboard | every tick | refresh the single leaderboard mark, which is pinned in prompts |+| Converged | two lanes share a fingerprint | keep one, give the others new directions |+| Stagnant | no new global best for 25 min (scaled to the timebox) | new directions for every lane |+| Lagging | a lane is more than 3 points or 10% behind the leader after 30% of the timebox | adopt the leader, then a direction |+| Warm-up | before the first valid score in any lane | none: lanes start free to get a runnable version fast |++Directions come from one system-model call per decision. Its inputs are the task+requirement, the leaderboard, recent marks and the lanes that need a direction, and it+returns one direction per lane. Each direction is written as a `directive` mark addressed+to its lane. A lane gets at most one live directive; a new one retires the old one, with a+20-minute cooldown.++The warm-up row is the one change from the prototype. The benchmark showed that forcing+diversity at minute 0 cost about 8 points at 30 min. Planned starting approaches become+optional (`--diverse-start`), and diversification starts after the first valid score.++### 5. Marks++The existing marks need no schema change. Score and lane live in the objective series,+and a mark's author lane is its `produces` source inside the lane container. Two additions:++- **Kind `directive`.** It is written only by the coordinator and carries `scopeId` = its+ lane. It ranks first in that lane's `<goal_marks>`, and other lanes do not see it.+- **The leaderboard is a pinned `pattern` written by the coordinator.** It is retired and+ replaced on each tick, so only one is live.++The `signature` column planned for pain detection stays a separate change.++### 6. Cost controls++- The lane count is capped by `maxConcurrentTasks`.+- Per-lane token accounting comes from operations. The leaderboard shows tokens per lane+ next to its score.+- Reclaim: a lagging lane that ignores two directives is stopped and re-forked from the+ champion.+- A Goal-level token budget is an alternative to the deadline. For a fixed budget, swarm+ spends it about a third faster on coordination-free sharing than independent best-of-N+ does.++## Delivery plan++All of it sits behind the Agent Lab gate (`useAgentLabGate`) until the benchmark target+below holds.++| PR | Content | Depends on |+|---|---|---|+| 1 | Goal marks (done, 0f5d9bb672a) | — |+| 2 | `config.objective`, `lh goal set-objective` / `evaluate` / `objective`, objective series with lane metadata, operation-token write path, leaderboard read model, `<goal_objective>` prompt section, per-machine evaluation lock (built) | 1 |+| 3 | `config.swarm`, lane containers, per-lane directory (device) / per-lane sandbox, graded-archive upload and `lane adopt`, timeboxed lane Tasks, deadline wrap-up and champion | 2 |+| 4 | Coordinator policy in tick, `directive` marks, prompt pinning | 3 |+| 5 | Goal page leaderboard and champion promote (web) | 2 (reads), 4 |++Each PR's acceptance includes the EdgeBench harness on `k12_math_recommendation`+(3 lanes, 2 h, Kimi Code). The bar for removing the Lab gate is:++- the score is at least best-of-3 independent sessions (≥ 37.0 mean over 3 runs);+- output tokens are at most 0.75× best-of-3;+- the 30-minute score is no worse than best-of-3, which the warm-up phase must buy back.++## Decisions++Everything defaults to automatic.++- **The planner selects swarm mode on its own** when the requirement names a score or metric+ to push and a command that produces it (an evaluator script, a benchmark, a test that+ prints a number). It infers the evaluator, the direction and the deadline from the+ requirement. The lane count is `min(3, maxConcurrentTasks)` unless the user sets it.+ `--swarm` / `--no-swarm` override the choice.+- **The champion is promoted automatically at wrap-up.** The best valid archive is+ unpacked over the root workspace, after the root's previous state has been kept as a+ snapshot: a Work version, plus `.lanes/_before_promote` on devices. A one-click restore+ undoes the promotion. The Goal report states what was promoted and from which lane.+- **Evaluations queue per machine, not globally.** Each device (or sandbox) evaluates only+ its own lanes, and a per-machine lock keeps heavy evaluators from running at the same+ time on one host. A global limit is needed only when the evaluator calls a shared+ external resource, such as a rate-limited judge API. For that case+ `config.swarm.maxConcurrentEvaluations` (default: unlimited) is enforced by the server+ through a short lease taken by `lh goal evaluate`.diff --git a/apps/server/src/services/goal/graphCompat.test.ts b/apps/server/src/services/goal/graphCompat.test.tsindex 6fd7865390f..0f1d0e4cd98 100644--- a/apps/server/src/services/goal/graphCompat.test.ts+++ b/apps/server/src/services/goal/graphCompat.test.ts@@ -26,3 +26,47 @@ describe('graphForClient', () => {expect(graphForClient(graph, ['batch'])).toBe(graph);});});++describe('graphForClient with marks', () => {+ const marked = {+ edges: [+ { id: 'e1', kind: 'confirms', sourceNodeId: 't', targetNodeId: 'm' },+ { id: 'e2', kind: 'refutes', sourceNodeId: 't', targetNodeId: 'h' },+ { id: 'e3', kind: 'produces', sourceNodeId: 't', targetNodeId: 'm' },+ ],+ nodes: [+ { id: 't', kind: 'task' },+ { id: 'm', kind: 'pattern' },+ { id: 'h', kind: 'hazard' },+ { id: 'r', kind: 'template' },+ ],+ } as unknown as GoalGraphSnapshot;++ it('sends marks and recipes as findings, and their judgements as supports / contradicts', () => {+ const legacy = graphForClient(marked, ['batch']);+ expect(legacy.nodes.map((node) => node.kind)).toEqual([+ 'task',+ 'finding',+ 'finding',+ 'finding',+ ]);+ expect(legacy.edges.map((edge) => edge.kind)).toEqual(['supports', 'contradicts', 'produces']);+ });++ it('keeps a recipe-only graph’s edges untouched', () => {+ const recipe = {+ edges: [{ id: 'e', kind: 'contains', sourceNodeId: 'b', targetNodeId: 'r' }],+ nodes: [+ { id: 'b', kind: 'batch' },+ { id: 'r', kind: 'template' },+ ],+ } as unknown as GoalGraphSnapshot;+ const legacy = graphForClient(recipe, ['batch']);+ expect(legacy.nodes[1].kind).toBe('finding');+ expect(legacy.edges).toBe(recipe.edges);+ });++ it('keeps the real kinds for a client that renders marks', () => {+ expect(graphForClient(marked, ['batch', 'marks'])).toBe(marked);+ });+});diff --git a/apps/server/src/services/goal/graphCompat.ts b/apps/server/src/services/goal/graphCompat.tsindex e7b256cbd6c..78c43423704 100644--- a/apps/server/src/services/goal/graphCompat.ts+++ b/apps/server/src/services/goal/graphCompat.ts@@ -1,5 +1,12 @@import { GOAL_GRAPH_CAPABILITY } from '@lobechat/const/goal';-import type { GoalGraphSnapshot } from '@lobechat/types';+import type { GoalEdgeKind, GoalGraphSnapshot, GoalNodeKind } from '@lobechat/types';+import { isMarkKind } from '@lobechat/utils/goalGraph';++/** The edge kinds a client without the `marks` capability already draws. */+const LEGACY_MARK_EDGE: Partial<Record<GoalEdgeKind, GoalEdgeKind>> = {+ confirms: 'supports',+ refutes: 'contradicts',+};/*** The graph as a client that declared `capabilities` can render it.@@ -9,17 +16,37 @@ import type { GoalGraphSnapshot } from '@lobechat/types';* client declares the capability, a batch goes out as an `experiment` — the* container those clients already draw, holding the same members — and only a* client that knows batches sees the real kind.+ *+ * Marks and `template` go out as `finding` the same way: a recipe was a+ * `finding` before it had a kind of its own, so an older client still finds it+ * by its title, and a mark reads as the note it is. Their `confirms` /+ * `refutes` edges become `supports` / `contradicts`.*/export const graphForClient = (graph: GoalGraphSnapshot,capabilities: readonly string[] = [],): GoalGraphSnapshot => {- if (capabilities.includes(GOAL_GRAPH_CAPABILITY.batch)) return graph;- if (!graph.nodes.some((node) => node.kind === 'batch')) return graph;+ const batches = capabilities.includes(GOAL_GRAPH_CAPABILITY.batch);+ const marks = capabilities.includes(GOAL_GRAPH_CAPABILITY.marks);+ const legacyKind = (kind: GoalNodeKind): GoalNodeKind => {+ if (!batches && kind === 'batch') return 'experiment';+ if (!marks && (kind === 'template' || isMarkKind(kind))) return 'finding';+ return kind;+ };+ if (!graph.nodes.some((node) => legacyKind(node.kind) !== node.kind)) return graph;+ // Only marks carry `confirms` / `refutes`, so a graph with none keeps its edges.+ const downgradesMarks = !marks && graph.nodes.some((node) => isMarkKind(node.kind));return {...graph,- nodes: graph.nodes.map((node) =>- node.kind === 'batch' ? { ...node, kind: 'experiment' as const } : node,- ),+ ...(downgradesMarks && {+ edges: graph.edges.map((edge) => {+ const kind = LEGACY_MARK_EDGE[edge.kind];+ return kind ? { ...edge, kind } : edge;+ }),+ }),+ nodes: graph.nodes.map((node) => {+ const kind = legacyKind(node.kind);+ return kind === node.kind ? node : { ...node, kind };+ }),};};diff --git a/apps/server/src/services/goal/manager/turnState.ts b/apps/server/src/services/goal/manager/turnState.tsindex 77572074f26..28a4a7d73fc 100644--- a/apps/server/src/services/goal/manager/turnState.ts+++ b/apps/server/src/services/goal/manager/turnState.ts@@ -1,6 +1,7 @@import { createHash, randomUUID } from 'node:crypto';import type { GoalGraphSnapshot, GoalManagerState } from '@lobechat/types';+import { withoutMarks } from '@lobechat/utils/goalGraph';import { eq, sql } from 'drizzle-orm';import type { AgentOperationModel } from '@/database/models/agentOperation';@@ -49,7 +50,9 @@ export const managerTurnToken = (goalId: string) => `${goalId}_${randomUUID()}`;* node look stale, so `startTurn` re-queued itself every five seconds forever.*/export const managerSnapshot = (input: GoalGraphSnapshot) => {- const graph = withoutGoalReport(input);+ // Marks are left by Tasks that keep running during a takeover turn; they are+ // context, not planning input, so they must not make the turn's plan stale.+ const graph = withoutMarks(withoutGoalReport(input));// Coordinator receipts are not planning input: arming a Task's quota wake while a// turn runs must not make that turn's plan stale, and neither may the system// planner's lease — a hand-over starts the turn while the lease is still helddiff --git a/apps/server/src/services/goal/marks.test.ts b/apps/server/src/services/goal/marks.test.tsnew file mode 100644index 00000000000..f60edd05acc--- /dev/null+++ b/apps/server/src/services/goal/marks.test.ts@@ -0,0 +1,189 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { goalExplorationSnapshot } from '@/database/models/goalExploration';+import { TaskModel } from '@/database/models/task';+import { taskTopics, topics } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { GoalService } from './GoalService';+import { managerSnapshot } from './manager/turnState';+import {+ activeMarks,+ GoalMarkService,+ markConfidence,+ MARKS_IN_PROMPT,+ marksForPrompt,+} from './marks';+import { registerGoalServiceTestCleanup } from './testUtils';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-mark-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++/** A goal whose first Task has a run, so that run's operation resolves to its node. */+const goalWithRun = async (operationId: string) => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Migrate the store'], title: 'Marks goal' });+ const { nodeId, taskId } = await service.tick(graph.goal.id);+ const topicId = `tpc_${operationId}`;+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB+ .insert(taskTopics)+ .values({ operationId, seq: 1, taskId: taskId!, topicId, userId });+ return { goalId: graph.goal.id, nodeId: nodeId!, service };+};++describe('markConfidence', () => {+ it('starts an unjudged mark at an even chance and never pins it', () => {+ expect(markConfidence(0, 0)).toBe(0.5);+ expect(markConfidence(2, 0)).toBe(0.75);+ expect(markConfidence(0, 2)).toBe(0.25);+ expect(markConfidence(100, 0)).toBeLessThan(1);+ });+});++describe('GoalMarkService', () => {+ it('finds the Goal Task a run works for from its operation, and nothing for a stranger', async () => {+ const { goalId, nodeId } = await goalWithRun('op_mark_resolve');+ const marks = new GoalMarkService(serverDB, userId);++ expect(await marks.runNode('op_mark_resolve')).toMatchObject({ goalId, nodeId });+ expect(await marks.runNode('op_unknown')).toBeUndefined();+ // Another user's token never reaches this run's goal.+ expect(+ await new GoalMarkService(serverDB, 'someone-else').runNode('op_mark_resolve'),+ ).toBeUndefined();+ });++ it('hangs a mark off the run that left it and makes it Goal-wide', async () => {+ const { goalId, nodeId, service } = await goalWithRun('op_mark_add');+ const marks = new GoalMarkService(serverDB, userId);++ const mark = await marks.add(+ goalId,+ { description: 'Run `bun i` first', kind: 'pattern', title: ' Missing dep → install ' },+ { nodeId },+ );++ const graph = await service.graph(goalId);+ expect(graph.nodes.find((node) => node.id === mark.id)).toMatchObject({+ kind: 'pattern',+ status: 'active',+ title: 'Missing dep → install',+ });+ expect(graph.edges).toContainEqual(+ expect.objectContaining({ kind: 'produces', sourceNodeId: nodeId, targetNodeId: mark.id }),+ );+ // Not contained in any experiment: every Task of the goal sees it.+ expect(+ graph.edges.some((edge) => edge.kind === 'contains' && edge.targetNodeId === mark.id),+ ).toBe(false);+ });++ it('moves a mark’s confidence with each run that judged it, once per verdict', async () => {+ const { goalId, nodeId, service } = await goalWithRun('op_mark_judge');+ const marks = new GoalMarkService(serverDB, userId);+ const mark = await marks.add(goalId, { kind: 'tool', title: 'codemod.ts' });++ expect((await marks.judge(goalId, mark.id, 'confirms', { nodeId })).confidence).toBeCloseTo(+ 2 / 3,+ );+ // The same run confirming again changes nothing.+ expect((await marks.judge(goalId, mark.id, 'confirms', { nodeId })).confirms).toBe(1);+ const refuted = await marks.judge(goalId, mark.id, 'refutes', { nodeId });+ expect(refuted).toMatchObject({ confirms: 1, refutes: 1 });+ expect(refuted.confidence).toBe(0.5);++ const stored = (await service.graph(goalId)).nodes.find((node) => node.id === mark.id);+ expect(Number(stored?.confidence)).toBe(0.5);+ });++ it('refuses to judge something that is not a mark', async () => {+ const { goalId, nodeId } = await goalWithRun('op_mark_refuse');+ const marks = new GoalMarkService(serverDB, userId);++ await expect(marks.judge(goalId, nodeId, 'confirms', { nodeId })).rejects.toThrow(/No mark/);+ });++ it('keeps marks out of the snapshots a planner’s answer is checked against', async () => {+ const { goalId, nodeId, service } = await goalWithRun('op_mark_snapshot');+ const before = await service.graph(goalId);+ const marks = new GoalMarkService(serverDB, userId);++ const mark = await marks.add(+ goalId,+ { kind: 'hazard', title: 'Do not touch index.ts' },+ { nodeId },+ );+ await marks.judge(goalId, mark.id, 'confirms', { nodeId });++ const after = await service.graph(goalId);+ expect(after.nodes.length).toBeGreaterThan(before.nodes.length);+ expect(goalExplorationSnapshot(after)).toBe(goalExplorationSnapshot(before));+ expect(managerSnapshot(after)).toBe(managerSnapshot(before));+ });++ it('hands a run hazards first, then the most trusted, and drops retired or refuted ones', async () => {+ const { goalId, nodeId, service } = await goalWithRun('op_mark_rank');+ const marks = new GoalMarkService(serverDB, userId);+ const plain = await marks.add(goalId, { kind: 'pattern', title: 'plain' });+ const trusted = await marks.add(goalId, { kind: 'pattern', title: 'trusted' });+ const hazard = await marks.add(goalId, { kind: 'hazard', title: 'hazard' });+ const wrong = await marks.add(goalId, { kind: 'dead_end', title: 'wrong' });+ const retired = await marks.add(goalId, { kind: 'tool', title: 'retired' });+ await marks.judge(goalId, trusted.id, 'confirms', { nodeId });+ await marks.judge(goalId, wrong.id, 'refutes', { nodeId });+ await marks.retire(goalId, retired.id, 'replaced');++ const ranked = activeMarks(await service.graph(goalId)).map((mark) => mark.id);++ // `wrong` sits at 1/3 — still above the floor after a single refutation.+ expect(ranked).toEqual([hazard.id, trusted.id, plain.id, wrong.id]);+ });++ it('caps the marks a prompt lists and says how many it left out', async () => {+ const { goalId, service } = await goalWithRun('op_mark_cap');+ const marks = new GoalMarkService(serverDB, userId);+ for (let i = 0; i < MARKS_IN_PROMPT + 2; i++)+ await marks.add(goalId, { kind: 'pattern', title: `pattern ${i}` });++ const prompt = marksForPrompt(await service.graph(goalId));++ expect(prompt.marks).toHaveLength(MARKS_IN_PROMPT);+ expect(prompt.omitted).toBe(2);+ });++ it('still records the outcome of a Task that left a mark while it ran', async () => {+ // A mark hangs off its Task by `produces`, the same edge an outcome finding+ // uses; settling must not read the mark as the finding already written.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Migrate a slice'], title: 'Outcome after mark' });+ const { nodeId, taskId } = await service.tick(graph.goal.id);+ await serverDB.insert(topics).values({ id: 'tpc_outcome', userId });+ await serverDB.insert(taskTopics).values({+ handoff: { summary: 'Slice migrated', title: 'Slice migrated' },+ operationId: 'op_outcome',+ seq: 1,+ status: 'completed',+ taskId: taskId!,+ topicId: 'tpc_outcome',+ userId,+ });+ await new GoalMarkService(serverDB, userId).add(+ graph.goal.id,+ { kind: 'pattern', title: 'mock internal_ actions' },+ { nodeId: nodeId! },+ );+ await new TaskModel(serverDB, userId).updateStatus(taskId!, 'completed');++ await service.tick(graph.goal.id);++ const after = await service.graph(graph.goal.id);+ expect(after.nodes.find((node) => node.kind === 'finding')).toMatchObject({+ title: 'Slice migrated',+ });+ });+});diff --git a/apps/server/src/services/goal/marks.ts b/apps/server/src/services/goal/marks.tsnew file mode 100644index 00000000000..f2dcd687b3c--- /dev/null+++ b/apps/server/src/services/goal/marks.ts@@ -0,0 +1,228 @@+import type { TaskRunPromptGoalMarks } from '@lobechat/prompts';+import type { GoalGraphSnapshot, GoalMarkKind } from '@lobechat/types';+import { isMarkKind } from '@lobechat/utils/goalGraph';++import { GoalGraphModel } from '@/database/models/goalGraph';+import { GoalMarkModel, type GoalMarkRunNode } from '@/database/models/goalMark';+import type { LobeChatDatabase } from '@/database/type';++/** A mark as its readers see it: the node plus the runs that judged it. */+export interface GoalMarkView {+ confidence: number;+ confirms: number;+ createdAt: Date;+ createdByAgentId: string | null;+ description: string | null;+ id: string;+ kind: GoalMarkKind;+ refutes: number;+ status: string;+ title: string;+}++/** How many marks a run's prompt lists before pointing at `lh goal mark list`. */+export const MARKS_IN_PROMPT = 12;++/**+ * Below this a mark has been refuted more than it held, and it leaves the+ * prompt. It stays on the graph and in `lh goal mark list`: a refutation can+ * itself be wrong, and the next run that finds the mark holds can confirm it.+ */+export const MARK_TRUST_FLOOR = 0.3;++export const MARK_TITLE_MAX = 200;+export const MARK_DESCRIPTION_MAX = 4000;++/**+ * Laplace-smoothed share of runs the mark held for: an unjudged mark is 0.5,+ * each confirmation pulls it toward 1 and each refutation toward 0, and no+ * count of either ever pins it.+ */+export const markConfidence = (confirms: number, refutes: number) =>+ (1 + confirms) / (2 + confirms + refutes);++/** Every mark in the graph with its judgements, newest first. */+export const goalMarks = (graph: Pick<GoalGraphSnapshot, 'edges' | 'nodes'>): GoalMarkView[] => {+ const judged = (id: string, kind: 'confirms' | 'refutes') =>+ graph.edges.filter((edge) => edge.targetNodeId === id && edge.kind === kind).length;+ return graph.nodes+ .filter((node) => isMarkKind(node.kind))+ .map((node) => {+ const confirms = judged(node.id, 'confirms');+ const refutes = judged(node.id, 'refutes');+ return {+ confidence: markConfidence(confirms, refutes),+ confirms,+ createdAt: new Date(node.createdAt),+ createdByAgentId: node.createdByAgentId ?? null,+ description: node.description ?? null,+ id: node.id,+ kind: node.kind as GoalMarkKind,+ refutes,+ status: node.status,+ title: node.title,+ };+ })+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());+};++/**+ * The marks a run is handed: not retired or rejected, trusted at least+ * {@link MARK_TRUST_FLOOR}. Hazards lead — they say what not to do — then the+ * most trusted, newest first among equals.+ */+export const activeMarks = (graph: Pick<GoalGraphSnapshot, 'edges' | 'nodes'>) =>+ goalMarks(graph)+ .filter(+ (mark) =>+ mark.status !== 'retired' &&+ mark.status !== 'rejected' &&+ mark.confidence >= MARK_TRUST_FLOOR,+ )+ .sort(+ (a, b) =>+ Number(b.kind === 'hazard') - Number(a.kind === 'hazard') ||+ b.confidence - a.confidence ||+ b.createdAt.getTime() - a.createdAt.getTime(),+ );++/** The `goalMarks` input of a Task run's prompt. */+export const marksForPrompt = (+ graph: Pick<GoalGraphSnapshot, 'edges' | 'nodes'>,+): TaskRunPromptGoalMarks => {+ const marks = activeMarks(graph);+ return {+ marks: marks.slice(0, MARKS_IN_PROMPT).map((mark) => ({+ confidence: mark.confidence,+ confirms: mark.confirms,+ description: mark.description,+ id: mark.id,+ kind: mark.kind,+ refutes: mark.refutes,+ title: mark.title,+ })),+ omitted: Math.max(0, marks.length - MARKS_IN_PROMPT) || undefined,+ };+};++export class GoalMarkError extends Error {+ constructor(+ message: string,+ readonly code: 'BAD_REQUEST' | 'NOT_FOUND',+ ) {+ super(message);+ this.name = 'GoalMarkError';+ }+}++export interface AddGoalMarkInput {+ description?: string;+ kind: GoalMarkKind;+ title: string;+}++/** Who leaves or judges a mark: a run's Task node, or a person when absent. */+export interface GoalMarkAuthor {+ agentId?: string;+ /** The Task node of the run; the mark hangs off it with a `produces` edge. */+ nodeId?: string;+}++/**+ * Leave, list, judge and retire the marks of a Goal.+ *+ * Writes go through `GoalGraphModel` so every mark and judgement lands on the+ * Goal's audit trail like any other graph edit.+ */+export class GoalMarkService {+ private readonly markModel: GoalMarkModel;++ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {+ this.markModel = new GoalMarkModel(db, userId, workspaceId);+ }++ private graphModel = (agentId?: string) =>+ new GoalGraphModel(+ this.db,+ this.userId,+ this.workspaceId,+ agentId ? { id: agentId, type: 'agent' } : undefined,+ );++ private requireGraph = async (goalId: string) => {+ const graph = await this.graphModel().getGraph(goalId);+ if (!graph) throw new GoalMarkError('Goal not found', 'NOT_FOUND');+ return graph;+ };++ private requireMark = (graph: GoalGraphSnapshot, markId: string) => {+ const mark = graph.nodes.find((node) => node.id === markId);+ if (!mark || !isMarkKind(mark.kind))+ throw new GoalMarkError(`No mark ${markId} in this Goal`, 'NOT_FOUND');+ return mark;+ };++ /** The Goal Task node a run works for; undefined when it works for none. */+ runNode = (operationId: string): Promise<GoalMarkRunNode | undefined> =>+ this.markModel.findRunNode(operationId);++ list = async (goalId: string) => goalMarks(await this.requireGraph(goalId));++ add = async (goalId: string, input: AddGoalMarkInput, author: GoalMarkAuthor = {}) => {+ const title = input.title.replaceAll(/\s+/g, ' ').trim();+ if (!title) throw new GoalMarkError('A mark needs a title', 'BAD_REQUEST');+ if (!isMarkKind(input.kind))+ throw new GoalMarkError(`Unknown mark kind "${input.kind}"`, 'BAD_REQUEST');+ await this.requireGraph(goalId);+ const graph = this.graphModel(author.agentId);+ const node = await graph.createNode(goalId, {+ confidence: markConfidence(0, 0),+ createdByAgentId: author.agentId,+ description: input.description?.trim().slice(0, MARK_DESCRIPTION_MAX) || undefined,+ kind: input.kind,+ status: 'active',+ title: title.slice(0, MARK_TITLE_MAX),+ });+ if (!node) throw new GoalMarkError('Goal not found', 'NOT_FOUND');+ if (author.nodeId) await graph.createEdge(goalId, author.nodeId, node.id, 'produces');+ return node;+ };++ /**+ * Record that the run on `author.nodeId` relied on a mark and it held+ * (`confirms`) or did not (`refutes`). A run judges a mark once per verdict;+ * repeating it is a no-op. Returns the mark's new standing.+ */+ judge = async (+ goalId: string,+ markId: string,+ verdict: 'confirms' | 'refutes',+ author: Required<Pick<GoalMarkAuthor, 'nodeId'>> & GoalMarkAuthor,+ ) => {+ const graph = await this.requireGraph(goalId);+ this.requireMark(graph, markId);+ if (author.nodeId === markId)+ throw new GoalMarkError('A mark cannot judge itself', 'BAD_REQUEST');+ const exists = graph.edges.some(+ (edge) =>+ edge.sourceNodeId === author.nodeId &&+ edge.targetNodeId === markId &&+ edge.kind === verdict,+ );+ if (!exists)+ await this.graphModel(author.agentId).createEdge(goalId, author.nodeId, markId, verdict);+ const view = goalMarks(await this.requireGraph(goalId)).find((mark) => mark.id === markId)!;+ await this.markModel.setConfidence(goalId, markId, view.confidence);+ return view;+ };++ /** Take a mark out of every later run's prompt. A person's call; it stays on the graph. */+ retire = async (goalId: string, markId: string, reason?: string) => {+ this.requireMark(await this.requireGraph(goalId), markId);+ await this.graphModel().updateNodeStatus(goalId, markId, 'retired', reason);+ };+}diff --git a/apps/server/src/services/goal/objective.test.ts b/apps/server/src/services/goal/objective.test.tsnew file mode 100644index 00000000000..e33de590fac--- /dev/null+++ b/apps/server/src/services/goal/objective.test.ts@@ -0,0 +1,176 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { GoalGraphModel } from '@/database/models/goalGraph';+import type { LobeChatDatabase } from '@/database/type';++import { GoalService } from './GoalService';+import { buildLeaderboard, GoalObjectiveService, MANUAL_LANE } from './objective';+import { registerGoalServiceTestCleanup } from './testUtils';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-objective-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++const objective = { direction: 'max' as const, evaluator: 'python score.py' };++/** A goal with two Task nodes, the second inside an experiment container. */+const goalWithLanes = async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Lane A'], title: 'Objective goal' });+ const graphModel = new GoalGraphModel(serverDB, userId);+ const problem = graph.nodes.find((node) => node.kind === 'problem')!;+ const laneA = graph.nodes.find((node) => node.kind === 'task')!;+ const container = await graphModel.createNode(graph.goal.id, {+ kind: 'experiment',+ questionId: problem.id,+ title: 'Lane B',+ });+ const laneBTask = await graphModel.createNode(graph.goal.id, {+ kind: 'task',+ scopeId: container!.id,+ title: 'Work in lane B',+ });+ return { container: container!, goalId: graph.goal.id, laneA, laneBTask: laneBTask! };+};++describe('buildLeaderboard', () => {+ const point = (lane: string | undefined, value: number, minute: number) => ({+ metadata: lane ? { lane } : null,+ observedAt: new Date(Date.UTC(2026, 0, 1, 0, minute)),+ value,+ });++ it('ranks lanes by their best score and keeps each lane latest result', () => {+ const board = buildLeaderboard(objective, [+ point('a', 10, 1),+ point('b', 12, 2),+ point('a', 15, 3),+ point('a', 11, 4),+ point(undefined, 3, 5),+ ]);++ expect(+ board.lanes.map((lane) => [lane.lane, lane.best, lane.latest, lane.evaluations]),+ ).toEqual([+ ['a', 15, 11, 3],+ ['b', 12, 12, 1],+ [MANUAL_LANE, 3, 3, 1],+ ]);+ expect(board).toMatchObject({ best: 15, leader: 'a' });+ expect(board.bestAt).toBe(new Date(Date.UTC(2026, 0, 1, 0, 3)).toISOString());+ });++ it('follows a minimising objective', () => {+ const board = buildLeaderboard({ ...objective, direction: 'min' }, [+ point('a', 10, 1),+ point('b', 4, 2),+ point('a', 6, 3),+ ]);++ expect(board.lanes.map((lane) => [lane.lane, lane.best])).toEqual([+ ['b', 4],+ ['a', 6],+ ]);+ expect(board.best).toBe(4);+ });+});++describe('GoalObjectiveService', () => {+ it('refuses an evaluation before the goal has an objective', async () => {+ const { goalId, laneA } = await goalWithLanes();++ await expect(+ new GoalObjectiveService(serverDB, userId).recordEvaluation(+ goalId,+ { score: 1, valid: true },+ { nodeId: laneA.id, taskId: 'task_x' },+ ),+ ).rejects.toThrow(/no objective/);+ });++ it('records each run in its lane — the experiment container, else the Task node', async () => {+ const { container, goalId, laneA, laneBTask } = await goalWithLanes();+ const service = new GoalObjectiveService(serverDB, userId);+ await service.setObjective(goalId, { ...objective, title: 'Judge score' });++ const first = await service.recordEvaluation(+ goalId,+ { fingerprint: 'abc', score: 20, valid: true },+ { nodeId: laneA.id, taskId: 'task_a' },+ );+ expect(first).toMatchObject({+ lane: laneA.id,+ newBest: true,+ newLaneBest: true,+ recorded: true,+ });++ const second = await service.recordEvaluation(+ goalId,+ { score: 25, valid: true },+ { nodeId: laneBTask.id, taskId: 'task_b' },+ );+ expect(second).toMatchObject({ lane: container.id, newBest: true });++ const third = await service.recordEvaluation(+ goalId,+ { score: 22, valid: true },+ { nodeId: laneA.id, taskId: 'task_a' },+ );+ expect(third).toMatchObject({ newBest: false, newLaneBest: true });++ const board = await service.leaderboard(goalId, laneBTask.id);+ expect(board?.lanes.map((lane) => [lane.title, lane.best, lane.latest])).toEqual([+ ['Lane B', 25, 25],+ ['Lane A', 22, 22],+ ]);+ expect(board).toMatchObject({+ best: 25,+ key: 'objective',+ leader: container.id,+ you: container.id,+ });+ });++ it('reports an invalid evaluation without charting it', async () => {+ const { goalId, laneA } = await goalWithLanes();+ const service = new GoalObjectiveService(serverDB, userId);+ await service.setObjective(goalId, objective);++ const result = await service.recordEvaluation(+ goalId,+ { score: 0, summary: 'crashed', valid: false },+ { nodeId: laneA.id, taskId: 'task_a' },+ );++ expect(result.recorded).toBe(false);+ expect((await service.leaderboard(goalId))?.lanes).toEqual([]);+ });++ it('puts an evaluation a person records in the manual lane, and clears the objective', async () => {+ const { goalId } = await goalWithLanes();+ const service = new GoalObjectiveService(serverDB, userId);+ await service.setObjective(goalId, objective);++ expect(await service.recordEvaluation(goalId, { score: 5, valid: true })).toMatchObject({+ lane: MANUAL_LANE,+ });++ await service.setObjective(goalId, null);+ expect(await service.leaderboard(goalId)).toBeUndefined();+ });++ it('rejects an objective without an evaluator', async () => {+ const { goalId } = await goalWithLanes();++ await expect(+ new GoalObjectiveService(serverDB, userId).setObjective(goalId, {+ ...objective,+ evaluator: ' ',+ }),+ ).rejects.toThrow(/evaluator/);+ });+});diff --git a/apps/server/src/services/goal/objective.ts b/apps/server/src/services/goal/objective.tsnew file mode 100644index 00000000000..ef346ae6bef--- /dev/null+++ b/apps/server/src/services/goal/objective.ts@@ -0,0 +1,283 @@+import type { GoalGraphSnapshot, GoalObjective } from '@lobechat/types';+import { experimentOwner } from '@lobechat/utils/goalGraph';+import { isBetterScore } from '@lobechat/utils/goalObjective';++import { GoalGraphModel } from '@/database/models/goalGraph';+import { MetricModel } from '@/database/models/metric';+import { GoalRepository } from '@/database/repositories/goal';+import type { LobeChatDatabase } from '@/database/type';++export const DEFAULT_OBJECTIVE_KEY = 'objective';+export const DEFAULT_EVALUATION_TIMEOUT_SECONDS = 1800;+/** Points a leaderboard reads; far beyond what a goal's lanes submit in a day. */+const LEADERBOARD_POINTS = 5000;+/** The lane of an evaluation recorded by a person rather than a Task run. */+export const MANUAL_LANE = 'manual';++export const objectiveKey = (objective: Pick<GoalObjective, 'key'>) =>+ objective.key?.trim() || DEFAULT_OBJECTIVE_KEY;++/** What one evaluation stores beside its score (metric point `metadata`). */+export interface EvaluationMetadata {+ durationMs?: number;+ /** Hash of the graded working tree, when the evaluator could compute one. */+ fingerprint?: string;+ lane: string;+ metrics?: Record<string, number>;+ summary?: string;+ taskId?: string;+ taskNodeId?: string;+}++export interface ObjectiveLane {+ best: number;+ bestAt: string;+ evaluations: number;+ /** The fingerprint of the latest evaluation, to tell lanes shipping identical work. */+ fingerprint?: string;+ lane: string;+ latest: number;+ latestAt: string;+ title: string;+}++export interface GoalLeaderboard {+ best?: number;+ /** When the overall best was first reached. */+ bestAt?: string;+ key: string;+ /** Best first, in the objective's direction. */+ lanes: ObjectiveLane[];+ leader?: string;+ objective: GoalObjective;+ /** The reader's own lane, when a Task run asked. */+ you?: string;+}++interface ObjectivePoint {+ metadata: unknown;+ observedAt: Date | string;+ value: number;+}++const iso = (at: Date | string) => new Date(at).toISOString();++/**+ * The leaderboard of an objective series: each lane's best and latest score,+ * best lane first. Points without a lane count as {@link MANUAL_LANE}.+ */+export const buildLeaderboard = (+ objective: GoalObjective,+ points: readonly ObjectivePoint[],+ titleOf: (lane: string) => string = (lane) => lane,+): GoalLeaderboard => {+ const lanes = new Map<string, ObjectiveLane>();+ const ordered = [...points].sort(+ (a, b) => new Date(a.observedAt).getTime() - new Date(b.observedAt).getTime(),+ );+ let best: number | undefined;+ let bestAt: string | undefined;+ for (const point of ordered) {+ const meta = (point.metadata ?? {}) as Partial<EvaluationMetadata>;+ const lane = meta.lane || MANUAL_LANE;+ const at = iso(point.observedAt);+ const current = lanes.get(lane);+ if (!current) {+ lanes.set(lane, {+ best: point.value,+ bestAt: at,+ evaluations: 1,+ fingerprint: meta.fingerprint,+ lane,+ latest: point.value,+ latestAt: at,+ title: titleOf(lane),+ });+ } else {+ current.evaluations += 1;+ current.latest = point.value;+ current.latestAt = at;+ current.fingerprint = meta.fingerprint;+ if (isBetterScore(objective.direction, point.value, current.best)) {+ current.best = point.value;+ current.bestAt = at;+ }+ }+ if (best === undefined || isBetterScore(objective.direction, point.value, best)) {+ best = point.value;+ bestAt = at;+ }+ }+ const ranked = [...lanes.values()].sort((a, b) =>+ a.best === b.best+ ? a.bestAt.localeCompare(b.bestAt)+ : isBetterScore(objective.direction, a.best, b.best)+ ? -1+ : 1,+ );+ return {+ best,+ bestAt,+ key: objectiveKey(objective),+ lanes: ranked,+ leader: ranked[0]?.lane,+ objective,+ };+};++/** A Task's lane: its experiment container, or the Task node itself outside one. */+export const laneOf = (graph: Pick<GoalGraphSnapshot, 'edges' | 'nodes'>, nodeId: string) =>+ experimentOwner(graph, nodeId) ?? nodeId;++export class GoalObjectiveError extends Error {+ constructor(+ message: string,+ readonly code: 'BAD_REQUEST' | 'NOT_FOUND',+ ) {+ super(message);+ this.name = 'GoalObjectiveError';+ }+}++export interface RecordEvaluationInput {+ durationMs?: number;+ fingerprint?: string;+ metrics?: Record<string, number>;+ score: number;+ summary?: string;+ valid: boolean;+}++/** The Goal Task run an evaluation comes from (see `GoalMarkModel.findRunNode`). */+export interface EvaluationRun {+ agentId?: string;+ nodeId: string;+ operationId?: string;+ taskId: string;+}++/**+ * Set, read and feed a goal's objective.+ *+ * Scores live in the generic metric layer (subject = the goal), so the+ * north-star views read them like any other measurement; the lane rides in+ * each point's metadata and the leaderboard is derived from the series.+ */+export class GoalObjectiveService {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private requireGraph = async (goalId: string) => {+ const graph = await new GoalGraphModel(this.db, this.userId, this.workspaceId).getGraph(goalId);+ if (!graph) throw new GoalObjectiveError('Goal not found', 'NOT_FOUND');+ return graph;+ };++ private titleOf = (graph: GoalGraphSnapshot) => (lane: string) =>+ graph.nodes.find((node) => node.id === lane)?.title ?? lane;++ /** Set the objective, or clear it with `null`. */+ setObjective = async (goalId: string, objective: GoalObjective | null) => {+ if (objective) {+ if (!objective.evaluator.trim())+ throw new GoalObjectiveError('The objective needs an evaluator command', 'BAD_REQUEST');+ if (objective.direction !== 'max' && objective.direction !== 'min')+ throw new GoalObjectiveError('Direction must be max or min', 'BAD_REQUEST');+ }+ await this.db.transaction(async (tx) => {+ const model = new GoalRepository(tx, this.userId, this.workspaceId);+ const goal = await model.lockById(goalId);+ if (!goal) throw new GoalObjectiveError('Goal not found', 'NOT_FOUND');+ const { objective: _previous, ...config } = goal.config ?? {};+ await model.update(goalId, {+ config: objective+ ? { ...config, objective: { ...objective, evaluator: objective.evaluator.trim() } }+ : config,+ });+ });+ return objective;+ };++ /**+ * The objective and its leaderboard; undefined when the goal has no+ * objective. `nodeId` is a reading run's Task node, to name its lane.+ */+ leaderboard = async (goalId: string, nodeId?: string): Promise<GoalLeaderboard | undefined> => {+ const graph = await this.requireGraph(goalId);+ const board = await this.leaderboardOf(graph);+ return board && nodeId ? { ...board, you: laneOf(graph, nodeId) } : board;+ };++ private leaderboardOf = async (graph: GoalGraphSnapshot) => {+ const objective = graph.goal.config?.objective;+ if (!objective) return undefined;+ const metrics = new MetricModel(this.db, this.userId, this.workspaceId);+ const series = await metrics.findByKey('goal', graph.goal.id, objectiveKey(objective));+ const points = series ? await metrics.recentPoints(series.id, LEADERBOARD_POINTS) : [];+ return buildLeaderboard(objective, points, this.titleOf(graph));+ };++ /**+ * Record one evaluation. A valid one becomes a point of the objective series+ * in the run's lane — its experiment container, or its Task node when it has+ * none; an invalid one is reported back but not charted, because the series+ * holds scores and an unrankable result has none.+ */+ recordEvaluation = async (goalId: string, input: RecordEvaluationInput, run?: EvaluationRun) => {+ if (!Number.isFinite(input.score))+ throw new GoalObjectiveError('The score must be a finite number', 'BAD_REQUEST');+ const graph = await this.requireGraph(goalId);+ const objective = graph.goal.config?.objective;+ if (!objective)+ throw new GoalObjectiveError(+ 'This goal has no objective; set one with `lh goal set-objective`',+ 'BAD_REQUEST',+ );+ const lane = run ? laneOf(graph, run.nodeId) : MANUAL_LANE;+ const before = await this.leaderboardOf(graph);+ if (!input.valid) return { lane, leaderboard: before, recorded: false as const };++ const metrics = new MetricModel(this.db, this.userId, this.workspaceId);+ const series = await metrics.ensure({+ key: objectiveKey(objective),+ kind: 'gauge',+ subjectId: goalId,+ subjectType: 'goal',+ title: objective.title,+ });+ if (!series)+ throw new GoalObjectiveError('Objective series is owned by another scope', 'BAD_REQUEST');+ const metadata: EvaluationMetadata = {+ durationMs: input.durationMs,+ fingerprint: input.fingerprint,+ lane,+ metrics: input.metrics,+ summary: input.summary?.slice(0, 2000),+ taskId: run?.taskId,+ taskNodeId: run?.nodeId,+ };+ await metrics.addPoint(series.id, {+ actorId: run?.agentId ?? this.userId,+ actorType: run?.agentId ? 'agent' : 'user',+ metadata,+ observedAt: new Date(),+ operationId: run?.operationId,+ sourceType: run ? 'probe' : 'manual',+ value: input.score,+ });+ const leaderboard = (await this.leaderboardOf(graph))!;+ const laneBefore = before?.lanes.find((item) => item.lane === lane)?.best;+ return {+ lane,+ leaderboard,+ newBest:+ before?.best === undefined || isBetterScore(objective.direction, input.score, before.best),+ newLaneBest:+ laneBefore === undefined || isBetterScore(objective.direction, input.score, laneBefore),+ recorded: true as const,+ };+ };+}diff --git a/apps/server/src/services/goal/rolloutBatch.ts b/apps/server/src/services/goal/rolloutBatch.tsindex 675c3c71c03..d18539ebb52 100644--- a/apps/server/src/services/goal/rolloutBatch.ts+++ b/apps/server/src/services/goal/rolloutBatch.ts@@ -323,7 +323,7 @@ export const materializeRolloutBatch = async ({const template = await writer.createNode(goalId, {createdByAgentId,description: recipeOutline,- kind: 'finding',+ kind: 'template',scopeId: batch.id,title: GOAL_BATCH_TEMPLATE_TITLE,});diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.test.tsindex c3e588e9a61..e74f192a8c7 100644--- a/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '@/database/core/getTestDB';@@ -24,6 +25,7 @@ import {verifyRuns,} from '@/database/schemas';+import { GoalObjectiveService } from '../goal/objective';import { buildTaskPrompt } from './buildTaskPrompt';const promptDeps = (@@ -108,6 +110,70 @@ describe('buildTaskPrompt Goal loop context', () => {});});+describe('buildTaskPrompt goal marks', () => {+ const goalTask = async (name: string) => {+ const taskModel = new TaskModel(db, userId);+ const task = await taskModel.create({ instruction: 'Migrate one store slice.', name });+ const goal = await new GoalModel(db, userId).create({+ subjectType: 'standalone',+ title: 'Migrate the stores',+ });+ const graphModel = new GoalGraphModel(db, userId);+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: name });+ await graphModel.bindTask(goal.id, node!.id, task.id);+ await graphModel.createNode(goal.id, {+ description: 'Add the action to __mocks__ as well.',+ kind: 'pattern',+ status: 'active',+ title: 'internal_ action mock missing',+ });+ return { task: (await taskModel.findById(task.id))!, taskModel };+ };++ it('hands a Goal Task run the marks its siblings left', async () => {+ const { task, taskModel } = await goalTask('Migrate chat slice');++ const { prompt } = await buildTaskPrompt(task, promptDeps(db, taskModel, userId));++ expect(prompt).toContain('<goal_marks>');+ expect(prompt).toContain('[pattern, unconfirmed] internal_ action mock missing');+ expect(prompt).toContain('Add the action to __mocks__ as well.');+ });++ it('gives the terminal acceptance Task none: it judges the Goal, it does not do its work', async () => {+ const { task, taskModel } = await goalTask(GOAL_ACCEPTANCE_TASK_TITLE);++ const { prompt } = await buildTaskPrompt(task, promptDeps(db, taskModel, userId));++ expect(prompt).not.toContain('<goal_marks>');+ });++ it('hands a run of an optimisation goal its objective and leaderboard', async () => {+ const { task, taskModel } = await goalTask('Tune the model');+ const goal = await new GoalModel(db, userId).findByGraphTask(task.id);+ await new GoalObjectiveService(db, userId).setObjective(goal!.id, {+ direction: 'max',+ evaluator: './score.sh',+ title: 'Judge score',+ });++ const { prompt } = await buildTaskPrompt(task, promptDeps(db, taskModel, userId));++ expect(prompt).toContain('<goal_objective>');+ expect(prompt).toContain('This Goal maximises Judge score');+ expect(prompt).toContain('runs `./score.sh` there');+ });++ it('gives a Task outside any Goal none', async () => {+ const taskModel = new TaskModel(db, userId);+ const task = await taskModel.create({ instruction: 'Standalone work.' });++ const { prompt } = await buildTaskPrompt(task, promptDeps(db, taskModel, userId));++ expect(prompt).not.toContain('<goal_marks>');+ });+});+describe('buildTaskPrompt questions earlier rounds asked', () => {/*** Regression: each Goal round is a fresh conversation, so a question andiff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.tsindex c3570da4785..cad7232039c 100644--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts@@ -1,5 +1,11 @@import { UserInteractionApiName } from '@lobechat/builtin-tool-user-interaction';-import { buildTaskRunPrompt, type TaskRunPromptGoalLoop } from '@lobechat/prompts';+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import {+ buildTaskRunPrompt,+ type TaskRunPromptGoalLoop,+ type TaskRunPromptGoalMarks,+ type TaskRunPromptGoalObjective,+} from '@lobechat/prompts';import type {TaskItem,TaskTopicHandoff,@@ -10,6 +16,7 @@ import type {import { AcceptanceModel } from '@/database/models/acceptance';import type { BriefModel } from '@/database/models/brief';import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';import { MessageModel } from '@/database/models/message';import type { TaskModel } from '@/database/models/task';import type { TaskTopicModel } from '@/database/models/taskTopic';@@ -24,6 +31,8 @@ import {} from '@/server/services/acceptanceReview/roundContext';import { extractFileIdsFromEditorData } from '@/server/services/file/extractFileIdsFromEditorData';import { resolveAttachmentMetadata } from '@/server/services/file/resolveAttachments';+import { marksForPrompt } from '@/server/services/goal/marks';+import { GoalObjectiveService } from '@/server/services/goal/objective';import {countChargedTaskAttempts,countUnchargedRuns,@@ -93,6 +102,47 @@ const isJudgedResult = (result: { status: string; verdict: string | null }) =>result.status !== 'errored' &&(!!result.verdict || result.status === 'passed' || result.status === 'failed');+/** How many lanes a run's prompt lists; the rest are behind `lh goal objective`. */+const OBJECTIVE_LANES_IN_PROMPT = 8;++/**+ * The Goal context every run of a Goal Task is handed — the marks other runs+ * left and, when the goal optimises a score, its objective and leaderboard —+ * read fresh for this run so what a sibling did a minute ago reaches it. The+ * terminal acceptance Task judges the Goal rather than doing its work, so it+ * gets neither. A failed read costs the run this context, never the run.+ */+const resolveGoalRunContext = async (+ task: TaskItem,+ deps: BuildTaskPromptDeps,+): Promise<{ marks?: TaskRunPromptGoalMarks; objective?: TaskRunPromptGoalObjective }> => {+ if (task.name === GOAL_ACCEPTANCE_TASK_TITLE) return {};+ const { db, userId, workspaceId } = deps;+ try {+ const goal = await new GoalModel(db, userId, workspaceId).findByGraphTask(task.id);+ if (!goal) return {};+ const graph = await new GoalGraphModel(db, userId, workspaceId).getGraph(goal.id);+ if (!graph) return {};+ const node = graph.nodes.find((item) => item.taskId === task.id);+ const board = graph.goal.config?.objective+ ? await new GoalObjectiveService(db, userId, workspaceId).leaderboard(goal.id, node?.id)+ : undefined;+ return {+ marks: marksForPrompt(graph),+ objective: board && {+ direction: board.objective.direction,+ evaluator: board.objective.evaluator,+ lanes: board.lanes.slice(0, OBJECTIVE_LANES_IN_PROMPT),+ title: board.objective.title,+ you: board.you,+ },+ };+ } catch (error) {+ console.error('[buildTaskPrompt] failed to read the goal context:', error);+ return {};+ }+};+/*** For a goal task that already ran at least one round, collect what the next* round must know: the previous round's unresolved checks (with the verifier's@@ -444,7 +494,10 @@ export async function buildTaskPrompt(});}- const goalLoop = await resolveGoalLoopContext(task, deps);+ const [goalLoop, { marks: goalMarks, objective: goalObjective }] = await Promise.all([+ resolveGoalLoopContext(task, deps),+ resolveGoalRunContext(task, deps),+ ]);const reviewId = reviewIdOfTask(task.config);const reviewMarks = reviewId@@ -453,6 +506,8 @@ export async function buildTaskPrompt(const prompt = buildTaskRunPrompt({...(goalLoop ? { goalLoop } : {}),+ ...(goalMarks ? { goalMarks } : {}),+ ...(goalObjective ? { goalObjective } : {}),activities: {briefs: briefs.map((b: any) => ({createdAt: b.createdAt,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 48bf546defb..f96e0a08100 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -987,11 +987,16 @@"goalProcess.graph.view.all": "Full map","goalProcess.graph.view.stage": "Current stage","goalProcess.kind.batch": "Batch",+ "goalProcess.kind.dead_end": "Dead end","goalProcess.kind.decision": "Decision","goalProcess.kind.experiment": "Experiment","goalProcess.kind.finding": "Finding",+ "goalProcess.kind.hazard": "Hazard",+ "goalProcess.kind.pattern": "Pattern","goalProcess.kind.problem": "Question","goalProcess.kind.task": "Task",+ "goalProcess.kind.template": "Recipe",+ "goalProcess.kind.tool": "Tool","goalProcess.lifecycle.action.activated": "started {{kind}}","goalProcess.lifecycle.action.created": "created {{kind}}","goalProcess.lifecycle.action.created.decision": "requested a decision",@@ -1013,12 +1018,17 @@"goalProcess.lifecycle.action.work.produced": "produced","goalProcess.lifecycle.action.work.supports": "added evidence","goalProcess.lifecycle.kind.batch": "batch",+ "goalProcess.lifecycle.kind.dead_end": "dead end","goalProcess.lifecycle.kind.decision": "decision","goalProcess.lifecycle.kind.experiment": "experiment","goalProcess.lifecycle.kind.finding": "finding","goalProcess.lifecycle.kind.goal": "goal",+ "goalProcess.lifecycle.kind.hazard": "hazard",+ "goalProcess.lifecycle.kind.pattern": "pattern","goalProcess.lifecycle.kind.problem": "question","goalProcess.lifecycle.kind.task": "task",+ "goalProcess.lifecycle.kind.template": "recipe",+ "goalProcess.lifecycle.kind.tool": "tool","goalProcess.lifecycle.note.budgetExhausted": "The goal or the main Agent ran out of turns","goalProcess.lifecycle.note.mainAgent": "Main Agent: {{text}}","goalProcess.lifecycle.note.recoveredAbandoned": "The previous run stopped responding; a new attempt started automatically",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex f6b5ca9c111..f1229470ad4 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -987,11 +987,16 @@"goalProcess.graph.view.all": "全图","goalProcess.graph.view.stage": "当前阶段","goalProcess.kind.batch": "批次",+ "goalProcess.kind.dead_end": "死路","goalProcess.kind.decision": "决策","goalProcess.kind.experiment": "实验","goalProcess.kind.finding": "结论",+ "goalProcess.kind.hazard": "警示",+ "goalProcess.kind.pattern": "经验","goalProcess.kind.problem": "问题","goalProcess.kind.task": "任务",+ "goalProcess.kind.template": "配方",+ "goalProcess.kind.tool": "工具","goalProcess.lifecycle.action.activated": "开始执行{{kind}}","goalProcess.lifecycle.action.created": "创建{{kind}}","goalProcess.lifecycle.action.created.decision": "发起决策",@@ -1013,12 +1018,17 @@"goalProcess.lifecycle.action.work.produced": "产出交付物","goalProcess.lifecycle.action.work.supports": "补充证据","goalProcess.lifecycle.kind.batch": "批次",+ "goalProcess.lifecycle.kind.dead_end": "死路","goalProcess.lifecycle.kind.decision": "决策","goalProcess.lifecycle.kind.experiment": "实验","goalProcess.lifecycle.kind.finding": "结论","goalProcess.lifecycle.kind.goal": "目标",+ "goalProcess.lifecycle.kind.hazard": "警示",+ "goalProcess.lifecycle.kind.pattern": "经验","goalProcess.lifecycle.kind.problem": "问题","goalProcess.lifecycle.kind.task": "任务",+ "goalProcess.lifecycle.kind.template": "配方",+ "goalProcess.lifecycle.kind.tool": "工具","goalProcess.lifecycle.note.budgetExhausted": "目标或主 Agent 的轮次预算已用完","goalProcess.lifecycle.note.mainAgent": "主 Agent:{{text}}","goalProcess.lifecycle.note.recoveredAbandoned": "上一次运行已失去响应,已自动重新开始",diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.tsindex 9031fe4eb43..963425bd113 100644--- a/packages/const/src/goal.ts+++ b/packages/const/src/goal.ts@@ -212,6 +212,8 @@ export const GOAL_BATCH_TITLE = 'Deliver the repeated batch';export const GOAL_GRAPH_CAPABILITY = {/** The `batch` node kind (repeated-mould rollouts). */batch: 'batch',+ /** The mark kinds (`pattern` / `tool` / `hazard` / `dead_end`), `template`, and their edges. */+ marks: 'marks',} as const;/**@@ -228,7 +230,7 @@ export const GOAL_BATCH_ASSAY_TITLE = 'Prove the batch runs automatically';*/export const GOAL_BATCH_RELEASE_TITLE = 'Approve releasing the next wave';-/** Fixed title of the Template (recipe) finding node a batch distills. */+/** Fixed title of the Template (recipe) node a batch distills. */export const GOAL_BATCH_TEMPLATE_TITLE = 'Batch recipe';/** Default probe size K — representative units that run before the gate. */@@ -310,3 +312,6 @@ export const mergeIslandDismissals = (current: string[], added: string[]): strin);return fresh.length === 0 ? current : [...current, ...fresh].slice(-MAX_ISLAND_DISMISSALS);};++/** Node kinds that are marks: Goal-wide, left by one Task for every later one. */+export const GOAL_MARK_KINDS = ['pattern', 'tool', 'hazard', 'dead_end'] as const;diff --git a/packages/database/src/models/goalExploration.ts b/packages/database/src/models/goalExploration.tsindex 820c9f62c42..499b3f18654 100644--- a/packages/database/src/models/goalExploration.ts+++ b/packages/database/src/models/goalExploration.ts@@ -8,6 +8,7 @@ import {isProtocolRevision,MAX_PROTOCOL_REVISIONS,protocolRevisionCount,+ withoutMarks,} from '@lobechat/utils/goalGraph';import { and, eq } from 'drizzle-orm';@@ -17,8 +18,13 @@ import type { LobeChatDatabase } from '../type';import { buildWorkspaceWhere } from '../utils/workspace';import { GoalGraphModel } from './goalGraph';-/** Ignore only coordinator bookkeeping; edits to policy, evidence or graph invalidate a plan. */-export const goalExplorationSnapshot = (graph: GoalGraphSnapshot): string => {+/**+ * Ignore only coordinator bookkeeping and marks; edits to policy, evidence or+ * graph invalidate a plan. Marks are left while sibling Tasks run, so hashing+ * them would void the plan whenever any of them noted a pitfall.+ */+export const goalExplorationSnapshot = (input: GoalGraphSnapshot): string => {+ const graph = withoutMarks(input);const { checkpoint: _checkpoint, ...policy } = graph.goal.config?.exploration ?? {};return createHash('sha256').update(diff --git a/packages/database/src/models/goalMark.ts b/packages/database/src/models/goalMark.tsnew file mode 100644index 00000000000..c6cd4523989--- /dev/null+++ b/packages/database/src/models/goalMark.ts@@ -0,0 +1,85 @@+import { GOAL_MARK_KINDS } from '@lobechat/const/goal';+import { and, eq, inArray } from 'drizzle-orm';++import { goals } from '../schemas/goal';+import { goalNodes } from '../schemas/goalGraph';+import { tasks, taskTopics } from '../schemas/task';+import type { LobeChatDatabase } from '../type';+import { buildWorkspaceWhere } from '../utils/workspace';++/** The Goal Task node a run works for, found from the run's operation. */+export interface GoalMarkRunNode {+ /** The agent the Task is assigned to: the author of what the run marks. */+ agentId?: string;+ goalId: string;+ nodeId: string;+ taskId: string;+}++/**+ * The reads and writes Goal marks need beyond the ordinary graph writes.+ *+ * A mark is created and linked through `GoalGraphModel`, which keeps the audit+ * trail; this model only resolves which Task node a run belongs to, and stores+ * the confidence derived from the runs that confirmed or refuted a mark.+ */+export class GoalMarkModel {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private ownership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, goals);++ /**+ * The Task node whose run `operationId` is. Only a run of a Task bound to a+ * Goal node resolves; a subtask's run, or one outside any Goal, does not.+ */+ findRunNode = async (operationId: string): Promise<GoalMarkRunNode | undefined> => {+ const [row] = await this.db+ .select({+ agentId: tasks.assigneeAgentId,+ goalId: goalNodes.goalId,+ nodeId: goalNodes.id,+ taskId: tasks.id,+ })+ .from(taskTopics)+ .innerJoin(tasks, eq(tasks.id, taskTopics.taskId))+ .innerJoin(goalNodes, eq(goalNodes.taskId, tasks.id))+ .innerJoin(goals, eq(goals.id, goalNodes.goalId))+ .where(+ and(+ eq(taskTopics.operationId, operationId),+ eq(taskTopics.userId, this.userId),+ this.ownership(),+ ),+ )+ .limit(1);+ if (!row) return undefined;+ return { ...row, agentId: row.agentId ?? undefined };+ };++ /** Store a mark's derived confidence; other node kinds are left alone. */+ setConfidence = async (goalId: string, nodeId: string, confidence: number) => {+ const [goal] = await this.db+ .select({ id: goals.id })+ .from(goals)+ .where(and(eq(goals.id, goalId), this.ownership()))+ .limit(1);+ if (!goal) return undefined;+ const [node] = await this.db+ .update(goalNodes)+ .set({ confidence: confidence.toFixed(3), updatedAt: new Date() })+ .where(+ and(+ eq(goalNodes.goalId, goalId),+ eq(goalNodes.id, nodeId),+ inArray(goalNodes.kind, [...GOAL_MARK_KINDS]),+ ),+ )+ .returning({ id: goalNodes.id });+ return node;+ };+}diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex b1c55b193b0..d2fc186d9e9 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3030,6 +3030,11 @@ export default {'goalProcess.kind.finding': 'Finding','goalProcess.kind.decision': 'Decision','goalProcess.kind.batch': 'Batch',+ 'goalProcess.kind.pattern': 'Pattern',+ 'goalProcess.kind.tool': 'Tool',+ 'goalProcess.kind.hazard': 'Hazard',+ 'goalProcess.kind.dead_end': 'Dead end',+ 'goalProcess.kind.template': 'Recipe','goalProcess.node.running': 'Running','goalProcess.node.stopped': 'Stopped','goalProcess.node.done': 'Done',@@ -3068,6 +3073,11 @@ export default {'goalProcess.lifecycle.kind.goal': 'goal','goalProcess.lifecycle.kind.problem': 'question','goalProcess.lifecycle.kind.task': 'task',+ 'goalProcess.lifecycle.kind.pattern': 'pattern',+ 'goalProcess.lifecycle.kind.tool': 'tool',+ 'goalProcess.lifecycle.kind.hazard': 'hazard',+ 'goalProcess.lifecycle.kind.dead_end': 'dead end',+ 'goalProcess.lifecycle.kind.template': 'recipe','goalProcess.lifecycle.note.budgetExhausted': 'The goal or the main Agent ran out of turns','goalProcess.lifecycle.note.mainAgent': 'Main Agent: {{text}}','goalProcess.lifecycle.note.recoveredAbandoned':diff --git a/packages/prompts/src/prompts/task/goalMarks.test.ts b/packages/prompts/src/prompts/task/goalMarks.test.tsnew file mode 100644index 00000000000..48fb9faa573--- /dev/null+++ b/packages/prompts/src/prompts/task/goalMarks.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';++import { buildGoalMarksSection } from './goalMarks';+import { buildTaskRunPrompt } from './index';++const mark = {+ confidence: 0.75,+ confirms: 2,+ description: 'tsc fails on `internal_` actions.\nMock them in __mocks__ too.',+ id: 'm-1',+ kind: 'pattern' as const,+ refutes: 0,+ title: 'internal_ mock missing → add to __mocks__',+};++describe('buildGoalMarksSection', () => {+ it('lists each mark with its record, id and a one-line description', () => {+ const section = buildGoalMarksSection({ marks: [mark] });++ expect(section).toContain(+ '- [pattern, confirmed 2 / refuted 0] internal_ mock missing → add to __mocks__ (id: m-1)',+ );+ expect(section).toContain(' tsc fails on `internal_` actions. Mock them in __mocks__ too.');+ expect(section).toContain('`lh goal mark confirm <id>`');+ });++ it('still teaches an empty Goal how to leave the first mark', () => {+ const section = buildGoalMarksSection({ marks: [] });++ expect(section).toContain('No marks yet.');+ expect(section).toContain('lh goal mark add pattern');+ });++ it('points at the full list when the cap left marks out', () => {+ expect(buildGoalMarksSection({ marks: [mark], omitted: 3 })).toContain(+ '3 more: `lh goal mark list`.',+ );+ });++ it('labels a mark nobody has judged as unconfirmed', () => {+ expect(+ buildGoalMarksSection({ marks: [{ ...mark, confirms: 0, description: null }] }),+ ).toContain('- [pattern, unconfirmed] internal_ mock missing → add to __mocks__ (id: m-1)\n');+ });+});++describe('buildTaskRunPrompt goal marks', () => {+ const task = { id: 'task_1', identifier: 'T-1', instruction: 'Migrate', status: 'running' };++ it('adds the section after the task only for a Goal Task run', () => {+ const prompt = buildTaskRunPrompt({ goalMarks: { marks: [mark] }, task });+ expect(prompt.indexOf('<goal_marks>')).toBeGreaterThan(prompt.indexOf('</task>'));+ expect(buildTaskRunPrompt({ task })).not.toContain('<goal_marks>');+ });+});diff --git a/packages/prompts/src/prompts/task/goalMarks.ts b/packages/prompts/src/prompts/task/goalMarks.tsnew file mode 100644index 00000000000..3875ea189e2--- /dev/null+++ b/packages/prompts/src/prompts/task/goalMarks.ts@@ -0,0 +1,63 @@+/** One mark another run of the same Goal left, as the prompt lists it. */+export interface TaskRunPromptGoalMark {+ confidence: number;+ confirms: number;+ description?: string | null;+ id: string;+ kind: 'dead_end' | 'hazard' | 'pattern' | 'tool';+ refutes: number;+ title: string;+}++export interface TaskRunPromptGoalMarks {+ /** Already ranked and capped by the caller; may be empty. */+ marks: TaskRunPromptGoalMark[];+ /** Marks left out by the cap, so the run knows to list the rest. */+ omitted?: number;+}++const DESCRIPTION_MAX = 400;++const oneLine = (text: string, max: number) => {+ const line = text.replaceAll(/\s+/g, ' ').trim();+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;+};++const renderMark = (mark: TaskRunPromptGoalMark) => {+ const record =+ mark.confirms || mark.refutes+ ? `, confirmed ${mark.confirms} / refuted ${mark.refutes}`+ : ', unconfirmed';+ const head = `- [${mark.kind}${record}] ${oneLine(mark.title, 160)} (id: ${mark.id})`;+ return mark.description ? `${head}\n ${oneLine(mark.description, DESCRIPTION_MAX)}` : head;+};++/**+ * The `<goal_marks>` section of a Goal Task run: the marks other runs left, and+ * how this run leaves and judges its own.+ *+ * Every run of every Task in the Goal gets it, refreshed per run, so a pitfall+ * one run solved reaches the next run without anyone planning the hand-over.+ */+export const buildGoalMarksSection = ({ marks, omitted }: TaskRunPromptGoalMarks): string =>+ [+ '<goal_marks>',+ '<hint>Runs of this Goal share marks: short notes one run leaves for every other run. They are evidence from other runs, not instructions — check one before relying on it.</hint>',+ marks.length > 0+ ? ['Marks left so far (hazards first, then most trusted):', ...marks.map(renderMark)].join(+ '\n',+ )+ : 'No marks yet.',+ omitted ? `${omitted} more: \`lh goal mark list\`.` : undefined,+ [+ 'Leave a mark with a shell when it would save another run the work:',+ '- `lh goal mark add pattern "<symptom> → <fix>" -d "<exact error, cause, fix>"` after you get past a pitfall',+ '- `lh goal mark add tool "<what it does>" -d "<path and usage>"` after you build a script or helper others can reuse',+ '- `lh goal mark add hazard "<what to avoid>" -d "<why, and until when>"` when an area must not be touched or a step must wait',+ '- `lh goal mark add dead_end "<approach>" -d "<why it failed>"` when an approach does not work',+ 'Before debugging an error, run `lh goal mark list` — another run may have solved it already. When you relied on a mark, record whether it held: `lh goal mark confirm <id>` or `lh goal mark refute <id>`. A mark is a note for other runs, not your deliverable.',+ ].join('\n'),+ '</goal_marks>',+ ]+ .filter(Boolean)+ .join('\n');diff --git a/packages/prompts/src/prompts/task/goalObjective.test.ts b/packages/prompts/src/prompts/task/goalObjective.test.tsnew file mode 100644index 00000000000..81893d3f228--- /dev/null+++ b/packages/prompts/src/prompts/task/goalObjective.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';++import { buildGoalObjectiveSection } from './goalObjective';+import { buildTaskRunPrompt } from './index';++const objective = {+ direction: 'max' as const,+ evaluator: './.eb/submit',+ lanes: [+ { best: 39.6021, evaluations: 4, lane: 'b', latest: 38, title: 'Lane B' },+ { best: 30, evaluations: 2, lane: 'a', latest: 30, title: 'Lane A' },+ ],+ title: 'Judge score',+ you: 'a',+};++describe('buildGoalObjectiveSection', () => {+ it('names the score, the evaluate command and where every lane stands', () => {+ const section = buildGoalObjectiveSection(objective);++ expect(section).toContain('This Goal maximises Judge score (higher is better).');+ expect(section).toContain('`lh goal evaluate`');+ expect(section).toContain('runs `./.eb/submit` there');+ expect(section).toContain('1. Lane B — best 39.6021, latest 38, 4 evaluation(s)');+ expect(section).toContain('2. Lane A (your lane) — best 30');+ });++ it('says when nothing has been evaluated, and words a minimising goal', () => {+ const section = buildGoalObjectiveSection({ ...objective, direction: 'min', lanes: [] });++ expect(section).toContain('minimises Judge score (lower is better)');+ expect(section).toContain('No evaluation recorded yet.');+ });+});++describe('buildTaskRunPrompt goal objective', () => {+ const task = { id: 'task_1', identifier: 'T-1', instruction: 'Tune', status: 'running' };++ it('puts the objective after the task and before the marks', () => {+ const prompt = buildTaskRunPrompt({ goalMarks: { marks: [] }, goalObjective: objective, task });++ expect(prompt.indexOf('<goal_objective>')).toBeGreaterThan(prompt.indexOf('</task>'));+ expect(prompt.indexOf('<goal_objective>')).toBeLessThan(prompt.indexOf('<goal_marks>'));+ expect(buildTaskRunPrompt({ task })).not.toContain('<goal_objective>');+ });+});diff --git a/packages/prompts/src/prompts/task/goalObjective.ts b/packages/prompts/src/prompts/task/goalObjective.tsnew file mode 100644index 00000000000..8dcc59fce2b--- /dev/null+++ b/packages/prompts/src/prompts/task/goalObjective.ts@@ -0,0 +1,51 @@+/** One lane of the leaderboard, as a Task run's prompt lists it. */+export interface TaskRunPromptObjectiveLane {+ best: number;+ evaluations: number;+ lane: string;+ latest: number;+ title: string;+}++export interface TaskRunPromptGoalObjective {+ direction: 'max' | 'min';+ evaluator: string;+ /** Best lane first; already capped by the caller. */+ lanes: TaskRunPromptObjectiveLane[];+ title?: string;+ /** This run's lane id. */+ you?: string;+}++const formatScore = (value: number) => String(Number(value.toFixed(4)));++/**+ * The `<goal_objective>` section of a Goal Task run: what score the goal+ * pushes, how to grade with `lh goal evaluate`, and where every lane stands.+ */+export const buildGoalObjectiveSection = ({+ direction,+ evaluator,+ lanes,+ title,+ you,+}: TaskRunPromptGoalObjective): string => {+ const name = title || 'the objective score';+ const board =+ lanes.length > 0+ ? [+ 'Leaderboard (best first):',+ ...lanes.map(+ (lane, index) =>+ `${index + 1}. ${lane.title}${lane.lane === you ? ' (your lane)' : ''} — best ${formatScore(lane.best)}, latest ${formatScore(lane.latest)}, ${lane.evaluations} evaluation(s)`,+ ),+ ].join('\n')+ : 'No evaluation recorded yet.';+ return [+ '<goal_objective>',+ `This Goal ${direction === 'max' ? 'maximises' : 'minimises'} ${name} (${direction === 'max' ? 'higher' : 'lower'} is better).`,+ `Grade your work with \`lh goal evaluate\` from your working directory: it runs \`${evaluator}\` there, records the score for your lane and prints the score and feedback (\`-d\` for details). Evaluate as soon as something runs, then after each improvement. Do not edit or bypass the evaluator, and do not report a score it did not produce.`,+ board,+ '</goal_objective>',+ ].join('\n');+};diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.tsindex b3f26df4082..aebc811c317 100644--- a/packages/prompts/src/prompts/task/index.ts+++ b/packages/prompts/src/prompts/task/index.ts@@ -1,5 +1,8 @@import type { TaskDetailData, TaskDetailWorkspaceNode, TaskStatus } from '@lobechat/types';+import { buildGoalMarksSection, type TaskRunPromptGoalMarks } from './goalMarks';+import { buildGoalObjectiveSection, type TaskRunPromptGoalObjective } from './goalObjective';+// ── Formatting helpers for Task tool responses ──const priorityLabel = (p?: number | null): string => {@@ -595,6 +598,10 @@ export interface TaskRunPromptInput {extraPrompt?: string;/** Present only for rounds spawned by the goal outer loop. */goalLoop?: TaskRunPromptGoalLoop;+ /** Present only for runs of a Task that works for a Goal. */+ goalMarks?: TaskRunPromptGoalMarks;+ /** Present only for runs of a Task whose Goal has an objective. */+ goalObjective?: TaskRunPromptGoalObjective;/** Parent task context (when current task is a subtask) */parentTask?: {id?: string;@@ -700,7 +707,16 @@ const briefIcon = (type: string): string => {* 4. Original Task (instruction + description) — the base requirement*/export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): string => {- const { task, activities, extraPrompt, goalLoop, workspace, parentTask } = input;+ const {+ task,+ activities,+ extraPrompt,+ goalLoop,+ goalMarks,+ goalObjective,+ workspace,+ parentTask,+ } = input;const sections: string[] = [];// ── 1. High Priority Instruction ──@@ -1038,6 +1054,8 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strintaskLines.push('</task>');sections.push(taskLines.join('\n'));+ if (goalObjective) sections.push(buildGoalObjectiveSection(goalObjective));+ if (goalMarks) sections.push(buildGoalMarksSection(goalMarks));return sections.join('\n\n');};@@ -1048,5 +1066,7 @@ export type { BuildTaskDetailPromptInput } from './buildTaskDetailPrompt';export { buildTaskDetailPrompt } from './buildTaskDetailPrompt';export type { BuildTaskListPromptInput } from './buildTaskListPrompt';export { buildTaskListPrompt } from './buildTaskListPrompt';+export type { TaskRunPromptGoalMark, TaskRunPromptGoalMarks } from './goalMarks';+export type { TaskRunPromptGoalObjective, TaskRunPromptObjectiveLane } from './goalObjective';export type { TaskManagerPromptDefaults } from './taskManagerDefaults';export { buildTaskManagerDefaultsPrompt } from './taskManagerDefaults';diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex ac633f2029c..2d38fae6177 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -468,6 +468,31 @@ export interface GoalUnderstanding {updatedAt: string;}+/**+ * The score an optimisation goal pushes, and the command that measures it.+ *+ * A Task run grades its working directory with `lh goal evaluate`, which runs+ * `evaluator` there and records the score as one point of the goal's metric+ * series `key`, tagged with the lane (the run's experiment container, or its+ * Task node). The leaderboard is that series grouped by lane.+ */+export interface GoalObjective {+ /** Higher or lower is better. */+ direction: 'max' | 'min';+ /**+ * Shell command run in the Task's working directory. Its output must carry+ * the score: a JSON object with `score` (and optional `valid`, `summary`,+ * `metrics`), a `TOTAL_SCORE <n>` / `score: <n>` line, or a bare number.+ */+ evaluator: string;+ /** Metric series key on this goal. Defaults to `objective`. */+ key?: string;+ /** Seconds before an evaluation is abandoned. Defaults to 1800. */+ timeoutSeconds?: number;+ /** Human-facing name of the score. */+ title?: string;+}+export interface GoalConfig {acceptance?: GoalAcceptancePolicy;/**@@ -492,6 +517,8 @@ export interface GoalConfig {* together with `provider`, and dropped when the goal changes agent.*/model?: string;+ /** The score this goal optimises, when it has one; see {@link GoalObjective}. */+ objective?: GoalObjective;/** Who the current pause belongs to; cleared when the goal runs again. */pausedBy?: GoalPauseReason;/** Coordinator-owned lease for initial decomposition; not a user policy. */@@ -588,7 +615,31 @@ export interface GoalItem {* `experiment`: an experiment is a candidate answer under test, a batch is one* reusable transformation applied many times.*/-export type GoalNodeKind = 'problem' | 'experiment' | 'task' | 'finding' | 'decision' | 'batch';+export type GoalNodeKind =+ | 'problem'+ | 'experiment'+ | 'task'+ | 'finding'+ | 'decision'+ | 'batch'+ | GoalMarkKind+ /**+ * A batch's recipe revision. Batches before this kind stored it as a `finding`+ * titled `GOAL_BATCH_TEMPLATE_TITLE`; those rows are left as they are and+ * readers accept both.+ */+ | 'template';++/**+ * A mark (trace) one Task leaves for every other Task in the same Goal: what works+ * (`pattern`), a tool it built (`tool`), what not to touch (`hazard`) and what+ * not to try again (`dead_end`). Unlike a `finding` — the outcome a Task+ * delivered, scoped to its experiment — a mark is Goal-wide, written while the+ * work happens (failures included), and handed to every later run. Runs that+ * use one record `confirms` / `refutes` edges, and the node's `confidence` is+ * derived from them.+ */+export type GoalMarkKind = 'pattern' | 'tool' | 'hazard' | 'dead_end';/** Semantic lifecycle of a node; independent from the execution status of its Task. */export type GoalNodeStatus =@@ -612,7 +663,11 @@ export type GoalEdgeKind =| 'produces'| 'supports'| 'contradicts'- | 'leads_to';+ | 'leads_to'+ /** A run used this mark and it held (`task confirms mark`). */+ | 'confirms'+ /** A run used this mark and it was wrong (`task refutes mark`). */+ | 'refutes';/** The role an immutable Work version plays for a Goal Graph node. */export type GoalNodeWorkVersionRelation = 'input' | 'produced' | 'supports' | 'contradicts';diff --git a/packages/utils/src/goalGraph.test.ts b/packages/utils/src/goalGraph.test.tsindex 2b31a9d4c20..ce020283bc0 100644--- a/packages/utils/src/goalGraph.test.ts+++ b/packages/utils/src/goalGraph.test.ts@@ -5,9 +5,12 @@ import {experimentMembers,experimentStatus,graphScopeIds,+ isBatchTemplate,+ isMarkKind,isProtocolRevision,protocolRevisionCount,provenanceParentId,+ withoutMarks,} from './goalGraph';const node = (@@ -127,3 +130,47 @@ describe('provenance and protocol revisions', () => {expect(protocolRevisionCount(graph, 'older')).toBe(0);});});++describe('marks', () => {+ const withMarks = () => {+ const base = graph();+ return {+ edges: [+ ...base.edges,+ ...[+ ['task', 'pattern', 'produces'],+ ['task', 'hazard', 'confirms'],+ ].map(([sourceNodeId, targetNodeId, kind]) => ({+ ...base.edges[0],+ id: sourceNodeId + targetNodeId,+ kind: kind as GoalGraphSnapshot['edges'][number]['kind'],+ sourceNodeId,+ targetNodeId,+ })),+ ],+ nodes: [...base.nodes, node('pattern', 'pattern', 'active'), node('hazard', 'hazard')],+ };+ };++ it('recognizes only the four mark kinds', () => {+ expect(['pattern', 'tool', 'hazard', 'dead_end'].every(isMarkKind)).toBe(true);+ expect(['finding', 'template', 'task'].some(isMarkKind)).toBe(false);+ });++ it('leaves marks and every edge touching them out of the planning view', () => {+ const view = withoutMarks(withMarks());+ expect(view.nodes.map((item) => item.id)).toEqual(graph().nodes.map((item) => item.id));+ expect(view.edges).toEqual(graph().edges);+ });++ it('returns the same graph when it holds no marks', () => {+ const plain = graph();+ expect(withoutMarks(plain)).toBe(plain);+ });++ it('reads a recipe from its own kind or from the titled finding older batches wrote', () => {+ expect(isBatchTemplate({ kind: 'template', title: 'anything' })).toBe(true);+ expect(isBatchTemplate({ kind: 'finding', title: 'Batch recipe' })).toBe(true);+ expect(isBatchTemplate({ kind: 'finding', title: 'Completed: probe 1' })).toBe(false);+ });+});diff --git a/packages/utils/src/goalGraph.ts b/packages/utils/src/goalGraph.tsindex 15ef119a3de..0158515b60e 100644--- a/packages/utils/src/goalGraph.ts+++ b/packages/utils/src/goalGraph.ts@@ -1,7 +1,44 @@-import type { GoalGraphNode, GoalGraphSnapshot, GoalNodeStatus } from '@lobechat/types';+import { GOAL_BATCH_TEMPLATE_TITLE, GOAL_MARK_KINDS } from '@lobechat/const/goal';+import type {+ GoalGraphNode,+ GoalGraphSnapshot,+ GoalMarkKind,+ GoalNodeKind,+ GoalNodeStatus,+} from '@lobechat/types';type Graph = Pick<GoalGraphSnapshot, 'nodes' | 'edges'>;+export const isMarkKind = (kind: GoalNodeKind | string): kind is GoalMarkKind =>+ (GOAL_MARK_KINDS as readonly string[]).includes(kind);++/**+ * A batch's recipe revision: a `template` node, or — for batches written before+ * that kind — a `finding` with the recipe title.+ */+export const isBatchTemplate = (node: Pick<GoalGraphNode, 'kind' | 'title'>) =>+ node.kind === 'template' || (node.kind === 'finding' && node.title === GOAL_BATCH_TEMPLATE_TITLE);++/**+ * The graph without its marks and the edges touching them.+ *+ * Marks are written by running Tasks at any moment, and their confidence moves+ * as other runs confirm or refute them. They are context for the work, not+ * planning input: a planner whose answer is checked against a graph snapshot+ * reads this view, or every mark a sibling left would make its plan stale.+ */+export const withoutMarks = <T extends Graph>(graph: T): T => {+ if (!graph.nodes.some((node) => isMarkKind(node.kind))) return graph;+ const marks = new Set(graph.nodes.filter((node) => isMarkKind(node.kind)).map((node) => node.id));+ return {+ ...graph,+ edges: graph.edges.filter(+ (edge) => !marks.has(edge.sourceNodeId) && !marks.has(edge.targetNodeId),+ ),+ nodes: graph.nodes.filter((node) => !marks.has(node.id)),+ };+};+/** Containment is a tree; reasoning/provenance edges remain a graph. */export const experimentOwner = (graph: Graph, nodeId: string) =>graph.edges.find((edge) => edge.kind === 'contains' && edge.targetNodeId === nodeId)diff --git a/packages/utils/src/goalObjective.test.ts b/packages/utils/src/goalObjective.test.tsnew file mode 100644index 00000000000..f7c257904e2--- /dev/null+++ b/packages/utils/src/goalObjective.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';++import { isBetterScore, parseEvaluatorOutput } from './goalObjective';++describe('parseEvaluatorOutput', () => {+ it('reads the last JSON result, with validity, summary and numeric metrics', () => {+ const output = [+ '{"progress": 0.5}',+ 'scoring...',+ '{"score": 37.539, "valid": true, "summary": "ok", "metrics": {"M1": 0.78, "note": "x"}}',+ ].join('\n');++ expect(parseEvaluatorOutput(output)).toEqual({+ metrics: { M1: 0.78 },+ score: 37.539,+ summary: 'ok',+ valid: true,+ });+ });++ it('keeps an unrankable JSON result as invalid rather than dropping it', () => {+ expect(parseEvaluatorOutput('{"score": 0, "valid": false, "summary": "crashed"}')).toEqual({+ score: 0,+ summary: 'crashed',+ valid: false,+ });+ });++ it('falls back to TOTAL_SCORE, then a score line, then a bare last number', () => {+ expect(parseEvaluatorOutput('TOTAL_SCORE 10\nlog\nTOTAL_SCORE 12.5\n')?.score).toBe(12.5);+ expect(parseEvaluatorOutput('training done\nScore: -3.25')?.score).toBe(-3.25);+ expect(parseEvaluatorOutput('running\n0.91\n')?.score).toBe(0.91);+ });++ it('finds nothing in output without a score', () => {+ expect(parseEvaluatorOutput('Traceback (most recent call last):\n oops')).toBeUndefined();+ expect(parseEvaluatorOutput('{"valid": true}')).toBeUndefined();+ expect(parseEvaluatorOutput('')).toBeUndefined();+ });+});++describe('isBetterScore', () => {+ it('follows the direction', () => {+ expect(isBetterScore('max', 2, 1)).toBe(true);+ expect(isBetterScore('min', 2, 1)).toBe(false);+ expect(isBetterScore('min', 1, 1)).toBe(false);+ });+});diff --git a/packages/utils/src/goalObjective.ts b/packages/utils/src/goalObjective.tsnew file mode 100644index 00000000000..d1eee4aaa35--- /dev/null+++ b/packages/utils/src/goalObjective.ts@@ -0,0 +1,76 @@+/** What an evaluator's output says about the deliverables it graded. */+export interface EvaluatorResult {+ metrics?: Record<string, number>;+ score: number;+ summary?: string;+ /** False when the evaluator ran but judged the submission unrankable. */+ valid: boolean;+}++const isFiniteNumber = (value: unknown): value is number =>+ typeof value === 'number' && Number.isFinite(value);++const numericMetrics = (value: unknown): Record<string, number> | undefined => {+ if (!value || typeof value !== 'object') return undefined;+ const entries = Object.entries(value as Record<string, unknown>).filter(([, v]) =>+ isFiniteNumber(v),+ ) as [string, number][];+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;+};++const fromJson = (text: string): EvaluatorResult | undefined => {+ // The last JSON object that carries a numeric `score` wins: evaluators often+ // log progress objects before the result.+ const candidates = text.match(/\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/g) ?? [];+ for (const raw of candidates.reverse()) {+ try {+ const data = JSON.parse(raw) as Record<string, unknown>;+ const score = isFiniteNumber(data.score)+ ? data.score+ : typeof data.score === 'string' &&+ data.score.trim() !== '' &&+ Number.isFinite(Number(data.score))+ ? Number(data.score)+ : undefined;+ if (score === undefined) continue;+ return {+ metrics: numericMetrics(data.metrics),+ score,+ summary: typeof data.summary === 'string' && data.summary ? data.summary : undefined,+ valid: data.valid !== false,+ };+ } catch {+ continue;+ }+ }+ return undefined;+};++const NUMBER = String.raw`[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?`;++/**+ * The score in an evaluator's output, or undefined when there is none.+ *+ * Accepted, most specific first: a JSON object with a numeric `score`+ * (optional `valid`, `summary`, `metrics`); a `TOTAL_SCORE <n>` line; a+ * `score: <n>` / `score = <n>` line; a last line that is a bare number. The+ * last match of a form wins, so a final result beats earlier progress output.+ */+export const parseEvaluatorOutput = (output: string): EvaluatorResult | undefined => {+ const json = fromJson(output);+ if (json) return json;+ for (const pattern of [+ new RegExp(String.raw`^\s*TOTAL_SCORE\s+(${NUMBER})\s*$`, 'gim'),+ new RegExp(String.raw`^\s*(?:final\s+)?score\s*[:=]\s*(${NUMBER})\s*$`, 'gim'),+ ]) {+ const matches = [...output.matchAll(pattern)];+ if (matches.length > 0) return { score: Number(matches.at(-1)![1]), valid: true };+ }+ const last = output.trim().split('\n').at(-1)?.trim() ?? '';+ if (new RegExp(`^${NUMBER}$`).test(last)) return { score: Number(last), valid: true };+ return undefined;+};++/** Whether `a` is a better score than `b` in this direction. */+export const isBetterScore = (direction: 'max' | 'min', a: number, b: number) =>+ direction === 'max' ? a > b : a < b;diff --git a/src/features/AgentGoals/ProcessControl/Graph/layout.ts b/src/features/AgentGoals/ProcessControl/Graph/layout.tsindex 9a5ea6eeaa2..f61debce1a0 100644--- a/src/features/AgentGoals/ProcessControl/Graph/layout.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/layout.ts@@ -15,19 +15,29 @@ type LayoutNode = Omit<GoalGraphNode, 'kind'> & { kind: GoalGraphNodeKind };export const NODE_WIDTH = {batch: 260,+ dead_end: 240,decision: 250,experiment: 260,finding: 240,+ hazard: 240,+ pattern: 240,problem: 230,task: 260,+ template: 240,+ tool: 240,} as const;export const NODE_HEIGHT = {batch: 112,+ dead_end: 76,decision: 76,experiment: 112,finding: 76,+ hazard: 76,+ pattern: 76,problem: 76,task: 112,+ template: 76,+ tool: 76,} as const;const RANK_GAP = 56;diff --git a/src/features/AgentGoals/ProcessControl/shared.tsx b/src/features/AgentGoals/ProcessControl/shared.tsxindex e8eef611530..4c4f19f4402 100644--- a/src/features/AgentGoals/ProcessControl/shared.tsx+++ b/src/features/AgentGoals/ProcessControl/shared.tsx@@ -1,6 +1,7 @@import { createStaticStyles, cssVar, Icon, Text } from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';import {+ Ban,Boxes,CircleHelp,FlaskConical,@@ -8,6 +9,9 @@ import {Lightbulb,ListChecks,type LucideIcon,+ Repeat,+ TriangleAlert,+ Wrench,} from 'lucide-react';import { memo } from 'react';@@ -32,6 +36,13 @@ export const KIND_COLOR: Record<GoalGraphNodeKind, { line: string; soft: stringfinding: { line: cssVar.green10, soft: cssVar.green3 },problem: { line: cssVar.purple10, soft: cssVar.purple3 },task: { line: cssVar.blue10, soft: cssVar.blue3 },+ // Marks are notes runs leave each other. Only a client that declares the+ // `marks` graph capability receives them; until then they arrive as findings.+ dead_end: { line: cssVar.colorTextTertiary, soft: cssVar.colorFillTertiary },+ hazard: { line: cssVar.red10, soft: cssVar.red3 },+ pattern: { line: cssVar.lime10, soft: cssVar.lime3 },+ template: { line: cssVar.colorSuccess, soft: cssVar.colorSuccessBg },+ tool: { line: cssVar.gold10, soft: cssVar.gold3 },};/**@@ -57,6 +68,11 @@ export const KIND_ICON: Record<GoalGraphNodeKind, LucideIcon> = {finding: Lightbulb,problem: CircleHelp,task: ListChecks,+ dead_end: Ban,+ hazard: TriangleAlert,+ pattern: Repeat,+ template: SKILL_ICON,+ tool: Wrench,};const styles = createStaticStyles(({ css }) => ({diff --git a/src/services/goal.ts b/src/services/goal.tsindex a8e1714b168..fd1b4ad4ebc 100644--- a/src/services/goal.ts+++ b/src/services/goal.ts@@ -229,13 +229,14 @@ class GoalService {}) => lambdaClient.goal.setBudget.mutate(params);/**- * A batch is only ever created by decomposition, never hand-authored, so the- * add-node surface accepts every kind except `batch`.+ * The kinds a person draws by hand. A batch and its recipe come only from+ * decomposition, and marks are left by runs (`addMark`), so none of them is+ * offered here.*/addNode = async (params: {description?: string;id: string;- kind: Exclude<GoalNodeKind, 'batch'>;+ kind: Extract<GoalNodeKind, 'decision' | 'experiment' | 'finding' | 'problem' | 'task'>;priority?: number;title: string;}) => lambdaClient.goal.addNode.mutate(params);