### Fast Path Project Initialization with GSD Source: https://github.com/sztheory/chimeway/blob/main/GSD-CONTEXT.md Use this command for a quick, automated project setup when a clear vision is defined in the prompt file. Ensure you are in the repository root. ```text /gsd-new-project --auto @prompts/CHIMEWAY-GSD-IDEA.md ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/sztheory/chimeway/blob/main/CONTRIBUTING.md Clone the Chimeway repository and install project dependencies using mix. ```bash git clone https://github.com/jonlunsford/chimeway.git cd chimeway mix deps.get ``` -------------------------------- ### Border and Box Shadow Example Source: https://github.com/sztheory/chimeway/blob/main/prompts/chimeway-brand-book.md Prefer borders over shadows for a cleaner look. This example shows the preferred usage for borders and subtle box shadows. ```css border: 1px solid var(--cw-line); box-shadow: 0 1px 2px rgb(7 19 26 / 0.06); ``` -------------------------------- ### Plan Phase 1 Source: https://github.com/sztheory/chimeway/blob/main/prompts/INTERACTIVE-GSD-NEW-PROJECT.md After the initial `/gsd-new-project` command completes, use this command to plan the first phase. Add `--text` if your GSD install requires it for CLIs without AskUserQuestion. ```text /gsd-plan-phase 1 ``` -------------------------------- ### Initiate New Project with Attachments Source: https://github.com/sztheory/chimeway/blob/main/prompts/INTERACTIVE-GSD-NEW-PROJECT.md Use this command in Claude Code/Cursor from the repo root to start a new project with deep questioning and parallel research. Include relevant prompt files for context. ```text /gsd-new-project @GSD-CONTEXT.md @prompts/CHIMEWAY-GSD-IDEA.md @prompts/chimeway-engineering-dna-from-prior-libs.md @prompts/elixir_notifykit_research_brief.md ``` -------------------------------- ### Basic Custom Adapter Structure Source: https://github.com/sztheory/chimeway/blob/main/guides/recipes/custom-adapter.md A minimal implementation of the `Chimeway.Adapter` behaviour. This serves as a starting point for any custom adapter. ```elixir defmodule MyApp.MyCustomAdapter do @behaviour Chimeway.Adapter @impl true def deliver(%Chimeway.Delivery{} = delivery, config) do # Implementation goes here end end ``` -------------------------------- ### NotifyKit Push Delivery Options Example Source: https://github.com/sztheory/chimeway/blob/main/prompts/elixir_notifykit_research_brief.md Demonstrates how to configure delivery options for push notifications, including TTL, collapse keys, priority, and platform-specific settings for APNS and FCM. Handle token invalidation and provider acceptance status carefully. ```elixir deliver :push, ttl: [hours: 4], collapse_key: "post:#{post.id}:comments", priority: :normal, apns: [interruption_level: :active], fcm: [analytics_label: "comment_created"] ``` -------------------------------- ### Manually Emit Digest Bucket Source: https://context7.com/sztheory/chimeway/llms.txt Explicitly trigger the emission of a digest bucket. This is necessary for setups not using Oban for automatic flushing. ```elixir # Manually emit a due bucket (for non-Oban setups) bucket = Digests.get_rule!(rule.id) {:ok, emission} = Digests.emit_bucket(bucket.id) ``` -------------------------------- ### Attach Default Telemetry Handlers Source: https://context7.com/sztheory/chimeway/llms.txt Call `Chimeway.Telemetry.attach_default_handlers()` in your `Application.start/2` function to enable default telemetry logging. This is a basic setup for integrating Chimeway's observability features. ```elixir # In application.ex def start(_type, _args) do Chimeway.Telemetry.attach_default_handlers() # ... end ``` -------------------------------- ### Define a Mention Escalation Workflow Source: https://github.com/sztheory/chimeway/blob/main/guides/flows/multi-step-journeys.md Implement the Chimeway.Workflow behavior to define a multi-step journey. This example includes an in-app notification, a wait step with a stop condition, and an email escalation. ```elixir defmodule MyApp.Workflows.MentionEscalation do @behaviour Chimeway.Workflow @impl true def workflow(_args) do %{ key: "mention_escalation", version: 1, steps: [ %{ id: "step_in_app", action: %{ type: :notify, channel: :in_app, render_key: "mention_notification" } }, %{ id: "step_wait_for_read", action: %{ type: :wait, duration: "PT2H", # Wait 2 hours (ISO 8601 duration) stop_conditions: [ %{ type: :signal_received, signal_type: "notification_read" } ] } }, %{ id: "step_email_escalation", action: %{ type: :notify, channel: :email, render_key: "mention_email" } } ] } end end ``` -------------------------------- ### Define an Inline Workflow in a Notifier Source: https://context7.com/sztheory/chimeway/llms.txt Define a multi-step workflow directly within a Chimeway Notifier. This example shows an 'in_app' step followed by an 'email' step with a 2-hour wait. ```elixir defmodule MyApp.MentionNotifier do use Chimeway.Notifier @impl true def notification_key, do: "mention.created" @impl true def version, do: 1 @impl true def recipients(%{mentioned_user_id: uid}), do: {:ok, [%{identity: "user:#{uid}", type: "user"}]} @impl true def build(params, _r), do: {:ok, params} # Inline workflow: in_app first, wait 2h, escalate to email if no signal @impl true def workflow(_params, _recipient) do {:ok, %{ workflow_key: "mention_escalation", workflow_version: 1, steps: [ %{ step_key: "in_app_step", step_order: 1, channel: "in_app", config: %{ "progress" => [ %{"kind" => "wait_until", "anchor" => "prior_delivery_terminal_at", "delay_seconds" => 7200, "to_step" => "email_step"} ] } }, %{ step_key: "email_step", step_order: 2, channel: "email", config: %{ "progress" => [ %{"kind" => "stop", "outcome" => "delivered"} ] } } ] }} end end ``` -------------------------------- ### Create Daily Digest Rule Source: https://context7.com/sztheory/chimeway/llms.txt Define a digest rule that groups notifications daily, with a specific boundary time and time zone. This example sets up a daily digest for 'updates' matching a category. ```elixir # Create a daily digest (boundary at 09:00 America/Chicago) {:ok, daily_rule} = Digests.upsert_rule(%{ rule_key: "email_daily_digest", rule_version: 1, channel: "email", match_category: "updates", group_by: :category, window_kind: :daily, boundary_hour: 9, boundary_minute: 0, boundary_time_zone: "America/Chicago" }) ``` -------------------------------- ### Configure Oban for Async Dispatch Source: https://context7.com/sztheory/chimeway/llms.txt Configure Chimeway to use Oban for asynchronous dispatch of notifications and workflow progression. This setup includes defining queues and scheduling the workflow progression worker. ```elixir # config/config.exs config :chimeway, dispatcher: Chimeway.Dispatch.Oban config :my_app, Oban, repo: MyApp.Repo, plugins: [ Oban.Plugins.Pruner, {Oban.Plugins.Cron, crontab: [ # Run progression worker every minute for wait-gate resolution {"* * * * *", Chimeway.Dispatch.WorkflowProgressionWorker} ]} ], queues: [ chimeway_delivery: [limit: 20], # Async notification dispatch chimeway_signals: [limit: 10], # Signal routing for workflows chimeway_workflows: [limit: 5] # Workflow progression tasks ] # config/test.exs — synchronous dispatch for tests config :chimeway, dispatcher: Chimeway.Dispatch.Sync ``` -------------------------------- ### Fetch and Process Inbox Items Source: https://github.com/sztheory/chimeway/blob/main/guides/introduction/getting-started.md Retrieve notifications for a specific recipient from their inbox using `Chimeway.list_for_recipient/1`. This example shows how to access the subject of the first message or handle an empty inbox. ```elixir recipient = "user_12345" # Fetch notifications inbox_items = Chimeway.list_for_recipient(recipient) case inbox_items do [first_item | _rest] -> IO.puts("Message: #{first_item.metadata["subject"]}") [] -> IO.puts("No messages.") end ``` -------------------------------- ### Create Rolling Digest Rule Source: https://context7.com/sztheory/chimeway/llms.txt Define a digest rule that groups notifications within a rolling time window. This example creates a 60-minute rolling digest for email comment notifications. ```elixir alias Chimeway.Digests # Create a rolling 60-minute digest rule for email comment notifications {:ok, rule} = Digests.upsert_rule(%{ rule_key: "email_comments_digest", rule_version: 1, channel: "email", match_notification_key: "comment.created", group_by: :notification_key, window_kind: :rolling, window_minutes: 60 }) ``` -------------------------------- ### Available Chimeway Telemetry Events Source: https://context7.com/sztheory/chimeway/llms.txt This list outlines the available telemetry events emitted by Chimeway across its pipeline stages. Each event supports `:start`, `:stop`, and `:exception` variants for detailed monitoring. ```elixir # Available telemetry events (each has :start, :stop, :exception variants): # [:chimeway, :events, :create] — event creation # [:chimeway, :deliveries, :plan] — delivery planning # [:chimeway, :policy, :evaluate] — policy checkpoint evaluation # [:chimeway, :dispatch, :sync] — synchronous adapter dispatch # [:chimeway, :dispatch, :enqueue] — Oban job enqueue (optional) # [:chimeway, :dispatch, :perform] — Oban job perform (optional) # [:chimeway, :attempts, :record] — attempt row persistence ``` -------------------------------- ### Custom Telemetry Handler for Delivery Outcomes Source: https://context7.com/sztheory/chimeway/llms.txt Implement a custom handler using `:telemetry.attach_many/4` to process specific Chimeway telemetry events. This example shows how to increment metrics based on delivery attempt outcomes, notification keys, and channels. Ensure only PII-safe keys are used in metadata. ```elixir # Custom handler for delivery attempt outcomes :telemetry.attach_many( "my-app-chimeway-handler", [ [:chimeway, :dispatch, :sync, :stop], [:chimeway, :policy, :evaluate, :stop], [:chimeway, :attempts, :record, :stop] ], fn event_name, measurements, metadata, _config -> # Safe keys only: delivery_id, notification_key, channel, outcome, # suppression_reason, correlation_id, attempt_number, error_class, adapter_module MyApp.Metrics.increment("chimeway.#{List.last(event_name)}", tags: [ "key:#{metadata[:notification_key]}", "channel:#{metadata[:channel]}", "outcome:#{metadata[:outcome]}" ]) end, nil ) ``` -------------------------------- ### Set Up Ecto Database Source: https://github.com/sztheory/chimeway/blob/main/CONTRIBUTING.md Initialize and set up the Ecto database for the project. ```bash mix ecto.setup ``` -------------------------------- ### Initiate New Project with Optional Attachments Source: https://github.com/sztheory/chimeway/blob/main/prompts/INTERACTIVE-GSD-NEW-PROJECT.md Add these optional prompt files for more context and a longer context window when initiating a new project. ```text @prompts/chimeway-brand-book.md @prompts/chimeway-admin-ui-and-operator-ia.md @prompts/chimeway-testing-and-e2e-strategy.md @prompts/chimeway-release-engineering-and-ci.md @prompts/chimeway-host-app-integration-seam.md @prompts/prior-art/SOURCE-CANONICAL.md ``` -------------------------------- ### Initialize Project via SDK Source: https://github.com/sztheory/chimeway/blob/main/prompts/INTERACTIVE-GSD-NEW-PROJECT.md An alternative to the slash workflow for initializing a new project using the `gsd-sdk`. This command is run from the project's root directory. ```bash cd /Users/jon/projects/chimeway gsd-sdk init @prompts/CHIMEWAY-GSD-IDEA.md ``` -------------------------------- ### GSD Project Initialization (Terminal) Source: https://github.com/sztheory/chimeway/blob/main/prompts/CHIMEWAY-GSD-IDEA.md This command initializes a new project from the terminal. Ensure Git is set up in the repository root first. ```bash cd /Users/jon/projects/chimeway git init # if not already in a repository gsd-sdk init @prompts/CHIMEWAY-GSD-IDEA.md ``` -------------------------------- ### Secure Runtime Configuration for Adapter Source: https://github.com/sztheory/chimeway/blob/main/guides/recipes/custom-adapter.md Demonstrates reading adapter configuration securely at runtime using `Keyword.get/2` and `Application.get_env/3`. Avoids compile-time configuration to ensure multi-environment safety. ```elixir defmodule MyApp.MyCustomAdapter do @behaviour Chimeway.Adapter @impl true def deliver(%Chimeway.Delivery{} = delivery, config) do # Good: Reading config at runtime api_key = Keyword.get(config, :api_key) || Application.get_env(:my_app, :custom_adapter_api_key) # ... external API call ... end end ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/sztheory/chimeway/blob/main/GSD-CONTEXT.md If cloning a fresh repository, initialize Git before the first GSD project command. This ensures the project meets the `has_git: true` requirement. ```bash git init ``` -------------------------------- ### Run Full Local Gate Source: https://github.com/sztheory/chimeway/blob/main/MAINTAINING.md Execute all lint and test steps locally before publishing. Ensure all steps pass. ```bash mix ci ``` -------------------------------- ### Verify Release Source: https://github.com/sztheory/chimeway/blob/main/MAINTAINING.md Run the trio of verification commands after publishing to ensure the release is clean, parity is maintained, and the version is accessible on Hex.pm. ```bash mix verify.clean mix verify.parity mix verify.published X.Y.Z ``` -------------------------------- ### Fetch Dependencies with mix deps.get Source: https://github.com/sztheory/chimeway/blob/main/guides/introduction/installation.md Run this command in your terminal after updating mix.exs to download the new dependency. ```bash mix deps.get ``` -------------------------------- ### Run Docs Gate Source: https://github.com/sztheory/chimeway/blob/main/MAINTAINING.md Build documentation to ensure no warnings-as-errors failures occur. This step is crucial for maintaining documentation quality. ```bash mix ci.docs ``` -------------------------------- ### Run Tests Source: https://github.com/sztheory/chimeway/blob/main/CONTRIBUTING.md Execute all project tests using the provided mix tasks. ```bash mix ci.test ``` ```bash mix test ``` -------------------------------- ### Preview Renders with Chimeway.preview_rendering/3 Source: https://context7.com/sztheory/chimeway/llms.txt Use this function to run the production rendering pipeline without side effects like persisting rows or dispatching traffic. It returns a preview struct containing rendering details. ```elixir {:ok, preview} = Chimeway.preview_rendering( MyApp.OrderShippedNotifier, %{order_id: "ord-123", user_id: 42}, channel: :email, recipient: %{identity: "user:42", type: "user"} ) preview.channel #=> "email" preview.render_key #=> "order_shipped_email" preview.render_version #=> 1 preview.render_data #=> %{subject: "Your order ord-123 shipped!", body: "It's on its way."} ``` -------------------------------- ### Run Ecto Migrations Source: https://github.com/sztheory/chimeway/blob/main/guides/introduction/installation.md Apply the generated Chimeway migrations to your database using this Ecto command. ```bash mix ecto.migrate ``` -------------------------------- ### Publish to Hex Source: https://github.com/sztheory/chimeway/blob/main/MAINTAINING.md Publish the new version of the package to Hex. Follow the prompts carefully to confirm package name and version. ```bash mix hex.publish ``` -------------------------------- ### Generate Chimeway Database Migrations Source: https://github.com/sztheory/chimeway/blob/main/guides/introduction/installation.md Execute this mix task to copy the necessary migration files into your project's priv/repo/migrations directory. ```bash mix chimeway.gen.migrations ``` -------------------------------- ### Plan and Persist Notification Event with Plain-Data API Source: https://github.com/sztheory/chimeway/blob/main/prompts/elixir_notifykit_research_brief.md Use the plain-data API to create an event specification and then plan, persist, and enqueue it. This approach avoids macro lock-in and keeps the framework testable. ```elixir %NotifyKit.EventSpec{ key: "comment.created", version: 1, params: %{post_id: post.id, comment_id: comment.id}, actor: NotifyKit.Ref.from(current_user), record: NotifyKit.Ref.from(comment), idempotency_key: "comment:#{comment.id}:created" } |> NotifyKit.plan(MyApp.NotifyConfig) |> NotifyKit.persist_and_enqueue(MyApp.Repo) ``` -------------------------------- ### NotifyKit Suggested Project Files Source: https://github.com/sztheory/chimeway/blob/main/prompts/elixir_notifykit_research_brief.md This list suggests essential project files for the NotifyKit project, defining their purpose in documenting vision, research, requirements, roadmap, and decisions. ```text PROJECT.md <- vision, principles, domain model RESEARCH.md <- ecosystem scan + footguns REQUIREMENTS.md <- MVP/v1/v2 requirements ROADMAP.md <- phases M1-M9 STATE.md <- current decisions and open questions ``` -------------------------------- ### Tag and Push Release Source: https://github.com/sztheory/chimeway/blob/main/MAINTAINING.md Create a Git tag for the release version and push it to the main branch along with other tags. ```bash git tag vX.Y.Z git push origin main --tags ``` -------------------------------- ### Implement Custom Sendgrid Adapter for Chimeway Source: https://context7.com/sztheory/chimeway/llms.txt Defines a custom adapter for Sendgrid, handling delivery, webhook verification, and feedback normalization. Configuration must be read at runtime using `Application.get_env/3`. ```elixir defmodule MyApp.SendgridAdapter do @behaviour Chimeway.Adapter @impl true def deliver(%Chimeway.Delivery{} = delivery, _config) do api_key = Application.get_env(:my_app, :sendgrid_api_key) payload = delivery.rendered_payload || %{} case HTTPClient.post("https://api.sendgrid.com/v3/mail/send", headers: [{"Authorization", "Bearer #{api_key}"}], body: Jason.encode!( to: [%{email: delivery.recipient_identity}], subject: payload["subject"], content: [%{type: "text/html", value: payload["body"]}] ) ) do {:ok, %{status: 202, headers: headers}} -> message_id = get_header(headers, "x-message-id") # MUST redact sensitive fields before returning {:ok, %{provider_message_id: message_id, status: 202}} {:ok, %{status: 400, body: body}} -> {:error, :permanent, %{status: 400, message: "bad_request"}} {:error, _reason} -> {:error, :temporary, %{message: "network_error"}} end end # Webhook verification for async delivery receipts @impl true def verify_webhook(raw_body, headers, config) do secret = Keyword.fetch!(config, :webhook_secret) signature = get_header(headers, "x-twilio-signature") if valid_hmac?(raw_body, signature, secret), do: :ok, else: {:error, :unauthorized} end @impl true def resolve_delivery(%{"MessageSid" => sid}), do: {:ok, %{provider_message_id: sid}} def resolve_delivery(_), do: :error @impl true def normalize_feedback(%{"MessageStatus" => "delivered"}), do: {:ok, %{status: :delivered}} def normalize_feedback(%{"MessageStatus" => "bounced"}), do: {:ok, %{status: :bounced}} def normalize_feedback(_), do: {:ok, %{status: :failed}} @impl true def resolve_provider_event_id(%{"MessageSid" => sid}), do: {:ok, sid} def resolve_provider_event_id(_), do: :none defp get_header(headers, name) do headers |> Enum.find_value(fn {k, v} -> if k == name, do: v end) end defp valid_hmac?(body, sig, secret) do expected = :crypto.mac(:hmac, :sha256, secret, body) |> Base.encode64() Plug.Crypto.secure_compare(expected, sig) end end # Register the adapter in config # config/config.exs config :chimeway, :adapters, email: MyApp.SendgridAdapter # Enforce the contract in tests using the shared contract test suite defmodule MyApp.SendgridAdapterTest do use ExUnit.Case, async: true use Chimeway.Adapter.ContractTest, adapter: MyApp.SendgridAdapter end ``` -------------------------------- ### NotifyKit Admin UI Router Integration Source: https://github.com/sztheory/chimeway/blob/main/prompts/elixir_notifykit_research_brief.md Shows how to mount the NotifyKit admin LiveView in a Phoenix application's router. Ensure proper scope, pipeline, and authentication are configured for production environments. ```elixir scope "/admin" do pipe_through [:browser, :require_admin] live_notify_kit "/notifications", otp_app: :my_app, repo: MyApp.Repo, auth: {MyAppWeb.AdminAuth, :authorize_notify_kit} end ``` -------------------------------- ### Commit Release Changes Source: https://github.com/sztheory/chimeway/blob/main/MAINTAINING.md Stage and commit the updated `mix.exs` and `CHANGELOG.md` files. Use a conventional commit message for clarity. ```bash git add mix.exs CHANGELOG.md git commit -m "chore: release vX.Y.Z" ``` -------------------------------- ### NotifyKit Phase 1 AI Coding Prompt Source: https://github.com/sztheory/chimeway/blob/main/prompts/elixir_notifykit_research_brief.md This prompt instructs an AI to create an implementation plan for Phase 1 of NotifyKit, focusing on core Ecto in-app notifications, based on provided project context. ```text Use PROJECT.md and RESEARCH.md as authoritative context. Create an implementation plan for Phase 1: Core + Ecto in-app notifications. Output: - assumptions - module/file tree - schemas and migrations - public API - generator behavior - tests - acceptance checklist Do not implement yet. Keep the plan small enough for one fresh execution context. ``` -------------------------------- ### Configure User Settings Source: https://context7.com/sztheory/chimeway/llms.txt Set quiet hours and delivery caps for a recipient. Ensure the recipient ID and time zone are correctly specified. ```elixir Settings.upsert_settings(%{ recipient_id: "user:42", quiet_hours_start_minute: 1320, # 22:00 = 22*60 quiet_hours_end_minute: 480, # 08:00 = 8*60 delivery_cap_count: 5, delivery_cap_window_minutes: 60, time_zone: "America/New_York" }) ``` -------------------------------- ### Primary UI and Docs Font Stack Source: https://github.com/sztheory/chimeway/blob/main/prompts/chimeway-brand-book.md Use Inter for primary UI and documentation. It is designed for screen readability and is open-source. ```css font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; ``` -------------------------------- ### Configure Chimeway to Use Oban Dispatcher Source: https://github.com/sztheory/chimeway/blob/main/guides/recipes/oban-integration.md Update your application's configuration to use `Chimeway.Dispatch.Oban` for asynchronous dispatch. ```elixir config :chimeway, dispatcher: Chimeway.Dispatch.Oban ``` -------------------------------- ### Transactional Enqueueing with Ecto.Multi Source: https://github.com/sztheory/chimeway/blob/main/guides/recipes/oban-integration.md Ensure transactional consistency by enqueuing Oban jobs within an Ecto.Multi transaction. ```elixir alias Ecto.Multi alias MyApp.Repo # Start a multi transaction Multi.new() # ... do your application work (e.g., create a user) ... |> Multi.insert(:user, %MyApp.User{name: "Alice", email: "alice@example.com"}) # Pass the multi to Chimeway |> Multi.run(:notification, fn repo, %{user: user} -> WelcomeNotifier.trigger( user.id, %{name: user.name}, # Ensure deliveries are saved and enqueued inside the Multi multi: multi ) # When using the multi option, trigger/3 returns {:ok, multi} end) |> Repo.transaction() ``` -------------------------------- ### Fetch User Settings Source: https://context7.com/sztheory/chimeway/llms.txt Retrieve the current settings for a given recipient. The returned structure contains all configured policy parameters. ```elixir settings = Settings.get_settings("user:42") ``` -------------------------------- ### NotifyKit Adapter Behavior Definition Source: https://github.com/sztheory/chimeway/blob/main/prompts/elixir_notifykit_research_brief.md Defines the callback interface for channel adapters. Implement this module to create custom adapters for new notification channels or providers. Ensure each callback handles its specific responsibilities. ```elixir defmodule NotifyKit.Adapter do @callback channel() :: atom() @callback provider() :: atom() @callback validate_config(keyword()) :: :ok | {:error, [String.t()]} @callback validate_payload(NotifyKit.Payload.t()) :: :ok | {:error, term()} @callback deliver(NotifyKit.Delivery.t(), keyword()) :: {:ok, NotifyKit.ProviderResponse.t()} | {:error, NotifyKit.ProviderError.t()} end ``` -------------------------------- ### Trigger a Workflow with Chimeway.Trigger Source: https://github.com/sztheory/chimeway/blob/main/guides/flows/multi-step-journeys.md Initiate a workflow run by calling Chimeway.Trigger.trigger. Pass the workflow module and any necessary arguments. ```elixir Chimeway.Trigger.trigger( MyApp.Workflows.MentionEscalation, %{ actor_id: "user_123", tenant_id: "org_456", document_id: "doc_789" }, tenant_id: "org_456" ) ``` -------------------------------- ### Configure Oban Queues and Workers Source: https://github.com/sztheory/chimeway/blob/main/guides/recipes/oban-integration.md Set up Oban in your application's configuration, including Chimeway-specific queues and the ProgressionWorker. ```elixir config :my_app, Oban, repo: MyApp.Repo, plugins: [ Oban.Plugins.Pruner, # Configure the ProgressionWorker to run periodically (e.g., every minute) {Oban.Plugins.Cron, crontab: [ {"* * * * *", Chimeway.Workflows.Workers.ProgressionWorker} ]} ], queues: [ default: 10, chimeway_delivery: [limit: 20], # For async dispatch of notifications chimeway_signals: [limit: 10], # For processing workflow signals chimeway_workflows: [limit: 5] # For general workflow progression tasks (if any) ] ``` -------------------------------- ### Configure Chimeway Repo Source: https://github.com/sztheory/chimeway/blob/main/guides/introduction/installation.md Configure Chimeway to use your application's Ecto Repo module by adding this to your config files. ```elixir config :chimeway, repo: MyApp.Repo ``` -------------------------------- ### List Digest Rules Source: https://context7.com/sztheory/chimeway/llms.txt Retrieve a list of all configured digest rules, optionally filtering by channel. ```elixir # List rules for a channel rules = Digests.list_rules(channel: "email") ``` -------------------------------- ### Chimeway.Workflows.list_traces/3 Source: https://context7.com/sztheory/chimeway/llms.txt Lists the transition history for a given workflow run. This provides a log of events and state changes within the workflow. ```APIDOC ## `Chimeway.Workflows.list_traces/3` ### Description Lists the transition history for a given workflow run. This provides a log of events and state changes within the workflow. ### Function Signature `Chimeway.Workflows.list_traces(tenant_id, workflow_run_id, opts)` ### Parameters - **tenant_id** (string) - The identifier for the tenant. - **workflow_run_id** (any) - The unique identifier for the workflow run. - **opts** (keyword list) - Optional keyword list, e.g., `limit`. ### Returns - `{:ok, traces}` - On success, returns a list of trace entries. ### Example ```elixir # Inspect workflow transition history {:ok, traces} = Chimeway.Workflows.list_traces("tenant_org_456", workflow_run_id, limit: 50) traces |> Enum.map(& &1.reason) #=> ["workflow_started", "step_activated", "waiting_for_step_progression", "signal_received", "progressed_on_delivery_outcome"] ``` ``` -------------------------------- ### Add Oban Dependency Source: https://github.com/sztheory/chimeway/blob/main/guides/recipes/oban-integration.md Add Oban to your project's dependencies in `mix.exs`. ```elixir defp deps do [ {:oban, "~> 2.17"} ] end ``` -------------------------------- ### NotifyKit Vertical Slice Architecture Source: https://github.com/sztheory/chimeway/blob/main/prompts/elixir_notifykit_research_brief.md This text-based diagram outlines the smallest vertical slice to prove the NotifyKit architecture, covering event triggering, notification persistence, delivery, and user interaction. ```text Phoenix app -> trigger CommentCreated -> Event row -> two recipient Notification rows -> in-app feed query -> PubSub/LiveView badge update -> delayed Swoosh email delivery via Oban -> user reads one notification before delay -> policy suppresses that email -> admin trace shows: suppressed because read_at present ``` -------------------------------- ### Trace Deliveries with Chimeway.Traces Source: https://context7.com/sztheory/chimeway/llms.txt Utilize Chimeway.Traces for diagnosing notification behavior by querying the lifecycle chain. It provides structured explanations, timelines, and reasons for suppression. ```elixir alias Chimeway.Traces # Full trace for a single event (preloads notifications -> deliveries -> attempts) {:ok, event} = Traces.get_trace("event-uuid-here") event.notifications |> Enum.flat_map(& &1.deliveries) |> Enum.map(& {&1.channel, &1.status}) #=> [{"email", :succeeded}, {"in_app", :suppressed}] ``` ```elixir # Explain exactly why a delivery was suppressed {:ok, explanation} = Traces.explain_delivery("delivery-uuid-here") explanation.status #=> :suppressed explanation.suppression_reason #=> "channel_disabled" explanation.planning_reason #=> nil explanation.timeline #=> [ # %{at: ~U[...], event: :event_created, detail: %{notification_key: "order_shipped"}}, # %{at: ~U[...], event: :notification_created, detail: %{recipient_id: "user:42"}}, # %{at: ~U[...], event: :delivery_planned, detail: %{channel: "email"}}, # %{at: ~U[...], event: :suppressed, detail: %{reason: "channel_disabled", policy_checkpoint: "planning"}} # ] ``` ```elixir # All traces for a recipient, filtered by notification type traces = Traces.find_traces_for_recipient("user:42", notification_key: "order_shipped", limit: 20 ) ``` ```elixir # By correlation ID (tie back to your own request traces) events = Traces.find_traces_by_correlation_id("req-abc-456") ``` ```elixir # Aggregate delivery outcomes for dashboards/alerting rows = Traces.aggregate_outcomes( notification_key: "order_shipped", channel: "email", inserted_after: ~U[2025-01-01 00:00:00Z] ) #=> [%{notification_key: "order_shipped", channel: "email", outcome: "sent", count: 1042}, # %{notification_key: "order_shipped", channel: "email", outcome: "suppressed", count: 17}] ``` ```elixir # Convenience wrapper for single notification key rows = Traces.aggregate_outcomes_for_notification("order_shipped", outcomes: ["sent", "failed"]) ``` -------------------------------- ### Chimeway.preview_rendering/3 Source: https://context7.com/sztheory/chimeway/llms.txt Preview notification renders without side effects. This function runs the production rendering pipeline and returns a preview of the rendered notification. ```APIDOC ## `Chimeway.preview_rendering/3` — Previewing Renders Without Side Effects `Chimeway.preview_rendering/3` runs the production rendering pipeline (notifier resolution, channel render dispatch) without persisting any rows or dispatching delivery traffic. Returns `{:ok, %Chimeway.Rendering.Preview{}}` with `channel`, `render_key`, `render_version`, and `render_data`. ### Parameters - **notifier**: The notifier module to use. - **params**: A map of parameters for the notifier. - **options**: A keyword list of options, such as `:channel`, `:recipient`. ### Returns - `{:ok, %Chimeway.Rendering.Preview{}}`: On success, returns a preview struct containing `channel`, `render_key`, `render_version`, and `render_data`. ### Example ```elixir {:ok, preview} = Chimeway.preview_rendering( MyApp.OrderShippedNotifier, %{order_id: "ord-123", user_id: 42}, channel: :email, recipient: %{identity: "user:42", type: "user"} ) preview.channel #=> "email" preview.render_key #=> "order_shipped_email" preview.render_version #=> 1 preview.render_data #=> %{subject: "Your order ord-123 shipped!", body: "It's on its way."} ``` ### CLI Usage ```bash mix chimeway.preview_rendering --notifier MyApp.OrderShippedNotifier \ --channel email --params '{"order_id":"ord-123","user_id":42}' \ --recipient '{"identity":"user:42","type":"user"}' ``` ``` -------------------------------- ### Configure Policy Settings with Chimeway.Policy.Settings Source: https://context7.com/sztheory/chimeway/llms.txt Manage per-recipient quiet hours and delivery frequency caps using Chimeway.Policy.Settings. The policy engine uses these settings to defer deliveries. ```elixir alias Chimeway.Policy.Settings ``` -------------------------------- ### Add Chimeway to Mix Dependencies Source: https://github.com/sztheory/chimeway/blob/main/README.md Include Chimeway in your project's dependencies by adding it to the `mix.exs` file. ```elixir def deps do [ {:chimeway, "~> 0.1"} ] end ``` -------------------------------- ### Chimeway.Workflows.explain/2 Source: https://context7.com/sztheory/chimeway/llms.txt Retrieves the current state of a specific workflow run. Useful for inspecting the progress and status of an ongoing workflow. ```APIDOC ## `Chimeway.Workflows.explain/2` ### Description Retrieves the current state of a specific workflow run. Useful for inspecting the progress and status of an ongoing workflow. ### Function Signature `Chimeway.Workflows.explain(tenant_id, workflow_run_id)` ### Parameters - **tenant_id** (string) - The identifier for the tenant. - **workflow_run_id** (any) - The unique identifier for the workflow run. ### Returns - `{:ok, run_state}` - On success, returns the run state of the workflow. ### Example ```elixir # Inspect workflow run state {:ok, run_state} = Chimeway.Workflows.explain("tenant_org_456", workflow_run_id) run_state.state #=> :waiting run_state.current_step_name #=> "email_step" run_state.suspended_until #=> ~U[2025-05-02 14:30:00Z] run_state.pending_signals #=> ["notification_read"] ``` ``` -------------------------------- ### Chimeway.Adapter Source: https://context7.com/sztheory/chimeway/llms.txt Defines the behaviour contract for custom outbound channel adapters. Adapters receive a pre-planned %Chimeway.Delivery{} and return structured outcomes. ```APIDOC ## `Chimeway.Adapter` — Custom Outbound Channel Adapters `Chimeway.Adapter` is the behaviour contract for outbound channel adapters. Adapters receive a pre-planned `%Chimeway.Delivery{}` with rendered content and return structured outcomes. Configuration must always be read at runtime via `Application.get_env/3`. Optional webhook callbacks enable async provider feedback loops. ```elixir defmodule MyApp.SendgridAdapter do @behaviour Chimeway.Adapter @impl true def deliver(%Chimeway.Delivery{} = delivery, _config) do api_key = Application.get_env(:my_app, :sendgrid_api_key) payload = delivery.rendered_payload || %{} case HTTPClient.post("https://api.sendgrid.com/v3/mail/send", headers: [{"Authorization", "Bearer #{api_key}"}], body: Jason.encode! %>{ to: [%{email: delivery.recipient_identity}], subject: payload["subject"], content: [%{type: "text/html", value: payload["body"]}] }) ) do {:ok, %{status: 202, headers: headers}} -> message_id = get_header(headers, "x-message-id") # MUST redact sensitive fields before returning {:ok, %{provider_message_id: message_id, status: 202}} {:ok, %{status: 400, body: body}} -> {:error, :permanent, %{status: 400, message: "bad_request"}} {:error, _reason} -> {:error, :temporary, %{message: "network_error"}} end end # Webhook verification for async delivery receipts @impl true def verify_webhook(raw_body, headers, config) do secret = Keyword.fetch!(config, :webhook_secret) signature = get_header(headers, "x-twilio-signature") if valid_hmac?(raw_body, signature, secret), do: :ok, else: {:error, :unauthorized} end @impl true def resolve_delivery(%{"MessageSid" => sid}), do: {:ok, %{provider_message_id: sid}} def resolve_delivery(_), do: :error @impl true def normalize_feedback(%{"MessageStatus" => "delivered"}), do: {:ok, %{status: :delivered}} def normalize_feedback(%{"MessageStatus" => "bounced"}), do: {:ok, %{status: :bounced}} def normalize_feedback(_), do: {:ok, %{status: :failed}} @impl true def resolve_provider_event_id(%{"MessageSid" => sid}), do: {:ok, sid} def resolve_provider_event_id(_), do: :none defp get_header(headers, name) do headers |> Enum.find_value(fn {k, v} -> if k == name, do: v end) end defp valid_hmac?(body, sig, secret) do expected = :crypto.mac(:hmac, :sha256, secret, body) |> Base.encode64() Plug.Crypto.secure_compare(expected, sig) end end # Register the adapter in config # config/config.exs config :chimeway, :adapters, [ email: MyApp.SendgridAdapter ] # Enforce the contract in tests using the shared contract test suite defmodule MyApp.SendgridAdapterTest do use ExUnit.Case, async: true use Chimeway.Adapter.ContractTest, adapter: MyApp.SendgridAdapter end ``` ``` -------------------------------- ### Chimeway.Traces Source: https://context7.com/sztheory/chimeway/llms.txt Provides tools for diagnosing notification behavior through detailed delivery traces and timelines. ```APIDOC ## `Chimeway.Traces` — Delivery Explainability `Chimeway.Traces` is the operator trace surface for diagnosing notification behavior. It exposes four query shapes over the durable lifecycle chain and builds structured explanations including full timestamped timelines, suppression reasons, planning context, resume/recovery metadata, and digest membership details. ### `get_trace/1` Retrieves the full trace for a single event, preloading notifications, deliveries, and attempts. #### Parameters - **event_uuid** (string): The unique identifier for the event. #### Returns - `{:ok, event}`: A struct containing the event trace details. ### `explain_delivery/1` Explains exactly why a specific delivery was suppressed. #### Parameters - **delivery_uuid** (string): The unique identifier for the delivery. #### Returns - `{:ok, explanation}`: A struct containing the explanation details, including status, suppression reason, planning reason, and timeline. ### `find_traces_for_recipient/2` Finds all traces for a given recipient, with optional filtering by notification type. #### Parameters - **recipient_id** (string): The identifier of the recipient. - **options** (keyword list): Options for filtering, such as `notification_key` and `limit`. ### `find_traces_by_correlation_id/1` Finds events by a correlation ID, allowing you to tie back to your own request traces. #### Parameters - **correlation_id** (string): The correlation ID to search for. ### `aggregate_outcomes/1` Aggregates delivery outcomes for dashboards and alerting. #### Parameters - **options** (keyword list): Criteria for aggregation, such as `notification_key`, `channel`, and `inserted_after`. #### Returns - `list`: A list of maps, each containing aggregated outcome data. ### `aggregate_outcomes_for_notification/2` A convenience wrapper for aggregating outcomes for a single notification key. #### Parameters - **notification_key** (string): The key of the notification. - **options** (keyword list): Options for filtering outcomes, such as `outcomes`. ### Example ```elixir alias Chimeway.Traces # Full trace for a single event {:ok, event} = Traces.get_trace("event-uuid-here") # Explain delivery suppression {:ok, explanation} = Traces.explain_delivery("delivery-uuid-here") # Find traces for a recipient traces = Traces.find_traces_for_recipient("user:42", notification_key: "order_shipped", limit: 20) # Find traces by correlation ID events = Traces.find_traces_by_correlation_id("req-abc-456") # Aggregate outcomes rows = Traces.aggregate_outcomes( notification_key: "order_shipped", channel: "email", inserted_after: ~U[2025-01-01 00:00:00Z] ) # Aggregate outcomes for a specific notification rows = Traces.aggregate_outcomes_for_notification("order_shipped", outcomes: ["sent", "failed"]) ``` ``` -------------------------------- ### Add Chimeway Supervisor to Application Source: https://github.com/sztheory/chimeway/blob/main/guides/introduction/installation.md Integrate the Chimeway Supervisor into your application's supervision tree by adding it to the children list in your application module. ```elixir def start(_type, _args) do children = [ MyApp.Repo, # ... other children Chimeway.Application ] opts = [strategy: :one_for_one, name: MyApp.Supervisor] Supervisor.start_link(children, opts) end ``` -------------------------------- ### GSD Command with Text-Only Output Source: https://github.com/sztheory/chimeway/blob/main/GSD-CONTEXT.md Employ the `--text` flag on your CLI if menu-based interactions are unavailable. This ensures command execution in environments without graphical interfaces. ```text --text ``` -------------------------------- ### Process Inbound Provider Webhook Ingestion with Chimeway Source: https://context7.com/sztheory/chimeway/llms.txt Handles inbound provider delivery callbacks synchronously. Verifies webhook signatures, parses and normalizes payloads, persists ingress rows, and enqueues jobs. Returns `{:ok, ingress}` only after row and job commits. ```elixir # In your Phoenix webhook controller defmodule MyAppWeb.WebhooksController do use MyAppWeb, :controller def create(conn, _params) do raw_body = conn.assigns[:raw_body] # requires CacheBodyReader plug headers = Enum.into(conn.req_headers, []) config = Application.get_env(:my_app, :sendgrid_webhook_config) case Chimeway.Webhooks.process(MyApp.SendgridAdapter, raw_body, headers, config) do {:ok, _ingress} -> send_resp(conn, 200, "") {:error, :unauthorized} -> send_resp(conn, 401, "Unauthorized") {:error, :unparseable_body} -> send_resp(conn, 400, "Bad Request") {:error, :unresolvable_delivery} -> # Unknown delivery — return 200 to prevent provider retries on unknown IDs send_resp(conn, 200, "") {:error, _reason} -> send_resp(conn, 500, "Internal Server Error") end end end # Add CacheBodyReader plug to preserve raw body for signature verification defmodule MyAppWeb.Endpoint do plug Plug.Parsers, parsers: [:json], body_reader: {MyApp.CacheBodyReader, :read_body, []}, json_decoder: Jason end ``` -------------------------------- ### Trigger a Notification with Chimeway.trigger/3 Source: https://context7.com/sztheory/chimeway/llms.txt Use `Chimeway.trigger/3` as the primary API to send notifications. It accepts a notifier module, params, and options like `idempotency_key` and `correlation_id`. It durably persists events and dispatches notifications. ```elixir # Basic trigger with idempotency key {:ok, result} = Chimeway.trigger( MyApp.OrderShippedNotifier, %{order_id: "ord-123", user_id: 42}, idempotency_key: "order-shipped-ord-123", correlation_id: "req-abc-456" ) result.event #=> %Chimeway.Events.Event{id: "uuid...", notification_key: "order_shipped"} result.notifications #=> [%Chimeway.Notifications.Notification{...}] ``` ```elixir # Transactional trigger inside Ecto.Multi (guarantees atomicity with application writes) alias Ecto.Multi {:ok, %{user: user, notification: _}} = Multi.new() |> Multi.insert(:user, MyApp.User.changeset(%MyApp.User{}, %{email: "alice@example.com"})) |> Multi.run(:notification, fn _repo, %{user: user} -> Chimeway.trigger( MyApp.WelcomeNotifier, %{user_id: user.id, name: user.name}, idempotency_key: "welcome-#{user.id}" ) end) |> MyApp.Repo.transaction() ``` ```elixir # Trigger with orchestration override (force digest for all channels) {:ok, result} = Chimeway.trigger( MyApp.OrderShippedNotifier, %{order_id: "ord-456", user_id: 99}, idempotency_key: "order-shipped-ord-456", orchestration_override: :digest ) ``` -------------------------------- ### Define a Comment Created Notifier with NotifyKit DSL Source: https://github.com/sztheory/chimeway/blob/main/prompts/elixir_notifykit_research_brief.md Use this DSL to define a notifier for comment creation events. It specifies parameters, recipients, and delivery methods (in-app and email) with custom rendering logic. ```elixir defmodule MyApp.Notifiers.CommentCreated do use NotifyKit.Notifier, key: "comment.created", version: 1 param :comment_id, Ecto.UUID param :post_id, Ecto.UUID recipients :post_watchers deliver :in_app deliver :email, adapter: MyApp.Notify.Email, wait: [minutes: 15], unless: :read?, queue: :notifications_email def post_watchers(ctx) do MyApp.Posts.watchers(ctx.params.post_id) end def render(:in_app, ctx, recipient) do {:ok, %{title: "New comment", body: "Someone commented on a post you watch", url: ~p"/posts/#{ctx.params.post_id}#comment-#{ctx.params.comment_id}"}} end def render(:email, ctx, recipient) do MyApp.Emails.comment_created(recipient, ctx.params) end end ``` -------------------------------- ### Refresh GitHub Actions SHAs Source: https://github.com/sztheory/chimeway/blob/main/MAINTAINING.md Fetch the latest SHAs for pinned GitHub Actions. These SHAs are used to ensure consistent builds. ```bash gh api /repos/actions/checkout/git/ref/tags/v4 --jq '.object.sha' gh api /repos/erlef/setup-beam/git/ref/tags/v1 --jq '.object.sha' gh api /repos/actions/cache/git/ref/tags/v4 --jq '.object.sha' ``` -------------------------------- ### Optional Editorial Font Stack Source: https://github.com/sztheory/chimeway/blob/main/prompts/chimeway-brand-book.md Use Source Serif 4 sparingly for major narrative elements like hero pull quotes and essays. It is available via Google Fonts. ```css font-family: "Source Serif 4", Georgia, serif; ```