rails_ai_admin 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +64 -0
  3. data/README.md +4 -9
  4. data/SECURITY.md +1 -1
  5. data/app/assets/builds/rails_ai_admin.js +5 -5
  6. data/app/controllers/rails_ai_admin/application_controller.rb +19 -6
  7. data/app/controllers/rails_ai_admin/assistant_controller.rb +20 -7
  8. data/app/controllers/rails_ai_admin/audit_controller.rb +5 -1
  9. data/app/controllers/rails_ai_admin/bulk_changes_controller.rb +26 -6
  10. data/app/controllers/rails_ai_admin/dashboard_controller.rb +3 -2
  11. data/app/controllers/rails_ai_admin/deleted_records_controller.rb +12 -4
  12. data/app/controllers/rails_ai_admin/files_controller.rb +16 -4
  13. data/app/controllers/rails_ai_admin/mcp_controller.rb +30 -4
  14. data/app/controllers/rails_ai_admin/mcp_tokens_controller.rb +4 -2
  15. data/app/controllers/rails_ai_admin/operations_controller.rb +5 -2
  16. data/app/controllers/rails_ai_admin/resources_controller.rb +44 -5
  17. data/app/controllers/rails_ai_admin/selections_controller.rb +41 -5
  18. data/app/helpers/rails_ai_admin/assistant_helper.rb +3 -1
  19. data/app/helpers/rails_ai_admin/fields_helper.rb +36 -7
  20. data/app/helpers/rails_ai_admin/history_helper.rb +1 -1
  21. data/app/views/layouts/rails_ai_admin/application.html.erb +1 -0
  22. data/app/views/layouts/rails_ai_admin/frame.html.erb +1 -1
  23. data/app/views/layouts/rails_ai_admin/status.html.erb +2 -2
  24. data/app/views/rails_ai_admin/assistant/_transcript.html.erb +5 -1
  25. data/app/views/rails_ai_admin/audit/index.html.erb +1 -1
  26. data/app/views/rails_ai_admin/deleted_records/index.html.erb +3 -2
  27. data/app/views/rails_ai_admin/fields/_input.html.erb +2 -1
  28. data/app/views/rails_ai_admin/selections/confirm_destroy.html.erb +1 -0
  29. data/config/locales/en.yml +2 -0
  30. data/db/assistant_migrate/20261103000001_create_rails_ai_admin_assistant.rb +1 -0
  31. data/db/migrate/20261122000001_add_missing_indexes_to_rails_ai_admin_tables.rb +12 -0
  32. data/lib/generators/rails_ai_admin/assistant/assistant_generator.rb +4 -1
  33. data/lib/generators/rails_ai_admin/assistant/templates/admin_assistant.rb +6 -0
  34. data/lib/generators/rails_ai_admin/assistant/templates/assistant_eval.yml +25 -0
  35. data/lib/generators/rails_ai_admin/install/templates/admin_context_devise.rb.tt +2 -1
  36. data/lib/generators/rails_ai_admin/install/templates/admin_context_rails.rb.tt +5 -2
  37. data/lib/rails_ai_admin/assistant/budget.rb +4 -2
  38. data/lib/rails_ai_admin/assistant/coordinator.rb +18 -4
  39. data/lib/rails_ai_admin/assistant/evaluation.rb +124 -0
  40. data/lib/rails_ai_admin/assistant/records.rb +2 -1
  41. data/lib/rails_ai_admin/assistant/retention.rb +12 -1
  42. data/lib/rails_ai_admin/assistant/runtime.rb +49 -1
  43. data/lib/rails_ai_admin/assistant/tools.rb +58 -18
  44. data/lib/rails_ai_admin/assistant.rb +1 -0
  45. data/lib/rails_ai_admin/authorization/access.rb +34 -23
  46. data/lib/rails_ai_admin/authorization/pundit_adapter.rb +6 -3
  47. data/lib/rails_ai_admin/collections/dispatcher.rb +3 -3
  48. data/lib/rails_ai_admin/collections/queries.rb +1 -1
  49. data/lib/rails_ai_admin/configuration.rb +39 -8
  50. data/lib/rails_ai_admin/doctor.rb +44 -9
  51. data/lib/rails_ai_admin/field.rb +37 -22
  52. data/lib/rails_ai_admin/fields/association.rb +27 -10
  53. data/lib/rails_ai_admin/fields/type.rb +1 -1
  54. data/lib/rails_ai_admin/forms/plan.rb +4 -2
  55. data/lib/rails_ai_admin/input_schema.rb +4 -4
  56. data/lib/rails_ai_admin/integrations/propose_operation.rb +18 -4
  57. data/lib/rails_ai_admin/integrations/tool_views.rb +29 -3
  58. data/lib/rails_ai_admin/mcp.rb +23 -13
  59. data/lib/rails_ai_admin/navigation/list_state.rb +3 -3
  60. data/lib/rails_ai_admin/navigation/saved_views.rb +6 -5
  61. data/lib/rails_ai_admin/operations/restore.rb +25 -4
  62. data/lib/rails_ai_admin/operations/runner.rb +51 -15
  63. data/lib/rails_ai_admin/outbox/dispatcher.rb +6 -2
  64. data/lib/rails_ai_admin/presentation/association_panel.rb +6 -6
  65. data/lib/rails_ai_admin/presentation/audit_log.rb +8 -3
  66. data/lib/rails_ai_admin/presentation/csv_export.rb +21 -8
  67. data/lib/rails_ai_admin/presentation/csv_import.rb +9 -1
  68. data/lib/rails_ai_admin/presentation/dashboard.rb +5 -2
  69. data/lib/rails_ai_admin/presentation/history.rb +1 -1
  70. data/lib/rails_ai_admin/prune.rb +16 -5
  71. data/lib/rails_ai_admin/queries/list.rb +138 -38
  72. data/lib/rails_ai_admin/record_version.rb +1 -1
  73. data/lib/rails_ai_admin/registry.rb +5 -0
  74. data/lib/rails_ai_admin/request_log_filter.rb +4 -2
  75. data/lib/rails_ai_admin/resource.rb +4 -0
  76. data/lib/rails_ai_admin/schema_suggestions.rb +13 -5
  77. data/lib/rails_ai_admin/templates/catalog.rb +4 -2
  78. data/lib/rails_ai_admin/templates/inspector.rb +6 -2
  79. data/lib/rails_ai_admin/templates/safe_paths.rb +2 -1
  80. data/lib/rails_ai_admin/version.rb +1 -1
  81. data/lib/rails_ai_admin/work.rb +1 -1
  82. data/lib/rails_ai_admin.rb +10 -6
  83. data/lib/tasks/rails_ai_admin.rake +20 -0
  84. metadata +25 -2
@@ -160,7 +160,7 @@ module RailsAiAdmin
160
160
  end.to_h
161
161
  end
162
162
 
163
- def reference_resolver(access) = Fields::Association.new(access.context, access.resource)
163
+ def reference_resolver(access) = Fields::Association.new(access.context, access.resource, assistant: true)
164
164
 
165
165
  def record_entry(access, record, view, references = reference_resolver(access))
166
166
  { "id" => record.id.to_s, "label" => access.record_label(record, view: view), "fields" => values(access, record, view, references) }
@@ -238,24 +238,35 @@ module RailsAiAdmin
238
238
  "key" => resource.key.to_s, "label" => resource.label,
239
239
  "fields" => access.fields(:read, nil, view: :show).map { |field| field_entry(field) },
240
240
  # Match mode per field: "prefix" means "Love" does not find "Ada Lovelace" (RAA-021).
241
- "search" => access.fields(:search).map { |field| { "field" => field.name.to_s, "match" => (field.options[:searchable] == true ? :prefix : field.options[:searchable]).to_s } },
241
+ "search" => access.fields(:search, assistant: true).map { |field| { "field" => field.name.to_s, "match" => (field.options[:searchable] == true ? :prefix : field.options[:searchable]).to_s } },
242
242
  "filters" => access.fields(:filter).map { |field| { "field" => field.name.to_s, "operators" => field.filter_operators.map(&:to_s) } },
243
- "sort" => access.fields(:sort).map { |field| field.name.to_s },
243
+ "sort" => access.fields(:sort, assistant: true).map { |field| field.name.to_s },
244
244
  # aggregate_records: measured fields and their functions, and the
245
245
  # categories results can be grouped by (filter grant required).
246
246
  "aggregates" => access.fields(:read).select { |field| field.aggregatable? && !field.virtual? }
247
247
  .map { |field| { "field" => field.name.to_s, "functions" => field.aggregate_functions.map(&:to_s) } },
248
248
  "group_by" => access.fields(:filter).select { |field| Field::GROUP_TYPES.include?(field.scalar_type) }.map { |field| field.name.to_s },
249
+ # Date and datetime fields aggregate_records can group by period.
250
+ "group_by_period" => access.fields(:filter).select { |field| Field::PERIOD_TYPES.include?(field.scalar_type) }.map { |field| field.name.to_s },
249
251
  # Search and count apply no list tab unless one is named (RAA-007).
250
252
  "scopes" => access.named_scopes.map { |definition| { "name" => definition.name.to_s, "label" => definition.label, "default_in_ui" => definition.default? } }
251
253
  }
252
254
  if RailsAiAdmin.configuration.surfaces
253
255
  result["operations"] = operations(resource, access)
254
256
  result["changes"] = changes(resource, access)
257
+ elsif resource.assistant_change?(:bulk_update) && bulk_granted?(access)
258
+ result["changes"] = bulk_only_changes(resource, access)
255
259
  end
256
260
  result
257
261
  end
258
262
 
263
+ def bulk_only_changes(resource, access)
264
+ fields = access.fields(:write, nil, operation: :update)
265
+ .reject { |field| ProposeChange::UNSUPPORTED.include?(field.scalar_type) }
266
+ .map { |field| field_entry(field).merge("required" => false) }
267
+ [ { "action" => "bulk_update", "fields" => fields, "max_records" => Selections::Builder::LIMIT } ]
268
+ end
269
+
259
270
  # Native changes this resource lets the assistant propose, with the
260
271
  # fields the user may set on create or update (never passwords or files).
261
272
  def changes(resource, access)
@@ -293,7 +304,7 @@ module RailsAiAdmin
293
304
  # proposal is authorized against its record by propose_operation.
294
305
  def operations(resource, _access)
295
306
  RailsAiAdmin.operation_registry.custom(resource).filter_map do |definition|
296
- next unless definition.scope == :member && resource.assistant_operation?(definition.key)
307
+ next unless definition.scope == :member && resource.assistant_operation?(definition.key) && resource.action_enabled?(definition.key)
297
308
  { "key" => definition.key.to_s, "description" => definition.description.to_s.truncate(200),
298
309
  "input" => definition.handler_class.input.map { |field| field_entry(field).merge("required" => field.options[:required] == true) } }
299
310
  end
@@ -331,23 +342,42 @@ module RailsAiAdmin
331
342
  raise AccessDenied, "INVALID_QUERY" unless direction.nil? || %w[asc desc].include?(direction)
332
343
  offset = (page - 1) * PAGE_LIMIT if offset.nil?
333
344
  raise AccessDenied, "INVALID_QUERY" unless offset.is_a?(Integer) && offset.between?(0, MAX_RECORDS - 1)
334
- result = Queries::List.new(@session.context, resource).call(search: query.presence, page: page.to_s, filters: wire_filters(filters),
345
+ result = Queries::List.new(@session.context, resource, assistant: true).call(search: query.presence, page: page.to_s, filters: wire_filters(filters),
335
346
  scope: list_scope(scope), sort: sort, direction: direction || "asc", page_size: [ PAGE_LIMIT, MAX_RECORDS - offset ].min, offset: offset)
336
- records, omitted = record_entries(access, result.records, :index)
347
+ records, omitted, @row_positions = record_entries_with_positions(access, result.records, :index)
348
+ @queried_count = result.records.size
337
349
  { "resource" => resource.key.to_s, "applied_scope" => result.scope,
338
350
  "applied_sort" => result.sort ? { "field" => result.sort, "direction" => result.direction } : nil,
339
351
  "page" => result.number, "offset" => offset, "has_more" => result.has_next,
340
352
  "omitted" => omitted, "records" => records }
341
353
  end
342
354
 
355
+ def record_entries_with_positions(access, records, view)
356
+ resolver = reference_resolver(access)
357
+ access.fields(:read, nil, view: view).select { |field| field.scalar_type == :belongs_to }.each do |field|
358
+ resolver.prime(field, records.filter_map { |record| record.has_attribute?(field.column) ? record.read_attribute(field.column)&.to_s : nil })
359
+ end
360
+ omitted = 0
361
+ positions = []
362
+ entries = []
363
+ records.each_with_index do |record, index|
364
+ entries << record_entry(access, record, view, resolver)
365
+ positions << (index + 1)
366
+ rescue AccessDenied
367
+ omitted += 1
368
+ end
369
+ [ entries, omitted, positions ]
370
+ end
371
+
343
372
  # Leave room for continuation metadata before applying the byte bound.
344
- # Advance by what the model actually saw, not the number queried.
373
+ # Advance by SQL rows consumed so omitted pages never loop infinitely.
345
374
  def bounded(result)
346
375
  return result if result["error"]
347
376
  result = super(result.merge("next_offset" => MAX_RECORDS, "limit_reached" => false))
348
377
  records = result.fetch("records")
349
378
  return failure("UNAVAILABLE") if records.empty? && result["truncated"]
350
- next_offset = result.fetch("offset") + records.size
379
+ consumed = result["truncated"] ? @row_positions[records.size - 1].to_i : @queried_count.to_i
380
+ next_offset = result.fetch("offset") + consumed
351
381
  more = result["has_more"] || result["truncated"] == true
352
382
  result.merge("next_offset" => more && next_offset < MAX_RECORDS ? next_offset : nil,
353
383
  "has_more" => more && next_offset < MAX_RECORDS, "limit_reached" => more && next_offset >= MAX_RECORDS)
@@ -374,7 +404,7 @@ module RailsAiAdmin
374
404
 
375
405
  def perform(tool_call:, resource:, query: nil, filters: nil, scope: nil)
376
406
  resource = @session.resource(resource)
377
- result = Queries::List.new(@session.context, resource).count(search: query.presence, filters: wire_filters(filters), scope: list_scope(scope))
407
+ result = Queries::List.new(@session.context, resource, assistant: true).count(search: query.presence, filters: wire_filters(filters), scope: list_scope(scope))
378
408
  { "resource" => resource.key.to_s, "applied_scope" => result.scope, "count" => result.count, "capped" => result.capped }
379
409
  end
380
410
  end
@@ -384,14 +414,17 @@ module RailsAiAdmin
384
414
  # rule as search; the measured field must be declared aggregatable.
385
415
  class AggregateRecords < Tool
386
416
  description "Calculate count, sum, average, minimum or maximum over one resource's records, optionally grouped by a " \
387
- "category field, with the same optional text, typed filters and list scope as search_records. describe_resource " \
388
- "lists the aggregatable fields and the group_by fields. Every record you may see is included unless you pass scope."
417
+ "category field, with the same optional text, typed filters and list scope as search_records. For totals per day, " \
418
+ "week, month or year, pass a group_by_period field as group_by with period; groups are oldest first in the user's " \
419
+ "time zone, weeks start on Monday, and each group is the period's first day. describe_resource lists the " \
420
+ "aggregatable, group_by and group_by_period fields. Every record you may see is included unless you pass scope."
389
421
  parameters({ "type" => "object", "required" => %w[resource function], "additionalProperties" => false,
390
422
  "properties" => {
391
423
  "resource" => { "type" => "string" },
392
424
  "function" => { "type" => "string", "enum" => Queries::List::AGGREGATE_FUNCTIONS },
393
425
  "field" => { "type" => "string", "description" => "An aggregatable field from describe_resource; omit for count" },
394
- "group_by" => { "type" => "string", "description" => "Optional group_by field from describe_resource" },
426
+ "group_by" => { "type" => "string", "description" => "Optional group_by field, or a group_by_period field with period" },
427
+ "period" => { "type" => "string", "enum" => Queries::List::PERIODS, "description" => "Calendar period for a group_by_period field" },
395
428
  "query" => { "type" => "string", "maxLength" => 200 },
396
429
  "filters" => { "type" => "object", "description" => "Field name to {operator: value}, as for search_records",
397
430
  "additionalProperties" => { "type" => "object", "additionalProperties" => FILTER_VALUE_SCHEMA } },
@@ -402,11 +435,13 @@ module RailsAiAdmin
402
435
 
403
436
  private
404
437
 
405
- def perform(tool_call:, resource:, function:, field: nil, group_by: nil, query: nil, filters: nil, scope: nil)
438
+ def perform(tool_call:, resource:, function:, field: nil, group_by: nil, period: nil, query: nil, filters: nil, scope: nil)
406
439
  resource = @session.resource(resource)
407
- raise AccessDenied, "INVALID_QUERY" unless function.is_a?(String) && (field.nil? || field.is_a?(String)) && (group_by.nil? || group_by.is_a?(String))
408
- result = Queries::List.new(@session.context, resource).aggregate(function: function, field: field, group_by: group_by,
409
- search: query.presence, filters: wire_filters(filters), scope: list_scope(scope))
440
+ unless function.is_a?(String) && [ field, group_by, period ].all? { |value| value.nil? || value.is_a?(String) }
441
+ raise AccessDenied, "INVALID_QUERY"
442
+ end
443
+ result = Queries::List.new(@session.context, resource, assistant: true).aggregate(function: function, field: field, group_by: group_by,
444
+ period: period, search: query.presence, filters: wire_filters(filters), scope: list_scope(scope))
410
445
  references = reference_resolver(@session.access(resource))
411
446
  if result.group_by&.scalar_type == :belongs_to
412
447
  references.prime(result.group_by, result.groups.filter_map { |group| group.key&.to_s })
@@ -416,8 +451,13 @@ module RailsAiAdmin
416
451
  entry["value"] = measure(result.field, function, result.value) if result.field
417
452
  if result.group_by
418
453
  entry["group_by"] = result.group_by.name.to_s
454
+ if result.period
455
+ entry["period"] = result.period
456
+ entry["time_zone"] = @session.context.time_zone if result.group_by.scalar_type == :datetime
457
+ end
419
458
  entry["groups"] = result.groups.map do |group|
420
- item = { "group" => typed(result.group_by, group.key, references), "count" => group.count }
459
+ key = result.period ? group.key&.iso8601 : typed(result.group_by, group.key, references)
460
+ item = { "group" => key, "count" => group.count }
421
461
  item["value"] = measure(result.field, function, group.value) if result.field
422
462
  item
423
463
  end
@@ -616,7 +656,7 @@ module RailsAiAdmin
616
656
  # The same records search_records would page through, one past the limit.
617
657
  def matching_ids(resource, query, filters, scope)
618
658
  model = resource.model_class
619
- Queries::List.new(@session.context, resource).relation(search: query.presence, filters: wire_filters(filters), scope: list_scope(scope))
659
+ Queries::List.new(@session.context, resource, assistant: true).relation(search: query.presence, filters: wire_filters(filters), scope: list_scope(scope))
620
660
  .limit(Selections::Builder::LIMIT + 1).pluck(model.arel_table[model.primary_key]).map(&:to_s)
621
661
  end
622
662
  end
@@ -50,3 +50,4 @@ require_relative "assistant/runtime"
50
50
  require_relative "assistant/coordinator"
51
51
  require_relative "assistant/continuation"
52
52
  require_relative "assistant/transcript"
53
+ require_relative "assistant/evaluation"
@@ -18,13 +18,7 @@ module RailsAiAdmin
18
18
  end
19
19
 
20
20
  def relation
21
- relation = @adapter.scope(context: context, resource: resource, relation: resource.model_class.all)
22
- unless relation.is_a?(ActiveRecord::Relation) && relation.klass == resource.model_class
23
- raise ConfigurationError, "Policy scope must return the resource's ActiveRecord relation"
24
- end
25
- if relation.limit_value || relation.offset_value || relation.select_values.any? || relation.group_values.any? || !relation.having_clause.empty? || !relation.from_clause.empty?
26
- raise ConfigurationError, "Policy scope must be a complete filter relation without limit, offset, select, group, having or from"
27
- end
21
+ relation = validate_policy_scope!(@adapter.scope(context: context, resource: resource, relation: resource.model_class.all))
28
22
  return relation unless resource.soft_delete?
29
23
  relation.where(resource.model_class.arel_table[resource.soft_delete].eq(nil))
30
24
  end
@@ -33,16 +27,20 @@ module RailsAiAdmin
33
27
  # the deleted-records page and restore read them.
34
28
  def discarded_relation
35
29
  raise AccessDenied unless resource.soft_delete?
36
- scoped = @adapter.scope(context: context, resource: resource, relation: resource.model_class.all)
37
- raise ConfigurationError, "Policy scope must return the resource's ActiveRecord relation" unless scoped.is_a?(ActiveRecord::Relation) && scoped.klass == resource.model_class
30
+ scoped = validate_policy_scope!(@adapter.scope(context: context, resource: resource, relation: resource.model_class.all))
38
31
  column = resource.model_class.arel_table[resource.soft_delete]
39
32
  scoped.where(column.not_eq(nil)).reorder(column.desc, resource.model_class.arel_table[resource.model_class.primary_key].desc)
40
33
  end
41
34
 
42
35
  def find!(id, action: :show, lock: false)
43
- scoped = relation
44
- scoped = scoped.lock if lock
45
- record = scoped.find(id)
36
+ record = if lock
37
+ model = resource.model_class
38
+ locked = model.unscoped.lock.find_by(model.primary_key => id)
39
+ raise AccessDenied unless locked && relation.where(model.primary_key => locked.id).exists?
40
+ locked
41
+ else
42
+ relation.find(id)
43
+ end
46
44
  authorize!(action, record)
47
45
  record
48
46
  rescue ActiveRecord::RecordNotFound
@@ -53,10 +51,11 @@ module RailsAiAdmin
53
51
  # Pages address a record only by the primary key's canonical text; the
54
52
  # trusted Runner API still canonicalizes through the scoped lookup.
55
53
  def canonical_id?(id)
56
- return id.positive? if id.is_a?(Integer)
54
+ type = resource.model_class.type_for_attribute(resource.model_class.primary_key).type
55
+ return type == :integer && id.positive? && id <= 2**63 - 1 if id.is_a?(Integer)
57
56
  return false unless id.is_a?(String) && id.valid_encoding? && id.bytesize.between?(1, 150) && !id.match?(/[[:cntrl:]]|[[:space:]]/)
58
- case resource.model_class.type_for_attribute(resource.model_class.primary_key).type
59
- when :integer then id.match?(/\A[1-9][0-9]{0,18}\z/)
57
+ case type
58
+ when :integer then id.match?(/\A[1-9][0-9]{0,18}\z/) && Integer(id, 10) <= 2**63 - 1
60
59
  when :uuid then id.match?(/\A[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}\z/)
61
60
  else true
62
61
  end
@@ -64,9 +63,9 @@ module RailsAiAdmin
64
63
 
65
64
  VIEWS = %i[index show create edit].freeze
66
65
 
67
- def fields(action, record = nil, operation: nil, view: nil)
66
+ def fields(action, record = nil, operation: nil, view: nil, assistant: false)
68
67
  view = write_view(operation, view) if action == :write
69
- granted = permission_fields(action, record, operation: operation, view: view)
68
+ granted = permission_fields(action, record, operation: operation, view: view, assistant: assistant)
70
69
  action == :read && view ? granted.select { |field| field.visible_on?(view) } : granted
71
70
  end
72
71
 
@@ -158,7 +157,9 @@ module RailsAiAdmin
158
157
  definition = RailsAiAdmin.operation_registry.fetch(resource, operation)
159
158
  return [] unless definition.custom?
160
159
  names = @adapter.respond_to?(:operation_fields) ? @adapter.operation_fields(context: context, resource: resource, operation: operation.to_sym, record: record) : []
161
- raise ConfigurationError, "Operation fields must be an array" unless names.is_a?(Array)
160
+ unless names.is_a?(Array) && names.all? { |name| name.is_a?(String) || name.is_a?(Symbol) }
161
+ raise ConfigurationError, "Operation fields must be an array of names"
162
+ end
162
163
  names = names.map(&:to_sym)
163
164
  definition.handler_class.input.select { |field| names.include?(field.name) }
164
165
  end
@@ -227,6 +228,16 @@ module RailsAiAdmin
227
228
 
228
229
  private
229
230
 
231
+ def validate_policy_scope!(relation)
232
+ unless relation.is_a?(ActiveRecord::Relation) && relation.klass == resource.model_class
233
+ raise ConfigurationError, "Policy scope must return the resource's ActiveRecord relation"
234
+ end
235
+ if relation.limit_value || relation.offset_value || relation.select_values.any? || relation.group_values.any? || !relation.having_clause.empty? || !relation.from_clause.empty?
236
+ raise ConfigurationError, "Policy scope must be a complete filter relation without limit, offset, select, group, having or from"
237
+ end
238
+ relation
239
+ end
240
+
230
241
  # The stored Action Text HTML, or nil. Pages sanitize it when they show it.
231
242
  def read_rich_text(record, field)
232
243
  unless record.class.reflect_on_association("rich_text_#{field.column}")
@@ -245,7 +256,7 @@ module RailsAiAdmin
245
256
  raise ConfigurationError, "references fields must name a has_many or has_and_belongs_to_many association"
246
257
  end
247
258
  ids = ActiveRecord::Base.while_preventing_writes { record.public_send(field.column) }
248
- ids.map { |id| id.to_s.freeze }.uniq.sort.freeze
259
+ ids.map { |id| id.to_s.freeze }.uniq.sort.first(Fields::Association::MAX_BATCH).freeze
249
260
  end
250
261
 
251
262
  # At most 100 files, oldest first, each with its attachment id.
@@ -276,7 +287,7 @@ module RailsAiAdmin
276
287
  end
277
288
  protected :granted_names
278
289
 
279
- def permission_fields(action, record, operation: nil, view: nil)
290
+ def permission_fields(action, record, operation: nil, view: nil, assistant: false)
280
291
  raise ConfigurationError, "Unknown presentation view" if view && !VIEWS.include?(view)
281
292
  names = granted_names(action, record)
282
293
  selected = resource.fields.select do |field|
@@ -288,7 +299,7 @@ module RailsAiAdmin
288
299
  (action != :search || !field.virtual? && field.options[:searchable]) &&
289
300
  (action != :sort || !field.virtual? && field.options[:sortable]) &&
290
301
  (action != :filter || !field.virtual? && field.filter_operators.any?) &&
291
- (!%i[search sort].include?(action) || field.scalar_type != :belongs_to || reference_title_granted?(field, action))
302
+ (!%i[search sort].include?(action) || field.scalar_type != :belongs_to || reference_title_granted?(field, action, assistant: assistant))
292
303
  end
293
304
  mask = presentation_mask(record, view) if view
294
305
  selected = selected.select { |field| mask.include?(field.name) } if mask
@@ -300,13 +311,13 @@ module RailsAiAdmin
300
311
  # title there. A title that is itself a reference never qualifies, and
301
312
  # only the title is checked: the target's own references are not, so a
302
313
  # self-reference or a cycle of references cannot recurse.
303
- def reference_title_granted?(field, action)
314
+ def reference_title_granted?(field, action, assistant: false)
304
315
  target = Fields::Association.target(field)
305
316
  title = target.fields.find { |candidate| candidate.name == target.title }
306
317
  return false if title.nil? || title.virtual? || title.hidden? || Field::REFERENCE_TYPES.include?(title.scalar_type)
307
318
  return false unless title.options[action == :sort ? :sortable : :searchable]
308
319
  access = self.class.new(context, target)
309
- access.authorize!(:index)
320
+ assistant ? access.authorize_assistant! : access.authorize!(:index)
310
321
  access.granted_names(action).include?(title.name)
311
322
  rescue AccessDenied
312
323
  false
@@ -32,10 +32,13 @@ module RailsAiAdmin
32
32
  def allowed?(context:, action:, resource:, record: nil)
33
33
  return false unless ACTIONS.include?(action.to_sym) || resource.operation_declarations.key?(action.to_sym)
34
34
  klass = policy_class(resource)
35
+ return false unless klass
35
36
  target = record || (action.to_sym == :create ? scope(context: context, resource: resource, relation: resource.model_class.all).new : resource.model_class)
36
- return false unless klass && klass.new(context, target).respond_to?("#{action}?")
37
- Pundit.authorize(context, target, "#{action}?", policy_class: klass)
38
- true
37
+ query = :"#{action}?"
38
+ policy = klass.new(context, target)
39
+ return false unless policy.respond_to?(query)
40
+ return false if Object.ancestors.include?(policy.method(query).owner)
41
+ policy.public_send(query) == true
39
42
  rescue Pundit::NotAuthorizedError
40
43
  false
41
44
  rescue StandardError => error
@@ -31,7 +31,7 @@ module RailsAiAdmin
31
31
  now = Time.current
32
32
  queued = BatchItem.where(status: "queued").where("next_attempt_at IS NULL OR next_attempt_at <= ?", now)
33
33
  stale = BatchItem.where(status: "running").where("lease_expires_at IS NULL OR lease_expires_at <= ?", now)
34
- ids = queued.or(stale).distinct.limit(limit).pluck(:parent_run_id)
34
+ ids = queued.or(stale).group(:parent_run_id).order(BatchItem.arel_table[:created_at].minimum.asc, :parent_run_id).limit(limit).pluck(:parent_run_id)
35
35
  ids.count do |ref|
36
36
  if inline
37
37
  run(ref)
@@ -100,8 +100,8 @@ module RailsAiAdmin
100
100
  next_attempt_at: retryable ? Time.current + [ 2**item.attempts, 60 ].min : nil,
101
101
  completed_at: retryable ? nil : Time.current)
102
102
  AuditEvent.create!(actor_ref: parent.actor_ref, tenant_ref: parent.tenant_ref, resource_key: parent.resource_key,
103
- operation: parent.operation, status: "rejected", code: result.code, correlation_ref: item.operation_run_id,
104
- origin: parent.origin, changed_fields: [], created_at: Time.current)
103
+ operation: parent.operation, status: "rejected", code: result.code, record_id: item.target_id,
104
+ correlation_ref: item.operation_run_id, origin: parent.origin, changed_fields: [], created_at: Time.current)
105
105
  Contract.refresh!(parent)
106
106
  end
107
107
  raise AccessDenied, "FENCED" unless lease_deadline > Time.current
@@ -44,7 +44,7 @@ module RailsAiAdmin
44
44
  parent_run_id: nil).where.not(selection_id: nil).where.not(status: "proposed").order(created_at: :desc, id: :desc).limit(50).pluck(:id)
45
45
  refs.filter_map do |ref|
46
46
  fetch(context: context, job_ref: ref, summary: true)
47
- rescue AccessDenied
47
+ rescue AccessDenied, ConfigurationError
48
48
  nil
49
49
  end
50
50
  end
@@ -29,6 +29,13 @@ module RailsAiAdmin
29
29
  # builds a RubyLLM::Context per admin Context; global RubyLLM settings
30
30
  # are never read for credentials or changed.
31
31
  :assistant, :assistant_adapter, :assistant_model, :assistant_provider, :assistant_protocol,
32
+ # Up to three models RubyLLM tries in order when the assistant_model
33
+ # request fails with a rate limit, overload, server or connection error.
34
+ :assistant_fallback_models,
35
+ # Ask the provider to cache the instructions and tool definitions every
36
+ # request repeats (true by default). Anthropic-style providers then bill
37
+ # repeated input at their cache-read price; OpenAI caches on its own.
38
+ :assistant_prompt_caching,
32
39
  # Messages one actor may send the assistant in any 24 hours; nil removes
33
40
  # the limit. Each message can cost several provider calls.
34
41
  :assistant_daily_message_limit,
@@ -84,6 +91,8 @@ module RailsAiAdmin
84
91
  @assistant_model = nil
85
92
  @assistant_provider = nil
86
93
  @assistant_protocol = nil
94
+ @assistant_fallback_models = []
95
+ @assistant_prompt_caching = true
87
96
  @assistant_daily_message_limit = 100
88
97
  @assistant_daily_token_limit = nil
89
98
  @assistant_daily_cost_limit = nil
@@ -97,16 +106,24 @@ module RailsAiAdmin
97
106
  @sign_out_method = :delete
98
107
  end
99
108
 
109
+ CONSTANT_NAME = /\A[A-Z]\w*(?:::[A-Z]\w*)*\z/.freeze
100
110
  # Validates and freezes the boot configuration without reading domain tables.
101
111
  def finalize!
102
- [ context_adapter, authorization_adapter ].compact.each do |name|
103
- raise ConfigurationError, "Adapters must be constant name strings" unless name.is_a?(String) && name.match?(/\A[A-Z]\w*(?:::[A-Z]\w*)*\z/)
112
+ return self if frozen?
113
+ unless context_adapter.nil? || context_adapter.is_a?(String) && context_adapter.match?(CONSTANT_NAME)
114
+ raise ConfigurationError, "Adapters must be constant name strings"
104
115
  end
105
- unless resources.is_a?(Array) && resources.all? { |name| name.is_a?(String) }
116
+ unless authorization_adapter.is_a?(String) && authorization_adapter.match?(CONSTANT_NAME)
117
+ raise ConfigurationError, "Adapters must be constant name strings"
118
+ end
119
+ unless resources.is_a?(Array) && resources.all? { |name| name.is_a?(String) && name.match?(CONSTANT_NAME) }
106
120
  raise ConfigurationError, "resources must contain constant name strings"
107
121
  end
108
- raise ConfigurationError, "intent_ttl must be between 60 and 3600 seconds" unless (60..3600).cover?(intent_ttl)
109
- unless work_handlers.is_a?(Hash) && work_handlers.all? { |kind, name| kind.is_a?(String) && kind.match?(/\A[a-z][a-z0-9_.-]{0,99}\z/) && name.is_a?(String) && name.match?(/\A[A-Z]\w*(?:::[A-Z]\w*)*\z/) } && [ true, false ].include?(outbox_auto_dispatch)
122
+ unless title.is_a?(String) && title.valid_encoding? && title.length.between?(1, 120) && !title.match?(/[[:cntrl:]]/)
123
+ raise ConfigurationError, "title must be 1 to 120 characters of plain text"
124
+ end
125
+ raise ConfigurationError, "intent_ttl must be between 60 and 3600 seconds" unless (intent_ttl.is_a?(Numeric) || intent_ttl.is_a?(ActiveSupport::Duration)) && (60..3600).cover?(intent_ttl)
126
+ unless work_handlers.is_a?(Hash) && work_handlers.all? { |kind, name| kind.is_a?(String) && kind.match?(/\A[a-z][a-z0-9_.-]{0,99}\z/) && name.is_a?(String) && name.match?(CONSTANT_NAME) } && [ true, false ].include?(outbox_auto_dispatch)
110
127
  raise ConfigurationError, "work_handlers needs stable string keys/class names and outbox_auto_dispatch must be boolean"
111
128
  end
112
129
  raise ConfigurationError, "collection_auto_dispatch must be boolean" unless [ true, false ].include?(collection_auto_dispatch)
@@ -159,6 +176,7 @@ module RailsAiAdmin
159
176
  context_adapter&.freeze
160
177
  authorization_adapter.freeze
161
178
  [ assistant_adapter, assistant_model, assistant_provider, assistant_protocol ].each { |value| value&.freeze }
179
+ assistant_fallback_models.each(&:freeze).freeze
162
180
  freeze
163
181
  end
164
182
 
@@ -183,9 +201,14 @@ module RailsAiAdmin
183
201
  end
184
202
 
185
203
  PROVIDER_NAME = /\A[a-z][a-z0-9_]{0,39}\z/
204
+ MODEL_ID = %r{\A[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}\z}
186
205
 
187
206
  def validate_assistant!
188
207
  raise ConfigurationError, "assistant must be boolean" unless [ true, false ].include?(assistant)
208
+ models = assistant_fallback_models
209
+ unless models.is_a?(Array) && models.all? { |id| id.is_a?(String) }
210
+ raise ConfigurationError, "assistant_fallback_models must list at most three other model ids"
211
+ end
189
212
  return unless assistant
190
213
  unless defined?(::RubyLLM::Railtie)
191
214
  raise ConfigurationError, "assistant requires the host to load ruby_llm (add it to the Gemfile)"
@@ -193,12 +216,17 @@ module RailsAiAdmin
193
216
  if (problem = self.class.optional_gem_problem("ruby_llm", "assistant"))
194
217
  raise ConfigurationError, problem
195
218
  end
196
- unless assistant_adapter.is_a?(String) && assistant_adapter.match?(/\A[A-Z]\w*(?:::[A-Z]\w*)*\z/)
219
+ unless assistant_adapter.is_a?(String) && assistant_adapter.match?(CONSTANT_NAME)
197
220
  raise ConfigurationError, "assistant_adapter must be a constant name string"
198
221
  end
199
- unless assistant_model.is_a?(String) && assistant_model.match?(/\A[A-Za-z0-9][A-Za-z0-9._:\/-]{0,99}\z/)
222
+ unless assistant_model.is_a?(String) && assistant_model.match?(MODEL_ID)
200
223
  raise ConfigurationError, "assistant_model must name one model"
201
224
  end
225
+ raise ConfigurationError, "assistant_prompt_caching must be boolean" unless [ true, false ].include?(assistant_prompt_caching)
226
+ unless models.size <= 3 && models.all? { |id| id.match?(MODEL_ID) } &&
227
+ models.uniq.size == models.size && !models.include?(assistant_model)
228
+ raise ConfigurationError, "assistant_fallback_models must list at most three other model ids"
229
+ end
202
230
  unless assistant_daily_message_limit.nil? || assistant_daily_message_limit.is_a?(Integer) && assistant_daily_message_limit.between?(1, 100_000)
203
231
  raise ConfigurationError, "assistant_daily_message_limit must be nil or a whole number from 1 to 100000"
204
232
  end
@@ -208,7 +236,10 @@ module RailsAiAdmin
208
236
  unless assistant_daily_cost_limit.nil? || cost_limit?(assistant_daily_cost_limit)
209
237
  raise ConfigurationError, "assistant_daily_cost_limit must be nil or an amount in US dollars above 0 and up to 1000000"
210
238
  end
211
- self.assistant_daily_cost_limit = BigDecimal(assistant_daily_cost_limit.to_s).freeze unless assistant_daily_cost_limit.nil?
239
+ unless assistant_daily_cost_limit.nil?
240
+ limit = assistant_daily_cost_limit.is_a?(Rational) ? BigDecimal(assistant_daily_cost_limit, 16) : BigDecimal(assistant_daily_cost_limit.to_s)
241
+ self.assistant_daily_cost_limit = limit.freeze
242
+ end
212
243
  unless assistant_retention.nil? || assistant_retention.is_a?(ActiveSupport::Duration) && assistant_retention.between?(1.day, 3660.days)
213
244
  raise ConfigurationError, "assistant_retention must be nil or a duration from 1 day to 10 years, such as 90.days"
214
245
  end
@@ -55,13 +55,15 @@ module RailsAiAdmin
55
55
  unless ::RailsToolViews::Surface.table_exists? && ::RailsToolViews::ActionExecution.table_exists?
56
56
  return Check.new("surfaces", :error, "Run the rails_tool_views installer migrations before enabling admin Surfaces.")
57
57
  end
58
- Integrations::ToolViews.ensure_registered!
58
+ Integrations::ToolViews.check_registration!
59
59
  operations = @registry.resources.sum { |resource| resource.operation_declarations.keys.count { |key| resource.surface_operation?(key) } }
60
60
  assistant = @configuration.respond_to?(:assistant) && @configuration.assistant
61
61
  Check.new("surfaces", :review, "#{Integrations::ToolViews::KEY} is registered for #{operations} member operations through admin-owned endpoints. " \
62
62
  "#{assistant ? 'Assistant proposals present it and confirmed outcomes continue their chat once.' : 'Assistant presentation is off.'}")
63
63
  rescue ConfigurationError => error
64
64
  Check.new("surfaces", :error, error.message)
65
+ rescue ActiveRecord::ActiveRecordError
66
+ Check.new("surfaces", :error, "Cannot inspect rails_tool_views tables. Check database connectivity and pending migrations.")
65
67
  end
66
68
 
67
69
  # Reports whether the opt-in MCP endpoint can authenticate tokens.
@@ -72,6 +74,8 @@ module RailsAiAdmin
72
74
  active = Mcp::AccessToken.active.count
73
75
  Check.new("mcp", :review, "MCP clients use personal access tokens (#{active} active). Each request resolves the owner through resolve_job " \
74
76
  "and applies the assistant? grant and the owner's current grants; proposals wait for confirmation in the admin. Serve it over HTTPS only.")
77
+ rescue ActiveRecord::ActiveRecordError
78
+ Check.new("mcp", :error, "Cannot inspect MCP access token table. Check database connectivity and pending migrations.")
75
79
  end
76
80
 
77
81
  # Reports whether opt-in admin Chat can run. It never calls the adapter or
@@ -84,18 +88,25 @@ module RailsAiAdmin
84
88
  missing = [ Assistant::Chat, Assistant::Message, Assistant::Turn, ::RubyLLM::ActiveRecord::ToolCall, ::RubyLLM::ActiveRecord::Usage ]
85
89
  .reject(&:table_exists?).map(&:table_name)
86
90
  return Check.new("assistant", :error, "Run rails_ai_admin:assistant and db:migrate; missing tables: #{missing.join(', ')}.") if missing.any?
87
- adapter = @configuration.assistant_adapter.safe_constantize
88
- unless adapter.is_a?(Class) && adapter.method_defined?(:llm_context) && adapter.instance_method(:llm_context).parameters.include?([ :keyreq, :context ])
91
+ adapter = @configuration.assistant_adapter&.safe_constantize
92
+ unless adapter.is_a?(Class) && adapter.respond_to?(:new) &&
93
+ accepts_arguments?(adapter.method(:new), 0, []) &&
94
+ accepts_arguments?(adapter.instance_method(:initialize), 0, []) &&
95
+ adapter.public_instance_methods.include?(:llm_context) &&
96
+ accepts_arguments?(adapter.instance_method(:llm_context), 0, [ :context ])
89
97
  return Check.new("assistant", :error, "#{@configuration.assistant_adapter} must define llm_context(context:) returning a RubyLLM::Context or nil.")
90
98
  end
91
99
  job = @configuration.context_adapter&.safe_constantize
92
- unless job.is_a?(Class) && job.method_defined?(:resolve_job)
93
- return Check.new("assistant", :error, "Assistant turns run in jobs; the context adapter must define resolve_job.")
100
+ unless job.is_a?(Class) && job.public_instance_methods.include?(:resolve_job) &&
101
+ accepts_arguments?(job.instance_method(:resolve_job), 0, %i[actor_ref tenant_ref security_version])
102
+ return Check.new("assistant", :error, "Assistant turns run in jobs; the context adapter must define resolve_job(actor_ref:, tenant_ref:, security_version:).")
94
103
  end
95
- Check.new("assistant", :review, "Model #{@configuration.assistant_model}; tools apply each actor's current grants and the independent assistant? grant. " \
104
+ fallbacks = @configuration.assistant_fallback_models
105
+ model = "Model #{@configuration.assistant_model}#{" (fallbacks #{fallbacks.join(', ')})" if fallbacks.any?}"
106
+ Check.new("assistant", :review, "#{model}; tools apply each actor's current grants and the independent assistant? grant. " \
96
107
  "Schedule rails_ai_admin:assistant:scan, keep provider credentials in the adapter's own RubyLLM::Context, and verify real-provider behavior separately. " \
97
108
  "#{assistant_limits}")
98
- rescue NameError, ConfigurationError => error
109
+ rescue NameError, ConfigurationError, ActiveRecord::ActiveRecordError => error
99
110
  Check.new("assistant", :error, "Assistant configuration failed (#{error.class.name}).")
100
111
  end
101
112
 
@@ -121,11 +132,12 @@ module RailsAiAdmin
121
132
  adapter_check("context", config.context_adapter, { resolve: [ 1, [] ] }),
122
133
  adapter_check("policy", config.authorization_adapter, { scope: [ 0, %i[context resource relation] ], allowed?: [ 0, %i[context action resource record] ], fields: [ 0, %i[context resource action record] ] }),
123
134
  autoload_check,
135
+ mount_check,
124
136
  rails_check,
125
137
  policy_preset_check,
126
138
  assistant_check,
127
139
  mcp_check,
128
- Check.new("files", :unsupported, "Private attachment management is not implemented."),
140
+ files_check,
129
141
  selection_check,
130
142
  saved_views_check,
131
143
  Check.new("queue", @work_registry.definitions.empty? && collections.zero? ? :closed : :review,
@@ -270,6 +282,9 @@ module RailsAiAdmin
270
282
  end
271
283
 
272
284
  def adapter_check(kind, name, methods)
285
+ if kind == "policy" && name.nil?
286
+ return Check.new(kind, :error, "authorization_adapter cannot be nil; use RailsAiAdmin::Authorization::Adapter or a host policy adapter class name.")
287
+ end
273
288
  if name.nil? || name == "RailsAiAdmin::Authorization::Adapter"
274
289
  return Check.new(kind, :closed, "Default denies access. Implement and test the host context, scopes, actions and independent field grants.")
275
290
  end
@@ -297,6 +312,26 @@ module RailsAiAdmin
297
312
  (keywords - parameters.filter_map { |kind, name| name if %i[key keyreq].include?(kind) }).empty?
298
313
  end
299
314
 
315
+ def files_check
316
+ fields = @registry.resources.sum { |resource| resource.fields.count { |field| Field::FILE_TYPES.include?(field.scalar_type) } }
317
+ return Check.new("files", :closed, "No resource declares Active Storage file or files fields.") if fields.zero?
318
+ Check.new("files", :review, "#{fields} declared Active Storage attachment #{fields == 1 ? 'field' : 'fields'} served through admin-owned file endpoints under current show/field grants. Verify private storage buckets and attachment grants.")
319
+ end
320
+
321
+ def mount_check
322
+ return unless @application&.respond_to?(:routes)
323
+ require "generators/rails_ai_admin/install/engine_mounts"
324
+ @application.reload_routes_unless_loaded if @application.respond_to?(:reload_routes_unless_loaded)
325
+ mounts = Generators::EngineMounts.names(@application.routes)
326
+ if mounts == [ "rails_ai_admin" ]
327
+ Check.new("mount", :ok, "RailsAiAdmin::Engine is mounted once under the standard rails_ai_admin helper.")
328
+ elsif mounts.empty?
329
+ Check.new("mount", :closed, "RailsAiAdmin::Engine is not mounted.")
330
+ else
331
+ Check.new("mount", :review, "Unexpected engine mount configuration (#{mounts.join(', ')}); use one mount with as: :rails_ai_admin and no dynamic path parameters.")
332
+ end
333
+ end
334
+
300
335
  def autoload_check
301
336
  unless @application
302
337
  return Check.new("autoload", :review, "Run doctor inside the host Rails application to check app/rails_ai_admin loading.")
@@ -330,7 +365,7 @@ module RailsAiAdmin
330
365
  next false unless column
331
366
  case field.scalar_type
332
367
  when :belongs_to then !%i[integer string uuid].include?(column.type)
333
- when :datetime then !%i[datetime timestamp].include?(column.type)
368
+ when :datetime then !%i[datetime timestamp timestamptz].include?(column.type)
334
369
  when :date then column.type != :date
335
370
  when :boolean then column.type != :boolean
336
371
  when :integer then column.type != :integer || model.defined_enums.key?(field.name.to_s)