diff --git a/config.example.yaml b/config.example.yaml index a7229d213..80f8746ed 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -356,7 +356,9 @@ sync: # failures on your own PR branches, drop # default-branch syncs and scheduled runs. # Repositories you follow without taking part in them: new PRs, issues and - # releases there. Nothing is set on the GitHub account. With + # releases there, and with the commit type the new commits on a branch (one + # record per branch; useful to gate a job on new commits, see docs/cron.md + # "messages"). Nothing is set on the GitHub account. With # sync.github.mode: hosted the channel gateway polls them too (it must know # the repository watch). Nothing older than a day is backfilled: a check # more than a day after the last (a daily schedule, an outage) reports the @@ -366,7 +368,14 @@ sync: enabled: false schedule: "*/15 * * * *" # poll mode; hosted: the fallback drain repos: [] # Required: ["acme/widgets"], each once, at most 50 - # types: [pull_request, issue] # pull_request | issue | release + # types: [pull_request, issue] # pull_request | issue | release | commit + # (hosted: commit only once the gateway + # knows the type, see docs/sources.md) + # branches: # commit type: the branches to follow, by + # acme/widgets: [main] # repository; no entry = its default branch. + # A branch's name, not a ref (main, not + # refs/heads/main); quote a name that YAML + # reads as something else: "1.10" # include_bots: false # also PRs and issues a GitHub App or a [bot] # opened; releases arrive whoever published them # include_drafts: true # false: a draft PR is reported when it is diff --git a/docs/config.md b/docs/config.md index b76851195..f4b3fc779 100644 --- a/docs/config.md +++ b/docs/config.md @@ -2195,7 +2195,8 @@ reload: | `sync.github_repos.enabled` | bool | `false` | Enable the repository watch. In hosted mode Nerve publishes it to the gateway only while it is on and `repos` lists a repository | | `sync.github_repos.schedule` | cron | `*/15 * * * *` | Poll frequency; in hosted mode the fallback cadence of the drain, which also runs on every delivery | | `sync.github_repos.repos` | list | `[]` | `owner/repo` names as GitHub writes them, each once (case does not matter), at most 50. While the watch is on, a name GitHub would not take, a repository named twice, or more than 50 refuses to load; while it is off, a warning names them. Empty = nothing is watched. Nothing older than a day is backfilled: a check more than a day after the last one (a daily schedule, an outage, the watch switched off for longer) reports the last day's items, with an hour of grace; in hosted mode, switching the watch off and on starts fresh | -| `sync.github_repos.types` | list | `[pull_request, issue]` | What is reported: `pull_request`, `issue`, `release`. Case does not matter; an unknown type or an empty list refuses to load | +| `sync.github_repos.types` | list | `[pull_request, issue]` | What is reported: `pull_request`, `issue`, `release`, `commit` (the new commits on a branch, one record per branch). Case does not matter; an unknown type or an empty list refuses to load. In hosted mode, name `commit` only once the gateway knows the type (see [sources.md](sources.md#hosted-repository-watch)) | +| `sync.github_repos.branches` | map | `{}` | With the `commit` type: the branches whose new commits are reported, as `owner/repo: [branch, …]` for a repository of `repos`, at most 8 each; a repository without an entry reports its default branch. An entry is a branch's name, not a ref (`main`, not `refs/heads/main`), and a name that YAML reads as something else goes in quotes (`"1.10"`). While the watch is on, a value that is not such a map (`branches: [main]`, `branches: []`), a branch that is not a string, a branch name the watch cannot follow, a branch named twice, more than 8, or a repository that `repos` does not list refuses to load (see [sources.md](sources.md#new-commits-on-a-branch)). Without the `commit` type the setting is not read, and a value there is ignored with a warning | | `sync.github_repos.include_bots` | bool | `false` | Also report the pull requests and issues that a GitHub App or an account whose login ends in `[bot]` opened. A release is reported whoever published it (release automation such as `github-actions[bot]` is the normal case) | | `sync.github_repos.include_drafts` | bool | `true` | `false`: a draft pull request is reported when it is marked ready for review (event `ready`), not when it is opened | | `sync.github_repos.updates` | bool | `false` | Also report a new head commit, ready for review, and the merge or close of each pull request the watch reported | diff --git a/docs/cron.md b/docs/cron.md index c998d670f..af735ce19 100644 --- a/docs/cron.md +++ b/docs/cron.md @@ -266,6 +266,41 @@ run_if: consumer: inbox ``` +A job that should run when a branch has new commits needs nothing more than +this gate. Let the [repository watch](sources.md#new-commits-on-a-branch) +report the branch's commits, and gate the job on that source's unread records: + +```yaml +# config.yaml +sync: + github_repos: + enabled: true + repos: [acme/widgets] + types: [commit] + branches: + acme/widgets: [main] +``` + +```yaml +jobs: + - id: on-new-commits + schedule: "*/10 * * * *" + prompt: > + Read the new records with poll_source(source="github_repos", + consumer="on-new-commits"). Each one lists the new commits of a branch. + Then ... + run_if: + - type: messages + sources: [github_repos] + consumer: on-new-commits +``` + +The job stays idle while the branch does not move. The watch reports one +record per branch however many commits arrive, so one push starts one run, +and reading the records with `poll_source` under the gate's `consumer` marks +them read. The gate looks at the source as a whole: when the watch also +reports pull requests or issues, those records satisfy it too. + Without `sources`, the gate checks the sources on which the consumer has a cursor. A consumer that reads every source with `poll_all_sources` gets a cursor on a new source before the source's first run, so the gate sees the first records diff --git a/docs/sources.md b/docs/sources.md index 80697e812..94a1a1f27 100644 --- a/docs/sources.md +++ b/docs/sources.md @@ -347,7 +347,9 @@ on the `github_pr_activity` gate. Repositories that the agent follows although its GitHub account takes no part in them: the new pull requests, issues and releases there arrive as `github_repos` records, and with `updates: true` so does each new commit, -ready for review, merge or close of a pull request it reported. It +ready for review, merge or close of a pull request it reported. With the +`commit` type it also reports the [new commits on a branch](#new-commits-on-a-branch), +one record per branch. It is the self-service form of GitHub's "Custom watch", which has no API. Nothing is set on the GitHub account (no watch, no e-mail), and it does not depend on `sync.github.inbox`. What the account itself takes part in (mentions, review @@ -359,11 +361,12 @@ notifications, and in hosted mode through `pr_watch`. - `pull_request`: `GET /repos/{repo}/pulls?state=all&sort=updated&direction=desc&per_page=100` - `issue`: `GET /repos/{repo}/issues?state=all&sort=updated&direction=desc&per_page=100`. The issues endpoint lists the pull requests too; they are skipped - `release`: `GET /repos/{repo}/releases?per_page=30`. Draft releases are skipped, prereleases are not + - `commit`: `GET /repos/{repo}/commits?sha=refs/heads/{branch}&per_page=100`, one request per branch that `branches` names for the repository. The request names the branch's ref, so a tag or a commit that has the same name is never read in its place. A repository without an entry in `branches` reports its default branch, which `GET /repos/{repo}` names at every run - **One page each:** a repository with more than 100 pull requests (or issues) changed between two runs loses the oldest of those changes. `batch_size` does not cap this source -- **Cursor:** JSON. Per repository and listing: the newest `updated_at` listed (`published_at` for releases), when the listing was read, and the numbers (release ids) of the items created in that newest second. Per repository, the pull requests it follows: a held draft (`include_drafts: false`) and, with `updates`, a reported pull request while it is open, as head commit, draft and held. At most 1,000 per repository; the one listed longest ago is forgotten first +- **Cursor:** JSON. Per repository and listing: the newest `updated_at` listed (`published_at` for releases), when the listing was read, and the numbers (release ids) of the items created in that newest second. Per repository, the pull requests it follows: a held draft (`include_drafts: false`) and, with `updates`, a reported pull request while it is open, as head commit, draft and held. At most 1,000 per repository; the one listed longest ago is forgotten first. And per repository, the head commit of each branch whose commits it follows - **First run:** the baseline. Each listing's cursor is set and nothing is reported, so switching the source on does not fill the inbox with history; a repository or a type added later takes its own baseline, and one removed is forgotten. An item is new when it was created (a release: published) after the last listing: later than the listing's cursor, or in the cursor's own second and not listed then, since GitHub's times have a resolution of one second. So an older pull request that changes later is never reported as new, and an item is reported once - **No backfill beyond a day:** nothing older than a day is backfilled, and the last day is. A check more than a day after the last one (a daily schedule, which always comes a moment past the day; a weekday schedule after the weekend; the watch switched off for longer; a long outage) reads the listing as of a day and an hour ago: it reports the items of the last day, with an hour of grace for the scheduler's delay (an item created moments after the last check is not lost), within the one page, and nothing older, and the pull requests it follows stay followed. So switching the watch off and on in poll mode resumes where it left within the day, and beyond it reports the last day's items -- **Failures:** a listing that fails (a repository that does not exist or that the `gh` login cannot read, a rate limit) keeps its cursor and is read again on the next run; the other listings still report. A run in which every listing fails fails, and the source's health shows it +- **Failures:** a listing that fails (a repository that does not exist or that the `gh` login cannot read, a branch that does not exist, a rate limit) keeps its cursor and is read again on the next run; the other listings still report. A run in which every listing fails fails, and the source's health shows it - **Upgrades:** the cursor of the earlier version of this source, one timestamp, becomes the cursor of every listing (one more than a day old reports the last day), so nothing is repeated or skipped; a buffer position left by the hosted mode is no cursor (a new baseline). The earlier version took any `repos` value: one that the watch now refuses (a URL such as `https://github.com/acme/widgets`, a trailing slash, `owner/repo/x`, the same repository twice, more than 50) only logs a warning while the watch is off, and refuses the config once it is on - **Default schedule:** `*/15 * * * *` (every 15 min); in hosted mode the fallback cadence of the drain - **Disabled by default** @@ -373,17 +376,20 @@ sync: github_repos: enabled: true repos: ["acme/widgets", "other-org/other-repo"] - types: [pull_request, issue] # pull_request | issue | release + types: [pull_request, issue] # pull_request | issue | release | commit include_bots: false # PRs and issues a GitHub App or a [bot] account opened include_drafts: true # false: a draft is reported when it is ready for review updates: false # true: commits, ready, merge and close of reported PRs deny_authors: [] # case-insensitive globs on the author's login + # branches: # with the commit type: the branches to follow, by repository + # acme/widgets: [main, release/1.2] # no entry: the repository's default branch ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `github_repos.repos` | list | `[]` | `owner/repo` names as GitHub writes them, each once (case does not matter), at most 50. While the watch is on, a name GitHub would not take, the same repository twice, or more than 50 refuses to load; while it is off, a warning names them. Empty = the source does nothing | -| `github_repos.types` | list | `[pull_request, issue]` | What is reported: `pull_request`, `issue`, `release`. Case does not matter; an unknown type, or an empty list, refuses to load | +| `github_repos.types` | list | `[pull_request, issue]` | What is reported: `pull_request`, `issue`, `release`, `commit` (the [new commits on a branch](#new-commits-on-a-branch)). Case does not matter; an unknown type, or an empty list, refuses to load | +| `github_repos.branches` | map | `{}` | With the `commit` type: the branches whose new commits are reported, as `owner/repo: [branch, …]` for a repository of `repos` (case does not matter; one branch may be written as a string), at most 8 each. A repository without an entry, or with an empty one, reports its default branch. An entry is the name of a branch, such as `main` or `release/1.2`, and not a ref: it starts with a letter or a digit and goes on with letters, digits, `_`, `.`, `/` and `-`, up to 121 characters, without `..`, not starting with `refs/` and not ending in `.lock`; the repository's name and the branch have at most 194 bytes together. Write a name that YAML reads as something else in quotes: an unquoted `1.10` is the number `1.1`, and `no`, `off` and `0` are no names. [New commits on a branch](#new-commits-on-a-branch) lists what refuses to load. Without the `commit` type the setting is not read: a value that is left there is ignored, with one warning | | `github_repos.include_bots` | bool | `false` | Also report the pull requests and issues that a GitHub App (`user.type` `Bot`) or an account whose login ends in `[bot]` opened. A release is reported whoever published it: release automation (`github-actions[bot]`, a release bot) is the normal case. `author_kind` still says `bot` on such a release | | `github_repos.include_drafts` | bool | `true` | `false`: a new draft pull request is held and reported when it is marked ready for review (event `ready`), never as `opened`; one closed while it is a draft is never reported | | `github_repos.updates` | bool | `false` | Also report, for each pull request this source reported, a new head commit (`updated`), ready for review (`ready`), and its merge (`merged`) or close (`closed`), after which it is no longer followed | @@ -399,6 +405,7 @@ Events (the record's `Event:` line and `event` metadata): | `merged` | `updates`: a reported pull request was merged | `#:merged:merged` | `merged_at` | | `closed` | `updates`: a reported pull request was closed without a merge | `#:closed:closed` | `closed_at` | | `released` | A release was published since the last run | `#:released:` | `published_at` | +| `pushed` | `commit` type: the head of a followed branch is another commit than at the last run | `@:pushed:..`, with the first 12 characters of the two commits | The time of the run | A pull request gives one record per run: `merged` or `closed`, else `ready`, else `updated`; back to draft gives none, and one seen for the first time is @@ -437,6 +444,97 @@ inbox guardrail applies them again to what arrives (`repo_name` against `types`), which catches the records delivered before a reload changed them. Everything here follows a reload. +#### New commits on a branch + +With `commit` among the `types`, the watch follows branches: those that +`branches` names for a repository, or the repository's default branch. It is +made for work that should start when a branch moves, such as a build or a +test run: a cron job [gated on the source's unread records](cron.md#messages) +runs when there are new commits and stays idle otherwise. + +- **One record per branch and run, never one per commit.** The first run of a + branch only stores its head. From then on, a run that finds another head + reports one `pushed` record for the branch, however many commits arrived + and however long after the last run: the day's limit above is for pull + requests, issues and releases, not for branches. +- **Which commits it lists.** The watch reads the first 100 commits of the + branch's listing on GitHub, the head first. `commits` are the newest + commits of that listing above the head of the last run (`before_sha`), up + to 50 of them, and `commit_count` counts the commits of the listing above + `before_sha`, listed or not. +- **Merges.** GitHub lists by commit date, not by ancestry. Across a merge + the listing interleaves the commits of the merged branches by their dates, + so a commit that the merge brought in can be listed below `before_sha`: + `commits` and `commit_count` are not always the exact set of the new + commits. `subject_url`, the comparison of the two heads on GitHub, is. +- **`truncated`.** `true` when `before_sha` is not among the listed commits, + after 100 or more new commits or a push that rewrote the branch: then + `commit_count` is empty and `commits` holds the branch's newest commits. + Also `true` when `commit_count` is more than the 50 commits that `commits` + lists. Otherwise `false`. +- **The record's ID names both heads**, + `@:pushed:..` with the first 12 characters of + `before_sha` and of `head_sha`. So a branch that returns to an earlier + head, as after a push that was taken back, gives a record of its own, and + only the same move again, between the same two commits, has the ID of an + earlier record. +- **Branches only.** A name in `branches` is followed as the branch of that + name: a tag or a commit that has the same name is never read in its place, + and without such a branch the listing fails as for a branch that does not + exist. +- **No author filters.** One record can hold commits of many authors, so + neither `include_bots` nor `deny_authors` judges it, and its metadata has + no `author`. +- **A branch that cannot be read** (it does not exist, or the repository has + no commit yet) fails its listing alone and keeps its head; see Failures + above. A default branch whose name is outside the shape of `branches` is + not followed, with a warning. + +With the `commit` type, and while the watch is on, `branches` refuses to load +when it holds any of these: + +- a value that is not a map of repositories to their branches, such as + `branches: [main]` or `branches: []`. To name no branch, leave the setting + out or write `branches: {}` +- a repository that `repos` does not list, or the same repository twice + (names ignore case) +- a branch that is not a string: what YAML makes of an unquoted `1.10`, `no`, + `off`, `yes`, `on`, `0` or a date, and an empty item of a list. The message + says to quote it: `"1.10"` +- a branch name of another shape than the settings table gives, or one that + starts with `refs/`: write `main`, not `refs/heads/main` +- the same branch twice, or more than 8 branches for one repository +- a repository's name and a branch that have more than 194 bytes together + +A blank name is left out. While the watch is off, one warning names what +would refuse and those entries are left out, so the config loads. Without the +`commit` type nothing of `branches` is checked. + +The record's summary is `[acme/widgets] 3 new commits on main`, or +`[acme/widgets] main moved to 5c4d3e2f1a0b` when it cannot count them. Its +content has the lines `Repository:`, `Type: Commit`, `Event: pushed`, +`Branch:`, `Commits:` (the count, when there is one), `Head:`, `Before:` and +`URL:`, then the commits, one line each: the commit and the first line of its +message, cut to 120 characters, with a space in the place of each control +character, of the line and the paragraph separator (U+2028, U+2029) and of +each bidirectional control (U+202A to U+202E, U+2066 to U+2069). A record +that is `truncated` ends with `[... not every new commit is listed]`. Its +metadata, the same in both modes: + +| Key | Value | +|-----|-------| +| `repo_name` | `owner/repo`, as configured | +| `event` | `pushed` | +| `subject_type` | `Commit` | +| `branch` | The branch | +| `head_sha` | The branch's head | +| `before_sha` | Its head at the last run | +| `commit_count` | The number of commits that the listing shows above `before_sha`, as a decimal string; empty when the listing does not show `before_sha` | +| `commits` | A list of the newest of them, up to 50, in the listing's order, each ` ` | +| `truncated` | `true` or `false`, as above | +| `subject_url` | `https://github.com///compare/...` | +| `repo_url` | `https://github.com//`, as configured | + #### Hosted repository watch GitHub is hosted as a whole: with `sync.github.mode: hosted` the channel @@ -452,7 +550,8 @@ machine for them. paused while the others keep being polled. - **What is published.** Nerve sends the gateway a `github_repos` subscription: each repository with `types`, `include_bots`, - `include_drafts`, `updates` and `deny_authors`, when a stream opens and again + `include_drafts`, `updates` and `deny_authors`, and with the `commit` type + the `branches` that the settings name for it, when a stream opens and again on every reload, only while `enabled` is true and `repos` lists a repository. Switching it off and reloading tells the gateway to stop. A `deny_authors` list the gateway cannot take (more than 256 patterns, or a @@ -467,6 +566,22 @@ machine for them. closes the stream, hosted Slack traffic included. Update the gateway before an agent switches the watch on in hosted mode. An agent that does not switch it on sends the same subscription as before, so it is unaffected. +- **The gateway must know the `commit` type.** Nerve cannot ask the gateway + which types it knows. A gateway older than the `commit` type refuses a + subscription that names it: it closes the stream, hosted Slack traffic + included, each time the agent connects, until the gateway is updated or + `commit` is taken out of `types`. So name `commit` on a hosted agent only + once its gateway knows the type. An agent whose `types` do not name + `commit` sends the same subscription as before, whatever `branches` says. +- **Commits in hosted mode.** The gateway follows the branches as described + under [New commits on a branch](#new-commits-on-a-branch), with these + differences: a branch that GitHub does not find rests for an hour before + the gateway asks again, while the repository's other branches and listings + go on, and a repository that GitHub does not find is paused as a whole, as + for the other types; a branch whose listing fails, as while GitHub has an + outage, rests for a few minutes; and the gateway reads a repository's + default branch at least once an hour, not at every poll, so a default + branch that changes is followed, from its head, within the hour. - **Same source, same name.** The records go to their own local buffer, and the `source:github_repos` runner drains it, as the `github` runner drains the notifications (see [Hosted GitHub source](#hosted-github-source)): it diff --git a/nerve/channels/hosted/contract/model.py b/nerve/channels/hosted/contract/model.py index d31872829..bc95a3690 100644 --- a/nerve/channels/hosted/contract/model.py +++ b/nerve/channels/hosted/contract/model.py @@ -98,9 +98,19 @@ # Such a subscription names 1 to this many repositories, each once. MAX_REPO_WATCHES = 50 # What a watched repository may report. -REPO_WATCH_TYPES = ("pull_request", "issue", "release") +REPO_WATCH_TYPES = ("pull_request", "issue", "release", "commit") +# The type that reports the new commits of a repository's branches: only a +# repository with it names branches, and a gateway that does not know the +# type refuses the whole subscription. +REPO_WATCH_COMMIT = "commit" # A repository as GitHub names it: owner/name. _REPO_NAME = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9_.-]{1,100}") +# A watched repository names at most this many branches, each a name of this +# shape, and its own name and a branch's have at most this many bytes +# together: the event ID of a commit record names both. +MAX_REPO_WATCH_BRANCHES = 8 +MAX_REPO_WATCH_BRANCH_KEY_BYTES = 194 +_REPO_BRANCH = re.compile(r"[A-Za-z0-9][A-Za-z0-9_./-]{0,120}") # A provider name is a lowercase token of at most this many bytes. MAX_PROVIDER_BYTES = 64 _PROVIDER_CHARACTERS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789_-.") @@ -165,6 +175,23 @@ def valid_repo_name(name: str) -> bool: return _REPO_NAME.fullmatch(name) is not None and name.split("/", 1)[1] not in (".", "..") +def valid_repo_branch(repo: str, branch: str) -> bool: + """Whether the gateway takes *branch* as a watched branch of *repo*. + + A letter or a digit, then up to 120 letters, digits, ``_``, ``.``, ``/`` + and ``-``, without ``..``, not starting with ``refs/`` (a branch is named + without its ref prefix) and not ending in ``.lock``, and no longer with + the repository's name than :data:`MAX_REPO_WATCH_BRANCH_KEY_BYTES`. + """ + return ( + _REPO_BRANCH.fullmatch(branch) is not None + and ".." not in branch + and not branch.startswith("refs/") + and not branch.endswith(".lock") + and byte_length(repo) + byte_length(branch) <= MAX_REPO_WATCH_BRANCH_KEY_BYTES + ) + + def valid_provider(provider: str) -> bool: """Whether the gateway takes *provider* as a provider name. @@ -905,7 +932,14 @@ class RepoWatch: glob never is. Without ``include_drafts`` a draft pull request is reported when it becomes ready for review, and with ``updates`` a reported pull request is reported again when its head - commit, its draft state or its state changes. Every member is sent. + commit, its draft state or its state changes. Every one of these members + is sent. + + ``branches`` are the branches whose new commits a repository with the + ``commit`` type reports; without them it reports its default branch. + Each is the name of a branch, without its ref prefix. It is sent only + when it names a branch, so the frame of a repository without one is the + same as before the member existed. """ name: str = "" @@ -914,6 +948,7 @@ class RepoWatch: include_drafts: bool = False updates: bool = False deny_authors: tuple[str, ...] = () + branches: tuple[str, ...] = omit_empty(()) @_record @@ -1025,7 +1060,9 @@ def _validate_repo_watches(source: SourceSubscription) -> None: ``owner/repo`` name (:func:`valid_repo_name`) and each once, ignoring case; every one reports one or more of :data:`REPO_WATCH_TYPES`, each once, and has at most :data:`MAX_SUBSCRIPTION_PATTERNS` ``deny_authors`` - that a filter list would take. It carries no filters, ``pr_watch`` or + that a filter list would take, and at most + :data:`MAX_REPO_WATCH_BRANCHES` branches, each once and each one that + :func:`valid_repo_branch` takes. It carries no filters, ``pr_watch`` or ``inbox``. """ if any(source.filters.pattern_lists().values()) or source.pr_watch or source.inbox: @@ -1056,6 +1093,12 @@ def _validate_repo_watches(source: SourceSubscription) -> None: "a watched repository's deny_authors pattern is empty, too long, or has a " "control character" ) + if len(repo.branches) > MAX_REPO_WATCH_BRANCHES: + reject(RejectionReason.LIMIT_EXCEEDED, "a watched repository names too many branches") + if len(set(repo.branches)) < len(repo.branches) or not all( + valid_repo_branch(repo.name, branch) for branch in repo.branches + ): + malformed("a watched repository names a branch twice, or one the gateway does not take") # ---------------------------------------------------------------------- # diff --git a/nerve/channels/hosted/sources.py b/nerve/channels/hosted/sources.py index 2db88d394..143ad69ed 100644 --- a/nerve/channels/hosted/sources.py +++ b/nerve/channels/hosted/sources.py @@ -43,13 +43,16 @@ validate_thread_item, ) from nerve.channels.hosted.contract.model import ( + MAX_REPO_WATCH_BRANCHES, MAX_REPO_WATCHES, MAX_SUBSCRIPTION_PATTERN_BYTES, MAX_SUBSCRIPTION_PATTERNS, + REPO_WATCH_COMMIT, REPO_WATCH_PROVIDER, REPO_WATCH_TYPES, ZERO_TIME, valid_pattern, + valid_repo_branch, valid_repo_name, ) from nerve.channels.hosted.contract.wire import Rejected, format_time @@ -162,6 +165,11 @@ def github_repos_subscription(settings: GitHubReposSyncConfig) -> SourceSubscrip :data:`MAX_REPO_WATCHES` too, with a warning, so that the gateway never closes the stream over them. ``deny_authors`` goes as a deny list does: the patterns that fit, while the inbox filter applies them all. + + The types are those of :func:`repo_watch_types`. A repository carries + ``branches`` only with the ``commit`` type and only when the settings + name one for it (:func:`_published_branches`), so the frame of an agent + that does not ask for commits is the same as before the type existed. """ names: list[str] = [] seen: set[str] = set() @@ -181,25 +189,69 @@ def github_repos_subscription(settings: GitHubReposSyncConfig) -> SourceSubscrip len(names), MAX_REPO_WATCHES, ) names = names[:MAX_REPO_WATCHES] - chosen = {str(kind).strip().lower() for kind in settings.types or ()} - types = tuple(kind for kind in REPO_WATCH_TYPES if kind in chosen) + types = repo_watch_types(settings) if not names or not types: return None deny_authors = _deny_list("sync.github_repos.deny_authors", settings.deny_authors) - return SourceSubscription( - provider=GITHUB_REPOS, - repos=tuple( - RepoWatch( - name=name, - types=types, - include_bots=bool(settings.include_bots), - include_drafts=bool(settings.include_drafts), - updates=bool(settings.updates), - deny_authors=deny_authors, - ) - for name in names - ), - ) + repos: list[RepoWatch] = [] + for name in names: + branches = _published_branches(settings, name) if REPO_WATCH_COMMIT in types else () + # A repository whose branches cannot be published does not report the + # commits of its default branch in their place. + reported = tuple( + kind for kind in types if kind != REPO_WATCH_COMMIT or branches is not None + ) + if not reported: + continue + repos.append(RepoWatch( + name=name, + types=reported, + include_bots=bool(settings.include_bots), + include_drafts=bool(settings.include_drafts), + updates=bool(settings.updates), + deny_authors=deny_authors, + branches=branches or (), + )) + return SourceSubscription(provider=GITHUB_REPOS, repos=tuple(repos)) if repos else None + + +def repo_watch_types(settings: GitHubReposSyncConfig) -> tuple[str, ...]: + """The types of ``sync.github_repos.types`` that the gateway is sent. + + Every type that the settings name, in the contract's order. The gateway + advertises nothing about the types that it knows, and one that does not + know a type refuses the whole subscription and closes the stream. So + ``commit`` may be named only where the gateway knows it (docs/sources.md, + "Hosted repository watch"). This function is the one place that decides + which types are sent. + """ + chosen = {str(kind).strip().lower() for kind in settings.types or ()} + return tuple(kind for kind in REPO_WATCH_TYPES if kind in chosen) + + +def _published_branches(settings: GitHubReposSyncConfig, repo: str) -> tuple[str, ...] | None: + """The branches of *repo* whose commits the gateway is asked for. + + Empty when the settings name none: the gateway then follows the + repository's default branch. The config refuses to load branches the + gateway would not take; a setting built some other way loses those, the + ones named twice and the ones past :data:`MAX_REPO_WATCH_BRANCHES`, with + a warning. ``None`` when the settings name branches and none can be + published. + """ + wanted = settings.branches_of(repo) + branches: list[str] = [] + for branch in wanted: + if valid_repo_branch(repo, branch) and branch not in branches: + branches.append(branch) + if len(branches) < len(wanted) or len(branches) > MAX_REPO_WATCH_BRANCHES: + logger.warning( + "sync.github_repos.branches of %s: the gateway is sent %d of %d branches", + repo, min(len(branches), MAX_REPO_WATCH_BRANCHES), len(wanted), + ) + if wanted and not branches: + return None + return tuple(branches[:MAX_REPO_WATCH_BRANCHES]) def _patterns(values: object) -> list[str]: @@ -374,5 +426,6 @@ async def stop(self) -> None: "github_repos_subscription", "github_subscription", "hosted_sources", + "repo_watch_types", "subscriptions_for", ] diff --git a/nerve/config.py b/nerve/config.py index 847269b30..1d3b7d7ee 100644 --- a/nerve/config.py +++ b/nerve/config.py @@ -2254,16 +2254,45 @@ def from_dict(cls, d: dict) -> GitHubEventsSyncConfig: # What the GitHub Repos source can report from a repository (see # GitHubReposSyncConfig.types), and what it reports when nothing is said. -GITHUB_REPOS_TYPES: tuple[str, ...] = ("pull_request", "issue", "release") +GITHUB_REPOS_TYPES: tuple[str, ...] = ("pull_request", "issue", "release", "commit") GITHUB_REPOS_DEFAULT_TYPES: tuple[str, ...] = ("pull_request", "issue") # The most repositories the source follows; the channel gateway's bound too. GITHUB_REPOS_MAX_REPOS = 50 +# The most branches of one repository whose commits the source follows, and +# the most bytes that a repository's name and a branch's name have together +# (the id of a commit record names both). The channel gateway's bounds too. +GITHUB_REPOS_MAX_BRANCHES = 8 +GITHUB_REPOS_MAX_BRANCH_KEY_BYTES = 194 +# A branch whose commits the source can follow: a letter or a digit, then up +# to 120 letters, digits, "_", ".", "/" and "-". It is the branch's name and +# not a ref, so it does not start with "refs/": the source asks GitHub for +# refs/heads/. The channel gateway checks the same. +_GITHUB_BRANCH_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_./-]{0,120}") +_GITHUB_REF_PREFIX = "refs/" # A repository as GitHub names it: an owner of 1 to 39 letters, digits and # hyphens that starts with a letter or a digit, then a name of 1 to 100 # letters, digits, ".", "_" and "-". The channel gateway checks the same. _GITHUB_REPO_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9_.-]{1,100}") +def github_repos_branch_ok(repo: str, branch: str) -> bool: + """Whether the GitHub Repos source can follow the commits of *branch* of *repo*. + + The name has the shape of :data:`_GITHUB_BRANCH_NAME_RE`, no ``..`` and no + ``.lock`` at its end, and with the repository's name it stays within + :data:`GITHUB_REPOS_MAX_BRANCH_KEY_BYTES`. A name that starts with + ``refs/`` is refused: a branch is named without its ref prefix, so that + ``main`` and ``refs/heads/main`` cannot both be followed. + """ + return ( + _GITHUB_BRANCH_NAME_RE.fullmatch(branch) is not None + and ".." not in branch + and not branch.endswith(".lock") + and not branch.startswith(_GITHUB_REF_PREFIX) + and len(repo.encode()) + len(branch.encode()) <= GITHUB_REPOS_MAX_BRANCH_KEY_BYTES + ) + + def _switched_on(value: object) -> bool: """An ``enabled`` value as the scalar coercion reads it, without its warning.""" if isinstance(value, bool): @@ -2356,6 +2385,94 @@ def _github_repos_types(value: object) -> list[str]: return [kind for kind in GITHUB_REPOS_TYPES if kind in chosen] +def _github_repos_branches( + value: object, repos: list[str], *, enabled: bool, commits: bool, +) -> dict[str, list[str]]: + """``sync.github_repos.branches``: the branches to follow, by repository. + + The setting is read only with the ``commit`` type (*commits*). Without + it, a value that names something is ignored, with one warning. + + A mapping of a repository of ``repos`` (GitHub's names ignore case) to one + branch or a list of branches, each a string; a blank one is left out, and + a repository without a value names none. It is returned under the names + that *repos* spells. While the watch is on (*enabled*), anything else + refuses to load: a value that is no mapping, a repository that ``repos`` + does not list or that the mapping names twice, a branch that is not a + string, that :func:`github_repos_branch_ok` refuses, or that is named + twice, and more than :data:`GITHUB_REPOS_MAX_BRANCHES` branches. A branch + that is not a string is one that YAML read as something else, and the + message says to quote it: an unquoted ``1.10`` is the number ``1.1``, and + ``no``, ``off`` and ``0`` are values that are no names. While the watch is + off, those are logged in one warning and left out. + """ + if value is None or value == "": + return {} + if not commits: + if value: + logger.warning( + "sync.github_repos.branches is set, and sync.github_repos.types does not name " + "commit: the branches are not read", + ) + return {} + problems: list[str] = [] + + def refuse(problem: str) -> None: + if enabled: + raise ValueError(f"sync.github_repos.branches {problem}") + problems.append(problem) + + branches: dict[str, list[str]] = {} + if not isinstance(value, dict): + refuse(f"must map owner/repo names to their branches, got {str(value)!r}") + value = {} + watched = {name.lower(): name for name in repos} + for key, entry in value.items(): + repo = watched.get(str(key or "").strip().lower()) + if repo is None: + refuse(f"names {str(key)!r}, which sync.github_repos.repos does not list") + continue + if repo in branches: + refuse(f"names {repo!r} twice") + continue + # A repository without a value names no branch, as an empty list does. + items = ( + list(entry) if isinstance(entry, (list, tuple)) else [] if entry is None else [entry] + ) + unquoted = [item for item in items if not isinstance(item, str)] + if unquoted: + refuse( + f"of {repo!r} must name each branch as a string, got {unquoted[0]!r}: put the " + "name in quotes, since YAML reads an unquoted 1.10 as the number 1.1, and an " + "unquoted no, off or 0 as a value that is no name" + ) + continue + names = [name for name in (item.strip() for item in items) if name] + bad = [name for name in names if not github_repos_branch_ok(repo, name)] + if bad: + refuse( + f"of {repo!r} must be branch names of letters, digits, '_', '.', '/' and '-' " + "that start with a letter or a digit, without '..', not starting with 'refs/' " + f"and not ending in '.lock', at most {GITHUB_REPOS_MAX_BRANCH_KEY_BYTES} bytes " + f"together with the repository's name, got {bad[0]!r}" + ) + elif len(set(names)) < len(names): + refuse(f"of {repo!r} name a branch twice") + elif len(names) > GITHUB_REPOS_MAX_BRANCHES: + refuse( + f"of {repo!r} must name at most {GITHUB_REPOS_MAX_BRANCHES} branches, " + f"got {len(names)}" + ) + else: + branches[repo] = names + if problems: + logger.warning( + "sync.github_repos is switched off, and its branches would refuse to load once " + "it is switched on: sync.github_repos.branches %s", "; ".join(problems), + ) + return {repo: names for repo, names in branches.items() if names} + + @dataclass class GitHubReposSyncConfig: """Config for the GitHub Repos source: repositories the agent follows. @@ -2363,7 +2480,8 @@ class GitHubReposSyncConfig: Unlike ``github`` (notifications) and ``github_events`` (your own activity), this source watches an explicit set of repositories that the account need not take part in, and reports new pull requests, issues and - releases there (``types``). ``repos`` is required: an empty list makes the + releases there, and the new commits of its branches (``types``, + ``branches``). ``repos`` is required: an empty list makes the source a no-op. With ``sync.github.mode: hosted`` the channel gateway polls the repositories for the agent, as it polls the notifications; otherwise this process polls them with the gh CLI. All of it follows a @@ -2375,9 +2493,17 @@ class GitHubReposSyncConfig: # watch is on, anything else refuses to load (while it is off, a # warning). Required; empty = no-op. repos: list[str] = field(default_factory=list) - # What is reported: pull_request, issue, release (GITHUB_REPOS_TYPES). - # An unknown type or an empty list refuses to load. + # What is reported: pull_request, issue, release, commit + # (GITHUB_REPOS_TYPES). An unknown type or an empty list refuses to load. types: list[str] = field(default_factory=lambda: list(GITHUB_REPOS_DEFAULT_TYPES)) + # With the commit type: the branches whose new commits are reported, by + # repository (a name of repos; case does not matter). A repository + # without an entry reports its default branch. At most + # GITHUB_REPOS_MAX_BRANCHES each; while the watch is on, a name that is + # not a string or that github_repos_branch_ok refuses, or a repository + # that repos does not list, refuses to load. Without the commit type the + # setting is not read, and a value there is ignored with a warning. + branches: dict[str, list[str]] = field(default_factory=dict) # Also report the pull requests and issues that a GitHub App or a "[bot]" # account opened. A release is reported whoever published it. include_bots: bool = False @@ -2396,16 +2522,28 @@ class GitHubReposSyncConfig: prompt_hint: str = "" model: str = "" + def branches_of(self, repo: str) -> list[str]: + """The branches of *repo* that ``branches`` names; none: its default branch.""" + wanted = repo.strip().lower() + for name, names in (self.branches or {}).items(): + if str(name).strip().lower() == wanted: + return [str(branch) for branch in names or ()] + return [] + @classmethod @_coerced def from_dict(cls, d: dict) -> GitHubReposSyncConfig: + enabled = _switched_on(d.get("enabled", False)) + repos = _github_repos_names(d.get("repos"), enabled=enabled) + types = _github_repos_types(d.get("types")) return cls( enabled=d.get("enabled", False), schedule=d.get("schedule", "*/15 * * * *"), - repos=_github_repos_names( - d.get("repos"), enabled=_switched_on(d.get("enabled", False)), + repos=repos, + types=types, + branches=_github_repos_branches( + d.get("branches"), repos, enabled=enabled, commits="commit" in types, ), - types=_github_repos_types(d.get("types")), include_bots=d.get("include_bots", False), include_drafts=d.get("include_drafts", True), updates=d.get("updates", False), diff --git a/nerve/onboarding_environment.py b/nerve/onboarding_environment.py index 08a0e66b1..39f04588b 100644 --- a/nerve/onboarding_environment.py +++ b/nerve/onboarding_environment.py @@ -260,7 +260,10 @@ def _github_access(cli: _GitHubCLI) -> str: "all": "the account's whole notification inbox (inbox `all`)", } #: How the repository watch names each of its types. -_WATCHED_TYPES = {"pull_request": "pull requests", "issue": "issues", "release": "releases"} +_WATCHED_TYPES = { + "pull_request": "pull requests", "issue": "issues", "release": "releases", + "commit": "branch commits", +} def _github_sync_text(config: Any) -> str: diff --git a/nerve/sources/github_hosted.py b/nerve/sources/github_hosted.py index 6460c5b48..3b2bf69c1 100644 --- a/nerve/sources/github_hosted.py +++ b/nerve/sources/github_hosted.py @@ -25,8 +25,9 @@ "timestamp": RFC 3339, "metadata": [{"key", "value", "values"}, ...]}} -Metadata values arrive as strings. ``actors`` and ``changes`` are lists, and -``unread`` and ``mentions_agent`` become booleans. +Metadata values arrive as strings. ``actors``, ``changes`` and ``commits`` +are lists, and ``unread``, ``truncated`` and ``mentions_agent`` become +booleans. A ``github_thread_item`` record (one comment, review or description of a thread, with its author) gets a few fixed lines before its text that say @@ -55,8 +56,8 @@ # and source name is the provider's name. PROVIDERS = ("github", "github_repos") # Metadata keys whose value is a list of strings, and those that are flags. -_LIST_KEYS = frozenset({"actors", "changes"}) -_FLAG_KEYS = frozenset({"unread", "mentions_agent"}) +_LIST_KEYS = frozenset({"actors", "changes", "commits"}) +_FLAG_KEYS = frozenset({"unread", "truncated", "mentions_agent"}) # How a thread item's message names its thread, its kind and its author's # relation to the agent (the gateway's ``author_relation``). diff --git a/nerve/sources/github_repos.py b/nerve/sources/github_repos.py index 0704e656a..86ba9ab43 100644 --- a/nerve/sources/github_repos.py +++ b/nerve/sources/github_repos.py @@ -4,7 +4,8 @@ ``github_events`` source captures *your own* actions, this source watches a configured set of repositories (``sync.github_repos.repos``) that the account need not take part in, and reports new pull requests, issues and releases -there (``types``). Nothing is set on the GitHub account: no watch, no e-mail. +there, and the new commits of its branches (``types``). Nothing is set on the +GitHub account: no watch, no e-mail. This module is the poll mode: the gh CLI, on the source's schedule. With ``sync.github.mode: hosted`` the channel gateway polls the same listings for @@ -17,6 +18,11 @@ * ``issue``: ``GET /repos/{repo}/issues?state=all&sort=updated&direction=desc&per_page=100``; the issues endpoint lists the pull requests too, and they are skipped * ``release``: ``GET /repos/{repo}/releases?per_page=30``; drafts are skipped +* ``commit``: ``GET /repos/{repo}/commits?sha=refs/heads/{branch}&per_page=100`` + for each branch that ``branches`` names for the repository, or for its + default branch, which ``GET /repos/{repo}`` names. The request names the + branch's ref, so a tag or a commit of the same name is never read in its + place Events (the record's ``Event:`` line and ``event`` metadata): @@ -28,6 +34,9 @@ merge, or a close without one, of a pull request already reported. One record per pull request and run: merged or closed, else ready, else updated * ``released``: a release published since the last listing +* ``pushed``: the head of a branch is another commit than at the last + listing. One record per branch and run, with the commits that the listing + shows above the earlier head, never one record per commit Comments, reviews and labels move ``updated_at`` and report nothing. Before anything is reported or remembered, a pull request or an issue is dropped @@ -35,17 +44,20 @@ ``include_bots``; a release is reported whoever published it, release automation being the normal case), and any item whose author's login matches a ``deny_authors`` glob (the rules of the actor guardrail: a -pattern that ends in ``[bot]`` names a GitHub App). +pattern that ends in ``[bot]`` names a GitHub App). Neither filter judges +the commits of a branch: one record can hold commits of many authors. The cursor is JSON: per repository, for each listing its newest ``updated_at`` (``published_at`` for releases), when it was read, and the keys of the items created in that newest second; and the fingerprints of the pull requests it follows (``[head commit, draft, held]``), a held draft or, with -``updates``, a reported pull request that is still open:: +``updates``, a reported pull request that is still open; and the head commit +of each branch whose commits it follows:: {"v": 1, "repos": {"acme/widgets": {"pulls": {"since": "2026-10-27T10:05:00Z", "listed_at": "2026-10-27T10:20:00Z", "at": ["12"]}, - "prs": {"12": ["0123456789ab", false, false]}}}} + "prs": {"12": ["0123456789ab", false, false]}, + "branches": {"main": "5c4d3e2f1a0b99887766554433221100ffeeddcc"}}}} An item is new when it was created (published) after the last listing: later than its cursor, or in the cursor's own second and not listed then, since @@ -54,6 +66,9 @@ listed longest ago is forgotten first. A listing without a cursor is the baseline: its cursor is set and nothing is reported, so switching the source on, or adding a repository or a type, does not fill the inbox with history. +A branch without a head in the cursor takes its baseline the same way: its +head is stored and nothing is reported, and from then on a head that moved is +reported however long after. Nothing older than a day is backfilled: a listing last read more than a day ago (:data:`STALE_AFTER`; a daily schedule, a long outage, the source switched off for longer) is read as of a day and an hour ago (:data:`STALE_GRACE`, for @@ -72,11 +87,13 @@ import contextlib import json import logging +import unicodedata from collections.abc import Callable from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING, Any +from nerve.config import github_repos_branch_ok from nerve.sources.base import Source from nerve.sources.filters import FieldRule, InboxFilter, matches_any from nerve.sources.models import FetchResult, SourceRecord @@ -125,8 +142,32 @@ } _DEFAULT_TYPES = ("pull_request", "issue") +# The type that reports the new commits of a repository's branches, and the +# listing of one branch: its newest commits, the head first. The listing is +# asked for the branch's ref, so that GitHub never reads a tag, a commit or +# the head of a pull request of the same name in its place. +_COMMIT_TYPE = "commit" +_COMMITS_ENDPOINT = "repos/{repo}/commits?sha=refs/heads/{branch}&per_page=100" +# A commit record lists at most this many commits, each as the commit and +# the first line of its message, cut to this many characters, the entry to +# this many bytes: the bounds of the record that the gateway builds. +MAX_RECORD_COMMITS = 50 +_MAX_COMMIT_SUBJECT_CHARS = 120 +_MAX_COMMIT_ENTRY_BYTES = 256 +# The characters of a commit that a record's id keeps of each of its two +# heads, and its summary of the head when the record counts no commit. +_SHORT_COMMIT_CHARS = 12 +# The characters that a commit's line shows as a space, besides the control +# characters: the line and the paragraph separator, and the bidirectional +# controls, which change the order in which a reader sees the text after them. +_SPACED_CHARS = frozenset("\u2028\u2029\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069") +# Ends the commits of a record that does not list every new one. +_TRUNCATED_COMMITS = "[... not every new commit is listed]" + # The record's subject_type for each type. -SUBJECT_TYPES = {"pull_request": "PullRequest", "issue": "Issue", "release": "Release"} +SUBJECT_TYPES = { + "pull_request": "PullRequest", "issue": "Issue", "release": "Release", "commit": "Commit", +} @dataclass @@ -198,13 +239,15 @@ def as_json(self) -> dict[str, Any]: class _RepoState: """What the cursor remembers of one repository. - Its listings by name (``pulls``, ``issues``, ``releases``), and in ``prs`` + Its listings by name (``pulls``, ``issues``, ``releases``), in ``prs`` the pull requests it follows: number → ``[head commit, draft, held]``, in - the order in which they were last listed. + the order in which they were last listed, and in ``branches`` the head + commit of each branch whose commits it follows. """ listings: dict[str, _Listing] = field(default_factory=dict) prs: dict[str, list[Any]] = field(default_factory=dict) + branches: dict[str, str] = field(default_factory=dict) def follow(self, number: str, head_sha: str, *, draft: bool, held: bool) -> None: """Remember a pull request, as the one listed last.""" @@ -215,6 +258,8 @@ def as_json(self) -> dict[str, Any]: out: dict[str, Any] = {name: listing.as_json() for name, listing in self.listings.items()} if self.prs: out["prs"] = self.prs + if self.branches: + out["branches"] = self.branches return out @@ -279,6 +324,10 @@ def _read_cursor(cursor: str | None) -> tuple[dict[str, _RepoState], str | None] and isinstance(entry[2], bool) ): state.prs[str(number)] = entry + branches = raw.get("branches") + for branch, head in (branches.items() if isinstance(branches, dict) else ()): + if isinstance(head, str) and head: + state.branches[str(branch)] = head states[repo] = state return states, None @@ -588,6 +637,100 @@ def release_record(repo: str, item: dict[str, Any]) -> SourceRecord: ) +def _commit_entry(item: dict[str, Any]) -> str: + """A commit as a record lists it: the commit, a space, and the first line + of its message. + + The line has a space in the place of each control character and of each + of :data:`_SPACED_CHARS`, no spaces around it, and at most + :data:`_MAX_COMMIT_SUBJECT_CHARS` characters; the entry is cut to + :data:`_MAX_COMMIT_ENTRY_BYTES` bytes and ends in no space, so a commit + without a message is the commit alone. + """ + commit = item.get("commit") + message = commit.get("message") if isinstance(commit, dict) else None + subject = (message if isinstance(message, str) else "").split("\n", 1)[0] + subject = "".join( + " " if character in _SPACED_CHARS or unicodedata.category(character) == "Cc" else character + for character in subject + ).strip(" ")[:_MAX_COMMIT_SUBJECT_CHARS] + entry = f"{item.get('sha')} {subject}".encode(errors="replace")[:_MAX_COMMIT_ENTRY_BYTES] + return entry.decode(errors="ignore").rstrip(" ") + + +def commits_record( + repo: str, branch: str, before: str, items: list[dict[str, Any]], now: datetime, +) -> SourceRecord: + """The record of the new commits of *branch*, whose head was *before* at + the last listing. + + *items* is the branch's listing, its head first, in GitHub's order: by + commit date, not by ancestry. The record counts the commits that the + listing shows above *before* and lists the newest + :data:`MAX_RECORD_COMMITS` of them; across a merge they are not always + the exact set of the new commits, and the record's URL compares the two + heads. When the listing does not show *before* (100 or more new commits, + or a rewritten branch), or *before* is empty, the record lists the + branch's newest commits and counts none. ``truncated`` says that, or that + the record lists fewer commits than it counts. The record's id names both + heads, so a branch that returns to an earlier head has a record of its + own. The record's time is *now*: the listing does not say when a commit + reached the branch. + """ + head = str(items[0].get("sha")) + shas = [item.get("sha") for item in items] + found = shas.index(before) if before and before in shas else -1 + fresh, count = (items[:found], str(found)) if found >= 0 else (items, "") + truncated = not count or len(fresh) > MAX_RECORD_COMMITS + commits = [_commit_entry(item) for item in fresh[:MAX_RECORD_COMMITS] if item.get("sha")] + url = ( + f"https://github.com/{repo}/compare/{before}...{head}" if before + else f"https://github.com/{repo}/commits/{branch}" + ) + if not count: + summary = f"{branch} moved to {head[:_SHORT_COMMIT_CHARS]}" + else: + summary = f"{count} new commit{'' if count == '1' else 's'} on {branch}" + content = [ + f"Repository: {repo}", + f"Type: {SUBJECT_TYPES[_COMMIT_TYPE]}", + "Event: pushed", + f"Branch: {branch}", + f"Commits: {count}" if count else None, + f"Head: {head}", + f"Before: {before}" if before else None, + f"URL: {url}", + "\n--- Commits ---\n- " + "\n- ".join(commits), + _TRUNCATED_COMMITS if truncated else None, + ] + return SourceRecord( + id=( + f"{repo}@{branch}:pushed:" + f"{before[:_SHORT_COMMIT_CHARS]}..{head[:_SHORT_COMMIT_CHARS]}" + ), + source=SOURCE_NAME, + record_type=RECORD_TYPE, + summary=f"[{repo}] {summary}", + content="\n".join(line for line in content if line), + timestamp=_stamp(now), + # The keys, values and order that the gateway sends for the commits of + # a branch, as the hosted source reads them: a list, and a flag. + metadata={ + "repo_name": repo, + "event": "pushed", + "subject_type": SUBJECT_TYPES[_COMMIT_TYPE], + "branch": branch, + "head_sha": head, + "before_sha": before, + "commit_count": count, + "commits": commits, + "truncated": truncated, + "subject_url": url, + "repo_url": f"https://github.com/{repo}", + }, + ) + + def _common_lines(item: dict[str, Any]) -> list[str | None]: """The labels, the times and the URL of a pull request or an issue.""" labels = [ @@ -611,8 +754,8 @@ class GitHubReposSource(Source): """Reports what is new in a configured set of repositories, with the gh CLI. *config* holds the ``sync.github_repos`` settings: ``repos``, ``types``, - ``include_bots``, ``include_drafts``, ``updates`` and ``deny_authors``; - a setting left out takes its default. + ``branches``, ``include_bots``, ``include_drafts``, ``updates`` and + ``deny_authors``; a setting left out takes its default. """ source_name = SOURCE_NAME @@ -631,6 +774,14 @@ def __init__( elif isinstance(chosen, str): chosen = [chosen] self._types = tuple(kind for kind in _LISTINGS if kind in chosen) + # The commits of branches: of those that ``branches`` names for a + # repository (names ignore case), else of its default branch. + self._commits = _COMMIT_TYPE in chosen + branches = self._config.get("branches") + self._branches: dict[str, list[str]] = { + str(repo).strip().lower(): [str(branch) for branch in names or ()] + for repo, names in (branches.items() if isinstance(branches, dict) else ()) + } self._include_bots = bool(self._config.get("include_bots", False)) self._include_drafts = bool(self._config.get("include_drafts", True)) self._updates = bool(self._config.get("updates", False)) @@ -645,7 +796,7 @@ async def fetch(self, cursor: str | None, limit: int = 100) -> FetchResult: not cap this source. A listing that fails is left for the next run with its cursor; when every listing fails, the run fails. """ - if not self._repos or not self._types: + if not self._repos or not (self._types or self._commits): logger.warning("github_repos: no repos or no types configured — nothing to fetch") return FetchResult(records=[], next_cursor=cursor) @@ -654,12 +805,19 @@ async def fetch(self, cursor: str | None, limit: int = 100) -> FetchResult: listings = [ (repo, kind, *_LISTINGS[kind]) for repo in self._repos for kind in self._types ] + # The branches to list: None stands for a repository's default branch. + watched = [ + (repo, branch) for repo in self._repos + for branch in (self._branches.get(repo.lower()) or [None]) + ] if self._commits else [] sem = asyncio.Semaphore(_MAX_CONCURRENT_FETCHES) results = await asyncio.gather( *(self._list(endpoint.format(repo=repo), sem) for repo, _, _, endpoint in listings), + *(self._branch(repo, branch, sem) for repo, branch in watched), return_exceptions=True, ) listed = {(repo, kind): result for (repo, kind, _, _), result in zip(listings, results)} + branches = list(zip(watched, results[len(listings):])) records: list[SourceRecord] = [] failures: list[str] = [] @@ -700,18 +858,29 @@ async def fetch(self, cursor: str | None, limit: int = 100) -> FetchResult: records += self._issues(repo, result, previous, state, now) else: records += self._releases(repo, result, previous, state, now) + for (watching, branch), result in branches: + if watching != repo: + continue + if isinstance(result, BaseException): + failures.append(f"{repo} commits of {branch or 'the default branch'}: {result}") + # A branch that could not be listed keeps its head; without + # the default branch's name, so does every branch. + kept = old.branches if branch is None else {branch: old.branches.get(branch)} + state.branches.update({name: head for name, head in kept.items() if head}) + elif result is not None: + records += self._commits_of(repo, *result, old, state, now) while len(state.prs) > MAX_FINGERPRINTS: state.prs.pop(next(iter(state.prs))) next_states[repo] = state if failures: - if len(failures) == len(listings): + if len(failures) == len(listings) + len(branches): raise RuntimeError( f"every GitHub listing failed ({len(failures)}), e.g. {failures[0]}" ) logger.warning( "github_repos: %d of %d listings failed and keep their cursor, e.g. %s", - len(failures), len(listings), failures[0], + len(failures), len(listings) + len(branches), failures[0], ) # Oldest first, for a natural reading order in the inbox. latest = datetime.max.replace(tzinfo=UTC) @@ -843,6 +1012,56 @@ def _releases( and not self._denied(_author(item.get("author"))[0]) ] + def _commits_of( + self, repo: str, branch: str, items: list[dict[str, Any]], old: _RepoState, + state: _RepoState, now: datetime, + ) -> list[SourceRecord]: + """The record of a branch whose head moved since the last listing. + + The first listing of a branch only stores its head, and a listing + without a commit keeps the head that the cursor had. + """ + before = old.branches.get(branch, "") + if not items: + if before: + state.branches[branch] = before + return [] + head = items[0]["sha"] + state.branches[branch] = head + if not before or before == head: + return [] + return [commits_record(repo, branch, before, items, now)] + + async def _branch( + self, repo: str, branch: str | None, sem: asyncio.Semaphore, + ) -> tuple[str, list[dict[str, Any]]] | None: + """The name of a branch of *repo* and its newest commits, the head first. + + *branch* ``None`` is the repository's default branch, as the + repository names it now. ``None`` for a default branch that the source + cannot follow (:func:`nerve.config.github_repos_branch_ok`). Raises + when the repository or the listing cannot be read. + """ + if branch is None: + async with sem: + found = await self._gh_api_get(f"repos/{repo}") + branch = found.get("default_branch") if isinstance(found, dict) else None + if not isinstance(branch, str) or not branch: + raise TypeError(f"gh api repos/{repo} named no default branch") + if not github_repos_branch_ok(repo, branch): + logger.warning( + "github_repos: the default branch of %s has a name that the source cannot " + "follow; its commits are not reported", repo, + ) + return None + endpoint = _COMMITS_ENDPOINT.format(repo=repo, branch=branch) + items = await self._list(endpoint, sem) + if not all(isinstance(item, dict) for item in items) or ( + items and not (isinstance(items[0].get("sha"), str) and items[0]["sha"]) + ): + raise TypeError(f"gh api {endpoint} did not return commits") + return branch, items + async def _list(self, endpoint: str, sem: asyncio.Semaphore) -> list[Any]: """One listing; raises when it cannot be read.""" async with sem: diff --git a/nerve/sources/registry.py b/nerve/sources/registry.py index 8f4d9c540..fd404f66c 100644 --- a/nerve/sources/registry.py +++ b/nerve/sources/registry.py @@ -237,7 +237,8 @@ def build_source_runners( )) logger.info("Registered source: github_events (batch=%d, repos=%s)", gh_events.batch_size, gh_events.repos or "all") - # GitHub Repos (repositories the agent follows: new PRs, issues, releases). + # GitHub Repos (repositories the agent follows: new PRs, issues, releases, + # and the new commits of their branches). # GitHub is hosted as a whole: with sync.github.mode hosted the gateway # polls these repositories too, and the runner drains what it delivered. gh_repos = config.sync.github_repos @@ -260,6 +261,7 @@ def build_source_runners( source = GitHubReposSource(config={ "repos": gh_repos.repos, "types": gh_repos.types, + "branches": gh_repos.branches, "include_bots": gh_repos.include_bots, "include_drafts": gh_repos.include_drafts, "updates": gh_repos.updates, @@ -276,12 +278,12 @@ def build_source_runners( inbox_filter=github_repos_inbox_filter(gh_repos), )) logger.info( - "Registered source: %s (batch=%d, repos=%s, types=%s, include_bots=%s, " - "include_drafts=%s, updates=%s, deny_authors=%s)", + "Registered source: %s (batch=%d, repos=%s, types=%s, branches=%s, " + "include_bots=%s, include_drafts=%s, updates=%s, deny_authors=%s)", "github_repos (hosted)" if repos_hosted else "github_repos", gh_repos.batch_size, gh_repos.repos or "none", gh_repos.types, - gh_repos.include_bots, gh_repos.include_drafts, gh_repos.updates, - gh_repos.deny_authors or [], + gh_repos.branches or "default", gh_repos.include_bots, gh_repos.include_drafts, + gh_repos.updates, gh_repos.deny_authors or [], ) # Channel source drains. Not a poll: the channel transport already diff --git a/tests/fixtures/channel_contract/github_repo_commits.json b/tests/fixtures/channel_contract/github_repo_commits.json new file mode 100644 index 000000000..232aac341 --- /dev/null +++ b/tests/fixtures/channel_contract/github_repo_commits.json @@ -0,0 +1,84 @@ +{ + "event_id": "github_repos:acme/widgets@main:pushed:89abcdef0123..5c4d3e2f1a0b", + "message_revision_id": "acme/widgets@main:pushed:89abcdef0123..5c4d3e2f1a0b", + "tenant_id": "6f1d3a2c-0b4e-4f7a-9c1d-2e5b8a3f7c04", + "agent_id": "b28c5e91-7d4a-4c3b-8f61-0a9e2d4b6c17", + "connection_id": "7b9e8d6c-5a0f-4e24-93a4-6c2f1a5b9e87", + "provider": "github_repos", + "kind": "source_record", + "conversation": { + "id": "acme/widgets", + "kind": "repository" + }, + "admission": { + "purpose": "observe", + "observe": { + "provenance": { + "provider": "github_repos", + "issuer": "", + "installation_id": "" + } + } + }, + "delivery": { + "inbox_id": "1022", + "received_at": "2026-09-16T10:35:02Z" + }, + "occurred_at": "2026-09-16T10:35:00Z", + "record": { + "id": "acme/widgets@main:pushed:89abcdef0123..5c4d3e2f1a0b", + "record_type": "github_repo_activity", + "summary": "[acme/widgets] 2 new commits on main", + "content": "Repository: acme/widgets\nType: Commit\nEvent: pushed\nBranch: main\nCommits: 2\nHead: 5c4d3e2f1a0b99887766554433221100ffeeddcc\nBefore: 89abcdef0123456789abcdef0123456789abcdef\nURL: https://github.com/acme/widgets/compare/89abcdef0123456789abcdef0123456789abcdef...5c4d3e2f1a0b99887766554433221100ffeeddcc\n\n--- Commits ---\n- 5c4d3e2f1a0b99887766554433221100ffeeddcc Cache rendered widgets\n- 1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d Add the widget cache interface", + "timestamp": "2026-09-16T10:35:00Z", + "metadata": [ + { + "key": "repo_name", + "value": "acme/widgets" + }, + { + "key": "event", + "value": "pushed" + }, + { + "key": "subject_type", + "value": "Commit" + }, + { + "key": "branch", + "value": "main" + }, + { + "key": "head_sha", + "value": "5c4d3e2f1a0b99887766554433221100ffeeddcc" + }, + { + "key": "before_sha", + "value": "89abcdef0123456789abcdef0123456789abcdef" + }, + { + "key": "commit_count", + "value": "2" + }, + { + "key": "commits", + "values": [ + "5c4d3e2f1a0b99887766554433221100ffeeddcc Cache rendered widgets", + "1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d Add the widget cache interface" + ] + }, + { + "key": "truncated", + "value": "false" + }, + { + "key": "subject_url", + "value": "https://github.com/acme/widgets/compare/89abcdef0123456789abcdef0123456789abcdef...5c4d3e2f1a0b99887766554433221100ffeeddcc" + }, + { + "key": "repo_url", + "value": "https://github.com/acme/widgets" + } + ] + } +} diff --git a/tests/test_channel_contract.py b/tests/test_channel_contract.py index 230f8fa46..6adbf1265 100644 --- a/tests/test_channel_contract.py +++ b/tests/test_channel_contract.py @@ -877,7 +877,20 @@ def test_a_watch_the_gateway_takes_is_valid(self): for n in range(50) )), )).validate() - repo_watch(watched("a/b", types=("pull_request", "issue", "release"))).validate() + repo_watch(watched("a/b", types=("pull_request", "issue", "release", "commit"))).validate() + repo_watch(watched(types=("commit",), branches=("main", "release/1.2", "b" * 121))).validate() + repo_watch(watched(types=("commit",), branches=tuple(f"b{n}" for n in range(8)))).validate() + # A branch may have the name of a tag, and refs in its name. + repo_watch(watched(types=("commit",), branches=("v1.2.0", "refs", "refsx/main", "feature/refs/heads"))).validate() + # The repository's name and a branch's: 194 bytes together. + repo_watch(watched("o" * 39 + "/" + "r" * 100, types=("commit",), branches=("b" * 54,))).validate() + + def test_branches_are_sent_only_when_a_repository_names_one(self): + """A repository without branches is sent as before the member existed.""" + assert '"branches"' not in dumps(repo_watch(watched(types=("commit",)))) + assert dumps(repo_watch(watched(types=("commit",), branches=("main", "next")))).endswith( + '"deny_authors":[],"branches":["main","next"]}]}]}' + ) @pytest.mark.parametrize(("subscriptions", "expected"), [ (Subscriptions(version="1", sources=(SourceSubscription(provider="github_repos"),)), "malformed_frame"), @@ -896,6 +909,20 @@ def test_a_watch_the_gateway_takes_is_valid(self): (repo_watch(watched(deny_authors=("x" * 257,))), "malformed_frame"), (repo_watch(watched(deny_authors=("",))), "malformed_frame"), (repo_watch(watched(deny_authors=("tab\there",))), "malformed_frame"), + (repo_watch(watched(types=("commit",), branches=tuple(f"b{n}" for n in range(9)))), "limit_exceeded"), + (repo_watch(watched(types=("commit",), branches=("main", "main"))), "malformed_frame"), + (repo_watch(watched(types=("commit",), branches=("",))), "malformed_frame"), + (repo_watch(watched(types=("commit",), branches=("-main",))), "malformed_frame"), + (repo_watch(watched(types=("commit",), branches=("a..b",))), "malformed_frame"), + (repo_watch(watched(types=("commit",), branches=("main.lock",))), "malformed_frame"), + # A branch is named without its ref prefix, and no other ref is one. + (repo_watch(watched(types=("commit",), branches=("refs/heads/main",))), "malformed_frame"), + (repo_watch(watched(types=("commit",), branches=("main", "refs/heads/main"))), "malformed_frame"), + (repo_watch(watched(types=("commit",), branches=("refs/tags/v1.2.0",))), "malformed_frame"), + (repo_watch(watched(types=("commit",), branches=("refs/pull/1/head",))), "malformed_frame"), + (repo_watch(watched(types=("commit",), branches=("b" * 122,))), "malformed_frame"), + (repo_watch(watched("o" * 39 + "/" + "r" * 100, types=("commit",), branches=("b" * 55,))), "malformed_frame"), + (repo_watch(watched(branches=("my branch",))), "malformed_frame"), (repo_watch(filters=SourceFilters(deny_actors=("alice",))), "malformed_frame"), (repo_watch(pr_watch=True), "malformed_frame"), (repo_watch(inbox="all"), "malformed_frame"), diff --git a/tests/test_github_repos_source.py b/tests/test_github_repos_source.py index e1a508a15..0bdde5c5c 100644 --- a/tests/test_github_repos_source.py +++ b/tests/test_github_repos_source.py @@ -1,7 +1,8 @@ """The GitHub Repos source in poll mode: what is new in repositories the agent follows. A fake ``gh api`` serves the pulls, issues and releases listings of a few -repositories, newest change first as GitHub does; each test lists once for the +repositories, and the commits of their branches, newest change first as GitHub +does; each test lists once for the baseline, changes the repositories, and lists again. The records are pinned to the shape the channel gateway builds for the hosted mode (same id, type, summary, content, timestamp and metadata), so that the guardrails, the gates @@ -11,10 +12,12 @@ from __future__ import annotations import copy +import hashlib import json import logging import re from datetime import UTC, datetime, timedelta +from pathlib import Path from typing import Any import pytest @@ -114,20 +117,67 @@ def release( } +def sha(number: int) -> str: + """The commit of a number: 40 characters, as GitHub names a commit, which + differ within the 12 characters that a record's id keeps of a commit.""" + return f"{number:08x}" + "c" * 32 + + +def pushed_id(branch: str, before: int, head: int, repo: str | None = None) -> str: + """The id of the record of a branch that moved from one commit to another.""" + return f"{repo or REPO}@{branch}:pushed:{sha(before)[:12]}..{sha(head)[:12]}" + + +def commit(number: int, message: str | None = None) -> dict[str, Any]: + """A commit as the commits listing of a branch returns it.""" + person = {"name": "Alice Example", "date": at(-5)} + return { + "sha": sha(number), + "commit": { + "message": f"Commit {number}" if message is None else message, + "author": person, "committer": person, + }, + "author": user(), + "html_url": f"https://github.com/{REPO}/commit/{sha(number)}", + } + + +def history(head: int) -> list[dict[str, Any]]: + """The commits of a branch whose head is *head*, down to 1, the head first.""" + return [commit(number) for number in range(head, 0, -1)] + + class FakeGitHub: """``gh api`` over a few repositories' listings; records every endpoint asked for.""" _ENDPOINT = re.compile(r"repos/([^/]+/[^/?]+)/(pulls|issues|releases)\?(.*)") + _COMMITS = re.compile(r"repos/([^/]+/[^/?]+)/commits\?sha=(refs/heads/)?([^&]+)&per_page=100") + _REPOSITORY = re.compile(r"repos/([^/]+/[^/?]+)") def __init__(self) -> None: self.pulls: dict[str, list[dict]] = {} self.issues: dict[str, list[dict]] = {} self.releases: dict[str, list[dict]] = {} + # The commits of each branch, the head first, by (repository, branch), + # and the default branch of each repository. GitHub lists a branch + # for its ref, refs/heads/; for a bare name it also lists a + # tag or a commit of that name, which other_refs holds. + self.commits: dict[tuple[str, str], list[dict]] = {} + self.other_refs: dict[tuple[str, str], list[dict]] = {} + self.default_branch: dict[str, str] = {} self.calls: list[str] = [] self.failing: set[str] = set() async def gh_api_get(self, endpoint: str, timeout: float = 30) -> Any: self.calls.append(endpoint) + if (commits := self._COMMITS.fullmatch(endpoint)) is not None: + repo, ref, name = commits.groups() + listed = self.commits if ref else {**self.other_refs, **self.commits} + if (repo, name) not in listed: + raise RuntimeError("gh: Not Found (HTTP 404)") + return copy.deepcopy(listed[(repo, name)][:100]) + if (repository := self._REPOSITORY.fullmatch(endpoint)) is not None: + return {"full_name": repository[1], "default_branch": self.default_branch[repository[1]]} repo, listing, _ = self._ENDPOINT.fullmatch(endpoint).groups() if f"{repo} {listing}" in self.failing: raise RuntimeError("gh: Not Found (HTTP 404)") @@ -662,9 +712,348 @@ def _source_record_event(record: SourceRecord): id=record.id, record_type=record.record_type, summary=record.summary, content=record.content, timestamp=datetime.fromisoformat(record.timestamp), - metadata=tuple(MetadataEntry(key=key, value=value) for key, value in record.metadata.items()), + metadata=tuple(_metadata_entry(key, value) for key, value in record.metadata.items()), + ), + ) + + +def _metadata_entry(key: str, value: Any) -> MetadataEntry: + """A metadata member as the gateway sends it: a list in ``values``, a flag as text.""" + if isinstance(value, list): + return MetadataEntry(key=key, values=tuple(value)) + if isinstance(value, bool): + return MetadataEntry(key=key, value="true" if value else "false") + return MetadataEntry(key=key, value=value) + + +# ---------------------------------------------------------------------- # +# Commits of a branch # +# ---------------------------------------------------------------------- # + +MAIN = (REPO, "main") + + +def commits_source(fake: FakeGitHub, **settings: Any) -> GitHubReposSource: + """A source that follows the commits of main of the repository, unless *settings* say otherwise.""" + settings.setdefault("types", ["commit"]) + settings.setdefault("branches", {REPO: ["main"]}) + return source(fake, **settings) + + +@pytest.mark.asyncio +async def test_the_first_listing_of_a_branch_only_stores_its_head(): + fake = FakeGitHub() + fake.commits[MAIN] = history(3) + src = commits_source(fake) + + first = await src.fetch(None) + + assert first.records == [] + assert cursor_of(first) == {"v": 1, "repos": {REPO: {"branches": {"main": sha(3)}}}} + assert fake.calls == [f"repos/{REPO}/commits?sha=refs/heads/main&per_page=100"] + again = await src.fetch(first.next_cursor) + assert (again.records, again.next_cursor) == ([], first.next_cursor) + + +@pytest.mark.asyncio +async def test_a_head_that_moved_gives_one_record_as_the_gateway_builds_it(): + """One record for the branch, whatever the number of commits, with the + time of the listing; the same head gives no second record.""" + fake = FakeGitHub() + fake.commits[MAIN] = history(2) + src = commits_source(fake) + cursor = await baseline(src) + fake.commits[MAIN] = history(5) + + result = await src.fetch(cursor) + + compare = f"https://github.com/{REPO}/compare/{sha(2)}...{sha(5)}" + assert result.records == [SourceRecord( + id=f"{REPO}@main:pushed:00000002cccc..00000005cccc", + source="github_repos", + record_type="github_repo_activity", + summary=f"[{REPO}] 3 new commits on main", + content=( + f"Repository: {REPO}\nType: Commit\nEvent: pushed\nBranch: main\nCommits: 3\n" + f"Head: {sha(5)}\nBefore: {sha(2)}\nURL: {compare}\n\n--- Commits ---\n" + f"- {sha(5)} Commit 5\n- {sha(4)} Commit 4\n- {sha(3)} Commit 3" ), + timestamp=STAMP, + metadata={ + "repo_name": REPO, "event": "pushed", "subject_type": "Commit", "branch": "main", + "head_sha": sha(5), "before_sha": sha(2), "commit_count": "3", + "commits": [f"{sha(5)} Commit 5", f"{sha(4)} Commit 4", f"{sha(3)} Commit 3"], + "truncated": False, "subject_url": compare, "repo_url": f"https://github.com/{REPO}", + }, + )] + assert list(result.records[0].metadata) == [ + "repo_name", "event", "subject_type", "branch", "head_sha", "before_sha", "commit_count", + "commits", "truncated", "subject_url", "repo_url", + ] + assert cursor_of(result)["repos"][REPO]["branches"] == {"main": sha(5)} + assert (await src.fetch(result.next_cursor)).records == [] + fake.commits[MAIN] = history(6) + (one,) = (await src.fetch(result.next_cursor)).records + assert (one.summary, one.metadata["before_sha"]) == (f"[{REPO}] 1 new commit on main", sha(5)) + assert one.id == pushed_id("main", 5, 6) + + +# A copy of the channel contract's sample of the new commits of a branch. It +# must stay byte for byte the same as the contract's +# ``testdata/events/github_repo_commits.json``. +COMMITS_SAMPLE = Path(__file__).parent / "fixtures" / "channel_contract" / "github_repo_commits.json" +COMMITS_SAMPLE_SHA256 = "84bb74bd0ad1d562466b85b14c3372e55e75586a8fa834f1d186d10911e577ea" + + +@pytest.mark.asyncio +async def test_the_record_is_the_one_of_the_contract_sample(): + """The gateway writes the contract's sample for two commits on main. This + source builds the same record from the same listing, and the hosted source + reads the sample into that record.""" + from nerve.channels.hosted.contract.model import Event + from nerve.channels.hosted.contract.wire import decode_record + + assert hashlib.sha256(COMMITS_SAMPLE.read_bytes()).hexdigest() == COMMITS_SAMPLE_SHA256 + event = decode_record(Event, json.loads(COMMITS_SAMPLE.read_text(encoding="utf-8"))) + earlier = {**commit(0, "Earlier work"), "sha": "89abcdef0123456789abcdef0123456789abcdef"} + fake = FakeGitHub() + fake.commits[MAIN] = [earlier] + src = commits_source(fake, clock=lambda: datetime(2026, 9, 16, 10, 35, 0, 987_000, tzinfo=UTC)) + cursor = await baseline(src) + fake.commits[MAIN] = [ + {**commit(0, "Cache rendered widgets\n\nRenders each widget once and keeps it."), + "sha": "5c4d3e2f1a0b99887766554433221100ffeeddcc"}, + {**commit(0, "Add the widget cache interface"), "sha": "1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d"}, + earlier, + ] + + (record,) = (await src.fetch(cursor)).records + + assert record == record_from_buffer(buffered_record(event), source="github_repos") + assert record == record_from_buffer(buffered_record(_source_record_event(record)), source="github_repos") + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("before", "head", "count", "listed", "truncated", "summary"), [ + (history(10), 60, "50", 50, False, "50 new commits on main"), + (history(10), 61, "51", 50, True, "51 new commits on main"), + (history(1), 100, "99", 50, True, "99 new commits on main"), + # As many commits as the listing's page, or more: it does not show the + # earlier head. + (history(1), 101, "", 50, True, f"main moved to {sha(101)[:12]}"), + (history(1), 140, "", 50, True, f"main moved to {sha(140)[:12]}"), + # A rewritten branch does not hold the earlier head any more. + ([commit(900)], 3, "", 3, True, f"main moved to {sha(3)[:12]}"), +]) +async def test_a_record_says_when_it_does_not_list_every_new_commit( + before, head, count, listed, truncated, summary, +): + fake = FakeGitHub() + fake.commits[MAIN] = before + src = commits_source(fake) + cursor = await baseline(src) + fake.commits[MAIN] = history(head) + + (record,) = (await src.fetch(cursor)).records + + metadata = record.metadata + assert (metadata["commit_count"], len(metadata["commits"]), metadata["truncated"]) == (count, listed, truncated) + assert (metadata["commits"][0], metadata["before_sha"]) == (f"{sha(head)} Commit {head}", before[0]["sha"]) + assert record.summary == f"[{REPO}] {summary}" + assert metadata["subject_url"] == f"https://github.com/{REPO}/compare/{before[0]['sha']}...{sha(head)}" + assert record.content.endswith("\n[... not every new commit is listed]") is truncated + assert ("\nCommits: " in record.content) is bool(count) + assert record.content.count("\n- ") == listed + + +@pytest.mark.asyncio +async def test_each_branch_is_reported_and_takes_its_own_baseline(): + """Two branches that moved give two records in one run. A branch named + later starts from its head, and one no longer named is forgotten.""" + fake = FakeGitHub() + fake.commits[MAIN], fake.commits[(REPO, "release/1.2")] = history(4), history(2) + src = commits_source(fake, branches={"Acme/Widgets": ["main", "release/1.2"]}) + cursor = await baseline(src) + assert fake.calls == [ + f"repos/{REPO}/commits?sha=refs/heads/{branch}&per_page=100" for branch in ("main", "release/1.2") + ] + fake.commits[MAIN], fake.commits[(REPO, "release/1.2")] = history(6), history(3) + + result = await src.fetch(cursor) + + assert [record.id for record in result.records] == [ + pushed_id("main", 4, 6), pushed_id("release/1.2", 2, 3), + ] + fake.commits[(REPO, "next")] = history(9) + fake.commits[(REPO, "release/1.2")] = history(5) + later = await commits_source(fake, branches={REPO: ["release/1.2", "next"]}).fetch(result.next_cursor) + assert [record.id for record in later.records] == [pushed_id("release/1.2", 3, 5)] + assert cursor_of(later)["repos"][REPO]["branches"] == {"release/1.2": sha(5), "next": sha(9)} + + +@pytest.mark.asyncio +async def test_without_branches_the_default_branch_is_followed(caplog): + """The repository names its default branch at every run. When it is + another one, that branch starts from its head and the earlier one is + forgotten; one with a name that the source cannot follow reports nothing.""" + fake = FakeGitHub() + fake.default_branch[REPO] = "trunk" + fake.commits[(REPO, "trunk")] = history(2) + src = commits_source(fake, branches={}) + cursor = await baseline(src) + assert fake.calls == [f"repos/{REPO}", f"repos/{REPO}/commits?sha=refs/heads/trunk&per_page=100"] + fake.commits[(REPO, "trunk")] = history(3) + + result = await src.fetch(cursor) + + assert [record.id for record in result.records] == [pushed_id("trunk", 2, 3)] + fake.default_branch[REPO], fake.commits[MAIN] = "main", history(7) + moved = await src.fetch(result.next_cursor) + assert (moved.records, cursor_of(moved)["repos"][REPO]["branches"]) == ([], {"main": sha(7)}) + fake.default_branch[REPO] = "feature+x" + with caplog.at_level(logging.WARNING, logger="nerve.sources.github_repos"): + unfollowed = await src.fetch(moved.next_cursor) + assert (unfollowed.records, cursor_of(unfollowed)["repos"][REPO]) == ([], {}) + assert "the default branch of acme/widgets has a name that the source cannot follow" in caplog.text + + +@pytest.mark.asyncio +async def test_a_branch_that_cannot_be_listed_keeps_its_head_and_the_others_report(caplog): + """A branch that GitHub does not find fails its listing alone: its head + stays in the cursor, and its commits report once it is back.""" + fake = FakeGitHub() + fake.commits[MAIN], fake.commits[(REPO, "gone")] = history(4), history(2) + src = commits_source(fake, branches={REPO: ["gone", "main"]}) + cursor = await baseline(src) + del fake.commits[(REPO, "gone")] + fake.commits[MAIN] = history(5) + + with caplog.at_level(logging.WARNING, logger="nerve.sources.github_repos"): + result = await src.fetch(cursor) + + assert [record.id for record in result.records] == [pushed_id("main", 4, 5)] + assert cursor_of(result)["repos"][REPO]["branches"] == {"gone": sha(2), "main": sha(5)} + assert "1 of 2 listings failed and keep their cursor, e.g. acme/widgets commits of gone" in caplog.text + fake.commits[(REPO, "gone")] = history(3) + back = await src.fetch(result.next_cursor) + assert [record.id for record in back.records] == [pushed_id("gone", 2, 3)] + del fake.commits[MAIN], fake.commits[(REPO, "gone")] + with pytest.raises(RuntimeError, match=r"every GitHub listing failed \(2\)"): + await src.fetch(back.next_cursor) + + +@pytest.mark.parametrize(("message", "subject"), [ + ("Fix the retry test", " Fix the retry test"), + ("Fix the retry test\n\nIt waited for the wrong event.", " Fix the retry test"), + ("Fix the retry test\r\nMore", " Fix the retry test"), + (" Fix\tthe\x07retry test ", " Fix the retry test"), + # The line and the paragraph separator, and the bidirectional controls. + ("Fix\u2028the\u2029retry test", " Fix the retry test"), + ("Fix the \u202etset yrter\u202c", " Fix the tset yrter"), + ("a\u202ab\u202bc\u202cd\u202de\u202ef\u2066g\u2067h\u2068i\u2069j", " a b c d e f g h i j"), + # The characters next to them stay. + ("a\u2027b\u202fc\u2065d\u206ae", " a\u2027b\u202fc\u2065d\u206ae"), + ("", ""), + ("\nBody alone", ""), + (" \nBody", ""), + ("a" * 125, " " + "a" * 120), + ("a" * 119 + " tail", " " + "a" * 119), + # The entry is cut to 256 bytes, at a character. + ("ü" * 125, " " + "ü" * 107), +]) +def test_a_commit_is_listed_with_the_first_line_of_its_message(message, subject): + """The rules of the gateway's record: control characters, the line and + paragraph separators and the bidirectional controls as spaces, no spaces + around the line, 120 characters, and the entry within 256 bytes.""" + assert module._commit_entry(commit(7, message)) == sha(7) + subject + + +@pytest.mark.asyncio +async def test_a_name_that_is_also_a_tag_or_a_commit_is_followed_as_a_branch_alone(): + """The listing is asked for the branch's ref. A name that GitHub would + also read as a tag or as a commit finds no branch: its listing fails, no + head is stored, and nothing is reported, whatever the tag does.""" + fake = FakeGitHub() + fake.commits[MAIN] = history(1) + names = ["v1.2.0", sha(7)] + for name in names: + fake.other_refs[(REPO, name)] = history(3) + src = commits_source(fake, branches={REPO: [*names, "main"]}) + + first = await src.fetch(None) + for name in names: + fake.other_refs[(REPO, name)] = history(4) + second = await src.fetch(first.next_cursor) + + assert (first.records, second.records) == ([], []) + assert cursor_of(second)["repos"][REPO]["branches"] == {"main": sha(1)} + assert all("/commits?sha=refs/heads/" in call for call in fake.calls) + + +@pytest.mark.asyncio +async def test_a_branch_that_returns_to_an_earlier_head_has_a_record_of_its_own(): + """The id names the earlier head and the head. A branch that goes back, + as after a push that was taken back, gives a record with another id, which + counts no commit; only the same move again has the id of an earlier one.""" + fake = FakeGitHub() + src = commits_source(fake) + cursor, records = None, [] + for head in (2, 3, 2, 3): + fake.commits[MAIN] = history(head) + result = await src.fetch(cursor) + cursor = result.next_cursor + records += result.records + + assert [record.id for record in records] == [ + pushed_id("main", 2, 3), pushed_id("main", 3, 2), pushed_id("main", 2, 3), + ] + back = records[1].metadata + assert (back["before_sha"], back["head_sha"], back["commit_count"], back["truncated"]) == ( + sha(3), sha(2), "", True, ) + assert back["subject_url"] == f"https://github.com/{REPO}/compare/{sha(3)}...{sha(2)}" + + +@pytest.mark.asyncio +async def test_the_record_lists_the_commits_that_the_listing_shows_above_the_earlier_head(): + """GitHub lists by commit date, not by ancestry. After a merge, a commit + that the merge brought in and that is older than the earlier head is + listed below it: the record neither lists nor counts it, and its URL + compares the two heads.""" + fake = FakeGitHub() + merge, head, side, base = ( + commit(30, "Merge the side branch"), commit(20, "The head before the merge"), + commit(10, "An older commit of the side branch"), commit(1, "The common base"), + ) + fake.commits[MAIN] = [head, base] + src = commits_source(fake) + cursor = await baseline(src) + fake.commits[MAIN] = [merge, head, side, base] + + (record,) = (await src.fetch(cursor)).records + + assert (record.metadata["commit_count"], record.metadata["truncated"]) == ("1", False) + assert record.metadata["commits"] == [f"{sha(30)} Merge the side branch"] + assert record.metadata["subject_url"] == f"https://github.com/{REPO}/compare/{sha(20)}...{sha(30)}" + + +def test_a_record_without_an_earlier_head_counts_no_commit(): + """The contract's record for an unknown earlier head. The source itself + reports only after it stored a head.""" + record = module.commits_record(REPO, "main", "", history(2), NOW) + + assert (record.metadata["before_sha"], record.metadata["commit_count"], record.metadata["truncated"]) == ("", "", True) + assert record.metadata["subject_url"] == f"https://github.com/{REPO}/commits/main" + assert "Before: " not in record.content + + +def test_the_inbox_filter_keeps_commit_records_only_with_the_commit_type(): + """A commit record has no author: neither deny_authors nor include_bots judges it.""" + record = module.commits_record(REPO, "main", sha(1), history(2), NOW) + + watching = GitHubReposSyncConfig(repos=[REPO], types=["commit"], deny_authors=["*"]) + assert github_repos_inbox_filter(watching).passes(record) + assert not github_repos_inbox_filter(GitHubReposSyncConfig(repos=[REPO])).passes(record) # ---------------------------------------------------------------------- # @@ -1041,8 +1430,9 @@ def test_the_registry_hands_the_settings_to_the_polling_source(): from nerve.sources.registry import build_source_runners config = NerveConfig.from_dict({"sync": {"github_repos": { - "enabled": True, "repos": [REPO], "types": ["release"], "include_bots": True, + "enabled": True, "repos": [REPO], "types": ["release", "commit"], "include_bots": True, "include_drafts": False, "updates": True, "deny_authors": ["noisy-*"], + "branches": {"ACME/Widgets": ["main", "release/1.2"]}, }}}) (runner,) = [r for r in build_source_runners(config, db=None) if r.job_id == "source:github_repos"] @@ -1052,6 +1442,7 @@ def test_the_registry_hands_the_settings_to_the_polling_source(): assert (src._repos, src._types, src._include_bots, src._include_drafts, src._updates, src._deny_authors) == ( [REPO], ("release",), True, False, True, ["noisy-*"], ) + assert (src._commits, src._branches) == (True, {REPO: ["main", "release/1.2"]}) assert [rule.field for rule in runner.inbox_filter.rules if rule.active] == [ "repo_name", "author", "subject_type", ] diff --git a/tests/test_hosted_sources.py b/tests/test_hosted_sources.py index 4d7a6f534..424fc4af8 100644 --- a/tests/test_hosted_sources.py +++ b/tests/test_hosted_sources.py @@ -11,10 +11,11 @@ import asyncio import contextlib import copy +import json import logging from collections.abc import AsyncIterator, Callable from dataclasses import dataclass -from datetime import UTC, datetime, timedelta +from datetime import UTC, date, datetime, timedelta from pathlib import Path from types import SimpleNamespace from typing import Any @@ -49,6 +50,7 @@ github_repos_subscription, github_subscription, hosted_sources, + repo_watch_types, subscriptions_for, ) from nerve.channels.router import ChannelRouter @@ -89,6 +91,10 @@ def hosted_github(**settings: Any) -> GitHubSyncConfig: return GitHubSyncConfig(mode="hosted", **settings) +# A copy of the channel contract's sample of the new commits of a branch +# (tests/test_github_repos_source.py pins its bytes). +COMMITS_SAMPLE = Path(__file__).parent / "fixtures" / "channel_contract" / "github_repo_commits.json" + # The metadata of a github_repos record: every key, empty ones included. REPO_ACTIVITY_METADATA = { "repo_name": "acme/widgets", "number": "12", "event": "opened", "subject_type": "PullRequest", @@ -227,9 +233,9 @@ def test_one_repository_written_as_a_string_is_a_list_of_one(self): @pytest.mark.parametrize(("settings", "message"), [ ({"types": ["pull_request", "commits"]}, - "sync.github_repos.types must be one or more of ('pull_request', 'issue', 'release'), got 'commits'"), + "sync.github_repos.types must be one or more of ('pull_request', 'issue', 'release', 'commit'), got 'commits'"), ({"types": []}, - "sync.github_repos.types must be one or more of ('pull_request', 'issue', 'release'), got none"), + "sync.github_repos.types must be one or more of ('pull_request', 'issue', 'release', 'commit'), got none"), ({"enabled": True, "repos": [f"acme/repo-{n}" for n in range(51)]}, "sync.github_repos.repos must name at most 50 repositories, got 51"), ({"enabled": True, "repos": ["acme"]}, @@ -249,7 +255,7 @@ def test_one_repository_written_as_a_string_is_a_list_of_one(self): "got \"{'acme': 'widgets'}\"" )), ({"types": {"issue": True}}, ( - "sync.github_repos.types must be one or more of ('pull_request', 'issue', 'release'), " + "sync.github_repos.types must be one or more of ('pull_request', 'issue', 'release', 'commit'), " "got \"{'issue': true}\"" )), ]) @@ -259,6 +265,116 @@ def test_a_repository_watch_the_gateway_would_refuse_refuses_to_load(self, setti assert str(refused.value) == message + def test_the_branches_of_the_commit_type_are_read(self): + """A repository's branches go by its name as repos spells it; one + branch may be written as a string, blanks are dropped, and a + repository without a value names none.""" + watch = NerveConfig.from_dict({"sync": {"github_repos": { + "enabled": True, "repos": ["acme/widgets", "Other-Org/tool", "acme/gadgets", "acme/gears"], + "types": ["commit", "issue"], + "branches": { + "ACME/Widgets": [" main ", "release/1.2", "", "1.10"], "other-org/tool": "trunk", + "acme/gadgets": [], "acme/gears": None, + }, + }}}).sync.github_repos + + assert watch.types == ["issue", "commit"] + assert watch.branches == {"acme/widgets": ["main", "release/1.2", "1.10"], "Other-Org/tool": ["trunk"]} + assert (watch.branches_of("Acme/Widgets"), watch.branches_of("acme/gadgets"), watch.branches_of("acme/gears")) == ( + ["main", "release/1.2", "1.10"], [], [], + ) + assert GitHubReposSyncConfig.from_dict({"types": ["commit"], "branches": None}).branches == {} + assert validate_config_keys({"sync": {"github_repos": {"branches": {"acme/widgets": ["main"]}}}}) == [] + + # What the message says about a branch that YAML read as something else. + QUOTE_IT = ( + ": put the name in quotes, since YAML reads an unquoted 1.10 as the number 1.1, and an " + "unquoted no, off or 0 as a value that is no name" + ) + + @pytest.mark.parametrize(("branches", "message"), [ + (["main"], "must map owner/repo names to their branches, got \"['main']\""), + ([], "must map owner/repo names to their branches, got '[]'"), + ("main", "must map owner/repo names to their branches, got 'main'"), + # A name with its ref prefix: main and refs/heads/main are one branch. + ({"acme/widgets": ["refs/heads/main"]}, "got 'refs/heads/main'"), + ({"acme/widgets": ["main", "refs/heads/main"]}, "got 'refs/heads/main'"), + ({"acme/widgets": "refs/tags/v1.2.0"}, "got 'refs/tags/v1.2.0'"), + # What YAML makes of an unquoted 1.10, no, off, 0, an empty item and a date. + ({"acme/widgets": [1.1]}, "of 'acme/widgets' must name each branch as a string, got 1.1" + QUOTE_IT), + ({"acme/widgets": ["main", False]}, "of 'acme/widgets' must name each branch as a string, got False" + QUOTE_IT), + ({"acme/widgets": False}, "of 'acme/widgets' must name each branch as a string, got False" + QUOTE_IT), + ({"acme/widgets": [0]}, "of 'acme/widgets' must name each branch as a string, got 0" + QUOTE_IT), + ({"acme/widgets": ["main", None]}, "of 'acme/widgets' must name each branch as a string, got None" + QUOTE_IT), + ({"acme/widgets": [date(2026, 1, 2)]}, "got datetime.date(2026, 1, 2)" + QUOTE_IT), + ({"acme/widgets": [["main"]]}, "got ['main']" + QUOTE_IT), + ({"acme/other": ["main"]}, "names 'acme/other', which sync.github_repos.repos does not list"), + ({"acme/widgets": ["main"], "ACME/Widgets": ["next"]}, "names 'acme/widgets' twice"), + ({"acme/widgets": ["main", "main"]}, "of 'acme/widgets' name a branch twice"), + ({"acme/widgets": [f"b{n}" for n in range(9)]}, "of 'acme/widgets' must name at most 8 branches, got 9"), + ({"acme/widgets": ["-main"]}, "got '-main'"), + ({"acme/widgets": ["my branch"]}, "got 'my branch'"), + ({"acme/widgets": ["a..b"]}, "got 'a..b'"), + ({"acme/widgets": ["main.lock"]}, "got 'main.lock'"), + ({"acme/widgets": ["b" * 122]}, f"got '{'b' * 122}'"), + ({"acme/widgets": ["b" * 121]}, None), + ({"acme/widgets": [f"b{n}" for n in range(8)]}, None), + ({"acme/widgets": ["refs", "refsx/main", "feature/refs/heads", "v1.2.0", "1.10", "no", "0"]}, None), + ]) + def test_branches_the_gateway_would_refuse_refuse_to_load(self, branches, message, caplog): + """While the watch is on. While it is off they are left out with a warning.""" + settings = {"repos": ["acme/widgets"], "types": ["commit"], "branches": branches} + if message is None: + assert GitHubReposSyncConfig.from_dict({"enabled": True, **settings}).branches == branches + return + + with pytest.raises(ValueError) as refused: + GitHubReposSyncConfig.from_dict({"enabled": True, **settings}) + + assert str(refused.value).startswith("sync.github_repos.branches ") + assert str(refused.value).endswith(message) + with caplog.at_level(logging.WARNING, logger="nerve.config"): + assert GitHubReposSyncConfig.from_dict(settings).branches in ({}, {"acme/widgets": ["main"]}) + assert "its branches would refuse to load once it is switched on" in caplog.text + + @pytest.mark.parametrize("branches", [ + {"acme/widgets": ["main"]}, + # What the commit type would refuse. + ["main"], {"acme/other": ["main"]}, {"acme/widgets": ["refs/heads/main", 1.1, "a..b"]}, "main", + ]) + @pytest.mark.parametrize("enabled", [True, False]) + def test_branches_are_read_only_with_the_commit_type(self, branches, enabled, caplog): + """Without the commit type the setting is not read: a value that is + left there loads whatever it holds, with one warning, and names no + branch. An empty one says nothing.""" + settings = {"enabled": enabled, "repos": ["acme/widgets"], "types": ["issue", "release"]} + + with caplog.at_level(logging.WARNING, logger="nerve.config"): + watch = GitHubReposSyncConfig.from_dict({**settings, "branches": branches}) + + assert (watch.branches, watch.branches_of("acme/widgets")) == ({}, []) + assert [record.getMessage() for record in caplog.records] == [ + "sync.github_repos.branches is set, and sync.github_repos.types does not name commit: " + "the branches are not read", + ] + caplog.clear() + with caplog.at_level(logging.WARNING, logger="nerve.config"): + for empty in (None, "", {}, []): + assert GitHubReposSyncConfig.from_dict({**settings, "branches": empty}).branches == {} + assert GitHubReposSyncConfig.from_dict(settings).branches == {} + assert caplog.records == [] + + def test_a_repository_and_a_branch_fit_the_id_of_a_commit_record_together(self): + """The gateway's bound: 194 bytes for both names.""" + repo = "o" * 39 + "/" + "r" * 100 + settings = {"enabled": True, "repos": [repo], "types": ["commit"]} + + fits = GitHubReposSyncConfig.from_dict({**settings, "branches": {repo: ["b" * 54]}}) + + assert fits.branches == {repo: ["b" * 54]} + with pytest.raises(ValueError, match="at most 194 bytes together with the repository's name"): + GitHubReposSyncConfig.from_dict({**settings, "branches": {repo: ["b" * 55]}}) + def test_fifty_repositories_load(self): repos = [f"acme/repo-{n}" for n in range(50)] @@ -498,6 +614,119 @@ def frame(**watch: Any) -> str: '"include_drafts":false,"updates":false,"deny_authors":["noisy-*"]}]}]}' ) + def test_the_frame_is_unchanged_unless_the_watch_asks_for_commits(self): + """A gateway that does not know the commit type refuses the type and + the branches member, and closes the stream. So an agent that does not + ask for commits sends the very bytes it sent before, whatever its + branches setting says, and only the commit type adds to the frame.""" + def frame(**watch: Any) -> str: + config = NerveConfig() + config.sync.github = hosted_github(enabled=False) + config.sync.github_repos = GitHubReposSyncConfig( + enabled=True, repos=["acme/widgets", "other-org/tool"], **watch, + ) + subscriptions = subscriptions_for(config, hosted_sources(config)) + subscriptions.validate() + return dumps(subscriptions) + + def repo(name: str, types: str, more: str = "") -> str: + return ( + f'{{"name":"{name}","types":[{types}],"include_bots":false,"include_drafts":true,' + f'"updates":false,"deny_authors":[]{more}}}' + ) + + def sources(*repos: str) -> str: + return ( + '{"version":"1","sources":[{"provider":"github_repos","filters":{},"repos":[' + + ",".join(repos) + "]}]}" + ) + + before = '"pull_request","issue"' + unchanged = sources(repo("acme/widgets", before), repo("other-org/tool", before)) + assert frame() == unchanged + assert frame(branches={"acme/widgets": ["main"]}) == unchanged + assert frame(types=["issue", "commit"], branches={"ACME/Widgets": ["main", "release/1.2"]}) == sources( + repo("acme/widgets", '"issue","commit"', ',"branches":["main","release/1.2"]'), + # Without branches the gateway follows the default branch. + repo("other-org/tool", '"issue","commit"'), + ) + + def test_the_commit_type_and_the_thread_item_entry_do_not_touch_each_other(self): + """The entry that says that Nerve accepts thread items goes with the + notifications, and the commit type with the repository watch. One + frame holds both, each as it is alone: the watch of an agent that does + not ask for commits is the same bytes with and without the entry, and + the entry is the same bytes with and without the commit type.""" + def frame(*, thread_items: bool, **watch: Any) -> str: + config = NerveConfig() + config.sync.github = hosted_github(enabled=True, thread_items=thread_items) + config.sync.github_repos = GitHubReposSyncConfig(enabled=True, repos=["acme/widgets"], **watch) + subscriptions = subscriptions_for(config, hosted_sources(config)) + subscriptions.validate() + return dumps(subscriptions) + + notifications = '{"provider":"github","filters":{},"pr_watch":true}' + items = '{"provider":"github_thread_items","filters":{}}' + + def watch(types: str, more: str = "") -> str: + return ( + '{"provider":"github_repos","filters":{},"repos":[{"name":"acme/widgets",' + f'"types":[{types}],"include_bots":false,"include_drafts":true,"updates":false,' + f'"deny_authors":[]{more}}}]}}' + ) + + def sources(*entries: str) -> str: + return '{"version":"1","sources":[' + ",".join(entries) + "]}" + + before, commits = watch('"pull_request","issue"'), watch('"issue","commit"', ',"branches":["main"]') + asks = {"types": ["issue", "commit"], "branches": {"acme/widgets": ["main"]}} + assert frame(thread_items=True) == sources(notifications, items, before) + assert frame(thread_items=False) == sources(notifications, before) + assert frame(thread_items=True, branches={"acme/widgets": ["main"]}) == sources(notifications, items, before) + assert frame(thread_items=True, **asks) == sources(notifications, items, commits) + assert frame(thread_items=False, **asks) == sources(notifications, commits) + + def test_the_types_that_are_published_are_chosen_in_one_place(self): + settings = GitHubReposSyncConfig(types=["commit", "Release", "release", "discussion"]) + + assert repo_watch_types(settings) == ("release", "commit") + assert github_repos_subscription( + GitHubReposSyncConfig(enabled=True, repos=["a/b"], types=["commit"]), + ).repos[0].types == ("commit",) + + def test_branches_the_gateway_would_refuse_are_not_published(self, caplog): + """The config refuses to load them; a setting built in code loses + them. A repository whose branches are all lost does not report the + commits of its default branch in their place.""" + settings = GitHubReposSyncConfig( + enabled=True, repos=["acme/widgets", "acme/gadgets", "acme/gears"], types=["issue", "commit"], + branches={ + "acme/widgets": ["main", "a..b", "main", *(f"b{n}" for n in range(9))], + "acme/gadgets": ["not a branch"], + }, + ) + + with caplog.at_level(logging.WARNING): + watch = github_repos_subscription(settings) + + assert [(repo.name, repo.types, repo.branches) for repo in watch.repos] == [ + ("acme/widgets", ("issue", "commit"), ("main", *(f"b{n}" for n in range(7)))), + ("acme/gadgets", ("issue",), ()), + ("acme/gears", ("issue", "commit"), ()), + ] + assert "sync.github_repos.branches of acme/widgets: the gateway is sent 8 of 12 branches" in caplog.text + Subscriptions(version="1", sources=(watch,)).validate() + only_commits = GitHubReposSyncConfig( + enabled=True, repos=["acme/gadgets"], types=["commit"], branches={"acme/gadgets": ["a..b"]}, + ) + assert github_repos_subscription(only_commits) is None + # A branch is named without its ref prefix. + by_ref = GitHubReposSyncConfig( + enabled=True, repos=["acme/gadgets"], types=["commit"], + branches={"acme/gadgets": ["main", "refs/heads/main", "refs/tags/v1.2.0"]}, + ) + assert github_repos_subscription(by_ref).repos[0].branches == ("main",) + def test_the_repository_watch_goes_without_the_notifications_and_never_in_poll_mode(self): watch = GitHubReposSyncConfig( enabled=True, repos=["acme/widgets"], types=["release"], include_bots=True, updates=True, @@ -660,6 +889,34 @@ def payload(self, **record: Any) -> dict[str, Any]: base.update(record) return {"record": base} + @pytest.mark.parametrize("thread_items", [True, False]) + def test_a_commit_record_and_a_thread_item_are_read_and_judged_each_by_its_own_source(self, thread_items): + """The two samples of the contract through the hosted reader: the + commits arrive as a list and truncated as a flag, and a thread item's + mentions_agent as a flag. The repository watch's guardrail keeps the + commit record only while types names commit, whatever + sync.github.thread_items says, and the notifications' guardrail keeps + the thread item whatever the watch reports.""" + from nerve.sources.github import github_inbox_filter + from nerve.sources.github_repos import github_repos_inbox_filter + + def read(sample: Path, source: str) -> Any: + event = json.loads(sample.read_text(encoding="utf-8")) + return record_from_buffer(buffered_record(decoded(event)), source=source) + + commits = read(COMMITS_SAMPLE, "github_repos") + item = read(COMMITS_SAMPLE.parent / "github_thread_item.json", "github") + + assert (commits.record_type, item.record_type) == ("github_repo_activity", "github_thread_item") + assert (len(commits.metadata["commits"]), commits.metadata["truncated"]) == (2, False) + assert isinstance(item.metadata["mentions_agent"], bool) and "truncated" not in item.metadata + assert "mentions_agent" not in commits.metadata and "actors" not in commits.metadata + notifications = hosted_github(enabled=True, thread_items=thread_items) + for types, kept in ((["commit"], True), (["pull_request", "issue", "release"], False)): + watch = GitHubReposSyncConfig(enabled=True, repos=["acme/widgets"], types=types) + assert github_repos_inbox_filter(watch).passes(commits) is kept + assert github_inbox_filter(notifications).passes(item) + def test_a_payload_maps_to_the_polling_sources_record_shape(self): record = record_from_buffer(self.payload()) @@ -1242,6 +1499,44 @@ async def test_the_repository_watch_is_published_and_its_records_reach_the_inbox assert stored["summary"] == "[acme/widgets] New PR #12: Add a widget cache" assert stored["metadata"] == REPO_ACTIVITY_METADATA + async def test_the_commits_of_a_branch_are_asked_for_and_their_record_reaches_the_inbox(self, hosted): + """The contract's sample of the new commits of a branch, as the + gateway delivers it: the commits arrive as a list and truncated as a + flag, and the guardrail keeps the record because the watch asks for + commits.""" + hosted.config.sync.github_repos = GitHubReposSyncConfig( + enabled=True, repos=["acme/widgets"], types=["commit"], branches={"acme/widgets": ["main"]}, + ) + sample = json.loads(COMMITS_SAMPLE.read_text(encoding="utf-8")) + stream = await hosted.stream() + [subscriptions] = await hosted.subscriptions() + inbox_id = hosted.gateway.store(sample) + + await stream.nudge("observe") + + # The entry for thread items goes with the notifications, and stays as + # it is next to a watch that asks for commits. + assert [source["provider"] for source in subscriptions["sources"]] == [ + "github", "github_thread_items", "github_repos", + ] + assert subscriptions["sources"][1] == THREAD_ITEMS + assert subscriptions["sources"][2] == {"provider": "github_repos", "filters": {}, "repos": [{ + "name": "acme/widgets", "types": ["commit"], "include_bots": False, "include_drafts": True, + "updates": False, "deny_authors": [], "branches": ["main"], + }]} + assert (await hosted.acknowledged(inbox_id))[inbox_id] == "accepted" + (runner,) = [ + r for r in build_source_runners(hosted.config, hosted.db) if r.job_id == "source:github_repos" + ] + assert (await runner.run()).records_ingested == 1 + stored = await hosted.db.get_source_message("github_repos", sample["record"]["id"]) + assert stored["summary"] == "[acme/widgets] 2 new commits on main" + assert stored["metadata"]["commits"] == [ + "5c4d3e2f1a0b99887766554433221100ffeeddcc Cache rendered widgets", + "1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d Add the widget cache interface", + ] + assert (stored["metadata"]["truncated"], stored["metadata"]["subject_type"]) == (False, "Commit") + async def test_the_repository_watch_guardrail_drops_what_the_settings_drop(self, hosted): """Records the gateway took before a reload changed the settings. The bot rule is for pull requests and issues: a bot's release is kept.""" diff --git a/tests/test_onboarding_environment.py b/tests/test_onboarding_environment.py index 24c52af90..62bce6a95 100644 --- a/tests/test_onboarding_environment.py +++ b/tests/test_onboarding_environment.py @@ -334,6 +334,20 @@ def test_the_repository_watch_line_says_who_polls_what_and_where(self, tmp_path) "also new commits, ready for review, merges and closes of the pull requests it reported" ) + def test_the_repository_watch_line_names_the_commits_of_branches(self, tmp_path): + config_dir, ws = _install(tmp_path) + merge_settings_paths(ws, { + "sync.github_repos.enabled": True, + "sync.github_repos.repos": ["acme/widgets"], + "sync.github_repos.types": ["commit", "issue"], + }) + + lines = _lines(env.gather(load_config(config_dir), ws).section) + + assert lines["GitHub repository watch"] == ( + "on (polled here with `gh`): new issues and branch commits in `acme/widgets`" + ) + def test_a_repository_watch_without_repositories_says_so(self, tmp_path): config_dir, ws = _install(tmp_path) merge_settings_paths(ws, {"sync.github_repos.enabled": True, "sync.github_repos.types": ["release"]}) diff --git a/web/src/components/Sources/renderers/GitHubRenderer.test.tsx b/web/src/components/Sources/renderers/GitHubRenderer.test.tsx new file mode 100644 index 000000000..9329e7e64 --- /dev/null +++ b/web/src/components/Sources/renderers/GitHubRenderer.test.tsx @@ -0,0 +1,55 @@ +import { describe, it, expect } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { GitHubRenderer } from './GitHubRenderer'; + +describe('GitHubRenderer', () => { + it('shows the repository, the subject type and the link of a record', () => { + render( + , + ); + + expect(screen.getByText('acme/widgets')).toBeInTheDocument(); + expect(screen.getByText('PullRequest')).toBeInTheDocument(); + expect(screen.getByRole('link', { name: /View on GitHub/ })) + .toHaveAttribute('href', 'https://github.com/acme/widgets/pull/12'); + }); + + it('shows the branch of new commits, and each commit as a list item', () => { + render( + , + ); + + expect(screen.getByText('Commit')).toBeInTheDocument(); + expect(screen.getByText('main')).toBeInTheDocument(); + const commits = screen.getAllByRole('listitem').map((item) => item.textContent); + expect(commits).toEqual([ + '5c4d3e2f1a0b99887766554433221100ffeeddcc Cache rendered widgets', + '1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d Add the widget cache interface', + ]); + }); +}); diff --git a/web/src/components/Sources/renderers/GitHubRenderer.tsx b/web/src/components/Sources/renderers/GitHubRenderer.tsx index 11886b37a..461c9c559 100644 --- a/web/src/components/Sources/renderers/GitHubRenderer.tsx +++ b/web/src/components/Sources/renderers/GitHubRenderer.tsx @@ -14,6 +14,8 @@ export function GitHubRenderer({ content, metadata, summary: _summary }: Props) const subjectUrl = metadata?.subject_url || ''; const subjectType = metadata?.subject_type || ''; const reason = metadata?.reason || ''; + // The branch of a repository watch's commit record. + const branch = metadata?.branch || ''; return (
@@ -27,6 +29,7 @@ export function GitHubRenderer({ content, metadata, summary: _summary }: Props) `text-hue-purple` mark above it. */} {subjectType && {subjectType}} {reason && {reason}} + {branch && {branch}}
{subjectUrl && ( ( {k}:{' '} - {typeof v === 'object' ? JSON.stringify(v) : String(v)} + {metadataValueText(k, v)} ))} diff --git a/web/src/utils/sourceMetadata.test.ts b/web/src/utils/sourceMetadata.test.ts new file mode 100644 index 000000000..cb41a72ec --- /dev/null +++ b/web/src/utils/sourceMetadata.test.ts @@ -0,0 +1,40 @@ +import { describe, it, expect } from 'vitest'; +import { metadataValueText } from './sourceMetadata'; + +const COMMITS = [ + '5c4d3e2f1a0b99887766554433221100ffeeddcc Cache rendered widgets', + '1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d Add the widget cache interface', +]; + +describe('metadataValueText', () => { + it('shows a scalar as it is', () => { + expect(metadataValueText('repo_name', 'acme/widgets')).toBe('acme/widgets'); + expect(metadataValueText('number', 12)).toBe('12'); + expect(metadataValueText('truncated', false)).toBe('false'); + expect(metadataValueText('commits', 'none')).toBe('none'); + }); + + it('shows the commits of a commit record as their number when they are too long for a chip', () => { + expect(metadataValueText('commits', COMMITS)).toBe('2 items'); + }); + + it('shows a short list of commits in full', () => { + expect(metadataValueText('commits', ['5c4d3e2 Cache rendered widgets'])).toBe('["5c4d3e2 Cache rendered widgets"]'); + expect(metadataValueText('commits', [])).toBe('[]'); + }); + + it('shows the list of every other key in full, however long', () => { + const labels = Array.from({ length: 12 }, (_, index) => `area/component-${index}`); + expect(metadataValueText('labels', labels)).toBe(JSON.stringify(labels)); + expect(metadataValueText('actors', ['alice', 'bob'])).toBe('["alice","bob"]'); + // The same list under another key is not the commits of a commit record. + expect(metadataValueText('changes', COMMITS)).toBe(JSON.stringify(COMMITS)); + expect(metadataValueText('Commits', COMMITS)).toBe(JSON.stringify(COMMITS)); + }); + + it('shows any other object as JSON', () => { + expect(metadataValueText('extra', { a: 1 })).toBe('{"a":1}'); + expect(metadataValueText('extra', null)).toBe('null'); + expect(metadataValueText('commits', { a: 1 })).toBe('{"a":1}'); + }); +}); diff --git a/web/src/utils/sourceMetadata.ts b/web/src/utils/sourceMetadata.ts new file mode 100644 index 000000000..a2d8bc399 --- /dev/null +++ b/web/src/utils/sourceMetadata.ts @@ -0,0 +1,19 @@ +/** + * The text of one metadata value in the header of a source message. + * + * A value is shown as it is, and a list or any other object as JSON. One key + * is the exception: `commits`, the list of a repository watch's commit + * record. When it is too long for a chip it is shown as its length, and the + * message's content holds its items. The lists of every other key, of any + * source, are shown in full. + */ +const COMMITS_KEY = 'commits'; +const MAX_COMMITS_TEXT = 80; + +export function metadataValueText(key: string, value: unknown): string { + if (key === COMMITS_KEY && Array.isArray(value)) { + const text = JSON.stringify(value); + return text.length > MAX_COMMITS_TEXT ? `${value.length} items` : text; + } + return typeof value === 'object' ? JSON.stringify(value) : String(value); +}