diff --git a/backend/README.md b/backend/README.md index 48ffac2..21a0ba4 100644 --- a/backend/README.md +++ b/backend/README.md @@ -16,6 +16,10 @@ Le serveur écoute sur `HOST:PORT` (par défaut `0.0.0.0:3000`, donc joignable d Prérequis Ollama : `OLLAMA_URL` doit pointer vers une instance Ollama et `OLLAMA_MODEL` doit être un modèle déjà téléchargé (`ollama pull llama3.2`). +La taille de la base est bornée par projet : au-delà de `MAX_PROJECT_MESSAGES` messages +(500 par défaut), les plus anciens sont supprimés à linsertion — un projet de longue durée +ne peut donc pas faire grossir `jarvise.db` sans limite. + ## Endpoints | Méthode | Route | Auth | Description | @@ -41,6 +45,7 @@ un modèle déjà téléchargé (`ollama pull llama3.2`). | POST | `/api/projects/:id/chat` | oui | Chat dans le projet (contexte envoyé) | | POST | `/api/chat/stream` | oui | Chat streamé en SSE (sans état) | | POST | `/api/projects/:id/chat/stream` | oui | Chat streamé en SSE dans le projet | +| POST | `/api/projects/:id/context/recall` | oui | Récite le contexte reçu (rien n'est enregistré) | Les routes protégées attendent le header `Authorization: Bearer `. Un projet n'est accessible qu'à son propriétaire : toute autre tentative renvoie `404`. @@ -64,8 +69,19 @@ curl -X POST http://localhost:3000/api/projects/1/chat \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{"message":"Où en est-on ?"}' + +# Vérifier que le contexte atteint bien le modèle (rien n'est enregistré) +curl -N -X POST http://localhost:3000/api/projects/1/context/recall \ + -H 'Authorization: Bearer ' \ + -H 'Content-Type: application/json' \ + -d '{}' ``` +`POST /api/projects/:id/context/recall` relit le contexte depuis la base à chaque appel et +demande à Jarvis de le réciter : l'événement `done` renvoie `contextMessages`, le nombre +exact de messages réellement renvoyés au modèle (40 au maximum). Rien n'est écrit dans le +projet, ce qui en fait une sonde de vérificationpurement lecture. + ### Exemple ```bash @@ -143,7 +159,7 @@ de Jarvis **au fur et à mesure** qu'Ollama la produit, sans attendre la fin. | Évènement | `data` | | ------------- | --------------------------------------------------------- | | `delta` | `{ "content": "morceau de texte" }` | -| `done` | `{ reply, model, projectId?, messages? }` | +| `done` | `{ reply, model, projectId?, messages?, contextMessages? }` | | `error` | `{ error, partial }` (erreur survenue en cours de flux) | Si Ollama est injoignable, la réponse est une **erreur HTTP classique** (`502`) en JSON, avant diff --git a/backend/src/config.js b/backend/src/config.js index 42cf8d5..5a7b256 100644 --- a/backend/src/config.js +++ b/backend/src/config.js @@ -47,6 +47,16 @@ export function loadConfig(overrides = {}) { port: Number(overrides.port ?? process.env.PORT ?? 3000), host: overrides.host ?? process.env.HOST ?? '0.0.0.0', dbPath: resolveFromRoot(overrides.dbPath ?? process.env.DB_PATH, 'data/jarvise.db'), + messages: { + /** + * Nombre de messages conservés par projet : au-delà, les plus anciens + * sont supprimés à l'insertion. Évite qu'un projet de longue durée fasse + * grossir la base sans borne. + */ + maxPerProject: Number( + overrides.maxMessagesPerProject ?? process.env.MAX_PROJECT_MESSAGES ?? 500, + ), + }, cors: { origin: overrides.corsOrigin ?? parseOrigin(process.env.CORS_ORIGIN), }, diff --git a/backend/src/db/index.js b/backend/src/db/index.js index 680c2a3..346cc01 100644 --- a/backend/src/db/index.js +++ b/backend/src/db/index.js @@ -41,8 +41,12 @@ const SCHEMA = ` /** * Opens (and initialises) the SQLite database and returns every query helper. * Each call creates an independent database, which is convenient for tests. + * + * @param {string} dbPath file path, or `:memory:` + * @param {{ maxMessagesPerProject?: number }} [options] retention of a project's + * context; the oldest messages are dropped beyond that count. */ -export function createDatabase(dbPath) { +export function createDatabase(dbPath, { maxMessagesPerProject = 500 } = {}) { if (dbPath !== ':memory:') { fs.mkdirSync(path.dirname(dbPath), { recursive: true }); } @@ -160,11 +164,41 @@ export function createDatabase(dbPath) { .prepare('SELECT 1 FROM messages WHERE project_id = ? AND id < ? LIMIT 1') .get(projectId, oldestId); + /** + * Drops the oldest messages of a project so at most `keep` remain. + * @returns {number} how many rows were deleted. + */ + const trimMessages = (projectId, keep = maxMessagesPerProject) => { + const { total } = db + .prepare('SELECT COUNT(*) AS total FROM messages WHERE project_id = ?') + .get(projectId); + const excess = total - keep; + if (excess <= 0) return 0; + + // `idx_messages_project (project_id, id)` makes both statements cheap, and + // the whole project fits in a few hundred rows anyway. + return db + .prepare( + `DELETE FROM messages WHERE project_id = ? AND id IN ( + SELECT id FROM messages WHERE project_id = ? ORDER BY id ASC LIMIT ? + )`, + ) + .run(projectId, projectId, excess).changes; + }; + const addMessage = (projectId, { role, content }) => { const result = db .prepare('INSERT INTO messages (project_id, role, content) VALUES (?, ?, ?)') .run(projectId, role, content); - return db.prepare('SELECT * FROM messages WHERE id = ?').get(Number(result.lastInsertRowid)); + const message = db + .prepare('SELECT * FROM messages WHERE id = ?') + .get(Number(result.lastInsertRowid)); + + // Single choke point for every writer (chat, chat/stream, manual notes), so + // the context of a project can never grow past the configured limit. + trimMessages(projectId); + + return message; }; const deleteMessages = (projectId) => @@ -192,6 +226,7 @@ export function createDatabase(dbPath) { listMessages, hasOlderMessages, addMessage, + trimMessages, deleteMessages, }; } diff --git a/backend/src/server.js b/backend/src/server.js index 8b6e18a..aa57983 100644 --- a/backend/src/server.js +++ b/backend/src/server.js @@ -4,7 +4,9 @@ import { createDatabase } from './db/index.js'; import { createOllama } from './services/ollama.js'; const config = loadConfig(); -const db = createDatabase(config.dbPath); +const db = createDatabase(config.dbPath, { + maxMessagesPerProject: config.messages.maxPerProject, +}); const ollama = createOllama(config); const app = await buildApp({ config, db, ollama }); diff --git a/backend/test/helpers.js b/backend/test/helpers.js index 9457d4b..4f3dce1 100644 --- a/backend/test/helpers.js +++ b/backend/test/helpers.js @@ -19,9 +19,12 @@ export async function startServer(options = {}) { dbPath: ':memory:', ollamaUrl: mock.url, ollamaModel: 'mock:1', + maxMessagesPerProject: options.maxMessagesPerProject, }); - const db = createDatabase(config.dbPath); + const db = createDatabase(config.dbPath, { + maxMessagesPerProject: config.messages.maxPerProject, + }); const ollama = createOllama(config); const app = await buildApp({ config, db, ollama }); diff --git a/backend/test/projects.test.js b/backend/test/projects.test.js index 6ad4b0d..e648546 100644 --- a/backend/test/projects.test.js +++ b/backend/test/projects.test.js @@ -217,3 +217,82 @@ describe('projects and context', () => { assert.equal(res.status, 401); }); }); + +describe('context retention', () => { + let srv; + let user; + + before(async () => { + // A tiny cap so the pruning is observable without writing 500 messages. + srv = await startServer({ maxMessagesPerProject: 4 }); + user = await registerUser(srv.base, 'carol@x.io'); + }); + + after(async () => { + await srv.close(); + }); + + async function cappedProject() { + const res = await api(srv.base, 'POST', '/api/projects', { + token: user.token, + body: { name: 'Capped' }, + }); + return res.json.project; + } + + async function append(projectId, content) { + const res = await api(srv.base, 'POST', `/api/projects/${projectId}/messages`, { + token: user.token, + body: { content }, + }); + assert.equal(res.status, 201); + } + + it('keeps only the last messages of a project', async () => { + const p = await cappedProject(); + for (let i = 1; i <= 7; i++) await append(p.id, `message ${i}`); + + const msgs = await api(srv.base, 'GET', `/api/projects/${p.id}/messages?limit=50`, { + token: user.token, + }); + assert.deepEqual( + msgs.json.messages.map((m) => m.content), + ['message 4', 'message 5', 'message 6', 'message 7'], + ); + // Nothing older remains, so pagination stops there. + assert.equal(msgs.json.hasMore, false); + + const project = await api(srv.base, 'GET', `/api/projects/${p.id}`, { token: user.token }); + assert.equal(project.json.project.messageCount, 4); + }); + + it('also caps what a chat exchange appends', async () => { + const p = await cappedProject(); + for (let i = 1; i <= 4; i++) await append(p.id, `message ${i}`); + + // One exchange adds a question and an answer: the two oldest go away. + const chat = await api(srv.base, 'POST', `/api/projects/${p.id}/chat`, { + token: user.token, + body: { message: 'Hi' }, + }); + assert.equal(chat.status, 200); + + const msgs = await api(srv.base, 'GET', `/api/projects/${p.id}/messages?limit=50`, { + token: user.token, + }); + assert.deepEqual( + msgs.json.messages.map((m) => m.content), + ['message 3', 'message 4', 'Hi', 'Bonjour Tony, je suis Jarvis.'], + ); + }); + + it('never trims another project', async () => { + const a = await cappedProject(); + const b = await cappedProject(); + for (let i = 1; i <= 6; i++) await append(a.id, `a${i}`); + await append(b.id, 'b1'); + + const kept = await api(srv.base, 'GET', `/api/projects/${b.id}/messages`, { token: user.token }); + assert.equal(kept.json.messages.length, 1); + }); +});