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): record who made each Goal Graph transition (#18793)

Arvin Xu82c72410466d
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 9f6bda4b6f9..d2fe721195d 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -99,6 +99,8 @@ export const goalRouter = router({
.input(
z.object({
agentId: z.string().optional(),
+ /** Set by the `/goal` tool so the seeded graph is authored by the agent. */
+ createdByAgentId: z.string().optional(),
config: z
.object({
recovery: z
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index cf6db7b7e40..0c0de8e6ac4 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -228,6 +229,67 @@ describe('GoalService', () => {
).not.toContainEqual(expect.objectContaining({ id: graph.goal.id }));
});
+ it('files a goal the agent created under that agent, not its owner', async () => {
+ // `/goal` is an agent making the call. `agentId` alone cannot say so β€” the
+ // creation modal sets it too, and there the author is the person.
+ await serverDB
+ .insert(agents)
+ .values({ id: 'agt_goal_author', slug: 'agt-goal-author', userId });
+ const service = new GoalService(serverDB, userId);
+
+ const graph = await service.create({
+ agentId: 'agt_goal_author',
+ createdByAgentId: 'agt_goal_author',
+ title: 'Agent-authored goal',
+ work: ['Do the thing'],
+ });
+
+ const seeded = graph.events.filter((event) => ['created', 'linked'].includes(event.eventType));
+ expect(seeded.length).toBeGreaterThan(0);
+ expect(seeded.every((event) => event.actorType === 'agent')).toBe(true);
+ expect(seeded.every((event) => event.actorId === 'agt_goal_author')).toBe(true);
+ expect(graph.nodes.every((node) => node.createdByAgentId === 'agt_goal_author')).toBe(true);
+ });
+
+ it('still files a goal the user created under the user, even on an agent page', async () => {
+ // The modal passes `agentId` for assignment; the author is the person.
+ await serverDB.insert(agents).values({ id: 'agt_assignee', slug: 'agt-assignee', userId });
+ const service = new GoalService(serverDB, userId);
+
+ const graph = await service.create({
+ agentId: 'agt_assignee',
+ title: 'User-authored goal',
+ work: ['Do the thing'],
+ });
+
+ const seeded = graph.events.filter((event) => ['created', 'linked'].includes(event.eventType));
+ expect(seeded.every((event) => event.actorType === 'user')).toBe(true);
+ expect(seeded.every((event) => event.actorId === userId)).toBe(true);
+ });
+
+ it('separates what the coordinator decided from what the user asked for', async () => {
+ // The audit trail recorded every transition as the goal's owner, so "what did
+ // the system decide on its own" could not be answered from product data.
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Attributed goal', work: ['Do the thing'] });
+
+ // Seeding is the user's ask; claiming the Work and binding its task is not.
+ await service.tick(graph.goal.id);
+
+ const { events, nodes } = await service.graph(graph.goal.id);
+ const work = nodes.find((node) => node.kind === 'work')!;
+ const actorsFor = (eventType: string, entityId: string) =>
+ events
+ .filter((event) => event.eventType === eventType && event.entityId === entityId)
+ .map((event) => ({ actorId: event.actorId, actorType: event.actorType }));
+
+ expect(actorsFor('created', work.id)).toEqual([{ actorId: userId, actorType: 'user' }]);
+ expect(actorsFor('activated', work.id)).toEqual([
+ { actorId: GOAL_COORDINATOR_ACTOR_ID, actorType: 'system' },
+ ]);
+ expect(events.some((event) => event.actorType === 'system')).toBe(true);
+ });
+
it('keeps the overall requirement as background while making the current work authoritative', async () => {
const service = new GoalService(serverDB, userId);
const requirement = `Generate verified training data. ${'Detailed acceptance evidence. '.repeat(20)}`;
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index ba6b1936640..578fde69b9d 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -1,3 +1,4 @@
+import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
import type {
GoalConfig,
GoalEdgeKind,
@@ -40,6 +41,12 @@ export interface CreateGoalWorkInput {
export interface CreateGoalGraphInput {
agentId?: string;
config?: GoalConfig;
+ /**
+ * The agent that made this call, when a tool did. Distinct from `agentId`,
+ * which is the agent the goal is assigned to β€” creating a goal from the modal
+ * on an agent's page sets that, but the author is still the person.
+ */
+ createdByAgentId?: string;
maxRounds?: number;
maxTotalCost?: number;
projectId?: string;
@@ -61,7 +68,18 @@ export interface CreateGoalNodeInput {
export class GoalService {
private readonly acceptanceService: AcceptanceService;
private readonly goalModel: GoalModel;
+ /**
+ * Graph writes attributed to the person who asked for them: seeding a goal,
+ * adding a node or edge by hand, resolving a decision gate.
+ */
private readonly graphModel: GoalGraphModel;
+ /**
+ * Graph writes the coordinator makes on its own β€” claiming Work, binding its
+ * task, synthesizing a finding, opening a gate. Attributed to the coordinator
+ * even when a person pressed Advance: they asked it to run, they did not make
+ * these moves.
+ */
+ private readonly coordinatorGraph: GoalGraphModel;
private readonly taskModel: TaskModel;
private readonly taskService: TaskService;
private readonly taskTopicModel: TaskTopicModel;
@@ -75,12 +93,25 @@ export class GoalService {
this.acceptanceService = new AcceptanceService(db, userId, workspaceId);
this.goalModel = new GoalModel(db, userId, workspaceId);
this.graphModel = new GoalGraphModel(db, userId, workspaceId);
+ this.coordinatorGraph = new GoalGraphModel(db, userId, workspaceId, {
+ id: GOAL_COORDINATOR_ACTOR_ID,
+ type: 'system',
+ });
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);
}
+ /**
+ * The graph model whose audit trail names `agentId` as the author, or the
+ * user-attributed one when a person is calling.
+ */
+ private graphAs = (agentId?: string) =>
+ agentId
+ ? new GoalGraphModel(this.db, this.userId, this.workspaceId, { id: agentId, type: 'agent' })
+ : this.graphModel;
+
create = async (input: CreateGoalGraphInput): Promise<GoalGraphSnapshot> => {
if (input.agentId) {
await assertAgentUsableBy(this.db, input.agentId, {
@@ -106,8 +137,14 @@ export class GoalService {
subjectType: 'standalone',
title: input.title,
});
+ // `/goal` is an agent making the call. Seeding through the user-attributed
+ // model would file the whole opening graph under the goal's owner, which is
+ // the same loss of authorship the coordinator split just fixed.
+ const authorGraph = this.graphAs(input.createdByAgentId);
+
try {
- const problem = await this.graphModel.createNode(goal.id, {
+ const problem = await authorGraph.createNode(goal.id, {
+ createdByAgentId: input.createdByAgentId,
description: input.requirement,
kind: 'problem',
status: 'active',
@@ -117,13 +154,14 @@ export class GoalService {
for (const seed of input.work ?? []) {
const { description, title } = typeof seed === 'string' ? { title: seed } : seed;
- const work = await this.graphModel.createNode(goal.id, {
+ const work = await authorGraph.createNode(goal.id, {
+ createdByAgentId: input.createdByAgentId,
description,
kind: 'work',
title,
});
if (!work) throw new Error('Failed to seed goal work');
- await this.graphModel.createEdge(goal.id, problem.id, work.id, 'decomposes');
+ await authorGraph.createEdge(goal.id, problem.id, work.id, 'decomposes');
}
} catch (error) {
await this.goalModel.delete(goal.id).catch(() => {});
@@ -337,7 +375,7 @@ export class GoalService {
(node) => node.title === GOAL_ACCEPTANCE_WORK_TITLE,
);
if (graph.goal.requirement && !goalAcceptanceWork) {
- const result = await this.graphModel.createNodeOnce(goalId, {
+ const result = await this.coordinatorGraph.createNodeOnce(goalId, {
description: [
`Complete and prove the overall Goal acceptance requirement: ${graph.goal.requirement}`,
'Inspect and reuse existing Goal findings, artifacts, metrics, and command results as the primary evidence. Do not repeat expensive or destructive work when the existing evidence is sufficient and still auditable.',
@@ -358,7 +396,12 @@ export class GoalService {
if (result.created) {
const problem = graph.nodes.find((node) => node.kind === 'problem');
if (problem) {
- await this.graphModel.createEdge(goalId, problem.id, result.node.id, 'decomposes');
+ await this.coordinatorGraph.createEdge(
+ goalId,
+ problem.id,
+ result.node.id,
+ 'decomposes',
+ );
}
}
return {
@@ -400,7 +443,7 @@ export class GoalService {
}
if (!frontier.taskId) {
- const claim = await this.graphModel.claimWorkNode(
+ const claim = await this.coordinatorGraph.claimWorkNode(
goalId,
frontier.id,
new Date(Date.now() - WORK_NODE_CLAIM_TTL_MS),
@@ -441,7 +484,7 @@ export class GoalService {
),
});
acceptanceId = acceptance.id;
- const bound = await this.graphModel.bindTask(goalId, frontier.id, task.id);
+ const bound = await this.coordinatorGraph.bindTask(goalId, frontier.id, task.id);
if (!bound) {
await this.acceptanceService.acceptanceModel.delete(acceptance.id);
await this.taskModel.delete(task.id);
@@ -461,7 +504,7 @@ export class GoalService {
console.error('[GoalService.tick] failed to delete unbound task:', cleanupError);
});
}
- await this.graphModel.updateNodeStatus(goalId, frontier.id, 'proposed');
+ await this.coordinatorGraph.updateNodeStatus(goalId, frontier.id, 'proposed');
throw error;
}
const work = await this.workModel.registerTask({
@@ -471,7 +514,7 @@ export class GoalService {
toolName: 'createResponsibleTask',
});
if (work?.currentVersionId) {
- await this.graphModel.attachWorkVersion(
+ await this.coordinatorGraph.attachWorkVersion(
goalId,
frontier.id,
work.currentVersionId,
@@ -490,7 +533,7 @@ export class GoalService {
const task = await this.taskModel.findById(frontier.taskId);
if (!task) {
- await this.graphModel.updateNodeStatus(
+ await this.coordinatorGraph.updateNodeStatus(
goalId,
frontier.id,
'waiting',
@@ -524,7 +567,7 @@ export class GoalService {
this.workspaceId,
).recover({ goal: graph.goal, spentCost: totalCost, task });
if (recovery === 'continued') {
- await this.graphModel.updateNodeStatus(
+ await this.coordinatorGraph.updateNodeStatus(
goalId,
frontier.id,
'active',
@@ -646,7 +689,7 @@ export class GoalService {
};
private ensureTaskWorkVersion = async (goalId: string, nodeId: string, taskId: string) => {
- const graph = await this.graphModel.getGraph(goalId);
+ const graph = await this.coordinatorGraph.getGraph(goalId);
if (graph?.workVersions.some((link) => link.nodeId === nodeId)) return;
const work = await this.workModel.registerTask({
changeType: 'created',
@@ -655,7 +698,12 @@ export class GoalService {
toolName: 'createResponsibleTask',
});
if (work?.currentVersionId) {
- await this.graphModel.attachWorkVersion(goalId, nodeId, work.currentVersionId, 'produced');
+ await this.coordinatorGraph.attachWorkVersion(
+ goalId,
+ nodeId,
+ work.currentVersionId,
+ 'produced',
+ );
}
};
@@ -722,7 +770,7 @@ export class GoalService {
this.workspaceId,
).recover({ goal: graph.goal, task });
if (recovery === 'continued') {
- await this.graphModel.updateNodeStatus(
+ await this.coordinatorGraph.updateNodeStatus(
graph.goal.id,
nodeId,
'active',
@@ -815,7 +863,7 @@ export class GoalService {
topicId: latest?.topicId,
});
if (completedWork?.currentVersionId) {
- await this.graphModel.attachWorkVersion(
+ await this.coordinatorGraph.attachWorkVersion(
graph.goal.id,
nodeId,
completedWork.currentVersionId,
@@ -824,7 +872,7 @@ export class GoalService {
}
if (!existingFinding) {
const handoff = latest?.handoff as TaskTopicHandoff | null;
- const finding = await this.graphModel.createNode(graph.goal.id, {
+ const finding = await this.coordinatorGraph.createNode(graph.goal.id, {
confidence: 1,
description: handoff?.content ?? handoff?.summary ?? undefined,
kind: 'finding',
@@ -834,9 +882,10 @@ export class GoalService {
handoff?.summary ??
`Completed: ${graph.nodes.find((node) => node.id === nodeId)?.title}`,
});
- if (finding) await this.graphModel.createEdge(graph.goal.id, nodeId, finding.id, 'produces');
+ if (finding)
+ await this.coordinatorGraph.createEdge(graph.goal.id, nodeId, finding.id, 'produces');
}
- await this.graphModel.updateNodeStatus(
+ await this.coordinatorGraph.updateNodeStatus(
graph.goal.id,
nodeId,
'resolved',
@@ -862,18 +911,18 @@ export class GoalService {
.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, {
+ const node = await this.coordinatorGraph.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.coordinatorGraph.createEdge(graph.goal.id, nodeId, node.id, 'leads_to');
const terminalAcceptance =
graph.nodes.find((candidate) => candidate.id === nodeId)?.title ===
GOAL_ACCEPTANCE_WORK_TITLE;
- await this.graphModel.createDecision(graph.goal.id, node.id, {
+ await this.coordinatorGraph.createDecision(graph.goal.id, node.id, {
authority: 'user',
options: terminalAcceptance
? [
@@ -892,7 +941,7 @@ export class GoalService {
});
}
}
- await this.graphModel.updateNodeStatus(graph.goal.id, nodeId, 'waiting', reason);
+ await this.coordinatorGraph.updateNodeStatus(graph.goal.id, nodeId, 'waiting', reason);
await this.goalModel.updateStatus(graph.goal.id, 'review');
return {
goalId: graph.goal.id,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/goal.ts b/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
index 85382355b2d..8b071e12a02 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
@@ -43,6 +43,7 @@ export const goalRuntime: ServerRuntimeRegistration = {
const goalService = new GoalService(serverDB, userId, workspaceId ?? undefined);
const graph = await goalService.create({
agentId,
+ createdByAgentId: agentId,
config: {
recovery: { maxAttemptsPerWork: resolveGoalAttemptBudget(args.maxIterations) },
},
diff --git a/packages/builtin-tool-goal/src/client/executor/index.ts b/packages/builtin-tool-goal/src/client/executor/index.ts
index 1b0af463266..0a258858019 100644
--- a/packages/builtin-tool-goal/src/client/executor/index.ts
+++ b/packages/builtin-tool-goal/src/client/executor/index.ts
@@ -53,6 +53,7 @@ class GoalExecutor extends BaseExecutor<typeof GoalApiName> {
try {
const graph = await goalService.create({
agentId: ctx.agentId,
+ createdByAgentId: ctx.agentId,
config: {
recovery: { maxAttemptsPerWork: resolveGoalAttemptBudget(params.maxIterations) },
},
diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.ts
index 4667a926852..73fdbe862a5 100644
--- a/packages/const/src/goal.ts
+++ b/packages/const/src/goal.ts
@@ -32,3 +32,13 @@ export type GoalStatus = (typeof goalStatuses)[number];
export const goalSubjectTypes = ['task', 'topic', 'standalone'] as const;
export type GoalSubjectType = (typeof goalSubjectTypes)[number];
+
+/**
+ * `actorId` the coordinator stamps on the graph transitions it makes itself.
+ *
+ * Goal events used to record every transition as the goal's owner, because the
+ * model falls back to its `userId`. That made the coordinator's own moves
+ * indistinguishable from the user's, and "what did the system decide on its own"
+ * unanswerable β€” a stable id for the one non-human actor is what separates them.
+ */
+export const GOAL_COORDINATOR_ACTOR_ID = 'goal-coordinator';
diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.ts
index f15f503a4a3..8dcdf5aa485 100644
--- a/packages/database/src/models/__tests__/goalGraph.test.ts
+++ b/packages/database/src/models/__tests__/goalGraph.test.ts
@@ -1,9 +1,10 @@
// @vitest-environment node
+import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { goalNodes, users } from '../../schemas';
+import { agents, goalNodes, users } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { GoalModel } from '../goal';
import { GoalGraphModel } from '../goalGraph';
@@ -47,6 +48,40 @@ describe('GoalGraphModel', () => {
expect(graph?.events.map((event) => event.eventType)).toEqual(['created', 'created', 'linked']);
});
+ it('records who made each transition', async () => {
+ // Every event used to be attributed to the goal's owner, because the model
+ // falls back to its `userId` β€” which made a move the coordinator decided on
+ // its own indistinguishable from one a person made.
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Attributed' });
+ const coordinator = new GoalGraphModel(serverDB, userId, undefined, {
+ id: GOAL_COORDINATOR_ACTOR_ID,
+ type: 'system',
+ });
+
+ const byUser = await graphModel.createNode(goal.id, { kind: 'work', title: 'Asked for' });
+ const bySystem = await coordinator.createNode(goal.id, { kind: 'finding', title: 'Concluded' });
+ await serverDB.insert(agents).values({ id: 'agt_author', slug: 'agt-author', userId });
+ const byAgent = await coordinator.createNode(goal.id, {
+ createdByAgentId: 'agt_author',
+ kind: 'finding',
+ title: 'Written by an agent',
+ });
+
+ const { events } = (await graphModel.getGraph(goal.id))!;
+ const actorOf = (nodeId: string) => {
+ const event = events.find((item) => item.entityId === nodeId);
+ return { actorId: event?.actorId, actorType: event?.actorType };
+ };
+
+ expect(actorOf(byUser!.id)).toEqual({ actorId: userId, actorType: 'user' });
+ expect(actorOf(bySystem!.id)).toEqual({
+ actorId: GOAL_COORDINATOR_ACTOR_ID,
+ actorType: 'system',
+ });
+ // An explicit agent author still wins over the instance actor.
+ expect(actorOf(byAgent!.id)).toEqual({ actorId: 'agt_author', actorType: 'agent' });
+ });
+
it('creates a synthesized node only once when coordinators race', async () => {
const goal = await goalModel.create({
subjectType: 'standalone',
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 79f84a3efab..9d2c7701e18 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -2,6 +2,7 @@ import type {
GoalDecisionAuthority,
GoalDecisionOption,
GoalEdgeKind,
+ GoalEventActor,
GoalEventActorType,
GoalEventEntityType,
GoalEventType,
@@ -57,10 +58,17 @@ interface CreateDecisionInput {
/** Persistence boundary for an owned Goal Graph and its append-only audit trail. */
export class GoalGraphModel {
+ /**
+ * `actor` is who the audit trail records for the transitions made through this
+ * instance. It defaults to the owning user, which is right for anything a
+ * person did; the coordinator passes its own so the trail can answer "did a
+ * human do this, or did the system decide it".
+ */
constructor(
private readonly db: LobeChatDatabase,
private readonly userId: string,
private readonly workspaceId?: string,
+ private readonly actor?: GoalEventActor,
) {}
private ownership = () =>
@@ -76,12 +84,13 @@ export class GoalGraphModel {
};
private appendEvent = async (tx: Transaction, goalId: string, input: EventInput) => {
+ const actor = this.actor ?? { id: this.userId, type: 'user' as const };
const [event] = await tx
.insert(goalEvents)
.values({
...input,
- actorId: input.actorId ?? this.userId,
- actorType: input.actorType ?? 'user',
+ actorId: input.actorId ?? actor.id,
+ actorType: input.actorType ?? actor.type,
goalId,
})
.returning();
@@ -191,7 +200,7 @@ export class GoalGraphModel {
.returning();
await this.appendEvent(tx, goalId, {
actorId: input.createdByAgentId,
- actorType: input.createdByAgentId ? 'agent' : 'user',
+ actorType: input.createdByAgentId ? 'agent' : undefined,
entityId: node.id,
entityType: 'node',
eventType: 'created',
@@ -230,7 +239,7 @@ export class GoalGraphModel {
.returning();
await this.appendEvent(tx, goalId, {
actorId: input.createdByAgentId,
- actorType: input.createdByAgentId ? 'agent' : 'user',
+ actorType: input.createdByAgentId ? 'agent' : undefined,
entityId: node.id,
entityType: 'node',
eventType: 'created',
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 074e1b965e1..59a565d32a4 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -101,6 +101,15 @@ export type GoalEventActorType = 'agent' | 'user' | 'system';
export type GoalEventEntityType = 'goal' | 'node' | 'edge' | 'decision' | 'task';
+/**
+ * Who a Goal Graph mutation is recorded as. Defaults to the acting user; the
+ * coordinator supplies its own so its moves are separable from a person's.
+ */
+export interface GoalEventActor {
+ id: string;
+ type: GoalEventActorType;
+}
+
export type GoalEventType =
'created' | 'updated' | 'activated' | 'resolved' | 'rejected' | 'retired' | 'linked' | 'unlinked';
diff --git a/src/services/goal.ts b/src/services/goal.ts
index 7041b6caca7..3dbd2b21e5c 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -23,6 +23,8 @@ class GoalService {
create = async (params: {
agentId?: string;
config?: GoalConfig;
+ /** Set by the `/goal` tool so the seeded graph is authored by the agent. */
+ createdByAgentId?: string;
maxRounds?: number;
maxTotalCost?: number;
projectId?: string;