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
@@ -16,9 +16,12 @@ module RailsAiAdmin
16
16
  AREL_PREDICATES = { "eq" => :eq, "gte" => :gteq, "lte" => :lteq }.freeze
17
17
  OPERATORS = Field::FILTER_OPERATORS.map(&:to_s).freeze
18
18
 
19
- def initialize(context, resource)
19
+ SEARCH_STRICTNESS = { exact: 0, prefix: 1, contains: 2 }.freeze
20
+
21
+ def initialize(context, resource, assistant: false)
20
22
  @access = Authorization::Access.new(context, resource)
21
23
  @resource = resource
24
+ @assistant = assistant == true
22
25
  end
23
26
 
24
27
  # scope: nil uses the declared default when it is currently granted;
@@ -76,16 +79,20 @@ module RailsAiAdmin
76
79
  # filtering by each value would show the same counts. Aggregates run over
77
80
  # the primary keys of the policy relation, so a join in a policy scope
78
81
  # cannot count a record twice. Values are type cast but not formatted.
82
+ # With period, group_by is a date or datetime field the actor may filter
83
+ # by, and groups are calendar periods in the actor's time zone.
79
84
  AGGREGATE_FUNCTIONS = %w[count sum average minimum maximum].freeze
85
+ PERIODS = %w[day week month year].freeze
80
86
  MAX_GROUPS = 25
81
- Aggregate = Data.define(:function, :field, :group_by, :count, :value, :groups, :groups_truncated, :scope)
87
+ Aggregate = Data.define(:function, :field, :group_by, :count, :value, :groups, :groups_truncated, :scope, :period)
82
88
  Group = Data.define(:key, :count, :value)
83
- def aggregate(function:, field: nil, group_by: nil, search: nil, scope: nil, filters: nil)
89
+ def aggregate(function:, field: nil, group_by: nil, period: nil, search: nil, scope: nil, filters: nil)
84
90
  @access.authorize!(:index)
85
91
  raise AccessDenied, "INVALID_QUERY" unless AGGREGATE_FUNCTIONS.include?(function)
92
+ raise AccessDenied, "INVALID_QUERY" unless period.nil? || PERIODS.include?(period) && !group_by.nil?
86
93
  measure = function == "count" ? nil : aggregate_field(field, function)
87
94
  raise AccessDenied, "INVALID_QUERY" if function == "count" && !field.nil?
88
- grouping = group_by.nil? ? nil : group_field(group_by)
95
+ grouping = group_by.nil? ? nil : group_field(group_by, period: !period.nil?)
89
96
  relation, named = filtered_relation(search: search, scope: scope, filters: filters)
90
97
  model = @resource.model_class
91
98
  primary = model.primary_key
@@ -95,7 +102,9 @@ module RailsAiAdmin
95
102
  expressions << table[measure.column].public_send(AREL_AGGREGATES.fetch(function)) if measure
96
103
  count, raw = base.pick(*expressions)
97
104
  groups, truncated = [], false
98
- if grouping
105
+ if grouping && period
106
+ groups, truncated = period_groups(base, table[grouping.column], grouping, period, expressions, measure, function)
107
+ elsif grouping
99
108
  column = table[grouping.column]
100
109
  rows = base.group(column).order(Arel.star.count.desc, column.asc.nulls_last).limit(MAX_GROUPS + 1).pluck(column, *expressions)
101
110
  truncated = rows.size > MAX_GROUPS
@@ -103,7 +112,8 @@ module RailsAiAdmin
103
112
  Group.new(cast(grouping, key), group_count.to_i, measure ? aggregate_value(measure, function, group_raw) : nil)
104
113
  end
105
114
  end
106
- Aggregate.new(function, measure, grouping, count.to_i, measure ? aggregate_value(measure, function, raw) : nil, groups, truncated, named&.name&.to_s)
115
+ Aggregate.new(function, measure, grouping, count.to_i, measure ? aggregate_value(measure, function, raw) : nil, groups, truncated,
116
+ named&.name&.to_s, period)
107
117
  end
108
118
 
109
119
  AREL_AGGREGATES = { "sum" => :sum, "average" => :average, "minimum" => :minimum, "maximum" => :maximum }.freeze
@@ -143,34 +153,100 @@ module RailsAiAdmin
143
153
  private_class_method :coerce_filter
144
154
 
145
155
  # The Arel condition for one validated filter value.
146
- def self.filter_predicate(field, column, operator, value)
156
+ def self.filter_predicate(field, column, operator, value, string_column: nil)
147
157
  case operator.to_s
148
158
  when "in" then column.in(value)
149
159
  when "contains" then column.matches("%#{ActiveRecord::Base.sanitize_sql_like(value)}%", "\\")
150
160
  when "blank"
151
- # Text stores "no value" as NULL or as an empty string.
152
- empty = Field::TEXT_TYPES.include?(field.scalar_type) ? column.eq(nil).or(column.eq("")) : column.eq(nil)
161
+ # Text stores "no value" as NULL or as an empty string; non-text PK columns cannot compare to "".
162
+ allow_empty = field.scalar_type == :id ? (string_column == true) : Field::TEXT_TYPES.include?(field.scalar_type)
163
+ empty = allow_empty ? column.eq(nil).or(column.eq("")) : column.eq(nil)
153
164
  value ? empty : empty.not
154
165
  else column.public_send(AREL_PREDICATES.fetch(operator.to_s), value)
155
166
  end
156
167
  end
157
168
 
169
+ # Deduplicates policy relations that join other tables before counting or
170
+ # paginating, avoiding DISTINCT on PostgreSQL JSON columns.
171
+ def self.unique_records(relation)
172
+ return relation unless relation.joins_values.any? || relation.left_outer_joins_values.any? || relation.eager_loading? || relation.distinct_value
173
+ model = relation.klass
174
+ key = model.primary_key
175
+ ids = relation.reorder(nil).reselect(model.arel_table[key])
176
+ records = model.unscoped.where(key => ids).readonly(relation.readonly_value).strict_loading(relation.strict_loading_value)
177
+ preloads = relation.preload_values | relation.includes_values | relation.eager_load_values
178
+ preloads.any? ? records.preload(*preloads) : records
179
+ end
180
+
158
181
  private
159
182
 
160
183
  def aggregate_field(name, function)
161
- raise AccessDenied, "INVALID_QUERY" unless name.is_a?(String) && name.match?(Field::NAME)
184
+ raise AccessDenied, "INVALID_QUERY" unless name.is_a?(String) && name.valid_encoding? && name.match?(Field::NAME)
162
185
  field = @access.fields(:read).find { |candidate| candidate.name.to_s == name && !candidate.virtual? }
163
186
  raise AccessDenied, "INVALID_QUERY" unless field&.aggregate_functions&.include?(function.to_sym)
164
187
  field
165
188
  end
166
189
 
167
- def group_field(name)
168
- raise AccessDenied, "INVALID_QUERY" unless name.is_a?(String) && name.match?(Field::NAME)
190
+ def group_field(name, period: false)
191
+ raise AccessDenied, "INVALID_QUERY" unless name.is_a?(String) && name.valid_encoding? && name.match?(Field::NAME)
169
192
  field = @access.fields(:filter).find { |candidate| candidate.name.to_s == name }
170
- raise AccessDenied, "INVALID_QUERY" unless field && Field::GROUP_TYPES.include?(field.scalar_type)
193
+ raise AccessDenied, "INVALID_QUERY" unless field && (period ? Field::PERIOD_TYPES : Field::GROUP_TYPES).include?(field.scalar_type)
171
194
  field
172
195
  end
173
196
 
197
+ # Calendar periods, oldest first, ending with the latest dated record's
198
+ # period; periods without records count zero. Each record falls in one
199
+ # period through a CASE over bound boundaries, so SQLite and PostgreSQL
200
+ # agree and datetimes split at midnight in the actor's time zone. Past
201
+ # MAX_GROUPS periods only the latest are returned. Records without a
202
+ # date form a final group whose key is nil, beyond that limit.
203
+ def period_groups(base, column, field, period, expressions, measure, function)
204
+ zone = ActiveSupport::TimeZone[@access.context.time_zone]
205
+ first, last = base.pick(column.minimum, column.maximum).map { |raw| cast(field, raw) }
206
+ starts = []
207
+ if last
208
+ day = ->(value) { field.scalar_type == :datetime ? value.in_time_zone(zone).to_date : value }
209
+ oldest = period_start(day.call(first), period)
210
+ start = period_start(day.call(last), period)
211
+ while start >= oldest && starts.size <= MAX_GROUPS
212
+ starts.unshift(start)
213
+ start = period_advance(start, period, -1)
214
+ end
215
+ end
216
+ truncated = starts.size > MAX_GROUPS
217
+ starts = starts.last(MAX_GROUPS)
218
+ edge = ->(date) { field.scalar_type == :datetime ? zone.local(date.year, date.month, date.day) : date }
219
+ bucket = Arel::Nodes::Case.new.when(column.eq(nil)).then(Arel::Nodes.build_quoted(-1))
220
+ starts.each_with_index do |start, index|
221
+ range = column.gteq(edge.call(start)).and(column.lt(edge.call(period_advance(start, period, 1))))
222
+ bucket = bucket.when(range).then(Arel::Nodes.build_quoted(index))
223
+ end
224
+ # Records before the returned periods fall to -2 and are left out.
225
+ bucket = bucket.else(Arel::Nodes.build_quoted(-2))
226
+ rows = base.group(bucket).pluck(bucket, *expressions).to_h { |index, *values| [ index.to_i, values ] }
227
+ groups = starts.each_with_index.map do |start, index|
228
+ group_count, group_raw = rows.fetch(index, [ 0, nil ])
229
+ Group.new(start, group_count.to_i, measure ? aggregate_value(measure, function, group_raw) : nil)
230
+ end
231
+ if (undated = rows[-1])
232
+ groups << Group.new(nil, undated[0].to_i, measure ? aggregate_value(measure, function, undated[1]) : nil)
233
+ end
234
+ [ groups, truncated ]
235
+ end
236
+
237
+ def period_start(date, period)
238
+ case period
239
+ when "day" then date
240
+ when "week" then date.beginning_of_week(:monday)
241
+ when "month" then date.beginning_of_month
242
+ else date.beginning_of_year
243
+ end
244
+ end
245
+
246
+ def period_advance(date, period, steps)
247
+ date.advance({ "day" => :days, "week" => :weeks, "month" => :months, "year" => :years }.fetch(period) => steps)
248
+ end
249
+
174
250
  # Database results arrive as the adapter returns them (SQLite sums
175
251
  # decimals as floats); each is cast through the column's type.
176
252
  def cast(field, raw)
@@ -192,7 +268,7 @@ module RailsAiAdmin
192
268
  settings = @resource.index
193
269
  table = @resource.model_class.arel_table
194
270
  primary = @resource.model_class.primary_key
195
- sortable = @access.fields(:sort)
271
+ sortable = @access.fields(:sort, assistant: @assistant)
196
272
  field = if sort.present?
197
273
  sortable.find { |entry| entry.name.to_s == sort } || raise(AccessDenied, "INVALID_QUERY")
198
274
  elsif settings.default_sort
@@ -216,18 +292,7 @@ module RailsAiAdmin
216
292
  [ relation, field, direction ]
217
293
  end
218
294
 
219
- # A policy join can return several rows for one record. Paginate and
220
- # count the authorized keys before sorting or projecting model columns.
221
- # Using IDs also avoids DISTINCT on PostgreSQL JSON columns.
222
- def unique_records(relation)
223
- return relation unless relation.joins_values.any? || relation.left_outer_joins_values.any? || relation.eager_loading? || relation.distinct_value
224
- model = relation.klass
225
- key = model.primary_key
226
- ids = relation.reorder(nil).reselect(model.arel_table[key])
227
- records = model.unscoped.where(key => ids).readonly(relation.readonly_value).strict_loading(relation.strict_loading_value)
228
- preloads = relation.preload_values | relation.includes_values | relation.eager_load_values
229
- preloads.any? ? records.preload(*preloads) : records
230
- end
295
+ def unique_records(relation) = self.class.unique_records(relation)
231
296
 
232
297
  def filtered_relation(search:, scope:, filters:)
233
298
  # Leading and trailing spaces are never part of the term (RAA-021).
@@ -249,20 +314,15 @@ module RailsAiAdmin
249
314
  relation = named.apply(relation) if named
250
315
  relation = apply_filters(relation, filters)
251
316
  if search.present?
252
- fields = @access.fields(:search)
317
+ fields = @access.fields(:search, assistant: @assistant)
253
318
  raise AccessDenied, "INVALID_QUERY" if fields.empty?
254
319
  predicates = fields.map do |field|
255
320
  term = ActiveRecord::Base.sanitize_sql_like(search)
256
- pattern = case field.options[:searchable]
257
- when :exact then term
258
- when :contains then "%#{term}%"
259
- else "#{term}%"
260
- end
261
321
  column = @resource.model_class.arel_table[field.column]
262
322
  if field.scalar_type == :belongs_to
263
- column.in(reference_matches(field, pattern))
323
+ column.in(reference_matches(field, term))
264
324
  else
265
- column.matches(pattern, "\\")
325
+ column.matches(search_pattern(search_mode(field), term), "\\")
266
326
  end
267
327
  end
268
328
  relation = relation.where(predicates.reduce(&:or))
@@ -270,6 +330,19 @@ module RailsAiAdmin
270
330
  [ relation, named ]
271
331
  end
272
332
 
333
+ def search_mode(field)
334
+ mode = field.options[:searchable]
335
+ mode == true ? :prefix : mode
336
+ end
337
+
338
+ def search_pattern(mode, term)
339
+ case mode
340
+ when :exact then term
341
+ when :contains then "%#{term}%"
342
+ else "#{term}%"
343
+ end
344
+ end
345
+
273
346
  # A subquery of the target's policy relation: its key and title.
274
347
  def reference_titles(field)
275
348
  relation, model, title = reference_relation(field)
@@ -278,15 +351,19 @@ module RailsAiAdmin
278
351
  end
279
352
 
280
353
  # Keys of target records in the target's policy relation whose title matches.
281
- def reference_matches(field, pattern)
354
+ # Intersects the reference field's match mode with the target title's so a
355
+ # referencing resource cannot weaken an :exact or :prefix target restriction.
356
+ def reference_matches(field, term)
282
357
  relation, model, title = reference_relation(field)
358
+ mode = [ search_mode(field), search_mode(title) ].min_by { |entry| SEARCH_STRICTNESS.fetch(entry, 1) }
283
359
  table = model.arel_table
284
- relation.where(table[title.column].matches(pattern, "\\")).reselect(table[model.primary_key]).arel
360
+ relation.where(table[title.column].matches(search_pattern(mode, term), "\\")).reselect(table[model.primary_key]).arel
285
361
  end
286
362
 
287
363
  def reference_relation(field)
288
364
  target = Fields::Association.target(field)
289
365
  access = Authorization::Access.new(@access.context, target)
366
+ access.authorize_assistant! if @assistant
290
367
  title = target.fields.find { |candidate| candidate.name == target.title }
291
368
  [ access.relation.unscope(:order, :limit, :offset), target.model_class, title ]
292
369
  end
@@ -299,14 +376,37 @@ module RailsAiAdmin
299
376
  raise AccessDenied, "INVALID_QUERY"
300
377
  end
301
378
  granted = @access.fields(:filter).index_by { |field| field.name.to_s }
302
- table = @resource.model_class.arel_table
379
+ model = @resource.model_class
380
+ table = model.arel_table
303
381
  filters.reduce(relation) do |scoped, (name, conditions)|
304
382
  field = granted[name.to_s] or raise AccessDenied, "INVALID_QUERY"
383
+ col_type = model.type_for_attribute(field.column).type
305
384
  conditions.reduce(scoped) do |inner, (operator, raw)|
306
385
  value = self.class.filter_value(field, operator.to_s, raw, time_zone: @access.context.time_zone)
307
- inner.where(self.class.filter_predicate(field, table[field.column], operator, value))
386
+ value = cast_key_filter(field, operator.to_s, value, col_type)
387
+ inner.where(self.class.filter_predicate(field, table[field.column], operator, value, string_column: %i[string text].include?(col_type)))
388
+ end
389
+ end
390
+ end
391
+
392
+ # Ensures raw Arel predicates on integer/UUID key columns receive valid
393
+ # typed values so PostgreSQL never raises InvalidTextRepresentation.
394
+ def cast_key_filter(field, operator, value, col_type)
395
+ return value if operator == "blank" || !%i[belongs_to id].include?(field.scalar_type)
396
+ cast_one = lambda do |item|
397
+ case col_type
398
+ when :integer
399
+ raise AccessDenied, "INVALID_QUERY" unless item.is_a?(String) && item.match?(/\A[1-9][0-9]{0,18}\z/)
400
+ number = Integer(item, 10)
401
+ raise AccessDenied, "INVALID_QUERY" if number > 2**63 - 1
402
+ number
403
+ when :uuid
404
+ raise AccessDenied, "INVALID_QUERY" unless item.is_a?(String) && item.match?(/\A[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}\z/)
405
+ item
406
+ else item
308
407
  end
309
408
  end
409
+ operator == "in" ? value.map(&cast_one) : cast_one.call(value)
310
410
  end
311
411
  end
312
412
  end
@@ -14,7 +14,7 @@ module RailsAiAdmin
14
14
  def strategy(model)
15
15
  return :lock_version if model.locking_enabled? && model.locking_column == "lock_version"
16
16
  column = model.columns_hash["updated_at"]
17
- return :updated_at if column && %i[datetime timestamp].include?(column.type) && model.record_timestamps
17
+ return :updated_at if column && %i[datetime timestamp timestamptz].include?(column.type) && model.record_timestamps
18
18
  nil
19
19
  end
20
20
 
@@ -32,10 +32,15 @@ module RailsAiAdmin
32
32
  end
33
33
  end
34
34
  end
35
+ @rich_text = @entries.each_value.any? { |resource| resource.fields.any? { |field| field.scalar_type == :rich_text } }
35
36
  @entries.freeze
36
37
  freeze
37
38
  end
38
39
 
40
+ # Whether any resource edits rich text, so layouts can load Trix on the
41
+ # first full page instead of only on the edit page reached through Turbo.
42
+ def rich_text? = @rich_text
43
+
39
44
  def fetch(key)
40
45
  @entries.fetch(key.to_s) { raise AccessDenied }
41
46
  end
@@ -4,6 +4,8 @@ module RailsAiAdmin
4
4
  # Redacts admin query values before Rails logs the initial request URL.
5
5
  # The documented mount name is required; its path can be customized/reloaded.
6
6
  class RequestLogFilter
7
+ HEADER_FILTER = /\AHTTP_(?:AUTHORIZATION|COOKIE)\z/i
8
+
7
9
  def initialize(app)
8
10
  @app = app
9
11
  end
@@ -12,10 +14,10 @@ module RailsAiAdmin
12
14
  helpers = Rails.application.routes.url_helpers
13
15
  if helpers.respond_to?(:rails_ai_admin_path)
14
16
  prefix = helpers.rails_ai_admin_path(script_name: "").delete_suffix("/")
15
- path = env["PATH_INFO"].to_s
17
+ path = ActionDispatch::Journey::Router::Utils.normalize_path(env["PATH_INFO"].to_s)
16
18
  if path == prefix || path.start_with?("#{prefix}/")
17
19
  filter = /\A(?!(?:controller|action|resource|id|format)\z)/
18
- env["action_dispatch.parameter_filter"] = Array(env["action_dispatch.parameter_filter"]) + [ filter ]
20
+ env["action_dispatch.parameter_filter"] = Array(env["action_dispatch.parameter_filter"]) + [ filter, HEADER_FILTER ]
19
21
  end
20
22
  end
21
23
  @app.call(env)
@@ -218,6 +218,8 @@ module RailsAiAdmin
218
218
  # Fail at registration rather than on every menu render; explicit labels
219
219
  # were already bounded when declared.
220
220
  Navigation::Settings.caption(label) unless navigation.hidden || navigation.label
221
+ @model_name.freeze
222
+ @label&.freeze
221
223
  @policy_name&.freeze
222
224
  @fields.freeze
223
225
  @scopes.freeze
@@ -227,6 +229,8 @@ module RailsAiAdmin
227
229
  @surface_operations.freeze
228
230
  @has_many.freeze
229
231
  @assistant_operations.freeze
232
+ @assistant_changes.freeze
233
+ @dashboard.freeze
230
234
  self
231
235
  end
232
236
  end
@@ -11,12 +11,12 @@ module RailsAiAdmin
11
11
  end
12
12
  Report = Data.define(:suggestions, :omitted, :available)
13
13
  TYPES = { string: :text, text: :textarea, integer: :integer, decimal: :decimal,
14
- boolean: :boolean, date: :date, datetime: :datetime, timestamp: :datetime, time: :time,
14
+ boolean: :boolean, date: :date, datetime: :datetime, timestamp: :datetime, timestamptz: :datetime, time: :time,
15
15
  json: :json, jsonb: :json }.freeze
16
16
  EMAIL_NAME = /(?:\A|_)email(?:_address)?\z/
17
17
  URL_NAME = /(?:\A|_)(?:url|website|homepage)\z/
18
18
  # Heuristics are a conservative starting point, never a sensitivity proof.
19
- SENSITIVE = /password|token|secret|credential|ciphertext|encrypted|(?:\A|_)(?:api_key|private_key|access_key|signing_key|otp|ssn|salt|session|digest|role|roles|permission|permissions|security_version|admin|superuser)(?:_|\z)|_digest\z/i
19
+ SENSITIVE = /password|passphrase|token|secret|credential|ciphertext|encrypted|(?:\A|_)(?:api_key|private_key|access_key|signing_key|encryption_key|master_key|webhook_key|auth_key|ssh_key|otp|totp|two_factor|recovery_code|backup_code|ssn|tax_id|cvv|cvc|credit_card|iban|salt|session|digest|role|roles|permission|permissions|privilege|privileges|security_version|admin|superuser)(?:_|\z)|_digest\z/i
20
20
  IDENTIFIER = /\A[a-z][a-z0-9_]*\z/
21
21
  # Reassigning a tenant is an authority change, so tenant-like references are
22
22
  # never suggested, even as comments.
@@ -56,15 +56,21 @@ module RailsAiAdmin
56
56
  # A declared non-polymorphic belongs_to may become a commented reference.
57
57
  references = @model.reflect_on_all_associations(:belongs_to).reject(&:polymorphic?).to_h { |association| [ association.foreign_key.to_s, association ] }
58
58
  omitted = 0
59
+ seen = {}
59
60
  suggestions = columns.filter_map do |column|
60
61
  name = column.name
61
62
  next if name == @model.primary_key || name == "id"
62
63
  # The resource declares it with soft_delete instead of as a field.
63
64
  next if name == self.class.soft_delete_column(@model)
64
65
  if (reference = suggest_reference(references[name], column))
66
+ if seen[reference.name]
67
+ omitted += 1
68
+ next
69
+ end
70
+ seen[reference.name] = true
65
71
  next reference
66
72
  end
67
- if !name.match?(IDENTIFIER) || [ "lock_version", @model.inheritance_column ].include?(name) || name.end_with?("_id") || foreign_keys.include?(name) || self.class.sensitive?(@model, name) || self.class.array?(column)
73
+ if seen[name] || !name.match?(IDENTIFIER) || [ "lock_version", @model.inheritance_column ].include?(name) || name.end_with?("_id") || foreign_keys.include?(name) || self.class.sensitive?(@model, name) || self.class.array?(column)
68
74
  omitted += 1
69
75
  next
70
76
  end
@@ -75,7 +81,7 @@ module RailsAiAdmin
75
81
  end
76
82
  options = {}
77
83
  enum = @model.defined_enums[name]
78
- if enum && (!enum.keys.all? { |value| value.length <= 100 } || !enum.size.between?(1, 100))
84
+ if enum && (!enum.keys.all? { |value| value.is_a?(String) && value.valid_encoding? && value.length.between?(1, 100) } || !enum.size.between?(1, 100))
79
85
  omitted += 1
80
86
  next
81
87
  end
@@ -86,7 +92,7 @@ module RailsAiAdmin
86
92
  options[:values] = enum.keys
87
93
  end
88
94
  options[:nullable] = false unless column.null
89
- options[:max_length] = column.limit if %i[text textarea email url].include?(type) && column.limit.is_a?(Integer) && column.limit.positive?
95
+ options[:max_length] = [ column.limit, 65_536 ].min if %i[text textarea email url].include?(type) && column.limit.is_a?(Integer) && column.limit.positive?
90
96
  # Explicit limits keep the declaration reviewable; coercion would
91
97
  # otherwise read the same values from the column on first use.
92
98
  if type == :decimal && column.precision.is_a?(Integer) && column.precision.between?(1, 1000)
@@ -94,6 +100,7 @@ module RailsAiAdmin
94
100
  options[:scale] = column.scale if column.scale.is_a?(Integer) && column.scale.between?(0, column.precision)
95
101
  end
96
102
  options[:readonly] = true if %w[created_at updated_at].include?(name)
103
+ seen[name] = true
97
104
  Suggestion.new(name, type, options.freeze)
98
105
  end
99
106
  Report.new(suggestions.freeze, omitted, true)
@@ -105,6 +112,7 @@ module RailsAiAdmin
105
112
 
106
113
  def suggest_reference(association, column)
107
114
  return unless association && association.name.to_s.match?(IDENTIFIER) && column.name.match?(IDENTIFIER)
115
+ return if column.name == association.name.to_s
108
116
  return if association.name.to_s.match?(TENANT) || self.class.sensitive?(@model, association.name) || self.class.sensitive?(@model, column.name)
109
117
  options = {}
110
118
  options[:foreign_key] = column.name unless column.name == "#{association.name}_id"
@@ -43,7 +43,7 @@ module RailsAiAdmin
43
43
  "job_index" => [ "rails_ai_admin/collection_jobs/index.html.erb", %i[context jobs], [] ],
44
44
  "job_show" => [ "rails_ai_admin/collection_jobs/show.html.erb", %i[context resource job], [] ],
45
45
  "selection" => [ "rails_ai_admin/selections/show.html.erb", %i[context resource selection operations deletable], [] ],
46
- "selection_destroy" => [ "rails_ai_admin/selections/confirm_destroy.html.erb", %i[context resource selection deletable skipped], [] ],
46
+ "selection_destroy" => [ "rails_ai_admin/selections/confirm_destroy.html.erb", %i[context resource selection deletable skipped review_signature], [] ],
47
47
  "resource_deleted" => [ "rails_ai_admin/deleted_records/index.html.erb", %i[context resource records page has_next], [] ],
48
48
  "selection_destroy_result" => [ "rails_ai_admin/selections/destroyed.html.erb", %i[context resource selection deleted skipped failed], [] ]
49
49
  }.freeze
@@ -51,7 +51,7 @@ module RailsAiAdmin
51
51
  navigation = %w[layout resource_index resource_show resource_history resource_new resource_edit resource_form resource_destroy operation_form operation_confirmation operation_failure collection_form collection_confirmation collection_failure job_show selection selection_destroy selection_destroy_result].include?(key)
52
52
  assigns += [ :list_navigation ] if navigation
53
53
  revision = if key == "layout"
54
- 4 # page titles, environment label and the session_links slot (RAA-024)
54
+ 5 # 4: page titles, environment label, session_links (RAA-024); 5: admin_rich_text_assets
55
55
  elsif key == "dashboard"
56
56
  4 # counts, widgets
57
57
  elsif key == "resource_index"
@@ -62,6 +62,8 @@ module RailsAiAdmin
62
62
  5 # intent_ref replaces intent (ADR 0025)
63
63
  elsif %w[resource_destroy resource_errors].include?(key)
64
64
  3 # intent_ref; outcome sentences and RESTRICTED
65
+ elsif key == "selection_destroy"
66
+ 3 # review_signature binds the confirmation to the records shown
65
67
  elsif navigation || %w[input_fields field_form].include?(key)
66
68
  2
67
69
  else
@@ -55,7 +55,7 @@ module RailsAiAdmin
55
55
  elsif stat.symlink? || !stat.file?
56
56
  relative = path.relative_path_from(@root).to_s
57
57
  @findings << Finding.new(relative, :error, "UNSAFE_PATH", relative, nil)
58
- elsif path.basename.to_s.end_with?(".html.erb")
58
+ else
59
59
  @files += 1
60
60
  incomplete! if @files > @max_files
61
61
  @findings << inspect_file(path)
@@ -72,8 +72,12 @@ module RailsAiAdmin
72
72
  relative = path.relative_path_from(@root.join("app/views")).to_s
73
73
  entry = @catalog.for_path(relative)
74
74
  key = entry&.key || relative
75
+ begin
76
+ SafePaths.check!(@root, path)
77
+ rescue ConfigurationError, SystemCallError
78
+ return Finding.new(key, :error, "UNSAFE_PATH", "app/views/#{relative}", nil)
79
+ end
75
80
  return Finding.new(key, :review, "UNCATALOGED", "app/views/#{relative}", nil) unless entry
76
- SafePaths.check!(@root, path)
77
81
  metadata = Metadata.read(path, entry)
78
82
  return Finding.new(key, :review, "UNTRACKED", "app/views/#{relative}", nil) unless metadata
79
83
  code, status = if metadata["contract"] != entry.revision
@@ -6,8 +6,9 @@ module RailsAiAdmin
6
6
  # Do not follow existing parent/leaf symlinks, including dangling links.
7
7
  # The host root itself is explicitly selected and resolved by its owner.
8
8
  def self.check!(root, path)
9
+ raise ConfigurationError, "Override path contains a NUL byte" if root.to_s.include?("\0") || path.to_s.include?("\0")
9
10
  requested_root = Pathname.new(root).expand_path
10
- relative = Pathname.new(path).expand_path.relative_path_from(requested_root)
11
+ relative = Pathname.new(path).expand_path(requested_root).relative_path_from(requested_root)
11
12
  root = requested_root.realpath
12
13
  raise ConfigurationError, "Override path is outside host root" if relative.each_filename.any? { |part| part == ".." }
13
14
  parts = relative.each_filename.to_a
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RailsAiAdmin
4
- VERSION = "0.4.1"
4
+ VERSION = "0.5.0"
5
5
  end
@@ -33,7 +33,7 @@ module RailsAiAdmin
33
33
 
34
34
  def validate!
35
35
  super
36
- unless (5..3600).cover?(lease_duration) && max_attempts.is_a?(Integer) && (1..10).cover?(max_attempts) && (60..7.days).cover?(max_age) && %i[exact current].include?(record_version_policy)
36
+ unless (5..3600).cover?(lease_duration) && lease_duration > max_duration && max_attempts.is_a?(Integer) && (1..10).cover?(max_attempts) && (60..7.days).cover?(max_age) && %i[exact current].include?(record_version_policy)
37
37
  raise ConfigurationError, "Invalid Work lease, retry, lifetime or record-version policy"
38
38
  end
39
39
  raise ConfigurationError, "Work must implement perform" if instance_method(:perform).owner == Work
@@ -51,6 +51,8 @@ require_relative "rails_ai_admin/navigation/saved_views"
51
51
 
52
52
  # Provides an isolated admin engine. The host supplies all authority.
53
53
  module RailsAiAdmin
54
+ Snapshot = Data.define(:registry, :operation_registry, :work_registry, :field_registry)
55
+
54
56
  class << self
55
57
  # Returns the process configuration, frozen after Rails initialization.
56
58
  def configuration
@@ -64,29 +66,31 @@ module RailsAiAdmin
64
66
 
65
67
  # Returns the current registry, rebuilt on Rails reload.
66
68
  def registry
67
- @registry ||= Registry.new([])
69
+ @snapshot&.registry || (@registry ||= Registry.new([]))
68
70
  end
69
71
 
70
72
  def field_registry
71
- return @field_registry if @field_registry&.matches?(configuration.field_types)
73
+ prepared = @snapshot&.field_registry
74
+ return prepared if prepared&.matches?(configuration.field_types)
72
75
  Fields::Registry.new(configuration.field_types)
73
76
  end
74
77
 
75
78
  def operation_registry
76
- @operation_registry ||= Operations::Registry.new([])
79
+ @snapshot&.operation_registry || (@operation_registry ||= Operations::Registry.new([]))
77
80
  end
78
81
 
79
82
  def work_registry
80
- @work_registry ||= Outbox::Registry.new({})
83
+ @snapshot&.work_registry || (@work_registry ||= Outbox::Registry.new({}))
81
84
  end
82
85
 
83
- # Rebuilds the registry from reloadable host constant names.
86
+ # Rebuilds the registry from reloadable host constant names and publishes
87
+ # the tuple as one atomic reference swap.
84
88
  def prepare!
85
89
  fields = Fields::Registry.new(configuration.field_types).validate!
86
90
  resources = Registry.new(configuration.resources)
87
91
  operations = Operations::Registry.new(resources.resources)
88
92
  work = Outbox::Registry.new(configuration.work_handlers)
89
- @registry, @operation_registry, @work_registry, @field_registry = resources, operations, work, fields
93
+ @snapshot = Snapshot.new(registry: resources, operation_registry: operations, work_registry: work, field_registry: fields)
90
94
  end
91
95
  end
92
96
  end
@@ -47,6 +47,26 @@ namespace :rails_ai_admin do
47
47
  puts "Visited #{RailsAiAdmin::Assistant::Coordinator.new.scan_pending!(inline: true)} assistant chats."
48
48
  end
49
49
 
50
+ desc "Ask the questions in FILE as ACTOR in TENANT and check the answers (real provider calls; see the assistant guide)"
51
+ task eval: :environment do
52
+ require "rails_ai_admin/assistant"
53
+ usage = "Usage: bin/rails rails_ai_admin:assistant:eval ACTOR=<actor ref> TENANT=<tenant ref> " \
54
+ "[FILE=config/rails_ai_admin/assistant_eval.yml] [ONLY=case,case] [GRADER=model|none] [REPORT=tmp/eval.json]"
55
+ actor, tenant = ENV["ACTOR"].to_s, ENV["TENANT"].to_s
56
+ abort usage if actor.empty? || tenant.empty?
57
+ adapter = RailsAiAdmin.configuration.context_adapter&.safe_constantize&.new
58
+ abort "rails_ai_admin:assistant:eval: the context adapter must define resolve_job" unless adapter.respond_to?(:resolve_job)
59
+ context = adapter.resolve_job(actor_ref: actor, tenant_ref: tenant, security_version: ENV["SECURITY_VERSION"].presence)
60
+ abort "rails_ai_admin:assistant:eval: #{actor} in #{tenant} is not a current admin person" unless context.is_a?(RailsAiAdmin::Context)
61
+ grader = ENV["GRADER"] == "none" ? false : ENV["GRADER"].presence
62
+ file = Rails.root.join(ENV.fetch("FILE", "config/rails_ai_admin/assistant_eval.yml")).to_s
63
+ evaluation = RailsAiAdmin::Assistant::Evaluation.for(context, dataset: file, grader: grader)
64
+ report = evaluation.run(only: ENV["ONLY"].presence&.split(","))
65
+ puts RailsAiAdmin::Assistant::Evaluation.summary(report)
66
+ report.save(ENV["REPORT"]) if ENV["REPORT"].present?
67
+ exit 1 unless report.passed?
68
+ end
69
+
50
70
  desc "Delete assistant conversations with no message for config.assistant_retention; schedule it daily"
51
71
  task prune: :environment do
52
72
  require "rails_ai_admin/assistant"