Files
MikrotikManager/backend/scripts/acceptance/mcp-step-journal.test.mjs
T

177 lines
8.4 KiB
JavaScript

import assert from 'node:assert/strict'
import { appendFileSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import { resumeMcpSteps } from './mcp-step-journal.mjs'
import { resumeServerPoll } from './mcp-server-poll-steps.mjs'
const uuid = 'ec4c6a09-3c3b-4a37-a370-c8821321807c'
const connectionId = 'd0d96834-948b-4cea-81d8-d8f9dc5e1429'
const operationId = 'c2cc9f5d-6d62-43b5-a6d2-ba7bedbd4fc1'
const pollReceipt = { operationId, receiptId: uuid, nativeReads: 4, complete: true,
maintenanceComplete: true, configurationVerified: true, automaticReplay: false,
confirmedPublications: 22, completedPublications: 22, snapshot: { serverId: 3, status: 'online' } }
function options(t, steps) {
const dir = mkdtempSync(join(tmpdir(), 'mm-mcp-step-test-'))
t.after(() => rmSync(dir, { recursive: true }))
return { journal: join(dir, 'history.jsonl'), fixture: 'owned-test', steps }
}
test('resumes the failed read and preserves successful reads and failed attempts', async t => {
const calls = []
const config = options(t, [
{ id: 'first', kind: 'read', run: async () => { calls.push('first'); return null } },
{ id: 'second', kind: 'read', run: async ({ attempt }) => {
calls.push('second:' + attempt)
if (attempt === 1) throw Error('test failure')
return null
} },
])
assert.deepEqual(await resumeMcpSteps(config), { status: 'failed', step: 'second' })
assert.deepEqual(await resumeMcpSteps(config), { status: 'passed' })
assert.deepEqual(await resumeMcpSteps(config), { status: 'passed' })
assert.deepEqual(calls, ['first', 'second:1', 'second:2'])
assert.deepEqual(readFileSync(config.journal, 'utf8').trim().split('\n').map(line => JSON.parse(line).phase),
['fixture', 'started', 'passed', 'started', 'failed', 'retryable', 'started', 'passed'])
})
test('unknown apply awaits reconciliation and a verified receipt advances without resending', async t => {
let sends = 0
let verified = false
let sentKey
const config = options(t, [
{ id: 'plan', kind: 'plan', run: async () => uuid },
{ id: 'apply', kind: 'apply', run: async ({ evidence, accept, idempotencyKey }) => {
assert.equal(evidence.get('plan'), uuid)
sentKey = idempotencyKey
sends++
accept(uuid)
throw Error('lost reply')
}, reconcile: async ({ accepted, idempotencyKey }) => {
assert.equal(accepted, uuid)
assert.equal(idempotencyKey, sentKey)
return verified ? { state: 'verified', evidence: uuid } : { state: 'no-effect' }
} },
{ id: 'next', kind: 'read', run: async ({ evidence }) => { assert.equal(evidence.get('apply'), uuid); return null } },
])
assert.deepEqual(await resumeMcpSteps(config), { status: 'failed', step: 'apply' })
assert.deepEqual(await resumeMcpSteps(config), { status: 'reconcile', step: 'apply' })
verified = true
assert.deepEqual(await resumeMcpSteps(config), { status: 'passed' })
assert.equal(sends, 1)
})
test('cannot resume a different fixture or an altered ordered step list', async t => {
const config = options(t, [{ id: 'read', kind: 'read', run: async () => null }])
await resumeMcpSteps(config)
await assert.rejects(resumeMcpSteps({ ...config, fixture: 'other' }), /fixture or ordered step/)
await assert.rejects(resumeMcpSteps({ ...config, steps: [{ ...config.steps[0], id: 'other' }] }), /fixture or ordered step/)
})
test('refuses a stored retry marker after an accepted apply', async t => {
const config = options(t, [{ id: 'apply', kind: 'apply', async run({ accept }) {
accept(uuid)
throw new Error('lost reply')
} }])
await resumeMcpSteps(config)
appendFileSync(config.journal, JSON.stringify({ id: 'apply', attempt: 1, phase: 'retryable', accepted: null }) + '\n')
await assert.rejects(resumeMcpSteps(config), /Cannot retry an accepted MCP step/)
})
test('the poll scenario resumes owner review and then reads the same accepted operation', async t => {
const { journal, fixture } = options(t, [])
const calls = []
let approved = false
let running = true
let storageBusy = true
const config = { journal, fixture, serverId: 3, connectionId, assertApproved: async id => {
assert.equal(id, uuid)
if (!approved) throw Error('approval not visible')
}, async call(tool, args) {
calls.push(tool)
if (tool === 'mm_server_poll_plan') { assert.deepEqual(args, { serverId: 3 }); return { planId: uuid } }
if (tool === 'mm_change_apply') {
assert.equal(args.planId, uuid)
assert.match(args.idempotencyKey, /^acceptance-[0-9a-f]{64}$/)
return { id: operationId }
}
assert.deepEqual(args, { operationId })
if (storageBusy) throw Object.assign(new Error('MCP storage busy'), {
name: 'SdkHttpError', status: 503, data: { text: '{"code":"PROTOCOL_STORAGE_BUSY"}' },
})
return { id: operationId, plan_id: uuid, connection_id: connectionId,
...(running ? { state: 'running' } : { state: 'applied', verification: 'passed',
steps: [{ state: 'verified', result: pollReceipt }] }) }
} }
assert.equal((await resumeServerPoll(config)).step, 'manager.plan-approved')
approved = true
assert.equal((await resumeServerPoll(config)).step, 'mm_operation_get')
storageBusy = false
assert.equal((await resumeServerPoll(config)).step, 'mm_operation_get')
running = false
assert.deepEqual(await resumeServerPoll(config), { status: 'passed' })
await assert.rejects(resumeServerPoll({ ...config, connectionId: uuid }), /fixture or ordered step/)
assert.deepEqual(calls, ['mm_server_poll_plan', 'mm_change_apply', 'mm_operation_get', 'mm_operation_get', 'mm_operation_get'])
const failures = readFileSync(journal, 'utf8').trim().split('\n').map(line => JSON.parse(line))
.filter(entry => entry.id === 'mm_operation_get' && entry.phase === 'failed')
assert.deepEqual(failures.map(entry => entry.code), ['PROTOCOL_STORAGE_BUSY', 'POLL_PENDING'])
})
test('recovers a lost poll apply response by the exact connection, plan and idempotency key', async t => {
const { journal, fixture } = options(t, [])
let key, sends = 0, wrongBinding = true
const config = { journal, fixture, serverId: 3, connectionId, assertApproved: async () => {},
async findAcceptedOperation(binding) {
assert.equal(binding.connectionId, connectionId)
assert.equal(binding.planId, uuid)
assert.equal(binding.idempotencyKey, key)
return operationId
},
async call(tool, args) {
if (tool === 'mm_server_poll_plan') return { planId: uuid }
if (tool === 'mm_change_apply') {
sends++
key = args.idempotencyKey
throw Error('apply response lost')
}
return { id: operationId, plan_id: uuid, connection_id: wrongBinding ? uuid : connectionId,
state: 'applied', verification: 'passed', steps: [{ state: 'verified', result: pollReceipt }] }
},
}
assert.equal((await resumeServerPoll(config)).step, 'mm_change_apply')
assert.equal((await resumeServerPoll(config)).step, 'mm_operation_get')
wrongBinding = false
assert.deepEqual(await resumeServerPoll(config), { status: 'passed' })
assert.equal(sends, 1)
})
test('rejects incomplete or misbound terminal poll receipts before recording success', async t => {
const { journal, fixture } = options(t, [])
const calls = []
const receipts = [
{ ...pollReceipt, operationId: uuid },
{ ...pollReceipt, receiptId: undefined },
{ ...pollReceipt, confirmedPublications: 21 },
{ ...pollReceipt, confirmedPublications: 0, completedPublications: 0 },
{ ...pollReceipt, maintenanceComplete: false },
{ ...pollReceipt, snapshot: { serverId: 4, status: 'online' } },
pollReceipt,
]
const config = { journal, fixture, serverId: 3, connectionId, assertApproved: async () => {},
async call(tool, args) {
calls.push(tool)
if (tool === 'mm_server_poll_plan') return { planId: uuid }
if (tool === 'mm_change_apply') return { id: operationId }
assert.deepEqual(args, { operationId })
return { id: operationId, plan_id: uuid, connection_id: connectionId, state: 'applied', verification: 'passed',
steps: [{ state: 'verified', result: receipts.shift() }] }
},
}
for (let i = 0; i < 6; i++) {
assert.deepEqual(await resumeServerPoll(config), { status: 'failed', step: 'mm_operation_get' })
}
assert.deepEqual(await resumeServerPoll(config), { status: 'passed' })
assert.deepEqual(calls, ['mm_server_poll_plan', 'mm_change_apply', ...Array(7).fill('mm_operation_get')])
})