PHPackages                             taecontrol/nodegraph - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. taecontrol/nodegraph

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

taecontrol/nodegraph
====================

Build agentic apps

0.2.1(9mo ago)032[2 PRs](https://github.com/taecontrol/nodegraph/pulls)MITPHPPHP ^8.4CI passing

Since Sep 11Pushed 2mo agoCompare

[ Source](https://github.com/taecontrol/nodegraph)[ Packagist](https://packagist.org/packages/taecontrol/nodegraph)[ Docs](https://github.com/taecontrol/nodegraph)[ GitHub Sponsors](https://github.com/Taecontrol)[ RSS](/packages/taecontrol-nodegraph/feed)WikiDiscussions main Synced today

READMEChangelog (4)Dependencies (12)Versions (10)Used By (0)

Build agentic apps with NodeGraph
=================================

[](#build-agentic-apps-with-nodegraph)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d25276f2eff56fc5a5a72278cf8e74e1628310fdc61300ab96f4e89ae9b5ef9c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746165636f6e74726f6c2f6e6f646567726170682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/taecontrol/nodegraph)[![GitHub Tests Action Status](https://camo.githubusercontent.com/8ad9d61add89ded49ac1ada84c8ca36bace4f47e26f1ecad53be06cb08ea2256/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746165636f6e74726f6c2f6e6f646567726170682f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/taecontrol/nodegraph/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/1b93e1e05677ec21a174fe470737f9b70cfe9c719f89e1ac3d5677f3545a721a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746165636f6e74726f6c2f6e6f646567726170682f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/taecontrol/nodegraph/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/266524bc436ccede880dc96b3e5f2570171e2556e9839594e467f804e8cc6547/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746165636f6e74726f6c2f6e6f646567726170682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/taecontrol/nodegraph)

NodeGraph is a tiny, testable state-graph runtime for Laravel. Define your process as an enum of states, map each state to a Node class, and let a Graph run the flow step-by-step while recording checkpoints, metadata, and dispatching events.

Core capabilities:

- Deterministic state transitions via a directed graph
- Nodes execute your domain logic and return a Decision (next state, metadata, events)
- Threads persist progress (`graph_name`, `current_state`, timestamps, metadata)
- Checkpoints store a timeline of transitions with merged metadata
- Multi-graph: configure multiple independent graphs, each with its own state enum

Why multi-graph?
----------------

[](#why-multi-graph)

Real systems rarely have a single lifecycle. Orders, shipments, payouts, document reviews—each has its own progression logic. Multi-graph support lets you:

- Model each lifecycle with a dedicated state enum + Graph class
- Persist them all in the same `threads` table (distinguished by `graph_name`)
- Keep logic isolated while sharing infrastructure (events, metadata, checkpoints)

Requirements
------------

[](#requirements)

- PHP &gt;= 8.4
- Laravel (Illuminate Contracts) ^12.0 (works with ^11.0 as well per constraint, but docs target 12)

Installation
------------

[](#installation)

Install via Composer:

```
composer require taecontrol/nodegraph
```

Publish the migration and migrate:

```
php artisan vendor:publish --tag="nodegraph-migrations"
php artisan migrate
```

Publish the config:

```
php artisan vendor:publish --tag="nodegraph-config"
```

Locate `config/nodegraph.php`. You will see a `graphs` array. Each entry declares a graph name and the enum that represents its states.

Single-graph (default) usage example (Quickstart below shows code usage):

```
return [
    'graphs' => [
        [
            'name' => 'default',
            'state_enum' => \App\Domain\Order\OrderState::class, // IMPORTANT: class constant (no quotes)
        ],
    ],
];
```

> Note: The published config may show a quoted "::class" string placeholder—replace it with the actual class constant as shown above.

Core concepts
-------------

[](#core-concepts)

- State enum: a PHP BackedEnum implementing `Taecontrol\NodeGraph\Contracts\HasNode`. Each enum case maps to a Node class.
- Node: extends `Taecontrol\NodeGraph\Node`. Implement `handle($context)` and return a `Decision`.
- Decision: extends `Taecontrol\NodeGraph\Decision`. Holds `nextState()`, `metadata()`, and `events()`.
- Graph: extends `Taecontrol\NodeGraph\Graph`. Implement `define()` (edges) and `initialState()`.
- Context: extends `Taecontrol\NodeGraph\Context`. Provides a `thread()` method.
- Thread model: `Taecontrol\NodeGraph\Models\Thread` stores `graph_name`, `current_state`, `metadata`, `started_at`, `finished_at`; has many `checkpoints`.
- Checkpoint model: `Taecontrol\NodeGraph\Models\Checkpoint` stores `state` + snapshot metadata per run.

How it runs
-----------

[](#how-it-runs)

`Graph::run($context)` will:

1. Initialize the thread's `current_state` to the graph's `initialState()` if null, setting `started_at`.
2. If the current state is terminal (no outgoing edges), return immediately — no node is executed.
3. Resolve the Node for the current state and execute it.
4. Validate the transition (`assertValidTransition`) before any side effects. Throws `InvalidStateTransition` if the node returns an undeclared next state.
5. The Node's Decision metadata is augmented with `state` and `execution_time` (seconds, float).
6. Inside a database transaction (with `lockForUpdate()` on existing threads):
    - Thread metadata is merged under the key of the current state's enum value.
    - A checkpoint is created with merged metadata.
    - Thread state advances. If the new state is terminal, `finished_at` is set.
7. After the transaction commits, Decision events are dispatched. If the new state is terminal, a `GraphFinished` event is dispatched.

All database writes in step 6 are atomic — they succeed together or roll back together. Events in step 7 only fire after a successful commit, so listeners always see consistent data.

Quickstart (single graph)
-------------------------

[](#quickstart-single-graph)

1. Create a state enum mapping states to Node classes:

```
use Taecontrol\NodeGraph\Contracts\HasNode;

enum OrderState: string implements HasNode
{
    case Start = 'start';
    case Charge = 'charge';
    case Done = 'done';

    public function node(): string
    {
        return match ($this) {
            self::Start => \App\Nodes\StartNode::class,
            self::Charge => \App\Nodes\ChargeNode::class,
            self::Done => \App\Nodes\DoneNode::class,
        };
    }
}
```

2. Create a Decision class:

```
namespace App\Decisions;

use Taecontrol\NodeGraph\Decision;

class SimpleDecision extends Decision {}
```

3. Create Nodes for each state:

```
namespace App\Nodes;

use App\Decisions\SimpleDecision;
use App\Enums\OrderState;
use App\Events\OrderEvent; // extends Taecontrol\NodeGraph\Event
use Taecontrol\NodeGraph\Node;

class StartNode extends Node
{
    public function handle($context): SimpleDecision
    {
        $d = new SimpleDecision(OrderState::Charge);
        $d->addMetadata('from', 'start');
        $d->addEvent(new OrderEvent('start'));
        return $d;
    }
}

class ChargeNode extends Node
{
    public function handle($context): SimpleDecision
    {
        // ... charge logic ...
        $d = new SimpleDecision(OrderState::Done);
        $d->addMetadata('from', 'charge');
        $d->addEvent(new OrderEvent('charged'));
        return $d;
    }
}

// DoneNode is never executed — terminal states are no-ops.
// The enum still maps Done to a node class (PHP requires exhaustive match),
// but Graph::run() returns early before resolving it.
```

4. Define your Graph:

```
use Taecontrol\NodeGraph\Graph;
use App\Enums\OrderState;

class OrderGraph extends Graph
{
    public function define(): void
    {
        $this->addEdge(OrderState::Start, OrderState::Charge);
        $this->addEdge(OrderState::Charge, OrderState::Done);
        // Done has no outgoing edges; it's terminal
    }

    public function initialState(): OrderState
    {
        return OrderState::Start;
    }
}
```

5. Provide a Context that exposes the Thread:

```
use Taecontrol\NodeGraph\Context;
use Taecontrol\NodeGraph\Models\Thread;

class OrderContext extends Context
{
    public function __construct(protected Thread $thread) {}

    public function thread(): Thread
    {
        return $this->thread;
    }
}
```

6. Create and run a Thread (e.g. controller, job, listener):

```
use Taecontrol\NodeGraph\Models\Thread;

$thread = Thread::create([
    'threadable_type' => \App\Models\Order::class,
    'threadable_id' => (string) \Illuminate\Support\Str::ulid(),
    'graph_name' => 'default', // single-graph setup uses 'default'
    'metadata' => [],
]);

$context = new \App\Contexts\OrderContext($thread);
$graph = app(\App\Graphs\OrderGraph::class); // graph_name does NOT auto-resolve to a class

$graph->run($context); // Start -> Charge
$graph->run($context); // Charge -> Done (finished_at set, GraphFinished dispatched)
$graph->run($context); // Done is terminal — no-op
```

Observability:

- `threads.current_state` moves across runs
- `threads.metadata` accumulates per-state metadata (includes `execution_time`)
- `checkpoints` appended each run with merged metadata snapshot
- Domain events dispatched through Laravel's event dispatcher

Advanced: Multi-graph usage
---------------------------

[](#advanced-multi-graph-usage)

You can define multiple graphs—each with its own enum—inside the same application. All share `threads` and `checkpoints` tables, distinguished by `graph_name`.

`config/nodegraph.php` example:

```
return [
    'graphs' => [
        [
            'name' => 'default',
            'state_enum' => \App\Domain\Order\OrderState::class,
        ],
        [
            'name' => 'shipment',
            'state_enum' => \App\Domain\Shipment\ShipmentState::class,
        ],
    ],
];
```

Second enum + graph example:

```
use Taecontrol\NodeGraph\Contracts\HasNode;

enum ShipmentState: string implements HasNode
{
    case Queued = 'queued';
    case Picking = 'picking';
    case Dispatching = 'dispatching';
    case Delivered = 'delivered';

    public function node(): string
    {
        return match ($this) {
            self::Queued => \App\Nodes\Shipment\QueuedNode::class,
            self::Picking => \App\Nodes\Shipment\PickingNode::class,
            self::Dispatching => \App\Nodes\Shipment\DispatchingNode::class,
            self::Delivered => \App\Nodes\Shipment\DeliveredNode::class,
        };
    }
}

class ShipmentGraph extends \Taecontrol\NodeGraph\Graph
{
    public function define(): void
    {
        $this->addEdge(ShipmentState::Queued, ShipmentState::Picking);
        $this->addEdge(ShipmentState::Picking, ShipmentState::Dispatching);
        $this->addEdge(ShipmentState::Dispatching, ShipmentState::Delivered);
    }

    public function initialState(): ShipmentState
    {
        return ShipmentState::Queued;
    }
}
```

Creating threads for different graphs:

```
$orderThread = Thread::create([
    'threadable_type' => \App\Models\Order::class,
    'threadable_id' => (string) \Illuminate\Support\Str::ulid(),
    'graph_name' => 'default',
]);

$shipmentThread = Thread::create([
    'threadable_type' => \App\Models\Shipment::class,
    'threadable_id' => (string) \Illuminate\Support\Str::ulid(),
    'graph_name' => 'shipment',
]);

app(\App\Graphs\OrderGraph::class)->run(new OrderContext($orderThread));
app(\App\Graphs\ShipmentGraph::class)->run(new ShipmentContext($shipmentThread));
```

### Important notes

[](#important-notes)

- `graph_name` does NOT auto-resolve a Graph class—you must choose the appropriate class yourself (e.g. via a map or conditional lookup).
- Each thread's state casting uses the enum from the matching config entry. If the `graph_name` is not configured, the enum cast will not apply (state behaves as a raw string). Document or validate `graph_name` creation to avoid surprises.
- Metadata and events are entirely isolated per thread—even across different graphs.
- `finished_at` is set automatically when a thread transitions into a terminal state. A `GraphFinished` event is dispatched at the same time.

### Retrieving enum metadata dynamically

[](#retrieving-enum-metadata-dynamically)

If you need the enum class for a given thread:

```
$enumClass = collect(config('nodegraph.graphs'))
    ->firstWhere('name', $thread->graph_name)['state_enum'] ?? null;
```

Check for `null` if the graph might not be configured.

API cheatsheet
--------------

[](#api-cheatsheet)

- `Graph::addEdge(sourceState, targetState)` — define allowed transitions
- `Graph::neighborsOf(State): array` — list outgoing states from the given state
- `Graph::canTransition(sourceState, targetState): bool` — check if transition is allowed
- `Graph::assertValidTransition(sourceState, targetState): void` — throws `InvalidStateTransition` on invalid transitions
- `Graph::isTerminal(State): bool` — true when no outgoing edges
- `Graph::run(Context): void` — execute one step and persist side effects
- `GraphFinished` event — dispatched when a thread reaches a terminal state (carries `thread`, `graphName`, `finalState`)

Data model
----------

[](#data-model)

Tables (published migration):

- threads
    - id (ULID), threadable\_type, threadable\_id (morphs)
    - graph\_name (string)
    - current\_state (string, cast to enum when configured), metadata (json)
    - started\_at, finished\_at, timestamps, softDeletes
- checkpoints
    - id (ULID), thread\_id, state (string, cast to enum when configured)
    - metadata (json), timestamps, softDeletes

Both `Thread::current_state` and `Checkpoint::state` are cast using the selected graph's `state_enum` if a matching `graph_name` is found.

Behavior with unknown graph\_name
---------------------------------

[](#behavior-with-unknown-graph_name)

If a thread references a `graph_name` absent from configuration:

- No enum casting will occur (raw string states)
- You must handle validation manually
- Graph execution will still function if you manually run the appropriate Graph class with states using the same raw values

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for recent changes.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Luis Güette](https://github.com/guetteman)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance73

Regular maintenance activity

Popularity7

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 93.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

4

Last Release

279d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/35845741?v=4)[Luis Güette](/maintainers/guetteluis)[@guetteluis](https://github.com/guetteluis)

---

Top Contributors

[![guetteman](https://avatars.githubusercontent.com/u/13571642?v=4)](https://github.com/guetteman "guetteman (60 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

laraveltaecontrolnodegraph

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/taecontrol-nodegraph/health.svg)

```
[![Health](https://phpackages.com/badges/taecontrol-nodegraph/health.svg)](https://phpackages.com/packages/taecontrol-nodegraph)
```

###  Alternatives

[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[codewithdennis/filament-select-tree

The multi-level select field enables you to make single selections from a predefined list of options that are organized into multiple levels or depths.

329530.5k29](/packages/codewithdennis-filament-select-tree)[worksome/exchange

Check Exchange Rates for any currency in Laravel.

124603.0k](/packages/worksome-exchange)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3914.6k](/packages/rawilk-profile-filament-plugin)[tarfin-labs/event-machine

Event-driven state machines for Laravel with event sourcing, type-safe context, and full audit trail.

199.4k](/packages/tarfin-labs-event-machine)[tapp/filament-form-builder

User facing form builder using Filament components

132.4k3](/packages/tapp-filament-form-builder)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
