#!/usr/bin/env node // Acceptation P14 (sans navigateur, sans quota Claude) : temps réel « armé ». Vrai daemon + vrai repo // git tmp + vrai client WS. Couvre les trois trous de visibilité corrigés : // 1. une session vivante épingle le watcher FS de SON worktree → les compteurs git d'un worktree // secondaire restent temps réel même si AUCUN client ne le regarde (avant : point « modifié » figé // sur le dernier listing REST) ; // 2. corrélation par contenance : un terminal lancé dans un SOUS-répertoire du worktree y est // rattaché (« Démarrer le projet »), et pas au checkout principal ; // 3. `watch` explicite → `worktree_changes` ciblé sur ce worktree secondaire. import { spawn, execFileSync } from 'node:child_process'; import { mkdtempSync, rmSync, writeFileSync, mkdirSync, appendFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); const WebSocket = require('ws'); const PORT = 7554; const ORIGIN = `http://127.0.0.1:${PORT}`; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..'); const results = []; const check = (name, ok, detail = '') => { results.push({ name, ok, detail }); console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`); }; const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p14-')); const repo = join(tmp, 'demo-repo'); mkdirSync(repo, { recursive: true }); const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' }); git('init', '-b', 'main'); git('config', 'user.email', 'test@arboretum.dev'); git('config', 'user.name', 'Test'); mkdirSync(join(repo, 'packages', 'api'), { recursive: true }); writeFileSync(join(repo, 'README.md'), '# demo\n'); writeFileSync(join(repo, 'packages', 'api', 'index.js'), 'console.log(1)\n'); git('add', '-A'); git('commit', '-m', 'init'); const srv = spawn( 'node', [join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'], { env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] }, ); let srvOut = ''; srv.stdout.on('data', (d) => (srvOut += d)); srv.stderr.on('data', (d) => (srvOut += d)); function wsClient(cookie) { const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } }); const state = { msgs: [] }; ws.on('message', (data, isBinary) => { if (!isBinary) state.msgs.push(JSON.parse(String(data))); }); const waitMsg = async (pred, timeout = 8000) => { const t0 = Date.now(); while (Date.now() - t0 < timeout) { const m = state.msgs.find(pred); if (m) return m; await sleep(50); } return null; }; return { ws, state, waitMsg, send: (m) => ws.send(JSON.stringify(m)) }; } const j = (path, method, cookie, body) => fetch(`${ORIGIN}${path}`, { method, headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}), }); try { await sleep(1500); const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0]; check('boot + token bootstrap', !!token); const login = await fetch(`${ORIGIN}/api/v1/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json', Origin: ORIGIN }, body: JSON.stringify({ token }), }); const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? ''; check('login → cookie', login.status === 200); const c = wsClient(cookie); await new Promise((res, rej) => (c.ws.on('open', res), c.ws.on('error', rej))); c.send({ type: 'hello', protocol: 1 }); await c.waitMsg((m) => m.type === 'hello_ok'); c.send({ type: 'sub', topics: ['worktrees', 'sessions'] }); const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo }); const repoId = (await addRepo.json()).repo.id; check('POST /repos → 201', addRepo.status === 201 && !!repoId); // ---- worktree secondaire (feature) avec un sous-répertoire ---- const created = await j(`/api/v1/repos/${repoId}/worktrees`, 'POST', cookie, { branch: 'feature/live', runHooks: false }); const wtPath = (await created.json()).worktree?.path; check('POST /worktrees → worktree secondaire créé', created.status === 201 && !!wtPath); const subDir = join(wtPath, 'packages', 'api'); // ---- 2. corrélation par contenance : session lancée DANS un sous-répertoire ---- const sess = await j('/api/v1/sessions', 'POST', cookie, { cwd: subDir, command: 'bash' }); const session = (await sess.json()).session; check('POST /sessions (cwd = sous-répertoire) → 201', sess.status === 201 && !!session?.id); await sleep(600); const list = await (await j('/api/v1/worktrees', 'GET', cookie)).json(); const secondary = (list.worktrees ?? []).find((w) => w.path === wtPath); const main = (list.worktrees ?? []).find((w) => w.isMain); check( 'la session du sous-répertoire est rattachée au worktree secondaire', (secondary?.sessions ?? []).some((s) => s.id === session.id), `sessions=${(secondary?.sessions ?? []).length}`, ); check( 'elle n’est PAS rattachée au checkout principal (désambiguïsation)', !(main?.sessions ?? []).some((s) => s.id === session.id), ); // ---- 1. session vivante → watcher épinglé SANS aucun watch client ---- // Aucun `watch` n'a été envoyé : seul `pinSession` peut produire cet événement. await sleep(900); // laisse chokidar finir son scan initial c.state.msgs.length = 0; const t0 = Date.now(); appendFileSync(join(wtPath, 'README.md'), 'edited by the agent\n'); const upd = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.path === wtPath && m.worktree?.git?.dirtyCount > 0, 6000); check('worktree secondaire non regardé : worktree_update reçu (pinSession)', !!upd, upd ? `${Date.now() - t0}ms` : 'timeout'); check('les compteurs git du worktree secondaire sont frais', (upd?.worktree?.git?.unstagedCount ?? 0) >= 1); // ---- pas de worktree_changes sans watch (le détail reste ciblé) ---- const changesWithoutWatch = c.state.msgs.find((m) => m.type === 'worktree_changes'); check('sans watch : aucun worktree_changes (push ciblé préservé)', !changesWithoutWatch); // ---- 3. watch explicite → worktree_changes ciblé ---- c.send({ type: 'watch', repoId, path: wtPath }); await sleep(900); c.state.msgs.length = 0; writeFileSync(join(wtPath, 'live.txt'), 'live\n'); const changesMsg = await c.waitMsg((m) => m.type === 'worktree_changes' && m.path === wtPath, 6000); check('watch → worktree_changes ciblé sur le worktree secondaire', !!changesMsg); c.send({ type: 'unwatch', repoId, path: wtPath }); await j(`/api/v1/sessions/${session.id}`, 'DELETE', cookie); await sleep(500); // ---- contraposée : le temps réel reste PILOTÉ (ni session, ni watch → pas de surveillance) ---- // Un watcher déjà ouvert est volontairement conservé en cache (évincé par la LRU) : on vérifie donc // sur un worktree neuf, jamais épinglé ni regardé, qu'aucun événement n'est émis. const idle = await j(`/api/v1/repos/${repoId}/worktrees`, 'POST', cookie, { branch: 'feature/idle', runHooks: false }); const idlePath = (await idle.json()).worktree?.path; check('POST /worktrees → second worktree (sans session)', idle.status === 201 && !!idlePath); await sleep(700); c.state.msgs.length = 0; writeFileSync(join(idlePath, 'unwatched.txt'), 'x\n'); const idleMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.path === idlePath, 2500); check('worktree sans session ni watch → aucune surveillance (coût piloté par l’attention)', !idleMsg); c.ws.close(); } catch (err) { check('exception', false, String(err)); } finally { srv.kill('SIGTERM'); await sleep(1500); check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null); rmSync(tmp, { recursive: true, force: true }); const failed = results.filter((r) => !r.ok); console.log(failed.length === 0 ? '\nACCEPTANCE P14: ALL GREEN' : `\nACCEPTANCE P14: ${failed.length} FAILURE(S)`); process.exit(failed.length === 0 ? 0 : 1); }