Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(mcp): rule tools with a mandatory preview (#3990)

scragnogec5cbd901434
diff --git a/app/models/assistant.rb b/app/models/assistant.rb
index f1eb763e92..3b00a04ad5 100644
--- a/app/models/assistant.rb
+++ b/app/models/assistant.rb
@@ -73,6 +73,12 @@ module Assistant
Function::CreateCategory,
Function::UpdateCategory,
Function::GetMerchants,
+ Function::GetRules,
+ Function::GetRuleOptions,
+ Function::PreviewRule,
+ Function::CreateRule,
+ Function::UpdateRule,
+ Function::ApplyRule,
Function::UpdateTransaction,
Function::CreateTransaction,
Function::DeleteTransaction,
diff --git a/app/models/assistant/function/apply_rule.rb b/app/models/assistant/function/apply_rule.rb
new file mode 100644
index 0000000000..529a7e339b
--- /dev/null
+++ b/app/models/assistant/function/apply_rule.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+# ApplyRule — activates a rule and applies it to existing transactions, like
+# the Apply button on the rule confirmation page. It needs the preview_token
+# from a preview of the rule as it is now, so a skipped, stale or edited
+# preview cannot be applied (see RuleSupport).
+class Assistant::Function::ApplyRule < Assistant::Function
+ include Assistant::Function::RuleSupport
+
+ class << self
+ def name
+ "apply_rule"
+ end
+
+ def description
+ <<~INSTRUCTIONS
+ Activates a rule and applies it to the transactions it matches now. Once
+ active, it also runs on every future sync. Undo future runs with
+ update_rule active: false; changes already made are not reverted.
+
+ preview_token must come from the latest preview_rule, create_rule or
+ update_rule for this rule (get_rules does not issue one). It expires
+ after #{Assistant::Function::RuleSupport::PREVIEW_TOKEN_TTL.inspect}. If the rule or its matches have
+ changed since, nothing is applied and a fresh preview, with a new
+ token, is returned.
+
+ By default transactions whose category, merchant, name or tags were set
+ by hand keep them. Pass override_locked: true to overwrite those too
+ (what the Settings > Rules Apply button does).
+
+ Runs in the background; check the result later with get_rules rule_id.
+ INSTRUCTIONS
+ end
+ end
+
+ def strict_mode?
+ false
+ end
+
+ def params_schema
+ build_schema(
+ required: %w[rule_id preview_token],
+ properties: {
+ rule_id: {
+ type: "string",
+ description: "Rule ID from get_rules or create_rule."
+ },
+ preview_token: {
+ type: "string",
+ description: "preview_token from the latest preview of this rule."
+ },
+ override_locked: {
+ type: "boolean",
+ description: "Also overwrite values the user set by hand (default false)."
+ }
+ }
+ )
+ end
+
+ def call(params = {})
+ rule = find_rule(params["rule_id"])
+ return error("not_found", "No rule with id '#{params["rule_id"]}'.") unless rule
+
+ if rule.actions.any? { |a| BLOCKED_ACTION_TYPES.include?(a.action_type) }
+ return error("ai_action", "This rule has an AI-backed action; apply it in Settings > Rules, which shows the cost estimate.")
+ end
+
+ token = read_preview_token(params["preview_token"], rule)
+ unless token
+ return error(
+ "preview_required",
+ "Preview this rule first (preview_rule with rule_id) and pass its preview_token. Tokens expire after #{PREVIEW_TOKEN_TTL.inspect}."
+ )
+ end
+
+ override_locked = ActiveModel::Type::Boolean.new.cast(params["override_locked"]) || false
+
+ current = nil
+ unchanged = false
+ rule.with_lock do
+ current = rule.affected_resource_count
+ unchanged = definition_digest(rule) == token["definition"] && current == token["match_count"]
+ rule.update!(active: true) if unchanged
+ end
+
+ unless unchanged
+ return error(
+ "preview_stale",
+ "The rule or its matches changed since that preview (it now matches #{current} transactions). Nothing was applied; check this preview and retry with its token.",
+ rule: serialize_rule(rule),
+ preview: preview(rule)
+ )
+ end
+
+ rule.apply_later(ignore_attribute_locks: override_locked)
+
+ {
+ success: true,
+ rule: serialize_rule(rule),
+ applied_to: current,
+ override_locked: override_locked,
+ message: "Rule activated and queued to apply to #{current} transactions. It will also run on future syncs."
+ }
+ end
+end
diff --git a/app/models/assistant/function/create_rule.rb b/app/models/assistant/function/create_rule.rb
new file mode 100644
index 0000000000..36b4ddb980
--- /dev/null
+++ b/app/models/assistant/function/create_rule.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+# CreateRule — saves a new transaction rule, always inactive. Nothing changes
+# until apply_rule activates it against a preview's match count, so a rule
+# cannot start rewriting transactions (or re-running on every sync) from a
+# single call.
+class Assistant::Function::CreateRule < Assistant::Function
+ include Assistant::Function::RuleSupport
+
+ class << self
+ def name
+ "create_rule"
+ end
+
+ def description
+ <<~INSTRUCTIONS
+ Saves a new transaction rule. The rule is always saved inactive: it does
+ not change any transaction until apply_rule activates it.
+
+ Build the definition from get_rule_options, and check it with
+ preview_rule first. Returns the saved rule and the same preview as
+ preview_rule; pass its preview_token to apply_rule after checking the sample.
+ INSTRUCTIONS
+ end
+ end
+
+ def strict_mode?
+ false
+ end
+
+ def params_schema
+ build_schema(
+ required: %w[conditions actions],
+ properties: {
+ name: {
+ type: "string",
+ description: "Optional rule name shown in Settings > Rules."
+ },
+ **definition_properties,
+ sample_size: {
+ type: "integer",
+ description: "Matches to list in the preview (default #{DEFAULT_SAMPLE_SIZE}, max #{MAX_SAMPLE_SIZE})."
+ }
+ }
+ )
+ end
+
+ def call(params = {})
+ return error("invalid_arguments", "conditions and actions are required.") unless params.key?("conditions") && params.key?("actions")
+
+ rule = family.rules.build(resource_type: "transaction", active: false, name: params["name"].to_s.strip.presence)
+ problems = assign_definition(rule, params.slice("conditions", "actions", "effective_date"))
+ problems = validate_rule(rule) if problems.empty?
+ return error("invalid_rule", "The rule was not saved.", problems: problems) if problems.any?
+
+ rule.save!
+
+ {
+ success: true,
+ rule: serialize_rule(rule),
+ preview: preview(rule, sample_size: resolved_sample_size(params)),
+ message: "Rule saved inactive. Check the preview, then call apply_rule with its preview_token to activate it."
+ }
+ end
+end
diff --git a/app/models/assistant/function/get_rule_options.rb b/app/models/assistant/function/get_rule_options.rb
new file mode 100644
index 0000000000..6bb3e97dec
--- /dev/null
+++ b/app/models/assistant/function/get_rule_options.rb
@@ -0,0 +1,94 @@
+# frozen_string_literal: true
+
+# GetRuleOptions — the condition types, operators and action types a rule can
+# use, so a client builds a valid definition for preview_rule / create_rule
+# without guessing. Id-valued fields point at the tool that lists the ids
+# rather than inlining every account, category, tag and merchant.
+class Assistant::Function::GetRuleOptions < Assistant::Function
+ include Assistant::Function::RuleSupport
+
+ class << self
+ def name
+ "get_rule_options"
+ end
+
+ def description
+ <<~INSTRUCTIONS
+ Returns what a transaction rule can contain: each condition type with its
+ operators and value format, and each action type with its value format.
+ Call this before preview_rule or create_rule.
+
+ Text conditions match case-insensitively with "like" (contains). Amount
+ conditions compare the absolute amount. Actions that call an AI model
+ (auto categorize, auto detect merchants) are not available here.
+ INSTRUCTIONS
+ end
+ end
+
+ def strict_mode?
+ false
+ end
+
+ def params_schema
+ build_schema
+ end
+
+ def call(_params = {})
+ rule = family.rules.build(resource_type: "transaction")
+
+ {
+ success: true,
+ conditions: rule.condition_filters.map { |filter| describe_filter(filter) } + [ compound_option ],
+ actions: rule.action_executors.reject { |e| BLOCKED_ACTION_TYPES.include?(e.key) }.map { |executor| describe_executor(executor) }
+ }
+ end
+
+ private
+ def describe_filter(filter)
+ {
+ condition_type: filter.key,
+ label: filter.label,
+ value_type: filter.type,
+ operators: filter_operators(filter).map { |label, value| { value: value, label: label } },
+ values: value_spec(filter.key)
+ }.compact
+ end
+
+ # The tag filter lists the generic select operators but only applies these.
+ def filter_operators(filter)
+ ops = filter.operators
+ filter.key == "transaction_tag" ? ops.select { |_, v| %w[= is_null].include?(v) } : ops
+ end
+
+ def compound_option
+ {
+ condition_type: "compound",
+ label: "Group of conditions",
+ operators: [ { value: "and", label: "all match" }, { value: "or", label: "any matches" } ],
+ values: "sub_conditions: an array of plain conditions (one level, no nesting)"
+ }
+ end
+
+ def describe_executor(executor)
+ {
+ action_type: executor.key,
+ label: executor.label,
+ value_type: executor.type,
+ values: executor.type == "function" ? nil : value_spec(executor.key)
+ }.compact
+ end
+
+ def value_spec(key)
+ case key
+ when *ACCOUNT_KEYS then "account id from get_accounts"
+ when *CATEGORY_KEYS then "category id from get_categories"
+ when "transaction_tag" then "tag id from get_tags"
+ when "set_transaction_tags" then "array of tag ids from get_tags"
+ when *MERCHANT_KEYS then "merchant id from get_merchants"
+ when "transaction_type", "set_investment_activity_label" then allowed_values(key)
+ when "transaction_amount" then "number (absolute amount, in the account's currency)"
+ when "set_transaction_name" then "the new transaction name"
+ else "text"
+ end
+ end
+end
diff --git a/app/models/assistant/function/get_rules.rb b/app/models/assistant/function/get_rules.rb
new file mode 100644
index 0000000000..a43a0f154a
--- /dev/null
+++ b/app/models/assistant/function/get_rules.rb
@@ -0,0 +1,122 @@
+# frozen_string_literal: true
+
+# GetRules — lists the family's transaction rules in readable form: each
+# condition and action with ids resolved to names, whether the rule is active,
+# and its latest run.
+class Assistant::Function::GetRules < Assistant::Function
+ include Assistant::Function::RuleSupport
+
+ class << self
+ def default_page_size
+ 50
+ end
+
+ def name
+ "get_rules"
+ end
+
+ def description
+ <<~INSTRUCTIONS
+ Lists the family's transaction rules: conditions, actions (with account,
+ category, tag and merchant names), whether each rule is active, its
+ effective_date, and its latest run.
+
+ Active rules run again on every sync. Pass rule_id for a single rule,
+ which also includes how many transactions it currently matches.
+
+ Use search to check whether a rule already exists: it matches the rule
+ name, condition values (e.g. a payee in a "name contains" condition),
+ action values, and the names of categories the rule sets.
+
+ Results are paginated (page_size defaults to #{default_page_size}); the
+ response includes total_results, page, page_size and total_pages.
+ INSTRUCTIONS
+ end
+ end
+
+ def strict_mode?
+ false
+ end
+
+ def params_schema
+ build_schema(
+ properties: {
+ rule_id: {
+ type: "string",
+ description: "Optional. Return only this rule, with its current match count."
+ },
+ active: {
+ type: "boolean",
+ description: "Optional. true for active rules only, false for inactive only."
+ },
+ search: {
+ type: "string",
+ description: "Optional. Case-insensitive text to find in the rule name, condition and action values, or the name of a category it sets."
+ },
+ page: {
+ type: "integer",
+ minimum: 1,
+ description: "Page number (defaults to 1)"
+ },
+ page_size: {
+ type: "integer",
+ minimum: 1,
+ maximum: MAX_PAGE_SIZE,
+ description: "Results per page (defaults to #{self.class.default_page_size})"
+ }
+ }
+ )
+ end
+
+ def call(params = {})
+ if params["rule_id"].present?
+ rule = find_rule(params["rule_id"])
+ return error("not_found", "No rule with id '#{params["rule_id"]}'.") unless rule
+
+ return { success: true, rule: serialize_rule(rule, include_last_run: true).merge(match_count: rule.affected_resource_count) }
+ end
+
+ rules = family.rules
+ rules = rules.where(active: ActiveModel::Type::Boolean.new.cast(params["active"])) unless params["active"].nil?
+ rules = matching_search(rules, params["search"]) if params["search"].present?
+
+ page_size = resolved_page_size(params)
+ pagy = Pagy.new(count: rules.count, page: resolved_page(params), limit: page_size)
+ page = rules.includes(:actions, conditions: :sub_conditions)
+ .order(Arel.sql("rules.name ASC NULLS LAST"), :created_at, :id)
+ .offset(pagy.offset).limit(pagy.limit)
+
+ {
+ success: true,
+ rules: page.map { |rule| serialize_rule(rule, include_last_run: true) },
+ total_results: pagy.count,
+ page: pagy.page,
+ page_size: page_size,
+ total_pages: pagy.pages
+ }
+ end
+
+ private
+ # Rules are often unnamed, so the search also looks inside conditions
+ # (including grouped ones), action values, and the categories they set.
+ def matching_search(rules, search)
+ pattern = "%#{ActiveRecord::Base.sanitize_sql_like(search.to_s.strip)}%"
+
+ rules.where(<<~SQL.squish, pattern: pattern, family_id: family.id)
+ rules.name ILIKE :pattern
+ OR EXISTS (
+ SELECT 1 FROM rule_conditions c
+ LEFT JOIN rule_conditions p ON p.id = c.parent_id
+ WHERE COALESCE(c.rule_id, p.rule_id) = rules.id AND c.value ILIKE :pattern
+ )
+ OR EXISTS (
+ SELECT 1 FROM rule_actions a
+ WHERE a.rule_id = rules.id
+ AND (
+ a.value ILIKE :pattern
+ OR a.value IN (SELECT id::text FROM categories WHERE family_id = :family_id AND name ILIKE :pattern)
+ )
+ )
+ SQL
+ end
+end
diff --git a/app/models/assistant/function/preview_rule.rb b/app/models/assistant/function/preview_rule.rb
new file mode 100644
index 0000000000..c582278fb0
--- /dev/null
+++ b/app/models/assistant/function/preview_rule.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+# PreviewRule — shows what a rule matches without changing anything, for a
+# saved rule or an unsaved definition. For a saved rule it also issues the
+# preview_token apply_rule requires.
+class Assistant::Function::PreviewRule < Assistant::Function
+ include Assistant::Function::RuleSupport
+
+ class << self
+ def name
+ "preview_rule"
+ end
+
+ def description
+ <<~INSTRUCTIONS
+ Shows which transactions a rule matches, without changing anything.
+ Pass either rule_id (a saved rule) or an unsaved definition (conditions,
+ actions, optional effective_date); see get_rule_options for valid values.
+
+ Returns match_count (every matching transaction in the family, which is
+ what the rule would touch), a sample of the most recent matches in
+ accounts you can see, with their current category and merchant, and the
+ actions in readable form. Check the sample before create_rule or
+ apply_rule: a loose condition (e.g. "greater than" instead of "equal to")
+ rewrites far more transactions than intended.
+
+ For a saved rule it also returns preview_token, which apply_rule needs.
+ No token is issued when no matches are shown: with sample_size 0, or
+ when every match is in an account you cannot see.
+ INSTRUCTIONS
+ end
+ end
+
+ def strict_mode?
+ false
+ end
+
+ def params_schema
+ build_schema(
+ properties: {
+ rule_id: {
+ type: "string",
+ description: "A saved rule from get_rules. Omit when passing a definition."
+ },
+ **definition_properties,
+ sample_size: {
+ type: "integer",
+ description: "Matches to list, most recent first (default #{DEFAULT_SAMPLE_SIZE}, max #{MAX_SAMPLE_SIZE})."
+ }
+ }
+ )
+ end
+
+ def call(params = {})
+ definition_given = params.key?("conditions") || params.key?("actions")
+
+ if params["rule_id"].present?
+ return error("invalid_arguments", "Pass either rule_id or a definition, not both.") if definition_given
+
+ rule = find_rule(params["rule_id"])
+ return error("not_found", "No rule with id '#{params["rule_id"]}'.") unless rule
+ else
+ return error("invalid_arguments", "Pass rule_id or a definition with conditions and actions.") unless definition_given
+
+ rule = family.rules.build(resource_type: "transaction", active: false)
+ problems = assign_definition(rule, params.slice("conditions", "actions", "effective_date"))
+ problems = validate_rule(rule) if problems.empty?
+ return error("invalid_rule", "The rule definition is not valid.", problems: problems) if problems.any?
+ end
+
+ { success: true, rule: serialize_rule(rule), preview: preview(rule, sample_size: resolved_sample_size(params)) }
+ end
+end
diff --git a/app/models/assistant/function/rule_support.rb b/app/models/assistant/function/rule_support.rb
new file mode 100644
index 0000000000..fc16f24607
--- /dev/null
+++ b/app/models/assistant/function/rule_support.rb
@@ -0,0 +1,463 @@
+# frozen_string_literal: true
+
+# Shared plumbing for the rule tools (get_rules, get_rule_options,
+# preview_rule, create_rule, update_rule, apply_rule).
+#
+# A rule rewrites every matching transaction, and an active rule runs again on
+# every family sync. So the write tools never activate a rule: create_rule and
+# update_rule save it inactive, and only apply_rule activates it. apply_rule
+# needs a preview_token, which only a preview that listed matching
+# transactions issues (preview_rule, create_rule, update_rule; never
+# get_rules). The token is bound to the rule's definition and match count, so
+# it can't be skipped, reused after an edit, or applied to changed matches.
+#
+# Allowed values are resolved here from the requesting user rather than from
+# the registry's own option lists: those read Current.user, which is nil on the
+# assistant and MCP paths.
+module Assistant::Function::RuleSupport
+ # AI-backed actions cost money per transaction; the web UI shows a cost
+ # estimate before applying them, which this surface cannot do yet.
+ BLOCKED_ACTION_TYPES = %w[auto_categorize auto_detect_merchants].freeze
+
+ # Ids are resolved to names by these lookups, keyed by condition or action type.
+ ACCOUNT_KEYS = %w[transaction_account set_as_transfer_or_payment].freeze
+ CATEGORY_KEYS = %w[transaction_category set_transaction_category].freeze
+ TAG_KEYS = %w[transaction_tag set_transaction_tags].freeze
+ MERCHANT_KEYS = %w[transaction_merchant set_transaction_merchant].freeze
+
+ DEFAULT_SAMPLE_SIZE = 10
+ MAX_SAMPLE_SIZE = 25
+
+ PREVIEW_TOKEN_TTL = 30.minutes
+
+ # JSON schema fragments shared by preview_rule, create_rule and update_rule.
+ def condition_schema
+ {
+ type: "object",
+ properties: {
+ condition_type: {
+ type: "string",
+ description: "A condition key from get_rule_options, or \"compound\" to group sub_conditions."
+ },
+ operator: {
+ type: "string",
+ description: "An operator value from get_rule_options for this condition. For compound: \"and\" or \"or\"."
+ },
+ value: {
+ type: "string",
+ description: "Text, number, or an id (account, category, tag, merchant) depending on the condition. Omit for is_null / is_not_null and compound."
+ },
+ sub_conditions: {
+ type: "array",
+ description: "Only for compound conditions: one level of plain conditions (no nesting).",
+ items: { type: "object" }
+ }
+ },
+ required: %w[condition_type operator]
+ }
+ end
+
+ def action_schema
+ {
+ type: "object",
+ properties: {
+ action_type: {
+ type: "string",
+ description: "An action key from get_rule_options."
+ },
+ value: {
+ description: "Category/merchant/account id, activity label or new name depending on the action; an array of tag ids for set_transaction_tags. Omit for actions without a value.",
+ anyOf: [ { type: "string" }, { type: "array", items: { type: "string" } } ]
+ }
+ },
+ required: %w[action_type]
+ }
+ end
+
+ def definition_properties
+ {
+ conditions: {
+ type: "array",
+ description: "All conditions must match (AND). Use a compound condition with operator \"or\" for alternatives.",
+ items: condition_schema
+ },
+ actions: {
+ type: "array",
+ description: "At least one action. Each action type may appear once.",
+ items: action_schema
+ },
+ effective_date: {
+ type: "string",
+ description: "Optional YYYY-MM-DD. The rule only touches transactions on or after this date."
+ }
+ }
+ end
+
+ private
+ # Finds a rule in the user's family. Returns nil for unknown or foreign ids.
+ def find_rule(id)
+ return nil unless valid_uuid?(id)
+
+ family.rules.includes(conditions: :sub_conditions).find_by(id: id)
+ end
+
+ # Replaces the rule's conditions and actions with the given definition and
+ # returns a list of problems. The rule is not saved. A key that is absent
+ # leaves that part of the rule unchanged.
+ def assign_definition(rule, params)
+ problems = []
+
+ if params.key?("effective_date")
+ raw = params["effective_date"]
+ if raw.blank?
+ rule.effective_date = nil
+ else
+ begin
+ rule.effective_date = Date.iso8601(raw.to_s)
+ rescue Date::Error
+ problems << "effective_date must be a YYYY-MM-DD date."
+ end
+ end
+ end
+
+ if params.key?("conditions")
+ conditions = params["conditions"]
+ if conditions.is_a?(Array)
+ rule.conditions.each(&:mark_for_destruction)
+ conditions.each_with_index do |condition, index|
+ problems.concat(build_condition(rule, rule.conditions, condition, "conditions[#{index}]", allow_compound: true))
+ end
+ else
+ problems << "conditions must be an array."
+ end
+ end
+
+ if params.key?("actions")
+ actions = params["actions"]
+ if actions.is_a?(Array)
+ rule.actions.each(&:mark_for_destruction)
+ actions.each_with_index do |action, index|
+ problems.concat(build_action(rule, action, "actions[#{index}]"))
+ end
+ else
+ problems << "actions must be an array."
+ end
+ end
+
+ problems
+ end
+
+ def build_condition(rule, collection, attrs, path, allow_compound:)
+ return [ "#{path} must be an object." ] unless attrs.is_a?(Hash)
+
+ type = attrs["condition_type"].to_s
+ operator = attrs["operator"].to_s
+
+ if type == "compound"
+ return [ "#{path}: compound conditions cannot be nested." ] unless allow_compound
+ return [ "#{path}: compound operator must be \"and\" or \"or\"." ] unless %w[and or].include?(operator)
+
+ subs = attrs["sub_conditions"]
+ return [ "#{path}: compound conditions need at least one sub_condition." ] unless subs.is_a?(Array) && subs.any?
+
+ compound = collection.build(condition_type: "compound", operator: operator)
+ return subs.each_with_index.flat_map do |sub, index|
+ build_condition(rule, compound.sub_conditions, sub, "#{path}.sub_conditions[#{index}]", allow_compound: false)
+ end
+ end
+
+ filter = rule.condition_filters.find { |f| f.key == type }
+ return [ "#{path}: unknown condition_type '#{type}'. See get_rule_options." ] unless filter
+
+ operators = filter.operators.map(&:last)
+ return [ "#{path}: operator '#{operator}' is not valid for #{type}. Valid: #{operators.join(", ")}." ] unless operators.include?(operator)
+
+ value = attrs["value"]
+ if Rule::ConditionFilter::VALUELESS_OPERATORS.include?(operator)
+ value = nil
+ else
+ value = value.to_s.strip
+ return [ "#{path}: value is required for operator '#{operator}'." ] if value.blank?
+ return [ "#{path}: value must be a number." ] if filter.type == "number" && !numeric?(value)
+
+ allowed = allowed_values(type)
+ return [ "#{path}: '#{value}' is not a valid value for #{type}. #{value_hint(type)}" ] if allowed && !allowed.include?(value)
+ end
+
+ collection.build(condition_type: type, operator: operator, value: value)
+ []
+ end
+
+ def build_action(rule, attrs, path)
+ return [ "#{path} must be an object." ] unless attrs.is_a?(Hash)
+
+ type = attrs["action_type"].to_s
+ return [ "#{path}: #{type} calls an AI model and is not available here; add it in Settings > Rules." ] if BLOCKED_ACTION_TYPES.include?(type)
+
+ executor = rule.action_executors.find { |e| e.key == type }
+ return [ "#{path}: unknown action_type '#{type}'. See get_rule_options." ] unless executor
+
+ value = attrs["value"]
+ case executor.type
+ when "function"
+ value = nil
+ when "multi_select"
+ values = Array(value).map { |v| v.to_s.strip }.compact_blank.uniq
+ return [ "#{path}: value must list at least one id for #{type}." ] if values.empty?
+
+ invalid = values - allowed_values(type)
+ return [ "#{path}: #{invalid.join(", ")} not valid for #{type}. #{value_hint(type)}" ] if invalid.any?
+
+ value = values
+ else
+ return [ "#{path}: value must be a single string for #{type}." ] if value.is_a?(Array)
+
+ value = value.to_s.strip
+ return [ "#{path}: value is required for #{type}." ] if value.blank?
+
+ allowed = allowed_values(type)
+ return [ "#{path}: '#{value}' is not a valid value for #{type}. #{value_hint(type)}" ] if allowed && !allowed.include?(value)
+ end
+
+ rule.actions.build(action_type: type, value: value)
+ []
+ end
+
+ # Runs model validations, then builds (without running) each condition's
+ # query, which surfaces operators a filter lists but cannot apply (e.g. tag
+ # "not equal to"). Returns a list of problems.
+ def validate_rule(rule)
+ return rule.errors.full_messages unless rule.valid?
+
+ scope = rule.registry.resource_scope
+ rule.conditions.reject(&:marked_for_destruction?).each { |c| c.apply(c.prepare(scope)) }
+ []
+ rescue Rule::ConditionFilter::UnsupportedOperatorError => e
+ [ e.message ]
+ end
+
+ # nil means free text (no fixed list of values).
+ def allowed_values(key)
+ case key
+ when *ACCOUNT_KEYS then accessible_accounts.pluck(:id).map(&:to_s)
+ when *CATEGORY_KEYS then family.categories.pluck(:id).map(&:to_s)
+ when *TAG_KEYS then family.tags.pluck(:id).map(&:to_s)
+ when "transaction_merchant" then family.available_merchants_for(user).pluck(:id).map(&:to_s)
+ when "set_transaction_merchant" then family.merchants.pluck(:id).map(&:to_s)
+ when "transaction_type" then %w[income expense transfer]
+ when "set_investment_activity_label" then Transaction::ACTIVITY_LABELS
+ end
+ end
+
+ def value_hint(key)
+ case key
+ when *ACCOUNT_KEYS then "Use an account id from get_accounts."
+ when *CATEGORY_KEYS then "Use a category id from get_categories."
+ when *TAG_KEYS then "Use tag ids from get_tags."
+ when *MERCHANT_KEYS then "Use a merchant id from get_merchants."
+ else "Valid: #{Array(allowed_values(key)).join(", ")}."
+ end
+ end
+
+ def numeric?(value)
+ BigDecimal(value)
+ true
+ rescue ArgumentError
+ false
+ end
+
+ def accessible_accounts
+ family.accounts.accessible_by(user)
+ end
+
+ # Rule in readable form: ids are returned alongside their names.
+ def serialize_rule(rule, include_last_run: false)
+ data = {
+ id: rule.id,
+ name: rule.name,
+ active: rule.active,
+ effective_date: rule.effective_date&.iso8601,
+ conditions: rule.conditions.reject(&:marked_for_destruction?).select { |c| c.parent_id.nil? }.map { |c| serialize_condition(rule, c) },
+ actions: rule.actions.reject(&:marked_for_destruction?).map { |a| serialize_action(rule, a) },
+ updated_at: rule.updated_at&.iso8601
+ }
+
+ if include_last_run
+ run = rule.rule_runs.recent.first
+ data[:last_run] = run && {
+ executed_at: run.executed_at.iso8601,
+ status: run.status,
+ execution_type: run.execution_type,
+ transactions_queued: run.transactions_queued,
+ transactions_modified: run.transactions_modified
+ }
+ end
+
+ data
+ end
+
+ def serialize_condition(rule, condition)
+ if condition.compound?
+ {
+ condition_type: "compound",
+ operator: condition.operator,
+ sub_conditions: condition.sub_conditions.map { |sub| serialize_condition(rule, sub) }
+ }
+ else
+ {
+ condition_type: condition.condition_type,
+ operator: condition.operator,
+ value: condition.value,
+ value_name: value_name(condition.condition_type, condition.value)
+ }.compact
+ end
+ end
+
+ def serialize_action(rule, action)
+ values = action_values(action)
+ names = values.map { |v| value_name(action.action_type, v) }.compact
+
+ {
+ action_type: action.action_type,
+ value: action.value,
+ value_name: names.any? ? names.join(", ") : nil
+ }.compact
+ end
+
+ def action_values(action)
+ return [] if action.value.blank?
+
+ action.action_type.in?(TAG_KEYS) ? action.value.to_s.split(",") : [ action.value.to_s ]
+ end
+
+ # Name for an id-valued condition or action, or nil for free text. An
+ # account the user cannot see is reported without its name.
+ def value_name(key, value)
+ return nil if value.blank?
+
+ names = name_lookup(key)
+ return nil unless names
+
+ names.fetch(value.to_s) { key.in?(ACCOUNT_KEYS) ? "(account not shared with you)" : "(deleted)" }
+ end
+
+ def name_lookup(key)
+ @name_lookups ||= {}
+ group =
+ case key
+ when *ACCOUNT_KEYS then :accounts
+ when *CATEGORY_KEYS then :categories
+ when *TAG_KEYS then :tags
+ when *MERCHANT_KEYS then :merchants
+ end
+ return nil unless group
+
+ @name_lookups[group] ||=
+ case group
+ when :accounts then accessible_accounts.pluck(:id, :name).to_h { |id, name| [ id.to_s, name ] }
+ when :categories then family.categories.includes(:parent).to_h { |c| [ c.id.to_s, c.name_with_parent ] }
+ when :tags then family.tags.pluck(:id, :name).to_h { |id, name| [ id.to_s, name ] }
+ when :merchants then family.available_merchants_for(user).pluck(:id, :name).to_h { |id, name| [ id.to_s, name ] }
+ end
+ end
+
+ # What applying the rule would touch. The count covers the whole family, as
+ # the rule does; the sample only lists transactions in accounts the user
+ # can see.
+ def preview(rule, sample_size: DEFAULT_SAMPLE_SIZE)
+ scope = rule.matching_resources
+ match_count = scope.count
+
+ visible = scope.where(entries: { account_id: accessible_accounts.select(:id) })
+ sample = visible
+ .includes(:category, :merchant, entry: :account)
+ .order("entries.date DESC, entries.id DESC")
+ .limit(sample_size)
+ .to_a
+
+ {
+ match_count: match_count,
+ visible_match_count: visible.count,
+ sample: sample.map { |txn| serialize_sample(txn) },
+ actions: rule.actions.reject(&:marked_for_destruction?).map { |a| describe_action(rule, a) },
+ preview_token: preview_token(rule, match_count, shown: sample.size)
+ }.compact
+ end
+
+ # Issued for a saved rule when the preview listed matches: none for a zero
+ # sample_size, or when every match is in an account the user can't see.
+ # A rule matching nothing gets one, so a rule meant for future
+ # transactions can be activated. Signed, and bound to the user, the rule's
+ # definition and the match count.
+ def preview_token(rule, match_count, shown:)
+ return nil unless rule.persisted? && rule.changes.empty?
+ return nil if match_count.positive? && shown.zero?
+
+ preview_verifier.generate(
+ { "rule_id" => rule.id, "user_id" => user.id, "definition" => definition_digest(rule), "match_count" => match_count },
+ purpose: :apply_rule, expires_in: PREVIEW_TOKEN_TTL
+ )
+ end
+
+ # The token's payload, or nil when it is missing, forged, expired, or
+ # issued to another user or rule.
+ def read_preview_token(token, rule)
+ payload = preview_verifier.verified(token.to_s, purpose: :apply_rule) if token.present?
+ return nil unless payload.is_a?(Hash)
+ return nil unless payload["rule_id"] == rule.id && payload["user_id"] == user.id
+
+ payload
+ end
+
+ # What the rule would do, independent of timestamps and display names.
+ def definition_digest(rule)
+ definition = {
+ effective_date: rule.effective_date&.iso8601,
+ conditions: rule.conditions.reject(&:marked_for_destruction?).select { |c| c.parent_id.nil? }
+ .map { |c| digest_condition(c) }.sort_by(&:to_json),
+ actions: rule.actions.reject(&:marked_for_destruction?).map { |a| [ a.action_type, a.value.to_s ] }.sort
+ }
+ Digest::SHA256.hexdigest(definition.to_json)
+ end
+
+ def digest_condition(condition)
+ return [ condition.operator, condition.sub_conditions.map { |sub| digest_condition(sub) }.sort_by(&:to_json) ] if condition.compound?
+
+ [ condition.condition_type, condition.operator, condition.value.to_s ]
+ end
+
+ def preview_verifier
+ Rails.application.message_verifier("assistant/rule_preview")
+ end
+
+ def serialize_sample(txn)
+ entry = txn.entry
+ {
+ id: txn.id,
+ date: entry.date.iso8601,
+ account: entry.account.name,
+ name: entry.name,
+ amount: entry.amount.to_s,
+ currency: entry.currency,
+ category: txn.category&.name_with_parent,
+ merchant: txn.merchant&.name,
+ excluded: entry.excluded
+ }
+ end
+
+ def describe_action(rule, action)
+ serialize_action(rule, action).merge(label: action.executor.label)
+ rescue Rule::Registry::UnsupportedActionError
+ serialize_action(rule, action)
+ end
+
+ def resolved_sample_size(params)
+ return DEFAULT_SAMPLE_SIZE if params["sample_size"].blank?
+
+ params["sample_size"].to_i.clamp(0, MAX_SAMPLE_SIZE)
+ end
+
+ def error(key, message, **extra)
+ { success: false, error: key, message: message }.merge(extra)
+ end
+end
diff --git a/app/models/assistant/function/update_rule.rb b/app/models/assistant/function/update_rule.rb
new file mode 100644
index 0000000000..67cf4aed73
--- /dev/null
+++ b/app/models/assistant/function/update_rule.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+# UpdateRule — renames a rule, replaces its definition, or deactivates it.
+# Changing what an active rule matches or does deactivates it, so the new
+# version only runs after apply_rule against a fresh preview.
+class Assistant::Function::UpdateRule < Assistant::Function
+ include Assistant::Function::RuleSupport
+
+ class << self
+ def name
+ "update_rule"
+ end
+
+ def description
+ <<~INSTRUCTIONS
+ Updates a transaction rule from get_rules. Any of:
+ - name: rename it (an active rule stays active).
+ - conditions / actions: replace that whole list (send every item, not
+ just the changed one). effective_date: change it, or "" to clear it.
+ Any of these deactivates the rule; call apply_rule after checking the
+ returned preview.
+ - active: false to stop the rule running on sync. It cannot activate a
+ rule; use apply_rule for that.
+
+ Rules with AI-backed actions (auto categorize, auto detect merchants)
+ must be edited in Settings > Rules.
+ INSTRUCTIONS
+ end
+ end
+
+ def strict_mode?
+ false
+ end
+
+ def params_schema
+ build_schema(
+ required: %w[rule_id],
+ properties: {
+ rule_id: {
+ type: "string",
+ description: "Rule ID from get_rules."
+ },
+ name: {
+ type: "string",
+ description: "New name. Pass \"\" to clear it."
+ },
+ **definition_properties,
+ active: {
+ type: "boolean",
+ description: "Only false is accepted: deactivates the rule."
+ },
+ sample_size: {
+ type: "integer",
+ description: "Matches to list in the preview (default #{DEFAULT_SAMPLE_SIZE}, max #{MAX_SAMPLE_SIZE})."
+ }
+ }
+ )
+ end
+
+ def call(params = {})
+ rule = find_rule(params["rule_id"])
+ return error("not_found", "No rule with id '#{params["rule_id"]}'.") unless rule
+
+ active = params.key?("active") ? ActiveModel::Type::Boolean.new.cast(params["active"]) : nil
+ return error("cannot_activate", "update_rule cannot activate a rule. Use apply_rule with a preview_token from a preview.") if active == true
+
+ definition = params.slice("conditions", "actions", "effective_date")
+ return error("no_changes", "Provide name, conditions, actions, effective_date or active: false.") if definition.empty? && !params.key?("name") && active.nil?
+
+ if rule.actions.any? { |a| BLOCKED_ACTION_TYPES.include?(a.action_type) } && definition.any?
+ return error("ai_action", "This rule has an AI-backed action; edit it in Settings > Rules.")
+ end
+
+ was_active = rule.active
+ rule.name = params["name"].to_s.strip.presence if params.key?("name")
+ rule.active = false if active == false || definition.any?
+
+ problems = assign_definition(rule, definition)
+ problems = validate_rule(rule) if problems.empty?
+ return error("invalid_rule", "The rule was not updated.", problems: problems) if problems.any?
+
+ rule.save!
+ rule = find_rule(rule.id)
+
+ message =
+ if was_active && !rule.active
+ "Rule updated and deactivated. Check the preview, then call apply_rule with its preview_token to activate it again."
+ else
+ "Rule updated."
+ end
+
+ {
+ success: true,
+ rule: serialize_rule(rule),
+ preview: preview(rule, sample_size: resolved_sample_size(params)),
+ message: message
+ }
+ end
+end
diff --git a/app/models/rule.rb b/app/models/rule.rb
index f5687d0017..0da970060c 100644
--- a/app/models/rule.rb
+++ b/app/models/rule.rb
@@ -105,6 +105,12 @@ class Rule < ApplicationRecord
matching_scope.where(id: transaction.id).exists?
end
+ # The transactions this rule currently matches, as a relation (e.g. for the
+ # assistant's rule preview, which counts and samples them).
+ def matching_resources
+ matching_resources_scope
+ end
+
# Creates a categorization rule for the Quick Categorize Wizard.
# Returns the saved rule, or nil if a duplicate or invalid rule already exists.
def self.create_from_grouping(family, grouping_key, category, transaction_type: nil)
diff --git a/docs/hosting/mcp.md b/docs/hosting/mcp.md
index 35483795aa..3c9c23ed82 100644
--- a/docs/hosting/mcp.md
+++ b/docs/hosting/mcp.md
@@ -151,6 +151,10 @@ At the time of writing, `tools/list` includes:
| `create_category` / `update_category` | Manage categories |
| `update_transaction` | Edit a transaction's metadata (name, notes, category, merchant, tags) |
| `update_budget` | Update budget allocations for a month |
+| `get_rules` / `get_rule_options` | Transaction rules in readable form (ids resolved to names, latest run; paginated, with a text search), and the condition and action types a rule can use |
+| `preview_rule` | Match count and a sample of matching transactions for a saved rule or an unsaved definition, without changing anything |
+| `create_rule` / `update_rule` | Save a rule definition. Rules are always saved inactive, and changing an active rule's conditions or actions deactivates it. AI-backed actions are not available |
+| `apply_rule` | Activate a rule and apply it. Requires the `preview_token` from `preview_rule`, `create_rule` or `update_rule` (never `get_rules`; it expires after 30 minutes) and refuses if the rule or its matches have changed; keeps hand-set values unless `override_locked: true` |
| `import_bank_statement` | Import bank statement data |
| `search_family_files` | Search documents uploaded through the import flow. Note this is the vector-store document index, not the Statement Vault — statements archived via `upload_account_statement` are not searchable through it |
diff --git a/test/models/assistant/function/apply_rule_test.rb b/test/models/assistant/function/apply_rule_test.rb
new file mode 100644
index 0000000000..7fa1ae5606
--- /dev/null
+++ b/test/models/assistant/function/apply_rule_test.rb
@@ -0,0 +1,158 @@
+require "test_helper"
+
+class Assistant::Function::ApplyRuleTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+ include ActiveJob::TestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @family = @user.family
+ @fn = Assistant::Function::ApplyRule.new(@user)
+ @category = categories(:food_and_drink)
+
+ @rule = @family.rules.create!(
+ resource_type: "transaction",
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "zxq coffee" } ],
+ actions_attributes: [ { action_type: "set_transaction_category", value: @category.id } ]
+ )
+ end
+
+ test "activates and applies the rule with a token from its preview" do
+ entry = create_transaction(name: "ZXQ Coffee Shop")
+
+ result = perform_enqueued_jobs(only: RuleJob) do
+ @fn.call("rule_id" => @rule.id, "preview_token" => preview_token)
+ end
+
+ assert result[:success], result.inspect
+ assert_equal 1, result[:applied_to]
+ assert @rule.reload.active
+ assert_equal @category, entry.entryable.reload.category
+ assert_equal 1, @rule.rule_runs.count
+ end
+
+ test "the match count from get_rules alone cannot apply a rule" do
+ create_transaction(name: "ZXQ Coffee Shop")
+ match_count = Assistant::Function::GetRules.new(@user).call("rule_id" => @rule.id)[:rule][:match_count]
+ assert_equal 1, match_count
+
+ [ nil, "", match_count.to_s, "forged--token" ].each do |token|
+ assert_no_enqueued_jobs only: RuleJob do
+ assert_equal "preview_required", @fn.call("rule_id" => @rule.id, "preview_token" => token)[:error]
+ end
+ end
+ assert_not @rule.reload.active
+ end
+
+ test "a preview without sample transactions issues no token" do
+ create_transaction(name: "ZXQ Coffee Shop")
+
+ preview = Assistant::Function::PreviewRule.new(@user).call("rule_id" => @rule.id, "sample_size" => 0)[:preview]
+
+ assert_equal 1, preview[:match_count]
+ assert_nil preview[:preview_token]
+ end
+
+ test "a preview whose matches are all in accounts the user can't see issues no token" do
+ create_transaction(name: "ZXQ Coffee Shop", account: accounts(:other_asset))
+
+ preview = Assistant::Function::PreviewRule.new(users(:family_member)).call("rule_id" => @rule.id)[:preview]
+
+ assert_equal 1, preview[:match_count]
+ assert_empty preview[:sample]
+ assert_nil preview[:preview_token]
+ end
+
+ test "a rule matching nothing can be activated for future transactions" do
+ preview = Assistant::Function::PreviewRule.new(@user).call("rule_id" => @rule.id)[:preview]
+ assert_equal 0, preview[:match_count]
+
+ result = @fn.call("rule_id" => @rule.id, "preview_token" => preview[:preview_token])
+
+ assert result[:success], result.inspect
+ assert @rule.reload.active
+ end
+
+ test "refuses a token once the matches change, and returns a fresh one" do
+ create_transaction(name: "ZXQ Coffee Shop")
+ token = preview_token
+ create_transaction(name: "ZXQ Coffee Bar")
+
+ result = nil
+ assert_no_enqueued_jobs(only: RuleJob) { result = @fn.call("rule_id" => @rule.id, "preview_token" => token) }
+
+ assert_equal "preview_stale", result[:error]
+ assert_equal 2, result[:preview][:match_count]
+ assert_not @rule.reload.active
+
+ assert @fn.call("rule_id" => @rule.id, "preview_token" => result[:preview][:preview_token])[:success]
+ end
+
+ test "refuses a token once the rule is edited, even with the same match count" do
+ create_transaction(name: "ZXQ Coffee Shop")
+ token = preview_token
+ Assistant::Function::UpdateRule.new(@user).call(
+ "rule_id" => @rule.id,
+ "actions" => [ { "action_type" => "set_transaction_category", "value" => categories(:income).id } ]
+ )
+
+ assert_equal "preview_stale", @fn.call("rule_id" => @rule.id, "preview_token" => token)[:error]
+ assert_not @rule.reload.active
+ end
+
+ test "refuses an expired token, another rule's token and another user's token" do
+ create_transaction(name: "ZXQ Coffee Shop")
+ token = preview_token
+
+ other_rule = @family.rules.create!(
+ resource_type: "transaction",
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "zxq coffee" } ],
+ actions_attributes: [ { action_type: "set_transaction_category", value: @category.id } ]
+ )
+ assert_equal "preview_required", @fn.call("rule_id" => other_rule.id, "preview_token" => token)[:error]
+
+ other_user = users(:family_member)
+ assert_equal "preview_required",
+ Assistant::Function::ApplyRule.new(other_user).call("rule_id" => @rule.id, "preview_token" => token)[:error]
+
+ travel Assistant::Function::RuleSupport::PREVIEW_TOKEN_TTL + 1.minute do
+ assert_equal "preview_required", @fn.call("rule_id" => @rule.id, "preview_token" => token)[:error]
+ end
+ end
+
+ test "keeps hand-set values unless override_locked" do
+ entry = create_transaction(name: "ZXQ Coffee Shop")
+ entry.entryable.lock_attr!(:category_id)
+
+ perform_enqueued_jobs(only: RuleJob) do
+ @fn.call("rule_id" => @rule.id, "preview_token" => preview_token)
+ end
+ assert_nil entry.entryable.reload.category_id
+
+ perform_enqueued_jobs(only: RuleJob) do
+ @fn.call("rule_id" => @rule.id, "preview_token" => preview_token, "override_locked" => true)
+ end
+ assert_equal @category, entry.entryable.reload.category
+ end
+
+ test "refuses rules with AI-backed actions, unknown ids and another family's rules" do
+ foreign = families(:empty).rules.create!(
+ resource_type: "transaction",
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "zxq" } ],
+ actions_attributes: [ { action_type: "set_transaction_name", value: "x" } ]
+ )
+ assert_equal "not_found", @fn.call("rule_id" => foreign.id, "preview_token" => "x")[:error]
+ assert_not foreign.reload.active
+ assert_equal "not_found", @fn.call("rule_id" => "nope", "preview_token" => "x")[:error]
+
+ @rule.actions.create!(action_type: "auto_categorize")
+ assert_equal "ai_action", @fn.call("rule_id" => @rule.id, "preview_token" => "x")[:error]
+ end
+
+ private
+ def preview_token
+ token = Assistant::Function::PreviewRule.new(@user).call("rule_id" => @rule.id)[:preview][:preview_token]
+ assert token, "a preview of a saved rule should issue a token"
+ token
+ end
+end
diff --git a/test/models/assistant/function/create_rule_test.rb b/test/models/assistant/function/create_rule_test.rb
new file mode 100644
index 0000000000..9ac02bd6f3
--- /dev/null
+++ b/test/models/assistant/function/create_rule_test.rb
@@ -0,0 +1,95 @@
+require "test_helper"
+
+class Assistant::Function::CreateRuleTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @family = @user.family
+ @fn = Assistant::Function::CreateRule.new(@user)
+ @category = categories(:food_and_drink)
+ end
+
+ test "saves the rule inactive and returns a preview" do
+ create_transaction(name: "ZXQ Coffee Shop", amount: 4.5)
+ create_transaction(name: "ZXQ Coffee Beans", amount: 25)
+
+ result = nil
+ assert_difference "@family.rules.count", 1 do
+ result = @fn.call(
+ "name" => "Coffee",
+ "conditions" => [
+ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq coffee" },
+ { "condition_type" => "transaction_amount", "operator" => "<", "value" => "10" }
+ ],
+ "actions" => [
+ { "action_type" => "set_transaction_category", "value" => @category.id },
+ { "action_type" => "set_transaction_tags", "value" => [ tags(:one).id, tags(:two).id ] }
+ ]
+ )
+ end
+
+ assert result[:success], result.inspect
+ rule = @family.rules.find(result[:rule][:id])
+ assert_not rule.active
+ assert_equal "Coffee", rule.name
+ assert_equal 2, rule.conditions.count
+ assert_equal [ tags(:one).id, tags(:two).id ].sort, rule.actions.find_by(action_type: "set_transaction_tags").value.split(",").sort
+ assert_equal 1, result[:preview][:match_count]
+ end
+
+ test "ignores an attempt to create an active rule" do
+ result = @fn.call(
+ "active" => true,
+ "conditions" => [ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq" } ],
+ "actions" => [ { "action_type" => "exclude_transaction" } ]
+ )
+
+ assert result[:success]
+ assert_not @family.rules.find(result[:rule][:id]).active
+ end
+
+ test "does not save an invalid rule" do
+ assert_no_difference "Rule.count" do
+ result = @fn.call(
+ "conditions" => [ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq" } ],
+ "actions" => [
+ { "action_type" => "exclude_transaction" },
+ { "action_type" => "exclude_transaction" }
+ ]
+ )
+
+ assert_equal "invalid_rule", result[:error]
+ end
+
+ assert_no_difference "Rule.count" do
+ assert_equal "invalid_rule", @fn.call("conditions" => [], "actions" => [])[:error]
+ end
+ end
+
+ test "rejects AI-backed actions and ids from outside the family" do
+ other_category = families(:empty).categories.create!(name: "Elsewhere", color: "#000000")
+
+ result = @fn.call(
+ "conditions" => [ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq" } ],
+ "actions" => [
+ { "action_type" => "auto_detect_merchants" },
+ { "action_type" => "set_transaction_category", "value" => other_category.id }
+ ]
+ )
+
+ assert_equal "invalid_rule", result[:error]
+ assert_equal 2, result[:problems].size
+ end
+
+ test "only accepts accounts the user can see" do
+ member_fn = Assistant::Function::CreateRule.new(users(:family_member))
+ params = {
+ "conditions" => [ { "condition_type" => "transaction_account", "operator" => "=", "value" => accounts(:other_asset).id } ],
+ "actions" => [ { "action_type" => "exclude_transaction" } ]
+ }
+
+ assert_equal "invalid_rule", member_fn.call(params)[:error]
+ assert @fn.call(params)[:success]
+ end
+end
diff --git a/test/models/assistant/function/get_rule_options_test.rb b/test/models/assistant/function/get_rule_options_test.rb
new file mode 100644
index 0000000000..15040dca3d
--- /dev/null
+++ b/test/models/assistant/function/get_rule_options_test.rb
@@ -0,0 +1,37 @@
+require "test_helper"
+
+class Assistant::Function::GetRuleOptionsTest < ActiveSupport::TestCase
+ setup do
+ @fn = Assistant::Function::GetRuleOptions.new(users(:family_admin))
+ end
+
+ test "describes conditions and actions without AI-backed actions" do
+ result = @fn.call
+
+ assert result[:success]
+ condition_types = result[:conditions].map { |c| c[:condition_type] }
+ assert_includes condition_types, "transaction_name"
+ assert_includes condition_types, "compound"
+
+ amount = result[:conditions].find { |c| c[:condition_type] == "transaction_amount" }
+ assert_includes amount[:operators].map { |o| o[:value] }, "="
+
+ tag = result[:conditions].find { |c| c[:condition_type] == "transaction_tag" }
+ assert_equal %w[= is_null], tag[:operators].map { |o| o[:value] }
+
+ action_types = result[:actions].map { |a| a[:action_type] }
+ assert_includes action_types, "set_transaction_category"
+ assert_not_includes action_types, "auto_categorize"
+ assert_not_includes action_types, "auto_detect_merchants"
+ end
+
+ test "inlines fixed value lists and points id values at their tools" do
+ result = @fn.call
+
+ type = result[:conditions].find { |c| c[:condition_type] == "transaction_type" }
+ assert_equal %w[income expense transfer], type[:values]
+
+ category = result[:actions].find { |a| a[:action_type] == "set_transaction_category" }
+ assert_match "get_categories", category[:values]
+ end
+end
diff --git a/test/models/assistant/function/get_rules_test.rb b/test/models/assistant/function/get_rules_test.rb
new file mode 100644
index 0000000000..c478d6a2c9
--- /dev/null
+++ b/test/models/assistant/function/get_rules_test.rb
@@ -0,0 +1,104 @@
+require "test_helper"
+
+class Assistant::Function::GetRulesTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @family = @user.family
+ @fn = Assistant::Function::GetRules.new(@user)
+ @category = categories(:food_and_drink)
+
+ @rule = @family.rules.create!(
+ name: "Coffee",
+ resource_type: "transaction",
+ active: true,
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "zxq coffee" } ],
+ actions_attributes: [ { action_type: "set_transaction_category", value: @category.id } ]
+ )
+ end
+
+ test "lists rules with ids resolved to names" do
+ result = @fn.call
+
+ assert result[:success]
+ rule = result[:rules].find { |r| r[:id] == @rule.id }
+ assert_equal "Coffee", rule[:name]
+ assert rule[:active]
+ assert_equal({ condition_type: "transaction_name", operator: "like", value: "zxq coffee" }, rule[:conditions].first)
+ assert_equal @category.name_with_parent, rule[:actions].first[:value_name]
+ assert_nil rule[:last_run]
+ end
+
+ test "filters by active" do
+ inactive = @family.rules.create!(
+ resource_type: "transaction",
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "other" } ],
+ actions_attributes: [ { action_type: "exclude_transaction" } ]
+ )
+
+ ids = @fn.call("active" => false)[:rules].map { |r| r[:id] }
+ assert_includes ids, inactive.id
+ assert_not_includes ids, @rule.id
+ end
+
+ test "single rule includes match count and last run" do
+ create_transaction(name: "ZXQ Coffee Shop")
+ RuleRun.create!(rule: @rule, rule_name: @rule.name, execution_type: "manual", status: "success",
+ transactions_queued: 1, transactions_processed: 1, transactions_modified: 1, executed_at: Time.current)
+
+ result = @fn.call("rule_id" => @rule.id)
+
+ assert result[:success]
+ assert_equal 1, result[:rule][:match_count]
+ assert_equal "success", result[:rule][:last_run][:status]
+ end
+
+ test "rules of another family are not found" do
+ other = families(:empty).rules.create!(
+ resource_type: "transaction",
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "x" } ],
+ actions_attributes: [ { action_type: "exclude_transaction" } ]
+ )
+
+ assert_equal "not_found", @fn.call("rule_id" => other.id)[:error]
+ assert_not_includes @fn.call[:rules].map { |r| r[:id] }, other.id
+ end
+
+ test "paginates" do
+ 3.times do |i|
+ @family.rules.create!(
+ name: "Paged #{i}",
+ resource_type: "transaction",
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "paged #{i}" } ],
+ actions_attributes: [ { action_type: "exclude_transaction" } ]
+ )
+ end
+ total = @family.rules.count
+
+ first = @fn.call("page_size" => 2)
+ assert_equal 2, first[:rules].size
+ assert_equal total, first[:total_results]
+ assert_equal (total / 2.0).ceil, first[:total_pages]
+
+ all_ids = (1..first[:total_pages]).flat_map { |page| @fn.call("page_size" => 2, "page" => page)[:rules].map { |r| r[:id] } }
+ assert_equal @family.rules.pluck(:id).sort, all_ids.sort
+ end
+
+ test "search matches names, condition values including grouped ones, action values and category names" do
+ unnamed = @family.rules.create!(
+ resource_type: "transaction",
+ conditions_attributes: [ {
+ condition_type: "compound", operator: "or",
+ sub_conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "Tesco Express" } ]
+ } ],
+ actions_attributes: [ { action_type: "set_transaction_name", value: "Groceries run" } ]
+ )
+
+ assert_equal [ unnamed.id ], @fn.call("search" => "tesco")[:rules].map { |r| r[:id] }
+ assert_equal [ unnamed.id ], @fn.call("search" => "groceries run")[:rules].map { |r| r[:id] }
+ assert_equal [ @rule.id ], @fn.call("search" => "coff")[:rules].map { |r| r[:id] }
+ assert_includes @fn.call("search" => @category.name)[:rules].map { |r| r[:id] }, @rule.id
+ assert_equal 0, @fn.call("search" => "100%")[:total_results]
+ end
+end
diff --git a/test/models/assistant/function/preview_rule_test.rb b/test/models/assistant/function/preview_rule_test.rb
new file mode 100644
index 0000000000..2d96f4c6ac
--- /dev/null
+++ b/test/models/assistant/function/preview_rule_test.rb
@@ -0,0 +1,119 @@
+require "test_helper"
+
+class Assistant::Function::PreviewRuleTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @family = @user.family
+ @fn = Assistant::Function::PreviewRule.new(@user)
+ @category = categories(:food_and_drink)
+ end
+
+ def definition(conditions: nil, actions: nil)
+ {
+ "conditions" => conditions || [ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq coffee" } ],
+ "actions" => actions || [ { "action_type" => "set_transaction_category", "value" => @category.id } ]
+ }
+ end
+
+ test "previews an unsaved definition without saving or changing anything" do
+ entry = create_transaction(name: "ZXQ Coffee Shop", amount: 4.5)
+ create_transaction(name: "Groceries")
+
+ assert_no_difference [ "Rule.count", "Rule::Condition.count", "Rule::Action.count" ] do
+ result = @fn.call(definition)
+
+ assert result[:success], result.inspect
+ assert_equal 1, result[:preview][:match_count]
+ assert_equal [ entry.entryable.id ], result[:preview][:sample].map { |t| t[:id] }
+ assert_equal @category.name_with_parent, result[:preview][:actions].first[:value_name]
+ end
+
+ assert_nil entry.entryable.reload.category_id
+ end
+
+ test "previews a saved rule" do
+ create_transaction(name: "ZXQ Coffee Shop")
+ rule = @family.rules.create!(resource_type: "transaction", **rule_attributes)
+
+ result = @fn.call("rule_id" => rule.id)
+
+ assert result[:success]
+ assert_equal 1, result[:preview][:match_count]
+ end
+
+ test "respects effective_date and compound or conditions" do
+ create_transaction(name: "ZXQ Coffee Shop", date: 10.days.ago.to_date)
+ create_transaction(name: "ZXQ Tea House", date: 2.days.ago.to_date)
+ create_transaction(name: "ZXQ Bakery", date: 2.days.ago.to_date)
+
+ params = definition(conditions: [
+ { "condition_type" => "compound", "operator" => "or", "sub_conditions" => [
+ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq coffee" },
+ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq tea" }
+ ] }
+ ])
+
+ assert_equal 2, @fn.call(params)[:preview][:match_count]
+ assert_equal 1, @fn.call(params.merge("effective_date" => 5.days.ago.to_date.iso8601))[:preview][:match_count]
+ end
+
+ test "rejects invalid definitions with every problem listed" do
+ result = @fn.call(definition(
+ conditions: [
+ { "condition_type" => "transaction_amount", "operator" => "like", "value" => "5" },
+ { "condition_type" => "transaction_category", "operator" => "=", "value" => SecureRandom.uuid }
+ ],
+ actions: [ { "action_type" => "auto_categorize" } ]
+ ))
+
+ assert_not result[:success]
+ assert_equal "invalid_rule", result[:error]
+ assert_equal 3, result[:problems].size
+ end
+
+ test "rejects nested compound conditions and non-numeric amounts" do
+ nested = @fn.call(definition(conditions: [
+ { "condition_type" => "compound", "operator" => "and", "sub_conditions" => [
+ { "condition_type" => "compound", "operator" => "or", "sub_conditions" => [] }
+ ] }
+ ]))
+ assert_match "cannot be nested", nested[:problems].first
+
+ amount = @fn.call(definition(conditions: [ { "condition_type" => "transaction_amount", "operator" => ">", "value" => "abc" } ]))
+ assert_match "must be a number", amount[:problems].first
+ end
+
+ test "rejects operators a filter lists but cannot apply" do
+ result = @fn.call(definition(conditions: [ { "condition_type" => "transaction_tag", "operator" => "!=", "value" => tags(:one).id } ]))
+
+ assert_equal "invalid_rule", result[:error]
+ end
+
+ test "requires exactly one of rule_id or a definition" do
+ assert_equal "invalid_arguments", @fn.call({})[:error]
+
+ rule = @family.rules.create!(resource_type: "transaction", **rule_attributes)
+ assert_equal "invalid_arguments", @fn.call(definition.merge("rule_id" => rule.id))[:error]
+ end
+
+ test "counts the whole family but samples only accounts the user can see" do
+ create_transaction(name: "ZXQ Coffee Shop", account: accounts(:other_asset))
+ visible = create_transaction(name: "ZXQ Coffee Bar", account: accounts(:depository))
+
+ result = Assistant::Function::PreviewRule.new(users(:family_member)).call(definition)
+
+ assert_equal 2, result[:preview][:match_count]
+ assert_equal 1, result[:preview][:visible_match_count]
+ assert_equal [ visible.entryable.id ], result[:preview][:sample].map { |t| t[:id] }
+ end
+
+ private
+ def rule_attributes
+ {
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "zxq coffee" } ],
+ actions_attributes: [ { action_type: "set_transaction_category", value: @category.id } ]
+ }
+ end
+end
diff --git a/test/models/assistant/function/update_rule_test.rb b/test/models/assistant/function/update_rule_test.rb
new file mode 100644
index 0000000000..2590fe500c
--- /dev/null
+++ b/test/models/assistant/function/update_rule_test.rb
@@ -0,0 +1,99 @@
+require "test_helper"
+
+class Assistant::Function::UpdateRuleTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @family = @user.family
+ @fn = Assistant::Function::UpdateRule.new(@user)
+ @category = categories(:food_and_drink)
+
+ @rule = @family.rules.create!(
+ name: "Coffee",
+ resource_type: "transaction",
+ active: true,
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "zxq coffee" } ],
+ actions_attributes: [ { action_type: "set_transaction_category", value: @category.id } ]
+ )
+ end
+
+ test "renaming keeps an active rule active" do
+ result = @fn.call("rule_id" => @rule.id, "name" => "Morning coffee")
+
+ assert result[:success]
+ @rule.reload
+ assert_equal "Morning coffee", @rule.name
+ assert @rule.active
+ end
+
+ test "replacing conditions deactivates the rule" do
+ create_transaction(name: "ZXQ Tea House")
+
+ result = @fn.call("rule_id" => @rule.id, "conditions" => [
+ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq tea" }
+ ])
+
+ assert result[:success], result.inspect
+ @rule.reload
+ assert_not @rule.active
+ assert_equal [ "zxq tea" ], @rule.conditions.map(&:value)
+ assert_equal 1, @rule.actions.count
+ assert_equal 1, result[:preview][:match_count]
+ assert_match "deactivated", result[:message]
+ end
+
+ test "replacing actions swaps the whole list" do
+ result = @fn.call("rule_id" => @rule.id, "actions" => [ { "action_type" => "exclude_transaction" } ])
+
+ assert result[:success]
+ assert_equal [ "exclude_transaction" ], @rule.reload.actions.map(&:action_type)
+ end
+
+ test "an invalid update changes nothing" do
+ result = @fn.call("rule_id" => @rule.id, "name" => "Changed", "actions" => [])
+
+ assert_equal "invalid_rule", result[:error]
+ @rule.reload
+ assert_equal "Coffee", @rule.name
+ assert @rule.active
+ assert_equal 1, @rule.actions.count
+ end
+
+ test "can deactivate but not activate" do
+ assert @fn.call("rule_id" => @rule.id, "active" => false)[:success]
+ assert_not @rule.reload.active
+
+ assert_equal "cannot_activate", @fn.call("rule_id" => @rule.id, "active" => true)[:error]
+ assert_not @rule.reload.active
+ end
+
+ test "requires a change and a rule in the family" do
+ assert_equal "no_changes", @fn.call("rule_id" => @rule.id)[:error]
+ assert_equal "not_found", @fn.call("rule_id" => SecureRandom.uuid, "name" => "x")[:error]
+ end
+
+ test "another family's rule is not found and left untouched" do
+ foreign = families(:empty).rules.create!(
+ name: "Theirs",
+ resource_type: "transaction",
+ active: true,
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "zxq" } ],
+ actions_attributes: [ { action_type: "set_transaction_name", value: "x" } ]
+ )
+
+ assert_equal "not_found", @fn.call("rule_id" => foreign.id, "name" => "Mine now", "active" => false)[:error]
+ foreign.reload
+ assert_equal "Theirs", foreign.name
+ assert foreign.active
+ end
+
+ test "an update returns a preview with a token for apply_rule" do
+ create_transaction(name: "ZXQ Coffee Shop")
+
+ result = @fn.call("rule_id" => @rule.id, "conditions" => [ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq" } ])
+
+ assert result[:success], result.inspect
+ assert result.dig(:preview, :preview_token).present?
+ end
+end