import { prepareRoutingControllerBaseline, advanceRoutingControllerBaseline } from "./routing-controller-baseline.js" import { saveControllerProfileCas, publishControllerState } from "./routing-controller-fence.js" import { withConfigMutationLock } from "../../services/config-mutation-lock.js" import { routerClient } from "./resources.js" import assert from "node:assert/strict" import { createServer } from "node:http" import { randomUUID } from "node:crypto" import { setTimeout as delay } from "node:timers/promises" import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp" import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing" import { pool } from "../../db/index.js" import type { AuthUser } from "../../lib/permissions.js" import { managedComment } from "../../managed-markers.js" import { compileManagedFilterRules } from "../../services/filter-rules-write-model.js" import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "./store.js" import { invokeMcpTool } from "./runtime.js" import { requireRecentPath } from "./path-verification.js" import { attestRoutingFixture } from "../../test/mcp-routing-fixture.js" import { approvePlan, applyPlan, loadPlan, publicPlan } from "./runtime.js" import { tickRoutingProfiles } from "./routing-profiles.js" import { assertIdentifiedRoutingCompletion } from "./routing-reservation-store.js" /** Diagnostic paths only; never print a matching private value or native row. */ function privateMarkerPaths(value: unknown, path = "$", found: string[] = []): string[] { if (typeof value === "string" && value.includes("NEVER_")) found.push(path) else if (Array.isArray(value)) value.forEach((item, index) => privateMarkerPaths(item, path + "[" + index + "]", found)) else if (value && typeof value === "object") for (const [key, item] of Object.entries(value)) privateMarkerPaths(item, path + "." + key, found) return found } /** Hook for the disposable SQL+HTTP integration suite; no real router writes. */ export async function acceptMainBaselineRuntime(actor: AuthUser) { const sid = 130 const writerActor: AuthUser = { ...actor, permissions: [...new Set([...actor.permissions, "mm:filters:write"])] } let writes = 0, requests = 0, secondConnection = false, counter = 0 let afterRead: (() => Promise) | undefined let table = "policy-only" const inputChain = "bgp-in" let inherited = false, parentChain = "bgp-in", oversized = false, afi = "ip", interfaceList = false let separateProbeVrf = false, bgpVrfDisabled = false const route: Record = { ".id": "*r", "dst-address": "192.0.2.1/32", "routing-table": "main", disabled: "false", comment: managedComment("recursive"), opaque: "NEVER_ROUTE_CONTEXT_NATIVE" } const body = compileManagedFilterRules([{ community: "65000:10", gateway: "192.0.2.1", outIface: "", action: "route", description: "" }]) let policyBody = body, changePolicyAfterTrace = false let policyComment = managedComment("filter"), mainWriteEnabled = false const reserveRoute = { ...route, ".id": "*r2", "dst-address": "192.0.2.9/32" } const connection = () => ({ ".id": "*c", name: "peer", disabled: "false", instance: "default", vrf: "main", "routing-table": table, afi, ...(!inherited ? { "input.filter": inputChain } : {}), "output.filter-chain": "", templates: inherited ? "parent" : "" }) const collections = (path: string): Record[] => ({ "/routing/table": [{ ".id": "*tm", name: "main", fib: "true", dynamic: "true" }, { ".id": "*tp", name: "policy-only", fib: "true" }, ...(separateProbeVrf ? [{ ".id": "*td", name: "probe-only", fib: "true", dynamic: "true" }] : [])], "/ip/vrf": [...(interfaceList ? [{ ".id": "*vl", name: "listed", interfaces: "WAN-LIST", disabled: "false" }] : []), ...(separateProbeVrf ? [{ ".id": "*vd", name: "probe-only", interfaces: "wan", disabled: "false" }] : []), { ".id": "*v", name: "main", interfaces: "all", disabled: String(bgpVrfDisabled) }], "/routing/bgp/connection": [connection(), ...(secondConnection ? [{ ...connection(), ".id": "*c2", "routing-table": "main" }] : [])], "/routing/bgp/instance": [{ ".id": "*i", name: "default", vrf: "main", "routing-table": "main", disabled: "false" }], "/routing/bgp/template": inherited ? [{ ".id": "*t", name: "parent", disabled: "false", "input.filter": parentChain }] : [], "/routing/filter/rule": [{ ".id": "*f", chain: "bgp-in", disabled: "false", rule: policyBody, comment: policyComment, opaque: "NEVER_ROUTE_CONTEXT_TARGET_OPAQUE" }], "/ip/route": mainWriteEnabled ? [route, reserveRoute] : [route], "/interface": ["wan", "hop", "target"].map((name, index) => ({ ".id": "*if" + index, name, disabled: "false", running: "true", "rx-byte": String(++counter) })), "/ip/address": ["wan", "hop", "target"].map((name, index) => ({ ".id": "*a" + index, interface: name, address: "192.0.2." + (index + 1) + "/32", disabled: "false", invalid: "false" })), } as Record[]>)[path] ?? [] const probeVrfs: string[] = [] const router = createServer(async (req, res) => { requests++; res.setHeader("content-type", "application/json") let raw = ""; for await (const chunk of req) raw += chunk const args = raw ? JSON.parse(raw) : {}, path = (req.url ?? "").replace(/^\/rest/, "") if (afterRead) { const hook = afterRead; afterRead = undefined; await hook() } if (oversized) { res.end(JSON.stringify({ value: "я".repeat(600000) })); return } if (mainWriteEnabled && req.method === "PATCH" && path === "/routing/filter/rule/*f") { assert.equal(args.chain, "bgp-in"); assert.equal(args.disabled, "no") writes++; policyBody = args.rule; policyComment = args.comment res.end(JSON.stringify(collections("/routing/filter/rule")[0])); return } if (req.method === "GET") { res.end(JSON.stringify(collections(path))); return } if (req.method === "POST" && path.endsWith("/get")) { const row = collections(path.slice(0, -4)).find(row => row[".id"] === args[".id"]), value = row?.[args["value-name"]] res.end(JSON.stringify(value === undefined ? [] : { ret: value })); return } if (req.method === "POST" && path === "/tool/ping") { probeVrfs.push(args.vrf); res.end(JSON.stringify([{ sent: "3", received: "3", "packet-loss": "0", "avg-rtt": "1ms" }])); return } if (req.method === "POST" && path === "/tool/traceroute") { probeVrfs.push(args.vrf) if (changePolicyAfterTrace) { changePolicyAfterTrace = false; policyBody = compileManagedFilterRules([{ community: "65000:10", gateway: "192.0.2.9", outIface: "", action: "route", description: "" }]) } res.end(JSON.stringify(["192.0.2.2", "192.0.2.3"].map(address => ({ address, sent: "1", loss: "0" })))); return } writes++; res.statusCode = 405; res.end("{}") }) await new Promise(resolve => router.listen(0, "127.0.0.1", resolve)) let connectionId: string | undefined, writeConnectionId: string | undefined try { await pool.query("INSERT INTO servers(id,name,host,port,use_ssl,password) VALUES($1,'route-context','127.0.0.1',$2,false,'NEVER_ROUTE_CONTEXT_PASSWORD')", [sid, (router.address() as { port: number }).port]) const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Route context", mode: "observer", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:read"], scope: { serverIds: [sid], operationIds: ["routing.analyze", "routing.path.verify"], allowGlobal: false }, limits: { callsPerMinute: 120 } }), actor) connectionId = access.connection.id const principal = await authenticateMcpToken(access.token) const base = routeAiProfileSchema.parse({ name: "table is not VRF", serverId: sid, community: "65000:10", family: "ipv4", table: "policy-only", probeVrf: "main", bgpContext: { connectionId: "*c", instance: "default", inputChain: "bgp-in" }, candidates: [{ id: "a", jumpHostId: sid, exitNodeId: sid, wanInterface: "wan", downstreamInterface: "hop", gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*r" }, controlProbe: { targetInterface: "target", expectedHops: [{ serverId: sid, interface: "hop" }, { serverId: sid, interface: "target" }] } }] }) const analyze = async (profile = base) => await invokeMcpTool(principal, "mm_route_optimizer_analyze", { profile }) as { currentCandidateId: string | null; executionAvailable: boolean; contextVerified: boolean; sharedConnectionIds: string[]; bgpVrf: string | null; probeVrf: string } const result = await analyze() assert.equal(result.contextVerified, true); assert.equal(result.currentCandidateId, "a"); assert.equal(result.executionAvailable, false) assert.ok(!JSON.stringify(result).includes("NEVER_")) route["dst-address"] = "192.0.2.1/24" assert.equal((await analyze()).currentCandidateId, null, "a covering route is not the registered recursive host route") route["dst-address"] = "192.0.2.1/32" afi = "ipv6" assert.equal((await analyze()).currentCandidateId, null, "the selected BGP binding must carry the requested address family") afi = "ip"; interfaceList = true const unavailableProbe = await analyze() as Awaited> & { candidateDiagnostics: Array<{ candidateId: string; status: string }> } assert.equal(unavailableProbe.candidateDiagnostics[0].status, "candidate-unavailable", "unknown earlier VRF interface-list membership cannot fall through to main all") interfaceList = false inherited = true assert.equal((await analyze()).currentCandidateId, "a", "explicit binding may be inherited from a uniquely resolved template") parentChain = "other" assert.equal((await analyze()).currentCandidateId, null, "different inherited input-chain is not the selected profile") parentChain = "bgp-in"; inherited = false; secondConnection = true assert.deepEqual((await analyze()).sharedConnectionIds.sort(), ["*c", "*c2"]) secondConnection = false const wrong = routeAiProfileSchema.parse({ ...base, bgpContext: { ...base.bgpContext, instance: "other" } }) assert.equal((await analyze(wrong)).currentCandidateId, null) assert.equal((await analyze(routeAiProfileSchema.parse({ ...base, table: "main" }))).currentCandidateId, null) const duplicate = routeAiProfileSchema.parse({ ...base, candidates: [...base.candidates, { ...base.candidates[0], id: "same-gateway" }] }) assert.equal((await analyze(duplicate)).currentCandidateId, null, "same gateway does not identify a unique candidate") const check = async (profile = base) => await invokeMcpTool(principal, "mm_route_path_verify", { profile, candidateId: "a" }) as { id: string; status: string; returnPathVerified: boolean } separateProbeVrf = true const distinct = routeAiProfileSchema.parse({ ...base, probeVrf: "probe-only", bgpContext: { ...base.bgpContext, vrf: "main" } }) const separated = await analyze(distinct) assert.equal(separated.contextVerified, true); assert.equal(separated.currentCandidateId, "a"); assert.equal(separated.executionAvailable, false) assert.equal(separated.bgpVrf, "main"); assert.equal(separated.probeVrf, "probe-only") assert.equal((await analyze(routeAiProfileSchema.parse({ ...distinct, bgpContext: { ...distinct.bgpContext, vrf: "probe-only" } }))).currentCandidateId, null, "wrong explicit BGP transport VRF cannot match merely because the probe uses it") const distinctCheck = await check(distinct) assert.equal(distinctCheck.status, "passed"); assert.equal(distinctCheck.returnPathVerified, false) assert.deepEqual(probeVrfs, ["probe-only", "probe-only"]) assert.equal(await requireRecentPath(distinct, "a", connectionId), distinctCheck.id) bgpVrfDisabled = true await assert.rejects(analyze(distinct), (error: { code?: string }) => error.code === "STATE_UNAVAILABLE", "BGP transport VRF is checked independently of the enabled probe VRF") bgpVrfDisabled = false; separateProbeVrf = false; probeVrfs.length = 0 changePolicyAfterTrace = true assert.equal((await check()).status, "unknown", "An owned policy change during the probe cannot retain passed status") policyBody = body; probeVrfs.length = 0 const passed = await check() assert.equal(passed.status, "passed"); assert.equal(passed.returnPathVerified, false); assert.deepEqual(probeVrfs, ["main", "main"]) assert.equal(await requireRecentPath(base, "a", connectionId), passed.id) route.opaque = "changed dependency" await assert.rejects(requireRecentPath(base, "a", connectionId), (error: { code?: string }) => error.code === "MEASUREMENT_UNKNOWN") route.opaque = "NEVER_ROUTE_CONTEXT_NATIVE" await pool.query("UPDATE mcp_path_checks SET evidence=jsonb_set(evidence,'{status}','\"failed\"') WHERE id=$1", [passed.id]) await assert.rejects(requireRecentPath(base, "a", connectionId)) await check() const beforeEndpoint = requests await pool.query("UPDATE servers SET password='NEVER_CHANGED_PASSWORD' WHERE id=$1", [sid]) await assert.rejects(requireRecentPath(base, "a", connectionId), (error: { code?: string }) => error.code === "STATE_CONFLICT") assert.equal(requests, beforeEndpoint, "prior source proof rejects changed endpoint before any native request") oversized = true await assert.rejects(analyze(), (error: Error & { code?: string }) => ["LIMIT_EXCEEDED", "STATE_UNAVAILABLE"].includes(error.code ?? "") && !error.message.includes("я")) oversized = false afterRead = () => setConnectionStatus(connectionId!, "paused", actor) await assert.rejects(analyze()) assert.equal(writes, 0) const saved = JSON.stringify((await pool.query("SELECT result FROM mcp_requests WHERE connection_id=$1", [connectionId])).rows) assert.ok(!saved.includes("NEVER_")) // Exercise the actual service through a human-approved runtime plan. The // legacy owned comment intentionally differs from the current server name. table = "main"; mainWriteEnabled = true; policyComment = managedComment("NEVER_LEGACY_OWNED_COMMENT") const legacyComment = policyComment const withoutProbe = (({ controlProbe: _probe, ...candidate }) => candidate)(base.candidates[0]) const mainProfile = routeAiProfileSchema.parse({ ...base, table: "main", candidates: [withoutProbe, { ...withoutProbe, id: "b", gateway: "192.0.2.9", gatewayRef: { resource: "ipv4_route", id: "*r2" } }] }) for (const iface of ["wan", "hop"]) { const observationId = randomUUID() await pool.query("INSERT INTO mcp_routing_observations(id,src_server_id,dst_server_id,src_interface,dst_interface,family,routing_table,ping_ms,loss_pct,dl_mbps,ul_mbps,ping_at,bandwidth_at,context_verified,source) VALUES($1,$2,$2,$3,'peer','ipv4','main',1,0,100,100,now(),now(),true,'fixture')", [observationId, sid, iface]) await attestRoutingFixture(observationId) } const writeAccess = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Main Route context write", mode: "approval", expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:network:read", "mm:network:write", "mm:filters:write"], scope: { serverIds: [sid], operationIds: ["routing.analyze", "routing.community.switch", "routing.profiles.save", "routing.profiles.read", "routing.controller.read", "routing.controller.update", "routing.path.verify"], allowGlobal: false }, limits: { callsPerMinute: 120 } }), writerActor) writeConnectionId = writeAccess.connection.id const writer = await authenticateMcpToken(writeAccess.token) const automatic = routeAiProfileSchema.parse({ ...mainProfile, autoRecovery: true, candidates: mainProfile.candidates.map(candidate => ({ ...candidate, controlProbe: base.candidates[0].controlProbe })) }) const unavailable = await invokeMcpTool(writer, "mm_route_optimizer_analyze", { profile: automatic }) as { executionAvailable: boolean; executionReason: string } assert.equal(unavailable.executionAvailable, false); assert.equal(unavailable.executionReason, "ROUTE_RECOVERY_EXECUTOR_UNAVAILABLE") await assert.rejects(invokeMcpTool(writer, "mm_route_optimizer_plan", { profile: automatic, candidateId: "b" }), (error: Error & { code?: string }) => error.code === "UNSUPPORTED_CAPABILITY" && error.message.includes("ROUTE_RECOVERY_EXECUTOR_UNAVAILABLE")) await assert.rejects(invokeMcpTool(writer, "mm_route_profile_save_plan", { profile: automatic, enabled: true, expiresAt: new Date(Date.now() + 900000).toISOString() }), (error: Error & { code?: string }) => error.code === "UNSUPPORTED_CAPABILITY" && error.message.includes("ROUTE_RECOVERY_EXECUTOR_UNAVAILABLE")) assert.equal(writes, 0) const waitOperation = async (id: string) => { for (let attempt=0; attempt<400; attempt++) { const row=(await pool.query("SELECT state,error_code FROM mcp_operations WHERE id=$1",[id])).rows[0] if(row && !["pending","running"].includes(row.state))return row await delay(20) } throw Error("Targeted runtime operation timeout") } const activate = async (profileId?: string) => { const grantExpiresAt=new Date(Date.now()+600000).toISOString() const prepared=await invokeMcpTool(writer,"mm_route_profile_save_plan",{...(profileId?{profileId}:{}),profile:mainProfile,enabled:true,expiresAt:grantExpiresAt}) as {planId:string} await approvePlan(prepared.planId,writerActor,true) return {planId:prepared.planId,grantExpiresAt} } // Both distinct NEW profile plans are publicly prepared and approved while // no profile is enabled. A later activation must recheck overlap at execute. const firstProfileId=randomUUID(),secondProfileId=randomUUID() const activation=await activate(firstProfileId),overlappingActivation=await activate(secondProfileId) assert.equal((await pool.query("SELECT count(*)::int AS count FROM mcp_routing_profiles WHERE connection_id=$1",[writeConnectionId])).rows[0].count,0) const activationOperation=await applyPlan(writer,activation.planId,"runtime-main-baseline-enable") assert.equal((await waitOperation(activationOperation.id)).state,"applied") let controller=(await pool.query("SELECT * FROM mcp_routing_profiles WHERE connection_id=$1",[writeConnectionId])).rows[0] assert.equal(controller.enabled,true);assert.equal(controller.version,1) assert.equal(controller.state.baseline.packet.candidateId,"a") assert.ok(controller.state.baseline.proof) assert.equal(controller.id,firstProfileId) const firstBaselineProof=controller.state.baseline.proof,beforeOverlapNative=writes // Terminal state publication precedes lease-finally cleanup. Observe the // REAL application lease release so rejection below proves overlap, not a // transient lock collision. No native or authority deadline is extended. const leaseProbe=await pool.connect();let acquired=false,unsafe=false try { const deadline=Date.now()+5000 while(!(acquired=(await leaseProbe.query("SELECT pg_try_advisory_lock(hashtextextended('mm-config:application',0)) AS acquired")).rows[0].acquired)){ assert(Date.now()error instanceof Error && "code" in error && error.code==="STATE_CONFLICT","A new overlapping prepare must refuse while the first profile is enabled") assert.equal((await pool.query("SELECT count(*)::int AS count FROM mcp_routing_profiles WHERE connection_id=$1 AND enabled",[writeConnectionId])).rows[0].count,1) assert.equal(writes,beforeOverlapNative) console.log("TARGETED_PUBLIC_OVERLAP_TOCTOU_NATIVE0_PASS",JSON.stringify({newProfilesApprovedBeforeEitherEnabled:2,firstActivationApplied:true,secondTerminalCode:overlapTerminal.error_code,secondCasRows:0,enabledProfiles:1,newPrepareRefused:true,nativeWrites:0})) const publicProfile=await invokeMcpTool(writer,"mm_route_profiles_list",{}) assert.ok(!JSON.stringify(publicProfile).includes(controller.state.baseline.proof),"Public profile DTO must omit baseline proof") const beforeControllerRead = requests const controllerView = await invokeMcpTool(writer, "mm_route_controller_get", { profileId: controller.id }) as { id: string; enabled: boolean; state: Record } assert.equal(controllerView.id, controller.id) assert.equal(controllerView.enabled, true) assert.equal(controllerView.state.baseline, undefined) const hiddenConfig = { ...mainProfile, candidates: mainProfile.candidates.map(candidate => ({ ...candidate, exitNodeId: sid + 1000 })) } await pool.query("UPDATE mcp_routing_profiles SET config=$2::jsonb WHERE id=$1", [controller.id, JSON.stringify(hiddenConfig)]) try { const notFound = (error: unknown) => error instanceof Error && "code" in error && error.code === "NOT_FOUND" await assert.rejects(invokeMcpTool(writer, "mm_route_controller_get", { profileId: controller.id }), notFound) await assert.rejects(invokeMcpTool(writer, "mm_route_profile_save_plan", { profileId: controller.id, profile: mainProfile, enabled: false, expiresAt: activation.grantExpiresAt }), notFound) } finally { await pool.query("UPDATE mcp_routing_profiles SET config=$2::jsonb WHERE id=$1", [controller.id, JSON.stringify(mainProfile)]) } assert.equal(requests, beforeControllerRead) console.log("✓ Route AI controller: exact public state, hidden dependencies reject read and replacement before RouterOS") // Explicit out-of-application drift after enrollment, before a trusted // private host prepares another persistent plan. MAC/authority stay valid. policyComment=legacyComment+"-external-drift" const driftMainPlan=await invokeMcpTool(writer,"mm_route_optimizer_plan",{profile:mainProfile,candidateId:"b"},undefined,{persistentRoutingProfile:{id:controller.id,version:controller.version}}) as {planId:string} await approvePlan(driftMainPlan.planId,writerActor,true) const beforeMainDrift=writes,driftMainOperation=await applyPlan(writer,driftMainPlan.planId,"main-private-prepared-after-external-drift") assert.notEqual((await waitOperation(driftMainOperation.id)).state,"applied") assert.equal(writes,beforeMainDrift,"Authenticated private MAIN input prepared after external drift must send0nativewrites") assert.equal((await pool.query("SELECT configuration_sealed FROM mcp_operation_checkpoints WHERE operation_id=$1",[driftMainOperation.id])).rows[0].configuration_sealed,null) policyComment=legacyComment console.log("TARGETED_MAIN_PRIVATE_DRIFT_NATIVE0_PASS") const plan = await invokeMcpTool(writer, "mm_route_optimizer_plan", { profile: mainProfile, candidateId: "b" },undefined,{persistentRoutingProfile:{id:controller.id,version:controller.version}}) as { planId: string } assert.deepEqual(privateMarkerPaths(plan), [], "initial plan response contains private native data") assert.deepEqual(privateMarkerPaths(await publicPlan(await loadPlan(plan.planId))), [], "retrieved public plan contains private native data") assert.equal((await pool.query("SELECT evidence FROM mcp_plans WHERE id=$1", [plan.planId])).rows[0].evidence.recovery, undefined) await approvePlan(plan.planId, writerActor, true) // Actual human-approved MAIN source joins the common admission profile-row // lock BEFORE its operation/intent/native write. No synthetic MAIN seal. const profileEditor = await pool.connect() await profileEditor.query("BEGIN") const editorPid = Number((await profileEditor.query("SELECT pg_backend_pid() AS pid")).rows[0].pid) await profileEditor.query("SELECT id FROM mcp_routing_profiles WHERE id=$1 FOR UPDATE", [controller.id]) const admission = applyPlan(writer, plan.planId, "route-context-main-comment") void admission.catch(() => {}) let admissionError: unknown, operation: Awaited | undefined, blocked = false try { for (let attempt = 0; attempt < 150; attempt++) { blocked = (await pool.query("SELECT pid FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND $1::int=ANY(pg_blocking_pids(pid)) AND query LIKE 'SELECT id FROM mcp_routing_profiles WHERE id=%FOR UPDATE'", [editorPid])).rowCount === 1 if (blocked) break await delay(20) } assert(blocked, "Actual MAIN admission must wait on the same profile owner lock") assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM mcp_operations WHERE plan_id=$1", [plan.planId])).rows[0].n), 0) assert.equal(writes, beforeMainDrift, "Profile edit lock must precede operation intent/native dispatch") } catch (error) { admissionError = error } finally { try { await profileEditor.query("ROLLBACK") } catch (error) { admissionError ??= error } profileEditor.release() try { operation = await admission } catch (error) { admissionError ??= error } } if (admissionError) throw admissionError assert(operation) console.log("TARGETED_MAIN_COMMON_PROFILE_ADMISSION_LOCK_PASS") let applied: { state: string; error_code?: string } | undefined for (let attempt = 0; attempt < 300; attempt++) { applied = (await pool.query("SELECT state,error_code FROM mcp_operations WHERE id=$1", [operation.id])).rows[0] if (applied && !["pending", "running"].includes(applied.state)) break await delay(30) } assert.equal(applied?.state, "applied", JSON.stringify(applied)); assert.equal(writes, 1); assert.equal(policyComment, legacyComment) const checkpoint=(await pool.query("SELECT configuration_sealed,configuration_proof FROM mcp_operation_checkpoints WHERE operation_id=$1",[operation.id])).rows[0] assert.ok(checkpoint.configuration_sealed);assert.ok(checkpoint.configuration_proof) const principalConnection=await (await import("./store.js")).effectiveMcpConnection(writer) const nextBaseline=await advanceRoutingControllerBaseline(controller.state.baseline,controller.id,controller.version,mainProfile,controller.grant_expires_at.toISOString(),{principal:writer,connection:principalConnection},plan.planId,operation.id) assert.equal(nextBaseline.packet.candidateId,"b") const forwardCharge=(await pool.query("SELECT charge_units,source_plan_id,profile_id FROM mcp_routing_forward_charges WHERE source_operation_id=$1",[operation.id])).rows assert.deepEqual(forwardCharge,[{charge_units:1,source_plan_id:plan.planId,profile_id:controller.id}]) const completionOwner=await pool.connect() try { await assertIdentifiedRoutingCompletion(completionOwner,controller.id,plan.planId,operation.id,writer) await assert.rejects(assertIdentifiedRoutingCompletion(completionOwner,randomUUID(),plan.planId,operation.id,writer),(error:unknown)=>(error as {code?:string}).code==="STATE_CONFLICT") } finally { completionOwner.release() } const { rows: [{ finished_at: finishedAt }] } = await pool.query("SELECT finished_at FROM mcp_operations WHERE id=$1", [operation.id]) const legacyAt=(await pool.query("SELECT clock_timestamp() AS at")).rows[0].at.toISOString() assert(Date.parse(legacyAt) > finishedAt.getTime(), "Controller observes the completion after it was recorded") assert.equal(await publishControllerState(pool,controller,{...controller.state,switches:[legacyAt],planId:plan.planId,candidateId:"a"}),true) const { withSystemDatabaseOperationLock } = await import("../../db/operation-lock.js") const readController = async () => (await pool.query("SELECT * FROM mcp_routing_profiles WHERE id=$1", [controller.id])).rows[0] const beforeMaintenance = await readController() await withSystemDatabaseOperationLock(() => pool.connect(), async () => { await tickRoutingProfiles() assert.deepEqual(await readController(), beforeMaintenance) }) await tickRoutingProfiles() controller=(await pool.query("SELECT * FROM mcp_routing_profiles WHERE id=$1",[controller.id])).rows[0] assert.equal(controller.state.baseline.packet.candidateId,"b") assert.equal(controller.state.expectedCandidateId,"b","Completion must use the signed baseline, even if the stored pending candidate is stale") assert.deepEqual(controller.state.switches,[legacyAt],"Trusted charge completion must not append/dedup legacy timestamps") assert.equal(controller.state.planId,undefined);assert.equal(controller.state.lastSwitchAt,finishedAt.toISOString()) console.log("TARGETED_MAIN_FORWARD_CHARGE_COMPLETION_BRIDGE_PASS") const {client}=await routerClient(sid) const beforeDenied=writes await assert.rejects(client.patch("/routing/filter/rule/*f",{rule:body})) assert.equal(writes,beforeDenied,"Active controller refuses foreign native write before I/O") // Disable through the same public human save/CAS service, not direct SQL. await assert.rejects(invokeMcpTool(writer, "mm_route_controller_update_plan", { profileId: randomUUID(), profile: mainProfile, enabled: false, expiresAt: activation.grantExpiresAt }), (error: unknown) => error instanceof Error && "code" in error && error.code === "NOT_FOUND") const disable=await invokeMcpTool(writer,"mm_route_controller_update_plan",{profileId:controller.id,profile:mainProfile,enabled:false,expiresAt:activation.grantExpiresAt}) as {planId:string} await approvePlan(disable.planId,writerActor,true) assert.equal((await waitOperation((await applyPlan(writer,disable.planId,"runtime-main-baseline-disable")).id)).state,"applied") // Native writer owns the REAL server lock first. Approved activation cannot // acquire its whole runtime lease or publish profile state through CAS. const writerFirst=await activate(controller.id) let writerEntered!:()=>void,releaseWriter!:()=>void const writerReady=new Promise(r=>{writerEntered=r}),writerBarrier=new Promise(r=>{releaseWriter=r}) const competingWriter=withConfigMutationLock([sid],async()=>{writerEntered();await writerBarrier;await client.patch("/routing/filter/rule/*f",{rule:body,chain:"bgp-in",disabled:"no",comment:legacyComment})}) await writerReady const writerFirstOperation=await applyPlan(writer,writerFirst.planId,"runtime-main-writer-first") assert.notEqual((await waitOperation(writerFirstOperation.id)).state,"applied") assert.equal((await pool.query("SELECT enabled FROM mcp_routing_profiles WHERE id=$1",[controller.id])).rows[0].enabled,false) releaseWriter();await competingWriter assert.equal(policyBody,body) // Activation owns real application+server leases first. Park its fixed // native baseline read, then prove foreign writer cannot enter the lease. const activationFirst=await activate(controller.id) let activationEntered!:()=>void,releaseActivation!:()=>void const activationReady=new Promise(r=>{activationEntered=r}),activationBarrier=new Promise(r=>{releaseActivation=r}) afterRead=async()=>{activationEntered();await activationBarrier} const activeOperation=await applyPlan(writer,activationFirst.planId,"runtime-main-activation-first") await activationReady const beforeRacingWrite=writes await assert.rejects(client.patch("/routing/filter/rule/*f",{rule:body})) assert.equal(writes,beforeRacingWrite) releaseActivation() assert.equal((await waitOperation(activeOperation.id)).state,"applied") controller=(await pool.query("SELECT * FROM mcp_routing_profiles WHERE id=$1",[controller.id])).rows[0] assert.equal(controller.enabled,true);assert.equal(controller.state.baseline.packet.candidateId,"a") await assert.rejects(client.patch("/routing/filter/rule/*f",{rule:body})) assert.equal(writes,beforeRacingWrite) // Two genuine production CAS calls on distinct SQL clients race the SAME // expected version and prepared NEXT-version baseline. Exactly one wins. const nextHumanBaseline=await prepareRoutingControllerBaseline(controller.id,controller.version+1,mainProfile,controller.grant_expires_at.toISOString(),{principal:writer,connection:principalConnection}) const casInput={profileId:controller.id,connectionId:writeConnectionId,expectedVersion:controller.version,profile:mainProfile,enabled:true,expiresAt:controller.grant_expires_at.toISOString(),credentialId:writer.credentialId,generation:controller.generation,policyVersion:controller.policy_version,baseline:nextHumanBaseline} const human1=await pool.connect(),human2=await pool.connect() try { const saved=await Promise.all([saveControllerProfileCas(human1,casInput),saveControllerProfileCas(human2,casInput)]) assert.equal(saved.filter(Boolean).length,1) assert.equal(saved.find(Boolean)!.version,controller.version+1) assert.equal(await publishControllerState(human1,controller,{baseline:controller.state.baseline,reason:"stale-tick"}),false) }finally{human1.release();human2.release()} const last=(await pool.query("SELECT * FROM mcp_routing_profiles WHERE id=$1",[controller.id])).rows[0] assert.equal(last.version,controller.version+1);assert.equal(last.state.baseline.packet.profileVersion,last.version) assert.equal(last.state.baseline.packet.candidateId,"a") console.log("TARGETED_MAIN_BASELINE_RUNTIME_PASS",JSON.stringify({humanActivation:true,realRuntime:true,realApplyFiltersWriter:true,mainWithoutProbe:true,ownSwitchAndAdvance:true,writerFirst:true,activationFirst:true,genuineTwoClientCas:true,publicOverlapTOCTOU:true,foreignNativeWrites:0,authorizedFixtureWrites:writes})) const afterSwitch = await invokeMcpTool(writer, "mm_route_optimizer_analyze", { profile: mainProfile }) as { currentCandidateId: string | null; executionAvailable: boolean } assert.equal(afterSwitch.currentCandidateId, "a"); assert.equal(afterSwitch.executionAvailable, true) const writerResults = (await pool.query("SELECT result FROM mcp_requests WHERE connection_id=$1", [writeConnectionId])).rows assert.deepEqual(privateMarkerPaths(writerResults), [], "request result contains private native data at these JSON paths") assert.ok(!JSON.stringify(writerResults).includes("NEVER_")) const beforeUnrecognizedState = writes await pool.query("UPDATE mcp_operations SET state='fixture-unrecognized-terminal' WHERE id=$1", [driftMainOperation.id]) assert.equal(await publishControllerState(pool, last, { ...last.state, planId: driftMainPlan.planId }), true) await tickRoutingProfiles() const stopped = await readController() assert.equal(stopped.enabled, false) assert.equal(stopped.state.pausedReason, "Изменение отклонено или требует разбора результата") assert.equal(stopped.state.planId, driftMainPlan.planId) assert.deepEqual(stopped.state.baseline, last.state.baseline) assert.equal(writes, beforeUnrecognizedState) console.log("✓ Targeted baseline extension plus existing Route AI context SQL+HTTP: independent table/BGP/probe VRF, exact effective input binding/inheritance/family/candidate ambiguity, shared-chain dependencies, private signed path checks, endpoint/dependency/tamper drift, return-path unknown, UTF-8 byte cap, live revocation; read-only/non-main/recovery guards made zero writes; approved main switch made one PATCH with verified read-back and preserved legacy owned comment") } finally { if (writeConnectionId) await setConnectionStatus(writeConnectionId, "paused", writerActor) if (connectionId) await setConnectionStatus(connectionId, "paused", actor) await pool.query("DELETE FROM servers WHERE id=$1", [sid]) router.closeAllConnections(); await new Promise((resolve, reject) => router.close(error => error ? reject(error) : resolve())) } }