π€― 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): let agents fix a draft goal's edges from the CLI (#21008)
Arvin Xu3f27f42194ac
diff --git a/.agents/skills/cli/references/goal.md b/.agents/skills/cli/references/goal.mdindex 6db8b3ebdd3..38575538241 100644--- a/.agents/skills/cli/references/goal.md+++ b/.agents/skills/cli/references/goal.md@@ -155,8 +155,9 @@ never shows on that topic's goal tray.From a chat, `create --topic` opens the Goal as a **draft**: nothing isdispatched until it is started. Arrange it first β seed tasks with `-t` or-`--task-file` (titles with descriptions), adjust with `add-node` / `add-edge` β-then launch it with `lh goal start <id>`; the owner can also start it from the+`--task-file` (titles with descriptions and a `dependsOn` list of other titles+in the file, drawn as `depends_on` edges), adjust with `add-node` / `add-edge` /+`remove-edge` β then launch it with `lh goal start <id>`; the owner can also start it from thegoal page. Many tasks of one recipe start as a batch:`lh goal start <id> --rollout canary --recipe-file <md> --probes <2-5 node ids>`moves the probes into a batch and turns every other seed (or only `--units`)@@ -168,9 +169,16 @@ next planning turn.## Decision gates and graph editing-| Command | Effect |-| ------------------------------------------------- | ------------------------------------------------ |-| `lh goal decide <id> <decision-id> --option <id>` | Resolve a durable decision gate |-| `lh goal retire <id> <node-ids...>` | Retire nodes that must not run |-| `lh goal add-node <id> <kind> <title>` | Add a node (`--scope`, `--question`, `-d`, `-p`) |-| `lh goal add-edge <id> <source> <target> <kind>` | Connect two nodes |+| Command | Effect |+| --------------------------------------------------- | ------------------------------------------------ |+| `lh goal decide <id> <decision-id> --option <id>` | Resolve a durable decision gate |+| `lh goal retire <id> <node-ids...>` | Retire nodes that must not run |+| `lh goal add-node <id> <kind> <title>` | Add a node (`--scope`, `--question`, `-d`, `-p`) |+| `lh goal add-edge <id> <source> <target> <kind>` | Connect two nodes |+| `lh goal remove-edge <id> <source> <target> [kind]` | Remove edges from a draft (`--reason`) |++An edge reads `<source> <kind> <target>`: `A depends_on B` means A waits for B.+`A blocks B` is accepted by `add-edge` and `remove-edge` and stored as+`B depends_on A`, which is how `lh goal show` prints it. Only a draft can lose+edges; a started Goal retires nodes instead. `lh goal show` / `list --json` carry+the goal page `url`.diff --git a/apps/cli/src/commands/goal/graphEdit.test.ts b/apps/cli/src/commands/goal/graphEdit.test.tsnew file mode 100644index 00000000000..16873f5cff6--- /dev/null+++ b/apps/cli/src/commands/goal/graphEdit.test.ts@@ -0,0 +1,103 @@+import { Command } from 'commander';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../utils/logger';+import { registerGoalGraphEditCommands, resolveEdge } from './graphEdit';++const { mockClient } = vi.hoisted(() => ({+ mockClient: {+ goal: {+ addEdge: { mutate: vi.fn() },+ removeEdge: { mutate: vi.fn() },+ },+ },+}));++vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));++const source = '11111111-1111-4111-8111-111111111111';+const target = '22222222-2222-4222-8222-222222222222';++const run = (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerGoalGraphEditCommands(program.command('goal'));+ return program.parseAsync(['node', 'test', 'goal', ...args]);+};++describe('resolveEdge', () => {+ it('stores `A blocks B` as `B depends_on A`', () => {+ expect(resolveEdge(source, target, 'blocks')).toEqual({+ kind: 'depends_on',+ sourceNodeId: target,+ targetNodeId: source,+ });+ });++ it('keeps a writable kind as typed', () => {+ expect(resolveEdge(source, target, 'depends_on')).toEqual({+ kind: 'depends_on',+ sourceNodeId: source,+ targetNodeId: target,+ });+ });++ it('names the valid kinds and the direction when the kind is unknown', () => {+ expect(() => resolveEdge(source, target, 'requires')).toThrow(+ /Unknown edge kind "requires".*A depends_on B. means A waits for B[\s\S]*Kinds: depends_on/,+ );+ });+});++describe('goal add-edge / remove-edge', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(log, 'info').mockImplementation(() => {});+ });++ it('add-edge sends the resolved edge and echoes it as a sentence', async () => {+ mockClient.goal.addEdge.mutate.mockResolvedValue({ data: { id: 'edge-1' } });++ await run('add-edge', 'goal-1', source, target, 'blocks');++ expect(mockClient.goal.addEdge.mutate).toHaveBeenCalledWith({+ id: 'goal-1',+ kind: 'depends_on',+ sourceNodeId: target,+ targetNodeId: source,+ });+ expect(log.info).toHaveBeenCalledWith('Created edge edge-1: 22222222 depends_on 11111111');+ });++ it('add-edge rejects an unknown kind before calling the server', async () => {+ await expect(run('add-edge', 'goal-1', source, target, 'requires')).rejects.toThrow(+ /Unknown edge kind/,+ );+ expect(mockClient.goal.addEdge.mutate).not.toHaveBeenCalled();+ });++ it('remove-edge without a kind removes every edge between the pair', async () => {+ mockClient.goal.removeEdge.mutate.mockResolvedValue({ message: 'Removed 2 edge(s)' });++ await run('remove-edge', 'goal-1', source, target, '--reason', 'wrong direction');++ expect(mockClient.goal.removeEdge.mutate).toHaveBeenCalledWith({+ id: 'goal-1',+ kind: undefined,+ reason: 'wrong direction',+ sourceNodeId: source,+ targetNodeId: target,+ });+ expect(log.info).toHaveBeenCalledWith('Removed 2 edge(s): 11111111 any 22222222');+ });++ it('remove-edge undoes a `blocks` edge with the same words that added it', async () => {+ mockClient.goal.removeEdge.mutate.mockResolvedValue({ message: 'Removed 1 edge(s)' });++ await run('remove-edge', 'goal-1', source, target, 'blocks');++ expect(mockClient.goal.removeEdge.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'depends_on', sourceNodeId: target, targetNodeId: source }),+ );+ });+});diff --git a/apps/cli/src/commands/goal/graphEdit.ts b/apps/cli/src/commands/goal/graphEdit.tsnew file mode 100644index 00000000000..bb3169e0638--- /dev/null+++ b/apps/cli/src/commands/goal/graphEdit.ts@@ -0,0 +1,132 @@+import type { GoalEdgeKind } from '@lobechat/types';+import type { Command } from 'commander';++import { getTrpcClient } from '../../api/client';+import { log } from '../../utils/logger';++/** Edge kinds the server accepts from a hand edit; `revises` is exploration-only. */+const writableEdgeKinds = [+ 'depends_on',+ 'decomposes',+ 'contains',+ 'answers',+ 'derived_from',+ 'investigates',+ 'produces',+ 'supports',+ 'contradicts',+ 'leads_to',+] as const satisfies readonly GoalEdgeKind[];++type WritableEdgeKind = (typeof writableEdgeKinds)[number];++const EDGE_DIRECTION_HELP = [+ 'Every edge reads `<source> <kind> <target>`. `A depends_on B` means A waits for B: B runs first.',+ '`A blocks B` is accepted too and stored as `B depends_on A`, the way `lh goal show` prints it.',+ `Kinds: ${writableEdgeKinds.join(', ')}, blocks.`,+].join('\n');++/**+ * Resolve the `<source> <target> <kind>` a person typed into the stored edge.+ * `blocks` is the inverse of `depends_on` and the word `lh goal show` prints,+ * so it is the one an agent reaches for; it swaps the ends instead of failing.+ */+export const resolveEdge = (+ sourceNodeId: string,+ targetNodeId: string,+ kind: string,+): { kind: WritableEdgeKind; sourceNodeId: string; targetNodeId: string } => {+ if (kind === 'blocks')+ return { kind: 'depends_on', sourceNodeId: targetNodeId, targetNodeId: sourceNodeId };+ if (!(writableEdgeKinds as readonly string[]).includes(kind))+ throw new Error(`Unknown edge kind "${kind}". ${EDGE_DIRECTION_HELP}`);+ return { kind: kind as WritableEdgeKind, sourceNodeId, targetNodeId };+};++const describeEdge = (edge: { kind: string; sourceNodeId: string; targetNodeId: string }) =>+ `${edge.sourceNodeId.slice(0, 8)} ${edge.kind} ${edge.targetNodeId.slice(0, 8)}`;++/** Hand edits to a Goal Graph: nodes, edges, and retiring tasks that should not run. */+export function registerGoalGraphEditCommands(goal: Command) {+ goal+ .command('retire <id> <node-ids...>')+ .description(+ 'Retire task nodes that should not run; unfinished tasks depending on them must be retired together',+ )+ .option('--reason <text>', 'Why the nodes are retired')+ .action(async (id: string, nodeIds: string[], options) => {+ const result = await (+ await getTrpcClient()+ ).goal.retireNodes.mutate({ id, nodeIds, reason: options.reason });+ log.info(result.message);+ });++ goal+ .command('add-node <id> <kind> <title>')+ .description('Add a question, experiment container, task, finding, or decision node')+ .option('--scope <experiment-id>', 'Contain this node in an experiment')+ .option('--question <node-id>', 'Question this experiment answers')+ .option('-d, --description <text>')+ .option('-p, --priority <n>')+ .action(+ async (+ id: string,+ kind: 'decision' | 'experiment' | 'finding' | 'problem' | 'task',+ title: string,+ options,+ ) => {+ const result = await (+ await getTrpcClient()+ ).goal.addNode.mutate({+ description: options.description,+ scopeId: options.scope,+ questionId: options.question,+ id,+ kind,+ priority: options.priority ? Number.parseInt(options.priority, 10) : undefined,+ title,+ });+ log.info(`Created node ${result.data.id}`);+ },+ );++ goal+ .command('add-edge <id> <source> <target> <kind>')+ .summary('Connect two Goal Graph nodes')+ .description(EDGE_DIRECTION_HELP)+ .action(async (id: string, source: string, target: string, kind: string) => {+ const edge = resolveEdge(source, target, kind);+ const result = await (await getTrpcClient()).goal.addEdge.mutate({ id, ...edge });+ log.info(`Created edge ${result.data.id}: ${describeEdge(edge)}`);+ });++ goal+ .command('remove-edge <id> <source> <target> [kind]')+ .summary('Remove an edge from a draft goal')+ .description(+ [+ 'Remove the edges from <source> to <target> on a draft goal, or only those of [kind].',+ 'A started goal keeps its edges; retire the task nodes instead.',+ '',+ EDGE_DIRECTION_HELP,+ ].join('\n'),+ )+ .option('--reason <text>', 'Why the edge is removed, kept on the audit trail')+ .action(+ async (+ id: string,+ source: string,+ target: string,+ kind: string | undefined,+ options: { reason?: string },+ ) => {+ const edge = kind+ ? resolveEdge(source, target, kind)+ : { kind: undefined, sourceNodeId: source, targetNodeId: target };+ const result = await (+ await getTrpcClient()+ ).goal.removeEdge.mutate({ id, ...edge, reason: options.reason });+ log.info(`${result.message}: ${describeEdge({ ...edge, kind: edge.kind ?? 'any' })}`);+ },+ );+}diff --git a/apps/cli/src/commands/goal/index.links.test.ts b/apps/cli/src/commands/goal/index.links.test.tsnew file mode 100644index 00000000000..a7b2e2200b3--- /dev/null+++ b/apps/cli/src/commands/goal/index.links.test.ts@@ -0,0 +1,158 @@+import { Buffer } from 'node:buffer';++import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type * as LoggerModule from '../../utils/logger';+import { log } from '../../utils/logger';+import { registerGoalCommand } from '.';++const { files, mockClient } = vi.hoisted(() => ({+ files: { tasks: '' },+ mockClient: {+ goal: {+ addEdge: { mutate: vi.fn() },+ create: { mutate: vi.fn() },+ createConversationGoal: { mutate: vi.fn() },+ graph: { query: vi.fn() },+ list: { query: vi.fn() },+ },+ },+}));++const taskFile = JSON.stringify([+ 'Signal',+ { description: 'rules', dependsOn: ['Signal'], title: 'Policy' },+]);+vi.mock('node:fs/promises', () => ({ readFile: async () => files.tasks }));+vi.mock('../../utils/logger', async (importOriginal) => {+ const actual = await importOriginal<typeof LoggerModule>();+ return { log: { ...actual.log, warn: vi.fn() } };+});+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));+vi.mock('../task/url', () => ({+ resolveAppUrlBuilder: vi+ .fn()+ .mockResolvedValue((pathname: string) => `https://app.lobehub.com${pathname}`),+}));++const run = (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerGoalCommand(program);+ return program.parseAsync(['node', 'test', 'goal', ...args]);+};++const output = () =>+ vi+ .mocked(console.log)+ .mock.calls.map(([value]) => (value === undefined ? '' : String(value)))+ .join('\n');++const snapshot = () => ({+ decisions: [],+ edges: [] as unknown[],+ events: [],+ goal: { id: 'goal-1', requirement: null, status: 'draft', title: 'Wake' },+ nodes: [+ { id: 'signal-id', kind: 'task', status: 'proposed', taskId: null, title: 'Signal' },+ { id: 'policy-id', kind: 'task', status: 'proposed', taskId: null, title: 'Policy' },+ ],+ workVersions: [],+});++beforeEach(() => {+ vi.clearAllMocks();+ // An operation token switches reads to their operation twins; these tests use the plain ones.+ vi.stubEnv('LOBEHUB_JWT', undefined);+ vi.spyOn(console, 'log').mockImplementation(() => {});+ files.tasks = taskFile;+});++afterEach(() => vi.unstubAllEnvs());++describe('goal links', () => {+ it('show prints the goal page and puts it in --json', async () => {+ mockClient.goal.graph.query.mockResolvedValue({ data: snapshot() });++ await run('show', 'goal-1');+ expect(output()).toContain('https://app.lobehub.com/goal/goal-1');++ vi.mocked(console.log).mockClear();+ await run('show', 'goal-1', '--json');+ expect(JSON.parse(output())).toMatchObject({ url: 'https://app.lobehub.com/goal/goal-1' });+ });++ it('list --json carries each goal page', async () => {+ mockClient.goal.list.query.mockResolvedValue({ goals: [{ goal: { id: 'goal-1' } }] });++ await run('list', '--json');++ expect(JSON.parse(output())).toEqual([+ { goal: { id: 'goal-1' }, url: 'https://app.lobehub.com/goal/goal-1' },+ ]);+ });+});++describe('goal create --task-file dependsOn', () => {+ const drawn = () => ({+ ...snapshot(),+ edges: [{ kind: 'depends_on', sourceNodeId: 'policy-id', targetNodeId: 'signal-id' }],+ });+ const operationJwt = `x.${Buffer.from(JSON.stringify({ purpose: 'hetero-operation' })).toString('base64url')}.y`;++ it('sends dependsOn with the seeds so the server draws the edges', async () => {+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-1');+ mockClient.goal.create.mutate.mockResolvedValue({ data: drawn() });++ await run('create', 'Wake', '--topic', '--task-file', 'tasks.json');++ expect(mockClient.goal.create.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ tasks: ['Signal', { dependsOn: ['Signal'], description: 'rules', title: 'Policy' }],+ }),+ );+ expect(mockClient.goal.addEdge.mutate).not.toHaveBeenCalled();+ expect(log.warn).not.toHaveBeenCalled();+ // The printed graph shows the edge: Signal blocks Policy.+ expect(output()).toContain('blocks policy-i');+ });++ it('needs no ordinary-route write from a run holding an operation token', async () => {+ // Device and gateway runs may only call operation endpoints; a follow-up+ // `addEdge` would be refused after the draft already exists.+ vi.stubEnv('LOBEHUB_JWT', operationJwt);+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-1');+ mockClient.goal.createConversationGoal.mutate.mockResolvedValue({ data: drawn() });++ await run('create', 'Wake', '--topic', '--task-file', 'tasks.json');++ expect(mockClient.goal.createConversationGoal.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ operationId: 'op-1',+ tasks: ['Signal', { dependsOn: ['Signal'], description: 'rules', title: 'Policy' }],+ }),+ );+ expect(mockClient.goal.addEdge.mutate).not.toHaveBeenCalled();+ });++ it('warns when the server dropped dependsOn', async () => {+ mockClient.goal.create.mutate.mockResolvedValue({ data: snapshot() });++ await run('create', 'Wake', '--task-file', 'tasks.json');++ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('"Policy" depends on "Signal"'));+ });++ it('refuses a dependency cycle before creating anything', async () => {+ files.tasks = JSON.stringify([+ { dependsOn: ['B'], title: 'A' },+ { dependsOn: ['A'], title: 'B' },+ ]);++ await expect(run('create', 'Wake', '--task-file', 'tasks.json')).rejects.toThrow(+ '--task-file: dependsOn forms a cycle: "A" β "B" β "A"',+ );+ expect(mockClient.goal.create.mutate).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal/index.test.tssimilarity index 99%rename from apps/cli/src/commands/goal.test.tsrename to apps/cli/src/commands/goal/index.test.tsindex ccf1d587d2d..099c3454b0e 100644--- a/apps/cli/src/commands/goal.test.ts+++ b/apps/cli/src/commands/goal/index.test.ts@@ -3,10 +3,10 @@ import { Buffer } from 'node:buffer';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type * as FormatModule from '../utils/format';-import { confirm } from '../utils/format';-import { log } from '../utils/logger';-import { registerGoalCommand } from './goal';+import type * as FormatModule from '../../utils/format';+import { confirm } from '../../utils/format';+import { log } from '../../utils/logger';+import { registerGoalCommand } from '.';const { mockClient } = vi.hoisted(() => ({mockClient: {@@ -44,15 +44,15 @@ vi.mock('node:fs/promises', () => ({},}));-vi.mock('../utils/format', async (importOriginal) => ({+vi.mock('../../utils/format', async (importOriginal) => ({...(await importOriginal<typeof FormatModule>()),confirm: vi.fn(),}));-vi.mock('../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));// Building the app URL otherwise resolves a workspace and a server, which needs// a real login; the link's shape is what this file is asserting, not its host.-vi.mock('./task/url', () => ({+vi.mock('../task/url', () => ({resolveAppUrlBuilder: vi.fn().mockResolvedValue((pathname: string) => `https://app.lobehub.com${pathname}`),diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal/index.tssimilarity index 94%rename from apps/cli/src/commands/goal.tsrename to apps/cli/src/commands/goal/index.tsindex e5d8bf36dc8..a9bd8434b1d 100644--- a/apps/cli/src/commands/goal.ts+++ b/apps/cli/src/commands/goal/index.ts@@ -11,33 +11,21 @@ import type {GoalPlanContext,GoalTickResult,} from '@lobechat/types';+import { goalSeedDependencyProblem } from '@lobechat/utils/goalSeeds';import { type Command, Option } from 'commander';import pc from 'picocolors';-import { getTrpcClient } from '../api/client';-import { confirm, outputJson, printTable, truncate } from '../utils/format';-import { log } from '../utils/logger';-import { resolveAppUrlBuilder } from './task/url';+import { getTrpcClient } from '../../api/client';+import { confirm, outputJson, printTable, truncate } from '../../utils/format';+import { log } from '../../utils/logger';+import { resolveAppUrlBuilder } from '../task/url';+import { registerGoalGraphEditCommands } from './graphEdit';+import { missingSeedDependencies, parseTaskFile } from './seedTasks';// Typed rather than inferred: an `as const` map is indexable by a widened// `any` node kind, which is how a renamed kind silently printed `undefined`// here after the type checker had signed off everywhere else.-/** `--task-file`: a JSON array of seed tasks, each a title or {"title","description"}. */-const parseTaskFile = (raw: string): Array<string | { description?: string; title: string }> => {- const parsed: unknown = JSON.parse(raw);- if (!Array.isArray(parsed)) throw new Error('--task-file must hold a JSON array');- return parsed.map((item, index) => {- if (typeof item === 'string' && item.trim()) return item.trim();- if (item && typeof item === 'object' && typeof item.title === 'string' && item.title.trim())- return {- description: typeof item.description === 'string' ? item.description : undefined,- title: item.title.trim(),- };- throw new Error(`--task-file entry ${index} needs a title`);- });-};-/** `--variant mechanism=replica,swr` β one axis and its values. */const parseVariant = (raw: string) => {const separator = raw.indexOf('=');@@ -464,6 +452,19 @@ const goalReads = async () => {};};+/**+ * Builds goal page links. Best-effort: a read must not fail over a link, and an+ * operation-token run may be refused the workspace lookup behind it.+ */+const goalUrlBuilder = async () => {+ try {+ const buildUrl = await resolveAppUrlBuilder(await getTrpcClient());+ return (id: string) => buildUrl(`/goal/${encodeURIComponent(id)}`);+ } catch {+ return () => undefined;+ }+};+export function registerGoalCommand(program: Command) {const goal = program.command('goal').description('Run long-horizon Goal Graphs');goal@@ -620,8 +621,8 @@ export function registerGoalCommand(program: Command) {'','From a chat, create it with --topic. The goal opens as a draft bound to this topic: nothing is','dispatched until it is started, so arrange it first:',- ' 1. Place the tasks: -t <titles...>, --task-file <json> for titles with descriptions, or later',- ' `lh goal add-node <id> task <title> -d <brief>` and `lh goal add-edge` for prerequisites.',+ ' 1. Place the tasks: -t <titles...>, --task-file <json> for briefs and dependsOn order, or later',+ ' `lh goal add-node <id> task <title> -d <brief>` and `lh goal add-edge` (`remove-edge` undoes one).',' 2. Check the graph the command prints (or `lh goal show <id>`).',' 3. Start it: `lh goal start <id>` (see `lh man goal start`). The owner can also start it from the',' goal page.',@@ -642,7 +643,7 @@ export function registerGoalCommand(program: Command) {.option('-t, --task <title...>', 'Seed task node titles (omit to let the planner decompose)').option('--task-file <path>',- 'Seed tasks from a JSON array of {"title","description"}; use it when each task needs its own brief',+ 'Seed tasks from a JSON array of {"title","description","dependsOn":[titles]}',).option('--agent <id>',@@ -697,10 +698,14 @@ export function registerGoalCommand(program: Command) {...((options.task as string[] | undefined) ?? []),...(options.taskFile ? parseTaskFile(await readFile(options.taskFile, 'utf8')) : []),];+ const seedProblem = goalSeedDependencyProblem(seedTasks);+ if (seedProblem) throw new Error(`--task-file: ${seedProblem}`);const operationId = process.env.LOBEHUB_OPERATION_ID;const fromTopic = Boolean(options.topic || options.conversation);if (fromTopic && !operationId) {- throw new Error('--topic must run inside an agent topic (LOBEHUB_OPERATION_ID)');+ throw new Error(+ '--topic must run inside an agent topic (LOBEHUB_OPERATION_ID). If this shell lost it, find the running operation with `lh trace op list --topic <topicId>` and export it',+ );}const client = await getTrpcClient();const buildUrl = await resolveAppUrlBuilder(client);@@ -787,6 +792,11 @@ export function registerGoalCommand(program: Command) {agentId: options.agent ?? process.env.LOBEHUB_AGENT_ID,createdByAgentId: process.env.LOBEHUB_AGENT_ID,});+ const undrawn = missingSeedDependencies(result.data!, seedTasks);+ if (undrawn.length)+ log.warn(+ `The server did not draw these dependsOn edges (it may predate dependsOn); add them with \`lh goal add-edge\`: ${undrawn.join('; ')}`,+ );const turnToken = 'turnToken' in result ? result.turnToken : undefined;// `goal.create` returns the whole graph snapshot, so the id is on its// goal β `result.data.id` is undefined, and the CLI cannot resolve the@@ -905,7 +915,14 @@ export function registerGoalCommand(program: Command) {projectId: options.project,statuses: options.status,});- if (options.json !== undefined) return outputJson(result.goals, options.json);+ if (options.json !== undefined) {+ const goalUrl = await goalUrlBuilder();+ const goals = result.goals.map((item: { goal: { id: string } }) => ({+ ...item,+ url: goalUrl(item.goal.id),+ }));+ return outputJson(goals, options.json);+ }if (result.goals.length === 0) return log.info('No goals yet.');printTable(result.goals.map((item) => [@@ -924,8 +941,10 @@ export function registerGoalCommand(program: Command) {const show = async (id: string, options: { json?: boolean | string }) => {const reads = await goalReads();const result = await reads.graph.query({ id });- if (options.json !== undefined) return outputJson(result.data, options.json);+ const url = (await goalUrlBuilder())(result.data.goal.id);+ if (options.json !== undefined) return outputJson({ ...result.data, url }, options.json);printGraph(result.data);+ if (url) console.log(`${pc.bold('goal')}: ${url}`);};goal.command('show <id>')@@ -1338,60 +1357,5 @@ export function registerGoalCommand(program: Command) {log.info(result.message);});- goal- .command('retire <id> <node-ids...>')- .description(- 'Retire task nodes that should not run; unfinished tasks depending on them must be retired together',- )- .option('--reason <text>', 'Why the nodes are retired')- .action(async (id: string, nodeIds: string[], options) => {- const result = await (- await getTrpcClient()- ).goal.retireNodes.mutate({ id, nodeIds, reason: options.reason });- log.info(result.message);- });-- goal- .command('add-node <id> <kind> <title>')- .description('Add a question, experiment container, task, finding, or decision node')- .option('--scope <experiment-id>', 'Contain this node in an experiment')- .option('--question <node-id>', 'Question this experiment answers')- .option('-d, --description <text>')- .option('-p, --priority <n>')- .action(- async (- id: string,- kind: 'decision' | 'experiment' | 'finding' | 'problem' | 'task',- title: string,- options,- ) => {- const result = await (- await getTrpcClient()- ).goal.addNode.mutate({- description: options.description,- scopeId: options.scope,- questionId: options.question,- id,- kind,- priority: options.priority ? Number.parseInt(options.priority, 10) : undefined,- title,- });- log.info(`Created node ${result.data.id}`);- },- );-- goal- .command('add-edge <id> <source> <target> <kind>')- .description('Connect two Goal Graph nodes')- .action(async (id: string, sourceNodeId: string, targetNodeId: string, kind) => {- const result = await (- await getTrpcClient()- ).goal.addEdge.mutate({- id,- kind,- sourceNodeId,- targetNodeId,- });- log.info(`Created edge ${result.data.id}`);- });+ registerGoalGraphEditCommands(goal);}diff --git a/apps/cli/src/commands/goal/seedTasks.test.ts b/apps/cli/src/commands/goal/seedTasks.test.tsnew file mode 100644index 00000000000..cd4136503e0--- /dev/null+++ b/apps/cli/src/commands/goal/seedTasks.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';++import { missingSeedDependencies, parseTaskFile } from './seedTasks';++describe('parseTaskFile', () => {+ it('reads titles, briefs and dependsOn', () => {+ expect(+ parseTaskFile(+ JSON.stringify([+ 'Signal',+ { description: 'rules', dependsOn: [' Signal '], title: 'Policy' },+ ]),+ ),+ ).toEqual(['Signal', { dependsOn: ['Signal'], description: 'rules', title: 'Policy' }]);+ });++ it('rejects a dependsOn that is not a list of titles', () => {+ expect(() => parseTaskFile(JSON.stringify([{ dependsOn: 'Signal', title: 'Policy' }]))).toThrow(+ '--task-file entry 0: dependsOn must be an array of task titles',+ );+ });++ it('rejects an entry without a title', () => {+ expect(() => parseTaskFile(JSON.stringify([{ description: 'x' }]))).toThrow(+ '--task-file entry 0 needs a title',+ );+ });+});++describe('missingSeedDependencies', () => {+ const nodes = [+ { id: 'signal-id', title: 'Signal' },+ { id: 'policy-id', title: 'Policy' },+ ] as any;+ const seeds = ['Signal', { dependsOn: ['Signal'], title: 'Policy' }];++ it('is empty when the server drew every dependsOn', () => {+ const edges = [{ kind: 'depends_on', sourceNodeId: 'policy-id', targetNodeId: 'signal-id' }];++ expect(missingSeedDependencies({ edges, nodes } as any, seeds)).toEqual([]);+ });++ it('lists the dependencies a server that predates dependsOn dropped', () => {+ expect(missingSeedDependencies({ edges: [], nodes } as any, seeds)).toEqual([+ '"Policy" depends on "Signal"',+ ]);+ });+});diff --git a/apps/cli/src/commands/goal/seedTasks.ts b/apps/cli/src/commands/goal/seedTasks.tsnew file mode 100644index 00000000000..f1ce8e8e728--- /dev/null+++ b/apps/cli/src/commands/goal/seedTasks.ts@@ -0,0 +1,57 @@+import type { GoalGraphSnapshot } from '@lobechat/types';+import type { GoalSeedTask } from '@lobechat/utils/goalSeeds';++/**+ * `--task-file`: a JSON array of seed tasks, each a title or+ * {"title","description","dependsOn"}. `dependsOn` names other entries of the+ * same file by title; the server draws them as `depends_on` edges while it+ * creates the goal, so the seeded graph arrives with its order in place.+ */+export const parseTaskFile = (raw: string): Array<GoalSeedTask | string> => {+ const parsed: unknown = JSON.parse(raw);+ if (!Array.isArray(parsed)) throw new Error('--task-file must hold a JSON array');+ const tasks = parsed.map((item, index): GoalSeedTask | string => {+ if (typeof item === 'string' && item.trim()) return item.trim();+ if (!item || typeof item !== 'object' || typeof item.title !== 'string' || !item.title.trim())+ throw new Error(`--task-file entry ${index} needs a title`);+ if (+ item.dependsOn !== undefined &&+ (!Array.isArray(item.dependsOn) ||+ !item.dependsOn.every((dep: unknown) => typeof dep === 'string'))+ )+ throw new Error(`--task-file entry ${index}: dependsOn must be an array of task titles`);+ return {+ dependsOn: item.dependsOn?.map((dep: string) => dep.trim()),+ description: typeof item.description === 'string' ? item.description : undefined,+ title: item.title.trim(),+ };+ });+ return tasks;+};++/**+ * Seed dependencies the created graph does not carry. A server that predates+ * `dependsOn` drops the field silently, so the CLI checks what came back+ * instead of trusting that it was understood.+ */+export const missingSeedDependencies = (+ graph: Pick<GoalGraphSnapshot, 'edges' | 'nodes'>,+ seeds: Array<GoalSeedTask | string>,+): string[] => {+ if (!seeds.some((seed) => typeof seed !== 'string' && seed.dependsOn?.length)) return [];+ const titleById = new Map(graph.nodes.map((node) => [node.id, node.title]));+ const drawn = new Set(+ graph.edges+ .filter((edge) => edge.kind === 'depends_on')+ .map(+ (edge) => `${titleById.get(edge.sourceNodeId)}\u0000${titleById.get(edge.targetNodeId)}`,+ ),+ );+ return seeds.flatMap((seed) =>+ typeof seed === 'string'+ ? []+ : (seed.dependsOn ?? [])+ .filter((dep) => !drawn.has(`${seed.title}\u0000${dep}`))+ .map((dep) => `"${seed.title}" depends on "${dep}"`),+ );+};diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex 1f9f410ea46..6845fc04d76 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -3,8 +3,6 @@ import { MAX_GOAL_METRIC_CRITERIA, summarizeGoalSupervision } from '@lobechat/tyimport { TRPCError } from '@trpc/server';import { z } from 'zod';-import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { GoalModel } from '@/database/models/goal';import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -26,25 +24,9 @@ import {} from '@/server/services/heterogeneousAgent/operationPrincipal';import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';+import { goalGraphEditProcedures } from './goalGraphEdit';+import { goalProcedure, goalWriteProcedure, idInput, mapGoalError } from './goalProcedures';-const goalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>- opts.next({- ctx: {- goalModel: new GoalModel(- opts.ctx.serverDB,- opts.ctx.userId,- opts.ctx.workspaceId ?? undefined,- ),- goalService: new GoalService(- opts.ctx.serverDB,- opts.ctx.userId,- opts.ctx.workspaceId ?? undefined,- ),- },- }),-);-const goalWriteProcedure = goalProcedure.use(withScopedPermission('agent:update'));-const idInput = z.object({ id: z.string() });/*** A wrap-up report submitted from a run. The metadata passes through as a* record: `GoalReportStore.submit` parses it with the report schema and checks@@ -150,12 +132,16 @@ const conversationGoalInput = z.object({projectId: z.string().optional(),requirement: z.string().optional(),title: z.string().min(1),- /** Seed task nodes, in dependency-free order. */+ /** Seed task nodes; `dependsOn` names other seeds by title. */tasks: z.array(z.union([z.string().min(1),- z.object({ description: z.string().optional(), title: z.string().min(1) }),+ z.object({+ dependsOn: z.array(z.string().min(1)).optional(),+ description: z.string().optional(),+ title: z.string().min(1),+ }),]),).optional(),@@ -196,16 +182,6 @@ const bindTopicResponse = ({turnToken,});-function mapGoalError(error: unknown, operation: string): never {- if (error instanceof TRPCError) throw error;- console.error(`[goal:${operation}]`, error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: `Failed to ${operation} goal`,- });-}-/** `<ISO>|<event id>` β opaque to callers, so the pair can change shape later. */const encodeEventCursor = (cursor: { createdAt: Date; id: string }) =>`${cursor.createdAt.toISOString()}|${cursor.id}`;@@ -557,62 +533,7 @@ export const goalRouter = router({});return { data, success: true };}),- addEdge: goalWriteProcedure- .input(- idInput.extend({- kind: z.enum([- 'contains',- 'answers',- 'decomposes',- 'depends_on',- 'derived_from',- 'investigates',- 'produces',- 'supports',- 'contradicts',- 'leads_to',- ]),- sourceNodeId: z.string().uuid(),- targetNodeId: z.string().uuid(),- }),- )- .mutation(async ({ ctx, input: { id, ...input } }) => {- try {- return {- data: await ctx.goalService.addEdge(- id,- input.sourceNodeId,- input.targetNodeId,- input.kind,- ),- success: true,- };- } catch (error) {- mapGoalError(error, 'addEdge');- }- }),-- addNode: goalWriteProcedure- .input(- idInput.extend({- description: z.string().optional(),- kind: z.enum(['problem', 'experiment', 'task', 'finding', 'decision']),- scopeId: z.string().uuid().optional(),- questionId: z.string().uuid().optional(),- priority: z.number().int().optional(),- status: z- .enum(['proposed', 'active', 'waiting', 'resolved', 'rejected', 'retired'])- .optional(),- title: z.string().min(1),- }),- )- .mutation(async ({ ctx, input: { id, ...input } }) => {- try {- return { data: await ctx.goalService.addNode(id, input), success: true };- } catch (error) {- mapGoalError(error, 'addNode');- }- }),+ ...goalGraphEditProcedures,/*** `/goal` from a conversation run authenticated by its operation token (devicediff --git a/apps/server/src/routers/lambda/goalGraphEdit.test.ts b/apps/server/src/routers/lambda/goalGraphEdit.test.tsnew file mode 100644index 00000000000..08290e7e909--- /dev/null+++ b/apps/server/src/routers/lambda/goalGraphEdit.test.ts@@ -0,0 +1,111 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: vi.fn(function () {+ return (opts: any) => opts.next({ ctx: opts.ctx });+ }),+}));++vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {+ const { authedProcedure } = await import('@/libs/trpc/lambda');+ return { ...(await importOriginal<object>()), wsCompatProcedure: authedProcedure };+});++vi.mock('@/server/services/aiAgent', () => ({ AiAgentService: vi.fn() }));+vi.mock('@/server/services/goal', () => ({ GoalService: vi.fn() }));++const mockFindById = vi.fn();+vi.mock('@/database/models/goal', () => ({+ GoalModel: vi.fn(function () {+ return { findById: mockFindById };+ }),+}));++const mockRemoveDraftEdges = vi.fn();+vi.mock('@/database/models/goalGraph', () => ({+ GoalGraphModel: vi.fn(function () {+ return { removeDraftEdges: mockRemoveDraftEdges };+ }),+}));++const { router } = await import('@/libs/trpc/lambda');+const { goalGraphEditProcedures } = await import('./goalGraphEdit');++const source = '00000000-0000-4000-8000-000000000001';+const target = '00000000-0000-4000-8000-000000000002';++describe('goalGraphEditProcedures.removeEdge', () => {+ const ctx: any = { serverDB: {}, userId: 'user-1', workspaceId: null };+ const caller = router(goalGraphEditProcedures).createCaller(ctx);++ beforeEach(() => {+ vi.clearAllMocks();+ mockFindById.mockResolvedValue({ id: 'goal_1', userId: 'user-1' });+ });++ it('removes the matching edges of a draft', async () => {+ mockRemoveDraftEdges.mockResolvedValue({ edgeIds: ['edge-1'], status: 'removed' });++ const result = await caller.removeEdge({+ id: 'goal_1',+ kind: 'depends_on',+ sourceNodeId: source,+ targetNodeId: target,+ });++ expect(mockRemoveDraftEdges).toHaveBeenCalledWith(+ 'goal_1',+ { kind: 'depends_on', sourceNodeId: source, targetNodeId: target },+ undefined,+ );+ expect(result).toMatchObject({ data: { edgeIds: ['edge-1'] }, success: true });+ });++ it('refuses a started goal with the reason', async () => {+ mockRemoveDraftEdges.mockResolvedValue({ goalStatus: 'running', status: 'not_draft' });++ await expect(+ caller.removeEdge({ id: 'goal_1', sourceNodeId: source, targetNodeId: target }),+ ).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: 'Only a draft Goal can remove edges; this one is running',+ });+ });++ it('says so when no edge matched', async () => {+ mockRemoveDraftEdges.mockResolvedValue({ edgeIds: [], status: 'removed' });++ await expect(+ caller.removeEdge({+ id: 'goal_1',+ kind: 'depends_on',+ sourceNodeId: source,+ targetNodeId: target,+ }),+ ).rejects.toMatchObject({+ code: 'NOT_FOUND',+ message: `No depends_on edge from ${source} to ${target}`,+ });+ });++ it("refuses a workspace member editing a colleague's goal", async () => {+ mockFindById.mockResolvedValue({ id: 'goal_1', userId: 'colleague' });+ const memberCaller = router(goalGraphEditProcedures).createCaller({+ ...ctx,+ workspaceId: 'ws-1',+ workspaceRole: 'member',+ });++ await expect(+ memberCaller.removeEdge({ id: 'goal_1', sourceNodeId: source, targetNodeId: target }),+ ).rejects.toThrow(/Only the creator or a workspace owner/);+ expect(mockRemoveDraftEdges).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/goalGraphEdit.ts b/apps/server/src/routers/lambda/goalGraphEdit.tsnew file mode 100644index 00000000000..86ca78d4506--- /dev/null+++ b/apps/server/src/routers/lambda/goalGraphEdit.ts@@ -0,0 +1,118 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { GoalGraphModel } from '@/database/models/goalGraph';++import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';+import { goalWriteProcedure, idInput, mapGoalError } from './goalProcedures';++/** Edge kinds a caller may write; `revises` stays internal to exploration. */+const writableEdgeKind = z.enum([+ 'contains',+ 'answers',+ 'decomposes',+ 'depends_on',+ 'derived_from',+ 'investigates',+ 'produces',+ 'supports',+ 'contradicts',+ 'leads_to',+]);++/** Hand edits to a Goal Graph's nodes and edges, spread into `goalRouter`. */+export const goalGraphEditProcedures = {+ addEdge: goalWriteProcedure+ .input(+ idInput.extend({+ kind: writableEdgeKind,+ sourceNodeId: z.string().uuid(),+ targetNodeId: z.string().uuid(),+ }),+ )+ .mutation(async ({ ctx, input: { id, ...input } }) => {+ try {+ return {+ data: await ctx.goalService.addEdge(+ id,+ input.sourceNodeId,+ input.targetNodeId,+ input.kind,+ ),+ success: true,+ };+ } catch (error) {+ mapGoalError(error, 'addEdge');+ }+ }),++ addNode: goalWriteProcedure+ .input(+ idInput.extend({+ description: z.string().optional(),+ kind: z.enum(['problem', 'experiment', 'task', 'finding', 'decision']),+ scopeId: z.string().uuid().optional(),+ questionId: z.string().uuid().optional(),+ priority: z.number().int().optional(),+ status: z+ .enum(['proposed', 'active', 'waiting', 'resolved', 'rejected', 'retired'])+ .optional(),+ title: z.string().min(1),+ }),+ )+ .mutation(async ({ ctx, input: { id, ...input } }) => {+ try {+ return { data: await ctx.goalService.addNode(id, input), success: true };+ } catch (error) {+ mapGoalError(error, 'addNode');+ }+ }),++ /**+ * Undo a mis-drawn edge while the Goal is still a draft. Without it, one+ * wrong `depends_on` meant deleting the draft and seeding it again.+ */+ removeEdge: goalWriteProcedure+ .input(+ idInput.extend({+ /** Omit to remove every edge from source to target. */+ kind: writableEdgeKind.optional(),+ reason: z.string().optional(),+ sourceNodeId: z.string().uuid(),+ targetNodeId: z.string().uuid(),+ }),+ )+ .mutation(async ({ ctx, input: { id, reason, ...match } }) => {+ try {+ // Same creator-or-owner rule as retire/delete: removal is destructive.+ const goal = await ctx.goalModel.findById(id);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');++ const result = await new GoalGraphModel(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).removeDraftEdges(id, match, reason);+ if (result.status === 'not_found')+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ if (result.status === 'not_draft')+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: `Only a draft Goal can remove edges; this one is ${result.goalStatus}`,+ });+ if (result.edgeIds.length === 0)+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: `No ${match.kind ? `${match.kind} ` : ''}edge from ${match.sourceNodeId} to ${match.targetNodeId}`,+ });+ return {+ data: { edgeIds: result.edgeIds },+ message: `Removed ${result.edgeIds.length} edge(s)`,+ success: true,+ };+ } catch (error) {+ mapGoalError(error, 'removeEdge');+ }+ }),+};diff --git a/apps/server/src/routers/lambda/goalProcedures.ts b/apps/server/src/routers/lambda/goalProcedures.tsnew file mode 100644index 00000000000..b47fe8b74f0--- /dev/null+++ b/apps/server/src/routers/lambda/goalProcedures.ts@@ -0,0 +1,38 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { GoalModel } from '@/database/models/goal';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { GoalService } from '@/server/services/goal';++/** Procedures and helpers shared by `goalRouter` and its spread-in procedure groups. */+export const goalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>+ opts.next({+ ctx: {+ goalModel: new GoalModel(+ opts.ctx.serverDB,+ opts.ctx.userId,+ opts.ctx.workspaceId ?? undefined,+ ),+ goalService: new GoalService(+ opts.ctx.serverDB,+ opts.ctx.userId,+ opts.ctx.workspaceId ?? undefined,+ ),+ },+ }),+);+export const goalWriteProcedure = goalProcedure.use(withScopedPermission('agent:update'));+export const idInput = z.object({ id: z.string() });++export function mapGoalError(error: unknown, operation: string): never {+ if (error instanceof TRPCError) throw error;+ console.error(`[goal:${operation}]`, error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: `Failed to ${operation} goal`,+ });+}diff --git a/apps/server/src/services/goal/index.seedDependencies.test.ts b/apps/server/src/services/goal/index.seedDependencies.test.tsnew file mode 100644index 00000000000..f369b3288d8--- /dev/null+++ b/apps/server/src/services/goal/index.seedDependencies.test.ts@@ -0,0 +1,55 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { goalEdges, goalEvents, goalNodes, goals, users } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { GoalService } from './index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-seed-dependencies-user';++beforeEach(async () => {+ await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();+});++afterEach(async () => {+ await serverDB.delete(goalEdges);+ await serverDB.delete(goalEvents);+ await serverDB.delete(goalNodes);+ await serverDB.delete(goals);+ await serverDB.delete(users);+});++describe('GoalService.create seed dependencies', () => {+ it('draws each dependsOn as a depends_on edge in the same call that seeds the tasks', async () => {+ const graph = await new GoalService(serverDB, userId).create({+ draft: true,+ tasks: ['Signal', { dependsOn: ['Signal'], description: 'rules', title: 'Policy' }],+ title: 'Wake',+ });++ const idOf = (title: string) =>+ graph.nodes.find((node) => node.kind === 'task' && node.title === title)!.id;+ expect(graph.edges.filter((edge) => edge.kind === 'depends_on')).toEqual([+ expect.objectContaining({ sourceNodeId: idOf('Policy'), targetNodeId: idOf('Signal') }),+ ]);+ });++ it('refuses a dependency cycle before creating the goal', async () => {+ await expect(+ new GoalService(serverDB, userId).create({+ tasks: [+ { dependsOn: ['B'], title: 'A' },+ { dependsOn: ['A'], title: 'B' },+ ],+ title: 'Cyclic',+ }),+ ).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ message: 'dependsOn forms a cycle: "A" β "B" β "A"',+ });+ expect(await serverDB.select().from(goals)).toHaveLength(0);+ });+});diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 973a3a04c41..d8b31245429 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -44,6 +44,7 @@ import type {} from '@lobechat/types';import { isAgentOperationInFlight } from '@lobechat/types';import { experimentOwner, provenanceParentId } from '@lobechat/utils/goalGraph';+import { goalSeedDependencyProblem, type GoalSeedTask } from '@lobechat/utils/goalSeeds';import { TRPCError } from '@trpc/server';import debug from 'debug';import { sql } from 'drizzle-orm';@@ -116,6 +117,7 @@ import {} from './rolloutBatch';import { evaluateRolloutGate, type RolloutGateResult, withGateVerdict } from './rolloutGate';import { scheduleGoalAdvance } from './scheduler';+import { seedGoalTasks } from './seedTasks';import { evaluateHomogeneity } from './spec';import { GoalSupervisorService } from './supervisor';import { statusAuthoredByActor } from './supervisor/policy';@@ -205,10 +207,7 @@ const draftNotStarted = (goalId: string) =>export const goalTaskAgentId = (goal: Pick<GoalItem, 'agentId' | 'config'>) =>goal.config?.taskAgentId ?? goal.agentId ?? undefined;-export interface CreateGoalTaskInput {- description?: string;- title: string;-}+export type CreateGoalTaskInput = GoalSeedTask;export interface CreateGoalGraphInput {/**@@ -248,7 +247,7 @@ export interface CreateGoalGraphInput {projectId?: string;requirement?: string;/**- * Seed task nodes, in dependency-free order. A plain string is title-only.+ * Seed task nodes; `dependsOn` names other seeds by title. A plain string is title-only.* When omitted, the coordinator plans the decomposition on first advance.*/tasks?: Array<CreateGoalTaskInput | string>;@@ -599,6 +598,8 @@ export class GoalService {// unsupervised Goal. A legacy `enabled: false` is rejected rather than// silently rewritten: the caller asked for the opposite of what it would// get, and hiding that would make the surprise surface later, mid-run.+ const seedProblem = goalSeedDependencyProblem(input.tasks ?? []);+ if (seedProblem) throw new TRPCError({ code: 'BAD_REQUEST', message: seedProblem });const requestedSupervision = config?.supervision;if (requestedSupervision?.enabled === false)throw new TRPCError({@@ -713,17 +714,13 @@ export class GoalService {});if (!taskNode) throw new Error('Failed to seed goal task');}- for (const seed of input.tasks ?? []) {- const { description, title } = typeof seed === 'string' ? { title: seed } : seed;- const taskNode = await authorGraph.createNode(goal.id, {- createdByAgentId: input.createdByAgentId,- description,- kind: 'task',- title,- });- if (!taskNode) throw new Error('Failed to seed goal task');- await authorGraph.createEdge(goal.id, problem.id, taskNode.id, 'decomposes');- }+ await seedGoalTasks(+ authorGraph,+ goal.id,+ problem.id,+ input.tasks ?? [],+ input.createdByAgentId,+ );} catch (error) {await this.goalModel.delete(goal.id).catch(() => {});throw error;diff --git a/apps/server/src/services/goal/seedTasks.ts b/apps/server/src/services/goal/seedTasks.tsnew file mode 100644index 00000000000..75f5e603162--- /dev/null+++ b/apps/server/src/services/goal/seedTasks.ts@@ -0,0 +1,43 @@+import type { GoalSeedTask } from '@lobechat/utils/goalSeeds';++import type { GoalGraphModel } from '@/database/models/goalGraph';++/**+ * Attach caller-supplied seed tasks to the goal's problem the way a planned+ * task attaches, then draw each `dependsOn` as a `depends_on` edge. Creating+ * the edges here, in the same call as the nodes, keeps them in place before+ * the goal can dispatch anything, and needs no second write a run's token+ * might not be allowed to make. Callers check `goalSeedDependencyProblem` first.+ */+export const seedGoalTasks = async (+ graph: GoalGraphModel,+ goalId: string,+ problemId: string,+ seeds: Array<GoalSeedTask | string>,+ createdByAgentId?: string,+) => {+ const nodeIdByTitle = new Map<string, string>();+ for (const seed of seeds) {+ const { description, title } = typeof seed === 'string' ? { title: seed } : seed;+ const taskNode = await graph.createNode(goalId, {+ createdByAgentId,+ description,+ kind: 'task',+ title,+ });+ if (!taskNode) throw new Error('Failed to seed goal task');+ await graph.createEdge(goalId, problemId, taskNode.id, 'decomposes');+ nodeIdByTitle.set(title, taskNode.id);+ }+ for (const seed of seeds) {+ if (typeof seed === 'string') continue;+ for (const dep of seed.dependsOn ?? []) {+ await graph.createEdge(+ goalId,+ nodeIdByTitle.get(seed.title)!,+ nodeIdByTitle.get(dep)!,+ 'depends_on',+ );+ }+ }+};diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.tsindex ff217f836a1..919b52da762 100644--- a/packages/database/src/models/__tests__/goalGraph.test.ts+++ b/packages/database/src/models/__tests__/goalGraph.test.ts@@ -515,4 +515,69 @@ it.skipIf(process.env.TEST_SERVER_DB !== '1')(await writer;}},-);\ No newline at end of file+);+describe('GoalGraphModel.removeDraftEdges', () => {+ const seed = async (status: 'draft' | 'running') => {+ const goal = await goalModel.create({ status, subjectType: 'standalone', title: 'Edges' });+ const first = await graphModel.createNode(goal.id, { kind: 'task', title: 'First' });+ const second = await graphModel.createNode(goal.id, { kind: 'task', title: 'Second' });+ await graphModel.createEdge(goal.id, second!.id, first!.id, 'depends_on');+ await graphModel.createEdge(goal.id, second!.id, first!.id, 'leads_to');+ return { first: first!.id, goalId: goal.id, second: second!.id };+ };++ it('removes only the matching kind from a draft and records the unlink', async () => {+ const { first, goalId, second } = await seed('draft');++ const result = await graphModel.removeDraftEdges(+ goalId,+ { kind: 'depends_on', sourceNodeId: second, targetNodeId: first },+ 'wrong direction',+ );++ expect(result).toMatchObject({ status: 'removed' });+ const graph = await graphModel.getGraph(goalId);+ expect(graph?.edges.map((edge) => edge.kind)).toEqual(['leads_to']);+ expect(graph?.events[0]).toMatchObject({+ entityType: 'edge',+ eventType: 'unlinked',+ reason: 'wrong direction',+ });+ });++ it('removes every edge between the pair when no kind is given', async () => {+ const { first, goalId, second } = await seed('draft');++ const result = await graphModel.removeDraftEdges(goalId, {+ sourceNodeId: second,+ targetNodeId: first,+ });++ expect(result.status === 'removed' && result.edgeIds).toHaveLength(2);+ expect((await graphModel.getGraph(goalId))?.edges).toHaveLength(0);+ });++ it('leaves a started goal untouched', async () => {+ const { first, goalId, second } = await seed('running');++ const result = await graphModel.removeDraftEdges(goalId, {+ sourceNodeId: second,+ targetNodeId: first,+ });++ expect(result).toEqual({ goalStatus: 'running', status: 'not_draft' });+ expect((await graphModel.getGraph(goalId))?.edges).toHaveLength(2);+ });++ it('does not touch another user goal', async () => {+ const { first, goalId, second } = await seed('draft');++ const result = await new GoalGraphModel(serverDB, otherUserId).removeDraftEdges(goalId, {+ sourceNodeId: second,+ targetNodeId: first,+ });++ expect(result).toEqual({ status: 'not_found' });+ expect((await graphModel.getGraph(goalId))?.edges).toHaveLength(2);+ });+});diff --git a/packages/database/src/models/goalEdgeRules.ts b/packages/database/src/models/goalEdgeRules.tsnew file mode 100644index 00000000000..76e6842cebe--- /dev/null+++ b/packages/database/src/models/goalEdgeRules.ts@@ -0,0 +1,66 @@+import type { GoalEdgeKind, GoalGraphSnapshot } from '@lobechat/types';+import { experimentMembers, experimentOwner } from '@lobechat/utils/goalGraph';++/**+ * Reject a `contains` / `answers` edge that would break experiment scoping.+ * Every other kind is unconstrained here.+ */+export const assertContainerEdge = (+ graph: Pick<GoalGraphSnapshot, 'edges' | 'nodes'>,+ sourceNodeId: string,+ targetNodeId: string,+ kind: GoalEdgeKind,+) => {+ if (kind !== 'contains' && kind !== 'answers') return;+ const { edges, nodes } = graph;+ const source = nodes.find((node) => node.id === sourceNodeId);+ const target = nodes.find((node) => node.id === targetNodeId);+ if (!source || !target || source.id === target.id)+ throw new Error('Invalid experiment relationship');+ // Two kinds are containers: an `experiment` (a candidate answer under+ // test) and a `batch` (one repeated mould delivered as a class). The+ // single-owner and cycle rules below are about containment itself, so+ // they hold for both; only the question-scope rules are experiment-only.+ if (source.kind !== 'experiment' && source.kind !== 'batch')+ throw new Error('Only a container can contain nodes or answer a question');+ if (kind === 'answers' && source.kind !== 'experiment')+ throw new Error('Only an experiment can answer a question');+ if (kind === 'contains') {+ const owner = experimentOwner(graph, target.id);+ if (owner && owner !== source.id) throw new Error('A node can belong to only one experiment');+ if (experimentMembers(graph, target.id).has(source.id))+ throw new Error('Experiment containment cannot form a cycle');+ const questionId = edges.find(+ (edge) => edge.kind === 'answers' && edge.sourceNodeId === target.id,+ )?.targetNodeId;+ if (+ source.kind === 'experiment' &&+ edges.some(+ (edge) =>+ edge.kind === 'answers' &&+ edge.targetNodeId === target.id &&+ experimentOwner(graph, edge.sourceNodeId) !== source.id,+ )+ )+ throw new Error('A question must share its answer scope');+ if (+ source.kind === 'experiment' &&+ questionId &&+ experimentOwner(graph, questionId) !== source.id+ )+ throw new Error('An answer must share its question scope');+ return;+ }+ if (target.kind !== 'problem') throw new Error('An experiment must answer a question');+ if (experimentOwner(graph, source.id) !== experimentOwner(graph, target.id))+ throw new Error('An answer must share its question scope');+ if (+ edges.some(+ (edge) =>+ edge.kind === 'answers' &&+ edge.sourceNodeId === source.id &&+ edge.targetNodeId !== target.id,+ )+ )+ throw new Error('An experiment answers one question');+};diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex ffbb774429f..8155db88a11 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -14,7 +14,7 @@ import type {GoalNodeWorkVersionRelation,GoalStatus,} from '@lobechat/types';-import { experimentMembers, experimentOwner, experimentStatus } from '@lobechat/utils/goalGraph';+import { experimentStatus } from '@lobechat/utils/goalGraph';import {and,asc,@@ -43,6 +43,7 @@ import { works, workVersions } from '../schemas/work';import type { LobeChatDatabase, Transaction } from '../type';import { notTrashed } from '../utils/softDelete';import { buildWorkspaceWhere } from '../utils/workspace';+import { assertContainerEdge } from './goalEdgeRules';import { workOwnership } from './work/context';interface EventInput {@@ -651,58 +652,7 @@ export class GoalGraphModel {if (kind === 'contains' || kind === 'answers') {const nodes = await tx.select().from(goalNodes).where(eq(goalNodes.goalId, goalId));const edges = await tx.select().from(goalEdges).where(eq(goalEdges.goalId, goalId));- const graph = { nodes, edges };- const source = nodes.find((node) => node.id === sourceNodeId);- const target = nodes.find((node) => node.id === targetNodeId);- if (!source || !target || source.id === target.id)- throw new Error('Invalid experiment relationship');- // Two kinds are containers: an `experiment` (a candidate answer under- // test) and a `batch` (one repeated mould delivered as a class). The- // single-owner and cycle rules below are about containment itself, so- // they hold for both; only the question-scope rules are experiment-only.- if (source.kind !== 'experiment' && source.kind !== 'batch')- throw new Error('Only a container can contain nodes or answer a question');- if (kind === 'answers' && source.kind !== 'experiment')- throw new Error('Only an experiment can answer a question');- if (kind === 'contains') {- const owner = experimentOwner(graph, target.id);- if (owner && owner !== source.id)- throw new Error('A node can belong to only one experiment');- if (experimentMembers(graph, target.id).has(source.id))- throw new Error('Experiment containment cannot form a cycle');- const questionId = edges.find(- (edge) => edge.kind === 'answers' && edge.sourceNodeId === target.id,- )?.targetNodeId;- if (- source.kind === 'experiment' &&- edges.some(- (edge) =>- edge.kind === 'answers' &&- edge.targetNodeId === target.id &&- experimentOwner(graph, edge.sourceNodeId) !== source.id,- )- )- throw new Error('A question must share its answer scope');- if (- source.kind === 'experiment' &&- questionId &&- experimentOwner(graph, questionId) !== source.id- )- throw new Error('An answer must share its question scope');- } else {- if (target.kind !== 'problem') throw new Error('An experiment must answer a question');- if (experimentOwner(graph, source.id) !== experimentOwner(graph, target.id))- throw new Error('An answer must share its question scope');- if (- edges.some(- (edge) =>- edge.kind === 'answers' &&- edge.sourceNodeId === source.id &&- edge.targetNodeId !== target.id,- )- )- throw new Error('An experiment answers one question');- }+ assertContainerEdge({ edges, nodes }, sourceNodeId, targetNodeId, kind);}const [edge] = await tx.insert(goalEdges)@@ -751,6 +701,46 @@ export class GoalGraphModel {return removed.length;});+ /**+ * Take edges back off a draft Goal's graph: every edge from `sourceNodeId` to+ * `targetNodeId`, or only those of `kind`. A draft has dispatched nothing, so+ * no run was gated by them; a started Goal keeps its edges.+ */+ removeDraftEdges = async (+ goalId: string,+ match: { kind?: GoalEdgeKind; sourceNodeId: string; targetNodeId: string },+ reason?: string,+ ): Promise<+ | { edgeIds: string[]; status: 'removed' }+ | { goalStatus: GoalStatus; status: 'not_draft' }+ | { status: 'not_found' }+ > =>+ this.db.transaction(async (tx) => {+ const goal = await this.ownedGoal(goalId, tx);+ if (!goal) return { status: 'not_found' as const };+ if (goal.status !== 'draft') return { goalStatus: goal.status, status: 'not_draft' as const };+ const removed = await tx+ .delete(goalEdges)+ .where(+ and(+ eq(goalEdges.goalId, goalId),+ eq(goalEdges.sourceNodeId, match.sourceNodeId),+ eq(goalEdges.targetNodeId, match.targetNodeId),+ match.kind ? eq(goalEdges.kind, match.kind) : undefined,+ ),+ )+ .returning({ id: goalEdges.id });+ for (const { id } of removed) {+ await this.appendEvent(tx, goalId, {+ entityId: id,+ entityType: 'edge',+ eventType: 'unlinked',+ reason,+ });+ }+ return { edgeIds: removed.map(({ id }) => id), status: 'removed' as const };+ });+bindTask = async (goalId: string, nodeId: string, taskId: string) =>this.db.transaction(async (tx) => {if (!(await this.ownedGoal(goalId, tx))) return undefined;diff --git a/packages/utils/src/goalSeeds.test.ts b/packages/utils/src/goalSeeds.test.tsnew file mode 100644index 00000000000..98938c5e8e6--- /dev/null+++ b/packages/utils/src/goalSeeds.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';++import { goalSeedDependencyProblem } from './goalSeeds';++describe('goalSeedDependencyProblem', () => {+ it('accepts seeds whose dependencies form a DAG', () => {+ expect(+ goalSeedDependencyProblem([+ 'Signal',+ { dependsOn: ['Signal'], title: 'Policy' },+ { dependsOn: ['Signal', 'Policy'], title: 'Context' },+ ]),+ ).toBeUndefined();+ });++ it('allows duplicate titles when nothing depends on anything', () => {+ expect(goalSeedDependencyProblem(['A', 'A'])).toBeUndefined();+ });++ it('names a dependency that is not a seed', () => {+ expect(goalSeedDependencyProblem([{ dependsOn: ['Signl'], title: 'Policy' }, 'Signal'])).toBe(+ '"Policy" depends on "Signl", which is not a seed task',+ );+ });++ it('refuses duplicate titles once dependsOn has to name them', () => {+ expect(goalSeedDependencyProblem(['A', 'A', { dependsOn: ['A'], title: 'B' }])).toBe(+ '"A" appears twice, so dependsOn cannot name it',+ );+ });++ it('refuses a task depending on itself', () => {+ expect(goalSeedDependencyProblem([{ dependsOn: ['A'], title: 'A' }])).toBe(+ '"A" cannot depend on itself',+ );+ });++ it('refuses a cycle and spells it out', () => {+ expect(+ goalSeedDependencyProblem([+ { dependsOn: ['B'], title: 'A' },+ { dependsOn: ['C'], title: 'B' },+ { dependsOn: ['A'], title: 'C' },+ 'D',+ ]),+ ).toBe('dependsOn forms a cycle: "A" β "B" β "C" β "A"');+ });+});diff --git a/packages/utils/src/goalSeeds.ts b/packages/utils/src/goalSeeds.tsnew file mode 100644index 00000000000..490ad208928--- /dev/null+++ b/packages/utils/src/goalSeeds.ts@@ -0,0 +1,53 @@+/** A seed task as a Goal is created with it; `dependsOn` names other seeds by title. */+export interface GoalSeedTask {+ dependsOn?: string[];+ description?: string;+ title: string;+}++const seedTitle = (seed: GoalSeedTask | string) => (typeof seed === 'string' ? seed : seed.title);++/**+ * Why the seeds' `dependsOn` cannot be drawn as `depends_on` edges, or+ * `undefined` when it can. A cycle is refused too: every task on it would wait+ * for another, so the Goal would start with nothing it could dispatch.+ */+export const goalSeedDependencyProblem = (+ seeds: Array<GoalSeedTask | string>,+): string | undefined => {+ const dependencies = new Map<string, string[]>();+ for (const seed of seeds) {+ if (typeof seed !== 'string' && seed.dependsOn?.length)+ dependencies.set(seed.title, seed.dependsOn);+ }+ if (dependencies.size === 0) return undefined;++ const titles = seeds.map(seedTitle);+ const duplicate = titles.find((title, index) => titles.indexOf(title) !== index);+ if (duplicate) return `"${duplicate}" appears twice, so dependsOn cannot name it`;+ for (const [title, deps] of dependencies) {+ for (const dep of deps) {+ if (dep === title) return `"${title}" cannot depend on itself`;+ if (!titles.includes(dep)) return `"${title}" depends on "${dep}", which is not a seed task`;+ }+ }++ // Depth-first walk; reaching a title still on the stack closes a cycle.+ const state = new Map<string, 'done' | 'visiting'>();+ const visit = (title: string, path: string[]): string[] | undefined => {+ if (state.get(title) === 'done') return undefined;+ if (state.get(title) === 'visiting') return [...path.slice(path.indexOf(title)), title];+ state.set(title, 'visiting');+ for (const dep of dependencies.get(title) ?? []) {+ const cycle = visit(dep, [...path, title]);+ if (cycle) return cycle;+ }+ state.set(title, 'done');+ return undefined;+ };+ for (const title of dependencies.keys()) {+ const cycle = visit(title, []);+ if (cycle) return `dependsOn forms a cycle: ${cycle.map((item) => `"${item}"`).join(' β ')}`;+ }+ return undefined;+};