/**
* Apply M4 migration directly via PostgreSQL client
*/
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
const { Client } = require('pg');
// Parse DATABASE_URL
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
console.error('ERROR: Missing DATABASE_URL');
process.exit(1);
}
const client = new Client({
connectionString: databaseUrl,
});
async function applyMigration() {
console.log('[M4 Migration] Connecting to Supabase PostgreSQL...');
await client.connect();
console.log('[M4 Migration] ✓ Connected');
// Check if column already exists
console.log('[M4 Migration] Checking if current_level column exists...');
const checkResult = await client.query(`
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'conversations'
AND column_name = 'current_level'
`);
if (checkResult.rows.length > 0) {
console.log('[M4 Migration] ✓ current_level column already exists');
await client.end();
return;
}
console.log('[M4 Migration] Adding current_level column...');
await client.query(`
ALTER TABLE conversations
ADD COLUMN current_level INTEGER NOT NULL DEFAULT 1
`);
console.log('[M4 Migration] ✓ Column added');
console.log('[M4 Migration] Adding constraint...');
await client.query(`
ALTER TABLE conversations
ADD CONSTRAINT valid_permission_level CHECK (current_level >= 1 AND current_level <= 3)
`);
console.log('[M4 Migration] ✓ Constraint added');
console.log('[M4 Migration] Adding index...');
await client.query(`
CREATE INDEX idx_conversations_current_level ON conversations(current_level)
`);
console.log('[M4 Migration] ✓ Index added');
console.log('[M4 Migration] Adding column comment...');
await client.query(`
COMMENT ON COLUMN conversations.current_level IS 'M4: Current permission level (1=read, 2=write, 3=execute). Accumulated through permission upgrades.'
`);
console.log('[M4 Migration] ✓ Comment added');
console.log('[M4 Migration] ✅ Migration complete!');
await client.end();
}
applyMigration().catch(err => {
console.error('[M4 Migration] Fatal error:', err);
process.exit(1);
});