diff --git a/sentry-delayed_job/spec/spec_helper.rb b/sentry-delayed_job/spec/spec_helper.rb index af62fa7e6..9e40b9836 100644 --- a/sentry-delayed_job/spec/spec_helper.rb +++ b/sentry-delayed_job/spec/spec_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true require "bundler/setup" + +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + begin require "debug/prelude" rescue LoadError diff --git a/sentry-opentelemetry/spec/spec_helper.rb b/sentry-opentelemetry/spec/spec_helper.rb index e9d82a6ca..ad492a76a 100644 --- a/sentry-opentelemetry/spec/spec_helper.rb +++ b/sentry-opentelemetry/spec/spec_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true require "bundler/setup" + +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + begin require "debug/prelude" rescue LoadError diff --git a/sentry-rails/lib/generators/sentry_generator.rb b/sentry-rails/lib/generators/sentry_generator.rb index ae6be1d7c..b00824db8 100644 --- a/sentry-rails/lib/generators/sentry_generator.rb +++ b/sentry-rails/lib/generators/sentry_generator.rb @@ -28,4 +28,13 @@ def inject_code_into_layout " <%= Sentry.get_trace_propagation_meta.html_safe %>\n " end end + + # The generator only runs while Sentry is being set up, so a coding agent running + # it gets pointed at the checklist right away. + def point_coding_agent_to_checklist + return unless Sentry::AgentHint.coding_agent? + + say_status :checklist, "Check the setup against Sentry's official setup checklist before you finish: " \ + "#{Sentry::AgentHint::CHECKLIST_PATH}", :yellow + end end diff --git a/sentry-rails/lib/sentry/rails/railtie.rb b/sentry-rails/lib/sentry/rails/railtie.rb index c6798904f..5607621f9 100644 --- a/sentry-rails/lib/sentry/rails/railtie.rb +++ b/sentry-rails/lib/sentry/rails/railtie.rb @@ -71,6 +71,18 @@ class Railtie < ::Rails::Railtie end end + # `rails server` runs until it's stopped, so show the agent hint while it boots. + # Not via Rails.logger: server blocks run before `rails server` sends it to the + # console, so the hint would only reach log/development.log. Rails 6.1+. + if respond_to?(:server) + server { Sentry::AgentHint.show } + end + + # Spring forks each command (rails runner, rspec, ...) from its preloaded app. + if defined?(::Spring) && ::Spring.respond_to?(:after_fork) + ::Spring.after_fork { Sentry::AgentHint.after_fork } + end + runner do next unless Sentry.initialized? Sentry.configuration.background_worker_threads = 0 diff --git a/sentry-rails/spec/sentry/generator_spec.rb b/sentry-rails/spec/sentry/generator_spec.rb index 5f5c77b52..8d9cefc9a 100644 --- a/sentry-rails/spec/sentry/generator_spec.rb +++ b/sentry-rails/spec/sentry/generator_spec.rb @@ -76,6 +76,18 @@ expect(content).not_to include("Sentry.get_trace_propagation_meta.html_safe") end + it "points a coding agent at the setup checklist" do + allow(Sentry::AgentHint).to receive(:coding_agent?).and_return(true) + + expect(run_generator).to include(Sentry::AgentHint::CHECKLIST_PATH) + end + + it "doesn't mention the checklist to people" do + allow(Sentry::AgentHint).to receive(:coding_agent?).and_return(false) + + expect(run_generator).not_to include(Sentry::AgentHint::CHECKLIST_PATH) + end + context "with a DSN option" do it "creates a initializer file with the DSN" do run_generator %w[--dsn foobarbaz] diff --git a/sentry-rails/spec/sentry/rails_spec.rb b/sentry-rails/spec/sentry/rails_spec.rb index b93435cdd..6b066d3e1 100644 --- a/sentry-rails/spec/sentry/rails_spec.rb +++ b/sentry-rails/spec/sentry/rails_spec.rb @@ -41,6 +41,23 @@ expect(Sentry.configuration.background_worker_threads).to eq(0) end + it "prints the coding agent hint to stderr when the server loads", skip: !Sentry::Railtie.respond_to?(:server) && "needs Rails 6.1+" do + allow(Sentry::AgentHint).to receive(:take).and_return("[sentry] hint") + + expect { Rails.application.load_server }.to output("[sentry] hint\n").to_stderr + end + + it "counts Rails structured logging, not the :logger patch, as logs for the coding agent hint" do + config = Sentry.configuration + missing = -> { Sentry::AgentHint.new(config, __FILE__).send(:missing) } + + config.enabled_patches << :logger + expect(missing.call).to include(:logs) + + config.rails.structured_logging.enabled = true + expect(missing.call).not_to include(:logs) + end + describe "logger detection" do it "sets a duplicated Rails logger as the SDK's logger" do if Gem::Version.new(Rails.version) > Gem::Version.new("7.1.0.beta") diff --git a/sentry-rails/spec/spec_helper.rb b/sentry-rails/spec/spec_helper.rb index cde34bdbd..e1abb18cf 100644 --- a/sentry-rails/spec/spec_helper.rb +++ b/sentry-rails/spec/spec_helper.rb @@ -2,6 +2,9 @@ require "bundler/setup" +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + ENV["RAILS_ENV"] = "test" begin diff --git a/sentry-resque/spec/spec_helper.rb b/sentry-resque/spec/spec_helper.rb index 4d516832c..37c756384 100644 --- a/sentry-resque/spec/spec_helper.rb +++ b/sentry-resque/spec/spec_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true require "bundler/setup" + +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + begin require "debug/prelude" rescue LoadError diff --git a/sentry-ruby/lib/sentry-ruby.rb b/sentry-ruby/lib/sentry-ruby.rb index 0532e622d..d54022389 100644 --- a/sentry-ruby/lib/sentry-ruby.rb +++ b/sentry-ruby/lib/sentry-ruby.rb @@ -33,6 +33,7 @@ require "sentry/vernier/profiler" require "sentry/metrics" require "sentry/job_extensions/extension" +require "sentry/agent_hint" [ "sentry/rake", @@ -294,6 +295,7 @@ def init(&block) @backpressure_monitor = config.enable_backpressure_handling ? Sentry::BackpressureMonitor.new(config, client) : nil exception_locals_tp.enable if config.data_collection.collect_stack_frame_variables? at_exit { close } + AgentHint.register(config, caller_locations(1, 1).first) end # Flushes pending events and cleans up SDK state. diff --git a/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md b/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md new file mode 100644 index 000000000..64bea8d84 --- /dev/null +++ b/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md @@ -0,0 +1,41 @@ +# Sentry Ruby SDK: setup checklist + +This is Sentry's official setup guidance, shipped in the `sentry-ruby` gem and maintained by Sentry with the SDK. It matches the agent setup guide at https://docs.sentry.io/ai/agent-setup/get-started.md. + +## Required + +- **Errors.** This is Sentry's core product. Set it up unless the user asked you not to. It needs a DSN: if the user hasn't given you one and you can't get one yourself, ask for it. Read it from an environment variable (`SENTRY_DSN`) and don't commit it. In a Rails app, add `sentry-ruby` and `sentry-rails` to the Gemfile and put `Sentry.init` in `config/initializers/sentry.rb`. Before you finish, send a test error and check that it arrives. + +## Recommended + +Turn these on unless the user asked you not to. Sentry links errors, traces and logs, so an error shows the request that caused it and the logs around it. + +- **Tracing.** Shows which request caused an error and where the time went. Set `config.traces_sample_rate` by environment: `1.0` locally, so you can see a trace when you verify, and a low rate in production (`0.1` is a common start) unless the project already has one. Don't default it to `0`: a rate of `0` starts no traces of its own (it only continues traces from incoming requests), and `nil` turns tracing off. +- **Logs.** In Rails, set `config.rails.structured_logging.enabled = true`, so Active Record and Action Controller events show up as logs next to the errors they belong to. Outside Rails, add `config.enabled_patches << :logger` to send what the app writes to a `::Logger`. In Rails that patch also sends every `Rails.logger` line, which can be noisy, so add it only if the user wants that. `Sentry.logger.info(...)` sends a log directly. +- **Environment and release.** Set `config.environment` so production issues are separate from local ones. The SDK reads the release from `SENTRY_RELEASE` or the git commit. If the app runs without `.git` (for example in a Docker image), set `SENTRY_RELEASE` at build time or set `config.release` to the app's version, so you can see which deploy caused an issue. + +To tell production from local runs, use a check the app already has, such as `Rails.env.production?`. Don't add a new variable that nothing sets. + +```ruby +Sentry.init do |config| + config.dsn = ENV["SENTRY_DSN"] + config.environment = Rails.env + config.traces_sample_rate = Rails.env.production? ? 0.1 : 1.0 + config.rails.structured_logging.enabled = true +end +``` + +## Situational + +Do the Required and Recommended items first. Then look at the ones below. Set them up only when the project matches. + +- **Crons**, if the app schedules jobs with sidekiq-cron, sidekiq-scheduler, GoodJob cron, Solid Queue recurring tasks or rufus-scheduler. Sentry alerts when a job fails or doesn't run, and every scheduled job gets a monitor, including ones added later. Add the matching patch: `config.enabled_patches += [:sidekiq_cron]`, `:sidekiq_scheduler`, `:good_job_cron`, `:solid_queue_recurring` or `:rufus_scheduler`. +- **Background jobs**, if the app uses Sidekiq, Resque or Delayed Job. Add `sentry-sidekiq`, `sentry-resque` or `sentry-delayed_job` to the Gemfile, so job errors and traces are captured and linked to the request that queued them. +- **Profiling**, if the user cares about the performance of specific code paths. On Ruby 3.2.1+, add the `vernier` gem and set `config.profiler_class = Sentry::Vernier::Profiler`. On older Rubies, add `stackprof` above `sentry-ruby` in the Gemfile. Then set `config.profiles_sample_rate`. It is relative to `traces_sample_rate`. +- **Metrics**, if the user wants to track counts or values over time (signups, queue depth). Call `Sentry.metrics.count(...)`, `gauge(...)` or `distribution(...)` where they happen. + +## Before you finish + +Tell the user what you set up, the trace sample rate you chose for each environment, whether logs are on, and which situational items you included and why. + +Then set `config.agent_setup_complete = true` in `Sentry.init`. That tells the SDK the setup has been checked, so it stops pointing coding agents to this file. diff --git a/sentry-ruby/lib/sentry/agent_hint.rb b/sentry-ruby/lib/sentry/agent_hint.rb new file mode 100644 index 000000000..5d9659262 --- /dev/null +++ b/sentry-ruby/lib/sentry/agent_hint.rb @@ -0,0 +1,232 @@ +# frozen_string_literal: true + +require "open3" +require "rbconfig" + +module Sentry + # Points a coding agent at SETUP_CHECKLIST.md while it sets up Sentry and + # leaves tracing or logs off. People running the app never see it. + # + # Best effort throughout: failures are logged at debug level and swallowed, so + # the hint can never break Sentry.init, a Rails boot or the app's exit status. + # @!visibility private + class AgentHint + CHECKLIST_PATH = File.expand_path("SETUP_CHECKLIST.md", __dir__) + + # AI_AGENT is the cross-tool convention; the rest cover agents that don't set it. + AGENT_ENV_VARS = %w[CLAUDECODE CODEX_THREAD_ID CODEX_SANDBOX CURSOR_AGENT GEMINI_CLI].freeze + + # How long after the last change to the file that calls Sentry.init the setup + # counts as in progress. Without git we can't tell whose change it is, so it's shorter. + SETUP_WINDOW = 60 * 60 + SETUP_WINDOW_WITHOUT_GIT = 10 * 60 + + # Per git call. A slow repo must not hold up the app's exit or a Rails boot. + GIT_TIMEOUT = 2 + # Its own process group, so a timeout also kills anything git started. + GIT_SPAWN_OPTIONS = Gem.win_platform? ? {} : { pgroup: true } + + class GitTimeout < StandardError; end + + # Say what Sentry won't show, not which settings are off. An agent that sees + # the setting names doesn't open the checklist. + NOT_SHOWN = { tracing: "the request trace around them", logs: "its logs" }.freeze + + @mutex = Mutex.new + @registered = false + @hint = nil + + class << self + # Called by Sentry.init. The hint is shown at exit, unless an integration + # shows it earlier. + def register(config, caller_location) + @init = [config, caller_location&.absolute_path || caller_location&.path] + arm + end + + # Spring runs Sentry.init once in its preloaded app, with the ENV Spring was + # started with, then forks each command with the caller's ENV. Decide again + # in the fork, so a command run by an agent shows the hint. + def after_fork + @mutex = Mutex.new + @registered = false + @hint = nil + arm + end + + def show + message = take + return unless message + + # Piped stdout is only flushed at exit. Flush it first so the hint stays + # last for agents that cut the output with `| tail`. + $stdout.flush + # Not Kernel#warn: it prints nothing when warnings are off (ruby -W0). + $stderr.puts(message) + rescue StandardError + # stderr may be closed. An error raised in at_exit would set exit status 1. + nil + end + + # Returns the message at most once per process. + def take + hint = @mutex.synchronize do + taken, @hint = @hint, nil + taken + end + hint&.message + end + + def coding_agent? + return false if Utils::EnvHelper.env_to_bool(ENV["CI"]) + # Only an explicit falsy value turns hints off, so SENTRY_AGENT_HINTS= keeps them on. + return false if Utils::EnvHelper.env_to_bool(ENV["SENTRY_AGENT_HINTS"], strict: true) == false + + # An empty AI_AGENT doesn't count, so it can't hide the agent-specific vars below. + ai_agent = ENV["AI_AGENT"].to_s + return Utils::EnvHelper.env_to_bool(ai_agent, strict: true) != false unless ai_agent.empty? + + AGENT_ENV_VARS.any? { |name| !ENV[name].to_s.empty? } + end + + def log_failure(config, error) + config&.sdk_logger&.debug(LOGGER_PROGNAME) { "Skipped the coding agent hint: #{error.class}: #{error.message}" } + rescue StandardError + nil + end + + private + + def arm + config, init_file = @init + # ENV checks first: outside a coding agent this is the only work done. + return if config.nil? || @registered || !coding_agent? + return if init_file.nil? || external_source?(init_file) + + hint = new(config, init_file) + return unless hint.applies? + + @mutex.synchronize do + return if @registered + + @registered = true + @hint = hint + end + + pid = Process.pid + at_exit do + # Forked workers inherit at_exit blocks, so only the process that registered prints. + show if Process.pid == pid + end + rescue StandardError => e + log_failure(config, e) + end + + # An installed gem or tool that calls Sentry.init isn't the user's app, + # even when it was installed a moment ago. + def external_source?(path) + path = real_path(path) + [*Gem.path, RbConfig::CONFIG["rubylibdir"]].compact.any? do |dir| + path.start_with?(File.join(real_path(dir), "")) + end + end + + # Gem dirs and tmp dirs are often symlinks (/var -> /private/var on macOS). + def real_path(path) + File.realpath(path) + rescue SystemCallError + File.expand_path(path) + end + end + + def initialize(config, init_file) + @config = config + @init_file = File.expand_path(init_file) + end + + # Runs during Sentry.init, so the slower git checks wait for #message. + def applies? + @config.dsn && !@config.agent_setup_complete && missing.any? && changed_within?(SETUP_WINDOW) + end + + def message + return unless setup_in_progress? + + "[sentry] Sentry will get errors from this app but not #{missing.map { |product| NOT_SHOWN[product] }.join(", or ")}. " \ + "If you're setting up Sentry, check the setup against Sentry's official setup checklist. If you leave " \ + "it as is, tell the user. The checklist is included in the sentry-ruby gem you installed: " \ + "#{CHECKLIST_PATH} (hide with SENTRY_AGENT_HINTS=0)" + rescue StandardError => e + self.class.log_failure(@config, e) + nil + end + + private + + def missing + @missing ||= NOT_SHOWN.keys.reject { |product| enabled?(product) } + end + + def enabled?(product) + case product + when :tracing + !@config.traces_sampler.nil? || @config.traces_sample_rate.to_f.positive? + when :logs + # sentry-rails adds config.rails. There, logs means Rails structured logging; + # the :logger patch would send every Rails.logger line, which is noisy. + if @config.respond_to?(:rails) + @config.rails.structured_logging.enabled? + else + @config.enabled_patches.include?(:logger) + end + end + end + + def changed_within?(seconds) + Time.now - File.mtime(@init_file) <= seconds + rescue SystemCallError + false + end + + # Whether this user changed the file recently. A checkout or a teammate's + # commit also gives the file a new mtime, so ask git. + def setup_in_progress? + status = git("status", "--porcelain", "--", @init_file) + return changed_within?(SETUP_WINDOW_WITHOUT_GIT) if status.nil? + return true unless status.empty? + + committer = git("log", "-1", "--since=#{SETUP_WINDOW} seconds ago", "--format=%ce", "--", @init_file) + !committer.to_s.empty? && committer == git("config", "user.email") + end + + # Returns nil when git isn't installed or the file isn't in a repo, and raises + # GitTimeout when git is too slow, which skips the hint. + # --no-optional-locks: the agent may be running git at the same time. + # core.fsmonitor=false: an fsmonitor would run a command configured in the repo. + # Open3 leaves the app's $? alone. + def git(*args) + Open3.popen2( + "git", "--no-optional-locks", "-c", "core.fsmonitor=false", *args, + chdir: File.dirname(@init_file), err: File::NULL, **GIT_SPAWN_OPTIONS + ) do |stdin, stdout, wait_thread| + stdin.close + # Read while waiting, so a full pipe can't stall git until the timeout. + # Closing stdout after a timeout makes the read raise, which is expected. + reader = Thread.new do + Thread.current.report_on_exception = false + stdout.read + end + + unless wait_thread.join(GIT_TIMEOUT) + Process.kill(:KILL, Gem.win_platform? ? wait_thread.pid : -wait_thread.pid) + raise GitTimeout, "git #{args.first} took over #{GIT_TIMEOUT}s" + end + + output = reader.value + output.strip if wait_thread.value.success? + end + rescue SystemCallError, IOError + nil + end + end +end diff --git a/sentry-ruby/lib/sentry/configuration.rb b/sentry-ruby/lib/sentry/configuration.rb index b640676ac..30b725f4b 100644 --- a/sentry-ruby/lib/sentry/configuration.rb +++ b/sentry-ruby/lib/sentry/configuration.rb @@ -297,6 +297,12 @@ def include_local_variables=(value) # @return [StructuredLoggingConfiguration] attr_reader :structured_logging + # Set to true once the setup has been checked against SETUP_CHECKLIST.md in this gem. + # Coding agents running the app are then no longer pointed at the checklist. + # Default is false. + # @return [Boolean] + attr_accessor :agent_setup_complete + # Send diagnostic client reports about dropped events, true by default # tries to attach to an existing envelope max once every 30s # @return [Boolean] @@ -592,6 +598,7 @@ def initialize self.std_lib_logger_filter = nil self.rack_env_whitelist = RACK_ENV_WHITELIST_DEFAULT self.traces_sampler = nil + self.agent_setup_complete = false self.profiler_class = Sentry::Profiler self.profiles_sample_interval = DEFAULT_PROFILES_SAMPLE_INTERVAL diff --git a/sentry-ruby/spec/sentry/agent_hint_spec.rb b/sentry-ruby/spec/sentry/agent_hint_spec.rb new file mode 100644 index 000000000..0cb18a97f --- /dev/null +++ b/sentry-ruby/spec/sentry/agent_hint_spec.rb @@ -0,0 +1,301 @@ +# frozen_string_literal: true + +require "spec_helper" +require "open3" +require "stringio" +require "tmpdir" + +RSpec.describe Sentry::AgentHint do + let(:checklist) { described_class::CHECKLIST_PATH } + let(:app) { File.join(@dir, "app.rb") } + let(:at_exit_hooks) { [] } + + around do |example| + names = ["CI", "SENTRY_AGENT_HINTS", "AI_AGENT", *described_class::AGENT_ENV_VARS] + saved = ENV.to_h.slice(*names) + names.each { |name| ENV.delete(name) } + + Dir.mktmpdir do |dir| + @dir = dir + example.run + end + ensure + names.each { |name| ENV.delete(name) } + ENV.update(saved) + end + + before do + described_class.instance_variable_set(:@hint, nil) + described_class.instance_variable_set(:@registered, false) + described_class.instance_variable_set(:@init, nil) + allow(described_class).to receive(:at_exit) { |&hook| at_exit_hooks << hook } + end + + # Loads a file that calls Sentry.init, the way an app's initializer does. + def load_app(env, config = "", before_load: nil, path: app) + ENV.update(env) + File.write(path, <<~RUBY) + Sentry.init do |config| + config.sdk_logger = ::Logger.new(nil) + config.dsn = #{Sentry::TestHelper::DUMMY_DSN.inspect} + config.transport.transport_class = Sentry::DummyTransport + #{config} + end + RUBY + before_load&.call(path) + load(path) + end + + # Loads the app and returns what the SDK prints at exit. + def run_app(...) + load_app(...) + capture_stderr { at_exit_hooks.each(&:call) } + end + + def capture_stderr + original, $stderr = $stderr, StringIO.new + yield + $stderr.string + ensure + $stderr = original + end + + describe "who sees it" do + { + { "AI_AGENT" => "claude-code" } => true, + { "CLAUDECODE" => "1" } => true, + { "CODEX_THREAD_ID" => "abc" } => true, + { "CURSOR_AGENT" => "1" } => true, + {} => false, + { "AI_AGENT" => "0" } => false, + { "AI_AGENT" => "claude-code", "CI" => "true" } => false, + { "CLAUDECODE" => "1", "SENTRY_AGENT_HINTS" => "0" } => false, + { "CLAUDECODE" => "" } => false, + { "AI_AGENT" => "", "CLAUDECODE" => "1" } => true, + { "CI" => "", "CLAUDECODE" => "1" } => true, + { "CI" => "false", "CLAUDECODE" => "1" } => true, + { "SENTRY_AGENT_HINTS" => "", "CLAUDECODE" => "1" } => true, + { "SENTRY_AGENT_HINTS" => "off", "CLAUDECODE" => "1" } => false + }.each do |env, shown| + it "is #{"not " unless shown}shown for #{env}" do + expect(run_app(env).include?(checklist)).to be(shown) + end + end + end + + # Gives the config the config.rails.structured_logging.enabled? that sentry-rails adds. + def self.rails_config(structured_logging:) + "logging = Struct.new(:enabled?).new(#{structured_logging}); " \ + "config.define_singleton_method(:rails) { Struct.new(:structured_logging).new(logging) }" + end + + describe "what it says" do + { + "" => "not the request trace around them, or its logs.", + "config.enabled_patches << :logger" => "not the request trace around them.", + "config.traces_sample_rate = 0.1" => "not its logs.", + "config.traces_sampler = ->(_) { 1.0 }" => "not its logs.", + "config.traces_sample_rate = 0.0" => "not the request trace around them, or its logs.", + "#{rails_config(structured_logging: true)}" => "not the request trace around them.", + "#{rails_config(structured_logging: false)}; config.enabled_patches << :logger" => + "not the request trace around them, or its logs." + }.each do |config, missing| + it "says what's missing with #{config.inspect}" do + expect(run_app({ "AI_AGENT" => "claude-code" }, config)) + .to start_with("[sentry] Sentry will get errors from this app but #{missing}") + .and include(checklist) + end + end + end + + [ + "config.traces_sample_rate = 0.1; config.enabled_patches << :logger", + "config.agent_setup_complete = true", + "config.dsn = nil" + ].each do |config| + it "is not shown with #{config.inspect}" do + expect(run_app({ "AI_AGENT" => "claude-code" }, config)).to eq("") + end + end + + it "is shown once" do + load_app({ "AI_AGENT" => "claude-code" }) + + expect(run_app({})).to include(checklist) + expect(at_exit_hooks.size).to eq(1) + end + + it "isn't printed at exit when an integration took it" do + load_app({ "AI_AGENT" => "claude-code" }) + + expect(described_class.take).to include(checklist) + expect(described_class.take).to be_nil + expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") + end + + it "is printed when Ruby warnings are off" do + load_app({ "AI_AGENT" => "claude-code" }) + verbose, $VERBOSE = $VERBOSE, nil + + expect(capture_stderr { at_exit_hooks.each(&:call) }).to include(checklist) + ensure + $VERBOSE = verbose + end + + it "isn't shown when an installed gem calls Sentry.init" do + allow(Gem).to receive(:path).and_return([@dir]) + + expect(run_app({ "AI_AGENT" => "claude-code" })).to eq("") + end + + it "runs git without fsmonitor or optional locks" do + allow(Open3).to receive(:popen2).and_call_original + + run_app({ "AI_AGENT" => "claude-code" }) + + expect(Open3).to have_received(:popen2) + .with("git", "--no-optional-locks", "-c", "core.fsmonitor=false", "status", any_args) + end + + it "does no file or git work outside a coding agent" do + expect(File).not_to receive(:realpath) + expect(Open3).not_to receive(:popen2) + + expect(run_app({})).to eq("") + end + + it "doesn't raise or print when building the message fails" do + load_app({ "AI_AGENT" => "claude-code" }) + allow(Open3).to receive(:popen2).and_raise(RuntimeError, "unexpected") + + expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") + end + + it "doesn't raise when stderr is closed" do + load_app({ "AI_AGENT" => "claude-code" }) + closed = StringIO.new.tap(&:close) + original, $stderr = $stderr, closed + + expect { at_exit_hooks.each(&:call) }.not_to raise_error + ensure + $stderr = original + end + + it "doesn't break Sentry.init when registering fails" do + allow(described_class).to receive(:new).and_raise(NoMethodError, "boom") + + expect { load_app({ "AI_AGENT" => "claude-code" }) }.not_to raise_error + expect(Sentry.initialized?).to be(true) + end + + it "isn't shown when git is too slow, and stops git", skip: Gem.win_platform? && "needs a shell script as git" do + fake_bin = File.join(@dir, "bin") + child_pid_file = File.join(@dir, "git_child.pid") + Dir.mkdir(fake_bin) + File.write(File.join(fake_bin, "git"), "#!/bin/sh\nsleep 5 &\necho $! > #{child_pid_file}.tmp\nmv #{child_pid_file}.tmp #{child_pid_file}\nwait\n") + File.chmod(0o755, File.join(fake_bin, "git")) + stub_const("#{described_class}::GIT_TIMEOUT", 0.5) + path = ENV["PATH"] + load_app({ "AI_AGENT" => "claude-code", "PATH" => "#{fake_bin}#{File::PATH_SEPARATOR}#{path}" }) + + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") + expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 2 + + child_pid = Integer(File.read(child_pid_file)) + sleep 0.1 + expect { Process.kill(0, child_pid) }.to raise_error(Errno::ESRCH) + ensure + ENV["PATH"] = path + end + + describe "under Spring" do + it "is shown by a forked command when Spring was started outside the agent" do + load_app({}) + expect(at_exit_hooks).to be_empty + + ENV["AI_AGENT"] = "claude-code" + allow(Process).to receive(:pid).and_return(Process.pid + 1) + described_class.after_fork + + expect(capture_stderr { at_exit_hooks.each(&:call) }).to include(checklist) + end + + it "is shown by the forked command, not only the preloaded app" do + load_app({ "AI_AGENT" => "claude-code" }) + allow(Process).to receive(:pid).and_return(Process.pid + 1) + described_class.after_fork + + expect(capture_stderr { at_exit_hooks.each(&:call) }.scan(checklist).size).to eq(1) + end + + it "isn't shown by a forked command run outside the agent" do + load_app({ "AI_AGENT" => "claude-code" }) + ENV.delete("AI_AGENT") + allow(Process).to receive(:pid).and_return(Process.pid + 1) + described_class.after_fork + + expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") + end + end + + it "isn't printed by a forked child" do + load_app({ "AI_AGENT" => "claude-code" }) + allow(Process).to receive(:pid).and_return(Process.pid + 1) + + expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") + end + + describe "only while Sentry is being set up" do + before { skip("needs git") unless system("git", "--version", out: File::NULL) } + + def git(path, *args, committer: "dev@example.com", date: nil) + env = { + "GIT_CONFIG_GLOBAL" => File::NULL, "GIT_CONFIG_NOSYSTEM" => "1", + "GIT_COMMITTER_NAME" => "Dev", "GIT_COMMITTER_EMAIL" => committer, + "GIT_AUTHOR_NAME" => "Dev", "GIT_AUTHOR_EMAIL" => committer + } + env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = date if date + _, status = Open3.capture2e(env, "git", *args, chdir: File.dirname(path)) + raise "git #{args.join(" ")} failed" unless status.success? + end + + def commit(path, **options) + git(path, "init", "-q") + git(path, "config", "user.email", "dev@example.com") + git(path, "add", File.basename(path)) + git(path, "commit", "-q", "-m", "Set up Sentry", **options) + end + + def touch(path, minutes_ago) + File.utime(Time.now - minutes_ago * 60, Time.now - minutes_ago * 60, path) + end + + def edit_old_commit(path, minutes_ago: 0) + commit(path, date: "2020-01-01T00:00:00") + File.write(path, "#{File.read(path)}\n") + touch(path, minutes_ago) + end + + { + "new file, no git repo" => [nil, true], + "no git repo, changed 20 minutes ago" => [->(path) { touch(path, 20) }, false], + "uncommitted change" => [->(path) { edit_old_commit(path) }, true], + "uncommitted change, 20 minutes ago" => [->(path) { edit_old_commit(path, minutes_ago: 20) }, true], + "uncommitted change, two hours ago" => [->(path) { edit_old_commit(path, minutes_ago: 120) }, false], + "committed here a moment ago" => [->(path) { commit(path) }, true], + "a teammate's new commit" => [->(path) { commit(path, committer: "teammate@example.com") }, false], + "fresh checkout of an old commit" => [->(path) { commit(path, date: "2020-01-01T00:00:00") }, false] + }.each do |name, (setup, shown)| + it "is #{"not " unless shown}shown for: #{name}" do + before_load = setup && ->(path) { instance_exec(path, &setup) } + + expect(run_app({ "AI_AGENT" => "claude-code" }, before_load: before_load).include?(checklist)).to be(shown) + end + end + end + + it "ships the setup checklist with the gem" do + expect(File.read(checklist)).to include("config.agent_setup_complete = true") + end +end diff --git a/sentry-ruby/spec/spec_helper.rb b/sentry-ruby/spec/spec_helper.rb index 20e055928..2c937663f 100644 --- a/sentry-ruby/spec/spec_helper.rb +++ b/sentry-ruby/spec/spec_helper.rb @@ -23,6 +23,9 @@ REDIS_HOST = ENV.fetch("REDIS_HOST", "127.0.0.1") +# The suite may itself run under a coding agent. The agent hint specs turn hints back on. +ENV["SENTRY_AGENT_HINTS"] = "0" + if ENV["CI"] require 'simplecov-cobertura' SimpleCov.formatter = SimpleCov::Formatter::CoberturaFormatter diff --git a/sentry-sidekiq/spec/spec_helper.rb b/sentry-sidekiq/spec/spec_helper.rb index 3908a2193..765e2d760 100644 --- a/sentry-sidekiq/spec/spec_helper.rb +++ b/sentry-sidekiq/spec/spec_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true require "bundler/setup" + +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + begin require "debug/prelude" rescue LoadError diff --git a/sentry-yabeda/spec/spec_helper.rb b/sentry-yabeda/spec/spec_helper.rb index 711ee6dd2..016ba3804 100644 --- a/sentry-yabeda/spec/spec_helper.rb +++ b/sentry-yabeda/spec/spec_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true require "bundler/setup" + +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + begin require "debug/prelude" rescue LoadError