Compare commits

..

10 Commits

Author SHA1 Message Date
diegosouzapw
c13cee2357 chore(changelog): prefix the fragment with PR #20825 2026-11-20 18:33:25 -03:00
diegosouzapw
eca9826d29 fix(security): bound regex work in compression engines (CodeQL #1301, #1302, #1349)
- headroom GCF needsQuote: inline-array regex excludes '[' from the bracket body (same .test verdict, linear on '[' runs).
- RTK raw-output: cut the tool_use command to 256 chars before the slug replaces.
- CCR grep: reject patterns with more than one unbounded quantifier and run the scan under a 1000 ms vm timeout.
2026-11-20 18:31:14 -03:00
Diego Rodrigues de Sa e Souza
a61261846f Merge pull request #20795 from cheaper-inference/chore/codeql-baseline-2-27-5
chore(quality): temporary codeqlAlerts ceiling for the CodeQL 2.27.5 upgrade
2026-11-20 17:24:27 -03:00
diegosouzapw
1ec3442acc chore(quality): temporary codeqlAlerts ceiling for the CodeQL 2.27.5 upgrade
The default setup moved CodeQL 2.27.4 -> 2.27.5 on 2026-11-20; the release/v3.8.55 JS analysis went 236 -> 339 results with the same 87 rules and no code change, opening 101 alerts at once and failing the codeql ratchet on every PR. Owner-authorized temporary ceiling 6 -> 103 while the security wave triages them; a follow-up lowers it to the measured count.
2026-11-20 13:12:41 -03:00
Diego Rodrigues de Sa e Souza
07a790f5c1 fix(ci): give the SonarQube scan coverage/lcov.info on pull requests (#20769)
#18336 dropped the lcov reporter from the coverage merge on pull_request while SonarQube was off; once vars.SONARQUBE_ENABLED came back, the scan found no coverage/lcov.info and every PR showed 0.0% coverage on new code. The merge step now writes lcov on a PR when SonarQube is enabled (measured cost: none beyond runner variance), and the sonarqube job fails before the scan when the file is missing. Closes #20725.
2026-11-20 12:12:03 -03:00
Diego Rodrigues de Sa e Souza
760357c44a Merge pull request #20772 from cheaper-inference/fix/release-v3.8.55-basereds-20771-combo-timeout
test(ci): stabilize combo target timeout on v3.8.55
2026-11-20 11:06:51 -03:00
diegosouzapw
3924a54945 test(ci): make combo target timeout assertion deterministic 2026-11-20 09:44:38 -03:00
Diego Rodrigues de Sa e Souza
8f56803041 chore(ci): retire the Mergify merge queue (#20616)
* chore(ci): retire the Mergify merge queue

The owner retired Mergify from the merge process on 2026-11-19.

- .mergify.yml: drop the release and relay-integration queue rules and
  the queue-label cleanup rule; keep the file with commands_restrictions
  that refuse every Mergify command that merges or rewrites a PR, since
  with no configuration Mergify's implicit queue still merges on
  @mergifyio queue.
- dry-run-lts-cut G11 now checks omni-queue: valid config at the source,
  bases managing the release branch, mode live, label present.
- Dated notes on the Mergify-era docs; G11 rows updated.

* docs(changelog): add the fragment for the Mergify retirement (#20616)

* chore(quality): record the retired Mergify contract in the test-masking allowlist (#20616)
2026-11-20 08:53:41 -03:00
Diego Rodrigues de Sa e Souza
0c9e0356f9 fix(release): sync-next-cycle opens a PR instead of pushing to the release branch (#20645)
* fix(release): sync-next-cycle opens a PR instead of pushing to the release branch

release/vX+1 is the default branch and ruleset 21899981 (Require PR on
default branch, no bypass actors) refuses a direct push, so the final
push of the sync-back could never land. The script now pushes the merge
commit to chore/sync-back-main-<sha12> and opens a PR into the release
branch; it never merges it. Re-running after the side branch reached
origin prints the open PR (or opens it) and stops. The old push stays
behind --direct-push (off by default). The sync worktree is detached at
origin/<branch>, so the merge commit never moves a local release branch
ref. The release-green gate and --skip-green-gate are unchanged.

* docs(changelog): add the fragment for #20645

* test(release): compare the sync-back next-steps line exactly (#20645)
2026-11-20 08:50:19 -03:00
Diego Rodrigues de Sa e Souza
632d84f569 Merge pull request #20718 from cheaper-inference/chore/derived-refresh
chore(docs): refresh derived numbers on release/v3.8.55
2026-11-20 07:30:23 -03:00
27 changed files with 1170 additions and 404 deletions

View File

@@ -1369,16 +1369,20 @@ jobs:
# Merging 8 shards of raw v8 coverage is memory-heavy. `--merge-async`
# keeps the V8 coverage merge incremental instead of loading every raw
# JSON blob into one in-memory merge, which avoids Node heap OOMs.
# lcov only outside pull_request (2026-10-26): its sole consumer on a PR was the
# informational Codecov upload below (SonarQube is off: vars.SONARQUBE_ENABLED is
# unset), and the PR gate only needs the json/text summaries. The step took ~21 min
# on a measured PR against the org's 20-job hosted cap.
# lcov on a PR only when SonarQube runs (#20725). #18336 (2026-10-26) dropped it on
# pull_request because its only PR consumer was the informational Codecov upload while
# SonarQube was off; once vars.SONARQUBE_ENABLED came back the `sonarqube` job scanned
# with no coverage/lcov.info and every PR showed 0.0% coverage on new code. Without
# Sonar the PR gate still only needs the json/text summaries, so lcov stays skipped.
env:
NODE_OPTIONS: --max-old-space-size=8192
EVENT_NAME: ${{ github.event_name }}
SONARQUBE_ENABLED: ${{ vars.SONARQUBE_ENABLED }}
run: |
LCOV_REPORTER=()
if [ "$EVENT_NAME" != "pull_request" ]; then LCOV_REPORTER=(--reporter=lcov); fi
if [ "$EVENT_NAME" != "pull_request" ] || [ "$SONARQUBE_ENABLED" = "true" ]; then
LCOV_REPORTER=(--reporter=lcov)
fi
mkdir -p coverage
first_coverage_file=""
if [ -d coverage-shards ]; then
@@ -1484,6 +1488,17 @@ jobs:
with:
name: coverage-report
path: coverage/
# Without lcov.info the scan still "succeeds" and publishes 0.0% coverage on new code
# (#20725): fail here, naming the cause, instead of letting the quality gate blame the PR.
- name: Require coverage/lcov.info for the scan
if: ${{ github.event_name == 'pull_request' && env.SONAR_TOKEN != '' && env.SONAR_HOST_URL != '' }}
run: |
if [ ! -s coverage/lcov.info ]; then
echo "::error::coverage/lcov.info is missing or empty after downloading coverage-report; SonarQube would report 0% coverage on new code. Check the lcov reporter in the test-coverage job's merge step (#20725)."
ls -la coverage || true
exit 1
fi
echo "coverage/lcov.info: $(wc -l < coverage/lcov.info) lines"
- name: Explain SonarQube skip
if: ${{ github.event_name != 'pull_request' || env.SONAR_TOKEN == '' || env.SONAR_HOST_URL == '' }}
run: |

View File

@@ -1,122 +1,53 @@
# Mergify merge queue — WS3.4/D5 of the v3.8.49 quality/velocity master plan.
# Mergify — merge queue RETIRED by the owner's decision of 2026-11-19.
#
# WHY: ~85-100 active PR authors/month and 300+ PRs/week peaks, all merged by ONE
# identity. The manual merge-train validated batches by hand; this queue automates
# it with batching + automatic batch bisection (a red batch of N costs ~log2(N)
# revalidations instead of N). Mergify Open Source plan: free, unlimited, public repo.
# History: the Mergify `release` queue (WS3.4/D5 of the v3.8.49 quality/velocity master plan:
# owner-applied `queue` label, serial squash, checks_timeout 240 min) and the opt-in
# `relay-integration` queue landed release PRs until 2026-11-19 (last Mergify merge: #19538,
# 2026-11-15). Their rules, and the rule that removed the `queue` label after a merge, are in
# git history. Release PRs are now merged by hand under the repository ruleset "Require green
# gates on the active release" (`Gate / CI` + `Gate / Quality`) until omni-queue runs in live
# mode, and through omni-queue after that (docs/ops/OMNI_QUEUE.md).
#
# GOVERNANCE (non-negotiable, mirrors CLAUDE.md Hard Rules #21/#22 + the owner's
# pre-merge ⭐ gate):
# • A PR enters the queue ONLY via the `queue` label — applied by the owner (or a
# session acting for the owner) AFTER the pre-merge ⭐ report/decision. The label
# IS the merge approval; Mergify only executes it.
# • During a release-freeze (open issue labeled `release-freeze`), do NOT label PRs
# targeting the frozen branch — the freeze is a human-honored coordination signal
# the queue cannot see. Retarget to the active release/vX+1 first (Hard Rule #21).
# • Never label a PR another session is actively working (Hard Rule #22b).
# • Fallback path if Mergify misbehaves or the OSS plan changes: the manual
# merge-train runbook (docs/ops/MERGE_TRAIN.md) — remove labels, proceed by hand.
# WHY this file is kept instead of deleted: the Mergify GitHub App is still installed, and
# Mergify documents that "With no Mergify configuration, your queue already ... Merges
# automatically when your required checks pass" once someone comments `@mergifyio queue`
# (docs.mergify.com/merge-queue/setup). The docs do not say what that command does on a config
# without `queue_rules`, so the commands that would merge or rewrite a pull request are
# refused here: each condition list below is `closed` AND `-closed`, which no pull request can
# match. `commands_restrictions` is read whatever Mergify products are enabled
# (docs.mergify.com/configuration/file-format). `refresh` and `dequeue` keep their defaults:
# they neither merge nor push.
#
# Contract: tests/unit/mergify-queue-config.test.ts. Do not add `queue_rules`,
# `merge_protections_settings` or a merging `pull_request_rules` action back: two queues would
# act on the same release PRs.
# Auto-enqueue (current Mergify model, 2026): auto_merge_conditions in
# merge_protections_settings — the rules-based queue action / autoqueue path is
# deprecated (EOL 2026-07-16). The owner-applied `queue` label IS the approval.
merge_protections_settings:
auto_merge_conditions:
- label = queue
queue_rules:
- name: release
# Any current or future release branch — the reason GitHub's native queue was
# rejected (no wildcard support on personal-account repos).
queue_conditions:
- base~=^release/v\d+\.\d+\.\d+$
- label=queue
- -draft
- -conflict
# A reviewed integration candidate must never be squashed by this queue,
# including when its second approval label is missing or its ref changed.
- -label=integration-reviewed
- -head~=^fix/relay-integration-candidate-
# "Everything that ran is green, nothing still running, AND the always-on
# anchor check succeeded" — robust to the path-filtered fast-gates (docs-only
# PRs skip code jobs; matrix shard names vary) while never fail-open: a PR with
# zero checks cannot vacuously merge, because `Merge integrity` runs on EVERY
# non-draft PR (quality.yml) and must be an affirmative success. Review approval
# is intentionally NOT a condition here: the owner-applied `queue` label IS the
# approval in this repo's single-maintainer model (see governance header).
merge_conditions:
# "Zero failures" — EXCEPT the advisory "Build (advisory)" job (quality.yml):
# continue-on-error by design, and its GH-hosted Turbopack build hangs
# recurrently mid-"Creating an optimized production build" (100% failure rate
# across every sampled PR since the job was added 2026-07-27, always killed by
# a runner timeout/shutdown signal, never a real compile error). Any OTHER
# failure still blocks (anti-fail-open kept). The prior dast-smoke exception
# (#7225) was dropped here: dast-smoke's hang (#7226) has been dormant for
# weeks (0 failures in the last 30 runs; 2 all-time, none since 2026-07-13) —
# carrying its tolerance forward would mask problems it no longer causes.
- or:
- "#check-failure=0"
- and:
- "#check-failure=1"
- check-failure=Build (advisory)
- "#check-pending=0"
- "#check-success>=1"
- check-success=Merge integrity (changelog + generated skills)
- check-success=Gate / CI
- check-success=Gate / Quality
# NO batching: 'Merge Queue Batch' requires a paid Mergify tier (live finding
# 2026-07-15 — the queue command fails with "Cannot use Merge Queue batch" on
# the free plan; #7220). Serial queue (1 PR at a time) still automates the train.
# Rail G11 (v3.8.54) asks for batch_size ~5: it stays BLOCKED on that tier —
# adding batch_size/batch_max_wait_time here would dequeue EVERY PR again. Do not
# re-add them unless the Mergify subscription is upgraded (owner decision).
#
# checks_timeout = 2 x p95 wall-clock of the quality.yml workflow (the fast-gates
# that run on PR -> release/**), measured over the last 100 successful runs
# (2026-09-28 .. 2026-10-08, createdAt -> updatedAt, so runner queueing counts):
# mean 34.5 min · p50 1.8 min · p90 101.0 min · p95 119.75 min · max 468.6 min
# (bimodal: path-filtered docs-only runs ~2 min vs full runs ~72 min median).
# 2 x 119.75 = 239.5 -> rounded up to 240 min. A PR whose checks are still
# pending past this is dequeued instead of blocking the serial queue forever.
# Re-measure with: gh run list --workflow quality.yml --status success
# --limit 100 --json createdAt,updatedAt (contract: tests/unit/mergify-queue-config.test.ts).
checks_timeout: 240 min
# Squash keeps the one-commit-per-PR history the CHANGELOG reconciliation expects.
merge_method: squash
# One already-composed PR, NOT Mergify's paid multi-PR batching feature.
# Activation requires this configuration to land on the default branch first.
# See docs/ops/RELAY_INTEGRATION_QUEUE.md for ownership, admission and readback.
- name: relay-integration
queue_conditions:
- base=release/v3.8.52
- head=fix/relay-integration-candidate-20261015
- author=diegosouzapw
- label=queue
- label=integration-reviewed
- -draft
- -conflict
merge_conditions:
- or:
- "#check-failure=0"
- and:
- "#check-failure=1"
- check-failure=Build (advisory)
- "#check-pending=0"
- "#check-success>=1"
- check-success=Merge integrity (changelog + generated skills)
- check-success=Gate / CI
- check-success=Gate / Quality
checks_timeout: 240 min
# Preserve the reviewed original PR heads; rebasing or squash would lose them.
update_method: merge
merge_method: merge
pull_request_rules:
- name: clean up the queue label after merge
commands_restrictions:
queue:
conditions:
- merged
actions:
label:
remove:
- queue
- closed
- -closed
requeue:
conditions:
- closed
- -closed
rebase:
conditions:
- closed
- -closed
update:
conditions:
- closed
- -closed
squash:
conditions:
- closed
- -closed
backport:
conditions:
- closed
- -closed
copy:
conditions:
- closed
- -closed

View File

@@ -0,0 +1 @@
- **fix(release):** `scripts/release/sync-next-cycle.mjs` no longer pushes the sync-back straight to the release branch, which ruleset 21899981 refuses on the default branch: it pushes the merge commit to `chore/sync-back-main-<sha12>` and opens a PR into the release branch (land it as a merge commit), re-runs find the open PR instead of creating another, and the old push stays behind `--direct-push` ([#20645](https://github.com/cheaper-inference/OmniRoute/pull/20645))

View File

@@ -0,0 +1 @@
- **fix(security):** Compression engines bound their regex work on hostile input: the headroom GCF inline-array check and the RTK raw-output command slug run in linear time, and CCR `grep` rejects patterns with more than one unbounded quantifier and stops a scan that exceeds a 1 s time budget (CodeQL #1301, #1302, #1349)

View File

@@ -0,0 +1 @@
- **chore(ci):** retire the Mergify merge queue: `.mergify.yml` drops the `release` and `relay-integration` queues, the auto-merge label condition and the label-cleanup rule, and refuses the Mergify commands that merge or rewrite a pull request; rail gate G11 of `release:dry-run-lts-cut` now checks omni-queue (valid config, release branch managed, mode `live`, label present) ([#20616](https://github.com/cheaper-inference/OmniRoute/pull/20616))

View File

@@ -0,0 +1 @@
- **fix(ci):** SonarCloud gets `coverage/lcov.info` on pull requests again — the coverage merge skipped the lcov reporter on PRs since #18336, so every PR showed 0.0% coverage on new code; the SonarQube job now also fails clearly when the file is missing ([#20769](https://github.com/cheaper-inference/OmniRoute/pull/20769))

View File

@@ -157,12 +157,13 @@
"dedicatedGate": true
},
"codeqlAlerts": {
"value": 6,
"value": 103,
"direction": "down",
"dedicatedGate": true,
"_rebaseline_2026_08_06_base_grew": "Base branch file-size drift: translator-openai-to-gemini.test.ts grew 1619->1622 (test assertions for Gemini translator compatibility). CodeQL alert (js/insufficient-password-hash in raycast.ts) is pre-existing base-red; incremented baseline to match.",
"_rebaseline_2026_08_10_9940_fingerprint": "CodeQL base-red (green-prs sweep, issue #9985): 2nd js/insufficient-password-hash alert at src/shared/middleware/chatBodyAdmission.ts:265,269 introduced by #9940 (per-connection virtual admission lanes). Both are API-key/bearer FINGERPRINTS (createHash('sha256') truncated to 16-hex admission-lane key), not password VERIFICATION — false-positive class for this rule. Reproduces on release/v3.8.50 tip. Owner-authorized rebaseline 1->2; revisit at v3.9.0.",
"_rebaseline_2026_08_11_merge_storm_drift": "2 -> 9. Drift from the 2026-08-11 authorized merge storm (99 PRs into release/v3.8.50): js/insufficient-password-hash in open-sse/executors/chatgpt-web-codex/storageState.ts x3 + conol-web.ts (PRs #8949/#8974 — Chromium browser-profile credential storage SKUs that CodeQL flags under the password-hash rule; same fingerprint/credential-cache false-positive class already rebaselined in #9940/2026-08-06), js/stack-trace-exposure (chatgpt-web-codex.ts, #8949 debug logging), js/double-escaping (environment.ts, #8949), js/insecure-randomness (tinycms.ts, #9435). None introduced by this base-fix PR. Owner-authorized rebaseline (2026-08-11); revisit hardening at v3.9.0."
"_rebaseline_2026_08_11_merge_storm_drift": "2 -> 9. Drift from the 2026-08-11 authorized merge storm (99 PRs into release/v3.8.50): js/insufficient-password-hash in open-sse/executors/chatgpt-web-codex/storageState.ts x3 + conol-web.ts (PRs #8949/#8974 — Chromium browser-profile credential storage SKUs that CodeQL flags under the password-hash rule; same fingerprint/credential-cache false-positive class already rebaselined in #9940/2026-08-06), js/stack-trace-exposure (chatgpt-web-codex.ts, #8949 debug logging), js/double-escaping (environment.ts, #8949), js/insecure-randomness (tinycms.ts, #9435). None introduced by this base-fix PR. Owner-authorized rebaseline (2026-08-11); revisit hardening at v3.9.0.",
"_rebaseline_2026_11_20_codeql_2_27_5": "6 -> 103. Tool upgrade, not code: the default setup moved CodeQL 2.27.4 -> 2.27.5 on 2026-11-20 and the release/v3.8.55 JS analysis went 236 -> 339 results with the same 87 rules (760357c4 only touched a test file). 101 alerts were created together at 14:07:12Z (path-injection 34, polynomial-redos 30, request-forgery 22, unvalidated-dynamic-method-call 6, regex-injection 6, resource-exhaustion 3). Owner-authorized temporary ceiling (2026-11-20) to unblock merges while the security wave triages them (dismiss false positives with justification, fix real defects); a follow-up PR lowers the value to the measured count."
},
"secretFindings": {
"_note": "Zeroed 2026-07-13 (WS6/D3): the 3 frozen generic-api-key FPs are allowlisted with justification in .gitleaks.toml — any NEW finding regresses the ratchet.",

View File

@@ -348,5 +348,6 @@
"@omniroute/opencode-plugin/tests/log-level.test.ts": "the v1 plugin no longer fetches /api/combos/auto on refresh; the retired fetcher 404 test and its import are removed with the source (21 to 19). Remaining level coverage unchanged.",
"@omniroute/opencode-plugin/tests/config-shim.test.ts": "the v1 plugin no longer fetches /api/combos/auto on refresh; the retired twin-wins case and its fixtures are removed with the static publication block (162 to 159). Remaining builder coverage unchanged.",
"tests/unit/stepfun-mono-fallback-and-sidebar-hydration-7743.test.ts": "ec27d84e (KEA-7886, F4, 2026-10-21): the legacy DashboardLayout and its synchronous localStorage collapse initializer were removed; the one dropped assert pinned that initializer. The replacement block pins the kit shell contract instead: no localStorage read in the layout files and the server passing the ci_sidebar_state cookie as sidebarDefaultOpen (3 new asserts in place of the old structure). Net count 9 -> 8 is the realignment, not a weakening. Release-green base-red #17219 (2026-10-24).",
"tests/unit/ui/rtl-logical-classes.test.tsx": "ec27d84e (KEA-7886, F4, 2026-10-21): the legacy mobile sidebar drawer (.dashboard-sidebar-mobile, start-0/-translate-x-full RTL rules) was removed with the legacy shell; its six drawer cases were replaced by the Kit shell block in the same file, which asserts the kit Sidebar Sheet anchoring by side. Net 21 -> 19 is the realignment, not a weakening. Release-green base-red #17219 (2026-10-24)."
"tests/unit/ui/rtl-logical-classes.test.tsx": "ec27d84e (KEA-7886, F4, 2026-10-21): the legacy mobile sidebar drawer (.dashboard-sidebar-mobile, start-0/-translate-x-full RTL rules) was removed with the legacy shell; its six drawer cases were replaced by the Kit shell block in the same file, which asserts the kit Sidebar Sheet anchoring by side. Net 21 -> 19 is the realignment, not a weakening. Release-green base-red #17219 (2026-10-24).",
"tests/unit/mergify-queue-config.test.ts": "PR #20616 (2026-11-19): the owner retired the Mergify merge queue, so .mergify.yml no longer carries queue_rules, merge_protections_settings or pull_request_rules. The 10 tests that pinned the release and relay-integration queue rules (squash method, label/draft/conflict conditions, the fail-closed anchor check, paid-tier and deprecated keys, integration routing and admission) have no surface left to assert. They are replaced by 5 tests of what remains: the file holds only commands_restrictions, no queue or auto-merge key exists, each of the 7 commands that merge or rewrite a pull request keeps an unsatisfiable condition list, and the two rules that outlive Mergify (checks timeout >= 2x the measured quality.yml p95; Gate / CI, Gate / Quality and Merge integrity required) are now asserted against omni-queue's config. The replacement queue's own admission contract is pinned in tests/unit/merge-queue/. Net 28 -> 11 is a retired surface, not a weakening. Prune after v3.8.55 merges to main."
}

View File

@@ -47,6 +47,12 @@ separate administrative change; adding these jobs does not itself protect a bran
### Merge queue
> **2026-11-19: the Mergify merge queue is retired** (owner's decision). `.mergify.yml` no
> longer defines a queue and refuses the Mergify commands that merge or rewrite a pull request.
> Release PRs are merged by hand under the repository ruleset "Require green gates on the active
> release" (`Gate / CI` + `Gate / Quality`) until omni-queue runs in live mode, and through
> omni-queue after that ([OMNI_QUEUE.md](../ops/OMNI_QUEUE.md)). The workflow handling of Mergify drafts described below is still in `ci.yml` and `quality.yml`, but no Mergify draft is opened any more.
The `queue` label sends a PR to the Mergify queue (`.mergify.yml`). Mergify opens a draft PR on
a `mergify/merge-queue/` branch, CI runs the full selection there, and the original PR merges
when `Gate / CI`, `Gate / Quality` and `Merge integrity (changelog + generated skills)` pass.

View File

@@ -7,7 +7,7 @@ lastUpdated: 2026-07-22
OmniRoute uses a **parallel-cycle** release model: a dedicated `release/vX.Y.Z`
branch for the active cycle, `main` for the published line, and an immutable
`vX.Y.Z` tag when that cycle ships. Seeing commits land on `release/*` *and* on
`vX.Y.Z` tag when that cycle ships. Seeing commits land on `release/*` _and_ on
`main` is expected — not a mix-up.
Maintainer detail lives in `CLAUDE.md` (Hard Rule #21) and
@@ -16,11 +16,11 @@ contributor-facing summary.
## At a glance
| Ref | Role |
| --- | --- |
| `release/vX.Y.Z` | **Active cycle** — day-to-day development and PR merges for that version |
| `main` | **Published line** — receives the cycle via squash-merge when the release ships |
| `vX.Y.Z` (tag) | **Ship marker** — immutable “what shipped” pointer cut at release time |
| Ref | Role |
| ---------------- | ------------------------------------------------------------------------------- |
| `release/vX.Y.Z` | **Active cycle** — day-to-day development and PR merges for that version |
| `main` | **Published line** — receives the cycle via squash-merge when the release ships |
| `vX.Y.Z` (tag) | **Ship marker** — immutable “what shipped” pointer cut at release time |
```mermaid
flowchart LR
@@ -63,12 +63,18 @@ gh issue list --repo diegosouzapw/OmniRoute --label release-freeze --state open
Merge mechanics (owner `queue` label → Mergify) are documented in
[MERGE_TRAIN.md](./MERGE_TRAIN.md).
> **2026-11-19: the Mergify merge queue is retired** (owner's decision). `.mergify.yml` no
> longer defines a queue and refuses the Mergify commands that merge or rewrite a pull request.
> Release PRs are merged by hand under the repository ruleset "Require green gates on the active
> release" (`Gate / CI` + `Gate / Quality`) until omni-queue runs in live mode, and through
> omni-queue after that ([OMNI_QUEUE.md](./OMNI_QUEUE.md)). The `queue` label no longer merges anything.
## Why both a branch and a tag?
| Artifact | Lifetime | Purpose |
| -------- | -------- | ------- |
| `release/vX.Y.Z` | In-flight cycle | Collects reviewed PRs, stays CI-green, is the PR base |
| Tag `vX.Y.Z` | Forever | Marks the exact bits that shipped to npm / GitHub Releases |
| Artifact | Lifetime | Purpose |
| ---------------- | --------------- | ---------------------------------------------------------- |
| `release/vX.Y.Z` | In-flight cycle | Collects reviewed PRs, stays CI-green, is the PR base |
| Tag `vX.Y.Z` | Forever | Marks the exact bits that shipped to npm / GitHub Releases |
The branch is the workshop; the tag is the sealed package. After squash-merge to
`main`, the next cycle continues on `release/vX+1` without waiting for the prior

View File

@@ -26,15 +26,15 @@ How to use it:
Only the gates of the 3.8.x rail. G3–G10 belong to the v4 phases (modular platform) and are
not part of the LTS decision.
| Gate | What must hold | How to prove | Evidence |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| G0 | PRs to `release/**` (the `quality.yml` lane) run the same ratchets and security gates as PRs to `main` | `Gate / Quality` green on the 3.9.0 release PR: `gh pr checks <release-PR>`; locally `npm run quality:ratchet` | |
| G1 | `check:known-symbols` is registry-aware (no regex false negatives on registered strategies/executors) | `npm run check:known-symbols` | |
| G2 | Every god-file slice left file size and quality metrics at or below baseline (no own-growth without the owner's explicit approval) | `npm run check:file-size` and `npm run quality:ratchet` on the tip; every change to `config/quality/quality-baseline.json` in the cycle (`git log -p origin/main..HEAD -- config/quality/quality-baseline.json`) lowers a number or links the owner's approval | |
| G11 | Mergify queue `release` active: `queue_rules` present, `checks_timeout` defined, label `queue` exists; `--admin merge` is not used (GitHub's native merge queue was rejected in v3.8.49 — no branch wildcards on a personal-account repo, see the `.mergify.yml` header; batching is blocked by the Mergify plan tier) | `npm run release:dry-run-lts-cut -- --from <tip>` shows `✓ merge-queue` (reads `.mergify.yml` at the tip + the `queue` label) and `✓ release-ruleset` (the `release/*` ruleset keeps `deletion` + `non_fast_forward`); no `--admin` merge in the cycle | |
| G12 | `Gate / CI` and `Gate / Quality` are the required status rollups and fail when any job they need fails | `gh pr checks <release-PR>` shows both rollups green; a deliberately red job on a scratch PR turns its rollup red | |
| G13 | The golden sets that pinned behavior before the `combo.ts` / `chatCore.ts` decomposition still pass | `node --import tsx/esm --test tests/unit/g13-combo-chatcore-golden.test.ts tests/unit/executor-map-golden.test.ts tests/unit/provider-translate-path-golden.test.ts` | |
| G14 | `no-restricted-imports` boundaries hold (no `localDb.ts` barrel import outside `src/lib/db/`, no `open-sse/executors/**` in `src/app/**`) | `npm run lint` and `node --import tsx/esm --test tests/unit/eslint-import-boundaries.test.ts` | |
| Gate | What must hold | How to prove | Evidence |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| G0 | PRs to `release/**` (the `quality.yml` lane) run the same ratchets and security gates as PRs to `main` | `Gate / Quality` green on the 3.9.0 release PR: `gh pr checks <release-PR>`; locally `npm run quality:ratchet` | |
| G1 | `check:known-symbols` is registry-aware (no regex false negatives on registered strategies/executors) | `npm run check:known-symbols` | |
| G2 | Every god-file slice left file size and quality metrics at or below baseline (no own-growth without the owner's explicit approval) | `npm run check:file-size` and `npm run quality:ratchet` on the tip; every change to `config/quality/quality-baseline.json` in the cycle (`git log -p origin/main..HEAD -- config/quality/quality-baseline.json`) lowers a number or links the owner's approval | |
| G11 | omni-queue lands the release PRs: `config/merge-queue/config.json` passes omni-queue's validator (queue label, `checksTimeoutMinutes`), its `bases` manage the release branch, `mode` is `live` (shadow lands nothing), and its label exists; `--admin merge` is not used (the Mergify `release` queue G11 checked before was retired on 2026-11-19, see the `.mergify.yml` header) | `npm run release:dry-run-lts-cut -- --from <tip>` shows `✓ merge-queue` (reads `config/merge-queue/config.json` at the tip + its label) and `✓ release-ruleset` (the `release/*` ruleset keeps `deletion` + `non_fast_forward`); no `--admin` merge in the cycle | |
| G12 | `Gate / CI` and `Gate / Quality` are the required status rollups and fail when any job they need fails | `gh pr checks <release-PR>` shows both rollups green; a deliberately red job on a scratch PR turns its rollup red | |
| G13 | The golden sets that pinned behavior before the `combo.ts` / `chatCore.ts` decomposition still pass | `node --import tsx/esm --test tests/unit/g13-combo-chatcore-golden.test.ts tests/unit/executor-map-golden.test.ts tests/unit/provider-translate-path-golden.test.ts` | |
| G14 | `no-restricted-imports` boundaries hold (no `localDb.ts` barrel import outside `src/lib/db/`, no `open-sse/executors/**` in `src/app/**`) | `npm run lint` and `node --import tsx/esm --test tests/unit/eslint-import-boundaries.test.ts` | |
## Closing battery

View File

@@ -4,6 +4,12 @@ title: Merge Queue & Manual Merge-Train Runbook
# Merge Queue & Manual Merge-Train Runbook
> **2026-11-19: the Mergify merge queue is retired** (owner's decision). `.mergify.yml` no
> longer defines a queue and refuses the Mergify commands that merge or rewrite a pull request.
> Release PRs are merged by hand under the repository ruleset "Require green gates on the active
> release" (`Gate / CI` + `Gate / Quality`) until omni-queue runs in live mode, and through
> omni-queue after that ([OMNI_QUEUE.md](./OMNI_QUEUE.md)). The Mergify sections below describe the queue as it was.
Since v3.8.49 (WS3.2/WS3.4 of the quality/velocity plan) the default merge path for
reviewed PRs into `release/vX.Y.Z` is the **Mergify merge queue** (`.mergify.yml`);
the **manual merge-train** documented below is the FALLBACK — used during incidents,

View File

@@ -12,6 +12,13 @@ the default `mode` in `config/merge-queue/config.json` is `shadow` (compose and
Until the owner approves the cut-over (see [Cut-over and rollback](#cut-over-and-rollback)), Mergify
and the `queue` label stay the default merge path.
> **2026-11-19: the Mergify merge queue is retired** (owner's decision; step 1 of
> [Cut-over and rollback](#cut-over-and-rollback)). `.mergify.yml` no longer defines a queue and
> refuses the Mergify commands that merge or rewrite a pull request. Until omni-queue runs in live
> mode, release PRs are merged by hand under the repository ruleset "Require green gates on the
> active release" (`Gate / CI` + `Gate / Quality`); mentions below of Mergify as the current merge
> path describe the state before that date.
## Why
- **Cost.** Mergify bills per active contributor seat, and batching with automatic bisection is a

View File

@@ -4,6 +4,12 @@ title: Relay integration queue
# Relay integration queue
> **2026-11-19: the Mergify merge queue is retired** (owner's decision). `.mergify.yml` no
> longer defines a queue and refuses the Mergify commands that merge or rewrite a pull request.
> Release PRs are merged by hand under the repository ruleset "Require green gates on the active
> release" (`Gate / CI` + `Gate / Quality`) until omni-queue runs in live mode, and through
> omni-queue after that ([OMNI_QUEUE.md](./OMNI_QUEUE.md)). The `relay-integration` rule described below was removed with it.
The opt-in `relay-integration` rule in `.mergify.yml` handles one precomposed,
owner-reviewed PR. It does not enable Mergify batching, change a subscription,
replace contributor PRs, or waive their acceptance requirements. Ordinary PRs

View File

@@ -420,8 +420,8 @@ grafted parent, so cut from a full clone or `git fetch --unshallow origin` first
tag exists, `package.json` is the target version, a `release-freeze` issue is open, no open
`Release branch not green` issue
on an existing release branch — a branch that does not exist reports `?` unknown, never
green — the Mergify `release` queue is configured (G11: `queue_rules`, `checks_timeout`,
label `queue`), the `release/*` ruleset still blocks deletion and force-push, and
green — omni-queue lands the release PRs (G11: `config/merge-queue/config.json` valid, its
`bases` manage the release branch, `mode` `live`, its label exists), the `release/*` ruleset still blocks deletion and force-push, and
`stable/v3` and `develop` do not exist yet), the two branch steps, which dormant-workflow
triggers and `if:` conditions turn true (and which stay gated by a repository variable or
pinned to the canonical repository), the expected dist-tags (`latest` → 3.9.0, `next` and

View File

@@ -170,3 +170,9 @@ is the per-listener memory budget above (ceiling 6 listeners), not CPU. The rema
are process ones: land campaign PRs through the Mergify queue (`label=queue`, batches share
one `merge_group` CI run instead of one run per PR plus one per push), trim the CodeQL
default-setup languages, and filter `release-acceptance.yml` by the files it reads.
> **2026-11-19: the Mergify merge queue is retired** (owner's decision). `.mergify.yml` no
> longer defines a queue and refuses the Mergify commands that merge or rewrite a pull request.
> Release PRs are merged by hand under the repository ruleset "Require green gates on the active
> release" (`Gate / CI` + `Gate / Quality`) until omni-queue runs in live mode, and through
> omni-queue after that ([OMNI_QUEUE.md](./OMNI_QUEUE.md)). The Mergify lever above no longer exists.

View File

@@ -96,14 +96,32 @@ inside your feature branch (a base-red fix is its own freeze-gated `fix/release-
PR); and if you must open a PR anyway, add `⚠️ base-red inherited: #<issue>` to the PR body so
reviewers and CI babysitters do not chase ghosts.
## Sync-back landings are fast-forward, never squash
## Sync-back landings are merge commits, never squash
A `main → release/vX+1` sync-back (Phase 5 of `/generate-release`, or any later "bring main's
post-release commits over" PR) must reach the release branch as the merge commit it already is:
`git merge-base --is-ancestor origin/release/vX+1 <head>` then
`git push origin <head>:refs/heads/release/vX+1` (GitHub marks the PR merged). Squash-merging it
drops `main` from the release branch's ancestry and the next sync-back re-conflicts on every file
main touched (551 conflicts on the v3.8.50 → v3.8.51 sync before the two-step merge). After
landing, `git merge-base --is-ancestor origin/main origin/release/vX+1` must be true — and check
that `config/quality/eslint-suppressions.json` / `quality-baseline.json` carried main's freezes
(they merge as "ours" silently). Details: `.agents/skills/generate-release/phases/phase-5-next-cycle.md`.
post-release commits over" PR) reaches the release branch through a pull request, and that PR
lands as a **merge commit**. `release/vX+1` is the repository's default branch, and ruleset
21899981 ("Require PR on default branch", no bypass actors) refuses a direct push to it.
`node scripts/release/sync-next-cycle.mjs <X+1>` does the merge in a temporary detached
worktree, runs `validate-release-green.mjs --quick` on the merged tree (unless
`--skip-green-gate`), pushes the merge commit to the side branch
`chore/sync-back-main-<first 12 hex of origin/main>` and opens a PR from it into
`release/vX+1`. It never pushes to the release branch and never merges the PR. Re-running it
after the side branch reached origin prints the open PR (or opens it) and stops. Its
`--direct-push` flag keeps the old push to the release branch for a repository without such a
ruleset; this repository refuses it.
Landing the PR:
1. Merge it with **Create a merge commit**, never squash or rebase. A squash drops `main` from
the release branch's ancestry and the next sync-back re-conflicts on every file main touched
(551 conflicts on the v3.8.50 → v3.8.51 sync before the two-step merge).
2. The required gates must be green on the PR head before landing.
3. After landing, `git merge-base --is-ancestor origin/main origin/release/vX+1` must be true —
and check that `config/quality/eslint-suppressions.json` / `quality-baseline.json` carried
main's freezes (they merge as "ours" silently).
A sync-back done by hand follows the same path: merge `origin/main` on a side branch, open a PR
into `release/vX+1`, land it as a merge commit (#20522 is the v3.8.54 → v3.8.55 example).
Details: `.agents/skills/generate-release/phases/phase-5-next-cycle.md`.

View File

@@ -3,9 +3,12 @@
*
* `full`/absent → whole text (backward-compat). All modes are fail-safe:
* incoherent params or an unsafe regex yield { error }, never throw. The grep
* mode validates the pattern with `safe-regex` (no catastrophic backtracking)
* before compiling, and bounds matches/pattern length.
* mode validates the pattern with `safe-regex` (no nested quantifiers), allows at
* most one unbounded quantifier, bounds matches/pattern length, and runs the scan
* under a wall-clock budget (CodeQL #1349): a caller-supplied pattern can still be
* super-linear (`.*x` is quadratic per line), so the budget is the hard bound.
*/
import vm from "node:vm";
import safeRegex from "safe-regex";
export type CcrMode = "full" | "head" | "tail" | "lines" | "grep" | "stats";
@@ -24,6 +27,8 @@ export type CcrQueryResult = { content: string } | { error: string };
export const MAX_RANGE_LINES = 10_000;
export const MAX_GREP_MATCHES = 1_000;
export const MAX_PATTERN_LEN = 512;
/** Wall-clock budget for one grep scan over a block (ms). */
export const GREP_TIME_BUDGET_MS = 1_000;
const err = (m: string): CcrQueryResult => ({ error: m });
const ok = (c: string): CcrQueryResult => ({ content: c });
@@ -53,30 +58,104 @@ function sliceLines(lines: string[], start?: number, end?: number): CcrQueryResu
return ok(lines.slice(start - 1, Math.min(end, lines.length)).join("\n"));
}
function grepLines(lines: string[], pattern?: string, unique?: boolean): CcrQueryResult {
/**
* Number of unbounded quantifiers (`*`, `+`, `{n,}`) outside character classes and
* escapes. Two or more in sequence make the backtracking polynomial in the line length
* (`.*.*.*.*x` is O(n^4)), which `safe-regex`'s star-height check does not catch.
*/
export function countUnboundedQuantifiers(pattern: string): number {
let count = 0;
let i = 0;
while (i < pattern.length) {
const c = pattern[i];
if (c === "\\") {
i += 2;
} else if (c === "[") {
i = classEnd(pattern, i);
} else {
if (c === "*" || c === "+" || (c === "{" && isOpenRange(pattern, i))) count++;
i++;
}
}
return count;
}
/** Index just past the character class that opens at `start` (escapes honoured). */
function classEnd(pattern: string, start: number): number {
let i = start + 1;
while (i < pattern.length && pattern[i] !== "]") i += pattern[i] === "\\" ? 2 : 1;
return i + 1;
}
/** True when an open range quantifier `{n,}` starts at `start`. */
function isOpenRange(pattern: string, start: number): boolean {
let j = start + 1;
while (j < pattern.length && pattern[j] >= "0" && pattern[j] <= "9") j++;
return j > start + 1 && pattern[j] === "," && pattern[j + 1] === "}";
}
// The scan runs in a dedicated context only so `timeout` can stop a runaway regex.
// No host object enters it: inputs are primitives, the result leaves as a JSON string.
const GREP_SCRIPT = new vm.Script(`(() => {
"use strict";
let re;
try { re = new RegExp(grepPattern); } catch { return JSON.stringify({ invalid: true }); }
const matched = [];
let truncated = false;
for (const line of grepText.split("\\n")) {
if (re.test(line)) {
matched.push(line);
if (matched.length >= grepMaxMatches) { truncated = true; break; }
}
}
return JSON.stringify({ matched, truncated });
})()`);
let grepContext: vm.Context | null = null;
function runGrepScan(
text: string,
pattern: string
): { matched: string[]; truncated: boolean } | "invalid" | "timeout" {
grepContext ??= vm.createContext(Object.create(null), {
codeGeneration: { strings: false, wasm: false },
});
grepContext.grepPattern = pattern;
grepContext.grepText = text;
grepContext.grepMaxMatches = MAX_GREP_MATCHES;
let raw: unknown;
try {
raw = GREP_SCRIPT.runInContext(grepContext, { timeout: GREP_TIME_BUDGET_MS });
} catch (e) {
if ((e as { code?: string })?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") return "timeout";
throw e;
} finally {
grepContext.grepText = "";
grepContext.grepPattern = "";
}
const parsed = JSON.parse(String(raw)) as {
invalid?: boolean;
matched?: string[];
truncated?: boolean;
};
if (parsed.invalid === true) return "invalid";
return { matched: parsed.matched ?? [], truncated: parsed.truncated === true };
}
function grepLines(text: string, pattern?: string, unique?: boolean): CcrQueryResult {
if (!pattern) return err("grep requires a 'pattern'");
if (pattern.length > MAX_PATTERN_LEN) return err(`pattern exceeds ${MAX_PATTERN_LEN} chars`);
if (!safeRegex(pattern)) return err("pattern rejected: potentially catastrophic backtracking");
let re: RegExp;
try {
re = new RegExp(pattern);
} catch {
return err("invalid regex pattern");
if (countUnboundedQuantifiers(pattern) > 1) {
return err("pattern rejected: at most one unbounded quantifier (*, +, {n,}) is allowed");
}
const matched: string[] = [];
let truncated = false;
for (const line of lines) {
if (re.test(line)) {
matched.push(line);
if (matched.length >= MAX_GREP_MATCHES) {
truncated = true;
break;
}
}
const scan = runGrepScan(text, pattern);
if (scan === "invalid") return err("invalid regex pattern");
if (scan === "timeout") {
return err(`grep exceeded its ${GREP_TIME_BUDGET_MS} ms time budget; use a narrower pattern`);
}
const out = unique ? [...new Set(matched)] : matched;
const out = unique ? [...new Set(scan.matched)] : scan.matched;
const body = out.join("\n");
return ok(truncated ? `${body}\n…[truncated at ${MAX_GREP_MATCHES} matches]` : body);
return ok(scan.truncated ? `${body}\n…[truncated at ${MAX_GREP_MATCHES} matches]` : body);
}
function blockStats(text: string, lines: string[]): CcrQueryResult {
@@ -101,7 +180,7 @@ export function queryBlock(text: string, q: CcrQuery): CcrQueryResult {
case "lines":
return sliceLines(lines, q.start, q.end);
case "grep":
return grepLines(lines, q.pattern, q.unique);
return grepLines(text, q.pattern, q.unique);
case "stats":
return blockStats(text, lines);
default:

View File

@@ -10,7 +10,9 @@
const JSON_NUMBER_RE = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
const NUMERIC_LIKE_RE = /^[+-]\.?\d|^\.\d|^0\d/;
const INLINE_ARRAY_RE = /\[[^\]]*\]\s*:/;
// `[` excluded from the bracket body keeps the scan linear on runs of `[` (CodeQL #1301).
// Same verdict for .test(): any match can restart at the last `[` before its `]`.
const INLINE_ARRAY_RE = /\[[^[\]]*\]\s*:/;
/** Check if a string value must be quoted per Section 2.4. */
export function needsQuote(s: string): boolean {

View File

@@ -106,7 +106,10 @@ export function maybePersistRtkRawOutput(
const maxBytes = Math.max(1024, Math.floor(options.maxBytes ?? 1_048_576));
const redaction = redactRtkRawOutput(safeUtf8Slice(raw, maxBytes));
const now = Date.now();
// Bound the client-supplied command before the regex passes (CodeQL #1302): the slug
// keeps at most 48 chars, so 256 raw chars leave the result unchanged for real commands.
const commandSlug = (options.command || "tool-output")
.slice(0, 256)
.replace(/[^A-Za-z0-9_-]+/g, "_")
.replace(/^_+|_+$/g, "")
.slice(0, 48);

View File

@@ -42,6 +42,13 @@ import { createInterface } from "node:readline/promises";
import { fileURLToPath } from "node:url";
import { load as yamlLoad } from "js-yaml";
import { resolveDistTag } from "./dist-tag.mjs";
import {
isManagedBase,
validateConfig as validateMergeQueueConfig,
} from "../merge-queue/config.mjs";
/** omni-queue's configuration, read at the cut source (rail gate G11). */
const MERGE_QUEUE_CONFIG = "config/merge-queue/config.json";
export const CANONICAL_REPO = "cheaper-inference/OmniRoute";
/** Former names GitHub still redirects to the canonical repository (transfer of 2026-10-21). */
@@ -181,38 +188,45 @@ export function isCanonicalRemoteUrl(url, repo = CANONICAL_REPO) {
// ── preconditions ───────────────────────────────────────────────────────────
/**
* Pure: is the Mergify `release` queue (rail gate G11) configured? GitHub's native
* merge queue was rejected in v3.8.49 (no branch wildcards on a personal-account
* repo — see the .mergify.yml header), so G11 is the Mergify queue: a
* `queue_rules` entry named `release` covering `release/vX.Y.Z`, entered through
* the `queue` label, with a `checks_timeout` so a hung check cannot park the queue.
* Pure: does a merge queue land the release PRs (rail gate G11)? The Mergify
* `release` queue that G11 checked until 2026-11-19 was retired by the owner that
* day (see the .mergify.yml header); the release merge queue is omni-queue
* (docs/ops/OMNI_QUEUE.md). G11 holds when `config/merge-queue/config.json` at the
* source passes omni-queue's own validator (which requires a queue `label` and a
* `checksTimeoutMinutes`, so a hung check cannot park the queue), its `bases`
* manage the cut's release branch, and its `mode` is `live`. `shadow` is a
* configured queue that lands nothing — release PRs are then merged by hand — so it
* is a NO-GO for G11, reported with the mode (`--advisory merge-queue` downgrades it).
*/
export function evaluateMergifyQueue(yamlText) {
if (yamlText == null) return { ok: false, problems: [".mergify.yml missing at the source"] };
let doc;
export function evaluateMergeQueue(jsonText, releaseBranch) {
if (jsonText == null) {
return { ok: false, problems: [`${MERGE_QUEUE_CONFIG} missing at the source`], label: null };
}
let raw;
try {
doc = yamlLoad(yamlText) ?? {};
raw = JSON.parse(jsonText);
} catch {
return { ok: false, problems: [".mergify.yml is not valid YAML"] };
return { ok: false, problems: [`${MERGE_QUEUE_CONFIG} is not valid JSON`], label: null };
}
const rules = Array.isArray(doc.queue_rules) ? doc.queue_rules : [];
const release = rules.find((rule) => rule?.name === "release");
if (!release) return { ok: false, problems: ["no queue_rules entry named `release`"] };
const result = validateMergeQueueConfig(raw);
if (!result.ok) {
return {
ok: false,
problems: [`${MERGE_QUEUE_CONFIG} is invalid: ${result.errors.join(", ")}`],
label: null,
};
}
const { config } = result;
const problems = [];
const conditions = (release.queue_conditions ?? []).map((c) => String(c).replace(/\s+/g, ""));
if (!conditions.some((c) => c.startsWith("base~=") && c.includes("release/"))) {
problems.push("queue `release` does not target release/* branches");
if (!isManagedBase(config, releaseBranch)) {
problems.push(`omni-queue \`bases\` (${config.bases}) does not manage ${releaseBranch}`);
}
const autoMerge = (doc.merge_protections_settings?.auto_merge_conditions ?? []).map((c) =>
String(c).replace(/\s+/g, "")
);
if (!conditions.includes("label=queue") && !autoMerge.includes("label=queue")) {
problems.push("queue `release` is not entered through the `queue` label");
if (config.mode !== "live") {
problems.push(
`omni-queue mode is \`${config.mode}\`: it lands nothing, release PRs are merged by hand`
);
}
if (release.checks_timeout == null || String(release.checks_timeout).trim() === "") {
problems.push("queue `release` has no checks_timeout");
}
return { ok: problems.length === 0, problems };
return { ok: problems.length === 0, problems, label: config.label, mode: config.mode };
}
function issueList(issues) {
@@ -234,7 +248,7 @@ export function evaluatePreconditions(facts, opts) {
});
const freeze = facts.freezeIssues;
const red = facts.baseRedIssues;
const queue = evaluateMergifyQueue(facts.mergifyConfig ?? null);
const queue = evaluateMergeQueue(facts.mergeQueueConfig ?? null, opts.sourceBranch);
const rulesetRules = facts.releaseRulesetRules;
const missingRules = Array.isArray(rulesetRules)
? ["deletion", "non_fast_forward"].filter((r) => !rulesetRules.includes(r))
@@ -317,19 +331,21 @@ export function evaluatePreconditions(facts, opts) {
},
check(
"merge-queue",
"G11: Mergify queue `release` active (queue_rules, checks_timeout, `queue` label)",
"queue_rules[release] with checks_timeout + label `queue` exists",
`G11: omni-queue lands the release PRs of ${opts.sourceBranch} (valid config, mode live, label)`,
`${MERGE_QUEUE_CONFIG} valid, bases manage ${opts.sourceBranch}, mode \`live\`, queue label exists`,
queue.ok && facts.queueLabelExists === true,
[
...queue.problems,
facts.queueLabelExists === null
? "label lookup failed"
: facts.queueLabelExists
? null
: "label `queue` missing",
queue.label === null
? null
: facts.queueLabelExists === null
? "label lookup failed"
: facts.queueLabelExists
? null
: `label \`${queue.label}\` missing`,
]
.filter(Boolean)
.join("; ") || "configured"
.join("; ") || `configured (mode ${queue.mode}, label \`${queue.label}\`)`
),
check(
"release-ruleset",
@@ -766,6 +782,10 @@ export function createRealIo(cwd) {
["ls-remote", "--heads", opts.remote, opts.stableBranch, opts.developBranch],
{ cwd }
);
const mergeQueueConfig = sourceSha
? tryExec("git", ["show", `${sourceSha}:${MERGE_QUEUE_CONFIG}`], { cwd })
: null;
const queueLabel = evaluateMergeQueue(mergeQueueConfig, opts.sourceBranch).label;
let remoteBranches = null;
if (headsOut !== null) {
remoteBranches = { [opts.stableBranch]: null, [opts.developBranch]: null };
@@ -781,10 +801,10 @@ export function createRealIo(cwd) {
sourceVersion,
previousTagExists,
sourceBranchExists: branchExists(opts.sourceBranch),
mergifyConfig: sourceSha
? tryExec("git", ["show", `${sourceSha}:.mergify.yml`], { cwd })
: null,
queueLabelExists: labelExists(opts.repo, "queue"),
mergeQueueConfig,
// The label omni-queue reads at the source; without a valid config there is none
// to look up (G11 already fails on the config).
queueLabelExists: queueLabel ? labelExists(opts.repo, queueLabel) : null,
releaseRulesetRules: releaseRulesetRules(opts.repo),
freezeIssues: ghIssues(opts.repo, ["--label", "release-freeze"]),
baseRedIssues: ghIssues(opts.repo, [

View File

@@ -9,16 +9,166 @@
// `## [<NEXT>] — TBD` section (with any bullets it already accumulated) is
// re-inserted on top. Design: _tasks/release-flow/2026-07-04_proposta-ciclo-paralelo-v2.md
//
// Usage: node scripts/release/sync-next-cycle.mjs <nextVersion> e.g. 3.8.45
// Usage: see SYNC_USAGE below (`--help`).
//
// The merge commit lands through a PULL REQUEST: release/vX+1 is the default branch and
// ruleset 21899981 ("Require PR on default branch", no bypass actors) refuses a direct
// push. The script pushes the merge commit to chore/sync-back-main-<sha12> and opens a PR
// into the release branch; it never merges that PR (the owner lands it as a merge commit).
//
// Idempotent: safe to re-run after resolving any conflicts it could not
// auto-resolve (it detects an in-progress merge in its worktree and resumes).
// auto-resolve (it detects an in-progress merge in its worktree and resumes), and
// after the side branch reached origin (it finds the open PR, or opens it, and stops).
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
export const SYNC_USAGE = `usage: node scripts/release/sync-next-cycle.mjs <nextVersion> [--skip-green-gate] [--direct-push]
e.g. node scripts/release/sync-next-cycle.mjs 3.8.45
Merges origin/main into release/v<nextVersion>, pushes the merge commit to the side branch
chore/sync-back-main-<first 12 hex of origin/main> and opens a pull request into the release
branch. It never pushes to the release branch and never merges the PR: land it as a MERGE
COMMIT (never squash or rebase) once the required gates are green.
--skip-green-gate skip the release-green --quick gate on the merged tree (emergency only:
verify first that the tip reds pre-exist on the release branch)
--direct-push push the merge commit straight to the release branch instead of opening
a PR. Off by default, for a repository without a PR-only rule on that
branch: this repository refuses it (ruleset 21899981, "Require PR on
default branch", no bypass actors).
-h, --help print this text`;
/** Pure: parse the CLI (`argv` = process.argv). `next` is null when absent or malformed. */
export function parseSyncArgs(argv) {
const out = { next: null, skipGreenGate: false, directPush: false, help: false, unknown: [] };
for (const arg of argv.slice(2)) {
if (arg === "--skip-green-gate") out.skipGreenGate = true;
else if (arg === "--direct-push") out.directPush = true;
else if (arg === "--help" || arg === "-h") out.help = true;
else if (arg.startsWith("-")) out.unknown.push(arg);
else if (out.next === null && /^\d+\.\d+\.\d+$/.test(arg)) out.next = arg;
else out.unknown.push(arg);
}
return out;
}
/** Pure: the side branch the sync-back merge commit is pushed to. */
export function syncBackBranchName(mainSha) {
const sha = String(mainSha || "").toLowerCase();
if (!/^[0-9a-f]+$/.test(sha)) throw new Error(`not a hex commit SHA: ${mainSha}`);
if (sha.length < 12) throw new Error(`need at least 12 hex characters, got ${sha.length}`);
return `chore/sync-back-main-${sha.slice(0, 12)}`;
}
/** Pure: the push argument array. Only --direct-push targets the release branch. */
export function syncPushArgs({ directPush, branch, sideBranch }) {
const target = directPush ? branch : sideBranch;
return ["push", "origin", `HEAD:refs/heads/${target}`];
}
/** Pure: `owner/name` from a GitHub remote URL (https, scp-style or ssh://), else null. */
export function githubRepoFromRemoteUrl(url) {
const m = String(url || "")
.trim()
.match(/^(?:https:\/\/|ssh:\/\/git@|git@)github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/);
return m ? `${m[1]}/${m[2]}` : null;
}
/** Pure: the sync-back PR title. */
export function syncBackPrTitle(branch) {
return `chore(release): sync-back main → ${branch}`;
}
/** Pure: `gh pr create` argument array (body always through a file). */
export function ghPrCreateArgs({ repo, base, head, title, bodyFile }) {
return [
"pr",
"create",
"--repo",
repo,
"--base",
base,
"--head",
head,
"--title",
title,
"--body-file",
bodyFile,
];
}
/** Pure: `gh pr list` argument array that prints the URL of an OPEN PR head → base (or ""). */
export function ghOpenPrListArgs({ repo, base, head }) {
return [
"pr",
"list",
"--repo",
repo,
"--head",
head,
"--base",
base,
"--state",
"open",
"--json",
"url",
"--jq",
".[0].url // empty",
];
}
function landingRules(branch) {
return [
"Land it as a MERGE COMMIT, never squash or rebase: a squash drops `main` from the release " +
"ancestry and the next sync-back re-conflicts on every file (551 files on v3.8.50 → v3.8.51).",
"The required gates must be green on the head commit before landing.",
"After landing, `git merge-base --is-ancestor origin/main origin/" +
branch +
"` must be true (exit 0).",
];
}
const GREEN_GATE_TEXT = {
passed: "`validate-release-green.mjs --quick` passed on the merged tree before the push.",
skipped:
"skipped with `--skip-green-gate` (the operator verified that the tip reds pre-exist on the release branch).",
};
/** Pure: the sync-back PR body (written to a file and passed with --body-file). */
export function syncBackPrBody({ branch, mainSha, prevVersion, greenGate }) {
const rules = landingRules(branch);
return [
"## Summary",
"",
`Parallel-cycle sync-back: merges \`origin/main\` at \`${String(mainSha).slice(0, 12)}\` ` +
`(v${prevVersion} close) into \`${branch}\`, opened by \`scripts/release/sync-next-cycle.mjs\`. ` +
"The release branch only accepts changes through a pull request (ruleset 21899981).",
"",
`Release-green gate: ${GREEN_GATE_TEXT[greenGate] || "not re-run (PR opened from a side branch already on origin)."}`,
"",
"## How to land",
"",
...rules.map((r, i) => `${i + 1}. ${r}`),
"",
"Also check that `config/quality/eslint-suppressions.json` and `config/quality/quality-baseline.json` " +
"carried main's freezes (they merge as ours silently).",
"",
].join("\n");
}
/** Pure: the final console output — PR URL + the three landing statements as next steps. */
export function syncBackNextSteps({ branch, prUrl }) {
return [
`[sync-next-cycle] sync-back PR: ${prUrl}`,
"Next steps (the script never merges the PR):",
...landingRules(branch).map((r, i) => ` ${i + 1}. ${r}`),
].join("\n");
}
/**
* Pure: insert (or replace) the next cycle's section into main's CHANGELOG.
* - `mainChangelog`: the full CHANGELOG.md content from origin/main (wins verbatim).
@@ -103,7 +253,11 @@ export function extractSection(changelog, version) {
function git(args, opts = {}) {
// maxBuffer: the default 1 MiB overflows on `git show origin/main:CHANGELOG.md`
// (the CHANGELOG alone is >1 MiB) — ENOBUFS found live in the v3.8.45 run (2026-07-06).
return execFileSync("git", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, ...opts }).trim();
return execFileSync("git", args, {
encoding: "utf8",
maxBuffer: 64 * 1024 * 1024,
...opts,
}).trim();
}
// The sync-back is the ONE write path to the release branch with no CI gate — a red
@@ -115,23 +269,123 @@ export function greenGateArgs(argv) {
return ["scripts/quality/validate-release-green.mjs", "--quick"];
}
function gh(args) {
return execFileSync("gh", args, {
encoding: "utf8",
stdio: ["ignore", "pipe", "inherit"],
}).trim();
}
function isAncestor(ancestor, descendant, cwd) {
try {
execFileSync("git", ["merge-base", "--is-ancestor", ancestor, descendant], {
cwd,
stdio: "ignore",
});
return true;
} catch {
return false;
}
}
// Find the open sync-back PR, or open it (body through a temp file + --body-file).
function openSyncBackPr({ repo, branch, side, mainSha, prevVersion, greenGate }) {
const existing = gh(ghOpenPrListArgs({ repo, base: branch, head: side }));
if (existing) return { url: existing, created: false };
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "sync-next-cycle-"));
try {
const bodyFile = path.join(dir, "pr-body.md");
fs.writeFileSync(bodyFile, syncBackPrBody({ branch, mainSha, prevVersion, greenGate }));
const out = gh(
ghPrCreateArgs({
repo,
base: branch,
head: side,
title: syncBackPrTitle(branch),
bodyFile,
})
);
const url = out
.split("\n")
.filter((l) => /\/pull\/\d+\s*$/.test(l))
.pop();
return { url: (url || out).trim(), created: true };
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
function main() {
const NEXT = process.argv[2];
if (!/^\d+\.\d+\.\d+$/.test(NEXT || "")) {
console.error("usage: node scripts/release/sync-next-cycle.mjs <nextVersion> (e.g. 3.8.45)");
const opts = parseSyncArgs(process.argv);
if (opts.help) {
console.log(SYNC_USAGE);
return;
}
if (!opts.next || opts.unknown.length) {
if (opts.unknown.length) {
console.error(`[sync-next-cycle] unknown argument(s): ${opts.unknown.join(" ")}`);
}
console.error(SYNC_USAGE);
process.exit(2);
}
const NEXT = opts.next;
const ROOT = git(["rev-parse", "--show-toplevel"]);
const BRANCH = `release/v${NEXT}`;
const WT = path.join(ROOT, ".claude", "worktrees", `sync-next-${NEXT}`);
git(["fetch", "origin", "main", BRANCH], { cwd: ROOT, stdio: ["ignore", "pipe", "pipe"] });
const prevVersion = JSON.parse(git(["show", "origin/main:package.json"], { cwd: ROOT })).version;
const mainSha = git(["rev-parse", "origin/main"], { cwd: ROOT });
const SIDE = syncBackBranchName(mainSha);
console.log(`[sync-next-cycle] main is v${prevVersion} → syncing into ${BRANCH}`);
let repo = null;
if (!opts.directPush) {
repo = githubRepoFromRemoteUrl(git(["remote", "get-url", "origin"], { cwd: ROOT }));
if (!repo) {
console.error("[sync-next-cycle] ABORT: origin is not a GitHub remote (needed for the PR).");
process.exit(1);
}
// Idempotent: this main commit's side branch is already on origin → reuse it.
const remoteSide = git(["ls-remote", "--heads", "origin", `refs/heads/${SIDE}`], {
cwd: ROOT,
});
if (remoteSide) {
const remoteSha = remoteSide.split(/\s+/)[0];
git(["fetch", "origin", SIDE], { cwd: ROOT, stdio: ["ignore", "pipe", "pipe"] });
if (!isAncestor(mainSha, remoteSha, ROOT)) {
console.error(
`[sync-next-cycle] ABORT: origin/${SIDE} exists but does not contain origin/main ` +
`(${mainSha.slice(0, 12)}) — inspect it by hand; this script never force-pushes.`
);
process.exit(1);
}
const pr = openSyncBackPr({
repo,
branch: BRANCH,
side: SIDE,
mainSha,
prevVersion,
greenGate: "unknown",
});
console.log(
pr.created
? `[sync-next-cycle] ${SIDE} was already on origin — opened its PR.`
: `[sync-next-cycle] ${SIDE} is already on origin with an open PR — nothing to do.`
);
console.log(syncBackNextSteps({ branch: BRANCH, prUrl: pr.url }));
return;
}
}
// Worktree (idempotent — reuse if a previous run left it for conflict resolution).
// Detached at origin/<BRANCH>: the merge commit never moves a local release branch ref
// (and the add does not fail when another checkout already has <BRANCH> checked out).
if (!fs.existsSync(WT)) {
git(["worktree", "add", WT, BRANCH], { cwd: ROOT, stdio: ["ignore", "pipe", "pipe"] });
git(["worktree", "add", "--detach", WT, `origin/${BRANCH}`], {
cwd: ROOT,
stdio: ["ignore", "pipe", "pipe"],
});
}
const mergeHeadPath = git(["rev-parse", "--path-format=absolute", "--git-path", "MERGE_HEAD"], {
cwd: WT,
@@ -162,7 +416,9 @@ function main() {
const merged = insertNextSection(mainChangelog + "\n", nextSection, NEXT);
// Assertions: main's latest section intact + next section present.
if (!merged.includes(`## [${prevVersion}]`)) {
console.error(`[sync-next-cycle] ABORT: main's ## [${prevVersion}] section missing after re-insertion`);
console.error(
`[sync-next-cycle] ABORT: main's ## [${prevVersion}] section missing after re-insertion`
);
process.exit(1);
}
if (!merged.includes(`## [${NEXT}]`)) {
@@ -217,7 +473,14 @@ function main() {
process.exit(1);
}
git(["commit", "-m", `chore(release): sync main (v${prevVersion} close) into ${BRANCH} — parallel-cycle sync-back`], { cwd: WT });
git(
[
"commit",
"-m",
`chore(release): sync main (v${prevVersion} close) into ${BRANCH} — parallel-cycle sync-back`,
],
{ cwd: WT }
);
// WS0.3 green gate: validate the MERGED tree before it reaches origin. The commit
// stays local on failure so the captain can inspect/fix in the sync worktree.
@@ -238,16 +501,46 @@ function main() {
}
fs.rmSync(nm, { force: true });
} else {
console.warn("[sync-next-cycle] ⚠ --skip-green-gate: pushing WITHOUT release-green validation.");
console.warn(
"[sync-next-cycle] ⚠ --skip-green-gate: pushing WITHOUT release-green validation."
);
}
git(["push", "origin", BRANCH], { cwd: WT });
// The side branch is named after mainSha: refuse to push a tree that does not contain it
// (a reused worktree may hold a merge of an older main — re-run to merge the newer one).
if (!opts.directPush && !isAncestor(mainSha, "HEAD", WT)) {
console.error(
`[sync-next-cycle] ABORT: the merged tree in ${WT} does not contain origin/main ` +
`(${mainSha.slice(0, 12)}) — re-run this script to merge it.`
);
process.exit(1);
}
const left = git(["rev-list", "--count", `${BRANCH}..origin/main`], { cwd: WT });
console.log(`[sync-next-cycle] pushed. origin/main commits not in ${BRANCH}: ${left} (expected 0)`);
// Default: side branch + PR (ruleset 21899981 refuses a push to the release branch).
const target = opts.directPush ? BRANCH : SIDE;
git(syncPushArgs({ directPush: opts.directPush, branch: BRANCH, sideBranch: SIDE }), { cwd: WT });
const left = git(["rev-list", "--count", "HEAD..origin/main"], { cwd: WT });
console.log(
`[sync-next-cycle] pushed ${target}. origin/main commits not in it: ${left} (expected 0)`
);
git(["worktree", "remove", "--force", WT], { cwd: ROOT });
console.log("[sync-next-cycle] done — worktree removed.");
console.log("[sync-next-cycle] worktree removed.");
if (opts.directPush) {
console.log(`[sync-next-cycle] done — --direct-push landed the merge commit on ${BRANCH}.`);
return;
}
const pr = openSyncBackPr({
repo,
branch: BRANCH,
side: SIDE,
mainSha,
prevVersion,
greenGate: gate ? "passed" : "skipped",
});
console.log(syncBackNextSteps({ branch: BRANCH, prUrl: pr.url }));
}
if (import.meta.url === pathToFileURL(process.argv[1] || "").href) main();

View File

@@ -217,8 +217,7 @@ test("resolveTargetTimeoutMs provided: uses per-target timeout when present", as
});
}),
comboTargetTimeoutMs: 20,
resolveTargetTimeoutMs: async (target) =>
target?.connectionId === "conn-1" ? 50 : undefined,
resolveTargetTimeoutMs: async (target) => (target?.connectionId === "conn-1" ? 50 : undefined),
log: noopLog,
});
const res = await runner({}, "slow-model", {
@@ -253,26 +252,31 @@ test("resolveTargetTimeoutMs without connection: falls back to comboTargetTimeou
assert.equal(aborted, true);
});
test("resolveTargetTimeoutMs extended: 50ms outlives the 20ms base (does not abort at 20ms)", async () => {
let resolvedWith = "";
test("resolveTargetTimeoutMs extended: a 45ms response survives the 20ms base", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const dispatched = Promise.withResolvers<AbortSignal | null | undefined>();
const upstream = Promise.withResolvers<Response>();
const runner = buildTargetTimeoutRunner({
handleSingleModel: async (_b, _m, target) => {
await new Promise((resolve) => {
target?.modelAbortSignal?.addEventListener("abort", resolve);
setTimeout(resolve, 45);
});
resolvedWith = target?.modelAbortSignal?.aborted ? "aborted" : "completed";
return new Response(resolvedWith, { status: resolvedWith === "aborted" ? 599 : 200 });
handleSingleModel: (_body, _model, target) => {
dispatched.resolve(target?.modelAbortSignal);
return upstream.promise;
},
comboTargetTimeoutMs: 20,
resolveTargetTimeoutMs: async (target) =>
target?.connectionId === "conn-1" ? 50 : undefined,
target && "connectionId" in target && target.connectionId === "conn-1" ? 50 : undefined,
log: noopLog,
});
const res = await runner({}, "slow-model", {
connectionId: "conn-1",
modelAbortSignal: undefined as unknown as AbortSignal,
} as SingleModelTarget);
const pending = runner({}, "slow-model", { connectionId: "conn-1" } as SingleModelTarget);
const signal = await dispatched.promise;
assert.ok(signal);
t.mock.timers.tick(20);
assert.equal(signal.aborted, false, "the base timeout must not abort this target");
t.mock.timers.tick(25);
assert.equal(signal.aborted, false, "the target must still be active at 45ms");
upstream.resolve(new Response("completed"));
const res = await pending;
assert.equal(res.status, 200);
assert.equal(resolvedWith, "completed");
assert.equal(await res.text(), "completed");
});

View File

@@ -0,0 +1,219 @@
/**
* Regex work in the compression engines stays bounded on hostile input
* (CodeQL #1301, #1302, #1349).
*
* - #1301 headroom/gcf needsQuote(): the inline-array check ran in O(n^2) on runs of `[`.
* - #1302 rtk maybePersistRtkRawOutput(): the command slug trim ran in O(n^2) on runs of `_`
* from a client-supplied tool_use command of unbounded length.
* - #1349 ccr grep: a caller-supplied pattern such as `.*.*.*.*x` passed the star-height
* gate and blocked the event loop for minutes on a single long line.
*
* Each block pairs a timing assertion (the pathological input finishes fast or is refused)
* with a behaviour assertion (ordinary input gives the same result as before).
*/
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { needsQuote } from "../../../open-sse/services/compression/engines/headroom/gcf/scalar.ts";
import { maybePersistRtkRawOutput } from "../../../open-sse/services/compression/engines/rtk/rawOutput.ts";
import { queryBlock } from "../../../open-sse/services/compression/engines/ccr/ccrQuery.ts";
/** Ceiling for the fixed paths. They run in a few ms when idle; before the fix the same
* inputs took 10 s (#1301), 21 s (#1302) and minutes (#1349). The headroom absorbs a loaded
* CI runner (one fixed case reached 806 ms at load average 44) without hiding a regression. */
const FAST_MS = 1_000;
/** Upper bound for a grep stopped by its 1 s time budget (budget plus scheduling slack). */
const BUDGET_CEILING_MS = 5_000;
function timed<T>(fn: () => T): { value: T; ms: number } {
const t0 = performance.now();
const value = fn();
return { value, ms: performance.now() - t0 };
}
/** Reference semantics of the SPEC 2.4 inline-array rule: some `[` whose first following
* `]` is followed by optional whitespace and a `:`. Written as a plain linear scan. */
function hasInlineArrayHeader(s: string): boolean {
for (let i = 0; i < s.length; i++) {
if (s[i] !== "[") continue;
const close = s.indexOf("]", i + 1);
if (close === -1) return false;
let k = close + 1;
while (k < s.length && /\s/.test(s[k])) k++;
if (s[k] === ":") return true;
}
return false;
}
/** Deterministic PRNG (mulberry32) so the equivalence sample is reproducible. */
function prng(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
describe("#1301 headroom/gcf needsQuote inline-array check", () => {
it("finishes fast on 50k '[' characters", () => {
for (const s of [
"[".repeat(50_000),
"a" + "[".repeat(50_000) + "]",
"[".repeat(50_000) + "]x",
]) {
const { value, ms } = timed(() => needsQuote(s));
assert.equal(value, false);
assert.ok(ms < FAST_MS, `needsQuote took ${ms.toFixed(1)}ms on ${s.length} chars`);
}
});
it("keeps the same verdict on ordinary values", () => {
assert.equal(needsQuote("ERR[404]: Not Found"), true);
assert.equal(needsQuote("[Speaker 1]: Hello"), true);
assert.equal(needsQuote("a[[b]: c"), true);
assert.equal(needsQuote("x[a[b] :y"), true);
assert.equal(needsQuote("arr[0] index"), false);
assert.equal(needsQuote("a]: [b"), false);
assert.equal(needsQuote("a[b] c: d"), false);
});
it("matches the reference rule on a random sample", () => {
const rand = prng(1301);
const alphabet = "[]: ab";
for (let n = 0; n < 20_000; n++) {
const len = Math.floor(rand() * 12);
let body = "";
for (let i = 0; i < len; i++) body += alphabet[Math.floor(rand() * alphabet.length)];
// Leading/trailing 'a' keeps the other needsQuote rules (edge space, numeric, '#'…)
// out of the way, so the verdict depends only on the inline-array rule.
const s = `a${body}a`;
assert.equal(needsQuote(s), hasInlineArrayHeader(s), JSON.stringify(s));
}
});
});
describe("#1302 rtk raw-output command slug", () => {
function persist(command: string) {
const base = process.env.DATA_DIR || os.tmpdir();
const dataDir = fs.mkdtempSync(path.join(base, "rtk-slug-"));
const previous = process.env.DATA_DIR;
process.env.DATA_DIR = dataDir;
try {
return timed(() =>
maybePersistRtkRawOutput("error: build failed\nline 2", { retention: "always", command })
);
} finally {
if (previous === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = previous;
fs.rmSync(dataDir, { recursive: true, force: true });
}
}
function slugOf(pointerPath: string): string {
const match = /^\d+-(.*)-[0-9a-f]{24}\.log$/.exec(path.basename(pointerPath));
assert.ok(match, pointerPath);
return match[1];
}
it("finishes fast on a 50k-underscore command", () => {
for (const command of ["_".repeat(50_000) + "x", "x" + "_".repeat(50_000) + "x"]) {
const { value, ms } = persist(command);
assert.ok(value, "pointer expected");
assert.ok(ms < FAST_MS, `slug took ${ms.toFixed(1)}ms on ${command.length} chars`);
}
});
it("keeps the same slug for ordinary commands", () => {
const cases: Array<[string, string]> = [
["git status --short", "git_status_--short"],
[" npm test -- --watch=false ", "npm_test_--_--watch_false"],
["__init__", "init"],
["cargo build --release && ./target/release/app", "cargo_build_--release_target_release_app"],
["a".repeat(100), "a".repeat(48)],
];
for (const [command, expected] of cases) {
const { value } = persist(command);
assert.ok(value);
assert.equal(slugOf(value.path), expected, command);
}
const { value } = persist("");
assert.ok(value);
assert.equal(slugOf(value.path), "tool-output");
});
});
describe("#1349 ccr grep pattern", () => {
it("refuses a multi-quantifier pattern on a 500+ char line quickly", () => {
const text = "a".repeat(600);
const { value, ms } = timed(() => queryBlock(text, { mode: "grep", pattern: ".*.*.*.*x" }));
assert.ok("error" in value, JSON.stringify(value));
assert.ok(ms < FAST_MS, `grep took ${ms.toFixed(1)}ms`);
});
it("stops a single-quantifier pattern that exceeds the time budget", () => {
// 2 MiB of 4096-char lines: `.*x` is quadratic per line (minutes before the fix).
const text = Array.from({ length: 512 }, () => "a".repeat(4095)).join("\n");
const { value, ms } = timed(() => queryBlock(text, { mode: "grep", pattern: ".*x" }));
assert.ok("error" in value, JSON.stringify(value).slice(0, 200));
assert.match((value as { error: string }).error, /time budget/);
assert.ok(ms < BUDGET_CEILING_MS, `grep took ${ms.toFixed(1)}ms`);
});
it("counts only unbounded quantifiers outside classes and escapes", () => {
const tooMany = ["a.*b.*c", "\\d+\\.\\d+", "x{2,}y+", "a.*?b.+?c"];
for (const pattern of tooMany) {
const r = queryBlock("abc", { mode: "grep", pattern });
assert.ok("error" in r, pattern);
assert.match((r as { error: string }).error, /unbounded quantifier/, pattern);
}
const text = ["l1 ERROR upstream timeout", "l2 *+ literal", "l3 {2,} braces", "l4 ok"].join(
"\n"
);
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "ERROR.*timeout" }), {
content: "l1 ERROR upstream timeout",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "[*+]+ literal" }), {
content: "l2 *+ literal",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "\\*\\+ lit.*" }), {
content: "l2 *+ literal",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "\\{2,\\} b.*s" }), {
content: "l3 {2,} braces",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "l[0-9]{1,2} (ok|ERROR)" }), {
content: "l1 ERROR upstream timeout\nl4 ok",
});
});
it("keeps grep results unchanged on an ordinary log block", () => {
const lines = Array.from(
{ length: 5_000 },
(_, i) => `2026-11-20T10:00:${String(i % 60).padStart(2, "0")}Z INFO req=${i} status=200`
);
lines[1234] = "2026-11-20T10:00:34Z ERROR req=1234 upstream timeout";
lines[4321] = "2026-11-20T10:00:01Z WARN req=4321 slow upstream";
const text = lines.join("\n");
const expected = (re: RegExp) => lines.filter((l) => re.test(l)).join("\n");
for (const pattern of ["ERROR", "(WARN|ERROR) req=", "req=12\\d\\d ", "^\\S+ WARN"]) {
assert.deepEqual(
queryBlock(text, { mode: "grep", pattern }),
{ content: expected(new RegExp(pattern)) },
pattern
);
}
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "INFO", unique: true }), {
content: lines
.filter((l) => l.includes("INFO"))
.slice(0, 1000)
.join("\n")
.concat("\n…[truncated at 1000 matches]"),
});
});
});

View File

@@ -21,7 +21,7 @@ import {
bumpLockfile,
bumpManifest,
bumpOpenApi,
evaluateMergifyQueue,
evaluateMergeQueue,
evaluatePreconditions,
executeCut,
expectedDistTags,
@@ -35,8 +35,15 @@ import { resolveDistTag } from "../../scripts/release/dist-tag.mjs";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const SCRIPT = path.join(repoRoot, "scripts/release/dry-run-lts-cut.mjs");
const SHA = "1".repeat(40);
// The real .mergify.yml of this checkout (G11: queue `release` with checks_timeout, #16066).
const MERGIFY = fs.readFileSync(path.join(repoRoot, ".mergify.yml"), "utf8");
// The real omni-queue config of this checkout (G11 since the Mergify `release` queue of #16066
// was retired on 2026-11-19). The checkout's `mode` is whatever the queue runs today, so a ready
// cut pins `live` explicitly; the shadow case is asserted on its own below.
const QUEUE_CONFIG_RAW = JSON.parse(
fs.readFileSync(path.join(repoRoot, "config/merge-queue/config.json"), "utf8")
);
const queueConfig = (overrides: Record<string, unknown> = {}) =>
JSON.stringify({ ...QUEUE_CONFIG_RAW, ...overrides });
const LIVE_QUEUE = queueConfig({ mode: "live" });
type Facts = Parameters<typeof evaluatePreconditions>[0];
@@ -49,7 +56,7 @@ function goodFacts(overrides: Partial<Facts> = {}): Facts {
freezeIssues: [{ number: 900, title: "🧊 Release freeze: release/v3.9.0" }],
baseRedIssues: [],
sourceBranchExists: true,
mergifyConfig: MERGIFY,
mergeQueueConfig: LIVE_QUEUE,
queueLabelExists: true,
releaseRulesetRules: ["deletion", "non_fast_forward"],
remoteBranches: { "stable/v3": null, develop: null },
@@ -159,8 +166,10 @@ test("each failing precondition is reported with expected vs actual", () => {
],
[{ remoteBranches: { "stable/v3": SHA, develop: null } }, "branches-absent", /stable\/v3/],
[{ freezeIssues: null }, "freeze", /unknown/],
[{ queueLabelExists: false }, "merge-queue", /label `queue` missing/],
[{ mergifyConfig: null }, "merge-queue", /\.mergify\.yml missing/],
[{ queueLabelExists: false }, "merge-queue", /label `omni-queue` missing/],
[{ queueLabelExists: null }, "merge-queue", /label lookup failed/],
[{ mergeQueueConfig: null }, "merge-queue", /config\/merge-queue\/config\.json missing/],
[{ mergeQueueConfig: queueConfig({ mode: "shadow" }) }, "merge-queue", /mode is `shadow`/],
[{ releaseRulesetRules: ["deletion"] }, "release-ruleset", /missing: non_fast_forward/],
[{ releaseRulesetRules: null }, "release-ruleset", /unknown/],
];
@@ -190,25 +199,57 @@ test("base-green is unknown (never green) when the release branch does not exist
assert.equal(existing?.verifiable, true);
});
test("G11 is the Mergify `release` queue, not GitHub's native merge queue", () => {
test("G11 is omni-queue landing release PRs, not the retired Mergify queue", () => {
const branch = "release/v3.9.0";
// This checkout's config passes omni-queue's own validator and manages the cut's branch:
// whatever its mode, the only problem G11 may report on it is the mode.
const actual = evaluateMergeQueue(queueConfig(), branch);
assert.equal(actual.label, "omni-queue");
assert.deepEqual(
evaluateMergifyQueue(MERGIFY),
{ ok: true, problems: [] },
"G11 GO on this base"
actual.problems.filter((p) => !/^omni-queue mode is /.test(p)),
[],
"this checkout's omni-queue config is valid for release branches"
);
const noTimeout = MERGIFY.replace(/^ {4}checks_timeout:.*\n/m, "");
assert.notEqual(noTimeout, MERGIFY, "fixture removed checks_timeout");
assert.deepEqual(evaluateMergifyQueue(noTimeout).problems, [
"queue `release` has no checks_timeout",
assert.deepEqual(evaluateMergeQueue(LIVE_QUEUE, branch), {
ok: true,
problems: [],
label: "omni-queue",
mode: "live",
});
// Shadow composes and tests but lands nothing: a configured queue, still a NO-GO for G11.
const shadow = evaluateMergeQueue(queueConfig({ mode: "shadow" }), branch);
assert.equal(shadow.ok, false);
assert.deepEqual(shadow.problems, [
"omni-queue mode is `shadow`: it lands nothing, release PRs are merged by hand",
]);
// Without checksTimeoutMinutes a hung check could park the queue: omni-queue's validator
// rejects the config, and G11 with it.
const { checksTimeoutMinutes: _timeout, ...noTimeout } = QUEUE_CONFIG_RAW;
const timeoutVerdict = evaluateMergeQueue(JSON.stringify({ ...noTimeout, mode: "live" }), branch);
assert.equal(timeoutVerdict.ok, false);
assert.match(timeoutVerdict.problems.join(), /invalid: .*checksTimeoutMinutes: /);
assert.match(
evaluateMergifyQueue("queue_rules:\n - name: other\n").problems.join(),
/no queue_rules entry named `release`/
evaluateMergeQueue(queueConfig({ mode: "live", label: "" }), branch).problems.join(),
/invalid: .*label: invalid/
);
const noLabel = MERGIFY.replace(/label ?= ?queue/g, "label=other");
assert.match(evaluateMergifyQueue(noLabel).problems.join(), /`queue` label/);
assert.equal(evaluateMergifyQueue(null).ok, false);
assert.equal(evaluateMergifyQueue(": : :\n - [").ok, false);
assert.match(
evaluateMergeQueue(queueConfig({ mode: "live", bases: "^main$" }), branch).problems.join(),
/does not manage release\/v3\.9\.0/
);
assert.equal(evaluateMergeQueue(null, branch).ok, false);
assert.equal(evaluateMergeQueue("{ not json", branch).ok, false);
const ready = evaluatePreconditions(goodFacts(), parseCutArgs([])).find(
(c) => c.id === "merge-queue"
);
assert.equal(ready?.ok, true);
assert.equal(ready?.actual, "configured (mode live, label `omni-queue`)");
// With no valid config there is no label to look up: only the config problem is reported.
const missing = evaluatePreconditions(
goodFacts({ mergeQueueConfig: null, queueLabelExists: null }),
parseCutArgs([])
).find((c) => c.id === "merge-queue");
assert.equal(missing?.ok, false);
assert.equal(missing?.actual, "config/merge-queue/config.json missing at the source");
});
test("--advisory downgrades a check to a warning without hiding it", () => {

View File

@@ -1,159 +1,83 @@
// Contract for .mergify.yml (rail G11, v3.8.54). Mergify silently ignores or
// rejects a bad config, so the queue's load-bearing keys are pinned here.
// Contract for .mergify.yml after the owner retired the Mergify merge queue (2026-11-19).
// The Mergify GitHub App is still installed and reads this file from the default branch; Mergify
// silently ignores or rejects a bad config, so what is left of it is pinned here: no queue, no
// auto-merge, no merging rule, and every command that would merge or rewrite a pull request
// refused by a condition list no pull request can match. Until 2026-11-19 this file pinned the
// `release` and `relay-integration` queue rules; their admission contract (the required checks
// and the checks timeout) now belongs to omni-queue, the replacement queue, and its timeout
// rationale is carried over at the end of this file.
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import * as yaml from "js-yaml";
type QueueRule = Record<string, unknown> & { name: string };
type MergifyConfig = {
merge_protections_settings?: { auto_merge_conditions?: unknown[] };
queue_rules?: QueueRule[];
pull_request_rules?: unknown[];
type CommandRestriction = { conditions?: unknown };
type MergifyConfig = Record<string, unknown> & {
commands_restrictions?: Record<string, CommandRestriction>;
};
const config = yaml.load(
readFileSync(new URL("../../.mergify.yml", import.meta.url), "utf8")
) as MergifyConfig;
// p95 wall-clock (createdAt -> updatedAt) of the last 100 successful quality.yml
// runs, measured 2026-10-09 over 2026-09-28..2026-10-08: 119.75 min. The queue's
// checks_timeout must be at least 2x this so a slow-but-healthy run is not dequeued.
const MEASURED_QUALITY_P95_MINUTES = 119.75;
const omniQueue = JSON.parse(
readFileSync(new URL("../../config/merge-queue/config.json", import.meta.url), "utf8")
) as { label: string; checksTimeoutMinutes: number; requiredChecks: string[] };
function durationToMinutes(value: unknown): number {
assert.equal(typeof value, "string", "checks_timeout must be a duration string");
const match = /^(\d+)\s*(seconds?|s|min|minutes?|m|hours?|h)$/i.exec(String(value).trim());
assert.ok(match, `unparseable duration: ${String(value)}`);
const n = Number(match[1]);
const unit = match[2].toLowerCase();
if (unit.startsWith("s")) return n / 60;
if (unit.startsWith("h")) return n * 60;
return n;
}
// Mergify commands that land, enqueue, rewrite or copy a pull request. `refresh` (re-evaluate)
// and `dequeue` (leave a queue) do neither and keep Mergify's defaults.
const MUTATING_COMMANDS = ["queue", "requeue", "rebase", "update", "squash", "backport", "copy"];
const release = config.queue_rules?.find((rule) => rule.name === "release");
test("release queue rule exists and keeps squash merges", () => {
assert.ok(release, "queue_rules must define the `release` queue");
assert.equal(release.merge_method, "squash");
test("the file is kept (not deleted) and holds only command restrictions", () => {
// Deleting it would not turn Mergify off: with no configuration, `@mergifyio queue` merges a PR
// once its required checks pass (docs.mergify.com/merge-queue/setup).
assert.deepEqual(Object.keys(config), ["commands_restrictions"]);
});
test("release queue only accepts owner-labelled, non-draft, conflict-free release PRs", () => {
const conditions = release?.queue_conditions as string[];
assert.ok(conditions.includes("label=queue"));
assert.ok(conditions.includes("-draft"));
assert.ok(conditions.includes("-conflict"));
assert.ok(conditions.some((c) => c.startsWith("base~=^release/")));
assert.deepEqual(config.merge_protections_settings?.auto_merge_conditions, ["label = queue"]);
});
test("merge conditions stay fail-closed on the always-on anchor check", () => {
const conditions = JSON.stringify(release?.merge_conditions);
assert.match(conditions, /#check-pending=0/);
assert.match(conditions, /#check-success>=1/);
assert.match(conditions, /check-success=Merge integrity \(changelog \+ generated skills\)/);
});
test("checks_timeout is at least 2x the measured quality.yml p95", () => {
const minutes = durationToMinutes(release?.checks_timeout);
assert.ok(
minutes >= 2 * MEASURED_QUALITY_P95_MINUTES,
`checks_timeout ${minutes} min < 2 x p95 (${2 * MEASURED_QUALITY_P95_MINUTES} min)`
test("no Mergify queue: no queue_rules, no auto-merge conditions", () => {
assert.equal("queue_rules" in config, false, "a second queue would act on release PRs");
assert.equal(
"merge_protections_settings" in config,
false,
"auto_merge_conditions would merge labelled PRs outside the release process"
);
// Mergify's floor is 60 s; an absurd ceiling would make the timeout meaningless.
assert.ok(minutes <= 8 * 60, "checks_timeout above 8 h no longer protects the queue");
assert.equal("pull_request_rules" in config, false, "no rule may merge, label or rewrite a PR");
assert.equal("defaults" in config, false);
});
test("no paid-tier batch keys (free plan dequeues every PR with them, #7220)", () => {
for (const key of [
"batch_size",
"batch_max_wait_time",
"batch_max_failure_resolution_attempts",
]) {
assert.equal(key in (release ?? {}), false, `${key} requires a paid Mergify tier`);
}
});
test("deprecated queue keys are not used", () => {
for (const key of [
"allow_inplace_checks",
"allow_queue_branch_edit",
"autoqueue",
"speculative_checks",
]) {
assert.equal(key in (release ?? {}), false, `${key} is deprecated/removed in Mergify`);
}
});
const integration = config.queue_rules?.find((rule) => rule.name === "relay-integration");
test("the opt-in Relay integration queue preserves original commits without paid batching", () => {
assert.ok(integration, "queue_rules must define the opt-in integration queue");
assert.equal(integration.merge_method, "merge");
assert.equal(integration.update_method, "merge", "rebasing would rewrite contributor heads");
assert.equal(integration.checks_timeout, release?.checks_timeout);
for (const rule of config.queue_rules ?? []) {
for (const key of [
"batch_size",
"batch_max_wait_time",
"batch_max_failure_resolution_attempts",
"allow_inplace_checks",
"allow_queue_branch_edit",
"autoqueue",
"speculative_checks",
"queue_branch_merge_method",
"merge_bot_account",
"update_bot_account",
]) {
assert.equal(
key in rule,
false,
`${rule.name}: unexpected paid, bypass or rewrite option ${key}`
);
}
}
});
test("integration routing is owner-only, exact-target and separately reviewed", () => {
assert.deepEqual(integration?.queue_conditions, [
"base=release/v3.8.52",
"head=fix/relay-integration-candidate-20261015",
"author=diegosouzapw",
"label=queue",
"label=integration-reviewed",
"-draft",
"-conflict",
]);
const conditions = release?.queue_conditions as string[];
assert.ok(conditions.includes("-label=integration-reviewed"));
assert.ok(
conditions.includes("-head~=^fix/relay-integration-candidate-"),
"a missing review label must not route the candidate to squash"
);
});
test("integration admission retains every ordinary gate and requires both aggregate verdicts", () => {
assert.deepEqual(integration?.merge_conditions, release?.merge_conditions);
for (const rule of config.queue_rules ?? []) {
const conditions = rule.merge_conditions as unknown[];
assert.ok(conditions.includes("check-success=Gate / CI"), `${rule.name}: missing CI verdict`);
assert.ok(
conditions.includes("check-success=Gate / Quality"),
`${rule.name}: missing Quality verdict`
test("every command that merges or rewrites a pull request is refused", () => {
const restrictions = config.commands_restrictions ?? {};
assert.deepEqual(Object.keys(restrictions).sort(), [...MUTATING_COMMANDS].sort());
for (const command of MUTATING_COMMANDS) {
// Conditions in one list are ANDed: `closed` and `-closed` can never both hold.
assert.deepEqual(
restrictions[command]?.conditions,
["closed", "-closed"],
`${command}: must keep an unsatisfiable condition list`
);
}
});
test("ordinary admission keeps its exact failure allowance instead of broadening it", () => {
assert.deepEqual(release?.merge_conditions, [
{
or: ["#check-failure=0", { and: ["#check-failure=1", "check-failure=Build (advisory)"] }],
},
"#check-pending=0",
"#check-success>=1",
"check-success=Merge integrity (changelog + generated skills)",
"check-success=Gate / CI",
"check-success=Gate / Quality",
]);
test("the retired `queue` label is not omni-queue's label", () => {
assert.notEqual(omniQueue.label, "queue", "a leftover `queue` label must not enter omni-queue");
});
// p95 wall-clock (createdAt -> updatedAt) of the last 100 successful quality.yml runs, measured
// 2026-10-09 over 2026-09-28..2026-10-08: 119.75 min. It sized Mergify's checks_timeout (240 min);
// the replacement queue must keep at least 2x this so a slow-but-healthy run is not dequeued.
const MEASURED_QUALITY_P95_MINUTES = 119.75;
test("omni-queue keeps the retired queue's timeout floor and both aggregate verdicts", () => {
assert.ok(
omniQueue.checksTimeoutMinutes >= 2 * MEASURED_QUALITY_P95_MINUTES,
`checksTimeoutMinutes ${omniQueue.checksTimeoutMinutes} < 2 x p95 (${2 * MEASURED_QUALITY_P95_MINUTES})`
);
assert.ok(omniQueue.checksTimeoutMinutes <= 8 * 60, "above 8 h the timeout no longer protects");
for (const check of [
"Gate / CI",
"Gate / Quality",
"Merge integrity (changelog + generated skills)",
]) {
assert.ok(omniQueue.requiredChecks.includes(check), `omni-queue must require ${check}`);
}
});

View File

@@ -143,11 +143,185 @@ test("greenGateArgs returns null only with the explicit --skip-green-gate flag",
assert.notEqual(greenGateArgs(["node", "script", "3.8.49", "--other"]), null);
});
// The push now goes through syncPushArgs() (side branch by default, the release branch
// only with --direct-push): the gate must still run before it. This assertion used to pin
// the literal direct push `git(["push", "origin", BRANCH]` — the default path no longer
// pushes to the release branch (ruleset 21899981 refuses it), see the tests below.
test("sync-next-cycle gates the push on release-green (source guard)", () => {
const src = readFileSync(SCRIPT_PATH, "utf8");
const mainIdx = src.indexOf("function main()");
const gateCallIdx = src.indexOf("greenGateArgs(process.argv)", mainIdx);
const pushIdx = src.indexOf('git(["push", "origin", BRANCH]');
const pushIdx = src.indexOf("git(syncPushArgs(", mainIdx);
assert.ok(gateCallIdx > mainIdx, "main() must call greenGateArgs(process.argv)");
assert.ok(pushIdx > mainIdx, "main() must push through syncPushArgs()");
assert.ok(pushIdx > gateCallIdx, "the release-green gate must run BEFORE the push");
});
// ── Sync-back lands through a pull request ─────────────────────────────────────────
// release/vX+1 is the default branch and ruleset 21899981 ("Require PR on default
// branch", no bypass actors) refuses a direct push. The default path pushes the merge
// commit to chore/sync-back-main-<sha12> and opens a PR into the release branch; the old
// direct push survives only behind --direct-push. The script never merges the PR.
const MAIN_SHA = "0123456789abcdef0123456789abcdef01234567";
test("syncBackBranchName uses the first 12 hex of the synced origin/main commit", async () => {
const { syncBackBranchName } = await import("../../scripts/release/sync-next-cycle.mjs");
assert.equal(syncBackBranchName(MAIN_SHA), "chore/sync-back-main-0123456789ab");
assert.equal(
syncBackBranchName(MAIN_SHA.toUpperCase()),
"chore/sync-back-main-0123456789ab",
"normalized to lower case"
);
assert.throws(() => syncBackBranchName("abc123"), /12/, "rejects a short SHA");
assert.throws(() => syncBackBranchName("zzzzzzzzzzzzzzzz"), /hex/i, "rejects non-hex input");
});
test("parseSyncArgs: PR flow by default, direct push only with the explicit flag", async () => {
const { parseSyncArgs } = await import("../../scripts/release/sync-next-cycle.mjs");
assert.deepEqual(parseSyncArgs(["node", "script", "3.8.56"]), {
next: "3.8.56",
skipGreenGate: false,
directPush: false,
help: false,
unknown: [],
});
const all = parseSyncArgs(["node", "script", "--skip-green-gate", "3.8.56", "--direct-push"]);
assert.equal(all.next, "3.8.56", "the version may come after a flag");
assert.equal(all.skipGreenGate, true);
assert.equal(all.directPush, true);
assert.equal(parseSyncArgs(["node", "script", "--help"]).help, true);
assert.equal(parseSyncArgs(["node", "script", "-h"]).help, true);
assert.deepEqual(parseSyncArgs(["node", "script", "3.8.56", "--force"]).unknown, ["--force"]);
assert.equal(parseSyncArgs(["node", "script"]).next, null, "missing version → null");
assert.equal(parseSyncArgs(["node", "script", "v3.8.56"]).next, null, "malformed version → null");
});
test("syncPushArgs never targets the release branch unless --direct-push was given", async () => {
const { syncPushArgs } = await import("../../scripts/release/sync-next-cycle.mjs");
const side = "chore/sync-back-main-0123456789ab";
const pr = syncPushArgs({ directPush: false, branch: "release/v3.8.56", sideBranch: side });
assert.deepEqual(pr, ["push", "origin", `HEAD:refs/heads/${side}`]);
assert.ok(!pr.join(" ").includes("release/v3.8.56"), "PR path never names the release branch");
assert.ok(!pr.some((a) => a.startsWith("-")), "no --force / --no-verify on the PR path");
const direct = syncPushArgs({ directPush: true, branch: "release/v3.8.56", sideBranch: side });
assert.deepEqual(direct, ["push", "origin", "HEAD:refs/heads/release/v3.8.56"]);
});
test("githubRepoFromRemoteUrl reads owner/name from https and ssh remotes", async () => {
const { githubRepoFromRemoteUrl } = await import("../../scripts/release/sync-next-cycle.mjs");
const want = "cheaper-inference/OmniRoute";
assert.equal(githubRepoFromRemoteUrl("https://github.com/cheaper-inference/OmniRoute.git"), want);
assert.equal(githubRepoFromRemoteUrl("https://github.com/cheaper-inference/OmniRoute"), want);
assert.equal(githubRepoFromRemoteUrl("git@github.com:cheaper-inference/OmniRoute.git"), want);
assert.equal(
githubRepoFromRemoteUrl("ssh://git@github.com/cheaper-inference/OmniRoute.git"),
want
);
assert.equal(githubRepoFromRemoteUrl("https://gitlab.com/a/b.git"), null, "non-GitHub → null");
assert.equal(githubRepoFromRemoteUrl(""), null);
});
test("ghPrCreateArgs builds an argument array with --body-file and never a merge", async () => {
const { ghPrCreateArgs, syncBackPrTitle } =
await import("../../scripts/release/sync-next-cycle.mjs");
const title = syncBackPrTitle("release/v3.8.56");
assert.equal(title, "chore(release): sync-back main → release/v3.8.56");
const args = ghPrCreateArgs({
repo: "cheaper-inference/OmniRoute",
base: "release/v3.8.56",
head: "chore/sync-back-main-0123456789ab",
title,
bodyFile: "/x/body.md",
});
assert.deepEqual(args, [
"pr",
"create",
"--repo",
"cheaper-inference/OmniRoute",
"--base",
"release/v3.8.56",
"--head",
"chore/sync-back-main-0123456789ab",
"--title",
"chore(release): sync-back main → release/v3.8.56",
"--body-file",
"/x/body.md",
]);
assert.ok(!args.includes("--body"), "body goes through a file, never inline");
});
test("ghOpenPrListArgs looks up an OPEN PR for exactly this head and base", async () => {
const { ghOpenPrListArgs } = await import("../../scripts/release/sync-next-cycle.mjs");
const args = ghOpenPrListArgs({
repo: "cheaper-inference/OmniRoute",
base: "release/v3.8.56",
head: "chore/sync-back-main-0123456789ab",
});
assert.equal(args[0], "pr");
assert.equal(args[1], "list");
const flag = (name) => args[args.indexOf(name) + 1];
assert.equal(flag("--repo"), "cheaper-inference/OmniRoute");
assert.equal(flag("--head"), "chore/sync-back-main-0123456789ab");
assert.equal(flag("--base"), "release/v3.8.56");
assert.equal(flag("--state"), "open");
assert.equal(flag("--json"), "url");
});
test("syncBackPrBody states merge-commit-only, green gates and the ancestry check, with no AI attribution", async () => {
const { syncBackPrBody } = await import("../../scripts/release/sync-next-cycle.mjs");
const body = syncBackPrBody({
branch: "release/v3.8.56",
mainSha: MAIN_SHA,
prevVersion: "3.8.55",
greenGate: "passed",
});
assert.match(body, /MERGE COMMIT/);
assert.match(body, /never squash or rebase/i);
assert.match(body, /551 files on v3\.8\.50 → v3\.8\.51/);
assert.match(body, /required gates must be green on the head/i);
assert.ok(
body.includes("git merge-base --is-ancestor origin/main origin/release/v3.8.56"),
"post-landing ancestry check names the release branch"
);
assert.ok(body.includes("0123456789ab"), "names the synced main commit");
assert.ok(body.includes("v3.8.55"), "names the shipped version");
assert.doesNotMatch(body, /co-authored-by|generated with|claude|copilot|\bAI\b|🤖/i);
});
test("syncBackNextSteps prints the PR URL and the three landing statements", async () => {
const { syncBackNextSteps } = await import("../../scripts/release/sync-next-cycle.mjs");
const out = syncBackNextSteps({
branch: "release/v3.8.56",
prUrl: "https://github.com/cheaper-inference/OmniRoute/pull/1",
});
assert.equal(
out.split("\n")[0],
"[sync-next-cycle] sync-back PR: https://github.com/cheaper-inference/OmniRoute/pull/1"
);
assert.match(out, /MERGE COMMIT/);
assert.match(out, /never squash or rebase/i);
assert.match(out, /required gates must be green/i);
assert.ok(out.includes("git merge-base --is-ancestor origin/main origin/release/v3.8.56"));
});
test("SYNC_USAGE documents --direct-push as refused by this repository", async () => {
const { SYNC_USAGE } = await import("../../scripts/release/sync-next-cycle.mjs");
assert.ok(SYNC_USAGE.includes("--direct-push"));
assert.ok(SYNC_USAGE.includes("--skip-green-gate"));
assert.match(SYNC_USAGE, /refuse/i);
assert.match(SYNC_USAGE, /21899981/);
});
test("the script never merges the PR it opens (source guard)", () => {
const src = readFileSync(SCRIPT_PATH, "utf8");
assert.doesNotMatch(src, /"pr",\s*"merge"/, "no gh pr merge argument array");
assert.doesNotMatch(src, /--admin/, "no admin bypass");
assert.doesNotMatch(src, /--no-verify/, "no hook bypass");
const pushLines = src.split("\n").filter((l) => l.includes('"push"'));
assert.ok(pushLines.length > 0, "push lines found");
for (const l of pushLines) {
assert.doesNotMatch(l, /"--force|"-f"|\+HEAD/, `no force-push: ${l.trim()}`);
}
assert.ok(!src.includes('git(["push", "origin", BRANCH]'), "the direct push is gone");
});