The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import assert from 'node:assert/strict'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import * as commandSdk from '@pulumi/command'
import * as gcpSdk from '@pulumi/gcp'
import { loadBuildConfig } from 'mbuild/config'
import { loadConfig } from 'mstage/config'
import { resolveScope } from 'mstage/scope'
import { componentTargets, deploymentComponents, type DeployedResource } from '../src/components.ts'
import { runnerFleetFrom } from '../src/stack-env.ts'
import { gcpRunnerProvider } from '../stack/providers/gcp/runners.ts'
import { resolveRunnerBinary } from '../stack/runner-binary.ts'
import { awsImages, gcpImages } from '../stack/image.ts'
import { gcpTarget, pulumiDeploy } from '../src/pulumi.ts'
import { gcpProgram, type ProgramInput } from '../pulumi/program.ts'
import type { StackOutputs } from '../stack/index.ts'
import { awsTarget } from '../src/sst.ts'
import { run } from '../src/run.ts'
import { mockRunnerStack } from './support/gcp-runner-stack.ts'
const environment = { MSTAGE_CONFIG: fileURLToPath(new URL('../../.mstage.config.example.json', import.meta.url)) }
const cwd = fileURLToPath(new URL('../..', import.meta.url))
const config = loadConfig({ cwd, environment })
const scope = resolveScope({ options: { stage: 'dev2' }, config, environment })
const app = scope.app!
const stage = scope.stage!
const prefix = `urn:pulumi:${stage}::${app}::`
const identity = { assertUsableFor: async () => {}, childEnvironment: async () => ({ env: {}, expiresAt: null }) }
const pin = (digit: string) => 'sha256:' + digit.repeat(64)
const oldImages = { api: pin('1'), proxy: pin('2'), 'otel-collector': pin('3'), 'registry-proxy': pin('4') }
const allImages = { ...oldImages, 'secret-server': pin('5') }
const runnerPins = { manifest: pin('6'), archive: pin('7') }
class Value {
constructor(readonly value: any) {}
apply(fn: (input: any) => any): Value {
return output(fn(this.value))
}
}
const output = (input: any): Value => (input instanceof Value ? input : new Value(input))
const unwrap = (input: any): any =>
input instanceof Value
? unwrap(input.value)
: Array.isArray(input)
? input.map(unwrap)
: input && typeof input === 'object'
? Object.fromEntries(Object.entries(input).map(([key, value]) => [key, unwrap(value)]))
: input
/** Capture real provider constructor calls, taking resource types from the installed SDK. */
const runnerState = (count: number, build = false) => {
const resources: (DeployedResource & { name: string; options: any })[] = []
const namespace = (sdk: object, path: string[] = []): any =>
new Proxy(function () {}, {
get: (_target, key) => namespace(sdk, [...path, String(key)]),
construct: (_target, [name, args, options]) => {
const type = path.reduce((value: any, key) => value[key], sdk).__pulumiType as string
const resource = { name, type, urn: `${prefix}${type}::${name}`, inputs: unwrap(args), options }
resources.push(resource)
return {
id: output(name),
name: output(args.name ?? name),
...(name === 'SecretServerRunnerRegistry' && { stdout: output('{"gcp_iit":{"12345":"runner-uuid"}}') }),
}
},
})
Object.assign(globalThis, {
$app: { name: app, stage },
$util: { output, secret: output },
$resolve: (items: any) => output(unwrap(items)),
$jsonStringify: (input: any) => output(JSON.stringify(unwrap(input))),
gcp: namespace(gcpSdk),
command: namespace(commandSdk),
})
const values = { RUNNERS: String(count) }
const binary = resolveRunnerBinary({
environment: build ? { RUNNER_ARTIFACT_SOURCE: 'build', RUNNER_ARTIFACT_REF: 'a'.repeat(40) } : {},
configRoot: config.root,
staging: { cloud: 'gcp', bucket: 'test-artifacts' },
})
gcpRunnerProvider({
project: scope.project!,
zone: scope.zone ?? `${scope.region}-a`,
artifactsBucket: 'test-artifacts',
volumePrefix: 'test-volume',
adminApiKey: 'synthetic-admin',
regionId: 'test-region',
dependsOn: [],
placement: { cloud: 'gcp', serviceAccount: output('[email protected]'), subnetwork: output('subnet') } as any,
})({
size: 'small',
rootDiskGb: 100,
nestedVirtualization: true,
binary,
fleet: runnerFleetFrom({ environment: values, app, stage }).map((slot) => ({ slot, token: 'synthetic-token' })),
apiUrl: 'https://api.example.test',
deploySecretFetch: () => ({ url: $util.output('https://fetch.example.test'), enrolledInstanceIds: $util.output(['12345']) }),
otlpUrl: 'https://otel.example.test',
registryProxyHost: null,
checkpointBucket: null,
environment: {},
secrets: {},
})
return resources
}
const apiState = (): DeployedResource[] => [
{ type: (gcpSdk.cloudrunv2.Service as any).__pulumiType, urn: `${prefix}gcp:cloudrunv2/service:Service::Api` },
{
type: (gcpSdk.cloudrunv2.Service as any).__pulumiType,
urn: `${prefix}gcp:cloudrunv2/service:Service::CloudAppWorker`,
},
{
type: (gcpSdk.cloudrunv2.Service as any).__pulumiType,
urn: `${prefix}gcp:cloudrunv2/service:Service::OtelCollector`,
},
]
test('component selection defaults to the full graph and rejects invalid or unsupported scopes', () => {
assert.equal(deploymentComponents({ home: 'aws' }), 'api+runner')
for (const value of ['', 'all', 'proxy', true, []])
assert.throws(() => deploymentComponents({ home: 'gcp', value }), /--components must/)
for (const value of ['api', 'runner']) {
assert.throws(() => deploymentComponents({ home: 'aws', value }), /AWS\/SST does not support/)
for (const intent of ['remove', 'refresh'] as const)
assert.throws(() => deploymentComponents({ home: 'gcp', value, intent }), /deploy and --diff only/)
}
})
test('an unhandled scoped component cannot select Runner targets', () => {
assert.throws(
() =>
componentTargets({
components: 'collector' as never,
app,
stage,
resources: runnerState(1),
environment: {},
}),
/Unsupported deployment component: collector/,
)
})
test('API-only updates target both the API and App worker without other services', () => {
const targets = componentTargets({ components: 'api', app, stage, resources: apiState(), environment: {} })
assert.deepEqual(targets, [
`${prefix}gcp:cloudrunv2/service:Service::Api`,
`${prefix}gcp:cloudrunv2/service:Service::CloudAppWorker`,
`${prefix}gcp:secretmanager/secretIamMember:SecretIamMember::ApiSecretAccess-*`,
])
})
for (const count of [1, 2])
test(`Runner targets come from actual provider identities (${count} hosts)`, () => {
const resources = runnerState(count)
const targets = componentTargets({
components: 'runner',
app,
stage,
resources,
environment: { RUNNERS: String(count) },
})
assert.deepEqual(
targets.slice(0, -1),
resources.filter((r) => r.type === 'gcp:osconfig/osPolicyAssignment:OsPolicyAssignment').map((r) => r.urn),
)
assert.ok(
targets.at(-1)?.endsWith('::RunnerArtifactsRead*'),
'the initially absent artifact grant must be targeted too',
)
assert.ok(targets.every((urn) => !urn.includes('compute/instance')))
})
test('build-mode policies wait directly for artifact access, then canary before fleet', () => {
const resources = runnerState(2, true)
const grant = resources.find((r) => r.name === 'RunnerArtifactsRead')!
const policies = resources.filter((r) => r.type === 'gcp:osconfig/osPolicyAssignment:OsPolicyAssignment')
assert.ok(grant, 'the production provider must create artifact access')
const targets = componentTargets({ components: 'runner', app, stage, resources, environment: { RUNNERS: '2' } })
assert.ok(grant.urn.startsWith(targets.at(-1)!.slice(0, -1)), 'the target must match the real grant resource type')
for (const policy of policies) {
assert.ok(policy.options.dependsOn.some((dependency: any) => unwrap(dependency.id) === grant.name))
assert.equal((policy.inputs as any).skipAwaitRollout, false)
}
assert.ok(policies[1]!.options.dependsOn.some((dependency: any) => unwrap(dependency.id) === policies[0]!.name))
})
test('Runner-only updates refuse fleet expansion, contraction and renamed membership', () => {
for (const [deployed, requested] of [
[1, 2],
[2, 1],
])
assert.throws(
() =>
componentTargets({
components: 'runner',
app,
stage,
resources: runnerState(deployed!),
environment: { RUNNERS: String(requested) },
}),
/full --components api\+runner/,
)
assert.throws(
() =>
componentTargets({
components: 'runner',
app,
stage,
resources: runnerState(1),
environment: { DEFAULT_RUNNER_NAME: 'renamed' },
}),
/full --components api\+runner/,
)
const resources = runnerState(1)
resources.find((r) => r.name === 'RunnerBinary')!.inputs!.instanceFilter!.inclusionLabels = []
assert.throws(
() => componentTargets({ components: 'runner', app, stage, resources, environment: {} }),
/full --components api\+runner/,
)
})
test('missing, deleted and foreign-stack workloads never become empty or full target sets', () => {
for (const resources of [
[],
apiState().filter((resource) => !resource.urn.endsWith('::CloudAppWorker')),
apiState().map((resource) =>
resource.urn.endsWith('::CloudAppWorker') ? { ...resource, delete: true } : resource,
),
apiState().map((resource) =>
resource.urn.endsWith('::CloudAppWorker')
? { ...resource, urn: resource.urn.replace(`:${stage}::`, ':foreign::') }
: resource,
),
apiState().map((r) => ({ ...r, delete: true })),
apiState().map((r) => ({ ...r, urn: r.urn.replace(`:${stage}::`, ':foreign::') })),
])
assert.throws(
() => componentTargets({ components: 'api', app, stage, resources, environment: {} }),
/full --components api\+runner/,
)
})
for (const components of ['api', 'runner', 'api+runner'] as const) {
for (const intent of ['diff', 'deploy'] as const)
test(`CLI forwards ${components} through the GCP adapter to ${intent}`, async () => {
const calls: { method: string; options: any }[] = []
const logs: string[] = []
const resources = [...apiState(), ...runnerState(1)]
const result = await run({
argv: ['--stage', stage, '--components', components, ...(intent === 'diff' ? ['--diff'] : [])],
environment,
cwd,
checkLogin: async () => 0,
log: (line) => logs.push(line),
fetchEnv: async () => ({ source: 'fixture', values: { PULUMI_CONFIG_PASSPHRASE: 'synthetic-passphrase' } }),
targetWith: async ({ config, scope }) =>
gcpTarget({
config,
scope,
identity,
backend: {} as any,
stateBucket: async () => 'test-state',
createStackWith: async (input) => {
assert.equal(input.selectOnly, components === 'api+runner' ? undefined : true)
return {
setAllConfig: async () => {},
exportStack: async () => ({ deployment: { resources } }),
preview: async (options) => {
calls.push({ method: 'diff', options })
},
up: async (options) => {
calls.push({ method: 'deploy', options })
},
destroy: async () => assert.fail('destroy'),
refresh: async () => assert.fail('refresh'),
}
},
}),
})
assert.equal(result, 0)
assert.equal(calls.length, 1)
assert.equal(calls[0]!.method, intent)
const actual = calls[0]!.options
if (components === 'api+runner') assert.equal(actual.target, undefined)
else {
assert.deepEqual(actual.target, componentTargets({ components, app, stage, resources, environment: {} }))
assert.equal(actual.targetDependents, false)
const discovery = resources.find((r) => r.urn.endsWith('::SecretServerRunnerRegistry'))!
assert.ok(discovery)
assert.ok(
actual.target.every((target: string) =>
target.endsWith('*') ? !discovery.urn.startsWith(target.slice(0, -1)) : target !== discovery.urn,
),
)
if (components === 'api')
assert.ok(
actual.target.some((urn: string) => urn.endsWith('::ApiSecretAccess-*')),
'new API secret grants need not exist in old state',
)
}
assert.ok(logs.every((line) => !line.includes('synthetic-passphrase')))
})
}
test('AWS adapter refuses a scoped request before identity resolution or SST spawn', async () => {
const target = awsTarget({
config,
scope,
backend: {} as any,
identity: {
assertUsableFor: async () => assert.fail('identity used'),
credentials: async () => assert.fail('credentials used'),
},
spawnProcess: (() => assert.fail('SST spawned')) as any,
})
await assert.rejects(target.run({ components: 'api', log: () => {} }), /AWS\/SST does not support/)
})
for (const [label, components, images, runner, error] of [
['old manifest, Runner only', 'runner', oldImages, runnerPins, undefined],
['old manifest, full deployment', 'api+runner', oldImages, runnerPins, undefined],
['old manifest, API only', 'api', oldImages, runnerPins, undefined],
['complete manifest, full deployment', 'api+runner', allImages, runnerPins, undefined],
[
'invalid Runner manifest digest',
'runner',
oldImages,
{ ...runnerPins, manifest: 'invalid' },
/Invalid release candidate pins for Runner/,
],
[
'invalid Runner archive digest',
'runner',
oldImages,
{ ...runnerPins, archive: 'invalid' },
/Invalid release candidate pins for Runner/,
],
] as const) {
test(`GCP release preview: ${label}`, async (t) => {
const tag = 'v1.2.3'
const sha = 'a'.repeat(40)
const required = Object.entries(config.envSelectGroup).flatMap(([group, keys]) =>
keys.filter((key) => !config.envOptional[group]?.includes(key)),
)
const stageEnvironment = {
...Object.fromEntries(
required.map((key) => [
key,
config.envSelectGroup.secret?.includes(key)
? JSON.stringify({ address: `projects/${scope.project}/secrets/${key}/versions/1` })
: 'fixture',
]),
),
BOXLITE_IMAGE_TAG: `${tag}-${sha}`,
VERSION: tag,
BOXLITE_RELEASE_DIGESTS: JSON.stringify({ tag, sha, images, runner }),
STACK_DOMAIN: 'dev.example.test',
PROXY_DOMAIN: 'proxy.dev.example.test',
}
// An inline program shares the driver's process. Only the stage manifest selects its images.
const previous = {
MSTAGE_CONFIG: process.env.MSTAGE_CONFIG,
BOXLITE_RELEASE_DIGESTS: process.env.BOXLITE_RELEASE_DIGESTS,
}
process.env.MSTAGE_CONFIG = environment.MSTAGE_CONFIG
process.env.BOXLITE_RELEASE_DIGESTS = JSON.stringify({ tag, sha, images: oldImages, runner: runnerPins })
t.after(() => {
for (const [key, value] of Object.entries(previous)) {
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
})
const resources = [...runnerState(1), ...apiState()]
const logs: string[] = []
const programWith = (options: ProgramInput) =>
gcpProgram({
...options,
loadModules: async () => ({
pulumi: { output, interpolate: undefined, jsonStringify: JSON.stringify, all: undefined, secret: output },
gcp: {},
random: {},
cloudflare: {},
command: {},
kubernetes: {},
}),
deployStackWith: ({ providers, inputs }) => {
const addresses = unwrap(providers.images({ tag: inputs.tag }))
assert.deepEqual(inputs.runnerBinary.release?.pins, { ...runnerPins, sha })
if (components !== 'runner') {
assert.deepEqual(Object.keys(addresses).sort(), Object.keys(oldImages).sort())
for (const [artifact, digest] of Object.entries(oldImages))
assert.ok(addresses[artifact].endsWith('@' + digest))
}
return {} as StackOutputs
},
})
const result = await pulumiDeploy({
intent: 'diff',
components,
config,
scope,
identity,
stageEnvironment,
state: { bucket: 'test-state' },
log: (line) => logs.push(line),
programWith,
createStackWith: async ({ program }) => ({
exportStack: async () => ({ deployment: { resources } }),
setAllConfig: async () => {},
preview: async (options) => {
if (components === 'runner') {
const policies = resources.filter((r) => r.type === 'gcp:osconfig/osPolicyAssignment:OsPolicyAssignment')
assert.deepEqual(options.target, [
...policies.map((r) => r.urn),
prefix + 'gcp:storage/bucketIAMMember:BucketIAMMember::RunnerArtifactsRead*',
])
assert.equal(options.targetDependents, false)
} else if (components === 'api+runner') assert.equal(options.target, undefined)
await program()
},
up: async () => assert.fail('apply'),
destroy: async () => assert.fail('destroy'),
refresh: async () => assert.fail('refresh'),
}),
})
assert.equal(result, error ? 1 : 0, logs.join('\n'))
if (error) assert.match(logs.join('\n'), error)
})
}
test('AWS dev and prod resolve all four release image pins without Secret Server', (t) => {
const awsDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'aws')
const saved = process.env.BOXLITE_RELEASE_DIGESTS
t.after(() => {
if (awsDescriptor) Object.defineProperty(globalThis, 'aws', awsDescriptor)
else Reflect.deleteProperty(globalThis, 'aws')
if (saved === undefined) delete process.env.BOXLITE_RELEASE_DIGESTS
else process.env.BOXLITE_RELEASE_DIGESTS = saved
})
Object.assign(globalThis, { aws: { getCallerIdentityOutput: () => ({ accountId: output('123456789012') }) } })
const build = loadBuildConfig({ cwd, environment })
const sha = 'a'.repeat(40)
process.env.BOXLITE_RELEASE_DIGESTS = JSON.stringify({ tag: 'v0.16.1', sha, images: oldImages })
for (const stage of ['dev', 'prod']) {
const addresses = awsImages({ config: build, stage, region: 'us-east-1' })({ tag: 'v0.16.1-' + sha })
assert.deepEqual(Object.keys(addresses).sort(), Object.keys(oldImages).sort())
for (const [name, digest] of Object.entries(oldImages)) assert.ok(unwrap(addresses[name]).endsWith('@' + digest))
}
})
test('GCP environments that deploy Secret Server require its pinned release image', (t) => {
mockRunnerStack(t)
const build = loadBuildConfig({ cwd, environment })
const sha = 'a'.repeat(40)
const tag = 'v1.2.3'
for (const stage of ['dev', 'stage', 'prod']) {
const resolve = (images: Record<string, string>) => gcpImages({
stage,
region: scope.region!,
project: scope.project!,
config: { ...build, stages: { [stage]: build.stages.dev2! } },
releaseImageManifest: JSON.stringify({ tag, sha, images, runner: runnerPins }),
})({ tag: tag + '-' + sha })
assert.throws(() => resolve(oldImages), /missing.*secret-server/i)
const addresses = resolve(allImages)
assert.deepEqual(Object.keys(addresses).sort(), Object.keys(allImages).sort())
for (const [image, digest] of Object.entries(allImages)) {
const { value } = addresses[image] as unknown as Value
assert.ok(value.endsWith('@' + digest))
}
}
})
test('the first App deployment requires the full graph before config writes or engine updates', async () => {
const calls: string[] = []
await assert.rejects(
pulumiDeploy({
intent: 'deploy',
components: 'api',
config,
scope,
identity,
state: { bucket: 'test-state' },
stageEnvironment: { PULUMI_CONFIG_PASSPHRASE: 'synthetic-passphrase', STACK_DOMAIN: 'example.test' },
lookupAuthorizations: () => assert.fail('unrelated DNS preflight ran'),
log: () => {},
createStackWith: async () => ({
exportStack: async () => ({
deployment: { resources: apiState().filter((resource) => !resource.urn.endsWith('::CloudAppWorker')) },
}),
setAllConfig: async () => {
calls.push('config')
},
up: async () => {
calls.push('up')
},
preview: async () => {
calls.push('preview')
},
destroy: async () => {},
refresh: async () => {},
}),
}),
/full --components api\+runner/,
)
assert.deepEqual(calls, [])
})
test('protected-stage confirmation remains required with the new selection parameter', async () => {
await assert.rejects(
run({
argv: ['--stage', 'prod', '--components', 'api+runner'],
environment,
cwd,
checkLogin: async () => 0,
targetWith: async () => assert.fail('target resolved before confirmation'),
}),
/protected.*--confirm/,
)
})
test('invalid CLI selections stop before login and stage-store access', async () => {
for (const argv of [
['--stage', 'dev', '--components', 'api'],
['--stage', stage, '--components', 'proxy'],
['--stage', stage, '--components', 'runner', '--remove', '--confirm'],
['--stage', stage, '--components', 'api', '--refresh'],
])
await assert.rejects(
run({
argv,
environment,
cwd,
checkLogin: async () => assert.fail('login used'),
fetchEnv: async () => assert.fail('store used'),
}),
/AWS\/SST does not support|--components/,
)
})