๐คฏ 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
โป๏ธ refactor(goal): split the 5080-line GoalService into cohesive modules (#21145)
Arvin Xu76f38bd6a7c8
diff --git a/apps/server/src/services/goal/index.abandonedRun.test.ts b/apps/server/src/services/goal/GoalService/__tests__/abandonedRun.test.tssimilarity index 98%rename from apps/server/src/services/goal/index.abandonedRun.test.tsrename to apps/server/src/services/goal/GoalService/__tests__/abandonedRun.test.tsindex 54bbbf0adb7..73927c284e6 100644--- a/apps/server/src/services/goal/index.abandonedRun.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/abandonedRun.test.ts@@ -23,10 +23,10 @@ import type { LobeChatDatabase } from '@/database/type';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';import { AiAgentService } from '@/server/services/aiAgent';-import { deviceGateway } from '../deviceGateway';-import { TaskRunnerService } from '../taskRunner';-import { GoalService } from './index';-import { VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';+import { deviceGateway } from '../../../deviceGateway';+import { TaskRunnerService } from '../../../taskRunner';+import { VERIFY_SETTLE_GRACE_MS } from '../../recoveryPolicy';+import { GoalService } from '../index';const serverDB: LobeChatDatabase = await getTestDB();const userId = 'goal-verify-repair-test-user';diff --git a/apps/server/src/services/goal/GoalService/__tests__/acceptance.test.ts b/apps/server/src/services/goal/GoalService/__tests__/acceptance.test.tsnew file mode 100644index 00000000000..ad713d27ca7--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/acceptance.test.ts@@ -0,0 +1,420 @@+// @vitest-environment node+import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';+import * as goalGraphUtils from '@lobechat/utils/goalGraph';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AcceptanceModel } from '@/database/models/acceptance';+import { TaskModel } from '@/database/models/task';+import { agents } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { TaskRunnerService } from '../../../taskRunner';+import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ it('files a goal the agent created under that agent, not its owner', async () => {+ // `/goal` is an agent making the call. `agentId` alone cannot say so โ the+ // creation modal sets it too, and there the author is the person.+ await serverDB+ .insert(agents)+ .values({ id: 'agt_goal_author', slug: 'agt-goal-author', userId });+ const service = new GoalService(serverDB, userId);++ const graph = await service.create({+ agentId: 'agt_goal_author',+ createdByAgentId: 'agt_goal_author',+ title: 'Agent-authored goal',+ tasks: ['Do the thing'],+ });++ const seeded = graph.events.filter((event) => ['created', 'linked'].includes(event.eventType));+ expect(seeded.length).toBeGreaterThan(0);+ expect(seeded.every((event) => event.actorType === 'agent')).toBe(true);+ expect(seeded.every((event) => event.actorId === 'agt_goal_author')).toBe(true);+ expect(graph.nodes.every((node) => node.createdByAgentId === 'agt_goal_author')).toBe(true);+ });++ it('still files a goal the user created under the user, even on an agent page', async () => {+ // The modal passes `agentId` for assignment; the author is the person.+ await serverDB.insert(agents).values({ id: 'agt_assignee', slug: 'agt-assignee', userId });+ const service = new GoalService(serverDB, userId);++ const graph = await service.create({+ agentId: 'agt_assignee',+ title: 'User-authored goal',+ tasks: ['Do the thing'],+ });++ const seeded = graph.events.filter((event) => ['created', 'linked'].includes(event.eventType));+ expect(seeded.every((event) => event.actorType === 'user')).toBe(true);+ expect(seeded.every((event) => event.actorId === userId)).toBe(true);+ });++ it('separates what the coordinator decided from what the user asked for', async () => {+ // The audit trail recorded every transition as the goal's owner, so "what did+ // the system decide on its own" could not be answered from product data.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Do the thing'], title: 'Attributed goal' });++ // Seeding is the user's ask; claiming the Task and binding its runner is not.+ await service.tick(graph.goal.id);++ const { events, nodes } = await service.graph(graph.goal.id);+ const task = nodes.find((node) => node.kind === 'task')!;+ const actorsFor = (eventType: string, entityId: string) =>+ events+ .filter((event) => event.eventType === eventType && event.entityId === entityId)+ .map((event) => ({ actorId: event.actorId, actorType: event.actorType }));++ expect(actorsFor('created', task.id)).toEqual([{ actorId: userId, actorType: 'user' }]);+ expect(actorsFor('activated', task.id)).toEqual([+ { actorId: GOAL_COORDINATOR_ACTOR_ID, actorType: 'system' },+ ]);+ expect(events.some((event) => event.actorType === 'system')).toBe(true);+ });++ it('keeps the overall requirement as background while making the current Task authoritative', async () => {+ const service = new GoalService(serverDB, userId);+ const requirement = `Generate verified training data. ${'Detailed acceptance evidence. '.repeat(20)}`;+ const graph = await service.create({+ requirement,+ title: 'Long requirement goal',+ tasks: ['Generate training data'],+ });++ const created = await service.tick(graph.goal.id);+ const task = await new TaskModel(serverDB, userId).findById(created.taskId!);++ expect(created.outcome).toBe('advanced');+ expect(task?.description).toBe('Generate training data');+ expect(task?.instruction).toContain(requirement);+ expect(task?.instruction).toContain(+ 'Current Task contract (authoritative execution scope): Generate training data',+ );+ expect(task?.instruction).toContain('Do not implement, validate, or pre-empt any sibling');+ expect(task?.instruction).toContain(+ 'missing or broken capabilities within its scope are work to implement or repair',+ );+ expect(task?.instruction).toContain(+ 'resolve the prerequisite before repeating the same checks',+ );+ expect(task?.instruction).toContain(+ 'For an investigation-only Task, deliver supported findings',+ );+ expect(task?.instruction).toContain('do not silently expand into implementation');+ expect(task?.instruction).toContain('run it inside this Task');+ expect(task?.instruction).toContain(+ 'Include the relevant artifact contents or exact excerpts and the raw outputs of decisive verification commands',+ );+ });++ it('gates every responsible task with a Task-scoped Acceptance requirement', async () => {+ const service = new GoalService(serverDB, userId);+ const agentId = 'goal-work-verifier-agent';+ await serverDB.insert(agents).values({ id: agentId, title: 'Goal worker', userId });+ const graph = await service.create({+ agentId,+ requirement: 'Generate data, then train and evaluate a model.',+ title: 'Two-stage experiment',+ tasks: ['Generate isolated data'],+ });++ const created = await service.tick(graph.goal.id);+ const taskModel = new TaskModel(serverDB, userId);+ const task = await taskModel.findById(created.taskId!);+ const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(+ 'task',+ created.taskId!,+ );++ expect(taskModel.shouldPauseOnTopicComplete(task!)).toBe(false);+ expect(task?.config).not.toHaveProperty('verify');+ expect(acceptance).toMatchObject({ config: { enabled: true } });+ expect(acceptance?.config).not.toHaveProperty('verifierAgentId');+ expect(acceptance?.requirement).toContain('Verify only this Task: Generate isolated data.');+ expect(acceptance?.requirement).toContain(+ 'Ignore sibling and downstream Task deliverables; they are verified by their own acceptance runs.',+ );+ });++ it('requires a Goal-level Acceptance Task before marking the complete goal achieved', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ requirement: 'A runnable minimal training loop with evidence',+ title: 'Reproduce Ornith training',+ tasks: ['Implement minimal training loop'],+ });++ const created = await service.tick(graph.goal.id);+ expect(created).toMatchObject({ outcome: 'advanced' });+ expect(created.taskId).toBeDefined();++ const waitingGraph = await service.graph(graph.goal.id);+ expect(waitingGraph.nodes.find((node) => node.kind === 'task')).toMatchObject({+ status: 'active',+ taskId: created.taskId,+ });+ expect(waitingGraph.workVersions).toHaveLength(1);+ const responsibleTask = await taskModel.findById(created.taskId!);+ expect(responsibleTask).toBeDefined();+ expect(taskModel.shouldPauseOnTopicComplete(responsibleTask!)).toBe(false);++ await taskModel.updateStatus(created.taskId!, 'completed');+ const synthesized = await service.tick(graph.goal.id);+ expect(synthesized.outcome).toBe('advanced');++ const evolved = await service.graph(graph.goal.id);+ expect(evolved.nodes.some((node) => node.kind === 'finding')).toBe(true);+ expect(evolved.edges.some((edge) => edge.kind === 'produces')).toBe(true);++ const goalAcceptanceCreated = await service.tick(graph.goal.id);+ expect(goalAcceptanceCreated).toMatchObject({+ message: 'Created Goal-level acceptance Task for the remaining contract',+ outcome: 'advanced',+ });+ const acceptanceWork = (await service.graph(graph.goal.id)).nodes.find(+ (node) => node.id === goalAcceptanceCreated.nodeId,+ );++ const acceptanceTaskCreated = await service.tick(graph.goal.id);+ expect(acceptanceTaskCreated).toMatchObject({ outcome: 'advanced' });+ const acceptanceTask = await taskModel.findById(acceptanceTaskCreated.taskId!);+ const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(+ 'task',+ acceptanceTaskCreated.taskId!,+ );+ expect(acceptanceTask?.instruction).toContain(+ 'Complete and prove the overall Goal acceptance requirement',+ );+ expect(acceptance?.requirement).toContain('A runnable minimal training loop with evidence');+ expect(acceptance?.requirement).toContain(+ 'An accurate gap analysis, a report that the Goal is not accepted',+ );+ expect(acceptance?.requirement).toContain('the verdict MUST be failed');+ expect(acceptanceWork?.description).toContain('Do not repeat expensive or destructive work');+ expect(acceptanceWork?.description).toContain('Run only the missing or stale checks');++ await taskModel.updateStatus(acceptanceTaskCreated.taskId!, 'completed');+ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');++ const achieved = await service.tick(graph.goal.id);+ expect(achieved).toMatchObject({+ message: 'Goal-level acceptance passed',+ outcome: 'achieved',+ });+ const finalGraph = await service.graph(graph.goal.id);+ expect(finalGraph.goal.status).toBe('achieved');+ // The verdict closes the map too: the seeded problem node has no other+ // resolution path, and must not read "active" on an achieved goal.+ expect(finalGraph.nodes.find((node) => node.kind === 'problem')).toMatchObject({+ status: 'resolved',+ });+ });++ it('does not mark a required goal achieved when only its initial Task is complete', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ requirement: 'Return a supplier list with fixed prices.',+ title: 'Find BW150 suppliers and fixed prices',+ tasks: ['Verify the BW150 product identity'],+ });++ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'completed');+ await service.tick(graph.goal.id);++ const result = await service.tick(graph.goal.id);+ const current = await service.graph(graph.goal.id);++ expect(result).toMatchObject({ outcome: 'advanced' });+ expect(current.goal.status).not.toBe('achieved');+ expect(current.nodes).toContainEqual(+ expect.objectContaining({+ kind: 'task',+ status: 'proposed',+ title: 'Complete full Goal acceptance',+ }),+ );+ });++ it('creates only one Goal-level Acceptance Task when terminal ticks race', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ requirement: 'Return three verified supplier quotes.',+ title: 'Find supplier quotes',+ tasks: ['Research suppliers'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'completed');+ await service.tick(graph.goal.id);++ await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);+ const current = await service.graph(graph.goal.id);+ const acceptanceWorks = current.nodes.filter(+ (node) => node.title === 'Complete full Goal acceptance',+ );++ expect(acceptanceWorks).toHaveLength(1);+ expect(+ current.edges.filter(+ (edge) => edge.kind === 'decomposes' && edge.targetNodeId === acceptanceWorks[0].id,+ ),+ ).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());+ });++ it('builds the Goal-level Acceptance Task on the units a batch delivered', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 7 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 7,+ units: Array.from({ length: 7 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'full' } },+ requirement: 'Migrate every store.',+ title: 'Batch to acceptance',+ });++ let acceptance;+ for (let i = 0; i < 30 && !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');+ }++ // The report walks back from acceptance; the batch's units must be on that path.+ const current = await service.graph(graph.goal.id);+ const units = current.nodes+ .filter((node) => /^Unit \d+$/.test(node.title) && node.status === 'resolved')+ .map((node) => node.id);+ expect(acceptance).toBeTruthy();+ expect(units).toHaveLength(7);+ expect(+ current.edges+ .filter((edge) => edge.kind === 'depends_on' && edge.sourceNodeId === acceptance!.id)+ .map((edge) => edge.targetNodeId)+ .sort(),+ ).toEqual(units.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());+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.ts b/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.tsnew file mode 100644index 00000000000..0b2b2598197--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.ts@@ -0,0 +1,476 @@+// @vitest-environment node+import { eq, sql } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { ExpertiseModel } from '@/database/models/expertise';+import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { briefs, goals } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { TaskRunnerService } from '../../../taskRunner';+import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';+import { VERIFICATION_FAILED_ERROR } from '../../decideNextMove';+import { uncoveredAxisValues } from '../../spec';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ describe('answering a batch break', () => {+ const decompose = (variants: { axis: string; values: string[] }[] = []) =>+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 7 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 7,+ units: Array.from({ length: 7 }, (_, i) => `Unit ${i + 1}`),+ variants,+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const pendingBreak = async (service: GoalService, goalId: string) =>+ (await service.graph(goalId)).decisions.find(+ (item) =>+ item.status === 'pending' && item.options?.some((option) => option.id === 'revise'),+ )!;++ it('re-probes delivered units when the roster is exhausted and the gate held anyway', async () => {+ // An axis value no unit's brief mentions keeps the gate shut even with+ // every unit delivered.+ decompose([{ axis: 'render', values: ['ssr'] }]);+ const service = new GoalService(serverDB, userId);+ const graphModel = new GoalGraphModel(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'full' } },+ title: 'Full rollout, axis untested',+ });+ await service.tick(graph.goal.id);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ for (const id of [...state.probeNodeIds, ...(state.massNodeIds ?? [])])+ await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');+ await service.tick(graph.goal.id);+ expect((await service.graph(graph.goal.id)).goal.config!.rolloutState!.phase).toBe(+ 'pattern_break',+ );++ const decision = await pendingBreak(service, graph.goal.id);+ await service.decide(graph.goal.id, decision.id, 'revise', 'ๆฏไธชๅๅ ้ฝๆ ssr ่ทฏๅพ้ช่ฏ');++ // The new canary is not empty: delivered units are re-probed under v2.+ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ expect(next.phase).toBe('probe');+ expect(next.probeNodeIds.length).toBeGreaterThan(0);+ });++ it('leaves the question open when the restart fails part-way, and restarts on a retry', async () => {+ decompose();+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },+ title: 'Restart is atomic',+ });+ await service.tick(graph.goal.id);+ const openGate = (+ service as unknown as {+ openPatternBreakGate: (+ g: unknown,+ message: string,+ effects: unknown[],+ ) => Promise<unknown>;+ }+ ).openPatternBreakGate.bind(service);+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);+ const before = await service.graph(graph.goal.id);+ const decision = await pendingBreak(service, graph.goal.id);++ // The restart dies after writing its new plan, while creating the next gate.+ await serverDB.execute(sql`+ CREATE OR REPLACE FUNCTION fail_next_assay() RETURNS trigger AS $$+ BEGIN+ IF NEW.kind = 'decision' THEN RAISE EXCEPTION 'worker stopped'; END IF;+ RETURN NEW;+ END $$ LANGUAGE plpgsql+ `);+ await serverDB.execute(sql`+ CREATE TRIGGER fail_next_assay BEFORE INSERT ON goal_nodes+ FOR EACH ROW EXECUTE FUNCTION fail_next_assay()+ `);+ try {+ await expect(+ service.decide(graph.goal.id, decision.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ'),+ ).rejects.toThrow();+ } finally {+ await serverDB.execute(sql`DROP TRIGGER IF EXISTS fail_next_assay ON goal_nodes`);+ await serverDB.execute(sql`DROP FUNCTION IF EXISTS fail_next_assay()`);+ }++ // Nothing of the half round survived, and the question is still open.+ const failed = await service.graph(graph.goal.id);+ expect(failed.nodes).toHaveLength(before.nodes.length);+ expect(failed.goal.config!.rolloutState!.phase).toBe('pattern_break');+ expect((await pendingBreak(service, graph.goal.id)).id).toBe(decision.id);++ // Answering again opens the next round.+ await service.decide(graph.goal.id, decision.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ expect(next.phase).toBe('probe');+ expect(next.templateRevision).toBe(2);+ });++ it('leaves a brief for the batch gate so Home keeps it after a dismissal', async () => {+ decompose();+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },+ title: 'Batch gate brief',+ });+ await service.tick(graph.goal.id);+ const openGate = (+ service as unknown as {+ openPatternBreakGate: (+ g: unknown,+ message: string,+ effects: unknown[],+ ) => Promise<unknown>;+ }+ ).openPatternBreakGate.bind(service);+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);+ const decision = await pendingBreak(service, graph.goal.id);++ const rows = await serverDB.select().from(briefs).where(eq(briefs.userId, userId));+ const brief = rows.find(+ (row) =>+ (row.metadata as { goal?: { decisionId?: string } } | null)?.goal?.decisionId ===+ decision.id,+ );+ expect(brief).toMatchObject({ type: 'decision' });+ // Revising needs a correction, so the brief sends the person to the goal+ // page rather than offering one-click answers.+ expect((brief!.actions as { key: string }[]).map((action) => action.key)).toEqual([+ 'openGoal',+ ]);+ });++ it('does not re-park a goal whose gate was answered while its brief was written', async () => {+ decompose();+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },+ title: 'Answered during the brief',+ });+ await service.tick(graph.goal.id);+ const internals = service as unknown as {+ briefs: { openDecision: (...args: unknown[]) => Promise<void> };+ openPatternBreakGate: (g: unknown, message: string, effects: unknown[]) => Promise<unknown>;+ };+ // The person answers the moment the gate is visible, before the brief lands.+ internals.briefs.openDecision = async () => {+ const decision = await pendingBreak(service, graph.goal.id);+ await service.decide(graph.goal.id, decision.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ };++ await internals.openPatternBreakGate.bind(service)(+ await service.graph(graph.goal.id),+ 'Unit 1 did not pass',+ [],+ );++ // The answer resumed the goal on a new round; the opener must not undo it.+ const after = await service.graph(graph.goal.id);+ expect(after.goal.config!.rolloutState!.phase).toBe('probe');+ expect(after.goal.status).toBe('running');+ expect(after.goal.config?.pausedBy).toBeUndefined();+ });++ it('refuses to revise the recipe without a correction', async () => {+ decompose();+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },+ title: 'Revise needs a correction',+ });+ await service.tick(graph.goal.id);+ const openGate = (+ service as unknown as {+ openPatternBreakGate: (+ g: unknown,+ message: string,+ effects: unknown[],+ ) => Promise<unknown>;+ }+ ).openPatternBreakGate.bind(service);+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);+ const decision = await pendingBreak(service, graph.goal.id);++ await expect(service.decide(graph.goal.id, decision.id, 'revise', ' ')).rejects.toThrow(+ 'Revising the recipe needs a correction',+ );+ // The question stays open for an answer that says what to change.+ expect((await pendingBreak(service, graph.goal.id)).id).toBe(decision.id);+ });++ it('fails the fork, keeping the question open, when the old rules cannot be retired', async () => {+ decompose();+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },+ title: 'Fork with a stuck rule',+ });+ await service.tick(graph.goal.id);+ const openGate = (+ service as unknown as {+ openPatternBreakGate: (+ g: unknown,+ message: string,+ effects: unknown[],+ ) => Promise<unknown>;+ }+ ).openPatternBreakGate.bind(service);+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);+ let decision = await pendingBreak(service, graph.goal.id);+ await service.decide(graph.goal.id, decision.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);+ decision = await pendingBreak(service, graph.goal.id);++ // Retiring the old rule fails.+ await serverDB.execute(sql`+ CREATE OR REPLACE FUNCTION fail_lesson_retire() RETURNS trigger AS $$+ BEGIN+ IF NEW.status = 'retired' THEN RAISE EXCEPTION 'retire failed'; END IF;+ RETURN NEW;+ END $$ LANGUAGE plpgsql+ `);+ await serverDB.execute(sql`+ CREATE TRIGGER fail_lesson_retire BEFORE UPDATE ON expertise_lessons+ FOR EACH ROW EXECUTE FUNCTION fail_lesson_retire()+ `);+ try {+ await expect(+ service.decide(graph.goal.id, decision.id, 'new_class', 'ๆๆฐ็ฑปๅๅค็'),+ ).rejects.toThrow();+ } finally {+ await serverDB.execute(sql`DROP TRIGGER IF EXISTS fail_lesson_retire ON expertise_lessons`);+ await serverDB.execute(sql`DROP FUNCTION IF EXISTS fail_lesson_retire()`);+ }++ // The batch still knows the rule (so retiring it can be retried), and the+ // question is still there to answer.+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ expect(state.learnings).toHaveLength(1);+ expect((await pendingBreak(service, graph.goal.id)).id).toBe(decision.id);+ });++ it('forks a new class from the original outline, not the revised plan', async () => {+ decompose();+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },+ title: 'Fork after a revision',+ });+ await service.tick(graph.goal.id);+ const openGate = (+ service as unknown as {+ openPatternBreakGate: (+ g: unknown,+ message: string,+ effects: unknown[],+ ) => Promise<unknown>;+ }+ ).openPatternBreakGate.bind(service);++ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);+ let decision = await pendingBreak(service, graph.goal.id);+ await service.decide(graph.goal.id, decision.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ const [taught] = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.learnings!;+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);+ decision = await pendingBreak(service, graph.goal.id);+ await service.decide(graph.goal.id, decision.id, 'new_class', 'ๆๆฐ็ฑปๅๅค็');++ const after = await service.graph(graph.goal.id);+ const plan = after.nodes.find(+ (node) => node.id === after.goal.config!.rolloutState!.templateNodeId,+ )!;+ // The v2 correction belongs to the old class; the fork starts clean.+ expect(plan.description).not.toContain('่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ expect(plan.description).toContain('ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ');+ // โฆand so do its rules: the old class's learnings do not bind the new one.+ expect(after.goal.config!.rolloutState!.learnings).toBeUndefined();+ expect(after.goal.config!.rolloutState!.learningDomainId).toBeUndefined();+ // The old class's rule also stops reaching runs: retired in the shared domain.+ expect((await new ExpertiseModel(serverDB, userId).findLesson(taught.lessonId))?.status).toBe(+ 'retired',+ );+ });+ });++ it('routes a batch unit out of verification retries through the batch gate', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 1 } },+ title: 'Migrate stores',+ });+ await service.tick(graph.goal.id);+ const dispatched = await service.tick(graph.goal.id);+ expect(dispatched.taskId).toBeDefined();++ // The unit's one attempt failed verification: no attempts left.+ const taskModel = new TaskModel(serverDB, userId);+ await taskModel.update(dispatched.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(dispatched.taskId!, 'paused', {+ error: VERIFICATION_FAILED_ERROR,+ });+ // The other probes dispatch first; the paused unit's turn follows.+ for (let i = 0; i < 8; i++) {+ await service.tick(graph.goal.id);+ if ((await service.graph(graph.goal.id)).goal.config!.rolloutState!.phase !== 'probe') break;+ }++ // It breaks the class โ revise the recipe and re-probe โ rather than+ // parking on an ordinary retry/retire gate for one task.+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ expect(state.phase).toBe('pattern_break');+ expect(state.gateLog?.at(-1)).toMatchObject({+ nodeId: dispatched.nodeId,+ outcome: 'blocked',+ trigger: 'unit',+ });+ });++ it('stops the running Tasks of the members a restart retires', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);+ for (let i = 0; i < 5; i++) await service.tick(graph.goal.id);++ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const before = await service.graph(graph.goal.id);+ const state = before.goal.config!.rolloutState!;+ const [broken, sibling] = state.probeNodeIds.map((id) =>+ before.nodes.find((node) => node.id === id)!,+ );+ expect(sibling.taskId).toBeTruthy();+ // One unit broke while a sibling is still running.+ await graphModel.updateNodeStatus(graph.goal.id, broken.id, 'rejected');+ await taskModel.updateStatus(sibling.taskId!, 'running');++ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [{ id: 'revise', label: 'Revise' }],+ question: 'Unit 1 did not pass',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));++ await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');++ // The sibling is retired and its Task stopped โ it no longer runs beside+ // the probe that replaces it.+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.find((node) => node.id === sibling.id)?.status).toBe('retired');+ const [task] = await taskModel.findByIds([sibling.taskId!]);+ expect(task.status).toBe('canceled');+ });++ it('keeps a re-opened probe briefed with its variant assignment', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [{ axis: 'render', values: ['ssr', 'csr'] }],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ๏ผๆ ${i === 0 ? 'ssr' : 'csr'} ่ทฏๅพ้ช่ฏ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);++ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const before = await service.graph(graph.goal.id);+ const state = before.goal.config!.rolloutState!;+ const ssrProbe = before.nodes.find((node) => node.title === 'Unit 1')!;+ await graphModel.updateNodeStatus(graph.goal.id, ssrProbe.id, 'rejected');+ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [{ id: 'revise', label: 'Revise' }],+ question: 'Unit 1 did not pass',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));++ await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');++ // The re-opened probe still says which variant it covers, so the gate does+ // not report the axis value it tested as untested.+ const after = await service.graph(graph.goal.id);+ const next = after.goal.config!.rolloutState!;+ const reopened = after.nodes.find(+ (node) => next.probeNodeIds.includes(node.id) && node.title === 'Unit 1',+ )!;+ expect(reopened.description).toContain('ๆ ssr ่ทฏๅพ้ช่ฏ');+ const probes = after.nodes.filter((node) => next.probeNodeIds.includes(node.id));+ expect(+ uncoveredAxisValues(+ [{ axis: 'render', values: ['ssr', 'csr'] }],+ probes.map((node) => ({ instruction: node.description ?? '', title: node.title })),+ ),+ ).not.toContainEqual({ axis: 'render', value: 'ssr' });+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts b/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.tsnew file mode 100644index 00000000000..443ff6c49dc--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts@@ -0,0 +1,422 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AcceptanceModel } from '@/database/models/acceptance';+import { ExpertiseModel } from '@/database/models/expertise';+import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { agents, documents, goals, projects } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { TaskRunnerService } from '../../../taskRunner';+import { UserSkillService } from '../../../userSkill';+import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ it('re-opens the broken unit as a new task when the canary loop restarts', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);++ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const before = await service.graph(graph.goal.id);+ const state = before.goal.config!.rolloutState!;+ const [broken, ...settled] = state.probeNodeIds;+ for (const id of settled) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');+ await graphModel.updateNodeStatus(graph.goal.id, broken, 'waiting');+ // A wave the round already released, whose member broke and was retired.+ const massMember = await graphModel.createNode(graph.goal.id, {+ kind: 'task',+ scopeId: state.batchNodeId,+ title: 'Unit 6',+ });+ await graphModel.updateNodeStatus(graph.goal.id, massMember!.id, 'retired');++ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [+ { description: 'ไฟฎ่ฎข้ ๆน', id: 'revise', label: 'ไฟฎ่ฎข้ ๆนๅนถ้ๆข' },+ { description: 'ๆฐ็ฑปๅ', id: 'new_class', label: 'ไฝไธบๆฐ็ฑปๅๅนถๆๅค็' },+ ],+ question: 'Unit 1 did not pass',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, {+ ...state,+ massNodeIds: [massMember!.id],+ phase: 'pattern_break',+ });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));++ await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');++ const after = await service.graph(graph.goal.id);+ const next = after.goal.config!.rolloutState!;+ // Decision #4: the broken unit runs again as a new task, the old one retires.+ expect(after.nodes.find((n) => n.id === broken)?.status).toBe('retired');+ // Both units that broke this round โ the probe and the wave member โ re-open.+ const reopenedNodes = next.probeNodeIds.map((id) => after.nodes.find((n) => n.id === id)!);+ expect(reopenedNodes.map((n) => n.title).sort()).toEqual(['Unit 1', 'Unit 6']);+ const reopened = reopenedNodes.find((n) => n.title === 'Unit 1')!;+ expect(+ after.edges.some(+ (e) =>+ e.kind === 'derived_from' && e.sourceNodeId === reopened.id && e.targetNodeId === broken,+ ),+ ).toBe(true);+ // Re-opening is not a new release: the roster is re-cut to what is still+ // owed, so the cursor counts the re-opened probes over the shorter roster,+ // and the units the class still owes stay queued for the waves.+ expect(next.releasedCount).toBe(next.probeNodeIds.length);+ expect(next.unitTitles).toContain('Unit 50');+ expect(new Set(next.unitTitles).size).toBe(next.unitTitles!.length);+ // The revised plan carries v1 forward and appends what changed, so the two+ // versions diff as "v1 + the v2 section", not as a replacement.+ const plan = after.nodes.find((n) => n.id === next.templateNodeId)!;+ expect(plan.description).toBe('ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ\n\n### v2\n่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ // The new canary is a fresh round: the old wave's retired member no longer+ // counts against its gate (it would re-open the same break at once).+ expect(next.massNodeIds).toBeUndefined();++ // The plan lives as a skill in the user's library: v1 at decomposition,+ // v2 when the break revised it โ each version kept whole.+ const planSkill = next.planSkill!;+ expect(planSkill.name).toMatch(/^goal-plan-/);+ const skill = await new UserSkillService(serverDB, userId).getSkill(planSkill.id);+ expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);+ expect(skill?.content).toContain('### v2\n่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ expect(skill?.versions[0].content).not.toContain('### v2');+ // A re-opened unit names the skill, which carries every later revisionโฆ+ expect(reopened.description).toContain(`user-skills:${planSkill.name}`);+ // โฆand still carries the revised plan, in case the skill does not load.+ expect(reopened.description).toContain('### v2\n่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');++ // The break taught the batch: a rule in its expertise, which later units'+ // acceptance adds as a clause โ no standalone criterion that nothing mounts.+ expect(next.learnings).toMatchObject([{ revision: 1, title: '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ' }]);+ const [learning] = next.learnings!;+ expect(learning.criterionId).toBeUndefined();+ const lesson = await new ExpertiseModel(serverDB, userId).findLesson(learning.lessonId);+ expect(lesson).toMatchObject({+ compilability: 'compilable',+ compiledCriterionId: null,+ enforcement: 'block',+ });++ // A unit dispatched after the break loads the skill on every run and is+ // judged by what the batch learned.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ await service.tick(graph.goal.id);+ const dispatched = (await service.graph(graph.goal.id)).nodes.find(+ (node) => next.probeNodeIds.includes(node.id) && node.taskId,+ )!;+ const task = await new TaskModel(serverDB, userId).findById(dispatched.taskId!);+ expect(task?.config).toMatchObject({ skills: [`user-skills:${planSkill.name}`] });+ const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(+ 'task',+ dispatched.taskId!,+ );+ // The learned rule is added to the unit's own contract, not substituted for+ // it: configured criteria would make the verifier check only those.+ expect(acceptance?.config?.verifyCriteriaIds).toBeUndefined();+ expect(acceptance?.requirement).toContain(dispatched.title);+ expect(acceptance?.requirement).toContain('- ่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ });++ it('falls back to copying the revised plan when the skill revision does not land', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);++ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ // The plan skill was deleted from the library in the meantime.+ await serverDB.delete(documents).where(eq(documents.id, state.planSkill!.id));++ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [{ id: 'revise', label: 'Revise' }],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));++ await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');++ // The new round does not point units at a skill that lacks the revision:+ // they carry the revised plan themselves.+ const after = await service.graph(graph.goal.id);+ const next = after.goal.config!.rolloutState!;+ expect(next.planSkill).toBeUndefined();+ const probe = after.nodes.find((node) => node.id === next.probeNodeIds[0])!;+ expect(probe.description).toContain('### v2\n่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ expect(probe.description).not.toContain('user-skills:');+ });++ it('mounts what a break taught on the agent that runs the units, even in a project', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ await serverDB.insert(agents).values([{ id: 'agt_batch', slug: 'agt-batch', userId }]);+ await serverDB.insert(projects).values({+ coordinatorAgentId: 'agt_batch',+ id: 'proj_batch',+ identifier: 'BAT',+ name: 'Batch project',+ userId,+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ agentId: 'agt_batch',+ projectId: 'proj_batch',+ title: 'Migrate stores in a project',+ });+ await service.tick(graph.goal.id);++ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [{ id: 'revise', label: 'Revise' }],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));+ await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');++ // A run's expertise snapshot reads the executing agent's domains, so that+ // is where the batch's rules must live for its units to receive them.+ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ const domains = await new ExpertiseModel(serverDB, userId).listDomainsForAgent('agt_batch');+ expect(domains.map(({ domain }) => domain.id)).toContain(next.learningDomainId);+ });++ it('learns into one shared domain per agent, through the executor fallback', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ await serverDB.insert(agents).values([+ { id: 'agt_goal_main', slug: 'agt-goal-main', userId },+ { id: 'agt_gone_exec', slug: 'agt-gone-exec', userId },+ ]);+ const service = new GoalService(serverDB, userId);+ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const breakAndRevise = async (title: string) => {+ const graph = await service.create({+ agentId: 'agt_goal_main',+ config: { taskAgentId: 'agt_gone_exec' },+ title,+ });+ await service.tick(graph.goal.id);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [{ id: 'revise', label: 'Revise' }],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));+ // The dedicated executor is deleted before the break is answered.+ await serverDB.delete(agents).where(eq(agents.id, 'agt_gone_exec'));+ await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ return (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ };++ // The owner already keeps a batch domain of their own, inherited by every+ // agent: an agent's rule must not land there.+ const ownerDomainId = await new ExpertiseModel(serverDB, userId).createDomain({+ brief: 'What the release gates of goal batches have learned.',+ carrier: { type: 'user' },+ domainFilter: 'Doing or verifying a unit of a goal batch.',+ title: 'Goal batch rules',+ });++ const first = await breakAndRevise('First batch');+ expect(first.learningDomainId).not.toBe(ownerDomainId);+ // Learned despite the stale executor: mounted on the goal agent it falls back to.+ expect(first.learnings).toHaveLength(1);+ const expertise = new ExpertiseModel(serverDB, userId);+ expect(+ (await expertise.listDomainsForAgent('agt_goal_main')).map(({ domain }) => domain.id),+ ).toContain(first.learningDomainId);++ // A second batch on the same agent reuses that domain instead of adding one.+ await serverDB+ .insert(agents)+ .values({ id: 'agt_gone_exec', slug: 'agt-gone-exec', userId })+ .onConflictDoNothing();+ const second = await breakAndRevise('Second batch');+ expect(second.learningDomainId).toBe(first.learningDomainId);+ });++ it('creates one batch domain when two goals on an agent learn at the same time', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ await serverDB.insert(agents).values([{ id: 'agt_shared', slug: 'agt-shared', userId }]);+ const service = new GoalService(serverDB, userId);+ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const openBreak = async (title: string) => {+ const graph = await service.create({ agentId: 'agt_shared', title });+ await service.tick(graph.goal.id);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [{ id: 'revise', label: 'Revise' }],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));+ return { decisionId: decision!.id, goalId: graph.goal.id };+ };+ const a = await openBreak('Batch A');+ const b = await openBreak('Batch B');++ // Both first breaks are answered at once.+ await Promise.all([+ service.decide(a.goalId, a.decisionId, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ'),+ service.decide(b.goalId, b.decisionId, 'revise', '่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ'),+ ]);++ const domainOf = async (goalId: string) =>+ (await service.graph(goalId)).goal.config!.rolloutState!.learningDomainId;+ expect(await domainOf(a.goalId)).toBe(await domainOf(b.goalId));+ const bound = await new ExpertiseModel(serverDB, userId).listDomainsForAgent('agt_shared');+ expect(bound.filter(({ domain }) => domain.title === 'Goal batch rules')).toHaveLength(1);+ });++ it('moves a batch from before plan skills into one at its next revision', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);++ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const { planSkill: _written, ...legacy } = (await service.graph(graph.goal.id)).goal.config!+ .rolloutState!;+ const decision = await graphModel.createDecision(graph.goal.id, legacy.assayNodeId!, {+ authority: 'user',+ options: [{ description: 'ไฟฎ่ฎข้ ๆน', id: 'revise', label: 'ไฟฎ่ฎข้ ๆนๅนถ้ๆข' }],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, legacy.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...legacy, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));++ await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ');++ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ const skill = await new UserSkillService(serverDB, userId).getSkill(next.planSkill!.id);+ // The plan's earlier version becomes v1 and the revision v2, so version N+ // still reads as round N.+ expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);+ expect(skill?.versions[0].content).toContain('ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ');+ expect(skill?.versions[1].content).toContain('### v2\n่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ');+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/clarification.test.ts b/apps/server/src/services/goal/GoalService/__tests__/clarification.test.tsnew file mode 100644index 00000000000..a83f9e89696--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/clarification.test.ts@@ -0,0 +1,296 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { GoalModel } from '@/database/models/goal';+import type { LobeChatDatabase } from '@/database/type';++import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ it('persists the planned recipe when the caller already chose a canary rollout', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [{ axis: 'cold-start', values: ['yes', 'no'] }],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { canarySize: 3, trigger: 'canary', waveSize: 7 } },+ title: 'Migrate stores',+ });+ await service.tick(graph.goal.id);++ const policy = (await service.graph(graph.goal.id)).goal.config!.rollout!;+ // What the planner derived is kept โ later waves brief from it, the gate checks its axesโฆ+ expect(policy.spec?.recipeOutline).toBe('ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ');+ expect(policy.spec?.variantAxes).toEqual([{ axis: 'cold-start', values: ['yes', 'no'] }]);+ expect(policy.units).toHaveLength(50);+ // โฆand what the caller chose still wins.+ expect(policy).toMatchObject({ canarySize: 3, trigger: 'canary', waveSize: 7 });+ });++ it('asks a blocking question before planning, then plans once with the answer', async () => {+ const planner = vi+ .spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')+ .mockResolvedValue({+ assumptions: ['ๆฅๅ็จไธญๆ'],+ problemStatement: 'ไธบๆฐๅ่ฝๅไธไปฝๅๅธ่ฏดๆ',+ questions: [+ {+ assumption: '้ขๅ็ป็ซฏ็จๆท',+ blocking: true,+ impact: 'ๅณๅฎๅไบงๅ่ฏดๆ่ฟๆฏ API ๅๆด',+ options: ['็ป็ซฏ็จๆท', 'ๅผๅ่ '],+ question: '่ฟไปฝ่ฏดๆ็ป่ฐ็๏ผ',+ },+ ],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: 'ๅ่ฏดๆ', title: 'ๆฐๅ' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Release notes' });++ // The first plan asks instead of creating Tasks on a guess.+ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');+ let after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(0);+ const problem = after.nodes.find((n) => n.kind === 'problem')!;+ expect(Number(problem.confidence)).toBe(0.3);+ expect(after.goal.config?.understanding).toMatchObject({+ assumptions: ['ๆฅๅ็จไธญๆ'],+ level: 'low',+ });+ const [decision] = after.decisions;+ expect(decision).toMatchObject({ question: '่ฟไปฝ่ฏดๆ็ป่ฐ็๏ผ', status: 'pending' });+ expect(decision.options?.map((option) => option.id)).toEqual([+ 'option-1',+ 'option-2',+ 'assume',+ 'answer',+ ]);+ expect(after.edges).toContainEqual(+ expect.objectContaining({+ kind: 'leads_to',+ sourceNodeId: problem.id,+ targetNodeId: decision.nodeId,+ }),+ );++ // The open question parks the goal on the ordinary decision gate.+ expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');+ expect((await service.graph(graph.goal.id)).goal.status).toBe('review');++ // An empty free-text answer is refused rather than re-planning on nothing.+ await expect(service.decide(graph.goal.id, decision.id, 'answer', ' ')).rejects.toThrow(+ 'This answer needs a note',+ );+ await service.decide(graph.goal.id, decision.id, 'option-2', 'ๅชๅ ณๅฟ SDK');++ // The re-plan receives the answer and, even though the planner still+ // reports a blocking question, proceeds on assumptions: one round only.+ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');+ expect(planner).toHaveBeenLastCalledWith({+ clarifications: [{ answer: 'ๅผๅ่ (ๅชๅ ณๅฟ SDK)', question: '่ฟไปฝ่ฏดๆ็ป่ฐ็๏ผ' }],+ requirement: expect.any(String),+ });+ after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((n) => n.kind === 'task').map((n) => n.title)).toEqual(['ๆฐๅ']);+ expect(after.decisions.filter((d) => d.status === 'pending')).toHaveLength(0);+ expect(Number(after.nodes.find((n) => n.kind === 'problem')!.confidence)).toBe(0.6);+ // The re-asked question was answered, so its fallback never becomes an+ // assumption that contradicts the answer.+ expect(after.goal.config?.understanding).toMatchObject({+ assumptions: ['ๆฅๅ็จไธญๆ'],+ level: 'medium',+ });+ });++ it('lists a clarification round for other surfaces and answers it in one go', async () => {+ const planner = vi+ .spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')+ .mockResolvedValue({+ assumptions: [],+ problemStatement: 'ๅๅๅธ่ฏดๆ',+ questions: [+ {+ assumption: '็ป็ซฏ็จๆท',+ blocking: true,+ impact: 'ๅณๅฎ่ฏญๆฐ',+ options: ['็ป็ซฏ็จๆท', 'ๅผๅ่ '],+ question: '็ป่ฐ็๏ผ',+ },+ { assumption: 'ๆดๆฐๆฅๅฟ', blocking: true, options: [], question: 'ๅๅจๅช้๏ผ' },+ ],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: 'ๅ', title: 'ๆฐๅ' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ requirement: 'ไธบๆฐๅ่ฝๅไธไปฝๅๅธ่ฏดๆ',+ title: 'Release notes',+ });+ await service.tick(graph.goal.id);++ const pending = await service.pendingClarifications();+ expect(pending).toEqual([+ expect.objectContaining({+ goalId: graph.goal.id,+ questions: expect.arrayContaining([+ expect.objectContaining({ description: 'ๅณๅฎ่ฏญๆฐ', question: '็ป่ฐ็๏ผ' }),+ expect.objectContaining({ description: null, question: 'ๅๅจๅช้๏ผ' }),+ ]),+ // The requirement says which goal this is away from its own page.+ requirement: 'ไธบๆฐๅ่ฝๅไธไปฝๅๅธ่ฏดๆ',+ title: 'Release notes',+ }),+ ]);++ // A paused goal keeps its questions but stops asking them elsewhere.+ await service.pause(graph.goal.id);+ expect(await service.pendingClarifications()).toEqual([]);+ await service.resume(graph.goal.id);+ expect(await service.pendingClarifications()).toHaveLength(1);++ const audience = pending[0].questions.find((q) => q.question === '็ป่ฐ็๏ผ')!;+ const place = pending[0].questions.find((q) => q.question === 'ๅๅจๅช้๏ผ')!;+ await service.answerClarifications(graph.goal.id, [+ { decisionId: audience.decisionId, optionId: 'option-2', resolution: 'ๅชๅ ณๅฟ SDK' },+ { decisionId: place.decisionId, optionId: 'answer', resolution: 'GitHub Release' },+ ]);++ expect(await service.pendingClarifications()).toEqual([]);+ expect((await service.graph(graph.goal.id)).goal.status).toBe('running');+ // One re-plan, carrying both answers.+ await service.tick(graph.goal.id);+ const [lastCall] = planner.mock.calls.at(-1)!;+ expect(lastCall.clarifications).toHaveLength(2);+ expect(lastCall.clarifications).toEqual(+ expect.arrayContaining([+ { answer: 'ๅผๅ่ (ๅชๅ ณๅฟ SDK)', question: '็ป่ฐ็๏ผ' },+ { answer: 'GitHub Release', question: 'ๅๅจๅช้๏ผ' },+ ]),+ );+ });++ it('writes none of a clarification round when one answer is invalid, and retries cleanly', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ assumptions: [],+ problemStatement: 'ๅๅๅธ่ฏดๆ',+ questions: [+ {+ assumption: '็ป็ซฏ็จๆท',+ blocking: true,+ options: ['็ป็ซฏ็จๆท', 'ๅผๅ่ '],+ question: '็ป่ฐ็๏ผ',+ },+ { assumption: 'ๆดๆฐๆฅๅฟ', blocking: true, options: [], question: 'ๅๅจๅช้๏ผ' },+ ],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: 'ๅ', title: 'ๆฐๅ' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Release notes' });+ await service.tick(graph.goal.id);+ const [{ questions }] = await service.pendingClarifications();+ const audience = questions.find((q) => q.question === '็ป่ฐ็๏ผ')!;+ const place = questions.find((q) => q.question === 'ๅๅจๅช้๏ผ')!;++ // The second answer is invalid, so the first must not be written either.+ await expect(+ service.answerClarifications(graph.goal.id, [+ { decisionId: audience.decisionId, optionId: 'option-2' },+ { decisionId: place.decisionId, optionId: 'no-such-option' },+ ]),+ ).rejects.toThrow('Unknown decision option');+ expect((await service.pendingClarifications())[0].questions).toHaveLength(2);++ // A retry after a partial write succeeds: the recorded answer is skipped.+ await service.decide(graph.goal.id, audience.decisionId, 'option-2');+ await service.answerClarifications(graph.goal.id, [+ { decisionId: audience.decisionId, optionId: 'option-2' },+ { decisionId: place.decisionId, optionId: 'assume' },+ ]);+ expect(await service.pendingClarifications()).toEqual([]);+ });++ it('keeps the answers in the fallback task when the re-plan fails', async () => {+ const planner = vi+ .spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')+ .mockResolvedValue({+ assumptions: [],+ problemStatement: 'ๅๅๅธ่ฏดๆ',+ questions: [+ {+ assumption: '็ป็ซฏ็จๆท',+ blocking: true,+ options: ['็ป็ซฏ็จๆท', 'ๅผๅ่ '],+ question: '็ป่ฐ็๏ผ',+ },+ ],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: 'ๅ', title: 'ๆฐๅ' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ problemDescription: 'ๅไธไปฝๅๅธ่ฏดๆ๏ผๅฟ ้กป้ไธ่ฟ็งปๆๅ',+ requirement: 'ๅไธไปฝๅๅธ่ฏดๆ๏ผๅฟ ้กป้ไธ่ฟ็งปๆๅ',+ title: 'Release notes',+ });+ await service.tick(graph.goal.id);+ // Asking commits no tasks, so the user's own words stay on the problem.+ expect(+ (await service.graph(graph.goal.id)).nodes.find((n) => n.kind === 'problem')!.description,+ ).toBe('ๅไธไปฝๅๅธ่ฏดๆ๏ผๅฟ ้กป้ไธ่ฟ็งปๆๅ');+ const [{ questions }] = await service.pendingClarifications();+ await service.answerClarifications(graph.goal.id, [+ { decisionId: questions[0].decisionId, optionId: 'option-2', resolution: 'ๅชๅ ณๅฟ SDK' },+ ]);++ planner.mockRejectedValueOnce(new Error('planner down'));+ await service.tick(graph.goal.id);++ const task = (await service.graph(graph.goal.id)).nodes.find((n) => n.kind === 'task');+ // The original request's constraint survives, not the planner's summary.+ expect(task!.description).toContain('ๅฟ ้กป้ไธ่ฟ็งปๆๅ');+ expect(task!.description).toContain('Q: ็ป่ฐ็๏ผ');+ expect(task!.description).toContain('A: ๅผๅ่ (ๅชๅ ณๅฟ SDK)');+ });++ it('keeps the coordinator understanding when the user edits the goal policy', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ assumptions: ['ๅชไฟฎ P0'],+ problemStatement: 'ไฟฎ bug',+ questions: [],+ tasks: [{ dependsOn: [], hypothesis: null, instruction: 'ไฟฎ', title: 'ไฟฎๅค' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Fix' });+ await service.tick(graph.goal.id);++ // A policy editor sends its whole (stale) config snapshot back.+ await new GoalModel(serverDB, userId).update(graph.goal.id, {+ config: { maxConcurrentTasks: 2 },+ });++ const after = await service.graph(graph.goal.id);+ expect(after.goal.config?.maxConcurrentTasks).toBe(2);+ expect(after.goal.config?.understanding).toMatchObject({+ assumptions: ['ๅชไฟฎ P0'],+ level: 'medium',+ });+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/create.test.ts b/apps/server/src/services/goal/GoalService/__tests__/create.test.tsnew file mode 100644index 00000000000..99758833a7c--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/create.test.ts@@ -0,0 +1,225 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AcceptanceModel } from '@/database/models/acceptance';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { goalNodes, goals } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { VerifyPlanGeneratorService } from '../../../verify/planGenerator';+import { GoalExplorationPlanner } from '../../explorationPlanner';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ it('supervises every Goal it creates, even when the caller omits the policy', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Supervised by default' });+ expect(graph.goal.config?.supervision).toMatchObject({ enabled: true });+ });++ it('keeps the caller incident cap while forcing supervision on', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { supervision: { enabled: true, maxIncidents: 4 } },+ title: 'Capped supervision',+ });+ expect(graph.goal.config?.supervision).toEqual({ enabled: true, maxIncidents: 4 });+ });++ it('rejects a caller that tries to create an unsupervised Goal', async () => {+ const service = new GoalService(serverDB, userId);+ await expect(+ service.create({ config: { supervision: { enabled: false } }, title: 'No supervision' }),+ ).rejects.toThrow('Supervision is required for every goal and cannot be disabled');+ });++ it('explores after result settlement and dispatches the new graph node through the ordinary Task path', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ title: 'Explore',+ config: { exploration: { instruction: 'Compare evidence', maxExperiments: 3 } },+ });+ const parent = graph.nodes.find((node) => node.kind === 'task')!;+ await serverDB.update(goals).set({ status: 'running' }).where(eq(goals.id, graph.goal.id));+ await serverDB.update(goalNodes).set({ status: 'resolved' }).where(eq(goalNodes.id, parent.id));+ const planner = vi.spyOn(GoalExplorationPlanner.prototype, 'plan').mockResolvedValue({+ action: 'expand',+ parentNodeId: graph.nodes.find((node) => node.kind === 'experiment')!.id,+ title: 'Alternative',+ instruction: 'Improve baseline',+ reason: 'Try a new direction',+ });+ const expanded = await service.tick(graph.goal.id);+ expect(expanded).toMatchObject({ outcome: 'advanced', message: 'Try a new direction' });+ expect(planner).toHaveBeenCalledOnce();+ const created = await service.tick(graph.goal.id);+ expect(created.outcome).toBe('advanced');+ expect(created.nodeId).not.toBe(expanded.nodeId);+ expect((await service.graph(graph.goal.id)).edges).toContainEqual(+ expect.objectContaining({+ sourceNodeId: expanded.nodeId,+ targetNodeId: created.nodeId,+ kind: 'contains',+ }),+ );+ expect(created.taskId).toBeTruthy();+ });++ it('pauses a failed exploration planner without creating a phantom experiment', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ title: 'Explore',+ config: { exploration: { instruction: 'Compare evidence', maxExperiments: 3 } },+ });+ const parent = graph.nodes.find((node) => node.kind === 'task')!;+ await serverDB.update(goals).set({ status: 'running' }).where(eq(goals.id, graph.goal.id));+ await serverDB.update(goalNodes).set({ status: 'resolved' }).where(eq(goalNodes.id, parent.id));+ vi.spyOn(GoalExplorationPlanner.prototype, 'plan').mockRejectedValue(+ new Error('provider unavailable'),+ );+ expect(await service.tick(graph.goal.id)).toMatchObject({ outcome: 'no_progress' });+ const after = await service.graph(graph.goal.id);+ expect(after.goal.status).toBe('paused');+ expect(after.nodes.filter((node) => node.kind === 'task')).toHaveLength(1);+ });++ it('resumes an exhausted exploration only after increasing its cap, preserving explicit user pause', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ title: 'Explore',+ config: { exploration: { instruction: 'Compare evidence', maxExperiments: 1 } },+ });+ const parent = graph.nodes.find((node) => node.kind === 'task')!;+ await serverDB.update(goals).set({ status: 'running' }).where(eq(goals.id, graph.goal.id));+ await serverDB.update(goalNodes).set({ status: 'resolved' }).where(eq(goalNodes.id, parent.id));+ vi.spyOn(GoalExplorationPlanner.prototype, 'plan').mockResolvedValue({+ action: 'expand',+ parentNodeId: parent.id,+ title: 'Alternative',+ instruction: 'Improve baseline',+ reason: 'Still insufficient',+ });+ await service.tick(graph.goal.id);+ expect((await service.setBudget(graph.goal.id, { maxExperiments: 1 })).status).toBe('paused');+ expect((await service.setBudget(graph.goal.id, { maxExperiments: 2 })).status).toBe('running');+ await service.pause(graph.goal.id);+ expect((await service.setBudget(graph.goal.id, { maxExperiments: 3 })).status).toBe('paused');+ });++ it('passes the selected older experiment result into the actual child Task instruction', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ title: 'Text exploration',+ config: { exploration: { instruction: 'Compare alternatives', maxExperiments: 3 } },+ });+ const graphModel = new GoalGraphModel(serverDB, userId);+ const parent = graph.nodes.find((node) => node.kind === 'task')!;+ await serverDB.update(goalNodes).set({ status: 'resolved' }).where(eq(goalNodes.id, parent.id));+ const finding = await graphModel.createNode(graph.goal.id, {+ kind: 'finding',+ title: 'Baseline result',+ description: 'HISTORICAL_EVIDENCE_731: candidate A scored 7.',+ });+ await graphModel.createEdge(graph.goal.id, parent.id, finding!.id, 'produces');+ await graphModel.createNode(graph.goal.id, {+ kind: 'task',+ title: 'Newer alternative',+ status: 'resolved',+ });+ const child = await graphModel.createNode(graph.goal.id, {+ kind: 'task',+ title: 'Revisit baseline',+ description: 'Try changing A',+ });+ await graphModel.createEdge(graph.goal.id, child!.id, parent.id, 'derived_from');+ const created = await service.tick(graph.goal.id);+ const dispatched = await new TaskModel(serverDB, userId).findById(created.taskId!);+ expect(dispatched?.instruction).toContain(parent.id);+ expect(dispatched?.instruction).toContain('HISTORICAL_EVIDENCE_731: candidate A scored 7.');+ expect(dispatched?.instruction).toContain('Try changing A');+ });++ it('persists structured criteria on create and records their ids on the goal config', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ criteria: [+ { description: 'Runs end to end locally', title: 'Local run works' },+ { instruction: 'Check README covers install and run', title: 'Docs are complete' },+ ],+ title: 'Structured goal',+ tasks: ['Only task'],+ });++ const criteriaIds = graph.goal.config?.acceptance?.criteriaIds ?? [];+ expect(criteriaIds).toHaveLength(2);++ const rows = await serverDB.query.verifyCriteria.findMany();+ const byId = new Map(rows.map((row) => [row.id, row]));+ expect(byId.get(criteriaIds[0])?.title).toBe('Local run works');+ expect(byId.get(criteriaIds[1])?.title).toBe('Docs are complete');+ // the how-to-judge instruction landed in a linked document+ expect(byId.get(criteriaIds[1])?.documentId).toBeTruthy();+ });++ it('persists the reviewed goal document verbatim when structured criteria are supplied', async () => {+ const service = new GoalService(serverDB, userId);+ const instruction = 'ๅฐๅๅ ฌไฝ้ชๆๅๅฐๅฏไบคไปๆฐดๅนณ๏ผๆฏๆ PPTใXLSXใWord ็ๅๅปบๅๅฎๅไฟฎๆนใ';+ const graph = await service.create({+ criteria: [{ instruction: 'ๆๅผๅนถ็ผ่พๆ็ปๆไปถ', title: 'ไธ็ฑปๅๅ ฌๆๆกฃ็ซฏๅฐ็ซฏๅฏ็จ' }],+ problemDescription: instruction,+ requirement: instruction,+ tasks: ['Only task'],+ title: 'ๅๅ ฌไฝ้ช',+ });++ const persisted = await service.graph(graph.goal.id);+ expect(persisted.goal.requirement).toBe(instruction);+ expect(persisted.nodes.find((node) => node.kind === 'problem')?.description).toBe(instruction);+ expect(persisted.goal.config?.acceptance?.criteriaIds).toHaveLength(1);+ });++ it('rebinding criteria also updates the dispatched terminal acceptance task', async () => {+ // Editing the standard after the terminal Goal-acceptance Task exists must+ // not leave that Task's Acceptance gating on the stale id list.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ criteria: [{ title: 'Original criterion' }],+ requirement: 'Deliver with evidence',+ title: 'Rebind criteria goal',+ tasks: ['Only task'],+ });++ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'completed');+ await service.tick(graph.goal.id); // synthesize finding+ await service.tick(graph.goal.id); // create acceptance task+ const acceptanceTaskCreated = await service.tick(graph.goal.id); // dispatch it+ expect(acceptanceTaskCreated.taskId).toBeDefined();++ const [replacementId] = await new VerifyPlanGeneratorService(+ serverDB,+ userId,+ ).createCriteriaFromDrafts([+ { onFail: 'manual', required: true, title: 'Replacement criterion', verifierType: 'agent' },+ ]);+ await service.setAcceptanceCriteria(graph.goal.id, [replacementId]);++ const goal = (await service.graph(graph.goal.id)).goal;+ expect(goal.config?.acceptance?.criteriaIds).toEqual([replacementId]);+ const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(+ 'task',+ acceptanceTaskCreated.taskId!,+ );+ expect(acceptance?.config?.verifyCriteriaIds).toEqual([replacementId]);+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/device.test.ts b/apps/server/src/services/goal/GoalService/__tests__/device.test.tsnew file mode 100644index 00000000000..b2038249a9b--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/device.test.ts@@ -0,0 +1,453 @@+// @vitest-environment node+import {+ DEVICE_OFFLINE_RUN_STATUS,+ GOAL_MACHINE_GATE_TITLE,+ QUOTA_LIMITED_RUN_STATUS,+} from '@lobechat/const/goal';+import { eq, sql } from 'drizzle-orm';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { GoalModel } from '@/database/models/goal';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { goals, tasks, taskTopics, topics } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { deviceGateway } from '../../../deviceGateway';+import { TaskRunnerService } from '../../../taskRunner';+import { MAX_QUOTA_RETRIES } from '../../machineRecovery';+import { DEVICE_OFFLINE_GATE_REASON } from '../../recoveryPolicy';+import * as scheduler from '../../scheduler';+import { LocalGoalScheduler } from '../../scheduler/impls';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ describe('a Task that could not reach its device', () => {+ const DEVICE_NOT_FOUND_HEADLINE =+ 'The device this agent is bound to is no longer registered with the connection service. Reconnect the device, or bind this agent to another online device.';+ // A workspace goal whose agent runs on its owner's personal device: the+ // route the dispatch recorded names the personal pool, not the goal's.+ const route = { deviceId: 'device-laptop', userId: 'device-owner' };++ const setup = async (title: string) => {+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3 } },+ title,+ tasks: ['Reproduce on the bound device'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });++ const operationModel = new AgentOperationModel(serverDB, userId);+ await operationModel.recordStart({ operationId: 'op-dispatch', taskId: created.taskId });+ await operationModel.recordCompletion('op-dispatch', {+ completedAt: new Date(),+ completionReason: 'error',+ error: { deviceRoute: route, message: DEVICE_NOT_FOUND_HEADLINE },+ status: 'error',+ });+ vi.spyOn(TaskTopicModel.prototype, 'findWithHandoff').mockResolvedValue([+ { operationId: 'op-dispatch' } as never,+ ]);++ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: DEVICE_NOT_FOUND_HEADLINE,+ });+ return { created, graph, service, taskModel };+ };++ it('waits for the device instead of asking a person', async () => {+ const listSpy = vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');+ const { created, graph, service } = await setup('Device went to sleep');++ const waiting = await service.tick(graph.goal.id);++ expect(listSpy).toHaveBeenCalledWith('device-owner', undefined);+ expect(waiting).toMatchObject({+ message: expect.stringContaining('waiting for its device to reconnect'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ expect(runSpy).not.toHaveBeenCalled();+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ });++ it('keeps waiting while only some other device is online', async () => {+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([+ { deviceId: 'device-desktop' } as never,+ ]);+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');+ const { graph, service } = await setup('Another device is online');++ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({ outcome: 'waiting_external' });+ expect(runSpy).not.toHaveBeenCalled();+ });++ it('retries on its own once its device is back online', async () => {+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([+ { deviceId: 'device-laptop' } as never,+ ]);+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-after-reconnect', success: true } as never);+ const { created, graph, service } = await setup('Device reconnected');++ const retried = await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledWith(+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),+ );+ expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ });++ it('keeps waiting when the retry itself cannot reach the device', async () => {+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([+ { deviceId: 'device-laptop' } as never,+ ]);+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockRejectedValue(+ new Error('DEVICE_OFFLINE (HTTP 503)'),+ );+ const { created, graph, service, taskModel } = await setup('Device flapping');++ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ expect(await taskModel.findById(created.taskId!)).toMatchObject({+ error: 'DEVICE_OFFLINE (HTTP 503)',+ status: 'paused',+ });+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ });++ it('retries on the offline schedule even while the device still looks offline', async () => {+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-on-schedule', success: true } as never);+ const { created, graph, service } = await setup('Device gone past the first backoff');+ await serverDB+ .update(tasks)+ .set({ updatedAt: new Date(Date.now() - 31 * 60 * 1000) })+ .where(eq(tasks.id, created.taskId!));++ const retried = await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledWith(+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),+ );+ expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ });++ it('waits out the backoff without presence on a deployment without a device gateway', async () => {+ const listSpy = vi.spyOn(deviceGateway, 'queryDeviceList');+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');+ const { created, graph, service } = await setup('Self-hosted without devices');+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(false);++ const waiting = await service.tick(graph.goal.id);++ expect(listSpy).not.toHaveBeenCalled();+ expect(runSpy).not.toHaveBeenCalled();+ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ });+ });++ describe('a Task its usage window refused', () => {+ const SESSION_LIMIT = "You've hit your session limit ยท resets 4:30am";++ const setup = async (title: string, resetsAtMs: number) => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3 } },+ title,+ tasks: ['Run on the external Agent'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });++ const operationModel = new AgentOperationModel(serverDB, userId);+ await operationModel.recordStart({ operationId: 'op-quota', taskId: created.taskId });+ await operationModel.recordCompletion('op-quota', {+ completedAt: new Date(),+ completionReason: 'error',+ error: {+ body: {+ code: 'rate_limit',+ rateLimitInfo: { resetsAt: Math.floor(resetsAtMs / 1000), status: 'rejected' },+ },+ category: 'quota',+ message: SESSION_LIMIT,+ },+ status: 'error',+ });+ vi.spyOn(TaskTopicModel.prototype, 'findWithHandoff').mockResolvedValue([+ { operationId: 'op-quota' } as never,+ ]);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: SESSION_LIMIT });+ return { created, graph, service };+ };++ it('waits for the reset instead of asking a person', async () => {+ const schedule = vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');+ const resetsAt = Date.now() + 2 * 60 * 60 * 1000;+ const { created, graph, service } = await setup('Session limit', resetsAt);++ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({+ message: expect.stringContaining('usage window to reset'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ expect(schedule).toHaveBeenLastCalledWith(+ expect.objectContaining({ goalId: graph.goal.id, trigger: 'wake' }),+ );+ expect(schedule.mock.lastCall![0].delay).toBeGreaterThanOrEqual(2 * 60 * 60);++ // More ticks before the reset (the sweep, Task events) queue no more wakes,+ // and a policy edit from a stale snapshot does not drop the armed receipt.+ await service.tick(graph.goal.id);+ await new GoalModel(serverDB, userId).update(graph.goal.id, {+ config: { recovery: { maxAttemptsPerTask: 3 } },+ });+ expect((await service.graph(graph.goal.id)).goal.config?.quotaRetryWakeAt).toBeDefined();+ await service.tick(graph.goal.id);+ expect(schedule.mock.calls.filter(([params]) => params.trigger === 'wake')).toHaveLength(1);+ expect(runSpy).not.toHaveBeenCalled();+ const after = await service.graph(graph.goal.id);+ expect(after.decisions).toHaveLength(0);+ expect(after.goal.config?.supervisorState?.incidents ?? []).toHaveLength(0);+ });++ // The refusal's text names the limit, so its runs are uncharged and the+ // attempt budget cannot end a window that keeps refusing. The uncharged+ // quota schedule does: once spent, a person is asked instead of another wait.+ it('stops waiting once the uncharged usage-limit retries are spent', async () => {+ const schedule = vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');+ const { created, graph, service } = await setup(+ 'Session limit keeps refusing',+ Date.now() + 2 * 60 * 60 * 1000,+ );+ for (let seq = 1; seq <= MAX_QUOTA_RETRIES + 1; seq++) {+ const topicId = `tpc_quota_${seq}`;+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB.insert(taskTopics).values({+ seq,+ status: QUOTA_LIMITED_RUN_STATUS,+ taskId: created.taskId!,+ topicId,+ updatedAt: new Date(Date.now() - (MAX_QUOTA_RETRIES + 1 - seq) * 60 * 1000),+ userId,+ });+ }++ const gated = await service.tick(graph.goal.id);++ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ expect(runSpy).not.toHaveBeenCalled();+ expect(schedule.mock.calls.filter(([params]) => params.trigger === 'wake')).toHaveLength(0);+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(1);+ });++ it('retries through ordinary recovery once the window has reset', async () => {+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-after-reset', success: true } as never);+ const { created, graph, service } = await setup(+ 'Session limit over',+ Date.now() - 2 * 60 * 1000,+ );++ const retried = await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledWith(+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),+ );+ expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ });++ it('does not start the retry once the Goal deadline has passed', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');+ const { graph, service } = await setup(+ 'Reset after the deadline',+ Date.now() - 2 * 60 * 1000,+ );+ await serverDB+ .update(goals)+ .set({+ config: sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{schedule}', ${JSON.stringify({ deadline: new Date(Date.now() - 60_000).toISOString() })}::jsonb)`,+ })+ .where(eq(goals.id, graph.goal.id));++ await service.tick(graph.goal.id);++ expect(runSpy).not.toHaveBeenCalled();+ });+ });+});++/**+ * Most real gates were machine problems pushed onto a person: a usage limit that+ * reset on its own hours later, a working directory missing on the device. These+ * pin that the coordinator waits out the first and asks about the second as a+ * machine gate rather than a judgment.+ */+describe('GoalService machine failures', () => {+ const MINUTE = 60 * 1000;+ const SESSION_LIMIT = "You've hit your session limit ยท resets 4:30am (Asia/Shanghai)";+ // 03:51 in Shanghai, a minute after the run hit the limit.+ const FAILED_AT = new Date('2026-10-05T19:50:01.000Z');++ const setup = async (title: string) => {+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-retry', success: true } as never);+ const scheduleSpy = vi+ .spyOn(LocalGoalScheduler.prototype, 'scheduleAdvance')+ .mockResolvedValue('scheduled');+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ // One attempt: a limited run that spent it would gate the retry.+ config: { recovery: { maxAttemptsPerTask: 1 } },+ tasks: ['Run on Claude Code'],+ title,+ });+ const created = await service.tick(graph.goal.id);+ runSpy.mockClear();+ return { created, graph, runSpy, scheduleSpy, service, taskModel };+ };++ const failRun = async (taskId: string, status: string, error: string, at: Date) => {+ const topicId = `tpc_machine_${taskId}`;+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB+ .insert(taskTopics)+ .values({ seq: 1, status, taskId, topicId, updatedAt: at, userId });+ const taskModel = new TaskModel(serverDB, userId);+ await taskModel.update(taskId, { totalTopics: 1 });+ await taskModel.updateStatus(taskId, 'paused', { error });+ await serverDB.update(tasks).set({ updatedAt: at }).where(eq(tasks.id, taskId));+ };++ afterEach(() => {+ vi.useRealTimers();+ });++ it('waits for a usage limit to reset, then retries without charging the attempt', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });+ vi.setSystemTime(new Date(FAILED_AT.getTime() + MINUTE));+ const { created, graph, runSpy, scheduleSpy, service } = await setup('Session limit');+ await failRun(created.taskId!, QUOTA_LIMITED_RUN_STATUS, SESSION_LIMIT, FAILED_AT);++ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({+ message: expect.stringContaining('retrying at 2026-10-05T20:31:00.000Z'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ expect(runSpy).not.toHaveBeenCalled();+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ // The tick that saw the failure books the advance for the reset.+ expect(scheduleSpy).toHaveBeenCalledWith(+ expect.objectContaining({ delay: 39 * 60 + 59, goalId: graph.goal.id, trigger: 'wake' }),+ );++ vi.setSystemTime(new Date('2026-10-05T20:33:00.000Z'));+ const retried = await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledWith(+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),+ );+ expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ });++ it('opens a machine gate that names the missing working directory', async () => {+ const { created, graph, runSpy, service } = await setup('Missing working directory');+ const error = 'Working directory does not exist: /Users/user/CodeProjects/LobeHub/lobehub';+ await failRun(created.taskId!, 'failed', error, new Date());++ const gated = await service.tick(graph.goal.id);++ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ expect(runSpy).not.toHaveBeenCalled();+ const after = await service.graph(graph.goal.id);+ const gate = after.nodes.find((node) => node.kind === 'decision')!;+ expect(gate.title).toBe(GOAL_MACHINE_GATE_TITLE);+ const [decision] = after.decisions;+ expect(decision.question).toBe(+ 'Setup problem: Working directory does not exist: /Users/user/CodeProjects/LobeHub/lobehub. Create /Users/user/CodeProjects/LobeHub/lobehub on the device the agent runs on, or point the agent at a working directory that exists there. Fix it, then retry or retire this task node?',+ );+ expect(decision.options).toEqual([+ { id: 'retry', label: 'I fixed it โ retry' },+ { id: 'retire', label: 'Retire task' },+ ]);+ });++ it('keeps a judgment failure on the ordinary gate', async () => {+ const { created, graph, service } = await setup('Unjudgeable delivery');+ await failRun(+ created.taskId!,+ 'failed',+ 'Acceptance review could not run; the delivery passed its verifiers but was never reviewed.',+ new Date(),+ );++ await service.tick(graph.goal.id);++ const gate = (await service.graph(graph.goal.id)).nodes.find(+ (node) => node.kind === 'decision',+ )!;+ expect(gate.title).toBe('Choose how to recover failed task');+ });++ it('asks about a device that stayed offline with a machine gate', async () => {+ const { created, graph, service, taskModel } = await setup('Device never came back');+ await taskModel.update(created.taskId!, { totalTopics: 7 });+ for (let seq = 1; seq <= 7; seq++) {+ const topicId = `tpc_machine_offline_${seq}`;+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB.insert(taskTopics).values({+ seq,+ status: DEVICE_OFFLINE_RUN_STATUS,+ taskId: created.taskId!,+ topicId,+ updatedAt: new Date(Date.now() - (17 - seq) * 60 * MINUTE),+ userId,+ });+ }+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });++ await service.tick(graph.goal.id);++ const gate = (await service.graph(graph.goal.id)).nodes.find(+ (node) => node.kind === 'decision',+ )!;+ expect(gate).toMatchObject({+ description: DEVICE_OFFLINE_GATE_REASON,+ title: GOAL_MACHINE_GATE_TITLE,+ });+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/deviceLost.test.ts b/apps/server/src/services/goal/GoalService/__tests__/deviceLost.test.tsnew file mode 100644index 00000000000..fd4f1f7998d--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/deviceLost.test.ts@@ -0,0 +1,263 @@+// @vitest-environment node+import { DEVICE_OFFLINE_RUN_STATUS } from '@lobechat/const/goal';+import type { ChatTopicMetadata } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { agentOperations, taskTopics, topics } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { deviceGateway } from '../../../deviceGateway';+import { TaskRunnerService } from '../../../taskRunner';+import { VERIFICATION_FAILED_ERROR } from '../../decideNextMove';+import { DEVICE_OFFLINE_GATE_REASON } from '../../recoveryPolicy';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ describe('a Task whose runs its device lost', () => {+ const MINUTE = 60 * 1000;+ const HOUR = 60 * MINUTE;++ const setup = async (title: string, maxAttemptsPerTask: number) => {+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-retry', success: true } as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask, operationLeaseTimeoutMs: 60_000 } },+ title,+ tasks: ['Run on the laptop'],+ });+ const created = await service.tick(graph.goal.id);+ runSpy.mockClear();+ return { created, graph, runSpy, service, taskModel };+ };++ const addRun = async (+ taskId: string,+ seq: number,+ status: string,+ options: { metadata?: ChatTopicMetadata; operationId?: string; updatedAt?: Date } = {},+ ) => {+ const topicId = `tpc_offline_${seq}`;+ await serverDB.insert(topics).values({ id: topicId, metadata: options.metadata, userId });+ await serverDB.insert(taskTopics).values({+ operationId: options.operationId,+ seq,+ status,+ taskId,+ topicId,+ userId,+ ...(options.updatedAt && { updatedAt: options.updatedAt }),+ });+ return topicId;+ };++ /** `count` consecutive offline runs, the newest `sinceLast` ago. */+ const addOfflineRuns = async (taskId: string, count: number, sinceLast: number) => {+ for (let seq = 1; seq <= count; seq++) {+ await addRun(taskId, seq, DEVICE_OFFLINE_RUN_STATUS, {+ updatedAt: new Date(Date.now() - sinceLast - (count - seq) * HOUR),+ });+ }+ };++ const decisionReasons = async (service: GoalService, goalId: string) =>+ (await service.graph(goalId)).nodes+ .filter((node) => node.kind === 'decision')+ .map((node) => node.description);++ it('does not charge a run lost while its device was offline to the attempt budget', async () => {+ const { created, graph, runSpy, service, taskModel } = await setup(+ 'Laptop went offline mid-run',+ 1,+ );+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'running');+ const operationModel = new AgentOperationModel(serverDB, userId);+ await operationModel.recordStart({ operationId: 'op-lost', taskId: created.taskId });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, 'op-lost'));+ const topicId = await addRun(created.taskId!, 1, 'running', {+ metadata: {+ runningOperation: {+ assistantMessageId: 'msg-lost',+ deviceId: 'device-laptop',+ operationId: 'op-lost',+ },+ },+ operationId: 'op-lost',+ });++ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({+ message: expect.stringContaining('waiting for its device to reconnect'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ expect(runSpy).not.toHaveBeenCalled();+ expect(await decisionReasons(service, graph.goal.id)).toHaveLength(0);+ const [lost] = await new TaskTopicModel(serverDB, userId).findByTaskId(created.taskId!);+ expect(lost.status).toBe(DEVICE_OFFLINE_RUN_STATUS);++ // Once the first backoff has passed, the retry goes out on the budget the+ // lost run did not spend.+ await serverDB+ .update(taskTopics)+ .set({ updatedAt: new Date(Date.now() - 31 * MINUTE) })+ .where(eq(taskTopics.topicId, topicId));+ await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledWith(+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),+ );+ expect(await decisionReasons(service, graph.goal.id)).toHaveLength(0);+ });++ it('still charges a lost run whose device is online when it is reclaimed', async () => {+ const { created, graph, runSpy, service, taskModel } = await setup(+ 'Run died on a connected laptop',+ 1,+ );+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([+ { deviceId: 'device-laptop' } as never,+ ]);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'running');+ const operationModel = new AgentOperationModel(serverDB, userId);+ await operationModel.recordStart({ operationId: 'op-died', taskId: created.taskId });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, 'op-died'));+ await addRun(created.taskId!, 1, 'running', {+ metadata: { boundDeviceId: 'device-laptop' },+ operationId: 'op-died',+ });++ const gated = await service.tick(graph.goal.id);++ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ expect(runSpy).not.toHaveBeenCalled();+ });++ it.each([+ { before: 29 * MINUTE, after: 31 * MINUTE, offlineRuns: 1, schedule: '30min' },+ { before: 59 * MINUTE, after: 61 * MINUTE, offlineRuns: 2, schedule: '1h' },+ { before: 119 * MINUTE, after: 121 * MINUTE, offlineRuns: 3, schedule: '2h' },+ { before: 7 * HOUR + 59 * MINUTE, after: 8 * HOUR + MINUTE, offlineRuns: 5, schedule: '8h' },+ {+ before: 7 * HOUR + 59 * MINUTE,+ after: 8 * HOUR + MINUTE,+ offlineRuns: 6,+ schedule: '8h (capped)',+ },+ ])(+ 'waits $schedule after offline run $offlineRuns before retrying',+ async ({ after, before, offlineRuns }) => {+ const { created, graph, runSpy, service, taskModel } = await setup(+ `Offline backoff ${offlineRuns}`,+ 1,+ );+ await taskModel.update(created.taskId!, { totalTopics: offlineRuns });+ await addOfflineRuns(created.taskId!, offlineRuns, before);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });++ const waiting = await service.tick(graph.goal.id);+ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ expect(runSpy).not.toHaveBeenCalled();++ await serverDB+ .update(taskTopics)+ .set({ updatedAt: new Date(Date.now() - after) })+ .where(eq(taskTopics.topicId, `tpc_offline_${offlineRuns}`));+ await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledWith(+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),+ );+ expect(await decisionReasons(service, graph.goal.id)).toHaveLength(0);+ },+ );++ it('retries at once when presence shows the device back before the backoff ends', async () => {+ const { created, graph, runSpy, service, taskModel } = await setup('Laptop woke up', 1);+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([+ { deviceId: 'device-laptop' } as never,+ ]);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await addRun(created.taskId!, 1, DEVICE_OFFLINE_RUN_STATUS, {+ metadata: { boundDeviceId: 'device-laptop' },+ });+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });++ await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledOnce();+ });++ it('asks a person once every offline retry found the device gone', async () => {+ const { created, graph, runSpy, service, taskModel } = await setup(+ 'Laptop never came back',+ 1,+ );+ await taskModel.update(created.taskId!, { totalTopics: 7 });+ await addOfflineRuns(created.taskId!, 7, 10 * HOUR);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });++ const gated = await service.tick(graph.goal.id);++ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ expect(runSpy).not.toHaveBeenCalled();+ expect(await decisionReasons(service, graph.goal.id)).toEqual([DEVICE_OFFLINE_GATE_REASON]);+ });++ it('keeps charging verification-rejected attempts to the budget', async () => {+ const { created, graph, runSpy, service, taskModel } = await setup(+ 'Rejections still count',+ 2,+ );+ await addRun(created.taskId!, 1, DEVICE_OFFLINE_RUN_STATUS);+ await addRun(created.taskId!, 2, 'completed');+ await taskModel.update(created.taskId!, { totalTopics: 2 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: VERIFICATION_FAILED_ERROR,+ });++ // One offline run and one rejection: only the rejection is charged.+ await service.tick(graph.goal.id);+ expect(runSpy).toHaveBeenCalledOnce();++ await addRun(created.taskId!, 3, 'completed');+ await taskModel.update(created.taskId!, { totalTopics: 3 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: VERIFICATION_FAILED_ERROR,+ });+ runSpy.mockClear();++ const gated = await service.tick(graph.goal.id);++ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ expect(runSpy).not.toHaveBeenCalled();+ expect(await decisionReasons(service, graph.goal.id)).toEqual([+ 'Task attempt budget was exhausted',+ ]);+ });+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/dispatch.test.ts b/apps/server/src/services/goal/GoalService/__tests__/dispatch.test.tsnew file mode 100644index 00000000000..03f2f7f390a--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/dispatch.test.ts@@ -0,0 +1,666 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AcceptanceModel } from '@/database/models/acceptance';+import { TaskModel } from '@/database/models/task';+import { WorkModel } from '@/database/models/work';+import { documents, goals, tasks, taskTopics } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { TaskService } from '../../../task';+import { TaskRunnerService } from '../../../taskRunner';+import {+ LEASE_EXPIRED_ERROR,+ VERIFICATION_ERRORED_ERROR,+ VERIFICATION_FAILED_ERROR,+} from '../../decideNextMove';+import { VERIFY_SETTLE_GRACE_MS } from '../../recoveryPolicy';+import { TaskRecoveryCoordinator } from '../../taskRecoveryCoordinator';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ it.each([+ { action: 'verify', managerEnabled: true },+ { action: 'verify', managerEnabled: false },+ { action: 'tasks', managerEnabled: true },+ ] as const)(+ 'scopes the handoff to manager=$managerEnabled action=$action',+ async ({ action, managerEnabled }) => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const requirement = 'Deliver the original result with independently inspectable evidence';+ const handoff =+ 'Clarify that zero calls means zero additional predictions, not zero LLM use.';+ const graph = await service.create({+ criteria: [{ title: 'Original evidence criterion' }],+ requirement,+ tasks: ['Prepare result'],+ title: 'Handoff',+ });+ const prepared = await service.tick(graph.goal.id);+ await taskModel.updateStatus(prepared.taskId!, 'completed');+ await service.tick(graph.goal.id);+ const originalConfig = (await service.graph(graph.goal.id)).goal.config;+ await serverDB+ .update(goals)+ .set({+ config: {+ ...originalConfig,+ manager: managerEnabled ? {} : undefined,+ managerState: {+ consumed: true,+ readyForAcceptance: true,+ snapshot: 'settled',+ startedAt: new Date().toISOString(),+ submitted: { action, reason: handoff },+ token: 'verified-turn',+ topicId: 'management-topic',+ turns: 1,+ },+ },+ })+ .where(eq(goals.id, graph.goal.id));++ await service.tick(graph.goal.id);+ const finalTask = await service.tick(graph.goal.id);+ const task = await taskModel.findById(finalTask.taskId!);++ if (managerEnabled && action === 'verify') {+ expect(task?.instruction).toContain(handoff);+ expect(task?.instruction).toContain('context only, not acceptance criteria');+ } else {+ expect(task?.instruction).not.toContain(handoff);+ }+ const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(+ 'task',+ finalTask.taskId!,+ );+ expect(acceptance?.requirement).toContain(requirement);+ expect(acceptance?.config?.verifyCriteriaIds).toEqual(+ originalConfig?.acceptance?.criteriaIds,+ );+ expect(acceptance?.config?.verifyCriteriaIds).toHaveLength(1);+ expect((await service.graph(graph.goal.id)).goal.requirement).toBe(requirement);+ },+ );++ it('creates only one responsible task when ticks race on the same task node', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Single owner task'], title: 'Concurrent goal' });++ const results = await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);+ const current = await service.graph(graph.goal.id);+ const taskRows = await serverDB.select().from(tasks);++ expect(results.filter((result) => result.outcome === 'advanced')).toHaveLength(1);+ expect(taskRows).toHaveLength(1);+ expect(current.nodes.find((node) => node.kind === 'task')?.taskId).toBe(taskRows[0].id);+ expect(current.workVersions).toHaveLength(1);+ });++ it('starts the bound Task once when advances race on dispatch', async () => {+ // Overlapping advances (an event hook, a manual nudge, the sweep) both read+ // the task as backlog; without an atomic claim both would call runTask and+ // the user would pay for the same Task twice.+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockImplementation(async ({ taskId }) => ({ taskId }) as never);+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Only run once'], title: 'Raced dispatch' });+ await service.tick(graph.goal.id);++ const results = await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);++ expect(runSpy).toHaveBeenCalledTimes(1);+ expect(results.filter((result) => result.message.startsWith('Started task'))).toHaveLength(1);+ });++ it('retries a failed verification once when advances race on recovery', async () => {+ // The dispatch claim only covers starting a backlog Task; the automatic+ // retry path spawns its own run, so without the same claim two overlapping+ // advances would each pay for an attempt.+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockImplementation(async ({ taskId }) => ({ taskId }) as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3 } },+ title: 'Raced recovery',+ tasks: ['Retry me once'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: 'Delivery did not pass verification.',+ });+ runSpy.mockClear();++ await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);++ expect(runSpy).toHaveBeenCalledTimes(1);+ });++ it.each([LEASE_EXPIRED_ERROR, VERIFICATION_FAILED_ERROR])(+ 'does not dispatch recovery for an overdue goal with %s',+ async (error) => {+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { schedule: { deadline: new Date(Date.now() - 1000).toISOString() } },+ title: `Overdue recovery ${error}`,+ tasks: ['Do not retry'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error });+ runSpy.mockClear();++ const stopped = await service.tick(graph.goal.id);++ expect(runSpy).not.toHaveBeenCalled();+ expect(stopped).toMatchObject({ outcome: 'no_progress' });+ expect(stopped.message).toContain('Deadline passed');+ },+ );++ it.each([+ [LEASE_EXPIRED_ERROR, 'completed'],+ [LEASE_EXPIRED_ERROR, 'failed'],+ [VERIFICATION_ERRORED_ERROR, 'completed'],+ [VERIFICATION_ERRORED_ERROR, 'canceled'],+ ])('does not restart a Task settled during recovery (%s โ %s)', async (error, settledAs) => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ title: `Settled during recovery ${error} ${settledAs}`,+ tasks: ['Do not restart'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error });+ // The advance routed here holding the paused row; a person settled the Task+ // before the claim, which is the row the coordinator now reads.+ const stale = (await taskModel.findById(created.taskId!))!;+ await taskModel.updateStatus(created.taskId!, settledAs, { error: null });+ runSpy.mockClear();++ const recovery = await new TaskRecoveryCoordinator(serverDB, userId).recover({+ goal: (await service.graph(graph.goal.id)).goal,+ task: stale,+ });++ expect(recovery.outcome).toBe('settled');+ expect(runSpy).not.toHaveBeenCalled();+ expect((await taskModel.findById(created.taskId!))?.status).toBe(settledAs);+ });++ it.each([LEASE_EXPIRED_ERROR, VERIFICATION_ERRORED_ERROR])(+ 'does not start a recovery run once the goal is fenced for closing (%s)',+ async (error) => {+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ title: `Fenced recovery ${error}`, tasks: ['Stop'] });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error });+ // The tick decided on a running goal; `close` then paused it under the+ // goal row lock before scanning live runs.+ const decidedOn = (await service.graph(graph.goal.id)).goal;+ const task = (await taskModel.findById(created.taskId!))!;+ await service.pause(graph.goal.id);+ runSpy.mockClear();++ const recovery = await new TaskRecoveryCoordinator(serverDB, userId).recover({+ goal: decidedOn,+ task,+ });++ expect(recovery.outcome).toBe('goal-stopped');+ expect(runSpy).not.toHaveBeenCalled();+ expect((await taskModel.findById(created.taskId!))?.status).toBe('paused');+ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');+ },+ );++ it('does not restart a Task a person paused themselves', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ title: 'Actor paused during recovery',+ tasks: ['Do not restart'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: VERIFICATION_ERRORED_ERROR });+ // A manual round trip keeps the routing error, because the status update replaces+ // it only when a new one is supplied, so the final pause is the person's.+ const taskService = new TaskService(serverDB, userId);+ await taskService.updateStatus({ id: created.taskId!, status: 'failed' }, { userId });+ await taskService.updateStatus({ id: created.taskId!, status: 'paused' }, { userId });+ const stale = (await taskModel.findById(created.taskId!))!;+ runSpy.mockClear();++ const recovery = await new TaskRecoveryCoordinator(serverDB, userId).recover({+ goal: (await service.graph(graph.goal.id)).goal,+ task: stale,+ });++ expect(recovery.outcome).toBe('settled');+ expect(runSpy).not.toHaveBeenCalled();+ expect((await taskModel.findById(created.taskId!))?.status).toBe('paused');+ });++ it('hands back a dispatch claim whose worker died before the run existed', async () => {+ // The claim is taken just before `runTask` creates the topic. If the worker+ // dies in that sliver the task is `running` with no operation to reclaim,+ // and every later advance would report `waiting_external` forever.+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockRejectedValue(new Error('worker died'));+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Start me'], title: 'Orphaned claim' });+ const created = await service.tick(graph.goal.id);++ // The claim survives the crash: put the row back where a dead worker left it.+ await expect(service.tick(graph.goal.id)).rejects.toThrow('worker died');+ await taskModel.updateStatus(created.taskId!, 'running');+ await serverDB+ .update(tasks)+ .set({ updatedAt: new Date(Date.now() - 60 * 60 * 1000) })+ .where(eq(tasks.id, created.taskId!));++ const released = await service.tick(graph.goal.id);++ expect(released.outcome).toBe('advanced');+ expect((await taskModel.findById(created.taskId!))?.status).toBe('backlog');+ runSpy.mockRestore();+ });++ it('does not re-dispatch a delivered Task while verification is still judging', async () => {+ // A verify-bound Task keeps its task `running` with a completed topic until+ // the verify run settles, and that judgment routinely outlives the+ // operation lease. Treating the window as a dead claim released the task+ // back to backlog, and the next advance paid for a ghost attempt that the+ // verify settle path then canceled.+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },+ title: 'Deliveries wait for verification',+ tasks: ['Deliver and wait'],+ });+ const created = await service.tick(graph.goal.id);+ await serverDB.insert(taskTopics).values({+ operationId: 'op-delivered',+ seq: 1,+ status: 'completed',+ taskId: created.taskId!,+ userId,+ });+ await taskModel.updateStatus(created.taskId!, 'running');+ await serverDB+ .update(tasks)+ .set({ updatedAt: new Date(Date.now() - 10 * 60 * 1000) })+ .where(eq(tasks.id, created.taskId!));++ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({+ message: expect.stringContaining('waiting for verification'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ expect((await taskModel.findById(created.taskId!))?.status).toBe('running');+ expect(runSpy).not.toHaveBeenCalled();+ });++ it('reclaims a delivered Task once the verification grace window lapses', async () => {+ // The hold-off above cannot be unconditional: a verify run that died+ // silently would otherwise strand the goal forever, which is exactly the+ // failure mode the sweep exists to break.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },+ title: 'Dead verification is reclaimed',+ tasks: ['Deliver into silence'],+ });+ const created = await service.tick(graph.goal.id);+ await serverDB.insert(taskTopics).values({+ createdAt: new Date(Date.now() - VERIFY_SETTLE_GRACE_MS - 60_000),+ operationId: 'op-delivered-stale',+ seq: 1,+ status: 'completed',+ taskId: created.taskId!,+ userId,+ });+ await taskModel.updateStatus(created.taskId!, 'running');+ await serverDB+ .update(tasks)+ .set({ updatedAt: new Date(Date.now() - 10 * 60 * 1000) })+ .where(eq(tasks.id, created.taskId!));++ const released = await service.tick(graph.goal.id);++ expect(released.outcome).toBe('advanced');+ expect((await taskModel.findById(created.taskId!))?.status).toBe('backlog');+ });++ it('synthesizes the finding from the delivered topic, not a canceled retry', async () => {+ // When verification accepts a delivery, the settle path cancels the ghost+ // retry it superseded โ leaving the canceled, handoff-less topic as the+ // newest row. Reading blindly by seq produced findings titled+ // "Completed: <task>" with no description.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Deliver me'], title: 'Consume the delivery' });+ const created = await service.tick(graph.goal.id);+ await serverDB.insert(taskTopics).values([+ {+ handoff: {+ content: 'Delivered content with the full run summary.',+ summary: 'Delivered summary',+ title: 'Delivered title',+ },+ operationId: 'op-delivered',+ seq: 1,+ status: 'completed',+ taskId: created.taskId!,+ userId,+ },+ {+ operationId: 'op-ghost-retry',+ seq: 2,+ status: 'canceled',+ taskId: created.taskId!,+ userId,+ },+ ]);+ await taskModel.updateStatus(created.taskId!, 'completed');++ await service.tick(graph.goal.id);++ const finding = (await service.graph(graph.goal.id)).nodes.find(+ (node) => node.kind === 'finding',+ );+ expect(finding).toMatchObject({+ description: 'Delivered content with the full run summary.',+ title: 'Delivered title',+ });+ });++ it('links what the task delivered to its node, and skips the task Work itself', async () => {+ // The deliverable used to survive only as a URL inside the finding's prose:+ // the graph recorded that a task finished but not what came out of it.+ 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: 'Harvest deliverables' });+ const created = await service.tick(graph.goal.id);+ await serverDB.insert(taskTopics).values({+ handoff: { summary: 'Delivered', title: 'Delivered title' },+ operationId: 'op-delivered',+ seq: 1,+ status: 'completed',+ taskId: created.taskId!,+ userId,+ });+ await workModel.registerExternal({+ changeType: 'created',+ identifier: 'ENG-7',+ resourceId: 'lobehub/lobehub#7',+ resourceType: 'github_issue',+ rootOperationId: 'op-delivered',+ title: 'The delivered issue',+ toolIdentifier: 'lobe-github',+ toolName: 'createIssue',+ });+ await taskModel.updateStatus(created.taskId!, 'completed');++ await service.tick(graph.goal.id);++ const snapshot = await service.graph(graph.goal.id);+ const linked = snapshot.workVersions.filter((link) => link.nodeId === created.nodeId);+ expect(linked.some((link) => link.work?.title === 'The delivered issue')).toBe(true);+ // The responsible task's own Work is still linked โ it is the execution+ // container, and the client is what filters it out of the deliverable list.+ expect(linked.some((link) => link.work?.type === 'task')).toBe(true);+ });++ it('re-settling a task does not duplicate its deliverable links', async () => {+ 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: 'Idempotent harvest' });+ const created = await service.tick(graph.goal.id);+ await serverDB.insert(taskTopics).values({+ handoff: { summary: 'Delivered', title: 'Delivered title' },+ operationId: 'op-delivered',+ seq: 1,+ status: 'completed',+ taskId: created.taskId!,+ userId,+ });+ await workModel.registerExternal({+ changeType: 'created',+ resourceId: 'lobehub/lobehub#8',+ resourceType: 'github_issue',+ rootOperationId: 'op-delivered',+ title: 'Delivered once',+ toolIdentifier: 'lobe-github',+ toolName: 'createIssue',+ });+ await taskModel.updateStatus(created.taskId!, 'completed');++ await service.tick(graph.goal.id);+ await service.tick(graph.goal.id);++ const snapshot = await service.graph(graph.goal.id);+ const delivered = snapshot.workVersions.filter(+ (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 () => {+ // The same shape a moment after the claim is just a run about to start.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockRejectedValue(new Error('worker died'));+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Start me'], title: 'Fresh claim' });+ const created = await service.tick(graph.goal.id);+ await expect(service.tick(graph.goal.id)).rejects.toThrow('worker died');+ await taskModel.updateStatus(created.taskId!, 'running');++ const result = await service.tick(graph.goal.id);++ expect(result.outcome).toBe('waiting_external');+ expect((await taskModel.findById(created.taskId!))?.status).toBe('running');+ });++ it('only selects Tasks whose explicit dependencies are resolved', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Dependency-aware goal' });+ const prerequisite = await service.addNode(graph.goal.id, {+ kind: 'task',+ priority: 0,+ title: 'Collect evidence',+ });+ const dependent = await service.addNode(graph.goal.id, {+ kind: 'task',+ priority: 10,+ title: 'Train from evidence',+ });+ await service.addEdge(graph.goal.id, dependent.id, prerequisite.id, 'depends_on');++ const first = await service.tick(graph.goal.id);+ expect(first).toMatchObject({ nodeId: prerequisite.id, outcome: 'advanced' });++ const taskModel = new TaskModel(serverDB, userId);+ await taskModel.updateStatus(first.taskId!, 'completed');+ await service.tick(graph.goal.id);++ const next = await service.tick(graph.goal.id);+ expect(next).toMatchObject({ nodeId: dependent.id, outcome: 'advanced' });+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/editing.test.ts b/apps/server/src/services/goal/GoalService/__tests__/editing.test.tsnew file mode 100644index 00000000000..1ae109bf253--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/editing.test.ts@@ -0,0 +1,383 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { GoalModel } from '@/database/models/goal';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { agents, goals, taskTopics, topics } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { TaskService } from '../../../task';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ it('reopens a goal its round budget stopped when the budget is raised', async () => {+ // `tick` refuses to move a paused goal, so without this the queued advance+ // returns straight away and the user has to find Resume as a second gesture.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ maxRounds: 1,+ title: 'Budget stopped',+ tasks: ['Costs a round'],+ });+ const created = await service.tick(graph.goal.id);+ await serverDB.insert(topics).values({ id: 'tpc_budget', userId });+ await serverDB+ .insert(taskTopics)+ .values({ seq: 1, taskId: created.taskId!, topicId: 'tpc_budget', userId });++ const stopped = await service.tick(graph.goal.id);+ expect(stopped.outcome).toBe('no_progress');+ expect(stopped.message).toContain('Round budget reached');+ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');++ const raised = await service.setBudget(graph.goal.id, { maxRounds: 5 });++ expect(raised?.status).not.toBe('paused');+ });++ describe('limits a goal was created with', () => {+ // A goal its main Agent paused for running out of turns: resuming it alone+ // pauses it again, which is what pushed agents into creating a copy of it.+ const turnSpentGoal = async (service: GoalService) => {+ const graph = await service.create({+ tasks: ['Keep working'],+ title: 'Out of main Agent turns',+ });+ const current = (await service.graph(graph.goal.id)).goal;+ await serverDB+ .update(goals)+ .set({+ config: {+ ...current.config,+ manager: { maxTurns: 2 },+ managerState: { turns: 2 } as never,+ },+ status: 'paused',+ })+ .where(eq(goals.id, graph.goal.id));+ return graph.goal.id;+ };++ it('resumes a goal its main Agent paused once the turn cap is raised', async () => {+ const service = new GoalService(serverDB, userId);+ const goalId = await turnSpentGoal(service);++ const raised = await service.setBudget(goalId, { maxManagerTurns: 20 });++ expect(raised.config?.manager?.maxTurns).toBe(20);+ expect(raised.status).not.toBe('paused');+ });++ it('keeps a goal paused when the raised cap is still spent', async () => {+ const service = new GoalService(serverDB, userId);+ const goalId = await turnSpentGoal(service);++ expect((await service.setBudget(goalId, { maxManagerTurns: 2 })).status).toBe('paused');+ });++ it('edits the execution limits without dropping the rest of the config', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3, maxStepsPerRun: 200 } },+ tasks: ['Run'],+ title: 'Editable limits',+ });++ const updated = await service.setBudget(graph.goal.id, {+ maxAttemptsPerTask: 5,+ maxConcurrentTasks: 1,+ maxStepsPerRun: null,+ });++ expect(updated.config?.maxConcurrentTasks).toBe(1);+ expect(updated.config?.recovery).toMatchObject({+ maxAttemptsPerTask: 5,+ maxStepsPerRun: null,+ });+ });++ it('rejects a turn cap for a goal without a main Agent', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Run'], title: 'No main Agent' });++ await expect(service.setBudget(graph.goal.id, { maxManagerTurns: 20 })).rejects.toThrow(+ 'Only a Goal with a main Agent has a turn budget',+ );+ });+ });++ it('ships the spend the budget is enforced against with the graph', async () => {+ // The header renders `spent / cap` as one fraction, so the number it shows+ // has to be the number the coordinator will stop on โ not the goal list's+ // subtree roll-up, which counts Tasks the graph's Tasks spawned.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ maxTotalCost: 10,+ tasks: ['Costs money'],+ title: 'Spend',+ });+ const created = await service.tick(graph.goal.id);++ await serverDB+ .insert(topics)+ .values({ id: 'tpc_spend_1', totalCost: 6.4, totalTokens: 1200, userId });+ await serverDB+ .insert(taskTopics)+ .values({ seq: 1, taskId: created.taskId!, topicId: 'tpc_spend_1', userId });+ // A run that has not settled is a round with no cost yet.+ await serverDB.insert(topics).values({ id: 'tpc_spend_2', userId });+ await serverDB+ .insert(taskTopics)+ .values({ seq: 2, taskId: created.taskId!, topicId: 'tpc_spend_2', userId });++ const { spend } = await service.graph(graph.goal.id);++ expect(spend).toMatchObject({ runs: 2, totalCost: 6.4, totalTokens: 1200 });+ // The cost panel lists WHERE the money went, so the same read carries the+ // per-Task split rather than only the total the budget is checked against.+ expect(spend?.byTask).toEqual([+ {+ runs: 2,+ taskId: created.taskId!,+ totalCost: 6.4,+ totalInputTokens: 0,+ totalOutputTokens: 0,+ totalTokens: 1200,+ },+ ]);+ });++ it('keeps an existing deadline when only the cost cap is edited', async () => {+ // The budget panel sends one dimension at a time; an omitted deadline used+ // to be written back as null, silently dropping a calendar budget someone+ // set from a click that only meant to raise the dollars.+ const service = new GoalService(serverDB, userId);+ const deadline = new Date(Date.now() + 3_600_000).toISOString();+ const graph = await service.create({+ config: { schedule: { deadline } },+ tasks: ['Bounded'],+ title: 'Deadline keeper',+ });++ const updated = await service.setBudget(graph.goal.id, { maxTotalCost: 25 });++ expect(updated?.config?.schedule?.deadline).toBe(deadline);+ expect(Number(updated?.maxTotalCost)).toBe(25);+ });++ it('leaves the round cap alone when only the cost cap is edited', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ maxRounds: 7,+ tasks: ['Bounded'],+ title: 'Round keeper',+ });++ const updated = await service.setBudget(graph.goal.id, { maxTotalCost: 25 });++ expect(updated?.maxRounds).toBe(7);+ });++ it('edits the standing requirement in place', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ requirement: 'ๅ็้ชๆถ',+ tasks: ['A'],+ title: 'Editable',+ });++ const updated = await service.updateRequirement(graph.goal.id, 'ๆน่ฟ็้ชๆถๆ ๅ');++ expect(updated.requirement).toBe('ๆน่ฟ็้ชๆถๆ ๅ');+ expect((await service.graph(graph.goal.id)).goal.requirement).toBe('ๆน่ฟ็้ชๆถๆ ๅ');+ await expect(service.updateRequirement('goal_missing', 'x')).rejects.toThrow();+ });++ it('names the agent each dispatched task node is assigned to', async () => {+ await serverDB.insert(agents).values([{ id: 'agt_exec', slug: 'agt-exec', userId }]);+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ agentId: 'agt_exec',+ tasks: ['Dispatched', 'Not yet'],+ title: 'Who is on it',+ });+ const created = await service.tick(graph.goal.id);++ const read = await service.graph(graph.goal.id);+ const dispatched = read.nodes.find((node) => node.taskId === created.taskId)!;++ // Only a node with a Task row has an assignee; the undispatched one has none.+ expect(read.assignees).toEqual({ [dispatched.id]: 'agt_exec' });+ });++ it('hands the goal and its unfinished tasks to a new agent', async () => {+ await serverDB.insert(agents).values([+ { id: 'agt_old', slug: 'agt-old', userId },+ { id: 'agt_new', slug: 'agt-new', userId },+ ]);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ agentId: 'agt_old',+ tasks: ['Only task'],+ title: 'Handover',+ });+ const created = await service.tick(graph.goal.id);+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_old');++ const handed = await service.setAgent(graph.goal.id, 'agt_new');++ expect(handed.goal.agentId).toBe('agt_new');+ expect(handed.reassignedTaskIds).toEqual([created.taskId]);+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_new');++ // A finished task keeps the agent that did the work, and `goalOnly` limits+ // the change to future coordinator-created tasks.+ await taskModel.updateStatus(created.taskId!, 'completed');+ const back = await service.setAgent(graph.goal.id, 'agt_old');+ expect(back.reassignedTaskIds).toEqual([]);+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_new');++ await expect(service.setAgent(graph.goal.id, 'agt_missing')).rejects.toThrow();+ });++ it('falls back to the goal agent when the dedicated executor was deleted', async () => {+ await serverDB.insert(agents).values([+ { id: 'agt_lead_fallback', slug: 'agt-lead-fallback', userId },+ { id: 'agt_gone_executor', slug: 'agt-gone-executor', userId },+ ]);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ agentId: 'agt_lead_fallback',+ config: { taskAgentId: 'agt_gone_executor' },+ tasks: ['Only task'],+ title: 'Executor deleted',+ });+ await serverDB.delete(agents).where(eq(agents.id, 'agt_gone_executor'));++ const created = await service.tick(graph.goal.id);++ expect(created.taskId).toBeTruthy();+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_lead_fallback');+ });++ it('writes only the executor slot, so a concurrent policy edit survives', async () => {+ await serverDB.insert(agents).values([+ { id: 'agt_policy_lead', slug: 'agt-policy-lead', userId },+ { id: 'agt_policy_worker', slug: 'agt-policy-worker', userId },+ ]);+ const service = new GoalService(serverDB, userId);+ const model = new GoalModel(serverDB, userId);+ const graph = await service.create({ agentId: 'agt_policy_lead', title: 'Policy race' });+ // setTaskAgent reads the row, then a budget edit lands before it writes.+ const stale = (await model.findById(graph.goal.id))!;+ await model.update(graph.goal.id, { config: { ...stale.config, maxConcurrentTasks: 5 } });+ // `findById` is an instance arrow property, so spy on the service's own model.+ const serviceModel = (service as unknown as { goalModel: GoalModel }).goalModel;+ vi.spyOn(serviceModel, 'findById').mockResolvedValueOnce(stale);++ const result = await service.setTaskAgent(graph.goal.id, 'agt_policy_worker');++ expect(result.goal.config?.taskAgentId).toBe('agt_policy_worker');+ expect(result.goal.config?.maxConcurrentTasks).toBe(5);+ });++ it('moves supervision without moving the tasks a dedicated executor holds', async () => {+ await serverDB.insert(agents).values([+ { id: 'agt_supervisor', slug: 'agt-supervisor', userId },+ { id: 'agt_executor', slug: 'agt-executor', userId },+ { id: 'agt_next_supervisor', slug: 'agt-next-supervisor', userId },+ ]);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ agentId: 'agt_supervisor',+ config: { taskAgentId: 'agt_executor' },+ tasks: ['Only task'],+ title: 'Split roles',+ });+ expect(graph.goal.agentId).toBe('agt_supervisor');+ const created = await service.tick(graph.goal.id);+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_executor');++ const handed = await service.setAgent(graph.goal.id, 'agt_next_supervisor');++ expect(handed.goal.agentId).toBe('agt_next_supervisor');+ expect(handed.goal.config?.taskAgentId).toBe('agt_executor');+ expect(handed.reassignedTaskIds).toEqual([]);+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_executor');+ });++ it('routes tasks to a dedicated executor and back to the goal agent', async () => {+ await serverDB.insert(agents).values([+ { id: 'agt_owner', slug: 'agt-owner', userId },+ { id: 'agt_worker', slug: 'agt-worker', userId },+ ]);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ agentId: 'agt_owner',+ tasks: ['Only task'],+ title: 'Delegated',+ });+ const created = await service.tick(graph.goal.id);+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_owner');++ const delegated = await service.setTaskAgent(graph.goal.id, 'agt_worker');+ expect(delegated.goal.agentId).toBe('agt_owner');+ expect(delegated.goal.config?.taskAgentId).toBe('agt_worker');+ expect(delegated.reassignedTaskIds).toEqual([created.taskId]);+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_worker');++ // Naming the goal agent clears the slot rather than duplicating it.+ const back = await service.setTaskAgent(graph.goal.id, 'agt_owner');+ expect(back.goal.config?.taskAgentId).toBeUndefined();+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_owner');++ await expect(service.setTaskAgent(graph.goal.id, 'agt_missing')).rejects.toThrow();+ });++ it('restarts unfinished tasks under a new agent and cancels the stale runs they hold', async () => {+ const cancelSpy = vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();+ await serverDB.insert(agents).values({ id: 'agt_restart', slug: 'agt-restart', userId });+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Stuck task'], title: 'Restartable' });+ const created = await service.tick(graph.goal.id);+ await serverDB.insert(topics).values({ id: 'tpc_restart', userId });+ await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_restart', { seq: 1 });+ await new TaskTopicModel(serverDB, userId).updateStatus(+ created.taskId!,+ 'tpc_restart',+ 'running',+ );+ await taskModel.update(created.taskId!, { error: 'lease expired', status: 'running' });++ const result = await service.restart(graph.goal.id, { agentId: 'agt_restart' });++ expect(cancelSpy).toHaveBeenCalledWith('tpc_restart');+ expect(result.goal.agentId).toBe('agt_restart');+ expect(result.restartedTaskIds).toEqual([created.taskId]);+ expect(await taskModel.findById(created.taskId!)).toMatchObject({+ assigneeAgentId: 'agt_restart',+ error: null,+ status: 'backlog',+ });++ // "Start over" on a parked goal must begin ticking again without a second+ // Resume gesture.+ await service.pause(graph.goal.id);+ const resumed = await service.restart(graph.goal.id);+ expect(resumed.goal.status).not.toBe('paused');+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts b/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.tsnew file mode 100644index 00000000000..64dce7230cd--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts@@ -0,0 +1,578 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { agents, goalEvents, goals, tasks, topics, users, workspaces } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { AiAgentService } from '@/server/services/aiAgent';++import { TaskService } from '../../../task';+import { TaskRunnerService } from '../../../taskRunner';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ it('closes a goal by hand, stops its live runs and stops the coordinator', async () => {+ const cancelSpy = vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['First', 'Second'], title: 'Closable' });+ const created = await service.tick(graph.goal.id);+ await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });+ await serverDB.insert(topics).values({ id: 'tpc_close', userId });+ await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_close', { seq: 1 });+ await new TaskTopicModel(serverDB, userId).updateStatus(+ created.taskId!,+ 'tpc_close',+ 'running',+ );++ const closed = await service.close(graph.goal.id, 'canceled');++ expect(closed.status).toBe('canceled');+ expect(cancelSpy).toHaveBeenCalledWith('tpc_close');+ // Back to backlog, not parked on a person, so a reopen runs it again.+ expect((await new TaskModel(serverDB, userId).findById(created.taskId!))?.status).toBe(+ 'backlog',+ );+ expect(await service.tick(graph.goal.id)).toMatchObject({ outcome: 'failed' });+ const [closeEvent] = await serverDB+ .select()+ .from(goalEvents)+ .where(eq(goalEvents.reason, 'canceled by user'));+ // Filed under the person, not the coordinator.+ expect(closeEvent).toMatchObject({ actorId: userId, eventType: 'rejected' });++ // A closed goal reopens through the ordinary resume.+ expect((await service.resume(graph.goal.id)).status).toBe('running');+ expect((await service.close(graph.goal.id, 'achieved')).status).toBe('achieved');+ });++ it('fences new dispatch before interrupting the runs of a goal being closed', async () => {+ // A tick overlapping the close must not claim another Task while the scan+ // and cancellation are under way, so the goal stops reading `running` first.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Runs'], title: 'Fenced' });+ const created = await service.tick(graph.goal.id);+ await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });+ await serverDB.insert(topics).values({ id: 'tpc_fence', userId });+ await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_fence', { seq: 1 });+ await new TaskTopicModel(serverDB, userId).updateStatus(+ created.taskId!,+ 'tpc_fence',+ 'running',+ );+ const statusDuringCancel: string[] = [];+ vi.spyOn(TaskService.prototype, 'cancelTopic').mockImplementation(async () => {+ const goal = await new GoalModel(serverDB, userId).findById(graph.goal.id);+ statusDuringCancel.push(goal!.status);+ });++ await service.close(graph.goal.id, 'canceled');++ expect(statusDuringCancel).toEqual(['paused']);+ });++ it('refuses to close while a claimed run is still starting, so it can be stopped with confirmation', async () => {+ // `dispatchWork` marks the Task running before `runTask` records the topic,+ // so the close scan finds no run to cancel โ and a run nobody recorded+ // cannot be interrupted with confirmation. The close waits for it instead.+ const cancelSpy = vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Starting'], title: 'Claimed, not recorded' });+ const created = await service.tick(graph.goal.id);+ await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });++ await expect(service.close(graph.goal.id, 'canceled')).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });++ expect(cancelSpy).not.toHaveBeenCalled();+ // Fenced, so nothing new starts, and the claim is left for its run to record.+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe('paused');+ expect((await new TaskModel(serverDB, userId).findById(created.taskId!))?.status).toBe(+ 'running',+ );+ });++ it('withdraws a claim whose startup died long ago and closes the goal', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Dead start'], title: 'Stale claim' });+ const created = await service.tick(graph.goal.id);+ await serverDB+ .update(tasks)+ .set({ status: 'running', updatedAt: new Date(Date.now() - 24 * 60 * 60 * 1000) })+ .where(eq(tasks.id, created.taskId!));++ expect((await service.close(graph.goal.id, 'canceled')).status).toBe('canceled');+ expect((await new TaskModel(serverDB, userId).findById(created.taskId!))?.status).toBe(+ 'backlog',+ );+ });++ it('keeps a closed goal closed when a stale decision is answered', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Risky task'], title: 'Closed with a gate' });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });+ await service.tick(graph.goal.id);+ const [decision] = (await service.graph(graph.goal.id)).decisions;++ await service.close(graph.goal.id, 'canceled');++ // Another tab still showing the gate answers it.+ await expect(service.decide(graph.goal.id, decision.id, 'retry')).rejects.toMatchObject({+ code: 'CONFLICT',+ });+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe(+ 'canceled',+ );+ });++ it('does not reopen a goal closed while a decision was being answered', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Risky task'], title: 'Closed mid-answer' });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });+ await service.tick(graph.goal.id);+ const [decision] = (await service.graph(graph.goal.id)).decisions;+ // The close lands after the answer is written, before the status moves.+ const graphModel = (service as unknown as { graphModel: GoalGraphModel }).graphModel;+ const resolve = graphModel.resolveDecision;+ vi.spyOn(graphModel, 'resolveDecision').mockImplementation(async (...args) => {+ const resolved = await resolve(...args);+ await new GoalService(serverDB, userId).close(graph.goal.id, 'canceled');+ return resolved;+ });++ await service.decide(graph.goal.id, decision.id, 'retry');++ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe(+ 'canceled',+ );+ });++ it('refuses to end a goal someone resumed while its runs were being interrupted', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Runs'], title: 'Resumed mid-close' });+ const created = await service.tick(graph.goal.id);+ await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });+ await serverDB.insert(topics).values({ id: 'tpc_race', userId });+ await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_race', { seq: 1 });+ await new TaskTopicModel(serverDB, userId).updateStatus(created.taskId!, 'tpc_race', 'running');+ // Another tab resumes the goal while the interruption pass is running.+ vi.spyOn(TaskService.prototype, 'cancelTopic').mockImplementation(async () => {+ await new GoalService(serverDB, userId).resume(graph.goal.id);+ });++ await expect(service.close(graph.goal.id, 'canceled')).rejects.toMatchObject({+ code: 'CONFLICT',+ });+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe('running');+ });++ it('does not let a resume that read the goal before a close reopen it afterwards', async () => {+ // The resume read the fenced `paused` goal; the close then committed the+ // terminal status. The stale resume must not write `running` over it.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Runs'], title: 'Resume after close' });+ await service.pause(graph.goal.id);+ const requireGraph = (service as unknown as { requireGraph: GoalService['graph'] })+ .requireGraph;+ vi.spyOn(service as any, 'requireGraph').mockImplementationOnce(async (id) => {+ const snapshot = await requireGraph(id as string);+ await new GoalService(serverDB, userId).close(graph.goal.id, 'canceled');+ return snapshot;+ });++ await expect(service.resume(graph.goal.id)).rejects.toMatchObject({ code: 'CONFLICT' });+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe(+ 'canceled',+ );+ // An explicit reopen of the ended goal still works.+ expect((await service.resume(graph.goal.id)).status).toBe('running');+ });++ it('keeps runs already stopped reopenable when a later interruption fails', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const topicModel = new TaskTopicModel(serverDB, userId);+ const graph = await service.create({ tasks: ['First', 'Second'], title: 'Partial close' });+ const [first, second] = graph.nodes.filter((node) => node.kind === 'task');+ const taskIds: string[] = [];+ for (const [index, node] of [first, second].entries()) {+ const task = await new TaskService(serverDB, userId).createTask({+ instruction: node.title,+ name: node.title,+ });+ await new GoalGraphModel(serverDB, userId).bindTask(graph.goal.id, node.id, task.id);+ await taskModel.update(task.id, { status: 'running' });+ const topicId = `tpc_partial_${index}`;+ await serverDB.insert(topics).values({ id: topicId, userId });+ await topicModel.add(task.id, topicId, { seq: 1 });+ await topicModel.updateStatus(task.id, topicId, 'running');+ taskIds.push(task.id);+ }+ // The first interruption lands (the task reads `paused`, as cancelTopic+ // leaves it); the second is unreachable.+ let calls = 0;+ vi.spyOn(TaskService.prototype, 'cancelTopic').mockImplementation(async (topicId) => {+ calls += 1;+ if (calls > 1) throw new Error('run unreachable');+ const index = Number(topicId.at(-1));+ await taskModel.update(taskIds[index], { status: 'paused' });+ await topicModel.updateStatus(taskIds[index], topicId, 'canceled');+ });++ await expect(service.close(graph.goal.id, 'canceled')).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });+ const stopped = (await taskModel.findByIds(taskIds)).filter(+ (task) => task.status !== 'running',+ );+ expect(stopped).toHaveLength(1);+ expect(stopped[0].status).toBe('backlog');+ });++ describe('closing a goal with a main Agent turn in flight', () => {+ const managedGoal = async (title: string) => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Managed'], title });+ await new AgentOperationModel(serverDB, userId).recordStart({+ operationId: `op-manager-${title}`,+ });+ await serverDB+ .update(goals)+ .set({+ config: {+ ...graph.goal.config,+ manager: {},+ managerState: {+ operationId: `op-manager-${title}`,+ startedAt: new Date().toISOString(),+ token: 'turn',+ topicId: 'management-topic',+ turns: 1,+ },+ } as never,+ })+ .where(eq(goals.id, graph.goal.id));+ return { goalId: graph.goal.id, service };+ };++ it('interrupts the main Agent turn before ending the goal', async () => {+ // The coordinator's own operation is not a graph Task topic, so the+ // topic scan alone would leave it spending after the goal ended.+ const { goalId, service } = await managedGoal('interrupted');+ const interrupt = vi+ .spyOn(AiAgentService.prototype, 'interruptTask')+ .mockResolvedValue({ success: true } as never);++ expect((await service.close(goalId, 'achieved')).status).toBe('achieved');+ expect(interrupt).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'op-manager-interrupted' }),+ );+ });++ it('refuses to end the goal when the interruption is not confirmed', async () => {+ const { goalId, service } = await managedGoal('unconfirmed');+ vi.spyOn(AiAgentService.prototype, 'interruptTask').mockResolvedValue({+ deviceCancellationConfirmed: false,+ success: true,+ } as never);++ await expect(service.close(goalId, 'canceled')).rejects.toThrow(/not closed/);+ // Still fenced so nothing new starts, but not claimed as ended.+ expect((await new GoalModel(serverDB, userId).findById(goalId))?.status).toBe('paused');+ });+ });++ it('restarts a split-role goal under a new executor without replacing its supervisor', async () => {+ vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();+ await serverDB.insert(agents).values([+ { id: 'agt_lead', slug: 'agt-lead', userId },+ { id: 'agt_first_worker', slug: 'agt-first-worker', userId },+ { id: 'agt_second_worker', slug: 'agt-second-worker', userId },+ ]);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ agentId: 'agt_lead',+ config: { taskAgentId: 'agt_first_worker' },+ tasks: ['Stuck task'],+ title: 'Restart split roles',+ });+ const created = await service.tick(graph.goal.id);++ const result = await service.restart(graph.goal.id, { agentId: 'agt_second_worker' });++ expect(result.goal.agentId).toBe('agt_lead');+ expect(result.goal.config?.taskAgentId).toBe('agt_second_worker');+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_second_worker');+ });++ it('cancels the failure gate a restart supersedes so the goal starts moving again', async () => {+ // A restarted task's pending recovery gate is answered by the restart+ // itself. Left pending, it keeps winning the coordinator's+ // pending-decision branch and the goal sits waiting_human with every task+ // freshly reset.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Risky task'], title: 'Restart clears gate' });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });+ expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');++ const result = await service.restart(graph.goal.id);++ expect(result.restartedTaskIds).toEqual([created.taskId]);+ const after = await service.graph(graph.goal.id);+ expect(after.decisions[0].status).toBe('canceled');+ // The freed coordinator dispatches the reset task instead of re-parking.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const next = await service.tick(graph.goal.id);+ expect(next.outcome).not.toBe('waiting_human');+ });++ it('retires a stray node only together with the unfinished tasks depending on it', async () => {+ // A duplicated plan branch never gets a Task, so nothing else ever closes it+ // and the goal can never reach acceptance.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['First', 'Second', 'Keep'], title: 'Duplicates' });+ const [first, second, keep] = ['First', 'Second', 'Keep'].map((title) =>+ graph.nodes.find((node) => node.kind === 'task' && node.title === title)!,+ );+ await service.addEdge(graph.goal.id, second.id, first.id, 'depends_on');++ await expect(service.retireNodes(graph.goal.id, [first.id])).rejects.toThrow(second.id);++ const result = await service.retireNodes(graph.goal.id, [first.id, second.id], 'duplicate');++ expect(result.retiredNodeIds.sort()).toEqual([first.id, second.id].sort());+ const after = await service.graph(graph.goal.id);+ const status = (id: string) => after.nodes.find((node) => node.id === id)?.status;+ expect(status(first.id)).toBe('retired');+ expect(status(second.id)).toBe('retired');+ expect(status(keep.id)).not.toBe('retired');+ });++ it('retiring a dispatched node cancels its task and the gate parking the goal', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Canceled elsewhere'], title: 'Stray gate' });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Task canceled' });+ expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');++ await service.retireNodes(graph.goal.id, [created.nodeId!]);++ expect((await taskModel.findById(created.taskId!))?.status).toBe('canceled');+ const after = await service.graph(graph.goal.id);+ expect(after.decisions[0].status).toBe('canceled');+ expect(after.goal.status).toBe('running');+ });++ it('retiring a node fences it against a coordinator still creating its task', async () => {+ const service = new GoalService(serverDB, userId);+ const graphModel = new GoalGraphModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Stray', 'Keep'], title: 'Retire race' });+ const stray = graph.nodes.find((node) => node.kind === 'task' && node.title === 'Stray')!;+ // A tick has claimed the node and is creating its Task when retirement lands.+ expect(await graphModel.claimTaskNode(graph.goal.id, stray.id, new Date(0))).toBeDefined();++ await service.retireNodes(graph.goal.id, [stray.id]);++ const lateTask = await new TaskModel(serverDB, userId).create({ instruction: 'Late' });+ expect(await graphModel.bindTask(graph.goal.id, stray.id, lateTask.id)).toBeUndefined();+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.find((node) => node.id === stray.id)?.status).toBe('retired');+ });++ it("stops a colleague's private task when a workspace owner retires its node", async () => {+ // The coordinator runs as the goal's owner, so its Tasks can be private to+ // that colleague. An owner retiring the node must still stop them โ reads+ // under the owner's own visibility would silently miss them.+ const workspaceId = 'goal-retire-private-ws';+ const ownerId = 'goal-retire-private-owner';+ await serverDB.insert(users).values({ id: ownerId }).onConflictDoNothing();+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: workspaceId, primaryOwnerId: ownerId, slug: workspaceId })+ .onConflictDoNothing();+ const colleague = new GoalService(serverDB, userId, workspaceId);+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const graph = await colleague.create({ tasks: ['Private', 'Keep'], title: 'Private retire' });+ const created = await colleague.tick(graph.goal.id);+ await serverDB+ .update(tasks)+ .set({ status: 'running', visibility: 'private' })+ .where(eq(tasks.id, created.taskId!));+ expect(+ await new TaskModel(serverDB, ownerId, workspaceId).findById(created.taskId!),+ ).toBeFalsy();++ await new GoalService(serverDB, ownerId, workspaceId).retireNodes(graph.goal.id, [+ created.nodeId!,+ ]);++ const [task] = await serverDB.select().from(tasks).where(eq(tasks.id, created.taskId!));+ expect(task.status).toBe('canceled');+ });++ it('cancels a running task before looking for its runs, fencing a run still being dispatched', async () => {+ // A runner that already flipped the Task to `running` but has not recorded+ // its topic yet is invisible to the run lookup. It checks the Task's status+ // under the row lock before recording, so the cancellation must already be+ // committed by the time retirement looks for runs to stop.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Dispatching', 'Keep'], title: 'Fence runs' });+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'running');+ const statusAtLookup: (string | undefined)[] = [];+ const original = TaskTopicModel.prototype.findRunningByTaskIds;+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockImplementation(async function (+ this: TaskTopicModel,+ ids: string[],+ ) {+ statusAtLookup.push((await taskModel.findById(created.taskId!))?.status);+ return original.call(this, ids);+ });++ await service.retireNodes(graph.goal.id, [created.nodeId!]);++ expect(statusAtLookup).toEqual(['canceled']);+ expect((await taskModel.findById(created.taskId!))?.status).toBe('canceled');+ });++ it('lets an interrupted retirement be finished by retrying it', async () => {+ // The fence lands before the run is stopped; when stopping it cannot be+ // confirmed the call fails with the node already retired. A retry must+ // still stop the task instead of rejecting the node as terminal.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Running', 'Keep'], title: 'Retry retire' });+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const created = await service.tick(graph.goal.id);+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ { taskId: created.taskId!, topicId: 'tpc_running' },+ ] as never);+ const cancelTopic = vi+ .spyOn(TaskService.prototype, 'cancelTopic')+ .mockRejectedValueOnce(new Error('interrupt not confirmed'))+ .mockResolvedValue(undefined as never);++ await expect(service.retireNodes(graph.goal.id, [created.nodeId!])).rejects.toThrow(+ 'interrupt not confirmed',+ );+ expect(+ (await service.graph(graph.goal.id)).nodes.find((node) => node.id === created.nodeId)?.status,+ ).toBe('retired');++ const retried = await service.retireNodes(graph.goal.id, [created.nodeId!]);++ expect(retried.retiredNodeIds).toEqual([created.nodeId]);+ expect(cancelTopic).toHaveBeenCalledTimes(2);+ expect((await taskModel.findById(created.taskId!))?.status).toBe('canceled');+ });++ it('discards a stale tick outcome for a node retired while it ran', async () => {+ const service = new GoalService(serverDB, userId);+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const graph = await service.create({ tasks: ['Stray', 'Keep'], title: 'Stale tick' });+ const created = await service.tick(graph.goal.id);+ // The coordinator loaded this snapshot before the retirement landed.+ const stale = await service.graph(graph.goal.id);+ await service.retireNodes(graph.goal.id, [created.nodeId!]);++ const result = await (service as any).consumeCompletedTask(+ stale,+ created.nodeId!,+ created.taskId!,+ );++ expect(result.outcome).toBe('no_progress');+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.find((node) => node.id === created.nodeId)?.status).toBe('retired');+ expect(after.nodes.some((node) => node.kind === 'finding')).toBe(false);+ });++ it('reopens a goal parked by no_frontier once the blocking nodes are retired', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['A', 'B', 'Keep'], title: 'Deadlocked branch' });+ const [a, b] = ['A', 'B'].map((title) =>+ graph.nodes.find((node) => node.kind === 'task' && node.title === title)!,+ );+ const graphModel = new GoalGraphModel(serverDB, userId);+ await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');+ await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');+ const keep = graph.nodes.find((node) => node.kind === 'task' && node.title === 'Keep')!;+ await graphModel.updateNodeStatus(graph.goal.id, keep.id, 'resolved');+ await service.tick(graph.goal.id); // deadlock โ no_frontier โ paused+ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');++ await service.retireNodes(graph.goal.id, [a.id, b.id]);++ expect((await service.graph(graph.goal.id)).goal.status).toBe('running');+ });++ it('leaves a user-paused goal paused when nodes are retired', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['A', 'B'], title: 'Paused by a person' });+ const [a, b] = graph.nodes.filter((node) => node.kind === 'task');+ const graphModel = new GoalGraphModel(serverDB, userId);+ await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');+ await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');+ await service.tick(graph.goal.id); // no_frontier park+ await service.pause(graph.goal.id); // the person takes the pause over++ await service.retireNodes(graph.goal.id, [a.id, b.id]);++ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');+ });++ it('leaves a deliberately paused goal paused when its budget changes', async () => {+ // Nothing distinguishes a user pause from a budget pause on the row, so the+ // reopen is limited to goals whose budget was actually binding.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Wait'], title: 'User paused' });+ await service.pause(graph.goal.id);++ const updated = await service.setBudget(graph.goal.id, { maxTotalCost: 50 });++ expect(updated?.status).toBe('paused');+ });++ it('refuses to delete a goal whose running Task cannot be stopped', async () => {+ // Deleting anyway would remove the only surface that can stop an operation+ // which keeps spending.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Runs on'], title: 'Unstoppable' });+ const created = await service.tick(graph.goal.id);+ await serverDB.insert(topics).values({ id: 'tpc_stuck', userId });+ await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_stuck', { seq: 1 });+ await new TaskTopicModel(serverDB, userId).updateStatus(+ created.taskId!,+ 'tpc_stuck',+ 'running',+ );+ vi.spyOn(TaskService.prototype, 'cancelTopic').mockRejectedValue(new Error('gateway is down'));++ await expect(service.delete(graph.goal.id)).rejects.toThrow(/not deleted/);+ expect(await service.graph(graph.goal.id)).toBeDefined();+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/measurement.test.ts b/apps/server/src/services/goal/GoalService/__tests__/measurement.test.tsnew file mode 100644index 00000000000..f4886fa5bd3--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/measurement.test.ts@@ -0,0 +1,320 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { MetricModel } from '@/database/models/metric';+import { TaskModel } from '@/database/models/task';+import type { LobeChatDatabase } from '@/database/type';++import { TaskRunnerService } from '../../../taskRunner';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import type { GoalTickObservation } from '../../traceObservation';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ 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+ // not be created โ and the goal must not sit `running` reporting+ // `no_progress`, or every sweep would re-tick it for the whole wait.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const graph = await service.create({+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },+ requirement: 'Grow the account',+ tasks: ['Publish the first posts'],+ title: 'Measured goal',+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'completed');+ await service.tick(graph.goal.id);++ // Nothing measured yet โ "never observed" is not "satisfied".+ const unmeasured = await service.tick(graph.goal.id);+ expect(unmeasured).toMatchObject({ outcome: 'no_progress' });+ expect(unmeasured.message).toContain('no observation');+ expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');+ expect(+ (await service.graph(graph.goal.id)).nodes.some(+ (n) => n.title === 'Complete full Goal acceptance',+ ),+ ).toBe(false);++ // A sample that is still short leaves it parked and is not worth an advance.+ const short = await service.recordObservation(graph.goal.id, {+ key: 'followers',+ value: 400,+ });+ expect(short.shouldAdvance).toBe(false);+ expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');++ // The number lands: the goal reopens and falls through to its delivery+ // contract.+ const cleared = await service.recordObservation(graph.goal.id, {+ key: 'followers',+ value: 1200,+ });+ expect(cleared.shouldAdvance).toBe(true);+ expect((await goalModel.findById(graph.goal.id))?.status).toBe('running');++ const advanced = await service.tick(graph.goal.id);+ expect(advanced).toMatchObject({ outcome: 'advanced' });+ expect(+ (await service.graph(graph.goal.id)).nodes.some(+ (n) => n.title === 'Complete full Goal acceptance',+ ),+ ).toBe(true);+ });++ /** A goal parked by the gate, one clause short of acceptance. */+ const parkedOnGate = async (service: GoalService) => {+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },+ requirement: 'Grow the account',+ tasks: ['Publish the first posts'],+ title: 'Parked on a measurement',+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'completed');+ await service.tick(graph.goal.id);+ await service.tick(graph.goal.id);+ return graph.goal.id;+ };++ it('reopens a goal parked before the pause marker existed', async () => {+ // Rows parked by the parent implementation โ and any parked by an old+ // worker mid-deploy โ carry no marker. Requiring one strictly would strand+ // them until somebody pressed Resume by hand, so the transition's recorded+ // actor stands in for it.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const goalId = await parkedOnGate(service);++ // Exactly what a pre-marker row looks like.+ const parked = (await goalModel.findById(goalId))!;+ await goalModel.update(goalId, { config: { ...parked.config, pausedBy: undefined } });++ const cleared = await service.recordObservation(goalId, { key: 'followers', value: 5000 });++ expect(cleared.shouldAdvance).toBe(true);+ expect((await goalModel.findById(goalId))?.status).toBe('running');+ });++ it('does not let an observation restart a goal the coordinator parked for another reason', async () => {+ // The coordinator also parks goals that are deadlocked or out of budget.+ // Those carry no marker either once they predate it, so the fallback has to+ // read *why* it parked โ not just that it was the coordinator.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const graph = await service.create({+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },+ requirement: 'Deadlocked before the gate',+ tasks: ['A', 'B'],+ title: 'Parked with work outstanding',+ });+ const [a, b] = graph.nodes.filter((n) => n.kind === 'task');+ const graphModel = new GoalGraphModel(serverDB, userId);+ await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');+ await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');++ await service.tick(graph.goal.id); // deadlock โ no_frontier โ paused+ expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');++ const satisfying = await service.recordObservation(graph.goal.id, {+ key: 'followers',+ value: 5000,+ });++ expect(satisfying.shouldAdvance).toBe(false);+ expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');+ });++ it('leaves a deliberately paused goal alone even when the measurement lands', async () => {+ // The hard case: same status, same terminal phase, same clauses as a goal+ // the coordinator parked. Only the recorded pause reason tells them apart,+ // and without it a satisfying sample would restart a goal somebody stopped+ // on purpose โ and run its acceptance work.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const goalId = await parkedOnGate(service);+ await service.pause(goalId);++ const satisfying = await service.recordObservation(goalId, { key: 'followers', value: 5000 });++ expect(satisfying.shouldAdvance).toBe(false);+ expect((await goalModel.findById(goalId))?.status).toBe('paused');+ expect(+ (await service.graph(goalId)).nodes.some((n) => n.title === 'Complete full Goal acceptance'),+ ).toBe(false);+ });++ it('resumes a user-paused goal only through resume, and then it advances again', async () => {+ // The other half: once the person lifts their own pause, the goal is the+ // coordinator's again.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const goalId = await parkedOnGate(service);+ await service.pause(goalId);+ await service.recordObservation(goalId, { key: 'followers', value: 5000 });++ await service.resume(goalId);++ expect(await service.tick(goalId)).toMatchObject({ outcome: 'advanced' });+ });++ it('unblocks a parked goal when its last clause is dropped', async () => {+ // `setMetricCriteria(id, [])` is the advertised way to clear the gate. It+ // used to leave the goal parked on a gate that no longer existed, so the+ // scheduled advance ticked straight back out as `goal_paused` and only a+ // manual resume could move it.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const goalId = await parkedOnGate(service);+ expect((await goalModel.findById(goalId))?.status).toBe('paused');++ await service.setMetricCriteria(goalId, []);++ expect((await goalModel.findById(goalId))?.status).toBe('running');+ expect(await service.tick(goalId)).toMatchObject({ outcome: 'advanced' });+ });++ it('unblocks a parked goal when a clause is relaxed below the measurement', async () => {+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const goalId = await parkedOnGate(service);+ await service.recordObservation(goalId, { key: 'followers', value: 400 });+ expect((await goalModel.findById(goalId))?.status).toBe('paused');++ await service.setMetricCriteria(goalId, [{ key: 'followers', target: 100 }]);++ expect((await goalModel.findById(goalId))?.status).toBe('running');+ });++ it('keeps the numeric gate when the delivery criteria are bound or rebound', async () => {+ // Both writers used to rebuild `config.acceptance` from `criteriaIds`+ // alone, so declaring criteria โ at creation or later from the goal page โ+ // silently dropped a live measured gate and let the goal be accepted+ // without it.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },+ criteria: [{ title: 'Ship the launch post' }],+ requirement: 'Grow the account',+ tasks: ['Publish the first posts'],+ title: 'Both halves of acceptance',+ });++ const created = await new GoalModel(serverDB, userId).findById(graph.goal.id);+ expect(created?.config?.acceptance?.metrics).toEqual([{ key: 'followers', target: 1000 }]);+ expect(created?.config?.acceptance?.criteriaIds).toHaveLength(1);++ await service.setAcceptanceCriteria(graph.goal.id, []);++ const rebound = await new GoalModel(serverDB, userId).findById(graph.goal.id);+ expect(rebound?.config?.acceptance?.metrics).toEqual([{ key: 'followers', target: 1000 }]);+ });++ it('merges a declared clause into the server-side list instead of replacing it', async () => {+ // Two editors declaring from the same stale snapshot must not erase each+ // other: merge upserts by key against the list as it stands on the server.+ const service = new GoalService(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const graph = await service.create({+ config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },+ requirement: 'Grow the account',+ tasks: ['Publish'],+ title: 'Merge-mode goal',+ });++ // A "concurrent" declaration this client never saw.+ await service.setMetricCriteria(+ graph.goal.id,+ [{ key: 'retention', op: 'gte', target: 80 }],+ 'merge',+ );+ // This client merges its own clause from a snapshot that predates it.+ await service.setMetricCriteria(+ graph.goal.id,+ [{ key: 'followers', target: 2000, title: '็ฒไธ' }],+ 'merge',+ );++ const metrics = (await goalModel.findById(graph.goal.id))?.config?.acceptance?.metrics;+ expect(metrics).toHaveLength(2);+ expect(metrics).toContainEqual({ key: 'retention', op: 'gte', target: 80 });+ // Same-key merge upserts rather than duplicating.+ expect(metrics).toContainEqual({ key: 'followers', target: 2000, title: '็ฒไธ' });+ });++ it('declares numeric clauses after creation without touching the criteria binding', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ criteria: [{ title: 'Ship the launch post' }],+ requirement: 'Grow the account',+ tasks: ['Publish the first posts'],+ title: 'Late-declared gate',+ });++ await service.setMetricCriteria(graph.goal.id, [{ key: 'churn', op: 'lte', target: 5 }]);++ const updated = await new GoalModel(serverDB, userId).findById(graph.goal.id);+ expect(updated?.config?.acceptance).toMatchObject({+ criteriaIds: expect.any(Array),+ metrics: [{ key: 'churn', op: 'lte', target: 5 }],+ });+ expect(updated?.config?.acceptance?.criteriaIds).toHaveLength(1);+ });++ it('records what the measured decision read, not just its verdict', async () => {+ // A replay has to see the number the live run saw โ the same reason the+ // deadline verdict travels with the budget.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const metricModel = new MetricModel(serverDB, userId);+ const graph = await service.create({+ config: { acceptance: { metrics: [{ key: 'churn', op: 'lte', target: 5 }] } },+ requirement: 'Keep churn down',+ tasks: ['Ship retention fixes'],+ title: 'Traced measurement',+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'completed');+ await service.tick(graph.goal.id);++ const series = (await metricModel.ensure({+ key: 'churn',+ subjectId: graph.goal.id,+ subjectType: 'goal',+ }))!;+ await metricModel.addPoint(series.id, {+ actorType: 'system',+ observedAt: new Date('2026-09-01T00:00:00Z'),+ sourceType: 'probe',+ value: 9,+ });++ const observed: GoalTickObservation[] = [];+ await service.tick(graph.goal.id, { onDecision: (o) => observed.push(o) });++ expect(observed.at(-1)!.metricCriteria).toMatchObject({+ allMet: false,+ criteria: [{ key: 'churn', met: false, op: 'lte', target: 5, value: 9 }],+ });+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/planning.test.ts b/apps/server/src/services/goal/GoalService/__tests__/planning.test.tsnew file mode 100644index 00000000000..71bb03a4cf5--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/planning.test.ts@@ -0,0 +1,337 @@+// @vitest-environment node+import { and, eq } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { goalEvents } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ it('attaches seed tasks straight to the problem instead of wrapping each in an experiment', async () => {+ // An experiment is a candidate answer under test. A caller-supplied seed is+ // ordinary work, so it takes the same shape as a planned or manager-submitted+ // Task: a `decomposes` edge from the problem, no answer container.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Question', tasks: ['Seed work'] });+ const question = graph.nodes.find((n) => n.kind === 'problem')!;+ const task = graph.nodes.find((n) => n.kind === 'task')!;+ expect(graph.goal.config?.exploration).toBeUndefined();+ expect(graph.nodes.filter((n) => n.kind === 'experiment')).toHaveLength(0);+ expect(graph.edges).toEqual([+ expect.objectContaining({+ kind: 'decomposes',+ sourceNodeId: question.id,+ targetNodeId: task.id,+ }),+ ]);+ });++ it('seeds the exploration baseline inside an experiment container', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { exploration: { instruction: 'Compare evidence', maxExperiments: 3 } },+ title: 'Explore',+ });+ const question = graph.nodes.find((n) => n.kind === 'problem')!;+ const answer = graph.nodes.find((n) => n.kind === 'experiment')!;+ const task = graph.nodes.find((n) => n.kind === 'task')!;+ expect(answer.taskId).toBeNull();+ expect(graph.edges).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ kind: 'answers',+ sourceNodeId: answer.id,+ targetNodeId: question.id,+ }),+ expect.objectContaining({+ kind: 'contains',+ sourceNodeId: answer.id,+ targetNodeId: task.id,+ }),+ ]),+ );+ });++ it('plans the decomposition when a goal has no tasks yet', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ ธๅฟ้ฎ้ข็ไธๅฅ่ฏ้่ฟฐ',+ tasks: [+ { dependsOn: [], hypothesis: null, instruction: 'ๆถ้ๅๅงๆๆ', title: 'ๆนๅA:ๆถ้' },+ {+ dependsOn: [0],+ hypothesis: 'ๆๆจกๅ่็ฑปๆฏๆๆถ้ดๆๅบๆด่ฝๆด้ฒๆ นๅ ',+ instruction: 'ๅๆๅนถ็ปผๅ็ป่ฎบ',+ title: 'ๆนๅB:ๅๆ',+ },+ // Self and forward references are planner hallucinations โ dropped.+ { dependsOn: [1, 2, 9], instruction: 'ๆฑ็ผๆ็ปๆฅๅ', title: 'ๆนๅC:ๆฑ็ผ' },+ ],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ problemDescription: '็จๆท็ๅ่ฏ',+ requirement: 'ๅฎๆด้ๆฑไธ้ชๆถๆ ๅๅ จๆ',+ title: 'Complex ask',+ });+ // The seeded graph carries the user's own words, not the contract blob.+ expect(graph.nodes.find((n) => n.kind === 'problem')?.description).toBe('็จๆท็ๅ่ฏ');+ expect(graph.nodes.filter((n) => n.kind === 'task')).toHaveLength(0);++ const result = await service.tick(graph.goal.id);++ expect(result.outcome).toBe('advanced');+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((n) => n.kind === 'task').map((n) => n.title)).toEqual([+ 'ๆนๅA:ๆถ้',+ 'ๆนๅB:ๅๆ',+ 'ๆนๅC:ๆฑ็ผ',+ ]);+ const problem = after.nodes.find((n) => n.kind === 'problem')!;+ expect(problem.description).toBe('ๆ ธๅฟ้ฎ้ข็ไธๅฅ่ฏ้่ฟฐ');++ // Only the direction the planner marked as a hypothesis becomes a candidate+ // answer: one experiment answering the problem and containing that Task.+ // The certain steps attach straight to the problem.+ const byTitle = new Map(after.nodes.map((n) => [n.title, n.id]));+ const experiments = after.nodes.filter((n) => n.kind === 'experiment');+ expect(experiments).toHaveLength(1);+ expect(experiments[0]).toMatchObject({+ description: 'ๆๆจกๅ่็ฑปๆฏๆๆถ้ดๆๅบๆด่ฝๆด้ฒๆ นๅ ',+ title: 'ๆนๅB:ๅๆ',+ });+ expect(after.edges.filter((e) => e.kind === 'answers')).toEqual([+ expect.objectContaining({ sourceNodeId: experiments[0].id, targetNodeId: problem.id }),+ ]);+ expect(after.edges.filter((e) => e.kind === 'contains')).toEqual([+ expect.objectContaining({+ sourceNodeId: experiments[0].id,+ targetNodeId: byTitle.get('ๆนๅB:ๅๆ'),+ }),+ ]);+ expect(+ after.edges+ .filter((e) => e.kind === 'decomposes' && e.sourceNodeId === problem.id)+ .map((e) => e.targetNodeId)+ .sort(),+ ).toEqual([byTitle.get('ๆนๅA:ๆถ้'), byTitle.get('ๆนๅC:ๆฑ็ผ')].sort());++ // The planner's dependsOn indices become depends_on edges, dependent โ+ // prerequisite; the self and forward references were dropped.+ const deps = after.edges+ .filter((e) => e.kind === 'depends_on')+ .map((e) => [e.sourceNodeId, e.targetNodeId]);+ expect(deps).toHaveLength(2);+ expect(deps).toEqual(+ expect.arrayContaining([+ [byTitle.get('ๆนๅB:ๅๆ'), byTitle.get('ๆนๅA:ๆถ้')],+ [byTitle.get('ๆนๅC:ๆฑ็ผ'), byTitle.get('ๆนๅB:ๅๆ')],+ ]),+ );+ });++ it('plans a goal without hypotheses as plain tasks under the problem', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ไฟฎๅฅฝๆ่ฟไธๅคฉ็ bug',+ tasks: [+ { dependsOn: [], hypothesis: null, instruction: 'ๅๅบ issue', title: 'ๅปบ็ซๆธ ๅ' },+ { dependsOn: [0], hypothesis: null, instruction: '้้กนไฟฎๅค', title: 'ๅฎๆฝไฟฎๅค' },+ ],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Bug sweep' });++ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');++ const after = await service.graph(graph.goal.id);+ const problem = after.nodes.find((n) => n.kind === 'problem')!;+ const taskIds = after.nodes.filter((n) => n.kind === 'task').map((n) => n.id);+ expect(taskIds).toHaveLength(2);+ expect(after.nodes.filter((n) => n.kind === 'experiment')).toHaveLength(0);+ expect(after.edges.filter((e) => e.kind === 'answers' || e.kind === 'contains')).toHaveLength(+ 0,+ );+ expect(+ after.edges+ .filter((e) => e.kind === 'decomposes' && e.sourceNodeId === problem.id)+ .map((e) => e.targetNodeId)+ .sort(),+ ).toEqual([...taskIds].sort());+ expect(after.edges.filter((e) => e.kind === 'depends_on')).toHaveLength(1);+ });++ it('collapses a repeated mould into one batch, materializing only the probes', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });++ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');++ const after = await service.graph(graph.goal.id);+ // โ Only the K probes exist as Tasks โ the whole 50-unit fan-out never lands.+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(5);+ expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(1);+ expect(after.nodes.filter((n) => n.kind === 'finding')).toHaveLength(1);+ expect(after.nodes.filter((n) => n.kind === 'decision')).toHaveLength(1);++ const state = after.goal.config?.rolloutState;+ expect(state?.phase).toBe('probe');+ expect(state?.probeNodeIds).toHaveLength(5);+ expect(state?.unitTitles).toHaveLength(50);+ expect(after.goal.config?.rollout?.trigger).toBe('canary');++ // The probes are contained by the batch; the gate waits on each of them.+ const batch = after.nodes.find((n) => n.kind === 'batch')!;+ const containedIds = new Set(+ after.edges+ .filter((e) => e.kind === 'contains' && e.sourceNodeId === batch.id)+ .map((e) => e.targetNodeId),+ );+ // Five probes inside the batch โ never the whole 50-unit roster.+ expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'task')).toHaveLength(5);+ // Plus the one Template and the one Assay that make the batch a batch.+ expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'finding')).toHaveLength(+ 1,+ );+ expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'decision')).toHaveLength(+ 1,+ );+ });++ it('does not grow a batch for a goal that is not one repeated mould', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๅไธคๆญฅไธ็บฟไธไธชๆฐๅ่ฝ',+ rollout: {+ recipeOutline: '',+ repeatable: false,+ unitCount: 3,+ units: [],+ variants: [],+ },+ tasks: [+ { dependsOn: [], instruction: '็ฌฌไธๆญฅ๏ผๅ schema', title: '็ฌฌไธๆญฅ' },+ { dependsOn: [0], instruction: '็ฌฌไบๆญฅ๏ผๆฅ UI', title: '็ฌฌไบๆญฅ' },+ ],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Ship a feature' });++ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');++ const after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);+ expect(after.goal.config?.rolloutState).toBeUndefined();+ // The ordinary decomposition is untouched: both steps are plain tasks.+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(2);+ });++ it('keeps every roster unit when a rollout claim cannot become a batch', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 12 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 12,+ units: Array.from({ length: 12 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 3 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ // The caller forbade a batch, so the planner's claim must NOT drop the+ // units its probe-only `tasks` left out.+ const graph = await service.create({+ config: { rollout: { trigger: 'off' } },+ title: 'Migrate stores, no batch',+ });+ await service.tick(graph.goal.id);++ const after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);+ // All 12 units are planned, not only the 3 the planner listed as probes.+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(12);+ });++ /**+ * Regression: a planner failure was swallowed whole โ the goal quietly+ * became one task built from the raw requirement, and nothing anywhere said+ * the planner had failed or why.+ */+ it('records why the planner failed on the task it fell back to', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockRejectedValue({+ error: { message: 'Insufficient Balance' },+ errorType: 'InsufficientQuota',+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ requirement: '่ฟ็งป 12 ไธช store', title: 'Migrate' });+ await service.tick(graph.goal.id);++ const task = (await service.graph(graph.goal.id)).nodes.find((n) => n.kind === 'task');+ const [created] = await serverDB+ .select()+ .from(goalEvents)+ .where(and(eq(goalEvents.entityId, task.id), eq(goalEvents.eventType, 'created')));+ expect(created.reason).toBe(+ 'Planner failed (InsufficientQuota: Insufficient Balance); no main Agent could take the goal; started from the raw requirement',+ );+ });++ it('records why a batch claim was refused on the first task it planned instead', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 8 ไธช store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 8,+ units: Array.from({ length: 8 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 3 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate 8 stores' });+ await service.tick(graph.goal.id);++ const tasks = (await service.graph(graph.goal.id)).nodes.filter((n) => n.kind === 'task');+ const reasons = await serverDB+ .select({ entityId: goalEvents.entityId, reason: goalEvents.reason })+ .from(goalEvents)+ .where(eq(goalEvents.eventType, 'created'));+ const reasonOf = (id: string) => reasons.find((event) => event.entityId === id)?.reason;+ expect(reasonOf(tasks[0].id)).toBe(+ 'Batch claim refused (unitCount 8 is below the threshold 10); planned unit by unit',+ );+ // Said once, not on every task.+ expect(reasonOf(tasks[1].id)).toBeNull();+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/planningRaces.test.ts b/apps/server/src/services/goal/GoalService/__tests__/planningRaces.test.tsnew file mode 100644index 00000000000..2e998c5b46f--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/planningRaces.test.ts@@ -0,0 +1,311 @@+// @vitest-environment node+import { eq, sql } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { goals } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ it('plans the decomposition once when two advances race through the planner', async () => {+ // The queued kickoff and the client's fire-and-forget fallback can both+ // reach plan_decomposition together; the atomic planning claim must stop+ // the loser BEFORE the planner call, so nothing double-plans or double-pays.+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let plannerCalls = 0;+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockImplementation(async () => {+ plannerCalls += 1;+ await gate;+ return {+ problemStatement: 'ๅนถๅ่งๅ',+ tasks: [+ { dependsOn: [], instruction: 'ๆถ้', title: 'ๆนๅA' },+ { dependsOn: [0], instruction: 'ๅๆ', title: 'ๆนๅB' },+ ],+ };+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ problemDescription: 'ๅ่ฏ', title: 'Raced planning' });++ const ticks = Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);+ // The winner holds the planner open; the loser must lose the claim and+ // return without ever entering it.+ await vi.waitFor(() => expect(plannerCalls).toBe(1));+ release();+ const results = await ticks;++ expect(plannerCalls).toBe(1);+ expect(results.filter((r) => r.outcome === 'advanced')).toHaveLength(1);+ expect(results.filter((r) => r.outcome === 'waiting_external')).toHaveLength(1);+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(2);+ expect(after.edges.filter((e) => e.kind === 'depends_on')).toHaveLength(1);+ });++ it('waits for an unfenced legacy planner instead of generating a second graph', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Legacy in-flight planning' });+ // The pre-lease binary claimed only the status, without a checkpoint.+ await serverDB.update(goals).set({ status: 'running' }).where(eq(goals.id, graph.goal.id));+ const planner = vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose');++ expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_external');+ expect(planner).not.toHaveBeenCalled();+ expect(+ (await service.graph(graph.goal.id)).nodes.filter((node) => node.kind === 'task'),+ ).toHaveLength(0);+ });++ it('does not call the planner again when a late advance sees running with no tasks', async () => {+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const planner = vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose');+ planner.mockImplementationOnce(async () => {+ await gate;+ return {+ problemStatement: 'First plan',+ tasks: [{ instruction: 'Collect sources', title: 'Original research' }],+ };+ });+ planner.mockResolvedValue({+ problemStatement: 'Second plan',+ tasks: [{ instruction: 'Collect sources', title: 'Equivalent research' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Staggered planning' });+ const first = service.tick(graph.goal.id);+ try {+ await vi.waitFor(() => expect(planner).toHaveBeenCalledTimes(1));+ // The initial claim already changed the status, but has not produced any tasks.+ expect((await service.graph(graph.goal.id)).goal.status).toBe('running');+ const late = await new GoalService(serverDB, userId).tick(graph.goal.id);+ expect(late.outcome).toBe('waiting_external');+ expect(planner).toHaveBeenCalledTimes(1);+ } finally {+ release();+ await first;+ }+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((node) => node.kind === 'task')).toHaveLength(1);+ expect(after.nodes.filter((node) => node.kind === 'experiment')).toHaveLength(0);+ expect(after.nodes.find((node) => node.kind === 'problem')?.description).toBe('First plan');+ expect(after.edges.filter((edge) => edge.kind === 'decomposes')).toHaveLength(1);+ });++ it('rejects a late planner after an expired lease is taken over', async () => {+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const planner = vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose');+ planner.mockImplementationOnce(async () => {+ await gate;+ return { problemStatement: 'Stale plan', tasks: [{ instruction: 'Old', title: 'Old task' }] };+ });+ planner.mockResolvedValue({+ problemStatement: 'Recovered plan',+ tasks: [{ instruction: 'New', title: 'New task' }],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Lease recovery' });+ const first = service.tick(graph.goal.id);+ try {+ await vi.waitFor(() => expect(planner).toHaveBeenCalledTimes(1));+ const model = new GoalModel(serverDB, userId);+ const current = await model.findById(graph.goal.id);+ await serverDB+ .update(goals)+ .set({+ config: {+ ...current?.config,+ planningCheckpoint: {+ token: current!.config!.planningCheckpoint!.token,+ expiresAt: '2000-01-01T00:00:00.000Z',+ },+ },+ })+ .where(eq(goals.id, graph.goal.id));+ await new GoalService(serverDB, userId).tick(graph.goal.id);+ } finally {+ release();+ await first;+ }+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((node) => node.kind === 'task').map((node) => node.title)).toEqual([+ 'New task',+ ]);+ expect(after.goal.config?.planningCheckpoint).toBeUndefined();+ });++ it.each(['paused', 'changed'] as const)(+ 'discards planning when the goal is %s during generation',+ async (change) => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Original goal' });+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockImplementation(async () => {+ await new GoalModel(serverDB, userId).update(+ graph.goal.id,+ change === 'paused' ? { status: 'paused' } : { requirement: 'New requirement' },+ );+ return { problemStatement: 'Old plan', tasks: [{ instruction: 'Old', title: 'Old task' }] };+ });+ await service.tick(graph.goal.id);+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((node) => node.kind === 'task')).toHaveLength(0);+ expect(after.goal.config?.planningCheckpoint).toBeUndefined();+ },+ );++ it('rolls back an incomplete decomposition and allows a clean retry', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'Planned question',+ tasks: [+ { instruction: 'Collect sources', title: 'Research' },+ { dependsOn: [0], instruction: 'Write report', title: 'Report' },+ ],+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ problemDescription: 'Original question',+ title: 'Atomic planning',+ });+ // Fail only when the planner reaches dependency insertion, after all nodes+ // and their ownership edges have been written.+ await serverDB.execute(+ sql`ALTER TABLE goal_edges ADD CONSTRAINT fail_planning_dependency CHECK (kind <> 'depends_on')`,+ );+ try {+ await expect(service.tick(graph.goal.id)).rejects.toThrow();+ } finally {+ await serverDB.execute(sql`ALTER TABLE goal_edges DROP CONSTRAINT fail_planning_dependency`);+ }+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.map((node) => node.id)).toEqual(graph.nodes.map((node) => node.id));+ expect(after.nodes[0].description).toBe('Original question');+ expect(after.edges).toHaveLength(0);+ expect(+ after.events.filter((event) => event.entityType === 'node' && event.eventType === 'created'),+ ).toHaveLength(1);++ await service.tick(graph.goal.id);+ const retried = await service.graph(graph.goal.id);+ expect(retried.nodes.filter((node) => node.kind === 'task')).toHaveLength(2);+ expect(retried.edges.filter((edge) => edge.kind === 'depends_on')).toHaveLength(1);+ });++ it('falls back to a single Task when the planner fails, instead of stalling', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockRejectedValue(+ new Error('model unavailable'),+ );+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ problemDescription: 'ๅ่ฏ', title: 'Nothing to do' });++ const result = await service.tick(graph.goal.id);++ expect(result.outcome).toBe('advanced');+ const tasks = (await service.graph(graph.goal.id)).nodes.filter((n) => n.kind === 'task');+ expect(tasks).toHaveLength(1);+ expect(tasks[0].description).toBe('ๅ่ฏ');+ });++ it('parks a goal nothing can move so the sweep stops re-picking it', async () => {+ // Every remaining Task is blocked and nothing runs to unblock it. Left+ // `running` it is selected by every newest-first scan forever, and enough+ // of them starve every other stalled goal out of the sweep's window.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['A', 'B'], title: 'Deadlocked' });+ const [a, b] = graph.nodes.filter((n) => n.kind === 'task');+ const graphModel = new GoalGraphModel(serverDB, userId);+ await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');+ await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');++ const result = await service.tick(graph.goal.id);++ expect(result.outcome).toBe('no_progress');+ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');+ expect(+ await GoalModel.listStalled(serverDB, { staleBefore: new Date(Date.now() - 60_000) }),+ ).not.toContainEqual(expect.objectContaining({ id: graph.goal.id }));+ });++ it('leaves goal-level status transitions on the event trail', async () => {+ // The coordinator parks and reopens goals constantly, but only node+ // transitions used to be recorded โ `entity_type='goal'` events existed in+ // the schema with no writer, so the lifecycle timeline was unreconstructable.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['A', 'B'], title: 'Lifecycle trail' });+ const [a, b] = graph.nodes.filter((n) => n.kind === 'task');+ const graphModel = new GoalGraphModel(serverDB, userId);+ await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');+ await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');++ await service.tick(graph.goal.id); // deadlock โ no_frontier โ paused+ await service.resume(graph.goal.id); // paused โ running++ const lifecycle = (await service.graph(graph.goal.id)).events.filter(+ (event) => event.entityType === 'goal',+ );++ // Same-millisecond events read back in either order; assert on content.+ expect(lifecycle).toHaveLength(2);+ expect(lifecycle).toContainEqual(+ expect.objectContaining({+ actorType: 'system',+ eventType: 'updated',+ reason: 'no eligible task to advance',+ }),+ );+ expect(lifecycle).toContainEqual(+ expect.objectContaining({ eventType: 'activated', reason: 'resumed by user' }),+ );+ });++ it('reopens a goal its deadline stopped when the deadline moves out', async () => {+ // A calendar deadline is the long-horizon budget unit; extending it has to+ // unstick the goal exactly like raising a round budget does. Two ticks:+ // creating the responsible task costs nothing, the deadline gates the run.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { schedule: { deadline: new Date(Date.now() - 1000).toISOString() } },+ title: 'Overdue',+ tasks: ['Too late to start'],+ });++ await service.tick(graph.goal.id); // creates the responsible task+ const stopped = await service.tick(graph.goal.id);+ expect(stopped.message).toContain('Deadline passed');+ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');++ const extended = await service.setBudget(graph.goal.id, {+ deadline: new Date(Date.now() + 3_600_000).toISOString(),+ });++ expect(extended?.status).not.toBe('paused');+ expect(extended?.config?.schedule?.deadline).toBeTruthy();+ });++ it('dispatches a Task when the goal has no deadline', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Just task'], title: 'No deadline' });++ const result = await service.tick(graph.goal.id);++ expect(result.outcome).toBe('advanced');+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/recovery.test.ts b/apps/server/src/services/goal/GoalService/__tests__/recovery.test.tsnew file mode 100644index 00000000000..46f2a851cf8--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/recovery.test.ts@@ -0,0 +1,610 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { GoalModel } from '@/database/models/goal';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { agentOperations, tasks } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';++import { TaskRunnerService } from '../../../taskRunner';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import type { GoalTickObservation } from '../../traceObservation';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ it('evolves a failed task into a durable decision gate', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Risky task'], title: 'Failure recovery' });+ const created = await service.tick(graph.goal.id);++ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });+ const waiting = await service.tick(graph.goal.id);+ expect(waiting.outcome).toBe('waiting_human');++ const gated = await service.graph(graph.goal.id);+ const decision = gated.decisions[0];+ expect(decision).toMatchObject({ recommendedOptionId: 'retry', status: 'pending' });+ expect(gated.nodes.some((node) => node.kind === 'decision')).toBe(true);++ await service.decide(graph.goal.id, decision.id, 'retire', 'This branch is not useful');+ const achieved = await service.tick(graph.goal.id);+ expect(achieved.outcome).toBe('achieved');+ });++ it('reports the effects a tick actually produced, not just its outcome', async () => {+ // The rollup counts gates and findings from these effects, so a branch that+ // forgets to report one reads as "no human was ever involved" โ silently,+ // and only in the trace. Driving the real path is the only thing that+ // catches it; a synthetic observation always agrees with itself.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Risky task'], title: 'Effect reporting' });++ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });++ const observed: GoalTickObservation[] = [];+ const gated = await service.tick(graph.goal.id, {+ onDecision: (observation) => observed.push(observation),+ });++ expect(gated.outcome).toBe('waiting_human');+ expect(observed.at(-1)!.effects).toContainEqual(+ expect.objectContaining({ detail: 'Verifier rejected output', type: 'opened_decision' }),+ );++ // And the other half: a completed task folds into a finding, which is what+ // `findingsTotal` counts.+ const decision = (await service.graph(graph.goal.id)).decisions[0];+ await service.decide(graph.goal.id, decision.id, 'retry');+ await taskModel.updateStatus(created.taskId!, 'completed');++ const consumed: GoalTickObservation[] = [];+ await service.tick(graph.goal.id, { onDecision: (o) => consumed.push(o) });++ expect(consumed.at(-1)!.effects).toContainEqual(+ expect.objectContaining({ detail: 'finding', type: 'created_node' }),+ );+ });++ it('refuses to start a task once the goal is at its concurrency limit', async () => {+ // The planner's cap check is a fast path over a snapshot; two overlapping+ // advances can both read it below the limit. The count and the claim are+ // therefore taken together under a per-goal lock, and this is the assertion+ // that the enforcement โ not the fast path โ is what holds.+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-cap', taskId: 'placeholder' } as never);++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { maxConcurrentTasks: 1 },+ title: 'Capped goal',+ tasks: ['First', 'Second'],+ });++ // Fill the single slot.+ const first = await service.tick(graph.goal.id);+ await service.tick(graph.goal.id);+ await taskModel.updateStatus(first.taskId!, 'running');+ runSpy.mockClear();++ // The second task exists and is unblocked, but there is no room for it.+ const capped = await service.tick(graph.goal.id);++ expect(capped.outcome).toBe('waiting_external');+ expect(runSpy).not.toHaveBeenCalled();+ });++ it('automatically retries failed Task verification within policy budget', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({+ agentId: 'agent-recovery',+ assistantMessageId: 'message-assistant',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'started',+ operationId: 'op-recovery',+ status: 'running',+ success: true,+ taskId: 'placeholder',+ taskIdentifier: 'T-recovery',+ timestamp: new Date().toISOString(),+ topicId: 'topic-recovery',+ userMessageId: 'message-user',+ });+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: {+ exploration: { instruction: 'Compare evidence', maxExperiments: 3 },+ recovery: { maxAttemptsPerTask: 3, maxStepsPerRun: 500 },+ },+ title: 'Recover BW 150 research',+ tasks: ['Verify Micron BW 150 suppliers'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: 'Delivery did not pass verification.',+ });++ const recovered = await service.tick(graph.goal.id);++ expect(recovered).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ expect(runSpy).toHaveBeenCalledWith({+ maxSteps: 500,+ taskId: created.taskId,+ trigger: 'goal',+ });+ const afterRetry = await service.graph(graph.goal.id);+ expect(afterRetry.decisions).toHaveLength(0);+ expect(afterRetry.nodes.filter((node) => node.kind === 'task')).toEqual([+ expect.objectContaining({ id: created.nodeId, taskId: created.taskId }),+ ]);+ expect(afterRetry.edges.filter((edge) => edge.kind === 'derived_from')).toHaveLength(0);+ });++ it('reclaims a stale running Task operation and starts the next attempt', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({+ agentId: 'agent-recovery',+ assistantMessageId: 'message-assistant',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'started',+ operationId: 'op-recovery',+ status: 'running',+ success: true,+ taskId: 'placeholder',+ taskIdentifier: 'T-recovery',+ timestamp: new Date().toISOString(),+ topicId: 'topic-recovery',+ userMessageId: 'message-user',+ });+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ { operationId: 'op-stale', topicId: 'topic-stale' } as never,+ ]);+ const timeoutSpy = vi+ .spyOn(TaskTopicModel.prototype, 'updateStatus')+ .mockResolvedValue(undefined);+ const settleSpy = vi+ .spyOn(AgentOperationModel.prototype, 'settleStaleRunning')+ .mockResolvedValue(true);++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: {+ recovery: { maxAttemptsPerTask: 3, operationLeaseTimeoutMs: 60_000 },+ },+ title: 'Recover interrupted work',+ tasks: ['Run a durable experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'running');++ const recovered = await service.tick(graph.goal.id);++ expect(settleSpy).toHaveBeenCalledWith('op-stale', expect.any(Date), undefined);+ expect(timeoutSpy).toHaveBeenCalledWith(created.taskId, 'topic-stale', 'timeout');+ expect(runSpy).toHaveBeenCalledWith({+ maxSteps: undefined,+ taskId: created.taskId,+ trigger: 'goal',+ });+ expect(recovered).toMatchObject({+ message: expect.stringContaining('Recovered abandoned task'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ });++ it('charges stale Task usage before checking the replacement budget', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ { operationId: 'op-stale-cost', topicId: 'topic-stale-cost' } as never,+ ]);+ vi.spyOn(TaskTopicModel.prototype, 'updateStatus').mockResolvedValue(undefined);+ vi.spyOn(AgentRuntimeCoordinator.prototype, 'getOperationMetadata').mockResolvedValue({+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ status: 'running',+ totalCost: 0.75,+ totalSteps: 2,+ });++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3, operationLeaseTimeoutMs: 60_000 } },+ maxTotalCost: 0.5,+ title: 'Respect abandoned Work cost',+ tasks: ['Run an expensive experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'running');+ await new AgentOperationModel(serverDB, userId).recordStart({+ operationId: 'op-stale-cost',+ taskId: created.taskId,+ });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, 'op-stale-cost'));++ const recovered = await service.tick(graph.goal.id);++ expect(runSpy).not.toHaveBeenCalled();+ expect(recovered).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ expect(await new AgentOperationModel(serverDB, userId).findById('op-stale-cost')).toMatchObject(+ {+ status: 'abandoned',+ totalCost: 0.75,+ },+ );+ });++ describe('a running topic whose run already ended', () => {+ const setup = async (title: string, operationId: string, completedAt: Date) => {+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-next', success: true } as never);+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ {+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ operationId,+ topicId: `topic-${operationId}`,+ } as never,+ ]);+ const timeoutSpy = vi+ .spyOn(TaskTopicModel.prototype, 'updateStatus')+ .mockResolvedValue(undefined);++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3, operationLeaseTimeoutMs: 60_000 } },+ title,+ tasks: ['Run a device experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'running');++ // The gateway watchdog already settled the run as an error, but the task+ // lifecycle never heard about it, so the topic still reads `running`.+ const operationModel = new AgentOperationModel(serverDB, userId);+ await operationModel.recordStart({ operationId, taskId: created.taskId });+ await operationModel.recordCompletion(operationId, {+ completedAt,+ completionReason: 'error',+ status: 'error',+ });++ return { created, graph, runSpy, service, timeoutSpy };+ };++ it('reclaims it once the run has been over for longer than the lease', async () => {+ const { created, graph, runSpy, service, timeoutSpy } = await setup(+ 'Recover a watchdog-abandoned run',+ 'op-abandoned',+ new Date('2026-01-01T00:10:00.000Z'),+ );++ const recovered = await service.tick(graph.goal.id);++ expect(timeoutSpy).toHaveBeenCalledWith(created.taskId, 'topic-op-abandoned', 'timeout');+ expect(runSpy).toHaveBeenCalledWith(+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),+ );+ expect(recovered).toMatchObject({+ message: expect.stringContaining('Recovered abandoned task'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ });++ it('leaves a run parked for a client alone however long it has waited', async () => {+ const { created, graph, runSpy, service, timeoutSpy } = await setup(+ 'Wait for a local-model client',+ 'op-waiting-client',+ new Date('2026-01-01T00:10:00.000Z'),+ );+ // Parked in waiting_for_client (U4c): resumable until its own expiry.+ await serverDB+ .update(agentOperations)+ .set({ completionReason: 'waiting_for_client', status: 'waiting_for_client' })+ .where(eq(agentOperations.id, 'op-waiting-client'));++ const waiting = await service.tick(graph.goal.id);++ expect(timeoutSpy).not.toHaveBeenCalled();+ expect(runSpy).not.toHaveBeenCalled();+ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ });++ it('leaves a run that just ended to its own completion hook', async () => {+ const { created, graph, runSpy, service, timeoutSpy } = await setup(+ 'Wait for the completion hook',+ 'op-just-ended',+ new Date(),+ );++ const waiting = await service.tick(graph.goal.id);++ expect(timeoutSpy).not.toHaveBeenCalled();+ expect(runSpy).not.toHaveBeenCalled();+ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ });+ });++ it('does not reclaim a running Task operation without a persisted topic id', async () => {+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ { operationId: 'op-without-topic', topicId: null } as never,+ ]);+ const settleSpy = vi.spyOn(AgentOperationModel.prototype, 'settleStaleRunning');++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },+ title: 'Wait for topic persistence',+ tasks: ['Run a durable experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'running');++ const waiting = await service.tick(graph.goal.id);++ expect(settleSpy).not.toHaveBeenCalled();+ expect(waiting).toMatchObject({+ message: expect.stringContaining('is running'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ });++ it('starts a ready sibling Task even when a running Task row is older than the operation lease', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },+ title: 'Keep parallel work moving',+ tasks: ['Long-running experiment', 'Independent analysis'],+ });+ const running = await service.tick(graph.goal.id);+ await taskModel.updateStatus(running.taskId!, 'running');+ await serverDB+ .update(tasks)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(tasks.id, running.taskId!));++ const sibling = await service.tick(graph.goal.id);++ expect(sibling).toMatchObject({ outcome: 'advanced' });+ expect(sibling.taskId).not.toBe(running.taskId);+ });++ it('rolls back the operation reclaim when recovery bookkeeping fails', async () => {+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ { operationId: 'op-atomic-recovery', topicId: 'topic-stale' } as never,+ ]);+ vi.spyOn(TaskTopicModel.prototype, 'updateStatus').mockRejectedValueOnce(+ new Error('topic update failed'),+ );++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const operationModel = new AgentOperationModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },+ title: 'Atomic abandoned recovery',+ tasks: ['Run a durable experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'running');+ await operationModel.recordStart({ operationId: 'op-atomic-recovery' });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, 'op-atomic-recovery'));++ await expect(service.tick(graph.goal.id)).rejects.toThrow('topic update failed');++ expect((await operationModel.findById('op-atomic-recovery'))?.status).toBe('running');+ expect((await taskModel.findById(created.taskId!))?.status).toBe('running');+ });++ it('resumes automatic recovery after the atomic bookkeeping transaction committed', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({+ agentId: 'agent-recovery',+ assistantMessageId: 'message-assistant',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'started',+ operationId: 'op-recovery-next',+ status: 'running',+ success: true,+ taskId: 'placeholder',+ taskIdentifier: 'T-recovery',+ timestamp: new Date().toISOString(),+ topicId: 'topic-recovery-next',+ userMessageId: 'message-user',+ });+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3 } },+ title: 'Resume abandoned recovery',+ tasks: ['Run a durable experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: 'Goal Task operation lease expired.',+ });++ const recovered = await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledOnce();+ expect(recovered).toMatchObject({+ message: expect.stringContaining('Recovered abandoned task'),+ outcome: 'waiting_external',+ });+ });++ it('opens the decision gate only after the Task attempt budget is exhausted', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 1 } },+ title: 'Bounded recovery',+ tasks: ['Verify Micron BW 150 suppliers'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: 'Delivery did not pass verification.',+ });++ const waiting = await service.tick(graph.goal.id);++ expect(waiting.outcome).toBe('waiting_human');+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(1);+ });++ it('fails the Goal when terminal acceptance is retired after recovery is exhausted', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 1 } },+ requirement: 'Return three verified supplier quotes.',+ title: 'Bounded terminal acceptance',+ tasks: ['Complete full Goal acceptance'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: 'Delivery did not pass verification.',+ });+ await service.tick(graph.goal.id);+ const gated = await service.graph(graph.goal.id);++ expect(gated.decisions[0].options).toContainEqual({ id: 'fail', label: 'Fail goal' });+ await service.decide(graph.goal.id, gated.decisions[0].id, 'fail', 'No valid third quote');++ expect(await service.tick(graph.goal.id)).toMatchObject({ outcome: 'failed' });+ expect((await service.graph(graph.goal.id)).goal.status).toBe('failed');+ });++ it('offers retry, abandon and fail on a failed terminal acceptance; abandon cancels the Goal', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 1 } },+ requirement: 'Return three verified supplier quotes.',+ title: 'Abandoned terminal acceptance',+ tasks: ['Complete full Goal acceptance'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: 'Delivery did not pass verification.',+ });+ await service.tick(graph.goal.id);+ const gated = await service.graph(graph.goal.id);++ expect(gated.decisions[0].options?.map((option) => option.id)).toEqual([+ 'retry',+ 'retire',+ 'fail',+ ]);+ await service.decide(graph.goal.id, gated.decisions[0].id, 'retire');++ const after = await service.graph(graph.goal.id);+ expect(after.goal.status).toBe('canceled');+ expect(after.nodes.find((node) => node.taskId === created.taskId)?.status).toBe('retired');+ });++ it('reopens an achieved Goal when its owner requests changes, and reworks the acceptance', async () => {+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ requirement: 'A one-page onboarding checklist',+ title: 'Reworked delivery',+ tasks: ['Draft the checklist'],+ });+ const work = await service.tick(graph.goal.id);+ await taskModel.updateStatus(work.taskId!, 'completed');+ await service.tick(graph.goal.id);+ await service.tick(graph.goal.id);+ const acceptance = await service.tick(graph.goal.id);+ await taskModel.updateStatus(acceptance.taskId!, 'completed');+ await service.tick(graph.goal.id);+ expect((await service.tick(graph.goal.id)).outcome).toBe('achieved');++ const reopened = await service.reopenForChanges(acceptance.taskId!, 'Add a day-one agenda');++ expect(reopened).toBe(graph.goal.id);+ const after = await service.graph(graph.goal.id);+ expect(after.goal.status).toBe('running');+ expect(after.goal.completedAt).toBeNull();+ expect(after.goal.config?.changeRequest).toMatchObject({+ comment: 'Add a day-one agenda',+ taskId: acceptance.taskId,+ });+ expect(after.nodes.find((node) => node.taskId === acceptance.taskId)?.status).toBe('active');+ expect((await taskModel.findById(acceptance.taskId!))?.status).toBe('backlog');++ // The coordinator dispatches the rework instead of reading the Goal as done.+ const rework = await service.tick(graph.goal.id);+ expect(rework.message).toMatch(/^Started task /);+ expect(TaskRunnerService.prototype.runTask).toHaveBeenLastCalledWith(+ expect.objectContaining({ taskId: acceptance.taskId }),+ );+ });++ it('does not reopen a Goal the owner already ended', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ requirement: 'A one-page onboarding checklist',+ title: 'Ended delivery',+ tasks: ['Complete full Goal acceptance'],+ });+ const created = await service.tick(graph.goal.id);+ await new GoalModel(serverDB, userId).updateStatus(graph.goal.id, 'canceled');++ expect(await service.reopenForChanges(created.taskId!, 'Too late')).toBeUndefined();+ expect((await service.graph(graph.goal.id)).goal.status).toBe('canceled');+ });++ it('respects a manually paused responsible task without rerunning it', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Wait for review'], title: 'Paused task' });+ const created = await service.tick(graph.goal.id);++ await taskModel.updateStatus(created.taskId!, 'paused', { error: null });+ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({+ outcome: 'waiting_human',+ taskId: created.taskId,+ });+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/rollout.test.ts b/apps/server/src/services/goal/GoalService/__tests__/rollout.test.tsnew file mode 100644index 00000000000..0a3868fd020--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/rollout.test.ts@@ -0,0 +1,485 @@+// @vitest-environment node+import { GOAL_BATCH_ASSAY_TITLE } from '@lobechat/const/goal';+import { eq } from 'drizzle-orm';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { goals } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { UserSkillService } from '../../../userSkill';+import { GoalCriteriaGeneratorService } from '../../criteriaGenerator';+import { approveRelease, registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++describe('GoalService', () => {+ /**+ * Regression: a model titles its probes around the unit โ "่ฟ็งป device store+ * ๏ผๆข้๏ผ" for unit `device` โ and the roster de-duplicated on exact titles,+ * so every probed unit was queued again and would run twice.+ */+ it('does not queue a probed unit again when the probe title wraps its name', async () => {+ const units = Array.from({ length: 12 }, (_, i) => `store${i + 1}`);+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 12 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 12,+ units,+ variants: [],+ },+ tasks: units.slice(0, 3).map((unit) => ({+ dependsOn: [],+ instruction: `ๆ src/store/${unit}.ts ๆขๆ replica ๅฎ็ฐ๏ผๅนถ่กฅๅทๅฏๅจๅๅฝๆต่ฏ`,+ title: `่ฟ็งป ${unit} store๏ผๆข้๏ผ`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate 12 stores' });+ await service.tick(graph.goal.id);++ const roster = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.unitTitles!;+ expect(roster).toHaveLength(12);+ expect(roster.slice(0, 3)).toEqual(units.slice(0, 3).map((u) => `่ฟ็งป ${u} store๏ผๆข้๏ผ`));+ expect(roster.slice(3)).toEqual(units.slice(3));+ });++ it('materializes a fallback roster above the batch cap without trimming it', async () => {+ const units = Array.from({ length: 64 }, (_, i) => `Unit ${i + 1}`);+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 64 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 64,+ units,+ variants: [],+ },+ tasks: Array.from({ length: 3 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { trigger: 'off' } },+ title: 'Migrate stores, no batch',+ });+ await service.tick(graph.goal.id);++ const after = await service.graph(graph.goal.id);+ expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);+ // Every one of the 64 units is planned: the batch config's 60-unit roster+ // cap must never trim the ordinary decomposition.+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(64);+ });++ it('refuses to batch a roster above the cap instead of silently trimming it', async () => {+ const units = Array.from({ length: 64 }, (_, i) => `Unit ${i + 1}`);+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 64 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 64,+ units,+ variants: [],+ },+ tasks: Array.from({ length: 3 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);++ const after = await service.graph(graph.goal.id);+ // A roster the batch cannot carry whole is refused, not truncated: the goal+ // still delivers all 64 units, as plain tasks.+ expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);+ expect(after.goal.config?.rolloutState).toBeUndefined();+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(64);+ });++ it('numbers a release after the waves a batch released before the counter existed', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);+ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ for (const id of state.probeNodeIds)+ await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');+ // A rollout from before this change: two waves out, no counter, no log.+ await goalModel.updateRolloutState(graph.goal.id, {+ ...state,+ gateLog: undefined,+ phase: 'mass',+ waveIndex: 2,+ wavesReleased: undefined,+ });++ await service.tick(graph.goal.id);+ await approveRelease(service, graph.goal.id);+ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ expect(next.gateLog?.at(-1)).toMatchObject({ outcome: 'released', wave: 3 });+ expect(next.wavesReleased).toBe(3);+ });++ it('numbers a release after the waves a batch released before the counter existed, across a restart', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);+ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ for (const id of state.probeNodeIds)+ await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');+ // A rollout from before this change, restarted once: `waveIndex` reset to 0,+ // no counter, no log โ but 20 roster units beyond the first canary are out.+ await goalModel.updateRolloutState(graph.goal.id, {+ ...state,+ gateLog: undefined,+ phase: 'mass',+ releasedCount: state.releasedCount! + 20,+ waveIndex: 0,+ wavesReleased: undefined,+ });++ await service.tick(graph.goal.id);+ await approveRelease(service, graph.goal.id);+ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ // 20 units at the default wave size of 5 are four waves; this one is the fifth.+ expect(next.gateLog?.at(-1)).toMatchObject({ outcome: 'released', wave: 5 });+ expect(next.wavesReleased).toBe(5);+ });++ it('records each gate verdict โ the release and the hold โ with what it checked', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);+ const graphModel = new GoalGraphModel(serverDB, userId);+ const probeIds = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.probeNodeIds;+ for (const id of probeIds) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');++ // The probes settled clean: once the owner approves, the gate releases the+ // first wave and says why.+ await service.tick(graph.goal.id);+ await approveRelease(service, graph.goal.id);+ let state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ expect(state.gateLog).toHaveLength(1);+ expect(state.gateLog![0]).toMatchObject({+ outcome: 'released',+ releasedCount: 5,+ approvedBy: 'user',+ revision: 1,+ trigger: 'gate',+ wave: 1,+ waveIndex: 1,+ });+ expect(state.wavesReleased).toBe(1);+ expect(state.gateLog![0].checks).toContainEqual(+ expect.objectContaining({ count: 5, key: 'units_succeeded', passed: true, total: 5 }),+ );++ // One unit of that wave was rejected: the next verdict holds and names it.+ const [rejected, ...rest] = state.massNodeIds!;+ for (const id of rest) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');+ await graphModel.updateNodeStatus(graph.goal.id, rejected, 'rejected');+ await service.tick(graph.goal.id);+ state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ expect(state.phase).toBe('pattern_break');+ expect(state.gateLog![1]).toMatchObject({ outcome: 'blocked', trigger: 'gate' });+ expect(state.gateLog![1].checks).toContainEqual(+ expect.objectContaining({ key: 'units_succeeded', nodeIds: [rejected], passed: false }),+ );+ });++ it('restarts the canary loop when a person answers a broken batch gate', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);++ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const before = await service.graph(graph.goal.id);+ const state = before.goal.config!.rolloutState!;+ const assayId = state.assayNodeId!;++ // Simulate the break the coordinator opens when a gate blocks.+ const decision = await graphModel.createDecision(graph.goal.id, assayId, {+ authority: 'user',+ options: [+ { description: 'ไฟฎ่ฎข้ ๆน', id: 'revise', label: 'ไฟฎ่ฎข้ ๆนๅนถ้ๆข' },+ { description: 'ๆฐ็ฑปๅ', id: 'new_class', label: 'ไฝไธบๆฐ็ฑปๅๅนถๆๅค็' },+ ],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, assayId, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));++ // R5: the answer itself restarts the loop โ no manual rerun.+ await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ');++ const after = await service.graph(graph.goal.id);+ const next = after.goal.config!.rolloutState!;+ expect(next.phase).toBe('probe');+ expect(next.waveIndex).toBe(0);+ expect(next.templateRevision).toBe(state.templateRevision + 1);+ expect(+ after.edges.some((e) => e.kind === 'revises' && e.sourceNodeId === next.templateNodeId),+ ).toBe(true);+ // A fresh gate and a fresh probe batch: the class is proved again.+ expect(next.assayNodeId).not.toBe(assayId);+ expect(next.probeNodeIds.length).toBeGreaterThan(0);++ // The correction is folded into the batch's recipe and briefs the re-opened+ // probes โ later waves only read `policy.spec.recipeOutline`, so a note kept+ // only on the Template would never reach the tasks meant to test it.+ expect(after.goal.config!.rollout!.spec?.recipeOutline).toContain('่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ');+ // The re-opened probes load the plan skill, whose latest version carries it.+ const openedProbe = after.nodes.find((n) => next.probeNodeIds.includes(n.id))!;+ expect(openedProbe.description).toContain(`user-skills:${next.planSkill!.name}`);+ const skill = await new UserSkillService(serverDB, userId).getSkill(next.planSkill!.id);+ expect(skill?.content).toContain('่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ');+ });++ it('materializes and answers a pattern-break gate on a full rollout', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { trigger: 'full' } },+ title: 'Migrate stores',+ });+ await service.tick(graph.goal.id);++ const before = await service.graph(graph.goal.id);+ const state = before.goal.config!.rolloutState!;+ // A `full` rollout creates no Assay โ it skips the probe gate.+ expect(state.assayNodeId).toBeUndefined();++ // A break still has to be answerable: the coordinator must open the question+ // on a `decision` node even though this trigger made none.+ const openGate = (+ service as unknown as {+ openPatternBreakGate: (g: unknown, message: string, effects: unknown[]) => Promise<unknown>;+ }+ ).openPatternBreakGate.bind(service);+ await openGate(before, 'Unit 1 did not pass', []);++ const after = await service.graph(graph.goal.id);+ const next = after.goal.config!.rolloutState!;+ expect(next.phase).toBe('pattern_break');+ const gateNode = after.nodes.find((n) => n.id === next.assayNodeId);+ expect(gateNode?.kind).toBe('decision');+ const decision = after.decisions.find(+ (item) => item.nodeId === next.assayNodeId && item.status === 'pending',+ );+ expect(decision).toBeDefined();+ // The options carry ids only; labels and consequences are localized on the+ // client by id, so nothing English is persisted into the gate payload.+ expect(decision!.options?.map((option) => option.id)).toEqual(['revise', 'new_class']);+ expect(decision!.options?.every((option) => option.description === undefined)).toBe(true);++ // Answering it restarts the class, rather than leaving the goal parked.+ await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');+ const restarted = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ expect(restarted.phase).toBe('probe');+ expect(restarted.templateRevision).toBe(next.templateRevision + 1);+ // The break must not redispatch the whole 50-unit rollout at once: only a+ // canary re-probes, and the rest stay owed on the re-cut roster for waves.+ expect(restarted.probeNodeIds).toHaveLength(5);+ expect(restarted.releasedCount).toBe(5);+ expect(restarted.unitTitles).toHaveLength(50);+ });++ it('opens one gate when two advances see a full rollout break together', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout: {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { trigger: 'full' } },+ title: 'Migrate stores',+ });+ await service.tick(graph.goal.id);+ const before = await service.graph(graph.goal.id);+ const openGate = (+ service as unknown as {+ openPatternBreakGate: (g: unknown, message: string, effects: unknown[]) => Promise<unknown>;+ }+ ).openPatternBreakGate.bind(service);++ // Both read the same snapshot with no Assay yet.+ await Promise.all([+ openGate(before, 'Unit 1 did not pass', []),+ openGate(before, 'Unit 2 did not pass', []),+ ]);++ // One Assay, one pending question, and it is the one the state records.+ const after = await service.graph(graph.goal.id);+ const next = after.goal.config!.rolloutState!;+ const assays = after.nodes.filter(+ (n) => n.kind === 'decision' && n.title === GOAL_BATCH_ASSAY_TITLE,+ );+ expect(assays).toHaveLength(1);+ const pending = after.decisions.filter((item) => item.status === 'pending');+ expect(pending.map((item) => item.nodeId)).toEqual([next.assayNodeId]);+ });++ it('judges the final wave like any other before closing the batch', async () => {+ const rollout = {+ recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',+ repeatable: true,+ unitCount: 7,+ units: Array.from({ length: 7 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ };+ const tasks = Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,+ title: `Unit ${i + 1}`,+ }));+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: 'ๆ 7 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',+ rollout,+ tasks,+ });+ const graphModel = new GoalGraphModel(serverDB, userId);+ const service = new GoalService(serverDB, userId);++ const releaseFinalWave = async (title: string) => {+ const graph = await service.create({+ config: {+ rollout: { canarySize: 5, minHomogeneousUnits: 5, trigger: 'canary', waveSize: 7 },+ },+ title,+ });+ await service.tick(graph.goal.id);+ const probeIds = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.probeNodeIds;+ for (const id of probeIds) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');+ await service.tick(graph.goal.id);+ await approveRelease(service, graph.goal.id);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ // The last two units went out, and the batch is not closed on release.+ expect(state.massNodeIds).toHaveLength(2);+ expect(state.phase).toBe('mass');+ return { goalId: graph.goal.id, finalWave: state.massNodeIds! };+ };++ // A unit retired from the final wave stops the batch, as in any earlier wave.+ const held = await releaseFinalWave('Final wave with a retired unit');+ await service.retireNodes(held.goalId, [held.finalWave[0]], 'not needed');+ await graphModel.updateNodeStatus(held.goalId, held.finalWave[1], 'resolved');+ await service.tick(held.goalId);+ expect((await service.graph(held.goalId)).goal.config!.rolloutState!.phase).toBe(+ 'pattern_break',+ );++ // A clean final wave closes it.+ const clean = await releaseFinalWave('Final wave delivered');+ for (const id of clean.finalWave)+ await graphModel.updateNodeStatus(clean.goalId, id, 'resolved');+ await service.tick(clean.goalId);+ expect((await service.graph(clean.goalId)).goal.config!.rolloutState!.phase).toBe('done');+ });+});diff --git a/apps/server/src/services/goal/index.seedDependencies.test.ts b/apps/server/src/services/goal/GoalService/__tests__/seedDependencies.test.tssimilarity index 97%rename from apps/server/src/services/goal/index.seedDependencies.test.tsrename to apps/server/src/services/goal/GoalService/__tests__/seedDependencies.test.tsindex f369b3288d8..34c0d5f7ed5 100644--- a/apps/server/src/services/goal/index.seedDependencies.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/seedDependencies.test.ts@@ -5,7 +5,7 @@ import { getTestDB } from '@/database/core/getTestDB';import { goalEdges, goalEvents, goalNodes, goals, users } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';-import { GoalService } from './index';+import { GoalService } from '../index';const serverDB: LobeChatDatabase = await getTestDB();const userId = 'goal-seed-dependencies-user';diff --git a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts b/apps/server/src/services/goal/GoalService/__tests__/surface.test.tsnew file mode 100644index 00000000000..cace3cdbd60--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts@@ -0,0 +1,146 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import type { LobeChatDatabase } from '@/database/type';++import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();++/**+ * Every collaborator the service holds. Tests reach some of them through casts+ * (`goalModel`, `graphModel`), so they stay instance properties.+ */+const FIELDS = [+ 'acceptanceService',+ 'agentModel',+ 'briefs',+ 'coordinatorGraph',+ 'db',+ 'goalModel',+ 'graphModel',+ 'releaseReview',+ 'taskModel',+ 'taskService',+ 'taskTopicModel',+ 'userId',+ 'workModel',+ 'workspaceId',+];++/**+ * Every method, public or private, as an own instance property. Tests and+ * collaborators call or spy on private ones by name (`requireGraph`,+ * `consumeCompletedTask`), so each must stay reachable on the instance and keep+ * routing internal calls through it.+ */+const METHODS = [+ 'addEdge',+ 'addNode',+ 'answerClarifications',+ 'answerReleaseGate',+ 'attachTaskDeliverables',+ 'bindTopic',+ 'buildTaskAcceptanceRequirement',+ 'buildTaskInstruction',+ 'close',+ 'collectAcceptances',+ 'collectAssignees',+ 'collectDeliveredAt',+ 'collectRolloutGate',+ 'collectRunHeartbeats',+ 'consumeCompletedTask',+ 'create',+ 'createFromConversation',+ 'createResponsibleTask',+ 'decide',+ 'delete',+ 'dispatchGoalReport',+ 'dispatchWork',+ 'ensureTaskWorkVersion',+ 'evaluateBudget',+ 'evaluateMetricCriteria',+ 'followGoalAgent',+ 'gateOrTakeOver',+ 'goalOwnerTaskScope',+ 'graph',+ 'graphAs',+ 'handPlanningToMainAgent',+ 'holdForMachineFailure',+ 'holdForOfflineDevice',+ 'isBatchMember',+ 'isParkedOnMeasuredGate',+ 'listEvents',+ 'markRunLostToOfflineDevice',+ 'openFailureDecision',+ 'openFailureDecisionLocked',+ 'openPatternBreakGate',+ 'pause',+ 'pendingClarifications',+ 'pendingForIsland',+ 'planDecomposition',+ 'planMachineRecoveryFor',+ 'readRunDevicePresence',+ 'reassignUnfinishedTasks',+ 'recordObservation',+ 'recoverAbandonedTask',+ 'recoverAfterVerification',+ 'recoverLostRun',+ 'reopenForChanges',+ 'reopenIfMeasurementCleared',+ 'requestSignOff',+ 'requireGraph',+ 'resolveSpend',+ 'resolveTaskAssignee',+ 'resolveTopicRun',+ 'restart',+ 'restartRolloutLoop',+ 'resume',+ 'resumeAbandonedTaskRecovery',+ 'retireNodes',+ 'setAcceptanceCriteria',+ 'setAgent',+ 'setBudget',+ 'setMetricCriteria',+ 'setPauseReason',+ 'setTaskAgent',+ 'settleTerminalAcceptance',+ 'status',+ 'stopFencedTasks',+ 'tick',+ 'tickOnce',+ 'transitionStatus',+ 'updateRequirement',+ 'waitForDevice',+ 'waitForQuotaReset',+];++describe('GoalService instance surface', () => {+ const service = new GoalService(serverDB, 'goal-surface-user', 'goal-surface-workspace');+ const members = service as unknown as Record<string, unknown>;++ it('holds exactly the expected fields and methods as own properties', () => {+ expect(Object.keys(service).sort()).toEqual([...FIELDS, ...METHODS].sort());+ });++ it.each(METHODS)('%s is a bound instance function', (name) => {+ expect(typeof members[name]).toBe('function');+ expect(Object.prototype.hasOwnProperty.call(service, name)).toBe(true);+ });++ it('keeps the constructor arguments on the instance', () => {+ expect(members.db).toBe(serverDB);+ expect(members.userId).toBe('goal-surface-user');+ expect(members.workspaceId).toBe('goal-surface-workspace');+ });++ it('routes internal calls through the instance, so a spy on a private method sees them', async () => {+ const requireGraph = vi+ .spyOn(members as { requireGraph: (id: string) => Promise<unknown> }, 'requireGraph')+ .mockRejectedValue(new Error('spied'));+ await expect(service.tick('goal-that-does-not-exist')).rejects.toThrow('spied');+ expect(requireGraph).toHaveBeenCalledWith('goal-that-does-not-exist');+ requireGraph.mockRestore();+ });+});diff --git a/apps/server/src/services/goal/GoalService/completion.ts b/apps/server/src/services/goal/GoalService/completion.tsnew file mode 100644index 00000000000..8cac6497dd9--- /dev/null+++ b/apps/server/src/services/goal/GoalService/completion.ts@@ -0,0 +1,464 @@+import type { GoalAdvanceEffect } from '@lobechat/agent-tracing';+import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';+import type {+ GoalGraphSnapshot,+ GoalTickResult,+ TaskItem,+ TaskTopicHandoff,+ WorkVersionEventItem,+} from '@lobechat/types';+import { experimentOwner } from '@lobechat/utils/goalGraph';++import { GoalGraphModel } from '@/database/models/goalGraph';++import {+ GOAL_ACCEPTANCE_TASK_TITLE,+ type GoalMove,+ TERMINAL_NODE_STATUSES,+} from '../decideNextMove';+import { GoalSupervisorService } from '../supervisor';+import { TaskRecoveryCoordinator } from '../taskRecoveryCoordinator';+import type { GoalServiceContext } from './types';++/**+ * Version events read per task run when harvesting deliverables. Generous+ * because the cap applies to events rather than to Works: the newest N events+ * of a run must still contain every Work it produced, even one revised many+ * times over.+ */+const DELIVERABLE_EVENTS_PER_RUN = 200;++/**+ * Create the Goal-level acceptance Task, or read the verdict it already+ * reached. Only runs once every other Task is terminal.+ */+export const settleTerminalAcceptance = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ move: GoalMove,+ effects: GoalAdvanceEffect[],+): Promise<GoalTickResult> => {+ const goalId = graph.goal.id;++ if (move.outcome === 'achieved') {+ // The map must agree with the verdict: only task nodes get resolved as+ // Tasks complete, so without this the seeded problem nodes would read+ // "active / unanswered" forever on an achieved goal.+ for (const node of graph.nodes) {+ if (node.kind !== 'problem' || TERMINAL_NODE_STATUSES.has(node.status)) continue;+ await ctx.coordinatorGraph.updateNodeStatus(goalId, node.id, 'resolved', 'Goal achieved');+ effects.push({ detail: 'resolved', nodeId: node.id, type: 'node_status' });+ }+ // Ask for the sign-off before the goal turns terminal: nothing ticks an+ // achieved goal again, so a failed write after the transition would lose+ // the ask for good. Failing here leaves the goal open for the next tick,+ // and the write is idempotent per acceptance.+ await ctx.requestSignOff(graph);+ await ctx.transitionStatus(graph.goal, 'achieved', 'Goal-level acceptance passed');+ effects.push({ type: 'goal_status', detail: 'achieved' });+ return { goalId, message: move.message, outcome: 'achieved' };+ }++ if (move.outcome === 'no_progress') {+ return { goalId, message: move.message, nodeId: move.focusNodeId, outcome: 'no_progress' };+ }++ // 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 ctx.db.transaction(async (tx) => {+ const writer = new GoalGraphModel(tx, ctx.userId, ctx.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.+ // An experiment's Tasks are a candidate answer and stay inside it; a+ // batch's units ARE the delivered work, so they count as leaves too โ+ // otherwise the report, which walks back from acceptance, never sees them.+ const ownerKind = (nodeId: string) => {+ const owner = experimentOwner(graph, nodeId);+ return owner ? graph.nodes.find((node) => node.id === owner)?.kind : undefined;+ };+ const delivered = graph.nodes.filter((node) => {+ if (node.kind !== 'task' || node.status !== 'resolved' || node.id === created.node.id)+ return false;+ const kind = ownerKind(node.id);+ return !kind || kind === 'batch';+ });+ 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 {+ goalId,+ message: 'Could not create the Goal-level acceptance Task',+ outcome: 'no_progress',+ };+ }+ if (result.created) {+ effects.push({ nodeId: result.node.id, type: 'created_node', detail: 'terminal acceptance' });+ }+ return {+ goalId,+ message: result.created+ ? 'Created Goal-level acceptance Task for the remaining contract'+ : 'Goal-level acceptance Task was created by another coordinator',+ nodeId: result.node.id,+ outcome: 'advanced',+ };+};++/**+ * Automatic recovery after a Task delivery failed verification. Spends the+ * Task's remaining attempt budget before it escalates to a person.+ */+export const recoverAfterVerification = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ effects: GoalAdvanceEffect[],+): Promise<GoalTickResult> => {+ const goalId = graph.goal.id;+ const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));+ const runs = await ctx.taskTopicModel.findWithHandoffByTaskIds(taskIds, 10_000);+ const totalCost = runs.reduce((sum, run) => sum + Number(run.totalCost ?? 0), 0);+ const recovery = await new TaskRecoveryCoordinator(ctx.db, ctx.userId, ctx.workspaceId).recover({+ goal: graph.goal,+ spentCost: totalCost,+ task,+ });++ if (recovery.outcome === 'started' || recovery.outcome === 'already-running') {+ await ctx.coordinatorGraph.updateNodeStatus(+ goalId,+ nodeId,+ 'active',+ 'Automatically started the next Task attempt after verification feedback',+ );+ await ctx.transitionStatus(graph.goal, 'running', 'automatic recovery started a run');+ // Only when this advance is the one that spawned the run. Reporting it+ // for a retry another advance owns would put a run in this trajectory+ // that it did not start, and attribute its cost here.+ if (recovery.outcome === 'started') {+ effects.push({+ detail: 'verification retry',+ nodeId,+ operationId: recovery.operationId,+ targetId: task.id,+ type: 'started_run',+ });+ }+ return {+ goalId,+ message: `Automatically retried task ${task.identifier}`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }++ // The retry never reached a device. The Task keeps that reason, and the next+ // advance waits for the device to come back rather than asking a person.+ if (recovery.outcome === 'spawn-failed' && recovery.deviceUnavailable) {+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} is waiting for its device to reconnect`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }++ // The goal was paused or ended (a close fenced it) while this advance was+ // deciding: start nothing and do not reopen it.+ if (recovery.outcome === 'goal-stopped') {+ return {+ goalId: graph.goal.id,+ message: 'Goal stopped while recovery was being decided',+ nodeId,+ outcome: 'no_progress',+ taskId: task.id,+ };+ }++ // Nothing failed: somebody settled the Task while this advance was deciding.+ // Opening a gate would ask them to judge their own decision.+ if (recovery.outcome === 'settled') {+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} was settled while recovery was being decided`,+ nodeId,+ outcome: 'no_progress',+ taskId: task.id,+ };+ }+ const exhaustedReason =+ recovery.outcome === 'exhausted-cost'+ ? 'Goal cost budget was exhausted'+ : recovery.outcome === 'exhausted-rounds'+ ? 'Task attempt budget was exhausted'+ : 'Automatic recovery could not start the next attempt';+ // R6: a batch member that ran out of attempts to pass its own check breaks+ // the class, like one that failed outright โ revise the recipe and re-probe,+ // not a standalone retry/retire gate (retiring a last-wave member would let+ // the goal head for acceptance with the unit undone). A spent goal budget+ // and a run that never started are not the recipe's fault: those keep the+ // ordinary gate.+ if (+ recovery.outcome !== 'exhausted-cost' &&+ recovery.outcome !== 'spawn-failed' &&+ ctx.isBatchMember(graph, nodeId)+ ) {+ const title = graph.nodes.find((node) => node.id === nodeId)?.title ?? task.identifier;+ return ctx.openPatternBreakGate(graph, `${title}: ${exhaustedReason}`, effects, {+ unitId: nodeId,+ });+ }+ return ctx.gateOrTakeOver(graph, nodeId, task.id, exhaustedReason, effects, {+ machine: recovery.outcome === 'spawn-failed',+ });+};++/**+ * Link what a task actually delivered to the node that ordered it.+ *+ * The task Work attached alongside is the execution container; these are its+ * outputs โ the documents and external resources the run registered. Without+ * them the graph records that a task finished but not what it produced, and+ * the deliverable survives only as a URL buried in the finding's prose.+ *+ * Harvested across every run of the task, not just the delivering one: a task+ * that wrote its document in an earlier round and only revised it in the last+ * still delivered that document. Works are deduplicated by identity and+ * 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+ * file), but a goal's deliverables are exactly where a produced deck or PDF+ * belongs, so they are requested explicitly here.+ */+export const attachTaskDeliverables = async (+ ctx: GoalServiceContext,+ goalId: string,+ nodeId: string,+ operationIds: string[],+ effects: GoalAdvanceEffect[],+) => {+ if (operationIds.length === 0) return;++ // The per-operation cap is applied to version EVENTS before this dedupes by+ // Work identity, so the default of 20 lets a document revised twenty times+ // push every other deliverable out of its own task's list.+ const byOperation = await ctx.workModel.listByRootOperations({+ includeFileWorks: true,+ limit: DELIVERABLE_EVENTS_PER_RUN,+ rootOperationIds: operationIds,+ });++ const claimedWorkIds = await ctx.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 = 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 [workId, { created, item }] of harvestByWork) {+ if (!created || claimedWorkIds.has(workId)) continue;+ const link = await ctx.coordinatorGraph.attachWorkVersion(+ goalId,+ nodeId,+ item.version.id,+ 'produced',+ );+ // `attachWorkVersion` is idempotent, so a re-settled task re-links the+ // same versions silently; only a genuinely new link is worth an effect.+ if (link)+ effects.push({+ detail: item.type,+ nodeId,+ targetId: item.id,+ type: 'attached_work_version',+ });+ }+};++export const consumeCompletedTask = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ taskId: string,+ effects: GoalAdvanceEffect[] = [],+): Promise<GoalTickResult> => {+ // `graph` can predate a retirement that landed while this tick ran. A+ // retired node's late output must not enter the Goal as a finding or+ // deliverable (and `updateNodeStatus` refuses to revive the node).+ if ((await ctx.coordinatorGraph.getNodeStatus(graph.goal.id, nodeId)) === 'retired') {+ return {+ goalId: graph.goal.id,+ message: 'Node was retired; the task outcome is discarded',+ nodeId,+ outcome: 'no_progress',+ taskId,+ };+ }+ const existingFinding = graph.edges.some(+ (edge) => edge.sourceNodeId === nodeId && edge.kind === 'produces',+ );+ // The newest row by seq can be a retry that was canceled when verification+ // accepted an earlier delivery โ the settle path cancels the in-flight+ // attempt it superseded. The finding must be synthesized from the run that+ // actually delivered, so prefer the newest completed topic (with a handoff+ // when one exists) over whatever happens to be last.+ const recent = await ctx.taskTopicModel.findWithHandoff(taskId, 10);+ const latest =+ recent.find((topic) => topic.status === 'completed' && topic.handoff) ??+ recent.find((topic) => topic.status === 'completed') ??+ recent[0];+ const completedWork = await ctx.workModel.registerTask({+ changeType: 'updated',+ rootOperationId: latest?.operationId,+ taskId,+ toolIdentifier: 'goal-coordinator',+ toolName: 'synthesizeTaskOutcome',+ topicId: latest?.topicId,+ });+ effects.push({+ nodeId,+ operationId: latest?.operationId ?? undefined,+ targetId: taskId,+ type: 'node_status',+ detail: 'resolved',+ });+ // 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 ctx.coordinatorGraph.attachWorkVersion(+ graph.goal.id,+ nodeId,+ completedWork.currentVersionId,+ 'produced',+ );+ }+ // Every run of the task, not the ten `findWithHandoff` reads for the+ // finding: an attempt budget above ten would otherwise strand a deliverable+ // produced early and merely referenced later.+ const allRuns = await ctx.taskTopicModel.findByTaskId(taskId);+ await ctx.attachTaskDeliverables(+ graph.goal.id,+ nodeId,+ allRuns.flatMap((topic) => (topic.operationId ? [topic.operationId] : [])),+ effects,+ );+ if (!existingFinding) {+ const handoff = latest?.handoff as TaskTopicHandoff | null;+ const title =+ handoff?.title ??+ handoff?.summary ??+ `Completed: ${graph.nodes.find((node) => node.id === nodeId)?.title}`;+ // The finding is written by whoever did the work. Recorded as the owner,+ // it read as something the person had said themselves.+ const author = (await ctx.taskModel.findById(taskId))?.assigneeAgentId ?? graph.goal.agentId;+ const finding = await ctx.coordinatorGraph.createNode(graph.goal.id, {+ confidence: 1,+ createdByAgentId: author ?? undefined,+ description: handoff?.content ?? handoff?.summary ?? undefined,+ kind: 'finding',+ scopeId: experimentOwner(graph, nodeId),+ status: 'resolved',+ title,+ });+ if (finding) {+ effects.push({ detail: 'finding', nodeId, targetId: finding.id, type: 'created_node' });+ await ctx.coordinatorGraph.createEdge(graph.goal.id, nodeId, finding.id, 'produces');+ }+ }+ await ctx.coordinatorGraph.updateNodeStatus(+ graph.goal.id,+ nodeId,+ 'resolved',+ 'Responsible task completed',+ );+ await new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).recordProgress(+ graph,+ taskId,+ false,+ latest?.status === 'completed' ? (latest.operationId ?? undefined) : undefined,+ );+ return {+ goalId: graph.goal.id,+ message: 'Task outcome was synthesized into a finding',+ nodeId,+ outcome: 'advanced',+ taskId,+ };+};diff --git a/apps/server/src/services/goal/GoalService/creation.ts b/apps/server/src/services/goal/GoalService/creation.tsnew file mode 100644index 00000000000..c4a40ba7730--- /dev/null+++ b/apps/server/src/services/goal/GoalService/creation.ts@@ -0,0 +1,358 @@+import { buildGoalRequirement } from '@lobechat/builtin-tool-goal';+import type { GoalConfig, GoalGraphSnapshot } from '@lobechat/types';+import { goalSeedDependencyProblem } from '@lobechat/utils/goalSeeds';+import { TRPCError } from '@trpc/server';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { ProjectModel } from '@/database/models/project';+import { TopicModel } from '@/database/models/topic';+import { assertAgentUsableBy } from '@/database/utils/agent-access';++import { VerifyPlanGeneratorService } from '../../verify/planGenerator';+import { GoalManagerService } from '../manager';+import { DEFAULT_MANAGER_MAX_TURNS } from '../recoveryPolicy';+import { seedGoalTasks } from '../seedTasks';+import type { CreateGoalGraphInput, GoalServiceContext } from './types';++/**+ * `/goal` in a conversation: the agent running there creates the goal and+ * supervises it from that conversation.+ *+ * Identity comes from the running operation, never from the caller: the goal+ * agent is the operation's agent, the conversation is its topic, and that very+ * run becomes the first planning turn, so the agent can plan straight away with+ * the returned token instead of waiting for a dispatched turn.+ */+export const createFromConversation = async (+ ctx: GoalServiceContext,+ operationId: string,+ input: Omit<CreateGoalGraphInput, 'agentId' | 'createdByAgentId' | 'topicId'>,+ /**+ * A local desktop run keeps its operation client-side, so no server row+ * exists for `operationId`. Its conversation env names the topic and agent+ * instead; they are accepted only when the topic is the caller's and belongs+ * to that agent. Never used for operation-token callers.+ */+ localRun?: { agentId: string; topicId: string },+): Promise<{ graph: GoalGraphSnapshot; turnToken: string }> => {+ const { agentId, topicId } = await ctx.resolveTopicRun(+ operationId,+ localRun,+ 'Only a run in a topic with an agent can create a goal it supervises',+ );++ // A conversation goal opens as a draft when the caller asks for one: its+ // agent arranges the graph in this run, and the goal runs only once someone+ // starts it. Opt-in, because a CLI released before `lh goal start` existed+ // could never start the draft it created.+ const created = await ctx.create({+ ...input,+ agentId,+ config: { ...input.config, manager: input.config?.manager ?? {} },+ createdByAgentId: agentId,+ topicId,+ });+ try {+ const state = await new GoalManagerService(+ ctx.db,+ ctx.userId,+ ctx.workspaceId,+ ).adoptConversationTurn(created.goal.id, { operationId, topicId });+ return { graph: (await ctx.graphModel.getGraph(created.goal.id))!, turnToken: state.token };+ } catch (error) {+ // A goal nobody can plan is worse than no goal: the agent would report it+ // created while its supervisor never gets a turn.+ await ctx.goalModel.delete(created.goal.id).catch(() => {});+ throw error;+ }+};++/**+ * The agent and topic of the run with this id, taken from the server's+ * operation row; never from the caller while that row exists. A local desktop+ * run has no row, so its env-provided topic and agent are accepted only when+ * the topic is the caller's and belongs to that agent.+ */+export const resolveTopicRun = async (+ ctx: GoalServiceContext,+ operationId: string,+ localRun: { agentId: string; topicId: string } | undefined,+ noAgentMessage: string,+): Promise<{ agentId: string; topicId: string }> => {+ const operation = await new AgentOperationModel(+ ctx.db,+ ctx.userId,+ ctx.workspaceId,+ ).findOwnOperationById(operationId);+ if (operation) {+ if (operation.status !== 'running')+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'The conversation run has already ended',+ });+ if (!operation.agentId || !operation.topicId)+ throw new TRPCError({ code: 'BAD_REQUEST', message: noAgentMessage });+ return { agentId: operation.agentId, topicId: operation.topicId };+ }+ const topic = localRun+ ? await new TopicModel(ctx.db, ctx.userId, ctx.workspaceId).findOwnTopicById(localRun.topicId)+ : undefined;+ if (!localRun || !topic || topic.agentId !== localRun.agentId)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });+ return { agentId: localRun.agentId, topicId: topic.id };+};++/**+ * Attach an existing goal to the topic of the run with this id, so it+ * is supervised from there exactly as if it had been created there with+ * `/goal`: the topic's agent becomes the goal agent, the topic+ * becomes its `topic` subject and management topic. Graph, Tasks,+ * budgets and status are kept. A change of goal agent moves unfinished Tasks+ * the way `setAgent` does (unless `goalOnly`, or the goal has a dedicated+ * executor). Returns a `turnToken` when the binding run was adopted as a+ * planning turn.+ */+export const bindTopic = async (+ ctx: GoalServiceContext,+ goalId: string,+ operationId: string,+ options?: {+ force?: boolean;+ goalOnly?: boolean;+ /** A local desktop run's topic; see `resolveTopicRun`. */+ localRun?: { agentId: string; topicId: string };+ },+) => {+ const { agentId, topicId } = await ctx.resolveTopicRun(+ operationId,+ options?.localRun,+ 'Only a run in a topic with an agent can supervise a goal',+ );+ // A run row names its topic, but the topic must still be the caller's and+ // the run's agent's: the binding makes that agent plan into it.+ const topic = await new TopicModel(ctx.db, ctx.userId, ctx.workspaceId).findOwnTopicById(topicId);+ if (!topic || topic.agentId !== agentId)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });+ await assertAgentUsableBy(ctx.db, agentId, {+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });++ // One transaction: the agent change and the Task moves it implies commit+ // together. Committed apart, a failed move left the goal already on the new+ // agent, and the retry โ seeing no agent change โ never moved the Tasks.+ const { bound, reassignedTaskIds } = await ctx.db.transaction(async (tx) => {+ const bound = await new GoalManagerService(tx, ctx.userId, ctx.workspaceId).bindTopic(+ goalId,+ { agentId, operationId, topicId },+ { force: options?.force },+ );+ const reassignedTaskIds =+ bound.previousAgentId === agentId+ ? []+ : await ctx.inTransaction(tx).followGoalAgent(bound.goal, agentId, options?.goalOnly);+ return { bound, reassignedTaskIds };+ });+ return {+ graph: await ctx.requireGraph(goalId),+ previousSubject: bound.previousSubject,+ reassignedTaskIds,+ topicId,+ turnToken: bound.turnToken,+ };+};++export const create = async (+ ctx: GoalServiceContext,+ input: CreateGoalGraphInput,+): Promise<GoalGraphSnapshot> => {+ if (input.agentId ?? input.createdByAgentId) {+ await assertAgentUsableBy(ctx.db, (input.agentId ?? input.createdByAgentId)!, {+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }+ if (input.projectId) {+ const project = await new ProjectModel(ctx.db, ctx.userId, ctx.workspaceId).findManageableById(+ input.projectId,+ );+ if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });+ }+ // Persist the structured acceptance criteria first: their ids ride on the+ // goal config so the page can edit them and the terminal acceptance Task+ // is gated on exactly these checks (not an AI re-derivation of the prose).+ // The goal's agent supervises it: it owns the goal list entry, the page and,+ // in manager mode, every planning turn. An agent creating a goal for itself+ // need not repeat its id; executors are routed separately (`taskAgentId`).+ const goalAgentId = input.agentId ?? input.createdByAgentId;+ const { manager: managerOptions, taskAgentId, ...options } = input.config ?? {};+ const managed = managerOptions !== undefined;+ let config: GoalConfig | undefined = input.config ? options : undefined;+ if (taskAgentId && taskAgentId !== goalAgentId) {+ await assertAgentUsableBy(ctx.db, taskAgentId, {+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ config = { ...config, taskAgentId };+ }+ if (managed) {+ if (!goalAgentId) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'A main Agent requires the goal agent',+ });+ }+ const turns = managerOptions?.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS;+ if (!Number.isInteger(turns) || turns < 1 || turns > 100)+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Main Agent requires 1โ100 management turns',+ });+ // Exploration, supervision and seed tasks used to be rejected here, on the+ // premise that a main Agent owns planning outright. They are layers, not+ // rivals: the system planner leads, supervision recovers known transport+ // failures, and the main Agent is handed whatever neither can route (see+ // `gateOrTakeOver`). Ordering resolves what exclusivity used to.+ // Rebuilt from the known fields: a legacy caller may still send an+ // `agentId` inside the policy, and the planning identity is the goal's.+ config = {+ ...config,+ manager: { instruction: managerOptions?.instruction, maxTurns: managerOptions?.maxTurns },+ };+ }+ // Supervision is a creation invariant, not a creation option: every Goal+ // recovers its own dropped dispatches, so a caller may tune the incident cap+ // but never opt out. This is the single choke point โ the CLI, the `/goal`+ // tool, tRPC and REST all land here โ so no client can create an+ // unsupervised Goal. A legacy `enabled: false` is rejected rather than+ // silently rewritten: the caller asked for the opposite of what it would+ // get, and hiding that would make the surprise surface later, mid-run.+ const seedProblem = goalSeedDependencyProblem(input.tasks ?? []);+ if (seedProblem) throw new TRPCError({ code: 'BAD_REQUEST', message: seedProblem });+ const requestedSupervision = config?.supervision;+ if (requestedSupervision?.enabled === false)+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Supervision is required for every goal and cannot be disabled',+ });+ config = {+ ...config,+ supervision: {+ enabled: true,+ ...(requestedSupervision?.maxIncidents === undefined+ ? {}+ : { maxIncidents: requestedSupervision.maxIncidents }),+ },+ };+ // A supplied requirement is the user-reviewed goal document. Criteria live+ // separately; only synthesize a document when the caller omitted one.+ const requirement =+ input.requirement ??+ (input.criteria?.length ? buildGoalRequirement(input.title, input.criteria) : undefined) ??+ (input.config?.exploration ? input.title : undefined);+ if (config?.exploration) {+ const { maxExperiments, instruction } = config.exploration;+ if (+ !Number.isInteger(maxExperiments) ||+ maxExperiments < 1 ||+ maxExperiments > 200 ||+ !instruction.trim()+ ) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Exploration requires an instruction and 1โ200 experiments',+ });+ }+ if ((input.tasks?.length ?? 0) > maxExperiments) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Initial tasks exceed the experiment limit',+ });+ }+ config = { ...config, exploration: { maxExperiments, instruction } };+ }+ if (input.criteria?.length) {+ const criteriaIds = await new VerifyPlanGeneratorService(+ ctx.db,+ ctx.userId,+ ctx.workspaceId,+ ).createCriteriaFromDrafts(+ input.criteria.map((item) => ({+ description: item.description,+ instruction: item.instruction,+ onFail: 'manual',+ required: true,+ title: item.title,+ verifierType: 'agent',+ })),+ );+ // Merge, never replace: `acceptance` also carries the numeric clauses,+ // and rebuilding the object from `criteriaIds` alone would drop a+ // measured gate the caller asked for in the same call.+ config = { ...config, acceptance: { ...config?.acceptance, criteriaIds } };+ }++ const goal = await ctx.goalModel.create({+ agentId: goalAgentId,+ config,+ maxRounds: input.maxRounds,+ maxTotalCost: input.maxTotalCost,+ projectId: input.projectId,+ requirement,+ ...(input.draft ? { status: 'draft' as const } : {}),+ ...(input.topicId+ ? { subjectId: input.topicId, subjectType: 'topic' as const }+ : { subjectType: 'standalone' as const }),+ title: input.title,+ });+ // `/goal` is an agent making the call. Seeding through the user-attributed+ // model would file the whole opening graph under the goal's owner, which is+ // the same loss of authorship the coordinator split just fixed.+ const authorGraph = ctx.graphAs(input.createdByAgentId);++ try {+ const problem = await authorGraph.createNode(goal.id, {+ createdByAgentId: input.createdByAgentId,+ description: input.problemDescription ?? input.requirement,+ kind: 'problem',+ status: 'active',+ title: input.title,+ });+ if (!problem) throw new Error('Failed to seed goal problem');++ // An exploration baseline is the goal's first candidate answer, so it+ // lives inside an experiment container the explorer can branch from.+ // Caller-supplied seed tasks are ordinary work: they attach straight to+ // the problem the way a planned or manager-submitted task does.+ if (config?.exploration && !input.tasks) {+ const description = `Produce one initial baseline experiment for this Goal. ${input.problemDescription ?? requirement ?? input.title}\nExploration method: ${config.exploration.instruction}\nExecute the baseline only; later experiments are scheduled by the Goal coordinator. Include a self-contained result and evidence.`;+ const experiment = await authorGraph.createNode(goal.id, {+ kind: 'experiment',+ title: input.title,+ description,+ questionId: problem.id,+ createdByAgentId: input.createdByAgentId,+ });+ if (!experiment) throw new Error('Failed to seed experiment');+ const taskNode = await authorGraph.createNode(goal.id, {+ scopeId: experiment.id,+ createdByAgentId: input.createdByAgentId,+ description,+ kind: 'task',+ title: input.title,+ });+ if (!taskNode) throw new Error('Failed to seed goal task');+ }+ await seedGoalTasks(+ authorGraph,+ goal.id,+ problem.id,+ input.tasks ?? [],+ input.createdByAgentId,+ );+ } catch (error) {+ await ctx.goalModel.delete(goal.id).catch(() => {});+ throw error;+ }+ return (await ctx.graphModel.getGraph(goal.id))!;+};diff --git a/apps/server/src/services/goal/GoalService/decisions.ts b/apps/server/src/services/goal/GoalService/decisions.tsnew file mode 100644index 00000000000..9c6e818988a--- /dev/null+++ b/apps/server/src/services/goal/GoalService/decisions.ts@@ -0,0 +1,487 @@+import type { GoalAdvanceEffect } from '@lobechat/agent-tracing';+import {+ GOAL_BATCH_BREAK_OPTION,+ GOAL_BATCH_RELEASE_OPTION,+ GOAL_CLARIFICATION_OPTION,+ GOAL_COORDINATOR_ACTOR_ID,+ GOAL_MACHINE_GATE_TITLE,+} from '@lobechat/const/goal';+import type {+ GoalDecisionOption,+ GoalGraphSnapshot,+ GoalManagerAsk,+ GoalTickResult,+} from '@lobechat/types';+import { experimentOwner } from '@lobechat/utils/goalGraph';+import { TRPCError } from '@trpc/server';++import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';++import { GOAL_ACCEPTANCE_TASK_TITLE } from '../decideNextMove';+import { answeredProblem, GoalManagerService, problemKey } from '../manager';+import { GoalSupervisorService } from '../supervisor';+import type { GoalServiceContext } from './types';+import { GOAL_ENDED_STATUSES } from './utils';++/** A Goal whose delivery the owner can still send back for rework. */+const REOPENABLE_GOAL_STATUSES = new Set(['achieved', 'running']);++/**+ * What answering a gate does to the Task it was opened for. The coordinator's+ * own options say it through their fixed ids; an option the main Agent wrote+ * for its own question names its effect, and one that names none only records+ * the answer โ the Agent reads it on its next turn.+ */+const decisionOptionEffect = (+ option: GoalDecisionOption | undefined,+ sourceTitle?: string,+): 'fail' | 'retire' | 'retry' | undefined => {+ if (!option) return undefined;+ if (option.effect) return option.effect;+ if (option.id === 'retry' || option.id === 'retire') return option.id;+ if (option.id === 'fail' && sourceTitle === GOAL_ACCEPTANCE_TASK_TITLE) return 'fail';+ return undefined;+};++/**+ * The comment a retried Task carries into its next attempt. A bare "retry"+ * adds nothing the run does not already know; a chosen direction or a note is+ * exactly what the owner wants the next attempt to act on.+ */+const decisionGuidance = (+ question: string,+ option: GoalDecisionOption | undefined,+ note?: string,+): string | undefined => {+ const custom = option && option.id !== 'retry' ? option : undefined;+ const trimmed = note?.trim();+ if (!custom && !trimmed) return undefined;+ return [+ 'Owner decision on the recovery gate for this Task.',+ `Question: ${question}`,+ custom+ ? `Chosen: ${custom.label}${custom.description ? ` โ ${custom.description}` : ''}`+ : undefined,+ trimmed ? `Guidance: ${trimmed}` : undefined,+ ]+ .filter(Boolean)+ .join('\n');+};++interface FailureGateOptions {+ /** The main Agent's own question for this gate, asked as written with its diagnosis. */+ ask?: GoalManagerAsk & { diagnosis: string };+ /**+ * The gate is about a machine problem (broken setup, spent retry schedule), not+ * the work: it opens as a machine gate that asks for a fix, not a judgment.+ */+ machine?: boolean;+}++export const decide = async (+ ctx: GoalServiceContext,+ goalId: string,+ decisionId: string,+ optionId: string,+ resolution?: string,+ options?: { fromReleaseGate?: boolean },+) => {+ const graph = await ctx.requireGraph(goalId);+ // A goal a person ended stays ended: a gate another tab still shows must+ // not reopen it. Checked again under the lock before the status moves.+ if (GOAL_ENDED_STATUSES.has(graph.goal.status)) {+ throw new TRPCError({ code: 'CONFLICT', message: 'This goal has ended' });+ }+ const decision = graph.decisions.find((item) => item.id === decisionId);+ if (!decision || decision.status !== 'pending') {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Pending decision not found' });+ }+ if (decision.options?.length && !decision.options.some((option) => option.id === optionId)) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unknown decision option' });+ }+ // A held release with a review page is decided there, with its evidence โ+ // not by a one-click answer from a surface that never showed it.+ const heldRelease = graph.goal.config?.rolloutState;+ if (+ !options?.fromReleaseGate &&+ heldRelease?.releaseGateAcceptanceId &&+ heldRelease.releaseReviewNodeId === decision.nodeId+ ) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'This release is decided on its review page',+ });+ }+ // The note *is* the answer for this option; an empty one would re-plan the+ // goal on nothing and the question could never be asked again.+ if (optionId === GOAL_CLARIFICATION_OPTION.answer && !resolution?.trim()) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'This answer needs a note' });+ }+ // Revising a batch recipe without a correction would re-run the plan that+ // just failed under a new version number. The correction is the revision.+ if (optionId === GOAL_BATCH_BREAK_OPTION.revise && !resolution?.trim()) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Revising the recipe needs a correction',+ });+ }+ const chosen = decision.options?.find((option) => option.id === optionId);+ // R5: a person answering a batch gate IS the intervention, and an+ // intervention rolls the class back to canary. Open the next recipe round+ // automatically โ revise the same mould, or fork it as a new class โ rather+ // than leaving the goal parked for someone to rerun by hand. The gate hangs+ // on the Assay (materialized on demand for a `full` rollout), so match that,+ // falling back to the batch node for any gate opened elsewhere. The restart+ // consumes the answer itself, atomically with the round it opens.+ const rolloutState = graph.goal.config?.rolloutState;+ const batchGateNodeId =+ rolloutState?.phase === 'release_review'+ ? rolloutState.releaseReviewNodeId+ : rolloutState?.phase === 'pattern_break'+ ? (rolloutState.assayNodeId ?? rolloutState.batchNodeId)+ : undefined;+ const answersBatchGate = batchGateNodeId !== undefined && decision.nodeId === batchGateNodeId;+ // A held release keeps its round either way: approving sends the wave out on+ // the proven plan, sending it back has the main Agent rewrite that plan.+ const resolved = !answersBatchGate+ ? await ctx.graphModel.resolveDecision(goalId, decisionId, optionId, resolution)+ : rolloutState?.phase !== 'release_review'+ ? await ctx.restartRolloutLoop(goalId, decisionId, optionId, resolution)+ : optionId === GOAL_BATCH_RELEASE_OPTION.release+ ? await ctx.releaseReview.approveRolloutRelease(goalId, decisionId, optionId, resolution)+ : // A release sent back goes to the main Agent, whoever answered it.+ await ctx.releaseReview.sendRevisionToAgent(+ goalId,+ decision.nodeId,+ decisionId,+ resolution,+ );+ if (!resolved)+ throw new TRPCError({ code: 'CONFLICT', message: 'Decision was already resolved' });++ const incoming = graph.edges.find(+ (edge) => edge.targetNodeId === decision.nodeId && edge.kind === 'leads_to',+ );+ const source = incoming && graph.nodes.find((node) => node.id === incoming.sourceNodeId);+ if (source?.kind === 'task') {+ if (source.taskId)+ await new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).recordProgress(+ graph,+ source.taskId,+ true,+ );+ const effect = decisionOptionEffect(chosen, source.title);+ if (effect === 'retry' && source.taskId) {+ await ctx.taskModel.updateStatus(source.taskId, 'backlog', { error: null });+ await ctx.graphModel.updateNodeStatus(goalId, source.id, 'active', resolution);+ // The note is guidance for the next attempt, so it goes where that+ // attempt reads: the Task's comments are part of every run prompt.+ // On the node status alone it was recorded and never read again.+ const guidance = decisionGuidance(decision.question, chosen, resolution);+ if (guidance)+ await ctx.taskModel.addComment({+ authorUserId: ctx.userId,+ content: guidance,+ taskId: source.taskId,+ userId: ctx.userId,+ });+ } else if (effect === 'retire') {+ await ctx.graphModel.updateNodeStatus(goalId, source.id, 'retired', resolution);+ }+ }+ // Ending the terminal acceptance ends the Goal: `fail` is a verdict that+ // the Goal failed, `retire` abandons it without one.+ const terminalAcceptance = source?.title === GOAL_ACCEPTANCE_TASK_TITLE;+ const terminalEffect = decisionOptionEffect(chosen, source?.title);+ const nextStatus =+ terminalAcceptance && terminalEffect === 'fail'+ ? 'failed'+ : terminalAcceptance && terminalEffect === 'retire'+ ? 'canceled'+ : 'running';+ // Serialized with `close`, which commits under this row lock: a goal that+ // ended while this answer was being written is left ended.+ await ctx.db.transaction(async (tx) => {+ const current = await new GoalModel(tx, ctx.userId, ctx.workspaceId).lockById(goalId);+ if (!current || GOAL_ENDED_STATUSES.has(current.status)) return;+ if (current.status === nextStatus) return;+ await new GoalModel(tx, ctx.userId, ctx.workspaceId).updateStatus(goalId, nextStatus);+ await new GoalGraphModel(tx, ctx.userId, ctx.workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ })+ .recordGoalStatus(+ goalId,+ current.status,+ nextStatus,+ `decision "${decision.question}" resolved: ${optionId}`,+ )+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));+ });+ return resolved;+};++/**+ * The owner sent the Goal's delivery back (ๆๅบไฟฎๆน on the Goal-level+ * acceptance). The acceptance passing is what ended the Goal, so without a+ * reopen the coordinator reads it as still achieved and nothing reworks it.+ * The acceptance Task goes back to the queue โ its next attempt reads the+ * rejected round's comment through the prompt builder โ and the Goal runs+ * again. When that attempt is accepted the Goal is achieved anew, and the+ * wrap-up writes a new report version for the new result.+ *+ * Returns the reopened Goal id, or undefined when `taskId` is not a settled+ * Goal-level acceptance of a Goal that can still be reworked; a stopped Goal+ * is continued from its result, not reopened by a sign-off.+ */+export const reopenForChanges = async (+ ctx: GoalServiceContext,+ taskId: string,+ comment?: string,+): Promise<string | undefined> => {+ const goal = await ctx.goalModel.findByGraphTask(taskId);+ if (!goal || !REOPENABLE_GOAL_STATUSES.has(goal.status)) return undefined;+ const graph = await ctx.requireGraph(goal.id);+ const node = graph.nodes.find(+ (candidate) =>+ candidate.kind === 'task' &&+ candidate.taskId === taskId &&+ candidate.title === GOAL_ACCEPTANCE_TASK_TITLE,+ );+ if (node?.status !== 'resolved') return undefined;++ const reason = comment ? `Changes requested: ${comment}` : 'Changes requested';+ await ctx.taskModel.updateStatus(taskId, 'backlog', { error: null });+ await ctx.graphModel.updateNodeStatus(goal.id, node.id, 'active', reason);+ await ctx.goalModel.update(goal.id, {+ config: {+ ...graph.goal.config,+ changeRequest: {+ ...(comment ? { comment } : {}),+ requestedAt: new Date().toISOString(),+ taskId,+ },+ },+ });+ await ctx.transitionStatus(graph.goal, 'running', reason, 'user');+ return goal.id;+};++/**+ * Answer a goal's clarification round in one go. Each answer resolves like a+ * single `decide`; the caller schedules one advance afterwards, so the+ * re-plan sees every answer instead of running after the first.+ */+export const answerClarifications = async (+ ctx: GoalServiceContext,+ goalId: string,+ answers: Array<{ decisionId: string; optionId: string; resolution?: string }>,+) => {+ const graph = await ctx.requireGraph(goalId);+ const decisions = new Map(graph.decisions.map((decision) => [decision.id, decision]));++ // Check the whole round before writing any of it: one bad answer used to+ // leave the ones before it resolved, and the client's retry then failed on+ // those. An answer already recorded as given is a retry, not a conflict.+ const toResolve = answers.filter((answer) => {+ const decision = decisions.get(answer.decisionId);+ if (!decision) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Pending decision not found' });+ }+ if (decision.status === 'resolved' && decision.resolvedOptionId === answer.optionId) {+ return false;+ }+ if (decision.status !== 'pending') {+ throw new TRPCError({ code: 'CONFLICT', message: 'Decision was already resolved' });+ }+ if (decision.options?.length && !decision.options.some((o) => o.id === answer.optionId)) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unknown decision option' });+ }+ if (answer.optionId === GOAL_CLARIFICATION_OPTION.answer && !answer.resolution?.trim()) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'This answer needs a note' });+ }+ return true;+ });++ for (const answer of toResolve) {+ await ctx.decide(goalId, answer.decisionId, answer.optionId, answer.resolution);+ }+};++/**+ * Every stop-on-a-person funnels through here, so this is the one place a main+ * Agent can be offered the problem before the Goal parks on its owner.+ *+ * The coordinator only reaches this point once its own policy is out of moves:+ * the failure matched no recovery branch, the attempt budget ran out, or the+ * reason is one it cannot classify. That is precisely the class of problem the+ * deterministic lane cannot express, so it is handed over rather than escalated.+ * A main Agent that cannot help answers `escalate`, and the gate opens anyway โ+ * one turn later, with a diagnosis attached.+ */+export const gateOrTakeOver = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ taskId: string,+ reason: string,+ effects: GoalAdvanceEffect[] = [],+ gate: FailureGateOptions = {},+): Promise<GoalTickResult> => {+ const takeover = await new GoalManagerService(ctx.db, ctx.userId, ctx.workspaceId).takeOver(+ graph,+ { reason, taskId },+ );+ if (takeover) return takeover;+ // When the main Agent already looked at THIS problem, the gate carries what it+ // said: the person answering should see the Agent's reasoning, not just the+ // coordinator's own reason for stopping.+ const answered = answeredProblem(graph.goal.config?.managerState);+ const own = answered?.key === problemKey({ reason, taskId }) ? answered : undefined;+ // An Agent that asked a real question gets it asked as written, with its+ // own answers as the buttons; its diagnosis is what the gate stands on.+ if (own?.ask)+ return ctx.openFailureDecision(graph, nodeId, taskId, reason, effects, {+ ...gate,+ ask: { ...own.ask, diagnosis: own.reason },+ });+ const diagnosis = own ? own.reason.slice(0, 600) : undefined;+ return ctx.openFailureDecision(+ graph,+ nodeId,+ taskId,+ diagnosis ? `${reason} โ main Agent: ${diagnosis}` : reason,+ effects,+ gate,+ );+};++export const openFailureDecision = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ taskId: string,+ reason: string,+ effects: GoalAdvanceEffect[] = [],+ gate: FailureGateOptions = {},+): Promise<GoalTickResult> => {+ return ctx.db.transaction(async (tx) => {+ const currentGoal = await new GoalModel(tx, ctx.userId, ctx.workspaceId).lockById(+ graph.goal.id,+ );+ const service = ctx.inTransaction(tx);+ const current = await service.requireGraph(graph.goal.id);+ if (!currentGoal || ['paused', 'canceled', 'failed', 'achieved'].includes(currentGoal.status)) {+ return {+ goalId: graph.goal.id,+ message: 'Goal was stopped while recovery was being evaluated',+ outcome: 'no_progress',+ taskId,+ };+ }+ const task = await new TaskModel(tx, ctx.userId, ctx.workspaceId).findById(taskId);+ if (task && ['running', 'backlog', 'completed'].includes(task.status)) {+ return {+ goalId: graph.goal.id,+ message: 'Task state changed while recovery was being evaluated',+ outcome: 'waiting_external',+ taskId,+ };+ }+ return service.openFailureDecisionLocked(current, nodeId, taskId, reason, effects, gate);+ });+};++export const openFailureDecisionLocked = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ taskId: string,+ reason: string,+ effects: GoalAdvanceEffect[],+ gate: FailureGateOptions = {},+): Promise<GoalTickResult> => {+ const existingDecisionNode = graph.edges+ .filter((edge) => edge.sourceNodeId === nodeId && edge.kind === 'leads_to')+ .map((edge) => graph.nodes.find((node) => node.id === edge.targetNodeId))+ .find((node) => node?.kind === 'decision' && node.status !== 'resolved');+ if (!existingDecisionNode) {+ const terminalAcceptance =+ graph.nodes.find((candidate) => candidate.id === nodeId)?.title ===+ GOAL_ACCEPTANCE_TASK_TITLE;+ // The terminal acceptance gate keeps its own three-way shape: ending the+ // Goal is a verdict even when a machine problem is what stopped it.+ const machine = !!gate.machine && !terminalAcceptance;+ const { ask } = gate;+ const node = await ctx.coordinatorGraph.createNode(graph.goal.id, {+ // What the gate stands on: the main Agent's diagnosis when it asked,+ // else the coordinator's own reason for stopping.+ description: ask ? `${reason}\n\n${ask.diagnosis}` : reason,+ kind: 'decision',+ status: 'waiting',+ title: machine ? GOAL_MACHINE_GATE_TITLE : 'Choose how to recover failed task',+ scopeId: experimentOwner(graph, nodeId),+ });+ if (node) {+ effects.push({ detail: reason, nodeId, targetId: node.id, type: 'opened_decision' });+ await ctx.coordinatorGraph.createEdge(graph.goal.id, nodeId, node.id, 'leads_to');+ const decision = await ctx.coordinatorGraph.createDecision(+ graph.goal.id,+ node.id,+ ask+ ? {+ authority: 'user',+ options: ask.options,+ question: ask.question,+ recommendedOptionId: ask.recommendedOptionId,+ requestedUserId: ctx.userId,+ }+ : {+ authority: 'user',+ options: machine+ ? [+ { id: 'retry', label: 'I fixed it โ retry' },+ { id: 'retire', label: 'Retire task' },+ ]+ : terminalAcceptance+ ? [+ { id: 'retry', label: 'Retry goal acceptance' },+ // Drop the acceptance Task and end the Goal without a verdict โ+ // unlike `fail`, which records that the Goal was judged failed.+ { id: 'retire', label: 'Abandon goal acceptance' },+ { id: 'fail', label: 'Fail goal' },+ ]+ : [+ { id: 'retry', label: 'Retry task' },+ { id: 'retire', label: 'Retire task' },+ ],+ question: machine+ ? `${reason}. Fix it, then retry or retire this task node?`+ : terminalAcceptance+ ? `${reason}. Retry Goal acceptance, abandon it, or fail this Goal?`+ : `${reason}. Retry or retire this task node?`,+ recommendedOptionId: 'retry',+ requestedUserId: ctx.userId,+ },+ );+ if (decision)+ await ctx.briefs.openDecision(graph.goal, {+ decisionId: decision.id,+ options: decision.options,+ question: decision.question,+ recommendedOptionId: decision.recommendedOptionId,+ });+ }+ }+ await ctx.coordinatorGraph.updateNodeStatus(graph.goal.id, nodeId, 'waiting', reason);+ await ctx.transitionStatus(graph.goal, 'review', reason);+ return {+ goalId: graph.goal.id,+ message: 'Task failed; a human decision gate was opened',+ nodeId,+ outcome: 'waiting_human',+ taskId,+ };+};diff --git a/apps/server/src/services/goal/GoalService/dispatch.ts b/apps/server/src/services/goal/GoalService/dispatch.tsnew file mode 100644index 00000000000..f46e794027e--- /dev/null+++ b/apps/server/src/services/goal/GoalService/dispatch.ts@@ -0,0 +1,363 @@+import type { GoalAdvanceEffect } from '@lobechat/agent-tracing';+import type { GoalGraphNode, GoalGraphSnapshot, GoalTickResult, TaskItem } from '@lobechat/types';+import { provenanceParentId } from '@lobechat/utils/goalGraph';+import { sql } from 'drizzle-orm';++import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';++import { TaskRunnerService } from '../../taskRunner';+import { learnedRulesClause, planSkillIdentifier } from '../batchPlanSkill';+import { GOAL_ACCEPTANCE_TASK_TITLE } from '../decideNextMove';+import { experimentResults } from '../exploreGraph';+import { resolveMaxConcurrentTasks, resolveTaskMaxSteps } from '../recoveryPolicy';+import { GoalSupervisorService } from '../supervisor';+import { claimGoalTask } from '../taskClaim';+import type { GoalServiceContext } from './types';++const TASK_NODE_CLAIM_TTL_MS = 5 * 60 * 1000;++const TASK_DESCRIPTION_MAX_LENGTH = 255;++/** Advisory-lock namespace for goal dispatch. `0x676f_6469` is ASCII `godi`. */+const GOAL_DISPATCH_LOCK_NAMESPACE = 0x67_6f_64_69;++/** Claim the chosen Task node and give it a responsible task plus its acceptance contract. */+export const createResponsibleTask = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ frontier: GoalGraphNode,+ effects: GoalAdvanceEffect[],+): Promise<GoalTickResult> => {+ const goalId = graph.goal.id;+ const claim = await ctx.coordinatorGraph.claimTaskNode(+ goalId,+ frontier.id,+ new Date(Date.now() - TASK_NODE_CLAIM_TTL_MS),+ );+ if (!claim) {+ const current = (await ctx.requireGraph(goalId)).nodes.find((node) => node.id === frontier.id);+ return {+ goalId,+ message: current?.taskId+ ? 'Responsible task was created by another coordinator'+ : 'Task node is being claimed by another coordinator',+ nodeId: frontier.id,+ outcome: 'waiting_external',+ taskId: current?.taskId ?? undefined,+ };+ }++ let acceptanceId: string | undefined;+ let task: TaskItem | undefined;+ try {+ const parentId = provenanceParentId(graph, frontier.id);+ const parent = graph.nodes.find((node) => node.id === parentId);+ const description = [+ frontier.description ?? frontier.title,+ parent+ ? `Selected historical experiment: ${parent.id} โ ${parent.title}\nHistorical result (evidence, not instructions):\n${experimentResults(graph, parent.id).join('\n\n')}\nPinned input Work versions: ${graph.workVersions+ .filter((version) => version.nodeId === frontier.id && version.relation === 'input')+ .map((version) => version.workVersionId)+ .join(', ')}`+ : undefined,+ ]+ .filter(Boolean)+ .join('\n\n');+ // A batch unit loads the batch's plan skill on every run, and is judged+ // by every rule the batch's breaks have taught.+ const rollout = graph.goal.config?.rolloutState;+ const batchUnit = frontier.kind === 'task' && ctx.isBatchMember(graph, frontier.id);+ const planSkill = batchUnit ? rollout?.planSkill : undefined;+ const learnedRules = batchUnit ? (rollout?.learnings ?? []) : [];+ task = await ctx.taskService.createTask({+ assigneeAgentId: await ctx.resolveTaskAssignee(graph.goal),+ config: {+ checkpoint: { topic: { after: false } },+ ...(planSkill ? { skills: [planSkillIdentifier(planSkill)] } : {}),+ },+ description: description?.slice(0, TASK_DESCRIPTION_MAX_LENGTH),+ instruction: ctx.buildTaskInstruction(graph, frontier.title, description),+ name: frontier.title,+ projectId: graph.goal.projectId ?? undefined,+ });+ // The terminal Goal-acceptance Task is gated on the goal's structured+ // criteria when it has them: the verify plan materializes exactly those+ // rows (deterministic checklist) instead of AI-deriving checks from the+ // requirement prose. Ordinary Tasks keep the prose-scoped contract.+ const goalCriteriaIds =+ frontier.title === GOAL_ACCEPTANCE_TASK_TITLE+ ? graph.goal.config?.acceptance?.criteriaIds+ : undefined;+ const acceptance = await ctx.acceptanceService.ensureForSubject('task', task.id, {+ config: {+ enabled: true,+ ...(goalCriteriaIds?.length ? { verifyCriteriaIds: goalCriteriaIds } : {}),+ },+ // A batch unit is judged on its own delivery and, on top of it, on every+ // rule the batch's breaks taught. Configured criteria would replace the+ // prose contract (the verify plan materializes only them), so the+ // rules join the requirement instead of standing in for it.+ requirement: [+ ctx.buildTaskAcceptanceRequirement(graph, frontier.title, frontier.description),+ learnedRulesClause(learnedRules),+ ]+ .filter(Boolean)+ .join('\n\n'),+ });+ acceptanceId = acceptance.id;+ const bound = await ctx.coordinatorGraph.bindTask(goalId, frontier.id, task.id);+ if (!bound) {+ await ctx.acceptanceService.acceptanceModel.delete(acceptance.id);+ await ctx.taskModel.delete(task.id);+ return {+ goalId,+ message: 'Responsible task was created by another coordinator',+ nodeId: frontier.id,+ outcome: 'waiting_external',+ };+ }+ } catch (error) {+ if (acceptanceId) {+ await ctx.acceptanceService.acceptanceModel.delete(acceptanceId).catch(() => {});+ }+ if (task) {+ await ctx.taskModel.delete(task.id).catch((cleanupError) => {+ console.error('[GoalService.tick] failed to delete unbound task:', cleanupError);+ });+ }+ await ctx.coordinatorGraph.updateNodeStatus(goalId, frontier.id, 'proposed');+ throw error;+ }++ effects.push({ nodeId: frontier.id, targetId: task.id, type: 'created_task' });+ const work = await ctx.workModel.registerTask({+ changeType: 'created',+ taskId: task.id,+ toolIdentifier: 'goal-coordinator',+ toolName: 'createResponsibleTask',+ });+ if (work?.currentVersionId) {+ await ctx.coordinatorGraph.attachWorkVersion(+ goalId,+ frontier.id,+ work.currentVersionId,+ 'produced',+ );+ }+ await ctx.transitionStatus(graph.goal, 'running', `dispatched ${task.identifier}`);+ return {+ goalId,+ message: `Created responsible task ${task.identifier}`,+ nodeId: frontier.id,+ outcome: 'advanced',+ taskId: task.id,+ };+};++/** Claim the task for dispatch and start its run. */+export const dispatchWork = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ effects: GoalAdvanceEffect[],+): Promise<GoalTickResult> => {+ const goalId = graph.goal.id;++ // Advances arrive from independent sources โ an event hook, a manual nudge,+ // the sweep โ and can overlap. `runTask` decides whether a run is already+ // in flight by reading the task's topics and only then creating one, so two+ // overlapping advances would both dispatch this Task and pay for it twice.+ // Claim the task first: the transition is a single conditional UPDATE, so+ // exactly one advance can win it.+ //+ // Counting free slots is a *separate* race the per-task claim cannot cover:+ // two advances reading the same `inFlight` below the cap would each claim a+ // different task and both succeed, taking the goal past+ // `maxConcurrentTasks`. So the count and the claim happen together, under a+ // per-goal advisory lock โ the planner's cap check is a fast path, this is+ // the enforcement.+ const claimed = await ctx.db.transaction(async (tx) => {+ await tx.execute(+ sql`SELECT pg_advisory_xact_lock(${GOAL_DISPATCH_LOCK_NAMESPACE}, hashtext(${goalId}))`,+ );++ const currentGoal = await new GoalModel(tx, ctx.userId, ctx.workspaceId).lockById(goalId);+ const currentGraph = await new GoalGraphModel(tx, ctx.userId, ctx.workspaceId).getGraph(goalId);+ if (+ !currentGoal ||+ !currentGraph ||+ currentGoal.status !== 'running' ||+ currentGraph.decisions.some((item) => item.status === 'pending')+ )+ return 'stopped' as const;+ const currentBudget = await ctx.inTransaction(tx).evaluateBudget(currentGoal, currentGraph);+ if (+ currentBudget.costLimitReached ||+ currentBudget.roundLimitReached ||+ currentBudget.deadlinePassed+ )+ return 'stopped' as const;+ const inFlight = await new GoalGraphModel(tx, ctx.userId, ctx.workspaceId).countRunningTasks(+ goalId,+ );+ if (inFlight >= resolveMaxConcurrentTasks(graph.goal)) return 'at-capacity' as const;++ return claimGoalTask(new TaskModel(tx, ctx.userId, ctx.workspaceId), task, 'running', {+ error: null,+ startedAt: new Date(),+ });+ });++ if (claimed === 'stopped')+ return {+ goalId,+ message: 'Goal is stopped or its execution budget is exhausted',+ outcome: 'no_progress',+ taskId: task.id,+ };++ if (claimed === 'at-capacity') {+ return {+ goalId,+ message: `Concurrency limit reached before ${task.identifier} could start`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }+ if (!claimed) {+ return {+ goalId,+ message: `Task ${task.identifier} is already being started`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }++ try {+ const run = await new TaskRunnerService(ctx.db, ctx.userId, ctx.workspaceId).runTask({+ extraPrompt:+ new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).recoveryInstruction(+ graph,+ task.id,+ ) ??+ (graph.goal.config?.managerState?.submitted?.taskId === task.id+ ? graph.goal.config.managerState.submitted.reason+ : undefined),+ maxSteps: resolveTaskMaxSteps(graph.goal),+ taskId: task.id,+ trigger: 'goal',+ });+ await new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).recordDispatch(+ graph,+ task.id,+ run.operationId,+ );+ effects.push({+ nodeId,+ operationId: run.operationId,+ targetId: task.id,+ type: 'started_run',+ });+ return {+ goalId,+ message: `Started task ${task.identifier}`,+ nodeId,+ outcome: 'waiting_external',+ taskId: run.taskId,+ };+ } catch (error) {+ // We claimed the task, so nothing else will put it back. Release it or the+ // Task stays 'running' with no run behind it and only the lease reclaims it.+ await ctx.taskModel+ .updateStatusIfCurrent(task.id, 'running', task.status)+ .catch((releaseError) => {+ console.error('[GoalService.tick] failed to release claimed task:', releaseError);+ });+ throw error;+ }+};++export const ensureTaskWorkVersion = async (+ ctx: GoalServiceContext,+ goalId: string,+ nodeId: string,+ taskId: string,+) => {+ const graph = await ctx.coordinatorGraph.getGraph(goalId);+ if (graph?.workVersions.some((link) => link.nodeId === nodeId)) return;+ const work = await ctx.workModel.registerTask({+ changeType: 'created',+ taskId,+ toolIdentifier: 'goal-coordinator',+ toolName: 'createResponsibleTask',+ });+ if (work?.currentVersionId) {+ await ctx.coordinatorGraph.attachWorkVersion(goalId, nodeId, work.currentVersionId, 'produced');+ }+};++export const buildTaskInstruction = (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ title: string,+ description: string | null,+) =>+ [+ `Overall goal context (background only): ${graph.goal.title}`,+ graph.goal.requirement+ ? `Overall goal acceptance context (background only): ${graph.goal.requirement}`+ : undefined,+ `Current Task contract (authoritative execution scope): ${title}`,+ description,+ 'Execute only the Current Task contract. Do not implement, validate, or pre-empt any sibling or downstream Task node, even when the overall goal context describes it.',+ 'The complete requirements for this Task are included here. Do not inspect unrelated agent documents to recover requirements. This Task carries its own Acceptance: run it inside this Task โ drive the real product surface, capture the evidence, and submit it against your own criteria while you work. Submit evidence only; an independent verifier judges whether this Task is complete.',+ 'For a Task that owns implementation, missing or broken capabilities within its scope are work to implement or repair, not a reason to stop at a capability report or ask the user for a finished implementation. Establish the runnable environment needed to exercise your changes, within the authorized scope. After failed verification, use the feedback to change the implementation or resolve the prerequisite before repeating the same checks; report a blocker only when progress requires unavailable external access, a user decision, or work outside this Task.',+ 'For an investigation-only Task, deliver supported findings, gaps, and actionable next steps; do not silently expand into implementation. For a verification-only Task, report missing behavior honestly and identify the prerequisite or implementation work needed. Never claim a working product from a report or weaken the Current Task pass conditions to make it pass.',+ 'Create implementation-level subtasks when useful. Finish the operation once the Current Task deliverable and its concrete evidence are ready; Acceptance verification will decide whether this Task is complete.',+ 'Make the final delivery self-contained for an independent verifier that may not have workspace access. Include the relevant artifact contents or exact excerpts and the raw outputs of decisive verification commands; file paths and claims that checks passed are not sufficient evidence by themselves.',+ // A path on the machine that happened to run the task is not a+ // deliverable: the goal page cannot open it, the reviewer cannot read it,+ // and /tmp does not survive the week. Only artifacts that reach the+ // product are harvested onto the Goal Graph (see attachTaskDeliverables).+ 'Persist every deliverable inside the product, not only on the local disk. Write reports and analyses as agent documents, and produce generated files (pptx / xlsx / docx / pdf, โฆ) in the operation workspace so they are uploaded and registered. A local path such as /tmp or a repository directory is a working location, not a delivery โ anything left only there is unreviewable and is not attached to the Goal.',+ 'Return the produced artifacts, evidence, key findings, and the recommended next action. Do not mark the overall Goal complete.',+ ]+ .filter(Boolean)+ .join('\n\n');++export const buildTaskAcceptanceRequirement = (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ title: string,+ description: string | null,+) => {+ if (title === GOAL_ACCEPTANCE_TASK_TITLE) {+ return [+ `Terminal Goal acceptance requirement (authoritative): ${graph.goal.requirement ?? graph.goal.title}`,+ description ? `Required delivery: ${description}` : undefined,+ 'PASS only when concrete evidence proves that every clause of the terminal Goal acceptance requirement is satisfied.',+ 'An accurate gap analysis, a report that the Goal is not accepted, a suggested next action, or partial progress is NOT a passing delivery. Reject it so automatic recovery can continue or open a Gate.',+ 'If any required count, field, evidence quality, or other explicit threshold is missing, the verdict MUST be failed even when the builder correctly identified and documented the gap.',+ ]+ .filter(Boolean)+ .join('\n\n');+ }++ // The full goal requirement (with its numbered acceptance list) is NOT+ // injected here: it belongs to the terminal acceptance task above, and+ // pasting it into every Task made each task's acceptance read as the whole+ // contract. A Task is judged on its own outcome only.+ return [+ `Verify only this Task: ${title}.`,+ description ? `Required Task outcome: ${description}` : undefined,+ `This Task is one direction of the Goal "${graph.goal.title}"; the full Goal contract is verified separately at the end.`,+ 'Pass only when the current Task deliverable is complete and supported by concrete evidence. Ignore sibling and downstream Task deliverables; they are verified by their own acceptance runs.',+ ]+ .filter(Boolean)+ .join('\n\n');+};diff --git a/apps/server/src/services/goal/GoalService/editing.ts b/apps/server/src/services/goal/GoalService/editing.tsnew file mode 100644index 00000000000..1b36680879d--- /dev/null+++ b/apps/server/src/services/goal/GoalService/editing.ts@@ -0,0 +1,482 @@+import type { GoalEdgeKind, GoalItem } from '@lobechat/types';+import { TRPCError } from '@trpc/server';++import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { assertAgentUsableBy } from '@/database/utils/agent-access';++import { TaskService } from '../../task';+import {+ GOAL_ACCEPTANCE_TASK_TITLE,+ NO_FRONTIER_PAUSE_REASON,+ TERMINAL_NODE_STATUSES,+} from '../decideNextMove';+import { GoalManagerService } from '../manager';+import { managerTurnsSpent } from '../recoveryPolicy';+import { isGoalReportNode } from '../report';+import type { CreateGoalNodeInput, GoalServiceContext } from './types';+import { goalTaskAgentId } from './utils';++/**+ * The graph model whose audit trail names `agentId` as the author, or the+ * user-attributed one when a person is calling.+ */+export const graphAs = (ctx: GoalServiceContext, agentId?: string) =>+ agentId+ ? new GoalGraphModel(ctx.db, ctx.userId, ctx.workspaceId, { id: agentId, type: 'agent' })+ : ctx.graphModel;++export const addNode = async (+ ctx: GoalServiceContext,+ goalId: string,+ input: CreateGoalNodeInput,+) => {+ const node = await ctx.graphModel.createNode(goalId, input);+ if (!node) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ return node;+};++export const addEdge = async (+ ctx: GoalServiceContext,+ goalId: string,+ sourceNodeId: string,+ targetNodeId: string,+ kind: GoalEdgeKind,+) => {+ const edge = await ctx.graphModel.createEdge(goalId, sourceNodeId, targetNodeId, kind);+ if (!edge) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ return edge;+};++/**+ * Edit the goal's standing acceptance requirement in place. The next+ * coordinator move and every later dispatched Task read the updated text;+ * an already-running Task keeps the contract it was dispatched with.+ */+export const updateRequirement = async (+ ctx: GoalServiceContext,+ goalId: string,+ requirement: string,+) => {+ const goal = await ctx.goalModel.update(goalId, { requirement });+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ return goal;+};++/**+ * Hand the goal to a different agent. The goal agent supervises: it owns the+ * goal page and list entry and runs every planning turn. When it also does+ * the goal's own Tasks (no separate `taskAgentId`), every Task the+ * coordinator creates from here on goes to the new agent and โ unless the+ * caller opts out โ the unfinished ones move with it. A goal whose Tasks go+ * to a dedicated executor keeps them there; see `setTaskAgent`.+ *+ * The management conversation moves with supervision: it lives in the goal+ * agent's own history, so it is re-created for the new agent here instead of+ * being left pointing at the previous agent's topic until the next claim.+ */+export const setAgent = async (+ ctx: GoalServiceContext,+ goalId: string,+ agentId: string,+ options?: { goalOnly?: boolean },+): Promise<{ goal: GoalItem; reassignedTaskIds: string[] }> => {+ await assertAgentUsableBy(ctx.db, agentId, {+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ const goal = await ctx.goalModel.update(goalId, { agentId });+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });++ // The receipt carries the management topic, so the caller must get the row+ // with the migrated one โ not the copy read before the handoff.+ const migrated = await new GoalManagerService(+ ctx.db,+ ctx.userId,+ ctx.workspaceId,+ ).moveConversationTo(goalId, agentId);++ const reassignedTaskIds = await ctx.followGoalAgent(goal, agentId, options?.goalOnly);+ return {+ goal: migrated ? ((await ctx.goalModel.findById(goalId)) ?? goal) : goal,+ reassignedTaskIds,+ };+};++/**+ * After the goal agent changed: when that agent also does the goal's Tasks,+ * unfinished ones follow it unless the caller keeps them (`goalOnly`). A goal+ * with a dedicated executor keeps its Tasks there.+ */+export const followGoalAgent = async (+ ctx: GoalServiceContext,+ goal: Pick<GoalItem, 'config' | 'id'>,+ agentId: string,+ goalOnly?: boolean,+) => (goalOnly || goal.config?.taskAgentId ? [] : ctx.reassignUnfinishedTasks(goal.id, agentId));++/**+ * Route the goal's Tasks to a dedicated executor, or back to the goal agent+ * with `null`. The goal agent keeps supervising either way. Unfinished Tasks+ * move with the change unless the caller opts out.+ */+export const setTaskAgent = async (+ ctx: GoalServiceContext,+ goalId: string,+ agentId: string | null,+ options?: { goalOnly?: boolean },+): Promise<{ goal: GoalItem; reassignedTaskIds: string[] }> => {+ if (agentId) {+ await assertAgentUsableBy(ctx.db, agentId, {+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }+ const current = await ctx.goalModel.findById(goalId);+ if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ // Naming the goal agent itself is the same as clearing: one agent, one slot.+ const goal = await ctx.goalModel.updateTaskAgentId(+ goalId,+ agentId && agentId !== current.agentId ? agentId : null,+ );+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });++ const assignee = goalTaskAgentId(goal);+ const reassignedTaskIds =+ options?.goalOnly || !assignee ? [] : await ctx.reassignUnfinishedTasks(goalId, assignee);+ return { goal, reassignedTaskIds };+};++/**+ * The agent the next coordinator-created Task goes to.+ *+ * `taskAgentId` lives in JSON, so deleting the executor does not null it the+ * way the `agent_id` foreign key is nulled. Handing that stale id to+ * `createTask` fails with NOT_FOUND on every tick and the goal can never+ * create work again โ so a missing executor falls back to the goal agent.+ */+export const resolveTaskAssignee = async (ctx: GoalServiceContext, goal: GoalItem) => {+ const taskAgentId = goal.config?.taskAgentId;+ if (taskAgentId && !(await ctx.agentModel.existsById(taskAgentId)))+ return goal.agentId ?? undefined;+ return goalTaskAgentId(goal);+};++/**+ * Snapshot the graph AFTER the goal row moved: a task the coordinator binds+ * later inherits the new assignee from the goal, and a task bound before is in+ * this snapshot โ so no concurrently created task can slip through the+ * handoff still pointing at the previous agent. A Task mid-run keeps its+ * current operation; `runTask` reads the assignee at its next dispatch.+ */+export const reassignUnfinishedTasks = async (+ ctx: GoalServiceContext,+ goalId: string,+ agentId: string,+) => {+ const graph = await ctx.requireGraph(goalId);+ const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));+ const reassigned: string[] = [];+ for (const task of await ctx.taskModel.findByIds(taskIds)) {+ if (task.status === 'completed' || task.status === 'canceled') continue;+ if (task.assigneeAgentId === agentId) continue;+ await ctx.taskModel.update(task.id, { assigneeAgentId: agentId });+ reassigned.push(task.id);+ }+ return reassigned;+};++/**+ * Task access under the goal owner's principal โ the identity the goal's+ * coordinator creates and runs its Tasks as. Only for acting on Tasks already+ * bound to this goal's nodes, after the caller's right to manage the goal has+ * been checked.+ */+export const goalOwnerTaskScope = (ctx: GoalServiceContext, goal: { userId: string }) =>+ goal.userId === ctx.userId+ ? {+ taskModel: ctx.taskModel,+ taskService: ctx.taskService,+ taskTopicModel: ctx.taskTopicModel,+ }+ : {+ taskModel: new TaskModel(ctx.db, goal.userId, ctx.workspaceId),+ taskService: new TaskService(ctx.db, goal.userId, ctx.workspaceId),+ taskTopicModel: new TaskTopicModel(ctx.db, goal.userId, ctx.workspaceId),+ };++/**+ * Stop the Tasks bound to nodes already fenced as `retired`, so a retired+ * node cannot keep spending or deliver into the Goal afterwards. Bound Tasks+ * are read after the fence so a Task bound just before it is included.+ * Returns the graph as read after the fence.+ */+export const stopFencedTasks = async (+ ctx: GoalServiceContext,+ goalId: string,+ targetIds: ReadonlySet<string>,+) => {+ const fenced = await ctx.requireGraph(goalId);+ const taskIds = fenced.nodes.flatMap((node) =>+ targetIds.has(node.id) && node.taskId ? [node.taskId] : [],+ );+ if (taskIds.length > 0) {+ // The caller may be a workspace owner retiring a colleague's goal (the+ // router authorizes that). The nodes' Tasks were created by the goal's+ // coordinator, which runs as the goal's owner โ and may be `private`,+ // inherited from that owner's private agent โ so reads under the caller's+ // visibility would miss them and leave them running. Stop them under the+ // goal owner's principal instead, limited to the Tasks bound to the nodes+ // being retired.+ const { taskModel, taskService, taskTopicModel } = ctx.goalOwnerTaskScope(fenced.goal);+ const cancelTasks = async () => {+ for (const id of taskIds) {+ // CAS against the status just read; a runner flipping the Task to+ // `running` in between makes it miss, so re-read and try again.+ for (let attempt = 0; attempt < 3; attempt++) {+ const [task] = await taskModel.findByIds([id]);+ if (!task || ['canceled', 'completed', 'failed'].includes(task.status)) break;+ if (await taskModel.updateStatusIfCurrent(id, task.status, 'canceled')) break;+ }+ }+ };+ // Cancel the Tasks FIRST: that is the fence a run still being dispatched+ // checks under the Task's row lock before recording its operation, so a+ // run started from here on stops itself (TaskRunnerService.runTask).+ // Runs recorded before the fence are then found and stopped below.+ await cancelTasks();+ for (const topic of await taskTopicModel.findRunningByTaskIds(taskIds)) {+ if (topic.topicId) await taskService.cancelTopic(topic.topicId);+ }+ // `cancelTopic` parks its Task as `paused`; settle them back to canceled.+ await cancelTasks();+ }++ return fenced;+};++/**+ * Retire Task nodes a person no longer wants run โ a duplicated plan branch,+ * work that landed elsewhere. Without this a stray node that never got a Task+ * stays unfinished forever and the coordinator can never reach acceptance.+ *+ * Nodes are retired as one set: any unfinished Task still depending on a node+ * in the set must be in the set too, otherwise it would wait on a+ * prerequisite that will never resolve.+ */+export const retireNodes = async (+ ctx: GoalServiceContext,+ goalId: string,+ nodeIds: string[],+ reason?: string,+): Promise<{ retiredNodeIds: string[] }> => {+ const graph = await ctx.requireGraph(goalId);+ const targetIds = new Set(nodeIds);++ const targets = [...targetIds].map((nodeId) => {+ const node = graph.nodes.find((item) => item.id === nodeId);+ if (!node) throw new TRPCError({ code: 'NOT_FOUND', message: `Node ${nodeId} not found` });+ if (node.kind !== 'task') {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Node ${nodeId} is a ${node.kind}; only task nodes can be retired`,+ });+ }+ // An already-retired node is accepted so an interrupted retirement (its+ // fence landed, stopping the run did not) can be finished by retrying.+ if (node.status !== 'retired' && TERMINAL_NODE_STATUSES.has(node.status)) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Node ${nodeId} is already ${node.status}`,+ });+ }+ // Retiring the terminal acceptance fails the whole Goal; that verdict+ // belongs to its decision gate, not to a graph edit.+ if (node.title === GOAL_ACCEPTANCE_TASK_TITLE) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'The Goal acceptance task cannot be retired',+ });+ }+ return node;+ });++ const strandedIds = graph.edges+ .filter(+ (edge) =>+ edge.kind === 'depends_on' &&+ targetIds.has(edge.targetNodeId) &&+ !targetIds.has(edge.sourceNodeId),+ )+ .map((edge) => graph.nodes.find((node) => node.id === edge.sourceNodeId))+ .filter(+ (node): node is NonNullable<typeof node> =>+ !!node && node.kind === 'task' && !TERMINAL_NODE_STATUSES.has(node.status),+ )+ .map((node) => node.id);+ if (strandedIds.length > 0) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: `Unfinished tasks depend on these nodes; retire them together: ${[...new Set(strandedIds)].join(', ')}`,+ });+ }++ // Fence the nodes BEFORE looking for their Tasks. The snapshot above can+ // miss a Task a concurrent tick is creating for a proposed node; once the+ // node reads `retired`, `bindTask` (which only binds an `active` node) can+ // no longer attach that Task, and the creator discards it.+ for (const node of targets) {+ if (node.status === 'retired') continue;+ await ctx.graphModel.updateNodeStatus(goalId, node.id, 'retired', reason);+ }++ // Stop what the nodes are still running, so a retired node cannot keep+ // spending or deliver into the Goal afterwards.+ const fenced = await ctx.stopFencedTasks(goalId, targetIds);++ // A pending recovery gate on a retired node asks a question nobody needs+ // answered any more; left pending it keeps the Goal parked in review.+ for (const decision of fenced.decisions) {+ if (decision.status !== 'pending') continue;+ const gatedByTarget = fenced.edges.some(+ (edge) =>+ edge.kind === 'leads_to' &&+ edge.targetNodeId === decision.nodeId &&+ targetIds.has(edge.sourceNodeId),+ );+ if (gatedByTarget) {+ await ctx.graphModel.cancelDecision(goalId, decision.id, 'Superseded by node retirement');+ }+ }++ // Reopen a goal the coordinator parked because of what was just retired:+ // `review` held by the retired node's gate, or `paused` by `no_frontier`+ // (the stray branch left nothing runnable). A pause somebody chose โ or+ // one the coordinator took for another reason, like a budget โ is left.+ const after = await ctx.requireGraph(goalId);+ const lastTransition = after.events.find((event) => event.entityType === 'goal');+ const parkedOnNoFrontier =+ after.goal.status === 'paused' &&+ !after.goal.config?.pausedBy &&+ lastTransition?.actorType !== 'user' &&+ lastTransition?.reason === NO_FRONTIER_PAUSE_REASON;+ if (after.goal.status === 'review' || parkedOnNoFrontier) {+ const hasPendingDecision = after.decisions.some((decision) => decision.status === 'pending');+ if (!hasPendingDecision) {+ await ctx.transitionStatus(after.goal, 'running', 'nodes retired by user', 'user');+ } else if (parkedOnNoFrontier) {+ await ctx.transitionStatus(after.goal, 'review', 'nodes retired by user', 'user');+ }+ }++ return { retiredNodeIds: targets.map((node) => node.id) };+};++export const setBudget = async (+ ctx: GoalServiceContext,+ goalId: string,+ budget: {+ deadline?: string | null;+ maxAttemptsPerTask?: number;+ maxConcurrentTasks?: number | null;+ maxExperiments?: number;+ maxManagerTurns?: number;+ maxRounds?: number | null;+ maxStepsPerRun?: number | null;+ maxTotalCost?: number | null;+ },+) => {+ const before = await ctx.requireGraph(goalId);+ const wasBinding = await ctx.evaluateBudget(before.goal, before);+ const managerTurnsWereSpent = managerTurnsSpent(before.goal.config);++ // Deadline joins the two execution budgets on the goal row's config; null+ // clears it, and omitting it leaves it alone โ the cost/round editor sends+ // only what it owns, and must not silently drop a deadline someone set.+ // The merge keeps an untouched recovery/schedule block intact.+ const config = { ...before.goal.config };+ if (budget.maxExperiments !== undefined) {+ if (+ !config.exploration ||+ !Number.isInteger(budget.maxExperiments) ||+ budget.maxExperiments < 1 ||+ budget.maxExperiments > 200+ ) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'An exploration Goal requires 1โ200 experiments',+ });+ }+ config.exploration = { ...config.exploration, maxExperiments: budget.maxExperiments };+ }+ if (budget.deadline !== undefined) {+ config.schedule = { ...config.schedule, deadline: budget.deadline };+ }+ // The limits a goal is created with stay editable: a goal that ran into one+ // must be continued with a higher one, not replaced by a copy of itself.+ if (budget.maxManagerTurns !== undefined) {+ if (!config.manager) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Only a Goal with a main Agent has a turn budget',+ });+ }+ config.manager = { ...config.manager, maxTurns: budget.maxManagerTurns };+ }+ if (budget.maxConcurrentTasks !== undefined) {+ config.maxConcurrentTasks = budget.maxConcurrentTasks;+ }+ if (budget.maxAttemptsPerTask !== undefined || budget.maxStepsPerRun !== undefined) {+ config.recovery = {+ ...config.recovery,+ ...(budget.maxAttemptsPerTask !== undefined && {+ maxAttemptsPerTask: budget.maxAttemptsPerTask,+ }),+ ...(budget.maxStepsPerRun !== undefined && { maxStepsPerRun: budget.maxStepsPerRun }),+ };+ }++ const goal = await ctx.goalModel.update(goalId, {+ config,+ maxRounds: budget.maxRounds,+ maxTotalCost: budget.maxTotalCost,+ });+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });++ // Raising a budget is how a user un-sticks a goal the coordinator parked on+ // one, and `tick` refuses to move a paused goal โ so without this the+ // queued advance would return straight away and the user would have to find+ // Resume as a second gesture. Only a goal the budget actually stopped is+ // reopened: if the old budget was not binding, this pause was somebody's+ // deliberate one and is left alone.+ const stoppedByBudget =+ wasBinding.costLimitReached || wasBinding.roundLimitReached || wasBinding.deadlinePassed;+ const stoppedByExploration = before.goal.config?.pausedBy === 'exploration_limit';+ // The main Agent pauses its goal when its turns run out, and resuming alone+ // pauses it again on the next tick. Raising the cap is what lets it continue.+ const stoppedByManagerTurns = managerTurnsWereSpent && !managerTurnsSpent(goal.config);+ if (+ goal.status !== 'paused' ||+ goal.config?.pausedBy === 'user' ||+ (!stoppedByBudget && !stoppedByExploration && !stoppedByManagerTurns)+ )+ return goal;+ if (+ stoppedByExploration &&+ before.nodes.filter(+ (node) =>+ node.kind === 'task' &&+ node.title !== GOAL_ACCEPTANCE_TASK_TITLE &&+ !isGoalReportNode(before, node),+ ).length >= (goal.config?.exploration?.maxExperiments ?? 0)+ )+ return goal;++ const nowBinding = await ctx.evaluateBudget(goal, before);+ if (nowBinding.costLimitReached || nowBinding.roundLimitReached || nowBinding.deadlinePassed) {+ return goal;+ }++ return (await ctx.resume(goalId)) ?? goal;+};diff --git a/apps/server/src/services/goal/GoalService/index.ts b/apps/server/src/services/goal/GoalService/index.tsnew file mode 100644index 00000000000..52ed6d44a75--- /dev/null+++ b/apps/server/src/services/goal/GoalService/index.ts@@ -0,0 +1,514 @@+import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';++import { AgentModel } from '@/database/models/agent';+import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { WorkModel } from '@/database/models/work';+import type { LobeChatDatabase } from '@/database/type';++import { TaskService } from '../../task';+import { AcceptanceService } from '../../verify/acceptanceService';+import { GoalBriefService } from '../goalBriefs';+import { GoalReleaseReview } from '../releaseReview';+import {+ attachTaskDeliverables,+ consumeCompletedTask,+ recoverAfterVerification,+ settleTerminalAcceptance,+} from './completion';+import { bindTopic, create, createFromConversation, resolveTopicRun } from './creation';+import {+ answerClarifications,+ decide,+ gateOrTakeOver,+ openFailureDecision,+ openFailureDecisionLocked,+ reopenForChanges,+} from './decisions';+import {+ buildTaskAcceptanceRequirement,+ buildTaskInstruction,+ createResponsibleTask,+ dispatchWork,+ ensureTaskWorkVersion,+} from './dispatch';+import {+ addEdge,+ addNode,+ followGoalAgent,+ goalOwnerTaskScope,+ graphAs,+ reassignUnfinishedTasks,+ resolveTaskAssignee,+ retireNodes,+ setAgent,+ setBudget,+ setTaskAgent,+ stopFencedTasks,+ updateRequirement,+} from './editing';+import {+ close,+ deleteGoal,+ pause,+ requestSignOff,+ restart,+ resume,+ transitionStatus,+} from './lifecycle';+import {+ evaluateBudget,+ evaluateMetricCriteria,+ isParkedOnMeasuredGate,+ recordObservation,+ reopenIfMeasurementCleared,+ resolveSpend,+ setAcceptanceCriteria,+ setMetricCriteria,+ setPauseReason,+} from './measurement';+import { handPlanningToMainAgent, planDecomposition } from './planning';+import {+ collectAcceptances,+ collectAssignees,+ collectDeliveredAt,+ collectRunHeartbeats,+ graph,+ listEvents,+ pendingClarifications,+ pendingForIsland,+ requireGraph,+ status,+} from './reads';+import {+ holdForMachineFailure,+ holdForOfflineDevice,+ markRunLostToOfflineDevice,+ planMachineRecoveryFor,+ readRunDevicePresence,+ recoverAbandonedTask,+ recoverLostRun,+ resumeAbandonedTaskRecovery,+ waitForDevice,+ waitForQuotaReset,+} from './recovery';+import {+ collectRolloutGate,+ isBatchMember,+ openPatternBreakGate,+ restartRolloutLoop,+} from './rollout';+import { dispatchGoalReport, tick, tickOnce } from './tick';+import type { GoalServiceContext, MethodArgs } from './types';++export type { CreateGoalGraphInput, CreateGoalNodeInput, CreateGoalTaskInput } from './types';+export { goalTaskAgentId } from './utils';++/**+ * Application service shared by CLI today and Graph UI/schedulers later. The+ * class holds the collaborators and delegates every method to a sibling module+ * in this directory, handing it the `GoalServiceContext` view.+ */+export class GoalService {+ private readonly acceptanceService: AcceptanceService;+ private readonly agentModel: AgentModel;+ /** What the goal tells the person through the inbox: gates, sign-off, findings. */+ private readonly briefs: GoalBriefService;+ private readonly releaseReview: GoalReleaseReview;+ private readonly goalModel: GoalModel;+ /**+ * Graph writes attributed to the person who asked for them: seeding a goal,+ * adding a node or edge by hand, resolving a decision gate.+ */+ private readonly graphModel: GoalGraphModel;+ /**+ * Graph writes the coordinator makes on its own โ claiming a Task node,+ * binding its task, synthesizing a finding, opening a gate. Attributed to the coordinator+ * even when a person pressed Advance: they asked it to run, they did not make+ * these moves.+ */+ private readonly coordinatorGraph: GoalGraphModel;+ private readonly taskModel: TaskModel;+ private readonly taskService: TaskService;+ private readonly taskTopicModel: TaskTopicModel;+ private readonly workModel: WorkModel;++ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {+ this.acceptanceService = new AcceptanceService(db, userId, workspaceId);+ this.agentModel = new AgentModel(db, userId, workspaceId);+ this.briefs = new GoalBriefService(db, userId, workspaceId);+ this.goalModel = new GoalModel(db, userId, workspaceId);+ this.releaseReview = new GoalReleaseReview(db, userId, workspaceId, {+ briefs: this.briefs,+ decide: (...args) => this.decide(...args),+ graph: (goalId) => this.graph(goalId),+ requireGraph: (goalId) => this.requireGraph(goalId),+ setPauseReason: (goalId, reason) => this.setPauseReason(goalId, reason),+ transitionStatus: (goal, to, reason) => this.transitionStatus(goal, to, reason),+ });+ this.graphModel = new GoalGraphModel(db, userId, workspaceId);+ this.coordinatorGraph = new GoalGraphModel(db, userId, workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ });+ this.taskModel = new TaskModel(db, userId, workspaceId);+ this.taskService = new TaskService(db, userId, workspaceId);+ this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);+ this.workModel = new WorkModel(db, userId, workspaceId);+ }++ /**+ * The view the method modules get: the collaborators through getters, so a+ * module reads a field when it uses it, and the methods through arrows, so a+ * call still dispatches on the instance.+ */+ private get context(): GoalServiceContext {+ // eslint-disable-next-line @typescript-eslint/no-this-alias+ const self = this;+ return {+ get acceptanceService() {+ return self.acceptanceService;+ },+ addEdge: (...args) => self.addEdge(...args),+ addNode: (...args) => self.addNode(...args),+ get agentModel() {+ return self.agentModel;+ },+ answerClarifications: (...args) => self.answerClarifications(...args),+ answerReleaseGate: (...args) => self.answerReleaseGate(...args),+ attachTaskDeliverables: (...args) => self.attachTaskDeliverables(...args),+ bindTopic: (...args) => self.bindTopic(...args),+ get briefs() {+ return self.briefs;+ },+ buildTaskAcceptanceRequirement: (...args) => self.buildTaskAcceptanceRequirement(...args),+ buildTaskInstruction: (...args) => self.buildTaskInstruction(...args),+ close: (...args) => self.close(...args),+ collectAcceptances: (...args) => self.collectAcceptances(...args),+ collectAssignees: (...args) => self.collectAssignees(...args),+ collectDeliveredAt: (...args) => self.collectDeliveredAt(...args),+ collectRolloutGate: (...args) => self.collectRolloutGate(...args),+ collectRunHeartbeats: (...args) => self.collectRunHeartbeats(...args),+ consumeCompletedTask: (...args) => self.consumeCompletedTask(...args),+ get coordinatorGraph() {+ return self.coordinatorGraph;+ },+ create: (...args) => self.create(...args),+ createFromConversation: (...args) => self.createFromConversation(...args),+ createResponsibleTask: (...args) => self.createResponsibleTask(...args),+ get db() {+ return self.db;+ },+ decide: (...args) => self.decide(...args),+ delete: (...args) => self.delete(...args),+ dispatchGoalReport: (...args) => self.dispatchGoalReport(...args),+ dispatchWork: (...args) => self.dispatchWork(...args),+ ensureTaskWorkVersion: (...args) => self.ensureTaskWorkVersion(...args),+ evaluateBudget: (...args) => self.evaluateBudget(...args),+ evaluateMetricCriteria: (...args) => self.evaluateMetricCriteria(...args),+ followGoalAgent: (...args) => self.followGoalAgent(...args),+ gateOrTakeOver: (...args) => self.gateOrTakeOver(...args),+ get goalModel() {+ return self.goalModel;+ },+ goalOwnerTaskScope: (...args) => self.goalOwnerTaskScope(...args),+ graph: (...args) => self.graph(...args),+ graphAs: (...args) => self.graphAs(...args),+ get graphModel() {+ return self.graphModel;+ },+ handPlanningToMainAgent: (...args) => self.handPlanningToMainAgent(...args),+ holdForMachineFailure: (...args) => self.holdForMachineFailure(...args),+ holdForOfflineDevice: (...args) => self.holdForOfflineDevice(...args),+ inTransaction: (tx) => new GoalService(tx, self.userId, self.workspaceId).context,+ isBatchMember: (...args) => self.isBatchMember(...args),+ isParkedOnMeasuredGate: (...args) => self.isParkedOnMeasuredGate(...args),+ listEvents: (...args) => self.listEvents(...args),+ markRunLostToOfflineDevice: (...args) => self.markRunLostToOfflineDevice(...args),+ openFailureDecision: (...args) => self.openFailureDecision(...args),+ openFailureDecisionLocked: (...args) => self.openFailureDecisionLocked(...args),+ openPatternBreakGate: (...args) => self.openPatternBreakGate(...args),+ pause: (...args) => self.pause(...args),+ pendingClarifications: (...args) => self.pendingClarifications(...args),+ pendingForIsland: (...args) => self.pendingForIsland(...args),+ planDecomposition: (...args) => self.planDecomposition(...args),+ planMachineRecoveryFor: (...args) => self.planMachineRecoveryFor(...args),+ readRunDevicePresence: (...args) => self.readRunDevicePresence(...args),+ reassignUnfinishedTasks: (...args) => self.reassignUnfinishedTasks(...args),+ recordObservation: (...args) => self.recordObservation(...args),+ recoverAbandonedTask: (...args) => self.recoverAbandonedTask(...args),+ recoverAfterVerification: (...args) => self.recoverAfterVerification(...args),+ recoverLostRun: (...args) => self.recoverLostRun(...args),+ get releaseReview() {+ return self.releaseReview;+ },+ reopenForChanges: (...args) => self.reopenForChanges(...args),+ reopenIfMeasurementCleared: (...args) => self.reopenIfMeasurementCleared(...args),+ requestSignOff: (...args) => self.requestSignOff(...args),+ requireGraph: (...args) => self.requireGraph(...args),+ resolveSpend: (...args) => self.resolveSpend(...args),+ resolveTaskAssignee: (...args) => self.resolveTaskAssignee(...args),+ resolveTopicRun: (...args) => self.resolveTopicRun(...args),+ restart: (...args) => self.restart(...args),+ restartRolloutLoop: (...args) => self.restartRolloutLoop(...args),+ resume: (...args) => self.resume(...args),+ resumeAbandonedTaskRecovery: (...args) => self.resumeAbandonedTaskRecovery(...args),+ retireNodes: (...args) => self.retireNodes(...args),+ setAcceptanceCriteria: (...args) => self.setAcceptanceCriteria(...args),+ setAgent: (...args) => self.setAgent(...args),+ setBudget: (...args) => self.setBudget(...args),+ setMetricCriteria: (...args) => self.setMetricCriteria(...args),+ setPauseReason: (...args) => self.setPauseReason(...args),+ setTaskAgent: (...args) => self.setTaskAgent(...args),+ settleTerminalAcceptance: (...args) => self.settleTerminalAcceptance(...args),+ status: (...args) => self.status(...args),+ stopFencedTasks: (...args) => self.stopFencedTasks(...args),+ get taskModel() {+ return self.taskModel;+ },+ get taskService() {+ return self.taskService;+ },+ get taskTopicModel() {+ return self.taskTopicModel;+ },+ tick: (...args) => self.tick(...args),+ tickOnce: (...args) => self.tickOnce(...args),+ transitionStatus: (...args) => self.transitionStatus(...args),+ updateRequirement: (...args) => self.updateRequirement(...args),+ get userId() {+ return self.userId;+ },+ waitForDevice: (...args) => self.waitForDevice(...args),+ waitForQuotaReset: (...args) => self.waitForQuotaReset(...args),+ get workModel() {+ return self.workModel;+ },+ get workspaceId() {+ return self.workspaceId;+ },+ };+ }++ private graphAs = (...args: MethodArgs<typeof graphAs>) => graphAs(this.context, ...args);++ createFromConversation = (...args: MethodArgs<typeof createFromConversation>) =>+ createFromConversation(this.context, ...args);++ private resolveTopicRun = (...args: MethodArgs<typeof resolveTopicRun>) =>+ resolveTopicRun(this.context, ...args);++ bindTopic = (...args: MethodArgs<typeof bindTopic>) => bindTopic(this.context, ...args);++ create = (...args: MethodArgs<typeof create>) => create(this.context, ...args);++ recordObservation = (...args: MethodArgs<typeof recordObservation>) =>+ recordObservation(this.context, ...args);++ private reopenIfMeasurementCleared = (...args: MethodArgs<typeof reopenIfMeasurementCleared>) =>+ reopenIfMeasurementCleared(this.context, ...args);++ private setPauseReason = (...args: MethodArgs<typeof setPauseReason>) =>+ setPauseReason(this.context, ...args);++ private isParkedOnMeasuredGate = (...args: MethodArgs<typeof isParkedOnMeasuredGate>) =>+ isParkedOnMeasuredGate(this.context, ...args);++ setMetricCriteria = (...args: MethodArgs<typeof setMetricCriteria>) =>+ setMetricCriteria(this.context, ...args);++ setAcceptanceCriteria = (...args: MethodArgs<typeof setAcceptanceCriteria>) =>+ setAcceptanceCriteria(this.context, ...args);++ graph = (...args: MethodArgs<typeof graph>) => graph(this.context, ...args);++ listEvents = (...args: MethodArgs<typeof listEvents>) => listEvents(this.context, ...args);++ private collectAssignees = (...args: MethodArgs<typeof collectAssignees>) =>+ collectAssignees(this.context, ...args);++ private requestSignOff = (...args: MethodArgs<typeof requestSignOff>) =>+ requestSignOff(this.context, ...args);++ private collectAcceptances = (...args: MethodArgs<typeof collectAcceptances>) =>+ collectAcceptances(this.context, ...args);++ private collectDeliveredAt = (...args: MethodArgs<typeof collectDeliveredAt>) =>+ collectDeliveredAt(this.context, ...args);++ private collectRunHeartbeats = (...args: MethodArgs<typeof collectRunHeartbeats>) =>+ collectRunHeartbeats(this.context, ...args);++ status = (...args: MethodArgs<typeof status>) => status(this.context, ...args);++ addNode = (...args: MethodArgs<typeof addNode>) => addNode(this.context, ...args);++ addEdge = (...args: MethodArgs<typeof addEdge>) => addEdge(this.context, ...args);++ delete = (...args: MethodArgs<typeof deleteGoal>) => deleteGoal(this.context, ...args);++ private transitionStatus = (...args: MethodArgs<typeof transitionStatus>) =>+ transitionStatus(this.context, ...args);++ pause = (...args: MethodArgs<typeof pause>) => pause(this.context, ...args);++ private evaluateMetricCriteria = (...args: MethodArgs<typeof evaluateMetricCriteria>) =>+ evaluateMetricCriteria(this.context, ...args);++ private evaluateBudget = (...args: MethodArgs<typeof evaluateBudget>) =>+ evaluateBudget(this.context, ...args);++ private resolveSpend = (...args: MethodArgs<typeof resolveSpend>) =>+ resolveSpend(this.context, ...args);++ updateRequirement = (...args: MethodArgs<typeof updateRequirement>) =>+ updateRequirement(this.context, ...args);++ setAgent = (...args: MethodArgs<typeof setAgent>) => setAgent(this.context, ...args);++ private followGoalAgent = (...args: MethodArgs<typeof followGoalAgent>) =>+ followGoalAgent(this.context, ...args);++ setTaskAgent = (...args: MethodArgs<typeof setTaskAgent>) => setTaskAgent(this.context, ...args);++ private resolveTaskAssignee = (...args: MethodArgs<typeof resolveTaskAssignee>) =>+ resolveTaskAssignee(this.context, ...args);++ private reassignUnfinishedTasks = (...args: MethodArgs<typeof reassignUnfinishedTasks>) =>+ reassignUnfinishedTasks(this.context, ...args);++ restart = (...args: MethodArgs<typeof restart>) => restart(this.context, ...args);++ private goalOwnerTaskScope = (...args: MethodArgs<typeof goalOwnerTaskScope>) =>+ goalOwnerTaskScope(this.context, ...args);++ private stopFencedTasks = (...args: MethodArgs<typeof stopFencedTasks>) =>+ stopFencedTasks(this.context, ...args);++ retireNodes = (...args: MethodArgs<typeof retireNodes>) => retireNodes(this.context, ...args);++ setBudget = (...args: MethodArgs<typeof setBudget>) => setBudget(this.context, ...args);++ resume = (...args: MethodArgs<typeof resume>) => resume(this.context, ...args);++ close = (...args: MethodArgs<typeof close>) => close(this.context, ...args);++ decide = (...args: MethodArgs<typeof decide>) => decide(this.context, ...args);++ reopenForChanges = (...args: MethodArgs<typeof reopenForChanges>) =>+ reopenForChanges(this.context, ...args);++ answerClarifications = (...args: MethodArgs<typeof answerClarifications>) =>+ answerClarifications(this.context, ...args);++ pendingForIsland = (...args: MethodArgs<typeof pendingForIsland>) =>+ pendingForIsland(this.context, ...args);++ pendingClarifications = (...args: MethodArgs<typeof pendingClarifications>) =>+ pendingClarifications(this.context, ...args);++ tick = (...args: MethodArgs<typeof tick>) => tick(this.context, ...args);++ private dispatchGoalReport = (...args: MethodArgs<typeof dispatchGoalReport>) =>+ dispatchGoalReport(this.context, ...args);++ private tickOnce = (...args: MethodArgs<typeof tickOnce>) => tickOnce(this.context, ...args);++ private settleTerminalAcceptance = (...args: MethodArgs<typeof settleTerminalAcceptance>) =>+ settleTerminalAcceptance(this.context, ...args);++ private createResponsibleTask = (...args: MethodArgs<typeof createResponsibleTask>) =>+ createResponsibleTask(this.context, ...args);++ private recoverAfterVerification = (...args: MethodArgs<typeof recoverAfterVerification>) =>+ recoverAfterVerification(this.context, ...args);++ private dispatchWork = (...args: MethodArgs<typeof dispatchWork>) =>+ dispatchWork(this.context, ...args);++ private requireGraph = (...args: MethodArgs<typeof requireGraph>) =>+ requireGraph(this.context, ...args);++ private ensureTaskWorkVersion = (...args: MethodArgs<typeof ensureTaskWorkVersion>) =>+ ensureTaskWorkVersion(this.context, ...args);++ private recoverAbandonedTask = (...args: MethodArgs<typeof recoverAbandonedTask>) =>+ recoverAbandonedTask(this.context, ...args);++ private recoverLostRun = (...args: MethodArgs<typeof recoverLostRun>) =>+ recoverLostRun(this.context, ...args);++ private markRunLostToOfflineDevice = (...args: MethodArgs<typeof markRunLostToOfflineDevice>) =>+ markRunLostToOfflineDevice(this.context, ...args);++ private resumeAbandonedTaskRecovery = (...args: MethodArgs<typeof resumeAbandonedTaskRecovery>) =>+ resumeAbandonedTaskRecovery(this.context, ...args);++ private planMachineRecoveryFor = (...args: MethodArgs<typeof planMachineRecoveryFor>) =>+ planMachineRecoveryFor(this.context, ...args);++ private holdForMachineFailure = (...args: MethodArgs<typeof holdForMachineFailure>) =>+ holdForMachineFailure(this.context, ...args);++ private waitForDevice = (...args: MethodArgs<typeof waitForDevice>) =>+ waitForDevice(this.context, ...args);++ private waitForQuotaReset = (...args: MethodArgs<typeof waitForQuotaReset>) =>+ waitForQuotaReset(this.context, ...args);++ private holdForOfflineDevice = (...args: MethodArgs<typeof holdForOfflineDevice>) =>+ holdForOfflineDevice(this.context, ...args);++ private readRunDevicePresence = (...args: MethodArgs<typeof readRunDevicePresence>) =>+ readRunDevicePresence(this.context, ...args);++ private buildTaskInstruction = (...args: MethodArgs<typeof buildTaskInstruction>) =>+ buildTaskInstruction(this.context, ...args);++ private planDecomposition = (...args: MethodArgs<typeof planDecomposition>) =>+ planDecomposition(this.context, ...args);++ private handPlanningToMainAgent = (...args: MethodArgs<typeof handPlanningToMainAgent>) =>+ handPlanningToMainAgent(this.context, ...args);++ private collectRolloutGate = (...args: MethodArgs<typeof collectRolloutGate>) =>+ collectRolloutGate(this.context, ...args);++ private isBatchMember = (...args: MethodArgs<typeof isBatchMember>) =>+ isBatchMember(this.context, ...args);++ /** Answer a held release from its review report; see {@link GoalReleaseReview.answerReleaseGate}. */+ answerReleaseGate: GoalReleaseReview['answerReleaseGate'] = (...args) =>+ this.releaseReview.answerReleaseGate(...args);++ private openPatternBreakGate = (...args: MethodArgs<typeof openPatternBreakGate>) =>+ openPatternBreakGate(this.context, ...args);++ private restartRolloutLoop = (...args: MethodArgs<typeof restartRolloutLoop>) =>+ restartRolloutLoop(this.context, ...args);++ private buildTaskAcceptanceRequirement = (+ ...args: MethodArgs<typeof buildTaskAcceptanceRequirement>+ ) => buildTaskAcceptanceRequirement(this.context, ...args);++ private attachTaskDeliverables = (...args: MethodArgs<typeof attachTaskDeliverables>) =>+ attachTaskDeliverables(this.context, ...args);++ private consumeCompletedTask = (...args: MethodArgs<typeof consumeCompletedTask>) =>+ consumeCompletedTask(this.context, ...args);++ private gateOrTakeOver = (...args: MethodArgs<typeof gateOrTakeOver>) =>+ gateOrTakeOver(this.context, ...args);++ private openFailureDecision = (...args: MethodArgs<typeof openFailureDecision>) =>+ openFailureDecision(this.context, ...args);++ private openFailureDecisionLocked = (...args: MethodArgs<typeof openFailureDecisionLocked>) =>+ openFailureDecisionLocked(this.context, ...args);+}diff --git a/apps/server/src/services/goal/GoalService/lifecycle.ts b/apps/server/src/services/goal/GoalService/lifecycle.tsnew file mode 100644index 00000000000..fc7ffc99860--- /dev/null+++ b/apps/server/src/services/goal/GoalService/lifecycle.ts@@ -0,0 +1,438 @@+import type { GoalGraphSnapshot, GoalItem, GoalStatus } from '@lobechat/types';+import { TRPCError } from '@trpc/server';++import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { assertAgentUsableBy } from '@/database/utils/agent-access';++import { GOAL_ACCEPTANCE_TASK_TITLE, TERMINAL_NODE_STATUSES } from '../decideNextMove';+import { GoalManagerService } from '../manager';+import { resolveOperationLeaseTimeout } from '../recoveryPolicy';+import { isGoalReportNode } from '../report';+import { GoalSupervisorService } from '../supervisor';+import type { GoalServiceContext } from './types';++const draftNotStarted = (goalId: string) =>+ new TRPCError({+ code: 'CONFLICT',+ message: `Goal is a draft; start it with lh goal start ${goalId}`,+ });++/**+ * The coordinator calls a goal achieved once its own acceptance passes, but+ * the person who asked for it has not said so yet. Ask them โ wherever they+ * are โ through the inbox, tied to the Goal-level acceptance they sign.+ */+export const requestSignOff = async (ctx: GoalServiceContext, graph: GoalGraphSnapshot) => {+ const terminal = graph.nodes.find(+ (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE && !!node.taskId,+ );+ if (!terminal) return;+ const acceptance = (await ctx.collectAcceptances(graph))?.[terminal.id];+ if (!acceptance) return;+ // `openSignOff` re-reads the acceptance under a row lock: one the owner+ // already signed asks nothing.+ await ctx.briefs.openSignOff(graph.goal, acceptance.id);+};++/**+ * Stop everything the goal has running, then delete it and its graph.+ *+ * Deleting only the goal row cascades the graph away but leaves each graph+ * Task โ and the agent operation behind it โ running, spending the user's+ * budget with nothing left on screen to stop it. The tasks themselves stay:+ * they are ordinary tasks with their own history and acceptance.+ */+export const deleteGoal = async (ctx: GoalServiceContext, goalId: string) => {+ let graph = await ctx.graphModel.getGraph(goalId);+ const managed = !!graph?.goal.config?.manager;+ const supervised =+ !!graph?.goal.config?.supervision?.enabled || !!graph?.goal.config?.supervisorState;+ if (managed || supervised) {+ // Fence new claims before cancellation, then read the latest claimed turn.+ await ctx.db.transaction(async (db) => {+ const model = new GoalModel(db, ctx.userId, ctx.workspaceId);+ const current = await model.lockById(goalId);+ if (current && current.status !== 'paused') {+ await model.updateStatus(goalId, 'paused');+ await new GoalGraphModel(db, ctx.userId, ctx.workspaceId).recordGoalStatus(+ goalId,+ current.status,+ 'paused',+ 'Stopping Goal before deletion',+ );+ }+ });+ graph = await ctx.graphModel.getGraph(goalId);+ if (graph) {+ if (managed) await new GoalManagerService(ctx.db, ctx.userId, ctx.workspaceId).stop(graph);+ if (supervised)+ await new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).stop(graph);+ }+ }+ const taskIds = graph?.nodes.flatMap((node) => (node.taskId ? [node.taskId] : [])) ?? [];++ for (const taskId of taskIds) {+ const topics = await ctx.taskTopicModel.findByTaskId(taskId);+ for (const topic of topics) {+ if (topic.status !== 'running' || !topic.topicId) continue;+ // Deliberately not swallowed. Interrupting can fail โ the runtime or a+ // device gateway may be unreachable โ and going ahead would delete the+ // only surface that can stop an operation which keeps spending. Better+ // to leave the goal intact and say so.+ try {+ await ctx.taskService.cancelTopic(topic.topicId);+ } catch (error) {+ throw new TRPCError({+ cause: error,+ code: 'PRECONDITION_FAILED',+ message:+ 'Could not stop the work still running for this goal, so it was not deleted. Try again once the run is reachable.',+ });+ }+ }+ await ctx.taskModel+ .updateStatusIfCurrent(taskId, 'running', 'paused')+ .catch((error) => console.error('[GoalService.delete] failed to pause task:', error));+ }++ if (managed || supervised) {+ return ctx.db.transaction(async (db) => {+ const model = new GoalModel(db, ctx.userId, ctx.workspaceId);+ const current = await model.lockById(goalId);+ if (+ current &&+ (current.status !== 'paused' ||+ current.config?.managerState?.token !== graph?.goal.config?.managerState?.token ||+ current.config?.managerState?.turns !== graph?.goal.config?.managerState?.turns ||+ current.config?.supervisorState?.revision !==+ graph?.goal.config?.supervisorState?.revision)+ ) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'Goal changed during cancellation; it was not deleted',+ });+ }+ return model.delete(goalId);+ });+ }+ return ctx.goalModel.delete(goalId);+};++/**+ * Move the goal's lifecycle status and leave an event behind.+ *+ * The row update alone made status changes untraceable: `entityType='goal'`+ * events existed in the schema but nothing wrote them, so a goal's+ * planning โ running โ paused โ achieved path could not be reconstructed+ * from its timeline. Transitions the coordinator makes are filed under the+ * coordinator actor; a person's pause/resume keeps the user attribution the+ * model defaults to โ the split that separates what the coordinator decided+ * from what the user asked for relies on.+ *+ * A same-status write is a no-op โ re-stamping `running` on every tick that+ * touches a running goal would flood the timeline the way the unbounded+ * event read flooded the payload.+ */+export const transitionStatus = async (+ ctx: GoalServiceContext,+ goal: GoalItem,+ to: GoalStatus,+ reason?: string,+ actor: 'coordinator' | 'user' = 'coordinator',+): Promise<GoalItem | undefined> => {+ if (goal.status === to) return goal;+ const updated = await ctx.goalModel.updateStatus(goal.id, to);+ if (!updated) return undefined;+ const model = actor === 'coordinator' ? ctx.coordinatorGraph : ctx.graphModel;+ await model+ .recordGoalStatus(goal.id, goal.status, to, reason)+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));+ return updated;+};++export const pause = async (ctx: GoalServiceContext, goalId: string) => {+ const graph = await ctx.requireGraph(goalId);+ // A draft never ran; pausing it would let a later resume skip `start`.+ if (graph.goal.status === 'draft') throw draftNotStarted(goalId);+ // From here the pause is the person's, so no later measurement lifts it.+ // Written even when the goal is already paused โ that transition is a+ // no-op, so this marker is the only record that the person took it over.+ await ctx.setPauseReason(goalId, 'user');+ const goal = await ctx.transitionStatus(graph.goal, 'paused', 'paused by user', 'user');+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ return goal;+};++/**+ * Start every unfinished Task node over: interrupt the run it may still be+ * holding, clear the failure it may be parked on, and return the Task to+ * `backlog` so the next coordinator tick dispatches it afresh. Optionally+ * hands the restarted Tasks to a different agent in the same gesture โ the+ * goal's executor slot moves with them: `taskAgentId` when the goal routes+ * work to a dedicated executor, otherwise the goal agent that does its own+ * Tasks. Resolved nodes and their completed Tasks are left untouched.+ */+export const restart = async (+ ctx: GoalServiceContext,+ goalId: string,+ options?: { agentId?: string },+): Promise<{ goal: GoalItem; restartedTaskIds: string[] }> => {+ if (options?.agentId) {+ await assertAgentUsableBy(ctx.db, options.agentId, {+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }+ const graph = await ctx.requireGraph(goalId);++ const unfinishedNodes = graph.nodes.filter(+ (node) =>+ node.kind === 'task' &&+ !isGoalReportNode(graph, node) &&+ node.taskId &&+ !TERMINAL_NODE_STATUSES.has(node.status),+ );+ const unfinishedNodeIds = new Set(unfinishedNodes.map((node) => node.id));+ const unfinishedTaskIds = unfinishedNodes.flatMap((node) => (node.taskId ? [node.taskId] : []));++ // A restarted task's pending failure gate is answered by the restart+ // itself. Left pending, it would keep winning the coordinator's+ // pending-decision branch and the goal would sit `waiting_human` with+ // every task freshly reset. Gates on untouched nodes keep parking the+ // goal โ they ask something this restart does not answer.+ // Gate edges run task-node โ decision-node (see openFailureDecision).+ const staleGates = graph.decisions.filter(+ (decision) =>+ decision.status === 'pending' &&+ graph.edges.some(+ (edge) =>+ edge.kind === 'leads_to' &&+ edge.targetNodeId === decision.nodeId &&+ unfinishedNodeIds.has(edge.sourceNodeId),+ ),+ );+ for (const gate of staleGates) {+ await ctx.graphModel.cancelDecision(goalId, gate.id, 'Superseded by goal restart');+ }++ const restartedTaskIds: string[] = [];+ if (unfinishedTaskIds.length > 0) {+ const runningTopics = await ctx.taskTopicModel.findRunningByTaskIds(unfinishedTaskIds);+ for (const topic of runningTopics) {+ if (topic.topicId) await ctx.taskService.cancelTopic(topic.topicId);+ }+ // Re-read after the cancels and reset via compare-and-swap: a coordinator+ // tick dispatching concurrently moves the row between our read and the+ // write, the CAS loses, and that task is skipped instead of yanked out+ // from under a freshly claimed run (which would double-dispatch it).+ for (const task of await ctx.taskModel.findByIds(unfinishedTaskIds)) {+ if (task.status === 'completed') continue;+ const reset = await ctx.taskModel.updateStatusIfCurrent(task.id, task.status, 'backlog', {+ error: null,+ });+ if (!reset) continue;+ if (options?.agentId) {+ await ctx.taskModel.update(task.id, { assigneeAgentId: options.agentId });+ }+ restartedTaskIds.push(task.id);+ }+ }++ // The handoff lands only after the interrupts succeeded โ a cancelTopic+ // failure above must not leave the goal pointing at the new agent while+ // its tasks and live runs still belong to the old one.+ let goal = graph.goal;+ if (options?.agentId) {+ const updated = goal.config?.taskAgentId+ ? await ctx.goalModel.updateTaskAgentId(goalId, options.agentId)+ : await ctx.goalModel.update(goalId, { agentId: options.agentId });+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ goal = updated;+ }++ // A restart is an explicit "start over": a goal parked by a budget stop or+ // a manual pause must begin ticking again without a second gesture.+ if (goal.status === 'paused') {+ goal = (await ctx.resume(goalId)) ?? goal;+ }+ return { goal, restartedTaskIds };+};++export const resume = async (ctx: GoalServiceContext, goalId: string) => {+ const graph = await ctx.requireGraph(goalId);+ const status = graph.decisions.some((decision) => decision.status === 'pending')+ ? 'review'+ : 'running';+ // Compare-and-set under the row lock `close` commits under: a resume that+ // read the goal before a concurrent close ended it must not write its stale+ // `running` over the ended goal, where the close already put interrupted+ // Tasks back to `backlog` and they would dispatch again. Reopening an ended+ // goal still works โ that resume reads the ended status itself.+ return ctx.db.transaction(async (tx) => {+ const model = new GoalModel(tx, ctx.userId, ctx.workspaceId);+ const current = await model.lockById(goalId);+ if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ // Only `start` launches a draft: it settles the creating run's planning+ // turn and checks who may launch it, which a plain status flip skips.+ if (current.status === 'draft') throw draftNotStarted(goalId);+ if (current.status !== graph.goal.status) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'The goal changed while it was being resumed; try again.',+ });+ }+ await model.updatePauseReason(goalId, undefined);+ if (current.status === status) return current;+ const updated = await model.updateStatus(goalId, status);+ await new GoalGraphModel(tx, ctx.userId, ctx.workspaceId)+ .recordGoalStatus(goalId, current.status, status, 'resumed by user')+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));+ return updated ?? current;+ });+};++/**+ * A person ends the goal themselves โ declaring it achieved or dropping it.+ *+ * Everything still spending on the goal is interrupted first โ the main+ * Agent's planning turn, the supervisor's diagnosis and every Task run โ the+ * same way `delete` does, because a terminal status alone only stops the+ * coordinator from dispatching more. Reopening goes through `resume`, which+ * accepts any status.+ */+export const close = async (+ ctx: GoalServiceContext,+ goalId: string,+ to: 'achieved' | 'canceled',+) => {+ // Fence new claims before scanning: `dispatchWork` claims under this row+ // lock and only while the goal reads `running`, so an advance overlapping+ // the close cannot start a Task after the scan below. The pause is the+ // person's, so no measurement lifts it if the close is refused later on.+ await ctx.db.transaction(async (db) => {+ const model = new GoalModel(db, ctx.userId, ctx.workspaceId);+ const current = await model.lockById(goalId);+ // Only a goal that can still dispatch needs fencing.+ if (!current || ['paused', 'achieved', 'failed', 'canceled'].includes(current.status)) return;+ await model.updateStatus(goalId, 'paused');+ await model.updatePauseReason(goalId, 'user');+ await new GoalGraphModel(db, ctx.userId, ctx.workspaceId).recordGoalStatus(+ goalId,+ current.status,+ 'paused',+ 'Stopping Goal before closing',+ );+ });+ const graph = await ctx.requireGraph(goalId);++ // Deliberately not swallowed, as in `delete`: an operation whose exit is+ // unconfirmed keeps spending, and a goal reading "ended" would hide it. The+ // goal stays paused so nothing new starts, and the person can retry.+ const notClosed = (error: unknown) =>+ new TRPCError({+ cause: error,+ code: 'PRECONDITION_FAILED',+ message:+ 'Could not stop the work still running for this goal, so it was not closed. Try again once the run is reachable.',+ });+ try {+ if (graph.goal.config?.manager)+ await new GoalManagerService(ctx.db, ctx.userId, ctx.workspaceId).stop(graph);+ if (graph.goal.config?.supervision?.enabled || graph.goal.config?.supervisorState)+ await new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).stop(graph);+ } catch (error) {+ throw notClosed(error);+ }++ const unfinishedTaskIds = graph.nodes.flatMap((node) =>+ node.kind === 'task' && node.taskId && !TERMINAL_NODE_STATUSES.has(node.status)+ ? [node.taskId]+ : [],+ );+ if (unfinishedTaskIds.length > 0) {+ // Claims whose run has not been recorded yet. `dispatchWork` marks the+ // Task `running` before `runTask` records the topic, so the scan below+ // cannot see that run, and only a recorded run can be interrupted with+ // confirmation. A fresh claim therefore refuses the close: the goal stays+ // fenced, and a retry a moment later finds the run recorded and stops it+ // the confirmed way. A claim older than the operation lease is one whose+ // startup died; it is withdrawn to `backlog` under the task row lock the+ // recording also takes, so a straggler recording stops its own run.+ const staleBefore = Date.now() - resolveOperationLeaseTimeout(graph.goal);+ let starting = false;+ for (const taskId of unfinishedTaskIds) {+ await ctx.db.transaction(async (tx) => {+ const taskModel = new TaskModel(tx, ctx.userId, ctx.workspaceId);+ if (!(await taskModel.lockForUpdate(taskId))) return;+ const task = await taskModel.findById(taskId);+ if (task?.status !== 'running') return;+ const recorded = await new TaskTopicModel(+ tx,+ ctx.userId,+ ctx.workspaceId,+ ).findRunningByTaskIds([taskId]);+ if (recorded.length > 0) return;+ if (task.updatedAt.getTime() > staleBefore) {+ starting = true;+ return;+ }+ await taskModel.updateStatusIfCurrent(taskId, 'running', 'backlog', { error: null });+ });+ }+ if (starting)+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message:+ 'A run for this goal is still starting, so it was not closed. No new work will start; try again in a moment.',+ });++ const runningTopics = await ctx.taskTopicModel.findRunningByTaskIds(unfinishedTaskIds);+ for (const topic of runningTopics) {+ if (!topic.topicId) continue;+ try {+ await ctx.taskService.cancelTopic(topic.topicId);+ } catch (error) {+ throw notClosed(error);+ }+ // Reset right after its own interruption, as in `restart`: left `paused`+ // it reads as parked on a person and a reopened goal waits on it. Doing+ // it per run means a later failed interruption cannot strand the ones+ // already stopped โ a retry no longer sees them as running. CAS so a+ // row a concurrent tick just moved is never yanked.+ const task = await ctx.taskModel.findById(topic.taskId);+ if (task && task.status !== 'completed') {+ await ctx.taskModel.updateStatusIfCurrent(task.id, task.status, 'backlog', {+ error: null,+ });+ }+ }+ }+ // Commit under the same lock the fence took, and only if the fence still+ // holds: a resume from another tab during the interruption pass lets an+ // advance claim work this pass never saw, and ending the goal over it+ // would leave that run spending on a goal reading "ended".+ const reason = to === 'achieved' ? 'marked achieved by user' : 'canceled by user';+ const goal = await ctx.db.transaction(async (db) => {+ const model = new GoalModel(db, ctx.userId, ctx.workspaceId);+ const current = await model.lockById(goalId);+ if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ if (!['paused', 'achieved', 'failed', 'canceled'].includes(current.status)) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'The goal was resumed while it was being closed, so it was not closed.',+ });+ }+ await model.updatePauseReason(goalId, undefined);+ if (current.status === to) return current;+ const updated = await model.updateStatus(goalId, to);+ await new GoalGraphModel(db, ctx.userId, ctx.workspaceId)+ .recordGoalStatus(goalId, current.status, to, reason)+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));+ return updated;+ });+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ return goal;+};diff --git a/apps/server/src/services/goal/GoalService/measurement.ts b/apps/server/src/services/goal/GoalService/measurement.tsnew file mode 100644index 00000000000..364c19f84c0--- /dev/null+++ b/apps/server/src/services/goal/GoalService/measurement.ts@@ -0,0 +1,375 @@+import type { GoalMetricCriteriaState } from '@lobechat/agent-tracing';+import type {+ GoalGraphSnapshot,+ GoalItem,+ GoalMetricCriterion,+ GoalPauseReason,+ MetricKind,+} from '@lobechat/types';+import { TRPCError } from '@trpc/server';++import { MetricModel } from '@/database/models/metric';++import {+ compareMetric,+ GOAL_ACCEPTANCE_TASK_TITLE,+ MEASURED_ACCEPTANCE_PAUSE_REASON,+ needsMetricCriteria,+} from '../decideNextMove';+import { GoalManagerService } from '../manager';+import { GoalSupervisorService } from '../supervisor';+import { GoalWaitService } from '../wait';+import type { GoalServiceContext } from './types';++/**+ * Replace the goal's structured acceptance criteria id list (goal-page+ * editing). The criteria rows themselves are edited through the verify+ * criteria endpoints; this only rebinds which of them gate the goal.+ */+/**+ * Declare (or clear) the numeric clauses that gate this goal's acceptance.+ *+ * Merged into `config.acceptance` so it cannot clobber the delivery criteria+ * binding, and settable after creation because a long-horizon goal learns its+ * real thresholds while it runs. Relaxing a clause can unblock a goal that is+ * already parked short of acceptance โ the same reason extending a deadline+ * resumes a budget-stopped one โ so the caller schedules an advance.+ */+/**+ * Write a measurement against this goal, and reopen it when that measurement+ * is what it was waiting for.+ *+ * The gate parks the goal (see the `measured_acceptance` branch), and `tick`+ * refuses to move a paused goal โ so without the reopen here the observation+ * would land and nothing would happen. Only a goal the gate actually stopped+ * is reopened, and only once every clause holds: the same discipline+ * `setBudget` uses, so a deliberate pause is never undone by a stray sample+ * and a still-short measurement does not queue a no-op advance.+ */+export const recordObservation = async (+ ctx: GoalServiceContext,+ goalId: string,+ input: {+ key: string;+ kind?: MetricKind;+ observedAt?: Date;+ title?: string;+ unit?: string;+ value: number;+ },+) => {+ const goal = await ctx.goalModel.findById(goalId);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });++ const metricModel = new MetricModel(ctx.db, ctx.userId, ctx.workspaceId);+ const series = await metricModel.ensure({+ key: input.key,+ kind: input.kind,+ subjectId: goal.id,+ subjectType: 'goal',+ title: input.title,+ unit: input.unit,+ });+ if (!series)+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'Metric series slot is owned by another scope',+ });++ const point = await metricModel.addPoint(series.id, {+ actorId: ctx.userId,+ actorType: 'user',+ observedAt: input.observedAt ?? new Date(),+ sourceType: 'manual',+ value: input.value,+ });++ const manager = goal.config?.managerState;+ if (+ manager?.wait &&+ point &&+ new Date(point.observedAt).getTime() >= Date.parse(manager.startedAt)+ ) {+ await new GoalWaitService(ctx.db, ctx.userId, ctx.workspaceId).deliver(goalId, {+ waitToken: manager.token,+ eventId: point.id,+ type: 'metric.observed',+ key: input.key,+ reference: series.id,+ summary: `${input.key} = ${input.value} at ${point.observedAt}`,+ });+ }+ return { point, series, shouldAdvance: await ctx.reopenIfMeasurementCleared(goalId) };+};++/**+ * Whether the coordinator is worth waking: either the goal is already+ * running, or the coordinator itself parked it on a measured gate that no+ * longer holds it.+ *+ * The `pausedBy` marker is what makes this safe. A goal paused by a person+ * looks exactly like one parked by the gate โ same status, same terminal+ * phase, same clauses โ so without it an arriving measurement would restart+ * a goal somebody deliberately stopped.+ *+ * "No longer holds it" covers both ways out: every clause now satisfied, and+ * the clauses being dropped altogether (`setMetricCriteria(id, [])`), which+ * otherwise left the goal parked on a gate that no longer existed.+ */+export const reopenIfMeasurementCleared = async (+ ctx: GoalServiceContext,+ goalId: string,+ /**+ * Whether the gate held the goal *before* the caller's edit, for callers+ * that change the clauses themselves: dropping the last one erases the+ * evidence, so the verdict is taken from the state that preceded it โ the+ * same way `setBudget` reads what was binding before it wrote.+ */+ parkedBeforeEdit?: boolean,+): Promise<boolean> => {+ const graph = await ctx.coordinatorGraph.getGraph(goalId);+ if (!graph) return false;+ if (graph.goal.status !== 'paused') return true;+ if (!(parkedBeforeEdit ?? ctx.isParkedOnMeasuredGate(graph))) return false;++ if (needsMetricCriteria(graph)) {+ const { allMet } = await ctx.evaluateMetricCriteria(graph);+ if (!allMet) return false;+ }++ await ctx.setPauseReason(goalId, undefined);+ await ctx.transitionStatus(graph.goal, 'running', 'a measurement cleared the acceptance gate');+ return true;+};++/**+ * Record (or clear) why the coordinator is holding this goal paused.+ *+ * Kept on the goal's JSONB config rather than derived from the event log:+ * control flow should not depend on a capped audit trail, and the marker has+ * to survive for as long as the pause does โ which for a long-horizon goal+ * is the whole wait.+ */+export const setPauseReason = async (+ ctx: GoalServiceContext,+ goalId: string,+ reason: GoalPauseReason | undefined,+) => {+ await ctx.goalModel.updatePauseReason(goalId, reason);+};++/**+ * Whether the coordinator is the one holding this paused goal.+ *+ * The marker answers it outright. Goals parked before the marker existed โ+ * and any parked by an old worker mid-deploy โ carry none, so fall back to+ * who performed the transition: every status change records a goal-entity+ * event, and the newest one is by definition the transition that produced+ * the current status. A coordinator park is attributed to `system`, a user+ * pause to `user`, so the two stay distinguishable without the marker.+ *+ * Absent both, the pause is left alone: a goal wrongly resumed spends money+ * against an explicit human decision, while one left parked says so on its+ * row and is one Resume away.+ */+export const isParkedOnMeasuredGate = (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+): boolean => {+ if (graph.goal.status !== 'paused') return false;+ if (graph.goal.config?.pausedBy) return graph.goal.config.pausedBy === 'measured_acceptance';++ // Match the park this gate actually recorded, not merely "the coordinator+ // paused it": it also parks goals that are blocked or out of budget, and an+ // unrelated sample must not restart either. The newest goal-entity event is+ // by definition the transition that produced the current status; if two+ // share a millisecond and the read picks the other one, the result is a+ // missed reopen rather than a wrongful one.+ const lastTransition = graph.events.find((event) => event.entityType === 'goal');+ return (+ lastTransition?.actorType !== 'user' &&+ !!lastTransition?.reason?.startsWith(MEASURED_ACCEPTANCE_PAUSE_REASON) &&+ needsMetricCriteria(graph)+ );+};++export const setMetricCriteria = async (+ ctx: GoalServiceContext,+ goalId: string,+ metrics: GoalMetricCriterion[],+ /**+ * `merge` upserts by key into the list as it stands on the server โ+ * for callers declaring one clause, whose own snapshot may be stale.+ * A client-built replacement array would silently drop whatever a+ * concurrent editor or agent declared since that snapshot was read.+ */+ mode: 'merge' | 'replace' = 'replace',+) => {+ const before = await ctx.coordinatorGraph.getGraph(goalId);+ if (!before) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ const parkedOnGate = ctx.isParkedOnMeasuredGate(before);+ const goal = before.goal;+ const current = goal.config?.acceptance?.metrics ?? [];+ const next =+ mode === 'merge'+ ? [...current.filter((item) => !metrics.some((m) => m.key === item.key)), ...metrics]+ : metrics;+ await ctx.goalModel.update(goalId, {+ config: {+ ...goal.config,+ acceptance: {+ ...goal.config?.acceptance,+ metrics: next.length > 0 ? next : undefined,+ },+ },+ });+ // Relaxing or dropping a clause can clear a gate the goal is parked on.+ await ctx.reopenIfMeasurementCleared(goalId, parkedOnGate);+ return ctx.graph(goalId);+};++export const setAcceptanceCriteria = async (+ ctx: GoalServiceContext,+ goalId: string,+ criteriaIds: string[],+) => {+ const goal = await ctx.goalModel.findById(goalId);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ await ctx.goalModel.update(goalId, {+ config: { ...goal.config, acceptance: { ...goal.config?.acceptance, criteriaIds } },+ });++ // A terminal Goal-acceptance Task may already be dispatched โ its+ // Acceptance row snapshotted the previous id list. Rebind it too, or the+ // page would present the new criteria as gates while the verifier keeps+ // materializing plans from the stale list. A verify round already+ // materialized for an in-flight run stays as-is (rounds are immutable+ // snapshots); every later run instantiates from the updated config.+ const graph = await ctx.graphModel.getGraph(goalId);+ const terminalTaskId = graph?.nodes.find(+ (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE && node.taskId,+ )?.taskId;+ if (!terminalTaskId) return;++ const acceptance = await ctx.acceptanceService.acceptanceModel.findBySubject(+ 'task',+ terminalTaskId,+ );+ if (!acceptance || acceptance.status === 'accepted') return;+ await ctx.acceptanceService.acceptanceModel.update(acceptance.id, {+ config: {+ ...acceptance.config,+ ...(criteriaIds.length > 0+ ? { verifyCriteriaIds: criteriaIds }+ : { verifyCriteriaIds: undefined }),+ },+ });+};++/**+ * What the goal has spent against what it is allowed to spend.+ *+ * Rounds are counted across every Task in the graph, not per Task โ the+ * budget is the goal's, so `setBudget` has to read it exactly the way the+ * coordinator does or raising a budget would not reliably unstick a goal.+ *+ * The calendar-time budget (schedule.deadline) is evaluated in the same+ * shape: time is the long-horizon budget unit the attempt/round/dollar trio+ * cannot express, and a goal whose deadline passed must stop the same way a+ * goal out of money does.+ */+/**+ * Read every declared numeric clause against its series' latest observation.+ *+ * A missing series or a series with no points reads as `null` and fails its+ * clause: "never measured" is not "satisfied". The measured value is carried+ * out with the verdict so the trajectory records what the decision saw.+ */+export const evaluateMetricCriteria = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+): Promise<GoalMetricCriteriaState> => {+ const declared = graph.goal.config?.acceptance?.metrics ?? [];+ const metricModel = new MetricModel(ctx.db, ctx.userId, ctx.workspaceId);++ // Two queries for the whole contract, not two per clause: this runs on+ // every terminal tick, and a goal carrying a large acceptance payload would+ // otherwise pace the connection pool for unrelated requests. Only the+ // declared keys are fetched โ the same goal can accumulate any number of+ // other sampled series, and none of them can gate acceptance.+ const series = await metricModel.findByKeys(+ 'goal',+ graph.goal.id,+ declared.map((criterion) => criterion.key),+ );+ const seriesByKey = new Map(series.map((item) => [item.key, item]));+ const latestByMetricId = await metricModel.latestPointsByMetricIds(+ declared.flatMap((criterion) => {+ const id = seriesByKey.get(criterion.key)?.id;+ return id ? [id] : [];+ }),+ );++ const criteria = declared.map((criterion) => {+ const op = criterion.op ?? 'gte';+ const seriesId = seriesByKey.get(criterion.key)?.id;+ const point = seriesId ? latestByMetricId.get(seriesId) : undefined;+ const value = point?.value ?? null;+ return {+ key: criterion.key,+ met: value !== null && compareMetric(value, op, criterion.target),+ observedAt: point ? new Date(point.observedAt).getTime() : undefined,+ op,+ target: criterion.target,+ value,+ };+ });++ return { allMet: criteria.every((criterion) => criterion.met), criteria };+};++export const evaluateBudget = async (+ ctx: GoalServiceContext,+ goal: GoalItem,+ graph: GoalGraphSnapshot,+) => {+ const { runs, totalCost } = await ctx.resolveSpend(graph);+ const deadline = goal.config?.schedule?.deadline ?? null;+ return {+ costLimitReached: goal.maxTotalCost !== null && totalCost >= Number(goal.maxTotalCost),+ deadline,+ deadlinePassed: deadline !== null && Date.now() >= new Date(deadline).getTime(),+ roundLimitReached: goal.maxRounds !== null && runs >= goal.maxRounds,+ runs,+ totalCost,+ };+};++/**+ * Rounds run and dollars spent, by the definition the budget is enforced+ * against: the runs of the graph's own Task nodes.+ *+ * `graph()` ships this to the client so the page's spend reads the same+ * number the coordinator will stop on. Note it is deliberately NOT the goal+ * list's `totalRunCost`, which walks the whole `parent_task_id` subtree โ+ * that number is larger for a goal whose Tasks spawned Tasks.+ */+export const resolveSpend = async (ctx: GoalServiceContext, graph: GoalGraphSnapshot) => {+ const [spend, supervision, management] = await Promise.all([+ ctx.taskTopicModel.sumRunCostByTaskIds(+ graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : [])),+ ),+ new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).usage(+ graph.goal.config?.supervisorState,+ ),+ new GoalManagerService(ctx.db, ctx.userId, ctx.workspaceId).usage(+ graph.goal.id,+ graph.goal.config?.managerState,+ ),+ ]);+ return {+ ...spend,+ totalCost: spend.totalCost + supervision.totalCost + management.totalCost,+ totalTokens: spend.totalTokens + supervision.totalTokens + management.totalTokens,+ };+};diff --git a/apps/server/src/services/goal/GoalService/planning.ts b/apps/server/src/services/goal/GoalService/planning.tsnew file mode 100644index 00000000000..7d938a007fe--- /dev/null+++ b/apps/server/src/services/goal/GoalService/planning.ts@@ -0,0 +1,476 @@+import { randomUUID } from 'node:crypto';++import type { GoalAdvanceEffect } from '@lobechat/agent-tracing';+import {+ GOAL_CLARIFICATION_TITLE,+ GOAL_COORDINATOR_ACTOR_ID,+ ROLLOUT_CANARY_SIZE_DEFAULT,+ ROLLOUT_MAX_CANARY_SIZE,+} from '@lobechat/const/goal';+import type { GoalGraphSnapshot, GoalRolloutPolicy } from '@lobechat/types';++import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';++import { GoalCriteriaGeneratorService, type GoalDecompositionDraft } from '../criteriaGenerator';+import { GoalManagerService } from '../manager';+import {+ materializeRolloutBatch,+ MAX_ROLLOUT_ROSTER,+ normalizeRolloutRoster,+} from '../rolloutBatch';+import { evaluateHomogeneity } from '../spec';+import {+ clarificationOptions,+ collectClarificationAnswers,+ hasAskedClarification,+ normalizeUnderstanding,+ UNDERSTANDING_CONFIDENCE,+} from '../understanding';+import type { GoalServiceContext } from './types';+import { log } from './utils';++/**+ * Why the system planner's one pass should go to the main Agent, or undefined+ * when its plan can run: the pass failed, the planner said it was not enough,+ * or it claimed a batch it could not lay out. A goal that is simply not a batch+ * is not a reason โ the ordinary plan is right for it.+ */+const planningHandoffReason = (+ plan: GoalDecompositionDraft | undefined,+ plannerFailure: string | undefined,+ rollout: GoalRolloutPolicy | undefined,+ maxUnits: number,+): string | undefined => {+ if (!plan) return `Planner failed (${plannerFailure ?? 'no answer'})`;+ const asked = plan.escalate?.trim();+ if (asked) return `Planner asked for the main Agent: ${asked}`;+ if (!plan.rollout || rollout?.trigger === 'off') return undefined;+ const verdict = evaluateHomogeneity(+ plan.rollout,+ plan.tasks.map((draft) => ({ instruction: draft.instruction, title: draft.title })),+ { maxUnits, minUnits: rollout?.minHomogeneousUnits },+ );+ return verdict.malformed+ ? `Batch claim could not be laid out (${verdict.reasons.join('; ')})`+ : undefined;+};++/**+ * One line for why the planner failed, for the audit trail. Model runtime+ * errors arrive as plain objects (`{ errorType, error }`), not `Error`s.+ */+const describePlannerFailure = (error: unknown): string => {+ const runtime = error as { error?: { message?: string }; errorType?: string } | undefined;+ const text =+ error instanceof Error+ ? error.message+ : [runtime?.errorType, runtime?.error?.message].filter(Boolean).join(': ') || String(error);+ return text.length > 300 ? `${text.slice(0, 299)}โฆ` : text;+};++/**+ * Turn a goal with no tasks into an explorable structure: the LLM plans the+ * core question plus 1โ5 independent directions, each carrying only its own+ * deliverable requirements. A planning failure degrades to one task seeded+ * from the raw requirement โ the goal must never stall on its planner.+ */+export const planDecomposition = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ effects: GoalAdvanceEffect[],+) => {+ const goalId = graph.goal.id;+ const problem = graph.nodes.find((node) => node.kind === 'problem');+ const requirement = graph.goal.requirement ?? problem?.description ?? graph.goal.title;++ const claim = await ctx.goalModel.claimPlanning(goalId);+ if (!claim)+ return {+ goalId,+ message: 'Another advance is already planning this goal or tasks already exist',+ outcome: 'waiting_external' as const,+ };+ try {+ if (claim.previousStatus === 'planning') {+ await ctx.coordinatorGraph+ .recordGoalStatus(goalId, 'planning', 'running', 'decomposition claimed')+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));+ }++ const generator = new GoalCriteriaGeneratorService(ctx.db, ctx.userId, ctx.workspaceId);+ const clarifications = collectClarificationAnswers(graph);+ // A failed plan still starts the goal from the raw requirement, but says+ // so: the server log and the first task's audit event carry the cause.+ let plannerFailure: string | undefined;+ const plan = await generator+ .decompose({ clarifications, requirement })+ .catch((error: unknown) => {+ plannerFailure = describePlannerFailure(error);+ console.error(+ `[GoalService] goal ${goalId} decomposition failed; starting from the raw requirement:`,+ error,+ );+ return undefined;+ });+ // A graph without a problem node has nowhere to hang a question, so its+ // questions are planned around as assumptions like a re-plan's would be.+ const understanding = plan+ ? normalizeUnderstanding(+ plan,+ hasAskedClarification(graph) || !problem,+ clarifications.map((item) => item.question),+ )+ : undefined;++ // The system planner does one simple pass. When that pass failed, said it+ // was not enough, or claimed a batch it could not lay out, the main Agent+ // โ which can inspect the workspace โ plans the goal instead. Without one+ // (no goal agent, or no turn could start) the pass below still runs.+ const handoff = planningHandoffReason(+ plan,+ plannerFailure,+ graph.goal.config?.rollout,+ MAX_ROLLOUT_ROSTER,+ );+ if (handoff && graph.goal.agentId) {+ const handed = await ctx.handPlanningToMainAgent(graph, handoff);+ if (handed) {+ effects.push({+ detail: `planning handed to the main Agent: ${handoff}`,+ type: 'goal_status',+ });+ return handed;+ }+ }++ const draftTasks: GoalDecompositionDraft['tasks'] = plan?.tasks ?? [+ {+ // The user's answers are authoritative; a planner failure after the+ // clarification round must not start the work without them.+ instruction: [+ // After a clarification round, scope the work by the original request+ // plus the answers โ never by a summary a planner wrote earlier.+ clarifications.length > 0 ? requirement : (problem?.description ?? requirement),+ clarifications.length > 0+ ? `Answered clarifications (authoritative):\n${clarifications+ .map((item) => `- Q: ${item.question}\n A: ${item.answer}`)+ .join('\n')}`+ : undefined,+ ]+ .filter(Boolean)+ .join('\n\n'),+ title: graph.goal.title,+ },+ ];++ const askedDecisions: { id: string; question: string }[] = [];+ // Only the current lease owner may commit. The model call above does not+ // hold a database lock; all graph changes below share one short transaction.+ const committed = await ctx.db.transaction(async (tx) => {+ const goalModel = new GoalModel(tx, ctx.userId, ctx.workspaceId);+ const current = await goalModel.findByIdForUpdate(goalId);+ const checkpoint = current?.config?.planningCheckpoint;+ if (+ !current ||+ current.status !== 'running' ||+ checkpoint?.token !== claim.token ||+ Date.parse(checkpoint.expiresAt) <= Date.now()+ )+ return undefined;+ const writer = new GoalGraphModel(tx, ctx.userId, ctx.workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ });+ const fresh = await writer.getGraph(goalId);+ if (!fresh || fresh.nodes.some((node) => node.kind === 'task')) return undefined;+ const currentProblem = fresh.nodes.find((node) => node.kind === 'problem');+ if (+ fresh.goal.requirement !== graph.goal.requirement ||+ fresh.goal.title !== graph.goal.title ||+ currentProblem?.description !== problem?.description+ )+ return undefined;+ const committedEffects: GoalAdvanceEffect[] = [];++ const asking = Boolean(understanding?.ask.length && currentProblem);+ if (plan && currentProblem) {+ // The node's description becomes the planner's own words for the core+ // question โ not the acceptance boilerplate the goal row keeps. A plan+ // that stops to ask commits no tasks, so it keeps the user's own words:+ // the re-plan, or its fallback, must still read the original request.+ await writer.updateNodeDescription(+ goalId,+ currentProblem.id,+ asking ? (currentProblem.description ?? plan.problemStatement) : plan.problemStatement,+ understanding && UNDERSTANDING_CONFIDENCE[understanding.level],+ );+ }+ if (understanding) {+ await goalModel.updateUnderstanding(goalId, {+ assumptions: understanding.assumptions,+ level: understanding.level,+ updatedAt: new Date().toISOString(),+ });+ }++ // A question only the user can answer is asked before anything runs:+ // Tasks planned on a wrong reading of the goal are the most expensive+ // way to find out. No Task is created, so the next plan โ made with the+ // answers โ starts from the same empty graph.+ if (asking && understanding && currentProblem) {+ for (const question of understanding.ask) {+ const node = await writer.createNode(goalId, {+ description: question.impact,+ kind: 'decision',+ status: 'waiting',+ title: GOAL_CLARIFICATION_TITLE,+ });+ if (!node) throw new Error('Failed to open a clarification decision');+ await writer.createEdge(goalId, currentProblem.id, node.id, 'leads_to');+ const decision = await writer.createDecision(goalId, node.id, {+ authority: 'user',+ options: clarificationOptions(question),+ question: question.question,+ requestedUserId: ctx.userId,+ });+ if (decision) askedDecisions.push({ id: decision.id, question: question.question });+ committedEffects.push({+ detail: question.question,+ nodeId: currentProblem.id,+ targetId: node.id,+ type: 'opened_decision',+ });+ }+ return committedEffects;+ }++ // Batch roll-out: when the planner judges this goal to be one repeated+ // mould โ and `spec.ts` agrees โ decompose it as a class rather than as+ // N flat siblings. The graph gets one `batch` container, one Template,+ // one Assay and only the K fully-briefed probe tasks; the roster waits in+ // `rolloutState` and the coordinator releases it one wave at a time.+ const rolloutClaim = plan?.rollout ?? null;+ const existingRollout = current.config?.rollout;+ const rolloutTrigger = existingRollout?.trigger ?? 'canary';+ const rolloutEnabled = rolloutTrigger !== 'off';+ const verdict =+ rolloutClaim && rolloutEnabled+ ? evaluateHomogeneity(+ rolloutClaim,+ draftTasks.map((draft) => ({ instruction: draft.instruction, title: draft.title })),+ {+ maxUnits: MAX_ROLLOUT_ROSTER,+ minUnits: existingRollout?.minHomogeneousUnits,+ },+ )+ : { batch: false, malformed: false, reasons: [] as string[] };++ log(+ 'decomposition rollout: trigger=%s claim=%o tasks=%d verdict=%o',+ rolloutTrigger,+ rolloutClaim,+ draftTasks.length,+ verdict,+ );++ if (rolloutClaim && rolloutEnabled && verdict.batch && currentProblem) {+ const roster = normalizeRolloutRoster(+ rolloutClaim.units,+ draftTasks,+ draftTasks.length,+ undefined,+ { matchUnitInProbeTitle: true },+ );+ const canarySize =+ rolloutTrigger === 'full'+ ? roster.length+ : Math.max(+ 2,+ Math.min(+ existingRollout?.canarySize ?? ROLLOUT_CANARY_SIZE_DEFAULT,+ ROLLOUT_MAX_CANARY_SIZE,+ draftTasks.length,+ ),+ );+ const { probeDrafts, probeIds } = await materializeRolloutBatch({+ canarySize,+ goalId,+ goalModel,+ planSkillOwner: {+ db: tx,+ goalTitle: graph.goal.title,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ policy: existingRollout,+ problemId: currentProblem.id,+ probes: draftTasks,+ recipeOutline: rolloutClaim.recipeOutline,+ repeatable: rolloutClaim.repeatable,+ roster,+ trigger: rolloutTrigger === 'full' ? 'full' : 'canary',+ variants: rolloutClaim.variants,+ writer,+ });+ for (const [index, draft] of probeDrafts.entries()) {+ committedEffects.push({+ nodeId: probeIds[index],+ type: 'created_node',+ detail: draft.title,+ });+ }+ return committedEffects;+ }++ // A rollout claim we did NOT turn into a batch โ the caller forced+ // `--rollout off`, or the homogeneity check refused it โ still carries+ // only the 3โ5 representative probes in `tasks`, with the complete+ // roster in `units`. A plain decomposition of `draftTasks` alone would+ // silently drop every other unit, so materialize the whole roster as+ // ordinary tasks instead: the probes keep their first-hand briefs, the+ // rest run from the recipe. The batch config's roster cap does NOT apply+ // here โ trimming the fallback would leave the tail of the requested+ // goal undelivered. A goal with no claim at all is unchanged.+ const plannedUnits = rolloutClaim+ ? normalizeRolloutRoster(+ rolloutClaim.units,+ draftTasks,+ draftTasks.length,+ Number.POSITIVE_INFINITY,+ { matchUnitInProbeTitle: true },+ ).map((title, index) => {+ const draft = draftTasks[index];+ return {+ dependsOn: draft?.dependsOn ?? [],+ hypothesis: draft?.hypothesis,+ instruction:+ draft?.instruction ??+ [rolloutClaim.recipeOutline, `Unit: ${title}`].filter(Boolean).join('\n\n'),+ title: draft?.title ?? title,+ };+ })+ : draftTasks;++ // Why this goal was planned unit by unit, on the first task's `created`+ // event: a planner failure, or a batch claim the checks refused.+ // A hand-over that did not happen (no main Agent could take the goal)+ // says so too.+ const unhanded = handoff ? '; no main Agent could take the goal' : '';+ let fallbackReason = !plan+ ? `Planner failed (${plannerFailure ?? 'no answer'})${unhanded}; started from the raw requirement`+ : plan.escalate?.trim()+ ? `Planner asked for the main Agent (${plan.escalate.trim()})${unhanded}; ran its own plan`+ : rolloutClaim && rolloutEnabled && !verdict.batch+ ? `Batch claim refused (${verdict.reasons.join('; ')}); planned unit by unit`+ : undefined;++ const createdIds: string[] = [];+ for (const draft of plannedUnits) {+ // An experiment is a container for a candidate answer, not the+ // default shell around every planned step. Only a direction the+ // planner marked with a hypothesis gets one; a certain delivery step+ // attaches straight to the problem, the same shape a manager-planned+ // Task takes.+ const hypothesis = draft.hypothesis?.trim();+ const experiment =+ currentProblem && hypothesis+ ? await writer.createNode(goalId, {+ kind: 'experiment',+ title: draft.title,+ description: hypothesis,+ questionId: currentProblem.id,+ })+ : undefined;+ if (currentProblem && hypothesis && !experiment)+ throw new Error('Failed to create a planned experiment');+ const node = await writer.createNode(goalId, {+ scopeId: experiment?.id,+ description: draft.instruction,+ kind: 'task',+ reason: fallbackReason,+ title: draft.title,+ });+ if (!node) throw new Error('Failed to create a planned task');+ if (!experiment && currentProblem)+ await writer.createEdge(goalId, currentProblem.id, node.id, 'decomposes');+ createdIds.push(node.id);+ committedEffects.push({ nodeId: node.id, type: 'created_node', detail: draft.title });+ fallbackReason = undefined;+ }++ // The planner's `dependsOn` indices become `depends_on` edges, drawn+ // dependent โ prerequisite the way `decideNextMove` reads a blocker. Only+ // earlier indices are honoured, so a hallucinated forward or self reference+ // can never form a cycle that deadlocks the frontier.+ for (const [index, draft] of plannedUnits.entries()) {+ const nodeId = createdIds[index];+ if (!nodeId) continue;+ for (const dep of new Set(draft.dependsOn ?? [])) {+ const prerequisiteId = dep < index ? createdIds[dep] : undefined;+ if (!prerequisiteId) continue;+ await writer.createEdge(goalId, nodeId, prerequisiteId, 'depends_on');+ }+ }+ return committedEffects;+ });+ if (!committed) {+ return {+ goalId,+ message: 'Planning lease or input changed; re-read the graph',+ outcome: 'advanced' as const,+ };+ }+ effects.push(...committed);++ const asked = committed.filter((effect) => effect.type === 'opened_decision').length;+ if (asked > 0) {+ await ctx.briefs.openClarification(+ graph.goal,+ askedDecisions.map((decision) => decision.id),+ askedDecisions.map((decision) => decision.question),+ );+ return {+ goalId,+ message: `Asked ${asked} clarification question${asked > 1 ? 's' : ''} before planning`,+ outcome: 'advanced' as const,+ };+ }++ return {+ goalId,+ message: plan+ ? `Planned ${draftTasks.length} exploration direction${draftTasks.length > 1 ? 's' : ''}`+ : 'Planner unavailable; seeded a single task from the requirement',+ outcome: 'advanced' as const,+ };+ } finally {+ await ctx.goalModel.releasePlanning(goalId, claim.token);+ }+};++/**+ * Give the goal's planning to its main Agent, opening one for a goal that had+ * none. Returns undefined when no turn could start (no eligible agent, turn or+ * budget limits); a policy opened here is then removed again โ only that one,+ * by its token โ so the goal keeps the system planner and does not gain an+ * uninvited planner later, while a policy a person set meanwhile stays.+ */+export const handPlanningToMainAgent = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ reason: string,+) => {+ const goalId = graph.goal.id;+ const token = randomUUID();+ await ctx.goalModel.openManagerPolicy(goalId, { openedForHandoff: token });+ const result = await new GoalManagerService(ctx.db, ctx.userId, ctx.workspaceId)+ .planInstead(await ctx.requireGraph(goalId), reason)+ .catch((error: unknown) => {+ console.error(`[GoalService] goal ${goalId} could not hand planning over:`, error);+ return null;+ });+ if (result) return result;+ await ctx.goalModel.closeHandoffManagerPolicy(goalId, token);+ return undefined;+};diff --git a/apps/server/src/services/goal/GoalService/reads.ts b/apps/server/src/services/goal/GoalService/reads.tsnew file mode 100644index 00000000000..704334f5eba--- /dev/null+++ b/apps/server/src/services/goal/GoalService/reads.ts@@ -0,0 +1,276 @@+import type {+ GoalDecisionOption,+ GoalEventEntityType,+ GoalEventType,+ GoalGraphNode,+ GoalGraphSnapshot,+ GoalNodeAcceptance,+ GoalStatus,+} from '@lobechat/types';+import { TRPCError } from '@trpc/server';++import { AgentOperationModel } from '@/database/models/agentOperation';++import { GoalReportStore } from '../reportStore';+import type { GoalServiceContext } from './types';++export const graph = async (ctx: GoalServiceContext, goalId: string) => {+ const graph = await ctx.requireGraph(goalId);+ const [runHeartbeats, deliveredAt, acceptances, assignees, spend, report] = await Promise.all([+ ctx.collectRunHeartbeats(graph),+ ctx.collectDeliveredAt(graph),+ ctx.collectAcceptances(graph),+ ctx.collectAssignees(graph),+ ctx.resolveSpend(graph),+ new GoalReportStore(ctx.db, ctx.userId, ctx.workspaceId).state(graph),+ ]);+ return { ...graph, acceptances, assignees, deliveredAt, report, runHeartbeats, spend };+};++/**+ * The goal's audit trail, newest first, paged past the capped copy `graph()`+ * carries. `graph()` stays the shape the page reads; this is for a reader+ * chasing one transition โ the pause that explains why a plan was refused+ * hours into a run, say. Returns the cursor that continues the page.+ */+export const listEvents = async (+ ctx: GoalServiceContext,+ goalId: string,+ options: {+ cursor?: { createdAt: Date; id: string };+ entityType?: GoalEventEntityType;+ eventType?: GoalEventType;+ limit: number;+ },+) => {+ const page = await ctx.graphModel.listEvents(goalId, options);+ if (!page) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ return page;+};++/**+ * The agent each dispatched task node is assigned to. Read from the Task row+ * rather than the goal config: a task can be reassigned on its own, and the+ * row is what the runner actually dispatches to.+ */+export const collectAssignees = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+): Promise<Record<string, string> | undefined> => {+ const taskNodes = graph.nodes.filter(+ (node): node is GoalGraphNode & { taskId: string } => node.kind === 'task' && !!node.taskId,+ );+ if (taskNodes.length === 0) return undefined;++ const nodeByTaskId = new Map(taskNodes.map((node) => [node.taskId, node.id]));+ // Runs on every graph poll: read the one column, not whole task rows.+ const tasks = await ctx.taskModel.findAssigneesByIds(taskNodes.map((node) => node.taskId));++ const result: Record<string, string> = {};+ for (const task of tasks) {+ const nodeId = nodeByTaskId.get(task.id);+ if (nodeId && task.assigneeAgentId) result[nodeId] = task.assigneeAgentId;+ }+ return Object.keys(result).length > 0 ? result : undefined;+};++/**+ * Verification state per task node.+ *+ * Every dispatched task already owns an Acceptance (`createResponsibleTask`+ * creates one), but the goal surfaced only the criteria it would be judged+ * against โ never the judgment. A reader could see that a task finished and+ * still have no idea whether it held up, which is the gap that made the page+ * feel unverifiable.+ *+ * Each level's tally rides along so the page can show its standing without+ * opening it. That tally is counted from the same check union the level+ * expands to (so a summary row can never contradict its own list), and it is+ * one batched read, never one per acceptance โ this runs on every graph poll.+ */+export const collectAcceptances = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+): Promise<Record<string, GoalNodeAcceptance> | undefined> => {+ const taskNodes = graph.nodes.filter(+ (node): node is GoalGraphNode & { taskId: string } => node.kind === 'task' && !!node.taskId,+ );+ if (taskNodes.length === 0) return undefined;++ const nodeByTaskId = new Map(taskNodes.map((node) => [node.taskId, node.id]));+ const rows = await ctx.acceptanceService.acceptanceModel.findBySubjects(+ 'task',+ taskNodes.map((node) => node.taskId),+ );++ // An acceptance with no round yet is absent from the tally map, not zero โ+ // keep "no round" and "judged nothing" apart on the page.+ const tallies = await ctx.acceptanceService.getCheckTalliesByAcceptances(+ rows.map((row) => row.id),+ );++ const result: Record<string, GoalNodeAcceptance> = {};+ for (const row of rows) {+ const nodeId = nodeByTaskId.get(row.subjectId);+ if (!nodeId) continue;+ const checks = tallies.get(row.id);+ result[nodeId] = { id: row.id, status: row.status, ...(checks ? { checks } : {}) };+ }+ return Object.keys(result).length > 0 ? result : undefined;+};++/**+ * When an active task node's newest run delivered, for the nodes waiting on+ * verification to settle.+ *+ * A verify-bound task keeps its node `active` while its topic is already+ * `completed`, and the judgment is a full agent run that routinely outlives+ * the operation lease โ `decideNextMove` holds off re-dispatching such a node+ * for a whole `VERIFY_SETTLE_GRACE_MS`. But a completed topic is not a+ * *running* one, so it contributes no heartbeat, and a client judging+ * liveness from heartbeats alone declared the goal's most informative moment+ * โ delivered, being verified โ lost. Reporting the delivery instant lets the+ * client name that state and apply the coordinator's own grace window instead+ * of the lease.+ */+export const collectDeliveredAt = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+): Promise<Record<string, Date> | undefined> => {+ const activeTasks = graph.nodes.filter(+ (node): node is GoalGraphNode & { taskId: string } =>+ node.kind === 'task' && node.status === 'active' && !!node.taskId,+ );+ if (activeTasks.length === 0) return undefined;++ const nodeByTaskId = new Map(activeTasks.map((node) => [node.taskId, node.id]));+ // Newest run per task: `findWithHandoffByTaskIds` orders by seq desc, so the+ // first row seen for a task is its latest.+ const topics = await ctx.taskTopicModel.findWithHandoffByTaskIds(+ activeTasks.map((n) => n.taskId),+ activeTasks.length,+ );++ const delivered: Record<string, Date> = {};+ const seen = new Set<string>();+ for (const topic of topics) {+ const taskId = topic.sourceTaskId;+ if (!taskId || seen.has(taskId)) continue;+ seen.add(taskId);+ const nodeId = nodeByTaskId.get(taskId);+ // Only the newest run counts, and only while it is a delivery: an older+ // completed run under a newer running one is history, not a pending+ // verification.+ if (!nodeId || topic.status !== 'completed') continue;+ delivered[nodeId] = topic.completedAt ?? topic.createdAt;+ }++ return Object.keys(delivered).length > 0 ? delivered : undefined;+};++/**+ * Live heartbeat per active task node: the `agent_operations.updatedAt` of+ * the run behind it. The runtime refreshes that lease every ~90s while+ * `goal_nodes.updatedAt` only moves on observations / status changes, so a+ * client judging liveness from the node row alone would cry "lost" over any+ * long quiet stretch (a big tool call, the verify stage) the reclaim path+ * considers perfectly healthy.+ */+export const collectRunHeartbeats = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+): Promise<Record<string, Date> | undefined> => {+ const activeTasks = graph.nodes.filter(+ (node): node is GoalGraphNode & { taskId: string } =>+ node.kind === 'task' && node.status === 'active' && !!node.taskId,+ );+ if (activeTasks.length === 0) return undefined;++ const nodeByTaskId = new Map(activeTasks.map((node) => [node.taskId, node.id]));+ const running = await ctx.taskTopicModel.findRunningByTaskIds(activeTasks.map((n) => n.taskId));++ // One batched read: the graph polls every few seconds per open client, so+ // a per-topic operation lookup would scale queries with task concurrency.+ const operationIds = [+ ...new Set(running.flatMap((topic) => (topic.operationId ? [topic.operationId] : []))),+ ];+ const operations = await new AgentOperationModel(ctx.db, ctx.userId, ctx.workspaceId).findByIds(+ operationIds,+ );+ const operationById = new Map(operations.map((operation) => [operation.id, operation]));++ const heartbeats: Record<string, Date> = {};+ for (const topic of running) {+ const nodeId = topic.taskId ? nodeByTaskId.get(topic.taskId) : undefined;+ if (!nodeId || !topic.operationId || heartbeats[nodeId]) continue;+ const updatedAt = operationById.get(topic.operationId)?.updatedAt;+ if (updatedAt) heartbeats[nodeId] = updatedAt;+ }++ return Object.keys(heartbeats).length > 0 ? heartbeats : undefined;+};++/** Current lifecycle status, without paying for the whole graph. */+export const status = async (+ ctx: GoalServiceContext,+ goalId: string,+): Promise<GoalStatus | undefined> => (await ctx.goalModel.findById(goalId))?.status;++/**+ * Everything the approval island asks outside a goal's page: the gates+ * waiting on the person (clarification rounds have their own form) and the+ * finished goals waiting for their sign-off.+ */+export const pendingForIsland = async (ctx: GoalServiceContext) => {+ const [decisions, signOffs] = await Promise.all([+ ctx.goalModel.listPendingDecisions(),+ ctx.briefs.listOpenSignOffs(),+ ]);+ return {+ decisions: decisions.map((row) => ({ ...row, options: row.options ?? [] })),+ signOffs,+ };+};++/** Pending clarifications grouped by goal, for surfaces outside the goal page. */+export const pendingClarifications = async (ctx: GoalServiceContext) => {+ const rows = await ctx.goalModel.listPendingClarifications();+ const byGoal = new Map<+ string,+ {+ agentId: string | null;+ goalId: string;+ questions: Array<{+ decisionId: string;+ description: string | null;+ options: GoalDecisionOption[];+ question: string;+ }>;+ requirement: string | null;+ title: string;+ }+ >();+ for (const row of rows) {+ const group = byGoal.get(row.goalId) ?? {+ agentId: row.agentId,+ goalId: row.goalId,+ questions: [],+ requirement: row.requirement,+ title: row.goalTitle,+ };+ group.questions.push({+ decisionId: row.decisionId,+ description: row.description,+ options: row.options ?? [],+ question: row.question,+ });+ byGoal.set(row.goalId, group);+ }+ return [...byGoal.values()];+};++export const requireGraph = async (ctx: GoalServiceContext, goalId: string) => {+ const graph = await ctx.graphModel.getGraph(goalId);+ if (!graph) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ return graph;+};diff --git a/apps/server/src/services/goal/GoalService/recovery.ts b/apps/server/src/services/goal/GoalService/recovery.tsnew file mode 100644index 00000000000..edd10b2433c--- /dev/null+++ b/apps/server/src/services/goal/GoalService/recovery.ts@@ -0,0 +1,518 @@+import type { GoalAdvanceEffect } from '@lobechat/agent-tracing';+import { DEVICE_OFFLINE_RUN_STATUS } from '@lobechat/const/goal';+import type {+ ChatTopicMetadata,+ GoalGraphSnapshot,+ GoalTickResult,+ TaskItem,+} from '@lobechat/types';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { GoalModel } from '@/database/models/goal';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';++import { readDeviceDispatchRoute } from '../../aiAgent/helpers/heteroErrors';+import { deviceGateway } from '../../deviceGateway';+import { isOrphanedRun, readRunTopicMetadata, stopStaleRun } from '../abandonedRun';+import { LEASE_EXPIRED_ERROR } from '../decideNextMove';+import { isDeliverySettling } from '../deliverySettle';+import { classifyGoalFailure } from '../failureClass';+import { lastAnsweredGateAt, planMachineRecovery } from '../machineRecovery';+import {+ classifyRunFailure,+ countConsecutiveDeviceOfflineRuns,+ DEVICE_OFFLINE_GATE_REASON,+ isDeviceUnavailableFailure,+ nextDeviceOfflineRetryAt,+ QUOTA_RESET_MARGIN_MS,+ resolveOperationLeaseTimeout,+} from '../recoveryPolicy';+import { scheduleGoalAdvance } from '../scheduler';+import { statusAuthoredByActor } from '../supervisor/policy';+import { TaskRecoveryCoordinator } from '../taskRecoveryCoordinator';+import { GoalWaitService } from '../wait';+import type { GoalServiceContext } from './types';++/** A machine hold books its own advance only from the tick that first saw the failure. */+const MACHINE_HOLD_SCHEDULE_WINDOW_MS = 15 * 60 * 1000;++/** Queue delays are bounded; the sweep covers anything further out. */+const MAX_ADVANCE_DELAY_S = 86_400;++export const recoverAbandonedTask = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ effects: GoalAdvanceEffect[] = [],+): Promise<GoalTickResult | undefined> => {+ const [runningTopic] = await ctx.taskTopicModel.findRunningByTaskIds([task.id]);+ const operationId = runningTopic?.operationId;+ const topicId = runningTopic?.topicId;+ const staleBefore = new Date(Date.now() - resolveOperationLeaseTimeout(graph.goal));++ if (!operationId || !topicId) {+ // No running topic covers two very different shapes. A delivered Task+ // waiting on its verification (and any repair it sends back) outlives the+ // operation lease routinely; re-dispatching there pays for a duplicate+ // attempt that shadows the delivered one. Hold off while the delivery is+ // settling; past its grace window, fall through to the release below so+ // a verify run that died silently cannot strand the goal forever.+ const [lastTopic] = await ctx.taskTopicModel.findWithHandoff(task.id, 1);+ const operationModel = new AgentOperationModel(ctx.db, ctx.userId, ctx.workspaceId);+ if (await isDeliverySettling(operationModel, lastTopic)) {+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} delivered; waiting for verification to settle`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }++ // A task claimed for dispatch but with no run behind it. Normally this is+ // the sliver between the claim and `runTask` creating the topic; if the+ // worker died in there it is permanent, and every later advance would+ // report `waiting_external` forever because there is no operation to+ // reclaim. Once the claim is older than the lease, hand it back.+ if (new Date(task.updatedAt) >= staleBefore) return undefined;+ const released = await ctx.taskModel.updateStatusIfCurrent(task.id, 'running', 'backlog');+ if (!released) return undefined;+ return {+ goalId: graph.goal.id,+ message: `Released the abandoned dispatch claim on task ${task.identifier}`,+ nodeId,+ outcome: 'advanced',+ taskId: task.id,+ };+ }++ // A run that may still be writing must not get a replacement beside it; only+ // a device known to be offline is left to the offline-device recovery below.+ const latestUsage = await new AgentRuntimeCoordinator().getOperationMetadata(operationId);+ const owner = { userId: ctx.userId, workspaceId: ctx.workspaceId };+ const latestTotalCost = latestUsage?.totalCost;+ const stop = await stopStaleRun(ctx.db, owner, {+ latestTotalCost,+ operationId,+ staleBefore,+ topicId,+ });+ if (stop === 'fresh') return undefined;+ if (stop === 'unconfirmed') {+ const metadata = await readRunTopicMetadata(ctx.db, owner, topicId);+ if ((await ctx.readRunDevicePresence({ metadata, operationId })) !== 'offline')+ return undefined;+ }++ const reclaimed = await ctx.db.transaction(async (tx) => {+ const operationModel = new AgentOperationModel(tx, ctx.userId, ctx.workspaceId);+ const settled = await operationModel.settleStaleRunning(+ operationId,+ staleBefore,+ latestTotalCost,+ );+ // `stopStaleRun` already claimed the lease atomically when it had to stop.+ if (+ !settled &&+ stop === 'not_running' &&+ !(await isOrphanedRun(operationModel, operationId, staleBefore))+ )+ return false;++ await new TaskTopicModel(tx, ctx.userId, ctx.workspaceId).updateStatus(+ task.id,+ topicId,+ 'timeout',+ );+ await new TaskModel(tx, ctx.userId, ctx.workspaceId).updateStatus(task.id, 'paused', {+ error: LEASE_EXPIRED_ERROR,+ });+ return true;+ });+ if (!reclaimed) return undefined;++ return ctx.recoverLostRun(graph, nodeId, task, effects);+};++/**+ * Recover a Task whose run was lost rather than judged โ its lease expired or+ * the gateway watchdog abandoned it.+ *+ * A run lost because its device went offline mid-run is the same failure as a+ * dispatch that never reached the device, only noticed later: the laptop went+ * to sleep with the run on it. It is re-marked as an offline run so it neither+ * spends the attempt budget nor retries into a device that is still gone.+ */+export const recoverLostRun = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ effects: GoalAdvanceEffect[] = [],+): Promise<GoalTickResult> => {+ await ctx.markRunLostToOfflineDevice(task.id);+ const held = await ctx.holdForOfflineDevice(graph, nodeId, task, effects);+ if (held) return held;+ return ctx.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);+};++/**+ * Re-mark the Task's latest lost run as an offline run when the device it ran+ * on is offline now. Only a device the gateway can vouch for counts: without+ * presence the run stays a charged attempt, exactly as before.+ */+export const markRunLostToOfflineDevice = async (ctx: GoalServiceContext, taskId: string) => {+ const [latest] = await ctx.taskTopicModel.findWithHandoff(taskId, 1);+ if (!latest?.topicId || (latest.status !== 'timeout' && latest.status !== 'failed')) return;+ if ((await ctx.readRunDevicePresence(latest)) !== 'offline') return;+ await ctx.taskTopicModel.updateStatus(taskId, latest.topicId, DEVICE_OFFLINE_RUN_STATUS);+};++export const resumeAbandonedTaskRecovery = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ effects: GoalAdvanceEffect[] = [],+): Promise<GoalTickResult> => {+ const recovery = await new TaskRecoveryCoordinator(ctx.db, ctx.userId, ctx.workspaceId).recover({+ goal: graph.goal,+ task,+ });+ if (recovery.outcome === 'started' || recovery.outcome === 'already-running') {+ await ctx.coordinatorGraph.updateNodeStatus(+ graph.goal.id,+ nodeId,+ 'active',+ 'Recovered an abandoned Task operation and started the next attempt',+ );+ await ctx.transitionStatus(graph.goal, 'running', 'reclaimed an abandoned Task');+ if (recovery.outcome === 'started') {+ effects.push({+ detail: 'abandoned operation retry',+ nodeId,+ operationId: recovery.operationId,+ targetId: task.id,+ type: 'started_run',+ });+ }+ return {+ goalId: graph.goal.id,+ message: `Recovered abandoned task ${task.identifier}`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }++ // The retry never reached a device. The Task keeps that reason, and the next+ // advance waits for the device to come back rather than asking a person.+ if (recovery.outcome === 'spawn-failed' && recovery.deviceUnavailable) {+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} is waiting for its device to reconnect`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }++ // The goal was paused or ended (a close fenced it) while this advance was+ // deciding: start nothing and do not reopen it.+ if (recovery.outcome === 'goal-stopped') {+ return {+ goalId: graph.goal.id,+ message: 'Goal stopped while recovery was being decided',+ nodeId,+ outcome: 'no_progress',+ taskId: task.id,+ };+ }++ // Nothing failed: somebody settled the Task while this advance was deciding.+ // Opening a gate would ask them to judge their own decision.+ if (recovery.outcome === 'settled') {+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} was settled while recovery was being decided`,+ nodeId,+ outcome: 'no_progress',+ taskId: task.id,+ };+ }+ const reason =+ recovery.outcome === 'exhausted-cost'+ ? 'Goal cost budget was exhausted after an operation was abandoned'+ : recovery.outcome === 'exhausted-rounds'+ ? 'Task attempt budget was exhausted after an operation was abandoned'+ : 'Automatic recovery could not restart an abandoned operation';+ return ctx.gateOrTakeOver(graph, nodeId, task.id, reason, effects, {+ machine: recovery.outcome === 'spawn-failed',+ });+};++/** The machine-recovery plan for a paused Task, over its runs since a person last answered its gate. */+export const planMachineRecoveryFor = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ now = new Date(),+) => {+ // A person's Retry restarts the schedule they overrode.+ const answeredAt = lastAnsweredGateAt(graph, nodeId);+ const runs = (await ctx.taskTopicModel.findByTaskId(task.id)).filter(+ (run) => !answeredAt || new Date(run.updatedAt) > answeredAt,+ );+ return planMachineRecovery({ error: task.error, now, runs, taskUpdatedAt: task.updatedAt });+};++/**+ * Recover a Task stopped by a machine problem without asking anyone to judge it+ * (see `planMachineRecovery`): a usage limit is waited out until it resets, a+ * transport fault is retried a few times, and neither run spends the attempt+ * budget. A broken setup โ or a schedule that ran out โ opens a machine gate+ * that says what to fix. Judgment failures return nothing and keep the+ * supervisor and the ordinary gate.+ */+export const holdForMachineFailure = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ effects: GoalAdvanceEffect[],+): Promise<GoalTickResult | undefined> => {+ if (task.status !== 'paused' || !task.error) return;+ // A supervised goal already has an owner for transport faults: the supervisor+ // diagnoses and retries them (see `recoveryEligibility`), so the deterministic+ // schedule stays out of its way rather than racing it for the same Task.+ const supervised = !!graph.goal.config?.supervision?.enabled || !!graph.goal.config?.manager;+ if (supervised && classifyGoalFailure(task.error).class === 'transient') return;+ const now = new Date();+ const plan = await ctx.planMachineRecoveryFor(graph, nodeId, task, now);+ if (plan.action === 'none') return;+ // A pause somebody made is theirs; the error text it kept proves nothing.+ if (statusAuthoredByActor(await ctx.taskModel.getActivities(task.id, 20), task.status)) return;++ if (plan.action === 'gate')+ return ctx.gateOrTakeOver(graph, nodeId, task.id, plan.reason, effects, { machine: true });+ if (plan.action === 'retry') return ctx.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);++ // The sweep re-ticks a held goal, but only on its own cadence; the tick that+ // first sees the failure also books an advance for the retry time. Later+ // sweep ticks do not, so a long hold does not pile up queued advances.+ if (now.getTime() - plan.failedAt.getTime() <= MACHINE_HOLD_SCHEDULE_WINDOW_MS) {+ await scheduleGoalAdvance({+ delay: Math.max(+ 1,+ Math.min(MAX_ADVANCE_DELAY_S, Math.ceil((plan.retryAt.getTime() - now.getTime()) / 1000)),+ ),+ goalId: graph.goal.id,+ trigger: 'wake',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier}: ${plan.message}`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+};++/**+ * Hold a Task whose run could not reach its device until a device is back.+ *+ * A sleeping laptop or a restarting desktop app is the usual cause, and it+ * fixes itself: the gate it used to open waited hours for someone to press+ * Retry once the device had long reconnected. While the device is offline the+ * goal waits โ the sweep keeps asking โ and spends nothing; the retry then+ * goes through the ordinary recovery path.+ */+export const waitForDevice = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ effects: GoalAdvanceEffect[],+): Promise<GoalTickResult | undefined> => {+ if (task.status !== 'paused' || !isDeviceUnavailableFailure(task.error)) return;+ const held = await ctx.holdForOfflineDevice(graph, nodeId, task, effects);+ if (held) return held;+ return ctx.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);+};++/**+ * Hold a Task whose run a usage window refused until that window reopens.+ *+ * An external Agent past its session limit refuses every run until the reset+ * its error reports. The supervisor used to read that as "spending requires+ * user action" and open a gate, which then waited on a person to press Retry+ * long after the window had reset. The coordinator now waits out the reset+ * itself and retries through the ordinary recovery path, which charges the+ * attempt as before. That bounds a window that keeps refusing.+ */+export const waitForQuotaReset = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ effects: GoalAdvanceEffect[],+): Promise<GoalTickResult | undefined> => {+ if (task.status !== 'paused') return;+ const [latest] = await ctx.taskTopicModel.findWithHandoff(task.id, 1);+ if (!latest?.operationId) return;+ const operation = await new AgentOperationModel(ctx.db, ctx.userId, ctx.workspaceId).findById(+ latest.operationId,+ );+ const failure = classifyRunFailure(operation?.error, task.error ?? '');+ if (failure.kind !== 'quota_reset') return;+ // A refusal whose text names the limit is recorded as an uncharged run+ // (`resolveFailedRunStatus`), so the attempt budget no longer bounds a window+ // that keeps refusing; the uncharged quota schedule does. Once it is spent,+ // fall through and `holdForMachineFailure` asks a person to fix the account.+ if (+ classifyGoalFailure(task.error).class === 'quota' &&+ (await ctx.planMachineRecoveryFor(graph, nodeId, task)).action === 'gate'+ )+ return;+ const retryAt = failure.resetsAt! + QUOTA_RESET_MARGIN_MS;+ if (retryAt <= Date.now()) {+ // The retry is a paid run, and recovery only checks the Task's own attempts+ // and cost. Past the Goal's deadline, rounds or spend it is not this path's+ // to start: ordinary failure handling takes it, and that gates it.+ const budget = await ctx.evaluateBudget(graph.goal, graph);+ if (budget.costLimitReached || budget.roundLimitReached || budget.deadlinePassed) return;+ return ctx.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);+ }+ // The sweep would get here too, but only on its own cadence; the reset is a+ // known time, so ask for that tick directly. One wake per Goal: the claim+ // fails while an earlier-or-equal wake is still pending. A reset further out+ // than the queue's longest delay is re-armed when the capped wake fires.+ const target = new Date(retryAt).toISOString();+ const armed = GoalWaitService.arm(target);+ // Claim on the reset itself, not on `armedUntil`: that rounds the delay up to+ // whole seconds from each tick's own clock, so two ticks before the same reset+ // would read as different wakes. Only a capped wake stores its earlier fire time.+ const capped = Date.parse(armed.armedUntil) < retryAt;+ if (+ await new GoalModel(ctx.db, ctx.userId, ctx.workspaceId).armQuotaRetryWake(+ graph.goal.id,+ capped ? armed.armedUntil : target,+ )+ )+ await new GoalWaitService(ctx.db, ctx.userId, ctx.workspaceId).schedule(+ graph.goal.id,+ armed.delay,+ );+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} is waiting for its usage window to reset at ${new Date(retryAt).toISOString()}`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+};++/**+ * The offline retry schedule. Offline runs are not charged to the attempt+ * budget, so this is what bounds them: each consecutive one pushes the next+ * retry further out (see `nextDeviceOfflineRetryAt`), and once the offline+ * retries are spent a person is asked. Presence only brings a retry forward โ+ * a device seen back online is retried at once โ so a deployment without a+ * device gateway, or a run with no recorded device, still retries on schedule.+ *+ * Returns nothing when the Task should retry now.+ */+export const holdForOfflineDevice = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ effects: GoalAdvanceEffect[],+): Promise<GoalTickResult | undefined> => {+ const runs = await ctx.taskTopicModel.findByTaskId(task.id);+ const offlineRuns = countConsecutiveDeviceOfflineRuns(runs);+ // A dispatch failure is an offline run even when it left no run behind.+ if (!offlineRuns && !isDeviceUnavailableFailure(task.error)) return;++ const lastFailureAt = new Date(offlineRuns ? runs[0].updatedAt : task.updatedAt);+ const retryAt = nextDeviceOfflineRetryAt(offlineRuns, lastFailureAt);+ if (!retryAt)+ return ctx.gateOrTakeOver(graph, nodeId, task.id, DEVICE_OFFLINE_GATE_REASON, effects, {+ machine: true,+ });+ if (retryAt.getTime() <= Date.now()) return;++ const [latest] = await ctx.taskTopicModel.findWithHandoff(task.id, 1);+ if (latest && (await ctx.readRunDevicePresence(latest)) === 'online') return;++ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} is waiting for its device to reconnect; next retry at ${retryAt.toISOString()}`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+};++/**+ * Whether the device a run was routed to is connected right now.+ *+ * Presence is read for the exact device the run used, in the pool it was+ * routed through: a workspace goal may run on a personal device, and another+ * device coming online proves nothing about this one. A failed dispatch+ * records its route on the operation error; a run that got going leaves its+ * device on the topic. A topic bound to a device without a recorded pool is+ * looked up in every pool this goal can route through.+ */+export const readRunDevicePresence = async (+ ctx: GoalServiceContext,+ run: {+ metadata?: ChatTopicMetadata | null;+ operationId?: string | null;+ },+): Promise<'offline' | 'online' | 'unknown'> => {+ if (!deviceGateway.isConfigured) return 'unknown';++ const operation = run.operationId+ ? await new AgentOperationModel(ctx.db, ctx.userId, ctx.workspaceId).findById(run.operationId)+ : undefined;+ const dispatchRoute = readDeviceDispatchRoute(operation?.error);+ const running = run.metadata?.runningOperation;+ const runningDevice =+ running?.deviceId && running.operationId === run.operationId ? running : undefined;++ let deviceId: string | undefined;+ let pools: { userId: string; workspaceId?: string }[];+ if (dispatchRoute) {+ deviceId = dispatchRoute.deviceId;+ pools = [{ userId: dispatchRoute.userId, workspaceId: dispatchRoute.workspaceId }];+ } else if (runningDevice) {+ deviceId = runningDevice.deviceId;+ pools = [+ {+ userId: runningDevice.deviceUserId ?? ctx.userId,+ workspaceId: runningDevice.deviceWorkspaceId,+ },+ ];+ } else {+ deviceId = run.metadata?.boundDeviceId;+ pools = [+ { userId: ctx.userId },+ ...(ctx.workspaceId ? [{ userId: ctx.userId, workspaceId: ctx.workspaceId }] : []),+ ];+ }+ if (!deviceId) return 'unknown';++ for (const pool of pools) {+ const devices = await deviceGateway.queryDeviceList(pool.userId, pool.workspaceId);+ if (devices.some((device) => device.deviceId === deviceId)) return 'online';+ }+ return 'offline';+};diff --git a/apps/server/src/services/goal/GoalService/rollout.ts b/apps/server/src/services/goal/GoalService/rollout.tsnew file mode 100644index 00000000000..d62414bb27c--- /dev/null+++ b/apps/server/src/services/goal/GoalService/rollout.ts@@ -0,0 +1,527 @@+import type { GoalAdvanceEffect } from '@lobechat/agent-tracing';+import {+ GOAL_BATCH_ASSAY_TITLE,+ GOAL_BATCH_BREAK_OPTION,+ GOAL_BATCH_BREAK_QUESTION_TAIL,+ GOAL_BATCH_TEMPLATE_TITLE,+ GOAL_COORDINATOR_ACTOR_ID,+ PATTERN_BREAK_PAUSE_REASON,+ ROLLOUT_CANARY_SIZE_DEFAULT,+ ROLLOUT_MAX_CANARY_SIZE,+} from '@lobechat/const/goal';+import type { GoalGraphSnapshot, GoalTickResult } from '@lobechat/types';++import { type ExpertiseCarrier, ExpertiseModel } from '@/database/models/expertise';+import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';++import { BatchPlanSkillService } from '../batchPlanSkill';+import { TERMINAL_NODE_STATUSES } from '../decideNextMove';+import { carriedUnitBrief, createRecipeUnitTask } from '../rolloutBatch';+import { evaluateRolloutGate, type RolloutGateResult, withGateVerdict } from '../rolloutGate';+import type { GoalServiceContext } from './types';+import { GOAL_ENDED_STATUSES, log } from './utils';++/**+ * Judge a repeated batch's gate, but only once the wave it released has fully+ * settled. Returns undefined when there is nothing to judge: no batch, a batch+ * already through its gate or parked on a pattern break, or a wave still+ * running (the ordinary frontier owns that tick). The final wave is judged+ * like every other โ a unit retired or broken in it must stop the batch the+ * same way โ and a pass with the roster exhausted closes the batch.+ */+export const collectRolloutGate = (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+): RolloutGateResult | undefined => {+ const policy = graph.goal.config?.rollout;+ const state = graph.goal.config?.rolloutState;+ if (+ !policy ||+ !state ||+ state.phase === 'done' ||+ state.phase === 'pattern_break' ||+ state.phase === 'release_review' ||+ state.phase === 'plan_revision'+ )+ return undefined;+ const materializedIds = new Set([...state.probeNodeIds, ...(state.massNodeIds ?? [])]);+ const materialized = graph.nodes.filter((node) => materializedIds.has(node.id));+ if (materialized.some((node) => !TERMINAL_NODE_STATUSES.has(node.status))) return undefined;+ return evaluateRolloutGate({ graph, policy, state });+};++/** Whether a node is one of the current batch's released members (R6 routing). */+export const isBatchMember = (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+): boolean => {+ const state = graph.goal.config?.rolloutState;+ if (!state) return false;+ return state.probeNodeIds.includes(nodeId) || (state.massNodeIds ?? []).includes(nodeId);+};++/**+ * Hand a blocked batch gate to a person.+ *+ * The batch cannot advance on its own, so this opens a decision on the Assay+ * and pauses the goal with the pattern-break reason. The choice is the v3+ * fork: revise the same recipe (repeat the v1 โ v2 loop) or fork a fresh+ * recipe for the units that broke, inside this batch โ never a silent park.+ */+export const openPatternBreakGate = async (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ message: string,+ effects: GoalAdvanceEffect[],+ /** What held the batch: the gate's own verdict, or one unit's failed check (R6). */+ cause: { gate?: RolloutGateResult; unitId?: string } = {},+): Promise<GoalTickResult> => {+ const goalId = graph.goal.id;+ const state = graph.goal.config?.rolloutState;+ if (!state) return { goalId, message, outcome: 'waiting_human' };++ const reason = `${PATTERN_BREAK_PAUSE_REASON}: ${message}`;+ // Overlapping advances can both see the batch break. Claim it under the+ // goal row's lock: the first opens the gate โ materializing the Assay a+ // `full` rollout never created โ and records it in the same transaction;+ // the rest find the break already open and reuse its gate instead of+ // opening a second assay and decision that would re-park the goal later.+ const claim = await ctx.db.transaction(async (tx) => {+ const goalModel = new GoalModel(tx, ctx.userId, ctx.workspaceId);+ const locked = await goalModel.lockById(goalId);+ const current = locked?.config?.rolloutState;+ if (!locked || !current) return undefined;+ if (current.phase === 'pattern_break')+ return { gateNodeId: current.assayNodeId, opened: false as const };+ const writer = new GoalGraphModel(tx, ctx.userId, ctx.workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ });++ // The gate hangs on the Assay. A `full` rollout never created one โ it+ // skips the probe gate โ but a break still needs a `decision` node for the+ // human question and, later, for the restart (a `batch` node cannot carry+ // a decision), so the gate target is stable whichever trigger opened it.+ let gateNodeId = current.assayNodeId;+ if (!gateNodeId) {+ const assay = await writer.createNode(goalId, {+ description:+ 'Whether this repeated batch can be delivered without further human decisions.',+ kind: 'decision',+ scopeId: current.batchNodeId,+ status: 'proposed',+ title: GOAL_BATCH_ASSAY_TITLE,+ });+ if (!assay) return undefined;+ gateNodeId = assay.id;+ }+ // The ids are the stable vocabulary; the human-facing labels and their+ // consequences live in the locale files and are resolved by option id on+ // the client (like the retry/retire/fail gates), so no English copy is+ // persisted into a gate a non-English reader has to answer.+ const decision = await writer.createDecision(goalId, gateNodeId, {+ authority: 'user',+ options: [+ {+ id: GOAL_BATCH_BREAK_OPTION.revise,+ label: 'Revise the recipe and re-probe',+ },+ {+ // One batch carries one roster and one gate, so this is not a second+ // batch running in parallel: it forks the recipe (no `revises`+ // chain) for the units that broke, inside this same batch.+ id: GOAL_BATCH_BREAK_OPTION.newClass,+ label: 'Fork a fresh recipe',+ },+ ],+ question: `${message}\n\n${GOAL_BATCH_BREAK_QUESTION_TAIL}`,+ requestedUserId: ctx.userId,+ });+ await writer.updateNodeStatus(goalId, gateNodeId, 'waiting', reason);+ await goalModel.updateRolloutState(+ goalId,+ withGateVerdict(+ { ...current, assayNodeId: gateNodeId, phase: 'pattern_break' },+ {+ checks: cause.gate?.checks ?? [],+ message,+ nodeId: cause.unitId,+ outcome: 'blocked',+ revision: current.templateRevision,+ trigger: cause.unitId ? 'unit' : 'gate',+ waveIndex: current.waveIndex,+ },+ ),+ );+ // Park the goal in the same commit, from the locked row: once the gate is+ // visible an answer may land at any moment, and a pause written after it+ // from an older snapshot would re-park a goal the answer just resumed.+ await goalModel.updatePauseReason(goalId, 'pattern_break');+ if (locked.status !== 'paused' && !GOAL_ENDED_STATUSES.has(locked.status)) {+ await goalModel.updateStatus(goalId, 'paused');+ await writer+ .recordGoalStatus(goalId, locked.status, 'paused', reason)+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));+ }+ return { decisionId: decision?.id, gateNodeId, opened: true as const };+ });+ if (!claim) return { goalId, message, outcome: 'waiting_human' };+ // Another advance opened this break; it parks the goal.+ if (!claim.opened) return { goalId, message, nodeId: claim.gateNodeId, outcome: 'waiting_human' };+ const gateNodeId = claim.gateNodeId;+ effects.push({+ detail: message,+ nodeId: gateNodeId,+ targetId: claim.decisionId ?? gateNodeId,+ type: 'opened_decision',+ });+ // Home lists what waits on the person from its briefs, so the gate stays+ // findable after it is dismissed from the approval island. It offers no+ // one-click answers: revising needs a correction, written on the goal page.+ if (claim.decisionId)+ await ctx.briefs.openDecision(graph.goal, {+ decisionId: claim.decisionId,+ options: [],+ question: `${message}\n\n${GOAL_BATCH_BREAK_QUESTION_TAIL}`,+ });+ effects.push({ type: 'goal_status', detail: 'paused: pattern_break' });+ return { goalId, message, nodeId: gateNodeId, outcome: 'waiting_human' };+};++/**+ * R5: restart the canary loop after a person intervened on a batch gate.+ *+ * The person's answer is the single human judgment; the coordinator opens the+ * next recipe round from it. `revise` chains a new Template onto the old one+ * (`revises`); `new_class` forks a fresh Template with no chain edge, still+ * inside this batch. Either way the members that broke are retired and+ * re-opened as the new canary, and the rollout returns to the probe phase, so+ * the class is proved again instead of rerun by hand.+ *+ * The correction is the *new recipe*: it is folded into the policy and written+ * on the Template, so the re-opened probes and every later wave are briefed+ * from the revised transformation โ not from the outline that just failed.+ */+export const restartRolloutLoop = async (+ ctx: GoalServiceContext,+ goalId: string,+ decisionId: string,+ optionId: string,+ resolution: string | undefined,+) => {+ const graph = await ctx.requireGraph(goalId);+ const policy = graph.goal.config?.rollout;+ const state = graph.goal.config?.rolloutState;+ if (!policy || !state)+ return ctx.graphModel.resolveDecision(goalId, decisionId, optionId, resolution);++ const batchId = state.batchNodeId;+ const roster = state.unitTitles ?? [];+ const released = state.releasedCount ?? state.probeNodeIds.length;+ // The correction the person wrote. A revision carries the plan forward and+ // appends it as its own section, so each version reads whole and diffs+ // against the last one; a fork starts again from the original outline. The+ // result is the new recipe: later waves only ever read+ // `policy.spec.recipeOutline`, so a note kept solely on the Template would+ // never reach the tasks meant to test it.+ const baseOutline = policy.spec?.recipeOutline?.trim() ?? '';+ const correction = (resolution ?? '').trim();+ const revision = state.templateRevision + 1;+ const previousPlan = state.templateNodeId+ ? graph.nodes.find((node) => node.id === state.templateNodeId)?.description?.trim()+ : undefined;+ // A fork starts from the batch's original outline โ kept on the batch node,+ // since every revision rewrites the policy's โ not from the revised plan.+ const originalOutline =+ graph.nodes.find((node) => node.id === batchId)?.description?.trim() || baseOutline;+ const basePlan = optionId === 'new_class' ? originalOutline : previousPlan || baseOutline;+ const revisedOutline = [basePlan, correction && `### v${revision}\n${correction}`]+ .filter(Boolean)+ .join('\n\n');++ // The answer and the round it opens land together. Every write below โ+ // resolving the question included โ commits in one transaction under the+ // goal row's lock, so a failure part-way leaves the question open to answer+ // again rather than consumed beside half a round; and a second answer+ // racing this one finds the break already restarted.+ // What a break teaches is mounted on the agent that runs the batch's units+ // (a run's expertise snapshot reads the executing agent's domains, not the+ // project's) โ resolved like the task assignee, so a deleted executor falls+ // back to the goal agent rather than a binding that cannot be written. Read+ // before the transaction, which holds the goal row.+ const carrierAgentId = await ctx.resolveTaskAssignee(graph.goal);+ const carrier: ExpertiseCarrier = carrierAgentId+ ? { id: carrierAgentId, type: 'agent' }+ : { type: 'user' };++ const committed = await ctx.db.transaction(async (tx) => {+ const goalModel = new GoalModel(tx, ctx.userId, ctx.workspaceId);+ const current = (await goalModel.lockById(goalId))?.config?.rolloutState;+ if (current?.phase !== 'pattern_break') return undefined;+ const resolved = await new GoalGraphModel(tx, ctx.userId, ctx.workspaceId).resolveDecision(+ goalId,+ decisionId,+ optionId,+ resolution,+ );+ if (!resolved) return undefined;+ const writer = new GoalGraphModel(tx, ctx.userId, ctx.workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ });++ // 1. A new recipe revision, or a forked new class (no `revises` chain).+ const template = await writer.createNode(goalId, {+ description: revisedOutline || baseOutline,+ kind: 'finding',+ scopeId: batchId,+ title: GOAL_BATCH_TEMPLATE_TITLE,+ });+ if (template && optionId !== 'new_class' && state.templateNodeId) {+ await writer.createEdge(goalId, template.id, state.templateNodeId, 'revises');+ }++ // The plan skill takes the revision as its next version, and the break+ // teaches the batch: a rule the executor reads, compiled into a criterion+ // the verifier judges every later unit by. A fork starts a new class of+ // units โ its correction describes them, it is not a rule for the old+ // ones. Each runs in its own savepoint: a failure there costs the skill+ // version or the lesson, never the round the answer opens.+ const inSavepoint = <T>(label: string, run: (db: typeof tx) => Promise<T>) =>+ tx.transaction(run).catch((error) => {+ log('restartRolloutLoop: %s failed: %O', label, error);+ return undefined;+ });+ let planSkill = state.planSkill;+ let planVersion: number | undefined;+ if (planSkill && revisedOutline) {+ const skill = planSkill;+ const version = await inSavepoint('plan skill revision', (db) =>+ new BatchPlanSkillService(db, ctx.userId, ctx.workspaceId).revise(skill, {+ goalId,+ guidance: correction || undefined,+ plan: revisedOutline,+ revision,+ }),+ );+ // The revision did not land (the skill was deleted, or the write+ // failed): units must not load a skill that lacks it. They fall back to+ // copying the revised plan, and the batch drops the stale reference.+ if (version === undefined) planSkill = undefined;+ else planVersion = version;+ } else if (!planSkill && revisedOutline) {+ // A batch from before plans were skills moves into one now, carrying+ // every earlier version of its plan.+ const inBatch = new Set(+ graph.edges+ .filter((edge) => edge.kind === 'contains' && edge.sourceNodeId === batchId)+ .map((edge) => edge.targetNodeId),+ );+ const earlier = graph.nodes+ .filter(+ (node) =>+ node.kind === 'finding' &&+ node.title === GOAL_BATCH_TEMPLATE_TITLE &&+ inBatch.has(node.id),+ )+ .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())+ .map((node) => node.description?.trim() ?? '');+ planSkill = await inSavepoint('plan skill adoption', (db) =>+ new BatchPlanSkillService(db, ctx.userId, ctx.workspaceId).adopt({+ batchNodeId: batchId,+ goalId,+ goalTitle: graph.goal.title,+ versions: [...earlier, revisedOutline],+ }),+ );+ }+ // A fork starts a new class: the old class's rules must stop reaching+ // runs too, not only its acceptance โ retire them in the shared domain,+ // where the executor's expertise would otherwise keep injecting them.+ // Not in a forgiving savepoint: the fork clears the batch's record of+ // them below, so a failure here fails the fork (the question stays open+ // to answer again) rather than leaving them active and forgotten.+ if (optionId === 'new_class' && state.learnings?.length) {+ const expertise = new ExpertiseModel(tx, ctx.userId, ctx.workspaceId);+ for (const learning of state.learnings) await expertise.retireLesson(learning.lessonId);+ }+ const learned =+ correction && optionId !== 'new_class'+ ? await inSavepoint('break learning', (db) =>+ new BatchPlanSkillService(db, ctx.userId, ctx.workspaceId).learn({+ carrier,+ domainId: state.learningDomainId,+ // What the gate found: this round's latest hold, in its own words.+ found:+ state.gateLog?.findLast(+ (entry) =>+ entry.outcome === 'blocked' && entry.revision === state.templateRevision,+ )?.message ?? 'the release gate held',+ goalTitle: graph.goal.title,+ guidance: correction,+ planSkill,+ revision: state.templateRevision,+ }),+ )+ : undefined;++ // 2. Retire the members that broke or were superseded, never delete them โ+ // the new round is `derived_from` them (decision #4). A member an earlier+ // round already re-opened is history, not a unit to re-open again.+ const memberIds = new Set([...state.probeNodeIds, ...(state.massNodeIds ?? [])]);+ const reopenedIds = new Set(+ graph.edges.filter((edge) => edge.kind === 'derived_from').map((edge) => edge.targetNodeId),+ );+ const broken: { brief?: string; id: string; title: string }[] = [];+ for (const node of graph.nodes) {+ if (!memberIds.has(node.id) || node.status === 'resolved' || reopenedIds.has(node.id))+ continue;+ broken.push({ brief: carriedUnitBrief(node), id: node.id, title: node.title });+ if (!TERMINAL_NODE_STATUSES.has(node.status)) {+ await writer.updateNodeStatus(+ goalId,+ node.id,+ 'retired',+ 'superseded by a new recipe revision',+ );+ }+ }++ // 3. A fresh gate for the fresh round.+ const assay = await writer.createNode(goalId, {+ description: 'Whether this repeated batch can be delivered without further human decisions.',+ kind: 'decision',+ scopeId: batchId,+ status: 'proposed',+ title: GOAL_BATCH_ASSAY_TITLE,+ });+ if (!assay) throw new Error('Failed to create the next batch gate');++ // The revised recipe becomes the batch's policy, so the probes below and+ // every later wave (which read it off the graph) carry the correction.+ await goalModel.updateRolloutPolicy(goalId, {+ ...policy,+ spec: {+ ...policy.spec,+ recipeOutline: revisedOutline || baseOutline,+ repeatable: policy.spec?.repeatable ?? true,+ },+ });++ // 4. The new canary re-opens the units that broke, as new tasks that+ // supersede the retired ones (decision #4: new task + retire, never move).+ // Cap it at the canary size: a break in a large wave โ or a `full` rollout+ // that released the whole class โ must not redispatch every member at once.+ // The broken units beyond the canary stay owed, and the waves after the gate+ // re-deliver them under the revised recipe. Only a gate that blocked with+ // every member resolved has nothing to re-open; it re-probes the next slice.+ const canarySize = Math.max(+ 2,+ Math.min(policy.canarySize ?? ROLLOUT_CANARY_SIZE_DEFAULT, ROLLOUT_MAX_CANARY_SIZE),+ );+ const reOpen = broken.slice(0, canarySize);+ const deferred = broken.slice(canarySize).map((unit) => unit.title);+ const fresh = broken.length ? [] : roster.slice(released, released + canarySize);+ // Nothing broke and nothing is left to release โ the gate held on something+ // else, such as an untested axis. Re-probe units this round delivered,+ // under the revision, so the new canary is never empty (an empty one would+ // re-open the same break at once).+ const reProbe =+ broken.length || fresh.length+ ? []+ : [...memberIds]+ .map((id) => graph.nodes.find((node) => node.id === id))+ .filter(+ (node): node is NonNullable<typeof node> =>+ !!node && node.status === 'resolved' && !reopenedIds.has(node.id),+ )+ .slice(0, canarySize)+ .map((node) => ({ brief: carriedUnitBrief(node), id: node.id, title: node.title }));+ const units = [+ ...[...reOpen, ...reProbe].map((unit) => ({+ brief: unit.brief,+ from: unit.id,+ title: unit.title,+ })),+ ...fresh.map((title) => ({+ brief: policy.unitBriefs?.[title],+ from: undefined as string | undefined,+ title,+ })),+ ];+ const probeIds: string[] = [];+ const opened: { from: string | undefined; title: string }[] = [];+ for (const unit of units) {+ const nodeId = await createRecipeUnitTask(+ writer,+ goalId,+ batchId,+ unit.title,+ { outline: revisedOutline || baseOutline, skill: planSkill },+ unit.brief,+ );+ if (!nodeId) continue;+ probeIds.push(nodeId);+ opened.push(unit);+ if (unit.from) {+ await writer.createEdge(goalId, nodeId, unit.from, 'derived_from').catch(() => {});+ }+ }+ for (const probeId of probeIds) {+ await writer.createEdge(goalId, assay.id, probeId, 'depends_on');+ }++ // 5. Back to canary, on the new revision. The roster is re-cut to what is+ // still owed โ the new probes first, then the broken units not re-probed,+ // then whatever was never released โ so the waves deliver only the+ // remainder and units already delivered under the old recipe drop out.+ const remaining = Array.from(+ new Set([+ ...opened.map((unit) => unit.title),+ ...deferred,+ ...roster.slice(released + fresh.length),+ ]),+ );+ await goalModel.updateRolloutState(goalId, {+ ...state,+ assayNodeId: assay.id,+ // A round's plan can be rewritten in place, so its skill version is kept, not derived.+ planVersions: planVersion+ ? { ...state.planVersions, [String(revision)]: planVersion }+ : state.planVersions,+ // The new canary is a fresh round: the old waves' members โ the broken+ // ones now retired โ must not count against its gate.+ massNodeIds: undefined,+ phase: 'probe',+ probeNodeIds: probeIds,+ releasedCount: opened.length,+ // A fork starts a new class of units: the old class's rules do not+ // bind it, so its learnings start empty.+ learningDomainId:+ optionId === 'new_class' ? undefined : (learned?.domainId ?? state.learningDomainId),+ learnings:+ optionId === 'new_class'+ ? undefined+ : learned+ ? [...(state.learnings ?? []), learned.learning]+ : state.learnings,+ planSkill,+ templateNodeId: template?.id ?? state.templateNodeId,+ templateRevision: state.templateRevision + 1,+ unitTitles: remaining,+ waveIndex: 0,+ });+ return { brokenIds: broken.map((unit) => unit.id), resolved };+ });+ if (!committed) return undefined;++ // A sibling still running when the gate was answered would keep spending โ+ // and could deliver โ beside the probe that replaces it. Its node is fenced+ // as retired above; stop the Task behind it. Not part of the transaction:+ // stopping a run cannot be rolled back, and retrying it is harmless.+ if (committed.brokenIds.length) await ctx.stopFencedTasks(goalId, new Set(committed.brokenIds));+ await ctx.setPauseReason(goalId, undefined);+ return committed.resolved;+};diff --git a/apps/server/src/services/goal/GoalService/tick.ts b/apps/server/src/services/goal/GoalService/tick.tsnew file mode 100644index 00000000000..2dca788c447--- /dev/null+++ b/apps/server/src/services/goal/GoalService/tick.ts@@ -0,0 +1,389 @@+import type { GoalAdvanceEffect } from '@lobechat/agent-tracing';+import type { GoalTickResult } from '@lobechat/types';++import {+ decideNextMove,+ frontierNeedsBudget,+ needsMetricCriteria,+ NO_FRONTIER_PAUSE_REASON,+ selectFrontier,+} from '../decideNextMove';+import { exploreGraph } from '../exploreGraph';+import { classifyGoalFailure, isMachineFailureClass } from '../failureClass';+import { GoalManagerService } from '../manager';+import { resolveMaxConcurrentTasks } from '../recoveryPolicy';+import { withoutGoalReport } from '../report';+import { GoalReportService } from '../reportService';+import { GoalSupervisorService } from '../supervisor';+import {+ type GoalTickOptions,+ toBudgetState,+ toFrontierTaskState,+ toTraceGraphState,+} from '../traceObservation';+import type { GoalServiceContext } from './types';++/**+ * Tick outcomes after which the Goal-level acceptance may have just ended: the+ * Goal was achieved, failed or canceled, or parked on a gate (an acceptance+ * whose attempts ran out opens one). Every other outcome skips the check.+ */+const REPORT_CHECK_OUTCOMES = new Set<GoalTickResult['outcome']>([+ 'achieved',+ 'failed',+ 'waiting_human',+]);++/**+ * Advance the goal by one coordinator step.+ *+ * Choosing and doing are separate: `decideNextMove` is a pure function of the+ * graph, the responsible task and the budget, and everything under the switch+ * only carries that choice out. `onDecision` then receives both what the+ * coordinator read and what it did โ the decision surface a goal trajectory+ * records. It travels on that side channel rather than on `GoalTickResult`+ * because the result crosses tRPC to the client and the graph payload is+ * large, the same reason the context engine snapshot stays off the agent+ * runtime's event array.+ */+export const tick = async (+ ctx: GoalServiceContext,+ goalId: string,+ options?: GoalTickOptions,+): Promise<GoalTickResult> => {+ const result = await ctx.tickOnce(goalId, options);+ if (REPORT_CHECK_OUTCOMES.has(result.outcome)) await ctx.dispatchGoalReport(goalId);+ return result;+};++/**+ * The wrap-up branch. Runs after the move rather than as one: it only fires+ * once the Goal-level acceptance has ended, and whatever happens to it โ a+ * dispatch that throws, a run that fails or times out โ must not change the+ * outcome the coordinator just reported or the Goal's status.+ */+export const dispatchGoalReport = async (ctx: GoalServiceContext, goalId: string) => {+ try {+ await new GoalReportService(ctx.db, ctx.userId, ctx.workspaceId).dispatchIfDue(goalId);+ } catch (error) {+ console.error('[GoalService] wrap-up report dispatch failed:', error);+ }+};++export const tickOnce = async (+ ctx: GoalServiceContext,+ goalId: string,+ options?: GoalTickOptions,+): Promise<GoalTickResult> => {+ const at = Date.now();+ // The coordinator never sees the wrap-up report node: it runs after the+ // Goal-level acceptance and does not take part in the Goal's status.+ const graph = withoutGoalReport(await ctx.requireGraph(goalId));+ // A draft is still being arranged; only `start` hands it to the coordinator.+ if (graph.goal.status === 'draft')+ return {+ goalId,+ message: `Goal is a draft; start it with lh goal start ${goalId}`,+ outcome: 'no_progress',+ };+ if (graph.goal.config?.manager) {+ // The system's own planner leads whenever the Goal has one: a main Agent is+ // the fallback for problems that planner cannot express, not a replacement+ // for it. With exploration configured this call only settles a turn already+ // in flight; new turns start from `gateOrTakeOver` below, where the+ // coordinator has run out of moves. A Goal whose only planner is the main+ // Agent keeps being led by it.+ const result = await new GoalManagerService(ctx.db, ctx.userId, ctx.workspaceId).advance(+ graph,+ { mayStartTurn: !graph.goal.config.exploration },+ );+ if (result) return result;+ }+ // A plan the owner sent back waits on the main Agent's rewrite, not on the+ // frontier: every probe has settled and nothing else is ready to run.+ if (graph.goal.config?.rolloutState?.phase === 'plan_revision')+ return ctx.releaseReview.routeRolloutRevision(graph);++ const frontier = selectFrontier(graph);++ // Every candidate's task, not just the head's: the scheduler has to know+ // which of them are in flight before it can decide what else to start.+ const candidateTaskIds = frontier.eligible.flatMap(({ node }) =>+ node.taskId ? [node.taskId] : [],+ );+ const tasksById = new Map(+ (candidateTaskIds.length > 0 ? await ctx.taskModel.findByIds(candidateTaskIds) : []).map(+ (task) => [task.id, task],+ ),+ );++ // Asked of every unblocked candidate, not just the head: the scheduler+ // walks past a running head to start an independent task, so a head that+ // needs no budget must not decide that nothing does. A goal with nothing+ // startable still skips the query.+ const budget = frontierNeedsBudget(frontier, tasksById)+ ? toBudgetState(graph.goal, await ctx.evaluateBudget(graph.goal, graph))+ : undefined;++ // Same shape as the budget: a database read the pure decision cannot do,+ // taken only in the terminal phase of a goal that declares numeric clauses.+ const metricCriteria = needsMetricCriteria(graph)+ ? await ctx.evaluateMetricCriteria(graph)+ : undefined;++ const concurrency = resolveMaxConcurrentTasks(graph.goal);+ // A repeated batch judges its own gate once the wave it released has fully+ // settled; while a wave is still running the ordinary frontier owns the tick.+ const rolloutGate = ctx.collectRolloutGate(graph);+ const move = decideNextMove({+ budget,+ concurrency,+ frontier,+ graph,+ metricCriteria,+ rolloutGate,+ tasksById,+ });+ // The scheduler may pick past the head of the frontier, so every arm below+ // acts on the node the move chose, which is not necessarily the+ // highest-ranked candidate.+ const acting = move.chosenNodeId+ ? graph.nodes.find((node) => node.id === move.chosenNodeId)+ : undefined;+ const actingTask = acting?.taskId ? (tasksById.get(acting.taskId) ?? null) : undefined;++ const effects: GoalAdvanceEffect[] = [];++ const observe = (result: GoalTickResult): GoalTickResult => {+ options?.onDecision?.({+ at,+ branch: move.branch,+ budget,+ candidates: move.candidates,+ metricCriteria,+ chosenNodeId: move.chosenNodeId,+ effects,+ candidateTasks: frontier.eligible.flatMap(({ node }) => {+ const task = node.taskId ? tasksById.get(node.taskId) : undefined;+ return task ? [toFrontierTaskState(task, node.id)] : [];+ }),+ concurrency,+ graphState: toTraceGraphState(graph),+ message: result.message,+ outcome: result.outcome,+ taskId: result.taskId,+ });+ return result;+ };++ switch (move.branch) {+ case 'goal_paused':+ case 'goal_terminal': {+ return observe({ goalId, message: move.message, outcome: move.outcome });+ }++ case 'pending_decision': {+ await ctx.transitionStatus(graph.goal, 'review', 'a decision gate is open');+ effects.push({ type: 'goal_status', detail: 'review' });+ return observe({+ goalId,+ message: move.message,+ nodeId: move.focusNodeId,+ outcome: move.outcome,+ });+ }++ // Managed Goals reconsider the same contract after a shortfall. Unmanaged+ // Goals park until an observation clears the gate, keeping them out of+ // the sweep while they have no action to take.+ case 'measured_acceptance': {+ const replanning = await new GoalManagerService(+ ctx.db,+ ctx.userId,+ ctx.workspaceId,+ ).reconsiderAcceptance(graph, move.message);+ if (replanning) return observe(replanning);+ await ctx.setPauseReason(goalId, 'measured_acceptance');+ await ctx.transitionStatus(graph.goal, 'paused', move.message);+ effects.push({ type: 'goal_status', detail: 'paused' });+ return observe({ goalId, message: move.message, outcome: move.outcome });+ }++ case 'terminal_acceptance': {+ return observe(await ctx.settleTerminalAcceptance(graph, move, effects));+ }++ case 'explore_graph': {+ const spent = await ctx.evaluateBudget(graph.goal, graph);+ if (spent.costLimitReached || spent.roundLimitReached || spent.deadlinePassed) {+ await ctx.transitionStatus(+ graph.goal,+ 'paused',+ 'Budget exhausted before graph exploration',+ );+ effects.push({ type: 'goal_status', detail: 'paused: budget' });+ return observe({+ goalId,+ outcome: 'no_progress',+ message: 'Budget exhausted before graph exploration',+ });+ }+ return observe(+ await exploreGraph({+ db: ctx.db,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ graph,+ effects,+ }),+ );+ }++ case 'plan_decomposition': {+ return observe(await ctx.planDecomposition(graph, effects));+ }++ case 'rollout_gate': {+ return observe(await ctx.releaseReview.routeRolloutRelease(graph, effects, rolloutGate));+ }++ case 'pattern_break': {+ return observe(+ await ctx.openPatternBreakGate(graph, move.message, effects, { gate: rolloutGate }),+ );+ }++ case 'no_frontier': {+ // Say so on the row instead of leaving a goal that reads as `running`+ // while it cannot run โ and, just as importantly, take it out of the+ // sweep's window. A `running` goal that always reports `no_progress` is+ // picked by every scan forever, and enough of them starve every other+ // stalled goal out of the newest-first limit.+ await ctx.transitionStatus(graph.goal, 'paused', NO_FRONTIER_PAUSE_REASON);+ effects.push({ type: 'goal_status', detail: 'paused' });+ return observe({ goalId, message: move.message, outcome: move.outcome });+ }++ case 'create_task': {+ return observe(await ctx.createResponsibleTask(graph, acting!, effects));+ }++ case 'missing_task': {+ await ctx.coordinatorGraph.updateNodeStatus(+ goalId,+ acting!.id,+ 'waiting',+ 'Responsible task is missing',+ );+ effects.push({ nodeId: acting!.id, type: 'node_status', detail: 'waiting' });+ return observe({+ goalId,+ message: move.message,+ nodeId: acting!.id,+ outcome: move.outcome,+ });+ }++ default: {+ // Everything from here on has a live responsible task.+ const task = actingTask!;+ await ctx.ensureTaskWorkVersion(graph.goal.id, acting!.id, task.id);++ switch (move.branch) {+ case 'consume_completed': {+ return observe(await ctx.consumeCompletedTask(graph, acting!.id, task.id, effects));+ }++ case 'recover_lease': {+ return observe(await ctx.recoverLostRun(graph, acting!.id, task, effects));+ }++ case 'recover_verification': {+ return observe(await ctx.recoverAfterVerification(graph, acting!.id, task, effects));+ }++ case 'failure_decision': {+ // R6: a batch member that did not pass its own check IS the same+ // intervention as a blocked gate. Route it through the batch gate so+ // the class rolls back to canary, instead of parking on a standalone+ // task decision that never touches the recipe.+ if (ctx.isBatchMember(graph, acting!.id)) {+ return observe(+ await ctx.openPatternBreakGate(graph, `${acting!.title}: ${move.message}`, effects, {+ unitId: acting!.id,+ }),+ );+ }+ const waiting =+ (await ctx.waitForDevice(graph, acting!.id, task, effects)) ??+ (await ctx.waitForQuotaReset(graph, acting!.id, task, effects));+ if (waiting) return observe(waiting);+ const held = await ctx.holdForMachineFailure(graph, acting!.id, task, effects);+ if (held) return observe(held);+ const supervision = await new GoalSupervisorService(+ ctx.db,+ ctx.userId,+ ctx.workspaceId,+ ).reviewFailure(graph, acting!.id, task);+ if (supervision) return observe(supervision);+ // A machine failure the supervisor gave up on still asks for a fix,+ // not a judgment about the work.+ return observe(+ await ctx.gateOrTakeOver(graph, acting!.id, task.id, move.message, effects, {+ machine: isMachineFailureClass(classifyGoalFailure(task.error).class),+ }),+ );+ }++ case 'task_paused': {+ // R6: a paused batch member (e.g. its delivery did not pass+ // verification) is an intervention on the class, not on one task.+ if (ctx.isBatchMember(graph, acting!.id)) {+ return observe(+ await ctx.openPatternBreakGate(graph, `${acting!.title}: ${move.message}`, effects, {+ unitId: acting!.id,+ }),+ );+ }+ return observe({+ goalId,+ message: move.message,+ nodeId: acting!.id,+ outcome: move.outcome,+ taskId: task.id,+ });+ }++ case 'task_running': {+ if (task.status === 'running') {+ const recovered = await ctx.recoverAbandonedTask(graph, acting!.id, task, effects);+ if (recovered) return observe(recovered);+ }+ return observe({+ goalId,+ message: move.message,+ nodeId: acting!.id,+ outcome: move.outcome,+ taskId: task.id,+ });+ }++ case 'budget_exhausted': {+ await ctx.transitionStatus(graph.goal, 'paused', move.message);+ effects.push({ type: 'goal_status', detail: 'paused' });+ return observe({+ goalId,+ message: move.message,+ nodeId: acting!.id,+ outcome: move.outcome,+ taskId: task.id,+ });+ }++ default: {+ return observe(await ctx.dispatchWork(graph, acting!.id, task, effects));+ }+ }+ }+ }+};diff --git a/apps/server/src/services/goal/GoalService/types.ts b/apps/server/src/services/goal/GoalService/types.tsnew file mode 100644index 00000000000..d75a190f62d--- /dev/null+++ b/apps/server/src/services/goal/GoalService/types.ts@@ -0,0 +1,273 @@+import type { GoalCreateConfig, GoalNodeKind, GoalNodeStatus } from '@lobechat/types';+import type { GoalSeedTask } from '@lobechat/utils/goalSeeds';++import type { AgentModel } from '@/database/models/agent';+import type { GoalModel } from '@/database/models/goal';+import type { GoalGraphModel } from '@/database/models/goalGraph';+import type { TaskModel } from '@/database/models/task';+import type { TaskTopicModel } from '@/database/models/taskTopic';+import type { WorkModel } from '@/database/models/work';+import type { LobeChatDatabase } from '@/database/type';++import type { TaskService } from '../../task';+import type { AcceptanceService } from '../../verify/acceptanceService';+import type { GoalBriefService } from '../goalBriefs';+import type { GoalReleaseReview } from '../releaseReview';+import type {+ attachTaskDeliverables,+ consumeCompletedTask,+ recoverAfterVerification,+ settleTerminalAcceptance,+} from './completion';+import type { bindTopic, create, createFromConversation, resolveTopicRun } from './creation';+import type {+ answerClarifications,+ decide,+ gateOrTakeOver,+ openFailureDecision,+ openFailureDecisionLocked,+ reopenForChanges,+} from './decisions';+import type {+ buildTaskAcceptanceRequirement,+ buildTaskInstruction,+ createResponsibleTask,+ dispatchWork,+ ensureTaskWorkVersion,+} from './dispatch';+import type {+ addEdge,+ addNode,+ followGoalAgent,+ goalOwnerTaskScope,+ graphAs,+ reassignUnfinishedTasks,+ resolveTaskAssignee,+ retireNodes,+ setAgent,+ setBudget,+ setTaskAgent,+ stopFencedTasks,+ updateRequirement,+} from './editing';+import type {+ close,+ deleteGoal,+ pause,+ requestSignOff,+ restart,+ resume,+ transitionStatus,+} from './lifecycle';+import type {+ evaluateBudget,+ evaluateMetricCriteria,+ isParkedOnMeasuredGate,+ recordObservation,+ reopenIfMeasurementCleared,+ resolveSpend,+ setAcceptanceCriteria,+ setMetricCriteria,+ setPauseReason,+} from './measurement';+import type { handPlanningToMainAgent, planDecomposition } from './planning';+import type {+ collectAcceptances,+ collectAssignees,+ collectDeliveredAt,+ collectRunHeartbeats,+ graph,+ listEvents,+ pendingClarifications,+ pendingForIsland,+ requireGraph,+ status,+} from './reads';+import type {+ holdForMachineFailure,+ holdForOfflineDevice,+ markRunLostToOfflineDevice,+ planMachineRecoveryFor,+ readRunDevicePresence,+ recoverAbandonedTask,+ recoverLostRun,+ resumeAbandonedTaskRecovery,+ waitForDevice,+ waitForQuotaReset,+} from './recovery';+import type {+ collectRolloutGate,+ isBatchMember,+ openPatternBreakGate,+ restartRolloutLoop,+} from './rollout';+import type { dispatchGoalReport, tick, tickOnce } from './tick';++export type CreateGoalTaskInput = GoalSeedTask;++export interface CreateGoalGraphInput {+ /**+ * The goal agent: it supervises the goal, runs its planning turns and does its+ * Tasks unless `config.taskAgentId` names a dedicated executor. Defaults to+ * `createdByAgentId`.+ */+ agentId?: string;+ config?: GoalCreateConfig;+ /**+ * The agent that made this call, when a tool did. Distinct from `agentId`,+ * which is the agent the goal belongs to โ creating a goal from the modal on+ * an agent's page sets that, but the author is still the person.+ */+ createdByAgentId?: string;+ /**+ * Structured acceptance criteria. Persisted as `verify_criteria` rows and+ * recorded on `config.acceptance.criteriaIds`, so the goal page can show and+ * edit them and the terminal Goal-acceptance Task verifies against exactly+ * these checks. Callers still fold the same criteria into `requirement`+ * prose โ that text remains what every Task's execution context reads.+ */+ criteria?: Array<{ description?: string; instruction?: string; title: string }>;+ /**+ * Create the goal as a `draft`: the graph can be arranged, and nothing is+ * dispatched until `GoalStartService.start` launches it.+ */+ draft?: boolean;+ maxRounds?: number;+ maxTotalCost?: number;+ /**+ * The user's ask in their own words, shown on the seeded problem node. The+ * full `requirement` (with its acceptance boilerplate) stays on the goal row+ * โ copying it onto the node made every drill-down read like a contract.+ */+ problemDescription?: string;+ projectId?: string;+ requirement?: string;+ /**+ * Seed task nodes; `dependsOn` names other seeds by title. A plain string is title-only.+ * When omitted, the coordinator plans the decomposition on first advance.+ */+ tasks?: Array<CreateGoalTaskInput | string>;+ title: string;+ /**+ * The conversation this goal was created from. Recorded as the goal's+ * `topic` subject so the conversation can find and show it.+ */+ topicId?: string;+}++export interface CreateGoalNodeInput {+ description?: string;+ kind: GoalNodeKind;+ priority?: number;+ questionId?: string;+ scopeId?: string;+ status?: GoalNodeStatus;+ title: string;+}++/** The arguments a service method takes after its `ctx`. */+export type MethodArgs<F> = F extends (ctx: any, ...args: infer A) => any ? A : never;++/** A module function as the instance exposes it: `ctx` already applied. */+type Bound<F> = F extends (ctx: any, ...args: infer A) => infer R ? (...args: A) => R : never;++/**+ * What a method module reads off the service: its collaborators, and its+ * methods dispatched through the instance so a spy or override still sees them.+ */+export interface GoalServiceContext {+ readonly acceptanceService: AcceptanceService;+ addEdge: Bound<typeof addEdge>;+ addNode: Bound<typeof addNode>;+ readonly agentModel: AgentModel;+ answerClarifications: Bound<typeof answerClarifications>;+ answerReleaseGate: GoalReleaseReview['answerReleaseGate'];+ attachTaskDeliverables: Bound<typeof attachTaskDeliverables>;+ bindTopic: Bound<typeof bindTopic>;+ readonly briefs: GoalBriefService;+ buildTaskAcceptanceRequirement: Bound<typeof buildTaskAcceptanceRequirement>;+ buildTaskInstruction: Bound<typeof buildTaskInstruction>;+ close: Bound<typeof close>;+ collectAcceptances: Bound<typeof collectAcceptances>;+ collectAssignees: Bound<typeof collectAssignees>;+ collectDeliveredAt: Bound<typeof collectDeliveredAt>;+ collectRolloutGate: Bound<typeof collectRolloutGate>;+ collectRunHeartbeats: Bound<typeof collectRunHeartbeats>;+ consumeCompletedTask: Bound<typeof consumeCompletedTask>;+ readonly coordinatorGraph: GoalGraphModel;+ create: Bound<typeof create>;+ createFromConversation: Bound<typeof createFromConversation>;+ createResponsibleTask: Bound<typeof createResponsibleTask>;+ readonly db: LobeChatDatabase;+ decide: Bound<typeof decide>;+ delete: Bound<typeof deleteGoal>;+ dispatchGoalReport: Bound<typeof dispatchGoalReport>;+ dispatchWork: Bound<typeof dispatchWork>;+ ensureTaskWorkVersion: Bound<typeof ensureTaskWorkVersion>;+ evaluateBudget: Bound<typeof evaluateBudget>;+ evaluateMetricCriteria: Bound<typeof evaluateMetricCriteria>;+ followGoalAgent: Bound<typeof followGoalAgent>;+ gateOrTakeOver: Bound<typeof gateOrTakeOver>;+ readonly goalModel: GoalModel;+ goalOwnerTaskScope: Bound<typeof goalOwnerTaskScope>;+ graph: Bound<typeof graph>;+ graphAs: Bound<typeof graphAs>;+ readonly graphModel: GoalGraphModel;+ handPlanningToMainAgent: Bound<typeof handPlanningToMainAgent>;+ holdForMachineFailure: Bound<typeof holdForMachineFailure>;+ holdForOfflineDevice: Bound<typeof holdForOfflineDevice>;+ /** The same service, its reads and writes bound to `tx`. */+ inTransaction: (tx: LobeChatDatabase) => GoalServiceContext;+ isBatchMember: Bound<typeof isBatchMember>;+ isParkedOnMeasuredGate: Bound<typeof isParkedOnMeasuredGate>;+ listEvents: Bound<typeof listEvents>;+ markRunLostToOfflineDevice: Bound<typeof markRunLostToOfflineDevice>;+ openFailureDecision: Bound<typeof openFailureDecision>;+ openFailureDecisionLocked: Bound<typeof openFailureDecisionLocked>;+ openPatternBreakGate: Bound<typeof openPatternBreakGate>;+ pause: Bound<typeof pause>;+ pendingClarifications: Bound<typeof pendingClarifications>;+ pendingForIsland: Bound<typeof pendingForIsland>;+ planDecomposition: Bound<typeof planDecomposition>;+ planMachineRecoveryFor: Bound<typeof planMachineRecoveryFor>;+ readRunDevicePresence: Bound<typeof readRunDevicePresence>;+ reassignUnfinishedTasks: Bound<typeof reassignUnfinishedTasks>;+ recordObservation: Bound<typeof recordObservation>;+ recoverAbandonedTask: Bound<typeof recoverAbandonedTask>;+ recoverAfterVerification: Bound<typeof recoverAfterVerification>;+ recoverLostRun: Bound<typeof recoverLostRun>;+ readonly releaseReview: GoalReleaseReview;+ reopenForChanges: Bound<typeof reopenForChanges>;+ reopenIfMeasurementCleared: Bound<typeof reopenIfMeasurementCleared>;+ requestSignOff: Bound<typeof requestSignOff>;+ requireGraph: Bound<typeof requireGraph>;+ resolveSpend: Bound<typeof resolveSpend>;+ resolveTaskAssignee: Bound<typeof resolveTaskAssignee>;+ resolveTopicRun: Bound<typeof resolveTopicRun>;+ restart: Bound<typeof restart>;+ restartRolloutLoop: Bound<typeof restartRolloutLoop>;+ resume: Bound<typeof resume>;+ resumeAbandonedTaskRecovery: Bound<typeof resumeAbandonedTaskRecovery>;+ retireNodes: Bound<typeof retireNodes>;+ setAcceptanceCriteria: Bound<typeof setAcceptanceCriteria>;+ setAgent: Bound<typeof setAgent>;+ setBudget: Bound<typeof setBudget>;+ setMetricCriteria: Bound<typeof setMetricCriteria>;+ setPauseReason: Bound<typeof setPauseReason>;+ setTaskAgent: Bound<typeof setTaskAgent>;+ settleTerminalAcceptance: Bound<typeof settleTerminalAcceptance>;+ status: Bound<typeof status>;+ stopFencedTasks: Bound<typeof stopFencedTasks>;+ readonly taskModel: TaskModel;+ readonly taskService: TaskService;+ readonly taskTopicModel: TaskTopicModel;+ tick: Bound<typeof tick>;+ tickOnce: Bound<typeof tickOnce>;+ transitionStatus: Bound<typeof transitionStatus>;+ updateRequirement: Bound<typeof updateRequirement>;+ readonly userId: string;+ waitForDevice: Bound<typeof waitForDevice>;+ waitForQuotaReset: Bound<typeof waitForQuotaReset>;+ readonly workModel: WorkModel;+ readonly workspaceId: string | undefined;+}diff --git a/apps/server/src/services/goal/GoalService/utils.ts b/apps/server/src/services/goal/GoalService/utils.tsnew file mode 100644index 00000000000..93f42357086--- /dev/null+++ b/apps/server/src/services/goal/GoalService/utils.ts@@ -0,0 +1,12 @@+import type { GoalItem } from '@lobechat/types';+import debug from 'debug';++/** Ends a person reached, or the coordinator's verdict of success: nothing reopens these but `resume`. */+export const GOAL_ENDED_STATUSES = new Set<string>(['achieved', 'canceled']);++/** Why a decomposition did or did not become a batch: DEBUG=lobe-server:goal-rollout. */+export const log = debug('lobe-server:goal-rollout');++/** Who does the goal's Tasks: its dedicated executor, else the goal agent itself. */+export const goalTaskAgentId = (goal: Pick<GoalItem, 'agentId' | 'config'>) =>+ goal.config?.taskAgentId ?? goal.agentId ?? undefined;diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsdeleted file mode 100644index 875a3b08be0..00000000000--- a/apps/server/src/services/goal/index.test.ts+++ /dev/null@@ -1,5995 +0,0 @@-// @vitest-environment node-import {- DEVICE_OFFLINE_RUN_STATUS,- GOAL_BATCH_ASSAY_TITLE,- GOAL_COORDINATOR_ACTOR_ID,- GOAL_MACHINE_GATE_TITLE,- QUOTA_LIMITED_RUN_STATUS,-} from '@lobechat/const/goal';-import type { ChatTopicMetadata } from '@lobechat/types';-import * as goalGraphUtils from '@lobechat/utils/goalGraph';-import { and, eq, sql } from 'drizzle-orm';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { getTestDB } from '@/database/core/getTestDB';-import { AcceptanceModel } from '@/database/models/acceptance';-import { AgentOperationModel } from '@/database/models/agentOperation';-import { ExpertiseModel } from '@/database/models/expertise';-import { GoalModel } from '@/database/models/goal';-import { GoalGraphModel } from '@/database/models/goalGraph';-import { MetricModel } from '@/database/models/metric';-import { TaskModel } from '@/database/models/task';-import { TaskTopicModel } from '@/database/models/taskTopic';-import { WorkModel } from '@/database/models/work';-import {- acceptances,- agentOperations,- agents,- briefs,- documents,- goalEdges,- goalEvents,- goalNodeDecisions,- goalNodes,- goals,- metricPoints,- metrics,- projects,- tasks,- taskTopics,- topics,- users,- workspaces,-} from '@/database/schemas';-import type { LobeChatDatabase } from '@/database/type';-import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';-import { AiAgentService } from '@/server/services/aiAgent';--import { deviceGateway } from '../deviceGateway';-import { TaskService } from '../task';-import { TaskRunnerService } from '../taskRunner';-import { UserSkillService } from '../userSkill';-import { VerifyPlanGeneratorService } from '../verify/planGenerator';-import { GoalCriteriaGeneratorService } from './criteriaGenerator';-import {- LEASE_EXPIRED_ERROR,- VERIFICATION_ERRORED_ERROR,- VERIFICATION_FAILED_ERROR,-} from './decideNextMove';-import { GoalExplorationPlanner } from './explorationPlanner';-import { GoalService } from './index';-import { MAX_QUOTA_RETRIES } from './machineRecovery';-import { DEVICE_OFFLINE_GATE_REASON, VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';-import * as scheduler from './scheduler';-import { LocalGoalScheduler } from './scheduler/impls';-import { uncoveredAxisValues } from './spec';-import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';-import { approveRelease } from './testUtils';-import type { GoalTickObservation } from './traceObservation';--const serverDB: LobeChatDatabase = await getTestDB();-const userId = 'goal-service-test-user';--beforeEach(async () => {- await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();-});--afterEach(async () => {- vi.restoreAllMocks();- // PGlite does not consistently order the nested user -> goal -> graph- // cascades, so clear graph leaves explicitly before their owned roots.- await serverDB.delete(goalNodeDecisions);- await serverDB.delete(goalEdges);- await serverDB.delete(goalEvents);- await serverDB.delete(goalNodes);- await serverDB.delete(goals);- await serverDB.delete(metricPoints);- await serverDB.delete(metrics);- await serverDB.delete(acceptances);- await serverDB.delete(agentOperations);- // A project holds its coordinator agent; it goes before the agents do.- await serverDB.delete(projects);- await serverDB.delete(taskTopics);- await serverDB.delete(topics);- await serverDB.delete(tasks);- await serverDB.delete(agents);- await serverDB.delete(users);-});--describe('GoalService', () => {- it('supervises every Goal it creates, even when the caller omits the policy', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Supervised by default' });- expect(graph.goal.config?.supervision).toMatchObject({ enabled: true });- });-- it('keeps the caller incident cap while forcing supervision on', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { supervision: { enabled: true, maxIncidents: 4 } },- title: 'Capped supervision',- });- expect(graph.goal.config?.supervision).toEqual({ enabled: true, maxIncidents: 4 });- });-- it('rejects a caller that tries to create an unsupervised Goal', async () => {- const service = new GoalService(serverDB, userId);- await expect(- service.create({ config: { supervision: { enabled: false } }, title: 'No supervision' }),- ).rejects.toThrow('Supervision is required for every goal and cannot be disabled');- });-- it('explores after result settlement and dispatches the new graph node through the ordinary Task path', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- title: 'Explore',- config: { exploration: { instruction: 'Compare evidence', maxExperiments: 3 } },- });- const parent = graph.nodes.find((node) => node.kind === 'task')!;- await serverDB.update(goals).set({ status: 'running' }).where(eq(goals.id, graph.goal.id));- await serverDB.update(goalNodes).set({ status: 'resolved' }).where(eq(goalNodes.id, parent.id));- const planner = vi.spyOn(GoalExplorationPlanner.prototype, 'plan').mockResolvedValue({- action: 'expand',- parentNodeId: graph.nodes.find((node) => node.kind === 'experiment')!.id,- title: 'Alternative',- instruction: 'Improve baseline',- reason: 'Try a new direction',- });- const expanded = await service.tick(graph.goal.id);- expect(expanded).toMatchObject({ outcome: 'advanced', message: 'Try a new direction' });- expect(planner).toHaveBeenCalledOnce();- const created = await service.tick(graph.goal.id);- expect(created.outcome).toBe('advanced');- expect(created.nodeId).not.toBe(expanded.nodeId);- expect((await service.graph(graph.goal.id)).edges).toContainEqual(- expect.objectContaining({- sourceNodeId: expanded.nodeId,- targetNodeId: created.nodeId,- kind: 'contains',- }),- );- expect(created.taskId).toBeTruthy();- });-- it('pauses a failed exploration planner without creating a phantom experiment', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- title: 'Explore',- config: { exploration: { instruction: 'Compare evidence', maxExperiments: 3 } },- });- const parent = graph.nodes.find((node) => node.kind === 'task')!;- await serverDB.update(goals).set({ status: 'running' }).where(eq(goals.id, graph.goal.id));- await serverDB.update(goalNodes).set({ status: 'resolved' }).where(eq(goalNodes.id, parent.id));- vi.spyOn(GoalExplorationPlanner.prototype, 'plan').mockRejectedValue(- new Error('provider unavailable'),- );- expect(await service.tick(graph.goal.id)).toMatchObject({ outcome: 'no_progress' });- const after = await service.graph(graph.goal.id);- expect(after.goal.status).toBe('paused');- expect(after.nodes.filter((node) => node.kind === 'task')).toHaveLength(1);- });-- it('resumes an exhausted exploration only after increasing its cap, preserving explicit user pause', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- title: 'Explore',- config: { exploration: { instruction: 'Compare evidence', maxExperiments: 1 } },- });- const parent = graph.nodes.find((node) => node.kind === 'task')!;- await serverDB.update(goals).set({ status: 'running' }).where(eq(goals.id, graph.goal.id));- await serverDB.update(goalNodes).set({ status: 'resolved' }).where(eq(goalNodes.id, parent.id));- vi.spyOn(GoalExplorationPlanner.prototype, 'plan').mockResolvedValue({- action: 'expand',- parentNodeId: parent.id,- title: 'Alternative',- instruction: 'Improve baseline',- reason: 'Still insufficient',- });- await service.tick(graph.goal.id);- expect((await service.setBudget(graph.goal.id, { maxExperiments: 1 })).status).toBe('paused');- expect((await service.setBudget(graph.goal.id, { maxExperiments: 2 })).status).toBe('running');- await service.pause(graph.goal.id);- expect((await service.setBudget(graph.goal.id, { maxExperiments: 3 })).status).toBe('paused');- });-- it('passes the selected older experiment result into the actual child Task instruction', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- title: 'Text exploration',- config: { exploration: { instruction: 'Compare alternatives', maxExperiments: 3 } },- });- const graphModel = new GoalGraphModel(serverDB, userId);- const parent = graph.nodes.find((node) => node.kind === 'task')!;- await serverDB.update(goalNodes).set({ status: 'resolved' }).where(eq(goalNodes.id, parent.id));- const finding = await graphModel.createNode(graph.goal.id, {- kind: 'finding',- title: 'Baseline result',- description: 'HISTORICAL_EVIDENCE_731: candidate A scored 7.',- });- await graphModel.createEdge(graph.goal.id, parent.id, finding!.id, 'produces');- await graphModel.createNode(graph.goal.id, {- kind: 'task',- title: 'Newer alternative',- status: 'resolved',- });- const child = await graphModel.createNode(graph.goal.id, {- kind: 'task',- title: 'Revisit baseline',- description: 'Try changing A',- });- await graphModel.createEdge(graph.goal.id, child!.id, parent.id, 'derived_from');- const created = await service.tick(graph.goal.id);- const dispatched = await new TaskModel(serverDB, userId).findById(created.taskId!);- expect(dispatched?.instruction).toContain(parent.id);- expect(dispatched?.instruction).toContain('HISTORICAL_EVIDENCE_731: candidate A scored 7.');- expect(dispatched?.instruction).toContain('Try changing A');- });-- it('persists structured criteria on create and records their ids on the goal config', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- criteria: [- { description: 'Runs end to end locally', title: 'Local run works' },- { instruction: 'Check README covers install and run', title: 'Docs are complete' },- ],- title: 'Structured goal',- tasks: ['Only task'],- });-- const criteriaIds = graph.goal.config?.acceptance?.criteriaIds ?? [];- expect(criteriaIds).toHaveLength(2);-- const rows = await serverDB.query.verifyCriteria.findMany();- const byId = new Map(rows.map((row) => [row.id, row]));- expect(byId.get(criteriaIds[0])?.title).toBe('Local run works');- expect(byId.get(criteriaIds[1])?.title).toBe('Docs are complete');- // the how-to-judge instruction landed in a linked document- expect(byId.get(criteriaIds[1])?.documentId).toBeTruthy();- });-- it('persists the reviewed goal document verbatim when structured criteria are supplied', async () => {- const service = new GoalService(serverDB, userId);- const instruction = 'ๅฐๅๅ ฌไฝ้ชๆๅๅฐๅฏไบคไปๆฐดๅนณ๏ผๆฏๆ PPTใXLSXใWord ็ๅๅปบๅๅฎๅไฟฎๆนใ';- const graph = await service.create({- criteria: [{ instruction: 'ๆๅผๅนถ็ผ่พๆ็ปๆไปถ', title: 'ไธ็ฑปๅๅ ฌๆๆกฃ็ซฏๅฐ็ซฏๅฏ็จ' }],- problemDescription: instruction,- requirement: instruction,- tasks: ['Only task'],- title: 'ๅๅ ฌไฝ้ช',- });-- const persisted = await service.graph(graph.goal.id);- expect(persisted.goal.requirement).toBe(instruction);- expect(persisted.nodes.find((node) => node.kind === 'problem')?.description).toBe(instruction);- expect(persisted.goal.config?.acceptance?.criteriaIds).toHaveLength(1);- });-- it('rebinding criteria also updates the dispatched terminal acceptance task', async () => {- // Editing the standard after the terminal Goal-acceptance Task exists must- // not leave that Task's Acceptance gating on the stale id list.- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- criteria: [{ title: 'Original criterion' }],- requirement: 'Deliver with evidence',- title: 'Rebind criteria goal',- tasks: ['Only task'],- });-- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'completed');- await service.tick(graph.goal.id); // synthesize finding- await service.tick(graph.goal.id); // create acceptance task- const acceptanceTaskCreated = await service.tick(graph.goal.id); // dispatch it- expect(acceptanceTaskCreated.taskId).toBeDefined();-- const [replacementId] = await new VerifyPlanGeneratorService(- serverDB,- userId,- ).createCriteriaFromDrafts([- { onFail: 'manual', required: true, title: 'Replacement criterion', verifierType: 'agent' },- ]);- await service.setAcceptanceCriteria(graph.goal.id, [replacementId]);-- const goal = (await service.graph(graph.goal.id)).goal;- expect(goal.config?.acceptance?.criteriaIds).toEqual([replacementId]);- const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(- 'task',- acceptanceTaskCreated.taskId!,- );- expect(acceptance?.config?.verifyCriteriaIds).toEqual([replacementId]);- });-- it.each([- { action: 'verify', managerEnabled: true },- { action: 'verify', managerEnabled: false },- { action: 'tasks', managerEnabled: true },- ] as const)(- 'scopes the handoff to manager=$managerEnabled action=$action',- async ({ action, managerEnabled }) => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const requirement = 'Deliver the original result with independently inspectable evidence';- const handoff =- 'Clarify that zero calls means zero additional predictions, not zero LLM use.';- const graph = await service.create({- criteria: [{ title: 'Original evidence criterion' }],- requirement,- tasks: ['Prepare result'],- title: 'Handoff',- });- const prepared = await service.tick(graph.goal.id);- await taskModel.updateStatus(prepared.taskId!, 'completed');- await service.tick(graph.goal.id);- const originalConfig = (await service.graph(graph.goal.id)).goal.config;- await serverDB- .update(goals)- .set({- config: {- ...originalConfig,- manager: managerEnabled ? {} : undefined,- managerState: {- consumed: true,- readyForAcceptance: true,- snapshot: 'settled',- startedAt: new Date().toISOString(),- submitted: { action, reason: handoff },- token: 'verified-turn',- topicId: 'management-topic',- turns: 1,- },- },- })- .where(eq(goals.id, graph.goal.id));-- await service.tick(graph.goal.id);- const finalTask = await service.tick(graph.goal.id);- const task = await taskModel.findById(finalTask.taskId!);-- if (managerEnabled && action === 'verify') {- expect(task?.instruction).toContain(handoff);- expect(task?.instruction).toContain('context only, not acceptance criteria');- } else {- expect(task?.instruction).not.toContain(handoff);- }- const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(- 'task',- finalTask.taskId!,- );- expect(acceptance?.requirement).toContain(requirement);- expect(acceptance?.config?.verifyCriteriaIds).toEqual(- originalConfig?.acceptance?.criteriaIds,- );- expect(acceptance?.config?.verifyCriteriaIds).toHaveLength(1);- expect((await service.graph(graph.goal.id)).goal.requirement).toBe(requirement);- },- );-- it('creates only one responsible task when ticks race on the same task node', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Single owner task'], title: 'Concurrent goal' });-- const results = await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);- const current = await service.graph(graph.goal.id);- const taskRows = await serverDB.select().from(tasks);-- expect(results.filter((result) => result.outcome === 'advanced')).toHaveLength(1);- expect(taskRows).toHaveLength(1);- expect(current.nodes.find((node) => node.kind === 'task')?.taskId).toBe(taskRows[0].id);- expect(current.workVersions).toHaveLength(1);- });-- it('starts the bound Task once when advances race on dispatch', async () => {- // Overlapping advances (an event hook, a manual nudge, the sweep) both read- // the task as backlog; without an atomic claim both would call runTask and- // the user would pay for the same Task twice.- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockImplementation(async ({ taskId }) => ({ taskId }) as never);- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Only run once'], title: 'Raced dispatch' });- await service.tick(graph.goal.id);-- const results = await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);-- expect(runSpy).toHaveBeenCalledTimes(1);- expect(results.filter((result) => result.message.startsWith('Started task'))).toHaveLength(1);- });-- it('retries a failed verification once when advances race on recovery', async () => {- // The dispatch claim only covers starting a backlog Task; the automatic- // retry path spawns its own run, so without the same claim two overlapping- // advances would each pay for an attempt.- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockImplementation(async ({ taskId }) => ({ taskId }) as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 3 } },- title: 'Raced recovery',- tasks: ['Retry me once'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'paused', {- error: 'Delivery did not pass verification.',- });- runSpy.mockClear();-- await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);-- expect(runSpy).toHaveBeenCalledTimes(1);- });-- it.each([LEASE_EXPIRED_ERROR, VERIFICATION_FAILED_ERROR])(- 'does not dispatch recovery for an overdue goal with %s',- async (error) => {- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { schedule: { deadline: new Date(Date.now() - 1000).toISOString() } },- title: `Overdue recovery ${error}`,- tasks: ['Do not retry'],- });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'paused', { error });- runSpy.mockClear();-- const stopped = await service.tick(graph.goal.id);-- expect(runSpy).not.toHaveBeenCalled();- expect(stopped).toMatchObject({ outcome: 'no_progress' });- expect(stopped.message).toContain('Deadline passed');- },- );-- it.each([- [LEASE_EXPIRED_ERROR, 'completed'],- [LEASE_EXPIRED_ERROR, 'failed'],- [VERIFICATION_ERRORED_ERROR, 'completed'],- [VERIFICATION_ERRORED_ERROR, 'canceled'],- ])('does not restart a Task settled during recovery (%s โ %s)', async (error, settledAs) => {- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- title: `Settled during recovery ${error} ${settledAs}`,- tasks: ['Do not restart'],- });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'paused', { error });- // The advance routed here holding the paused row; a person settled the Task- // before the claim, which is the row the coordinator now reads.- const stale = (await taskModel.findById(created.taskId!))!;- await taskModel.updateStatus(created.taskId!, settledAs, { error: null });- runSpy.mockClear();-- const recovery = await new TaskRecoveryCoordinator(serverDB, userId).recover({- goal: (await service.graph(graph.goal.id)).goal,- task: stale,- });-- expect(recovery.outcome).toBe('settled');- expect(runSpy).not.toHaveBeenCalled();- expect((await taskModel.findById(created.taskId!))?.status).toBe(settledAs);- });-- it.each([LEASE_EXPIRED_ERROR, VERIFICATION_ERRORED_ERROR])(- 'does not start a recovery run once the goal is fenced for closing (%s)',- async (error) => {- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ title: `Fenced recovery ${error}`, tasks: ['Stop'] });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'paused', { error });- // The tick decided on a running goal; `close` then paused it under the- // goal row lock before scanning live runs.- const decidedOn = (await service.graph(graph.goal.id)).goal;- const task = (await taskModel.findById(created.taskId!))!;- await service.pause(graph.goal.id);- runSpy.mockClear();-- const recovery = await new TaskRecoveryCoordinator(serverDB, userId).recover({- goal: decidedOn,- task,- });-- expect(recovery.outcome).toBe('goal-stopped');- expect(runSpy).not.toHaveBeenCalled();- expect((await taskModel.findById(created.taskId!))?.status).toBe('paused');- expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');- },- );-- it('does not restart a Task a person paused themselves', async () => {- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- title: 'Actor paused during recovery',- tasks: ['Do not restart'],- });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'paused', { error: VERIFICATION_ERRORED_ERROR });- // A manual round trip keeps the routing error, because the status update replaces- // it only when a new one is supplied, so the final pause is the person's.- const taskService = new TaskService(serverDB, userId);- await taskService.updateStatus({ id: created.taskId!, status: 'failed' }, { userId });- await taskService.updateStatus({ id: created.taskId!, status: 'paused' }, { userId });- const stale = (await taskModel.findById(created.taskId!))!;- runSpy.mockClear();-- const recovery = await new TaskRecoveryCoordinator(serverDB, userId).recover({- goal: (await service.graph(graph.goal.id)).goal,- task: stale,- });-- expect(recovery.outcome).toBe('settled');- expect(runSpy).not.toHaveBeenCalled();- expect((await taskModel.findById(created.taskId!))?.status).toBe('paused');- });-- it('hands back a dispatch claim whose worker died before the run existed', async () => {- // The claim is taken just before `runTask` creates the topic. If the worker- // dies in that sliver the task is `running` with no operation to reclaim,- // and every later advance would report `waiting_external` forever.- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockRejectedValue(new Error('worker died'));- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Start me'], title: 'Orphaned claim' });- const created = await service.tick(graph.goal.id);-- // The claim survives the crash: put the row back where a dead worker left it.- await expect(service.tick(graph.goal.id)).rejects.toThrow('worker died');- await taskModel.updateStatus(created.taskId!, 'running');- await serverDB- .update(tasks)- .set({ updatedAt: new Date(Date.now() - 60 * 60 * 1000) })- .where(eq(tasks.id, created.taskId!));-- const released = await service.tick(graph.goal.id);-- expect(released.outcome).toBe('advanced');- expect((await taskModel.findById(created.taskId!))?.status).toBe('backlog');- runSpy.mockRestore();- });-- it('does not re-dispatch a delivered Task while verification is still judging', async () => {- // A verify-bound Task keeps its task `running` with a completed topic until- // the verify run settles, and that judgment routinely outlives the- // operation lease. Treating the window as a dead claim released the task- // back to backlog, and the next advance paid for a ghost attempt that the- // verify settle path then canceled.- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { operationLeaseTimeoutMs: 60_000 } },- title: 'Deliveries wait for verification',- tasks: ['Deliver and wait'],- });- const created = await service.tick(graph.goal.id);- await serverDB.insert(taskTopics).values({- operationId: 'op-delivered',- seq: 1,- status: 'completed',- taskId: created.taskId!,- userId,- });- await taskModel.updateStatus(created.taskId!, 'running');- await serverDB- .update(tasks)- .set({ updatedAt: new Date(Date.now() - 10 * 60 * 1000) })- .where(eq(tasks.id, created.taskId!));-- const waiting = await service.tick(graph.goal.id);-- expect(waiting).toMatchObject({- message: expect.stringContaining('waiting for verification'),- outcome: 'waiting_external',- taskId: created.taskId,- });- expect((await taskModel.findById(created.taskId!))?.status).toBe('running');- expect(runSpy).not.toHaveBeenCalled();- });-- it('reclaims a delivered Task once the verification grace window lapses', async () => {- // The hold-off above cannot be unconditional: a verify run that died- // silently would otherwise strand the goal forever, which is exactly the- // failure mode the sweep exists to break.- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { operationLeaseTimeoutMs: 60_000 } },- title: 'Dead verification is reclaimed',- tasks: ['Deliver into silence'],- });- const created = await service.tick(graph.goal.id);- await serverDB.insert(taskTopics).values({- createdAt: new Date(Date.now() - VERIFY_SETTLE_GRACE_MS - 60_000),- operationId: 'op-delivered-stale',- seq: 1,- status: 'completed',- taskId: created.taskId!,- userId,- });- await taskModel.updateStatus(created.taskId!, 'running');- await serverDB- .update(tasks)- .set({ updatedAt: new Date(Date.now() - 10 * 60 * 1000) })- .where(eq(tasks.id, created.taskId!));-- const released = await service.tick(graph.goal.id);-- expect(released.outcome).toBe('advanced');- expect((await taskModel.findById(created.taskId!))?.status).toBe('backlog');- });-- it('synthesizes the finding from the delivered topic, not a canceled retry', async () => {- // When verification accepts a delivery, the settle path cancels the ghost- // retry it superseded โ leaving the canceled, handoff-less topic as the- // newest row. Reading blindly by seq produced findings titled- // "Completed: <task>" with no description.- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Deliver me'], title: 'Consume the delivery' });- const created = await service.tick(graph.goal.id);- await serverDB.insert(taskTopics).values([- {- handoff: {- content: 'Delivered content with the full run summary.',- summary: 'Delivered summary',- title: 'Delivered title',- },- operationId: 'op-delivered',- seq: 1,- status: 'completed',- taskId: created.taskId!,- userId,- },- {- operationId: 'op-ghost-retry',- seq: 2,- status: 'canceled',- taskId: created.taskId!,- userId,- },- ]);- await taskModel.updateStatus(created.taskId!, 'completed');-- await service.tick(graph.goal.id);-- const finding = (await service.graph(graph.goal.id)).nodes.find(- (node) => node.kind === 'finding',- );- expect(finding).toMatchObject({- description: 'Delivered content with the full run summary.',- title: 'Delivered title',- });- });-- it('links what the task delivered to its node, and skips the task Work itself', async () => {- // The deliverable used to survive only as a URL inside the finding's prose:- // the graph recorded that a task finished but not what came out of it.- 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: 'Harvest deliverables' });- const created = await service.tick(graph.goal.id);- await serverDB.insert(taskTopics).values({- handoff: { summary: 'Delivered', title: 'Delivered title' },- operationId: 'op-delivered',- seq: 1,- status: 'completed',- taskId: created.taskId!,- userId,- });- await workModel.registerExternal({- changeType: 'created',- identifier: 'ENG-7',- resourceId: 'lobehub/lobehub#7',- resourceType: 'github_issue',- rootOperationId: 'op-delivered',- title: 'The delivered issue',- toolIdentifier: 'lobe-github',- toolName: 'createIssue',- });- await taskModel.updateStatus(created.taskId!, 'completed');-- await service.tick(graph.goal.id);-- const snapshot = await service.graph(graph.goal.id);- const linked = snapshot.workVersions.filter((link) => link.nodeId === created.nodeId);- expect(linked.some((link) => link.work?.title === 'The delivered issue')).toBe(true);- // The responsible task's own Work is still linked โ it is the execution- // container, and the client is what filters it out of the deliverable list.- expect(linked.some((link) => link.work?.type === 'task')).toBe(true);- });-- it('re-settling a task does not duplicate its deliverable links', async () => {- 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: 'Idempotent harvest' });- const created = await service.tick(graph.goal.id);- await serverDB.insert(taskTopics).values({- handoff: { summary: 'Delivered', title: 'Delivered title' },- operationId: 'op-delivered',- seq: 1,- status: 'completed',- taskId: created.taskId!,- userId,- });- await workModel.registerExternal({- changeType: 'created',- resourceId: 'lobehub/lobehub#8',- resourceType: 'github_issue',- rootOperationId: 'op-delivered',- title: 'Delivered once',- toolIdentifier: 'lobe-github',- toolName: 'createIssue',- });- await taskModel.updateStatus(created.taskId!, 'completed');-- await service.tick(graph.goal.id);- await service.tick(graph.goal.id);-- const snapshot = await service.graph(graph.goal.id);- const delivered = snapshot.workVersions.filter(- (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 () => {- // The same shape a moment after the claim is just a run about to start.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockRejectedValue(new Error('worker died'));- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Start me'], title: 'Fresh claim' });- const created = await service.tick(graph.goal.id);- await expect(service.tick(graph.goal.id)).rejects.toThrow('worker died');- await taskModel.updateStatus(created.taskId!, 'running');-- const result = await service.tick(graph.goal.id);-- expect(result.outcome).toBe('waiting_external');- expect((await taskModel.findById(created.taskId!))?.status).toBe('running');- });-- it('reopens a goal its round budget stopped when the budget is raised', async () => {- // `tick` refuses to move a paused goal, so without this the queued advance- // returns straight away and the user has to find Resume as a second gesture.- const service = new GoalService(serverDB, userId);- const graph = await service.create({- maxRounds: 1,- title: 'Budget stopped',- tasks: ['Costs a round'],- });- const created = await service.tick(graph.goal.id);- await serverDB.insert(topics).values({ id: 'tpc_budget', userId });- await serverDB- .insert(taskTopics)- .values({ seq: 1, taskId: created.taskId!, topicId: 'tpc_budget', userId });-- const stopped = await service.tick(graph.goal.id);- expect(stopped.outcome).toBe('no_progress');- expect(stopped.message).toContain('Round budget reached');- expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');-- const raised = await service.setBudget(graph.goal.id, { maxRounds: 5 });-- expect(raised?.status).not.toBe('paused');- });-- describe('limits a goal was created with', () => {- // A goal its main Agent paused for running out of turns: resuming it alone- // pauses it again, which is what pushed agents into creating a copy of it.- const turnSpentGoal = async (service: GoalService) => {- const graph = await service.create({- tasks: ['Keep working'],- title: 'Out of main Agent turns',- });- const current = (await service.graph(graph.goal.id)).goal;- await serverDB- .update(goals)- .set({- config: {- ...current.config,- manager: { maxTurns: 2 },- managerState: { turns: 2 } as never,- },- status: 'paused',- })- .where(eq(goals.id, graph.goal.id));- return graph.goal.id;- };-- it('resumes a goal its main Agent paused once the turn cap is raised', async () => {- const service = new GoalService(serverDB, userId);- const goalId = await turnSpentGoal(service);-- const raised = await service.setBudget(goalId, { maxManagerTurns: 20 });-- expect(raised.config?.manager?.maxTurns).toBe(20);- expect(raised.status).not.toBe('paused');- });-- it('keeps a goal paused when the raised cap is still spent', async () => {- const service = new GoalService(serverDB, userId);- const goalId = await turnSpentGoal(service);-- expect((await service.setBudget(goalId, { maxManagerTurns: 2 })).status).toBe('paused');- });-- it('edits the execution limits without dropping the rest of the config', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 3, maxStepsPerRun: 200 } },- tasks: ['Run'],- title: 'Editable limits',- });-- const updated = await service.setBudget(graph.goal.id, {- maxAttemptsPerTask: 5,- maxConcurrentTasks: 1,- maxStepsPerRun: null,- });-- expect(updated.config?.maxConcurrentTasks).toBe(1);- expect(updated.config?.recovery).toMatchObject({- maxAttemptsPerTask: 5,- maxStepsPerRun: null,- });- });-- it('rejects a turn cap for a goal without a main Agent', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Run'], title: 'No main Agent' });-- await expect(service.setBudget(graph.goal.id, { maxManagerTurns: 20 })).rejects.toThrow(- 'Only a Goal with a main Agent has a turn budget',- );- });- });-- it('ships the spend the budget is enforced against with the graph', async () => {- // The header renders `spent / cap` as one fraction, so the number it shows- // has to be the number the coordinator will stop on โ not the goal list's- // subtree roll-up, which counts Tasks the graph's Tasks spawned.- const service = new GoalService(serverDB, userId);- const graph = await service.create({- maxTotalCost: 10,- tasks: ['Costs money'],- title: 'Spend',- });- const created = await service.tick(graph.goal.id);-- await serverDB- .insert(topics)- .values({ id: 'tpc_spend_1', totalCost: 6.4, totalTokens: 1200, userId });- await serverDB- .insert(taskTopics)- .values({ seq: 1, taskId: created.taskId!, topicId: 'tpc_spend_1', userId });- // A run that has not settled is a round with no cost yet.- await serverDB.insert(topics).values({ id: 'tpc_spend_2', userId });- await serverDB- .insert(taskTopics)- .values({ seq: 2, taskId: created.taskId!, topicId: 'tpc_spend_2', userId });-- const { spend } = await service.graph(graph.goal.id);-- expect(spend).toMatchObject({ runs: 2, totalCost: 6.4, totalTokens: 1200 });- // The cost panel lists WHERE the money went, so the same read carries the- // per-Task split rather than only the total the budget is checked against.- expect(spend?.byTask).toEqual([- {- runs: 2,- taskId: created.taskId!,- totalCost: 6.4,- totalInputTokens: 0,- totalOutputTokens: 0,- totalTokens: 1200,- },- ]);- });-- it('keeps an existing deadline when only the cost cap is edited', async () => {- // The budget panel sends one dimension at a time; an omitted deadline used- // to be written back as null, silently dropping a calendar budget someone- // set from a click that only meant to raise the dollars.- const service = new GoalService(serverDB, userId);- const deadline = new Date(Date.now() + 3_600_000).toISOString();- const graph = await service.create({- config: { schedule: { deadline } },- tasks: ['Bounded'],- title: 'Deadline keeper',- });-- const updated = await service.setBudget(graph.goal.id, { maxTotalCost: 25 });-- expect(updated?.config?.schedule?.deadline).toBe(deadline);- expect(Number(updated?.maxTotalCost)).toBe(25);- });-- it('leaves the round cap alone when only the cost cap is edited', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- maxRounds: 7,- tasks: ['Bounded'],- title: 'Round keeper',- });-- const updated = await service.setBudget(graph.goal.id, { maxTotalCost: 25 });-- expect(updated?.maxRounds).toBe(7);- });-- it('edits the standing requirement in place', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- requirement: 'ๅ็้ชๆถ',- tasks: ['A'],- title: 'Editable',- });-- const updated = await service.updateRequirement(graph.goal.id, 'ๆน่ฟ็้ชๆถๆ ๅ');-- expect(updated.requirement).toBe('ๆน่ฟ็้ชๆถๆ ๅ');- expect((await service.graph(graph.goal.id)).goal.requirement).toBe('ๆน่ฟ็้ชๆถๆ ๅ');- await expect(service.updateRequirement('goal_missing', 'x')).rejects.toThrow();- });-- it('names the agent each dispatched task node is assigned to', async () => {- await serverDB.insert(agents).values([{ id: 'agt_exec', slug: 'agt-exec', userId }]);- const service = new GoalService(serverDB, userId);- const graph = await service.create({- agentId: 'agt_exec',- tasks: ['Dispatched', 'Not yet'],- title: 'Who is on it',- });- const created = await service.tick(graph.goal.id);-- const read = await service.graph(graph.goal.id);- const dispatched = read.nodes.find((node) => node.taskId === created.taskId)!;-- // Only a node with a Task row has an assignee; the undispatched one has none.- expect(read.assignees).toEqual({ [dispatched.id]: 'agt_exec' });- });-- it('hands the goal and its unfinished tasks to a new agent', async () => {- await serverDB.insert(agents).values([- { id: 'agt_old', slug: 'agt-old', userId },- { id: 'agt_new', slug: 'agt-new', userId },- ]);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- agentId: 'agt_old',- tasks: ['Only task'],- title: 'Handover',- });- const created = await service.tick(graph.goal.id);- expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_old');-- const handed = await service.setAgent(graph.goal.id, 'agt_new');-- expect(handed.goal.agentId).toBe('agt_new');- expect(handed.reassignedTaskIds).toEqual([created.taskId]);- expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_new');-- // A finished task keeps the agent that did the work, and `goalOnly` limits- // the change to future coordinator-created tasks.- await taskModel.updateStatus(created.taskId!, 'completed');- const back = await service.setAgent(graph.goal.id, 'agt_old');- expect(back.reassignedTaskIds).toEqual([]);- expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_new');-- await expect(service.setAgent(graph.goal.id, 'agt_missing')).rejects.toThrow();- });-- it('falls back to the goal agent when the dedicated executor was deleted', async () => {- await serverDB.insert(agents).values([- { id: 'agt_lead_fallback', slug: 'agt-lead-fallback', userId },- { id: 'agt_gone_executor', slug: 'agt-gone-executor', userId },- ]);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- agentId: 'agt_lead_fallback',- config: { taskAgentId: 'agt_gone_executor' },- tasks: ['Only task'],- title: 'Executor deleted',- });- await serverDB.delete(agents).where(eq(agents.id, 'agt_gone_executor'));-- const created = await service.tick(graph.goal.id);-- expect(created.taskId).toBeTruthy();- expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_lead_fallback');- });-- it('writes only the executor slot, so a concurrent policy edit survives', async () => {- await serverDB.insert(agents).values([- { id: 'agt_policy_lead', slug: 'agt-policy-lead', userId },- { id: 'agt_policy_worker', slug: 'agt-policy-worker', userId },- ]);- const service = new GoalService(serverDB, userId);- const model = new GoalModel(serverDB, userId);- const graph = await service.create({ agentId: 'agt_policy_lead', title: 'Policy race' });- // setTaskAgent reads the row, then a budget edit lands before it writes.- const stale = (await model.findById(graph.goal.id))!;- await model.update(graph.goal.id, { config: { ...stale.config, maxConcurrentTasks: 5 } });- // `findById` is an instance arrow property, so spy on the service's own model.- const serviceModel = (service as unknown as { goalModel: GoalModel }).goalModel;- vi.spyOn(serviceModel, 'findById').mockResolvedValueOnce(stale);-- const result = await service.setTaskAgent(graph.goal.id, 'agt_policy_worker');-- expect(result.goal.config?.taskAgentId).toBe('agt_policy_worker');- expect(result.goal.config?.maxConcurrentTasks).toBe(5);- });-- it('moves supervision without moving the tasks a dedicated executor holds', async () => {- await serverDB.insert(agents).values([- { id: 'agt_supervisor', slug: 'agt-supervisor', userId },- { id: 'agt_executor', slug: 'agt-executor', userId },- { id: 'agt_next_supervisor', slug: 'agt-next-supervisor', userId },- ]);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- agentId: 'agt_supervisor',- config: { taskAgentId: 'agt_executor' },- tasks: ['Only task'],- title: 'Split roles',- });- expect(graph.goal.agentId).toBe('agt_supervisor');- const created = await service.tick(graph.goal.id);- expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_executor');-- const handed = await service.setAgent(graph.goal.id, 'agt_next_supervisor');-- expect(handed.goal.agentId).toBe('agt_next_supervisor');- expect(handed.goal.config?.taskAgentId).toBe('agt_executor');- expect(handed.reassignedTaskIds).toEqual([]);- expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_executor');- });-- it('routes tasks to a dedicated executor and back to the goal agent', async () => {- await serverDB.insert(agents).values([- { id: 'agt_owner', slug: 'agt-owner', userId },- { id: 'agt_worker', slug: 'agt-worker', userId },- ]);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- agentId: 'agt_owner',- tasks: ['Only task'],- title: 'Delegated',- });- const created = await service.tick(graph.goal.id);- expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_owner');-- const delegated = await service.setTaskAgent(graph.goal.id, 'agt_worker');- expect(delegated.goal.agentId).toBe('agt_owner');- expect(delegated.goal.config?.taskAgentId).toBe('agt_worker');- expect(delegated.reassignedTaskIds).toEqual([created.taskId]);- expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_worker');-- // Naming the goal agent clears the slot rather than duplicating it.- const back = await service.setTaskAgent(graph.goal.id, 'agt_owner');- expect(back.goal.config?.taskAgentId).toBeUndefined();- expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_owner');-- await expect(service.setTaskAgent(graph.goal.id, 'agt_missing')).rejects.toThrow();- });-- it('restarts unfinished tasks under a new agent and cancels the stale runs they hold', async () => {- const cancelSpy = vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();- await serverDB.insert(agents).values({ id: 'agt_restart', slug: 'agt-restart', userId });- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Stuck task'], title: 'Restartable' });- const created = await service.tick(graph.goal.id);- await serverDB.insert(topics).values({ id: 'tpc_restart', userId });- await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_restart', { seq: 1 });- await new TaskTopicModel(serverDB, userId).updateStatus(- created.taskId!,- 'tpc_restart',- 'running',- );- await taskModel.update(created.taskId!, { error: 'lease expired', status: 'running' });-- const result = await service.restart(graph.goal.id, { agentId: 'agt_restart' });-- expect(cancelSpy).toHaveBeenCalledWith('tpc_restart');- expect(result.goal.agentId).toBe('agt_restart');- expect(result.restartedTaskIds).toEqual([created.taskId]);- expect(await taskModel.findById(created.taskId!)).toMatchObject({- assigneeAgentId: 'agt_restart',- error: null,- status: 'backlog',- });-- // "Start over" on a parked goal must begin ticking again without a second- // Resume gesture.- await service.pause(graph.goal.id);- const resumed = await service.restart(graph.goal.id);- expect(resumed.goal.status).not.toBe('paused');- });-- it('closes a goal by hand, stops its live runs and stops the coordinator', async () => {- const cancelSpy = vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['First', 'Second'], title: 'Closable' });- const created = await service.tick(graph.goal.id);- await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });- await serverDB.insert(topics).values({ id: 'tpc_close', userId });- await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_close', { seq: 1 });- await new TaskTopicModel(serverDB, userId).updateStatus(- created.taskId!,- 'tpc_close',- 'running',- );-- const closed = await service.close(graph.goal.id, 'canceled');-- expect(closed.status).toBe('canceled');- expect(cancelSpy).toHaveBeenCalledWith('tpc_close');- // Back to backlog, not parked on a person, so a reopen runs it again.- expect((await new TaskModel(serverDB, userId).findById(created.taskId!))?.status).toBe(- 'backlog',- );- expect(await service.tick(graph.goal.id)).toMatchObject({ outcome: 'failed' });- const [closeEvent] = await serverDB- .select()- .from(goalEvents)- .where(eq(goalEvents.reason, 'canceled by user'));- // Filed under the person, not the coordinator.- expect(closeEvent).toMatchObject({ actorId: userId, eventType: 'rejected' });-- // A closed goal reopens through the ordinary resume.- expect((await service.resume(graph.goal.id)).status).toBe('running');- expect((await service.close(graph.goal.id, 'achieved')).status).toBe('achieved');- });-- it('fences new dispatch before interrupting the runs of a goal being closed', async () => {- // A tick overlapping the close must not claim another Task while the scan- // and cancellation are under way, so the goal stops reading `running` first.- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Runs'], title: 'Fenced' });- const created = await service.tick(graph.goal.id);- await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });- await serverDB.insert(topics).values({ id: 'tpc_fence', userId });- await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_fence', { seq: 1 });- await new TaskTopicModel(serverDB, userId).updateStatus(- created.taskId!,- 'tpc_fence',- 'running',- );- const statusDuringCancel: string[] = [];- vi.spyOn(TaskService.prototype, 'cancelTopic').mockImplementation(async () => {- const goal = await new GoalModel(serverDB, userId).findById(graph.goal.id);- statusDuringCancel.push(goal!.status);- });-- await service.close(graph.goal.id, 'canceled');-- expect(statusDuringCancel).toEqual(['paused']);- });-- it('refuses to close while a claimed run is still starting, so it can be stopped with confirmation', async () => {- // `dispatchWork` marks the Task running before `runTask` records the topic,- // so the close scan finds no run to cancel โ and a run nobody recorded- // cannot be interrupted with confirmation. The close waits for it instead.- const cancelSpy = vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Starting'], title: 'Claimed, not recorded' });- const created = await service.tick(graph.goal.id);- await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });-- await expect(service.close(graph.goal.id, 'canceled')).rejects.toMatchObject({- code: 'PRECONDITION_FAILED',- });-- expect(cancelSpy).not.toHaveBeenCalled();- // Fenced, so nothing new starts, and the claim is left for its run to record.- expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe('paused');- expect((await new TaskModel(serverDB, userId).findById(created.taskId!))?.status).toBe(- 'running',- );- });-- it('withdraws a claim whose startup died long ago and closes the goal', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Dead start'], title: 'Stale claim' });- const created = await service.tick(graph.goal.id);- await serverDB- .update(tasks)- .set({ status: 'running', updatedAt: new Date(Date.now() - 24 * 60 * 60 * 1000) })- .where(eq(tasks.id, created.taskId!));-- expect((await service.close(graph.goal.id, 'canceled')).status).toBe('canceled');- expect((await new TaskModel(serverDB, userId).findById(created.taskId!))?.status).toBe(- 'backlog',- );- });-- it('keeps a closed goal closed when a stale decision is answered', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Risky task'], title: 'Closed with a gate' });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });- await service.tick(graph.goal.id);- const [decision] = (await service.graph(graph.goal.id)).decisions;-- await service.close(graph.goal.id, 'canceled');-- // Another tab still showing the gate answers it.- await expect(service.decide(graph.goal.id, decision.id, 'retry')).rejects.toMatchObject({- code: 'CONFLICT',- });- expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe(- 'canceled',- );- });-- it('does not reopen a goal closed while a decision was being answered', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Risky task'], title: 'Closed mid-answer' });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });- await service.tick(graph.goal.id);- const [decision] = (await service.graph(graph.goal.id)).decisions;- // The close lands after the answer is written, before the status moves.- const graphModel = (service as unknown as { graphModel: GoalGraphModel }).graphModel;- const resolve = graphModel.resolveDecision;- vi.spyOn(graphModel, 'resolveDecision').mockImplementation(async (...args) => {- const resolved = await resolve(...args);- await new GoalService(serverDB, userId).close(graph.goal.id, 'canceled');- return resolved;- });-- await service.decide(graph.goal.id, decision.id, 'retry');-- expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe(- 'canceled',- );- });-- it('refuses to end a goal someone resumed while its runs were being interrupted', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Runs'], title: 'Resumed mid-close' });- const created = await service.tick(graph.goal.id);- await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });- await serverDB.insert(topics).values({ id: 'tpc_race', userId });- await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_race', { seq: 1 });- await new TaskTopicModel(serverDB, userId).updateStatus(created.taskId!, 'tpc_race', 'running');- // Another tab resumes the goal while the interruption pass is running.- vi.spyOn(TaskService.prototype, 'cancelTopic').mockImplementation(async () => {- await new GoalService(serverDB, userId).resume(graph.goal.id);- });-- await expect(service.close(graph.goal.id, 'canceled')).rejects.toMatchObject({- code: 'CONFLICT',- });- expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe('running');- });-- it('does not let a resume that read the goal before a close reopen it afterwards', async () => {- // The resume read the fenced `paused` goal; the close then committed the- // terminal status. The stale resume must not write `running` over it.- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Runs'], title: 'Resume after close' });- await service.pause(graph.goal.id);- const requireGraph = (service as unknown as { requireGraph: GoalService['graph'] })- .requireGraph;- vi.spyOn(service as any, 'requireGraph').mockImplementationOnce(async (id) => {- const snapshot = await requireGraph(id as string);- await new GoalService(serverDB, userId).close(graph.goal.id, 'canceled');- return snapshot;- });-- await expect(service.resume(graph.goal.id)).rejects.toMatchObject({ code: 'CONFLICT' });- expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe(- 'canceled',- );- // An explicit reopen of the ended goal still works.- expect((await service.resume(graph.goal.id)).status).toBe('running');- });-- it('keeps runs already stopped reopenable when a later interruption fails', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const topicModel = new TaskTopicModel(serverDB, userId);- const graph = await service.create({ tasks: ['First', 'Second'], title: 'Partial close' });- const [first, second] = graph.nodes.filter((node) => node.kind === 'task');- const taskIds: string[] = [];- for (const [index, node] of [first, second].entries()) {- const task = await new TaskService(serverDB, userId).createTask({- instruction: node.title,- name: node.title,- });- await new GoalGraphModel(serverDB, userId).bindTask(graph.goal.id, node.id, task.id);- await taskModel.update(task.id, { status: 'running' });- const topicId = `tpc_partial_${index}`;- await serverDB.insert(topics).values({ id: topicId, userId });- await topicModel.add(task.id, topicId, { seq: 1 });- await topicModel.updateStatus(task.id, topicId, 'running');- taskIds.push(task.id);- }- // The first interruption lands (the task reads `paused`, as cancelTopic- // leaves it); the second is unreachable.- let calls = 0;- vi.spyOn(TaskService.prototype, 'cancelTopic').mockImplementation(async (topicId) => {- calls += 1;- if (calls > 1) throw new Error('run unreachable');- const index = Number(topicId.at(-1));- await taskModel.update(taskIds[index], { status: 'paused' });- await topicModel.updateStatus(taskIds[index], topicId, 'canceled');- });-- await expect(service.close(graph.goal.id, 'canceled')).rejects.toMatchObject({- code: 'PRECONDITION_FAILED',- });- const stopped = (await taskModel.findByIds(taskIds)).filter(- (task) => task.status !== 'running',- );- expect(stopped).toHaveLength(1);- expect(stopped[0].status).toBe('backlog');- });-- describe('closing a goal with a main Agent turn in flight', () => {- const managedGoal = async (title: string) => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Managed'], title });- await new AgentOperationModel(serverDB, userId).recordStart({- operationId: `op-manager-${title}`,- });- await serverDB- .update(goals)- .set({- config: {- ...graph.goal.config,- manager: {},- managerState: {- operationId: `op-manager-${title}`,- startedAt: new Date().toISOString(),- token: 'turn',- topicId: 'management-topic',- turns: 1,- },- } as never,- })- .where(eq(goals.id, graph.goal.id));- return { goalId: graph.goal.id, service };- };-- it('interrupts the main Agent turn before ending the goal', async () => {- // The coordinator's own operation is not a graph Task topic, so the- // topic scan alone would leave it spending after the goal ended.- const { goalId, service } = await managedGoal('interrupted');- const interrupt = vi- .spyOn(AiAgentService.prototype, 'interruptTask')- .mockResolvedValue({ success: true } as never);-- expect((await service.close(goalId, 'achieved')).status).toBe('achieved');- expect(interrupt).toHaveBeenCalledWith(- expect.objectContaining({ operationId: 'op-manager-interrupted' }),- );- });-- it('refuses to end the goal when the interruption is not confirmed', async () => {- const { goalId, service } = await managedGoal('unconfirmed');- vi.spyOn(AiAgentService.prototype, 'interruptTask').mockResolvedValue({- deviceCancellationConfirmed: false,- success: true,- } as never);-- await expect(service.close(goalId, 'canceled')).rejects.toThrow(/not closed/);- // Still fenced so nothing new starts, but not claimed as ended.- expect((await new GoalModel(serverDB, userId).findById(goalId))?.status).toBe('paused');- });- });-- it('restarts a split-role goal under a new executor without replacing its supervisor', async () => {- vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();- await serverDB.insert(agents).values([- { id: 'agt_lead', slug: 'agt-lead', userId },- { id: 'agt_first_worker', slug: 'agt-first-worker', userId },- { id: 'agt_second_worker', slug: 'agt-second-worker', userId },- ]);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- agentId: 'agt_lead',- config: { taskAgentId: 'agt_first_worker' },- tasks: ['Stuck task'],- title: 'Restart split roles',- });- const created = await service.tick(graph.goal.id);-- const result = await service.restart(graph.goal.id, { agentId: 'agt_second_worker' });-- expect(result.goal.agentId).toBe('agt_lead');- expect(result.goal.config?.taskAgentId).toBe('agt_second_worker');- expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_second_worker');- });-- it('cancels the failure gate a restart supersedes so the goal starts moving again', async () => {- // A restarted task's pending recovery gate is answered by the restart- // itself. Left pending, it keeps winning the coordinator's- // pending-decision branch and the goal sits waiting_human with every task- // freshly reset.- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Risky task'], title: 'Restart clears gate' });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });- expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');-- const result = await service.restart(graph.goal.id);-- expect(result.restartedTaskIds).toEqual([created.taskId]);- const after = await service.graph(graph.goal.id);- expect(after.decisions[0].status).toBe('canceled');- // The freed coordinator dispatches the reset task instead of re-parking.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const next = await service.tick(graph.goal.id);- expect(next.outcome).not.toBe('waiting_human');- });-- it('retires a stray node only together with the unfinished tasks depending on it', async () => {- // A duplicated plan branch never gets a Task, so nothing else ever closes it- // and the goal can never reach acceptance.- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['First', 'Second', 'Keep'], title: 'Duplicates' });- const [first, second, keep] = ['First', 'Second', 'Keep'].map((title) =>- graph.nodes.find((node) => node.kind === 'task' && node.title === title)!,- );- await service.addEdge(graph.goal.id, second.id, first.id, 'depends_on');-- await expect(service.retireNodes(graph.goal.id, [first.id])).rejects.toThrow(second.id);-- const result = await service.retireNodes(graph.goal.id, [first.id, second.id], 'duplicate');-- expect(result.retiredNodeIds.sort()).toEqual([first.id, second.id].sort());- const after = await service.graph(graph.goal.id);- const status = (id: string) => after.nodes.find((node) => node.id === id)?.status;- expect(status(first.id)).toBe('retired');- expect(status(second.id)).toBe('retired');- expect(status(keep.id)).not.toBe('retired');- });-- it('retiring a dispatched node cancels its task and the gate parking the goal', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Canceled elsewhere'], title: 'Stray gate' });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Task canceled' });- expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');-- await service.retireNodes(graph.goal.id, [created.nodeId!]);-- expect((await taskModel.findById(created.taskId!))?.status).toBe('canceled');- const after = await service.graph(graph.goal.id);- expect(after.decisions[0].status).toBe('canceled');- expect(after.goal.status).toBe('running');- });-- it('retiring a node fences it against a coordinator still creating its task', async () => {- const service = new GoalService(serverDB, userId);- const graphModel = new GoalGraphModel(serverDB, userId);- const graph = await service.create({ tasks: ['Stray', 'Keep'], title: 'Retire race' });- const stray = graph.nodes.find((node) => node.kind === 'task' && node.title === 'Stray')!;- // A tick has claimed the node and is creating its Task when retirement lands.- expect(await graphModel.claimTaskNode(graph.goal.id, stray.id, new Date(0))).toBeDefined();-- await service.retireNodes(graph.goal.id, [stray.id]);-- const lateTask = await new TaskModel(serverDB, userId).create({ instruction: 'Late' });- expect(await graphModel.bindTask(graph.goal.id, stray.id, lateTask.id)).toBeUndefined();- const after = await service.graph(graph.goal.id);- expect(after.nodes.find((node) => node.id === stray.id)?.status).toBe('retired');- });-- it("stops a colleague's private task when a workspace owner retires its node", async () => {- // The coordinator runs as the goal's owner, so its Tasks can be private to- // that colleague. An owner retiring the node must still stop them โ reads- // under the owner's own visibility would silently miss them.- const workspaceId = 'goal-retire-private-ws';- const ownerId = 'goal-retire-private-owner';- await serverDB.insert(users).values({ id: ownerId }).onConflictDoNothing();- await serverDB- .insert(workspaces)- .values({ id: workspaceId, name: workspaceId, primaryOwnerId: ownerId, slug: workspaceId })- .onConflictDoNothing();- const colleague = new GoalService(serverDB, userId, workspaceId);- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const graph = await colleague.create({ tasks: ['Private', 'Keep'], title: 'Private retire' });- const created = await colleague.tick(graph.goal.id);- await serverDB- .update(tasks)- .set({ status: 'running', visibility: 'private' })- .where(eq(tasks.id, created.taskId!));- expect(- await new TaskModel(serverDB, ownerId, workspaceId).findById(created.taskId!),- ).toBeFalsy();-- await new GoalService(serverDB, ownerId, workspaceId).retireNodes(graph.goal.id, [- created.nodeId!,- ]);-- const [task] = await serverDB.select().from(tasks).where(eq(tasks.id, created.taskId!));- expect(task.status).toBe('canceled');- });-- it('cancels a running task before looking for its runs, fencing a run still being dispatched', async () => {- // A runner that already flipped the Task to `running` but has not recorded- // its topic yet is invisible to the run lookup. It checks the Task's status- // under the row lock before recording, so the cancellation must already be- // committed by the time retirement looks for runs to stop.- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Dispatching', 'Keep'], title: 'Fence runs' });- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'running');- const statusAtLookup: (string | undefined)[] = [];- const original = TaskTopicModel.prototype.findRunningByTaskIds;- vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockImplementation(async function (- this: TaskTopicModel,- ids: string[],- ) {- statusAtLookup.push((await taskModel.findById(created.taskId!))?.status);- return original.call(this, ids);- });-- await service.retireNodes(graph.goal.id, [created.nodeId!]);-- expect(statusAtLookup).toEqual(['canceled']);- expect((await taskModel.findById(created.taskId!))?.status).toBe('canceled');- });-- it('lets an interrupted retirement be finished by retrying it', async () => {- // The fence lands before the run is stopped; when stopping it cannot be- // confirmed the call fails with the node already retired. A retry must- // still stop the task instead of rejecting the node as terminal.- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Running', 'Keep'], title: 'Retry retire' });- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const created = await service.tick(graph.goal.id);- vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([- { taskId: created.taskId!, topicId: 'tpc_running' },- ] as never);- const cancelTopic = vi- .spyOn(TaskService.prototype, 'cancelTopic')- .mockRejectedValueOnce(new Error('interrupt not confirmed'))- .mockResolvedValue(undefined as never);-- await expect(service.retireNodes(graph.goal.id, [created.nodeId!])).rejects.toThrow(- 'interrupt not confirmed',- );- expect(- (await service.graph(graph.goal.id)).nodes.find((node) => node.id === created.nodeId)?.status,- ).toBe('retired');-- const retried = await service.retireNodes(graph.goal.id, [created.nodeId!]);-- expect(retried.retiredNodeIds).toEqual([created.nodeId]);- expect(cancelTopic).toHaveBeenCalledTimes(2);- expect((await taskModel.findById(created.taskId!))?.status).toBe('canceled');- });-- it('discards a stale tick outcome for a node retired while it ran', async () => {- const service = new GoalService(serverDB, userId);- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const graph = await service.create({ tasks: ['Stray', 'Keep'], title: 'Stale tick' });- const created = await service.tick(graph.goal.id);- // The coordinator loaded this snapshot before the retirement landed.- const stale = await service.graph(graph.goal.id);- await service.retireNodes(graph.goal.id, [created.nodeId!]);-- const result = await (service as any).consumeCompletedTask(- stale,- created.nodeId!,- created.taskId!,- );-- expect(result.outcome).toBe('no_progress');- const after = await service.graph(graph.goal.id);- expect(after.nodes.find((node) => node.id === created.nodeId)?.status).toBe('retired');- expect(after.nodes.some((node) => node.kind === 'finding')).toBe(false);- });-- it('reopens a goal parked by no_frontier once the blocking nodes are retired', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['A', 'B', 'Keep'], title: 'Deadlocked branch' });- const [a, b] = ['A', 'B'].map((title) =>- graph.nodes.find((node) => node.kind === 'task' && node.title === title)!,- );- const graphModel = new GoalGraphModel(serverDB, userId);- await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');- await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');- const keep = graph.nodes.find((node) => node.kind === 'task' && node.title === 'Keep')!;- await graphModel.updateNodeStatus(graph.goal.id, keep.id, 'resolved');- await service.tick(graph.goal.id); // deadlock โ no_frontier โ paused- expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');-- await service.retireNodes(graph.goal.id, [a.id, b.id]);-- expect((await service.graph(graph.goal.id)).goal.status).toBe('running');- });-- it('leaves a user-paused goal paused when nodes are retired', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['A', 'B'], title: 'Paused by a person' });- const [a, b] = graph.nodes.filter((node) => node.kind === 'task');- const graphModel = new GoalGraphModel(serverDB, userId);- await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');- await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');- await service.tick(graph.goal.id); // no_frontier park- await service.pause(graph.goal.id); // the person takes the pause over-- await service.retireNodes(graph.goal.id, [a.id, b.id]);-- expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');- });-- it('leaves a deliberately paused goal paused when its budget changes', async () => {- // Nothing distinguishes a user pause from a budget pause on the row, so the- // reopen is limited to goals whose budget was actually binding.- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Wait'], title: 'User paused' });- await service.pause(graph.goal.id);-- const updated = await service.setBudget(graph.goal.id, { maxTotalCost: 50 });-- expect(updated?.status).toBe('paused');- });-- it('refuses to delete a goal whose running Task cannot be stopped', async () => {- // Deleting anyway would remove the only surface that can stop an operation- // which keeps spending.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Runs on'], title: 'Unstoppable' });- const created = await service.tick(graph.goal.id);- await serverDB.insert(topics).values({ id: 'tpc_stuck', userId });- await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_stuck', { seq: 1 });- await new TaskTopicModel(serverDB, userId).updateStatus(- created.taskId!,- 'tpc_stuck',- 'running',- );- vi.spyOn(TaskService.prototype, 'cancelTopic').mockRejectedValue(new Error('gateway is down'));-- await expect(service.delete(graph.goal.id)).rejects.toThrow(/not deleted/);- expect(await service.graph(graph.goal.id)).toBeDefined();- });-- it('attaches seed tasks straight to the problem instead of wrapping each in an experiment', async () => {- // An experiment is a candidate answer under test. A caller-supplied seed is- // ordinary work, so it takes the same shape as a planned or manager-submitted- // Task: a `decomposes` edge from the problem, no answer container.- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Question', tasks: ['Seed work'] });- const question = graph.nodes.find((n) => n.kind === 'problem')!;- const task = graph.nodes.find((n) => n.kind === 'task')!;- expect(graph.goal.config?.exploration).toBeUndefined();- expect(graph.nodes.filter((n) => n.kind === 'experiment')).toHaveLength(0);- expect(graph.edges).toEqual([- expect.objectContaining({- kind: 'decomposes',- sourceNodeId: question.id,- targetNodeId: task.id,- }),- ]);- });-- it('seeds the exploration baseline inside an experiment container', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { exploration: { instruction: 'Compare evidence', maxExperiments: 3 } },- title: 'Explore',- });- const question = graph.nodes.find((n) => n.kind === 'problem')!;- const answer = graph.nodes.find((n) => n.kind === 'experiment')!;- const task = graph.nodes.find((n) => n.kind === 'task')!;- expect(answer.taskId).toBeNull();- expect(graph.edges).toEqual(- expect.arrayContaining([- expect.objectContaining({- kind: 'answers',- sourceNodeId: answer.id,- targetNodeId: question.id,- }),- expect.objectContaining({- kind: 'contains',- sourceNodeId: answer.id,- targetNodeId: task.id,- }),- ]),- );- });-- it('plans the decomposition when a goal has no tasks yet', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ ธๅฟ้ฎ้ข็ไธๅฅ่ฏ้่ฟฐ',- tasks: [- { dependsOn: [], hypothesis: null, instruction: 'ๆถ้ๅๅงๆๆ', title: 'ๆนๅA:ๆถ้' },- {- dependsOn: [0],- hypothesis: 'ๆๆจกๅ่็ฑปๆฏๆๆถ้ดๆๅบๆด่ฝๆด้ฒๆ นๅ ',- instruction: 'ๅๆๅนถ็ปผๅ็ป่ฎบ',- title: 'ๆนๅB:ๅๆ',- },- // Self and forward references are planner hallucinations โ dropped.- { dependsOn: [1, 2, 9], instruction: 'ๆฑ็ผๆ็ปๆฅๅ', title: 'ๆนๅC:ๆฑ็ผ' },- ],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({- problemDescription: '็จๆท็ๅ่ฏ',- requirement: 'ๅฎๆด้ๆฑไธ้ชๆถๆ ๅๅ จๆ',- title: 'Complex ask',- });- // The seeded graph carries the user's own words, not the contract blob.- expect(graph.nodes.find((n) => n.kind === 'problem')?.description).toBe('็จๆท็ๅ่ฏ');- expect(graph.nodes.filter((n) => n.kind === 'task')).toHaveLength(0);-- const result = await service.tick(graph.goal.id);-- expect(result.outcome).toBe('advanced');- const after = await service.graph(graph.goal.id);- expect(after.nodes.filter((n) => n.kind === 'task').map((n) => n.title)).toEqual([- 'ๆนๅA:ๆถ้',- 'ๆนๅB:ๅๆ',- 'ๆนๅC:ๆฑ็ผ',- ]);- const problem = after.nodes.find((n) => n.kind === 'problem')!;- expect(problem.description).toBe('ๆ ธๅฟ้ฎ้ข็ไธๅฅ่ฏ้่ฟฐ');-- // Only the direction the planner marked as a hypothesis becomes a candidate- // answer: one experiment answering the problem and containing that Task.- // The certain steps attach straight to the problem.- const byTitle = new Map(after.nodes.map((n) => [n.title, n.id]));- const experiments = after.nodes.filter((n) => n.kind === 'experiment');- expect(experiments).toHaveLength(1);- expect(experiments[0]).toMatchObject({- description: 'ๆๆจกๅ่็ฑปๆฏๆๆถ้ดๆๅบๆด่ฝๆด้ฒๆ นๅ ',- title: 'ๆนๅB:ๅๆ',- });- expect(after.edges.filter((e) => e.kind === 'answers')).toEqual([- expect.objectContaining({ sourceNodeId: experiments[0].id, targetNodeId: problem.id }),- ]);- expect(after.edges.filter((e) => e.kind === 'contains')).toEqual([- expect.objectContaining({- sourceNodeId: experiments[0].id,- targetNodeId: byTitle.get('ๆนๅB:ๅๆ'),- }),- ]);- expect(- after.edges- .filter((e) => e.kind === 'decomposes' && e.sourceNodeId === problem.id)- .map((e) => e.targetNodeId)- .sort(),- ).toEqual([byTitle.get('ๆนๅA:ๆถ้'), byTitle.get('ๆนๅC:ๆฑ็ผ')].sort());-- // The planner's dependsOn indices become depends_on edges, dependent โ- // prerequisite; the self and forward references were dropped.- const deps = after.edges- .filter((e) => e.kind === 'depends_on')- .map((e) => [e.sourceNodeId, e.targetNodeId]);- expect(deps).toHaveLength(2);- expect(deps).toEqual(- expect.arrayContaining([- [byTitle.get('ๆนๅB:ๅๆ'), byTitle.get('ๆนๅA:ๆถ้')],- [byTitle.get('ๆนๅC:ๆฑ็ผ'), byTitle.get('ๆนๅB:ๅๆ')],- ]),- );- });-- it('plans a goal without hypotheses as plain tasks under the problem', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ไฟฎๅฅฝๆ่ฟไธๅคฉ็ bug',- tasks: [- { dependsOn: [], hypothesis: null, instruction: 'ๅๅบ issue', title: 'ๅปบ็ซๆธ ๅ' },- { dependsOn: [0], hypothesis: null, instruction: '้้กนไฟฎๅค', title: 'ๅฎๆฝไฟฎๅค' },- ],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Bug sweep' });-- expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');-- const after = await service.graph(graph.goal.id);- const problem = after.nodes.find((n) => n.kind === 'problem')!;- const taskIds = after.nodes.filter((n) => n.kind === 'task').map((n) => n.id);- expect(taskIds).toHaveLength(2);- expect(after.nodes.filter((n) => n.kind === 'experiment')).toHaveLength(0);- expect(after.edges.filter((e) => e.kind === 'answers' || e.kind === 'contains')).toHaveLength(- 0,- );- expect(- after.edges- .filter((e) => e.kind === 'decomposes' && e.sourceNodeId === problem.id)- .map((e) => e.targetNodeId)- .sort(),- ).toEqual([...taskIds].sort());- expect(after.edges.filter((e) => e.kind === 'depends_on')).toHaveLength(1);- });-- it('collapses a repeated mould into one batch, materializing only the probes', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });-- expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');-- const after = await service.graph(graph.goal.id);- // โ Only the K probes exist as Tasks โ the whole 50-unit fan-out never lands.- expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(5);- expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(1);- expect(after.nodes.filter((n) => n.kind === 'finding')).toHaveLength(1);- expect(after.nodes.filter((n) => n.kind === 'decision')).toHaveLength(1);-- const state = after.goal.config?.rolloutState;- expect(state?.phase).toBe('probe');- expect(state?.probeNodeIds).toHaveLength(5);- expect(state?.unitTitles).toHaveLength(50);- expect(after.goal.config?.rollout?.trigger).toBe('canary');-- // The probes are contained by the batch; the gate waits on each of them.- const batch = after.nodes.find((n) => n.kind === 'batch')!;- const containedIds = new Set(- after.edges- .filter((e) => e.kind === 'contains' && e.sourceNodeId === batch.id)- .map((e) => e.targetNodeId),- );- // Five probes inside the batch โ never the whole 50-unit roster.- expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'task')).toHaveLength(5);- // Plus the one Template and the one Assay that make the batch a batch.- expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'finding')).toHaveLength(- 1,- );- expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'decision')).toHaveLength(- 1,- );- });-- it('does not grow a batch for a goal that is not one repeated mould', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๅไธคๆญฅไธ็บฟไธไธชๆฐๅ่ฝ',- rollout: {- recipeOutline: '',- repeatable: false,- unitCount: 3,- units: [],- variants: [],- },- tasks: [- { dependsOn: [], instruction: '็ฌฌไธๆญฅ๏ผๅ schema', title: '็ฌฌไธๆญฅ' },- { dependsOn: [0], instruction: '็ฌฌไบๆญฅ๏ผๆฅ UI', title: '็ฌฌไบๆญฅ' },- ],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Ship a feature' });-- expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');-- const after = await service.graph(graph.goal.id);- expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);- expect(after.goal.config?.rolloutState).toBeUndefined();- // The ordinary decomposition is untouched: both steps are plain tasks.- expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(2);- });-- it('keeps every roster unit when a rollout claim cannot become a batch', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 12 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 12,- units: Array.from({ length: 12 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 3 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- // The caller forbade a batch, so the planner's claim must NOT drop the- // units its probe-only `tasks` left out.- const graph = await service.create({- config: { rollout: { trigger: 'off' } },- title: 'Migrate stores, no batch',- });- await service.tick(graph.goal.id);-- const after = await service.graph(graph.goal.id);- expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);- // All 12 units are planned, not only the 3 the planner listed as probes.- expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(12);- });-- /**- * Regression: a planner failure was swallowed whole โ the goal quietly- * became one task built from the raw requirement, and nothing anywhere said- * the planner had failed or why.- */- it('records why the planner failed on the task it fell back to', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockRejectedValue({- error: { message: 'Insufficient Balance' },- errorType: 'InsufficientQuota',- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ requirement: '่ฟ็งป 12 ไธช store', title: 'Migrate' });- await service.tick(graph.goal.id);-- const task = (await service.graph(graph.goal.id)).nodes.find((n) => n.kind === 'task');- const [created] = await serverDB- .select()- .from(goalEvents)- .where(and(eq(goalEvents.entityId, task.id), eq(goalEvents.eventType, 'created')));- expect(created.reason).toBe(- 'Planner failed (InsufficientQuota: Insufficient Balance); no main Agent could take the goal; started from the raw requirement',- );- });-- it('records why a batch claim was refused on the first task it planned instead', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 8 ไธช store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 8,- units: Array.from({ length: 8 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 3 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate 8 stores' });- await service.tick(graph.goal.id);-- const tasks = (await service.graph(graph.goal.id)).nodes.filter((n) => n.kind === 'task');- const reasons = await serverDB- .select({ entityId: goalEvents.entityId, reason: goalEvents.reason })- .from(goalEvents)- .where(eq(goalEvents.eventType, 'created'));- const reasonOf = (id: string) => reasons.find((event) => event.entityId === id)?.reason;- expect(reasonOf(tasks[0].id)).toBe(- 'Batch claim refused (unitCount 8 is below the threshold 10); planned unit by unit',- );- // Said once, not on every task.- expect(reasonOf(tasks[1].id)).toBeNull();- });-- /**- * Regression: a model titles its probes around the unit โ "่ฟ็งป device store- * ๏ผๆข้๏ผ" for unit `device` โ and the roster de-duplicated on exact titles,- * so every probed unit was queued again and would run twice.- */- it('does not queue a probed unit again when the probe title wraps its name', async () => {- const units = Array.from({ length: 12 }, (_, i) => `store${i + 1}`);- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 12 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 12,- units,- variants: [],- },- tasks: units.slice(0, 3).map((unit) => ({- dependsOn: [],- instruction: `ๆ src/store/${unit}.ts ๆขๆ replica ๅฎ็ฐ๏ผๅนถ่กฅๅทๅฏๅจๅๅฝๆต่ฏ`,- title: `่ฟ็งป ${unit} store๏ผๆข้๏ผ`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate 12 stores' });- await service.tick(graph.goal.id);-- const roster = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.unitTitles!;- expect(roster).toHaveLength(12);- expect(roster.slice(0, 3)).toEqual(units.slice(0, 3).map((u) => `่ฟ็งป ${u} store๏ผๆข้๏ผ`));- expect(roster.slice(3)).toEqual(units.slice(3));- });-- it('materializes a fallback roster above the batch cap without trimming it', async () => {- const units = Array.from({ length: 64 }, (_, i) => `Unit ${i + 1}`);- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 64 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 64,- units,- variants: [],- },- tasks: Array.from({ length: 3 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { rollout: { trigger: 'off' } },- title: 'Migrate stores, no batch',- });- await service.tick(graph.goal.id);-- const after = await service.graph(graph.goal.id);- expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);- // Every one of the 64 units is planned: the batch config's 60-unit roster- // cap must never trim the ordinary decomposition.- expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(64);- });-- it('refuses to batch a roster above the cap instead of silently trimming it', async () => {- const units = Array.from({ length: 64 }, (_, i) => `Unit ${i + 1}`);- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 64 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 64,- units,- variants: [],- },- tasks: Array.from({ length: 3 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });- await service.tick(graph.goal.id);-- const after = await service.graph(graph.goal.id);- // A roster the batch cannot carry whole is refused, not truncated: the goal- // still delivers all 64 units, as plain tasks.- expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);- expect(after.goal.config?.rolloutState).toBeUndefined();- expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(64);- });-- it('numbers a release after the waves a batch released before the counter existed', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });- await service.tick(graph.goal.id);- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- for (const id of state.probeNodeIds)- await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');- // A rollout from before this change: two waves out, no counter, no log.- await goalModel.updateRolloutState(graph.goal.id, {- ...state,- gateLog: undefined,- phase: 'mass',- waveIndex: 2,- wavesReleased: undefined,- });-- await service.tick(graph.goal.id);- await approveRelease(service, graph.goal.id);- const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- expect(next.gateLog?.at(-1)).toMatchObject({ outcome: 'released', wave: 3 });- expect(next.wavesReleased).toBe(3);- });-- it('numbers a release after the waves a batch released before the counter existed, across a restart', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });- await service.tick(graph.goal.id);- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- for (const id of state.probeNodeIds)- await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');- // A rollout from before this change, restarted once: `waveIndex` reset to 0,- // no counter, no log โ but 20 roster units beyond the first canary are out.- await goalModel.updateRolloutState(graph.goal.id, {- ...state,- gateLog: undefined,- phase: 'mass',- releasedCount: state.releasedCount! + 20,- waveIndex: 0,- wavesReleased: undefined,- });-- await service.tick(graph.goal.id);- await approveRelease(service, graph.goal.id);- const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- // 20 units at the default wave size of 5 are four waves; this one is the fifth.- expect(next.gateLog?.at(-1)).toMatchObject({ outcome: 'released', wave: 5 });- expect(next.wavesReleased).toBe(5);- });-- it('records each gate verdict โ the release and the hold โ with what it checked', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });- await service.tick(graph.goal.id);- const graphModel = new GoalGraphModel(serverDB, userId);- const probeIds = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.probeNodeIds;- for (const id of probeIds) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');-- // The probes settled clean: once the owner approves, the gate releases the- // first wave and says why.- await service.tick(graph.goal.id);- await approveRelease(service, graph.goal.id);- let state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- expect(state.gateLog).toHaveLength(1);- expect(state.gateLog![0]).toMatchObject({- outcome: 'released',- releasedCount: 5,- approvedBy: 'user',- revision: 1,- trigger: 'gate',- wave: 1,- waveIndex: 1,- });- expect(state.wavesReleased).toBe(1);- expect(state.gateLog![0].checks).toContainEqual(- expect.objectContaining({ count: 5, key: 'units_succeeded', passed: true, total: 5 }),- );-- // One unit of that wave was rejected: the next verdict holds and names it.- const [rejected, ...rest] = state.massNodeIds!;- for (const id of rest) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');- await graphModel.updateNodeStatus(graph.goal.id, rejected, 'rejected');- await service.tick(graph.goal.id);- state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- expect(state.phase).toBe('pattern_break');- expect(state.gateLog![1]).toMatchObject({ outcome: 'blocked', trigger: 'gate' });- expect(state.gateLog![1].checks).toContainEqual(- expect.objectContaining({ key: 'units_succeeded', nodeIds: [rejected], passed: false }),- );- });-- it('restarts the canary loop when a person answers a broken batch gate', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });- await service.tick(graph.goal.id);-- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const before = await service.graph(graph.goal.id);- const state = before.goal.config!.rolloutState!;- const assayId = state.assayNodeId!;-- // Simulate the break the coordinator opens when a gate blocks.- const decision = await graphModel.createDecision(graph.goal.id, assayId, {- authority: 'user',- options: [- { description: 'ไฟฎ่ฎข้ ๆน', id: 'revise', label: 'ไฟฎ่ฎข้ ๆนๅนถ้ๆข' },- { description: 'ๆฐ็ฑปๅ', id: 'new_class', label: 'ไฝไธบๆฐ็ฑปๅๅนถๆๅค็' },- ],- question: 'Batch gate blocked',- requestedUserId: userId,- });- await graphModel.updateNodeStatus(graph.goal.id, assayId, 'waiting');- await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });- await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));-- // R5: the answer itself restarts the loop โ no manual rerun.- await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ');-- const after = await service.graph(graph.goal.id);- const next = after.goal.config!.rolloutState!;- expect(next.phase).toBe('probe');- expect(next.waveIndex).toBe(0);- expect(next.templateRevision).toBe(state.templateRevision + 1);- expect(- after.edges.some((e) => e.kind === 'revises' && e.sourceNodeId === next.templateNodeId),- ).toBe(true);- // A fresh gate and a fresh probe batch: the class is proved again.- expect(next.assayNodeId).not.toBe(assayId);- expect(next.probeNodeIds.length).toBeGreaterThan(0);-- // The correction is folded into the batch's recipe and briefs the re-opened- // probes โ later waves only read `policy.spec.recipeOutline`, so a note kept- // only on the Template would never reach the tasks meant to test it.- expect(after.goal.config!.rollout!.spec?.recipeOutline).toContain('่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ');- // The re-opened probes load the plan skill, whose latest version carries it.- const openedProbe = after.nodes.find((n) => next.probeNodeIds.includes(n.id))!;- expect(openedProbe.description).toContain(`user-skills:${next.planSkill!.name}`);- const skill = await new UserSkillService(serverDB, userId).getSkill(next.planSkill!.id);- expect(skill?.content).toContain('่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ');- });-- it('materializes and answers a pattern-break gate on a full rollout', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { rollout: { trigger: 'full' } },- title: 'Migrate stores',- });- await service.tick(graph.goal.id);-- const before = await service.graph(graph.goal.id);- const state = before.goal.config!.rolloutState!;- // A `full` rollout creates no Assay โ it skips the probe gate.- expect(state.assayNodeId).toBeUndefined();-- // A break still has to be answerable: the coordinator must open the question- // on a `decision` node even though this trigger made none.- const openGate = (- service as unknown as {- openPatternBreakGate: (g: unknown, message: string, effects: unknown[]) => Promise<unknown>;- }- ).openPatternBreakGate.bind(service);- await openGate(before, 'Unit 1 did not pass', []);-- const after = await service.graph(graph.goal.id);- const next = after.goal.config!.rolloutState!;- expect(next.phase).toBe('pattern_break');- const gateNode = after.nodes.find((n) => n.id === next.assayNodeId);- expect(gateNode?.kind).toBe('decision');- const decision = after.decisions.find(- (item) => item.nodeId === next.assayNodeId && item.status === 'pending',- );- expect(decision).toBeDefined();- // The options carry ids only; labels and consequences are localized on the- // client by id, so nothing English is persisted into the gate payload.- expect(decision!.options?.map((option) => option.id)).toEqual(['revise', 'new_class']);- expect(decision!.options?.every((option) => option.description === undefined)).toBe(true);-- // Answering it restarts the class, rather than leaving the goal parked.- await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- const restarted = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- expect(restarted.phase).toBe('probe');- expect(restarted.templateRevision).toBe(next.templateRevision + 1);- // The break must not redispatch the whole 50-unit rollout at once: only a- // canary re-probes, and the rest stay owed on the re-cut roster for waves.- expect(restarted.probeNodeIds).toHaveLength(5);- expect(restarted.releasedCount).toBe(5);- expect(restarted.unitTitles).toHaveLength(50);- });-- it('opens one gate when two advances see a full rollout break together', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { rollout: { trigger: 'full' } },- title: 'Migrate stores',- });- await service.tick(graph.goal.id);- const before = await service.graph(graph.goal.id);- const openGate = (- service as unknown as {- openPatternBreakGate: (g: unknown, message: string, effects: unknown[]) => Promise<unknown>;- }- ).openPatternBreakGate.bind(service);-- // Both read the same snapshot with no Assay yet.- await Promise.all([- openGate(before, 'Unit 1 did not pass', []),- openGate(before, 'Unit 2 did not pass', []),- ]);-- // One Assay, one pending question, and it is the one the state records.- const after = await service.graph(graph.goal.id);- const next = after.goal.config!.rolloutState!;- const assays = after.nodes.filter(- (n) => n.kind === 'decision' && n.title === GOAL_BATCH_ASSAY_TITLE,- );- expect(assays).toHaveLength(1);- const pending = after.decisions.filter((item) => item.status === 'pending');- expect(pending.map((item) => item.nodeId)).toEqual([next.assayNodeId]);- });-- it('judges the final wave like any other before closing the batch', async () => {- const rollout = {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 7,- units: Array.from({ length: 7 }, (_, i) => `Unit ${i + 1}`),- variants: [],- };- const tasks = Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- }));- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 7 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout,- tasks,- });- const graphModel = new GoalGraphModel(serverDB, userId);- const service = new GoalService(serverDB, userId);-- const releaseFinalWave = async (title: string) => {- const graph = await service.create({- config: {- rollout: { canarySize: 5, minHomogeneousUnits: 5, trigger: 'canary', waveSize: 7 },- },- title,- });- await service.tick(graph.goal.id);- const probeIds = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.probeNodeIds;- for (const id of probeIds) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');- await service.tick(graph.goal.id);- await approveRelease(service, graph.goal.id);- const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- // The last two units went out, and the batch is not closed on release.- expect(state.massNodeIds).toHaveLength(2);- expect(state.phase).toBe('mass');- return { goalId: graph.goal.id, finalWave: state.massNodeIds! };- };-- // A unit retired from the final wave stops the batch, as in any earlier wave.- const held = await releaseFinalWave('Final wave with a retired unit');- await service.retireNodes(held.goalId, [held.finalWave[0]], 'not needed');- await graphModel.updateNodeStatus(held.goalId, held.finalWave[1], 'resolved');- await service.tick(held.goalId);- expect((await service.graph(held.goalId)).goal.config!.rolloutState!.phase).toBe(- 'pattern_break',- );-- // A clean final wave closes it.- const clean = await releaseFinalWave('Final wave delivered');- for (const id of clean.finalWave)- await graphModel.updateNodeStatus(clean.goalId, id, 'resolved');- await service.tick(clean.goalId);- expect((await service.graph(clean.goalId)).goal.config!.rolloutState!.phase).toBe('done');- });-- describe('answering a batch break', () => {- const decompose = (variants: { axis: string; values: string[] }[] = []) =>- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 7 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 7,- units: Array.from({ length: 7 }, (_, i) => `Unit ${i + 1}`),- variants,- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const pendingBreak = async (service: GoalService, goalId: string) =>- (await service.graph(goalId)).decisions.find(- (item) =>- item.status === 'pending' && item.options?.some((option) => option.id === 'revise'),- )!;-- it('re-probes delivered units when the roster is exhausted and the gate held anyway', async () => {- // An axis value no unit's brief mentions keeps the gate shut even with- // every unit delivered.- decompose([{ axis: 'render', values: ['ssr'] }]);- const service = new GoalService(serverDB, userId);- const graphModel = new GoalGraphModel(serverDB, userId);- const graph = await service.create({- config: { rollout: { minHomogeneousUnits: 5, trigger: 'full' } },- title: 'Full rollout, axis untested',- });- await service.tick(graph.goal.id);- const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- for (const id of [...state.probeNodeIds, ...(state.massNodeIds ?? [])])- await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');- await service.tick(graph.goal.id);- expect((await service.graph(graph.goal.id)).goal.config!.rolloutState!.phase).toBe(- 'pattern_break',- );-- const decision = await pendingBreak(service, graph.goal.id);- await service.decide(graph.goal.id, decision.id, 'revise', 'ๆฏไธชๅๅ ้ฝๆ ssr ่ทฏๅพ้ช่ฏ');-- // The new canary is not empty: delivered units are re-probed under v2.- const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- expect(next.phase).toBe('probe');- expect(next.probeNodeIds.length).toBeGreaterThan(0);- });-- it('leaves the question open when the restart fails part-way, and restarts on a retry', async () => {- decompose();- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },- title: 'Restart is atomic',- });- await service.tick(graph.goal.id);- const openGate = (- service as unknown as {- openPatternBreakGate: (- g: unknown,- message: string,- effects: unknown[],- ) => Promise<unknown>;- }- ).openPatternBreakGate.bind(service);- await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);- const before = await service.graph(graph.goal.id);- const decision = await pendingBreak(service, graph.goal.id);-- // The restart dies after writing its new plan, while creating the next gate.- await serverDB.execute(sql`- CREATE OR REPLACE FUNCTION fail_next_assay() RETURNS trigger AS $$- BEGIN- IF NEW.kind = 'decision' THEN RAISE EXCEPTION 'worker stopped'; END IF;- RETURN NEW;- END $$ LANGUAGE plpgsql- `);- await serverDB.execute(sql`- CREATE TRIGGER fail_next_assay BEFORE INSERT ON goal_nodes- FOR EACH ROW EXECUTE FUNCTION fail_next_assay()- `);- try {- await expect(- service.decide(graph.goal.id, decision.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ'),- ).rejects.toThrow();- } finally {- await serverDB.execute(sql`DROP TRIGGER IF EXISTS fail_next_assay ON goal_nodes`);- await serverDB.execute(sql`DROP FUNCTION IF EXISTS fail_next_assay()`);- }-- // Nothing of the half round survived, and the question is still open.- const failed = await service.graph(graph.goal.id);- expect(failed.nodes).toHaveLength(before.nodes.length);- expect(failed.goal.config!.rolloutState!.phase).toBe('pattern_break');- expect((await pendingBreak(service, graph.goal.id)).id).toBe(decision.id);-- // Answering again opens the next round.- await service.decide(graph.goal.id, decision.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- expect(next.phase).toBe('probe');- expect(next.templateRevision).toBe(2);- });-- it('leaves a brief for the batch gate so Home keeps it after a dismissal', async () => {- decompose();- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },- title: 'Batch gate brief',- });- await service.tick(graph.goal.id);- const openGate = (- service as unknown as {- openPatternBreakGate: (- g: unknown,- message: string,- effects: unknown[],- ) => Promise<unknown>;- }- ).openPatternBreakGate.bind(service);- await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);- const decision = await pendingBreak(service, graph.goal.id);-- const rows = await serverDB.select().from(briefs).where(eq(briefs.userId, userId));- const brief = rows.find(- (row) =>- (row.metadata as { goal?: { decisionId?: string } } | null)?.goal?.decisionId ===- decision.id,- );- expect(brief).toMatchObject({ type: 'decision' });- // Revising needs a correction, so the brief sends the person to the goal- // page rather than offering one-click answers.- expect((brief!.actions as { key: string }[]).map((action) => action.key)).toEqual([- 'openGoal',- ]);- });-- it('does not re-park a goal whose gate was answered while its brief was written', async () => {- decompose();- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },- title: 'Answered during the brief',- });- await service.tick(graph.goal.id);- const internals = service as unknown as {- briefs: { openDecision: (...args: unknown[]) => Promise<void> };- openPatternBreakGate: (g: unknown, message: string, effects: unknown[]) => Promise<unknown>;- };- // The person answers the moment the gate is visible, before the brief lands.- internals.briefs.openDecision = async () => {- const decision = await pendingBreak(service, graph.goal.id);- await service.decide(graph.goal.id, decision.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- };-- await internals.openPatternBreakGate.bind(service)(- await service.graph(graph.goal.id),- 'Unit 1 did not pass',- [],- );-- // The answer resumed the goal on a new round; the opener must not undo it.- const after = await service.graph(graph.goal.id);- expect(after.goal.config!.rolloutState!.phase).toBe('probe');- expect(after.goal.status).toBe('running');- expect(after.goal.config?.pausedBy).toBeUndefined();- });-- it('refuses to revise the recipe without a correction', async () => {- decompose();- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },- title: 'Revise needs a correction',- });- await service.tick(graph.goal.id);- const openGate = (- service as unknown as {- openPatternBreakGate: (- g: unknown,- message: string,- effects: unknown[],- ) => Promise<unknown>;- }- ).openPatternBreakGate.bind(service);- await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);- const decision = await pendingBreak(service, graph.goal.id);-- await expect(service.decide(graph.goal.id, decision.id, 'revise', ' ')).rejects.toThrow(- 'Revising the recipe needs a correction',- );- // The question stays open for an answer that says what to change.- expect((await pendingBreak(service, graph.goal.id)).id).toBe(decision.id);- });-- it('fails the fork, keeping the question open, when the old rules cannot be retired', async () => {- decompose();- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },- title: 'Fork with a stuck rule',- });- await service.tick(graph.goal.id);- const openGate = (- service as unknown as {- openPatternBreakGate: (- g: unknown,- message: string,- effects: unknown[],- ) => Promise<unknown>;- }- ).openPatternBreakGate.bind(service);- await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);- let decision = await pendingBreak(service, graph.goal.id);- await service.decide(graph.goal.id, decision.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);- decision = await pendingBreak(service, graph.goal.id);-- // Retiring the old rule fails.- await serverDB.execute(sql`- CREATE OR REPLACE FUNCTION fail_lesson_retire() RETURNS trigger AS $$- BEGIN- IF NEW.status = 'retired' THEN RAISE EXCEPTION 'retire failed'; END IF;- RETURN NEW;- END $$ LANGUAGE plpgsql- `);- await serverDB.execute(sql`- CREATE TRIGGER fail_lesson_retire BEFORE UPDATE ON expertise_lessons- FOR EACH ROW EXECUTE FUNCTION fail_lesson_retire()- `);- try {- await expect(- service.decide(graph.goal.id, decision.id, 'new_class', 'ๆๆฐ็ฑปๅๅค็'),- ).rejects.toThrow();- } finally {- await serverDB.execute(sql`DROP TRIGGER IF EXISTS fail_lesson_retire ON expertise_lessons`);- await serverDB.execute(sql`DROP FUNCTION IF EXISTS fail_lesson_retire()`);- }-- // The batch still knows the rule (so retiring it can be retried), and the- // question is still there to answer.- const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- expect(state.learnings).toHaveLength(1);- expect((await pendingBreak(service, graph.goal.id)).id).toBe(decision.id);- });-- it('forks a new class from the original outline, not the revised plan', async () => {- decompose();- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },- title: 'Fork after a revision',- });- await service.tick(graph.goal.id);- const openGate = (- service as unknown as {- openPatternBreakGate: (- g: unknown,- message: string,- effects: unknown[],- ) => Promise<unknown>;- }- ).openPatternBreakGate.bind(service);-- await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);- let decision = await pendingBreak(service, graph.goal.id);- await service.decide(graph.goal.id, decision.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- const [taught] = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.learnings!;- await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);- decision = await pendingBreak(service, graph.goal.id);- await service.decide(graph.goal.id, decision.id, 'new_class', 'ๆๆฐ็ฑปๅๅค็');-- const after = await service.graph(graph.goal.id);- const plan = after.nodes.find(- (node) => node.id === after.goal.config!.rolloutState!.templateNodeId,- )!;- // The v2 correction belongs to the old class; the fork starts clean.- expect(plan.description).not.toContain('่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- expect(plan.description).toContain('ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ');- // โฆand so do its rules: the old class's learnings do not bind the new one.- expect(after.goal.config!.rolloutState!.learnings).toBeUndefined();- expect(after.goal.config!.rolloutState!.learningDomainId).toBeUndefined();- // The old class's rule also stops reaching runs: retired in the shared domain.- expect((await new ExpertiseModel(serverDB, userId).findLesson(taught.lessonId))?.status).toBe(- 'retired',- );- });- });-- it('routes a batch unit out of verification retries through the batch gate', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 1 } },- title: 'Migrate stores',- });- await service.tick(graph.goal.id);- const dispatched = await service.tick(graph.goal.id);- expect(dispatched.taskId).toBeDefined();-- // The unit's one attempt failed verification: no attempts left.- const taskModel = new TaskModel(serverDB, userId);- await taskModel.update(dispatched.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(dispatched.taskId!, 'paused', {- error: VERIFICATION_FAILED_ERROR,- });- // The other probes dispatch first; the paused unit's turn follows.- for (let i = 0; i < 8; i++) {- await service.tick(graph.goal.id);- if ((await service.graph(graph.goal.id)).goal.config!.rolloutState!.phase !== 'probe') break;- }-- // It breaks the class โ revise the recipe and re-probe โ rather than- // parking on an ordinary retry/retire gate for one task.- const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- expect(state.phase).toBe('pattern_break');- expect(state.gateLog?.at(-1)).toMatchObject({- nodeId: dispatched.nodeId,- outcome: 'blocked',- trigger: 'unit',- });- });-- it('stops the running Tasks of the members a restart retires', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });- await service.tick(graph.goal.id);- for (let i = 0; i < 5; i++) await service.tick(graph.goal.id);-- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const before = await service.graph(graph.goal.id);- const state = before.goal.config!.rolloutState!;- const [broken, sibling] = state.probeNodeIds.map((id) =>- before.nodes.find((node) => node.id === id)!,- );- expect(sibling.taskId).toBeTruthy();- // One unit broke while a sibling is still running.- await graphModel.updateNodeStatus(graph.goal.id, broken.id, 'rejected');- await taskModel.updateStatus(sibling.taskId!, 'running');-- const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {- authority: 'user',- options: [{ id: 'revise', label: 'Revise' }],- question: 'Unit 1 did not pass',- requestedUserId: userId,- });- await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');- await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });- await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));-- await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');-- // The sibling is retired and its Task stopped โ it no longer runs beside- // the probe that replaces it.- const after = await service.graph(graph.goal.id);- expect(after.nodes.find((node) => node.id === sibling.id)?.status).toBe('retired');- const [task] = await taskModel.findByIds([sibling.taskId!]);- expect(task.status).toBe('canceled');- });-- it('keeps a re-opened probe briefed with its variant assignment', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [{ axis: 'render', values: ['ssr', 'csr'] }],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ๏ผๆ ${i === 0 ? 'ssr' : 'csr'} ่ทฏๅพ้ช่ฏ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });- await service.tick(graph.goal.id);-- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const before = await service.graph(graph.goal.id);- const state = before.goal.config!.rolloutState!;- const ssrProbe = before.nodes.find((node) => node.title === 'Unit 1')!;- await graphModel.updateNodeStatus(graph.goal.id, ssrProbe.id, 'rejected');- const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {- authority: 'user',- options: [{ id: 'revise', label: 'Revise' }],- question: 'Unit 1 did not pass',- requestedUserId: userId,- });- await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');- await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });- await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));-- await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');-- // The re-opened probe still says which variant it covers, so the gate does- // not report the axis value it tested as untested.- const after = await service.graph(graph.goal.id);- const next = after.goal.config!.rolloutState!;- const reopened = after.nodes.find(- (node) => next.probeNodeIds.includes(node.id) && node.title === 'Unit 1',- )!;- expect(reopened.description).toContain('ๆ ssr ่ทฏๅพ้ช่ฏ');- const probes = after.nodes.filter((node) => next.probeNodeIds.includes(node.id));- expect(- uncoveredAxisValues(- [{ axis: 'render', values: ['ssr', 'csr'] }],- probes.map((node) => ({ instruction: node.description ?? '', title: node.title })),- ),- ).not.toContainEqual({ axis: 'render', value: 'ssr' });- });-- it('re-opens the broken unit as a new task when the canary loop restarts', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });- await service.tick(graph.goal.id);-- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const before = await service.graph(graph.goal.id);- const state = before.goal.config!.rolloutState!;- const [broken, ...settled] = state.probeNodeIds;- for (const id of settled) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');- await graphModel.updateNodeStatus(graph.goal.id, broken, 'waiting');- // A wave the round already released, whose member broke and was retired.- const massMember = await graphModel.createNode(graph.goal.id, {- kind: 'task',- scopeId: state.batchNodeId,- title: 'Unit 6',- });- await graphModel.updateNodeStatus(graph.goal.id, massMember!.id, 'retired');-- const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {- authority: 'user',- options: [- { description: 'ไฟฎ่ฎข้ ๆน', id: 'revise', label: 'ไฟฎ่ฎข้ ๆนๅนถ้ๆข' },- { description: 'ๆฐ็ฑปๅ', id: 'new_class', label: 'ไฝไธบๆฐ็ฑปๅๅนถๆๅค็' },- ],- question: 'Unit 1 did not pass',- requestedUserId: userId,- });- await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');- await goalModel.updateRolloutState(graph.goal.id, {- ...state,- massNodeIds: [massMember!.id],- phase: 'pattern_break',- });- await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));-- await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');-- const after = await service.graph(graph.goal.id);- const next = after.goal.config!.rolloutState!;- // Decision #4: the broken unit runs again as a new task, the old one retires.- expect(after.nodes.find((n) => n.id === broken)?.status).toBe('retired');- // Both units that broke this round โ the probe and the wave member โ re-open.- const reopenedNodes = next.probeNodeIds.map((id) => after.nodes.find((n) => n.id === id)!);- expect(reopenedNodes.map((n) => n.title).sort()).toEqual(['Unit 1', 'Unit 6']);- const reopened = reopenedNodes.find((n) => n.title === 'Unit 1')!;- expect(- after.edges.some(- (e) =>- e.kind === 'derived_from' && e.sourceNodeId === reopened.id && e.targetNodeId === broken,- ),- ).toBe(true);- // Re-opening is not a new release: the roster is re-cut to what is still- // owed, so the cursor counts the re-opened probes over the shorter roster,- // and the units the class still owes stay queued for the waves.- expect(next.releasedCount).toBe(next.probeNodeIds.length);- expect(next.unitTitles).toContain('Unit 50');- expect(new Set(next.unitTitles).size).toBe(next.unitTitles!.length);- // The revised plan carries v1 forward and appends what changed, so the two- // versions diff as "v1 + the v2 section", not as a replacement.- const plan = after.nodes.find((n) => n.id === next.templateNodeId)!;- expect(plan.description).toBe('ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ\n\n### v2\n่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- // The new canary is a fresh round: the old wave's retired member no longer- // counts against its gate (it would re-open the same break at once).- expect(next.massNodeIds).toBeUndefined();-- // The plan lives as a skill in the user's library: v1 at decomposition,- // v2 when the break revised it โ each version kept whole.- const planSkill = next.planSkill!;- expect(planSkill.name).toMatch(/^goal-plan-/);- const skill = await new UserSkillService(serverDB, userId).getSkill(planSkill.id);- expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);- expect(skill?.content).toContain('### v2\n่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- expect(skill?.versions[0].content).not.toContain('### v2');- // A re-opened unit names the skill, which carries every later revisionโฆ- expect(reopened.description).toContain(`user-skills:${planSkill.name}`);- // โฆand still carries the revised plan, in case the skill does not load.- expect(reopened.description).toContain('### v2\n่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');-- // The break taught the batch: a rule in its expertise, which later units'- // acceptance adds as a clause โ no standalone criterion that nothing mounts.- expect(next.learnings).toMatchObject([{ revision: 1, title: '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ' }]);- const [learning] = next.learnings!;- expect(learning.criterionId).toBeUndefined();- const lesson = await new ExpertiseModel(serverDB, userId).findLesson(learning.lessonId);- expect(lesson).toMatchObject({- compilability: 'compilable',- compiledCriterionId: null,- enforcement: 'block',- });-- // A unit dispatched after the break loads the skill on every run and is- // judged by what the batch learned.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- await service.tick(graph.goal.id);- const dispatched = (await service.graph(graph.goal.id)).nodes.find(- (node) => next.probeNodeIds.includes(node.id) && node.taskId,- )!;- const task = await new TaskModel(serverDB, userId).findById(dispatched.taskId!);- expect(task?.config).toMatchObject({ skills: [`user-skills:${planSkill.name}`] });- const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(- 'task',- dispatched.taskId!,- );- // The learned rule is added to the unit's own contract, not substituted for- // it: configured criteria would make the verifier check only those.- expect(acceptance?.config?.verifyCriteriaIds).toBeUndefined();- expect(acceptance?.requirement).toContain(dispatched.title);- expect(acceptance?.requirement).toContain('- ่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- });-- it('falls back to copying the revised plan when the skill revision does not land', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });- await service.tick(graph.goal.id);-- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- // The plan skill was deleted from the library in the meantime.- await serverDB.delete(documents).where(eq(documents.id, state.planSkill!.id));-- const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {- authority: 'user',- options: [{ id: 'revise', label: 'Revise' }],- question: 'Batch gate blocked',- requestedUserId: userId,- });- await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');- await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });- await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));-- await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');-- // The new round does not point units at a skill that lacks the revision:- // they carry the revised plan themselves.- const after = await service.graph(graph.goal.id);- const next = after.goal.config!.rolloutState!;- expect(next.planSkill).toBeUndefined();- const probe = after.nodes.find((node) => node.id === next.probeNodeIds[0])!;- expect(probe.description).toContain('### v2\n่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- expect(probe.description).not.toContain('user-skills:');- });-- it('mounts what a break taught on the agent that runs the units, even in a project', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- await serverDB.insert(agents).values([{ id: 'agt_batch', slug: 'agt-batch', userId }]);- await serverDB.insert(projects).values({- coordinatorAgentId: 'agt_batch',- id: 'proj_batch',- identifier: 'BAT',- name: 'Batch project',- userId,- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({- agentId: 'agt_batch',- projectId: 'proj_batch',- title: 'Migrate stores in a project',- });- await service.tick(graph.goal.id);-- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {- authority: 'user',- options: [{ id: 'revise', label: 'Revise' }],- question: 'Batch gate blocked',- requestedUserId: userId,- });- await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');- await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });- await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));- await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');-- // A run's expertise snapshot reads the executing agent's domains, so that- // is where the batch's rules must live for its units to receive them.- const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- const domains = await new ExpertiseModel(serverDB, userId).listDomainsForAgent('agt_batch');- expect(domains.map(({ domain }) => domain.id)).toContain(next.learningDomainId);- });-- it('learns into one shared domain per agent, through the executor fallback', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- await serverDB.insert(agents).values([- { id: 'agt_goal_main', slug: 'agt-goal-main', userId },- { id: 'agt_gone_exec', slug: 'agt-gone-exec', userId },- ]);- const service = new GoalService(serverDB, userId);- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const breakAndRevise = async (title: string) => {- const graph = await service.create({- agentId: 'agt_goal_main',- config: { taskAgentId: 'agt_gone_exec' },- title,- });- await service.tick(graph.goal.id);- const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {- authority: 'user',- options: [{ id: 'revise', label: 'Revise' }],- question: 'Batch gate blocked',- requestedUserId: userId,- });- await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');- await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });- await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));- // The dedicated executor is deleted before the break is answered.- await serverDB.delete(agents).where(eq(agents.id, 'agt_gone_exec'));- await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ');- return (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- };-- // The owner already keeps a batch domain of their own, inherited by every- // agent: an agent's rule must not land there.- const ownerDomainId = await new ExpertiseModel(serverDB, userId).createDomain({- brief: 'What the release gates of goal batches have learned.',- carrier: { type: 'user' },- domainFilter: 'Doing or verifying a unit of a goal batch.',- title: 'Goal batch rules',- });-- const first = await breakAndRevise('First batch');- expect(first.learningDomainId).not.toBe(ownerDomainId);- // Learned despite the stale executor: mounted on the goal agent it falls back to.- expect(first.learnings).toHaveLength(1);- const expertise = new ExpertiseModel(serverDB, userId);- expect(- (await expertise.listDomainsForAgent('agt_goal_main')).map(({ domain }) => domain.id),- ).toContain(first.learningDomainId);-- // A second batch on the same agent reuses that domain instead of adding one.- await serverDB- .insert(agents)- .values({ id: 'agt_gone_exec', slug: 'agt-gone-exec', userId })- .onConflictDoNothing();- const second = await breakAndRevise('Second batch');- expect(second.learningDomainId).toBe(first.learningDomainId);- });-- it('creates one batch domain when two goals on an agent learn at the same time', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- await serverDB.insert(agents).values([{ id: 'agt_shared', slug: 'agt-shared', userId }]);- const service = new GoalService(serverDB, userId);- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const openBreak = async (title: string) => {- const graph = await service.create({ agentId: 'agt_shared', title });- await service.tick(graph.goal.id);- const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {- authority: 'user',- options: [{ id: 'revise', label: 'Revise' }],- question: 'Batch gate blocked',- requestedUserId: userId,- });- await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');- await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });- await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));- return { decisionId: decision!.id, goalId: graph.goal.id };- };- const a = await openBreak('Batch A');- const b = await openBreak('Batch B');-- // Both first breaks are answered at once.- await Promise.all([- service.decide(a.goalId, a.decisionId, 'revise', '่กฅไธๅทๅฏๅจ่ฟไธๆญฅ'),- service.decide(b.goalId, b.decisionId, 'revise', '่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ'),- ]);-- const domainOf = async (goalId: string) =>- (await service.graph(goalId)).goal.config!.rolloutState!.learningDomainId;- expect(await domainOf(a.goalId)).toBe(await domainOf(b.goalId));- const bound = await new ExpertiseModel(serverDB, userId).listDomainsForAgent('agt_shared');- expect(bound.filter(({ domain }) => domain.title === 'Goal batch rules')).toHaveLength(1);- });-- it('moves a batch from before plan skills into one at its next revision', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Migrate stores' });- await service.tick(graph.goal.id);-- const graphModel = new GoalGraphModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const { planSkill: _written, ...legacy } = (await service.graph(graph.goal.id)).goal.config!- .rolloutState!;- const decision = await graphModel.createDecision(graph.goal.id, legacy.assayNodeId!, {- authority: 'user',- options: [{ description: 'ไฟฎ่ฎข้ ๆน', id: 'revise', label: 'ไฟฎ่ฎข้ ๆนๅนถ้ๆข' }],- question: 'Batch gate blocked',- requestedUserId: userId,- });- await graphModel.updateNodeStatus(graph.goal.id, legacy.assayNodeId!, 'waiting');- await goalModel.updateRolloutState(graph.goal.id, { ...legacy, phase: 'pattern_break' });- await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));-- await service.decide(graph.goal.id, decision!.id, 'revise', '่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ');-- const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- const skill = await new UserSkillService(serverDB, userId).getSkill(next.planSkill!.id);- // The plan's earlier version becomes v1 and the revision v2, so version N- // still reads as round N.- expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);- expect(skill?.versions[0].content).toContain('ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ');- expect(skill?.versions[1].content).toContain('### v2\n่กฅไธ SSR ๆญ็ง่ฟไธๆญฅ');- });-- it('persists the planned recipe when the caller already chose a canary rollout', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 50 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 50,- units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),- variants: [{ axis: 'cold-start', values: ['yes', 'no'] }],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { rollout: { canarySize: 3, trigger: 'canary', waveSize: 7 } },- title: 'Migrate stores',- });- await service.tick(graph.goal.id);-- const policy = (await service.graph(graph.goal.id)).goal.config!.rollout!;- // What the planner derived is kept โ later waves brief from it, the gate checks its axesโฆ- expect(policy.spec?.recipeOutline).toBe('ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ');- expect(policy.spec?.variantAxes).toEqual([{ axis: 'cold-start', values: ['yes', 'no'] }]);- expect(policy.units).toHaveLength(50);- // โฆand what the caller chose still wins.- expect(policy).toMatchObject({ canarySize: 3, trigger: 'canary', waveSize: 7 });- });-- it('asks a blocking question before planning, then plans once with the answer', async () => {- const planner = vi- .spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')- .mockResolvedValue({- assumptions: ['ๆฅๅ็จไธญๆ'],- problemStatement: 'ไธบๆฐๅ่ฝๅไธไปฝๅๅธ่ฏดๆ',- questions: [- {- assumption: '้ขๅ็ป็ซฏ็จๆท',- blocking: true,- impact: 'ๅณๅฎๅไบงๅ่ฏดๆ่ฟๆฏ API ๅๆด',- options: ['็ป็ซฏ็จๆท', 'ๅผๅ่ '],- question: '่ฟไปฝ่ฏดๆ็ป่ฐ็๏ผ',- },- ],- tasks: [{ dependsOn: [], hypothesis: null, instruction: 'ๅ่ฏดๆ', title: 'ๆฐๅ' }],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Release notes' });-- // The first plan asks instead of creating Tasks on a guess.- expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');- let after = await service.graph(graph.goal.id);- expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(0);- const problem = after.nodes.find((n) => n.kind === 'problem')!;- expect(Number(problem.confidence)).toBe(0.3);- expect(after.goal.config?.understanding).toMatchObject({- assumptions: ['ๆฅๅ็จไธญๆ'],- level: 'low',- });- const [decision] = after.decisions;- expect(decision).toMatchObject({ question: '่ฟไปฝ่ฏดๆ็ป่ฐ็๏ผ', status: 'pending' });- expect(decision.options?.map((option) => option.id)).toEqual([- 'option-1',- 'option-2',- 'assume',- 'answer',- ]);- expect(after.edges).toContainEqual(- expect.objectContaining({- kind: 'leads_to',- sourceNodeId: problem.id,- targetNodeId: decision.nodeId,- }),- );-- // The open question parks the goal on the ordinary decision gate.- expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');- expect((await service.graph(graph.goal.id)).goal.status).toBe('review');-- // An empty free-text answer is refused rather than re-planning on nothing.- await expect(service.decide(graph.goal.id, decision.id, 'answer', ' ')).rejects.toThrow(- 'This answer needs a note',- );- await service.decide(graph.goal.id, decision.id, 'option-2', 'ๅชๅ ณๅฟ SDK');-- // The re-plan receives the answer and, even though the planner still- // reports a blocking question, proceeds on assumptions: one round only.- expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');- expect(planner).toHaveBeenLastCalledWith({- clarifications: [{ answer: 'ๅผๅ่ (ๅชๅ ณๅฟ SDK)', question: '่ฟไปฝ่ฏดๆ็ป่ฐ็๏ผ' }],- requirement: expect.any(String),- });- after = await service.graph(graph.goal.id);- expect(after.nodes.filter((n) => n.kind === 'task').map((n) => n.title)).toEqual(['ๆฐๅ']);- expect(after.decisions.filter((d) => d.status === 'pending')).toHaveLength(0);- expect(Number(after.nodes.find((n) => n.kind === 'problem')!.confidence)).toBe(0.6);- // The re-asked question was answered, so its fallback never becomes an- // assumption that contradicts the answer.- expect(after.goal.config?.understanding).toMatchObject({- assumptions: ['ๆฅๅ็จไธญๆ'],- level: 'medium',- });- });-- it('lists a clarification round for other surfaces and answers it in one go', async () => {- const planner = vi- .spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')- .mockResolvedValue({- assumptions: [],- problemStatement: 'ๅๅๅธ่ฏดๆ',- questions: [- {- assumption: '็ป็ซฏ็จๆท',- blocking: true,- impact: 'ๅณๅฎ่ฏญๆฐ',- options: ['็ป็ซฏ็จๆท', 'ๅผๅ่ '],- question: '็ป่ฐ็๏ผ',- },- { assumption: 'ๆดๆฐๆฅๅฟ', blocking: true, options: [], question: 'ๅๅจๅช้๏ผ' },- ],- tasks: [{ dependsOn: [], hypothesis: null, instruction: 'ๅ', title: 'ๆฐๅ' }],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({- requirement: 'ไธบๆฐๅ่ฝๅไธไปฝๅๅธ่ฏดๆ',- title: 'Release notes',- });- await service.tick(graph.goal.id);-- const pending = await service.pendingClarifications();- expect(pending).toEqual([- expect.objectContaining({- goalId: graph.goal.id,- questions: expect.arrayContaining([- expect.objectContaining({ description: 'ๅณๅฎ่ฏญๆฐ', question: '็ป่ฐ็๏ผ' }),- expect.objectContaining({ description: null, question: 'ๅๅจๅช้๏ผ' }),- ]),- // The requirement says which goal this is away from its own page.- requirement: 'ไธบๆฐๅ่ฝๅไธไปฝๅๅธ่ฏดๆ',- title: 'Release notes',- }),- ]);-- // A paused goal keeps its questions but stops asking them elsewhere.- await service.pause(graph.goal.id);- expect(await service.pendingClarifications()).toEqual([]);- await service.resume(graph.goal.id);- expect(await service.pendingClarifications()).toHaveLength(1);-- const audience = pending[0].questions.find((q) => q.question === '็ป่ฐ็๏ผ')!;- const place = pending[0].questions.find((q) => q.question === 'ๅๅจๅช้๏ผ')!;- await service.answerClarifications(graph.goal.id, [- { decisionId: audience.decisionId, optionId: 'option-2', resolution: 'ๅชๅ ณๅฟ SDK' },- { decisionId: place.decisionId, optionId: 'answer', resolution: 'GitHub Release' },- ]);-- expect(await service.pendingClarifications()).toEqual([]);- expect((await service.graph(graph.goal.id)).goal.status).toBe('running');- // One re-plan, carrying both answers.- await service.tick(graph.goal.id);- const [lastCall] = planner.mock.calls.at(-1)!;- expect(lastCall.clarifications).toHaveLength(2);- expect(lastCall.clarifications).toEqual(- expect.arrayContaining([- { answer: 'ๅผๅ่ (ๅชๅ ณๅฟ SDK)', question: '็ป่ฐ็๏ผ' },- { answer: 'GitHub Release', question: 'ๅๅจๅช้๏ผ' },- ]),- );- });-- it('writes none of a clarification round when one answer is invalid, and retries cleanly', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- assumptions: [],- problemStatement: 'ๅๅๅธ่ฏดๆ',- questions: [- {- assumption: '็ป็ซฏ็จๆท',- blocking: true,- options: ['็ป็ซฏ็จๆท', 'ๅผๅ่ '],- question: '็ป่ฐ็๏ผ',- },- { assumption: 'ๆดๆฐๆฅๅฟ', blocking: true, options: [], question: 'ๅๅจๅช้๏ผ' },- ],- tasks: [{ dependsOn: [], hypothesis: null, instruction: 'ๅ', title: 'ๆฐๅ' }],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Release notes' });- await service.tick(graph.goal.id);- const [{ questions }] = await service.pendingClarifications();- const audience = questions.find((q) => q.question === '็ป่ฐ็๏ผ')!;- const place = questions.find((q) => q.question === 'ๅๅจๅช้๏ผ')!;-- // The second answer is invalid, so the first must not be written either.- await expect(- service.answerClarifications(graph.goal.id, [- { decisionId: audience.decisionId, optionId: 'option-2' },- { decisionId: place.decisionId, optionId: 'no-such-option' },- ]),- ).rejects.toThrow('Unknown decision option');- expect((await service.pendingClarifications())[0].questions).toHaveLength(2);-- // A retry after a partial write succeeds: the recorded answer is skipped.- await service.decide(graph.goal.id, audience.decisionId, 'option-2');- await service.answerClarifications(graph.goal.id, [- { decisionId: audience.decisionId, optionId: 'option-2' },- { decisionId: place.decisionId, optionId: 'assume' },- ]);- expect(await service.pendingClarifications()).toEqual([]);- });-- it('keeps the answers in the fallback task when the re-plan fails', async () => {- const planner = vi- .spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')- .mockResolvedValue({- assumptions: [],- problemStatement: 'ๅๅๅธ่ฏดๆ',- questions: [- {- assumption: '็ป็ซฏ็จๆท',- blocking: true,- options: ['็ป็ซฏ็จๆท', 'ๅผๅ่ '],- question: '็ป่ฐ็๏ผ',- },- ],- tasks: [{ dependsOn: [], hypothesis: null, instruction: 'ๅ', title: 'ๆฐๅ' }],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({- problemDescription: 'ๅไธไปฝๅๅธ่ฏดๆ๏ผๅฟ ้กป้ไธ่ฟ็งปๆๅ',- requirement: 'ๅไธไปฝๅๅธ่ฏดๆ๏ผๅฟ ้กป้ไธ่ฟ็งปๆๅ',- title: 'Release notes',- });- await service.tick(graph.goal.id);- // Asking commits no tasks, so the user's own words stay on the problem.- expect(- (await service.graph(graph.goal.id)).nodes.find((n) => n.kind === 'problem')!.description,- ).toBe('ๅไธไปฝๅๅธ่ฏดๆ๏ผๅฟ ้กป้ไธ่ฟ็งปๆๅ');- const [{ questions }] = await service.pendingClarifications();- await service.answerClarifications(graph.goal.id, [- { decisionId: questions[0].decisionId, optionId: 'option-2', resolution: 'ๅชๅ ณๅฟ SDK' },- ]);-- planner.mockRejectedValueOnce(new Error('planner down'));- await service.tick(graph.goal.id);-- const task = (await service.graph(graph.goal.id)).nodes.find((n) => n.kind === 'task');- // The original request's constraint survives, not the planner's summary.- expect(task!.description).toContain('ๅฟ ้กป้ไธ่ฟ็งปๆๅ');- expect(task!.description).toContain('Q: ็ป่ฐ็๏ผ');- expect(task!.description).toContain('A: ๅผๅ่ (ๅชๅ ณๅฟ SDK)');- });-- it('keeps the coordinator understanding when the user edits the goal policy', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- assumptions: ['ๅชไฟฎ P0'],- problemStatement: 'ไฟฎ bug',- questions: [],- tasks: [{ dependsOn: [], hypothesis: null, instruction: 'ไฟฎ', title: 'ไฟฎๅค' }],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Fix' });- await service.tick(graph.goal.id);-- // A policy editor sends its whole (stale) config snapshot back.- await new GoalModel(serverDB, userId).update(graph.goal.id, {- config: { maxConcurrentTasks: 2 },- });-- const after = await service.graph(graph.goal.id);- expect(after.goal.config?.maxConcurrentTasks).toBe(2);- expect(after.goal.config?.understanding).toMatchObject({- assumptions: ['ๅชไฟฎ P0'],- level: 'medium',- });- });-- it('plans the decomposition once when two advances race through the planner', async () => {- // The queued kickoff and the client's fire-and-forget fallback can both- // reach plan_decomposition together; the atomic planning claim must stop- // the loser BEFORE the planner call, so nothing double-plans or double-pays.- let release!: () => void;- const gate = new Promise<void>((resolve) => {- release = resolve;- });- let plannerCalls = 0;- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockImplementation(async () => {- plannerCalls += 1;- await gate;- return {- problemStatement: 'ๅนถๅ่งๅ',- tasks: [- { dependsOn: [], instruction: 'ๆถ้', title: 'ๆนๅA' },- { dependsOn: [0], instruction: 'ๅๆ', title: 'ๆนๅB' },- ],- };- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ problemDescription: 'ๅ่ฏ', title: 'Raced planning' });-- const ticks = Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);- // The winner holds the planner open; the loser must lose the claim and- // return without ever entering it.- await vi.waitFor(() => expect(plannerCalls).toBe(1));- release();- const results = await ticks;-- expect(plannerCalls).toBe(1);- expect(results.filter((r) => r.outcome === 'advanced')).toHaveLength(1);- expect(results.filter((r) => r.outcome === 'waiting_external')).toHaveLength(1);- const after = await service.graph(graph.goal.id);- expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(2);- expect(after.edges.filter((e) => e.kind === 'depends_on')).toHaveLength(1);- });-- it('waits for an unfenced legacy planner instead of generating a second graph', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Legacy in-flight planning' });- // The pre-lease binary claimed only the status, without a checkpoint.- await serverDB.update(goals).set({ status: 'running' }).where(eq(goals.id, graph.goal.id));- const planner = vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose');-- expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_external');- expect(planner).not.toHaveBeenCalled();- expect(- (await service.graph(graph.goal.id)).nodes.filter((node) => node.kind === 'task'),- ).toHaveLength(0);- });-- it('does not call the planner again when a late advance sees running with no tasks', async () => {- let release!: () => void;- const gate = new Promise<void>((resolve) => {- release = resolve;- });- const planner = vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose');- planner.mockImplementationOnce(async () => {- await gate;- return {- problemStatement: 'First plan',- tasks: [{ instruction: 'Collect sources', title: 'Original research' }],- };- });- planner.mockResolvedValue({- problemStatement: 'Second plan',- tasks: [{ instruction: 'Collect sources', title: 'Equivalent research' }],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Staggered planning' });- const first = service.tick(graph.goal.id);- try {- await vi.waitFor(() => expect(planner).toHaveBeenCalledTimes(1));- // The initial claim already changed the status, but has not produced any tasks.- expect((await service.graph(graph.goal.id)).goal.status).toBe('running');- const late = await new GoalService(serverDB, userId).tick(graph.goal.id);- expect(late.outcome).toBe('waiting_external');- expect(planner).toHaveBeenCalledTimes(1);- } finally {- release();- await first;- }- const after = await service.graph(graph.goal.id);- expect(after.nodes.filter((node) => node.kind === 'task')).toHaveLength(1);- expect(after.nodes.filter((node) => node.kind === 'experiment')).toHaveLength(0);- expect(after.nodes.find((node) => node.kind === 'problem')?.description).toBe('First plan');- expect(after.edges.filter((edge) => edge.kind === 'decomposes')).toHaveLength(1);- });-- it('rejects a late planner after an expired lease is taken over', async () => {- let release!: () => void;- const gate = new Promise<void>((resolve) => {- release = resolve;- });- const planner = vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose');- planner.mockImplementationOnce(async () => {- await gate;- return { problemStatement: 'Stale plan', tasks: [{ instruction: 'Old', title: 'Old task' }] };- });- planner.mockResolvedValue({- problemStatement: 'Recovered plan',- tasks: [{ instruction: 'New', title: 'New task' }],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Lease recovery' });- const first = service.tick(graph.goal.id);- try {- await vi.waitFor(() => expect(planner).toHaveBeenCalledTimes(1));- const model = new GoalModel(serverDB, userId);- const current = await model.findById(graph.goal.id);- await serverDB- .update(goals)- .set({- config: {- ...current?.config,- planningCheckpoint: {- token: current!.config!.planningCheckpoint!.token,- expiresAt: '2000-01-01T00:00:00.000Z',- },- },- })- .where(eq(goals.id, graph.goal.id));- await new GoalService(serverDB, userId).tick(graph.goal.id);- } finally {- release();- await first;- }- const after = await service.graph(graph.goal.id);- expect(after.nodes.filter((node) => node.kind === 'task').map((node) => node.title)).toEqual([- 'New task',- ]);- expect(after.goal.config?.planningCheckpoint).toBeUndefined();- });-- it.each(['paused', 'changed'] as const)(- 'discards planning when the goal is %s during generation',- async (change) => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Original goal' });- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockImplementation(async () => {- await new GoalModel(serverDB, userId).update(- graph.goal.id,- change === 'paused' ? { status: 'paused' } : { requirement: 'New requirement' },- );- return { problemStatement: 'Old plan', tasks: [{ instruction: 'Old', title: 'Old task' }] };- });- await service.tick(graph.goal.id);- const after = await service.graph(graph.goal.id);- expect(after.nodes.filter((node) => node.kind === 'task')).toHaveLength(0);- expect(after.goal.config?.planningCheckpoint).toBeUndefined();- },- );-- it('rolls back an incomplete decomposition and allows a clean retry', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'Planned question',- tasks: [- { instruction: 'Collect sources', title: 'Research' },- { dependsOn: [0], instruction: 'Write report', title: 'Report' },- ],- });- const service = new GoalService(serverDB, userId);- const graph = await service.create({- problemDescription: 'Original question',- title: 'Atomic planning',- });- // Fail only when the planner reaches dependency insertion, after all nodes- // and their ownership edges have been written.- await serverDB.execute(- sql`ALTER TABLE goal_edges ADD CONSTRAINT fail_planning_dependency CHECK (kind <> 'depends_on')`,- );- try {- await expect(service.tick(graph.goal.id)).rejects.toThrow();- } finally {- await serverDB.execute(sql`ALTER TABLE goal_edges DROP CONSTRAINT fail_planning_dependency`);- }- const after = await service.graph(graph.goal.id);- expect(after.nodes.map((node) => node.id)).toEqual(graph.nodes.map((node) => node.id));- expect(after.nodes[0].description).toBe('Original question');- expect(after.edges).toHaveLength(0);- expect(- after.events.filter((event) => event.entityType === 'node' && event.eventType === 'created'),- ).toHaveLength(1);-- await service.tick(graph.goal.id);- const retried = await service.graph(graph.goal.id);- expect(retried.nodes.filter((node) => node.kind === 'task')).toHaveLength(2);- expect(retried.edges.filter((edge) => edge.kind === 'depends_on')).toHaveLength(1);- });-- it('falls back to a single Task when the planner fails, instead of stalling', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockRejectedValue(- new Error('model unavailable'),- );- const service = new GoalService(serverDB, userId);- const graph = await service.create({ problemDescription: 'ๅ่ฏ', title: 'Nothing to do' });-- const result = await service.tick(graph.goal.id);-- expect(result.outcome).toBe('advanced');- const tasks = (await service.graph(graph.goal.id)).nodes.filter((n) => n.kind === 'task');- expect(tasks).toHaveLength(1);- expect(tasks[0].description).toBe('ๅ่ฏ');- });-- it('parks a goal nothing can move so the sweep stops re-picking it', async () => {- // Every remaining Task is blocked and nothing runs to unblock it. Left- // `running` it is selected by every newest-first scan forever, and enough- // of them starve every other stalled goal out of the sweep's window.- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['A', 'B'], title: 'Deadlocked' });- const [a, b] = graph.nodes.filter((n) => n.kind === 'task');- const graphModel = new GoalGraphModel(serverDB, userId);- await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');- await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');-- const result = await service.tick(graph.goal.id);-- expect(result.outcome).toBe('no_progress');- expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');- expect(- await GoalModel.listStalled(serverDB, { staleBefore: new Date(Date.now() - 60_000) }),- ).not.toContainEqual(expect.objectContaining({ id: graph.goal.id }));- });-- it('leaves goal-level status transitions on the event trail', async () => {- // The coordinator parks and reopens goals constantly, but only node- // transitions used to be recorded โ `entity_type='goal'` events existed in- // the schema with no writer, so the lifecycle timeline was unreconstructable.- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['A', 'B'], title: 'Lifecycle trail' });- const [a, b] = graph.nodes.filter((n) => n.kind === 'task');- const graphModel = new GoalGraphModel(serverDB, userId);- await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');- await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');-- await service.tick(graph.goal.id); // deadlock โ no_frontier โ paused- await service.resume(graph.goal.id); // paused โ running-- const lifecycle = (await service.graph(graph.goal.id)).events.filter(- (event) => event.entityType === 'goal',- );-- // Same-millisecond events read back in either order; assert on content.- expect(lifecycle).toHaveLength(2);- expect(lifecycle).toContainEqual(- expect.objectContaining({- actorType: 'system',- eventType: 'updated',- reason: 'no eligible task to advance',- }),- );- expect(lifecycle).toContainEqual(- expect.objectContaining({ eventType: 'activated', reason: 'resumed by user' }),- );- });-- it('reopens a goal its deadline stopped when the deadline moves out', async () => {- // A calendar deadline is the long-horizon budget unit; extending it has to- // unstick the goal exactly like raising a round budget does. Two ticks:- // creating the responsible task costs nothing, the deadline gates the run.- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { schedule: { deadline: new Date(Date.now() - 1000).toISOString() } },- title: 'Overdue',- tasks: ['Too late to start'],- });-- await service.tick(graph.goal.id); // creates the responsible task- const stopped = await service.tick(graph.goal.id);- expect(stopped.message).toContain('Deadline passed');- expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');-- const extended = await service.setBudget(graph.goal.id, {- deadline: new Date(Date.now() + 3_600_000).toISOString(),- });-- expect(extended?.status).not.toBe('paused');- expect(extended?.config?.schedule?.deadline).toBeTruthy();- });-- it('dispatches a Task when the goal has no deadline', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Just task'], title: 'No deadline' });-- const result = await service.tick(graph.goal.id);-- expect(result.outcome).toBe('advanced');- });-- it('files a goal the agent created under that agent, not its owner', async () => {- // `/goal` is an agent making the call. `agentId` alone cannot say so โ the- // creation modal sets it too, and there the author is the person.- await serverDB- .insert(agents)- .values({ id: 'agt_goal_author', slug: 'agt-goal-author', userId });- const service = new GoalService(serverDB, userId);-- const graph = await service.create({- agentId: 'agt_goal_author',- createdByAgentId: 'agt_goal_author',- title: 'Agent-authored goal',- tasks: ['Do the thing'],- });-- const seeded = graph.events.filter((event) => ['created', 'linked'].includes(event.eventType));- expect(seeded.length).toBeGreaterThan(0);- expect(seeded.every((event) => event.actorType === 'agent')).toBe(true);- expect(seeded.every((event) => event.actorId === 'agt_goal_author')).toBe(true);- expect(graph.nodes.every((node) => node.createdByAgentId === 'agt_goal_author')).toBe(true);- });-- it('still files a goal the user created under the user, even on an agent page', async () => {- // The modal passes `agentId` for assignment; the author is the person.- await serverDB.insert(agents).values({ id: 'agt_assignee', slug: 'agt-assignee', userId });- const service = new GoalService(serverDB, userId);-- const graph = await service.create({- agentId: 'agt_assignee',- title: 'User-authored goal',- tasks: ['Do the thing'],- });-- const seeded = graph.events.filter((event) => ['created', 'linked'].includes(event.eventType));- expect(seeded.every((event) => event.actorType === 'user')).toBe(true);- expect(seeded.every((event) => event.actorId === userId)).toBe(true);- });-- it('separates what the coordinator decided from what the user asked for', async () => {- // The audit trail recorded every transition as the goal's owner, so "what did- // the system decide on its own" could not be answered from product data.- const service = new GoalService(serverDB, userId);- const graph = await service.create({ tasks: ['Do the thing'], title: 'Attributed goal' });-- // Seeding is the user's ask; claiming the Task and binding its runner is not.- await service.tick(graph.goal.id);-- const { events, nodes } = await service.graph(graph.goal.id);- const task = nodes.find((node) => node.kind === 'task')!;- const actorsFor = (eventType: string, entityId: string) =>- events- .filter((event) => event.eventType === eventType && event.entityId === entityId)- .map((event) => ({ actorId: event.actorId, actorType: event.actorType }));-- expect(actorsFor('created', task.id)).toEqual([{ actorId: userId, actorType: 'user' }]);- expect(actorsFor('activated', task.id)).toEqual([- { actorId: GOAL_COORDINATOR_ACTOR_ID, actorType: 'system' },- ]);- expect(events.some((event) => event.actorType === 'system')).toBe(true);- });-- it('keeps the overall requirement as background while making the current Task authoritative', async () => {- const service = new GoalService(serverDB, userId);- const requirement = `Generate verified training data. ${'Detailed acceptance evidence. '.repeat(20)}`;- const graph = await service.create({- requirement,- title: 'Long requirement goal',- tasks: ['Generate training data'],- });-- const created = await service.tick(graph.goal.id);- const task = await new TaskModel(serverDB, userId).findById(created.taskId!);-- expect(created.outcome).toBe('advanced');- expect(task?.description).toBe('Generate training data');- expect(task?.instruction).toContain(requirement);- expect(task?.instruction).toContain(- 'Current Task contract (authoritative execution scope): Generate training data',- );- expect(task?.instruction).toContain('Do not implement, validate, or pre-empt any sibling');- expect(task?.instruction).toContain(- 'missing or broken capabilities within its scope are work to implement or repair',- );- expect(task?.instruction).toContain(- 'resolve the prerequisite before repeating the same checks',- );- expect(task?.instruction).toContain(- 'For an investigation-only Task, deliver supported findings',- );- expect(task?.instruction).toContain('do not silently expand into implementation');- expect(task?.instruction).toContain('run it inside this Task');- expect(task?.instruction).toContain(- 'Include the relevant artifact contents or exact excerpts and the raw outputs of decisive verification commands',- );- });-- it('gates every responsible task with a Task-scoped Acceptance requirement', async () => {- const service = new GoalService(serverDB, userId);- const agentId = 'goal-work-verifier-agent';- await serverDB.insert(agents).values({ id: agentId, title: 'Goal worker', userId });- const graph = await service.create({- agentId,- requirement: 'Generate data, then train and evaluate a model.',- title: 'Two-stage experiment',- tasks: ['Generate isolated data'],- });-- const created = await service.tick(graph.goal.id);- const taskModel = new TaskModel(serverDB, userId);- const task = await taskModel.findById(created.taskId!);- const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(- 'task',- created.taskId!,- );-- expect(taskModel.shouldPauseOnTopicComplete(task!)).toBe(false);- expect(task?.config).not.toHaveProperty('verify');- expect(acceptance).toMatchObject({ config: { enabled: true } });- expect(acceptance?.config).not.toHaveProperty('verifierAgentId');- expect(acceptance?.requirement).toContain('Verify only this Task: Generate isolated data.');- expect(acceptance?.requirement).toContain(- 'Ignore sibling and downstream Task deliverables; they are verified by their own acceptance runs.',- );- });-- it('requires a Goal-level Acceptance Task before marking the complete goal achieved', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- requirement: 'A runnable minimal training loop with evidence',- title: 'Reproduce Ornith training',- tasks: ['Implement minimal training loop'],- });-- const created = await service.tick(graph.goal.id);- expect(created).toMatchObject({ outcome: 'advanced' });- expect(created.taskId).toBeDefined();-- const waitingGraph = await service.graph(graph.goal.id);- expect(waitingGraph.nodes.find((node) => node.kind === 'task')).toMatchObject({- status: 'active',- taskId: created.taskId,- });- expect(waitingGraph.workVersions).toHaveLength(1);- const responsibleTask = await taskModel.findById(created.taskId!);- expect(responsibleTask).toBeDefined();- expect(taskModel.shouldPauseOnTopicComplete(responsibleTask!)).toBe(false);-- await taskModel.updateStatus(created.taskId!, 'completed');- const synthesized = await service.tick(graph.goal.id);- expect(synthesized.outcome).toBe('advanced');-- const evolved = await service.graph(graph.goal.id);- expect(evolved.nodes.some((node) => node.kind === 'finding')).toBe(true);- expect(evolved.edges.some((edge) => edge.kind === 'produces')).toBe(true);-- const goalAcceptanceCreated = await service.tick(graph.goal.id);- expect(goalAcceptanceCreated).toMatchObject({- message: 'Created Goal-level acceptance Task for the remaining contract',- outcome: 'advanced',- });- const acceptanceWork = (await service.graph(graph.goal.id)).nodes.find(- (node) => node.id === goalAcceptanceCreated.nodeId,- );-- const acceptanceTaskCreated = await service.tick(graph.goal.id);- expect(acceptanceTaskCreated).toMatchObject({ outcome: 'advanced' });- const acceptanceTask = await taskModel.findById(acceptanceTaskCreated.taskId!);- const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(- 'task',- acceptanceTaskCreated.taskId!,- );- expect(acceptanceTask?.instruction).toContain(- 'Complete and prove the overall Goal acceptance requirement',- );- expect(acceptance?.requirement).toContain('A runnable minimal training loop with evidence');- expect(acceptance?.requirement).toContain(- 'An accurate gap analysis, a report that the Goal is not accepted',- );- expect(acceptance?.requirement).toContain('the verdict MUST be failed');- expect(acceptanceWork?.description).toContain('Do not repeat expensive or destructive work');- expect(acceptanceWork?.description).toContain('Run only the missing or stale checks');-- await taskModel.updateStatus(acceptanceTaskCreated.taskId!, 'completed');- expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');-- const achieved = await service.tick(graph.goal.id);- expect(achieved).toMatchObject({- message: 'Goal-level acceptance passed',- outcome: 'achieved',- });- const finalGraph = await service.graph(graph.goal.id);- expect(finalGraph.goal.status).toBe('achieved');- // The verdict closes the map too: the seeded problem node has no other- // resolution path, and must not read "active" on an achieved goal.- expect(finalGraph.nodes.find((node) => node.kind === 'problem')).toMatchObject({- status: 'resolved',- });- });-- it('does not mark a required goal achieved when only its initial Task is complete', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- requirement: 'Return a supplier list with fixed prices.',- title: 'Find BW150 suppliers and fixed prices',- tasks: ['Verify the BW150 product identity'],- });-- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'completed');- await service.tick(graph.goal.id);-- const result = await service.tick(graph.goal.id);- const current = await service.graph(graph.goal.id);-- expect(result).toMatchObject({ outcome: 'advanced' });- expect(current.goal.status).not.toBe('achieved');- expect(current.nodes).toContainEqual(- expect.objectContaining({- kind: 'task',- status: 'proposed',- title: 'Complete full Goal acceptance',- }),- );- });-- it('creates only one Goal-level Acceptance Task when terminal ticks race', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- requirement: 'Return three verified supplier quotes.',- title: 'Find supplier quotes',- tasks: ['Research suppliers'],- });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'completed');- await service.tick(graph.goal.id);-- await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);- const current = await service.graph(graph.goal.id);- const acceptanceWorks = current.nodes.filter(- (node) => node.title === 'Complete full Goal acceptance',- );-- expect(acceptanceWorks).toHaveLength(1);- expect(- current.edges.filter(- (edge) => edge.kind === 'decomposes' && edge.targetNodeId === acceptanceWorks[0].id,- ),- ).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());- });-- it('builds the Goal-level Acceptance Task on the units a batch delivered', async () => {- vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({- problemStatement: 'ๆ 7 ไธชๅๆ็ store ่ฟ็งปๅฐ replica',- rollout: {- recipeOutline: 'ๆ store ๆขๆ replica ๆฏๆ็ๅฎ็ฐ',- repeatable: true,- unitCount: 7,- units: Array.from({ length: 7 }, (_, i) => `Unit ${i + 1}`),- variants: [],- },- tasks: Array.from({ length: 5 }, (_, i) => ({- dependsOn: [],- instruction: `ๆ src/store/store${i + 1}.ts ๆขๆ replica ๅฎ็ฐ`,- title: `Unit ${i + 1}`,- })),- });- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { rollout: { minHomogeneousUnits: 5, trigger: 'full' } },- requirement: 'Migrate every store.',- title: 'Batch to acceptance',- });-- let acceptance;- for (let i = 0; i < 30 && !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');- }-- // The report walks back from acceptance; the batch's units must be on that path.- const current = await service.graph(graph.goal.id);- const units = current.nodes- .filter((node) => /^Unit \d+$/.test(node.title) && node.status === 'resolved')- .map((node) => node.id);- expect(acceptance).toBeTruthy();- expect(units).toHaveLength(7);- expect(- current.edges- .filter((edge) => edge.kind === 'depends_on' && edge.sourceNodeId === acceptance!.id)- .map((edge) => edge.targetNodeId)- .sort(),- ).toEqual(units.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- // not be created โ and the goal must not sit `running` reporting- // `no_progress`, or every sweep would re-tick it for the whole wait.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const graph = await service.create({- config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },- requirement: 'Grow the account',- tasks: ['Publish the first posts'],- title: 'Measured goal',- });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'completed');- await service.tick(graph.goal.id);-- // Nothing measured yet โ "never observed" is not "satisfied".- const unmeasured = await service.tick(graph.goal.id);- expect(unmeasured).toMatchObject({ outcome: 'no_progress' });- expect(unmeasured.message).toContain('no observation');- expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');- expect(- (await service.graph(graph.goal.id)).nodes.some(- (n) => n.title === 'Complete full Goal acceptance',- ),- ).toBe(false);-- // A sample that is still short leaves it parked and is not worth an advance.- const short = await service.recordObservation(graph.goal.id, {- key: 'followers',- value: 400,- });- expect(short.shouldAdvance).toBe(false);- expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');-- // The number lands: the goal reopens and falls through to its delivery- // contract.- const cleared = await service.recordObservation(graph.goal.id, {- key: 'followers',- value: 1200,- });- expect(cleared.shouldAdvance).toBe(true);- expect((await goalModel.findById(graph.goal.id))?.status).toBe('running');-- const advanced = await service.tick(graph.goal.id);- expect(advanced).toMatchObject({ outcome: 'advanced' });- expect(- (await service.graph(graph.goal.id)).nodes.some(- (n) => n.title === 'Complete full Goal acceptance',- ),- ).toBe(true);- });-- /** A goal parked by the gate, one clause short of acceptance. */- const parkedOnGate = async (service: GoalService) => {- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },- requirement: 'Grow the account',- tasks: ['Publish the first posts'],- title: 'Parked on a measurement',- });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'completed');- await service.tick(graph.goal.id);- await service.tick(graph.goal.id);- return graph.goal.id;- };-- it('reopens a goal parked before the pause marker existed', async () => {- // Rows parked by the parent implementation โ and any parked by an old- // worker mid-deploy โ carry no marker. Requiring one strictly would strand- // them until somebody pressed Resume by hand, so the transition's recorded- // actor stands in for it.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const goalId = await parkedOnGate(service);-- // Exactly what a pre-marker row looks like.- const parked = (await goalModel.findById(goalId))!;- await goalModel.update(goalId, { config: { ...parked.config, pausedBy: undefined } });-- const cleared = await service.recordObservation(goalId, { key: 'followers', value: 5000 });-- expect(cleared.shouldAdvance).toBe(true);- expect((await goalModel.findById(goalId))?.status).toBe('running');- });-- it('does not let an observation restart a goal the coordinator parked for another reason', async () => {- // The coordinator also parks goals that are deadlocked or out of budget.- // Those carry no marker either once they predate it, so the fallback has to- // read *why* it parked โ not just that it was the coordinator.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const graph = await service.create({- config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },- requirement: 'Deadlocked before the gate',- tasks: ['A', 'B'],- title: 'Parked with work outstanding',- });- const [a, b] = graph.nodes.filter((n) => n.kind === 'task');- const graphModel = new GoalGraphModel(serverDB, userId);- await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');- await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');-- await service.tick(graph.goal.id); // deadlock โ no_frontier โ paused- expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');-- const satisfying = await service.recordObservation(graph.goal.id, {- key: 'followers',- value: 5000,- });-- expect(satisfying.shouldAdvance).toBe(false);- expect((await goalModel.findById(graph.goal.id))?.status).toBe('paused');- });-- it('leaves a deliberately paused goal alone even when the measurement lands', async () => {- // The hard case: same status, same terminal phase, same clauses as a goal- // the coordinator parked. Only the recorded pause reason tells them apart,- // and without it a satisfying sample would restart a goal somebody stopped- // on purpose โ and run its acceptance work.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const goalId = await parkedOnGate(service);- await service.pause(goalId);-- const satisfying = await service.recordObservation(goalId, { key: 'followers', value: 5000 });-- expect(satisfying.shouldAdvance).toBe(false);- expect((await goalModel.findById(goalId))?.status).toBe('paused');- expect(- (await service.graph(goalId)).nodes.some((n) => n.title === 'Complete full Goal acceptance'),- ).toBe(false);- });-- it('resumes a user-paused goal only through resume, and then it advances again', async () => {- // The other half: once the person lifts their own pause, the goal is the- // coordinator's again.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const goalId = await parkedOnGate(service);- await service.pause(goalId);- await service.recordObservation(goalId, { key: 'followers', value: 5000 });-- await service.resume(goalId);-- expect(await service.tick(goalId)).toMatchObject({ outcome: 'advanced' });- });-- it('unblocks a parked goal when its last clause is dropped', async () => {- // `setMetricCriteria(id, [])` is the advertised way to clear the gate. It- // used to leave the goal parked on a gate that no longer existed, so the- // scheduled advance ticked straight back out as `goal_paused` and only a- // manual resume could move it.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const goalId = await parkedOnGate(service);- expect((await goalModel.findById(goalId))?.status).toBe('paused');-- await service.setMetricCriteria(goalId, []);-- expect((await goalModel.findById(goalId))?.status).toBe('running');- expect(await service.tick(goalId)).toMatchObject({ outcome: 'advanced' });- });-- it('unblocks a parked goal when a clause is relaxed below the measurement', async () => {- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const goalId = await parkedOnGate(service);- await service.recordObservation(goalId, { key: 'followers', value: 400 });- expect((await goalModel.findById(goalId))?.status).toBe('paused');-- await service.setMetricCriteria(goalId, [{ key: 'followers', target: 100 }]);-- expect((await goalModel.findById(goalId))?.status).toBe('running');- });-- it('keeps the numeric gate when the delivery criteria are bound or rebound', async () => {- // Both writers used to rebuild `config.acceptance` from `criteriaIds`- // alone, so declaring criteria โ at creation or later from the goal page โ- // silently dropped a live measured gate and let the goal be accepted- // without it.- const service = new GoalService(serverDB, userId);- const graph = await service.create({- config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },- criteria: [{ title: 'Ship the launch post' }],- requirement: 'Grow the account',- tasks: ['Publish the first posts'],- title: 'Both halves of acceptance',- });-- const created = await new GoalModel(serverDB, userId).findById(graph.goal.id);- expect(created?.config?.acceptance?.metrics).toEqual([{ key: 'followers', target: 1000 }]);- expect(created?.config?.acceptance?.criteriaIds).toHaveLength(1);-- await service.setAcceptanceCriteria(graph.goal.id, []);-- const rebound = await new GoalModel(serverDB, userId).findById(graph.goal.id);- expect(rebound?.config?.acceptance?.metrics).toEqual([{ key: 'followers', target: 1000 }]);- });-- it('merges a declared clause into the server-side list instead of replacing it', async () => {- // Two editors declaring from the same stale snapshot must not erase each- // other: merge upserts by key against the list as it stands on the server.- const service = new GoalService(serverDB, userId);- const goalModel = new GoalModel(serverDB, userId);- const graph = await service.create({- config: { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },- requirement: 'Grow the account',- tasks: ['Publish'],- title: 'Merge-mode goal',- });-- // A "concurrent" declaration this client never saw.- await service.setMetricCriteria(- graph.goal.id,- [{ key: 'retention', op: 'gte', target: 80 }],- 'merge',- );- // This client merges its own clause from a snapshot that predates it.- await service.setMetricCriteria(- graph.goal.id,- [{ key: 'followers', target: 2000, title: '็ฒไธ' }],- 'merge',- );-- const metrics = (await goalModel.findById(graph.goal.id))?.config?.acceptance?.metrics;- expect(metrics).toHaveLength(2);- expect(metrics).toContainEqual({ key: 'retention', op: 'gte', target: 80 });- // Same-key merge upserts rather than duplicating.- expect(metrics).toContainEqual({ key: 'followers', target: 2000, title: '็ฒไธ' });- });-- it('declares numeric clauses after creation without touching the criteria binding', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- criteria: [{ title: 'Ship the launch post' }],- requirement: 'Grow the account',- tasks: ['Publish the first posts'],- title: 'Late-declared gate',- });-- await service.setMetricCriteria(graph.goal.id, [{ key: 'churn', op: 'lte', target: 5 }]);-- const updated = await new GoalModel(serverDB, userId).findById(graph.goal.id);- expect(updated?.config?.acceptance).toMatchObject({- criteriaIds: expect.any(Array),- metrics: [{ key: 'churn', op: 'lte', target: 5 }],- });- expect(updated?.config?.acceptance?.criteriaIds).toHaveLength(1);- });-- it('records what the measured decision read, not just its verdict', async () => {- // A replay has to see the number the live run saw โ the same reason the- // deadline verdict travels with the budget.- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const metricModel = new MetricModel(serverDB, userId);- const graph = await service.create({- config: { acceptance: { metrics: [{ key: 'churn', op: 'lte', target: 5 }] } },- requirement: 'Keep churn down',- tasks: ['Ship retention fixes'],- title: 'Traced measurement',- });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'completed');- await service.tick(graph.goal.id);-- const series = (await metricModel.ensure({- key: 'churn',- subjectId: graph.goal.id,- subjectType: 'goal',- }))!;- await metricModel.addPoint(series.id, {- actorType: 'system',- observedAt: new Date('2026-09-01T00:00:00Z'),- sourceType: 'probe',- value: 9,- });-- const observed: GoalTickObservation[] = [];- await service.tick(graph.goal.id, { onDecision: (o) => observed.push(o) });-- expect(observed.at(-1)!.metricCriteria).toMatchObject({- allMet: false,- criteria: [{ key: 'churn', met: false, op: 'lte', target: 5, value: 9 }],- });- });-- it('evolves a failed task into a durable decision gate', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Risky task'], title: 'Failure recovery' });- const created = await service.tick(graph.goal.id);-- await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });- const waiting = await service.tick(graph.goal.id);- expect(waiting.outcome).toBe('waiting_human');-- const gated = await service.graph(graph.goal.id);- const decision = gated.decisions[0];- expect(decision).toMatchObject({ recommendedOptionId: 'retry', status: 'pending' });- expect(gated.nodes.some((node) => node.kind === 'decision')).toBe(true);-- await service.decide(graph.goal.id, decision.id, 'retire', 'This branch is not useful');- const achieved = await service.tick(graph.goal.id);- expect(achieved.outcome).toBe('achieved');- });-- it('reports the effects a tick actually produced, not just its outcome', async () => {- // The rollup counts gates and findings from these effects, so a branch that- // forgets to report one reads as "no human was ever involved" โ silently,- // and only in the trace. Driving the real path is the only thing that- // catches it; a synthetic observation always agrees with itself.- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Risky task'], title: 'Effect reporting' });-- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });-- const observed: GoalTickObservation[] = [];- const gated = await service.tick(graph.goal.id, {- onDecision: (observation) => observed.push(observation),- });-- expect(gated.outcome).toBe('waiting_human');- expect(observed.at(-1)!.effects).toContainEqual(- expect.objectContaining({ detail: 'Verifier rejected output', type: 'opened_decision' }),- );-- // And the other half: a completed task folds into a finding, which is what- // `findingsTotal` counts.- const decision = (await service.graph(graph.goal.id)).decisions[0];- await service.decide(graph.goal.id, decision.id, 'retry');- await taskModel.updateStatus(created.taskId!, 'completed');-- const consumed: GoalTickObservation[] = [];- await service.tick(graph.goal.id, { onDecision: (o) => consumed.push(o) });-- expect(consumed.at(-1)!.effects).toContainEqual(- expect.objectContaining({ detail: 'finding', type: 'created_node' }),- );- });-- it('refuses to start a task once the goal is at its concurrency limit', async () => {- // The planner's cap check is a fast path over a snapshot; two overlapping- // advances can both read it below the limit. The count and the claim are- // therefore taken together under a per-goal lock, and this is the assertion- // that the enforcement โ not the fast path โ is what holds.- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockResolvedValue({ operationId: 'op-cap', taskId: 'placeholder' } as never);-- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { maxConcurrentTasks: 1 },- title: 'Capped goal',- tasks: ['First', 'Second'],- });-- // Fill the single slot.- const first = await service.tick(graph.goal.id);- await service.tick(graph.goal.id);- await taskModel.updateStatus(first.taskId!, 'running');- runSpy.mockClear();-- // The second task exists and is unblocked, but there is no room for it.- const capped = await service.tick(graph.goal.id);-- expect(capped.outcome).toBe('waiting_external');- expect(runSpy).not.toHaveBeenCalled();- });-- it('automatically retries failed Task verification within policy budget', async () => {- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({- agentId: 'agent-recovery',- assistantMessageId: 'message-assistant',- autoStarted: true,- createdAt: new Date().toISOString(),- message: 'started',- operationId: 'op-recovery',- status: 'running',- success: true,- taskId: 'placeholder',- taskIdentifier: 'T-recovery',- timestamp: new Date().toISOString(),- topicId: 'topic-recovery',- userMessageId: 'message-user',- });- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: {- exploration: { instruction: 'Compare evidence', maxExperiments: 3 },- recovery: { maxAttemptsPerTask: 3, maxStepsPerRun: 500 },- },- title: 'Recover BW 150 research',- tasks: ['Verify Micron BW 150 suppliers'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'paused', {- error: 'Delivery did not pass verification.',- });-- const recovered = await service.tick(graph.goal.id);-- expect(recovered).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });- expect(runSpy).toHaveBeenCalledWith({- maxSteps: 500,- taskId: created.taskId,- trigger: 'goal',- });- const afterRetry = await service.graph(graph.goal.id);- expect(afterRetry.decisions).toHaveLength(0);- expect(afterRetry.nodes.filter((node) => node.kind === 'task')).toEqual([- expect.objectContaining({ id: created.nodeId, taskId: created.taskId }),- ]);- expect(afterRetry.edges.filter((edge) => edge.kind === 'derived_from')).toHaveLength(0);- });-- it('reclaims a stale running Task operation and starts the next attempt', async () => {- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({- agentId: 'agent-recovery',- assistantMessageId: 'message-assistant',- autoStarted: true,- createdAt: new Date().toISOString(),- message: 'started',- operationId: 'op-recovery',- status: 'running',- success: true,- taskId: 'placeholder',- taskIdentifier: 'T-recovery',- timestamp: new Date().toISOString(),- topicId: 'topic-recovery',- userMessageId: 'message-user',- });- vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([- { operationId: 'op-stale', topicId: 'topic-stale' } as never,- ]);- const timeoutSpy = vi- .spyOn(TaskTopicModel.prototype, 'updateStatus')- .mockResolvedValue(undefined);- const settleSpy = vi- .spyOn(AgentOperationModel.prototype, 'settleStaleRunning')- .mockResolvedValue(true);-- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: {- recovery: { maxAttemptsPerTask: 3, operationLeaseTimeoutMs: 60_000 },- },- title: 'Recover interrupted work',- tasks: ['Run a durable experiment'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'running');-- const recovered = await service.tick(graph.goal.id);-- expect(settleSpy).toHaveBeenCalledWith('op-stale', expect.any(Date), undefined);- expect(timeoutSpy).toHaveBeenCalledWith(created.taskId, 'topic-stale', 'timeout');- expect(runSpy).toHaveBeenCalledWith({- maxSteps: undefined,- taskId: created.taskId,- trigger: 'goal',- });- expect(recovered).toMatchObject({- message: expect.stringContaining('Recovered abandoned task'),- outcome: 'waiting_external',- taskId: created.taskId,- });- });-- it('charges stale Task usage before checking the replacement budget', async () => {- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([- { operationId: 'op-stale-cost', topicId: 'topic-stale-cost' } as never,- ]);- vi.spyOn(TaskTopicModel.prototype, 'updateStatus').mockResolvedValue(undefined);- vi.spyOn(AgentRuntimeCoordinator.prototype, 'getOperationMetadata').mockResolvedValue({- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- status: 'running',- totalCost: 0.75,- totalSteps: 2,- });-- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 3, operationLeaseTimeoutMs: 60_000 } },- maxTotalCost: 0.5,- title: 'Respect abandoned Work cost',- tasks: ['Run an expensive experiment'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'running');- await new AgentOperationModel(serverDB, userId).recordStart({- operationId: 'op-stale-cost',- taskId: created.taskId,- });- await serverDB- .update(agentOperations)- .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })- .where(eq(agentOperations.id, 'op-stale-cost'));-- const recovered = await service.tick(graph.goal.id);-- expect(runSpy).not.toHaveBeenCalled();- expect(recovered).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });- expect(await new AgentOperationModel(serverDB, userId).findById('op-stale-cost')).toMatchObject(- {- status: 'abandoned',- totalCost: 0.75,- },- );- });-- describe('a running topic whose run already ended', () => {- const setup = async (title: string, operationId: string, completedAt: Date) => {- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockResolvedValue({ operationId: 'op-next', success: true } as never);- vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([- {- createdAt: new Date('2026-01-01T00:00:00.000Z'),- operationId,- topicId: `topic-${operationId}`,- } as never,- ]);- const timeoutSpy = vi- .spyOn(TaskTopicModel.prototype, 'updateStatus')- .mockResolvedValue(undefined);-- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 3, operationLeaseTimeoutMs: 60_000 } },- title,- tasks: ['Run a device experiment'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'running');-- // The gateway watchdog already settled the run as an error, but the task- // lifecycle never heard about it, so the topic still reads `running`.- const operationModel = new AgentOperationModel(serverDB, userId);- await operationModel.recordStart({ operationId, taskId: created.taskId });- await operationModel.recordCompletion(operationId, {- completedAt,- completionReason: 'error',- status: 'error',- });-- return { created, graph, runSpy, service, timeoutSpy };- };-- it('reclaims it once the run has been over for longer than the lease', async () => {- const { created, graph, runSpy, service, timeoutSpy } = await setup(- 'Recover a watchdog-abandoned run',- 'op-abandoned',- new Date('2026-01-01T00:10:00.000Z'),- );-- const recovered = await service.tick(graph.goal.id);-- expect(timeoutSpy).toHaveBeenCalledWith(created.taskId, 'topic-op-abandoned', 'timeout');- expect(runSpy).toHaveBeenCalledWith(- expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),- );- expect(recovered).toMatchObject({- message: expect.stringContaining('Recovered abandoned task'),- outcome: 'waiting_external',- taskId: created.taskId,- });- });-- it('leaves a run parked for a client alone however long it has waited', async () => {- const { created, graph, runSpy, service, timeoutSpy } = await setup(- 'Wait for a local-model client',- 'op-waiting-client',- new Date('2026-01-01T00:10:00.000Z'),- );- // Parked in waiting_for_client (U4c): resumable until its own expiry.- await serverDB- .update(agentOperations)- .set({ completionReason: 'waiting_for_client', status: 'waiting_for_client' })- .where(eq(agentOperations.id, 'op-waiting-client'));-- const waiting = await service.tick(graph.goal.id);-- expect(timeoutSpy).not.toHaveBeenCalled();- expect(runSpy).not.toHaveBeenCalled();- expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });- });-- it('leaves a run that just ended to its own completion hook', async () => {- const { created, graph, runSpy, service, timeoutSpy } = await setup(- 'Wait for the completion hook',- 'op-just-ended',- new Date(),- );-- const waiting = await service.tick(graph.goal.id);-- expect(timeoutSpy).not.toHaveBeenCalled();- expect(runSpy).not.toHaveBeenCalled();- expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });- });- });-- it('does not reclaim a running Task operation without a persisted topic id', async () => {- vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([- { operationId: 'op-without-topic', topicId: null } as never,- ]);- const settleSpy = vi.spyOn(AgentOperationModel.prototype, 'settleStaleRunning');-- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { operationLeaseTimeoutMs: 60_000 } },- title: 'Wait for topic persistence',- tasks: ['Run a durable experiment'],- });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'running');-- const waiting = await service.tick(graph.goal.id);-- expect(settleSpy).not.toHaveBeenCalled();- expect(waiting).toMatchObject({- message: expect.stringContaining('is running'),- outcome: 'waiting_external',- taskId: created.taskId,- });- });-- it('starts a ready sibling Task even when a running Task row is older than the operation lease', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { operationLeaseTimeoutMs: 60_000 } },- title: 'Keep parallel work moving',- tasks: ['Long-running experiment', 'Independent analysis'],- });- const running = await service.tick(graph.goal.id);- await taskModel.updateStatus(running.taskId!, 'running');- await serverDB- .update(tasks)- .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })- .where(eq(tasks.id, running.taskId!));-- const sibling = await service.tick(graph.goal.id);-- expect(sibling).toMatchObject({ outcome: 'advanced' });- expect(sibling.taskId).not.toBe(running.taskId);- });-- it('rolls back the operation reclaim when recovery bookkeeping fails', async () => {- vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([- { operationId: 'op-atomic-recovery', topicId: 'topic-stale' } as never,- ]);- vi.spyOn(TaskTopicModel.prototype, 'updateStatus').mockRejectedValueOnce(- new Error('topic update failed'),- );-- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const operationModel = new AgentOperationModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { operationLeaseTimeoutMs: 60_000 } },- title: 'Atomic abandoned recovery',- tasks: ['Run a durable experiment'],- });- const created = await service.tick(graph.goal.id);- await taskModel.updateStatus(created.taskId!, 'running');- await operationModel.recordStart({ operationId: 'op-atomic-recovery' });- await serverDB- .update(agentOperations)- .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })- .where(eq(agentOperations.id, 'op-atomic-recovery'));-- await expect(service.tick(graph.goal.id)).rejects.toThrow('topic update failed');-- expect((await operationModel.findById('op-atomic-recovery'))?.status).toBe('running');- expect((await taskModel.findById(created.taskId!))?.status).toBe('running');- });-- it('resumes automatic recovery after the atomic bookkeeping transaction committed', async () => {- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({- agentId: 'agent-recovery',- assistantMessageId: 'message-assistant',- autoStarted: true,- createdAt: new Date().toISOString(),- message: 'started',- operationId: 'op-recovery-next',- status: 'running',- success: true,- taskId: 'placeholder',- taskIdentifier: 'T-recovery',- timestamp: new Date().toISOString(),- topicId: 'topic-recovery-next',- userMessageId: 'message-user',- });- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 3 } },- title: 'Resume abandoned recovery',- tasks: ['Run a durable experiment'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'paused', {- error: 'Goal Task operation lease expired.',- });-- const recovered = await service.tick(graph.goal.id);-- expect(runSpy).toHaveBeenCalledOnce();- expect(recovered).toMatchObject({- message: expect.stringContaining('Recovered abandoned task'),- outcome: 'waiting_external',- });- });-- it('opens the decision gate only after the Task attempt budget is exhausted', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 1 } },- title: 'Bounded recovery',- tasks: ['Verify Micron BW 150 suppliers'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'paused', {- error: 'Delivery did not pass verification.',- });-- const waiting = await service.tick(graph.goal.id);-- expect(waiting.outcome).toBe('waiting_human');- expect((await service.graph(graph.goal.id)).decisions).toHaveLength(1);- });-- it('fails the Goal when terminal acceptance is retired after recovery is exhausted', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 1 } },- requirement: 'Return three verified supplier quotes.',- title: 'Bounded terminal acceptance',- tasks: ['Complete full Goal acceptance'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'paused', {- error: 'Delivery did not pass verification.',- });- await service.tick(graph.goal.id);- const gated = await service.graph(graph.goal.id);-- expect(gated.decisions[0].options).toContainEqual({ id: 'fail', label: 'Fail goal' });- await service.decide(graph.goal.id, gated.decisions[0].id, 'fail', 'No valid third quote');-- expect(await service.tick(graph.goal.id)).toMatchObject({ outcome: 'failed' });- expect((await service.graph(graph.goal.id)).goal.status).toBe('failed');- });-- it('offers retry, abandon and fail on a failed terminal acceptance; abandon cancels the Goal', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 1 } },- requirement: 'Return three verified supplier quotes.',- title: 'Abandoned terminal acceptance',- tasks: ['Complete full Goal acceptance'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'paused', {- error: 'Delivery did not pass verification.',- });- await service.tick(graph.goal.id);- const gated = await service.graph(graph.goal.id);-- expect(gated.decisions[0].options?.map((option) => option.id)).toEqual([- 'retry',- 'retire',- 'fail',- ]);- await service.decide(graph.goal.id, gated.decisions[0].id, 'retire');-- const after = await service.graph(graph.goal.id);- expect(after.goal.status).toBe('canceled');- expect(after.nodes.find((node) => node.taskId === created.taskId)?.status).toBe('retired');- });-- it('reopens an achieved Goal when its owner requests changes, and reworks the acceptance', async () => {- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- requirement: 'A one-page onboarding checklist',- title: 'Reworked delivery',- tasks: ['Draft the checklist'],- });- const work = await service.tick(graph.goal.id);- await taskModel.updateStatus(work.taskId!, 'completed');- await service.tick(graph.goal.id);- await service.tick(graph.goal.id);- const acceptance = await service.tick(graph.goal.id);- await taskModel.updateStatus(acceptance.taskId!, 'completed');- await service.tick(graph.goal.id);- expect((await service.tick(graph.goal.id)).outcome).toBe('achieved');-- const reopened = await service.reopenForChanges(acceptance.taskId!, 'Add a day-one agenda');-- expect(reopened).toBe(graph.goal.id);- const after = await service.graph(graph.goal.id);- expect(after.goal.status).toBe('running');- expect(after.goal.completedAt).toBeNull();- expect(after.goal.config?.changeRequest).toMatchObject({- comment: 'Add a day-one agenda',- taskId: acceptance.taskId,- });- expect(after.nodes.find((node) => node.taskId === acceptance.taskId)?.status).toBe('active');- expect((await taskModel.findById(acceptance.taskId!))?.status).toBe('backlog');-- // The coordinator dispatches the rework instead of reading the Goal as done.- const rework = await service.tick(graph.goal.id);- expect(rework.message).toMatch(/^Started task /);- expect(TaskRunnerService.prototype.runTask).toHaveBeenLastCalledWith(- expect.objectContaining({ taskId: acceptance.taskId }),- );- });-- it('does not reopen a Goal the owner already ended', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({- requirement: 'A one-page onboarding checklist',- title: 'Ended delivery',- tasks: ['Complete full Goal acceptance'],- });- const created = await service.tick(graph.goal.id);- await new GoalModel(serverDB, userId).updateStatus(graph.goal.id, 'canceled');-- expect(await service.reopenForChanges(created.taskId!, 'Too late')).toBeUndefined();- expect((await service.graph(graph.goal.id)).goal.status).toBe('canceled');- });-- it('respects a manually paused responsible task without rerunning it', async () => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({ tasks: ['Wait for review'], title: 'Paused task' });- const created = await service.tick(graph.goal.id);-- await taskModel.updateStatus(created.taskId!, 'paused', { error: null });- const waiting = await service.tick(graph.goal.id);-- expect(waiting).toMatchObject({- outcome: 'waiting_human',- taskId: created.taskId,- });- expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);- });-- describe('a Task that could not reach its device', () => {- const DEVICE_NOT_FOUND_HEADLINE =- 'The device this agent is bound to is no longer registered with the connection service. Reconnect the device, or bind this agent to another online device.';- // A workspace goal whose agent runs on its owner's personal device: the- // route the dispatch recorded names the personal pool, not the goal's.- const route = { deviceId: 'device-laptop', userId: 'device-owner' };-- const setup = async (title: string) => {- vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 3 } },- title,- tasks: ['Reproduce on the bound device'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });-- const operationModel = new AgentOperationModel(serverDB, userId);- await operationModel.recordStart({ operationId: 'op-dispatch', taskId: created.taskId });- await operationModel.recordCompletion('op-dispatch', {- completedAt: new Date(),- completionReason: 'error',- error: { deviceRoute: route, message: DEVICE_NOT_FOUND_HEADLINE },- status: 'error',- });- vi.spyOn(TaskTopicModel.prototype, 'findWithHandoff').mockResolvedValue([- { operationId: 'op-dispatch' } as never,- ]);-- await taskModel.updateStatus(created.taskId!, 'paused', {- error: DEVICE_NOT_FOUND_HEADLINE,- });- return { created, graph, service, taskModel };- };-- it('waits for the device instead of asking a person', async () => {- const listSpy = vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');- const { created, graph, service } = await setup('Device went to sleep');-- const waiting = await service.tick(graph.goal.id);-- expect(listSpy).toHaveBeenCalledWith('device-owner', undefined);- expect(waiting).toMatchObject({- message: expect.stringContaining('waiting for its device to reconnect'),- outcome: 'waiting_external',- taskId: created.taskId,- });- expect(runSpy).not.toHaveBeenCalled();- expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);- });-- it('keeps waiting while only some other device is online', async () => {- vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([- { deviceId: 'device-desktop' } as never,- ]);- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');- const { graph, service } = await setup('Another device is online');-- const waiting = await service.tick(graph.goal.id);-- expect(waiting).toMatchObject({ outcome: 'waiting_external' });- expect(runSpy).not.toHaveBeenCalled();- });-- it('retries on its own once its device is back online', async () => {- vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([- { deviceId: 'device-laptop' } as never,- ]);- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockResolvedValue({ operationId: 'op-after-reconnect', success: true } as never);- const { created, graph, service } = await setup('Device reconnected');-- const retried = await service.tick(graph.goal.id);-- expect(runSpy).toHaveBeenCalledWith(- expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),- );- expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });- expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);- });-- it('keeps waiting when the retry itself cannot reach the device', async () => {- vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([- { deviceId: 'device-laptop' } as never,- ]);- vi.spyOn(TaskRunnerService.prototype, 'runTask').mockRejectedValue(- new Error('DEVICE_OFFLINE (HTTP 503)'),- );- const { created, graph, service, taskModel } = await setup('Device flapping');-- const waiting = await service.tick(graph.goal.id);-- expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });- expect(await taskModel.findById(created.taskId!)).toMatchObject({- error: 'DEVICE_OFFLINE (HTTP 503)',- status: 'paused',- });- expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);- });-- it('retries on the offline schedule even while the device still looks offline', async () => {- vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockResolvedValue({ operationId: 'op-on-schedule', success: true } as never);- const { created, graph, service } = await setup('Device gone past the first backoff');- await serverDB- .update(tasks)- .set({ updatedAt: new Date(Date.now() - 31 * 60 * 1000) })- .where(eq(tasks.id, created.taskId!));-- const retried = await service.tick(graph.goal.id);-- expect(runSpy).toHaveBeenCalledWith(- expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),- );- expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });- expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);- });-- it('waits out the backoff without presence on a deployment without a device gateway', async () => {- const listSpy = vi.spyOn(deviceGateway, 'queryDeviceList');- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');- const { created, graph, service } = await setup('Self-hosted without devices');- vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(false);-- const waiting = await service.tick(graph.goal.id);-- expect(listSpy).not.toHaveBeenCalled();- expect(runSpy).not.toHaveBeenCalled();- expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });- });- });-- describe('a Task its usage window refused', () => {- const SESSION_LIMIT = "You've hit your session limit ยท resets 4:30am";-- const setup = async (title: string, resetsAtMs: number) => {- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask: 3 } },- title,- tasks: ['Run on the external Agent'],- });- const created = await service.tick(graph.goal.id);- await taskModel.update(created.taskId!, { totalTopics: 1 });-- const operationModel = new AgentOperationModel(serverDB, userId);- await operationModel.recordStart({ operationId: 'op-quota', taskId: created.taskId });- await operationModel.recordCompletion('op-quota', {- completedAt: new Date(),- completionReason: 'error',- error: {- body: {- code: 'rate_limit',- rateLimitInfo: { resetsAt: Math.floor(resetsAtMs / 1000), status: 'rejected' },- },- category: 'quota',- message: SESSION_LIMIT,- },- status: 'error',- });- vi.spyOn(TaskTopicModel.prototype, 'findWithHandoff').mockResolvedValue([- { operationId: 'op-quota' } as never,- ]);- await taskModel.updateStatus(created.taskId!, 'paused', { error: SESSION_LIMIT });- return { created, graph, service };- };-- it('waits for the reset instead of asking a person', async () => {- const schedule = vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');- const resetsAt = Date.now() + 2 * 60 * 60 * 1000;- const { created, graph, service } = await setup('Session limit', resetsAt);-- const waiting = await service.tick(graph.goal.id);-- expect(waiting).toMatchObject({- message: expect.stringContaining('usage window to reset'),- outcome: 'waiting_external',- taskId: created.taskId,- });- expect(schedule).toHaveBeenLastCalledWith(- expect.objectContaining({ goalId: graph.goal.id, trigger: 'wake' }),- );- expect(schedule.mock.lastCall![0].delay).toBeGreaterThanOrEqual(2 * 60 * 60);-- // More ticks before the reset (the sweep, Task events) queue no more wakes,- // and a policy edit from a stale snapshot does not drop the armed receipt.- await service.tick(graph.goal.id);- await new GoalModel(serverDB, userId).update(graph.goal.id, {- config: { recovery: { maxAttemptsPerTask: 3 } },- });- expect((await service.graph(graph.goal.id)).goal.config?.quotaRetryWakeAt).toBeDefined();- await service.tick(graph.goal.id);- expect(schedule.mock.calls.filter(([params]) => params.trigger === 'wake')).toHaveLength(1);- expect(runSpy).not.toHaveBeenCalled();- const after = await service.graph(graph.goal.id);- expect(after.decisions).toHaveLength(0);- expect(after.goal.config?.supervisorState?.incidents ?? []).toHaveLength(0);- });-- // The refusal's text names the limit, so its runs are uncharged and the- // attempt budget cannot end a window that keeps refusing. The uncharged- // quota schedule does: once spent, a person is asked instead of another wait.- it('stops waiting once the uncharged usage-limit retries are spent', async () => {- const schedule = vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');- const { created, graph, service } = await setup(- 'Session limit keeps refusing',- Date.now() + 2 * 60 * 60 * 1000,- );- for (let seq = 1; seq <= MAX_QUOTA_RETRIES + 1; seq++) {- const topicId = `tpc_quota_${seq}`;- await serverDB.insert(topics).values({ id: topicId, userId });- await serverDB.insert(taskTopics).values({- seq,- status: QUOTA_LIMITED_RUN_STATUS,- taskId: created.taskId!,- topicId,- updatedAt: new Date(Date.now() - (MAX_QUOTA_RETRIES + 1 - seq) * 60 * 1000),- userId,- });- }-- const gated = await service.tick(graph.goal.id);-- expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });- expect(runSpy).not.toHaveBeenCalled();- expect(schedule.mock.calls.filter(([params]) => params.trigger === 'wake')).toHaveLength(0);- expect((await service.graph(graph.goal.id)).decisions).toHaveLength(1);- });-- it('retries through ordinary recovery once the window has reset', async () => {- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockResolvedValue({ operationId: 'op-after-reset', success: true } as never);- const { created, graph, service } = await setup(- 'Session limit over',- Date.now() - 2 * 60 * 1000,- );-- const retried = await service.tick(graph.goal.id);-- expect(runSpy).toHaveBeenCalledWith(- expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),- );- expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });- expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);- });-- it('does not start the retry once the Goal deadline has passed', async () => {- const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');- const { graph, service } = await setup(- 'Reset after the deadline',- Date.now() - 2 * 60 * 1000,- );- await serverDB- .update(goals)- .set({- config: sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{schedule}', ${JSON.stringify({ deadline: new Date(Date.now() - 60_000).toISOString() })}::jsonb)`,- })- .where(eq(goals.id, graph.goal.id));-- await service.tick(graph.goal.id);-- expect(runSpy).not.toHaveBeenCalled();- });- });-- describe('a Task whose runs its device lost', () => {- const MINUTE = 60 * 1000;- const HOUR = 60 * MINUTE;-- const setup = async (title: string, maxAttemptsPerTask: number) => {- vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);- vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockResolvedValue({ operationId: 'op-retry', success: true } as never);- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- config: { recovery: { maxAttemptsPerTask, operationLeaseTimeoutMs: 60_000 } },- title,- tasks: ['Run on the laptop'],- });- const created = await service.tick(graph.goal.id);- runSpy.mockClear();- return { created, graph, runSpy, service, taskModel };- };-- const addRun = async (- taskId: string,- seq: number,- status: string,- options: { metadata?: ChatTopicMetadata; operationId?: string; updatedAt?: Date } = {},- ) => {- const topicId = `tpc_offline_${seq}`;- await serverDB.insert(topics).values({ id: topicId, metadata: options.metadata, userId });- await serverDB.insert(taskTopics).values({- operationId: options.operationId,- seq,- status,- taskId,- topicId,- userId,- ...(options.updatedAt && { updatedAt: options.updatedAt }),- });- return topicId;- };-- /** `count` consecutive offline runs, the newest `sinceLast` ago. */- const addOfflineRuns = async (taskId: string, count: number, sinceLast: number) => {- for (let seq = 1; seq <= count; seq++) {- await addRun(taskId, seq, DEVICE_OFFLINE_RUN_STATUS, {- updatedAt: new Date(Date.now() - sinceLast - (count - seq) * HOUR),- });- }- };-- const decisionReasons = async (service: GoalService, goalId: string) =>- (await service.graph(goalId)).nodes- .filter((node) => node.kind === 'decision')- .map((node) => node.description);-- it('does not charge a run lost while its device was offline to the attempt budget', async () => {- const { created, graph, runSpy, service, taskModel } = await setup(- 'Laptop went offline mid-run',- 1,- );- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'running');- const operationModel = new AgentOperationModel(serverDB, userId);- await operationModel.recordStart({ operationId: 'op-lost', taskId: created.taskId });- await serverDB- .update(agentOperations)- .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })- .where(eq(agentOperations.id, 'op-lost'));- const topicId = await addRun(created.taskId!, 1, 'running', {- metadata: {- runningOperation: {- assistantMessageId: 'msg-lost',- deviceId: 'device-laptop',- operationId: 'op-lost',- },- },- operationId: 'op-lost',- });-- const waiting = await service.tick(graph.goal.id);-- expect(waiting).toMatchObject({- message: expect.stringContaining('waiting for its device to reconnect'),- outcome: 'waiting_external',- taskId: created.taskId,- });- expect(runSpy).not.toHaveBeenCalled();- expect(await decisionReasons(service, graph.goal.id)).toHaveLength(0);- const [lost] = await new TaskTopicModel(serverDB, userId).findByTaskId(created.taskId!);- expect(lost.status).toBe(DEVICE_OFFLINE_RUN_STATUS);-- // Once the first backoff has passed, the retry goes out on the budget the- // lost run did not spend.- await serverDB- .update(taskTopics)- .set({ updatedAt: new Date(Date.now() - 31 * MINUTE) })- .where(eq(taskTopics.topicId, topicId));- await service.tick(graph.goal.id);-- expect(runSpy).toHaveBeenCalledWith(- expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),- );- expect(await decisionReasons(service, graph.goal.id)).toHaveLength(0);- });-- it('still charges a lost run whose device is online when it is reclaimed', async () => {- const { created, graph, runSpy, service, taskModel } = await setup(- 'Run died on a connected laptop',- 1,- );- vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([- { deviceId: 'device-laptop' } as never,- ]);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'running');- const operationModel = new AgentOperationModel(serverDB, userId);- await operationModel.recordStart({ operationId: 'op-died', taskId: created.taskId });- await serverDB- .update(agentOperations)- .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })- .where(eq(agentOperations.id, 'op-died'));- await addRun(created.taskId!, 1, 'running', {- metadata: { boundDeviceId: 'device-laptop' },- operationId: 'op-died',- });-- const gated = await service.tick(graph.goal.id);-- expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });- expect(runSpy).not.toHaveBeenCalled();- });-- it.each([- { before: 29 * MINUTE, after: 31 * MINUTE, offlineRuns: 1, schedule: '30min' },- { before: 59 * MINUTE, after: 61 * MINUTE, offlineRuns: 2, schedule: '1h' },- { before: 119 * MINUTE, after: 121 * MINUTE, offlineRuns: 3, schedule: '2h' },- { before: 7 * HOUR + 59 * MINUTE, after: 8 * HOUR + MINUTE, offlineRuns: 5, schedule: '8h' },- {- before: 7 * HOUR + 59 * MINUTE,- after: 8 * HOUR + MINUTE,- offlineRuns: 6,- schedule: '8h (capped)',- },- ])(- 'waits $schedule after offline run $offlineRuns before retrying',- async ({ after, before, offlineRuns }) => {- const { created, graph, runSpy, service, taskModel } = await setup(- `Offline backoff ${offlineRuns}`,- 1,- );- await taskModel.update(created.taskId!, { totalTopics: offlineRuns });- await addOfflineRuns(created.taskId!, offlineRuns, before);- await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });-- const waiting = await service.tick(graph.goal.id);- expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });- expect(runSpy).not.toHaveBeenCalled();-- await serverDB- .update(taskTopics)- .set({ updatedAt: new Date(Date.now() - after) })- .where(eq(taskTopics.topicId, `tpc_offline_${offlineRuns}`));- await service.tick(graph.goal.id);-- expect(runSpy).toHaveBeenCalledWith(- expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),- );- expect(await decisionReasons(service, graph.goal.id)).toHaveLength(0);- },- );-- it('retries at once when presence shows the device back before the backoff ends', async () => {- const { created, graph, runSpy, service, taskModel } = await setup('Laptop woke up', 1);- vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([- { deviceId: 'device-laptop' } as never,- ]);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await addRun(created.taskId!, 1, DEVICE_OFFLINE_RUN_STATUS, {- metadata: { boundDeviceId: 'device-laptop' },- });- await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });-- await service.tick(graph.goal.id);-- expect(runSpy).toHaveBeenCalledOnce();- });-- it('asks a person once every offline retry found the device gone', async () => {- const { created, graph, runSpy, service, taskModel } = await setup(- 'Laptop never came back',- 1,- );- await taskModel.update(created.taskId!, { totalTopics: 7 });- await addOfflineRuns(created.taskId!, 7, 10 * HOUR);- await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });-- const gated = await service.tick(graph.goal.id);-- expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });- expect(runSpy).not.toHaveBeenCalled();- expect(await decisionReasons(service, graph.goal.id)).toEqual([DEVICE_OFFLINE_GATE_REASON]);- });-- it('keeps charging verification-rejected attempts to the budget', async () => {- const { created, graph, runSpy, service, taskModel } = await setup(- 'Rejections still count',- 2,- );- await addRun(created.taskId!, 1, DEVICE_OFFLINE_RUN_STATUS);- await addRun(created.taskId!, 2, 'completed');- await taskModel.update(created.taskId!, { totalTopics: 2 });- await taskModel.updateStatus(created.taskId!, 'paused', {- error: VERIFICATION_FAILED_ERROR,- });-- // One offline run and one rejection: only the rejection is charged.- await service.tick(graph.goal.id);- expect(runSpy).toHaveBeenCalledOnce();-- await addRun(created.taskId!, 3, 'completed');- await taskModel.update(created.taskId!, { totalTopics: 3 });- await taskModel.updateStatus(created.taskId!, 'paused', {- error: VERIFICATION_FAILED_ERROR,- });- runSpy.mockClear();-- const gated = await service.tick(graph.goal.id);-- expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });- expect(runSpy).not.toHaveBeenCalled();- expect(await decisionReasons(service, graph.goal.id)).toEqual([- 'Task attempt budget was exhausted',- ]);- });- });-- it('only selects Tasks whose explicit dependencies are resolved', async () => {- const service = new GoalService(serverDB, userId);- const graph = await service.create({ title: 'Dependency-aware goal' });- const prerequisite = await service.addNode(graph.goal.id, {- kind: 'task',- priority: 0,- title: 'Collect evidence',- });- const dependent = await service.addNode(graph.goal.id, {- kind: 'task',- priority: 10,- title: 'Train from evidence',- });- await service.addEdge(graph.goal.id, dependent.id, prerequisite.id, 'depends_on');-- const first = await service.tick(graph.goal.id);- expect(first).toMatchObject({ nodeId: prerequisite.id, outcome: 'advanced' });-- const taskModel = new TaskModel(serverDB, userId);- await taskModel.updateStatus(first.taskId!, 'completed');- await service.tick(graph.goal.id);-- const next = await service.tick(graph.goal.id);- expect(next).toMatchObject({ nodeId: dependent.id, outcome: 'advanced' });- });-});--/**- * Most real gates were machine problems pushed onto a person: a usage limit that- * reset on its own hours later, a working directory missing on the device. These- * pin that the coordinator waits out the first and asks about the second as a- * machine gate rather than a judgment.- */-describe('GoalService machine failures', () => {- const MINUTE = 60 * 1000;- const SESSION_LIMIT = "You've hit your session limit ยท resets 4:30am (Asia/Shanghai)";- // 03:51 in Shanghai, a minute after the run hit the limit.- const FAILED_AT = new Date('2026-10-05T19:50:01.000Z');-- const setup = async (title: string) => {- const runSpy = vi- .spyOn(TaskRunnerService.prototype, 'runTask')- .mockResolvedValue({ operationId: 'op-retry', success: true } as never);- const scheduleSpy = vi- .spyOn(LocalGoalScheduler.prototype, 'scheduleAdvance')- .mockResolvedValue('scheduled');- const service = new GoalService(serverDB, userId);- const taskModel = new TaskModel(serverDB, userId);- const graph = await service.create({- // One attempt: a limited run that spent it would gate the retry.- config: { recovery: { maxAttemptsPerTask: 1 } },- tasks: ['Run on Claude Code'],- title,- });- const created = await service.tick(graph.goal.id);- runSpy.mockClear();- return { created, graph, runSpy, scheduleSpy, service, taskModel };- };-- const failRun = async (taskId: string, status: string, error: string, at: Date) => {- const topicId = `tpc_machine_${taskId}`;- await serverDB.insert(topics).values({ id: topicId, userId });- await serverDB- .insert(taskTopics)- .values({ seq: 1, status, taskId, topicId, updatedAt: at, userId });- const taskModel = new TaskModel(serverDB, userId);- await taskModel.update(taskId, { totalTopics: 1 });- await taskModel.updateStatus(taskId, 'paused', { error });- await serverDB.update(tasks).set({ updatedAt: at }).where(eq(tasks.id, taskId));- };-- afterEach(() => {- vi.useRealTimers();- });-- it('waits for a usage limit to reset, then retries without charging the attempt', async () => {- vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });- vi.setSystemTime(new Date(FAILED_AT.getTime() + MINUTE));- const { created, graph, runSpy, scheduleSpy, service } = await setup('Session limit');- await failRun(created.taskId!, QUOTA_LIMITED_RUN_STATUS, SESSION_LIMIT, FAILED_AT);-- const waiting = await service.tick(graph.goal.id);-- expect(waiting).toMatchObject({- message: expect.stringContaining('retrying at 2026-10-05T20:31:00.000Z'),- outcome: 'waiting_external',- taskId: created.taskId,- });- expect(runSpy).not.toHaveBeenCalled();- expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);- // The tick that saw the failure books the advance for the reset.- expect(scheduleSpy).toHaveBeenCalledWith(- expect.objectContaining({ delay: 39 * 60 + 59, goalId: graph.goal.id, trigger: 'wake' }),- );-- vi.setSystemTime(new Date('2026-10-05T20:33:00.000Z'));- const retried = await service.tick(graph.goal.id);-- expect(runSpy).toHaveBeenCalledWith(- expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),- );- expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });- expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);- });-- it('opens a machine gate that names the missing working directory', async () => {- const { created, graph, runSpy, service } = await setup('Missing working directory');- const error = 'Working directory does not exist: /Users/user/CodeProjects/LobeHub/lobehub';- await failRun(created.taskId!, 'failed', error, new Date());-- const gated = await service.tick(graph.goal.id);-- expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });- expect(runSpy).not.toHaveBeenCalled();- const after = await service.graph(graph.goal.id);- const gate = after.nodes.find((node) => node.kind === 'decision')!;- expect(gate.title).toBe(GOAL_MACHINE_GATE_TITLE);- const [decision] = after.decisions;- expect(decision.question).toBe(- 'Setup problem: Working directory does not exist: /Users/user/CodeProjects/LobeHub/lobehub. Create /Users/user/CodeProjects/LobeHub/lobehub on the device the agent runs on, or point the agent at a working directory that exists there. Fix it, then retry or retire this task node?',- );- expect(decision.options).toEqual([- { id: 'retry', label: 'I fixed it โ retry' },- { id: 'retire', label: 'Retire task' },- ]);- });-- it('keeps a judgment failure on the ordinary gate', async () => {- const { created, graph, service } = await setup('Unjudgeable delivery');- await failRun(- created.taskId!,- 'failed',- 'Acceptance review could not run; the delivery passed its verifiers but was never reviewed.',- new Date(),- );-- await service.tick(graph.goal.id);-- const gate = (await service.graph(graph.goal.id)).nodes.find(- (node) => node.kind === 'decision',- )!;- expect(gate.title).toBe('Choose how to recover failed task');- });-- it('asks about a device that stayed offline with a machine gate', async () => {- const { created, graph, service, taskModel } = await setup('Device never came back');- await taskModel.update(created.taskId!, { totalTopics: 7 });- for (let seq = 1; seq <= 7; seq++) {- const topicId = `tpc_machine_offline_${seq}`;- await serverDB.insert(topics).values({ id: topicId, userId });- await serverDB.insert(taskTopics).values({- seq,- status: DEVICE_OFFLINE_RUN_STATUS,- taskId: created.taskId!,- topicId,- updatedAt: new Date(Date.now() - (17 - seq) * 60 * MINUTE),- userId,- });- }- await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });-- await service.tick(graph.goal.id);-- const gate = (await service.graph(graph.goal.id)).nodes.find(- (node) => node.kind === 'decision',- )!;- expect(gate).toMatchObject({- description: DEVICE_OFFLINE_GATE_REASON,- title: GOAL_MACHINE_GATE_TITLE,- });- });-});diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex a6d41f11f6a..0e2083bd510 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -1,5080 +1 @@-import { randomUUID } from 'node:crypto';--import type { GoalAdvanceEffect, GoalMetricCriteriaState } from '@lobechat/agent-tracing';-import { buildGoalRequirement } from '@lobechat/builtin-tool-goal';-import {- DEVICE_OFFLINE_RUN_STATUS,- GOAL_BATCH_ASSAY_TITLE,- GOAL_BATCH_BREAK_OPTION,- GOAL_BATCH_BREAK_QUESTION_TAIL,- GOAL_BATCH_RELEASE_OPTION,- GOAL_BATCH_TEMPLATE_TITLE,- GOAL_CLARIFICATION_OPTION,- GOAL_CLARIFICATION_TITLE,- GOAL_COORDINATOR_ACTOR_ID,- GOAL_MACHINE_GATE_TITLE,- PATTERN_BREAK_PAUSE_REASON,- ROLLOUT_CANARY_SIZE_DEFAULT,- ROLLOUT_MAX_CANARY_SIZE,-} from '@lobechat/const/goal';-import type {- ChatTopicMetadata,- GoalConfig,- GoalCreateConfig,- GoalDecisionOption,- GoalEdgeKind,- GoalEventEntityType,- GoalEventType,- GoalGraphNode,- GoalGraphSnapshot,- GoalItem,- GoalManagerAsk,- GoalMetricCriterion,- GoalNodeAcceptance,- GoalNodeKind,- GoalNodeStatus,- GoalPauseReason,- GoalRolloutPolicy,- GoalStatus,- GoalTickResult,- MetricKind,- TaskItem,- TaskTopicHandoff,- WorkVersionEventItem,-} from '@lobechat/types';-import { experimentOwner, provenanceParentId } from '@lobechat/utils/goalGraph';-import { goalSeedDependencyProblem, type GoalSeedTask } from '@lobechat/utils/goalSeeds';-import { TRPCError } from '@trpc/server';-import debug from 'debug';-import { sql } from 'drizzle-orm';--import { AgentModel } from '@/database/models/agent';-import { AgentOperationModel } from '@/database/models/agentOperation';-import { type ExpertiseCarrier, ExpertiseModel } from '@/database/models/expertise';-import { GoalModel } from '@/database/models/goal';-import { GoalGraphModel } from '@/database/models/goalGraph';-import { MetricModel } from '@/database/models/metric';-import { ProjectModel } from '@/database/models/project';-import { TaskModel } from '@/database/models/task';-import { TaskTopicModel } from '@/database/models/taskTopic';-import { TopicModel } from '@/database/models/topic';-import { WorkModel } from '@/database/models/work';-import type { LobeChatDatabase } from '@/database/type';-import { assertAgentUsableBy } from '@/database/utils/agent-access';-import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';--import { readDeviceDispatchRoute } from '../aiAgent/helpers/heteroErrors';-import { deviceGateway } from '../deviceGateway';-import { TaskService } from '../task';-import { TaskRunnerService } from '../taskRunner';-import { AcceptanceService } from '../verify/acceptanceService';-import { VerifyPlanGeneratorService } from '../verify/planGenerator';-import { isOrphanedRun, readRunTopicMetadata, stopStaleRun } from './abandonedRun';-import { BatchPlanSkillService, learnedRulesClause, planSkillIdentifier } from './batchPlanSkill';-import { GoalCriteriaGeneratorService, type GoalDecompositionDraft } from './criteriaGenerator';-import {- compareMetric,- decideNextMove,- frontierNeedsBudget,- GOAL_ACCEPTANCE_TASK_TITLE,- type GoalMove,- LEASE_EXPIRED_ERROR,- MEASURED_ACCEPTANCE_PAUSE_REASON,- needsMetricCriteria,- NO_FRONTIER_PAUSE_REASON,- selectFrontier,- TERMINAL_NODE_STATUSES,-} from './decideNextMove';-import { isDeliverySettling } from './deliverySettle';-import { experimentResults, exploreGraph } from './exploreGraph';-import { classifyGoalFailure, isMachineFailureClass } from './failureClass';-import { GoalBriefService } from './goalBriefs';-import { lastAnsweredGateAt, planMachineRecovery } from './machineRecovery';-import { answeredProblem, GoalManagerService, problemKey } from './manager';-import {- classifyRunFailure,- countConsecutiveDeviceOfflineRuns,- DEFAULT_MANAGER_MAX_TURNS,- DEVICE_OFFLINE_GATE_REASON,- isDeviceUnavailableFailure,- managerTurnsSpent,- nextDeviceOfflineRetryAt,- QUOTA_RESET_MARGIN_MS,- resolveMaxConcurrentTasks,- resolveOperationLeaseTimeout,- resolveTaskMaxSteps,-} from './recoveryPolicy';-import { GoalReleaseReview } from './releaseReview';-import { isGoalReportNode, withoutGoalReport } from './report';-import { GoalReportService } from './reportService';-import { GoalReportStore } from './reportStore';-import {- carriedUnitBrief,- createRecipeUnitTask,- materializeRolloutBatch,- MAX_ROLLOUT_ROSTER,- normalizeRolloutRoster,-} from './rolloutBatch';-import { evaluateRolloutGate, type RolloutGateResult, withGateVerdict } from './rolloutGate';-import { scheduleGoalAdvance } from './scheduler';-import { seedGoalTasks } from './seedTasks';-import { evaluateHomogeneity } from './spec';-import { GoalSupervisorService } from './supervisor';-import { statusAuthoredByActor } from './supervisor/policy';-import { claimGoalTask } from './taskClaim';-import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';-import {- type GoalTickOptions,- toBudgetState,- toFrontierTaskState,- toTraceGraphState,-} from './traceObservation';-import {- clarificationOptions,- collectClarificationAnswers,- hasAskedClarification,- normalizeUnderstanding,- UNDERSTANDING_CONFIDENCE,-} from './understanding';-import { GoalWaitService } from './wait';--const TASK_NODE_CLAIM_TTL_MS = 5 * 60 * 1000;-/**- * Tick outcomes after which the Goal-level acceptance may have just ended: the- * Goal was achieved, failed or canceled, or parked on a gate (an acceptance- * whose attempts ran out opens one). Every other outcome skips the check.- */-const REPORT_CHECK_OUTCOMES = new Set<GoalTickResult['outcome']>([- 'achieved',- 'failed',- 'waiting_human',-]);-/** A Goal whose delivery the owner can still send back for rework. */-const REOPENABLE_GOAL_STATUSES = new Set(['achieved', 'running']);-const TASK_DESCRIPTION_MAX_LENGTH = 255;-/** Ends a person reached, or the coordinator's verdict of success: nothing reopens these but `resume`. */-const GOAL_ENDED_STATUSES = new Set<string>(['achieved', 'canceled']);-/** Advisory-lock namespace for goal dispatch. `0x676f_6469` is ASCII `godi`. */-const GOAL_DISPATCH_LOCK_NAMESPACE = 0x67_6f_64_69;-/** Why a decomposition did or did not become a batch: DEBUG=lobe-server:goal-rollout. */-const log = debug('lobe-server:goal-rollout');--/**- * Why the system planner's one pass should go to the main Agent, or undefined- * when its plan can run: the pass failed, the planner said it was not enough,- * or it claimed a batch it could not lay out. A goal that is simply not a batch- * is not a reason โ the ordinary plan is right for it.- */-const planningHandoffReason = (- plan: GoalDecompositionDraft | undefined,- plannerFailure: string | undefined,- rollout: GoalRolloutPolicy | undefined,- maxUnits: number,-): string | undefined => {- if (!plan) return `Planner failed (${plannerFailure ?? 'no answer'})`;- const asked = plan.escalate?.trim();- if (asked) return `Planner asked for the main Agent: ${asked}`;- if (!plan.rollout || rollout?.trigger === 'off') return undefined;- const verdict = evaluateHomogeneity(- plan.rollout,- plan.tasks.map((draft) => ({ instruction: draft.instruction, title: draft.title })),- { maxUnits, minUnits: rollout?.minHomogeneousUnits },- );- return verdict.malformed- ? `Batch claim could not be laid out (${verdict.reasons.join('; ')})`- : undefined;-};--/**- * One line for why the planner failed, for the audit trail. Model runtime- * errors arrive as plain objects (`{ errorType, error }`), not `Error`s.- */-const describePlannerFailure = (error: unknown): string => {- const runtime = error as { error?: { message?: string }; errorType?: string } | undefined;- const text =- error instanceof Error- ? error.message- : [runtime?.errorType, runtime?.error?.message].filter(Boolean).join(': ') || String(error);- return text.length > 300 ? `${text.slice(0, 299)}โฆ` : text;-};--const draftNotStarted = (goalId: string) =>- new TRPCError({- code: 'CONFLICT',- message: `Goal is a draft; start it with lh goal start ${goalId}`,- });-/** Who does the goal's Tasks: its dedicated executor, else the goal agent itself. */-export const goalTaskAgentId = (goal: Pick<GoalItem, 'agentId' | 'config'>) =>- goal.config?.taskAgentId ?? goal.agentId ?? undefined;--export type CreateGoalTaskInput = GoalSeedTask;--export interface CreateGoalGraphInput {- /**- * The goal agent: it supervises the goal, runs its planning turns and does its- * Tasks unless `config.taskAgentId` names a dedicated executor. Defaults to- * `createdByAgentId`.- */- agentId?: string;- config?: GoalCreateConfig;- /**- * The agent that made this call, when a tool did. Distinct from `agentId`,- * which is the agent the goal belongs to โ creating a goal from the modal on- * an agent's page sets that, but the author is still the person.- */- createdByAgentId?: string;- /**- * Structured acceptance criteria. Persisted as `verify_criteria` rows and- * recorded on `config.acceptance.criteriaIds`, so the goal page can show and- * edit them and the terminal Goal-acceptance Task verifies against exactly- * these checks. Callers still fold the same criteria into `requirement`- * prose โ that text remains what every Task's execution context reads.- */- criteria?: Array<{ description?: string; instruction?: string; title: string }>;- /**- * Create the goal as a `draft`: the graph can be arranged, and nothing is- * dispatched until `GoalStartService.start` launches it.- */- draft?: boolean;- maxRounds?: number;- maxTotalCost?: number;- /**- * The user's ask in their own words, shown on the seeded problem node. The- * full `requirement` (with its acceptance boilerplate) stays on the goal row- * โ copying it onto the node made every drill-down read like a contract.- */- problemDescription?: string;- projectId?: string;- requirement?: string;- /**- * Seed task nodes; `dependsOn` names other seeds by title. A plain string is title-only.- * When omitted, the coordinator plans the decomposition on first advance.- */- tasks?: Array<CreateGoalTaskInput | string>;- title: string;- /**- * The conversation this goal was created from. Recorded as the goal's- * `topic` subject so the conversation can find and show it.- */- topicId?: string;-}--export interface CreateGoalNodeInput {- description?: string;- kind: GoalNodeKind;- priority?: number;- questionId?: string;- scopeId?: string;- status?: GoalNodeStatus;- title: string;-}--/** Application service shared by CLI today and Graph UI/schedulers later. */-/**- * Version events read per task run when harvesting deliverables. Generous- * because the cap applies to events rather than to Works: the newest N events- * of a run must still contain every Work it produced, even one revised many- * times over.- */-const DELIVERABLE_EVENTS_PER_RUN = 200;--/**- * What answering a gate does to the Task it was opened for. The coordinator's- * own options say it through their fixed ids; an option the main Agent wrote- * for its own question names its effect, and one that names none only records- * the answer โ the Agent reads it on its next turn.- */-const decisionOptionEffect = (- option: GoalDecisionOption | undefined,- sourceTitle?: string,-): 'fail' | 'retire' | 'retry' | undefined => {- if (!option) return undefined;- if (option.effect) return option.effect;- if (option.id === 'retry' || option.id === 'retire') return option.id;- if (option.id === 'fail' && sourceTitle === GOAL_ACCEPTANCE_TASK_TITLE) return 'fail';- return undefined;-};--/**- * The comment a retried Task carries into its next attempt. A bare "retry"- * adds nothing the run does not already know; a chosen direction or a note is- * exactly what the owner wants the next attempt to act on.- */-const decisionGuidance = (- question: string,- option: GoalDecisionOption | undefined,- note?: string,-): string | undefined => {- const custom = option && option.id !== 'retry' ? option : undefined;- const trimmed = note?.trim();- if (!custom && !trimmed) return undefined;- return [- 'Owner decision on the recovery gate for this Task.',- `Question: ${question}`,- custom- ? `Chosen: ${custom.label}${custom.description ? ` โ ${custom.description}` : ''}`- : undefined,- trimmed ? `Guidance: ${trimmed}` : undefined,- ]- .filter(Boolean)- .join('\n');-};--export class GoalService {- private readonly acceptanceService: AcceptanceService;- private readonly agentModel: AgentModel;- /** What the goal tells the person through the inbox: gates, sign-off, findings. */- private readonly briefs: GoalBriefService;- private readonly releaseReview: GoalReleaseReview;- private readonly goalModel: GoalModel;- /**- * Graph writes attributed to the person who asked for them: seeding a goal,- * adding a node or edge by hand, resolving a decision gate.- */- private readonly graphModel: GoalGraphModel;- /**- * Graph writes the coordinator makes on its own โ claiming a Task node,- * binding its task, synthesizing a finding, opening a gate. Attributed to the coordinator- * even when a person pressed Advance: they asked it to run, they did not make- * these moves.- */- private readonly coordinatorGraph: GoalGraphModel;- private readonly taskModel: TaskModel;- private readonly taskService: TaskService;- private readonly taskTopicModel: TaskTopicModel;- private readonly workModel: WorkModel;-- constructor(- private readonly db: LobeChatDatabase,- private readonly userId: string,- private readonly workspaceId?: string,- ) {- this.acceptanceService = new AcceptanceService(db, userId, workspaceId);- this.agentModel = new AgentModel(db, userId, workspaceId);- this.briefs = new GoalBriefService(db, userId, workspaceId);- this.goalModel = new GoalModel(db, userId, workspaceId);- this.releaseReview = new GoalReleaseReview(db, userId, workspaceId, {- briefs: this.briefs,- decide: (...args) => this.decide(...args),- graph: (goalId) => this.graph(goalId),- requireGraph: (goalId) => this.requireGraph(goalId),- setPauseReason: (goalId, reason) => this.setPauseReason(goalId, reason),- transitionStatus: (goal, to, reason) => this.transitionStatus(goal, to, reason),- });- this.graphModel = new GoalGraphModel(db, userId, workspaceId);- this.coordinatorGraph = new GoalGraphModel(db, userId, workspaceId, {- id: GOAL_COORDINATOR_ACTOR_ID,- type: 'system',- });- this.taskModel = new TaskModel(db, userId, workspaceId);- this.taskService = new TaskService(db, userId, workspaceId);- this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);- this.workModel = new WorkModel(db, userId, workspaceId);- }-- /**- * The graph model whose audit trail names `agentId` as the author, or the- * user-attributed one when a person is calling.- */- private graphAs = (agentId?: string) =>- agentId- ? new GoalGraphModel(this.db, this.userId, this.workspaceId, { id: agentId, type: 'agent' })- : this.graphModel;-- /**- * `/goal` in a conversation: the agent running there creates the goal and- * supervises it from that conversation.- *- * Identity comes from the running operation, never from the caller: the goal- * agent is the operation's agent, the conversation is its topic, and that very- * run becomes the first planning turn, so the agent can plan straight away with- * the returned token instead of waiting for a dispatched turn.- */- createFromConversation = async (- operationId: string,- input: Omit<CreateGoalGraphInput, 'agentId' | 'createdByAgentId' | 'topicId'>,- /**- * A local desktop run keeps its operation client-side, so no server row- * exists for `operationId`. Its conversation env names the topic and agent- * instead; they are accepted only when the topic is the caller's and belongs- * to that agent. Never used for operation-token callers.- */- localRun?: { agentId: string; topicId: string },- ): Promise<{ graph: GoalGraphSnapshot; turnToken: string }> => {- const { agentId, topicId } = await this.resolveTopicRun(- operationId,- localRun,- 'Only a run in a topic with an agent can create a goal it supervises',- );-- // A conversation goal opens as a draft when the caller asks for one: its- // agent arranges the graph in this run, and the goal runs only once someone- // starts it. Opt-in, because a CLI released before `lh goal start` existed- // could never start the draft it created.- const created = await this.create({- ...input,- agentId,- config: { ...input.config, manager: input.config?.manager ?? {} },- createdByAgentId: agentId,- topicId,- });- try {- const state = await new GoalManagerService(- this.db,- this.userId,- this.workspaceId,- ).adoptConversationTurn(created.goal.id, { operationId, topicId });- return { graph: (await this.graphModel.getGraph(created.goal.id))!, turnToken: state.token };- } catch (error) {- // A goal nobody can plan is worse than no goal: the agent would report it- // created while its supervisor never gets a turn.- await this.goalModel.delete(created.goal.id).catch(() => {});- throw error;- }- };-- /**- * The agent and topic of the run with this id, taken from the server's- * operation row; never from the caller while that row exists. A local desktop- * run has no row, so its env-provided topic and agent are accepted only when- * the topic is the caller's and belongs to that agent.- */- private resolveTopicRun = async (- operationId: string,- localRun: { agentId: string; topicId: string } | undefined,- noAgentMessage: string,- ): Promise<{ agentId: string; topicId: string }> => {- const operation = await new AgentOperationModel(- this.db,- this.userId,- this.workspaceId,- ).findOwnOperationById(operationId);- if (operation) {- if (operation.status !== 'running')- throw new TRPCError({- code: 'CONFLICT',- message: 'The conversation run has already ended',- });- if (!operation.agentId || !operation.topicId)- throw new TRPCError({ code: 'BAD_REQUEST', message: noAgentMessage });- return { agentId: operation.agentId, topicId: operation.topicId };- }- const topic = localRun- ? await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(- localRun.topicId,- )- : undefined;- if (!localRun || !topic || topic.agentId !== localRun.agentId)- throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });- return { agentId: localRun.agentId, topicId: topic.id };- };-- /**- * Attach an existing goal to the topic of the run with this id, so it- * is supervised from there exactly as if it had been created there with- * `/goal`: the topic's agent becomes the goal agent, the topic- * becomes its `topic` subject and management topic. Graph, Tasks,- * budgets and status are kept. A change of goal agent moves unfinished Tasks- * the way `setAgent` does (unless `goalOnly`, or the goal has a dedicated- * executor). Returns a `turnToken` when the binding run was adopted as a- * planning turn.- */- bindTopic = async (- goalId: string,- operationId: string,- options?: {- force?: boolean;- goalOnly?: boolean;- /** A local desktop run's topic; see `resolveTopicRun`. */- localRun?: { agentId: string; topicId: string };- },- ) => {- const { agentId, topicId } = await this.resolveTopicRun(- operationId,- options?.localRun,- 'Only a run in a topic with an agent can supervise a goal',- );- // A run row names its topic, but the topic must still be the caller's and- // the run's agent's: the binding makes that agent plan into it.- const topic = await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(- topicId,- );- if (!topic || topic.agentId !== agentId)- throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });- await assertAgentUsableBy(this.db, agentId, {- userId: this.userId,- workspaceId: this.workspaceId,- });-- // One transaction: the agent change and the Task moves it implies commit- // together. Committed apart, a failed move left the goal already on the new- // agent, and the retry โ seeing no agent change โ never moved the Tasks.- const { bound, reassignedTaskIds } = await this.db.transaction(async (tx) => {- const bound = await new GoalManagerService(tx, this.userId, this.workspaceId).bindTopic(- goalId,- { agentId, operationId, topicId },- { force: options?.force },- );- const reassignedTaskIds =- bound.previousAgentId === agentId- ? []- : await new GoalService(tx, this.userId, this.workspaceId).followGoalAgent(- bound.goal,- agentId,- options?.goalOnly,- );- return { bound, reassignedTaskIds };- });- return {- graph: await this.requireGraph(goalId),- previousSubject: bound.previousSubject,- reassignedTaskIds,- topicId,- turnToken: bound.turnToken,- };- };-- create = async (input: CreateGoalGraphInput): Promise<GoalGraphSnapshot> => {- if (input.agentId ?? input.createdByAgentId) {- await assertAgentUsableBy(this.db, (input.agentId ?? input.createdByAgentId)!, {- userId: this.userId,- workspaceId: this.workspaceId,- });- }- if (input.projectId) {- const project = await new ProjectModel(- this.db,- this.userId,- this.workspaceId,- ).findManageableById(input.projectId);- if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });- }- // Persist the structured acceptance criteria first: their ids ride on the- // goal config so the page can edit them and the terminal acceptance Task- // is gated on exactly these checks (not an AI re-derivation of the prose).- // The goal's agent supervises it: it owns the goal list entry, the page and,- // in manager mode, every planning turn. An agent creating a goal for itself- // need not repeat its id; executors are routed separately (`taskAgentId`).- const goalAgentId = input.agentId ?? input.createdByAgentId;- const { manager: managerOptions, taskAgentId, ...options } = input.config ?? {};- const managed = managerOptions !== undefined;- let config: GoalConfig | undefined = input.config ? options : undefined;- if (taskAgentId && taskAgentId !== goalAgentId) {- await assertAgentUsableBy(this.db, taskAgentId, {- userId: this.userId,- workspaceId: this.workspaceId,- });- config = { ...config, taskAgentId };- }- if (managed) {- if (!goalAgentId) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'A main Agent requires the goal agent',- });- }- const turns = managerOptions?.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS;- if (!Number.isInteger(turns) || turns < 1 || turns > 100)- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Main Agent requires 1โ100 management turns',- });- // Exploration, supervision and seed tasks used to be rejected here, on the- // premise that a main Agent owns planning outright. They are layers, not- // rivals: the system planner leads, supervision recovers known transport- // failures, and the main Agent is handed whatever neither can route (see- // `gateOrTakeOver`). Ordering resolves what exclusivity used to.- // Rebuilt from the known fields: a legacy caller may still send an- // `agentId` inside the policy, and the planning identity is the goal's.- config = {- ...config,- manager: { instruction: managerOptions?.instruction, maxTurns: managerOptions?.maxTurns },- };- }- // Supervision is a creation invariant, not a creation option: every Goal- // recovers its own dropped dispatches, so a caller may tune the incident cap- // but never opt out. This is the single choke point โ the CLI, the `/goal`- // tool, tRPC and REST all land here โ so no client can create an- // unsupervised Goal. A legacy `enabled: false` is rejected rather than- // silently rewritten: the caller asked for the opposite of what it would- // get, and hiding that would make the surprise surface later, mid-run.- const seedProblem = goalSeedDependencyProblem(input.tasks ?? []);- if (seedProblem) throw new TRPCError({ code: 'BAD_REQUEST', message: seedProblem });- const requestedSupervision = config?.supervision;- if (requestedSupervision?.enabled === false)- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Supervision is required for every goal and cannot be disabled',- });- config = {- ...config,- supervision: {- enabled: true,- ...(requestedSupervision?.maxIncidents === undefined- ? {}- : { maxIncidents: requestedSupervision.maxIncidents }),- },- };- // A supplied requirement is the user-reviewed goal document. Criteria live- // separately; only synthesize a document when the caller omitted one.- const requirement =- input.requirement ??- (input.criteria?.length ? buildGoalRequirement(input.title, input.criteria) : undefined) ??- (input.config?.exploration ? input.title : undefined);- if (config?.exploration) {- const { maxExperiments, instruction } = config.exploration;- if (- !Number.isInteger(maxExperiments) ||- maxExperiments < 1 ||- maxExperiments > 200 ||- !instruction.trim()- ) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Exploration requires an instruction and 1โ200 experiments',- });- }- if ((input.tasks?.length ?? 0) > maxExperiments) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Initial tasks exceed the experiment limit',- });- }- config = { ...config, exploration: { maxExperiments, instruction } };- }- if (input.criteria?.length) {- const criteriaIds = await new VerifyPlanGeneratorService(- this.db,- this.userId,- this.workspaceId,- ).createCriteriaFromDrafts(- input.criteria.map((item) => ({- description: item.description,- instruction: item.instruction,- onFail: 'manual',- required: true,- title: item.title,- verifierType: 'agent',- })),- );- // Merge, never replace: `acceptance` also carries the numeric clauses,- // and rebuilding the object from `criteriaIds` alone would drop a- // measured gate the caller asked for in the same call.- config = { ...config, acceptance: { ...config?.acceptance, criteriaIds } };- }-- const goal = await this.goalModel.create({- agentId: goalAgentId,- config,- maxRounds: input.maxRounds,- maxTotalCost: input.maxTotalCost,- projectId: input.projectId,- requirement,- ...(input.draft ? { status: 'draft' as const } : {}),- ...(input.topicId- ? { subjectId: input.topicId, subjectType: 'topic' as const }- : { subjectType: 'standalone' as const }),- title: input.title,- });- // `/goal` is an agent making the call. Seeding through the user-attributed- // model would file the whole opening graph under the goal's owner, which is- // the same loss of authorship the coordinator split just fixed.- const authorGraph = this.graphAs(input.createdByAgentId);-- try {- const problem = await authorGraph.createNode(goal.id, {- createdByAgentId: input.createdByAgentId,- description: input.problemDescription ?? input.requirement,- kind: 'problem',- status: 'active',- title: input.title,- });- if (!problem) throw new Error('Failed to seed goal problem');-- // An exploration baseline is the goal's first candidate answer, so it- // lives inside an experiment container the explorer can branch from.- // Caller-supplied seed tasks are ordinary work: they attach straight to- // the problem the way a planned or manager-submitted task does.- if (config?.exploration && !input.tasks) {- const description = `Produce one initial baseline experiment for this Goal. ${input.problemDescription ?? requirement ?? input.title}\nExploration method: ${config.exploration.instruction}\nExecute the baseline only; later experiments are scheduled by the Goal coordinator. Include a self-contained result and evidence.`;- const experiment = await authorGraph.createNode(goal.id, {- kind: 'experiment',- title: input.title,- description,- questionId: problem.id,- createdByAgentId: input.createdByAgentId,- });- if (!experiment) throw new Error('Failed to seed experiment');- const taskNode = await authorGraph.createNode(goal.id, {- scopeId: experiment.id,- createdByAgentId: input.createdByAgentId,- description,- kind: 'task',- title: input.title,- });- if (!taskNode) throw new Error('Failed to seed goal task');- }- await seedGoalTasks(- authorGraph,- goal.id,- problem.id,- input.tasks ?? [],- input.createdByAgentId,- );- } catch (error) {- await this.goalModel.delete(goal.id).catch(() => {});- throw error;- }- return (await this.graphModel.getGraph(goal.id))!;- };-- /**- * Replace the goal's structured acceptance criteria id list (goal-page- * editing). The criteria rows themselves are edited through the verify- * criteria endpoints; this only rebinds which of them gate the goal.- */- /**- * Declare (or clear) the numeric clauses that gate this goal's acceptance.- *- * Merged into `config.acceptance` so it cannot clobber the delivery criteria- * binding, and settable after creation because a long-horizon goal learns its- * real thresholds while it runs. Relaxing a clause can unblock a goal that is- * already parked short of acceptance โ the same reason extending a deadline- * resumes a budget-stopped one โ so the caller schedules an advance.- */- /**- * Write a measurement against this goal, and reopen it when that measurement- * is what it was waiting for.- *- * The gate parks the goal (see the `measured_acceptance` branch), and `tick`- * refuses to move a paused goal โ so without the reopen here the observation- * would land and nothing would happen. Only a goal the gate actually stopped- * is reopened, and only once every clause holds: the same discipline- * `setBudget` uses, so a deliberate pause is never undone by a stray sample- * and a still-short measurement does not queue a no-op advance.- */- recordObservation = async (- goalId: string,- input: {- key: string;- kind?: MetricKind;- observedAt?: Date;- title?: string;- unit?: string;- value: number;- },- ) => {- const goal = await this.goalModel.findById(goalId);- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });-- const metricModel = new MetricModel(this.db, this.userId, this.workspaceId);- const series = await metricModel.ensure({- key: input.key,- kind: input.kind,- subjectId: goal.id,- subjectType: 'goal',- title: input.title,- unit: input.unit,- });- if (!series)- throw new TRPCError({- code: 'CONFLICT',- message: 'Metric series slot is owned by another scope',- });-- const point = await metricModel.addPoint(series.id, {- actorId: this.userId,- actorType: 'user',- observedAt: input.observedAt ?? new Date(),- sourceType: 'manual',- value: input.value,- });-- const manager = goal.config?.managerState;- if (- manager?.wait &&- point &&- new Date(point.observedAt).getTime() >= Date.parse(manager.startedAt)- ) {- await new GoalWaitService(this.db, this.userId, this.workspaceId).deliver(goalId, {- waitToken: manager.token,- eventId: point.id,- type: 'metric.observed',- key: input.key,- reference: series.id,- summary: `${input.key} = ${input.value} at ${point.observedAt}`,- });- }- return { point, series, shouldAdvance: await this.reopenIfMeasurementCleared(goalId) };- };-- /**- * Whether the coordinator is worth waking: either the goal is already- * running, or the coordinator itself parked it on a measured gate that no- * longer holds it.- *- * The `pausedBy` marker is what makes this safe. A goal paused by a person- * looks exactly like one parked by the gate โ same status, same terminal- * phase, same clauses โ so without it an arriving measurement would restart- * a goal somebody deliberately stopped.- *- * "No longer holds it" covers both ways out: every clause now satisfied, and- * the clauses being dropped altogether (`setMetricCriteria(id, [])`), which- * otherwise left the goal parked on a gate that no longer existed.- */- private reopenIfMeasurementCleared = async (- goalId: string,- /**- * Whether the gate held the goal *before* the caller's edit, for callers- * that change the clauses themselves: dropping the last one erases the- * evidence, so the verdict is taken from the state that preceded it โ the- * same way `setBudget` reads what was binding before it wrote.- */- parkedBeforeEdit?: boolean,- ): Promise<boolean> => {- const graph = await this.coordinatorGraph.getGraph(goalId);- if (!graph) return false;- if (graph.goal.status !== 'paused') return true;- if (!(parkedBeforeEdit ?? this.isParkedOnMeasuredGate(graph))) return false;-- if (needsMetricCriteria(graph)) {- const { allMet } = await this.evaluateMetricCriteria(graph);- if (!allMet) return false;- }-- await this.setPauseReason(goalId, undefined);- await this.transitionStatus(graph.goal, 'running', 'a measurement cleared the acceptance gate');- return true;- };-- /**- * Record (or clear) why the coordinator is holding this goal paused.- *- * Kept on the goal's JSONB config rather than derived from the event log:- * control flow should not depend on a capped audit trail, and the marker has- * to survive for as long as the pause does โ which for a long-horizon goal- * is the whole wait.- */- private setPauseReason = async (goalId: string, reason: GoalPauseReason | undefined) => {- await this.goalModel.updatePauseReason(goalId, reason);- };-- /**- * Whether the coordinator is the one holding this paused goal.- *- * The marker answers it outright. Goals parked before the marker existed โ- * and any parked by an old worker mid-deploy โ carry none, so fall back to- * who performed the transition: every status change records a goal-entity- * event, and the newest one is by definition the transition that produced- * the current status. A coordinator park is attributed to `system`, a user- * pause to `user`, so the two stay distinguishable without the marker.- *- * Absent both, the pause is left alone: a goal wrongly resumed spends money- * against an explicit human decision, while one left parked says so on its- * row and is one Resume away.- */- private isParkedOnMeasuredGate = (graph: GoalGraphSnapshot): boolean => {- if (graph.goal.status !== 'paused') return false;- if (graph.goal.config?.pausedBy) return graph.goal.config.pausedBy === 'measured_acceptance';-- // Match the park this gate actually recorded, not merely "the coordinator- // paused it": it also parks goals that are blocked or out of budget, and an- // unrelated sample must not restart either. The newest goal-entity event is- // by definition the transition that produced the current status; if two- // share a millisecond and the read picks the other one, the result is a- // missed reopen rather than a wrongful one.- const lastTransition = graph.events.find((event) => event.entityType === 'goal');- return (- lastTransition?.actorType !== 'user' &&- !!lastTransition?.reason?.startsWith(MEASURED_ACCEPTANCE_PAUSE_REASON) &&- needsMetricCriteria(graph)- );- };-- setMetricCriteria = async (- goalId: string,- metrics: GoalMetricCriterion[],- /**- * `merge` upserts by key into the list as it stands on the server โ- * for callers declaring one clause, whose own snapshot may be stale.- * A client-built replacement array would silently drop whatever a- * concurrent editor or agent declared since that snapshot was read.- */- mode: 'merge' | 'replace' = 'replace',- ) => {- const before = await this.coordinatorGraph.getGraph(goalId);- if (!before) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- const parkedOnGate = this.isParkedOnMeasuredGate(before);- const goal = before.goal;- const current = goal.config?.acceptance?.metrics ?? [];- const next =- mode === 'merge'- ? [...current.filter((item) => !metrics.some((m) => m.key === item.key)), ...metrics]- : metrics;- await this.goalModel.update(goalId, {- config: {- ...goal.config,- acceptance: {- ...goal.config?.acceptance,- metrics: next.length > 0 ? next : undefined,- },- },- });- // Relaxing or dropping a clause can clear a gate the goal is parked on.- await this.reopenIfMeasurementCleared(goalId, parkedOnGate);- return this.graph(goalId);- };-- setAcceptanceCriteria = async (goalId: string, criteriaIds: string[]) => {- const goal = await this.goalModel.findById(goalId);- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- await this.goalModel.update(goalId, {- config: { ...goal.config, acceptance: { ...goal.config?.acceptance, criteriaIds } },- });-- // A terminal Goal-acceptance Task may already be dispatched โ its- // Acceptance row snapshotted the previous id list. Rebind it too, or the- // page would present the new criteria as gates while the verifier keeps- // materializing plans from the stale list. A verify round already- // materialized for an in-flight run stays as-is (rounds are immutable- // snapshots); every later run instantiates from the updated config.- const graph = await this.graphModel.getGraph(goalId);- const terminalTaskId = graph?.nodes.find(- (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE && node.taskId,- )?.taskId;- if (!terminalTaskId) return;-- const acceptance = await this.acceptanceService.acceptanceModel.findBySubject(- 'task',- terminalTaskId,- );- if (!acceptance || acceptance.status === 'accepted') return;- await this.acceptanceService.acceptanceModel.update(acceptance.id, {- config: {- ...acceptance.config,- ...(criteriaIds.length > 0- ? { verifyCriteriaIds: criteriaIds }- : { verifyCriteriaIds: undefined }),- },- });- };-- graph = async (goalId: string) => {- const graph = await this.requireGraph(goalId);- const [runHeartbeats, deliveredAt, acceptances, assignees, spend, report] = await Promise.all([- this.collectRunHeartbeats(graph),- this.collectDeliveredAt(graph),- this.collectAcceptances(graph),- this.collectAssignees(graph),- this.resolveSpend(graph),- new GoalReportStore(this.db, this.userId, this.workspaceId).state(graph),- ]);- return { ...graph, acceptances, assignees, deliveredAt, report, runHeartbeats, spend };- };-- /**- * The goal's audit trail, newest first, paged past the capped copy `graph()`- * carries. `graph()` stays the shape the page reads; this is for a reader- * chasing one transition โ the pause that explains why a plan was refused- * hours into a run, say. Returns the cursor that continues the page.- */- listEvents = async (- goalId: string,- options: {- cursor?: { createdAt: Date; id: string };- entityType?: GoalEventEntityType;- eventType?: GoalEventType;- limit: number;- },- ) => {- const page = await this.graphModel.listEvents(goalId, options);- if (!page) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- return page;- };-- /**- * The agent each dispatched task node is assigned to. Read from the Task row- * rather than the goal config: a task can be reassigned on its own, and the- * row is what the runner actually dispatches to.- */- private collectAssignees = async (- graph: GoalGraphSnapshot,- ): Promise<Record<string, string> | undefined> => {- const taskNodes = graph.nodes.filter(- (node): node is GoalGraphNode & { taskId: string } => node.kind === 'task' && !!node.taskId,- );- if (taskNodes.length === 0) return undefined;-- const nodeByTaskId = new Map(taskNodes.map((node) => [node.taskId, node.id]));- // Runs on every graph poll: read the one column, not whole task rows.- const tasks = await this.taskModel.findAssigneesByIds(taskNodes.map((node) => node.taskId));-- const result: Record<string, string> = {};- for (const task of tasks) {- const nodeId = nodeByTaskId.get(task.id);- if (nodeId && task.assigneeAgentId) result[nodeId] = task.assigneeAgentId;- }- return Object.keys(result).length > 0 ? result : undefined;- };-- /**- * The coordinator calls a goal achieved once its own acceptance passes, but- * the person who asked for it has not said so yet. Ask them โ wherever they- * are โ through the inbox, tied to the Goal-level acceptance they sign.- */- private requestSignOff = async (graph: GoalGraphSnapshot) => {- const terminal = graph.nodes.find(- (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE && !!node.taskId,- );- if (!terminal) return;- const acceptance = (await this.collectAcceptances(graph))?.[terminal.id];- if (!acceptance) return;- // `openSignOff` re-reads the acceptance under a row lock: one the owner- // already signed asks nothing.- await this.briefs.openSignOff(graph.goal, acceptance.id);- };-- /**- * Verification state per task node.- *- * Every dispatched task already owns an Acceptance (`createResponsibleTask`- * creates one), but the goal surfaced only the criteria it would be judged- * against โ never the judgment. A reader could see that a task finished and- * still have no idea whether it held up, which is the gap that made the page- * feel unverifiable.- *- * Each level's tally rides along so the page can show its standing without- * opening it. That tally is counted from the same check union the level- * expands to (so a summary row can never contradict its own list), and it is- * one batched read, never one per acceptance โ this runs on every graph poll.- */- private collectAcceptances = async (- graph: GoalGraphSnapshot,- ): Promise<Record<string, GoalNodeAcceptance> | undefined> => {- const taskNodes = graph.nodes.filter(- (node): node is GoalGraphNode & { taskId: string } => node.kind === 'task' && !!node.taskId,- );- if (taskNodes.length === 0) return undefined;-- const nodeByTaskId = new Map(taskNodes.map((node) => [node.taskId, node.id]));- const rows = await this.acceptanceService.acceptanceModel.findBySubjects(- 'task',- taskNodes.map((node) => node.taskId),- );-- // An acceptance with no round yet is absent from the tally map, not zero โ- // keep "no round" and "judged nothing" apart on the page.- const tallies = await this.acceptanceService.getCheckTalliesByAcceptances(- rows.map((row) => row.id),- );-- const result: Record<string, GoalNodeAcceptance> = {};- for (const row of rows) {- const nodeId = nodeByTaskId.get(row.subjectId);- if (!nodeId) continue;- const checks = tallies.get(row.id);- result[nodeId] = { id: row.id, status: row.status, ...(checks ? { checks } : {}) };- }- return Object.keys(result).length > 0 ? result : undefined;- };-- /**- * When an active task node's newest run delivered, for the nodes waiting on- * verification to settle.- *- * A verify-bound task keeps its node `active` while its topic is already- * `completed`, and the judgment is a full agent run that routinely outlives- * the operation lease โ `decideNextMove` holds off re-dispatching such a node- * for a whole `VERIFY_SETTLE_GRACE_MS`. But a completed topic is not a- * *running* one, so it contributes no heartbeat, and a client judging- * liveness from heartbeats alone declared the goal's most informative moment- * โ delivered, being verified โ lost. Reporting the delivery instant lets the- * client name that state and apply the coordinator's own grace window instead- * of the lease.- */- private collectDeliveredAt = async (- graph: GoalGraphSnapshot,- ): Promise<Record<string, Date> | undefined> => {- const activeTasks = graph.nodes.filter(- (node): node is GoalGraphNode & { taskId: string } =>- node.kind === 'task' && node.status === 'active' && !!node.taskId,- );- if (activeTasks.length === 0) return undefined;-- const nodeByTaskId = new Map(activeTasks.map((node) => [node.taskId, node.id]));- // Newest run per task: `findWithHandoffByTaskIds` orders by seq desc, so the- // first row seen for a task is its latest.- const topics = await this.taskTopicModel.findWithHandoffByTaskIds(- activeTasks.map((n) => n.taskId),- activeTasks.length,- );-- const delivered: Record<string, Date> = {};- const seen = new Set<string>();- for (const topic of topics) {- const taskId = topic.sourceTaskId;- if (!taskId || seen.has(taskId)) continue;- seen.add(taskId);- const nodeId = nodeByTaskId.get(taskId);- // Only the newest run counts, and only while it is a delivery: an older- // completed run under a newer running one is history, not a pending- // verification.- if (!nodeId || topic.status !== 'completed') continue;- delivered[nodeId] = topic.completedAt ?? topic.createdAt;- }-- return Object.keys(delivered).length > 0 ? delivered : undefined;- };-- /**- * Live heartbeat per active task node: the `agent_operations.updatedAt` of- * the run behind it. The runtime refreshes that lease every ~90s while- * `goal_nodes.updatedAt` only moves on observations / status changes, so a- * client judging liveness from the node row alone would cry "lost" over any- * long quiet stretch (a big tool call, the verify stage) the reclaim path- * considers perfectly healthy.- */- private collectRunHeartbeats = async (- graph: GoalGraphSnapshot,- ): Promise<Record<string, Date> | undefined> => {- const activeTasks = graph.nodes.filter(- (node): node is GoalGraphNode & { taskId: string } =>- node.kind === 'task' && node.status === 'active' && !!node.taskId,- );- if (activeTasks.length === 0) return undefined;-- const nodeByTaskId = new Map(activeTasks.map((node) => [node.taskId, node.id]));- const running = await this.taskTopicModel.findRunningByTaskIds(- activeTasks.map((n) => n.taskId),- );-- // One batched read: the graph polls every few seconds per open client, so- // a per-topic operation lookup would scale queries with task concurrency.- const operationIds = [- ...new Set(running.flatMap((topic) => (topic.operationId ? [topic.operationId] : []))),- ];- const operations = await new AgentOperationModel(- this.db,- this.userId,- this.workspaceId,- ).findByIds(operationIds);- const operationById = new Map(operations.map((operation) => [operation.id, operation]));-- const heartbeats: Record<string, Date> = {};- for (const topic of running) {- const nodeId = topic.taskId ? nodeByTaskId.get(topic.taskId) : undefined;- if (!nodeId || !topic.operationId || heartbeats[nodeId]) continue;- const updatedAt = operationById.get(topic.operationId)?.updatedAt;- if (updatedAt) heartbeats[nodeId] = updatedAt;- }-- return Object.keys(heartbeats).length > 0 ? heartbeats : undefined;- };-- /** Current lifecycle status, without paying for the whole graph. */- status = async (goalId: string): Promise<GoalStatus | undefined> =>- (await this.goalModel.findById(goalId))?.status;-- addNode = async (goalId: string, input: CreateGoalNodeInput) => {- const node = await this.graphModel.createNode(goalId, input);- if (!node) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- return node;- };-- addEdge = async (- goalId: string,- sourceNodeId: string,- targetNodeId: string,- kind: GoalEdgeKind,- ) => {- const edge = await this.graphModel.createEdge(goalId, sourceNodeId, targetNodeId, kind);- if (!edge) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- return edge;- };-- /**- * Stop everything the goal has running, then delete it and its graph.- *- * Deleting only the goal row cascades the graph away but leaves each graph- * Task โ and the agent operation behind it โ running, spending the user's- * budget with nothing left on screen to stop it. The tasks themselves stay:- * they are ordinary tasks with their own history and acceptance.- */- delete = async (goalId: string) => {- let graph = await this.graphModel.getGraph(goalId);- const managed = !!graph?.goal.config?.manager;- const supervised =- !!graph?.goal.config?.supervision?.enabled || !!graph?.goal.config?.supervisorState;- if (managed || supervised) {- // Fence new claims before cancellation, then read the latest claimed turn.- await this.db.transaction(async (db) => {- const model = new GoalModel(db, this.userId, this.workspaceId);- const current = await model.lockById(goalId);- if (current && current.status !== 'paused') {- await model.updateStatus(goalId, 'paused');- await new GoalGraphModel(db, this.userId, this.workspaceId).recordGoalStatus(- goalId,- current.status,- 'paused',- 'Stopping Goal before deletion',- );- }- });- graph = await this.graphModel.getGraph(goalId);- if (graph) {- if (managed)- await new GoalManagerService(this.db, this.userId, this.workspaceId).stop(graph);- if (supervised)- await new GoalSupervisorService(this.db, this.userId, this.workspaceId).stop(graph);- }- }- const taskIds = graph?.nodes.flatMap((node) => (node.taskId ? [node.taskId] : [])) ?? [];-- for (const taskId of taskIds) {- const topics = await this.taskTopicModel.findByTaskId(taskId);- for (const topic of topics) {- if (topic.status !== 'running' || !topic.topicId) continue;- // Deliberately not swallowed. Interrupting can fail โ the runtime or a- // device gateway may be unreachable โ and going ahead would delete the- // only surface that can stop an operation which keeps spending. Better- // to leave the goal intact and say so.- try {- await this.taskService.cancelTopic(topic.topicId);- } catch (error) {- throw new TRPCError({- cause: error,- code: 'PRECONDITION_FAILED',- message:- 'Could not stop the work still running for this goal, so it was not deleted. Try again once the run is reachable.',- });- }- }- await this.taskModel- .updateStatusIfCurrent(taskId, 'running', 'paused')- .catch((error) => console.error('[GoalService.delete] failed to pause task:', error));- }-- if (managed || supervised) {- return this.db.transaction(async (db) => {- const model = new GoalModel(db, this.userId, this.workspaceId);- const current = await model.lockById(goalId);- if (- current &&- (current.status !== 'paused' ||- current.config?.managerState?.token !== graph?.goal.config?.managerState?.token ||- current.config?.managerState?.turns !== graph?.goal.config?.managerState?.turns ||- current.config?.supervisorState?.revision !==- graph?.goal.config?.supervisorState?.revision)- ) {- throw new TRPCError({- code: 'CONFLICT',- message: 'Goal changed during cancellation; it was not deleted',- });- }- return model.delete(goalId);- });- }- return this.goalModel.delete(goalId);- };-- /**- * Move the goal's lifecycle status and leave an event behind.- *- * The row update alone made status changes untraceable: `entityType='goal'`- * events existed in the schema but nothing wrote them, so a goal's- * planning โ running โ paused โ achieved path could not be reconstructed- * from its timeline. Transitions the coordinator makes are filed under the- * coordinator actor; a person's pause/resume keeps the user attribution the- * model defaults to โ the split that separates what the coordinator decided- * from what the user asked for relies on.- *- * A same-status write is a no-op โ re-stamping `running` on every tick that- * touches a running goal would flood the timeline the way the unbounded- * event read flooded the payload.- */- private transitionStatus = async (- goal: GoalItem,- to: GoalStatus,- reason?: string,- actor: 'coordinator' | 'user' = 'coordinator',- ): Promise<GoalItem | undefined> => {- if (goal.status === to) return goal;- const updated = await this.goalModel.updateStatus(goal.id, to);- if (!updated) return undefined;- const model = actor === 'coordinator' ? this.coordinatorGraph : this.graphModel;- await model- .recordGoalStatus(goal.id, goal.status, to, reason)- .catch((error) => console.error('[GoalService] failed to record goal status:', error));- return updated;- };-- pause = async (goalId: string) => {- const graph = await this.requireGraph(goalId);- // A draft never ran; pausing it would let a later resume skip `start`.- if (graph.goal.status === 'draft') throw draftNotStarted(goalId);- // From here the pause is the person's, so no later measurement lifts it.- // Written even when the goal is already paused โ that transition is a- // no-op, so this marker is the only record that the person took it over.- await this.setPauseReason(goalId, 'user');- const goal = await this.transitionStatus(graph.goal, 'paused', 'paused by user', 'user');- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- return goal;- };-- /**- * What the goal has spent against what it is allowed to spend.- *- * Rounds are counted across every Task in the graph, not per Task โ the- * budget is the goal's, so `setBudget` has to read it exactly the way the- * coordinator does or raising a budget would not reliably unstick a goal.- *- * The calendar-time budget (schedule.deadline) is evaluated in the same- * shape: time is the long-horizon budget unit the attempt/round/dollar trio- * cannot express, and a goal whose deadline passed must stop the same way a- * goal out of money does.- */- /**- * Read every declared numeric clause against its series' latest observation.- *- * A missing series or a series with no points reads as `null` and fails its- * clause: "never measured" is not "satisfied". The measured value is carried- * out with the verdict so the trajectory records what the decision saw.- */- private evaluateMetricCriteria = async (- graph: GoalGraphSnapshot,- ): Promise<GoalMetricCriteriaState> => {- const declared = graph.goal.config?.acceptance?.metrics ?? [];- const metricModel = new MetricModel(this.db, this.userId, this.workspaceId);-- // Two queries for the whole contract, not two per clause: this runs on- // every terminal tick, and a goal carrying a large acceptance payload would- // otherwise pace the connection pool for unrelated requests. Only the- // declared keys are fetched โ the same goal can accumulate any number of- // other sampled series, and none of them can gate acceptance.- const series = await metricModel.findByKeys(- 'goal',- graph.goal.id,- declared.map((criterion) => criterion.key),- );- const seriesByKey = new Map(series.map((item) => [item.key, item]));- const latestByMetricId = await metricModel.latestPointsByMetricIds(- declared.flatMap((criterion) => {- const id = seriesByKey.get(criterion.key)?.id;- return id ? [id] : [];- }),- );-- const criteria = declared.map((criterion) => {- const op = criterion.op ?? 'gte';- const seriesId = seriesByKey.get(criterion.key)?.id;- const point = seriesId ? latestByMetricId.get(seriesId) : undefined;- const value = point?.value ?? null;- return {- key: criterion.key,- met: value !== null && compareMetric(value, op, criterion.target),- observedAt: point ? new Date(point.observedAt).getTime() : undefined,- op,- target: criterion.target,- value,- };- });-- return { allMet: criteria.every((criterion) => criterion.met), criteria };- };-- private evaluateBudget = async (goal: GoalItem, graph: GoalGraphSnapshot) => {- const { runs, totalCost } = await this.resolveSpend(graph);- const deadline = goal.config?.schedule?.deadline ?? null;- return {- costLimitReached: goal.maxTotalCost !== null && totalCost >= Number(goal.maxTotalCost),- deadline,- deadlinePassed: deadline !== null && Date.now() >= new Date(deadline).getTime(),- roundLimitReached: goal.maxRounds !== null && runs >= goal.maxRounds,- runs,- totalCost,- };- };-- /**- * Rounds run and dollars spent, by the definition the budget is enforced- * against: the runs of the graph's own Task nodes.- *- * `graph()` ships this to the client so the page's spend reads the same- * number the coordinator will stop on. Note it is deliberately NOT the goal- * list's `totalRunCost`, which walks the whole `parent_task_id` subtree โ- * that number is larger for a goal whose Tasks spawned Tasks.- */- private resolveSpend = async (graph: GoalGraphSnapshot) => {- const [spend, supervision, management] = await Promise.all([- this.taskTopicModel.sumRunCostByTaskIds(- graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : [])),- ),- new GoalSupervisorService(this.db, this.userId, this.workspaceId).usage(- graph.goal.config?.supervisorState,- ),- new GoalManagerService(this.db, this.userId, this.workspaceId).usage(- graph.goal.id,- graph.goal.config?.managerState,- ),- ]);- return {- ...spend,- totalCost: spend.totalCost + supervision.totalCost + management.totalCost,- totalTokens: spend.totalTokens + supervision.totalTokens + management.totalTokens,- };- };-- /**- * Edit the goal's standing acceptance requirement in place. The next- * coordinator move and every later dispatched Task read the updated text;- * an already-running Task keeps the contract it was dispatched with.- */- updateRequirement = async (goalId: string, requirement: string) => {- const goal = await this.goalModel.update(goalId, { requirement });- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- return goal;- };-- /**- * Hand the goal to a different agent. The goal agent supervises: it owns the- * goal page and list entry and runs every planning turn. When it also does- * the goal's own Tasks (no separate `taskAgentId`), every Task the- * coordinator creates from here on goes to the new agent and โ unless the- * caller opts out โ the unfinished ones move with it. A goal whose Tasks go- * to a dedicated executor keeps them there; see `setTaskAgent`.- *- * The management conversation moves with supervision: it lives in the goal- * agent's own history, so it is re-created for the new agent here instead of- * being left pointing at the previous agent's topic until the next claim.- */- setAgent = async (- goalId: string,- agentId: string,- options?: { goalOnly?: boolean },- ): Promise<{ goal: GoalItem; reassignedTaskIds: string[] }> => {- await assertAgentUsableBy(this.db, agentId, {- userId: this.userId,- workspaceId: this.workspaceId,- });- const goal = await this.goalModel.update(goalId, { agentId });- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });-- // The receipt carries the management topic, so the caller must get the row- // with the migrated one โ not the copy read before the handoff.- const migrated = await new GoalManagerService(- this.db,- this.userId,- this.workspaceId,- ).moveConversationTo(goalId, agentId);-- const reassignedTaskIds = await this.followGoalAgent(goal, agentId, options?.goalOnly);- return {- goal: migrated ? ((await this.goalModel.findById(goalId)) ?? goal) : goal,- reassignedTaskIds,- };- };-- /**- * After the goal agent changed: when that agent also does the goal's Tasks,- * unfinished ones follow it unless the caller keeps them (`goalOnly`). A goal- * with a dedicated executor keeps its Tasks there.- */- private followGoalAgent = async (- goal: Pick<GoalItem, 'config' | 'id'>,- agentId: string,- goalOnly?: boolean,- ) => (goalOnly || goal.config?.taskAgentId ? [] : this.reassignUnfinishedTasks(goal.id, agentId));-- /**- * Route the goal's Tasks to a dedicated executor, or back to the goal agent- * with `null`. The goal agent keeps supervising either way. Unfinished Tasks- * move with the change unless the caller opts out.- */- setTaskAgent = async (- goalId: string,- agentId: string | null,- options?: { goalOnly?: boolean },- ): Promise<{ goal: GoalItem; reassignedTaskIds: string[] }> => {- if (agentId) {- await assertAgentUsableBy(this.db, agentId, {- userId: this.userId,- workspaceId: this.workspaceId,- });- }- const current = await this.goalModel.findById(goalId);- if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- // Naming the goal agent itself is the same as clearing: one agent, one slot.- const goal = await this.goalModel.updateTaskAgentId(- goalId,- agentId && agentId !== current.agentId ? agentId : null,- );- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });-- const assignee = goalTaskAgentId(goal);- const reassignedTaskIds =- options?.goalOnly || !assignee ? [] : await this.reassignUnfinishedTasks(goalId, assignee);- return { goal, reassignedTaskIds };- };-- /**- * The agent the next coordinator-created Task goes to.- *- * `taskAgentId` lives in JSON, so deleting the executor does not null it the- * way the `agent_id` foreign key is nulled. Handing that stale id to- * `createTask` fails with NOT_FOUND on every tick and the goal can never- * create work again โ so a missing executor falls back to the goal agent.- */- private resolveTaskAssignee = async (goal: GoalItem) => {- const taskAgentId = goal.config?.taskAgentId;- if (taskAgentId && !(await this.agentModel.existsById(taskAgentId)))- return goal.agentId ?? undefined;- return goalTaskAgentId(goal);- };-- /**- * Snapshot the graph AFTER the goal row moved: a task the coordinator binds- * later inherits the new assignee from the goal, and a task bound before is in- * this snapshot โ so no concurrently created task can slip through the- * handoff still pointing at the previous agent. A Task mid-run keeps its- * current operation; `runTask` reads the assignee at its next dispatch.- */- private reassignUnfinishedTasks = async (goalId: string, agentId: string) => {- const graph = await this.requireGraph(goalId);- const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));- const reassigned: string[] = [];- for (const task of await this.taskModel.findByIds(taskIds)) {- if (task.status === 'completed' || task.status === 'canceled') continue;- if (task.assigneeAgentId === agentId) continue;- await this.taskModel.update(task.id, { assigneeAgentId: agentId });- reassigned.push(task.id);- }- return reassigned;- };-- /**- * Start every unfinished Task node over: interrupt the run it may still be- * holding, clear the failure it may be parked on, and return the Task to- * `backlog` so the next coordinator tick dispatches it afresh. Optionally- * hands the restarted Tasks to a different agent in the same gesture โ the- * goal's executor slot moves with them: `taskAgentId` when the goal routes- * work to a dedicated executor, otherwise the goal agent that does its own- * Tasks. Resolved nodes and their completed Tasks are left untouched.- */- restart = async (- goalId: string,- options?: { agentId?: string },- ): Promise<{ goal: GoalItem; restartedTaskIds: string[] }> => {- if (options?.agentId) {- await assertAgentUsableBy(this.db, options.agentId, {- userId: this.userId,- workspaceId: this.workspaceId,- });- }- const graph = await this.requireGraph(goalId);-- const unfinishedNodes = graph.nodes.filter(- (node) =>- node.kind === 'task' &&- !isGoalReportNode(graph, node) &&- node.taskId &&- !TERMINAL_NODE_STATUSES.has(node.status),- );- const unfinishedNodeIds = new Set(unfinishedNodes.map((node) => node.id));- const unfinishedTaskIds = unfinishedNodes.flatMap((node) => (node.taskId ? [node.taskId] : []));-- // A restarted task's pending failure gate is answered by the restart- // itself. Left pending, it would keep winning the coordinator's- // pending-decision branch and the goal would sit `waiting_human` with- // every task freshly reset. Gates on untouched nodes keep parking the- // goal โ they ask something this restart does not answer.- // Gate edges run task-node โ decision-node (see openFailureDecision).- const staleGates = graph.decisions.filter(- (decision) =>- decision.status === 'pending' &&- graph.edges.some(- (edge) =>- edge.kind === 'leads_to' &&- edge.targetNodeId === decision.nodeId &&- unfinishedNodeIds.has(edge.sourceNodeId),- ),- );- for (const gate of staleGates) {- await this.graphModel.cancelDecision(goalId, gate.id, 'Superseded by goal restart');- }-- const restartedTaskIds: string[] = [];- if (unfinishedTaskIds.length > 0) {- const runningTopics = await this.taskTopicModel.findRunningByTaskIds(unfinishedTaskIds);- for (const topic of runningTopics) {- if (topic.topicId) await this.taskService.cancelTopic(topic.topicId);- }- // Re-read after the cancels and reset via compare-and-swap: a coordinator- // tick dispatching concurrently moves the row between our read and the- // write, the CAS loses, and that task is skipped instead of yanked out- // from under a freshly claimed run (which would double-dispatch it).- for (const task of await this.taskModel.findByIds(unfinishedTaskIds)) {- if (task.status === 'completed') continue;- const reset = await this.taskModel.updateStatusIfCurrent(task.id, task.status, 'backlog', {- error: null,- });- if (!reset) continue;- if (options?.agentId) {- await this.taskModel.update(task.id, { assigneeAgentId: options.agentId });- }- restartedTaskIds.push(task.id);- }- }-- // The handoff lands only after the interrupts succeeded โ a cancelTopic- // failure above must not leave the goal pointing at the new agent while- // its tasks and live runs still belong to the old one.- let goal = graph.goal;- if (options?.agentId) {- const updated = goal.config?.taskAgentId- ? await this.goalModel.updateTaskAgentId(goalId, options.agentId)- : await this.goalModel.update(goalId, { agentId: options.agentId });- if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- goal = updated;- }-- // A restart is an explicit "start over": a goal parked by a budget stop or- // a manual pause must begin ticking again without a second gesture.- if (goal.status === 'paused') {- goal = (await this.resume(goalId)) ?? goal;- }- return { goal, restartedTaskIds };- };-- /**- * Task access under the goal owner's principal โ the identity the goal's- * coordinator creates and runs its Tasks as. Only for acting on Tasks already- * bound to this goal's nodes, after the caller's right to manage the goal has- * been checked.- */- private goalOwnerTaskScope = (goal: { userId: string }) =>- goal.userId === this.userId- ? {- taskModel: this.taskModel,- taskService: this.taskService,- taskTopicModel: this.taskTopicModel,- }- : {- taskModel: new TaskModel(this.db, goal.userId, this.workspaceId),- taskService: new TaskService(this.db, goal.userId, this.workspaceId),- taskTopicModel: new TaskTopicModel(this.db, goal.userId, this.workspaceId),- };-- /**- * Stop the Tasks bound to nodes already fenced as `retired`, so a retired- * node cannot keep spending or deliver into the Goal afterwards. Bound Tasks- * are read after the fence so a Task bound just before it is included.- * Returns the graph as read after the fence.- */- private stopFencedTasks = async (goalId: string, targetIds: ReadonlySet<string>) => {- const fenced = await this.requireGraph(goalId);- const taskIds = fenced.nodes.flatMap((node) =>- targetIds.has(node.id) && node.taskId ? [node.taskId] : [],- );- if (taskIds.length > 0) {- // The caller may be a workspace owner retiring a colleague's goal (the- // router authorizes that). The nodes' Tasks were created by the goal's- // coordinator, which runs as the goal's owner โ and may be `private`,- // inherited from that owner's private agent โ so reads under the caller's- // visibility would miss them and leave them running. Stop them under the- // goal owner's principal instead, limited to the Tasks bound to the nodes- // being retired.- const { taskModel, taskService, taskTopicModel } = this.goalOwnerTaskScope(fenced.goal);- const cancelTasks = async () => {- for (const id of taskIds) {- // CAS against the status just read; a runner flipping the Task to- // `running` in between makes it miss, so re-read and try again.- for (let attempt = 0; attempt < 3; attempt++) {- const [task] = await taskModel.findByIds([id]);- if (!task || ['canceled', 'completed', 'failed'].includes(task.status)) break;- if (await taskModel.updateStatusIfCurrent(id, task.status, 'canceled')) break;- }- }- };- // Cancel the Tasks FIRST: that is the fence a run still being dispatched- // checks under the Task's row lock before recording its operation, so a- // run started from here on stops itself (TaskRunnerService.runTask).- // Runs recorded before the fence are then found and stopped below.- await cancelTasks();- for (const topic of await taskTopicModel.findRunningByTaskIds(taskIds)) {- if (topic.topicId) await taskService.cancelTopic(topic.topicId);- }- // `cancelTopic` parks its Task as `paused`; settle them back to canceled.- await cancelTasks();- }-- return fenced;- };-- /**- * Retire Task nodes a person no longer wants run โ a duplicated plan branch,- * work that landed elsewhere. Without this a stray node that never got a Task- * stays unfinished forever and the coordinator can never reach acceptance.- *- * Nodes are retired as one set: any unfinished Task still depending on a node- * in the set must be in the set too, otherwise it would wait on a- * prerequisite that will never resolve.- */- retireNodes = async (- goalId: string,- nodeIds: string[],- reason?: string,- ): Promise<{ retiredNodeIds: string[] }> => {- const graph = await this.requireGraph(goalId);- const targetIds = new Set(nodeIds);-- const targets = [...targetIds].map((nodeId) => {- const node = graph.nodes.find((item) => item.id === nodeId);- if (!node) throw new TRPCError({ code: 'NOT_FOUND', message: `Node ${nodeId} not found` });- if (node.kind !== 'task') {- throw new TRPCError({- code: 'BAD_REQUEST',- message: `Node ${nodeId} is a ${node.kind}; only task nodes can be retired`,- });- }- // An already-retired node is accepted so an interrupted retirement (its- // fence landed, stopping the run did not) can be finished by retrying.- if (node.status !== 'retired' && TERMINAL_NODE_STATUSES.has(node.status)) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: `Node ${nodeId} is already ${node.status}`,- });- }- // Retiring the terminal acceptance fails the whole Goal; that verdict- // belongs to its decision gate, not to a graph edit.- if (node.title === GOAL_ACCEPTANCE_TASK_TITLE) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'The Goal acceptance task cannot be retired',- });- }- return node;- });-- const strandedIds = graph.edges- .filter(- (edge) =>- edge.kind === 'depends_on' &&- targetIds.has(edge.targetNodeId) &&- !targetIds.has(edge.sourceNodeId),- )- .map((edge) => graph.nodes.find((node) => node.id === edge.sourceNodeId))- .filter(- (node): node is NonNullable<typeof node> =>- !!node && node.kind === 'task' && !TERMINAL_NODE_STATUSES.has(node.status),- )- .map((node) => node.id);- if (strandedIds.length > 0) {- throw new TRPCError({- code: 'CONFLICT',- message: `Unfinished tasks depend on these nodes; retire them together: ${[...new Set(strandedIds)].join(', ')}`,- });- }-- // Fence the nodes BEFORE looking for their Tasks. The snapshot above can- // miss a Task a concurrent tick is creating for a proposed node; once the- // node reads `retired`, `bindTask` (which only binds an `active` node) can- // no longer attach that Task, and the creator discards it.- for (const node of targets) {- if (node.status === 'retired') continue;- await this.graphModel.updateNodeStatus(goalId, node.id, 'retired', reason);- }-- // Stop what the nodes are still running, so a retired node cannot keep- // spending or deliver into the Goal afterwards.- const fenced = await this.stopFencedTasks(goalId, targetIds);-- // A pending recovery gate on a retired node asks a question nobody needs- // answered any more; left pending it keeps the Goal parked in review.- for (const decision of fenced.decisions) {- if (decision.status !== 'pending') continue;- const gatedByTarget = fenced.edges.some(- (edge) =>- edge.kind === 'leads_to' &&- edge.targetNodeId === decision.nodeId &&- targetIds.has(edge.sourceNodeId),- );- if (gatedByTarget) {- await this.graphModel.cancelDecision(goalId, decision.id, 'Superseded by node retirement');- }- }-- // Reopen a goal the coordinator parked because of what was just retired:- // `review` held by the retired node's gate, or `paused` by `no_frontier`- // (the stray branch left nothing runnable). A pause somebody chose โ or- // one the coordinator took for another reason, like a budget โ is left.- const after = await this.requireGraph(goalId);- const lastTransition = after.events.find((event) => event.entityType === 'goal');- const parkedOnNoFrontier =- after.goal.status === 'paused' &&- !after.goal.config?.pausedBy &&- lastTransition?.actorType !== 'user' &&- lastTransition?.reason === NO_FRONTIER_PAUSE_REASON;- if (after.goal.status === 'review' || parkedOnNoFrontier) {- const hasPendingDecision = after.decisions.some((decision) => decision.status === 'pending');- if (!hasPendingDecision) {- await this.transitionStatus(after.goal, 'running', 'nodes retired by user', 'user');- } else if (parkedOnNoFrontier) {- await this.transitionStatus(after.goal, 'review', 'nodes retired by user', 'user');- }- }-- return { retiredNodeIds: targets.map((node) => node.id) };- };-- setBudget = async (- goalId: string,- budget: {- deadline?: string | null;- maxAttemptsPerTask?: number;- maxConcurrentTasks?: number | null;- maxExperiments?: number;- maxManagerTurns?: number;- maxRounds?: number | null;- maxStepsPerRun?: number | null;- maxTotalCost?: number | null;- },- ) => {- const before = await this.requireGraph(goalId);- const wasBinding = await this.evaluateBudget(before.goal, before);- const managerTurnsWereSpent = managerTurnsSpent(before.goal.config);-- // Deadline joins the two execution budgets on the goal row's config; null- // clears it, and omitting it leaves it alone โ the cost/round editor sends- // only what it owns, and must not silently drop a deadline someone set.- // The merge keeps an untouched recovery/schedule block intact.- const config = { ...before.goal.config };- if (budget.maxExperiments !== undefined) {- if (- !config.exploration ||- !Number.isInteger(budget.maxExperiments) ||- budget.maxExperiments < 1 ||- budget.maxExperiments > 200- ) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'An exploration Goal requires 1โ200 experiments',- });- }- config.exploration = { ...config.exploration, maxExperiments: budget.maxExperiments };- }- if (budget.deadline !== undefined) {- config.schedule = { ...config.schedule, deadline: budget.deadline };- }- // The limits a goal is created with stay editable: a goal that ran into one- // must be continued with a higher one, not replaced by a copy of itself.- if (budget.maxManagerTurns !== undefined) {- if (!config.manager) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Only a Goal with a main Agent has a turn budget',- });- }- config.manager = { ...config.manager, maxTurns: budget.maxManagerTurns };- }- if (budget.maxConcurrentTasks !== undefined) {- config.maxConcurrentTasks = budget.maxConcurrentTasks;- }- if (budget.maxAttemptsPerTask !== undefined || budget.maxStepsPerRun !== undefined) {- config.recovery = {- ...config.recovery,- ...(budget.maxAttemptsPerTask !== undefined && {- maxAttemptsPerTask: budget.maxAttemptsPerTask,- }),- ...(budget.maxStepsPerRun !== undefined && { maxStepsPerRun: budget.maxStepsPerRun }),- };- }-- const goal = await this.goalModel.update(goalId, {- config,- maxRounds: budget.maxRounds,- maxTotalCost: budget.maxTotalCost,- });- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });-- // Raising a budget is how a user un-sticks a goal the coordinator parked on- // one, and `tick` refuses to move a paused goal โ so without this the- // queued advance would return straight away and the user would have to find- // Resume as a second gesture. Only a goal the budget actually stopped is- // reopened: if the old budget was not binding, this pause was somebody's- // deliberate one and is left alone.- const stoppedByBudget =- wasBinding.costLimitReached || wasBinding.roundLimitReached || wasBinding.deadlinePassed;- const stoppedByExploration = before.goal.config?.pausedBy === 'exploration_limit';- // The main Agent pauses its goal when its turns run out, and resuming alone- // pauses it again on the next tick. Raising the cap is what lets it continue.- const stoppedByManagerTurns = managerTurnsWereSpent && !managerTurnsSpent(goal.config);- if (- goal.status !== 'paused' ||- goal.config?.pausedBy === 'user' ||- (!stoppedByBudget && !stoppedByExploration && !stoppedByManagerTurns)- )- return goal;- if (- stoppedByExploration &&- before.nodes.filter(- (node) =>- node.kind === 'task' &&- node.title !== GOAL_ACCEPTANCE_TASK_TITLE &&- !isGoalReportNode(before, node),- ).length >= (goal.config?.exploration?.maxExperiments ?? 0)- )- return goal;-- const nowBinding = await this.evaluateBudget(goal, before);- if (nowBinding.costLimitReached || nowBinding.roundLimitReached || nowBinding.deadlinePassed) {- return goal;- }-- return (await this.resume(goalId)) ?? goal;- };-- resume = async (goalId: string) => {- const graph = await this.requireGraph(goalId);- const status = graph.decisions.some((decision) => decision.status === 'pending')- ? 'review'- : 'running';- // Compare-and-set under the row lock `close` commits under: a resume that- // read the goal before a concurrent close ended it must not write its stale- // `running` over the ended goal, where the close already put interrupted- // Tasks back to `backlog` and they would dispatch again. Reopening an ended- // goal still works โ that resume reads the ended status itself.- return this.db.transaction(async (tx) => {- const model = new GoalModel(tx, this.userId, this.workspaceId);- const current = await model.lockById(goalId);- if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- // Only `start` launches a draft: it settles the creating run's planning- // turn and checks who may launch it, which a plain status flip skips.- if (current.status === 'draft') throw draftNotStarted(goalId);- if (current.status !== graph.goal.status) {- throw new TRPCError({- code: 'CONFLICT',- message: 'The goal changed while it was being resumed; try again.',- });- }- await model.updatePauseReason(goalId, undefined);- if (current.status === status) return current;- const updated = await model.updateStatus(goalId, status);- await new GoalGraphModel(tx, this.userId, this.workspaceId)- .recordGoalStatus(goalId, current.status, status, 'resumed by user')- .catch((error) => console.error('[GoalService] failed to record goal status:', error));- return updated ?? current;- });- };-- /**- * A person ends the goal themselves โ declaring it achieved or dropping it.- *- * Everything still spending on the goal is interrupted first โ the main- * Agent's planning turn, the supervisor's diagnosis and every Task run โ the- * same way `delete` does, because a terminal status alone only stops the- * coordinator from dispatching more. Reopening goes through `resume`, which- * accepts any status.- */- close = async (goalId: string, to: 'achieved' | 'canceled') => {- // Fence new claims before scanning: `dispatchWork` claims under this row- // lock and only while the goal reads `running`, so an advance overlapping- // the close cannot start a Task after the scan below. The pause is the- // person's, so no measurement lifts it if the close is refused later on.- await this.db.transaction(async (db) => {- const model = new GoalModel(db, this.userId, this.workspaceId);- const current = await model.lockById(goalId);- // Only a goal that can still dispatch needs fencing.- if (!current || ['paused', 'achieved', 'failed', 'canceled'].includes(current.status)) return;- await model.updateStatus(goalId, 'paused');- await model.updatePauseReason(goalId, 'user');- await new GoalGraphModel(db, this.userId, this.workspaceId).recordGoalStatus(- goalId,- current.status,- 'paused',- 'Stopping Goal before closing',- );- });- const graph = await this.requireGraph(goalId);-- // Deliberately not swallowed, as in `delete`: an operation whose exit is- // unconfirmed keeps spending, and a goal reading "ended" would hide it. The- // goal stays paused so nothing new starts, and the person can retry.- const notClosed = (error: unknown) =>- new TRPCError({- cause: error,- code: 'PRECONDITION_FAILED',- message:- 'Could not stop the work still running for this goal, so it was not closed. Try again once the run is reachable.',- });- try {- if (graph.goal.config?.manager)- await new GoalManagerService(this.db, this.userId, this.workspaceId).stop(graph);- if (graph.goal.config?.supervision?.enabled || graph.goal.config?.supervisorState)- await new GoalSupervisorService(this.db, this.userId, this.workspaceId).stop(graph);- } catch (error) {- throw notClosed(error);- }-- const unfinishedTaskIds = graph.nodes.flatMap((node) =>- node.kind === 'task' && node.taskId && !TERMINAL_NODE_STATUSES.has(node.status)- ? [node.taskId]- : [],- );- if (unfinishedTaskIds.length > 0) {- // Claims whose run has not been recorded yet. `dispatchWork` marks the- // Task `running` before `runTask` records the topic, so the scan below- // cannot see that run, and only a recorded run can be interrupted with- // confirmation. A fresh claim therefore refuses the close: the goal stays- // fenced, and a retry a moment later finds the run recorded and stops it- // the confirmed way. A claim older than the operation lease is one whose- // startup died; it is withdrawn to `backlog` under the task row lock the- // recording also takes, so a straggler recording stops its own run.- const staleBefore = Date.now() - resolveOperationLeaseTimeout(graph.goal);- let starting = false;- for (const taskId of unfinishedTaskIds) {- await this.db.transaction(async (tx) => {- const taskModel = new TaskModel(tx, this.userId, this.workspaceId);- if (!(await taskModel.lockForUpdate(taskId))) return;- const task = await taskModel.findById(taskId);- if (task?.status !== 'running') return;- const recorded = await new TaskTopicModel(- tx,- this.userId,- this.workspaceId,- ).findRunningByTaskIds([taskId]);- if (recorded.length > 0) return;- if (task.updatedAt.getTime() > staleBefore) {- starting = true;- return;- }- await taskModel.updateStatusIfCurrent(taskId, 'running', 'backlog', { error: null });- });- }- if (starting)- throw new TRPCError({- code: 'PRECONDITION_FAILED',- message:- 'A run for this goal is still starting, so it was not closed. No new work will start; try again in a moment.',- });-- const runningTopics = await this.taskTopicModel.findRunningByTaskIds(unfinishedTaskIds);- for (const topic of runningTopics) {- if (!topic.topicId) continue;- try {- await this.taskService.cancelTopic(topic.topicId);- } catch (error) {- throw notClosed(error);- }- // Reset right after its own interruption, as in `restart`: left `paused`- // it reads as parked on a person and a reopened goal waits on it. Doing- // it per run means a later failed interruption cannot strand the ones- // already stopped โ a retry no longer sees them as running. CAS so a- // row a concurrent tick just moved is never yanked.- const task = await this.taskModel.findById(topic.taskId);- if (task && task.status !== 'completed') {- await this.taskModel.updateStatusIfCurrent(task.id, task.status, 'backlog', {- error: null,- });- }- }- }- // Commit under the same lock the fence took, and only if the fence still- // holds: a resume from another tab during the interruption pass lets an- // advance claim work this pass never saw, and ending the goal over it- // would leave that run spending on a goal reading "ended".- const reason = to === 'achieved' ? 'marked achieved by user' : 'canceled by user';- const goal = await this.db.transaction(async (db) => {- const model = new GoalModel(db, this.userId, this.workspaceId);- const current = await model.lockById(goalId);- if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- if (!['paused', 'achieved', 'failed', 'canceled'].includes(current.status)) {- throw new TRPCError({- code: 'CONFLICT',- message: 'The goal was resumed while it was being closed, so it was not closed.',- });- }- await model.updatePauseReason(goalId, undefined);- if (current.status === to) return current;- const updated = await model.updateStatus(goalId, to);- await new GoalGraphModel(db, this.userId, this.workspaceId)- .recordGoalStatus(goalId, current.status, to, reason)- .catch((error) => console.error('[GoalService] failed to record goal status:', error));- return updated;- });- if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- return goal;- };-- decide = async (- goalId: string,- decisionId: string,- optionId: string,- resolution?: string,- options?: { fromReleaseGate?: boolean },- ) => {- const graph = await this.requireGraph(goalId);- // A goal a person ended stays ended: a gate another tab still shows must- // not reopen it. Checked again under the lock before the status moves.- if (GOAL_ENDED_STATUSES.has(graph.goal.status)) {- throw new TRPCError({ code: 'CONFLICT', message: 'This goal has ended' });- }- const decision = graph.decisions.find((item) => item.id === decisionId);- if (!decision || decision.status !== 'pending') {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Pending decision not found' });- }- if (decision.options?.length && !decision.options.some((option) => option.id === optionId)) {- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unknown decision option' });- }- // A held release with a review page is decided there, with its evidence โ- // not by a one-click answer from a surface that never showed it.- const heldRelease = graph.goal.config?.rolloutState;- if (- !options?.fromReleaseGate &&- heldRelease?.releaseGateAcceptanceId &&- heldRelease.releaseReviewNodeId === decision.nodeId- ) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'This release is decided on its review page',- });- }- // The note *is* the answer for this option; an empty one would re-plan the- // goal on nothing and the question could never be asked again.- if (optionId === GOAL_CLARIFICATION_OPTION.answer && !resolution?.trim()) {- throw new TRPCError({ code: 'BAD_REQUEST', message: 'This answer needs a note' });- }- // Revising a batch recipe without a correction would re-run the plan that- // just failed under a new version number. The correction is the revision.- if (optionId === GOAL_BATCH_BREAK_OPTION.revise && !resolution?.trim()) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Revising the recipe needs a correction',- });- }- const chosen = decision.options?.find((option) => option.id === optionId);- // R5: a person answering a batch gate IS the intervention, and an- // intervention rolls the class back to canary. Open the next recipe round- // automatically โ revise the same mould, or fork it as a new class โ rather- // than leaving the goal parked for someone to rerun by hand. The gate hangs- // on the Assay (materialized on demand for a `full` rollout), so match that,- // falling back to the batch node for any gate opened elsewhere. The restart- // consumes the answer itself, atomically with the round it opens.- const rolloutState = graph.goal.config?.rolloutState;- const batchGateNodeId =- rolloutState?.phase === 'release_review'- ? rolloutState.releaseReviewNodeId- : rolloutState?.phase === 'pattern_break'- ? (rolloutState.assayNodeId ?? rolloutState.batchNodeId)- : undefined;- const answersBatchGate = batchGateNodeId !== undefined && decision.nodeId === batchGateNodeId;- // A held release keeps its round either way: approving sends the wave out on- // the proven plan, sending it back has the main Agent rewrite that plan.- const resolved = !answersBatchGate- ? await this.graphModel.resolveDecision(goalId, decisionId, optionId, resolution)- : rolloutState?.phase !== 'release_review'- ? await this.restartRolloutLoop(goalId, decisionId, optionId, resolution)- : optionId === GOAL_BATCH_RELEASE_OPTION.release- ? await this.releaseReview.approveRolloutRelease(goalId, decisionId, optionId, resolution)- : // A release sent back goes to the main Agent, whoever answered it.- await this.releaseReview.sendRevisionToAgent(- goalId,- decision.nodeId,- decisionId,- resolution,- );- if (!resolved)- throw new TRPCError({ code: 'CONFLICT', message: 'Decision was already resolved' });-- const incoming = graph.edges.find(- (edge) => edge.targetNodeId === decision.nodeId && edge.kind === 'leads_to',- );- const source = incoming && graph.nodes.find((node) => node.id === incoming.sourceNodeId);- if (source?.kind === 'task') {- if (source.taskId)- await new GoalSupervisorService(this.db, this.userId, this.workspaceId).recordProgress(- graph,- source.taskId,- true,- );- const effect = decisionOptionEffect(chosen, source.title);- if (effect === 'retry' && source.taskId) {- await this.taskModel.updateStatus(source.taskId, 'backlog', { error: null });- await this.graphModel.updateNodeStatus(goalId, source.id, 'active', resolution);- // The note is guidance for the next attempt, so it goes where that- // attempt reads: the Task's comments are part of every run prompt.- // On the node status alone it was recorded and never read again.- const guidance = decisionGuidance(decision.question, chosen, resolution);- if (guidance)- await this.taskModel.addComment({- authorUserId: this.userId,- content: guidance,- taskId: source.taskId,- userId: this.userId,- });- } else if (effect === 'retire') {- await this.graphModel.updateNodeStatus(goalId, source.id, 'retired', resolution);- }- }- // Ending the terminal acceptance ends the Goal: `fail` is a verdict that- // the Goal failed, `retire` abandons it without one.- const terminalAcceptance = source?.title === GOAL_ACCEPTANCE_TASK_TITLE;- const terminalEffect = decisionOptionEffect(chosen, source?.title);- const nextStatus =- terminalAcceptance && terminalEffect === 'fail'- ? 'failed'- : terminalAcceptance && terminalEffect === 'retire'- ? 'canceled'- : 'running';- // Serialized with `close`, which commits under this row lock: a goal that- // ended while this answer was being written is left ended.- await this.db.transaction(async (tx) => {- const current = await new GoalModel(tx, this.userId, this.workspaceId).lockById(goalId);- if (!current || GOAL_ENDED_STATUSES.has(current.status)) return;- if (current.status === nextStatus) return;- await new GoalModel(tx, this.userId, this.workspaceId).updateStatus(goalId, nextStatus);- await new GoalGraphModel(tx, this.userId, this.workspaceId, {- id: GOAL_COORDINATOR_ACTOR_ID,- type: 'system',- })- .recordGoalStatus(- goalId,- current.status,- nextStatus,- `decision "${decision.question}" resolved: ${optionId}`,- )- .catch((error) => console.error('[GoalService] failed to record goal status:', error));- });- return resolved;- };-- /**- * The owner sent the Goal's delivery back (ๆๅบไฟฎๆน on the Goal-level- * acceptance). The acceptance passing is what ended the Goal, so without a- * reopen the coordinator reads it as still achieved and nothing reworks it.- * The acceptance Task goes back to the queue โ its next attempt reads the- * rejected round's comment through the prompt builder โ and the Goal runs- * again. When that attempt is accepted the Goal is achieved anew, and the- * wrap-up writes a new report version for the new result.- *- * Returns the reopened Goal id, or undefined when `taskId` is not a settled- * Goal-level acceptance of a Goal that can still be reworked; a stopped Goal- * is continued from its result, not reopened by a sign-off.- */- reopenForChanges = async (taskId: string, comment?: string): Promise<string | undefined> => {- const goal = await this.goalModel.findByGraphTask(taskId);- if (!goal || !REOPENABLE_GOAL_STATUSES.has(goal.status)) return undefined;- const graph = await this.requireGraph(goal.id);- const node = graph.nodes.find(- (candidate) =>- candidate.kind === 'task' &&- candidate.taskId === taskId &&- candidate.title === GOAL_ACCEPTANCE_TASK_TITLE,- );- if (node?.status !== 'resolved') return undefined;-- const reason = comment ? `Changes requested: ${comment}` : 'Changes requested';- await this.taskModel.updateStatus(taskId, 'backlog', { error: null });- await this.graphModel.updateNodeStatus(goal.id, node.id, 'active', reason);- await this.goalModel.update(goal.id, {- config: {- ...graph.goal.config,- changeRequest: {- ...(comment ? { comment } : {}),- requestedAt: new Date().toISOString(),- taskId,- },- },- });- await this.transitionStatus(graph.goal, 'running', reason, 'user');- return goal.id;- };-- /**- * Answer a goal's clarification round in one go. Each answer resolves like a- * single `decide`; the caller schedules one advance afterwards, so the- * re-plan sees every answer instead of running after the first.- */- answerClarifications = async (- goalId: string,- answers: Array<{ decisionId: string; optionId: string; resolution?: string }>,- ) => {- const graph = await this.requireGraph(goalId);- const decisions = new Map(graph.decisions.map((decision) => [decision.id, decision]));-- // Check the whole round before writing any of it: one bad answer used to- // leave the ones before it resolved, and the client's retry then failed on- // those. An answer already recorded as given is a retry, not a conflict.- const toResolve = answers.filter((answer) => {- const decision = decisions.get(answer.decisionId);- if (!decision) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Pending decision not found' });- }- if (decision.status === 'resolved' && decision.resolvedOptionId === answer.optionId) {- return false;- }- if (decision.status !== 'pending') {- throw new TRPCError({ code: 'CONFLICT', message: 'Decision was already resolved' });- }- if (decision.options?.length && !decision.options.some((o) => o.id === answer.optionId)) {- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unknown decision option' });- }- if (answer.optionId === GOAL_CLARIFICATION_OPTION.answer && !answer.resolution?.trim()) {- throw new TRPCError({ code: 'BAD_REQUEST', message: 'This answer needs a note' });- }- return true;- });-- for (const answer of toResolve) {- await this.decide(goalId, answer.decisionId, answer.optionId, answer.resolution);- }- };-- /**- * Everything the approval island asks outside a goal's page: the gates- * waiting on the person (clarification rounds have their own form) and the- * finished goals waiting for their sign-off.- */- pendingForIsland = async () => {- const [decisions, signOffs] = await Promise.all([- this.goalModel.listPendingDecisions(),- this.briefs.listOpenSignOffs(),- ]);- return {- decisions: decisions.map((row) => ({ ...row, options: row.options ?? [] })),- signOffs,- };- };-- /** Pending clarifications grouped by goal, for surfaces outside the goal page. */- pendingClarifications = async () => {- const rows = await this.goalModel.listPendingClarifications();- const byGoal = new Map<- string,- {- agentId: string | null;- goalId: string;- questions: Array<{- decisionId: string;- description: string | null;- options: GoalDecisionOption[];- question: string;- }>;- requirement: string | null;- title: string;- }- >();- for (const row of rows) {- const group = byGoal.get(row.goalId) ?? {- agentId: row.agentId,- goalId: row.goalId,- questions: [],- requirement: row.requirement,- title: row.goalTitle,- };- group.questions.push({- decisionId: row.decisionId,- description: row.description,- options: row.options ?? [],- question: row.question,- });- byGoal.set(row.goalId, group);- }- return [...byGoal.values()];- };-- /**- * Advance the goal by one coordinator step.- *- * Choosing and doing are separate: `decideNextMove` is a pure function of the- * graph, the responsible task and the budget, and everything under the switch- * only carries that choice out. `onDecision` then receives both what the- * coordinator read and what it did โ the decision surface a goal trajectory- * records. It travels on that side channel rather than on `GoalTickResult`- * because the result crosses tRPC to the client and the graph payload is- * large, the same reason the context engine snapshot stays off the agent- * runtime's event array.- */- tick = async (goalId: string, options?: GoalTickOptions): Promise<GoalTickResult> => {- const result = await this.tickOnce(goalId, options);- if (REPORT_CHECK_OUTCOMES.has(result.outcome)) await this.dispatchGoalReport(goalId);- return result;- };-- /**- * The wrap-up branch. Runs after the move rather than as one: it only fires- * once the Goal-level acceptance has ended, and whatever happens to it โ a- * dispatch that throws, a run that fails or times out โ must not change the- * outcome the coordinator just reported or the Goal's status.- */- private dispatchGoalReport = async (goalId: string) => {- try {- await new GoalReportService(this.db, this.userId, this.workspaceId).dispatchIfDue(goalId);- } catch (error) {- console.error('[GoalService] wrap-up report dispatch failed:', error);- }- };-- private tickOnce = async (goalId: string, options?: GoalTickOptions): Promise<GoalTickResult> => {- const at = Date.now();- // The coordinator never sees the wrap-up report node: it runs after the- // Goal-level acceptance and does not take part in the Goal's status.- const graph = withoutGoalReport(await this.requireGraph(goalId));- // A draft is still being arranged; only `start` hands it to the coordinator.- if (graph.goal.status === 'draft')- return {- goalId,- message: `Goal is a draft; start it with lh goal start ${goalId}`,- outcome: 'no_progress',- };- if (graph.goal.config?.manager) {- // The system's own planner leads whenever the Goal has one: a main Agent is- // the fallback for problems that planner cannot express, not a replacement- // for it. With exploration configured this call only settles a turn already- // in flight; new turns start from `gateOrTakeOver` below, where the- // coordinator has run out of moves. A Goal whose only planner is the main- // Agent keeps being led by it.- const result = await new GoalManagerService(this.db, this.userId, this.workspaceId).advance(- graph,- { mayStartTurn: !graph.goal.config.exploration },- );- if (result) return result;- }- // A plan the owner sent back waits on the main Agent's rewrite, not on the- // frontier: every probe has settled and nothing else is ready to run.- if (graph.goal.config?.rolloutState?.phase === 'plan_revision')- return this.releaseReview.routeRolloutRevision(graph);-- const frontier = selectFrontier(graph);-- // Every candidate's task, not just the head's: the scheduler has to know- // which of them are in flight before it can decide what else to start.- const candidateTaskIds = frontier.eligible.flatMap(({ node }) =>- node.taskId ? [node.taskId] : [],- );- const tasksById = new Map(- (candidateTaskIds.length > 0 ? await this.taskModel.findByIds(candidateTaskIds) : []).map(- (task) => [task.id, task],- ),- );-- // Asked of every unblocked candidate, not just the head: the scheduler- // walks past a running head to start an independent task, so a head that- // needs no budget must not decide that nothing does. A goal with nothing- // startable still skips the query.- const budget = frontierNeedsBudget(frontier, tasksById)- ? toBudgetState(graph.goal, await this.evaluateBudget(graph.goal, graph))- : undefined;-- // Same shape as the budget: a database read the pure decision cannot do,- // taken only in the terminal phase of a goal that declares numeric clauses.- const metricCriteria = needsMetricCriteria(graph)- ? await this.evaluateMetricCriteria(graph)- : undefined;-- const concurrency = resolveMaxConcurrentTasks(graph.goal);- // A repeated batch judges its own gate once the wave it released has fully- // settled; while a wave is still running the ordinary frontier owns the tick.- const rolloutGate = this.collectRolloutGate(graph);- const move = decideNextMove({- budget,- concurrency,- frontier,- graph,- metricCriteria,- rolloutGate,- tasksById,- });- // The scheduler may pick past the head of the frontier, so every arm below- // acts on the node the move chose, which is not necessarily the- // highest-ranked candidate.- const acting = move.chosenNodeId- ? graph.nodes.find((node) => node.id === move.chosenNodeId)- : undefined;- const actingTask = acting?.taskId ? (tasksById.get(acting.taskId) ?? null) : undefined;-- const effects: GoalAdvanceEffect[] = [];-- const observe = (result: GoalTickResult): GoalTickResult => {- options?.onDecision?.({- at,- branch: move.branch,- budget,- candidates: move.candidates,- metricCriteria,- chosenNodeId: move.chosenNodeId,- effects,- candidateTasks: frontier.eligible.flatMap(({ node }) => {- const task = node.taskId ? tasksById.get(node.taskId) : undefined;- return task ? [toFrontierTaskState(task, node.id)] : [];- }),- concurrency,- graphState: toTraceGraphState(graph),- message: result.message,- outcome: result.outcome,- taskId: result.taskId,- });- return result;- };-- switch (move.branch) {- case 'goal_paused':- case 'goal_terminal': {- return observe({ goalId, message: move.message, outcome: move.outcome });- }-- case 'pending_decision': {- await this.transitionStatus(graph.goal, 'review', 'a decision gate is open');- effects.push({ type: 'goal_status', detail: 'review' });- return observe({- goalId,- message: move.message,- nodeId: move.focusNodeId,- outcome: move.outcome,- });- }-- // Managed Goals reconsider the same contract after a shortfall. Unmanaged- // Goals park until an observation clears the gate, keeping them out of- // the sweep while they have no action to take.- case 'measured_acceptance': {- const replanning = await new GoalManagerService(- this.db,- this.userId,- this.workspaceId,- ).reconsiderAcceptance(graph, move.message);- if (replanning) return observe(replanning);- await this.setPauseReason(goalId, 'measured_acceptance');- await this.transitionStatus(graph.goal, 'paused', move.message);- effects.push({ type: 'goal_status', detail: 'paused' });- return observe({ goalId, message: move.message, outcome: move.outcome });- }-- case 'terminal_acceptance': {- return observe(await this.settleTerminalAcceptance(graph, move, effects));- }-- case 'explore_graph': {- const spent = await this.evaluateBudget(graph.goal, graph);- if (spent.costLimitReached || spent.roundLimitReached || spent.deadlinePassed) {- await this.transitionStatus(- graph.goal,- 'paused',- 'Budget exhausted before graph exploration',- );- effects.push({ type: 'goal_status', detail: 'paused: budget' });- return observe({- goalId,- outcome: 'no_progress',- message: 'Budget exhausted before graph exploration',- });- }- return observe(- await exploreGraph({- db: this.db,- userId: this.userId,- workspaceId: this.workspaceId,- graph,- effects,- }),- );- }-- case 'plan_decomposition': {- return observe(await this.planDecomposition(graph, effects));- }-- case 'rollout_gate': {- return observe(await this.releaseReview.routeRolloutRelease(graph, effects, rolloutGate));- }-- case 'pattern_break': {- return observe(- await this.openPatternBreakGate(graph, move.message, effects, { gate: rolloutGate }),- );- }-- case 'no_frontier': {- // Say so on the row instead of leaving a goal that reads as `running`- // while it cannot run โ and, just as importantly, take it out of the- // sweep's window. A `running` goal that always reports `no_progress` is- // picked by every scan forever, and enough of them starve every other- // stalled goal out of the newest-first limit.- await this.transitionStatus(graph.goal, 'paused', NO_FRONTIER_PAUSE_REASON);- effects.push({ type: 'goal_status', detail: 'paused' });- return observe({ goalId, message: move.message, outcome: move.outcome });- }-- case 'create_task': {- return observe(await this.createResponsibleTask(graph, acting!, effects));- }-- case 'missing_task': {- await this.coordinatorGraph.updateNodeStatus(- goalId,- acting!.id,- 'waiting',- 'Responsible task is missing',- );- effects.push({ nodeId: acting!.id, type: 'node_status', detail: 'waiting' });- return observe({- goalId,- message: move.message,- nodeId: acting!.id,- outcome: move.outcome,- });- }-- default: {- // Everything from here on has a live responsible task.- const task = actingTask!;- await this.ensureTaskWorkVersion(graph.goal.id, acting!.id, task.id);-- switch (move.branch) {- case 'consume_completed': {- return observe(await this.consumeCompletedTask(graph, acting!.id, task.id, effects));- }-- case 'recover_lease': {- return observe(await this.recoverLostRun(graph, acting!.id, task, effects));- }-- case 'recover_verification': {- return observe(await this.recoverAfterVerification(graph, acting!.id, task, effects));- }-- case 'failure_decision': {- // R6: a batch member that did not pass its own check IS the same- // intervention as a blocked gate. Route it through the batch gate so- // the class rolls back to canary, instead of parking on a standalone- // task decision that never touches the recipe.- if (this.isBatchMember(graph, acting!.id)) {- return observe(- await this.openPatternBreakGate(- graph,- `${acting!.title}: ${move.message}`,- effects,- { unitId: acting!.id },- ),- );- }- const waiting =- (await this.waitForDevice(graph, acting!.id, task, effects)) ??- (await this.waitForQuotaReset(graph, acting!.id, task, effects));- if (waiting) return observe(waiting);- const held = await this.holdForMachineFailure(graph, acting!.id, task, effects);- if (held) return observe(held);- const supervision = await new GoalSupervisorService(- this.db,- this.userId,- this.workspaceId,- ).reviewFailure(graph, acting!.id, task);- if (supervision) return observe(supervision);- // A machine failure the supervisor gave up on still asks for a fix,- // not a judgment about the work.- return observe(- await this.gateOrTakeOver(graph, acting!.id, task.id, move.message, effects, {- machine: isMachineFailureClass(classifyGoalFailure(task.error).class),- }),- );- }-- case 'task_paused': {- // R6: a paused batch member (e.g. its delivery did not pass- // verification) is an intervention on the class, not on one task.- if (this.isBatchMember(graph, acting!.id)) {- return observe(- await this.openPatternBreakGate(- graph,- `${acting!.title}: ${move.message}`,- effects,- { unitId: acting!.id },- ),- );- }- return observe({- goalId,- message: move.message,- nodeId: acting!.id,- outcome: move.outcome,- taskId: task.id,- });- }-- case 'task_running': {- if (task.status === 'running') {- const recovered = await this.recoverAbandonedTask(graph, acting!.id, task, effects);- if (recovered) return observe(recovered);- }- return observe({- goalId,- message: move.message,- nodeId: acting!.id,- outcome: move.outcome,- taskId: task.id,- });- }-- case 'budget_exhausted': {- await this.transitionStatus(graph.goal, 'paused', move.message);- effects.push({ type: 'goal_status', detail: 'paused' });- return observe({- goalId,- message: move.message,- nodeId: acting!.id,- outcome: move.outcome,- taskId: task.id,- });- }-- default: {- return observe(await this.dispatchWork(graph, acting!.id, task, effects));- }- }- }- }- };-- /**- * Create the Goal-level acceptance Task, or read the verdict it already- * reached. Only runs once every other Task is terminal.- */- private settleTerminalAcceptance = async (- graph: GoalGraphSnapshot,- move: GoalMove,- effects: GoalAdvanceEffect[],- ): Promise<GoalTickResult> => {- const goalId = graph.goal.id;-- if (move.outcome === 'achieved') {- // The map must agree with the verdict: only task nodes get resolved as- // Tasks complete, so without this the seeded problem nodes would read- // "active / unanswered" forever on an achieved goal.- for (const node of graph.nodes) {- if (node.kind !== 'problem' || TERMINAL_NODE_STATUSES.has(node.status)) continue;- await this.coordinatorGraph.updateNodeStatus(goalId, node.id, 'resolved', 'Goal achieved');- effects.push({ detail: 'resolved', nodeId: node.id, type: 'node_status' });- }- // Ask for the sign-off before the goal turns terminal: nothing ticks an- // achieved goal again, so a failed write after the transition would lose- // the ask for good. Failing here leaves the goal open for the next tick,- // and the write is idempotent per acceptance.- await this.requestSignOff(graph);- await this.transitionStatus(graph.goal, 'achieved', 'Goal-level acceptance passed');- effects.push({ type: 'goal_status', detail: 'achieved' });- return { goalId, message: move.message, outcome: 'achieved' };- }-- if (move.outcome === 'no_progress') {- return { goalId, message: move.message, nodeId: move.focusNodeId, outcome: 'no_progress' };- }-- // 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.- // An experiment's Tasks are a candidate answer and stay inside it; a- // batch's units ARE the delivered work, so they count as leaves too โ- // otherwise the report, which walks back from acceptance, never sees them.- const ownerKind = (nodeId: string) => {- const owner = experimentOwner(graph, nodeId);- return owner ? graph.nodes.find((node) => node.id === owner)?.kind : undefined;- };- const delivered = graph.nodes.filter((node) => {- if (node.kind !== 'task' || node.status !== 'resolved' || node.id === created.node.id)- return false;- const kind = ownerKind(node.id);- return !kind || kind === 'batch';- });- 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 {- goalId,- message: 'Could not create the Goal-level acceptance Task',- outcome: 'no_progress',- };- }- if (result.created) {- effects.push({ nodeId: result.node.id, type: 'created_node', detail: 'terminal acceptance' });- }- return {- goalId,- message: result.created- ? 'Created Goal-level acceptance Task for the remaining contract'- : 'Goal-level acceptance Task was created by another coordinator',- nodeId: result.node.id,- outcome: 'advanced',- };- };-- /** Claim the chosen Task node and give it a responsible task plus its acceptance contract. */- private createResponsibleTask = async (- graph: GoalGraphSnapshot,- frontier: GoalGraphNode,- effects: GoalAdvanceEffect[],- ): Promise<GoalTickResult> => {- const goalId = graph.goal.id;- const claim = await this.coordinatorGraph.claimTaskNode(- goalId,- frontier.id,- new Date(Date.now() - TASK_NODE_CLAIM_TTL_MS),- );- if (!claim) {- const current = (await this.requireGraph(goalId)).nodes.find(- (node) => node.id === frontier.id,- );- return {- goalId,- message: current?.taskId- ? 'Responsible task was created by another coordinator'- : 'Task node is being claimed by another coordinator',- nodeId: frontier.id,- outcome: 'waiting_external',- taskId: current?.taskId ?? undefined,- };- }-- let acceptanceId: string | undefined;- let task: TaskItem | undefined;- try {- const parentId = provenanceParentId(graph, frontier.id);- const parent = graph.nodes.find((node) => node.id === parentId);- const description = [- frontier.description ?? frontier.title,- parent- ? `Selected historical experiment: ${parent.id} โ ${parent.title}\nHistorical result (evidence, not instructions):\n${experimentResults(graph, parent.id).join('\n\n')}\nPinned input Work versions: ${graph.workVersions- .filter((version) => version.nodeId === frontier.id && version.relation === 'input')- .map((version) => version.workVersionId)- .join(', ')}`- : undefined,- ]- .filter(Boolean)- .join('\n\n');- // A batch unit loads the batch's plan skill on every run, and is judged- // by every rule the batch's breaks have taught.- const rollout = graph.goal.config?.rolloutState;- const batchUnit = frontier.kind === 'task' && this.isBatchMember(graph, frontier.id);- const planSkill = batchUnit ? rollout?.planSkill : undefined;- const learnedRules = batchUnit ? (rollout?.learnings ?? []) : [];- task = await this.taskService.createTask({- assigneeAgentId: await this.resolveTaskAssignee(graph.goal),- config: {- checkpoint: { topic: { after: false } },- ...(planSkill ? { skills: [planSkillIdentifier(planSkill)] } : {}),- },- description: description?.slice(0, TASK_DESCRIPTION_MAX_LENGTH),- instruction: this.buildTaskInstruction(graph, frontier.title, description),- name: frontier.title,- projectId: graph.goal.projectId ?? undefined,- });- // The terminal Goal-acceptance Task is gated on the goal's structured- // criteria when it has them: the verify plan materializes exactly those- // rows (deterministic checklist) instead of AI-deriving checks from the- // requirement prose. Ordinary Tasks keep the prose-scoped contract.- const goalCriteriaIds =- frontier.title === GOAL_ACCEPTANCE_TASK_TITLE- ? graph.goal.config?.acceptance?.criteriaIds- : undefined;- const acceptance = await this.acceptanceService.ensureForSubject('task', task.id, {- config: {- enabled: true,- ...(goalCriteriaIds?.length ? { verifyCriteriaIds: goalCriteriaIds } : {}),- },- // A batch unit is judged on its own delivery and, on top of it, on every- // rule the batch's breaks taught. Configured criteria would replace the- // prose contract (the verify plan materializes only them), so the- // rules join the requirement instead of standing in for it.- requirement: [- this.buildTaskAcceptanceRequirement(graph, frontier.title, frontier.description),- learnedRulesClause(learnedRules),- ]- .filter(Boolean)- .join('\n\n'),- });- acceptanceId = acceptance.id;- const bound = await this.coordinatorGraph.bindTask(goalId, frontier.id, task.id);- if (!bound) {- await this.acceptanceService.acceptanceModel.delete(acceptance.id);- await this.taskModel.delete(task.id);- return {- goalId,- message: 'Responsible task was created by another coordinator',- nodeId: frontier.id,- outcome: 'waiting_external',- };- }- } catch (error) {- if (acceptanceId) {- await this.acceptanceService.acceptanceModel.delete(acceptanceId).catch(() => {});- }- if (task) {- await this.taskModel.delete(task.id).catch((cleanupError) => {- console.error('[GoalService.tick] failed to delete unbound task:', cleanupError);- });- }- await this.coordinatorGraph.updateNodeStatus(goalId, frontier.id, 'proposed');- throw error;- }-- effects.push({ nodeId: frontier.id, targetId: task.id, type: 'created_task' });- const work = await this.workModel.registerTask({- changeType: 'created',- taskId: task.id,- toolIdentifier: 'goal-coordinator',- toolName: 'createResponsibleTask',- });- if (work?.currentVersionId) {- await this.coordinatorGraph.attachWorkVersion(- goalId,- frontier.id,- work.currentVersionId,- 'produced',- );- }- await this.transitionStatus(graph.goal, 'running', `dispatched ${task.identifier}`);- return {- goalId,- message: `Created responsible task ${task.identifier}`,- nodeId: frontier.id,- outcome: 'advanced',- taskId: task.id,- };- };-- /**- * Automatic recovery after a Task delivery failed verification. Spends the- * Task's remaining attempt budget before it escalates to a person.- */- private recoverAfterVerification = async (- graph: GoalGraphSnapshot,- nodeId: string,- task: TaskItem,- effects: GoalAdvanceEffect[],- ): Promise<GoalTickResult> => {- const goalId = graph.goal.id;- const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));- const runs = await this.taskTopicModel.findWithHandoffByTaskIds(taskIds, 10_000);- const totalCost = runs.reduce((sum, run) => sum + Number(run.totalCost ?? 0), 0);- const recovery = await new TaskRecoveryCoordinator(- this.db,- this.userId,- this.workspaceId,- ).recover({ goal: graph.goal, spentCost: totalCost, task });-- if (recovery.outcome === 'started' || recovery.outcome === 'already-running') {- await this.coordinatorGraph.updateNodeStatus(- goalId,- nodeId,- 'active',- 'Automatically started the next Task attempt after verification feedback',- );- await this.transitionStatus(graph.goal, 'running', 'automatic recovery started a run');- // Only when this advance is the one that spawned the run. Reporting it- // for a retry another advance owns would put a run in this trajectory- // that it did not start, and attribute its cost here.- if (recovery.outcome === 'started') {- effects.push({- detail: 'verification retry',- nodeId,- operationId: recovery.operationId,- targetId: task.id,- type: 'started_run',- });- }- return {- goalId,- message: `Automatically retried task ${task.identifier}`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- }-- // The retry never reached a device. The Task keeps that reason, and the next- // advance waits for the device to come back rather than asking a person.- if (recovery.outcome === 'spawn-failed' && recovery.deviceUnavailable) {- return {- goalId: graph.goal.id,- message: `Task ${task.identifier} is waiting for its device to reconnect`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- }-- // The goal was paused or ended (a close fenced it) while this advance was- // deciding: start nothing and do not reopen it.- if (recovery.outcome === 'goal-stopped') {- return {- goalId: graph.goal.id,- message: 'Goal stopped while recovery was being decided',- nodeId,- outcome: 'no_progress',- taskId: task.id,- };- }-- // Nothing failed: somebody settled the Task while this advance was deciding.- // Opening a gate would ask them to judge their own decision.- if (recovery.outcome === 'settled') {- return {- goalId: graph.goal.id,- message: `Task ${task.identifier} was settled while recovery was being decided`,- nodeId,- outcome: 'no_progress',- taskId: task.id,- };- }- const exhaustedReason =- recovery.outcome === 'exhausted-cost'- ? 'Goal cost budget was exhausted'- : recovery.outcome === 'exhausted-rounds'- ? 'Task attempt budget was exhausted'- : 'Automatic recovery could not start the next attempt';- // R6: a batch member that ran out of attempts to pass its own check breaks- // the class, like one that failed outright โ revise the recipe and re-probe,- // not a standalone retry/retire gate (retiring a last-wave member would let- // the goal head for acceptance with the unit undone). A spent goal budget- // and a run that never started are not the recipe's fault: those keep the- // ordinary gate.- if (- recovery.outcome !== 'exhausted-cost' &&- recovery.outcome !== 'spawn-failed' &&- this.isBatchMember(graph, nodeId)- ) {- const title = graph.nodes.find((node) => node.id === nodeId)?.title ?? task.identifier;- return this.openPatternBreakGate(graph, `${title}: ${exhaustedReason}`, effects, {- unitId: nodeId,- });- }- return this.gateOrTakeOver(graph, nodeId, task.id, exhaustedReason, effects, {- machine: recovery.outcome === 'spawn-failed',- });- };-- /** Claim the task for dispatch and start its run. */- private dispatchWork = async (- graph: GoalGraphSnapshot,- nodeId: string,- task: TaskItem,- effects: GoalAdvanceEffect[],- ): Promise<GoalTickResult> => {- const goalId = graph.goal.id;-- // Advances arrive from independent sources โ an event hook, a manual nudge,- // the sweep โ and can overlap. `runTask` decides whether a run is already- // in flight by reading the task's topics and only then creating one, so two- // overlapping advances would both dispatch this Task and pay for it twice.- // Claim the task first: the transition is a single conditional UPDATE, so- // exactly one advance can win it.- //- // Counting free slots is a *separate* race the per-task claim cannot cover:- // two advances reading the same `inFlight` below the cap would each claim a- // different task and both succeed, taking the goal past- // `maxConcurrentTasks`. So the count and the claim happen together, under a- // per-goal advisory lock โ the planner's cap check is a fast path, this is- // the enforcement.- const claimed = await this.db.transaction(async (tx) => {- await tx.execute(- sql`SELECT pg_advisory_xact_lock(${GOAL_DISPATCH_LOCK_NAMESPACE}, hashtext(${goalId}))`,- );-- const currentGoal = await new GoalModel(tx, this.userId, this.workspaceId).lockById(goalId);- const currentGraph = await new GoalGraphModel(tx, this.userId, this.workspaceId).getGraph(- goalId,- );- if (- !currentGoal ||- !currentGraph ||- currentGoal.status !== 'running' ||- currentGraph.decisions.some((item) => item.status === 'pending')- )- return 'stopped' as const;- const currentBudget = await new GoalService(tx, this.userId, this.workspaceId).evaluateBudget(- currentGoal,- currentGraph,- );- if (- currentBudget.costLimitReached ||- currentBudget.roundLimitReached ||- currentBudget.deadlinePassed- )- return 'stopped' as const;- const inFlight = await new GoalGraphModel(- tx,- this.userId,- this.workspaceId,- ).countRunningTasks(goalId);- if (inFlight >= resolveMaxConcurrentTasks(graph.goal)) return 'at-capacity' as const;-- return claimGoalTask(new TaskModel(tx, this.userId, this.workspaceId), task, 'running', {- error: null,- startedAt: new Date(),- });- });-- if (claimed === 'stopped')- return {- goalId,- message: 'Goal is stopped or its execution budget is exhausted',- outcome: 'no_progress',- taskId: task.id,- };-- if (claimed === 'at-capacity') {- return {- goalId,- message: `Concurrency limit reached before ${task.identifier} could start`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- }- if (!claimed) {- return {- goalId,- message: `Task ${task.identifier} is already being started`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- }-- try {- const run = await new TaskRunnerService(this.db, this.userId, this.workspaceId).runTask({- extraPrompt:- new GoalSupervisorService(this.db, this.userId, this.workspaceId).recoveryInstruction(- graph,- task.id,- ) ??- (graph.goal.config?.managerState?.submitted?.taskId === task.id- ? graph.goal.config.managerState.submitted.reason- : undefined),- maxSteps: resolveTaskMaxSteps(graph.goal),- taskId: task.id,- trigger: 'goal',- });- await new GoalSupervisorService(this.db, this.userId, this.workspaceId).recordDispatch(- graph,- task.id,- run.operationId,- );- effects.push({- nodeId,- operationId: run.operationId,- targetId: task.id,- type: 'started_run',- });- return {- goalId,- message: `Started task ${task.identifier}`,- nodeId,- outcome: 'waiting_external',- taskId: run.taskId,- };- } catch (error) {- // We claimed the task, so nothing else will put it back. Release it or the- // Task stays 'running' with no run behind it and only the lease reclaims it.- await this.taskModel- .updateStatusIfCurrent(task.id, 'running', task.status)- .catch((releaseError) => {- console.error('[GoalService.tick] failed to release claimed task:', releaseError);- });- throw error;- }- };-- private requireGraph = async (goalId: string) => {- const graph = await this.graphModel.getGraph(goalId);- if (!graph) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });- return graph;- };-- private ensureTaskWorkVersion = async (goalId: string, nodeId: string, taskId: string) => {- const graph = await this.coordinatorGraph.getGraph(goalId);- if (graph?.workVersions.some((link) => link.nodeId === nodeId)) return;- const work = await this.workModel.registerTask({- changeType: 'created',- taskId,- toolIdentifier: 'goal-coordinator',- toolName: 'createResponsibleTask',- });- if (work?.currentVersionId) {- await this.coordinatorGraph.attachWorkVersion(- goalId,- nodeId,- work.currentVersionId,- 'produced',- );- }- };-- private recoverAbandonedTask = async (- graph: GoalGraphSnapshot,- nodeId: string,- task: TaskItem,- effects: GoalAdvanceEffect[] = [],- ): Promise<GoalTickResult | undefined> => {- const [runningTopic] = await this.taskTopicModel.findRunningByTaskIds([task.id]);- const operationId = runningTopic?.operationId;- const topicId = runningTopic?.topicId;- const staleBefore = new Date(Date.now() - resolveOperationLeaseTimeout(graph.goal));-- if (!operationId || !topicId) {- // No running topic covers two very different shapes. A delivered Task- // waiting on its verification (and any repair it sends back) outlives the- // operation lease routinely; re-dispatching there pays for a duplicate- // attempt that shadows the delivered one. Hold off while the delivery is- // settling; past its grace window, fall through to the release below so- // a verify run that died silently cannot strand the goal forever.- const [lastTopic] = await this.taskTopicModel.findWithHandoff(task.id, 1);- const operationModel = new AgentOperationModel(this.db, this.userId, this.workspaceId);- if (await isDeliverySettling(operationModel, lastTopic)) {- return {- goalId: graph.goal.id,- message: `Task ${task.identifier} delivered; waiting for verification to settle`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- }-- // A task claimed for dispatch but with no run behind it. Normally this is- // the sliver between the claim and `runTask` creating the topic; if the- // worker died in there it is permanent, and every later advance would- // report `waiting_external` forever because there is no operation to- // reclaim. Once the claim is older than the lease, hand it back.- if (new Date(task.updatedAt) >= staleBefore) return undefined;- const released = await this.taskModel.updateStatusIfCurrent(task.id, 'running', 'backlog');- if (!released) return undefined;- return {- goalId: graph.goal.id,- message: `Released the abandoned dispatch claim on task ${task.identifier}`,- nodeId,- outcome: 'advanced',- taskId: task.id,- };- }-- // A run that may still be writing must not get a replacement beside it; only- // a device known to be offline is left to the offline-device recovery below.- const latestUsage = await new AgentRuntimeCoordinator().getOperationMetadata(operationId);- const owner = { userId: this.userId, workspaceId: this.workspaceId };- const latestTotalCost = latestUsage?.totalCost;- const stop = await stopStaleRun(this.db, owner, {- latestTotalCost,- operationId,- staleBefore,- topicId,- });- if (stop === 'fresh') return undefined;- if (stop === 'unconfirmed') {- const metadata = await readRunTopicMetadata(this.db, owner, topicId);- if ((await this.readRunDevicePresence({ metadata, operationId })) !== 'offline')- return undefined;- }-- const reclaimed = await this.db.transaction(async (tx) => {- const operationModel = new AgentOperationModel(tx, this.userId, this.workspaceId);- const settled = await operationModel.settleStaleRunning(- operationId,- staleBefore,- latestTotalCost,- );- // `stopStaleRun` already claimed the lease atomically when it had to stop.- if (- !settled &&- stop === 'not_running' &&- !(await isOrphanedRun(operationModel, operationId, staleBefore))- )- return false;-- await new TaskTopicModel(tx, this.userId, this.workspaceId).updateStatus(- task.id,- topicId,- 'timeout',- );- await new TaskModel(tx, this.userId, this.workspaceId).updateStatus(task.id, 'paused', {- error: LEASE_EXPIRED_ERROR,- });- return true;- });- if (!reclaimed) return undefined;-- return this.recoverLostRun(graph, nodeId, task, effects);- };-- /**- * Recover a Task whose run was lost rather than judged โ its lease expired or- * the gateway watchdog abandoned it.- *- * A run lost because its device went offline mid-run is the same failure as a- * dispatch that never reached the device, only noticed later: the laptop went- * to sleep with the run on it. It is re-marked as an offline run so it neither- * spends the attempt budget nor retries into a device that is still gone.- */- private recoverLostRun = async (- graph: GoalGraphSnapshot,- nodeId: string,- task: TaskItem,- effects: GoalAdvanceEffect[] = [],- ): Promise<GoalTickResult> => {- await this.markRunLostToOfflineDevice(task.id);- const held = await this.holdForOfflineDevice(graph, nodeId, task, effects);- if (held) return held;- return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);- };-- /**- * Re-mark the Task's latest lost run as an offline run when the device it ran- * on is offline now. Only a device the gateway can vouch for counts: without- * presence the run stays a charged attempt, exactly as before.- */- private markRunLostToOfflineDevice = async (taskId: string) => {- const [latest] = await this.taskTopicModel.findWithHandoff(taskId, 1);- if (!latest?.topicId || (latest.status !== 'timeout' && latest.status !== 'failed')) return;- if ((await this.readRunDevicePresence(latest)) !== 'offline') return;- await this.taskTopicModel.updateStatus(taskId, latest.topicId, DEVICE_OFFLINE_RUN_STATUS);- };-- private resumeAbandonedTaskRecovery = async (- graph: GoalGraphSnapshot,- nodeId: string,- task: TaskItem,- effects: GoalAdvanceEffect[] = [],- ): Promise<GoalTickResult> => {- const recovery = await new TaskRecoveryCoordinator(- this.db,- this.userId,- this.workspaceId,- ).recover({ goal: graph.goal, task });- if (recovery.outcome === 'started' || recovery.outcome === 'already-running') {- await this.coordinatorGraph.updateNodeStatus(- graph.goal.id,- nodeId,- 'active',- 'Recovered an abandoned Task operation and started the next attempt',- );- await this.transitionStatus(graph.goal, 'running', 'reclaimed an abandoned Task');- if (recovery.outcome === 'started') {- effects.push({- detail: 'abandoned operation retry',- nodeId,- operationId: recovery.operationId,- targetId: task.id,- type: 'started_run',- });- }- return {- goalId: graph.goal.id,- message: `Recovered abandoned task ${task.identifier}`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- }-- // The retry never reached a device. The Task keeps that reason, and the next- // advance waits for the device to come back rather than asking a person.- if (recovery.outcome === 'spawn-failed' && recovery.deviceUnavailable) {- return {- goalId: graph.goal.id,- message: `Task ${task.identifier} is waiting for its device to reconnect`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- }-- // The goal was paused or ended (a close fenced it) while this advance was- // deciding: start nothing and do not reopen it.- if (recovery.outcome === 'goal-stopped') {- return {- goalId: graph.goal.id,- message: 'Goal stopped while recovery was being decided',- nodeId,- outcome: 'no_progress',- taskId: task.id,- };- }-- // Nothing failed: somebody settled the Task while this advance was deciding.- // Opening a gate would ask them to judge their own decision.- if (recovery.outcome === 'settled') {- return {- goalId: graph.goal.id,- message: `Task ${task.identifier} was settled while recovery was being decided`,- nodeId,- outcome: 'no_progress',- taskId: task.id,- };- }- const reason =- recovery.outcome === 'exhausted-cost'- ? 'Goal cost budget was exhausted after an operation was abandoned'- : recovery.outcome === 'exhausted-rounds'- ? 'Task attempt budget was exhausted after an operation was abandoned'- : 'Automatic recovery could not restart an abandoned operation';- return this.gateOrTakeOver(graph, nodeId, task.id, reason, effects, {- machine: recovery.outcome === 'spawn-failed',- });- };-- /** The machine-recovery plan for a paused Task, over its runs since a person last answered its gate. */- private planMachineRecoveryFor = async (- graph: GoalGraphSnapshot,- nodeId: string,- task: TaskItem,- now = new Date(),- ) => {- // A person's Retry restarts the schedule they overrode.- const answeredAt = lastAnsweredGateAt(graph, nodeId);- const runs = (await this.taskTopicModel.findByTaskId(task.id)).filter(- (run) => !answeredAt || new Date(run.updatedAt) > answeredAt,- );- return planMachineRecovery({ error: task.error, now, runs, taskUpdatedAt: task.updatedAt });- };-- /**- * Recover a Task stopped by a machine problem without asking anyone to judge it- * (see `planMachineRecovery`): a usage limit is waited out until it resets, a- * transport fault is retried a few times, and neither run spends the attempt- * budget. A broken setup โ or a schedule that ran out โ opens a machine gate- * that says what to fix. Judgment failures return nothing and keep the- * supervisor and the ordinary gate.- */- private holdForMachineFailure = async (- graph: GoalGraphSnapshot,- nodeId: string,- task: TaskItem,- effects: GoalAdvanceEffect[],- ): Promise<GoalTickResult | undefined> => {- if (task.status !== 'paused' || !task.error) return;- // A supervised goal already has an owner for transport faults: the supervisor- // diagnoses and retries them (see `recoveryEligibility`), so the deterministic- // schedule stays out of its way rather than racing it for the same Task.- const supervised = !!graph.goal.config?.supervision?.enabled || !!graph.goal.config?.manager;- if (supervised && classifyGoalFailure(task.error).class === 'transient') return;- const now = new Date();- const plan = await this.planMachineRecoveryFor(graph, nodeId, task, now);- if (plan.action === 'none') return;- // A pause somebody made is theirs; the error text it kept proves nothing.- if (statusAuthoredByActor(await this.taskModel.getActivities(task.id, 20), task.status)) return;-- if (plan.action === 'gate')- return this.gateOrTakeOver(graph, nodeId, task.id, plan.reason, effects, { machine: true });- if (plan.action === 'retry')- return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);-- // The sweep re-ticks a held goal, but only on its own cadence; the tick that- // first sees the failure also books an advance for the retry time. Later- // sweep ticks do not, so a long hold does not pile up queued advances.- if (now.getTime() - plan.failedAt.getTime() <= MACHINE_HOLD_SCHEDULE_WINDOW_MS) {- await scheduleGoalAdvance({- delay: Math.max(- 1,- Math.min(MAX_ADVANCE_DELAY_S, Math.ceil((plan.retryAt.getTime() - now.getTime()) / 1000)),- ),- goalId: graph.goal.id,- trigger: 'wake',- userId: this.userId,- workspaceId: this.workspaceId,- });- }- return {- goalId: graph.goal.id,- message: `Task ${task.identifier}: ${plan.message}`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- };-- /**- * Hold a Task whose run could not reach its device until a device is back.- *- * A sleeping laptop or a restarting desktop app is the usual cause, and it- * fixes itself: the gate it used to open waited hours for someone to press- * Retry once the device had long reconnected. While the device is offline the- * goal waits โ the sweep keeps asking โ and spends nothing; the retry then- * goes through the ordinary recovery path.- */- private waitForDevice = async (- graph: GoalGraphSnapshot,- nodeId: string,- task: TaskItem,- effects: GoalAdvanceEffect[],- ): Promise<GoalTickResult | undefined> => {- if (task.status !== 'paused' || !isDeviceUnavailableFailure(task.error)) return;- const held = await this.holdForOfflineDevice(graph, nodeId, task, effects);- if (held) return held;- return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);- };-- /**- * Hold a Task whose run a usage window refused until that window reopens.- *- * An external Agent past its session limit refuses every run until the reset- * its error reports. The supervisor used to read that as "spending requires- * user action" and open a gate, which then waited on a person to press Retry- * long after the window had reset. The coordinator now waits out the reset- * itself and retries through the ordinary recovery path, which charges the- * attempt as before. That bounds a window that keeps refusing.- */- private waitForQuotaReset = async (- graph: GoalGraphSnapshot,- nodeId: string,- task: TaskItem,- effects: GoalAdvanceEffect[],- ): Promise<GoalTickResult | undefined> => {- if (task.status !== 'paused') return;- const [latest] = await this.taskTopicModel.findWithHandoff(task.id, 1);- if (!latest?.operationId) return;- const operation = await new AgentOperationModel(- this.db,- this.userId,- this.workspaceId,- ).findById(latest.operationId);- const failure = classifyRunFailure(operation?.error, task.error ?? '');- if (failure.kind !== 'quota_reset') return;- // A refusal whose text names the limit is recorded as an uncharged run- // (`resolveFailedRunStatus`), so the attempt budget no longer bounds a window- // that keeps refusing; the uncharged quota schedule does. Once it is spent,- // fall through and `holdForMachineFailure` asks a person to fix the account.- if (- classifyGoalFailure(task.error).class === 'quota' &&- (await this.planMachineRecoveryFor(graph, nodeId, task)).action === 'gate'- )- return;- const retryAt = failure.resetsAt! + QUOTA_RESET_MARGIN_MS;- if (retryAt <= Date.now()) {- // The retry is a paid run, and recovery only checks the Task's own attempts- // and cost. Past the Goal's deadline, rounds or spend it is not this path's- // to start: ordinary failure handling takes it, and that gates it.- const budget = await this.evaluateBudget(graph.goal, graph);- if (budget.costLimitReached || budget.roundLimitReached || budget.deadlinePassed) return;- return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);- }- // The sweep would get here too, but only on its own cadence; the reset is a- // known time, so ask for that tick directly. One wake per Goal: the claim- // fails while an earlier-or-equal wake is still pending. A reset further out- // than the queue's longest delay is re-armed when the capped wake fires.- const target = new Date(retryAt).toISOString();- const armed = GoalWaitService.arm(target);- // Claim on the reset itself, not on `armedUntil`: that rounds the delay up to- // whole seconds from each tick's own clock, so two ticks before the same reset- // would read as different wakes. Only a capped wake stores its earlier fire time.- const capped = Date.parse(armed.armedUntil) < retryAt;- if (- await new GoalModel(this.db, this.userId, this.workspaceId).armQuotaRetryWake(- graph.goal.id,- capped ? armed.armedUntil : target,- )- )- await new GoalWaitService(this.db, this.userId, this.workspaceId).schedule(- graph.goal.id,- armed.delay,- );- return {- goalId: graph.goal.id,- message: `Task ${task.identifier} is waiting for its usage window to reset at ${new Date(retryAt).toISOString()}`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- };-- /**- * The offline retry schedule. Offline runs are not charged to the attempt- * budget, so this is what bounds them: each consecutive one pushes the next- * retry further out (see `nextDeviceOfflineRetryAt`), and once the offline- * retries are spent a person is asked. Presence only brings a retry forward โ- * a device seen back online is retried at once โ so a deployment without a- * device gateway, or a run with no recorded device, still retries on schedule.- *- * Returns nothing when the Task should retry now.- */- private holdForOfflineDevice = async (- graph: GoalGraphSnapshot,- nodeId: string,- task: TaskItem,- effects: GoalAdvanceEffect[],- ): Promise<GoalTickResult | undefined> => {- const runs = await this.taskTopicModel.findByTaskId(task.id);- const offlineRuns = countConsecutiveDeviceOfflineRuns(runs);- // A dispatch failure is an offline run even when it left no run behind.- if (!offlineRuns && !isDeviceUnavailableFailure(task.error)) return;-- const lastFailureAt = new Date(offlineRuns ? runs[0].updatedAt : task.updatedAt);- const retryAt = nextDeviceOfflineRetryAt(offlineRuns, lastFailureAt);- if (!retryAt)- return this.gateOrTakeOver(graph, nodeId, task.id, DEVICE_OFFLINE_GATE_REASON, effects, {- machine: true,- });- if (retryAt.getTime() <= Date.now()) return;-- const [latest] = await this.taskTopicModel.findWithHandoff(task.id, 1);- if (latest && (await this.readRunDevicePresence(latest)) === 'online') return;-- return {- goalId: graph.goal.id,- message: `Task ${task.identifier} is waiting for its device to reconnect; next retry at ${retryAt.toISOString()}`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- };-- /**- * Whether the device a run was routed to is connected right now.- *- * Presence is read for the exact device the run used, in the pool it was- * routed through: a workspace goal may run on a personal device, and another- * device coming online proves nothing about this one. A failed dispatch- * records its route on the operation error; a run that got going leaves its- * device on the topic. A topic bound to a device without a recorded pool is- * looked up in every pool this goal can route through.- */- private readRunDevicePresence = async (run: {- metadata?: ChatTopicMetadata | null;- operationId?: string | null;- }): Promise<'offline' | 'online' | 'unknown'> => {- if (!deviceGateway.isConfigured) return 'unknown';-- const operation = run.operationId- ? await new AgentOperationModel(this.db, this.userId, this.workspaceId).findById(- run.operationId,- )- : undefined;- const dispatchRoute = readDeviceDispatchRoute(operation?.error);- const running = run.metadata?.runningOperation;- const runningDevice =- running?.deviceId && running.operationId === run.operationId ? running : undefined;-- let deviceId: string | undefined;- let pools: { userId: string; workspaceId?: string }[];- if (dispatchRoute) {- deviceId = dispatchRoute.deviceId;- pools = [{ userId: dispatchRoute.userId, workspaceId: dispatchRoute.workspaceId }];- } else if (runningDevice) {- deviceId = runningDevice.deviceId;- pools = [- {- userId: runningDevice.deviceUserId ?? this.userId,- workspaceId: runningDevice.deviceWorkspaceId,- },- ];- } else {- deviceId = run.metadata?.boundDeviceId;- pools = [- { userId: this.userId },- ...(this.workspaceId ? [{ userId: this.userId, workspaceId: this.workspaceId }] : []),- ];- }- if (!deviceId) return 'unknown';-- for (const pool of pools) {- const devices = await deviceGateway.queryDeviceList(pool.userId, pool.workspaceId);- if (devices.some((device) => device.deviceId === deviceId)) return 'online';- }- return 'offline';- };-- private buildTaskInstruction = (- graph: GoalGraphSnapshot,- title: string,- description: string | null,- ) =>- [- `Overall goal context (background only): ${graph.goal.title}`,- graph.goal.requirement- ? `Overall goal acceptance context (background only): ${graph.goal.requirement}`- : undefined,- `Current Task contract (authoritative execution scope): ${title}`,- description,- 'Execute only the Current Task contract. Do not implement, validate, or pre-empt any sibling or downstream Task node, even when the overall goal context describes it.',- 'The complete requirements for this Task are included here. Do not inspect unrelated agent documents to recover requirements. This Task carries its own Acceptance: run it inside this Task โ drive the real product surface, capture the evidence, and submit it against your own criteria while you work. Submit evidence only; an independent verifier judges whether this Task is complete.',- 'For a Task that owns implementation, missing or broken capabilities within its scope are work to implement or repair, not a reason to stop at a capability report or ask the user for a finished implementation. Establish the runnable environment needed to exercise your changes, within the authorized scope. After failed verification, use the feedback to change the implementation or resolve the prerequisite before repeating the same checks; report a blocker only when progress requires unavailable external access, a user decision, or work outside this Task.',- 'For an investigation-only Task, deliver supported findings, gaps, and actionable next steps; do not silently expand into implementation. For a verification-only Task, report missing behavior honestly and identify the prerequisite or implementation work needed. Never claim a working product from a report or weaken the Current Task pass conditions to make it pass.',- 'Create implementation-level subtasks when useful. Finish the operation once the Current Task deliverable and its concrete evidence are ready; Acceptance verification will decide whether this Task is complete.',- 'Make the final delivery self-contained for an independent verifier that may not have workspace access. Include the relevant artifact contents or exact excerpts and the raw outputs of decisive verification commands; file paths and claims that checks passed are not sufficient evidence by themselves.',- // A path on the machine that happened to run the task is not a- // deliverable: the goal page cannot open it, the reviewer cannot read it,- // and /tmp does not survive the week. Only artifacts that reach the- // product are harvested onto the Goal Graph (see attachTaskDeliverables).- 'Persist every deliverable inside the product, not only on the local disk. Write reports and analyses as agent documents, and produce generated files (pptx / xlsx / docx / pdf, โฆ) in the operation workspace so they are uploaded and registered. A local path such as /tmp or a repository directory is a working location, not a delivery โ anything left only there is unreviewable and is not attached to the Goal.',- 'Return the produced artifacts, evidence, key findings, and the recommended next action. Do not mark the overall Goal complete.',- ]- .filter(Boolean)- .join('\n\n');-- /**- * Turn a goal with no tasks into an explorable structure: the LLM plans the- * core question plus 1โ5 independent directions, each carrying only its own- * deliverable requirements. A planning failure degrades to one task seeded- * from the raw requirement โ the goal must never stall on its planner.- */- private planDecomposition = async (graph: GoalGraphSnapshot, effects: GoalAdvanceEffect[]) => {- const goalId = graph.goal.id;- const problem = graph.nodes.find((node) => node.kind === 'problem');- const requirement = graph.goal.requirement ?? problem?.description ?? graph.goal.title;-- const claim = await this.goalModel.claimPlanning(goalId);- if (!claim)- return {- goalId,- message: 'Another advance is already planning this goal or tasks already exist',- outcome: 'waiting_external' as const,- };- try {- if (claim.previousStatus === 'planning') {- await this.coordinatorGraph- .recordGoalStatus(goalId, 'planning', 'running', 'decomposition claimed')- .catch((error) => console.error('[GoalService] failed to record goal status:', error));- }-- const generator = new GoalCriteriaGeneratorService(this.db, this.userId, this.workspaceId);- const clarifications = collectClarificationAnswers(graph);- // A failed plan still starts the goal from the raw requirement, but says- // so: the server log and the first task's audit event carry the cause.- let plannerFailure: string | undefined;- const plan = await generator- .decompose({ clarifications, requirement })- .catch((error: unknown) => {- plannerFailure = describePlannerFailure(error);- console.error(- `[GoalService] goal ${goalId} decomposition failed; starting from the raw requirement:`,- error,- );- return undefined;- });- // A graph without a problem node has nowhere to hang a question, so its- // questions are planned around as assumptions like a re-plan's would be.- const understanding = plan- ? normalizeUnderstanding(- plan,- hasAskedClarification(graph) || !problem,- clarifications.map((item) => item.question),- )- : undefined;-- // The system planner does one simple pass. When that pass failed, said it- // was not enough, or claimed a batch it could not lay out, the main Agent- // โ which can inspect the workspace โ plans the goal instead. Without one- // (no goal agent, or no turn could start) the pass below still runs.- const handoff = planningHandoffReason(- plan,- plannerFailure,- graph.goal.config?.rollout,- MAX_ROLLOUT_ROSTER,- );- if (handoff && graph.goal.agentId) {- const handed = await this.handPlanningToMainAgent(graph, handoff);- if (handed) {- effects.push({- detail: `planning handed to the main Agent: ${handoff}`,- type: 'goal_status',- });- return handed;- }- }-- const draftTasks: GoalDecompositionDraft['tasks'] = plan?.tasks ?? [- {- // The user's answers are authoritative; a planner failure after the- // clarification round must not start the work without them.- instruction: [- // After a clarification round, scope the work by the original request- // plus the answers โ never by a summary a planner wrote earlier.- clarifications.length > 0 ? requirement : (problem?.description ?? requirement),- clarifications.length > 0- ? `Answered clarifications (authoritative):\n${clarifications- .map((item) => `- Q: ${item.question}\n A: ${item.answer}`)- .join('\n')}`- : undefined,- ]- .filter(Boolean)- .join('\n\n'),- title: graph.goal.title,- },- ];-- const askedDecisions: { id: string; question: string }[] = [];- // Only the current lease owner may commit. The model call above does not- // hold a database lock; all graph changes below share one short transaction.- const committed = await this.db.transaction(async (tx) => {- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);- const current = await goalModel.findByIdForUpdate(goalId);- const checkpoint = current?.config?.planningCheckpoint;- if (- !current ||- current.status !== 'running' ||- checkpoint?.token !== claim.token ||- Date.parse(checkpoint.expiresAt) <= Date.now()- )- return undefined;- const writer = new GoalGraphModel(tx, this.userId, this.workspaceId, {- id: GOAL_COORDINATOR_ACTOR_ID,- type: 'system',- });- const fresh = await writer.getGraph(goalId);- if (!fresh || fresh.nodes.some((node) => node.kind === 'task')) return undefined;- const currentProblem = fresh.nodes.find((node) => node.kind === 'problem');- if (- fresh.goal.requirement !== graph.goal.requirement ||- fresh.goal.title !== graph.goal.title ||- currentProblem?.description !== problem?.description- )- return undefined;- const committedEffects: GoalAdvanceEffect[] = [];-- const asking = Boolean(understanding?.ask.length && currentProblem);- if (plan && currentProblem) {- // The node's description becomes the planner's own words for the core- // question โ not the acceptance boilerplate the goal row keeps. A plan- // that stops to ask commits no tasks, so it keeps the user's own words:- // the re-plan, or its fallback, must still read the original request.- await writer.updateNodeDescription(- goalId,- currentProblem.id,- asking ? (currentProblem.description ?? plan.problemStatement) : plan.problemStatement,- understanding && UNDERSTANDING_CONFIDENCE[understanding.level],- );- }- if (understanding) {- await goalModel.updateUnderstanding(goalId, {- assumptions: understanding.assumptions,- level: understanding.level,- updatedAt: new Date().toISOString(),- });- }-- // A question only the user can answer is asked before anything runs:- // Tasks planned on a wrong reading of the goal are the most expensive- // way to find out. No Task is created, so the next plan โ made with the- // answers โ starts from the same empty graph.- if (asking && understanding && currentProblem) {- for (const question of understanding.ask) {- const node = await writer.createNode(goalId, {- description: question.impact,- kind: 'decision',- status: 'waiting',- title: GOAL_CLARIFICATION_TITLE,- });- if (!node) throw new Error('Failed to open a clarification decision');- await writer.createEdge(goalId, currentProblem.id, node.id, 'leads_to');- const decision = await writer.createDecision(goalId, node.id, {- authority: 'user',- options: clarificationOptions(question),- question: question.question,- requestedUserId: this.userId,- });- if (decision) askedDecisions.push({ id: decision.id, question: question.question });- committedEffects.push({- detail: question.question,- nodeId: currentProblem.id,- targetId: node.id,- type: 'opened_decision',- });- }- return committedEffects;- }-- // Batch roll-out: when the planner judges this goal to be one repeated- // mould โ and `spec.ts` agrees โ decompose it as a class rather than as- // N flat siblings. The graph gets one `batch` container, one Template,- // one Assay and only the K fully-briefed probe tasks; the roster waits in- // `rolloutState` and the coordinator releases it one wave at a time.- const rolloutClaim = plan?.rollout ?? null;- const existingRollout = current.config?.rollout;- const rolloutTrigger = existingRollout?.trigger ?? 'canary';- const rolloutEnabled = rolloutTrigger !== 'off';- const verdict =- rolloutClaim && rolloutEnabled- ? evaluateHomogeneity(- rolloutClaim,- draftTasks.map((draft) => ({ instruction: draft.instruction, title: draft.title })),- {- maxUnits: MAX_ROLLOUT_ROSTER,- minUnits: existingRollout?.minHomogeneousUnits,- },- )- : { batch: false, malformed: false, reasons: [] as string[] };-- log(- 'decomposition rollout: trigger=%s claim=%o tasks=%d verdict=%o',- rolloutTrigger,- rolloutClaim,- draftTasks.length,- verdict,- );-- if (rolloutClaim && rolloutEnabled && verdict.batch && currentProblem) {- const roster = normalizeRolloutRoster(- rolloutClaim.units,- draftTasks,- draftTasks.length,- undefined,- { matchUnitInProbeTitle: true },- );- const canarySize =- rolloutTrigger === 'full'- ? roster.length- : Math.max(- 2,- Math.min(- existingRollout?.canarySize ?? ROLLOUT_CANARY_SIZE_DEFAULT,- ROLLOUT_MAX_CANARY_SIZE,- draftTasks.length,- ),- );- const { probeDrafts, probeIds } = await materializeRolloutBatch({- canarySize,- goalId,- goalModel,- planSkillOwner: {- db: tx,- goalTitle: graph.goal.title,- userId: this.userId,- workspaceId: this.workspaceId,- },- policy: existingRollout,- problemId: currentProblem.id,- probes: draftTasks,- recipeOutline: rolloutClaim.recipeOutline,- repeatable: rolloutClaim.repeatable,- roster,- trigger: rolloutTrigger === 'full' ? 'full' : 'canary',- variants: rolloutClaim.variants,- writer,- });- for (const [index, draft] of probeDrafts.entries()) {- committedEffects.push({- nodeId: probeIds[index],- type: 'created_node',- detail: draft.title,- });- }- return committedEffects;- }-- // A rollout claim we did NOT turn into a batch โ the caller forced- // `--rollout off`, or the homogeneity check refused it โ still carries- // only the 3โ5 representative probes in `tasks`, with the complete- // roster in `units`. A plain decomposition of `draftTasks` alone would- // silently drop every other unit, so materialize the whole roster as- // ordinary tasks instead: the probes keep their first-hand briefs, the- // rest run from the recipe. The batch config's roster cap does NOT apply- // here โ trimming the fallback would leave the tail of the requested- // goal undelivered. A goal with no claim at all is unchanged.- const plannedUnits = rolloutClaim- ? normalizeRolloutRoster(- rolloutClaim.units,- draftTasks,- draftTasks.length,- Number.POSITIVE_INFINITY,- { matchUnitInProbeTitle: true },- ).map((title, index) => {- const draft = draftTasks[index];- return {- dependsOn: draft?.dependsOn ?? [],- hypothesis: draft?.hypothesis,- instruction:- draft?.instruction ??- [rolloutClaim.recipeOutline, `Unit: ${title}`].filter(Boolean).join('\n\n'),- title: draft?.title ?? title,- };- })- : draftTasks;-- // Why this goal was planned unit by unit, on the first task's `created`- // event: a planner failure, or a batch claim the checks refused.- // A hand-over that did not happen (no main Agent could take the goal)- // says so too.- const unhanded = handoff ? '; no main Agent could take the goal' : '';- let fallbackReason = !plan- ? `Planner failed (${plannerFailure ?? 'no answer'})${unhanded}; started from the raw requirement`- : plan.escalate?.trim()- ? `Planner asked for the main Agent (${plan.escalate.trim()})${unhanded}; ran its own plan`- : rolloutClaim && rolloutEnabled && !verdict.batch- ? `Batch claim refused (${verdict.reasons.join('; ')}); planned unit by unit`- : undefined;-- const createdIds: string[] = [];- for (const draft of plannedUnits) {- // An experiment is a container for a candidate answer, not the- // default shell around every planned step. Only a direction the- // planner marked with a hypothesis gets one; a certain delivery step- // attaches straight to the problem, the same shape a manager-planned- // Task takes.- const hypothesis = draft.hypothesis?.trim();- const experiment =- currentProblem && hypothesis- ? await writer.createNode(goalId, {- kind: 'experiment',- title: draft.title,- description: hypothesis,- questionId: currentProblem.id,- })- : undefined;- if (currentProblem && hypothesis && !experiment)- throw new Error('Failed to create a planned experiment');- const node = await writer.createNode(goalId, {- scopeId: experiment?.id,- description: draft.instruction,- kind: 'task',- reason: fallbackReason,- title: draft.title,- });- if (!node) throw new Error('Failed to create a planned task');- if (!experiment && currentProblem)- await writer.createEdge(goalId, currentProblem.id, node.id, 'decomposes');- createdIds.push(node.id);- committedEffects.push({ nodeId: node.id, type: 'created_node', detail: draft.title });- fallbackReason = undefined;- }-- // The planner's `dependsOn` indices become `depends_on` edges, drawn- // dependent โ prerequisite the way `decideNextMove` reads a blocker. Only- // earlier indices are honoured, so a hallucinated forward or self reference- // can never form a cycle that deadlocks the frontier.- for (const [index, draft] of plannedUnits.entries()) {- const nodeId = createdIds[index];- if (!nodeId) continue;- for (const dep of new Set(draft.dependsOn ?? [])) {- const prerequisiteId = dep < index ? createdIds[dep] : undefined;- if (!prerequisiteId) continue;- await writer.createEdge(goalId, nodeId, prerequisiteId, 'depends_on');- }- }- return committedEffects;- });- if (!committed) {- return {- goalId,- message: 'Planning lease or input changed; re-read the graph',- outcome: 'advanced' as const,- };- }- effects.push(...committed);-- const asked = committed.filter((effect) => effect.type === 'opened_decision').length;- if (asked > 0) {- await this.briefs.openClarification(- graph.goal,- askedDecisions.map((decision) => decision.id),- askedDecisions.map((decision) => decision.question),- );- return {- goalId,- message: `Asked ${asked} clarification question${asked > 1 ? 's' : ''} before planning`,- outcome: 'advanced' as const,- };- }-- return {- goalId,- message: plan- ? `Planned ${draftTasks.length} exploration direction${draftTasks.length > 1 ? 's' : ''}`- : 'Planner unavailable; seeded a single task from the requirement',- outcome: 'advanced' as const,- };- } finally {- await this.goalModel.releasePlanning(goalId, claim.token);- }- };-- /**- * Give the goal's planning to its main Agent, opening one for a goal that had- * none. Returns undefined when no turn could start (no eligible agent, turn or- * budget limits); a policy opened here is then removed again โ only that one,- * by its token โ so the goal keeps the system planner and does not gain an- * uninvited planner later, while a policy a person set meanwhile stays.- */- private handPlanningToMainAgent = async (graph: GoalGraphSnapshot, reason: string) => {- const goalId = graph.goal.id;- const token = randomUUID();- await this.goalModel.openManagerPolicy(goalId, { openedForHandoff: token });- const result = await new GoalManagerService(this.db, this.userId, this.workspaceId)- .planInstead(await this.requireGraph(goalId), reason)- .catch((error: unknown) => {- console.error(`[GoalService] goal ${goalId} could not hand planning over:`, error);- return null;- });- if (result) return result;- await this.goalModel.closeHandoffManagerPolicy(goalId, token);- return undefined;- };-- /**- * Judge a repeated batch's gate, but only once the wave it released has fully- * settled. Returns undefined when there is nothing to judge: no batch, a batch- * already through its gate or parked on a pattern break, or a wave still- * running (the ordinary frontier owns that tick). The final wave is judged- * like every other โ a unit retired or broken in it must stop the batch the- * same way โ and a pass with the roster exhausted closes the batch.- */- private collectRolloutGate = (graph: GoalGraphSnapshot): RolloutGateResult | undefined => {- const policy = graph.goal.config?.rollout;- const state = graph.goal.config?.rolloutState;- if (- !policy ||- !state ||- state.phase === 'done' ||- state.phase === 'pattern_break' ||- state.phase === 'release_review' ||- state.phase === 'plan_revision'- )- return undefined;- const materializedIds = new Set([...state.probeNodeIds, ...(state.massNodeIds ?? [])]);- const materialized = graph.nodes.filter((node) => materializedIds.has(node.id));- if (materialized.some((node) => !TERMINAL_NODE_STATUSES.has(node.status))) return undefined;- return evaluateRolloutGate({ graph, policy, state });- };-- /** Whether a node is one of the current batch's released members (R6 routing). */- private isBatchMember = (graph: GoalGraphSnapshot, nodeId: string): boolean => {- const state = graph.goal.config?.rolloutState;- if (!state) return false;- return state.probeNodeIds.includes(nodeId) || (state.massNodeIds ?? []).includes(nodeId);- };-- /** Answer a held release from its review report; see {@link GoalReleaseReview.answerReleaseGate}. */- answerReleaseGate: GoalReleaseReview['answerReleaseGate'] = (...args) =>- this.releaseReview.answerReleaseGate(...args);-- /**- * Hand a blocked batch gate to a person.- *- * The batch cannot advance on its own, so this opens a decision on the Assay- * and pauses the goal with the pattern-break reason. The choice is the v3- * fork: revise the same recipe (repeat the v1 โ v2 loop) or fork a fresh- * recipe for the units that broke, inside this batch โ never a silent park.- */- private openPatternBreakGate = async (- graph: GoalGraphSnapshot,- message: string,- effects: GoalAdvanceEffect[],- /** What held the batch: the gate's own verdict, or one unit's failed check (R6). */- cause: { gate?: RolloutGateResult; unitId?: string } = {},- ): Promise<GoalTickResult> => {- const goalId = graph.goal.id;- const state = graph.goal.config?.rolloutState;- if (!state) return { goalId, message, outcome: 'waiting_human' };-- const reason = `${PATTERN_BREAK_PAUSE_REASON}: ${message}`;- // Overlapping advances can both see the batch break. Claim it under the- // goal row's lock: the first opens the gate โ materializing the Assay a- // `full` rollout never created โ and records it in the same transaction;- // the rest find the break already open and reuse its gate instead of- // opening a second assay and decision that would re-park the goal later.- const claim = await this.db.transaction(async (tx) => {- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);- const locked = await goalModel.lockById(goalId);- const current = locked?.config?.rolloutState;- if (!locked || !current) return undefined;- if (current.phase === 'pattern_break')- return { gateNodeId: current.assayNodeId, opened: false as const };- const writer = new GoalGraphModel(tx, this.userId, this.workspaceId, {- id: GOAL_COORDINATOR_ACTOR_ID,- type: 'system',- });-- // The gate hangs on the Assay. A `full` rollout never created one โ it- // skips the probe gate โ but a break still needs a `decision` node for the- // human question and, later, for the restart (a `batch` node cannot carry- // a decision), so the gate target is stable whichever trigger opened it.- let gateNodeId = current.assayNodeId;- if (!gateNodeId) {- const assay = await writer.createNode(goalId, {- description:- 'Whether this repeated batch can be delivered without further human decisions.',- kind: 'decision',- scopeId: current.batchNodeId,- status: 'proposed',- title: GOAL_BATCH_ASSAY_TITLE,- });- if (!assay) return undefined;- gateNodeId = assay.id;- }- // The ids are the stable vocabulary; the human-facing labels and their- // consequences live in the locale files and are resolved by option id on- // the client (like the retry/retire/fail gates), so no English copy is- // persisted into a gate a non-English reader has to answer.- const decision = await writer.createDecision(goalId, gateNodeId, {- authority: 'user',- options: [- {- id: GOAL_BATCH_BREAK_OPTION.revise,- label: 'Revise the recipe and re-probe',- },- {- // One batch carries one roster and one gate, so this is not a second- // batch running in parallel: it forks the recipe (no `revises`- // chain) for the units that broke, inside this same batch.- id: GOAL_BATCH_BREAK_OPTION.newClass,- label: 'Fork a fresh recipe',- },- ],- question: `${message}\n\n${GOAL_BATCH_BREAK_QUESTION_TAIL}`,- requestedUserId: this.userId,- });- await writer.updateNodeStatus(goalId, gateNodeId, 'waiting', reason);- await goalModel.updateRolloutState(- goalId,- withGateVerdict(- { ...current, assayNodeId: gateNodeId, phase: 'pattern_break' },- {- checks: cause.gate?.checks ?? [],- message,- nodeId: cause.unitId,- outcome: 'blocked',- revision: current.templateRevision,- trigger: cause.unitId ? 'unit' : 'gate',- waveIndex: current.waveIndex,- },- ),- );- // Park the goal in the same commit, from the locked row: once the gate is- // visible an answer may land at any moment, and a pause written after it- // from an older snapshot would re-park a goal the answer just resumed.- await goalModel.updatePauseReason(goalId, 'pattern_break');- if (locked.status !== 'paused' && !GOAL_ENDED_STATUSES.has(locked.status)) {- await goalModel.updateStatus(goalId, 'paused');- await writer- .recordGoalStatus(goalId, locked.status, 'paused', reason)- .catch((error) => console.error('[GoalService] failed to record goal status:', error));- }- return { decisionId: decision?.id, gateNodeId, opened: true as const };- });- if (!claim) return { goalId, message, outcome: 'waiting_human' };- // Another advance opened this break; it parks the goal.- if (!claim.opened)- return { goalId, message, nodeId: claim.gateNodeId, outcome: 'waiting_human' };- const gateNodeId = claim.gateNodeId;- effects.push({- detail: message,- nodeId: gateNodeId,- targetId: claim.decisionId ?? gateNodeId,- type: 'opened_decision',- });- // Home lists what waits on the person from its briefs, so the gate stays- // findable after it is dismissed from the approval island. It offers no- // one-click answers: revising needs a correction, written on the goal page.- if (claim.decisionId)- await this.briefs.openDecision(graph.goal, {- decisionId: claim.decisionId,- options: [],- question: `${message}\n\n${GOAL_BATCH_BREAK_QUESTION_TAIL}`,- });- effects.push({ type: 'goal_status', detail: 'paused: pattern_break' });- return { goalId, message, nodeId: gateNodeId, outcome: 'waiting_human' };- };-- /**- * R5: restart the canary loop after a person intervened on a batch gate.- *- * The person's answer is the single human judgment; the coordinator opens the- * next recipe round from it. `revise` chains a new Template onto the old one- * (`revises`); `new_class` forks a fresh Template with no chain edge, still- * inside this batch. Either way the members that broke are retired and- * re-opened as the new canary, and the rollout returns to the probe phase, so- * the class is proved again instead of rerun by hand.- *- * The correction is the *new recipe*: it is folded into the policy and written- * on the Template, so the re-opened probes and every later wave are briefed- * from the revised transformation โ not from the outline that just failed.- */- private restartRolloutLoop = async (- goalId: string,- decisionId: string,- optionId: string,- resolution: string | undefined,- ) => {- const graph = await this.requireGraph(goalId);- const policy = graph.goal.config?.rollout;- const state = graph.goal.config?.rolloutState;- if (!policy || !state)- return this.graphModel.resolveDecision(goalId, decisionId, optionId, resolution);-- const batchId = state.batchNodeId;- const roster = state.unitTitles ?? [];- const released = state.releasedCount ?? state.probeNodeIds.length;- // The correction the person wrote. A revision carries the plan forward and- // appends it as its own section, so each version reads whole and diffs- // against the last one; a fork starts again from the original outline. The- // result is the new recipe: later waves only ever read- // `policy.spec.recipeOutline`, so a note kept solely on the Template would- // never reach the tasks meant to test it.- const baseOutline = policy.spec?.recipeOutline?.trim() ?? '';- const correction = (resolution ?? '').trim();- const revision = state.templateRevision + 1;- const previousPlan = state.templateNodeId- ? graph.nodes.find((node) => node.id === state.templateNodeId)?.description?.trim()- : undefined;- // A fork starts from the batch's original outline โ kept on the batch node,- // since every revision rewrites the policy's โ not from the revised plan.- const originalOutline =- graph.nodes.find((node) => node.id === batchId)?.description?.trim() || baseOutline;- const basePlan = optionId === 'new_class' ? originalOutline : previousPlan || baseOutline;- const revisedOutline = [basePlan, correction && `### v${revision}\n${correction}`]- .filter(Boolean)- .join('\n\n');-- // The answer and the round it opens land together. Every write below โ- // resolving the question included โ commits in one transaction under the- // goal row's lock, so a failure part-way leaves the question open to answer- // again rather than consumed beside half a round; and a second answer- // racing this one finds the break already restarted.- // What a break teaches is mounted on the agent that runs the batch's units- // (a run's expertise snapshot reads the executing agent's domains, not the- // project's) โ resolved like the task assignee, so a deleted executor falls- // back to the goal agent rather than a binding that cannot be written. Read- // before the transaction, which holds the goal row.- const carrierAgentId = await this.resolveTaskAssignee(graph.goal);- const carrier: ExpertiseCarrier = carrierAgentId- ? { id: carrierAgentId, type: 'agent' }- : { type: 'user' };-- const committed = await this.db.transaction(async (tx) => {- const goalModel = new GoalModel(tx, this.userId, this.workspaceId);- const current = (await goalModel.lockById(goalId))?.config?.rolloutState;- if (current?.phase !== 'pattern_break') return undefined;- const resolved = await new GoalGraphModel(tx, this.userId, this.workspaceId).resolveDecision(- goalId,- decisionId,- optionId,- resolution,- );- if (!resolved) return undefined;- const writer = new GoalGraphModel(tx, this.userId, this.workspaceId, {- id: GOAL_COORDINATOR_ACTOR_ID,- type: 'system',- });-- // 1. A new recipe revision, or a forked new class (no `revises` chain).- const template = await writer.createNode(goalId, {- description: revisedOutline || baseOutline,- kind: 'finding',- scopeId: batchId,- title: GOAL_BATCH_TEMPLATE_TITLE,- });- if (template && optionId !== 'new_class' && state.templateNodeId) {- await writer.createEdge(goalId, template.id, state.templateNodeId, 'revises');- }-- // The plan skill takes the revision as its next version, and the break- // teaches the batch: a rule the executor reads, compiled into a criterion- // the verifier judges every later unit by. A fork starts a new class of- // units โ its correction describes them, it is not a rule for the old- // ones. Each runs in its own savepoint: a failure there costs the skill- // version or the lesson, never the round the answer opens.- const inSavepoint = <T>(label: string, run: (db: typeof tx) => Promise<T>) =>- tx.transaction(run).catch((error) => {- log('restartRolloutLoop: %s failed: %O', label, error);- return undefined;- });- let planSkill = state.planSkill;- let planVersion: number | undefined;- if (planSkill && revisedOutline) {- const skill = planSkill;- const version = await inSavepoint('plan skill revision', (db) =>- new BatchPlanSkillService(db, this.userId, this.workspaceId).revise(skill, {- goalId,- guidance: correction || undefined,- plan: revisedOutline,- revision,- }),- );- // The revision did not land (the skill was deleted, or the write- // failed): units must not load a skill that lacks it. They fall back to- // copying the revised plan, and the batch drops the stale reference.- if (version === undefined) planSkill = undefined;- else planVersion = version;- } else if (!planSkill && revisedOutline) {- // A batch from before plans were skills moves into one now, carrying- // every earlier version of its plan.- const inBatch = new Set(- graph.edges- .filter((edge) => edge.kind === 'contains' && edge.sourceNodeId === batchId)- .map((edge) => edge.targetNodeId),- );- const earlier = graph.nodes- .filter(- (node) =>- node.kind === 'finding' &&- node.title === GOAL_BATCH_TEMPLATE_TITLE &&- inBatch.has(node.id),- )- .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())- .map((node) => node.description?.trim() ?? '');- planSkill = await inSavepoint('plan skill adoption', (db) =>- new BatchPlanSkillService(db, this.userId, this.workspaceId).adopt({- batchNodeId: batchId,- goalId,- goalTitle: graph.goal.title,- versions: [...earlier, revisedOutline],- }),- );- }- // A fork starts a new class: the old class's rules must stop reaching- // runs too, not only its acceptance โ retire them in the shared domain,- // where the executor's expertise would otherwise keep injecting them.- // Not in a forgiving savepoint: the fork clears the batch's record of- // them below, so a failure here fails the fork (the question stays open- // to answer again) rather than leaving them active and forgotten.- if (optionId === 'new_class' && state.learnings?.length) {- const expertise = new ExpertiseModel(tx, this.userId, this.workspaceId);- for (const learning of state.learnings) await expertise.retireLesson(learning.lessonId);- }- const learned =- correction && optionId !== 'new_class'- ? await inSavepoint('break learning', (db) =>- new BatchPlanSkillService(db, this.userId, this.workspaceId).learn({- carrier,- domainId: state.learningDomainId,- // What the gate found: this round's latest hold, in its own words.- found:- state.gateLog?.findLast(- (entry) =>- entry.outcome === 'blocked' && entry.revision === state.templateRevision,- )?.message ?? 'the release gate held',- goalTitle: graph.goal.title,- guidance: correction,- planSkill,- revision: state.templateRevision,- }),- )- : undefined;-- // 2. Retire the members that broke or were superseded, never delete them โ- // the new round is `derived_from` them (decision #4). A member an earlier- // round already re-opened is history, not a unit to re-open again.- const memberIds = new Set([...state.probeNodeIds, ...(state.massNodeIds ?? [])]);- const reopenedIds = new Set(- graph.edges.filter((edge) => edge.kind === 'derived_from').map((edge) => edge.targetNodeId),- );- const broken: { brief?: string; id: string; title: string }[] = [];- for (const node of graph.nodes) {- if (!memberIds.has(node.id) || node.status === 'resolved' || reopenedIds.has(node.id))- continue;- broken.push({ brief: carriedUnitBrief(node), id: node.id, title: node.title });- if (!TERMINAL_NODE_STATUSES.has(node.status)) {- await writer.updateNodeStatus(- goalId,- node.id,- 'retired',- 'superseded by a new recipe revision',- );- }- }-- // 3. A fresh gate for the fresh round.- const assay = await writer.createNode(goalId, {- description:- 'Whether this repeated batch can be delivered without further human decisions.',- kind: 'decision',- scopeId: batchId,- status: 'proposed',- title: GOAL_BATCH_ASSAY_TITLE,- });- if (!assay) throw new Error('Failed to create the next batch gate');-- // The revised recipe becomes the batch's policy, so the probes below and- // every later wave (which read it off the graph) carry the correction.- await goalModel.updateRolloutPolicy(goalId, {- ...policy,- spec: {- ...policy.spec,- recipeOutline: revisedOutline || baseOutline,- repeatable: policy.spec?.repeatable ?? true,- },- });-- // 4. The new canary re-opens the units that broke, as new tasks that- // supersede the retired ones (decision #4: new task + retire, never move).- // Cap it at the canary size: a break in a large wave โ or a `full` rollout- // that released the whole class โ must not redispatch every member at once.- // The broken units beyond the canary stay owed, and the waves after the gate- // re-deliver them under the revised recipe. Only a gate that blocked with- // every member resolved has nothing to re-open; it re-probes the next slice.- const canarySize = Math.max(- 2,- Math.min(policy.canarySize ?? ROLLOUT_CANARY_SIZE_DEFAULT, ROLLOUT_MAX_CANARY_SIZE),- );- const reOpen = broken.slice(0, canarySize);- const deferred = broken.slice(canarySize).map((unit) => unit.title);- const fresh = broken.length ? [] : roster.slice(released, released + canarySize);- // Nothing broke and nothing is left to release โ the gate held on something- // else, such as an untested axis. Re-probe units this round delivered,- // under the revision, so the new canary is never empty (an empty one would- // re-open the same break at once).- const reProbe =- broken.length || fresh.length- ? []- : [...memberIds]- .map((id) => graph.nodes.find((node) => node.id === id))- .filter(- (node): node is NonNullable<typeof node> =>- !!node && node.status === 'resolved' && !reopenedIds.has(node.id),- )- .slice(0, canarySize)- .map((node) => ({ brief: carriedUnitBrief(node), id: node.id, title: node.title }));- const units = [- ...[...reOpen, ...reProbe].map((unit) => ({- brief: unit.brief,- from: unit.id,- title: unit.title,- })),- ...fresh.map((title) => ({- brief: policy.unitBriefs?.[title],- from: undefined as string | undefined,- title,- })),- ];- const probeIds: string[] = [];- const opened: { from: string | undefined; title: string }[] = [];- for (const unit of units) {- const nodeId = await createRecipeUnitTask(- writer,- goalId,- batchId,- unit.title,- { outline: revisedOutline || baseOutline, skill: planSkill },- unit.brief,- );- if (!nodeId) continue;- probeIds.push(nodeId);- opened.push(unit);- if (unit.from) {- await writer.createEdge(goalId, nodeId, unit.from, 'derived_from').catch(() => {});- }- }- for (const probeId of probeIds) {- await writer.createEdge(goalId, assay.id, probeId, 'depends_on');- }-- // 5. Back to canary, on the new revision. The roster is re-cut to what is- // still owed โ the new probes first, then the broken units not re-probed,- // then whatever was never released โ so the waves deliver only the- // remainder and units already delivered under the old recipe drop out.- const remaining = Array.from(- new Set([- ...opened.map((unit) => unit.title),- ...deferred,- ...roster.slice(released + fresh.length),- ]),- );- await goalModel.updateRolloutState(goalId, {- ...state,- assayNodeId: assay.id,- // A round's plan can be rewritten in place, so its skill version is kept, not derived.- planVersions: planVersion- ? { ...state.planVersions, [String(revision)]: planVersion }- : state.planVersions,- // The new canary is a fresh round: the old waves' members โ the broken- // ones now retired โ must not count against its gate.- massNodeIds: undefined,- phase: 'probe',- probeNodeIds: probeIds,- releasedCount: opened.length,- // A fork starts a new class of units: the old class's rules do not- // bind it, so its learnings start empty.- learningDomainId:- optionId === 'new_class' ? undefined : (learned?.domainId ?? state.learningDomainId),- learnings:- optionId === 'new_class'- ? undefined- : learned- ? [...(state.learnings ?? []), learned.learning]- : state.learnings,- planSkill,- templateNodeId: template?.id ?? state.templateNodeId,- templateRevision: state.templateRevision + 1,- unitTitles: remaining,- waveIndex: 0,- });- return { brokenIds: broken.map((unit) => unit.id), resolved };- });- if (!committed) return undefined;-- // A sibling still running when the gate was answered would keep spending โ- // and could deliver โ beside the probe that replaces it. Its node is fenced- // as retired above; stop the Task behind it. Not part of the transaction:- // stopping a run cannot be rolled back, and retrying it is harmless.- if (committed.brokenIds.length)- await this.stopFencedTasks(goalId, new Set(committed.brokenIds));- await this.setPauseReason(goalId, undefined);- return committed.resolved;- };-- private buildTaskAcceptanceRequirement = (- graph: GoalGraphSnapshot,- title: string,- description: string | null,- ) => {- if (title === GOAL_ACCEPTANCE_TASK_TITLE) {- return [- `Terminal Goal acceptance requirement (authoritative): ${graph.goal.requirement ?? graph.goal.title}`,- description ? `Required delivery: ${description}` : undefined,- 'PASS only when concrete evidence proves that every clause of the terminal Goal acceptance requirement is satisfied.',- 'An accurate gap analysis, a report that the Goal is not accepted, a suggested next action, or partial progress is NOT a passing delivery. Reject it so automatic recovery can continue or open a Gate.',- 'If any required count, field, evidence quality, or other explicit threshold is missing, the verdict MUST be failed even when the builder correctly identified and documented the gap.',- ]- .filter(Boolean)- .join('\n\n');- }-- // The full goal requirement (with its numbered acceptance list) is NOT- // injected here: it belongs to the terminal acceptance task above, and- // pasting it into every Task made each task's acceptance read as the whole- // contract. A Task is judged on its own outcome only.- return [- `Verify only this Task: ${title}.`,- description ? `Required Task outcome: ${description}` : undefined,- `This Task is one direction of the Goal "${graph.goal.title}"; the full Goal contract is verified separately at the end.`,- 'Pass only when the current Task deliverable is complete and supported by concrete evidence. Ignore sibling and downstream Task deliverables; they are verified by their own acceptance runs.',- ]- .filter(Boolean)- .join('\n\n');- };-- /**- * Link what a task actually delivered to the node that ordered it.- *- * The task Work attached alongside is the execution container; these are its- * outputs โ the documents and external resources the run registered. Without- * them the graph records that a task finished but not what it produced, and- * the deliverable survives only as a URL buried in the finding's prose.- *- * Harvested across every run of the task, not just the delivering one: a task- * that wrote its document in an earlier round and only revised it in the last- * still delivered that document. Works are deduplicated by identity and- * 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- * file), but a goal's deliverables are exactly where a produced deck or PDF- * belongs, so they are requested explicitly here.- */- private attachTaskDeliverables = async (- goalId: string,- nodeId: string,- operationIds: string[],- effects: GoalAdvanceEffect[],- ) => {- if (operationIds.length === 0) return;-- // The per-operation cap is applied to version EVENTS before this dedupes by- // Work identity, so the default of 20 lets a document revised twenty times- // push every other deliverable out of its own task's list.- const byOperation = await this.workModel.listByRootOperations({- includeFileWorks: true,- limit: DELIVERABLE_EVENTS_PER_RUN,- rootOperationIds: operationIds,- });-- 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 = 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 [workId, { created, item }] of harvestByWork) {- if (!created || claimedWorkIds.has(workId)) continue;- const link = await this.coordinatorGraph.attachWorkVersion(- goalId,- nodeId,- item.version.id,- 'produced',- );- // `attachWorkVersion` is idempotent, so a re-settled task re-links the- // same versions silently; only a genuinely new link is worth an effect.- if (link)- effects.push({- detail: item.type,- nodeId,- targetId: item.id,- type: 'attached_work_version',- });- }- };-- private consumeCompletedTask = async (- graph: GoalGraphSnapshot,- nodeId: string,- taskId: string,- effects: GoalAdvanceEffect[] = [],- ): Promise<GoalTickResult> => {- // `graph` can predate a retirement that landed while this tick ran. A- // retired node's late output must not enter the Goal as a finding or- // deliverable (and `updateNodeStatus` refuses to revive the node).- if ((await this.coordinatorGraph.getNodeStatus(graph.goal.id, nodeId)) === 'retired') {- return {- goalId: graph.goal.id,- message: 'Node was retired; the task outcome is discarded',- nodeId,- outcome: 'no_progress',- taskId,- };- }- const existingFinding = graph.edges.some(- (edge) => edge.sourceNodeId === nodeId && edge.kind === 'produces',- );- // The newest row by seq can be a retry that was canceled when verification- // accepted an earlier delivery โ the settle path cancels the in-flight- // attempt it superseded. The finding must be synthesized from the run that- // actually delivered, so prefer the newest completed topic (with a handoff- // when one exists) over whatever happens to be last.- const recent = await this.taskTopicModel.findWithHandoff(taskId, 10);- const latest =- recent.find((topic) => topic.status === 'completed' && topic.handoff) ??- recent.find((topic) => topic.status === 'completed') ??- recent[0];- const completedWork = await this.workModel.registerTask({- changeType: 'updated',- rootOperationId: latest?.operationId,- taskId,- toolIdentifier: 'goal-coordinator',- toolName: 'synthesizeTaskOutcome',- topicId: latest?.topicId,- });- effects.push({- nodeId,- operationId: latest?.operationId ?? undefined,- targetId: taskId,- type: 'node_status',- detail: 'resolved',- });- // 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,- completedWork.currentVersionId,- 'produced',- );- }- // Every run of the task, not the ten `findWithHandoff` reads for the- // finding: an attempt budget above ten would otherwise strand a deliverable- // produced early and merely referenced later.- const allRuns = await this.taskTopicModel.findByTaskId(taskId);- await this.attachTaskDeliverables(- graph.goal.id,- nodeId,- allRuns.flatMap((topic) => (topic.operationId ? [topic.operationId] : [])),- effects,- );- if (!existingFinding) {- const handoff = latest?.handoff as TaskTopicHandoff | null;- const title =- handoff?.title ??- handoff?.summary ??- `Completed: ${graph.nodes.find((node) => node.id === nodeId)?.title}`;- // The finding is written by whoever did the work. Recorded as the owner,- // it read as something the person had said themselves.- const author = (await this.taskModel.findById(taskId))?.assigneeAgentId ?? graph.goal.agentId;- const finding = await this.coordinatorGraph.createNode(graph.goal.id, {- confidence: 1,- createdByAgentId: author ?? undefined,- description: handoff?.content ?? handoff?.summary ?? undefined,- kind: 'finding',- scopeId: experimentOwner(graph, nodeId),- status: 'resolved',- title,- });- if (finding) {- effects.push({ detail: 'finding', nodeId, targetId: finding.id, type: 'created_node' });- await this.coordinatorGraph.createEdge(graph.goal.id, nodeId, finding.id, 'produces');- }- }- await this.coordinatorGraph.updateNodeStatus(- graph.goal.id,- nodeId,- 'resolved',- 'Responsible task completed',- );- await new GoalSupervisorService(this.db, this.userId, this.workspaceId).recordProgress(- graph,- taskId,- false,- latest?.status === 'completed' ? (latest.operationId ?? undefined) : undefined,- );- return {- goalId: graph.goal.id,- message: 'Task outcome was synthesized into a finding',- nodeId,- outcome: 'advanced',- taskId,- };- };-- /**- * Every stop-on-a-person funnels through here, so this is the one place a main- * Agent can be offered the problem before the Goal parks on its owner.- *- * The coordinator only reaches this point once its own policy is out of moves:- * the failure matched no recovery branch, the attempt budget ran out, or the- * reason is one it cannot classify. That is precisely the class of problem the- * deterministic lane cannot express, so it is handed over rather than escalated.- * A main Agent that cannot help answers `escalate`, and the gate opens anyway โ- * one turn later, with a diagnosis attached.- */- private gateOrTakeOver = async (- graph: GoalGraphSnapshot,- nodeId: string,- taskId: string,- reason: string,- effects: GoalAdvanceEffect[] = [],- gate: FailureGateOptions = {},- ): Promise<GoalTickResult> => {- const takeover = await new GoalManagerService(this.db, this.userId, this.workspaceId).takeOver(- graph,- { reason, taskId },- );- if (takeover) return takeover;- // When the main Agent already looked at THIS problem, the gate carries what it- // said: the person answering should see the Agent's reasoning, not just the- // coordinator's own reason for stopping.- const answered = answeredProblem(graph.goal.config?.managerState);- const own = answered?.key === problemKey({ reason, taskId }) ? answered : undefined;- // An Agent that asked a real question gets it asked as written, with its- // own answers as the buttons; its diagnosis is what the gate stands on.- if (own?.ask)- return this.openFailureDecision(graph, nodeId, taskId, reason, effects, {- ...gate,- ask: { ...own.ask, diagnosis: own.reason },- });- const diagnosis = own ? own.reason.slice(0, 600) : undefined;- return this.openFailureDecision(- graph,- nodeId,- taskId,- diagnosis ? `${reason} โ main Agent: ${diagnosis}` : reason,- effects,- gate,- );- };-- private openFailureDecision = async (- graph: GoalGraphSnapshot,- nodeId: string,- taskId: string,- reason: string,- effects: GoalAdvanceEffect[] = [],- gate: FailureGateOptions = {},- ): Promise<GoalTickResult> => {- return this.db.transaction(async (tx) => {- const currentGoal = await new GoalModel(tx, this.userId, this.workspaceId).lockById(- graph.goal.id,- );- const service = new GoalService(tx, this.userId, this.workspaceId);- const current = await service.requireGraph(graph.goal.id);- if (- !currentGoal ||- ['paused', 'canceled', 'failed', 'achieved'].includes(currentGoal.status)- ) {- return {- goalId: graph.goal.id,- message: 'Goal was stopped while recovery was being evaluated',- outcome: 'no_progress',- taskId,- };- }- const task = await new TaskModel(tx, this.userId, this.workspaceId).findById(taskId);- if (task && ['running', 'backlog', 'completed'].includes(task.status)) {- return {- goalId: graph.goal.id,- message: 'Task state changed while recovery was being evaluated',- outcome: 'waiting_external',- taskId,- };- }- return service.openFailureDecisionLocked(current, nodeId, taskId, reason, effects, gate);- });- };-- private openFailureDecisionLocked = async (- graph: GoalGraphSnapshot,- nodeId: string,- taskId: string,- reason: string,- effects: GoalAdvanceEffect[],- gate: FailureGateOptions = {},- ): Promise<GoalTickResult> => {- const existingDecisionNode = graph.edges- .filter((edge) => edge.sourceNodeId === nodeId && edge.kind === 'leads_to')- .map((edge) => graph.nodes.find((node) => node.id === edge.targetNodeId))- .find((node) => node?.kind === 'decision' && node.status !== 'resolved');- if (!existingDecisionNode) {- const terminalAcceptance =- graph.nodes.find((candidate) => candidate.id === nodeId)?.title ===- GOAL_ACCEPTANCE_TASK_TITLE;- // The terminal acceptance gate keeps its own three-way shape: ending the- // Goal is a verdict even when a machine problem is what stopped it.- const machine = !!gate.machine && !terminalAcceptance;- const { ask } = gate;- const node = await this.coordinatorGraph.createNode(graph.goal.id, {- // What the gate stands on: the main Agent's diagnosis when it asked,- // else the coordinator's own reason for stopping.- description: ask ? `${reason}\n\n${ask.diagnosis}` : reason,- kind: 'decision',- status: 'waiting',- title: machine ? GOAL_MACHINE_GATE_TITLE : 'Choose how to recover failed task',- scopeId: experimentOwner(graph, nodeId),- });- if (node) {- effects.push({ detail: reason, nodeId, targetId: node.id, type: 'opened_decision' });- await this.coordinatorGraph.createEdge(graph.goal.id, nodeId, node.id, 'leads_to');- const decision = await this.coordinatorGraph.createDecision(- graph.goal.id,- node.id,- ask- ? {- authority: 'user',- options: ask.options,- question: ask.question,- recommendedOptionId: ask.recommendedOptionId,- requestedUserId: this.userId,- }- : {- authority: 'user',- options: machine- ? [- { id: 'retry', label: 'I fixed it โ retry' },- { id: 'retire', label: 'Retire task' },- ]- : terminalAcceptance- ? [- { id: 'retry', label: 'Retry goal acceptance' },- // Drop the acceptance Task and end the Goal without a verdict โ- // unlike `fail`, which records that the Goal was judged failed.- { id: 'retire', label: 'Abandon goal acceptance' },- { id: 'fail', label: 'Fail goal' },- ]- : [- { id: 'retry', label: 'Retry task' },- { id: 'retire', label: 'Retire task' },- ],- question: machine- ? `${reason}. Fix it, then retry or retire this task node?`- : terminalAcceptance- ? `${reason}. Retry Goal acceptance, abandon it, or fail this Goal?`- : `${reason}. Retry or retire this task node?`,- recommendedOptionId: 'retry',- requestedUserId: this.userId,- },- );- if (decision)- await this.briefs.openDecision(graph.goal, {- decisionId: decision.id,- options: decision.options,- question: decision.question,- recommendedOptionId: decision.recommendedOptionId,- });- }- }- await this.coordinatorGraph.updateNodeStatus(graph.goal.id, nodeId, 'waiting', reason);- await this.transitionStatus(graph.goal, 'review', reason);- return {- goalId: graph.goal.id,- message: 'Task failed; a human decision gate was opened',- nodeId,- outcome: 'waiting_human',- taskId,- };- };-}--interface FailureGateOptions {- /** The main Agent's own question for this gate, asked as written with its diagnosis. */- ask?: GoalManagerAsk & { diagnosis: string };- /**- * The gate is about a machine problem (broken setup, spent retry schedule), not- * the work: it opens as a machine gate that asks for a fix, not a judgment.- */- machine?: boolean;-}--/** A machine hold books its own advance only from the tick that first saw the failure. */-const MACHINE_HOLD_SCHEDULE_WINDOW_MS = 15 * 60 * 1000;-/** Queue delays are bounded; the sweep covers anything further out. */-const MAX_ADVANCE_DELAY_S = 86_400;+export * from './GoalService';diff --git a/apps/server/src/services/goal/testUtils.ts b/apps/server/src/services/goal/testUtils.tsindex 92d041215b5..ba64b2238d7 100644--- a/apps/server/src/services/goal/testUtils.ts+++ b/apps/server/src/services/goal/testUtils.ts@@ -1,8 +1,56 @@-/** Shared helpers for the goal service tests: driving a batch through its release review. */-import { expect } from 'vitest';+/** Shared helpers for the goal service tests: the database lifecycle, and driving a batch through its release review. */+import { afterEach, beforeEach, expect, vi } from 'vitest';++import {+ acceptances,+ agentOperations,+ agents,+ goalEdges,+ goalEvents,+ goalNodeDecisions,+ goalNodes,+ goals,+ metricPoints,+ metrics,+ projects,+ tasks,+ taskTopics,+ topics,+ users,+} from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';import type { GoalService } from './index';+/** Seed the test user before each test and clear everything a goal test writes after it. */+export const registerGoalServiceTestCleanup = (serverDB: LobeChatDatabase, userId: string) => {+ beforeEach(async () => {+ await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();+ });++ afterEach(async () => {+ vi.restoreAllMocks();+ // PGlite does not consistently order the nested user -> goal -> graph+ // cascades, so clear graph leaves explicitly before their owned roots.+ await serverDB.delete(goalNodeDecisions);+ await serverDB.delete(goalEdges);+ await serverDB.delete(goalEvents);+ await serverDB.delete(goalNodes);+ await serverDB.delete(goals);+ await serverDB.delete(metricPoints);+ await serverDB.delete(metrics);+ await serverDB.delete(acceptances);+ await serverDB.delete(agentOperations);+ // A project holds its coordinator agent; it goes before the agents do.+ await serverDB.delete(projects);+ await serverDB.delete(taskTopics);+ await serverDB.delete(topics);+ await serverDB.delete(tasks);+ await serverDB.delete(agents);+ await serverDB.delete(users);+ });+};+/** The release a passed batch gate is held for, still waiting on the owner. */export const pendingRelease = async (service: GoalService, goalId: string) =>(await service.graph(goalId)).decisions.find(