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): parallel task scheduling, trace fixes and CLI 0.0.51 (#18944)

Arvin Xu66c0a001beec
diff --git a/apps/cli/man/man1/lh.1 b/apps/cli/man/man1/lh.1
index 9e7c7541aa1..9005e6262b4 100644
--- a/apps/cli/man/man1/lh.1
+++ b/apps/cli/man/man1/lh.1
@@ -1,6 +1,6 @@
.\" Code generated by `npm run man:generate`; DO NOT EDIT.
.\" Manual command details come from the Commander command tree.
-.TH LH 1 "" "@lobehub/cli 0.0.50" "User Commands"
+.TH LH 1 "" "@lobehub/cli 0.0.51" "User Commands"
.SH NAME
lh \- LobeHub CLI \- manage and connect to LobeHub services
.SH SYNOPSIS
@@ -87,7 +87,7 @@ Run long\-horizon Goal Graphs
Manage files
.TP
.B hetero
-Run heterogeneous agent CLIs (Amp / Claude Code / CodeBuddy / Codex / Cursor / Grok Build / Kimi Code / OpenCode / Pi / Qoder / TRAE CLI) and stream their output
+Run heterogeneous agent CLIs (Amp / Claude Code / CodeBuddy / Codex / Cursor / Factory Droid / Grok Build / Kimi Code / OpenCode / Pi / Qoder / TRAE CLI) and stream their output
.TP
.B skill
Manage agent skills
diff --git a/apps/cli/package.json b/apps/cli/package.json
index b26916ef3d0..fb0dfcc0ecc 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@lobehub/cli",
- "version": "0.0.50",
+ "version": "0.0.51",
"type": "module",
"bin": {
"lh": "./dist/index.js",
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.ts
index fc7427ed716..40a5c824d58 100644
--- a/apps/cli/src/commands/goal.test.ts
+++ b/apps/cli/src/commands/goal.test.ts
@@ -6,6 +6,7 @@ import { registerGoalCommand } from './goal';
const { mockClient } = vi.hoisted(() => ({
mockClient: {
goal: {
+ create: { mutate: vi.fn() },
graph: { query: vi.fn() },
tick: { mutate: vi.fn() },
},
@@ -13,6 +14,13 @@ const { mockClient } = vi.hoisted(() => ({
}));
vi.mock('../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));
+// Building the app URL otherwise resolves a workspace and a server, which needs
+// a real login; the link's shape is what this file is asserting, not its host.
+vi.mock('./task/url', () => ({
+ resolveAppUrlBuilder: vi
+ .fn()
+ .mockResolvedValue((pathname: string) => `https://app.lobehub.com${pathname}`),
+}));
const createProgram = () => {
const program = new Command();
program.exitOverride();
@@ -153,3 +161,36 @@ describe('goal show command', () => {
expect(await render()).toContain('task_8A1DyvjIc7PL');
});
});
+
+describe('goal create command', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ it('links to the created goal rather than to /goal/undefined', async () => {
+ // `goal.create` returns the whole graph snapshot, so the id lives on its
+ // goal. Reading `data.id` printed a link nobody could follow, and the CLI
+ // cannot resolve the router's types to catch it.
+ mockClient.goal.create.mutate.mockResolvedValue({
+ data: {
+ decisions: [],
+ edges: [],
+ events: [],
+ goal: { id: 'goal_PrUIwfSnU9TH', requirement: null, status: 'planning', title: 'Fix bugs' },
+ nodes: [],
+ workVersions: [],
+ },
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'goal', 'create', 'Fix bugs']);
+
+ const output = vi
+ .mocked(console.log)
+ .mock.calls.map(([value]) => (value === undefined ? '' : String(value)))
+ .join('\n');
+
+ expect(output).toContain('https://app.lobehub.com/goal/goal_PrUIwfSnU9TH');
+ expect(output).not.toContain('/goal/undefined');
+ });
+});
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index 4f1ccb5b61b..f67e393093f 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -92,6 +92,11 @@ export function registerGoalCommand(program: Command) {
.option('--max-rounds <n>', 'Maximum goal rounds')
.option('--max-cost <usd>', 'Maximum total cost in USD')
.option('--max-attempts-per-work <n>', 'Attempts per Work before opening a decision gate')
+ .option(
+ '--max-concurrent-tasks <n>',
+ "How many of this goal's tasks may run at once (default 3)",
+ )
+
.option('--max-steps-per-run <n>', 'Optional agent step cap per Work run (for example 500)')
.option(
'--operation-lease-timeout-ms <n>',
@@ -104,8 +109,14 @@ export function registerGoalCommand(program: Command) {
const result = await client.goal.create.mutate({
agentId: options.agent,
config:
- options.maxAttemptsPerTask || options.maxStepsPerRun || options.operationLeaseTimeoutMs
+ options.maxAttemptsPerTask ||
+ options.maxStepsPerRun ||
+ options.operationLeaseTimeoutMs ||
+ options.maxConcurrentTasks
? {
+ maxConcurrentTasks: options.maxConcurrentTasks
+ ? Number.parseInt(options.maxConcurrentTasks, 10)
+ : undefined,
recovery: {
maxAttemptsPerTask: options.maxAttemptsPerTask
? Number.parseInt(options.maxAttemptsPerTask, 10)
@@ -127,7 +138,10 @@ export function registerGoalCommand(program: Command) {
title,
work: options.work,
});
- const url = buildUrl(`/goal/${encodeURIComponent(result.data.id)}`);
+ // `goal.create` returns the whole graph snapshot, so the id is on its
+ // goal β€” `result.data.id` is undefined, and the CLI cannot resolve the
+ // router's types to catch that, which is how it reached a printed URL.
+ const url = buildUrl(`/goal/${encodeURIComponent(result.data.goal.id)}`);
if (options.json !== undefined) return outputJson({ ...result.data, url }, options.json);
printGraph(result.data);
console.log(`${pc.bold('goal')}: ${url}`);
diff --git a/apps/server/src/modules/GoalTracing/S3GoalTraceStore.ts b/apps/server/src/modules/GoalTracing/S3GoalTraceStore.ts
index 3aeb1d94a8d..92abfc7e815 100644
--- a/apps/server/src/modules/GoalTracing/S3GoalTraceStore.ts
+++ b/apps/server/src/modules/GoalTracing/S3GoalTraceStore.ts
@@ -23,6 +23,14 @@ const ZSTD_CONTENT_TYPE = 'application/zstd';
export const buildGoalTraceKey = (goalId: string): string =>
`${TRACE_PREFIX}/${goalId}${TRAJECTORY_SUFFIX}`;
+/**
+ * Where an in-progress trajectory lives. A long-horizon goal is a partial for
+ * nearly all of its life, so this is the object a reader wants most of the
+ * time β€” the finalized key only exists once the goal is terminal.
+ */
+export const buildGoalTracePartialKey = (goalId: string): string =>
+ `${TRACE_PREFIX}/_partial/${goalId}${TRAJECTORY_SUFFIX}`;
+
/**
* S3-backed goal trajectories.
*
@@ -43,7 +51,7 @@ export class S3GoalTraceStore implements IGoalTraceStore {
}
private partialKey(goalId: string): string {
- return `${TRACE_PREFIX}/_partial/${goalId}${TRAJECTORY_SUFFIX}`;
+ return buildGoalTracePartialKey(goalId);
}
private async encode(value: unknown): Promise<Buffer> {
diff --git a/apps/server/src/modules/GoalTracing/index.ts b/apps/server/src/modules/GoalTracing/index.ts
index f95b93fbcf5..d83a4fa580e 100644
--- a/apps/server/src/modules/GoalTracing/index.ts
+++ b/apps/server/src/modules/GoalTracing/index.ts
@@ -1 +1 @@
-export { buildGoalTraceKey, S3GoalTraceStore } from './S3GoalTraceStore';
+export { buildGoalTraceKey, buildGoalTracePartialKey, S3GoalTraceStore } from './S3GoalTraceStore';
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 50105ff1af0..50b1d5dd82a 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -103,6 +103,9 @@ export const goalRouter = router({
createdByAgentId: z.string().optional(),
config: z
.object({
+ // Bounds mirror `resolveMaxConcurrentTasks`, so a rejected value and
+ // a clamped one cannot disagree about what the cap may be.
+ maxConcurrentTasks: z.number().int().min(1).max(10).nullable().optional(),
recovery: z
.object({
maxAttemptsPerTask: z.number().int().positive().optional(),
diff --git a/apps/server/src/services/goal/advanceGoal.test.ts b/apps/server/src/services/goal/advanceGoal.test.ts
index e35fa3bf68c..2f274ef78c9 100644
--- a/apps/server/src/services/goal/advanceGoal.test.ts
+++ b/apps/server/src/services/goal/advanceGoal.test.ts
@@ -201,7 +201,10 @@ describe('advanceGoal trajectory recording', () => {
finalStatus: null,
goalId: 'goal-1',
ticksTotal: 1,
- traceS3Key: 'goal-traces/goal-1.json.zst',
+ // The partial, because that is the object that exists while the goal
+ // runs. Pointing at the finalized key here made `hasTrace` a lie and
+ // had the server sign a URL that 404s until the goal was over.
+ traceS3Key: 'goal-traces/_partial/goal-1.json.zst',
// The column name, not the rollup's. Pinned so the mapping in
// `writeObservationRow` cannot drift silently.
workOperations: 1,
@@ -222,6 +225,13 @@ describe('advanceGoal trajectory recording', () => {
expect(state.saved).toMatchObject({ completionReason: 'achieved', totalAdvances: 1 });
expect(state.partial).toBeUndefined();
+ // And the row follows the object: the partial is gone, so the key moves.
+ expect(mocks.upsert).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ finalStatus: 'achieved',
+ traceS3Key: 'goal-traces/goal-1.json.zst',
+ }),
+ );
});
it('leaves the trajectory open for a goal that is merely parked', async () => {
diff --git a/apps/server/src/services/goal/advanceGoal.ts b/apps/server/src/services/goal/advanceGoal.ts
index 7c3632e4651..254c630f14d 100644
--- a/apps/server/src/services/goal/advanceGoal.ts
+++ b/apps/server/src/services/goal/advanceGoal.ts
@@ -25,9 +25,10 @@ const STOP_OUTCOMES = new Set<GoalTickOutcome>([
]);
/**
- * Safety limit for one advance. Dispatching a Work takes two ticks, so a
- * healthy run is a handful; anything near this is a loop that is not
- * converging, and the sweep will come back to it.
+ * Safety limit for one advance. Dispatching a Task takes two ticks and an
+ * advance now fills every free concurrency slot, so a healthy run is a
+ * handful; anything near this is a loop that is not converging, and the sweep
+ * will come back to it.
*/
export const MAX_TICKS_PER_ADVANCE = 20;
diff --git a/apps/server/src/services/goal/decideNextMove.test.ts b/apps/server/src/services/goal/decideNextMove.test.ts
index 4b2cd7848e0..eb370d02550 100644
--- a/apps/server/src/services/goal/decideNextMove.test.ts
+++ b/apps/server/src/services/goal/decideNextMove.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import {
decideNextMove,
+ frontierNeedsBudget,
GOAL_ACCEPTANCE_TASK_TITLE,
LEASE_EXPIRED_ERROR,
needsBudget,
@@ -36,12 +37,30 @@ const graph = (overrides: Partial<GoalGraphSnapshot> = {}): GoalGraphSnapshot =>
const task = (overrides: Partial<TaskItem> = {}): TaskItem =>
({ error: null, id: 'task_1', identifier: 'T-1', status: 'backlog', ...overrides }) as TaskItem;
+/**
+ * `frontierTask` is the old single-node shape these tests were written
+ * against; it is expressed as the one-entry task map the scheduler now takes,
+ * so the existing cases keep reading as "this node, this task".
+ */
const decide = (
snapshot: GoalGraphSnapshot,
- extra: Parameters<typeof decideNextMove>[0] extends infer T
- ? Partial<Omit<T & object, 'graph' | 'frontier'>>
- : never = {},
-) => decideNextMove({ frontier: selectFrontier(snapshot), graph: snapshot, ...extra });
+ extra: {
+ budget?: Parameters<typeof decideNextMove>[0]['budget'];
+ concurrency?: number;
+ frontierTask?: TaskItem | null;
+ tasks?: TaskItem[];
+ } = {},
+) => {
+ const { budget, concurrency = 3, frontierTask, tasks } = extra;
+ const listed = tasks ?? (frontierTask ? [frontierTask] : []);
+ return decideNextMove({
+ budget,
+ concurrency,
+ frontier: selectFrontier(snapshot),
+ graph: snapshot,
+ tasksById: new Map(listed.map((item) => [item.id, item])),
+ });
+};
describe('selectFrontier', () => {
it('ranks by priority, then by creation order', () => {
@@ -274,3 +293,126 @@ describe('needsBudget', () => {
expect(needsBudget(null)).toBe(false);
});
});
+
+describe('decideNextMove concurrency', () => {
+ const independent = (count: number) =>
+ graph({
+ nodes: Array.from({ length: count }, (_, index) =>
+ node(`n${index}`, { createdAt: new Date(1000 + index) }),
+ ),
+ });
+
+ it('moves past a running task to start an independent one', () => {
+ // The whole point: four fixes that share no code should not queue behind
+ // each other. The old frontier stopped at its head, saw it running, and
+ // ended the advance.
+ const snapshot = graph({
+ nodes: [node('a', { taskId: 'task_1' }), node('b'), node('c')],
+ });
+
+ expect(decide(snapshot, { tasks: [task({ id: 'task_1', status: 'running' })] })).toMatchObject({
+ branch: 'create_task',
+ chosenNodeId: 'b',
+ });
+ });
+
+ it('stops once the concurrency limit is reached', () => {
+ const snapshot = graph({
+ nodes: [node('a', { taskId: 'task_1' }), node('b', { taskId: 'task_2' }), node('c')],
+ });
+
+ const move = decide(snapshot, {
+ concurrency: 2,
+ tasks: [task({ id: 'task_1', status: 'running' }), task({ id: 'task_2', status: 'running' })],
+ });
+
+ expect(move).toMatchObject({ branch: 'task_running', outcome: 'waiting_external' });
+ expect(move.message).toContain('concurrency limit of 2');
+ });
+
+ it('fills the remaining slots rather than only the first', () => {
+ // Dispatching reports `advanced`, so the advance loop keeps going and the
+ // next tick picks the next idle node.
+ const move = decide(independent(4), {
+ concurrency: 3,
+ tasks: [task({ id: 'task_1', status: 'running' })],
+ });
+
+ expect(move.outcome).toBe('advanced');
+ });
+
+ it('does not let a paused task block independent work', () => {
+ const snapshot = graph({ nodes: [node('a', { taskId: 'task_1' }), node('b')] });
+
+ expect(decide(snapshot, { tasks: [task({ id: 'task_1', status: 'paused' })] })).toMatchObject({
+ branch: 'create_task',
+ chosenNodeId: 'b',
+ });
+ });
+
+ it('reports the human wait only when every ready task is parked', () => {
+ const snapshot = graph({ nodes: [node('a', { taskId: 'task_1' })] });
+
+ expect(decide(snapshot, { tasks: [task({ id: 'task_1', status: 'paused' })] })).toMatchObject({
+ branch: 'task_paused',
+ outcome: 'waiting_human',
+ });
+ });
+
+ it('still respects dependencies when running in parallel', () => {
+ const snapshot = graph({
+ edges: [
+ { id: 'e1', kind: 'depends_on', sourceNodeId: 'b', targetNodeId: 'a' },
+ ] as GoalGraphSnapshot['edges'],
+ nodes: [node('a', { taskId: 'task_1' }), node('b')],
+ });
+
+ // `a` is running and `b` depends on it, so there is nothing else to start.
+ expect(decide(snapshot, { tasks: [task({ id: 'task_1', status: 'running' })] })).toMatchObject({
+ branch: 'task_running',
+ outcome: 'waiting_external',
+ });
+ });
+});
+
+describe('frontierNeedsBudget', () => {
+ const withTasks = (snapshot: GoalGraphSnapshot, tasks: TaskItem[]) =>
+ frontierNeedsBudget(selectFrontier(snapshot), new Map(tasks.map((item) => [item.id, item])));
+
+ it('is true when a later candidate can start even though the head cannot', () => {
+ // The hole parallelism opened: the head is running and needs no budget, so
+ // asking only the head would skip the budget read entirely β€” and
+ // `budget_exhausted` can only fire on a budget that was read.
+ const snapshot = graph({ nodes: [node('a', { taskId: 'task_1' }), node('b')] });
+
+ expect(withTasks(snapshot, [task({ id: 'task_1', status: 'running' })])).toBe(true);
+ });
+
+ it('is false when nothing unblocked could start paid work', () => {
+ const snapshot = graph({ nodes: [node('a', { taskId: 'task_1' })] });
+
+ expect(withTasks(snapshot, [task({ id: 'task_1', status: 'running' })])).toBe(false);
+ expect(withTasks(snapshot, [task({ id: 'task_1', status: 'completed' })])).toBe(false);
+ });
+
+ it('is true for a retryable failure, which spends money too', () => {
+ const snapshot = graph({ nodes: [node('a', { taskId: 'task_1' })] });
+
+ expect(
+ withTasks(snapshot, [
+ task({ error: VERIFICATION_FAILED_ERROR, id: 'task_1', status: 'paused' }),
+ ]),
+ ).toBe(true);
+ });
+
+ it('ignores blocked candidates', () => {
+ const snapshot = graph({
+ edges: [
+ { id: 'e1', kind: 'depends_on', sourceNodeId: 'b', targetNodeId: 'a' },
+ ] as GoalGraphSnapshot['edges'],
+ nodes: [node('a', { taskId: 'task_1' }), node('b')],
+ });
+
+ expect(withTasks(snapshot, [task({ id: 'task_1', status: 'running' })])).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.ts
index afa90c69a94..5f4a24bb7dd 100644
--- a/apps/server/src/services/goal/decideNextMove.ts
+++ b/apps/server/src/services/goal/decideNextMove.ts
@@ -15,9 +15,12 @@ export const VERIFICATION_FAILED_ERROR = 'Delivery did not pass verification.';
const TERMINAL_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired']);
export interface FrontierSelection {
- /** Every eligible work node, best first. */
+ /** Every eligible task node, best first β€” the trace-shaped view. */
candidates: FrontierCandidate[];
+ /** The first unblocked node, kept for callers that only need the head. */
chosen?: GoalGraphNode;
+ /** The same ranking, carrying the nodes the scheduler has to walk. */
+ eligible: Array<{ blockedBy: string[]; node: GoalGraphNode }>;
}
/**
@@ -60,6 +63,7 @@ export const selectFrontier = (graph: GoalGraphSnapshot): FrontierSelection => {
title: node.title,
})),
chosen: eligible.find(({ blockedBy }) => blockedBy.length === 0)?.node,
+ eligible,
};
};
@@ -72,21 +76,59 @@ export const selectFrontier = (graph: GoalGraphSnapshot): FrontierSelection => {
* every sweep.
*/
export const needsBudget = (task?: TaskItem | null): boolean => {
- if (!task) return false;
- return !['completed', 'failed', 'canceled', 'paused', 'running', 'scheduled'].includes(
- task.status,
- );
+ // A candidate with no task yet will need one created and then dispatched.
+ if (task === undefined) return true;
+ if (task === null) return false;
+ // A failure the coordinator can retry spends money too.
+ if (task.status === 'paused') {
+ return task.error === LEASE_EXPIRED_ERROR || task.error === VERIFICATION_FAILED_ERROR;
+ }
+ return !['completed', 'failed', 'canceled', 'running', 'scheduled'].includes(task.status);
};
+/**
+ * Whether *any* unblocked candidate could start paid work this tick.
+ *
+ * Asking only about the frontier's head was safe while the head was the only
+ * thing that could be dispatched. Now that the scheduler walks past a running
+ * head to start an independent task, keying the budget off the head would let a
+ * goal spend past `maxRounds` / `maxTotalCost`: the head reports "no budget
+ * needed", the budget is never read, and `budget_exhausted` cannot fire.
+ */
+export const frontierNeedsBudget = (
+ frontier: FrontierSelection,
+ tasksById: Map<string, TaskItem>,
+): boolean =>
+ frontier.eligible.some(({ blockedBy, node }) => {
+ if (blockedBy.length > 0) return false;
+ if (!node.taskId) return true;
+ return needsBudget(tasksById.get(node.taskId) ?? null);
+ });
+
export interface GoalMoveInput {
/** Required only when {@link needsBudget} says the branch could dispatch. */
budget?: GoalBudgetState;
+ /** How many of this goal's Tasks may be in flight at once. */
+ concurrency: number;
frontier: FrontierSelection;
- /** The chosen work node's responsible task, when it already has one. */
- frontierTask?: TaskItem | null;
graph: GoalGraphSnapshot;
+ /**
+ * The responsible Task of every candidate that has one, keyed by task id.
+ * A candidate whose task id is absent from the map has lost its row.
+ */
+ tasksById: Map<string, TaskItem>;
}
+/** Task statuses that occupy a concurrency slot. */
+const IN_FLIGHT_STATUSES = new Set(['running', 'scheduled']);
+
+/**
+ * Whether this candidate is one the coordinator is already waiting on, and so
+ * neither actionable nor a reason to stop looking at the others.
+ */
+const isInFlight = (task: TaskItem | undefined): boolean =>
+ Boolean(task && IN_FLIGHT_STATUSES.has(task.status));
+
export interface GoalMove {
branch: GoalTickBranch;
candidates: FrontierCandidate[];
@@ -100,6 +142,8 @@ export interface GoalMove {
* which is why the trace records the actual outcome separately.
*/
outcome: GoalTickOutcome;
+ /** The responsible task this move is about, when it has one. */
+ taskId?: string;
}
/**
@@ -113,9 +157,10 @@ export interface GoalMove {
*/
export const decideNextMove = ({
budget,
+ concurrency,
frontier,
- frontierTask,
graph,
+ tasksById,
}: GoalMoveInput): GoalMove => {
const { candidates, chosen } = frontier;
const base = { candidates, chosenNodeId: chosen?.id };
@@ -151,18 +196,108 @@ export const decideNextMove = ({
};
}
+ // Walk the whole ranked frontier rather than stopping at its head. Four bug
+ // fixes that share no code have no reason to run one after another, and the
+ // old single-node frontier made them: the running node stayed eligible, was
+ // re-picked every tick, and reported `waiting_external`, which ends the
+ // advance before anything behind it is even considered.
+ const inFlight = graph.nodes.filter(
+ (node) => node.kind === 'task' && isInFlight(tasksById.get(node.taskId ?? '')),
+ ).length;
+
+ let parked = false;
+ let capacityBlocked = false;
+ let waitingOn: { node: GoalGraphNode; task: TaskItem } | undefined;
+
+ for (const candidate of frontier.eligible) {
+ if (candidate.blockedBy.length > 0) continue;
+
+ const task = candidate.node.taskId ? tasksById.get(candidate.node.taskId) : undefined;
+ if (isInFlight(task)) {
+ waitingOn ??= { node: candidate.node, task: task! };
+ continue;
+ }
+
+ const move = decideForCandidate({
+ budget,
+ capacity: inFlight < concurrency,
+ candidates,
+ graph,
+ node: candidate.node,
+ task: candidate.node.taskId ? (task ?? null) : undefined,
+ });
+
+ if (move === 'needs-capacity') {
+ capacityBlocked = true;
+ continue;
+ }
+ if (move === 'parked') {
+ parked = true;
+ continue;
+ }
+ return move;
+ }
+
if (!chosen) return decideWithoutFrontier(graph, candidates);
- if (!chosen.taskId) {
+ // Everything eligible is either running, parked on a person, or waiting for a
+ // slot. Report which, so the row does not read as stalled when it is simply
+ // saturated.
+ if (waitingOn || capacityBlocked) {
+ return {
+ ...base,
+ branch: 'task_running',
+ chosenNodeId: waitingOn?.node.id ?? base.chosenNodeId,
+ message: capacityBlocked
+ ? `${inFlight} task(s) running at the concurrency limit of ${concurrency}`
+ : `Task ${waitingOn!.task.identifier} is ${waitingOn!.task.status}`,
+ outcome: 'waiting_external',
+ taskId: waitingOn?.task.id,
+ };
+ }
+ if (parked) {
+ return {
+ ...base,
+ branch: 'task_paused',
+ message: 'Every ready task is paused',
+ outcome: 'waiting_human',
+ };
+ }
+
+ return decideWithoutFrontier(graph, candidates);
+};
+
+/** What one candidate wants, or why it cannot be acted on right now. */
+type CandidateMove = GoalMove | 'needs-capacity' | 'parked';
+
+const decideForCandidate = ({
+ budget,
+ capacity,
+ candidates,
+ graph,
+ node,
+ task,
+}: {
+ budget?: GoalBudgetState;
+ capacity: boolean;
+ candidates: FrontierCandidate[];
+ graph: GoalGraphSnapshot;
+ node: GoalGraphNode;
+ task: TaskItem | null | undefined;
+}): CandidateMove => {
+ const base = { candidates, chosenNodeId: node.id };
+
+ if (task === undefined) {
+ if (!capacity) return 'needs-capacity';
return {
...base,
branch: 'create_task',
- message: `Work "${chosen.title}" has no responsible task yet`,
+ message: `Task "${node.title}" has no responsible task yet`,
outcome: 'advanced',
};
}
- if (!frontierTask) {
+ if (task === null) {
return {
...base,
branch: 'missing_task',
@@ -171,7 +306,7 @@ export const decideNextMove = ({
};
}
- return decideForTask(base, frontierTask, budget, graph);
+ return decideForTask(base, task, budget, graph, capacity);
};
const decideWithoutFrontier = (
@@ -237,7 +372,8 @@ const decideForTask = (
task: TaskItem,
budget: GoalBudgetState | undefined,
graph: GoalGraphSnapshot,
-): GoalMove => {
+ capacity = true,
+): CandidateMove => {
if (task.status === 'completed') {
return {
...base,
@@ -253,6 +389,7 @@ const decideForTask = (
(task.status === 'paused' && task.error)
) {
if (task.status === 'paused' && task.error === LEASE_EXPIRED_ERROR) {
+ if (!capacity) return 'needs-capacity';
return {
...base,
branch: 'recover_lease',
@@ -261,6 +398,7 @@ const decideForTask = (
};
}
if (task.status === 'paused' && task.error === VERIFICATION_FAILED_ERROR) {
+ if (!capacity) return 'needs-capacity';
return {
...base,
branch: 'recover_verification',
@@ -276,23 +414,12 @@ const decideForTask = (
};
}
- if (task.status === 'paused') {
- return {
- ...base,
- branch: 'task_paused',
- message: `Task ${task.identifier} is paused`,
- outcome: 'waiting_human',
- };
- }
+ // Parked on a person, and holding no slot. The goal has other work.
+ if (task.status === 'paused') return 'parked';
- if (task.status === 'running' || task.status === 'scheduled') {
- return {
- ...base,
- branch: 'task_running',
- message: `Task ${task.identifier} is ${task.status}`,
- outcome: 'waiting_external',
- };
- }
+ // Callers filter these out before they get here; kept so the classification
+ // stays total if a status slips through.
+ if (task.status === 'running' || task.status === 'scheduled') return 'parked';
if (budget?.roundLimitReached || budget?.costLimitReached) {
return {
@@ -305,10 +432,14 @@ const decideForTask = (
};
}
+ if (!capacity) return 'needs-capacity';
+
+ // Dispatching is progress, not a stopping point: the advance should carry on
+ // and fill the remaining slots rather than end after starting one Task.
return {
...base,
branch: 'dispatch_task',
message: `Task ${task.identifier} is ready to run`,
- outcome: 'waiting_external',
+ outcome: 'advanced',
};
};
diff --git a/apps/server/src/services/goal/goalTraceRecorder.ts b/apps/server/src/services/goal/goalTraceRecorder.ts
index 720173b5a43..6ab67d41d0c 100644
--- a/apps/server/src/services/goal/goalTraceRecorder.ts
+++ b/apps/server/src/services/goal/goalTraceRecorder.ts
@@ -12,7 +12,7 @@ import { sql } from 'drizzle-orm';
import { GoalTraceModel } from '@/database/models/goalTrace';
import type { LobeChatDatabase } from '@/database/type';
-import { buildGoalTraceKey } from '@/server/modules/GoalTracing';
+import { buildGoalTraceKey, buildGoalTracePartialKey } from '@/server/modules/GoalTracing';
import type { GoalTickObservation } from './traceObservation';
import { createDefaultGoalTraceStore } from './traceStore';
@@ -136,7 +136,13 @@ export class GoalAdvanceRecorder {
startedAt: new Date(rollup.startedAt),
ticksByBranch: rollup.ticksByBranch,
ticksTotal: rollup.ticksTotal,
- traceS3Key: buildGoalTraceKey(this.goalId),
+ // Whichever object exists *now*. Writing the finalized key from the
+ // first advance made `hasTrace` a lie for every running goal and had the
+ // server sign a URL that 404s β€” so a goal could not be inspected until it
+ // was over, which is the opposite of the intent.
+ traceS3Key: trajectory.completionReason
+ ? buildGoalTraceKey(this.goalId)
+ : buildGoalTracePartialKey(this.goalId),
workOperations: rollup.operationsTotal,
// Columns kept as shipped. The node kind is now `task`, but renaming
// three columns on a live table buys nothing the reporting names above
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 209d672385f..781e7a352cc 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -576,6 +576,36 @@ describe('GoalService', () => {
);
});
+ it('refuses to start a task once the goal is at its concurrency limit', async () => {
+ // The planner's cap check is a fast path over a snapshot; two overlapping
+ // advances can both read it below the limit. The count and the claim are
+ // therefore taken together under a per-goal lock, and this is the assertion
+ // that the enforcement β€” not the fast path β€” is what holds.
+ const runSpy = vi
+ .spyOn(TaskRunnerService.prototype, 'runTask')
+ .mockResolvedValue({ operationId: 'op-cap', taskId: 'placeholder' } as never);
+
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ config: { maxConcurrentTasks: 1 },
+ title: 'Capped goal',
+ work: ['First', 'Second'],
+ });
+
+ // Fill the single slot.
+ const first = await service.tick(graph.goal.id);
+ await service.tick(graph.goal.id);
+ await taskModel.updateStatus(first.taskId!, 'running');
+ runSpy.mockClear();
+
+ // The second task exists and is unblocked, but there is no room for it.
+ const capped = await service.tick(graph.goal.id);
+
+ expect(capped.outcome).toBe('waiting_external');
+ expect(runSpy).not.toHaveBeenCalled();
+ });
+
it('automatically retries failed Work verification within policy budget', async () => {
const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({
agentId: 'agent-recovery',
@@ -743,6 +773,27 @@ describe('GoalService', () => {
});
});
+ it('starts ready sibling Work even when a running Task row is older than the operation lease', async () => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },
+ title: 'Keep parallel work moving',
+ work: ['Long-running experiment', 'Independent analysis'],
+ });
+ const running = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(running.taskId!, 'running');
+ await serverDB
+ .update(tasks)
+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })
+ .where(eq(tasks.id, running.taskId!));
+
+ const sibling = await service.tick(graph.goal.id);
+
+ expect(sibling).toMatchObject({ outcome: 'advanced' });
+ expect(sibling.taskId).not.toBe(running.taskId);
+ });
+
it('rolls back the operation reclaim when recovery bookkeeping fails', async () => {
vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([
{ operationId: 'op-atomic-recovery', topicId: 'topic-stale' } as never,
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index f9a782b0bad..d0c91e54579 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -14,6 +14,7 @@ import type {
TaskTopicHandoff,
} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
+import { sql } from 'drizzle-orm';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { GoalModel } from '@/database/models/goal';
@@ -32,12 +33,16 @@ import { AcceptanceService } from '../verify/acceptanceService';
import { GoalCriteriaGeneratorService } from './criteriaGenerator';
import {
decideNextMove,
+ frontierNeedsBudget,
GOAL_ACCEPTANCE_TASK_TITLE,
type GoalMove,
- needsBudget,
selectFrontier,
} from './decideNextMove';
-import { resolveOperationLeaseTimeout, resolveTaskMaxSteps } from './recoveryPolicy';
+import {
+ resolveMaxConcurrentTasks,
+ resolveOperationLeaseTimeout,
+ resolveTaskMaxSteps,
+} from './recoveryPolicy';
import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';
import {
type GoalTickOptions,
@@ -48,6 +53,8 @@ import {
const TASK_NODE_CLAIM_TTL_MS = 5 * 60 * 1000;
const TASK_DESCRIPTION_MAX_LENGTH = 255;
+/** Advisory-lock namespace for goal dispatch. `0x676f_6469` is ASCII `godi`. */
+const GOAL_DISPATCH_LOCK_NAMESPACE = 0x67_6f_64_69;
export interface CreateGoalWorkInput {
description?: string;
@@ -371,18 +378,42 @@ export class GoalService {
const at = Date.now();
const graph = await this.requireGraph(goalId);
const frontier = selectFrontier(graph);
- const chosen = frontier.chosen;
- const frontierTask = chosen?.taskId
- ? ((await this.taskModel.findById(chosen.taskId)) ?? null)
- : undefined;
- // Only the branch that could start a run reads the budget, so a goal that is
- // merely waiting on running Work does not pay for the query on every sweep.
- const budget = needsBudget(frontierTask)
+ // Every candidate's task, not just the head's: the scheduler has to know
+ // which of them are in flight before it can decide what else to start.
+ const candidateTaskIds = frontier.eligible.flatMap(({ node }) =>
+ node.taskId ? [node.taskId] : [],
+ );
+ const tasksById = new Map(
+ (candidateTaskIds.length > 0 ? await this.taskModel.findByIds(candidateTaskIds) : []).map(
+ (task) => [task.id, task],
+ ),
+ );
+
+ // Asked of every unblocked candidate, not just the head: the scheduler
+ // walks past a running head to start an independent task, so a head that
+ // needs no budget must not decide that nothing does. A goal with nothing
+ // startable still skips the query.
+ const budget = frontierNeedsBudget(frontier, tasksById)
? toBudgetState(graph.goal, await this.evaluateBudget(graph.goal, graph))
: undefined;
- const move = decideNextMove({ budget, frontier, frontierTask, graph });
+ const concurrency = resolveMaxConcurrentTasks(graph.goal);
+ const move = decideNextMove({
+ budget,
+ concurrency,
+ frontier,
+ graph,
+ tasksById,
+ });
+ // The scheduler may pick past the head of the frontier, so every arm below
+ // acts on the node the move chose, which is not necessarily the
+ // highest-ranked candidate.
+ const acting = move.chosenNodeId
+ ? graph.nodes.find((node) => node.id === move.chosenNodeId)
+ : undefined;
+ const actingTask = acting?.taskId ? (tasksById.get(acting.taskId) ?? null) : undefined;
+
const effects: GoalAdvanceEffect[] = [];
const observe = (result: GoalTickResult): GoalTickResult => {
@@ -393,7 +424,11 @@ export class GoalService {
candidates: move.candidates,
chosenNodeId: move.chosenNodeId,
effects,
- frontierTask: frontierTask ? toFrontierTaskState(frontierTask) : undefined,
+ candidateTasks: frontier.eligible.flatMap(({ node }) => {
+ const task = node.taskId ? tasksById.get(node.taskId) : undefined;
+ return task ? [toFrontierTaskState(task, node.id)] : [];
+ }),
+ concurrency,
graphState: toTraceGraphState(graph),
message: result.message,
outcome: result.outcome,
@@ -439,48 +474,48 @@ export class GoalService {
}
case 'create_task': {
- return observe(await this.createResponsibleTask(graph, chosen!, effects));
+ return observe(await this.createResponsibleTask(graph, acting!, effects));
}
case 'missing_task': {
await this.coordinatorGraph.updateNodeStatus(
goalId,
- chosen!.id,
+ acting!.id,
'waiting',
'Responsible task is missing',
);
- effects.push({ nodeId: chosen!.id, type: 'node_status', detail: 'waiting' });
+ effects.push({ nodeId: acting!.id, type: 'node_status', detail: 'waiting' });
return observe({
goalId,
message: move.message,
- nodeId: chosen!.id,
+ nodeId: acting!.id,
outcome: move.outcome,
});
}
default: {
// Everything from here on has a live responsible task.
- const task = frontierTask!;
- await this.ensureTaskWorkVersion(graph.goal.id, chosen!.id, task.id);
+ const task = actingTask!;
+ await this.ensureTaskWorkVersion(graph.goal.id, acting!.id, task.id);
switch (move.branch) {
case 'consume_completed': {
- return observe(await this.consumeCompletedTask(graph, chosen!.id, task.id, effects));
+ return observe(await this.consumeCompletedTask(graph, acting!.id, task.id, effects));
}
case 'recover_lease': {
return observe(
- await this.resumeAbandonedTaskRecovery(graph, chosen!.id, task, effects),
+ await this.resumeAbandonedTaskRecovery(graph, acting!.id, task, effects),
);
}
case 'recover_verification': {
- return observe(await this.recoverAfterVerification(graph, chosen!.id, task, effects));
+ return observe(await this.recoverAfterVerification(graph, acting!.id, task, effects));
}
case 'failure_decision': {
return observe(
- await this.openFailureDecision(graph, chosen!.id, task.id, move.message, effects),
+ await this.openFailureDecision(graph, acting!.id, task.id, move.message, effects),
);
}
@@ -488,7 +523,7 @@ export class GoalService {
return observe({
goalId,
message: move.message,
- nodeId: chosen!.id,
+ nodeId: acting!.id,
outcome: move.outcome,
taskId: task.id,
});
@@ -496,13 +531,13 @@ export class GoalService {
case 'task_running': {
if (task.status === 'running') {
- const recovered = await this.recoverAbandonedTask(graph, chosen!.id, task, effects);
+ const recovered = await this.recoverAbandonedTask(graph, acting!.id, task, effects);
if (recovered) return observe(recovered);
}
return observe({
goalId,
message: move.message,
- nodeId: chosen!.id,
+ nodeId: acting!.id,
outcome: move.outcome,
taskId: task.id,
});
@@ -514,14 +549,14 @@ export class GoalService {
return observe({
goalId,
message: move.message,
- nodeId: chosen!.id,
+ nodeId: acting!.id,
outcome: move.outcome,
taskId: task.id,
});
}
default: {
- return observe(await this.dispatchWork(graph, chosen!.id, task, effects));
+ return observe(await this.dispatchWork(graph, acting!.id, task, effects));
}
}
}
@@ -754,10 +789,42 @@ export class GoalService {
// overlapping advances would both dispatch this Work and pay for it twice.
// Claim the task first: the transition is a single conditional UPDATE, so
// exactly one advance can win it.
- const claimed = await this.taskModel.updateStatusIfCurrent(task.id, task.status, 'running', {
- error: null,
- startedAt: new Date(),
+ //
+ // Counting free slots is a *separate* race the per-task claim cannot cover:
+ // two advances reading the same `inFlight` below the cap would each claim a
+ // different task and both succeed, taking the goal past
+ // `maxConcurrentTasks`. So the count and the claim happen together, under a
+ // per-goal advisory lock β€” the planner's cap check is a fast path, this is
+ // the enforcement.
+ const claimed = await this.db.transaction(async (tx) => {
+ await tx.execute(
+ sql`SELECT pg_advisory_xact_lock(${GOAL_DISPATCH_LOCK_NAMESPACE}, hashtext(${goalId}))`,
+ );
+
+ const inFlight = await new GoalGraphModel(
+ tx,
+ this.userId,
+ this.workspaceId,
+ ).countRunningTasks(goalId);
+ if (inFlight >= resolveMaxConcurrentTasks(graph.goal)) return 'at-capacity' as const;
+
+ return new TaskModel(tx, this.userId, this.workspaceId).updateStatusIfCurrent(
+ task.id,
+ task.status,
+ 'running',
+ { error: null, startedAt: new Date() },
+ );
});
+
+ if (claimed === 'at-capacity') {
+ return {
+ goalId,
+ message: `Concurrency limit reached before ${task.identifier} could start`,
+ nodeId,
+ outcome: 'waiting_external',
+ taskId: task.id,
+ };
+ }
if (!claimed) {
return {
goalId,
diff --git a/apps/server/src/services/goal/recoveryPolicy.ts b/apps/server/src/services/goal/recoveryPolicy.ts
index b7b197555be..7c7e8aec7f7 100644
--- a/apps/server/src/services/goal/recoveryPolicy.ts
+++ b/apps/server/src/services/goal/recoveryPolicy.ts
@@ -1,6 +1,13 @@
import type { GoalItem } from '@lobechat/types';
const DEFAULT_MAX_ATTEMPTS_PER_WORK = 3;
+/**
+ * Conservative on purpose: enough to stop independent Tasks queueing behind one
+ * another, low enough that a goal cannot empty its budget in one fan-out before
+ * anyone sees a result.
+ */
+const DEFAULT_MAX_CONCURRENT_TASKS = 3;
+const MAX_CONCURRENT_TASKS_CEILING = 10;
const DEFAULT_OPERATION_LEASE_TIMEOUT_MS = 5 * 60 * 1000;
// Agent runtime refreshes the durable operation lease every third 30-second
// step-lock heartbeat. Keep the timeout above two durable heartbeat intervals
@@ -14,6 +21,13 @@ export const resolveTaskAttemptBudget = (goal: GoalItem): number => {
return DEFAULT_MAX_ATTEMPTS_PER_WORK;
};
+/** How many of this goal's Tasks may run at once. */
+export const resolveMaxConcurrentTasks = (goal: GoalItem): number => {
+ const configured = goal.config?.maxConcurrentTasks;
+ if (typeof configured !== 'number') return DEFAULT_MAX_CONCURRENT_TASKS;
+ return Math.min(MAX_CONCURRENT_TASKS_CEILING, Math.max(1, configured));
+};
+
export const resolveTaskMaxSteps = (goal: GoalItem): number | undefined => {
const configured = goal.config?.recovery?.maxStepsPerRun;
return typeof configured === 'number' && configured > 0 ? configured : undefined;
diff --git a/apps/server/src/services/goal/replayCoordinator.test.ts b/apps/server/src/services/goal/replayCoordinator.test.ts
index 23c04d51fa6..3966b0942a7 100644
--- a/apps/server/src/services/goal/replayCoordinator.test.ts
+++ b/apps/server/src/services/goal/replayCoordinator.test.ts
@@ -154,7 +154,8 @@ describe('replayGoalAgainstCurrentCoordinator', () => {
{ blockedBy: ['a'], nodeId: 'b', priority: 0, status: 'proposed', title: 'b' },
],
chosenNodeId: 'a',
- frontierTask: { id: 'task_1', status: 'backlog', updatedAt: 0 },
+ candidateTasks: [{ id: 'task_1', nodeId: 'a', status: 'backlog', updatedAt: 0 }],
+ concurrency: 3,
outcome: 'no_progress',
}),
],
@@ -169,3 +170,38 @@ describe('replayGoalAgainstCurrentCoordinator', () => {
expect(replayGoalAgainstCurrentCoordinator(exhausted).divergences).toEqual([]);
});
});
+
+describe('replaying trajectories recorded before the scheduler', () => {
+ it('reads the legacy single-task field instead of seeing no tasks at all', () => {
+ // Older ticks carry `frontierTask`, not `candidateTasks`. Dropping it would
+ // replay every one of them as `missing_task` and report divergences that
+ // never happened.
+ const legacy: GoalTrajectory = {
+ ...trajectory,
+ advances: [
+ {
+ ...trajectory.advances[0],
+ ticks: [
+ {
+ ...trajectory.advances[0].ticks[0],
+ branch: 'dispatch_task',
+ candidateTasks: undefined,
+ frontierTask: { id: 'task_1', status: 'backlog', updatedAt: 0 },
+ },
+ ],
+ },
+ ],
+ graphBaseline: {
+ ...trajectory.graphBaseline,
+ nodes: [
+ { ...trajectory.graphBaseline.nodes[0], taskId: 'task_1' },
+ trajectory.graphBaseline.nodes[1],
+ ],
+ },
+ };
+
+ const result = replayGoalAgainstCurrentCoordinator(legacy);
+
+ expect(result.divergences.filter((item) => item.replayed === 'missing_task')).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/goal/replayCoordinator.ts b/apps/server/src/services/goal/replayCoordinator.ts
index 8453bfaee56..e38f10a9f5b 100644
--- a/apps/server/src/services/goal/replayCoordinator.ts
+++ b/apps/server/src/services/goal/replayCoordinator.ts
@@ -11,6 +11,9 @@ import type { GoalGraphSnapshot, TaskItem } from '@lobechat/types';
import { decideNextMove, selectFrontier } from './decideNextMove';
+/** Matches `resolveMaxConcurrentTasks`'s default, for traces that predate it. */
+const DEFAULT_REPLAY_CONCURRENCY = 3;
+
/**
* Lift a recorded graph back into the shape the coordinator reads.
*
@@ -37,10 +40,14 @@ export const fromTraceGraphState = (state: GoalGraphState): GoalGraphSnapshot =>
workVersions: [],
}) as unknown as GoalGraphSnapshot;
-const toTask = (input: GoalDecisionInput): TaskItem | undefined | null => {
- if (input.frontierTask === undefined) return undefined;
- return { ...input.frontierTask, updatedAt: new Date(input.frontierTask.updatedAt) } as TaskItem;
-};
+/** Rebuild the task map the scheduler reads from the recorded candidate states. */
+const toTasksById = (input: GoalDecisionInput): Map<string, TaskItem> =>
+ new Map(
+ (input.candidateTasks ?? []).map((task) => [
+ task.id,
+ { ...task, updatedAt: new Date(task.updatedAt) } as TaskItem,
+ ]),
+ );
/**
* The live coordinator, as a decider a recorded trajectory can be replayed
@@ -54,9 +61,11 @@ export const coordinatorDecider: GoalDecider = (input): GoalDecision => {
const frontier = selectFrontier(graph);
const move = decideNextMove({
budget: input.budget,
+ // A trajectory recorded before the cap existed replays at its default.
+ concurrency: input.concurrency ?? DEFAULT_REPLAY_CONCURRENCY,
frontier,
- frontierTask: toTask(input),
graph,
+ tasksById: toTasksById(input),
});
return { branch: move.branch, candidates: move.candidates, chosenNodeId: move.chosenNodeId };
diff --git a/apps/server/src/services/goal/traceObservation.ts b/apps/server/src/services/goal/traceObservation.ts
index eea5f0f9f63..354c6e0d739 100644
--- a/apps/server/src/services/goal/traceObservation.ts
+++ b/apps/server/src/services/goal/traceObservation.ts
@@ -21,9 +21,10 @@ export interface GoalTickObservation {
branch: GoalTickBranch;
budget?: GoalBudgetState;
candidates: FrontierCandidate[];
+ candidateTasks?: GoalFrontierTaskState[];
chosenNodeId?: string;
+ concurrency?: number;
effects: GoalAdvanceEffect[];
- frontierTask?: GoalFrontierTaskState;
graphState: GoalGraphState;
message: string;
outcome: GoalTickOutcome;
@@ -75,10 +76,11 @@ export const toTraceGraphState = (graph: GoalGraphSnapshot): GoalGraphState => (
})),
});
-export const toFrontierTaskState = (task: TaskItem): GoalFrontierTaskState => ({
+export const toFrontierTaskState = (task: TaskItem, nodeId?: string): GoalFrontierTaskState => ({
error: task.error,
id: task.id,
identifier: task.identifier,
+ nodeId,
status: task.status,
updatedAt: new Date(task.updatedAt).getTime(),
});
diff --git a/packages/agent-tracing/src/goal/__tests__/loadTrajectory.test.ts b/packages/agent-tracing/src/goal/__tests__/loadTrajectory.test.ts
index 531b698235a..8283d2f2940 100644
--- a/packages/agent-tracing/src/goal/__tests__/loadTrajectory.test.ts
+++ b/packages/agent-tracing/src/goal/__tests__/loadTrajectory.test.ts
@@ -80,6 +80,43 @@ describe('loadGoalTrajectory', () => {
expect(resolveDownloadUrl).toHaveBeenCalledWith('goal_missing');
});
+ it('re-fetches an unfinished goal instead of serving a stale cached copy', async () => {
+ // A running goal is a moving object; a cache hit would pin the reader to
+ // whatever it looked like the first time it was inspected.
+ const cacheDir = path.join(rootDir, '.goal-tracing', '_remote');
+ await fs.mkdir(cacheDir, { recursive: true });
+ await fs.writeFile(
+ path.join(cacheDir, 'goal_running.json'),
+ JSON.stringify({ ...trajectory('goal_running'), advances: [] }),
+ 'utf8',
+ );
+ const resolveDownloadUrl = vi.fn().mockResolvedValue(null);
+
+ await loadGoalTrajectory('goal_running', { allowDownload: true, resolveDownloadUrl, rootDir });
+
+ expect(resolveDownloadUrl).toHaveBeenCalledWith('goal_running');
+ });
+
+ it('serves a finished goal from cache without asking the server again', async () => {
+ const cacheDir = path.join(rootDir, '.goal-tracing', '_remote');
+ await fs.mkdir(cacheDir, { recursive: true });
+ await fs.writeFile(
+ path.join(cacheDir, 'goal_done.json'),
+ JSON.stringify({ ...trajectory('goal_done'), completionReason: 'achieved' }),
+ 'utf8',
+ );
+ const resolveDownloadUrl = vi.fn();
+
+ const loaded = await loadGoalTrajectory('goal_done', {
+ allowDownload: true,
+ resolveDownloadUrl,
+ rootDir,
+ });
+
+ expect(loaded?.completionReason).toBe('achieved');
+ expect(resolveDownloadUrl).not.toHaveBeenCalled();
+ });
+
it('reads a trajectory straight off a json path', async () => {
const filePath = path.join(rootDir, 'exported.json');
await fs.writeFile(filePath, JSON.stringify(trajectory('goal_3')), 'utf8');
diff --git a/packages/agent-tracing/src/goal/__tests__/viewer.test.ts b/packages/agent-tracing/src/goal/__tests__/viewer.test.ts
index 4345716d5e1..d0ed3d11dca 100644
--- a/packages/agent-tracing/src/goal/__tests__/viewer.test.ts
+++ b/packages/agent-tracing/src/goal/__tests__/viewer.test.ts
@@ -54,13 +54,17 @@ const trajectory: GoalTrajectory = {
totalCost: 0,
},
effects: [{ operationId: 'op_1', targetId: 'task_A', type: 'started_run' }],
- frontierTask: {
- error: null,
- id: 'task_A',
- identifier: 'T-31',
- status: 'backlog',
- updatedAt: 0,
- },
+ candidateTasks: [
+ {
+ error: null,
+ id: 'task_A',
+ identifier: 'T-31',
+ nodeId: 'aaaaaaaa-1111',
+ status: 'backlog',
+ updatedAt: 0,
+ },
+ ],
+ concurrency: 3,
}),
],
trigger: 'create',
@@ -108,10 +112,38 @@ describe('renderGoalAdvanceDetail', () => {
const output = renderGoalAdvanceDetail(trajectory, 0);
expect(output).toContain('budget: rounds ∞ cost $0.0000/$5');
- expect(output).toContain('task: T-31 backlog');
+ expect(output).toContain('β–Έ task: T-31 backlog');
+ expect(output).toContain('concurrency: 3');
expect(output).toContain('effect: started_run task_A op=op_1');
});
+ it('shows the legacy frontier task when candidate tasks were not recorded yet', () => {
+ const legacyTrajectory: GoalTrajectory = {
+ ...trajectory,
+ advances: [
+ {
+ ...trajectory.advances[0],
+ ticks: [
+ tick({
+ candidateTasks: undefined,
+ frontierTask: {
+ error: 'Device offline',
+ id: 'task_legacy',
+ identifier: 'T-legacy',
+ status: 'failed',
+ updatedAt: 0,
+ },
+ }),
+ ],
+ },
+ ],
+ };
+
+ const output = renderGoalAdvanceDetail(legacyTrajectory, 0);
+
+ expect(output).toContain('task: T-legacy failed β€” Device offline');
+ });
+
it('says so rather than rendering an empty frame for an advance that is not there', () => {
expect(renderGoalAdvanceDetail(trajectory, 9)).toBe('No advance #9 in goal_1');
});
diff --git a/packages/agent-tracing/src/goal/replay.ts b/packages/agent-tracing/src/goal/replay.ts
index 4e80252032e..47f5b1c884e 100644
--- a/packages/agent-tracing/src/goal/replay.ts
+++ b/packages/agent-tracing/src/goal/replay.ts
@@ -14,10 +14,12 @@ import type {
*/
export interface GoalDecisionInput {
budget?: GoalBudgetState;
- /** State of the chosen work node's responsible task, when it already has one. */
+ /** Every candidate's responsible task β€” the scheduler reads all of them. */
+ candidateTasks?: GoalFrontierTaskState[];
+ concurrency?: number;
+ /** @deprecated Legacy single-task shape; present only on older trajectories. */
frontierTask?: GoalFrontierTaskState;
graph: GoalGraphState;
- now: number;
}
/**
@@ -78,9 +80,13 @@ export const replayGoalTrajectory = (
const graph: GoalGraphState = reconstructGraphAt(trajectory, advance.seq, tick.index);
const replayed = decide({
budget: tick.budget,
- frontierTask: tick.frontierTask,
+ // A trajectory recorded before the scheduler existed has only the
+ // chosen candidate's task. Dropping it would replay every one of those
+ // ticks as `missing_task` and report divergences that never happened.
+ candidateTasks:
+ tick.candidateTasks ?? (tick.frontierTask ? [tick.frontierTask] : undefined),
+ concurrency: tick.concurrency,
graph,
- now: tick.at,
});
const before = divergences.length;
diff --git a/packages/agent-tracing/src/goal/store/loadTrajectory.ts b/packages/agent-tracing/src/goal/store/loadTrajectory.ts
index c8e8389c384..aea4c136171 100644
--- a/packages/agent-tracing/src/goal/store/loadTrajectory.ts
+++ b/packages/agent-tracing/src/goal/store/loadTrajectory.ts
@@ -51,8 +51,10 @@ export async function loadGoalTrajectory(
if (local) return local;
const remote = new RemoteGoalTraceStore(rootDir);
+ // Cached copies are only written for finished goals, but an older cache may
+ // predate that rule, so an unfinished one is re-fetched rather than served.
const cached = await remote.getCached(target);
- if (cached) return cached;
+ if (cached?.completionReason) return cached;
if (!allowDownload) return undefined;
diff --git a/packages/agent-tracing/src/goal/store/remote-store.ts b/packages/agent-tracing/src/goal/store/remote-store.ts
index 91034b59767..ac06d31fd2d 100644
--- a/packages/agent-tracing/src/goal/store/remote-store.ts
+++ b/packages/agent-tracing/src/goal/store/remote-store.ts
@@ -58,9 +58,14 @@ export class RemoteGoalTraceStore {
const decoded = isZstdFrame(body) ? await decompressZstd(body) : body;
const trajectory = JSON.parse(decoded.toString('utf8')) as GoalTrajectory;
- await fs.mkdir(this.cacheDir, { recursive: true });
- await fs.writeFile(this.cachePath(goalId), JSON.stringify(trajectory, null, 2), 'utf8');
- console.error(`βœ“ Cached to: ${DEFAULT_DIR}/${REMOTE_DIR}/${goalId}.json`);
+ // Only a finished goal is safe to cache. A running one is a snapshot of a
+ // moving object, and caching it would pin the reader to whatever the goal
+ // happened to look like the first time it was inspected.
+ if (trajectory.completionReason) {
+ await fs.mkdir(this.cacheDir, { recursive: true });
+ await fs.writeFile(this.cachePath(goalId), JSON.stringify(trajectory, null, 2), 'utf8');
+ console.error(`βœ“ Cached to: ${DEFAULT_DIR}/${REMOTE_DIR}/${goalId}.json`);
+ }
return trajectory;
}
diff --git a/packages/agent-tracing/src/goal/types.ts b/packages/agent-tracing/src/goal/types.ts
index 185ec5a1cdd..53b81c98fa4 100644
--- a/packages/agent-tracing/src/goal/types.ts
+++ b/packages/agent-tracing/src/goal/types.ts
@@ -138,11 +138,13 @@ export interface GoalBudgetState {
totalCost: number;
}
-/** The responsible task's state at decision time; drives every post-dispatch branch. */
+/** A candidate's responsible task at decision time; drives every post-dispatch branch. */
export interface GoalFrontierTaskState {
error?: string | null;
id: string;
identifier?: string;
+ /** The task node this task belongs to, so a reader can line the two up. */
+ nodeId?: string;
status: string;
updatedAt: number;
}
@@ -172,9 +174,23 @@ export interface GoalTickSnapshot {
*/
budget?: GoalBudgetState;
candidates: FrontierCandidate[];
+ /**
+ * The responsible task of every candidate that had one. The scheduler reads
+ * all of them β€” it has to know which are in flight before it can decide what
+ * else to start β€” so recording only the chosen one would leave a replay
+ * unable to reproduce the decision.
+ */
+ candidateTasks?: GoalFrontierTaskState[];
chosenNodeId?: string;
+ /** Concurrency cap in force for this tick. */
+ concurrency?: number;
/** What this tick changed. Attributed per tick so an advance's writes stay ordered. */
effects: GoalAdvanceEffect[];
+ /**
+ * @deprecated Superseded by `candidateTasks`, which carries every candidate
+ * rather than only the chosen one. Still read when replaying trajectories
+ * recorded before the scheduler could look past the head of the frontier.
+ */
frontierTask?: GoalFrontierTaskState;
/**
* Graph change since the previously recorded tick, observed on entry to this
diff --git a/packages/agent-tracing/src/goal/viewer.ts b/packages/agent-tracing/src/goal/viewer.ts
index b750c3e20f6..55b5ef5e358 100644
--- a/packages/agent-tracing/src/goal/viewer.ts
+++ b/packages/agent-tracing/src/goal/viewer.ts
@@ -95,6 +95,9 @@ export const renderGoalAdvanceDetail = (trajectory: GoalTrajectory, seq: number)
);
if (tick.budget) {
+ if (tick.concurrency !== undefined) {
+ lines.push(` concurrency: ${tick.concurrency}`);
+ }
const limits = [
tick.budget.maxRounds == null
? 'rounds ∞'
@@ -106,11 +109,11 @@ export const renderGoalAdvanceDetail = (trajectory: GoalTrajectory, seq: number)
lines.push(` budget: ${limits}`);
}
- if (tick.frontierTask) {
- const error = tick.frontierTask.error ? ` β€” ${tick.frontierTask.error}` : '';
- lines.push(
- ` task: ${tick.frontierTask.identifier ?? tick.frontierTask.id} ${tick.frontierTask.status}${error}`,
- );
+ const candidateTasks = tick.candidateTasks ?? (tick.frontierTask ? [tick.frontierTask] : []);
+ for (const task of candidateTasks) {
+ const error = task.error ? ` β€” ${task.error}` : '';
+ const mark = task.nodeId && task.nodeId === tick.chosenNodeId ? 'β–Έ' : ' ';
+ lines.push(` ${mark} task: ${task.identifier ?? task.id} ${task.status}${error}`);
}
if (tick.candidates.length > 0) {
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 98b4e38a388..8f1593d649f 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -11,7 +11,7 @@ import type {
GoalNodeStatus,
GoalNodeWorkVersionRelation,
} from '@lobechat/types';
-import { and, asc, eq, isNull, lt, or, sql } from 'drizzle-orm';
+import { and, asc, count, eq, inArray, isNull, lt, or, sql } from 'drizzle-orm';
import { goals } from '../schemas/goal';
import {
@@ -21,6 +21,7 @@ import {
goalNodes,
goalNodeWorkVersions,
} from '../schemas/goalGraph';
+import { tasks } from '../schemas/task';
import { works, workVersions } from '../schemas/work';
import type { LobeChatDatabase, Transaction } from '../type';
import { buildWorkspaceWhere } from '../utils/workspace';
@@ -186,6 +187,28 @@ export class GoalGraphModel {
return link;
});
+ /**
+ * How many of a goal's tasks are occupying a concurrency slot.
+ *
+ * Counted in the database rather than from a graph snapshot so it can be read
+ * inside the same transaction as the dispatch claim β€” two advances that each
+ * counted from their own snapshot would both see room and both start work.
+ */
+ countRunningTasks = async (goalId: string): Promise<number> => {
+ const [row] = await this.db
+ .select({ count: count() })
+ .from(goalNodes)
+ .innerJoin(tasks, eq(goalNodes.taskId, tasks.id))
+ .where(
+ and(
+ eq(goalNodes.goalId, goalId),
+ eq(goalNodes.kind, 'task'),
+ inArray(tasks.status, ['running', 'scheduled']),
+ ),
+ );
+ return row?.count ?? 0;
+ };
+
createNode = async (goalId: string, input: CreateNodeInput) =>
this.db.transaction(async (tx) => {
if (!(await this.ownedGoal(goalId, tx))) return undefined;
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 06e92e67a31..70a143bd723 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -32,6 +32,13 @@ export interface GoalRecoveryPolicy {
}
export interface GoalConfig {
+ /**
+ * How many of a goal's Tasks may be in flight at once. Independent Tasks are
+ * the common case β€” four bug fixes that share no code have no reason to run
+ * one after another β€” but an uncapped fan-out would spend the whole budget
+ * before the first result came back. Null/undefined uses the default.
+ */
+ maxConcurrentTasks?: number | null;
recovery?: GoalRecoveryPolicy;
}