Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(codex): address validation regressions and runtime certification gaps

Alfredo Lopez58875a2cdfdd
diff --git a/codex-llm-proxy/src/toolNameMap.ts b/codex-llm-proxy/src/toolNameMap.ts
index 620f2f6c0..c602158c4 100644
--- a/codex-llm-proxy/src/toolNameMap.ts
+++ b/codex-llm-proxy/src/toolNameMap.ts
@@ -42,6 +42,9 @@ export class ToolNameMap {
fromWire(name: string): string | undefined {
const canonical = this.inbound.get(name)
if (canonical !== undefined) return canonical
+ // Some providers echo the registered canonical name despite receiving an
+ // alias. Accept only an exact known key; do not infer or normalize targets.
+ if (this.outbound.has(name)) return name
// Ordinary unknown names still reach the Host registry for rejection.
// Never infer a target from an unregistered alias or unsafe name.
if (wireNamePattern.test(name) && !name.startsWith('__codex_tool_')) return name
diff --git a/codex-llm-proxy/test/codexTransport.conformance.test.ts b/codex-llm-proxy/test/codexTransport.conformance.test.ts
index c16cc3ce7..1f7003b90 100644
--- a/codex-llm-proxy/test/codexTransport.conformance.test.ts
+++ b/codex-llm-proxy/test/codexTransport.conformance.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, it, vi } from 'vitest'
-import { hashCodexCompletionRequestV1 } from '@clerum/llm-provider-attempt-contract'
+import {
+ hashCodexCompletionRequestV1,
+ parseCodexCompletionRequestV1,
+} from '@clerum/llm-provider-attempt-contract'
import { CodexTransportError, streamCodexCompletion } from '../src/codexTransport.js'
import type { RedeemAttemptSuccess } from '../src/controlApiClient.js'
import { CODEX_COMPLETIONS_ORIGIN } from '../src/originPolicy.js'
@@ -673,81 +676,147 @@ describe('streamCodexCompletion', () => {
expect(body).not.toHaveProperty('temperature')
})
- it.each(['service.with.dots__read', `generated_server_${'x'.repeat(70)}__read`])(
- 'roundtrips the canonical tool name %s without changing authorization identity',
- async name => {
- const request = {
- ...REQUEST,
- tools: [{ name, description: 'Read one record', parameters: { type: 'object' } }],
- messages: [
- ...REQUEST.messages,
- {
- role: 'assistant' as const,
- content: '',
- toolCalls: [{ id: 'previous', name, arguments: {} }],
- },
- { role: 'tool' as const, content: 'previous result', toolCallId: 'previous', name },
- ],
- }
- const requestHash = hashCodexCompletionRequestV1(request)
- const original = structuredClone(request)
- const emitted: unknown[] = []
- const fetchFn = vi.fn(async (_url: unknown, init?: RequestInit) => {
- const body = JSON.parse(String(init?.body))
- const wireName = body.tools[0].name
- expect(wireName).toMatch(/^[A-Za-z0-9_-]{1,64}$/)
- expect(wireName).not.toBe(name)
- expect(
- body.input.find((item: { type?: string }) => item.type === 'function_call').name
- ).toBe(wireName)
- expect(
- body.input.find((item: { type?: string }) => item.type === 'function_call_output')
- ).toEqual({
- type: 'function_call_output',
- call_id: 'previous',
- output: 'previous result',
- })
- return sseResponse([
- `data: ${JSON.stringify({
- type: 'response.output_item.done',
- item: {
- type: 'function_call',
- id: 'item-new',
- call_id: 'new-call',
- name: wireName,
- arguments: '{}',
- },
- })}\n\n`,
- 'data: {"type":"response.completed","response":{"usage":{}}}\n\n',
- ])
+ it.each([
+ { name: 'service.with.dots__read', mode: 'alias' },
+ { name: `generated_server_${'x'.repeat(140)}__read`, mode: 'alias' },
+ { name: '工具@read record', mode: 'alias' },
+ { name: 'history@removed tool', mode: 'history-only' },
+ { name: 'service.with.dots__read', mode: 'canonical-echo' },
+ ])('roundtrips $name ($mode) without changing authorization identity', async ({ name, mode }) => {
+ const request = {
+ ...REQUEST,
+ ...(mode === 'history-only'
+ ? {}
+ : { tools: [{ name, description: 'Read one record', parameters: { type: 'object' } }] }),
+ messages: [
+ ...REQUEST.messages,
+ {
+ role: 'assistant' as const,
+ content: '',
+ toolCalls: [{ id: 'previous', name, arguments: {} }],
+ },
+ { role: 'tool' as const, content: 'previous result', toolCallId: 'previous', name },
+ ],
+ }
+ const requestHash = hashCodexCompletionRequestV1(request)
+ expect(parseCodexCompletionRequestV1(request).ok).toBe(true)
+ const original = structuredClone(request)
+ const emitted: unknown[] = []
+ const fetchFn = vi.fn(async (_url: unknown, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body))
+ const wireName = body.input.find(
+ (item: { type?: string }) => item.type === 'function_call'
+ ).name
+ if (mode === 'history-only') expect(body.tools).toBeUndefined()
+ else expect(body.tools[0].name).toBe(wireName)
+ expect(wireName).toMatch(/^[A-Za-z0-9_-]{1,64}$/)
+ expect(wireName).not.toBe(name)
+ expect(body.input.find((item: { type?: string }) => item.type === 'function_call').name).toBe(
+ wireName
+ )
+ expect(
+ body.input.find((item: { type?: string }) => item.type === 'function_call_output')
+ ).toEqual({
+ type: 'function_call_output',
+ call_id: 'previous',
+ output: 'previous result',
})
- const result = await streamCodexCompletion({
- executionTicket: 'ticket-name-map',
+ return sseResponse([
+ `data: ${JSON.stringify({
+ type: 'response.output_item.done',
+ item: {
+ type: 'function_call',
+ id: 'item-new',
+ call_id: 'new-call',
+ name: mode === 'canonical-echo' ? name : wireName,
+ arguments: '{}',
+ },
+ })}\n\n`,
+ 'data: {"type":"response.completed","response":{"usage":{}}}\n\n',
+ ])
+ })
+ const result = await streamCodexCompletion({
+ executionTicket: 'ticket-name-map',
+ requestHash,
+ request,
+ ticket: {
+ jti: 'name-map',
+ hostRef: 'research-host',
+ model: request.model,
+ requestHash,
+ providerAttemptId: 'att-name-map',
+ },
+ redeem: async () => redeemSuccess(),
+ finalize: async () => ({
+ providerAttemptId: 'att-name-map',
+ outcome: 'success' as const,
+ duplicate: false,
+ }),
+ fetchFn,
+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],
+ onFrame: frame => emitted.push(frame),
+ })
+ expect(result.outcome).toBe('success')
+ expect(emitted).toContainEqual({ type: 'tool_call', id: 'new-call', name, arguments: {} })
+ expect(request).toEqual(original)
+ expect(hashCodexCompletionRequestV1(request)).toBe(requestHash)
+ })
+
+ it('rejects an unregistered alias in a completed stream before emitting any calls', async () => {
+ const emitted: unknown[] = []
+ const finalize = vi.fn(async () => ({
+ providerAttemptId: 'att-unknown-alias',
+ outcome: 'error' as const,
+ duplicate: false,
+ }))
+ const request = {
+ ...REQUEST,
+ tools: [{ name: 'known.read', description: 'Read a record', parameters: { type: 'object' } }],
+ }
+ const requestHash = hashCodexCompletionRequestV1(request)
+ const fetchFn = vi.fn(async (_url: unknown, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body))
+ return sseResponse([
+ ...[body.tools[0].name, '__codex_tool_unregistered'].map(
+ (name, index) =>
+ `data: ${JSON.stringify({
+ type: 'response.output_item.done',
+ item: { type: 'function_call', id: `call-${index}`, name, arguments: '{}' },
+ })}\n\n`
+ ),
+ 'data: {"type":"response.completed"}\n\n',
+ ])
+ })
+ await expect(
+ streamCodexCompletion({
+ executionTicket: 'ticket-unknown-alias',
requestHash,
request,
ticket: {
- jti: 'name-map',
+ jti: 'unknown-alias',
hostRef: 'research-host',
model: request.model,
requestHash,
- providerAttemptId: 'att-name-map',
+ providerAttemptId: 'att-unknown-alias',
},
redeem: async () => redeemSuccess(),
- finalize: async () => ({
- providerAttemptId: 'att-name-map',
- outcome: 'success' as const,
- duplicate: false,
- }),
+ finalize,
fetchFn,
lookup: async () => [{ address: '1.2.3.4', family: 4 }],
onFrame: frame => emitted.push(frame),
})
- expect(result.outcome).toBe('success')
- expect(emitted).toContainEqual({ type: 'tool_call', id: 'new-call', name, arguments: {} })
- expect(request).toEqual(original)
- expect(hashCodexCompletionRequestV1(request)).toBe(requestHash)
- }
- )
+ ).rejects.toMatchObject({
+ code: 'provider_unavailable',
+ message: 'upstream returned an unknown tool name',
+ })
+ expect(fetchFn).toHaveBeenCalledOnce()
+ expect(emitted).toEqual([])
+ expect(finalize).toHaveBeenCalledWith(
+ expect.objectContaining({
+ receipt: expect.objectContaining({ outcome: 'error' }),
+ })
+ )
+ })
it('omits Notify-like generation fields on the Responses wire', async () => {
const fetchFn = vi.fn(async () =>
diff --git a/codex-llm-proxy/test/toolNameMap.test.ts b/codex-llm-proxy/test/toolNameMap.test.ts
index 114c5c2b0..8e9c1d714 100644
--- a/codex-llm-proxy/test/toolNameMap.test.ts
+++ b/codex-llm-proxy/test/toolNameMap.test.ts
@@ -1,5 +1,5 @@
-import { createHash } from 'node:crypto'
import { describe, expect, it, vi } from 'vitest'
+import { createHash } from 'node:crypto'
import { ToolNameMap } from '../src/toolNameMap.js'
vi.mock('node:crypto', async importOriginal => {
@@ -8,8 +8,16 @@ vi.mock('node:crypto', async importOriginal => {
})
describe('ToolNameMap', () => {
- it('preserves compliant names and reverses punctuation and 128-character names', () => {
- const names = ['tool_A-2', 'x'.repeat(64), 'files.read', 'mcp:lookup', 'x'.repeat(128)]
+ it('preserves compliant names and reverses opaque canonical names', () => {
+ const names = [
+ 'tool_A-2',
+ 'x'.repeat(64),
+ 'files.read',
+ 'mcp:lookup',
+ 'x'.repeat(129),
+ 'tool name',
+ '工具@read',
+ ]
const map = new ToolNameMap(names)
for (const name of names) {
expect(map.toWire(name)).toMatch(/^[A-Za-z0-9_-]{1,64}$/)
@@ -47,10 +55,16 @@ describe('ToolNameMap', () => {
expect(map.fromWire(map.toWire('a.b'))).toBe('a.b')
expect(map.fromWire(map.toWire('a:b'))).toBe('a:b')
})
+ it('accepts exact registered canonical echoes', () => {
+ const name = '工具@read record'
+ const map = new ToolNameMap([name])
+ expect(map.fromWire(name)).toBe(name)
+ expect(map.fromWire(`${name} extra`)).toBeUndefined()
+ })
it('does not manufacture canonical targets from unknown aliases or unsafe names', () => {
const map = new ToolNameMap(['files.read'])
expect(map.fromWire('__codex_tool_unknown')).toBeUndefined()
- expect(map.fromWire('files.read')).toBeUndefined()
+ expect(map.fromWire('unknown.read')).toBeUndefined()
expect(map.fromWire('ordinary_unknown')).toBe('ordinary_unknown')
expect(() => map.toWire('missing')).toThrow('Unknown canonical tool name')
})
diff --git a/docs/architecture/codex-subscription-transport-contract.md b/docs/architecture/codex-subscription-transport-contract.md
index 55207c945..1a352056f 100644
--- a/docs/architecture/codex-subscription-transport-contract.md
+++ b/docs/architecture/codex-subscription-transport-contract.md
@@ -117,9 +117,10 @@ ordinary unknown names retain the Host registry's authorization checks.
### Selected MCP argument validation
-The Host validates selected MCP arguments before approval and rechecks the live
-schema immediately before dispatch. Missing `$schema` uses JSON Schema 2020-12;
-explicit draft-07 and 2019-09 are also supported. Unsupported dialects and
+For tasks whose provider chain includes Codex, the Host validates selected MCP
+arguments before approval and rechecks the live schema immediately before
+dispatch. Other provider chains retain server-side argument validation. Missing `$schema` uses JSON Schema 2020-12;
+explicit draft-07 and 2019-09 are also supported, including HTTP/HTTPS URI aliases. Unsupported dialects and
unresolved references fail explicitly. Validation never coerces types, applies
defaults, removes arguments, or loads remote references.
@@ -127,10 +128,14 @@ Compilation and evaluation run in disposable Node workers, outside the Host
event loop. Each operation has a two-second deadline and V8 heap/stack limits;
these are not a total-process RSS guarantee. Inputs are bounded to 256 KiB per
schema/argument document, 10,000 nodes and depth 64. At most four workers may be
-active; saturation fails validation instead of building an unbounded queue.
+active, with a FIFO queue of at most 32 waiting requests. Admission and execution
+share the two-second deadline; queue overflow and timeout fail explicitly.
Worker startup adds latency and is not claimed as a quota optimization. A
successful validation waits for worker teardown before releasing its caller.
-Schema or argument changes during validation prevent dispatch.
+A single successful schema/argument pair may be reused by the same adapter;
+byte-identical live inputs are required, so changes invalidate reuse before
+dispatch. Sanitized failure codes distinguish argument/schema errors, resource
+limits, saturation, timeout and worker failure.
Deployment readiness checks after a combined apply do not enforce the ordering
above. The infrastructure rollout barrier remains a separate release dependency;
diff --git a/docs/testing/minikube-t2-runbook.md b/docs/testing/minikube-t2-runbook.md
index 9be4bf776..788a18a22 100644
--- a/docs/testing/minikube-t2-runbook.md
+++ b/docs/testing/minikube-t2-runbook.md
@@ -133,6 +133,26 @@ cluster fingerprint, image coordinate, and the exact `imagesGeneratedAt` value
from the image manifest. A mismatch—including a new image acquisition at the
same HEAD—stops with a stable error code instead of allowing a mixed-commit run.
+Certifying preflight also verifies the live `codex-llm-proxy` against the
+profile's recorded production image ID. The Deployment and every selected
+running pod must have the production image, with no approved-tools fixture
+annotation or environment flags. A bounded read-only predicate checks the live
+environment without exposing values, including flags inherited through
+`envFrom`. Repository digests are resolved to config image IDs through the
+bounded, profile-local image inventory; missing or ambiguous mappings fail
+`PROXY_RUNTIME_MISMATCH`. Ready replicas and a matching marker alone cannot
+certify a fixture proxy left by prepare or an interrupted journey. Restore the
+production proxy before retrying runtime certification. This check runs again
+in the final preflight after optional journeys; planner mode does not certify it.
+
+Health and Playwright commands inherit the parent's opaque lease token,
+profile, explicit context, repository, and lock root for that invocation only.
+A nested mutation wrapper revalidates the full repository/branch/HEAD/profile/
+context/worktree/lock-key binding and live owner before using the lease. A
+missing token or mismatched binding fails; the journey cannot acquire a second
+lease or redirect an inherited lease to another profile. Hermetic coverage is
+`bash scripts/tests/test-minikube-t2-proxy-runtime.sh`.
+
Mutating image acquisition/builds and targeted deploys are children of that
same exact profile lease. Public Make targets acquire it; private body targets,
`pull-images.sh`, and `build-images.sh` validate the inherited token again
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index e8f24ccb6..006383322 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.325",
+ "version": "0.1.326",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.325",
+ "version": "0.1.326",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 468d8879a..0516d30c4 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.325",
+ "version": "0.1.326",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/agent/taskExecutor.ts b/mcp-host/src/agent/taskExecutor.ts
index 07e18f356..b0320836b 100644
--- a/mcp-host/src/agent/taskExecutor.ts
+++ b/mcp-host/src/agent/taskExecutor.ts
@@ -1726,8 +1726,8 @@ export class TaskExecutor {
this.workflowCallerContextOverride === undefined
? await this.prepareChannelWorkflowCallerContext()
: this.workflowCallerContextOverride
- // Failover reuses this presentation and bridge; optimization follows the
- // primary provider for this task. Both presentations remain executable.
+ // Failover reuses this registry: any Codex provider in the chain requires
+ // Codex-compatible presentation before the first provider attempt.
const presentation = resolveToolPresentation(
this.deps.llmProvider.getProviderType(),
appConfig,
@@ -1763,7 +1763,8 @@ export class TaskExecutor {
// absent). buildToolRegistry runs per turn, so one userId per adapter.
new McpToolRegistryAdapter(
this.deps.mcpManager,
- this.task.sourceMessage?.sender ?? undefined
+ this.task.sourceMessage?.sender ?? undefined,
+ { strictValidation: presentation.codexMode !== undefined }
)
: nativeRegistry
const compositeRegistry = this.deps.mcpManager
diff --git a/mcp-host/src/core/adapters/__tests__/boundedSchemaValidation.test.ts b/mcp-host/src/core/adapters/__tests__/boundedSchemaValidation.test.ts
index 63f4a44d2..2f61d5485 100644
--- a/mcp-host/src/core/adapters/__tests__/boundedSchemaValidation.test.ts
+++ b/mcp-host/src/core/adapters/__tests__/boundedSchemaValidation.test.ts
@@ -30,6 +30,9 @@ describe('bounded MCP schema validation', () => {
it.each([
undefined,
'http://json-schema.org/draft-07/schema#',
+ 'https://json-schema.org/draft-07/schema',
+ 'http://json-schema.org/draft/2020-12/schema#',
+ 'http://json-schema.org/draft/2019-09/schema',
'https://json-schema.org/draft/2019-09/schema',
'https://json-schema.org/draft/2020-12/schema',
])('validates without coercion for %s', async dialect => {
@@ -72,7 +75,29 @@ describe('bounded MCP schema validation', () => {
expect(() => boundedJson({ toJSON: () => ({}) })).toThrow()
})
- it('fails closed at capacity until cancelled workers actually exit', async () => {
+ it('queues a fifth validation until a worker exits', async () => {
+ const workers = Array.from({ length: 5 }, () => {
+ const worker = new EventEmitter() as EventEmitter & { terminate: ReturnType<typeof vi.fn> }
+ worker.terminate = vi.fn(async () => {
+ worker.emit('exit', 0)
+ return 0
+ })
+ vi.mocked(Worker).mockImplementationOnce(function () {
+ return worker as unknown as Worker
+ })
+ return worker
+ })
+ const pending = workers.map(() => validateBoundedSchema('{}', '{}'))
+ await Promise.resolve()
+ expect(Worker).toHaveBeenCalledTimes(4)
+ workers[0].emit('message', true)
+ await Promise.resolve()
+ expect(Worker).toHaveBeenCalledTimes(5)
+ workers.slice(1).forEach(worker => worker.emit('message', true))
+ expect(await Promise.all(pending)).toEqual([true, true, true, true, true])
+ })
+
+ it('bounds queued requests and retains slots until stalled workers exit', async () => {
vi.useFakeTimers()
const workers = Array.from({ length: 4 }, () => {
const worker = new EventEmitter() as EventEmitter & { terminate: ReturnType<typeof vi.fn> }
@@ -82,12 +107,13 @@ describe('bounded MCP schema validation', () => {
})
return worker
})
- const pending = workers.map(() => validateBoundedSchema('{}', '{}'))
- expect(await validateBoundedSchema('{}', '{}')).toBe(false)
+ const pending = Array.from({ length: 36 }, () => validateBoundedSchema('{}', '{}'))
+ const failure = vi.fn()
+ expect(await validateBoundedSchema('{}', '{}', failure)).toBe(false)
+ expect(failure).toHaveBeenCalledWith('queue_full')
expect(Worker).toHaveBeenCalledTimes(4)
await vi.advanceTimersByTimeAsync(2_000)
- expect(await Promise.all(pending)).toEqual([false, false, false, false])
- expect(await validateBoundedSchema('{}', '{}')).toBe(false)
+ expect(await Promise.all(pending)).toEqual(Array(36).fill(false))
expect(Worker).toHaveBeenCalledTimes(4)
for (const worker of workers) worker.emit('exit', 1)
})
@@ -104,11 +130,35 @@ describe('bounded MCP schema validation', () => {
})
const hostTick = vi.fn()
setTimeout(hostTick, 10)
- const result = validateBoundedSchema('{}', '{}')
+ const failure = vi.fn()
+ const result = validateBoundedSchema('{}', '{}', failure)
await vi.advanceTimersByTimeAsync(10)
expect(hostTick).toHaveBeenCalledOnce()
await vi.advanceTimersByTimeAsync(2_000)
expect(await result).toBe(false)
+ expect(failure).toHaveBeenCalledWith('timeout')
expect(stalled.terminate).toHaveBeenCalledOnce()
})
})
+
+it.each([
+ [{ $schema: 'https://example.invalid/schema' }, {}, 'unsupported_schema'],
+ [{ type: 'unknown-type' }, {}, 'invalid_schema'],
+ [{ type: 'object', required: ['count'] }, {}, 'invalid_arguments'],
+] as const)(
+ 'classifies validation failures without raw diagnostics: %s',
+ async (schema, params, code) => {
+ const failure = vi.fn()
+ expect(await validateBoundedSchema(boundedJson(schema), boundedJson(params), failure)).toBe(
+ false
+ )
+ expect(failure).toHaveBeenCalledExactlyOnceWith(code)
+ }
+)
+
+it('classifies oversized worker input before starting a worker', async () => {
+ const failure = vi.fn()
+ expect(await validateBoundedSchema('{}', 'x'.repeat(256 * 1024 + 1), failure)).toBe(false)
+ expect(failure).toHaveBeenCalledExactlyOnceWith('input_limit')
+ expect(Worker).not.toHaveBeenCalled()
+})
diff --git a/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts b/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts
index a66467c40..0d5b62c84 100644
--- a/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts
+++ b/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts
@@ -378,7 +378,9 @@ describe('MCP dispatch freshness across asynchronous validation', () => {
: [],
callTool: vi.fn(async () => ({ result: { content: [] }, isError: false })),
}
- const tool = new McpToolRegistryAdapter(manager as any).get('alpha__read')!
+ const tool = new McpToolRegistryAdapter(manager as any, undefined, {
+ strictValidation: true,
+ }).get('alpha__read')!
let complete!: (valid: boolean) => void
vi.mocked(validateBoundedSchema).mockImplementationOnce(
() =>
@@ -396,3 +398,81 @@ describe('MCP dispatch freshness across asynchronous validation', () => {
}
)
})
+
+describe('MCP validation scope and reuse', () => {
+ function fixture(strictValidation: boolean) {
+ const schema: Record<string, unknown> = { type: 'object' }
+ const manager = {
+ getAllTools: () => [{ name: 'alpha__read', serverName: 'alpha', inputSchema: schema }],
+ callTool: vi.fn(async () => ({ result: 'ok', isError: false })),
+ }
+ const tool = new McpToolRegistryAdapter(manager as any, undefined, { strictValidation }).get(
+ 'alpha__read'
+ )!
+ return { schema, manager, tool }
+ }
+
+ it('preserves server validation of other providers, including large arguments and older dialects', async () => {
+ const { schema, manager, tool } = fixture(false)
+ schema.$schema = 'http://json-schema.org/draft-04/schema#'
+ const args = { content: 'x'.repeat(256 * 1024 + 1) }
+ const before = vi.mocked(validateBoundedSchema).mock.calls.length
+ expect((await tool.validateParams!(args)).is_valid).toBe(true)
+ expect((await tool.execute(args)).is_error).toBe(false)
+ expect(manager.callTool).toHaveBeenCalledWith('alpha__read', args, { userId: undefined })
+ expect(vi.mocked(validateBoundedSchema).mock.calls.length).toBe(before)
+ })
+
+ it('reuses a successful pair but revalidates changed schema and arguments after approval', async () => {
+ const { schema, manager, tool } = fixture(true)
+ const args = { count: 1 }
+ const before = vi.mocked(validateBoundedSchema).mock.calls.length
+ expect((await tool.validateParams!(args)).is_valid).toBe(true)
+ expect((await tool.execute(args)).is_error).toBe(false)
+ expect(vi.mocked(validateBoundedSchema).mock.calls.length - before).toBe(1)
+ args.count = 2
+ expect((await tool.execute(args)).is_error).toBe(false)
+ expect(vi.mocked(validateBoundedSchema).mock.calls.length - before).toBe(2)
+ schema.required = ['missing']
+ expect((await tool.execute(args)).is_error).toBe(true)
+ expect(vi.mocked(validateBoundedSchema).mock.calls.length - before).toBe(3)
+ expect(manager.callTool).toHaveBeenCalledTimes(2)
+ })
+
+ it.each([
+ ['queue_full', 'busy'],
+ ['timeout', 'time limit'],
+ ['unsupported_schema', 'unsupported'],
+ ['invalid_schema', 'could not be compiled'],
+ ['invalid_arguments', 'correct the arguments'],
+ ['worker_failure', 'could not complete'],
+ ] as const)(
+ 'preserves safe %s diagnostics through validation and dispatch',
+ async (code, text) => {
+ const { manager, tool } = fixture(true)
+ vi.mocked(validateBoundedSchema).mockImplementationOnce(
+ async (_schema, _params, onFailure) => {
+ onFailure?.(code)
+ return false
+ }
+ )
+ expect((await tool.validateParams!({})).errors.join(' ')).toContain(text)
+ vi.mocked(validateBoundedSchema).mockImplementationOnce(
+ async (_schema, _params, onFailure) => {
+ onFailure?.(code)
+ return false
+ }
+ )
+ expect((await tool.execute({})).content).toContain(text)
+ expect(manager.callTool).not.toHaveBeenCalled()
+ }
+ )
+ it('fails closed for unsupported dialects and oversized arguments in strict mode', async () => {
+ const { schema, manager, tool } = fixture(true)
+ schema.$schema = 'http://json-schema.org/draft-04/schema#'
+ expect((await tool.execute({})).is_error).toBe(true)
+ delete schema.$schema
+ expect((await tool.execute({ content: 'x'.repeat(256 * 1024 + 1) })).is_error).toBe(true)
+ expect(manager.callTool).not.toHaveBeenCalled()
+ })
+})
diff --git a/mcp-host/src/core/adapters/boundedSchemaValidation.ts b/mcp-host/src/core/adapters/boundedSchemaValidation.ts
index 816744bab..03ae447da 100644
--- a/mcp-host/src/core/adapters/boundedSchemaValidation.ts
+++ b/mcp-host/src/core/adapters/boundedSchemaValidation.ts
@@ -5,44 +5,87 @@ const MAX_NODES = 10_000
const MAX_DEPTH = 64
const DEADLINE_MS = 2_000
const MAX_WORKERS = 4
+const MAX_QUEUED = 32
let activeWorkers = 0
+const queue: Array<() => void> = []
+
+export type SchemaValidationFailure =
+ | 'input_limit'
+ | 'queue_full'
+ | 'timeout'
+ | 'unsupported_schema'
+ | 'invalid_schema'
+ | 'invalid_arguments'
+ | 'worker_failure'
+
+function reserveWorker(): Promise<true | 'queue_full' | 'timeout'> {
+ if (activeWorkers < MAX_WORKERS) {
+ activeWorkers++
+ return Promise.resolve(true)
+ }
+ if (queue.length >= MAX_QUEUED) return Promise.resolve('queue_full')
+ return new Promise(resolve => {
+ const start = () => {
+ clearTimeout(timer)
+ activeWorkers++
+ resolve(true)
+ }
+ const timer = setTimeout(() => {
+ queue.splice(queue.indexOf(start), 1)
+ resolve('timeout')
+ }, DEADLINE_MS)
+ queue.push(start)
+ })
+}
+
+function releaseWorker(): void {
+ activeWorkers--
+ queue.shift()?.()
+}
/** Bound cloning/serialization before crossing the worker boundary. Catalog and
* argument inputs are JSON data; reject accessors, cycles and non-JSON values.
* No toJSON hook is called and no caller-owned value is mutated. */
+export class BoundedJsonError extends Error {
+ constructor(readonly failure: 'input_limit' | 'input_invalid') {
+ super(failure)
+ }
+}
+
export function boundedJson(value: unknown): string {
let nodes = 0
let characters = 0
const ancestors = new Set<object>()
function clone(input: unknown, depth: number): unknown {
- if (++nodes > MAX_NODES || depth > MAX_DEPTH) throw new Error('JSON limit')
+ if (++nodes > MAX_NODES || depth > MAX_DEPTH) throw new BoundedJsonError('input_limit')
if (typeof input === 'string') {
characters += input.length
- if (characters > MAX_BYTES) throw new Error('JSON limit')
+ if (characters > MAX_BYTES) throw new BoundedJsonError('input_limit')
return input
}
if (input === null || typeof input === 'boolean') return input
if (typeof input === 'number' && Number.isFinite(input)) return input
- if (!input || typeof input !== 'object' || ancestors.has(input)) throw new Error('JSON type')
+ if (!input || typeof input !== 'object' || ancestors.has(input))
+ throw new BoundedJsonError('input_invalid')
const array = Array.isArray(input)
if (
!array &&
Object.getPrototypeOf(input) !== Object.prototype &&
Object.getPrototypeOf(input) !== null
)
- throw new Error('JSON type')
- if (array && input.length > MAX_NODES) throw new Error('JSON limit')
+ throw new BoundedJsonError('input_invalid')
+ if (array && input.length > MAX_NODES) throw new BoundedJsonError('input_limit')
ancestors.add(input)
const output: Record<string, unknown> | unknown[] = array ? [] : Object.create(null)
let entries = 0
for (const key in input) {
if (!Object.hasOwn(input, key)) continue
- if (array && key !== String(entries)) throw new Error('JSON array')
+ if (array && key !== String(entries)) throw new BoundedJsonError('input_invalid')
entries++
characters += key.length
- if (characters > MAX_BYTES) throw new Error('JSON limit')
+ if (characters > MAX_BYTES) throw new BoundedJsonError('input_limit')
const property = Object.getOwnPropertyDescriptor(input, key)!
- if (!('value' in property)) throw new Error('JSON accessor')
+ if (!('value' in property)) throw new BoundedJsonError('input_invalid')
Object.defineProperty(output, key, {
value: clone(property.value, depth + 1),
enumerable: true,
@@ -50,12 +93,12 @@ export function boundedJson(value: unknown): string {
writable: true,
})
}
- if (array && entries !== input.length) throw new Error('JSON array')
+ if (array && entries !== input.length) throw new BoundedJsonError('input_invalid')
ancestors.delete(input)
return output
}
const serialized = JSON.stringify(clone(value, 0))
- if (Buffer.byteLength(serialized) > MAX_BYTES) throw new Error('JSON limit')
+ if (Buffer.byteLength(serialized) > MAX_BYTES) throw new BoundedJsonError('input_limit')
return serialized
}
@@ -63,39 +106,53 @@ export function boundedJson(value: unknown): string {
// output. Only Ajv compile/evaluation executes here; no remote ref loader exists.
const WORKER_SOURCE = `
const { parentPort, workerData } = require('node:worker_threads');
+let failure = 'invalid_schema';
try {
const schema = JSON.parse(workerData.schema);
const params = JSON.parse(workerData.params);
- const dialect = typeof schema.$schema === 'string' ? schema.$schema.replace(/#$/, '') : undefined;
+ const dialect = typeof schema.$schema === 'string' ? schema.$schema.replace(/#$/, '').replace(/^http:/, 'https:') : undefined;
const index = dialect === undefined || dialect === 'https://json-schema.org/draft/2020-12/schema' ? 2
: dialect === 'https://json-schema.org/draft/2019-09/schema' ? 1
- : dialect === 'http://json-schema.org/draft-07/schema' ? 0 : -1;
- if (index < 0) throw new Error('Unsupported schema');
+ : dialect === 'https://json-schema.org/draft-07/schema' ? 0 : -1;
+ if (index < 0 || schema.$async === true) { failure = 'unsupported_schema'; throw new Error(); }
+ if (dialect !== undefined) schema.$schema = index === 0
+ ? 'http://json-schema.org/draft-07/schema#' : dialect;
const module = require(workerData.modules[index]);
const Ajv = module.default || module;
const ajv = new Ajv({ strict: false, allErrors: false, coerceTypes: false,
useDefaults: false, removeAdditional: false, validateFormats: false });
const validate = ajv.compile(schema);
- parentPort.postMessage(!('$async' in validate) && validate(params) === true);
-} catch { parentPort.postMessage(false); }
+ failure = 'invalid_arguments';
+ parentPort.postMessage(validate(params) === true ? true : failure);
+} catch { parentPort.postMessage(failure); }
`
-/** One disposable worker per validation, no unbounded queue or schema cache.
+/** Disposable workers with a bounded FIFO queue and total wait/execution deadline.
* Capacity remains reserved until the worker actually exits, including timeout
* cancellation. Resource exhaustion, startup errors and invalid replies fail closed.
* No schema, arguments or Ajv diagnostics are returned to the Host. */
-export async function validateBoundedSchema(schema: string, params: string): Promise<boolean> {
- if (
- Buffer.byteLength(schema) > MAX_BYTES ||
- Buffer.byteLength(params) > MAX_BYTES ||
- activeWorkers >= MAX_WORKERS
- )
+export async function validateBoundedSchema(
+ schema: string,
+ params: string,
+ onFailure?: (failure: SchemaValidationFailure) => void
+): Promise<boolean> {
+ const reject = (failure: SchemaValidationFailure) => {
+ onFailure?.(failure)
return false
- activeWorkers++
+ }
+ if (Buffer.byteLength(schema) > MAX_BYTES || Buffer.byteLength(params) > MAX_BYTES)
+ return reject('input_limit')
+ const deadline = Date.now() + DEADLINE_MS
+ const reservation = await reserveWorker()
+ if (reservation !== true) return reject(reservation)
+ if (Date.now() >= deadline) {
+ releaseWorker()
+ return reject('timeout')
+ }
return new Promise<boolean>(resolve => {
let worker: Worker
let done = false
- const finish = (valid: boolean) => {
+ const finish = (valid: boolean, failure: SchemaValidationFailure = 'worker_failure') => {
if (done) return
done = true
clearTimeout(timer)
@@ -103,17 +160,17 @@ export async function validateBoundedSchema(schema: string, params: string): Pro
if (valid && worker) {
void worker.terminate().then(
() => resolve(true),
- () => resolve(false)
+ () => resolve(reject('worker_failure'))
)
} else {
- resolve(false)
+ resolve(reject(failure))
if (worker)
void worker.terminate().catch(() => {
/* Exit retains capacity ownership. */
})
}
}
- const timer = setTimeout(() => finish(false), DEADLINE_MS)
+ const timer = setTimeout(() => finish(false, 'timeout'), Math.max(0, deadline - Date.now()))
try {
worker = new Worker(WORKER_SOURCE, {
eval: true,
@@ -132,14 +189,21 @@ export async function validateBoundedSchema(schema: string, params: string): Pro
stackSizeMb: 4,
},
})
- worker.once('message', message => finish(message === true))
+ worker.once('message', message => {
+ const failure = ['unsupported_schema', 'invalid_schema', 'invalid_arguments'].includes(
+ message
+ )
+ ? (message as SchemaValidationFailure)
+ : 'worker_failure'
+ finish(message === true, failure)
+ })
worker.once('error', () => finish(false))
worker.once('exit', () => {
- activeWorkers--
+ releaseWorker()
finish(false)
})
} catch {
- activeWorkers--
+ releaseWorker()
finish(false)
}
})
diff --git a/mcp-host/src/core/adapters/toolRegistryAdapter.ts b/mcp-host/src/core/adapters/toolRegistryAdapter.ts
index 6a1da2b7e..c382bd6dd 100644
--- a/mcp-host/src/core/adapters/toolRegistryAdapter.ts
+++ b/mcp-host/src/core/adapters/toolRegistryAdapter.ts
@@ -3,7 +3,12 @@ import { logger } from '../../logger'
import { McpManager } from '../../mcp/manager'
import { Tool, ToolRegistry } from '../interfaces'
import { Attachment, ToolDefinition, ToolOutput, ValidationResult } from '../types'
-import { boundedJson, validateBoundedSchema } from './boundedSchemaValidation'
+import {
+ BoundedJsonError,
+ type SchemaValidationFailure,
+ boundedJson,
+ validateBoundedSchema,
+} from './boundedSchemaValidation'
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value)
@@ -77,6 +82,10 @@ function extractMcpContent(
* Tool names preserve the serverName__toolName convention (Risk 4.8).
*/
class McpToolAdapter implements Tool {
+ // One bounded successful pair per adapter avoids re-running Ajv after approval.
+ // Every use still serializes the live schema and arguments and checks freshness.
+ private validated?: { schemaJson: string; paramsJson: string }
+
constructor(
private readonly fullName: string,
private readonly desc: string,
@@ -88,7 +97,8 @@ class McpToolAdapter implements Tool {
* tool-lane guardrail identity that `server=` rules match on — see below.
*/
private readonly serverName: string,
- private readonly userId?: string
+ private readonly userId: string | undefined,
+ private readonly strictValidation: boolean
) {}
name() {
@@ -112,21 +122,59 @@ class McpToolAdapter implements Tool {
.find(tool => tool.name === this.fullName && serverNameOf(tool) === this.serverName)
}
+ private validationFailure(
+ code: SchemaValidationFailure | 'tool_changed' | 'input_invalid'
+ ): ValidationResult {
+ const messages = {
+ input_limit:
+ 'MCP validation input exceeds the supported size limit; reduce the request size.',
+ input_invalid:
+ 'MCP schema or arguments are not supported bounded JSON; check their structure and size.',
+ queue_full: 'MCP validation is busy; retry shortly.',
+ timeout: 'MCP validation exceeded its time limit; retry or simplify the request.',
+ unsupported_schema:
+ 'This MCP schema dialect or asynchronous schema is unsupported by local validation; ask the server owner to update it.',
+ invalid_schema:
+ 'The MCP schema could not be compiled locally; ask the server owner to correct it.',
+ invalid_arguments: 'Arguments do not match the current MCP schema; correct the arguments.',
+ worker_failure:
+ 'MCP validation could not complete; retry and contact the administrator if it persists.',
+ tool_changed:
+ 'The MCP tool or arguments changed during validation; retry with the current tool definition.',
+ }
+ logger.warn({ component: 'ToolRegistry', validationFailure: code }, 'MCP validation rejected')
+ return { is_valid: false, errors: [messages[code]] }
+ }
+
private async validateCurrent(params: Record<string, unknown>) {
const live = this.liveTool()
- const rejected: ValidationResult = {
- is_valid: false,
- errors: ['Arguments or current MCP schema could not be validated; describe the tool again.'],
- }
try {
- if (!live || !asRecord(live.inputSchema)) return { result: rejected }
+ if (!live || !asRecord(live.inputSchema)) {
+ this.validated = undefined
+ return { result: this.validationFailure('tool_changed') }
+ }
const schemaJson = boundedJson(live.inputSchema)
const paramsJson = boundedJson(params)
- if (!(await validateBoundedSchema(schemaJson, paramsJson))) return { result: rejected }
+ if (this.validated?.schemaJson !== schemaJson || this.validated?.paramsJson !== paramsJson) {
+ this.validated = undefined
+ let failure: SchemaValidationFailure = 'worker_failure'
+ if (
+ !(await validateBoundedSchema(schemaJson, paramsJson, code => {
+ failure = code
+ }))
+ )
+ return { result: this.validationFailure(failure) }
+ this.validated = { schemaJson, paramsJson }
+ }
return { result: { is_valid: true, errors: [] } as ValidationResult, schemaJson, paramsJson }
- } catch {
+ } catch (error) {
// Never include raw schemas, arguments or validator diagnostics in errors.
- return { result: rejected }
+ this.validated = undefined
+ return {
+ result: this.validationFailure(
+ error instanceof BoundedJsonError ? error.failure : 'input_invalid'
+ ),
+ }
}
}
@@ -148,10 +196,12 @@ class McpToolAdapter implements Tool {
}
async validateParams(params: Record<string, unknown>): Promise<ValidationResult> {
+ if (!this.strictValidation) return { is_valid: true, errors: [] }
const checked = await this.validateCurrent(params)
+ if (!checked.result.is_valid) return checked.result
return this.validationStillCurrent(checked, params)
? checked.result
- : { is_valid: false, errors: ['MCP validation failed or tool changed during validation.'] }
+ : this.validationFailure('tool_changed')
}
traceDescriptor() {
// `sourceRef` is the tool-lane guardrail's `server` identity (provenance.ts),
@@ -172,12 +222,15 @@ class McpToolAdapter implements Tool {
try {
// An approval may have been suspended with an older adapter/schema.
// Resolve the live schema again immediately before manager dispatch.
- const checked = await this.validateCurrent(params)
+ const checked = this.strictValidation ? await this.validateCurrent(params) : undefined
// No await between the freshness check and manager dispatch: catalog or
// argument changes during worker evaluation cannot authorize this call.
- if (!this.validationStillCurrent(checked, params)) {
+ if (checked && !this.validationStillCurrent(checked, params)) {
return {
- content: 'MCP validation failed or tool changed during validation.',
+ content: (checked.result.is_valid
+ ? this.validationFailure('tool_changed')
+ : checked.result
+ ).errors.join(' '),
duration_ms: Date.now() - startTime,
is_error: true,
}
@@ -247,7 +300,10 @@ export class McpToolRegistryAdapter implements ToolRegistry {
*/
constructor(
private readonly mcpManager: McpManager,
- private readonly userId?: string
+ private readonly userId?: string,
+ // Codex bridge dispatch promises local, bounded schema validation. Other
+ // providers retain their existing MCP server-side validation contract.
+ private readonly options: { strictValidation?: boolean } = {}
) {
this.refresh()
}
@@ -292,7 +348,8 @@ export class McpToolRegistryAdapter implements ToolRegistry {
mcpTool.inputSchema || {},
this.mcpManager,
serverNameOf(mcpTool),
- this.userId
+ this.userId,
+ this.options.strictValidation === true
)
)
}
diff --git a/mcp-host/src/core/orchestration/__tests__/approvedToolsLifecycle.integration.test.ts b/mcp-host/src/core/orchestration/__tests__/approvedToolsLifecycle.integration.test.ts
index 411101734..87d3e5aa4 100644
--- a/mcp-host/src/core/orchestration/__tests__/approvedToolsLifecycle.integration.test.ts
+++ b/mcp-host/src/core/orchestration/__tests__/approvedToolsLifecycle.integration.test.ts
@@ -116,7 +116,7 @@ async function setup(count = 83, reverse = false) {
}
const registry = new CompositeToolRegistry(
native,
- new McpToolRegistryAdapter(manager, 'authenticated-user')
+ new McpToolRegistryAdapter(manager, 'authenticated-user', { strictValidation: true })
)
const conversation = makeFakeConversation({ state: ConversationState.Processing })
const config = buildLoopConfig({
@@ -354,7 +354,9 @@ describe('approved catalog across presentation and lifecycle', () => {
const result = await executeToolCalls([bridgeCall(target)], config, 0)
expect(result.pendingApproval).toBeUndefined()
expect(result.toolResults[0].is_error).toBe(true)
- expect(result.toolResults[0].content).toContain('MCP validation failed')
+ expect(result.toolResults[0].content).toContain(
+ '$async' in schema ? 'unsupported by local validation' : 'could not be compiled locally'
+ )
expect(result.toolResults[0].content.length).toBeLessThan(150)
expect(result.toolResults[0].content).not.toContain('unresolvable.example')
expect(remote.calls).not.toHaveBeenCalled()
@@ -547,7 +549,7 @@ describe('approved catalog across presentation and lifecycle', () => {
message => message.role === 'tool' && message.tool_call_id === call.id
)
if (decision === 'schema-change')
- expect(result?.content).toContain('MCP validation failed')
+ expect(result?.content).toContain('Arguments do not match the current MCP schema')
else if (decision === 'revoke')
expect(result?.content).toMatch(/not found|not available/i)
else expect(result?.content).toContain('receipt:alpha:record__read_082')
diff --git a/mcp-host/src/core/reasoning/promptBuilder.ts b/mcp-host/src/core/reasoning/promptBuilder.ts
index 20a3263e4..feae61447 100644
--- a/mcp-host/src/core/reasoning/promptBuilder.ts
+++ b/mcp-host/src/core/reasoning/promptBuilder.ts
@@ -117,8 +117,8 @@ export const MCP_SERVER_SELECTION_TEXT =
* `context` tier without breaking the stable/context cache hash.
*/
export const TOOL_DISCOVERY_TEXT =
- 'You have access to a large catalog of tools that are not all listed directly. ' +
- 'Use `clerum__tool_search` to find them by keyword, `clerum__tool_describe` to ' +
+ 'Use directly listed tools when available. For additional approved tools, ' +
+ 'use `clerum__tool_search` to find them by keyword, `clerum__tool_describe` to ' +
"see one's schema, and `clerum__tool_call` to invoke it. Native tools are " +
'already available directly. Search narrowly for the current task; refine or page ' +
'only when needed rather than loading the whole catalog. Describe only the chosen ' +
diff --git a/mcp-host/src/logger.ts b/mcp-host/src/logger.ts
index 77d2f44fc..9d6e8a490 100644
--- a/mcp-host/src/logger.ts
+++ b/mcp-host/src/logger.ts
@@ -122,8 +122,13 @@ function writeStructured(
(configured && levels[configured] !== undefined ? levels[configured] : levels.info)
)
return
+ const redactedFields = redactUnknown(fields)
const entry = {
- ...(redactUnknown(fields) as Record<string, unknown>),
+ ...(redactedFields !== null &&
+ typeof redactedFields === 'object' &&
+ !Array.isArray(redactedFields)
+ ? (redactedFields as Record<string, unknown>)
+ : { fields: '[Unserializable]' }),
timestamp: new Date().toISOString(),
level,
msg: msg.replace(/[\r\n\u2028\u2029]/g, ' ').trim(),
diff --git a/packages/llm-provider-attempt-contract/index.cjs b/packages/llm-provider-attempt-contract/index.cjs
index 070825841..fa7e9bad3 100644
--- a/packages/llm-provider-attempt-contract/index.cjs
+++ b/packages/llm-provider-attempt-contract/index.cjs
@@ -124,6 +124,12 @@ function isBoundedId(value) {
return typeof value === 'string' && ID_PATTERN.test(value)
}
+// Tool names are opaque registry keys, not authorization/request identifiers.
+// Their size is bounded by maxRequestBodyBytes; transport aliases apply later.
+function isToolName(value) {
+ return typeof value === 'string' && value.length > 0 && !/[\p{Cc}\p{Cs}]/u.test(value)
+}
+
function rejectUnknown(obj, allowed, label) {
const extra = unknownKeys(obj, allowed)
if (extra.length === 0) return null
@@ -176,7 +182,7 @@ function parseMessages(raw) {
if (typeof item.content !== 'string') return fail('invalid', `messages[${i}].content must be a string`)
const message = { role: item.role, content: item.content }
if (item.name !== undefined) {
- if (!isBoundedId(item.name)) return fail('invalid', `messages[${i}].name is invalid`)
+ if (!isToolName(item.name)) return fail('invalid', `messages[${i}].name is invalid`)
message.name = item.name
}
if (item.toolCallId !== undefined) {
@@ -204,7 +210,7 @@ function parseMessages(raw) {
if (!isBoundedId(call.id)) {
return fail('invalid', `messages[${i}].toolCalls[${j}].id is invalid`)
}
- if (!isBoundedId(call.name)) {
+ if (!isToolName(call.name)) {
return fail('invalid', `messages[${i}].toolCalls[${j}].name is invalid`)
}
if (!isPlainObject(call.arguments)) {
@@ -236,7 +242,7 @@ function parseTools(raw) {
if (!isPlainObject(item)) return fail('invalid', `tools[${i}] must be an object`)
const extra = rejectUnknown(item, TOOL_KEYS, `tools[${i}]`)
if (extra) return extra
- if (!isBoundedId(item.name)) return fail('invalid', `tools[${i}].name is invalid`)
+ if (!isToolName(item.name)) return fail('invalid', `tools[${i}].name is invalid`)
if (typeof item.description !== 'string') {
return fail('invalid', `tools[${i}].description must be a string`)
}
diff --git a/packages/llm-provider-attempt-contract/index.test.cjs b/packages/llm-provider-attempt-contract/index.test.cjs
index 0ce9f9b9b..3b9982d90 100644
--- a/packages/llm-provider-attempt-contract/index.test.cjs
+++ b/packages/llm-provider-attempt-contract/index.test.cjs
@@ -303,7 +303,7 @@ test('large catalogs remain bounded by serialized request bytes including UTF-8'
})
test('validates the last definition beyond the former count boundary', () => {
- for (const invalid of [{ name: 'invalid name' }, { parameters: { value: Infinity } }, { headers: {} }]) {
+ for (const invalid of [{ name: 'invalid\u0000name' }, { parameters: { value: Infinity } }, { headers: {} }]) {
const tools = catalog(250)
tools[249] = { ...tools[249], ...invalid }
const parsed = contract.parseCodexCompletionRequestV1({ ...BASE, tools })
@@ -311,3 +311,59 @@ test('validates the last definition beyond the former count boundary', () => {
assert.match(parsed.message, /tools\[249\]/)
}
})
+
+function withCanonicalName(name) {
+ return {
+ ...BASE,
+ tools: [{ name, description: 'Read a record', parameters: { type: 'object' } }],
+ messages: [
+ { role: 'assistant', content: '', toolCalls: [{ id: 'call-1', name, arguments: {} }] },
+ { role: 'tool', content: 'ok', toolCallId: 'call-1', name },
+ ],
+ }
+}
+
+test('preserves opaque canonical names in definitions and assistant/tool history', () => {
+ for (const name of ['read record', '工具@café', 'x'.repeat(129)]) {
+ const request = withCanonicalName(name)
+ const parsed = contract.parseCodexCompletionRequestV1(request)
+ assert.equal(parsed.ok, true, parsed.message)
+ assert.deepEqual(parsed.value, request)
+ assert.equal(contract.hashCodexCompletionRequestV1(parsed.value),
+ crypto.createHash('sha256').update(contract.stableStringify(request)).digest('hex'))
+ }
+})
+
+test('rejects empty and control-bearing names at every canonical name location', () => {
+ for (const name of ['', 'a\u0000b', 'a\nb', 'a\u007fb', 'a\u0085b', 'a\ud800b']) {
+ for (const location of ['definition', 'assistant', 'result']) {
+ const request = withCanonicalName('valid')
+ if (location === 'definition') request.tools[0].name = name
+ if (location === 'assistant') request.messages[0].toolCalls[0].name = name
+ if (location === 'result') request.messages[1].name = name
+ assert.equal(contract.parseCodexCompletionRequestV1(request).ok, false, location)
+ }
+ }
+})
+
+test('opaque tool name support retains strict request and call identifiers', () => {
+ for (const value of ['read record', '工具@café', 'x'.repeat(129)]) {
+ for (const location of ['requestId', 'idempotencyKey', 'callId', 'toolCallId']) {
+ const request = withCanonicalName(value)
+ if (location === 'callId') request.messages[0].toolCalls[0].id = value
+ else if (location === 'toolCallId') request.messages[1].toolCallId = value
+ else request[location] = value
+ assert.equal(contract.parseCodexCompletionRequestV1(request).ok, false, location)
+ }
+ }
+})
+
+test('opaque canonical names remain bounded by serialized UTF-8 request bytes', () => {
+ const request = { ...BASE, tools: [{ name: '工具', description: 'Read a record', parameters: {} }] }
+ request.tools[0].name += 'x'.repeat(contract.LIMITS.maxRequestBodyBytes - Buffer.byteLength(JSON.stringify(request)))
+ assert.equal(contract.parseCodexCompletionRequestV1(request).ok, true)
+ request.tools[0].name += 'é'
+ assert.deepEqual(contract.parseCodexCompletionRequestV1(request), {
+ ok: false, code: 'limit', message: 'request exceeds maxRequestBodyBytes',
+ })
+})
diff --git a/scripts/minikube/t2-common.sh b/scripts/minikube/t2-common.sh
index 84e9b4840..66b04074f 100755
--- a/scripts/minikube/t2-common.sh
+++ b/scripts/minikube/t2-common.sh
@@ -652,9 +652,118 @@ PY
fi
}
+# Readiness alone does not prove that a journey restored the production proxy.
+# The planner may reconcile; certifying preflight requires the live baseline.
+t2_proxy_runtime_check() {
+ [ "$T2_PLAN_MODE" != true ] && [ "$T2_BOOTSTRAP_REQUIRED" != true ] || return 0
+ local deployments="$1" pods inventory pod_names pod_name environment_check
+ if ! pods="$(t2_kc -n "$T2_CONTROL_NAMESPACE" get pods -l app=codex-llm-proxy -o json)"; then
+ t2_fail PROXY_RUNTIME_MISMATCH 'unable to observe running proxy identity'
+ return 1
+ fi
+ if ! inventory="$(t2_mk image ls --format=json)"; then
+ t2_fail PROXY_RUNTIME_MISMATCH 'unable to observe profile image inventory'
+ return 1
+ fi
+ if ! pod_names="$(python3 - "$T2_IMAGE_MANIFEST" "$T2_PROFILE" "$T2_CONTROL_NAMESPACE" "$deployments" "$pods" "$inventory" <<'PY_PROXY'
+import json
+import re
+import sys
+from pathlib import Path
+
+def require(condition):
+ if not condition:
+ raise ValueError("unproven production proxy")
+
+def clean(template):
+ require("evenfire.ai/codex-tools-fixture-run" not in (template.get("metadata", {}).get("annotations") or {}))
+ containers = [c for c in template["spec"]["containers"] if c.get("name") == "codex-llm-proxy"]
+ require(len(containers) == 1)
+ container = containers[0]
+ for entry in container.get("env", []):
+ require(entry.get("name") not in {"CODEX_APPROVED_TOOLS_TEST_ONLY", "CODEX_APPROVED_TOOLS_MINIKUBE_PROFILE"})
+ require(entry.get("name") != "NODE_ENV" or entry.get("value") != "test")
+ return container
+
+try:
+ manifest = json.loads(Path(sys.argv[1]).read_text())
+ require(manifest.get("profile") == sys.argv[2])
+ images = manifest["images"]
+ # Both acquisition modes record this production alias and Docker config ID.
+ baseline = images["clerum/codex-llm-proxy:test"]
+ require(isinstance(baseline, str) and re.fullmatch(r"sha256:[0-9a-f]{64}", baseline))
+ inventory = json.loads(sys.argv[6])
+ require(isinstance(inventory, list))
+ observed = {}
+ for item in inventory:
+ identity = item.get("id", "")
+ if not identity.startswith("sha256:"):
+ identity = "sha256:" + identity
+ require(re.fullmatch(r"sha256:[0-9a-f]{64}", identity))
+ for ref in (item.get("repoTags") or []) + (item.get("repoDigests") or []):
+ require(ref not in observed or observed[ref] == identity)
+ observed[ref] = identity
+ deployments = [d for d in json.loads(sys.argv[4])["items"] if
+ d.get("metadata", {}).get("namespace") == sys.argv[3] and
+ d.get("metadata", {}).get("name") == "codex-llm-proxy"]
+ require(len(deployments) == 1)
+ deployment = deployments[0]
+ desired = deployment["spec"].get("replicas", 1)
+ require(isinstance(desired, int) and desired > 0)
+ target = clean(deployment["spec"]["template"])
+ require(images.get(target["image"]) == baseline)
+ ref = target["image"]
+ canonical = "docker.io/" + ref if ref.startswith("clerum/") else ref
+ require(observed.get(canonical) == baseline)
+ pods = json.loads(sys.argv[5])["items"]
+ require(len(pods) >= desired)
+ names = []
+ for pod in pods:
+ require(not pod["metadata"].get("deletionTimestamp"))
+ require(pod["metadata"].get("namespace") == sys.argv[3])
+ container = clean(pod)
+ require(container["image"] == target["image"])
+ statuses = [c for c in pod["status"]["containerStatuses"] if c.get("name") == "codex-llm-proxy"]
+ require(len(statuses) == 1 and statuses[0].get("ready") is True)
+ require(bool(statuses[0].get("state", {}).get("running")))
+ # Resolve a repository digest through the owned profile inventory;
+ # config IDs and repository manifest digests are different identities.
+ image_id = statuses[0].get("imageID", "")
+ if image_id.startswith("docker://"):
+ image_id = image_id[len("docker://"):]
+ elif image_id.startswith("docker-pullable://"):
+ image_id = image_id[len("docker-pullable://"):]
+ if "@sha256:" in image_id:
+ image_id = observed.get(image_id)
+ require(image_id == baseline)
+ name = pod["metadata"]["name"]
+ require(re.fullmatch(r"[a-z0-9][a-z0-9.-]*", name))
+ names.append(name)
+ print("\n".join(names))
+except (OSError, ValueError, KeyError, TypeError, AttributeError):
+ raise SystemExit("production proxy identity, fixture markers, or baseline evidence did not match")
+PY_PROXY
+ )"; then
+ T2_NEXT_COMMAND="restore the production proxy and retry MINIKUBE_PROFILE=$T2_PROFILE make minikube-t2-runtime"
+ t2_fail PROXY_RUNTIME_MISMATCH 'live proxy does not prove the recorded production baseline'
+ return 1
+ fi
+ # Read only fixture predicates, including envFrom/image-level variables;
+ # never emit the environment or secret-bearing objects as evidence.
+ while IFS= read -r pod_name; do
+ if ! environment_check="$(t2_kc -n "$T2_CONTROL_NAMESPACE" exec "$pod_name" -c codex-llm-proxy -- node -e \
+ 'process.stdout.write(String(!("CODEX_APPROVED_TOOLS_TEST_ONLY" in process.env) && !("CODEX_APPROVED_TOOLS_MINIKUBE_PROFILE" in process.env) && process.env.NODE_ENV !== "test"))')" ||
+ [ "$environment_check" != true ]; then
+ t2_fail PROXY_RUNTIME_MISMATCH 'running proxy environment is unknown or retains fixture configuration'
+ return 1
+ fi
+ done <<< "$pod_names"
+}
+
t2_deployment_check() {
local deployment_json unready
deployment_json="$(t2_kc get deployments -A -o json 2>/dev/null || true)"
+ T2_DEPLOYMENT_JSON="$deployment_json"
if [ -z "$deployment_json" ]; then
if [ "$T2_BOOTSTRAP_REQUIRED" = true ]; then
T2_PLAN_STATE=full-bootstrap
diff --git a/scripts/minikube/t2-preflight.sh b/scripts/minikube/t2-preflight.sh
index 4f146c02e..5bff3987c 100755
--- a/scripts/minikube/t2-preflight.sh
+++ b/scripts/minikube/t2-preflight.sh
@@ -51,6 +51,7 @@ main() {
t2_resource_checks
t2_postgres_check
t2_deployment_check
+ t2_proxy_runtime_check "$T2_DEPLOYMENT_JSON"
t2_process_check
t2_classify_transition
t2_write_plan "$T2_PLAN_FILE"
diff --git a/scripts/tests/test-minikube-t2-contract.sh b/scripts/tests/test-minikube-t2-contract.sh
index 5e00e25a5..5f870b69d 100755
--- a/scripts/tests/test-minikube-t2-contract.sh
+++ b/scripts/tests/test-minikube-t2-contract.sh
@@ -26,6 +26,7 @@ for file in "$MINIKUBE_DIR/profile-readiness.sh" "$ROOT/scripts/tests/test-minik
"$ROOT/scripts/tests/lib/minikube-fixture-repo.sh" \
"$ROOT/scripts/tests/test-minikube-t2-public-boundary.sh" \
"$ROOT/scripts/tests/test-minikube-t2-scenarios.sh" \
+ "$ROOT/scripts/tests/test-minikube-t2-proxy-runtime.sh" \
"$ROOT/scripts/tests/test-minikube-settle-gfs-reader-rollout.sh" \
"$ROOT/scripts/tests/test-minikube-gfs-rollout-shim.sh" \
"$ROOT/scripts/tests/test-minikube-gfs-provision-order.sh" \
@@ -644,6 +645,7 @@ if T2_PUBLIC_ROOT="$public_repo" T2_PUBLIC_BASE_REF="$public_base" \
exit 1
fi
bash "$ROOT/scripts/tests/test-minikube-t2-scenarios.sh"
+bash "$ROOT/scripts/tests/test-minikube-t2-proxy-runtime.sh"
bash "$ROOT/scripts/tests/test-minikube-profile-readiness.sh"
bash "$ROOT/scripts/tests/test-minikube-settle-gfs-reader-rollout.sh"
bash "$ROOT/scripts/tests/test-minikube-gfs-rollout-shim.sh"
diff --git a/scripts/tests/test-minikube-t2-proxy-runtime.sh b/scripts/tests/test-minikube-t2-proxy-runtime.sh
new file mode 100644
index 000000000..6d8d71764
--- /dev/null
+++ b/scripts/tests/test-minikube-t2-proxy-runtime.sh
@@ -0,0 +1,157 @@
+#!/usr/bin/env bash
+# Hermetic certifying-preflight and inherited-journey lease regressions.
+# shellcheck disable=SC2034
+set -euo pipefail
+ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
+source "$ROOT/scripts/tests/lib/minikube-fixture-repo.sh"
+tmp="$(mktemp -d)"
+cleanup() {
+ local status=$?
+ minikube_test_assert_host_unchanged || status=1
+ rm -rf "$tmp"
+ exit "$status"
+}
+minikube_test_fixture_repo_init "$ROOT" "$tmp"
+trap cleanup EXIT
+export T2_PROJECT_DIR="$MINIKUBE_TEST_PROJECT_DIR"
+export T2_BRANCH="$MINIKUBE_TEST_BRANCH" T2_HEAD="$MINIKUBE_TEST_HEAD"
+export T2_WORKTREE_ID="$MINIKUBE_TEST_WORKTREE_ID"
+export T2_PROFILE=fake T2_CONTEXT=fake T2_LOCK_ROOT="$tmp/locks"
+source "$ROOT/scripts/minikube/t2-common.sh"
+T2_IMAGE_MANIFEST="$tmp/manifest.json"
+T2_CONTROL_NAMESPACE=control-plane
+T2_REQUIRED_DEPLOYMENTS=control-plane/codex-llm-proxy
+T2_PLAN_MODE=false
+T2_BOOTSTRAP_REQUIRED=false
+t2_fail() { printf '%s: %s\n' "$1" "$2" >&2; return 1; }
+# Every runtime entry point is replaced; no cluster or container is contacted.
+t2_kc() {
+ case "$*" in
+ 'get deployments -A -o json') cat "$tmp/deployments.json" ;;
+ '-n control-plane get pods -l app=codex-llm-proxy -o json') cat "$tmp/pods.json" ;;
+ '-n control-plane exec proxy-1 -c codex-llm-proxy -- node -e '*) printf '%s' "$runtime_environment" ;;
+ *) printf 'unexpected cluster command\n' >&2; return 1 ;;
+ esac
+}
+t2_mk() {
+ [ "$*" = 'image ls --format=json' ] || return 1
+ cat "$tmp/inventory.json"
+}
+make_case() {
+ runtime_environment=true
+ python3 - "$tmp" "$1" <<'PY'
+import copy, json, sys
+from pathlib import Path
+root, case = Path(sys.argv[1]), sys.argv[2]
+base, other = 'sha256:' + 'a'*64, 'sha256:' + 'b'*64
+ref = 'clerum/codex-llm-proxy:test'
+digest_ref = 'ghcr.io/evenfire-ai/codex-llm-proxy@sha256:' + 'c'*64
+manifest = {'profile': 'fake', 'images': {ref: base}}
+container = {'name': 'codex-llm-proxy', 'image': ref, 'env': []}
+template = {'metadata': {}, 'spec': {'containers': [container]}}
+deployment = {'metadata': {'name': 'codex-llm-proxy', 'namespace': 'control-plane', 'generation': 1},
+ 'spec': {'replicas': 1, 'template': template},
+ 'status': {'observedGeneration': 1, 'updatedReplicas': 1, 'readyReplicas': 1, 'availableReplicas': 1}}
+pod = copy.deepcopy(template)
+pod['metadata'] = {'name': 'proxy-1', 'namespace': 'control-plane'}
+status = {'name': 'codex-llm-proxy', 'imageID': 'docker://' + base, 'ready': True, 'state': {'running': {'startedAt': '2026-01-01'}}}
+pod['status'] = {'containerStatuses': [status]}
+inventory = [{'id': base[7:], 'repoTags': ['docker.io/' + ref], 'repoDigests': [digest_ref]}]
+if case == 'fixture-image':
+ container['image'] = 'clerum/codex-approved-tools-proxy-e2e:test'
+ manifest['images'][container['image']] = other
+if case == 'fixture-env': container['env'] = [{'name': 'CODEX_APPROVED_TOOLS_TEST_ONLY', 'value': '1'}]
+if case == 'fixture-marker': template['metadata']['annotations'] = {'evenfire.ai/codex-tools-fixture-run': 'approved-tools-aabbccddeeff'}
+if case == 'old-fixture-pod': pod['spec']['containers'][0]['env'] = [{'name': 'CODEX_APPROVED_TOOLS_MINIKUBE_PROFILE', 'value': 'fake'}]
+if case == 'wrong-id': status['imageID'] = 'docker://' + other
+if case == 'unknown-id': status['imageID'] = 'unknown'
+if case == 'missing-id': del status['imageID']
+if case == 'missing-baseline': manifest['images'] = {}
+if case == 'missing-proxy': deployment = None
+if case == 'wrong-profile': manifest['profile'] = 'other'
+if case == 'missing-pods': pod = None
+if case == 'missing-inventory': inventory = []
+if case == 'ghcr':
+ ghcr = 'ghcr.io/evenfire-ai/codex-llm-proxy:v1'
+ manifest['images'][ghcr] = base
+ container['image'] = ghcr
+ pod['spec']['containers'][0]['image'] = ghcr
+ inventory[0]['repoTags'].append(ghcr)
+ status['imageID'] = 'docker-pullable://' + digest_ref
+if case == 'unknown-repo-digest': status['imageID'] = 'docker-pullable://' + digest_ref + 'd'
+for name, data in [('manifest', manifest), ('deployments', {'items': [deployment] if deployment else []}),
+ ('pods', {'items': [pod] if pod else []}), ('inventory', inventory)]:
+ (root / (name + '.json')).write_text(json.dumps(data))
+PY
+}
+for scenario in restored ghcr; do
+ make_case "$scenario"
+ t2_deployment_check
+ t2_proxy_runtime_check "$T2_DEPLOYMENT_JSON"
+done
+# Keep the production preflight integration under regression coverage.
+grep -Fq 't2_proxy_runtime_check "$T2_DEPLOYMENT_JSON"' "$ROOT/scripts/minikube/t2-preflight.sh"
+for scenario in fixture-image fixture-env fixture-marker old-fixture-pod wrong-id unknown-id missing-id missing-baseline missing-proxy wrong-profile missing-pods missing-inventory unknown-repo-digest runtime-fixture runtime-unknown; do
+ make_case "$scenario"
+ case "$scenario" in runtime-fixture) runtime_environment=false ;; runtime-unknown) runtime_environment='' ;; esac
+ if t2_proxy_runtime_check "$(cat "$tmp/deployments.json")" >"$tmp/result" 2>&1; then
+ printf 'unexpected PASS: %s\n' "$scenario" >&2; exit 1
+ fi
+ grep -q PROXY_RUNTIME_MISMATCH "$tmp/result"
+done
+# Exercise the actual journey functions without sourcing the orchestrator main.
+python3 - "$ROOT/scripts/minikube/t2.sh" "$tmp/journeys.sh" <<'PY'
+import sys
+from pathlib import Path
+source = Path(sys.argv[1]).read_text()
+functions = []
+for name in ('run_healthcheck_if_requested', 'run_playwright_if_requested'):
+ start = source.index(name + '() {')
+ end = source.index('\n}\n', start) + 3
+ functions.append(source[start:end])
+Path(sys.argv[2]).write_text('\n'.join(functions))
+PY
+source "$tmp/journeys.sh"
+export T2_BRANCH T2_HEAD T2_WORKTREE_ID
+export JOURNEY_COMMON="$ROOT/scripts/minikube/t2-common.sh"
+cat >"$tmp/child.sh" <<'CHILD'
+set -eo pipefail
+source "$JOURNEY_COMMON"
+t2_fail() { printf '%s\n' "$1" >&2; return 1; }
+[ "$T2_SKIP_LOCK" = true ]
+t2_lock_validate_inherited
+CHILD
+T2_HEALTHCHECK_COMMAND="bash '$tmp/child.sh'"
+T2_PLAYWRIGHT_COMMAND="$T2_HEALTHCHECK_COMMAND"
+T2_DEADLINE_RUNNER="$ROOT/scripts/minikube/run-with-deadline.mjs"
+T2_HEALTHCHECK_TIMEOUT_SECONDS=10
+T2_HEALTHCHECK_KILL_GRACE_SECONDS=1
+T2_HEALTHCHECK_REQUIRED=false
+T2_REQUIRE_PLAYWRIGHT=true
+t2_evidence_write() { :; }
+# Stable process metadata makes start-time verification hermetic even when
+# native sandboxed ps intentionally hides host process details.
+ps() {
+ case "$*" in *lstart=*) printf 'Tue Sep 15 01:00:00 2026\n' ;; *state=*) printf 'S\n' ;; *) return 1 ;; esac
+}
+export -f ps
+t2_lock_acquire
+run_healthcheck_if_requested
+run_playwright_if_requested
+cp "$T2_LOCK_DIR/owner.env" "$tmp/owner-original"
+for key in TOKEN REPOSITORY BRANCH HEAD PROFILE CONTEXT WORKTREE_ID LOCK_KEY PROCESS_START PID; do
+ python3 - "$tmp/owner-original" "$T2_LOCK_DIR/owner.env" "$key" <<'PY'
+import sys
+from pathlib import Path
+lines = Path(sys.argv[1]).read_text().splitlines()
+Path(sys.argv[2]).write_text('\n'.join(sys.argv[3] + '=wrong' if line.startswith(sys.argv[3] + '=') else line for line in lines) + '\n')
+PY
+ for journey in run_healthcheck_if_requested run_playwright_if_requested; do
+ if "$journey" >"$tmp/result" 2>&1; then
+ printf 'journey accepted mismatched %s\n' "$key" >&2; exit 1
+ fi
+ done
+done
+cp "$tmp/owner-original" "$T2_LOCK_DIR/owner.env"
+t2_lock_release 0
+printf 'PASS: proxy baseline and inherited journey lease regressions\n'
diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.json
index e4d00c946..5358e4c30 100644
--- a/tests/e2e/playwright/package-lock.json
+++ b/tests/e2e/playwright/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-playwright-tests",
- "version": "0.1.45",
+ "version": "0.1.46",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-playwright-tests",
- "version": "0.1.45",
+ "version": "0.1.46",
"devDependencies": {
"@playwright/test": "^1.50.0",
"@types/node": "^22.0.0",
diff --git a/tests/e2e/playwright/package.json b/tests/e2e/playwright/package.json
index 148018fcb..1c164ddab 100644
--- a/tests/e2e/playwright/package.json
+++ b/tests/e2e/playwright/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-playwright-tests",
- "version": "0.1.45",
+ "version": "0.1.46",
"private": true,
"description": "Playwright E2E tests for Control UI and Desktop App",
"scripts": {
diff --git a/tests/e2e/playwright/playwright.codex-approved-tools.config.ts b/tests/e2e/playwright/playwright.codex-approved-tools.config.ts
index ed7912761..58d8f1ec3 100644
--- a/tests/e2e/playwright/playwright.codex-approved-tools.config.ts
+++ b/tests/e2e/playwright/playwright.codex-approved-tools.config.ts
@@ -17,6 +17,7 @@ export default defineConfig({
baseURL: localUrl(required('CONTROL_UI_URL')),
screenshot: 'only-on-failure',
video: 'retain-on-failure',
- trace: 'retain-on-failure',
+ // Login inputs must not be persisted in Playwright action traces.
+ trace: 'off',
},
})