Class: Assistant::AudienceToolBuilder

Inherits:
Object
  • Object
show all
Defined in:
app/services/assistant/audience_tool_builder.rb

Overview

Builds RubyLLM::Tool subclasses for audience (subscriber-list) and
email-preference management — Phase 3 of the email_management plan
(doc/tasks/202605301200_EMAIL_MANAGEMENT_TOOL_PLAN.md). Folded into the
email_management service alongside EmailToolBuilder (templates +
campaigns) and CommunicationToolBuilder (one-off drafts).

Provides audience tools:
list_audiences, get_audience, create_static_audience,
create_dynamic_audience, update_audience, add_audience_members,
remove_audience_members, estimate_audience_size
and single-address email-preference tools:
get_email_preferences, update_email_preferences

Safety posture:

  • Writes are email-list-only. customer-type audiences belong to the
    outside-sales pipeline; every mutating tool refuses them.
  • Large audiences need an explicit confirm (plan decision #5): any tool
    committing a dynamic audience over AUDIENCE_CONFIRM_THRESHOLD recipients
    returns a confirm_required payload instead of acting, until re-called
    with confirm: true.
  • Dynamic lists are validated before save through the strict ransack
    probe (Audience#perform_search_query_count
    assert_valid_customer_search_params!), so a bad search key fails fast
    with the ransack error instead of exploding at send time.
  • Member removal is archive-safe: it goes through
    AudienceMember#remove!, which archives members that have delivery
    history rather than hard-deleting them.
  • Email preferences are consent data. Tools act on ONE address at a
    time and only on explicit user instruction; suppression itself stays the
    platform's job (CampaignDelivery enforces EmailPreference regardless).

Usage (via ChatToolBuilder's email-management service):
tools = Assistant::AudienceToolBuilder.tools(audit_context: { user_id: 42 })

rubocop:disable Metrics/ClassLength -- builder defines 10 tools, each with a
long LLM-facing heredoc description; splitting would hurt readability. Mirrors
the same disable on the sibling EmailToolBuilder.

Constant Summary collapse

CRM_AUDIENCE_URL =

URL for the CRM audience screens.

"#{CRM_URL}/audiences".freeze
CRM_EMAIL_PREFERENCE_URL =

URL for the CRM email-preference screens.

"#{CRM_URL}/email_preferences".freeze
AUDIENCE_CONFIRM_THRESHOLD =

Dynamic-audience recipient estimate above which a tool returns
confirm_required instead of committing (plan decision #5).

500
MAX_EMAILS_PER_CALL =

Cap on emails accepted per create/add call — a larger paste is a sign the
model misread the request (bulk imports belong to the CRM CSV flow).

1_000
MEMBER_SAMPLE_SIZE =

Member emails echoed by get_audience as a sample.

25
CATEGORY_FLAGS =

The six per-category opt-out flags on EmailPreference (deliberately
excludes disable_email_tracking, which is a tracking-consent toggle, not
a marketing category).

%w[
  disable_promotions disable_newsletters disable_announcements
  disable_events disable_webinars disable_reviews
].freeze

Class Method Summary collapse

Class Method Details

.add_members(audience, raw_emails, actor_id) ⇒ Hash

Shared member-add for create_static_audience / add_audience_members.
Downcased + deduped input, per-row save so one bad email doesn't fail
the batch, and an informational warning for addresses that have
completely unsubscribed (delivery suppression still applies at send).

An address already on the list as INACTIVE (e.g. bounce-deactivated) is
reactivated and counted in +reactivated+, not silently reported as
"skipped" while receiving nothing.

Returns:

  • (Hash)

    added:, skipped_duplicates:, reactivated:, invalid:, unsubscribed:



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'app/services/assistant/audience_tool_builder.rb', line 116

def add_members(audience, raw_emails, actor_id)
  # No .uniq on purpose: within-batch repeats surface as skipped_duplicates
  # alongside pre-existing members, so the report covers every input row.
  emails = Array(raw_emails).filter_map { |e| e.to_s.strip.downcase.presence }
  existing_by_email = audience.audience_members.index_by { |m| m.email_address&.downcase }

  added = []
  skipped = []
  reactivated = []
  invalid = []
  emails.each do |email|
    existing = existing_by_email[email]
    if existing&.active?
      skipped << email
      next
    elsif existing
      begin
        existing.update!(active: true, updater_id: actor_id)
        reactivated << email
      rescue ActiveRecord::RecordInvalid => e
        invalid << { email: email, error: e.message }
      end
      next
    end

    member = audience.audience_members.build(email_address: email, creator_id: actor_id, updater_id: actor_id)
    if member.save
      added << email
      existing_by_email[email] = member
    else
      invalid << { email: email, error: member.errors.full_messages.to_sentence }
    end
  end

  unsubscribed = EmailPreference.completely_unsubscribed.where(email: added + reactivated).pluck(:email)
  { added: added, skipped_duplicates: skipped, reactivated: reactivated, invalid: invalid, unsubscribed: unsubscribed }
end

.audience_estimate(audience) ⇒ Integer

Returns the live recipient estimate for one audience.

Ungenerated dynamic lists are probed through their customer-search
criteria instead of reading a misleading zero materialized members. A
list whose criteria cannot be probed reads as over-threshold rather than
bypassing a confirmation gate.

Parameters:

  • audience (Audience)

    list whose recipients should be estimated

Returns:

  • (Integer)

    estimated recipient count



181
182
183
184
185
186
187
188
189
190
# File 'app/services/assistant/audience_tool_builder.rb', line 181

def audience_estimate(audience)
  if audience.dynamic? && !audience.audience_members.exists?
    count, = probe_dynamic_criteria(audience.customer_search_params,
                                    max_members: audience.max_members,
                                    add_all_emails: audience.add_all_emails)
    count || (AUDIENCE_CONFIRM_THRESHOLD + 1)
  else
    audience.audience_members.active.count
  end
end

.build_add_audience_members_tool(audit_context) ⇒ Object



583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
# File 'app/services/assistant/audience_tool_builder.rb', line 583

def build_add_audience_members_tool(audit_context)
  captured_ctx = audit_context
  crm_url = CRM_AUDIENCE_URL
  max_emails = MAX_EMAILS_PER_CALL

  klass = Class.new(RubyLLM::Tool) do
    description <<~DESC
      Add member emails to a STATIC audience. Emails are downcased and
      deduplicated; existing members are reported as skipped, malformed
      addresses as invalid — neither fails the call. At most #{max_emails}
      emails per call.

      Refuses dynamic lists (their membership comes from search criteria —
      change them with update_audience) and 'customer' lists. The response
      warns about added addresses that have completely unsubscribed.
    DESC

    parameters type: 'object',
           properties: {
             audience_id: { type: 'integer', description: 'Audience id. Required.' },
             emails: { type: 'array', items: { type: 'string' },
                       description: "Email addresses to add (max #{max_emails}). Required." }
           },
           required: %w[audience_id emails]

    define_method(:name) { 'add_audience_members' }

    define_method(:execute) do |audience_id:, emails:, **_|
      audience, error = Assistant::AudienceToolBuilder.find_audience_or_error(audience_id)
      return error if error

      error = Assistant::AudienceToolBuilder.guard_email_list!(audience)
      return error if error

      unless audience.static?
        return { error: "Audience ##{audience.id} is dynamic — its membership is generated from " \
                        'its search criteria. Use update_audience to change the criteria.' }.to_json
      end
      emails = Array(emails)
      return { error: 'emails must be a non-empty array.' }.to_json if emails.empty?
      return { error: "#{emails.size} emails exceeds the #{max_emails}-per-call cap." }.to_json if emails.size > max_emails

      author = Employee.find_by(id: captured_ctx[:user_id])
      result = Assistant::AudienceToolBuilder.add_members(audience, emails, author&.id)
      warning = if result[:unsubscribed].any?
                  "#{result[:unsubscribed].size} added address(es) have completely unsubscribed — " \
                    'they will be suppressed at delivery.'
                end

      {
        success: true,
        audience_id: audience.id,
        added: result[:added].size,
        added_emails: result[:added],
        reactivated: result[:reactivated],
        skipped_duplicates: result[:skipped_duplicates],
        invalid: result[:invalid],
        warning: warning,
        url: "#{crm_url}/#{audience.id}"
      }.compact.to_json
    rescue StandardError => e
      { error: e.message }.to_json
    end
  end

  klass.new
end

.build_create_dynamic_audience_tool(audit_context) ⇒ Object



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'app/services/assistant/audience_tool_builder.rb', line 454

def build_create_dynamic_audience_tool(audit_context)
  captured_ctx = audit_context
  crm_url = CRM_AUDIENCE_URL
  threshold = AUDIENCE_CONFIRM_THRESHOLD

  klass = Class.new(RubyLLM::Tool) do
    description <<~DESC
      Create a DYNAMIC audience — a subscriber list whose membership is
      generated from saved customer-search criteria (the same ransack params
      as the CRM customer advanced search, e.g. { "state_in": ["customer"],
      "store_id_in": [1] }). Members are NOT generated on create: the list
      regenerates itself when a campaign email using it prepares to send.

      Don't guess the vocabulary: call `describe_customer_search` for the
      full criteria list with live value ranges (states, profiles, product
      lines, the has_ordered/has_not_ordered dormancy keys, …), and
      `run_customer_search` or `estimate_audience_size` to dry-run criteria
      before committing.

      The criteria are validated against the real search before anything is
      saved — an unknown key returns the ransack error so you can correct it.
      Use estimate_audience_size first if you need to iterate on criteria
      without creating lists.

      Sizes over #{threshold} recipients return confirm_required instead of
      creating: show the user the estimate and only re-call with
      confirm: true after they explicitly approve.
    DESC

    parameters type: 'object',
           properties: {
             name: { type: 'string', description: 'List name. Required.' },
             customer_search_params: { type: 'object',
                                       description: 'Ransack customer-search criteria (as in the CRM advanced search). Required.' },
             add_all_emails: { type: 'boolean',
                               description: 'Include every email on each matching customer, not just the main one (default false).' },
             max_members: { type: 'integer',
                            description: 'Cap matching customers to the top N by lifetime revenue before email expansion. With add_all_emails, recipients may exceed N. Optional.' },
             confirm: { type: 'boolean', description: "Required true when the estimate exceeds #{threshold} recipients." }
           },
           required: %w[name customer_search_params]

    define_method(:name) { 'create_dynamic_audience' }

    define_method(:execute) do |name:, customer_search_params:, add_all_emails: false, max_members: nil, confirm: false, **_|
      return { error: 'customer_search_params must be a non-empty object of search criteria.' }.to_json unless customer_search_params.is_a?(Hash) && customer_search_params.present?

      author = Employee.find_by(id: captured_ctx[:user_id])
      audience = Audience.new(name: Audience.ensure_unique_name(name.to_s.strip),
                              list_type: 'dynamic',
                              customer_search_params: customer_search_params,
                              add_all_emails: add_all_emails.to_b,
                              max_members: max_members,
                              creator_id: author&.id)

      # Fail fast on bad criteria BEFORE saving — the strict ransack probe
      # raises on unknown keys.
      count = audience.perform_search_query_count

      gate = Assistant::AudienceToolBuilder.confirm_gate(count, confirm, 'audience')
      return gate if gate

      return { error: "Could not create audience: #{audience.errors.full_messages.to_sentence}" }.to_json unless audience.save

      {
        success: true,
        audience_id: audience.id,
        name: audience.name,
        list_type: audience.list_type,
        estimated_size: count,
        add_all_emails: audience.add_all_emails,
        max_members: audience.max_members,
        url: "#{crm_url}/#{audience.id}",
        message: "Dynamic list created with an estimated #{count} recipients. Members generate " \
                 'when a campaign email using this list prepares to send — attach it to a ' \
                 'campaign and a human reviews/schedules from the CRM.'
      }.to_json
    rescue Ransack::InvalidSearchError => e
      { error: "Invalid customer search criteria: #{e.message}" }.to_json
    rescue StandardError => e
      { error: e.message }.to_json
    end
  end

  klass.new
end

.build_create_static_audience_tool(audit_context) ⇒ Object



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'app/services/assistant/audience_tool_builder.rb', line 373

def build_create_static_audience_tool(audit_context)
  captured_ctx = audit_context
  crm_url = CRM_AUDIENCE_URL
  max_emails = MAX_EMAILS_PER_CALL

  klass = Class.new(RubyLLM::Tool) do
    description <<~DESC
      Create a STATIC audience (fixed subscriber list) and add member emails
      in one call. Static lists change only through explicit add/remove —
      use create_dynamic_audience instead when membership should come from
      customer-search criteria.

      Emails are downcased and deduplicated; addresses already on the list are
      reported as skipped, malformed ones as invalid (neither fails the call).
      At most #{max_emails} emails per call — larger imports belong to the CRM
      CSV import flow. The response warns about added addresses that have
      completely unsubscribed (they still won't receive email — suppression is
      enforced at delivery).
    DESC

    parameters type: 'object',
           properties: {
             name: { type: 'string', description: 'List name. Required.' },
             emails: { type: 'array', items: { type: 'string' },
                       description: "Member email addresses (max #{max_emails}). Optional — an empty list is fine." }
           },
           required: %w[name]

    define_method(:name) { 'create_static_audience' }

    define_method(:execute) do |name:, emails: nil, **_|
      emails = Array(emails)
      if emails.size > max_emails
        return { error: "#{emails.size} emails exceeds the #{max_emails}-per-call cap — " \
                        'use the CRM CSV import for bulk lists.' }.to_json
      end

      author = Employee.find_by(id: captured_ctx[:user_id])
      audience = Audience.new(name: Audience.ensure_unique_name(name.to_s.strip),
                              list_type: 'static', creator_id: author&.id)

      # One transaction: a mid-loop failure must not leave a persisted list
      # holding a partial member set behind a bare error.
      result = nil
      save_error = nil
      Audience.transaction do
        if audience.save
          result = Assistant::AudienceToolBuilder.add_members(audience, emails, author&.id)
        else
          save_error = audience.errors.full_messages.to_sentence
          raise ActiveRecord::Rollback
        end
      end
      return { error: "Could not create audience: #{save_error}" }.to_json if save_error

      warning = if result[:unsubscribed].any?
                  "#{result[:unsubscribed].size} added address(es) have completely unsubscribed " \
                    "(#{result[:unsubscribed].first(5).join(', ')}#{'' if result[:unsubscribed].size > 5}) — " \
                    'they will be suppressed at delivery.'
                end

      {
        success: true,
        audience_id: audience.id,
        name: audience.name,
        list_type: audience.list_type,
        added: result[:added].size,
        reactivated: result[:reactivated],
        skipped_duplicates: result[:skipped_duplicates],
        invalid: result[:invalid],
        warning: warning,
        url: "#{crm_url}/#{audience.id}"
      }.compact.to_json
    rescue StandardError => e
      { error: e.message }.to_json
    end
  end

  klass.new
end

.build_estimate_audience_size_toolObject



729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
# File 'app/services/assistant/audience_tool_builder.rb', line 729

def build_estimate_audience_size_tool
  threshold = AUDIENCE_CONFIRM_THRESHOLD

  klass = Class.new(RubyLLM::Tool) do
    description <<~DESC
      Dry-run a set of dynamic customer-search criteria and return the
      estimated recipient count — WITHOUT creating or changing anything.
      Use this to iterate on criteria with the user before
      create_dynamic_audience / update_audience. Invalid criteria return
      the ransack error so you can correct them.
    DESC

    parameters type: 'object',
           properties: {
             customer_search_params: { type: 'object',
                                       description: 'Ransack customer-search criteria to size. Required.' }
           },
           required: %w[customer_search_params]

    define_method(:name) { 'estimate_audience_size' }

    define_method(:execute) do |customer_search_params:, **_|
      return { error: 'customer_search_params must be a non-empty object of search criteria.' }.to_json unless customer_search_params.is_a?(Hash) && customer_search_params.present?

      count, error = Assistant::AudienceToolBuilder.probe_dynamic_criteria(customer_search_params)
      return error if error

      {
        estimated_size: count,
        confirm_threshold: threshold,
        over_threshold: count > threshold,
        note: 'Estimate only — no list was created or changed. Dynamic lists regenerate ' \
              'from their criteria when a campaign email prepares to send.'
      }.to_json
    rescue StandardError => e
      { error: e.message }.to_json
    end
  end

  klass.new
end

.build_get_audience_toolObject



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'app/services/assistant/audience_tool_builder.rb', line 319

def build_get_audience_tool
  crm_url = CRM_AUDIENCE_URL

  klass = Class.new(RubyLLM::Tool) do
    description <<~DESC
      Read a single audience (subscriber list): name, list_type, member counts,
      attached campaigns, and — for dynamic lists — the customer_search_params
      criteria and add_all_emails flag. Includes a sample of up to
      #{Assistant::AudienceToolBuilder::MEMBER_SAMPLE_SIZE} active member emails.
      Call this before update_audience so you report the current state, not
      stale chat history.
    DESC

    parameters type: 'object',
           properties: {
             audience_id: { type: 'integer', description: 'Audience id. Required.' }
           },
           required: %w[audience_id]

    define_method(:name) { 'get_audience' }

    define_method(:execute) do |audience_id:, **_|
      audience, error = Assistant::AudienceToolBuilder.find_audience_or_error(audience_id)
      return error if error

      result = {
        id: audience.id,
        name: audience.name,
        list_type: audience.list_type,
        member_counts: audience.audience_member_counts_grouped,
        campaigns: audience.campaigns.map { |c| { id: c.id, name: c.name, state: c.state } },
        ad_platforms: Array(audience.ad_platforms),
        sample_member_emails: audience.audience_members.active.order(created_at: :desc)
                                      .limit(Assistant::AudienceToolBuilder::MEMBER_SAMPLE_SIZE).pluck(:email_address),
        created_at: audience.created_at,
        url: "#{crm_url}/#{audience.id}"
      }
      if audience.dynamic?
        result[:customer_search_params] = audience.customer_search_params
        result[:add_all_emails] = audience.add_all_emails
        result[:max_members] = audience.max_members
      end

      result.to_json
    rescue Ransack::InvalidSearchError => e
      { error: "Audience ##{audience_id} has invalid search criteria: #{e.message}" }.to_json
    rescue StandardError => e
      { error: e.message }.to_json
    end
  end

  klass.new
end

.build_get_email_preferences_toolObject



771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
# File 'app/services/assistant/audience_tool_builder.rb', line 771

def build_get_email_preferences_tool
  crm_url = CRM_EMAIL_PREFERENCE_URL

  klass = Class.new(RubyLLM::Tool) do
    description <<~DESC
      Read the email preferences (per-category opt-outs and tracking consent)
      for ONE email address. Returns every disable_* flag, whether the
      address is completely unsubscribed, its last delivery status, and the
      CRM URL. An address with no record receives everything — the tool
      reports found: false and does NOT create a record.
    DESC

    parameters type: 'object',
           properties: {
             email: { type: 'string', description: 'Email address to look up. Required.' }
           },
           required: %w[email]

    define_method(:name) { 'get_email_preferences' }

    define_method(:execute) do |email:, **_|
      normalized = Heatwave::Normalizers.chain(email, :strip, :blank, :downcase)
      return { error: 'email must be a non-empty address.' }.to_json if normalized.blank?

      preference = EmailPreference.find_by(email: normalized)
      unless preference
        return {
          found: false,
          email: normalized,
          message: 'No preference record — this address currently receives all email categories.'
        }.to_json
      end

      {
        found: true,
        email: preference.email,
        flags: Assistant::AudienceToolBuilder.preference_flags(preference),
        completely_unsubscribed: preference.disable_all,
        last_delivery_status: preference.last_delivery_status,
        last_delivery_status_at: preference.last_delivery_status_at,
        url: "#{crm_url}/#{preference.id}"
      }.to_json
    rescue StandardError => e
      { error: e.message }.to_json
    end
  end

  klass.new
end

.build_list_audiences_toolObject



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'app/services/assistant/audience_tool_builder.rb', line 249

def build_list_audiences_tool
  crm_url = CRM_AUDIENCE_URL

  klass = Class.new(RubyLLM::Tool) do
    description <<~DESC
      List audiences (subscriber lists) with their sizes and attached campaigns.
      Use this to find an existing list by name before attaching it to a
      campaign, or to survey what lists exist.

      Returns per list: id, name, list_type, active member count (null for a
      dynamic list whose members haven't been generated yet — its size is
      computed from the search criteria at send time; use estimate_audience_size
      or get_audience for a live number), campaigns, created date, and CRM URL.

      Filters (all optional):
        search    — case-insensitive match on name
        list_type — "static", "dynamic", or "customer"
                    (default: email lists only — static + dynamic)
        limit     — max rows (default 25, max 100)
    DESC

    parameters type: 'object',
           properties: {
             search: { type: 'string', description: 'Case-insensitive match on name.' },
             list_type: { type: 'string', description: 'Filter by type (default: static + dynamic).',
                          enum: Audience::LIST_TYPES },
             limit: { type: 'integer', description: 'Max rows (default 25, max 100).' }
           },
           required: []

    define_method(:name) { 'list_audiences' }

    define_method(:execute) do |search: nil, list_type: nil, limit: 25, **_|
      limit = limit.to_i.clamp(1, 100)
      scope = Audience.includes(:campaigns).order(created_at: :desc)
      scope = list_type.present? ? scope.where(list_type: list_type) : scope.where(list_type: %w[static dynamic])
      scope = scope.where('audiences.name ILIKE ?', "%#{ActiveRecord::Base.sanitize_sql_like(search)}%") if search.present?

      rows = scope.limit(limit).to_a
      # Grouped counts up front — per-row exists?/count queries are an N+1
      # at up to 100 rows. A dynamic list with NO member rows sizes itself
      # from its search criteria at send time; report null + a note rather
      # than running a full customer search per row.
      member_counts = AudienceMember.where(audience_id: rows.map(&:id)).group(:audience_id).count
      active_counts = AudienceMember.where(audience_id: rows.map(&:id)).active.group(:audience_id).count

      audiences = rows.map do |a|
        ungenerated_dynamic = a.dynamic? && !member_counts.key?(a.id)
        row = {
          id: a.id,
          name: a.name,
          list_type: a.list_type,
          active_member_count: ungenerated_dynamic ? nil : active_counts.fetch(a.id, 0),
          campaigns: a.campaigns.map { |c| { id: c.id, name: c.name } },
          created_at: a.created_at.to_date,
          url: "#{crm_url}/#{a.id}"
        }
        row[:size_note] = 'dynamic list — members generate at send time from its search criteria' if ungenerated_dynamic
        row
      end

      { audiences: audiences, count: audiences.size }.to_json
    rescue StandardError => e
      { error: e.message }.to_json
    end
  end

  klass.new
end

.build_remove_audience_members_toolObject



651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
# File 'app/services/assistant/audience_tool_builder.rb', line 651

def build_remove_audience_members_tool
  crm_url = CRM_AUDIENCE_URL
  max_emails = MAX_EMAILS_PER_CALL

  klass = Class.new(RubyLLM::Tool) do
    description <<~DESC
      Remove member emails from a STATIC audience. Members with campaign
      delivery history are ARCHIVED (kept for record-keeping), the rest are
      deleted — the response reports which. Unknown addresses are reported
      as not_found. Refuses dynamic lists (change the criteria with
      update_audience) and 'customer' lists. At most #{max_emails} emails
      per call — larger removals belong to the CRM UI.
    DESC

    parameters type: 'object',
           properties: {
             audience_id: { type: 'integer', description: 'Audience id. Required.' },
             emails: { type: 'array', items: { type: 'string' },
                       description: 'Email addresses to remove. Required.' }
           },
           required: %w[audience_id emails]

    define_method(:name) { 'remove_audience_members' }

    define_method(:execute) do |audience_id:, emails:, **_|
      audience, error = Assistant::AudienceToolBuilder.find_audience_or_error(audience_id)
      return error if error

      error = Assistant::AudienceToolBuilder.guard_email_list!(audience)
      return error if error

      unless audience.static?
        return { error: "Audience ##{audience.id} is dynamic — its membership is generated from " \
                        'its search criteria. Use update_audience to change the criteria.' }.to_json
      end
      emails = Array(emails).filter_map { |e| e.to_s.strip.downcase.presence }.uniq
      return { error: 'emails must be a non-empty array.' }.to_json if emails.empty?
      return { error: "#{emails.size} emails exceeds the #{max_emails}-per-call cap." }.to_json if emails.size > max_emails

      members = audience.audience_members.where('LOWER(email_address) IN (?)', emails)
      by_email = members.index_by { |m| m.email_address.downcase }

      removed = []
      archived = []
      not_found = []
      failed = []
      emails.each do |email|
        member = by_email[email]
        if member.nil?
          not_found << email
          next
        end

        begin
          member.remove!
          (member.archived? ? archived : removed) << email
        rescue ActiveRecord::RecordNotDestroyed, ActiveRecord::InvalidForeignKey => e
          failed << { email: email, error: e.message }
        end
      end

      {
        success: true,
        audience_id: audience.id,
        removed: removed,
        archived: archived,
        not_found: not_found,
        failed: failed,
        url: "#{crm_url}/#{audience.id}"
      }.to_json
    rescue StandardError => e
      { error: e.message }.to_json
    end
  end

  klass.new
end

.build_update_audience_tool(audit_context) ⇒ Object



541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# File 'app/services/assistant/audience_tool_builder.rb', line 541

def build_update_audience_tool(audit_context)
  captured_ctx = audit_context
  threshold = AUDIENCE_CONFIRM_THRESHOLD

  klass = Class.new(RubyLLM::Tool) do
    description <<~DESC
      Modify an existing email audience: rename it, or — for a DYNAMIC list —
      replace its customer-search criteria / add_all_emails flag. Static-list
      membership changes go through add_audience_members /
      remove_audience_members, not this tool.

      New criteria are validated against the real search before saving. When
      the new estimate exceeds #{threshold} recipients the tool returns
      confirm_required instead of saving — show the user and re-call with
      confirm: true after they approve.

      Refuses 'customer'-type lists (outside-sales pipeline).
    DESC

    parameters type: 'object',
           properties: {
             audience_id: { type: 'integer', description: 'Audience id. Required.' },
             name: { type: 'string', description: 'New list name. Optional.' },
             customer_search_params: { type: 'object',
                                       description: 'Replacement search criteria (dynamic lists only). Optional.' },
             add_all_emails: { type: 'boolean', description: 'Replacement add_all_emails flag. Optional.' },
             max_members: { type: 'integer',
                            description: 'Cap matching customers to the top N by lifetime revenue before email expansion. Optional.' },
             confirm: { type: 'boolean', description: "Required true when new criteria estimate exceeds #{threshold}." }
           },
           required: %w[audience_id]

    define_method(:name) { 'update_audience' }

    define_method(:execute) do |**attributes|
      Assistant::AudienceUpdater.call(attributes, actor_id: captured_ctx[:user_id])
    end
  end

  klass.new
end

.build_update_email_preferences_tool(audit_context) ⇒ Object



821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
# File 'app/services/assistant/audience_tool_builder.rb', line 821

def build_update_email_preferences_tool(audit_context)
  captured_ctx = audit_context

  klass = Class.new(RubyLLM::Tool) do
    description <<~DESC
      Modify email preferences for ONE email address — per-category opt-outs
      (disable_promotions/newsletters/announcements/events/webinars/reviews)
      and disable_email_tracking. Only flags you explicitly pass are changed;
      the record is created if the address has none.

      CONSENT-SENSITIVE: use only on an explicit user instruction about this
      specific address (e.g. "john@example.com asked to stop getting
      newsletters"). Never invent opt-outs, never batch addresses.
      unsubscribe_all opts the address out of every marketing category;
      resubscribe_all re-enables every category — use resubscribe ONLY when
      the user says the recipient explicitly asked to receive email again,
      and it requires a confirm: true round-trip.

      Delivery suppression is enforced by the platform at send time.
      After a successful save that newly disables one or more marketing
      categories, the standard EmailUnsubscribed event is published;
      no-op and tracking-only changes do not publish it.
    DESC

    parameters type: 'object',
           properties: {
             email: { type: 'string', description: 'Email address to modify. Required.' },
             disable_promotions: { type: 'boolean', description: 'Opt out of promotions.' },
             disable_newsletters: { type: 'boolean', description: 'Opt out of newsletters.' },
             disable_announcements: { type: 'boolean', description: 'Opt out of announcements.' },
             disable_events: { type: 'boolean', description: 'Opt out of events.' },
             disable_webinars: { type: 'boolean', description: 'Opt out of webinars.' },
             disable_reviews: { type: 'boolean', description: 'Opt out of review requests.' },
             disable_email_tracking: { type: 'boolean', description: 'Opt out of open/click tracking.' },
             unsubscribe_all: { type: 'boolean', description: 'Opt out of ALL marketing categories.' },
             resubscribe_all: { type: 'boolean', description: 'Re-enable ALL marketing categories (explicit consent only). Requires confirm: true.' },
             confirm: { type: 'boolean', description: 'Required true for resubscribe_all — re-enabling marketing email after an unsubscribe is consent-reversing.' }
           },
           required: %w[email]

    define_method(:name) { 'update_email_preferences' }

    define_method(:execute) do |**attributes|
      Assistant::EmailPreferenceUpdater.call(attributes, actor_id: captured_ctx[:user_id])
    end
  end

  klass.new
end

.confirm_gate(count, confirm, action_description) ⇒ Object

The confirm gate (plan decision #5). Returns a confirm_required JSON
string when the estimate exceeds the threshold and confirm is not
truthy; nil when the action may proceed.



230
231
232
233
234
235
236
237
238
239
240
241
# File 'app/services/assistant/audience_tool_builder.rb', line 230

def confirm_gate(count, confirm, action_description)
  return nil if count <= AUDIENCE_CONFIRM_THRESHOLD || confirm.to_b

  {
    confirm_required: true,
    estimated_size: count,
    threshold: AUDIENCE_CONFIRM_THRESHOLD,
    message: "This #{action_description} targets #{count} recipients (over the " \
             "#{AUDIENCE_CONFIRM_THRESHOLD} threshold). Show the user the size and only " \
             're-call with confirm: true after they explicitly approve.'
  }.to_json
end

.find_audience_or_error(audience_id) ⇒ Object

Look up an audience by id, returning [audience, nil] or [nil, error_json].



88
89
90
91
92
93
# File 'app/services/assistant/audience_tool_builder.rb', line 88

def find_audience_or_error(audience_id)
  audience = Audience.find_by(id: audience_id)
  return [nil, { error: "Audience ##{audience_id} not found" }.to_json] unless audience

  [audience, nil]
end

.find_email_audiences_or_error(audience_ids) ⇒ Object

Resolve ids to email (static/dynamic) audiences for campaign attachment
or per-email recipient override. Returns [audiences, nil] or
[nil, error_json].



157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'app/services/assistant/audience_tool_builder.rb', line 157

def find_email_audiences_or_error(audience_ids)
  ids = Array(audience_ids).map(&:to_i)
  audiences = Audience.where(id: ids).to_a
  missing = ids - audiences.map(&:id)
  return [nil, { error: "Audience(s) not found: #{missing.join(', ')}" }.to_json] if missing.any?

  non_email = audiences.reject(&:email?)
  if non_email.any?
    return [nil, { error: 'Only email audiences (static/dynamic lists) can be attached to an ' \
                          "email campaign — not #{non_email.map { |a| "#{a.name} (#{a.list_type})" }.join(', ')}." }.to_json]
  end

  [audiences, nil]
end

.guard_email_list!(audience) ⇒ Object

Guard: refuse writes to customer-type lists (outside-sales pipeline,
not email). Returns an error JSON string when refused, nil otherwise.



97
98
99
100
101
102
103
104
# File 'app/services/assistant/audience_tool_builder.rb', line 97

def guard_email_list!(audience)
  return nil if audience.email?

  {
    error: "Audience ##{audience.id} (#{audience.name}) is a 'customer' list — those belong to " \
           'the outside-sales pipeline and cannot be modified with these tools.'
  }.to_json
end

.live_audience_estimate(campaign_email, estimate_cache: {}) ⇒ Integer

Returns the summed live recipient estimate for a campaign email.

Per-list sums can overcount overlaps, which is the safe direction for a
confirmation gate.

Parameters:

  • campaign_email (CampaignEmail)

    email whose effective audiences are counted

  • estimate_cache (Hash{Integer => Integer}) (defaults to: {})

    optional per-call audience cache

Returns:

  • (Integer)

    estimated recipient count

See Also:



201
202
203
204
205
206
207
# File 'app/services/assistant/audience_tool_builder.rb', line 201

def live_audience_estimate(campaign_email, estimate_cache: {})
  campaign_email.recipient_audiences.sum do |audience|
    estimate_cache.fetch(audience.id) do
      estimate_cache[audience.id] = audience_estimate(audience)
    end
  end
end

.preference_flags(preference) ⇒ Object

Current preference flags as a flat Hash (string keys for JSON).



244
245
246
247
# File 'app/services/assistant/audience_tool_builder.rb', line 244

def preference_flags(preference)
  CATEGORY_FLAGS.index_with { |flag| preference.public_send(flag) }
                .merge('disable_email_tracking' => preference.disable_email_tracking)
end

.probe_dynamic_criteria(customer_search_params, max_members: nil, add_all_emails: false) ⇒ Array

Strict-probes and estimates dynamic search criteria without saving.

max_members caps matching customers before add_all_emails expands
them, so the returned recipient count can exceed the customer cap.

Parameters:

  • customer_search_params (Hash)

    customer-search criteria

  • max_members (Integer, nil) (defaults to: nil)

    optional top-customer cap

  • add_all_emails (Boolean) (defaults to: false)

    whether every address per customer is counted

Returns:

  • (Array)

    count/error tuple: [Integer, nil] or [nil, String]



218
219
220
221
222
223
224
225
# File 'app/services/assistant/audience_tool_builder.rb', line 218

def probe_dynamic_criteria(customer_search_params, max_members: nil, add_all_emails: false)
  probe = Audience.new(list_type: 'dynamic', name: 'criteria-probe',
                       customer_search_params: customer_search_params,
                       max_members: max_members, add_all_emails: add_all_emails)
  [probe.perform_search_query_count, nil]
rescue Ransack::InvalidSearchError => e
  [nil, { error: "Invalid customer search criteria: #{e.message}" }.to_json]
end

.tools(audit_context: {}) ⇒ Array<RubyLLM::Tool>

Build all audience + email-preference tools.

Parameters:

  • audit_context (Hash) (defaults to: {})

    expects :user_id (Employee id for
    creator/updater attribution) and :conversation_id.

Returns:

  • (Array<RubyLLM::Tool>)


72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'app/services/assistant/audience_tool_builder.rb', line 72

def tools(audit_context: {})
  [
    build_list_audiences_tool,
    build_get_audience_tool,
    build_create_static_audience_tool(audit_context),
    build_create_dynamic_audience_tool(audit_context),
    build_update_audience_tool(audit_context),
    build_add_audience_members_tool(audit_context),
    build_remove_audience_members_tool,
    build_estimate_audience_size_tool,
    build_get_email_preferences_tool,
    build_update_email_preferences_tool(audit_context)
  ]
end