BoxLang 🚀 A New JVM Dynamic Language Learn More...
RuleBox is a modern, intuitive, natural-language rules engine for BoxLang and ColdBox applications.
Tired of classes filled with if/then/else statements?
Need a nice abstraction that decouples rules from each other and lets
you write them the same way you write the rest of your BoxLang?
RuleBox is right for you. Rules are written in an expressive, dynamic
Domain Specific Language modeled closely after the Given-When-Then methodology.
Full documentation, guides, and the complete DSL reference at: https://rulebox.coldbox.org
The site covers everything: getting started, defining RuleBooks, the
given/when/except/then/using/stop
DSL, facts and results, the Builder, rule auditing,
thread safety, error handling, and a full worked example - versioned,
so the 1.0.0 docs stay right where they were.
bx-cli module for BoxLang)In your ColdBox application run this within the CommandBox shell:
box install rulebox
Optionally, if you will be using YAML rules or our SQL metrics store:
box install bx-yaml
SQLiteMetricsStore): box install
bx-sqlite, plus a datasourcebox install bx-yaml, bx-sqlite
Or open your server.json and add them in the
installScripts section:
"scripts":{
"onServerInitialInstall":"install bx-esapi,bx-yaml,bx-sqlite --noSave"
}
Apache License, Version 2.0.
See CONTRIBUTING.md.
Made with ❤️ by Ortus Solutions, Corp.
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
RULE_STATES.FAILED status: a then() consumer that throws now records the rule as FAILED in the audit trail before the exception is re-thrown to the callerRule.run() now throws a RuleBox.RuleNotAttachedException if called on a Rule that was never attached to a RuleBook via addRule(), instead of a cryptic null-reference errorRule.withPriority( priority ): rules now execute in priority order (highest first) instead of strictly insertion order. Rules sharing the same priority (default 0) execute in the order they were addeddryRun() on both Rule and RuleBook: preview which rules would fire for a given set of facts without invoking any then() consumers or mutating any state (facts, result, or the real audit trail). Unlike run(), Rule.dryRun() does not require the rule to be attached to a RuleBookRule.active( from, until ): restrict a rule to a time window; outside of it the rule is skipped exactly like a failed when(). Either bound is optional. Externalized rule definitions can set this via activeFrom/activeUntil (or active_from/active_until columns for DBRuleSource)RuleBook.loadRules( source ) loads rule definitions from JSONRuleSource, YAMLRuleSource, DBRuleSource, or any object exposing load(), and turns each one into a real Rule - priority, dryRun(), and the audit trail all keep working unmodified. See the "Externalized Rule Definitions" guideRuleBook.registerAction()/registerPredicate(): register named actions/predicates a loaded rule definition can reference by name, accepting a closure/lambda, an object instance (duck-typed execute()/test()), or a WireBox mapping ID string resolved eagerly at registrationeq/neq/lt/lte/gt/gte/in/and/or/not over dot-path facts) for a rule definition's when/except, with no eval - untrusted rule sources can't execute arbitrary codeRuleAction/RulePredicate: optional documented interfaces for a class-based action/predicate registered via registerAction()/registerPredicate()RuleBook.clearRules()/reloadRules( source ): manually re-read an external rule source (a JSON/YAML file, a DB table) without restarting. RuleBox never watches a source for changes on its own - you decide when to reload. Registries and rule metrics are untouchedInlineRuleSource: a RuleSource backed by a literal array of rule-definition structs, no file or databaseRuleBookRegistry@rulebox: build named rulebooks from moduleSettings.rulebox.rulebooks config (a file path, inline rule definitions, or a full descriptor with actions/predicates/a DB source) and/or auto-discovered *.json/*.yaml files in a convention folder, instead of hand-wiring registerAction()/loadRules() per rulebook. getRuleBook( name ) always returns a fresh instance - never a shared/cached one - so it's safe to use from a singleton or across concurrent requests. reload() re-scans config/the convention folderruleBook( name ) application helper mixin, available in handlers/views/layoutsrulebook/rulebook:{name} WireBox injection DSL: rulebook injects the RuleBookRegistry singleton, rulebook:{name} injects a provider (.get()) for that declared rulebook so it stays safe to inject even into a singletonRuleBook can declare the facts it takes with fact( name ) in a new defineFacts() method (type(), required(), defaultValue(), description(), example(), values()), or from data with withFacts( struct ). getFactDefinitions() returns them for documentation or a UI. The declarations only describe the rulebook unless it calls enforceFacts(): then run() and dryRun() apply defaults and throw RuleBox.InvalidFactsException, listing every missing, mistyped or disallowed fact, before any rule runs. strictFacts() (or enforceFacts( strict = true )) also rejects undeclared facts. validateFacts( facts ) returns the same problems without running or throwing. Messages never include fact values. See the "Declaring Facts" guidewithDescription() and getDescription() on RuleBook and Rule. A RuleBook subclass without one falls back to its @description or @hint annotation, else its docblock. Rule definitions, rule-file envelopes and config declarations take a description key, dryRun() reports each rule's description, and the Rule Visualizer shows them on the dashboard, the chain view and the Dry Run screen{ description, facts, enforceFacts, strictFacts, rules }, instead of a bare array of rules, and declared rulebooks take description, facts, enforceFacts and strictFacts keys in configRuleBook.getRuleMetrics( name )/getRuleMetricsMap(): dashboard-ready, JSON-serializable per-rule execution metrics (evaluation counts by state, min/max/total/last duration, first/last run timestamps), accumulated across every run() call on the instance rather than resetting each run. resetMetrics() clears themRuleBook.getRuleMetrics() adds completed, failed, completionRate, errorRate, avgDurationMs and, once a rule fails, lastError ({ type, message, at, fingerprint }) and errors: the rule's distinct errors, each stored once with a count (the same error is never added twice), with its cause chain (up to 5), up to 10 BoxLang frames and the raw Java trace (cut to 4000 characters). RuleHealth::errorOf() and foldError() do the trimming and dedupmoduleSettings.rulebox.visualizer.enabled = true - RuleBox doesn't secure it on its own, so wrap it with cbSecurity (or your own auth) once enabled. Built on Bootstrap 5, Alpine.js, and Phosphor Icons via CDN. See the "Rule Visualizer" guideapiFacts JSON endpoint returns a rulebook's facts, and runDryRun answers 400 with the problemsFAILED rows with their error. Each failing rule's distinct errors open with their count, first and last seen, "Caused by" chain, BoxLang stack frames and raw Java stack traceIMetricsStore@rulebox: the visualizer's metrics persistence contract, with InMemoryMetricsStore (default, no I/O, nothing survives a restart) and SQLiteMetricsStore (opt-in, persists across restarts via the bx-sqlite module) implementations. Swap in your own via moduleSettings.rulebox.visualizer.metricsStoreIMetricsStore.queryAllRuleMetrics( rulebookName ) and queryRuleErrors( rulebookName, ruleName, limit ), and the same health fields on every store summary. A FAILED event carries errorType, errorMessage, errorFingerprint, errorCausedBy, errorStackTrace and errorRawStackTrace. SQLiteMetricsStore keeps each distinct error once in a new rulebox_errors table (an upsert counts repeats) and adds errorType/errorMessage/errorFingerprint columns to an existing rulebox_events table on startup. A custom store must implement the new methodsRuleEventBus@rulebox: fans out one event per rule evaluation to the configured metrics store and any live subscribers (the visualizer's SSE stream). A complete no-op while the visualizer is disabledAGENTS.md instructions for AI coding agentsRULE_STATES.REGISTERED now has the value REGISTERED instead of the legacy value NONE?.) used for Rule chain traversal instead of manual isNull() guardsRuleBook.run() now resets the rule status audit trail (getRuleStatusMap()/getRuleStatus()) at the start of every run, so a rule that isn't reached in the current run (e.g. a chain that stops earlier than before) no longer reports a stale status from a previous rungiven()/givenAll()'s overwrite argument was previously ignored (facts were always force-overwritten); it is now honored on both Rule and RuleBookRULE_STATES broken instance access under BoxLang (see #6, #7)
$
box install rulebox