π€― 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
π fix(goal): prevent duplicate decomposition with planning leases (#19307)
Arvin Xu065cc132d817
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex ecb786ca507..22c1b1dc4a5 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -1,6 +1,6 @@// @vitest-environment nodeimport { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';-import { eq } from 'drizzle-orm';+import { eq, sql } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '@/database/core/getTestDB';@@ -922,6 +922,159 @@ describe('GoalService', () => {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(1);+ expect(after.nodes.find((node) => node.kind === 'problem')?.description).toBe('First plan');+ expect(after.edges.filter((edge) => edge.kind === 'answers')).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'),diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 850a427c426..be610448233 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -1886,96 +1886,118 @@ export class GoalService {const problem = graph.nodes.find((node) => node.kind === 'problem');const requirement = graph.goal.requirement ?? problem?.description ?? graph.goal.title;- // Two advances can reach this branch together β the queued kickoff and the- // client's fire-and-forget fallback both see zero Tasks. The conditional- // `planning β running` write is the claim: the loser stops before even- // calling the planner, so nothing double-plans and nothing double-pays.- // `waiting_external` ends its advance loop β the winner carries the goal.- if (graph.goal.status === 'planning') {- const claimed = await this.goalModel.claimPlanning(goalId);- if (!claimed) {- return {- goalId,- message: 'Another advance is already planning this goal',- outcome: 'waiting_external' as const,- };+ 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));}- 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 plan = await generator.decompose({ requirement }).catch(() => undefined);+ const generator = new GoalCriteriaGeneratorService(this.db, this.userId, this.workspaceId);+ const plan = await generator.decompose({ requirement }).catch(() => undefined);++ const draftTasks: GoalDecompositionDraft['tasks'] = plan?.tasks ?? [+ { instruction: problem?.description ?? requirement, title: graph.goal.title },+ ];++ // 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[] = [];++ 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.+ await writer.updateNodeDescription(goalId, currentProblem.id, plan.problemStatement);+ }- // Rare shape: a goal already past `planning` whose Tasks were all removed.- // There is no status edge to claim on that path, so shrink the duplicate- // window to the instant before the inserts with a re-read instead.- if (graph.goal.status !== 'planning') {- const fresh = await this.graphModel.getGraph(goalId);- if (fresh?.nodes.some((node) => node.kind === 'task')) {+ const createdIds: string[] = [];+ for (const draft of draftTasks) {+ const experiment = currentProblem+ ? await writer.createNode(goalId, {+ kind: 'experiment',+ title: draft.title,+ description: draft.instruction,+ questionId: currentProblem.id,+ })+ : undefined;+ if (currentProblem && !experiment)+ throw new Error('Failed to create a planned experiment');+ const node = await writer.createNode(goalId, {+ scopeId: experiment?.id,+ description: draft.instruction,+ kind: 'task',+ title: draft.title,+ });+ if (!node) throw new Error('Failed to create a planned task');+ createdIds.push(node.id);+ committedEffects.push({ nodeId: node.id, type: 'created_node', detail: draft.title });+ }++ // 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 draftTasks.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: 'Decomposition already planned by a concurrent advance',+ message: 'Planning lease or input changed; re-read the graph',outcome: 'advanced' as const,};}- }+ effects.push(...committed);- const draftTasks: GoalDecompositionDraft['tasks'] = plan?.tasks ?? [- { instruction: problem?.description ?? requirement, title: graph.goal.title },- ];-- if (plan && problem) {- // The node's description becomes the planner's own words for the core- // question β not the acceptance boilerplate the goal row keeps.- await this.coordinatorGraph.updateNodeDescription(goalId, problem.id, plan.problemStatement);- }-- const createdIds: (string | undefined)[] = [];- for (const draft of draftTasks) {- const experiment = problem- ? await this.coordinatorGraph.createNode(goalId, {- kind: 'experiment',- title: draft.title,- description: draft.instruction,- questionId: problem.id,- })- : undefined;- const node = await this.coordinatorGraph.createNode(goalId, {- scopeId: experiment?.id,- description: draft.instruction,- kind: 'task',- title: draft.title,- });- createdIds.push(node?.id);- if (!node) continue;- if (problem && !experiment)- await this.coordinatorGraph.createEdge(goalId, problem.id, node.id, 'decomposes');- effects.push({ nodeId: node.id, type: 'created_node', detail: draft.title });- }-- // 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 draftTasks.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 this.coordinatorGraph.createEdge(goalId, nodeId, prerequisiteId, 'depends_on');- }+ 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);}-- 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,- };};private buildTaskAcceptanceRequirement = (diff --git a/docs/development/goal-planning-lease-rollout.md b/docs/development/goal-planning-lease-rollout.mdnew file mode 100644index 00000000000..8e4b8e8fc6d--- /dev/null+++ b/docs/development/goal-planning-lease-rollout.md@@ -0,0 +1,46 @@+# Goal planning lease rollout and rollback++The pre-lease coordinator does not validate a lease before invoking the planner+or inserting nodes. A rolling deployment with that version is **not supported**.+The guard on legacy running goals prevents takeover of an old worker; it cannot+stop an old worker from reading a goal claimed by a new worker. Five minutes of+elapsed time is not proof that an old process has stopped.++## First deployment++1. Stop admission of Goal advance requests from every entry point (API/client+ fallback, queued kickoff, scheduled and background workers). Pause consumers+ and producers; preserve queued work for replay.+2. Drain all active Goal advance requests and planner calls on the old fleet.+ Terminate remaining old processes if they cannot drain, and confirm they+ cannot reconnect or write. Do not deploy lease-aware workers alongside+ still-running old workers.+3. Deploy the lease-aware version to **all** Goal API and worker instances.+4. Inspect legacy running goals with no task nodes and no planning checkpoint or+ protocol marker. Leave goals with tasks alone. Only after the old fleet has+ stopped, reset confirmed orphan goals to planning using an ownership-scoped+ administrative update; never reset an actively owned goal.+5. Resume admission and replay queued advances. Concurrent lease-aware advances+ are safe. Verify that each goal has one initial task graph.++## Rollback across the lease boundary++Stop admission and drain/terminate **all** lease-aware workers before starting+any pre-lease worker. Do not allow the two protocols to overlap. Reset only+confirmed orphan goals without task nodes to planning after draining. The old+binary does not enforce leases, even if the JSON metadata remains present.++Normal rollouts between versions that both implement this protocol do not need+this stop-and-drain procedure.++## Runtime safeguards++- A running goal with neither checkpoint nor protocol marker is not automatically+ reclaimed: it may belong to an old worker.+- The protocol marker survives lease release, so lease-aware failed attempts can+ retry without reopening the legacy takeover path.+- Ordinary config replacements retain the current row's runtime lease metadata.+ They cannot erase a new claim, overwrite a replacement token, or resurrect a+ released token. Claim/release are the only runtime writers.+- These safeguards do not make old binaries lease-aware. Completing the+ deployment procedure is a release prerequisite, not a claim proven by tests.diff --git a/packages/database/src/models/__tests__/goal.test.ts b/packages/database/src/models/__tests__/goal.test.tsindex 475dd2deab0..d0ca6fda0c3 100644--- a/packages/database/src/models/__tests__/goal.test.ts+++ b/packages/database/src/models/__tests__/goal.test.ts@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { agents, goalEdges, goalNodeDecisions, goalNodes, users } from '../../schemas';+import { agents, goalEdges, goalNodeDecisions, goalNodes, goals, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { GoalModel } from '../goal';import { GoalGraphModel } from '../goalGraph';@@ -355,3 +355,69 @@ describe('GoalModel', () => {});});});++describe('planning leases', () => {+ it('does not take over a running goal claimed by a legacy worker', async () => {+ const goal = await goalModel.create({ title: 'Legacy planner', status: 'running' });+ expect(await goalModel.claimPlanning(goal.id)).toBeUndefined();+ expect((await goalModel.findById(goal.id))?.config?.planningCheckpoint).toBeUndefined();+ });++ it.each([+ null,+ { acceptance: { criteriaIds: ['updated-criterion'] } },+ { acceptance: { metrics: [{ key: 'followers', target: 1000 }] } },+ { schedule: { deadline: null } },+ ])(+ 'preserves the lease across a stale config replacement (%j) without resurrecting a released token',+ async (config) => {+ const goal = await goalModel.create({ title: 'Config race', config: { pausedBy: 'user' } });+ const claim = await goalModel.claimPlanning(goal.id);+ const claimed = await goalModel.findById(goal.id);+ await goalModel.update(goal.id, { config });+ expect((await goalModel.findById(goal.id))?.config?.planningCheckpoint?.token).toBe(+ claim!.token,+ );+ expect(await goalModel.claimPlanning(goal.id)).toBeUndefined();++ await goalModel.releasePlanning(goal.id, claim!.token);+ await goalModel.update(goal.id, { config: claimed!.config });+ expect((await goalModel.findById(goal.id))?.config?.planningCheckpoint).toBeUndefined();+ // A lease-aware goal can retry; a legacy running goal cannot.+ expect(await goalModel.claimPlanning(goal.id)).toBeDefined();+ },+ );++ it('allows one owner, fences expired owners, and preserves unrelated config on release', async () => {+ const goal = await goalModel.create({ title: 'Planning lease', config: { pausedBy: 'user' } });+ const first = await goalModel.claimPlanning(goal.id);+ expect(first).toBeDefined();+ expect(await goalModel.claimPlanning(goal.id)).toBeUndefined();+ expect(await new GoalModel(serverDB, otherUserId).claimPlanning(goal.id)).toBeUndefined();+ await new GoalModel(serverDB, otherUserId).releasePlanning(goal.id, first!.token);+ expect((await goalModel.findById(goal.id))?.config?.planningCheckpoint?.token).toBe(+ first!.token,+ );+ await serverDB+ .update(goals)+ .set({+ config: {+ pausedBy: 'user',+ planningProtocol: 'lease-v1',+ planningCheckpoint: { token: first!.token, expiresAt: '2000-01-01T00:00:00.000Z' },+ },+ })+ .where(eq(goals.id, goal.id));+ const second = await goalModel.claimPlanning(goal.id);+ expect(second?.token).not.toBe(first!.token);+ await goalModel.releasePlanning(goal.id, first!.token);+ expect((await goalModel.findById(goal.id))?.config?.planningCheckpoint?.token).toBe(+ second!.token,+ );+ await goalModel.releasePlanning(goal.id, second!.token);+ expect((await goalModel.findById(goal.id))?.config).toEqual({+ pausedBy: 'user',+ planningProtocol: 'lease-v1',+ });+ });+});diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.tsindex 31fadd4176f..e1044517c62 100644--- a/packages/database/src/models/__tests__/goalGraph.test.ts+++ b/packages/database/src/models/__tests__/goalGraph.test.ts@@ -333,3 +333,42 @@ describe('GoalGraphModel', () => {});});});++// PGlite has a single connection and cannot model PostgreSQL reader/writer concurrency.+it.skipIf(process.env.TEST_SERVER_DB !== '1')(+ 'reads a graph while another transaction locks its goal',+ async () => {+ const goal = await goalModel.create({ title: 'Readable while planning' });+ let unlock!: () => void;+ let acquired!: () => void;+ const gate = new Promise<void>((resolve) => {+ unlock = resolve;+ });+ const ready = new Promise<void>((resolve) => {+ acquired = resolve;+ });+ const writer = serverDB.transaction(async (tx) => {+ await new GoalModel(tx, userId).findByIdForUpdate(goal.id);+ acquired();+ await gate;+ });+ let timeout: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([ready, writer]);+ const graph = await Promise.race([+ graphModel.getGraph(goal.id),+ new Promise<never>((_, reject) => {+ timeout = setTimeout(+ () => reject(new Error('Graph refresh waited for a write lock')),+ 2000,+ );+ }),+ ]);+ expect(graph?.goal.id).toBe(goal.id);+ } finally {+ if (timeout) clearTimeout(timeout);+ unlock();+ await writer;+ }+ },+);diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.tsindex a7297761638..c96e4286573 100644--- a/packages/database/src/models/goal.ts+++ b/packages/database/src/models/goal.ts@@ -1,3 +1,5 @@+import { randomUUID } from 'node:crypto';+import type { GoalStatus } from '@lobechat/const/goal';import type { GoalNodeStatus } from '@lobechat/types';import { and, desc, eq, inArray, sql } from 'drizzle-orm';@@ -108,29 +110,94 @@ export class GoalModel {update = async (id: string, value: Partial<Omit<GoalItem, 'id' | 'userId'>>) => {const [row] = await this.db.update(goals)- .set({ ...value, updatedAt: new Date() })+ .set({+ ...value,+ // Policy editors may carry a pre-claim or pre-release snapshot. Runtime+ // ownership always comes from the current row, never that snapshot.+ ...(value.config !== undefined+ ? {+ config: sql`(COALESCE(${JSON.stringify(value.config ?? {})}::jsonb, '{}'::jsonb) - 'planningCheckpoint' - 'planningProtocol')+ || jsonb_strip_nulls(jsonb_build_object(+ 'planningCheckpoint', ${goals.config}->'planningCheckpoint',+ 'planningProtocol', ${goals.config}->'planningProtocol'+ ))`,+ }+ : {}),+ updatedAt: new Date(),+ }).where(and(eq(goals.id, id), this.ownership())).returning();return row as GoalItem | undefined;};- /**- * Atomically take `planning β running` as the decomposition claim: several- * concurrent advances can all see an unplanned goal, and only the one this- * conditional write succeeds for may seed the graph. `startedAt` is stamped- * here because the later dispatch transition becomes a same-status no-op.- */- claimPlanning = async (id: string) => {+ /** Call inside a transaction when a coordinator needs to serialize a write. */+ findByIdForUpdate = async (id: string) => {const [row] = await this.db+ .select()+ .from(goals)+ .where(and(eq(goals.id, id), this.ownership()))+ .limit(1)+ .for('update');+ return row;+ };++ /** Claim a bounded planning lease without holding a connection during the model call. */+ claimPlanning = async (id: string) =>+ this.db.transaction(async (tx) => {+ const model = new GoalModel(tx, this.userId, this.workspaceId);+ const goal = await model.findByIdForUpdate(id);+ if (!goal || !['planning', 'running'].includes(goal.status)) return undefined;+ // A running goal without lease provenance may still have an unfenced+ // pre-lease worker in flight. Never infer abandonment from elapsed time.+ // See docs/development/goal-planning-lease-rollout.md before rollout/rollback.+ if (+ goal.status === 'running' &&+ !goal.config?.planningProtocol &&+ !goal.config?.planningCheckpoint+ )+ return undefined;+ const now = Date.now();+ if (+ goal.config?.planningCheckpoint &&+ Date.parse(goal.config.planningCheckpoint.expiresAt) > now+ )+ return undefined;+ const [task] = await tx+ .select({ id: goalNodes.id })+ .from(goalNodes)+ .where(and(eq(goalNodes.goalId, id), eq(goalNodes.kind, 'task')))+ .limit(1);+ if (task) return undefined;+ const checkpoint = {+ token: randomUUID(),+ expiresAt: new Date(now + 5 * 60_000).toISOString(),+ };+ await tx+ .update(goals)+ .set({+ config: { ...goal.config, planningCheckpoint: checkpoint, planningProtocol: 'lease-v1' },+ startedAt: goal.startedAt ?? new Date(now),+ status: 'running',+ updatedAt: new Date(now),+ })+ .where(eq(goals.id, id));+ return { ...checkpoint, previousStatus: goal.status };+ });++ /** A late worker must never clear a newer worker's lease or other configuration. */+ releasePlanning = async (id: string, token: string) => {+ await this.db.update(goals).set({- startedAt: sql`coalesce(${goals.startedAt}, now())`,- status: 'running',- updatedAt: new Date(),+ config: sql`${goals.config} - 'planningCheckpoint'`,})- .where(and(eq(goals.id, id), eq(goals.status, 'planning'), this.ownership()))- .returning();- return row as GoalItem | undefined;+ .where(+ and(+ eq(goals.id, id),+ this.ownership(),+ sql`${goals.config}->'planningCheckpoint'->>'token' = ${token}`,+ ),+ );};/**diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex b8ffc3b42d9..8db39dfe7dd 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -105,7 +105,12 @@ export class GoalGraphModel {};getGraph = async (goalId: string): Promise<GoalGraphSnapshot | undefined> => {- const goal = await this.ownedGoal(goalId);+ // Ordinary graph refreshes must not queue behind a coordinator's write lock.+ const [goal] = await this.db+ .select()+ .from(goals)+ .where(and(eq(goals.id, goalId), this.ownership()))+ .limit(1);if (!goal) return undefined;const [nodes, edges, decisions, events, linkedWorkVersions] = await Promise.all([diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex e3eebd00e82..5d3cf203ba1 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -129,6 +129,7 @@ export interface GoalExplorationConfig {export interface GoalConfig {acceptance?: GoalAcceptancePolicy;+exploration?: GoalExplorationConfig;/*** How many of a goal's Tasks may be in flight at once. Independent Tasks are@@ -139,6 +140,10 @@ export interface GoalConfig {maxConcurrentTasks?: number | null;/** Who the current pause belongs to; cleared when the goal runs again. */pausedBy?: GoalPauseReason;+ /** Coordinator-owned lease for initial decomposition; not a user policy. */+ planningCheckpoint?: { expiresAt: string; token: string };+ /** Retained after release to distinguish lease-aware retries from legacy planners. */+ planningProtocol?: 'lease-v1';recovery?: GoalRecoveryPolicy;schedule?: GoalSchedulePolicy;}