AI

AI Debugging: Behavior Trees & StateTrees

AI bugs are hard to test because the moment that matters is usually over by the time you look: the enemy chased for half a second, then switched targets. Specter records an AI trailfor every AI from the start of each test, so you can assert on what happened, not only on what's true right now, and see why a check failed without reproducing it.

What's Recorded

Specter follows every AI controller with a behavior tree, a StateTree or a blackboard, and every other actor with a StateTree component, including AIs your test spawns. Behavior trees and StateTrees both work, in the same project. For each, it records:

  • Where the logic is: the path from a behavior tree's root to its running node, or a StateTree's active states. One entry each time it moves, plus where it was when first seen.
  • Blackboard changes, as they happen (not polled). A key that changes every frame, like a move goal, is folded into one entry with its first and latest values and how many changes there were.
  • The tree itself starting, stopping or being swapped, and a StateTree's run status (Running, Succeeded, Failed, Stopped).

Up to 400 changes per AI and 512 AIs per test. Times are seconds since the test started.

Asserting on AI Behavior

These matchers take the AI controller, the pawn it possesses, or an actor running its own StateTree. State and node names match whole and ignore case.

MatcherPasses when
toBeInState(name)The logic is in that state now: an active StateTree state at any level, or a node on the running behavior tree path. Retries until the timeout.
toHaveVisitedState(name)The logic was in that state at any point of the test, even for a single frame.
toHaveBlackboardChange(key, { from?, to? })The key changed during the test, optionally from or to a value: text, a RegExp, a number, a boolean, or an actor locator.
toHaveBlackboardValue(key, value)The key holds that value now.
toBeRunningBehaviorTree(tree)It runs that behavior tree (asset name or path).
import { test, expect } from '@specter-automation/test';

test('a tower targets the intruder, then lets go when it dies', async ({ world }) => {
  const tower = world.actor('BP_Tower');
  const intruder = await world.spawnActor('BP_Minion_Enemy', { location: { x: 600, y: 0, z: 100 } });

  // The blackboard picked it up (a change that's already over still counts)
  await expect(tower).toHaveBlackboardChange('Target', { to: intruder });

  // Its logic reached the attack, even if it was only there for a moment
  await expect(tower).toHaveVisitedState('Attack');

  // And once the intruder is gone, the target clears
  await expect(intruder).toBeDestroyed({ timeout: 10000 });
  await expect(tower).toHaveBlackboardChange('Target', { from: intruder, to: 'None' });
});

test('a minion fights what it meets on its lane', async ({ world }) => {
  const minion = await world.spawnActor('BP_Minion', { location: { x: 0, y: 2800, z: 100 } });

  // A StateTree: Root › Combat › Attack. A parent state counts too.
  await expect(minion).toBeInState('Combat', { timeout: 8000 });
  await expect(minion).not.toBeInState('Advance');
});

Failures Explain Themselves

When an AI matcher fails (these, and the movement ones like toBeMovingTowards), the message ends with the AI's trail: its recent changes, where it is now and its blackboard, with the keys the check was about listed first. Here the minion never reached its attack because it was still chasing:

Error: Expected AI to be in state 'Attack'.
Active states: Root › Combat › Chase

BP_Minion_C_3's StateTree ST_Minion, its last 4 changes:
     0.00s  ▸ Root › Advance
     2.41s  TargetActor: None → BP_Minion_Enemy_C_0
     2.42s  ▸ Root › Combat › Chase
     6.80s  MoveGoal: (0, 2800, 92) → (1180, 2795, 92) (38 changes until 6.80s)
Now (8.02s): Root › Combat › Chase
Blackboard: TargetActor = BP_Minion_Enemy_C_0 · MoveGoal = (1180, 2795, 92)

Reading the Trail in a Test

getBehaviorTrail()returns the whole record, for checks the matchers don't cover or for logging:

import { describeBehaviorTrail } from '@specter-automation/test';

const trail = await minion.getBehaviorTrail({ limit: 50 });

trail.logic;        // 'StateTree' | 'BehaviorTree'
trail.tree;         // 'ST_Minion'
trail.activePath;   // ['Root', 'Combat', 'Chase']
trail.blackboard;   // { TargetActor: 'BP_Minion_Enemy_C_0', ... }

// Every time the logic moved, oldest first
const visited = trail.events.filter(e => e.kind === 'active').map(e => e.path.join(' › '));

// The same text the matchers print when they fail
console.log(describeBehaviorTrail(trail, { keys: ['TargetActor'] }));

BehaviorTrail

interface BehaviorTrail {
  actor: string;          // the pawn (or StateTree actor)
  controller: string;     // its AI controller ('' for an actor running its own StateTree)
  logic: 'BehaviorTree' | 'StateTree' | '';
  tree: string;           // the asset it runs
  running: boolean;
  status: string;         // a StateTree's run status
  activePath: string[];   // root to the running node, or the active states
  blackboard: Record<string, string>;
  events: BehaviorTrailEvent[];   // the most recent changes, oldest first
  earlierEvents: number;          // changes before those that weren't sent
  recorded: boolean;      // false when no test was running
  now: number;            // seconds since the test started
}

type BehaviorTrailEvent =
  | { t: number; kind: 'active'; path: string[]; from: string }
  | { t: number; kind: 'blackboard'; key: string; from: string; to: string; changes?: number; until?: number }
  | { t: number; kind: 'tree'; from: string; to: string }
  | { t: number; kind: 'status'; from: string; to: string };

On the Runner's Timeline

Every change also goes on the test's timeline in the in-engine runner, as lime markers in the AI category (with its own filter chip), on the same row as that actor's tags and attributes. They read like Combat › Attack or Target: None → BP_Minion_C_2. The timeline preview also points its camera at AIs whose behavior changes, so you can scrub to the moment and see it.