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): explain a refused plan and diagnose a stalled Goal from the server's admission (#20680)

Arvin Xu8c76aceb49aa
diff --git a/.agents/skills/cli/SKILL.md b/.agents/skills/cli/SKILL.md
index 82b895291a7..7bdf2f284be 100644
--- a/.agents/skills/cli/SKILL.md
+++ b/.agents/skills/cli/SKILL.md
@@ -354,6 +354,7 @@ cd apps/cli && bun run cli:link
See `references/` for each command group:
- **Agent**: `references/agent.md` (CRUD, run, status)
+- **Goals**: `references/goal.md` (planning turn, state, events, lifecycle, decisions)
- **Content Generation**: `references/generate.md` (text, image, video, tts, asr, download)
- **Knowledge & Files**: `references/knowledge.md` (kb, file, doc)
- **Conversation**: `references/conversation.md` (topic, message)
diff --git a/.agents/skills/cli/references/goal.md b/.agents/skills/cli/references/goal.md
new file mode 100644
index 00000000000..3b576a267c8
--- /dev/null
+++ b/.agents/skills/cli/references/goal.md
@@ -0,0 +1,139 @@
+# Goal Commands
+
+Long-horizon Goal Graphs: a Goal owns a requirement, a graph of
+`task` / `finding` / `decision` / `problem` / `experiment` nodes, and one
+supervising agent that plans between bounded turns. Task workers execute and
+register deliverables through the normal lifecycle; the planning agent only
+plans.
+
+**Source**: `apps/cli/src/commands/goal.ts`
+
+## The planning loop
+
+Every planning turn is handed a block with a `token` and the current
+`LOBEHUB_OPERATION_ID`. Three CLI calls are involved:
+
+1. `lh goal show <id> --json` (or `lh goal state <id>`) — read the evidence.
+2. Write a JSON plan file.
+3. `lh goal plan <id> --token <turn token> --file <plan.json> --json` — submit
+ one atomic plan and exit.
+
+`plan` picks its endpoint from the credential: an operation-bound token (device,
+gateway, sandbox) goes to `submitOperationPlan`, a user login to `submitPlan`.
+
+A refusal is a **verdict about the turn, not a transport blip** — do not retry
+the same token. On refusal the CLI now prints the server's own admission to
+stderr (so `--json` stdout stays parseable) before the error propagates; `lh goal state <id>` reproduces that answer on demand.
+
+## Reading state
+
+### `lh goal state <id>` (alias `inspect`)
+
+`[--events <n>] [--json [fields]]`
+
+The one call that answers "why can this Goal not move?". It renders:
+
+- the Goal's status, `pausedBy`, subject carrier and agent
+- the **planning turn**: token, operation and its run status, `consumed`,
+ `failedTurns`, `dispatchNeverStarted`, `problem`
+- **snapshot / review**: the receipt hash the turn was pinned to next to what the
+ server computes now — the only place a "stale plan" becomes visible, because
+ these hashes are server-owned
+- **Admission**: whether a plan for this turn would be accepted, and if not, the
+ server's `code` (`stale_input`, `consumed`, `turn_settled`, `inactive`,
+ `pending_decision`, `budget_exhausted`, …) plus a one-line reading of it
+- the queue (unfinished tasks, pending decisions) and the newest events
+
+### `lh goal events <id>`
+
+`[-L, --limit <n>] [--cursor <token>] [--entity <type>] [--type <type>] [--json]`
+
+The audit trail, newest first. `--entity` filters
+`goal | node | edge | decision | task`; `--type` filters
+`created | updated | activated | resolved | rejected | retired | linked | unlinked`.
+`show`/`graph` embed only the newest 200 events; this command pages the whole log.
+
+Paging is by cursor, not offset: events are prepended while a goal runs, so an
+offset would re-serve a row a later insert pushed down. When a page is full the
+command prints the cursor to continue with (`--cursor "<iso>|<id>"`).
+
+### `lh goal show <id>` / `lh goal graph <id>`
+
+The graph snapshot: the header carries status, `pausedBy`, subject carrier and a
+planning-turn line; then a table of nodes with their incoming relations.
+`--json` returns the full snapshot including `decisions`, `events`, `spend`,
+`acceptances` and `runHeartbeats`.
+
+### `lh goal list`
+
+`[--agent <id>] [--project <id>] [--status <s>...] [--limit <n>]`
+
+Roll-up per Goal: task progress, findings, `NEEDS YOU` (pending decisions), cost.
+
+### `lh goal decisions <id>` / `supervision <id>`
+
+Durable decision gates; and recovery incidents with the effective recovery rate.
+
+## Submitting a plan
+
+### `lh goal plan <id>`
+
+`--token <turn token> --file <plan.json> [--operation <id>] [--json]`
+
+The file is one of:
+
+```json
+{ "action": "tasks", "reason": "...", "tasks": [{ "title": "...", "description": "...", "dependsOn": ["<task node ID>", 0] }] }
+{ "action": "verify", "reason": "..." }
+{ "action": "wait", "reason": "...", "until": "<future UTC ISO>", "event": { "type": "external.result", "key": "<job id>" } }
+{ "action": "retry", "taskId": "<failed task>", "failedOperationId": "<latest failure>", "reason": "..." }
+{ "action": "escalate", "reason": "...", "ask": { "question": "...", "options": [{ "id": "waive", "label": "...", "description": "...", "effect": "retry" }], "recommendedOptionId": "waive" } }
+```
+
+`dependsOn` accepts a task node ID from an earlier round or the 0-based index of
+an earlier task in the same plan. A later round without these links looks
+unrelated to the evidence it uses.
+
+`wait` is how a turn waits for time or external evidence — never sleep or poll.
+Producers deliver the event with `lh goal wake`.
+
+### `lh goal wake <id>`
+
+`--token <managerState.token> --event <id> --type <type> --key <key> [--summary] [--reference]`
+
+Delivers an external result to a specific wait. A wake asks the planner to
+reconsider evidence; it never proves success.
+
+### `lh goal report <id>`
+
+`--metadata-file <path> --content-file <path> [--operation <id>]`
+
+Submits the wrap-up report from the Goal's wrap-up run.
+
+## Lifecycle, budget and routing
+
+| Command | Effect |
+| ------------------------------------- | -------------------------------------------------------------------- |
+| `lh goal create <title>` | Create a standalone goal and seed its graph |
+| `lh goal pause <id>` / `resume <id>` | Stop / restart coordination (`--confirm-exit` settles a paused turn) |
+| `lh goal restart <id>` | Reset every unfinished task to backlog |
+| `lh goal delete <id>` | Delete the goal and its graph (`--yes`) |
+| `lh goal tick <id>` | Advance exactly one coordinator step |
+| `lh goal run <id>` | Tick until a stop condition |
+| `lh goal set-budget <id>` | Rounds / cost / experiments / turns / concurrency / attempts |
+| `lh goal set-agent <id> <agent>` | Hand supervision to another agent |
+| `lh goal set-task-agent <id> <agent>` | Route tasks to a dedicated executor (`none` hands them back) |
+| `lh goal bind-topic <id>` | Supervise from the current topic run |
+
+`create --topic` links a Goal to the conversation it was created from and
+returns a `turnToken` for the first plan; without it the Goal is standalone and
+never shows on that topic's goal tray.
+
+## Decision gates and graph editing
+
+| Command | Effect |
+| ------------------------------------------------- | ------------------------------------------------ |
+| `lh goal decide <id> <decision-id> --option <id>` | Resolve a durable decision gate |
+| `lh goal retire <id> <node-ids...>` | Retire nodes that must not run |
+| `lh goal add-node <id> <kind> <title>` | Add a node (`--scope`, `--question`, `-d`, `-p`) |
+| `lh goal add-edge <id> <source> <target> <kind>` | Connect two nodes |
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.ts
index 81b989b9268..e1701837882 100644
--- a/apps/cli/src/commands/goal.test.ts
+++ b/apps/cli/src/commands/goal.test.ts
@@ -1,3 +1,5 @@
+import { Buffer } from 'node:buffer';
+
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -14,6 +16,11 @@ const { mockClient } = vi.hoisted(() => ({
bindOperationTopic: { mutate: vi.fn() },
create: { mutate: vi.fn() },
delete: { mutate: vi.fn() },
+ events: { query: vi.fn() },
+ eventsOperation: { query: vi.fn() },
+ graphOperation: { query: vi.fn() },
+ planContext: { query: vi.fn() },
+ planContextOperation: { query: vi.fn() },
submitPlan: { mutate: vi.fn() },
submitOperationPlan: { mutate: vi.fn() },
submitOperationReport: { mutate: vi.fn() },
@@ -29,7 +36,12 @@ const { mockClient } = vi.hoisted(() => ({
}));
vi.mock('node:fs/promises', () => ({
- readFile: async () => JSON.stringify({ action: 'verify', reason: 'Ready' }),
+ readFile: async (path: string) => {
+ // A sentinel local failure so a test can prove the plan command keeps file
+ // errors out of the server-refusal diagnostic.
+ if (path === 'missing.json') throw new Error('ENOENT: no such file or directory');
+ return JSON.stringify({ action: 'verify', reason: 'Ready' });
+ },
}));
vi.mock('../utils/format', async (importOriginal) => ({
@@ -875,3 +887,329 @@ describe('goal event delivery', () => {
expect(output).toHaveBeenCalledWith(expect.stringContaining(`"accepted": ${accepted}`));
});
});
+
+const eventRow = {
+ actorType: 'system',
+ createdAt: new Date('2026-10-10T07:26:39.811Z'),
+ entityId: 'node-1',
+ entityType: 'node',
+ eventType: 'activated',
+ goalId: 'goal-1',
+ id: 'e1',
+ reason: 'Recovered an abandoned Task operation and started the next attempt',
+};
+
+/** A JWT-shaped string whose payload marks the caller as a device / gateway run. */
+const operationJwt = () =>
+ `x.${Buffer.from(JSON.stringify({ purpose: 'hetero-operation' })).toString('base64url')}.y`;
+
+const goalStateGraph = {
+ decisions: [],
+ edges: [],
+ events: [],
+ goal: {
+ agentId: 'agt-1',
+ config: {},
+ id: 'goal-1',
+ requirement: 'Migrate every client data resource to replica',
+ status: 'running',
+ subjectId: 'tpc-1',
+ subjectType: 'topic',
+ title: 'Replica migration',
+ },
+ nodes: [],
+ workVersions: [],
+};
+
+const goalStateContext = {
+ admission: { code: 'stale_input', message: 'Stale planning input; no plan applied', ok: false },
+ budget: {
+ blocked: false,
+ deadline: null,
+ maxRounds: 50,
+ maxTotalCost: 12,
+ runs: 12,
+ totalCost: 3.5,
+ },
+ goal: { agentId: 'agt-1', pausedBy: null, status: 'running' },
+ queue: { pendingDecisions: 0, unfinishedTasks: 4 },
+ review: { current: 'bbbbbbbbbbbb', recorded: 'bbbbbbbbbbbb' },
+ snapshot: { current: 'cccccccccccc', recorded: 'aaaaaaaaaaaa' },
+ turn: {
+ adopted: false,
+ consumed: false,
+ dispatchNeverStarted: false,
+ failedTurns: 0,
+ operationId: 'op-1',
+ opStatus: 'running',
+ problem: 'Automatic recovery could not start the next attempt',
+ problemTaskId: 'task-1',
+ retryAfter: null,
+ startedAt: '2026-10-09T17:47:59.776Z',
+ submitted: null,
+ token: 'goal-1_tok',
+ turns: 13,
+ },
+};
+
+describe('goal state command', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockClient.goal.graph.query.mockResolvedValue({ data: goalStateGraph });
+ mockClient.goal.planContext.query.mockResolvedValue({ data: goalStateContext });
+ mockClient.goal.events.query.mockResolvedValue({ data: { events: [], nextCursor: null } });
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ const output = () =>
+ vi
+ .mocked(console.log)
+ .mock.calls.map(([value]) => String(value))
+ .join('\n');
+
+ it('takes the verdict from the server instead of re-deriving it from the graph', async () => {
+ await createProgram().parseAsync(['node', 'test', 'goal', 'state', 'goal-1']);
+
+ expect(mockClient.goal.planContext.query).toHaveBeenCalledWith({ id: 'goal-1' });
+ expect(mockClient.goal.graph.query).toHaveBeenCalledWith({ id: 'goal-1' });
+ });
+
+ it('renders the planning turn, the moved snapshot and the admission code', async () => {
+ await createProgram().parseAsync(['node', 'test', 'goal', 'state', 'goal-1']);
+ const text = output();
+
+ expect(text).toContain('Planning turn #13');
+ expect(text).toContain('stale_input');
+ expect(text).toContain('the graph moved after this turn started');
+ expect(text).toContain('moved');
+ expect(text).toContain('4 unfinished task(s)');
+ // The requirement language is not the CLI's place to invent: the hint must
+ // come from the code, and the server's message must survive verbatim.
+ expect(text).toContain('Stale planning input; no plan applied');
+ });
+
+ it('renders recent events and lets --events 0 turn them off', async () => {
+ mockClient.goal.events.query.mockResolvedValue({
+ data: { events: [eventRow], nextCursor: null },
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'goal', 'state', 'goal-1', '--events', '5']);
+ expect(mockClient.goal.events.query).toHaveBeenCalledWith({ id: 'goal-1', limit: 5 });
+ expect(output()).toContain('Recovered an abandoned Task operation');
+
+ vi.mocked(console.log).mockClear();
+ mockClient.goal.events.query.mockClear();
+
+ await createProgram().parseAsync(['node', 'test', 'goal', 'state', 'goal-1', '--events', '0']);
+ expect(mockClient.goal.events.query).not.toHaveBeenCalled();
+ expect(output()).not.toContain('Recent events');
+ });
+
+ it('reads through the operation endpoints when this is a planning run', async () => {
+ vi.stubEnv('LOBEHUB_JWT', operationJwt());
+ mockClient.goal.graphOperation.query.mockResolvedValue({ data: goalStateGraph });
+ mockClient.goal.planContextOperation.query.mockResolvedValue({ data: goalStateContext });
+ mockClient.goal.eventsOperation.query.mockResolvedValue({
+ data: { events: [], nextCursor: null },
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'goal', 'state', 'goal-1']);
+
+ expect(mockClient.goal.graphOperation.query).toHaveBeenCalledWith({ id: 'goal-1' });
+ expect(mockClient.goal.planContextOperation.query).toHaveBeenCalledWith({ id: 'goal-1' });
+ // The ordinary routes refuse a hetero-operation token by design, so falling
+ // back to them would 401 exactly the run whose refusal this explains.
+ expect(mockClient.goal.graph.query).not.toHaveBeenCalled();
+ expect(mockClient.goal.planContext.query).not.toHaveBeenCalled();
+ });
+
+ it('renders an already-recorded plan as settled, not accepted', async () => {
+ mockClient.goal.planContext.query.mockResolvedValue({
+ data: { ...goalStateContext, admission: { code: 'duplicate', ok: true } },
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'goal', 'state', 'goal-1']);
+ const text = output();
+
+ expect(text).toContain('a plan is already recorded for this turn');
+ expect(text).not.toContain('would be accepted');
+ });
+});
+
+describe('goal plan refusal', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ const planArgs = ['node', 'test', 'goal', 'plan', 'goal-1', '--token', 'tok', '--file', 'p.json'];
+ const stdout = () =>
+ vi
+ .mocked(console.log)
+ .mock.calls.map(([value]) => String(value))
+ .join('\n');
+ const output = () =>
+ vi
+ .mocked(console.error)
+ .mock.calls.map(([value]) => String(value))
+ .join('\n');
+
+ it('explains the refusal from the server admission before the error propagates', async () => {
+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-env');
+ mockClient.goal.submitPlan.mutate.mockRejectedValue(
+ new Error('Stale planning input; no plan applied'),
+ );
+ mockClient.goal.planContext.query.mockResolvedValue({ data: goalStateContext });
+
+ await expect(createProgram().parseAsync(planArgs)).rejects.toThrow('Stale planning input');
+
+ expect(mockClient.goal.planContext.query).toHaveBeenCalledWith({
+ id: 'goal-1',
+ operationId: 'op-env',
+ // The submitted plan travels too: four guards (`existing_work`,
+ // `acceptance_escalate_only`, `wait_unsettled`, `wait_until_past`) only
+ // fire with a plan, so without it the read would report `ok` and explain
+ // nothing for exactly those refusals.
+ plan: { action: 'verify', reason: 'Ready' },
+ // The submitted token travels too: without it the verdict would name the
+ // next failing precondition instead of the token mismatch the server threw.
+ token: 'tok',
+ });
+ const text = output();
+ expect(text).toContain('Refused (stale_input)');
+ expect(text).toContain('snapshot');
+ expect(text).toContain('lh goal state goal-1');
+ });
+
+ it('keeps the refusal explanation off stdout under --json', async () => {
+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-env');
+ mockClient.goal.submitPlan.mutate.mockRejectedValue(
+ new Error('Stale planning input; no plan applied'),
+ );
+ mockClient.goal.planContext.query.mockResolvedValue({ data: goalStateContext });
+
+ await expect(createProgram().parseAsync([...planArgs, '--json'])).rejects.toThrow(
+ 'Stale planning input',
+ );
+
+ // Automation parses stdout as JSON; the human-readable verdict goes to stderr.
+ expect(stdout()).toBe('');
+ expect(output()).toContain('Refused (stale_input)');
+ });
+
+ it('never lets a failing diagnostic replace the original error', async () => {
+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-env');
+ mockClient.goal.submitPlan.mutate.mockRejectedValue(
+ new Error('Stale planning input; no plan applied'),
+ );
+ mockClient.goal.planContext.query.mockRejectedValue(new Error('network down'));
+
+ await expect(createProgram().parseAsync(planArgs)).rejects.toThrow('Stale planning input');
+ expect(output()).not.toContain('Refused');
+ });
+
+ it('keeps a local plan-file error out of the refusal diagnostic', async () => {
+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-env');
+ // The Goal's admission is a non-OK refusal DTO — standing in for "the CLI is
+ // ready to explain one" — and must still stay unprinted: a missing or
+ // malformed file never reached the server, so it is not a server refusal.
+ mockClient.goal.planContext.query.mockResolvedValue({
+ data: { ...goalStateContext, admission: { code: 'existing_work', ok: false } },
+ });
+
+ await expect(
+ createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'goal',
+ 'plan',
+ 'goal-1',
+ '--token',
+ 'tok',
+ '--file',
+ 'missing.json',
+ ]),
+ ).rejects.toThrow('ENOENT');
+
+ // The read happens before the mutation, so a local failure never submits and
+ // never asks for a diagnostic that would otherwise print "Refused (...)".
+ expect(mockClient.goal.submitPlan.mutate).not.toHaveBeenCalled();
+ expect(mockClient.goal.planContext.query).not.toHaveBeenCalled();
+ expect(output()).not.toContain('Refused');
+ });
+});
+
+describe('goal events command', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ const output = () =>
+ vi
+ .mocked(console.log)
+ .mock.calls.map(([value]) => String(value))
+ .join('\n');
+
+ it('pages the audit trail by cursor and passes every filter through', async () => {
+ const cursor = '2026-10-10T08:00:00.000Z|e9';
+ mockClient.goal.events.query.mockResolvedValue({
+ data: { events: [eventRow], nextCursor: cursor },
+ });
+
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'goal',
+ 'events',
+ 'goal-1',
+ '--limit',
+ '5',
+ '--cursor',
+ cursor,
+ '--entity',
+ 'node',
+ '--type',
+ 'activated',
+ '--json',
+ ]);
+
+ expect(mockClient.goal.events.query).toHaveBeenCalledWith({
+ id: 'goal-1',
+ cursor,
+ entityType: 'node',
+ eventType: 'activated',
+ limit: 5,
+ });
+ const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]));
+ expect(printed.events).toHaveLength(1);
+ expect(printed.events[0].id).toBe('e1');
+ expect(printed.nextCursor).toBe(cursor);
+ });
+
+ it('prints the continuation cursor so the next page is a copy-paste', async () => {
+ const cursor = '2026-10-10T08:00:00.000Z|e9';
+ mockClient.goal.events.query.mockResolvedValue({
+ data: { events: [eventRow], nextCursor: cursor },
+ });
+
+ await createProgram().parseAsync(['node', 'test', 'goal', 'events', 'goal-1', '--limit', '1']);
+
+ expect(output()).toContain(`--cursor "${cursor}"`);
+ });
+});
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index c34e60caa66..0f4537fbe54 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -2,9 +2,13 @@ import { readFile } from 'node:fs/promises';
import type {
GoalEdgeKind,
+ GoalEventEntityType,
+ GoalEventType,
GoalGraphDecision,
+ GoalGraphEvent,
GoalGraphSnapshot,
GoalNodeKind,
+ GoalPlanContext,
GoalTickResult,
} from '@lobechat/types';
import { type Command, Option } from 'commander';
@@ -124,8 +128,24 @@ const isSameWaitingState = (previous: GoalRunTickResult | undefined, current: Go
previous.taskId === current.taskId;
function printGraph(graph: GoalGraphSnapshot) {
- console.log(`\n${pc.bold(graph.goal.title)} ${pc.dim(graph.goal.id)} [${graph.goal.status}]`);
- if (graph.goal.requirement) console.log(`${pc.dim('Requirement:')} ${graph.goal.requirement}`);
+ const { goal } = graph;
+ console.log(
+ `\n${pc.bold(goal.title)} ${pc.dim(goal.id)} [${goal.status}${
+ goal.config?.pausedBy ? ` · paused by ${goal.config.pausedBy}` : ''
+ }]`,
+ );
+ if (goal.subjectType)
+ console.log(`${pc.dim('Subject:')} ${`${goal.subjectType} ${goal.subjectId ?? ''}`.trim()}`);
+ if (goal.requirement) console.log(`${pc.dim('Requirement:')} ${goal.requirement}`);
+ const turn = goal.config?.managerState;
+ const pending = graph.decisions.filter((decision) => decision.status === 'pending').length;
+ console.log(
+ `${pc.dim('Planning:')} ${
+ turn
+ ? `turn #${turn.turns} · started ${turn.startedAt}${turn.consumed ? ' · settled' : ''}`
+ : 'no planning turn'
+ }${pending > 0 ? pc.yellow(` · ${pending} decision(s) need you`) : ''}`,
+ );
const incoming = new Map<string, typeof graph.edges>();
for (const edge of graph.edges) {
const list = incoming.get(edge.targetNodeId) ?? [];
@@ -163,6 +183,207 @@ function printTick(result: GoalTickResult) {
if (result.nodeId) console.log(` ${pc.dim(`node: ${result.nodeId}`)}`);
}
+/** Recent events `lh goal state` shows unless a caller asks for another count. */
+const GOAL_EVENT_TAIL_DEFAULT = 10;
+
+/**
+ * A one-line reading of each admission code the server can return.
+ *
+ * Keyed by code, not by message: the server deliberately folds several causes
+ * ("the turn was consumed", "its run ended", "the graph moved") into the single
+ * `Stale planning input` message, so the message alone cannot say which
+ * precondition failed — which is exactly what the CLI is here to surface.
+ */
+const admissionHint: Record<string, string> = {
+ acceptance_escalate_only:
+ 'a failed Goal acceptance can only be escalated — it cannot be superseded by new work',
+ budget_exhausted: 'a budget bound is reached (rounds, cost or deadline)',
+ consumed: 'this turn was already settled; its plan cannot be submitted again',
+ duplicate:
+ 'a plan is already recorded for this turn; submitting again returns that receipt unchanged',
+ existing_work: 'unfinished work must be delivered before planning or verifying',
+ inactive: 'the Goal is not in an active state (planning or running)',
+ operation_mismatch: 'the token does not speak for the operation bound to this Goal',
+ pending_decision: 'a decision gate is still waiting on an answer',
+ review_changed: 'task review feedback changed after this turn started',
+ stale_input: 'the graph moved after this turn started, so the plan would apply to stale input',
+ turn_owner: 'this Goal has no matching planning turn',
+ turn_settled: "this turn's run is no longer running",
+ wait_unsettled: 'unfinished work must be settled before waiting',
+ wait_until_past: 'the wait deadline is already in the past',
+};
+
+const toIso = (value: Date | string) =>
+ value instanceof Date ? value.toISOString() : new Date(value).toISOString();
+
+const shortHash = (hash?: string | null) => (hash ? `${hash.slice(0, 12)}…` : '—');
+
+/**
+ * Recorded receipt against what the server computes now. The snapshot a plan is
+ * validated against is server-owned — a client cannot recompute it — so this is
+ * the one place the "why was my plan stale" comparison becomes visible.
+ */
+const compareHash = (recorded: string | null, current?: string) => {
+ if (!current) return pc.dim('unavailable');
+ if (!recorded) return `${shortHash(current)} ${pc.dim('(no receipt)')}`;
+ return current === recorded
+ ? `${shortHash(current)} ${pc.dim('matches receipt')}`
+ : `${shortHash(recorded)} → ${shortHash(current)} ${pc.yellow('moved')}`;
+};
+
+/** The same comparison without color, for a message that is not a console line. */
+const compareHashPlain = (recorded: string | null, current?: string) => {
+ if (!current) return 'unavailable';
+ if (!recorded) return `${shortHash(current)} (no receipt)`;
+ return current === recorded
+ ? `${shortHash(current)} matches receipt`
+ : `${shortHash(recorded)} → ${shortHash(current)} MOVED`;
+};
+
+function printGoalState(
+ graph: GoalGraphSnapshot,
+ context: GoalPlanContext,
+ events: GoalGraphEvent[],
+) {
+ const { goal } = graph;
+ const field = (label: string, value: string) =>
+ console.log(` ${pc.dim(label.padEnd(11))} ${value}`);
+
+ console.log(`\n${pc.bold(goal.title)} ${pc.dim(goal.id)}`);
+ field(
+ 'Status',
+ `${context.goal.status}${
+ context.goal.pausedBy ? pc.yellow(` (paused by ${context.goal.pausedBy})`) : ''
+ }`,
+ );
+ field(
+ 'Subject',
+ goal.subjectType ? `${goal.subjectType} ${goal.subjectId ?? ''}`.trim() : 'standalone',
+ );
+ field('Agent', context.goal.agentId ?? '—');
+ if (goal.requirement) field('Requirement', truncate(goal.requirement, 96));
+ if (context.budget) {
+ const cap =
+ context.budget.maxTotalCost === null
+ ? ''
+ : `/${Number(context.budget.maxTotalCost).toFixed(2)}`;
+ field(
+ 'Budget',
+ `runs ${context.budget.runs}/${context.budget.maxRounds ?? '∞'} · $${context.budget.totalCost.toFixed(2)}${cap}${
+ context.budget.deadline ? ` · deadline ${context.budget.deadline}` : ''
+ }${context.budget.blocked ? pc.red(' · exhausted') : ''}`,
+ );
+ }
+
+ if (context.turn) {
+ const { turn } = context;
+ console.log(
+ `\n ${pc.bold(`Planning turn #${turn.turns}`)} ${pc.dim(`started ${turn.startedAt}`)}`,
+ );
+ field('token', turn.token);
+ field(
+ 'operation',
+ `${turn.operationId ?? '—'}${turn.opStatus ? pc.dim(` (${turn.opStatus})`) : ''}`,
+ );
+ field(
+ 'receipt',
+ `consumed ${turn.consumed} · failedTurns ${turn.failedTurns} · neverStarted ${turn.dispatchNeverStarted} · adopted ${turn.adopted}`,
+ );
+ field('snapshot', compareHash(context.snapshot.recorded, context.snapshot.current));
+ field('review', compareHash(context.review.recorded, context.review.current));
+ if (turn.problem)
+ field('problem', `${turn.problemTaskId ?? '—'} · ${truncate(turn.problem, 60)}`);
+ if (turn.submitted)
+ field('submitted', `${turn.submitted.action} · ${truncate(turn.submitted.reason, 60)}`);
+ if (turn.retryAfter) field('retryAfter', turn.retryAfter);
+ } else {
+ console.log(`\n ${pc.dim('No planning turn recorded for this Goal.')}`);
+ }
+
+ const { admission } = context;
+ // `duplicate` is `ok` (nothing is refused) but is NOT an invitation to plan:
+ // the turn already holds a submitted plan, and `submit` returns that receipt
+ // instead of applying a new one, so it must not read as "accepted".
+ const alreadyRecorded = admission.code === 'duplicate';
+ console.log(
+ `\n ${pc.bold('Admission')} ${
+ alreadyRecorded
+ ? pc.yellow('◆ a plan is already recorded for this turn — a new one will not replace it')
+ : admission.ok
+ ? pc.green('✓ a plan for the current turn would be accepted')
+ : pc.red(`✗ refused — ${admission.code}`)
+ }`,
+ );
+ if (!admission.ok) {
+ const hint = admissionHint[admission.code];
+ if (hint) console.log(` ${pc.dim(hint)}`);
+ if (admission.message) console.log(` ${admission.message}`);
+ }
+
+ if (context.queue)
+ field(
+ 'Queue',
+ `${context.queue.unfinishedTasks} unfinished task(s) · ${context.queue.pendingDecisions} pending decision(s)`,
+ );
+
+ if (events.length > 0) {
+ console.log(`\n ${pc.bold('Recent events')} ${pc.dim(`(newest ${events.length})`)}`);
+ for (const event of events)
+ console.log(
+ ` ${pc.dim(toIso(event.createdAt))} ${event.entityType} ${event.eventType}${
+ event.reason ? ` ${truncate(event.reason, 76)}` : ''
+ }`,
+ );
+ }
+}
+
+/**
+ * The plan shape `goal.planContext` accepts, read off the client so the two
+ * cannot drift. A refused `lh goal plan` re-reads the admission with the plan it
+ * just submitted: four guards (`existing_work`, `acceptance_escalate_only`,
+ * `wait_unsettled`, `wait_until_past`) only fire when a plan is present, so
+ * omitting it would report `ok` and explain nothing.
+ */
+type PlanInput = NonNullable<
+ Parameters<Awaited<ReturnType<typeof getTrpcClient>>['goal']['planContext']['query']>[0]['plan']
+>;
+
+/**
+ * Explain a refused `lh goal plan` from the server's own admission, so an
+ * operator does not have to re-derive it from the graph. Best-effort: a
+ * diagnostic that itself fails must never replace the real error.
+ */
+async function explainPlanRefusal(
+ id: string,
+ options: { operation?: string; plan?: PlanInput; token?: string },
+): Promise<string | undefined> {
+ try {
+ const reads = await goalReads();
+ const { data } = await reads.planContext.query({
+ id,
+ operationId: options.operation ?? process.env.LOBEHUB_OPERATION_ID,
+ plan: options.plan,
+ token: options.token,
+ });
+ if (data.admission.ok) return undefined;
+ const lines = [`Refused (${data.admission.code}): ${admissionHint[data.admission.code] ?? ''}`];
+ if (data.admission.message) lines.push(` ${data.admission.message}`);
+ if (data.turn) {
+ lines.push(
+ ` turn #${data.turn.turns} started ${data.turn.startedAt} · consumed ${data.turn.consumed} · run ${
+ data.turn.opStatus ?? 'n/a'
+ }`,
+ );
+ lines.push(` snapshot ${compareHashPlain(data.snapshot.recorded, data.snapshot.current)}`);
+ lines.push(` review ${compareHashPlain(data.review.recorded, data.review.current)}`);
+ }
+ lines.push(` Inspect with: lh goal state ${id}`);
+ return lines.join('\n');
+ } catch {
+ return undefined;
+ }
+}
+
/**
* Whether this process runs with a server-minted operation token (device and
* gateway runs) rather than the user's own login. Operation tokens are refused
@@ -182,6 +403,30 @@ const hasOperationToken = () => {
}
};
+/**
+ * The Goal reads `lh goal show` / `state` / `events` use, picked by credential.
+ *
+ * A device or gateway planning run holds a `hetero-operation` JWT, and the
+ * server's ordinary authed routes refuse that by design — so the same reads have
+ * an operation-authenticated twin. Runs holding one are exactly the runs whose
+ * refusal these commands exist to explain, so they must not be the ones that
+ * cannot read.
+ */
+const goalReads = async () => {
+ const client = await getTrpcClient();
+ return hasOperationToken()
+ ? {
+ events: client.goal.eventsOperation,
+ graph: client.goal.graphOperation,
+ planContext: client.goal.planContextOperation,
+ }
+ : {
+ events: client.goal.events,
+ graph: client.goal.graph,
+ planContext: client.goal.planContext,
+ };
+};
+
export function registerGoalCommand(program: Command) {
const goal = program.command('goal').description('Run long-horizon Goal Graphs');
goal
@@ -243,19 +488,36 @@ export function registerGoalCommand(program: Command) {
) => {
const operationId = options.operation ?? process.env.LOBEHUB_OPERATION_ID;
if (!operationId) throw new Error('Current manager operation ID required');
+ // Read and parse the plan BEFORE any network call: a missing or malformed
+ // file is a local error, and must not be dressed up as a server refusal
+ // just because the Goal's own admission happens to be non-OK.
+ const plan = JSON.parse(await readFile(options.file, 'utf8'));
const client = await getTrpcClient();
const endpoint = hasOperationToken()
? client.goal.submitOperationPlan
: client.goal.submitPlan;
- const result = await endpoint.mutate({
- id,
- token: options.token,
- operationId,
- plan: JSON.parse(await readFile(options.file, 'utf8')),
- });
- if (options.json) outputJson(result.data);
- else
- console.log('Plan recorded; the coordinator will continue after this Agent turn exits.');
+ try {
+ const result = await endpoint.mutate({ id, token: options.token, operationId, plan });
+ if (options.json) outputJson(result.data);
+ else
+ console.log(
+ 'Plan recorded; the coordinator will continue after this Agent turn exits.',
+ );
+ } catch (error) {
+ // A refusal is a verdict about this turn, so print the server's own
+ // admission before the error propagates: the bare message ("Stale
+ // planning input") cannot say which precondition failed. The plan
+ // travels with it — the read is only as specific as the plan it sees.
+ // stderr, not stdout: `--json` callers parse stdout, and a refusal
+ // must not turn it into prose.
+ const explanation = await explainPlanRefusal(id, {
+ operation: options.operation,
+ plan,
+ token: options.token,
+ });
+ if (explanation) console.error(explanation);
+ throw error;
+ }
},
);
@@ -473,7 +735,8 @@ export function registerGoalCommand(program: Command) {
});
const show = async (id: string, options: { json?: boolean | string }) => {
- const result = await (await getTrpcClient()).goal.graph.query({ id });
+ const reads = await goalReads();
+ const result = await reads.graph.query({ id });
if (options.json !== undefined) return outputJson(result.data, options.json);
printGraph(result.data);
};
@@ -488,6 +751,77 @@ export function registerGoalCommand(program: Command) {
.option('--json [fields]', 'Output JSON')
.action(show);
+ goal
+ .command('state <id>')
+ .alias('inspect')
+ .description('Explain why this Goal will or will not accept a plan right now')
+ .option(
+ '--events <n>',
+ 'Recent events to include (0 disables)',
+ String(GOAL_EVENT_TAIL_DEFAULT),
+ )
+ .option('--json [fields]', 'Output JSON')
+ .action(async (id: string, options: { events: string; json?: boolean | string }) => {
+ const reads = await goalReads();
+ const tail = Math.max(0, Number.parseInt(options.events, 10) || 0);
+ const [graph, context] = await Promise.all([
+ reads.graph.query({ id }),
+ reads.planContext.query({ id }),
+ ]);
+ const events = tail > 0 ? (await reads.events.query({ id, limit: tail })).data.events : [];
+ if (options.json !== undefined) return outputJson({ ...context.data, events }, options.json);
+ printGoalState(graph.data, context.data, events);
+ });
+
+ goal
+ .command('events <id>')
+ .description("List this Goal's audit trail, newest first")
+ .option('-L, --limit <n>', 'Events to fetch', '50')
+ .option('--cursor <token>', 'Continue from the previous page (the token it printed)')
+ .option('--entity <type>', 'Filter by entity: goal | node | edge | decision | task')
+ .option(
+ '--type <type>',
+ 'Filter by event: created | updated | activated | resolved | rejected | retired | linked | unlinked',
+ )
+ .option('--json [fields]', 'Output JSON')
+ .action(
+ async (
+ id: string,
+ options: {
+ cursor?: string;
+ entity?: GoalEventEntityType;
+ json?: boolean | string;
+ limit: string;
+ type?: GoalEventType;
+ },
+ ) => {
+ const reads = await goalReads();
+ const result = await reads.events.query({
+ id,
+ cursor: options.cursor,
+ entityType: options.entity,
+ eventType: options.type,
+ limit: Number.parseInt(options.limit, 10),
+ });
+ if (options.json !== undefined) return outputJson(result.data, options.json);
+ if (result.data.events.length === 0) return log.info('No events.');
+ printTable(
+ result.data.events.map((event) => [
+ toIso(event.createdAt),
+ `${event.entityType} ${event.eventType}`,
+ event.actorType,
+ truncate(event.reason ?? '-', 64),
+ event.id,
+ ]),
+ ['TIME', 'EVENT', 'ACTOR', 'REASON', 'EVENT ID'],
+ );
+ if (result.data.nextCursor)
+ console.log(
+ pc.dim(`\nMore may follow — continue with --cursor "${result.data.nextCursor}"`),
+ );
+ },
+ );
+
goal
.command('supervision <id>')
.description('Inspect recovery incidents, diagnostic topic and effective recovery rate')
diff --git a/apps/server/src/routers/lambda/__tests__/goal.operationRead.test.ts b/apps/server/src/routers/lambda/__tests__/goal.operationRead.test.ts
new file mode 100644
index 00000000000..5e27c45bbed
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/goal.operationRead.test.ts
@@ -0,0 +1,138 @@
+// @vitest-environment node
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+// The operation token is classified by the real middleware; only the claim
+// validator is stubbed, so `heteroAuthKind` is decided the way production does.
+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ validateHeteroOperationClaims: vi.fn((claims: Record<string, unknown> | undefined) =>
+ claims?.purpose === 'hetero-operation'
+ ? { capabilities: ['hetero:ingest'], operation_id: 'op_1', sub: claims.sub }
+ : undefined,
+ ),
+}));
+
+const mockResolve = vi.fn();
+vi.mock('@/server/services/heterogeneousAgent/operationPrincipal', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ resolveActiveHeteroOperationPrincipal: mockResolve,
+}));
+
+const mockGraph = vi.fn();
+vi.mock('@/server/services/goal', () => ({
+ GoalService: vi.fn(function () {
+ return { graph: mockGraph };
+ }),
+}));
+
+const mockAdmission = vi.fn();
+const mockAssertOwnsTurn = vi.fn();
+vi.mock('@/server/services/goal/manager', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ GoalManagerService: vi.fn(function () {
+ return { admission: mockAdmission, assertOperationOwnsTurn: mockAssertOwnsTurn };
+ }),
+}));
+
+const { goalRouter } = await import('../goal');
+
+const caller = (authKind: 'operation' | 'user') =>
+ goalRouter.createCaller({
+ jwtPayload: { userId: 'user-1' },
+ oidcAuth: {
+ ...(authKind === 'operation' ? { purpose: 'hetero-operation' } : {}),
+ sub: 'user-1',
+ },
+ serverDB: {},
+ userId: 'user-1',
+ } as never);
+
+describe('goalRouter operation reads', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockResolve.mockResolvedValue({ operationId: 'op_1', userId: 'user-1', workspaceId: 'ws-1' });
+ // The guard resolves the Goal's current turn itself; mocks only its wiring.
+ mockAssertOwnsTurn.mockResolvedValue(undefined);
+ mockGraph.mockResolvedValue({ goal: { id: 'goal_1' } });
+ mockAdmission.mockResolvedValue({ admission: { code: 'ok', ok: true } });
+ });
+
+ it('refuses an ordinary user token — this surface is not a wider read', async () => {
+ await expect(caller('user').graphOperation({ id: 'goal_1' })).rejects.toThrow(
+ 'An operation-bound token is required',
+ );
+ });
+
+ it('reads under the operation principal, pinned to the token’s own operation', async () => {
+ const result = await caller('operation').graphOperation({ id: 'goal_1' });
+
+ expect(mockResolve).toHaveBeenCalledWith(
+ expect.objectContaining({ capability: 'hetero:ingest', operationId: 'op_1' }),
+ );
+ expect(mockGraph).toHaveBeenCalledWith('goal_1');
+ expect(result.data).toEqual({ goal: { id: 'goal_1' } });
+ });
+
+ it('serves the plan context and the audit trail through the same guard', async () => {
+ await expect(caller('user').planContextOperation({ id: 'goal_1' })).rejects.toThrow(
+ 'An operation-bound token is required',
+ );
+
+ const context = await caller('operation').planContextOperation({ id: 'goal_1' });
+ expect(context.data).toEqual({ admission: { code: 'ok', ok: true } });
+ // The turn's own token is not supplied, so the read falls back to the
+ // recorded one — an operation may read without resubmitting.
+ expect(mockAdmission).toHaveBeenCalledWith('goal_1', {
+ operationId: undefined,
+ token: undefined,
+ });
+ });
+
+ it('refuses a Goal whose current turn belongs to another operation', async () => {
+ // A `hetero:ingest` token is held by runs that never plan, so holding one must
+ // not let a run read a Goal it does not own — least of all the manager state
+ // and planning token `planContext` returns.
+ const refusal = new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'This run does not own the current planning turn of this goal',
+ });
+ mockAssertOwnsTurn.mockRejectedValue(refusal);
+
+ await expect(caller('operation').graphOperation({ id: 'goal_2' })).rejects.toThrow(
+ 'does not own',
+ );
+ await expect(caller('operation').planContextOperation({ id: 'goal_2' })).rejects.toThrow(
+ 'does not own',
+ );
+ await expect(caller('operation').eventsOperation({ id: 'goal_2' })).rejects.toThrow(
+ 'does not own',
+ );
+
+ // Refused before touching the Goal's graph, manager state or audit trail.
+ expect(mockGraph).not.toHaveBeenCalled();
+ expect(mockAdmission).not.toHaveBeenCalled();
+ // Every read asked the same question, of the Goal it was handed.
+ expect(mockAssertOwnsTurn.mock.calls).toEqual([
+ ['goal_2', 'op_1'],
+ ['goal_2', 'op_1'],
+ ['goal_2', 'op_1'],
+ ]);
+ });
+
+ it('refuses an operation read of a Goal it cannot see', async () => {
+ mockAssertOwnsTurn.mockRejectedValue(
+ new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' }),
+ );
+
+ await expect(caller('operation').graphOperation({ id: 'goal-missing' })).rejects.toThrow(
+ 'Goal not found',
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 6dd6d5b620b..3cd42fa384d 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -186,6 +186,142 @@ function mapGoalError(error: unknown, operation: string): never {
});
}
+/** `<ISO>|<event id>` — opaque to callers, so the pair can change shape later. */
+const encodeEventCursor = (cursor: { createdAt: Date; id: string }) =>
+ `${cursor.createdAt.toISOString()}|${cursor.id}`;
+
+const decodeEventCursor = (raw: string) => {
+ const separator = raw.lastIndexOf('|');
+ const createdAt = separator > 0 ? new Date(raw.slice(0, separator)) : new Date(Number.NaN);
+ const id = separator > 0 ? raw.slice(separator + 1) : '';
+ if (Number.isNaN(createdAt.getTime()) || !id) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid events cursor' });
+ }
+ return { createdAt, id };
+};
+
+/**
+ * Events paging is cursor-based, not offset-based: the feed is live and events
+ * are PREPENDED while a goal runs, so an offset taken on page one re-serves a row
+ * that a later insert pushed down.
+ */
+const eventsInput = idInput.extend({
+ cursor: z.string().min(1).optional(),
+ entityType: z.enum(['goal', 'node', 'edge', 'decision', 'task']).optional(),
+ eventType: z
+ .enum([
+ 'created',
+ 'updated',
+ 'activated',
+ 'resolved',
+ 'rejected',
+ 'retired',
+ 'linked',
+ 'unlinked',
+ ])
+ .optional(),
+ limit: z.number().int().min(1).max(200).optional(),
+});
+
+const planContextInput = idInput.extend({
+ operationId: z.string().min(1).optional(),
+ // A refused `lh goal plan` re-reads this with the plan it just submitted, so
+ // the plan-specific guards it was refused on (`existing_work`,
+ // `acceptance_escalate_only`, `wait_unsettled`, `wait_until_past`) are
+ // re-evaluated. Without it the read would report `ok` and explain nothing.
+ plan: goalPlanSchema.optional(),
+ token: z.string().min(1).optional(),
+});
+
+type EventsInput = z.infer<typeof eventsInput>;
+type PlanContextInput = z.infer<typeof planContextInput>;
+
+/** Shared by the ordinary and the operation-authenticated read; the caller builds the manager. */
+const readPlanContext = (manager: GoalManagerService, input: PlanContextInput) =>
+ manager.admission(input.id, {
+ operationId: input.operationId,
+ plan: input.plan,
+ token: input.token,
+ });
+
+const readEvents = async (goalService: GoalService, input: EventsInput) => {
+ const page = await goalService.listEvents(input.id, {
+ cursor: input.cursor ? decodeEventCursor(input.cursor) : undefined,
+ entityType: input.entityType,
+ eventType: input.eventType,
+ limit: input.limit ?? 50,
+ });
+ return {
+ events: page.events,
+ nextCursor: page.nextCursor ? encodeEventCursor(page.nextCursor) : null,
+ };
+};
+
+/**
+ * The Goal reads a device / gateway planning run needs.
+ *
+ * Those runs hold a `hetero-operation` JWT, and `oidcAuth` deliberately refuses
+ * it on ordinary authed routes so a leaked sandbox token cannot be replayed
+ * elsewhere — which left a planner unable to read the very Goal it plans, and
+ * made `lh goal state` (and the refusal explanation) unauthorized in exactly the
+ * runs that need them. These mirror the ordinary reads for that caller only:
+ * writes stay on `goalWriteProcedure`, and scope comes from the operation's own
+ * principal.
+ *
+ * The capability is `hetero:ingest` rather than `goal:manage` because the token
+ * a takeover planning turn holds never carries `goal:manage` — that is granted
+ * only to the `/goal` message that creates a goal, so requiring it would leave
+ * the planner locked out. `hetero:ingest` is what the same token already uses to
+ * submit its plan.
+ *
+ * `allowTerminalOperation` is deliberately unset: reads of a run that has already
+ * ended are an ordinary-session job, so the token works exactly while its turn
+ * runs.
+ *
+ * Scope is the operation's principal AND its Goal: every endpoint calls
+ * `GoalManagerService.assertOperationOwnsTurn`, so a token reaches exactly the
+ * Goal whose current turn it holds — not any Goal in the workspace whose id it
+ * learns.
+ */
+const goalOperationReadProcedure = heteroAuthedProcedure.use(serverDatabase).use(async (opts) => {
+ if (opts.ctx.heteroAuthKind !== 'operation' || !opts.ctx.heteroOperation) {
+ throw new TRPCError({
+ code: 'UNAUTHORIZED',
+ message: 'An operation-bound token is required',
+ });
+ }
+ let principal;
+ try {
+ principal = await resolveActiveHeteroOperationPrincipal({
+ capability: 'hetero:ingest',
+ claims: opts.ctx.heteroOperation,
+ db: opts.ctx.serverDB,
+ operationId: opts.ctx.heteroOperation.operation_id,
+ });
+ } catch (error) {
+ if (!(error instanceof HeteroOperationPrincipalError)) throw error;
+ throw new TRPCError({
+ cause: error,
+ code: error.status === 401 ? 'UNAUTHORIZED' : error.status === 409 ? 'CONFLICT' : 'FORBIDDEN',
+ message: error.message,
+ });
+ }
+ return opts.next({
+ ctx: {
+ goalManager: new GoalManagerService(
+ opts.ctx.serverDB,
+ principal.userId,
+ principal.workspaceId,
+ ),
+ goalService: new GoalService(opts.ctx.serverDB, principal.userId, principal.workspaceId),
+ // The operation the token was minted for — not an id the caller supplies.
+ heteroOperationId: principal.operationId,
+ userId: principal.userId,
+ workspaceId: principal.workspaceId ?? null,
+ },
+ });
+});
+
export const goalRouter = router({
wake: goalWriteProcedure
.input(goalWakeEventSchema.extend({ id: z.string() }))
@@ -805,6 +941,70 @@ export const goalRouter = router({
}
}),
+ /**
+ * Why `submitPlan` would accept or refuse a plan right now, without writing.
+ *
+ * `lh goal state` renders it and a refused `lh goal plan` re-reads it, so the
+ * CLI explains a refusal from the same predicates the write path uses — the
+ * manager and review snapshots a client cannot see from the graph alone.
+ */
+ planContext: goalProcedure.input(planContextInput).query(async ({ ctx, input }) => {
+ try {
+ const manager = new GoalManagerService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ return { data: await readPlanContext(manager, input), success: true };
+ } catch (error) {
+ mapGoalError(error, 'read the plan context of');
+ }
+ }),
+
+ /**
+ * The goal's audit trail, newest first, paged past the capped copy `graph`
+ * bundles. `lh goal events` reads it.
+ */
+ events: goalProcedure.input(eventsInput).query(async ({ ctx, input }) => {
+ try {
+ return { data: await readEvents(ctx.goalService, input), success: true };
+ } catch (error) {
+ mapGoalError(error, 'list events of');
+ }
+ }),
+
+ // The same three reads for a planning run that holds an operation token, which
+ // the ordinary `goalProcedure` above refuses — see `goalOperationReadProcedure`.
+
+ graphOperation: goalOperationReadProcedure.input(idInput).query(async ({ ctx, input }) => {
+ try {
+ await ctx.goalManager.assertOperationOwnsTurn(input.id, ctx.heteroOperationId);
+ return { data: await ctx.goalService.graph(input.id), success: true };
+ } catch (error) {
+ mapGoalError(error, 'graph');
+ }
+ }),
+
+ planContextOperation: goalOperationReadProcedure
+ .input(planContextInput)
+ .query(async ({ ctx, input }) => {
+ try {
+ await ctx.goalManager.assertOperationOwnsTurn(input.id, ctx.heteroOperationId);
+ return { data: await readPlanContext(ctx.goalManager, input), success: true };
+ } catch (error) {
+ mapGoalError(error, 'read the plan context of');
+ }
+ }),
+
+ eventsOperation: goalOperationReadProcedure.input(eventsInput).query(async ({ ctx, input }) => {
+ try {
+ await ctx.goalManager.assertOperationOwnsTurn(input.id, ctx.heteroOperationId);
+ return { data: await readEvents(ctx.goalService, input), success: true };
+ } catch (error) {
+ mapGoalError(error, 'list events of');
+ }
+ }),
+
/**
* List goals with their graph roll-up: how many Tasks are done, how many
* decision gates wait on a human, and what the exploration has cost.
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index b5f4706f3d6..205f41f80c1 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -13,6 +13,8 @@ import type {
GoalCreateConfig,
GoalDecisionOption,
GoalEdgeKind,
+ GoalEventEntityType,
+ GoalEventType,
GoalGraphNode,
GoalGraphSnapshot,
GoalItem,
@@ -884,6 +886,26 @@ export class GoalService {
return { ...graph, acceptances, assignees, deliveredAt, report, runHeartbeats, spend };
};
+ /**
+ * The goal's audit trail, newest first, paged past the capped copy `graph()`
+ * carries. `graph()` stays the shape the page reads; this is for a reader
+ * chasing one transition — the pause that explains why a plan was refused
+ * hours into a run, say. Returns the cursor that continues the page.
+ */
+ listEvents = async (
+ goalId: string,
+ options: {
+ cursor?: { createdAt: Date; id: string };
+ entityType?: GoalEventEntityType;
+ eventType?: GoalEventType;
+ limit: number;
+ },
+ ) => {
+ const page = await this.graphModel.listEvents(goalId, options);
+ if (!page) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ return page;
+ };
+
/**
* The agent each dispatched task node is assigned to. Read from the Task row
* rather than the goal config: a task can be reassigned on its own, and the
diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.ts
index f7bb1ac485b..01e2dab40a6 100644
--- a/apps/server/src/services/goal/manager.test.ts
+++ b/apps/server/src/services/goal/manager.test.ts
@@ -4,7 +4,7 @@ import {
GOAL_COORDINATOR_ACTOR_ID,
GOAL_MANAGER_QUESTION_TITLE,
} from '@lobechat/const/goal';
-import { eq } from 'drizzle-orm';
+import { eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '@/database/core/getTestDB';
@@ -739,6 +739,179 @@ describe('CLI main Agent planning', () => {
await expect(manager().submit(id, state.token, op.id, taskPlan)).resolves.toBeTruthy();
});
+ it('names on the read path the refusal submit folds into one message', async () => {
+ const { id, state, op } = await start();
+
+ // A live, unchanged turn: both paths agree a plan would apply.
+ expect((await manager().admission(id)).admission).toMatchObject({ code: 'ok', ok: true });
+
+ // The same changed graph `submit` refuses — but admission says WHICH
+ // precondition failed, where the shared message says only "Stale planning
+ // input". This is the answer `lh goal state` renders.
+ await new GoalGraphModel(db, userId).createNode(id, {
+ title: 'Changed input',
+ kind: 'finding',
+ });
+ expect((await manager().admission(id)).admission).toMatchObject({
+ code: 'stale_input',
+ ok: false,
+ });
+ await expect(manager().submit(id, state.token, op.id, taskPlan)).rejects.toThrow('Stale');
+
+ // A pause is its own code, not the same "the graph moved" answer.
+ await service().pause(id);
+ expect((await manager().admission(id)).admission).toMatchObject({
+ code: 'inactive',
+ ok: false,
+ });
+
+ // A token that is not this turn's is named as such, rather than reported as
+ // whatever precondition happens to fail next.
+ expect((await manager().admission(id, { token: 'not-the-token' })).admission).toMatchObject({
+ code: 'turn_owner',
+ ok: false,
+ });
+ });
+
+ it('re-derives the plan-specific refusals the read path would otherwise call ok', async () => {
+ const { id, state, op } = await start();
+
+ // `existing_work` and `wait_until_past` only fire when a plan is present. A
+ // read that does not see the plan therefore reports `ok`, and `lh goal plan`
+ // prints no explanation for exactly the refusals that need one. Feed the plan
+ // and the read matches what `submit` refuses on.
+ const verifyPlan = { action: 'verify' as const, reason: 'Compare results' };
+ expect((await manager().admission(id, { plan: verifyPlan })).admission).toMatchObject({
+ code: 'existing_work',
+ ok: false,
+ });
+ await expect(manager().submit(id, state.token, op.id, verifyPlan)).rejects.toThrow(
+ 'Existing work',
+ );
+
+ const pastWait = {
+ action: 'wait' as const,
+ reason: 'Let tasks settle',
+ until: new Date(Date.now() - 1000).toISOString(),
+ };
+ expect((await manager().admission(id, { plan: pastWait })).admission).toMatchObject({
+ code: 'wait_until_past',
+ ok: false,
+ });
+ await expect(manager().submit(id, state.token, op.id, pastWait)).rejects.toThrow(
+ 'Wait until must be in the future',
+ );
+
+ // With no plan the read still answers the non-plan question.
+ expect((await manager().admission(id)).admission).toMatchObject({ code: 'ok', ok: true });
+ });
+
+ it('authorizes a read from the turn’s own operation before its id reaches the receipt', async () => {
+ const { id, op } = await start();
+
+ // `advance` saves `managerState.operationId` only after the dispatched run's
+ // `execAgent` resolves, so a fast run is live and holding a token while the
+ // field is still absent (and if that save fails it never arrives, yet the turn
+ // is live and `submit` still succeeds). Ownership must therefore come from the
+ // topic/source-message lookup `submit` uses, not the receipt field.
+ const goal = (await model().findById(id))!;
+ const { operationId: _unpersisted, ...managerState } = goal.config!.managerState!;
+ await db
+ .update(goals)
+ .set({ config: { ...goal.config, managerState } })
+ .where(eq(goals.id, id));
+ expect((await model().findById(id))!.config!.managerState!.operationId).toBeUndefined();
+
+ await expect(manager().assertOperationOwnsTurn(id, op.id)).resolves.toBeUndefined();
+ await expect(manager().assertOperationOwnsTurn(id, 'op-someone-else')).rejects.toThrow(
+ 'does not own',
+ );
+ await expect(manager().assertOperationOwnsTurn('goal-missing', op.id)).rejects.toThrow(
+ 'Goal not found',
+ );
+ });
+
+ it('pages the goal audit trail by cursor and refuses another owner', async () => {
+ const { id } = await start();
+ const graph = new GoalGraphModel(db, userId);
+ // A second event, so paging has something to page over.
+ await graph.createNode(id, { title: 'Extra finding', kind: 'finding' });
+ const first = await graph.listEvents(id, { limit: 50 });
+ const all = first!.events;
+
+ expect(all.length).toBeGreaterThan(1);
+ expect(all[0]!.createdAt.getTime()).toBeGreaterThanOrEqual(all.at(-1)!.createdAt.getTime());
+
+ const page = await graph.listEvents(id, { limit: 1 });
+ expect(page!.events).toHaveLength(1);
+ expect(page!.nextCursor).toBeDefined();
+ // The cursor continues on the second-newest row...
+ const next = await graph.listEvents(id, { cursor: page!.nextCursor!, limit: 1 });
+ expect(next!.events[0]!.id).toBe(all[1]!.id);
+
+ // ...and still does after a live insert. This is why the page is keyed by
+ // `(createdAt, id)` and not an offset: events are PREPENDED while a goal
+ // runs, so `offset=2` would re-serve a row a new event pushed down.
+ await graph.createNode(id, { title: 'Inserted between pages', kind: 'finding' });
+ const afterInsert = await graph.listEvents(id, { cursor: page!.nextCursor!, limit: 1 });
+ expect(afterInsert!.events[0]!.id).toBe(all[1]!.id);
+
+ // The last page reports no continuation, so a caller can stop paging.
+ const last = await graph.listEvents(id, { limit: 200 });
+ expect(last!.nextCursor).toBeUndefined();
+
+ // A missing goal and someone else's goal are both invisible.
+ expect(await graph.listEvents('goal-missing', { limit: 5 })).toBeUndefined();
+ expect(await new GoalGraphModel(db, 'other-user').listEvents(id, { limit: 5 })).toBeUndefined();
+ });
+
+ it('pages across microsecond-apart events that share one millisecond', async () => {
+ const { id } = await start();
+ // Four events 100–400µs into 2026-01-01T00:00:00.000Z — all inside ONE
+ // millisecond. The column keeps microseconds, but a cursor round-trips
+ // through a JS Date and so carries only milliseconds: an untruncated keyset
+ // compares the microsecond column against a millisecond bound and drops the
+ // rows it cannot place (they match neither `<` nor the id tie-break).
+ const seeds = [
+ { entityId: 'micro-1', id: '00000000-0000-4000-8000-000000000001', micros: '000100' },
+ { entityId: 'micro-2', id: '00000000-0000-4000-8000-000000000002', micros: '000200' },
+ { entityId: 'micro-3', id: '00000000-0000-4000-8000-000000000003', micros: '000300' },
+ { entityId: 'micro-4', id: '00000000-0000-4000-8000-000000000004', micros: '000400' },
+ ];
+ for (const seed of seeds) {
+ await db.insert(goalEvents).values({
+ actorType: 'system',
+ createdAt: sql`${`2026-01-01T00:00:00.${seed.micros}Z`}::timestamptz`,
+ entityId: seed.entityId,
+ entityType: 'node',
+ eventType: 'created',
+ goalId: id,
+ id: seed.id,
+ });
+ }
+
+ // Walk the whole trail one row at a time, the way `lh goal events --limit 1` does.
+ const graph = new GoalGraphModel(db, userId);
+ const seen: string[] = [];
+ let cursor: { createdAt: Date; id: string } | undefined;
+ for (let i = 0; i < 50; i += 1) {
+ const page = await graph.listEvents(id, { cursor, limit: 1 });
+ if (!page) throw new Error('goal vanished mid-page');
+ seen.push(...page.events.map((event) => event.entityId));
+ if (!page.nextCursor) break;
+ cursor = page.nextCursor;
+ }
+
+ // None of the four is lost to the millisecond boundary. Within the shared
+ // millisecond the order falls back to id, which here runs with time.
+ expect(seen.filter((entityId) => entityId.startsWith('micro-'))).toEqual([
+ 'micro-4',
+ 'micro-3',
+ 'micro-2',
+ 'micro-1',
+ ]);
+ });
+
it('adopts a dispatch with a lost response rather than launching another Agent', async () => {
const original = vi.mocked(AiAgentService.prototype.execAgent).getMockImplementation()!;
vi.mocked(AiAgentService.prototype.execAgent).mockImplementation(async (params) => {
diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.ts
index 29c0b3fbfb6..3ae0a711d84 100644
--- a/apps/server/src/services/goal/manager.ts
+++ b/apps/server/src/services/goal/manager.ts
@@ -8,9 +8,11 @@ import {
} from '@lobechat/const/goal';
import { buildGoalManagerPrompt } from '@lobechat/prompts';
import type {
+ GoalGraphNode,
GoalGraphSnapshot,
GoalItem,
GoalManagerState,
+ GoalPlanContext,
GoalTickResult,
TaskItem,
} from '@lobechat/types';
@@ -152,6 +154,82 @@ export const MAX_FAILED_MANAGER_TURNS = 5;
const FAILED_TURN_BASE_BACKOFF_MS = 60_000;
const FAILED_TURN_MAX_BACKOFF_MS = 30 * 60_000;
+/**
+ * Why a plan was refused, with the verbatim message this service has thrown
+ * since before a diagnosis surface existed.
+ *
+ * A table rather than literals at each throw site so the write path (`submit`)
+ * and the read path (`admission`) cannot drift: both read the same entry, and
+ * `lh goal state` turns `code` into a sentence. Several codes share one message
+ * on purpose — `submit` has always folded "consumed", "the run ended" and "the
+ * graph moved" into a single stale-input refusal, and callers match that text.
+ */
+const PLAN_REJECTION = {
+ acceptance_escalate_only: {
+ message:
+ 'A failed Goal acceptance can only be escalated; it cannot be superseded by new work yet',
+ trpc: 'CONFLICT',
+ },
+ budget_exhausted: { message: 'Goal budget exhausted', trpc: 'CONFLICT' },
+ consumed: { message: 'Stale planning input; no plan applied', trpc: 'CONFLICT' },
+ existing_work: {
+ message: 'Existing work must be delivered before planning or verification',
+ trpc: 'CONFLICT',
+ },
+ inactive: { message: 'Goal stopped or awaiting human decision', trpc: 'CONFLICT' },
+ operation_mismatch: { message: 'Unrelated main Agent operation', trpc: 'FORBIDDEN' },
+ pending_decision: { message: 'Goal stopped or awaiting human decision', trpc: 'CONFLICT' },
+ review_changed: {
+ message:
+ 'Task review feedback changed; exit without a plan so the next bounded turn can read it',
+ trpc: 'CONFLICT',
+ },
+ stale_input: { message: 'Stale planning input; no plan applied', trpc: 'CONFLICT' },
+ turn_owner: { message: 'This planning turn does not own the Goal', trpc: 'FORBIDDEN' },
+ turn_settled: { message: 'Stale planning input; no plan applied', trpc: 'CONFLICT' },
+ wait_unsettled: { message: 'Settle existing work before waiting', trpc: 'CONFLICT' },
+ wait_until_past: { message: 'Wait until must be in the future', trpc: 'BAD_REQUEST' },
+} as const satisfies Record<
+ string,
+ { message: string; trpc: 'BAD_REQUEST' | 'CONFLICT' | 'FORBIDDEN' }
+>;
+
+type PlanRejectionCode = keyof typeof PLAN_REJECTION;
+
+/** A precondition verdict: enough for `submit` to throw it, or for the CLI to explain it. */
+type PlanAdmission =
+ | {
+ agentId: string;
+ code: 'ok';
+ graph: GoalGraphSnapshot;
+ ok: true;
+ opStatus?: string;
+ unfinished: GoalGraphNode[];
+ }
+ | {
+ code: 'duplicate';
+ ok: true;
+ /** Never set here — the duplicate branch returns before the run is resolved. */
+ opStatus?: string;
+ submitted: NonNullable<GoalManagerState['submitted']>;
+ }
+ | {
+ code: PlanRejectionCode;
+ message: string;
+ ok: false;
+ /** The turn's run status when it was already resolved, so a refusal can still name it. */
+ opStatus?: string;
+ trpcCode: (typeof PLAN_REJECTION)[PlanRejectionCode]['trpc'];
+ };
+
+const rejectPlan = (code: PlanRejectionCode, opStatus?: string): PlanAdmission => ({
+ code,
+ message: PLAN_REJECTION[code].message,
+ ok: false,
+ opStatus,
+ trpcCode: PLAN_REJECTION[code].trpc,
+});
+
export type FailedTurnDecision =
| { action: 'pause'; failure: RunFailure; reason: string }
| {
@@ -677,7 +755,8 @@ export class GoalManagerService {
};
};
- private budgetBlocked = async (graph: GoalGraphSnapshot, db = this.db) => {
+ /** Whether a budget bound is reached, with the numbers behind it for `lh goal state`. */
+ private budgetFacts = async (graph: GoalGraphSnapshot, db = this.db) => {
const spend = await new TaskTopicModel(db, this.userId, this.workspaceId).sumRunCostByTaskIds(
graph.nodes.flatMap((n) => (n.taskId ? [n.taskId] : [])),
);
@@ -686,14 +765,24 @@ export class GoalManagerService {
graph.goal.config?.managerState,
);
const goal = graph.goal;
- return (
- (goal.maxRounds !== null && spend.runs >= goal.maxRounds) ||
- (goal.maxTotalCost !== null &&
- spend.totalCost + management.totalCost >= Number(goal.maxTotalCost)) ||
- (!!goal.config?.schedule?.deadline && Date.now() >= Date.parse(goal.config.schedule.deadline))
- );
+ const totalCost = spend.totalCost + management.totalCost;
+ const deadline = goal.config?.schedule?.deadline ?? null;
+ return {
+ blocked:
+ (goal.maxRounds !== null && spend.runs >= goal.maxRounds) ||
+ (goal.maxTotalCost !== null && totalCost >= Number(goal.maxTotalCost)) ||
+ (!!deadline && Date.now() >= Date.parse(deadline)),
+ deadline,
+ maxRounds: goal.maxRounds,
+ maxTotalCost: goal.maxTotalCost,
+ runs: spend.runs,
+ totalCost,
+ };
};
+ private budgetBlocked = async (graph: GoalGraphSnapshot, db = this.db) =>
+ (await this.budgetFacts(graph, db)).blocked;
+
private wait = async (goalId: string, message: string): Promise<GoalTickResult> => {
await scheduleGoalAdvance({
goalId,
@@ -1252,6 +1341,212 @@ export class GoalManagerService {
await this.save(db, goalId, { ...fresh.config.managerState, dispatchNeverStarted: true });
});
+ /**
+ * Every precondition a plan has to satisfy, evaluated without writing.
+ *
+ * `submit` runs this first and throws its verdict; `admission()` returns the
+ * same verdict to `lh goal state`. One implementation, so the refusal a caller
+ * sees and the reason the CLI prints can never disagree.
+ *
+ * `token` / `operationId` are optional because the read path asks "would the
+ * CURRENT turn's plan apply?" — it has no submitted token to compare, so it
+ * passes the recorded one. Guards that only make sense with a plan are skipped
+ * when none is supplied.
+ */
+ private evaluateAdmission = async (
+ db: LobeChatDatabase,
+ input: {
+ goal: GoalItem;
+ operationId?: string;
+ plan?: GoalPlan;
+ state: GoalManagerState;
+ token?: string;
+ },
+ ): Promise<PlanAdmission> => {
+ const { goal, plan, state } = input;
+ if (!goal.config?.manager || !goal.agentId) return rejectPlan('turn_owner');
+ if (input.token !== undefined && state.token !== input.token) return rejectPlan('turn_owner');
+ // Bound to the goal agent as it is NOW: a turn dispatched before a handoff
+ // no longer speaks for the goal.
+ const agentId = goal.agentId;
+ const op = await this.turnOperation(
+ new AgentOperationModel(db, this.userId, this.workspaceId),
+ state,
+ );
+ if (input.operationId !== undefined) {
+ // An adopted local desktop run has no server operation row; it is the run
+ // whose id the conversation environment carried when the goal was created.
+ const localAdoptedRun = !!state.adopted && !op && input.operationId === state.operationId;
+ if (!localAdoptedRun && (op?.id !== input.operationId || op.agentId !== agentId))
+ return rejectPlan('operation_mismatch', op?.status);
+ }
+ const graph = await this.graph(db).getGraph(goal.id);
+ if (!graph || !activeStatuses.has(goal.status)) return rejectPlan('inactive', op?.status);
+ if (graph.decisions.some((d) => d.status === 'pending'))
+ return rejectPlan('pending_decision', op?.status);
+ if (state.submitted) return { code: 'duplicate', ok: true, submitted: state.submitted };
+ if (state.consumed) return rejectPlan('consumed', op?.status);
+ if (op && op.status !== 'running') return rejectPlan('turn_settled', op?.status);
+ if (managerSnapshot(graph) !== state.snapshot) return rejectPlan('stale_input', op?.status);
+ if (state.reviewSnapshot && (await this.reviews(graph, db)).hash !== state.reviewSnapshot)
+ return rejectPlan('review_changed', op?.status);
+ if ((await this.budgetFacts(graph, db)).blocked)
+ return rejectPlan('budget_exhausted', op?.status);
+ 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 (
+ plan &&
+ (plan.action === 'tasks' || plan.action === 'verify') &&
+ state.problem &&
+ graph.nodes.some(
+ (n) =>
+ n.kind === 'task' &&
+ n.taskId === state.problemTaskId &&
+ n.title === GOAL_ACCEPTANCE_TASK_TITLE,
+ )
+ )
+ return rejectPlan('acceptance_escalate_only', op?.status);
+ // 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 &&
+ (plan.action === 'tasks' || plan.action === 'verify') &&
+ ((unfinished.length && !state.problem) ||
+ (plan.action === 'verify' &&
+ !graph.nodes.some((n) => n.kind === 'task' && n.status === 'resolved')))
+ )
+ return rejectPlan('existing_work', op?.status);
+ if (plan?.action === 'wait' && unfinished.length)
+ return rejectPlan('wait_unsettled', op?.status);
+ if (plan?.action === 'wait' && Date.parse(plan.until) <= Date.now())
+ return rejectPlan('wait_until_past', op?.status);
+ return { agentId, code: 'ok', graph, ok: true, opStatus: op?.status, unfinished };
+ };
+
+ /**
+ * The verdict `submit` would reach right now, plus the facts behind it.
+ *
+ * Read-only: `lh goal state` renders it and a refused `lh goal plan` re-reads
+ * it, so the CLI explains a refusal from these predicates instead of deriving
+ * them from a graph that cannot see the manager or review receipts. Token and
+ * operation default to the current turn's — the plan a takeover prompt sends.
+ *
+ * `plan` is forwarded to `evaluateAdmission` because four guards only fire with
+ * one (`existing_work`, `acceptance_escalate_only`, `wait_unsettled`,
+ * `wait_until_past`). A refused `lh goal plan` passes the plan it just
+ * submitted so those refusals are re-derived rather than reported as `ok`;
+ * `lh goal state` has no plan and asks only whether the non-plan guards pass.
+ */
+ admission = async (
+ goalId: string,
+ input: { operationId?: string; plan?: GoalPlan; token?: string } = {},
+ ): Promise<GoalPlanContext> => {
+ const goal = await new GoalModel(this.db, this.userId, this.workspaceId).findById(goalId);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ const state = goal.config?.managerState;
+ const verdict: PlanAdmission =
+ state && goal.config?.manager && goal.agentId
+ ? await this.evaluateAdmission(this.db, {
+ goal,
+ operationId: input.operationId ?? state.operationId,
+ plan: input.plan,
+ state,
+ token: input.token ?? state.token,
+ })
+ : rejectPlan('turn_owner');
+ const graph =
+ verdict.ok && verdict.code === 'ok' ? verdict.graph : await this.graph().getGraph(goalId);
+ const budget = graph ? await this.budgetFacts(graph) : undefined;
+ return {
+ admission: {
+ code: verdict.code,
+ ...(verdict.ok ? {} : { message: verdict.message }),
+ ok: verdict.ok,
+ },
+ budget: budget
+ ? {
+ blocked: budget.blocked,
+ deadline: budget.deadline,
+ maxRounds: budget.maxRounds,
+ maxTotalCost: budget.maxTotalCost,
+ runs: budget.runs,
+ totalCost: budget.totalCost,
+ }
+ : undefined,
+ goal: { agentId: goal.agentId, pausedBy: goal.config?.pausedBy ?? null, status: goal.status },
+ queue: graph
+ ? {
+ pendingDecisions: graph.decisions.filter((d) => d.status === 'pending').length,
+ unfinishedTasks: graph.nodes.filter(
+ (n) => n.kind === 'task' && !terminalNodes.has(n.status),
+ ).length,
+ }
+ : undefined,
+ review: {
+ ...(graph && state ? { current: (await this.reviews(graph)).hash } : {}),
+ recorded: state?.reviewSnapshot ?? null,
+ },
+ snapshot: {
+ ...(graph ? { current: managerSnapshot(graph) } : {}),
+ recorded: state?.snapshot ?? null,
+ },
+ turn: state
+ ? {
+ adopted: !!state.adopted,
+ consumed: !!state.consumed,
+ dispatchNeverStarted: !!state.dispatchNeverStarted,
+ failedTurns: state.failedTurns ?? 0,
+ operationId: state.operationId ?? null,
+ opStatus: verdict.opStatus ?? null,
+ problem: state.problem ?? null,
+ problemTaskId: state.problemTaskId ?? null,
+ retryAfter: state.retryAfter ?? null,
+ startedAt: state.startedAt,
+ submitted: state.submitted ?? null,
+ token: state.token,
+ turns: state.turns,
+ }
+ : null,
+ };
+ };
+
+ /**
+ * Authorize a heterogeneous planning read: the caller's operation must be the
+ * one the Goal's *current* turn belongs to.
+ *
+ * The turn is resolved through `turnOperation` — the lookup `submit` uses — not
+ * through the `managerState.operationId` receipt. That receipt is written only
+ * once the dispatched run's `execAgent` resolves, so a fast run can be live and
+ * holding a token before the field exists; and if that save fails the field never
+ * arrives, yet the turn is live and `submit` still succeeds. Reading ownership
+ * off the same recoverable lookup keeps reads and writes in step.
+ */
+ assertOperationOwnsTurn = async (goalId: string, operationId: string): Promise<void> => {
+ const goal = await new GoalModel(this.db, this.userId, this.workspaceId).findById(goalId);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ const state = goal.config?.managerState;
+ const operation = state
+ ? await this.turnOperation(
+ new AgentOperationModel(this.db, this.userId, this.workspaceId),
+ state,
+ )
+ : undefined;
+ if (operation?.id !== operationId)
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'This run does not own the current planning turn of this goal',
+ });
+ };
+
submit = async (goalId: string, token: string, operationId: string, input: GoalPlan) => {
const plan = goalPlanSchema.parse(input);
const armed = plan.action === 'wait' ? GoalWaitService.arm(plan.until) : undefined;
@@ -1259,92 +1554,13 @@ export class GoalManagerService {
const model = new GoalModel(db, this.userId, this.workspaceId);
const goal = await model.lockById(goalId);
const state = goal?.config?.managerState;
- if (!goal?.config?.manager || !goal.agentId || !state || state.token !== token)
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: 'This planning turn does not own the Goal',
- });
- const op = await this.turnOperation(
- new AgentOperationModel(db, this.userId, this.workspaceId),
- state,
- );
- // Bound to the goal agent as it is NOW: a turn dispatched before a handoff
- // no longer speaks for the goal.
- const agentId = goal.agentId;
- // An adopted local desktop run has no server operation row; it is the run
- // whose id the conversation environment carried when the goal was created.
- const localAdoptedRun = !!state.adopted && !op && operationId === state.operationId;
- if (!localAdoptedRun && (op?.id !== operationId || op.agentId !== agentId))
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Unrelated main Agent operation' });
- const graph = await this.graph(db).getGraph(goalId);
- if (
- !graph ||
- !activeStatuses.has(goal.status) ||
- graph.decisions.some((d) => d.status === 'pending')
- )
- throw new TRPCError({
- code: 'CONFLICT',
- message: 'Goal stopped or awaiting human decision',
- });
- if (state.submitted) return { duplicate: true, plan: state.submitted };
- if (
- state.consumed ||
- (op && op.status !== 'running') ||
- managerSnapshot(graph) !== state.snapshot
- )
- throw new TRPCError({ code: 'CONFLICT', message: 'Stale planning input; no plan applied' });
- if (state.reviewSnapshot && (await this.reviews(graph, db)).hash !== state.reviewSnapshot)
- throw new TRPCError({
- code: 'CONFLICT',
- message:
- 'Task review feedback changed; exit without a plan so the next bounded turn can read it',
- });
- if (await this.budgetBlocked(graph, db))
- throw new TRPCError({ code: 'CONFLICT', message: 'Goal budget exhausted' });
- 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 && !state.problem) ||
- (plan.action === 'verify' &&
- !graph.nodes.some((n) => n.kind === 'task' && n.status === 'resolved')))
- )
- throw new TRPCError({
- code: 'CONFLICT',
- message: 'Existing work must be delivered before planning or verification',
- });
- if (plan.action === 'wait' && unfinished.length)
- throw new TRPCError({ code: 'CONFLICT', message: 'Settle existing work before waiting' });
- if (plan.action === 'wait' && Date.parse(plan.until) <= Date.now())
- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Wait until must be in the future' });
+ if (!goal || !state)
+ throw new TRPCError({ code: 'FORBIDDEN', message: PLAN_REJECTION.turn_owner.message });
+ const admission = await this.evaluateAdmission(db, { goal, operationId, plan, state, token });
+ if (!admission.ok)
+ throw new TRPCError({ code: admission.trpcCode, message: admission.message });
+ if (admission.code === 'duplicate') return { duplicate: true, plan: admission.submitted };
+ const { agentId, graph, unfinished } = admission;
const authored = new GoalGraphModel(db, this.userId, this.workspaceId, {
id: agentId,
type: 'agent',
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 7e58eff4465..8d892c99f9c 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -6,6 +6,7 @@ import type {
GoalEventActorType,
GoalEventEntityType,
GoalEventType,
+ GoalGraphEvent,
GoalGraphSnapshot,
GoalGraphWorkVersionDisplay,
GoalNodeKind,
@@ -197,6 +198,80 @@ export class GoalGraphModel {
};
};
+ /**
+ * The goal's audit trail, newest first, with the cursor that continues it.
+ *
+ * `getGraph` bundles only the newest {@link GRAPH_EVENT_LIMIT} events, which a
+ * long-running goal exhausts — the transition that explains a stall can sit
+ * just past the cap. This pages the same table so a reader can reach it.
+ * Ownership is the predicate `getGraph` uses, so "no such goal" and "not
+ * yours" stay indistinguishable and neither leaks another user's goal.
+ *
+ * A cursor, not an offset: this feed is live and events are PREPENDED while the
+ * goal runs, so an offset taken on page one re-serves a row that a later insert
+ * pushed down. `(createdAt, id)` is the sort key, so it is also the
+ * continuation key.
+ *
+ * `createdAt` is compared and ordered at **millisecond** precision, matching
+ * the cursor. The column is `timestamptz` and can carry microseconds, but the
+ * cursor round-trips through a JS `Date` / ISO string and so only carries
+ * milliseconds; comparing the raw column against that truncated cursor makes a
+ * same-millisecond row match neither the `<` bound nor the `eq`/id tie-break,
+ * silently dropping it from the next page. Truncating both sides keeps the
+ * keyset lossless — the same pattern as `verifyRun.queryPage`.
+ */
+ listEvents = async (
+ goalId: string,
+ options: {
+ cursor?: { createdAt: Date; id: string };
+ entityType?: GoalEventEntityType;
+ eventType?: GoalEventType;
+ limit: number;
+ },
+ ): Promise<
+ { events: GoalGraphEvent[]; nextCursor?: { createdAt: Date; id: string } } | undefined
+ > => {
+ const [goal] = await this.db
+ .select({ id: goals.id })
+ .from(goals)
+ .where(and(eq(goals.id, goalId), this.ownership()))
+ .limit(1);
+ if (!goal) return undefined;
+
+ // Millisecond-truncated `createdAt`, the precision the cursor round-trips at.
+ const createdAtMs = sql`date_trunc('milliseconds', ${goalEvents.createdAt})`;
+
+ const filters = [eq(goalEvents.goalId, goalId)];
+ if (options.entityType) filters.push(eq(goalEvents.entityType, options.entityType));
+ if (options.eventType) filters.push(eq(goalEvents.eventType, options.eventType));
+ // Strictly older than the cursor, ties broken by id — the same pair the rows
+ // are ordered by, so a page can neither repeat nor skip.
+ const afterCursor = options.cursor
+ ? or(
+ lt(createdAtMs, options.cursor.createdAt),
+ and(eq(createdAtMs, options.cursor.createdAt), lt(goalEvents.id, options.cursor.id)),
+ )
+ : undefined;
+
+ // One row past the page answers "is there more?" without a second count query.
+ const rows = await this.db
+ .select()
+ .from(goalEvents)
+ .where(and(...filters, afterCursor))
+ .orderBy(desc(createdAtMs), desc(goalEvents.id))
+ .limit(options.limit + 1);
+
+ const events = rows.slice(0, options.limit);
+ const last = events.at(-1);
+ return {
+ events,
+ nextCursor:
+ rows.length > options.limit && last
+ ? { createdAt: last.createdAt, id: last.id }
+ : undefined,
+ };
+ };
+
/**
* Display snapshots for linked Work versions, keyed by version id.
*
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 808fbee0985..abcad0e2cb1 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -343,6 +343,53 @@ export interface GoalManagerState {
wait?: GoalManagerWait;
}
+/**
+ * The admission verdict `submit` would reach, plus the facts behind it.
+ *
+ * Served as `goal.planContext` and rendered by `lh goal state`: a refused
+ * `lh goal plan` re-reads it, so the CLI can explain *why* from the server's own
+ * predicates. `snapshot` / `review` carry the recorded hashes next to the
+ * current ones because a stale plan is exactly the case a client cannot judge on
+ * its own — the graph it holds has no manager or review receipt.
+ */
+export interface GoalPlanContext {
+ /**
+ * `ok` means nothing refuses this turn — NOT that a new plan would be applied.
+ * `code: 'duplicate'` is `ok` because a plan is already recorded and
+ * re-submitting returns its receipt unchanged; it must not be rendered as
+ * "accepted".
+ */
+ admission: { code: string; message?: string; ok: boolean };
+ budget?: {
+ blocked: boolean;
+ deadline: string | null;
+ maxRounds: number | null;
+ maxTotalCost: number | null;
+ runs: number;
+ totalCost: number;
+ };
+ goal: { agentId: string | null; pausedBy: GoalPauseReason | null; status: GoalStatus };
+ queue?: { pendingDecisions: number; unfinishedTasks: number };
+ review: { current?: string; recorded: string | null };
+ snapshot: { current?: string; recorded: string | null };
+ turn: {
+ adopted: boolean;
+ consumed: boolean;
+ dispatchNeverStarted: boolean;
+ failedTurns: number;
+ operationId: string | null;
+ /** `agent_operations.status` of the run behind this turn, when one exists. */
+ opStatus: string | null;
+ problem: string | null;
+ problemTaskId: string | null;
+ retryAfter: string | null;
+ startedAt: string;
+ submitted: GoalManagerState['submitted'] | null;
+ token: string;
+ turns: number;
+ } | null;
+}
+
/**
* The owner's 提出修改 on a delivered Goal: rejecting the Goal-level acceptance
* reopens the Goal, and this is what the rework answers to.