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.

8.1 KB
Raw Blame
import type { GoalGraphState, GoalTickSnapshot, GoalTrajectory } from '@lobechat/agent-tracing';
import { describe, expect, it } from 'vitest';

import {
  coordinatorDecider,
  fromTraceGraphState,
  replayGoalAgainstCurrentCoordinator,
} from './replayCoordinator';
import { toTraceGraphState } from './traceObservation';

const task = (id: string, overrides: Partial<GoalGraphState['nodes'][number]> = {}) => ({
  createdAt: 1000,
  id,
  kind: 'task',
  priority: 0,
  status: 'proposed',
  taskId: null,
  title: id,
  ...overrides,
});

const graphState = (overrides: Partial<GoalGraphState> = {}): GoalGraphState => ({
  decisions: [],
  edges: [],
  goal: {
    id: 'goal_1',
    maxRounds: null,
    maxTotalCost: null,
    requirement: 'Prove it',
    status: 'running',
    title: 'Reproduce nanoGPT',
  },
  nodes: [],
  ...overrides,
});

const tick = (index: number, overrides: Partial<GoalTickSnapshot>): GoalTickSnapshot => ({
  at: 1000,
  branch: 'create_task',
  candidates: [],
  effects: [],
  graphShape: {
    edgesTotal: 0,
    findings: 0,
    gatesPending: 0,
    nodesTotal: 0,
    tasksBlocked: 0,
    tasksOpen: 0,
    tasksReady: 0,
    tasksCompleted: 0,
  },
  index,
  message: '',
  outcome: 'advanced',
  ...overrides,
});

/**
 * Two advances of a two-Task goal: the second Task depends on the first, so the
 * coordinator picks `a`, then picks `b` only once `a` resolves.
 */
const trajectory: GoalTrajectory = {
  advances: [
    {
      completedAt: 10,
      durationMs: 10,
      seq: 0,
      startedAt: 0,
      ticks: [
        tick(0, {
          candidates: [
            { blockedBy: [], nodeId: 'a', priority: 0, status: 'proposed', title: 'a' },
            { blockedBy: ['a'], nodeId: 'b', priority: 0, status: 'proposed', title: 'b' },
          ],
          chosenNodeId: 'a',
        }),
      ],
      trigger: 'create',
    },
    {
      completedAt: 30,
      durationMs: 10,
      seq: 1,
      startedAt: 20,
      ticks: [
        tick(0, {
          candidates: [{ blockedBy: [], nodeId: 'b', priority: 0, status: 'proposed', title: 'b' }],
          chosenNodeId: 'b',
          graphDelta: { nodesUpserted: [task('a', { status: 'resolved' })] },
        }),
      ],
      trigger: 'settle',
    },
  ],
  goalId: 'goal_1',
  graphBaseline: graphState({
    edges: [{ id: 'e1', kind: 'depends_on', sourceNodeId: 'b', targetNodeId: 'a' }],
    nodes: [task('a'), task('b')],
  }),
  startedAt: 0,
  title: 'Reproduce nanoGPT',
  totalAdvances: 2,
  totalTicks: 2,
  traceId: 'goal_1',
};

describe('replayGoalAgainstCurrentCoordinator', () => {
  it('reproduces a recorded run against the live coordinator', () => {
    expect(replayGoalAgainstCurrentCoordinator(trajectory)).toMatchObject({
      divergences: [],
      matched: 2,
      ticks: 2,
    });
  });

  it('reports the advance and tick where the coordinator would now choose differently', () => {
    const altered: GoalTrajectory = {
      ...trajectory,
      advances: [
        trajectory.advances[0],
        {
          ...trajectory.advances[1],
          ticks: [{ ...trajectory.advances[1].ticks[0], chosenNodeId: 'a' }],
        },
      ],
    };

    expect(replayGoalAgainstCurrentCoordinator(altered).divergences).toEqual([
      { advanceSeq: 1, field: 'chosenNodeId', recorded: 'a', replayed: 'b', tickIndex: 0 },
    ]);
  });

  it('replays the dependency gate from the state at each tick, not the final one', () => {
    // Without folding the delta, `b` would look blocked at advance 1 and the
    // recorded choice would read as a divergence.
    const result = replayGoalAgainstCurrentCoordinator(trajectory);

    expect(result.matched).toBe(result.ticks);
  });

  it('carries the recorded budget into the decision', () => {
    const exhausted: GoalTrajectory = {
      ...trajectory,
      advances: [
        {
          ...trajectory.advances[0],
          ticks: [
            tick(0, {
              branch: 'budget_exhausted',
              budget: {
                costLimitReached: true,
                maxTotalCost: 1,
                roundLimitReached: false,
                runs: 4,
                totalCost: 2,
              },
              candidates: [
                { blockedBy: [], nodeId: 'a', priority: 0, status: 'proposed', title: 'a' },
                { blockedBy: ['a'], nodeId: 'b', priority: 0, status: 'proposed', title: 'b' },
              ],
              chosenNodeId: 'a',
              candidateTasks: [{ id: 'task_1', nodeId: 'a', status: 'backlog', updatedAt: 0 }],
              concurrency: 3,
              outcome: 'no_progress',
            }),
          ],
        },
      ],
      graphBaseline: graphState({
        edges: [{ id: 'e1', kind: 'depends_on', sourceNodeId: 'b', targetNodeId: 'a' }],
        nodes: [task('a', { taskId: 'task_1' }), task('b')],
      }),
    };

    expect(replayGoalAgainstCurrentCoordinator(exhausted).divergences).toEqual([]);
  });

  /**
   * The measured gate stops in the terminal phase, exactly like the delivery
   * contract does. If the replay could not tell the two apart, a regressed gate
   * would be reported as a match — the one failure mode a regression harness
   * must not have.
   */
  const measured = (branch: 'measured_acceptance' | 'terminal_acceptance'): GoalTrajectory => ({
    ...trajectory,
    advances: [
      {
        ...trajectory.advances[0],
        ticks: [
          tick(0, {
            branch,
            candidates: [],
            metricCriteria: {
              allMet: false,
              criteria: [{ key: 'followers', met: false, op: 'gte', target: 1_000_000, value: 42 }],
            },
            outcome: 'no_progress',
          }),
        ],
      },
    ],
    // No config on the replayed goal on purpose: the gate reads the recorded
    // `metricCriteria` and nothing else, which is what makes it replayable
    // from the trajectory alone.
    graphBaseline: graphState({ nodes: [task('a', { status: 'resolved' })] }),
  });

  it('carries the recorded measured criteria into the decision', () => {
    expect(
      replayGoalAgainstCurrentCoordinator(measured('measured_acceptance')).divergences,
    ).toEqual([]);
  });

  it('reports a gate that no longer fires instead of matching it', () => {
    // A trajectory whose terminal tick was recorded as the plain delivery
    // contract must not replay as an unmet gate, and vice versa.
    expect(
      replayGoalAgainstCurrentCoordinator(measured('terminal_acceptance')).divergences,
    ).toMatchObject([
      { field: 'branch', recorded: 'terminal_acceptance', replayed: 'measured_acceptance' },
    ]);
  });
});

describe('replaying trajectories recorded before the scheduler', () => {
  it('reads the legacy single-task field instead of seeing no tasks at all', () => {
    // Older ticks carry `frontierTask`, not `candidateTasks`. Dropping it would
    // replay every one of them as `missing_task` and report divergences that
    // never happened.
    const legacy: GoalTrajectory = {
      ...trajectory,
      advances: [
        {
          ...trajectory.advances[0],
          ticks: [
            {
              ...trajectory.advances[0].ticks[0],
              branch: 'dispatch_task',
              candidateTasks: undefined,
              frontierTask: { id: 'task_1', status: 'backlog', updatedAt: 0 },
            },
          ],
        },
      ],
      graphBaseline: {
        ...trajectory.graphBaseline,
        nodes: [
          { ...trajectory.graphBaseline.nodes[0], taskId: 'task_1' },
          trajectory.graphBaseline.nodes[1],
        ],
      },
    };

    const result = replayGoalAgainstCurrentCoordinator(legacy);

    expect(result.divergences.filter((item) => item.replayed === 'missing_task')).toEqual([]);
  });
});

it('preserves exploration policy through trace and replay', () => {
  const state = graphState({ nodes: [task('baseline', { status: 'resolved' })] });
  state.goal.exploration = { instruction: 'Explore alternatives', maxExperiments: 3 };
  const roundtrip = toTraceGraphState(fromTraceGraphState(state));
  expect(roundtrip.goal.exploration).toEqual(state.goal.exploration);
  expect(coordinatorDecider({ graph: roundtrip }).branch).toBe('explore_graph');
});