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): bound graph reads, trace lifecycle transitions, add a deadline budget (#18970)

Arvin Xu7d06d137879d
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 50b1d5dd82a..33b772b456a 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -113,6 +113,12 @@ export const goalRouter = router({
operationLeaseTimeoutMs: z.number().int().min(60_000).optional(),
})
.optional(),
+ schedule: z
+ .object({
+ /** ISO-8601 instant; past it the coordinator stops dispatching. */
+ deadline: z.string().datetime().nullable().optional(),
+ })
+ .optional(),
})
.optional(),
maxRounds: z.number().int().positive().optional(),
@@ -269,6 +275,8 @@ export const goalRouter = router({
setBudget: goalWriteProcedure
.input(
idInput.extend({
+ /** ISO-8601 calendar-time budget; null clears the deadline. */
+ deadline: z.string().datetime().nullable().optional(),
maxRounds: z.number().int().positive().nullable().optional(),
maxTotalCost: z.number().positive().nullable().optional(),
}),
diff --git a/apps/server/src/services/goal/decideNextMove.test.ts b/apps/server/src/services/goal/decideNextMove.test.ts
index eb370d02550..784e14b9f42 100644
--- a/apps/server/src/services/goal/decideNextMove.test.ts
+++ b/apps/server/src/services/goal/decideNextMove.test.ts
@@ -205,11 +205,46 @@ describe('decideNextMove', () => {
expect(move.message).toContain('3/');
});
+ it('stops when the deadline passed instead of dispatching', () => {
+ // A calendar deadline is a budget unit the attempt/round/dollar trio
+ // cannot express; past it the coordinator must park the goal exactly
+ // like any other exhausted budget.
+ const move = decide(snapshot, {
+ budget: {
+ costLimitReached: false,
+ deadlinePassed: true,
+ roundLimitReached: false,
+ runs: 0,
+ totalCost: 0,
+ },
+ frontierTask: task(),
+ });
+
+ expect(move).toMatchObject({ branch: 'budget_exhausted', outcome: 'no_progress' });
+ expect(move.message).toContain('Deadline passed');
+ });
+
+ it('checks the deadline before the round and cost budgets', () => {
+ const move = decide(snapshot, {
+ budget: {
+ costLimitReached: true,
+ deadlinePassed: true,
+ roundLimitReached: true,
+ runs: 9,
+ totalCost: 9,
+ },
+ frontierTask: task(),
+ });
+
+ expect(move.message).toContain('Deadline passed');
+ });
+
it('dispatches when the budget still has room', () => {
expect(
decide(snapshot, {
budget: {
costLimitReached: false,
+ deadlinePassed: false,
roundLimitReached: false,
runs: 1,
totalCost: 0.5,
diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.ts
index 5f4a24bb7dd..51c3bc773b0 100644
--- a/apps/server/src/services/goal/decideNextMove.ts
+++ b/apps/server/src/services/goal/decideNextMove.ts
@@ -421,6 +421,15 @@ const decideForTask = (
// stays total if a status slips through.
if (task.status === 'running' || task.status === 'scheduled') return 'parked';
+ if (budget?.deadlinePassed) {
+ return {
+ ...base,
+ branch: 'budget_exhausted',
+ message: `Deadline passed (${graph.goal.config?.schedule?.deadline ?? 'unknown'}); no new Work will be dispatched`,
+ outcome: 'no_progress',
+ };
+ }
+
if (budget?.roundLimitReached || budget?.costLimitReached) {
return {
...base,
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 781e7a352cc..b699d9d1b17 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -281,6 +281,71 @@ describe('GoalService', () => {
).not.toContainEqual(expect.objectContaining({ id: graph.goal.id }));
});
+ it('leaves goal-level status transitions on the event trail', async () => {
+ // The coordinator parks and reopens goals constantly, but only node
+ // transitions used to be recorded β€” `entity_type='goal'` events existed in
+ // the schema with no writer, so the lifecycle timeline was unreconstructable.
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Lifecycle trail', work: ['A', 'B'] });
+ const [a, b] = graph.nodes.filter((n) => n.kind === 'task');
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');
+ await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');
+
+ await service.tick(graph.goal.id); // deadlock β†’ no_frontier β†’ paused
+ await service.resume(graph.goal.id); // paused β†’ running
+
+ const lifecycle = (await service.graph(graph.goal.id)).events.filter(
+ (event) => event.entityType === 'goal',
+ );
+
+ // Same-millisecond events read back in either order; assert on content.
+ expect(lifecycle).toHaveLength(2);
+ expect(lifecycle).toContainEqual(
+ expect.objectContaining({
+ actorType: 'system',
+ eventType: 'updated',
+ reason: 'no eligible work to advance',
+ }),
+ );
+ expect(lifecycle).toContainEqual(
+ expect.objectContaining({ eventType: 'activated', reason: 'resumed by user' }),
+ );
+ });
+
+ it('reopens a goal its deadline stopped when the deadline moves out', async () => {
+ // A calendar deadline is the long-horizon budget unit; extending it has to
+ // unstick the goal exactly like raising a round budget does. Two ticks:
+ // creating the responsible task costs nothing, the deadline gates the run.
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { schedule: { deadline: new Date(Date.now() - 1000).toISOString() } },
+ title: 'Overdue',
+ work: ['Too late to start'],
+ });
+
+ await service.tick(graph.goal.id); // creates the responsible task
+ const stopped = await service.tick(graph.goal.id);
+ expect(stopped.message).toContain('Deadline passed');
+ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');
+
+ const extended = await service.setBudget(graph.goal.id, {
+ deadline: new Date(Date.now() + 3_600_000).toISOString(),
+ });
+
+ expect(extended?.status).not.toBe('paused');
+ expect(extended?.config?.schedule?.deadline).toBeTruthy();
+ });
+
+ it('dispatches work when the goal has no deadline', async () => {
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'No deadline', work: ['Just work'] });
+
+ const result = await service.tick(graph.goal.id);
+
+ expect(result.outcome).toBe('advanced');
+ });
+
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.
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index d0c91e54579..ac562202190 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -264,8 +264,40 @@ export class GoalService {
return this.goalModel.delete(goalId);
};
+ /**
+ * Move the goal's lifecycle status and leave an event behind.
+ *
+ * The row update alone made status changes untraceable: `entityType='goal'`
+ * events existed in the schema but nothing wrote them, so a goal's
+ * planning β†’ running β†’ paused β†’ achieved path could not be reconstructed
+ * from its timeline. Transitions the coordinator makes are filed under the
+ * coordinator actor; a person's pause/resume keeps the user attribution the
+ * model defaults to β€” the split that separates what the coordinator decided
+ * from what the user asked for relies on.
+ *
+ * A same-status write is a no-op β€” re-stamping `running` on every tick that
+ * touches a running goal would flood the timeline the way the unbounded
+ * event read flooded the payload.
+ */
+ private transitionStatus = async (
+ goal: GoalItem,
+ to: GoalStatus,
+ reason?: string,
+ actor: 'coordinator' | 'user' = 'coordinator',
+ ): Promise<GoalItem | undefined> => {
+ if (goal.status === to) return goal;
+ const updated = await this.goalModel.updateStatus(goal.id, to);
+ if (!updated) return undefined;
+ const model = actor === 'coordinator' ? this.coordinatorGraph : this.graphModel;
+ await model
+ .recordGoalStatus(goal.id, goal.status, to, reason)
+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));
+ return updated;
+ };
+
pause = async (goalId: string) => {
- const goal = await this.goalModel.updateStatus(goalId, 'paused');
+ const graph = await this.requireGraph(goalId);
+ const goal = await this.transitionStatus(graph.goal, 'paused', 'paused by user', 'user');
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
return goal;
};
@@ -281,8 +313,11 @@ export class GoalService {
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 deadline = goal.config?.schedule?.deadline ?? null;
return {
costLimitReached: goal.maxTotalCost !== null && totalCost >= Number(goal.maxTotalCost),
+ deadline,
+ deadlinePassed: deadline !== null && Date.now() >= new Date(deadline).getTime(),
roundLimitReached: goal.maxRounds !== null && runs.length >= goal.maxRounds,
runs,
totalCost,
@@ -291,12 +326,27 @@ export class GoalService {
setBudget = async (
goalId: string,
- budget: { maxRounds?: number | null; maxTotalCost?: number | null },
+ budget: {
+ deadline?: string | null;
+ maxRounds?: number | null;
+ maxTotalCost?: number | null;
+ },
) => {
const before = await this.requireGraph(goalId);
const wasBinding = await this.evaluateBudget(before.goal, before);
- const goal = await this.goalModel.update(goalId, budget);
+ // Deadline joins the two execution budgets on the goal row's config; null
+ // clears it. The merge keeps an untouched recovery/schedule block intact.
+ const config = { ...before.goal.config };
+ if (budget.deadline !== undefined || config.schedule) {
+ config.schedule = { ...config.schedule, deadline: budget.deadline ?? null };
+ }
+
+ const goal = await this.goalModel.update(goalId, {
+ config,
+ maxRounds: budget.maxRounds,
+ maxTotalCost: budget.maxTotalCost,
+ });
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
// Raising a budget is how a user un-sticks a goal the coordinator parked on
@@ -305,11 +355,14 @@ export class GoalService {
// Resume as a second gesture. Only a goal the budget actually stopped is
// reopened: if the old budget was not binding, this pause was somebody's
// deliberate one and is left alone.
- const stoppedByBudget = wasBinding.costLimitReached || wasBinding.roundLimitReached;
+ const stoppedByBudget =
+ wasBinding.costLimitReached || wasBinding.roundLimitReached || wasBinding.deadlinePassed;
if (goal.status !== 'paused' || !stoppedByBudget) return goal;
const nowBinding = await this.evaluateBudget(goal, before);
- if (nowBinding.costLimitReached || nowBinding.roundLimitReached) return goal;
+ if (nowBinding.costLimitReached || nowBinding.roundLimitReached || nowBinding.deadlinePassed) {
+ return goal;
+ }
return (await this.resume(goalId)) ?? goal;
};
@@ -319,7 +372,8 @@ export class GoalService {
const status = graph.decisions.some((decision) => decision.status === 'pending')
? 'review'
: 'running';
- return this.goalModel.updateStatus(goalId, status);
+ const goal = await this.transitionStatus(graph.goal, status, 'resumed by user', 'user');
+ return goal ?? graph.goal;
};
decide = async (goalId: string, decisionId: string, optionId: string, resolution?: string) => {
@@ -358,7 +412,11 @@ export class GoalService {
const terminalAcceptanceFailed =
source?.title === GOAL_ACCEPTANCE_TASK_TITLE &&
(optionId === 'retire' || optionId === 'fail');
- await this.goalModel.updateStatus(goalId, terminalAcceptanceFailed ? 'failed' : 'running');
+ await this.transitionStatus(
+ graph.goal,
+ terminalAcceptanceFailed ? 'failed' : 'running',
+ `decision "${decision.question}" resolved: ${optionId}`,
+ );
return resolved;
};
@@ -444,7 +502,7 @@ export class GoalService {
}
case 'pending_decision': {
- await this.goalModel.updateStatus(goalId, 'review');
+ await this.transitionStatus(graph.goal, 'review', 'a decision gate is open');
effects.push({ type: 'goal_status', detail: 'review' });
return observe({
goalId,
@@ -468,7 +526,7 @@ export class GoalService {
// sweep's window. A `running` goal that always reports `no_progress` is
// picked by every scan forever, and enough of them starve every other
// stalled goal out of the newest-first limit.
- await this.goalModel.updateStatus(goalId, 'paused');
+ await this.transitionStatus(graph.goal, 'paused', 'no eligible work to advance');
effects.push({ type: 'goal_status', detail: 'paused' });
return observe({ goalId, message: move.message, outcome: move.outcome });
}
@@ -544,7 +602,7 @@ export class GoalService {
}
case 'budget_exhausted': {
- await this.goalModel.updateStatus(goalId, 'paused');
+ await this.transitionStatus(graph.goal, 'paused', move.message);
effects.push({ type: 'goal_status', detail: 'paused' });
return observe({
goalId,
@@ -575,7 +633,7 @@ export class GoalService {
const goalId = graph.goal.id;
if (move.outcome === 'achieved') {
- await this.goalModel.updateStatus(goalId, 'achieved');
+ await this.transitionStatus(graph.goal, 'achieved', 'Goal-level acceptance passed');
effects.push({ type: 'goal_status', detail: 'achieved' });
return { goalId, message: move.message, outcome: 'achieved' };
}
@@ -706,7 +764,7 @@ export class GoalService {
'produced',
);
}
- await this.goalModel.updateStatus(goalId, 'running');
+ await this.transitionStatus(graph.goal, 'running', `dispatched ${task.identifier}`);
return {
goalId,
message: `Created responsible task ${task.identifier}`,
@@ -743,7 +801,7 @@ export class GoalService {
'active',
'Automatically started the next Work attempt after verification feedback',
);
- await this.goalModel.updateStatus(goalId, 'running');
+ await this.transitionStatus(graph.goal, 'running', 'automatic recovery started a run');
// Only when this advance is the one that spawned the run. Reporting it
// for a retry another advance owns would put a run in this trajectory
// that it did not start, and attribute its cost here.
@@ -962,7 +1020,7 @@ export class GoalService {
'active',
'Recovered an abandoned Work operation and started the next attempt',
);
- await this.goalModel.updateStatus(graph.goal.id, 'running');
+ await this.transitionStatus(graph.goal, 'running', 'reclaimed an abandoned Work');
if (recovery.outcome === 'started') {
effects.push({
detail: 'abandoned operation retry',
@@ -1196,7 +1254,7 @@ export class GoalService {
}
}
await this.coordinatorGraph.updateNodeStatus(graph.goal.id, nodeId, 'waiting', reason);
- await this.goalModel.updateStatus(graph.goal.id, 'review');
+ await this.transitionStatus(graph.goal, 'review', reason);
return {
goalId: graph.goal.id,
message: 'Task failed; a human decision gate was opened',
diff --git a/apps/server/src/services/goal/traceObservation.ts b/apps/server/src/services/goal/traceObservation.ts
index 354c6e0d739..531a3e54933 100644
--- a/apps/server/src/services/goal/traceObservation.ts
+++ b/apps/server/src/services/goal/traceObservation.ts
@@ -87,6 +87,9 @@ export const toFrontierTaskState = (task: TaskItem, nodeId?: string): GoalFronti
export interface BudgetEvaluation {
costLimitReached: boolean;
+ /** ISO deadline from the goal's schedule config; null = uncapped. */
+ deadline: string | null;
+ deadlinePassed: boolean;
roundLimitReached: boolean;
runs: { length: number };
totalCost: number;
@@ -94,6 +97,7 @@ export interface BudgetEvaluation {
export const toBudgetState = (goal: GoalItem, budget: BudgetEvaluation): GoalBudgetState => ({
costLimitReached: budget.costLimitReached,
+ deadlinePassed: budget.deadlinePassed,
maxRounds: goal.maxRounds,
maxTotalCost: goal.maxTotalCost === null ? null : Number(goal.maxTotalCost),
roundLimitReached: budget.roundLimitReached,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/goal.ts b/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
index ddf19041d39..30efd1b3ffc 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
@@ -2,6 +2,7 @@ import {
buildGoalRequirement,
GoalIdentifier,
resolveGoalAttemptBudget,
+ resolveGoalScheduleConfig,
} from '@lobechat/builtin-tool-goal';
import { GoalService } from '@/server/services/goal';
@@ -27,6 +28,7 @@ export const goalRuntime: ServerRuntimeRegistration = {
return {
createGoal: async (args: {
criteria: Array<{ description?: string; instruction?: string; title: string }>;
+ deadline?: string | null;
instruction: string;
maxIterations?: number | null;
maxTotalCost?: number | null;
@@ -41,11 +43,13 @@ export const goalRuntime: ServerRuntimeRegistration = {
try {
const goalService = new GoalService(serverDB, userId, workspaceId ?? undefined);
+ const scheduleConfig = resolveGoalScheduleConfig(args.deadline);
const graph = await goalService.create({
agentId,
createdByAgentId: agentId,
config: {
recovery: { maxAttemptsPerTask: resolveGoalAttemptBudget(args.maxIterations) },
+ ...(scheduleConfig ? { schedule: scheduleConfig } : {}),
},
// `maxIterations` caps attempts on one Work; it is deliberately not
// passed as `maxRounds`, which counts runs across every Work in the
diff --git a/packages/agent-tracing/src/goal/types.ts b/packages/agent-tracing/src/goal/types.ts
index 53b81c98fa4..713d3f8b465 100644
--- a/packages/agent-tracing/src/goal/types.ts
+++ b/packages/agent-tracing/src/goal/types.ts
@@ -131,6 +131,13 @@ export interface FrontierCandidate {
/** Budget as the coordinator read it, not as it looks now. */
export interface GoalBudgetState {
costLimitReached: boolean;
+ /**
+ * The goal's calendar-time budget (config.schedule.deadline), evaluated at
+ * decision time. Time-based stopping is derived, not stored β€” a replay of a
+ * recorded trajectory must see the same verdict the live run saw, so it
+ * travels with the budget rather than being recomputed from the wall clock.
+ */
+ deadlinePassed?: boolean;
maxRounds?: number | null;
maxTotalCost?: number | null;
roundLimitReached: boolean;
diff --git a/packages/builtin-tool-goal/src/client/executor/index.ts b/packages/builtin-tool-goal/src/client/executor/index.ts
index 69abcd1c7ed..9ffc77ebbd8 100644
--- a/packages/builtin-tool-goal/src/client/executor/index.ts
+++ b/packages/builtin-tool-goal/src/client/executor/index.ts
@@ -9,7 +9,11 @@ import { BaseExecutor } from '@lobechat/types';
import { goalService } from '@/services/goal';
-import { buildGoalRequirement, resolveGoalAttemptBudget } from '../../createGoalInput';
+import {
+ buildGoalRequirement,
+ resolveGoalAttemptBudget,
+ resolveGoalScheduleConfig,
+} from '../../createGoalInput';
import { GoalIdentifier } from '../../manifest';
import type { CreateGoalParams } from '../../types';
import { GoalApiName } from '../../types';
@@ -51,11 +55,13 @@ class GoalExecutor extends BaseExecutor<typeof GoalApiName> {
}
try {
+ const scheduleConfig = resolveGoalScheduleConfig(params.deadline);
const graph = await goalService.create({
agentId: ctx.agentId,
createdByAgentId: ctx.agentId,
config: {
recovery: { maxAttemptsPerTask: resolveGoalAttemptBudget(params.maxIterations) },
+ ...(scheduleConfig ? { schedule: scheduleConfig } : {}),
},
// `maxIterations` caps attempts on one Work; it is deliberately not
// passed as `maxRounds`, which counts runs across every Work in the
diff --git a/packages/builtin-tool-goal/src/createGoalInput.test.ts b/packages/builtin-tool-goal/src/createGoalInput.test.ts
index 8ed02e442e3..d650c77aeb7 100644
--- a/packages/builtin-tool-goal/src/createGoalInput.test.ts
+++ b/packages/builtin-tool-goal/src/createGoalInput.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { resolveGoalAttemptBudget } from './createGoalInput';
+import { resolveGoalAttemptBudget, resolveGoalScheduleConfig } from './createGoalInput';
describe('resolveGoalAttemptBudget', () => {
it('leaves the budget unset when the user cleared the field', () => {
@@ -16,3 +16,23 @@ describe('resolveGoalAttemptBudget', () => {
expect(resolveGoalAttemptBudget(99)).toBe(10);
});
});
+
+describe('resolveGoalScheduleConfig', () => {
+ it('leaves the schedule unset when the user cleared the field', () => {
+ expect(resolveGoalScheduleConfig(null)).toBeUndefined();
+ expect(resolveGoalScheduleConfig(undefined)).toBeUndefined();
+ expect(resolveGoalScheduleConfig('')).toBeUndefined();
+ });
+
+ it('normalizes a valid deadline to ISO-8601', () => {
+ const config = resolveGoalScheduleConfig('2026-12-31T23:59:59Z');
+ expect(config?.deadline).toBe('2026-12-31T23:59:59.000Z');
+ });
+
+ it('drops an unparseable deadline instead of storing it', () => {
+ // A deadline that cannot be parsed would either never fire (silently no
+ // budget) or fire immediately (silently paused goal); both hide the
+ // mistake from the user, so it never reaches the config.
+ expect(resolveGoalScheduleConfig('not a date')).toBeUndefined();
+ });
+});
diff --git a/packages/builtin-tool-goal/src/createGoalInput.ts b/packages/builtin-tool-goal/src/createGoalInput.ts
index 6aa0711600e..4683c58491c 100644
--- a/packages/builtin-tool-goal/src/createGoalInput.ts
+++ b/packages/builtin-tool-goal/src/createGoalInput.ts
@@ -3,6 +3,7 @@
* server runtime: both create the same Goal Graph, so the wording the agent and
* the verifier read must not drift between the two paths.
*/
+import type { GoalSchedulePolicy } from '@lobechat/types';
export interface GoalCriterionInput {
description?: string;
@@ -22,6 +23,24 @@ export interface GoalCriterionInput {
export const resolveGoalAttemptBudget = (maxIterations?: number | null): number | undefined =>
typeof maxIterations === 'number' ? Math.min(10, Math.max(2, maxIterations)) : undefined;
+/**
+ * The goal's calendar-time budget, as the schedule config the coordinator reads.
+ *
+ * `null` is the manifest's documented "no user-specified deadline" β€” the cleared
+ * input field β€” and returns `undefined` so the schedule block stays off the
+ * config entirely. An invalid string is dropped rather than stored: a deadline
+ * that cannot be parsed would either never fire (silently no budget) or fire
+ * immediately (silently paused goal), and both hide the mistake from the user.
+ */
+export const resolveGoalScheduleConfig = (
+ deadline?: string | null,
+): GoalSchedulePolicy | undefined => {
+ if (typeof deadline !== 'string' || deadline.trim() === '') return undefined;
+ const parsed = new Date(deadline);
+ if (Number.isNaN(parsed.getTime())) return undefined;
+ return { deadline: parsed.toISOString() };
+};
+
/**
* The goal's acceptance requirement. The Goal Graph models "what counts as
* done" as one authoritative text, which the coordinator folds into every
diff --git a/packages/builtin-tool-goal/src/index.ts b/packages/builtin-tool-goal/src/index.ts
index 571eb13065b..f54729a783b 100644
--- a/packages/builtin-tool-goal/src/index.ts
+++ b/packages/builtin-tool-goal/src/index.ts
@@ -2,6 +2,7 @@ export {
buildGoalRequirement,
type GoalCriterionInput,
resolveGoalAttemptBudget,
+ resolveGoalScheduleConfig,
} from './createGoalInput';
export { isGoalPrompt } from './goalPrompt';
export { GoalIdentifier, GoalManifest } from './manifest';
diff --git a/packages/builtin-tool-goal/src/manifest.ts b/packages/builtin-tool-goal/src/manifest.ts
index 2fa48403542..e6d59c9e3cf 100644
--- a/packages/builtin-tool-goal/src/manifest.ts
+++ b/packages/builtin-tool-goal/src/manifest.ts
@@ -37,6 +37,11 @@ export const GoalManifest: BuiltinToolManifest = {
},
type: 'array',
},
+ deadline: {
+ description:
+ 'Optional ISO-8601 calendar deadline. Past it the coordinator stops dispatching new work and pauses the goal β€” use for long-horizon goals that must conclude by a date. Null means no user-specified deadline.',
+ type: ['string', 'null'],
+ },
instruction: { description: 'Detailed task direction and constraints.', type: 'string' },
maxIterations: {
description:
diff --git a/packages/builtin-tool-task/src/types.ts b/packages/builtin-tool-task/src/types.ts
index 534b87c092d..4410bcd363a 100644
--- a/packages/builtin-tool-task/src/types.ts
+++ b/packages/builtin-tool-task/src/types.ts
@@ -89,6 +89,8 @@ export interface GoalCriterionDraft {
export interface CreateGoalParams {
criteria: GoalCriterionDraft[];
+ /** ISO-8601 calendar-time budget; past it the coordinator stops dispatching. */
+ deadline?: string | null;
instruction: string;
maxIterations?: number | null;
maxTotalCost?: number | null;
diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.ts
index 616eb9b8423..7912de4d4d2 100644
--- a/packages/database/src/models/__tests__/goalGraph.test.ts
+++ b/packages/database/src/models/__tests__/goalGraph.test.ts
@@ -45,7 +45,8 @@ describe('GoalGraphModel', () => {
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']);
+ // Newest first β€” getGraph bounds and orders the trail for the polling UI.
+ expect(graph?.events.map((event) => event.eventType)).toEqual(['linked', 'created', 'created']);
});
it('records who made each transition', async () => {
@@ -238,4 +239,54 @@ describe('GoalGraphModel', () => {
expect(graph?.nodes[0].status).toBe('proposed');
expect(graph?.events).toHaveLength(1);
});
+
+ it('caps the events a graph read carries, newest first', async () => {
+ // The detail page polls getGraph every few seconds; without a limit a
+ // long-horizon goal's payload grew linearly with its age.
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Noisy graph' });
+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Churn' });
+ for (let i = 0; i < GoalGraphModel.GRAPH_EVENT_LIMIT + 5; i++) {
+ await graphModel.updateNodeStatus(goal.id, node!.id, i % 2 ? 'active' : 'waiting');
+ }
+
+ const graph = await graphModel.getGraph(goal.id);
+
+ expect(graph?.events).toHaveLength(GoalGraphModel.GRAPH_EVENT_LIMIT);
+ const createdAt = graph!.events.map((event) => event.createdAt.getTime());
+ expect([...createdAt].sort((a, b) => b - a)).toEqual(createdAt);
+ expect(graph!.events[0].eventType).toBe('updated');
+ });
+
+ it('records a goal-level status transition as a system-attributed event', async () => {
+ // The lifecycle event types existed in the schema but nothing wrote them,
+ // so a goal's planning β†’ running β†’ paused path left no trace at all.
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Status trail' });
+ const coordinator = new GoalGraphModel(serverDB, userId, undefined, {
+ id: GOAL_COORDINATOR_ACTOR_ID,
+ type: 'system',
+ });
+
+ await coordinator.recordGoalStatus(goal.id, 'planning', 'running');
+ await coordinator.recordGoalStatus(goal.id, 'running', 'paused', 'nothing ready');
+ // A same-status write is a no-op β€” re-stamping would flood the timeline.
+ await coordinator.recordGoalStatus(goal.id, 'paused', 'paused');
+
+ const events = (await graphModel.getGraph(goal.id))!.events.filter(
+ (event) => event.entityType === 'goal',
+ );
+
+ expect(events).toHaveLength(2);
+ // Newest first: [1] is the earlier activation, [0] the later pause.
+ expect(events[1]).toMatchObject({
+ actorId: GOAL_COORDINATOR_ACTOR_ID,
+ actorType: 'system',
+ entityId: goal.id,
+ eventType: 'activated',
+ reason: 'status planning β†’ running',
+ });
+ expect(events[0]).toMatchObject({
+ eventType: 'updated',
+ reason: 'nothing ready',
+ });
+ });
});
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 8f1593d649f..705ba4c2d7c 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -10,8 +10,9 @@ import type {
GoalNodeKind,
GoalNodeStatus,
GoalNodeWorkVersionRelation,
+ GoalStatus,
} from '@lobechat/types';
-import { and, asc, count, eq, inArray, isNull, lt, or, sql } from 'drizzle-orm';
+import { and, asc, count, desc, eq, inArray, isNull, lt, or, sql } from 'drizzle-orm';
import { goals } from '../schemas/goal';
import {
@@ -123,7 +124,8 @@ export class GoalGraphModel {
.select()
.from(goalEvents)
.where(eq(goalEvents.goalId, goalId))
- .orderBy(asc(goalEvents.createdAt)),
+ .orderBy(desc(goalEvents.createdAt))
+ .limit(GoalGraphModel.GRAPH_EVENT_LIMIT),
this.db
.select({ link: goalNodeWorkVersions })
.from(goalNodeWorkVersions)
@@ -142,6 +144,57 @@ export class GoalGraphModel {
};
};
+ /**
+ * How many events one graph read carries.
+ *
+ * `getGraph` backs both the coordinator (which never reads events) and the
+ * detail page (which polls it every few seconds and renders the most recent
+ * lifecycle entries), so the read has to be bounded: a long-horizon goal
+ * accumulates events for months and an unbounded query made every poll's
+ * payload β€” and the client's rebuild cost β€” grow linearly with goal age.
+ * Newest wins: the audit trail's full history stays queryable in the
+ * database, and the trajectory (`lh trace goal`) already records decisions
+ * with more fidelity than these events ever carried.
+ */
+ static readonly GRAPH_EVENT_LIMIT = 200;
+
+ /**
+ * Record a goal-level lifecycle transition as an event.
+ *
+ * `goal_events` carries `entity_type = 'goal'` and the lifecycle event types
+ * (`activated`, `resolved`, `rejected`, `retired`) for exactly this, but no
+ * writer used them β€” a goal's planning β†’ running β†’ paused β†’ achieved moves
+ * were invisible on its own timeline, only node transitions ever got one.
+ * Called alongside the row update in `GoalService.transitionStatus`; kept
+ * separate because the `goals` row update lives on `GoalModel` and must not
+ * depend on this model's actor.
+ */
+ recordGoalStatus = async (
+ goalId: string,
+ from: GoalStatus,
+ to: GoalStatus,
+ reason?: string,
+ ): Promise<void> => {
+ if (from === to) return;
+ const eventType: GoalEventType =
+ to === 'running'
+ ? 'activated'
+ : to === 'achieved'
+ ? 'resolved'
+ : to === 'failed' || to === 'canceled'
+ ? 'rejected'
+ : 'updated';
+ await this.db.insert(goalEvents).values({
+ actorId: this.actor?.id ?? this.userId,
+ actorType: this.actor?.type ?? 'user',
+ entityId: goalId,
+ entityType: 'goal',
+ eventType,
+ goalId,
+ reason: reason ?? `status ${from} β†’ ${to}`,
+ });
+ };
+
attachWorkVersion = async (
goalId: string,
nodeId: string,
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 70a143bd723..cb667248be6 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -31,6 +31,20 @@ export interface GoalRecoveryPolicy {
operationLeaseTimeoutMs?: number;
}
+/**
+ * Calendar-time bounds for a long-horizon goal. Lives on the JSONB `config`
+ * column deliberately: attempts, rounds and dollars measure one agent run,
+ * but a goal that runs for months also needs "stop trying by this date" as a
+ * first-class budget unit, and that needs no schema of its own.
+ */
+export interface GoalSchedulePolicy {
+ /**
+ * ISO-8601 instant. Past it the coordinator stops dispatching new Work and
+ * pauses the goal β€” the temporal twin of `budget_exhausted`.
+ */
+ deadline?: string | null;
+}
+
export interface GoalConfig {
/**
* How many of a goal's Tasks may be in flight at once. Independent Tasks are
@@ -40,6 +54,7 @@ export interface GoalConfig {
*/
maxConcurrentTasks?: number | null;
recovery?: GoalRecoveryPolicy;
+ schedule?: GoalSchedulePolicy;
}
/**
diff --git a/src/services/goal.ts b/src/services/goal.ts
index 14ae26a6a36..68902c63d62 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -77,6 +77,7 @@ class GoalService {
}) => lambdaClient.goal.decide.mutate(params);
setBudget = async (params: {
+ deadline?: string | null;
id: string;
maxRounds?: number | null;
maxTotalCost?: number | null;
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index ccf89de1864..8721d140b67 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -114,7 +114,11 @@ export class GoalActionImpl {
setGoalBudget = async (
goalId: string,
- budget: { maxRounds?: number | null; maxTotalCost?: number | null },
+ budget: {
+ deadline?: string | null;
+ maxRounds?: number | null;
+ maxTotalCost?: number | null;
+ },
): Promise<void> => {
await goalService.setBudget({ id: goalId, ...budget });
await this.refreshGoalGraph(goalId);