Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- **Schema tools can ask whether a column is set** (`activeagent`). A
filter value of `null` means "no filter", so a model had no way to ask
for the tickets with no assignee or the requests not yet approved, and
hosts wrote sentinel ranges such as `{"after": "2000-01-01"}` into their
instructions instead. A filter now takes `{"present": false}` (IS NULL)
or `{"present": true}` (IS NOT NULL) on any filterable column, alone or
beside a range bound. The tool schema offers it in the range object of
nullable date, time and number columns, so foreign keys get it too, and
an enum accepts it though it takes no comparison. Anything but true or
false is rejected rather than guessed.

### Fixed

- **An evaluation run is executed by one job** (`actionagent`). The run job
Expand Down
2 changes: 2 additions & 0 deletions docs/actions/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@ Three properties make this safe to hand to a model:
- **Results are capped** (25 by default, 100 at most) with a `truncated` flag, so a `find_*` with no filters cannot select a table into the prompt.
- **The scope is yours.** `scope { |actor| ... }` receives whatever your host passes as `actor:` and returns the relation to read through; `scope_by_policy` resolves `<Model>Policy::Scope` by name. Omit both and the tools read unscoped — a deliberate choice, not a default.

A filter value is matched for equality, or takes an object: date, time and number columns accept a range (`{ "before": "2026-12-01" }`, `{ "gte": 10, "lt": 20 }`), and any column accepts `{ "present": false }` for the records where it is empty (null) or `{ "present": true }` for those where it is set. A `null` value means "no filter", because models send `null` for the optional parameters they leave out, so "reservations with no guest" is asked as `guest_id: { "present": false }`. The schema offers `present` on the nullable columns that already carry the range form; an unknown comparison or a `present` that is not `true` or `false` comes back as an error rather than as an empty answer.

The tool definitions are ordinary [common-format tools](#common-tools-format-recommended), so an agent offers them with `prompt(tools: ReservationTools.tool_definitions)` and answers each call with `ReservationTools.call(name, actor: current_user, **arguments)`. The [dashboard engine](/framework/dashboard) discovers every class under `app/agent_tools` and offers each generated tool in the agent editor.

Start from the generator rather than a blank file:
Expand Down
12 changes: 12 additions & 0 deletions docs/work/schema-tools-presence-filter/branch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Schema tools presence filter — branch

| Branch | PR | Base | Scope |
|---|---|---|---|
| `feat/schema-tools-presence-filter` | #718 | `main` (after 1.9.8) | `{"present": true\|false}` on SchemaTools filters |

Files: `lib/active_agent/schema_tools.rb`, `test/schema_tools_test.rb`,
`docs/actions/tools.md`, `CHANGELOG.md` (`[Unreleased]`).

Local runs follow `docs/work/schema-tools-follow-ups/branch.md` ("Running the suite locally"):
a placeholder `.env.test`, `CI=1`, and the live-network RubyLLM/Anthropic tests failing without
real keys.
25 changes: 25 additions & 0 deletions docs/work/schema-tools-presence-filter/issues.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Schema tools presence filter — issues

## The gap

`permitted_filters!` drops a `nil` value as "no filter", which is right: models send `null` for
every optional parameter they leave out. But it leaves no way to ask for the records where a
column *is* null — tickets with no assignee, requests not yet approved, posts never published.
A host's instructions had to teach the model a sentinel range (`{"after": "2000-01-01"}` on a
timestamp) to mean "is set", and there was no sentinel at all for "is not set" on a foreign key.

## Decisions

| Question | Decision |
|---|---|
| Make `null` mean IS NULL? | No. It would turn every omitted optional parameter into a filter. |
| Operator name | `present`, a key inside the existing object form, beside `before`/`gte`. |
| Strings: does `""` count as empty? | No. `present` is NULL / NOT NULL everywhere; it is only *offered* on dates, times and numbers, where `""` cannot occur. |
| Where it is offered | In the range object of nullable range columns (dates, times, numbers, so foreign keys too). Not wrapped around every nullable string or enum, to keep the schema small. |
| Where it is accepted | Any filterable column, including an enum, which otherwise rejects an object. |
| Operands | `true`/`false` or their strings. Anything else is an error, never a guess. |

## Not done

- A blank-string-aware form for text columns (`present` meaning "not null and not empty").
- Offering `present` on nullable strings and enums in the schema.
9 changes: 9 additions & 0 deletions docs/work/schema-tools-presence-filter/milestones.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Schema tools presence filter — milestones

| # | Milestone | Status |
|---|---|---|
| M1 | Filter accepted and applied (IS NULL / IS NOT NULL), alone, with a bound, on an enum | ✅ |
| M2 | Offered in the schema on nullable range columns only | ✅ |
| M3 | Docs (`docs/actions/tools.md`) and changelog | ✅ |
| M4 | PR open (#718), CI green | ⏳ CI |
| M5 | Released (next patch after 1.9.8) | ⏳ |
12 changes: 12 additions & 0 deletions docs/work/schema-tools-presence-filter/pull-request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Schema tools presence filter — pull request

#718 against `main`: `feat/schema-tools-presence-filter`.

- **What:** `{"present": false}` / `{"present": true}` on any SchemaTools filter, offered in the
schema on nullable date, time and number columns.
- **Tests:** 7 new in `test/schema_tools_test.rb` (null, not null, with a bound and an equality
filter, string operands, a rejected operand, a string column and an enum, where it is offered),
plus the advertised-operators test updated. 64 SchemaTools tests and 64 engine/generator
schema-tools tests green; RuboCop clean.
- **Upgrade:** none. Existing filters behave as before; the schema gains one boolean property in
the range object of nullable columns.
61 changes: 50 additions & 11 deletions lib/active_agent/schema_tools.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ class SchemaTools
"on_or_before" => :lteq, "on_or_after" => :gteq
}.freeze

# Asks whether a column holds a value at all: `{ "present" => false }` is
# IS NULL, `{ "present" => true }` IS NOT NULL. A nil filter value cannot
# ask it, because nil means "no filter" (models send null for the
# optional parameters they leave out), so without this "tickets with no
# assignee" or "requests not yet approved" has no filter that says so.
PRESENCE_OPERATOR = "present"

# Column names that look like they hold a credential. The schema tools
# generator never suggests one, and the dashboard never lets one be
# chosen: reading one back would hand a model a credential, and
Expand Down Expand Up @@ -329,7 +336,8 @@ def relation_for(actor)
#
# A filter value is normally matched for equality. A Hash value instead
# declares a range — `{ "before" => "2026-01-01" }`, `{ "gte" => 10 }` —
# and may carry two bounds at once to express a window.
# and may carry two bounds at once to express a window, or asks whether
# the column is set at all (`{ "present" => false }`).
#
# @api private
# @raise [UnpermittedAttribute] if any key is not declared filterable,
Expand Down Expand Up @@ -389,17 +397,37 @@ def range_predicates!(column, value)
type = @model.type_for_attribute(column)

value.map do |operator, operand|
next presence_predicate!(column, arel, operand) if operator.to_s == PRESENCE_OPERATOR

predicate = RANGE_OPERATORS[operator.to_s]
unless predicate
raise UnpermittedAttribute,
"`#{operator}` is not a valid comparison for `#{column}`. " \
"Allowed comparisons: #{RANGE_OPERATORS.keys.join(", ")}"
"Allowed comparisons: #{[ *RANGE_OPERATORS.keys, PRESENCE_OPERATOR ].join(", ")}"
end

arel.public_send(predicate, type.cast(operand))
end
end

# Builds IS NULL / IS NOT NULL for `{ "present" => ... }`.
#
# Only true and false (or their strings) are accepted: anything else
# would have to be guessed into one of the two, and a wrong guess
# answers the opposite question.
#
# @api private
# @raise [UnpermittedAttribute] on any other operand
def presence_predicate!(column, arel, operand)
case operand.to_s
when "true" then arel.not_eq(nil)
when "false" then arel.eq(nil)
else
raise UnpermittedAttribute,
"`#{PRESENCE_OPERATOR}` for `#{column}` takes true or false, not #{operand.inspect}"
end
end

# A value outside a Rails enum reaches `where` as an unmatched name and
# returns zero rows — the same silent-nothing that {.range_predicates!}
# rejects for an unknown operator, and just as bad here: an agent reads
Expand All @@ -415,9 +443,12 @@ def validate_enum_value!(column, value)
return if values.blank?

if value.is_a?(Hash)
# Whether it is set at all is a question an enum can answer.
return if value.keys.map(&:to_s) == [ PRESENCE_OPERATOR ]

raise UnpermittedAttribute,
"`#{column}` is an enum and cannot be compared as a range. " \
"Allowed values: #{values.keys.join(", ")}"
"Allowed values: #{values.keys.join(", ")}, or {\"#{PRESENCE_OPERATOR}\": true|false}"
end

# An Array is an IN filter, which `where` silently narrows to its
Expand Down Expand Up @@ -550,20 +581,28 @@ def range_filterable?(column)
# only `{type: "string", format: "date"}` has no way to know it may ask
# for `before`, and answers date questions with an equality match or no
# filter at all.
#
# A nullable column's range object also takes `present`, so "has no
# due date" is asked in the same shape as "due before Friday". It is
# offered only here, on the columns that already carry an object form,
# rather than wrapping every nullable string and enum in one; a call
# may still send it for any filterable column.
def with_range_form(column, scalar)
operand = scalar.slice(:type, :format)
description = scalar[:description]
nullable = @model.columns_hash[column.to_s]&.null
properties = RANGE_OPERATORS.keys.index_with { operand.dup }
properties[PRESENCE_OPERATOR] = { type: "boolean" } if nullable

description = [ scalar[:description], "Accepts an exact value, or a range object such as " \
"{\"before\": ...} / {\"gte\": ...} (#{RANGE_OPERATORS.keys.join(", ")})." ]
description << "{\"#{PRESENCE_OPERATOR}\": false} matches records where it is empty (null), " \
"{\"#{PRESENCE_OPERATOR}\": true} where it is set." if nullable

{
description: [ description, "Accepts an exact value, or a range object such as " \
"{\"before\": ...} / {\"gte\": ...} (#{RANGE_OPERATORS.keys.join(", ")})." ].compact.join(" "),
description: description.compact.join(" "),
anyOf: [
scalar.except(:description),
{
type: "object",
properties: RANGE_OPERATORS.keys.index_with { operand.dup },
additionalProperties: false
}
{ type: "object", properties: properties, additionalProperties: false }
]
}
end
Expand Down
86 changes: 85 additions & 1 deletion test/schema_tools_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,90 @@ class DatedPostTools < ActiveAgent::SchemaTools
.dig(:parameters, :properties)
advertised = properties[:published_at][:anyOf].last[:properties].keys.map(&:to_s)

assert_equal ActiveAgent::SchemaTools::RANGE_OPERATORS.keys.sort, advertised.sort
expected = [ *ActiveAgent::SchemaTools::RANGE_OPERATORS.keys, ActiveAgent::SchemaTools::PRESENCE_OPERATOR ]
assert_equal expected.sort, advertised.sort
end

# --- Presence filters --------------------------------------------------
#
# A nil filter value is dropped as "no filter", so before `present` there
# was no way to ask for the records where a column is empty; hosts worked
# around it with sentinel ranges such as {"after": "2000-01-01"}.

test "present false matches the records where the column is null" do
Post.delete_all
draft = Post.create!(title: "Draft", content: "body", user: @alice)
Post.create!(title: "Out", content: "body", user: @alice, published_at: 1.day.ago)

result = DatedPostTools.call("find_posts", published_at: { "present" => false })

assert_equal [ draft.title ], result[:results].map { |r| r[:title] }
end

test "present true matches the records where the column is set" do
Post.delete_all
Post.create!(title: "Draft", content: "body", user: @alice)
Post.create!(title: "Out", content: "body", user: @alice, published_at: 1.day.ago)
Post.create!(title: "Scheduled", content: "body", user: @alice, published_at: 1.day.from_now)

assert_equal({ count: 2 }, DatedPostTools.call("count_posts", published_at: { "present" => true }))
end

test "present combines with a bound and with an equality filter" do
Post.delete_all
Post.create!(title: "Draft", content: "body", user: @alice, published: false)
Post.create!(title: "Old", content: "body", user: @alice, published_at: 10.days.ago, published: true)
Post.create!(title: "Old draft", content: "body", user: @alice, published_at: 10.days.ago, published: false)

result = DatedPostTools.call(
"find_posts", published: true, published_at: { "present" => true, "before" => Time.current.iso8601 }
)

assert_equal [ "Old" ], result[:results].map { |r| r[:title] }
end

test "present accepts the strings a model may send" do
Post.delete_all
Post.create!(title: "Draft", content: "body", user: @alice)

assert_equal({ count: 1 }, DatedPostTools.call("count_posts", published_at: { "present" => "false" }))
assert_equal({ count: 0 }, DatedPostTools.call("count_posts", published_at: { "present" => "true" }))
end

test "present rejects anything but true or false rather than guessing" do
result = DatedPostTools.call("count_posts", published_at: { "present" => "maybe" })

refute result.key?(:count)
assert_match "takes true or false", result[:error]
assert DatedPostTools.call("count_posts", published_at: { "present" => nil }).key?(:error)
end

test "present works on columns that are not offered the range form" do
Post.delete_all
# Written past validation: the dummy model requires content, the column does not.
Post.create!(title: "No body", content: "body", user: @alice).update_columns(content: nil, state: nil)
Post.create!(title: "Body", content: "body", user: @alice)
tools = ActiveAgent::SchemaTools.define(Post, filterable: %i[content state], returns: %i[id title], name: "PresencePostTools")

assert_equal({ count: 1 }, tools.call("count_posts", content: { "present" => true }))
# An enum takes `present` though it takes no comparison.
assert_equal({ count: 1 }, tools.call("count_posts", state: { "present" => false }))
assert_match "cannot be compared as a range", tools.call("count_posts", state: { "present" => false, "gt" => 1 })[:error]
ensure
ActiveAgent::SchemaTools.undefine(Post)
end

test "present is offered on nullable range columns only" do
properties = DatedPostTools.tool_definitions.find { |d| d[:name] == "find_posts" }
.dig(:parameters, :properties)
created = ActiveAgent::SchemaTools.define(Post, filterable: %i[created_at], name: "CreatedPostTools")
.tool_definitions.find { |d| d[:name] == "find_posts" }.dig(:parameters, :properties, :created_at)

assert_equal({ type: "boolean" }, properties[:published_at][:anyOf].last[:properties]["present"])
assert_match "\"present\": false", properties[:published_at][:description]
refute created[:anyOf].last[:properties].key?("present"), "a NOT NULL column is never empty"
refute properties[:published].key?(:anyOf), "a boolean column gets no object form for presence either"
ensure
ActiveAgent::SchemaTools.undefine(Post)
end
end