Skip to content

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

60.5 KB
Raw Blame
import { createHash, generateKeyPairSync } from 'node:crypto'
import { Readable } from 'node:stream'
import { buffer } from 'node:stream/consumers'
import { gunzipSync } from 'node:zlib'
import { createCloudAppStore } from '../../../../test/cloud-app-store'
import { jsonPost, managementHttp, principal } from '../../../../test/cloud-app/management'
import type { AppRow, EnvRow } from '../db'
import type { Ctx, Deps } from '../ctx'
import type { Config } from '../config'
import { buildCtx } from '../server'
import { createApp } from '../services/apps'
import { MAX_FILE_BYTES } from '../platform'
import { setLimits } from '../limits'
import { logsTopic } from '../events'
import { UpstreamError } from '../errors'
import { VOLUME_FILE_MAX } from '../volume-files'
import { upsertUser } from '../enduser/sessions'
import { MAX_NOTE_CHARS, MAX_NOTES } from '../services/notes'

const suite = process.env.DB_HOST ? describe : describe.skip
const api = '/v1/apps/journal'
const main = '/envs/main'
const manifest = `name = "journal"
[runtime]
image = "node"
size = "small"
build = ["npm ci"]
[[service]]
name = "web"
command = "node index.js"
port = 3000
health = "/health"
`

const config: Config = {
  supervisorUrl: 'https://supervisor.example.test',
  identityPrivateKey: '',
  sessionSecret: 'test-session',
  diskSizeGb: 10,
  autoStopSeconds: 300,
  domainsEnabled: false,
  svBinDir: '.',
  publicUrl: 'https://api.example.test',
  managementUrl: 'https://api.example.test/v1',
  artifactUrl: 'https://api.example.test/artifacts',
  agentMdPath: 'agent.md',
  runtimeImages: { node: 'node-image' },
}

suite('Hosted App management over HTTP and PostgreSQL', () => {
  jest.setTimeout(120_000)
  let db: Awaited<ReturnType<typeof createCloudAppStore>>
  let ctx: Ctx
  let app: AppRow
  let env: EnvRow
  let http: ReturnType<typeof managementHttp>
  const request = (path: string, init?: RequestInit) =>
    http(api + path, init, { ...principal, organizationId: db.organizationId })
  const admin = (path: string, init?: RequestInit) =>
    http('/admin' + path, init, { ...principal, organizationId: db.organizationId })
  const post = (path: string, data: unknown) => request(path, jsonPost(data))
  const responseBody = async (response: Response, status = 200) => {
    const body = await response.json()
    expect({ body, status: response.status }).toMatchObject({ status })
    return body
  }

  beforeAll(async () => {
    db = await createCloudAppStore()
  })
  afterAll(async () => {
    await db?.close()
  })
  afterEach(() => jest.restoreAllMocks())

  beforeEach(async () => {
    await db.source.query(`TRUNCATE ${db.schema}.apps, ${db.schema}.org_secrets CASCADE`)
    const objects = new Map<string, Buffer>()
    ctx = buildCtx(
      config,
      {
        store: db.store,
        origins: { envUrl: (e: EnvRow) => e.public_url },
        domains: { list: async () => [], releaseEnvironment: jest.fn() },
        volumes: { list: async () => [] },
        boxes: { list: async () => [] },
        blobs: {
          has: async (_id: string, sha: string) => objects.has(sha),
          put: async (_id: string, sha: string, source: Readable) => {
            const bytes = await buffer(source)
            objects.set(sha, bytes)
            return { bytes: bytes.length, deduped: false }
          },
          read: (_id: string, sha: string) => Readable.from([objects.get(sha)!]),
          deleteApp: async () => objects.clear(),
        },
        boxlite: {
          getBox: async () => ({ id: 'box', status: 'running' }),
          deleteBox: jest.fn(),
          startBox: jest.fn().mockResolvedValue(undefined),
        },
        supervisor: {
          health: async () => ({ version: 2, services: [{ name: 'web', state: 'running', health: 'healthy' }] }),
          logs: jest.fn(),
          restart: jest.fn(),
        },
        appdb: { listApplied: jest.fn(), query: jest.fn() },
        withPurgeLock: async (_id: string, f: (signal: AbortSignal) => Promise<unknown>) =>
          await f(new AbortController().signal),
      } as unknown as Deps,
      { pollMs: 20, activateMs: 1000, buildMs: 1000, supervisorReadyMs: 1000 },
    )
    http = managementHttp(ctx)
    app = await createApp(ctx, 'journal')
    env = (await db.store.envByName(app.id, 'main'))!
  })

  async function apply(text = manifest, target = main) {
    const created = await responseBody(await post(target + '/deployments', { kind: 'apply', manifest: text }), 202)
    const current = (await db.store.envByName(app.id, target.split('/').at(-1)!))!
    await ctx.orchestrator.runQueued(current.id)
    expect(await db.store.deployment(current.id, created.number)).toMatchObject({ status: 'live', spec_version: 1 })
  }

  it('uploads source once, completes idempotently and downloads the deployed archive through both APIs', async () => {
    const content = 'export const message = "hello"'
    const sha = createHash('sha256').update(content).digest('hex')
    const file = { path: 'src/index.js', mode: 0o644, size: content.length, sha256: sha }
    const { upload_id, missing } = await responseBody(await post('/uploads', { manifest: [file] }))
    expect(missing).toEqual([sha])
    const upload = '/uploads/' + upload_id
    expect(await responseBody(await post(upload + '/complete', {}), 400)).toMatchObject({
      error: { code: 'upload_incomplete', missing: [sha] },
    })
    expect((await request(upload + '/files/other', { method: 'PUT', body: content })).status).toBe(404)
    setLimits(ctx, { uploadsInFlightPerApp: 0 })
    const busy = await request(upload + '/files/' + sha, { method: 'PUT', body: content })
    expect([busy.status, busy.headers.get('Retry-After')]).toEqual([429, '1'])
    setLimits(ctx, {})
    expect(await responseBody(await request(upload + '/files/' + sha, { method: 'PUT', body: content }))).toEqual({
      sha256: sha,
      bytes: file.size,
      deduped: false,
    })
    const completed = await responseBody(await post(upload + '/complete', {}))
    expect(completed).toEqual({ snapshot_id: expect.stringMatching(/^snap_/), files: 1, bytes: file.size })
    expect(await responseBody(await post(upload + '/complete', {}))).toEqual(completed)
    expect(await responseBody(await post('/uploads', { manifest: [file] }))).toMatchObject({ missing: [] })
    const deployment = await responseBody(
      await post(main + '/deployments', { kind: 'deploy', manifest, snapshot_id: completed.snapshot_id }),
      202,
    )
    for (const base of [main, '']) {
      const archive = await request(base + '/deployments/' + deployment.number + '/source')
      expect(archive.headers.get('content-type')).toBe('application/gzip')
      expect(archive.headers.get('content-disposition')).toContain('journal-1.tar.gz')
      const tar = gunzipSync(Buffer.from(await archive.arrayBuffer())).toString()
      expect(tar).toContain('src/index.js')
      expect(tar).toContain(content)
    }
  })

  it('reports all upload manifest errors before allocating an upload', async () => {
    const file = { mode: 0o644, size: MAX_FILE_BYTES + 1, sha256: 'a'.repeat(64) }
    const files = ['/index.js', 'src//index.js', 'index.js', 'index.js'].map((path) => ({ ...file, path }))
    const body = await responseBody(await post('/uploads', { manifest: files }), 422)
    expect(body.error.errors.map((error: { rule: string }) => error.rule)).toEqual(
      expect.arrayContaining(['upload_path', 'file_too_large', 'upload_duplicate', 'upload_too_large']),
    )
    expect(await db.store.get('SELECT count(*) AS n FROM uploads WHERE app_id = ?', app.id)).toEqual({ n: 0 })
    expect((await post('/uploads/missing/complete', {})).status).toBe(404)
  })

  it('branches and deletes a preview environment while protecting main and busy environments', async () => {
    expect((await post('/envs', { name: 'Bad Name' })).status).toBe(400)
    expect((await post('/envs', { name: 'main' })).status).toBe(409)
    expect((await post('/envs', { name: 'preview', from: 'absent' })).status).toBe(404)
    const created = await responseBody(await post('/envs', { name: 'preview', with_data: true }), 201)
    expect(created).toMatchObject({ name: 'preview', from: 'main', status: 'new', url: null })
    expect(await responseBody(await request('/envs/preview'))).toEqual(created)
    expect((await responseBody(await request('/envs?view=dashboard'))).map((e: EnvRow) => e.name)).toEqual([
      'main',
      'preview',
    ])
    expect((await responseBody(await request('/envs'))).map((e: EnvRow) => e.name)).toEqual(['main', 'preview'])
    expect((await request('/envs/preview/spec')).status).toBe(404)
    expect((await request('/envs/main', { method: 'DELETE' })).status).toBe(403)
    await responseBody(await post('/envs/preview/deployments', { kind: 'apply', manifest }), 202)
    expect((await request('/envs/preview', { method: 'DELETE' })).status).toBe(409)
    await responseBody(await post('/envs/preview/deployments/1/cancel', {}), 202)
    expect(await responseBody(await request('/envs/preview', { method: 'DELETE' }))).toEqual({ deleted: 'preview' })
    expect(await db.store.envByName(app.id, 'preview')).toBeUndefined()
  })

  it('stores notes, feedback and app and organization secrets without disclosing their values', async () => {
    const put = (value: string) => ({ ...jsonPost({ value }), method: 'PUT' })
    expect((await admin('/secrets/wrong', put('private'))).status).toBe(400)
    expect((await admin('/secrets/org/mail', put('mailer-value'))).status).toBe(200)
    expect((await request('/secrets/cache', put('cache-value'))).status).toBe(200)
    const names = await responseBody(await request('/secrets'))
    expect(names.map((s: { name: string }) => s.name)).toEqual(['app/cache', 'org/mail'])
    expect(JSON.stringify(names)).not.toContain('cache-value')
    expect((await responseBody(await admin('/secrets')))[0].name).toBe('org/mail')
    const note = await responseBody(await post('/notes', { text: '  Use UTC for reporting  ' }), 201)
    expect(await responseBody(await request('/notes?q=utc+REPORTING&limit=1'))).toEqual([
      expect.objectContaining({ id: note.id, text: 'Use UTC for reporting' }),
    ])
    expect(await responseBody(await request('/notes/' + note.id, { method: 'DELETE' }))).toEqual({ forgotten: note.id })
    expect((await request('/notes/' + note.id, { method: 'DELETE' })).status).toBe(404)
    const report = await responseBody(
      await post('/feedback', { message: 'The timeline needs more detail', env: 'main', cli_version: '1.0' }),
      201,
    )
    expect(await responseBody(await admin('/feedback'))).toEqual([
      expect.objectContaining({ id: report.id, app: 'journal', env: 'main', actor: principal.actor }),
    ])
    expect((await request('/secrets/cache', { method: 'DELETE' })).status).toBe(204)
    expect((await admin('/secrets/org/mail', { method: 'DELETE' })).status).toBe(204)
    expect(await responseBody(await request('/activity?limit=20'))).toEqual(
      expect.arrayContaining([
        expect.objectContaining({ action: 'note.forget', detail: { id: note.id } }),
        expect.objectContaining({ action: 'secret.delete', detail: { name: 'app/cache' } }),
      ]),
    )
    expect(await responseBody(await request(''))).toMatchObject({
      name: 'journal',
      envs: [{ name: 'main', status: 'new' }],
    })
  })

  it('checks plans, queues once per idempotency key, streams final events and reports stale bases', async () => {
    const plan = await responseBody(
      await post(main + '/plan', {
        manifest,
        upload: { warnings: ['large build', { rule: 'ignored', message: 'excluding modules' }] },
      }),
    )
    expect(plan).toMatchObject({
      latest_version: 0,
      stale: false,
      errors: [],
      warnings: expect.arrayContaining([
        { rule: 'upload', message: 'large build' },
        { rule: 'ignored', message: 'excluding modules' },
      ]),
    })
    expect((await request('/envs/missing/spec')).status).toBe(404)
    expect((await request(main + '/plan', { method: 'POST', body: '{' })).status).toBe(400)
    expect((await post(main + '/plan', { base_version: -1 })).status).toBe(400)
    for (const [value, rule] of [
      [false, 'invalid_manifest'],
      [{ environment: 'preview' }, 'env_mismatch'],
      [{ environment: 'main', extra: 'typo' }, 'unknown_field'],
    ]) {
      const invalid = await responseBody(await post(main + '/plan', { manifest: value }))
      expect(invalid.errors).toContainEqual(expect.objectContaining({ rule }))
    }
    expect((await post(main + '/deployments', { kind: 'apply', manifest: 'name =' })).status).toBe(422)
    expect((await post(main + '/deployments', { kind: 'deploy', manifest, snapshot_id: 'missing' })).status).toBe(404)
    const input = {
      ...jsonPost({ kind: 'apply', manifest }),
      headers: { 'content-type': 'application/json', 'idempotency-key': 'one' },
    }
    setLimits(ctx, { queuedDeploymentsPerEnv: 1 })
    const queued = await responseBody(await request(main + '/deployments', input), 202)
    expect(await responseBody(await request(main + '/deployments', input))).toEqual(queued)
    expect(await responseBody(await post(main + '/deployments', { kind: 'apply', manifest }), 409)).toMatchObject({
      error: { queued: [1], wait_for: 1 },
    })
    await ctx.orchestrator.runQueued(env.id)
    const spec = await responseBody(await request(main + '/spec?version=1'))
    expect(spec).toMatchObject({ version: 1, assigned: { app_url: null } })
    expect((await request(main + '/spec?version=2')).status).toBe(404)
    expect(await responseBody(await post(main + '/plan', { manifest }))).toMatchObject({
      stale: true,
      latest_version: 1,
    })
    expect((await post(main + '/deployments', { kind: 'apply', manifest })).status).toBe(409)
    const dep = await responseBody(await request(main + '/deployments/1'))
    expect(dep).toMatchObject({ kind: 'apply', number: 1, status: 'live', log_tail: expect.any(Array) })
    expect(await responseBody(await request(main + '/deployments?limit=1'))).toEqual([
      expect.objectContaining({ number: 1, status: 'live' }),
    ])
    const events = await request(main + '/deployments/1/events')
    expect(events.headers.get('content-type')).toContain('text/event-stream')
    expect(await events.text()).toContain('event: done')
    expect((await request(main + '/deployments/1/source')).status).toBe(404)
    expect((await request(main + '/deployments/99')).status).toBe(404)
    expect((await post(main + '/deployments', { kind: 'rollback', to: 99 })).status).toBe(404)
  })

  it('rejects empty, oversized and credential-bearing notes and releases a note slot after deletion', async () => {
    for (const [input, message] of [
      ['  ', 'the note is empty'],
      ['a'.repeat(MAX_NOTE_CHARS + 1), 'the limit is ' + MAX_NOTE_CHARS],
      ['Use postgres://demo:[email protected]/journal', 'a database URL with its password'],
    ]) {
      const invalid = await responseBody(await post('/notes', { text: input }), 400)
      expect(invalid.error.message).toContain(message)
    }
    expect(await responseBody(await request('/notes'))).toEqual([])
    await db.store.run(
      "INSERT INTO app_notes (app_id, text, by, created_at) SELECT ?, 'note ' || n, ?, now() FROM generate_series(1, ?) AS n",
      app.id,
      principal.actor,
      MAX_NOTES,
    )
    expect((await responseBody(await post('/notes', { text: 'Another fact' }), 409)).error.message).toContain(
      'already has ' + MAX_NOTES + ' notes',
    )
    const [latest] = await responseBody(await request('/notes?limit=1'))
    await responseBody(await request('/notes/' + latest.id, { method: 'DELETE' }))
    expect(await responseBody(await post('/notes', { text: 'Another fact' }), 201)).toMatchObject({
      text: 'Another fact',
    })
  })

  it('reads log history, filters source and severity and follows new messages once', async () => {
    const t = '2026-01-02T12:00:00.000Z'
    const lines = await db.store.appendLogs(env.id, [
      { ts: t, deployment: 1, source: 'web', level: 'info', line: 'ready' },
      { ts: t, deployment: 1, source: 'web', level: 'Warning', line: 'slow' },
      { ts: t, deployment: 2, source: 'worker', level: 'fatal', line: 'failed' },
    ])
    const filtered = await responseBody(
      await request(main + '/logs/search?level=warn&source=web&deployment=1&since=2026-01-01&until=2026-01-03'),
    )
    expect(filtered).toEqual([lines[1]])
    await ctx.store.appendLogs(env.id, [{ ts: t, source: 'cron', level: 'info', line: 'background task' }])
    expect(await responseBody(await request(main + '/logs/search?level=info&limit=1'))).toEqual([
      expect.objectContaining({ line: 'background task', deployment: null }),
    ])
    expect(await responseBody(await request(main + '/logs/search?level=error'))).toEqual([lines[2]])
    expect((await request(main + '/logs/search?level=verbose')).status).toBe(400)
    expect(await responseBody(await request(main + '/logs?source=worker'))).toEqual([lines[2]])
    expect((await request(main + '/logs?box=1')).status).toBe(404)
    setLimits(ctx, { sseSubscribersPerEnv: 1 })
    const stream = await request(main + '/logs?follow=1&source=worker')
    const reader = stream.body!.getReader()
    async function nextEvent() {
      for (let i = 0; i < 30; i++) {
        const frame = new TextDecoder().decode((await reader.read()).value)
        if (frame.includes('event: log')) return frame
      }
      throw new Error('stream sent only heartbeats')
    }
    try {
      expect(await nextEvent()).toContain('failed')
      expect((await request(main + '/logs?follow=1')).status).toBe(429)
      const persisted = await db.store.appendLogs(env.id, [
        { ts: t, source: 'web', level: 'info', line: 'another service' },
        { ts: t, source: 'worker', level: 'info', line: 'recovered' },
      ])
      ctx.bus.publish(logsTopic(env.id), lines[2])
      for (const line of persisted) ctx.bus.publish(logsTopic(env.id), line)
      expect(await nextEvent()).toContain('recovered')
      await db.store.appendLogs(env.id, [{ ts: t, source: 'worker', level: 'info', line: 'from another process' }])
      expect(await nextEvent()).toContain('from another process')
    } finally {
      await reader.cancel()
    }
  })

  it('shows stored logs and access requests together, and selects only release logs for one deployment', async () => {
    const start = Date.now() - 60000
    const at = (seconds: number) => new Date(start + seconds * 1000).toISOString()
    await apply()
    await db.store.appendLogs(env.id, [
      {
        ts: at(1),
        deployment: 1,
        source: 'system',
        level: 'info',
        line: 'deployment #1 is live at https://journal.example.test',
      },
      { ts: at(2), deployment: 1, source: 'web', level: 'info', line: 'first release' },
      { ts: at(3), source: 'worker', level: 'error', line: 'job failed' },
    ])
    for (const [second, status] of [
      [4, 200],
      [5, 404],
      [6, 500],
    ] as const) {
      await ctx.accessLog.record(env.id, { ts: at(second), method: 'GET', path: '/notes', status, ms: 10 })
    }
    const all = await responseBody(await request('/logs?since=2h'))
    expect(all).toContainEqual(expect.objectContaining({ source: 'worker', line: 'job failed', deployment: null }))
    expect(all.filter((l: { source: string }) => l.source === 'access')).toMatchObject([
      { level: 'error', line: 'GET /notes 500 10ms' },
      { level: 'warn', line: 'GET /notes 404 10ms' },
      { level: 'info', line: 'GET /notes 200 10ms' },
    ])
    const releaseLogs = await responseBody(await request('/logs?deployment=1'))
    expect(releaseLogs).toContainEqual(
      expect.objectContaining({ source: 'deploy', line: expect.stringContaining('#1 is live with new configuration') }),
    )
    expect(releaseLogs.some((line: { source: string }) => line.source === 'access')).toBe(false)
    expect(await responseBody(await request('/logs?deployment=99'))).toEqual([])
  })

  it('bounds the Console and CLI logs of a config-only deployment that restarts an earlier release', async () => {
    const base = Date.now() - 10 * 60_000
    const at = (seconds: number) => new Date(base + seconds * 1000).toISOString()
    const upload = await responseBody(await post('/uploads', { manifest: [] }))
    const snapshot = await responseBody(await post('/uploads/' + upload.upload_id + '/complete', {}))
    await responseBody(
      await post(main + '/deployments', { kind: 'deploy', manifest, snapshot_id: snapshot.snapshot_id }),
      202,
    )
    await db.store.updateDeployment(env.id, 1, {
      status: 'live',
      release: 1,
      started_at: at(0),
      finished_at: at(5),
      live_at: at(5),
      built: true,
    })
    await responseBody(await post(main + '/deployments', { kind: 'apply', manifest }), 202)
    await db.store.updateDeployment(env.id, 2, { status: 'starting', release: 1, started_at: at(20) })
    const samples = [
      { second: 10, deployment: 1, line: 'before apply' },
      { second: 21, deployment: 2, line: 'applying config' },
      { second: 24, deployment: 1, line: 'restarted service' },
      { second: 48, deployment: 1, line: 'settling' },
      { second: 70, deployment: 1, line: 'serving requests' },
    ]
    await db.store.appendLogs(
      env.id,
      samples.map(({ second, deployment, line }) => ({
        ts: at(second),
        deployment,
        line,
        source: 'web',
        level: 'info',
      })),
    )
    const lineText = (lines: { line: string }[]) => lines.map((l) => l.line)
    const timeline = async () => lineText((await responseBody(await request(main + '/deployments/2/timeline'))).logs)
    expect(await timeline()).toEqual(['applying config', 'restarted service', 'settling', 'serving requests'])
    const panel = async (query = '') => lineText(await responseBody(await request('/logs?deployment=2' + query)))
    expect(await panel()).toEqual(['serving requests', 'settling', 'restarted service', 'applying config'])
    await db.store.updateDeployment(env.id, 2, { status: 'live', finished_at: at(28), live_at: at(28) })
    expect(await timeline()).toEqual(['applying config', 'restarted service', 'settling'])
    await responseBody(await post(main + '/deployments', { kind: 'apply', manifest }), 202)
    await db.store.updateDeployment(env.id, 3, {
      status: 'live',
      release: 1,
      started_at: at(80),
      finished_at: at(83),
      live_at: at(83),
    })
    await db.store.appendLogs(env.id, [
      { ts: at(90), deployment: 1, source: 'web', level: 'info', line: 'next deployment' },
    ])
    expect(await panel('&since=' + encodeURIComponent(at(30)) + '&limit=2')).toEqual(['serving requests', 'settling'])
    expect((await responseBody(await request('/logs?since=yesterdayish'), 400)).error.code).toBe('invalid_request')
  })

  it('exposes an empty environment to CLI diagnosis before the first configuration', async () => {
    expect(await responseBody(await request('/context'))).toMatchObject({
      status: 'new',
      live: null,
      runtime: null,
      services: [],
      volumes: [],
      database: null,
      urls: { health: null, login: null },
    })
    expect(await responseBody(await request(main + '/volumes'))).toEqual([])
    expect((await request(main + '/volumes/uploads/files')).status).toBe(404)
    expect(await responseBody(await request(main + '/probe'))).toMatchObject({
      path: '/',
      url: null,
      reason: 'not_deployed',
    })
  })

  it('reports CLI context, acknowledges the public access finding and reopens it when requested', async () => {
    const secret = await request('/secrets/mail', { ...jsonPost({ value: 'test-mail-token' }), method: 'PUT' })
    expect(secret.status).toBe(200)
    await apply(`access = "public"\n${manifest}
[[volume]]
name = "uploads"
mount = "/data/uploads"
[[schedule]]
name = "daily"
cron = "0 9 * * *"
target = "web:/jobs/daily"
[variables]
LOG_LEVEL = "info"
[secrets]
MAIL_TOKEN = "app/mail"`)
    const context = await responseBody(await request(main + '/context'))
    expect(context).toMatchObject({
      env: 'main',
      access: { level: 'public' },
      services: [expect.objectContaining({ name: 'web', health_path: '/health' })],
      deployments: [expect.objectContaining({ status: 'live' })],
      next_actions: expect.arrayContaining([expect.objectContaining({ id: 'public_anonymous' })]),
    })
    expect((await request(main + '/volumes/uploads/files?path=/')).status).toBe(404)
    const link = main + '/findings/public_anonymous/ack'
    expect((await responseBody(await post(link, { reason: '   ' }), 400)).error.message).toContain('say why')
    expect(
      (await responseBody(await post(main + '/findings/missing/ack', { reason: 'already reviewed' }), 404)).error.next,
    ).toContain('public_anonymous')
    expect(await responseBody(await post(link, { reason: 'Published by request' }))).toMatchObject({
      reason: 'Published by request',
      by: principal.actor,
    })
    expect(await responseBody(await request('/context'))).toMatchObject({
      acknowledged: [expect.objectContaining({ id: 'public_anonymous' })],
    })
    expect(await responseBody(await request(link, { method: 'DELETE' }))).toEqual({
      unacknowledged: 'public_anonymous',
    })
    expect((await responseBody(await request(link, { method: 'DELETE' }), 404)).error.message).toContain(
      'is not acknowledged',
    )
    expect(await responseBody(await request(main + '/vars'))).toEqual(
      expect.arrayContaining([
        expect.objectContaining({ name: 'LOG_LEVEL', value: 'info' }),
        expect.objectContaining({ name: 'MAIL_TOKEN', value: null, resolved: true, source: 'secret app/mail' }),
      ]),
    )
    expect(await responseBody(await request(main + '/schedules'))).toEqual([
      expect.objectContaining({ name: 'daily', next_run: expect.stringMatching(/T09:00:00\.000Z$/) }),
    ])
    expect(await responseBody(await request(main + '/volumes'))).toEqual([
      { name: 'uploads', mount: '/data/uploads', mode: 'rw' },
    ])
    expect(await responseBody(await request(main + '/probe'))).toMatchObject({
      path: '/health',
      reason: 'not_deployed',
      ok: false,
    })
    await db.store.updateEnv(env.id, {
      public_url: 'https://journal.example.test',
      box_url: 'https://box.example.test',
      active_box_id: 'box',
    })
    const upstream = jest
      .spyOn(globalThis, 'fetch')
      .mockResolvedValue(new Response('healthy', { headers: { 'content-type': 'text/plain' } }))
    expect(await responseBody(await request(main + '/probe'))).toMatchObject({
      url: 'https://journal.example.test/health',
      status: 200,
      reason: 'ok',
      body_head: 'healthy',
    })
    const file = main + '/volumes/uploads/files?path='
    expect((await request(file + '/', { method: 'DELETE' })).status).toBe(400)
    expect((await request(file + '/', { method: 'PUT', body: 'data' })).status).toBe(400)
    expect(
      (
        await request(file + '/large.bin', {
          method: 'PUT',
          headers: { 'content-length': String(VOLUME_FILE_MAX + 1) },
        })
      ).status,
    ).toBe(400)
    expect(
      (await request(file + '/large.bin', { method: 'PUT', body: new Uint8Array(VOLUME_FILE_MAX + 1) })).status,
    ).toBe(400)
    expect(upstream).toHaveBeenCalledTimes(1)
    upstream.mockResolvedValueOnce(
      new Response('not ready', { status: 404, headers: { 'content-type': 'text/plain' } }),
    )
    expect(await responseBody(await request(main + '/probe?path=/ready'))).toMatchObject({
      reason: 'http_error',
      status: 404,
      body_head: 'not ready',
    })
    expect(upstream.mock.calls[0]![0]).toBe('https://box.example.test/health')
    jest.spyOn(ctx.resources, 'appUrl').mockRejectedValueOnce(new Error('unavailable origin'))
    expect(await responseBody(await request(main + '/probe?path=check'))).toMatchObject({
      url: 'https://journal.example.test/check',
      ok: false,
      reason: 'unreachable',
    })
  })

  it('shows migrations and creates a restore point before resetting a preview database', async () => {
    expect((await request(main + '/db/applied')).status).toBe(404)
    expect((await post(main + '/db/reset', {})).status).toBe(403)
    await responseBody(await post('/envs', { name: 'preview' }), 201)
    const preview = (await db.store.envByName(app.id, 'preview'))!
    const url = 'postgres://[email protected]/journal'
    await db.store.updateEnv(preview.id, { db_url: url })
    const entry = { file: '001.sql', sha256: 'a'.repeat(64), deployment: 1, applied_at: '2026-01-01' }
    jest.mocked(ctx.appdb.listApplied).mockResolvedValue([entry])
    expect(await responseBody(await request('/envs/preview/db/applied'))).toEqual([entry])
    jest.mocked(ctx.appdb.query).mockResolvedValue({
      columns: ['table_name'],
      rows: [['boxlite_migrations'], ['entries']],
      row_count: 2,
      elapsed_ms: 1,
      truncated: false,
    })
    const reset = await responseBody(await post('/envs/preview/db/reset', {}))
    expect(reset).toEqual({ reset: 'preview', snapshot: expect.stringMatching(/^dbs_/), dropped_tables: ['entries'] })
    expect(ctx.appdb.query).toHaveBeenLastCalledWith(
      url,
      ['DROP SCHEMA IF EXISTS public CASCADE', 'CREATE SCHEMA public'],
      { write: true },
    )
    expect(await responseBody(await request('/envs/preview/db/snapshots'))).toEqual([
      expect.objectContaining({ id: reset.snapshot, message: 'before db reset' }),
    ])
  })

  it('lists and exports users in the selected environment and keeps blocked users in the Console', async () => {
    await db.store.updateEnv(env.id, { public_url: 'https://journal.example.test' })
    await apply(manifest + '\n[auth]\nproviders = ["github", "google", "email"]')
    const auth = main + '/auth'
    const testUser = await responseBody(await post(auth + '/test-sessions', { email: '[email protected]' }), 201)
    const signedIn = await upsertUser(ctx, app, env, 'github', {
      id: '105',
      email: '[email protected]',
      name: '+Lee, "May"',
      avatarUrl: null,
    })
    await responseBody(await post('/envs', { name: 'preview' }), 201)
    const events = await db.store.appendLogs(env.id, [
      { ts: new Date().toISOString(), source: 'auth', level: 'warning', line: 'sign-in cancelled' },
      { ts: new Date().toISOString(), source: 'web', level: 'info', line: 'application started' },
    ])
    for (const action of ['block', 'unblock', 'signout']) {
      const missing = await post('/envs/preview/auth/users/' + testUser.user.id + '/' + action, {})
      expect(await responseBody(missing, 404)).toMatchObject({ error: { code: 'not_found' } })
    }
    expect(await responseBody(await post(auth + '/users/' + testUser.user.id + '/block', {}))).toMatchObject({
      blocked: true,
      active_sessions: 0,
    })
    const list = (q: string) => request(auth + '/users' + q).then((r) => responseBody(r))
    expect(await list('?search=qa_')).toEqual([expect.objectContaining({ id: testUser.user.id })])
    expect(await list('?limit=1')).toHaveLength(1)
    expect(await list('?limit=invalid')).toHaveLength(2)
    const panel = await responseBody(await request('/auth?search=qa_'))
    expect(panel.status).toMatchObject({ declared: true, enforced: false, users: 2 })
    expect(panel.status.note).toContain('GitHub, Google need an OAuth app')
    expect(panel.status.note).toContain('email sign-in needs a mail sender')
    expect(panel.users).toEqual([expect.objectContaining({ id: testUser.user.id, sessions: 0, blocked: true })])
    expect(panel.events).toEqual([
      { id: 'l' + events[0]!.id, ts: events[0]!.ts, level: 'warn', line: 'sign-in cancelled' },
    ])
    const csv = await request('/users.csv')
    expect(csv.headers.get('content-disposition')).toBe('attachment; filename="journal-main-users.csv"')
    const contents = await csv.text()
    expect(contents).toContain(signedIn.id + ',[email protected],"\'+Lee, ""May""",github')
    expect(await (await request(auth + '/users/export')).text()).toBe(contents)
    expect((await responseBody(await request('/auth?env=preview'))).users).toEqual([])
    expect(await responseBody(await request(auth + '/test-users', { method: 'DELETE' }))).toEqual({
      emails: ['[email protected]'],
      removed: 1,
      mirror: 'none',
    })
    expect(await list('')).toEqual([expect.objectContaining({ id: signedIn.id })])
    for (const body of [{ email: 'missing-at' }, { email: '[email protected]', role: 'member' }]) {
      expect((await post(auth + '/test-sessions', body)).status).toBe(400)
    }
  })

  it('requires valid initial provider credentials and preserves Apple key fields during rotation', async () => {
    const configure = (provider: string, fields: Record<string, string>) =>
      request('/auth/methods/' + provider, { ...jsonPost({ keys: 'own', ...fields }), method: 'PUT' })
    expect((await responseBody(await configure('github', { clientId: 'demo-app' }), 400)).error.message).toContain(
      'client secret',
    )
    const initial = { clientId: 'org.example.journal', teamId: 'TEAMID', keyId: 'MYKEY' }
    expect(
      (await responseBody(await configure('apple', { ...initial, privateKey: 'invalid' }), 400)).error.message,
    ).toContain('.p8')
    const pem = generateKeyPairSync('ec', { namedCurve: 'P-256' })
      .privateKey.export({ format: 'pem', type: 'pkcs8' })
      .toString()
    const enabled = await responseBody(await configure('apple', { ...initial, privateKey: pem }))
    expect(enabled.status.methods).toContainEqual(
      expect.objectContaining({ provider: 'apple', keys: 'own', clientId: initial.clientId }),
    )
    expect(JSON.stringify(enabled)).not.toContain('BEGIN PRIVATE KEY')
    const rotated = await responseBody(await configure('apple', { clientId: initial.clientId, keyId: 'NEWKEY' }))
    expect(rotated.status.methods).toContainEqual(expect.objectContaining({ provider: 'apple', status: 'ready' }))
    const saved = await ctx.store.get<{ client_secret: string }>(
      'SELECT client_secret FROM app_oauth_clients WHERE app_id = ? AND provider = ?',
      app.id,
      'apple',
    )
    expect(JSON.parse(saved!.client_secret)).toEqual({
      keyId: 'NEWKEY',
      teamId: initial.teamId,
      privateKey: pem.trim(),
    })
    expect((await post('/auth/email/test', { to: 'invalid' })).status).toBe(400)
    expect(
      (await responseBody(await post('/auth/email/test', { to: '[email protected]' }), 404)).error.message,
    ).toContain('no mail sender')
  })

  it('keeps test accounts when referenced by application rows and removes them on a successful retry', async () => {
    const url = 'postgres://[email protected]/journal'
    await db.store.updateApp(app.id, { neon_project_id: 'project', neon_main_branch_id: 'primary' })
    await db.store.updateEnv(env.id, {
      db_url: url,
      neon_branch_id: 'primary',
      public_url: 'https://journal.example.test',
    })
    ctx.appdb.ensureReader = jest.fn()
    await apply(manifest + '\n[database]\n[auth]\nproviders = ["email"]')
    const auth = main + '/auth'
    const email = '[email protected]'
    const created = await responseBody(await post(auth + '/test-sessions', { email }), 201)
    const purge = () => request(auth + '/test-users', { method: 'DELETE' }).then((r) => responseBody(r))
    jest.mocked(ctx.appdb.query).mockRejectedValueOnce(new Error('orders still reference this user'))
    expect(await purge()).toEqual({ emails: [email], mirror: 'kept: orders still reference this user', removed: 0 })
    expect(await responseBody(await request(auth + '/users'))).toEqual([
      expect.objectContaining({ id: created.user.id, active_sessions: 1 }),
    ])
    expect(await purge()).toEqual({ emails: [email], mirror: 'removed', removed: 1 })
    expect(ctx.appdb.query).toHaveBeenLastCalledWith(url, ["DELETE FROM boxlite.users WHERE provider = 'test'"], {
      write: true,
    })
    expect(await responseBody(await request(auth + '/users'))).toEqual([])
    expect(await purge()).toEqual({ emails: [], mirror: 'removed', removed: 0 })
  })

  it('projects deployment step times and log lines through both CLI and Console timelines', async () => {
    await apply()
    const cli = await responseBody(await request(main + '/deployments/1/timeline'))
    expect(cli.deployment).toMatchObject({ status: 'live', number: 1 })
    expect(cli.steps).toContainEqual(
      expect.objectContaining({
        name: 'live',
        status: 'done',
        started_at: expect.any(String),
        finished_at: expect.any(String),
      }),
    )
    expect(cli.truncated).toBe(false)
    expect(cli.logs).toContainEqual(expect.objectContaining({ line: 'spec v1 written' }))
    const view = await responseBody(await request('/deployments/1'))
    expect(view).toMatchObject({ id: '#1', number: 1, specVersion: 1, failure: null, logTruncated: false })
    expect(view.timeline).toContainEqual(
      expect.objectContaining({
        name: 'live',
        startedAt: cli.steps.at(-1).started_at,
        finishedAt: cli.steps.at(-1).finished_at,
      }),
    )
    expect(view.log.map((l: { line: string }) => l.line)).toEqual(cli.logs.map((l: { line: string }) => l.line))
    expect((await request('/deployments/missing')).status).toBe(404)
    expect((await request(main + '/deployments/99/timeline')).status).toBe(404)
    expect((await post('/releases/abc/activate', {})).status).toBe(400)
    expect((await post('/releases/99/activate', {})).status).toBe(404)
    await db.store.updateDeployment(env.id, 1, { release: 1, box_id: 'box' })
    await db.store.updateEnv(env.id, { active_box_id: 'box' })
    const rolled = await responseBody(await post('/releases/%231/activate', {}))
    expect(rolled.deploying.number).toBe(2)
    expect(await db.store.deployment(env.id, 2)).toMatchObject({
      kind: 'rollback',
      request: { to: 1 },
      status: 'queued',
    })
  })

  it('edits variables and secret references as apply deployments', async () => {
    const action = (value: unknown) => post('/actions', value)
    expect((await action({ type: 'setVariable', name: 'PAGE_SIZE', value: '5' })).status).toBe(409)
    await apply(manifest + '\n[variables]\nPAGE_SIZE = "10"')
    async function edit(value: unknown) {
      const detail = await responseBody(await action(value))
      const queued = (await db.store.deployment(env.id, detail.deploying.number))!
      expect(queued).toMatchObject({ kind: 'apply', status: 'queued' })
      await ctx.orchestrator.runQueued(env.id)
      return queued.request.manifest!
    }
    expect((await edit({ type: 'setVariable', name: 'PAGE_SIZE', value: '5' })).variables).toEqual({ PAGE_SIZE: '5' })
    expect((await edit({ type: 'importVariables', values: { TITLE: 'Notes' } })).variables).toEqual({
      PAGE_SIZE: '5',
      TITLE: 'Notes',
    })
    expect((await edit({ type: 'removeVariable', name: 'PAGE_SIZE' })).variables).toEqual({ TITLE: 'Notes' })
    expect((await action({ type: 'removeVariable', name: 'MISSING' })).status).toBe(404)
    expect((await action({ type: 'importVariables', values: {} })).status).toBe(400)
    expect((await action({ type: 'setVariable', name: 'not a variable', value: 'x' })).status).toBe(400)
    expect((await action({ type: 'referenceSecret', name: 'API_KEY', from: 'app/missing' })).status).toBe(404)
    const secret = await edit({ type: 'addSecret', name: 'API_KEY', value: 'private-api-value' })
    const ref = secret.secrets.API_KEY!
    expect(ref).toMatch(/^app\//)
    expect(JSON.stringify(secret)).not.toContain('private-api-value')
    expect((await action({ type: 'addSecret', name: 'API_KEY', value: 'replacement' })).status).toBe(409)
    expect((await edit({ type: 'referenceSecret', name: 'OTHER_KEY', from: ref })).secrets).toEqual({
      API_KEY: ref,
      OTHER_KEY: ref,
    })
    expect((await edit({ type: 'removeSecret', name: 'OTHER_KEY' })).secrets).toEqual({ API_KEY: ref })
    expect((await action({ type: 'removeSecret', name: 'MISSING' })).status).toBe(404)
    expect((await post('/variables/copy', { from: 'missing' })).status).toBe(404)
    await responseBody(await post('/envs', { name: 'preview' }), 201)
    await apply(manifest + '\n[variables]\nFROM_PREVIEW = "true"', '/envs/preview')
    const copied = await responseBody(await post('/variables/copy', { from: 'preview' }))
    const queued = await db.store.deployment(env.id, copied.deploying.number)
    expect(queued?.request.manifest).toMatchObject({ variables: { FROM_PREVIEW: 'true' }, secrets: {} })
    await db.store.updateEnv(env.id, { db_url: 'postgres://[email protected]/journal' })
    await responseBody(await action({ type: 'createBackup', message: 'before copying' }))
    expect(await responseBody(await request(main + '/db/snapshots'))).toEqual([
      expect.objectContaining({ message: 'before copying' }),
    ])
  })

  it('creates and opens an App through the Console and restores a soft deletion', async () => {
    const caller = { ...principal, organizationId: db.organizationId }
    const create = await responseBody(await http('/v1/apps', jsonPost({ name: 'second' }), caller), 201)
    expect(create.app).toMatchObject({ name: 'second', environment: 'main' })
    expect(create.prompt).toContain('--app second')
    expect(await responseBody(await http('/v1/apps', undefined, caller))).toContainEqual(
      expect.objectContaining({ name: 'second' }),
    )
    expect((await http('/v1/apps/no-such-app/view', undefined, caller)).status).toBe(404)
    expect((await http('/v1/apps/deleted/second/restore', jsonPost({}), caller)).status).toBe(404)
    expect(await responseBody(await http('/v1/apps/' + create.app.appId + '/view', undefined, caller))).toMatchObject({
      name: 'second',
    })
    expect((await request('/view?env=staging')).status).toBe(404)
    const session = await responseBody(await http('/v1/session', undefined, { ...caller, name: 'Reader' }))
    expect(session).toMatchObject({
      user: 'Reader',
      controlPlane: config.managementUrl,
      organization: { id: db.organizationId, apps: 2 },
    })
    const emailOnly = await responseBody(
      await http('/v1/session', undefined, { ...caller, email: '[email protected]' }),
    )
    expect(emailOnly.user).toBe('[email protected]')
    expect((await responseBody(await http('/v1/session', undefined, caller))).user).toBe('you')
    const handoff = await responseBody(await request('/handoff'))
    expect(handoff.prompt).toContain('--app journal --env main')
    expect((await request('/preview')).status).toBe(404)
    expect((await post('/preview', {})).status).toBe(409)
    expect((await post('/sleep', {})).status).toBe(409)
    expect((await post('/restart', {})).status).toBe(404)
    expect((await post('/schedules/absent/run', {})).status).toBe(404)
    await db.store.updateEnv(env.id, { public_url: 'https://journal.example.test' })
    const ticket = await responseBody(await post('/open-ticket', { next: '/notes' }))
    const target = new URL(ticket.url)
    expect([target.origin, target.searchParams.get('next')]).toEqual(['https://journal.example.test', '/notes'])
    const reader = { ...caller, permissions: ['read:apps'] }
    const cliTicket = await responseBody(
      await http(api + main + '/open-ticket?next=/notes', { method: 'POST' }, reader),
      201,
    )
    expect(new URL(cliTicket.url).searchParams.get('next')).toBe('/notes')
    expect((await http(api + main + '/open-ticket', jsonPost({ as: '[email protected]' }), reader)).status).toBe(403)
    expect(target.searchParams.get('t')).toBeTruthy()
    expect(await responseBody(await post('/publish', { visibility: 'org' }))).toMatchObject({
      visibility: 'org',
      accessSource: 'online',
    })
    expect((await request('', { method: 'DELETE' })).status).toBe(204)
    expect(await responseBody(await http('/v1/apps/deleted', undefined, caller))).toContainEqual(
      expect.objectContaining({ name: 'journal', environments: 1 }),
    )
    expect(await responseBody(await http('/v1/apps/deleted/journal/restore', jsonPost({}), caller))).toMatchObject({
      name: 'journal',
    })
    expect((await request('/view')).status).toBe(200)
    expect((await http('/v1/apps/deleted/journal', { method: 'DELETE' }, caller)).status).toBe(404)
    expect((await request('', { method: 'DELETE' })).status).toBe(204)
    expect(
      (await http('/v1/apps/deleted/journal', { method: 'DELETE' }, { ...caller, permissions: ['read:apps'] })).status,
    ).toBe(403)
    expect((await http('/v1/apps/deleted/journal', { method: 'DELETE' }, caller)).status).toBe(204)
    expect(await db.store.appByNameAnyState(app.name)).toBeUndefined()
  })

  it('replays deployment events after the cursor and follows a worker writing to the shared database', async () => {
    await responseBody(await post(main + '/deployments', { kind: 'apply', manifest }), 202)
    const seq1 = await ctx.store.insertEvent(env.id, 1, 'log', { line: 'already delivered' })
    await ctx.store.insertEvent(env.id, 1, 'log', { line: 'new history' })
    setLimits(ctx, { sseSubscribersPerEnv: 1, sseHeartbeatMs: 20 })
    const stream = await request(main + '/deployments/1/events', { headers: { 'last-event-id': String(seq1) } })
    const reader = stream.body!.getReader()
    const next = async () => new TextDecoder().decode((await reader.read()).value)
    try {
      const replay = await next()
      expect(replay).toContain('new history')
      expect(replay).not.toContain('already delivered')
      expect((await request(main + '/deployments/1/events')).status).toBe(429)
      expect(await next()).toContain('keepalive')
      await ctx.orchestrator.emit(env.id, 1, 'log', { line: 'from the queue' })
      // A separate worker has no access to this HTTP server's in-process bus.
      await ctx.store.insertEvent(env.id, 1, 'done', { status: 'live' })
      let rest = ''
      for (;;) {
        const { value, done } = await reader.read()
        if (done) break
        rest += new TextDecoder().decode(value)
      }
      expect(rest.match(/from the queue/g)).toHaveLength(1)
      expect(rest).toContain('event: done')
      expect(rest).toContain('"status":"live"')
    } finally {
      await reader.cancel()
    }
    await ctx.store.updateDeployment(env.id, 1, { status: 'live' })
    const last = await request(main + '/deployments/1/events?after=4')
    expect(await last.text()).toContain('event: done')
  })

  it('validates pending migration files during planning and detects edits to applied migrations', async () => {
    const text = manifest + '\n[database]\nmigrations = "db/migrations"'
    const sql = 'CREATE TABLE entries (id integer)'
    const migration = { file: '0001_entries.sql', sql, sha256: createHash('sha256').update(sql).digest('hex') }
    const plan = (migrations: unknown[]) => post(main + '/plan', { manifest: text, migrations, base_version: 0 })
    const invalid = await responseBody(await plan([{ ...migration, sha256: '0'.repeat(64) }]))
    expect(invalid.errors).toContainEqual(expect.objectContaining({ rule: 'migration_sha256' }))
    const pending = await responseBody(await plan([migration]))
    expect(pending.errors).toEqual([])
    expect(pending.changes).toContainEqual({ kind: '+', path: 'migrations/0001_entries.sql', to: 'pending' })
    await db.store.updateApp(app.id, { neon_project_id: 'project', neon_main_branch_id: 'primary' })
    await db.store.updateEnv(env.id, {
      neon_branch_id: 'primary',
      db_url: 'postgres://[email protected]/journal',
    })
    ctx.appdb.ensureReader = jest.fn()
    ctx.appdb.applyMigration = jest.fn()
    jest.mocked(ctx.appdb.listApplied).mockResolvedValue([])
    await responseBody(
      await post(main + '/deployments', { kind: 'apply', manifest: text, migrations: [migration] }),
      202,
    )
    await ctx.orchestrator.runQueued(env.id)
    expect(ctx.appdb.applyMigration).toHaveBeenCalledWith(expect.any(String), migration, 1)
    // A variable save must carry the migration SQL into the next apply.
    const saved = await responseBody(await post('/actions', { type: 'setVariable', name: 'LANGUAGE', value: 'en' }))
    const next = await db.store.deployment(env.id, saved.deploying.number)
    expect(next?.request.migrations).toEqual([migration])
    await post(main + '/deployments/' + saved.deploying.number + '/cancel', {})
    // A release with just a resolved migration list reads its SQL from the App's source storage.
    const applied = (await db.store.deployment(env.id, 1))!
    const { migrations: _inlineFiles, ...resolved } = applied.request
    await db.store.updateDeployment(env.id, 1, { request: resolved })
    await ctx.blobs.put(app.id, migration.sha256, Readable.from([Buffer.from(sql)]), MAX_FILE_BYTES)
    const savedFromSource = await responseBody(
      await post('/actions', { type: 'setVariable', name: 'LANGUAGE', value: 'fr' }),
    )
    expect((await db.store.deployment(env.id, savedFromSource.deploying.number))?.request.migrations).toEqual([
      migration,
    ])
    const edited = 'CREATE TABLE entries (id bigint)'
    const changed = await responseBody(
      await plan([{ ...migration, sql: edited, sha256: createHash('sha256').update(edited).digest('hex') }]),
    )
    expect(changed.errors).toContainEqual(
      expect.objectContaining({ file: 'db/migrations/0001_entries.sql', rule: 'migration_changed' }),
    )
  })

  it('provisions an environment from the parent branch and removes a failed creation before retrying', async () => {
    const mainUrl = 'postgres://[email protected]/journal'
    await db.store.updateApp(app.id, { neon_project_id: 'project', neon_main_branch_id: 'primary' })
    await db.store.updateEnv(env.id, { neon_branch_id: 'primary', db_url: mainUrl })
    ctx.neon = {
      createBranch: jest
        .fn()
        .mockRejectedValueOnce(new UpstreamError('neon', 503, 'branch service busy'))
        .mockResolvedValueOnce({ branchId: 'preview-branch' }),
      connectionUri: jest.fn().mockResolvedValue('postgres://[email protected]/journal'),
      deleteBranch: jest.fn(),
    } as unknown as Ctx['neon']
    ctx.appdb.copyMigrationLedger = jest.fn().mockResolvedValue(1)
    const create = () => post('/envs', { name: 'preview', from: 'main' })
    expect((await create()).status).toBe(503)
    expect(await db.store.envByName(app.id, 'preview')).toBeUndefined()
    expect(await responseBody(await create(), 201)).toMatchObject({
      from: 'main',
      database: { branch: 'preview-branch' },
    })
    expect(ctx.neon.createBranch).toHaveBeenCalledWith('project', 'preview', 'primary', 'schema-only')
    expect(ctx.appdb.copyMigrationLedger).toHaveBeenCalledWith(mainUrl, expect.stringContaining('preview.example.test'))
    expect(await responseBody(await request('/envs/preview', { method: 'DELETE' }))).toEqual({ deleted: 'preview' })
    expect(ctx.neon.deleteBranch).toHaveBeenCalledWith('project', 'preview-branch')
  })

  it('reads live service state, runs a schedule, restarts the service and puts the Box to sleep', async () => {
    expect(await responseBody(await request(main + '/services'))).toEqual([])
    await apply(manifest + '\n[[schedule]]\nname = "daily"\ncron = "0 9 * * *"\ntarget = "web:/jobs/daily"')
    const url = 'https://journal.example.test'
    const boxUrl = 'https://box.example.test'
    await db.store.updateEnv(env.id, { public_url: url, box_url: boxUrl, active_box_id: 'box' })
    const service = await responseBody(await request(main + '/services'))
    expect(service).toEqual([expect.objectContaining({ name: 'web', state: 'running', health: 'healthy' })])
    expect((await post(main + '/services/absent/restart', {})).status).toBe(404)
    expect(await responseBody(await post('/restart', { service: 'web' }))).toMatchObject({
      services: [expect.objectContaining({ name: 'web' })],
    })
    expect(ctx.supervisor.restart).toHaveBeenCalledWith(boxUrl, env.control_secret, 'web')
    const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xd9])
    await ctx.store.run(
      'INSERT INTO previews (env_id,captured_at,deployment,image) VALUES (?,?,?,?)',
      env.id,
      new Date().toISOString(),
      1,
      jpeg,
    )
    const preview = await request('/preview')
    expect(preview.headers.get('content-type')).toBe('image/jpeg')
    expect(Buffer.from(await preview.arrayBuffer())).toEqual(jpeg)
    expect(await responseBody(await post('/preview', {}), 202)).toEqual({ capturing: true })
    const upstream = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 204 }))
    expect(await responseBody(await post('/schedules/daily/run', {}))).toMatchObject({
      name: 'daily',
      status: 204,
      starting: false,
    })
    expect(upstream).toHaveBeenCalledWith(boxUrl + '/jobs/daily', expect.objectContaining({ method: 'POST' }))
    jest.mocked(ctx.supervisor.logs).mockResolvedValue({ lines: [{ line: 'healthy' }] })
    expect(await responseBody(await request(main + '/logs?box=1&source=web&limit=3000'))).toEqual({
      lines: [{ line: 'healthy' }],
    })
    expect(ctx.supervisor.logs).toHaveBeenCalledWith(boxUrl, env.control_secret, 'web', 2000)
    ctx.boxes.list = jest.fn().mockResolvedValue(['box'])
    ctx.boxlite.stopBox = jest.fn()
    expect(await responseBody(await post('/sleep', {}))).toMatchObject({ box: { id: 'box', state: 'stopped' } })
    expect(ctx.boxlite.stopBox).toHaveBeenCalledWith('box')
    expect(await responseBody(await request(main + '/services'))).toEqual([
      expect.objectContaining({ state: 'stopped (Box asleep)', memory_bytes: null }),
    ])
    expect(await responseBody(await request(main + '/probe'))).toMatchObject({ starting: true, reason: 'starting' })

    expect(await responseBody(await request(main + '/access'))).toEqual({ access: 'private', source: 'manifest' })
    expect(await responseBody(await request(main + '/dev-env'))).toMatchObject({
      env: { BOXLITE_APP: 'journal', BOXLITE_APP_URL: url },
      database: null,
    })
  })

  it('explains the application database schema, migration drift and connection failures in the CLI context', async () => {
    const ledger = { deployment: 1, applied_at: '2026-01-01T00:00:00.000Z' }
    const migrations = ['authors', 'entries', 'tags'].map((table, index) => {
      const sql = 'CREATE TABLE ' + table + ' (id integer)'
      return {
        file: '000' + (index + 1) + '_' + table + '.sql',
        sql,
        sha256: createHash('sha256').update(sql).digest('hex'),
      }
    })
    await db.store.updateApp(app.id, { neon_project_id: 'project', neon_main_branch_id: 'primary' })
    await db.store.updateEnv(env.id, {
      neon_branch_id: 'primary',
      db_url: 'postgres://[email protected]/journal',
    })
    ctx.appdb.ensureReader = jest.fn()
    ctx.appdb.applyMigration = jest.fn()
    jest.mocked(ctx.appdb.listApplied).mockResolvedValue([])
    await responseBody(
      await post(main + '/deployments', { kind: 'apply', manifest: manifest + '\n[database]', migrations }),
      202,
    )
    await ctx.orchestrator.runQueued(env.id)
    jest.mocked(ctx.appdb.listApplied).mockResolvedValue([
      { ...ledger, file: '0000_legacy.sql', sha256: 'historical' },
      { ...ledger, file: migrations[0]!.file, sha256: migrations[0]!.sha256 },
      { ...ledger, file: migrations[1]!.file, sha256: 'prior-content' },
    ])
    jest.mocked(ctx.appdb.query).mockResolvedValue({
      columns: [],
      rows: [
        ['entries', 'id', 'integer', 'NO', null],
        ['entries', 'title', 'text', 'YES', "'untitled'"],
      ],
      row_count: 2,
      elapsed_ms: 1,
      truncated: false,
    })
    const context = () => request(main + '/context').then((r) => responseBody(r))
    const ready = await context()
    expect(ready.database).toEqual({
      status: 'ready',
      branch: 'primary',
      tables: [
        {
          name: 'entries',
          columns: [
            { name: 'id', type: 'integer', nullable: false, default: null },
            { name: 'title', type: 'text', nullable: true, default: "'untitled'" },
          ],
        },
      ],
      migrations: [
        { file: '0000_legacy.sql', status: 'applied', ...ledger },
        { file: migrations[0]!.file, status: 'applied', ...ledger },
        { file: migrations[1]!.file, status: 'changed', ...ledger },
        { file: migrations[2]!.file, status: 'pending', deployment: null, applied_at: null },
      ],
    })
    expect(ready.variables).toContainEqual(
      expect.objectContaining({ name: 'DATABASE_URL', value: null, secret: true, resolved: true }),
    )
    expect(ready.next_actions).toEqual(
      expect.arrayContaining([
        expect.objectContaining({ id: 'migration_changed' }),
        expect.objectContaining({ id: 'pending_migrations' }),
      ]),
    )
    expect(
      (await responseBody(await post(main + '/findings/migration_changed/ack', { reason: 'reviewed migration' }), 400))
        .error.message,
    ).toContain('an error')
    jest.mocked(ctx.appdb.listApplied).mockRejectedValueOnce(new Error('database is starting'))
    const unavailable = await context()
    expect(unavailable.database).toMatchObject({
      status: 'unreachable',
      branch: 'primary',
      error: 'database is starting',
      tables: [],
      migrations: [],
    })
    expect(unavailable.next_actions).toContainEqual(expect.objectContaining({ id: 'db_unreachable' }))
    const sql = 'CREATE TABLE topics (id integer)'
    const nextFile = { file: '0004_topics.sql', sql, sha256: createHash('sha256').update(sql).digest('hex') }
    jest.mocked(ctx.appdb.listApplied).mockResolvedValue([])
    await responseBody(
      await post(main + '/deployments', {
        kind: 'apply',
        base_version: 1,
        manifest: manifest + '\n[database]',
        migrations: [...migrations, nextFile],
      }),
      202,
    )
    expect((await context()).database.migrations).toContainEqual({
      file: nextFile.file,
      status: 'pending',
      deployment: null,
      applied_at: null,
    })
    await db.store.updateEnv(env.id, { db_url: null })
    expect((await context()).database).toEqual({ status: 'not_provisioned', branch: null, tables: [], migrations: [] })
  })

  it.each([
    { service: 'static = "dist/"', command: null, staticDir: 'dist/', healthPath: null },
    { service: 'command = "node index.js"\nport = 3000', command: 'node index.js', staticDir: null, healthPath: '/' },
  ])('describes the default health path for $service', async ({ service, command, staticDir, healthPath }) => {
    await apply(manifest.slice(0, manifest.indexOf('command = ')) + service)
    await db.store.updateEnv(env.id, { public_url: 'https://journal.example.test' })
    const context = await responseBody(await request(main + '/context'))
    expect(context.services).toEqual([
      expect.objectContaining({ name: 'web', exposed: true, command, static: staticDir, health_path: healthPath }),
    ])
    expect(context.urls.health).toBe(healthPath ? 'https://journal.example.test/' : null)
    expect(await responseBody(await request(main + '/probe'))).toMatchObject({
      path: '/',
      url: 'https://journal.example.test/',
      reason: 'not_deployed',
    })
  })

  it('separates live runtime health and resource data from retained logs and stopped Box reports', async () => {
    await apply()
    const publicUrl = 'https://journal.example.test'
    await db.store.updateEnv(env.id, {
      active_box_id: 'box',
      box_url: 'https://box.example.test',
      public_url: publicUrl,
      access_override: 'org',
    })
    await db.store.updateDeployment(env.id, 1, { release: 1, box_id: 'box' })
    const at = new Date().toISOString()
    await db.store.appendLogs(env.id, [
      {
        ts: at,
        deployment: 1,
        source: 'build',
        level: 'error',
        line: 'npm notice New major version of npm available!',
      },
      { ts: at, deployment: 1, source: 'build', level: 'error', line: 'npm ERR! missing script: start' },
      { ts: at, deployment: 1, source: 'web', level: 'error', line: 'job failed' },
      { ts: '2000-01-01T00:00:00Z', source: 'web', level: 'error', line: 'expired error' },
    ])
    jest.spyOn(ctx.supervisor, 'health').mockResolvedValue({
      version: 2,
      ok: true,
      deployment: 1,
      services: [
        { name: 'web', state: 'running', health: 'healthy', memory_bytes: 900, restarts: 2, last_exit_code: 0 },
      ],
      box: { memory_total_bytes: 1000, memory_available_bytes: 50, disk_total_bytes: 1000, disk_free_bytes: 500 },
    })
    const live = await responseBody(await request('/context'))
    expect(live).toMatchObject({
      box: { id: 'box', state: 'running', usage: { memory_available_bytes: 50 } },
      urls: { health: publicUrl + '/health' },
      access: { level: 'org', source: 'online' },
      services: [expect.objectContaining({ memory_bytes: 900, health: 'healthy', restarts: 2 })],
    })
    expect(live.recent_errors.map((e: { line: string }) => e.line)).toEqual([
      'npm ERR! missing script: start',
      'job failed',
    ])
    expect(live.next_actions).toContainEqual(expect.objectContaining({ id: 'memory_low' }))
    expect(
      (await responseBody(await post(main + '/findings/memory_low/ack', { reason: 'reviewed usage' }), 400)).error
        .message,
    ).toContain('a warning')
    ctx.boxlite.stopBox = jest.fn()
    await ctx.resources.sleep('box')
    expect(await responseBody(await request('/context'))).toMatchObject({
      box: { state: 'stopped', usage: null },
      services: [expect.objectContaining({ state: 'stopped (Box asleep)', memory_bytes: null })],
    })
  })
})