Files
MikrotikManager/backend/src/modules/mcp/flow-envelope-allowance.test.ts
T

38 lines
2.7 KiB
TypeScript

import assert from "node:assert/strict"
import { test } from "node:test"
import { planFlowEnvelope } from "./flow-envelope-allowance.js"
import { boundedToolError, boundedToolResult } from "./result-budget.js"
import { deliverRegisteredToolResult } from "./result-delivery.js"
const info = { name: "MikrotikManager", version: "1.0.0" }
const read = { id: "traffic.flow.fixture", effect: "read" as const, hasRead: true, hasPrepare: false }
test("same2MiB/8MiB caps, exact id/framing, existing1024 reserve and B1 ceiling", () => {
for (const cap of [2, 8].map(value => value * 1048576)) for (const era of ["legacy", "modern"] as const) {
const allowance = planFlowEnvelope("я\\\"".repeat(100), era, cap, info)
assert(allowance.readByteLimit <= 1048576)
assert(allowance.readByteLimit + allowance.reservedEnvelopeBytes <= cap)
assert.equal(allowance.reservedEnvelopeBytes, allowance.terminalEnvelopeBytes + 1024)
}
assert(planFlowEnvelope("a".repeat(1048576 - 2), "modern", 2 * 1048576, info).readByteLimit < 1048576)
})
test("read narrowing never produces empty healthy quality or fake metadata", () => {
const decision = boundedToolResult({ quality: "unknown", metadata: { received: 2, dropped: 1 }, rows: "x".repeat(5000) }, "read", undefined, 8192)
assert.equal(decision.kind, "result")
if (decision.kind === "result") { assert.equal(decision.result.isError, true); assert.equal(decision.result.structuredContent, undefined); assert(!JSON.stringify(decision.result).includes('"quality"')) }
})
test("read allowance is validated before effects and cannot change applied outcome budget", async () => {
let invoked = 0
for (const contract of [read, { ...read, id: "changes.apply", effect: "write" as const }]) {
const result = await deliverRegisteredToolResult(contract, async () => { invoked++; return {} }, () => boundedToolError("INTERNAL_ERROR", "ошибка"), undefined, 100)
assert.equal(result.isError, true)
}
assert.equal(invoked, 0)
})
test("bounded invocation error is retained too; fitting quality and metadata stay intact", async () => {
const charged: number[] = []
const error = await deliverRegisteredToolResult(read, async () => { throw Error("private") }, () => boundedToolError("STATE_UNAVAILABLE", "Источник временно недоступен"), bytes => charged.push(bytes), 8192)
assert.equal(error.isError, true); assert.equal(charged[0], Buffer.byteLength(JSON.stringify(error)))
const dto = { quality: "unknown", metadata: { received: 2, dropped: 1 } }
const fit = await deliverRegisteredToolResult(read, async () => dto, () => { throw Error("unexpected") }, undefined, 8192)
assert.deepEqual(fit.structuredContent, { result: dto })
})