# go-bt

A minimalist [[behavior-tree]] library for Go. Designed for background workers, game AI, task automation, and asynchronous logic. Nodes return state instantly (cooperative multitasking) rather than blocking with goroutines or sleeps.

## How it works

Every node's `Run` method returns one of three integers: `1` (success), `0` (running), `-1` (failure). A supervisor ticks the tree on a configurable interval, and each tick propagates through the tree without blocking.

The core abstraction is `BTContext[T]`, a generic context that embeds Go's `context.Context` (for cancellation/timeouts) and carries a typed blackboard — a shared state struct that nodes read from and write to.

Node types:

- **Composites** — `Selector` (try children until one succeeds), `Sequence` (run children until one fails), `MemSequence` (resume from where it left off)
- **Decorators** — `Inverter`, `Optional` (swallow failures), `Timeout`, `Retry`, `Repeat`
- **Leaves** — `Condition` (check blackboard), `Action` (do work), `Sleep` (non-blocking wait)

## Usage

```go
type WorkerState struct {
    IsConnected  bool
    PendingTasks int
}

tree := composite.NewSelector(
    composite.NewSequence(
        leaf.NewCondition(func(bb *WorkerState) bool {
            return bb.IsConnected
        }),
        leaf.NewAction(func(ctx *core.BTContext[WorkerState]) int {
            ctx.Blackboard.PendingTasks--
            return 1
        }),
    ),
)

supervisor := core.NewSupervisor(tree, 100*time.Millisecond, func(err any) {
    println("recovered:", err)
})
wg := supervisor.Start(btCtx)
wg.Wait()
```

## Testing

The library injects a clock on `BTContext`, so temporal nodes (`Timeout`, `Sleep`) can be tested by advancing time artificially — no real waits needed.

## Limitations

Very new (April 2026, ~73 stars). No license declared yet. No parallel node for concurrent child execution. The stateless composite design means `MemSequence` is the only way to resume mid-sequence across ticks.

For data-oriented entity management to pair with per-entity behavior trees, see [[ark-ecs|Ark]] — both are minimal Go libraries with similar design philosophy.

https://github.com/rvitorper/go-bt
