Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

36.1 KB
Raw Blame
// @vitest-environment node
import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';

import { getTestDB } from '../../core/getTestDB';
import {
  acceptances,
  agents,
  goalNodes,
  goals,
  tasks,
  topics,
  users,
  workspaces,
} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { AcceptanceModel } from '../acceptance';
import { GoalModel } from '../goal';
import { GoalGraphModel } from '../goalGraph';
import { TaskModel } from '../task';
import { WorkModel } from '../work';

const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'goal-graph-test-user';
const otherUserId = 'goal-graph-other-user';

const goalModel = new GoalModel(serverDB, userId);
const graphModel = new GoalGraphModel(serverDB, userId);

beforeEach(async () => {
  await serverDB.delete(users);
  await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
});

afterEach(async () => {
  await serverDB.delete(users);
});

describe('GoalGraphModel', () => {
  it('creates nodes and edges with an atomic event trail', async () => {
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Reproduce Ornith' });
    const problem = await graphModel.createNode(goal.id, {
      kind: 'problem',
      title: 'Can the published specification reproduce the system?',
    });
    const work = await graphModel.createNode(goal.id, {
      kind: 'task',
      title: 'Implement the minimal training loop',
    });

    const edge = await graphModel.createEdge(goal.id, problem!.id, work!.id, 'leads_to');
    const graph = await graphModel.getGraph(goal.id);

    expect(edge).toMatchObject({ goalId: goal.id, kind: 'leads_to' });
    expect(graph?.nodes).toHaveLength(2);
    expect(graph?.edges).toHaveLength(1);
    // Newest first — getGraph bounds and orders the trail for the polling UI.
    expect(graph?.events.map((event) => event.eventType)).toEqual(['linked', 'created', 'created']);
  });

  it('records who made each transition', async () => {
    // Every event used to be attributed to the goal's owner, because the model
    // falls back to its `userId` — which made a move the coordinator decided on
    // its own indistinguishable from one a person made.
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Attributed' });
    const coordinator = new GoalGraphModel(serverDB, userId, undefined, {
      id: GOAL_COORDINATOR_ACTOR_ID,
      type: 'system',
    });

    const byUser = await graphModel.createNode(goal.id, { kind: 'task', title: 'Asked for' });
    const bySystem = await coordinator.createNode(goal.id, { kind: 'finding', title: 'Concluded' });
    await serverDB.insert(agents).values({ id: 'agt_author', slug: 'agt-author', userId });
    const byAgent = await coordinator.createNode(goal.id, {
      createdByAgentId: 'agt_author',
      kind: 'finding',
      title: 'Written by an agent',
    });

    const { events } = (await graphModel.getGraph(goal.id))!;
    const actorOf = (nodeId: string) => {
      const event = events.find((item) => item.entityId === nodeId);
      return { actorId: event?.actorId, actorType: event?.actorType };
    };

    expect(actorOf(byUser!.id)).toEqual({ actorId: userId, actorType: 'user' });
    expect(actorOf(bySystem!.id)).toEqual({
      actorId: GOAL_COORDINATOR_ACTOR_ID,
      actorType: 'system',
    });
    // An explicit agent author still wins over the instance actor.
    expect(actorOf(byAgent!.id)).toEqual({ actorId: 'agt_author', actorType: 'agent' });
  });

  it('creates a synthesized node only once when coordinators race', async () => {
    const goal = await goalModel.create({
      subjectType: 'standalone',
      title: 'Concurrent synthesis',
    });
    const input = { kind: 'task' as const, title: 'Complete full Goal acceptance' };

    const results = await Promise.all([
      graphModel.createNodeOnce(goal.id, input),
      graphModel.createNodeOnce(goal.id, input),
    ]);
    const graph = await graphModel.getGraph(goal.id);

    expect(results.filter((result) => result?.created)).toHaveLength(1);
    expect(new Set(results.map((result) => result?.node.id))).toHaveLength(1);
    expect(graph?.nodes).toHaveLength(1);
    expect(graph?.events).toHaveLength(1);
  });

  it('creates and resolves a durable human decision', async () => {
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Decision goal' });
    const node = await graphModel.createNode(goal.id, {
      kind: 'decision',
      title: 'Choose verifier',
    });
    const decision = await graphModel.createDecision(goal.id, node!.id, {
      authority: 'user',
      options: [
        { id: 'harden', label: 'Harden verifier' },
        { id: 'continue', label: 'Continue training' },
      ],
      question: 'Which branch should run next?',
      recommendedOptionId: 'harden',
    });

    const resolved = await graphModel.resolveDecision(
      goal.id,
      decision!.id,
      'harden',
      'Safer first',
    );
    const graph = await graphModel.getGraph(goal.id);

    expect(resolved).toMatchObject({ resolvedOptionId: 'harden', status: 'resolved' });
    expect(graph?.nodes[0]).toMatchObject({ status: 'resolved' });
    expect(graph?.decisions[0]).toMatchObject({ resolution: 'Safer first', status: 'resolved' });
  });

  it('allows only one concurrent resolution of a pending decision', async () => {
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Decision race' });
    const node = await graphModel.createNode(goal.id, {
      kind: 'decision',
      title: 'Choose once',
    });
    const decision = await graphModel.createDecision(goal.id, node!.id, {
      authority: 'user',
      options: [
        { id: 'retry', label: 'Retry' },
        { id: 'retire', label: 'Retire' },
      ],
      question: 'Which outcome wins?',
    });

    const results = await Promise.all([
      graphModel.resolveDecision(goal.id, decision!.id, 'retry'),
      graphModel.resolveDecision(goal.id, decision!.id, 'retire'),
    ]);
    const graph = await graphModel.getGraph(goal.id);

    expect(results.filter(Boolean)).toHaveLength(1);
    expect(graph?.events.filter((event) => event.eventType === 'resolved')).toHaveLength(1);
    expect(graph?.decisions[0].resolvedOptionId).toBe(results.find(Boolean)!.resolvedOptionId);
  });

  it('allows only one task binding for a task node', async () => {
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Task binding race' });
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Run once' });
    const taskModel = new TaskModel(serverDB, userId);
    const [firstTask, secondTask] = await Promise.all([
      taskModel.create({ instruction: 'First candidate' }),
      taskModel.create({ instruction: 'Second candidate' }),
    ]);

    expect(await graphModel.claimTaskNode(goal.id, node!.id, new Date(0))).toBeDefined();
    const bindings = await Promise.all([
      graphModel.bindTask(goal.id, node!.id, firstTask.id),
      graphModel.bindTask(goal.id, node!.id, secondTask.id),
    ]);
    const graph = await graphModel.getGraph(goal.id);

    expect(bindings.filter(Boolean)).toHaveLength(1);
    expect(graph?.nodes[0].taskId).toBe(bindings.find(Boolean)!.taskId);
    expect(graph?.events.filter((event) => event.entityType === 'task')).toHaveLength(1);
  });

  it('finds the goal a task belongs to, as a node task, the carrier, or via an ancestor', async () => {
    const taskModel = new TaskModel(serverDB, userId);
    const [nodeTask, carrierTask, looseTask] = await Promise.all([
      taskModel.create({ instruction: 'Node task' }),
      taskModel.create({ instruction: 'Carrier task' }),
      taskModel.create({ instruction: 'Loose task' }),
    ]);
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Owning goal' });
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Do it' });
    await graphModel.claimTaskNode(goal.id, node!.id, new Date(0));
    await graphModel.bindTask(goal.id, node!.id, nodeTask.id);
    const carrierGoal = await goalModel.create({
      subjectId: carrierTask.id,
      subjectType: 'task',
      title: 'Carrier goal',
    });

    const child = await taskModel.create({ instruction: 'Child', parentTaskId: nodeTask.id });
    const grandchild = await taskModel.create({
      instruction: 'Grandchild',
      parentTaskId: child.id,
    });

    expect(await graphModel.findGoalByTaskId(nodeTask.id)).toEqual({
      id: goal.id,
      title: 'Owning goal',
    });
    // Subtasks a goal task spawns belong to the same goal.
    expect((await graphModel.findGoalByTaskId(grandchild.id))?.id).toBe(goal.id);
    expect((await graphModel.findGoalByTaskId(carrierTask.id))?.id).toBe(carrierGoal.id);
    // The nearest goal wins: a subtask carrying its own goal links to that one.
    const nested = await taskModel.create({ instruction: 'Nested', parentTaskId: nodeTask.id });
    const nestedGoal = await goalModel.create({
      subjectId: nested.id,
      subjectType: 'task',
      title: 'Nested goal',
    });
    expect((await graphModel.findGoalByTaskId(nested.id))?.id).toBe(nestedGoal.id);
    expect(await graphModel.findGoalByTaskId(looseTask.id)).toBeUndefined();
    expect(
      await new GoalGraphModel(serverDB, otherUserId).findGoalByTaskId(nodeTask.id),
    ).toBeUndefined();
  });

  it('finds the goal through a task chain deeper than 32 levels and stops on a cycle', async () => {
    const taskModel = new TaskModel(serverDB, userId);
    const root = await taskModel.create({ instruction: 'Root' });
    const goal = await goalModel.create({
      subjectId: root.id,
      subjectType: 'task',
      title: 'Deep goal',
    });
    let leaf = root;
    for (let i = 0; i < 40; i++) {
      leaf = await taskModel.create({ instruction: `Level ${i}`, parentTaskId: leaf.id });
    }
    expect((await graphModel.findGoalByTaskId(leaf.id))?.id).toBe(goal.id);

    // A corrupt cycle (a -> b -> a) must terminate instead of recursing forever.
    const a = await taskModel.create({ instruction: 'Cycle A' });
    const b = await taskModel.create({ instruction: 'Cycle B', parentTaskId: a.id });
    await serverDB.update(tasks).set({ parentTaskId: b.id }).where(eq(tasks.id, a.id));
    expect(await graphModel.findGoalByTaskId(b.id)).toBeUndefined();
  });

  it('refuses to bind a task to a node retired while the task was being created', async () => {
    // Retirement fences the node before it looks for bound Tasks; a Task a
    // concurrent coordinator finishes creating afterwards must not flip the
    // retired node back to `active`.
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Retire race' });
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Stray' });
    const task = await new TaskModel(serverDB, userId).create({ instruction: 'Late task' });

    expect(await graphModel.claimTaskNode(goal.id, node!.id, new Date(0))).toBeDefined();
    await graphModel.updateNodeStatus(goal.id, node!.id, 'retired');

    expect(await graphModel.bindTask(goal.id, node!.id, task.id)).toBeUndefined();
    const [after] = (await graphModel.getGraph(goal.id))!.nodes;
    expect(after.status).toBe('retired');
    expect(after.taskId).toBeNull();
  });

  it('does not let a stale status write revive a retired node', async () => {
    // A coordinator tick that loaded the node before retirement would
    // otherwise write it back to `resolved`.
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Stale write' });
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Stray' });
    await graphModel.updateNodeStatus(goal.id, node!.id, 'retired');

    expect(await graphModel.updateNodeStatus(goal.id, node!.id, 'resolved')).toBeUndefined();
    expect(await graphModel.getNodeStatus(goal.id, node!.id)).toBe('retired');
  });

  it('closes the acceptance a retired node was still waiting on', async () => {
    // A retired node's delivery is discarded; left `delivered`, its acceptance
    // kept asking the owner to sign off on work the Goal had already dropped.
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Retire sign-off' });
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Replaced' });
    const verifying = await graphModel.createNode(goal.id, { kind: 'task', title: 'Judging' });
    const taskModel = new TaskModel(serverDB, userId);
    const task = await taskModel.create({ instruction: 'Delivered work' });
    const judged = await taskModel.create({ instruction: 'Still judged' });
    await graphModel.bindTask(goal.id, node!.id, task.id);
    await graphModel.bindTask(goal.id, verifying!.id, judged.id);
    const [delivered, inFlight] = await serverDB
      .insert(acceptances)
      .values([
        { status: 'delivered', subjectId: task.id, subjectType: 'task', userId },
        { status: 'verifying', subjectId: judged.id, subjectType: 'task', userId },
      ])
      .returning();

    await graphModel.updateNodeStatus(goal.id, node!.id, 'retired', 'replaced by a new plan');
    await graphModel.updateNodeStatus(goal.id, verifying!.id, 'retired');

    const rows = await serverDB.select().from(acceptances);
    const statusOf = (id: string) => rows.find((row) => row.id === id);
    expect(statusOf(delivered.id)).toMatchObject({ status: 'closed' });
    expect(statusOf(delivered.id)?.completedAt).toBeInstanceOf(Date);
    // A round still running is left to land; only a settled wait is closed.
    expect(statusOf(inFlight.id)).toMatchObject({ status: 'verifying' });
  });

  it.each(['pending', 'planned', 'rejected'] as const)(
    'closes a %s acceptance when its node is retired before delivering',
    async (status) => {
      // Dispatch files the acceptance as `pending` before any round exists; a
      // node retired then has no round left to settle, so retirement is the
      // only chance to take it off the active list.
      const goal = await goalModel.create({ subjectType: 'standalone', title: 'Early retire' });
      const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Dropped early' });
      const task = await new TaskModel(serverDB, userId).create({ instruction: 'Not yet run' });
      await graphModel.bindTask(goal.id, node!.id, task.id);
      const [acceptance] = await serverDB
        .insert(acceptances)
        .values({ status, subjectId: task.id, subjectType: 'task', userId })
        .returning();

      await graphModel.updateNodeStatus(goal.id, node!.id, 'retired');

      const [row] = await serverDB
        .select()
        .from(acceptances)
        .where(eq(acceptances.id, acceptance.id));
      expect(row).toMatchObject({ status: 'closed' });
      expect(row.completedAt).toBeInstanceOf(Date);
    },
  );

  it('settles a task acceptance closed once its goal node is retired', async () => {
    // A round still verifying at retirement lands afterwards: the settle closes
    // it under the row lock retirement also takes, while a live step still
    // moves to `delivered` and a user's decision is never overwritten.
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Late settle' });
    const retired = await graphModel.createNode(goal.id, { kind: 'task', title: 'Dropped' });
    const live = await graphModel.createNode(goal.id, { kind: 'task', title: 'Live' });
    const taskModel = new TaskModel(serverDB, userId);
    const dropped = await taskModel.create({ instruction: 'Dropped work' });
    const running = await taskModel.create({ instruction: 'Live work' });
    const decided = await taskModel.create({ instruction: 'Accepted work' });
    await graphModel.bindTask(goal.id, retired!.id, dropped.id);
    await graphModel.bindTask(goal.id, live!.id, running.id);
    const [late, onLive, accepted] = await serverDB
      .insert(acceptances)
      .values([
        { status: 'verifying', subjectId: dropped.id, subjectType: 'task', userId },
        { status: 'verifying', subjectId: running.id, subjectType: 'task', userId },
        { status: 'accepted', subjectId: decided.id, subjectType: 'task', userId },
      ])
      .returning();
    await graphModel.updateNodeStatus(goal.id, retired!.id, 'retired');

    const acceptanceModel = new AcceptanceModel(serverDB, userId);
    expect(await acceptanceModel.settleTaskPolicyStatus(late.id, 'delivered')).toBe('closed');
    expect(await acceptanceModel.settleTaskPolicyStatus(onLive.id, 'delivered')).toBe('delivered');
    expect(await acceptanceModel.settleTaskPolicyStatus(accepted.id, 'delivered')).toBe('accepted');

    const rows = await serverDB.select().from(acceptances);
    const rowOf = (id: string) => rows.find((row) => row.id === id);
    expect(rowOf(late.id)).toMatchObject({ status: 'closed' });
    expect(rowOf(late.id)?.completedAt).toBeInstanceOf(Date);
    expect(rowOf(onLive.id)).toMatchObject({ completedAt: null, status: 'delivered' });
    expect(rowOf(accepted.id)).toMatchObject({ status: 'accepted' });
  });

  it('skips the write when the settled status already matches, and settles nothing outside its scope', async () => {
    // `verifying` is not closed by retirement, so the settle just writes the
    // status it was handed. When the row already holds it there is no update
    // and no `completedAt`; a row outside the caller's scope is not seen at all.
    const task = await new TaskModel(serverDB, userId).create({ instruction: 'Settle no-op' });
    const [waiting] = await serverDB
      .insert(acceptances)
      .values({ status: 'verifying', subjectId: task.id, subjectType: 'task', userId })
      .returning();

    const acceptanceModel = new AcceptanceModel(serverDB, userId);
    expect(await acceptanceModel.settleTaskPolicyStatus(waiting.id, 'verifying')).toBe('verifying');

    const [row] = await serverDB.select().from(acceptances).where(eq(acceptances.id, waiting.id));
    expect(row).toMatchObject({ completedAt: null, status: 'verifying' });

    // Unknown id and another user's row both resolve to undefined.
    expect(
      await acceptanceModel.settleTaskPolicyStatus(
        '00000000-0000-4000-8000-000000000000',
        'delivered',
      ),
    ).toBeUndefined();
    expect(
      await new AcceptanceModel(serverDB, otherUserId).settleTaskPolicyStatus(
        waiting.id,
        'delivered',
      ),
    ).toBeUndefined();
  });

  it('treats a same-status write as a no-op instead of churning the graph', async () => {
    // Re-activating an already-active node must not bump `updatedAt` or append
    // an event: a coordinator retry loop does this on every tick, and the
    // planning manager hashes these rows — churn made every in-flight
    // planning turn submit into a stale snapshot.
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'No churn' });
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Looped' });
    await graphModel.updateNodeStatus(goal.id, node!.id, 'active', 'first start');
    const [before] = (await graphModel.getGraph(goal.id))!.nodes;
    const eventsBefore = (await graphModel.getGraph(goal.id))!.events.length;

    await graphModel.updateNodeStatus(goal.id, node!.id, 'active', 'retry loop tick');

    const [after] = (await graphModel.getGraph(goal.id))!.nodes;
    expect(after.updatedAt.getTime()).toBe(before.updatedAt.getTime());
    expect((await graphModel.getGraph(goal.id))!.events.length).toBe(eventsBefore);
  });

  it('refuses to bind a task to a node that is not a task node', async () => {
    // This used to be a CHECK constraint. It lives in `bindTask`'s WHERE now,
    // so the rule needs a test on the write path or nothing enforces it.
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Wrong kind' });
    const finding = await graphModel.createNode(goal.id, { kind: 'finding', title: 'A finding' });
    const task = await new TaskModel(serverDB, userId).create({ instruction: 'Should not bind' });

    expect(await graphModel.bindTask(goal.id, finding!.id, task.id)).toBeUndefined();
    expect((await graphModel.getGraph(goal.id))?.nodes[0].taskId).toBeNull();
  });

  it('allows an abandoned work claim to be recovered after its lease expires', async () => {
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Recover claim' });
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Recoverable work' });

    expect(await graphModel.claimTaskNode(goal.id, node!.id, new Date(0))).toBeDefined();
    expect(await graphModel.claimTaskNode(goal.id, node!.id, new Date(0))).toBeUndefined();

    await serverDB
      .update(goalNodes)
      .set({ updatedAt: new Date('2020-01-01') })
      .where(eq(goalNodes.id, node!.id));

    expect(await graphModel.claimTaskNode(goal.id, node!.id, new Date('2021-01-01'))).toBeDefined();
  });

  it('pins an immutable Work version to an owned graph node', async () => {
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Evidence goal' });
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Produce evidence' });
    const task = await new TaskModel(serverDB, userId).create({ instruction: 'Produce evidence' });
    const work = await new WorkModel(serverDB, userId).registerTask({
      changeType: 'created',
      taskId: task.id,
      toolIdentifier: 'goal-test',
      toolName: 'createTask',
    });

    const link = await graphModel.attachWorkVersion(
      goal.id,
      node!.id,
      work!.currentVersionId!,
      'produced',
    );

    expect(link).toMatchObject({ nodeId: node!.id, relation: 'produced' });
    const links = (await graphModel.getGraph(goal.id))?.workVersions;
    expect(links).toHaveLength(1);
    // Personal mode: the Work ownership predicate the workspace case needs must
    // not hide the owner's own deliverable from their own goal.
    expect(links?.[0].work).toMatchObject({ type: 'task', workId: work!.id });
  });

  it('hydrates what a file deliverable needs to be downloaded and cited', async () => {
    // The result page's reader shows a file's format and size on its download
    // card, and matches acceptance evidence to the file by its file-store id.
    await serverDB.insert(topics).values({ id: 'goal-graph-file-topic', userId });
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'File goal' });
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Export sheet' });
    const work = await new WorkModel(serverDB, userId).registerFile({
      filePath: '/mnt/data/pricing.xlsx',
      metadata: {
        fileId: 'file-pricing',
        filePath: '/mnt/data/pricing.xlsx',
        fileSize: 4096,
        fileUrl: 'https://cdn.example.com/pricing.xlsx',
        mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      },
      title: 'pricing.xlsx',
      toolIdentifier: 'goal-test',
      toolName: 'writeFile',
      topicId: 'goal-graph-file-topic',
      userId,
    });
    await graphModel.attachWorkVersion(goal.id, node!.id, work.currentVersionId!, 'produced');

    const links = (await graphModel.getGraph(goal.id))?.workVersions;
    expect(links?.[0].work).toMatchObject({
      fileId: 'file-pricing',
      fileSize: 4096,
      fileUrl: 'https://cdn.example.com/pricing.xlsx',
      mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      type: 'file',
    });
  });

  it('hydrates a linked Work only for a viewer allowed to see it', async () => {
    // A workspace goal is readable by every member (`goals` has no visibility
    // column), but a Work is owner-scoped. Hydrating the link without the Work
    // ownership predicate handed another member the owner's private title,
    // status, url and document binding.
    const workspaceId = 'goal-graph-workspace';
    await serverDB.insert(workspaces).values({
      id: workspaceId,
      name: 'Goal graph workspace',
      primaryOwnerId: userId,
      slug: 'goal-graph-workspace',
    });
    const ownerGoals = new GoalModel(serverDB, userId, workspaceId);
    const ownerGraph = new GoalGraphModel(serverDB, userId, workspaceId);
    const goal = await ownerGoals.create({ subjectType: 'standalone', title: 'Shared goal' });
    await serverDB.update(goals).set({ workspaceId }).where(eq(goals.id, goal.id));
    const node = await ownerGraph.createNode(goal.id, { kind: 'task', title: 'Produce evidence' });

    const work = await new WorkModel(serverDB, userId, workspaceId).registerExternal({
      changeType: 'created',
      resourceId: 'lobehub/lobehub#1',
      resourceType: 'github_issue',
      title: 'Private follow-up issue',
      toolIdentifier: 'goal-test',
      toolName: 'createIssue',
      url: 'https://github.com/lobehub/lobehub/issues/1',
    });
    await ownerGraph.attachWorkVersion(goal.id, node!.id, work!.currentVersionId!, 'produced');

    const asOwner = await ownerGraph.getGraph(goal.id);
    expect(asOwner?.workVersions[0].work).toMatchObject({ title: 'Private follow-up issue' });

    // The other member reaches the same goal and the same link…
    const asMember = await new GoalGraphModel(serverDB, otherUserId, workspaceId).getGraph(goal.id);
    expect(asMember?.workVersions).toHaveLength(1);
    // …but the Work behind it stays unresolved rather than naming itself.
    expect(asMember?.workVersions[0].work).toBeUndefined();
  });

  it('does not expose or mutate another user graph', async () => {
    const otherGoalModel = new GoalModel(serverDB, otherUserId);
    const otherGraphModel = new GoalGraphModel(serverDB, otherUserId);
    const goal = await otherGoalModel.create({ subjectType: 'standalone', title: 'Private graph' });
    const node = await otherGraphModel.createNode(goal.id, { kind: 'task', title: 'Private work' });

    expect(await graphModel.getGraph(goal.id)).toBeUndefined();
    expect(await graphModel.updateNodeStatus(goal.id, node!.id, 'resolved')).toBeUndefined();

    const graph = await otherGraphModel.getGraph(goal.id);
    expect(graph?.nodes[0].status).toBe('proposed');
    expect(graph?.events).toHaveLength(1);
  });

  it('caps the events a graph read carries, newest first', async () => {
    // The detail page polls getGraph every few seconds; without a limit a
    // long-horizon goal's payload grew linearly with its age.
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Noisy graph' });
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Churn' });
    for (let i = 0; i < GoalGraphModel.GRAPH_EVENT_LIMIT + 5; i++) {
      await graphModel.updateNodeStatus(goal.id, node!.id, i % 2 ? 'active' : 'waiting');
    }

    const graph = await graphModel.getGraph(goal.id);

    expect(graph?.events).toHaveLength(GoalGraphModel.GRAPH_EVENT_LIMIT);
    const createdAt = graph!.events.map((event) => event.createdAt.getTime());
    expect([...createdAt].sort((a, b) => b - a)).toEqual(createdAt);
    expect(graph!.events[0].eventType).toBe('updated');
  });

  it('records a goal-level status transition as a system-attributed event', async () => {
    // The lifecycle event types existed in the schema but nothing wrote them,
    // so a goal's planning → running → paused path left no trace at all.
    const goal = await goalModel.create({ subjectType: 'standalone', title: 'Status trail' });
    const coordinator = new GoalGraphModel(serverDB, userId, undefined, {
      id: GOAL_COORDINATOR_ACTOR_ID,
      type: 'system',
    });

    await coordinator.recordGoalStatus(goal.id, 'planning', 'running');
    await coordinator.recordGoalStatus(goal.id, 'running', 'paused', 'nothing ready');
    // A same-status write is a no-op — re-stamping would flood the timeline.
    await coordinator.recordGoalStatus(goal.id, 'paused', 'paused');

    const events = (await graphModel.getGraph(goal.id))!.events.filter(
      (event) => event.entityType === 'goal',
    );

    expect(events).toHaveLength(2);
    // Newest first: [1] is the earlier activation, [0] the later pause.
    expect(events[1]).toMatchObject({
      actorId: GOAL_COORDINATOR_ACTOR_ID,
      actorType: 'system',
      entityId: goal.id,
      eventType: 'activated',
      reason: 'status planning → running',
    });
    expect(events[0]).toMatchObject({
      eventType: 'updated',
      reason: 'nothing ready',
    });
  });
});

// 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;
    }
  },
);
describe('GoalGraphModel.removeDraftEdges', () => {
  const seed = async (status: 'draft' | 'running') => {
    const goal = await goalModel.create({ status, subjectType: 'standalone', title: 'Edges' });
    const first = await graphModel.createNode(goal.id, { kind: 'task', title: 'First' });
    const second = await graphModel.createNode(goal.id, { kind: 'task', title: 'Second' });
    await graphModel.createEdge(goal.id, second!.id, first!.id, 'depends_on');
    await graphModel.createEdge(goal.id, second!.id, first!.id, 'leads_to');
    return { first: first!.id, goalId: goal.id, second: second!.id };
  };

  it('removes only the matching kind from a draft and records the unlink', async () => {
    const { first, goalId, second } = await seed('draft');

    const result = await graphModel.removeDraftEdges(
      goalId,
      { kind: 'depends_on', sourceNodeId: second, targetNodeId: first },
      'wrong direction',
    );

    expect(result).toMatchObject({ status: 'removed' });
    const graph = await graphModel.getGraph(goalId);
    expect(graph?.edges.map((edge) => edge.kind)).toEqual(['leads_to']);
    expect(graph?.events[0]).toMatchObject({
      entityType: 'edge',
      eventType: 'unlinked',
      reason: 'wrong direction',
    });
  });

  it('removes every edge between the pair when no kind is given', async () => {
    const { first, goalId, second } = await seed('draft');

    const result = await graphModel.removeDraftEdges(goalId, {
      sourceNodeId: second,
      targetNodeId: first,
    });

    expect(result.status === 'removed' && result.edgeIds).toHaveLength(2);
    expect((await graphModel.getGraph(goalId))?.edges).toHaveLength(0);
  });

  it('leaves a started goal untouched', async () => {
    const { first, goalId, second } = await seed('running');

    const result = await graphModel.removeDraftEdges(goalId, {
      sourceNodeId: second,
      targetNodeId: first,
    });

    expect(result).toEqual({ goalStatus: 'running', status: 'not_draft' });
    expect((await graphModel.getGraph(goalId))?.edges).toHaveLength(2);
  });

  it('does not touch another user goal', async () => {
    const { first, goalId, second } = await seed('draft');

    const result = await new GoalGraphModel(serverDB, otherUserId).removeDraftEdges(goalId, {
      sourceNodeId: second,
      targetNodeId: first,
    });

    expect(result).toEqual({ status: 'not_found' });
    expect((await graphModel.getGraph(goalId))?.edges).toHaveLength(2);
  });
});

describe('GoalGraphModel guard branches', () => {
  const seedGoal = async (title: string) => goalModel.create({ subjectType: 'standalone', title });

  it('refuses every goal-scoped write on another user goal', async () => {
    const goal = await seedGoal('Owned elsewhere');
    const sibling = new GoalGraphModel(serverDB, otherUserId);

    expect(
      await sibling.createNode(goal.id, { kind: 'task', title: 'Intruder task' }),
    ).toBeUndefined();
    expect(
      await sibling.createNodeOnce(goal.id, { kind: 'task', title: 'Intruder task' }),
    ).toBeUndefined();
    expect(
      await sibling.createEdge(goal.id, 'source-node', 'target-node', 'leads_to'),
    ).toBeUndefined();
    expect(await sibling.bindTask(goal.id, 'node', 'task')).toBeUndefined();
    expect(await sibling.claimTaskNode(goal.id, 'node', new Date())).toBeUndefined();
    expect(await sibling.updateNodeDescription(goal.id, 'node', 'desc')).toBeUndefined();
    expect(
      await sibling.createDecision(goal.id, 'node', { authority: 'user', question: 'why?' }),
    ).toBeUndefined();
    expect(await sibling.resolveDecision(goal.id, 'decision', 'option')).toBeUndefined();
    expect(await sibling.cancelDecision(goal.id, 'decision', 'never asked')).toBeUndefined();
    expect(await sibling.attachWorkVersion(goal.id, 'node', 'version', 'produced')).toBeUndefined();

    // Nothing leaked through: the goal graph is still empty for its owner.
    const graph = await graphModel.getGraph(goal.id);
    expect(graph?.nodes).toHaveLength(0);
    expect(graph?.edges).toHaveLength(0);
  });

  it('rejects an experiment that answers no question', async () => {
    const goal = await seedGoal('Experiment without a question');

    await expect(
      graphModel.createNode(goal.id, { kind: 'experiment', title: 'Try it' }),
    ).rejects.toThrow('An experiment must answer a question');
  });

  it('rejects a non-experiment that claims to answer a question', async () => {
    const goal = await seedGoal('Task answering a question');

    await expect(
      graphModel.createNode(goal.id, {
        kind: 'task',
        questionId: '00000000-0000-0000-0000-000000000000',
        title: 'Not an experiment',
      }),
    ).rejects.toThrow('Only experiments can answer questions');
  });

  it('returns undefined when the node to attach a Work version to is missing', async () => {
    const goal = await seedGoal('No such node');

    expect(
      await graphModel.attachWorkVersion(
        goal.id,
        '00000000-0000-0000-0000-000000000000',
        '00000000-0000-0000-0000-000000000001',
        'produced',
      ),
    ).toBeUndefined();
  });

  it('returns undefined when a decision is opened on a non-decision node', async () => {
    const goal = await seedGoal('Decision on a task');
    const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'W1' });

    expect(
      await graphModel.createDecision(goal.id, node!.id, {
        authority: 'user',
        question: 'not a gate',
      }),
    ).toBeUndefined();
  });

  it('returns undefined when resolving an already resolved decision', async () => {
    const goal = await seedGoal('Resolve twice');
    const gate = await graphModel.createNode(goal.id, { kind: 'decision', title: 'Ship?' });
    const decision = await graphModel.createDecision(goal.id, gate!.id, {
      authority: 'user',
      options: [{ id: 'yes', label: 'Yes' }],
      question: 'ship?',
    });

    expect(await graphModel.resolveDecision(goal.id, decision!.id, 'yes')).toBeDefined();
    expect(await graphModel.resolveDecision(goal.id, decision!.id, 'yes')).toBeUndefined();
  });

  it('returns undefined when cancelling an already resolved decision', async () => {
    const goal = await seedGoal('Cancel after resolve');
    const gate = await graphModel.createNode(goal.id, { kind: 'decision', title: 'Ship?' });
    const decision = await graphModel.createDecision(goal.id, gate!.id, {
      authority: 'user',
      options: [{ id: 'yes', label: 'Yes' }],
      question: 'ship?',
    });
    await graphModel.resolveDecision(goal.id, decision!.id, 'yes');

    expect(await graphModel.cancelDecision(goal.id, decision!.id, 'too late')).toBeUndefined();
  });

  it('returns undefined when no goal carries the task', async () => {
    expect(
      await graphModel.findGoalByTaskId('00000000-0000-0000-0000-000000000000'),
    ).toBeUndefined();
  });
});