Compare commits

...

10 Commits

Author SHA1 Message Date
diegosouzapw
035b02bcd1 chore(changelog): number the fragment for #20819 2026-11-20 18:12:44 -03:00
diegosouzapw
380b6a7786 fix(security): operator-only credential and denied roots for corpus and vault paths (CodeQL #1371, #1372, #1373)
POST /api/settings/local-corpus (rootPath) and POST /api/settings/obsidian/webdav
(vaultPath) now require an operator credential (dashboard session or local CLI) through
requireOperatorCredential; API keys of any scope and access tokens get 403. The webdav
route passes alwaysRequireAuth because /api/settings/obsidian is ALWAYS_PROTECTED.

Both roots also refuse the filesystem root, the home directory itself and the system
directories /etc /usr /bin /sbin /var /proc /sys /dev /boot /root (and below), compared
after path.resolve and realpath, with a fixed 400 message. The vault keeps its DATA_DIR
overlap refusal.
2026-11-20 18:05:40 -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
30 changed files with 1218 additions and 428 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):** Choosing the local corpus root (`POST /api/settings/local-corpus`) or the Obsidian WebDAV vault (`POST /api/settings/obsidian/webdav`) now needs a dashboard session or the local CLI: API keys and access tokens of any scope get 403. Both routes also refuse the filesystem root, the home directory itself and system directories (`/etc`, `/usr`, `/bin`, `/sbin`, `/var`, `/proc`, `/sys`, `/dev`, `/boot`, `/root`) with a fixed 400 (CodeQL #1371, #1372, #1373)

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

@@ -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

@@ -11,6 +11,7 @@ import {
getConfiguredLocalCorpusStatus,
resetLocalCorpusIndex,
} from "@/lib/localCorpus/configured";
import { requireOperatorCredential } from "@/lib/api/operatorCredential";
import { isAuthenticated } from "@/shared/utils/apiAuth";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
@@ -20,6 +21,11 @@ const localCorpusSchema = z
})
.strict();
// CodeQL #1371: the root is indexed and served by the MCP local-corpus search tools, so choosing
// it is an operator action. A machine credential (an API key of any scope) gets 403.
const LOCAL_CORPUS_ROOT_FORBIDDEN_MESSAGE =
"Choosing the local corpus root requires a signed-in dashboard session or the local CLI; API keys and access tokens cannot change it.";
export async function GET(request: NextRequest) {
if (!(await isAuthenticated(request))) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
@@ -40,6 +46,10 @@ export async function POST(request: NextRequest) {
if (!(await isAuthenticated(request))) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const operatorVerdict = await requireOperatorCredential(request, {
forbiddenMessage: LOCAL_CORPUS_ROOT_FORBIDDEN_MESSAGE,
});
if (operatorVerdict.ok === false) return operatorVerdict.response;
let body: unknown;
try {

View File

@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { isAuthenticated } from "@/shared/utils/apiAuth";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { requireOperatorCredential } from "@/lib/api/operatorCredential";
import { buildErrorBody } from "@omniroute/open-sse/utils/error";
import {
getObsidianSyncStatus,
@@ -15,6 +16,12 @@ const enableSchema = z
})
.strict();
// CodeQL #1372/#1373: the vault becomes the root of a read/write WebDAV service with freshly
// minted credentials, so choosing it is an operator action. The route is ALWAYS_PROTECTED, so an
// open instance (login disabled) does not make a machine credential the operator either.
const WEBDAV_VAULT_FORBIDDEN_MESSAGE =
"Choosing the WebDAV vault requires a signed-in dashboard session or the local CLI; API keys and access tokens cannot change it.";
export async function GET(request: NextRequest) {
if (!(await isAuthenticated(request))) {
return NextResponse.json(buildErrorBody(401, "Authentication required"), { status: 401 });
@@ -32,8 +39,7 @@ export async function GET(request: NextRequest) {
return NextResponse.json({
webdavEnabled: status.webdavEnabled,
webdavUsername: status.webdavEnabled ? status.webdavUsername : null,
webdavPassword:
status.webdavEnabled && hasManagement ? status.webdavPassword : null,
webdavPassword: status.webdavEnabled && hasManagement ? status.webdavPassword : null,
webdavPasswordSet: status.webdavEnabled && Boolean(status.webdavPassword),
vaultPath: status.vaultPath,
});
@@ -47,6 +53,11 @@ export async function POST(request: NextRequest) {
if (!(await isAuthenticated(request))) {
return NextResponse.json(buildErrorBody(401, "Authentication required"), { status: 401 });
}
const operatorVerdict = await requireOperatorCredential(request, {
forbiddenMessage: WEBDAV_VAULT_FORBIDDEN_MESSAGE,
alwaysRequireAuth: true,
});
if (operatorVerdict.ok === false) return operatorVerdict.response;
let rawBody: unknown;
try {
@@ -57,10 +68,7 @@ export async function POST(request: NextRequest) {
const parsed = enableSchema.safeParse(rawBody);
if (!parsed.success) {
return NextResponse.json(
buildErrorBody(400, "Missing or invalid vaultPath"),
{ status: 400 }
);
return NextResponse.json(buildErrorBody(400, "Missing or invalid vaultPath"), { status: 400 });
}
const result = await enableObsidianVaultSync(parsed.data.vaultPath);

View File

@@ -0,0 +1,79 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
/**
* System directories that must never become the root of a host-filesystem surface (the local
* corpus indexed for the MCP search tools, the read/write Obsidian WebDAV vault). The directory
* itself and everything below it are refused, unless the canonical path lives inside the user's
* home directory (a service account whose home is `/root` or `/var/lib/<app>` keeps its folders).
* POSIX only: on Windows the drive root and the home directory itself are refused.
*/
const POSIX_SYSTEM_DIRECTORIES = [
"/etc",
"/usr",
"/bin",
"/sbin",
"/var",
"/proc",
"/sys",
"/dev",
"/boot",
"/root",
] as const;
/** Fixed refusal message: it never echoes the requested path back to the caller. */
export const DENIED_ROOT_DIRECTORY_ERROR =
"This directory cannot be used as a root: choose a dedicated folder, not the filesystem root, the home directory itself or a system directory";
/** Canonical (symlink-resolved) absolute form of a path; falls back to the lexical resolve. */
function canonicalPath(target: string): string {
const resolved = path.resolve(target);
try {
return fs.realpathSync.native(resolved);
} catch {
return resolved;
}
}
/** True when `child` is `parent` itself or lives anywhere below it. */
function isSameOrInside(parent: string, child: string): boolean {
const rel = path.relative(parent, child);
if (rel === "") return true;
if (path.isAbsolute(rel)) return false; // different drive (win32)
return rel !== ".." && !rel.startsWith(`..${path.sep}`);
}
function isFilesystemRoot(target: string): boolean {
return path.parse(target).root === target;
}
/**
* Is `candidate` a directory that must not be exposed as a corpus or vault root? Both the lexical
* (`path.resolve`) and canonical (`realpath`) forms are checked, so a symlink cannot dodge the
* comparison in either direction. Refused: the filesystem root (`/`, a drive root on Windows), the
* user's home directory itself (its subfolders stay allowed) and the POSIX system directories
* above.
*/
export function isDeniedRootDirectory(candidate: string): boolean {
const lexical = path.resolve(candidate);
const canonical = canonicalPath(candidate);
const forms = lexical === canonical ? [canonical] : [lexical, canonical];
if (forms.some(isFilesystemRoot)) return true;
const homeForms = [path.resolve(os.homedir()), canonicalPath(os.homedir())];
if (forms.some((form) => homeForms.includes(form))) return true;
if (process.platform === "win32") return false;
const canonicalHome = homeForms[1];
if (isFilesystemRoot(canonicalHome) === false && isSameOrInside(canonicalHome, canonical)) {
return false;
}
return POSIX_SYSTEM_DIRECTORIES.some((dir) => {
const dirForms = [dir, canonicalPath(dir)];
return dirForms.some((dirForm) => forms.some((form) => isSameOrInside(dirForm, form)));
});
}

View File

@@ -2,6 +2,8 @@ import { createHash } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { DENIED_ROOT_DIRECTORY_ERROR, isDeniedRootDirectory } from "../deniedRootDirectories";
const DEFAULT_ALLOWED_EXTENSIONS = new Set([
".cfg",
".csv",
@@ -278,6 +280,9 @@ export async function canonicalizeLocalCorpusRoot(inputPath: string): Promise<st
} catch {
throw new Error("Local corpus root is not accessible");
}
if (isDeniedRootDirectory(canonical)) {
throw new Error(DENIED_ROOT_DIRECTORY_ERROR);
}
if (!stat.isDirectory()) {
throw new Error("Local corpus root must point to a directory");
}

View File

@@ -1,6 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import { resolveDataDir } from "./dataPaths";
import { DENIED_ROOT_DIRECTORY_ERROR, isDeniedRootDirectory } from "./deniedRootDirectories";
import {
getObsidianVaultPath,
setObsidianVaultPath,
@@ -75,6 +76,12 @@ export async function enableObsidianVaultSync(
): Promise<ObsidianSyncEnableResult> {
const resolvedPath = path.resolve(vaultPath);
// The vault root is served read/write by the WebDAV file service: the filesystem root, the
// home directory itself and system directories are never a vault (CodeQL #1372/#1373).
if (isDeniedRootDirectory(resolvedPath)) {
return { success: false, error: DENIED_ROOT_DIRECTORY_ERROR };
}
if (!fs.existsSync(resolvedPath)) {
return { success: false, error: `Vault directory not found: ${resolvedPath}` };
}

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

@@ -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

@@ -49,14 +49,22 @@ function makeRequest(url: string, options?: RequestInit): NextRequest {
return Object.assign(new Request(url, options), { ip: "127.0.0.1" }) as unknown as NextRequest;
}
function postVault(vaultPath: string): Promise<Response> {
return route.POST(
makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath }),
})
);
/**
* POST carrying an operator credential (dashboard session). Choosing the vault is an
* operator-only action on this ALWAYS_PROTECTED route (CodeQL #1372/#1373): the handler no
* longer treats an anonymous open-mode caller as the operator — the authz pipeline already
* refused that caller over HTTP — so the tests below that enable WebDAV sign in first.
*/
async function makeOperatorPost(body: Record<string, unknown>): Promise<NextRequest> {
const req = await makeManagementSessionRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
body,
});
return Object.assign(req, { ip: "127.0.0.1" }) as unknown as NextRequest;
}
async function postVault(vaultPath: string): Promise<Response> {
return route.POST(await makeOperatorPost({ vaultPath }));
}
async function errorMessageOf(res: Response): Promise<string | undefined> {
@@ -113,11 +121,7 @@ test("GET with no config → webdavEnabled:false, all creds null", async () => {
test("POST with a valid temp dir → returns { username, password }, GET shows enabled", async () => {
const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault-"));
try {
const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
});
const req = await makeOperatorPost({ vaultPath: vaultDir });
const res = await route.POST(req);
assert.equal(res.status, 200);
@@ -154,13 +158,7 @@ test("GET masks the WebDAV password for anonymous callers but reveals it to a ma
const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault-62vw-"));
try {
// Enable WebDAV so there is a stored password to leak.
const enableRes = await route.POST(
makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
})
);
const enableRes = await route.POST(await makeOperatorPost({ vaultPath: vaultDir }));
assert.equal(enableRes.status, 200);
// Anonymous (open-mode) caller: password masked, flag still set.
@@ -192,11 +190,7 @@ test("GET masks the WebDAV password for anonymous callers but reveals it to a ma
test("POST with a non-existent path → 400, body does NOT contain a stack trace", async () => {
const nonExistentPath = path.join(os.tmpdir(), "omni-nonexistent-vault-" + Date.now());
const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: nonExistentPath }),
});
const req = await makeOperatorPost({ vaultPath: nonExistentPath });
const res = await route.POST(req);
assert.equal(res.status, 400);
@@ -276,11 +270,7 @@ test("POST with a directory unrelated to the data directory still succeeds (sibl
});
test("POST with invalid body (missing vaultPath) → 400", async () => {
const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({}),
});
const req = await makeOperatorPost({});
const res = await route.POST(req);
assert.equal(res.status, 400);
});
@@ -289,11 +279,7 @@ test("DELETE after enable → webdavEnabled:false, creds cleared in GET", async
const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault2-"));
try {
// Enable first
const enableReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
});
const enableReq = await makeOperatorPost({ vaultPath: vaultDir });
const enableRes = await route.POST(enableReq);
assert.equal(enableRes.status, 200);
@@ -322,11 +308,7 @@ test("GET when disabled does not leak password even if stale data exists", async
const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault3-"));
try {
// Enable, then disable
const enableReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
});
const enableReq = await makeOperatorPost({ vaultPath: vaultDir });
await route.POST(enableReq);
const deleteReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "DELETE",

View File

@@ -0,0 +1,236 @@
// CodeQL js/path-injection #1371 (src/lib/localCorpus/index.ts) and #1372/#1373
// (src/lib/obsidianSync.ts): the caller-chosen directory behind
// - POST /api/settings/local-corpus (`rootPath`, indexed and served by the MCP search tools)
// - POST /api/settings/obsidian/webdav (`vaultPath`, root of a read/write WebDAV service)
// is a host-filesystem root. Choosing it is an operator action:
// - a machine credential (a manage-scoped API key) gets 403, on both routes;
// - an operator (dashboard session) still sets an ordinary folder such as ~/Documents/vault;
// - the filesystem root, the home directory itself and system directories (/etc, ...) are
// refused with a fixed 400 message that never echoes the requested path.
import test 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 { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-path-roots-data-"));
const FAKE_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-path-roots-home-"));
const ORIGINAL_ENV = {
DATA_DIR: process.env.DATA_DIR,
HOME: process.env.HOME,
API_KEY_SECRET: process.env.API_KEY_SECRET,
JWT_SECRET: process.env.JWT_SECRET,
INITIAL_PASSWORD: process.env.INITIAL_PASSWORD,
OMNIROUTE_DISABLE_REDIS_AUTH_CACHE: process.env.OMNIROUTE_DISABLE_REDIS_AUTH_CACHE,
};
process.env.DATA_DIR = TEST_DATA_DIR;
// os.homedir() follows $HOME on POSIX: the "home directory itself" case and the ordinary
// ~/Documents/vault folder both live in a throwaway directory, never in the real home.
process.env.HOME = FAKE_HOME;
process.env.API_KEY_SECRET = "path-roots-api-key-secret";
process.env.JWT_SECRET = "path-roots-jwt-secret";
process.env.OMNIROUTE_DISABLE_REDIS_AUTH_CACHE = "1";
delete process.env.INITIAL_PASSWORD;
const core = await import("../../src/lib/db/core.ts");
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
const settingsDb = await import("../../src/lib/db/settings.ts");
const localCorpusDb = await import("../../src/lib/db/localCorpus.ts");
const obsidianDb = await import("../../src/lib/db/obsidian.ts");
const managementPassword = await import("../../src/lib/auth/managementPassword.ts");
const localCorpusRoute = await import("../../src/app/api/settings/local-corpus/route.ts");
const webdavRoute = await import("../../src/app/api/settings/obsidian/webdav/route.ts");
const LOCAL_CORPUS_URL = "http://localhost:20128/api/settings/local-corpus";
const WEBDAV_URL = "http://localhost:20128/api/settings/obsidian/webdav";
const DENIED_ROOT_MESSAGE =
"This directory cannot be used as a root: choose a dedicated folder, not the filesystem root, the home directory itself or a system directory";
const ORDINARY_VAULT = path.join(FAKE_HOME, "Documents", "vault");
fs.mkdirSync(ORDINARY_VAULT, { recursive: true });
await settingsDb.updateSettings({
requireLogin: true,
setupComplete: true,
password: await managementPassword.hashManagementPassword("path-roots-operator-secret"),
});
const manageKey = await apiKeysDb.createApiKey("manage-automation", "machine-paths", ["manage"]);
test.after(() => {
apiKeysDb.resetApiKeyState();
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.rmSync(FAKE_HOME, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
test.beforeEach(() => {
localCorpusDb.clearLocalCorpusRoot();
obsidianDb.clearObsidianVaultPath();
obsidianDb.clearWebdavEnabled();
});
function keyRequest(url: string, body: Record<string, unknown>): Request {
return new Request(url, {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${manageKey.key}` },
body: JSON.stringify(body),
});
}
async function sessionRequest(url: string, body: Record<string, unknown>): Promise<Request> {
return makeManagementSessionRequest(url, { method: "POST", body });
}
type RouteHandler = (request: never) => Promise<Response>;
function post(handler: RouteHandler, request: Request): Promise<Response> {
return (handler as (request: Request) => Promise<Response>)(request);
}
/**
* Error text of either body shape: `{ error: "..." }` (local corpus, which renders the thrown
* Error as "Error: <message>") or `{ error: { message } }` (WebDAV, buildErrorBody).
*/
async function errorText(response: Response): Promise<string> {
const body = (await response.json()) as { error?: unknown };
if (typeof body.error === "string") return body.error.replace(/^Error: /, "");
const nested = body.error as { message?: unknown } | undefined;
return typeof nested?.message === "string" ? nested.message : JSON.stringify(body);
}
// ─── (a) a manage-scoped API key cannot choose the root ────────────────────────────────
test("a manage-scoped API key cannot set the local corpus root (403)", async () => {
const response = await post(
localCorpusRoute.POST,
keyRequest(LOCAL_CORPUS_URL, { rootPath: ORDINARY_VAULT })
);
assert.equal(response.status, 403, await response.clone().text());
assert.equal(localCorpusDb.getLocalCorpusRoot(), null, "root must not be stored");
});
test("a manage-scoped API key cannot set the WebDAV vault path (403)", async () => {
const response = await post(
webdavRoute.POST,
keyRequest(WEBDAV_URL, { vaultPath: ORDINARY_VAULT })
);
assert.equal(response.status, 403, await response.clone().text());
assert.equal(obsidianDb.getWebdavEnabled(), false, "WebDAV must stay disabled");
assert.equal(obsidianDb.getObsidianVaultPath(), null, "vault path must not be stored");
});
test("with login disabled, a manage-scoped API key still cannot set the WebDAV vault path (403)", async () => {
// /api/settings/obsidian is ALWAYS_PROTECTED: an open instance does not turn a machine
// credential into the operator for this credential-issuing surface.
await settingsDb.updateSettings({ requireLogin: false });
try {
const response = await post(
webdavRoute.POST,
keyRequest(WEBDAV_URL, { vaultPath: ORDINARY_VAULT })
);
assert.equal(response.status, 403, await response.clone().text());
assert.equal(obsidianDb.getWebdavEnabled(), false);
} finally {
await settingsDb.updateSettings({ requireLogin: true });
}
});
// ─── (b) the dashboard session keeps working with an ordinary folder ───────────────────
test("a dashboard session sets an ordinary folder (~/Documents/vault) as the local corpus root", async () => {
const response = await post(
localCorpusRoute.POST,
await sessionRequest(LOCAL_CORPUS_URL, { rootPath: ORDINARY_VAULT })
);
assert.equal(response.status, 200, await response.clone().text());
const body = (await response.json()) as { rootPath?: string };
assert.equal(body.rootPath, fs.realpathSync(ORDINARY_VAULT));
assert.equal(localCorpusDb.getLocalCorpusRoot(), fs.realpathSync(ORDINARY_VAULT));
});
test("a dashboard session sets an ordinary folder (~/Documents/vault) as the WebDAV vault", async () => {
const response = await post(
webdavRoute.POST,
await sessionRequest(WEBDAV_URL, { vaultPath: ORDINARY_VAULT })
);
assert.equal(response.status, 200, await response.clone().text());
const body = (await response.json()) as Record<string, unknown>;
assert.equal(body.vaultPath, path.resolve(ORDINARY_VAULT));
assert.ok(typeof body.password === "string" && body.password.length > 0);
assert.equal(obsidianDb.getWebdavEnabled(), true);
});
// ─── (c) dangerous roots are refused with a fixed message ──────────────────────────────
const DENIED_ROOTS: Array<{ label: string; value: () => string }> = [
{ label: "the filesystem root", value: () => path.parse(process.cwd()).root },
{ label: "the home directory itself", value: () => FAKE_HOME },
{ label: "/etc", value: () => "/etc" },
];
for (const denied of DENIED_ROOTS) {
test(`local corpus refuses ${denied.label} with a fixed 400`, async () => {
const response = await post(
localCorpusRoute.POST,
await sessionRequest(LOCAL_CORPUS_URL, { rootPath: denied.value() })
);
assert.equal(response.status, 400);
assert.equal(await errorText(response), DENIED_ROOT_MESSAGE);
assert.equal(localCorpusDb.getLocalCorpusRoot(), null, "root must not be stored");
});
test(`WebDAV vault refuses ${denied.label} with a fixed 400`, async () => {
const response = await post(
webdavRoute.POST,
await sessionRequest(WEBDAV_URL, { vaultPath: denied.value() })
);
assert.equal(response.status, 400);
assert.equal(await errorText(response), DENIED_ROOT_MESSAGE);
assert.equal(obsidianDb.getWebdavEnabled(), false, "WebDAV must stay disabled");
assert.equal(obsidianDb.getObsidianVaultPath(), null, "vault path must not be stored");
});
}
test("a symlink inside the home directory that resolves to /etc is refused on both routes", async () => {
const link = path.join(FAKE_HOME, "etc-link");
try {
fs.symlinkSync("/etc", link, "dir");
} catch {
return; // platform without symlink permission — nothing to assert
}
try {
const corpus = await post(
localCorpusRoute.POST,
await sessionRequest(LOCAL_CORPUS_URL, { rootPath: link })
);
assert.equal(corpus.status, 400);
assert.equal(await errorText(corpus), DENIED_ROOT_MESSAGE);
const vault = await post(
webdavRoute.POST,
await sessionRequest(WEBDAV_URL, { vaultPath: link })
);
assert.equal(vault.status, 400);
assert.equal(await errorText(vault), DENIED_ROOT_MESSAGE);
} finally {
fs.rmSync(link, { force: true });
}
});
// ─── helper: which directories are denied ──────────────────────────────────────────────
test("isDeniedRootDirectory: system directories and their children, root and home itself", async () => {
const { isDeniedRootDirectory } = await import("../../src/lib/deniedRootDirectories.ts");
for (const denied of ["/", FAKE_HOME, `${FAKE_HOME}/`, "/etc", "/etc/ssh", "/usr/local/bin"]) {
assert.equal(isDeniedRootDirectory(denied), true, denied);
}
for (const allowed of [ORDINARY_VAULT, path.join(FAKE_HOME, "Documents"), TEST_DATA_DIR]) {
assert.equal(isDeniedRootDirectory(allowed), false, allowed);
}
});

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");
});