feat(p7): moteur git détaillé, API fichiers et watcher FS temps réel

Fondations de la refonte « vrai IDE IA worktree » (chantier P7→P12).

- git.ts : listChanges (status --porcelain=v2 -z + --numstat fusionnés),
  fileDiff (diff unifié borné, refus binaire, untracked via --no-index),
  stage/unstage/restore/clean, commitStaged, amendCommit (refus si poussé),
  fetchRemote, pull (ff-only|rebase), lastCommit, resolveGitDir,
  isSafeRelativePath ; worktreeStatus enrichi (compteurs staged/unstaged/
  conflict + dernier commit), champs additifs WorktreeGitStatus.
- core/fs-watcher.ts : FsWatcherService (chokidar, refcount + pool LRU borné,
  ignore .git sauf HEAD/index, débounce) → invalide factsCache, rediffuse
  worktree_update et émet worktree_changes.
- WorktreeManager : getWorktreeChanges/getFileDiff/stage/unstage/discard/
  fetch/pull/watch/unwatch/assertPathInWorktree ; commitWorktree { mode, amend }.
- routes/git.ts (changes/diff/stage/unstage/discard/fetch/pull) et
  routes/files.ts (GET/PUT contenu fichier, bornage strict au worktree) ;
  fs/list?includeFiles=1 (flag isFile).
- protocole ADDITIF (PROTOCOL_VERSION inchangé) : messages WS watch/unwatch
  (validés dans parseClientMessage) + worktree_changes poussé ciblé par la
  gateway ; front wsClient.watchWorktree + lib/git-api.ts + api.put.
- tests git/fs-watcher/protocole + acceptance-p7.mjs (ALL GREEN).
- dépendance : chokidar (serveur).
This commit is contained in:
2026-06-27 12:15:00 +02:00
parent 062bb64d41
commit be43911dc0
21 changed files with 1610 additions and 21 deletions

View File

@@ -0,0 +1,86 @@
// API fichiers (P7) pour l'éditeur Monaco : lecture/écriture du contenu d'un fichier, strictement
// bornées à un worktree ENREGISTRÉ (WorktreeManager.assertPathInWorktree : anti `..`, anti symlink
// sortant). Authentifiée par le hook preValidation global. Un terminal web est déjà du RCE par
// conception, mais on borne quand même (défense en profondeur + moindre étonnement).
import type { FastifyInstance } from 'fastify';
import { readFile, writeFile, stat, mkdir } from 'node:fs/promises';
import { dirname, extname } from 'node:path';
import type { FileContentResponse, WriteFileRequest, WriteFileResponse } from '@arboretum/shared';
import type { WorktreeManager } from '../core/worktree-manager.js';
import type { Db } from '../db/index.js';
import { recordAudit } from '../core/audit-log.js';
import { sendManagerError } from './repos.js';
const FILE_MAX_BYTES = 2 * 1024 * 1024;
/** Langage Monaco déduit de l'extension (sous-ensemble courant ; Monaco a un fallback 'plaintext'). */
const LANG_BY_EXT: Record<string, string> = {
'.ts': 'typescript', '.tsx': 'typescript', '.js': 'javascript', '.jsx': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript',
'.json': 'json', '.vue': 'vue', '.css': 'css', '.scss': 'scss', '.less': 'less', '.html': 'html', '.md': 'markdown',
'.py': 'python', '.rb': 'ruby', '.go': 'go', '.rs': 'rust', '.java': 'java', '.c': 'c', '.h': 'c', '.cpp': 'cpp', '.cc': 'cpp',
'.cs': 'csharp', '.php': 'php', '.sh': 'shell', '.bash': 'shell', '.zsh': 'shell', '.yml': 'yaml', '.yaml': 'yaml',
'.toml': 'toml', '.xml': 'xml', '.sql': 'sql', '.swift': 'swift', '.kt': 'kotlin', '.dart': 'dart', '.lua': 'lua',
};
function languageFor(path: string): string | undefined {
return LANG_BY_EXT[extname(path).toLowerCase()];
}
/** Détecte un fichier binaire par présence d'un octet NUL dans le buffer. */
function looksBinary(buf: Buffer): boolean {
const n = Math.min(buf.length, 8192);
for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
return false;
}
export function registerFileRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
// Lecture du contenu d'un fichier (UTF-8) d'un worktree.
app.get('/api/v1/repos/:id/files/content', async (req, reply) => {
const { id } = req.params as { id: string };
const q = req.query as { wt?: string; path?: string };
if (typeof q.wt !== 'string' || q.wt === '' || typeof q.path !== 'string' || q.path === '') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'wt and path are required' } });
}
try {
const abs = await wt.assertPathInWorktree(id, q.wt, q.path);
const st = await stat(abs).catch(() => null);
if (!st || !st.isFile()) return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No such file' } });
if (st.size > FILE_MAX_BYTES) return reply.status(413).send({ error: { code: 'FILE_TOO_LARGE', message: `File exceeds ${FILE_MAX_BYTES} bytes` } });
const buf = await readFile(abs);
if (looksBinary(buf)) return reply.status(415).send({ error: { code: 'BINARY_FILE', message: 'Binary files are not editable' } });
const lang = languageFor(q.path);
const res: FileContentResponse = {
path: q.path,
content: buf.toString('utf-8'),
encoding: 'utf-8',
size: st.size,
...(lang ? { language: lang } : {}),
};
return reply.send(res);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Écriture (création/modification) du contenu d'un fichier d'un worktree.
app.put('/api/v1/repos/:id/files/content', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<WriteFileRequest> | null;
if (!body || typeof body.wt !== 'string' || typeof body.path !== 'string' || typeof body.content !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'wt, path and content are required' } });
}
if (Buffer.byteLength(body.content, 'utf-8') > FILE_MAX_BYTES) {
return reply.status(413).send({ error: { code: 'FILE_TOO_LARGE', message: `Content exceeds ${FILE_MAX_BYTES} bytes` } });
}
try {
const abs = await wt.assertPathInWorktree(id, body.wt, body.path);
await mkdir(dirname(abs), { recursive: true }); // dirname reste sous le worktree (abs validé)
await writeFile(abs, body.content, 'utf-8');
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'file.write', resourceId: id, details: { path: body.path } });
const res: WriteFileResponse = { ok: true, size: Buffer.byteLength(body.content, 'utf-8') };
return reply.send(res);
} catch (err) {
return sendManagerError(reply, err);
}
});
}

View File

@@ -18,7 +18,7 @@ import type { FsEntry, FsListResponse } from '@arboretum/shared';
*/
export function registerFsRoutes(app: FastifyInstance): void {
app.get('/api/v1/fs/list', async (req, reply) => {
const q = req.query as { path?: string; markRepos?: string; showHidden?: string };
const q = req.query as { path?: string; markRepos?: string; showHidden?: string; includeFiles?: string };
const raw = q.path && q.path.length > 0 ? q.path : homedir();
if (!raw.startsWith('/')) {
return reply.status(400).send({ error: { code: 'BAD_PATH', message: 'path must be absolute' } });
@@ -41,6 +41,7 @@ export function registerFsRoutes(app: FastifyInstance): void {
const markRepos = q.markRepos === '1' || q.markRepos === 'true';
const showHidden = q.showHidden === '1' || q.showHidden === 'true';
const includeFiles = q.includeFiles === '1' || q.includeFiles === 'true';
let dirents;
try {
@@ -63,13 +64,24 @@ export function registerFsRoutes(app: FastifyInstance): void {
isDir = false;
}
}
if (!isDir) continue;
const full = join(abs, d.name);
if (!isDir) {
// En mode includeFiles, on remonte aussi les fichiers (arbre de l'IDE worktree).
if (!includeFiles) continue;
entries.push({ name: d.name, path: full, isFile: true });
continue;
}
const entry: FsEntry = { name: d.name, path: full };
if (markRepos && existsSync(join(full, '.git'))) entry.isRepo = true;
entries.push(entry);
}
entries.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
// Dossiers d'abord, puis fichiers ; tri insensible à la casse dans chaque groupe.
entries.sort((a, b) => {
const af = a.isFile ? 1 : 0;
const bf = b.isFile ? 1 : 0;
if (af !== bf) return af - bf;
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
});
const res: FsListResponse = {
path: abs,

View File

@@ -0,0 +1,132 @@
// Routes git « IDE » (P7) : diff par fichier, statut détaillé, staging sélectif, discard, fetch, pull.
// Toutes authentifiées par le hook preValidation global (/api/**), validées strictement et auditées.
// Le commit (sélectif/amend) reste sur POST /worktrees/commit (routes/worktrees.ts) pour ne pas
// dupliquer la sémantique.
import type { FastifyInstance } from 'fastify';
import type {
WorktreeChangesResponse,
FileDiffResponse,
WorktreeFilesRequest,
DiscardFilesRequest,
FetchWorktreeRequest,
PullWorktreeRequest,
WorktreeResponse,
} from '@arboretum/shared';
import type { WorktreeManager } from '../core/worktree-manager.js';
import type { Db } from '../db/index.js';
import { recordAudit } from '../core/audit-log.js';
import { sendManagerError } from './repos.js';
export function registerGitRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
// Liste des fichiers modifiés d'un worktree (statut détaillé + stats +/-).
app.get('/api/v1/repos/:id/worktrees/changes', async (req, reply) => {
const { id } = req.params as { id: string };
const q = req.query as { path?: string };
if (typeof q.path !== 'string' || q.path === '') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
}
try {
const { changes, truncated } = await wt.getWorktreeChanges(id, q.path);
return reply.send({ repoId: id, path: q.path, changes, truncated } satisfies WorktreeChangesResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Diff unifié d'un fichier (staged ou non ; untracked détecté côté manager).
app.get('/api/v1/repos/:id/worktrees/diff', async (req, reply) => {
const { id } = req.params as { id: string };
const q = req.query as { path?: string; file?: string; staged?: string };
if (typeof q.path !== 'string' || q.path === '' || typeof q.file !== 'string' || q.file === '') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and file are required' } });
}
const staged = q.staged === '1' || q.staged === 'true';
try {
const res = await wt.getFileDiff(id, q.path, q.file, staged);
return reply.send(res satisfies FileDiffResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Staging sélectif.
app.post('/api/v1/repos/:id/worktrees/stage', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<WorktreeFilesRequest> | null;
if (!body || typeof body.path !== 'string' || !Array.isArray(body.files)) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and files are required' } });
}
try {
const worktree = await wt.stage(id, body.path, body.files);
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.stage', resourceId: id, details: { path: body.path, count: body.files.length } });
return reply.send({ worktree } satisfies WorktreeResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Désindexation sélective.
app.post('/api/v1/repos/:id/worktrees/unstage', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<WorktreeFilesRequest> | null;
if (!body || typeof body.path !== 'string' || !Array.isArray(body.files)) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and files are required' } });
}
try {
const worktree = await wt.unstage(id, body.path, body.files);
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.unstage', resourceId: id, details: { path: body.path, count: body.files.length } });
return reply.send({ worktree } satisfies WorktreeResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Annulation des changements locaux (restore ; clean des untracked uniquement si includeUntracked).
app.post('/api/v1/repos/:id/worktrees/discard', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<DiscardFilesRequest> | null;
if (!body || typeof body.path !== 'string' || !Array.isArray(body.files)) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and files are required' } });
}
try {
const worktree = await wt.discard(id, body.path, body.files, body.includeUntracked === true);
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.discard', resourceId: id, details: { path: body.path, count: body.files.length, includeUntracked: body.includeUntracked === true } });
return reply.send({ worktree } satisfies WorktreeResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Fetch (--all --prune) : actualise ahead/behind.
app.post('/api/v1/repos/:id/worktrees/fetch', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<FetchWorktreeRequest> | null;
if (!body || typeof body.path !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
}
try {
const worktree = await wt.fetch(id, body.path);
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.fetch', resourceId: id, details: { path: body.path } });
return reply.send({ worktree } satisfies WorktreeResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Pull (ff-only par défaut, rebase optionnel).
app.post('/api/v1/repos/:id/worktrees/pull', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<PullWorktreeRequest> | null;
if (!body || typeof body.path !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
}
const mode = body.mode === 'rebase' ? 'rebase' : 'ff-only';
try {
const worktree = await wt.pull(id, body.path, mode);
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.pull', resourceId: id, details: { path: body.path, mode } });
return reply.send({ worktree } satisfies WorktreeResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
}

View File

@@ -134,12 +134,18 @@ export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager
if (!body || typeof body.path !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
}
if (typeof body.message !== 'string' || body.message.trim() === '') {
const amend = body.amend === true;
if (!amend && (typeof body.message !== 'string' || body.message.trim() === '')) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'message is required' } });
}
const mode = body.mode === 'staged' ? 'staged' : 'all';
try {
const worktree = await wt.commitWorktree(id, body.path, body.message.trim());
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.commit', resourceId: id, details: { path: body.path } });
const worktree = await wt.commitWorktree(id, body.path, {
message: typeof body.message === 'string' ? body.message.trim() : '',
mode,
amend,
});
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.commit', resourceId: id, details: { path: body.path, mode, amend } });
return reply.send({ worktree } satisfies WorktreeResponse);
} catch (err) {
return sendManagerError(reply, err);