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): declare each deliverable once, on the node that delivered it (#20234)

Arvin Xu33bd7a6d6048
diff --git a/apps/server/src/routers/lambda/notebook.test.ts b/apps/server/src/routers/lambda/notebook.test.ts
index 82858e0959d..250d462032c 100644
--- a/apps/server/src/routers/lambda/notebook.test.ts
+++ b/apps/server/src/routers/lambda/notebook.test.ts
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
findDocumentById: vi.fn(),
findOwnOperationById: vi.fn(),
findTopicById: vi.fn(),
+ findVerbatimTwin: vi.fn(),
registerDocument: vi.fn(),
}));
vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));
@@ -22,7 +23,7 @@ vi.mock('@/database/models/document', () => ({
}));
vi.mock('@/database/models/topicDocument', () => ({
TopicDocumentModel: vi.fn().mockImplementation(function () {
- return { associate: mocks.associate };
+ return { associate: mocks.associate, findVerbatimTwin: mocks.findVerbatimTwin };
}),
}));
vi.mock('@/database/models/topic', () => ({
@@ -100,6 +101,39 @@ describe('notebook document work provenance', () => {
expect(mocks.registerDocument).not.toHaveBeenCalled();
});
+ it('reuses a document this topic already holds verbatim instead of forking it', async () => {
+ // One report written through the agent documents tool and again through
+ // this one used to leave two documents behind: two entries in the topic's
+ // list and two deliverable cards on the goal graph, for one report.
+ mocks.findVerbatimTwin.mockResolvedValue({ id: 'doc-existing' });
+
+ const result = await (await caller()).createDocument(input);
+
+ expect(mocks.findVerbatimTwin).toHaveBeenCalledWith({
+ content: input.content,
+ fileType: 'markdown',
+ title: input.title,
+ topicId: input.topicId,
+ });
+ expect(result).toEqual({ id: 'doc-existing' });
+ expect(mocks.create).not.toHaveBeenCalled();
+ expect(mocks.associate).not.toHaveBeenCalled();
+ expect(mocks.registerDocument).not.toHaveBeenCalled();
+ });
+
+ it('carries the requested kind into the twin search', async () => {
+ // A plan is found by its type, so the search has to know it is looking for
+ // one and not reuse a markdown note that holds the same text.
+ await (await caller()).createDocument({ ...input, type: 'agent/plan' });
+
+ expect(mocks.findVerbatimTwin).toHaveBeenCalledWith({
+ content: input.content,
+ fileType: 'agent/plan',
+ title: input.title,
+ topicId: input.topicId,
+ });
+ });
+
it('rejects inaccessible ancestry before writing', async () => {
mocks.findOwnOperationById
.mockResolvedValueOnce({ id: 'child', topicId: 'topic-1', parentOperationId: 'foreign' })
diff --git a/apps/server/src/routers/lambda/notebook.ts b/apps/server/src/routers/lambda/notebook.ts
index f89ff1fdfa4..b67f1096a88 100644
--- a/apps/server/src/routers/lambda/notebook.ts
+++ b/apps/server/src/routers/lambda/notebook.ts
@@ -98,6 +98,24 @@ export const notebookRouter = router({
? await resolveRootOperation((id) => ctx.operationModel.findOwnOperationById(id), operation)
: null;
+ // One report written twice β€” through the agent documents tool and through
+ // this one β€” used to land as two documents: two entries in the topic's
+ // document list, two Works, and two deliverable cards on the goal graph,
+ // all for one piece of work. A byte-identical document of the same kind
+ // already in this topic is that second write, so it reuses the row
+ // instead of forking the document. Nothing changed, so nothing is
+ // registered either. The kind travels with the search, because a document
+ // is found by its type: `agent/plan` and the labelled kinds (`article` /
+ // `note` / `report`) stay distinct, so a plan is never answered with a
+ // markdown note and a note is never answered with a markdown row.
+ const twin = await ctx.topicDocumentModel.findVerbatimTwin({
+ content: input.content,
+ fileType: input.type,
+ title: input.title,
+ topicId: input.topicId,
+ });
+ if (twin) return twin;
+
// Create the document
const document = await ctx.documentModel.create({
content: input.content,
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index e25cc128712..4f51b4f8e91 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -18,6 +18,7 @@ import {
acceptances,
agentOperations,
agents,
+ documents,
goalEdges,
goalEvents,
goalNodeDecisions,
@@ -677,6 +678,151 @@ describe('GoalService', () => {
(link) => link.nodeId === created.nodeId && link.work?.title === 'Delivered once',
);
expect(delivered).toHaveLength(1);
+ // The execution container is claimed once per node too, not once per
+ // settle: re-linking the completed version added a second identical row for
+ // the same task, which is where half of a goal's Work links came from.
+ expect(
+ snapshot.workVersions.filter(
+ (link) => link.nodeId === created.nodeId && link.work?.type === 'task',
+ ),
+ ).toHaveLength(1);
+ });
+
+ it('does not declare a shared document a task only revised', async () => {
+ // A backlog document every task appends to used to be declared as the
+ // output of every task that touched it, because a Work registered during a
+ // run counted as that run's deliverable. Only a Work one of the task's own
+ // runs created is one; a revision is not a delivery.
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const graph = await service.create({
+ tasks: ['Deliver me'],
+ title: 'Revisions are not deliveries',
+ });
+ const created = await service.tick(graph.goal.id);
+ const [backlog] = await serverDB
+ .insert(documents)
+ .values({
+ content: 'Shared backlog body',
+ fileType: 'markdown',
+ filename: 'Shared backlog',
+ source: 'notebook',
+ sourceType: 'api',
+ title: 'Shared backlog',
+ totalCharCount: 19,
+ totalLineCount: 1,
+ userId,
+ })
+ .returning();
+ // Written by an earlier task's run; this task only appends to it.
+ await workModel.registerDocument({
+ changeType: 'created',
+ documentId: backlog.id,
+ rootOperationId: 'op-wrote-it-first',
+ toolIdentifier: 'lobehub-notebook',
+ toolName: 'createDocument',
+ });
+ await serverDB.insert(taskTopics).values({
+ handoff: { summary: 'Delivered', title: 'Delivered title' },
+ operationId: 'op-delivered',
+ seq: 1,
+ status: 'completed',
+ taskId: created.taskId!,
+ userId,
+ });
+ await workModel.registerDocument({
+ changeType: 'updated',
+ documentId: backlog.id,
+ rootOperationId: 'op-delivered',
+ toolIdentifier: 'lobe-agent-documents',
+ toolName: 'modifyNodes',
+ });
+ await taskModel.updateStatus(created.taskId!, 'completed');
+
+ await service.tick(graph.goal.id);
+
+ const snapshot = await service.graph(graph.goal.id);
+ expect(
+ snapshot.workVersions.filter(
+ (link) => link.nodeId === created.nodeId && link.work?.resourceId === backlog.id,
+ ),
+ ).toHaveLength(0);
+ });
+
+ it('declares a deliverable once, on the node that delivered it', async () => {
+ // The flare case behind the reported duplicate deliverables: one document
+ // delivered by a node, then written again by another node's run, appeared
+ // as a deliverable of both.
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const workModel = new WorkModel(serverDB, userId);
+ const graph = await service.create({
+ tasks: ['First delivery', 'Second delivery'],
+ title: 'One claim per deliverable',
+ });
+ const [backlog] = await serverDB
+ .insert(documents)
+ .values({
+ content: 'Shared backlog body',
+ fileType: 'markdown',
+ filename: 'Shared backlog',
+ source: 'notebook',
+ sourceType: 'api',
+ title: 'Shared backlog',
+ totalCharCount: 19,
+ totalLineCount: 1,
+ userId,
+ })
+ .returning();
+
+ const first = await service.tick(graph.goal.id);
+ await serverDB.insert(taskTopics).values({
+ handoff: { summary: 'Delivered', title: 'Delivered title' },
+ operationId: 'op-first',
+ seq: 1,
+ status: 'completed',
+ taskId: first.taskId!,
+ userId,
+ });
+ await workModel.registerDocument({
+ changeType: 'created',
+ documentId: backlog.id,
+ rootOperationId: 'op-first',
+ toolIdentifier: 'lobe-agent-documents',
+ toolName: 'createDocument',
+ });
+ await taskModel.updateStatus(first.taskId!, 'completed');
+ await service.tick(graph.goal.id);
+
+ const second = await service.tick(graph.goal.id);
+ expect(second.taskId).toBeTruthy();
+ await serverDB.insert(taskTopics).values({
+ handoff: { summary: 'Delivered again', title: 'Delivered again' },
+ operationId: 'op-second',
+ seq: 1,
+ status: 'completed',
+ taskId: second.taskId!,
+ userId,
+ });
+ // The second node's run writes the same document (a new version of the same
+ // Work), which is what a shared backlog looks like from the graph's side.
+ await workModel.registerDocument({
+ changeType: 'created',
+ documentId: backlog.id,
+ rootOperationId: 'op-second',
+ toolIdentifier: 'lobehub-notebook',
+ toolName: 'createDocument',
+ });
+ await taskModel.updateStatus(second.taskId!, 'completed');
+ await service.tick(graph.goal.id);
+
+ const snapshot = await service.graph(graph.goal.id);
+ const claims = snapshot.workVersions.filter(
+ (link) => link.work?.resourceId === backlog.id && link.relation === 'produced',
+ );
+ expect(claims).toHaveLength(1);
+ expect(claims[0].nodeId).toBe(first.nodeId);
});
it('leaves a fresh dispatch claim alone', async () => {
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index ae4f55145d9..ee6dd4fd6d8 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -3132,6 +3132,17 @@ export class GoalService {
* linked at their newest version, so a document refined across rounds is one
* deliverable with a history rather than several deliverables.
*
+ * Two rules keep one deliverable from being declared once per task:
+ *
+ * - **Created only.** A Work none of the task's runs created is someone
+ * else's artifact this task happened to revise. A shared backlog document
+ * that every run appends to is the case that surfaced this: without the
+ * rule the document is declared as the output of every task in the goal.
+ * - **Claimed once per goal.** The first node to deliver a Work owns it. A
+ * later node that revises it adds no link and no lifecycle event, so the
+ * history reads "C1-c delivered the backlog" instead of repeating the same
+ * deliverable under each task.
+ *
* `task` Works are deliberately excluded: the responsible task's own Work is
* the execution container and the caller already links it. `file` Works are
* opt-in at the registry (conversation lists do not want every exported
@@ -3155,14 +3166,29 @@ export class GoalService {
rootOperationIds: operationIds,
});
- const newestByWork = new Map<string, WorkVersionEventItem>();
+ const claimedWorkIds = await this.coordinatorGraph.listProducedWorkIds(goalId);
+
+ // Per Work: whether the task's runs created it, and the newest version they
+ // registered. `created` is sticky across the run's versions β€” a document
+ // written in round one and revised in round three is still this task's
+ // deliverable, while one that was only ever revised is not.
+ const harvestByWork = new Map<string, { created: boolean; item: WorkVersionEventItem }>();
for (const item of Object.values(byOperation).flat()) {
if (item.type === 'task') continue;
- const seen = newestByWork.get(item.id);
- if (!seen || seen.version.createdAt < item.version.createdAt) newestByWork.set(item.id, item);
+ const seen = harvestByWork.get(item.id);
+ const created = item.version.changeType === 'created';
+ if (!seen) {
+ harvestByWork.set(item.id, { created, item });
+ continue;
+ }
+ harvestByWork.set(item.id, {
+ created: seen.created || created,
+ item: seen.item.version.createdAt < item.version.createdAt ? item : seen.item,
+ });
}
- for (const item of newestByWork.values()) {
+ for (const [workId, { created, item }] of harvestByWork) {
+ if (!created || claimedWorkIds.has(workId)) continue;
const link = await this.coordinatorGraph.attachWorkVersion(
goalId,
nodeId,
@@ -3227,7 +3253,18 @@ export class GoalService {
type: 'node_status',
detail: 'resolved',
});
- if (completedWork?.currentVersionId) {
+ // The container link is written once per node β€” at dispatch, or by
+ // `ensureTaskWorkVersion` for a node that never got one. Re-linking the
+ // completed version only appended a second identical row for the same task:
+ // the goal's task-container links were one per settle round instead of one
+ // per node, which is where half of the graph's hidden Work links came from.
+ const containerLinked = graph.workVersions.some(
+ (link) =>
+ link.nodeId === nodeId &&
+ link.relation === 'produced' &&
+ link.work?.workId === completedWork?.id,
+ );
+ if (completedWork?.currentVersionId && !containerLinked) {
await this.coordinatorGraph.attachWorkVersion(
graph.goal.id,
nodeId,
diff --git a/packages/database/src/models/__tests__/topicDocument.test.ts b/packages/database/src/models/__tests__/topicDocument.test.ts
index bc9e08f6dd7..464c51f0aab 100644
--- a/packages/database/src/models/__tests__/topicDocument.test.ts
+++ b/packages/database/src/models/__tests__/topicDocument.test.ts
@@ -330,6 +330,92 @@ describe('TopicDocumentModel', () => {
});
});
+ describe('findVerbatimTwin', () => {
+ const createWith = async (title: string, content: string, fileType: string) => {
+ const doc = await documentModel.create({
+ content,
+ fileType,
+ source: `notebook:${topicId}`,
+ sourceType: 'api',
+ title,
+ totalCharCount: content.length,
+ totalLineCount: 1,
+ });
+ await topicDocumentModel.associate({ documentId: doc.id, topicId });
+ return doc;
+ };
+
+ it('reuses a byte-identical document another surface wrote, whatever it calls the kind', async () => {
+ // The notebook calls a report `markdown`; the page surface calls the same
+ // report `custom/document`. It is one document either way.
+ const page = await createWith('Report', 'Same body', 'custom/document');
+
+ const twin = await topicDocumentModel.findVerbatimTwin({
+ content: 'Same body',
+ fileType: 'markdown',
+ title: 'Report',
+ topicId,
+ });
+
+ expect(twin?.id).toBe(page.id);
+ });
+
+ it('does not answer a plan write with a page holding the same text', async () => {
+ // `findPlanByTopic` filters on `agent/plan`. Reusing the page here would
+ // report a successful create and leave no discoverable plan behind.
+ await createWith('Plan', 'Same body', 'custom/document');
+
+ const twin = await topicDocumentModel.findVerbatimTwin({
+ content: 'Same body',
+ fileType: 'agent/plan',
+ title: 'Plan',
+ topicId,
+ });
+
+ expect(twin).toBeUndefined();
+ });
+
+ it('does not answer a plain write with a plan holding the same text', async () => {
+ await createWith('Plan', 'Same body', 'agent/plan');
+
+ const twin = await topicDocumentModel.findVerbatimTwin({
+ content: 'Same body',
+ fileType: 'markdown',
+ title: 'Plan',
+ topicId,
+ });
+
+ expect(twin).toBeUndefined();
+ });
+
+ it('keeps a labelled kind distinct β€” a note is not answered by a markdown row', async () => {
+ await createWith('Notes', 'Same body', 'markdown');
+
+ const twin = await topicDocumentModel.findVerbatimTwin({
+ content: 'Same body',
+ fileType: 'note',
+ title: 'Notes',
+ topicId,
+ });
+
+ expect(twin).toBeUndefined();
+ // The read has to agree with the write: a `note` create that reported
+ // success must be findable as a note.
+ expect(await topicDocumentModel.findByTopicId(topicId, { type: 'note' })).toHaveLength(0);
+ });
+
+ it('finds a plain document under every equivalent kind', async () => {
+ // `documentFileTypesOfKind` widens the write; the same equivalence widens
+ // the read, so whichever equivalent name a plain document was written as,
+ // a read by the name the caller asked for finds it.
+ const page = await createWith('Report', 'Same body', 'custom/document');
+
+ const byMarkdown = await topicDocumentModel.findByTopicId(topicId, { type: 'markdown' });
+
+ expect(byMarkdown.map((doc) => doc.id)).toEqual([page.id]);
+ });
+ });
+
describe('findByDocumentId', () => {
it('should return all topic IDs associated with a document', async () => {
const doc = await createTestDocument(documentModel, 'Shared Document');
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 60cd246a651..7a5ff9eb0a5 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -336,6 +336,32 @@ export class GoalGraphModel {
return link;
});
+ /**
+ * Work ids this goal already declares as produced, on any node.
+ *
+ * The claim predicate for deliverables: one Work is one deliverable, and it
+ * belongs to the node that first delivered it. A later round that merely
+ * revises the same resource (a shared document every task appends to is the
+ * common case) must not re-declare it on its own node, or the goal history
+ * repeats one deliverable under every task and its Works list counts one
+ * artifact several times.
+ *
+ * Read from the database rather than from a graph snapshot because the
+ * harvest of one settle has to see the links an earlier settle β€” possibly in
+ * the same tick β€” already wrote. Ticks of one goal are serialized by the
+ * dispatch advisory lock, so this read-then-write needs no extra guard.
+ */
+ listProducedWorkIds = async (goalId: string): Promise<Set<string>> => {
+ const rows = await this.db
+ .select({ workId: workVersions.workId })
+ .from(goalNodeWorkVersions)
+ .innerJoin(goalNodes, eq(goalNodeWorkVersions.nodeId, goalNodes.id))
+ .innerJoin(workVersions, eq(goalNodeWorkVersions.workVersionId, workVersions.id))
+ .where(and(eq(goalNodes.goalId, goalId), eq(goalNodeWorkVersions.relation, 'produced')));
+
+ return new Set(rows.map((row) => row.workId));
+ };
+
/**
* How many of a goal's tasks are occupying a concurrency slot.
*
diff --git a/packages/database/src/models/topicDocument.ts b/packages/database/src/models/topicDocument.ts
index 765702d56ff..b5809222049 100644
--- a/packages/database/src/models/topicDocument.ts
+++ b/packages/database/src/models/topicDocument.ts
@@ -1,6 +1,11 @@
+import {
+ AGENT_DOCUMENT_FILE_TYPE,
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ MARKDOWN_DOCUMENT_FILE_TYPES,
+} from '@lobechat/const';
import type { DocumentAccessScope } from '@lobechat/types';
import { ordinaryDocumentAccessScope } from '@lobechat/types';
-import { and, desc, eq } from 'drizzle-orm';
+import { and, desc, eq, inArray } from 'drizzle-orm';
import type { DocumentItem, NewTopicDocument } from '../schemas';
import { documents, topicDocuments } from '../schemas';
@@ -12,6 +17,39 @@ export interface TopicDocumentWithDetails extends DocumentItem {
associatedAt: Date;
}
+/**
+ * Kinds that are all the same document: the surfaces' own names for a plain text
+ * document whose content is its bytes. The notebook writes the unlabelled
+ * default as `markdown`, the agent-documents surface writes `agent/document`,
+ * and a Page is `custom/document` β€” so a report written through two of them is
+ * one document, not two.
+ *
+ * The notebook's *labelled* kinds β€” `article`, `note`, `report` β€” are absent on
+ * purpose. A caller that asks for one of them asked for that kind, so it is
+ * matched and read exactly: letting a `note` write be answered by a markdown row
+ * would report success and then leave `listDocuments({ type: 'note' })` with
+ * nothing to return.
+ *
+ * A structured artifact is absent for the same reason, one step further:
+ * `agent/plan` is *found* by its type (`findPlanByTopic` filters on it).
+ */
+export const SAME_DOCUMENT_KIND_FILE_TYPES = [
+ ...MARKDOWN_DOCUMENT_FILE_TYPES,
+ AGENT_DOCUMENT_FILE_TYPE,
+ CUSTOM_DOCUMENT_FILE_TYPE,
+];
+
+/**
+ * Every kind a document of `fileType` may be stored as: the whole equivalent set
+ * for a plain document, the kind itself for anything with a name of its own.
+ *
+ * Both the twin search and {@link TopicDocumentModel.findByTopicId}'s kind
+ * filter read this, so the two cannot disagree β€” a document is always findable
+ * under the kind its writer asked for.
+ */
+export const documentFileTypesOfKind = (fileType: string): string[] =>
+ SAME_DOCUMENT_KIND_FILE_TYPES.includes(fileType) ? SAME_DOCUMENT_KIND_FILE_TYPES : [fileType];
+
export class TopicDocumentModel {
private userId: string;
private db: LobeChatDatabase;
@@ -96,7 +134,9 @@ export class TopicDocumentModel {
this.ownership(),
buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),
documentMatchesAccessScope(documents.metadata, this.documentAccessScope),
- filter?.type ? eq(documents.fileType, filter.type) : undefined,
+ filter?.type
+ ? inArray(documents.fileType, documentFileTypesOfKind(filter.type))
+ : undefined,
),
)
.orderBy(desc(topicDocuments.createdAt));
@@ -107,6 +147,52 @@ export class TopicDocumentModel {
}));
};
+ /**
+ * A document this topic already holds under the same title, the same body and
+ * the same kind.
+ *
+ * The notebook surface and the agent-documents surface answer one intent with
+ * two tools, and an agent that writes the same report through both used to
+ * leave two rows behind: two entries in the topic's document list and two
+ * deliverable cards on the goal graph, for one report. A matching title alone
+ * is weak (two documents may share one), so the body has to match too β€”
+ * byte-identical identity plus byte-identical content is the same document
+ * written twice, and the second write reuses the row.
+ *
+ * The kind is part of that identity, because a document can be *found* by its
+ * type: `findPlanByTopic` filters on `agent/plan`, and the notebook's labelled
+ * kinds are filtered by callers too. Two plain documents that agree are still
+ * one (see {@link SAME_DOCUMENT_KIND_FILE_TYPES}); a plan write must never be
+ * answered with the page that happens to hold the same text, and neither must
+ * a `note` write be answered by a markdown row.
+ */
+ findVerbatimTwin = async (params: {
+ content: string;
+ fileType: string;
+ title: string;
+ topicId: string;
+ }): Promise<DocumentItem | undefined> => {
+ const [twin] = await this.db
+ .select({ document: documents })
+ .from(topicDocuments)
+ .innerJoin(documents, eq(topicDocuments.documentId, documents.id))
+ .where(
+ and(
+ eq(topicDocuments.topicId, params.topicId),
+ eq(documents.title, params.title),
+ eq(documents.content, params.content),
+ inArray(documents.fileType, documentFileTypesOfKind(params.fileType)),
+ this.ownership(),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),
+ documentMatchesAccessScope(documents.metadata, this.documentAccessScope),
+ ),
+ )
+ .orderBy(desc(topicDocuments.createdAt))
+ .limit(1);
+
+ return twin?.document;
+ };
+
/**
* Get all topics associated with a document
*/
diff --git a/src/features/AgentGoals/ProcessControl/Deliverables.tsx b/src/features/AgentGoals/ProcessControl/Deliverables.tsx
index 6f2ae7f0531..ffe3c33d469 100644
--- a/src/features/AgentGoals/ProcessControl/Deliverables.tsx
+++ b/src/features/AgentGoals/ProcessControl/Deliverables.tsx
@@ -11,6 +11,7 @@ import { isSafeExternalUrl } from '@/features/Work/descriptors';
import { useActivityTime } from '@/hooks/useActivityTime';
import { useChatStore } from '@/store/chat';
+import { dedupeArtifacts } from './deliverableList';
import type { GoalArtifactView, GoalGraphView } from './goalGraphViewModel';
import { KindDot } from './shared';
@@ -169,7 +170,15 @@ const Deliverables = memo<{ graph: GoalGraphView }>(({ graph }) => {
const { t } = useTranslation('chat');
const open = useOpenGoalArtifact();
- if (graph.artifacts.length === 0)
+ // Several nodes can declare the same Work as their own delivery, because each
+ // later run's version was claimed by whoever wrote it: a shared document
+ // listed once per task. Folding here β€” one row per deliverable, under the node
+ // that delivered it first β€” is the same rule the activity timeline applies.
+ // `graph.artifacts` keeps the raw join because timeline rows resolve their
+ // card by version id.
+ const artifacts = dedupeArtifacts(graph.artifacts);
+
+ if (artifacts.length === 0)
return (
<Flexbox horizontal align={'center'} gap={6}>
<Icon color={cssVar.colorTextQuaternary} icon={Link2} size={14} />
@@ -181,7 +190,7 @@ const Deliverables = memo<{ graph: GoalGraphView }>(({ graph }) => {
return (
<Flexbox gap={0}>
- {graph.artifacts.map((artifact) => (
+ {artifacts.map((artifact) => (
<DeliverableRow
artifact={artifact}
key={artifact.workVersionId}
diff --git a/src/features/AgentGoals/ProcessControl/deliverableList.test.ts b/src/features/AgentGoals/ProcessControl/deliverableList.test.ts
index f6fbe1fb2b5..bb9b5db6719 100644
--- a/src/features/AgentGoals/ProcessControl/deliverableList.test.ts
+++ b/src/features/AgentGoals/ProcessControl/deliverableList.test.ts
@@ -39,12 +39,60 @@ const titleOf = (nodeId: string) => titles[nodeId];
describe('dedupeArtifacts', () => {
it('keeps one row per version, under the node that produced it', () => {
- const produced = artifact({ nodeId: 'n1', workVersionId: 'same' });
- const input = artifact({ nodeId: 'n2', relation: 'input', workVersionId: 'same' });
+ const produced = artifact({ nodeId: 'n1', workId: 'w_same', workVersionId: 'same' });
+ const input = artifact({
+ nodeId: 'n2',
+ relation: 'input',
+ workId: 'w_same',
+ workVersionId: 'same',
+ });
expect(dedupeArtifacts([input, produced])).toEqual([produced]);
expect(dedupeArtifacts([produced, input])).toEqual([produced]);
});
+
+ it('keeps one row per deliverable, under the node that delivered it first', () => {
+ // A shared document revised by three tasks used to list three times: each
+ // task declared the version it wrote as its own delivery.
+ const first = artifact({
+ createdAt: new Date(2026, 8, 1, 0, 1),
+ nodeId: 'n1',
+ workId: 'w_shared',
+ workVersionId: 'v1',
+ });
+ const second = artifact({
+ createdAt: new Date(2026, 8, 1, 0, 2),
+ nodeId: 'n2',
+ workId: 'w_shared',
+ workVersionId: 'v2',
+ });
+ const third = artifact({
+ createdAt: new Date(2026, 8, 1, 0, 3),
+ nodeId: 'n3',
+ workId: 'w_shared',
+ workVersionId: 'v3',
+ });
+
+ expect(dedupeArtifacts([third, second, first])).toEqual([first]);
+ });
+
+ it('still names a deliverable another task only took as input', () => {
+ const produced = artifact({
+ createdAt: new Date(2026, 8, 1, 0, 5),
+ nodeId: 'n1',
+ workId: 'w_doc',
+ workVersionId: 'v9',
+ });
+ const laterInput = artifact({
+ createdAt: new Date(2026, 8, 1, 0, 1),
+ nodeId: 'n2',
+ relation: 'input',
+ workId: 'w_doc',
+ workVersionId: 'v10',
+ });
+
+ expect(dedupeArtifacts([laterInput, produced])).toEqual([produced]);
+ });
});
describe('evidenceCites', () => {
diff --git a/src/features/AgentGoals/ProcessControl/deliverableList.ts b/src/features/AgentGoals/ProcessControl/deliverableList.ts
index c2ab2d5b34b..5bd065e264d 100644
--- a/src/features/AgentGoals/ProcessControl/deliverableList.ts
+++ b/src/features/AgentGoals/ProcessControl/deliverableList.ts
@@ -33,21 +33,40 @@ export const MANY_DELIVERABLES = 6;
const RELATION_RANK: Record<string, number> = { produced: 0 };
/**
- * One row per Work version. A version is linked to every node that touched it
- * β€” the task that `produced` it and each task that took it as `input` β€” and a
- * goal-level list must name it once, under the task that made it.
+ * One row per Work. Two things used to arrive here as several rows for one
+ * deliverable:
+ *
+ * - A version is linked to every node that touched it β€” the task that
+ * `produced` it and each task that took it as `input` β€” and a goal-level list
+ * must name it once, under the task that made it.
+ * - A Work several runs revised gets a new version per claim, and every node
+ * that revised it declared that version as its own delivery. A shared backlog
+ * document therefore listed once per task (17 rows for 5 deliverables in the
+ * case that surfaced this). The deliverable is the same one: the row belongs
+ * to whoever delivered it first, which is the rule the coordinator now writes
+ * with too.
+ *
+ * So the surviving row is the best claim on the Work β€” `produced` beats a mere
+ * `input` β€” and the earliest of those, so the list names the producer rather
+ * than the last task that happened to touch it.
*/
export const dedupeArtifacts = (artifacts: GoalArtifactView[]): GoalArtifactView[] => {
- const byVersion = new Map<string, GoalArtifactView>();
+ const rankOf = (artifact: GoalArtifactView) => RELATION_RANK[artifact.relation ?? ''] ?? 1;
+ const byWork = new Map<string, GoalArtifactView>();
for (const artifact of artifacts) {
- const seen = byVersion.get(artifact.workVersionId);
- if (
- !seen ||
- (RELATION_RANK[artifact.relation ?? ''] ?? 1) < (RELATION_RANK[seen.relation ?? ''] ?? 1)
- )
- byVersion.set(artifact.workVersionId, artifact);
+ const seen = byWork.get(artifact.workId);
+ if (!seen) {
+ byWork.set(artifact.workId, artifact);
+ continue;
+ }
+ // Same version, or a later claim on the same Work: keep the one that owns
+ // the delivery β€” an explicit `produced`, and the earliest of those.
+ const better =
+ rankOf(artifact) < rankOf(seen) ||
+ (rankOf(artifact) === rankOf(seen) && artifact.createdAt < seen.createdAt);
+ if (better) byWork.set(artifact.workId, artifact);
}
- return [...byVersion.values()].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
+ return [...byWork.values()].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
};
/**
diff --git a/src/features/Portal/GoalMetric/Lifecycle.tsx b/src/features/Portal/GoalMetric/Lifecycle.tsx
index bf3ba2fefa9..9f8eb22e255 100644
--- a/src/features/Portal/GoalMetric/Lifecycle.tsx
+++ b/src/features/Portal/GoalMetric/Lifecycle.tsx
@@ -43,12 +43,8 @@ import { goalSelectors, useGoalStore } from '@/store/goal';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
-import {
- type LifecycleNote,
- type LifecyclePresentation,
- nodeTwinKey,
- presentLifecycleEvent,
-} from './lifecycleEvent';
+import type { LifecycleNote } from './lifecycleEvent';
+import { buildLifecycleDays, type LifecycleGroup, type LifecycleRow } from './lifecycleRows';
/**
* The goal's history as a timeline, newest first and grouped by day. Each event
@@ -57,6 +53,10 @@ import {
* for a quick scan β€” never coded in color. Only the leading glyph carries tone:
* a resolve reads green, a reject red, everything else stays neutral, so the eye
* can skim the outcomes.
+ *
+ * Which events share a line is decided in `lifecycleRows`: one line per
+ * deliverable and one line per moment, so a settle that attached five artifacts
+ * reads as one event with five cards instead of five identical sentences.
*/
const BADGE = 20;
@@ -172,8 +172,8 @@ const styles = createStaticStyles(({ css }) => ({
font-size: 12px;
line-height: 1.6;
color: ${cssVar.colorTextSecondary};
- white-space: pre-line;
overflow-wrap: anywhere;
+ white-space: pre-line;
background: ${cssVar.colorFillQuaternary};
`,
@@ -442,22 +442,24 @@ Actor.displayName = 'GoalMetricLifecycleActor';
const noteText = (note: LifecycleNote, t: (key: any, options?: any) => string) => {
if (!('key' in note)) return note.text;
- if (note.key === 'mainAgent') return t('goalProcess.lifecycle.note.mainAgent', { text: note.text });
+ if (note.key === 'mainAgent')
+ return t('goalProcess.lifecycle.note.mainAgent', { text: note.text });
return t(`goalProcess.lifecycle.note.${note.key}` as const);
};
const EventItem = memo<{
- event: GoalGraphEvent;
graph: GoalGraphView;
+ group: LifecycleGroup;
onSelect: (nodeId: string) => void;
- presentation: Exclude<LifecyclePresentation, { hidden: true }>;
-}>(({ event, graph, onSelect, presentation }) => {
+}>(({ graph, group, onSelect }) => {
const { t } = useTranslation('chat');
+ const { event, presentation } = group.rows[0] as LifecycleRow;
const visual = EVENT_VISUAL[event.eventType] ?? { icon: History, tone: NEUTRAL };
const tone = visual.tone;
// A recognised event names what happened more precisely than its raw type:
// a canceled task or a delivered Work is not an "edit".
- const icon = (presentation.action && ACTION_ICON[presentation.action.split('.')[0]]) || visual.icon;
+ const icon =
+ (presentation.action && ACTION_ICON[presentation.action.split('.')[0]]) || visual.icon;
const subjects = subjectNodes(event, graph);
const kind = eventKind(event, subjects);
const phrase = `${event.eventType}.${kind}`;
@@ -468,9 +470,15 @@ const EventItem = memo<{
: t(`goalProcess.lifecycle.action.${event.eventType}` as const, {
kind: kind ? t(`goalProcess.lifecycle.kind.${kind}` as const) : '',
}).trim();
- const artifact = presentation.workVersion
- ? graph.artifacts.find((item) => item.workVersionId === presentation.workVersion!.id)
- : undefined;
+ // One row can carry several deliverables: a settle attaches each of them, and
+ // the fold in `buildLifecycleDays` merged them back into the moment they were
+ // attached in. The row names the task, each card is one thing it delivered.
+ const artifacts = group.rows.flatMap((row) => {
+ const version = row.presentation.workVersion;
+ if (!version) return [];
+ const artifact = graph.artifacts.find((item) => item.workVersionId === version.id);
+ return artifact ? [artifact] : [];
+ });
const note = presentation.note ? noteText(presentation.note, t) : undefined;
return (
@@ -510,7 +518,9 @@ const EventItem = memo<{
{dayjs(event.createdAt).format('HH:mm')}
</Text>
</Flexbox>
- {artifact && <ArtifactCard artifact={artifact} />}
+ {artifacts.map((artifact) => (
+ <ArtifactCard artifact={artifact} key={artifact.workVersionId} />
+ ))}
{note && (
<div className={styles.reason} title={note}>
{note}
@@ -544,31 +554,16 @@ const Lifecycle = memo<{ goalId: string; graph: GoalGraphView }>(({ goalId, grap
const onSelect = useGoalNodeSelect(goalId, graph);
const days = useMemo(() => {
- const events = snapshot?.events ?? [];
const workTypes = new Map(
(snapshot?.workVersions ?? []).map((link) => [link.workVersionId, link.work?.type]),
);
- const nodeTwins = new Set(
- events.filter((event) => event.entityType === 'node' && event.reason).map(nodeTwinKey),
+ const workIds = new Map(
+ (snapshot?.workVersions ?? []).map((link) => [link.workVersionId, link.work?.workId]),
);
- const sorted = [...events].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
- type Row = { event: GoalGraphEvent; presentation: Exclude<LifecyclePresentation, { hidden: true }> };
- const groups: { day: dayjs.Dayjs; rows: Row[] }[] = [];
- for (const event of sorted) {
- const presentation = presentLifecycleEvent(event, {
- hasNodeTwin: event.entityType === 'goal' && nodeTwins.has(nodeTwinKey(event)),
- workTypeOf: (id) => workTypes.get(id),
- });
- // Bookkeeping rows are dropped before grouping so a day holding nothing
- // else does not leave an empty header behind.
- if (presentation.hidden) continue;
- const row = { event, presentation };
- const day = dayjs(event.createdAt).startOf('day');
- const last = groups.at(-1);
- if (last?.day.isSame(day)) last.rows.push(row);
- else groups.push({ day, rows: [row] });
- }
- return groups;
+ return buildLifecycleDays(snapshot?.events ?? [], {
+ workIdOf: (id) => workIds.get(id),
+ workTypeOf: (id) => workTypes.get(id),
+ });
}, [snapshot]);
if (days.length === 0)
@@ -576,16 +571,15 @@ const Lifecycle = memo<{ goalId: string; graph: GoalGraphView }>(({ goalId, grap
return (
<Flexbox gap={0}>
- {days.map(({ day, rows }) => (
+ {days.map(({ day, groups }) => (
<Flexbox gap={2} key={day.valueOf()}>
<div className={styles.day}>{dayLabel(day)}</div>
<Flexbox gap={0}>
- {rows.map(({ event, presentation }) => (
+ {groups.map((group) => (
<EventItem
- event={event}
graph={graph}
- key={event.id}
- presentation={presentation}
+ group={group}
+ key={group.rows[0].event.id}
onSelect={onSelect}
/>
))}
diff --git a/src/features/Portal/GoalMetric/lifecycleRows.test.ts b/src/features/Portal/GoalMetric/lifecycleRows.test.ts
new file mode 100644
index 00000000000..f3e15161622
--- /dev/null
+++ b/src/features/Portal/GoalMetric/lifecycleRows.test.ts
@@ -0,0 +1,207 @@
+import type { GoalGraphEvent } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { buildLifecycleDays } from './lifecycleRows';
+
+/**
+ * The shapes below are the ones the coordinator actually writes: one
+ * `Attached Work version <id> as produced` event per deliverable a settle
+ * attaches, all within the same second, plus bookkeeping rows for the task
+ * container of each node.
+ */
+const attach = (
+ versionId: string,
+ {
+ at,
+ eventId,
+ nodeId,
+ relation = 'produced',
+ }: {
+ at: string;
+ eventId: string;
+ nodeId: string;
+ relation?: string;
+ },
+): GoalGraphEvent => ({
+ actorId: null,
+ actorType: 'system',
+ createdAt: new Date(at),
+ entityId: nodeId,
+ entityType: 'node',
+ eventType: 'updated',
+ goalId: 'goal-1',
+ id: eventId,
+ operationId: null,
+ reason: `Attached Work version ${versionId} as ${relation}`,
+ taskId: null,
+});
+
+/** Version β†’ Work map, the two halves of the graph's joined display. */
+const worksOf = (entries: [string, { type: string; workId: string }][]) => {
+ const map = new Map(entries);
+ return {
+ workIdOf: (id: string) => map.get(id)?.workId,
+ workTypeOf: (id: string) => map.get(id)?.type,
+ };
+};
+
+const docs = worksOf([
+ ['v1', { type: 'document', workId: 'wk_backlog' }],
+ ['v2', { type: 'document', workId: 'wk_backlog' }],
+ ['v3', { type: 'document', workId: 'wk_backlog' }],
+ ['pr1', { type: 'external', workId: 'wk_pr1' }],
+ ['pr2', { type: 'external', workId: 'wk_pr2' }],
+ ['task1', { type: 'task', workId: 'wk_task' }],
+ ['task2', { type: 'task', workId: 'wk_task' }],
+]);
+
+const rowsOf = (days: ReturnType<typeof buildLifecycleDays>) =>
+ days.flatMap((day) => day.groups.flatMap((group) => group.rows));
+
+describe('buildLifecycleDays', () => {
+ it('keeps the first claim of a deliverable and drops later ones', () => {
+ // The reported shape: one shared backlog document revised in three
+ // different tasks' runs was declared as each of their deliverables, so the
+ // goal history showed one document delivered three times.
+ const days = buildLifecycleDays(
+ [
+ attach('v1', { at: '2026-09-27T07:33:41.813Z', eventId: 'e1', nodeId: 'node-a' }),
+ attach('v2', { at: '2026-09-27T08:01:15.137Z', eventId: 'e2', nodeId: 'node-b' }),
+ attach('v3', { at: '2026-09-27T08:16:30.339Z', eventId: 'e3', nodeId: 'node-c' }),
+ ],
+ docs,
+ );
+
+ const rows = rowsOf(days);
+ expect(rows).toHaveLength(1);
+ expect(rows[0].event.id).toBe('e1');
+ expect(rows[0].event.entityId).toBe('node-a');
+ });
+
+ it.each(['input', 'supports', 'contradicts'] as const)(
+ 'keeps a later %s link on a Work another node already produced',
+ (relation) => {
+ // `GoalExplorationModel` reattaches a previously produced version as
+ // `input` when a later node reuses it, and the other relations exist for
+ // a node that relies on or disputes the Work. Those are new transitions,
+ // not another delivery of it, so each keeps its own row.
+ const days = buildLifecycleDays(
+ [
+ attach('v1', { at: '2026-09-27T07:33:41.813Z', eventId: 'e1', nodeId: 'node-a' }),
+ attach('v1', {
+ at: '2026-09-27T08:01:15.137Z',
+ eventId: 'e2',
+ nodeId: 'node-b',
+ relation,
+ }),
+ ],
+ docs,
+ );
+
+ expect(rowsOf(days).map((row) => row.event.id)).toEqual(['e2', 'e1']);
+ },
+ );
+
+ it('keeps the claim when only one node ever made it', () => {
+ const days = buildLifecycleDays(
+ [attach('v1', { at: '2026-09-27T07:33:41.813Z', eventId: 'e1', nodeId: 'node-a' })],
+ docs,
+ );
+
+ expect(rowsOf(days)).toHaveLength(1);
+ });
+
+ it('folds a settle batch into one row with a row per deliverable', () => {
+ // Four pull requests attached in one step read as one event with four
+ // cards, instead of four identical "produces a deliverable" sentences.
+ const days = buildLifecycleDays(
+ [
+ attach('pr1', { at: '2026-09-28T04:02:51.041Z', eventId: 'e1', nodeId: 'node-a' }),
+ attach('pr2', { at: '2026-09-28T04:02:51.197Z', eventId: 'e2', nodeId: 'node-a' }),
+ ],
+ docs,
+ );
+
+ const groups = days.flatMap((day) => day.groups);
+ expect(groups).toHaveLength(1);
+ expect(groups[0].rows.map((row) => row.event.id)).toEqual(['e2', 'e1']);
+ });
+
+ it('does not fold deliverables of different nodes or different moments', () => {
+ const otherNode = buildLifecycleDays(
+ [
+ attach('pr1', { at: '2026-09-28T04:02:51.041Z', eventId: 'e1', nodeId: 'node-a' }),
+ attach('pr2', { at: '2026-09-28T04:02:51.197Z', eventId: 'e2', nodeId: 'node-b' }),
+ ],
+ docs,
+ );
+ expect(otherNode.flatMap((day) => day.groups)).toHaveLength(2);
+
+ const otherMinute = buildLifecycleDays(
+ [
+ attach('pr1', { at: '2026-09-28T04:02:51.041Z', eventId: 'e1', nodeId: 'node-a' }),
+ attach('pr2', { at: '2026-09-28T04:03:02.000Z', eventId: 'e2', nodeId: 'node-a' }),
+ ],
+ docs,
+ );
+ expect(otherMinute.flatMap((day) => day.groups)).toHaveLength(2);
+ });
+
+ it('drops the task container a node registers, and folds nothing into it', () => {
+ const days = buildLifecycleDays(
+ [
+ attach('task1', { at: '2026-09-28T04:02:50.938Z', eventId: 'e1', nodeId: 'node-a' }),
+ attach('pr1', { at: '2026-09-28T04:02:51.041Z', eventId: 'e2', nodeId: 'node-a' }),
+ ],
+ docs,
+ );
+
+ const rows = rowsOf(days);
+ expect(rows).toHaveLength(1);
+ expect(rows[0].presentation.workVersion?.id).toBe('pr1');
+ });
+
+ it('never folds rows that are not deliverables', () => {
+ const starts: GoalGraphEvent[] = ['e1', 'e2'].map((id, index) => ({
+ actorId: null,
+ actorType: 'system',
+ createdAt: new Date(`2026-09-28T04:02:5${index}.000Z`),
+ entityId: 'node-a',
+ entityType: 'node',
+ eventType: 'activated',
+ goalId: 'goal-1',
+ id,
+ operationId: null,
+ reason: 'Started attempt',
+ taskId: null,
+ }));
+
+ expect(buildLifecycleDays(starts, docs).flatMap((day) => day.groups)).toHaveLength(2);
+ });
+
+ it('groups by day, newest first', () => {
+ const days = buildLifecycleDays(
+ [
+ attach('v1', { at: '2026-09-27T07:33:41.813Z', eventId: 'e1', nodeId: 'node-a' }),
+ attach('pr1', { at: '2026-09-28T04:02:51.041Z', eventId: 'e2', nodeId: 'node-a' }),
+ ],
+ docs,
+ );
+
+ expect(days).toHaveLength(2);
+ expect(days[0].day.format('YYYY-MM-DD')).toBe('2026-09-28');
+ expect(days[1].day.format('YYYY-MM-DD')).toBe('2026-09-27');
+ expect(days[0].groups[0].rows[0].event.id).toBe('e2');
+ });
+
+ it('keeps an attached Work whose row is gone', () => {
+ // Same rule the single-event presentation already followed: a version the
+ // graph could not join still happened, it just cannot be named.
+ const days = buildLifecycleDays(
+ [attach('missing', { at: '2026-09-28T04:02:51.041Z', eventId: 'e1', nodeId: 'node-a' })],
+ docs,
+ );
+
+ expect(rowsOf(days)).toHaveLength(1);
+ });
+});
diff --git a/src/features/Portal/GoalMetric/lifecycleRows.ts b/src/features/Portal/GoalMetric/lifecycleRows.ts
new file mode 100644
index 00000000000..4c7401e2334
--- /dev/null
+++ b/src/features/Portal/GoalMetric/lifecycleRows.ts
@@ -0,0 +1,131 @@
+import type { GoalGraphEvent } from '@lobechat/types';
+import dayjs from 'dayjs';
+
+import { type LifecyclePresentation, nodeTwinKey, presentLifecycleEvent } from './lifecycleEvent';
+
+/**
+ * Shaping the goal's event trail into timeline rows.
+ *
+ * The trail is written by the coordinator for bookkeeping, so one human moment
+ * can arrive as several near-identical rows: a settle attaches each deliverable
+ * with its own event, and a long-lived resource that several nodes touched used
+ * to be re-declared as "produced" on every one of them. Two folds turn that
+ * back into what happened:
+ *
+ * - **One claim per deliverable.** A Work is declared produced once, by the
+ * node that first delivered it. Later `produced` claims on the same Work are
+ * bookkeeping about a revision, not another delivery, and they are dropped.
+ * This mirrors the coordinator's own rule
+ * (`GoalService.attachTaskDeliverables`) and also cleans up histories written
+ * before it. A later `input` / `supports` / `contradicts` link is a different
+ * transition in that Work's life and keeps its row.
+ * - **One row per moment.** Adjacent deliverable rows of the same node and the
+ * same action that share a displayed time read as one event carrying several
+ * outputs, which is what a settle with five deliverables actually was.
+ */
+
+export interface LifecycleRow {
+ event: GoalGraphEvent;
+ presentation: Exclude<LifecyclePresentation, { hidden: true }>;
+}
+
+/** Rows a person reads as one line: one event, or one settle's batch of them. */
+export interface LifecycleGroup {
+ /** Newest first. The first row supplies the actor, action, subject and time. */
+ rows: LifecycleRow[];
+}
+
+export interface LifecycleDay {
+ day: dayjs.Dayjs;
+ groups: LifecycleGroup[];
+}
+
+export interface LifecycleRowContext {
+ /** Work a linked version belongs to β€” the deliverable's identity. */
+ workIdOf: (workVersionId: string) => string | undefined;
+ /** Type of the Work behind a Work version id, when the graph joined it. */
+ workTypeOf: (workVersionId: string) => string | undefined;
+}
+
+/** The node a deliverable row names, so rows about one subject can merge. */
+const subjectKeyOf = (row: LifecycleRow) =>
+ row.presentation.action?.startsWith('work.') ? row.event.entityId : undefined;
+
+/**
+ * Deliverable claims to drop: for each Work, every row but its earliest claim.
+ *
+ * Scanned oldest-first because "who delivered it" is decided by who claimed it
+ * first, not by where it happens to sit in the newest-first list.
+ */
+const redundantClaims = (rows: LifecycleRow[], { workIdOf }: LifecycleRowContext) => {
+ const claimed = new Set<string>();
+ const redundant = new Set<string>();
+ for (const row of [...rows].reverse()) {
+ // Only a repeated *produced* claim is bookkeeping. The same version later
+ // reattached as `input` β€” `GoalExplorationModel` does exactly that β€” or as
+ // `supports` / `contradicts`, is a new transition in the Work's life, so
+ // its row is not a duplicate of the delivery.
+ if (row.presentation.action !== 'work.produced') continue;
+ const version = row.presentation.workVersion;
+ if (!version) continue;
+ const workId = workIdOf(version.id);
+ if (!workId) continue;
+ if (claimed.has(workId)) redundant.add(row.event.id);
+ else claimed.add(workId);
+ }
+ return redundant;
+};
+
+export const buildLifecycleDays = (
+ events: GoalGraphEvent[],
+ context: LifecycleRowContext,
+): LifecycleDay[] => {
+ const nodeTwins = new Set(
+ events.filter((event) => event.entityType === 'node' && event.reason).map(nodeTwinKey),
+ );
+
+ const rows: LifecycleRow[] = [...events]
+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
+ .flatMap((event) => {
+ const presentation = presentLifecycleEvent(event, {
+ hasNodeTwin: event.entityType === 'goal' && nodeTwins.has(nodeTwinKey(event)),
+ workTypeOf: context.workTypeOf,
+ });
+ // Bookkeeping rows are dropped before grouping so a day holding nothing
+ // else does not leave an empty header behind.
+ return presentation.hidden ? [] : [{ event, presentation }];
+ });
+
+ // Drop the redundant claims before folding, so a dropped row cannot carry a
+ // neighbouring row into a merge that no longer makes sense.
+ const redundant = redundantClaims(rows, context);
+
+ const days: LifecycleDay[] = [];
+ for (const row of rows) {
+ if (redundant.has(row.event.id)) continue;
+
+ const day = dayjs(row.event.createdAt).startOf('day');
+ const current = days.at(-1);
+ if (!current || !current.day.isSame(day)) {
+ days.push({ day, groups: [{ rows: [row] }] });
+ continue;
+ }
+
+ const last = current.groups.at(-1)!;
+ if (merges(last, row)) last.rows.push(row);
+ else current.groups.push({ rows: [row] });
+ }
+
+ return days;
+};
+
+/** Same node, same action, same displayed time β€” one event with several outputs. */
+const merges = (group: LifecycleGroup, row: LifecycleRow) => {
+ const head = group.rows[0];
+ const subject = subjectKeyOf(head);
+ if (!subject || subjectKeyOf(row) !== subject) return false;
+ if (head.presentation.action !== row.presentation.action) return false;
+ // The row prints `HH:mm`, so that is the granularity at which two rows look
+ // like the same moment; merging beyond it would fold unrelated rounds.
+ return dayjs(head.event.createdAt).format('HH:mm') === dayjs(row.event.createdAt).format('HH:mm');
+};