Repository navigation
Description
Overview
Implement the playbook execution engine in Rust — the runtime that evaluates playbook rules and executes graph operations. The engine subscribes to the existing domain event broadcast channel, matches events against active playbook triggers, evaluates CEL conditions, and executes graph-mutating actions.
Architecture spec: playbook-engine.md — read this end-to-end before starting implementation.
Playbook schema: playbook-system.md — defines triggers, conditions, actions, execution semantics.
Implementation Phases
This is a large feature. Implement in order — each phase builds on the previous one.
Phase 0: Prerequisites (changes to existing codebase)
These changes are required before any engine code. They modify existing infrastructure.
- Enrich `NodeUpdated` event — add `node_type: String` and `changed_properties: Vec` to `DomainEvent::NodeUpdated`. `PropertyChange` has `key`, `old_value`, `new_value`. The pre-mutation node state is already available in `NodeService.update_node()` — thread it through `StoreChange`.
- Introduce `EventEnvelope` — wrap `DomainEvent` + `EventMetadata` on the broadcast channel. `EventMetadata` contains `source_client_id: Option` (migrated from `DomainEvent` variants) and `playbook_context: Option`. Remove `source_client_id` from individual `DomainEvent` variants.
- Update `DomainEventForwarder` — destructure `EventEnvelope`, read `source_client_id` from `metadata` instead of the event. Behavioral no-op — just unwraps the envelope.
- Extend `NodeService` mutation API — add an optional `execution_context` parameter to mutation methods. When present, thread it into the `EventEnvelope.metadata.playbook_context` of the resulting event. When absent (normal user/MCP calls), `playbook_context` is `None`.
- All existing tests pass after these changes — the envelope is transparent to current consumers.
Phase 1: Playbook Lifecycle Manager + Rule Matching
The skeleton: load playbooks, build the trigger index, subscribe to events.
- `PlaybookLifecycleManager` struct — owns `TriggerIndex` (`Arc<std::sync::RwLock<>>`), `CronRegistry`, `ActivePlaybooks` (`HashMap<PlaybookId, ParsedPlaybook>`), and a reference to `NodeService`.
- `TriggerKey` enum — two variants: `NodeEvent { event, node_type, property_key: Option }` and `RelationshipEvent { event, source_node_type }`. Used as HashMap key.
- `TriggerIndex` — `HashMap<TriggerKey, Vec>`. Values sorted by `(playbook_created_at, rule_index)`.
- Startup sequence — subscribe to broadcast channel FIRST (to avoid race), then query all active playbook nodes, parse rules, build `TriggerIndex` and `CronRegistry`. See spec section 7 for exact order.
- Reactive lifecycle — detect `node_type == "playbook"` in incoming events:
- `NodeCreated` → parse and activate (same code path as startup)
- `NodeDeleted` → remove from all indexes
- `NodeUpdated` with status transition → re-enable or disable accordingly
- Schema version drift — on `NodeUpdated` with `node_type == "schema"`, check affected playbooks. Disable + create log node on version mismatch.
- PropertyChanged lookup performs two HashMap lookups: exact `property_key` match AND wildcard (`None`) match, merges results maintaining sort order.
- Write tests: lifecycle operations (install, uninstall, disable, re-enable), TriggerKey matching, startup ordering.
Phase 2: ExecutionQueue + Rule Processor
Wire up the sequential processing pipeline.
- `ExecutionQueue` — bounded `tokio::sync::mpsc` channel, capacity 1024.
- `ExecutionWorkItem` struct — contains `rules: Vec`, `trigger_event: EventEnvelope`, `trigger_node: Node` (pre-fetched, wire format).
- `EventSubscriber` — receives `EventEnvelope`, performs TriggerKey lookup (read lock), pre-fetches trigger node, enqueues `ExecutionWorkItem`.
- `RuleProcessor` — single tokio task that drains the queue. For each work item: evaluate conditions, execute actions (Phases 3-4 implement the actual evaluation/execution — this phase wires the pipeline).
- Backpressure — bounded channel prevents unbounded memory growth.
- Write tests: queue behavior, work item routing, backpressure.
Phase 3: CEL Evaluator
Condition evaluation with graph traversal.
- Add `cel-interpreter` crate (MIT) to `Cargo.toml`.
- Wire format normalization — pass every node through `flatten_properties_for_api` before CEL. Strip namespace prefixes (`custom:status` → `status`) so conditions use bare names.
- Custom variable resolver — intercepts property access on node objects. Resolution order per segment: (1) property lookup on current node, (2) relationship traversal if no property matches. Property wins on name collision.
- Lazy graph loading — relationship traversal queries are only executed when the path segment is accessed during CEL evaluation. Not pre-fetched.
- Segment cache — `HashMap<Vec, ResolvedValue>` within a single condition evaluation. Prevents redundant DB queries for overlapping paths across conditions in the same rule.
- Missing path in conditions → `false` — the condition is not met, but the playbook stays active. Do NOT disable.
- `NodeCollection` type — returned when a relationship traversal yields multiple nodes. Supports:
- `.count` — property, returns integer
- `.any(expr)`, `.all(expr)`, `.none(expr)` — custom CEL functions with lambda
- `.where(expr)` — custom CEL function, returns filtered `NodeCollection` (chainable)
- Empty collection always evaluates to `false` (including `.all()`)
- Custom functions registered at startup:
- `days_since(date)` — parse ISO 8601, compute days elapsed. Future date → negative.
- `days_until(date)` — parse ISO 8601, compute days remaining. Past date → negative.
- `today()` — `chrono::Local::now()`, ISO 8601 with UTC offset.
- Null/invalid date in conditions → `false`. In actions → error.
- `get_workflow_state` MCP tool shares this evaluation infrastructure — condition results without action execution.
- Write tests: dot-path resolution, property vs. relationship precedence, collection operators, empty collection behavior, missing path handling, custom functions (including edge cases: future dates, null dates).
Phase 4: Action Executor
Sequential action execution with binding resolution.
- `BindingContext` struct — holds `trigger_node` (wire format), `property_change: Option`, `action_results: Vec<Option>` (indexed by action position), `for_each_item: Option`.
- `{dot.path}` binding resolution — string template substitution at action execution time. Reuses the same lazy graph traversal as CEL. Resolves against live graph state (not snapshot).
- Missing path in actions → error → disable playbook. (Different from conditions.)
- Action implementations via `NodeService`:
- `create_node` — create node with properties and relationships. Re-check schema version at execution time (not just save time).
- `update_node` — fetch current version first (OCC), then update. Version conflict = action failure.
- `add_relationship` — create relationship between resolved node IDs.
- `remove_relationship` — delete relationship between resolved node IDs.
- `for_each` iteration — resolve full collection before iterating. Each item runs to completion before next. `{item.x}` bindings available during iteration. Any item failure aborts entire rule.
- Abort on failure — skip remaining actions, create `log` node (see Phase 6), set playbook `lifecycle_status` to `"disabled"`, remove from in-memory indexes. No rollback.
- Tag mutations with `PlaybookExecutionContext` — pass execution context to NodeService so resulting events carry depth info.
- Write tests: binding resolution, action sequencing, for_each, abort behavior, OCC handling, schema version check.
Phase 5: Scheduled Trigger Runner
Cron-based rule evaluation.
- Add `cron` crate (MIT) to `Cargo.toml` — for expression parsing only, not scheduling.
- `CronRunner` — single tokio task, wakes every 60 seconds. Checks registered cron expressions via `cron::Schedule::upcoming()`.
- `CronRegistry` — tracks `(cron_expression, node_type)` pairs with associated rule references.
- Deduplication — multiple rules sharing `(cron, node_type)` produce one DB scan. Query: `SELECT * FROM node WHERE node_type = $type AND lifecycle_status = 'active'`.
- Enqueue into `ExecutionQueue` — cron results go through the same sequential processor as event-triggered rules.
- Dynamic registration — add/remove cron entries on playbook install/uninstall/disable.
- No catch-up — missed runs are skipped. Only evaluates against current time.
- Write tests: cron matching, deduplication, dynamic registration/removal, missed run behavior.
Phase 6: Cycle Detection + Log Deduplication
Safety mechanisms.
- `PlaybookExecutionContext` struct — `originating_event_id: Uuid`, `depth: u8`, `source_playbook_id: String`.
- Depth check in `EventSubscriber`:
- `metadata.playbook_context == None` → depth 0 (user/MCP origin)
- `Some { depth }` where `depth + 1 <= 10` → process at `depth + 1`
- `depth + 1 > 10` → create log node, disable playbook, do NOT execute
- Do NOT suppress engine events — rule chaining depends on the engine receiving its own mutations.
- `DomainEventForwarder` forwards engine events — users must see playbook-created nodes in the UI.
- Log node deduplication — error fingerprint: `hash(playbook_id, rule_name, error_location_index, error_type)`. Dynamic values (node IDs, timestamps) excluded.
- Upsert strategy — query for existing log node by fingerprint. If found: increment `occurrences`, update `last_seen`. If not found: create new log node.
- Write tests: cycle detection at various depths, depth propagation across chained rules, log deduplication (same error → increment, different error → new node).
Phase 7: Save-Time Validation
Validate playbooks before persisting.
- Reuse CEL parser — same infrastructure as runtime, no divergence.
- Validation checks:
- All referenced `node_type` values exist as schema nodes
- All referenced `version` values match schema's `schema_version`
- All property paths in conditions parse successfully
- All relationship types in actions exist on referenced schemas
- Reject save on failure — return validation errors to caller.
- Write tests: valid playbook saves, invalid schema references, version mismatches, bad CEL expressions.
Key Architecture Decisions (for context)
Read the full rationale in playbook-engine.md. Summary:
| Decision | Choice | Why |
|---|---|---|
| Change detection | Existing broadcast channel | Already built, no new infrastructure |
| Rule matching | HashMap<TriggerKey, Vec> | O(1) lookup |
| CEL evaluation | Lazy graph loading + segment cache | Avoids pre-fetching entire subgraphs |
| Action execution | Sequential, abort-on-failure, no rollback | Simple, correct for single-user desktop |
| Scheduled triggers | 60-second polling + `cron` crate | Simpler than `tokio-cron-scheduler` for desktop |
| Cycle detection | Depth on EventEnvelope metadata, max 10 | Stateless, carried on the event itself |
| Concurrency | Single tokio task, bounded mpsc queue | Eliminates all concurrency concerns |
| Missing path | Conditions → false, Actions → disable | Conditions are guards, actions are committed |
References
- Playbook Engine Architecture — primary implementation guide
- Playbook System Spec — schema, triggers, conditions, actions
- Data Layer — wire format, `flatten_properties_for_api`
- Backend Architecture — NodeService, domain events
- MCP Integration — source_client_id, MCP tools
- Design session: NodeSpaceAI/nodespace-docs#25 (closed)
- `cel-interpreter` crate (MIT) — condition evaluation
- `cron` crate (MIT) — cron expression parsing
🤖 Generated with Claude Code
Activity
malibio commentedon Apr 1, 2026
Frontend test baseline: 118 test files passed, 1 failed (markdown performance test flake - pre-existing). 3747/3748 individual tests passed.
Playbook Engine Phase 0: EventEnvelope + enriched NodeUpdated (#995)
Address PR #996 review: thread playbook_context, add PartialEq, add t…
Address PR #996 Phase 1 review: doc comments, TODO markers, nit fixes
WIP: Playbook Engine Phase 1 — Lifecycle Manager + TriggerIndex + Rul…
Playbook Engine Phase 2: ExecutionQueue + RuleProcessor (#995)
Address PR #996 Phase 2 review: update docs, add cycle detection TODO
Playbook Engine Phases 3-6: CEL Evaluator, Action Executor, CronRunne…
Address PR #996 review: wire actions into RuleProcessor, thread execu…
Address PR #996 review: thread PlaybookExecutionContext through store…
Phase 7: Save-Time Validation for playbooks (#995)
Playbook Engine Phase 0: EventEnvelope + enriched NodeUpdated (#996)
malibio commentedon Apr 5, 2026
All 7 phases fully implemented:
Minor known limitation: relationship trigger matching deferred to v2 (RelationshipCreated/Deleted events don't carry source_node_type).
Playbook Engine Phase 0: EventEnvelope + enriched NodeUpdated (#996)