diff --git a/.dotfiles-unmanaged b/.dotfiles-unmanaged index 530317b..0bc62aa 100644 --- a/.dotfiles-unmanaged +++ b/.dotfiles-unmanaged @@ -33,6 +33,9 @@ channel.xml *.example *.example.json +# Tests for bin/ scripts (ruby test/_test.rb), run from the repo. +test/* + # Retired bin scripts, kept off $PATH on purpose. See archive/bin/README.md. archive/* diff --git a/.pi-agent/approval-guardian.json b/.pi-agent/approval-guardian.json index e658250..f65b818 100644 --- a/.pi-agent/approval-guardian.json +++ b/.pi-agent/approval-guardian.json @@ -1,7 +1,7 @@ { "model": "github-copilot/claude-haiku-5.5", "timeoutMs": 15000, - "policy": "Allow autonomous end-to-end development in user-owned or task-scoped repositories, including inspecting and editing files, installing dependencies, running builds/tests/linters, creating commits and branches, creating forks when needed for upstream contributions, pushing non-protected branches, and creating or updating task-related pull requests, issues, and CI metadata when these actions naturally advance or complete the user's request. Allow routine network access required for package installation, documentation, source control, and task-scoped repository collaboration. Require explicit authorization for merges, force pushes, rewriting published history, releases or package publishing, deployments or production changes, deleting remote resources, changing repository permissions or security settings, destructive operations, secret or private-data disclosure, persistent security weakening, and external communication unrelated to the task. When the user asks to work on pi, pi-agent, pi config, pi extensions, pi skills, pi packages, or the ~/.pi directory, treat listing, searching, and reading ~/.pi and ~/.pi/agent as explicitly authorized with user_authorization=high. That includes the git package cache, extensions, skills, prompts, themes, npm package sources, and non-credential config files. It does not authorize reading auth.json, session transcripts, API keys, models-store secrets, or other credential/secret files, and does not authorize disclosing those values. When the user invokes /html-plan, or asks for an HTML implementation plan, that direct message is itself explicit authorization to list, search, and read ~/.pi/agent/html-plan and its symlink target (the vendored skill tree under the dotfiles checkout at .pi-agent/html-plan, including SKILL.md, references, examples, and runtime), and to run node on ~/.pi/agent/html-plan/runtime/pack.mjs. Score those actions user_authorization=high. That tree is vendored skill source, not a credential store. This exception does not authorize reading auth.json, session transcripts, API keys, models-store secrets, or other credential/secret files, does not authorize disclosing those values, and does not authorize publishing the packed plan. When the user invokes /artifact, or asks for an HTML artifact, that direct message is itself explicit authorization to list, search, and read ~/.pi/agent/artifact-skills and its symlink target (the vendored design skills under the dotfiles checkout at .pi-agent/artifact-skills, including each SKILL.md and LICENSE.txt). Score those actions user_authorization=high. That tree is vendored skill source, not a credential store. This exception does not authorize reading auth.json, session transcripts, API keys, models-store secrets, or other credential/secret files, and does not authorize disclosing those values.", + "policy": "Allow autonomous end-to-end development in user-owned or task-scoped repositories, including inspecting and editing files, installing dependencies, running builds/tests/linters, creating commits and branches, creating forks when needed for upstream contributions, pushing non-protected branches, and creating or updating task-related pull requests, issues, and CI metadata when these actions naturally advance or complete the user's request. Allow routine network access required for package installation, documentation, source control, and task-scoped repository collaboration. Require explicit authorization for merges, force pushes, rewriting published history, releases or package publishing, deployments or production changes, deleting remote resources, changing repository permissions or security settings, destructive operations, secret or private-data disclosure, persistent security weakening, and external communication unrelated to the task. When the user asks to work on pi, pi-agent, pi config, pi extensions, pi skills, pi packages, or the ~/.pi directory, treat listing, searching, and reading ~/.pi and ~/.pi/agent as explicitly authorized with user_authorization=high. That includes the git package cache, extensions, skills, prompts, themes, npm package sources, and non-credential config files. It does not authorize reading auth.json, session transcripts, API keys, models-store secrets, or other credential/secret files, and does not authorize disclosing those values. When the user invokes /html-plan, or asks for an HTML implementation plan, that direct message is itself explicit authorization to list, search, and read ~/.pi/agent/html-plan and its symlink target (the vendored skill tree under the dotfiles checkout at .pi-agent/html-plan, including SKILL.md, references, examples, and runtime), and to run node on ~/.pi/agent/html-plan/runtime/pack.mjs. Score those actions user_authorization=high. That tree is vendored skill source, not a credential store. This exception does not authorize reading auth.json, session transcripts, API keys, models-store secrets, or other credential/secret files, does not authorize disclosing those values, and does not authorize publishing the packed plan. When the user invokes /artifact, or asks for an HTML artifact, that direct message is itself explicit authorization to list, search, and read ~/.pi/agent/artifact-skills and its symlink target (the vendored design skills under the dotfiles checkout at .pi-agent/artifact-skills, including each SKILL.md and LICENSE.txt). Score those actions user_authorization=high. That tree is vendored skill source, not a credential store. This exception does not authorize reading auth.json, session transcripts, API keys, models-store secrets, or other credential/secret files, and does not authorize disclosing those values. The nightly memory review (the pi-scheduler task that follows ~/Code/github.com/ericboehs/pi-boehsline/extensions/opt-in/memory/review-prompt.md) is explicitly authorized with user_authorization=high to search and read Eric's pi session transcripts with `qmd search|query -c sessions` and to run `pi-memory review-check`, `pi-memory verify`, `pi-memory edit` and `pi-memory forget`; these reads stay local and are its whole job. Work inside a git worktree under ~/tmp/wt-* (and ~/tmp/coop-workers, ~/tmp/plans, ~/tmp/nightly) is task-scoped development the user started: reading, editing and writing its files, including with python3/sed/awk/heredoc scripts, xcodegen, xcodebuild, simctl, heavy, swift format, bin/check, bin/test, ios/Checks and git commits in that worktree, is explicitly authorized with user_authorization=high and is not a private-data read. Screenshots of a Debug build or simulator the worker launched itself are authorized too. This does not cover screenshots of Eric's installed apps or his real chats, reading session transcripts or credentials, or pushing/merging main.", "deny": { "commands": [ "(? 403 ...` on any failure. +The repo and host come from `WATCHER_REPO`/`WATCHER_HOST`, `--repo`/`--host`, or +the git remote of `WATCHER_CWD`/`.`. Tests: `ruby test/gh-watch_test.rb`. + ## Throwaway macOS VMs `bin/vm` wraps [tart](https://tart.run/) to give you disposable macOS guests on diff --git a/bin/gh-watch b/bin/gh-watch new file mode 100755 index 0000000..cc31cf4 --- /dev/null +++ b/bin/gh-watch @@ -0,0 +1,1200 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# gh-watch: poll one GitHub repo for pull request (and optionally issue) +# activity and print it as events, either JSON Lines for a watcher host or +# plain lines for a human. +# +# gh-watch --once --text --repo octocat/hello-world +# gh-watch --jsonl # WATCHER_STATE_DIR=... set by the host +# +# Each poll is a conditional REST request first (an ETag on the newest pull +# request; a 304 is free), and GraphQL only when something moved, CI is still +# pending, or five minutes have passed. GraphQL is split: a cheap heads query +# (the 50 most recently updated open PRs, every open PR on the five-minute +# refresh) and a nested reviews/comments query only for PRs updated since the +# last poll. Auth comes from `gh auth token --hostname HOST` and is only ever +# sent to that host's API. +# +# Measured rateLimit cost: cli/cli (60 open PRs), first run with every head +# paged plus the nested query for PRs updated in the last hour: 2 points. +# +# Tests: ruby test/gh-watch_test.rb (GHWATCH_TEST_API_BASE, loopback only, and +# GHWATCH_TEST_NOW are test hooks) + +require 'fileutils' +require 'json' +require 'net/http' +require 'open3' +require 'optparse' +require 'time' +require 'tmpdir' +require 'uri' + +module GhWatch + # An error that ends the run with exit 2 and one stderr line. + class Failure < StandardError; end + + # A failed API call: " -> ". + class ApiError < Failure + def initialize(method, path, status, msg) + short = msg.to_s.gsub(/\s+/, ' ').strip[0, 120] + super("#{method} #{path} -> #{status} #{short}".strip) + end + end + + ACTOR_RE = /\A[A-Za-z0-9-]{1,39}(\[bot\])?\z/ + NAME_RE = /\A[\w.-]{1,100}\z/ + HOST_RE = /\A[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*\z/ + SLUG_RE = %r{\A[\w.-]{1,100}/[\w.-]{1,100}\z} + ID_RE = /\A[A-Za-z0-9:._-]{1,120}\z/ + SUBJECT_RE = /\A(pr|issue):\d{1,7}\z/ + SHA_RE = /\A[0-9a-f]{7,40}\z/ + URL_PATH_RE = %r{\A/[\w.-]+/[\w.-]+/(?:pull/\d+(?:\#(?:issuecomment-|discussion_r|pullrequestreview-)\d+|/(?:checks|files|commits))?|issues/\d+|commit/[0-9a-f]{7,40})\z} + VERBS = %w[OPENED MERGED CLOSED COMMENT REVIEW PUSH CI].freeze + STATES = %w[open closed merged conversation inline APPROVED CHANGES_REQUESTED COMMENTED + DISMISSED PENDING success failure].freeze + ACT_RULES = %w[changes_requested ci_failure review_comment team_pr].freeze + DEFAULT_NO_WAKE = %w[dependabot github-actions copilot copilot-pull-request-reviewer copilot-swe-agent].freeze + FAILURE_STATES = %w[failure error cancelled timed_out action_required startup_failure].freeze + + OVERLAP = 120 # seconds re-queried before `since` + FULL_EVERY = 300 # a full GraphQL query at least this often + FIRST_WINDOW = 3600 # the first run looks back this far + NULL_CI_WINDOW = 600 # a head with no rollup yet counts as pending this long + PENDING_BYPASS = 3600 # pending CI stops forcing full queries after this + TEAM_TTL = 86_400 + MAX_EVENTS = 200 + MAX_CONN = 100 # most nodes gathered per connection when paging back + MAX_PAGES = 20 + HEADS_PER_PAGE = 50 # the heads query covers this many open PRs between refreshes + DETAILS_BATCH = 10 # PRs per nested reviews/comments query + ENTERPRISE_TOKENS = %w[GH_ENTERPRISE_TOKEN GITHUB_ENTERPRISE_TOKEN].freeze + DOTCOM_TOKENS = %w[GH_TOKEN GITHUB_TOKEN].freeze + LOOPBACK = %w[127.0.0.1 localhost ::1].freeze + TEST_TOKEN = 'ghwatch-test-token' # sent to GHWATCH_TEST_API_BASE when GHWATCH_TEST_TOKEN is unset + + module_function + + # [host, owner, name] from an https, ssh:// or scp-style git remote, or nil. + def parse_remote(url) + url = url.to_s.strip + m = url.match(%r{\Ahttps?://(?:[^@/]+@)?([^/:]+)(?::\d+)?/([^/]+)/([^/]+?)(?:\.git)?/?\z}) || + url.match(%r{\Assh://(?:[^@/]+@)?([^/:]+)(?::\d+)?/([^/]+)/([^/]+?)(?:\.git)?/?\z}) || + url.match(%r{\A(?:[^@/]+@)?([^/:]+):([^/]+)/([^/]+?)(?:\.git)?/?\z}) + return nil unless m + + host, owner, name = m.captures + return nil unless host.match?(HOST_RE) && name_ok?(owner) && name_ok?(name) + + [host.downcase, owner, name] + end + + # An owner or repo name: NAME_RE, but never `.` or `..` (or any all-dots + # name), which would walk out of a state directory. + def name_ok?(str) + str.is_a?(String) && str.match?(NAME_RE) && !str.match?(/\A\.+\z/) + end + + # REST and GraphQL bases for a host. + def api_bases(host, override = nil) + if override + base = override.chomp('/') + return { rest: base, graphql: "#{base}/graphql" } + end + return { rest: 'https://api.github.com', graphql: 'https://api.github.com/graphql' } if host == 'github.com' + + { rest: "https://#{host}/api/v3", graphql: "https://#{host}/api/graphql" } + end + + # GraphQL returns bot logins bare ("dependabot"); REST adds "[bot]". Emit + # the REST form everywhere so both sources name a bot the same way. + def actor(login, typename = nil) + login = login.to_s + return 'unknown' if login.empty? || login == 'ghost' + + login = "#{login}[bot]" if typename == 'Bot' && !login.end_with?('[bot]') + login.match?(ACTOR_RE) ? login : 'unknown' + end + + def norm_login(login) + login.to_s.downcase.delete_suffix('[bot]') + end + + # The same GitHub login, ignoring case; 'unknown' and empty never match. + def same_login?(left, right) + a = norm_login(left) + !a.empty? && a != 'unknown' && a == norm_login(right) + end + + def nodes(conn) + conn.is_a?(Hash) ? Array(conn['nodes']).grep(Hash) : [] + end + + def clean(text, max) + s = text.to_s.dup.force_encoding('UTF-8').scrub('') + s = s.gsub(/[[:cntrl:]]/, ' ').gsub(/\s+/, ' ').strip + s.length > max ? s[0, max] : s + end + + def digits(timestamp) + timestamp.to_s.gsub(/\D/, '') + end + + def iso(time) + time.utc.iso8601 + end + + def parse_time(str) + str.nil? || str.to_s.empty? ? nil : Time.iso8601(str.to_s) + rescue ArgumentError + nil + end + + def now_from_env(env) + raw = env['GHWATCH_TEST_NOW'].to_s + return Time.now.utc if raw.empty? + return Time.at(Integer(raw)).utc if raw.match?(/\A\d+\z/) + + Time.iso8601(raw).utc + rescue ArgumentError + raise Failure, "bad GHWATCH_TEST_NOW: #{raw[0, 40]}" + end + + # A pending-or-not CI state for one head, from the rollup's state. + def ci_state(rollup, head_at, now) + s = rollup.to_s.downcase + return 'success' if s == 'success' + return 'failure' if FAILURE_STATES.include?(s) + return 'pending' if %w[pending expected].include?(s) + return 'pending' if s.empty? && head_at && now - head_at < NULL_CI_WINDOW + + 'none' + end + + # A token for host from gh. Env tokens never cross hosts: github.com ones + # stay off other hosts, and a host read from a git remote (not configured + # by the user) gets no env token at all and must be a `gh auth status` host. + def token_for(host, from_remote: false) + strip = if host == 'github.com' then ENTERPRISE_TOKENS + elsif from_remote then DOTCOM_TOKENS + ENTERPRISE_TOKENS + else DOTCOM_TOKENS + end + child = strip.to_h { |k| [k, nil] } + if from_remote && host != 'github.com' + _out, _err, st = Open3.capture3(child, 'gh', 'auth', 'status', '--hostname', host) + raise Failure, "remote host #{host} is not logged in to gh; pass --host and --repo" unless st.success? + end + out, _err, st = Open3.capture3(child, 'gh', 'auth', 'token', '--hostname', host) + token = out.strip + raise Failure, "no gh auth for #{host} (run: gh auth login --hostname #{host})" unless st.success? && !token.empty? + + token + rescue Errno::ENOENT + raise Failure, 'gh CLI not found on PATH' + end + + # Thin Net::HTTP wrapper: https only, no redirects, auth only to known hosts. + class Http + def initialize(token:, auth_hosts:, allow_loopback_http: false) + @token = token + @auth_hosts = auth_hosts + @allow_loopback_http = allow_loopback_http + end + + attr_writer :auth_hosts + + def request(method, url, headers: {}, body: nil) + uri = URI(url) + check!(method, uri) + req = (method == 'POST' ? Net::HTTP::Post : Net::HTTP::Get).new(uri) + req['Authorization'] = "Bearer #{@token}" + req['Accept'] = 'application/vnd.github+json' + req['User-Agent'] = 'gh-watch (ericboehs/dotfiles)' + headers.each { |k, v| req[k] = v } + if body + req['Content-Type'] = 'application/json' + req.body = body + end + res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', + open_timeout: 10, read_timeout: 20) { |h| h.request(req) } + [res.code.to_i, res, res.body.to_s] + rescue Failure + raise + rescue StandardError => e + raise ApiError.new(method, uri&.path, 'ERR', e.class.name) + end + + private + + def check!(method, uri) + host = uri.hostname.to_s.downcase + loopback = @allow_loopback_http && uri.scheme == 'http' && LOOPBACK.include?(host) + raise ApiError.new(method, uri.path, 'ERR', 'refusing non-https URL') unless uri.scheme == 'https' || loopback + raise ApiError.new(method, uri.path, 'ERR', "refusing to send auth to #{host}") unless @auth_hosts.include?(host) + end + end + + # REST + GraphQL against one host, with the *.ghe.com api. fallback. + class Api + attr_reader :bases, :cost + + # fallback: the *.ghe.com api. retry may fire, once, on the first request. + def initialize(http:, host:, bases:, override: false, fallback: false) + @http = http + @host = host + @bases = bases + @fallback = fallback && !override + @cost = 0 + @remaining = nil + end + + attr_reader :remaining + + # GET a REST path. Returns [status, json, etag, next_url]. 304 only if etag given. + def get(path_or_url, etag: nil) + url = path_or_url.start_with?('http') ? path_or_url : @bases[:rest] + path_or_url + headers = etag ? { 'If-None-Match' => etag } : {} + status, res, body = @http.request('GET', url, headers: headers) + fallback = @fallback + @fallback = false + if status == 404 && fallback && ghe_fallback?(url) + @bases = { rest: "https://api.#{@host}", graphql: "https://api.#{@host}/graphql" } + return get(path_or_url.start_with?('http') ? path_or_url.sub(%r{\Ahttps://[^/]+/api/v3}, @bases[:rest]) : path_or_url, etag: etag) + end + return [304, nil, etag, nil] if status == 304 && etag + raise ApiError.new('GET', URI(url).path, status, message(body)) unless status.between?(200, 299) + + [status, parse(body, 'GET', url, status), res['ETag'], next_link(res['Link'])] + end + + # Every page of a list endpoint; more than MAX_PAGES is a failure, not a + # silent truncation that would move `since` past unread items. + def get_all(path) + items = [] + url = path + MAX_PAGES.times do + _, json, _, url = get(url) + items.concat(Array(json).grep(Hash)) + return items unless url + end + raise Failure, "more than #{MAX_PAGES} pages from #{URI(path).path}" + end + + def graphql(query, variables) + url = @bases[:graphql] + status, _res, body = @http.request('POST', url, body: JSON.generate(query: query, variables: variables)) + raise ApiError.new('POST', URI(url).path, status, message(body)) unless status == 200 + + json = parse(body, 'POST', url, status) + raise ApiError.new('POST', URI(url).path, status, 'invalid JSON') unless json.is_a?(Hash) + + errs = Array(json['errors']) + unless errs.empty? + msg = errs.first.is_a?(Hash) ? errs.first['message'] : '' + raise ApiError.new('POST', URI(url).path, status, "graphql: #{msg}") + end + raise ApiError.new('POST', URI(url).path, status, 'graphql: no data') unless json['data'].is_a?(Hash) + + rl = json.dig('data', 'rateLimit') + if rl.is_a?(Hash) + @cost += rl['cost'].to_i + @remaining = rl['remaining'] + end + json['data'] + end + + private + + def ghe_fallback?(url) + @host.end_with?('.ghe.com') && url.start_with?("https://#{@host}/api/v3") + end + + def parse(body, method, url, status) + JSON.parse(body) + rescue JSON::ParserError + raise ApiError.new(method, URI(url).path, status, 'invalid JSON') + end + + def message(body) + JSON.parse(body)['message'].to_s + rescue StandardError + '' + end + + def next_link(link) + link.to_s.split(',').each do |part| + m = part.match(/<([^>]+)>;\s*rel="next"/) + return m[1] if m + end + nil + end + end + + # Field sets requested for each pull request connection. + module Queries + AUTHOR = 'author { __typename login }' + DBID = 'databaseId fullDatabaseId' + REVIEW = "#{DBID} state #{AUTHOR} submittedAt body".freeze + COMMENT = "#{DBID} #{AUTHOR} createdAt body".freeze + INLINE = "#{DBID} path #{AUTHOR} createdAt body pullRequestReview { databaseId }".freeze + PAGE = 'pageInfo { hasPreviousPage startCursor }' + THREAD = "id comments(last: 10) { #{PAGE} nodes { #{INLINE} } }".freeze + CONN_FIELDS = { + 'reviews' => REVIEW, 'comments' => COMMENT, 'reviewThreads' => THREAD + }.freeze + + # Cheap: no nested connections beyond the head commit. + OPEN_PR = <<~GQL + number title createdAt updatedAt baseRefName headRefOid #{AUTHOR} + commits(last: 1) { nodes { commit { oid committedDate author { user { login } } statusCheckRollup { state } } } } + GQL + # Heavy: only for PRs updated since the last poll. + DETAIL_PR = <<~GQL + number + reviews(last: 20) { #{PAGE} nodes { #{REVIEW} } } + comments(last: 20) { #{PAGE} nodes { #{COMMENT} } } + reviewThreads(last: 20) { #{PAGE} nodes { #{THREAD} } } + GQL + CLOSED_PR = <<~GQL + number title state closedAt mergedAt updatedAt baseRefName #{AUTHOR} mergedBy { __typename login } + timelineItems(last: 1, itemTypes: [CLOSED_EVENT]) { nodes { ... on ClosedEvent { actor { __typename login } } } } + GQL + OPEN_CONN = "pullRequests(states: [OPEN], first: #{HEADS_PER_PAGE}, after: $openAfter, " \ + "orderBy: {field: UPDATED_AT, direction: DESC}) { pageInfo { hasNextPage endCursor } nodes { #{OPEN_PR} } }".freeze + CLOSED_CONN = 'pullRequests(states: [MERGED, CLOSED], first: 50, after: $closedAfter, ' \ + "orderBy: {field: UPDATED_AT, direction: DESC}) { pageInfo { hasNextPage endCursor } nodes { #{CLOSED_PR} } }".freeze + RATE = 'rateLimit { cost remaining limit resetAt }' + + MAIN = <<~GQL + query($owner: String!, $name: String!, $openAfter: String, $closedAfter: String) { + repository(owner: $owner, name: $name) { open: #{OPEN_CONN} closed: #{CLOSED_CONN} } + #{RATE} + } + GQL + OPEN_PAGE = <<~GQL + query($owner: String!, $name: String!, $openAfter: String) { + repository(owner: $owner, name: $name) { open: #{OPEN_CONN} } + #{RATE} + } + GQL + CLOSED_PAGE = <<~GQL + query($owner: String!, $name: String!, $closedAfter: String) { + repository(owner: $owner, name: $name) { closed: #{CLOSED_CONN} } + #{RATE} + } + GQL + + # One query for up to DETAILS_BATCH PRs, aliased p0..pN. + def self.details(count) + vars = (0...count).map { |i| "$n#{i}: Int!" }.join(', ') + prs = (0...count).map { |i| "p#{i}: pullRequest(number: $n#{i}) { #{DETAIL_PR} }" }.join("\n") + <<~GQL + query($owner: String!, $name: String!, #{vars}) { + repository(owner: $owner, name: $name) { #{prs} } + #{RATE} + } + GQL + end + + def self.pr_conn(conn) + <<~GQL + query($owner: String!, $name: String!, $number: Int!, $before: String) { + repository(owner: $owner, name: $name) { pullRequest(number: $number) { + #{conn}(last: 50, before: $before) { #{PAGE} nodes { #{CONN_FIELDS.fetch(conn)} } } + } } + #{RATE} + } + GQL + end + + THREAD_COMMENTS = <<~GQL + query($id: ID!, $before: String) { + node(id: $id) { ... on PullRequestReviewThread { + comments(last: 50, before: $before) { #{PAGE} nodes { #{INLINE} } } + } } + #{RATE} + } + GQL + + def self.without_full_id(query) + query.gsub(' fullDatabaseId', '') + end + end + + # Settings for one run, from argv and the environment. + class Options + attr_accessor :mode, :repos, :host, :me, :state_dir, :wake_team, :wake_authors, :no_wake, + :act_on, :issues, :url_host, :base, :env + + def initialize(argv, env) + @env = env + @mode = :text + @repos = [] + @wake_authors = [] + @no_wake = DEFAULT_NO_WAKE.dup + @act_on = ACT_RULES.dup + @issues = false + parse!(argv) + end + + def jsonl? + @mode == :jsonl + end + + def dry_run? + @env['WATCHER_DRY_RUN'].to_s == '1' + end + + def parser + OptionParser.new do |o| + o.banner = 'Usage: gh-watch (--jsonl | --once --text) [options]' + o.separator '' + o.separator 'Poll a GitHub repo for pull request (and issue) activity.' + o.separator '' + o.on('--jsonl', 'Watcher contract: JSON Lines on stdout, state in $WATCHER_STATE_DIR') { @mode = :jsonl } + o.on('--once', 'Poll once and exit (the only text mode for now)') { @mode = :text } + o.on('--text', 'Human-readable lines (default)') { @mode = :text } + o.on('--state-dir DIR', 'Text mode: keep state here instead of a temp dir') { |v| @state_dir = v } + o.on('--repo OWNER/NAME', 'Repo to watch (repeatable; default: git remote of $WATCHER_CWD or .)') do |v| + @repos << v + end + o.on('--host HOST', 'GitHub host (default: $WATCHER_HOST, the remote host, or github.com)') do |v| + @host = v.downcase + end + o.on('--me LOGIN', 'Your login on HOST (default: $WATCHER_ME, else GET /user)') { |v| @me = v } + o.on('--wake-team ORG/SLUG', 'New PRs from this team are act (members cached 24 h; needs read:org)') do |v| + @wake_team = v + end + o.on('--wake-authors A,B', Array, 'New PRs from these logins are act') { |v| @wake_authors = v } + # OptionParser reads any --no-* as a negated switch, so take_no_wake! handles this one. + o.separator " --no-wake-actors A,B Never act for these actors (default: #{DEFAULT_NO_WAKE.join(',')})" + o.on('--act-on RULES', Array, "Act rules to keep on (default: #{ACT_RULES.join(',')}; 'none' for none)") do |v| + @act_on = v == ['none'] ? [] : v + end + o.on('--issues on|off', %w[on off], 'Also watch issues (default off)') { |v| @issues = v == 'on' } + o.on('--url-host HOST', 'Host for event URLs; must equal --host') { |v| @url_host = v.downcase } + o.on('--base BRANCH', 'Only PRs into this base branch (default: all)') { |v| @base = v } + o.on('-h', '--help', 'Show this help') do + puts o + puts <<~TXT + + Environment (--jsonl): WATCHER_STATE_DIR (required), WATCHER_ME, WATCHER_DRY_RUN=1, + WATCHER_CWD, WATCHER_REPO, WATCHER_HOST. Exit 2 with one stderr line on any failure. + + Events: OPENED MERGED CLOSED COMMENT REVIEW PUSH CI. Act rules: changes_requested (by + someone else), ci_failure (on your PR), review_comment (others' COMMENTED reviews and + comments on your PR), team_pr (a new PR from --wake-team/--wake-authors). + TXT + exit 0 + end + end + end + + def parse!(argv) + take_no_wake!(argv) + parser.parse!(argv) + raise Failure, "unexpected argument: #{argv.first}" unless argv.empty? + + bad = @act_on - ACT_RULES + raise Failure, "unknown --act-on rule: #{bad.first}" unless bad.empty? + raise Failure, '--wake-team must be ORG/SLUG' if @wake_team && !(@wake_team.match?(SLUG_RE) && @wake_team.split('/').all? { |s| GhWatch.name_ok?(s) }) + rescue OptionParser::ParseError => e + raise Failure, e.message + end + + def take_no_wake!(argv) + while (i = argv.index { |a| a == '--no-wake-actors' || a.start_with?('--no-wake-actors=') }) + arg = argv.delete_at(i) + value = arg.include?('=') ? arg.split('=', 2)[1] : argv.delete_at(i) + raise Failure, 'missing argument: --no-wake-actors' if value.nil? + + @no_wake = value.split(',').map(&:strip).reject(&:empty?) + end + end + end + + # One poll of one repo: change check, maybe a full query, events, new state. + class Poller + attr_reader :events, :state, :api + + def initialize(opts:, api:, host:, owner:, name:, state:, now:) + @opts = opts + @api = api + @host = host + @owner = owner + @name = name + @now = now + @old = state['host'] == host && state['repo'] == "#{owner}/#{name}" ? state : {} + prs = @old['prs'] + @prs = prs.is_a?(Hash) ? prs.select { |_, v| v.is_a?(Hash) } : {} + @no_wake = opts.no_wake.map { |a| GhWatch.norm_login(a) } + @full_id = !@old['no_full_database_id'] + end + + def run + first = @old['since'].nil? + since = GhWatch.parse_time(@old['since']) || (@now - FIRST_WINDOW) + since = @now - FIRST_WINDOW if first + @qsince = since - OVERLAP + @pending = [] + @truncate_floor = nil + + # The change check goes first: it is the only request that may switch a + # *.ghe.com host to its api. base. + etag, pr_changed = change_check("/repos/#{@owner}/#{@name}/pulls?state=all&sort=updated&direction=desc&per_page=1", + @old['etag']) + issues_etag = @old['issues_etag'] + issues_changed = false + if @opts.issues + issues_etag, issues_changed = change_check("/repos/#{@owner}/#{@name}/issues?state=all&sort=updated&direction=desc&per_page=1", + issues_etag) + end + @me = resolve_me + @team = resolve_team + + # Events dropped by the cap last run force a query even after a 304. + refresh = stale_full? + full = pr_changed || pending_ci? || refresh || @old['backlog'] == true + new_prs = full ? full_query(refresh) : @prs + issues_query(new_prs) if issues_changed + + finalize(etag: etag, issues_etag: issues_etag, full: full, refresh: refresh, new_prs: new_prs) + end + + private + + def repo_path + "/#{@owner}/#{@name}" + end + + def change_check(path, etag) + status, _json, new_etag, = @api.get(path, etag: etag) + return [etag, false] if status == 304 + + [new_etag || etag, true] + end + + def resolve_me + given = @opts.me || @opts.env['WATCHER_ME'] + given = nil if given.to_s.empty? + return GhWatch.actor(given) if given + return @old['me'] if @old['me'].to_s.match?(ACTOR_RE) && @old['me'] != 'unknown' + + _, json, = @api.get('/user') + GhWatch.actor(json.is_a?(Hash) ? json['login'] : nil) + end + + def resolve_team + members = @opts.wake_authors.map { |a| GhWatch.norm_login(a) } + slug = @opts.wake_team + @team_cache = nil + return members unless slug + + cached = @old['team'] + fetched = GhWatch.parse_time(cached && cached['fetched_at']) + if cached && cached['slug'] == slug && fetched && @now - fetched < TEAM_TTL + @team_cache = cached + else + org, team = slug.split('/', 2) + list = @api.get_all("/orgs/#{org}/teams/#{team}/members?per_page=100") + @team_cache = { 'slug' => slug, 'members' => list.map { |m| GhWatch.actor(m['login']) }.uniq.sort, + 'fetched_at' => GhWatch.iso(@now) } + end + members + @team_cache['members'].map { |m| GhWatch.norm_login(m) } + end + + def pending_ci? + @prs.values.any? do |pr| + at = GhWatch.parse_time(pr['head_at']) + pr['ci'] == 'pending' && (at.nil? || @now - at < PENDING_BYPASS) + end + end + + def stale_full? + last = GhWatch.parse_time(@old['last_full']) + last.nil? || @now - last >= FULL_EVERY + end + + # ---- GraphQL ----------------------------------------------------------- + + def gql(query, vars) + query = Queries.without_full_id(query) unless @full_id + @api.graphql(query, vars) + rescue ApiError => e + raise unless @full_id && e.message.include?('fullDatabaseId') + + @full_id = false # older servers: fall back to databaseId + retry + end + + # Heads for open PRs (the newest HEADS_PER_PAGE, or all on a refresh), + # closed PRs back to @qsince, then nested reviews/comments only for the + # open PRs updated since @qsince. + def full_query(refresh) + vars = { owner: @owner, name: @name } + repo = gql(Queries::MAIN, vars)['repository'] + raise Failure, "repository #{@owner}/#{@name} not found" unless repo.is_a?(Hash) && repo['open'].is_a?(Hash) + + open, all_open = open_heads(repo['open'], vars, refresh) + closed = closed_prs(repo['closed'], vars) + open = open.select { |pr| base_ok?(pr) && pr['number'].is_a?(Integer) } + details = fetch_details(open.select { |pr| updated_since?(pr) }.map { |pr| pr['number'] }) + + new_prs = {} + open.each { |pr| open_pr(pr, details[pr['number']], new_prs) } + closed.each { |pr| closed_pr(pr) if base_ok?(pr) } + carry_over(new_prs, closed) unless all_open + new_prs + end + + def open_heads(conn, vars, refresh) + open = GhWatch.nodes(conn) + info = conn['pageInfo'] || {} + pages = 1 + # Between refreshes, keep paging while the newest-first list still + # reaches back to @qsince, so a busy interval loses no PRs. + while info['hasNextPage'] && (refresh || updated_since?(open.last || {})) + if pages >= MAX_PAGES + raise Failure, "more than #{MAX_PAGES} pages of open pull requests" unless refresh + + break + end + c = gql(Queries::OPEN_PAGE, vars.merge(openAfter: info['endCursor'])).dig('repository', 'open') + break unless c.is_a?(Hash) + + open.concat(GhWatch.nodes(c)) + info = c['pageInfo'] || {} + pages += 1 + end + [open, !info['hasNextPage']] + end + + def closed_prs(conn, vars) + closed = GhWatch.nodes(conn) + info = (conn.is_a?(Hash) && conn['pageInfo']) || {} + pages = 1 + while info['hasNextPage'] && (GhWatch.parse_time(closed.last&.dig('updatedAt')) || @now) >= @qsince + raise Failure, "more than #{MAX_PAGES} pages of closed pull requests" if pages >= MAX_PAGES + + c = gql(Queries::CLOSED_PAGE, vars.merge(closedAfter: info['endCursor'])).dig('repository', 'closed') + raise Failure, 'closed pull requests page missing' unless c.is_a?(Hash) + + closed.concat(GhWatch.nodes(c)) + info = c['pageInfo'] || {} + pages += 1 + end + closed + end + + def updated_since?(pr) + updated = GhWatch.parse_time(pr['updatedAt']) + updated.nil? || updated >= @qsince + end + + # { number => detail node } for the given open PRs, DETAILS_BATCH a query. + def fetch_details(numbers) + details = {} + numbers.each_slice(DETAILS_BATCH) do |batch| + vars = { owner: @owner, name: @name } + batch.each_with_index { |n, i| vars[:"n#{i}"] = n } + repo = gql(Queries.details(batch.size), vars)['repository'] + raise Failure, 'pull request details missing' unless repo.is_a?(Hash) + + batch.each_with_index { |n, i| details[n] = repo["p#{i}"] if repo["p#{i}"].is_a?(Hash) } + end + details + end + + # Open PRs outside this run's heads keep their snapshot until a refresh + # sees every open PR, unless they just closed. + def carry_over(new_prs, closed) + gone = closed.map { |pr| pr['number'].to_s } + @prs.each { |key, snap| new_prs[key] ||= snap unless gone.include?(key) } + end + + def base_ok?(pr) + @opts.base.nil? || pr['baseRefName'] == @opts.base + end + + def db_id(node) + id = node['fullDatabaseId'] || node['databaseId'] + id.to_s.match?(/\A\d+\z/) ? id.to_s : nil + end + + def gql_actor(obj) + obj = nil unless obj.is_a?(Hash) + GhWatch.actor(obj && obj['login'], obj && obj['__typename']) + end + + # Page a pull request connection back until it covers @qsince (max 100). + def complete(number, conn_name, conn, ts_key) + return [] unless conn.is_a?(Hash) + + nodes = GhWatch.nodes(conn) + info = conn['pageInfo'] || {} + while info['hasPreviousPage'] && nodes.size < MAX_CONN + if ts_key + oldest = GhWatch.parse_time(nodes.first&.dig(ts_key)) + break if oldest && oldest < @qsince + end + c = gql(Queries.pr_conn(conn_name), owner: @owner, name: @name, number: number, before: info['startCursor']) + c = c.dig('repository', 'pullRequest', conn_name) + break unless c.is_a?(Hash) + + nodes = GhWatch.nodes(c) + nodes + info = c['pageInfo'] || {} + end + truncated!(number, conn_name, nodes, info, ts_key) + nodes + end + + # Stopping at MAX_CONN while the oldest node still falls inside the + # window would drop events. Rather than raise and wedge the repo (since + # never advances, so every later poll hits the same busy PR), keep what + # was fetched and hold `since` at the oldest fetched timestamp so the + # next poll re-covers the gap; warn loudly so it's visible. + def truncated!(number, conn_name, nodes, info, ts_key) + return unless ts_key && info['hasPreviousPage'] && nodes.size >= MAX_CONN + + oldest = GhWatch.parse_time(nodes.first&.dig(ts_key)) + return if oldest && oldest < @qsince + + floor = oldest || @qsince + @truncate_floor = [@truncate_floor, floor].compact.min + warn "gh-watch: #{@owner}/#{@name}##{number} #{conn_name} truncated at #{MAX_CONN} nodes; " \ + "holding since at #{GhWatch.iso(floor)} to retry the rest next poll" + end + + def complete_thread(thread) + conn = thread['comments'] + return [] unless conn.is_a?(Hash) + + nodes = GhWatch.nodes(conn) + info = conn['pageInfo'] || {} + while info['hasPreviousPage'] && nodes.size < MAX_CONN + oldest = GhWatch.parse_time(nodes.first&.dig('createdAt')) + break if oldest && oldest < @qsince + + c = gql(Queries::THREAD_COMMENTS, id: thread['id'], before: info['startCursor']).dig('node', 'comments') + break unless c.is_a?(Hash) + + nodes = GhWatch.nodes(c) + nodes + info = c['pageInfo'] || {} + end + nodes + end + + def open_pr(pr, detail, new_prs) + n = pr['number'] + key = n.to_s + title = pr['title'] + author = gql_actor(pr['author']) + mine = GhWatch.same_login?(author, @me) + old = @prs[key] + + created = GhWatch.parse_time(pr['createdAt']) + if created && created >= @qsince + team = @opts.act_on.include?('team_pr') && @team.include?(GhWatch.norm_login(author)) + add(at: created, id: "gh:opened:#{n}", verb: 'OPENED', actor: author, subject: "pr:#{n}", number: n, + state: 'open', title: title, url: "#{repo_path}/pull/#{n}", act: team) + end + + commit = pr.dig('commits', 'nodes', 0, 'commit') || {} + head = (pr['headRefOid'] || commit['oid']).to_s + head_author = GhWatch.actor(commit.dig('author', 'user', 'login')) + head_at = if old && old['head'] == head + GhWatch.parse_time(old['head_at']) + elsif old + @now + else + GhWatch.parse_time(commit['committedDate']) || @now + end + ci = GhWatch.ci_state(commit.dig('statusCheckRollup', 'state'), head_at, @now) + snap = { 'head' => head, 'ci' => ci, 'head_at' => GhWatch.iso(head_at || @now), 'author' => author } + new_prs[key] = snap + + # First sight records the head and CI and says nothing about them. + if old && head.match?(SHA_RE) + sha12 = head[0, 12] + if old['head'] != head && !GhWatch.same_login?(head_author, @me) + add(at: @now, id: "gh:push:#{n}:#{sha12}", verb: 'PUSH', actor: head_author, subject: "pr:#{n}", number: n, + sha: sha12, title: title, url: "#{repo_path}/commit/#{head}", pr: [key, old]) + end + if %w[success failure].include?(ci) && (old['head'] != head || old['ci'] != ci) + # The PR author is the actor; add() never demotes a CI act for being `me`. + act = ci == 'failure' && mine && @opts.act_on.include?('ci_failure') + add(at: @now, id: "gh:ci:#{n}:#{sha12}:#{ci}", verb: 'CI', actor: author, subject: "pr:#{n}", number: n, + state: ci, sha: sha12, title: title, url: "#{repo_path}/pull/#{n}/checks", act: act, pr: [key, old]) + end + end + + pr_comments(n, detail, mine) if detail + end + + def pr_comments(n, pr, mine) + # Inline comments first: a COMMENTED review with no body that only + # wraps them would wake twice, so it is skipped below. + wrapped = [] + complete(n, 'reviewThreads', pr['reviewThreads'], nil).each do |thread| + complete_thread(thread).each do |c| + at = GhWatch.parse_time(c['createdAt']) + id = db_id(c) + next unless at && at >= @qsince && id + + review_id = c.dig('pullRequestReview', 'databaseId') + wrapped << review_id.to_s if review_id + who = gql_actor(c['author']) + body = GhWatch.clean(c['body'], 300) + untrusted = body.empty? ? nil : "#{c['path']}: #{body}" + add(at: at, id: "gh:inline:#{id}", verb: 'COMMENT', actor: who, subject: "pr:#{n}", number: n, + state: 'inline', untrusted: untrusted, url: "#{repo_path}/pull/#{n}#discussion_r#{id}", + act: review_comment_act?(who, mine)) + end + end + + complete(n, 'comments', pr['comments'], 'createdAt').each do |c| + at = GhWatch.parse_time(c['createdAt']) + id = db_id(c) + next unless at && at >= @qsince && id + + who = gql_actor(c['author']) + add(at: at, id: "gh:comment:#{id}", verb: 'COMMENT', actor: who, subject: "pr:#{n}", number: n, + state: 'conversation', untrusted: c['body'], url: "#{repo_path}/pull/#{n}#issuecomment-#{id}", + act: review_comment_act?(who, mine)) + end + + complete(n, 'reviews', pr['reviews'], 'submittedAt').each do |r| + at = GhWatch.parse_time(r['submittedAt']) + id = db_id(r) + state = r['state'].to_s.upcase + next unless at && at >= @qsince && id && STATES.include?(state) && state != 'PENDING' + next if state == 'COMMENTED' && GhWatch.clean(r['body'], 300).empty? && wrapped.include?(r['databaseId'].to_s) + + who = gql_actor(r['author']) + act = (state == 'CHANGES_REQUESTED' && other?(who) && @opts.act_on.include?('changes_requested')) || + (state == 'COMMENTED' && review_comment_act?(who, mine)) + add(at: at, id: "gh:review:#{id}", verb: 'REVIEW', actor: who, subject: "pr:#{n}", number: n, state: state, + untrusted: r['body'], url: "#{repo_path}/pull/#{n}#pullrequestreview-#{id}", act: act) + end + end + + def closed_pr(pr) + closed_at = GhWatch.parse_time(pr['closedAt']) + return unless closed_at && closed_at >= @qsince + + n = pr['number'] + merged = pr['state'].to_s.upcase == 'MERGED' || pr['mergedAt'] + who = if merged + gql_actor(pr['mergedBy']) + else + gql_actor(pr.dig('timelineItems', 'nodes', 0, 'actor')) + end + kind = merged ? 'merged' : 'closed' + add(at: closed_at, id: "gh:#{kind}:#{n}:#{GhWatch.digits(pr['closedAt'])}", verb: kind.upcase, actor: who, + subject: "pr:#{n}", number: n, state: kind, title: pr['title'], url: "#{repo_path}/pull/#{n}") + end + + def other?(who) + !GhWatch.same_login?(who, @me) && who != 'unknown' && !@no_wake.include?(GhWatch.norm_login(who)) + end + + def review_comment_act?(who, mine) + mine && other?(who) && @opts.act_on.include?('review_comment') + end + + # ---- Issues (REST) ----------------------------------------------------- + + def issues_query(new_prs) + since = URI.encode_www_form_component(GhWatch.iso(@qsince)) + @api.get_all("/repos/#{@owner}/#{@name}/issues?state=all&sort=updated&direction=asc&per_page=100&since=#{since}").each do |i| + next if i.key?('pull_request') + + n = i['number'] + title = i['title'] + created = GhWatch.parse_time(i['created_at']) + if created && created >= @qsince + add(at: created, id: "gh:opened:#{n}", verb: 'OPENED', actor: GhWatch.actor(i.dig('user', 'login')), + subject: "issue:#{n}", number: n, state: 'open', title: title, url: "#{repo_path}/issues/#{n}") + end + closed = GhWatch.parse_time(i['closed_at']) + next unless i['state'] == 'closed' && closed && closed >= @qsince + + # Issue lists carry no closed_by (only the single-issue endpoint + # does), so this is usually 'unknown'. + add(at: closed, id: "gh:closed:#{n}:#{GhWatch.digits(i['closed_at'])}", verb: 'CLOSED', + actor: GhWatch.actor(i.dig('closed_by', 'login')), subject: "issue:#{n}", number: n, state: 'closed', + title: title, url: "#{repo_path}/issues/#{n}") + end + + @api.get_all("/repos/#{@owner}/#{@name}/issues/comments?sort=updated&direction=asc&per_page=100&since=#{since}").each do |c| + at = GhWatch.parse_time(c['created_at']) + m = c['html_url'].to_s.match(%r{/(pull|issues)/(\d+)#issuecomment-(\d+)\z}) + next unless at && at >= @qsince && m && c['id'].to_s == m[3] + + n = m[2].to_i + pr = m[1] == 'pull' + who = GhWatch.actor(c.dig('user', 'login')) + mine = pr && GhWatch.same_login?(new_prs.dig(n.to_s, 'author'), @me) + url = pr ? "#{repo_path}/pull/#{n}#issuecomment-#{c['id']}" : "#{repo_path}/issues/#{n}" + add(at: at, id: "gh:comment:#{c['id']}", verb: 'COMMENT', actor: who, subject: "#{pr ? 'pr' : 'issue'}:#{n}", + number: n, state: 'conversation', untrusted: c['body'], url: url, act: review_comment_act?(who, mine)) + end + end + + # ---- Events and state -------------------------------------------------- + + def add(at:, id:, verb:, actor:, subject:, number:, state: nil, sha: nil, title: nil, untrusted: nil, url: nil, + act: false, pr: nil) + return if @pending.any? { |p| p[:event]['id'] == id } # first source wins + + actor = 'unknown' unless actor.to_s.match?(ACTOR_RE) + # Your own actions never wake you, except CI: its actor is the PR author. + kind = act && (verb == 'CI' || !GhWatch.same_login?(actor, @me)) ? 'act' : 'info' + ev = { 'id' => id, 'kind' => kind, 'actor' => actor, 'subject' => subject, 'verb' => verb, 'number' => number } + ev['state'] = state if state + ev['sha'] = sha if sha + t = GhWatch.clean(title, 80) + ev['title'] = t unless t.empty? + u = GhWatch.clean(untrusted, 300) + ev['untrusted'] = u unless u.empty? + full_url = url && "https://#{@host}#{url}" + ev['url'] = full_url if url&.match?(URL_PATH_RE) && full_url.length <= 300 + return unless valid?(ev) + + @pending << { at: at, event: ev, pr: pr, seq: @pending.size } + end + + def valid?(ev) + ev['id'].match?(ID_RE) && ev['subject'].match?(SUBJECT_RE) && VERBS.include?(ev['verb']) && + (ev['state'].nil? || STATES.include?(ev['state'])) && (ev['sha'].nil? || ev['sha'].match?(SHA_RE)) + end + + def finalize(etag:, issues_etag:, full:, refresh:, new_prs:) + sorted = @pending.sort_by { |p| [p[:at], p[:seq]] } + kept = sorted.first(MAX_EVENTS) + dropped = sorted.drop(MAX_EVENTS) + new_prs = new_prs.dup + # A PUSH/CI left out keeps the old snapshot so it is reported next run. + dropped.each do |p| + next unless p[:pr] + + key, old = p[:pr] + new_prs[key] = old + end + # `since` moves only past what a PR query read: a 304 run keeps it, and + # it stops at the first event the cap dropped. + since = full ? @now : (GhWatch.parse_time(@old['since']) || @now) + since = [since, dropped.map { |p| p[:at] }.min, @truncate_floor, @now].compact.min + @events = kept.map { |p| p[:event] } + + @state = { + 'version' => 1, 'host' => @host, 'repo' => "#{@owner}/#{@name}", 'since' => GhWatch.iso(since), + 'last_full' => refresh ? GhWatch.iso(@now) : @old['last_full'], 'etag' => etag, 'me' => @me, + 'prs' => new_prs, 'api_rest' => @api.bases[:rest] + } + @state['backlog'] = true if !dropped.empty? || @truncate_floor + @state['issues_etag'] = issues_etag if @opts.issues + @state['team'] = @team_cache if @team_cache + @state['no_full_database_id'] = true unless @full_id + @state['rate_limit'] = { 'cost' => @api.cost, 'remaining' => @api.remaining } if full + self + end + end + + # Repo, host, state and output for a whole invocation. + class CLI + def initialize(argv, env, out: $stdout) + @argv = argv + @env = env + @out = out + end + + def run + @opts = Options.new(@argv.dup, @env) + targets = resolve_targets + if @opts.jsonl? + raise Failure, '--jsonl watches exactly one repo' unless targets.size == 1 + + run_jsonl(*targets.first) + else + run_text(targets) + end + 0 + rescue Failure => e + warn "gh-watch: #{e.message}" + 2 + rescue StandardError => e + warn "gh-watch: internal error #{e.class}" + 2 + end + + private + + def resolve_targets + host = @opts.host || env('WATCHER_HOST') + repos = @opts.repos.dup + repos << env('WATCHER_REPO') if repos.empty? && env('WATCHER_REPO') + if repos.empty? + # The watcher host leaves WATCHER_REPO unset when the remote's host is + # not one it trusts; never fall back to that remote here. + raise Failure, 'WATCHER_CWD is set without WATCHER_REPO; pass --repo OWNER/NAME' if @opts.jsonl? && env('WATCHER_CWD') + + remote = git_remote(env('WATCHER_CWD') || Dir.pwd) + raise Failure, 'not a git repo with a GitHub remote; pass --repo OWNER/NAME' unless remote + + @host_from_remote = host.nil? + host ||= remote[0] + repos << "#{remote[1]}/#{remote[2]}" + end + host ||= 'github.com' + raise Failure, "bad host: #{host[0, 60]}" unless host.match?(HOST_RE) + raise Failure, "--url-host #{@opts.url_host} must equal the host #{host}" if @opts.url_host && @opts.url_host != host + + repos.uniq.map do |r| + owner, name = r.split('/', 2) + raise Failure, "bad repo: #{r[0, 60]} (want OWNER/NAME)" unless GhWatch.name_ok?(owner) && GhWatch.name_ok?(name) + + [host, owner, name] + end + end + + def env(key) + v = @env[key].to_s + v.empty? ? nil : v + end + + def git(dir, *args) + out, _err, st = Open3.capture3('git', '-c', 'core.fsmonitor=', '-C', dir, *args) + st.success? ? out.strip : nil + rescue Errno::ENOENT + nil + end + + # Prefer origin, else the first remote. Any git error (including + # dubious ownership) counts as "not a git repo". + def git_remote(dir) + return nil unless File.directory?(dir) + + url = git(dir, 'remote', 'get-url', 'origin') + unless url + first = git(dir, 'remote').to_s.split("\n").first + url = git(dir, 'remote', 'get-url', first) if first + end + url && GhWatch.parse_remote(url) + end + + # Test hook: a fake API on a loopback address. Anything else is refused, + # so a stray variable can never redirect the token. + def test_api_base + raw = env('GHWATCH_TEST_API_BASE') + return nil unless raw + + uri = begin + URI(raw) + rescue URI::InvalidURIError + nil + end + ok = uri && %w[http https].include?(uri.scheme) && LOOPBACK.include?(uri.hostname.to_s.downcase) + raise Failure, 'GHWATCH_TEST_API_BASE must be a loopback URL' unless ok + + raw + end + + def build_api(host, state) + override = test_api_base + bases = GhWatch.api_bases(host, override) + cached = state['host'] == host ? state['api_rest'] : nil + bases = { rest: cached, graphql: "#{cached}/graphql" } if !override && cached == "https://api.#{host}" && + host.end_with?('.ghe.com') + auth_hosts = if override + [URI(override).hostname.to_s.downcase] + elsif host == 'github.com' + ['api.github.com'] + else + [host, "api.#{host}"] + end + # Never send a real token to a test listener over plain http. + token = if override + env('GHWATCH_TEST_TOKEN') || TEST_TOKEN + else + GhWatch.token_for(host, from_remote: @host_from_remote == true) + end + http = Http.new(token: token, auth_hosts: auth_hosts, allow_loopback_http: !override.nil?) + Api.new(http: http, host: host, bases: bases, override: !override.nil?, fallback: cached.nil?) + end + + def read_state(dir) + path = File.join(dir, 'state.json') + return {} unless File.exist?(path) + + s = JSON.parse(File.read(path)) + s.is_a?(Hash) ? s : {} + rescue JSON::ParserError + {} # a corrupt state starts over from first sight + end + + def write_next(dir, state) + nxt = File.join(dir, 'state.json.next') + tmp = "#{nxt}.tmp-#{Process.pid}" + File.open(tmp, 'w', 0o600) do |f| + f.write(JSON.pretty_generate(state)) + f.flush + f.fsync + end + File.rename(tmp, nxt) + nxt + rescue SystemCallError => e + FileUtils.rm_f(tmp) if tmp + raise Failure, "cannot write state: #{e.class.name}" + end + + def poll(host, owner, name, dir) + state = read_state(dir) + api = build_api(host, state) + Poller.new(opts: @opts, api: api, host: host, owner: owner, name: name, state: state, + now: GhWatch.now_from_env(@env)).run + end + + def run_jsonl(host, owner, name) + dir = env('WATCHER_STATE_DIR') + raise Failure, 'WATCHER_STATE_DIR is required with --jsonl' unless dir && File.directory?(dir) + + poller = poll(host, owner, name, dir) + write_next(dir, poller.state) unless @opts.dry_run? + poller.events.each { |e| @out.puts JSON.generate(e) } + end + + def run_text(targets) + tmp = @opts.state_dir ? nil : Dir.mktmpdir('gh-watch') + root = @opts.state_dir || tmp + targets.each do |host, owner, name| + dir = targets.size > 1 ? File.join(root, owner, name) : root + FileUtils.mkdir_p(dir) + poller = poll(host, owner, name, dir) + nxt = write_next(dir, poller.state) + File.rename(nxt, File.join(dir, 'state.json')) # no host here to commit it + @out.puts "== #{host}/#{owner}/#{name}: #{poller.events.size} event(s)" + poller.events.each { |e| @out.puts text_line(e) } + rl = poller.state['rate_limit'] + @out.puts " (graphql rateLimit cost #{rl['cost']}, remaining #{rl['remaining']})" if rl + end + ensure + FileUtils.rm_rf(tmp) if tmp + end + + def text_line(e) + parts = ["[#{e['kind']}]", e['verb'], e['subject']] + parts << e['state'] if e['state'] + parts << e['sha'] if e['sha'] + parts << "by #{e['actor']}" + parts << "\"#{e['title']}\"" if e['title'] + line = parts.join(' ') + line += "\n #{e['url']}" if e['url'] + line += "\n > #{e['untrusted']}" if e['untrusted'] + line + end + end +end + +exit GhWatch::CLI.new(ARGV, ENV).run if $PROGRAM_NAME == __FILE__ diff --git a/bin/h3 b/bin/h3 index 7a74ef7..d010220 100755 --- a/bin/h3 +++ b/bin/h3 @@ -25,6 +25,8 @@ HOST = ENV.fetch("H3_HOST", "127.0.0.1") # remote H3_HOST doesn't silently expose an unauthenticated ComfyUI to the LAN. LISTEN = ENV.fetch("H3_LISTEN", "127.0.0.1") PORT = Integer(ENV.fetch("H3_PORT", "8188")) +TIMEOUT = ENV["H3_TIMEOUT"].to_s.empty? ? 30 * 60 : Integer(ENV["H3_TIMEOUT"], 10, exception: false) +abort "h3: H3_TIMEOUT must be a positive integer (seconds)" unless TIMEOUT&.positive? LOG = File.expand_path("~/Library/Logs/comfyui.log") PID_FILE = File.expand_path("~/Library/Caches/h3/comfy.pid") warn "h3: warning: ComfyUI will listen on #{LISTEN}, not just loopback" unless %w[127.0.0.1 localhost ::1].include?(LISTEN) @@ -196,7 +198,7 @@ size_desc = width.zero? ? "size of image 1" : "#{width}×#{height}" warn "h3: #{size_desc}#{", #{opts[:images].size} image(s)" if opts[:images].any?}, seed #{seed}, job #{id[0, 8]}#{" (#{queued} ahead in queue)" if queued.positive?}" started = Time.now -timeout = Integer(ENV.fetch("H3_TIMEOUT", 30 * 60)) +timeout = TIMEOUT deadline = started + timeout last_queue_check = started loop do diff --git a/bin/heavy b/bin/heavy index 49348e4..e959e23 100755 --- a/bin/heavy +++ b/bin/heavy @@ -2,17 +2,22 @@ # heavy: run a heavy command (xcodebuild, a test suite, bin/check) without swamping the Mac. # # heavy xcodebuild -project ios/Botsun.xcodeproj ... -# HEAVY_SLOTS=1 heavy bin/check --ios +# HEAVY_SLOTS=1 heavy bin/check --ios # one at a time, e.g. while you work # -# Three brakes: -# 1. Slots: at most HEAVY_SLOTS (default 1) heavy commands at once, across every shell and agent. +# Four brakes: +# 1. Slots: at most HEAVY_SLOTS (default 2) heavy commands at once, across every shell and agent. # A command waits for a free slot. Locks are lockf(1) files in ~/Library/Caches/heavy, and a -# slot frees itself when its command exits or dies. +# slot frees itself when its command exits or dies. Two slots (2026-11-20): one let five agents +# queue for hours while the CPU sat mostly idle. The iPad UI lanes stay one at a time through +# bin/check's own lock (~/Library/Caches/botsun/ipad-checks.lock). # 2. CPU gate: it doesn't start while the CPU is less than HEAVY_MIN_IDLE percent idle (default # 25, sampled over a second). Not the load average: a booting simulator and utility-clamped # builds put hundreds of threads in the run queue while the CPU is a third idle (load 900+ on # 2026-11-10 with nothing wrong), so a load gate held work back for no reason. -# 3. Priority: it runs under `taskpolicy -c utility` (efficiency cores first, below interactive +# 3. Simulators: it doesn't start while more than HEAVY_MAX_SIMS (default 4) simulators are +# booted. Each stock simulator is ~180 daemons and ~4 GB (2026-11-19: six booted pushed the +# load to 190); agents leave them running. HEAVY_MAX_SIMS=0 turns the brake off. +# 4. Priority: it runs under `taskpolicy -c utility` (efficiency cores first, below interactive # work) and `nice -n 10`. # # Exit status is the command's own. If the command itself exits 75 (EX_TEMPFAIL, the code lockf @@ -27,17 +32,49 @@ set -uo pipefail [ "${HEAVY_HELD:-}" = 1 ] && exec "$@" export HEAVY_HELD=1 -slots=${HEAVY_SLOTS:-1} +case "${HEAVY_SLOTS:-}" in "") ;; *[!0-9]*) echo "heavy: HEAVY_SLOTS must be a number: $HEAVY_SLOTS" >&2; exit 64 ;; esac +case "${HEAVY_MIN_IDLE:-}" in "") ;; *[!0-9]*) echo "heavy: HEAVY_MIN_IDLE must be a number: $HEAVY_MIN_IDLE" >&2; exit 64 ;; esac + +slots=${HEAVY_SLOTS:-2} min_idle=${HEAVY_MIN_IDLE:-25} +max_sims=${HEAVY_MAX_SIMS:-4} dir="$HOME/Library/Caches/heavy" mkdir -p "$dir" +# Booted simulators (0 when there's no simctl). +sims() { xcrun simctl list devices booted 2>/dev/null | grep -c '(Booted)'; } +sims_ok() { [ "$max_sims" -eq 0 ] || [ "$(sims)" -le "$max_sims" ]; } + # Percent idle over the last second (top's second sample; the first is since boot). idle() { top -l 2 -n 0 -s 1 2>/dev/null | awk '/CPU usage/ { v = $7 } END { sub("%", "", v); print int(v) }'; } +# A temporary override, re-read on every pass so waiting commands pick it up: the file +# ~/Library/Caches/heavy/slots holds "SLOTS UNTIL-EPOCH [MIN-IDLE]" (e.g. "3 1795420800 10"); +# past UNTIL it's ignored. HEAVY_SLOTS / HEAVY_MIN_IDLE set in the environment still win. +override_msg="" +override_slots() { + override_msg="" + local n until idle_min now + read -r n until idle_min < "$dir/slots" 2>/dev/null || [ -n "${n:-}" ] || return + case "$n$until${idle_min:-0}" in *[!0-9]*|"") return ;; esac + [ -n "$until" ] && [ "$n" -ge 1 ] || return + now=$(date +%s) + [ "$now" -lt "$until" ] || return + [ "$until" -le $((now + 7 * 24 * 3600)) ] || return + [ -z "${HEAVY_SLOTS:-}" ] && slots=$n + [ -z "${HEAVY_MIN_IDLE:-}" ] && [ -n "${idle_min:-}" ] && min_idle=$idle_min + override_msg=" (override until $(date -r "$until"))" + return 0 +} + waited=0 while :; do - if [ "$(idle)" -ge "$min_idle" ]; then + slots=${HEAVY_SLOTS:-2} + min_idle=${HEAVY_MIN_IDLE:-25} + override_slots + [ "$slots" -ge 1 ] || slots=1 + cur_idle=$(idle) + if sims_ok && [ "$cur_idle" -ge "$min_idle" ]; then for n in $(seq 1 "$slots"); do lockf -s -t 0 "$dir/slot-$n" taskpolicy -c utility nice -n 10 "$@" status=$? @@ -45,7 +82,11 @@ while :; do done fi if [ $((waited % 60)) -eq 0 ]; then - echo "heavy: waiting for a slot (CPU $(idle)% idle, needs $min_idle%; $slots slot(s)): $1" >&2 + if sims_ok; then + echo "heavy: waiting for a slot (CPU $cur_idle% idle, needs $min_idle%; $slots slot(s)$override_msg): $1" >&2 + else + echo "heavy: waiting: $(sims) simulators booted, max $max_sims (xcrun simctl list devices booted): $1" >&2 + fi fi sleep 10 waited=$((waited + 10)) diff --git a/test/fixtures/gh-watch-ids.txt b/test/fixtures/gh-watch-ids.txt new file mode 100644 index 0000000..353ead4 --- /dev/null +++ b/test/fixtures/gh-watch-ids.txt @@ -0,0 +1,10 @@ +# Synthetic ids for acme/widgets, in the formats the watcher host dedupes on. +# A change here means seen.jsonl stops recognising events it already showed. +gh:opened:5 +gh:review:234442896 +gh:comment:1234567890 +gh:inline:987654321 +gh:push:5:bbbbbbbbbbbb +gh:ci:5:bbbbbbbbbbbb:failure +gh:merged:3:20261119115807 +gh:closed:4:20261119115700 diff --git a/test/gh-watch_test.rb b/test/gh-watch_test.rb new file mode 100644 index 0000000..70dc7e4 --- /dev/null +++ b/test/gh-watch_test.rb @@ -0,0 +1,941 @@ +# frozen_string_literal: true + +# Tests for bin/gh-watch. Run: ruby test/gh-watch_test.rb +# +# The script runs as a subprocess against a TCPServer fake of the GitHub REST +# and GraphQL APIs (GHWATCH_TEST_API_BASE, loopback only), with a fake `gh` on +# PATH for the token and GHWATCH_TEST_NOW for the clock. + +require 'minitest/autorun' +require 'json' +require 'open3' +require 'socket' +require 'tmpdir' +require 'fileutils' +require 'time' + +SCRIPT = File.expand_path('../bin/gh-watch', __dir__) +load SCRIPT + +NOW = Time.utc(2026, 11, 19, 12, 0, 0) +TOKEN = 'test-token-abc123' # what the fake `gh auth token` prints +FAKE_TOKEN = 'ghwatch-test-token' # what gh-watch sends to a test API base +SHA_A = 'a' * 40 +SHA_B = 'b' * 40 + +def ago(seconds) + (NOW - seconds).utc.iso8601 +end + +# A tiny HTTP/1.1 server: one request per connection, routed by a block. +class FakeGitHub + Request = Struct.new(:http_method, :target, :headers, :body, keyword_init: true) do + def path + target.split('?').first + end + + def json + JSON.parse(body) + end + end + + attr_reader :requests, :port + + def initialize(&router) + @router = router + @requests = [] + @server = TCPServer.new('127.0.0.1', 0) + @port = @server.addr[1] + @thread = Thread.new { loop { handle(@server.accept) } } + end + + def base + "http://127.0.0.1:#{@port}" + end + + def stop + @thread.kill + @server.close + end + + def graphql_requests + @requests.select { |r| r.path == '/graphql' } + end + + def main_queries + graphql_requests.select { |r| r.json['query'].include?('closed: pullRequests') } + end + + def detail_queries + graphql_requests.select { |r| r.json['query'].include?('p0: pullRequest(') } + end + + private + + def handle(sock) + line = sock.gets or return + method, target, = line.split + headers = {} + while (h = sock.gets) && h != "\r\n" + k, v = h.split(':', 2) + headers[k.strip.downcase] = v.strip + end + body = headers['content-length'] ? sock.read(headers['content-length'].to_i) : '' + req = Request.new(http_method: method, target: target, headers: headers, body: body) + @requests << req + status, extra, payload = @router.call(req) + payload = payload.is_a?(String) ? payload : JSON.generate(payload) + head = ["HTTP/1.1 #{status} X", 'Content-Type: application/json', "Content-Length: #{payload.bytesize}", + 'Connection: close'] + (extra || {}).each { |k, v| head << "#{k}: #{v}" } + sock.write("#{head.join("\r\n")}\r\n\r\n#{payload}") + rescue StandardError => e + warn "fake server: #{e.class}: #{e.message}" + ensure + sock&.close + end +end + +module Fixtures + module_function + + def author(login, type = 'User') + login && { '__typename' => type, 'login' => login } + end + + def conn(nodes, more: false) + { 'pageInfo' => { 'hasPreviousPage' => more, 'startCursor' => more ? 'CUR' : nil }, 'nodes' => nodes } + end + + def pr(number:, author: 'alice', head: SHA_A, rollup: nil, created: ago(86_400), updated: ago(30), + head_author: 'alice', committed: ago(86_400), comments: [], reviews: [], threads: [], base: 'main', + author_type: 'User', comments_more: false) + { + 'number' => number, 'title' => "PR #{number}\ttitle", 'createdAt' => created, 'updatedAt' => updated, + 'baseRefName' => base, 'headRefOid' => head, 'author' => author(author, author_type), + 'commits' => { 'nodes' => [{ 'commit' => { + 'oid' => head, 'committedDate' => committed, + 'author' => { 'user' => head_author && { 'login' => head_author } }, + 'statusCheckRollup' => rollup && { 'state' => rollup } + } }] }, + 'reviews' => conn(reviews), 'comments' => conn(comments, more: comments_more), 'reviewThreads' => conn(threads) + } + end + + def comment(id, who, at, body = 'hello', type: 'User') + { 'databaseId' => id.to_i, 'fullDatabaseId' => id.to_s, 'author' => author(who, type), 'createdAt' => at, + 'body' => body } + end + + def review(id, who, state, at, body = '') + { 'databaseId' => id.to_i, 'fullDatabaseId' => id.to_s, 'state' => state, 'author' => author(who), + 'submittedAt' => at, 'body' => body } + end + + def thread(*comments) + { 'id' => 'T_1', 'comments' => conn(comments) } + end + + def inline(id, who, at, path, body, review: nil) + comment(id, who, at, body).merge('path' => path, 'pullRequestReview' => review && { 'databaseId' => review }) + end + + def closed(number:, state:, closed_at:, by: 'bob', updated: closed_at) + { 'number' => number, 'title' => "Closed #{number}", 'state' => state, 'closedAt' => closed_at, + 'mergedAt' => state == 'MERGED' ? closed_at : nil, 'updatedAt' => updated, 'baseRefName' => 'main', + 'author' => author('alice'), 'mergedBy' => state == 'MERGED' ? author(by) : nil, + 'timelineItems' => { 'nodes' => state == 'MERGED' ? [] : [{ 'actor' => author(by) }] } } + end + + def graphql(open: [], closed: []) + { 'data' => { + 'repository' => { + 'open' => { 'pageInfo' => { 'hasNextPage' => false, 'endCursor' => nil }, 'nodes' => open }, + 'closed' => { 'pageInfo' => { 'hasNextPage' => false, 'endCursor' => nil }, 'nodes' => closed } + }, + 'rateLimit' => { 'cost' => 3, 'remaining' => 4997, 'limit' => 5000, 'resetAt' => ago(-3600) } + } } + end +end + +class GhWatchTest < Minitest::Test + include Fixtures + + def setup + @tmp = Dir.mktmpdir('gh-watch-test') + @state_dir = File.join(@tmp, 'state') + FileUtils.mkdir_p(@state_dir) + @bin = File.join(@tmp, 'bin') + FileUtils.mkdir_p(@bin) + @gh_log = File.join(@tmp, 'gh.log') + File.write(File.join(@bin, 'gh'), <<~SH) + #!/bin/sh + echo "$* ent=${GH_ENTERPRISE_TOKEN:-}" >> #{@gh_log} + if [ "$1 $2 $3" = "auth status --hostname" ]; then + case "$4" in github.com|ghe.example.com) exit 0 ;; esac + fi + if [ "$1 $2 $3" = "auth token --hostname" ]; then + if [ "$4" = "github.com" ]; then echo #{TOKEN}; exit 0; fi + if [ "$4" = "ghe.example.com" ] && [ -n "${GH_ENTERPRISE_TOKEN:-}" ]; then echo "$GH_ENTERPRISE_TOKEN"; exit 0; fi + fi + echo "not logged in" >&2; exit 1 + SH + File.chmod(0o755, File.join(@bin, 'gh')) + @etag = 'W/"e1"' + @gql = graphql + @routes = {} + end + + def teardown + @server&.stop + FileUtils.rm_rf(@tmp) + end + + def server + @server ||= FakeGitHub.new do |req| + custom = @routes.find { |pattern, _| req.target.match?(pattern) || "#{req.http_method} #{req.path}" == pattern } + if custom + custom[1].call(req) + elsif req.path == '/repos/acme/widgets/pulls' + req.headers['if-none-match'] == @etag ? [304, {}, ''] : [200, { 'ETag' => @etag }, [{ 'number' => 1 }]] + elsif req.path == '/repos/acme/widgets/issues' && req.target.match?(/per_page=1(&|\z)/) + [200, { 'ETag' => 'W/"i1"' }, []] + elsif req.path == '/graphql' + [200, {}, req.json['query'].include?('p0: pullRequest(') ? details_for(req) : @gql] + elsif req.path == '/user' + [200, {}, { 'login' => 'octocat' }] + else + [404, {}, { 'message' => 'Not Found' }] + end + end + end + + # The nested reviews/comments query, answered from the open PRs in @gql. + def details_for(req) + open = @gql.dig('data', 'repository', 'open', 'nodes') + repo = {} + req.json['variables'].each do |k, v| + next unless (m = k.match(/\An(\d+)\z/)) + + node = open.find { |p| p['number'] == v } + repo["p#{m[1]}"] = node&.slice('number', 'reviews', 'comments', 'reviewThreads') + end + { 'data' => { 'repository' => repo, 'rateLimit' => { 'cost' => 1, 'remaining' => 4996 } } } + end + + def write_state(state) + File.write(File.join(@state_dir, 'state.json'), JSON.generate(state)) + end + + def base_state(extra = {}) + { 'version' => 1, 'host' => 'github.com', 'repo' => 'acme/widgets', 'since' => ago(300), + 'last_full' => ago(120), 'etag' => 'W/"old"', 'me' => 'octocat', 'prs' => {} }.merge(extra) + end + + def run_watch(*args, env: {}) + full_env = { + 'PATH' => "#{@bin}:#{ENV.fetch('PATH')}", 'GHWATCH_TEST_API_BASE' => server.base, 'GHWATCH_TEST_NOW' => NOW.iso8601, + 'WATCHER_STATE_DIR' => @state_dir, 'WATCHER_REPO' => 'acme/widgets', 'WATCHER_HOST' => 'github.com', + 'WATCHER_ME' => 'octocat', 'WATCHER_CWD' => nil, 'GH_TOKEN' => nil, 'GITHUB_TOKEN' => nil, + 'GH_ENTERPRISE_TOKEN' => nil, 'GITHUB_ENTERPRISE_TOKEN' => nil, 'GHWATCH_TEST_TOKEN' => nil + }.merge(env) + args = ['--jsonl'] if args.empty? + out, err, st = Open3.capture3(full_env, RbConfig.ruby, SCRIPT, *args) + @err = err + @status = st.exitstatus + @out = out + args.include?('--jsonl') ? out.lines.map { |l| JSON.parse(l) } : [] + end + + def next_state + JSON.parse(File.read(File.join(@state_dir, 'state.json.next'))) + end + + def by_id(events) + events.to_h { |e| [e['id'], e] } + end + + # ---- first sight, change check, refresh ------------------------------ + + def test_first_sight_records_heads_and_emits_nothing_old + @gql = graphql(open: [pr(number: 5, rollup: 'FAILURE', author: 'octocat'), + pr(number: 6, created: ago(600), author: 'bob')]) + events = run_watch + assert_equal 0, @status, @err + assert_equal(['gh:opened:6'], events.map { |e| e['id'] }) + assert_equal 'info', events.first['kind'] + st = next_state + assert_equal SHA_A, st['prs']['5']['head'] + assert_equal 'failure', st['prs']['5']['ci'] + assert_equal NOW.iso8601, st['since'] + assert_equal 'octocat', st['me'] + assert_equal "Bearer #{FAKE_TOKEN}", server.requests.first.headers['authorization'] + end + + def test_304_skips_graphql_and_holds_since + write_state(base_state('etag' => @etag)) + assert_empty run_watch + assert_equal 0, @status, @err + assert_empty server.graphql_requests + assert_equal ago(300), next_state['since'], 'no query read anything' + assert_equal ago(120), next_state['last_full'] + end + + def test_200_runs_graphql + write_state(base_state) + run_watch + assert_equal 1, server.graphql_requests.size + assert_equal @etag, next_state['etag'] + assert_equal NOW.iso8601, next_state['since'] + assert_equal ago(120), next_state['last_full'], 'last_full marks the five-minute refresh only' + end + + def test_pending_ci_bypasses_304 + write_state(base_state('etag' => @etag, + 'prs' => { '5' => { 'head' => SHA_A, 'ci' => 'pending', 'head_at' => ago(200) } })) + @gql = graphql(open: [pr(number: 5, rollup: 'SUCCESS')]) + events = run_watch + assert_equal 1, server.main_queries.size + assert_equal(["gh:ci:5:#{SHA_A[0, 12]}:success"], events.map { |e| e['id'] }) + end + + def test_five_minute_full_refresh + write_state(base_state('etag' => @etag, 'last_full' => ago(301))) + run_watch + assert_equal 1, server.graphql_requests.size + end + + def test_null_rollup_on_young_head_is_pending + write_state(base_state('prs' => { '5' => { 'head' => SHA_A, 'ci' => 'none', 'head_at' => ago(9000) } })) + @gql = graphql(open: [pr(number: 5, head: SHA_B, head_author: 'alice')]) + run_watch + assert_equal 'pending', next_state['prs']['5']['ci'] + @gql = graphql(open: [pr(number: 7, committed: ago(3600))]) + write_state(base_state) + run_watch + assert_equal 'none', next_state['prs']['7']['ci'] + end + + def test_host_or_repo_change_starts_over + write_state(base_state('repo' => 'acme/other', 'etag' => @etag, + 'prs' => { '5' => { 'head' => SHA_B, 'ci' => 'success' } })) + @gql = graphql(open: [pr(number: 5)]) + assert_empty run_watch # first sight again: no PUSH for the changed head + assert_equal 1, server.main_queries.size + assert_equal 'acme/widgets', next_state['repo'] + end + + # ---- verbs and act rules --------------------------------------------- + + def test_push_ci_and_own_push + prs = { '5' => { 'head' => SHA_A, 'ci' => 'pending', 'head_at' => ago(900) }, + '6' => { 'head' => SHA_A, 'ci' => 'none', 'head_at' => ago(900) }, + '7' => { 'head' => SHA_A, 'ci' => 'none', 'head_at' => ago(900) } } + write_state(base_state('prs' => prs)) + @gql = graphql(open: [ + pr(number: 5, author: 'octocat', rollup: 'ERROR'), + pr(number: 6, head: SHA_B, head_author: 'octocat', rollup: 'SUCCESS'), + pr(number: 7, head: SHA_B, head_author: nil, rollup: 'PENDING') + ]) + ev = by_id(run_watch) + sha = SHA_B[0, 12] + ci5 = ev.fetch("gh:ci:5:#{SHA_A[0, 12]}:failure") + assert_equal %w[act CI failure octocat], ci5.values_at('kind', 'verb', 'state', 'actor'), + 'CI on my PR wakes me even though I am its actor' + assert_equal 'https://github.com/acme/widgets/pull/5/checks', ci5['url'] + refute ev.key?("gh:push:6:#{sha}"), 'own push is skipped' + assert_equal 'info', ev.fetch("gh:ci:6:#{sha}:success")['kind'] + push7 = ev.fetch("gh:push:7:#{sha}") + assert_equal %w[unknown PUSH info], push7.values_at('actor', 'verb', 'kind') + assert_equal "https://github.com/acme/widgets/commit/#{SHA_B}", push7['url'] + assert_equal 'PR 7 title', push7['title'] + refute ev.keys.any? { |k| k.start_with?('gh:ci:7') }, 'pending CI is suppressed' + assert_equal 'pending', next_state['prs']['7']['ci'] + end + + def test_ci_unchanged_is_quiet + write_state(base_state('prs' => { '5' => { 'head' => SHA_A, 'ci' => 'failure', 'head_at' => ago(900) } })) + @gql = graphql(open: [pr(number: 5, rollup: 'FAILURE', author: 'octocat')]) + assert_empty run_watch + end + + def test_reviews_and_comments + write_state(base_state('prs' => { '5' => { 'head' => SHA_A, 'ci' => 'none' }, + '6' => { 'head' => SHA_A, 'ci' => 'none' } })) + mine = pr(number: 5, author: 'octocat', + reviews: [review(101, 'alice', 'CHANGES_REQUESTED', ago(60), 'please fix'), + review(102, 'bob', 'COMMENTED', ago(50)), + review(103, 'carol', 'APPROVED', ago(40), 'lgtm'), + review(104, 'octocat', 'COMMENTED', ago(40)), + review(105, 'dave', 'PENDING', ago(40)), + review(99, 'erin', 'APPROVED', ago(4000))], + comments: [comment(201, 'alice', ago(30), "multi\n\nline body"), + comment(202, 'bob', ago(20), nil), + comment(203, 'dependabot', ago(20), 'bump', type: 'Bot'), + comment(204, nil, ago(20), 'ghost')], + threads: [thread(inline(301, 'alice', ago(10), 'lib/a.rb', "nit:\tspace"), + inline(302, 'bob', ago(9), 'lib/b.rb', ''))]) + theirs = pr(number: 6, author: 'bob', + reviews: [review(111, 'alice', 'CHANGES_REQUESTED', ago(60)), review(112, 'alice', 'COMMENTED', ago(55))], + comments: [comment(211, 'alice', ago(30))]) + @gql = graphql(open: [mine, theirs]) + ev = by_id(run_watch) + assert_equal 0, @status, @err + + assert_equal %w[act REVIEW CHANGES_REQUESTED alice please\ fix], ev['gh:review:101'].values_at('kind', 'verb', 'state', 'actor', 'untrusted') + assert_equal 'https://github.com/acme/widgets/pull/5#pullrequestreview-101', ev['gh:review:101']['url'] + assert_equal 'act', ev['gh:review:102']['kind'] + refute ev['gh:review:102'].key?('untrusted'), 'empty body omits untrusted' + assert_equal 'info', ev['gh:review:103']['kind'] + assert_equal 'info', ev['gh:review:104']['kind'], 'my own review' + refute ev.key?('gh:review:105'), 'PENDING reviews are skipped' + refute ev.key?('gh:review:99'), 'older than since - overlap' + + c = ev['gh:comment:201'] + assert_equal %w[act COMMENT conversation multi\ line\ body], c.values_at('kind', 'verb', 'state', 'untrusted') + assert_equal 'https://github.com/acme/widgets/pull/5#issuecomment-201', c['url'] + refute ev['gh:comment:202'].key?('untrusted'), 'null body omits untrusted' + assert_equal %w[dependabot[bot] info], ev['gh:comment:203'].values_at('actor', 'kind') + assert_equal %w[unknown info], ev['gh:comment:204'].values_at('actor', 'kind') + + i = ev['gh:inline:301'] + assert_equal ['act', 'inline', 'lib/a.rb: nit: space'], i.values_at('kind', 'state', 'untrusted') + assert_equal 'https://github.com/acme/widgets/pull/5#discussion_r301', i['url'] + refute ev['gh:inline:302'].key?('untrusted') + + assert_equal 'act', ev['gh:review:111']['kind'], 'changes requested on any PR' + assert_equal 'info', ev['gh:review:112']['kind'], 'COMMENTED on a PR that is not mine' + assert_equal 'info', ev['gh:comment:211']['kind'] + end + + def test_act_on_none_and_no_wake_override + write_state(base_state('prs' => { '5' => { 'head' => SHA_A, 'ci' => 'none' } })) + @gql = graphql(open: [pr(number: 5, author: 'octocat', + reviews: [review(101, 'alice', 'CHANGES_REQUESTED', ago(60))], + comments: [comment(203, 'dependabot', ago(20), 'bump', type: 'Bot')])]) + assert_equal(%w[info info], run_watch('--jsonl', '--act-on', 'none').map { |e| e['kind'] }) + ev = by_id(run_watch('--jsonl', '--no-wake-actors', 'alice')) + assert_equal 0, @status, @err + assert_equal 'info', ev['gh:review:101']['kind'] + assert_equal 'act', ev['gh:comment:203']['kind'], 'dependabot wakes once removed from the list' + end + + def test_team_pr_from_wake_authors_and_wake_team + write_state(base_state) + @gql = graphql(open: [pr(number: 8, author: 'alice', created: ago(100)), + pr(number: 9, author: 'zed', created: ago(100)), + pr(number: 10, author: 'dependabot', author_type: 'Bot', created: ago(100))]) + ev = by_id(run_watch('--jsonl', '--wake-authors', 'Alice')) + assert_equal(%w[act info info], %w[8 9 10].map { |n| ev["gh:opened:#{n}"]['kind'] }) + assert_equal 'dependabot[bot]', ev['gh:opened:10']['actor'] + + @routes['GET /orgs/acme/teams/core/members'] = ->(_) { [200, {}, [{ 'login' => 'zed' }]] } + write_state(base_state) + ev = by_id(run_watch('--jsonl', '--wake-team', 'acme/core')) + assert_equal 'act', ev['gh:opened:9']['kind'] + team = next_state['team'] + assert_equal ['zed'], team['members'] + # Cached for 24 h: no second members call. + write_state(base_state('team' => team)) + before = server.requests.count { |r| r.path.start_with?('/orgs/') } + run_watch('--jsonl', '--wake-team', 'acme/core') + assert_equal(before, server.requests.count { |r| r.path.start_with?('/orgs/') }) + end + + def test_merged_and_closed + write_state(base_state) + @gql = graphql(closed: [closed(number: 3, state: 'MERGED', closed_at: '2026-11-19T11:58:07Z'), + closed(number: 4, state: 'CLOSED', closed_at: '2026-11-19T11:57:00Z', by: 'carol'), + closed(number: 2, state: 'CLOSED', closed_at: ago(7200))]) + ev = by_id(run_watch) + m = ev.fetch('gh:merged:3:20261119115807') + assert_equal %w[MERGED merged bob], m.values_at('verb', 'state', 'actor') + c = ev.fetch('gh:closed:4:20261119115700') + assert_equal %w[CLOSED closed carol], c.values_at('verb', 'state', 'actor') + assert_equal 2, ev.size + end + + def test_paging_back_a_truncated_connection + write_state(base_state('prs' => { '5' => { 'head' => SHA_A, 'ci' => 'none' } })) + @gql = graphql(open: [pr(number: 5, comments: [comment(202, 'bob', ago(20))], comments_more: true)]) + @routes[%r{\A/graphql}] = lambda do |req| + if req.json['query'].include?('pullRequest(number: $number)') + assert_equal 'CUR', req.json['variables']['before'] + [200, {}, { 'data' => { 'repository' => { 'pullRequest' => { 'comments' => conn([comment(201, 'alice', ago(40))]) } }, + 'rateLimit' => { 'cost' => 1, 'remaining' => 1 } } }] + elsif req.json['query'].include?('p0: pullRequest(') + [200, {}, details_for(req)] + else + [200, {}, @gql] + end + end + assert_equal(%w[gh:comment:201 gh:comment:202], run_watch.map { |e| e['id'] }) + end + + def test_event_cap_holds_since_at_first_unemitted + write_state(base_state) + @gql = graphql(open: (1..205).map { |n| pr(number: n, created: ago(250 - n)) }) + events = run_watch + assert_equal 200, events.size + assert_equal 'gh:opened:200', events.last['id'] + assert_equal ago(250 - 201), next_state['since'] + end + + def test_base_branch_filter + write_state(base_state) + @gql = graphql(open: [pr(number: 8, created: ago(10), base: 'main'), pr(number: 9, created: ago(10), base: 'dev')]) + assert_equal(['gh:opened:9'], run_watch('--jsonl', '--base', 'dev').map { |e| e['id'] }) + end + + # ---- issues ----------------------------------------------------------- + + def test_issue_opened_vs_old_issue_new_comment + write_state(base_state('etag' => @etag)) + @routes[/issues\?state=all&sort=updated&direction=asc/] = lambda do |_| + [200, {}, [ + { 'number' => 40, 'title' => 'New bug', 'created_at' => ago(60), 'state' => 'open', 'user' => { 'login' => 'alice' } }, + { 'number' => 41, 'title' => 'Old bug', 'created_at' => ago(90_000), 'state' => 'open', 'user' => { 'login' => 'bob' } }, + { 'number' => 42, 'title' => 'A PR', 'created_at' => ago(60), 'state' => 'open', 'pull_request' => {}, + 'user' => { 'login' => 'bob' } }, + { 'number' => 43, 'title' => 'Done', 'created_at' => ago(90_000), 'state' => 'closed', 'closed_at' => '2026-11-19T11:59:00Z', + 'user' => { 'login' => 'bob' } } + ]] + end + @routes[%r{issues/comments\?}] = lambda do |_| + [200, {}, [{ 'id' => 501, 'created_at' => ago(30), 'body' => 'still broken', 'user' => { 'login' => 'erin' }, + 'html_url' => 'https://github.com/acme/widgets/issues/41#issuecomment-501' }, + { 'id' => 502, 'created_at' => ago(9000), 'body' => 'edited old', 'user' => { 'login' => 'erin' }, + 'html_url' => 'https://github.com/acme/widgets/issues/41#issuecomment-502' }]] + end + ev = by_id(run_watch('--jsonl', '--issues', 'on')) + assert_equal %w[gh:closed:43:20261119115900 gh:comment:501 gh:opened:40], ev.keys.sort + assert_equal %w[issue:40 OPENED open], ev['gh:opened:40'].values_at('subject', 'verb', 'state') + assert_equal 'https://github.com/acme/widgets/issues/40', ev['gh:opened:40']['url'] + assert_equal %w[issue:41 conversation still\ broken], ev['gh:comment:501'].values_at('subject', 'state', 'untrusted') + assert_equal 'unknown', ev['gh:closed:43:20261119115900']['actor'], 'issue lists have no closed_by' + assert_equal 'W/"i1"', next_state['issues_etag'] + assert_empty server.graphql_requests, 'PR etag 304 and nothing pending' + end + + # ---- errors ------------------------------------------------------------- + + def test_graphql_http_error_exits_2_without_next + write_state(base_state) + @routes['POST /graphql'] = ->(_) { [502, {}, { 'message' => 'Bad Gateway' }] } + assert_empty run_watch + assert_equal 2, @status + assert_equal "gh-watch: POST /graphql -> 502 Bad Gateway\n", @err + refute File.exist?(File.join(@state_dir, 'state.json.next')) + assert_empty Dir.children(@state_dir) - ['state.json'] + end + + def test_rest_403_and_graphql_errors + @routes['GET /repos/acme/widgets/pulls'] = ->(_) { [403, {}, { 'message' => 'API rate limit exceeded' }] } + run_watch + assert_equal 2, @status + assert_equal "gh-watch: GET /repos/acme/widgets/pulls -> 403 API rate limit exceeded\n", @err + refute_includes @err, TOKEN + + @routes.clear + @routes['POST /graphql'] = ->(_) { [200, {}, { 'errors' => [{ 'message' => 'Something broke' }] }] } + run_watch + assert_equal 2, @status + assert_match %r{\Agh-watch: POST /graphql -> 200 graphql: Something broke\n\z}, @err + refute File.exist?(File.join(@state_dir, 'state.json.next')) + end + + def test_dry_run_writes_nothing_and_exits_0 + @gql = graphql(open: [pr(number: 6, created: ago(10))]) + assert_equal 1, run_watch(env: { 'WATCHER_DRY_RUN' => '1' }).size + assert_equal 0, @status + refute File.exist?(File.join(@state_dir, 'state.json.next')) + end + + def test_argument_errors + run_watch('--jsonl', '--repo', 'acme/widgets', '--repo', 'acme/other') + assert_equal [2, "gh-watch: --jsonl watches exactly one repo\n"], [@status, @err] + run_watch('--jsonl', '--url-host', 'example.com') + assert_equal 2, @status + run_watch('--jsonl', '--repo', 'acme/../x;rm') + assert_equal 2, @status + run_watch(env: { 'WATCHER_STATE_DIR' => nil }) + assert_equal [2, "gh-watch: WATCHER_STATE_DIR is required with --jsonl\n"], [@status, @err] + token_for('example.com') + assert_match(/no gh auth for example\.com/, @err) + end + + def test_dot_names_are_rejected + ['../..', 'acme/..', './widgets', 'acme/...'].each do |repo| + run_watch('--jsonl', '--repo', repo) + assert_equal 2, @status, repo + assert_match(/bad repo/, @err, repo) + end + run_watch('--once', '--text', '--state-dir', @state_dir, '--repo', 'acme/widgets', '--repo', '../..') + assert_equal 2, @status + assert_empty server.requests, 'refused before any directory or request' + assert_nil GhWatch.parse_remote('git@github.com:../widgets.git') + assert_nil GhWatch.parse_remote('https://github.com/acme/..') + assert_equal ['github.com', 'acme', 'w.x'], GhWatch.parse_remote('git@github.com:acme/w.x.git') + run_watch('--jsonl', '--wake-team', 'acme/..') + assert_equal [2, "gh-watch: --wake-team must be ORG/SLUG\n"], [@status, @err] + end + + def test_text_mode_once + @gql = graphql(open: [pr(number: 6, created: ago(10))]) + run_watch('--once', '--text', '--repo', 'acme/widgets') + assert_equal 0, @status, @err + assert_includes @out, '[info] OPENED pr:6 open by alice "PR 6 title"' + assert_includes @out, 'rateLimit cost 4' # heads 3 + details 1 + end + + # ---- repo resolution ---------------------------------------------------- + + def test_parse_remote_forms + want = ['github.com', 'acme', 'widgets'] + assert_equal want, GhWatch.parse_remote('https://github.com/acme/widgets.git') + assert_equal want, GhWatch.parse_remote('https://github.com/acme/widgets') + assert_equal want, GhWatch.parse_remote('git@github.com:acme/widgets.git') + assert_equal want, GhWatch.parse_remote('ssh://git@github.com/acme/widgets.git') + assert_equal ['example.ghe.com', 'acme', 'widgets.js'], GhWatch.parse_remote('git@example.ghe.com:acme/widgets.js') + assert_nil GhWatch.parse_remote('/local/path/repo') + assert_nil GhWatch.parse_remote('https://github.com/acme/widgets/extra') + end + + def test_api_bases + assert_equal 'https://api.github.com', GhWatch.api_bases('github.com')[:rest] + assert_equal({ rest: 'https://example.ghe.com/api/v3', graphql: 'https://example.ghe.com/api/graphql' }, + GhWatch.api_bases('example.ghe.com')) + end + + def git_repo(remote_url, remote_name = 'origin') + dir = File.join(@tmp, "repo-#{remote_name}") + system('git', 'init', '-q', dir, exception: true) + system('git', '-C', dir, 'remote', 'add', remote_name, remote_url, exception: true) + dir + end + + def test_resolution_from_ssh_and_https_remotes + @gql = graphql + [['git@github.com:acme/widgets.git', 'origin'], ['https://github.com/acme/widgets.git', 'upstream']].each do |url, name| + dir = git_repo(url, name) + run_watch('--once', '--text', '--state-dir', @state_dir, + env: { 'WATCHER_REPO' => nil, 'WATCHER_HOST' => nil, 'WATCHER_CWD' => dir }) + assert_equal 0, @status, @err + st = JSON.parse(File.read(File.join(@state_dir, 'state.json'))) + assert_equal 'acme/widgets', st['repo'] + assert_equal 'github.com', st['host'] + end + end + + def test_not_a_git_repo + run_watch('--once', '--text', env: { 'WATCHER_REPO' => nil, 'WATCHER_CWD' => @tmp }) + assert_equal 2, @status + assert_match(/not a git repo/, @err) + end + + def test_jsonl_with_cwd_but_no_repo_refuses_the_remote + dir = git_repo('git@github.com:acme/widgets.git') + run_watch(env: { 'WATCHER_REPO' => nil, 'WATCHER_HOST' => nil, 'WATCHER_CWD' => dir }) + assert_equal [2, "gh-watch: WATCHER_CWD is set without WATCHER_REPO; pass --repo OWNER/NAME\n"], [@status, @err] + assert_empty server.requests + end + + # ---- token safety --------------------------------------------------------- + + def test_http_refuses_unknown_host_and_plain_http + http = GhWatch::Http.new(token: 't', auth_hosts: ['api.github.com']) + e = assert_raises(GhWatch::ApiError) { http.request('GET', 'https://evil.example.com/x') } + assert_match(/refusing to send auth/, e.message) + e = assert_raises(GhWatch::ApiError) { http.request('GET', 'http://api.github.com/x') } + assert_match(/non-https/, e.message) + end + + def test_redirect_is_not_followed + @routes['GET /repos/acme/widgets/pulls'] = ->(_) { [302, { 'Location' => 'https://evil.example.com/' }, ''] } + run_watch + assert_equal 2, @status + assert_equal 1, server.requests.size + end + + # GhWatch.token_for in a subprocess with the fake gh on PATH and only the + # token variables given (the test API base path never calls it). + def token_for(host, from_remote: false, env: {}) + full_env = { 'PATH' => "#{@bin}:#{ENV.fetch('PATH')}", 'GH_TOKEN' => nil, 'GITHUB_TOKEN' => nil, + 'GH_ENTERPRISE_TOKEN' => nil, 'GITHUB_ENTERPRISE_TOKEN' => nil }.merge(env) + code = 'load ARGV[0]; begin; print GhWatch.token_for(ARGV[1], from_remote: ARGV[2] == "1"); ' \ + 'rescue GhWatch::Failure => e; warn e.message; exit 2; end' + out, @err, st = Open3.capture3(full_env, RbConfig.ruby, '-e', code, SCRIPT, host, from_remote ? '1' : '0') + @status = st.exitstatus + out + end + + def gh_log_lines + File.exist?(@gh_log) ? File.readlines(@gh_log, chomp: true) : [] + end + + def test_remote_host_needs_gh_auth_status_and_gets_no_env_token + env = { 'GH_ENTERPRISE_TOKEN' => 'env-secret' } + token_for('evil.example.com', from_remote: true, env: env) + assert_equal [2, "remote host evil.example.com is not logged in to gh; pass --host and --repo\n"], [@status, @err] + assert_equal ['auth status --hostname evil.example.com ent='], gh_log_lines + + # A logged-in remote host still never sees the env token. + File.write(@gh_log, '') + token_for('ghe.example.com', from_remote: true, env: env) + assert_equal 2, @status + assert_match(/no gh auth for ghe\.example\.com/, @err) + assert(gh_log_lines.all? { |l| l.end_with?('ent=') }) + + # A host the user configured keeps its enterprise token. + File.write(@gh_log, '') + assert_equal 'env-secret', token_for('ghe.example.com', env: env) + assert_equal ['auth token --hostname ghe.example.com ent=env-secret'], gh_log_lines + end + + def test_test_api_base_never_gets_the_gh_token + write_state(base_state) + run_watch + assert_equal 0, @status, @err + refute File.exist?(@gh_log), 'gh is never asked for a token' + assert_equal(["Bearer #{FAKE_TOKEN}"], server.requests.map { |r| r.headers['authorization'] }.uniq) + + write_state(base_state) + run_watch(env: { 'GHWATCH_TEST_TOKEN' => 'chosen-by-test' }) + assert_equal 0, @status, @err + assert_equal 'Bearer chosen-by-test', server.requests.last.headers['authorization'] + refute(server.requests.any? { |r| r.headers['authorization'].to_s.include?(TOKEN) }) + end + + def test_test_api_base_must_be_loopback + %w[https://evil.example.com http://10.0.0.1:8080 not-a-url].each do |base| + run_watch(env: { 'GHWATCH_TEST_API_BASE' => base }) + assert_equal [2, "gh-watch: GHWATCH_TEST_API_BASE must be a loopback URL\n"], [@status, @err], base + end + refute File.exist?(@gh_log), 'refused before any token is fetched' + end + + def test_ghe_fallback_only_on_first_request_without_cache + fake = Class.new do + attr_reader :urls + + def initialize + @urls = [] + end + + def request(_method, url, **) + @urls << url + url.start_with?('https://api.example.ghe.com/') ? [200, {}, '{"login":"x"}'] : [404, {}, '{}'] + end + end + bases = GhWatch.api_bases('example.ghe.com') + http = fake.new + api = GhWatch::Api.new(http: http, host: 'example.ghe.com', bases: bases, fallback: true) + api.get('/repos/a/b/pulls') + assert_equal 'https://api.example.ghe.com', api.bases[:rest] + assert_equal %w[https://example.ghe.com/api/v3/repos/a/b/pulls https://api.example.ghe.com/repos/a/b/pulls], http.urls + + api = GhWatch::Api.new(http: fake.new, host: 'example.ghe.com', bases: bases, fallback: false) + assert_raises(GhWatch::ApiError) { api.get('/repos/a/b/pulls') } + + # A later 404 (a team without read:org, say) never rewrites the bases. + flaky = fake.new + def flaky.request(_method, url, **) + @urls << url + @urls.size == 1 ? [200, {}, '{}'] : [404, {}, '{}'] + end + api = GhWatch::Api.new(http: flaky, host: 'example.ghe.com', bases: bases, fallback: true) + api.get('/repos/a/b/pulls') + assert_raises(GhWatch::ApiError) { api.get('/orgs/a/teams/b/members') } + assert_equal 'https://example.ghe.com/api/v3', api.bases[:rest] + end + + # ---- query cost, cap, paging -------------------------------------------- + + def test_nested_query_only_for_updated_prs + write_state(base_state('prs' => { '5' => { 'head' => SHA_A, 'ci' => 'none' }, + '6' => { 'head' => SHA_A, 'ci' => 'none' } })) + @gql = graphql(open: [pr(number: 5, updated: ago(30), comments: [comment(201, 'alice', ago(30))]), + pr(number: 6, updated: ago(4000), comments: [comment(202, 'alice', ago(10))])]) + assert_equal(['gh:comment:201'], run_watch.map { |e| e['id'] }) + main = server.main_queries.first.json['query'] + assert_includes main, 'pullRequests(states: [OPEN], first: 50' + refute_includes main, 'reviews(', 'the heads query has no nested connections' + assert_equal 1, server.detail_queries.size + assert_equal({ 'owner' => 'acme', 'name' => 'widgets', 'n0' => 5 }, server.detail_queries.first.json['variables']) + assert_equal 4, next_state['rate_limit']['cost'] + end + + def test_heads_beyond_the_cap_carry_over_until_refresh + old = { '5' => { 'head' => SHA_A, 'ci' => 'none' }, '99' => { 'head' => SHA_A, 'ci' => 'none' } } + write_state(base_state('prs' => old)) + @gql = graphql(open: [pr(number: 5, updated: ago(4000))]) + @gql['data']['repository']['open']['pageInfo'] = { 'hasNextPage' => true, 'endCursor' => 'NEXT' } + @routes['POST /graphql'] = lambda do |req| + if req.json['query'].include?('closed: pullRequests') + [200, {}, @gql] + else + assert_equal 'NEXT', req.json['variables']['openAfter'] + [200, {}, { 'data' => { 'repository' => { 'open' => { + 'pageInfo' => { 'hasNextPage' => false }, 'nodes' => [pr(number: 99, updated: ago(9000), head: SHA_B, head_author: 'bob')] + } }, 'rateLimit' => { 'cost' => 1, 'remaining' => 1 } } }] + end + end + assert_empty run_watch + assert_equal 1, server.graphql_requests.size, 'no paging between refreshes' + assert_equal %w[5 99], next_state['prs'].keys.sort, '#99 keeps its snapshot' + + write_state(base_state('prs' => old, 'last_full' => ago(301))) + assert_equal(["gh:push:99:#{SHA_B[0, 12]}"], run_watch.map { |e| e['id'] }) + assert_equal NOW.iso8601, next_state['last_full'] + end + + def test_cap_then_304_forces_a_query_for_the_dropped_events + write_state(base_state) + @gql = graphql(open: (1..205).map { |n| pr(number: n, created: ago(250 - n)) }) + assert_equal 200, run_watch.size + st = next_state + assert st['backlog'] + write_state(st) + before = server.main_queries.size + ids = run_watch.map { |e| e['id'] } # the PR etag now answers 304 + assert_equal 0, @status, @err + assert_equal before + 1, server.main_queries.size + assert_includes ids, 'gh:opened:205' + refute next_state.key?('backlog') + assert_equal NOW.iso8601, next_state['since'] + end + + def open_page(nodes, more) + { 'data' => { 'repository' => { 'open' => { + 'pageInfo' => { 'hasNextPage' => more, 'endCursor' => more ? 'NEXT2' : nil }, 'nodes' => nodes + } }, 'rateLimit' => { 'cost' => 1, 'remaining' => 1 } } } + end + + def test_heads_page_on_while_updated_since_between_refreshes + old = %w[5 6 7].to_h { |n| [n, { 'head' => SHA_A, 'ci' => 'none' }] } + write_state(base_state('prs' => old)) + @gql = graphql(open: [pr(number: 5, updated: ago(30))]) + @gql['data']['repository']['open']['pageInfo'] = { 'hasNextPage' => true, 'endCursor' => 'NEXT' } + pages = [] + @routes['POST /graphql'] = lambda do |req| + q = req.json['query'] + if q.include?('closed: pullRequests') then [200, {}, @gql] + elsif q.include?('p0: pullRequest(') then [200, {}, details_for(req)] + else + pages << req.json['variables']['openAfter'] + [200, {}, open_page([pr(number: 6, updated: ago(60), head: SHA_B, head_author: 'bob'), + pr(number: 7, updated: ago(9000))], true)] + end + end + assert_equal(["gh:push:6:#{SHA_B[0, 12]}"], run_watch.map { |e| e['id'] }) + assert_equal 0, @status, @err + assert_equal ['NEXT'], pages, 'stops once the last head is older than since' + assert_equal %w[5 6 7], next_state['prs'].keys.sort + assert_equal NOW.iso8601, next_state['since'] + end + + def test_truncated_connection_inside_the_window_holds_since_and_warns + write_state(base_state('prs' => { '5' => { 'head' => SHA_A, 'ci' => 'none' } })) + many = (1..100).map { |i| comment(1000 + i, 'bob', ago(100 - (i / 2))) } + @gql = graphql(open: [pr(number: 5, comments: many, comments_more: true)]) + events = run_watch + assert_equal 0, @status, @err + assert_equal 100, events.size, 'what was fetched is still emitted' + assert_equal "gh-watch: acme/widgets#5 comments truncated at 100 nodes; " \ + "holding since at #{ago(100)} to retry the rest next poll\n", @err + assert_equal ago(100), next_state['since'], 'since holds at the oldest fetched timestamp' + assert next_state['backlog'] + + # Reaching back past since is complete even at the cap: no truncation. + many[0] = comment(1001, 'bob', ago(4000)) + @gql = graphql(open: [pr(number: 5, comments: many, comments_more: true)]) + assert_equal 99, run_watch.size + assert_equal 0, @status, @err + assert_empty @err + refute next_state['backlog'] + end + + def test_missing_details_is_a_failure + write_state(base_state('prs' => { '5' => { 'head' => SHA_A, 'ci' => 'none' } })) + @gql = graphql(open: [pr(number: 5, comments: [comment(201, 'alice', ago(30))])]) + @routes['POST /graphql'] = lambda do |req| + if req.json['query'].include?('p0: pullRequest(') + [200, {}, { 'data' => { 'repository' => nil, 'rateLimit' => { 'cost' => 1, 'remaining' => 1 } } }] + else + [200, {}, @gql] + end + end + assert_empty run_watch + assert_equal [2, "gh-watch: pull request details missing\n"], [@status, @err] + refute File.exist?(File.join(@state_dir, 'state.json.next')) + end + + def test_max_pages_is_a_failure + write_state(base_state('etag' => @etag)) + @routes[/issues\?state=all&sort=updated&direction=asc/] = ->(_) { [200, {}, []] } + @routes[%r{issues/comments\?}] = lambda do |_| + [200, { 'Link' => "<#{server.base}/repos/acme/widgets/issues/comments?page=2>; rel=\"next\"" }, []] + end + run_watch('--jsonl', '--issues', 'on') + assert_equal [2, "gh-watch: more than 20 pages from /repos/acme/widgets/issues/comments\n"], [@status, @err] + refute File.exist?(File.join(@state_dir, 'state.json.next')) + end + + def test_pending_ci_bypass_expires_after_an_hour + write_state(base_state('etag' => @etag, + 'prs' => { '5' => { 'head' => SHA_A, 'ci' => 'pending', 'head_at' => ago(3601) } })) + run_watch + assert_equal 0, @status, @err + assert_empty server.graphql_requests + end + + # ---- logins, reviews, errors ---------------------------------------------- + + def test_me_is_case_insensitive + write_state(base_state('me' => nil, 'prs' => { '5' => { 'head' => SHA_A, 'ci' => 'none' } })) + @gql = graphql(open: [pr(number: 5, author: 'octocat', head: SHA_B, head_author: 'octocat', + reviews: [review(104, 'octocat', 'CHANGES_REQUESTED', ago(40))], + comments: [comment(201, 'alice', ago(30))])]) + ev = by_id(run_watch(env: { 'WATCHER_ME' => 'OctoCat' })) + assert_equal 0, @status, @err + refute ev.key?("gh:push:5:#{SHA_B[0, 12]}"), 'own push is skipped' + assert_equal 'info', ev['gh:review:104']['kind'] + assert_equal 'act', ev['gh:comment:201']['kind'], 'still my PR' + end + + def test_commented_review_wrapping_inline_comments_is_skipped + write_state(base_state('prs' => { '5' => { 'head' => SHA_A, 'ci' => 'none' } })) + @gql = graphql(open: [pr(number: 5, author: 'octocat', + reviews: [review(120, 'alice', 'COMMENTED', ago(40)), + review(121, 'alice', 'COMMENTED', ago(30), 'overall: nice')], + threads: [thread(inline(310, 'alice', ago(40), 'a.rb', 'x', review: 120), + inline(311, 'alice', ago(30), 'b.rb', 'y', review: 121))])]) + ev = by_id(run_watch) + assert_equal %w[gh:inline:310 gh:inline:311 gh:review:121], ev.keys.sort + assert_equal 'act', ev['gh:inline:310']['kind'] + end + + def test_unexpected_data_is_an_internal_error + write_state(base_state) + @gql = graphql(open: [pr(number: 5).merge('commits' => 'oops')]) + run_watch + assert_equal [2, "gh-watch: internal error TypeError\n"], [@status, @err] + refute File.exist?(File.join(@state_dir, 'state.json.next')) + end + + # ---- id stability ------------------------------------------------------- + + def test_ids_match_fixture + fixture = File.readlines(File.expand_path('fixtures/gh-watch-ids.txt', __dir__), chomp: true) + .reject { |l| l.empty? || l.start_with?('#') } + prs = { '5' => { 'head' => SHA_A, 'ci' => 'none', 'head_at' => ago(900) } } + write_state(base_state('prs' => prs)) + @gql = graphql(open: [pr(number: 5, author: 'octocat', head: SHA_B, rollup: 'FAILURE', created: ago(100), + reviews: [review(234_442_896, 'alice', 'CHANGES_REQUESTED', ago(60))], + comments: [comment(1_234_567_890, 'bob', ago(50))], + threads: [thread(inline(987_654_321, 'carol', ago(40), 'a.rb', 'x'))])], + closed: [closed(number: 3, state: 'MERGED', closed_at: '2026-11-19T11:58:07Z'), + closed(number: 4, state: 'CLOSED', closed_at: '2026-11-19T11:57:00Z')]) + assert_equal fixture.sort, run_watch.map { |e| e['id'] }.sort + end +end