feat: rename keep-notes to memento-note, migrate to PostgreSQL, fix MCP bugs

- Rename directory keep-notes -> memento-note with all code references
- Prisma: SQLite -> PostgreSQL (both app and MCP server schemas)
- Sync MCP schema with main app (add missing fields, relations, indexes)
- Delete 17 SQLite migrations (clean slate for PostgreSQL)
- Remove SQLite dependencies (@libsql/client, better-sqlite3, etc.)
- Fix MCP server: hardcoded Windows DB paths -> DATABASE_URL env var
- Fix MCP server: .dockerignore excluded index-sse.js (SSE mode broken)
- MCP Dockerfile: node:20 -> node:22
- Docker Compose: add postgres service, remove SQLite volume
- Generate favicon.ico, icon-192.png, icon-512.png, apple-icon.png
- Update layout.tsx icons and manifest.json for PNG icons
- Update all .env files for PostgreSQL
- Rewrite README.md with updated sections
- Remove mcp-server/node_modules and prisma/client-generated from git tracking

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Sepehr Ramezani
2026-04-20 20:58:04 +02:00
parent e2ddfa53d4
commit aa6a214f37
3548 changed files with 440 additions and 516800 deletions

View File

@@ -0,0 +1,22 @@
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
const configs = await prisma.systemConfig.findMany()
console.log('--- System Config ---')
configs.forEach(c => {
if (c.key.startsWith('AI_') || c.key.startsWith('OLLAMA_')) {
console.log(`${c.key}: ${c.value}`)
}
})
}
main()
.catch(e => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})

View File

@@ -0,0 +1,76 @@
// Import directly from the generated client
const { PrismaClient } = require('./node_modules/@prisma/client')
const prisma = new PrismaClient()
async function checkLabels() {
try {
console.log('\n=== TOUS LES LABELS DANS LA TABLE Label ===')
const allLabels = await prisma.label.findMany({
select: { id: true, name: true, userId: true }
})
console.log(`Total: ${allLabels.length} labels`)
allLabels.forEach(l => {
console.log(` - ${l.name} (userId: ${l.userId}, id: ${l.id})`)
})
console.log('\n=== TOUS LES LABELS DANS LES NOTES (Note.labels) ===')
const allNotes = await prisma.note.findMany({
select: { id: true, labels: true, userId: true }
})
const labelsInNotes = new Set()
allNotes.forEach(note => {
if (note.labels) {
try {
const parsed = JSON.parse(note.labels)
if (Array.isArray(parsed)) {
parsed.forEach(l => labelsInNotes.add(l))
}
} catch (e) {}
}
})
console.log(`Total unique: ${labelsInNotes.size} labels`)
labelsInNotes.forEach(l => console.log(` - ${l}`))
console.log('\n=== LABELS ORPHELINS (dans Label table MAIS PAS dans les notes) ===')
const orphanLabels = []
allLabels.forEach(label => {
let found = false
labelsInNotes.forEach(noteLabel => {
if (noteLabel.toLowerCase() === label.name.toLowerCase()) {
found = true
}
})
if (!found) {
orphanLabels.push(label)
}
})
console.log(`Total orphans: ${orphanLabels.length}`)
orphanLabels.forEach(l => {
console.log(` - ${l.name} (userId: ${l.userId})`)
})
console.log('\n=== LABELS MANQUANTS (dans notes MAIS PAS dans Label table) ===')
const missingLabels = []
const existingLabelNames = new Set()
allLabels.forEach(l => existingLabelNames.add(l.name.toLowerCase()))
labelsInNotes.forEach(noteLabel => {
if (!existingLabelNames.has(noteLabel.toLowerCase())) {
missingLabels.push(noteLabel)
}
})
console.log(`Total missing: ${missingLabels.length}`)
missingLabels.forEach(l => console.log(` - ${l}`))
} catch (error) {
console.error('Error:', error)
} finally {
await prisma.$disconnect()
}
}
checkLabels()

View File

@@ -0,0 +1,25 @@
import { prisma } from '../lib/prisma'
async function main() {
console.log('🔍 Checking users in database...')
console.log('Database URL used:', process.env.DATABASE_URL || "file:./dev.db")
const users = await prisma.user.findMany()
if (users.length === 0) {
console.log('❌ No users found in database!')
} else {
console.log(`✅ Found ${users.length} users:`)
console.table(users.map(u => ({
email: u.email,
role: u.role,
id: u.id,
hasPassword: !!u.password
})))
}
}
main()
.catch(e => console.error(e))
.finally(async () => await prisma.$disconnect())

View File

@@ -0,0 +1,41 @@
import { siteConfig } from '../config/site'
import { PrismaClient } from '@prisma/client'
async function main() {
console.log('🕵️‍♀️ Comparing Databases...')
// 1. Check Root DB
console.log('--- ROOT DB (./dev.db) ---')
const prismaRoot = new PrismaClient({
datasources: { db: { url: 'file:./dev.db' } }
})
try {
const countRoot = await prismaRoot.note.count()
console.log(`📦 Note Count: ${countRoot}`)
const usersRoot = await prismaRoot.user.count()
console.log(`👥 User Count: ${usersRoot}`)
} catch (e) {
console.log('❌ Failed to connect to Root DB', e)
} finally {
await prismaRoot.$disconnect()
}
// 2. Check Prisma Folder DB
console.log('\n--- PRISMA DB (./prisma/dev.db) ---')
const prismaPrisma = new PrismaClient({
datasources: { db: { url: 'file:./prisma/dev.db' } }
})
try {
const countPrisma = await prismaPrisma.note.count()
console.log(`📦 Note Count: ${countPrisma}`)
const usersPrisma = await prismaPrisma.user.count()
console.log(`👥 User Count: ${usersPrisma}`)
} catch (e) {
console.log('❌ Failed to connect to Prisma DB', e)
} finally {
await prismaPrisma.$disconnect()
}
}
main().catch(console.error)

View File

@@ -0,0 +1,41 @@
import prisma from '../lib/prisma'
async function debugConfig() {
console.log('=== System Configuration Debug ===\n')
const configs = await prisma.systemConfig.findMany()
console.log(`Total configs in DB: ${configs.length}\n`)
// Group by category
const aiConfigs = configs.filter(c => c.key.startsWith('AI_'))
const ollamaConfigs = configs.filter(c => c.key.includes('OLLAMA'))
const openaiConfigs = configs.filter(c => c.key.includes('OPENAI'))
console.log('=== AI Provider Configs ===')
aiConfigs.forEach(c => {
console.log(`${c.key}: "${c.value}"`)
})
console.log('\n=== Ollama Configs ===')
ollamaConfigs.forEach(c => {
console.log(`${c.key}: "${c.value}"`)
})
console.log('\n=== OpenAI Configs ===')
openaiConfigs.forEach(c => {
console.log(`${c.key}: "${c.value}"`)
})
console.log('\n=== All Configs ===')
configs.forEach(c => {
console.log(`${c.key}: "${c.value}"`)
})
}
debugConfig()
.then(() => process.exit(0))
.catch((err) => {
console.error(err)
process.exit(1)
})

View File

@@ -0,0 +1,36 @@
import { getAllNotes } from '../app/actions/notes'
import { prisma } from '../lib/prisma'
async function main() {
console.log('🕵️‍♀️ Debugging getAllNotes...')
// 1. Get raw DB data for a sample note
const rawNote = await prisma.note.findFirst({
where: { size: { not: 'small' } }
})
if (rawNote) {
console.log('📊 Raw DB Note (should be large/medium):', {
id: rawNote.id,
size: rawNote.size
})
} else {
console.log('⚠️ No notes with size != small found in DB directly.')
}
// 2. Mock auth/session if needed (actions check session)
// Since we can't easily mock next-auth in this script environment without setup,
// we might need to rely on the direct DB check above or check if getAllNotes extracts userId safely.
// getAllNotes checks `auth()`. In this script context, `auth()` will arguably return null.
// So we can't easily run `getAllNotes` directly if it guards auth.
// Let's modify the plan: We will check the DB directly to confirm PERMANENCE.
// Then we will manually simulate `parseNote` logic.
const notes = await prisma.note.findMany({ take: 5 })
console.log('📋 Checking first 5 notes sizes in DB:')
notes.forEach(n => console.log(`- ${n.id}: ${n.size}`))
}
main().catch(console.error).finally(() => prisma.$disconnect())

View File

@@ -0,0 +1,24 @@
import { prisma } from '../lib/prisma'
async function main() {
console.log('👑 Granting ADMIN access to ALL users...')
try {
const result = await prisma.user.updateMany({
data: {
role: 'ADMIN'
}
})
console.log(`✅ Success! Updated ${result.count} users to ADMIN role.`)
} catch (error) {
console.error('❌ Error updating users:', error)
process.exit(1)
}
}
main()
.catch(e => console.error(e))
.finally(async () => await prisma.$disconnect())

View File

@@ -0,0 +1,35 @@
const { PrismaClient } = require('../prisma/client-generated');
const prisma = new PrismaClient();
async function promoteAdmin() {
const email = process.argv[2];
try {
let user;
if (email) {
user = await prisma.user.findUnique({ where: { email } });
} else {
console.log("Aucun email fourni, promotion du premier utilisateur trouvé...");
user = await prisma.user.findFirst();
}
if (!user) {
console.error("Aucun utilisateur trouvé.");
return;
}
await prisma.user.update({
where: { id: user.id },
data: { role: 'ADMIN' }
});
console.log(`Succès : L'utilisateur ${user.email} (${user.name}) est maintenant ADMIN.`);
} catch (e) {
console.error("Erreur :", e);
} finally {
await prisma.$disconnect();
}
}
promoteAdmin();

View File

@@ -0,0 +1,67 @@
import { PrismaClient } from '../prisma/client-generated'
import { getAIProvider } from '../lib/ai/factory'
import { getSystemConfig } from '../lib/config'
const prisma = new PrismaClient()
async function regenerateAllEmbeddings() {
console.log('🔄 Starting embedding regeneration...\n')
// Get all notes
const notes = await prisma.note.findMany({
select: {
id: true,
title: true,
content: true
}
})
console.log(`📝 Found ${notes.length} notes to process\n`)
// Get AI provider
const config = await getSystemConfig()
const provider = getAIProvider(config)
console.log(`🤖 Using AI provider...`)
let successCount = 0
let errorCount = 0
for (const note of notes) {
try {
const title = note.title || '(no title)'
process.stdout.write(`\r⏳ Processing ${successCount + 1}/${notes.length}: ${title.substring(0, 40)}...`)
// Generate new embedding
const embedding = await provider.getEmbeddings(note.content)
if (embedding) {
// Update note with new embedding
await prisma.note.update({
where: { id: note.id },
data: {
embedding: JSON.stringify(embedding)
}
})
successCount++
} else {
errorCount++
console.log(`\n❌ Failed: ${title} (no embedding generated)`)
}
} catch (error) {
errorCount++
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
console.log(`\n❌ Error: ${note.title || '(no title)'} - ${errorMessage}`)
}
}
console.log(`\n\n📊 Summary:`)
console.log(` ✅ Success: ${successCount}/${notes.length}`)
console.log(` ❌ Errors: ${errorCount}/${notes.length}`)
console.log('\n✨ Embeddings regenerated successfully!')
await prisma.$disconnect()
}
regenerateAllEmbeddings().catch(console.error)

View File

@@ -0,0 +1,36 @@
import { prisma } from '../lib/prisma'
import bcrypt from 'bcryptjs'
async function main() {
const email = 'test@example.com'
const newPassword = 'password123'
console.log(`Resetting password for ${email}...`)
const hashedPassword = await bcrypt.hash(newPassword, 10)
try {
const user = await prisma.user.update({
where: { email },
data: {
password: hashedPassword,
resetToken: null,
resetTokenExpiry: null
},
})
console.log(`✅ Password successfully reset for ${user.email}`)
} catch (error) {
console.error('❌ Error resetting password:', error)
process.exit(1)
}
}
main()
.catch(e => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})

View File

@@ -0,0 +1,145 @@
/**
* Script DIRECT de reset de mot de passe
*
* POURQUOI CE SCRIPT ?
* -----------------
* - Le compte `test@example.com` N'EXISTE PAS (vous avez raison !)
* - L'envoi d'email nécessite une configuration SMTP complexe
* - VOUS VOULEZ UNE SOLUTION DIRECTE, SANS PERDRE DE TEMPS
*
* CE QUE FAIT CE SCRIPT :
* -------------------
* - Réinitialise DIRECTEMENT le mot de passe d'un compte existant
* - Sans avoir besoin d'email
* - Sans avoir besoin d'interface graphique
*
* COMMENT UTILISER :
* ---------------
* 1. Ouvrez un terminal dans le dossier memento-note
* 2. Exécutez: node scripts/reset-password.js
* 3. Quand demandé, entrez l'email du compte à réinitialiser
* 4. Entrez le nouveau mot de passe (2 fois pour confirmation)
* 5. FINI ! Connectez-vous avec le nouveau mot de passe
*/
const readline = require('readline');
const bcrypt = require('bcryptjs');
const prisma = require('../lib/prisma').default;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log('╔══════════════════════════════════════════════════════════════════╗');
console.log('║ RESET DE MOT DE PASSE DIRECT ║');
console.log('║ ║');
console.log('║ ⚠️ ATTENTION : Utilisez seulement pour VOTRE propre compte ! ║');
console.log('║ ║');
console.log('╚══════════════════════════════════════════════════════════════════════╝');
console.log('');
rl.question('Entrez l\'EMAIL du compte à réinitialiser : ', async (email) => {
if (!email || !email.includes('@')) {
console.log('❌ Erreur : Email invalide !');
rl.close();
process.exit(1);
}
email = email.toLowerCase().trim();
console.log(`🔍 Recherche du compte : ${email}...`);
try {
const user = await prisma.user.findUnique({
where: { email: email }
});
if (!user) {
console.log('');
console.log('❌ ERREUR : AUCUN compte trouvé avec cet email !');
console.log('');
console.log('📋 COMPTES DISPONIBLES (si existants) :');
console.log('─────────────────────────────────────────');
// Afficher tous les utilisateurs de la base de données
const allUsers = await prisma.user.findMany({
select: { email: true, name: true, role: true, createdAt: true },
orderBy: { createdAt: 'desc' }
});
if (allUsers.length > 0) {
console.log('');
allUsers.forEach((u, index) => {
console.log(`${index + 1}. 📧 Email: ${u.email}`);
console.log(` 👤 Nom: ${u.name || 'N/A'}`);
console.log(` 🏷️ Rôle: ${u.role}`);
console.log(` 📅 Créé: ${u.createdAt.toLocaleString('fr-FR')}`);
console.log('');
});
} else {
console.log(' (Aucun compte dans la base de données)');
}
console.log('─────────────────────────────────────────');
console.log('');
rl.close();
process.exit(1);
}
console.log(`✅ Compte trouvé : ${user.email} (${user.name})`);
console.log('');
rl.question('Entrez le NOUVEAU mot de passe (minimum 6 caractères) : ', async (newPassword) => {
if (!newPassword || newPassword.length < 6) {
console.log('❌ Erreur : Le mot de passe doit avoir au moins 6 caractères !');
rl.close();
process.exit(1);
}
rl.question('Confirmez le nouveau mot de passe : ', async (confirmPassword) => {
if (newPassword !== confirmPassword) {
console.log('❌ Erreur : Les mots de passe ne correspondent pas !');
rl.close();
process.exit(1);
}
console.log('');
console.log('🔄 Réinitialisation du mot de passe en cours...');
const hashedPassword = await bcrypt.hash(newPassword, 10);
await prisma.user.update({
where: { id: user.id },
data: {
password: hashedPassword,
resetToken: null,
resetTokenExpiry: null
}
});
console.log('✅ SUCCÈS ! Le mot de passe a été réinitialisé !');
console.log('');
console.log('═══════════════════════════════════════════════════════════════════════');
console.log('🎉 VOUS POUVEZ MAINTENANT VOUS CONNECTER !');
console.log('═════════════════════════════════════════════════════════════════════');
console.log('');
console.log('📱 URL de connexion : http://localhost:3000/login');
console.log('📧 Email :', email);
console.log('🔑 Mot de passe :', newPassword);
console.log('');
console.log('⏩ Copiez ces informations et connectez-vous !');
console.log('');
rl.close();
process.exit(0);
});
});
} catch (error) {
console.log('');
console.log('❌ ERREUR lors de la réinitialisation :');
console.error(error);
rl.close();
process.exit(1);
}
});

View File

@@ -0,0 +1,22 @@
import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcryptjs'
const prisma = new PrismaClient()
async function main() {
const hashedPassword = await bcrypt.hash('password123', 10)
const user = await prisma.user.upsert({
where: { email: 'test@example.com' },
update: {},
create: {
email: 'test@example.com',
name: 'Test User',
password: hashedPassword,
},
})
console.log('User created:', user)
}
main()
.catch(e => console.error(e))
.finally(async () => await prisma.$disconnect())

View File

@@ -0,0 +1,48 @@
import prisma from '../lib/prisma'
/**
* Setup OpenAI as default AI provider in database
* Run this to ensure OpenAI is properly configured
*/
async function setupOpenAI() {
console.log('🔧 Setting up OpenAI as default AI provider...\n')
const configs = [
{ key: 'AI_PROVIDER_TAGS', value: 'openai' },
{ key: 'AI_PROVIDER_EMBEDDING', value: 'openai' },
{ key: 'AI_MODEL_TAGS', value: 'gpt-4o-mini' },
{ key: 'AI_MODEL_EMBEDDING', value: 'text-embedding-3-small' },
]
try {
for (const config of configs) {
await prisma.systemConfig.upsert({
where: { key: config.key },
update: { value: config.value },
create: { key: config.key, value: config.value }
})
console.log(`✅ Set ${config.key} = ${config.value}`)
}
console.log('\n✨ OpenAI configuration complete!')
console.log('\nNext steps:')
console.log('1. Add your OPENAI_API_KEY in admin settings: http://localhost:3000/admin/settings')
console.log('2. Or add it to .env.docker: OPENAI_API_KEY=sk-...')
console.log('3. Restart the application')
// Verify
const verify = await prisma.systemConfig.findMany({
where: { key: { in: configs.map(c => c.key) } }
})
console.log('\n✅ Verification:')
verify.forEach(c => console.log(` ${c.key}: ${c.value}`))
} catch (error) {
console.error('❌ Error:', error)
process.exit(1)
}
}
setupOpenAI()
.then(() => process.exit(0))
.catch(() => process.exit(1))

View File

@@ -0,0 +1,63 @@
import { prisma } from '../lib/prisma'
// Copy of parseNote from app/actions/notes.ts (since it's not exported)
function parseNote(dbNote: any) {
const embedding = dbNote.embedding ? JSON.parse(dbNote.embedding) : null
if (embedding && Array.isArray(embedding)) {
// Simplified validation check for test
if (embedding.length !== 1536 && embedding.length !== 768 && embedding.length !== 384) {
return {
...dbNote,
checkItems: dbNote.checkItems ? JSON.parse(dbNote.checkItems) : null,
labels: dbNote.labels ? JSON.parse(dbNote.labels) : null,
images: dbNote.images ? JSON.parse(dbNote.images) : null,
links: dbNote.links ? JSON.parse(dbNote.links) : null,
embedding: null,
sharedWith: dbNote.sharedWith ? JSON.parse(dbNote.sharedWith) : [],
size: dbNote.size || 'small',
}
}
}
return {
...dbNote,
checkItems: dbNote.checkItems ? JSON.parse(dbNote.checkItems) : null,
labels: dbNote.labels ? JSON.parse(dbNote.labels) : null,
images: dbNote.images ? JSON.parse(dbNote.images) : null,
links: dbNote.links ? JSON.parse(dbNote.links) : null,
embedding,
sharedWith: dbNote.sharedWith ? JSON.parse(dbNote.sharedWith) : [],
size: dbNote.size || 'small',
}
}
async function main() {
console.log('🧪 Testing parseNote logic...')
// 1. Fetch a real note from DB that is KNOWN to be large
const rawNote = await prisma.note.findFirst({
where: { size: 'large' }
})
if (!rawNote) {
console.error('❌ No large note found in DB. Create one first.')
return
}
console.log('📊 Raw Note from DB:', { id: rawNote.id, size: rawNote.size })
// 2. Pass it through parseNote
const parsed = parseNote(rawNote)
console.log('🔄 Parsed Note:', { id: parsed.id, size: parsed.size })
if (parsed.size === 'large') {
console.log('✅ parseNote preserves size correctly.')
} else {
console.error('❌ parseNote returned wrong size:', parsed.size)
}
}
main().catch(console.error).finally(() => prisma.$disconnect())

View File

@@ -0,0 +1,56 @@
import { prisma } from '../lib/prisma'
import { updateSize } from '../app/actions/notes'
async function main() {
console.log('🧪 Starting Note Size Persistence Verification...')
// 1. Create a test note
const note = await prisma.note.create({
data: {
content: 'Size Test Note',
userId: (await prisma.user.findFirst())?.id || '',
size: 'small', // Start small
}
})
console.log(`📝 Created test note (${note.id}) with size: ${note.size}`)
if (!note.userId) {
console.error('❌ No user found to create note. Aborting.')
return
}
try {
// 2. Update size to LARGE
console.log('🔄 Updating size to LARGE...')
// We mock the session for the action or call prisma directly if action fails (actions usually need auth context)
// Since we're running as script, we'll use prisma update directly to simulate what the action does at DB level
// OR we can try to invoke the action if we can mock auth.
// Let's test the DB interaction first which is the critical "persistence" part.
await prisma.note.update({
where: { id: note.id },
data: { size: 'large' }
})
// 3. Fetch back
const updatedNote = await prisma.note.findUnique({ where: { id: note.id } })
console.log(`🔍 Fetched note after update. Size is: ${updatedNote?.size}`)
if (updatedNote?.size === 'large') {
console.log('✅ BACKEND PERSISTENCE: PASSED')
} else {
console.error('❌ BACKEND PERSISTENCE: FAILED (Size reverted or did not update)')
}
} catch (error) {
console.error('❌ Error during test:', error)
} finally {
// Cleanup
await prisma.note.delete({ where: { id: note.id } })
console.log('🧹 Cleaned up test note')
await prisma.$disconnect()
}
}
main().catch(console.error)