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): let the system planner lead and hand problems to the main Agent (#19477)

Arvin Xu3df8460895ca
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index a8625b36624..18ecfb49f42 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -205,7 +205,10 @@ export function registerGoalCommand(program: Command) {
goal
.command('create <title>')
- .option('--max-manager-turns <n>', 'Enable CLI manager planning with this turn limit')
+ .option(
+ '--max-manager-turns <n>',
+ 'Add a main Agent with this turn limit; it takes over problems the system planner cannot route',
+ )
.description('Create a standalone goal and seed its graph')
.option('-r, --requirement <text>', 'Acceptance requirement')
.option(
diff --git a/apps/server/src/services/goal/EXPLORATION.md b/apps/server/src/services/goal/EXPLORATION.md
index 752f3fb6209..9ddeb6bce64 100644
--- a/apps/server/src/services/goal/EXPLORATION.md
+++ b/apps/server/src/services/goal/EXPLORATION.md
@@ -24,6 +24,14 @@ and schedules a Goal advance. The Goal model then chooses one of three actions:
- `verify`: request the existing independent terminal acceptance Task. The
planner cannot declare the Goal achieved.
+These three are the whole vocabulary, and that bounds what exploration can say: it
+can move within the graph, but it cannot express "this goal is mis-framed", "the
+judge was wrong" or "stop and ask". Those belong to an optional main Agent, which
+`config.manager` adds as a second layer rather than a replacement β€” exploration
+keeps the ordinary path and the main Agent is handed the problem at the moment the
+coordinator would otherwise stop the Goal on a person. See `manager.README.md`;
+the handover point is `gateOrTakeOver`.
+
A correction is a Task inside the experiment it corrects, not a new container, so
it does not consume an experiment slot: fixing an instrument should not cost an
exploration budget. `MAX_PROTOCOL_REVISIONS` bounds them per experiment, and
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index e8de164e9b6..787bd5da701 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -54,7 +54,7 @@ import {
TERMINAL_NODE_STATUSES,
} from './decideNextMove';
import { experimentResults, exploreGraph } from './exploreGraph';
-import { GoalManagerService } from './manager';
+import { answeredProblem, GoalManagerService, problemKey } from './manager';
import {
resolveMaxConcurrentTasks,
resolveOperationLeaseTimeout,
@@ -217,13 +217,11 @@ export class GoalService {
code: 'BAD_REQUEST',
message: 'Main Agent requires 1–100 management turns',
});
- if (options.exploration || options.supervision?.enabled || input.tasks?.length) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message:
- 'Manager mode owns initial and subsequent planning; do not combine with exploration, supervision or seed tasks',
- });
- }
+ // Exploration, supervision and seed tasks used to be rejected here, on the
+ // premise that a main Agent owns planning outright. They are layers, not
+ // rivals: the system planner leads, supervision recovers known transport
+ // failures, and the main Agent is handed whatever neither can route (see
+ // `gateOrTakeOver`). Ordering resolves what exclusivity used to.
await assertAgentUsableBy(this.db, creatorAgentId, {
userId: this.userId,
workspaceId: this.workspaceId,
@@ -1230,8 +1228,15 @@ export class GoalService {
const at = Date.now();
const graph = await this.requireGraph(goalId);
if (graph.goal.config?.manager) {
+ // The system's own planner leads whenever the Goal has one: a main Agent is
+ // the fallback for problems that planner cannot express, not a replacement
+ // for it. With exploration configured this call only settles a turn already
+ // in flight; new turns start from `gateOrTakeOver` below, where the
+ // coordinator has run out of moves. A Goal whose only planner is the main
+ // Agent keeps being led by it.
const result = await new GoalManagerService(this.db, this.userId, this.workspaceId).advance(
graph,
+ { mayStartTurn: !graph.goal.config.exploration },
);
if (result) return result;
}
@@ -1430,7 +1435,7 @@ export class GoalService {
).reviewFailure(graph, acting!.id, task);
if (supervision) return observe(supervision);
return observe(
- await this.openFailureDecision(graph, acting!.id, task.id, move.message, effects),
+ await this.gateOrTakeOver(graph, acting!.id, task.id, move.message, effects),
);
}
@@ -1733,7 +1738,7 @@ export class GoalService {
: recovery.outcome === 'exhausted-rounds'
? 'Task attempt budget was exhausted'
: 'Automatic recovery could not start the next attempt';
- return this.openFailureDecision(graph, nodeId, task.id, exhaustedReason, effects);
+ return this.gateOrTakeOver(graph, nodeId, task.id, exhaustedReason, effects);
};
/** Claim the task for dispatch and start its run. */
@@ -2023,7 +2028,7 @@ export class GoalService {
: recovery.outcome === 'exhausted-rounds'
? 'Task attempt budget was exhausted after an operation was abandoned'
: 'Automatic recovery could not restart an abandoned operation';
- return this.openFailureDecision(graph, nodeId, task.id, reason, effects);
+ return this.gateOrTakeOver(graph, nodeId, task.id, reason, effects);
};
private buildTaskInstruction = (
@@ -2373,6 +2378,44 @@ export class GoalService {
};
};
+ /**
+ * Every stop-on-a-person funnels through here, so this is the one place a main
+ * Agent can be offered the problem before the Goal parks on its owner.
+ *
+ * The coordinator only reaches this point once its own policy is out of moves:
+ * the failure matched no recovery branch, the attempt budget ran out, or the
+ * reason is one it cannot classify. That is precisely the class of problem the
+ * deterministic lane cannot express, so it is handed over rather than escalated.
+ * A main Agent that cannot help answers `escalate`, and the gate opens anyway β€”
+ * one turn later, with a diagnosis attached.
+ */
+ private gateOrTakeOver = async (
+ graph: GoalGraphSnapshot,
+ nodeId: string,
+ taskId: string,
+ reason: string,
+ effects: GoalAdvanceEffect[] = [],
+ ): Promise<GoalTickResult> => {
+ const takeover = await new GoalManagerService(this.db, this.userId, this.workspaceId).takeOver(
+ graph,
+ { reason, taskId },
+ );
+ if (takeover) return takeover;
+ // When the main Agent already looked at THIS problem, the gate carries what it
+ // said: the person answering should see the Agent's reasoning, not just the
+ // coordinator's own reason for stopping.
+ const answered = answeredProblem(graph.goal.config?.managerState);
+ const diagnosis =
+ answered?.key === problemKey({ reason, taskId }) ? answered.reason.slice(0, 600) : undefined;
+ return this.openFailureDecision(
+ graph,
+ nodeId,
+ taskId,
+ diagnosis ? `${reason} β€” main Agent: ${diagnosis}` : reason,
+ effects,
+ );
+ };
+
private openFailureDecision = async (
graph: GoalGraphSnapshot,
nodeId: string,
diff --git a/apps/server/src/services/goal/manager.README.md b/apps/server/src/services/goal/manager.README.md
index dbe558822af..81f5e731cae 100644
--- a/apps/server/src/services/goal/manager.README.md
+++ b/apps/server/src/services/goal/manager.README.md
@@ -34,10 +34,70 @@ stale input and unrelated operations reject writes. Work is not dispatched until
the main turn's terminal operation is observed. A backend losing the dispatch
response adopts the operation through its stable source-message identity.
-The main Agent owns initial and subsequent planning. Manager mode cannot be
-combined with seed Tasks, exploration or the legacy opt-in supervisor. Neither
-the old decomposition model nor exploration planner runs during its planning
-turns. Execution, delivery verification and human Gates remain coordinator-owned.
+The main Agent may be combined with seed Tasks, exploration and supervision; they
+are ordered layers, not rivals. On a Goal that has no exploration planner the main
+Agent leads planning as before. On a Goal that has one, the system planner owns
+the ordinary path and the main Agent only starts a turn when the coordinator is
+about to stop the Goal on a person β€” the failure matched no recovery branch, the
+attempt budget ran out, or the reason could not be classified. That handover point
+is `gateOrTakeOver`, and the ladder there is supervision first (known transport
+failures), then the main Agent, then the human Gate. An uninvited turn never
+claims a failure on a Goal with supervision enabled, or it would reach that
+failure before the supervisor does and spend a planning turn on something the
+supervisor recovers on its own. A turn already in flight is
+settled on every tick regardless of who leads, or its plan would never land.
+
+A takeover turn is told which problem it inherited and is expected to answer with
+a corrective Task, independent verification, a diagnosed retry, or `escalate` β€”
+and all four can actually commit. The unfinished-work guard on `tasks` / `verify`
+is waived for an invited turn: it exists to stop an uninvited one from double
+planning the frontier, while a takeover's inherited Task is stuck by definition.
+`retry` remains limited to recognised transport failures, and the prompt says so
+rather than advertising a move that will be refused.
+
+A `tasks` or `verify` plan from a takeover turn also RETIRES the node it inherited,
+because accepting a plan is not the same as the Goal moving: a nonterminal blocked
+node is reached by the next tick's frontier before the corrective node, which routes
+straight back to the Gate, and terminal verification cannot start while it is
+unfinished. Retiring is the same move the human Gate offers under "Retire task",
+scoped to the single node the turn was invited about and attributed to the Agent.
+
+The terminal acceptance node is excluded from that retirement.
+`decideWithoutFrontier` finds the acceptance task by TITLE regardless of status, so
+retiring it parks the Goal on `no_progress` with neither a Gate nor a verdict;
+failing the Goal belongs to the Gate's own `retire` answer, which is coupled to that
+option rather than to the node's status. A takeover invited for a FAILED terminal
+acceptance does start β€” the acceptance guard is uninvited-only β€” but it is accepted
+only as an `escalate`: a corrective task returns to the same failed node and `verify`
+sets `readyForAcceptance` without producing a fresh run, so both would strand.
+Refusing at submit keeps the prompt's offer and the server's answer identical, and
+the prompt names the limit so a turn is not spent discovering it. Letting corrective
+work supersede a failed acceptance is a lifecycle change, not a validation one.
+
+Retirement is also refused when something `depends_on` the stuck node: a prerequisite
+counts as met only when it is `resolved`, and the graph has no edge removal, so the
+dependents cannot be rewired onto the replacement and would sit behind a prerequisite
+that can never resolve. Those blocks go to the Gate.
+
+**Known gap.** Exploration's own stop conditions β€” the experiment limit, a spent
+revision allowance, a planner error β€” pause the Goal directly instead of passing
+through `gateOrTakeOver`, and `eligible()` then rejects the paused Goal. So the one
+planner whose "I am out of moves" most deserves a second opinion never reaches the
+main Agent. Closing that needs an invited turn to be allowed to revive a Goal the
+system paused, which changes who may restart it.
+which puts the Gate back with its original reason, one turn later and with the
+Agent's diagnosis appended to the question. An escalation from a takeover turn
+deliberately does NOT pause the Goal the way an ordinary planning turn's does: the
+coordinator opens that Gate on the next tick, and a paused Goal would never reach
+it. The same problem is never handed over twice β€” `managerState.problem` records what a
+turn was invited for, keyed by **task and reason together**, because
+"Task attempt budget was exhausted" is the same sentence for every Task that
+reaches it and a reason-only key made the next Task inherit the previous one's
+answer. Any committed plan counts as an answer, not just `escalate`: if the Agent's
+move did not unstick the Goal, handing the same problem back only buys the same
+move, so the Gate is the honest next step and the Agent's reasoning rides on it. An invited turn with no turn budget left declines rather than
+pausing, so the Gate keeps carrying the real question. Execution, delivery
+verification and human Gates remain coordinator-owned.
Read `config.managerState` in the Goal graph for the current receipt and Topic.
Wakeups use the existing Goal scheduler (queued mode for restart durability).
diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.ts
index b05647d1d1a..06c63b59a97 100644
--- a/apps/server/src/services/goal/manager.test.ts
+++ b/apps/server/src/services/goal/manager.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -553,16 +554,493 @@ describe('CLI main Agent planning', () => {
expect((await model().findById(id))!.config!.managerState!.readyForAcceptance).not.toBe(true);
});
- it('does not mix planning owners', async () => {
+ it('accepts a main Agent alongside the system planner', async () => {
+ // Previously rejected outright. The two are layers now: the system planner
+ // leads and the main Agent is handed what it cannot route, so configuring
+ // both is the supported shape rather than a conflict.
+ const graph = await service().create({
+ config: {
+ exploration: { instruction: 'Other planner', maxExperiments: 2 },
+ manager: {},
+ },
+ createdByAgentId: agentId,
+ title: 'Mixed',
+ });
+ expect(graph.goal.config).toMatchObject({
+ exploration: { maxExperiments: 2 },
+ manager: { agentId },
+ });
+ });
+});
+
+/**
+ * The two planners are ordered, not exclusive: the system's exploration planner
+ * owns the ordinary path and a main Agent is the fallback for problems that
+ * planner cannot express. Before this, `tick` asked the main Agent first and
+ * returned early, so exploration never got a turn on a Goal that had both β€” and
+ * the main Agent was never asked about a problem outside the transport
+ * whitelist, which is why a Goal could park on a person for hours with a main
+ * Agent configured and idle.
+ */
+describe('planner precedence', () => {
+ const explored = (maxTurns = 4) =>
+ service().create({
+ config: {
+ exploration: { instruction: 'Follow the pre-registered branches', maxExperiments: 4 },
+ manager: { maxTurns },
+ },
+ createdByAgentId: agentId,
+ title: 'Explored research',
+ });
+
+ it('leaves the ordinary path to the system planner', async () => {
+ const graph = await explored();
+ await service().tick(graph.goal.id);
+ expect((await model().findById(graph.goal.id))!.config!.managerState).toBeUndefined();
+ });
+
+ it('still settles a main Agent turn already in flight', async () => {
+ const { id, state, op } = await start();
+ const caller = operationCaller(op.id);
+ await caller.submitOperationPlan({
+ id,
+ operationId: op.id,
+ token: state.token,
+ plan: taskPlan,
+ });
+ await db.update(agentOperations).set({ status: 'done' }).where(eq(agentOperations.id, op.id));
+ const current = (await model().findById(id))!.config!;
+ await model().update(id, {
+ config: {
+ ...current,
+ exploration: { instruction: 'Follow the pre-registered branches', maxExperiments: 4 },
+ },
+ });
+ // The turn was already paid for; declining to settle it would lose its plan.
+ expect(
+ await manager().advance((await service().graph(id))!, { mayStartTurn: false }),
+ ).toMatchObject({ outcome: 'advanced' });
+ expect((await model().findById(id))!.config!.managerState!.consumed).toBe(true);
+ });
+
+ it('hands the problem over instead of opening the gate', async () => {
+ const graph = await service().create({
+ config: {
+ exploration: { instruction: 'Follow the pre-registered branches', maxExperiments: 4 },
+ manager: { maxTurns: 4 },
+ recovery: { maxAttemptsPerTask: 1 },
+ },
+ createdByAgentId: agentId,
+ tasks: ['Measure ranking ability on the frozen holdout'],
+ title: 'Explored research',
+ });
+ const created = await service().tick(graph.goal.id);
+ const taskModel = new TaskModel(db, userId);
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+ await taskModel.updateStatus(created.taskId!, 'paused', {
+ error: 'Delivery did not pass verification.',
+ });
+
+ await service().tick(graph.goal.id);
+
+ expect((await model().findById(graph.goal.id))!.config!.managerState).toMatchObject({
+ turns: 1,
+ });
+ expect((await service().graph(graph.goal.id)).decisions).toHaveLength(0);
+ });
+
+ it('opens the gate once the main Agent has had its turn and the block remains', async () => {
+ const graph = await service().create({
+ config: {
+ exploration: { instruction: 'Follow the pre-registered branches', maxExperiments: 4 },
+ manager: { maxTurns: 1 },
+ recovery: { maxAttemptsPerTask: 1 },
+ },
+ createdByAgentId: agentId,
+ tasks: ['Measure ranking ability on the frozen holdout'],
+ title: 'Explored research',
+ });
+ const created = await service().tick(graph.goal.id);
+ const taskModel = new TaskModel(db, userId);
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+ await taskModel.updateStatus(created.taskId!, 'paused', {
+ error: 'Delivery did not pass verification.',
+ });
+
+ // Its one turn is handed over, then exits without changing anything.
+ await service().tick(graph.goal.id);
+ const state = (await model().findById(graph.goal.id))!.config!.managerState!;
+ const turn = await ops().findByTopicSourceMessage(
+ state.topicId,
+ `msg_goal_manager_${state.token}`,
+ );
+ await db
+ .update(agentOperations)
+ .set({ status: 'done' })
+ .where(eq(agentOperations.id, turn!.id));
+ await service().tick(graph.goal.id);
+
+ // Out of turns, so the block goes back to its owner carrying the original
+ // reason rather than "the main Agent is out of turns".
+ expect(await service().tick(graph.goal.id)).toMatchObject({ outcome: 'waiting_human' });
+ const gated = await service().graph(graph.goal.id);
+ expect(gated.decisions).toHaveLength(1);
+ expect(gated.decisions[0].question).toContain('Task attempt budget was exhausted');
+ expect(gated.goal.status).not.toBe('paused');
+ });
+});
+
+/**
+ * Codex review on #19477 caught both of these: the newly allowed combinations
+ * each broke an ordering the PR itself documented.
+ */
+describe('takeover ordering', () => {
+ /**
+ * Supervision is cheaper than a planning turn and stricter about who authored a
+ * status. Allowing `manager` + `supervision` without `exploration` made `tick`
+ * start an uninvited turn on a recognised transport failure before
+ * `reviewFailure` could ever run, reversing the documented ladder.
+ */
+ it('consults supervision before starting a main Agent turn', async () => {
+ const graph = await service().create({
+ config: { manager: { maxTurns: 4 }, supervision: { enabled: true } },
+ createdByAgentId: agentId,
+ tasks: ['Collect the baseline'],
+ title: 'Supervised research',
+ });
+ const created = await service().tick(graph.goal.id);
+ const taskModel = new TaskModel(db, userId);
+ await taskModel.updateStatus(created.taskId!, 'failed', { error: 'fetch failed' });
+
+ await service().tick(graph.goal.id);
+
+ // Before this, `tick` claimed the recognised transport failure with an
+ // UNINVITED turn and returned early, so `decideNextMove` never reached the
+ // `failure_decision` branch and the supervisor never saw it. The turn that
+ // runs now is an invited one, which is only reachable through that branch β€”
+ // `problem` is the receipt that it came down the documented ladder.
+ expect((await model().findById(graph.goal.id))!.config!.managerState).toMatchObject({
+ problem: `${created.taskId}::fetch failed`,
+ });
+ });
+
+ /**
+ * The takeover contract says `escalate` puts the Gate back one turn later. The
+ * escalate branch only paused the Goal, so no answerable question existed and
+ * later ticks sat on `goal_paused` forever.
+ */
+ it('turns a takeover escalation into the Gate it was holding', async () => {
+ const graph = await service().create({
+ config: {
+ exploration: { instruction: 'Follow the pre-registered branches', maxExperiments: 4 },
+ manager: { maxTurns: 4 },
+ recovery: { maxAttemptsPerTask: 1 },
+ },
+ createdByAgentId: agentId,
+ tasks: ['Measure ranking ability on the frozen holdout'],
+ title: 'Explored research',
+ });
+ const created = await service().tick(graph.goal.id);
+ const taskModel = new TaskModel(db, userId);
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+ await taskModel.updateStatus(created.taskId!, 'paused', {
+ error: 'Delivery did not pass verification.',
+ });
+ await service().tick(graph.goal.id);
+
+ const state = (await model().findById(graph.goal.id))!.config!.managerState!;
+ expect(state.problem).toBe(`${created.taskId}::Task attempt budget was exhausted`);
+ const turn = await ops().findByTopicSourceMessage(
+ state.topicId,
+ `msg_goal_manager_${state.token}`,
+ );
+ await operationCaller(turn!.id).submitOperationPlan({
+ id: graph.goal.id,
+ operationId: turn!.id,
+ plan: { action: 'escalate', reason: 'The reproducibility criterion needs a human judge' },
+ token: state.token,
+ });
+ // A takeover escalation must not park the Goal: the gate is opened by the tick
+ // that follows, and a paused Goal never reaches it.
+ expect((await model().findById(graph.goal.id))!.status).not.toBe('paused');
+ await db
+ .update(agentOperations)
+ .set({ status: 'done' })
+ .where(eq(agentOperations.id, turn!.id));
+ await service().tick(graph.goal.id);
+
+ expect(await service().tick(graph.goal.id)).toMatchObject({ outcome: 'waiting_human' });
+ const gated = await service().graph(graph.goal.id);
+ expect(gated.decisions).toHaveLength(1);
+ expect(gated.decisions[0].question).toContain('needs a human judge');
+ });
+});
+
+/**
+ * Codex review round 2 on #19477. Both findings were about the takeover contract
+ * promising more than the code would accept.
+ */
+describe('takeover submissions', () => {
+ const stuckGoal = async (title = 'Explored research') => {
+ const graph = await service().create({
+ config: {
+ exploration: { instruction: 'Follow the pre-registered branches', maxExperiments: 4 },
+ manager: { maxTurns: 4 },
+ recovery: { maxAttemptsPerTask: 1 },
+ },
+ createdByAgentId: agentId,
+ tasks: ['Measure ranking ability on the frozen holdout'],
+ title,
+ });
+ const created = await service().tick(graph.goal.id);
+ const taskModel = new TaskModel(db, userId);
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+ await taskModel.updateStatus(created.taskId!, 'paused', {
+ error: 'Delivery did not pass verification.',
+ });
+ await service().tick(graph.goal.id);
+ const state = (await model().findById(graph.goal.id))!.config!.managerState!;
+ const turn = await ops().findByTopicSourceMessage(
+ state.topicId,
+ `msg_goal_manager_${state.token}`,
+ );
+ return { goalId: graph.goal.id, state, taskId: created.taskId!, turn: turn! };
+ };
+
+ /**
+ * The prompt advertises a corrective task, verification, a retry and escalation.
+ * `submit` refused `tasks` and `verify` whenever any task node was unfinished β€”
+ * which a takeover's inherited task always is β€” so only `escalate` could ever
+ * commit and the other three were a contract the code broke.
+ */
+ it('accepts the corrective task a takeover was invited to plan', async () => {
+ const { goalId, state, turn } = await stuckGoal();
await expect(
- service().create({
- title: 'Mixed',
- createdByAgentId: agentId,
- config: {
- manager: {},
- exploration: { instruction: 'Other planner', maxExperiments: 2 },
+ operationCaller(turn.id).submitOperationPlan({
+ id: goalId,
+ operationId: turn.id,
+ plan: {
+ action: 'tasks',
+ reason: 'The previous run captured no evidence at all',
+ tasks: [{ description: 'Rerun the scoring and register the report', title: 'Redo it' }],
+ },
+ token: state.token,
+ }),
+ ).resolves.toMatchObject({ success: true });
+ expect((await service().graph(goalId)).nodes.some((node) => node.title === 'Redo it')).toBe(
+ true,
+ );
+ });
+
+ /**
+ * Accepting the plan is not the same as the Goal moving. The inherited node
+ * stayed nonterminal, so the next tick's frontier reached it before the new
+ * corrective node and routed straight back to the Gate β€” the advertised action
+ * committed and changed nothing.
+ */
+ it('retires the replaced work so the corrective task actually runs', async () => {
+ const { goalId, state, taskId, turn } = await stuckGoal();
+ await operationCaller(turn.id).submitOperationPlan({
+ id: goalId,
+ operationId: turn.id,
+ plan: {
+ action: 'tasks',
+ reason: 'The previous run captured no evidence at all',
+ tasks: [{ description: 'Rerun the scoring and register the report', title: 'Redo it' }],
+ },
+ token: state.token,
+ });
+ await db.update(agentOperations).set({ status: 'done' }).where(eq(agentOperations.id, turn.id));
+ await service().tick(goalId);
+
+ const graph = await service().graph(goalId);
+ expect(graph.nodes.find((node) => node.taskId === taskId)!.status).toBe('retired');
+ const moved = await service().tick(goalId);
+ expect(moved.outcome).not.toBe('waiting_human');
+ expect((await service().graph(goalId)).decisions).toHaveLength(0);
+ });
+
+ /**
+ * "Task attempt budget was exhausted" is the same sentence for every task that
+ * reaches it. Keying the already-answered check on the reason alone made a second
+ * task skip its own takeover and inherit the first task's diagnosis in its gate.
+ */
+ it('gives a second task its own takeover despite an identical reason', async () => {
+ const first = await stuckGoal('First research');
+ await operationCaller(first.turn.id).submitOperationPlan({
+ id: first.goalId,
+ operationId: first.turn.id,
+ plan: { action: 'escalate', reason: 'Needs a human judge' },
+ token: first.state.token,
+ });
+ await db
+ .update(agentOperations)
+ .set({ status: 'done' })
+ .where(eq(agentOperations.id, first.turn.id));
+ await service().tick(first.goalId);
+
+ // A different Goal and task reaching the same wording must not be read as the
+ // problem that was already answered.
+ const second = await stuckGoal('Second research');
+ expect(second.state.problem).toBe(`${second.taskId}::Task attempt budget was exhausted`);
+ expect(second.state.problem).not.toBe(first.state.problem);
+ });
+
+ it('stops handing the same problem over once its turn has answered', async () => {
+ const { goalId, state, turn } = await stuckGoal();
+ await operationCaller(turn.id).submitOperationPlan({
+ id: goalId,
+ operationId: turn.id,
+ plan: { action: 'escalate', reason: 'Needs a human judge' },
+ token: state.token,
+ });
+ await db.update(agentOperations).set({ status: 'done' }).where(eq(agentOperations.id, turn.id));
+ await service().tick(goalId);
+
+ expect(await service().tick(goalId)).toMatchObject({ outcome: 'waiting_human' });
+ const gated = await service().graph(goalId);
+ expect(gated.decisions).toHaveLength(1);
+ expect(gated.decisions[0].question).toContain('Needs a human judge');
+ });
+});
+
+/**
+ * Codex review round 4. The acceptance guard was written for uninvited turns
+ * ("verification exists, stop planning more work") but sat above the invited
+ * branch, so a takeover invited BECAUSE the terminal acceptance failed could never
+ * start and the Goal still reached a bare Gate with a main Agent idle.
+ */
+describe('takeover on a failed terminal acceptance', () => {
+ const failedAcceptance = async () => {
+ const graph = await service().create({
+ config: {
+ exploration: { instruction: 'Follow the pre-registered branches', maxExperiments: 4 },
+ manager: { maxTurns: 4 },
+ recovery: { maxAttemptsPerTask: 1 },
+ },
+ createdByAgentId: agentId,
+ requirement: 'Return a defensible training recommendation.',
+ tasks: [GOAL_ACCEPTANCE_TASK_TITLE],
+ title: 'Explored research',
+ });
+ const created = await service().tick(graph.goal.id);
+ const taskModel = new TaskModel(db, userId);
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+ await taskModel.updateStatus(created.taskId!, 'paused', {
+ error: 'Delivery did not pass verification.',
+ });
+ await service().tick(graph.goal.id);
+ return { goalId: graph.goal.id, taskId: created.taskId! };
+ };
+
+ it('hands a failed terminal acceptance to the main Agent', async () => {
+ const { goalId, taskId } = await failedAcceptance();
+ expect((await model().findById(goalId))!.config!.managerState).toMatchObject({
+ problemTaskId: taskId,
+ });
+ expect((await service().graph(goalId)).decisions).toHaveLength(0);
+ });
+
+ /**
+ * A failed acceptance cannot be superseded: the acceptance task is matched by TITLE
+ * regardless of status, so a corrective task returns to that same failed node and
+ * `verify` sets `readyForAcceptance` without producing a fresh run. Refusing keeps
+ * the prompt's offer and the server's answer identical instead of accepting a plan
+ * that strands.
+ */
+ it('accepts only an escalation for a failed acceptance', async () => {
+ const { goalId, taskId } = await failedAcceptance();
+ const state = (await model().findById(goalId))!.config!.managerState!;
+ const turn = await ops().findByTopicSourceMessage(
+ state.topicId,
+ `msg_goal_manager_${state.token}`,
+ );
+ const caller = operationCaller(turn!.id);
+ await expect(
+ caller.submitOperationPlan({
+ id: goalId,
+ operationId: turn!.id,
+ plan: {
+ action: 'tasks',
+ reason: 'The judge read evidence it was never shown',
+ tasks: [{ description: 'Recapture the evidence and redeliver', title: 'Recapture' }],
},
+ token: state.token,
+ }),
+ ).rejects.toThrow('can only be escalated');
+ await expect(
+ caller.submitOperationPlan({
+ id: goalId,
+ operationId: turn!.id,
+ plan: { action: 'escalate', reason: 'The judge read evidence it was never shown' },
+ token: state.token,
}),
- ).rejects.toThrow('do not combine');
+ ).resolves.toMatchObject({ success: true });
+ expect(
+ (await service().graph(goalId)).nodes.find((node) => node.taskId === taskId)!.status,
+ ).not.toBe('retired');
+ });
+});
+
+/**
+ * Codex review round 5, dependency half. A prerequisite only counts as met when it is
+ * `resolved`, so retiring a node something depends on leaves the dependent blocked and
+ * the Goal lands on `no_frontier` β€” and the graph has no edge removal, so the
+ * dependents cannot be rewired onto the replacement.
+ */
+describe('takeover and dependent work', () => {
+ it('leaves stuck work that something depends on for the Gate', async () => {
+ const graph = await service().create({
+ config: {
+ exploration: { instruction: 'Follow the pre-registered branches', maxExperiments: 4 },
+ manager: { maxTurns: 4 },
+ recovery: { maxAttemptsPerTask: 1 },
+ },
+ createdByAgentId: agentId,
+ tasks: ['Measure ranking ability'],
+ title: 'Explored research',
+ });
+ const created = await service().tick(graph.goal.id);
+ const blockedNode = (await service().graph(graph.goal.id)).nodes.find(
+ (node) => node.taskId === created.taskId,
+ )!;
+ const problem = (await service().graph(graph.goal.id)).nodes.find(
+ (node) => node.kind === 'problem',
+ )!;
+ const dependent = await service().addNode(graph.goal.id, {
+ kind: 'task',
+ title: 'Train the head',
+ });
+ await service().addEdge(graph.goal.id, problem.id, dependent!.id, 'decomposes');
+ await service().addEdge(graph.goal.id, dependent!.id, blockedNode.id, 'depends_on');
+ const taskModel = new TaskModel(db, userId);
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+ await taskModel.updateStatus(created.taskId!, 'paused', {
+ error: 'Delivery did not pass verification.',
+ });
+ await service().tick(graph.goal.id);
+
+ const state = (await model().findById(graph.goal.id))!.config!.managerState!;
+ const turn = await ops().findByTopicSourceMessage(
+ state.topicId,
+ `msg_goal_manager_${state.token}`,
+ );
+ await operationCaller(turn!.id).submitOperationPlan({
+ id: graph.goal.id,
+ operationId: turn!.id,
+ plan: {
+ action: 'tasks',
+ reason: 'Replace the stuck measurement',
+ tasks: [{ description: 'Measure again from the frozen inputs', title: 'Measure again' }],
+ },
+ token: state.token,
+ });
+
+ // Retiring it would strand "Train the head" behind a prerequisite that can never
+ // resolve, so the node keeps its status and the block stays visible to a person.
+ expect(
+ (await service().graph(graph.goal.id)).nodes.find((node) => node.id === blockedNode.id)!
+ .status,
+ ).not.toBe('retired');
});
});
diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.ts
index 6e2cceb4592..ee801a1f2c6 100644
--- a/apps/server/src/services/goal/manager.ts
+++ b/apps/server/src/services/goal/manager.ts
@@ -2,7 +2,12 @@ import { createHash, randomUUID } from 'node:crypto';
import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';
import { buildGoalManagerPrompt } from '@lobechat/prompts';
-import type { GoalGraphSnapshot, GoalManagerState, GoalTickResult } from '@lobechat/types';
+import type {
+ GoalGraphSnapshot,
+ GoalManagerState,
+ GoalTickResult,
+ TaskItem,
+} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { eq, sql } from 'drizzle-orm';
import { z } from 'zod';
@@ -73,6 +78,27 @@ export const managerSnapshot = (graph: GoalGraphSnapshot) => {
};
/** Durable wakeups around ordinary CLI-capable Agent runs. No supervisor builtin tools. */
+/** A takeover problem is identified by the task it blocked, not by its wording
+ * alone: "Task attempt budget was exhausted" is the same sentence for every task
+ * that reaches it, so a reason-only key makes the second task inherit the first
+ * one's answer. */
+export const problemKey = (problem: { reason: string; taskId?: string }) =>
+ `${problem.taskId ?? 'goal'}::${problem.reason}`;
+
+/**
+ * The problem a settled takeover turn already answered, with the answer.
+ *
+ * Reading it is how the coordinator tells "nobody has looked at this yet" from
+ * "the main Agent looked and this is what it said". Any committed answer counts,
+ * not just `escalate`: if the Agent's plan did not unstick the Goal, handing the
+ * same problem over again only buys the same plan, so the Gate is the honest next
+ * step and the Agent's reasoning rides along on it.
+ */
+export const answeredProblem = (state?: GoalManagerState) =>
+ state?.consumed && state.problem && state.submitted
+ ? { key: state.problem, reason: state.submitted.reason }
+ : undefined;
+
export class GoalManagerService {
constructor(
private readonly db: LobeChatDatabase,
@@ -198,15 +224,65 @@ export class GoalManagerService {
});
};
- advance = async (graph: GoalGraphSnapshot): Promise<GoalTickResult | null> => {
+ /**
+ * Advance the goal through its main Agent.
+ *
+ * `mayStartTurn` is what orders the two planners. The system's own
+ * exploration planner owns the ordinary path; a main Agent is the fallback for
+ * problems that planner cannot express, so on a Goal that has exploration
+ * configured this only settles a turn already in flight and otherwise declines.
+ * A Goal whose only planner IS the main Agent keeps starting turns here.
+ */
+ advance = async (
+ graph: GoalGraphSnapshot,
+ options?: { mayStartTurn?: boolean },
+ ): Promise<GoalTickResult | null> => {
+ if (!this.eligible(graph)) return null;
+ const settled = await this.settleInFlight(graph);
+ if (settled) return settled;
+ if (options?.mayStartTurn === false) return null;
+ return this.startTurn(graph);
+ };
+
+ /**
+ * Hand a problem the coordinator could not route to the main Agent, instead of
+ * stopping the Goal on a person.
+ *
+ * The invitation IS the authorization: the caller has already decided it would
+ * otherwise open a human gate, so the ordinary "is there unfinished work" and
+ * "is this a recognised transport failure" narrowings do not apply β€” those
+ * exist to stop an uninvited turn from preempting running work. Turn limits,
+ * budgets and the compare-and-swap claim still hold, and a main Agent that
+ * cannot help answers `escalate`, which puts the gate back.
+ */
+ takeOver = async (
+ graph: GoalGraphSnapshot,
+ problem: { reason: string; taskId?: string },
+ ): Promise<GoalTickResult | null> => {
+ if (!this.eligible(graph)) return null;
+ // Already answered: a takeover turn that ran for THIS problem has had its say,
+ // so handing it over again would buy the same plan instead of asking a person.
+ // `answeredProblem` is what the caller attaches to the gate.
+ if (answeredProblem(graph.goal.config?.managerState)?.key === problemKey(problem)) return null;
+ const settled = await this.settleInFlight(graph);
+ if (settled) return settled;
+ return this.startTurn(graph, problem);
+ };
+
+ /** Shared entry conditions: a policy, an active Goal, and nobody waiting on a person. */
+ private eligible = (graph: GoalGraphSnapshot) =>
+ Boolean(
+ graph.goal.config?.manager &&
+ activeStatuses.has(graph.goal.status) &&
+ !graph.decisions.some((d) => d.status === 'pending'),
+ );
+
+ /**
+ * Poll a dispatched turn. Runs on every tick regardless of who leads planning:
+ * a turn already paid for has to be settled, or its plan would never land.
+ */
+ private settleInFlight = async (graph: GoalGraphSnapshot): Promise<GoalTickResult | null> => {
const { goal } = graph;
- const policy = goal.config?.manager;
- if (
- !policy ||
- !activeStatuses.has(goal.status) ||
- graph.decisions.some((d) => d.status === 'pending')
- )
- return null;
const state = goal.config?.managerState;
if (state && !state.consumed) {
const operation = await new AgentOperationModel(
@@ -252,27 +328,68 @@ export class GoalManagerService {
: 'Main Agent exited without a plan; a new bounded turn will reread durable state',
};
}
+ return null;
+ };
+
+ /**
+ * Whether an UNINVITED turn must stand down. A main Agent that nobody asked for
+ * may only plan when the graph is quiet, or recover a failure the transport
+ * whitelist recognises β€” anything else is work in flight that it would preempt.
+ */
+ private uninvitedTurnBlocked = async (
+ graph: GoalGraphSnapshot,
+ unfinished: GoalGraphSnapshot['nodes'],
+ tasks: TaskItem[],
+ ) => {
+ const failed = tasks.find((t) => t.status === 'failed');
+ if (!failed) return unfinished.length > 0;
+ // Supervision owns recognised transport failures, and it is both cheaper than
+ // a planning turn and stricter about who authored the status. Claiming one
+ // uninvited would reverse that order and spend a turn on a failure the
+ // supervisor recovers on its own; whatever it declines reaches
+ // `gateOrTakeOver`, which invites this Agent properly.
+ if (graph.goal.config?.supervision?.enabled) return true;
+ const runs = await new TaskTopicModel(this.db, this.userId, this.workspaceId).findByTaskId(
+ failed.id,
+ );
+ const op = runs[0]?.operationId
+ ? await new AgentOperationModel(this.db, this.userId, this.workspaceId).findById(
+ runs[0].operationId,
+ )
+ : undefined;
+ return !recoveryEligibility(graph, failed, op).eligible;
+ };
+
+ private startTurn = async (
+ graph: GoalGraphSnapshot,
+ problem?: { reason: string; taskId?: string },
+ ): Promise<GoalTickResult | null> => {
+ const { goal } = graph;
+ const policy = goal.config!.manager!;
+ const state = goal.config?.managerState;
const nodes = graph.nodes.filter((n) => n.kind === 'task');
- if (state?.readyForAcceptance || nodes.some((n) => n.title === GOAL_ACCEPTANCE_TASK_TITLE))
- return null;
const unfinished = nodes.filter((n) => !terminalNodes.has(n.status));
- const tasks = await new TaskModel(this.db, this.userId, this.workspaceId).findByIds(
- unfinished.flatMap((n) => (n.taskId ? [n.taskId] : [])),
- );
- const failed = tasks.find((t) => t.status === 'failed');
- // Only confirmed recoverable failures enter autonomous diagnosis; all other failures keep the normal Gate path.
- if (failed) {
- const runs = await new TaskTopicModel(this.db, this.userId, this.workspaceId).findByTaskId(
- failed.id,
+ // An invited turn skips the checks below. They ask "should an uninvited main
+ // Agent interrupt what is running", and the caller has already answered a
+ // harder question: the coordinator is out of moves and the alternative is
+ // stopping the Goal on a person. The acceptance guard belongs to that set too:
+ // it means "verification exists, stop planning more work", which is right for an
+ // uninvited turn and wrong for a takeover invited BECAUSE the terminal
+ // acceptance is the thing that failed.
+ if (!problem) {
+ if (state?.readyForAcceptance || nodes.some((n) => n.title === GOAL_ACCEPTANCE_TASK_TITLE))
+ return null;
+ const tasks = await new TaskModel(this.db, this.userId, this.workspaceId).findByIds(
+ unfinished.flatMap((n) => (n.taskId ? [n.taskId] : [])),
);
- const op = runs[0]?.operationId
- ? await new AgentOperationModel(this.db, this.userId, this.workspaceId).findById(
- runs[0].operationId,
- )
- : undefined;
- if (!recoveryEligibility(graph, failed, op).eligible) return null;
- } else if (unfinished.length) return null;
+ const blocked = await this.uninvitedTurnBlocked(graph, unfinished, tasks);
+ if (blocked) return null;
+ }
if ((state?.turns ?? 0) >= (policy.maxTurns ?? 12) || (await this.budgetBlocked(graph))) {
+ // An invited turn declines instead of pausing. The caller was about to open
+ // a gate carrying the actual problem; pausing here would replace that
+ // question with "the main Agent is out of turns" and lose it.
+ if (problem) return null;
return this.pause(goal.id, 'Goal or main Agent turn budget exhausted');
}
const claimed = await this.db.transaction(async (db) => {
@@ -303,6 +420,12 @@ export class GoalManagerService {
).id;
const reviews = await this.reviews(current, db);
const next: GoalManagerState = {
+ ...(problem
+ ? {
+ problem: problemKey(problem),
+ ...(problem.taskId && { problemTaskId: problem.taskId }),
+ }
+ : {}),
reviewSnapshot: reviews.hash,
topicId,
turns: (state?.turns ?? 0) + 1,
@@ -331,6 +454,7 @@ export class GoalManagerService {
instruction: policy.instruction,
token: claimed.token,
feedback: claimed.reviewNotes,
+ problem: problem?.reason,
}),
});
await this.db.transaction(async (db) => {
@@ -393,9 +517,36 @@ export class GoalManagerService {
const unfinished = graph.nodes.filter(
(n) => n.kind === 'task' && !terminalNodes.has(n.status),
);
+ // A takeover of the terminal acceptance can only be answered with `escalate`.
+ // The acceptance task is matched by TITLE regardless of status, so a corrective
+ // task returns to that same failed node and `verify` sets `readyForAcceptance`
+ // without producing a fresh run β€” both end at the Gate. Refusing here keeps the
+ // prompt's offer and the server's answer the same; letting the acceptance be
+ // superseded is a lifecycle change, not a validation one.
+ if (
+ state.problem &&
+ (plan.action === 'tasks' || plan.action === 'verify') &&
+ graph.nodes.some(
+ (n) =>
+ n.kind === 'task' &&
+ n.taskId === state.problemTaskId &&
+ n.title === GOAL_ACCEPTANCE_TASK_TITLE,
+ )
+ )
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message:
+ 'A failed Goal acceptance can only be escalated; it cannot be superseded by new work yet',
+ });
+ // The unfinished-work guard asks whether an UNINVITED turn may plan while
+ // work is in flight; it would double-plan the frontier. A takeover turn
+ // inherits work that is stuck by definition β€” the coordinator only handed it
+ // over because nothing else moves it β€” so a corrective task is the answer
+ // rather than the thing to forbid. Without this exemption the prompt
+ // advertises four actions and only `escalate` can ever commit.
if (
(plan.action === 'tasks' || plan.action === 'verify') &&
- (unfinished.length ||
+ ((unfinished.length && !state.problem) ||
(plan.action === 'verify' &&
!graph.nodes.some((n) => n.kind === 'task' && n.status === 'resolved')))
)
@@ -407,6 +558,33 @@ export class GoalManagerService {
id: goal.config.manager.agentId,
type: 'agent',
});
+ // Accepting a plan that REPLACES the inherited work has to settle it too.
+ // Validation alone was not enough: the blocked node stayed nonterminal, so
+ // the next tick's frontier reached it before the corrective node and routed
+ // straight back to the Gate, and terminal verification could not start at
+ // all. Retiring is the same move the human Gate offers, scoped to the one
+ // node this turn was invited about and attributed to the Agent.
+ if (
+ state.problem &&
+ state.problemTaskId &&
+ (plan.action === 'tasks' || plan.action === 'verify')
+ ) {
+ const inherited = graph.nodes.find(
+ (n) => n.kind === 'task' && n.taskId === state.problemTaskId,
+ );
+ // A prerequisite only counts as met when it is `resolved`, so retiring a node
+ // that something depends on leaves the dependent blocked forever and the Goal
+ // lands on `no_frontier`. Rewiring the dependents onto the replacement would
+ // be the answer, but the graph has no edge removal, so the old edge would keep
+ // pointing at the retired node. Leave it alone and let the Gate handle it.
+ const hasDependents =
+ inherited &&
+ graph.edges.some(
+ (edge) => edge.kind === 'depends_on' && edge.targetNodeId === inherited.id,
+ );
+ if (inherited && !hasDependents && !terminalNodes.has(inherited.status))
+ await authored.updateNodeStatus(goalId, inherited.id, 'retired', plan.reason);
+ }
if (plan.action === 'tasks') {
const problem = graph.nodes.find((n) => n.kind === 'problem');
for (const task of plan.tasks) {
@@ -449,7 +627,11 @@ export class GoalManagerService {
))
)
throw new TRPCError({ code: 'CONFLICT', message: 'Task changed before retry' });
- } else if (plan.action === 'escalate') {
+ } else if (plan.action === 'escalate' && !state.problem) {
+ // Only an ORDINARY planning turn pauses the Goal here. A takeover turn has
+ // a gate waiting behind it for this exact problem, and the coordinator
+ // opens that gate on the next tick β€” a paused Goal would stop the tick from
+ // ever reaching it, leaving the escalation with no answerable question.
await model.updateStatus(goalId, 'paused');
await authored.recordGoalStatus(goalId, goal.status, 'paused', plan.reason);
}
diff --git a/packages/prompts/src/chains/goalManager.test.ts b/packages/prompts/src/chains/goalManager.test.ts
index 8dbde219977..8c94dc3e1ca 100644
--- a/packages/prompts/src/chains/goalManager.test.ts
+++ b/packages/prompts/src/chains/goalManager.test.ts
@@ -15,7 +15,7 @@ describe('buildGoalManagerPrompt', () => {
requirement,
token: 'test-token',
});
- expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v3');
+ expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v4');
expect(prompt).toContain(`Requirement: ${requirement}`);
expect(prompt).toContain('Use the language of the Goal requirement');
expect(prompt).toContain(
@@ -29,4 +29,32 @@ describe('buildGoalManagerPrompt', () => {
);
},
);
+
+ /**
+ * Regression: a takeover turn has to know what it is taking over. Without the
+ * problem the coordinator hands over, the main Agent reads an ordinary planning
+ * turn and re-plans work that is already in flight.
+ */
+ it('states the handed-over problem and the answers that move the goal', () => {
+ const prompt = buildGoalManagerPrompt({
+ feedback: '[]',
+ goalId: 'goal_1',
+ problem: 'Task attempt budget was exhausted',
+ requirement: 'Find the training scheme closest to my rejections',
+ token: 't',
+ });
+ expect(prompt).toContain('Task attempt budget was exhausted');
+ expect(prompt).toContain('this Goal stops on a person');
+ expect(prompt).toContain('escalate with the specific question');
+ });
+
+ it('says nothing about a takeover on an ordinary planning turn', () => {
+ const prompt = buildGoalManagerPrompt({
+ feedback: '[]',
+ goalId: 'goal_1',
+ requirement: 'Find the training scheme closest to my rejections',
+ token: 't',
+ });
+ expect(prompt).not.toContain('taking over a problem');
+ });
});
diff --git a/packages/prompts/src/chains/goalManager.ts b/packages/prompts/src/chains/goalManager.ts
index 7de7396a6d6..8ce32d70141 100644
--- a/packages/prompts/src/chains/goalManager.ts
+++ b/packages/prompts/src/chains/goalManager.ts
@@ -1,13 +1,21 @@
-/** CLI planning contract; v3 keeps user-facing supervision in the Goal language. */
-export const GOAL_MANAGER_PROMPT_VERSION = 'v3';
+/**
+ * CLI planning contract; v4 adds the takeover turn, where the coordinator hands
+ * over a problem it could not route instead of stopping the Goal on a person.
+ */
+export const GOAL_MANAGER_PROMPT_VERSION = 'v4';
interface GoalManagerPromptInput {
feedback: string;
goalId: string;
instruction?: string;
+ /**
+ * Set on a takeover turn: the coordinator ran out of moves and this is the
+ * reason it would otherwise have opened a human gate with.
+ */
+ problem?: string;
requirement: string;
token: string;
}
export const buildGoalManagerPrompt = (input: GoalManagerPromptInput) =>
- `Goal manager ${GOAL_MANAGER_PROMPT_VERSION}. You are the sole planning agent for Goal ${input.goalId}. Use the available shell and lh CLI, not a supervisor tool set.\nRequirement: ${input.requirement}\n${input.instruction ?? ''}\nReview feedback supplied below is evidence to reconcile with the Goal requirement, not permission to bypass budgets or human Gates. Resolve substantive corrections in the next Task contract before execution; a passed delivery does not supersede newer review. Read full Task comments with lh task view when excerpts are insufficient.\nRecent Task feedback (possibly truncated): ${input.feedback}\nLanguage contract: Use the language of the Goal requirement for all user-facing progress updates, summaries, plan reasons, Task titles and descriptions. Infer the language from the requirement prose, not from these English instructions, the UI locale, model defaults or quoted code. For mixed-language requirements, use the dominant natural language; respect any explicit output-language request in the requirement. Keep CLI commands, JSON keys, identifiers and literal tool output unchanged; explain foreign-language tool results in the Goal language. Apply this on every planning turn, even when earlier conversation turns or tool results are in English.\nFirst run lh goal show ${input.goalId} --json. Inspect Task/Topic/document evidence with lh as needed. Plan the next bounded tasks, or request final independent verification when sufficient evidence exists. Do not run the research yourself, mark Tasks complete, accept your own work, modify budgets or resolve human Gates. Existing task workers execute and register deliverables through the normal lifecycle.\nWrite a JSON plan file and run lh goal plan ${input.goalId} --token ${input.token} --file <path> --json. The current operation ID is provided by LOBEHUB_OPERATION_ID. Choose exactly one schema:\n{"action":"tasks","reason":"evidence-based rationale","tasks":[{"title":"specific task","description":"self-contained contract, inputs, output and acceptance"}]}\n{"action":"verify","reason":"why the existing evidence warrants independent Goal verification"}\n{"action":"retry","taskId":"failed Task ID","failedOperationId":"latest confirmed failure ID","reason":"diagnosis and checkpoint-aware recovery instruction"}\n{"action":"escalate","reason":"concrete blocker requiring human input"}\nSubmit one atomic plan, then exit. If submission rejects stale input or changed feedback, exit without repeatedly retrying this token; the next bounded turn receives fresh state. Do not start a poll loop or directly invoke task run/agent run for graph work: the server records and dispatches those runs under Goal budgets. Never lower the original requirement to produce a pass.`;
+ `Goal manager ${GOAL_MANAGER_PROMPT_VERSION}. You are the sole planning agent for Goal ${input.goalId}. Use the available shell and lh CLI, not a supervisor tool set.\nRequirement: ${input.requirement}\n${input.instruction ?? ''}\n${input.problem ? `You are taking over a problem the coordinator could not route on its own: ${input.problem}\nWithout you this Goal stops on a person, so decide what actually moves it: a corrective task that replaces the stuck work, independent verification when the evidence already warrants it, a diagnosed retry (only a transport failure is retryable; anything else will be refused), or β€” when the block genuinely needs a human β€” escalate with the specific question they have to answer. Two limits are enforced, so do not spend the turn on them: a FAILED Goal acceptance can only be escalated, not replaced by new work; and stuck work that something else depends on cannot be retired, so escalate that too.\n` : ''}Review feedback supplied below is evidence to reconcile with the Goal requirement, not permission to bypass budgets or human Gates. Resolve substantive corrections in the next Task contract before execution; a passed delivery does not supersede newer review. Read full Task comments with lh task view when excerpts are insufficient.\nRecent Task feedback (possibly truncated): ${input.feedback}\nLanguage contract: Use the language of the Goal requirement for all user-facing progress updates, summaries, plan reasons, Task titles and descriptions. Infer the language from the requirement prose, not from these English instructions, the UI locale, model defaults or quoted code. For mixed-language requirements, use the dominant natural language; respect any explicit output-language request in the requirement. Keep CLI commands, JSON keys, identifiers and literal tool output unchanged; explain foreign-language tool results in the Goal language. Apply this on every planning turn, even when earlier conversation turns or tool results are in English.\nFirst run lh goal show ${input.goalId} --json. Inspect Task/Topic/document evidence with lh as needed. Plan the next bounded tasks, or request final independent verification when sufficient evidence exists. Do not run the research yourself, mark Tasks complete, accept your own work, modify budgets or resolve human Gates. Existing task workers execute and register deliverables through the normal lifecycle.\nWrite a JSON plan file and run lh goal plan ${input.goalId} --token ${input.token} --file <path> --json. The current operation ID is provided by LOBEHUB_OPERATION_ID. Choose exactly one schema:\n{"action":"tasks","reason":"evidence-based rationale","tasks":[{"title":"specific task","description":"self-contained contract, inputs, output and acceptance"}]}\n{"action":"verify","reason":"why the existing evidence warrants independent Goal verification"}\n{"action":"retry","taskId":"failed Task ID","failedOperationId":"latest confirmed failure ID","reason":"diagnosis and checkpoint-aware recovery instruction"}\n{"action":"escalate","reason":"concrete blocker requiring human input"}\nSubmit one atomic plan, then exit. If submission rejects stale input or changed feedback, exit without repeatedly retrying this token; the next bounded turn receives fresh state. Do not start a poll loop or directly invoke task run/agent run for graph work: the server records and dispatches those runs under Goal budgets. Never lower the original requirement to produce a pass.`;
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index d32b26ec13f..0830ed00a0e 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -222,6 +222,17 @@ export interface GoalManagerPolicy {
export interface GoalManagerState {
consumed?: boolean;
operationId?: string;
+ /**
+ * The problem this turn was invited to take over, when the coordinator handed
+ * one over instead of opening a human gate. Its presence is what separates a
+ * takeover turn from ordinary planning: an `escalate` from a takeover turn puts
+ * the gate back rather than pausing the Goal, and the same problem is not handed
+ * over twice.
+ */
+ problem?: string;
+ /** The blocked task that problem belongs to, so accepting a plan that replaces
+ * it can retire exactly that node without parsing the key. */
+ problemTaskId?: string;
readyForAcceptance?: boolean;
reviewSnapshot?: string;
snapshot: string;