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.

๐Ÿ› fix(goal): lay manager plans out by round and surface agent-written deliverables (#19587)

Arvin Xu185d3c485885
diff --git a/apps/cli/src/commands/doc.test.ts b/apps/cli/src/commands/doc.test.ts
index 76d2f121ad1..0988ba39305 100644
--- a/apps/cli/src/commands/doc.test.ts
+++ b/apps/cli/src/commands/doc.test.ts
@@ -221,6 +221,24 @@ describe('doc command', () => {
// โ”€โ”€ create โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
describe('create', () => {
+ /**
+ * Regression: inside an agent run the created document was never tied to the
+ * run, so a Goal could not show it as the Task's deliverable.
+ */
+ it.each([
+ { env: 'op-run-1', expected: { operationId: 'op-run-1' } },
+ { env: '', expected: undefined },
+ ])('passes the current run operation when set: %j', async ({ env, expected }) => {
+ vi.stubEnv('LOBEHUB_OPERATION_ID', env);
+ mockTrpcClient.document.createDocument.mutate.mockResolvedValue({ id: 'new-doc' });
+
+ await createProgram().parseAsync(['node', 'test', 'doc', 'create', '--title', 'Report']);
+
+ const [params] = mockTrpcClient.document.createDocument.mutate.mock.calls[0];
+ if (expected) expect(params).toMatchObject(expected);
+ else expect(params).not.toHaveProperty('operationId');
+ });
+
it('should create a document with title and body', async () => {
mockTrpcClient.document.createDocument.mutate.mockResolvedValue({ id: 'new-doc' });
@@ -403,6 +421,20 @@ describe('doc command', () => {
// โ”€โ”€ edit โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
describe('edit', () => {
+ it.each([
+ { env: 'op-run-1', expected: { operationId: 'op-run-1' } },
+ { env: '', expected: undefined },
+ ])('passes the current run operation when set: %j', async ({ env, expected }) => {
+ vi.stubEnv('LOBEHUB_OPERATION_ID', env);
+ mockTrpcClient.document.updateDocument.mutate.mockResolvedValue({});
+
+ await createProgram().parseAsync(['node', 'test', 'doc', 'edit', 'doc1', '--body', 'v2']);
+
+ const [params] = mockTrpcClient.document.updateDocument.mutate.mock.calls[0];
+ if (expected) expect(params).toMatchObject(expected);
+ else expect(params).not.toHaveProperty('operationId');
+ });
+
it('should update document title', async () => {
mockTrpcClient.document.updateDocument.mutate.mockResolvedValue({});
diff --git a/apps/cli/src/commands/doc.ts b/apps/cli/src/commands/doc.ts
index e9b4dfe4725..fcde9083ecd 100644
--- a/apps/cli/src/commands/doc.ts
+++ b/apps/cli/src/commands/doc.ts
@@ -144,6 +144,11 @@ export function registerDocCommand(program: Command) {
editorData: JSON.stringify({ content: content || '', type: 'doc' }),
fileType: options.fileType,
knowledgeBaseId: options.kb,
+ // Inside an agent run, credit the document to that run so it shows up
+ // as the run's deliverable (e.g. on a Goal) instead of a loose page.
+ ...(process.env.LOBEHUB_OPERATION_ID
+ ? { operationId: process.env.LOBEHUB_OPERATION_ID }
+ : {}),
parentId: options.parent,
slug: options.slug,
title: options.title,
@@ -258,6 +263,8 @@ export function registerDocCommand(program: Command) {
params.parentId = options.parent || null;
}
if (options.fileType) params.fileType = options.fileType;
+ // Inside an agent run, an edit becomes a new version of that run's deliverable.
+ if (process.env.LOBEHUB_OPERATION_ID) params.operationId = process.env.LOBEHUB_OPERATION_ID;
await client.document.updateDocument.mutate(params as any);
console.log(`${pc.green('โœ“')} Updated document ${pc.bold(id)}`);
diff --git a/apps/server/src/routers/lambda/_helpers/runProvenance.ts b/apps/server/src/routers/lambda/_helpers/runProvenance.ts
new file mode 100644
index 00000000000..08f100e2b39
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/runProvenance.ts
@@ -0,0 +1,34 @@
+import { TRPCError } from '@trpc/server';
+
+interface OperationLink {
+ id: string;
+ parentOperationId?: string | null;
+}
+
+/**
+ * Walk an operation the caller already owns up to the root of its run.
+ *
+ * Work versions are keyed by the ROOT operation (`work_versions.root_operation_id`),
+ * so a document written from a sub-operation has to be credited to the run that
+ * contains it โ€” that is the id a Goal harvests deliverables by. Every ancestor
+ * must be owned by the caller too, otherwise a write could claim someone else's run.
+ */
+export const resolveRootOperation = async <T extends OperationLink>(
+ findOwnOperationById: (id: string) => Promise<T | null | undefined>,
+ operation: T,
+): Promise<T> => {
+ let rootOperation = operation;
+ const visited = new Set<string>();
+ while (rootOperation.parentOperationId) {
+ if (visited.has(rootOperation.id)) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid operation ancestry' });
+ }
+ visited.add(rootOperation.id);
+ const parent = await findOwnOperationById(rootOperation.parentOperationId);
+ if (!parent) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Operation ancestry is not accessible' });
+ }
+ rootOperation = parent;
+ }
+ return rootOperation;
+};
diff --git a/apps/server/src/routers/lambda/document.test.ts b/apps/server/src/routers/lambda/document.test.ts
index ac7dabf6826..904ca4c9e40 100644
--- a/apps/server/src/routers/lambda/document.test.ts
+++ b/apps/server/src/routers/lambda/document.test.ts
@@ -6,8 +6,25 @@ import { createContextInner } from '@/libs/trpc/lambda/context';
import { documentRouter } from './document';
-const mocks = vi.hoisted(() => ({ getDocumentById: vi.fn(), getFileAccessUrl: vi.fn() }));
+const mocks = vi.hoisted(() => ({
+ createDocument: vi.fn(),
+ findOwnOperationById: vi.fn(),
+ getDocumentById: vi.fn(),
+ getFileAccessUrl: vi.fn(),
+ registerDocument: vi.fn(),
+ updateDocument: vi.fn(),
+}));
vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn().mockImplementation(function () {
+ return { findOwnOperationById: mocks.findOwnOperationById };
+ }),
+}));
+vi.mock('@/database/models/work', () => ({
+ WorkModel: vi.fn().mockImplementation(function () {
+ return { registerDocument: mocks.registerDocument };
+ }),
+}));
vi.mock('@/database/models/chunk', () => ({ ChunkModel: vi.fn() }));
vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
vi.mock('@/database/models/message', () => ({ MessageModel: vi.fn() }));
@@ -17,7 +34,11 @@ vi.mock('@/database/models/document', () => ({
}));
vi.mock('@/server/services/document', () => ({
DocumentService: vi.fn().mockImplementation(function () {
- return { getDocumentById: mocks.getDocumentById };
+ return {
+ createDocument: mocks.createDocument,
+ getDocumentById: mocks.getDocumentById,
+ updateDocument: mocks.updateDocument,
+ };
}),
}));
vi.mock('@/server/services/file', () => ({
@@ -77,3 +98,101 @@ describe('document source URL resolution', () => {
expect(mocks.getFileAccessUrl).not.toHaveBeenCalled();
});
});
+
+/**
+ * Regression: documents an agent wrote through `lh doc create` were never
+ * registered as Work, so a Goal's deliverables stayed empty even though the
+ * run produced its report.
+ */
+describe('document work provenance', () => {
+ const liveChild = {
+ agentId: 'agent-1',
+ id: 'child',
+ parentOperationId: 'root',
+ status: 'running',
+ topicId: 'topic-1',
+ };
+
+ beforeEach(() => {
+ for (const mock of Object.values(mocks)) mock.mockReset();
+ mocks.createDocument.mockResolvedValue({ id: 'doc-1', visibility: 'private' });
+ mocks.updateDocument.mockResolvedValue({ id: 'doc-1' });
+ });
+
+ it('credits a document written from a live run to the root of that run', async () => {
+ mocks.findOwnOperationById
+ .mockResolvedValueOnce(liveChild)
+ .mockResolvedValueOnce({ id: 'root', parentOperationId: null });
+
+ await (await caller()).createDocument({ content: 'Report', operationId: 'child', title: 'R' });
+
+ expect(mocks.createDocument).toHaveBeenCalledWith(
+ expect.not.objectContaining({ operationId: expect.anything() }),
+ );
+ expect(mocks.registerDocument).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ changeType: 'created',
+ documentId: 'doc-1',
+ rootOperationId: 'root',
+ topicId: 'topic-1',
+ }),
+ );
+ });
+
+ it.each([
+ { label: 'not owned', operation: null },
+ { label: 'already finished', operation: { ...liveChild, status: 'done' } },
+ ])(
+ 'writes the document but credits no run when the operation is $label',
+ async ({ operation }) => {
+ mocks.findOwnOperationById.mockResolvedValue(operation);
+
+ await expect(
+ (await caller()).createDocument({ content: 'Report', operationId: 'child', title: 'R' }),
+ ).resolves.toMatchObject({ id: 'doc-1' });
+ expect(mocks.registerDocument).not.toHaveBeenCalled();
+ },
+ );
+
+ it('adds a version when a live run edits the content', async () => {
+ mocks.findOwnOperationById.mockResolvedValue({ ...liveChild, parentOperationId: null });
+
+ await (await caller()).updateDocument({ content: 'v2', id: 'doc-1', operationId: 'child' });
+
+ expect(mocks.updateDocument).toHaveBeenCalledWith(
+ 'doc-1',
+ expect.not.objectContaining({ operationId: expect.anything() }),
+ );
+ expect(mocks.registerDocument).toHaveBeenCalledWith(
+ expect.objectContaining({
+ changeType: 'updated',
+ documentId: 'doc-1',
+ rootOperationId: 'child',
+ }),
+ );
+ });
+
+ it('does not treat a file-type change as a new deliverable version', async () => {
+ await (
+ await caller()
+ ).updateDocument({
+ fileType: 'custom/folder',
+ id: 'doc-1',
+ operationId: 'child',
+ });
+
+ expect(mocks.findOwnOperationById).not.toHaveBeenCalled();
+ expect(mocks.registerDocument).not.toHaveBeenCalled();
+ });
+
+ it('never fails the write when Work bookkeeping fails', async () => {
+ mocks.findOwnOperationById.mockResolvedValue({ ...liveChild, parentOperationId: null });
+ mocks.registerDocument.mockRejectedValue(new Error('work table unavailable'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(
+ (await caller()).updateDocument({ content: 'v2', id: 'doc-1', operationId: 'child' }),
+ ).resolves.toMatchObject({ id: 'doc-1' });
+ });
+});
diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.ts
index 86baa38e5cd..201eed3c95a 100644
--- a/apps/server/src/routers/lambda/document.ts
+++ b/apps/server/src/routers/lambda/document.ts
@@ -6,12 +6,14 @@ import { businessFileTransferStorageCheck } from '@/business/server/lambda-route
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { FREE_DOCUMENT_HISTORY_WINDOW_DAYS } from '@/const/documentHistory';
+import { AgentOperationModel } from '@/database/models/agentOperation';
import { ChunkModel } from '@/database/models/chunk';
import { DOCUMENT_TRANSFER_FOREIGN_ROWS, DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import { MessageModel } from '@/database/models/message';
import { RbacModel } from '@/database/models/rbac';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { WorkModel } from '@/database/models/work';
import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -32,6 +34,7 @@ import {
assertContentsNotInRestrictedKnowledgeBase,
getRestrictedKnowledgeBaseIds,
} from './_helpers/knowledgeBaseAccess';
+import { resolveRootOperation } from './_helpers/runProvenance';
import {
compareDocumentHistoryItemsInputSchema,
getDocumentHistoryItemInputSchema,
@@ -130,6 +133,48 @@ const notifyDocumentMentionsBestEffort = (
});
};
+/**
+ * Credit a document written inside an agent run to that run as a Work version,
+ * so run consumers (a Goal harvesting a Task's deliverables) can find it. Agents
+ * that write through the `lh doc` CLI never pass through a tool runtime, which is
+ * where document Work is otherwise registered.
+ *
+ * Attribution is best effort and never fails the write: only an owned operation
+ * that is still running can claim the document โ€” a stale `LOBEHUB_OPERATION_ID`
+ * left in a shell must not credit a finished run โ€” and any provenance or
+ * bookkeeping failure just leaves the document unattributed.
+ */
+const registerRunDocumentWork = async (
+ ctx: { operationModel: AgentOperationModel; workModel: WorkModel },
+ params: {
+ changeType: 'created' | 'updated';
+ documentId: string;
+ operationId?: string;
+ toolName: string;
+ },
+) => {
+ if (!params.operationId) return;
+ try {
+ const operation = await ctx.operationModel.findOwnOperationById(params.operationId);
+ if (!operation || operation.status !== 'running') return;
+ const rootOperation = await resolveRootOperation(
+ (id) => ctx.operationModel.findOwnOperationById(id),
+ operation,
+ );
+ await ctx.workModel.registerDocument({
+ agentId: operation.agentId,
+ changeType: params.changeType,
+ documentId: params.documentId,
+ rootOperationId: rootOperation.id,
+ toolIdentifier: 'lobehub-document',
+ toolName: params.toolName,
+ topicId: operation.topicId,
+ });
+ } catch (error) {
+ console.error('[document] Failed to credit the document to its run', error);
+ }
+};
+
const documentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const wsId = ctx.workspaceId ?? undefined;
@@ -141,6 +186,8 @@ const documentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)
documentService: new DocumentService(ctx.serverDB, ctx.userId, wsId),
fileModel: new FileModel(ctx.serverDB, ctx.userId, wsId),
messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),
+ operationModel: new AgentOperationModel(ctx.serverDB, ctx.userId, wsId),
+ workModel: new WorkModel(ctx.serverDB, ctx.userId, wsId),
},
});
});
@@ -155,6 +202,8 @@ export const documentRouter = router({
fileType: z.string().optional(),
knowledgeBaseId: z.string().optional(),
metadata: z.record(z.string(), z.any()).optional(),
+ /** The agent run writing this document; credits it to that run as Work. */
+ operationId: z.string().optional(),
parentId: z.string().optional(),
slug: z.string().optional(),
title: z.string(),
@@ -164,10 +213,11 @@ export const documentRouter = router({
}),
)
.mutation(async ({ ctx, input }) => {
+ const { operationId, ...documentInput } = input;
// Resolve parentId if it's a slug
- let resolvedParentId = input.parentId;
- if (input.parentId) {
- const docBySlug = await ctx.documentModel.findBySlug(input.parentId);
+ let resolvedParentId = documentInput.parentId;
+ if (documentInput.parentId) {
+ const docBySlug = await ctx.documentModel.findBySlug(documentInput.parentId);
if (docBySlug) {
resolvedParentId = docBySlug.id;
}
@@ -176,9 +226,11 @@ export const documentRouter = router({
await assertCanCreateUnderParent(ctx, resolvedParentId);
// Parse editorData from JSON string to object
- const editorData = input.editorData ? JSON.parse(input.editorData) : undefined;
+ const editorData = documentInput.editorData
+ ? JSON.parse(documentInput.editorData)
+ : undefined;
const document = await ctx.documentService.createDocument({
- ...input,
+ ...documentInput,
editorData,
parentId: resolvedParentId,
});
@@ -190,6 +242,12 @@ export const documentRouter = router({
ctx.userId,
);
}
+ await registerRunDocumentWork(ctx, {
+ changeType: 'created',
+ documentId: document.id,
+ operationId,
+ toolName: 'createDocument',
+ });
return document;
}),
@@ -484,7 +542,12 @@ export const documentRouter = router({
updateDocument: documentProcedure
.use(withScopedPermission('document:update'))
- .input(updateDocumentInputSchema)
+ .input(
+ updateDocumentInputSchema.extend({
+ /** The agent run editing this document; an edit adds a Work version to that run. */
+ operationId: z.string().optional(),
+ }),
+ )
.mutation(async ({ ctx, input }) => {
await assertContentsNotInRestrictedKnowledgeBase(ctx, [input.id]);
@@ -502,7 +565,7 @@ export const documentRouter = router({
}
}
- const { id, editorData: editorDataString, ...params } = input;
+ const { id, editorData: editorDataString, operationId, ...params } = input;
// Parse editorData from JSON string to object if present
const editorData = editorDataString ? JSON.parse(editorDataString) : undefined;
const result = await ctx.documentService.updateDocument(id, {
@@ -510,6 +573,17 @@ export const documentRouter = router({
editorData,
});
+ // Only a change to what the document says is a new deliverable version;
+ // a move or a file-type change is not.
+ if (result && (params.content !== undefined || params.title !== undefined)) {
+ await registerRunDocumentWork(ctx, {
+ changeType: 'updated',
+ documentId: id,
+ operationId,
+ toolName: 'updateDocument',
+ });
+ }
+
if (ctx.workspaceId && result?.addedMentionUserIds && result.savedAt) {
notifyDocumentMentionsBestEffort(
{ serverDB: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
diff --git a/apps/server/src/routers/lambda/notebook.ts b/apps/server/src/routers/lambda/notebook.ts
index 86509e44576..9a6fb7c7a5f 100644
--- a/apps/server/src/routers/lambda/notebook.ts
+++ b/apps/server/src/routers/lambda/notebook.ts
@@ -18,6 +18,7 @@ import {
} from '@/server/services/resourcePermission';
import { isWorkspaceNonOwner } from './_helpers/assertWorkspaceRowManageable';
+import { resolveRootOperation } from './_helpers/runProvenance';
const notebookProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -69,24 +70,9 @@ export const notebookRouter = router({
message: 'Operation does not belong to this topic',
});
}
- let rootOperation = operation;
- const visited = new Set<string>();
- while (rootOperation?.parentOperationId) {
- if (visited.has(rootOperation.id)) {
- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid operation ancestry' });
- }
- visited.add(rootOperation.id);
- const parent = await ctx.operationModel.findOwnOperationById(
- rootOperation.parentOperationId,
- );
- if (!parent) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Operation ancestry is not accessible',
- });
- }
- rootOperation = parent;
- }
+ const rootOperation = operation
+ ? await resolveRootOperation((id) => ctx.operationModel.findOwnOperationById(id), operation)
+ : null;
// Create the document
const document = await ctx.documentModel.create({
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index eb6beaab4d2..2e99ccd1549 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
+import * as goalGraphUtils from '@lobechat/utils/goalGraph';
import { eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -1750,6 +1751,100 @@ describe('GoalService', () => {
).toHaveLength(1);
});
+ /**
+ * Regression: the terminal acceptance hung only off the problem node, so it
+ * rendered beside the first round instead of after the work it closes.
+ */
+ it('builds the Goal-level Acceptance Task on the delivered leaf Tasks', async () => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ requirement: 'Return two verified supplier quotes.',
+ title: 'Find two supplier quotes',
+ tasks: ['Research supplier A', 'Research supplier B'],
+ });
+
+ let acceptance;
+ for (let i = 0; i < 12 && !acceptance; i++) {
+ await service.tick(graph.goal.id);
+ const current = await service.graph(graph.goal.id);
+ for (const node of current.nodes) {
+ if (node.taskId && node.title !== 'Complete full Goal acceptance')
+ await taskModel.updateStatus(node.taskId, 'completed');
+ }
+ acceptance = current.nodes.find((node) => node.title === 'Complete full Goal acceptance');
+ }
+
+ const current = await service.graph(graph.goal.id);
+ const leaves = current.nodes
+ .filter((node) => node.title.startsWith('Research supplier'))
+ .map((node) => node.id);
+ expect(acceptance).toBeTruthy();
+ expect(
+ current.edges
+ .filter((edge) => edge.kind === 'depends_on' && edge.sourceNodeId === acceptance!.id)
+ .map((edge) => edge.targetNodeId)
+ .sort(),
+ ).toEqual(leaves.sort());
+ });
+
+ /**
+ * Regression: the acceptance node and its dependency edges were written in
+ * separate transactions. A failure between them left the node without its
+ * links for good, because once the node exists no later tick writes them.
+ */
+ it('creates the Goal-level Acceptance Task and its dependencies atomically', async () => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ requirement: 'Return two verified supplier quotes.',
+ title: 'Atomic acceptance links',
+ tasks: ['Research supplier A', 'Research supplier B'],
+ });
+ const findAcceptance = async () =>
+ (await service.graph(graph.goal.id)).nodes.find(
+ (node) => node.title === 'Complete full Goal acceptance',
+ );
+
+ let interrupted = false;
+ for (let i = 0; i < 14 && !(await findAcceptance()); i++) {
+ const tasks = (await service.graph(graph.goal.id)).nodes.filter(
+ (node) => node.kind === 'task',
+ );
+ if (!interrupted && tasks.length > 0 && tasks.every((node) => node.status === 'resolved')) {
+ // Every Task is delivered, so this tick creates the acceptance. Fail it
+ // after the node insert and before its dependency edges are written.
+ const spy = vi.spyOn(goalGraphUtils, 'experimentOwner').mockImplementation(() => {
+ throw new Error('interrupted while linking the acceptance');
+ });
+ await service.tick(graph.goal.id).catch(() => undefined);
+ spy.mockRestore();
+ interrupted = true;
+ expect(await findAcceptance()).toBeUndefined();
+ continue;
+ }
+ await service.tick(graph.goal.id);
+ for (const node of (await service.graph(graph.goal.id)).nodes) {
+ if (node.taskId && node.title !== 'Complete full Goal acceptance')
+ await taskModel.updateStatus(node.taskId, 'completed');
+ }
+ }
+
+ const current = await service.graph(graph.goal.id);
+ const acceptance = current.nodes.find((node) => node.title === 'Complete full Goal acceptance');
+ const leaves = current.nodes
+ .filter((node) => node.title.startsWith('Research supplier'))
+ .map((node) => node.id);
+ expect(interrupted).toBe(true);
+ expect(acceptance).toBeTruthy();
+ expect(
+ current.edges
+ .filter((edge) => edge.kind === 'depends_on' && edge.sourceNodeId === acceptance!.id)
+ .map((edge) => edge.targetNodeId)
+ .sort(),
+ ).toEqual(leaves.sort());
+ });
+
it('parks a goal short of acceptance and reopens it when the measurement clears', async () => {
// The measured half of acceptance: "followers >= 1000" is not a document a
// verifier reads, it is a number. Until it holds, the acceptance Task must
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index e4480ff9f20..62a581282ba 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -1702,21 +1702,58 @@ export class GoalService {
return { goalId, message: move.message, nodeId: move.focusNodeId, outcome: 'no_progress' };
}
- const result = await this.coordinatorGraph.createNodeOnce(goalId, {
- description: [
- `Complete and prove the overall Goal acceptance requirement: ${graph.goal.requirement}`,
- 'Inspect and reuse existing Goal findings, artifacts, metrics, and command results as the primary evidence. Do not repeat expensive or destructive work when the existing evidence is sufficient and still auditable.',
- 'Explicitly close every remaining acceptance gap instead of treating completed upstream Tasks as proof that the whole Goal is achieved. Run only the missing or stale checks needed to close those gaps.',
- 'Return one auditable final delivery with evidence for every requirement. If a requirement cannot be satisfied, state the exact gap and the minimum next action; do not claim the Goal is complete.',
- graph.goal.config?.manager && graph.goal.config.managerState?.submitted?.action === 'verify'
- ? `Main Agent verification handoff (context only, not acceptance criteria):\n${graph.goal.config.managerState.submitted.reason}\nIndependently check these notes against the evidence. They do not amend the authoritative Goal requirement or establish that it passed.`
- : undefined,
- ]
- .filter(Boolean)
- .join('\n\n'),
- kind: 'task',
- priority: -1,
- title: GOAL_ACCEPTANCE_TASK_TITLE,
+ // The node and its links commit together. Once the node exists no later tick
+ // comes back to link it, so writing them in separate transactions let an
+ // interruption in between leave the acceptance detached from the work it
+ // closes for good. Rolling the node back instead lets the next tick retry.
+ const result = await this.db.transaction(async (tx) => {
+ const writer = new GoalGraphModel(tx, this.userId, this.workspaceId, {
+ id: GOAL_COORDINATOR_ACTOR_ID,
+ type: 'system',
+ });
+ const created = await writer.createNodeOnce(goalId, {
+ description: [
+ `Complete and prove the overall Goal acceptance requirement: ${graph.goal.requirement}`,
+ 'Inspect and reuse existing Goal findings, artifacts, metrics, and command results as the primary evidence. Do not repeat expensive or destructive work when the existing evidence is sufficient and still auditable.',
+ 'Explicitly close every remaining acceptance gap instead of treating completed upstream Tasks as proof that the whole Goal is achieved. Run only the missing or stale checks needed to close those gaps.',
+ 'Return one auditable final delivery with evidence for every requirement. If a requirement cannot be satisfied, state the exact gap and the minimum next action; do not claim the Goal is complete.',
+ graph.goal.config?.manager &&
+ graph.goal.config.managerState?.submitted?.action === 'verify'
+ ? `Main Agent verification handoff (context only, not acceptance criteria):\n${graph.goal.config.managerState.submitted.reason}\nIndependently check these notes against the evidence. They do not amend the authoritative Goal requirement or establish that it passed.`
+ : undefined,
+ ]
+ .filter(Boolean)
+ .join('\n\n'),
+ kind: 'task',
+ priority: -1,
+ title: GOAL_ACCEPTANCE_TASK_TITLE,
+ });
+ if (!created?.created) return created;
+
+ const problem = graph.nodes.find((node) => node.kind === 'problem');
+ if (problem) {
+ await writer.createEdge(goalId, problem.id, created.node.id, 'decomposes');
+ }
+ // Acceptance closes the whole Goal, so it builds on the work that ends each
+ // line of the graph. Linking the delivered leaf Tasks lays it out below them
+ // instead of beside the first round. They are all resolved, so nothing blocks.
+ const delivered = graph.nodes.filter(
+ (node) =>
+ node.kind === 'task' &&
+ node.status === 'resolved' &&
+ node.id !== created.node.id &&
+ !experimentOwner(graph, node.id),
+ );
+ const deliveredIds = new Set(delivered.map((node) => node.id));
+ const builtUpon = new Set(
+ graph.edges
+ .filter((edge) => edge.kind === 'depends_on' && deliveredIds.has(edge.sourceNodeId))
+ .map((edge) => edge.targetNodeId),
+ );
+ for (const leaf of delivered.filter((node) => !builtUpon.has(node.id))) {
+ await writer.createEdge(goalId, created.node.id, leaf.id, 'depends_on');
+ }
+ return created;
});
if (!result) {
return {
@@ -1727,10 +1764,6 @@ export class GoalService {
}
if (result.created) {
effects.push({ nodeId: result.node.id, type: 'created_node', detail: 'terminal acceptance' });
- const problem = graph.nodes.find((node) => node.kind === 'problem');
- if (problem) {
- await this.coordinatorGraph.createEdge(goalId, problem.id, result.node.id, 'decomposes');
- }
}
return {
goalId,
diff --git a/apps/server/src/services/goal/manager.README.md b/apps/server/src/services/goal/manager.README.md
index a1054e3d1ee..ac0c2f93283 100644
--- a/apps/server/src/services/goal/manager.README.md
+++ b/apps/server/src/services/goal/manager.README.md
@@ -25,8 +25,14 @@ the new agent's history instead of continuing the previous agent's.
The main Agent reads `lh goal show`, `lh task view`, `lh topic view`, and document
commands. It submits a JSON file through `lh goal plan <goal-id> --token <turn> --file plan.json`. The runtime supplies `LOBEHUB_OPERATION_ID`. Plan actions:
-- `tasks`: reason and 1โ€“10 objects with title/description. All existing work must
- first be settled. The coordinator creates and runs ordinary Tasks.
+- `tasks`: reason and 1โ€“10 objects with title/description and an optional
+ `dependsOn` list โ€” existing task node IDs (earlier rounds) or 0-based indexes of
+ earlier tasks in the same plan. Each entry becomes a `depends_on` edge, so the
+ graph lays rounds out in order instead of one flat row; a forward index, an
+ unknown node or a retired/rejected node rejects the whole plan before anything
+ is written. All existing work must first be settled. The coordinator creates
+ and runs ordinary Tasks. The terminal acceptance Task depends on the delivered
+ leaf Tasks, so it renders after the work it closes.
- `verify`: reason; requests the ordinary independent final acceptance Task.
This does not mark the Goal achieved.
- `retry`: reason (checkpoint-aware recovery instruction), taskId and exact
diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.ts
index e6e3c243ecd..38609097733 100644
--- a/apps/server/src/services/goal/manager.test.ts
+++ b/apps/server/src/services/goal/manager.test.ts
@@ -452,6 +452,73 @@ describe('CLI main Agent planning', () => {
});
});
+ /**
+ * Regression: every planned task used to hang only off the problem node, so a
+ * multi-round Goal rendered as one flat row with no visible progression.
+ */
+ it('links planned tasks to earlier rounds and earlier tasks through depends_on', async () => {
+ const graph = await service().create({
+ title: 'Second round',
+ createdByAgentId: agentId,
+ config: { manager: { maxTurns: 4 } },
+ });
+ const earlier = await new GoalGraphModel(db, userId).createNode(graph.goal.id, {
+ kind: 'task',
+ status: 'resolved',
+ title: 'R1 ยท Facts',
+ });
+ expect((await service().tick(graph.goal.id)).outcome).toBe('waiting_external');
+ const state = (await model().findById(graph.goal.id))!.config!.managerState!;
+ const op = await ops().findByTopicSourceMessage(
+ state.topicId,
+ `msg_goal_manager_${state.token}`,
+ );
+
+ await manager().submit(graph.goal.id, state.token, op!.id, {
+ action: 'tasks',
+ reason: 'Analyse on top of the facts',
+ tasks: [
+ { title: 'R2 ยท Options', description: 'Compare options', dependsOn: [earlier!.id] },
+ { title: 'R3 ยท Report', description: 'Write the report', dependsOn: [0] },
+ ],
+ });
+
+ const current = await service().graph(graph.goal.id);
+ const byTitle = (title: string) => current.nodes.find((n) => n.title === title)!;
+ const dependsOn = current.edges
+ .filter((edge) => edge.kind === 'depends_on')
+ .map((edge) => [edge.sourceNodeId, edge.targetNodeId]);
+ expect(dependsOn).toEqual(
+ expect.arrayContaining([
+ [byTitle('R2 ยท Options').id, earlier!.id],
+ [byTitle('R3 ยท Report').id, byTitle('R2 ยท Options').id],
+ ]),
+ );
+ expect(dependsOn).toHaveLength(2);
+ });
+
+ it.each([
+ { label: 'a forward index', dependsOn: [1] },
+ { label: 'an unknown node', dependsOn: ['node-that-does-not-exist'] },
+ ])(
+ 'rejects a plan whose dependsOn names $label without writing any task',
+ async ({ dependsOn }) => {
+ const { id, state, op } = await start();
+ await expect(
+ manager().submit(id, state.token, op.id, {
+ action: 'tasks',
+ reason: 'Plan with a bad reference',
+ tasks: [
+ { title: 'First', description: 'First task', dependsOn },
+ { title: 'Second', description: 'Second task' },
+ ],
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect((await service().graph(id)).nodes.filter((n) => n.kind === 'task')).toHaveLength(0);
+ expect((await model().findById(id))!.config!.managerState!.submitted).toBeUndefined();
+ },
+ );
+
it('does not dispatch the previous supervisor when a handoff lands before the claim', async () => {
const { id, op } = await start();
await ops().recordCompletion(op.id, { status: 'done' });
diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.ts
index 5527dc158b0..70d08fe0d87 100644
--- a/apps/server/src/services/goal/manager.ts
+++ b/apps/server/src/services/goal/manager.ts
@@ -33,7 +33,22 @@ export const goalPlanSchema = z.discriminatedUnion('action', [
action: z.literal('tasks'),
reason,
tasks: z
- .array(z.object({ title: z.string().trim().min(1).max(255), description: reason }))
+ .array(
+ z.object({
+ title: z.string().trim().min(1).max(255),
+ description: reason,
+ /**
+ * What this task builds on: an existing task node ID from the Goal
+ * graph, or the 0-based index of an earlier task in this same plan.
+ * Becomes a `depends_on` edge, which both gates dispatch and lays
+ * the graph out round by round instead of as one flat row.
+ */
+ dependsOn: z
+ .array(z.union([z.number().int().min(0), z.string().trim().min(1)]))
+ .max(20)
+ .optional(),
+ }),
+ )
.min(1)
.max(10),
})
@@ -687,15 +702,52 @@ export class GoalManagerService {
await authored.updateNodeStatus(goalId, inherited.id, 'retired', plan.reason);
}
if (plan.action === 'tasks') {
+ // Resolve every reference before writing anything, so a bad one rejects
+ // the plan whole instead of leaving half of it on the graph. A prerequisite
+ // only counts as met once `resolved`, so a retired or rejected node would
+ // block its dependent forever โ€” refuse it here rather than deadlock later.
+ // That includes the stuck node a takeover turn is replacing: `graph` is the
+ // snapshot from before the retirement above.
+ const dependable = new Set(
+ graph.nodes
+ .filter(
+ (n) =>
+ n.kind === 'task' &&
+ n.status !== 'retired' &&
+ n.status !== 'rejected' &&
+ !(state.problem && n.taskId === state.problemTaskId),
+ )
+ .map((n) => n.id),
+ );
+ plan.tasks.forEach((task, index) => {
+ for (const dep of task.dependsOn ?? []) {
+ const valid = typeof dep === 'number' ? dep < index : dependable.has(dep);
+ if (!valid)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Task ${index} dependsOn ${JSON.stringify(dep)} is neither an earlier task in this plan nor an active task node of this Goal`,
+ });
+ }
+ });
const problem = graph.nodes.find((n) => n.kind === 'problem');
- for (const task of plan.tasks) {
+ const createdIds: string[] = [];
+ for (const { dependsOn: _dependsOn, ...task } of plan.tasks) {
const node = await authored.createNode(goalId, {
...task,
kind: 'task',
status: 'proposed',
createdByAgentId: agentId,
});
- if (node && problem) await authored.createEdge(goalId, problem.id, node.id, 'decomposes');
+ if (!node) throw new Error('Failed to create a planned task');
+ createdIds.push(node.id);
+ if (problem) await authored.createEdge(goalId, problem.id, node.id, 'decomposes');
+ }
+ // Drawn dependent โ†’ prerequisite, the direction `selectFrontier` reads a blocker.
+ for (const [index, task] of plan.tasks.entries()) {
+ for (const dep of new Set(task.dependsOn ?? [])) {
+ const prerequisiteId = typeof dep === 'number' ? createdIds[dep] : dep;
+ await authored.createEdge(goalId, createdIds[index], prerequisiteId, 'depends_on');
+ }
}
} else if (plan.action === 'retry') {
const node = unfinished.find((n) => n.taskId === plan.taskId);
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 4c8247b2134..375ca442389 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -626,6 +626,10 @@
"goalProcess.gate.recommended": "recommended",
"goalProcess.gate.title.goalAcceptance": "Decide the goal acceptance outcome",
"goalProcess.gate.title.recoverTask": "Decide what happens to the failed task",
+ "goalProcess.goalAcceptance.review": "Review delivery",
+ "goalProcess.goalAcceptance.state.accepted": "Accepted",
+ "goalProcess.goalAcceptance.state.awaitingAcceptance": "Awaiting your acceptance",
+ "goalProcess.goalAcceptance.viewFull": "Read full report",
"goalProcess.graph.exitFullscreen": "Exit fullscreen",
"goalProcess.graph.fullscreen": "Fullscreen",
"goalProcess.graph.legend.hide": "Hide this kind on the map",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index a7b5fb07960..e35dbe1b55d 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -626,6 +626,10 @@
"goalProcess.gate.recommended": "ๆŽจ่",
"goalProcess.gate.title.goalAcceptance": "ๅ†ณๅฎš็›ฎๆ ‡้ชŒๆ”ถ็š„ๅŽปๅ‘",
"goalProcess.gate.title.recoverTask": "ๅ†ณๅฎšๅคฑ่ดฅไปปๅŠก็š„ๅŽปๅ‘",
+ "goalProcess.goalAcceptance.review": "ๅŽป้ชŒๆ”ถ",
+ "goalProcess.goalAcceptance.state.accepted": "ๅทฒ้ชŒๆ”ถ",
+ "goalProcess.goalAcceptance.state.awaitingAcceptance": "ๅพ…ไฝ ้ชŒๆ”ถ",
+ "goalProcess.goalAcceptance.viewFull": "ๆŸฅ็œ‹ๅ…จๆ–‡",
"goalProcess.graph.exitFullscreen": "้€€ๅ‡บๅ…จๅฑ",
"goalProcess.graph.fullscreen": "ๅ…จๅฑ",
"goalProcess.graph.legend.hide": "ๅœจๅ›พไธญ้š่—่ฟ™็ฑป่Š‚็‚น",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index b45dec76576..e1833d38905 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2011,6 +2011,10 @@ export default {
'goalProcess.acceptance.delivered': 'Awaiting your call',
'goalProcess.acceptance.errored': 'Verification error',
'goalProcess.acceptance.rejected': 'Rejected',
+ 'goalProcess.goalAcceptance.state.accepted': 'Accepted',
+ 'goalProcess.goalAcceptance.state.awaitingAcceptance': 'Awaiting your acceptance',
+ 'goalProcess.goalAcceptance.viewFull': 'Read full report',
+ 'goalProcess.goalAcceptance.review': 'Review delivery',
'goalProcess.tag.verifying': 'Verifying',
'goalProcess.tag.lost': 'Lost',
'goalProcess.tag.done': 'Done',
diff --git a/packages/prompts/src/chains/goalManager.test.ts b/packages/prompts/src/chains/goalManager.test.ts
index 8c94dc3e1ca..87dd6c5dfb2 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('v4');
+ expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v5');
expect(prompt).toContain(`Requirement: ${requirement}`);
expect(prompt).toContain('Use the language of the Goal requirement');
expect(prompt).toContain(
@@ -48,6 +48,21 @@ describe('buildGoalManagerPrompt', () => {
expect(prompt).toContain('escalate with the specific question');
});
+ /**
+ * Regression: without dependsOn every planned task hung directly off the
+ * problem node, so a four-round Goal rendered as one flat row.
+ */
+ it('asks each planned task to declare what it builds on', () => {
+ const prompt = buildGoalManagerPrompt({
+ feedback: '[]',
+ goalId: 'goal_1',
+ requirement: 'Research how agents can manage a database',
+ token: 't',
+ });
+ expect(prompt).toContain('"dependsOn":["task node ID from an earlier round", 0]');
+ expect(prompt).toContain('Never depend on a retired or rejected node');
+ });
+
it('says nothing about a takeover on an ordinary planning turn', () => {
const prompt = buildGoalManagerPrompt({
feedback: '[]',
diff --git a/packages/prompts/src/chains/goalManager.ts b/packages/prompts/src/chains/goalManager.ts
index 8ce32d70141..07722707350 100644
--- a/packages/prompts/src/chains/goalManager.ts
+++ b/packages/prompts/src/chains/goalManager.ts
@@ -1,8 +1,10 @@
/**
* 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.
+ * v5 asks each planned task to declare what it builds on (`dependsOn`), so a
+ * multi-round Goal reads as a progression instead of one flat row of tasks.
*/
-export const GOAL_MANAGER_PROMPT_VERSION = 'v4';
+export const GOAL_MANAGER_PROMPT_VERSION = 'v5';
interface GoalManagerPromptInput {
feedback: string;
@@ -18,4 +20,4 @@ interface GoalManagerPromptInput {
}
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 ?? ''}\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.`;
+ `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. Give every planned task a dependsOn list naming the work it builds on: task node IDs from lh goal show for earlier rounds, or 0-based indexes of earlier tasks in the same plan. Omit it only for work that is genuinely independent โ€” the Goal graph is laid out from these links, so a later round without them looks unrelated to the evidence it uses. Never depend on a retired or rejected node. Choose exactly one schema:\n{"action":"tasks","reason":"evidence-based rationale","tasks":[{"title":"specific task","description":"self-contained contract, inputs, output and acceptance","dependsOn":["task node ID from an earlier round", 0]}]}\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/prompts/src/chains/taskTopicHandoff.test.ts b/packages/prompts/src/chains/taskTopicHandoff.test.ts
new file mode 100644
index 00000000000..1484c704f63
--- /dev/null
+++ b/packages/prompts/src/chains/taskTopicHandoff.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { chainTaskTopicHandoff, TASK_TOPIC_HANDOFF_PROMPT_VERSION } from './taskTopicHandoff';
+
+describe('chainTaskTopicHandoff', () => {
+ /**
+ * Regression: the handoff title becomes the Goal finding's title, and titles
+ * that only said "ๅฎŒๆˆ Neon ่ƒฝๅŠ›่ฐƒ็ ”" told the reader nothing about the finding.
+ */
+ it('titles the result itself rather than the fact that work happened', () => {
+ const payload = chainTaskTopicHandoff({
+ lastAssistantContent: '็ป“่ฎบ๏ผšNeon ่ƒฝ่ฆ†็›–ไปŽๅผ€้€šๅˆฐ็ฎก็†็š„ๅฎŒๆ•ด้“พ่ทฏใ€‚',
+ responseLanguage: 'zh-CN',
+ taskInstruction: 'Research Neon capabilities',
+ taskName: 'R1 ยท Neon ่ƒฝ็ป™ agent ๆไพ›ไป€ไนˆ๏ผŸ',
+ });
+ const system = payload.messages![0].content as string;
+
+ expect(TASK_TOPIC_HANDOFF_PROMPT_VERSION).toBe('v1.1');
+ expect(system).toContain('what was found, decided or delivered');
+ expect(system).toContain('never a status such as "Completed X", "Task done" or "ๅฎŒๆˆ X"');
+ expect(system).toContain('condense that line into the title');
+ });
+});
diff --git a/packages/prompts/src/chains/taskTopicHandoff.ts b/packages/prompts/src/chains/taskTopicHandoff.ts
index 2c92b310f9a..3ea20503747 100644
--- a/packages/prompts/src/chains/taskTopicHandoff.ts
+++ b/packages/prompts/src/chains/taskTopicHandoff.ts
@@ -5,7 +5,7 @@ import type { ChatStreamPayload } from '@lobechat/types';
* `tracing.promptVersion` at the call site so per-call tracing groups runs
* by prompt iteration.
*/
-export const TASK_TOPIC_HANDOFF_PROMPT_VERSION = 'v1.0';
+export const TASK_TOPIC_HANDOFF_PROMPT_VERSION = 'v1.1';
export const TASK_TOPIC_HANDOFF_SCHEMA_NAME = 'task_topic_handoff';
@@ -32,7 +32,7 @@ export const chainTaskTopicHandoff = (params: {
content: `You are a task execution summarizer. A topic (one round of agent execution) has just completed within a task. Generate a handoff summary for the next topic to read.
Output a JSON object with these fields:
-- "title": A concise title summarizing what this topic accomplished (max 50 chars)
+- "title": The headline result of this topic (max 50 chars): what was found, decided or delivered, readable on its own
- "summary": A 1-3 sentence summary of what was done and the key outcome
- "keyFindings": An array of key findings or decisions made (optional, max 5 items)
- "nextAction": What the next topic should do (optional, 1 sentence)
@@ -40,6 +40,7 @@ Output a JSON object with these fields:
Rules:
- Focus on WHAT WAS ACCOMPLISHED, not what was asked
- ${languageInstruction}
+- The title states the result itself, not that work happened: never a status such as "Completed X", "Task done" or "ๅฎŒๆˆ X". If the response opens with an explicit conclusion line, condense that line into the title
- Keep title short and specific
- summary should capture the essential outcome a new topic needs to know
- Output ONLY the JSON object, no markdown fences or explanations`,
diff --git a/src/features/AgentGoals/ProcessControl/Frontier.tsx b/src/features/AgentGoals/ProcessControl/Frontier.tsx
index d733e16f7e7..2cbcae686d8 100644
--- a/src/features/AgentGoals/ProcessControl/Frontier.tsx
+++ b/src/features/AgentGoals/ProcessControl/Frontier.tsx
@@ -20,8 +20,10 @@ import {
coordinatorGateReason,
coordinatorNodeTitleKey,
coordinatorReasonCopy,
+ isGoalAcceptanceTask,
viewGateKind,
} from './coordinatorCopy';
+import { GoalFinalAcceptance } from './GoalAcceptanceCard';
import type { FrontierItem, GoalGraphView, GoalNodeView } from './goalGraphViewModel';
import { useElapsed } from './useElapsed';
@@ -500,6 +502,12 @@ const Frontier = memo<FrontierProps>(({ actions, canEdit, graph, onSelect, plann
graph.nodes.filter((view) => view.seq !== undefined).map((view) => [view.node.id, view.seq!]),
);
const achieved = graph.goal.status === 'achieved';
+ // Once the Goal's final acceptance finished, its acceptance document is what
+ // the owner reads next, so it takes the task list's place (the component
+ // keeps the list until the latest round is confirmed passed).
+ const finalAcceptanceView = graph.nodes.find(
+ (view) => isGoalAcceptanceTask(view) && view.node.status === 'resolved' && !!view.acceptance,
+ );
return (
<Flexbox gap={8}>
@@ -520,73 +528,77 @@ const Frontier = memo<FrontierProps>(({ actions, canEdit, graph, onSelect, plann
{canEdit && <AddTaskButton onAdd={actions.addTask} />}
</Flexbox>
- <div className={styles.list}>
- <Block gap={0} padding={2} variant={'borderless'}>
- {graph.frontier.length === 0 &&
- (planning ? (
- <Flexbox horizontal align={'center'} gap={10} padding={12}>
- <RunningGlyph size={16} />
- <Flexbox gap={2}>
- <Text weight={500}>{t('goalProcess.planning.title')}</Text>
+ <GoalFinalAcceptance graph={graph} view={finalAcceptanceView}>
+ <div className={styles.list}>
+ <Block gap={0} padding={2} variant={'borderless'}>
+ {graph.frontier.length === 0 &&
+ (planning ? (
+ <Flexbox horizontal align={'center'} gap={10} padding={12}>
+ <RunningGlyph size={16} />
+ <Flexbox gap={2}>
+ <Text weight={500}>{t('goalProcess.planning.title')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.planning.description')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ ) : (
+ <Flexbox gap={2} padding={12}>
+ <Text weight={500}>
+ {achieved
+ ? t('goalProcess.frontier.achievedTitle')
+ : t('goalProcess.frontier.emptyTitle')}
+ </Text>
<Text fontSize={12} type={'secondary'}>
- {t('goalProcess.planning.description')}
+ {achieved
+ ? t('goalProcess.frontier.achievedDescription')
+ : t('goalProcess.frontier.emptyDescription')}
</Text>
</Flexbox>
- </Flexbox>
- ) : (
- <Flexbox gap={2} padding={12}>
- <Text weight={500}>
- {achieved
- ? t('goalProcess.frontier.achievedTitle')
- : t('goalProcess.frontier.emptyTitle')}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {achieved
- ? t('goalProcess.frontier.achievedDescription')
- : t('goalProcess.frontier.emptyDescription')}
- </Text>
- </Flexbox>
+ ))}
+ {graph.frontier.map((item, index) => (
+ <Fragment key={item.key}>
+ {index > 0 && <Divider dashed style={{ margin: 0 }} />}
+ <FrontierRow
+ actions={actions}
+ canEdit={canEdit}
+ item={item}
+ numbers={numbers}
+ subject={
+ item.view.gateSubjectId ? graph.byId[item.view.gateSubjectId] : undefined
+ }
+ onSelect={onSelect}
+ />
+ </Fragment>
))}
- {graph.frontier.map((item, index) => (
- <Fragment key={item.key}>
- {index > 0 && <Divider dashed style={{ margin: 0 }} />}
- <FrontierRow
- actions={actions}
- canEdit={canEdit}
- item={item}
- numbers={numbers}
- subject={item.view.gateSubjectId ? graph.byId[item.view.gateSubjectId] : undefined}
- onSelect={onSelect}
- />
- </Fragment>
- ))}
- </Block>
- {graph.blocked.length > 0 && (
- <>
- <Divider dashed style={{ margin: 0 }} />
- <div className={styles.blockedHead} onClick={() => setShowBlocked(!showBlocked)}>
- <Icon icon={showBlocked ? ChevronDown : ChevronRight} size={12} />
- <span>{t('goalProcess.frontier.blocked', { count: graph.blocked.length })}</span>
- </div>
- {showBlocked && (
- <Block gap={0} padding={2} variant={'borderless'}>
- {graph.blocked.map((view, index) => (
- <Fragment key={view.node.id}>
- {index > 0 && <Divider dashed style={{ margin: 0 }} />}
- <FrontierRow
- actions={actions}
- canEdit={canEdit}
- item={{ key: view.node.id, kind: 'ready', rank: 3, view }}
- numbers={numbers}
- onSelect={onSelect}
- />
- </Fragment>
- ))}
- </Block>
- )}
- </>
- )}
- </div>
+ </Block>
+ {graph.blocked.length > 0 && (
+ <>
+ <Divider dashed style={{ margin: 0 }} />
+ <div className={styles.blockedHead} onClick={() => setShowBlocked(!showBlocked)}>
+ <Icon icon={showBlocked ? ChevronDown : ChevronRight} size={12} />
+ <span>{t('goalProcess.frontier.blocked', { count: graph.blocked.length })}</span>
+ </div>
+ {showBlocked && (
+ <Block gap={0} padding={2} variant={'borderless'}>
+ {graph.blocked.map((view, index) => (
+ <Fragment key={view.node.id}>
+ {index > 0 && <Divider dashed style={{ margin: 0 }} />}
+ <FrontierRow
+ actions={actions}
+ canEdit={canEdit}
+ item={{ key: view.node.id, kind: 'ready', rank: 3, view }}
+ numbers={numbers}
+ onSelect={onSelect}
+ />
+ </Fragment>
+ ))}
+ </Block>
+ )}
+ </>
+ )}
+ </div>
+ </GoalFinalAcceptance>
</Flexbox>
);
});
diff --git a/src/features/AgentGoals/ProcessControl/GoalAcceptanceCard.tsx b/src/features/AgentGoals/ProcessControl/GoalAcceptanceCard.tsx
new file mode 100644
index 00000000000..72240766935
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/GoalAcceptanceCard.tsx
@@ -0,0 +1,181 @@
+'use client';
+
+import { Flexbox, Icon, Markdown } from '@lobehub/ui';
+import { Button, Tag, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { FileText } from 'lucide-react';
+import type { MouseEvent, ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAcceptanceBundle } from '@/features/Acceptance/hooks';
+import { useClientDataSWR } from '@/libs/swr';
+import { portalKeys } from '@/libs/swr/keys';
+import { documentService } from '@/services/document';
+import { useChatStore } from '@/store/chat';
+
+import {
+ goalAcceptanceState,
+ isFinalAcceptanceReady,
+ latestRunStatus,
+ pickFinalDeliverable,
+} from './goalAcceptanceReport';
+import type { GoalGraphView, GoalNodeView } from './goalGraphViewModel';
+
+/**
+ * The Goal's final deliverable, in place of the task list.
+ *
+ * Once every task ran through and the final acceptance passed, nothing is left
+ * to advance: what the owner wants to read is what the Goal produced. So the
+ * list gives way to that product โ€” the document the work wrote, its title and a
+ * preview of its content โ€” and the full document opens in the side Portal, like
+ * every other drill-down here. Neither the acceptance report nor the synthesized
+ * finding stands in for it: both are about the product, not the product.
+ *
+ * Until that point (see `isFinalAcceptanceReady`), or when the Goal produced no
+ * document, the list stays exactly as it was.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ document: css`
+ cursor: pointer;
+
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+
+ width: 100%;
+ padding-block: 16px;
+ padding-inline: 18px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadius};
+
+ text-align: start;
+
+ background: ${cssVar.colorBgContainer};
+
+ &:hover {
+ border-color: ${cssVar.colorBorder};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimary};
+ outline-offset: -2px;
+ }
+ `,
+ preview: css`
+ overflow: hidden;
+ max-height: 320px;
+
+ mask-image: linear-gradient(to bottom, #000 75%, transparent);
+ `,
+}));
+
+interface GoalFinalAcceptanceProps {
+ /** The task list, shown until the Goal's final deliverable can replace it. */
+ children: ReactNode;
+ graph: GoalGraphView;
+ /** The Goal's resolved final acceptance task, when there is one. */
+ view?: GoalNodeView;
+}
+
+// The tag and the button are their own actions, not "open the document".
+const stop = (event: MouseEvent) => event.stopPropagation();
+
+const FinalDeliverable = ({
+ acceptance,
+ children,
+ graph,
+ view,
+}: GoalFinalAcceptanceProps & {
+ acceptance: NonNullable<GoalNodeView['acceptance']>;
+ view: GoalNodeView;
+}) => {
+ const { t } = useTranslation('chat');
+ const openAcceptance = useChatStore((s) => s.openAcceptance);
+ const openDocument = useChatStore((s) => s.openDocument);
+
+ const { data } = useAcceptanceBundle(acceptance.id);
+ const state = goalAcceptanceState(acceptance.status, latestRunStatus(data?.rounds ?? []));
+ const ready = !!data && isFinalAcceptanceReady(view.node.status, state);
+ const deliverable = ready ? pickFinalDeliverable(graph.artifacts, view.node.id) : undefined;
+
+ // The graph carries only the document id; its content is read for the preview.
+ const { data: document } = useClientDataSWR(
+ deliverable ? portalKeys.documentHeader(deliverable.documentId) : null,
+ () => documentService.getDocumentById(deliverable!.documentId),
+ );
+
+ if (!deliverable) return <>{children}</>;
+
+ const open = () => openDocument(deliverable.documentId, deliverable.agentDocumentId);
+ const producer = graph.byId[deliverable.nodeId]?.node.title;
+
+ return (
+ <Flexbox gap={10}>
+ <div
+ className={styles.document}
+ role={'button'}
+ tabIndex={0}
+ onClick={open}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ open();
+ }}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={cssVar.colorTextSecondary} icon={FileText} size={16} />
+ <Text ellipsis fontSize={15} style={{ flex: 1, minWidth: 0 }} weight={600}>
+ {document?.title || deliverable.title || t('goalProcess.deliverables.untitled')}
+ </Text>
+ <Tag
+ color={state === 'accepted' ? 'success' : 'warning'}
+ size={'small'}
+ style={{ cursor: 'pointer' }}
+ onClick={(event) => {
+ stop(event);
+ openAcceptance(acceptance.id);
+ }}
+ >
+ {t(
+ state === 'accepted'
+ ? 'goalProcess.goalAcceptance.state.accepted'
+ : 'goalProcess.goalAcceptance.state.awaitingAcceptance',
+ )}
+ </Tag>
+ </Flexbox>
+ {!!producer && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.deliverables.from', { title: producer })}
+ </Text>
+ )}
+ {!!document?.content && (
+ <div className={styles.preview}>
+ <Markdown fontSize={13} variant={'chat'}>
+ {document.content}
+ </Markdown>
+ </div>
+ )}
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.goalAcceptance.viewFull')}
+ </Text>
+ </div>
+ {state === 'awaitingAcceptance' && (
+ <Flexbox horizontal>
+ <Button size={'small'} type={'primary'} onClick={() => openAcceptance(acceptance.id)}>
+ {t('goalProcess.goalAcceptance.review')}
+ </Button>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+};
+
+export const GoalFinalAcceptance = ({ children, graph, view }: GoalFinalAcceptanceProps) => {
+ if (!view?.acceptance) return <>{children}</>;
+ return (
+ <FinalDeliverable acceptance={view.acceptance} graph={graph} view={view}>
+ {children}
+ </FinalDeliverable>
+ );
+};
diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts
index f8b1b68c39d..c13936375eb 100644
--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts
+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts
@@ -34,6 +34,21 @@ describe('coordinatorNodeTitleKey', () => {
});
});
+describe('isGoalAcceptanceTask', () => {
+ it('recognizes only the terminal Goal acceptance task', async () => {
+ const { isGoalAcceptanceTask } = await import('./coordinatorCopy');
+ const view = (node: any) => ({ humanTouches: [], node }) as any;
+
+ expect(
+ isGoalAcceptanceTask(view({ kind: 'task', title: 'Complete full Goal acceptance' })),
+ ).toBe(true);
+ expect(isGoalAcceptanceTask(view({ kind: 'task', title: 'R2 ยท ๅฏนๆฏ”' }))).toBe(false);
+ expect(
+ isGoalAcceptanceTask(view({ kind: 'decision', title: 'Complete full Goal acceptance' })),
+ ).toBe(false);
+ });
+});
+
describe('coordinatorGateReason', () => {
it('strips the question template down to the reason', () => {
expect(
diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts
index 9cc269d0d9c..a739c4e3a36 100644
--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts
+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts
@@ -36,14 +36,17 @@ export const viewGateKind = (view: GoalNodeView): CoordinatorGateKind | undefine
export const gateTitleKey = (kind: CoordinatorGateKind): string => `goalProcess.gate.title.${kind}`;
+/** The coordinator's terminal Task that accepts the whole Goal (matched by its fixed title). */
+export const isGoalAcceptanceTask = (view: GoalNodeView): boolean =>
+ view.node.kind === 'task' && view.node.title === GOAL_ACCEPTANCE_TASK_TITLE;
+
/**
* Locale key for a coordinator-authored fixed node title (gate nodes and the
* terminal Goal-acceptance Task), or undefined for user/agent-authored nodes.
*/
export const coordinatorNodeTitleKey = (view: GoalNodeView): string | undefined => {
const { node } = view;
- if (node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE)
- return 'goalProcess.node.terminalAcceptance';
+ if (isGoalAcceptanceTask(view)) return 'goalProcess.node.terminalAcceptance';
if (node.kind === 'decision') {
const kind = viewGateKind(view);
if (kind) return gateTitleKey(kind);
diff --git a/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.test.ts b/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.test.ts
new file mode 100644
index 00000000000..44ad438e3d8
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ goalAcceptanceState,
+ isFinalAcceptanceReady,
+ latestRunStatus,
+ pickFinalDeliverable,
+} from './goalAcceptanceReport';
+
+describe('goalAcceptanceState', () => {
+ /**
+ * Regression: the terminal acceptance only ever showed a small "ๅพ…ไฝ ็กฎ่ฎค" chip,
+ * which read the same for a Goal awaiting sign-off and one that failed.
+ */
+ it('tells a passed delivery awaiting sign-off from one that needs a decision', () => {
+ expect(goalAcceptanceState('delivered', 'passed')).toBe('awaitingAcceptance');
+ expect(goalAcceptanceState('delivered', 'failed')).toBe('awaitingDecision');
+ expect(goalAcceptanceState('delivered', undefined)).toBe('awaitingDecision');
+ });
+
+ it('maps the running and settled statuses', () => {
+ expect(goalAcceptanceState('verifying')).toBe('inProgress');
+ expect(goalAcceptanceState('repairing')).toBe('inProgress');
+ expect(goalAcceptanceState('planned')).toBe('inProgress');
+ expect(goalAcceptanceState('accepted')).toBe('accepted');
+ expect(goalAcceptanceState('rejected')).toBe('rejected');
+ expect(goalAcceptanceState('errored')).toBe('errored');
+ expect(goalAcceptanceState('closed')).toBeUndefined();
+ });
+});
+
+describe('isFinalAcceptanceReady', () => {
+ /**
+ * Regression: the report view showed on an acceptance that was still lost and
+ * retrying, next to a ledger of failed attempts. It belongs only to a Goal
+ * whose final acceptance finished and waits on sign-off.
+ */
+ it('shows the report only once the acceptance task finished and passed', () => {
+ expect(isFinalAcceptanceReady('resolved', 'awaitingAcceptance')).toBe(true);
+ expect(isFinalAcceptanceReady('resolved', 'accepted')).toBe(true);
+ expect(isFinalAcceptanceReady('active', 'awaitingAcceptance')).toBe(false);
+ expect(isFinalAcceptanceReady('waiting', 'awaitingDecision')).toBe(false);
+ expect(isFinalAcceptanceReady('resolved', 'awaitingDecision')).toBe(false);
+ expect(isFinalAcceptanceReady('resolved', 'inProgress')).toBe(false);
+ expect(isFinalAcceptanceReady('resolved', undefined)).toBe(false);
+ });
+});
+
+describe('pickFinalDeliverable', () => {
+ const artifact = (
+ resourceId: string,
+ minute: number,
+ nodeId = 'task_work',
+ type = 'document',
+ ) => ({
+ createdAt: new Date(2026, 8, 16, 1, minute),
+ nodeId,
+ resourceId,
+ title: `Doc ${resourceId}`,
+ type,
+ });
+
+ /**
+ * Regression: the finished Goal showed the acceptance report (and before that
+ * the acceptance Task's synthesized finding) in place of the task list, while
+ * the owner wanted to read the product the Goal made.
+ */
+ it('picks the newest document the work produced', () => {
+ expect(
+ pickFinalDeliverable(
+ [
+ artifact('docs_old', 1),
+ artifact('docs_new', 5),
+ artifact('file_1', 9, 'task_work', 'file'),
+ ],
+ 'task_acceptance',
+ ),
+ ).toEqual({ documentId: 'docs_new', nodeId: 'task_work', title: 'Doc docs_new' });
+ });
+
+ it('prefers the work over a document the acceptance task wrote', () => {
+ expect(
+ pickFinalDeliverable(
+ [artifact('docs_work', 1), artifact('docs_check_notes', 9, 'task_acceptance')],
+ 'task_acceptance',
+ ),
+ ).toMatchObject({ documentId: 'docs_work' });
+
+ expect(
+ pickFinalDeliverable([artifact('docs_check_notes', 9, 'task_acceptance')], 'task_acceptance'),
+ ).toMatchObject({ documentId: 'docs_check_notes' });
+ });
+
+ it('keeps the binding id so the document opens in-app', () => {
+ expect(
+ pickFinalDeliverable(
+ [{ ...artifact('docs_1', 1), agentDocumentId: 'agd_1' }],
+ 'task_acceptance',
+ ),
+ ).toMatchObject({ agentDocumentId: 'agd_1', documentId: 'docs_1' });
+ });
+
+ it('returns nothing when the Goal left no document', () => {
+ expect(pickFinalDeliverable([], 'task_acceptance')).toBeUndefined();
+ expect(
+ pickFinalDeliverable([artifact('file_1', 1, 'task_work', 'file')], 'task_acceptance'),
+ ).toBeUndefined();
+ });
+});
+
+describe('latestRunStatus', () => {
+ it('reads the newest round', () => {
+ expect(
+ latestRunStatus([
+ { run: { status: 'failed' } },
+ { run: { status: 'failed' } },
+ { run: { status: 'repairing' } },
+ ]),
+ ).toBe('repairing');
+ expect(latestRunStatus([])).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.ts b/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.ts
new file mode 100644
index 00000000000..4abc0cc2241
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.ts
@@ -0,0 +1,105 @@
+/**
+ * What the terminal Goal acceptance means to the person who owns the Goal.
+ *
+ * `delivered` alone cannot be rendered honestly: a round that passed and is
+ * waiting for sign-off lands there, and so does one that ran out of rounds
+ * without passing. The latest round's status tells them apart.
+ */
+export type GoalAcceptanceState =
+ 'accepted' | 'awaitingAcceptance' | 'awaitingDecision' | 'errored' | 'inProgress' | 'rejected';
+
+export const goalAcceptanceState = (
+ status: string,
+ latestRunStatus?: string | null,
+): GoalAcceptanceState | undefined => {
+ switch (status) {
+ case 'accepted': {
+ return 'accepted';
+ }
+ case 'delivered': {
+ return latestRunStatus === 'passed' ? 'awaitingAcceptance' : 'awaitingDecision';
+ }
+ case 'errored': {
+ return 'errored';
+ }
+ case 'pending':
+ case 'planned':
+ case 'repairing':
+ case 'verifying': {
+ return 'inProgress';
+ }
+ case 'rejected': {
+ return 'rejected';
+ }
+ default: {
+ return undefined;
+ }
+ }
+};
+
+/**
+ * Whether the final acceptance has earned its report view: the acceptance Task
+ * finished (its node resolved) and the only thing left is the owner's sign-off,
+ * or it was already signed off. Anything short of that โ€” still running, lost,
+ * failed, parked on a gate โ€” is ordinary work and keeps the ordinary row.
+ */
+export const isFinalAcceptanceReady = (
+ nodeStatus: string,
+ state: GoalAcceptanceState | undefined,
+): boolean => nodeStatus === 'resolved' && (state === 'awaitingAcceptance' || state === 'accepted');
+
+interface ArtifactLike {
+ agentDocumentId?: string;
+ createdAt: Date;
+ nodeId: string;
+ resourceId: string | null;
+ title: string | null;
+ type: string;
+}
+
+export interface FinalDeliverable {
+ agentDocumentId?: string;
+ documentId: string;
+ /** The task node that produced it. */
+ nodeId: string;
+ title: string | null;
+}
+
+/**
+ * The document the Goal produced โ€” the product itself, which is what the owner
+ * opens a finished Goal to read. Never the acceptance report or a synthesized
+ * finding: those describe the product.
+ *
+ * The newest document wins, but one written by the work outranks one written by
+ * the final acceptance Task, whose job is to check the product rather than to
+ * be it. Returns nothing when the Goal left no document behind.
+ */
+export const pickFinalDeliverable = (
+ artifacts: ArtifactLike[],
+ acceptanceNodeId: string,
+): FinalDeliverable | undefined => {
+ const documents = artifacts
+ .filter((artifact) => artifact.type === 'document' && artifact.resourceId)
+ .sort(
+ (a, b) =>
+ Number(a.nodeId === acceptanceNodeId) - Number(b.nodeId === acceptanceNodeId) ||
+ b.createdAt.getTime() - a.createdAt.getTime(),
+ );
+ const picked = documents[0];
+ if (!picked?.resourceId) return undefined;
+
+ return {
+ ...(picked.agentDocumentId ? { agentDocumentId: picked.agentDocumentId } : {}),
+ documentId: picked.resourceId,
+ nodeId: picked.nodeId,
+ title: picked.title,
+ };
+};
+
+interface RoundLike {
+ run: { status: string | null };
+}
+
+/** Rounds arrive in round order; the newest one decides the state. */
+export const latestRunStatus = (rounds: RoundLike[]): string | null | undefined =>
+ rounds.at(-1)?.run.status;