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): identify the wrap-up by its recorded node; only its current run may submit (#20195)

Arvin Xu8a1efc9ab4a9
diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.ts
index f5bbdeacd18..0ef7aa0c6a5 100644
--- a/apps/server/src/services/goal/decideNextMove.ts
+++ b/apps/server/src/services/goal/decideNextMove.ts
@@ -35,8 +35,10 @@ export const TERMINAL_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired'
* the Goal's status: its failure or timeout must not open a gate, occupy a slot
* or keep a Goal from being judged.
*/
-export const isCoordinatedTask = (node: Pick<GoalGraphNode, 'kind' | 'title'>) =>
- node.kind === 'task' && !isGoalReportNode(node);
+export const isCoordinatedTask = (
+ graph: Pick<GoalGraphSnapshot, 'goal'>,
+ node: Pick<GoalGraphNode, 'id' | 'kind'>,
+) => node.kind === 'task' && !isGoalReportNode(graph, node);
/**
* Whether a paused Task lost its run rather than failed it: the coordinator
@@ -68,7 +70,7 @@ export const selectFrontier = (graph: GoalGraphSnapshot): FrontierSelection => {
);
const eligible = graph.nodes
- .filter((node) => isCoordinatedTask(node) && !TERMINAL_NODE_STATUSES.has(node.status))
+ .filter((node) => isCoordinatedTask(graph, node) && !TERMINAL_NODE_STATUSES.has(node.status))
.map((node) => ({
blockedBy: graph.edges
.filter(
@@ -186,7 +188,7 @@ export const compareMetric = (
*/
export const needsMetricCriteria = (graph: GoalGraphSnapshot): boolean => {
if (!graph.goal.config?.acceptance?.metrics?.length) return false;
- const taskNodes = graph.nodes.filter(isCoordinatedTask);
+ const taskNodes = graph.nodes.filter((node) => isCoordinatedTask(graph, node));
return taskNodes.length > 0 && taskNodes.every((node) => TERMINAL_NODE_STATUSES.has(node.status));
};
@@ -295,7 +297,7 @@ export const decideNextMove = ({
// re-picked every tick, and reported `waiting_external`, which ends the
// advance before anything behind it is even considered.
const inFlight = graph.nodes.filter(
- (node) => isCoordinatedTask(node) && isInFlight(tasksById.get(node.taskId ?? '')),
+ (node) => isCoordinatedTask(graph, node) && isInFlight(tasksById.get(node.taskId ?? '')),
).length;
let parked = false;
@@ -408,7 +410,7 @@ const decideWithoutFrontier = (
metricCriteria?: GoalMetricCriteriaState,
): GoalMove => {
const base = { candidates };
- const taskNodes = graph.nodes.filter(isCoordinatedTask);
+ const taskNodes = graph.nodes.filter((node) => isCoordinatedTask(graph, node));
// A goal with no tasks at all has not been planned yet β€” decompose it into
// explorable directions before anything runs, instead of parking it.
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 8f69386f5d7..8cb011dcd18 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -1241,7 +1241,7 @@ export class GoalService {
const unfinishedNodes = graph.nodes.filter(
(node) =>
node.kind === 'task' &&
- !isGoalReportNode(node) &&
+ !isGoalReportNode(graph, node) &&
node.taskId &&
!TERMINAL_NODE_STATUSES.has(node.status),
);
@@ -1405,7 +1405,7 @@ export class GoalService {
(node) =>
node.kind === 'task' &&
node.title !== GOAL_ACCEPTANCE_TASK_TITLE &&
- !isGoalReportNode(node),
+ !isGoalReportNode(before, node),
).length >= (goal.config?.exploration?.maxExperiments ?? 0)
)
return goal;
diff --git a/apps/server/src/services/goal/report.test.ts b/apps/server/src/services/goal/report.test.ts
index fcc9b74f41a..8b6560eba5d 100644
--- a/apps/server/src/services/goal/report.test.ts
+++ b/apps/server/src/services/goal/report.test.ts
@@ -74,6 +74,23 @@ const graph = (overrides: Partial<GoalGraphSnapshot> = {}): GoalGraphSnapshot =>
...overrides,
}) as GoalGraphSnapshot;
+/** A graph whose wrap-up was dispatched to the node `report` β€” the only way a node is the wrap-up. */
+const withReportDispatched = (snapshot: GoalGraphSnapshot): GoalGraphSnapshot => ({
+ ...snapshot,
+ goal: {
+ ...snapshot.goal,
+ config: {
+ ...snapshot.goal.config,
+ report: {
+ acceptanceKey: 'acc:resolved',
+ dispatchedAt: new Date(0).toISOString(),
+ nodeId: 'report',
+ trigger: 'accepted',
+ },
+ },
+ },
+});
+
const acceptance = (overrides: Partial<GoalGraphNode> = {}) =>
node('acc', { title: GOAL_ACCEPTANCE_TASK_TITLE, ...overrides });
@@ -251,9 +268,11 @@ describe('the wrap-up node does not take part in the Goal status', () => {
});
it('a failed wrap-up Task opens no gate and does not block acceptance', () => {
- const snapshot = graph({
- nodes: [node('t1', { status: 'resolved' }), reportNode],
- });
+ const snapshot = withReportDispatched(
+ graph({
+ nodes: [node('t1', { status: 'resolved' }), reportNode],
+ }),
+ );
const move = decideNextMove({
concurrency: 1,
frontier: selectFrontier(snapshot),
@@ -270,7 +289,7 @@ describe('the wrap-up node does not take part in the Goal status', () => {
});
it('a running wrap-up Task holds no concurrency slot and never becomes the frontier', () => {
- const snapshot = graph({ nodes: [node('t1'), reportNode] });
+ const snapshot = withReportDispatched(graph({ nodes: [node('t1'), reportNode] }));
const frontier = selectFrontier(snapshot);
expect(frontier.candidates.map((candidate) => candidate.nodeId)).toEqual(['t1']);
const move = decideNextMove({
@@ -288,41 +307,43 @@ describe('the wrap-up node does not take part in the Goal status', () => {
describe('buildGoalReportSkeleton', () => {
// problem β†’ t1 (resolved) β†’ t2 (resolved, depends on t1) β†’ acc (depends on t2)
// t1b: an earlier protocol revised by t2; t0: a retired direction off t1.
- const snapshot = graph({
- edges: [
- edge('t2', 'depends_on', 't1'),
- edge('acc', 'depends_on', 't2'),
- edge('t1', 'produces', 'f1'),
- edge('t2', 'produces', 'f2'),
- edge('t2', 'revises', 't1b'),
- edge('t0', 'depends_on', 't1'),
- ],
- events: [
- { createdAt: new Date(1), id: 'evt_old' },
- { createdAt: new Date(9), id: 'evt_new' },
- ] as GoalGraphSnapshot['events'],
- nodes: [
- node('problem', { kind: 'problem', status: 'resolved' }),
- node('t1', { createdAt: new Date(1), status: 'resolved' }),
- node('f1', { kind: 'finding', status: 'resolved' }),
- node('t1b', { createdAt: new Date(2), status: 'resolved' }),
- node('t0', { createdAt: new Date(3), status: 'retired' }),
- node('t2', { createdAt: new Date(4), status: 'resolved' }),
- node('f2', { kind: 'finding', status: 'resolved' }),
- acceptance({ createdAt: new Date(5), status: 'resolved' }),
- node('report', { title: GOAL_REPORT_TASK_TITLE }),
- ],
- workVersions: [
- {
- createdAt: new Date(6),
- id: 'l1',
- nodeId: 't2',
- relation: 'produced',
- work: { title: 'Final doc', type: 'document', workId: 'work_doc' },
- workVersionId: 'wv_doc',
- },
- ] as GoalGraphSnapshot['workVersions'],
- });
+ const snapshot = withReportDispatched(
+ graph({
+ edges: [
+ edge('t2', 'depends_on', 't1'),
+ edge('acc', 'depends_on', 't2'),
+ edge('t1', 'produces', 'f1'),
+ edge('t2', 'produces', 'f2'),
+ edge('t2', 'revises', 't1b'),
+ edge('t0', 'depends_on', 't1'),
+ ],
+ events: [
+ { createdAt: new Date(1), id: 'evt_old' },
+ { createdAt: new Date(9), id: 'evt_new' },
+ ] as GoalGraphSnapshot['events'],
+ nodes: [
+ node('problem', { kind: 'problem', status: 'resolved' }),
+ node('t1', { createdAt: new Date(1), status: 'resolved' }),
+ node('f1', { kind: 'finding', status: 'resolved' }),
+ node('t1b', { createdAt: new Date(2), status: 'resolved' }),
+ node('t0', { createdAt: new Date(3), status: 'retired' }),
+ node('t2', { createdAt: new Date(4), status: 'resolved' }),
+ node('f2', { kind: 'finding', status: 'resolved' }),
+ acceptance({ createdAt: new Date(5), status: 'resolved' }),
+ node('report', { title: GOAL_REPORT_TASK_TITLE }),
+ ],
+ workVersions: [
+ {
+ createdAt: new Date(6),
+ id: 'l1',
+ nodeId: 't2',
+ relation: 'produced',
+ work: { title: 'Final doc', type: 'document', workId: 'work_doc' },
+ workVersionId: 'wv_doc',
+ },
+ ] as GoalGraphSnapshot['workVersions'],
+ }),
+ );
it('traces the main path back from the deliverable and hangs detours under their fork', () => {
const skeleton = buildGoalReportSkeleton(snapshot);
diff --git a/apps/server/src/services/goal/report.ts b/apps/server/src/services/goal/report.ts
index 43a3fb7b378..f05cc3b6ca7 100644
--- a/apps/server/src/services/goal/report.ts
+++ b/apps/server/src/services/goal/report.ts
@@ -1,4 +1,4 @@
-import { GOAL_ACCEPTANCE_TASK_TITLE, GOAL_REPORT_TASK_TITLE } from '@lobechat/const/goal';
+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';
import type {
GoalEdgeKind,
GoalGraphNode,
@@ -14,8 +14,19 @@ import type {
* the agent and the checks on what it submits can be tested without IO.
*/
-export const isGoalReportNode = (node: Pick<GoalGraphNode, 'kind' | 'title'>) =>
- node.kind === 'task' && node.title === GOAL_REPORT_TASK_TITLE;
+/**
+ * The wrap-up node is the one the dispatch recorded on the Goal. It is never
+ * matched by title: any task a planner or a person happens to call "Write the
+ * Goal report" would otherwise be hidden from the coordinator and reused as
+ * the wrap-up.
+ */
+export const goalReportNodeId = (graph: Pick<GoalGraphSnapshot, 'goal'>) =>
+ graph.goal.config?.report?.nodeId;
+
+export const isGoalReportNode = (
+ graph: Pick<GoalGraphSnapshot, 'goal'>,
+ node: Pick<GoalGraphNode, 'id'>,
+) => node.id === goalReportNodeId(graph);
/**
* The graph as the coordinator should see it: without the wrap-up node, its
@@ -24,8 +35,9 @@ export const isGoalReportNode = (node: Pick<GoalGraphNode, 'kind' | 'title'>) =>
* from finishing β€” so every decision path reads this view.
*/
export const withoutGoalReport = <T extends GoalGraphSnapshot>(graph: T): T => {
- const hidden = new Set(graph.nodes.filter(isGoalReportNode).map((node) => node.id));
- if (hidden.size === 0) return graph;
+ const reportNodeId = goalReportNodeId(graph);
+ if (!reportNodeId) return graph;
+ const hidden = new Set([reportNodeId]);
return {
...graph,
edges: graph.edges.filter(
diff --git a/apps/server/src/services/goal/reportService.test.ts b/apps/server/src/services/goal/reportService.test.ts
index d7b6ea3c494..f73b1c3eeba 100644
--- a/apps/server/src/services/goal/reportService.test.ts
+++ b/apps/server/src/services/goal/reportService.test.ts
@@ -194,6 +194,135 @@ describe('GoalService wrap-up branch', () => {
expect(second.taskId).toBe(first.taskId);
});
+ /**
+ * Regression: a re-dispatch reuses the wrap-up Task, and the previous run can
+ * outlive a failed cancel. Any run in the Task's history could submit, so the
+ * superseded one could land stale content as the newest report version.
+ */
+ it('accepts a report only from the current wrap-up run after a re-dispatch', async () => {
+ const service = new GoalService(serverDB, userId);
+ const { acceptanceTaskId, goalId, taskModel } = await runToAcceptance(service);
+ await taskModel.updateStatus(acceptanceTaskId, 'completed');
+ await service.tick(goalId);
+ await service.tick(goalId);
+ const acceptanceNode = (await service.graph(goalId)).nodes.find(
+ (node) => node.taskId === acceptanceTaskId,
+ )!;
+ await serverDB
+ .update(goalNodes)
+ .set({ resolvedAt: new Date(Date.now() + 60_000), status: 'resolved' })
+ .where(eq(goalNodes.id, acceptanceNode.id));
+ await service.tick(goalId);
+
+ const graph = await service.graph(goalId);
+ const { dispatch } = graph.report!;
+ const runs = await new TaskTopicModel(serverDB, userId).findByTaskId(dispatch.taskId!);
+ const current = runs.find((run) => run.operationId === dispatch.operationId)!;
+ const superseded = runs.find((run) => run.operationId !== dispatch.operationId)!;
+ const buildNode = graph.nodes.find((node) => node.title === 'Build the thing')!;
+ const metadata: GoalReportMetadata = {
+ chapters: [
+ {
+ detours: [],
+ findingIds: [],
+ narrative: 'Built it.',
+ nodeIds: [buildNode.id],
+ title: 'Building',
+ workVersionIds: [],
+ },
+ ],
+ graphCursor: graph.events[0].id,
+ headline: 'Delivered',
+ mainline: { edgeIds: [], nodeIds: [buildNode.id] },
+ nextSteps: [],
+ };
+ const reports = new GoalReportStore(serverDB, userId);
+
+ await expect(
+ reports.submit(goalId, { content: '# Stale', metadata }, { topicId: superseded.topicId }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ const stored = await reports.submit(
+ goalId,
+ { content: '# Current', metadata },
+ { topicId: current.topicId },
+ );
+ expect(stored.version).toBe(1);
+ });
+
+ /**
+ * Regression: while a re-dispatch was still starting its run, the receipt had
+ * no operation yet and the newest run β€” the superseded one β€” counted as
+ * current, so it could still land stale content.
+ */
+ it('refuses the superseded run while a re-dispatch has not recorded its run yet', async () => {
+ const service = new GoalService(serverDB, userId);
+ const { acceptanceTaskId, goalId, taskModel } = await runToAcceptance(service);
+ await taskModel.updateStatus(acceptanceTaskId, 'completed');
+ await service.tick(goalId);
+ await service.tick(goalId);
+ const first = (await service.graph(goalId)).report!.dispatch;
+ const [oldRun] = await new TaskTopicModel(serverDB, userId).findByTaskId(first.taskId!);
+
+ // A re-dispatch claimed its receipt, but its run has not been recorded yet.
+ const goalRow = (await serverDB.select().from(goals).where(eq(goals.id, goalId)))[0];
+ await serverDB
+ .update(goals)
+ .set({
+ config: {
+ ...goalRow.config,
+ report: {
+ ...first,
+ acceptanceKey: `${first.acceptanceKey}:again`,
+ dispatchedAt: new Date(Date.now() + 1000).toISOString(),
+ operationId: undefined,
+ },
+ },
+ })
+ .where(eq(goals.id, goalId));
+
+ const graph = await service.graph(goalId);
+ const buildNode = graph.nodes.find((node) => node.title === 'Build the thing')!;
+ const metadata: GoalReportMetadata = {
+ chapters: [
+ {
+ detours: [],
+ findingIds: [],
+ narrative: 'Built it.',
+ nodeIds: [buildNode.id],
+ title: 'Building',
+ workVersionIds: [],
+ },
+ ],
+ graphCursor: graph.events[0].id,
+ headline: 'Delivered',
+ mainline: { edgeIds: [], nodeIds: [buildNode.id] },
+ nextSteps: [],
+ };
+ await expect(
+ new GoalReportStore(serverDB, userId).submit(
+ goalId,
+ { content: '# Stale', metadata },
+ { topicId: oldRun.topicId },
+ ),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ /**
+ * Regression: the wrap-up node was recognised by its title, so planned work
+ * that happened to be called the same was hidden from the coordinator.
+ */
+ it('dispatches ordinary work that only shares the wrap-up title', async () => {
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ requirement: 'Write it up',
+ tasks: [GOAL_REPORT_TASK_TITLE],
+ title: 'Lookalike goal',
+ });
+ const result = await service.tick(graph.goal.id);
+ expect(result.taskId).toBeDefined();
+ expect(reportTaskRuns()).toHaveLength(0);
+ });
+
/**
* Regression: a heterogeneous wrap-up agent never receives server tools, so an
* instruction naming only the report tool could never be followed.
@@ -315,7 +444,7 @@ describe('GoalReportStore.submit', () => {
await expect(
reports.submit(goalId, { content: '# Report', metadata }, { topicId: 'tpc_other' }),
- ).rejects.toThrow('not the wrap-up run');
+ ).rejects.toThrow('not the current wrap-up run');
expect(await new WorkModel(serverDB, userId).findLatestGoalReport(goalId)).toBeUndefined();
expect((await service.graph(goalId)).report?.status).toBe('running');
diff --git a/apps/server/src/services/goal/reportService.ts b/apps/server/src/services/goal/reportService.ts
index e3c28c07b49..a4d552e90eb 100644
--- a/apps/server/src/services/goal/reportService.ts
+++ b/apps/server/src/services/goal/reportService.ts
@@ -67,28 +67,34 @@ export class GoalReportService {
id: GOAL_COORDINATOR_ACTOR_ID,
type: 'system',
});
- const created = await writer.createNodeOnce(goalId, {
- description:
- 'Wrap-up: turn the finished Goal graph into a chaptered storyline and a written report. Does not affect the Goal status.',
- kind: 'task',
- priority: -2,
- status: 'proposed',
- title: GOAL_REPORT_TASK_TITLE,
- });
- if (!created) return undefined;
- if (created.created) {
+ // A later result reuses the wrap-up node this Goal already recorded; it is
+ // never looked up by title, which any task could share.
+ const recorded = goal.config?.report?.nodeId;
+ const existing = recorded ? graph.nodes.find((node) => node.id === recorded) : undefined;
+ const node =
+ existing ??
+ (await writer.createNode(goalId, {
+ description:
+ 'Wrap-up: turn the finished Goal graph into a chaptered storyline and a written report. Does not affect the Goal status.',
+ kind: 'task',
+ priority: -2,
+ status: 'proposed',
+ title: GOAL_REPORT_TASK_TITLE,
+ }));
+ if (!node) return undefined;
+ if (!existing) {
const acceptance = graph.nodes.find(
- (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE,
+ (candidate) =>
+ candidate.kind === 'task' && candidate.title === GOAL_ACCEPTANCE_TASK_TITLE,
);
- if (acceptance)
- await writer.createEdge(goalId, created.node.id, acceptance.id, 'depends_on');
+ if (acceptance) await writer.createEdge(goalId, node.id, acceptance.id, 'depends_on');
}
const dispatch: GoalReportDispatch = {
acceptanceKey: decision.key,
dispatchedAt: new Date().toISOString(),
- nodeId: created.node.id,
- taskId: created.node.taskId ?? undefined,
+ nodeId: node.id,
+ taskId: node.taskId ?? undefined,
trigger: decision.trigger,
};
await model.update(goalId, { config: { ...goal.config, report: dispatch } });
diff --git a/apps/server/src/services/goal/reportStore.ts b/apps/server/src/services/goal/reportStore.ts
index 9708e4e7a27..d4acf56d3fb 100644
--- a/apps/server/src/services/goal/reportStore.ts
+++ b/apps/server/src/services/goal/reportStore.ts
@@ -107,11 +107,24 @@ export class GoalReportStore {
});
if (caller) {
+ // Only the run of the CURRENT dispatch may write. A re-dispatch reuses the
+ // Task and starts a new run, and the previous one can outlive a failed
+ // cancel β€” accepting any run in the Task's history would let it land stale
+ // content as the newest version.
+ //
+ // The dispatch records its operation only once the new run has started.
+ // Until then the newest run may still be the superseded one, so a run
+ // counts only if it was created after this dispatch was claimed; with
+ // neither, nothing is current and every run is refused.
const runs = dispatch.taskId ? await this.taskTopicModel.findByTaskId(dispatch.taskId) : [];
- if (!caller.topicId || !runs.some((run) => run.topicId === caller.topicId))
+ const dispatchedAt = Date.parse(dispatch.dispatchedAt);
+ const current = dispatch.operationId
+ ? runs.find((run) => run.operationId === dispatch.operationId)
+ : runs.find((run) => new Date(run.createdAt).getTime() >= dispatchedAt);
+ if (!caller.topicId || current?.topicId !== caller.topicId)
throw new TRPCError({
code: 'FORBIDDEN',
- message: 'This conversation is not the wrap-up run of this Goal',
+ message: 'This conversation is not the current wrap-up run of this Goal',
});
}
diff --git a/src/features/AgentGoals/ProcessControl/goalResultState.test.ts b/src/features/AgentGoals/ProcessControl/goalResultState.test.ts
index f4016cf3adb..ad7a91bc4fa 100644
--- a/src/features/AgentGoals/ProcessControl/goalResultState.test.ts
+++ b/src/features/AgentGoals/ProcessControl/goalResultState.test.ts
@@ -10,6 +10,7 @@ import {
buildStoryChapters,
buildUserDecisions,
type CheckLike,
+ countGoalTasks,
deriveGoalResultStatus,
deriveSignOffState,
findFinalAcceptanceView,
@@ -608,6 +609,7 @@ describe('buildResultTrail', () => {
artifacts: [artifact('v-a', 'task-a', 12), artifact('v-b', 'task-b', 7)],
byId: { 'task-a': taskA, 'task-b': taskB, 'task-idle': idle },
findings: [findingA, orphan, findingB],
+ goal: { config: {} } as any,
});
expect(trail.map((step) => step.key)).toEqual(['task-b', 'task-a', 'unattributed']);
@@ -645,10 +647,30 @@ describe('buildResultTrail without the wrap-up Task', () => {
],
byId: { 'task': work, 'task-a': work, 'wrap': wrapUp },
findings: [finding],
+ goal: { config: { report: { nodeId: 'wrap' } } } as any,
});
expect(trail.map((step) => step.key)).toEqual(['task-a']);
});
+
+ /**
+ * Regression: the wrap-up was recognised by its title, so ordinary work that
+ * happened to be called the same vanished from the trail and the task count.
+ */
+ it('keeps a task that only shares the wrap-up title', () => {
+ const lookalike = task('task-b', GOAL_REPORT_TASK_TITLE, 3);
+ const goal = { config: { report: { nodeId: 'wrap' } } } as any;
+
+ const trail = buildResultTrail({
+ artifacts: [{ createdAt: at(3), nodeId: 'task-b', workVersionId: 'v-b' } as any],
+ byId: { 'task-b': lookalike },
+ findings: [],
+ goal,
+ });
+
+ expect(trail.map((step) => step.key)).toEqual(['task-b']);
+ expect(countGoalTasks({ goal, nodes: [lookalike] })).toBe(1);
+ });
});
describe('resultTrailSource', () => {
diff --git a/src/features/AgentGoals/ProcessControl/goalResultState.ts b/src/features/AgentGoals/ProcessControl/goalResultState.ts
index e08a1573ee3..f6a53235756 100644
--- a/src/features/AgentGoals/ProcessControl/goalResultState.ts
+++ b/src/features/AgentGoals/ProcessControl/goalResultState.ts
@@ -1,4 +1,3 @@
-import { GOAL_REPORT_TASK_TITLE } from '@lobechat/const/goal';
import type {
AcceptanceStatus,
GoalChangeRequest,
@@ -384,17 +383,23 @@ export const buildAbandonedNodes = (graph: Pick<GoalGraphView, 'nodes'>): Abando
* Work Tasks the Goal ran, for the scale line. The coordinator's own acceptance
* and wrap-up Tasks check and describe the work; they are not part of it.
*/
-export const countGoalTasks = (graph: Pick<GoalGraphView, 'nodes'>): number =>
+export const countGoalTasks = (graph: Pick<GoalGraphView, 'goal' | 'nodes'>): number =>
graph.nodes.filter(
(view) =>
view.node.kind === 'task' &&
!isGoalAcceptanceTask(view) &&
- view.node.title !== GOAL_REPORT_TASK_TITLE,
+ !isGoalReportTaskView(graph, view),
).length;
-/** The coordinator's wrap-up Task, which writes the report about the Goal. */
-export const isGoalReportTaskView = (view: Pick<GoalNodeView, 'node'>): boolean =>
- view.node.kind === 'task' && view.node.title === GOAL_REPORT_TASK_TITLE;
+/**
+ * The coordinator's wrap-up Task, which writes the report about the Goal. It is
+ * the node the dispatch recorded on the Goal, never matched by title β€” a task
+ * that merely shares the title is ordinary work.
+ */
+export const isGoalReportTaskView = (
+ graph: Pick<GoalGraphView, 'goal'>,
+ view: Pick<GoalNodeView, 'node'>,
+): boolean => view.node.id === graph.goal.config?.report?.nodeId;
/**
* One step of the result's audit trail: the work that ran, what it concluded,
@@ -421,7 +426,7 @@ const settledAt = (view: GoalNodeView) => (view.node.resolvedAt ?? view.node.cre
* the trail is about output, the process tab already lists every task.
*/
export const buildResultTrail = (
- graph: Pick<GoalGraphView, 'artifacts' | 'byId' | 'findings'>,
+ graph: Pick<GoalGraphView, 'artifacts' | 'byId' | 'findings' | 'goal'>,
): ResultTrailStep[] => {
const steps = new Map<string, ResultTrailStep>();
const orphans: GoalNodeView[] = [];
@@ -437,7 +442,7 @@ export const buildResultTrail = (
for (const finding of graph.findings) {
const producer = finding.producedBy && graph.byId[finding.producedBy.id];
- if (producer && isGoalReportTaskView(producer)) continue;
+ if (producer && isGoalReportTaskView(graph, producer)) continue;
if (producer) stepOf(producer.node.id).findings.push(finding);
else orphans.push(finding);
}
@@ -447,7 +452,7 @@ export const buildResultTrail = (
const ordered = [...steps.values()]
// The wrap-up Task describes the result; it is not a step toward it.
- .filter((step) => step.view && !isGoalReportTaskView(step.view))
+ .filter((step) => step.view && !isGoalReportTaskView(graph, step.view))
.sort((a, b) => settledAt(a.view!) - settledAt(b.view!));
for (const step of ordered) {
step.findings.sort((a, b) => settledAt(a) - settledAt(b));