Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

28.2 KB
Raw Blame
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";

import ts from "typescript";

const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");

type InventoryKind = "connection" | "credential" | "executor";
type BypassClass = "A" | "B" | "C";

const EXPECTED: Record<InventoryKind, Record<string, number>> = {
  credential: {
    // v3.8.51 #12867 (d6f315018): the two credential-resolution sites that used to
    // live in chatCore.ts (codex 429 and antigravity 422 account rotation) were
    // extracted into the provider execution pipeline. chatCore.ts now only hands
    // `getProviderCredentials` across the seam as a dependency (a reference, not a
    // call), so the two sites are inventoried at their new home — see the
    // property-access branch in countCalls().
    // #14213 (8bf6b60a) re-added one direct call: the opt-in FLUSH_EMPTY_RETRY path picks
    // the next credential for a bounded empty-turn retry. The retry dispatches through
    // executeProviderRequest(), whose assertManagedLeaseFence(attemptConnectionId) rejects a
    // connection other than the leased one — so it is fenced centrally (class A).
    // #14914 moved that loop (and its credential rollback) into
    // chatCore/emptyTurnRetryLoop.ts; the response-path split (chatCore.ts split into
    // response-path leaves) then moved the call site into streamingTail.ts, which now
    // passes `getProviderCredentials` in as a dependency (a reference, not a call) to
    // emptyTurnRetryLoop.ts — still dispatched through executeProviderRequest(), still
    // fenced centrally (class A).
    "open-sse/handlers/chatCore/emptyTurnRetryLoop.ts": 1,
    "open-sse/handlers/chatCore/providerExecutionPipeline.ts": 2,
    "open-sse/services/imageCombo.ts": 1,
    // GHSA-3w2r: keyless providers (local zero-config defaults, keyless
    // remotes) look up an in-scope connection for a connection-scoped API key
    // before running (chat's #9057 rule) — one extra scoped lookup per site.
    "open-sse/services/speechCombo.ts": 2,
    "open-sse/services/videoCombo.ts": 2,
    "src/app/api/compression/compare/verify/route.ts": 1,
    "src/app/api/internal/codex-responses-ws/route.ts": 1,
    // PR #11390: rerank listing endpoint probes configured credentials so the
    // dashboard rerank selector only offers providers that can actually serve.
    "src/app/api/memory/rerank-providers/route.ts": 1,
    "src/app/api/search/providers/route.ts": 3,
    "src/app/api/v1/_shared/elevenLabsProxy.ts": 1,
    "src/app/api/v1/_shared/fishAudioProxy.ts": 1,
    // GHSA-3w2r: keyless providers (local zero-config defaults, keyless
    // remotes) look up an in-scope connection for a connection-scoped API key
    // before running (chat's #9057 rule) — one extra scoped lookup per site.
    "src/app/api/v1/audio/speech/route.ts": 2,
    "src/app/api/v1/_shared/videoModelResolution.ts": 1,
    "src/app/api/v1/audio/transcriptions/route.ts": 3,
    "src/app/api/v1/audio/translations/route.ts": 2,
    "src/app/api/v1/classify/route.ts": 1,
    // v3.8.51 #11754: the second resolveImageRouteModel() call (a duplicate
    // of the retirement-check one hoisted before enforceApiKeyPolicy) was
    // removed as dead redundant code, 6->5. #12653 added combo target
    // resolution with the same shape as imageCombo, 5->6.
    // #15513: added Antigravity/Gemini image edits support branch, 6->7.
    // #14269: SYNTX.ai image edits branch, same quota-preflight credential lookup
    // shape as the sibling provider branches, 7->8.
    // #14619 extracted Firefly's credential lookup into adobeFireflyEdit.ts;
    // the same class-B site moves with it, 8->7 here and 0->1 in the helper.
    "src/app/api/v1/images/edits/route.ts": 7,
    "src/app/api/v1/images/generations/route.ts": 3,
    "src/app/api/v1/images/upscale/route.ts": 1,
    "src/app/api/v1/messages/count_tokens/route.ts": 1,
    "src/app/api/v1/moderations/route.ts": 1,
    // GHSA-3w2r: the local-override lookup now reuses the shared
    // resolveLocalOverrideCredentials (_shared/videoModelResolution.ts), 2->1.
    "src/app/api/v1/music/generations/route.ts": 1,
    "src/app/api/v1/ocr/route.ts": 1,
    "src/app/api/v1/providers/[provider]/embeddings/route.ts": 1,
    "src/app/api/v1/providers/[provider]/images/generations/route.ts": 1,
    "src/app/api/v1/rerank/route.ts": 2,
    "src/app/api/v1/search/route.ts": 2,
    "src/app/api/v1/segment/route.ts": 1,
    "src/app/api/v1/session-leases/route.ts": 1,
    "src/app/api/v1/videos/generations/route.ts": 2,
    // #13788: Codex native web search (/v1/alpha/search) — same quota-preflight credential
    // lookup as web/fetch (class B).
    "src/app/api/v1/alpha/search/route.ts": 1,
    "src/app/api/v1/web/fetch/route.ts": 1,
    // #15703: Firecrawl Map endpoint, same quota-preflight credential lookup as web/fetch (class B).
    "src/app/api/v1/web/map/route.ts": 1,
    // #11088/#11271: third site is the synced local-endpoint route — it resolves
    // credentials through getProviderCredentials with the connection allowlist
    // from resolveLocalSyncedEndpointRoute, and handles allRateLimited, so it is
    // fenced the same way as the two pre-existing sites.
    // #15761: local embeddings resolve credentials through the serving-connection allowlist
    // (getProviderCredentials(provider, null, servingIds)) — one more site (3 -> 4).
    // GHSA-3w2r: keyless providers (local zero-config defaults, keyless
    // remotes) look up an in-scope connection for a connection-scoped API key
    // before running (chat's #9057 rule) — one extra scoped lookup per site.
    "src/lib/embeddings/service.ts": 5,
    "src/lib/images/adobeFireflyEdit.ts": 1,
    // PR #11390: second site is the generic derived-provider listing fallback —
    // read-only key presence probe used to decide whether a configured chat
    // provider may appear in the memory embedding-source dropdown.
    "src/lib/memory/embedding/index.ts": 2,
    "src/lib/search/executeWebSearch.ts": 2,
    "src/lib/skills/webFetchExecution.ts": 1,
    "src/sse/handlers/chat.ts": 2,
    "src/sse/services/auth.ts": 4,
    "src/sse/services/imageCredentialRetry.ts": 1,
  },
  executor: {
    // The three executor.execute() sites that used to sit in chatCore.ts moved
    // with the decomposition: two into the wire-send leaf and one into the
    // streaming leg (same sites, new homes).
    "open-sse/handlers/chatCore/executeProviderRequest.ts": 2,
    "open-sse/handlers/chatCore/streamingResponse.ts": 1,
    "open-sse/handlers/chatCore/cliproxyModelMapping.ts": 1,
    "open-sse/handlers/chatCore/cliproxyapiCredentials.ts": 1,
    // v3.8.51 #11754: the legacy common ChatGPT Web's synthetic
    // image-edit-continuation ChatGptWebExecutor.execute() call (the sole
    // executor.execute() site in this file) was removed with the provider;
    // no executor site remains here. The clean-room restoration delegates
    // through its adapter and does not reintroduce this bypass call site.
    // Gemini Web's own image handler+file (open-sse/handlers/imageGeneration/providers/geminiWeb.ts)
    // was already retired by #11708 (its .execute() site removed then too).
    "open-sse/handlers/videoGeneration.ts": 1,
    "open-sse/services/compression/eval/executorModelClient.ts": 1,
    "src/lib/compression/judgeModelClient.ts": 1,
    "src/lib/services/quotaAutoPing.ts": 1,
  },
  connection: {
    "open-sse/handlers/autoComboCandidates.ts": 1,
    // Two of the three connection re-resolution sites moved into the streaming
    // leg with the decomposition (same sites, new home).
    "open-sse/handlers/chatCore.ts": 1,
    "open-sse/handlers/chatCore/streamingResponse.ts": 2,
    "open-sse/handlers/cursorCliProxy.ts": 1,
    "open-sse/services/alibabaFreeTier.ts": 1,
    "open-sse/services/alibabaFreeTierQuotaFetcher.ts": 1,
    // Family cooldown persist looks the row up to write PSD, not dispatch.
    "open-sse/services/antigravityFamilyCooldown.ts": 1,
    // #12864: on the first REQUEST_REJECTED refusal seen by this process the
    // streak seeder reads the row's lastErrorType/lastErrorAt so a crash loop
    // cannot reset the backoff count on every boot — a state read, not dispatch.
    "open-sse/handlers/chatCore/requestRejectedFailure.ts": 1,
    // #14958: after a successful search the proxy re-reads the connection row it
    // just used so clearAccountError() can wipe a stale lastError/testStatus — a
    // post-dispatch state read, not connection selection, so it stays class C.
    "open-sse/handlers/search/searchProxy.ts": 1,
    // v3.8.50 back-merge additions (f95b03d7): combo routing infra and the
    // volcengine-plan binding/auto-sync services query connections the same
    // way as their classified siblings.
    // v3.8.51 #12746 (6b587d004) split executeTarget out of combo.ts; the
    // persisted-cooldown gate's connection read moved here byte-identically
    // (readConnectionForCooldownGate), so this is the same site, renamed.
    "open-sse/services/combo/executeTargetGates.ts": 1,
    // #15927: providerWildcard.ts no longer queries connections itself — the Alibaba
    // free-tier drained-model filter now reads through getCachedProviderPoolConnections()
    // (open-sse/services/providerConnectionPool.ts), which goes through the shared
    // getCachedProviderConnections() read cache (its getProviderConnections site is the one
    // already inventoried under src/lib/db/readCache.ts). Read-only state lookup, no dispatch, 1->0.
    "open-sse/services/tokenRefresh.ts": 1,
    // #15138: per-account test message config/send — reads the row for its stored test model
    // and active flag; dispatch goes through runSingleModelTest, which refuses managed-lease
    // connections itself (class C).
    "src/app/api/providers/[id]/test-message/route.ts": 3,
    "src/lib/providers/volcPlanAutoSyncBackfill.ts": 1,
    "src/lib/providers/volcenginePlanBinding.ts": 1,
    "src/app/(dashboard)/dashboard/tools/agent-bridge/page.tsx": 1,
    "src/app/api/cloud/auth/route.ts": 1,
    "src/app/api/cloud/credentials/update/route.ts": 1,
    "src/app/api/models/route.ts": 1,
    // #13487 (61198da9e): Test-all reads the provider's rows once only to reject
    // with 409 when every connection is disabled — a state read behind the
    // management route; the per-model probes it dispatches still go through the
    // fenced chat pipeline, so it never selects a connection itself (class C).
    "src/app/api/models/test-all/route.ts": 1,
    "src/app/api/monitoring/health/route.ts": 1,
    "src/app/api/oauth/[provider]/[action]/route.ts": 4,
    "src/app/api/oauth/codex/import/route.ts": 1,
    "src/app/api/oauth/kiro/api-key/route.ts": 1,
    "src/app/api/oauth/kiro/auto-import/route.ts": 2,
    "src/app/api/oauth/kiro/import/route.ts": 1,
    "src/app/api/oauth/kiro/social-exchange/route.ts": 1,
    "src/app/api/playground/simulate-route/route.ts": 1,
    "src/app/api/provider-nodes/[id]/route.ts": 1,
    "src/app/api/providers/[id]/chatgpt-web-codex-doctor/route.ts": 1,
    "src/app/api/providers/[id]/refresh-token/route.ts": 1,
    // #15130: the connection test re-reads the row uncached right before its write so an
    // operator disable that landed mid-probe is honored — a state re-read of the connection
    // under test, never a connection selection (class C).
    "src/app/api/providers/[id]/test/route.ts": 1,
    "src/app/api/providers/bulk/route.ts": 1,
    "src/app/api/providers/client/route.ts": 1,
    "src/app/api/providers/free-onboarding/route.ts": 2,
    "src/app/api/providers/import/route.ts": 1,
    // Base drift (already present before #11754 boarded, from earlier-merged
    // #11698/#11720 retirement PRs): a third getProviderConnections-family
    // call site landed here without a golden-inventory update at the time.
    // +1: bulk PATCH reads the row to carry the operator-disable marker in
    // providerSpecificData next to isActive — a state read, not dispatch.
    "src/app/api/providers/route.ts": 4,
    "src/app/api/providers/test-batch/route.ts": 2,
    "src/app/api/rate-limits/route.ts": 1,
    "src/app/api/services/dario/admin/import-from-omniroute/route.ts": 2,
    // 7a921299 (configurable semantic-cache embeddings): the provider picker reads the connection rows once.
    "src/app/api/settings/cache-config/embeddingOptions.ts": 1,
    "src/app/api/settings/export-json/route.ts": 1,
    "src/app/api/settings/qdrant/embedding-models/route.ts": 1,
    "src/app/api/settings/route.ts": 1,
    "src/app/api/token-health/route.ts": 1,
    "src/app/api/translator/send/route.ts": 1,
    "src/app/api/translator/translate/route.ts": 1,
    "src/app/api/usage/call-logs/route.ts": 1,
    // v3.8.51 #12805 (c042a5188): the reset-credit endpoint now serves codex and
    // grok-cli, so it reads the connection once only to decide which handler runs
    // (resolveResetCreditProvider). Read-only lookup behind requireManagementAuth;
    // the handlers it delegates to carry the auxiliary-lease fence themselves. It
    // never selects a connection to serve a request, so it stays class C.
    "src/app/api/usage/codex-reset-credit/route.ts": 1,
    "src/app/api/usage/quota/route.ts": 1,
    "src/app/api/usage/utilization/route.ts": 1,
    "src/app/api/v1/vscode/[token]/api/tags/route.ts": 1,
    "src/app/api/v1/vscode/raw/[token]/api/tags/route.ts": 1,
    "src/app/api/v1beta/models/route.ts": 1,
    "src/instrumentation-node.ts": 1,
    "src/lib/a2a/skills/providerDiscovery.ts": 1,
    "src/lib/chaos/chaosExecutor.ts": 1,
    "src/lib/cloudAgent/api.ts": 1,
    "src/lib/cloudSync.ts": 1,
    "src/lib/combos/builderOptions.ts": 1,
    "src/lib/copilot/tools.ts": 1,
    // #16190: the retest of gateway-disabled connections loads the inactive rows once per
    // sweep and re-reads a row by id after its test to see whether it was switched back on.
    // State reads only: the retest dispatches through testSingleConnection, which defers
    // while an exclusive lease is active, so it never selects a connection itself (class C).
    "src/lib/credentialHealth/autoDisabledRevalidation.ts": 2,
    "src/lib/credentialHealth/scheduler.ts": 1,
    // Base drift (already present before #11754 boarded, from earlier-merged
    // #11698/#11720 retirement PRs' combined getProviderConnectionById
    // fallback in the three write-path functions): not introduced by this PR.
    // #15485: the priority-0 move-to-top edit re-reads the row by id after reorderConnections (3 -> 4).
    "src/lib/db/providers.ts": 4,
    "src/lib/db/readCache.ts": 2,
    // Local embedding providers: reads the active rows only to build the allowlist of
    // connections whose default model does not conflict with the requested one; the
    // connection itself is still selected by getProviderCredentials (class C).
    "src/lib/embeddings/service.ts": 1,
    "src/lib/freeProviderRankings.ts": 1,
    "src/lib/guardrails/visionBridgeCredentials.ts": 2,
    "src/lib/kimi/tokenRefresh.ts": 1,
    // Test&Add re-reads selected credentials behind the canonical auxiliary lease
    // guard. Class B: FREE lease-capable connections remain usable; ACTIVE leases
    // block the fresh lookup and every physical dispatch (behavioral runner/service tests).
    "src/lib/modelValidation/runner.ts": 1,
    "src/lib/monitoring/providerHealthAutopilot.ts": 1,
    "src/lib/monitoring/providerHealthMatrix.ts": 1,
    "src/lib/oauth/connectionPersistence.ts": 1,
    "src/lib/oauth/services/persistCursorConnection.ts": 1,
    "src/lib/oauth/utils/agyAuthImport.ts": 1,
    "src/lib/oauth/utils/claudeAuthImport.ts": 1,
    "src/lib/oauth/utils/codexAuthImport.ts": 1,
    "src/lib/providerModels/managedModelImport.ts": 1,
    "src/lib/providers/codexConnectionDefaults.ts": 1,
    // Volcano Ark plan connect flow (commit d732cf615): both are connection *persistence*
    // sites, not dispatch. volcenginePlanBinding looks the plan connection up by name to
    // decide update-vs-create during connect (same shape as oauth/connectionPersistence);
    // volcPlanAutoSyncBackfill is a one-shot boot backfill that patches a providerSpecificData
    // flag and issues no upstream call. Neither selects a connection to serve a request, so
    // both stay class C (see CLASSIFICATION below).
    "src/lib/providers/volcPlanAutoSyncBackfill.ts": 1,
    "src/lib/providers/volcenginePlanBinding.ts": 1,
    "src/lib/proxyEgress.ts": 1,
    "src/lib/quota/connectionRecovery.ts": 2,
    "src/lib/sync/bundle.ts": 1,
    // #11495: verify-only sweep queries oauth + cookie connections
    // #13874: the health check re-reads the row inside the refresh lane to see whether
    // a Layer 2 refresh already rotated the token before it POSTs a consumed one (2 -> 3).
    // #15891: after a successful refresh, getRefreshRecoveryUpdate() re-reads the row's
    // rateLimitedUntil so it does not clear an active cooldown's diagnostics — a state
    // read, not connection selection or dispatch, class C like its siblings (3 -> 4).
    "src/lib/tokenHealthCheck.ts": 4,
    "src/lib/tokenHealthCheckCopilot.ts": 1,
    // Selective provider-account transfer: one read of every connection to build the
    // catalog, the export selection and the import match set. Read-only state, no dispatch.
    "src/lib/transfer/providerTransfer.ts": 1,
    "src/lib/usage/callLogs.ts": 1,
    "src/lib/usage/codexResetCredits.ts": 1,
    "src/lib/usage/comboScoringInspector.ts": 1,
    "src/lib/usage/glmResetCards.ts": 1,
    // v3.8.51 #12805 (c042a5188): grok-cli sibling of codexResetCredits.ts, same
    // shape — isConnectionUnavailableToAuxiliaryActivity() gates the lookup, so an
    // ACTIVE exclusive lease defers redemption (409 exclusive_lease_active).
    "src/lib/usage/grokResetCredits.ts": 1,
    "src/lib/usage/providerLimits.ts": 4,
    // #4305 port: after a confirmed reset-credit redemption (whose caller already passed
    // the auxiliary-lease gate) the row is re-read only to check its terminal/codex-scope
    // state before lifting the local quota cooldown — a state read, never connection
    // selection or dispatch, so class C.
    "src/lib/usage/resetCreditCooldownRelease.ts": 1,
    "src/lib/usage/resilienceExplain.ts": 1,
    "src/lib/usage/usageStats.ts": 1,
    "src/lib/vncSession/service.ts": 2,
    "src/lib/warmupScheduler.ts": 1,
    "src/shared/services/codexCatalogRevalidation.ts": 2,
    "src/shared/services/modelSyncScheduler.ts": 1,
    "src/sse/handlers/chatHelpers.ts": 1,
    "src/sse/services/auth.ts": 4,
  },
};

const CLASSIFICATION: Record<InventoryKind, Record<string, BypassClass>> = {
  credential: Object.fromEntries(
    Object.keys(EXPECTED.credential).map((file) => [
      file,
      file === "open-sse/handlers/chatCore/emptyTurnRetryLoop.ts" ||
      file === "src/app/api/v1/session-leases/route.ts" ||
      file === "src/sse/handlers/chat.ts" ||
      file === "src/sse/services/auth.ts"
        ? "A"
        : "B",
    ])
  ),
  executor: {
    "open-sse/handlers/chatCore/executeProviderRequest.ts": "A",
    "open-sse/handlers/chatCore/streamingResponse.ts": "A",
    "open-sse/handlers/chatCore/cliproxyModelMapping.ts": "A",
    "open-sse/handlers/chatCore/cliproxyapiCredentials.ts": "A",
    "open-sse/handlers/videoGeneration.ts": "B",
    "open-sse/services/compression/eval/executorModelClient.ts": "B",
    "src/lib/compression/judgeModelClient.ts": "B",
    "src/lib/services/quotaAutoPing.ts": "B",
  },
  connection: Object.fromEntries(
    Object.keys(EXPECTED.connection).map((file) => [
      file,
      [
        "open-sse/handlers/autoComboCandidates.ts",
        "open-sse/handlers/chatCore.ts",
        "open-sse/handlers/chatCore/streamingResponse.ts",
        "open-sse/services/alibabaFreeTier.ts",
        "open-sse/services/alibabaFreeTierQuotaFetcher.ts",
        "open-sse/services/combo/executeTargetGates.ts",
        "open-sse/services/tokenRefresh.ts",
        "src/app/api/translator/send/route.ts",
        "src/lib/credentialHealth/scheduler.ts",
        "src/lib/modelValidation/runner.ts",
        "src/lib/providers/volcPlanAutoSyncBackfill.ts",
        "src/lib/providers/volcenginePlanBinding.ts",
        "src/lib/services/quotaAutoPing.ts",
        "src/lib/usage/codexResetCredits.ts",
        "src/lib/usage/glmResetCards.ts",
        "src/lib/usage/grokResetCredits.ts",
        "src/lib/usage/providerLimits.ts",
        "src/lib/vncSession/service.ts",
        "src/lib/warmupScheduler.ts",
        "src/shared/services/modelSyncScheduler.ts",
        "src/sse/services/auth.ts",
      ].includes(file)
        ? "B"
        : "C",
    ])
  ),
};

function sourceFiles(directory: string): string[] {
  const absolute = path.join(REPO_ROOT, directory);
  return fs.readdirSync(absolute, { withFileTypes: true }).flatMap((entry) => {
    const relative = path.join(directory, entry.name);
    if (entry.isDirectory()) return sourceFiles(relative);
    return /\.(?:cjs|js|mjs|ts|tsx)$/.test(entry.name) ? [relative] : [];
  });
}

function countCalls(): Record<InventoryKind, Record<string, number>> {
  const actual: Record<InventoryKind, Record<string, number>> = {
    connection: {},
    credential: {},
    executor: {},
  };
  for (const file of [...sourceFiles("src"), ...sourceFiles("open-sse"), ...sourceFiles("bin")]) {
    const text = fs.readFileSync(path.join(REPO_ROOT, file), "utf8");
    const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
    const increment = (kind: InventoryKind) => {
      // Normalize to forward slashes so the frozen inventory is
      // platform-independent (EXPECTED keys are POSIX-style).
      const key = file.split(path.sep).join("/");
      actual[kind][key] = (actual[kind][key] ?? 0) + 1;
    };
    const visit = (node: ts.Node): void => {
      if (ts.isCallExpression(node)) {
        const expression = node.expression;
        if (ts.isIdentifier(expression)) {
          if (
            expression.text === "getProviderCredentials" ||
            expression.text === "getProviderCredentialsWithQuotaPreflight"
          ) {
            increment("credential");
          }
          if (
            expression.text === "getProviderConnectionById" ||
            expression.text === "getProviderConnections"
          ) {
            increment("connection");
          }
        } else if (
          ts.isPropertyAccessExpression(expression) &&
          (expression.name.text === "getProviderCredentials" ||
            expression.name.text === "getProviderCredentialsWithQuotaPreflight")
        ) {
          // Injected-dependency shape. #12867 moved codex/antigravity account
          // rotation behind a seam: chatCore passes `getProviderCredentials` in and
          // the provider execution pipeline calls it off its injected `connection`
          // context. Counting bare identifier calls only would let an
          // extract-to-a-seam refactor silently drop a credential-resolution site
          // out of this inventory, which is exactly what this guard exists to catch.
          increment("credential");
        } else if (
          ts.isPropertyAccessExpression(expression) &&
          expression.name.text === "execute" &&
          ts.isIdentifier(expression.expression) &&
          ["executor", "fallbackExecutor", "providerExecutor", "streamExecutor"].includes(
            expression.expression.text
          )
        ) {
          increment("executor");
        }
      }
      ts.forEachChild(node, visit);
    };
    visit(source);
  }
  return actual;
}

test("hard-lease credential, executor, and connection-query inventory has no unclassified site", () => {
  const actual = countCalls();
  assert.deepEqual(actual, EXPECTED);
  for (const kind of Object.keys(EXPECTED) as InventoryKind[]) {
    assert.deepEqual(Object.keys(CLASSIFICATION[kind]).sort(), Object.keys(EXPECTED[kind]).sort());
    for (const classification of Object.values(CLASSIFICATION[kind])) {
      assert.match(classification, /^[ABC]$/);
    }
  }
});

test("managed request surfaces are fenced centrally or rejected before independent dispatch", () => {
  const chat = fs.readFileSync(path.join(REPO_ROOT, "src/sse/handlers/chat.ts"), "utf8");
  const ws = fs.readFileSync(
    path.join(REPO_ROOT, "src/app/api/internal/codex-responses-ws/route.ts"),
    "utf8"
  );
  const internalKeys = fs.readFileSync(path.join(REPO_ROOT, "src/lib/db/apiKeys.ts"), "utf8");
  const auxiliaryIsolationSources = [
    "src/app/api/providers/[id]/models/route.ts",
    "src/app/api/translator/send/route.ts",
    "src/app/api/translator/translate/route.ts",
    "src/lib/api/modelTestRunner.ts",
    "src/lib/modelValidation/runner.ts",
    "src/lib/services/quotaAutoPing.ts",
    "src/lib/services/quotaAutoPingManual.ts",
    "src/lib/usage/codexResetCredits.ts",
    "src/lib/usage/glmResetCards.ts",
    "src/lib/usage/grokResetCredits.ts",
    "src/lib/vncSession/service.ts",
    "src/lib/warmupScheduler.ts",
    "src/shared/services/modelSyncScheduler.ts",
  ].map((file) => fs.readFileSync(path.join(REPO_ROOT, file), "utf8"));
  const unfencedUsageRefreshSource = fs.readFileSync(
    path.join(REPO_ROOT, "src/lib/usage/providerLimits.ts"),
    "utf8"
  );

  assert.match(chat, /parseManagedLeaseRequestContext\(request\.headers\)/);
  assert.match(chat, /isManagedComboUnsupported/);
  // The fence call sites moved into the leg leaves with the decomposition.
  const eprSource = fs.readFileSync(
    path.join(REPO_ROOT, "open-sse/handlers/chatCore/executeProviderRequest.ts"),
    "utf8"
  );
  const streamingLeg = fs.readFileSync(
    path.join(REPO_ROOT, "open-sse/handlers/chatCore/streamingResponse.ts"),
    "utf8"
  );
  const nonStreamingLeg = fs.readFileSync(
    path.join(REPO_ROOT, "open-sse/handlers/chatCore/nonStreamingResponse.ts"),
    "utf8"
  );
  assert.match(eprSource, /assertManagedLeaseFence\(attemptConnectionId\)/);
  assert.match(
    streamingLeg,
    /assertManagedLeaseFence\(getExecutionConnectionId\(getExecutionCredentials\(\)\)\)/
  );
  // #12867 (d6f315018) extracted codex 429 / antigravity 422 account rotation out
  // of chatCore.ts into the provider execution pipeline. The managed-lease fence was
  // NOT dropped — it now crosses the seam as `policy.allowAccountRotation`. Pin both
  // ends so neither half can be weakened alone: chatCore must keep deriving the
  // policy from `!managedLease` on both legs, and the pipeline must keep gating the
  // codex rotation branch on it. (The antigravity 422 branch, which had no lease
  // fence at all before the extract, is now gated by the same flag.)
  const pipeline = fs.readFileSync(
    path.join(REPO_ROOT, "open-sse/handlers/chatCore/providerExecutionPipeline.ts"),
    "utf8"
  );
  const rotationPolicySites = [
    ...nonStreamingLeg.matchAll(
      /allowAccountRotation: !managedLease && comboStrategy !== "context-relay"/g
    ),
    ...streamingLeg.matchAll(
      /allowAccountRotation: !managedLease && comboStrategy !== "context-relay"/g
    ),
  ];
  assert.equal(
    rotationPolicySites?.length,
    2,
    "both the streaming and the non-streaming leg must derive account rotation from !managedLease"
  );
  assert.match(pipeline, /const canRotateAccount = policy\.allowAccountRotation && !isolateProbe;/);
  assert.match(pipeline, /canRotateAccount &&\s*target\.provider === "codex"/);
  assert.match(pipeline, /canRotateAccount &&\s*target\.provider === "antigravity"/);
  assert.match(ws, /LEASE_UNSUPPORTED_TRANSPORT/);
  assert.match(internalKeys, /!k\.scopes\?\.includes\(EXCLUSIVE_LEASE_SCOPE\)/);
  for (const source of auxiliaryIsolationSources) {
    assert.match(source, /isConnectionUnavailableToAuxiliaryActivity/);
  }
  // Usage/quota refresh is read-only admin telemetry (#11758) and must not inherit
  // the exclusive-lease auxiliary fence that blocks model tests, translation, VNC,
  // reset-credits, and warmup.
  assert.doesNotMatch(unfencedUsageRefreshSource, /isConnectionUnavailableToAuxiliaryActivity/);
});

test("SQLite claim-race retry removes only the lost candidate from the same policy-valid set", () => {
  const auth = fs.readFileSync(path.join(REPO_ROOT, "src/sse/services/auth.ts"), "utf8");

  assert.match(auth, /_leaseCandidateIds: candidateIds/);
  assert.match(auth, /excludeConnectionIds: \[\.\.\.excludedConnectionIds, connection\.id\]/);
  assert.match(
    auth,
    /pendingCredentialSelection =\s*await selectedCredentials\.selectNextLeaseCandidate\?\.\(connectionId\)/
  );
  assert.doesNotMatch(auth, /exclusiveChatRouting|exclusiveCredentialSelection/);
});