Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(llm): prepare measured admission and private QA identities
Alfredo Lopezd011177d6668
diff --git a/scripts/e2e/prepare-subscription-remaining-fixtures.gfs.mjs b/scripts/e2e/prepare-subscription-remaining-fixtures.gfs.mjsnew file mode 100644index 000000000..0c4bd7222--- /dev/null+++ b/scripts/e2e/prepare-subscription-remaining-fixtures.gfs.mjs@@ -0,0 +1,106 @@+// E2E_GUARDIAN_IPC_FLOW: data preparation only. Authentication is the existing+// in-pod PrivateCookieSession; it never leaves that process or advances UI.++/**+ * Self-contained so the existing seeder can include this exact function in its+ * in-pod bundle. `session.request` is the real Control API CookieGuard client:+ * JSON returns {status,json}; binary returns {status,bytes}, bounded by it.+ */+export async function prepareGfsImages({ session, userId, hostNamespace, hostRef,+ parentResourceId, folderName, files }) {+ const { createHash } = await import('node:crypto')+ const sha256 = bytes => createHash('sha256').update(bytes).digest('hex')+ const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i+ const dns = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/+ const rid = value => typeof value === 'string' ? value.replaceAll('-', '').toLowerCase() : ''+ const fail = code => { throw new Error(code) }+ if (typeof session?.request !== 'function' || !uuid.test(userId ?? '') ||+ !uuid.test(parentResourceId ?? '') || !dns.test(hostNamespace ?? '') || !dns.test(hostRef ?? '') ||+ !/^e2e-gfs-[a-z0-9-]{1,96}$/.test(folderName ?? '') || !Array.isArray(files) || files.length !== 2) {+ fail('GFS_PREPARE_INPUT_INVALID')+ }+ const names = new Set(), hashes = new Set()+ const inputs = files.map(file => {+ if (!file || !/^[a-f0-9-]{36}\.(?:png|jpeg)$/.test(file.name ?? '') ||+ !['image/png', 'image/jpeg'].includes(file.mimeType) ||+ typeof file.contentBase64 !== 'string' || file.contentBase64.length > 4 * 1024 * 1024 ||+ !/^[a-f0-9]{64}$/.test(file.sha256 ?? '')) fail('GFS_PREPARE_IMAGE_INVALID')+ const bytes = Buffer.from(file.contentBase64, 'base64')+ if (!bytes.length || bytes.length > 3 * 1024 * 1024 || bytes.toString('base64') !== file.contentBase64 ||+ sha256(bytes) !== file.sha256 ||+ (file.mimeType === 'image/png' && !bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) ||+ (file.mimeType === 'image/jpeg' && !bytes.subarray(0, 3).equals(Buffer.from([255,216,255])))) {+ fail('GFS_PREPARE_IMAGE_INVALID')+ }+ names.add(file.name); hashes.add(file.sha256)+ return { ...file, bytes }+ })+ if (names.size !== 2 || hashes.size !== 2) fail('GFS_PREPARE_IMAGES_NOT_INDEPENDENT')+ const drive = 'main'+ // Native Control API only: its CookieGuard proxy fixes drive=main and+ // delegates these operations to the actual gfsc writer. No direct gfsc URL.+ const resourcePath = resourceId => `/api/v1/gfs/proxy/v1/resources/${rid(resourceId)}`+ const unwrap = (response, status) => {+ if (response?.status !== status || response.json?.ok !== true ||+ !response.json.data || typeof response.json.data !== 'object' || Array.isArray(response.json.data)) {+ fail('GFS_PREPARE_API_REFUSED')+ }+ return response.json.data+ }+ const verifyResource = (value, expected) => {+ if (!uuid.test(value?.resourceId ?? '') || value.drive !== drive || value.rid !== rid(value.resourceId) ||+ value.gfsUri !== `gfs://${drive}/${value.rid}` || value.kind !== expected.kind || value.name !== expected.name ||+ rid(value.parentResourceId) !== rid(expected.parentResourceId) ||+ !Number.isSafeInteger(value.version) || value.version < 0 ||+ !Number.isSafeInteger(value.bytes) || value.bytes < 0) fail('GFS_PREPARE_RESOURCE_INVALID')+ return value+ }+ const folder = verifyResource(unwrap(await session.request({+ method: 'POST', path: `${resourcePath(parentResourceId)}/children`,+ body: { name: folderName, kind: 'directory' }, binary: false,+ }), 201), { name: folderName, kind: 'directory', parentResourceId })+ if (typeof folder.path !== 'string' || !folder.path.startsWith('/')) fail('GFS_PREPARE_FOLDER_PATH_INVALID')+ const folderNames = folder.path.split('/').filter(Boolean)+ if (!folderNames.length || folderNames.length > 8 || folderNames[folderNames.length - 1] !== folderName ||+ folderNames.some(name => name.length > 128 || /[\x00-\x1f/\\]/.test(name) || name === '.' || name === '..')) {+ fail('GFS_PREPARE_FOLDER_PATH_INVALID')+ }+ const hostSubject = `1st:${hostNamespace}/${hostRef}`+ const subjects = [{ type: 'user', id: userId }, { type: 'host', id: hostSubject }]+ const grant = await session.request({ method: 'PUT', path: '/api/v1/gfs/grants', binary: false,+ body: { drive, resourceId: folder.resourceId, subjects, permissions: ['read'], inherit: true } })+ if (grant?.status !== 200 || grant.json?.ok !== true || grant.json.count !== 2) fail('GFS_PREPARE_GRANT_REFUSED')+ const grants = await session.request({ method: 'GET',+ path: `/api/v1/gfs/grants?drive=${drive}&resourceId=${encodeURIComponent(folder.resourceId)}`, binary: false })+ if (grants?.status !== 200 || !Array.isArray(grants.json?.items)) fail('GFS_PREPARE_GRANT_WITNESS_MISSING')+ for (const subject of subjects) {+ const rows = grants.json.items.filter(row => rid(row.resourceId) === rid(folder.resourceId) && row.drive === drive &&+ row.subject?.type === subject.type && row.subject?.id === subject.id)+ if (rows.length !== 1 || rows[0].inherit !== true || !rows[0].permissions?.includes('read')) {+ fail('GFS_PREPARE_GRANT_WITNESS_MISSING')+ }+ }+ const prepared = []+ for (const file of inputs) {+ const resource = verifyResource(unwrap(await session.request({ method: 'POST',+ path: `${resourcePath(folder.resourceId)}/children`, binary: false,+ body: { name: file.name, kind: 'file', contentBase64: file.contentBase64 },+ }), 201), { name: file.name, kind: 'file', parentResourceId: folder.resourceId })+ if (resource.bytes !== file.bytes.length) fail('GFS_PREPARE_BYTE_COUNT_MISMATCH')+ const content = await session.request({ method: 'GET', path: `${resourcePath(resource.resourceId)}/content`, binary: true })+ if (content?.status !== 200 || !Buffer.isBuffer(content.bytes) || content.bytes.length !== file.bytes.length ||+ sha256(content.bytes) !== file.sha256) fail('GFS_PREPARE_CONTENT_MISMATCH')+ const fresh = verifyResource(unwrap(await session.request({ method: 'GET',+ path: resourcePath(resource.resourceId), binary: false,+ }), 200), { name: file.name, kind: 'file', parentResourceId: folder.resourceId })+ if (fresh.version !== resource.version || fresh.bytes !== resource.bytes || fresh.resourceId !== resource.resourceId) {+ fail('GFS_PREPARE_SOURCE_CHANGED')+ }+ prepared.push({ name: fresh.name, drive, pickerResourceId: fresh.resourceId,+ resourceId: fresh.rid, gfsUri: fresh.gfsUri, version: fresh.version, sizeBytes: fresh.bytes,+ mimeType: file.mimeType, imageSha256: file.sha256, width: 512, height: 512 })+ }+ return { folderNames, folderResourceId: folder.resourceId, hostSubject, userId, files: prepared,+ evidence: { createStatus: 201, contentStatus: 200, metadataStatus: 200, grantStatus: 200,+ grantSubjects: subjects, inheritedRead: true } }+}diff --git a/scripts/e2e/prepare-subscription-remaining-fixtures.mjs b/scripts/e2e/prepare-subscription-remaining-fixtures.mjsnew file mode 100644index 000000000..380419849--- /dev/null+++ b/scripts/e2e/prepare-subscription-remaining-fixtures.mjs@@ -0,0 +1,160 @@+// E2E_GUARDIAN_IPC_FLOW: scoped QA data and private frame preparation only.+// The renderer still logs in, selects, attaches, approves and sends visibly.+import { createHash, randomUUID } from 'node:crypto'+import fs from 'node:fs'+import path from 'node:path'+import { createRequire } from 'node:module'+import { validateRemainingFixture } from '../../desktop-app/test/e2e-playwright/subscriptionRemainingJourneysContract.ts'++const codec = createRequire(import.meta.url)('./fixtures/subscription-image-challenge.cjs')+const sha256 = bytes => createHash('sha256').update(bytes).digest('hex')+const MAX_FRAME_BYTES = 8 * 1024 * 1024+const fail = code => { throw new Error(code) }+const SUITES = ['tool-screenshot', 'gfs-image', 'admission-recovery']+const assetDirectory = (root, suite) => path.join(root, `remaining-${suite}`)+export const remainingAssetPath = (root, suite, name) => path.join(assetDirectory(root, suite), name)++function admitRun(admission, root) {+ if (admission?.mode === 'real') fail('REMAINING_REAL_SUBSCRIPTION_PREPARATION_REQUIRES_OPERATOR')+ if (!SUITES.includes(admission?.suiteId) || admission.mode !== 'fixture' ||+ !/^subscription-image-[a-f0-9]{12}$/.test(admission.runId ?? '') ||+ !/^[a-f0-9]{64}$/.test(admission.sourceManifestSha256 ?? '') ||+ !/^[a-z0-9][a-z0-9-]{0,62}$/.test(admission.profile ?? '') || admission.profile === 'clerum-test' ||+ /(^|[-_])(prod|production)([-_]|$)/i.test(admission.profile) ||+ admission.profile !== admission.context || !path.isAbsolute(root) || path.resolve(root) !== root ||+ !Array.isArray(admission.bindings) || admission.bindings.length !== 2) fail('REMAINING_PREPARATION_RUN_INVALID')+ const providers = admission.bindings.map(binding => binding.provider)+ if (new Set(providers).size !== 2 || !providers.includes('grok-subscription') || !providers.includes('codex-subscription')) {+ fail('REMAINING_PREPARATION_BINDINGS_INVALID')+ }+}++/** Generate actual native PNG/JPEG bytes; no code/answer is returned or persisted. */+export function createRemainingPixelAssets({ admission, runRoot }) {+ admitRun(admission, runRoot)+ if (admission.suiteId === 'admission-recovery') return []+ const assets = []+ for (const binding of admission.bindings) {+ const formats = admission.suiteId === 'gfs-image' ? ['png', 'jpeg'] : ['png']+ for (const format of formats) {+ const { bytes, width, height } = codec.tileChallengeImage(format, { requirePixels: true })+ const name = `${randomUUID()}.${format}`+ assets.push({ provider: binding.provider, name, mimeType: `image/${format}`,+ contentsBase64: bytes.toString('base64'), sha256: sha256(bytes), width, height })+ }+ }+ return assets+}++function canonicalReceipt(receipt) {+ if (!receipt || typeof receipt !== 'object' || !receipt.fixtures || typeof receipt.fixtures !== 'object') {+ fail('REMAINING_FIXTURE_RECEIPT_INVALID')+ }+ const fixtures = {}+ for (const [provider, raw] of Object.entries(receipt.fixtures ?? {})) {+ const common = { hostRef: raw.hostRef, podUid: raw.podUid, imageId: raw.imageId }+ if (receipt.suite === 'tool-screenshot') {+ fixtures[provider] = { ...common, hostImagePath: raw.hostImagePath,+ fixtureImagePath: raw.fixtureImagePath, imageSha256: raw.imageSha256,+ region: { x: raw.region?.x, y: raw.region?.y, w: raw.region?.w, h: raw.region?.h } }+ } else if (receipt.suite === 'gfs-image') {+ fixtures[provider] = { ...common, folderNames: raw.folderNames,+ files: (raw.files ?? []).map(file => ({ name: file.name, drive: file.drive,+ pickerResourceId: file.pickerResourceId, resourceId: file.resourceId, version: file.version,+ gfsUri: file.gfsUri, sizeBytes: file.sizeBytes, mimeType: file.mimeType,+ fixtureImagePath: file.fixtureImagePath, imageSha256: file.imageSha256, width: file.width, height: file.height })) }+ } else {+ fixtures[provider] = { ...common, controlApiPodUid: raw.controlApiPodUid,+ controlApiImageId: raw.controlApiImageId, maxInFlight: raw.maxInFlight,+ readDeadlineMs: raw.readDeadlineMs, pressure: { receiptFile: raw.pressure?.receiptFile },+ fallback: { provider: raw.fallback?.provider, modelId: raw.fallback?.modelId } }+ }+ }+ return { kind: receipt.kind, runId: receipt.runId, suite: receipt.suite,+ profile: receipt.profile, context: receipt.context, sourceManifestSha256: receipt.sourceManifestSha256,+ preparedAt: receipt.preparedAt, fixtures }+}++/** Combine real preparation results; the caller obtains identities from the runtime/API, never literals. */+export async function buildRemainingFixtureFrame({ admission, runRoot, fixtures, assets }) {+ admitRun(admission, runRoot)+ const receipt = canonicalReceipt({ kind: 'evenfire-subscription-remaining-journey-fixture-v1',+ runId: admission.runId, suite: admission.suiteId, profile: admission.profile, context: admission.context,+ sourceManifestSha256: admission.sourceManifestSha256, preparedAt: new Date().toISOString(), fixtures })+ const frame = { kind: 'evenfire-subscription-remaining-fixture-frame-v1', runId: admission.runId,+ suiteId: admission.suiteId, sourceManifestSha256: admission.sourceManifestSha256, receipt,+ assets: assets.map(({ provider, name, mimeType, contentsBase64, sha256: digest }) =>+ ({ provider, name, mimeType, contentsBase64, sha256: digest })) }+ await validateFrame(frame, admission, runRoot)+ return frame+}++async function validateFrame(frame, admission, root) {+ admitRun(admission, root)+ if (frame?.kind !== 'evenfire-subscription-remaining-fixture-frame-v1' || frame.runId !== admission.runId ||+ frame.suiteId !== admission.suiteId || frame.sourceManifestSha256 !== admission.sourceManifestSha256 ||+ Buffer.byteLength(JSON.stringify(frame)) > MAX_FRAME_BYTES || !Array.isArray(frame.assets)) {+ fail('REMAINING_FIXTURE_FRAME_INVALID')+ }+ const receipt = canonicalReceipt(frame.receipt)+ const receiptPath = path.join(root, `remaining-${admission.suiteId}.json`)+ validateRemainingFixture(receipt, { suite: admission.suiteId, fixtureReceiptPath: receiptPath },+ { ...admission, runRoot: root }, admission.sourceManifestSha256)+ const expected = []+ for (const binding of admission.bindings) {+ const fixture = receipt.fixtures[binding.provider]+ if (admission.suiteId === 'tool-screenshot') expected.push({ provider: binding.provider,+ fixtureImagePath: fixture.fixtureImagePath, imageSha256: fixture.imageSha256, mimeType: 'image/png' })+ else if (admission.suiteId === 'gfs-image') {+ for (const file of fixture.files) expected.push({ provider: binding.provider, ...file })+ }+ }+ if (frame.assets.length !== expected.length) fail('REMAINING_FIXTURE_ASSETS_MISSING')+ const decoded = [], names = new Set()+ for (const asset of frame.assets) {+ if (!/^[a-f0-9-]{36}\.(?:png|jpeg)$/.test(asset.name ?? '') || names.has(asset.name) ||+ typeof asset.contentsBase64 !== 'string' || asset.contentsBase64.length > 4 * 1024 * 1024 ||+ !/^[a-f0-9]{64}$/.test(asset.sha256 ?? '') || !['image/png', 'image/jpeg'].includes(asset.mimeType)) {+ fail('REMAINING_FIXTURE_ASSET_INVALID')+ }+ names.add(asset.name)+ const bytes = Buffer.from(asset.contentsBase64, 'base64')+ const filename = remainingAssetPath(root, admission.suiteId, asset.name)+ const matches = expected.filter(item => item.provider === asset.provider && item.fixtureImagePath === filename &&+ item.imageSha256 === asset.sha256 && item.mimeType === asset.mimeType)+ if (!bytes.length || bytes.length > 3 * 1024 * 1024 || bytes.toString('base64') !== asset.contentsBase64 ||+ sha256(bytes) !== asset.sha256 || matches.length !== 1 ||+ (asset.mimeType === 'image/png' && !bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) ||+ (asset.mimeType === 'image/jpeg' && !bytes.subarray(0, 3).equals(Buffer.from([255,216,255]))) ||+ (matches[0].sizeBytes !== undefined && matches[0].sizeBytes !== bytes.length)) fail('REMAINING_FIXTURE_ASSET_MISMATCH')+ // Decoding each received byte sequence rules out shape-only images and an+ // answer table keyed by file names, digests or PNG metadata.+ await codec.decodeTileChallenge(bytes)+ decoded.push({ filename, bytes })+ }+ return { receipt, receiptPath, decoded }+}++/** Runner-only materializer. It imports no CAPI, session, seeder or server modules. */+export async function acceptRemainingFixtureFrame(frame, { admission, runRoot }) {+ const { receipt, receiptPath, decoded } = await validateFrame(frame, admission, runRoot)+ const root = fs.lstatSync(runRoot)+ if (!root.isDirectory() || root.isSymbolicLink() || root.uid !== process.getuid?.() ||+ (root.mode & 0o077) !== 0 || fs.realpathSync(runRoot) !== runRoot) fail('REMAINING_FIXTURE_RUN_ROOT_INVALID')+ const directory = assetDirectory(runRoot, admission.suiteId)+ if (fs.existsSync(directory) || fs.existsSync(receiptPath)) fail('REMAINING_FIXTURE_ALREADY_PREPARED')+ fs.mkdirSync(directory, { mode: 0o700 })+ try {+ for (const { filename, bytes } of decoded) fs.writeFileSync(filename, bytes, { flag: 'wx', mode: 0o600 })+ fs.writeFileSync(receiptPath, JSON.stringify(receipt), { flag: 'wx', mode: 0o600 })+ } catch (error) {+ for (const { filename } of decoded) if (fs.existsSync(filename)) fs.unlinkSync(filename)+ if (fs.existsSync(receiptPath)) fs.unlinkSync(receiptPath)+ fs.rmdirSync(directory)+ throw error+ } finally {+ for (const item of decoded) item.bytes.fill(0)+ }+ return { receiptPath, assets: decoded.map(item => ({ path: item.filename })),+ suiteId: admission.suiteId, sourceManifestSha256: admission.sourceManifestSha256 }+}diff --git a/scripts/e2e/prepare-subscription-remaining-fixtures.prepare.mjs b/scripts/e2e/prepare-subscription-remaining-fixtures.prepare.mjsnew file mode 100644index 000000000..ebd31cf3b--- /dev/null+++ b/scripts/e2e/prepare-subscription-remaining-fixtures.prepare.mjs@@ -0,0 +1,68 @@+// E2E_GUARDIAN_IPC_FLOW: caller is Main's leased coordinator. The existing+// seeder owns login/session and server config; this prepares only QA assets.+import { createRemainingPixelAssets, buildRemainingFixtureFrame, remainingAssetPath } from './prepare-subscription-remaining-fixtures.mjs'+import { observeQaHostRuntime, prepareQaScreen } from './prepare-subscription-remaining-fixtures.runtime.mjs'++/**+ * `hostBindings` contains actual names/UIDs returned by the existing seeder.+ * `prepareGfs` dispatches its real prepare-gfs-images action in that same+ * authenticated process, implemented by prepare-subscription-remaining-fixtures.gfs.mjs.+ * `pressure` is the actual Main pressure publication/inspector result, not a+ * proposed policy. No credential, session, cookie or JWT enters this output.+ */+export async function prepareRemainingFixtures({ admission, runRoot, hostBindings, prepareGfs, pressure }) {+ const assets = createRemainingPixelAssets({ admission, runRoot })+ if (!Array.isArray(hostBindings) || hostBindings.length !== 2) throw new Error('REMAINING_PREPARE_ACTUAL_HOST_BINDINGS_REQUIRED')+ const fixtures = {}, evidence = {}+ for (const binding of admission.bindings) {+ const actual = hostBindings.filter(item => item.hostRef === binding.hostRef)+ if (actual.length !== 1) throw new Error('REMAINING_PREPARE_HOST_BINDING_AMBIGUOUS')+ const target = { context: admission.context, hostNamespace: actual[0].hostNamespace,+ hostRef: binding.hostRef, hostUid: actual[0].hostUid }+ const runtime = observeQaHostRuntime(target)+ const common = { hostRef: binding.hostRef, podUid: runtime.podUid, imageId: runtime.imageId }+ const selected = assets.filter(asset => asset.provider === binding.provider)+ if (admission.suiteId === 'tool-screenshot') {+ const asset = selected[0]+ const screen = await prepareQaScreen({ runtime, asset })+ fixtures[binding.provider] = { ...common, hostImagePath: screen.hostImagePath,+ fixtureImagePath: remainingAssetPath(runRoot, admission.suiteId, asset.name), imageSha256: asset.sha256,+ region: screen.region }+ evidence[binding.provider] = screen.evidence+ } else if (admission.suiteId === 'gfs-image') {+ if (typeof prepareGfs !== 'function') throw new Error('REMAINING_PREPARE_GFS_API_SESSION_REQUIRED')+ const result = await prepareGfs({ hostNamespace: runtime.hostNamespace, hostRef: binding.hostRef,+ folderName: `e2e-gfs-${admission.runId}-${binding.provider.startsWith('grok') ? 'grok' : 'codex'}`,+ files: selected.map(asset => ({ name: asset.name, mimeType: asset.mimeType,+ contentBase64: asset.contentsBase64, sha256: asset.sha256 })) })+ if (!Array.isArray(result?.files) || result.files.length !== 2) throw new Error('REMAINING_PREPARE_GFS_SOURCE_MISSING')+ const files = result.files.map(file => {+ const matches = selected.filter(asset => asset.name === file.name && asset.sha256 === file.imageSha256)+ if (matches.length !== 1) throw new Error('REMAINING_PREPARE_GFS_BYTES_MISMATCH')+ return { ...file, fixtureImagePath: remainingAssetPath(runRoot, admission.suiteId, matches[0].name) }+ })+ fixtures[binding.provider] = { ...common, folderNames: result.folderNames, files }+ evidence[binding.provider] = result.evidence+ } else {+ const other = admission.bindings.find(item => item.provider !== binding.provider)+ const configured = actual[0].fallback+ if (!pressure || pressure.profile !== admission.profile || pressure.context !== admission.context ||+ pressure.sourceManifestSha256 !== admission.sourceManifestSha256 ||+ !pressure.hostRefs?.includes(binding.hostRef) || configured?.provider !== other.provider ||+ configured?.modelId !== other.modelId ||+ !runtime.fallbacks.some(item => item.provider === configured.provider && item.model === configured.modelId)) {+ throw new Error('REMAINING_PREPARE_ACTUAL_PRESSURE_AND_FALLBACK_REQUIRED')+ }+ fixtures[binding.provider] = { ...common, controlApiPodUid: pressure.podUid,+ controlApiImageId: pressure.imageId, maxInFlight: pressure.maxInFlight,+ readDeadlineMs: pressure.readDeadlineMs, pressure: { receiptFile: pressure.receiptFile },+ fallback: { provider: configured.provider, modelId: configured.modelId } }+ }+ const fresh = observeQaHostRuntime(target)+ if (fresh.podUid !== runtime.podUid || fresh.imageId !== runtime.imageId || fresh.hostUid !== runtime.hostUid) {+ throw new Error('REMAINING_PREPARE_RUNTIME_CHANGED')+ }+ }+ const frame = await buildRemainingFixtureFrame({ admission, runRoot, fixtures, assets })+ return { frame, evidence }+}diff --git a/scripts/e2e/prepare-subscription-remaining-fixtures.runtime.mjs b/scripts/e2e/prepare-subscription-remaining-fixtures.runtime.mjsnew file mode 100644index 000000000..e1af812fd--- /dev/null+++ b/scripts/e2e/prepare-subscription-remaining-fixtures.runtime.mjs@@ -0,0 +1,117 @@+// E2E_GUARDIAN_IPC_FLOW: Main calls these under its verified branch mutation+// lease. Only fresh QA Host metadata and owned QA desktop data are accessed.+import { execFileSync } from 'node:child_process'+import { randomUUID } from 'node:crypto'+import { createRequire } from 'node:module'++const codec = createRequire(import.meta.url)('./fixtures/subscription-image-challenge.cjs')+const dns = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/+const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i+const fail = code => { throw new Error(code) }+function kubectl(context, args, input) {+ if (!dns.test(context) || context === 'clerum-test' || /(^|-)(prod|production)(-|$)/i.test(context)) fail('REMAINING_RUNTIME_CONTEXT_INVALID')+ return execFileSync('kubectl', [`--context=${context}`, '--request-timeout=15s', ...args],+ { input, encoding: 'utf8', timeout: 20_000, maxBuffer: 5 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'] })+}+const rows = text => text.trim().split('\n').filter(Boolean).map(line => line.split('\t'))+const digestId = raw => {+ const matched = /(?:^|[@/:])sha256:([a-f0-9]{64})$/.exec(raw ?? '')+ if (!matched) fail('REMAINING_RUNTIME_IMAGE_ID_MISSING')+ return `sha256:${matched[1]}`+}++/** No Ready, UID, image, deployment or pod is inferred from a planned name. */+export function observeQaHostRuntime({ context, hostNamespace, hostRef, hostUid }) {+ if (!dns.test(hostNamespace) || !dns.test(hostRef) || !uuid.test(hostUid ?? '')) fail('REMAINING_RUNTIME_HOST_INVALID')+ const host = kubectl(context, ['-n', hostNamespace, 'get', 'host', hostRef,+ '-o=jsonpath={.metadata.uid}{"\\n"}{.spec.desktop.x11}{"\\n"}{range .spec.llmPolicy.fallbacks[*]}{.provider}{"\\t"}{.model}{"\\n"}{end}']).trim().split('\n')+ if (host[0] !== hostUid) fail('REMAINING_RUNTIME_HOST_RECREATED')+ const deployments = rows(kubectl(context, ['-n', hostNamespace, 'get', 'deployment',+ '-o=jsonpath={range .items[*]}{.metadata.name}{"\\t"}{.metadata.uid}{"\\t"}{.metadata.ownerReferences[*].uid}{"\\t"}{.spec.replicas}{"\\t"}{.status.readyReplicas}{"\\n"}{end}']))+ .filter(row => row[2]?.split(' ').includes(hostUid))+ if (deployments.length !== 1 || deployments[0][3] !== '1' || deployments[0][4] !== '1') fail('REMAINING_RUNTIME_DEPLOYMENT_NOT_UNIQUE_READY')+ const replicaSets = rows(kubectl(context, ['-n', hostNamespace, 'get', 'replicaset',+ '-o=jsonpath={range .items[*]}{.metadata.uid}{"\\t"}{.metadata.ownerReferences[*].uid}{"\\n"}{end}']))+ .filter(row => row[1]?.split(' ').includes(deployments[0][1])).map(row => row[0])+ const pods = rows(kubectl(context, ['-n', hostNamespace, 'get', 'pod',+ '-o=jsonpath={range .items[*]}{.metadata.name}{"\\t"}{.metadata.uid}{"\\t"}{.metadata.ownerReferences[*].uid}{"\\t"}{.metadata.deletionTimestamp}{"\\t"}{.status.phase}{"\\t"}{range .status.containerStatuses[*]}{.name}{":"}{.ready}{":"}{.imageID}{" "}{end}{"\\n"}{end}']))+ .filter(row => row[2]?.split(' ').some(owner => replicaSets.includes(owner)) && !row[3] && row[4] === 'Running')+ if (pods.length !== 1 || !uuid.test(pods[0][1] ?? '')) fail('REMAINING_RUNTIME_POD_NOT_UNIQUE_READY')+ const containers = pods[0][5]?.trim().split(' ').filter(Boolean) ?? []+ if (containers.length !== 1) fail('REMAINING_RUNTIME_CONTAINER_AMBIGUOUS')+ const match = /^([^:]+):true:(.+)$/.exec(containers[0])+ if (!match) fail('REMAINING_RUNTIME_CONTAINER_NOT_READY')+ return { context, hostNamespace, hostRef, hostUid, deploymentUid: deployments[0][1],+ podName: pods[0][0], podUid: pods[0][1], containerName: match[1], imageId: digestId(match[2]),+ desktopX11: host[1] === 'true', fallbacks: host.slice(2).filter(Boolean).map(line => {+ const [provider, model] = line.split('\t')+ if (!provider || !model) fail('REMAINING_RUNTIME_FALLBACK_INVALID')+ return { provider, model }+ }) }+}++// This program touches only a unique QA PNG and its own ImageMagick viewer.+// It reads no environment, credentials, keychain, process command lines or logs.+export const SCREEN_PROGRAM = String.raw`+const fs = require('node:fs'), cp = require('node:child_process');+let chunks=[], count=0;+process.stdin.on('data',chunk=>{count+=chunk.length;if(count>4*1024*1024)throw Error('SCREEN_INPUT_BOUND');chunks.push(chunk)});+process.stdin.on('end',()=>{+ const input=JSON.parse(Buffer.concat(chunks).toString('utf8'));+ if(!/^\/tmp\/evenfire-qa-screen-[a-f0-9-]{36}\.png$/.test(input.filename)||!/^evenfire-qa-[a-f0-9-]{36}$/.test(input.title))throw Error('SCREEN_INPUT_INVALID');+ for(const command of ['scrot','import','display','xdotool'])cp.execFileSync('sh',['-c','command -v '+command],{timeout:5000,stdio:'pipe'});+ // The existing Dockerfile.desktop starts mcp-host and XFCE as abc. Other+ // images must fail this concrete runtime contract instead of guessing a UID.+ const uid=Number(cp.execFileSync('id',['-u','abc'],{encoding:'utf8',timeout:5000}).trim());+ const gid=Number(cp.execFileSync('id',['-g','abc'],{encoding:'utf8',timeout:5000}).trim());+ if(!Number.isSafeInteger(uid)||uid<=0||!Number.isSafeInteger(gid)||gid<=0)throw Error('SCREEN_RUNTIME_USER_INVALID');+ if(process.getuid()===0){process.setgroups([]);process.setgid(gid);process.setuid(uid)}+ if(process.getuid()!==uid||process.getgid()!==gid)throw Error('SCREEN_RUNTIME_USER_MISMATCH');+ let viewerPid=input.viewerPid, viewerStartTime=input.viewerStartTime;+ if(input.kind==='install'){+ const bytes=Buffer.from(input.contentsBase64,'base64');+ if(!bytes.length||bytes.length>3*1024*1024||bytes.toString('base64')!==input.contentsBase64)throw Error('SCREEN_IMAGE_INVALID');+ fs.writeFileSync(input.filename,bytes,{flag:'wx',mode:0o600});+ const viewer=cp.spawn('display',['-display',':1','-borderwidth','0','-geometry','512x512+64+64','-title',input.title,'-immutable',input.filename],{env:{DISPLAY:':1',HOME:'/config'},stdio:'ignore',detached:true});+ viewer.unref();viewerPid=viewer.pid;+ viewerStartTime=fs.readFileSync('/proc/'+viewerPid+'/stat','utf8').split(') ')[1].split(' ')[19];+ }else if(input.kind!=='capture')throw Error('SCREEN_ACTION_INVALID');+ if(!Number.isSafeInteger(viewerPid)||viewerPid<=0||fs.readFileSync('/proc/'+viewerPid+'/stat','utf8').split(') ')[1].split(' ')[19]!==viewerStartTime)throw Error('SCREEN_VIEWER_OWNERSHIP_CHANGED');+ const windowIds=cp.execFileSync('xdotool',['search','--sync','--onlyvisible','--name','^'+input.title+'$'],{env:{DISPLAY:':1'},encoding:'utf8',timeout:8000}).trim().split(/\s+/);+ if(windowIds.length!==1||!/^\d+$/.test(windowIds[0]))throw Error('SCREEN_WINDOW_AMBIGUOUS');+ const geometry=Object.fromEntries(cp.execFileSync('xdotool',['getwindowgeometry','--shell',windowIds[0]],{env:{DISPLAY:':1'},encoding:'utf8',timeout:5000}).trim().split('\n').map(line=>line.split('=')));+ const region={x:Number(geometry.X),y:Number(geometry.Y),w:Number(geometry.WIDTH),h:Number(geometry.HEIGHT)};+ if(!Number.isSafeInteger(region.x)||region.x<0||!Number.isSafeInteger(region.y)||region.y<0||region.w!==512||region.h!==512)throw Error('SCREEN_WINDOW_GEOMETRY_INVALID');+ const png=cp.execFileSync('import',['-display',':1','-window','root','-crop','512x512+'+region.x+'+'+region.y,'png:-'],{timeout:8000,maxBuffer:3*1024*1024});+ process.stdout.write(JSON.stringify({uid,gid,viewerPid,viewerStartTime,region,contentsBase64:png.toString('base64')}));+});`++/** Physical X11 pixels are decoded before a fixture receipt can be produced. */+export async function prepareQaScreen({ runtime, asset, deadlineMs = 20_000 }) {+ if (!Number.isSafeInteger(deadlineMs) || deadlineMs <= 0 || deadlineMs > 60_000) fail('SCREENSHOT_RUNTIME_DEADLINE_INVALID')+ if (!runtime.desktopX11 || asset.mimeType !== 'image/png') fail('SCREENSHOT_RUNTIME_X11_NOT_ENABLED')+ const filename = `/tmp/evenfire-qa-screen-${randomUUID()}.png`, title = `evenfire-qa-${randomUUID()}`+ const source = Buffer.from(asset.contentsBase64, 'base64')+ const expected = await codec.decodeTileChallenge(source)+ let viewer, latest, kind = 'install'+ const started = Date.now()+ do {+ const payload = { kind, filename, title, ...(kind === 'install' ? { contentsBase64: asset.contentsBase64 } : viewer) }+ latest = JSON.parse(kubectl(runtime.context, ['-n', runtime.hostNamespace, 'exec', '-i', runtime.podName,+ '-c', runtime.containerName, '--', 'node', '-e', SCREEN_PROGRAM], JSON.stringify(payload)))+ viewer = { viewerPid: latest.viewerPid, viewerStartTime: latest.viewerStartTime }+ let decoded+ try { decoded = await codec.decodeTileChallenge(Buffer.from(latest.contentsBase64, 'base64')) }+ catch { decoded = null } // A newly mapped window may not have drawn the pixels yet.+ if (decoded === expected) {+ const fresh = observeQaHostRuntime(runtime)+ if (fresh.podUid !== runtime.podUid || fresh.imageId !== runtime.imageId) fail('SCREENSHOT_RUNTIME_RECREATED')+ return { hostImagePath: filename, region: latest.region,+ evidence: { podUid: runtime.podUid, imageId: runtime.imageId, viewerPid: latest.viewerPid,+ viewerStartTime: latest.viewerStartTime, uid: latest.uid, gid: latest.gid, pixelChallengeMatched: true } }+ }+ kind = 'capture'+ // Each retry reads a real X11 frame; no fixed sleep advances readiness.+ } while (Date.now() - started < deadlineMs)+ fail('SCREENSHOT_RUNTIME_PIXELS_NOT_READY')+}diff --git a/scripts/e2e/prepare-subscription-remaining-fixtures.test.mjs b/scripts/e2e/prepare-subscription-remaining-fixtures.test.mjsnew file mode 100644index 000000000..f3472e686--- /dev/null+++ b/scripts/e2e/prepare-subscription-remaining-fixtures.test.mjs@@ -0,0 +1,140 @@+// Unit-only protocol and native-pixel controls. No fake session/Ready value in+// this file is runtime evidence or used by the physical preparer.+// E2E_GUARDIAN_IPC_FLOW: source contracts for the private QA preparation channel.+import assert from 'node:assert/strict'+import test from 'node:test'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import vm from 'node:vm'+import { createRemainingPixelAssets, buildRemainingFixtureFrame, acceptRemainingFixtureFrame, remainingAssetPath } from './prepare-subscription-remaining-fixtures.mjs'+import { prepareGfsImages } from './prepare-subscription-remaining-fixtures.gfs.mjs'+import { SCREEN_PROGRAM } from './prepare-subscription-remaining-fixtures.runtime.mjs'++const uid = '12345678-1234-4234-8234-123456789abc'+const digest = 'a'.repeat(64)+const admission = { runId: 'subscription-image-123456789abc', mode: 'fixture', suiteId: 'gfs-image',+ profile: 'qa-owned-unit', context: 'qa-owned-unit', sourceManifestSha256: digest,+ bindings: ['grok', 'codex'].map(kind => ({ provider: `${kind}-subscription`, hostRef: `qa-${kind}`,+ modelId: `${kind}-image`, modelLabel: `${kind} Image`, hostLabel: `QA ${kind}` })) }+const root = () => { const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'pr806-remaining-prep-unit-'))); fs.chmodSync(dir, 0o700); return dir }+const uuidAt = index => `00000000-0000-4000-8000-${String(index).padStart(12, '0')}`++function fixtureMap(runRoot, assets) {+ return Object.fromEntries(admission.bindings.map((binding, providerIndex) => [binding.provider, {+ hostRef: binding.hostRef, podUid: uid, imageId: `sha256:${digest}`,+ folderNames: ['e2e-gfs-unit'], files: assets.filter(asset => asset.provider === binding.provider).map((asset, index) => {+ const pickerResourceId = uuidAt(providerIndex * 10 + index + 1)+ return { name: asset.name, drive: 'main', pickerResourceId, resourceId: pickerResourceId.replaceAll('-', ''),+ gfsUri: `gfs://main/${pickerResourceId.replaceAll('-', '')}`, version: 1,+ sizeBytes: Buffer.from(asset.contentsBase64, 'base64').length, mimeType: asset.mimeType,+ fixtureImagePath: remainingAssetPath(runRoot, admission.suiteId, asset.name), imageSha256: asset.sha256, width: 512, height: 512 }+ })+ }]))+}++test('private frame materializes actual native pixels with no answer metadata', async () => {+ const runRoot = root()+ try {+ const assets = createRemainingPixelAssets({ admission, runRoot })+ assert.equal(assets.length, 4)+ assert.equal(new Set(assets.map(asset => asset.sha256)).size, 4)+ assert.ok(assets.every(asset => !('code' in asset)))+ const fixtures = fixtureMap(runRoot, assets)+ fixtures['grok-subscription'].unusedMetadata = 'must-not-be-published'+ const frame = await buildRemainingFixtureFrame({ admission, runRoot, fixtures, assets })+ assert.ok(!JSON.stringify(frame).includes('must-not-be-published'))+ const result = await acceptRemainingFixtureFrame(frame, { admission, runRoot })+ assert.equal(fs.statSync(result.receiptPath).mode & 0o777, 0o600)+ assert.equal(result.assets.length, 4)+ assert.ok(result.assets.every(item => (fs.statSync(item.path).mode & 0o777) === 0o600))+ await assert.rejects(acceptRemainingFixtureFrame(frame, { admission, runRoot }), /ALREADY_PREPARED/)+ } finally { fs.rmSync(runRoot, { recursive: true, force: true }) }+})++test('fixture source/run mismatch fails before any materialization', async () => {+ const runRoot = root()+ try {+ const assets = createRemainingPixelAssets({ admission, runRoot })+ const frame = await buildRemainingFixtureFrame({ admission, runRoot, fixtures: fixtureMap(runRoot, assets), assets })+ frame.sourceManifestSha256 = 'b'.repeat(64)+ await assert.rejects(acceptRemainingFixtureFrame(frame, { admission, runRoot }), /FRAME_INVALID/)+ assert.deepEqual(fs.readdirSync(runRoot), [])+ } finally { fs.rmSync(runRoot, { recursive: true, force: true }) }+})++test('changed bytes, duplicate assets and traversal cannot publish a receipt', async () => {+ const runRoot = root()+ try {+ const assets = createRemainingPixelAssets({ admission, runRoot })+ const original = await buildRemainingFixtureFrame({ admission, runRoot, fixtures: fixtureMap(runRoot, assets), assets })+ for (const change of [frame => { frame.assets[0].contentsBase64 = frame.assets[1].contentsBase64 },+ frame => { frame.assets[0].name = '../escape.png' }, frame => { frame.assets[0] = frame.assets[1] }]) {+ const frame = structuredClone(original); change(frame)+ await assert.rejects(acceptRemainingFixtureFrame(frame, { admission, runRoot }), /ASSET_/)+ assert.deepEqual(fs.readdirSync(runRoot), [])+ }+ } finally { fs.rmSync(runRoot, { recursive: true, force: true }) }+})++test('real subscription preparation requires its separate operator contract', () => {+ assert.throws(() => createRemainingPixelAssets({ admission: { ...admission, mode: 'real' }, runRoot: '/private/tmp/unit' }), /REQUIRES_OPERATOR/)+})++function apiSession({ inputs, denial, changedContent, missingGrant } = {}) {+ const calls = [], folderId = uuidAt(99), resources = new Map()+ let fileIndex = 0+ const view = (id, name, kind, bytes) => ({ resourceId: id, rid: id.replaceAll('-', ''), drive: 'main',+ gfsUri: `gfs://main/${id.replaceAll('-', '')}`, parentResourceId: kind === 'directory' ? uid : folderId,+ name, kind, bytes, version: 1, path: kind === 'directory' ? '/seeded-parent/e2e-gfs-unit' : `/seeded-parent/e2e-gfs-unit/${name}` })+ return { calls, request: async input => {+ calls.push(input)+ if (denial === calls.length) return { status: 403, json: { error: 'forbidden' } }+ if (input.method === 'PUT') return { status: 200, json: { ok: true, count: 2 } }+ if (input.path.startsWith('/api/v1/gfs/grants?')) return { status: 200, json: { items: missingGrant ? [] : [+ { drive: 'main', resourceId: folderId, subject: { type: 'user', id: uid }, permissions: ['read'], inherit: true },+ { drive: 'main', resourceId: folderId, subject: { type: 'host', id: '1st:mcp-host/qa-grok' }, permissions: ['read'], inherit: true },+ ] } }+ assert.ok(input.path.startsWith('/api/v1/gfs/proxy/v1/resources/'), 'creation/content must use the native CookieGuard proxy')+ if (input.method === 'POST' && input.body.kind === 'directory') return { status: 201, json: { ok: true, data: view(folderId, input.body.name, 'directory', 0) } }+ if (input.method === 'POST') {+ const selected = inputs[fileIndex++], id = uuidAt(fileIndex)+ assert.equal(input.body.contentBase64, selected.contentBase64)+ const data = view(id, selected.name, 'file', Buffer.from(selected.contentBase64, 'base64').length)+ resources.set(data.rid, { data, bytes: Buffer.from(selected.contentBase64, 'base64') })+ return { status: 201, json: { ok: true, data } }+ }+ const selected = resources.get(input.path.split('/')[7])+ if (input.binary) return { status: 200, bytes: changedContent ? Buffer.from('changed unit bytes') : selected.bytes }+ return { status: 200, json: { ok: true, data: selected.data } }+ } }+}+function gfsInput(session, assets) {+ return { session, userId: uid, hostNamespace: 'mcp-host', hostRef: 'qa-grok', parentResourceId: uid,+ folderName: 'e2e-gfs-unit', files: assets.filter(asset => asset.provider === 'grok-subscription').map(asset =>+ ({ name: asset.name, mimeType: asset.mimeType, contentBase64: asset.contentsBase64, sha256: asset.sha256 })) }+}+test('real GFS preparation contract uses create/grant/content/metadata and preserves UUID/rid', async () => {+ const assets = createRemainingPixelAssets({ admission, runRoot: '/private/tmp/unit' })+ const inputs = gfsInput(null, assets).files, session = apiSession({ inputs })+ const result = await prepareGfsImages(gfsInput(session, assets))+ assert.equal(result.files.length, 2)+ assert.deepEqual(result.folderNames, ['seeded-parent', 'e2e-gfs-unit'])+ assert.ok(result.files.every(file => file.pickerResourceId.replaceAll('-', '') === file.resourceId))+ assert.deepEqual(session.calls.filter(call => call.method === 'PUT')[0].body.subjects,+ [{ type: 'user', id: uid }, { type: 'host', id: '1st:mcp-host/qa-grok' }])+ assert.ok(!('session' in result))+ const callable = new Function(`return (${prepareGfsImages.toString()})`)()+ const isolated = apiSession({ inputs })+ const bundledResult = await callable(gfsInput(isolated, assets))+ assert.deepEqual(bundledResult.files, result.files, 'seeder bundle function must execute without captured helpers')+})+test('GFS refusal or wrong read-back bytes cannot produce preparation success', async () => {+ const assets = createRemainingPixelAssets({ admission, runRoot: '/private/tmp/unit' }), inputs = gfsInput(null, assets).files+ for (const options of [{ denial: 1 }, { missingGrant: true }, { changedContent: true }]) {+ await assert.rejects(prepareGfsImages(gfsInput(apiSession({ inputs, ...options }), assets)), /GFS_PREPARE_/)+ }+})+test('X11 preparation payload is valid JavaScript without executing a cluster operation', () => {+ assert.doesNotThrow(() => new vm.Script(SCREEN_PROGRAM))+})diff --git a/scripts/tests/lib/control-api-authorize-memory-companion.ts b/scripts/tests/lib/control-api-authorize-memory-companion.tsindex c0028f9cc..1b215fdbc 100644--- a/scripts/tests/lib/control-api-authorize-memory-companion.ts+++ b/scripts/tests/lib/control-api-authorize-memory-companion.ts@@ -111,7 +111,7 @@ export async function runCompanion(): Promise<void> {if (server.cwd !== process.cwd() || server.argv.length !== 2 || !server.argv[1]?.endsWith('/dist/main.js') ||flags.filter(flag => flag.startsWith('--max-old-space-size=')).length !== 1 || !flags.includes(`--max-old-space-size=${options.candidate.heapSizeMiB}`) || flags.filter(flag => flag.startsWith('--inspect=')).length !== 1 || !flags.includes(`--inspect=127.0.0.1:${options.inspectorPort}`) ||flags.some(flag => !/^--(?:max-old-space-size=\d+|inspect=127\.0\.0\.1:\d+|enable-source-maps)$/.test(flag))) throw new Error('actual server source/argv mismatch')- const expected = { maxInFlight: options.candidate.concurrency, readDeadlineMs: options.candidate.readDeadlineMs, workDeadlineMs: options.candidate.workDeadlineMs, closeGraceMs: options.candidate.closeGraceMs }+ const expected: Record<string, number> = { maxInFlight: options.candidate.concurrency, readDeadlineMs: options.candidate.readDeadlineMs, workDeadlineMs: options.candidate.workDeadlineMs, closeGraceMs: options.candidate.closeGraceMs }if (!Object.keys(expected).every(key => prod.policy[key] === expected[key]) || Object.keys(prod.policy).length !== 4) throw new Error('actual compiled admission policy differs from candidate')if (options.pressureOnly === true) {if (options.bindings.some((binding: any) => !/^[a-z0-9][a-z0-9-]{0,62}$/.test(binding.hostRef) || !/^[a-f0-9-]{36}$/.test(binding.hostUid))) throw new Error('pressure Host identity invalid')@@ -139,8 +139,9 @@ export async function runCompanion(): Promise<void> {if (!connection || connection.status !== 'connected' || connection.catalogStatus !== 'ready') throw new Error('actual connection unavailable')const model = await prod.db.pool.query('SELECT enabled, stale FROM grok_catalog_models WHERE connection_id = $1 AND model = $2', [connection.id, 'grok-4.6'])if (model.rows.length !== 1 || !model.rows[0].enabled || model.rows[0].stale) throw new Error('actual model not admitted')- const budget = await prod.db.pool.query('SELECT name FROM token_budgets WHERE id = $1', [binding.budgetId])- if (budget.rows.length !== 1 || !budget.rows[0].name.includes(options.fixtureRunId)) throw new Error('budget not fixture-owned')+ const budget = await prod.db.pool.query('SELECT name, enabled, scope, unit, currency, enforcement, limit_amount, max_task_amount, min_start_amount, period, timezone FROM token_budgets WHERE id = $1', [binding.budgetId])+ const rule = budget.rows[0], scope = rule?.scope+ if (budget.rows.length !== 1 || !rule.name.includes(options.fixtureRunId) || rule.enabled !== true || rule.unit !== 'tokens' || rule.currency !== null || rule.enforcement !== 'block' || Number(rule.limit_amount) !== 100 || Number(rule.max_task_amount) !== 200 || Number(rule.min_start_amount) !== 1 || rule.period !== 'daily' || rule.timezone !== 'UTC' || !scope || Object.keys(scope).length !== 3 || scope.host_ref?.length !== 1 || scope.host_ref[0] !== binding.hostRef || scope.provider?.length !== 1 || scope.provider[0] !== 'grok-subscription' || scope.model?.length !== 1 || scope.model[0] !== 'grok-4.6') throw new Error('actual owned danger-zone budget mismatch')const policyHash = prod.grok.computeGrokPolicyHash({ model: 'grok-4.6', catalogRevision: connection.catalogRevision, credentialRevision: connection.credentialRevision, connectionKey: binding.connectionKey })bindings.push({ hostRef: binding.hostRef, hostUid: binding.hostUid, connectionKey: binding.connectionKey, budgetId: binding.budgetId, connectionId: connection.id, policyRevision: connection.catalogRevision, policyHash })}@@ -166,8 +167,9 @@ export async function runCompanion(): Promise<void> {if (!input.name?.startsWith(`${options.runId}-`)) throw new Error('GFS filename not owned')headers.cookie = `${cookieName}=${options.cookie}`; route = `/api/v1/gfs/proxy/v1/resources/${options.gfsParentRid}/children`} else throw new Error('invalid route')+ if (options.pressureOnly === true) { headers['x-evenfire-qa-pressure-id'] = input.requestId; headers.connection = 'close' }const state: any = { input, acceptedWriteBytes: 0, maxWritableBytes: 0, closedByClient: false }- const request = http.request({ hostname: '127.0.0.1', port: prod.config.port, method: 'POST', path: route, headers }, response => {+ const request = http.request({ hostname: '127.0.0.1', port: prod.config.port, method: 'POST', path: route, headers, ...(options.pressureOnly === true ? { agent: false } : {}) }, response => {const chunks: Buffer[] = []; let bytes = 0response.on('data', chunk => { bytes += chunk.length; if (bytes > 65536) request.destroy(new Error('response bound')); else chunks.push(chunk) })response.on('end', async () => {@@ -194,7 +196,13 @@ export async function runCompanion(): Promise<void> {state.request = request; sockets.set(input.requestId, state)request.on('error', () => { sockets.delete(input.requestId); emit({ event: 'response', requestId: input.requestId, data: { transportClosed: true, acceptedWriteBytes: state.acceptedWriteBytes, closedByClient: state.closedByClient } }) })request.setTimeout(options.candidate.workDeadlineMs + options.candidate.readDeadlineMs + 5000, () => request.destroy(new Error('HTTP deadline')))- request.flushHeaders(); return { opened: true }+ request.flushHeaders()+ if (options.pressureOnly === true) {+ const wireHeader = (request as unknown as { _header?: string })._header+ if (typeof wireHeader !== 'string') throw new Error('actual pressure header unavailable')+ state.headerBytes = Buffer.byteLength(wireHeader, 'latin1')+ }+ return { opened: true }}async function download(rid: string) {const owned = created.get(rid); if (!owned) throw new Error('download not owned')@@ -247,7 +255,9 @@ export async function runCompanion(): Promise<void> {const owner = await inspector.owners()const incomplete = [...sockets.values()].map(state => ({ requestId: state.input.requestId, acceptedWriteBytes: state.acceptedWriteBytes, declaredBytes: state.input.length, closedByClient: state.closedByClient }))if (incomplete.some(value => value.acceptedWriteBytes >= value.declaredBytes)) throw new Error('pressure body is not incomplete')- return { ...owner, incompleteFixtureBodies: incomplete }+ const serverReads = options.pressureOnly === true ? await inspector.pressureReads([...sockets.values()].map(state => ({ requestId: state.input.requestId, headerBytes: state.headerBytes }))) : undefined+ if (serverReads && serverReads.pid !== owner.pid) throw new Error('pressure ownership/read observations changed process')+ return { ...owner, incompleteFixtureBodies: incomplete, serverReads }}if (input.kind === 'lock') {if (lockClient) throw new Error('lock already held')@@ -271,12 +281,13 @@ export async function runCompanion(): Promise<void> {if (input.kind === 'cleanup') return cleanup()throw new Error('unknown command')}- let header = Buffer.alloc(0), frame: Frame, remaining = 0+ let header = Buffer.alloc(0), frame: Frame | undefined, remaining = 0try {for await (const chunk of process.stdin) {let offset = 0while (offset < chunk.length) {if (remaining) {+ if (!frame) throw new Error('body frame was not initialized')const length = Math.min(remaining, chunk.length - offset), state = sockets.get(frame.requestId!)if (!state) throw new Error('request closed before streaming completed')if (options.pressureOnly === true && (state.acceptedWriteBytes + length > 65536 || state.acceptedWriteBytes + length >= state.input.length)) throw new Error('pressure body cannot complete')@@ -292,11 +303,11 @@ export async function runCompanion(): Promise<void> {if (header.length > 32768) throw new Error('header bound exceeded')offset = newline < 0 ? end : end + 1if (newline < 0) continue- frame = JSON.parse(header.toString()); header = Buffer.alloc(0)- if (frame.kind === 'write') {- if (!Number.isSafeInteger(frame.length) || frame.length! < 1 || frame.length! > 65536) throw new Error('body frame bound exceeded')- remaining = frame.length!- } else { try { emit({ callId: frame.callId, data: await command(frame) }) } catch { emit({ callId: frame.callId, failed: true, code: 'REAL_RUNTIME_COMMAND_FAILED' }) } }+ const parsed: Frame = JSON.parse(header.toString()); frame = parsed; header = Buffer.alloc(0)+ if (parsed.kind === 'write') {+ if (!Number.isSafeInteger(parsed.length) || parsed.length! < 1 || parsed.length! > 65536) throw new Error('body frame bound exceeded')+ remaining = parsed.length!+ } else { try { emit({ callId: parsed.callId, data: await command(parsed) }) } catch { emit({ callId: parsed.callId, failed: true, code: 'REAL_RUNTIME_COMMAND_FAILED' }) } }}}}diff --git a/scripts/tests/lib/control-api-authorize-memory-inspector.mjs b/scripts/tests/lib/control-api-authorize-memory-inspector.mjsindex df1d56c3c..1aadaf64f 100644--- a/scripts/tests/lib/control-api-authorize-memory-inspector.mjs+++ b/scripts/tests/lib/control-api-authorize-memory-inspector.mjs@@ -46,6 +46,38 @@ export class InspectorClient {return { kind: 'native-inspector-AuthorizeBodyAdmission.snapshot', ...value }} finally { await this.call('Runtime.releaseObjectGroup', { objectGroup: group }) }}+ async pressureReads(expected) {+ if (!Array.isArray(expected) || expected.some(item => !/^[a-z0-9-]{1,96}$/.test(item.requestId) || !Number.isSafeInteger(item.headerBytes) || item.headerBytes < 1)) throw new Error('Invalid pressure read projection')+ const group = 'qa-pressure-read-observation'+ try {+ const prototype = await this.call('Runtime.evaluate', { expression: "process.mainModule.require('node:http').IncomingMessage.prototype", objectGroup: group })+ if (prototype?.exceptionDetails || !prototype?.result?.objectId) throw new Error('Actual server incoming-message prototype unavailable')+ const objects = await this.call('Runtime.queryObjects', { prototypeObjectId: prototype.result.objectId, objectGroup: group })+ if (!objects?.objects?.objectId) throw new Error('Actual server request objects unavailable')+ // Only lengths leave the server. Headers (including authorization), the+ // socket and request body never enter an inspection result. Each pressure+ // request uses a fresh non-persistent socket, so bytesRead has no history.+ const declaration = `function(expected){+ const rows=[];+ for(const req of this){+ const id=req.headers?.['x-evenfire-qa-pressure-id'];+ const wanted=expected.find(item=>item.requestId===id);+ if(!wanted||req.method!=='POST'||req.url!=='/api/v1/mcp-host/llm/provider-attempts/authorize'||req.aborted||req.destroyed||req.complete)continue;+ let header=req.method+' '+req.url+' HTTP/'+req.httpVersion+'\\r\\n';+ for(let i=0;i<req.rawHeaders.length;i+=2)header+=req.rawHeaders[i]+': '+req.rawHeaders[i+1]+'\\r\\n';+ header+='\\r\\n';+ const headerBytes=Buffer.byteLength(header,'latin1'), socketBytesRead=req.socket?.bytesRead;+ rows.push({requestId:id,headerBytes,expectedHeaderBytes:wanted.headerBytes,socketBytesRead,receivedBodyBytes:Number.isSafeInteger(socketBytesRead)?socketBytesRead-headerBytes:null,declaredBytes:Number(req.headers['content-length']),complete:req.complete,aborted:req.aborted});+ }+ return {pid:process.pid,at:Date.now(),reads:rows};+ }`+ const reply = await this.call('Runtime.callFunctionOn', { objectId: objects.objects.objectId, functionDeclaration: declaration, arguments: [{ value: expected }], returnByValue: true })+ const value = reply?.result?.value+ if (reply?.exceptionDetails || !Number.isSafeInteger(value?.pid) || !Number.isSafeInteger(value.at) || !Array.isArray(value.reads)) throw new Error('Actual server body reception is unavailable')+ if (new Set(value.reads.map(item => item.requestId)).size !== value.reads.length || value.reads.some(item => item.headerBytes !== item.expectedHeaderBytes || !Number.isSafeInteger(item.receivedBodyBytes) || item.receivedBodyBytes < 0 || item.declaredBytes !== 35 * 1024 * 1024 - 4096 || item.receivedBodyBytes >= item.declaredBytes || item.complete !== false || item.aborted !== false)) throw new Error('Actual pressure connection framing is unknown')+ return { kind: 'native-inspector-IncomingMessage-fresh-socket-bytes', ...value }+ } finally { await this.call('Runtime.releaseObjectGroup', { objectGroup: group }) }+ }async forceGc() {const before = await this.snapshot()await this.call('HeapProfiler.enable')diff --git a/scripts/tests/lib/control-api-authorize-memory-seeder.ts b/scripts/tests/lib/control-api-authorize-memory-seeder.tsindex d23a75c76..5c32f0a44 100644--- a/scripts/tests/lib/control-api-authorize-memory-seeder.ts+++ b/scripts/tests/lib/control-api-authorize-memory-seeder.ts@@ -10,38 +10,85 @@ import { randomBytes, createHash } from 'node:crypto'type SeedOptions = { runId: string; hostNamespace: string; operatorUser: string; operatorPassword?: string; cookie?: string }const seedAssert = (condition: unknown, code: string) => { if (!condition) throw new Error(code) }+export function validateDesktopOperatorLink(controlAdminId: string, link: any) {+ const uuid = (value: unknown) => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value)+ seedAssert(uuid(controlAdminId) && link?.controlAdminId === controlAdminId && uuid(link.desktopUserId) && link.desktopUserId !== controlAdminId && link.gfsOperatorLinkStatus === 'active', 'SEED_DESKTOP_OPERATOR_LINK_UNPROVED')+ return { desktopUserId: link.desktopUserId, gfsOperatorLinkStatus: link.gfsOperatorLinkStatus, generation: link.generation, rowVersion: link.rowVersion }+}+/** Credentials remain private fields in the in-pod process. The public request+ * interface returns neither session headers nor the underlying cookie value.+ */+export class PrivateCookieSession {+ #port: number; #db: any; #bootstrap: string; #runId: string; #operator: string+ #password?: string; #cookie?: string+ constructor(config: any, db: any, options: SeedOptions) {+ this.#port = config.port; this.#db = db; this.#bootstrap = config.adminBootstrapUsername+ this.#runId = options.runId; this.#operator = options.operatorUser+ this.#password = options.operatorPassword; this.#cookie = options.cookie+ }+ async #raw(method: string, route: string, body?: unknown, binary = false, anonymous = false): Promise<any> {+ seedAssert(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && (route.startsWith('/api/v1/admin/') || route.startsWith('/api/v1/gfs/')), 'SEED_REQUEST_OUTSIDE_API_BOUNDARY')+ return new Promise((resolve, reject) => {+ const req = http.request({ hostname: '127.0.0.1', port: this.#port, method, path: route,+ headers: { 'content-type': 'application/json', ...(!anonymous && this.#cookie ? { cookie: `control_ui_admin_session=${this.#cookie}` } : {}) } }, res => {+ const chunks: Buffer[] = []; let bytes = 0+ res.on('data', chunk => { bytes += chunk.length; if (bytes > (binary ? 8 * 1024 * 1024 : 65536)) req.destroy(new Error('SEED_RESPONSE_BOUND')); else chunks.push(chunk) })+ res.on('end', () => { try { const data = Buffer.concat(chunks); resolve({ status: res.statusCode, headers: res.headers, ...(binary ? { bytes: data } : { json: bytes ? JSON.parse(data.toString()) : null }) }) } catch { reject(new Error('SEED_RESPONSE_INVALID')) } })+ })+ req.on('error', () => reject(new Error('SEED_HTTP_FAILED')))+ req.setTimeout(30000, () => req.destroy(new Error('SEED_HTTP_DEADLINE')))+ if (body) req.write(JSON.stringify(body)); req.end()+ })+ }+ #takeSession(response: any) {+ const value = (response.headers['set-cookie'] ?? []).find((item: string) => item.startsWith('control_ui_admin_session='))+ seedAssert(response.status === 200 && value, 'SEED_LOGIN_OR_SETUP_REFUSED')+ this.#cookie = value.split(';')[0].slice('control_ui_admin_session'.length + 1)+ }+ async authenticate() {+ let setupPerformed = false+ if (!this.#cookie) {+ seedAssert(typeof this.#password === 'string' && this.#password.length >= 8, 'SEED_PRIVATE_OPERATOR_MATERIAL_REQUIRED')+ const bootstrap = await this.#db.pool.query(`SELECT id::text, username, status, last_login_at FROM control_admin_users WHERE username = $1`, [this.#bootstrap])+ const active = await this.#db.pool.query("SELECT COUNT(*)::int AS count FROM control_admin_users WHERE status = 'active'")+ const eligible = bootstrap.rows.length === 1 && bootstrap.rows[0].status === 'active' && bootstrap.rows[0].last_login_at === null && active.rows[0].count === 1+ if (eligible) {+ seedAssert(this.#operator === `${this.#runId}-operator`, 'SEED_FIRST_RUN_OPERATOR_MUST_BE_OWNED')+ const collision = await this.#db.pool.query('SELECT COUNT(*)::int AS count FROM control_admin_users WHERE username = $1 OR lower(email) = lower($2)', [this.#operator, `${this.#runId}@example.invalid`])+ seedAssert(collision.rows[0].count === 0, 'SEED_INITIAL_OPERATOR_IDENTITY_COLLISION')+ this.#takeSession(await this.#raw('POST', '/api/v1/admin/auth/setup', { username: this.#operator, email: `${this.#runId}@example.invalid`, password: this.#password, seedDesktopPassword: true }, false, true))+ setupPerformed = true+ } else {+ this.#takeSession(await this.#raw('POST', '/api/v1/admin/auth/login', { username: this.#operator, password: this.#password }, false, true))+ }+ this.#password = undefined+ }+ const me = await this.#raw('GET', '/api/v1/admin/auth/me')+ seedAssert(me.status === 200 && me.json?.me?.username === this.#operator && me.json.me.role === 'admin', 'SEED_OPERATOR_IDENTITY_MISMATCH')+ const link = await this.#raw('GET', `/api/v1/admin/control-admins/${me.json.me.id}/gfs-operator-link`)+ seedAssert(link.status === 200, 'SEED_DESKTOP_OPERATOR_LINK_UNAVAILABLE')+ return { id: me.json.me.id, username: me.json.me.username, setupPerformed, ...validateDesktopOperatorLink(me.json.me.id, link.json) }+ }+ async request(input: { method: string; path: string; body?: unknown; binary?: boolean }) {+ const value = await this.#raw(input.method, input.path, input.body, input.binary === true)+ return input.binary === true ? { status: value.status, bytes: value.bytes } : { status: value.status, json: value.json }+ }+}export function assertQaBudget(budget: any, hostRef: string, name: string): void {const scope = budget.scopeseedAssert(budget.name === name && budget.enabled === true && budget.unit === 'tokens' && budget.currency === null && budget.enforcement === 'block' &&Number(budget.limit_amount) === 100 && Number(budget.max_task_amount) === 200 && Number(budget.min_start_amount) === 1 && budget.period === 'daily' && budget.timezone === 'UTC' &&scope && Object.keys(scope).length === 3 && scope.host_ref?.length === 1 && scope.host_ref[0] === hostRef && scope.provider?.length === 1 && scope.provider[0] === 'grok-subscription' && scope.model?.length === 1 && scope.model[0] === 'grok-4.6', 'QA_DANGER_ZONE_BUDGET_MISMATCH')}-export async function runSeedCompanion(): Promise<void> {+export async function runSeedCompanion(actions: { prepareGfsImages?: (input: any) => Promise<unknown> } = {}): Promise<void> {const output = process.stdout.write.bind(process.stdout)process.stdout.write = () => true; process.stderr.write = () => trueprocess.env.LOG_LEVEL = 'silent'const emit = (value: unknown) => output(JSON.stringify(value) + '\n')const require = createRequire(path.join(process.cwd(), 'package.json'))let prod: any, options: SeedOptions, phase = 'private-input', input = Buffer.alloc(0)- const cookieName = 'control_ui_admin_session'- async function request(method: string, route: string, body?: unknown, cookie = options.cookie): Promise<any> {- return new Promise((resolve, reject) => {- const req = http.request({ hostname: '127.0.0.1', port: prod.config.port, method, path: route,- headers: { 'content-type': 'application/json', ...(cookie ? { cookie: `${cookieName}=${cookie}` } : {}) } }, res => {- const chunks: Buffer[] = []; let bytes = 0- res.on('data', chunk => { bytes += chunk.length; if (bytes > 65536) req.destroy(new Error('SEED_RESPONSE_BOUND')); else chunks.push(chunk) })- res.on('end', () => { try { resolve({ status: res.statusCode, headers: res.headers, body: bytes ? JSON.parse(Buffer.concat(chunks).toString()) : null }) } catch { reject(new Error('SEED_RESPONSE_INVALID')) } })- })- req.on('error', () => reject(new Error('SEED_HTTP_FAILED')))- req.setTimeout(30000, () => req.destroy(new Error('SEED_HTTP_DEADLINE')))- if (body) req.write(JSON.stringify(body)); req.end()- })- }- function takeSession(response: any) {- const value = (response.headers['set-cookie'] ?? []).find((item: string) => item.startsWith(`${cookieName}=`))- seedAssert(response.status === 200 && value, 'SEED_LOGIN_OR_SETUP_REFUSED')- options.cookie = value.split(';')[0].slice(cookieName.length + 1)- }+ let session: PrivateCookieSession+ async function request(method: string, route: string, body?: unknown): Promise<any> { const value = await session.request({ method, path: route, body }); return { status: value.status, body: value.json } }async function prepare() {seedAssert(/^pr806-memory-[a-f0-9]{12}$/.test(options.runId), 'SEED_RUN_ID_INVALID')prod = { config: require('./dist/config.js').config, db: require('./dist/db.js'),@@ -50,24 +97,9 @@ export async function runSeedCompanion(): Promise<void> {seedAssert(prod.config.hostsNamespace === options.hostNamespace && prod.config.grokSubscriptionEnabled && prod.config.codexSubscriptionEnabled, 'SEED_PROVIDER_OR_NAMESPACE_MISMATCH')seedAssert(prod.config.subscriptionCatalogSyncCronEnabled === false && prod.config.llmCatalogSyncCronEnabled === false, 'SEED_VENDOR_CRON_MUST_BE_DISABLED')phase = 'operator-session'- let setupPerformed = false- if (!options.cookie) {- seedAssert(typeof options.operatorPassword === 'string' && options.operatorPassword.length >= 8, 'SEED_PRIVATE_OPERATOR_MATERIAL_REQUIRED')- const bootstrap = await prod.db.pool.query(`SELECT id::text, username, status, last_login_at FROM control_admin_users WHERE username = $1`, [prod.config.adminBootstrapUsername])- const active = await prod.db.pool.query("SELECT COUNT(*)::int AS count FROM control_admin_users WHERE status = 'active'")- const eligible = bootstrap.rows.length === 1 && bootstrap.rows[0].status === 'active' && bootstrap.rows[0].last_login_at === null && active.rows[0].count === 1- if (eligible) {- seedAssert(options.operatorUser === `${options.runId}-operator`, 'SEED_FIRST_RUN_OPERATOR_MUST_BE_OWNED')- takeSession(await request('POST', '/api/v1/admin/auth/setup', { username: options.operatorUser, email: `${options.runId}@example.invalid`, password: options.operatorPassword, seedDesktopPassword: false }, ''))- setupPerformed = true- } else {- // Only explicit canonical harness material authenticates an initialized- // account. No reset, alternate secret store or bootstrap retry occurs.- takeSession(await request('POST', '/api/v1/admin/auth/login', { username: options.operatorUser, password: options.operatorPassword }, ''))- }- }- const me = await request('GET', '/api/v1/admin/auth/me')- seedAssert(me.status === 200 && me.body?.me?.username === options.operatorUser && me.body.me.role === 'admin', 'SEED_OPERATOR_IDENTITY_MISMATCH')+ session = new PrivateCookieSession(prod.config, prod.db, options)+ const operator = await session.authenticate()+ options.operatorPassword = undefined; options.cookie = undefinedphase = 'context-binding'const context = await request('GET', '/api/v1/admin/contexts/context1')seedAssert(context.status === 200 && context.body?.metadata?.name === 'context1' && context.body.metadata.namespace === prod.config.contextsNamespace && /^[a-f0-9-]{36}$/.test(context.body.metadata.uid) &&@@ -120,13 +152,13 @@ export async function runSeedCompanion(): Promise<void> {let host = await request('GET', `/api/v1/admin/hosts/${hostRef}`), createdHost = falseif (host.status === 404) {host = await request('POST', '/api/v1/admin/hosts', { metadata: { name: hostRef, labels: { 'evenfire.io/qa-memory-run': options.runId } },- spec: { host: hostRef, contextRef: 'context1', model: { provider: 'grok-subscription', name: 'grok-4.6', connectionRef: connectionKey }, allowedModels: [{ provider: 'grok-subscription', model: 'grok-4.6' }] } })+ spec: { host: hostRef, contextRef: 'context1', desktop: { x11: true, browser: false }, model: { provider: 'grok-subscription', name: 'grok-4.6', connectionRef: connectionKey }, allowedModels: [{ provider: 'grok-subscription', model: 'grok-4.6' }] } })seedAssert(host.status === 201, 'SEED_HOST_API_REFUSED'); createdHost = true}const value = host.bodyseedAssert((host.status === 200 || host.status === 201) && value?.metadata?.name === hostRef && value.metadata.namespace === options.hostNamespace && /^[a-f0-9-]{36}$/.test(value.metadata.uid) &&value.metadata.labels?.['evenfire.io/qa-memory-run'] === options.runId && value.spec?.host === hostRef && value.spec.contextRef === 'context1' && value.spec.model?.provider === 'grok-subscription' && value.spec.model.name === 'grok-4.6' && value.spec.model.connectionRef === connectionKey &&- value.spec.allowedModels?.length === 1 && value.spec.allowedModels[0].provider === 'grok-subscription' && value.spec.allowedModels[0].model === 'grok-4.6', 'SEED_EXISTING_HOST_OWNER_OR_SPEC_CHANGED')+ value.spec.desktop?.x11 === true && value.spec.desktop.browser === false && value.spec.allowedModels?.length === 1 && value.spec.allowedModels[0].provider === 'grok-subscription' && value.spec.allowedModels[0].model === 'grok-4.6', 'SEED_EXISTING_HOST_OWNER_OR_SPEC_CHANGED')bindings.push({ hostRef, hostUid: value.metadata.uid, connectionKey, connectionId: connection.id, credentialRevision: connection.credentialRevision, catalogRevision: connection.catalogRevision, budgetId: budget.id, budgetName, reservationAmount: 200, hostCreateStatus: createdHost ? 201 : 200, catalogProjectionPublished: true })}phase = 'gfs-owned-directory'@@ -141,7 +173,8 @@ export async function runSeedCompanion(): Promise<void> {const parent = await request('GET', `/api/v1/gfs/proxy/v1/resources/${directory.body.data.rid}`)seedAssert(parent.status === 200 && parent.body?.data?.resourceId === directory.body.data.resourceId && parent.body.data.name === options.runId && parent.body.data.parentResourceId === root.body.resourceId, 'SEED_GFS_DIRECTORY_NOT_DURABLE')phase = 'complete'- return { fixtureCredentialState: 'opaque-qa-not-real-G8', upstreamDispatch: 'NOT_RUN', operatorUsername: me.body.me.username, operatorId: me.body.me.id, setupPerformed,+ return { fixtureCredentialState: 'opaque-qa-not-real-G8', upstreamDispatch: 'NOT_RUN', operatorUsername: operator.username, operatorId: operator.id, operatorDesktopUserId: operator.desktopUserId,+ operatorLink: { status: operator.gfsOperatorLinkStatus, generation: operator.generation, rowVersion: operator.rowVersion }, setupPerformed: operator.setupPerformed,context: { name: 'context1', namespace: context.body.metadata.namespace, uid: context.body.metadata.uid, resourceVersion: context.body.metadata.resourceVersion, mcpServers: [] }, bindings,gfs: { drive: 'main', rootRid: root.body.rid, rootResourceId: root.body.resourceId, parentRid: directory.body.data.rid, parentResourceId: directory.body.data.resourceId, name: options.runId, createStatus: 201, durableReadStatus: 200 },budgetCache: { definitionsTtlMs: 5000, strategy: 'benchmark-requires-new-actual-api-pod-before-first-authorize', resetHelperCalled: false },@@ -150,14 +183,23 @@ export async function runSeedCompanion(): Promise<void> {let handled = falsetry {for await (const chunk of process.stdin) {- input = Buffer.concat([input, chunk]); seedAssert(input.length <= 32768, 'SEED_PRIVATE_INPUT_BOUND')+ input = Buffer.concat([input, chunk]); seedAssert(input.length <= 4 * 1024 * 1024, 'SEED_PRIVATE_INPUT_BOUND')const end = input.indexOf(10); if (end < 0) continueseedAssert(end === input.length - 1, 'SEED_ONE_PRIVATE_COMMAND_REQUIRED')const frame = JSON.parse(input.toString()); input = Buffer.alloc(0)- seedAssert(frame.kind === 'prepare' && typeof frame.callId === 'string', 'SEED_PRIVATE_COMMAND_INVALID')+ seedAssert(['prepare', 'prepare-gfs-images'].includes(frame.kind) && typeof frame.callId === 'string', 'SEED_PRIVATE_COMMAND_INVALID')options = frame.optionshandled = true- try { emit({ callId: frame.callId, data: await prepare() }) }+ try {+ if (frame.kind === 'prepare') emit({ callId: frame.callId, data: await prepare() })+ else {+ seedAssert(actions.prepareGfsImages, 'GFS_FIXTURE_ACTION_NOT_INSTALLED')+ prod = { config: require('./dist/config.js').config, db: require('./dist/db.js') }+ seedAssert(/^pr806-memory-[a-f0-9]{12}$/.test(options.runId) && options.hostNamespace === prod.config.hostsNamespace, 'GFS_FIXTURE_BINDING_INVALID')+ session = new PrivateCookieSession(prod.config, prod.db, options); await session.authenticate()+ emit({ callId: frame.callId, data: await actions.prepareGfsImages!({ ...frame.input, session }) })+ }+ }catch (error: any) { emit({ callId: frame.callId, failed: true, code: /^[A-Z0-9_]+$/.test(error.message) ? error.message : 'SEED_REAL_RUNTIME_FAILED', phase }); process.exitCode = 1 }break}diff --git a/scripts/tests/measure-control-api-authorize-memory.mjs b/scripts/tests/measure-control-api-authorize-memory.mjsindex 59354ab9f..1aaef827b 100644--- a/scripts/tests/measure-control-api-authorize-memory.mjs+++ b/scripts/tests/measure-control-api-authorize-memory.mjs@@ -12,15 +12,40 @@ const NAMESPACE = 'control-plane', DEPLOYMENT = 'control-api', CONTAINER = 'contconst sleepPoll = ms => new Promise(resolve => setTimeout(resolve, ms))const assert = (condition, code) => { if (!condition) throw new Error(code) }const uuid = value => /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value)+function readOwnedJson(file, maxBytes = 65536) {+ const stat = fs.lstatSync(file)+ assert(stat.isFile() && !stat.isSymbolicLink() && stat.uid === process.getuid() && !(stat.mode & 0o077) && stat.size > 0 && stat.size <= maxBytes, 'OWNED_PRIVATE_JSON_REQUIRED')+ return JSON.parse(fs.readFileSync(file, 'utf8'))+}+export function validateFixtureReceipt(record, binding) {+ const value = record.fixtures+ assert(record.kind === 'control-api-authorize-memory-fixtures.v1' && record.status === 'complete' && record.producer?.code === 0 && !record.producer.signal &&+ record.options?.profile === binding.profile && record.options.context === binding.context && record.options.runId === binding.runId && record.options.hostNamespace === binding.hostNamespace &&+ /^[a-f0-9]{40}$/.test(record.source?.head ?? '') && /^[a-f0-9]{40}$/.test(record.source.worktreeId ?? '') && typeof record.source.clusterFingerprint === 'string' && record.source.clusterFingerprint.length > 0 &&+ Number.isFinite(Date.parse(record.startedAt)) && Date.parse(record.finishedAt) >= Date.parse(record.startedAt), 'COMPLETE_OWNED_FIXTURE_RECEIPT_REQUIRED')+ assert(value?.fixtureCredentialState === 'opaque-qa-not-real-G8' && value.upstreamDispatch === 'NOT_RUN' && value.vendorCronsDisabled === true &&+ value.context?.name === 'context1' && uuid(value.context.uid) && Array.isArray(value.context.mcpServers) && value.context.mcpServers.length === 0 && value.bindings?.length === 2 &&+ value.gfs?.drive === 'main' && value.gfs.name === binding.runId && value.gfs.createStatus === 201 && value.gfs.durableReadStatus === 200 && /^[a-f0-9]{32}$/.test(value.gfs.parentRid ?? '') && uuid(value.gfs.parentResourceId), 'REAL_QA_FIXTURE_STATE_REQUIRED')+ const refs = ['pr806-memory-grok-host', 'pr806-memory-grok-host-2']+ const hosts = value.bindings.map((item, index) => {+ assert(item.hostRef === refs[index] && uuid(item.hostUid) && uuid(item.budgetId) && uuid(item.connectionId) && item.connectionKey === `${binding.runId}-grok-${index + 1}` &&+ item.credentialRevision === 1 && item.catalogRevision === 1 && item.reservationAmount === 200 && item.catalogProjectionPublished === true, 'FIXTURE_HOST_BINDING_INVALID')+ return { hostRef: item.hostRef, hostUid: item.hostUid, budgetId: item.budgetId, connectionKey: item.connectionKey, connectionId: item.connectionId }+ })+ assert(new Set(hosts.map(item => item.budgetId)).size === 2 && typeof value.operatorUsername === 'string' && /^[A-Za-z0-9_.-]{3,64}$/.test(value.operatorUsername), 'FIXTURE_OPERATOR_OR_BUDGET_INVALID')+ if (value.operatorDesktopUserId !== undefined) assert(uuid(value.operatorDesktopUserId) && value.operatorDesktopUserId !== value.operatorId && value.operatorLink?.status === 'active', 'FIXTURE_DESKTOP_OPERATOR_ID_INVALID')+ return { worktreeId: record.source.worktreeId, clusterFingerprint: record.source.clusterFingerprint, hosts, parentRid: value.gfs.parentRid,+ parentResourceId: value.gfs.parentResourceId, operatorUser: value.operatorUsername, operatorDesktopUserId: value.operatorDesktopUserId, contextUid: value.context.uid, seedPodUid: record.podUid }+}export function parseOptions(args, env = process.env) {- const fields = {}, flags = new Set(['inspect-plan', 'include-legacy-gfs'])+ const fields = {}, flags = new Set(['inspect-plan', 'include-legacy-gfs', 'prepare-fixtures'])for (let index = 0; index < args.length; index++) {const key = args[index]; assert(/^--[a-z-]+$/.test(key), 'INVALID_ARGUMENT')const name = key.slice(2); assert(!(name in fields), 'DUPLICATE_ARGUMENT')if (flags.has(name)) fields[name] = trueelse { assert(args[index + 1] && !args[index + 1].startsWith('--'), 'MISSING_ARGUMENT_VALUE'); fields[name] = args[++index] }}- const allowed = ['config', 'profile', 'context', 'run-id', 'host-namespace', 'budget-ids', 'gfs-parent-rid', 'operator-user', 'heap-size-mib', 'concurrency', 'read-deadline-ms', 'work-deadline-ms', 'close-grace-ms', 'runs', 'cgroup-limit-mib', 'shape', 'report', 'prepare', 'inspector-port', ...flags]+ const allowed = ['config', 'profile', 'context', 'run-id', 'host-namespace', 'budget-ids', 'gfs-parent-rid', 'fixtures-receipt', 'operator-user', 'heap-size-mib', 'concurrency', 'read-deadline-ms', 'work-deadline-ms', 'close-grace-ms', 'runs', 'cgroup-limit-mib', 'shape', 'report', 'prepare', 'inspector-port', ...flags]for (const key of Object.keys(fields)) assert(allowed.includes(key), 'UNKNOWN_ARGUMENT')if (fields.config) {assert(Object.keys(fields).every(key => key === 'config' || flags.has(key)), 'CONFIG_ARGUMENT_CONFLICT')@@ -29,7 +54,7 @@ export function parseOptions(args, env = process.env) {assert(input.kind === 'control-api-authorize-memory-config.v1', 'CONFIG_KIND_INVALID')const converted = []for (const [key, value] of Object.entries(input.arguments)) { assert(allowed.includes(key) && key !== 'config', 'CONFIG_FIELD_INVALID'); converted.push(`--${key}`); if (!flags.has(key)) converted.push(String(value)); else assert(value === true, 'CONFIG_FLAG_INVALID') }- if (fields['inspect-plan'] && !converted.includes('--inspect-plan')) converted.push('--inspect-plan')+ for (const flag of flags) if (fields[flag] && !converted.includes(`--${flag}`)) converted.push(`--${flag}`)return parseOptions(converted, env)}const string = (key, value = fields[key]) => { assert(typeof value === 'string' && value.trim() === value && value.length > 0, `REQUIRED_${key.toUpperCase().replaceAll('-', '_')}`); return value }@@ -38,14 +63,21 @@ export function parseOptions(args, env = process.env) {assert(profile === context && /^[a-z0-9][a-z0-9-]{0,62}$/.test(profile) && profile !== 'clerum-test' && !/(^|[-_])(prod|production)([-_]|$)/i.test(profile), 'OWNED_DEVELOPMENT_CONTEXT_REQUIRED')const runId = string('run-id'); assert(/^pr806-memory-[a-f0-9]{12}$/.test(runId), 'RUN_ID_INVALID')const hostNamespace = string('host-namespace'); assert(/^[a-z0-9][a-z0-9-]{0,62}$/.test(hostNamespace), 'HOST_NAMESPACE_INVALID')- const budgets = string('budget-ids').split(','); assert(budgets.length === 2 && budgets.every(uuid), 'TWO_OWNED_BUDGET_IDS_REQUIRED')- const parentRid = string('gfs-parent-rid'); assert(/^[a-f0-9]{32}$/.test(parentRid) || uuid(parentRid), 'GFS_PARENT_RID_INVALID')+ const prepareFixtures = fields['prepare-fixtures'] === true+ assert(!prepareFixtures || (!fields['budget-ids'] && !fields['gfs-parent-rid'] && !fields['fixtures-receipt']), 'PREPARATION_CANNOT_REUSE_FIXTURE_DATA')+ const fixture = fields['fixtures-receipt'] ? validateFixtureReceipt(readOwnedJson(fields['fixtures-receipt']), { profile, context, runId, hostNamespace }) : undefined+ assert(!fixture || (!fields['budget-ids'] && !fields['gfs-parent-rid'] && !fields['operator-user']), 'FIXTURE_RECEIPT_ARGUMENT_CONFLICT')+ const budgets = prepareFixtures ? [] : fixture?.hosts.map(item => item.budgetId) ?? string('budget-ids').split(',')+ assert(prepareFixtures || (budgets.length === 2 && budgets.every(uuid) && new Set(budgets).size === 2), 'TWO_OWNED_BUDGET_IDS_REQUIRED')+ const parentRid = prepareFixtures ? undefined : fixture?.parentRid ?? string('gfs-parent-rid')+ assert(prepareFixtures || /^[a-f0-9]{32}$/.test(parentRid) || uuid(parentRid), 'GFS_PARENT_RID_INVALID')const shapes = string('shape').split(','); assert(new Set(shapes).size === shapes.length && shapes.every(value => SHAPES.includes(value)) && ['visual-35mib', 'worst-structure', 'wide-strings'].every(value => shapes.includes(value)), 'REPRESENTATIVE_SHAPES_REQUIRED')const report = string('report'); assert(path.isAbsolute(report) && path.extname(report) === '.json', 'ABSOLUTE_JSON_REPORT_REQUIRED')const prepare = string('prepare'); assert(['restart', 'build'].includes(prepare), 'PREPARE_MODE_INVALID')assert(fields['include-legacy-gfs'] === true, 'LEGACY_GFS_REQUIRED')const options = { profile, context, runId, hostNamespace, budgets, parentRid, shapes, report: path.resolve(report), prepare,- operatorUser: string('operator-user'), inspectorPort: integer('inspector-port', 1024, 65535), runs: integer('runs', 3, 3), cgroupLimitMiB: integer('cgroup-limit-mib', 768, 768), inspectPlan: fields['inspect-plan'] === true,+ operatorUser: prepareFixtures ? string('operator-user', fields['operator-user'] ?? `${runId}-operator`) : fixture?.operatorUser ?? string('operator-user'), prepareFixtures, fixtureBinding: fixture,+ inspectorPort: integer('inspector-port', 1024, 65535), runs: integer('runs', 3, 3), cgroupLimitMiB: integer('cgroup-limit-mib', 768, 768), inspectPlan: fields['inspect-plan'] === true,candidate: { heapSizeMiB: integer('heap-size-mib', 64, 512), concurrency: integer('concurrency', 1, 4), readDeadlineMs: integer('read-deadline-ms', 100, 60000), workDeadlineMs: integer('work-deadline-ms', 100, 120000), closeGraceMs: integer('close-grace-ms', 1, 10000) }, publicArguments: fields }assert(options.candidate.closeGraceMs < options.candidate.readDeadlineMs, 'CLOCK_ARGUMENT_RELATION_INVALID')return options@@ -61,6 +93,12 @@ async function command(binary, args, { env = process.env, timeoutMs = 180000, machild.once('close', (code, signal) => { clearTimeout(timer); if (code !== 0 || timedOut || size > maxBytes) reject(new Error(`COMMAND_FAILED_${binary.toUpperCase()}_${code ?? 'SIGNAL'}`)); else resolve(Buffer.concat(chunks).toString()) })})}+export function buildAuthorizeMemorySeederBundle(prepareGfsImages) {+ const source = fs.readFileSync(path.join(ROOT, 'scripts/tests/lib/control-api-authorize-memory-seeder.ts'), 'utf8')+ const action = prepareGfsImages ? `const gfsFixtureAction = ${prepareGfsImages.toString()};\n` : ''+ assert(!prepareGfsImages || typeof prepareGfsImages === 'function', 'GFS_FIXTURE_ACTION_SOURCE_REQUIRED')+ return stripTypeScriptTypes(source).replace(/^export /gm, '') + '\n' + action + (prepareGfsImages ? 'await runSeedCompanion({prepareGfsImages:gfsFixtureAction})\n' : 'await runSeedCompanion()\n')+}export function buildAuthorizeMemoryCompanionBundle() {const dir = path.join(ROOT, 'scripts/tests/lib')const inspector = fs.readFileSync(path.join(dir, 'control-api-authorize-memory-inspector.mjs'), 'utf8').replace(/^export /gm, '')@@ -101,6 +139,43 @@ export class Channel {async stop() { this.child.stdin.end(); const timer = setTimeout(() => { this.child.kill('SIGTERM'); setTimeout(() => this.child.kill('SIGKILL'), 1000).unref() }, 10000); const exit = await this.closed; clearTimeout(timer); assert(exit.code === 0 && !exit.signal, 'COMPANION_EXIT_NOT_ZERO'); return exit }}async function waitFor(check, predicate, timeoutMs, code) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const value = await check(); if (predicate(value)) return value; await sleepPoll(25) }; throw new Error(code) }+/** Source for the private Unix relay. The caller owns its verified kubectl exec+ * Channel, real Host bindings and loopback inspector lease; no material leaves+ * the in-pod signer. This fixture can only keep incomplete authorize requests.+ */+export async function openAuthorizeAdmissionPressure(channel, privateOptions) {+ const baseline = await channel.call({ kind: 'hello', options: { ...privateOptions, pressureOnly: true } })+ assert(baseline.pressureOnly === true && baseline.owner.inFlight === 0 && baseline.policy.maxInFlight === privateOptions.candidate.concurrency, 'PRESSURE_BASELINE_UNPROVED')+ const handles = []+ const zeroBusiness = async () => {+ const counts = await channel.call({ kind: 'counts' })+ assert(counts.total === 0 && counts.tickets === 0 && counts.reservationRows === 0, 'PRESSURE_REACHED_BUSINESS_WORK')+ return counts+ }+ const owners = async () => {+ const value = await channel.call({ kind: 'owners' })+ assert(value.pid === baseline.serverPid && value.instanceCount === 1 && value.serverReads?.pid === baseline.serverPid, 'PRESSURE_PROCESS_OR_READ_OBSERVATION_UNKNOWN')+ return { ...value, counts: await zeroBusiness() }+ }+ const release = async () => {+ for (const handle of handles) await channel.call({ kind: 'close', requestId: handle.requestId })+ await Promise.all(handles.map(handle => handle.result))+ const value = await waitFor(owners, value => value.inFlight === 0 && value.serverReads.reads.length === 0, baseline.policy.workDeadlineMs + baseline.policy.closeGraceMs + 5000, 'PRESSURE_RELEASE_NOT_QUIESCENT')+ handles.length = 0+ return value+ }+ return {+ async hold() {+ assert(handles.length === 0, 'PRESSURE_ALREADY_HELD')+ for (let index = 0; index < baseline.policy.maxInFlight; index++) {+ const handle = await channel.open({ requestId: `${privateOptions.runId}-pressure-${index + 1}`, route: 'authorize', hostRef: privateOptions.bindings[index % privateOptions.bindings.length].hostRef, length: 35 * MIB - 4096 })+ handles.push(handle); await channel.call({ kind: 'write', requestId: handle.requestId, length: 1 }, Buffer.from('{'))+ }+ return waitFor(owners, value => value.inFlight === baseline.policy.maxInFlight && value.serverReads.reads.length === handles.length && value.serverReads.reads.every(read => handles.some(handle => handle.requestId === read.requestId) && read.receivedBodyBytes > 0 && read.complete === false), baseline.policy.readDeadlineMs, 'AUTHENTICATED_SERVER_BODY_HOLD_UNOBSERVED')+ }, owners, release,+ async close() { if (handles.length) await release(); return channel.stop() },+ }+}export function validateReceipt(report) {assert(/^[a-f0-9]{40}$/.test(report.source?.head ?? '') && /^[a-f0-9]{64}$/.test(report.source?.policySha256 ?? '') && Number.isFinite(Date.parse(report.startedAt)) && Date.parse(report.finishedAt) >= Date.parse(report.startedAt), 'SOURCE_OR_REPORT_WINDOW_MISSING')assert(report.status === 'complete' && report.runs.length === 3 && report.restoration?.verified === true && report.restoration.healthStatus === 200, 'INCOMPLETE_REPORT')@@ -117,11 +192,19 @@ export function validateReceipt(report) {assert(run.causality?.excess?.status === 503 && run.causality.excess.acceptedWriteBytes === 0 && run.causality.coverage.parser === 0 && run.causality.coverage.authorizer === 0, 'PRE_PARSE_PROOF_MISSING')assert(run.samples.length >= 2 && run.baseline.cgroup.events.oom === 0 && run.baseline.cgroup.events.oom_kill === 0 && run.samples.every(sample => sample.server.applicationProcesses === 1 && sample.server.nodeProcessesIncludingAuxiliary === 2 && sample.cgroup.limit === 768 * MIB && sample.cgroup.peak * 1.25 <= sample.cgroup.limit && sample.cgroup.events.oom === run.baseline.cgroup.events.oom && sample.cgroup.events.oom_kill === run.baseline.cgroup.events.oom_kill), 'CGROUP_MARGIN_OR_OOM_FAILED')assert(run.combined.length === report.options.shapes.length * 2 && run.combined.every(phase => phase.authorizes.length === report.options.candidate.concurrency && phase.authorizes.every(row => row.status === 200 && row.durableRowVerified === true && row.reservationVerified === true && row.reservationAmount === 200) && phase.gfs.length === phase.gfsConcurrency && phase.gfs.every(row => row.status === 201 && row.verifiedDigest === row.expectedDigest)), 'COMBINED_WORKLOAD_INCOMPLETE')- assert(run.rejected.length === 2 && run.rejected.every(row => row.status === 413) && run.recovery?.status === 200 && run.health?.status === 200 && run.stalled?.status === 408 && run.closedTransaction?.physicallyQuiesced === true, 'LIFECYCLE_CONTROL_INCOMPLETE')+ assert(run.rejected.length === 2 && run.rejected.every(row => row.status === 413) && run.recovery?.status === 200 && run.recovery.durableRowVerified === true && run.recovery.reservationVerified === true && run.recovery.reservationAmount === 200 && run.health?.status === 200 && run.stalled?.status === 408 && run.closedTransaction?.physicallyHeldBeforeClose === true && run.closedTransaction.physicallyQuiesced === true, 'LIFECYCLE_CONTROL_INCOMPLETE')}return true}-async function run(options) {+export async function run(options, privateSeedOptions) {+ assert(privateSeedOptions === undefined || (privateSeedOptions && typeof privateSeedOptions === 'object' && !Array.isArray(privateSeedOptions) && Object.keys(privateSeedOptions).every(key => ['cookie', 'operatorPassword'].includes(key))), 'PRIVATE_SEED_ARGUMENT_INVALID')+ for (const field of ['cookie', 'operatorPassword', 'password', 'privateSeedOptions', 'dsn', 'privateKey']) assert(!(field in options) && !(field in (options.publicArguments ?? {})), 'PRIVATE_MATERIAL_CANNOT_ENTER_PUBLIC_OPTIONS')+ // The long-lived caller retains its original object in RAM across preparation,+ // visible Linux login and later measurement calls. Only these private values+ // cross the child stdin; the report/config/options never receive this object.+ const privateMaterial = privateSeedOptions === undefined+ ? { cookie: process.env.E2E_ADMIN_TOKEN, operatorPassword: process.env.CONTROL_API_MEMORY_OPERATOR_PASSWORD }+ : { cookie: privateSeedOptions.cookie, operatorPassword: privateSeedOptions.operatorPassword }const env = { ...process.env, MINIKUBE_PROFILE: options.profile, CONTROL_API_REAL_PG_CONTEXT: options.context }const kc = args => command('kubectl', ['--context', options.context, ...args], { env, timeoutMs: args.includes('rollout') ? 150000 : 15000 })const json = async args => JSON.parse(await kc(args))@@ -141,12 +224,36 @@ async function run(options) {const allowedReports = path.join(canonical, '.local-notes/infra/runs')assert(options.report.startsWith(allowedReports + path.sep) && !fs.existsSync(options.report), 'FRESH_CANONICAL_REPORT_REQUIRED')fs.mkdirSync(path.dirname(options.report), { recursive: true, mode: 0o700 }); assert(fs.realpathSync(path.dirname(options.report)) === path.dirname(options.report), 'REPORT_PARENT_SYMLINK')- const report = { kind: 'control-api-authorize-memory.v1', status: 'running', startedAt: new Date().toISOString(), source: { head, worktreeId, policySha256: sha256(fs.readFileSync(path.join(ROOT, 'control-api/src/middleware/llmProviderAttemptAdmissionLimits.ts'))), driverSha256: sha256(fs.readFileSync(fileURLToPath(import.meta.url))), companionBundleSha256: sha256(buildAuthorizeMemoryCompanionBundle()), clusterFingerprint: marker.clusterFingerprint, imagesGeneratedAt: manifest.generated }, options, runs: [], restoration: { verified: false } }+ if (options.fixtureBinding) assert(options.fixtureBinding.worktreeId === worktreeId && options.fixtureBinding.clusterFingerprint === marker.clusterFingerprint, 'FIXTURE_PROFILE_IDENTITY_CHANGED')+ const report = { kind: options.prepareFixtures ? 'control-api-authorize-memory-fixtures.v1' : 'control-api-authorize-memory.v1', status: 'running', startedAt: new Date().toISOString(), source: { head, worktreeId, policySha256: sha256(fs.readFileSync(path.join(ROOT, 'control-api/src/middleware/llmProviderAttemptAdmissionLimits.ts'))), driverSha256: sha256(fs.readFileSync(fileURLToPath(import.meta.url))), companionBundleSha256: sha256(buildAuthorizeMemoryCompanionBundle()), clusterFingerprint: marker.clusterFingerprint, imagesGeneratedAt: manifest.generated }, options, runs: [], restoration: { verified: false } }const save = () => { const temporary = options.report + '.next'; fs.writeFileSync(temporary, JSON.stringify(report, null, 2), { flag: 'wx', mode: 0o600 }); fs.renameSync(temporary, options.report) }const deployment = await json(['-n', NAMESPACE, 'get', 'deployment', DEPLOYMENT, '-o', 'json'])assert(deployment.spec.replicas === 1, 'SINGLE_APP_REPLICA_REQUIRED')const ci = deployment.spec.template.spec.containers.findIndex(container => container.name === CONTAINER)assert(ci >= 0 && !deployment.spec.template.spec.hostNetwork, 'OWNED_CONTAINER_REQUIRED')+ if (options.prepareFixtures) {+ const ready = (await json(['-n', NAMESPACE, 'get', 'pods', '-l', 'app=control-api', '-o', 'json'])).items.filter(pod => !pod.metadata.deletionTimestamp && pod.status.phase === 'Running' && pod.status.containerStatuses?.some(item => item.name === CONTAINER && item.ready))+ assert(ready.length === 1, 'SEED_READY_API_POD_AMBIGUOUS')+ const pod = ready[0], status = pod.status.containerStatuses.find(item => item.name === CONTAINER), spec = pod.spec.containers.find(item => item.name === CONTAINER)+ const replica = pod.metadata.ownerReferences?.find(item => item.kind === 'ReplicaSet' && item.controller === true)+ assert(replica && !pod.spec.hostNetwork && status.restartCount === 0, 'SEED_POD_IDENTITY_INVALID')+ const rs = await json(['-n', NAMESPACE, 'get', 'replicaset', replica.name, '-o', 'json'])+ assert(rs.metadata.ownerReferences?.some(item => item.kind === 'Deployment' && item.uid === deployment.metadata.uid && item.controller === true), 'SEED_DEPLOYMENT_OWNER_CHANGED')+ const imageId = status.imageID.match(/sha256:[a-f0-9]{64}$/)?.[0]+ assert(imageId && imageId === (manifest.images[spec.image] ?? manifest.images[`docker.io/${spec.image}`]) && manifest.sourceRevisions?.[spec.image] === head, 'SEED_IMAGE_SOURCE_MISMATCH')+ report.podUid = pod.metadata.uid; report.imageId = imageId; report.containerId = status.containerID+ report.source.seederBundleSha256 = sha256(buildAuthorizeMemorySeederBundle()); report.phase = 'real-fixture-preparation'; save()+ const child = spawn('kubectl', ['--context', options.context, '-n', NAMESPACE, 'exec', '-i', pod.metadata.name, '-c', CONTAINER, '--', 'env', '-u', 'NODE_OPTIONS', 'node', '--max-old-space-size=256', '--input-type=module', '-e', buildAuthorizeMemorySeederBundle()], { cwd: ROOT, env, stdio: ['pipe', 'pipe', 'pipe'] })+ const channel = new Channel(child, 120000)+ try {+ report.fixtures = await channel.call({ kind: 'prepare', options: { runId: options.runId, hostNamespace: options.hostNamespace, operatorUser: options.operatorUser, ...privateMaterial } })+ report.producer = await channel.stop(); report.finishedAt = new Date().toISOString(); report.status = 'complete'; report.phase = 'complete'+ validateFixtureReceipt(report, options); save(); return report+ } catch {+ report.status = 'failed'; report.failure = 'REAL_FIXTURE_PREPARATION_FAILED'; report.finishedAt = new Date().toISOString()+ await channel.stop().catch(() => {}); report.producer = channel.exit ?? { code: null, signal: 'unknown' }; save(); throw new Error('SEED_FAILED_REPORT_SAVED')+ }+ }const original = deployment.spec.template.spec.containers[ci].env?.find(item => item.name === 'NODE_OPTIONS')assert(!original?.valueFrom && (!original || /^--max-old-space-size=\d+$/.test(original.value)), 'ORIGINAL_NODE_OPTIONS_UNSUPPORTED')const candidateValue = `--max-old-space-size=${options.candidate.heapSizeMiB} --inspect=127.0.0.1:${options.inspectorPort}`@@ -180,6 +287,7 @@ async function run(options) {for (const [hi, hostRef] of ['pr806-memory-grok-host', 'pr806-memory-grok-host-2'].entries()) {const host = await json(['-n', options.hostNamespace, 'get', 'host', hostRef, '-o', 'json'])assert(host.spec.model?.provider === 'grok-subscription' && host.spec.model.connectionRef?.includes(options.runId), 'HOST_ASSIGNMENT_NOT_OWNED')+ if (options.fixtureBinding) assert(options.fixtureBinding.hosts[hi].hostUid === host.metadata.uid && options.fixtureBinding.hosts[hi].connectionKey === host.spec.model.connectionRef, 'FIXTURE_HOST_INCARCERATION_CHANGED')bindings.push({ hostRef, hostUid: host.metadata.uid, connectionKey: host.spec.model.connectionRef, budgetId: options.budgets[hi] })}const child = spawn('kubectl', ['--context', options.context, '-n', NAMESPACE, 'exec', '-i', pod.metadata.name, '-c', CONTAINER, '--', 'env', '-u', 'NODE_OPTIONS', 'node', '--max-old-space-size=64', '--input-type=module', '-e', buildAuthorizeMemoryCompanionBundle()], { cwd: ROOT, env, stdio: ['pipe', 'pipe', 'pipe'] })@@ -201,8 +309,7 @@ async function run(options) {}const sample = async () => { const value = await channel.call({ kind: 'sample' }); row.samples.push(value); assert(value.cgroup.peak * 1.25 <= value.cgroup.limit && value.cgroup.events.oom === row.baseline.cgroup.events.oom && value.cgroup.events.oom_kill === row.baseline.cgroup.events.oom_kill, 'MEMORY_MARGIN_OR_OOM_FAILED'); return value }try {- const credentials = { cookie: process.env.E2E_ADMIN_TOKEN, operatorPassword: process.env.CONTROL_API_MEMORY_OPERATOR_PASSWORD }- row.baseline = await channel.call({ kind: 'hello', options: { candidate: options.candidate, inspectorPort: options.inspectorPort, runId: trialId, hostNamespace: options.hostNamespace, fixtureRunId: options.runId, bindings, operatorUser: options.operatorUser, ...credentials, gfsParentRid: options.parentRid } })+ row.baseline = await channel.call({ kind: 'hello', options: { candidate: options.candidate, inspectorPort: options.inspectorPort, runId: trialId, hostNamespace: options.hostNamespace, fixtureRunId: options.runId, bindings, operatorUser: options.operatorUser, ...privateMaterial, gfsParentRid: options.parentRid } })row.bindings = row.baseline.bindingsassert(row.baseline.server.applicationProcesses === 1 && row.baseline.server.nodeProcessesIncludingAuxiliary === 2 && row.baseline.cgroup.events.oom === 0 && row.baseline.cgroup.events.oom_kill === 0 && row.baseline.auxiliary.inputHighWaterMark <= 65536, 'CLIENT_RETAINER_BOUND_INVALID')row.warmup = await execute(requestFixture('visual-35mib', row.bindings[0], true), row.bindings[0])@@ -219,7 +326,9 @@ async function run(options) {row.causality = { excess, coverage }assert((await channel.call({ kind: 'counts' })).total === 1, 'EXCESS_OR_HELD_REQUEST_AUTHORIZED')for (const handle of held) await channel.call({ kind: 'close', requestId: handle.requestId })- await channel.call({ kind: 'coverage-stop' }); await sleepPoll(100)+ await Promise.all(held.map(handle => handle.result))+ await waitFor(() => channel.call({ kind: 'owners' }), value => value.inFlight === 0, options.candidate.closeGraceMs + 5000, 'READ_OWNER_CALLBACK_DID_NOT_UNWIND')+ await channel.call({ kind: 'coverage-stop' })row.gc = await channel.call({ kind: 'gc' }); await sample()for (const shape of options.shapes) for (const gfsConcurrency of [1, 2]) {await channel.call({ kind: 'lock' })@@ -266,10 +375,10 @@ async function run(options) {}async function main() {const options = parseOptions(process.argv.slice(2))- if (options.inspectPlan) { process.stdout.write(JSON.stringify({ mode: 'read-only-plan', profile: options.profile, context: options.context, candidate: options.candidate, shapes: options.shapes, runs: 3, gfsConcurrency: [1, 2], physicalExecution: 'NOT_RUN' }) + '\n'); return }+ if (options.inspectPlan) { process.stdout.write(JSON.stringify({ mode: options.prepareFixtures ? 'read-only-fixtures-plan' : 'read-only-plan', profile: options.profile, context: options.context, candidate: options.candidate, shapes: options.shapes, runs: 3, gfsConcurrency: [1, 2], physicalExecution: 'NOT_RUN' }) + '\n'); return }if (process.env.T2_SKIP_LOCK !== 'true' || !process.env.T2_LOCK_TOKEN) {const common = (await command('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'])).trim(), dir = path.join(path.dirname(common), '.local-notes/infra/runs', options.runId)- fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); const config = path.join(dir, 'memory-configuration.json')+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); const config = path.join(dir, options.prepareFixtures ? 'memory-fixtures-configuration.json' : 'memory-benchmark-configuration.json')fs.writeFileSync(config, JSON.stringify({ kind: 'control-api-authorize-memory-config.v1', arguments: options.publicArguments }), { flag: 'wx', mode: 0o600 })await command('make', ['--no-print-directory', 'minikube-control-api-authorize-memory'], { env: { ...process.env, MINIKUBE_PROFILE: options.profile, CONTROL_API_REAL_PG_CONTEXT: options.context, CONTROL_API_MEMORY_CONFIG: config }, timeoutMs: 3 * (options.shapes.length * 2 + 2) * (120000 + options.candidate.readDeadlineMs + options.candidate.workDeadlineMs + 30000) + 600000, maxBytes: MIB })process.stdout.write('CONTROL_API_AUTHORIZE_MEMORY_COMPLETE\n'); returndiff --git a/scripts/tests/measure-control-api-authorize-memory.test.mjs b/scripts/tests/measure-control-api-authorize-memory.test.mjsindex d490d4257..cc690c2ca 100644--- a/scripts/tests/measure-control-api-authorize-memory.test.mjs+++ b/scripts/tests/measure-control-api-authorize-memory.test.mjs@@ -7,10 +7,11 @@ import os from 'node:os'import { spawnSync } from 'node:child_process'import { EventEmitter } from 'node:events'import { PassThrough } from 'node:stream'-import { parseOptions, validateReceipt, Channel } from './measure-control-api-authorize-memory.mjs'+import { parseOptions, validateReceipt, validateFixtureReceipt, buildAuthorizeMemorySeederBundle, buildAuthorizeMemoryCompanionBundle, openAuthorizeAdmissionPressure, Channel } from './measure-control-api-authorize-memory.mjs'import { buildAuthorizeFixture, buildRejectedFixture, buildGfsFixture, MIB } from './lib/control-api-authorize-memory-fixtures.mjs'import { InspectorClient, parseCgroup } from './lib/control-api-authorize-memory-inspector.mjs'import { ownedIssuedCleanupPlan } from './lib/control-api-authorize-memory-companion.ts'+import { assertQaBudget, PrivateCookieSession } from './lib/control-api-authorize-memory-seeder.ts'const require = createRequire(import.meta.url)const grok = require('../../packages/grok-provider-attempt-contract/index.cjs')@@ -124,7 +125,7 @@ function completeUnitReceipt() {gc:{gc:{forced:true,kind:'native-HeapProfiler.collectGarbage',before:{pid:1,at:1000},after:{pid:1,at:2000}}},causality:{excess:{status:503,acceptedWriteBytes:0},coverage:{parser:0,authorizer:0}},samples:[{server:{applicationProcesses:1,nodeProcessesIncludingAuxiliary:2},cgroup},{server:{applicationProcesses:1,nodeProcessesIncludingAuxiliary:2},cgroup}],combined:Array.from({length:6},(_,i)=>({cleanup:{lifecycle:'pg-issued-expiry-before-host-release',liveIssuedTickets:0,reservationRows:0},authorizes:[{status:200,durableRowVerified:true,reservationVerified:true,reservationAmount:200}],gfsConcurrency:i%2+1,gfs:Array.from({length:i%2+1},()=>({status:201,verifiedDigest:'unit-digest',expectedDigest:'unit-digest'}))})),- rejected:[{status:413},{status:413}],recovery:{status:200},health:{status:200},stalled:{status:408},closedTransaction:{physicallyQuiesced:true}+ rejected:[{status:413},{status:413}],recovery:{status:200,durableRowVerified:true,reservationVerified:true,reservationAmount:200},health:{status:200},stalled:{status:408},closedTransaction:{physicallyHeldBeforeClose:true,physicallyQuiesced:true}})) }}test('complete producer/status/report windows are mandatory and unknown/partial/failed observations cannot become green', () => {@@ -239,3 +240,89 @@ test('native owner projection requires unique actual singleton and releases inspsocket.missing=true;await assert.rejects(()=>inspector.owners(),/unavailable/)assert.equal(socket.commands.at(-1),'Runtime.releaseObjectGroup');inspector.close()})++function unitFixtureReceipt() {+ const runId='pr806-memory-123456abcdef',timestamp=new Date(1000).toISOString()+ return {kind:'control-api-authorize-memory-fixtures.v1',status:'complete',producer:{code:0},startedAt:timestamp,finishedAt:timestamp,+ options:{profile:'unit-owned',context:'unit-owned',runId,hostNamespace:'mcp-host'},source:{head:'a'.repeat(40),worktreeId:'b'.repeat(40),clusterFingerprint:'c'.repeat(64)},podUid:'11111111-1111-1111-1111-111111111111',+ fixtures:{fixtureCredentialState:'opaque-qa-not-real-G8',upstreamDispatch:'NOT_RUN',vendorCronsDisabled:true,operatorUsername:runId+'-operator',+ context:{name:'context1',uid:'22222222-2222-2222-2222-222222222222',mcpServers:[]},+ gfs:{drive:'main',name:runId,createStatus:201,durableReadStatus:200,parentRid:'3'.repeat(32),parentResourceId:'33333333-3333-3333-3333-333333333333'},+ bindings:['pr806-memory-grok-host','pr806-memory-grok-host-2'].map((hostRef,index)=>({hostRef,hostUid:`${index+4}`.repeat(8)+'-4444-4444-4444-444444444444',budgetId:`${index+6}`.repeat(8)+'-6666-6666-6666-666666666666',connectionId:`${index+8}`.repeat(8)+'-8888-8888-8888-888888888888',connectionKey:`${runId}-grok-${index+1}`,credentialRevision:1,catalogRevision:1,reservationAmount:200,catalogProjectionPublished:true}))}}+}+test('QA receipt requires native completed seed, exact owned bindings and vendor-free context; arbitrary fields cannot leak into driver options', () => {+ const receipt=unitFixtureReceipt(),binding=receipt.options+ receipt.fixtures.bindings[0].cookie='unit-cookie'+ const projected=validateFixtureReceipt(receipt,binding)+ assert.equal(projected.hosts.length,2);assert(!JSON.stringify(projected).includes('unit-cookie'))+ for(const change of [r=>r.producer.code=1,r=>r.fixtures.context.mcpServers=['unapproved'],r=>r.fixtures.bindings[0].hostUid=undefined,r=>r.fixtures.bindings[0].reservationAmount=0,r=>r.fixtures.vendorCronsDisabled=false,r=>r.fixtures.gfs.createStatus=200]) {+ const invalid=unitFixtureReceipt();change(invalid);assert.throws(()=>validateFixtureReceipt(invalid,binding))+ }+})+test('prepare CLI is read-only when requested and rejects reuse/manual data before any setup; receipt-derived flags preserve real identities', () => {+ const input=args()+ for(const flag of ['--budget-ids','--gfs-parent-rid','--operator-user'])input.splice(input.indexOf(flag),2)+ const options=parseOptions([...input,'--prepare-fixtures'],{})+ assert.equal(options.prepareFixtures,true);assert.equal(options.operatorUser,options.runId+'-operator');assert.deepEqual(options.budgets,[])+ assert.throws(()=>parseOptions([...args(),'--prepare-fixtures'],{}))+ const root=fs.mkdtempSync(path.join(os.tmpdir(),'pr806-unit-fixtures-'))+ try {+ const file=path.join(root,'fixture.json');fs.writeFileSync(file,JSON.stringify(unitFixtureReceipt()),{mode:0o600})+ const measured=parseOptions([...input,'--fixtures-receipt',file],{})+ assert.equal(measured.fixtureBinding.hosts.length,2);assert.equal(measured.budgets.length,2)+ const plan=spawnSync(process.execPath,[new URL('./measure-control-api-authorize-memory.mjs',import.meta.url).pathname,...input,'--prepare-fixtures','--inspect-plan'],{env:{PATH:path.dirname(process.execPath)},encoding:'utf8',timeout:5000})+ assert.equal(plan.status,0);assert.equal(JSON.parse(plan.stdout).mode,'read-only-fixtures-plan')+ fs.chmodSync(file,0o644);assert.throws(()=>parseOptions([...input,'--fixtures-receipt',file],{}))+ } finally {fs.rmSync(root,{recursive:true,force:true})}+})+test('actual QA budget definitions must reserve200 within100 danger zone; unbudgeted/high-headroom/wrong scopes fail', () => {+ const budget={name:'unit-budget',enabled:true,unit:'tokens',currency:null,enforcement:'block',limit_amount:100,max_task_amount:200,min_start_amount:1,period:'daily',timezone:'UTC',scope:{host_ref:['unit-host'],provider:['grok-subscription'],model:['grok-4.6']}}+ assertQaBudget(budget,'unit-host','unit-budget')+ for(const change of [b=>b.limit_amount=1000,b=>b.max_task_amount=null,b=>b.scope={},b=>b.scope.host_ref=['foreign'],b=>b.currency='USD']){const invalid=structuredClone(budget);change(invalid);assert.throws(()=>assertQaBudget(invalid,'unit-host','unit-budget'))}+ const session=new PrivateCookieSession({port:1,adminBootstrapUsername:'unit-bootstrap'},{},{runId:'unit',hostNamespace:'unit',operatorUser:'unit',cookie:'unit-cookie',operatorPassword:'unit-pw'})+ assert.equal(JSON.stringify(session),'{}')+})+test('complete companion/seeder bundles parse as native Node24 modules without executing production config or runtime', () => {+ for(const source of [buildAuthorizeMemoryCompanionBundle(),buildAuthorizeMemorySeederBundle(),buildAuthorizeMemorySeederBundle(async function prepareGfsImages(){return {unit:true}})]) {+ const parsed=spawnSync(process.execPath,['--input-type=module','--check'],{input:source,encoding:'utf8',timeout:5000})+ assert.equal(parsed.status,0,parsed.stderr)+ }+})+class UnitServerReadSocket extends UnitOwnerSocket {+ constructor(){super();this.mismatch=false;this.captured=false}+ send(raw){+ const request=JSON.parse(raw);this.commands.push(request.method);let result={}+ if(request.method==='Runtime.evaluate')result={result:{objectId:'unit-incoming-prototype'}}+ if(request.method==='Runtime.queryObjects')result={objects:{objectId:'unit-incoming-array'}}+ if(request.method==='Runtime.callFunctionOn'){+ const expected=request.params.arguments[0].value,id=expected[0].requestId+ const headers=['x-evenfire-qa-pressure-id',id,'content-length',String(35*MIB-4096)]+ const header='POST /api/v1/mcp-host/llm/provider-attempts/authorize HTTP/1.1\r\n'+headers[0]+': '+headers[1]+'\r\n'+headers[2]+': '+headers[3]+'\r\n\r\n'+ const actual=Buffer.byteLength(header,'latin1');expected[0].headerBytes=actual+(this.mismatch?1:0)+ const read={method:'POST',url:'/api/v1/mcp-host/llm/provider-attempts/authorize',httpVersion:'1.1',rawHeaders:headers,headers:{'x-evenfire-qa-pressure-id':id,'content-length':String(35*MIB-4096)},socket:{bytesRead:actual+1},complete:false,aborted:false,destroyed:false}+ const fn=new Function(`return (${request.params.functionDeclaration})`)()+ result={result:{value:fn.call([read],expected)}};this.captured=true+ }+ queueMicrotask(()=>this.dispatchEvent(new MessageEvent('message',{data:JSON.stringify({id:request.id,result})})))+ }+}+test('server body-byte projection executes its real framing logic and refuses mismatched/unknown header history', async () => {+ const socket=new UnitServerReadSocket(),inspector=new InspectorClient(socket)+ const result=await inspector.pressureReads([{requestId:'unit-pressure-1',headerBytes:1}])+ assert(socket.captured);assert.equal(result.reads[0].receivedBodyBytes,1);assert.equal(result.reads[0].complete,false)+ socket.mismatch=true;await assert.rejects(()=>inspector.pressureReads([{requestId:'unit-pressure-1',headerBytes:1}]),/framing/)+ assert.equal(socket.commands.at(-1),'Runtime.releaseObjectGroup');inspector.close()+})+test('private pressure adapter requires native server body reception and real zero-business closure before releasing relay', async () => {+ let held=false,resolveResult;const calls=[]+ const channel={async call(input){calls.push(input.kind)+ if(input.kind==='hello')return {pressureOnly:true,owner:{inFlight:0},serverPid:4,policy:{maxInFlight:1,readDeadlineMs:100,workDeadlineMs:100,closeGraceMs:1}}+ if(input.kind==='owners')return {pid:4,instanceCount:1,inFlight:held?1:0,serverReads:{pid:4,reads:held?[{requestId:'pr806-memory-123456abcdef-pressure-1',receivedBodyBytes:1,complete:false}]:[]}}+ if(input.kind==='counts')return {total:0,tickets:0,reservationRows:0}+ if(input.kind==='close'){held=false;resolveResult({transportClosed:true})}return {}},+ async open(input){held=true;return {requestId:input.requestId,result:new Promise(resolve=>resolveResult=resolve)}},async stop(){return {code:0}}}+ const fixture=await openAuthorizeAdmissionPressure(channel,{runId:'pr806-memory-123456abcdef',candidate:{concurrency:1},bindings:[{hostRef:'unit-host'}]})+ assert.equal((await fixture.hold()).serverReads.reads[0].receivedBodyBytes,1)+ assert.equal((await fixture.release()).inFlight,0);assert.equal((await fixture.close()).code,0)+ assert(!calls.includes('end'));assert(!calls.includes('cleanup'));assert(calls.includes('write'))+})