mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-26 09:52:11 +03:00
* chore(release): open v3.8.21 development cycle
* fix: pass through valid max_tokens-truncated responses instead of fake 502 (#3572) (#3595)
* fix: /v1/completions returns legacy text-completion format, not chat (#3571) (#3596)
* fix: z.ai/GLM coding plan no longer shows Monthly 0% when no monthly cap (#3580) (#3597)
* docs: mark DISCOVERY_TOOL_DESIGN endpoints as Phase-2 not-yet-implemented (#3498) (#3599)
* fix(agent-bridge): add validate-only upstream-ca/test route (#3488) (#3600)
* fix(gamification): add level/badges/badges-earned profile routes (#3484)
* security(oauth): migrate 5 public client_ids to resolvePublicCred (#3493)
* fix(mcp): ship MCP server source closure in npm files + coverage gate (#3578)
* fix: add reasoning token buffer for combo routing (fixes #3587) (#3588)
Integrated into release/v3.8.21
* Refactor: Extract chatCore phases into modular files (#3598)
Integrated into release/v3.8.21 — chatCore phase modularization. Adjusted: re-derive idempotencyKey for the save path after the check moved into the module (co-authored). Thanks @oyi77!
* docs(changelog): credit #3598 (chatCore modularization) + #3588 (combo reasoning buffer)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(api): implement GET /api/guardrails + POST /api/guardrails/test, drop shadow/guardrails doc-fiction (#3496) (#3602)
Integrated into release/v3.8.21 — implements GET /api/guardrails + POST /api/guardrails/test, removes shadow/guardrails doc-fiction. TDD-validated (5/5) + check-docs-symbols/typecheck/eslint green.
* fix(gemini): isolate textual reasoning wrappers (#3605)
Split-out PR C from #3584. Isolates textual reasoning wrappers (<think>/<thinking>/<thought>/<internal_thought>, including malformed/open tags) into reasoning_content across both the non-streaming sanitizer and the Gemini streaming translator, with split-chunk buffering. Additive to the existing textual tool-call pipeline; does not touch the #3569 native functionResponse path. Integrated into release/v3.8.21. Thanks @dhaern!
* fix(antigravity): normalize Gemini 3.5 Flash tier IDs (#3603)
Split-out PR A from #3584. Normalizes the Antigravity/agy Gemini 3.5 Flash tier IDs to clean public names (gemini-3.5-flash-low/medium/high), maps them to the live upstream IDs at the executor boundary, and removes Antigravity from the global model resolver so the executor owns wire normalization. Maintainer follow-up: kept gemini-3.5-flash-preview as a hidden backward-compat alias routing to the High tier (so saved combos/configs keep working). Live-validated the tier set via the agy CLI catalog. Integrated into release/v3.8.21. Thanks @dhaern!
* fix(agent-bridge): surface real MITM startup-failure cause, not always port 443 (#3606) (#3608)
Integrated into release/v3.8.21 (#3606)
* fix(oauth): surface real Kiro import-token failure cause, not a bare 500 (#3589) (#3609)
Integrated into release/v3.8.21 (#3589)
* docs(opencode-provider): soft-deprecate in favor of @omniroute/opencode-plugin (#3419) (#3613)
Integrated into release/v3.8.21 (#3419)
* fix(usage): normalize Antigravity and agy provider quotas (#3604)
Split-out PR B from #3584. Normalizes Antigravity/agy provider quotas: prefers retrieveUserQuota for live consumption, falls back to fetchAvailableModels and local usage_history, sanitizes cached Provider Limits so retired upstream IDs are not re-exposed, and schedules a deduplicated post-usage refresh. Maintainer follow-up: decoupled the post-usage refresh via a lightweight usageEvents bus (usageHistory no longer dynamic-imports providerLimits) so it does not pull the executors/translator graph into the typecheck-core surface — typecheck:core stays at 0. Integrated into release/v3.8.21. Thanks @dhaern!
* feat(cli): add autostart on/off/toggle shorthand for headless serve mode (#3331) (#3614)
Integrated into release/v3.8.21 (#3331)
* docs(changelog): credit #3603 (Flash tier IDs) + #3604 (provider quotas) + #3605 (reasoning wrappers)
Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>
* fix(review): resolve findings from /review-reviews battery (v3.8.21 hardening) (#3618)
Pre-release hardening from the /review-reviews battery — 15 findings resolved (L1-L13,L15) + L14 live-verified WONTFIX, convergence re-review clean. lint/typecheck:core/test:vitest(146)/build green; zero new test:unit failures vs baseline 797de433f.
* chore(release): v3.8.21 CHANGELOG + i18n + env-doc sync
---------
Co-authored-by: Hernan Javier Ardila Sanchez <hjasgr@gmail.com>
Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Raxxoor <manker_lol@hotmail.com>
222 lines
9.6 KiB
JavaScript
222 lines
9.6 KiB
JavaScript
#!/usr/bin/env node
|
||
// scripts/check/check-docs-symbols.mjs
|
||
// Gate anti-alucinação (docs → código): toda referência a uma rota `/api/...` dentro de
|
||
// docs/**/*.md deve resolver para um `route.ts` real em src/app/api/. Pega endpoint
|
||
// INVENTADO/obsoleto que a IA escreve em docs/PRs descrevendo uma rota que não existe —
|
||
// o padrão recorrente das PRs de docs (ex.: oyi77) que fabricam endpoints/APIs.
|
||
//
|
||
// Complementa os outros gates anti-alucinação:
|
||
// - check-fetch-targets.mjs : fetch("/api/...") na UI → route.ts (código → código)
|
||
// - check-openapi-routes.mjs : path da openapi.yaml → route.ts (spec → código)
|
||
// - este gate : /api/... na prosa/markdown → route.ts (docs → código)
|
||
//
|
||
// LOW-NOISE por design: escopo APENAS a paths de rota `/api/...` (sinal mais alto).
|
||
// Tudo que é ruído conhecido (superfície proxy OpenAI-compat, refs a arquivos-fonte,
|
||
// APIs upstream de terceiros, placeholders) vai para IGNORE com justificativa, NÃO para
|
||
// a allowlist. A allowlist congela só drift REAL pré-existente de docs.
|
||
import fs from "node:fs";
|
||
import path from "node:path";
|
||
import { pathToFileURL } from "node:url";
|
||
|
||
const ROOT = process.cwd();
|
||
const DOCS = path.join(ROOT, "docs");
|
||
const API = path.join(ROOT, "src/app/api");
|
||
|
||
// Padrões que NÃO são rotas internas do OmniRoute (ruído estrutural, não drift).
|
||
// Adicione aqui (com justificativa) em vez da allowlist quando uma categoria gera
|
||
// falsos positivos — a allowlist é só para endpoints stale REAIS.
|
||
const IGNORE = [
|
||
/^\/api\/v1\//, // superfície OpenAI-compat (proxy), não rota interna
|
||
/^\/api\/v1beta\//, // superfície Gemini-compat (proxy)
|
||
/^\/api\/v0\//, // APIs upstream de terceiros citadas em docs de pesquisa
|
||
/^\/api\/v2\//, // idem (deployments etc.)
|
||
/^\/api\/(organizations|map-image|graphql|gql)\b/, // APIs de provedores externos documentadas
|
||
/your-/i, // placeholder de exemplo
|
||
/example/i, // placeholder de exemplo
|
||
/\.{3}/, // placeholder "..."
|
||
/\{\}/, // placeholder de param vazio
|
||
/_(POST|GET|PUT|DELETE|PATCH)$/, // refs estilo trace de rede (gql_POST)
|
||
];
|
||
|
||
// Refs a ARQUIVOS-FONTE, não a URLs (ex.: src/app/api/.../route.ts citado em prosa).
|
||
// O gate só valida URLs de rota, não caminhos de arquivo.
|
||
function isFileRef(p) {
|
||
return /\.(ts|tsx|js|mjs|jsx)$/.test(p) || /\/route$/.test(p);
|
||
}
|
||
|
||
// Refs a `/api/...` que NÃO resolvem para rota real, congeladas para triagem
|
||
// (catraca: bloqueia QUALQUER nova ref inventada em docs). Estas são achados REAIS de
|
||
// drift/alucinação em docs pré-existentes — cada uma precisa de: criar a rota, corrigir
|
||
// o path na doc, ou remover a menção. NÃO adicione novas aqui sem justificativa — esse
|
||
// é o ponto do gate. Issues de tracking devem ser abertas para cada cluster.
|
||
export const KNOWN_STALE_DOC_REFS = new Set([
|
||
// docs/reference/API_REFERENCE.md — guardrails/shadow doc-fiction RESOLVED in #3496:
|
||
// GET /api/guardrails + POST /api/guardrails/test are now REAL routes (wrapping the
|
||
// existing guardrailRegistry); the fictional enable/disable/logs rows and the entire
|
||
// shadow table were removed from the doc (shadow A-B comparison is combo-config +
|
||
// /api/combos/metrics). No allowlist entries needed for these anymore.
|
||
// docs/research/DISCOVERY_TOOL_DESIGN.md — design doc de feature NÃO implementada
|
||
// (Phase 2). Refs INTENCIONAIS: o doc agora traz um banner "⚠️ Not yet implemented
|
||
// — Phase 2" acima da tabela de endpoints. Mantidos aqui até a feature existir. — #3498
|
||
"/api/discovery/results",
|
||
"/api/discovery/results/:id",
|
||
"/api/discovery/scan",
|
||
"/api/discovery/verify/:id",
|
||
// docs/reference/ENVIRONMENT.md — endpoint UPSTREAM do provedor Blackbox Web,
|
||
// citado na descrição de env var (não é rota do OmniRoute):
|
||
"/api/chat",
|
||
// docs/ops/TUNNELS_GUIDE.md — a doc afirma EXPLICITAMENTE que este endpoint NÃO
|
||
// existe ("There is no central /api/settings/tunnels endpoint"); menção pedagógica:
|
||
"/api/settings/tunnels",
|
||
]);
|
||
|
||
function walk(dir, filter, acc = []) {
|
||
if (!fs.existsSync(dir)) return acc;
|
||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||
const p = path.join(dir, e.name);
|
||
if (e.isDirectory()) walk(p, filter, acc);
|
||
else if (filter(e.name)) acc.push(p);
|
||
}
|
||
return acc;
|
||
}
|
||
|
||
export function collectRouteFiles() {
|
||
return new Set(
|
||
walk(API, (n) => /^route\.tsx?$/.test(n)).map((p) =>
|
||
path.relative(ROOT, p).replace(/\\/g, "/")
|
||
)
|
||
);
|
||
}
|
||
|
||
/** Normaliza um segmento dinâmico ({param} / [param] / [...param] / :param) para wildcard. */
|
||
function normSeg(seg) {
|
||
if (/^\[\[?\.{3}.+\]\]?$/.test(seg)) return ""; // catch-all [...x] / [[...x]]
|
||
if (/^\{[^}]+\}$/.test(seg) || /^\[[^\]]+\]$/.test(seg) || /^:[^/]+$/.test(seg)) return " ";
|
||
return seg;
|
||
}
|
||
|
||
// /api/providers/{id}/models → src/app/api/providers/[id]/models/route.ts
|
||
// Casa por contagem de segmentos OU por prefixo (uma doc pode citar só o prefixo de
|
||
// uma rota mais profunda, ex.: /api/auth descrevendo a família /api/auth/login). Qualquer
|
||
// segmento dinâmico ([..]/{..}/:..) casa com um segmento dinâmico real.
|
||
export function resolveApiDocPathToRoute(apiPath, routeFiles) {
|
||
const segs = apiPath
|
||
.replace(/^\//, "")
|
||
.replace(/[?#].*$/, "")
|
||
.split("/")
|
||
.map(normSeg);
|
||
for (const rf of routeFiles) {
|
||
const rsegs = rf
|
||
.replace(/^src\/app\//, "")
|
||
.replace(/\/route\.tsx?$/, "")
|
||
.split("/");
|
||
const rnorm = rsegs.map((rs) => {
|
||
if (/^\[\[?\.{3}.+\]\]?$/.test(rs)) return ""; // catch-all
|
||
if (/^\[[^\]]+\]$/.test(rs)) return " "; // [param]
|
||
return rs;
|
||
});
|
||
const catchAll = rnorm.includes("");
|
||
const effLen = catchAll ? rnorm.indexOf("") : rnorm.length;
|
||
if (!catchAll && segs.length > rnorm.length) continue; // doc mais profunda que a rota
|
||
if (catchAll && segs.length < effLen) continue;
|
||
const cmpLen = Math.min(segs.length, effLen || rnorm.length);
|
||
let match = true;
|
||
for (let i = 0; i < cmpLen; i++) {
|
||
const rs = rnorm[i];
|
||
if (rs === "") break; // catch-all absorve o resto
|
||
if (!(rs === segs[i] || rs === " " || segs[i] === " ")) {
|
||
match = false;
|
||
break;
|
||
}
|
||
}
|
||
if (match) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/** Limpa o path capturado: remove pontuação/ênfase de prosa, fecha brackets pendentes. */
|
||
function cleanCapturedPath(raw) {
|
||
let p = raw.replace(/[.,:;_)>]+$/, "");
|
||
const ob = (p.match(/\[/g) || []).length;
|
||
const cb = (p.match(/\]/g) || []).length;
|
||
const oc = (p.match(/\{/g) || []).length;
|
||
const cc = (p.match(/\}/g) || []).length;
|
||
if (ob !== cb || oc !== cc) {
|
||
// segmento final truncado pelo regex (bracket aberto sem fechar na prosa) → descarta
|
||
p = p.replace(/\/[^/]*[[{][^/]*$/, "");
|
||
}
|
||
return p.replace(/\/$/, ""); // remove barra final (forma de prefixo)
|
||
}
|
||
|
||
// /api/... só conta como URL quando NÃO é a cauda de um caminho de arquivo-fonte
|
||
// (src/lib/api/, @/app/api/, app/api/). O grupo 2 é o path.
|
||
const API_PATH_RE = /(^|[^A-Za-z0-9_/])(\/api\/[A-Za-z0-9_\-/{}\[\].:]+)/g;
|
||
|
||
/** Extrai os paths /api/... distintos de um arquivo markdown (forma URL, não arquivo). */
|
||
export function extractDocApiPaths(src) {
|
||
const out = new Set();
|
||
let m;
|
||
API_PATH_RE.lastIndex = 0;
|
||
while ((m = API_PATH_RE.exec(src))) {
|
||
const p = cleanCapturedPath(m[2]);
|
||
if (p && p !== "/api") out.add(p);
|
||
}
|
||
return [...out];
|
||
}
|
||
|
||
/**
|
||
* Núcleo puro/testável.
|
||
* @param {{file: string, paths: string[]}[]} docPathsByFile
|
||
* @param {Set<string>} routeFiles conjunto de "src/app/api/.../route.ts"
|
||
* @param {Set<string>} allowlist paths stale congelados
|
||
* @returns {string[]} misses no formato "file → /api/path"
|
||
*/
|
||
export function findStaleDocApiRefs(docPathsByFile, routeFiles, allowlist) {
|
||
const misses = [];
|
||
for (const { file, paths } of docPathsByFile) {
|
||
for (const p of paths) {
|
||
if (IGNORE.some((rx) => rx.test(p))) continue;
|
||
if (isFileRef(p)) continue;
|
||
if (allowlist.has(p)) continue;
|
||
if (!resolveApiDocPathToRoute(p, routeFiles)) {
|
||
misses.push(`${file} → ${p}`);
|
||
}
|
||
}
|
||
}
|
||
return misses;
|
||
}
|
||
|
||
function main() {
|
||
const routeFiles = collectRouteFiles();
|
||
// docs/i18n/** são espelhos auto-gerados das docs canônicas — validar só o canônico
|
||
// evita 40× de ruído duplicado (e os mirrors herdam qualquer fix do canônico).
|
||
// docs/superpowers/** são planos internos de implementação (snapshots históricos
|
||
// de intenção — podem citar rotas planejadas/abandonadas), não claims sobre o
|
||
// código atual; fora do escopo do gate (drift surgiu no ciclo v3.8.18).
|
||
const docFiles = walk(DOCS, (n) => /\.md$/.test(n)).filter((f) => {
|
||
const rel = path.relative(ROOT, f).replace(/\\/g, "/");
|
||
return !rel.startsWith("docs/i18n/") && !rel.startsWith("docs/superpowers/");
|
||
});
|
||
const docPathsByFile = docFiles.map((f) => ({
|
||
file: path.relative(ROOT, f).replace(/\\/g, "/"),
|
||
paths: extractDocApiPaths(fs.readFileSync(f, "utf8")),
|
||
}));
|
||
const misses = findStaleDocApiRefs(docPathsByFile, routeFiles, KNOWN_STALE_DOC_REFS);
|
||
if (misses.length) {
|
||
console.error(
|
||
`[check-docs-symbols] ${misses.length} ref(s) /api em docs sem rota real:\n` +
|
||
misses.map((m) => " ✗ " + m).join("\n") +
|
||
`\n → crie o route.ts, corrija o path na doc, ou (se for upstream/placeholder)` +
|
||
` adicione um padrão a IGNORE com justificativa. NÃO adicione à allowlist sem` +
|
||
` confirmar que é drift pré-existente real.`
|
||
);
|
||
process.exit(1);
|
||
}
|
||
console.log(
|
||
`[check-docs-symbols] OK — ${docFiles.length} docs canônicas, ` +
|
||
`${routeFiles.size} rotas conhecidas, ${KNOWN_STALE_DOC_REFS.size} stale congeladas`
|
||
);
|
||
}
|
||
|
||
if (import.meta.url === pathToFileURL(process.argv[1] || "").href) main();
|