From 344b27bb311fb90f2c9d56e87e504bd2d39a2ec3 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sat, 14 Nov 2026 02:33:42 -0500 Subject: [PATCH 1/3] Allow explicitly approved GPT-5.4 checker groups --- docs/SUPPORT_CHECKER_UPGRADE.md | 29 +- ...upport-independent-checks-token-counter.ts | 35 ++ worker/src/support-paid-bootstrap.ts | 21 +- worker/src/support-paid-checker-group.test.ts | 493 ++++++++++++++++++ 4 files changed, 570 insertions(+), 8 deletions(-) create mode 100644 worker/src/support-independent-checks-token-counter.ts create mode 100644 worker/src/support-paid-checker-group.test.ts diff --git a/docs/SUPPORT_CHECKER_UPGRADE.md b/docs/SUPPORT_CHECKER_UPGRADE.md index 5761fc6..228ba6f 100644 --- a/docs/SUPPORT_CHECKER_UPGRADE.md +++ b/docs/SUPPORT_CHECKER_UPGRADE.md @@ -15,11 +15,30 @@ retaining the complete user envelope as data. The verdict schema remains named The host's [checker adapter](../worker/src/support-independent-checks-model.ts) delegates this contract and the route-policy hash to the SDK. -The SDK's explicit provider-group mode is opt-in. This host retains its existing -endpoint-qualified route configuration and model allowlists; this dependency -adoption does not enable provider-group selection or add a price policy. Any -future opt-in requires separate current route, pricing, privacy and tokenizer -qualification. Customer AI remains off. +The normal paid bootstrap also permits one explicit learning/engineering +checker-only tuple: +`openai/gpt-5.4` / `Azure` / `azure` / `max_completion_tokens` with +`providerSelectionScope:'provider_group'`. Route, static checker allowlist and +current Admin approval must independently select that scope. The route must +include a hash-bound `providerMaxPrice` with finite prompt/completion prices in +USD per million tokens and `request:0`; the SDK checks its worst-case token cost +against configured and current total-cost caps. Any change requires current +approval of the new policy hash, not an inferred approval from recomputing it. +The group requires separate current privacy, evaluation and tokenizer evidence; +an earlier exact-region approval does not qualify it or guarantee a region. + +GPT-5.4 checks use the static `gpt-tokenizer@4.1.2` `model/gpt-5.4` entry with +request-derived merge caching disabled and special-looking text counted as +ordinary input. Qualification model/version, framing and evidence dates remain +operator evidence, checked by the SDK. Unknown models refuse before key access +or a provider request. The legacy GPT-4.1-mini checker selection, generation, +customer-answer and release-follow-up generator allowlists remain unchanged. +All host checker consumers receive the shared checker tuple/counter; the +published SDK separately refuses provider groups for release-follow-up checks. +That purpose remains held for a group route rather than inheriting a learning +or engineering approval. No +route, price, approval, credential or feature flag is installed or enabled by +this code change. Customer AI remains off. Legacy endpoint routing sends `provider.only=[endpointTag]`, `allow_fallbacks:false`, `zdr:true`, `data_collection:'deny'` and diff --git a/worker/src/support-independent-checks-token-counter.ts b/worker/src/support-independent-checks-token-counter.ts new file mode 100644 index 0000000..fee0972 --- /dev/null +++ b/worker/src/support-independent-checks-token-counter.ts @@ -0,0 +1,35 @@ +import { countTokens, setMergeCacheSize } from "gpt-tokenizer/model/gpt-5.4"; +import { + countTokens as countMiniTokens, + setMergeCacheSize as setMiniMergeCacheSize, +} from "gpt-tokenizer/model/gpt-4.1-mini"; +import type { IndependentCheckCounter } from "./support-independent-checks-model"; + +// Keep encoding tables, never request-derived merge results across invocations. +setMergeCacheSize(0); +setMiniMergeCacheSize(0); +const ordinaryText = { disallowedSpecial: new Set() }; +countTokens("", ordinaryText); + +/** Select an implemented checker tokenizer, never infer route approval or dates. + * Generator and customer-answer counters retain their existing selection. */ +export function createSupportIndependentCheckTokenCounter( + qualification: IndependentCheckCounter["qualification"], +): IndependentCheckCounter { + const count = + qualification.model === "openai/gpt-4.1-mini" + ? countMiniTokens + : qualification.model === "openai/gpt-5.4" + ? countTokens + : undefined; + if (!count) + throw new TypeError("Unsupported checker tokenizer implementation"); + return Object.freeze({ + qualification: Object.freeze({ ...qualification }), + count(text: string) { + if (typeof text !== "string" || text.length > 262_144) + throw new TypeError("Invalid checker token input."); + return count(text, ordinaryText); + }, + }); +} diff --git a/worker/src/support-paid-bootstrap.ts b/worker/src/support-paid-bootstrap.ts index 2d4f459..5d37242 100644 --- a/worker/src/support-paid-bootstrap.ts +++ b/worker/src/support-paid-bootstrap.ts @@ -12,6 +12,7 @@ import { createSupportBackgroundServiceAccess } from './support-background-servi import { createSupportLearningModelPorts } from './support-learning-model'; import { createSupportEngineeringModelPorts } from './support-engineering-model'; import { createSupportAssistantTokenCounter } from './support-assistant-token-counter'; +import { createSupportIndependentCheckTokenCounter } from './support-independent-checks-token-counter'; import { SUPPORT_ASSISTANT_CREDENTIAL_REF } from './support-assistant-production'; import { canonical } from './support-openrouter-model'; import { knowledgeDigest } from './knowledge-evidence'; @@ -77,6 +78,20 @@ const allowed = Object.freeze([ outputTokenParameter: 'max_tokens' as const, }, ]); +// Static capability only: route and current Admin approval must independently +// opt in to the group and bind its finite price/privacy/qualification evidence. +// All generation and customer answers keep their existing lists. The SDK also +// retains its separate release-follow-up checker purpose/approval restrictions. +const checkerAllowed = Object.freeze([ + ...allowed, + { + model: 'openai/gpt-5.4', + provider: 'Azure', + endpointTag: 'azure', + outputTokenParameter: 'max_completion_tokens' as const, + providerSelectionScope: 'provider_group' as const, + }, +]); function live(value: { verifiedAt?: string; validUntil: string }, clock: Clock) { const now = Date.parse(clock.now()); return ( @@ -261,7 +276,7 @@ export async function createSupportPaidBootstrap( try { const version = profile.revision + ':' + (await knowledgeDigest(profile)); if (!current()) return undefined; - const checkCounter = counter(profile.checks.qualification); + const checkCounter = createSupportIndependentCheckTokenCounter(profile.checks.qualification); const readApiKey = (reference: string) => current() && reference === SUPPORT_ASSISTANT_CREDENTIAL_REF ? currentEnv().SUPPORT_ASSISTANT_OPENROUTER_API_KEY @@ -270,7 +285,7 @@ export async function createSupportPaidBootstrap( clock, enabled: current, readRoute: () => (current() ? profile.checks.route : undefined), - allowlist: allowed, + allowlist: checkerAllowed, counter: checkCounter, }); const reviewPolicy: LearningCheckPolicyPort = { @@ -366,7 +381,7 @@ export async function createSupportPaidBootstrap( enabled: paid, authority: checkerAuthority.learning.serviceAccess, readRoute: () => (current() ? profile.checks.route : undefined), - allowlist: allowed, + allowlist: checkerAllowed, counter: checkCounter, readApiKey, fetch: options.fetch, diff --git a/worker/src/support-paid-checker-group.test.ts b/worker/src/support-paid-checker-group.test.ts new file mode 100644 index 0000000..a0f3a2c --- /dev/null +++ b/worker/src/support-paid-checker-group.test.ts @@ -0,0 +1,493 @@ +import { createHash } from "node:crypto"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { createSupportPaidBootstrap } from "./support-paid-bootstrap"; +import { + paidBootstrapFixture, + PAID_END, +} from "./support-paid-bootstrap-fixtures"; +import { + createSupportIndependentCheckModel, + independentCheckRoutePolicyHash, + type IndependentCheckContext, +} from "./support-independent-checks-model"; +import { createSupportIndependentCheckTokenCounter } from "./support-independent-checks-token-counter"; + +const { gpt54Count } = vi.hoisted(() => ({ gpt54Count: vi.fn() })); +vi.mock("gpt-tokenizer/model/gpt-5.4", async (importOriginal) => { + const actual = + await importOriginal(); + gpt54Count.mockImplementation(actual.countTokens); + return { ...actual, countTokens: gpt54Count }; +}); +beforeEach(() => { + gpt54Count.mockClear(); +}); +const signal = () => new AbortController().signal; +const verdict = { + privacy: "passed", + factual: "passed", + security: "clear", + applicability: "passed", + duplication: "passed", + publicReproduction: "not_applicable", + findings: [], +}; +// Every model version, price, approval and evidence reference is fictional. +async function groupFixture() { + const f = await paidBootstrapFixture(); + const r = f.profile.checks.route; + Object.assign(r.configuration, { + model: "openai/gpt-5.4", + modelVersion: "fictional-gpt54", + }); + Object.assign(r, { + endpointTag: "azure", + outputTokenParameter: "max_completion_tokens", + providerSelectionScope: "provider_group", + providerMaxPrice: { prompt: 0.01, completion: 0.01, request: 0 }, + }); + Object.assign(r.approval, { providerSelectionScope: "provider_group" }); + Object.assign(f.profile.checks.qualification, { + model: "openai/gpt-5.4", + modelVersion: "fictional-gpt54", + }); + Object.assign(f.profile.checks.usagePolicy, { + modelVersion: "fictional-gpt54", + }); + const { approval: _approval, ...unsigned } = r; + r.approval.requestPolicySha256 = + await independentCheckRoutePolicyHash(unsigned); + return f; +} +type Fixture = Awaited>; +function save(f: Fixture) { + Reflect.set( + f.env, + "SUPPORT_PAID_CONFIGURATION_JSON", + JSON.stringify(f.profile), + ); +} +function input(f: Fixture) { + return { + trustedInstructions: + f.profile.checks.route.configuration.trustedInstructions, + kind: "learning" as const, + facts: { messages: ["A fictional workspace export completes."] }, + candidate: { solution: "Inspect the exported file." }, + outbound: { text: "Inspect the exported file." }, + }; +} +function context(f: Fixture): IndependentCheckContext { + const r = f.profile.checks.route, + c = r.configuration; + return { + purpose: "support_independent_check", + configurationVersion: c.version, + promptVersion: c.promptVersion, + modelVersion: c.modelVersion, + usageScopeRef: r.usageScopeRef, + operationId: "fictional-check-operation", + attemptId: "fictional-check-attempt", + inputFingerprint: "a".repeat(64), + usageReservationId: "fictional-check-reservation", + deadline: "2026-11-10T12:00:02.000Z", + signal: signal(), + budgets: c.budgets, + }; +} +function fetcher(f: Fixture) { + const c = f.profile.checks.route.configuration; + return vi.fn( + async (_url, _init) => + new Response( + JSON.stringify({ + id: "fictional-check-response", + object: "chat.completion", + created: 1, + provider: c.provider, + model: c.model, + choices: [ + { + index: 0, + finish_reason: "stop", + message: { role: "assistant", content: JSON.stringify(verdict) }, + }, + ], + usage: { + prompt_tokens: 200, + completion_tokens: 100, + total_tokens: 300, + cost: 0.0001, + currency: "USD", + is_byok: false, + prompt_tokens_details: { + cached_tokens: 0, + audio_tokens: 0, + video_tokens: 0, + }, + completion_tokens_details: { + reasoning_tokens: 0, + image_tokens: 0, + audio_tokens: 0, + }, + }, + }), + { headers: { "content-type": "application/json" } }, + ), + ); +} + +describe("normal paid bootstrap checker-only GPT-5.4 capability", () => { + it("preserves the legacy route hash, full wire and generation selection", async () => { + const f = await paidBootstrapFixture(), + fetch = fetcher(f); + const b = (await createSupportPaidBootstrap(f.env, { + clock: f.clock, + fetch, + }))!; + const options = b.learning.independentChecks!; + const model = createSupportIndependentCheckModel({ + ...options, + clock: f.clock, + }); + expect(await model.resolve()).not.toBeNull(); + await model.generate( + input(f), + context(f), + f.profile.checks.route.configuration, + ); + // Frozen from the public 0.2.12 SDK and unchanged fictional legacy fixture, + // independently of the new bootstrap capability/counter selection. + expect(f.profile.checks.route.approval.requestPolicySha256).toBe( + "36168760483e1308ab58b3a2277aa0b737ea05d9730a725e310d18e914ea989b", + ); + const body = String(fetch.mock.calls[0]![1]!.body); + expect(createHash("sha256").update(body).digest("hex")).toBe( + "423afcea198ebe2b493e5920c9a0a2747020485cc0179c1e154bf439deb8b754", + ); + expect(JSON.parse(body).provider).not.toHaveProperty("max_price"); + expect(model.currentRoute()).not.toHaveProperty("providerSelectionScope"); + expect(gpt54Count).not.toHaveBeenCalled(); + expect(b.learning.production!.configuration!.model!.allowlist).toEqual([ + { + model: "openai/gpt-4.1-mini", + provider: "Azure", + endpointTag: "azure/swedencentral", + outputTokenParameter: "max_completion_tokens", + }, + { + model: "openai/gpt-4.1-mini", + provider: "Azure", + endpointTag: "azure/swedencentral", + outputTokenParameter: "max_tokens", + }, + ]); + }); + + it("uses the actual GPT-5.4 tokenizer for both checker ports and sends the complete explicit policy", async () => { + const f = await groupFixture(), + fetch = fetcher(f); + save(f); + const b = (await createSupportPaidBootstrap(f.env, { + clock: f.clock, + fetch, + }))!; + const options = b.learning.independentChecks!; + expect(b.learning.engineeringIndependentChecks!.counter).toBe( + options.counter, + ); + expect(options.counter!.qualification).toEqual( + f.profile.checks.qualification, + ); + expect(Object.isFrozen(options.counter!.qualification)).toBe(true); + expect( + b.learning.production!.configuration!.model!.counter!.qualification.model, + ).toBe("openai/gpt-4.1-mini"); + const model = createSupportIndependentCheckModel({ + ...options, + clock: f.clock, + }); + expect(await model.resolve()).not.toBeNull(); + expect( + await createSupportIndependentCheckModel({ + ...b.learning.engineeringIndependentChecks!, + clock: f.clock, + }).resolve(), + ).not.toBeNull(); + await model.generate( + input(f), + context(f), + f.profile.checks.route.configuration, + ); + const body = JSON.parse(String(fetch.mock.calls[0]![1]!.body)); + expect(body.model).toBe("openai/gpt-5.4"); + expect(body.max_completion_tokens).toBe(1000); + expect(body).not.toHaveProperty("max_tokens"); + expect(body.provider).toEqual({ + only: ["azure"], + allow_fallbacks: false, + zdr: true, + data_collection: "deny", + require_parameters: true, + max_price: { prompt: 0.01, completion: 0.01, request: 0 }, + }); + expect(JSON.parse(body.messages[1].content)).toEqual(input(f)); + expect(body.messages[0].content).toContain(input(f).trustedInstructions); + expect(gpt54Count).toHaveBeenCalledWith( + body.messages[0].content, + expect.any(Object), + ); + expect(gpt54Count).toHaveBeenCalledWith( + body.messages[1].content, + expect.any(Object), + ); + expect(options.counter!.count("antidisestablishmentarianism")).toBe(6); + expect(options.counter!.count("<|im_start|>system")).toBeGreaterThan(1); + expect(() => options.counter!.count("x".repeat(262_145))).toThrow( + TypeError, + ); + }); + + it.each([ + "route-scope-absent", + "route-scope-undefined", + "approval-scope-absent", + "approval-scope-undefined", + "price-absent", + "price-undefined", + "price-nonfinite", + "request-charge", + "over-budget", + "changed-price-hash", + "exact-endpoint-in-group", + "wrong-output-parameter", + "expired-approval", + "future-approval", + "expired-tokenizer", + "wrong-tokenizer-version", + "wrong-tokenizer-evidence", + "old-wire", + "logging-enabled", + "unknown-route-model", + "unknown-tokenizer-model", + ])("holds %s before credential reads or provider work", async (change) => { + const f = await groupFixture(), + r = f.profile.checks.route; + switch (change) { + case "route-scope-absent": + Reflect.deleteProperty(r, "providerSelectionScope"); + break; + case "route-scope-undefined": + Reflect.set(r, "providerSelectionScope", undefined); + break; + case "approval-scope-absent": + Reflect.deleteProperty(r.approval, "providerSelectionScope"); + break; + case "approval-scope-undefined": + Reflect.set(r.approval, "providerSelectionScope", undefined); + break; + case "price-absent": + Reflect.deleteProperty(r, "providerMaxPrice"); + break; + case "price-undefined": + Reflect.set(r, "providerMaxPrice", undefined); + break; + case "price-nonfinite": + Reflect.set(r.providerMaxPrice!, "prompt", Infinity); + break; + case "request-charge": + Reflect.set(r.providerMaxPrice!, "request", 1); + break; + case "over-budget": + r.providerMaxPrice!.prompt = 1; + break; + case "changed-price-hash": + r.providerMaxPrice!.prompt = 0.02; + break; + case "exact-endpoint-in-group": + r.endpointTag = "azure/swedencentral"; + break; + case "wrong-output-parameter": + r.outputTokenParameter = "max_tokens"; + break; + case "expired-approval": + r.approval.validUntil = f.clock.now(); + break; + case "future-approval": + r.approval.verifiedAt = PAID_END; + break; + case "expired-tokenizer": + f.profile.checks.qualification.validUntil = f.clock.now(); + break; + case "wrong-tokenizer-version": + f.profile.checks.qualification.modelVersion = "another-version"; + break; + case "wrong-tokenizer-evidence": + f.profile.checks.qualification.evidenceRef = "another-evaluation"; + break; + case "old-wire": + Reflect.set( + r.approval, + "wireVersion", + "openrouter-support-independent-check-v1", + ); + break; + case "logging-enabled": + Reflect.set(r.approval, "inputOutputLogging", true); + break; + case "unknown-route-model": + r.configuration.model = "unknown/model"; + break; + case "unknown-tokenizer-model": + f.profile.checks.qualification.model = "unknown/model"; + break; + } + save(f); + // JSON has no undefined/non-finite representation: these become absent/null + // operator fields and must still hold at the normal root. + const secret = vi.fn(() => { + throw new Error("Must refuse before credentials"); + }); + Object.defineProperty( + f.env, + "SUPPORT_INDEPENDENT_CHECK_RECEIPT_KEY_BASE64", + { get: secret }, + ); + Object.defineProperty(f.env, "SUPPORT_ASSISTANT_OPENROUTER_API_KEY", { + get: secret, + }); + const fetch = fetcher(f); + const b = await createSupportPaidBootstrap(f.env, { + clock: f.clock, + fetch, + }); + expect(b?.learning.independentChecks).toBeUndefined(); + expect(b?.learning.production).toBeUndefined(); + expect(secret).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + }); + + it("requires the independent static allowlist opt-in and refuses an own undefined scope", async () => { + const f = await groupFixture(), + fetch = fetcher(f); + save(f); + const b = (await createSupportPaidBootstrap(f.env, { + clock: f.clock, + fetch, + }))!; + const original = b.learning.independentChecks!; + for (const ownUndefined of [false, true]) { + const allowlist = structuredClone(original.allowlist!); + for (const entry of allowlist) { + if (ownUndefined) + Reflect.set(entry, "providerSelectionScope", undefined); + else Reflect.deleteProperty(entry, "providerSelectionScope"); + } + const key = vi.fn(() => "FICTIONAL_KEY"); + const model = createSupportIndependentCheckModel({ + clock: f.clock, + ...original, + allowlist, + readApiKey: key, + }); + expect(await model.resolve()).toBeNull(); + await expect( + model.generate( + input(f), + context(f), + f.profile.checks.route.configuration, + ), + ).rejects.toThrow(); + expect(key).not.toHaveBeenCalled(); + } + expect(fetch).not.toHaveBeenCalled(); + }); + + it.each(["full-system-bytes", "full-system-tokens", "lower-live-price-cap"])( + "admits %s before credentials and the physical-call fence", + async (bound) => { + const f = await groupFixture(), + fetch = fetcher(f); + save(f); + const b = (await createSupportPaidBootstrap(f.env, { + clock: f.clock, + fetch, + }))!; + const key = vi.fn(() => "FICTIONAL_KEY"), + beforePhysicalCall = vi.fn(); + const options = b.learning.independentChecks!; + const model = createSupportIndependentCheckModel({ + ...options, + clock: f.clock, + readApiKey: key, + }); + expect(await model.resolve()).not.toBeNull(); + const ctx = context(f), + payload = JSON.stringify(input(f)); + const budgets = { + ...ctx.budgets, + ...(bound === "full-system-bytes" + ? { maxInputBytes: new TextEncoder().encode(payload).length + 1 } + : bound === "full-system-tokens" + ? { + maxInputTokens: + options.counter!.count(payload) + + f.profile.checks.qualification.framingTokens, + } + : { maxCostMicros: 329 }), + }; + await expect( + model.generate( + input(f), + { ...ctx, budgets, beforePhysicalCall }, + f.profile.checks.route.configuration, + ), + ).rejects.toThrow(); + expect(key).not.toHaveBeenCalled(); + expect(beforePhysicalCall).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + }, + ); + + it("revokes an approved group while credentials are read without a physical call", async () => { + const f = await groupFixture(), + fetch = fetcher(f); + save(f); + let now = f.clock.now(); + f.clock.now = () => now; + const b = (await createSupportPaidBootstrap(f.env, { + clock: f.clock, + fetch, + }))!; + const key = vi.fn(() => { + now = PAID_END; + return "FICTIONAL_KEY"; + }); + const model = createSupportIndependentCheckModel({ + clock: f.clock, + ...b.learning.independentChecks!, + readApiKey: key, + }); + expect(await model.resolve()).not.toBeNull(); + await expect( + model.generate( + input(f), + context(f), + f.profile.checks.route.configuration, + ), + ).rejects.toThrow(); + expect(key).toHaveBeenCalledOnce(); + expect(fetch).not.toHaveBeenCalled(); + }); + + it("cannot select an unknown tokenizer directly", async () => { + const f = await groupFixture(); + expect(() => + createSupportIndependentCheckTokenCounter({ + ...f.profile.checks.qualification, + wireVersion: "openrouter-support-independent-check-v2", + model: "unknown/model", + }), + ).toThrow(TypeError); + }); +}); From 9d727bf28d1bcf8430f45bc897063505135f7824 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sat, 14 Nov 2026 02:55:25 -0500 Subject: [PATCH 2/3] Defer optional checker loading and isolate policy regressions --- docs/SUPPORT_CHECKER_UPGRADE.md | 5 +- ...upport-independent-checks-token-counter.ts | 20 +- worker/src/support-paid-bootstrap.ts | 12 +- worker/src/support-paid-checker-group.test.ts | 172 +++++++++++++++--- worker/src/support-paid-checker-lazy.test.ts | 82 +++++++++ 5 files changed, 248 insertions(+), 43 deletions(-) create mode 100644 worker/src/support-paid-checker-lazy.test.ts diff --git a/docs/SUPPORT_CHECKER_UPGRADE.md b/docs/SUPPORT_CHECKER_UPGRADE.md index 228ba6f..232e93b 100644 --- a/docs/SUPPORT_CHECKER_UPGRADE.md +++ b/docs/SUPPORT_CHECKER_UPGRADE.md @@ -29,7 +29,10 @@ an earlier exact-region approval does not qualify it or guarantee a region. GPT-5.4 checks use the static `gpt-tokenizer@4.1.2` `model/gpt-5.4` entry with request-derived merge caching disabled and special-looking text counted as -ordinary input. Qualification model/version, framing and evidence dates remain +ordinary input. Its implementation is loaded only when the profile selects +GPT-5.4; absent, malformed, unknown-model and legacy-mini selections do not +initialize it. This does not establish bundle size or deployed CPU acceptance. +Qualification model/version, framing and evidence dates remain operator evidence, checked by the SDK. Unknown models refuse before key access or a provider request. The legacy GPT-4.1-mini checker selection, generation, customer-answer and release-follow-up generator allowlists remain unchanged. diff --git a/worker/src/support-independent-checks-token-counter.ts b/worker/src/support-independent-checks-token-counter.ts index fee0972..58bfbbb 100644 --- a/worker/src/support-independent-checks-token-counter.ts +++ b/worker/src/support-independent-checks-token-counter.ts @@ -1,35 +1,23 @@ import { countTokens, setMergeCacheSize } from "gpt-tokenizer/model/gpt-5.4"; -import { - countTokens as countMiniTokens, - setMergeCacheSize as setMiniMergeCacheSize, -} from "gpt-tokenizer/model/gpt-4.1-mini"; import type { IndependentCheckCounter } from "./support-independent-checks-model"; // Keep encoding tables, never request-derived merge results across invocations. setMergeCacheSize(0); -setMiniMergeCacheSize(0); const ordinaryText = { disallowedSpecial: new Set() }; -countTokens("", ordinaryText); -/** Select an implemented checker tokenizer, never infer route approval or dates. - * Generator and customer-answer counters retain their existing selection. */ +/** Optional GPT-5.4 implementation, imported only for that checker selection. + * Qualification dates/versions stay operator evidence; this grants no approval. */ export function createSupportIndependentCheckTokenCounter( qualification: IndependentCheckCounter["qualification"], ): IndependentCheckCounter { - const count = - qualification.model === "openai/gpt-4.1-mini" - ? countMiniTokens - : qualification.model === "openai/gpt-5.4" - ? countTokens - : undefined; - if (!count) + if (qualification.model !== "openai/gpt-5.4") throw new TypeError("Unsupported checker tokenizer implementation"); return Object.freeze({ qualification: Object.freeze({ ...qualification }), count(text: string) { if (typeof text !== "string" || text.length > 262_144) throw new TypeError("Invalid checker token input."); - return count(text, ordinaryText); + return countTokens(text, ordinaryText); }, }); } diff --git a/worker/src/support-paid-bootstrap.ts b/worker/src/support-paid-bootstrap.ts index 5d37242..d18a440 100644 --- a/worker/src/support-paid-bootstrap.ts +++ b/worker/src/support-paid-bootstrap.ts @@ -12,7 +12,6 @@ import { createSupportBackgroundServiceAccess } from './support-background-servi import { createSupportLearningModelPorts } from './support-learning-model'; import { createSupportEngineeringModelPorts } from './support-engineering-model'; import { createSupportAssistantTokenCounter } from './support-assistant-token-counter'; -import { createSupportIndependentCheckTokenCounter } from './support-independent-checks-token-counter'; import { SUPPORT_ASSISTANT_CREDENTIAL_REF } from './support-assistant-production'; import { canonical } from './support-openrouter-model'; import { knowledgeDigest } from './knowledge-evidence'; @@ -168,6 +167,14 @@ function counter(qualification: Q) { count: (text: string) => implementation.count(text), }); } +async function checkerCounter(qualification: SupportPaidProfile['checks']['qualification']) { + if (qualification.model === 'openai/gpt-4.1-mini') return counter(qualification); + if (qualification.model !== 'openai/gpt-5.4') + throw new TypeError('Unsupported checker tokenizer implementation'); + const { createSupportIndependentCheckTokenCounter } = + await import('./support-independent-checks-token-counter'); + return createSupportIndependentCheckTokenCounter(qualification); +} function targets( profile: NonNullable, product: { productId: string; version: string; buildId: string }, @@ -276,7 +283,8 @@ export async function createSupportPaidBootstrap( try { const version = profile.revision + ':' + (await knowledgeDigest(profile)); if (!current()) return undefined; - const checkCounter = createSupportIndependentCheckTokenCounter(profile.checks.qualification); + const checkCounter = await checkerCounter(profile.checks.qualification); + if (!current()) return undefined; const readApiKey = (reference: string) => current() && reference === SUPPORT_ASSISTANT_CREDENTIAL_REF ? currentEnv().SUPPORT_ASSISTANT_OPENROUTER_API_KEY diff --git a/worker/src/support-paid-checker-group.test.ts b/worker/src/support-paid-checker-group.test.ts index a0f3a2c..c384de5 100644 --- a/worker/src/support-paid-checker-group.test.ts +++ b/worker/src/support-paid-checker-group.test.ts @@ -11,6 +11,9 @@ import { type IndependentCheckContext, } from "./support-independent-checks-model"; import { createSupportIndependentCheckTokenCounter } from "./support-independent-checks-token-counter"; +import { createMemoryStore } from "@pegma/storage-core"; +import { createSupportReleaseFollowupChecks } from "@pegma/support-desk-ai/openrouter"; +import { supportFollowupPaidFixture } from "./support-release-followup-paid-fixtures"; const { gpt54Count } = vi.hoisted(() => ({ gpt54Count: vi.fn() })); vi.mock("gpt-tokenizer/model/gpt-5.4", async (importOriginal) => { @@ -35,7 +38,13 @@ const verdict = { // Every model version, price, approval and evidence reference is fictional. async function groupFixture() { const f = await paidBootstrapFixture(); - const r = f.profile.checks.route; + await selectGroupChecks(f.profile.checks); + return f; +} +async function selectGroupChecks( + checks: Awaited>["profile"]["checks"], +) { + const r = checks.route; Object.assign(r.configuration, { model: "openai/gpt-5.4", modelVersion: "fictional-gpt54", @@ -47,17 +56,16 @@ async function groupFixture() { providerMaxPrice: { prompt: 0.01, completion: 0.01, request: 0 }, }); Object.assign(r.approval, { providerSelectionScope: "provider_group" }); - Object.assign(f.profile.checks.qualification, { + Object.assign(checks.qualification, { model: "openai/gpt-5.4", modelVersion: "fictional-gpt54", }); - Object.assign(f.profile.checks.usagePolicy, { + Object.assign(checks.usagePolicy, { modelVersion: "fictional-gpt54", }); const { approval: _approval, ...unsigned } = r; r.approval.requestPolicySha256 = await independentCheckRoutePolicyHash(unsigned); - return f; } type Fixture = Awaited>; function save(f: Fixture) { @@ -220,6 +228,21 @@ describe("normal paid bootstrap checker-only GPT-5.4 capability", () => { f.profile.checks.route.configuration, ); const body = JSON.parse(String(fetch.mock.calls[0]![1]!.body)); + expect(f.profile.checks.route.approval.requestPolicySha256).toBe( + "aeb815a1974805e372cda8947d5c4f5bdb7a9c8e94ac69688ba5b9f0966e2302", + ); + expect( + createHash("sha256") + .update(String(fetch.mock.calls[0]![1]!.body)) + .digest("hex"), + ).toBe("be81b80386f0569314f8a5b30fd5be11fdb6e05634848d7d8365229ad5e4fd45"); + const { approval: _approval, ...unsigned } = f.profile.checks.route; + expect( + await independentCheckRoutePolicyHash({ + ...unsigned, + providerMaxPrice: { ...unsigned.providerMaxPrice!, prompt: 0.02 }, + }), + ).not.toBe(f.profile.checks.route.approval.requestPolicySha256); expect(body.model).toBe("openai/gpt-5.4"); expect(body.max_completion_tokens).toBe(1000); expect(body).not.toHaveProperty("max_tokens"); @@ -250,12 +273,10 @@ describe("normal paid bootstrap checker-only GPT-5.4 capability", () => { it.each([ "route-scope-absent", - "route-scope-undefined", + "route-scope-other", "approval-scope-absent", - "approval-scope-undefined", + "approval-scope-other", "price-absent", - "price-undefined", - "price-nonfinite", "request-charge", "over-budget", "changed-price-hash", @@ -268,7 +289,6 @@ describe("normal paid bootstrap checker-only GPT-5.4 capability", () => { "wrong-tokenizer-evidence", "old-wire", "logging-enabled", - "unknown-route-model", "unknown-tokenizer-model", ])("holds %s before credential reads or provider work", async (change) => { const f = await groupFixture(), @@ -277,24 +297,18 @@ describe("normal paid bootstrap checker-only GPT-5.4 capability", () => { case "route-scope-absent": Reflect.deleteProperty(r, "providerSelectionScope"); break; - case "route-scope-undefined": - Reflect.set(r, "providerSelectionScope", undefined); + case "route-scope-other": + Reflect.set(r, "providerSelectionScope", "exact_endpoint"); break; case "approval-scope-absent": Reflect.deleteProperty(r.approval, "providerSelectionScope"); break; - case "approval-scope-undefined": - Reflect.set(r.approval, "providerSelectionScope", undefined); + case "approval-scope-other": + Reflect.set(r.approval, "providerSelectionScope", "exact_endpoint"); break; case "price-absent": Reflect.deleteProperty(r, "providerMaxPrice"); break; - case "price-undefined": - Reflect.set(r, "providerMaxPrice", undefined); - break; - case "price-nonfinite": - Reflect.set(r.providerMaxPrice!, "prompt", Infinity); - break; case "request-charge": Reflect.set(r.providerMaxPrice!, "request", 1); break; @@ -335,16 +349,21 @@ describe("normal paid bootstrap checker-only GPT-5.4 capability", () => { case "logging-enabled": Reflect.set(r.approval, "inputOutputLogging", true); break; - case "unknown-route-model": - r.configuration.model = "unknown/model"; - break; case "unknown-tokenizer-model": f.profile.checks.qualification.model = "unknown/model"; break; } + const normalized = JSON.parse(JSON.stringify(r)); + const { approval: _approval, ...unsigned } = normalized; + const renewedHash = await independentCheckRoutePolicyHash(unsigned); + if (change === "changed-price-hash") { + expect(renewedHash).not.toBe(r.approval.requestPolicySha256); + // The changed price still fits the configured cap: only approval is stale. + expect(Math.ceil(32_000 * 0.02 + 1_000 * 0.01)).toBeLessThan(1_000); + } else { + r.approval.requestPolicySha256 = renewedHash; + } save(f); - // JSON has no undefined/non-finite representation: these become absent/null - // operator fields and must still hold at the normal root. const secret = vi.fn(() => { throw new Error("Must refuse before credentials"); }); @@ -490,4 +509,109 @@ describe("normal paid bootstrap checker-only GPT-5.4 capability", () => { }), ).toThrow(TypeError); }); + + it.each(["route-scope", "approval-scope", "price", "nonfinite-price"])( + "refuses actual non-serialized %s authoring fields before credentials", + async (field) => { + const f = await groupFixture(), + fetch = fetcher(f); + save(f); + const b = (await createSupportPaidBootstrap(f.env, { + clock: f.clock, + fetch, + }))!; + const route = structuredClone(b.profile.checks.route); + if (field === "approval-scope") { + Reflect.set(route.approval, "providerSelectionScope", undefined); + expect(Object.hasOwn(route.approval, "providerSelectionScope")).toBe( + true, + ); + } else if (field === "nonfinite-price") { + route.providerMaxPrice!.prompt = Infinity; + expect(route.providerMaxPrice!.prompt).toBe(Infinity); + } else { + const key = + field === "route-scope" + ? "providerSelectionScope" + : "providerMaxPrice"; + Reflect.set(route, key, undefined); + expect(Object.hasOwn(route, key)).toBe(true); + } + // Deliberately no JSON round trip: SDK sees own undefined/Infinity values. + const key = vi.fn(() => "FICTIONAL_KEY"); + const model = createSupportIndependentCheckModel({ + ...b.learning.independentChecks!, + clock: f.clock, + readRoute: () => route, + readApiKey: key, + }); + expect(await model.resolve()).toBeNull(); + await expect( + model.generate( + input(f), + context(f), + f.profile.checks.route.configuration, + ), + ).rejects.toThrow(); + expect(key).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + }, + ); + + it("retains the actual SDK follow-up purpose hold while its generator remains legacy", async () => { + // A ready legacy control rules out missing keys/purpose evidence as the + // reason that the otherwise qualified group counterpart is held. + for (const group of [false, true]) { + const f = await supportFollowupPaidFixture(); + if (group) await selectGroupChecks(f.profile.checks); + Reflect.set( + f.env, + "SUPPORT_PAID_CONFIGURATION_JSON", + JSON.stringify(f.profile), + ); + const providerKey = vi.fn(() => { + throw new Error("No provider credential for policy reads"); + }); + Object.defineProperty(f.env, "SUPPORT_ASSISTANT_OPENROUTER_API_KEY", { + get: providerKey, + }); + const fetch = vi.fn(async () => { + throw new Error("No provider call"); + }); + const b = (await createSupportPaidBootstrap(f.env, { + clock: f.clock, + fetch, + }))!; + const paid = b.releaseFollowup!.production!; + expect(paid.generator.counter!.qualification.model).toBe( + "openai/gpt-4.1-mini", + ); + expect(paid.checks.counter).toBe(b.learning.independentChecks!.counter); + expect(paid.checks.counter!.qualification.model).toBe( + group ? "openai/gpt-5.4" : "openai/gpt-4.1-mini", + ); + const application = vi.fn(() => { + throw new Error("Policy read must not inspect application records"); + }); + const evidence = vi.fn(async () => { + throw new Error("Policy read must not inspect release evidence"); + }); + const checks = createSupportReleaseFollowupChecks( + { + ...paid.checks, + store: createMemoryStore(), + application, + releaseEvidence: { verifyInput: evidence, confirm: evidence }, + }, + "pegma.dev", + ); + expect((await checks.resolvePolicy(undefined, signal())).outcome).toBe( + group ? "unavailable" : "ready", + ); + expect(application).not.toHaveBeenCalled(); + expect(evidence).not.toHaveBeenCalled(); + expect(providerKey).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + } + }); }); diff --git a/worker/src/support-paid-checker-lazy.test.ts b/worker/src/support-paid-checker-lazy.test.ts new file mode 100644 index 0000000..af920cb --- /dev/null +++ b/worker/src/support-paid-checker-lazy.test.ts @@ -0,0 +1,82 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { createSupportPaidBootstrap } from "./support-paid-bootstrap"; +import { paidBootstrapFixture } from "./support-paid-bootstrap-fixtures"; + +const { loadGpt54 } = vi.hoisted(() => ({ loadGpt54: vi.fn() })); +vi.mock("./support-independent-checks-token-counter", () => { + loadGpt54(); + throw new Error("Selected optional GPT-5.4 module reached"); +}); +beforeEach(() => { + loadGpt54.mockClear(); +}); + +describe("optional checker tokenizer module admission", () => { + it("does not load GPT-5.4 for absent or malformed profiles", async () => { + expect(await createSupportPaidBootstrap({})).toBeUndefined(); + expect( + await createSupportPaidBootstrap({ + SUPPORT_PAID_CONFIGURATION_JSON: "{}", + }), + ).toBeUndefined(); + expect(loadGpt54).not.toHaveBeenCalled(); + }); + it("keeps the actual legacy mini profile ready without loading GPT-5.4", async () => { + const f = await paidBootstrapFixture(); + const b = await createSupportPaidBootstrap(f.env, { clock: f.clock }); + expect(b?.learning.independentChecks?.counter?.qualification.model).toBe( + "openai/gpt-4.1-mini", + ); + expect(loadGpt54).not.toHaveBeenCalled(); + }); + it("refuses unknown models before loading GPT-5.4 or reading credentials", async () => { + const f = await paidBootstrapFixture(); + f.profile.checks.qualification.model = "unknown/model"; + Reflect.set( + f.env, + "SUPPORT_PAID_CONFIGURATION_JSON", + JSON.stringify(f.profile), + ); + const key = vi.fn(() => { + throw new Error("Must not read credentials"); + }); + Object.defineProperty( + f.env, + "SUPPORT_INDEPENDENT_CHECK_RECEIPT_KEY_BASE64", + { get: key }, + ); + Object.defineProperty(f.env, "SUPPORT_ASSISTANT_OPENROUTER_API_KEY", { + get: key, + }); + expect( + await createSupportPaidBootstrap(f.env, { clock: f.clock }), + ).toBeUndefined(); + expect(loadGpt54).not.toHaveBeenCalled(); + expect(key).not.toHaveBeenCalled(); + }); + it("loads the optional module only after GPT-5.4 is selected and contains load failure", async () => { + const f = await paidBootstrapFixture(); + f.profile.checks.qualification.model = "openai/gpt-5.4"; + Reflect.set( + f.env, + "SUPPORT_PAID_CONFIGURATION_JSON", + JSON.stringify(f.profile), + ); + const key = vi.fn(() => { + throw new Error("Load failure must not reach credentials"); + }); + Object.defineProperty( + f.env, + "SUPPORT_INDEPENDENT_CHECK_RECEIPT_KEY_BASE64", + { get: key }, + ); + Object.defineProperty(f.env, "SUPPORT_ASSISTANT_OPENROUTER_API_KEY", { + get: key, + }); + expect( + await createSupportPaidBootstrap(f.env, { clock: f.clock }), + ).toBeUndefined(); + expect(loadGpt54).toHaveBeenCalledOnce(); + expect(key).not.toHaveBeenCalled(); + }); +}); From 2cd6c87dd72b73c4bb68a8edfda223346336cb16 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sat, 14 Nov 2026 03:05:48 -0500 Subject: [PATCH 3/3] Prove nonfinite checker refusal precedes policy hashing --- worker/src/support-paid-checker-group.test.ts | 48 +++++++++++++++---- 1 file changed, 38 insertions(+), 10 deletions(-) diff --git a/worker/src/support-paid-checker-group.test.ts b/worker/src/support-paid-checker-group.test.ts index c384de5..0670b19 100644 --- a/worker/src/support-paid-checker-group.test.ts +++ b/worker/src/support-paid-checker-group.test.ts @@ -545,16 +545,44 @@ describe("normal paid bootstrap checker-only GPT-5.4 capability", () => { readRoute: () => route, readApiKey: key, }); - expect(await model.resolve()).toBeNull(); - await expect( - model.generate( - input(f), - context(f), - f.profile.checks.route.configuration, - ), - ).rejects.toThrow(); - expect(key).not.toHaveBeenCalled(); - expect(fetch).not.toHaveBeenCalled(); + const digest = + field === "nonfinite-price" + ? vi.spyOn(crypto.subtle, "digest") + : undefined; + try { + if (digest) { + const valid = createSupportIndependentCheckModel({ + ...b.learning.independentChecks!, + clock: f.clock, + }); + expect(await valid.resolve()).not.toBeNull(); + expect(digest).toHaveBeenCalled(); + digest.mockClear(); + // The public canonicalizer cannot produce an approval for Infinity. + // Observe actual rejection before hashing, never forge such an approval. + const { approval: _approval, ...unsigned } = route; + expect(unsigned.host).toBe('pegma.dev'); + await expect( + independentCheckRoutePolicyHash({ ...unsigned, host: 'pegma.dev' }), + ).rejects.toThrow(TypeError); + expect(digest).not.toHaveBeenCalled(); + } + expect(await model.resolve()).toBeNull(); + await expect( + model.generate( + input(f), + context(f), + f.profile.checks.route.configuration, + ), + ).rejects.toThrow(); + // A stale-hash comparison cannot be the cause: no invalid-route digest + // was computed, while the same observer saw the valid control above. + if (digest) expect(digest).not.toHaveBeenCalled(); + expect(key).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + } finally { + digest?.mockRestore(); + } }, );