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

120 lines
6.4 KiB
JavaScript

import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import { closeSync, constants, fstatSync, fsyncSync, openSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'
import { isDeepStrictEqual } from 'node:util'
const key = /^[a-z0-9][a-z0-9_.:-]{0,127}$/i
const evidenceId = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i
const errorCode = /^[A-Z][A-Z0-9_]{0,63}$/
const validEvidence = (receipt, kind) => receipt === null ? kind === 'read' : typeof receipt === 'string' && evidenceId.test(receipt)
/** A test journal only. The caller owns the fixture and all reconciliation reads. */
export async function resumeMcpSteps({ journal, fixture, steps }) {
assert(key.test(fixture))
const scope = steps.map(({ id, kind }) => ({ id, kind }))
assert(scope.length && new Set(scope.map(step => step.id)).size === scope.length)
assert(scope.every(({ id, kind }) => key.test(id) && ['read', 'plan', 'apply'].includes(kind)))
// One process owns a journal at a time. A leftover lock requires operator reconciliation.
const lock = openSync(journal + '.lock', 'wx', 0o600)
let records
try {
let fd
try {
fd = openSync(journal, constants.O_RDWR | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600)
assert(fstatSync(fd).isFile(), 'Test journal must be a regular file')
const raw = readFileSync(fd, 'utf8')
assert(!raw || raw.endsWith('\n'), 'Truncated test receipt')
records = raw.trimEnd().split('\n').filter(Boolean).map(line => JSON.parse(line))
const header = { phase: 'fixture', fixture, steps: scope }
const append = entry => {
writeFileSync(fd, JSON.stringify(entry) + '\n', 'utf8')
fsyncSync(fd)
records.push(entry)
}
if (!records.length) append(header)
assert(isDeepStrictEqual(records[0], header), 'Test fixture or ordered step list changed')
const state = new Map()
let cursor = 0
for (const entry of records.slice(1)) {
const previous = state.get(entry.id)
assert(scope[cursor]?.id === entry.id, 'Unexpected test receipt order')
if (entry.phase === 'started') {
assert(!previous || previous.phase === 'retryable', 'Unexpected resumed dispatch')
assert(entry.attempt === (previous?.attempt ?? 0) + 1, 'Unexpected test attempt')
} else {
assert(['started', 'accepted', 'failed'].includes(previous?.phase) && entry.attempt === previous.attempt, 'Unbound test receipt')
assert(['passed', 'retryable', 'accepted', 'failed'].includes(entry.phase), 'Unknown test receipt')
if (entry.phase === 'accepted') {
assert(previous.phase === 'started' && scope[cursor].kind !== 'read' &&
validEvidence(entry.evidence, scope[cursor].kind), 'Invalid MCP acceptance receipt')
}
if (entry.phase === 'failed') {
assert(previous.phase !== 'failed' && typeof entry.code === 'string' && errorCode.test(entry.code), 'Invalid failure receipt')
assert(entry.accepted === (previous.phase === 'accepted' ? previous.evidence : null), 'MCP acceptance receipt changed')
}
if (entry.phase === 'passed') {
assert(validEvidence(entry.evidence, scope[cursor].kind), 'Invalid stored MCP receipt ID')
const accepted = previous.phase === 'accepted' ? previous.evidence : previous.accepted
assert(!accepted || accepted === entry.evidence, 'MCP acceptance receipt changed')
cursor++
}
if (entry.phase === 'retryable') {
assert(entry.accepted === null && (previous.phase === 'started' ||
previous.phase === 'failed' && previous.accepted === null), 'Cannot retry an accepted MCP step')
}
}
state.set(entry.id, entry)
}
const evidence = new Map([...state].filter(([, entry]) => entry.phase === 'passed').map(([id, entry]) => [id, entry.evidence]))
const attemptKey = (step, attempt) => 'acceptance-' + createHash('sha256')
.update(JSON.stringify([fixture, step.id, step.kind, attempt])).digest('hex')
const record = (step, attempt, phase, details = {}) => append({ id: step.id, attempt, phase, ...details })
const complete = (step, attempt, receipt) => {
assert(validEvidence(receipt, step.kind), 'Invalid MCP receipt ID')
record(step, attempt, 'passed', { evidence: receipt })
evidence.set(step.id, receipt)
}
for (const step of steps.slice(cursor)) {
const previous = state.get(step.id)
let attempt = previous?.attempt ?? 0
if (previous && ['started', 'accepted', 'failed'].includes(previous.phase)) {
const accepted = previous.phase === 'accepted' ? previous.evidence : previous.accepted ?? null
const result = step.kind === 'read' ? { state: 'no-effect' } :
await step.reconcile?.({ attempt, accepted, idempotencyKey: attemptKey(step, attempt), evidence: new Map(evidence) })
if (result?.state === 'verified') {
assert(!accepted || accepted === result.evidence, 'Reconciled a different MCP receipt')
complete(step, attempt, result.evidence)
continue
}
if (accepted || result?.state !== 'no-effect') return { status: 'reconcile', step: step.id }
record(step, attempt, 'retryable', { accepted })
}
attempt++
record(step, attempt, 'started')
let receipt
let accepted = null
try {
receipt = await step.run({ attempt, idempotencyKey: attemptKey(step, attempt), evidence: new Map(evidence), accept(id) {
assert(accepted === null && step.kind !== 'read' && validEvidence(id, step.kind), 'Invalid MCP acceptance receipt')
record(step, attempt, 'accepted', { evidence: id })
accepted = id
} })
} catch (error) {
const code = typeof error?.code === 'string' && errorCode.test(error.code) ? error.code : 'TEST_STEP_FAILED'
record(step, attempt, 'failed', { code, accepted })
return { status: 'failed', step: step.id }
}
assert(!accepted || accepted === receipt, 'Verified a different MCP receipt')
complete(step, attempt, receipt)
}
return { status: 'passed' }
} finally {
if (fd !== undefined) closeSync(fd)
}
} finally {
closeSync(lock)
unlinkSync(journal + '.lock')
}
}