Skip to content

🀯 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.

✨ feat(goal): add CLI-driven goal graph runtime (#18597)

Arvin Xu4f664f1aa00a
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
new file mode 100644
index 00000000000..a56287ac57e
--- /dev/null
+++ b/apps/cli/src/commands/goal.ts
@@ -0,0 +1,242 @@
+import type { GoalGraphDecision, GoalGraphSnapshot, GoalTickResult } from '@lobechat/types';
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../api/client';
+import { outputJson, printTable, truncate } from '../utils/format';
+import { log } from '../utils/logger';
+
+const nodeIcon = { decision: 'β—†', finding: '●', problem: 'β—‡', work: 'β–£' } as const;
+const terminalOutcomes = new Set(['achieved', 'waiting_human', 'no_progress', 'failed']);
+
+function printGraph(graph: GoalGraphSnapshot) {
+ console.log(`\n${pc.bold(graph.goal.title)} ${pc.dim(graph.goal.id)} [${graph.goal.status}]`);
+ if (graph.goal.requirement) console.log(`${pc.dim('Requirement:')} ${graph.goal.requirement}`);
+ const incoming = new Map<string, typeof graph.edges>();
+ for (const edge of graph.edges) {
+ const list = incoming.get(edge.targetNodeId) ?? [];
+ list.push(edge);
+ incoming.set(edge.targetNodeId, list);
+ }
+ const rows = graph.nodes.map((node) => {
+ const dependencies = (incoming.get(node.id) ?? [])
+ .map((edge) => `${edge.kind}:${edge.sourceNodeId.slice(0, 8)}`)
+ .join(', ');
+ return [
+ `${nodeIcon[node.kind]} ${node.kind}`,
+ node.status,
+ truncate(node.title, 46),
+ node.taskId ?? '-',
+ dependencies || '-',
+ node.id,
+ ];
+ });
+ console.log();
+ printTable(rows, ['TYPE', 'STATUS', 'TITLE', 'TASK', 'INCOMING', 'NODE ID']);
+}
+
+function printTick(result: GoalTickResult) {
+ const icon =
+ result.outcome === 'achieved'
+ ? pc.green('βœ“')
+ : result.outcome === 'waiting_human'
+ ? pc.yellow('β—†')
+ : result.outcome === 'failed'
+ ? pc.red('βœ—')
+ : pc.blue('β†’');
+ console.log(`${icon} ${pc.bold(result.outcome)} ${result.message}`);
+ if (result.taskId) console.log(` ${pc.dim(`task: ${result.taskId}`)}`);
+ if (result.nodeId) console.log(` ${pc.dim(`node: ${result.nodeId}`)}`);
+}
+
+export function registerGoalCommand(program: Command) {
+ const goal = program.command('goal').description('Run long-horizon Goal Graphs');
+
+ goal
+ .command('create <title>')
+ .description('Create a standalone goal and seed its graph')
+ .option('-r, --requirement <text>', 'Acceptance requirement')
+ .option('-w, --work <title...>', 'Initial work node titles')
+ .option('--agent <id>', 'Responsible agent ID')
+ .option('--project <id>', 'Project ID')
+ .option('--max-rounds <n>', 'Maximum goal rounds')
+ .option('--max-cost <usd>', 'Maximum total cost in USD')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (title: string, options) => {
+ const client = await getTrpcClient();
+ const result = await client.goal.create.mutate({
+ agentId: options.agent,
+ maxRounds: options.maxRounds ? Number.parseInt(options.maxRounds, 10) : undefined,
+ maxTotalCost: options.maxCost ? Number.parseFloat(options.maxCost) : undefined,
+ projectId: options.project,
+ requirement: options.requirement,
+ title,
+ work: options.work,
+ });
+ if (options.json !== undefined) return outputJson(result.data, options.json);
+ printGraph(result.data);
+ });
+
+ const show = async (id: string, options: { json?: boolean | string }) => {
+ const result = await (await getTrpcClient()).goal.graph.query({ id });
+ if (options.json !== undefined) return outputJson(result.data, options.json);
+ printGraph(result.data);
+ };
+ goal
+ .command('show <id>')
+ .description('Show goal and graph')
+ .option('--json [fields]', 'Output JSON')
+ .action(show);
+ goal
+ .command('graph <id>')
+ .description('Show the Goal Graph')
+ .option('--json [fields]', 'Output JSON')
+ .action(show);
+
+ goal
+ .command('tick <id>')
+ .description('Advance exactly one deterministic coordinator step')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (id: string, options) => {
+ const result = await (await getTrpcClient()).goal.tick.mutate({ id });
+ if (options.json !== undefined) return outputJson(result.data, options.json);
+ printTick(result.data);
+ });
+
+ goal
+ .command('run <id>')
+ .description('Tick until the goal reaches a stop condition')
+ .option('--max-ticks <n>', 'Safety limit for this CLI invocation', '100')
+ .option('--poll-ms <ms>', 'Delay while waiting for task execution', '3000')
+ .option('--json', 'Output tick results as JSON')
+ .action(async (id: string, options: { json?: boolean; maxTicks: string; pollMs: string }) => {
+ const client = await getTrpcClient();
+ const results: GoalTickResult[] = [];
+ const maxTicks = Number.parseInt(options.maxTicks, 10);
+ const pollMs = Number.parseInt(options.pollMs, 10);
+ for (let index = 0; index < maxTicks; index++) {
+ const { data } = await client.goal.tick.mutate({ id });
+ results.push(data);
+ if (!options.json) printTick(data);
+ if (terminalOutcomes.has(data.outcome)) break;
+ if (data.outcome === 'waiting_external') {
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
+ }
+ }
+ if (options.json) outputJson(results);
+ const last = results.at(-1);
+ if (last && !terminalOutcomes.has(last.outcome) && results.length === maxTicks) {
+ log.warn(`Stopped after ${maxTicks} ticks; rerun to continue.`);
+ }
+ });
+
+ for (const action of ['pause', 'resume'] as const) {
+ goal
+ .command(`${action} <id>`)
+ .description(`${action === 'pause' ? 'Pause' : 'Resume'} goal coordination`)
+ .action(async (id: string) => {
+ const client = await getTrpcClient();
+ const result = await client.goal[action].mutate({ id });
+ log.info(result.message);
+ });
+ }
+
+ goal
+ .command('set-budget <id>')
+ .description('Update limits; pass "none" to remove a limit')
+ .option('--max-rounds <n>')
+ .option('--max-cost <usd>')
+ .action(async (id: string, options: { maxCost?: string; maxRounds?: string }) => {
+ const parseLimit = (value: string | undefined, integer = false) =>
+ value === undefined
+ ? undefined
+ : value === 'none'
+ ? null
+ : integer
+ ? Number.parseInt(value, 10)
+ : Number.parseFloat(value);
+ const result = await (
+ await getTrpcClient()
+ ).goal.setBudget.mutate({
+ id,
+ maxRounds: parseLimit(options.maxRounds, true),
+ maxTotalCost: parseLimit(options.maxCost),
+ });
+ log.info(result.message);
+ });
+
+ goal
+ .command('decisions <id>')
+ .description('List durable decision gates')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (id: string, options) => {
+ const graph = (await (await getTrpcClient()).goal.graph.query({ id })).data;
+ if (options.json !== undefined) return outputJson(graph.decisions, options.json);
+ printTable(
+ graph.decisions.map((decision: GoalGraphDecision) => [
+ decision.status,
+ truncate(decision.question, 60),
+ decision.recommendedOptionId ?? '-',
+ decision.id,
+ ]),
+ ['STATUS', 'QUESTION', 'RECOMMENDED', 'DECISION ID'],
+ );
+ });
+
+ goal
+ .command('decide <id> <decision-id>')
+ .description('Resolve a durable decision gate')
+ .requiredOption('--option <id>', 'Selected option ID')
+ .option('--reason <text>', 'Resolution rationale')
+ .action(async (id: string, decisionId: string, options) => {
+ const result = await (
+ await getTrpcClient()
+ ).goal.decide.mutate({
+ decisionId,
+ id,
+ optionId: options.option,
+ resolution: options.reason,
+ });
+ log.info(result.message);
+ });
+
+ goal
+ .command('add-node <id> <kind> <title>')
+ .description('Add a problem, work, finding, or decision node')
+ .option('-d, --description <text>')
+ .option('-p, --priority <n>')
+ .action(
+ async (
+ id: string,
+ kind: 'decision' | 'finding' | 'problem' | 'work',
+ title: string,
+ options,
+ ) => {
+ const result = await (
+ await getTrpcClient()
+ ).goal.addNode.mutate({
+ description: options.description,
+ 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}`);
+ });
+}
diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.ts
index 9c46388792c..283dc0b2dda 100644
--- a/apps/cli/src/program.ts
+++ b/apps/cli/src/program.ts
@@ -12,6 +12,7 @@ import { registerDocCommand } from './commands/doc';
import { registerEvalCommand } from './commands/eval';
import { registerFileCommand } from './commands/file';
import { registerGenerateCommand } from './commands/generate';
+import { registerGoalCommand } from './commands/goal';
import { registerHeteroCommand } from './commands/hetero';
import { registerKbCommand } from './commands/kb';
import { registerLoginCommand } from './commands/login';
@@ -84,6 +85,7 @@ export function createProgram() {
registerAgentSignalCommand(program);
registerBotCommand(program);
registerGenerateCommand(program);
+ registerGoalCommand(program);
registerFileCommand(program);
registerHeteroCommand(program);
registerSkillCommand(program);
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
new file mode 100644
index 00000000000..bb09b5e1a79
--- /dev/null
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -0,0 +1,190 @@
+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 { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { GoalService } from '@/server/services/goal';
+
+const goalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
+ opts.next({
+ ctx: {
+ 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() });
+
+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`,
+ });
+}
+
+export const goalRouter = router({
+ addEdge: goalWriteProcedure
+ .input(
+ idInput.extend({
+ kind: z.enum([
+ 'decomposes',
+ 'depends_on',
+ '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', 'work', 'finding', 'decision']),
+ 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');
+ }
+ }),
+
+ create: goalWriteProcedure
+ .input(
+ z.object({
+ agentId: z.string().optional(),
+ maxRounds: z.number().int().positive().optional(),
+ maxTotalCost: z.number().positive().optional(),
+ projectId: z.string().optional(),
+ requirement: z.string().optional(),
+ title: z.string().min(1),
+ work: z.array(z.string().min(1)).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return {
+ data: await ctx.goalService.create(input),
+ message: 'Goal created',
+ success: true,
+ };
+ } catch (error) {
+ mapGoalError(error, 'create');
+ }
+ }),
+
+ decide: goalWriteProcedure
+ .input(
+ idInput.extend({
+ decisionId: z.string().uuid(),
+ optionId: z.string(),
+ resolution: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return {
+ data: await ctx.goalService.decide(
+ input.id,
+ input.decisionId,
+ input.optionId,
+ input.resolution,
+ ),
+ message: 'Decision resolved',
+ success: true,
+ };
+ } catch (error) {
+ mapGoalError(error, 'decide');
+ }
+ }),
+
+ graph: goalProcedure.input(idInput).query(async ({ ctx, input }) => {
+ try {
+ return { data: await ctx.goalService.graph(input.id), success: true };
+ } catch (error) {
+ mapGoalError(error, 'graph');
+ }
+ }),
+
+ pause: goalWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
+ try {
+ return { data: await ctx.goalService.pause(input.id), message: 'Goal paused', success: true };
+ } catch (error) {
+ mapGoalError(error, 'pause');
+ }
+ }),
+
+ resume: goalWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
+ try {
+ return {
+ data: await ctx.goalService.resume(input.id),
+ message: 'Goal resumed',
+ success: true,
+ };
+ } catch (error) {
+ mapGoalError(error, 'resume');
+ }
+ }),
+
+ setBudget: goalWriteProcedure
+ .input(
+ idInput.extend({
+ maxRounds: z.number().int().positive().nullable().optional(),
+ maxTotalCost: z.number().positive().nullable().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input: { id, ...budget } }) => {
+ try {
+ return {
+ data: await ctx.goalService.setBudget(id, budget),
+ message: 'Goal budget updated',
+ success: true,
+ };
+ } catch (error) {
+ mapGoalError(error, 'setBudget');
+ }
+ }),
+
+ tick: goalWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
+ try {
+ return { data: await ctx.goalService.tick(input.id), success: true };
+ } catch (error) {
+ mapGoalError(error, 'tick');
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index a80c51fe626..2dc48bc18fe 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -54,6 +54,7 @@ import { followUpActionRouter } from './followUpAction';
import { generationRouter } from './generation';
import { generationBatchRouter } from './generationBatch';
import { generationTopicRouter } from './generationTopic';
+import { goalRouter } from './goal';
import { homeRouter } from './home';
import { imageRouter } from './image';
import { importerRouter } from './importer';
@@ -129,6 +130,7 @@ export const lambdaRouter = router({
generation: generationRouter,
generationBatch: generationBatchRouter,
generationTopic: generationTopicRouter,
+ goal: goalRouter,
group: agentGroupRouter,
healthcheck: publicProcedure.query(() => "i'm live!"),
home: homeRouter,
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
new file mode 100644
index 00000000000..5dae1ec35b3
--- /dev/null
+++ b/apps/server/src/services/goal/index.test.ts
@@ -0,0 +1,167 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '@/database/core/getTestDB';
+import { TaskModel } from '@/database/models/task';
+import {
+ goalEdges,
+ goalEvents,
+ goalNodeDecisions,
+ goalNodes,
+ goals,
+ tasks,
+ users,
+} from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { GoalService } from './index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'goal-service-test-user';
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();
+});
+
+afterEach(async () => {
+ // PGlite does not consistently order the nested user -> goal -> graph
+ // cascades, so clear graph leaves explicitly before their owned roots.
+ await serverDB.delete(goalNodeDecisions);
+ await serverDB.delete(goalEdges);
+ await serverDB.delete(goalEvents);
+ await serverDB.delete(goalNodes);
+ await serverDB.delete(goals);
+ await serverDB.delete(tasks);
+ await serverDB.delete(users);
+});
+
+describe('GoalService', () => {
+ it('creates only one responsible task when ticks race on the same work node', async () => {
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Concurrent goal', work: ['Single owner work'] });
+
+ const results = await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);
+ const current = await service.graph(graph.goal.id);
+ const taskRows = await serverDB.select().from(tasks);
+
+ expect(results.filter((result) => result.outcome === 'advanced')).toHaveLength(1);
+ expect(taskRows).toHaveLength(1);
+ expect(current.nodes.find((node) => node.kind === 'work')?.taskId).toBe(taskRows[0].id);
+ expect(current.workVersions).toHaveLength(1);
+ });
+
+ it('keeps long goal requirements in the task instruction without overflowing its description', async () => {
+ const service = new GoalService(serverDB, userId);
+ const requirement = `Generate verified training data. ${'Detailed acceptance evidence. '.repeat(20)}`;
+ const graph = await service.create({
+ requirement,
+ title: 'Long requirement goal',
+ work: ['Generate training data'],
+ });
+
+ const created = await service.tick(graph.goal.id);
+ const task = await new TaskModel(serverDB, userId).findById(created.taskId!);
+
+ expect(created.outcome).toBe('advanced');
+ expect(task?.description).toHaveLength(255);
+ expect(task?.instruction).toContain(requirement);
+ });
+
+ it('advances create task -> finding -> achieved without treating task creation as completion', async () => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ requirement: 'A runnable minimal training loop with evidence',
+ title: 'Reproduce Ornith training',
+ work: ['Implement minimal training loop'],
+ });
+
+ const created = await service.tick(graph.goal.id);
+ expect(created).toMatchObject({ outcome: 'advanced' });
+ expect(created.taskId).toBeDefined();
+
+ const waitingGraph = await service.graph(graph.goal.id);
+ expect(waitingGraph.nodes.find((node) => node.kind === 'work')).toMatchObject({
+ status: 'active',
+ taskId: created.taskId,
+ });
+ expect(waitingGraph.workVersions).toHaveLength(1);
+ const responsibleTask = await taskModel.findById(created.taskId!);
+ expect(responsibleTask).toBeDefined();
+ expect(taskModel.shouldPauseOnTopicComplete(responsibleTask!)).toBe(false);
+
+ await taskModel.updateStatus(created.taskId!, 'completed');
+ const synthesized = await service.tick(graph.goal.id);
+ expect(synthesized.outcome).toBe('advanced');
+
+ const evolved = await service.graph(graph.goal.id);
+ expect(evolved.nodes.some((node) => node.kind === 'finding')).toBe(true);
+ expect(evolved.edges.some((edge) => edge.kind === 'produces')).toBe(true);
+
+ const achieved = await service.tick(graph.goal.id);
+ expect(achieved.outcome).toBe('achieved');
+ expect((await service.graph(graph.goal.id)).goal.status).toBe('achieved');
+ });
+
+ it('evolves a failed work task into a durable decision gate', async () => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({ title: 'Failure recovery', work: ['Risky work'] });
+ const created = await service.tick(graph.goal.id);
+
+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });
+ const waiting = await service.tick(graph.goal.id);
+ expect(waiting.outcome).toBe('waiting_human');
+
+ const gated = await service.graph(graph.goal.id);
+ const decision = gated.decisions[0];
+ expect(decision).toMatchObject({ recommendedOptionId: 'retry', status: 'pending' });
+ expect(gated.nodes.some((node) => node.kind === 'decision')).toBe(true);
+
+ await service.decide(graph.goal.id, decision.id, 'retire', 'This branch is not useful');
+ const achieved = await service.tick(graph.goal.id);
+ expect(achieved.outcome).toBe('achieved');
+ });
+
+ it('respects a manually paused responsible task without rerunning it', async () => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({ title: 'Paused work', work: ['Wait for review'] });
+ const created = await service.tick(graph.goal.id);
+
+ await taskModel.updateStatus(created.taskId!, 'paused', { error: null });
+ const waiting = await service.tick(graph.goal.id);
+
+ expect(waiting).toMatchObject({
+ outcome: 'waiting_human',
+ taskId: created.taskId,
+ });
+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);
+ });
+
+ it('only selects work whose explicit dependencies are resolved', async () => {
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Dependency-aware goal' });
+ const prerequisite = await service.addNode(graph.goal.id, {
+ kind: 'work',
+ priority: 0,
+ title: 'Collect evidence',
+ });
+ const dependent = await service.addNode(graph.goal.id, {
+ kind: 'work',
+ priority: 10,
+ title: 'Train from evidence',
+ });
+ await service.addEdge(graph.goal.id, dependent.id, prerequisite.id, 'depends_on');
+
+ const first = await service.tick(graph.goal.id);
+ expect(first).toMatchObject({ nodeId: prerequisite.id, outcome: 'advanced' });
+
+ const taskModel = new TaskModel(serverDB, userId);
+ await taskModel.updateStatus(first.taskId!, 'completed');
+ await service.tick(graph.goal.id);
+
+ const next = await service.tick(graph.goal.id);
+ expect(next).toMatchObject({ nodeId: dependent.id, outcome: 'advanced' });
+ });
+});
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
new file mode 100644
index 00000000000..865332c3062
--- /dev/null
+++ b/apps/server/src/services/goal/index.ts
@@ -0,0 +1,532 @@
+import type {
+ GoalEdgeKind,
+ GoalGraphSnapshot,
+ GoalNodeKind,
+ GoalNodeStatus,
+ GoalTickResult,
+ TaskItem,
+ TaskTopicHandoff,
+} from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+
+import { GoalModel } from '@/database/models/goal';
+import { GoalGraphModel } from '@/database/models/goalGraph';
+import { ProjectModel } from '@/database/models/project';
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+import { WorkModel } from '@/database/models/work';
+import type { LobeChatDatabase } from '@/database/type';
+import { assertAgentUsableBy } from '@/database/utils/agent-access';
+
+import { TaskService } from '../task';
+import { TaskRunnerService } from '../taskRunner';
+
+const WORK_NODE_CLAIM_TTL_MS = 5 * 60 * 1000;
+const TASK_DESCRIPTION_MAX_LENGTH = 255;
+
+export interface CreateGoalGraphInput {
+ agentId?: string;
+ maxRounds?: number;
+ maxTotalCost?: number;
+ projectId?: string;
+ requirement?: string;
+ title: string;
+ work?: string[];
+}
+
+export interface CreateGoalNodeInput {
+ description?: string;
+ kind: GoalNodeKind;
+ priority?: number;
+ status?: GoalNodeStatus;
+ title: string;
+}
+
+/** Application service shared by CLI today and Graph UI/schedulers later. */
+export class GoalService {
+ private readonly goalModel: GoalModel;
+ private readonly graphModel: GoalGraphModel;
+ private readonly taskModel: TaskModel;
+ private readonly taskService: TaskService;
+ private readonly taskTopicModel: TaskTopicModel;
+ private readonly workModel: WorkModel;
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {
+ this.goalModel = new GoalModel(db, userId, workspaceId);
+ this.graphModel = new GoalGraphModel(db, userId, workspaceId);
+ this.taskModel = new TaskModel(db, userId, workspaceId);
+ this.taskService = new TaskService(db, userId, workspaceId);
+ this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);
+ this.workModel = new WorkModel(db, userId, workspaceId);
+ }
+
+ create = async (input: CreateGoalGraphInput): Promise<GoalGraphSnapshot> => {
+ if (input.agentId) {
+ await assertAgentUsableBy(this.db, input.agentId, {
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ }
+ if (input.projectId) {
+ const project = await new ProjectModel(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).findManageableById(input.projectId);
+ if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
+ }
+ const goal = await this.goalModel.create({
+ agentId: input.agentId,
+ maxRounds: input.maxRounds,
+ maxTotalCost: input.maxTotalCost,
+ projectId: input.projectId,
+ requirement: input.requirement,
+ subjectType: 'standalone',
+ title: input.title,
+ });
+ try {
+ const problem = await this.graphModel.createNode(goal.id, {
+ description: input.requirement,
+ kind: 'problem',
+ status: 'active',
+ title: input.title,
+ });
+ if (!problem) throw new Error('Failed to seed goal problem');
+
+ for (const title of input.work ?? []) {
+ const work = await this.graphModel.createNode(goal.id, { kind: 'work', title });
+ if (!work) throw new Error('Failed to seed goal work');
+ await this.graphModel.createEdge(goal.id, problem.id, work.id, 'decomposes');
+ }
+ } catch (error) {
+ await this.goalModel.delete(goal.id).catch(() => {});
+ throw error;
+ }
+ return (await this.graphModel.getGraph(goal.id))!;
+ };
+
+ graph = async (goalId: string) => this.requireGraph(goalId);
+
+ addNode = async (goalId: string, input: CreateGoalNodeInput) => {
+ const node = await this.graphModel.createNode(goalId, input);
+ if (!node) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ return node;
+ };
+
+ addEdge = async (
+ goalId: string,
+ sourceNodeId: string,
+ targetNodeId: string,
+ kind: GoalEdgeKind,
+ ) => {
+ const edge = await this.graphModel.createEdge(goalId, sourceNodeId, targetNodeId, kind);
+ if (!edge) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ return edge;
+ };
+
+ pause = async (goalId: string) => {
+ const goal = await this.goalModel.updateStatus(goalId, 'paused');
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ return goal;
+ };
+
+ setBudget = async (
+ goalId: string,
+ budget: { maxRounds?: number | null; maxTotalCost?: number | null },
+ ) => {
+ const goal = await this.goalModel.update(goalId, budget);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ return goal;
+ };
+
+ resume = async (goalId: string) => {
+ const graph = await this.requireGraph(goalId);
+ const status = graph.decisions.some((decision) => decision.status === 'pending')
+ ? 'review'
+ : 'running';
+ return this.goalModel.updateStatus(goalId, status);
+ };
+
+ decide = async (goalId: string, decisionId: string, optionId: string, resolution?: string) => {
+ const graph = await this.requireGraph(goalId);
+ const decision = graph.decisions.find((item) => item.id === decisionId);
+ if (!decision || decision.status !== 'pending') {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Pending decision not found' });
+ }
+ if (decision.options?.length && !decision.options.some((option) => option.id === optionId)) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unknown decision option' });
+ }
+ const resolved = await this.graphModel.resolveDecision(
+ goalId,
+ decisionId,
+ optionId,
+ resolution,
+ );
+ if (!resolved)
+ throw new TRPCError({ code: 'CONFLICT', message: 'Decision was already resolved' });
+
+ const incoming = graph.edges.find(
+ (edge) => edge.targetNodeId === decision.nodeId && edge.kind === 'leads_to',
+ );
+ const source = incoming && graph.nodes.find((node) => node.id === incoming.sourceNodeId);
+ if (source?.kind === 'work') {
+ if (optionId === 'retry' && source.taskId) {
+ await this.taskModel.updateStatus(source.taskId, 'backlog', { error: null });
+ await this.graphModel.updateNodeStatus(goalId, source.id, 'active', resolution);
+ } else if (optionId === 'retire') {
+ await this.graphModel.updateNodeStatus(goalId, source.id, 'retired', resolution);
+ }
+ }
+ await this.goalModel.updateStatus(goalId, 'running');
+ return resolved;
+ };
+
+ tick = async (goalId: string): Promise<GoalTickResult> => {
+ const graph = await this.requireGraph(goalId);
+ if (graph.goal.status === 'paused') {
+ return { goalId, message: 'Goal is paused', outcome: 'no_progress' };
+ }
+ if (graph.goal.status === 'achieved') {
+ return { goalId, message: 'Goal is already achieved', outcome: 'achieved' };
+ }
+ if (graph.goal.status === 'failed' || graph.goal.status === 'canceled') {
+ return { goalId, message: `Goal is ${graph.goal.status}`, outcome: 'failed' };
+ }
+
+ const pendingDecision = graph.decisions.find((decision) => decision.status === 'pending');
+ if (pendingDecision) {
+ await this.goalModel.updateStatus(goalId, 'review');
+ return {
+ goalId,
+ message: pendingDecision.question,
+ nodeId: pendingDecision.nodeId,
+ outcome: 'waiting_human',
+ };
+ }
+
+ const resolvedNodeIds = new Set(
+ graph.nodes.filter((node) => node.status === 'resolved').map((node) => node.id),
+ );
+ const frontier = graph.nodes
+ .filter((node) => {
+ if (node.kind !== 'work' || ['resolved', 'rejected', 'retired'].includes(node.status)) {
+ return false;
+ }
+
+ const dependencies = graph.edges.filter(
+ (edge) => edge.kind === 'depends_on' && edge.sourceNodeId === node.id,
+ );
+ return dependencies.every((edge) => resolvedNodeIds.has(edge.targetNodeId));
+ })
+ .sort((a, b) => b.priority - a.priority || a.createdAt.getTime() - b.createdAt.getTime())[0];
+
+ if (!frontier) {
+ const workNodes = graph.nodes.filter((node) => node.kind === 'work');
+ const allWorkTerminal =
+ workNodes.length > 0 &&
+ workNodes.every((node) => ['resolved', 'rejected', 'retired'].includes(node.status));
+ if (allWorkTerminal) {
+ await this.goalModel.updateStatus(goalId, 'achieved');
+ return { goalId, message: 'All work nodes reached a terminal state', outcome: 'achieved' };
+ }
+ return {
+ goalId,
+ message:
+ workNodes.length === 0
+ ? 'No work frontier exists; add a work node'
+ : 'No work node is ready; resolve its dependencies first',
+ outcome: 'no_progress',
+ };
+ }
+
+ if (!frontier.taskId) {
+ const claim = await this.graphModel.claimWorkNode(
+ goalId,
+ frontier.id,
+ new Date(Date.now() - WORK_NODE_CLAIM_TTL_MS),
+ );
+ if (!claim) {
+ const current = (await this.requireGraph(goalId)).nodes.find(
+ (node) => node.id === frontier.id,
+ );
+ return {
+ goalId,
+ message: current?.taskId
+ ? 'Responsible task was created by another coordinator'
+ : 'Work node is being claimed by another coordinator',
+ nodeId: frontier.id,
+ outcome: 'waiting_external',
+ taskId: current?.taskId ?? undefined,
+ };
+ }
+
+ let task: TaskItem | undefined;
+ try {
+ const description = frontier.description ?? graph.goal.requirement;
+ task = await this.taskService.createTask({
+ assigneeAgentId: graph.goal.agentId ?? undefined,
+ config: { checkpoint: { topic: { after: false } } },
+ description: description?.slice(0, TASK_DESCRIPTION_MAX_LENGTH),
+ instruction: this.buildWorkInstruction(graph, frontier.title, frontier.description),
+ name: frontier.title,
+ projectId: graph.goal.projectId ?? undefined,
+ });
+ const bound = await this.graphModel.bindTask(goalId, frontier.id, task.id);
+ if (!bound) {
+ await this.taskModel.delete(task.id);
+ return {
+ goalId,
+ message: 'Responsible task was created by another coordinator',
+ nodeId: frontier.id,
+ outcome: 'waiting_external',
+ };
+ }
+ } catch (error) {
+ if (task) {
+ await this.taskModel.delete(task.id).catch((cleanupError) => {
+ console.error('[GoalService.tick] failed to delete unbound task:', cleanupError);
+ });
+ }
+ await this.graphModel.updateNodeStatus(goalId, frontier.id, 'proposed');
+ throw error;
+ }
+ const work = await this.workModel.registerTask({
+ changeType: 'created',
+ taskId: task.id,
+ toolIdentifier: 'goal-coordinator',
+ toolName: 'createResponsibleTask',
+ });
+ if (work?.currentVersionId) {
+ await this.graphModel.attachWorkVersion(
+ goalId,
+ frontier.id,
+ work.currentVersionId,
+ 'produced',
+ );
+ }
+ await this.goalModel.updateStatus(goalId, 'running');
+ return {
+ goalId,
+ message: `Created responsible task ${task.identifier}`,
+ nodeId: frontier.id,
+ outcome: 'advanced',
+ taskId: task.id,
+ };
+ }
+
+ const task = await this.taskModel.findById(frontier.taskId);
+ if (!task) {
+ await this.graphModel.updateNodeStatus(
+ goalId,
+ frontier.id,
+ 'waiting',
+ 'Responsible task is missing',
+ );
+ return {
+ goalId,
+ message: 'Responsible task is missing',
+ nodeId: frontier.id,
+ outcome: 'failed',
+ };
+ }
+ await this.ensureTaskWorkVersion(graph.goal.id, frontier.id, task.id);
+
+ if (task.status === 'completed') return this.consumeCompletedWork(graph, frontier.id, task.id);
+ if (
+ task.status === 'failed' ||
+ task.status === 'canceled' ||
+ (task.status === 'paused' && task.error)
+ ) {
+ return this.openFailureDecision(
+ graph,
+ frontier.id,
+ task.id,
+ task.error ?? `Task ${task.status}`,
+ );
+ }
+ if (task.status === 'paused') {
+ return {
+ goalId,
+ message: `Task ${task.identifier} is paused`,
+ nodeId: frontier.id,
+ outcome: 'waiting_human',
+ taskId: task.id,
+ };
+ }
+ if (task.status === 'running' || task.status === 'scheduled') {
+ return {
+ goalId,
+ message: `Task ${task.identifier} is ${task.status}`,
+ nodeId: frontier.id,
+ outcome: 'waiting_external',
+ taskId: task.id,
+ };
+ }
+
+ const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));
+ const runs = await this.taskTopicModel.findWithHandoffByTaskIds(taskIds, 10_000);
+ const totalCost = runs.reduce((sum, run) => sum + Number(run.totalCost ?? 0), 0);
+ const roundLimitReached = graph.goal.maxRounds !== null && runs.length >= graph.goal.maxRounds;
+ const costLimitReached =
+ graph.goal.maxTotalCost !== null && totalCost >= Number(graph.goal.maxTotalCost);
+ if (roundLimitReached || costLimitReached) {
+ await this.goalModel.updateStatus(goalId, 'paused');
+ return {
+ goalId,
+ message: roundLimitReached
+ ? `Round budget reached (${runs.length}/${graph.goal.maxRounds})`
+ : `Cost budget reached ($${totalCost.toFixed(4)}/$${graph.goal.maxTotalCost})`,
+ nodeId: frontier.id,
+ outcome: 'no_progress',
+ taskId: task.id,
+ };
+ }
+
+ const run = await new TaskRunnerService(this.db, this.userId, this.workspaceId).runTask({
+ taskId: task.id,
+ trigger: 'goal',
+ });
+ return {
+ goalId,
+ message: `Started task ${task.identifier}`,
+ nodeId: frontier.id,
+ outcome: 'waiting_external',
+ taskId: run.taskId,
+ };
+ };
+
+ private requireGraph = async (goalId: string) => {
+ const graph = await this.graphModel.getGraph(goalId);
+ if (!graph) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ return graph;
+ };
+
+ private ensureTaskWorkVersion = async (goalId: string, nodeId: string, taskId: string) => {
+ const graph = await this.graphModel.getGraph(goalId);
+ if (graph?.workVersions.some((link) => link.nodeId === nodeId)) return;
+ const work = await this.workModel.registerTask({
+ changeType: 'created',
+ taskId,
+ toolIdentifier: 'goal-coordinator',
+ toolName: 'createResponsibleTask',
+ });
+ if (work?.currentVersionId) {
+ await this.graphModel.attachWorkVersion(goalId, nodeId, work.currentVersionId, 'produced');
+ }
+ };
+
+ private buildWorkInstruction = (
+ graph: GoalGraphSnapshot,
+ title: string,
+ description: string | null,
+ ) =>
+ [
+ `Long-horizon goal: ${graph.goal.title}`,
+ graph.goal.requirement ? `Acceptance requirement: ${graph.goal.requirement}` : undefined,
+ `Current work objective: ${title}`,
+ description,
+ 'Complete this work objective. Create implementation-level subtasks when useful. Return concrete evidence, key findings, and the recommended next action.',
+ ]
+ .filter(Boolean)
+ .join('\n\n');
+
+ private consumeCompletedWork = async (
+ graph: GoalGraphSnapshot,
+ nodeId: string,
+ taskId: string,
+ ): Promise<GoalTickResult> => {
+ const existingFinding = graph.edges.some(
+ (edge) => edge.sourceNodeId === nodeId && edge.kind === 'produces',
+ );
+ const [latest] = await this.taskTopicModel.findWithHandoff(taskId, 1);
+ const completedWork = await this.workModel.registerTask({
+ changeType: 'updated',
+ rootOperationId: latest?.operationId,
+ taskId,
+ toolIdentifier: 'goal-coordinator',
+ toolName: 'synthesizeTaskOutcome',
+ topicId: latest?.topicId,
+ });
+ if (completedWork?.currentVersionId) {
+ await this.graphModel.attachWorkVersion(
+ graph.goal.id,
+ nodeId,
+ completedWork.currentVersionId,
+ 'produced',
+ );
+ }
+ if (!existingFinding) {
+ const handoff = latest?.handoff as TaskTopicHandoff | null;
+ const finding = await this.graphModel.createNode(graph.goal.id, {
+ confidence: 1,
+ description: handoff?.content ?? handoff?.summary ?? undefined,
+ kind: 'finding',
+ status: 'resolved',
+ title:
+ handoff?.title ??
+ handoff?.summary ??
+ `Completed: ${graph.nodes.find((node) => node.id === nodeId)?.title}`,
+ });
+ if (finding) await this.graphModel.createEdge(graph.goal.id, nodeId, finding.id, 'produces');
+ }
+ await this.graphModel.updateNodeStatus(
+ graph.goal.id,
+ nodeId,
+ 'resolved',
+ 'Responsible task completed',
+ );
+ return {
+ goalId: graph.goal.id,
+ message: 'Task outcome was synthesized into a finding',
+ nodeId,
+ outcome: 'advanced',
+ taskId,
+ };
+ };
+
+ private openFailureDecision = async (
+ graph: GoalGraphSnapshot,
+ nodeId: string,
+ taskId: string,
+ reason: string,
+ ): Promise<GoalTickResult> => {
+ const existingDecisionNode = graph.edges
+ .filter((edge) => edge.sourceNodeId === nodeId && edge.kind === 'leads_to')
+ .map((edge) => graph.nodes.find((node) => node.id === edge.targetNodeId))
+ .find((node) => node?.kind === 'decision' && node.status !== 'resolved');
+ if (!existingDecisionNode) {
+ const node = await this.graphModel.createNode(graph.goal.id, {
+ description: reason,
+ kind: 'decision',
+ status: 'waiting',
+ title: 'Choose how to recover failed work',
+ });
+ if (node) {
+ await this.graphModel.createEdge(graph.goal.id, nodeId, node.id, 'leads_to');
+ await this.graphModel.createDecision(graph.goal.id, node.id, {
+ authority: 'user',
+ options: [
+ { id: 'retry', label: 'Retry work' },
+ { id: 'retire', label: 'Retire work' },
+ ],
+ question: `${reason}. Retry or retire this work node?`,
+ recommendedOptionId: 'retry',
+ requestedUserId: this.userId,
+ });
+ }
+ }
+ await this.graphModel.updateNodeStatus(graph.goal.id, nodeId, 'waiting', reason);
+ await this.goalModel.updateStatus(graph.goal.id, 'review');
+ return {
+ goalId: graph.goal.id,
+ message: 'Task failed; a human decision gate was opened',
+ nodeId,
+ outcome: 'waiting_human',
+ taskId,
+ };
+ };
+}
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 35427e1dbb9..1d51fdc1e2c 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -239,6 +239,9 @@ export class TaskLifecycleService {
// 'scheduled' to wait for the next tick. They never auto-pause
// on success β€” only `reason === 'error'` below puts them in
// 'paused' for human attention.
+ // - Goal-owned root tasks complete immediately. The Goal coordinator
+ // owns the broader delivery decision and cannot consume a task that
+ // merely stays running after its topic has already finished.
// - Subtasks complete immediately. Their parent owns the broader
// delivery decision, so pausing every successful child for a second
// user review stalls an otherwise autonomous task graph. Completing
@@ -262,6 +265,13 @@ export class TaskLifecycleService {
}
if (currentTask) {
+ const completionRequestedByCurrentOperation =
+ (
+ currentTask.context as {
+ completion?: { requestedByOperationId?: string };
+ } | null
+ )?.completion?.requestedByOperationId === params.operationId;
+
if (
currentTask.automationMode === 'schedule' &&
(await this.scheduleCapReached(currentTask))
@@ -276,6 +286,20 @@ export class TaskLifecycleService {
// failed β€” the live `error` alone would silently self-heal.
await this.recordAutomationRecovery(currentTask);
await this.taskModel.updateStatus(taskId, 'scheduled', { error: null });
+ } else if (!verifyBound && completionRequestedByCurrentOperation) {
+ if (currentTask.parentTaskId) {
+ await this.completeSubtask(currentTask);
+ } else {
+ await this.taskModel.updateStatusIfCurrent(taskId, 'running', 'completed', {
+ completedAt: new Date(),
+ error: null,
+ });
+ }
+ } else if (!verifyBound && params.runTrigger === 'goal' && !currentTask.parentTaskId) {
+ await this.taskModel.updateStatusIfCurrent(taskId, 'running', 'completed', {
+ completedAt: new Date(),
+ error: null,
+ });
} else if (!verifyBound && currentTask.parentTaskId) {
const checkpoint = this.taskModel.getCheckpointConfig(currentTask);
if (checkpoint.topic?.after) {
diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
index a8eff70ac7c..1caa250332d 100644
--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
@@ -271,6 +271,28 @@ describe('TaskLifecycleService.onTopicComplete', () => {
expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'scheduled', expect.anything());
});
+ it('finalizes a current-operation completion request after the topic completes', async () => {
+ const task = baseTask({
+ automationMode: null,
+ context: { completion: { requestedByOperationId: 'op-1' } },
+ });
+ findById.mockResolvedValue(task);
+
+ await service.onTopicComplete({
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {
+ completedAt: expect.any(Date),
+ error: null,
+ });
+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());
+ });
+
it('successful subtask β†’ completes and unlocks downstream tasks instead of pausing', async () => {
const task = baseTask({ automationMode: null, parentTaskId: 'parent-task' });
const parentTask = baseTask({ id: 'parent-task', identifier: 'TASK-0' });
@@ -379,6 +401,27 @@ describe('TaskLifecycleService.onTopicComplete', () => {
expect(updateStatus).not.toHaveBeenCalled();
});
+
+ it('goal-owned root task completes instead of remaining running', async () => {
+ const task = baseTask({ automationMode: null, parentTaskId: null });
+ findById.mockResolvedValue(task);
+ (service as any).taskModel.shouldPauseOnTopicComplete = vi.fn().mockReturnValue(false);
+
+ await service.onTopicComplete({
+ operationId: 'op-1',
+ reason: 'done',
+ runTrigger: 'goal',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {
+ completedAt: expect.any(Date),
+ error: null,
+ });
+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());
+ });
});
describe('reason=done with brief.mode', () => {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
index b4f83d4739e..b2490db80e2 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
@@ -846,6 +846,30 @@ describe('createTaskRuntime', () => {
status: 'completed',
});
});
+
+ it('defers completing the current task until its operation finishes', async () => {
+ const taskCaller = { updateStatus: vi.fn() };
+ const taskModel = {
+ resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-1' }),
+ updateContext: vi.fn().mockResolvedValue({}),
+ };
+ const runtime = createTaskRuntime({
+ agentModel: { existsById: vi.fn() } as any,
+ operationId: 'operation-1',
+ taskCaller: taskCaller as any,
+ taskId: 'task-1',
+ taskModel: taskModel as any,
+ taskService: {} as any,
+ });
+
+ const result = await runtime.updateTaskStatus({ identifier: 'T-1', status: 'completed' });
+
+ expect(result).toMatchObject({ success: true });
+ expect(taskModel.updateContext).toHaveBeenCalledWith('task-1', {
+ completion: { requestedByOperationId: 'operation-1' },
+ });
+ expect(taskCaller.updateStatus).not.toHaveBeenCalled();
+ });
});
describe('runTask / runTasks', () => {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
index 6eda94fbd7e..27c8094cc2e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
@@ -792,6 +792,26 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
}
try {
+ // Completing the task that owns the current operation is a delivery
+ // request, not an external cancellation. TaskService.updateStatus
+ // interrupts every still-running topic when a task leaves `running`;
+ // calling it here would therefore make the agent cancel itself and
+ // leave an `interrupted` operation / `canceled` topic. Persist the
+ // intent instead and let onTopicComplete finalize it after the runtime
+ // has reached `done`.
+ if (args.status === 'completed' && operationId && taskId) {
+ const target = await taskModel().resolve(id);
+ if (target?.id === taskId) {
+ await taskModel().updateContext(target.id, {
+ completion: { requestedByOperationId: operationId },
+ });
+ return {
+ content: `Task ${target.identifier} completion requested. It will be finalized when the current run finishes.`,
+ success: true,
+ };
+ }
+ }
+
const result = await taskCaller().updateStatus({
error: args.error,
id,
diff --git a/docs/development/goal-graph-cli.md b/docs/development/goal-graph-cli.md
new file mode 100644
index 00000000000..d5bc38ea12e
--- /dev/null
+++ b/docs/development/goal-graph-cli.md
@@ -0,0 +1,66 @@
+# Goal Graph CLI prototype
+
+The Goal Graph runtime is intentionally usable without a Graph UI. The CLI is
+only a client of the same server application service that a future UI,
+scheduler, or signal source can call.
+
+## Lifecycle
+
+`goal tick` advances one deterministic transition:
+
+1. Select the highest-priority non-terminal Work node whose explicit
+ `depends_on` targets are resolved.
+2. Create and bind exactly one responsible Task when the Work has none.
+3. Start that Task through the existing General Agent runtime.
+4. While the Task runs, report `waiting_external` without duplicating it.
+5. On completion, pin the immutable Task Work version, create a Finding, and
+ resolve the Work node.
+6. On failure (`paused` with an error included), create a durable Decision node
+ and stop at `waiting_human`; a manually paused Task is never restarted by the
+ coordinator.
+7. Mark the Goal achieved only after every Work node is terminal and no
+ Decision is pending.
+
+`goal run` repeatedly calls `tick`. It stops at achieved, a human gate, a
+budget/no-progress boundary, or failure. It can be safely invoked again after a
+restart because lifecycle state lives in PostgreSQL rather than in the CLI
+process.
+
+## Ornith reproduction scenario
+
+```bash
+lh goal create "Reproduce the Ornith self-improvement training system" \
+ --requirement "A reproducible minimal training loop, frozen-set evaluation, and evidence that capability improves without verifier leakage" \
+ --work \
+ "Recover and validate the public training specification" \
+ "Implement the minimal training loop" \
+ "Build a frozen-set verifier and adversarial checks"
+
+lh goal graph <goal-id>
+lh goal run <goal-id>
+```
+
+When a failed Work opens a gate:
+
+```bash
+lh goal decisions <goal-id>
+lh goal decide <goal-id> <decision-id> --option retry --reason "Harden the verifier first"
+lh goal run <goal-id>
+```
+
+The graph can evolve during exploration instead of requiring all branches at
+creation time:
+
+```bash
+lh goal add-node <goal-id> work "Run leakage-resistant frozen-set evaluation"
+lh goal add-edge <goal-id> <finding-node-id> <new-work-node-id> leads_to
+lh goal run <goal-id>
+```
+
+Budget exhaustion pauses coordination and is resumable:
+
+```bash
+lh goal set-budget <goal-id> --max-rounds 20 --max-cost 10
+lh goal resume <goal-id>
+lh goal run <goal-id>
+```
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index de0c67736a7..9d56928d684 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -208,6 +208,7 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
generation: { any: 'model:invoke' },
generationBatch: { any: 'model:invoke' },
generationTopic: { any: 'model:invoke' },
+ goal: rw('agent:read', 'agent:write'),
group: rw('agent:read', 'agent:write'),
healthcheck: 'open',
home: rw('chat:read', 'chat:write'),
diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.ts
new file mode 100644
index 00000000000..49e05f17f8a
--- /dev/null
+++ b/packages/database/src/models/__tests__/goalGraph.test.ts
@@ -0,0 +1,176 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { goalNodes, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { GoalModel } from '../goal';
+import { GoalGraphModel } from '../goalGraph';
+import { TaskModel } from '../task';
+import { WorkModel } from '../work';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'goal-graph-test-user';
+const otherUserId = 'goal-graph-other-user';
+
+const goalModel = new GoalModel(serverDB, userId);
+const graphModel = new GoalGraphModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('GoalGraphModel', () => {
+ it('creates nodes and edges with an atomic event trail', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Reproduce Ornith' });
+ const problem = await graphModel.createNode(goal.id, {
+ kind: 'problem',
+ title: 'Can the published specification reproduce the system?',
+ });
+ const work = await graphModel.createNode(goal.id, {
+ kind: 'work',
+ title: 'Implement the minimal training loop',
+ });
+
+ const edge = await graphModel.createEdge(goal.id, problem!.id, work!.id, 'leads_to');
+ const graph = await graphModel.getGraph(goal.id);
+
+ expect(edge).toMatchObject({ goalId: goal.id, kind: 'leads_to' });
+ expect(graph?.nodes).toHaveLength(2);
+ expect(graph?.edges).toHaveLength(1);
+ expect(graph?.events.map((event) => event.eventType)).toEqual(['created', 'created', 'linked']);
+ });
+
+ it('creates and resolves a durable human decision', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Decision goal' });
+ const node = await graphModel.createNode(goal.id, {
+ kind: 'decision',
+ title: 'Choose verifier',
+ });
+ const decision = await graphModel.createDecision(goal.id, node!.id, {
+ authority: 'user',
+ options: [
+ { id: 'harden', label: 'Harden verifier' },
+ { id: 'continue', label: 'Continue training' },
+ ],
+ question: 'Which branch should run next?',
+ recommendedOptionId: 'harden',
+ });
+
+ const resolved = await graphModel.resolveDecision(
+ goal.id,
+ decision!.id,
+ 'harden',
+ 'Safer first',
+ );
+ const graph = await graphModel.getGraph(goal.id);
+
+ expect(resolved).toMatchObject({ resolvedOptionId: 'harden', status: 'resolved' });
+ expect(graph?.nodes[0]).toMatchObject({ status: 'resolved' });
+ expect(graph?.decisions[0]).toMatchObject({ resolution: 'Safer first', status: 'resolved' });
+ });
+
+ it('allows only one concurrent resolution of a pending decision', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Decision race' });
+ const node = await graphModel.createNode(goal.id, {
+ kind: 'decision',
+ title: 'Choose once',
+ });
+ const decision = await graphModel.createDecision(goal.id, node!.id, {
+ authority: 'user',
+ options: [
+ { id: 'retry', label: 'Retry' },
+ { id: 'retire', label: 'Retire' },
+ ],
+ question: 'Which outcome wins?',
+ });
+
+ const results = await Promise.all([
+ graphModel.resolveDecision(goal.id, decision!.id, 'retry'),
+ graphModel.resolveDecision(goal.id, decision!.id, 'retire'),
+ ]);
+ const graph = await graphModel.getGraph(goal.id);
+
+ expect(results.filter(Boolean)).toHaveLength(1);
+ expect(graph?.events.filter((event) => event.eventType === 'resolved')).toHaveLength(1);
+ expect(graph?.decisions[0].resolvedOptionId).toBe(results.find(Boolean)!.resolvedOptionId);
+ });
+
+ it('allows only one task binding for a work node', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Task binding race' });
+ const node = await graphModel.createNode(goal.id, { kind: 'work', title: 'Run once' });
+ const taskModel = new TaskModel(serverDB, userId);
+ const [firstTask, secondTask] = await Promise.all([
+ taskModel.create({ instruction: 'First candidate' }),
+ taskModel.create({ instruction: 'Second candidate' }),
+ ]);
+
+ expect(await graphModel.claimWorkNode(goal.id, node!.id, new Date(0))).toBeDefined();
+ const bindings = await Promise.all([
+ graphModel.bindTask(goal.id, node!.id, firstTask.id),
+ graphModel.bindTask(goal.id, node!.id, secondTask.id),
+ ]);
+ const graph = await graphModel.getGraph(goal.id);
+
+ expect(bindings.filter(Boolean)).toHaveLength(1);
+ expect(graph?.nodes[0].taskId).toBe(bindings.find(Boolean)!.taskId);
+ expect(graph?.events.filter((event) => event.entityType === 'task')).toHaveLength(1);
+ });
+
+ it('allows an abandoned work claim to be recovered after its lease expires', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Recover claim' });
+ const node = await graphModel.createNode(goal.id, { kind: 'work', title: 'Recoverable work' });
+
+ expect(await graphModel.claimWorkNode(goal.id, node!.id, new Date(0))).toBeDefined();
+ expect(await graphModel.claimWorkNode(goal.id, node!.id, new Date(0))).toBeUndefined();
+
+ await serverDB
+ .update(goalNodes)
+ .set({ updatedAt: new Date('2020-01-01') })
+ .where(eq(goalNodes.id, node!.id));
+
+ expect(await graphModel.claimWorkNode(goal.id, node!.id, new Date('2021-01-01'))).toBeDefined();
+ });
+
+ it('pins an immutable Work version to an owned graph node', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Evidence goal' });
+ const node = await graphModel.createNode(goal.id, { kind: 'work', title: 'Produce evidence' });
+ const task = await new TaskModel(serverDB, userId).create({ instruction: 'Produce evidence' });
+ const work = await new WorkModel(serverDB, userId).registerTask({
+ changeType: 'created',
+ taskId: task.id,
+ toolIdentifier: 'goal-test',
+ toolName: 'createTask',
+ });
+
+ const link = await graphModel.attachWorkVersion(
+ goal.id,
+ node!.id,
+ work!.currentVersionId!,
+ 'produced',
+ );
+
+ expect(link).toMatchObject({ nodeId: node!.id, relation: 'produced' });
+ expect((await graphModel.getGraph(goal.id))?.workVersions).toHaveLength(1);
+ });
+
+ it('does not expose or mutate another user graph', async () => {
+ const otherGoalModel = new GoalModel(serverDB, otherUserId);
+ const otherGraphModel = new GoalGraphModel(serverDB, otherUserId);
+ const goal = await otherGoalModel.create({ subjectType: 'standalone', title: 'Private graph' });
+ const node = await otherGraphModel.createNode(goal.id, { kind: 'work', title: 'Private work' });
+
+ expect(await graphModel.getGraph(goal.id)).toBeUndefined();
+ expect(await graphModel.updateNodeStatus(goal.id, node!.id, 'resolved')).toBeUndefined();
+
+ const graph = await otherGraphModel.getGraph(goal.id);
+ expect(graph?.nodes[0].status).toBe('proposed');
+ expect(graph?.events).toHaveLength(1);
+ });
+});
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
new file mode 100644
index 00000000000..ee040ac74d9
--- /dev/null
+++ b/packages/database/src/models/goalGraph.ts
@@ -0,0 +1,388 @@
+import type {
+ GoalDecisionAuthority,
+ GoalDecisionOption,
+ GoalEdgeKind,
+ GoalEventActorType,
+ GoalEventEntityType,
+ GoalEventType,
+ GoalGraphSnapshot,
+ GoalNodeKind,
+ GoalNodeStatus,
+ GoalNodeWorkVersionRelation,
+} from '@lobechat/types';
+import { and, asc, eq, isNull, lt, or } from 'drizzle-orm';
+
+import { goals } from '../schemas/goal';
+import {
+ goalEdges,
+ goalEvents,
+ goalNodeDecisions,
+ goalNodes,
+ goalNodeWorkVersions,
+} from '../schemas/goalGraph';
+import { works, workVersions } from '../schemas/work';
+import type { LobeChatDatabase, Transaction } from '../type';
+import { buildWorkspaceWhere } from '../utils/workspace';
+import { workOwnership } from './work/context';
+
+interface EventInput {
+ actorId?: string;
+ actorType?: GoalEventActorType;
+ entityId: string;
+ entityType: GoalEventEntityType;
+ eventType: GoalEventType;
+ operationId?: string;
+ reason?: string;
+ taskId?: string;
+}
+
+interface CreateNodeInput {
+ confidence?: number;
+ createdByAgentId?: string;
+ description?: string;
+ kind: GoalNodeKind;
+ priority?: number;
+ status?: GoalNodeStatus;
+ title: string;
+}
+
+interface CreateDecisionInput {
+ authority: GoalDecisionAuthority;
+ options?: GoalDecisionOption[];
+ question: string;
+ recommendedOptionId?: string;
+ requestedProjectRole?: string;
+ requestedUserId?: string;
+}
+
+/** Persistence boundary for an owned Goal Graph and its append-only audit trail. */
+export class GoalGraphModel {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ private ownership = () =>
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, goals);
+
+ private ownedGoal = async (goalId: string, tx: LobeChatDatabase | Transaction = this.db) => {
+ const [goal] = await tx
+ .select()
+ .from(goals)
+ .where(and(eq(goals.id, goalId), this.ownership()))
+ .limit(1);
+ return goal;
+ };
+
+ private appendEvent = async (tx: Transaction, goalId: string, input: EventInput) => {
+ const [event] = await tx
+ .insert(goalEvents)
+ .values({
+ ...input,
+ actorId: input.actorId ?? this.userId,
+ actorType: input.actorType ?? 'user',
+ goalId,
+ })
+ .returning();
+ return event;
+ };
+
+ getGraph = async (goalId: string): Promise<GoalGraphSnapshot | undefined> => {
+ const goal = await this.ownedGoal(goalId);
+ if (!goal) return undefined;
+
+ const [nodes, edges, decisions, events, linkedWorkVersions] = await Promise.all([
+ this.db
+ .select()
+ .from(goalNodes)
+ .where(eq(goalNodes.goalId, goalId))
+ .orderBy(asc(goalNodes.createdAt)),
+ this.db
+ .select()
+ .from(goalEdges)
+ .where(eq(goalEdges.goalId, goalId))
+ .orderBy(asc(goalEdges.createdAt)),
+ this.db
+ .select()
+ .from(goalNodeDecisions)
+ .innerJoin(goalNodes, eq(goalNodeDecisions.nodeId, goalNodes.id))
+ .where(eq(goalNodes.goalId, goalId))
+ .orderBy(asc(goalNodeDecisions.createdAt)),
+ this.db
+ .select()
+ .from(goalEvents)
+ .where(eq(goalEvents.goalId, goalId))
+ .orderBy(asc(goalEvents.createdAt)),
+ this.db
+ .select({ link: goalNodeWorkVersions })
+ .from(goalNodeWorkVersions)
+ .innerJoin(goalNodes, eq(goalNodeWorkVersions.nodeId, goalNodes.id))
+ .where(eq(goalNodes.goalId, goalId))
+ .orderBy(asc(goalNodeWorkVersions.createdAt)),
+ ]);
+
+ return {
+ decisions: decisions.map(({ goal_node_decisions }) => goal_node_decisions),
+ edges,
+ events,
+ goal,
+ nodes,
+ workVersions: linkedWorkVersions.map(({ link }) => link),
+ };
+ };
+
+ attachWorkVersion = async (
+ goalId: string,
+ nodeId: string,
+ workVersionId: string,
+ relation: GoalNodeWorkVersionRelation,
+ ) =>
+ this.db.transaction(async (tx) => {
+ if (!(await this.ownedGoal(goalId, tx))) return undefined;
+ const [node] = await tx
+ .select({ id: goalNodes.id })
+ .from(goalNodes)
+ .where(and(eq(goalNodes.goalId, goalId), eq(goalNodes.id, nodeId)))
+ .limit(1);
+ if (!node) return undefined;
+ const [ownedVersion] = await tx
+ .select({ id: workVersions.id })
+ .from(workVersions)
+ .innerJoin(works, eq(workVersions.workId, works.id))
+ .where(
+ and(
+ eq(workVersions.id, workVersionId),
+ workOwnership({
+ db: this.db,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ }),
+ ),
+ )
+ .limit(1);
+ if (!ownedVersion) return undefined;
+ const [link] = await tx
+ .insert(goalNodeWorkVersions)
+ .values({ nodeId, relation, workVersionId })
+ .onConflictDoNothing()
+ .returning();
+ if (!link) return undefined;
+ await this.appendEvent(tx, goalId, {
+ entityId: nodeId,
+ entityType: 'node',
+ eventType: 'updated',
+ reason: `Attached Work version ${workVersionId} as ${relation}`,
+ });
+ return link;
+ });
+
+ createNode = async (goalId: string, input: CreateNodeInput) =>
+ this.db.transaction(async (tx) => {
+ if (!(await this.ownedGoal(goalId, tx))) return undefined;
+ const [node] = await tx
+ .insert(goalNodes)
+ .values({
+ ...input,
+ confidence: input.confidence?.toString(),
+ createdByUserId: input.createdByAgentId ? undefined : this.userId,
+ goalId,
+ })
+ .returning();
+ await this.appendEvent(tx, goalId, {
+ actorId: input.createdByAgentId,
+ actorType: input.createdByAgentId ? 'agent' : 'user',
+ entityId: node.id,
+ entityType: 'node',
+ eventType: 'created',
+ });
+ return node;
+ });
+
+ createEdge = async (
+ goalId: string,
+ sourceNodeId: string,
+ targetNodeId: string,
+ kind: GoalEdgeKind,
+ ) =>
+ this.db.transaction(async (tx) => {
+ if (!(await this.ownedGoal(goalId, tx))) return undefined;
+ const [edge] = await tx
+ .insert(goalEdges)
+ .values({ goalId, kind, sourceNodeId, targetNodeId })
+ .returning();
+ await this.appendEvent(tx, goalId, {
+ entityId: edge.id,
+ entityType: 'edge',
+ eventType: 'linked',
+ });
+ return edge;
+ });
+
+ bindTask = async (goalId: string, nodeId: string, taskId: string) =>
+ this.db.transaction(async (tx) => {
+ if (!(await this.ownedGoal(goalId, tx))) return undefined;
+ const [node] = await tx
+ .update(goalNodes)
+ .set({ status: 'active', taskId, updatedAt: new Date() })
+ .where(
+ and(
+ eq(goalNodes.goalId, goalId),
+ eq(goalNodes.id, nodeId),
+ eq(goalNodes.kind, 'work'),
+ isNull(goalNodes.taskId),
+ ),
+ )
+ .returning();
+ if (!node) return undefined;
+ await this.appendEvent(tx, goalId, {
+ entityId: taskId,
+ entityType: 'task',
+ eventType: 'linked',
+ taskId,
+ });
+ return node;
+ });
+
+ claimWorkNode = async (goalId: string, nodeId: string, staleBefore: Date) =>
+ this.db.transaction(async (tx) => {
+ if (!(await this.ownedGoal(goalId, tx))) return undefined;
+ const [node] = await tx
+ .update(goalNodes)
+ .set({ status: 'active', updatedAt: new Date() })
+ .where(
+ and(
+ eq(goalNodes.goalId, goalId),
+ eq(goalNodes.id, nodeId),
+ eq(goalNodes.kind, 'work'),
+ or(
+ eq(goalNodes.status, 'proposed'),
+ and(eq(goalNodes.status, 'active'), lt(goalNodes.updatedAt, staleBefore)),
+ ),
+ isNull(goalNodes.taskId),
+ ),
+ )
+ .returning();
+ if (!node) return undefined;
+ await this.appendEvent(tx, goalId, {
+ entityId: node.id,
+ entityType: 'node',
+ eventType: 'activated',
+ });
+ return node;
+ });
+
+ updateNodeStatus = async (
+ goalId: string,
+ nodeId: string,
+ status: GoalNodeStatus,
+ reason?: string,
+ ) =>
+ this.db.transaction(async (tx) => {
+ if (!(await this.ownedGoal(goalId, tx))) return undefined;
+ const [node] = await tx
+ .update(goalNodes)
+ .set({
+ resolvedAt: status === 'resolved' ? new Date() : null,
+ status,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(goalNodes.goalId, goalId), eq(goalNodes.id, nodeId)))
+ .returning();
+ if (!node) return undefined;
+ const eventType: GoalEventType =
+ status === 'active'
+ ? 'activated'
+ : status === 'resolved'
+ ? 'resolved'
+ : status === 'rejected'
+ ? 'rejected'
+ : status === 'retired'
+ ? 'retired'
+ : 'updated';
+ await this.appendEvent(tx, goalId, {
+ entityId: node.id,
+ entityType: 'node',
+ eventType,
+ reason,
+ taskId: node.taskId ?? undefined,
+ });
+ return node;
+ });
+
+ createDecision = async (goalId: string, nodeId: string, input: CreateDecisionInput) =>
+ this.db.transaction(async (tx) => {
+ if (!(await this.ownedGoal(goalId, tx))) return undefined;
+ const [node] = await tx
+ .select()
+ .from(goalNodes)
+ .where(
+ and(
+ eq(goalNodes.goalId, goalId),
+ eq(goalNodes.id, nodeId),
+ eq(goalNodes.kind, 'decision'),
+ ),
+ )
+ .limit(1);
+ if (!node) return undefined;
+ const [decision] = await tx
+ .insert(goalNodeDecisions)
+ .values({ ...input, nodeId })
+ .returning();
+ await this.appendEvent(tx, goalId, {
+ entityId: decision.id,
+ entityType: 'decision',
+ eventType: 'created',
+ });
+ return decision;
+ });
+
+ resolveDecision = async (
+ goalId: string,
+ decisionId: string,
+ optionId: string,
+ resolution?: string,
+ ) =>
+ this.db.transaction(async (tx) => {
+ if (!(await this.ownedGoal(goalId, tx))) return undefined;
+ const [ownedDecision] = await tx
+ .select({ id: goalNodeDecisions.id })
+ .from(goalNodeDecisions)
+ .innerJoin(goalNodes, eq(goalNodeDecisions.nodeId, goalNodes.id))
+ .where(
+ and(
+ eq(goalNodeDecisions.id, decisionId),
+ eq(goalNodeDecisions.status, 'pending'),
+ eq(goalNodes.goalId, goalId),
+ ),
+ )
+ .limit(1);
+ if (!ownedDecision) return undefined;
+ const [decision] = await tx
+ .update(goalNodeDecisions)
+ .set({
+ resolution,
+ resolvedAt: new Date(),
+ resolvedByUserId: this.userId,
+ resolvedOptionId: optionId,
+ status: 'resolved',
+ updatedAt: new Date(),
+ })
+ .where(
+ and(eq(goalNodeDecisions.id, ownedDecision.id), eq(goalNodeDecisions.status, 'pending')),
+ )
+ .returning();
+ if (!decision) return undefined;
+ await tx
+ .update(goalNodes)
+ .set({ resolvedAt: new Date(), status: 'resolved', updatedAt: new Date() })
+ .where(eq(goalNodes.id, decision.nodeId));
+ await this.appendEvent(tx, goalId, {
+ entityId: decision.id,
+ entityType: 'decision',
+ eventType: 'resolved',
+ reason: resolution,
+ });
+ return decision;
+ });
+}
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 02778ddbc31..1f7fe8867c1 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -101,3 +101,91 @@ export type GoalEventEntityType = 'goal' | 'node' | 'edge' | 'decision' | 'task'
export type GoalEventType =
'created' | 'updated' | 'activated' | 'resolved' | 'rejected' | 'retired' | 'linked' | 'unlinked';
+
+export interface GoalGraphNode {
+ confidence: string | null;
+ createdAt: Date;
+ createdByAgentId: string | null;
+ createdByUserId: string | null;
+ description: string | null;
+ goalId: string;
+ id: string;
+ kind: GoalNodeKind;
+ priority: number;
+ resolvedAt: Date | null;
+ status: GoalNodeStatus;
+ taskId: string | null;
+ title: string;
+ updatedAt: Date;
+}
+
+export interface GoalGraphEdge {
+ createdAt: Date;
+ goalId: string;
+ id: string;
+ kind: GoalEdgeKind;
+ sourceNodeId: string;
+ targetNodeId: string;
+}
+
+export interface GoalGraphDecision {
+ authority: GoalDecisionAuthority;
+ canceledAt: Date | null;
+ createdAt: Date;
+ id: string;
+ nodeId: string;
+ options: GoalDecisionOption[] | null;
+ question: string;
+ recommendedOptionId: string | null;
+ requestedProjectRole: string | null;
+ requestedUserId: string | null;
+ resolution: string | null;
+ resolvedAt: Date | null;
+ resolvedByAgentId: string | null;
+ resolvedByUserId: string | null;
+ resolvedOptionId: string | null;
+ status: GoalDecisionStatus;
+ updatedAt: Date;
+}
+
+export interface GoalGraphEvent {
+ actorId: string | null;
+ actorType: GoalEventActorType;
+ createdAt: Date;
+ entityId: string;
+ entityType: GoalEventEntityType;
+ eventType: GoalEventType;
+ goalId: string;
+ id: string;
+ operationId: string | null;
+ reason: string | null;
+ taskId: string | null;
+}
+
+export interface GoalGraphWorkVersionLink {
+ createdAt: Date;
+ id: string;
+ nodeId: string;
+ relation: GoalNodeWorkVersionRelation;
+ workVersionId: string;
+}
+
+export interface GoalGraphSnapshot {
+ decisions: GoalGraphDecision[];
+ edges: GoalGraphEdge[];
+ events: GoalGraphEvent[];
+ goal: GoalItem;
+ nodes: GoalGraphNode[];
+ workVersions: GoalGraphWorkVersionLink[];
+}
+
+export type GoalTickOutcome =
+ 'advanced' | 'achieved' | 'waiting_human' | 'waiting_external' | 'no_progress' | 'failed';
+
+export interface GoalTickResult {
+ goalId: string;
+ message: string;
+ nodeId?: string;
+ outcome: GoalTickOutcome;
+ taskId?: string;
+}
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index b5ee4d62fc0..b4c1cdb1052 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -210,6 +210,11 @@ export interface TaskOriginContext {
}
export interface TaskContext {
+ completion?: {
+ /** The running operation that asked to complete its own task. The lifecycle
+ * finalizes the task only after that operation has finished cleanly. */
+ requestedByOperationId?: string;
+ };
lifecycle?: TaskLifecycleAudit;
origin?: TaskOriginContext;
scheduler?: TaskSchedulerContext;