Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

9.3 KB
Raw Blame
import { deploymentChanges, failureView, runningStepStartedAt } from './console-deployment'
import { lastDeploy, releaseViews } from './console-releases'
import type { Ctx } from './ctx'
import type { AppRow, Deployment, DeploymentRequest, EnvRow, LogLine } from './db'

type Manifest = NonNullable<DeploymentRequest['manifest']>

const app = { id: 'app', name: 'orders' } as AppRow
const env = { id: 'stage', name: 'staging', live_deployment: 4 } as EnvRow
const at = '2026-10-21T12:00:00.000Z'

function deployment(number: number, fields: Partial<Deployment> = {}): Deployment {
  return {
    env_id: env.id,
    number,
    kind: 'deploy',
    status: 'live',
    message: null,
    by: 'key:…1234',
    created_at: at,
    started_at: at,
    finished_at: at,
    live_at: at,
    request: { kind: 'deploy' },
    spec_version: 1,
    base_version: 0,
    snapshot_id: null,
    steps: [],
    changes: [],
    error: null,
    idempotency_key: null,
    release: null,
    box_id: null,
    built: false,
    restore_point: null,
    ...fields,
  }
}

function fixture() {
  const store = {
    deployments: jest.fn().mockResolvedValue([]),
    deploymentsWhere: jest.fn().mockResolvedValue([]),
    snapshot: jest.fn(),
    logs: jest.fn().mockResolvedValue([]),
    all: jest.fn().mockResolvedValue([]),
  }
  const orchestrator = {
    rollbackProblem: jest.fn(async (_env: EnvRow, number: number) =>
      number === 1 ? 'release no longer retained' : null,
    ),
  }
  const ctx = { store, orchestrator } as unknown as Pick<Ctx, 'store' | 'orchestrator'>
  return { ctx, store, orchestrator }
}

it('shows the serving rollback separately from the deploy it restored and reports source availability for each release', async () => {
  const { ctx, store, orchestrator } = fixture()
  const active = deployment(4, { kind: 'rollback', release: 2, request: { kind: 'rollback', to: 2 } })
  const config = deployment(3, { kind: 'apply', request: { kind: 'apply' }, release: 2, status: 'superseded' })
  const previous = deployment(2, {
    release: 2,
    status: 'superseded',
    snapshot_id: 'source',
    steps: [{ name: 'build', status: 'done', ms: 2249 }],
  })
  const oldest = deployment(1, { snapshot_id: 'expired', status: 'superseded', message: 'Launch beta' })
  store.deployments.mockResolvedValue([active, config, previous, oldest])
  store.snapshot.mockImplementation(async (_app, id) => (id === 'source' ? { files: 7, bytes: 420 } : undefined))
  const releases = await releaseViews(ctx, app, env, 4)
  expect(store.deployments).toHaveBeenCalledWith(env.id, 4)
  expect(releases).toMatchObject([
    {
      id: '#4',
      current: true,
      summary: 'Rollback',
      rollback: { possible: false, reason: 'this deployment is live' },
      files: null,
      bytes: null,
      hasSource: false,
    },
    { id: '#3', current: false, summary: 'Configuration change', rollback: { possible: true }, buildSeconds: null },
    {
      id: '#2',
      current: false,
      summary: 'Deploy',
      rollback: { possible: true },
      files: 7,
      bytes: 420,
      hasSource: true,
      buildSeconds: 2.2,
    },
    {
      id: '#1',
      summary: 'Launch beta',
      rollback: { possible: false, reason: 'release no longer retained' },
      hasSource: false,
    },
  ])
  expect(orchestrator.rollbackProblem).not.toHaveBeenCalledWith(env, 4)
  expect(lastDeploy(active)).toEqual({ releaseId: '#4', at, by: 'key …1234' })
  expect(lastDeploy(undefined)).toBeNull()
})

it('summarizes the first three change paths and uses only the running step’s own start event', async () => {
  const { ctx, store } = fixture()
  const pending = deployment(7, {
    status: 'building',
    steps: [{ name: 'build', status: 'running' }],
    changes: [
      { kind: 'online_only', path: 'variables.LOG', to: 'info' },
      { kind: '+', path: 'service.web', to: { port: 3000 } },
      { kind: '~', path: 'runtime.size', from: 'small', to: 'medium' },
      { kind: '-', path: 'service.legacy' },
    ],
  })
  store.deployments.mockResolvedValue([pending, deployment(6, { status: 'queued' })])
  store.all.mockResolvedValue([{ data: JSON.stringify({ name: 'download', status: 'running' }), ts: at }])
  const [release, queued] = await releaseViews(ctx, app, env)
  expect(release.summary).toBe('variables.LOG, +service.web, ~runtime.size (+1 more)')
  expect(release.changes).toEqual([
    'online variables.LOG: info',
    '+ service.web',
    '~ runtime.size: small → medium',
    '- service.legacy',
  ])
  expect(release.running).toEqual({ name: 'build', since: null })
  expect(queued.running).toBeNull()
  expect(await runningStepStartedAt(ctx, env, deployment(6))).toBeNull()
})

it('reports no code change for an apply or unavailable source, and compares retained uploads by path and contents', async () => {
  const { ctx, store } = fixture()
  const current = deployment(5, { snapshot_id: 'new' })
  const first = {
    files: 2,
    manifest: [
      { path: 'kept', sha256: 'same' },
      { path: 'new', sha256: 'added' },
    ],
  }
  store.snapshot.mockImplementation(async (_app, id) => (id === 'new' ? first : undefined))
  expect((await deploymentChanges(ctx, app, env, { ...current, kind: 'apply' })).code).toBeNull()
  expect((await deploymentChanges(ctx, app, env, { ...current, snapshot_id: 'absent' })).code).toBeNull()
  const firstUpload = await deploymentChanges(ctx, app, env, current)
  expect(firstUpload.code).toEqual({ files: 2, added: 2, changed: 0, removed: 0, comparedWith: null })
  store.deploymentsWhere.mockResolvedValue([{ number: 2, snapshot_id: 'old' }])
  expect((await deploymentChanges(ctx, app, env, current)).code).toMatchObject({ added: 2, comparedWith: 2 })
  store.snapshot.mockImplementation(async (_app, id) =>
    id === 'new'
      ? first
      : {
          files: 2,
          manifest: [
            { path: 'kept', sha256: 'same' },
            { path: 'deleted', sha256: 'gone' },
          ],
        },
  )
  expect((await deploymentChanges(ctx, app, env, current)).code).toEqual({
    files: 2,
    added: 1,
    changed: 0,
    removed: 1,
    comparedWith: 2,
  })
})

const manifest: Manifest = {
  app: app.name,
  environment: env.name,
  runtime: { image: 'node', size: 'small', build: [], output: null },
  services: [{ name: 'api', port: 3000, command: 'node server.js', health: '/ready' }],
  database: { migrations: 'sql/' },
  schedules: [],
  volumes: [],
  auth: null,
  domains: { builtin: 'orders', custom: [] },
  access: 'public',
  public_paths: [],
  variables: {},
  secrets: {},
}

it('links a failed migration to the SQL line and gives the original database error as evidence', async () => {
  const { ctx } = fixture()
  const file = '0003_orders.sql'
  const message = `migration ${file} failed: relation "old_orders" does not exist`
  const failed = deployment(7, {
    status: 'failed',
    error: { step: 'migrate', message },
    request: {
      kind: 'deploy',
      manifest,
      migrations: [{ file, sha256: 'fixture', sql: '-- preview migration\nINSERT INTO old_orders SELECT 1;' }],
    },
  })
  const view = await failureView(ctx, app, env, failed)
  expect(view?.diagnosis).toMatchObject({
    cause: 'migration_sql_error',
    file: 'sql/0003_orders.sql',
    line: 2,
    evidence: [message],
  })
  expect(view?.fixPrompt).toContain('File: sql/0003_orders.sql:2')
  expect(view?.fixPrompt).toContain('Log lines:\n  ' + message)
  expect(view?.fixPrompt).toContain('/apps/orders/envs/staging/deployments/7/timeline')
})

it('names the failing service command and includes its stored stderr in the repair prompt', async () => {
  const { ctx, store } = fixture()
  const log: LogLine = {
    id: 3,
    ts: at,
    source: 'api',
    level: 'error',
    line: 'TypeError: invalid startup configuration',
    deployment: 8,
  }
  store.logs.mockResolvedValue([log])
  const failed = deployment(8, {
    status: 'failed',
    request: { kind: 'deploy', manifest },
    error: { step: 'start', message: 'service api exited with code 1', log_tail: [] },
  })
  const view = await failureView(ctx, app, env, failed)
  expect(view?.diagnosis).toMatchObject({ cause: 'crash_on_start', fix: expect.stringContaining('node server.js') })
  expect(view?.fixPrompt).toContain(`${at} [api] ${log.line}`)
  store.logs.mockResolvedValue([])
  const unknown = await failureView(
    ctx,
    app,
    env,
    deployment(9, { status: 'failed', error: { step: 'provision', message: 'provisioning interrupted' } }),
  )
  expect(unknown?.diagnosis).toMatchObject({ cause: 'unknown', evidence: [] })
  expect(unknown?.fixPrompt).not.toContain('Log lines:')
})

it('points a static site’s build failure at the package script before an HTTP service starts', async () => {
  const { ctx } = fixture()
  const error = 'npm ERR! Missing script: "docs"'
  const site: Manifest = {
    ...manifest,
    services: [{ name: 'docs', static: 'dist' }],
    runtime: { ...manifest.runtime, build: ['npm run docs'] },
    database: null,
  }
  const failed = deployment(10, {
    status: 'failed',
    request: { kind: 'deploy', manifest: site },
    error: { step: 'build', message: 'build step 1 (npm run docs) exited with code 1', log_tail: [error] },
  })
  const view = await failureView(ctx, app, env, failed)
  expect(view?.diagnosis).toMatchObject({ cause: 'npm_script_missing', file: 'package.json', evidence: [error] })
  expect(view?.fixPrompt).toContain('File: package.json\n')
  expect(view?.fixPrompt).toContain('add "docs" to "scripts" in package.json')
})