import { MIGRATION_MANIFEST } from "../db/migration-manifest.js" import assert from "node:assert/strict" import { randomUUID } from "node:crypto" import { readFile } from "node:fs/promises" import { basename,dirname,resolve } from "node:path" assert.equal(process.env.MMAPP_OWN_SERVER_POLL_STORAGE_FRESH,"true") const endpoint=new URL(process.env.DATABASE_URL??"") assert.equal(endpoint.hostname,"127.0.0.1");assert.equal(endpoint.pathname,"/postgres") assert(process.env.MCP_STATE_DIR&&basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-")) const {pool,closePool}=await import("../db/index.js") const {Pool}=await import("pg") const {applySqlMigrations}=await import("../db/migrate.js") const {applyLegacyPollStorageFixtureMigrations}=await import("../db/legacy-poll-storage-fixture.js") try{ await applySqlMigrations(pool);await applySqlMigrations(pool) assert.equal((await pool.query("SELECT count(*)::int AS n FROM schema_migrations")).rows[0].n,MIGRATION_MANIFEST.length) assert.deepEqual((await pool.query("SELECT * FROM server_poll_storage_usage")).rows,[{scope:"global",admissions:0,reserved_rows:0,reserved_bytes:0,compacted_admissions:0,archive_bytes:0}]) assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_admissions")).rows[0].n,0) const migration=await readFile(new URL("../../drizzle/0039_server_poll_storage.sql",import.meta.url),"utf8") const name="owned_poll_enroll_"+randomUUID().replaceAll("-","") await pool.query(`CREATE DATABASE "${name}" TEMPLATE template0`) const otherUrl=new URL(endpoint);otherUrl.pathname="/"+name const other=new Pool({connectionString:otherUrl.toString(),max:2,connectionTimeoutMillis:3000}) try{ await applyLegacyPollStorageFixtureMigrations(other) const receiptId=randomUUID(),executionId=randomUUID() await other.query("INSERT INTO server_poll_quarantines(receipt_id,identity_kind,execution_id,context_proof) VALUES($1,'rest',$2,$3)",[receiptId,executionId,"a".repeat(64)]) const before=(await other.query("SELECT to_jsonb(t) AS value FROM server_poll_quarantines t")).rows const client=await other.connect() try{await assert.rejects(client.query(migration))}finally{client.release(true)} assert.deepEqual((await other.query("SELECT to_jsonb(t) AS value FROM server_poll_quarantines t")).rows,before) assert.equal((await other.query("SELECT to_regclass('public.server_poll_storage_admissions') IS NULL AS absent")).rows[0].absent,true) assert.equal((await other.query("SELECT count(*)::int AS n FROM schema_migrations WHERE id='0039_server_poll_storage'")).rows[0].n,0) }finally{await other.end();await pool.query(`DROP DATABASE "${name}"`)} const {tickMcpWorkers}=await import("../modules/mcp/workers.js") assert.equal((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled,false) const expiredRequestIds = Array.from({ length: 1001 }, () => randomUUID()).sort() const [runningId, freshId] = [randomUUID(), randomUUID()].sort() await pool.query(`INSERT INTO mcp_requests(id,tool,status,created_at) SELECT id,'owned-retention-test','completed',now()-interval '31 days' FROM unnest($1::uuid[]) AS ids(id) UNION ALL SELECT $2::uuid,'owned-retention-test','running',now()-interval '32 days' UNION ALL SELECT $3::uuid,'owned-retention-test','completed',now()-interval '29 days'`, [expiredRequestIds, runningId, freshId]) const expiredAudit = (await pool.query(`INSERT INTO mcp_audit(actor_id,action,created_at) SELECT 'owned-retention-test','expired',now()-interval '181 days' FROM generate_series(1,1001) RETURNING id`)).rows.map(row => String(row.id)) const lastExpiredAuditId = expiredAudit.reduce((last, id) => BigInt(id) > BigInt(last) ? id : last) const freshAuditId = (await pool.query(`INSERT INTO mcp_audit(actor_id,action,created_at) VALUES ('owned-retention-test','fresh',now()-interval '179 days') RETURNING id`)).rows[0].id const artifactConnectionId = randomUUID() const expiredArtifactIds = Array.from({ length: 1001 }, () => randomUUID()).sort() const freshArtifactId = randomUUID() await pool.query(`INSERT INTO mcp_connections(id,name,owner_id,owner_permissions,policy,generation) VALUES ($1,'owned-retention-test','owned-retention-test','[]','{}','owned-retention-test')`, [artifactConnectionId]) await pool.query(`INSERT INTO mcp_artifacts(id,connection_id,filename,media_type,ciphertext,expires_at) SELECT id,$1::uuid,'test','application/octet-stream','test',now()-interval '1 day' FROM unnest($2::uuid[]) AS ids(id) UNION ALL SELECT $3::uuid,$1::uuid,'test','application/octet-stream','test',now()+interval '1 day'`, [artifactConnectionId, expiredArtifactIds, freshArtifactId]) const requestIds = async () => (await pool.query("SELECT id FROM mcp_requests WHERE tool='owned-retention-test' ORDER BY id")).rows.map(row => row.id) const auditIds = async () => (await pool.query("SELECT id FROM mcp_audit WHERE actor_id='owned-retention-test' ORDER BY id")).rows.map(row => String(row.id)) const artifactIds = async () => (await pool.query("SELECT id FROM mcp_artifacts WHERE connection_id=$1 ORDER BY id", [artifactConnectionId])).rows.map(row => row.id) await tickMcpWorkers() assert.deepEqual(await requestIds(), [...expiredRequestIds.slice(-1), runningId, freshId].sort()) assert.deepEqual(await auditIds(), [lastExpiredAuditId, String(freshAuditId)]) assert.deepEqual(await artifactIds(), [...expiredArtifactIds.slice(-1), freshArtifactId].sort()) await tickMcpWorkers() assert.deepEqual(await requestIds(), [runningId, freshId].sort()) assert.deepEqual(await auditIds(), [String(freshAuditId)]) assert.deepEqual(await artifactIds(), [freshArtifactId]) await pool.query("DELETE FROM mcp_artifacts WHERE id=$1", [freshArtifactId]) await pool.query("DELETE FROM mcp_connections WHERE id=$1", [artifactConnectionId]) console.log("Owned fresh poll storage:",JSON.stringify({normalStartupTwice:true,migrations:MIGRATION_MANIFEST.length,globalZeroSeed:true,legacyPrefix:38,nonemptyJournalRefusedBeforeDdl:true,oldRowsPreserved:true,noForgedMarker:true,actualWorkerTickWithMcpDisabled:true,boundedRequestAuditAndArtifactRetention:true})) if (process.env.MMAPP_OWN_SERVER_POLL_SETTINGS_EPOCH === "true") { await (await import("../db/server-poll-settings-epoch.owned-helper.js")).acceptServerPollSettingsEpochMigrationSql(pool) } else if (process.env.MMAPP_OWN_SERVER_POLL_ATOMIC_MAINTENANCE === "true") { await (await import("./server-poll-atomic-owned-helper.js")).acceptAtomicServerPollOwned() } else if (process.env.MMAPP_OWN_SERVER_POLL_DELAYED_APPROVAL === "true") { assert.equal(process.env.NODE_ENV,"test");assert.equal(endpoint.username,"mcp_test") await(await import("../db/bootstrap.js")).initDatabase() const {acceptServerPollPublicRuntimeSql}=await import("../modules/mcp/server-poll-http.sql-helper.js") for(const scenario of ["runtime","configuration-aba","guard"] as const)await acceptServerPollPublicRuntimeSql({delayedApproval:scenario}) console.log("Owned delayed human approval: runtime waiting accepted; configuration ABA and missing guard refused before admission/native") } else if (process.env.MMAPP_OWN_SERVER_POLL_HTTP_ROUTE === "true") { assert.equal(process.env.NODE_ENV, "test"); assert.equal(endpoint.username, "mcp_test") await (await import("../db/bootstrap.js")).initDatabase() await (await import("./server-poll-rest-authority.sql-helper.js")).acceptServerPollRestAuthoritySql({ httpRoute: true }) await (await import("../modules/mcp/server-poll-http.sql-helper.js")).acceptServerPollPublicRuntimeSql() console.log("Owned full poll registered HTTP route and normal MCP parity accepted; cold/quota matrix not run") } else { const publicOnly=process.env.MMAPP_OWN_SERVER_POLL_PUBLIC_ONLY==="true" if(!publicOnly&&process.env.MMAPP_OWN_SERVER_POLL_AUTHORITY_ONLY!=="true")await(await import("./server-poll-storage-execution.sql-helper.js")).acceptServerPollStorageExecutionSql() if(!publicOnly)await(await import("./server-poll-rest-authority.sql-helper.js")).acceptServerPollRestAuthoritySql() if(process.env.MMAPP_OWN_SERVER_POLL_AUTHORITY_ONLY!=="true")await(await import("../modules/mcp/server-poll-http.sql-helper.js")).acceptServerPollPublicRuntimeSql() console.log("Owned fresh poll quota:",JSON.stringify(await(await import("./server-poll-storage-fill.sql-helper.js")).acceptPollStorageGlobalCapSql())) } }finally{await closePool()}