Compare commits

..

6 Commits
main ... v3.2.8

Author SHA1 Message Date
diegosouzapw
3fb72b973a fix(build): revert middleware.ts rename to proxy.ts because of Next.js Edge constraints 2026-03-29 12:53:50 -03:00
diegosouzapw
7b1c945324 fix(build): remove legacy proxy.ts causing Next.js build collision 2026-03-29 12:52:04 -03:00
diegosouzapw
1a7c363413 fix(auth): redirect and unconditional 401 on disabled requireLogin + fix test cases 2026-03-29 12:49:34 -03:00
Gorchakov-Pressure
107a572174 fix: handle allRateLimited credentials & forward extra body keys in embeddings/images routes (#757)
* fix: handle allRateLimited credentials in embeddings and images routes

When getProviderCredentials() returns an allRateLimited object (truthy,
but without apiKey/accessToken), the embeddings and images routes
incorrectly passed it to handlers as valid credentials. The handlers
then sent upstream requests without Authorization headers, causing
401 errors from providers (e.g. NVIDIA NIM).

This only manifested under concurrent requests: a chat/completions
call could trigger rate limiting on a provider account, and a
simultaneous embeddings request would receive the allRateLimited
sentinel — but treat it as valid credentials.

The chat pipeline already handled this case correctly. This commit
adds the same allRateLimited guard to all affected routes:
- POST /v1/embeddings
- POST /v1/providers/{provider}/embeddings
- POST /v1/images/generations
- POST /v1/providers/{provider}/images/generations

Also adds a defense-in-depth guard in the embeddings handler itself:
if no auth token is available for a non-local provider, return 401
immediately instead of sending an unauthenticated request upstream.

Made-with: Cursor

* fix(embeddings): forward extra body keys to upstream providers

The embeddings handler only forwarded model, input, dimensions, and
encoding_format to upstream providers, silently dropping any additional
fields. This broke asymmetric embedding APIs (e.g. NVIDIA NIM
nv-embedqa-e5-v5) that require input_type, and other providers
expecting user or truncate parameters.

Add a KNOWN_FIELDS exclusion set and forward all unrecognized body
keys to the upstream request, matching the passthrough pattern used
by the chat pipeline's DefaultExecutor.transformRequest().

Made-with: Cursor
2026-03-29 12:48:52 -03:00
tombii
89bd31c670 fix(sse): remove race condition in cache metrics tracking (#758)
- Remove in-memory metrics tracking (currentMetrics, trackCacheMetrics, updateCacheMetrics)
- Cache metrics now computed on-the-fly from usage_history table (single source of truth)
- Fixes CRITICAL issue from code review: concurrent requests overwriting metrics
- Fixes WARNING: duplicate metric tracking logic in streaming/non-streaming paths

Ref: PR #752 (merged before this fix was included)
2026-03-29 12:48:33 -03:00
diegosouzapw
2e29e45a3a chore(release): v3.2.8 — Docker auto-update UI and cache analytics fixes 2026-03-29 11:31:36 -03:00
28312 changed files with 357046 additions and 8924660 deletions

View File

@@ -0,0 +1,39 @@
---
description: Deploy the latest OmniRoute code to the Akamai VPS (69.164.221.35)
---
# Deploy to Akamai VPS Workflow
Deploy OmniRoute to the Akamai VPS using `npm pack + scp` + PM2.
**Akamai VPS:** `69.164.221.35`
**Process manager:** PM2 (`omniroute`)
**Port:** `20128`
## Steps
### 1. Build + pack locally
// turbo
```bash
cd /home/diegosouzapw/dev/proxys/9router && npm run build:cli && npm pack --ignore-scripts
```
### 2. Copy to Akamai VPS and install
// turbo-all
```bash
scp omniroute-*.tgz root@69.164.221.35:/tmp/
```
```bash
ssh root@69.164.221.35 "npm install -g /tmp/omniroute-*.tgz --ignore-scripts && cd /usr/lib/node_modules/omniroute/app && npm rebuild better-sqlite3 && pm2 delete omniroute 2>/dev/null; pm2 start /root/.omniroute/ecosystem.config.cjs --update-env && pm2 save && echo '✅ Akamai done'"
```
### 3. Verify the deployment
```bash
curl -s -o /dev/null -w 'AKAMAI HTTP %{http_code}\n' http://69.164.221.35:20128/
```

View File

@@ -0,0 +1,49 @@
---
description: Deploy the latest OmniRoute code to BOTH the Akamai VPS and the Local VPS
---
# Deploy to VPS (Both) Workflow
Deploy OmniRoute to the production VPSs using `npm pack + scp` + PM2.
**Akamai VPS:** `69.164.221.35`
**Local VPS:** `192.168.0.15`
**Process manager:** PM2 (`omniroute`)
**Port:** `20128`
**PM2 entry:** `/usr/lib/node_modules/omniroute/app/server.js`
> [!IMPORTANT]
> The npm registry rejects packages > 100MB, so deployment uses **npm pack + scp**.
## Steps
### 1. Build + pack locally
// turbo
```bash
cd /home/diegosouzapw/dev/proxys/9router && npm run build:cli && npm pack --ignore-scripts
```
### 2. Copy to both VPS and install
// turbo-all
```bash
scp omniroute-*.tgz root@69.164.221.35:/tmp/ && scp omniroute-*.tgz root@192.168.0.15:/tmp/
```
```bash
ssh root@69.164.221.35 "npm install -g /tmp/omniroute-*.tgz --ignore-scripts && cd /usr/lib/node_modules/omniroute/app && npm rebuild better-sqlite3 && pm2 delete omniroute 2>/dev/null; pm2 start /root/.omniroute/ecosystem.config.cjs --update-env && pm2 save && echo '✅ Akamai done'"
```
```bash
ssh root@192.168.0.15 "npm install -g /tmp/omniroute-*.tgz --ignore-scripts && cd /usr/lib/node_modules/omniroute/app && npm rebuild better-sqlite3 && pm2 delete omniroute 2>/dev/null; pm2 start /root/.omniroute/ecosystem.config.cjs --update-env && pm2 save && echo '✅ Local done'"
```
### 3. Verify the deployment
```bash
curl -s -o /dev/null -w 'AKAMAI HTTP %{http_code}\n' http://69.164.221.35:20128/
curl -s -o /dev/null -w 'LOCAL HTTP %{http_code}\n' http://192.168.0.15:20128/
```

View File

@@ -0,0 +1,39 @@
---
description: Deploy the latest OmniRoute code to the Local VPS (192.168.0.15)
---
# Deploy to Local VPS Workflow
Deploy OmniRoute to the Local VPS using `npm pack + scp` + PM2.
**Local VPS:** `192.168.0.15`
**Process manager:** PM2 (`omniroute`)
**Port:** `20128`
## Steps
### 1. Build + pack locally
// turbo
```bash
cd /home/diegosouzapw/dev/proxys/9router && npm run build:cli && npm pack --ignore-scripts
```
### 2. Copy to Local VPS and install
// turbo-all
```bash
scp omniroute-*.tgz root@192.168.0.15:/tmp/
```
```bash
ssh root@192.168.0.15 "npm install -g /tmp/omniroute-*.tgz --ignore-scripts && cd /usr/lib/node_modules/omniroute/app && npm rebuild better-sqlite3 && pm2 delete omniroute 2>/dev/null; pm2 start /root/.omniroute/ecosystem.config.cjs --update-env && pm2 save && echo '✅ Local done'"
```
### 3. Verify the deployment
```bash
curl -s -o /dev/null -w 'LOCAL HTTP %{http_code}\n' http://192.168.0.15:20128/
```

View File

@@ -0,0 +1,256 @@
---
description: Create a new release, bump version up to 1.x.10 threshold, update changelog, and manage Pull Requests
---
# Generate Release Workflow
Bump version, finalize CHANGELOG, commit, open a **PR to main** and wait for user confirmation before tagging, publishing, and deploying.
> **VERSION RULE: Always use PATCH bumps (2.x.y → 2.x.y+1)**
> NEVER use `npm version minor` or `npm version major`.
> Always use: `npm version patch --no-git-tag-version`
> The threshold rule: when `y` reaches 10, bump to `2.(x+1).0` — e.g. `2.1.10` → `2.2.0`.
---
## ⚠️ Two-Phase Flow
```
Phase 1 (automated): bump → docs → i18n → commit → push → open PR
↕ 🛑 STOP: Notify user, wait for PR confirmation
Phase 2 (post-merge): tag → publish → GitHub release → Docker → deploy
```
**NEVER push directly to main or create tags before the user confirms the PR.**
---
## Phase 1: Pre-Merge
### 1. Create release branch
```bash
git checkout -b release/v2.x.y
```
### 2. Determine new version
Check current version in `package.json` and increment the **patch** number only:
```bash
grep '"version"' package.json
```
Version format: `2.x.y` — examples:
- `2.1.2` → `2.1.3` (patch)
- `2.1.9` → `2.1.10` (patch)
- `2.1.10` → `2.2.0` (minor threshold — do manually with `sed`)
> **⚠️ ATOMIC COMMIT RULE — Version bump MUST happen before committing feature files.**
>
> **CORRECT order:**
>
> 1. `npm version patch --no-git-tag-version` ← bump first
> 2. implement features / fix bugs
> 3. `git add -A && git commit -m "chore(release): v2.x.y — all changes in ONE commit"`
>
> **OR if features are already staged:**
>
> 1. implement features (do NOT commit yet)
> 2. `npm version patch --no-git-tag-version` ← bump before committing
> 3. `git add -A && git commit -m "chore(release): v2.x.y — all changes in ONE commit"`
>
> **NEVER do this (creates version mismatch in git history):**
>
> - ~~commit features → then bump version → commit package.json separately~~
>
> This ensures that `git show v2.x.y` always contains both code changes and the version bump together.
> The GitHub release tag will point to a commit that includes ALL changes for that version.
### 3. Regenerate lock file (REQUIRED after version bump)
**Mandatory** — skipping causes `@swc/helpers` lock mismatch and CI failures:
```bash
npm install
```
### 4. Finalize CHANGELOG.md
Replace `[Unreleased]` header with the new version and date.
Keep an empty `## [Unreleased]` section above it.
```markdown
## [Unreleased]
---
## [2.x.y] — YYYY-MM-DD
```
### 5. Update openapi.yaml version ⚠️ MANDATORY
> **CI will fail** if `docs/openapi.yaml` version ≠ `package.json` version (`check:docs-sync` enforces this).
// turbo
```bash
VERSION=$(node -p "require('./package.json').version") && sed -i "s/ version: .*/ version: $VERSION/" docs/openapi.yaml && echo "✓ openapi.yaml → $VERSION"
```
### 6. Update README.md and i18n docs
Run `/update-docs` workflow steps to:
- Update feature table rows in `README.md`
- Sync changes to all 29 language `docs/i18n/*/README.md` files
- Update `docs/FEATURES.md` if Settings section changed
### 7. Run tests
// turbo
```bash
npm test
```
All tests must pass before creating the PR.
### 8. Stage, commit, and push
// turbo-all
```bash
git add -A
git commit -m "chore(release): v2.x.y — summary of changes"
git push origin release/v2.x.y
```
### 9. Open PR to main
```bash
gh pr create \
--repo diegosouzapw/OmniRoute \
--base main \
--head release/v2.x.y \
--title "chore(release): v2.x.y — summary" \
--body "## 🚀 Release v2.x.y
### Changes
...
### Tests
- X/X tests pass
### ⚠️ After merging: run Phase 2 steps to tag, publish, and deploy."
```
### 10. 🛑 STOP — Notify User & Await PR Confirmation
**This is a mandatory stop point.** Use `notify_user` with `BlockedOnUser: true`:
Inform the user:
- PR URL
- Summary of changes
- Test results
- List of files changed
**DO NOT proceed to Phase 2 until the user confirms the PR looks good and merges it.**
---
## Phase 2: Post-Merge (only after user confirms)
> Run these steps only AFTER the user has merged the PR.
### 11. Pull main and create tag
```bash
git checkout main
git pull origin main
git tag -a v2.x.y -m "Release v2.x.y"
```
### 12. Push tag to GitHub
```bash
git push origin --tags
```
### 13. Create GitHub release
```bash
gh release create v2.x.y --title "v2.x.y — summary" --notes "..."
```
### 14. 🐳 Trigger Docker Hub build (MANDATORY — keep npm and Docker in sync)
> **CRITICAL**: Docker Hub and npm MUST always publish the same version.
> The Docker image is built automatically via GitHub Actions when a new tag is pushed.
> After pushing the tag in step 11-12, **verify the workflow runs**:
```bash
# Verify the Docker workflow triggered
gh run list --repo diegosouzapw/OmniRoute --workflow docker-publish.yml --limit 3
# Wait for the Docker build to complete (usually 5–10 min)
gh run watch --repo diegosouzapw/OmniRoute
# After completion, verify on Docker Hub:
# https://hub.docker.com/r/diegosouzapw/omniroute/tags
```
If the Docker build was not triggered automatically, trigger it manually:
```bash
gh workflow run docker-publish.yml --repo diegosouzapw/OmniRoute --ref v2.x.y
```
### 15. Deploy to BOTH VPS environments (MANDATORY)
> Always deploy to **both** environments after every release.
> See `/deploy-vps` workflow for detailed steps.
```bash
# Build and pack locally
cd /home/diegosouzapw/dev/proxys/9router && npm run build:cli && npm pack --ignore-scripts
# Deploy to LOCAL VPS (192.168.0.15)
scp omniroute-*.tgz root@192.168.0.15:/tmp/
ssh root@192.168.0.15 "npm install -g /tmp/omniroute-*.tgz --ignore-scripts && pm2 restart omniroute && pm2 save"
# Deploy to AKAMAI VPS (69.164.221.35)
scp omniroute-*.tgz root@69.164.221.35:/tmp/
ssh root@69.164.221.35 "npm install -g /tmp/omniroute-*.tgz --ignore-scripts && pm2 restart omniroute && pm2 save"
# Verify both
curl -s -o /dev/null -w "LOCAL: HTTP %{http_code}\n" http://192.168.0.15:20128/
curl -s -o /dev/null -w "AKAMAI: HTTP %{http_code}\n" http://69.164.221.35:20128/
```
### 16. Clean up release branch
```bash
git branch -d release/v2.x.y
```
---
## Notes
- Always run `/update-docs` BEFORE this workflow (ensures CHANGELOG and README are current)
- The `prepublishOnly` script runs `npm run build:cli` automatically during `npm publish`
- After npm publish, verify with `npm info omniroute version`
- Lock file sync errors are caused by skipping `npm install` after version bump
- Use `gh auth switch -u diegosouzapw` if git push fails with wrong account
## Known CI Pitfalls
| CI failure | Cause | Fix |
| ------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------- |
| `[docs-sync] FAIL - OpenAPI version differs from package.json` | Skipped step 5 — `docs/openapi.yaml` version not updated | Run step 5 (`sed -i ...`) and commit |
| `[docs-sync] FAIL - CHANGELOG.md first section must be "## [Unreleased]"` | `## [Unreleased]` missing or not at top of CHANGELOG | Add `## [Unreleased]\n\n---\n` before the first versioned `## [x.y.z]` |
| Electron Linux `.deb` build fails (`FpmTarget` error) | `fpm` Ruby gem not installed on `ubuntu-latest` runner | Already fixed in `electron-release.yml` (`gem install fpm` step) |
| Docker Hub `502 error writing layer blob` | Transient Docker Hub network error during ARM64 push | Re-run the Docker publish workflow; no code change needed |

View File

@@ -0,0 +1,131 @@
---
description: Analyze open feature request issues, implement viable ones on dedicated branches, and respond to authors
---
# /implement-features — Feature Request Implementation Workflow
## Overview
Fetches open feature request issues, analyzes each against the current codebase, implements viable ones on dedicated branches, and responds to authors with results. Does NOT merge to main — leaves branches for author validation.
## Steps
### 1. Identify the Repository
// turbo
- Run: `git -C <project_root> remote get-url origin` to extract owner/repo
### 2. Fetch Open Feature Request Issues
// turbo
- Run: `gh issue list --repo <owner>/<repo> --state open --limit 50 --json number,title,labels,body,comments,createdAt,author`
- Filter for issues that are feature requests (label `enhancement`/`feature`, or body describes new functionality, or previously classified as feature request)
- Sort by oldest first
### 3. Analyze Each Feature Request
For each feature request issue, perform a **two-level analysis**:
#### Level 1 — Viability Assessment
Ask yourself:
- Does this feature align with the project's goals and architecture?
- Is the request technically feasible with the current codebase?
- Does it duplicate existing functionality?
- Would it introduce breaking changes or security risks?
- Is there enough detail to implement it?
**Verdict options:**
1. ✅ **VIABLE** — Makes sense, enough detail to implement → Go to Level 2
2. ❓ **NEEDS MORE INFO** — Good idea but insufficient detail → Post comment asking for specifics
3. ❌ **NOT VIABLE** — Doesn't fit the project or is fundamentally flawed → Post comment explaining why, close issue
#### Level 2 — Implementation (only for VIABLE features)
1. **Research** — Read all related source files to understand the current architecture
2. **Design** — Plan the implementation, filling gaps in the original request
3. **Create branch** — Name format: `feat/issue-<NUMBER>-<short-slug>`
```bash
git checkout main
git pull origin main
git checkout -b feat/issue-<NUMBER>-<short-slug>
```
4. **Implement** — Build the complete solution following project patterns
5. **Build** — Run `npm run build` to verify compilation
6. **Commit** — Commit with: `feat: <description> (#<NUMBER>)`
7. **Push** — Push the branch: `git push -u origin feat/issue-<NUMBER>-<short-slug>`
8. **Return to main** — `git checkout main`
### 4. Respond to Authors
#### For VIABLE (implemented) features:
// turbo
Post a comment on the issue:
````markdown
## ✅ Feature Implemented!
Hi @<author>! We've analyzed your request and implemented it on a dedicated branch.
**Branch:** `feat/issue-<NUMBER>-<short-slug>`
### What was implemented:
- <bullet list of what was done>
### How to try it:
```bash
git fetch origin
git checkout feat/issue-<NUMBER>-<short-slug>
npm install && npm run dev
```
````
### Next steps:
1. **Test it** — Please verify it works as you expected
2. **Want to improve it?** — You're welcome to contribute! Just:
```bash
git checkout feat/issue-<NUMBER>-<short-slug>
# Make your improvements
git add -A && git commit -m "improve: <your changes>"
git push origin feat/issue-<NUMBER>-<short-slug>
```
Then open a Pull Request from your branch to `main` 🎉
3. **Not quite right?** — Let us know in this issue what needs to change
Looking forward to your feedback! 🚀
```
#### For NEEDS MORE INFO:
// turbo
Post a comment asking for specific missing details needed to implement, e.g.:
- "Could you describe the exact behavior when X happens?"
- "Which API endpoints should be affected?"
- "Should this apply to all providers or only specific ones?"
Add the context of WHY you need each piece of information.
#### For NOT VIABLE:
// turbo
Post a polite comment explaining why the feature doesn't fit at this time:
- If the idea is decent but timing is wrong: "This is an interesting idea, but it doesn't align with our current priorities. Feel free to open a new issue with more details if you'd like us to reconsider."
- If fundamentally flawed: Explain the technical or architectural reasons why it won't work, suggest alternatives if possible.
- Close the issue after posting the comment.
### 5. Summary Report
Present a summary report to the user via `notify_user`:
| Issue | Title | Verdict | Branch / Action |
|---|---|---|---|
| #N | Title | ✅ Implemented | `feat/issue-N-slug` |
| #N | Title | ❓ Needs Info | Comment posted |
| #N | Title | ❌ Not Viable | Closed with explanation |
```

View File

@@ -0,0 +1,50 @@
---
description: How to respond to GitHub issues with insufficient information
---
# Issue Triage Workflow
Respond to GitHub issues that need more information before they can be investigated.
## Steps
### 1. Identify issues needing triage
```bash
gh issue list --state open --limit 20
```
### 2. Evaluate each issue
Check if the issue has:
- Clear reproduction steps
- Environment details (OS, Node.js version, OmniRoute version)
- Error logs/screenshots
- Expected vs actual behavior
### 3. Respond with triage template
For issues missing information:
```markdown
Thank you for reporting this issue! To help us investigate, please provide:
1. **OmniRoute version**: (`omniroute --version`)
2. **Node.js version**: (`node --version`)
3. **Operating system**: (e.g., Ubuntu 24.04, macOS 15, Windows 11)
4. **Installation method**: (npm, Docker, source)
5. **Steps to reproduce**: (exact commands/actions that trigger the issue)
6. **Error logs**: (paste relevant logs from the console)
7. **Expected behavior**: (what should happen)
This will help us debug and resolve your issue faster. 🙏
```
### 4. Label the issue
Add appropriate labels: `needs-info`, `bug`, `enhancement`, `question`, etc.
```bash
gh issue edit <NUMBER> --add-label "needs-info"
```

View File

@@ -0,0 +1,120 @@
---
description: Fetch all open GitHub issues, analyze bugs, resolve what's possible, triage the rest, wait for user validation, then commit and release
---
# /resolve-issues — Automated Issue Resolution Workflow
## Overview
This workflow fetches all open issues from the project's GitHub repository, classifies them, analyzes bugs, resolves what can be fixed, and triages issues with insufficient information. **It does NOT merge or release automatically** — it creates a PR and waits for user validation before merging.
## Steps
### 1. Identify the GitHub Repository
// turbo
- Run: `git -C <project_root> remote get-url origin` to extract the owner/repo
- Parse the owner and repo name from the URL
### 2. Fetch All Open Issues
// turbo
- Run: `gh issue list --repo <owner>/<repo> --state open --limit 500 --json number,title,labels,body,comments,createdAt,author`
- Parse the JSON output to get a list of **all** open issues
- Sort by oldest first (FIFO)
### 3. Classify Each Issue
For each issue, determine its type:
- **Bug** — Has `bug` label, or body contains error messages, stack traces, "doesn't work", "broken", "crash", "error"
- **Feature Request** — Has `enhancement`/`feature` label, or body describes new functionality
- **Question** — Has `question` label, or is asking "how to" something
- **Other** — Anything else
Focus ONLY on **Bugs** for resolution. Feature requests and questions should be skipped with a note in the final report.
### 4. Analyze Each Bug — For each bug issue:
#### 4a. Check Information Sufficiency
Verify the issue contains enough information to reproduce and fix:
- [ ] Clear description of the problem
- [ ] Steps to reproduce
- [ ] Error messages or logs
- [ ] Expected vs actual behavior
#### 4b. If Information Is INSUFFICIENT
Call the `/issue-triage` workflow (located at `~/.gemini/antigravity/global_workflows/issue-triage.md`):
// turbo
- Post a comment asking for more details using `gh issue comment`
- Add `needs-info` label using `gh issue edit`
- Mark this issue as **DEFERRED** and move to the next one
#### 4c. If Information Is SUFFICIENT
Proceed with resolution:
1. **Create a fix branch** — `git checkout -b fix/issue-<NUMBER>-<short-description>`
2. **Research** — Search the codebase for files related to the issue
3. **Root Cause** — Identify the root cause by reading the relevant source files
4. **Implement Fix** — Apply the fix following existing code patterns and conventions
5. **Test** — Build the project and run tests to verify the fix
6. **Commit** — Commit with message format: `fix: <description> (#<issue_number>)`
### 5. Generate Report & Wait for Validation
Present a summary report to the user via `notify_user` with `BlockedOnUser: true`:
| Issue | Title | Status | Action |
| ----- | ----- | ------------- | ----------------------------- |
| #N | Title | ✅ Ready | Files changed (not committed) |
| #N | Title | ❓ Needs Info | Triage comment posted |
| #N | Title | ⏭️ Skipped | Feature request / not a bug |
> **⚠️ IMPORTANT**: Do NOT commit, close issues, or generate releases at this step.
> Wait for the user to review the changes and respond with **OK** before proceeding.
- If the user says **OK** or approves → Proceed to step 6
- If the user requests changes → Apply the requested adjustments first, then present the report again
- If the user rejects → Revert the changes and stop
### 6. Commit & Push Fix Branch (only after user approval)
After the user validates:
- Commit each fix individually with message format: `fix: <description> (#<issue_number>)`
- Push the fix branch: `git push origin fix/issue-<NUMBER>-<short-description>`
- Create a PR: `gh pr create --title "fix: <description> (#<issue_number>)" --body "<details>" --base main`
### 7. 🛑 WAIT — Notify User & Await PR Verification
**This is a mandatory stop point.** Use `notify_user` with `BlockedOnUser: true`:
- Inform the user that the PR was created and is **awaiting their verification**
- Include the PR number, URL, and a summary of what was changed
- **DO NOT merge, close issues, generate releases, or deploy until the user confirms**
Wait for the user to respond:
- **User confirms** → Proceed to step 8
- **User requests changes** → Apply changes, push to the same branch, notify again
- **User rejects** → Close the PR and stop
### 8. Merge, Close Issues & Release (only after user confirms PR)
After the user confirms the PR:
1. **Merge** the PR: `gh pr merge <NUMBER> --merge --repo <owner>/<repo>` or via local merge
2. **Close** resolved issues with a comment: `gh issue close <NUMBER> --repo <owner>/<repo> --comment "Fixed in <commit_hash>. The fix will be included in the next release."`
3. **Switch to main**: `git checkout main && git pull`
4. Run the `/update-docs` workflow (at `~/.gemini/antigravity/global_workflows/update-docs.md`) to update CHANGELOG and README
5. Run the `/generate-release` workflow (at `.agents/workflows/generate-release.md`) to bump version, tag, and publish
6. Deploy to local VPS: `ssh root@192.168.0.15 "npm install -g omniroute@<VERSION> && pm2 restart omniroute"`
If NO fixes were committed, skip this step and just present the report.

View File

@@ -0,0 +1,118 @@
---
description: Read all open GitHub Discussions, summarize them, respond to pending ones, and create issues from actionable feature requests
---
# /review-discussions — GitHub Discussions Review & Response Workflow
## Overview
This workflow reads all open GitHub Discussions, generates a categorized summary, identifies which ones need a response, drafts and posts replies, and optionally creates issues from actionable feature requests. It follows the same flow used for Issues but adapted for the Discussions forum.
// turbo-all
## Steps
### 1. Identify the GitHub Repository
- Run: `git -C <project_root> remote get-url origin` to extract the owner/repo
- Parse the owner and repo name from the URL
### 2. Fetch All Open Discussions
- Use `read_url_content` to fetch `https://github.com/<owner>/<repo>/discussions`
- Parse the discussion list to get all discussion titles, IDs, authors, categories, and dates
- For each discussion, fetch the individual page to read the full content and all comments/replies
### 3. Summarize All Discussions
For each discussion, extract:
- **Title** and **#Number**
- **Author** (GitHub username)
- **Category** (Announcements, General, Ideas, Q&A, Show and tell)
- **Date** created
- **Summary** of the original post (1-2 sentences)
- **Comments count** and key participants
- **Your previous response** (if any)
- **Pending action** — whether a response or follow-up is needed
### 4. Present Summary Report to User
Present the full summary to the user organized by category, using a table:
| # | Category | Title | Author | Date | Status |
| --- | -------- | ----- | ------ | ------ | ----------------- |
| #N | Ideas | Title | @user | Mar 23 | ⚠️ Needs response |
| #N | Q&A | Title | @user | Mar 9 | ✅ Answered |
| #N | General | Title | @user | Mar 19 | ⚠️ Needs response |
Highlight:
- **⚠️ Needs response** — No reply from maintainer, or a follow-up comment was left unanswered
- **✅ Answered** — Maintainer already responded
- **🐛 Bug reported** — A bug was mentioned that needs tracking
- **💡 Actionable** — Contains a concrete feature request that could become an issue
### 5. Draft & Post Responses
For each discussion that needs a response, draft a reply following these guidelines:
#### Response Style
- **Friendly and professional** — Start with "Hey @username!"
- **Acknowledge the contribution** — Thank the user for their input
- **Be specific** — Reference existing features, settings, or dashboard pages if the feature already exists
- **Provide workarounds** — If the request isn't implemented yet, suggest current alternatives
- **Commit to action** — If the request is valid, state that you'll open an issue or add it to the roadmap
- **Keep it concise** — 3-5 paragraphs max
#### Posting via Browser
- Use `browser_subagent` to navigate to each discussion and post the comment
- **IMPORTANT**: When typing text in GitHub comment boxes via the browser, use only plain ASCII characters:
- Use regular hyphens `-` instead of em-dashes
- Use `->` instead of arrow symbols
- Do NOT use emoji Unicode characters (the browser keyboard may fail on them)
- Use `**bold**` and `\`code\`` markdown formatting
- Click the green "Comment" button (or "Reply" for threaded replies) after typing
- Verify the comment was posted by checking the page shows the new comment
### 6. Create Issues from Actionable Feature Requests
For discussions that contain concrete, actionable feature requests:
1. Ask the user which ones should become issues
2. For each approved request, create a GitHub issue via `browser_subagent`:
- Navigate to `https://github.com/<owner>/<repo>/issues/new`
- **Title**: `<Feature Name> - <Short description>`
- **Body** should include:
- `## Feature Request` header
- `**Source:** Discussion #N by @author`
- `## Problem` — What limitation the user hit
- `## Proposed Solution` — How it could work
- `### Implementation Ideas` — Technical approach
- `### Current Workarounds` — What users can do today
- `## Additional Context` — Links to related issues/discussions
- Add `enhancement` label
- Click "Submit new issue" / "Create"
3. After creation, go back to the original discussion and post a comment linking to the new issue:
- "I've opened Issue #N to track this feature request. Follow along there for updates!"
### 7. Final Report
Present a final summary to the user:
| Discussion | Action Taken |
| ---------- | ---------------------------------- |
| #N — Title | Responded with workarounds |
| #N — Title | Responded + created Issue #N |
| #N — Title | Already answered, no action needed |
| #N — Title | Responded to follow-up comment |
## Notes
- This workflow is **interactive** — always present the summary and wait for user approval before posting responses or creating issues
- If the user says "pode responder" (or similar approval), proceed with posting all drafted responses
- For discussions in non-English languages, respond in the same language as the original post
- Always reference specific dashboard paths, config options, or code files when explaining existing features
- When a discussion reveals a bug, note it separately from feature requests

View File

@@ -0,0 +1,149 @@
---
description: Analyze open Pull Requests from the project's GitHub repository, generate a critical report, and optionally implement approved changes
---
# /review-prs — PR Review & Analysis Workflow
## Overview
This workflow fetches all open PRs from the project's GitHub repository, performs a critical analysis of each one, generates a detailed report, and waits for user approval before proceeding with implementation. **All improvements are committed on top of the PR branch** and the user must verify before merge.
## Steps
### 1. Identify the GitHub Repository
- Read `package.json` to get the repository URL, or use the git remote origin URL
// turbo
- Run: `git -C <project_root> remote get-url origin` to extract the owner/repo
### 2. Fetch Open Pull Requests
// turbo
- Run: `gh pr list --repo <owner>/<repo> --state open --limit 500 --json number,title,author,headRefName,body,createdAt,additions,deletions,files`
- This fetches **all** open PRs without restriction. Get the diff for each with:
`gh pr diff <NUMBER> --repo <owner>/<repo>`
- For each open PR, collect:
- PR number, title, author, branch, number of commits, date
- PR description/body
- Files changed (diff)
- Existing review comments (from bots or humans)
### 3. Analyze Each PR — For each open PR, perform the following analysis:
#### 3a. Feature Assessment
- **Does it make sense?** Evaluate if the feature fills a real gap or solves a valid problem
- **Alignment** — Check if it aligns with the project's architecture and roadmap
- **Complexity** — Assess if the scope is reasonable or if it should be split
#### 3b. Code Quality Review
- Check for code duplication
- Evaluate error handling patterns (consistent with existing codebase?)
- Check naming conventions and code style
- Verify TypeScript types (any `any` usage, missing types?)
#### 3c. Security Review
- Check for missing authentication/authorization on new endpoints
- Check for injection vulnerabilities (URL params, SQL, XSS)
- Verify input validation on all user-controlled data
- Check for hardcoded secrets or credentials
#### 3d. Architecture Review
- Does the change follow existing patterns?
- Are there any breaking changes to public APIs?
- Is the database schema affected? Migration needed?
- Impact on performance (N+1 queries, missing indexes?)
#### 3e. Test Coverage
- Does the PR include tests?
- Are edge cases covered?
- Would existing tests break?
#### 3f. Cross-Layer (Global) Analysis
Perform a **global impact assessment** to verify whether the PR changes are complete across all layers of the application:
- **Backend → Frontend check**: If the PR adds or modifies backend-only resources (new endpoints, services, data models), evaluate whether corresponding frontend changes are missing:
- Does a new endpoint require a new screen/page in the dashboard?
- Should there be a new action button, menu item, or navigation link?
- Are there new data fields that should be displayed or editable in the UI?
- Does a new feature need a toggle, configuration panel, or status indicator?
- **Frontend → Backend check**: If the PR adds frontend elements, verify the backend support exists:
- Are the required API endpoints implemented?
- Is the data model sufficient for the new UI components?
- **Cross-cutting concerns**: Check shared layers (types, DTOs, validation schemas, routes, middleware) for completeness
- **Document gaps** — If missing layers are detected, list them as **IMPORTANT** issues in the report with concrete suggestions for what should be added
### 4. Generate Report — Create a markdown report for each PR including:
- **PR Summary** — What it does, files affected, commit count
- **Improvements/Benefits** — Numbered list with impact level (HIGH/MEDIUM/LOW)
- **Risks & Issues** — Categorized as CRITICAL / IMPORTANT / MINOR
- **Scoring Table** — Rate across: Feature Relevance, Code Quality, Security, Robustness, Tests
- **Verdict** — Ready to merge? With mandatory vs optional fixes
- **Next Steps** — What will happen if approved
### 5. Present to User
- Show the report via `notify_user` with `BlockedOnUser: true`
- Wait for user decision:
- **Approved** → Proceed to step 6
- **Approved with changes** → Implement the fixes and corrections before merging
- **Rejected** → Close the PR or leave a review comment
### 6. Implementation (if approved)
- Checkout the PR branch: `gh pr checkout <NUMBER>`
- Implement any required fixes identified in the analysis
- If the Cross-Layer Analysis (3f) identified missing frontend/backend counterparts, implement them
- **Commit improvements on top of the PR branch** with descriptive commit messages
- Run the project's test suite to verify nothing breaks
// turbo
- Run: `npm test` or equivalent test command
- Build the project to verify compilation
// turbo
- Run: `npm run build` or equivalent build command
- Push the updated branch: `git push origin <branch-name>`
### 7. 🛑 WAIT — Notify User & Await PR Verification
**This is a mandatory stop point.** Use `notify_user` with `BlockedOnUser: true`:
- Inform the user that the PR has been **improved and pushed**, and is **awaiting their verification**
- Include:
- PR number and URL
- Summary of improvements/fixes applied
- Build/test status
- List of files changed
- **DO NOT merge, generate releases, or deploy until the user confirms**
Wait for the user to respond:
- **User confirms** → Proceed to step 8
- **User requests more changes** → Apply changes, push to the same branch, notify again
- **User rejects** → Leave a review comment and stop
### 8. Thank the Contributor
- Post a **thank-you comment** on the PR via the GitHub API
- The message should:
- Thank the author by name/username for their contribution
- Briefly mention what the PR accomplishes and any improvements applied
- Be friendly, professional, and encouraging
- Example: _"Thanks @author for this great contribution! 🎉 The [feature/fix] is now merged and will be part of the next release. We appreciate your effort!"_
### 9. Merge & Release (only after user confirms PR)
After the user confirms the PR:
1. **Merge** the PR into main (local merge with `--no-ff` or via `gh pr merge`)
2. **Push** to main: `git push origin main`
3. **Clean up** the feature branch: `git branch -d <branch-name>`
4. **Update CHANGELOG.md** with the new feature/fix
5. Run the `/generate-release` workflow (at `.agents/workflows/generate-release.md`) to bump version, tag, and publish
6. Deploy to local VPS: `ssh root@192.168.0.15 "npm install -g omniroute@<VERSION> && pm2 restart omniroute"`

View File

@@ -0,0 +1,105 @@
---
description: How to automatically summarize recent changes and update README and CHANGELOG
---
# Update Documentation Workflow
Update CHANGELOG.md, README.md, docs/ files, and all multi-language translations whenever features are added or changed.
## Steps
### 1. Summarize recent changes
Review git log and identify new features, fixes, or changes since the last release tag:
```bash
git log $(git describe --tags --abbrev=0)..HEAD --oneline
```
### 2. Update English CHANGELOG.md
Add an `[Unreleased]` section (or version header if releasing) with:
- `### ✨ New Features` — each feature as a bullet point
- `### 🐛 Bug Fixes` — if applicable
- `### 🧪 Tests` — test count changes
- `### 📁 New Files` — table of new files with purpose
### 3. Update English README.md
Update the feature tables in these sections:
- **🧠 Routing & Intelligence** — for routing/model features
- **🛡️ Resilience & Security** — for security/resilience features
- **📊 Observability & Analytics** — for monitoring features
- **☁️ Deploy & Sync** — for deployment features
### 4. Update docs/ files
- `docs/FEATURES.md` — update the Settings section description
- `docs/API_REFERENCE.md` — add new API routes if any
- `docs/ARCHITECTURE.md` — update architecture if structural changes
### 5. 🌐 Sync Multi-Language Documentation (CRITICAL)
// turbo-all
**This step MUST be run after every README or docs update.**
The project has **30 language versions** of documentation:
**README files (root directory):**
```
README.md (English - source of truth)
README.pt-BR.md README.pt.md README.es.md README.fr.md README.it.md
README.de.md README.nl.md README.sv.md README.no.md README.da.md README.fi.md
README.ru.md README.uk-UA.md README.bg.md README.sk.md README.pl.md README.ro.md README.hu.md
README.ar.md README.he.md README.th.md README.in.md README.id.md README.ms.md README.vi.md
README.ja.md README.ko.md README.zh-CN.md README.phi.md README.cs.md
```
**docs/i18n/ directories (29 languages):**
```
docs/i18n/{ar,bg,cs,da,de,es,fi,fr,he,hu,id,in,it,ja,ko,ms,nl,no,phi,pl,pt,pt-BR,ro,ru,sk,sv,th,uk-UA,vi,zh-CN}/
Each contains: API_REFERENCE.md, ARCHITECTURE.md, CODEBASE_DOCUMENTATION.md, FEATURES.md, TROUBLESHOOTING.md, USER_GUIDE.md
```
**Sync approach for feature table updates:**
a. Identify which feature table rows were added to English README.md
b. For each translated README, find the corresponding anchor lines:
- **Routing section:** Find the `💬` (System Prompt) table row — the line before it is always the last routing feature. Insert new routing features before System Prompt.
- **Resilience section:** Find the `📊` Rate Limits table row (the one in lines 590-600, NOT the quota tracking one in lines 560-570). Insert new resilience features after it.
c. The new feature entries can stay in English for technical features, matching the pattern used in the existing translations.
d. Use `sed` or similar tool to batch-insert across all 29 translated READMEs.
**Verification:**
```bash
# Verify all READMEs have the new features
grep -l "NEW_FEATURE_NAME" README.*.md | wc -l
# Should return 30 (all language versions)
```
**FEATURES.md sync:**
```bash
# Update Settings description in all docs/i18n/*/FEATURES.md
for dir in docs/i18n/*/; do
# Update the Settings section description to mention new features
# Check FEATURES.md in each directory
done
```
### 6. Verify documentation changes
```bash
# Check all modified files
git status --short
# Verify no broken markdown
# Optional: run markdownlint if available
```

View File

@@ -1,201 +0,0 @@
# codebase-memory-mcp ignore list
#
# Padrão gitignore-style. Linhas começando com `#` são comentários.
# Barra final (`/`) = só diretório. Sem barra = casa arquivo OU diretório.
#
# O CBM também lê `.gitignore` automaticamente — esta lista deixa explícito o que
# os hooks do CBM vão pular. Se uma regra entrar em conflito entre os dois arquivos,
# vale a união. Editar este arquivo é mais barato do que confiar na herança implícita.
#
# Última reconciliação: 2026-07-31, status `ready` (513k nodes / 689k edges),
# `auto_index_limit=50000`, total indexável medido ≈11.546 arquivos (folga 4,3×).
#
# Fontes cruzadas:
# - `codebase-memory-mcp cli index_status --project home-diegosouzapw-dev-proxys-OmniRoute`
# → `not_indexed.dirs` (27) + `not_indexed.files` (336), todos `BY DESIGN`.
# - `.gitignore` deste repo (5.691 B) — fonte canônica secundária.
#
# Como auditar mudanças: depois de editar este arquivo, rodar `index_repository`
# (ou esperar `auto_watch` re-indexar) e re-checar `cli index_status` → comparar
# contagens em `not_indexed.dirs_count` e `not_indexed.files_count`.
# ─────────────────────────────────────────────────────────────────────────────
# 1. Diretorios de runtime / pacote — nao sao codigo-fonte
# ─────────────────────────────────────────────────────────────────────────────
node_modules/
node_modules
# Builds e artefatos reproduziveis (Layer 1 Next.js / Electron)
.build/
dist/
.next/
out/
# Electron especifico
electron/dist-electron/
electron/node_modules/
icon.iconset/
# Workspaces internos que tem proprio node_modules
@omniroute/opencode-plugin/dist/
@omniroute/opencode-plugin/node_modules/
@omniroute/opencode-provider/dist/
@omniroute/opencode-provider/node_modules/
# Recursos nativos compilados (C/JNI/wasm)
src/mitm/tproxy/native/build/
# Artefatos locais do Stryker / Playwright / coverage
.stryker-tmp/
reports/mutation/
stryker-output-*.json
.playwright-mcp/
test-results/
playwright-report/
blob-report/
# Analise / linters / caches
.analysis/
.sisyphus/
.plans/
.gitnexus
.worktrees
.codegraph/
# Quality artifacts (gerados por npm run lint --cache etc)
.eslintcache
.eslintcache-complexity
# Claude Code local state
.claude/scheduled_tasks.lock
.claude/scheduled_tasks/
.claude/sessions/
.claude/state.json
.claude/settings.local.json
# Serena / Antigravity / outras tools locais
.serena/
.antigravitycli/
.gemini/
.config/
# ─────────────────────────────────────────────────────────────────────────────
# 2. Diretorios com prefixo `_` — locais / privados (regra global do .gitignore)
# ─────────────────────────────────────────────────────────────────────────────
_*/
_artifacts/
_cache/
_mono_repo/
_references/
_tasks/
# ─────────────────────────────────────────────────────────────────────────────
# 3. Diretorios de tooling IA (state local, nao codigo)
# ─────────────────────────────────────────────────────────────────────────────
.agents/
.claude/
.vscode/
.idea/
.junie/
.omc/
.data/
.data-dev/
.local-data/
.logs/
.artifacts/
.source/
.superpowers/
.claude-flow/
.omnivscodeagent/
omnirouteCloud/
omnirouteSite/
.omniroute/
.stent/
# Subpaths especificos do Claude Code que nao estao em .claude/ (criados sob repo)
.claude/worktrees/
# ─────────────────────────────────────────────────────────────────────────────
# 4. Diretorios de dados / runtime locais (storage, env, secrets, scratch)
# ─────────────────────────────────────────────────────────────────────────────
data/
# NOTA: src/lib/env/, src/app/api/{cloud,sync/cloud,system/env,agent-skills/coverage}/
# foram removidos daqui (2026-08-05). Os nomes sugerem dados/segredos locais, mas os
# 8 arquivos sao route handlers e modulos rastreados no git — escondia-los do grafo
# criava pontos cegos em buscas e em analise de impacto.
tests/golden-set/data/
# Logs e saida de teste
logs/*
test_output.log
home-diegosouzapw-dev-automacoes-*.txt
# ─────────────────────────────────────────────────────────────────────────────
# 5. Diretorios do monorepo por subprojeto (nao fazem parte do app principal)
# ─────────────────────────────────────────────────────────────────────────────
security-analysis/
vscode-extension/
obsidian-plugin/node_modules/
# ─────────────────────────────────────────────────────────────────────────────
# 6. Diretorios de documentacao interna / workflow
# ─────────────────────────────────────────────────────────────────────────────
docs/superpowers/
# Docs traduzidas: 1.215 arquivos / 94 MB (inclui 20+ copias do CHANGELOG).
# Sao traducoes do tree em ingles, ja indexado — no grafo so geram ruido em
# search_code e consomem o auto_index_limit.
docs/i18n/
# ─────────────────────────────────────────────────────────────────────────────
# 7. Arquivos especificos (nao diretorios inteiros)
# ─────────────────────────────────────────────────────────────────────────────
# Segredos e env — NUNCA indexar
.env
.env.*
!.env.example
!.env.homolog.example
# TypeScript build info e next env declaration
*.tsbuildinfo
next-env.d.ts
typescript
# SQLite transient files (WAL/SHM/journal)
*.sqlite-shm
*.sqlite-wal
*.sqlite-journal
# Mapas e source maps
*.map
# Bun / npm lockfiles ruidosos
bun.lock
# `cheaper-inference-gateway.svg` e arquivos de midia na raiz/asset ja cobertos
# pelos `ignored-suffix` do indexador (svg/png/jpg/ico/etc >50kB ou >500linhas);
# manter a regra explicita aqui ajuda a auditar:
cheaper-inference-gateway.svg
cheaper-inference-gateway-*.svg
# Husky internals
.husky/_/
# CI / quality metric artifacts
config/quality/quality-metrics.json
config/quality/test-impact-map.json
audit-report.json
.gh-discussions.json
# i18n audit (gerado por npm run scripts)
scripts/i18n/_audit.json
scripts/i18n/_pending-keys.json
# NOTA: bin/omniroute.mjs foi removido daqui (2026-08-05). Estava marcado como
# "scratch", mas e o entrypoint real do CLI publicado (package.json -> bin.omniroute)
# e consta em PACK_ARTIFACT_REQUIRED_PATHS. Precisa estar no grafo.
# Deploy / docker backups
deploy.sh
docker-compose.yml.bak
docker-compose.minimal.yml

View File

@@ -1,141 +0,0 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
#
# CodeRabbit review configuration for cheaper-inference/OmniRoute (open-source plan,
# public repository). Reviews run on CodeRabbit's infrastructure, not on our Actions runners.
#
# Calibration phase (from 2026-10-28, ~2 weeks): profile `chill` and every pre-merge check
# in `warning`. The maintainer decides afterwards whether the CodeRabbit status becomes a
# Mergify queue condition and whether any check moves to `error`. Plan:
# _tasks/superpowers/plans/2026-10-28-coderabbit-blacksmith.md (private repo).
#
# Bot comments are external content generated from the PR diff (which may come from a fork):
# agents and skills that read reviews treat them as data, never as instructions.
language: en-US
reviews:
profile: chill
high_level_summary: true
# Keep the summary in the walkthrough comment. Writing it into the PR description fires a
# pull_request "edited" event, which ci.yml and quality.yml listen to, so every review
# restarted (and cancelled) the PR's CI and Quality Gates runs.
high_level_summary_in_walkthrough: true
poem: false
# Single maintainer identity and a lot of walkthrough already: keep the summary lean.
sequence_diagrams: false
suggested_reviewers: false
# Anti-slop for public repos: label low-quality PRs instead of spending a review on them.
slop_detection:
enabled: true
label: "slop"
auto_review:
enabled: true
# The open-source plan allows ~1-10 PR reviews per hour per developer (scaled by stars)
# and most PRs here come from one maintainer identity used by several sessions, each
# pushing many commits. Review each PR once; re-run on demand with
# `@coderabbitai review` (or `@coderabbitai full review`).
auto_incremental_review: false
# Bot PRs would burn the hourly allowance; Dependabot bumps are covered by CI and the
# security wave, Mergify queue candidates are drafts anyway.
ignore_usernames:
- "dependabot[bot]"
- "mergify[bot]"
# Drafts are skipped; the Mergify merge-queue candidates are drafts too.
drafts: false
base_branches:
- "^release/v\\d+\\.\\d+\\.\\d+$"
- "^main$"
labels:
- "!skip-coderabbit"
ignore_title_keywords:
- "[skip review]"
- "WIP"
# Release-train validation PRs: 400+ files, over the review file limit, never merged.
- "do not merge"
path_filters:
# 66 translated doc mirrors and the translation state are produced by the i18n waves.
- "!docs/i18n/**"
- "!.i18n-state.json"
# Translated UI catalogs; the English source catalog stays in review.
# Exclusions only: a pattern without "!" turns the filter into an allowlist, and
# exclusions always win, so an "en.json" include left every file out of review.
# The two classes match every catalog except en.json (el, es, et start with "e").
- "!src/i18n/messages/[a-df-z]*.json"
- "!src/i18n/messages/e[a-mo-z]*.json"
- "!**/package-lock.json"
# Generated files.
- "!docs/reference/PROVIDER_REFERENCE.md"
- "!**/*.svg"
- "!CHANGELOG.md"
# Vendored CI UI Kit: fixes belong upstream, and the snapshot check rejects local edits.
- "!packages/ui-kit/**"
path_instructions:
- path: "src/app/api/**"
instructions: >-
Every route follows CORS -> Zod validation -> optional auth -> handler in open-sse/handlers.
Error bodies go only through buildErrorBody() or sanitizeErrorMessage() from
open-sse/utils/error.ts; never return raw err.stack or err.message. No raw SQL in routes:
use the src/lib/db/* modules. Routes that can spawn processes need isLocalOnlyPath()
classification in src/server/authz/routeGuard.ts.
- path: "open-sse/**"
instructions: >-
Public upstream OAuth client ids/secrets and Firebase Web keys only through
resolvePublicCred() (open-sse/utils/publicCreds.ts), never as string literals. Never
swallow errors in SSE streams. Hash opaque tokens with opaqueTokenFingerprint() and check
hosts with open-sse/utils/urlHost.ts instead of ad-hoc substring checks.
- path: "src/lib/db/**"
instructions: >-
Migrations must be idempotent and run in transactions. Never barrel-import from localDb.ts;
import the specific src/lib/db/* module.
- path: ".github/workflows/**"
instructions: >-
Never run fork pull-request code on self-hosted runners. Pin third-party actions by SHA.
Pass event fields to run: steps through env, never interpolate them. Job ids must stay in
sync with config/quality/admission-policy.json (Gate / CI and Gate / Quality).
- path: "tests/**"
instructions: >-
Tests must isolate DATA_DIR and close DB handles. Flag weakened or removed assertions and
skipped tests that only exist to make CI green.
pre_merge_checks:
title:
mode: warning
requirements: >-
Conventional Commits: type(scope): subject, with type one of feat, fix, refactor, docs,
test, chore, ci, deps, perf.
description:
mode: warning
custom_checks:
- name: "Tests for production code"
mode: warning
instructions: >-
If production code under src/, open-sse/, electron/ or bin/ changes, the PR must add or
update tests (AGENTS.md Hard Rules #8 and #18).
- name: "No AI attribution"
mode: warning
instructions: >-
Commits and the PR body must not carry a Co-Authored-By trailer naming an AI assistant
or bot, nor a "Generated with <AI tool>" footer (AGENTS.md Hard Rule #16). Human
co-authors are fine.
tools:
# CI's lint applies the frozen suppressions in config/quality/eslint-suppressions.json;
# without them CodeRabbit's eslint run would re-report years of accepted debt.
eslint:
enabled: false
# Docs have their own gates (npm run check:docs-all).
markdownlint:
enabled: false
gitleaks:
enabled: true
actionlint:
enabled: true
shellcheck:
enabled: true
chat:
auto_reply: true
knowledge_base:
code_guidelines:
enabled: true
# **/AGENTS.md, **/CLAUDE.md, **/GEMINI.md and .github/copilot-instructions.md are read
# by default (each scoped to its own directory); these patterns only add the security
# references the hard rules point to.
filePatterns:
- "docs/security/ERROR_SANITIZATION.md"
- "docs/security/PUBLIC_CREDS.md"

View File

@@ -7,15 +7,8 @@
**/.vscode
# Dependencies and build output
# `node_modules` alone matches the ROOT only — Docker's matcher does not cross
# `/` like .gitignore does. Without the `**/` form, nested installs ship in the
# build context (e.g. @omniroute/opencode-provider/node_modules, ~79 MB of
# devDependencies). Both forms are kept: the bare one is the documented root
# rule, the `**/` one covers every nested package.
node_modules
**/node_modules
.next
.build
out
build
dist
@@ -24,152 +17,16 @@ coverage
# Runtime data and logs
data
logs
.sandbox
# Local env files (inject at runtime via --env-file or -e)
.env*
**/.env*
!.env.example
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Debug logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# Test suites
tests
test-results
playwright-report
blob-report
output
.playwright-cli
.playwright-mcp
.stryker-tmp
reports/mutation
# Local caches and quality-gate artifacts (all gitignored). `_*` does not match
# dot-prefixed names, so these need explicit entries.
.artifacts
.eslintcache*
.fakebin-*
MAX
quality-ratchet/
# Documentation
# Issue #2348: The Dashboard Docs viewer reads markdown from `/app/docs` at
# runtime. The previous `docs/*` block hid every file except openapi.yaml,
# so the in-product help screen failed with ENOENT for every page.
# We now keep the English markdown tree plus the docs assets imported by MDX
# during `next build`, while still dropping the extra raster diagram sources
# and the translated files the runtime never reads.
#
# 2026-11-03 (owner decision): the image serves the translated /docs pages
# (#18699), which read docs/i18n/<locale>/docs/<section>/<PAGE>.md at runtime.
# Re-include exactly those mirrors: the sections source.config.ts compiles,
# minus the operator-internal security pages re-excluded below. The README,
# CHANGELOG, agent-guide and llm.txt mirrors at each locale root stay out.
# Keep in sync with scripts/build/docsMirrorRuntime.mjs (enforced by
# tests/unit/docs-mirror-runtime-shipping.test.ts).
docs/i18n/**
!docs/i18n/*/docs/getting-started/**/*.md
!docs/i18n/*/docs/guides/**/*.md
!docs/i18n/*/docs/architecture/**/*.md
!docs/i18n/*/docs/reference/**/*.md
!docs/i18n/*/docs/frameworks/**/*.md
!docs/i18n/*/docs/routing/**/*.md
!docs/i18n/*/docs/security/**/*.md
!docs/i18n/*/docs/compression/**/*.md
!docs/i18n/*/docs/ops/**/*.md
!docs/i18n/*/docs/providers/**/*.md
!docs/i18n/*/docs/comparison/**/*.md
docs/i18n/*/docs/security/STEALTH_GUIDE.md
docs/i18n/*/docs/security/SOCKET_DEV_FINDINGS.md
docs/i18n/*/docs/security/MITM-TPROXY-DECRYPT.md
docs/i18n/*/docs/security/PUBLIC_CREDS.md
# Internal planning artifacts (gitignored). `*.md` above only matches the root,
# so without this rule these land in /app/docs and become readable through the
# dashboard's Docs viewer at runtime.
docs/superpowers/**
# Operator-internal security writeups: git only, not the image or /docs catalog.
docs/security/STEALTH_GUIDE.md
docs/security/SOCKET_DEV_FINDINGS.md
docs/security/MITM-TPROXY-DECRYPT.md
docs/security/PUBLIC_CREDS.md
docs/diagrams/**/*.png
docs/diagrams/**/*.jpg
docs/diagrams/**/*.jpeg
docs/diagrams/**/*.gif
docs/diagrams/**/*.webp
# Note: `*.md` matches the root only (Go filepath.Match does not cross /),
# so nested docs/**/*.md is implicitly kept without a re-include rule.
*.md
!README.md
# Electron (separate build)
electron
# VS Code extension (separate project)
vscode-extension
# Build artifacts
*.tgz
*.AppImage
*.deb
*.rpm
# Package manager lock (bun)
bun.lock
# Agent config
.agents
.gemini
.claude
.source
# Misc
llm.txt
images
clipr
omnirouteCloud
omnirouteSite
# Temporary/Scratch Folders
_*
# CI/CD and Version Control (that are not actual code)
.github
.husky
.omc
# Test Configs and Reports
playwright.config.ts
vitest*.ts
audit-report.json
sonar-project.properties
# Deployment Configs
docker-compose*.yml
fly.toml
# Consistent with .gitignore
.DS_Store
.idea/
.config/
.data/
.omnivscodeagent/
*.sqlite-*
*.tsbuildinfo
next-env.d.ts
security-analysis/
.analysis/
antigravity-manager-analysis/
.sisyphus/
.plans/
app.__qa_backup/
.app-build-backup-*/
.gitnexus
.worktrees
.next-playwright/
cloud/
electron/dist-electron

View File

@@ -1,12 +0,0 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.sh]
indent_size = 4

View File

@@ -1,6 +0,0 @@
ENABLE_LIVE_DEVIN_TESTS=0
DEVIN_BRIDGE_MODEL=devin-cli-agentic/swe-1-7
DEVIN_BRIDGE_SONNET_MODEL=devin-cli-agentic/swe-1-7
DEVIN_BRIDGE_OPUS_MODEL=devin-cli-agentic/swe-1-7
DEVIN_BRIDGE_HAIKU_MODEL=devin-cli-agentic/swe-1-7
DEVIN_BRIDGE_SUBAGENT_MODEL=devin-cli-agentic/swe-1-7

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +0,0 @@
# Homologação E2E real — copie para .env.homolog (NUNCA commitar o real)
HOMOLOG_BASE_URL=http://192.168.0.15:20128
# Senha de management do dashboard da VPS (a mesma do /login)
HOMOLOG_ADMIN_PASSWORD=
# Deixe vazio: a suíte cria uma API key efêmera via admin e revoga no fim.
# Só preencha para depurar uma camada isolada com uma key fixa.
HOMOLOG_API_KEY=
# Tier crítico (chat real, max_tokens=5). Demais providers: só validação de catálogo.
HOMOLOG_CRITICAL_PROVIDERS=openai,anthropic,gemini,codex,grok,glm,deepseek,openrouter

View File

@@ -1,45 +0,0 @@
# ──────────────────────────────────────────────────────────────────────
# OmniRoute — Self-Host env (minimal, zero-fee self-host)
# ──────────────────────────────────────────────────────────────────────
# cp .env.selfhost.example .env
# Edit only the two lines marked `# EDIT ME`. Everything else has a sane
# default. No secrets are baked in — OmniRoute never ships credentials.
#
# Full variable reference: docs/guides/DOCKER_GUIDE.md and .env.example
# ──────────────────────────────────────────────────────────────────────
# ── Ports (host-side) ──────────────────────────────────────────────────
# Dashboard + API + Live-WS. Already match the image defaults.
DASHBOARD_PORT=20128
API_PORT=20129
LIVE_WS_PORT=20132
# ── Bind address ───────────────────────────────────────────────────────
# 127.0.0.1 = loopback only (safe with REQUIRE_API_KEY=false, the default).
# Set to 0.0.0.0 ONLY when REQUIRE_API_KEY=true OR a reverse proxy
# enforces auth upstream. Exposing an unauthenticated /v1 proxy on the
# LAN/WAN lets anyone burn your provider quotas. # EDIT ME if you must.
APP_BIND_HOST=127.0.0.1
# ── Auth ──────────────────────────────────────────────────────────────
# false = the dashboard and /v1 proxy are open to APP_BIND_HOST's network.
# true = /v1 requests need an API key (a logged-in dashboard session also works);
# the dashboard needs login once a password
# exists. Create the login password in the onboarding wizard on first visit
# (skipping that step turns dashboard login off, even with
# REQUIRE_API_KEY=true); after you submit it, the wizard asks for
# a one-time token from `docker logs omniroute | grep BOOTSTRAP`.
# # EDIT ME — set true.
REQUIRE_API_KEY=false
# INITIAL_PASSWORD=strong-password-here # fill in to pre-seed the dashboard password (an empty value behaves like unset)
# ── Memory ceiling (V8 old-space) ──────────────────────────────────────
# 1024 = dashboard + light chat. Coding agents (long POST /v1/responses
# bodies) need more — see SELF_HOST_GUIDE.md "sizing". 2048 is a safe
# default for a single user who runs Claude Code / Codex through it.
OMNIROUTE_MEMORY_MB=2048
# ── Browser-facing origin (optional) ───────────────────────────────────
# Set ONLY if you expose OmniRoute behind a domain via a reverse proxy.
# NEXT_PUBLIC_BASE_URL=https://your-domain.example.com
# BASE_URL=http://omniroute:20128

11
.gitattributes vendored
View File

@@ -1,11 +0,0 @@
# Shell scripts must always be checked out with LF line endings.
#
# On Windows, core.autocrlf=true converts text files to CRLF in the working
# tree. Scripts that are kernel-exec'd (Docker ENTRYPOINT, bin/*.sh on Linux
# hosts) then fail with `exec ...: no such file or directory` because the
# shebang becomes "#!/bin/sh\r". eol=lf overrides autocrlf for these files.
*.sh text eol=lf
# This file must stay LF too: git parses it as-is, and a trailing CR would
# corrupt every pattern (e.g. "*.sh\r" matches nothing).
.gitattributes text eol=lf

2
.github/CODEOWNERS vendored
View File

@@ -1,2 +0,0 @@
* @diegosouzapw

5
.github/FUNDING.yml vendored
View File

@@ -1,5 +0,0 @@
# Funding links for OmniRoute — rendered as the "Sponsor" button on GitHub.
# Docs: https://docs.github.com/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/displaying-a-sponsor-button-in-your-repository
github: diegosouzapw
# Additional platforms (uncomment and fill in before enabling):
# custom: ["https://omniroute.online/donate"]

View File

@@ -1,6 +1,6 @@
name: Bug Report
description: Report a bug or unexpected behavior in OmniRoute
title: "fix(): "
title: "[BUG] "
labels: ["bug"]
body:
- type: markdown
@@ -8,14 +8,12 @@ body:
value: |
Thanks for taking the time to report a bug. Please fill out the sections below so we can reproduce and fix the issue.
The title is prefilled as `fix(): ` to match the [Conventional Commits](https://github.com/cheaper-inference/OmniRoute/blob/main/CONTRIBUTING.md#commit-messages) convention — pick a scope from the list documented there (e.g. `providers`, `resilience`, `dashboard`, `api`).
- type: input
id: version
attributes:
label: OmniRoute Version
description: "Run `omniroute --version` or check the left sidebar in the dashboard."
placeholder: "e.g. 3.7.9"
placeholder: "e.g. 3.0.9"
validations:
required: true
@@ -46,7 +44,7 @@ body:
id: os-version
attributes:
label: OS Version
placeholder: "e.g. Windows 11 25H2, macOS 26.5, Ubuntu 26.04"
placeholder: "e.g. Windows 11 23H2, macOS 15.3, Ubuntu 24.04"
validations:
required: false
@@ -55,7 +53,7 @@ body:
attributes:
label: Node.js Version
description: "Run `node --version`. Skip if using Docker."
placeholder: "e.g. 24.15.0"
placeholder: "e.g. 22.12.0"
validations:
required: false
@@ -72,7 +70,7 @@ body:
id: model
attributes:
label: Model(s) Involved
placeholder: "e.g. claude-opus-4-7, gpt-5.5, gemini-3.1-pro"
placeholder: "e.g. claude-sonnet-4-20250514, gpt-4o, gemini-2.5-pro"
validations:
required: false
@@ -121,20 +119,6 @@ body:
validations:
required: true
- type: dropdown
id: test-impact
attributes:
label: Test Impact
description: "What automated test coverage should exist for this bug?"
options:
- Needs a new unit test
- Needs a new integration test
- Needs a new e2e test
- Existing automated test already fails
- Unsure
validations:
required: true
- type: textarea
id: logs
attributes:
@@ -159,15 +143,3 @@ body:
description: "Any other context about the problem (e.g. proxy config, number of accounts, network setup)."
validations:
required: false
- type: textarea
id: validation-plan
attributes:
label: Validation Plan
description: "Which commands or tests should prove this bug is fixed?"
placeholder: |
Example:
- node --import tsx --test tests/unit/my-file.test.ts
- npm run test:coverage
validations:
required: false

View File

@@ -1,5 +1,5 @@
blank_issues_enabled: false
blank_issues_enabled: true
contact_links:
- name: Question / Help
url: https://github.com/cheaper-inference/OmniRoute/discussions
url: https://github.com/diegosouzapw/OmniRoute/discussions
about: For questions or help with setup, please use GitHub Discussions instead of opening an issue.

View File

@@ -1,6 +1,6 @@
name: Feature Request
description: Suggest a new feature or improvement for OmniRoute
title: "feat(): "
title: "[Feature] "
labels: ["enhancement"]
body:
- type: markdown
@@ -8,8 +8,6 @@ body:
value: |
Thanks for suggesting a feature! Please describe the problem you're trying to solve and how you'd like it to work.
The title is prefilled as `feat(): ` to match the [Conventional Commits](https://github.com/cheaper-inference/OmniRoute/blob/main/CONTRIBUTING.md#commit-messages) convention — pick a scope from the list documented there (e.g. `providers`, `resilience`, `dashboard`, `api`).
- type: textarea
id: problem
attributes:
@@ -35,19 +33,6 @@ body:
validations:
required: false
- type: textarea
id: acceptance
attributes:
label: Acceptance Criteria
description: "Describe the concrete behaviors or outcomes that should be validated before this is considered done."
placeholder: |
Example:
- API route returns 200 with valid payload
- Unit coverage added for the new branch
- Existing integrations remain green
validations:
required: true
- type: dropdown
id: area
attributes:
@@ -83,16 +68,3 @@ body:
description: "Any other context, mockups, or references."
validations:
required: false
- type: textarea
id: test-plan
attributes:
label: Expected Test Plan
description: "Which automated tests or coverage changes should accompany this work?"
placeholder: |
Example:
- Add unit tests for open-sse/services/combo.ts
- Extend integration coverage for /api/v1/models
- Keep npm run test:coverage at 60%+
validations:
required: false

View File

@@ -1,73 +0,0 @@
name: Test Coverage Task
description: Create a focused coverage-improvement issue tied to concrete files and targets
title: "[Coverage] "
labels: ["test", "coverage"]
body:
- type: markdown
attributes:
value: |
Use this template for scoped coverage work. Keep it tied to specific files, measurable targets, and the gate that must stay green.
- type: input
id: baseline
attributes:
label: Current Coverage Baseline
description: "Paste the current overall or file-level coverage number that justifies this task."
placeholder: "e.g. Lines 79.00%, Branches 72.85%, open-sse/handlers/chatCore.ts = 67.22%"
validations:
required: true
- type: textarea
id: scope
attributes:
label: Target Files Or Modules
description: "List the concrete source files or directories that this task will cover."
placeholder: |
Example:
- open-sse/handlers/chatCore.ts
- open-sse/services/combo.ts
- tests/integration/chat-pipeline.test.ts
validations:
required: true
- type: textarea
id: scenarios
attributes:
label: Missing Scenarios
description: "Describe the specific behaviors, branches, or failure paths that are currently uncovered."
placeholder: |
Example:
- Upstream timeout path
- Empty tool_calls normalization
- Fallback route after first provider failure
validations:
required: true
- type: input
id: target
attributes:
label: Coverage Target
description: "Set the expected target for this task."
placeholder: "e.g. Raise open-sse/handlers to 80%+ lines and keep global gate >= 60%"
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation Commands
description: "List the commands that must pass before this issue can be closed."
placeholder: |
Example:
- node --import tsx --test tests/unit/my-suite.test.ts
- npm run test:coverage
validations:
required: true
- type: textarea
id: notes
attributes:
label: Notes
description: "Optional context, blockers, or dependencies."
validations:
required: false

View File

@@ -1,49 +0,0 @@
## Summary
- What was broken, for whom, and what does this change fix?
- Root cause in one or two sentences.
## Related Issues
- Closes # <!-- use "Refs #" if this only partially fixes the issue -->
## Target Branch
See the [Release Strategy](../../docs/ops/RELEASE_STRATEGY.md) and the [ROADMAP](../../ROADMAP.md):
- [ ] Base is the active `release/v3.8.x` branch (the highest open `release/v*`), not `main`
(after 3.9.0, fixes target `stable/v3` and are forward-ported to v4 with credit)
## Proof Of Fix (required)
Every bug fix must be validated by ONE of the following (`AGENTS.md`, Hard Rule #18).
A fix without either is not merged.
- [ ] **TDD (preferred)** — a test that fails before the fix and passes after it.
- Test file(s):
- Failing output before the fix (paste the relevant lines):
- [ ] **Real-environment test** (only when TDD is not possible — OAuth upstream flows,
upstream WebSocket/Cloudflare behavior, UI-only regressions, hardware-dependent
behavior) — record the exact command and its result:
- Environment:
- Command:
- Result:
## Scope
- [ ] Only the files the failing test proves need changing are touched
- [ ] No test was weakened or deleted to make the suite pass
## Validation
Choose the focused loop for your change type from the
[Contribution Golden Path](../../docs/ops/CONTRIBUTION_GOLDEN_PATH.md). The full unit suite,
Vitest, the 60% coverage gate, and the production build all run in CI on this PR:
- [ ] Change type: provider / routing / UI / i18n / CLI / DB / build-deploy / other
- [ ] Focused tests and category gates from the golden path
- [ ] `npm run lint`
## Reviewer Notes
- Risky areas, side effects on other providers/routes, or follow-ups reviewers should know about.

View File

@@ -1,44 +0,0 @@
## Summary
- What does this feature add, and who uses it?
- Link the issue or discussion where it was agreed on.
## Related Issues
- Closes #
- Related to #
## Target Branch
See the [Release Strategy](../../docs/ops/RELEASE_STRATEGY.md) and the [ROADMAP](../../ROADMAP.md):
- [ ] Base is the active `release/v3.8.x` branch (the highest open `release/v*`), not `main`
- [ ] I understand that from 3.8.55 on, feature PRs are held with the `v4-feature` label and
re-targeted to the v4 channel (`develop`) when it opens — they are not closed
## Design
- Where does the code live (route / handler / executor / service / DB module / UI)?
- New settings, env vars, feature flags, DB migrations, or MCP tools? List them.
- Is it opt-in? Data-mutating behavior must be off by default.
## Validation
Choose the focused loop for your change type from the
[Contribution Golden Path](../../docs/ops/CONTRIBUTION_GOLDEN_PATH.md). The full unit suite,
Vitest, the 60% coverage gate, and the production build all run in CI on this PR:
- [ ] Change type: provider / routing / UI / i18n / CLI / DB / build-deploy / other
- [ ] Focused tests and category gates from the golden path
- [ ] `npm run lint`
- [ ] New production code ships with new automated tests in this PR
- [ ] Docs updated for every new endpoint, env var, CLI command, or setting
- [ ] New UI strings added to the i18n catalogs
## Tests Added Or Updated
- List every changed or added automated test file.
## Reviewer Notes
- Risky areas, migrations, feature flags, or manual validation reviewers should know about.

View File

@@ -1,32 +0,0 @@
# npm ci with retry
This action installs the checkout dependencies with up to three attempts and restores a node_modules tree only when its complete cache key matches. Node, npm, lockfile, project npm configuration, postinstall helpers and the action itself participate in the key. Cached and freshly installed trees still pass the existing native-runtime verification.
The installation step sets `ONNXRUNTIME_NODE_INSTALL=skip` before invoking npm. ONNX Runtime reads this environment variable directly, so skipping its additional CUDA installation does not depend on npm forwarding the custom `.npmrc` key. The repository retains that key temporarily; its npm warning can therefore remain.
## Installing this checkout locally
For a POSIX shell, set the variable on the install command:
```sh
ONNXRUNTIME_NODE_INSTALL=skip npm ci
```
Use `npm install` in place of `npm ci` when deliberately updating the lockfile.
In PowerShell, set it in the current shell before starting npm:
```powershell
$env:ONNXRUNTIME_NODE_INSTALL = "skip"
npm ci
```
The PowerShell assignment remains in that process environment and is inherited by its children. npm does not load the application's `.env` file for this purpose. A package preinstall script cannot set the environment of its parent npm process.
## Scope
The environment is scoped to this action's install step. Direct checkout-install steps in the enumerated workflows set the same variable themselves. It is not exported to unrelated workflow steps or changed for tarball smoke tests.
The Dockerfile checkout install already uses `--ignore-scripts`, then builds only the SQLite native dependency; that path does not execute the ONNX install script.
This policy does not force an environment variable on people installing the published package, on remote deployment commands, or inside a separate container. The checkout `.npmrc` is also not a configuration mechanism for those consumers. Those installation paths have their own contracts. The regression tests exercise the ONNX flag parser and a local npm lifecycle without downloading CUDA, installing the application or claiming to reproduce a startup crash.

View File

@@ -1,101 +0,0 @@
name: npm ci with retry
description: >-
Install dependencies. Restores node_modules from the Actions cache when the exact
lockfile / runner / Node version / postinstall inputs match; otherwise runs npm ci
with retries for transient registry/network failures and saves the tree for the
next run.
inputs:
cache:
description: Set to "false" to skip the node_modules cache and always run npm ci.
required: false
default: "true"
runs:
using: composite
steps:
- name: Select the lockfile-compatible npm version
id: npm
shell: bash
run: |
set -euo pipefail
expected=$(node -p "require('./config/ci/toolchain.json').npm")
if ! [[ "$expected" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Invalid pinned npm version" >&2
exit 1
fi
if [ "$(npm --version)" != "$expected" ]; then
npm install --global "npm@$expected" --no-audit --no-fund
fi
actual=$(npm --version)
if [ "$actual" != "$expected" ]; then
echo "npm version differs from the lockfile toolchain" >&2
exit 1
fi
echo "version=$actual" >> "$GITHUB_OUTPUT"
- name: Resolve Node version for the cache key
id: node
shell: bash
run: echo "version=$(node --version)" >> "$GITHUB_OUTPUT"
# #8084 D3 (plan 3.8.51 task 5): every job used to pay ~80-90 s of `npm ci` even
# with setup-node's npm tarball cache warm — 36 jobs per ci.yml run, ~55 min of
# runner time per run just installing. A node_modules cache keyed on EVERYTHING
# that shapes the tree lets a hit skip the install entirely.
#
# No restore-keys on purpose (same rule as the ESLint cache, #11600): a partial
# tree from another lockfile / Node / postinstall script is exactly the kind of
# silent drift a lockfile-pinned CI must never inherit. Exact key or a full npm ci.
#
# postinstall (scripts/build/postinstall.mjs + helpers) only mutates node_modules
# on a plain install — its dist/ branch is gated on dist/ existing, which never
# holds at install time in CI — so the cached tree already carries its effects.
- name: Restore node_modules
id: node-modules
if: inputs.cache == 'true'
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: node_modules
key: node-modules-v3-${{ runner.os }}-${{ runner.arch }}-${{ steps.node.outputs.version }}-${{ steps.npm.outputs.version }}-${{ hashFiles('package-lock.json', '.npmrc', 'scripts/build/postinstall.mjs', 'scripts/build/postinstallSupport.mjs', 'scripts/build/colocateOptionals.mjs', 'scripts/build/wreqJsNative.mjs', 'scripts/build/fixPlaywrightAndroid.mjs', 'scripts/build/native-binary-compat.mjs', 'scripts/build/betterSqlitePrebuildTarget.mjs', 'scripts/ci/verify-ci-install.mjs', '.github/actions/npm-ci-retry/action.yml') }}
- name: npm ci (with retry)
if: steps.node-modules.outputs.cache-hit != 'true'
shell: bash
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
run: |
set -euo pipefail
max_attempts=3
delay_seconds=20
for attempt in $(seq 1 "$max_attempts"); do
if [ "$attempt" -gt 1 ]; then
echo "npm ci attempt $attempt/$max_attempts after transient failure"
fi
# --no-audit: `audit:deps` is its own gate; the inline audit only adds latency.
if npm ci --no-audit --no-fund; then
exit 0
else
exit_code=$?
fi
if [ "$attempt" -eq "$max_attempts" ]; then
exit "$exit_code"
fi
sleep "$delay_seconds"
delay_seconds=$((delay_seconds * 2))
done
# Both cache hits and successful installs must execute the native runtimes.
# A package directory alone cannot prove ABI compatibility or a usable binary.
- name: Verify installed native runtimes
id: verify-install
shell: bash
run: node scripts/ci/verify-ci-install.mjs
- name: node_modules restored from cache
if: steps.node-modules.outputs.cache-hit == 'true'
shell: bash
run: echo "node_modules restored from cache (key hit) — npm ci skipped"

View File

@@ -1,15 +0,0 @@
# OmniRoute PR and Coverage Instructions
- Treat `npm run test:coverage` as a required gate for PR work.
- The repository minimum is `60%` for statements, lines, functions, and branches.
- If a PR changes production code in `src/`, `open-sse/`, `electron/`, or `bin/`, it must include automated tests in the same PR.
- When reviewing or updating a PR, if the report shows missing tests or coverage below `60%`, do not stop after reporting the problem. Add or update tests in the PR first, rerun the coverage gate, and only then ask for confirmation.
- Prefer the smallest test layer that proves the behavior:
- unit tests first
- integration tests when multiple modules or DB state are involved
- e2e only when the behavior is truly UI or workflow-dependent
- For bug issues, try to encode the reproduction as an automated test before or alongside the fix.
- In the final PR report, include:
- the commands you ran
- the changed test files
- the final coverage result

100
.github/dependabot.yml vendored
View File

@@ -24,108 +24,8 @@ updates:
update-types: ["version-update:semver-major"]
- dependency-name: "eslint-config-next"
update-types: ["version-update:semver-major"]
# typescript majors are peer-blocked by typescript-eslint, which pins a hard
# upper bound (8.64.0 → peerDependencies.typescript ">=4.8.4 <6.1.0"). A TS 7
# bump therefore violates the peer and takes down the whole toolchain at once —
# #7068 grouped it with 6 harmless bumps and turned Build + Lint + Quality Ratchet
# + Unit (6/8, 8/8) + Integration (1/2, 2/2) + dast-smoke red in one shot, blocking
# the innocuous updates riding along with it. Un-ignore once typescript-eslint
# widens the peer, and migrate TS majors intentionally (own PR, own CI run).
- dependency-name: "typescript"
update-types: ["version-update:semver-major"]
# jscpd v5 is a Rust rewrite (native binary, no Node.js programmatic API).
# scripts/check/check-duplication.mjs is deliberately pinned to jscpd@4 (it
# parses jscpd-report.json against a frozen baseline). A v5 major would break
# the duplication gate — migrate the gate intentionally, not via dependabot.
- dependency-name: "jscpd"
update-types: ["version-update:semver-major"]
# ioredis is a SOFT/optional dependency loaded through a dynamic import
# (src/lib/quota/redisQuotaStore.ts — "Redis driver requires ioredis package"),
# so a breaking major never fails at build or typecheck time: the only consumers
# are the distributed quota store (redisQuotaStore.ts, storeFactory.ts) and the
# `import type Redis` in src/shared/utils/rateLimiter.ts. Nothing in the unit or
# vitest suites exercises a live Redis connection, so a v5→v6 API break would ship
# green and only surface at runtime for operators running distributed quota — the
# exact users least able to absorb it. #9310 grouped that major with 9 harmless
# bumps; majors here need their own PR and a deliberate migration review.
- dependency-name: "ioredis"
update-types: ["version-update:semver-major"]
# @huggingface/transformers is VPS-validated at ^4.2.0 (migrated intentionally in
# #9962). It is load-bearing for the LLMLingua ONNX compression engine (open-sse/
# services/compression/engines/llmlingua/ — @atjsh/llmlingua-2@2.0.5 peers on
# "@huggingface/transformers": "^3.5.2 || ^4.0.0") and for local memory embeddings
# (src/lib/memory/embedding/transformersLocal.ts). Further majors must be re-validated
# on the VPS — so keep auto-bumps frozen (no update-types = ignore every version).
# Migrate it intentionally, not via dependabot (#4050).
- dependency-name: "@huggingface/transformers"
# onnxruntime-node is the OTHER HALF of the @huggingface/transformers pair frozen
# above: the hoisted copy must equal the exact version transformers pins, or npm
# nests a second ABI-incompatible native copy (contract test
# tests/unit/onnxruntime-single-copy.test.ts, pair established in #9962). A solo
# bump can never be correct — it only ever moves together with transformers, in
# the same deliberate migration PR. Freezing it keeps the production group PRs
# (e.g. #12219) from being born red on the pair contract.
- dependency-name: "onnxruntime-node"
# eslint-plugin-react-hooks is pinned to 7.0.1 by a contract test
# (tests/unit/eslint-react-hooks-version-pinned.test.ts) until the 7.1.1 rule set
# is adopted deliberately — that adoption needs a full cold lint run and its own
# PR (the #12146 react-hooks migration finished on 2026-09-01, so the path is
# open; the bump still must not ride a dependabot group, where it reds the
# development group PRs, e.g. #12220). Remove this ignore in the adoption PR
# together with the pin test.
- dependency-name: "eslint-plugin-react-hooks"
# The four entries below came out of the development group #17197 (26 updates),
# which could not land because these bumps break contracts or need a migration.
# Each one has to move in its own PR; the rest of the group stays automatic.
#
# promptfoo is an exact pin mirrored by the nightly LLM-security workflow
# (`npx --yes promptfoo@X.Y.Z` in nightly-llm-security.yml). The contract test
# tests/unit/build/llm-security-nightly-promptfoo-pin.test.ts requires the workflow
# pin to equal package.json and rejects releases proven broken (KNOWN_BROKEN:
# 0.123.1 and 0.124.1, promptfoo/promptfoo#10866 — the guard-validation step exits
# 100 on the guard's 4xx JSON body). Dependabot only edits package.json, so every
# bump reds that test. Bump by hand: package.json + workflow pin together, after
# re-running guard-validation against the new release.
- dependency-name: "promptfoo"
# fumadocs-mdx 15.4.7 imports `embedSource` from fumadocs-core/mdx-plugins/stringifier,
# which the fumadocs-core on this branch (16.15.x) does not export yet: the Build job
# dies loading next.config.mjs (#17197). fumadocs-core/fumadocs-ui ride the
# production group and fumadocs-mdx the development group, so dependabot can never
# move them together. Remove this ignore in the PR that bumps fumadocs-core,
# fumadocs-ui and fumadocs-mdx as one set.
- dependency-name: "fumadocs-mdx"
versions: [">=15.4.7"]
# @playwright/test must equal the runtime `playwright` / `playwright-core` exact pin
# (one Playwright in the tree — tests/unit/playwright-runner-args.test.ts). The
# runtime pair is a production dependency and @playwright/test a development one,
# so a solo bump from the development group always breaks that contract. Bump it by
# hand in the same PR that moves playwright and playwright-core.
- dependency-name: "@playwright/test"
# bun is an exact devDependency pin documented in AGENTS.md (Environment) and
# docs/ops/BUILD_WARNINGS.md: it runs only allow-listed gate/generator scripts, and
# any new Bun version must be validated byte-identical against the
# `node --import tsx` output first. @types/bun is its paired type package and moves
# with it. Bump both by hand, together with the docs that name the version.
- dependency-name: "bun"
- dependency-name: "@types/bun"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/electron"
schedule:
interval: "weekly"
day: "monday"
commit-message:
prefix: "deps"
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
commit-message:
prefix: "deps"

41
.github/labels.yml vendored
View File

@@ -1,41 +0,0 @@
# Declarative GitHub labels for the 3.8.5x -> 3.9.0 LTS release rail.
#
# Synced by `npm run labels:sync` (scripts/release/sync-labels.mjs): dry-run by
# default, `-- --apply` to create/update. Only the labels listed here are managed;
# labels missing from this file are never touched or deleted.
#
# Pre-existing operational labels (`queue`, `release-freeze`, `base-red`, ...) are
# intentionally NOT listed — they keep their current meaning and colors.
#
# Model: docs/ops/RELEASE_STRATEGY.md
#
# Fields: name (required), color (QUOTED 6-digit hex - unquoted values like 5319E7 or
# 012345 are parsed by YAML as numbers), description (<= 100 chars).
- name: v4-feature
color: "1D76DB"
description: Feature PR held for the v4 channel (develop); re-targeted when it opens
- name: lts
color: "0E8A16"
description: Belongs to the v3 LTS line (stable/v3) - fixes, security, provider updates
- name: forward-port
color: "C5DEF5"
description: Fix forward-ported from stable/v3 to develop with original-author credit
- name: channel:latest
color: "2EA44F"
description: Ships on the npm `latest` dist-tag (v3 until 4.0 GA)
- name: channel:next
color: "FBCA04"
description: Ships on the npm `next` dist-tag (v4 release candidates)
- name: channel:nightly
color: "5319E7"
description: Ships on the npm `nightly` dist-tag (v4 develop builds)
- name: preview-artifact
color: "BFDADC"
description: Requests a PR preview build artifact (dormant until the 3.8.58 rehearsal)

View File

@@ -1,45 +0,0 @@
## Summary
- Describe the user-facing or operational change.
## Related Issues
- Closes #
- Related to #
## Target Branch
See the [Release Strategy](../docs/ops/RELEASE_STRATEGY.md), the
[Contribution Golden Path](../docs/ops/CONTRIBUTION_GOLDEN_PATH.md) and the
[ROADMAP](../ROADMAP.md):
- [ ] Base is the active `release/v3.8.x` branch (the highest open `release/v*`), not `main`
- [ ] New feature? From 3.8.55 on it is held with the `v4-feature` label for the v4 channel
- Focused templates: append `?template=feature.md` or `?template=bugfix.md` to the compare URL
## Validation
Choose the change type and focused loop from the
[Contribution Golden Path](../docs/ops/CONTRIBUTION_GOLDEN_PATH.md). The full unit suite,
Vitest, the 60% coverage gate, and the production build all run in CI on this PR (#8329):
- [ ] Change type: provider / routing / UI / i18n / CLI / DB / build-deploy / other
- [ ] Focused tests and category gates from the golden path
- [ ] `npm run lint`
- [ ] Reconciled with the current active release base; focused checks rerun afterward
- [ ] Production-code changes include a new or updated automated test in this PR
- SonarQube is temporarily opt-in while the private project has no quota; it is not a PR gate.
## Tests Added Or Updated
- List every changed or added automated test file.
- If no production code changed, state that here.
## Coverage Notes
- If this PR changes `src/`, `open-sse/`, `electron/`, or `bin/`, explain which tests cover the change.
- If coverage moved down in any touched file, explain why and what follow-up task will recover it.
## Reviewer Notes
- Call out any risky areas, migrations, feature flags, or manual validation that reviewers should know about.

View File

@@ -1,36 +0,0 @@
name: API Route Typecheck
on:
pull_request:
branches:
- main
- "release/**"
types: [opened, synchronize, reopened, ready_for_review]
push:
branches: [main]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
api-typecheck:
name: API Route Typecheck
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
node-version: "24"
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Reject new API-route TypeScript diagnostics
run: node scripts/check/check-api-typecheck.mjs
- name: API typecheck gate unit tests
run: node --import tsx/esm --test tests/unit/build/check-api-typecheck.test.ts

View File

@@ -1,29 +0,0 @@
name: Release base repair
on:
push:
branches: [fix/release-v3.8.52-basereds]
permissions:
contents: read
jobs:
regression:
runs-on: ubuntu-latest
timeout-minutes: 12
env:
CI: "true"
OMNIROUTE_SKIP_SYSTEM_TRUST: "1"
DISABLE_SQLITE_AUTO_BACKUP: "true"
NEXT_TELEMETRY_DISABLED: "1"
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1"
OMNIROUTE_MAX_TEST_WORKERS: "2"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
fetch-depth: 0
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020
with:
node-version: "24"
- name: Verify old failure and final guarded transport
run: node scripts/check/base-ci-repair.mjs
- name: Clean owned state
if: always()
run: rm -rf -- .ci-work/base-ci-repair

View File

@@ -1,72 +0,0 @@
name: Build App
# Manual-only since #11946. The hosted 7 GB runner can no longer build this tree — 19 of
# the last 30 runs died with "The runner has received a shutdown signal" (VM out of
# memory) ~8 min into `next build`, release/v3.8.51 itself included, even with the 10 GB
# swapfile below. Triggered on `push: branches: ["**"]` it painted every branch and every
# PR red while producing an artefact nothing downloads. The bundle is validated where a
# build actually fits:
# - main: ci.yml `Build` (self-hosted omni-build pool) on every merge
# - release/**: nightly-release-green.yml (same pool, continuous)
# Dispatch this workflow by hand when a hosted build artefact is genuinely needed.
on:
workflow_dispatch:
permissions:
contents: read
jobs:
build:
name: Fast Production Build
runs-on: ubuntu-latest
steps:
- name: Expand Virtual Memory (Native 10GB Swap)
run: |
sudo swapoff -a || true
sudo rm -f /mnt/swapfile /swapfile
sudo fallocate -l 10G /mnt/swapfile || sudo dd if=/dev/zero of=/mnt/swapfile bs=1M count=10240
sudo chmod 600 /mnt/swapfile
sudo mkswap /mnt/swapfile
sudo swapon /mnt/swapfile
free -h
- name: Checkout repository
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- name: Install dependencies
run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Build Next.js app & CLI bundle
run: |
npm run build:release
env:
# Hosted artifact builds run with less memory than the opt-in 64 GB
# CI build slot. Keep Webpack here without overriding the latter's
# separately measured Turbopack policy (#16169). Validated 2026-10-18 on the
# hosted runner (run 39151150605): webpack compiled in 7.1 min, job 17 min.
# This is the floor docker-publish.yml must not go below
# (tests/unit/docker-publish-build-heap-14325.test.ts).
NODE_OPTIONS: "--max-old-space-size=10240"
OMNIROUTE_BUILD_MEMORY_MB: "10240"
OMNIROUTE_USE_TURBOPACK: "0"
- name: Archive build outputs
run: |
tar -czf omniroute-build.tar.gz .build dist
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: omniroute-build
path: omniroute-build.tar.gz
retention-days: 7

View File

@@ -1,42 +0,0 @@
name: Cancel runs of closed PRs
# A closed PR (merged or not) never gets a newer run on its ref, so the per-ref
# `concurrency` + cancel-in-progress in ci.yml / quality.yml never supersedes its runs
# and they keep their place in the hosted-runner queue. On 2026-10-26, 34 of 229 queued
# PR runs belonged to closed PRs or superseded heads while the org's Free plan allows 20
# concurrent hosted jobs. This job only calls the Actions API: it never checks out or runs
# the PR's code. `pull_request` (not `_target`): fork PRs get a read-only token and are
# skipped, which is fine — their runs wait for maintainer approval anyway.
on:
pull_request:
types: [closed]
permissions:
contents: read
jobs:
cancel:
name: Cancel queued runs of this PR
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
actions: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
sparse-checkout: scripts/ci/cancel-closed-pr-runs.mjs
sparse-checkout-cone-mode: false
- name: Cancel this PR's queued and running workflow runs
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
HEAD_REF: ${{ github.event.pull_request.head.ref }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
SELF_RUN_ID: ${{ github.run_id }}
run: node scripts/ci/cancel-closed-pr-runs.mjs

1885
.github/workflows/ci.yml vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,54 +0,0 @@
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
# Least-privilege default: no token permissions at the top level; the `claude` job
# grants exactly what it needs below (Scorecard TokenPermissions).
permissions: {}
jobs:
claude:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
persist-credentials: false
fetch-depth: 1
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
# This is an optional setting that allows Claude to read CI results on PRs
additional_permissions: |
actions: read
# Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
# prompt: 'Update the pull request description to include a summary of changes.'
# Optional: Add claude_args to customize behavior and configuration
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
# or https://code.claude.com/docs/en/cli-reference for available options
# claude_args: '--allowed-tools Bash(gh pr *)'

View File

@@ -1,31 +0,0 @@
name: CodeQL
# OWNER ACTION REQUIRED before enabling auto-triggers: advanced CodeQL conflicts with
# GitHub "default setup" — the analyze step fails with "CodeQL analyses from advanced
# configurations cannot be processed when the default setup is enabled". Switch repo
# Settings → Code security → CodeQL from Default to Advanced, THEN restore the
# push/pull_request/schedule triggers below. Until then this only runs on manual dispatch
# so it never produces a red check on PRs. (The codeqlAlerts ratchet keeps working via the
# default setup's alerts in the meantime.)
on:
workflow_dispatch:
permissions:
contents: read
jobs:
analyze:
name: Analyze (javascript-typescript)
runs-on: ubuntu-latest
permissions:
security-events: write
actions: read
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
with:
languages: javascript-typescript
queries: security-extended
- uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
with:
category: "/language:javascript-typescript"

View File

@@ -1,98 +0,0 @@
name: DAST smoke (PR)
# PRs into main only since #11946. The job's "Build CLI bundle" step is a backend-only
# `next build`; on the hosted 7 GB runner it fits main's tree (~5.5 min) but dies on
# release/v3.8.51 (VM shutdown ~7 min in, before the server even starts), and because the
# job is continue-on-error the result was a permanently red advisory check on every
# release PR — noise, not signal. DAST coverage for release/** lives on the nightly rail
# (nightly-schemathesis.yml, nightly-llm-security.yml); dispatch this workflow by hand
# to smoke a release branch on demand.
on:
workflow_dispatch:
pull_request:
branches: ["main"]
# Runner-cost guard (#8084): the CLI-bundle build alone is 6-11min; a docs-only PR
# cannot change DAST behavior, so skip the whole workflow for pure docs/markdown
# changes. Any code path in the diff still runs the full smoke.
paths-ignore:
- "docs/**"
- "**/*.md"
permissions:
contents: read
# Superseded runs on the same PR must not stack 25-minute advisory builds
# (force-push storms were holding 2-3 runners each). Same group rule as quality.yml.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
dast-smoke:
runs-on: ubuntu-latest
# ADVISORY while this new gate matures (repo convention: advisory -> blocking).
# Flip to blocking (remove continue-on-error) once it's proven stable across a few PRs.
continue-on-error: true
# Build CLI bundle alone varies 6-11min on GitHub-hosted runners (3 consecutive
# timeouts observed on 2026-07-14 with the old 12min cap killing schemathesis
# mid-run) — 25min leaves real headroom for the actual DAST steps.
timeout-minutes: 25
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-api-key-secret-with-sufficient-length-aaaa
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: "24"
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Build CLI bundle
env:
OMNIROUTE_BUILD_BACKEND_ONLY: "1"
run: npm run build:cli
- name: Start OmniRoute
env:
PORT: "20128"
INJECTION_GUARD_MODE: block
REQUIRE_API_KEY: "false"
run: |
node dist/server.js > server.log 2>&1 &
echo $! > server.pid
for _ in $(seq 1 30); do
if curl -sf http://localhost:20128/api/monitoring/health >/dev/null; then echo up; break; fi
sleep 2
done
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.12"
- run: pip install schemathesis
- name: Schemathesis smoke (high-risk endpoints, blocking)
run: |
# /api/auth/oidc/* is a BROWSER redirect flow (302 to the IdP, 302 back to
# /login?oidc_error=... on every failure), not a REST endpoint: Schemathesis reads
# those 302s as "the API accepted a schema-violating request" and the configured-off
# 400 as "rejected a schema-compliant request". Documenting the flow in the spec is
# still right (operators need it); fuzzing it is not what this smoke is for.
# /api/auth/login has brute-force rate limiting: repeated failed logins return 429,
# which Schemathesis flags as rejection of schema-compliant requests.
schemathesis run docs/openapi.yaml --url http://localhost:20128 \
--include-path-regex '^/v1/(chat/completions|models)$|^/api/(auth|keys)' \
--exclude-path-regex '^/api/auth/(oidc/|login)' \
--max-examples 8 --workers 4 --checks all --max-response-time 30 \
--request-timeout 20 --suppress-health-check all --no-color
- name: Install promptfoo
run: npm install -g promptfoo@0.122.0
- name: promptfoo injection-guard (blocking)
env:
OMNIROUTE_URL: http://localhost:20128
OMNIROUTE_API_KEY: not-needed-blocked-before-upstream
run: promptfoo eval -c promptfooconfig.yaml --no-cache
- name: Stop server
if: always()
run: kill "$(cat server.pid)" || true
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
with:
name: dast-smoke-logs
path: server.log
retention-days: 7

View File

@@ -6,9 +6,6 @@ on:
types: [completed]
workflow_dispatch:
permissions:
contents: read
jobs:
deploy:
if: >-
@@ -16,84 +13,28 @@ jobs:
&& vars.DEPLOY_ENABLED == 'true'
name: Deploy OmniRoute to VPS
runs-on: ubuntu-latest
# Bound a hung SSH session to an hour instead of GitHub's 6-hour default; the deploy
# itself fails fast when the VPS is unreachable (run 39101148517: 0 min of work).
timeout-minutes: 60
steps:
- name: Check VPS SSH reachability from runner
id: reach
env:
# Pass the host via env (never interpolate a secret straight into the
# script body) so /dev/tcp gets a shell variable, not inlined text.
VPS_HOST: ${{ secrets.VPS_HOST }}
run: |
set -euo pipefail
# A GitHub-hosted runner can only deploy when it can actually open a TCP
# connection to the VPS SSH port. The Local VPS lives on a private LAN and
# the Akamai host firewalls :22 to known IPs, so the runner is routinely
# unable to reach it. An enabled deployment that cannot start is a failed
# deployment, not success. Keep DEPLOY_ENABLED=false when this runner has
# no authorized route; do not convert a requested deployment into green.
if timeout 15 bash -c 'exec 3<>"/dev/tcp/${VPS_HOST}/22"' 2>/dev/null; then
echo "reachable=true" >> "$GITHUB_OUTPUT"
echo "✅ VPS_HOST:22 reachable from the runner — proceeding with deploy."
else
echo "reachable=false" >> "$GITHUB_OUTPUT"
echo "::error title=Deployment did not start::VPS_HOST:22 is not reachable from this runner. An operator must provide an authorized route or perform a separately authorized deployment."
exit 1
fi
- name: Deploy via SSH
if: steps.reach.outputs.reachable == 'true'
uses: appleboy/ssh-action@v1
continue-on-error: true
with:
host: ${{ secrets.VPS_HOST }}
username: ${{ secrets.VPS_USER }}
key: ${{ secrets.VPS_SSH_KEY }}
port: 22
timeout: 60s
command_timeout: 15m
timeout: 30s
command_timeout: 5m
script: |
set -euo pipefail
echo "=== Updating OmniRoute ==="
npm install -g omniroute@latest
INSTALLED_VERSION=$(omniroute --version 2>/dev/null | tr -d '[:space:]' || echo "unknown")
echo "Installed CLI version: $INSTALLED_VERSION"
npm install -g omniroute@latest 2>&1
INSTALLED_VERSION=$(omniroute --version 2>/dev/null || echo "unknown")
echo "Installed version: $INSTALLED_VERSION"
# Recreate the PM2 process instead of `pm2 restart`. A bare restart
# re-runs whatever script path was saved earlier; after the build-output
# reorg (app/ -> dist/, .next -> .build/next) a process pinned to the old
# app/server-ws.mjs path can no longer start, and the node process dies
# while PM2 still reports "online" — so the box never binds :20128.
# Always launch via the `omniroute` bin so .env is loaded and the dist/
# layout is resolved correctly.
echo "=== (Re)creating PM2 process via bin ==="
pm2 delete omniroute 2>/dev/null || true
pm2 start omniroute --name omniroute -- --port 20128
echo "=== Restarting PM2 ==="
pm2 restart omniroute || pm2 start omniroute --name omniroute -- --port 20128
pm2 save
# Health gate: fail the deploy unless the box actually reports healthy.
# Poll /api/monitoring/health for "status":"healthy" (a deeper signal than
# a static page 200 — it confirms the app booted, not just that a port is
# bound). Boot can take a while after a native-module/build-layout change,
# so poll up to ~3min before giving up.
echo "=== Health Check (gates the deploy) ==="
ok=0
for i in $(seq 1 36); do
BODY=$(curl -sf -m 5 http://localhost:20128/api/monitoring/health 2>/dev/null || true)
if printf '%s' "$BODY" | grep -q '"status":"healthy"'; then
ok=1
echo "✅ /api/monitoring/health -> healthy (attempt $i) — version $INSTALLED_VERSION"
break
fi
echo "… not healthy yet (attempt $i/36), retrying in 5s"
sleep 5
done
if [ "$ok" != "1" ]; then
echo "❌ Health check failed — /api/monitoring/health never reported healthy after ~3min"
echo "--- recent PM2 logs ---"
pm2 logs omniroute --lines 40 --nostream || true
exit 1
fi
echo "=== Health Check ==="
sleep 3
curl -sf http://localhost:20128/api/settings > /dev/null && echo "✅ OmniRoute is healthy" || echo "❌ Health check failed"
echo "=== Deploy complete ==="

View File

@@ -4,891 +4,85 @@ on:
push:
branches:
- main
- "release/v*"
tags:
- "v*"
paths-ignore:
- ".github/workflows/**"
# Use 'released' instead of 'published' so editing/re-publishing old releases
# does NOT re-trigger this workflow. 'released' fires only on the initial
# release publication (and pre-release → release transition).
release:
types: [released]
# #14560: nightly re-run exists only to drive the omni-build runner alert below
# (open/close the tracking issue). Publish jobs skip themselves on this event.
schedule:
- cron: "41 4 * * *"
types: [published]
workflow_dispatch:
inputs:
version:
description: "Version tag to build (e.g. 3.8.4)"
description: "Version tag to build (e.g. 2.6.0)"
required: true
type: string
promote_latest:
description: "Also tag :latest (only if this is the highest semver)"
required: false
type: boolean
default: false
# One publish per ref. A merge storm used to fan out 8 concurrent hosted builds,
# every one OOM-killing `npm run build` inside BuildKit (#11976). The :next
# channel only needs the newest SHA; cancel-in-progress is the same pattern as
# quality.yml / nightly-release-green.
# The nightly `schedule` run (runner-alert only) gets its own group: it runs on the
# default branch ref, so sharing the publish group would let cancel-in-progress kill
# an in-flight release-branch publish every night (#14560 follow-up).
# A push to release/v* must NOT cancel the build already running for that branch (#17230):
# the amd64 image takes ~2 h on the single omni-build runner and the branch merges faster than
# that, so with cancel-in-progress the next/next-web channel went 13 days without an image
# (24 cancelled publishes on 2026-10-19 alone). Without it GitHub still keeps at most one
# running and one pending run per group — an older pending run is replaced by the newest push,
# the in-flight build completes, the latest tip follows. Tags, releases, dispatches and the
# scheduled alert keep cancelling.
concurrency:
group: docker-publish-${{ github.event_name == 'schedule' && 'runner-alert' || github.ref }}
cancel-in-progress: ${{ !(github.event_name == 'push' && startsWith(github.ref, 'refs/heads/release/')) }}
# Least-privilege default: read-only at the top level; the build and merge jobs that
# push to GHCR grant packages: write themselves (Scorecard TokenPermissions).
permissions:
contents: read
packages: write
jobs:
prepare:
name: Resolve Docker release metadata
permissions:
contents: read
packages: read
# Read this month's docker-publish jobs for the Blacksmith budget step.
actions: read
# Keep the explicit upstream scheduled-run guard on every job, including
# publish jobs that currently exclude schedule entirely.
if: >-
github.event_name != 'schedule' &&
(github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
# With DOCKER_AMD64_RUNNER=blacksmith the small jobs around the build run on Blacksmith as
# well: on 2026-11-03 this job waited 3 h for a hosted ubuntu-latest slot behind ~300 queued
# PR runs. About 2.5 min here plus 4.5 min in `merge` per publish, on 2 vCPU.
runs-on: ${{ vars.DOCKER_AMD64_RUNNER == 'blacksmith' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }}
outputs:
version: ${{ steps.version.outputs.version }}
promote_latest: ${{ steps.version.outputs.promote_latest }}
skip: ${{ steps.version.outputs.skip }}
# 'true' while DOCKER_AMD64_RUNNER=blacksmith and the month's Blacksmith minutes are
# under BLACKSMITH_MONTHLY_MINUTES_CAP; `build` and `merge` route on it.
blacksmith: ${{ steps.budget.outputs.blacksmith }}
env:
IMAGE_NAME: diegosouzapw/omniroute
GHCR_IMAGE_NAME: ghcr.io/cheaper-inference/omniroute
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
# Control scripts come from this workflow ref, not an older release tag.
# The build job below still checks out the requested version's source.
# Shallow: the :latest decision reads tag NAMES from `git ls-remote` below, so the
# 2.6 GB history is not needed. A full clone took 30+ min on a Blacksmith runner
# (outside GitHub's network) on 2026-11-03.
fetch-depth: 1
# Blacksmith keeps running and invoices past its free 3,000 minutes, and a publish costs
# ~90 of them, so the month's usage is summed here and the build falls back to the hosted
# runner at the cap (default 2,500, leaving room for the jobs already in flight).
- name: Stay within the Blacksmith monthly minutes
id: budget
env:
WANT: ${{ vars.DOCKER_AMD64_RUNNER }}
CAP: ${{ vars.BLACKSMITH_MONTHLY_MINUTES_CAP || '2500' }}
REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
SELF_RUN_ID: ${{ github.run_id }}
run: node scripts/ci/blacksmith-budget.mjs
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to GitHub Container Registry
uses: docker/login-action@v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Resolve version, latest-promotion, and skip flag
id: version
env:
EVENT_NAME: ${{ github.event_name }}
REF_NAME: ${{ github.ref_name }}
REF_TYPE: ${{ github.ref_type }}
INPUT_VERSION: ${{ inputs.version }}
PROMOTE_INPUT: ${{ inputs.promote_latest }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
run: |
set -euo pipefail
# 1) Resolve version/channel from the trigger. Only the current default
# release branch publishes the mutable `next` channel; main keeps `main`.
VERSION=$(bash scripts/ci/resolve-docker-publish-version.sh \
"$EVENT_NAME" "$REF_TYPE" "$REF_NAME" "$INPUT_VERSION" "$DEFAULT_BRANCH")
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
# Frozen release branches keep receiving coordination commits after the
# next cycle becomes the default branch. They must not overwrite :next,
# but that expected no-op is not a workflow failure.
if [ "$VERSION" = "skip" ]; then
echo "promote_latest=false" >> "$GITHUB_OUTPUT"
echo "skip=true" >> "$GITHUB_OUTPUT"
echo "Skipping Docker publish from non-default release branch: $REF_NAME"
exit 0
fi
# 2) Decide whether to promote :latest. Floating channels are never
# eligible, and the helper independently fails closed for non-semver.
PROMOTE="false"
if [ "$VERSION" = "main" ] || [ "$VERSION" = "next" ]; then
PROMOTE="false"
elif printf '%s' "$VERSION" | grep -qE -- '-(rc|alpha|beta|pre|next)'; then
echo "Pre-release identifier detected — skipping :latest."
PROMOTE="false"
elif [ "$EVENT_NAME" = "workflow_dispatch" ]; then
PROMOTE="${PROMOTE_INPUT:-false}"
else
# Decide via the extracted helper, which folds VERSION into the
# candidate set so the result is independent of git-tag sync timing
# on `release` events (#5301). Without that, the freshly-created tag
# is often not yet visible here and :latest stays a release behind.
# Tag names come straight from the remote (same set `git fetch --tags`
# gave the full clone); under pipefail a failed listing fails the step
# instead of promoting against an empty list.
PROMOTE=$(git ls-remote --tags --refs origin \
| sed -n 's#^[0-9a-f]*[[:space:]]refs/tags/\(v[0-9].*\)$#\1#p' \
| bash scripts/ci/should-promote-latest.sh "$VERSION")
if [ "$PROMOTE" != "true" ]; then
echo "Version $VERSION is not the highest stable semver. Not promoting :latest."
fi
fi
echo "promote_latest=$PROMOTE" >> "$GITHUB_OUTPUT"
# 3) Skip only when the mandatory Node and Web images are complete in BOTH
# registries: an existing Node base must not block repairing a missing Web
# image or architecture. Bun is deliberately not part of this check. It is
# best-effort, so a release with a failing Bun leg, or a historical version
# without Bun tags, must not rebuild (~2 h) on every trigger. workflow_dispatch
# never skips: it is the explicit repair path, Bun tags and stale aliases included.
# Helper exit codes: 1 = missing or incomplete (publish), 2 = could not tell.
SKIP="false"
if [ "$VERSION" != "main" ] && [ "$VERSION" != "next" ] && [ "$EVENT_NAME" != "workflow_dispatch" ]; then
SKIP="true"
for ref in \
"${IMAGE_NAME}:${VERSION}" "${IMAGE_NAME}:${VERSION}-web" \
"${GHCR_IMAGE_NAME}:${VERSION}" "${GHCR_IMAGE_NAME}:${VERSION}-web"; do
rc=0
node scripts/ci/docker-image-complete.mjs "$ref" || rc=$?
if [ "$rc" -eq 1 ]; then
echo "$ref is missing or incomplete — publishing."
SKIP="false"
break
fi
if [ "$rc" -ne 0 ]; then
echo "::error::Could not inspect $ref (registry error, not a missing tag). Not starting a rebuild on an unknown state: re-run this job once the registry recovers, or use workflow_dispatch to force a publish."
exit 1
fi
done
fi
echo "skip=$SKIP" >> "$GITHUB_OUTPUT"
echo "Publishing diegosouzapw/omniroute:$VERSION (promote_latest=$PROMOTE, skip=$SKIP)"
# #14560: when USE_VPS_RUNNER is on, the amd64 leg can ONLY run on the single
# `omni-build` self-hosted listener. If that box is offline, GitHub queues the
# job forever — no error, no timeout (timeout-minutes only starts once a
# runner picks the job up, so it cannot bound queue time) — and the publish
# silently stalls until a human cancels the run. This preflight turns that
# silent queue into a red run within minutes, with the verdict in the job name.
runner-preflight:
name: Preflight — amd64 runner availability
needs: prepare
if: >-
github.event_name != 'schedule' && needs.prepare.outputs.skip != 'true' && vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' &&
vars.DOCKER_AMD64_RUNNER != 'blacksmith' && vars.DOCKER_AMD64_RUNNER != 'hosted' &&
(github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
docker:
name: Build and Push Docker (multi-arch)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Check an online runner carries the omni-build label
env:
# Listing self-hosted runners needs the repository "Administration: read"
# permission, which GITHUB_TOKEN can never be granted through `permissions:`.
# RUNNER_STATUS_TOKEN (optional secret: fine-grained PAT with Administration
# read on this repo, or a classic PAT with `repo`) activates the check;
# without it the API answers 403 and the preflight fails OPEN with a
# warning, so a missing/under-scoped token can never block a publish.
GH_TOKEN: ${{ secrets.RUNNER_STATUS_TOKEN || github.token }}
run: |
set -euo pipefail
if ! ONLINE=$(gh api "repos/${GITHUB_REPOSITORY}/actions/runners" \
--paginate --jq '[.runners[] | select(.status == "online") | select(any(.labels[]; .name == "omni-build"))] | length'); then
echo "::warning::Could not list self-hosted runners (token lacks Administration read — set the RUNNER_STATUS_TOKEN secret). Skipping the omni-build availability check."
exit 0
fi
echo "online omni-build runners: ${ONLINE}"
if [ "${ONLINE}" -eq 0 ]; then
echo "::error::No ONLINE runner carries the omni-build label. The amd64 build would queue forever (silent publish stall, #14560)."
echo "Check the self-hosted runner pool, or set DOCKER_AMD64_RUNNER=hosted (or blacksmith) to build amd64 off the .113 slot."
exit 1
fi
build:
name: Build Docker (${{ matrix.platform }})
needs: [prepare, runner-preflight]
# runner-preflight is SKIPPED when USE_VPS_RUNNER is off; a plain `if:` would
# inherit the implicit success() check and skip the whole build with it.
if: >-
!cancelled() && github.event_name != 'schedule' &&
needs.prepare.result == 'success' && needs.prepare.outputs.skip != 'true' &&
(needs.runner-preflight.result == 'success' || needs.runner-preflight.result == 'skipped') &&
(github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
# amd64: the .113 omni-build pool (31 GB / 32 cores, ONE listener since
# #12048). Hosted ubuntu-24.04 is 16 GB; the ~7 GB runners of #11976 died
# ResourceExhausted. Falls back to hosted when USE_VPS_RUNNER is off. arm64: no ARM box — stay
# on GitHub's ubuntu-24.04-arm.
# Webpack on BOTH arches: Turbopack on omniroute-113-6 hit
# TurbopackInternalError "there must be a path to a root" after 26 min
# (run 33253576569). The same tree's arm64 webpack build on hosted ARM
# succeeded (run 33264823398). Dockerfile already documents webpack as the
# Docker escape hatch (OMNIROUTE_USE_TURBOPACK=0).
# DOCKER_AMD64_RUNNER (repository variable) moves the amd64 leg off the .113 slot, which takes
# 90-165 min per publish while the same build on a 16 GB / 4 vCPU hosted runner takes 20-45:
# blacksmith → blacksmith-4vcpu-ubuntu-2404 (16 GB; needs the Blacksmith app on the org; the
# free tier is 3,000 2-vCPU minutes a month and a 4 vCPU minute counts as two)
# hosted → ubuntu-24.04 (16 GB)
# unset → unchanged: omni-build when the .113 opt-in is on, hosted otherwise
# The Dockerfile build is sized for 16 GB (OMNIROUTE_BUILD_WORKERS, #7518).
# `blacksmith` routes through prepare's budget output; at the monthly cap it lands on hosted.
runs-on: ${{ matrix.arch == 'amd64' && (needs.prepare.outputs.blacksmith == 'true' && 'blacksmith-4vcpu-ubuntu-2404' || vars.DOCKER_AMD64_RUNNER != 'hosted' && vars.DOCKER_AMD64_RUNNER != 'blacksmith' && vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && fromJSON('["self-hosted","omni-build"]') || 'ubuntu-24.04') || 'ubuntu-24.04-arm' }}
# Share the 1-slot omni-build ceiling (#12048) with ci.yml `Build` /
# npm-publish. Same group as main's Build so a :next publish waits beside
# the artefact instead of sitting next to it. arm64 is hosted — its own
# group, cancelled by the workflow-level concurrency. An amd64 leg moved by
# DOCKER_AMD64_RUNNER does not hold the slot, so it gets a per-ref group.
concurrency:
group: ${{ matrix.arch == 'amd64' && (vars.DOCKER_AMD64_RUNNER != 'blacksmith' && vars.DOCKER_AMD64_RUNNER != 'hosted' && 'heavy-build-main' || format('docker-publish-amd64-{0}', github.ref)) || format('docker-publish-arm-{0}', github.ref) }}
cancel-in-progress: ${{ matrix.arch != 'amd64' }}
# Backstop for a hung BUILD step only — it cannot and must not bound the
# queue wait (that is runner-preflight's job): the clock starts when a
# runner accepts the job. 350 min = the ~2h50m observed webpack build plus
# headroom, so a wedged Docker/BuildKit step fails loudly instead of
# holding the single omni-build slot until someone notices.
timeout-minutes: 350
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
include:
- platform: linux/amd64
arch: amd64
- platform: linux/arm64
arch: arm64
env:
IMAGE_NAME: diegosouzapw/omniroute
GHCR_IMAGE_NAME: ghcr.io/cheaper-inference/omniroute
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
persist-credentials: false
ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/v{0}', inputs.version) || '' }}
# .dockerignore drops .git, so the image build never reads history.
fetch-depth: 1
- name: Assert Docker Engine
run: docker info
- name: Set up QEMU (for multi-arch builds)
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# Heap for the webpack build inside BuildKit: 12288 MB on every build-args block below.
# Validated on the hosted runners (16 GB) by the publishes of 2026-10-16/17 — runs
# 38904652365, 38907575198 and 39010473398, amd64 and arm64 green (27-55 min). It stays
# at or above build.yml's native webpack floor (10240 MB), never below it
# (tests/unit/docker-publish-build-heap-14325.test.ts).
- name: Build and push platform image by digest
id: build
- name: Extract version from release tag or input
id: version
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
VERSION="${{ inputs.version }}"
else
VERSION="${GITHUB_REF_NAME}"
VERSION="${VERSION#v}"
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "Publishing Docker image: $IMAGE_NAME:$VERSION"
- name: Build and push multi-arch image
uses: docker/build-push-action@v7
with:
context: .
target: runner-base
platforms: ${{ matrix.platform }}
build-args: |
OMNIROUTE_USE_TURBOPACK=0
OMNIROUTE_BUILD_MEMORY_MB=12288
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ env.IMAGE_NAME }}
${{ env.GHCR_IMAGE_NAME }}
cache-from: type=gha,scope=docker-${{ matrix.arch }}
cache-to: type=gha,scope=docker-${{ matrix.arch }},mode=max,ignore-error=true
${{ env.IMAGE_NAME }}:${{ steps.version.outputs.version }}
${{ env.IMAGE_NAME }}:latest
ghcr.io/diegosouzapw/omniroute:${{ steps.version.outputs.version }}
ghcr.io/diegosouzapw/omniroute:latest
cache-from: type=gha
cache-to: type=gha,mode=max
no-cache: false
env:
DOCKER_BUILDKIT_INLINE_CACHE: 1
- name: Build and push WEB platform image by digest
id: build-web
uses: docker/build-push-action@v7
with:
context: .
target: runner-web
platforms: ${{ matrix.platform }}
build-args: |
OMNIROUTE_USE_TURBOPACK=0
OMNIROUTE_BUILD_MEMORY_MB=12288
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
tags: |
${{ env.IMAGE_NAME }}
${{ env.GHCR_IMAGE_NAME }}
# runner-web extends runner-base: reuse this run's base build as well
# as the previous Web cache, without mixing Node/Bun or architectures.
cache-from: |
type=gha,scope=docker-web-${{ matrix.arch }}
type=gha,scope=docker-${{ matrix.arch }}
cache-to: type=gha,scope=docker-web-${{ matrix.arch }},mode=max,ignore-error=true
no-cache: false
env:
DOCKER_BUILDKIT_INLINE_CACHE: 1
# Check the binaries in both final Node images on each native architecture,
# before their digests can reach the multi-arch manifest/promotion job.
- name: Verify published Node runtimes
env:
DIGEST_BASE: ${{ steps.build.outputs.digest }}
DIGEST_WEB: ${{ steps.build-web.outputs.digest }}
PLATFORM: ${{ matrix.platform }}
run: |
set -euo pipefail
for digest in "$DIGEST_BASE" "$DIGEST_WEB"; do
image="${GHCR_IMAGE_NAME}@${digest}"
echo "Verifying Node runtime in ${image} (${PLATFORM})"
docker run --rm --pull always --platform "$PLATFORM" --entrypoint node -i \
"$image" --input-type=module < scripts/ci/check-docker-node-runtime.mjs
done
# The mandatory digests leave this job BEFORE any Bun step starts, so nothing Bun
# does can stop them from being exported and uploaded (#11724, #11740, #17223).
- name: Export digests
env:
DIGEST_BASE: ${{ steps.build.outputs.digest }}
DIGEST_WEB: ${{ steps.build-web.outputs.digest }}
run: |
set -euo pipefail
# Self-hosted runners keep /tmp across runs: start empty so digests of
# earlier runs are never uploaded (#15184).
rm -rf /tmp/digests
mkdir -p /tmp/digests/base /tmp/digests/web
touch "/tmp/digests/base/${DIGEST_BASE#sha256:}"
touch "/tmp/digests/web/${DIGEST_WEB#sha256:}"
- name: Upload base digests
uses: actions/upload-artifact@v7
with:
name: digests-base-${{ matrix.arch }}
path: /tmp/digests/base/*
if-no-files-found: error
retention-days: 1
- name: Upload web digests
uses: actions/upload-artifact@v7
with:
name: digests-web-${{ matrix.arch }}
path: /tmp/digests/web/*
if-no-files-found: error
retention-days: 1
- name: Build and push BUN base platform image by digest
id: build-bun-base
# Bun is a best-effort compatibility target, not a supported runtime
# (AGENTS.md -> Environment). Its `bun run build` has been OOM-killing on
# both arches; letting that sink the whole publish means the SUPPORTED
# runner-base / runner-web images never reach the registry either. The
# merge job publishes a Bun tag only when both architectures produced a
# valid digest, so a failure here costs that tag and nothing else.
continue-on-error: true
# A step limit, because reaching the job's 350 min limit fails the job and the
# merge job then publishes nothing. Observed amd64 Bun base: 57 min (2026-11-02).
timeout-minutes: 80
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
with:
context: .
file: Dockerfile.bun
target: runner-base
platforms: ${{ matrix.platform }}
build-args: |
OMNIROUTE_USE_TURBOPACK=0
OMNIROUTE_BUILD_MEMORY_MB=12288
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
tags: |
${{ env.IMAGE_NAME }}
${{ env.GHCR_IMAGE_NAME }}
cache-from: type=gha,scope=docker-bun-base-${{ matrix.arch }}
cache-to: type=gha,scope=docker-bun-base-${{ matrix.arch }},mode=max,ignore-error=true
no-cache: false
env:
DOCKER_BUILDKIT_INLINE_CACHE: 1
- name: Build and push BUN web platform image by digest
id: build-bun-web
# Best-effort, same as the Bun base step above.
continue-on-error: true
timeout-minutes: 80
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
with:
context: .
file: Dockerfile.bun
target: runner-web
platforms: ${{ matrix.platform }}
build-args: |
OMNIROUTE_USE_TURBOPACK=0
OMNIROUTE_BUILD_MEMORY_MB=12288
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
tags: |
${{ env.IMAGE_NAME }}
${{ env.GHCR_IMAGE_NAME }}
cache-from: |
type=gha,scope=docker-bun-web-${{ matrix.arch }}
type=gha,scope=docker-bun-base-${{ matrix.arch }}
cache-to: type=gha,scope=docker-bun-web-${{ matrix.arch }},mode=max,ignore-error=true
no-cache: false
env:
DOCKER_BUILDKIT_INLINE_CACHE: 1
- name: Export Bun digests
continue-on-error: true
env:
DIGEST_BUN_BASE: ${{ steps.build-bun-base.outputs.digest }}
DIGEST_BUN_WEB: ${{ steps.build-bun-web.outputs.digest }}
run: |
set -euo pipefail
mkdir -p /tmp/digests/bun-base /tmp/digests/bun-web
# Empty when the (non-blocking) bun build produced no image. `if` blocks,
# not `[ -n ] && touch`: under `set -e` a failing AND-list aborts the step,
# which is precisely the case being handled here.
if [ -n "$DIGEST_BUN_BASE" ]; then
touch "/tmp/digests/bun-base/${DIGEST_BUN_BASE#sha256:}"
else
echo "::warning::Bun base build produced no digest on this architecture: no -bun tag this run."
fi
if [ -n "$DIGEST_BUN_WEB" ]; then
touch "/tmp/digests/bun-web/${DIGEST_BUN_WEB#sha256:}"
else
echo "::warning::Bun web build produced no digest on this architecture: no -web-bun tag this run."
fi
- name: Upload bun-base digests
# continue-on-error: a failed upload would otherwise fail the job and the merge
# job would then skip the mandatory images too. `ignore`, not `error`: an absent
# digest is the expected outcome of a failed bun image.
continue-on-error: true
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: digests-bun-base-${{ matrix.arch }}
path: /tmp/digests/bun-base/*
if-no-files-found: ignore
retention-days: 1
- name: Upload bun-web digests
# Same as the bun-base upload above.
continue-on-error: true
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: digests-bun-web-${{ matrix.arch }}
path: /tmp/digests/bun-web/*
if-no-files-found: ignore
retention-days: 1
merge:
name: Publish multi-arch manifests
needs:
- prepare
- build
# Explicit results, like `build`: an implicit success() also looks at `build`'s own
# dependency runner-preflight, which is SKIPPED whenever amd64 is off the omni-build slot
# (DOCKER_AMD64_RUNNER, USE_VPS_RUNNER off), and that silently skipped this job after both
# images built (run 41703618029, 2026-11-03).
if: >-
!cancelled() && github.event_name != 'schedule' &&
needs.prepare.result == 'success' && needs.build.result == 'success' &&
needs.prepare.outputs.skip != 'true' &&
(github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
# On Blacksmith with the amd64 build; on hosted once the monthly budget is spent.
runs-on: ${{ needs.prepare.outputs.blacksmith == 'true' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }}
permissions:
contents: read
packages: write
security-events: write
env:
IMAGE_NAME: diegosouzapw/omniroute
GHCR_IMAGE_NAME: ghcr.io/cheaper-inference/omniroute
VERSION: ${{ needs.prepare.outputs.version }}
PROMOTE_LATEST: ${{ needs.prepare.outputs.promote_latest }}
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
# Manifest validation must use the current workflow's helper on backfills.
# Manifests, smoke test and scans read no git history.
fetch-depth: 1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4.6.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Download base digests
uses: actions/download-artifact@v8
with:
pattern: digests-base-*
path: /tmp/digests/base
merge-multiple: true
- name: Download web digests
uses: actions/download-artifact@v8
with:
pattern: digests-web-*
path: /tmp/digests/web
merge-multiple: true
- name: Download bun-base digests
# Non-blocking: the bun image is best-effort, so its artifact may not
# exist at all. The guard below decides whether its tag is published.
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
pattern: digests-bun-base-*
path: /tmp/digests/bun-base
merge-multiple: true
- name: Download bun-web digests
# Non-blocking: the bun image is best-effort, so its artifact may not
# exist at all. The guard below decides whether its tag is published.
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
pattern: digests-bun-web-*
path: /tmp/digests/bun-web
merge-multiple: true
- name: Guard against stale digests
id: digests
run: |
set -euo pipefail
# Validate every flavor in both registries BEFORE moving any public tag.
# Counting alone cannot distinguish two AMD64 images from AMD64 + ARM64.
pair_is_valid() {
local dir="$1" image digest_file
local refs
for image in "$IMAGE_NAME" "$GHCR_IMAGE_NAME"; do
refs=()
while IFS= read -r digest_file; do
refs+=("${image}@sha256:$(basename "$digest_file")")
done < <(find "$dir" -type f | sort)
node scripts/ci/docker-image-complete.mjs "${refs[@]}" || return 1
done
}
# Node and Web are mandatory: anything but a valid pair stops the publish.
for dir in base web; do
if [ ! -d "/tmp/digests/$dir" ]; then
echo "Missing digest directory: $dir" >&2
exit 1
fi
count=$(find "/tmp/digests/$dir" -type f | wc -l)
if [ "$count" -gt 2 ] || [ "$count" -lt 2 ]; then
echo "digests in $dir: found $count, expected exactly 2 (amd64 + arm64)" >&2
exit 1
fi
if ! pair_is_valid "/tmp/digests/$dir"; then
echo "digests in $dir: the pair is not one linux/amd64 + one linux/arm64 in both registries" >&2
exit 1
fi
done
# Bun is best-effort but all-or-nothing per flavor: both architectures valid
# in both registries publish the tag; anything else warns and publishes none.
for dir in bun-base bun-web; do
problem=""
if [ ! -d "/tmp/digests/$dir" ]; then
problem="no digests"
else
count=$(find "/tmp/digests/$dir" -type f | wc -l)
if [ "$count" -gt 2 ] || [ "$count" -lt 2 ]; then
problem="found $count digests, expected exactly 2 (amd64 + arm64)"
elif ! pair_is_valid "/tmp/digests/$dir"; then
problem="the pair is not one linux/amd64 + one linux/arm64 in both registries"
fi
fi
publish="true"
if [ -n "$problem" ]; then
publish="false"
echo "::warning::Not publishing the $dir image: $problem. Bun is best-effort; the Node and Web images are unaffected."
fi
echo "publish_${dir//-/_}=$publish" >> "$GITHUB_OUTPUT"
done
- name: Create Docker Hub version manifests
env:
PUBLISH_BUN_BASE: ${{ steps.digests.outputs.publish_bun_base }}
PUBLISH_BUN_WEB: ${{ steps.digests.outputs.publish_bun_web }}
run: |
set -euo pipefail
create_manifest() {
local image="$1" suffix="$2" dir="$3"
local refs=()
while IFS= read -r digest_file; do
refs+=("${image}@sha256:$(basename "$digest_file")")
done < <(find "$dir" -type f | sort)
node scripts/ci/docker-image-complete.mjs "${refs[@]}" || return 1
docker buildx imagetools create -t "${image}:${VERSION}${suffix}" "${refs[@]}" || return 1
}
# A failed Bun manifest warns and never stops the mandatory tags.
create_bun_manifest() {
local publish="$1" image="$2" suffix="$3" dir="$4"
if [ "$publish" != "true" ]; then
return 0
fi
if ! create_manifest "$image" "$suffix" "$dir"; then
echo "::warning::Could not publish ${image}:${VERSION}${suffix}. Bun is best-effort; continuing."
fi
}
create_manifest "${IMAGE_NAME}" "" /tmp/digests/base
create_manifest "${IMAGE_NAME}" "-web" /tmp/digests/web
create_bun_manifest "${PUBLISH_BUN_BASE:-false}" "${IMAGE_NAME}" "-bun" /tmp/digests/bun-base
create_bun_manifest "${PUBLISH_BUN_WEB:-false}" "${IMAGE_NAME}" "-web-bun" /tmp/digests/bun-web
- name: Create GHCR version manifests
env:
PUBLISH_BUN_BASE: ${{ steps.digests.outputs.publish_bun_base }}
PUBLISH_BUN_WEB: ${{ steps.digests.outputs.publish_bun_web }}
run: |
set -euo pipefail
create_manifest() {
local image="$1" suffix="$2" dir="$3"
local refs=()
while IFS= read -r digest_file; do
refs+=("${image}@sha256:$(basename "$digest_file")")
done < <(find "$dir" -type f | sort)
node scripts/ci/docker-image-complete.mjs "${refs[@]}" || return 1
docker buildx imagetools create -t "${image}:${VERSION}${suffix}" "${refs[@]}" || return 1
}
# A failed Bun manifest warns and never stops the mandatory tags.
create_bun_manifest() {
local publish="$1" image="$2" suffix="$3" dir="$4"
if [ "$publish" != "true" ]; then
return 0
fi
if ! create_manifest "$image" "$suffix" "$dir"; then
echo "::warning::Could not publish ${image}:${VERSION}${suffix}. Bun is best-effort; continuing."
fi
}
create_manifest "${GHCR_IMAGE_NAME}" "" /tmp/digests/base
create_manifest "${GHCR_IMAGE_NAME}" "-web" /tmp/digests/web
create_bun_manifest "${PUBLISH_BUN_BASE:-false}" "${GHCR_IMAGE_NAME}" "-bun" /tmp/digests/bun-base
create_bun_manifest "${PUBLISH_BUN_WEB:-false}" "${GHCR_IMAGE_NAME}" "-web-bun" /tmp/digests/bun-web
- name: Smoke-test published Docker image
if: needs.prepare.outputs.version != 'main'
run: |
set -euo pipefail
container="omniroute-smoke-${VERSION//[^a-zA-Z0-9_.-]/-}"
trap 'docker rm -f "$container" >/dev/null 2>&1 || true' EXIT
docker run --detach --name "$container" "${IMAGE_NAME}:${VERSION}"
for attempt in $(seq 1 30); do
status="$(docker inspect --format '{{.State.Health.Status}}' "$container")"
if [ "$status" = "healthy" ]; then
exit 0
fi
if [ "$status" = "unhealthy" ] || [ "$(docker inspect --format '{{.State.Status}}' "$container")" = "exited" ]; then
docker logs "$container"
exit 1
fi
sleep 2
done
docker logs "$container"
exit 1
- name: Promote Docker Hub latest tags
if: needs.prepare.outputs.promote_latest == 'true'
env:
PUBLISH_BUN_BASE: ${{ steps.digests.outputs.publish_bun_base }}
PUBLISH_BUN_WEB: ${{ steps.digests.outputs.publish_bun_web }}
run: |
set -euo pipefail
promote_tag() {
local suffix="$1"
docker buildx imagetools create -t "${IMAGE_NAME}:latest${suffix}" "${IMAGE_NAME}:${VERSION}${suffix}"
}
# Validate every source before promoting any flavor. The mandatory tags must be
# complete; a Bun alias moves only for a complete tag published by this run.
for suffix in "" -web; do
node scripts/ci/docker-image-complete.mjs "${IMAGE_NAME}:${VERSION}${suffix}"
done
bun_aliases=()
add_bun_alias() {
local publish="$1" suffix="$2"
if [ "$publish" = "true" ] && node scripts/ci/docker-image-complete.mjs "${IMAGE_NAME}:${VERSION}${suffix}"; then
bun_aliases+=("$suffix")
else
echo "::warning::Not promoting ${IMAGE_NAME}:latest${suffix}: this run has no complete Bun image for it."
fi
}
add_bun_alias "${PUBLISH_BUN_BASE:-false}" -bun
add_bun_alias "${PUBLISH_BUN_WEB:-false}" -web-bun
for suffix in "" -web; do
promote_tag "$suffix"
done
for suffix in "${bun_aliases[@]}"; do
promote_tag "$suffix" || echo "::warning::Could not promote ${IMAGE_NAME}:latest${suffix}. Bun is best-effort; continuing."
done
- name: Promote GHCR latest tags
if: needs.prepare.outputs.promote_latest == 'true'
env:
PUBLISH_BUN_BASE: ${{ steps.digests.outputs.publish_bun_base }}
PUBLISH_BUN_WEB: ${{ steps.digests.outputs.publish_bun_web }}
run: |
set -euo pipefail
promote_tag() {
local suffix="$1"
docker buildx imagetools create -t "${GHCR_IMAGE_NAME}:latest${suffix}" "${GHCR_IMAGE_NAME}:${VERSION}${suffix}"
}
for suffix in "" -web; do
node scripts/ci/docker-image-complete.mjs "${GHCR_IMAGE_NAME}:${VERSION}${suffix}"
done
bun_aliases=()
add_bun_alias() {
local publish="$1" suffix="$2"
if [ "$publish" = "true" ] && node scripts/ci/docker-image-complete.mjs "${GHCR_IMAGE_NAME}:${VERSION}${suffix}"; then
bun_aliases+=("$suffix")
else
echo "::warning::Not promoting ${GHCR_IMAGE_NAME}:latest${suffix}: this run has no complete Bun image for it."
fi
}
add_bun_alias "${PUBLISH_BUN_BASE:-false}" -bun
add_bun_alias "${PUBLISH_BUN_WEB:-false}" -web-bun
for suffix in "" -web; do
promote_tag "$suffix"
done
for suffix in "${bun_aliases[@]}"; do
promote_tag "$suffix" || echo "::warning::Could not promote ${GHCR_IMAGE_NAME}:latest${suffix}. Bun is best-effort; continuing."
done
- name: Inspect image
if: needs.prepare.outputs.version != 'main'
run: |
docker buildx imagetools inspect "${IMAGE_NAME}:${VERSION}"
- name: Generate CycloneDX SBOM (image, advisory)
if: needs.prepare.outputs.version != 'main'
continue-on-error: true
uses: anchore/sbom-action@v0
with:
image: ${{ env.GHCR_IMAGE_NAME }}:${{ env.VERSION }}
format: cyclonedx-json
output-file: sbom-image.cdx.json
artifact-name: sbom-image.cdx.json
# Visibility scan: reports HIGH + CRITICAL into the SARIF (Security tab) but
# never blocks (exit-code 0). The blocking gate below narrows to CRITICAL.
#
# ignore-unfixed mirrors the blocking gate: the Security tab must surface only
# ACTIONABLE vulnerabilities — ones with a published fix we can pull by rebuilding
# on a patched base or bumping the dep. Without it the advisory upload floods the
# tab with unfixable base-image OS CVEs (Debian trixie packages with no upstream
# patch yet, overwhelmingly local-only and not reachable from the proxy request
# surface), which is noise an operator cannot act on. trivyignores points at the
# repo-root .trivyignore so accepted-risk fixable CVEs have one auditable home.
# See docs/security/SUPPLY_CHAIN.md.
- name: Trivy image scan (SARIF, advisory)
if: needs.prepare.outputs.version != 'main'
continue-on-error: true
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
image-ref: ${{ env.GHCR_IMAGE_NAME }}:${{ env.VERSION }}
format: sarif
output: trivy-results.sarif
severity: HIGH,CRITICAL
ignore-unfixed: true
trivyignores: .trivyignore
exit-code: "0"
# BLOCKING gate (v3.8.27 cycle-end): fail the release on a CRITICAL CVE in the
# published image. Narrowed to severity CRITICAL (HIGH stays visible in the
# SARIF step above, not blocking). ignore-unfixed:true so an unfixable base-image
# CVE with no upstream patch does not red the release (reduces false-blocks);
# a fixable CRITICAL still blocks. Per docs/security/SUPPLY_CHAIN.md. NB: Trivy
# scans against a CVE DB that grows continuously — a newly-disclosed CRITICAL on
# an unchanged base image can red this gate; the fix is to rebuild on a patched
# base, bump the dep, or add a justified .trivyignore entry (see the CVE-variance
# note in docs/security/SUPPLY_CHAIN.md).
- name: Trivy CRITICAL gate (blocking)
if: needs.prepare.outputs.version != 'main'
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
image-ref: ${{ env.GHCR_IMAGE_NAME }}:${{ env.VERSION }}
format: table
severity: CRITICAL
ignore-unfixed: true
exit-code: "1"
# Explicit: the advisory scan above already points at it, and the blocking
# gate must honour the same accepted-risk list (#12084).
trivyignores: .trivyignore
- name: Upload Trivy SARIF to Security tab
if: needs.prepare.outputs.version != 'main'
continue-on-error: true
uses: github/codeql-action/upload-sarif@v4.39.1
with:
sarif_file: trivy-results.sarif
category: trivy-image
docker buildx imagetools inspect "${{ env.IMAGE_NAME }}:${{ steps.version.outputs.version }}"
- name: Update Docker Hub description
# Only refresh README/description when we actually promote :latest
# (avoids overwriting from main, next, or back-fill builds).
if: needs.prepare.outputs.promote_latest == 'true'
uses: peter-evans/dockerhub-description@v5
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
@@ -896,66 +90,3 @@ jobs:
repository: diegosouzapw/omniroute
short-description: "OmniRoute — Unified AI proxy. Route any LLM through one endpoint."
readme-filepath: ./README.md
# #14560: alert when the only omni-build runner goes offline. Mirrors the
# nightly-release-green issue loop: open a deduplicated tracking issue when
# no online runner carries the label, comment with fresh evidence while it
# persists, and auto-close it when the pool recovers. Without this, an
# offline box is only discovered the next time a publish silently stalls.
runner-alert:
name: omni-build runner offline alert
if: >-
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') &&
vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' &&
(github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
issues: write
steps:
- name: Open/update/close the tracking issue
env:
# Issue writes use GITHUB_TOKEN (issues: write); only the runner listing
# needs RUNNER_STATUS_TOKEN (see runner-preflight). Without it the check is
# skipped with a warning instead of opening/closing the issue on bad data.
GH_TOKEN: ${{ github.token }}
RUNNERS_TOKEN: ${{ secrets.RUNNER_STATUS_TOKEN || github.token }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
TITLE="Docker publish runner offline: no online omni-build runner"
if ! ONLINE=$(GH_TOKEN="$RUNNERS_TOKEN" gh api "repos/${GITHUB_REPOSITORY}/actions/runners" \
--paginate --jq '[.runners[] | select(.status == "online") | select(any(.labels[]; .name == "omni-build"))] | length'); then
echo "::warning::Could not list self-hosted runners (token lacks Administration read — set the RUNNER_STATUS_TOKEN secret). Alert skipped."
exit 0
fi
echo "online omni-build runners: ${ONLINE}"
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title ${TITLE}" --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ "${ONLINE}" -eq 0 ]; then
{
echo "No **online** runner carries the \`omni-build\` label (\`GET /repos/{owner}/{repo}/actions/runners\`)."
echo ""
echo "While this persists, every Docker publish with \`USE_VPS_RUNNER=true\` queues the amd64 build forever - the silent stall from #14560 (the runner-preflight job turns it into a red run at publish time; this issue is the standing signal between publishes)."
echo ""
echo "**Checked:** ${RUN_URL} at \`$(date -u +%Y-%m-%dT%H:%M:%SZ)\`"
echo ""
echo "_Auto-managed by the Publish to Docker Hub schedule - closes itself when a runner comes back online._"
} > issue-body.md
if [ -n "$EXISTING" ]; then
gh issue comment "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file issue-body.md
echo "Updated existing issue #$EXISTING"
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --body-file issue-body.md
echo "Created tracking issue"
fi
elif [ -n "$EXISTING" ]; then
gh issue close "$EXISTING" --repo "$GITHUB_REPOSITORY" --reason completed \
--comment "OK: ${ONLINE} online \`omni-build\` runner(s) - pool recovered. Auto-closed."
echo "Closed issue #$EXISTING"
else
echo "Pool healthy (${ONLINE} online), nothing to do"
fi

View File

@@ -4,183 +4,48 @@ on:
push:
tags:
- "v*"
# A dispatch builds the ref it is dispatched ON (`gh workflow run … --ref v3.8.50` rebuilds
# that tag; `--ref main` builds the repaired line). The ref is deliberately NOT an input:
# CodeQL flags an input-controlled checkout next to the npm cache on the default branch as
# cache poisoning (actions/cache-poisoning/poisonable-step), and `github.ref` is trusted.
workflow_dispatch:
inputs:
version:
description: "Release version (e.g., v1.6.8)"
required: true
type: string
publish_npm:
description: "Also run the npm publish leg (turn off when re-attaching desktop assets to a release whose npm package already shipped)"
required: false
default: true
type: boolean
# Least-privilege default: read-only at the top level; each job grants the writes it
# needs (build/release upload assets, publish-npm forwards npm provenance / packages
# to the reusable workflow) — Scorecard TokenPermissions.
permissions:
contents: read
contents: write
jobs:
validate:
name: Validate version
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
version: ${{ steps.validate.outputs.version }}
steps:
- name: Checkout code
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
persist-credentials: false
fetch-depth: 0
- name: Validate version format
id: validate
env:
# Pass workflow context via env (never interpolate ${{ ... }} straight
# into the run: script body) so the shell receives variables, not
# inlined text — zizmor template-injection mitigation. INPUT_VERSION is
# the operator-supplied value and is regex-validated below before use.
EVENT_NAME: ${{ github.event_name }}
INPUT_VERSION: ${{ inputs.version }}
run: |
if [[ "$EVENT_NAME" == "push" ]]; then
if [[ "${{ github.event_name }}" == "push" ]]; then
VERSION="${GITHUB_REF#refs/tags/}"
else
VERSION="$INPUT_VERSION"
VERSION="${{ inputs.version }}"
fi
if [[ ! "$VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Error: Invalid version format. Expected: v1.6.8"
exit 1
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "✓ Valid version: $VERSION"
web-build:
name: Build shared Next standalone
needs: validate
# Stage 8 (issue #10321): the four desktop legs used to each run the full
# `npm run build` (Next standalone) — ~111 runner-minutes per release just to
# produce the same platform-independent bundle four times. This job builds it
# once on ubuntu; every leg then restores the byte-verified archive and
# re-forks its native optionals (scripts/build/standaloneBundle.mjs).
#
# Rollback lever: set the repo variable ELECTRON_SHARED_STANDALONE=disabled.
# This job then skips, every leg falls back to building its own web bundle
# (the legacy step below), and the pipeline behaves exactly like pre-Stage 8 —
# no revert needed.
if: ${{ !cancelled() && needs.validate.result == 'success' && vars.ELECTRON_SHARED_STANDALONE != 'disabled' }}
runs-on: ubuntu-latest
permissions:
contents: read
actions: read # find + download the CI run's next-build artifact for this SHA (as npm-publish does)
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: 24
- name: Install dependencies
run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
NPM_CONFIG_LEGACY_PEER_DEPS: true
# The Next standalone is platform-independent, and `ci.yml` already built it for this
# exact commit on the omni-build runner (the `next-build` artifact every `main` push
# produces — the release squash included). Reusing it is what `npm-publish.yml` does
# (#8941): the hosted build below needs 18–20 GB and this runner has 16, which is why
# the legacy per-leg fallback cost 53 min on macOS-intel and 4h41 on macOS arm64 for
# v3.8.52. Only runs of THIS repository's CI are candidates (artifact-poisoning guard,
# as in npm-publish); a missing/expired artifact falls back to the full build.
- name: Reuse CI's next-build artifact for this commit
id: reuse
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HEAD_SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
run: |
set -uo pipefail
CANDIDATES=$(gh api "repos/$REPO/actions/runs?head_sha=$HEAD_SHA&per_page=100" \
--jq '[.workflow_runs[]
| select(.name == "CI"
and .head_repository.full_name == env.REPO)]
| sort_by(.run_started_at) | reverse | .[0:5] | .[].id') || CANDIDATES=""
if [ -z "$CANDIDATES" ]; then
echo "::notice::no CI run from this repository for $HEAD_SHA — building the standalone here"
exit 0
fi
for candidate in $CANDIDATES; do
if gh run download "$candidate" --repo "$REPO" --name next-build --dir "$RUNNER_TEMP/next-build" 2>/dev/null; then
tar -xzf "$RUNNER_TEMP/next-build/e2e-build.tar.gz" -C .
rm -rf "$RUNNER_TEMP/next-build"
if [ -f .build/next/standalone/server.js ]; then
echo "reused=true" >> "$GITHUB_OUTPUT"
echo "✓ reused next-build from CI run $candidate"
exit 0
fi
echo " run $candidate unpacked without .build/next/standalone/server.js — trying the next"
rm -rf .build/next
else
echo " run $candidate carries no usable next-build — trying the next"
fi
done
echo "::notice::none of the candidate runs still carries next-build (1-day retention) — building the standalone here"
- name: Build Next.js standalone (fallback when no CI artifact)
if: steps.reuse.outputs.reused != 'true'
# webpack, not Turbopack, for the same hosted-runner RAM reason as the
# linux leg (see the long comment on the fallback step in `build`).
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
NODE_OPTIONS: "--max_old_space_size=6144"
OMNIROUTE_USE_TURBOPACK: "0"
run: npm run build
- name: Pack standalone bundle
# Deterministic tar.gz + byte-level manifest; the manifest embeds the
# archive's own sha256 so artifact-transfer corruption is caught before
# extraction, and every entry is re-verified after extraction.
run: node scripts/build/standaloneBundle.mjs pack --out web-bundle.tar.gz
- name: Upload shared web bundle
uses: actions/upload-artifact@v7
with:
name: web-standalone-bundle
# compression-level 0: the payload is already a deterministic tar.gz;
# re-zipping would only burn runner CPU without shrinking it further.
compression-level: 0
# Legs consume this within minutes; no reason to retain it like the
# installer artifacts (default 90d).
retention-days: 3
path: |
web-bundle.tar.gz
web-bundle.tar.gz.manifest.json
build:
name: Build Electron (${{ matrix.platform }})
needs: [validate, web-build]
# `web-build` is skipped when ELECTRON_SHARED_STANDALONE=disabled (rollback
# mode); legs then run the legacy per-leg web build below. If it ran and
# failed, fail closed: legs cannot package without the bundle, and silently
# falling back to four per-leg builds would hide exactly the regression the
# shared job exists to surface.
if: ${{ !cancelled() && needs.validate.result == 'success' && (needs.web-build.result == 'success' || needs.web-build.result == 'skipped') }}
needs: validate
runs-on: ${{ matrix.runner }}
permissions:
contents: write # electron-builder may publish artifacts with GH_TOKEN
strategy:
fail-fast: false
matrix:
@@ -189,125 +54,50 @@ jobs:
runner: windows-latest
target: win
ext: .exe
os: win32
arch: x64
- platform: macos-intel
runner: macos-15-intel
target: mac-x64
ext: .dmg
os: darwin
arch: x64
- platform: macos-arm64
runner: macos-latest
target: mac-arm64
ext: -arm64.dmg
os: darwin
arch: arm64
- platform: linux
runner: ubuntu-latest
target: linux
ext: .AppImage
deb_ext: .deb
os: linux
arch: x64,arm64
steps:
- uses: actions/checkout@v7
- name: Checkout
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v6
with:
persist-credentials: false
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: 24
node-version: 22
cache: npm
- name: Cache node_modules
uses: actions/cache@v5
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install dependencies
run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
NPM_CONFIG_LEGACY_PEER_DEPS: true
# The Linux leg produces x64 + arm64 installers from one x64 runner. npm
# deliberately installs only host-compatible optional dependencies, so
# hydrateNativeDeps cannot source the arm64 fork unless we fetch the exact
# package pinned in package-lock before either build path runs.
- name: Install Linux arm64 wreq binding for cross-package
if: matrix.platform == 'linux'
shell: bash
run: |
npm install --no-save --ignore-scripts --force --legacy-peer-deps \
@wreq-js/binding-linux-arm64-gnu@3.2.0
git diff --exit-code -- package.json package-lock.json
mkdir -p "$RUNNER_TEMP/omniroute-wreq-verify"
DATA_DIR="$RUNNER_TEMP/omniroute-wreq-verify" node --import tsx/esm --test \
--test-name-pattern='wreq-js 3.2 manifest pins all nine' \
tests/unit/wreq-native-manifest.test.ts
- name: Sanitize Windows home directory
if: runner.os == 'Windows'
shell: bash
run: |
# The default USERPROFILE contains junction points (Application Data)
# that cause EPERM errors during Next.js standalone build glob scans.
# Create a clean temp profile directory to avoid this.
mkdir -p "$RUNNER_TEMP/home"
echo "USERPROFILE=$RUNNER_TEMP/home" >> "$GITHUB_ENV"
- name: Build Next.js standalone (legacy per-leg fallback)
# Stage 8: only runs in rollback mode (ELECTRON_SHARED_STANDALONE=disabled)
# or when the shared web-build job was skipped. Otherwise the leg restores
# the shared bundle from the `web-build` job below.
if: needs.web-build.result == 'skipped'
- name: Build Next.js standalone
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
NODE_OPTIONS: "--max_old_space_size=6144"
# Linux builds with webpack, not Turbopack. Turbopack's production build
# allocates natively (Rust, off the V8 heap), so --max_old_space_size does
# not bound it, and on this module graph it peaks above what the hosted
# runner can give — the VM is reclaimed mid-compile with "The runner has
# received a shutdown signal", no exit code. That is what silently took the
# whole desktop channel out of v3.8.49: the linux leg died, `release` was
# skipped, and the release shipped with ZERO assets. Measured on a 32 GB
# box the same build passes and peaks past 14 GB. The webpack fallback is
# the project's documented escape hatch for RAM-constrained machines
# (docs/reference/ENVIRONMENT.md, #6409) and is the same remedy already
# applied to nightly-compat's Node 26 build (#8090).
OMNIROUTE_USE_TURBOPACK: ${{ matrix.platform == 'linux' && '0' || '1' }}
run: npm run build
- name: Download shared web bundle
# Stage 8: inverse of the fallback step above — runs exactly when the
# shared `web-build` job produced the bundle.
if: needs.web-build.result == 'success'
uses: actions/download-artifact@v8
with:
name: web-standalone-bundle
- name: Restore + hydrate shared web bundle
if: needs.web-build.result == 'success'
shell: bash
# restore: verify the archive's sha256 against the manifest, extract, then
# re-verify every entry (existence + size + content hash + symlink
# targets, and no unlisted files) byte-for-byte.
# hydrate: the bundle was built on ubuntu, so install-machine-forked native
# optionals (@img/sharp-*, @img/sharp-libvips-*, @ngrok/ngrok-*,
# @wreq-js/binding-*, fsevents) carry linux forks. Replace them with the forks this
# leg's own `npm ci` resolved, then assert every bundled native
# (better-sqlite3 prebuilds, wreq-js, onnxruntime)
# can service this leg's platform/arch before packaging starts.
run: |
node scripts/build/standaloneBundle.mjs restore --archive web-bundle.tar.gz
node scripts/build/standaloneBundle.mjs hydrate --platform ${{ matrix.os }} --arch ${{ matrix.arch }}
- name: Sync version in electron/package.json
shell: bash
env:
# Pass the validated version via env (never interpolate ${{ ... }}
# straight into the run: script body) — zizmor template-injection
# mitigation. Already regex-validated (^v[0-9]+\.[0-9]+\.[0-9]+$) in
# the `validate` job, so it cannot carry shell metacharacters.
VERSION: ${{ needs.validate.outputs.version }}
run: |
VERSION="${{ needs.validate.outputs.version }}"
VERSION_NO_V="${VERSION#v}"
node -e "
const fs = require('fs');
@@ -323,7 +113,7 @@ jobs:
- name: Install Electron dependencies
working-directory: electron
run: npm ci --no-audit --no-fund
run: npm install --no-audit --no-fund
- name: Build Electron for ${{ matrix.platform }}
working-directory: electron
@@ -331,35 +121,6 @@ jobs:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: npm run build:${{ matrix.target }}
- name: Smoke packaged Electron app
if: matrix.platform != 'linux'
# Best-effort smoke on Windows + macos-arm64:
# - Windows: requestSingleInstanceLock() fails due to USERPROFILE
# sanitization needed for the build step.
# - macos-arm64: the headless GitHub arm64 runner crashes Electron's GPU
# process (gpu_process_host exit_code=15 → network service crash →
# "No rendezvous client, terminating process"), so the app can't bind
# 127.0.0.1:20128 in time. The identical bundle is smoke-gated on
# macos-intel + linux, so packaging is still verified per-OS; we don't
# let the arm64 runner's GPU flakiness block the desktop release.
continue-on-error: ${{ matrix.platform == 'windows' || matrix.platform == 'macos-arm64' }}
env:
ELECTRON_SMOKE_TIMEOUT_MS: 60000
ELECTRON_SMOKE_STREAM_LOGS: "1"
run: npm run electron:smoke:packaged
- name: Smoke packaged Electron app (Linux)
if: matrix.platform == 'linux'
# #7592: also cold-restart against the same DATA_DIR and assert a
# native SQLite driver (not the sql.js WASM fallback) is selected on
# the second launch — blocking here since Linux has no Windows-style
# sandbox caveats that would make it flaky.
env:
ELECTRON_SMOKE_TIMEOUT_MS: 60000
ELECTRON_SMOKE_STREAM_LOGS: "1"
ELECTRON_SMOKE_COLD_RESTART: "1"
run: xvfb-run -a npm run electron:smoke:packaged
- name: Collect installers
shell: bash
run: |
@@ -383,18 +144,6 @@ jobs:
[ -f "$file" ] && cp "$file" "../../release-assets/OmniRoute.exe" && break
done
fi
# electron-updater manifests (latest.yml / latest-mac.yml / latest-linux.yml)
# must be published alongside the installers, or autoUpdater fails with
# "Cannot find latest.yml in the latest release artifacts" (#6766).
for file in latest*.yml; do
[ -f "$file" ] && cp "$file" ../../release-assets/
done
# Publish exactly the content-addressed packs named by this build.
cd ../..
node scripts/release/collect-optional-packs.mjs \
.build/electron-standalone/optional-packs.index.json \
.build/optional-packs release-assets
- name: Upload artifacts
uses: actions/upload-artifact@v7
@@ -405,69 +154,28 @@ jobs:
release:
name: Create Release
needs: [validate, build]
# Fail-partial, not fail-closed. `build` is a 4-leg matrix with `fail-fast: false`,
# so the legs that succeed still upload their artifacts — but a default `needs:`
# gate skips this job the moment ANY leg fails, discarding all of them. That is
# exactly what happened to v3.8.49: the linux leg died and the release shipped with
# ZERO assets, throwing away 1.7 GB of good Windows/macOS installers **and** the
# source archives + SBOM, which do not depend on a build at all. The result was
# indistinguishable from "this version has no desktop channel".
# Now: attach everything that did build, then fail the job loudly (see the last
# step) so an incomplete channel is visible instead of silent.
if: ${{ !cancelled() && needs.validate.result == 'success' }}
runs-on: ubuntu-latest
permissions:
contents: write # softprops/action-gh-release creates the GitHub Release
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
persist-credentials: false
fetch-depth: 0
# `merge-multiple` is deliberately OFF. It resolves same-name collisions by ARRIVAL
# ORDER, and the two macOS jobs each emit their own `latest-mac.yml` listing only their
# own dmg (measured: 338 and 350 bytes, different content, identical name). One silently
# overwrote the other — arm64 won in the published v3.8.48, and since the Intel dmg
# carries no arch suffix in its name, electron-updater's
# `files.find(url includes process.arch) ?? files.shift()` sends every Intel Mac to the
# ARM dmg. Downloading into per-artifact subdirectories keeps both, so they can be
# merged on purpose instead of by luck.
- name: Download all artifacts
uses: actions/download-artifact@v8
with:
path: artifacts
# Writes release-assets/latest-mac.yml with BOTH dmgs, un-suffixed entry first (that is
# the one electron-updater can only reach through its fallback). Refuses to write when the
# inputs disagree on version — a manifest stitched from two builds is worse than none.
- name: Merge the per-arch macOS updater manifests
run: node scripts/release/merge-mac-update-manifest.mjs artifacts release-assets
# Everything else moves across as-is. The partial latest-mac.yml files are excluded so
# they cannot clobber the merged one; -n is a second belt on the same braces.
- name: Collect the remaining artifacts
run: |
mkdir -p release-assets
find artifacts -type f ! -name latest-mac.yml -exec cp -n {} release-assets/ \;
echo "release-assets:"
ls -la release-assets/
path: release-assets
merge-multiple: true
- name: Create source archives
env:
# Pass the validated version via env (never interpolate ${{ ... }}
# straight into the run: script body) — zizmor template-injection
# mitigation. Already regex-validated (^v[0-9]+\.[0-9]+\.[0-9]+$) in
# the `validate` job, so it cannot carry shell metacharacters.
VERSION: ${{ needs.validate.outputs.version }}
run: |
# Create source code archives (excluding dev dependencies and build artifacts)
export TARBALL="OmniRoute-${VERSION}.source.tar.gz"
export ZIPBALL="OmniRoute-${VERSION}.source.zip"
export TARBALL="OmniRoute-${{ needs.validate.outputs.version }}.source.tar.gz"
export ZIPBALL="OmniRoute-${{ needs.validate.outputs.version }}.source.zip"
# Use git archive for clean source export
git archive --format=tar.gz --prefix="OmniRoute-${VERSION}/" HEAD -o "release-assets/$TARBALL"
git archive --format=zip --prefix="OmniRoute-${VERSION}/" HEAD -o "release-assets/$ZIPBALL"
git archive --format=tar.gz --prefix=OmniRoute-${{ needs.validate.outputs.version }}/ HEAD -o "release-assets/$TARBALL"
git archive --format=zip --prefix=OmniRoute-${{ needs.validate.outputs.version }}/ HEAD -o "release-assets/$ZIPBALL"
echo "✓ Created source archives:"
ls -lh "release-assets/$TARBALL" "release-assets/$ZIPBALL"
@@ -476,19 +184,12 @@ jobs:
run: ls -la release-assets/
- name: Create Release
uses: softprops/action-gh-release@v3
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.validate.outputs.version }}
draft: false
prerelease: false
# NEVER. Phase 3 of the release flow creates the GitHub Release with the curated
# notes seconds after pushing the tag, so by the time this step runs (1-2 h of
# builds later) the body already exists — and `true` APPENDS GitHub's
# auto-generated "What's Changed" block to it (v3.8.48 shipped that way; the
# v3.8.50 re-attach dispatch added +1,416 chars to a 121 KB body, run
# 33238093090). A curated body sits ~3 KB under the 125,000-char cap, so the
# append can also turn this step RED and leave the release with no assets.
generate_release_notes: false
generate_release_notes: true
fail_on_unmatched_files: false
files: |
release-assets/*.dmg
@@ -496,74 +197,14 @@ jobs:
release-assets/*.AppImage
release-assets/*.deb
release-assets/*.blockmap
release-assets/*.yml
release-assets/optional-pack-*.tar.gz
release-assets/*.source.tar.gz
release-assets/*.source.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
verify-desktop-assets:
name: Verify desktop assets landed
needs: [validate, release]
# Deliberately a SEPARATE job, not a final step of `release`: failing inside
# `release` would cascade into `publish-npm` (which gates on `needs: release`) and
# block the npm channel over a desktop-only gap. Here the assets are attached, npm
# still publishes, and an incomplete desktop channel shows up as a red job instead
# of passing unnoticed — the v3.8.49 release had ZERO assets and every gate was
# green, because nothing ever asserted the release HAS binaries.
if: ${{ !cancelled() && needs.release.result == 'success' }}
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Assert every platform is present on the release
env:
# Regex-validated (^v[0-9]+\.[0-9]+\.[0-9]+$) in the `validate` job, and
# passed via env rather than interpolated into the script body.
VERSION: ${{ needs.validate.outputs.version }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
names=$(gh release view "$VERSION" --repo "$GITHUB_REPOSITORY" \
--json assets --jq '.assets[].name')
echo "Assets on $VERSION:"
echo "$names" | sed 's/^/ /'
missing=""
# `[ ... ] && missing=...` as the last command in a branch returns 1 and
# would abort the whole script under Actions' default `set -e`. Use if/fi.
for want in '\.exe$' '\.dmg$' '\.AppImage$' '\.deb$' '^latest.*\.yml$' '\.source\.tar\.gz$'; do
if ! echo "$names" | grep -qE "$want"; then
missing="$missing $want"
fi
done
if [ -n "$missing" ]; then
echo "::error::Desktop channel incomplete on $VERSION — no asset matching:$missing"
exit 1
fi
echo "✓ every platform present on $VERSION"
publish-npm:
name: Publish to npm
needs: [validate, release]
# A re-dispatch that only re-attaches desktop assets must not publish the npm package again.
if: ${{ github.event_name != 'workflow_dispatch' || inputs.publish_npm }}
permissions:
# Must be `write`, not `read`: this job calls the reusable npm-publish.yml whose
# `publish` job needs `contents: write` (gh release upload — attach the SBOM, #3874).
# A reusable workflow's job cannot request more permission than the caller grants,
# so a `read` here makes GitHub reject the run at startup (startup_failure).
#
# `actions: read` for the same reason: the called `publish` job downloads the next-build
# artefact and requests it. v3.8.50 (run 33005490476) died at startup with "The nested
# job 'publish' is requesting 'actions: read', but is only allowed 'actions: none'" — and
# because `release` lives in this same workflow, the tag shipped with ZERO assets. Keep
# this block a superset of every job's permissions in npm-publish.yml.
actions: read
contents: write
id-token: write # npm provenance (forwarded to the reusable workflow)
packages: write # publish to npm.pkg.github.com
uses: ./.github/workflows/npm-publish.yml
with:
version: ${{ needs.validate.outputs.version }}

View File

@@ -1,156 +0,0 @@
name: Forward-port stable/v3 → develop (dormant)
# DORMANT until the 3.9.0 LTS cut creates `stable/v3` and `develop`
# (docs/ops/RELEASE_STRATEGY.md → "Forward-port"). The push filter and the job
# `if:` both pin it to `refs/heads/stable/v3`, and the job exits quietly while
# `develop` does not exist.
#
# Every commit pushed to stable/v3 is cherry-picked (`-x`) onto a fresh
# `forward-port/<sha7>` branch cut from develop, and a PR is opened against
# develop. The original author stays the commit author and is also credited with
# a `Co-authored-by:` trailer, so the credit survives a squash-merge of the
# forward-port PR. A conflicting cherry-pick still opens a PR — as a DRAFT with
# the exact commands to finish it by hand.
#
# PRs opened with the default GITHUB_TOKEN do not trigger other workflows; set the
# `FORWARD_PORT_TOKEN` secret (fine-grained PAT or App token with contents +
# pull-requests write) before go-live so CI runs on the forward-port PRs.
on:
push:
branches: [stable/v3]
workflow_dispatch:
inputs:
sha:
description: "Commit on stable/v3 to forward-port (full or short SHA)"
required: true
type: string
permissions:
contents: read
concurrency:
group: forward-port
cancel-in-progress: false
jobs:
forward-port:
name: Cherry-pick onto develop
if: github.ref == 'refs/heads/stable/v3' && github.repository == 'cheaper-inference/OmniRoute'
runs-on: ubuntu-latest
permissions:
contents: write # push forward-port/<sha7>
pull-requests: write # open the PR against develop
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Check that develop exists
id: develop
run: |
set -euo pipefail
if [ -n "$(git ls-remote --heads origin develop)" ]; then
echo "exists=true" >> "$GITHUB_OUTPUT"
else
echo "exists=false" >> "$GITHUB_OUTPUT"
echo "develop does not exist yet — forward-port is dormant, nothing to do."
fi
- name: Resolve commits to forward-port
id: commits
if: steps.develop.outputs.exists == 'true'
env:
EVENT_NAME: ${{ github.event_name }}
BEFORE: ${{ github.event.before }}
AFTER: ${{ github.sha }}
INPUT_SHA: ${{ inputs.sha }}
run: |
set -euo pipefail
if [ "$EVENT_NAME" = "workflow_dispatch" ]; then
if ! printf '%s' "$INPUT_SHA" | grep -qE '^[0-9a-fA-F]{7,40}$'; then
echo "Refusing non-SHA input: $INPUT_SHA" >&2
exit 1
fi
TARGET=$(git rev-parse --verify "${INPUT_SHA}^{commit}")
git merge-base --is-ancestor "$TARGET" origin/stable/v3 \
|| { echo "$TARGET is not on stable/v3" >&2; exit 1; }
RANGE="${TARGET}^..${TARGET}"
elif printf '%s' "$BEFORE" | grep -qE '^0+$' || [ -z "$BEFORE" ]; then
RANGE="${AFTER}^..${AFTER}"
else
RANGE="${BEFORE}..${AFTER}"
fi
git rev-list --reverse --no-merges "$RANGE" > commits.txt
echo "count=$(wc -l < commits.txt | tr -d ' ')" >> "$GITHUB_OUTPUT"
echo "Commits to forward-port:"; cat commits.txt
- name: Cherry-pick and open PRs
if: steps.develop.outputs.exists == 'true' && steps.commits.outputs.count != '0'
env:
GH_TOKEN: ${{ secrets.FORWARD_PORT_TOKEN || github.token }}
REPO: ${{ github.repository }}
STRATEGY_URL: ${{ github.server_url }}/${{ github.repository }}/blob/develop/docs/ops/RELEASE_STRATEGY.md
run: |
set -euo pipefail
gh auth setup-git
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
while read -r SHA; do
SHORT="${SHA:0:7}"
BRANCH="forward-port/${SHORT}"
if [ -n "$(git ls-remote --heads origin "$BRANCH")" ]; then
echo "$BRANCH already exists — skipping $SHORT."
continue
fi
SUBJECT=$(git log -1 --format=%s "$SHA")
AUTHOR=$(git log -1 --format='%an <%ae>' "$SHA")
git checkout --quiet -B "$BRANCH" origin/develop
DRAFT=""
if git cherry-pick -x "$SHA"; then
# Keep the original author (cherry-pick already does) AND add the trailer,
# so a squash-merge of this PR still credits them.
git log -1 --format=%B > msg.txt
git interpret-trailers --in-place --if-exists addIfDifferent \
--trailer "Co-authored-by: ${AUTHOR}" msg.txt
git commit --amend --quiet --file msg.txt
BODY_STATE="Clean cherry-pick (\`git cherry-pick -x\`) of ${SHA} from \`stable/v3\`."
else
git cherry-pick --abort
DRAFT="--draft"
printf 'chore(forward-port): %s needs a manual cherry-pick\n\nCherry-pick of %s from stable/v3 conflicted on develop.\n\nCo-authored-by: %s\n' \
"$SHORT" "$SHA" "$AUTHOR" > msg.txt
git commit --allow-empty --quiet --file msg.txt
BODY_STATE=$(printf '%s\n\n%s\n\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n' \
"⚠️ **The cherry-pick of ${SHA} conflicted on \`develop\`** — this draft holds an empty placeholder commit." \
"To finish it:" \
'```bash' \
"git fetch origin" \
"git switch ${BRANCH}" \
"git cherry-pick -x ${SHA} # resolve the conflicts, then: git cherry-pick --continue" \
"git commit --amend # keep the trailer: Co-authored-by: ${AUTHOR}" \
"git push origin ${BRANCH}" \
'```')
fi
git push --quiet origin "HEAD:refs/heads/${BRANCH}"
{
echo "Automatic forward-port of \`stable/v3\` → \`develop\`."
echo
echo "$BODY_STATE"
echo
echo "Original author: ${AUTHOR}"
echo
echo "Policy: ${STRATEGY_URL}"
} > body.md
# shellcheck disable=SC2086 # DRAFT is intentionally empty or one flag
gh pr create --repo "$REPO" --base develop --head "$BRANCH" $DRAFT \
--title "${SUBJECT} (forward-port ${SHORT})" \
--body-file body.md \
--label forward-port
done < commits.txt

View File

@@ -1,334 +0,0 @@
name: i18n mirror refresh
# Post-merge refresh of the translated docs mirrors (docs/i18n/<locale>/…). Since #18420 the
# docs drift gate is advisory on PRs and the merge train, so drifted mirrors pile up on the
# release branch until somebody runs `npm run i18n:run` by hand. This workflow does that run
# on a schedule and turns the result into ONE pull request:
#
# 1. target = the highest release/v* branch (or the `base` input); skipped with a notice while
# an open `release-freeze` issue names that branch (Hard Rule #21);
# 2. drifted sources = `check-translation-drift.mjs --json --warn` (drifted, missing,
# hand-edited and stale mirrors);
# 3. translate them: the LLM chain first when the backend secrets are configured (model, then
# OMNIROUTE_TRANSLATION_FALLBACK_MODELS, then a re-split, then Google as the last resort),
# otherwise the structure-safe Google engine alone;
# 4. `npm run check:docs-all` + the drift check must both pass; then the mirrors are committed
# to the fixed branch `chore/i18n-mirror-refresh` (force-reset from the target every run)
# and one PR is opened, or the open one is updated by the force-push;
# 5. a partial translation (run-translation exit 3: some (source, locale) units failed, the
# rest translated) still opens the PR with the translated mirrors. The failed units keep
# their mirror and state record, the drift check excuses exactly those units, and the PR
# body lists them for the next run (#18538);
# 6. a run where nothing translated, any other translation error, or any other check failure
# opens NO PR and fails the job with a step summary that lists the failing files / locales.
#
# PRs opened with the default GITHUB_TOKEN do not trigger other workflows (no CI on the refresh
# PR). Set the `I18N_REFRESH_TOKEN` secret (fine-grained PAT or App token with contents +
# pull-requests write) so CI runs on it, the same pattern as FORWARD_PORT_TOKEN in
# forward-port.yml. With GITHUB_TOKEN the repo setting "Allow GitHub Actions to create and
# approve pull requests" must be on for `gh pr create` to work.
#
# Operator configuration (all optional; without the LLM ones the Google engine is used):
# secrets.OMNIROUTE_TRANSLATION_API_KEY LLM backend bearer token
# secrets/vars.OMNIROUTE_TRANSLATION_API_URL OpenAI-compatible base URL (…/v1)
# vars.OMNIROUTE_TRANSLATION_MODEL first model of the chain
# vars.OMNIROUTE_TRANSLATION_FALLBACK_MODELS comma-separated fallback chain
# secrets.OMNIROUTE_TRANSLATION_GOOGLE_API_KEY official Cloud Translation v2 instead of the
# keyless web endpoint
# secrets.I18N_REFRESH_TOKEN token that opens the PR (see above)
#
# Secrets only ever reach the scripts through `env:`; no `${{ }}` expression is interpolated into
# a `run:` script.
on:
schedule:
- cron: "23 */6 * * *"
workflow_dispatch:
inputs:
base:
description: "Branch to refresh (default: the highest release/v* branch)"
required: false
type: string
permissions:
contents: read
concurrency:
group: i18n-mirror-refresh
cancel-in-progress: false
jobs:
refresh:
name: Refresh drifted docs mirrors
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
timeout-minutes: 330
permissions:
contents: write # push chore/i18n-mirror-refresh
pull-requests: write # open / retarget the refresh PR
env:
REFRESH_BRANCH: chore/i18n-mirror-refresh
PR_TITLE: "docs(i18n): refresh drifted mirrors (scheduled)"
steps:
- name: Resolve the target branch and the release freeze
id: target
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
INPUT_BASE: ${{ inputs.base }}
run: |
set -euo pipefail
if [ -n "${INPUT_BASE:-}" ]; then
if ! printf '%s' "$INPUT_BASE" | grep -qE '^[A-Za-z0-9._/-]+$'; then
echo "::error::refusing base input with unexpected characters" >&2
exit 1
fi
BASE="$INPUT_BASE"
else
BASE=$(gh api --paginate "repos/$REPO/git/matching-refs/heads/release/v" --jq '.[].ref' \
| sed 's#^refs/heads/##' | grep -E '^release/v[0-9]+\.[0-9]+\.[0-9]+$' \
| sort -V | tail -1)
fi
if [ -z "$BASE" ]; then
echo "::error::could not resolve the target branch" >&2
exit 1
fi
echo "base=$BASE" >> "$GITHUB_OUTPUT"
# Hard Rule #21: never refresh a frozen release branch. A freeze issue is titled
# "🔒 release-freeze: vX.Y.Z in progress"; one that names no version freezes everything.
VER="${BASE#release/}"
VER_RE=$(printf '%s' "$VER" | sed 's/\./\\./g')
FROZEN=""
while IFS=$'\t' read -r NUM TITLE; do
[ -n "$NUM" ] || continue
if printf '%s' "$TITLE" | grep -qE "(^|[^0-9.])${VER_RE}([^0-9]|$)" \
|| ! printf '%s' "$TITLE" | grep -qE 'v[0-9]+\.[0-9]+\.[0-9]+'; then
FROZEN="#$NUM"
fi
done < <(gh issue list --repo "$REPO" --label release-freeze --state open \
--json number,title --jq '.[] | "\(.number)\t\(.title)"')
if [ -n "$FROZEN" ]; then
echo "::notice::$BASE is under release-freeze ($FROZEN) — skipping the mirror refresh."
echo "Skipped: \`$BASE\` is under release-freeze ($FROZEN)." >> "$GITHUB_STEP_SUMMARY"
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "skip=false" >> "$GITHUB_OUTPUT"
echo "Target branch: \`$BASE\`" >> "$GITHUB_STEP_SUMMARY"
fi
- name: Checkout the target branch
if: steps.target.outputs.skip == 'false'
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ steps.target.outputs.base }}
fetch-depth: 1
persist-credentials: false
- name: Find the drifted sources
id: drift
if: steps.target.outputs.skip == 'false'
run: |
set -euo pipefail
node scripts/i18n/check-translation-drift.mjs --json --warn > "$RUNNER_TEMP/drift-before.json"
# every source with a drifted / missing / hand-edited / stale mirror, as repo-relative paths
FILES=$(DRIFT_JSON="$RUNNER_TEMP/drift-before.json" node -e '
const r = JSON.parse(require("fs").readFileSync(process.env.DRIFT_JSON, "utf8"));
const keys = ["driftedSources", "missingTargets", "driftedTargets", "staleTargets"];
const rels = keys.flatMap((k) => r[k] ?? [])
.map((x) => x.rel).filter(Boolean);
process.stdout.write([...new Set(rels)].sort().join(","));
')
if [ -z "$FILES" ]; then
echo "No drifted mirrors — nothing to refresh." >> "$GITHUB_STEP_SUMMARY"
echo "files=" >> "$GITHUB_OUTPUT"
else
echo "Drifted sources: \`${FILES//,/\`, \`}\`" >> "$GITHUB_STEP_SUMMARY"
echo "files=$FILES" >> "$GITHUB_OUTPUT"
fi
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
if: steps.drift.outputs.files != ''
with:
package-manager-cache: false
node-version: "24"
- uses: ./.github/actions/npm-ci-retry
if: steps.drift.outputs.files != ''
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Translate the drifted mirrors
id: translate
if: steps.drift.outputs.files != ''
env:
FILES: ${{ steps.drift.outputs.files }}
OMNIROUTE_TRANSLATION_API_KEY: ${{ secrets.OMNIROUTE_TRANSLATION_API_KEY }}
OMNIROUTE_TRANSLATION_API_URL: ${{ secrets.OMNIROUTE_TRANSLATION_API_URL || vars.OMNIROUTE_TRANSLATION_API_URL }}
OMNIROUTE_TRANSLATION_MODEL: ${{ vars.OMNIROUTE_TRANSLATION_MODEL }}
OMNIROUTE_TRANSLATION_FALLBACK_MODELS: ${{ vars.OMNIROUTE_TRANSLATION_FALLBACK_MODELS }}
OMNIROUTE_TRANSLATION_GOOGLE_API_KEY: ${{ secrets.OMNIROUTE_TRANSLATION_GOOGLE_API_KEY }}
run: |
set -uo pipefail
if [ -n "$OMNIROUTE_TRANSLATION_API_KEY" ] && [ -n "$OMNIROUTE_TRANSLATION_API_URL" ] \
&& [ -n "$OMNIROUTE_TRANSLATION_MODEL" ]; then
ENGINE=llm
else
ENGINE=google
if [ -n "$OMNIROUTE_TRANSLATION_API_KEY" ] || [ -n "$OMNIROUTE_TRANSLATION_API_URL" ]; then
echo "::warning::LLM backend partially configured (API key, API URL and vars.OMNIROUTE_TRANSLATION_MODEL are all required) — using Google."
fi
fi
export OMNIROUTE_TRANSLATION_ENGINE="$ENGINE"
export OMNIROUTE_TRANSLATION_GOOGLE_FALLBACK=1
echo "engine=$ENGINE" >> "$GITHUB_OUTPUT"
echo "Engine: \`$ENGINE\`" >> "$GITHUB_STEP_SUMMARY"
# The default `bash -e` would end the step on a non-zero pipeline before RC is read, so
# catch the status here (pipefail makes it the translator's exit code).
RC=0
node scripts/i18n/run-translation.mjs --files="$FILES" \
--failures-json="$RUNNER_TEMP/translate-failures.json" 2>&1 \
| tee "$RUNNER_TEMP/translate.log" || RC=$?
if [ "$RC" -eq 3 ]; then
# Partial: the translated units are written and recorded, the failed ones are untouched.
echo "partial=true" >> "$GITHUB_OUTPUT"
{
echo "### Partial translation (exit 3): failed locales left as they were"
echo
echo '```'
grep -E '^ - .+ \[[^]]+\]: ' "$RUNNER_TEMP/translate.log" | head -100 || true
grep -E 'summary: translated=' "$RUNNER_TEMP/translate.log" | tail -1 || true
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
elif [ "$RC" -ne 0 ]; then
{
echo "### Translation failed (exit $RC) — no PR opened"
echo
echo '```'
grep -E '^ - .+ \[[^]]+\]: ' "$RUNNER_TEMP/translate.log" | head -100 || true
grep -E 'summary: translated=' "$RUNNER_TEMP/translate.log" | tail -1 || true
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
exit "$RC"
fi
- name: Check the refreshed mirrors
if: steps.drift.outputs.files != ''
run: |
set -uo pipefail
FAILED=0
npm run check:docs-all 2>&1 | tee "$RUNNER_TEMP/docs-all.log"
DOCS_RC=${PIPESTATUS[0]}
node scripts/i18n/check-translation-drift.mjs --json --warn > "$RUNNER_TEMP/drift-after.json"
# Drift left by the failed units of a partial run is excused; any other drift blocks.
if ! BLOCKING=$(DRIFT_JSON="$RUNNER_TEMP/drift-after.json" \
FAILURES_JSON="$RUNNER_TEMP/translate-failures.json" node --input-type=module -e '
import { existsSync, readFileSync } from "node:fs";
import { blockingDrift } from "./scripts/i18n/run-translation.mjs";
const read = (p) => JSON.parse(readFileSync(p, "utf8"));
const run = existsSync(process.env.FAILURES_JSON) ? read(process.env.FAILURES_JSON) : {};
const left = blockingDrift(read(process.env.DRIFT_JSON), run.failures ?? [], run.translatedUnits ?? []);
for (const x of left) console.log(x.kind + ": " + x.rel + (x.locale ? " [" + x.locale + "]" : ""));
'); then
echo "::error::could not evaluate the drift report"
exit 1
fi
if [ "$DOCS_RC" -ne 0 ]; then
FAILED=1
{
echo "### \`npm run check:docs-all\` failed (exit $DOCS_RC) — no PR opened"
echo
echo '```'
grep -E 'docs/i18n/|FAIL|✗|✖|ERROR' "$RUNNER_TEMP/docs-all.log" | head -100 || true
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
fi
if [ -n "$BLOCKING" ]; then
FAILED=1
{
echo "### Drift check still reports drift — no PR opened"
echo
echo '```'
printf '%s\n' "$BLOCKING" | head -100
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
fi
exit "$FAILED"
- name: Commit and open or update the refresh PR
if: steps.drift.outputs.files != ''
env:
GH_TOKEN: ${{ secrets.I18N_REFRESH_TOKEN || github.token }}
REPO: ${{ github.repository }}
BASE: ${{ steps.target.outputs.base }}
ENGINE: ${{ steps.translate.outputs.engine }}
PARTIAL: ${{ steps.translate.outputs.partial }}
FILES: ${{ steps.drift.outputs.files }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
git add -A docs/i18n .i18n-state.json
if git diff --cached --quiet; then
echo "Translation produced no change — nothing to commit." >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
COUNT=$(git diff --cached --name-only -- docs/i18n | wc -l | tr -d ' ')
FAILED_UNITS=""
if [ "${PARTIAL:-}" = "true" ]; then
FAILED_UNITS=$(FAILURES_JSON="$RUNNER_TEMP/translate-failures.json" node -e '
const r = JSON.parse(require("fs").readFileSync(process.env.FAILURES_JSON, "utf8"));
const one = (e) => String(e ?? "").replace(/\s+/g, " ").replace(/`/g, "\x27").slice(0, 200);
for (const f of r.failures) console.log("- `" + f.rel + "` [" + f.locale + "]: " + one(f.error));
')
fi
NOTE=""
[ -z "$FAILED_UNITS" ] || NOTE=" $(printf '%s\n' "$FAILED_UNITS" | wc -l | tr -d ' ') unit(s) failed and were left as they were."
# CI bot commit: the bot identity is the author, no Co-Authored-By trailer.
git -c user.name="github-actions[bot]" \
-c user.email="41898282+github-actions[bot]@users.noreply.github.com" \
commit --quiet -m "$PR_TITLE" \
-m "Engine: ${ENGINE}. Sources: ${FILES//,/, }. ${COUNT} mirror file(s).${NOTE}" \
-m "Run: ${RUN_URL}"
gh auth setup-git
# Fixed branch, reset from the target on every run: the open PR always shows exactly
# one refresh commit on top of the current target.
git push --force --quiet origin "HEAD:refs/heads/${REFRESH_BRANCH}"
{
echo "Automatic refresh of the translated docs mirrors, opened by the \`i18n-mirror-refresh\` workflow (${RUN_URL})."
echo
echo "- Target: \`${BASE}\`"
echo "- Engine: \`${ENGINE}\` (LLM chain first, Google as the last resort; \`google\` when no LLM backend is configured)"
echo "- Drifted sources: \`${FILES//,/\`, \`}\`"
echo "- Mirror files changed: ${COUNT}"
echo
echo "\`npm run check:docs-all\` and \`check-translation-drift.mjs\` passed on the refreshed tree before this PR was opened."
if [ -n "$FAILED_UNITS" ]; then
echo
echo "Partial run: these (source, locale) units failed to translate. Their mirrors and \`.i18n-state.json\` records are unchanged, so they still show as stale or drifted and the next run retries them. The drift check excused only these units:"
echo
printf '%s\n' "$FAILED_UNITS"
fi
echo
echo "The branch \`${REFRESH_BRANCH}\` is force-reset from the target on every run, so a later run replaces this commit."
echo "PRs opened with the default \`GITHUB_TOKEN\` do not trigger other workflows; set the \`I18N_REFRESH_TOKEN\` secret so CI runs here."
} > "$RUNNER_TEMP/pr-body.md"
PR=$(gh pr list --repo "$REPO" --head "$REFRESH_BRANCH" --state open \
--json number,baseRefName --jq '.[0] | select(.) | "\(.number) \(.baseRefName)"')
if [ -z "$PR" ]; then
URL=$(gh pr create --repo "$REPO" --base "$BASE" --head "$REFRESH_BRANCH" \
--title "$PR_TITLE" --body-file "$RUNNER_TEMP/pr-body.md")
echo "Opened $URL" >> "$GITHUB_STEP_SUMMARY"
else
NUM="${PR%% *}"
OLD_BASE="${PR#* }"
if [ "$OLD_BASE" != "$BASE" ]; then
gh pr edit "$NUM" --repo "$REPO" --base "$BASE"
NEW_BASE=$(gh pr view "$NUM" --repo "$REPO" --json baseRefName --jq .baseRefName)
[ "$NEW_BASE" = "$BASE" ] || { echo "::error::retarget of #$NUM to $BASE did not apply"; exit 1; }
fi
# The force-push already updated the PR; a comment (not a body edit) records the run.
gh pr comment "$NUM" --repo "$REPO" --body-file "$RUNNER_TEMP/pr-body.md"
echo "Updated #$NUM" >> "$GITHUB_STEP_SUMMARY"
fi

View File

@@ -1,134 +0,0 @@
name: Lock released branch
# Two responsibilities (defense in depth — Hard Rule #18 enforcement):
#
# 1. `on: release: published` — when a GitHub Release publishes tag v3.X.Y,
# apply branch protection (lock_branch + enforce_admins) to release/v3.X.Y
# so no further commits can land on a shipped version. To reopen later:
# gh api -X DELETE repos/<owner>/<repo>/branches/release/<tag>/protection
#
# 2. `on: push: branches: ['release/v*']` — verify that no push lands on a
# release/* branch whose matching tag already exists. This is the preventive
# guard: if the lock didn't apply (workflow bug, missing PAT, race), this
# job FAILS the push run so the operator gets paged immediately.
#
# `permissions:` cannot grant the `Administration` scope to GITHUB_TOKEN — that
# scope only exists on PATs. Set BRANCH_LOCK_TOKEN as a repo secret pointing to
# a PAT/fine-grained token with `Administration: read & write`. Without it, the
# lock step will fail loudly (which is what we want — silent failure caused the
# v3.8.3 incident on 2026-05-26 where 6 commits landed post-release).
on:
release:
types: [published]
push:
branches:
- "release/v*"
workflow_dispatch:
inputs:
tag:
description: "Tag of the released version (e.g. v3.8.2)"
required: true
type: string
permissions:
contents: read
# One run per ref at a time. The push guard below is a 5-second tag lookup whose
# verdict is identical for every push on the same branch, yet without a concurrency
# group each of the ~10 pushes/hour on the active release branch queued its own
# hosted run (20 queued on 2026-10-17 against the account's concurrent-job limit).
# The newest push supersedes the older ones; a `release` event carries its own ref.
concurrency:
group: lock-released-${{ github.ref }}
cancel-in-progress: true
jobs:
# ─────────────────────────────────────────────────────────────────────────
# Job 1 — Lock the release branch when a Release is published.
# ─────────────────────────────────────────────────────────────────────────
lock-branch:
if: github.event_name == 'release' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
steps:
- name: Lock release/<tag> branch
env:
# Administration scope is required to PUT branch protection. Default
# GITHUB_TOKEN cannot do this — operator must provision BRANCH_LOCK_TOKEN.
GH_TOKEN: ${{ secrets.BRANCH_LOCK_TOKEN }}
TAG: ${{ github.event.release.tag_name || inputs.tag }}
REPO: ${{ github.repository }}
run: |
set -euo pipefail
if [ -z "${GH_TOKEN}" ]; then
echo "::error::BRANCH_LOCK_TOKEN secret is not set. Create a PAT with Administration:write and add it as repo secret."
exit 1
fi
if [ -z "${TAG}" ]; then
echo "::error::No tag provided; cannot determine release branch."
exit 1
fi
BRANCH="release/${TAG}"
echo "Target branch: ${BRANCH} (repo: ${REPO})"
if ! gh api "repos/${REPO}/branches/${BRANCH}" >/dev/null 2>&1; then
echo "::warning::Branch ${BRANCH} not found — nothing to lock."
exit 0
fi
echo "Applying lock_branch protection to ${BRANCH}..."
gh api -X PUT "repos/${REPO}/branches/${BRANCH}/protection" --input - <<'JSON'
{
"required_status_checks": null,
"enforce_admins": true,
"required_pull_request_reviews": null,
"restrictions": null,
"lock_branch": true,
"allow_force_pushes": false,
"allow_deletions": false
}
JSON
LOCKED=$(gh api "repos/${REPO}/branches/${BRANCH}/protection" \
--jq '.lock_branch.enabled')
if [ "${LOCKED}" != "true" ]; then
echo "::error::Failed to confirm lock on ${BRANCH} (lock_branch=${LOCKED})."
exit 1
fi
echo "✅ ${BRANCH} is now locked (read-only)."
# ─────────────────────────────────────────────────────────────────────────
# Job 2 — Preventive guard: fail if a push lands on release/vX.Y.Z whose
# tag already exists. This catches the case where the lock didn't apply
# (PAT missing, race window, workflow bug) and pages the operator.
# ─────────────────────────────────────────────────────────────────────────
guard-no-push-after-release:
if: github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- name: Reject push if matching release tag exists
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
REF: ${{ github.ref_name }}
run: |
set -euo pipefail
# Extract version from ref: release/v3.8.3 -> v3.8.3
if [[ ! "${REF}" =~ ^release/(v[0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
echo "Ref ${REF} does not match release/vX.Y.Z — nothing to guard."
exit 0
fi
TAG="${BASH_REMATCH[1]}"
echo "Checking if tag ${TAG} already exists on ${REPO}..."
if gh api "repos/${REPO}/git/refs/tags/${TAG}" >/dev/null 2>&1; then
echo "::error::Hard Rule #18 violation — push to ${REF} but tag ${TAG} is already released."
echo "::error::Hotfixes for a released version must go on a NEW branch: release/v$(echo "${TAG#v}" | awk -F. '{$3=$3+1; print $1"."$2"."$3}' OFS=.)"
echo "::error::To undo this push: revert the offending commits, or contact an admin to lock the branch if it wasn't already."
exit 1
fi
echo "✅ No release tag for ${TAG} yet — push is OK."

View File

@@ -1,65 +0,0 @@
name: Mutation Redundancy (disableBail, on-demand)
# One-off measurement to UNBLOCK R1 (test-redundancy prune). The nightly mutation run
# (nightly-mutation.yml) bails on the first kill, so `killedBy` lists only the FIRST
# killer — 🟠 redundant is understated and 🟢 unique overstated (see the caveat in
# scripts/quality/mutation-radiography.mjs). This workflow re-runs the SAME combo +
# chatCore leaf batches with stryker.disablebail.json (disableBail:true, incremental:false)
# so `killedBy` lists EVERY killer. Feed the uploaded reports to
# `node scripts/quality/mutation-radiography.mjs --candidates mutation-nobail-*/mutation.json`
# to get the accurate R1 prune-candidate list (🔴 empty ∪ 🟠 redundant) for human review.
#
# Batches mirror the nightly's leaf decomposition (d/e/f/g/h/i) rather than 2 mega-batches:
# disableBail is MORE expensive than bail (it never stops early), and Stryker only writes
# mutation.json on a SUCCESSFUL finish — a batch cancelled at the cap produces NO data — so
# smaller batches each fit the 300min headroom and run in parallel. auth/accountFallback and
# the security quartet are out of scope: R1 targets the combo/chatCore leaves.
on:
workflow_dispatch:
permissions:
contents: read
jobs:
stryker-nobail:
name: Stryker disableBail (batch ${{ matrix.batch.name }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
batch:
- name: d
mutate: "open-sse/services/combo/comboStructure.ts,open-sse/services/combo/autoStrategy.ts,open-sse/services/combo/validateQuality.ts"
- name: e
mutate: "open-sse/services/combo/shadowRouting.ts,open-sse/services/combo/targetSorters.ts,open-sse/services/combo/comboPredicates.ts,open-sse/services/combo/rrState.ts,open-sse/services/combo/comboData.ts"
- name: f
mutate: "open-sse/services/combo/quotaScoring.ts,open-sse/services/combo/quotaStrategies.ts"
- name: g
mutate: "open-sse/handlers/chatCore/comboContextCache.ts,open-sse/handlers/chatCore/idempotency.ts,open-sse/handlers/chatCore/passthroughHelpers.ts,open-sse/handlers/chatCore/responseHeaders.ts,open-sse/handlers/chatCore/sanitization.ts,open-sse/handlers/chatCore/upstreamTimeouts.ts"
- name: h
mutate: "open-sse/handlers/chatCore/headers.ts,open-sse/handlers/chatCore/logTruncation.ts,open-sse/handlers/chatCore/memoryExtraction.ts,open-sse/handlers/chatCore/nonStreamingSse.ts,open-sse/handlers/chatCore/passthroughToolNames.ts,open-sse/handlers/chatCore/executorHelpers.ts"
- name: i
mutate: "open-sse/handlers/chatCore/telemetryHelpers.ts,open-sse/handlers/chatCore/memorySkillsInjection.ts,open-sse/handlers/chatCore/semanticCache.ts"
timeout-minutes: 300
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Run Stryker (disableBail)
env:
BATCH_MUTATE: ${{ matrix.batch.mutate }}
run: npx stryker run --config-file stryker.disablebail.json --mutate "$BATCH_MUTATE"
- name: Upload mutation report
if: always()
uses: actions/upload-artifact@v7
with:
name: mutation-nobail-${{ matrix.batch.name }}
path: reports/mutation/
if-no-files-found: warn
retention-days: 14

View File

@@ -1,142 +0,0 @@
name: Nightly Node Compat
# Plano mestre testes+CI (Eixo D2, aprovado 2026-07-04): as matrizes de compatibilidade
# Node 24/26 custavam ~28% de CADA run do CI pesado (2 execuções completas da suíte por
# sync da release-PR) para pegar uma classe de quebra que raramente nasce num PR típico.
# Elas rodam aqui 1×/dia contra o tip da release ativa (mesmo alvo do nightly-release-green)
# e continuam obrigatórias no gate de release via workflow_dispatch do ci.yml se preciso.
# fail-fast desligado: numa quebra queremos saber TODAS as versões afetadas de uma vez.
on:
schedule:
- cron: "47 6 * * *" # 06:47 UTC diário — slot distinto dos demais nightlies
workflow_dispatch:
inputs:
branch:
description: "Branch to validate (default: highest release/vX.Y.Z)"
required: false
type: string
permissions:
contents: read
issues: write
concurrency:
group: nightly-compat
cancel-in-progress: true
jobs:
resolve-branch:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Resolve active release branch
runs-on: ubuntu-latest
outputs:
target: ${{ steps.branch.outputs.target }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- name: Resolve active release branch
id: branch
env:
INPUT_BRANCH: ${{ github.event.inputs.branch }}
run: |
set -euo pipefail
if [ -n "${INPUT_BRANCH:-}" ]; then
TARGET="$INPUT_BRANCH"
else
TARGET=$(git for-each-ref --format='%(refname:short)' 'refs/remotes/origin/release/v*' \
| sed 's#origin/##' \
| sort -t/ -k2 -V \
| tail -1)
fi
case "$TARGET" in
release/v[0-9]*.[0-9]*.[0-9]*) ;;
*) echo "Refusing non-canonical branch name: $TARGET"; exit 1 ;;
esac
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
compat-build-26:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Node 26 Compatibility Build
runs-on: ubuntu-latest
timeout-minutes: 25
needs: resolve-branch
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.resolve-branch.outputs.target }}
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "26"
cache: npm
- uses: ./.github/actions/npm-ci-retry
# #8090 — this is the ONLY Node 26 build in the whole CI matrix (ci.yml pins
# CI_NODE_VERSION=24). It failed every nightly with the runner-reclaimed
# signature ("The runner has received a shutdown signal" / "The operation was
# canceled", no exit code) always at the same Turbopack compile phase — a
# classic OOM kill on the memory-constrained ubuntu-latest runner. Turbopack's
# native (Rust, off-V8-heap) allocation is NOT bounded by --max-old-space-size
# and peaks far higher than webpack on this large module graph (#6409), and is
# heavier still under Node 26. Use the documented webpack fallback here: it still
# validates that the app *builds* on Node 26 (the point of this compat job) at a
# much lower memory peak. Turbopack-on-Node-24 stays covered by ci.yml's build
# job. See docs/reference/ENVIRONMENT.md (OMNIROUTE_USE_TURBOPACK) and #6409.
- run: npm run build
env:
OMNIROUTE_USE_TURBOPACK: "0"
compat-tests:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Node ${{ matrix.node }} Compat Tests (${{ matrix.shard }}/4)
runs-on: ubuntu-latest
timeout-minutes: 25
needs: resolve-branch
strategy:
fail-fast: false
matrix:
node: [24, 26]
shard: [1, 2, 3, 4]
env:
JWT_SECRET: ci-nightly-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-nightly-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
TEST_SHARD: ${{ matrix.shard }}/4
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.resolve-branch.outputs.target }}
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ matrix.node }}
cache: npm
- uses: ./.github/actions/npm-ci-retry
- run: npm run check:node-runtime
- run: npm run test:unit:ci:shard
report:
name: Open / update tracking issue on failure
runs-on: ubuntu-latest
if: ${{ (!cancelled() && (needs.compat-tests.result == 'failure' || needs.compat-build-26.result == 'failure')) && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
needs: [resolve-branch, compat-build-26, compat-tests]
permissions:
issues: write
steps:
- name: Open or update issue
env:
GH_TOKEN: ${{ github.token }}
TARGET: ${{ needs.resolve-branch.outputs.target }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
TITLE="🌙 nightly-compat: Node 24/26 failures on $TARGET"
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open --search "$TITLE in:title" --json number --jq '.[0].number')
BODY="Nightly Node-compat run failed on \`$TARGET\`: $RUN_URL — triage which Node version/shard broke (fail-fast off, all versions reported)."
if [ -n "$EXISTING" ]; then
gh issue comment "$EXISTING" --repo "$GITHUB_REPOSITORY" --body "$BODY"
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --body "$BODY"
fi

View File

@@ -1,184 +0,0 @@
name: Nightly LLM Security
on:
schedule:
- cron: "53 5 * * *"
workflow_dispatch:
permissions:
contents: read
jobs:
promptfoo-guard:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: promptfoo — injection guard (block mode, no secret)
# #11965: this job runs a backend-only `next build`; the hosted 7 GB runner cannot build
# release/v3.8.51 (VM shutdown ~7 min in), so it targets the box's light pool (`omni-light`:
# two listeners, jobs ≤ ~6 GB). Falls back to hosted when USE_VPS_RUNNER is off.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with: { node-version: "24", cache: npm }
# Fresh runtime state per run (same contract as nightly-schemathesis.yml). The
# omni-light runner keeps a persistent $HOME, so the server used to boot on
# $HOME/.omniroute, where the database left by older nights sat at migration 134
# while the tip ships 200+: the mass-migration guard (#3416, threshold 50) refused
# to migrate it, the catalog warm-up hit `no such table: model_capability_overrides`
# and the health wait failed every night (no verdict since 2026-08-27). A DATA_DIR
# under $RUNNER_TEMP is a new database every run, so every migration applies and
# nothing on the box is touched. Auto-backups stay off: one pre-migration backup
# per boot had piled up 1.6 GB under the runner's home.
- name: Prepare isolated runtime state
id: runtime
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-llm-security.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Build CLI bundle
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
OMNIROUTE_BUILD_BACKEND_ONLY: "1"
OMNIROUTE_USE_TURBOPACK: "0"
run: npm run build:cli
# Own port: this box also hosts the deployed server (the a11y job's
# "20128 is already used" nights prove it). A test server that dies on
# EADDRINUSE must NOT let the eval fall through to whatever else answers
# on the port — a block-mode validation against a server running WITHOUT
# block mode validates the wrong deployment and can only ever pass.
- name: Start OmniRoute (block mode)
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
PORT: "21778"
INJECTION_GUARD_MODE: block
DISABLE_SQLITE_AUTO_BACKUP: "true"
run: |
node dist/server.js > server.log 2>&1 &
echo $! > server.pid
for i in $(seq 1 60); do
if curl -sf http://localhost:21778/api/monitoring/health >/dev/null; then echo up; exit 0; fi
sleep 2
done
echo "::error::Test server did not come up on 21778 in 120s — see server.log. Refusing to run the guard eval against an unknown target."
tail -40 server.log || true
exit 1
# Pinned, network-isolated promptfoo. Two constraints, both verified on this box:
# (1) never `promptfoo@latest`: promptfoo >= 0.123.1 (promptfoo/promptfoo#10866) throws
# `result?.error?.includes is not a function` inside its rate-limit classifier when
# the https provider hands it the parsed 4xx JSON body the guard answers in block
# mode, so every blocked request became an eval ERROR, not a PASS (run 39007982929);
# (2) never the lockfile install (`npx --no-install`): #17017 — the lock nests js-yaml
# 4.3.2 under @apidevtools/json-schema-ref-parser, so the in-repo promptfoo dies at
# import on `binaryTag` (run 39084298931). `npx --yes promptfoo@<exact>` installs its
# own tree in the npx cache — when run from a directory without that package
# (see the step's working-directory). The version mirrors the devDependency pin in
# package.json; tests/unit/build/llm-security-nightly-promptfoo-pin.test.ts keeps
# the two equal and off the releases proven broken.
# `working-directory` OUTSIDE the checkout is load-bearing: npx resolves a package from
# the nearest node_modules first, and since #17005 the repo's own promptfoo satisfies
# the `@0.123.0` spec, so run from the workspace it picked node_modules/promptfoo and
# died on the nested js-yaml again (#17017, run 39095530088). From $RUNNER_TEMP there is
# no local install to shadow the npx cache tree.
- name: promptfoo guard-validation
working-directory: ${{ runner.temp }}
run: npx --yes promptfoo@0.123.0 eval -c "$GITHUB_WORKSPACE/promptfooconfig.yaml" --no-cache
env:
OMNIROUTE_URL: http://localhost:21778
OMNIROUTE_API_KEY: not-needed-blocked-before-upstream
- name: Stop server
if: always()
run: kill "$(cat server.pid)" || true
garak:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: garak probes (skip without provider secret)
# #11965: this job runs a backend-only `next build`; the hosted 7 GB runner cannot build
# release/v3.8.51 (VM shutdown ~7 min in), so it targets the box's light pool (`omni-light`:
# two listeners, jobs ≤ ~6 GB). Falls back to hosted when USE_VPS_RUNNER is off.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
# NOTE: the `secrets` context is NOT available in a job-level `if:` — referencing
# it there makes GitHub reject the file on push (startup_failure on every push).
# Map the secret into a job-level env and gate each step on a presence check, so
# the job stays green and simply skips the probes when the secret is absent.
env:
PROMPTFOO_PROVIDER_KEY: ${{ secrets.PROMPTFOO_PROVIDER_KEY }}
steps:
- name: Gate on provider secret
id: gate
run: |
if [ -n "$PROMPTFOO_PROVIDER_KEY" ]; then
echo "run=true" >> "$GITHUB_OUTPUT"
else
echo "run=false" >> "$GITHUB_OUTPUT"
echo "::notice::PROMPTFOO_PROVIDER_KEY not set — skipping garak probes (advisory)."
fi
- uses: actions/checkout@v7
with:
persist-credentials: false
if: steps.gate.outputs.run == 'true'
- uses: actions/setup-node@v7
if: steps.gate.outputs.run == 'true'
with: { node-version: "24", cache: npm }
# Same isolation as the promptfoo job above: a fresh DATA_DIR per run, never the
# runner's persistent $HOME/.omniroute (stale schema → migration guard → no boot).
- name: Prepare isolated runtime state
id: runtime
if: steps.gate.outputs.run == 'true'
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-llm-security.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
if: steps.gate.outputs.run == 'true'
- name: Build CLI bundle
if: steps.gate.outputs.run == 'true'
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
OMNIROUTE_BUILD_BACKEND_ONLY: "1"
OMNIROUTE_USE_TURBOPACK: "0"
run: npm run build:cli
# Same contract as the promptfoo job above: dedicated port, and the
# health wait must fail the job instead of letting garak probe whatever
# else listens on the default port.
- name: Start OmniRoute
if: steps.gate.outputs.run == 'true'
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
PORT: "21779"
DISABLE_SQLITE_AUTO_BACKUP: "true"
run: |
node dist/server.js > server.log 2>&1 &
echo $! > server.pid
for i in $(seq 1 60); do
if curl -sf http://localhost:21779/api/monitoring/health >/dev/null; then echo up; exit 0; fi
sleep 2
done
echo "::error::Test server did not come up on 21779 in 120s — see server.log."
tail -40 server.log || true
exit 1
- uses: actions/setup-python@v7
if: steps.gate.outputs.run == 'true'
with: { python-version: "3.12" }
- run: pip install garak
if: steps.gate.outputs.run == 'true'
- name: garak limited probes
if: steps.gate.outputs.run == 'true'
env:
OPENAI_API_KEY: ${{ secrets.PROMPTFOO_PROVIDER_KEY }}
OPENAI_BASE_URL: http://localhost:21779/v1
run: garak --model_type openai --model_name gpt-4o-mini --probes promptinject,dan,leakreplay --report_prefix garak-omniroute || true
- name: Stop server
if: always() && steps.gate.outputs.run == 'true'
run: kill "$(cat server.pid)" || true

View File

@@ -1,166 +0,0 @@
name: Nightly Mutation
on:
schedule:
- cron: "17 3 * * *"
workflow_dispatch:
permissions:
contents: read
jobs:
stryker:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Stryker mutation (batch ${{ matrix.batch.name }} — advisory)
runs-on: ubuntu-latest
# Mutation testing is expensive. History of the budget:
# - Full 8-module set TIMED OUT at the 180min cap (run 27705123780 = exactly 180min).
# The two god-files chatCore.ts/combo.ts dominated ~2/3 of the mutants and were
# removed from stryker.conf.json `mutate`.
# - The remaining 6 modules in 3 batches: auth.ts and accountFallback.ts are large; the
# a (auth+publicCreds) and b (accountFallback+error) batches still ran near the 180min
# cap (the perTest dry-run over ~130 covering test files is itself costly), so the two
# big modules are now ISOLATED into their own batches (a=auth, b=accountFallback).
# - Onda 3 / Fase 9 T5 re-add: combo.ts was split into 11 leaves; the 8 well-covered
# combo/* leaves are back in `mutate` (covered by the 24 combo-*.test.ts), grouped into
# 2 batches (d=heavy, e=light). After #4204 (D7b) merged, the reset-aware quota pair
# quotaScoring/quotaStrategies was added as batch f. A covering-test audit then added the
# 6 chatCore/* leaves with direct unit coverage as batch g. A follow-up then wrote dedicated
# unit tests for 6 more leaves and added them as batch h. A final follow-up added dedicated
# tests (no mock.module — fetch-override + crafted inputs + temp-DATA_DIR) for telemetryHelpers
# + memorySkillsInjection + semanticCache (its cache-HIT block now has a setCachedResponse
# fixture) as batch i — ALL 15/15 chatCore leaves are now mutated. See
# _mutate_godfiles_excluded_comment in stryker.conf.json.
# 9 PARALLEL batches, each overriding the mutate set via `--mutate` (Stryker 9 CLI:
# `-m, --mutate <comma-list>`; the conf's `mutate[]` remains the local-run default/union).
# - Cold-seeding budget (per-batch `timeout-minutes: ${{ matrix.batch.timeout || 180 }}`):
# a COLD run must COMPLETE once to write stryker-incremental.json (Stryker writes it only on
# a successful finish); a job cancelled at the cap writes nothing, so the next run is cold
# again — an infinite never-seeds loop. actions/cache is also branch-scoped, so each branch
# (incl. release) must seed its OWN cache via a run with enough headroom. Measured cold runs
# Measured cold totals (run 27801802713, extrapolated from the % at the 180/350 cancel point):
# auth ~375min (2301 mutants — EXCEEDS the 360min job max even isolated), accountFallback
# ~358min (1441), the c security quartet ~348min (1163), d ~197min (1316), g=142, h=132, e=66,
# f=45, i=33. The widely-covered modules blow the budget because the tap-runner re-runs every
# covering test file per mutant (a perTest fixed cost over ~138 test files, times thousands of
# mutants). A flat timeout bump cannot rescue auth (>360min max) — so the three over-budget
# batches are SPLIT so each half fits: auth->a1/a2 and accountFallback->b1/b2 by mutation range
# (`file:startLine-endLine`), the c quartet->c1/c2 by module pair. Splitting also seeds each
# sub-batch's own incremental cache, after which nightlies re-test only changed mutants.
# Full coverage every night in parallel; wall-clock = the slowest batch's cold run until seeded.
# Runs at stryker concurrency=4 with per-process DATA_DIR isolation
# (tests/_setup/isolateDataDir.ts) — see _concurrency_comment in stryker.conf.json.
strategy:
fail-fast: false
matrix:
batch:
# Per-batch `timeout` (minutes) tiers the cold-seeding budget by measured cost; batches
# without the key default to 180. Cold-run profiling (run 27801802713) showed the
# widely-covered modules need FAR more than the 180 cap because the tap-runner re-runs every
# covering test file per mutant: auth ~375min (2301 mutants, EXCEEDS the 360min GitHub job
# max even isolated), accountFallback ~358min, the c security quartet ~348min — none fit a
# single job. So auth/accountFallback are split by MUTATION RANGE (`file:startLine-endLine`,
# ~half the mutants each) into a1/a2, b1/b2; the c quartet is split by MODULE pair into
# c1/c2. d (3 combo modules, ~197min) stays whole. Split-heavy batches get 300min headroom
# for their cold seeding run; once each batch completes once and writes
# stryker-incremental.json, later runs re-test only changed mutants and finish far faster.
# g/h (142/132min cold) keep a 240 buffer; e/f/i (33-66min) keep the 180 default.
- name: a1
mutate: "src/sse/services/auth.ts:1-1109"
timeout: 300
- name: a2
mutate: "src/sse/services/auth.ts:1110-2218"
timeout: 300
- name: b1
mutate: "open-sse/services/accountFallback.ts:1-863"
timeout: 300
- name: b2
mutate: "open-sse/services/accountFallback.ts:864-1726"
timeout: 300
- name: c1
mutate: "src/server/authz/routeGuard.ts,src/shared/utils/circuitBreaker.ts"
timeout: 300
- name: c2
mutate: "open-sse/utils/error.ts,open-sse/utils/publicCreds.ts"
timeout: 300
- name: d
mutate: "open-sse/services/combo/comboStructure.ts,open-sse/services/combo/autoStrategy.ts,open-sse/services/combo/validateQuality.ts"
timeout: 300
- name: e
mutate: "open-sse/services/combo/shadowRouting.ts,open-sse/services/combo/targetSorters.ts,open-sse/services/combo/comboPredicates.ts,open-sse/services/combo/rrState.ts,open-sse/services/combo/comboData.ts"
- name: f
mutate: "open-sse/services/combo/quotaScoring.ts,open-sse/services/combo/quotaStrategies.ts"
- name: g
mutate: "open-sse/handlers/chatCore/comboContextCache.ts,open-sse/handlers/chatCore/idempotency.ts,open-sse/handlers/chatCore/passthroughHelpers.ts,open-sse/handlers/chatCore/responseHeaders.ts,open-sse/handlers/chatCore/sanitization.ts,open-sse/handlers/chatCore/upstreamTimeouts.ts"
timeout: 240
- name: h
mutate: "open-sse/handlers/chatCore/headers.ts,open-sse/handlers/chatCore/logTruncation.ts,open-sse/handlers/chatCore/memoryExtraction.ts,open-sse/handlers/chatCore/nonStreamingSse.ts,open-sse/handlers/chatCore/passthroughToolNames.ts,open-sse/handlers/chatCore/executorHelpers.ts"
timeout: 240
- name: i
mutate: "open-sse/handlers/chatCore/telemetryHelpers.ts,open-sse/handlers/chatCore/memorySkillsInjection.ts,open-sse/handlers/chatCore/semanticCache.ts"
# Per-batch budget: split-heavy batches (a1/a2/b1/b2/c1/c2/d) override to 300min, g/h to 240min;
# the rest default to 180min. `matrix.batch.timeout` is null for batches without the key -> `|| 180`.
# NOTE: a1+a2 both mutate auth.ts (disjoint line ranges) and b1+b2 both mutate accountFallback.ts;
# when merging the per-batch mutation.json for radiography/scores, same-file mutants from sibling
# ranges must be UNIONED (scripts/check/check-mutation-ratchet.mjs::measureMutationScores and
# scripts/quality/mutation-radiography.mjs both merge per file).
timeout-minutes: ${{ matrix.batch.timeout || 180 }}
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Restore Stryker incremental cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: reports/mutation/stryker-incremental.json
key: stryker-incremental-${{ matrix.batch.name }}-${{ github.run_id }}
restore-keys: stryker-incremental-${{ matrix.batch.name }}-
- name: Run Stryker (advisory)
id: stryker
continue-on-error: true
env:
BATCH_MUTATE: ${{ matrix.batch.mutate }}
run: npx stryker run --mutate "$BATCH_MUTATE"
- name: Upload mutation report
if: always()
uses: actions/upload-artifact@v7
with:
name: mutation-report-${{ matrix.batch.name }}
path: reports/mutation/
if-no-files-found: warn
retention-days: 14
# Aggregation gate (T3): each split batch emits a PARTIAL view of a mutated file
# (auth.ts lives in a1+a2, accountFallback in b1+b2), so a PER-BATCH ratchet would
# only ever see half a file vs the whole-file baseline. This job runs AFTER every
# batch, downloads all reports, and ratchets the MERGED per-module scores
# (check-mutation-ratchet UNIONS same-file mutants across reports) against the
# dedicatedGate `mutationScore.*` floors in quality-baseline.json (seeded ~2pt below
# the first full measurement). Blocking: a module dropping below its floor fails the
# run. Missing reports (e.g. an artifact-upload flake) are skipped, never failed.
mutation-ratchet:
name: Mutation score ratchet (blocking)
needs: stryker
if: ${{ always() && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
- name: Download all mutation reports
uses: actions/download-artifact@v8
with:
pattern: mutation-report-*
path: reports/all
- name: Ratchet merged per-module mutation scores
run: node scripts/check/check-mutation-ratchet.mjs reports/all/*/mutation.json --ratchet

View File

@@ -1,38 +0,0 @@
name: Nightly Property Discovery
on:
schedule:
- cron: "0 6 * * *"
workflow_dispatch:
permissions:
contents: read
issues: write
jobs:
property-random-seed:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: fast-check random seed (high runs)
id: prop
run: FC_SEED=random FC_NUM_RUNS=2000 npm run test:property
- name: Open issue on failure
if: failure()
uses: actions/github-script@v9
with:
script: |
await github.rest.issues.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: "Nightly property-test failure (Fase 8 B)",
body: "fast-check found a counterexample with a random seed. Check the run logs for the reproducible seed + minimal case, then add it as a fixture.\n\nRun: " + context.serverUrl + "/" + context.repo.owner + "/" + context.repo.repo + "/actions/runs/" + context.runId,
labels: ["quality-gate-finding"],
});

View File

@@ -1,890 +0,0 @@
name: Release-Green (continuous)
# Continuous validation: artifacts, issue state and job exit must agree.
#
# WHY: the full gate (ci.yml) only runs on the release PR (PR → main), so reds
# accrue silently on release/** and explode — in layers — at release time. This
# workflow reproduces the release-equivalent validation on the release branch and,
# when there are HARD failures, opens/updates a single tracking issue.
#
# WS5.1 (v3.8.49 quality plan) — two modes:
# push to release/v* (code paths) → --quick (fast HARD gates, ~5-8min). Catches the
# captain's direct pushes (sync-back — the one ungated write path) AND the merged
# COMBINATION right after every PR merge, attributing the offending push range in
# the issue. Base-red MTTD drops from ≤24h to ≤~15min after the offending push.
# schedule → full --with-build --full-ci (the deep sweep incl. build+suites): 3×/day for
# the release branch, 1×/day (05:23) for main, whose SHA only moves on a release.
#
# It is NOT a required status check and never touches a contributor PR — it only
# reports. Ratchet drift (eslint warnings / cognitive-complexity / file-size) is
# expected mid-cycle and is reported but never raises the alarm on its own; only
# real defects (typecheck / lint errors / unit / vitest / db-rules / public-creds /
# package-artifact) flip the issue open.
on:
push:
branches: ["release/v*", "main"]
paths:
- "src/**"
- "open-sse/**"
- "bin/**"
- "electron/**"
- "scripts/**"
- "tests/**"
- "config/**"
- ".github/workflows/**"
- ".github/actions/**"
- "package.json"
- "package-lock.json"
- "tsconfig*.json"
schedule:
- cron: "23 5 * * *" # full sweep — off-peak, distinct from other nightlies
- cron: "23 12 * * *" # full sweep — midday (WS5.1: 3×/day instead of 1×); release only
- cron: "23 18 * * *" # full sweep — evening; release only (main-green runs at 05:23 only)
workflow_dispatch:
inputs:
branch:
description: "Release branch to validate (default: highest release/vX.Y.Z)"
required: false
type: string
permissions:
contents: read
issues: write
concurrency:
# push storms during merge campaigns collapse to the newest commit per branch;
# scheduled full sweeps keep their own single lane. A started run is never cancelled:
# with cancel-in-progress on push, ~10 pushes/hour cancelled 97 of 100 push runs in a
# day (2026-10-18) after 2-18 min of work each, so the per-merge verdict almost never
# landed. GitHub keeps one running + one pending run per group, and a newer push still
# replaces the pending one, so the storm still collapses — without throwing work away.
group: release-green-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: false
env:
OMNIROUTE_SKIP_SYSTEM_TRUST: "1"
jobs:
# Schedule/dispatch only: the commit the hosted suites and the slot validation share.
# Resolved once so a push landing mid-sweep cannot split the lanes across two commits.
resolve-target:
name: Resolve sweep target
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
target: ${{ steps.resolve.outputs.target }}
sha: ${{ steps.resolve.outputs.sha }}
node-version: ${{ steps.runtime.outputs.node-version }}
steps:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
id: runtime
with:
node-version: "24"
package-manager-cache: false
- name: Resolve the active release branch and its tip
id: resolve
env:
GH_TOKEN: ${{ github.token }}
INPUT_BRANCH: ${{ github.event.inputs.branch }}
run: |
set -euo pipefail
if [ -n "${INPUT_BRANCH:-}" ]; then
TARGET="$INPUT_BRANCH"
else
TARGET=$(gh api "repos/$GITHUB_REPOSITORY/branches?per_page=100" --paginate \
--jq '.[].name' | grep -E '^release/v[0-9]+\.[0-9]+\.[0-9]+$' | sort -t/ -k2 -V | tail -1)
fi
if ! printf '%s' "$TARGET" | grep -qE '^release/v[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "Refusing non-canonical branch name: $TARGET"; exit 1
fi
SHA=$(gh api "repos/$GITHUB_REPOSITORY/branches/$TARGET" --jq '.commit.sha')
if ! printf '%s' "$SHA" | grep -qE '^[0-9a-f]{40}$'; then echo "No tip for $TARGET"; exit 1; fi
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
echo "sha=$SHA" >> "$GITHUB_OUTPUT"
echo "Sweep target: $TARGET @ $SHA"
# The full sweep's unit, integration and vitest lanes, on hosted runners with ci.yml's own
# shards and commands. On the 8-core omni-release slot they took ~4h15 per sweep and failed
# timing tests on CPU starvation (2026-10-19/20); hosted, a shard takes ~13 min. The shard
# counts must match ci.yml (tests/unit/validate-release-green.test.ts pins it).
suites:
name: Hosted suite (${{ matrix.name }})
needs: resolve-target
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- { name: unit-1, script: "test:unit:ci:shard", shard: "1/8" }
- { name: unit-2, script: "test:unit:ci:shard", shard: "2/8" }
- { name: unit-3, script: "test:unit:ci:shard", shard: "3/8" }
- { name: unit-4, script: "test:unit:ci:shard", shard: "4/8" }
- { name: unit-5, script: "test:unit:ci:shard", shard: "5/8" }
- { name: unit-6, script: "test:unit:ci:shard", shard: "6/8" }
- { name: unit-7, script: "test:unit:ci:shard", shard: "7/8" }
- { name: unit-8, script: "test:unit:ci:shard", shard: "8/8" }
- { name: integration-1, script: "test:integration:ci", shard: "1/2" }
- { name: integration-2, script: "test:integration:ci", shard: "2/2" }
- { name: vitest, script: "test:vitest", shard: "" }
env:
JWT_SECRET: ci-nightly-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-nightly-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.resolve-target.outputs.sha }}
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ needs.resolve-target.outputs.node-version }}
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Run the suite and record its result
env:
NAME: ${{ matrix.name }}
SUITE: ${{ matrix.script }}
TEST_SHARD: ${{ matrix.shard }}
NODE_OPTIONS: --max-old-space-size=8192
run: |
set +e
if [[ "$NAME" == integration-* ]]; then
# as ci.yml's test-integration job
export DATA_DIR="/tmp/omniroute-ci-${NAME#integration-}"
export INITIAL_PASSWORD=ci-test-password-for-integration
fi
(
if [ "$NAME" = "vitest" ]; then
npm run test:vitest && npm run test:vitest:ui
else
npm run "$SUITE"
fi
) 2>&1 | tee suite.log
code=${PIPESTATUS[0]}
node scripts/ci/release-green-suite.mjs "$NAME" "$code" suite.log suite-results \
"$GITHUB_WORKFLOW_SHA" "$SUITE" "$TEST_SHARD" || exit "$?"
exit "$code"
- name: Upload the suite result
if: always()
uses: actions/upload-artifact@v7
with:
name: release-green-suite-${{ github.run_attempt }}-${{ matrix.name }}
path: suite-results/
if-no-files-found: ignore
retention-days: 7
release-green:
name: Validate active release branch
# On a push, only run for release/* pushes — a push to main is handled by the
# main-green job below. Schedule/dispatch always run (they validate the highest release).
# On push the two jobs above are skipped; !cancelled() keeps this job from being skipped
# with them, and on schedule/dispatch it still reports when a suite job failed.
needs: [resolve-target, suites]
if: ${{ !cancelled() && (github.event_name != 'push' || startsWith(github.ref_name, 'release/')) && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
# Dynamic runner: with USE_VPS_RUNNER=true (release window / on-demand pre-flight)
# this runs on the dedicated VPS runner — clean env (no operator OMNIROUTE_API_KEY,
# no local noauth CLIs => zero machine-specific false positives) and no contention.
# Nightly cron normally finds the var false (VM off) and falls back to hosted.
# Own slot (docs/ops/RUNNER_BOX.md): `omni-release` is omniroute-113-6 only, so the
# validation no longer queues on the single `omni-build` slot (the 2026-10-18 05:29
# sweep waited 6 h for it). That slot is capped at 24 GB, so the validation's build
# runs on webpack (~14-16 GB); Turbopack fidelity stays with ci.yml's Build on
# `omni-build` and with the npm publish.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && fromJSON('["self-hosted","omni-release"]')) || 'ubuntu-latest' }}
env:
OMNIROUTE_USE_TURBOPACK: "0"
JWT_SECRET: ci-nightly-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-nightly-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- name: Resolve active release branch
id: branch
env:
INPUT_BRANCH: ${{ github.event.inputs.branch }}
EVENT_NAME: ${{ github.event_name }}
PUSHED_REF: ${{ github.ref_name }}
SWEEP_TARGET: ${{ needs.resolve-target.outputs.target }}
run: |
set -euo pipefail
if [ -n "${SWEEP_TARGET:-}" ]; then
# schedule/dispatch: the branch the hosted suites tested
TARGET="$SWEEP_TARGET"
elif [ -n "${INPUT_BRANCH:-}" ]; then
TARGET="$INPUT_BRANCH"
elif [ "$EVENT_NAME" = "push" ]; then
# validate exactly what was pushed, not the highest branch
TARGET="$PUSHED_REF"
else
# highest release/vX.Y.Z by semver among remote branches
TARGET=$(git for-each-ref --format='%(refname:short)' 'refs/remotes/origin/release/v*' \
| sed 's#origin/##' \
| sort -t/ -k2 -V \
| tail -1)
fi
if [ -z "$TARGET" ]; then echo "No release/v* branch found"; exit 1; fi
# Strict format guard — reject anything that isn't release/vX.Y.Z (blocks
# ref/command injection via the workflow_dispatch input).
if ! printf '%s' "$TARGET" | grep -qE '^release/v[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "Refusing non-canonical branch name: $TARGET"; exit 1
fi
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
echo "Active release branch: $TARGET"
- name: Checkout the release branch
env:
TARGET: ${{ steps.branch.outputs.target }}
EVENT_NAME: ${{ github.event_name }}
PUSH_SHA: ${{ github.sha }}
SWEEP_SHA: ${{ needs.resolve-target.outputs.sha }}
run: |
set -euo pipefail
if [ "$EVENT_NAME" = "push" ]; then
git checkout --detach "$PUSH_SHA"
elif [ -n "${SWEEP_SHA:-}" ]; then
# the exact commit the hosted suites tested
git checkout --detach "$SWEEP_SHA"
else
git checkout --detach "origin/$TARGET"
fi
git log -1 --oneline
- name: Record validated revision
id: revision
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- uses: actions/setup-node@v7
with:
node-version: ${{ needs.resolve-target.outputs.node-version || '24' }}
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Collect the hosted suite results
if: github.event_name != 'push'
continue-on-error: true
uses: actions/download-artifact@v8
with:
# A partial re-run cannot reuse receipts from an earlier attempt;
# rerun all suite jobs for a new complete observation of the same tip.
pattern: release-green-suite-${{ github.run_attempt }}-*
path: suite-results
merge-multiple: true
# Use the immutable workflow revision, not the target checkout (which may
# predate this installer). Both scanners are required even for --quick.
- name: Prepare pinned workflow scanners
id: workflow_scanners
env:
WORKFLOW_SHA: ${{ github.workflow_sha }}
run: |
set -euo pipefail
installer=$(mktemp "${RUNNER_TEMP:?}/workflow-scanners-installer.XXXXXX")
git show "${WORKFLOW_SHA}:scripts/ci/install-workflow-scanners.sh" > "$installer"
bash "$installer"
- name: Release-green validation (full)
id: validate
env:
EVENT_NAME: ${{ github.event_name }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
run: |
set +e
# --hermetic: scrub live-test trigger vars (self-hosted runner may carry
# operator env; hosted ignores the unknown flag before #6300 lands).
# push → --quick: fast HARD gates only (~5-8min), per-merge signal.
# schedule/dispatch → --with-build --full-ci: ALSO run every static gate from
# ci.yml's gate jobs (lint, quality-gate, quality-extended, docs-sync-strict,
# pr-test-policy) + build + full suites. PRs into release/** only get the
# fast-gates, so these accrue silently and explode in layers on the release PR
# (v3.8.46: 11 static base-reds leaked).
if [ "$EVENT_NAME" = "push" ]; then
MODE="--quick"
else
# unit/integration/vitest ran in the hosted `suites` jobs; a missing result fails
mkdir -p suite-results
MODE="--with-build --full-ci --suites-from suite-results"
fi
echo "[release-green] mode: $MODE (event: $EVENT_NAME)"
# MODE is an intentional flag list, so word-splitting is wanted here
# shellcheck disable=SC2086
node scripts/quality/validate-release-green.mjs --json --hermetic $MODE \
--suites-workflow-sha "$GITHUB_WORKFLOW_SHA" \
1> release-green.json 2> release-green.log
validation_exit=$?
node scripts/ci/release-green-result.mjs release-green.json "$validation_exit" "$VALIDATED_SHA" "$EVENT_NAME" >> release-green.log
echo "------- report -------"
cat release-green.log
- name: Open / update tracking issue on HARD failure
if: steps.validate.outputs.exit != '0'
env:
GH_TOKEN: ${{ github.token }}
TARGET: ${{ steps.branch.outputs.target }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
EVENT_NAME: ${{ github.event_name }}
BEFORE_SHA: ${{ github.event.before }}
AFTER_SHA: ${{ github.event.after }}
run: |
set -euo pipefail
TITLE="🔴 Release branch not green: ${TARGET}"
{
echo "The **release-green** validation found HARD failures on \`${TARGET}\`."
echo "The required validation failed or its evidence was incomplete. Compare the"
echo "signature on the exact base before attributing a defect to a contributor."
echo ""
echo "**Run:** ${RUN_URL} (mode: ${EVENT_NAME})"
# This is an observed range, not proof of causality. Compare with the base.
if [ "$EVENT_NAME" = "push" ] && [ -n "${BEFORE_SHA:-}" ] && \
git cat-file -e "$BEFORE_SHA" 2>/dev/null; then
echo ""
echo "**Observed push range** (\`${BEFORE_SHA:0:9}..${AFTER_SHA:0:9}\`):"
echo '```'
git log --no-decorate --oneline "${BEFORE_SHA}..${AFTER_SHA}" | head -20
echo '```'
fi
echo ""
echo '```'
if grep -q '──────── verdict ────────' release-green.log; then
sed -n '/──────── verdict ────────/,$p' release-green.log
else
tail -40 release-green.log
fi
echo '```'
echo ""
echo "_Ratchet drift (eslint warnings / cognitive-complexity / file-size) listed above is expected mid-cycle and is rebaselined at release — it is NOT a contributor concern and did not, on its own, open this issue._"
} > issue-body.md
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title $TITLE" --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING" ]; then
gh issue comment "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file issue-body.md
echo "Updated existing issue #$EXISTING"
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --label base-red --body-file issue-body.md
fi
- name: Close tracking issue when the branch is green again
if: steps.validate.outputs.exit == '0' && github.event_name != 'push'
env:
GH_TOKEN: ${{ github.token }}
TARGET: ${{ steps.branch.outputs.target }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
CURRENT_SHA=$(git ls-remote origin "refs/heads/$TARGET" | cut -f1)
if [ "$CURRENT_SHA" != "$VALIDATED_SHA" ]; then
echo "Branch advanced; retaining the tracking issue."
exit 0
fi
# The open/update step above is the UPWARD half of the loop; without this
# step a stale "not green" issue outlives the fix and every base-green check
# (`AGENTS.md` → "Base-green check") keeps stamping new PRs as base-red inherited.
TITLE="🔴 Release branch not green: ${TARGET}"
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title $TITLE" --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING" ]; then
gh issue close "$EXISTING" --repo "$GITHUB_REPOSITORY" --reason completed \
--comment "✅ \`${TARGET}\` is release-green again at \`${VALIDATED_SHA}\` — ${RUN_URL}. Auto-closed after full validation of the current branch."
echo "Closed issue #$EXISTING"
fi
# Best-effort: the verdict above is already recorded (issue open/closed,
# step summary). The artifact upload has raced job teardown on the shared
# runner three runs in a row (403 "job is completed" after the job was
# done), turning a finished verdict into a red run — a false base-red
# that every PR gate reads. Never let the upload outvote the verdict.
- name: Upload report artifact
if: always()
continue-on-error: true
uses: actions/upload-artifact@v7
with:
name: release-green-report
path: |
release-green.json
release-green.log
suite-results/
_artifacts/release-green/
if-no-files-found: error
retention-days: 14
- name: Enforce validation verdict
if: always()
env:
VALIDATION_EXIT: ${{ steps.validate.outputs.exit }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
EVENT_NAME: ${{ github.event_name }}
run: node scripts/ci/release-green-result.mjs release-green.json "$VALIDATION_EXIT" "$VALIDATED_SHA" "$EVENT_NAME"
# main's own sweep target, resolved once so the hosted suites and the slot validation
# cannot split across two commits. Same 05:23-only schedule as main-green.
resolve-main:
name: Resolve main sweep target
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || (github.repository == 'cheaper-inference/OmniRoute' && github.event.schedule == '23 5 * * *')) }}
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
sha: ${{ steps.resolve.outputs.sha }}
steps:
- name: Resolve the main tip
id: resolve
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
SHA=$(gh api "repos/$GITHUB_REPOSITORY/branches/main" --jq '.commit.sha')
if ! printf '%s' "$SHA" | grep -qE '^[0-9a-f]{40}$'; then echo "No tip for main"; exit 1; fi
echo "sha=$SHA" >> "$GITHUB_OUTPUT"
# Same reasons as `suites`: the 8-core root slot cannot run these lanes meaningfully.
# The matrix must match main's ci.yml shard counts; a mismatch fails closed as missing receipts.
main-suites:
name: Hosted main suite (${{ matrix.name }})
needs: [resolve-target, resolve-main]
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || (github.repository == 'cheaper-inference/OmniRoute' && github.event.schedule == '23 5 * * *')) }}
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- { name: unit-1, script: "test:unit:ci:shard", shard: "1/8" }
- { name: unit-2, script: "test:unit:ci:shard", shard: "2/8" }
- { name: unit-3, script: "test:unit:ci:shard", shard: "3/8" }
- { name: unit-4, script: "test:unit:ci:shard", shard: "4/8" }
- { name: unit-5, script: "test:unit:ci:shard", shard: "5/8" }
- { name: unit-6, script: "test:unit:ci:shard", shard: "6/8" }
- { name: unit-7, script: "test:unit:ci:shard", shard: "7/8" }
- { name: unit-8, script: "test:unit:ci:shard", shard: "8/8" }
- { name: integration-1, script: "test:integration:ci", shard: "1/2" }
- { name: integration-2, script: "test:integration:ci", shard: "2/2" }
- { name: vitest, script: "test:vitest", shard: "" }
env:
JWT_SECRET: ci-nightly-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-nightly-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.resolve-main.outputs.sha }}
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ needs.resolve-target.outputs.node-version }}
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Run the suite and record its result
env:
NAME: ${{ matrix.name }}
SUITE: ${{ matrix.script }}
TEST_SHARD: ${{ matrix.shard }}
NODE_OPTIONS: --max-old-space-size=8192
run: |
set +e
if [[ "$NAME" == integration-* ]]; then
# as ci.yml's test-integration job
export DATA_DIR="/tmp/omniroute-ci-${NAME#integration-}"
export INITIAL_PASSWORD=ci-test-password-for-integration
fi
(
if [ "$NAME" = "vitest" ]; then
npm run test:vitest && npm run test:vitest:ui
else
npm run "$SUITE"
fi
) 2>&1 | tee suite.log
code=${PIPESTATUS[0]}
node scripts/ci/release-green-suite.mjs "$NAME" "$code" suite.log suite-results \
"$GITHUB_WORKFLOW_SHA" "$SUITE" "$TEST_SHARD" || exit "$?"
exit "$code"
- name: Upload the suite result
if: always()
uses: actions/upload-artifact@v7
with:
name: main-green-suite-${{ github.run_attempt }}-${{ matrix.name }}
path: suite-results/
if-no-files-found: ignore
retention-days: 7
# Companion arm for `main`. Under the parallel-cycle model, main only receives merged
# work at the release squash — so a gate/infra fix that lands only on release leaves
# main red the whole cycle, and repo-wide gates (CodeQL alert count, ratchet baselines)
# turn EVERY PR into main red on a check unrelated to its diff. This detects that and
# opens a "🔴 main not green" tracking issue. The PREVENTION is the companion-PR reflex
# (Hard Rule #21 area / _shared/merge-gates.md §8); this is the automated backstop.
main-green:
name: Validate main branch
# On a push, only run for a push to main — a push to release/* is handled by
# release-green above. Dispatch always runs. On schedule, only the 05:23 cron sweeps
# main: main's SHA only moves on a release or hotfix, so the midday and evening sweeps
# re-validated the same commit and held the single `omni-release` slot for ~2 h each
# (2026-10-19: 08:04–10:01 right after the 2 h20 release sweep, while a `--quick` push
# run waited ~4 h in the group). The release branch keeps all three sweeps.
# On push the three jobs above are skipped; !cancelled() keeps this job from being skipped
# with them, and on schedule/dispatch it still reports when a suite job failed.
needs: [resolve-target, resolve-main, main-suites]
if: ${{ !cancelled() && (github.event_name != 'push' || github.ref_name == 'main') && (github.event_name != 'schedule' || (github.repository == 'cheaper-inference/OmniRoute' && github.event.schedule == '23 5 * * *')) }}
# Own slot (docs/ops/RUNNER_BOX.md): `omni-release` is omniroute-113-6 only, so the
# validation no longer queues on the single `omni-build` slot (the 2026-10-18 05:29
# sweep waited 6 h for it). That slot is capped at 24 GB, so the validation's build
# runs on webpack (~14-16 GB); Turbopack fidelity stays with ci.yml's Build on
# `omni-build` and with the npm publish.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && fromJSON('["self-hosted","omni-release"]')) || 'ubuntu-latest' }}
env:
OMNIROUTE_USE_TURBOPACK: "0"
JWT_SECRET: ci-nightly-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-nightly-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.event_name == 'push' && github.sha || needs.resolve-main.outputs.sha || 'main' }}
fetch-depth: 0
persist-credentials: false
- name: Record validated revision
id: revision
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
# hostedSuiteIdentity compares nodeVersion exactly, so match the hosted suites' runtime.
- uses: actions/setup-node@v7
with:
node-version: ${{ needs.resolve-target.outputs.node-version || '24' }}
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Collect the hosted suite results
if: github.event_name != 'push'
continue-on-error: true
uses: actions/download-artifact@v8
with:
# A partial re-run cannot reuse receipts from an earlier attempt;
# rerun all suite jobs for a new complete observation of the same tip.
pattern: main-green-suite-${{ github.run_attempt }}-*
path: suite-results
merge-multiple: true
# main can predate the installer: obtain tooling from the workflow SHA.
- name: Prepare pinned workflow scanners
id: workflow_scanners
env:
WORKFLOW_SHA: ${{ github.workflow_sha }}
run: |
set -euo pipefail
installer=$(mktemp "${RUNNER_TEMP:?}/workflow-scanners-installer.XXXXXX")
git show "${WORKFLOW_SHA}:scripts/ci/install-workflow-scanners.sh" > "$installer"
bash "$installer"
- name: Main-green validation
id: validate
env:
EVENT_NAME: ${{ github.event_name }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
run: |
set +e
# push (a merge into main) → --quick fast HARD gates; schedule/dispatch → full sweep.
if [ "$EVENT_NAME" = "push" ]; then
MODE="--quick"
else
# unit/integration/vitest ran in the hosted `main-suites` jobs; a missing result fails
mkdir -p suite-results
MODE="--with-build --full-ci --suites-from suite-results"
fi
echo "[main-green] mode: $MODE (event: $EVENT_NAME)"
# MODE is an intentional flag list, so word-splitting is wanted here
# shellcheck disable=SC2086
node scripts/quality/validate-release-green.mjs --json --hermetic $MODE \
--suites-workflow-sha "$GITHUB_WORKFLOW_SHA" \
1> main-green.json 2> main-green.log
validation_exit=$?
node scripts/ci/release-green-result.mjs main-green.json "$validation_exit" "$VALIDATED_SHA" "$EVENT_NAME" >> main-green.log
echo "------- report -------"
cat main-green.log
- name: Open / update tracking issue on HARD failure
if: steps.validate.outputs.exit != '0'
env:
GH_TOKEN: ${{ github.token }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
EVENT_NAME: ${{ github.event_name }}
run: |
set -euo pipefail
TITLE="🔴 main branch not green"
{
echo "The **main-green** validation found HARD failures on \`main\`."
echo ""
echo "Because \`main\` only receives merged work at the release squash, a gate/infra"
echo "fix that landed only on the release branch leaves \`main\` broken for the whole"
echo "cycle — and repo-wide gates (CodeQL alert count, ratchet baselines) then turn"
echo "**every open PR into main** red on a check unrelated to its diff. The fix is a"
echo "companion PR \`--base main\` carrying the release-side fix (see"
echo "\`_shared/merge-gates.md\` §8), NOT chasing each contributor PR."
echo ""
echo "**Run:** ${RUN_URL} (mode: ${EVENT_NAME})"
echo ""
echo '```'
if grep -q '──────── verdict ────────' main-green.log; then
sed -n '/──────── verdict ────────/,$p' main-green.log
else
tail -40 main-green.log
fi
echo '```'
echo ""
echo "_Ratchet drift (eslint warnings / cognitive-complexity / file-size) is expected mid-cycle and did NOT, on its own, open this issue._"
} > issue-body.md
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title $TITLE" --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING" ]; then
gh issue comment "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file issue-body.md
echo "Updated existing issue #$EXISTING"
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --label base-red --body-file issue-body.md
fi
- name: Close tracking issue when the branch is green again
if: steps.validate.outputs.exit == '0' && github.event_name != 'push'
env:
GH_TOKEN: ${{ github.token }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
CURRENT_SHA=$(git ls-remote origin refs/heads/main | cut -f1)
if [ "$CURRENT_SHA" != "$VALIDATED_SHA" ]; then
echo "Branch advanced; retaining the tracking issue."
exit 0
fi
# The open/update step above is the UPWARD half of the loop; without this
# step a stale "not green" issue outlives the fix and every base-green check
# (`AGENTS.md` → "Base-green check") keeps stamping new PRs as base-red inherited.
TITLE="🔴 main branch not green"
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title $TITLE" --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING" ]; then
gh issue close "$EXISTING" --repo "$GITHUB_REPOSITORY" --reason completed \
--comment "✅ \`main\` is main-green again at \`${VALIDATED_SHA}\` — ${RUN_URL}. Auto-closed after full validation of the current branch."
echo "Closed issue #$EXISTING"
fi
# Same best-effort contract as the release-green report upload above.
- name: Upload report artifact
if: always()
continue-on-error: true
uses: actions/upload-artifact@v7
with:
name: main-green-report
path: |
main-green.json
main-green.log
_artifacts/release-green/
if-no-files-found: error
retention-days: 14
- name: Enforce validation verdict
if: always()
env:
VALIDATION_EXIT: ${{ steps.validate.outputs.exit }}
VALIDATED_SHA: ${{ steps.revision.outputs.sha }}
EVENT_NAME: ${{ github.event_name }}
run: node scripts/ci/release-green-result.mjs main-green.json "$VALIDATION_EXIT" "$VALIDATED_SHA" "$EVENT_NAME"
# ── Banking lane (#8584) ──────────────────────────────────────────────────
# The ratchet is asymmetric: RAISING a cap is a ten-second manual JSON edit made
# under merge pressure, LOWERING one requires someone to run `--update` and commit
# — which no workflow does. Grep `.github/workflows/` for `--update`: only
# wiki-sync.yml (unrelated) and ci.yml's check-quality-ratchet.mjs --require-tighten
# (a different script, a different metric). So a cap outlives the code that earned
# it and every completed decomposition silently becomes a growth allowance for
# whoever touches the file next. Measured on 2026-07-25: 18 frozen files already at
# or under the 800-line new-file cap, up to 132x (schemas.ts, 19 lines / 2523 cap),
# and 31 unfulfilled "tighten via --update next cycle" notes honoured exactly once
# (-1 unit) in six weeks.
#
# This job closes that loop by making the DOWNWARD direction as automatic as the
# upward one is easy. It measures the active release branch, runs the shrink-only
# `--update` paths, and opens ONE always-current PR with the result. It never
# pushes to release/* — a human still merges, so a bad measurement cannot land
# unreviewed. verify-ratchet-bank.mjs is the hard guarantee that the automation can
# only ever write in the shrink direction; if anything was raised, added, or a
# rebaseline note was touched, the job aborts and opens nothing.
#
# Schedule/dispatch only, deliberately NOT on push: banking has no latency
# requirement (a shrink banked within 8h is fine) and a per-merge run would rebuild
# the PR branch repeatedly during merge campaigns while paying for a full ESLint
# walk each time. Detection stays on push (release-green above); banking is batched.
bank-ratchet-shrinks:
name: Bank ratchet shrinks
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Resolve active release branch
id: branch
env:
INPUT_BRANCH: ${{ github.event.inputs.branch }}
run: |
set -euo pipefail
if [ -n "${INPUT_BRANCH:-}" ]; then
TARGET="$INPUT_BRANCH"
else
TARGET=$(git for-each-ref --format='%(refname:short)' 'refs/remotes/origin/release/v*' \
| sed 's#origin/##' \
| sort -t/ -k2 -V \
| tail -1)
fi
if [ -z "$TARGET" ]; then echo "No release/v* branch found"; exit 1; fi
# Same strict guard as the validation job — blocks ref/command injection
# through the workflow_dispatch input.
if ! printf '%s' "$TARGET" | grep -qE '^release/v[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "Refusing non-canonical branch name: $TARGET"; exit 1
fi
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
echo "bank_branch=chore/bank-ratchet-${TARGET#release/}" >> "$GITHUB_OUTPUT"
- name: Checkout the release branch
env:
TARGET: ${{ steps.branch.outputs.target }}
run: |
set -euo pipefail
git checkout "$TARGET"
git log -1 --oneline
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Ratchet the baselines down
run: |
# Both --update paths are shrink-only by construction (file-size writes only
# on `improvements`, complexity-ratchets only when `.improved`), and both exit
# non-zero while the branch is over baseline — which is exactly when there is
# nothing to bank. Their exit code is not the signal; the verifier below is.
# Velocity phase (quality-baseline.json `_policy`, relax-baselines.mjs): the caps
# were raised on purpose, so banking the measured shrink would silently undo the
# 20% headroom every night. Pause the downward ratchet until the phase closes.
if node -e 'process.exit(require("./config/quality/quality-baseline.json")._policy?.phase === "velocity" ? 0 : 1)'; then
echo "Velocity phase active — ratchet banking paused (see docs/architecture/QUALITY_GATES.md → Velocity phase)."
exit 0
fi
set +e
node scripts/check/check-file-size.mjs --update
node scripts/check/check-complexity-ratchets.mjs --update
exit 0
- name: Verify the write only went downward
id: verify
run: |
set -euo pipefail
# Exits 1 if ANYTHING was raised/added or a rebaseline note was touched.
# `set -e` then aborts the job before a commit exists — no PR is opened.
node scripts/quality/verify-ratchet-bank.mjs > bank-summary.md
if [ -n "$(git status --porcelain config/quality/)" ]; then
echo "changed=true" >> "$GITHUB_OUTPUT"
else
echo "changed=false" >> "$GITHUB_OUTPUT"
echo "Nothing to bank — baselines already match the code."
fi
- name: Open / update the banking PR
if: steps.verify.outputs.changed == 'true'
env:
GH_TOKEN: ${{ github.token }}
TARGET: ${{ steps.branch.outputs.target }}
BANK_BRANCH: ${{ steps.branch.outputs.bank_branch }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git checkout -B "$BANK_BRANCH"
git add config/quality/
git commit -m "chore(quality): bank ratchet shrinks measured on ${TARGET}"
git push --force origin "$BANK_BRANCH"
{
echo "Automated banking of quality-ratchet **shrinks** already present in"
echo "\`${TARGET}\` — the downward half of the ratchet, which nothing else runs (#8584)."
echo ""
echo "Produced by \`check:file-size --update\` + \`check:complexity-ratchets --update\`,"
echo "then verified by \`scripts/quality/verify-ratchet-bank.mjs\`: **nothing was raised,"
echo "nothing was added, no rebaseline note was touched** — the job aborts without"
echo "opening a PR if any of those is violated."
echo ""
echo "No product code changes. Merging retires growth allowances that the code no"
echo "longer needs; not merging leaves them available to whoever edits those files next."
echo ""
cat bank-summary.md
echo ""
echo "**Run:** ${RUN_URL}"
} > pr-body.md
EXISTING=$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$BANK_BRANCH" \
--state open --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING" ]; then
gh pr edit "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file pr-body.md
echo "Updated existing PR #$EXISTING"
else
gh pr create --repo "$GITHUB_REPOSITORY" --base "$TARGET" --head "$BANK_BRANCH" \
--title "chore(quality): bank ratchet shrinks (${TARGET})" --body-file pr-body.md
fi
# ── Baseline headroom (velocity phase, 2026-08-30 → v4.0) ──────────────────────
# The ratchets only speak when a baseline is crossed. With every baseline loosened by
# 20% (scripts/quality/relax-baselines.mjs) the question is how fast the budget is
# being consumed — this job measures each gate the way CI does and publishes the
# headroom table in the run summary and retained artifacts. Keep recurring reports
# out of the issue queue; the existing quality gates still enforce their budgets.
baseline-headroom:
name: Baseline headroom
if: ${{ github.event_name != 'push' && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
timeout-minutes: 60
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 1
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Measure headroom on ${{ github.ref_name }}
run: |
set -euo pipefail
node scripts/quality/baseline-headroom.mjs \
--json reports/quality/headroom.json --md reports/quality/headroom.md
cat reports/quality/headroom.md >> "$GITHUB_STEP_SUMMARY"
- name: Upload headroom report
if: always()
uses: actions/upload-artifact@v7
with:
name: baseline-headroom-${{ github.run_id }}
path: reports/quality/headroom.*
retention-days: 90

View File

@@ -1,245 +0,0 @@
name: Nightly Resilience
on:
schedule:
- cron: "41 4 * * *"
workflow_dispatch:
permissions:
contents: read
jobs:
heap:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Heap-growth gate
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- run: npm run test:heap
chaos:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Resilience chaos (fault injection)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- run: npm run test:chaos
k6-soak:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: k6 load/soak
# #11965: this job runs a backend-only `next build`; the hosted 7 GB runner cannot build
# release/v3.8.51 (VM shutdown ~7 min in), so it targets the box's light pool (`omni-light`:
# two listeners, jobs ≤ ~6 GB). Falls back to hosted when USE_VPS_RUNNER is off.
# #16853: on hosted it died in `npm run build:cli` 8 nights out of 8 ("The runner has
# received a shutdown signal").
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
# Fresh runtime state per run (same contract as nightly-llm-security.yml). The
# omni-light runner keeps a persistent $HOME, so a server booted without DATA_DIR
# lands on $HOME/.omniroute, where a database left by older runs can sit far behind
# the tip's migrations: the mass-migration guard (#3416) refuses to migrate it and
# the server never becomes healthy. A DATA_DIR under $RUNNER_TEMP is a new database
# every run, so every migration applies and nothing on the box is touched.
- name: Prepare isolated runtime state
id: runtime
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-k6-soak.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Build CLI bundle
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
OMNIROUTE_BUILD_BACKEND_ONLY: "1"
OMNIROUTE_USE_TURBOPACK: "0"
run: npm run build:cli
# Own port: this box also hosts the deployed server on 20128. A test server that
# dies on EADDRINUSE must NOT let the soak fall through to whatever else answers
# there, and a soak against nothing must not go green — the health wait fails the
# job (same contract as nightly-llm-security.yml). Auto-backups stay off: one
# pre-migration backup per boot piles up under the runner's home.
- name: Start OmniRoute (background)
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
PORT: "21776"
DISABLE_SQLITE_AUTO_BACKUP: "true"
run: |
node dist/server.js > server.log 2>&1 &
echo $! > server.pid
for i in $(seq 1 60); do
if curl -sf http://localhost:21776/api/monitoring/health >/dev/null; then echo "server up"; exit 0; fi
sleep 2
done
echo "::error::Test server did not come up on 21776 in 120s — see server.log. Refusing to run the soak against an unknown target."
tail -40 server.log || true
exit 1
- name: Install k6
uses: grafana/setup-k6-action@v1
- name: Run k6 soak
run: k6 run tests/load/k6-soak.js
env:
BASE_URL: http://localhost:21776
SOAK_DURATION: "3m"
SOAK_VUS: "10"
- name: Stop server
if: always()
run: kill "$(cat server.pid)" || true
a11y-build:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: A11y build (production artefact, omni-build)
# #16853: the a11y suite needs a production build of the FULL dashboard, and that build
# does not fit the light pool the a11y job runs on (Turbopack reaches ~40 GB RSS on the
# `.113`, #16169; webpack needs a >= 10 GB V8 heap for this tree). Build it once on the
# build pool — same runner class and Turbopack policy as ci.yml's `build` job — and hand
# the artefact to the a11y job, which only boots it. Falls back to hosted (webpack) when
# the VPS build runner is off, like ci.yml.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true') && fromJSON('["self-hosted","omni-build"]') || 'ubuntu-latest' }}
timeout-minutes: 60
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: "24"
cache: npm
# Page-data collection imports server modules that open the database: keep it in a
# fresh DATA_DIR, never the self-hosted runner's persistent $HOME (same contract as
# the k6 job above and nightly-llm-security.yml).
- name: Prepare isolated runtime state
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-a11y-build.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Build Next.js (production)
run: npm run build
env:
OMNIROUTE_USE_TURBOPACK: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true') && '1' || '0' }}
# Same archive contract as ci.yml's build -> test-e2e hand-off: tar keeps the paths
# relative to the checkout (.build/next/...), the build cache stays out.
- name: Archive the build for the a11y job
run: |
tar -czf "$RUNNER_TEMP/a11y-build.tar.gz" \
--exclude='.build/next/cache' \
.build/next
- name: Upload the build for the a11y job
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: a11y-next-build
path: ${{ runner.temp }}/a11y-build.tar.gz
retention-days: 1
a11y:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: A11y axe (nightly, freeze-and-alert)
needs: a11y-build
# Boots the production build made by `a11y-build` (no self-build here: #16853) and runs
# the axe suite against it. Hosted, always: on the light pool the 1.2 GB artefact took
# 1,416 s to download and the 30-minute timeout cancelled the job before axe ran (run
# 39156364797, 2026-10-18), after it had already queued 80 min behind lint-guard jobs.
# Hosted runners pull the same class of artefact in seconds (the per-PR E2E shards), a
# standalone server fits them, and a fresh VM has no port or $HOME left by other jobs.
# REQUIRE_AXE=1 makes the suite run the real axe analysis (the 4 page tests are gated to
# nightly so per-PR e2e stays fast) and makes the meta-test fail loudly if
# @axe-core/playwright ever goes missing.
runs-on: ubuntu-latest
timeout-minutes: 30
env:
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-test-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
REQUIRE_AXE: "1"
# Own a port the rest of the box cannot steal. This job ran on the default
# 20128 and failed 9 of 10 nights two ways: "http://localhost:20128/
# api/monitoring/health is already used" when the deployed server (or a
# concurrent runner job) answered first (runs 35688196787, 35562389397),
# and a 900 s webServer timeout under listener contention (run
# 35819784314). DASHBOARD_PORT drives playwright.config's readiness URL,
# PORT drives the server the webServer script boots — both set, same value.
DASHBOARD_PORT: "21777"
PORT: "21777"
# The webServer only boots the downloaded standalone build (same switch the per-PR
# test-e2e shards use), so its window covers a boot, not a build.
OMNIROUTE_PLAYWRIGHT_SKIP_BUILD: "1"
OMNIROUTE_PLAYWRIGHT_WEB_SERVER_TIMEOUT: "600000"
# Send the server's stdout to the job log: the 2026-10-18 failure was a 30-minute
# silent wait because Playwright discards webServer stdout by default.
OMNIROUTE_PLAYWRIGHT_WEB_SERVER_STDOUT: "pipe"
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
# The server this job boots must not open the runner's persistent $HOME/.omniroute:
# a database left there by older runs sits behind the tip's migrations and the
# mass-migration guard (#3416) keeps the server from ever becoming healthy.
- name: Prepare isolated runtime state
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-a11y.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Cache Playwright browsers
uses: actions/cache@v6.1.0
with:
path: ~/.cache/ms-playwright
key: playwright-chromium-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: playwright-chromium-${{ runner.os }}-
- run: npx playwright install --with-deps chromium
- name: Download the production build
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: a11y-next-build
path: next-build-artifact
- name: Extract the production build
run: tar -xzf next-build-artifact/a11y-build.tar.gz
- name: Run axe a11y suite (prebuilt standalone server)
run: npx playwright test tests/e2e/a11y.spec.ts

View File

@@ -1,111 +0,0 @@
name: Nightly Schemathesis
on:
schedule:
- cron: "23 4 * * *"
workflow_dispatch:
permissions:
contents: read
jobs:
schemathesis:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Schemathesis — OpenAPI contract fuzz (advisory)
# #11965: this job runs a backend-only `next build`; the hosted 7 GB runner cannot build
# release/v3.8.51 (VM shutdown ~7 min in), so it targets the box's light pool (`omni-light`:
# two listeners, jobs ≤ ~6 GB). Falls back to hosted when USE_VPS_RUNNER is off.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
# 2026-10-17: the webpack backend-only build alone took >25 min on the busy .113 and the
# old 30-minute cap cancelled the job before the probes started (run 38982564979).
timeout-minutes: 120
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with: { node-version: "24", cache: npm }
- name: Prepare isolated runtime state
id: runtime
run: |
data_dir=$(mktemp -d "$RUNNER_TEMP/omniroute-schemathesis.XXXXXX")
mkdir "$data_dir/plugins"
{
echo "DATA_DIR=$data_dir"
echo "OMNIROUTE_PLUGINS_DIR=$data_dir/plugins"
} >> "$GITHUB_ENV"
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Build CLI bundle
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
OMNIROUTE_BUILD_BACKEND_ONLY: "1"
OMNIROUTE_USE_TURBOPACK: "0"
run: npm run build:cli
- name: Start OmniRoute (background)
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
HOSTNAME: "127.0.0.1"
PORT: "21780"
run: |
# A persistent runner can already host another deployment. Never fuzz it.
if (echo > /dev/tcp/127.0.0.1/"$PORT") 2>/dev/null; then
echo "::error::Port $PORT is already occupied; refusing to probe another server."
exit 1
fi
node dist/server.js > server.log 2>&1 &
server_pid=$!
echo "$server_pid" > "$DATA_DIR/server.pid"
for _ in $(seq 1 30); do
if ! kill -0 "$server_pid" 2>/dev/null; then
echo "::error::OmniRoute exited before becoming ready; see server.log."
exit 1
fi
if curl --max-time 2 -sf "http://127.0.0.1:$PORT/api/monitoring/health" >/dev/null && kill -0 "$server_pid" 2>/dev/null; then
echo "server up"
exit 0
fi
sleep 2
done
echo "::error::OmniRoute did not become healthy after 30 attempts; see server.log."
exit 1
- uses: actions/setup-python@v7
with: { python-version: "3.12" }
- name: Install schemathesis
run: pip install schemathesis
- name: Schemathesis contract fuzz (advisory)
# Advisory gate: never fails the job. `continue-on-error` covers a crash of the
# step itself; `|| true` covers schemathesis exiting non-zero when it finds spec
# violations / upstream 500s — both are expected here (most /v1 endpoints proxy an
# upstream that has no provider configured in CI). The point of the nightly is to
# PROVE the contract is fuzzable and surface regressions, not to gate the build.
continue-on-error: true
run: |
schemathesis run docs/openapi.yaml \
--url http://127.0.0.1:21780 \
--max-examples 20 \
--workers 4 \
--checks all \
--max-response-time 30 \
--request-timeout 30 \
--suppress-health-check all \
--report junit \
--report-junit-path schemathesis-report/junit.xml \
--no-color \
|| true
- name: Stop server
if: always() && steps.runtime.outcome == 'success'
run: |
if [ -n "$DATA_DIR" ] && [ -f "$DATA_DIR/server.pid" ]; then
kill "$(cat "$DATA_DIR/server.pid")" || true
fi
- name: Upload schemathesis report
if: always()
uses: actions/upload-artifact@v7
with:
name: schemathesis-report
path: |
schemathesis-report/
server.log
if-no-files-found: warn
retention-days: 14

View File

@@ -1,176 +0,0 @@
name: Nightly v4 build (dormant)
# DORMANT until the 3.9.0 LTS cut creates `develop` (docs/ops/RELEASE_STRATEGY.md →
# channel `nightly`). The first job checks `git ls-remote --heads origin develop`
# and ends the run green and silent while the branch does not exist.
#
# When develop exists: compute `<core>-nightly.<YYYYMMDD>.<sha7>` with
# scripts/release/compute-nightly-version.mjs, build the release bundle, validate
# the pack artifact and keep the tarball as a workflow artifact. Publishing to npm
# under the `nightly` dist-tag happens ONLY when the repository variable
# `NIGHTLY_PUBLISH` is exactly 'true' — and additionally requires npm Trusted
# Publishing to accept this workflow file (npmjs.com → package settings), since
# today it is configured for npm-publish.yml only.
on:
schedule:
- cron: "23 4 * * *" # 04:23 UTC daily
workflow_dispatch:
permissions:
contents: read
concurrency:
group: nightly-v4-build
cancel-in-progress: false
env:
NIGHTLY_NODE_VERSION: "24"
jobs:
detect:
name: Detect develop
# Upstream-only for scheduled runs (check-workflows scheduled-guard).
if: (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute')
runs-on: ubuntu-latest
permissions: {}
outputs:
exists: ${{ steps.develop.outputs.exists }}
steps:
- name: Check that develop exists
id: develop
env:
REPO_URL: ${{ github.server_url }}/${{ github.repository }}.git
run: |
set -euo pipefail
if [ -n "$(git ls-remote --heads "$REPO_URL" develop)" ]; then
echo "exists=true" >> "$GITHUB_OUTPUT"
else
echo "exists=false" >> "$GITHUB_OUTPUT"
echo "develop does not exist yet — nightly v4 build is dormant, nothing to do."
fi
build:
name: Build nightly
needs: detect
if: (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') && needs.detect.outputs.exists == 'true'
# Same dynamic-runner rule as npm-publish.yml: a full `next build` outgrew the
# 16 GB hosted runner during v3.8.49. Never runs on pull_request.
runs-on: ${{ vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && fromJSON('["self-hosted","omni-build"]') || 'ubuntu-latest' }}
permissions:
contents: read
outputs:
version: ${{ steps.version.outputs.version }}
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
steps:
- name: Checkout develop
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: develop
fetch-depth: 0
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: ${{ env.NIGHTLY_NODE_VERSION }}
package-manager-cache: false
- name: Compute nightly version
id: version
run: |
set -euo pipefail
# The schedule's GITHUB_SHA is the default branch, not develop — use HEAD.
HEAD_SHA=$(git rev-parse HEAD)
VERSION=$(node scripts/release/compute-nightly-version.mjs --sha "$HEAD_SHA")
# Defense in depth: the computed version must resolve to the nightly channel.
TAG=$(node scripts/release/dist-tag.mjs --version "$VERSION" --requested auto < /dev/null)
if [ "$TAG" != "nightly" ]; then
echo "Computed $VERSION resolves to dist-tag '$TAG', expected 'nightly'" >&2
exit 1
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "📦 omniroute@$VERSION (dist-tag=nightly)"
- name: Install dependencies
uses: ./.github/actions/npm-ci-retry
with:
cache: "false" # a publishable artifact never restores node_modules from cache
- name: Stamp the nightly version
env:
VERSION: ${{ steps.version.outputs.version }}
run: npm version "$VERSION" --no-git-tag-version --allow-same-version
- name: Build release bundle
run: npm run build:release
- name: Validate npm package artifact
env:
# The provenance guard checks ancestry against origin/main by default; a
# nightly is cut from develop.
OMNIROUTE_RELEASE_REF: origin/develop
run: npm run check:pack-artifact
- name: Pack the tarball
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
set -euo pipefail
npm pack --ignore-scripts
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "expected $TARBALL after npm pack" >&2; ls -la ./*.tgz || true; exit 1; }
- name: Upload nightly tarball
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: npm-nightly-tarball
path: omniroute-${{ steps.version.outputs.version }}.tgz
retention-days: 7
if-no-files-found: error
publish:
name: Publish nightly to npm
needs: build
if: (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') && vars.NIGHTLY_PUBLISH == 'true'
runs-on: ubuntu-latest # Trusted Publishing (OIDC) requires a GitHub-hosted runner
permissions:
contents: read
id-token: write # npm provenance + Trusted Publishing
steps:
- name: Download nightly tarball
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: npm-nightly-tarball
path: .
- name: Setup Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: ${{ env.NIGHTLY_NODE_VERSION }}
registry-url: https://registry.npmjs.org
package-manager-cache: false
- name: Ensure npm supports Trusted Publishing
run: |
set -euo pipefail
if ! node -e "const [a,b]=process.argv[1].split('.').map(Number); process.exit(a>11||(a===11&&b>=15)?0:1)" "$(npm --version)"; then
# Pinned exact version (supply-chain: never float @latest in a publish job).
npm install -g --ignore-scripts npm@11.15.0
fi
npm --version
- name: Publish with --tag nightly
env:
VERSION: ${{ needs.build.outputs.version }}
run: |
set -euo pipefail
case "$VERSION" in
*-nightly.*) ;;
*) echo "Refusing to publish non-nightly version '$VERSION' from the nightly workflow" >&2; exit 1 ;;
esac
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "tarball $TARBALL did not arrive from the build job" >&2; exit 1; }
npm publish "$TARBALL" --provenance --access public --tag nightly --ignore-scripts
echo "✅ Published omniroute@$VERSION (dist-tag=nightly)"

View File

@@ -1,11 +1,8 @@
name: Publish to npm
on:
# 'released' (not 'published') so editing/re-publishing old releases does NOT
# re-trigger this workflow. Pairs with the semver guard below as defense in
# depth against accidental dist-tag clobbering by old releases.
release:
types: [released]
types: [published]
workflow_dispatch:
inputs:
version:
@@ -13,26 +10,13 @@ on:
required: true
type: string
tag:
description: "npm dist-tag (auto / latest / next / nightly / lts / historic)"
description: "npm dist-tag (latest / next)"
required: false
default: "auto"
default: "latest"
type: choice
options:
- auto
- latest
- next
- nightly
- lts
- historic
publish_mode:
description: "auto = publish through npm Trusted Publishing (OIDC, no token, no 2FA prompt — the default); staged = npm stage publish (owner approves with 2FA); direct = legacy token publish (emergency fallback only)"
required: false
default: "auto"
type: choice
options:
- auto
- staged
- direct
workflow_call:
inputs:
version:
@@ -40,627 +24,103 @@ on:
required: true
type: string
tag:
description: "npm dist-tag (auto / latest / next / nightly / lts / historic)"
description: "npm dist-tag (latest / next)"
required: false
default: "auto"
default: "latest"
type: string
secrets:
NPM_TOKEN:
required: true
# Least-privilege default: read-only at the top level; each publish job grants the
# id-token (npm provenance) / packages (GitHub Packages) writes it needs (Scorecard
# TokenPermissions).
permissions:
contents: read
env:
NPM_PUBLISH_NODE_VERSION: "24"
id-token: write
packages: write
jobs:
publish:
# Same dynamic-runner rule as ci.yml's `build`/`test-unit`: `build:cli` falls back to a
# full `next build`, whose working set outgrew the 16 GB hosted runner during the
# v3.8.49 cycle — the publish died with "The runner has received a shutdown signal"
# mid-"Creating an optimized production build" while v3.8.48 had still fit in 16min.
# This job never runs on `pull_request`, so the fork-safety clause is always true here;
# it is kept verbatim so the expression stays greppable against ci.yml.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && fromJSON('["self-hosted","omni-build"]') || 'ubuntu-latest' }}
outputs:
version: ${{ steps.resolve.outputs.version }}
tag: ${{ steps.resolve.outputs.tag }}
skip: ${{ steps.resolve.outputs.skip }}
permissions:
actions: read # find + download the CI run's next-build artifact for this SHA
contents: write # gh release upload (attach SBOM to the GitHub Release)
id-token: write # npm provenance (GitHub Packages step)
packages: write # publish to npm.pkg.github.com
runs-on: ubuntu-latest
environment: NPM_TOKEN
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
# Need full tag history to compare against highest semver when
# deciding whether this release should claim dist-tag `latest`.
fetch-depth: 0
uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v7
uses: actions/setup-node@v6
with:
node-version: ${{ env.NPM_PUBLISH_NODE_VERSION }}
node-version: 22
registry-url: https://registry.npmjs.org
- name: Install dependencies (skip scripts to avoid heavy build)
run: npm install --ignore-scripts --no-audit --no-fund
- name: Resolve version, dist-tag and skip flag
- name: Resolve version and dist-tag
id: resolve
env:
EVENT_NAME: ${{ github.event_name }}
REF_NAME: ${{ github.ref_name }}
INPUT_VERSION: ${{ inputs.version }}
INPUT_TAG: ${{ inputs.tag }}
run: |
set -euo pipefail
# 1) Resolve VERSION from the trigger (all inputs come via env).
VERSION="${INPUT_VERSION:-}"
if [ -z "$VERSION" ] && [ "$EVENT_NAME" = "release" ]; then
VERSION="$REF_NAME"
fi
case "${{ github.event_name }}" in
workflow_dispatch|workflow_call)
VERSION="${{ inputs.version }}"
TAG="${{ inputs.tag }}"
;;
release)
VERSION="${GITHUB_REF_NAME}"
;;
esac
# Strip v prefix if present
VERSION="${VERSION#v}"
if ! printf '%s' "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+([.-][A-Za-z0-9.-]+)?$'; then
echo "Refusing to publish unsafe VERSION value: $VERSION" >&2
exit 1
# Default dist-tag logic
if [ -z "$TAG" ]; then
if [[ "$VERSION" == *-* ]]; then
TAG="next"
else
TAG="latest"
fi
fi
# 2) Resolve dist-tag via scripts/release/dist-tag.mjs (single source of the
# channel rules in docs/ops/RELEASE_STRATEGY.md; tests/unit/
# compute-nightly-version.test.ts pins every decision):
# - explicit 'latest'/'next'/'nightly'/'lts'/'historic' is honored
# - 'auto' (or empty): `-nightly.*` → 'nightly' (never 'latest');
# rc/beta/alpha/pre/next and any other pre-release → 'next';
# stable versions → 'latest' only if VERSION is the highest stable
# `v*` tag; a stable of an OLDER major than the highest stable tag
# (3.9.x after the 4.0 GA) → 'lts' only if it is the highest of the
# older majors; anything else → 'historic' (never clobbers a channel).
# Values reach the script as quoted argv and stdin — never interpolated.
REQUESTED_TAG="${INPUT_TAG:-auto}"
test -f scripts/release/dist-tag.mjs || {
echo "scripts/release/dist-tag.mjs is missing from this checkout — refusing to guess a dist-tag." >&2
exit 1
}
git fetch --tags --quiet || true
TAG=$(git tag -l 'v[0-9]*' | node scripts/release/dist-tag.mjs --version "$VERSION" --requested "$REQUESTED_TAG")
if [ "$REQUESTED_TAG" = "auto" ] && [ "$TAG" = "historic" ]; then
echo "Version $VERSION is not the highest stable tag of its channel. Using dist-tag 'historic' to avoid clobbering @latest/@lts."
fi
# 3) Skip-if-already-published. NOTE: do NOT pass `--silent` to
# `npm view` — it suppresses stdout and breaks the grep, which
# caused old releases (3.2.8) to be re-published and steal
# dist-tag `latest`. See incident notes in CHANGELOG.
PUBLISHED="$(npm view "omniroute@${VERSION}" version 2>/dev/null || true)"
SKIP="false"
if [ "$PUBLISHED" = "$VERSION" ]; then
echo "⚠️ omniroute@${VERSION} is already on npm — skipping publish."
SKIP="true"
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "skip=$SKIP" >> "$GITHUB_OUTPUT"
echo "📦 Resolved omniroute@$VERSION dist-tag=$TAG skip=$SKIP"
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "tag=$TAG" >> $GITHUB_OUTPUT
echo "📦 Publishing omniroute@$VERSION with tag=$TAG"
- name: Sync package.json version
if: steps.resolve.outputs.skip != 'true'
env:
VERSION: ${{ steps.resolve.outputs.version }}
run: |
npm version "$VERSION" --no-git-tag-version --allow-same-version
# Fast path: CI already built the standalone tree for THIS commit and uploaded it as
# `next-build`. `build:cli` (scripts/build/prepublish.ts) only shells out to a full
# `next build` when `.build/next/standalone/server.js` is missing — restoring the
# artifact turns the heaviest step of the publish into a download. Matching on
# `head_sha` is the tree-equality guarantee: same commit, same tree.
# Best-effort by design (retention is 1 day): every miss falls through to the build
# step below, which is why the dynamic runner above matters as the backstop.
#
# The `head_repository.full_name == env.REPO` clause is a supply-chain guard, not a
# filter refinement. This artifact becomes the published npm tarball. `pull_request`
# runs from forks execute in THIS repository's context and upload their own
# `next-build` built from fork-controlled source, and the runs API returns them for a
# matching `head_sha` — 57 such runs exist in this repo today. Without the clause,
# anything that made a fork's head commit coincide with the publish commit could put
# attacker-built bytes on npm. Requiring the run to originate from this repository
# excludes every fork run while keeping the fast path intact (verified: the same
# single run is selected either way for the current tip).
# CodeQL: actions/artifact-poisoning/critical.
- name: Reuse CI's next-build artifact (skips the heavy rebuild)
if: steps.resolve.outputs.skip != 'true'
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HEAD_SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
run: |
set -uo pipefail
# The question is "which run HAS the artifact", not "which run passed" (gap 16).
# Requiring `conclusion == "success"` on the whole run discarded a perfectly good tree
# whenever any unrelated shard went red — one flaky test then pushed the publish into
# the 40-minute build this step exists to avoid. The artifact is only uploaded if the
# Build job itself succeeded, so its PRESENCE is the accurate signal; the run's overall
# conclusion is noise from jobs that have nothing to do with the tree.
#
# `head_repository.full_name == env.REPO` stays, and it is not a filter refinement:
# this tree becomes the published npm tarball, and fork `pull_request` runs execute in
# THIS repository's context uploading their own next-build. That clause is the
# supply-chain guard (CodeQL actions/artifact-poisoning).
CANDIDATES=$(gh api "repos/$REPO/actions/runs?head_sha=$HEAD_SHA&per_page=100" \
--jq '[.workflow_runs[]
| select(.name == "CI"
and .head_repository.full_name == env.REPO)]
| sort_by(.run_started_at) | reverse | .[0:5] | .[].id') || CANDIDATES=""
if [ -z "$CANDIDATES" ]; then
echo "::notice::no CI run from this repository for $HEAD_SHA — falling back to a full build"
exit 0
fi
RUN=""
# $RUNNER_TEMP, never /tmp: on the .113 pool /tmp is a 12 GB tmpfs (RAM). Parking
# this 1.3 GB artefact there took 27–32 min of the 76-min publish job — the
# same bytes upload from disk in 2 min. RUNNER_TEMP is per-runner and on disk.
for candidate in $CANDIDATES; do
if gh run download "$candidate" --repo "$REPO" --name next-build --dir "$RUNNER_TEMP/next-build" 2>/dev/null; then
RUN="$candidate"
break
fi
echo " run $candidate carries no usable next-build — trying the next"
done
if [ -z "$RUN" ]; then
echo "::notice::none of the candidate runs still carries next-build (1-day retention) — falling back to a full build"
exit 0
fi
tar -xzf "$RUNNER_TEMP/next-build/e2e-build.tar.gz" -C .
rm -rf "$RUNNER_TEMP/next-build"
if [ -f .build/next/standalone/server.js ]; then
echo "✅ standalone tree restored from CI run $RUN — build:cli will skip next build"
else
echo "::notice::extract did not yield .build/next/standalone — falling back to a full build"
rm -rf .build
fi
npm version "${{ steps.resolve.outputs.version }}" --no-git-tag-version --allow-same-version
- name: Build CLI bundle (standalone app)
if: steps.resolve.outputs.skip != 'true'
env:
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
run: npm run build:cli
run: node scripts/prepublish.mjs
# `build:cli` assembles dist/ but does NOT write dist/BUILD_SHA — only
# `build:release` does, by calling write-build-sha.mjs. The #10427 provenance
# guard inside check:pack-artifact rejects an artifact with no SHA (and rejects
# it even under OMNIROUTE_ALLOW_CANARY_BUILD=1: what cannot be identified cannot
# be vouched for). Without this step the build+validate pair in this job is
# structurally incompatible and fails 100% of the time — the same gap that was
# fixed in ci.yml's Package Artifact job.
- name: Stamp dist/BUILD_SHA for the provenance guard (#10427)
if: steps.resolve.outputs.skip != 'true'
env:
OMNIROUTE_BUILD_SHA: ${{ github.sha }}
- name: Publish to npm
run: |
export OMNIROUTE_BUILD_SHA="${OMNIROUTE_BUILD_SHA:0:7}"
node scripts/build/write-build-sha.mjs
# The guard checks ancestry against origin/main by default, which is correct
# here (a release tag is cut from main), but the ref has to exist locally for
# `git merge-base` to resolve it.
- name: Fetch main for the provenance probe
if: steps.resolve.outputs.skip != 'true'
run: git fetch --no-tags --depth=50 origin +refs/heads/main:refs/remotes/origin/main
- name: Validate npm package artifact
if: steps.resolve.outputs.skip != 'true'
run: npm run check:pack-artifact
- name: Generate CycloneDX SBOM (npm)
if: steps.resolve.outputs.skip != 'true'
run: npx @cyclonedx/cyclonedx-npm --ignore-npm-errors --output-format JSON --output-file sbom-npm.cdx.json
- name: Upload SBOM (npm) as workflow artifact
if: steps.resolve.outputs.skip != 'true'
uses: actions/upload-artifact@v7
with:
name: sbom-npm
path: sbom-npm.cdx.json
if-no-files-found: error
- name: Attach SBOM to GitHub Release
# Not only on the `release` event: the v3.8.50 package shipped through a
# workflow_dispatch (staged publish, 11 attempts) and this step was skipped, so the
# GitHub Release carried no SBOM until it was attached by hand from the run's
# `sbom-npm` artifact. Attach whenever a release for the published tag exists.
if: steps.resolve.outputs.skip != 'true' && (github.event_name == 'release' || github.event_name == 'workflow_dispatch')
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ github.event_name == 'release' && github.ref_name || format('v{0}', inputs.version) }}
run: |
if ! gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
echo "::notice::no GitHub Release for $TAG yet — SBOM stays on the sbom-npm workflow artifact"
VERSION="${{ steps.resolve.outputs.version }}"
TAG="${{ steps.resolve.outputs.tag }}"
# Check if this version is already published — skip instead of failing with E403
if npm view "omniroute@${VERSION}" version --silent 2>/dev/null | grep -q "^${VERSION}$"; then
echo "⚠️ Version ${VERSION} is already published on npm — skipping."
exit 0
fi
gh release upload "$TAG" sbom-npm.cdx.json --repo "$GITHUB_REPOSITORY" --clobber
# WS1.2/WS1.3 (#7065 class): the artifact that is about to be published must
# BOOT. build:cli already assembled dist/ above; this packs+installs+boots the
# real tarball and fails the publish before anything reaches the registry.
- name: Boot-smoke the tarball before ANY publish
if: steps.resolve.outputs.skip != 'true'
run: npm run check:pack-boot
# The boot-smoke above proves a CLEAN install boots. It does not prove the path that
# actually broke us: installing over an existing version, where ~110 SQLite migrations
# run against a populated database. v3.8.48 shipped as a hotfix because the published
# 3.8.47 crashed on boot, and the v3.8.49 upgrade path was first exercised end-to-end
# by hand on a real 3.8.48 box (VPS .16) — after publishing, which is exactly backwards.
# Runs BEFORE `npm stage publish` so a broken upgrade never reaches the registry at all;
# a staged package that is never approved simply expires, with no `npm deprecate` needed.
- name: Prove clean-install AND upgrade-over-previous both boot
if: steps.resolve.outputs.skip != 'true'
# 60, not 30. This gate was added in #8953 and the 2026-08-27 v3.8.50 publish
# was the FIRST run to ever reach it — every earlier attempt died upstream, so
# its budget had never been measured against a real run. It then blew the limit
# on its debut: `npm pack` alone took 24m37s, leaving 5 minutes for two installs
# and two boots. 30 was a guess; 60 is sized to the one measurement we have.
timeout-minutes: 60
run: npm run check:install-upgrade
# WS1.3 (D2, v3.8.49 plan): STAGED publishing by default — `npm stage publish`
# parks the exact bytes on the registry WITHOUT making them installable; the
# owner then verifies and approves with 2FA (`npm stage approve`), moving the
# human gate to AFTER the proof instead of before it. Requires npm >= 11.15
# (staged publishing GA 2026-05-22). publish_mode=direct is the emergency
# fallback (legacy immediate publish) via workflow_dispatch.
- name: Ensure npm supports staged publishing
if: steps.resolve.outputs.skip != 'true' && (github.event_name != 'workflow_dispatch' || inputs.publish_mode != 'direct')
run: |
set -euo pipefail
CUR=$(npm --version)
if ! node -e "const [a,b]='$(npm --version)'.split('.').map(Number); process.exit(a>11||(a===11&&b>=15)?0:1)"; then
# Pinned exact version (supply-chain: never float @latest in the publish
# job); bump deliberately when a newer npm is required.
echo "npm $CUR < 11.15 — installing pinned npm 11.15.0 for staged publishing"
npm install -g --ignore-scripts npm@11.15.0
if [ "$TAG" = "latest" ]; then
npm publish --access public
else
npm publish --access public --tag "$TAG"
fi
npm --version
# The registry upload itself moved to the `stage-npm` job below: npm REFUSES
# `--provenance` from a self-hosted runner (422 "Unsupported GitHub Actions
# runner environment"), and the heavy verification above cannot move to a
# hosted one (16 GB is not enough for build:cli's next-build fallback — see
# this job's runs-on comment). So this job proves the bytes and hands them
# over; a tiny hosted job does the upload.
- name: Pack the verified tarball for the upload job
if: steps.resolve.outputs.skip != 'true'
echo "✅ Published omniroute@$VERSION (tag: $TAG)"
env:
VERSION: ${{ steps.resolve.outputs.version }}
run: |
set -euo pipefail
# --ignore-scripts: prepublishOnly would re-run build:cli-api && build:cli,
# rebuilding bytes this job has already built, validated and boot-smoked.
npm pack --ignore-scripts
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "expected $TARBALL to exist after npm pack" >&2; ls -la ./*.tgz || true; exit 1; }
echo "packed $TARBALL ($(du -h "$TARBALL" | cut -f1))"
- name: Hand the tarball to the hosted publish job
if: steps.resolve.outputs.skip != 'true'
uses: actions/upload-artifact@v7
with:
name: npm-tarball
path: omniroute-${{ steps.resolve.outputs.version }}.tgz
retention-days: 1
if-no-files-found: error
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Publish to GitHub Packages
if: steps.resolve.outputs.skip != 'true'
env:
VERSION: ${{ steps.resolve.outputs.version }}
TAG: ${{ steps.resolve.outputs.tag }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
VERSION="${{ steps.resolve.outputs.version }}"
TAG="${{ steps.resolve.outputs.tag }}"
echo "Configuring for GitHub Packages..."
echo "//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}" > .npmrc
npm pkg set name="@cheaper-inference/omniroute"
npm publish --registry=https://npm.pkg.github.com --tag "$TAG" \
|| echo "⚠️ omniroute@${VERSION} might already be published on GitHub Packages."
echo "//npm.pkg.github.com/:_authToken=${{ secrets.GITHUB_TOKEN }}" > .npmrc
npm pkg set name="@diegosouzapw/omniroute"
if [ "$TAG" = "latest" ]; then
npm publish --registry=https://npm.pkg.github.com || echo "⚠️ Version ${VERSION} might already be published on GitHub."
else
npm publish --registry=https://npm.pkg.github.com --tag "$TAG" || echo "⚠️ Version ${VERSION} might already be published on GitHub."
fi
echo "✅ Action finished for GitHub Packages"
# npm REFUSES `--provenance` from a self-hosted runner:
# 422 Unprocessable Entity - Error verifying sigstore provenance bundle:
# Unsupported GitHub Actions runner environment: "self-hosted".
# Only "github-hosted" runners are supported when publishing with provenance.
# v3.8.49 published fine because it predates USE_VPS_RUNNER being turned on
# (2026-08-02); v3.8.50 was the first release after it, so this had been latent
# for four weeks. Dropping --provenance was not an option: 3.8.49 carries a
# SLSA attestation and 3.8.50 must not regress that.
# The `publish` job cannot simply move to a hosted runner either — 16 GB is not
# enough for build:cli's next-build fallback. So it keeps proving the bytes and
# this job, which needs no memory at all, performs the upload.
stage-npm:
needs: publish
if: needs.publish.outputs.skip != 'true'
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # npm provenance — the whole reason this job is separate
steps:
- name: Download the tarball the publish job proved
uses: actions/download-artifact@v8
with:
name: npm-tarball
path: .
- name: Setup Node.js
uses: actions/setup-node@v7
with:
node-version: ${{ env.NPM_PUBLISH_NODE_VERSION }}
registry-url: https://registry.npmjs.org
- name: Ensure npm supports staged publishing
run: |
set -euo pipefail
CUR=$(npm --version)
if ! node -e "const [a,b]='$(npm --version)'.split('.').map(Number); process.exit(a>11||(a===11&&b>=15)?0:1)"; then
# Pinned exact version (supply-chain: never float @latest in a publish
# job); bump deliberately when a newer npm is required.
echo "npm $CUR < 11.15 — installing pinned npm 11.15.0 for staged publishing"
npm install -g --ignore-scripts npm@11.15.0
fi
npm --version
# Trusted Publishing (OIDC): npm mints a short-lived credential for THIS run from
# GitHub's id-token — no NPM_TOKEN secret, no 2FA prompt, provenance included, and
# it is the bypass npm sanctions now that tokens which skip 2FA are being retired
# (gh.io/npm-gat-bypass2fa-deprecation). Requires the package's Trusted Publisher to
# be configured on npmjs.com (owner: cheaper-inference/OmniRoute, workflow
# npm-publish.yml) and a github-hosted runner — which is why this job exists.
# Without that configuration `npm publish` fails with ENEEDAUTH: re-dispatch with
# publish_mode=staged or direct. Automatic publishing was the flow up to v3.8.48;
# v3.8.49 moved to staged (WS1.3) to keep a leaked token from publishing alone —
# OIDC gives the same guarantee without the manual approve.
- name: Publish to npm (Trusted Publishing / OIDC — automatic)
if: github.event_name != 'workflow_dispatch' || inputs.publish_mode == 'auto'
env:
VERSION: ${{ needs.publish.outputs.version }}
TAG: ${{ needs.publish.outputs.tag }}
run: |
set -euo pipefail
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "tarball $TARBALL did not arrive from the publish job" >&2; ls -la; exit 1; }
# Deliberately NO NODE_AUTH_TOKEN in this step: npm >= 11.5 detects the GitHub
# OIDC token itself. Always pass --tag explicitly (defense in depth: an older
# VERSION can never claim `@latest`).
npm publish "$TARBALL" --provenance --access public --tag "$TAG" --ignore-scripts
echo "✅ Published omniroute@$VERSION (dist-tag=$TAG) via Trusted Publishing"
- name: Publish to npm (staged — owner approves with 2FA)
# Only on an explicit request now: Trusted Publishing below is the default.
if: github.event_name == 'workflow_dispatch' && inputs.publish_mode == 'staged'
env:
VERSION: ${{ needs.publish.outputs.version }}
TAG: ${{ needs.publish.outputs.tag }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "tarball $TARBALL did not arrive from the publish job" >&2; ls -la; exit 1; }
# Always pass --tag explicitly. Defense in depth: even if VERSION is
# accidentally an older release, the historic tag will NOT claim `@latest`.
# --ignore-scripts: publishing a built tarball must never re-run
# prepublishOnly (build:cli-api && build:cli) on this small runner.
npm stage publish "$TARBALL" --provenance --access public --tag "$TAG" --ignore-scripts
{
echo "## 📦 omniroute@$VERSION STAGED (not yet installable)"
echo ""
echo "The exact bytes are parked on the registry. To release them:"
echo '```'
echo "npm stage list omniroute # find the stage id"
echo "npm stage approve <id> # owner 2FA — THE publish"
echo '```'
echo "To verify the staged bytes first: npm stage download <id> → run"
echo "scripts/check/check-pack-boot.mjs against them (see RELEASE_CHECKLIST)."
echo "To discard: npm stage reject <id>."
} >> "$GITHUB_STEP_SUMMARY"
echo "✅ Staged omniroute@$VERSION (dist-tag=$TAG) — awaiting owner 'npm stage approve'"
- name: Publish to npm (DIRECT — emergency fallback)
if: github.event_name == 'workflow_dispatch' && inputs.publish_mode == 'direct'
env:
VERSION: ${{ needs.publish.outputs.version }}
TAG: ${{ needs.publish.outputs.tag }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
TARBALL="omniroute-${VERSION}.tgz"
test -f "$TARBALL" || { echo "tarball $TARBALL did not arrive from the publish job" >&2; ls -la; exit 1; }
npm publish "$TARBALL" --provenance --access public --tag "$TAG" --ignore-scripts
echo "✅ Published omniroute@$VERSION (dist-tag=$TAG) [DIRECT mode]"
publish-opencode-plugin:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # npm provenance
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
fetch-depth: 0
# Full history needed for auto-bump: git diff against previous release tag
- name: Setup Node.js
uses: actions/setup-node@v7
with:
node-version: ${{ env.NPM_PUBLISH_NODE_VERSION }}
registry-url: https://registry.npmjs.org
- name: Auto-bump plugin version if plugin changed since last release
id: bump
working-directory: "@omniroute/opencode-plugin"
env:
CURRENT_TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
PKG_VERSION=$(node -p "require('./package.json').version")
PKG_NAME=$(node -p "require('./package.json').name")
# 1) Skip if current version is not yet published (no bump needed)
PUBLISHED="$(npm view "${PKG_NAME}@${PKG_VERSION}" version 2>/dev/null || true)"
if [ "$PUBLISHED" != "$PKG_VERSION" ]; then
echo "✅ ${PKG_NAME}@${PKG_VERSION} is new — no bump needed."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 2) Find the previous release tag (exclude the current one)
PREV_TAG=$(git tag -l 'v*' --sort=-version:refname \
| grep -v "^${CURRENT_TAG}$" | head -1 || echo "")
if [ -z "$PREV_TAG" ]; then
echo "No previous tag to compare — skipping bump."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 3) Check if plugin dir actually changed since that tag
if git diff --quiet "$PREV_TAG" -- "@omniroute/opencode-plugin/"; then
echo "⏭️ No plugin changes since $PREV_TAG — nothing to publish."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 4) Auto-bump patch version
npm version patch --no-git-tag-version --allow-same-version
NEW_VERSION=$(node -p "require('./package.json').version")
echo "bumped=true" >> "$GITHUB_OUTPUT"
echo "📦 Auto-bumped ${PKG_NAME} from ${PKG_VERSION} to ${NEW_VERSION}"
- name: Install plugin dependencies
working-directory: "@omniroute/opencode-plugin"
run: npm install --no-audit --no-fund
- name: Build plugin
working-directory: "@omniroute/opencode-plugin"
run: npm run clean && npm run build
- name: Test plugin
working-directory: "@omniroute/opencode-plugin"
run: npm test
- name: Publish @omniroute/opencode-plugin to npm
working-directory: "@omniroute/opencode-plugin"
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
PKG_VERSION=$(node -p "require('./package.json').version")
PKG_NAME=$(node -p "require('./package.json').name")
# Same hardened skip-check as the main job (no --silent flag).
PUBLISHED="$(npm view "${PKG_NAME}@${PKG_VERSION}" version 2>/dev/null || true)"
if [ "$PUBLISHED" = "$PKG_VERSION" ]; then
echo "⚠️ ${PKG_NAME}@${PKG_VERSION} is already published on npm — skipping."
exit 0
fi
npm publish --provenance --access public --ignore-scripts
echo "✅ Published ${PKG_NAME}@${PKG_VERSION}"
publish-opencode-plugin-v2:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # npm provenance
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
fetch-depth: 0
# Full history needed for auto-bump: git diff against previous release tag
- name: Setup Node.js
uses: actions/setup-node@v7
with:
node-version: ${{ env.NPM_PUBLISH_NODE_VERSION }}
registry-url: https://registry.npmjs.org
- name: Auto-bump plugin-v2 version if plugin-v2 changed since last release
id: bump
working-directory: "@omniroute/opencode-plugin-v2"
env:
CURRENT_TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
PKG_VERSION=$(node -p "require('./package.json').version")
PKG_NAME=$(node -p "require('./package.json').name")
# 1) Skip if current version is not yet published (no bump needed)
PUBLISHED="$(npm view "${PKG_NAME}@${PKG_VERSION}" version 2>/dev/null || true)"
if [ "$PUBLISHED" != "$PKG_VERSION" ]; then
echo "✅ ${PKG_NAME}@${PKG_VERSION} is new — no bump needed."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 2) Find the previous release tag (exclude the current one)
PREV_TAG=$(git tag -l 'v*' --sort=-version:refname \
| grep -v "^${CURRENT_TAG}$" | head -1 || echo "")
if [ -z "$PREV_TAG" ]; then
echo "No previous tag to compare — skipping bump."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 3) Check if plugin-v2 dir actually changed since that tag
if git diff --quiet "$PREV_TAG" -- "@omniroute/opencode-plugin-v2/"; then
echo "⏭️ No plugin-v2 changes since $PREV_TAG — nothing to publish."
echo "bumped=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# 4) Auto-bump patch version
npm version patch --no-git-tag-version --allow-same-version
NEW_VERSION=$(node -p "require('./package.json').version")
echo "bumped=true" >> "$GITHUB_OUTPUT"
echo "📦 Auto-bumped ${PKG_NAME} from ${PKG_VERSION} to ${NEW_VERSION}"
- name: Install plugin-v2 dependencies
working-directory: "@omniroute/opencode-plugin-v2"
run: npm install --no-audit --no-fund
- name: Build plugin-v2
working-directory: "@omniroute/opencode-plugin-v2"
run: npm run clean && npm run build
- name: Test plugin-v2
working-directory: "@omniroute/opencode-plugin-v2"
run: npm test
- name: Publish @omniroute/opencode-plugin-v2 to npm
working-directory: "@omniroute/opencode-plugin-v2"
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
set -euo pipefail
PKG_VERSION=$(node -p "require('./package.json').version")
PKG_NAME=$(node -p "require('./package.json').name")
# Same hardened skip-check as the main job (no --silent flag).
PUBLISHED="$(npm view "${PKG_NAME}@${PKG_VERSION}" version 2>/dev/null || true)"
if [ "$PUBLISHED" = "$PKG_VERSION" ]; then
echo "⚠️ ${PKG_NAME}@${PKG_VERSION} is already published on npm — skipping."
exit 0
fi
npm publish --provenance --access public --ignore-scripts
echo "✅ Published ${PKG_NAME}@${PKG_VERSION}"
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,90 +0,0 @@
name: opencode-plugin CI
on:
push:
branches: [main, "release/**"]
paths:
- "@omniroute/opencode-plugin/**"
- "@omniroute/opencode-plugin-v2/**"
pull_request:
branches: [main, "release/**"]
paths:
- "@omniroute/opencode-plugin/**"
- "@omniroute/opencode-plugin-v2/**"
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
defaults:
run:
working-directory: "@omniroute/opencode-plugin"
jobs:
test:
name: Test (Node ${{ matrix.node }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node: ["22", "24"]
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ matrix.node }}
cache: npm
cache-dependency-path: "@omniroute/opencode-plugin/package-lock.json"
- run: npm install --no-audit --no-fund
- run: npm run build
- run: npm test
test-v2:
name: Test v2 (Node ${{ matrix.node }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node: ["22", "24"]
defaults:
run:
working-directory: "@omniroute/opencode-plugin-v2"
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ matrix.node }}
cache: npm
cache-dependency-path: "@omniroute/opencode-plugin-v2/package-lock.json"
- run: npm ci --no-audit --no-fund
- run: npm run build
- run: npm test
build:
name: Build
runs-on: ubuntu-latest
needs: [test, test-v2]
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "22"
- name: Build plugin-v2 artifact
working-directory: "@omniroute/opencode-plugin-v2"
run: npm ci --no-audit --no-fund && npm run build
- uses: actions/upload-artifact@v7
with:
name: opencode-plugin-v2-dist
path: "@omniroute/opencode-plugin-v2/dist"
retention-days: 7

View File

@@ -1,65 +0,0 @@
name: opencode-provider CI
on:
push:
branches: [main, release/v3.8.0]
paths:
- "@omniroute/opencode-provider/**"
pull_request:
branches: [main, release/v3.8.0]
paths:
- "@omniroute/opencode-provider/**"
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
defaults:
run:
working-directory: "@omniroute/opencode-provider"
jobs:
test:
name: Test (Node ${{ matrix.node }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node: ["20", "22", "24"]
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: ${{ matrix.node }}
cache: npm
cache-dependency-path: "@omniroute/opencode-provider/package-lock.json"
- run: npm ci
- run: npm test
build:
name: Build
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: "20"
cache: npm
cache-dependency-path: "@omniroute/opencode-provider/package-lock.json"
- run: npm ci
- run: npm run build
- uses: actions/upload-artifact@v7
with:
name: opencode-provider-dist
path: "@omniroute/opencode-provider/dist"
retention-days: 7

View File

@@ -1,252 +0,0 @@
name: Preview artifact (build once)
# PR preview artifact — #8084 slice (a), rehearsed in 3.8.58 (ROADMAP Phase 2).
#
# Builds ONE production-equivalent npm tarball from the exact PR head, validates
# THAT build (check:pack-artifact + check:pack-boot, which installs the packed
# tarball into a clean prefix and boots it with fake secrets on an isolated
# DATA_DIR), records its identity (head SHA + base SHA + lockfile hash +
# platform/arch/node ABI + build policy, scripts/release/artifact-identity.mjs),
# uploads tarball + identity + SHA256SUMS and attests the tarball's provenance.
# The uploaded bytes are what a preview install or a promotion consumes: there is
# no second source build anywhere downstream.
#
# Out of scope on purpose: publishing (nothing here talks to a registry), DB-clone
# migration rehearsal (#8084 reply 3 — its own subsystem) and live provider probes.
#
# Triggers: `workflow_dispatch` with a PR number, or adding the `preview-artifact`
# label to a PR. Fork PRs are never built: the label path checks
# head.repo.full_name in the job `if:`, the dispatch path re-checks it from the API
# before anything is checked out. This runs PR code (same-repository branches
# only), so the build job holds a read-only token and no OIDC permission; the
# OIDC/attestation permissions live in the separate `attest` job, which never
# checks out or executes repository code.
on:
workflow_dispatch:
inputs:
pr_number:
description: "Pull request number to build (same-repository PRs only)"
required: true
type: string
pull_request:
types: [labeled]
permissions:
contents: read # default for every job; each job narrows or extends below
concurrency:
group: preview-artifact-${{ github.event.pull_request.number || inputs.pr_number }}
cancel-in-progress: true
env:
PREVIEW_NODE_VERSION: "24"
jobs:
resolve:
name: Resolve PR head and base
if: >-
github.event_name == 'workflow_dispatch' ||
(github.event.label.name == 'preview-artifact' &&
github.event.pull_request.head.repo.full_name == github.repository)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: read # gh api repos/<repo>/pulls/<N> (head repo, state, SHAs)
outputs:
pr_number: ${{ steps.pr.outputs.pr_number }}
head_sha: ${{ steps.pr.outputs.head_sha }}
base_sha: ${{ steps.pr.outputs.base_sha }}
base_ref: ${{ steps.pr.outputs.base_ref }}
steps:
- name: Resolve the PR and refuse forks
id: pr
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
EVENT_PR: ${{ github.event.pull_request.number }}
INPUT_PR: ${{ inputs.pr_number }}
run: |
set -euo pipefail
PR="${EVENT_PR:-$INPUT_PR}"
if ! printf '%s' "$PR" | grep -qE '^[0-9]+$'; then
echo "::error::pr_number must be a positive integer"
exit 1
fi
DATA=$(gh api "repos/$REPO/pulls/$PR")
HEAD_REPO=$(jq -r '.head.repo.full_name // ""' <<<"$DATA")
STATE=$(jq -r '.state' <<<"$DATA")
HEAD_SHA=$(jq -r '.head.sha' <<<"$DATA")
BASE_REF=$(jq -r '.base.ref' <<<"$DATA")
if [ "$HEAD_REPO" != "$REPO" ]; then
echo "::error::PR #$PR comes from a fork ($HEAD_REPO) — preview artifacts are built for same-repository branches only"
exit 1
fi
if [ "$STATE" != "open" ]; then
echo "::error::PR #$PR is $STATE — preview artifacts are built for open PRs only"
exit 1
fi
# The base SHA recorded in the identity is the base branch tip at build time.
BASE_SHA=$(gh api "repos/$REPO/git/ref/heads/$BASE_REF" --jq '.object.sha')
{
echo "pr_number=$PR"
echo "head_sha=$HEAD_SHA"
echo "base_sha=$BASE_SHA"
echo "base_ref=$BASE_REF"
} >> "$GITHUB_OUTPUT"
echo "PR #$PR head=$HEAD_SHA base=$BASE_REF@$BASE_SHA"
build:
name: Build once, validate, upload
needs: resolve
# Same pool rule as npm-publish.yml: the hosted runner cannot hold `next build`
# for this tree any more (#11946). The fork clause is redundant here (resolve
# already refused forks) and is kept so the expression stays greppable.
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && vars.USE_VPS_BUILD_RUNNER == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && fromJSON('["self-hosted","omni-build"]') || 'ubuntu-latest' }}
timeout-minutes: 120
permissions:
contents: read # checkout + git fetch refs/pull/<N>/head — read-only, no OIDC
outputs:
artifact_name: ${{ steps.name.outputs.artifact_name }}
env:
# Fake, build-time-only values. No real secret is ever exposed to this job.
JWT_SECRET: preview-artifact-fake-jwt-secret-with-sufficient-length
API_KEY_SECRET: preview-artifact-fake-api-key-secret-0000000000000000
steps:
- name: Checkout the PR head
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ needs.resolve.outputs.head_sha }}
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: ${{ env.PREVIEW_NODE_VERSION }}
package-manager-cache: false
- name: Install dependencies (npm ci)
uses: ./.github/actions/npm-ci-retry
with:
# A promotable artifact is never built from a cached node_modules.
cache: "false"
- name: Build release bundle
run: npm run build:release
# check:pack-artifact's provenance guard (#10427) needs a ref the stamped head
# is an ancestor of. refs/pull/<N>/head exists in this repository for every PR.
- name: Fetch the PR head ref for the provenance guard
env:
PR_NUMBER: ${{ needs.resolve.outputs.pr_number }}
run: |
git fetch --no-tags --depth=50 origin \
"+refs/pull/$PR_NUMBER/head:refs/remotes/origin/pr-head"
- name: Validate the npm package artifact
env:
OMNIROUTE_RELEASE_REF: origin/pr-head
run: npm run check:pack-artifact
- name: Pack the tarball (the bytes that get uploaded)
id: pack
run: |
set -euo pipefail
OUT_DIR="$RUNNER_TEMP/preview-artifact"
mkdir -p "$OUT_DIR"
FILE=$(npm pack --json --pack-destination "$OUT_DIR" | jq -r '.[0].filename' | tr '/' '-')
test -f "$OUT_DIR/$FILE"
SHA=$(sha256sum "$OUT_DIR/$FILE" | cut -d' ' -f1)
{
echo "dir=$OUT_DIR"
echo "file=$FILE"
echo "sha256=$SHA"
} >> "$GITHUB_OUTPUT"
echo "packed $FILE sha256=$SHA"
# Packs the same tree again, installs it into a clean prefix and boots it with
# fake JWT/API-key secrets on an ephemeral DATA_DIR (the script also forces its
# own isolated values for the spawned server).
- name: Boot-smoke the packed tarball
env:
DATA_DIR: ${{ runner.temp }}/preview-artifact-data
run: npm run check:pack-boot
# Build once: the tree must not have changed while it was being validated, and
# `npm pack` must reproduce the uploaded bytes exactly — otherwise what booted
# and what gets uploaded are not provably the same artifact.
- name: Prove the validated bytes are the uploaded bytes
env:
OUT_DIR: ${{ steps.pack.outputs.dir }}
FILE: ${{ steps.pack.outputs.file }}
EXPECTED_SHA: ${{ steps.pack.outputs.sha256 }}
run: |
set -euo pipefail
RECHECK="$RUNNER_TEMP/preview-artifact-recheck"
mkdir -p "$RECHECK"
npm pack --pack-destination "$RECHECK" >/dev/null
ACTUAL=$(sha256sum "$RECHECK/$FILE" | cut -d' ' -f1)
if [ "$ACTUAL" != "$EXPECTED_SHA" ]; then
echo "::error::re-pack digest $ACTUAL != uploaded $EXPECTED_SHA — the artifact is not reproducible from the validated tree"
exit 1
fi
rm -rf "$RECHECK"
echo "re-pack reproduces $FILE byte for byte"
- name: Record the artifact identity
env:
HEAD_SHA: ${{ needs.resolve.outputs.head_sha }}
BASE_SHA: ${{ needs.resolve.outputs.base_sha }}
OUT_DIR: ${{ steps.pack.outputs.dir }}
FILE: ${{ steps.pack.outputs.file }}
run: |
set -euo pipefail
node scripts/release/artifact-identity.mjs \
--head "$HEAD_SHA" \
--base "$BASE_SHA" \
--lockfile package-lock.json \
--tarball "$OUT_DIR/$FILE" \
--out "$OUT_DIR/artifact-identity.json"
(cd "$OUT_DIR" && sha256sum "$FILE" artifact-identity.json > SHA256SUMS)
- name: Name the workflow artifact
id: name
env:
PR_NUMBER: ${{ needs.resolve.outputs.pr_number }}
HEAD_SHA: ${{ needs.resolve.outputs.head_sha }}
run: echo "artifact_name=preview-artifact-pr${PR_NUMBER}-${HEAD_SHA:0:7}" >> "$GITHUB_OUTPUT"
- name: Upload tarball + identity
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: ${{ steps.name.outputs.artifact_name }}
path: ${{ steps.pack.outputs.dir }}
if-no-files-found: error
retention-days: 14
attest:
name: Attest build provenance
needs: build
# GitHub-hosted on purpose: attestation signing uses the job's OIDC token, and
# this job never checks out or runs repository code.
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read # required by attest-build-provenance
id-token: write # Sigstore signing of the provenance statement
attestations: write # store the attestation on this repository
steps:
- name: Download the uploaded artifact
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: ${{ needs.build.outputs.artifact_name }}
path: preview-artifact
- name: Verify checksums
working-directory: preview-artifact
run: sha256sum -c SHA256SUMS
- name: Attest the tarball
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
with:
subject-path: preview-artifact/*.tgz

View File

@@ -1,558 +0,0 @@
name: Quality Gates
on:
push:
# release/** pushes are covered by the PR run of each change plus Release-Green on the
# merged combination (see ci.yml for the 2026-10-18 measurement); the per-push run here
# only ever queued hosted slots and was cancelled by the next merge.
branches: [main]
pull_request:
branches: [main, "release/**"]
types: [opened, synchronize, reopened, ready_for_review, converted_to_draft, edited]
merge_group:
types: [checks_requested]
workflow_dispatch:
# A description edit on a Mergify queue draft (Mergify writes its queue summary there, and
# the Blacksmith app appends its footer, ~4 edits in the first 30 s) gets its own group and
# skips the matrix: in the shared group it cancelled the candidate's real run, and Mergify
# dequeued the PR on the cancelled checks ("checks interrupted", #18853/#18858 on 2026-11-03).
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}${{ (github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.pull_request.user.login == 'mergify[bot]' && startsWith(github.head_ref, 'mergify/merge-queue/') && github.event.pull_request.head.repo.id == github.event.repository.id) && format('-queue-edit-{0}', github.run_id) || '' }}
cancel-in-progress: true
permissions:
contents: read
env:
# CI must never mutate the runner's OS trust store (2026-07-05: a cert-flow
# test installed a fake PEM on a persistent self-hosted runner and broke all
# system TLS). Belt-and-suspenders with tests/_setup/isolateDataDir.ts.
OMNIROUTE_SKIP_SYSTEM_TRUST: "1"
CI_NODE_VERSION: "24"
jobs:
# Same classifier as ci.yml (scripts/quality/classify-pr-changes.mjs) so PR→release
# path filters share existence reasons: code / docs / i18n / workflow.
changes:
name: Change Classification
if: ${{ !(github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.pull_request.user.login == 'mergify[bot]' && startsWith(github.head_ref, 'mergify/merge-queue/') && github.event.pull_request.head.repo.id == github.event.repository.id) }}
runs-on: ubuntu-latest
outputs:
code: ${{ steps.classify.outputs.code }}
docs: ${{ steps.classify.outputs.docs }}
i18n: ${{ steps.classify.outputs.i18n }}
workflow: ${{ steps.classify.outputs.workflow }}
testsOnly: ${{ steps.classify.outputs.testsOnly }}
# Exposure only (one-CI-policy step 1, RFC #8084): no job depends on it yet.
domains: ${{ steps.classify.outputs.domains }}
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
fetch-depth: 0
- uses: actions/setup-node@v7
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- name: Validate gate inventory
run: npm run check:gate-manifest
- name: Validate recurring free catalog evidence
env:
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
run: npm run check:free-catalog-evidence
- id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
if [ "$EVENT_NAME" != "pull_request" ]; then
{
echo "code=true"
echo "docs=true"
echo "i18n=true"
echo "workflow=true"
echo "testsOnly=false"
echo "domains=build,catalog,cli,core,db,docs,i18n,provider,routing,tests,ui,workflow"
} >> "$GITHUB_OUTPUT"
exit 0
fi
git diff --name-only "$BASE_SHA" "$HEAD_SHA" > changed-files.txt
node scripts/quality/classify-pr-changes.mjs changed-files.txt >> "$GITHUB_OUTPUT"
# Full build/package/boot authority lives in CI; no permanently skipped duplicate.
# Docs/OpenAPI contract gates only — existence reason is doc accuracy + route refs.
# Split out of fast-gates so pure-docs PRs skip typecheck/unit while still validating docs.
docs-gates:
name: Docs Gates (fast-path)
needs: changes
if: ${{ github.event_name != 'pull_request' || ((github.event.pull_request.draft == false || startsWith(github.head_ref, 'mergify/merge-queue/')) && (needs.changes.outputs.docs == 'true' || needs.changes.outputs.code == 'true')) }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- uses: ./.github/actions/npm-ci-retry
with:
# PR acceleration is not release-candidate provenance.
cache: ${{ github.event_name == 'pull_request' }}
# One walk of src/app/api for openapi-routes + docs-symbols (both still fail independently).
- run: npm run check:api-docs-refs
- name: Docs accuracy (fabricated-docs + i18n mirrors, strict)
run: npm run check:docs-all
fast-gates:
name: Fast Quality Gates
needs: changes
# Code surface only — pure docs/i18n PRs skip this bag (docs-gates covers docs).
if: ${{ github.event_name != 'pull_request' || ((github.event.pull_request.draft == false || startsWith(github.head_ref, 'mergify/merge-queue/')) && needs.changes.outputs.code == 'true') }}
# Dynamic runner (same rule as ci.yml): use the self-hosted VPS pool only when the
# release captain has USE_VPS_RUNNER=true AND this is not a fork PR (own-origin
# branches only — a fork PR must never execute on the LAN runner). Var unset/false
# or a fork PR falls back to ubuntu-latest, so this is inert until the flag flips.
# PINNED to hosted (gap 19). This job carried the USE_VPS_RUNNER expression, and that
# expression was DEAD CONFIGURATION: across 160 quality.yml runs the job never once landed on
# a self-hosted runner — every non-skipped sample is `GitHub Actions NNNN`. The classifier is
# not at fault: in the same window ci.yml's Build demonstrably ran on omniroute-113-7 and
# omniroute-113-6, so self-hosted runs are visible when they happen.
#
# And if it ever HAD fired it would have inherited the measured penalty, because this job's
# first two steps are exactly the bottleneck: actions/setup-node + npm ci took 20m06s on .113
# with 4 concurrent runners versus 16s hosted (npm cache restore saturating the link). Median
# here is 5.6 min hosted across 72 successful runs.
#
# With this pinned, USE_VPS_RUNNER governs ONLY build-like jobs — one variable, one coherent
# purpose. That is what gap 19 asked for; a second variable turned out to be unnecessary.
runs-on: ubuntu-latest
# tsx gates (known-symbols, route-guard-membership) import modules that open
# SQLite on load; provide DB env so a fresh CI DB initializes cleanly.
env:
JWT_SECRET: ci-lint-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-lint-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-node@v7
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- uses: ./.github/actions/npm-ci-retry
with:
# PR acceleration is not release-candidate provenance.
cache: ${{ github.event_name == 'pull_request' }}
- name: Restore ESLint file cache
if: github.event_name == 'pull_request'
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: |
.eslintcache
.eslintcache-complexity
key: eslint-${{ runner.os }}-${{ hashFiles('eslint.config.mjs', 'eslint.complexity-ratchets.config.mjs', 'config/quality/eslint-suppressions.json', 'package-lock.json') }}
# No restore-keys fallback on purpose (#11600, P-II.1 of the v3.8.50 postmortem): a
# cache built under a different suppressions file / lint config / lockfile reports
# stale per-file verdicts, which is exactly how 215 pre-existing errors stayed
# invisible for a whole cycle. Exact key or a cold full lint (~13 min) — never a
# partial cache from another configuration.
# Security scanners — same hardened install as ci.yml quality-extended
# (gh release download = authenticated, 5000 req/hr; curl to api.github.com
# is rate-limited to 60/hr and silently no-ops when throttled). The blocking
# gates below SKIP (exit 0) when their binary is absent — only a measured
# regression vs config/quality/quality-baseline.json blocks.
- name: Install security scanners (gitleaks/osv/actionlint/zizmor/oasdiff)
continue-on-error: true
env:
GH_TOKEN: ${{ github.token }}
run: |
set +e
mkdir -p "$HOME/.local/bin"
# Ratchets compare scanner COUNTS across runs. Pin every auditor: a rule-set
# update must be an explicit PR that re-measures/rebaselines, never a random
# red (or green) caused by whatever "latest" served that morning.
GITLEAKS_VERSION=v8.30.1
OSV_SCANNER_VERSION=v2.3.8
ACTIONLINT_VERSION=v1.7.12
ZIZMOR_VERSION=1.25.2
OASDIFF_VERSION=v1.19.1
# gitleaks — pinned linux x64 tarball via gh (authed), extract binary
rm -rf /tmp/gl && mkdir -p /tmp/gl
gh release download "$GITLEAKS_VERSION" --repo gitleaks/gitleaks --pattern '*linux_x64.tar.gz' --dir /tmp/gl
tar -xzf /tmp/gl/*linux_x64.tar.gz -C "$HOME/.local/bin" gitleaks
# osv-scanner — pinned linux amd64 bare binary via gh (authed)
rm -rf /tmp/osv && mkdir -p /tmp/osv
gh release download "$OSV_SCANNER_VERSION" --repo google/osv-scanner --pattern '*linux_amd64' --dir /tmp/osv
install -m 0755 /tmp/osv/*linux_amd64 "$HOME/.local/bin/osv-scanner"
# actionlint — official installer from a pinned release tag (never main)
bash <(curl -fsSL "https://raw.githubusercontent.com/rhysd/actionlint/${ACTIONLINT_VERSION}/scripts/download-actionlint.bash") "${ACTIONLINT_VERSION#v}" "$HOME/.local/bin"
# zizmor — pinned PyPI package (same version as ci.yml quality-extended)
pipx install "zizmor==$ZIZMOR_VERSION" || pip install --user "zizmor==$ZIZMOR_VERSION"
# oasdiff — pinned linux amd64 tarball via gh (authed), extract binary
rm -rf /tmp/oasd && mkdir -p /tmp/oasd
gh release download "$OASDIFF_VERSION" --repo Tufin/oasdiff --pattern '*linux_amd64.tar.gz' --dir /tmp/oasd
tar -xzf /tmp/oasd/*linux_amd64.tar.gz -C "$HOME/.local/bin" oasdiff
# ALWAYS export the bin dir (even if any step above failed)
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
"$HOME/.local/bin/gitleaks" version || true
"$HOME/.local/bin/actionlint" -version || true
"$HOME/.local/bin/osv-scanner" --version || true
"$HOME/.local/bin/oasdiff" --version || true
zizmor --version || true
- name: Forgotten sibling tests (advisory)
env:
GITHUB_BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
node scripts/quality/build-test-impact-map.mjs
node scripts/check/check-forgotten-sibling-tests.mjs \
--summary-file forgotten-sibling-tests.md \
--json-file forgotten-sibling-tests.json
cat forgotten-sibling-tests.md >> "$GITHUB_STEP_SUMMARY"
- name: Upload forgotten sibling report
if: always()
uses: actions/upload-artifact@v7
with:
name: forgotten-sibling-tests
path: |
forgotten-sibling-tests.md
forgotten-sibling-tests.json
if-no-files-found: ignore
retention-days: 30
# Quality gates (all, non-fail-fast) — #8542: replaces 17 bare check:* steps,
# 6 G0 gates, 4 ratchet gates, and 3 typecheck steps with a single aggregation
# step. Each gate runs in a loop with ::group::; failures are collected and
# reported at the end. set -uo pipefail (NOT set -e) so one failing gate does
# not abort the job and mask every later gate. Release-added gates are folded
# in: open-sse typecheck (#8781) and file-size base-relative mode (#8522).
- name: Quality gates (all, non-fail-fast)
env:
# #8522: base-relative file-size mode on PR events — inherited drift (base
# already over frozen cap) must not red an innocent PR. Unset on
# workflow_dispatch (no PR base) → absolute comparison.
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
BASE_REF: ${{ github.base_ref && format('origin/{0}', github.base_ref) || '' }}
run: |
set -uo pipefail
gates=(
provider-consistency provider-asset-provenance fetch-targets deps file-size error-helper
migration-numbering public-creds db-rules known-symbols
route-guard-membership test-discovery test-runner-api
mutation-test-coverage any-budget:t11 build-scope pack-policy
complexity-ratchets model-lifecycle
lockfile duplication dead-code type-coverage compression-budget
# #8781: open-sse workspace typecheck gate — the workspace imports @/ which
# escapes to src/ via undeclared path aliases. See check-open-sse-typecheck.mjs.
open-sse-typecheck
# Hard Rule #16 — AI/bot attribution in PR commits, title or body (#14436). Reads the PR
# from GITHUB_EVENT_PATH; no-op on non-PR events. ci.yml only runs on PRs to main.
ai-attribution
)
# Ratchet-mode gates append --ratchet. `cycles` belongs here since #15281
# (69cb18dca8): check-cycles.mjs exits 1 on ANY cycle without --ratchet, and
# the frozen ceiling lives in quality-baseline.json → metrics.cycles — same
# `check:cycles:ratchet` semantics ci.yml runs (base-red #15306). `boundary`
# caps the open-sse → src edge count (measure-boundary.mjs --ratchet, ceiling
# quality-baseline.json → metrics.boundaryOpenSseToSrc) — same as ci.yml lint.
ratchet_gates=(
secrets vuln-ratchet workflows openapi-breaking cycles boundary
)
failed=()
for g in "${gates[@]}"; do
echo "::group::check:$g"
# #8522: file-size is base-relative on PR events (compare against
# max(frozen, base)) so inherited drift doesn't red an innocent PR;
# workflow_dispatch (no PR base) falls back to absolute comparison.
# New-code mode (Clean-as-You-Code, 2026-08-30): complexity-ratchets and
# dead-code compare the PR's files against the merge-base and block only on
# what the PR added; the global totals are advisory on PRs and re-frozen at
# release. See scripts/check/newCodeMode.mjs.
case "$g" in file-size|complexity-ratchets|dead-code) NEW_CODE=1 ;; *) NEW_CODE= ;; esac
if [ -n "$NEW_CODE" ] && [ -n "${PR_BASE_SHA:-}" ]; then
npm run "check:$g" -- --base-ref "$PR_BASE_SHA" || failed+=("$g")
else
npm run "check:$g" || failed+=("$g")
fi
echo "::endgroup::"
done
for g in "${ratchet_gates[@]}"; do
echo "::group::check:$g (ratchet)"
# boundary is base-relative on PR events, like file-size (#8522): the ceiling
# becomes max(baseline ceiling, edges on the PR base), so open-sse → src edges
# other merges added after the seed never red an innocent PR; only edges this
# PR adds block. workflow_dispatch (no PR base) keeps the absolute ceiling.
case "$g" in boundary) BASE_RELATIVE=1 ;; *) BASE_RELATIVE= ;; esac
if [ -n "$BASE_RELATIVE" ] && [ -n "${PR_BASE_SHA:-}" ]; then
npm run "check:$g" -- --ratchet --base-ref "$PR_BASE_SHA" || failed+=("$g")
else
npm run "check:$g" -- --ratchet || failed+=("$g")
fi
echo "::endgroup::"
done
echo "::group::typecheck:core"
npm run typecheck:core || failed+=("typecheck:core")
echo "::endgroup::"
echo "::group::check:dashboard-typecheck"
npm run check:dashboard-typecheck || failed+=("check:dashboard-typecheck")
echo "::endgroup::"
echo "::group::check:build-typecheck"
npm run check:build-typecheck || failed+=("check:build-typecheck")
echo "::endgroup::"
# #10134: TS7 zero-new-diagnostics ratchet — folded into this non-fail-fast
# loop (never a separate blocking step) so an earlier red gate cannot abort
# the job and mask it (#8542 mechanism). PR-only: the base-relative
# comparison needs the PR base SHA (empty on workflow_dispatch).
if [ -n "${PR_BASE_SHA:-}" ]; then
echo "::group::check:ts7-diagnostics-ratchet"
npm run check:ts7-diagnostics-ratchet -- --base-ref "$PR_BASE_SHA" || failed+=("ts7-diagnostics-ratchet")
echo "::endgroup::"
fi
if (( ${#failed[@]} )); then
printf '::error::%d gate(s) failed: %s\n' "${#failed[@]}" "${failed[*]}"
exit 1
fi
# WS4.2 (v3.8.49 plan): TypeScript 7 native-compiler SHADOW — advisory only.
# TS7 went GA 2026-07-08 with 8-12x type-check speedups; its Compiler API only
# arrives in 7.1, so typescript-eslint / type-coverage / Stryker stay on 6.x
# (the hybrid is the officially documented pattern). Isolated npx on purpose:
# installing an alias package could collide node_modules/.bin/tsc with 6.x.
# The full result stays advisory while #8484 has a backlog. The blocking
# base-relative ratchet (folded into the non-fail-fast gates step above)
# rejects only diagnostics added by the PR, so existing release debt does
# not block unrelated work.
- name: Typecheck (core) — TS7 native shadow (advisory)
continue-on-error: true
run: |
RC=0
START=$(date +%s)
npm exec --yes --package=typescript@7.0.2 -- tsc --pretty false -p tsconfig.typecheck-core.json || RC=$?
echo "[ts7-shadow] exit=$RC elapsed=$(( $(date +%s) - START ))s — the 6.x step above stays authoritative"
exit $RC
# TIA: build the impact map at runtime (gitignored, ~21MB) and run only the
# unit tests impacted by this PR's changed files. On hub/unmapped changes the
# selector returns __RUN_ALL__ — full-suite authority is ci.yml's `test-unit`
# 8-shard job (test:unit:ci:shard), NOT an unsharded re-run here. Stacking an
# unsharded test:unit:ci on top of it doubled wall time without extra coverage.
# (quality.yml had its own 4-shard `fast-unit` + `fast-vitest` for PR->release from
# 2026-06-23; ci.yml runs on those PRs since #14420 (2026-10-01), so both were an
# exact duplicate — ~62 runner-min and 5 hosted jobs per PR — and were removed.)
#
# BLOCKING for the *impacted subset* (flipped 2026-06-17). Fail-safe full
# coverage remains required via ci.yml `Unit Tests (N/8)` (test-unit).
- name: Impacted unit tests (TIA subset; blocking)
env:
GITHUB_BASE_REF: ${{ github.base_ref }}
run: |
git fetch --no-tags origin "$GITHUB_BASE_REF" || true
# The advisory sibling-test step generates the same map earlier in this job.
[ -f config/quality/test-impact-map.json ] || node scripts/quality/build-test-impact-map.mjs
SEL="$(node scripts/quality/select-impacted-tests.mjs)"
# Shadow evidence (#8084): persist every selection so TIA false negatives can
# be measured against ci.yml test-unit's full-suite verdict across releases BEFORE
# any gate authority moves off ordinary PRs. Artifact uploaded below.
printf '%s\n' "$SEL" > tia-selection.txt
if [ -z "$SEL" ]; then
echo "TIA selection: empty (no source/test changes)" >> "$GITHUB_STEP_SUMMARY"
echo "No source/test changes — skipping unit tests"; exit 0
fi
# CI runners are 4-vCPU; run at --test-concurrency=4 (matching the ci.yml unit
# job) rather than test:unit's local-tuned concurrency=20. Oversubscribing the
# runner makes timing-sensitive tests (db-backup, upstream-timeout, ...) flake,
# which must not happen on a blocking gate. DATA_DIR isolation keeps the parallel
# run race-free regardless of concurrency.
if echo "$SEL" | grep -q "__RUN_ALL__"; then
echo "TIA selection: __RUN_ALL__ (fail-safe) — full-suite authority stays with ci.yml test-unit" >> "$GITHUB_STEP_SUMMARY"
echo "Fail-safe: __RUN_ALL__ — deferring FULL unit suite to ci.yml test-unit (8-shard)."
echo "Not re-running unsharded test:unit:ci here (duplicate of test-unit coverage)."
exit 0
fi
echo "TIA selection: $(grep -c . tia-selection.txt) impacted test file(s) — full suite still runs in ci.yml test-unit (shadow-evidence phase, #8084)" >> "$GITHUB_STEP_SUMMARY"
echo "Running impacted tests:"; echo "$SEL"
mapfile -t FILES <<< "$SEL"
# Loader parity with test:unit:ci:shard (#6787): tests/unit/dashboard/** runs
# under `--import tsx` (CJS transform — required for ESM-only deep imports like
# @lobehub/icons/es/* reached via lobeProviderIcons.ts); everything else under
# `--import tsx/esm`. A single tsx/esm invocation false-reds every dashboard
# module-shape test the impact map selects ("Unexpected token 'export'").
DASH=(); REST=()
for f in "${FILES[@]}"; do
case "$f" in
tests/unit/dashboard/*) DASH+=("$f") ;;
*) REST+=("$f") ;;
esac
done
RC=0
if [ ${#REST[@]} -gt 0 ]; then
node --import tsx/esm --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 "${REST[@]}" || RC=$?
fi
if [ ${#DASH[@]} -gt 0 ]; then
node --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 "${DASH[@]}" || RC=$?
fi
exit $RC
# #8084 shadow evidence: keep the raw selection downloadable so TIA misses can be
# audited against ci.yml test-unit failures on the same commit (gate moves need this data).
- name: Upload TIA selection (shadow evidence)
if: always()
uses: actions/upload-artifact@v7
with:
name: tia-selection
path: tia-selection.txt
if-no-files-found: ignore
retention-days: 30
# ── Pacote 4 (plano mestre testes+CI, aprovado 2026-07-04) ─────────────────────────
# No-new-warnings por PR via ESLint bulk suppressions nativo (>=9.24). O baseline
# config/quality/eslint-suppressions.json congela as violações EXISTENTES por
# arquivo+regra; qualquer warning NOVO aparece e o --max-warnings 0 falha o job — o
# drift de +41/+88 warnings por ciclo passa a morrer no PR que o introduz, em vez de
# ser rebaselinado às cegas na release. Aperto do baseline (na reconciliação da
# release): npx eslint . --prune-suppressions --suppressions-location config/quality/eslint-suppressions.json
#
# Forks use hosted runners and the same required code-quality result. A base-red
# is maintainer work, but must not be reported as a passing candidate.
lint-guard:
name: No new ESLint warnings
needs: changes
if: ${{ github.event_name != 'pull_request' || ((github.event.pull_request.draft == false || startsWith(github.head_ref, 'mergify/merge-queue/')) && needs.changes.outputs.code == 'true') }}
runs-on: ${{ (vars.USE_VPS_RUNNER == 'true' && github.event_name != 'merge_group' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted","omni-light"]')) || 'ubuntu-latest' }}
# 2026-08-30: a cold full lint with the eslint-plugin-react-hooks 7 compiler rules is
# killed on the 7 GB hosted runner without a message (status null → exit 1, the
# JSON never written); the box lints it in ~12 min with the heap below.
# G0 (trilho .50): security-events:read lets the CodeQL ratchet below read open
# code-scanning alerts via `gh api .../code-scanning/alerts` (same as ci.yml's
# quality-gate job). contents: read keeps checkout working.
permissions:
contents: read
security-events: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- uses: ./.github/actions/npm-ci-retry
with:
# PR acceleration is not release-candidate provenance.
cache: ${{ github.event_name == 'pull_request' }}
- name: Restore ESLint file cache
if: github.event_name == 'pull_request'
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: |
.eslintcache
.eslintcache-complexity
key: eslint-${{ runner.os }}-${{ hashFiles('eslint.config.mjs', 'eslint.complexity-ratchets.config.mjs', 'config/quality/eslint-suppressions.json', 'package-lock.json') }}
# No restore-keys fallback on purpose (#11600, P-II.1 of the v3.8.50 postmortem): a
# cache built under a different suppressions file / lint config / lockfile reports
# stale per-file verdicts, which is exactly how 215 pre-existing errors stayed
# invisible for a whole cycle. Exact key or a cold full lint (~13 min) — never a
# partial cache from another configuration.
- name: ESLint (baseline congelado — warning novo = vermelho)
# lint:json writes the report; --max-warnings 0 keeps no-new-warnings policy.
run: npm run lint:json -- --max-warnings 0
env:
NODE_OPTIONS: --max-old-space-size=8192
# ── G0 (trilho .50): motor de ratchet também no trilho B ─────────────────────
# This job just wrote .artifacts/eslint-results.json — collect-metrics prefers
# that file, so the ratchet engine lands here at ZERO extra ESLint cost (one
# inventory, two consumers; same reason ci.yml chains lint → quality-gate).
# The coverage-report artifact does not exist on this rail, so both ratchet
# invocations run --allow-missing: coverage.* metrics skip gracefully while
# the deterministic ones (eslint / openapi-coverage / i18n-ui) stay BLOCKING.
# Coverage authority remains on the main rail (ci.yml test-coverage → quality-gate).
- run: npm run quality:collect
- name: Ratchet check (blocking)
run: node scripts/quality/check-quality-ratchet.mjs --allow-missing --summary .artifacts/quality-ratchet.md
- name: Require-tighten (blocking)
run: node scripts/quality/check-quality-ratchet.mjs --allow-missing --require-tighten
# CodeQL alerts ratchet — same semantics as ci.yml quality-gate: exits 1 ONLY
# on a real regression (open alerts > baseline in quality-baseline.json);
# a measurement failure (gh/auth/api) self-skips with exit 0.
- name: CodeQL alerts ratchet (blocking)
run: npm run check:codeql-ratchet
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Append ratchet summary
if: always()
run: cat .artifacts/quality-ratchet.md >> "$GITHUB_STEP_SUMMARY" || true
# Merge-integrity: pega no PR os dois vazamentos crônicos de merge que hoje só
# explodem na release-PR. (1) CHANGELOG-eat — o auto-resolve do merge come
# bullets vizinhos/seções inteiras (incidente #6193, 2026-07-05: 212 linhas /
# 130 bullets); o checkout de PR é refs/pull/N/merge, então comparar contra a
# base detecta o eat ANTES do merge. (2) SKILL.md gerado stale vs o catálogo de
# agent-skills (#6186 mergeou um id de catálogo sem rodar o gerador → 8 reds de
# integration invisíveis até a release).
#
# Merge integrity is required regardless of who owns the PR branch.
merge-integrity:
name: Merge integrity (changelog + generated skills)
# Always on non-draft PRs — CHANGELOG/skills can break on docs-only merges too.
if: ${{ github.event_name != 'pull_request' || (github.event.pull_request.draft == false || startsWith(github.head_ref, 'mergify/merge-queue/')) }}
runs-on: ubuntu-latest
env:
JWT_SECRET: ci-lint-secret-with-sufficient-length-for-validation
API_KEY_SECRET: ci-lint-api-key-secret-long
DISABLE_SQLITE_AUTO_BACKUP: "true"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v6
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- uses: ./.github/actions/npm-ci-retry
with:
# PR acceleration is not release-candidate provenance.
cache: ${{ github.event_name == 'pull_request' }}
- name: CHANGELOG integrity (nenhum bullet da base pode sumir no merge-result)
run: npm run check:changelog-integrity
- name: Agent-skills generator sync (SKILL.md gerado ≡ catálogo)
run: npm run check:agent-skills-sync
admission-verdict:
# A queue-draft edit run must not leave a check named "Gate / Quality" on the draft: Mergify
# read that skipped check as a finished non-success and dequeued the PR (#18961 on
# 2026-11-04) before the real run reported. Every other run keeps the exact name.
name: ${{ (github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.pull_request.user.login == 'mergify[bot]' && startsWith(github.head_ref, 'mergify/merge-queue/') && github.event.pull_request.head.repo.id == github.event.repository.id) && 'Gate / Quality (queue-draft edit)' || 'Gate / Quality' }}
# Runs on every candidate; only a Mergify queue-draft description edit skips it (see the
# workflow concurrency note): that draft is never what branch protection merges.
if: ${{ always() && !(github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.pull_request.user.login == 'mergify[bot]' && startsWith(github.head_ref, 'mergify/merge-queue/') && github.event.pull_request.head.repo.id == github.event.repository.id) }}
runs-on: ubuntu-latest
timeout-minutes: 5
needs:
- changes
- docs-gates
- fast-gates
- lint-guard
- merge-integrity
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: ${{ github.sha }}
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
package-manager-cache: false
node-version: ${{ env.CI_NODE_VERSION }}
- name: Evaluate exact-candidate admission
env:
NEEDS_JSON: ${{ toJSON(needs) }}
run: node scripts/quality/admission-verdict.mjs quality
- name: Retain admission receipt
if: ${{ always() }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: quality-admission-${{ github.run_id }}-${{ github.run_attempt }}
path: .artifacts/quality-admission.json
if-no-files-found: error
retention-days: 14

View File

@@ -1,73 +0,0 @@
# Publica o export estável do catálogo consumido pelo OmniRoute Radar numa URL
# fixa (asset de release `radar-export-latest`), para o servidor privado do Radar
# (1 GB RAM, nunca clona/builda o OmniRoute) baixá-lo via `RADAR_EXPORT_URL` em
# vez de depender do snapshot gravado no deploy. Fonte: scripts/release/radar-export.mjs.
#
# A URL estável resultante (definir em RADAR_EXPORT_URL no .env do radar-server):
# https://github.com/cheaper-inference/OmniRoute/releases/download/radar-export-latest/export-omniroute.json
name: Radar Export
on:
workflow_dispatch: # o operador pode publicar sob demanda (de qualquer ref)
push:
# `main` e a release ativa (default branch) publicam no mesmo asset estável: o
# radar-server só consome o asset, então um merge de catálogo na release que ficasse
# à espera do cron semanal deixava o feed até 7 dias atrás do README (2026-09-14: a
# linha da Together removida em d6e62ae só saiu do feed com dispatch manual).
branches: [main, "release/**"]
paths:
- open-sse/config/freeModelCatalog.data.ts
- open-sse/config/freeModelCatalog.ts
- open-sse/config/providerRegistry.ts
- open-sse/config/providers/**
- scripts/release/radar-export.mjs
- .github/workflows/radar-export.yml
schedule:
# Diário 03:17 UTC — antes do `radar-feed.timer` do servidor (04:23 UTC), para o ciclo
# do dia já enxergar o export do dia; também mantém geradoEm/proveniência frescos.
- cron: "17 3 * * *"
permissions:
contents: read
concurrency:
group: radar-export-${{ github.ref }}
cancel-in-progress: true
env:
CI_NODE_VERSION: "24"
jobs:
publish-export:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
runs-on: ubuntu-latest
permissions:
contents: write # gh release upload — clobra o asset estável do export
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false # publish usa GH_TOKEN via gh release, não a credencial do checkout
- uses: actions/setup-node@v7
with:
node-version: ${{ env.CI_NODE_VERSION }}
cache: npm
- run: npm ci
env:
ONNXRUNTIME_NODE_INSTALL: "skip"
- name: Generate catalog export with provenance
run: node --import tsx/esm scripts/release/radar-export.mjs "$RUNNER_TEMP/export-omniroute.json"
- name: Publish to the stable release asset
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
TAG="radar-export-latest"
# Cria o release estável na primeira vez; nas seguintes só re-anexa o asset.
if ! gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
gh release create "$TAG" \
--repo "$GITHUB_REPOSITORY" \
--title "Radar catalog export (rolling)" \
--notes "Export estável do catálogo OmniRoute para o Radar. Atualizado automaticamente; NÃO é um release de versão do produto." \
--latest=false
fi
gh release upload "$TAG" "$RUNNER_TEMP/export-omniroute.json" --repo "$GITHUB_REPOSITORY" --clobber

View File

@@ -1,44 +0,0 @@
name: Release acceptance
on:
push:
branches: ["release/v*"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: release-acceptance-${{ github.ref }}
cancel-in-progress: false
jobs:
acceptance:
name: Release acceptance
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: ".node-version"
cache: npm
- uses: ./.github/actions/npm-ci-retry
with:
cache: "false"
- name: Emit shadow acceptance report
run: |
node scripts/quality/validate-release-acceptance.mjs \
--plan tests/fixtures/release-acceptance/plan-lint.json \
--manifests tests/fixtures/release-acceptance/shadow-manifests \
--out release-acceptance-report.json
continue-on-error: true
- uses: actions/upload-artifact@v4
if: always()
with:
name: release-acceptance-report
path: release-acceptance-report.json
if-no-files-found: ignore
retention-days: 30

View File

@@ -1,52 +0,0 @@
name: OpenSSF Scorecard
on:
branch_protection_rule:
schedule:
- cron: "27 7 * * 1"
push:
# Scorecard only accepts the DEFAULT branch — here the active release/vX.Y.Z,
# not `main`. The job below guards on it so a push to any other branch skips.
branches: ["main", "release/**"]
permissions: read-all
# One analysis per ref at a time. The `push` trigger fires on every push to the active
# release branch (~10/hour) and the job guard below only skips INSIDE the run, so each
# push still queued a hosted run (20 queued on 2026-10-17 against the account's
# concurrent-job limit). Scorecard scores repository posture, not the commit: the
# newest push supersedes the older ones and the weekly schedule keeps its own ref.
concurrency:
group: scorecard-${{ github.ref }}
cancel-in-progress: true
jobs:
analysis:
if: ${{ (github.event_name != 'push' || github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) && (github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute') }}
name: Scorecard analysis
runs-on: ubuntu-latest
permissions:
# security-events: write removed — Scorecard findings are advisory and no longer
# uploaded to the code-scanning Security tab (they are supply-chain/posture scores,
# not code vulnerabilities, and drowned out real CodeQL alerts). The run still
# produces the OpenSSF badge (publish_results) and a downloadable SARIF artifact.
id-token: write
contents: read
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Run analysis
uses: ossf/scorecard-action@v2.5.0
with:
results_file: results.sarif
results_format: sarif
publish_results: true
- name: Upload artifact
uses: actions/upload-artifact@v7
with:
name: SARIF file
path: results.sarif
retention-days: 5

View File

@@ -1,35 +0,0 @@
name: semgrep
on:
pull_request:
branches: ["main", "release/**"]
push:
branches: ["main"]
permissions:
contents: read
# Cancel superseded PR runs (same rule as quality.yml). No paths filter on purpose:
# p/secrets must keep scanning docs-only diffs too — credentials leak in .md files.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
semgrep:
runs-on: ubuntu-latest
container:
image: semgrep/semgrep
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run semgrep (advisory)
continue-on-error: true
run: |
semgrep scan --config p/owasp-top-ten --config p/secrets \
--sarif --output semgrep.sarif --metrics off || true
python -c "import json; d=json.load(open('semgrep.sarif')); print('semgrepFindings=%d' % len(d['runs'][0]['results']))" || echo "semgrepFindings=SKIP"
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
with:
name: semgrep-sarif
path: semgrep.sarif
retention-days: 14

43
.github/workflows/sync-upstream.yml vendored Normal file
View File

@@ -0,0 +1,43 @@
name: Sync Upstream
on:
schedule:
# Run every 6 hours
- cron: '0 */6 * * *'
workflow_dispatch:
permissions:
contents: write
jobs:
sync:
name: Sync with upstream
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- name: Configure Git
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
- name: Fetch upstream
run: |
git remote add upstream https://github.com/diegosouzapw/OmniRoute.git || true
git fetch upstream
git fetch origin
- name: Sync main branch
run: |
git checkout main
git merge upstream/main --no-edit || {
echo "Merge conflict detected. Manual intervention required."
exit 1
}
- name: Push changes
run: git push https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/tombii/OmniRoute.git main

View File

@@ -1,61 +0,0 @@
name: Quarantined Tests (debt, not admission)
on:
schedule:
- cron: "17 5 * * *"
workflow_dispatch:
permissions:
contents: read
issues: read
concurrency:
group: quarantine-${{ github.ref }}
cancel-in-progress: false
jobs:
quarantine:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .node-version
cache: npm
- uses: ./.github/actions/npm-ci-retry
- name: Read current tracking issue states
id: inventory
env:
GH_TOKEN: ${{ github.token }}
run: |
node --input-type=module <<'JS'
import { readFileSync, mkdirSync, writeFileSync, appendFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
const inventory = JSON.parse(readFileSync('config/quality/vitest-exclusions.json', 'utf8'));
const states = {};
for (const issue of new Set(inventory.excluded.map(entry => entry.issue))) {
if (!/^#[1-9]\d*$/.test(issue)) throw new Error('Invalid issue reference');
const value = JSON.parse(execFileSync('gh', ['api', `repos/${process.env.GITHUB_REPOSITORY}/issues/${issue.slice(1)}`], { encoding: 'utf8' }));
states[issue] = value.state;
}
mkdirSync('.artifacts/quarantine', { recursive: true });
writeFileSync('.artifacts/quarantine/issue-states.json', JSON.stringify(states, null, 2));
appendFileSync(process.env.GITHUB_OUTPUT, `count=${inventory.excluded.length}\n`);
JS
- name: Validate inventory lifetime and tracker
run: node scripts/check/check-vitest-exclusions.mjs --issue-states .artifacts/quarantine/issue-states.json
- name: Execute quarantined tests
if: ${{ !cancelled() && steps.inventory.outputs.count != '' && steps.inventory.outputs.count != '0' }}
run: npx --no-install vitest run --config vitest.quarantine.config.ts --reporter=default --reporter=json --outputFile.json=.artifacts/quarantine/results.json
- name: Preserve measured failures and issue evidence
if: always()
uses: actions/upload-artifact@v7
with:
name: quarantine-${{ github.sha }}-${{ github.run_attempt }}
path: .artifacts/quarantine/
if-no-files-found: error
retention-days: 14

View File

@@ -1,200 +0,0 @@
name: UI Kit upstream watch
# The CI UI Kit is a vendored snapshot (packages/ui-kit, pinned in UPSTREAM.md), so nothing tells
# the team when Keak ships a new release: 0.0.66 sat in the tree while 0.0.76 was out. Once a day
# this compares the pinned version with the newest `v*` tag upstream. While we are behind it keeps
# ONE sync PR open against the highest release/vX.Y.Z branch (scripts/ci/ui-kit-sync-pr.sh). It
# never merges: every kit release still needs a visual check on the local VPS. When no PR can be
# opened (frozen release, no PR token, a maintainer closed it) ONE tracking issue says what to do.
#
# Secrets:
# UI_KIT_READ_TOKEN read-only token for the private keak-ai/cheaper-inference-ui-kit. When the
# check can't read upstream it reports "unknown": the run stays green but
# warns, and keeps ONE issue open until a later run can read upstream again.
# UI_KIT_SYNC_PR_TOKEN fine-grained token on this repository (Contents and Pull requests: write).
# This repository doesn't let GITHUB_TOKEN create PRs, and a PR it opened
# wouldn't trigger CI. Without this token only the branch is pushed.
on:
schedule:
- cron: "17 9 * * *" # daily 09:17 UTC
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ui-kit-upstream-watch
cancel-in-progress: true
jobs:
watch:
if: ${{ github.event_name != 'schedule' || github.repository == 'cheaper-inference/OmniRoute' }}
name: Compare the pinned kit with the latest upstream release
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write # push chore/ui-kit-sync-latest
issues: write # the tracking issues
pull-requests: write # read the sync PR's state; opening it uses UI_KIT_SYNC_PR_TOKEN
steps:
- name: Resolve the target release branch
id: base
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
BASE=$(gh api "repos/$GITHUB_REPOSITORY/branches" --paginate --jq '.[].name' \
| grep -E '^release/v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1)
[ -n "$BASE" ] || { echo "no release/vX.Y.Z branch" >&2; exit 1; }
FREEZES=$(gh issue list --repo "$GITHUB_REPOSITORY" --label release-freeze --state open \
--json title --jq '.[].title')
# Titles read "release-freeze: v3.8.52 in progress"; v3.8.5 must not match v3.8.52.
VERSION="${BASE#release/}"
if printf '%s\n' "$FREEZES" | grep -qE "release-freeze: ${VERSION//./\\.}([^0-9.]|$)"; then
FROZEN=true
else
FROZEN=false
fi
RED=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "Release branch not green: $BASE in:title" --json number --jq '.[0].number // empty')
{
echo "branch=$BASE"
echo "frozen=$FROZEN"
echo "red=$RED"
} >> "$GITHUB_OUTPUT"
echo "target $BASE (frozen=$FROZEN, base-red=${RED:-none})"
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ steps.base.outputs.branch }}
persist-credentials: false
- name: Check upstream
id: check
env:
UI_KIT_READ_TOKEN: ${{ secrets.UI_KIT_READ_TOKEN }}
run: |
set -euo pipefail
node scripts/check/check-ui-kit-upstream.mjs --json > ui-kit-upstream.json
cat ui-kit-upstream.json
echo "state=$(node -p "require('./ui-kit-upstream.json').state")" >> "$GITHUB_OUTPUT"
- name: Warn about and track an unreadable upstream
env:
GH_TOKEN: ${{ github.token }}
STATE: ${{ steps.check.outputs.state }}
run: |
set -euo pipefail
if [ "$STATE" = "unknown" ]; then
DETAIL=$(node -p "require('./ui-kit-upstream.json').detail")
echo "::warning title=UI Kit upstream watch::$DETAIL"
echo "**UI Kit upstream watch:** state is \`unknown\`, so new kit releases aren't being tracked. $DETAIL" >> "$GITHUB_STEP_SUMMARY"
fi
# Triage may prefix an issue title ("fix: ..."), so match the end of the title. `in:title`
# is a looser phrase search, so it can't decide this on its own. No `|| echo ""` here: a
# failed lookup has to fail the step, not look like "no issue open" and open a duplicate.
NO_TOKEN_TITLE="UI Kit upstream watch can't run: UI_KIT_READ_TOKEN isn't set"
UNREADABLE_TITLE="UI Kit upstream watch can't read upstream"
OPEN=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title \"UI Kit upstream watch can't\"" --limit 100 --json number,title \
| jq -r --arg a "$NO_TOKEN_TITLE" --arg b "$UNREADABLE_TITLE" \
'.[] | select((.title | endswith($a)) or (.title | endswith($b))) | .number')
if [ "$STATE" != "unknown" ]; then
for NUMBER in $OPEN; do
gh issue close "$NUMBER" --repo "$GITHUB_REPOSITORY" --reason completed \
--comment "The watch can read upstream again (state: $STATE)."
done
elif [ -n "$OPEN" ]; then
echo "Already tracked in: $(echo "$OPEN" | sed 's/^/#/' | paste -sd ' ' -)" >> "$GITHUB_STEP_SUMMARY"
else
REASON=$(node -p "require('./ui-kit-upstream.json').reason")
REPO=$(node -p "require('./ui-kit-upstream.json').repo")
# Only a token that really is unset gets the title that says so.
TITLE="$UNREADABLE_TITLE"
if [ "$REASON" = "no-token" ]; then TITLE="$NO_TOKEN_TITLE"; fi
{
echo "$DETAIL"
echo
echo "Until this is fixed, nothing opens when \`$REPO\` gets a new release. \`npm run check:ui-kit-upstream\` still works locally with your git credentials."
echo
echo "The watch needs a read-only token for that repo in the \`UI_KIT_READ_TOKEN\` secret. This issue closes itself on the next run that can read upstream."
echo
echo "Run: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
} > access-body.md
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --body-file access-body.md
fi
- name: Open or update the sync PR
id: sync
if: ${{ steps.check.outputs.state == 'behind' && steps.base.outputs.frozen == 'false' }}
env:
GH_TOKEN: ${{ secrets.UI_KIT_SYNC_PR_TOKEN || github.token }}
HAS_PR_TOKEN: ${{ secrets.UI_KIT_SYNC_PR_TOKEN != '' }}
KIT_TOKEN: ${{ secrets.UI_KIT_READ_TOKEN }}
BASE: ${{ steps.base.outputs.branch }}
BASE_RED_ISSUE: ${{ steps.base.outputs.red }}
run: |
set -euo pipefail
gh auth setup-git
REPO="$GITHUB_REPOSITORY"
LATEST_VERSION=$(node -p "require('./ui-kit-upstream.json').latest.version")
LATEST_COMMIT=$(node -p "require('./ui-kit-upstream.json').latest.commit")
PINNED_COMMIT=$(node -p "require('./ui-kit-upstream.json').pinned.commit")
export REPO LATEST_VERSION LATEST_COMMIT PINNED_COMMIT
scripts/ci/ui-kit-sync-pr.sh
- name: Open, update or close the tracking issue
# Not on an empty state: a failed check says nothing about the pin, so it can't close the issue.
if: ${{ !cancelled() && (steps.check.outputs.state == 'behind' || steps.check.outputs.state == 'up-to-date') }}
env:
GH_TOKEN: ${{ github.token }}
STATE: ${{ steps.check.outputs.state }}
FROZEN: ${{ steps.base.outputs.frozen }}
BASE: ${{ steps.base.outputs.branch }}
DECISION: ${{ steps.sync.outputs.decision }}
BRANCH: ${{ steps.sync.outputs.branch }}
PR_URL: ${{ steps.sync.outputs.pr_url }}
run: |
set -euo pipefail
TITLE="UI kit: a newer upstream release is available"
# Triage may prefix an issue title, so match the end of it, as the step above does.
EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open \
--search "in:title \"$TITLE\"" --limit 100 --json number,title \
| jq -r --arg title "$TITLE" '[.[] | select(.title | endswith($title))][0].number // empty')
if [ "$STATE" = "behind" ] && [ -z "$PR_URL" ]; then
PINNED=$(node -p "require('./ui-kit-upstream.json').pinned.version")
LATEST=$(node -p "require('./ui-kit-upstream.json').latest.version")
{
echo "The vendored kit is pinned at \`$PINNED\`; upstream released \`v$LATEST\`."
echo
if [ "$FROZEN" = "true" ]; then
echo "No sync PR was opened because \`$BASE\` is frozen."
elif [ "$DECISION" = "branch-only" ]; then
echo "\`$BRANCH\` is pushed with the sync, but no PR was opened: the \`UI_KIT_SYNC_PR_TOKEN\` secret isn't set. Open it from that branch against \`$BASE\`."
elif [ "$DECISION" = "hand-edited" ]; then
echo "The open sync PR on \`$BRANCH\` has commits pushed by hand, so the watch won't overwrite them with this release. Update that PR, or close it to let the watch open a new one."
elif [ "$DECISION" = "declined" ]; then
echo "The sync PR for this version was closed without merging, so it stays closed until a newer release."
else
echo "The sync step didn't finish; see $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID."
fi
echo
echo "To sync by hand from the main checkout:"
echo
echo '```'
echo 'git -C _references/cheaper-inference-ui-kit fetch --tags'
echo 'scripts/dev/sync-ui-kit.sh latest'
echo '```'
echo
echo "Then run the kit guards (\`tests/unit/*kit*\`, \`design-kit-bridge\`, \`ui-kit-snapshot-gate\`) and the dashboard typecheck."
} > body.md
# Edited in place: this runs daily, so a comment per run would only be noise.
if [ -n "$EXISTING" ]; then
gh issue edit "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file body.md
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$TITLE" --body-file body.md
fi
elif [ -n "$EXISTING" ]; then
if [ -n "$PR_URL" ]; then
COMMENT="The sync is now tracked in $PR_URL."
else
COMMENT="The pinned kit matches the latest upstream release."
fi
gh issue close "$EXISTING" --repo "$GITHUB_REPOSITORY" --reason completed --comment "$COMMENT"
fi

View File

@@ -1,53 +0,0 @@
name: Validate stable/v3 PR (dormant)
# DORMANT until the 3.9.0 LTS cut creates `stable/v3` (docs/ops/RELEASE_STRATEGY.md).
# The `branches:` filter means this never triggers while that branch does not exist.
#
# `stable/v3` only takes LTS-safe changes: a Conventional title starting with
# fix / docs / chore(i18n) / feat(providers), or anything the maintainer marks
# with the `lts` label. Everything else belongs on `develop` (v4).
#
# `pull_request` (not `pull_request_target`): nothing is checked out and no code
# from the PR runs — the title and labels arrive through env, never inlined into
# the script (zizmor template-injection).
on:
pull_request:
branches: [stable/v3]
types: [opened, edited, synchronize, reopened, labeled, unlabeled]
permissions:
contents: read
concurrency:
group: validate-stable-pr-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
validate:
name: LTS scope (stable/v3)
if: github.base_ref == 'stable/v3'
runs-on: ubuntu-latest
permissions: {}
steps:
- name: Check title scope or lts label
env:
PR_TITLE: ${{ github.event.pull_request.title }}
PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}
run: |
set -euo pipefail
STRATEGY="docs/ops/RELEASE_STRATEGY.md"
case ",${PR_LABELS}," in
*,lts,*)
echo "✅ label 'lts' present — accepted for stable/v3."
exit 0
;;
esac
if printf '%s' "$PR_TITLE" | grep -qE '^((fix|docs)(\([A-Za-z0-9._/-]+\))?|chore\(i18n\)|feat\(providers\))!?: .+'; then
echo "✅ title scope accepted for stable/v3."
exit 0
fi
{
echo "::error title=Not an LTS change::stable/v3 only accepts fix:, docs:, chore(i18n): or feat(providers): titles, or a PR labelled 'lts'. Retarget this PR to develop, or ask a maintainer for the 'lts' label. See ${STRATEGY}."
}
exit 1

View File

@@ -1,69 +0,0 @@
name: Wiki Sync
# Keeps the GitHub wiki in sync with docs/ on every release that lands on main.
# The wiki has no native generator and historically drifts (it sat at "212+ providers /
# 14 strategies / 37 MCP tools" while code was at 226 / 15 / 87, and new docs like
# SUPPLY_CHAIN never appeared). This runs scripts/docs/sync-wiki.mjs, which:
# - ADDS any docs/ page missing from the wiki (curated; internal reports excluded),
# - syncs the four cover-page counts on Home.md.
# It does NOT overwrite existing wiki pages by default: several docs sources still carry
# stale counts (e.g. ARCHITECTURE.md says "177 providers" while the wiki cover is 226),
# so blind overwrite would regress the wiki. Full content parity (--update-existing) is
# gated on regenerating those sources first.
on:
push:
branches: [main]
paths:
- "docs/**"
- "README.md"
- "AGENTS.md"
- "src/shared/constants/routingStrategies.ts"
- "config/i18n.json"
- "open-sse/mcp-server/server.ts"
- "scripts/docs/sync-wiki.mjs"
workflow_dispatch:
permissions:
contents: write
concurrency:
group: wiki-sync
cancel-in-progress: false
jobs:
sync-wiki:
name: Sync wiki with docs
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v7
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: "24"
- name: Clone wiki
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
run: |
git clone "https://x-access-token:${GH_TOKEN}@github.com/${REPO}.wiki.git" wiki
- name: Sync wiki (add missing pages + cover counts)
run: node scripts/docs/sync-wiki.mjs --wiki-dir wiki
- name: Commit & push if changed
run: |
cd wiki
if [ -n "$(git status --porcelain)" ]; then
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add -A
git commit -m "docs(wiki): auto-sync pages + cover counts with docs"
git push
echo "Wiki updated."
else
echo "Wiki already in sync — nothing to push."
fi

297
.gitignore vendored
View File

@@ -1,67 +1,35 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# project-specific directories
/output/
.slim/deepwork/
.omnivscodeagent/
omnirouteCloud/
omnirouteSite/
_cache/
_ideia/
_mono_repo/
_references/
_tasks/
.agents/**
.claude/**
.gemini/**
.code-forge/**
.config/**
.data/**
.logs/**
.tests/**
.coverage/**
/coverage/
.dist/**
.next/**
.build/**
.out/**
# Stryker mutation testing — ephemeral sandbox + generated reports (never commit)
.stryker-tmp/
reports/mutation/
stryker-output-*.json
# Memory Bank and Cursor rules (local-only AI agent context)
memory-bank/
.cursor/rules/core.mdc
.cursor/rules/memory-bank.mdc
# Claude Code local state — runtime files only; shared commands at .claude/commands/ are tracked
.claude/scheduled_tasks.lock
.claude/scheduled_tasks/
.claude/sessions/
.claude/state.json
.claude/settings.local.json
# Root-level underscore-prefixed directories (private/draft — never commit)
/_*/
/_*
# Draft features documentation (internal only)
docs/new-features/
# dependencies
node_modules/
# Also ignore a root node_modules SYMLINK (worktree setups symlink it from the main
# checkout). The trailing-slash pattern above only matches a directory, so without this
# a symlink named node_modules could be staged by `git add -A` and committed.
/node_modules
*.map
.DS_Store
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# Serena AI assistant config (local-only tool, not project code)
.serena/
# testing
coverage/
# next.js
.next/
/out/
# production
/build
/app
cloud/*
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
@@ -71,15 +39,7 @@ yarn-error.log*
# env files (can opt-in for committing if needed)
.env*
# Local gitleaks artifacts (do not commit)
gitleaks-local.json
!.env.example
!.env.selfhost.example
!.env.homolog.example
!.env.devin-bridge.example
# Provider API keys (never commit)
*.api-key
.nvidia-api-key
# vercel
.vercel
@@ -89,10 +49,8 @@ gitleaks-local.json
next-env.d.ts
# data and logs
/data/
.data/
data/
logs/*
test_output.log
# analysis directories (generated, not tracked)
.analysis/
@@ -100,6 +58,38 @@ antigravity-manager-analysis/
.sisyphus/
.plans/
# docs (allow specific tracked files)
docs/*
!docs/ARCHITECTURE.md
!docs/CODEBASE_DOCUMENTATION.md
!docs/CONTRIBUTING.md
!docs/USER_GUIDE.md
!docs/API_REFERENCE.md
!docs/TROUBLESHOOTING.md
!docs/EXECUTION_CONTEXT_PROVIDER_SYNC.md
!docs/TASK_NEBIUS_BACKEND_ENABLEMENT.md
!docs/frontend-backend-provider-gap-report.md
!docs/openapi.yaml
!docs/RELEASE_CHECKLIST.md
!docs/PLANO-IMPLANTACAO.md
!docs/TASKS.md
!docs/FASE-*.md
!docs/adr/
!docs/cli-tools/
!docs/planning/
!docs/improvement-plans/
!docs/api/
!docs/VM_DEPLOYMENT_GUIDE.md
!docs/FEATURES.md
!docs/screenshots/
!docs/i18n/
!docs/i18n/**
!docs/A2A-SERVER.md
!docs/AUTO-COMBO.md
!docs/MCP-SERVER.md
!docs/CLI-TOOLS.md
# open-sse tests
open-sse/test/*
@@ -107,12 +97,10 @@ open-sse/test/*
.github/instructions/codacy.instructions.md
# Playwright
.playwright-mcp/
test-results/
playwright-report/
blob-report/
/cloud/
.tmp/
cloud/
# Security Analysis (standalone project with own git)
security-analysis/
@@ -121,27 +109,18 @@ security-analysis/
clipr/
app.log
*.tgz
.gh-discussions.json
deploy.sh
docker-compose.minimal.yml
# Docker Compose override (local-only, never commit)
docker-compose.override.yml
# Backup directories
app.__qa_backup/
.app-build-backup-*/
backup/
# Build intermediates (.build/) and shippable standalone (dist/).
# These are fully reproducible from source; never committed.
# Layer 1: Next.js now writes to .build/next (was .next); assembled bundle → dist/
# (Previously /app/ was the standalone output; renamed to /dist/ in Layer 1.)
/.build/
/dist/
/.next/
# Production standalone build (created by scripts/prepublish.mjs)
# Conflicts with Next.js App Router detection in dev (root app/ shadows src/app/)
# npm publish still includes it via package.json "files" field
/app/
# Electron
# Electron (subproject dependency lock and build artifacts)
electron/package-lock.json
electron/dist-electron/
electron/node_modules/
icon.iconset/
@@ -154,153 +133,5 @@ vscode-extension/
*.sqlite-wal
*.sqlite-journal
# IDEA
.idea/
# Local OpenCode agent config
.config/
# Empty/dangling files
typescript
/MAX
# Gemini Antigravity agent data
.gemini/
# Superpowers plans/specs (internal tooling, not project code)
docs/superpowers/
# Superpowers visual-companion brainstorm mockups (ephemeral)
.superpowers/
# TIA test-impact map — generated at runtime in CI (build-test-impact-map.mjs), never committed (~21MB)
config/quality/test-impact-map.json
# GitNexus local index
.gitnexus
.worktrees
# Consistent with .dockerignore / .npmignore
.omc/
audit-report.json
bun.lock
# Private environment variables for .http-client
http-client.private.env.json
# Note: _ideia/ (feature-triage drafts) is fully covered by the /_*/ rule above
# and kept as a separate local-only git repo. Never committed to OmniRoute.
# i18n audit artifact (generated by scripts/i18n/audit-dashboard-pages.mjs)
scripts/i18n/_audit.json
scripts/i18n/_pending-keys.json
# Private workflow / skill / command implementations
# These contain proprietary multi-phase logic and should not be committed
.agents/workflows/implement-features-ag.md
.agents/workflows/port-upstream-features-ag.md
.agents/workflows/port-upstream-issues-ag.md
.agents/skills/implement-features/
.claude/commands/implement-features-cc.md
.claude/commands/port-upstream-features-cc.md
.claude/commands/port-upstream-issues-cc.md
.claude/worktrees/
.codegraph/
# Test executable shims belong in the OS temporary directory, not the repository root
/.fakebin-*/
# Fumadocs generated source
.source/
# AI agent local settings and configs
.agents/
.antigravitycli/
/.claude/
# PR Reviews and local feedback files
pr_reviews*.json
/review/
#hidden local data directories (never commit)
.local-data/
.data-dev/
/.junie/
# internal setup prompts with personal credentials — never commit
CODEX-SETUP-PROMPT.md
# Quality ratchet — métricas efêmeras (baseline commitado em config/quality/; métricas não)
config/quality/quality-metrics.json
# Electron desktop build output unpacked into the repo root.
# `electron-builder` (squirrel-windows target) unpacks the packaged app — the
# entire Chromium runtime, ~24k files — directly into the repository root.
# Every rule below is ROOT-ANCHORED (leading `/`) on purpose: a bare `locales/`
# or `resources/` would also swallow tracked sources such as the CLI
# translations in `bin/cli/locales/*.json`.
/OmniRoute.exe
/Uninstall OmniRoute.exe
/uninstallerIcon.ico
/locales/
/resources/
/*.pak
/*.dll
/icudtl.dat
/snapshot_blob.bin
/v8_context_snapshot.bin
/vk_swiftshader_icd.json
/LICENSE.electron.txt
/LICENSES.chromium.html
# Runtime logs (diretório local, nunca versionado)
/logs/
-home-diegosouzapw-dev-automações-bots-yt-downloader-20260504 .txt
-home-diegosouzapw-dev-automações-bots-yt-downloader-20260410 .txt
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.omniroute.md
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.md
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.omniroute-mim.md
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.omniroute-mid.md
omniroute.md
# mise configuration
mise.toml
_artifacts/ # release-green artifacts
.claude-flow/
# ESLint file cache (npm run lint --cache / complexity ratchets)
.eslintcache
.eslintcache-complexity
/.eslintcache-*
# CI/local quality artifacts (eslint-results.json, quality-ratchet.md, etc.)
.artifacts/
/perf-audit*.md
/quality-ratchet/
# Homologation E2E suite (npm run homolog) — real-environment credentials + report output
.env.homolog
tests/homolog/.auth/
tests/homolog/ui/.auth/
homolog-report/
docker-compose.yml.bak
# _tasks e um repo git SEPARADO (ver AGENTS.md). A linha _tasks/ (com barra) NAO
# ignora um SYMLINK chamado _tasks; /_tasks (ancorado) cobre arquivo/symlink/dir na raiz
# e impede que um git add -A recapture o symlink (incidente 2026-08-08).
/_tasks
# CLI local cache/state
.playwright-cli
# Ad-hoc test sandboxes (never tracked — may contain local DBs)
/.sandbox/
.aider*
# check:install-upgrade work trees (~12 GB, disposable)
/.install-upgrade/
# run-translation.mjs writes the state atomically via a per-process temp file
/.i18n-state.json.*.tmp
# Scoped tsc incremental state written by the typecheck gates (typecheck:core / open-sse / api)
.tsbuildinfo-*
# Compiled npm-package build artifact (not source, should not be in git)
/app

View File

@@ -1,107 +0,0 @@
# .gitleaks.toml — Configuração do gitleaks para OmniRoute
# Task 7.18 — PLANO-QUALITY-GATES-FASE7.md
#
# Estende as regras padrão do gitleaks com allowlists específicas do projeto.
#
# INSTRUÇÕES para allowlists:
# Findings legítimos (fixtures de teste, creds OAuth públicas já cobertas pelo
# check-public-creds.mjs, valores de exemplo em docs) devem ser registrados abaixo
# em [[allowlist]] com um comentário explicativo obrigatório.
#
# NÃO adicione uma entrada de allowlist sem justificativa. Cada entrada é revisada
# a cada release (stale-enforcement). Regra: se o finding é um valor real que o
# sistema usa em produção, é um verdadeiro positivo — não allowliste, corrija.
#
# Referência: docs/security/PUBLIC_CREDS.md (credenciais OAuth públicas conhecidas)
# CLAUDE.md Hard Rule #11 (resolvePublicCred obrigatório)
# Herdar TODAS as regras padrão do gitleaks. ATENÇÃO: um config customizado
# SEM [extend].useDefault = true (e sem [[rules]] próprias) resulta em ZERO
# regras — o gitleaks SUBSTITUI o ruleset padrão pelo arquivo, não o estende
# automaticamente. Sem esta seção, `gitleaks --config .gitleaks.toml` nunca
# detecta nada (todo finding vira 0), tornando o gate inerte. Com useDefault,
# a allowlist abaixo é aplicada POR CIMA das ~170 regras padrão.
[extend]
useDefault = true
# Para desabilitar uma regra específica, usar:
# [[rules]]
# id = "rule-id"
# [rules.allowlist]
# description = "..."
# ---------------------------------------------------------------------------
# Allowlist global do projeto
# Entradas aqui são ignoradas em TODAS as varreduras.
# ---------------------------------------------------------------------------
[allowlist]
description = "OmniRoute project-level allowlist — fixtures, test vectors, public OAuth creds"
# Paths a ignorar completamente (node_modules, builds, etc.)
paths = [
'''node_modules''',
'''\.next''',
'''dist''',
'''\.git''',
'''coverage''',
'''\.nyc_output''',
]
# Commits específicos a ignorar (ex: commit que introduziu fixtures de teste)
# commits = []
# Regexes de stopwords — linhas que contêm estes padrões são ignoradas.
# Usar apenas para falsos positivos comprovados com justificativa abaixo.
# stopwords = []
# Regexes de targets (paths de arquivos) que podem ser allowlistados por regra.
# Ver [[allowlist]] por-regra abaixo para granularidade.
# ---------------------------------------------------------------------------
# Allowlist por-regra (adicionar conforme necessário durante o stale review)
# ---------------------------------------------------------------------------
#
# Exemplo (REMOVER / SUBSTITUIR por entradas reais quando necessário):
#
# [[rules]]
# # Allowlistar fixtures de teste que contêm tokens OAuth de exemplo/inválidos
# # Adicionado: 2026-06-13 | Revisar em: v3.9.0 | Justificativa: valores não-reais de teste
# id = "github-fine-grained-pat"
# [rules.allowlist]
# description = "Test fixture PATs — valores sintéticos, não funcionais"
# paths = [
# '''tests/fixtures/''',
# '''tests/unit/''',
# ]
#
[[rules]]
# Falsos-positivos comprovados do generic-api-key — zerados em 2026-07-13 (WS6/D3,
# plano v3.8.49). Revisar em v3.9.0. Nenhum é credencial: dois são NOMES DE CAMPO
# de métricas de latência; o terceiro é o valor PÚBLICO de um beta header da API
# da Anthropic (documentado publicamente, não é segredo).
id = "generic-api-key"
[rules.allowlist]
description = "Field names + public Anthropic beta-header value (não são segredos)"
regexes = [
'''latencyP\d{2}Ms''',
'''interleaved-thinking-2025-05-14''',
# v3.8.49 pre-flight (2026-07-28). Nenhum dos dois e credencial:
# - chave de localStorage do banner de patrocinio (#8723; #10200 bumpou v1->v2,
# generalizado para -v\d+ no round 3 de base-reds #9985), so um identificador de UI;
# - x-api-key PUBLICO do Firefly web (documentado em open-sse/utils/publicCreds.ts:207);
# as duas ocorrencias sinalizadas estao em COMENTARIOS JSDoc, o runtime le de resolvePublicCred().
'''omniroute-kimi-sponsor-banner-dismissed-v\d+''',
# CheaperInference sponsor banner localStorage key (upstream #11196 /
# eb5797370). Same UI-identifier pattern as the kimi banner above, not a
# credential; the generic-api-key rule flags the long hyphenated string.
'''omniroute-cheaperinference-sponsor-banner-dismissed-v\d+''',
'''SunbreakWebUI1''',
# Uzbek dashboard catalog (#13727, src/i18n/messages/uz.json `outputTokenDesc`):
# "Yakunlash/javob tokenlari" = "completion/response tokens". The rule reads the
# `...TokenDesc` key as a token assignment and the translated words as its value.
'''Yakunlash/javob''',
# Feature-flag id from #13439 (src/shared/constants/featureFlagDefinitions.ts):
# `key: "PROTECTED_PRIORITY_INFRA_502_ENABLED"` is a flag name, not a credential.
'''PROTECTED_PRIORITY_INFRA_502_ENABLED''',
]

View File

@@ -1,4 +0,0 @@
#!/usr/bin/env sh
# Hard Rule #16 — no AI/bot Co-Authored-By trailers or AI-generation footers in commit metadata.
# Human co-authors stay. Incident record: #14436.
node scripts/check/check-ai-attribution.mjs --message-file "$1"

23
.husky/pre-commit Executable file → Normal file
View File

@@ -1,20 +1,3 @@
#!/usr/bin/env sh
set -eu
if ! command -v npx >/dev/null 2>&1; then
echo "npx not found in PATH — install the project's Node/npm toolchain before committing." >&2
exit 1
fi
# Cheap, deterministic local gates (re-enabled). Slower checks (i18n drift,
# openapi coverage/security-tiers, env-doc sync) run in CI to keep commits fast.
sh scripts/check/check-git-identity.sh
# The stash is shared by every worktree. Never let a local hook stash another
# session's changes, and never download a missing tool during a commit.
npx --no-install lint-staged --no-stash
node scripts/quality/gate-manifest.mjs
node scripts/check/check-docs-sync.mjs
npm run check:any-budget:t11
node scripts/check/check-tracked-artifacts.mjs
# vendored kit must stay byte-identical to the pinned upstream commit; skips with a warning where the private clone is absent
npm run --silent check:ui-kit-snapshot
npx lint-staged
node scripts/check-docs-sync.mjs
npm run test:unit

View File

@@ -1,15 +0,0 @@
#!/usr/bin/env sh
# .husky/pre-push — intentionally light.
# any-budget + tracked-artifacts already run on pre-commit; re-running them on
# every push only doubles local wall time for the same existence reason (CI still
# enforces both). Keep this hook as a PATH/npm sanity check + reminder.
# Intentionally excludes test:unit / typecheck (slow; covered by CI).
if ! command -v npm >/dev/null 2>&1; then
echo "⚠️ npm not found in PATH — skipping pre-push hooks"
echo " Run 'npm run check:any-budget:t11 && npm run check:tracked-artifacts' manually before pushing."
exit 0
fi
# No-op success: real local gates live in pre-commit; CI owns the rest.
exit 0

File diff suppressed because it is too large Load Diff

View File

@@ -1,40 +0,0 @@
# .mailmap — canonical author identities for git log/shortlog/blame.
#
# Why this file exists: between 2026-08-13 and 2026-08-26 this checkout carried a
# `git config --local` whose user.name was one contributor's ("Xiangzhe" / @xz-dev)
# and whose user.email was ANOTHER contributor's (@backryun). Every commit produced
# on this machine in that window was therefore signed with @backryun's address —
# 237 commits, all in the -0300 timezone, while @backryun's own work commits from
# +0900 and continued normally throughout. The local override was removed on
# 2026-08-26; this file repairs the RECORD without rewriting published history
# (those commits live on release/v3.8.50 and release/v3.8.51, which other sessions
# and open PRs build on — a rewrite would force-push both and orphan the v3.8.50 tag).
#
# Format: Canonical Name <canonical@email> Commit Name <commit@email>
# --- Maintainer: several addresses used over the project's life ---
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diegosouza.pw@gmail.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diegosouza.pw@outlook.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diegosouzapw@users.noreply.github.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> Diego Rodrigues de Sa e Souza <8016841+diegosouzapw@users.noreply.github.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> Diego Souza <8016841+diegosouzapw@users.noreply.github.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diego.souza.pw@gmail.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <souzamiriamrodrigues790@gmail.com>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diego.souza@cdwasolutions.com.br>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> <diegosouzapw@devbox.local>
# --- The misattribution window: name Xiangzhe + @backryun's email, from -0300.
# These are maintainer/session commits, NOT @backryun's contributions.
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> Xiangzhe <bakryun0718@proton.me>
diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> Xiangzhe <diegosouza.pw@gmail.com>
# --- Xiangzhe (@xz-dev) — a distinct contributor; keep their own work intact ---
Xiangzhe <32761048+xz-dev@users.noreply.github.com> <xz-dev@users.noreply.github.com>
Xiangzhe <32761048+xz-dev@users.noreply.github.com> <xiangzhedev@gmail.com>
# --- @backryun's own alternate addresses (their real work, kept intact) ---
backryun <24198422+backryun@users.noreply.github.com> <bakryun0718@proton.me>
backryun <24198422+backryun@users.noreply.github.com> <backryun@daonlab.local>
backryun <24198422+backryun@users.noreply.github.com> <busan011@ormbiz.co.kr>
backryun <24198422+backryun@users.noreply.github.com> <backryun@users.noreply.github.com>

View File

@@ -1,14 +0,0 @@
{
"_comment": "Advisory markdown lint for docs/ + root *.md. Rules that conflict with the existing doc style (heavy inline HTML, long lines, centered headings) are disabled so the gate stays signal-not-noise. Run: npm run lint:md",
"default": true,
"MD013": false,
"MD033": false,
"MD041": false,
"MD024": { "siblings_only": true },
"MD026": false,
"MD036": false,
"MD040": false,
"MD029": false,
"MD007": { "indent": 2 },
"MD046": false
}

View File

@@ -1,122 +0,0 @@
# Mergify merge queue — WS3.4/D5 of the v3.8.49 quality/velocity master plan.
#
# 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.
#
# 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.
# 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
conditions:
- merged
actions:
label:
remove:
- queue

View File

@@ -1 +0,0 @@
24

View File

@@ -4,24 +4,11 @@ data/
**/db.json
# VS Code extension test runtime (large binary, not needed in npm package)
app/vscode-extension/
**/data/
**/db.json
# Source code (pre-built dist/ is published instead)
#
# NOTA (2026-08-05): as entradas `app/*` foram removidas — o diretorio `app/`
# foi renomeado para `dist/` na Layer 1 e nao existe mais. Elas sugeriam um
# layout que ja nao e o do projeto.
#
# NOTE (#3578 / #3821-review): package.json "files" is the source of truth for what
# ships. It now allowlists the backend source closure the MCP server needs at runtime
# (open-sse/, src/lib, src/server, ...) and OVERRIDES the broad src/ + open-sse/ excludes
# below — npm honors files[] over .npmignore for inclusion. These lines are kept only as
# intent/back-stop: if files[] is ever trimmed back to specific paths, they must NOT be
# allowed to re-hide the MCP closure (that would silently reintroduce the --mcp
# ERR_MODULE_NOT_FOUND #3578 fixed). The closure gate in
# tests/unit/mcp-published-files-closure-3578.test.ts asserts the real `npm pack` output
# in both directions (closure present + zero test files), catching such a regression.
# Source code (pre-built app/ is published instead)
src/
open-sse/
docs/
@@ -31,17 +18,6 @@ images/
logs/
scripts/
# Co-located tests must never ship even when their parent dir is allowlisted by files[].
# (Primary guard is the "!**/*.test.*" negations in package.json files[]; this is defense
# in depth for any nested dir the allowlist pulls in.)
**/__tests__/
**/*.test.ts
**/*.test.tsx
**/*.test.js
**/*.test.mjs
**/*.spec.ts
**/*.spec.tsx
# Config/dev files
*.md
!README.md
@@ -50,19 +26,14 @@ scripts/
.github/
.husky/
.vscode/
.agents/
.env*
eslint.config.mjs
prettier.config.mjs
postcss.config.mjs
next.config.mjs
tsconfig.json
tsconfig.typecheck-core.json
tsconfig.typecheck-noimplicit-core.json
playwright.config.ts
vitest.config.ts
next-env.d.ts
llm.txt
# Docker
docker-compose*.yml
@@ -70,12 +41,12 @@ Dockerfile
.dockerignore
# Misc
restart.sh
AGENTS.md
bun.lock
# Build artifacts (pre-built goes inside app/)
/.next/
/node_modules/
.next/
node_modules/
# Ignore large binary files and other build directories
*.tgz
@@ -83,41 +54,5 @@ bun.lock
*.deb
*.rpm
electron/
# Subprojects
clipr/
omnirouteCloud/
omnirouteSite/
vscode-extension/
# Root-level underscore-prefixed directories (private/draft — never publish)
/_*/
# Consistent with .gitignore and .dockerignore
.claude/
.fakebin-*
.eslintcache*
_tasks/
.DS_Store
.idea/
.config/
.data/
.omnivscodeagent/
.omc/
*.sqlite-*
*.tsbuildinfo
security-analysis/
.analysis/
antigravity-manager-analysis/
.sisyphus/
.plans/
app.__qa_backup/
.app-build-backup-*/
.gitnexus
.worktrees
.next-playwright/
test-results/
playwright-report/
blob-report/
coverage/
@omniroute/
app/electron/
app/vscode-extension/

23
.npmrc
View File

@@ -1,23 +0,0 @@
# @lobehub/icons declares UI peers that are not needed by our deep icon imports.
# Keeping peer auto-install disabled prevents npm from pulling @lobehub/ui/mermaid
# back into the tree and reopening npm audit findings for unused packages.
legacy-peer-deps=true
# Network resilience: enlarge npm's fetch retry budget so a transient registry
# socket reset (ECONNRESET) mid-download retries instead of failing the job.
# npm defaults to only 2 retries with short timeouts; `npm ci` in
# electron-release.yml hit ECONNRESET during v3.8.41 publish. Applies to every
# CI workflow (electron / docker / unit) and local installs.
fetch-retries=5
fetch-retry-factor=4
fetch-retry-mintimeout=20000
fetch-retry-maxtimeout=120000
# onnxruntime-node bundles the CPU binaries (bin/napi-v6/...) inside the npm
# package, but its postinstall still tries to fetch the CUDA 12 binaries from
# NuGet on linux/x64 by default (~300MB). Skipping that keeps local/CI installs
# network-free and prevents npm's optional-dependency chain (@huggingface/
# transformers) from being dropped entirely whenever that download fails —
# which previously left `@huggingface/transformers` missing after `npm install`
# and broke startup with a crash in the transformers loader.
onnxruntime-node-install=skip

1
.nvmrc
View File

@@ -1 +0,0 @@
24

View File

@@ -1,37 +0,0 @@
# wasm-bindgen glue + embedded WASM_BASE64. Prettier rewrites the generated JS
# (quotes, wrapping) on any touch of this file; format tinycmsDomMocks.ts instead.
open-sse/executors/tinycmsSigner.ts
# Long reference tables are manually aligned; formatting the whole file causes noisy diffs.
docs/reference/ENVIRONMENT.md
# Generated by `npm run gen:provider-reference`; the generator aligns the tables and
# is their formatter of record. Without this, lint-staged reformats the file whenever
# it is staged and the next generator run reverts it — a diff ping-pong.
docs/reference/PROVIDER_REFERENCE.md
# Dense auto-generated free-tier budget rows (one object per line) — prettier multi-line expand blows past file-size cap 800.
open-sse/config/freeModelCatalog.data.ts
# Generated by scripts/skills/generate-agent-skills.mjs; the generator is their
# formatter of record and check:agent-skills-sync diffs its output byte-for-byte.
# Prettier reformats the frontmatter (blank line after ---), which makes the gate
# fail on any skill that happens to pass through lint-staged.
skills/*/SKILL.md
skills/*/references/*.md
# check:changelog-integrity compares release bullets against the base as exact
# strings. Prettier normalizes markdown emphasis inside them (*from* -> _from_)
# and re-wraps table rows, so any PR that stages CHANGELOG.md would "lose" base
# bullets and turn the merge-integrity job red. The changelog is generated and
# reconciled by scripts/release/*, which are its formatter of record.
CHANGELOG.md
docs/i18n/*/CHANGELOG.md
# Helm templates are Go text/template, not YAML: `{{- if ... }}` at the start of
# a line is a parse error for Prettier's YAML parser. Helm itself is the
# formatter of record here — `helm lint` and `helm template` validate them.
deploy/helm/*/templates/
# packages/ui-kit/ — vendored snapshot of the CI UI Kit; synced verbatim by scripts/dev/sync-ui-kit.sh, formatted upstream.
packages/ui-kit/src/**

View File

@@ -1,22 +0,0 @@
[
{
"name": "CLI entry (omniroute.mjs)",
"path": "bin/omniroute.mjs",
"limit": "15 KB"
},
{
"name": "MCP server entry (mcp-server.mjs)",
"path": "bin/mcp-server.mjs",
"limit": "5 KB"
},
{
"name": "Node runtime support (nodeRuntimeSupport.mjs)",
"path": "bin/nodeRuntimeSupport.mjs",
"limit": "8 KB"
},
{
"name": "Reset password entry (reset-password.mjs)",
"path": "bin/reset-password.mjs",
"limit": "6 KB"
}
]

View File

@@ -1,28 +0,0 @@
# .trivyignore — accepted-risk suppressions for the container image scan
#
# Policy (see docs/security/SUPPLY_CHAIN.md):
# - The Trivy steps in .github/workflows/docker-publish.yml run with
# `ignore-unfixed: true`, so vulnerabilities WITHOUT a published fix are
# already excluded from both the blocking CRITICAL gate and the advisory
# Security-tab upload. You do NOT need an entry here for an unfixable
# base-image OS CVE — it will not be reported.
# - This file is the single auditable home for the rare case where a *fixable*
# CVE must be temporarily accepted (e.g. the upstream fix is not yet in the
# pinned base tag, or the affected package/binary is provably unreachable
# from the proxy request surface and rebuilding now is not justified).
#
# Format — one CVE id per line, each with a justification comment and, where
# possible, an expiry, e.g.:
# # CVE-XXXX-YYYY — <why accepted>; revisit on next base-image bump (YYYY-MM-DD)
# CVE-XXXX-YYYY
#
# Keep this list SHORT and reviewed every release. Prefer fixing (rebuild on a
# patched base / bump the dep) over suppressing. Stale entries are debt.
# CVE-2026-118764 (minimatch 10.2.5, fix 11.0.1) and CVE-2026-118773 (glob 13.0.6, fix 14.0.2)
# live in the npm bundled in the image, and npm 12.2.1 (latest) still declares the
# vulnerable lines. Medium; OmniRoute calls npm with fixed subcommands, so request input
# does not reach npm as a glob. An overlay would cross majors outside npm's ranges.
# Accepted by the maintainer (#18765); revisit when npm ships the fixed lines (2026-12-02).
CVE-2026-118764
CVE-2026-118773

View File

@@ -1,15 +0,0 @@
# Advisory prose lint for OmniRoute docs (Vale — https://vale.sh).
# Warning-first: surfaces vague language, passive voice, and terminology drift without
# blocking CI. The Microsoft style is pulled by the CI step (vale sync / vale-action).
# Project terms live in the OmniRoute vocabulary so they never read as misspellings.
StylesPath = .vale/styles
MinAlertLevel = warning
Packages = Microsoft
Vocab = OmniRoute
[*.md]
BasedOnStyles = Vale, Microsoft
# Code-heavy reference docs and auto-generated catalogs are noisy under prose rules.
[docs/reference/PROVIDER_REFERENCE.md]
BasedOnStyles = Vale

View File

@@ -1,50 +0,0 @@
OmniRoute
combo
combos
[Cc]ombo
[Aa]uto-[Cc]ombo
MCP
A2A
ACP
RTK
Caveman
Troglodita
Qdrant
FTS5
SQLite
LowDB
OAuth
PKCE
SSE
JSON-RPC
LKGP
P2C
Antigravity
Codex
Kiro
Qoder
Pollinations
LongCat
Cerebras
DeepSeek
Groq
Cline
OpenCode
Termux
Electron
Fumadocs
Notion
Obsidian
WebDAV
IPv4
IPv6
SOCKS5
loopback
backoff
changelog
i18n
locale
locales
roadmap
[Ww]ildcard
upstream

122
.vscode/settings.json vendored
View File

@@ -1,5 +1,4 @@
{
"workbench.sideBar.location": "left",
"css.lint.unknownAtRules": "ignore",
"sonarlint.rules": {
"css:S4662": {
@@ -17,126 +16,5 @@
"javascript:S3776": {
"level": "off"
}
},
"git.ignoreLimitWarning": true,
// ─── Git: não adicionar os ~44 repos aninhados (9 worktrees + _references/* +
// _mono_repo/* + _ideia/_tasks/.agents) ao Source Control. Era a causa do
// "validando muito": um git status + watcher por repo. Só o repo raiz fica. ───
"git.autoRepositoryDetection": false,
"git.repositoryScanMaxDepth": 0,
"git.detectSubmodules": false,
"git.autofetch": false,
"git.autorefresh": true,
// ─── Performance: não seguir o symlink de node_modules criado pelas worktrees ───
// As worktrees em .worktrees/ apontam node_modules para o checkout principal;
// sem isto a busca atravessa o symlink mesmo com node_modules excluído.
"search.followSymlinks": false,
// ─── TypeScript server (monorepo grande: ~6,6k arquivos rastreados, Next.js 16) ───
"typescript.tsserver.maxTsServerMemory": 4096,
"typescript.disableAutomaticTypeAcquisition": true,
"typescript.tsc.autoDetect": "off",
"npm.autoDetect": "off",
// O tsserver tem o próprio watcher (independente de files.watcherExclude).
// excludeDirectories evita que ele vigie as árvores pesadas.
"typescript.tsserver.watchOptions": {
"excludeDirectories": [
"**/node_modules",
"**/.next",
"**/.build",
"**/dist",
"**/coverage",
"**/.worktrees",
"**/.claude/worktrees",
"**/electron",
"**/_references",
"**/_mono_repo",
"**/_tasks"
]
},
// Para esconder os diretórios gerados da árvore do Explorer, descomente:
// (MANTIDO comentado — o dono precisa ver _references/_mono_repo/_tasks na árvore.
// A performance é resolvida por watcherExclude + search.exclude + tsserver, sem
// precisar escondê-los do Explorer.)
// "files.exclude": {
// "**/.worktrees": true,
// "**/coverage": true,
// "**/dist": true,
// "**/.build": true,
// "**/.next": true,
// "**/_references": true,
// "**/_mono_repo": true,
// "**/_tasks": true,
// "**/omniroute-*.tgz": true
// },
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/node_modules/**": true,
"**/.next/**": true,
"**/.build/**": true,
"**/dist/**": true,
"**/build/**": true,
"**/out/**": true,
"**/coverage/**": true,
"**/.coverage/**": true,
"**/.nyc_output/**": true,
"**/.cache/**": true,
"**/.turbo/**": true,
"**/.swc/**": true,
"**/.stryker-tmp/**": true,
"**/stryker-output-*/**": true,
"**/playwright-report/**": true,
"**/test-results/**": true,
"**/.worktrees/**": true,
"**/.claude/worktrees/**": true,
"**/electron/**": true,
"**/_references/**": true,
"**/_mono_repo/**": true,
"**/_tasks/**": true,
"**/logs/**": true,
"**/*.tgz": true,
"**/*.tsbuildinfo": true,
"**/OmniRoute-*/**": true,
"**/*-merge-*/**": true,
"**/*-worktree-*/**": true,
"**/*-issues-*/**": true,
"**/*-reorg*/**": true
},
"search.exclude": {
"**/node_modules": true,
"**/.next": true,
"**/.build": true,
"**/dist": true,
"**/build": true,
"**/out": true,
"**/coverage": true,
"**/.coverage": true,
"**/.nyc_output": true,
"**/.cache": true,
"**/.turbo": true,
"**/.swc": true,
"**/.stryker-tmp": true,
"**/stryker-output-*": true,
"**/playwright-report": true,
"**/test-results": true,
"**/.worktrees": true,
"**/.claude/worktrees": true,
"**/electron": true,
"**/_references": true,
"**/_mono_repo": true,
"**/_tasks": true,
"**/logs": true,
"**/*.tgz": true,
"**/*.tsbuildinfo": true,
"**/package-lock.json": true,
"**/OmniRoute-*": true,
"**/*-merge-*": true,
"**/*-worktree-*": true,
"**/*-issues-*": true,
"**/*-reorg*": true
}
}

View File

@@ -1,104 +0,0 @@
# .zizmor.yml — zizmor security audit configuration
# https://github.com/woodruffw/zizmor
#
# zizmor audits GitHub Actions workflows for security anti-patterns:
# • Unpinned third-party actions (supply-chain risk)
# • Script injection via ${{ github.* }} in run: steps
# • pull_request_target misuse (allows untrusted code to reach secrets)
# • Excessive permissions / overly broad GITHUB_TOKEN scopes
# • Cache poisoning via actions/cache with unguarded keys
# • … 20+ additional audits
#
# MOTIVATION (2026-03 incident): the trivy-action/LiteLLM supply-chain attack
# exploited exactly the kind of pull_request_target misconfiguration that zizmor
# detects statically. OmniRoute's npm/Docker/Electron publish workflows are high-
# value targets that warrant proactive audit.
#
# BASELINE STRATEGY: this file starts with an EMPTY ignores list. As zizmor is
# first run against the existing workflows, findings will be reviewed:
# • True positives → fix the workflow (preferred)
# • Accepted risk → add an entry below with a justification comment
# This enforces the same stale-enforcement discipline as other allowlists in
# this project: every ignore requires human sign-off and is subject to review
# at each release cycle.
#
# RATCHET: zizmorFindings metric in quality-baseline.json (direction: down)
# starts advisory; current baseline is frozen at first green run; new findings
# must be remediated or explicitly ignored here.
# ── Global settings ──────────────────────────────────────────────────────────
# Uncomment to pin to a specific minimum severity level.
# min-severity: low # low | medium | high | critical (default: low = all)
# ── Per-rule ignores ─────────────────────────────────────────────────────────
# zizmor ≥1.0 replaced the old top-level `ignores:` list with a `rules:` map
# keyed by audit id. Per-rule config lives under `rules.<audit-id>.ignore`,
# where each entry is `filename` or `filename:line` (line optional, column
# further-optional). See: https://docs.zizmor.sh/configuration/
#
# Format:
# rules:
# <zizmor-audit-id>: # e.g. "unpinned-uses", "template-injection"
# ignore:
# - <workflow-filename> # ignore this audit across the file
# - <workflow-filename>:<line> # or scope to a specific line
#
# Example (do not uncomment without real justification):
#
# rules:
# unpinned-uses:
# # actions/checkout@v6 is pinned at the major-version tag intentionally:
# # GitHub-managed first-party action; SHA pinning buys little against a
# # GitHub-side compromise and adds significant maintenance burden.
# ignore:
# - ci.yml
# Every entry below is an explicit, justified ignore (same stale-review
# discipline as the other allowlists in this project). New ignores require a
# per-rule entry with a justification comment.
rules:
dangerous-triggers:
# deploy-vps.yml uses `on: workflow_run` (after "Publish to Docker Hub").
# zizmor flags workflow_run as "almost always used insecurely", but this one
# is guarded and not exploitable:
# • The deploy job is gated on `github.event.workflow_run.conclusion ==
# 'success'` (deploy-vps.yml job `if:`, L15), so it only runs after a
# successful, trusted upstream run — never on a forked/PR-triggered
# failure.
# • It does NOT checkout or execute untrusted code: the deploy runs over SSH
# using repository secrets; there is no `actions/checkout` of an attacker
# ref in the privileged context.
# Accepted risk, re-review at the next release cycle (added 2026-06-15).
ignore:
- deploy-vps.yml
cache-poisoning:
# zizmor's cache-poisoning audit flags `actions/setup-node` (cache: npm) and
# `actions/cache` steps that populate a cache which a later artifact-publishing
# job could consume — the attack is: a fork PR seeds a poisoned cache that a
# trusted publish run then restores and ships. None of the four entries below
# are exploitable in that way:
#
# • electron-release.yml / npm-publish.yml — PUBLISH workflows that trigger
# ONLY on trusted events: `push: tags v*` + `workflow_dispatch` (electron)
# and `release: [released]` + `workflow_dispatch` + `workflow_call`
# (npm). They NEVER run on a `pull_request` from a fork, so an untrusted
# ref can never populate the npm/node_modules cache they restore. The
# cache key is `hashFiles('package-lock.json')` / `runner.os-node-…`, a
# first-party, lockfile-pinned key on trusted events.
#
# • opencode-plugin-ci.yml / opencode-provider-ci.yml — CI-only workflows
# (lint/test of the two opencode packages). They DO run on `pull_request`,
# but (a) they publish NO artifacts — there is no downstream publish job
# that restores their cache, and (b) GitHub Actions cache is branch-scoped:
# a fork-PR run writes to a PR-isolated cache that base-branch / release
# runs cannot read. The `cache: npm` here only speeds up `npm ci` within
# the same ephemeral CI run.
#
# Accepted risk (first-party caching on trusted/isolated events), re-review at
# the next release cycle (added 2026-06-16).
ignore:
- electron-release.yml
- npm-publish.yml
- opencode-plugin-ci.yml
- opencode-provider-ci.yml

View File

@@ -1,4 +0,0 @@
node_modules
dist
*.log
.DS_Store

View File

@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 OmniRoute contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,191 +0,0 @@
# @omniroute/opencode-plugin-v2
OpenCode v2 plugin (`define({ id, setup })`, Promise API) that publishes the live OmniRoute catalog — models from `/v1/models`, combos from `/api/combos` (least-common-denominator join), enrichment (names + pricing), and usable-provider filtering — into the v2 `catalog.transform`, with `key` + `env` auth via `integration.transform`.
Companion to `@omniroute/opencode-plugin` (OpenCode v1, same repo). The two packages are independent: this one carries its own catalog-mapping logic and the v1 plugin is left untouched.
## Install
```sh
npm install @omniroute/opencode-plugin-v2
```
`opencode.json`:
```json
{
"plugins": [
{
"package": "@omniroute/opencode-plugin-v2",
"options": {
"providerId": "omniroute",
"baseURL": "http://localhost:20128"
}
}
]
}
```
### Local `file://` install
OpenCode resolves a local plugin **directory** by probing the subpaths
`server.*` / `index.*` (then `tui`, `rpc`) at the package root — it never
reads `package.json` `main`/`exports`. A folder exposing only `dist/` is
therefore silently skipped (no `loading plugin`, no error).
This package ships a root `server.js` re-exporting `./dist/index.js` for
exactly that probe, so pointing OpenCode at a local checkout works:
```json
{
"plugins": [
{
"package": "file:///path/to/OmniRoute/@omniroute/opencode-plugin-v2",
"options": {
"providerId": "omniroute",
"baseURL": "http://localhost:20128"
}
}
]
}
```
Prerequisites when targeting a folder: run `npm run build` first (the root
`server.js` re-exports `./dist/index.js`), and keep the folder's root
`server.js` — `dist/` alone is not resolvable by the host.
## Credentials
The plugin needs a gateway key to read the catalog, and looks for one in this
order:
1. **The credential you connected in OpenCode.** The plugin registers an
integration, so `opencode auth` (or the Connect action in the model picker)
can store a key for it. Nothing is written to `opencode.json` — this is the
recommended route.
2. **`apiKey` in the plugin options**, when you want a per-project override.
Remember that this puts the key in a config file you may be committing.
3. **`OMNIROUTE_API_KEY` in the environment.**
If none of the three yields a key, the catalog is empty and the plugin says so
once at startup rather than leaving you with a silent empty model list.
### The management token is a different key
Combos, provider health and enrichment (display names, pricing, free-tier
budgets) come from the gateway's `/api/*` endpoints, which most deployments
gate behind a **management** token rather than the inference key. Set it
explicitly:
```json
"options": {
"baseURL": "http://localhost:20128",
"managementReadToken": "<management read token>"
}
```
The token can also come from the `OMNIROUTE_MANAGEMENT_API_KEY` environment
variable (the option wins when both are set). Resolution order:
`managementReadToken` option, then `OMNIROUTE_MANAGEMENT_API_KEY`, then the
`apiKey` fallback.
Left unset, `managementReadToken` falls back to `apiKey` for backwards
compatibility, and the plugin warns once at startup that the fallback is
active. When a gateway rejects that fallback, the catalog still
publishes — but with raw model ids instead of display names, no canonical
alias dedupe, no pricing and no combos. The plugin warns once per endpoint
when this happens, naming the endpoint and the consequence, so the degraded
catalog is never a mystery. Environment variables must reach the opencode
server process: when the host runs as a service, export the key where the
server reads it, not only in the shell that runs `opencode models`.
## Options
| Key | Default | Notes |
| --------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `providerId` | `"omniroute"` | Provider id and integration id; models publish under `<providerId>/…` |
| `baseURL` | required | OmniRoute gateway root (no `/v1` suffix needed) |
| `apiKey` | connected credential, then `OMNIROUTE_API_KEY` | Chat key for `/v1/*` — see [Credentials](#credentials) |
| `managementReadToken` | option, then `OMNIROUTE_MANAGEMENT_API_KEY`, then `apiKey` | Management key for `/api/*` (combos, providers, enrichment) — usually **not** the same key |
| `displayName` | `"OmniRoute"` | Provider display name |
| `timeoutMs` | `10000` | Per-endpoint fetch timeout |
| `modelCacheTtlMs` | `300000` | Catalog cache TTL and background refresh period (minimum 60000 ms): the served catalog follows the gateway within this window, with no service restart; disk snapshot warms cold starts |
| `timeouts` | per-endpoint override | `{ models, combos, enrichment }` in ms; falls back to `timeoutMs` (`autoCombos` still parses but is ignored — the virtual-entries route is no longer requested) |
| `enrichment` | `true` | Fetch names + pricing (`/api/pricing*`, `/api/free-tier/summary`) |
| `providerTag` | `true` | Prefix a display name with the upstream provider it routes to |
| `geminiSanitization` | `true` | Strip `$schema`/`additionalProperties` from tool schemas sent to Gemini models (`$ref` tools are forwarded untouched) |
| `usableOnly` | `false` | Filter to healthy provisioned providers (`/api/providers`) |
| `combosSource` | `"api"` | Combo source. `"api"` reads `/api/combos` and publishes a combo only when every member passes the filters; `"models"` skips that request and publishes the combo rows `/v1/models` serves. Any preset, `usableOnly`, `providersAllow` or visible/hidden list keeps `"api"` |
| `freeOnly` / `toolsOnly` / `visionOnly` | `false` / `false` / `false` | Filter to free-tier / tool-calling / image-input models; combos with a filtered member are dropped, never partial. Presets filter the pool before the default view ranks it, and a combo publishes only when every resolved member passes (dropped when a member fails or none resolves) |
| `freeSignals` | `["declared"]` | Extra signals that admit a model under `freeOnly`: `priced`, `named`, `provider-named` (see below) |
| `freeProviders` | none | Provider prefixes counted as free by `provider-named` |
| `showcasePerOwner` | `10` | Default-view entries kept per provider |
| `freshPerOwner` | `10` | Default-view fresh entries kept per provider |
| `freshWindowDays` | `90` | Freshness window in days for the fresh branch |
| `usageMemory` | `true` | Restore statically dropped entries named by 30-day usage analytics (needs a management token; inert without one) |
| `visibleModels` / `hiddenModels` | `[]` | Exact (`cc/keep-me`), suffix (`keep-me`), or branch (`prefix/*`) entries ; deny wins ; `"*"` publishes the full catalog and skips narrowing |
| `providersAllow` | `[]` | Provider allowlist by flat name, or branch claim (`prefix/*`) for exhaustive mode ; a branch claim names a branch, a flat entry names a provider prefix |
| `combos` | `true` | Set to `false` to hide every combo (no `/api/combos` request, no combo rows from `/v1/models`) ; models are unchanged |
| `apiFormat.allowAnthropic` | `false` | Route allowlisted ids to the Anthropic API block |
| `apiFormat.anthropicModels` | `[]` | Full model ids routed to Anthropic |
| `apiFormat.anthropicPrefixes` | v1 defaults | Deprecated, warns once — prefer `anthropicModels` |
| `logLevel` / `startupDebug` | `warn` / `false` | Logger verbosity |
`toolsOnly` is off by default, so the full catalog is published. Set
`toolsOnly: true` to hide models without tool calling from the host picker —
useful for agent sessions that call tools on almost every turn. It does not cap
the catalog size, and a very large catalog can still slow the host picker (see
[opencode#47615](https://github.com/anomalyco/opencode/issues/47615)).
Usage memory is on by default. Without a management token it stays inert
(a startup notice is logged) and nothing is restored — the picker stays filtered.
`"*"` publishes the full catalog and ignores showcase and fresh narrowing.
A visible branch keeps a combo when any member is in the branch ; `hiddenModels` removes the same combo the same way. Combos are filtered by members, not by combo id.
A visible entry pins its branch : the whole branch is published, including rows the default view would drop (retired rows, rows past the fresh and showcase caps) ; capability filters and `usableOnly` still apply.
## Inferred free models
`freeOnly` keeps the models the free-tier catalog classifies. That list can lag what the gateway serves, so `freeSignals` lets you opt into a few weaker signals. The default stays `["declared"]`; nothing changes unless you set it. Models admitted by an inferred signal are labelled `(free, inferred)`.
| Signal | Admits a model when |
| ---------------- | ----------------------------------------------------------------------------------------------- |
| `priced` | the pricing table lists `input` and `output` at `0` for its `<provider>/<model>` id |
| `named` | its id ends in `-free` or `:free` and the pricing table holds no price for it (any price field) |
| `provider-named` | its provider prefix ends in `-free`, or is listed in `freeProviders` |
```json
{ "freeOnly": true, "freeSignals": ["declared", "priced", "named"] }
```
What the signals do not do:
- A declared classification always wins. `one-time-initial` and `discontinued` entries are never promoted, and any price field other than zero (`input`, `output`, `cacheRead`, `cacheWrite`) vetoes every inferred signal.
- Bare ids (no provider prefix) are never inferred, and a price stored under a bare id is ignored.
- Router entries (an `auto` or `auto-*` segment after the provider prefix) carry a placeholder zero price, so `priced` skips them. Routers whose price depends on the routed target (`pareto-code`, `bodybuilder`) are not recognised and may be admitted by `priced`, `named` or `provider-named`.
- `freeProviders` matches the provider prefix as served or its alias/canonical twin, case-insensitively.
- With `provider-named` on, no overlay is needed, so the empty-overlay warning is not issued; with the other signals it still is when the overlay is fully empty.
- A zero price can also mean a trial credit or a quota the pricing table does not model. Treat `(free, inferred)` as "looks free", not as a contract.
## Tool calling on Gemini models
Gemini answers `400 INVALID_ARGUMENT` — for the whole request, not just the
offending tool — when a tool declaration carries `$schema` or
`additionalProperties`. Anything that emits standard JSON Schema therefore
breaks tool calling as soon as the chain routes to Gemini.
The plugin strips those keywords from tool schemas bound for a Gemini model of
this provider, and leaves every other request untouched. A tool carrying a
`$ref` is forwarded untouched instead of stripped: removing the reference
would widen the schema to "accept anything". Set
`"geminiSanitization": false` to turn it off.
## Migrating from the v1 plugin
The v2 plugin publishes provider id `X` bare. The v1 plugin published `opencode-X` (native-adapter gate). Sessions pinned to `opencode-X/...` must re-select the model under `X/...`.
## License
MIT

View File

@@ -1,9 +0,0 @@
# Release process — `@omniroute/opencode-plugin-v2`
## Publishing
One package, no ordering: bump `@omniroute/opencode-plugin-v2` (`npm version patch`) and publish it. The plugin carries its own copy of the mapping logic, so a release never has to be coordinated with another package.
## Migration note (`opencode-X` → `X`)
The v1 plugin published provider id `opencode-X` (native-adapter gate). The v2 plugin publishes `X` bare. Sessions pinned to `opencode-X/...` resolve `ModelUnavailableError` — users must re-select the model under `X/...`.

File diff suppressed because it is too large Load Diff

View File

@@ -1,72 +0,0 @@
{
"name": "@omniroute/opencode-plugin-v2",
"version": "0.1.0",
"description": "OmniRoute OpenCode plugin (v2 Promise API): catalog transform with models, combos, enrichment, and naming.",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist",
"server.js",
"README.md",
"LICENSE"
],
"scripts": {
"build": "tsup",
"clean": "rm -rf dist",
"test": "node --import tsx/esm --test tests/*.test.ts",
"prepublishOnly": "npm run clean && npm run build && npm test"
},
"dependencies": {
"zod": "^4.6.7"
},
"devDependencies": {
"@opencode/plugin": "2.0.12",
"@types/node": "^22.19.19",
"tsup": "^8.5.1",
"tsx": "^4.22.3",
"typescript": "^5.9.3"
},
"engines": {
"node": ">=22.22.3"
},
"license": "MIT",
"author": "OmniRoute contributors",
"repository": {
"type": "git",
"url": "https://github.com/cheaper-inference/OmniRoute.git",
"directory": "@omniroute/opencode-plugin-v2"
},
"homepage": "https://github.com/cheaper-inference/OmniRoute/tree/main/%40omniroute/opencode-plugin-v2#readme",
"bugs": {
"url": "https://github.com/cheaper-inference/OmniRoute/issues"
},
"keywords": [
"omniroute",
"opencode",
"opencode-plugin",
"opencode-v2",
"ai-sdk",
"openai-compatible",
"provider",
"catalog",
"combos",
"gemini"
],
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"@opencode/plugin": ">=2.0.12 <3"
},
"overrides": {
"esbuild": "^0.28.1",
"zod": "$zod"
}
}

View File

@@ -1,10 +0,0 @@
// Root entrypoint for OpenCode host plugin loading.
//
// OpenCode 2.x local installs (`file://` directory in `opencode.json`) never
// read package.json `main`/`exports`: the config scan resolves only the
// subpaths ["server", ""] then ["tui"], ["rpc"] from the package directory.
// With only `dist/index.js` present the scan yields `{}` and the plugin is
// silently dropped (no `loading plugin`, no error). This stable re-export
// keeps `dist/` as the only build output while exposing the module the host
// actually probes for.
export { default } from "./dist/index.js";

View File

@@ -1,255 +0,0 @@
import { createHash } from "node:crypto";
import { homedir } from "node:os";
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import type {
OmniRouteEnrichmentEntry,
OmniRouteEnrichmentMap,
OmniRouteProviderConnection,
OmniRouteRawCombo,
OmniRouteRawModelEntry,
} from "./shared/index.js";
import { isHttpUrl } from "./shared/index.js";
export const DEFAULT_MODEL_CACHE_TTL_MS = 300_000 as const;
/**
* Lower bound on the background refresh period. Keeps the loop from spinning
* on configurations that set a tiny TTL (the existing tests use 1 ms) and
* matches the v1 minimum.
*/
export const MIN_REFRESH_INTERVAL_MS = 60_000 as const;
/**
* Breather after a refresh whose models fetch came back empty (gateway down
* or refusing). Transforms inside the window serve last-known-good without
* re-firing the fetch suite. Short on purpose: it only guards the
* pathological case, normal TTL expiry still refetches every window.
*/
export const UNREACHABLE_COOLDOWN_MS = 15_000 as const;
export interface CatalogSnapshot {
models: OmniRouteRawModelEntry[];
combos: OmniRouteRawCombo[];
providers?: OmniRouteProviderConnection[];
enrichment?: OmniRouteEnrichmentMap;
fetchedAt: number;
}
export const SNAPSHOT_FORMAT_VERSION = 2 as const;
/**
* A raw snapshot entry is stale when it cannot be mapped to a publishable
* model: no string `id` (unroutable), or a pre-mapped `api` block missing a
* valid `npm` package (the runner would reject it as `Unsupported package`)
* or a usable `url` (the host would reach the AI SDK with no baseURL).
* Plain `/v1/models` entries carry no `api` block -- it is synthesized at
* publish time -- so only a present-but-invalid block drops the entry.
*/
export function isStaleSnapshotModel(entry: unknown): boolean {
if (!entry || typeof entry !== "object") return true;
const id = (entry as { id?: unknown }).id;
if (typeof id !== "string" || id.length === 0) return true;
const api = (entry as { api?: unknown }).api;
if (api === undefined) return false;
if (!api || typeof api !== "object") return true;
const npm = (api as { npm?: unknown }).npm;
if (typeof npm !== "string" || npm.length === 0) return true;
// Same requirement as `npm`, and the same predicate the options schema
// applies to `baseURL`: a pre-mapped block without a callable `url` publishes
// a model the host cannot route -- see `legacyApiToInfoApi`.
return !isHttpUrl((api as { url?: unknown }).url);
}
interface DiskSnapshotV2 {
v: 2;
identityFingerprint: string;
models: OmniRouteRawModelEntry[];
combos: OmniRouteRawCombo[];
providers?: OmniRouteProviderConnection[];
/**
* Display names, provider labels, pricing and free-tier budgets, as
* `[key, entry]` pairs (a Map does not survive JSON). Persisted because a
* cold start otherwise publishes raw model ids until the first refresh
* completes — which is the moment the snapshot exists to cover.
*/
enrichment?: [string, OmniRouteEnrichmentEntry][];
writtenAt: number;
}
/**
* Ceiling on what one snapshot may occupy on disk. A gateway with thousands of
* models makes this file grow without bound otherwise; past the cap the
* enrichment overlay is dropped first (it is rebuilt on the next refresh)
* rather than losing the catalog itself.
*/
const MAX_SNAPSHOT_BYTES = 32 * 1024 * 1024;
// Suffix for the temp file each write publishes via rename. Monotone per
// process: two writes for one provider (for example across a credential
// rotation) must not share a temp name. Built after the empty-models and
// size-cap guards, so only real attempts consume a value.
let snapshotWriteCounter = 0;
function trimTrailingSlashes(value: string): string {
let i = value.length;
while (i > 0 && value.charCodeAt(i - 1) === 0x2f) i -= 1;
return i === value.length ? value : value.slice(0, i);
}
function normalizeBaseURL(baseURL: string): string {
try {
const parsed = new URL(baseURL);
parsed.hash = "";
parsed.pathname = trimTrailingSlashes(parsed.pathname) || "/";
return parsed.toString();
} catch {
return trimTrailingSlashes(baseURL);
}
}
export function memoryCacheKey(baseURL: string, credentialId: string): string {
return `${baseURL}::${createHash("sha256").update(credentialId).digest("hex")}`;
}
export function snapshotIdentityFingerprint(
baseURL: string,
apiKey: string,
managementReadToken: string
): string {
return createHash("sha256")
.update(JSON.stringify([normalizeBaseURL(baseURL), apiKey, managementReadToken]))
.digest("hex");
}
export function diskSnapshotPath(providerId: string): string {
// OPENCODE_DATA_DIR is honoured verbatim when set: whoever controls the
// process environment already chooses where the process writes, so
// resolving it further would only surprise. The providerId segment stays
// bounded by the options schema (letters, digits, '.', '_' and '-'; never
// "." or ".."), keeping the file inside <dir>/plugins/.
const dir = process.env.OPENCODE_DATA_DIR ?? join(homedir(), ".local", "share", "opencode");
return join(dir, "plugins", `omniroute-${providerId}.json`);
}
export async function readDiskSnapshot(
providerId: string,
identityFingerprint: string,
logger?: { warn: (message: string) => void }
): Promise<CatalogSnapshot | undefined> {
try {
const body = await readFile(diskSnapshotPath(providerId), "utf8");
// A retired snapshot field survives JSON.parse as an unknown key and is
// never read back, so legacy snapshots load with it ignored.
const parsed = JSON.parse(body) as Partial<DiskSnapshotV2> & {
autoCombos?: unknown;
};
void (parsed as { autoCombos?: unknown }).autoCombos;
if (
!parsed ||
typeof parsed.v !== "number" ||
parsed.v !== SNAPSHOT_FORMAT_VERSION ||
typeof parsed.identityFingerprint !== "string" ||
parsed.identityFingerprint !== identityFingerprint
) {
return undefined;
}
if (
!Array.isArray(parsed.models) ||
parsed.models.length === 0 ||
!Array.isArray(parsed.combos)
) {
return undefined;
}
const stale = (parsed.models as unknown[]).filter(isStaleSnapshotModel).length;
const models = (parsed.models as OmniRouteRawModelEntry[]).filter(
(entry) => !isStaleSnapshotModel(entry)
);
if (stale > 0) {
logger?.warn(
`[omniroute-v2] dropping ${stale} stale snapshot entries with an unusable api block`
);
}
if (models.length === 0) return undefined;
return {
models,
combos: parsed.combos as OmniRouteRawCombo[],
providers: Array.isArray(parsed.providers)
? (parsed.providers as OmniRouteProviderConnection[])
: [],
// A snapshot written before this field existed, or one whose overlay was
// dropped for size, simply starts unenriched and recovers on the first
// refresh — the same state as before it was persisted at all.
enrichment: Array.isArray(parsed.enrichment)
? new Map(parsed.enrichment as [string, OmniRouteEnrichmentEntry][])
: undefined,
fetchedAt: typeof parsed.writtenAt === "number" ? parsed.writtenAt : Date.now(),
};
} catch {
return undefined;
}
}
export async function writeDiskSnapshot(
providerId: string,
snapshot: CatalogSnapshot,
identityFingerprint: string,
logger?: { warn: (message: string) => void }
): Promise<void> {
// Monotone per-process suffix: two writes for one provider (for example
// across a credential rotation) must not share a temp name. Declared here
// so the catch below can clean it up; assigned after the guards so only
// real attempts consume a counter value.
let tmp = "";
try {
if (snapshot.models.length === 0) return;
const file = diskSnapshotPath(providerId);
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
const envelope: DiskSnapshotV2 = {
v: 2,
identityFingerprint,
models: snapshot.models,
combos: snapshot.combos,
providers: snapshot.providers ?? [],
enrichment: snapshot.enrichment ? [...snapshot.enrichment.entries()] : undefined,
writtenAt: Date.now(),
};
let payload = JSON.stringify(envelope);
if (
Buffer.byteLength(payload, "utf8") > MAX_SNAPSHOT_BYTES &&
envelope.enrichment !== undefined
) {
delete envelope.enrichment;
payload = JSON.stringify(envelope);
}
if (Buffer.byteLength(payload, "utf8") > MAX_SNAPSHOT_BYTES) {
logger?.warn(
`[omniroute-v2] snapshot for ${providerId} exceeds the size cap, skipping disk write`
);
return;
}
tmp = `${file}.${process.pid}.${snapshotWriteCounter++}`;
await writeFile(tmp, payload, { encoding: "utf8", mode: 0o600 });
await rename(tmp, file);
} catch (err) {
// Best-effort: callers already hold the in-memory entry.
logger?.warn(
`[omniroute-v2] snapshot write failed for ${providerId}: ` +
`${err instanceof Error ? err.message : String(err)}, keeping the in-memory entry`
);
try {
await unlink(tmp);
} catch {
// Ignore: the temp file may not exist (mkdir failed first).
}
}
}
export async function clearDiskSnapshot(providerId: string): Promise<boolean> {
try {
await unlink(diskSnapshotPath(providerId));
return true;
} catch {
return false;
}
}

View File

@@ -1,251 +0,0 @@
import type { LegacyModel } from "./legacy-model.js";
import type { OmniRouteEnrichmentEntry, OmniRouteEnrichmentMap } from "./shared/enrich.js";
import { lookupEnrichment } from "./shared/enrich.js";
import type { OmniRouteRawCombo } from "./shared/combos-map.js";
import type { OmniRouteRawModelEntry } from "./shared/models-map.js";
import { isFreeOnlyFreeType } from "./shared/naming.js";
export interface CapabilityPresetFlags {
freeOnly?: boolean;
/** The caller's inferred-free verdict for this entry (see `inferFreeSignal`). */
freeInferred?: boolean;
toolsOnly?: boolean;
visionOnly?: boolean;
}
/**
* Single subtractive predicate for the capability presets. Reads the
* mapped+enriched entry: `freeOnly` needs the enrichment overlay entry
* (absent entry = not free = dropped), `toolsOnly`/`visionOnly` read the
* mapped capabilities (proven 1:1 with the raw signals). Applied after the
* allowlist at the model and combo collection points. Auto combos are not
* published (#15392), so there is no third point to filter.
*/
export function passesCapabilityPresets(
mapped: LegacyModel,
enrichment: OmniRouteEnrichmentEntry | undefined,
flags: CapabilityPresetFlags
): boolean {
if (
flags.freeOnly === true &&
!isFreeOnlyFreeType(enrichment?.freeType) &&
flags.freeInferred !== true
)
return false;
if (flags.toolsOnly === true && mapped.capabilities.toolcall !== true) return false;
if (
flags.visionOnly === true &&
!(mapped.capabilities.attachment === true || mapped.capabilities.input.image === true)
)
return false;
return true;
}
/**
* Raw-entry form of the preset predicate for the ranks-before-filters
* pool. Reads the same signals as `passesCapabilityPresets` without
* mapping the entry first: `freeOnly` uses `isFreeOnlyFreeType` on the
* overlay row the caller resolved, `toolsOnly` reads `capabilities.tool_calling`,
* `visionOnly`
* reads `capabilities.attachment ?? capabilities.vision` or an `image`
* input modality (same `?? ["text"]` default as the mapper). Neutral
* when no preset is on, so the default view is unchanged without one.
*/
export function passesRawPreset(
raw: OmniRouteRawModelEntry,
enrichment: OmniRouteEnrichmentEntry | undefined,
flags: CapabilityPresetFlags
): boolean {
if (
flags.freeOnly === true &&
!isFreeOnlyFreeType(enrichment?.freeType) &&
flags.freeInferred !== true
)
return false;
if (flags.toolsOnly === true && Boolean(raw.capabilities?.tool_calling ?? false) !== true)
return false;
if (
flags.visionOnly === true &&
!(
Boolean(raw.capabilities?.attachment ?? raw.capabilities?.vision ?? false) ||
new Set(raw.input_modalities ?? ["text"]).has("image")
)
)
return false;
return true;
}
/** True when any preset subtracts: the pool narrows, combos resolve per member. */
export function presetsActive(flags: CapabilityPresetFlags): boolean {
return flags.freeOnly === true || flags.toolsOnly === true || flags.visionOnly === true;
}
/**
* Narrow a raw pool to the entries that pass the presets. The showcase
* and the recent picks rank this narrowed pool instead of ranking
* everything and letting the preset empty the pick. Neutral when no
* preset is on, so the default view is unchanged without one.
*/
export function filterRawPoolByPreset(
entries: readonly OmniRouteRawModelEntry[],
enrichment: OmniRouteEnrichmentMap | undefined,
canonicalToAlias: Map<string, string>,
flags: CapabilityPresetFlags,
isFreeInferred?: (id: string, entry: OmniRouteEnrichmentEntry | undefined) => boolean
): OmniRouteRawModelEntry[] {
if (!presetsActive(flags)) return [...entries];
return entries.filter((entry) => {
if (!entry.id) return false;
const row = lookupEnrichment(entry.id, enrichment, canonicalToAlias);
return passesRawPreset(entry, row, {
...flags,
freeInferred: isFreeInferred?.(entry.id, row) ?? flags.freeInferred,
});
});
}
interface ComboPresetStep {
memberEntries: OmniRouteRawModelEntry[];
deferred: boolean;
failsPreset: boolean;
countable: boolean;
}
function readComboStepField(step: unknown, key: "kind" | "comboName" | "model"): unknown {
return (step as Record<string, unknown> | null | undefined)?.[key];
}
/**
* Fold one combo step list into member entries plus the preset verdict.
* A `combo-ref` step reads the child verdict from `presetByName` (kept
* for dropped combos too): a ref to an unknown name stays deferred, a
* ref to a dropped combo fails. Never looks up an enrichment row for
* the synthesized `combo-ref:<name>` id (there is none). An unknown
* model id fails under an active preset, stays neutral without one.
*/
export function foldComboPresetSteps(
combo: OmniRouteRawCombo,
rawModelById: ReadonlyMap<string, OmniRouteRawModelEntry>,
resolvedByName: ReadonlyMap<string, LegacyModel>,
presetByName: ReadonlyMap<string, boolean>,
enrichment: OmniRouteEnrichmentMap | undefined,
canonicalToAlias: Map<string, string>,
flags: CapabilityPresetFlags,
isFreeInferred?: (id: string, entry: OmniRouteEnrichmentEntry | undefined) => boolean
): ComboPresetStep {
const memberEntries: OmniRouteRawModelEntry[] = [];
const active = presetsActive(flags);
let deferred = false;
let failsPreset = false;
let countable = false;
const memberSteps = Array.isArray(combo.models) ? combo.models : [];
for (const step of memberSteps) {
const kind = readComboStepField(step, "kind");
if (kind === "combo-ref") {
const comboName = readComboStepField(step, "comboName");
if (typeof comboName !== "string" || comboName.length === 0) continue;
if (active && presetByName.get(comboName) === false) {
failsPreset = true;
break;
}
const nested = resolvedByName.get(comboName);
if (!nested) {
deferred = true;
break;
}
if (active) countable = true;
memberEntries.push(synthesizeNestedMember(comboName, nested));
continue;
}
const modelId = readComboStepField(step, "model");
if (typeof modelId !== "string" || modelId.length === 0) continue;
const member = rawModelById.get(modelId);
if (!member) {
if (active) failsPreset = true;
continue;
}
if (active) {
countable = true;
const memberRow = lookupEnrichment(member.id, enrichment, canonicalToAlias);
if (
!passesRawPreset(member, memberRow, {
...flags,
freeInferred: isFreeInferred?.(member.id, memberRow) ?? flags.freeInferred,
})
) {
failsPreset = true;
break;
}
}
memberEntries.push(member);
}
return { memberEntries, deferred, failsPreset, countable };
}
/**
* Record the preset verdict of a resolved combo (published or dropped)
* under its lookup name: `name` trimmed, else `id`. Under an active
* preset a combo with no countable member never passes, so it is
* dropped, never partial.
*/
export function recordComboPresetVerdict(
presetByName: Map<string, boolean>,
combo: OmniRouteRawCombo,
failsPreset: boolean,
countable: boolean,
flags: CapabilityPresetFlags
): boolean {
const comboName =
typeof combo.name === "string" && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
const passes = !presetsActive(flags) || (failsPreset !== true && countable);
presetByName.set(comboName, passes);
return passes;
}
/** Lookup name of a combo: `name` trimmed, else `id`. */
export function comboLookupName(combo: OmniRouteRawCombo): string {
return typeof combo.name === "string" && combo.name.trim().length > 0
? combo.name.trim()
: combo.id;
}
/**
* Synthesize a raw-model entry from an already-resolved nested combo so a
* parent combo's LCD folds the whole nested capability vector (context,
* output, modalities, capabilities) instead of only direct raw members.
* v1 parity (combo member synthesis at nested resolution time).
*/
export function synthesizeNestedMember(name: string, nested: LegacyModel): OmniRouteRawModelEntry {
const inputModalities: string[] = [];
if (nested.capabilities.input.text) inputModalities.push("text");
if (nested.capabilities.input.audio) inputModalities.push("audio");
if (nested.capabilities.input.image) inputModalities.push("image");
if (nested.capabilities.input.video) inputModalities.push("video");
if (nested.capabilities.input.pdf) inputModalities.push("pdf");
const outputModalities: string[] = [];
if (nested.capabilities.output.text) outputModalities.push("text");
if (nested.capabilities.output.audio) outputModalities.push("audio");
if (nested.capabilities.output.image) outputModalities.push("image");
if (nested.capabilities.output.video) outputModalities.push("video");
if (nested.capabilities.output.pdf) outputModalities.push("pdf");
return {
id: `combo-ref:${name}`,
context_length: nested.limit.context,
max_output_tokens: nested.limit.output,
...(nested.limit.input !== undefined ? { max_input_tokens: nested.limit.input } : {}),
owned_by: "combo",
input_modalities: inputModalities,
output_modalities: outputModalities,
capabilities: {
temperature: nested.capabilities.temperature,
// A raw entry carries plain flags; the mapped model widens them to
// `boolean | { field }` (custom reasoning/thinking field). Every
// non-false form means the capability is present, which is all the
// LCD fold reads.
reasoning: nested.capabilities.reasoning !== false,
thinking: nested.capabilities.interleaved !== false,
attachment: nested.capabilities.attachment,
tool_calling: nested.capabilities.toolcall,
},
};
}

View File

@@ -1,233 +0,0 @@
import type { OmniRouteRawModelEntry } from "./shared/index.js";
import { matchesModelFilter, type ModelListFilter } from "./model-filter.js";
/**
* Freshness window in days. The millisecond value below derives from it,
* so tuning the default means touching this line only.
*/
export const FRESH_WINDOW_DAYS = 90;
/**
* Default freshness window in milliseconds. Models curated with a
* `release_date` or `last_updated` inside this window publish without any
* other signal.
*/
export const FRESHNESS_WINDOW_MS = FRESH_WINDOW_DAYS * 24 * 3600 * 1000;
/** How many models each provider keeps in the default showcase. */
export const SHOWCASE_PER_OWNER = 10;
/** How many recent models each provider keeps in the default view. */
export const FRESH_PER_OWNER = 10;
/**
* Convert a freshness window in days to milliseconds. A non-finite or
* non-positive value cannot come through parsed options (the schema rejects
* it), only through direct calls: fall back to the default window instead
* of an unbounded (Infinity) or empty (0) one.
*/
export function freshWindowDaysToMs(days: number): number {
if (!Number.isFinite(days) || days <= 0) return FRESHNESS_WINDOW_MS;
return days * 24 * 3600 * 1000;
}
/**
* Fresh when the newest valid curatorial date (`release_date`, then
* `last_updated`) is inside the window. No fallback to `created`:
* gateway-assembled rows carry the build timestamp there (same value for
* the whole catalog), except openrouter rows which mix an upstream value
* — neither works as a uniform freshness date.
*/
export function isFreshModel(
entry: OmniRouteRawModelEntry,
nowMs: number,
windowMs: number = FRESHNESS_WINDOW_MS
): boolean {
if (!Number.isFinite(windowMs) || windowMs <= 0) windowMs = FRESHNESS_WINDOW_MS;
const candidates = [entry.release_date, entry.last_updated];
let newest = Number.NaN;
for (const raw of candidates) {
if (typeof raw !== "string" || raw.length === 0) continue;
const parsed = Date.parse(raw);
if (Number.isNaN(parsed)) continue;
if (Number.isNaN(newest) || parsed > newest) newest = parsed;
}
if (Number.isNaN(newest)) return false;
if (newest > nowMs) return false;
return nowMs - newest <= windowMs;
}
/**
* Owner group key: explicit `owned_by` first, then the id prefix before
* `/`, else `"unknown"`. Shared by the showcase ranking and the fresh cap
* so both count the same groups.
*/
export function ownerKeyOf(entry: OmniRouteRawModelEntry): string {
if (typeof entry.owned_by === "string" && entry.owned_by.length > 0) return entry.owned_by;
if (typeof entry.id === "string" && entry.id.includes("/"))
return entry.id.slice(0, entry.id.indexOf("/"));
return "unknown";
}
/**
* Recency order shared by the showcase ranking and the fresh cap: newest
* `release_date` first (unknown = oldest), then largest `context_length`.
*/
export function compareByRecency(a: OmniRouteRawModelEntry, b: OmniRouteRawModelEntry): number {
const aDate = typeof a.release_date === "string" ? Date.parse(a.release_date) : NaN;
const bDate = typeof b.release_date === "string" ? Date.parse(b.release_date) : NaN;
const aMs = Number.isNaN(aDate) ? 0 : aDate;
const bMs = Number.isNaN(bDate) ? 0 : bDate;
if (aMs !== bMs) return bMs - aMs;
const aCtx = typeof a.context_length === "number" ? a.context_length : 0;
const bCtx = typeof b.context_length === "number" ? b.context_length : 0;
return bCtx - aCtx;
}
/**
* Read the lifecycle hint the raw gateway row carries, if any. The typed
* entry has no `status` field, so this stays a defensive local read: only
* the exact `"deprecated"` string excludes, anything else (absent,
* mistyped, other value) keeps the entry.
*/
export function readEntryStatus(entry: OmniRouteRawModelEntry): unknown {
return (entry as { status?: unknown }).status;
}
/**
* Flat effort-variant ids the gateway publishes next to their base model
* (e.g. `owner/model-high` beside `owner/model`). Only these seven
* suffixes exclude; any other ending (provider literals) leaves the id
* alone. Returns the base id, or undefined when there is no such suffix.
*/
const FLAT_TIER_SUFFIXES = new Set(["high", "low", "max", "medium", "xhigh", "minimal", "none"]);
export function baseIdOf(id: string): string | undefined {
const slash = id.lastIndexOf("/");
const short = slash >= 0 ? id.slice(slash + 1) : id;
const dash = short.lastIndexOf("-");
if (dash <= 0) return undefined;
const suffix = short.slice(dash + 1).toLowerCase();
if (!FLAT_TIER_SUFFIXES.has(suffix)) return undefined;
const base = short.slice(0, dash);
if (base.length === 0) return undefined;
return slash >= 0 ? id.slice(0, slash + 1) + base : base;
}
/** True when the id is a flat effort-variant id (see `baseIdOf`). */
export function isFlatTierId(id: string): boolean {
return baseIdOf(id) !== undefined;
}
/**
* Pick the showcase ids: per `owned_by` group (prefix before `/`, else
* `"unknown"`), newest `release_date` first (unknown = oldest), then
* largest `context_length`. Providers surface at runtime; nothing is
* hardcoded here.
*/
export function selectShowcaseIds(
entries: readonly OmniRouteRawModelEntry[],
perOwner: number = SHOWCASE_PER_OWNER
): Set<string> {
const groups = new Map<string, OmniRouteRawModelEntry[]>();
for (const entry of entries) {
if (!entry || typeof entry.id !== "string" || entry.id.length === 0) continue;
const owner = ownerKeyOf(entry);
const list = groups.get(owner);
if (list) list.push(entry);
else groups.set(owner, [entry]);
}
const out = new Set<string>();
// A non-finite or non-positive size cannot come through parsed options
// (the schema rejects it), only through direct calls: fall back instead
// of publishing an unbounded group (Infinity) or an empty one (0).
const perOwnerCount = Number.isFinite(perOwner) && perOwner > 0 ? perOwner : SHOWCASE_PER_OWNER;
for (const list of groups.values()) {
const ranked = [...list].sort(compareByRecency);
for (const entry of ranked.slice(0, perOwnerCount)) out.add(entry.id);
}
return out;
}
/**
* Static pass: allowlisted (exact id or short suffix) first, then the
* default view — retired entries and flat effort-variant ids stay out,
* recent entries only up to the per-owner fresh cap, showcased ids pass.
* A pin always wins over every exclusion below.
*/
export function passesWhatServes(
entry: OmniRouteRawModelEntry,
showcased: ReadonlySet<string>,
visibleFilter: ModelListFilter | undefined,
nowMs: number = Date.now(),
freshKept?: ReadonlySet<string>,
windowMs: number = FRESHNESS_WINDOW_MS
): boolean {
if (visibleFilter !== undefined) {
if (matchesModelFilter(entry.id, visibleFilter)) return true;
}
// The raw gateway row may carry a lifecycle hint the typed entry does
// not declare (it already flows through the fetcher untouched).
if (readEntryStatus(entry) === "deprecated") return false;
if (isFlatTierId(entry.id)) return false;
if (isFreshModel(entry, nowMs, windowMs)) {
if (freshKept !== undefined) return freshKept.has(entry.id);
return true;
}
if (showcased.has(entry.id)) return true;
return false;
}
/**
* Rank recent entries per owner (same group key and order as the
* showcase) and keep up to `perOwner` ids per group. Only
* `isFreshModel`-true entries compete; pinned, retired and flat
* effort-variant ids never take a fresh slot.
*/
export function selectFreshKeptIds(
entries: readonly OmniRouteRawModelEntry[],
perOwner: number = FRESH_PER_OWNER,
nowMs: number = Date.now(),
visibleFilter?: ModelListFilter,
windowMs: number = FRESHNESS_WINDOW_MS
): Set<string> {
const perOwnerCount = Number.isFinite(perOwner) && perOwner > 0 ? perOwner : FRESH_PER_OWNER;
const groups = new Map<string, OmniRouteRawModelEntry[]>();
for (const entry of entries) {
if (!entry || typeof entry.id !== "string" || entry.id.length === 0) continue;
if (readEntryStatus(entry) === "deprecated") continue;
if (isFlatTierId(entry.id)) continue;
if (visibleFilter !== undefined) {
if (matchesModelFilter(entry.id, visibleFilter)) continue;
}
if (!isFreshModel(entry, nowMs, windowMs)) continue;
const owner = ownerKeyOf(entry);
const list = groups.get(owner);
if (list) list.push(entry);
else groups.set(owner, [entry]);
}
const out = new Set<string>();
for (const list of groups.values()) {
const ranked = [...list].sort(compareByRecency);
for (const entry of ranked.slice(0, perOwnerCount)) out.add(entry.id);
}
return out;
}
/**
* Whether a statically dropped entry stays dropped under the usage
* memory: retired entries, flat effort-variant ids and entries past the
* per-owner fresh cap are never restored. Pinned ids never reach this
* filter (they pass the static gate already).
*/
export function staysDropped(
entry: OmniRouteRawModelEntry,
freshKept: ReadonlySet<string>,
nowMs: number = Date.now(),
windowMs: number = FRESHNESS_WINDOW_MS
): boolean {
if (readEntryStatus(entry) === "deprecated") return true;
if (isFlatTierId(entry.id)) return true;
if (isFreshModel(entry, nowMs, windowMs) && !freshKept.has(entry.id)) return true;
return false;
}

Some files were not shown because too many files have changed in this diff Show More