Sortify Auto-Merge Policy and Architecture
Overview
Sortify uses a safe, risk-aware auto-merge system designed to reduce routine PR coordination and branch-conflict churn on main without compromising security or code quality.
Because fderuiter/sortify is owned by a personal GitHub account (where native GitHub Merge Queue is unavailable), the system uses a serialized auto-merge controller backed by GitHub Actions concurrency, mandatory main branch freshness re-validation, and durable required status gates.
1. Risk Classification & Eligibility
Every Pull Request undergoes automated risk classification via .github/workflows/classify-pr.yml and scripts/classify_pr.py.
A. Automatically Eligible by Default
- Maintainer documentation-only changes (
docs/**,README.md) opened from an in-repository branch by a non-bot human collaborator withwrite,maintain, oradminrepository access within low-risk size limits ($\le 10$ changed files and $\le 500$ changed lines) that do not touch sensitive/security files. Documentation changes from bots, external forks, non-collaborators, or oversized diffs require a human maintainer-appliedautomergelabel (failing closed if collaborator permission lookup fails). - Dependabot minor or patch updates (single-package PRs and grouped
python-minor-patchorpython-zero-major-patchupdates from.github/dependabot.yml) topyproject.toml/uv.lockafter full CI verification, when verified merge-baseuv.lockdiffs and/or signed Dependabot commit/PR metadata confirm every package bump is a non-0.xminor or patch update (including0.xpatch updates). Major bumps,0.xminor bumps, and updates with missing version metadata fail closed to human review. Only PRs authored bydependabot[bot]qualify; adependencieslabel alone does not. GitHub Actions bumps touch.github/**and always need a human merge.
B. Explicit Opt-In (automerge label) vs Classifier Approval (automerge:eligible)
Production-code maintenance, refactor, and non-maintainer/bot/fork/oversized documentation PRs require an explicit automerge label to authorize automated evaluation.
Autonomous agent PRs (including BOT_AUTHORS: stitch, jules, github-actions[bot], dependabot[bot], dependabot, plus any *[bot] account), external fork PRs, and automated security patches do not bypass review: they require an explicit maintainer-applied automerge label (applied by a human maintainer with write access or above) before automated evaluation or merging can proceed.
.github/workflows/classify-pr.yml runs on pull_request_target events targeting main and actionable pull_request_review (submitted, dismissed) events on in-repository PRs targeting main, checks out refs/heads/main under job-scoped write permissions, strips any automerge label not applied by a human maintainer, and runs scripts/classify_pr.py. Completed runs always post a success automerge/classification commit status describing 'Eligible for auto-merge' (applying automerge:eligible), 'Approved for serialized merge (<risk>)' (applying automerge:approved when @fderuiter has an active approval on the head commit and automerge is present), or 'Human review required (<risk>)' (applying automerge:blocked), failing closed on unhandled GitHub REST API errors.
The auto-merge controller requires either unreviewed low-risk eligibility (automerge:eligible) or owner-approved serialized queue eligibility (automerge:approved / maintainer-applied automerge backed by an active @fderuiter review approval on the head commit) to proceed, re-verifies via issue event history that any automerge label was added by a human maintainer rather than an automated bot or untrusted author, and removes stale automerge:eligible or automerge:approved labels while applying automerge:blocked whenever merge-time reclassification rejects a candidate PR.
Trust model
The PR under evaluation must not be able to approve itself:
- classify-pr.yml filters pull_request_target to main, defaults to read-only workflow permissions, and checks out refs/heads/main, so both the workflow and scripts/classify_pr.py always evaluate current default-branch rules without checking out or executing the PR's code.
- The automerge:eligible label and the automerge/classification status are only a pre-filter. Before acting, the controller re-runs classify_pr() from its own default-branch checkout on file, commit and label data fetched from the GitHub API.
- Required CI is accepted only as a check run created by GitHub Actions. Plain commit statuses with that name are ignored.
Thresholds for low-risk opt-in PRs: - $\le 10$ changed files - $\le 500$ non-generated changed lines - No sensitive paths touched - No snapshot, type-check, or API baseline modifications - Not draft
(Note: Resolved review conversations are mandatory and enforced directly by GitHub main branch rulesets.)
C. Never Unreviewed Auto-Merge (Owner @fderuiter Approval Mandatory)
scripts/classify_pr.py separates unreviewed auto-merge eligibility (eligible=True, label automerge:eligible) from owner-approved serialized queue eligibility (queue_eligible=True, label automerge:approved). PRs touching any of the following Tier 3 sensitive or baseline categories never receive automerge:eligible; they stay blocked (automerge:blocked) unless the repository owner (@fderuiter) has an active APPROVED GitHub pull-request review on the current head commit (preserving approval across verified GitHub web-flow base-branch merge updates onto main, while rejecting any unapproved post-review commit) and a human maintainer has applied the automerge label, in which case the serialized controller updates, retests (Required CI), and squash-merges them sequentially:
- Workflow or action configuration (.github/**)
- Documentation build configuration (mkdocs.yml, with scripts/generate_docs.py rejecting non-allowlisted YAML tags before mkdocs build)
- Local pre-commit hooks, repository git attributes, and custom merge drivers (.pre-commit-config.yaml, .gitattributes)
- Agent instructions, skills, and local hook configurations (AGENTS.md, CLAUDE.md, .agents/**, .claude/**)
- Security & privacy policies (SECURITY.md, PRIVACY.md, .gitleaks.toml)
- Application configuration & schema (app/config.py, network_rules.json)
- Envelope encryption & key management (app/core/crypto.py)
- Safe file movement, ledger, database, & rollback logic (app/core/mover.py, app/core/resilient_file_ops.py, app/core/ledger.py, app/core/history.py, app/core/db.py, app/core/db_conn.py, app/core/db_worker.py)
- Quarantine & interceptor logic (app/core/quarantine_interceptor.py, app/core/session.py)
- Release & compilation toolchains and CI/merge tooling (scripts/**, smart-autosorter.spec)
- Dependency manifests and lockfiles (pyproject.toml, uv.lock), unless the PR is an approved native Dependabot update (dependabot[bot]) or an automated security patch with a maintainer-applied automerge label (offline_bundle/requirements.txt is derived at bundle build time, untracked in Git, and kept in PROTECTED_PATHS and .github/CODEOWNERS so any accidental re-addition fails closed as risk:sensitive)
- Major dependency updates (e.g. major version bumps)
- Snapshot and type-check baselines (tests/snapshots/api/**, tests/snapshots/tui_svg/**, tests/ty_baseline.json)
2. Conflict Handling & Serialization
- Read-Only Queue Pre-Gate & Serialized Execution:
.github/workflows/auto-merge-controller.ymltriggers on successfulCI PipelineandPR Risk Classifierworkflow_runcompletions,workflow_dispatch, and a 15-minute schedule, first runningjobs.check-queueunderpermissions: pull-requests: readto check whether any open non-draft PR carries unreviewedautomerge:eligibleor an owner-approved (@fderuiter)automerge/automerge:approvedstate on the current head commit (preserving approval across verified GitHubweb-flowbase-branch merges) without hard-blocking labels. Only whenneeds.check-queue.outputs.has_eligible == 'true'doesjobs.auto-mergerun, acquiringconcurrency: group: auto-merge-controller(cancel-in-progress: false), minting job-scoped write permissions, and executingpython -m scripts.auto_merge_controlleron Python 3.12 using only standard-library HTTP (urllib) with zero PyPI packages. Placingneedsandifbeforeconcurrencyensures empty-queue polls and unrelated workflow runs never mint write tokens or contend for an active merge lock. - Current-Main Validation &
workflow_dispatchOrchestration: Because branch updates and squash merges performed withGITHUB_TOKENsuppress downstreampull_requestandpushevents,scripts/auto_merge_controller.pyexplicitly orchestrates.github/workflows/ci.ymland.github/workflows/docs.ymlviaworkflow_dispatch: - In-repository stale branches: When
mergeable_state == "behind"and the PR's head branch belongs tofderuiter/sortify, the controller updates the branch via the GitHubupdate-branchAPI, polls pull request metadata briefly until the new head SHA is visible, and dispatches.github/workflows/ci.ymlon that branch soRequired CIruns on the updated commit. - Post-merge
mainverification & documentation deployment: Aftermerge_pull_requestcompletes a squash merge, the controller always dispatches.github/workflows/ci.ymlonmainand dispatches.github/workflows/docs.ymlonmainwhen the merged PR'schanged_filesinclude documentation inputs (docs/**,mkdocs.yml, root*.md,app/**,scripts/**,sandbox_cli.py,network_rules.json,pyproject.toml,uv.lock, or.github/workflows/docs.yml), skippingdocs.ymlfor non-documentation merges such astests/**-only changes—withci.yml(ci-main) anddocs.yml(build-docs) cancelling superseded runs (cancel-in-progress: true) whiledeploy-docsserializes active Pages deployments (cancel-in-progress: false) (logging any transient dispatch error without failing the completed merge). - Fork-branch limits:
GITHUB_TOKENcannot update or dispatch.github/workflows/ci.ymlagainst branches in external forks. Stale fork PRs (mergeable_state == "behind") are skipped without blocking other eligible PRs in the queue until a contributor updates or rebases the fork branch ontomain(which triggers normalpull_requestCI). Up-to-date fork PRs with a maintainer-appliedautomergelabel and a passingRequired CIcheck run still merge automatically. - No Automatic Conflict Resolution: If updating a branch results in Git merge conflicts, the controller:
- Withholds auto-merge eligibility.
- Applies the
automerge:conflictandautomerge:blockedlabels. - Leaves source code intact for developer resolution.
3. Emergency Overrides & Disabling Automation
- Disable Auto-Merge for a Specific PR: Apply the
disable-automergelabel to the PR. - Global Emergency Override: Disable
.github/workflows/auto-merge-controller.ymlin GitHub Actions settings or remove the workflow file.mainbranch protection rules remain active regardless of controller status. - Clear a Backed-Up Actions Queue: Run Cancel All Runs (
.github/workflows/cancel-queued-runs.yml) from the Actions tab. With the defaults one run cancels every queued and running workflow run on every branch. Inputs narrow it to queued or running runs, one branch or one workflow, force-cancel stuck runs, re-run the newest cancelled run of each workflow once per branch (requeue), or only list what would happen (dry_run).
4. Organization Migration Path (Future Work)
If fderuiter/sortify is transferred to a GitHub Organization in the future:
1. Enable native GitHub Merge Queue on the main branch ruleset (.github/workflows/ci.yml already declares merge_group: triggers with merge_group secret-scan, docs-build, and freshness scoping).
2. Deprecate .github/workflows/auto-merge-controller.yml.