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 { readFileSync } from 'node:fs'
import test from 'node:test'
import { DeployConfigError, parseDeployConfig } from '../src/config.ts'
const valid = {
database: { name: 'boxlite', size: 'small', highlyAvailable: false, backupRetentionDays: 7, protected: false },
cache: { size: 'small', clustered: false, encryptInTransit: true },
storage: { volumePrefix: 'boxlite-volume', versioning: true },
clickhouse: {
mode: 'self-hosted',
database: 'otel',
writerUsername: 'otel_writer',
readerUsername: 'otel_reader',
instanceSize: 'medium',
dataGb: 50,
},
runners: { size: 'large', rootDiskGb: 100 },
alarms: {
apiServerErrors: { threshold: 1, periods: 1 },
proxyUnhealthyTargets: { threshold: 1, periods: 2 },
runnersUnreachable: { threshold: 1, periods: 3 },
runnersDiskExpansionFailing: { threshold: 3, periods: 1 },
runnersDiskPressureCritical: { threshold: 1, periods: 2 },
},
}
const parse = (overrides: Record<string, unknown> = {}) =>
parseDeployConfig('/repo/apps/infra/mdeploy.config.json', JSON.stringify({ ...valid, ...overrides }))
test('API instance bounds validate configured values and may be omitted', () => {
assert.equal(parse().api, undefined)
assert.equal(parse({ api: {} }).api?.minInstances, undefined)
for (const minInstances of [0, 5]) {
assert.equal(parse({ api: { minInstances } }).api?.minInstances, minInstances)
}
for (const minInstances of [-1, 1.5, '5', null]) {
assert.throws(() => parse({ api: { minInstances } }), /minInstances must be a whole number/)
}
assert.deepEqual(parse({ api: { maxInstances: 15 } }).api, { maxInstances: 15 })
assert.throws(() => parse({ api: { maxInstances: 0 } }), /maxInstances/)
assert.throws(() => parse({ api: { minInstances: 16, maxInstances: 15 } }), /maxInstances/)
assert.throws(() => parse({ api: { minInstance: 5 } }), /does not take minInstance/)
})
test('API instance sizing validates CPU and memory together', () => {
for (const instance of [{ cpu: 1, memoryMiB: 512 }, { cpu: 8, memoryMiB: 32768 }]) {
assert.deepEqual(parse({ api: { instance } }).api?.instance, instance)
}
for (const instance of [{ cpu: 2 }, { memoryMiB: 2048 }, { cpu: 3, memoryMiB: 2048 },
{ cpu: 1, memoryMiB: 4097 }, { cpu: 4, memoryMiB: 1024 }, { cpu: 2, memoryMiB: '2048' }]) {
assert.throws(() => parse({ api: { instance } }), DeployConfigError)
}
})
test('runner configuration accepts an optional data disk while preserving required fields and bounds', () => {
assert.deepEqual(parse().runners, valid.runners)
const runners = { ...valid.runners, size: '2xlarge', machineTypes: { medium: 'n4-standard-8', '2xlarge': 'n4d-standard-64' } }
assert.deepEqual(parse({ runners }).runners, runners)
assert.throws(() => parse({ runners: { ...runners, machineTypes: { tiny: 'n4-standard-4' } } }), /does not take tiny/)
for (const dataDiskGb of [20, 2048, 4000]) {
const runners = { ...valid.runners, dataDiskGb }
assert.deepEqual(parse({ runners }).runners, runners)
}
for (const dataDiskGb of [19, 4001, 20.5, '2048', null]) {
assert.throws(() => parse({ runners: { ...valid.runners, dataDiskGb } }), /dataDiskGb must be a whole number/)
}
for (const required of ['size', 'rootDiskGb']) {
const runners: Record<string, unknown> = { ...valid.runners, dataDiskGb: 2048 }
delete runners[required]
assert.throws(() => parse({ runners }), new RegExp(`must set ${required}`))
}
assert.throws(() => parse({ runners: { ...valid.runners, dataDiskSize: 2048 } }), /does not take dataDiskSize/)
})
test('the defaults have to be complete, because nothing else supplies them', () => {
// A stage says only what differs, so a gap there is the point. A gap in the
// defaults is a value nothing supplies, and the resource would be created
// from whatever the provider happened to default to.
const { database, ...withoutDatabase } = valid
assert.throws(
() => parseDeployConfig('/repo/mdeploy.config.json', JSON.stringify(withoutDatabase)),
/"database" must be an object/,
)
assert.throws(() => parse({ runners: { size: 'large' } }), /"runners" must set rootDiskGb/)
})
test('an unencrypted cache is refused rather than accepted and overridden', () => {
// Accepting it and quietly turning encryption on would read as if the setting
// worked. The cache carries sessions and box credentials across a network
// every workload shares.
assert.throws(() => parse({ cache: { ...valid.cache, encryptInTransit: false } }), /cannot be false/)
})
test('the two ClickHouse accounts must differ', () => {
// One credential for both would let a compromised read path rewrite the
// history it is reading, which is the whole reason there are two.
assert.throws(
() => parse({ clickhouse: { ...valid.clickhouse, readerUsername: 'otel_writer' } }),
/writerUsername and readerUsername must differ/,
)
})
test('a volume prefix that is not a bucket name on both clouds is refused', () => {
// The prefix bounds what the API may delete, so a value two clouds could read
// two ways is not one to accept.
assert.throws(() => parse({ storage: { volumePrefix: 'BoxLite_Volume', versioning: true } }), /must match/)
assert.throws(() => parse({ storage: { volumePrefix: 'x', versioning: true } }), /must match/)
/*
* Shape is not enough: `boxlite-volumes` passes the pattern and is still
* wrong, because the API hardcodes the singular. That combination deploys
* and then denies every mount — a CEL condition matching no bucket is no
* grant and no error — so it is refused where it can still be read as a
* configuration mistake.
*/
assert.throws(
() => parse({ storage: { volumePrefix: 'boxlite-volumes', versioning: true } }),
/must be boxlite-volume:/,
)
})
test('the prefix this refuses to vary is the one the API actually names', () => {
/*
* The guard above pins one value. What makes that value right is a template
* literal in another app: `Volume.getBucketName()` builds the name the API
* creates and the runner mounts, and it is not built from this config. Change
* it there and nothing here objects — every grant this repository writes goes
* on bounding a prefix no bucket has, and a CEL condition that matches nothing
* denies without erroring, so the deploy succeeds and every mount 403s.
*
* Read rather than imported. `apps/api` is a different project with its own
* build, and one line of its source is the whole of what this pairing needs;
* importing the entity would drag a TypeORM decorator graph into a config
* test to learn a string.
*/
const entity = readFileSync(new URL('../../../api/src/box/entities/volume.entity.ts', import.meta.url), 'utf8')
const named = /return `([a-z][a-z0-9-]*)-\$\{this\.id\}`/.exec(entity)?.[1]
assert.ok(named, 'volume.entity.ts no longer builds its bucket name from a literal prefix')
assert.doesNotThrow(
() => parse({ storage: { volumePrefix: named, versioning: true } }),
`the API names volume buckets ${named}-<id>, and this config would refuse that`,
)
})
test('a size no provider answers to is refused here rather than at the apply', () => {
assert.throws(() => parse({ database: { ...valid.database, size: 'enormous' } }), /must be one of small, standard, medium/)
assert.throws(() => parse({ runners: { size: 'tiny', rootDiskGb: 100 } }), /must be one of small, medium, large/)
})
test('a key nothing reads is refused, so a typo is not silently inert', () => {
assert.throws(() => parse({ database: { ...valid.database, retention: 7 } }), /does not take retention/)
assert.throws(() => parse({ databse: {} }), /does not take databse/)
/*
* `stages` is the old shape: defaults at the top level and per-stage
* overrides beneath them, in a file of mdeploy's own. A block pasted from one
* would parse as the defaults and drop every per-stage value silently, so the
* key is refused rather than ignored — the stage a block belongs to is now
* the stage it is written inside.
*/
assert.throws(() => parse({ stages: { dev: {} } }), /does not take stages/)
})
test('DeployConfigError is the single failure type callers can catch', () => {
assert.throws(
() => parse({ database: { ...valid.database, size: 'enormous' } }),
(error) => error instanceof DeployConfigError,
)
})
/**
* Every stage's block, read out of the committed example.
*
* `.mstage.config.example.json` rather than `.mstage.config.json`: the real one
* names somebody's cloud account and is not committed, so this is the only copy
* a fresh checkout and CI have. Reading it here is also what keeps it usable —
* it is copied before it is read, so an example that no longer parses is worse
* than none.
*/
const declared = (() => {
const path = new URL('../../.mstage.config.example.json', import.meta.url)
const raw = JSON.parse(readFileSync(path, 'utf8')) as { stages: Record<string, { deploy?: unknown }> }
return { path: path.pathname, stages: raw.stages }
})()
const blockFor = (stage: string) =>
parseDeployConfig(`${declared.path}: stage "${stage}" deploy`, JSON.stringify(declared.stages[stage]?.deploy ?? {}))
test('every stage this repository declares carries a complete, parseable block', () => {
/*
* The property that replaced "a stage is an override": there are no
* repository-wide defaults any more, so a stage added without a block is not
* a stage that deploys the usual shape — it is a stage that cannot deploy.
* The failure without this is a parse error at the apply, after the stage was
* already reachable from CI.
*/
const stages = Object.keys(declared.stages)
assert.ok(stages.length > 0, `${declared.path} declares no stage`)
for (const stage of stages) {
const block = blockFor(stage)
assert.equal(block.database.name, 'boxlite', `${stage} names another database`)
assert.ok(block.runners.rootDiskGb > 0, `${stage} sizes no runner disk`)
}
})
test('the stages differ where they are meant to, and each says so in full', () => {
// Read from the blocks rather than from a diff against defaults, because
// there are none: what makes prod prod is written in prod.
assert.equal(blockFor('prod').database.protected, true, 'production refuses deletion')
assert.equal(blockFor('prod').database.highlyAvailable, true)
assert.equal(blockFor('prod').cache.size, 'medium')
assert.equal(blockFor('dev').database.protected, false, 'dev is deletable')
assert.equal(blockFor('dev2').clickhouse.mode, 'disabled')
assert.equal(blockFor('dev2').runners.size, 'small', 'the GCP stage runs a smaller fleet than AWS dev')
assert.equal(blockFor('dev2').runners.rootDiskGb, 50, 'a GCP boot disk holds the OS and the runner; boxes live on the data disk')
assert.equal(blockFor('dev').storage.versioning, true)
assert.equal(blockFor('dev').runners.rootDiskGb, 100)
assert.equal(blockFor('dev').runners.size, 'large', 'a runner has to be a machine family that can nest')
})
/*
* The disk alarms are the only notice a failing expansion or a runner at
* critical pressure gets, and the threshold a person tunes lives in every
* stage's block. A key in the type but missing from a stage is not a default
* — it is a deploy-time refusal, which is the loud version of the trap the
* committed example exists to prevent.
*/
test('the runner disk alarms parse, and a stage without them is refused', () => {
assert.deepEqual(parse().alarms, valid.alarms)
for (const [name, alarm] of Object.entries({
runnersDiskExpansionFailing: { threshold: 3, periods: 1 },
runnersDiskPressureCritical: { threshold: 1, periods: 2 },
})) {
assert.deepEqual((parse().alarms as any)[name], alarm, name)
const tightened = { ...valid.alarms, [name]: { threshold: 5, periods: 4 } }
assert.deepEqual(parse({ alarms: tightened }).alarms, tightened)
}
for (const name of ['runnersDiskExpansionFailing', 'runnersDiskPressureCritical']) {
const alarms = { ...valid.alarms } as Record<string, unknown>
delete alarms[name]
assert.throws(() => parse({ alarms }), new RegExp(`must set ${name}`))
}
for (const bad of [{ threshold: 0, periods: 1 }, { threshold: 1, periods: 0 }]) {
assert.throws(
() => parse({ alarms: { ...valid.alarms, runnersDiskExpansionFailing: bad } }),
/must be a whole number/,
)
}
assert.throws(() => parse({ alarms: { ...valid.alarms, runnersDiskExpansionFailing: { threshold: 1 } } }), /must set periods/)
})
test('the committed example carries the disk alarms every stage must now set', () => {
// The example is the template a new stage copies, so it is where the
// defaults live — and the stage-completeness test beside this one holds
// every committed stage file against the same requirement.
const example = JSON.parse(readFileSync(new URL('../../.mstage.config.example.json', import.meta.url), 'utf8'))
for (const [stage, block] of Object.entries<any>(example.stages)) {
assert.equal(block.deploy.alarms.runnersDiskExpansionFailing.threshold, 3, stage)
assert.equal(block.deploy.alarms.runnersDiskExpansionFailing.periods, 1, stage)
assert.equal(block.deploy.alarms.runnersDiskPressureCritical.threshold, 1, stage)
assert.equal(block.deploy.alarms.runnersDiskPressureCritical.periods, 2, stage)
}
})