New Rule Types
TL;DR - Add your own rule types
Rule types are Python classes, and you can add your own. A new rule type is declared like the built-in rules, fires inside the same transaction and logic phases, and is reused in every project that declares it. Allocation is built this way.
This is extensibility: extending the automation, not just one project. See Customize and Extend.
When to write a rule type
Write an event when a requirement in one project needs code. Write a rule type when you find yourself writing the same event in several projects, varying only in its tables and conditions. Typical candidates:
-
Audit copy - copy a row to an audit table when certain attributes change (LogicBank's
copy_row) -
Allocation - distribute an amount from a provider to a list of recipients (LogicBank's
Allocate) -
Find-or-create, clone, rollover - patterns your organization repeats, with your own conventions
The payoff is the same as for the built-in rules: the pattern is written and tested once, and each use is a one-line declaration that reads as the requirement does.
How it works
A rule type is a subclass of one of LogicBank's event rule classes. Creating an instance registers it with the rule engine, which then calls its execute(logic_row) method at that class's point in the logic phases:
| Subclass | Fires | Use it to |
|---|---|---|
EarlyRowEvent |
before the row's own rules | set values on the row, which the row's rules then see (Allocate uses this) |
RowEvent |
after the row's own rules | insert or update other rows, whose rules then fire (CopyRow uses this) |
CommitRowEvent |
after all rows' rules, before commit | act on the transaction's final state |
All three are in logic_bank.rule_type.row_event.
Write one: three parts
1. The rule class
This is LogicBank's own CopyRow (logic_bank/extensions/copy_row.py), slightly condensed:
from typing import Callable
from logic_bank.exec_row_logic.logic_row import LogicRow
from logic_bank.rule_type.row_event import RowEvent
class CopyRow(RowEvent):
"""
Copy copy_from -> copy_to (e.g., auditing).
"""
def __init__(self, copy_from: object, copy_to: object, copy_when: Callable = None):
if copy_to is None:
raise Exception("copy_to object is required")
self.copy_to = copy_to # your rule's own arguments
self.copy_when = copy_when
super(CopyRow, self).__init__(copy_from, None) # on_class, and no calling function: registers the rule
def __str__(self):
return f'Copy to: {self.copy_to.__name__}' # shown in the logic log
def execute(self, logic_row: LogicRow):
""" Called by the logic engine for each copy_from row in the transaction """
if not self.copy_when(logic_row):
return self
logic_row.log(f'BEGIN {str(self)}')
copy_to_logic_row = logic_row.new_logic_row(new_row_class=self.copy_to)
copy_to_logic_row.link(to_parent=logic_row)
copy_to_logic_row.set_same_named_attributes(logic_row)
copy_to_logic_row.session.add(copy_to_logic_row.row) # required under Flask
copy_to_logic_row.insert(reason="Copy " + copy_to_logic_row.name) # the new row's rules fire
return self
Points to note:
-
Arguments: the constructor takes your rule's arguments (
copy_to,copy_when), then calls the superclass with the class the rule is declared on. -
Conditions are your own arguments:
execute()replaces the standard event handling, so the built-incalling=andwhen_condition=do not apply. Take a condition as an argument (copy_when) and test it first. -
Use
logic_rowto change data:new_logic_row(),link(),insert()andupdate()run the rules of the rows you touch, so your rule chains with the others. See LogicRow. -
Do not set attributes of the triggering row in a
RowEvent: its rules have already run. Use anEarlyRowEventfor that. -
__str__is how the rule appears in the logic log.
2. Publish it
A class of static methods "publishes" your rules, so they are discovered with code completion, with their arguments documented. This is LogicBank's RuleExtension (logic_bank/extensions/rule_extensions.py), reduced to one rule:
class RuleExtension:
""" Invoke these functions to *define* rules """
@staticmethod
def copy_row(copy_from: object = None, copy_to: object = None, copy_when: Callable = None):
"""
Copies like-named attrs from copy_from (current row) to copy_to, e.g.,
RuleExtension.copy_row(copy_from=Employee, copy_to=EmployeeAudit,
copy_when=lambda logic_row: logic_row.are_attributes_changed([Employee.Salary, Employee.Title]))
"""
return CopyRow(copy_from=copy_from, copy_to=copy_to, copy_when=copy_when)
Name your own class for your organization (say AcmeRule), and keep the rule classes and the publishing class together in one module.
3. Declare it
Declare it in logic/logic_discovery/, beside the built-in rules:
RuleExtension.copy_row(copy_from=models.Employee, copy_to=models.EmployeeAudit,
copy_when=lambda logic_row: logic_row.are_attributes_changed([models.Employee.Salary, models.Employee.Title]))
Share it across projects
A rule type pays off when every project can use it. Either:
-
Package it (a pip package your projects install), or
-
Ship it in your organization's project template, so every new project has it: see Extensible Scaffold. Add a training file describing it to the same template (or the Manager's
system/project_context_engineering/), so the AI Assistant uses your rule when a requirement calls for it.
A larger example: Allocation
Allocate (logic_bank/extensions/allocate.py) is an EarlyRowEvent with custom arguments for the recipients and the allocation function. It inserts allocation rows whose own rules (sums, formulas) then fire. See Allocation, and in LogicBank, the Rule Extensibility wiki page and examples/nw/logic/extensibility/.
Ask your AI Assistant
This page is a summary, and a snapshot as of this writing. Ask your AI Assistant "how do I add my own rule type?": it reads the installed LogicBank, and can help you write, publish and test one for your pattern.