Compare commits

..
7 Commits
Author SHA1 Message Date
Johan LEROYandClaude Opus 4.8 c177eeea07 P2: découverte & reprise des sessions Claude
Arboretum découvre désormais toutes les sessions Claude de la machine
(scan ~/.claude/projects + registre ~/.claude/sessions), distingue
vivantes/mortes par pid+procStart, et permet de reprendre une morte
(--resume dans son cwd d'origine) ou forker une vivante sans la corrompre.

- shared: SessionSummary enrichi (source, claudeSessionId, pid, resumable,
  attachable, registryStatus) — additif, PROTOCOL_VERSION inchangé ;
  types REST resume/fork.
- db: migration id:2 (claude_session_id, resumed_from).
- core: jsonl-discovery (parseur tolérant, scan asynchrone non bloquant),
  session-registry (vivacité pid+procStart), discovery-service (cache +
  refresh périodique + diff/broadcast), pty-manager (resume/fork + capture
  du claudeSessionId via le registre).
- routes: /sessions/:id/resume (garde-fou 409 anti-corruption sur session
  vivante) et /fork ; GET fusionné managées + découvertes ; relais WS.
- web: badges managed/discovered + busy/idle/waiting, actions conditionnelles
  (Open/Observe/Kill vs Fork/View vs Resume/Fork), vue read-only des sessions
  externes, i18n EN/FR.
- tests: jsonl-discovery, session-registry, discovery-service + resume/fork
  (130 verts) ; acceptation E2E acceptance-p2.mjs (sans quota) ALL GREEN.

Conforme aux verdicts S1 (resume dans cwd d'origine, vivacité pid+procStart)
et S4 (munge cwd, parseur tête+queue, priorité de titre).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 18:20:21 +02:00
Johan LEROYandClaude Fable 5 770f58a640 P1 complete: web front, test suite, CI — acceptance ALL GREEN
Fan-out integration + fixes found by the test/acceptance pass:
- FIX ring-buffer: chunks >= capacity skipped bytes now count into the
  monotonic offset (invariant: stream byte k lives at k % capacity) —
  window order was corrupted on unaligned big chunks
- FIX auth: non-numeric cookie expiry no longer bypasses expiration
- FIX protocol: safe-integer validation on ack.bytes / hello.protocol
- FIX @fastify/websocket v11: websocket route must be registered in an
  encapsulated context after plugin load (handler got REST signature)
- FIX flow-control deadlock found by e2e acceptance: client only ACKs
  on data receipt, so pausing with an unACKed residue in (LOW,
  ACK_EVERY] stalled both sides at 0.9 MB. ACK_EVERY now 64 KiB (<=
  LOW invariant, tested) + trailing debounced ACK in the web client
- Web: Vue 3 + Vite + Pinia + Tailwind 4 + vue-i18n (EN/FR) + xterm 6
  (fit + webgl fallback), multiplexed ws-client with reconnect/backoff
  and resync epochs
- Tests: 100 vitest (protocol fuzz, ring edges, auth, pty-manager flow
  control with mocked pty, REST e2e) ; CI Node 22/24 + pack-smoke
- scripts/acceptance-p1.mjs: real daemon + real WS client — boot,
  login, attach, stdin, 10 MB flood w/ ACK (13.7 MB/1.9s, RSS bounded),
  brutal disconnect + replay resync, kill broadcast, SIGTERM drain

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 22:29:58 +02:00
Johan LEROYandClaude Fable 5 f6f73329b9 P1 spine: monorepo, shared WS protocol, server daemon
- npm workspaces (shared / server / web), TS strict, project refs
- @arboretum/shared: multiplexed WS protocol (JSON control + binary
  output frames: 1B type + u32le channel), flow-control constants
  (ACK 256K, HIGH 384K, LOW 128K, lagging 2M), REST types
- git-arboretum server: Fastify 5 + node:sqlite (single native dep:
  node-pty prebuilt), token auth (sha256 at rest, HMAC cookie, global
  login rate limit + backoff), strict Origin check on /api and /ws,
  PtyManager (2MiB ring with monotonic offset, resync replay = reset +
  256KiB tail, pause/resume only when ALL interactive clients exceed
  HIGH, observers never throttle, lagging clients resync), WS gateway
  (attach/stdin/resize/ack, heartbeat 30s), SIGTERM→SIGKILL 5s grace
- CLI: arboretum [--port 7317] [--bind 127.0.0.1] — non-loopback bind
  requires an explicit safety flag
- Smoke-tested: login/401/403-origin/spawn bash/kill/grace-SIGKILL all
  green

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 22:04:09 +02:00
Johan LEROYandClaude Fable 5 8733c17e44 Spike S3: TUI dialogs, keystrokes — GO (documented partial)
Response protocol: digit positions + Enter confirms (digit alone is not
enough); arrows+Enter work everywhere. Registry detects waiting state
for both permission and AskUserQuestion dialogs (same waitingFor label
— fine-grained dialog typing needs screen reading). Sandboxed bash runs
no-prompt for most commands: real waits come from edits/network/
questions. Pre-trust via ~/.claude.json projects[dir]
.hasTrustDialogAccepted captured and plausible. Esc-deny and plan
approval deferred to P4 reliability campaign.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 17:58:28 +02:00
Johan LEROYandClaude Fable 5 c98f619b25 Spike S1: resume/fork/liveness — GO; flood: pause/resume — GO
Demonstrated on CLI 2.1.173: resuming a live session interleaves both
TUIs into one transcript (no lock, no warning) — liveness detection via
registry pid+procStart is mandatory; --fork-session is safe on live
sessions; --resume must run in the session's original cwd ("No
conversation found" otherwise); registry files are cleaned on graceful
exit AND SIGTERM, may be GC'd later after SIGKILL — never reason on
file presence. ANSI-stripped TUI text loses spaces (cursor-positioned
painting) — confirms @xterm/headless for screen parsing.
Flood: 21 MB through node-pty with 10s pause => 0 bytes leaked, no
loss, 4.7 ms echo after flood.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 17:47:05 +02:00
Johan LEROYandClaude Fable 5 45dba47b8b Spike S4: JSONL discovery + sessions registry — GO
99.8% of 1318 real transcripts (449 MB) yield sessionId+cwd in 1.37s
(head+tail reads only). Munge cwd→dir validated on 100% of files.
Registry pid/procStart liveness check validated 3/3. 12 line types
inventoried, ai-title is the best title source.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 17:39:19 +02:00
Johan LEROYandClaude Fable 5 f4075e0385 Initial commit: positioning, license, project scaffold
Arboretum — self-hosted web dashboard for git worktrees and the Claude
Code sessions running on them. README states the positioning vs
GitKraken Agent Mode, Happy/CloudCLI and Anthropic Remote Control, the
security model (localhost-first + Tailscale), and the Claude usage note.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 17:37:07 +02:00
239 changed files with 642 additions and 24606 deletions
-55
View File
@@ -1,55 +0,0 @@
name: Deploy site (production)
# Déploie le site vitrine (packages/site) sur Plesk via FTPS (lftp), à l'identique
# de lidge_web / tracksniff-web. Ne se déclenche que sur un changement du site.
on:
push:
branches:
- main
paths:
- 'packages/site/**'
- '.gitea/workflows/prod.yml'
workflow_dispatch:
concurrency:
group: deploy-site
cancel-in-progress: true
jobs:
build-and-deploy:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Install scopé au workspace du site : pas de build des deps natives du
# serveur (node-pty / node:sqlite) qui n'ont rien à faire ici.
- name: Install deps (@arboretum/site)
run: npm install -w @arboretum/site --no-audit --no-fund
- name: Build site
run: npm run build:site
- name: Check build output
run: ls -la packages/site/dist
- name: Deploy via FTPS (lftp)
run: |
if [ -z "$REMOTE_PATH" ]; then
echo "::error::Secret SITE_REMOTE_PATH manquant (chemin docroot du vhost git-arboretum.com)."
exit 1
fi
apt-get update && apt-get install -y lftp
lftp -c "
open -u \"$FTP_USER\",\"$FTP_PASSWORD\" \"$FTP_HOST\"
set ssl:verify-certificate no
mirror -R --delete --verbose packages/site/dist \"$REMOTE_PATH\"
"
env:
FTP_HOST: ${{ secrets.FTP_HOST }}
FTP_USER: ${{ secrets.FTP_USER }}
FTP_PASSWORD: ${{ secrets.FTP_PASSWORD }}
# Chemin docroot du vhost git-arboretum.com sur Plesk (ex. /httpdocs/arboretum/public).
REMOTE_PATH: ${{ secrets.SITE_REMOTE_PATH }}
-73
View File
@@ -1,73 +0,0 @@
# Publication du paquet @johanleroy/git-arboretum sur le registre npm du Gitea,
# déclenchée UNIQUEMENT par un tag vX.Y.Z (jamais sur un push de branche).
name: Release
on:
push:
tags: ['v*']
permissions:
contents: read
packages: write
jobs:
publish:
name: Publish to Gitea npm registry
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
registry-url: 'https://git.lidge.fr/api/packages/johanleroy/npm/'
scope: '@johanleroy'
cache: npm
- run: npm ci
- run: npm run build
# Garde-fou : le tag (sans le "v") doit correspondre à la version du paquet.
# GITHUB_REF_NAME est une variable d'env du runner (pas d'interpolation ${{ }} dans le shell).
- name: Verify tag matches package version
run: |
pkg=$(node -p "require('./packages/server/package.json').version")
tag="${GITHUB_REF_NAME#v}"
if [ "$pkg" != "$tag" ]; then
echo "ERREUR: tag '$tag' != version paquet '$pkg'"
exit 1
fi
echo "OK: tag $tag == version $pkg"
# Publication idempotente : le signal faisant autorité d'une version déjà présente est le
# 409 « already exists » renvoyé par npm publish lui-même (npm view est non fiable contre le
# registre npm de Gitea — faux négatif masqué par >/dev/null). On tente toujours le publish ;
# un 409 = succès idempotent, tout autre échec reste fatal. Le shell Actions tourne en
# `bash -eo pipefail` : on isole l'échec attendu dans la condition d'un `if` pour ne pas
# déclencher `set -e`. Le secret du registre est mappé sur NODE_AUTH_TOKEN lu par le .npmrc
# de setup-node.
- name: Publish (idempotent — tolère un 409 « already exists »)
run: |
if out="$(npm publish -w @johanleroy/git-arboretum 2>&1)"; then
printf '%s\n' "$out"
echo "Publication réussie."
else
code=$?
printf '%s\n' "$out"
if printf '%s' "$out" | grep -qiE 'E409|409 Conflict|already exists'; then
echo "::notice::Version déjà présente sur le registre (409) — publication idempotente, étape ignorée."
else
echo "::error::Échec de la publication (code $code)."
exit "$code"
fi
fi
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# SBOM (transparence supply-chain entreprise) : généré pour le paquet publié et exposé en
# artefact. C'est un bonus : un échec de génération/upload ne doit jamais faire rougir une
# release dont le publish a réussi → continue-on-error.
# upload-artifact@v3 : Gitea Actions (GHES-like) ne supporte pas @v4 (@actions/artifact v2+).
- name: Generate SBOM (CycloneDX)
continue-on-error: true
run: npx --yes @cyclonedx/cyclonedx-npm --omit dev --output-format JSON --output-file sbom.json -w @johanleroy/git-arboretum || npx --yes @cyclonedx/cyclonedx-npm --omit dev --output-format JSON --output-file sbom.json
- uses: actions/upload-artifact@v3
continue-on-error: true
with:
name: sbom
path: sbom.json
-73
View File
@@ -1,73 +0,0 @@
# Packaging du VSIX de l'extension VS Code, déclenché UNIQUEMENT par un tag vscode-vX.Y.Z
# (séparé de la release du daemon, qui écoute les tags v*). Le .vsix est exposé en artefact du run
# (toujours) et, en best-effort, attaché à la release Gitea correspondante.
name: VSCode Release
on:
push:
tags: ['vscode-v*']
permissions:
contents: write
jobs:
package:
name: Package VSIX
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
# Garde-fou : le tag (sans "vscode-v") doit correspondre à la version du manifeste de l'extension.
- name: Verify tag matches extension version
run: |
pkg=$(node -p "require('./packages/vscode/package.json').version")
tag="${GITHUB_REF_NAME#vscode-v}"
if [ "$pkg" != "$tag" ]; then
echo "ERREUR: tag '$tag' != version extension '$pkg'"
exit 1
fi
echo "OK: tag $tag == version $pkg"
# Build du shared puis bundle esbuild de l'extension (typecheck inclus), puis packaging VSIX.
# --no-dependencies : tout est bundlé dans dist/extension.js → pas de node_modules dans le VSIX.
- name: Build & package
run: |
npm run build:vscode
version=$(node -p "require('./packages/vscode/package.json').version")
cd packages/vscode
npx --yes @vscode/vsce package --no-dependencies -o "git-arboretum-${version}.vsix"
# Artefact du run : canal de distribution fiable, indépendant de l'API release.
# upload-artifact@v3 : Gitea Actions ne supporte pas @v4 (@actions/artifact v2+).
- uses: actions/upload-artifact@v3
with:
name: vsix
path: packages/vscode/*.vsix
# Best-effort : attache le VSIX à la release Gitea du tag (crée la release si absente).
# Nécessite un secret RELEASE_TOKEN (token Gitea avec write:repository) ; sans lui, l'étape est
# ignorée sans faire échouer le job (continue-on-error).
- name: Attach VSIX to Gitea release
continue-on-error: true
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
if [ -z "$RELEASE_TOKEN" ]; then
echo "::notice::RELEASE_TOKEN absent — VSIX disponible en artefact uniquement."
exit 0
fi
api="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
auth="Authorization: token ${RELEASE_TOKEN}"
version=$(node -p "require('./packages/vscode/package.json').version")
vsix="packages/vscode/git-arboretum-${version}.vsix"
# id de release du tag, sinon création
rid=$(curl -fsSL -H "$auth" "${api}/releases/tags/${GITHUB_REF_NAME}" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''" || true)
if [ -z "$rid" ]; then
rid=$(curl -fsSL -X POST -H "$auth" -H 'Content-Type: application/json' \
-d "{\"tag_name\":\"${GITHUB_REF_NAME}\",\"name\":\"Arboretum VSCode ${version}\"}" \
"${api}/releases" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''")
fi
curl -fsSL -X POST -H "$auth" -F "attachment=@${vsix}" \
"${api}/releases/${rid}/assets?name=git-arboretum-${version}.vsix"
echo "VSIX attaché à la release ${GITHUB_REF_NAME}."
@@ -27,7 +27,6 @@ jobs:
- run: npm ci
- run: npm run typecheck
- run: npm run build
- run: npm run build:site
- run: npx vitest run
pack-smoke:
@@ -42,27 +41,14 @@ jobs:
cache: npm
- run: npm ci
- run: npm run build
# @arboretum/shared (paquet workspace NON publié) est INLINÉ dans dist/_shared au prepack
# (scripts/inline-shared.mjs) : le tarball est 100 % autonome — aucun node_modules embarqué,
# aucune bundleDependency, aucun symlink. On packe en mode workspace (-w), EXACTEMENT comme
# le fait « npm publish » dans release.yml, puis on l'installe seul comme un vrai consommateur.
- name: Pack tarball
# @arboretum/shared est une dépendance runtime non publiée : on packe les
# deux tarballs et on les installe ensemble dans un projet vierge.
- name: Pack tarballs
run: |
rm -rf /tmp/tarballs && mkdir -p /tmp/tarballs
npm pack -w @johanleroy/git-arboretum --pack-destination /tmp/tarballs
mkdir -p /tmp/tarballs
npm pack -w @arboretum/shared -w git-arboretum --pack-destination /tmp/tarballs
ls -l /tmp/tarballs
- name: Assert the package is self-contained (@arboretum/shared inlined)
run: |
tgz=$(ls /tmp/tarballs/*.tgz)
rm -rf /tmp/inspect && mkdir -p /tmp/inspect && tar -xzf "$tgz" -C /tmp/inspect
test -f /tmp/inspect/package/dist/_shared/index.js \
|| { echo "ERREUR: dist/_shared/index.js absent de $tgz — inline-shared n'a pas tourné ?"; exit 1; }
if grep -rq '@arboretum/shared' /tmp/inspect/package/dist; then
echo "ERREUR: import bare '@arboretum/shared' encore présent dans le JS publié"
grep -rn '@arboretum/shared' /tmp/inspect/package/dist; exit 1
fi
echo "OK: paquet autonome — shared inliné dans dist/_shared, aucun import externe"
- name: Install tarball in an empty project
- name: Install tarballs in an empty project
run: |
mkdir /tmp/smoke
cd /tmp/smoke
+2 -27
View File
@@ -1,36 +1,11 @@
# Dependencies
node_modules/
# Build output
dist/
packages/server/public/
*.tgz
*.tsbuildinfo
# README/LICENSE copiés dans le paquet au prepack (générés depuis la racine)
packages/server/README.md
packages/server/LICENSE
# Test / coverage
coverage/
# Local data & secrets
*.log
.env
.env.*
*.db
*.db-*
*.log
# Editors & OS
.idea/
.vscode/
.DS_Store
# Claude Code / agent tooling (local only — do not commit)
CLAUDE.md
.claude/
.remember/
# Spike scratch output
spikes/**/tmp/
spikes/**/captures/
packages/server/public/
-5
View File
@@ -1,5 +0,0 @@
# Route le scope @johanleroy vers le registre npm intégré du Gitea self-hosted.
# Les dépendances publiques (fastify, node-pty…) restent résolues depuis npmjs.
# Le token d'auth (_authToken) ne se commit JAMAIS : il vit dans ~/.npmrc (local)
# ou dans un secret CI (NODE_AUTH_TOKEN écrit par setup-node).
@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/
+79
View File
@@ -0,0 +1,79 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Projet
Arboretum : un daemon Node.js unique (`npx git-arboretum`) qui sert un dashboard web pour piloter les worktrees git et les sessions Claude Code qui tournent dessus, depuis n'importe quel appareil. Pré-MVP. L'étape **P1** (colonne vertébrale : monorepo, protocole WS, daemon, front, tests, CI) est terminée ; voir les `VERDICT.md` dans `spikes/` pour les décisions techniques actées avant implémentation.
Les commentaires du code et la doc interne sont en **français** ; le README et les messages utilisateur en anglais. Conserver cette convention.
## Commandes
```bash
npm run build # build shared → server → web (l'ordre compte, voir ci-dessous)
npm run typecheck # tsc -b shared + server UNIQUEMENT (le web se typecheck via vue-tsc dans son build)
npm test # vitest run sur packages/*/test/**/*.test.ts
npx vitest run packages/server/test/ring-buffer.test.ts # un seul fichier
npx vitest run -t "flow control" # par nom de test
npm run dev:server # daemon en watch (tsc -b --watch + node --watch)
npm run dev:web # Vite ; proxifie /api et /ws vers le daemon sur :7317 (cf. note Origin)
npm run pack # build + npm pack du tarball git-arboretum
node packages/server/scripts/acceptance-p1.mjs # acceptation E2E P1 (daemon réel + client WS réel)
node packages/server/scripts/acceptance-p2.mjs # acceptation E2E P2 (découverte/reprise : faux ~/.claude + faux binaire claude)
```
L'acceptation exige `npm run build` au préalable (elle lance `dist/index.js`) et utilise la commande `bash` plutôt que `claude` pour ne pas consommer de quota.
**Node >= 22.16 est requis** (pas seulement recommandé) : la persistance utilise `node:sqlite` (`DatabaseSync`), natif et stable seulement à partir de cette version. `.nvmrc` = 22.
## Monorepo (npm workspaces)
- **`packages/shared`** (`@arboretum/shared`) — source unique de vérité du protocole WS (`protocol.ts`) et des types REST (`api.ts`), importée par le serveur ET le front. C'est une **dépendance runtime non publiée** : la CI pack les deux tarballs (`@arboretum/shared` + `git-arboretum`) et les installe ensemble.
- **`packages/server`** (`git-arboretum`) — le daemon Fastify, **le seul paquet publié sur npm** (bin `arboretum`). Embarque la SPA buildée dans `public/` via le hook `prepack` (`scripts/copy-web.mjs`).
- **`packages/web`** (`@arboretum/web`) — SPA Vue 3 (Pinia, vue-router, xterm.js, Tailwind 4), privée.
Ordre de build imposé : `shared` se construit en premier (projets TS `composite` avec references) ; le front doit être buildé avant `prepack` du serveur pour être embarqué.
## Architecture serveur
`buildApp()` (`packages/server/src/app.ts`) câble tout : `AuthService`, `LoginRateLimiter`, `PtyManager`, les routes REST, la gateway WS, et le service statique de la SPA. `index.ts` est le bin (parse config, ouvre la db, écoute, gère le bootstrap token et le drain au SIGTERM/SIGINT).
### Modèle de sécurité (central — ne pas affaiblir)
Un terminal web est de l'exécution de code à distance par conception. Les garde-fous sont structurants :
- Bind `127.0.0.1` par défaut ; `config.ts` **refuse** tout bind non-loopback sans `--i-know-this-exposes-a-terminal`. Accès distant recommandé via Tailscale Serve.
- Un hook `preValidation` global authentifie **toute** requête `/api/**` et `/ws`, et applique un **check Origin strict** quand l'en-tête est présent (anti cross-site WS hijacking — le cookie `SameSite=Strict` ne couvre pas les upgrades). Les routes statiques sont publiques ; les routes publiques explicites portent `config: { public: true }` (ex. login).
- Tokens stockés **hashés** (sha256), comparaison en temps constant. Le bootstrap token n'est affiché qu'une fois au premier démarrage. Le cookie de session est un payload signé HMAC. Le rate-limit du login est **global** (pas par IP : derrière Tailscale tout arrive de 127.0.0.1) avec backoff exponentiel.
### Protocole WebSocket (`packages/shared/src/protocol.ts`)
Une **seule connexion multiplexée par client**, plusieurs canaux (channels) :
- Contrôle = frames **texte JSON** ; sortie terminal = frames **binaires** `[type u8][channel u32le][payload]`. Un chunk PTY peut couper un caractère UTF-8 en frontière de frame → le décodage est délégué à `xterm.write(Uint8Array)`, jamais au transport.
- **Flow control par watermarks** (`FLOW`). Invariant anti-deadlock à préserver absolument : `ACK_EVERY_BYTES <= LOW_WATERMARK`. Le PTY n'est mis en pause que quand **tous** les clients interactifs dépassent `HIGH` ; les observers ne freinent jamais le flux. Un client trop en retard (`LAGGING_BYTES`) est coupé puis resynchronisé.
- Handshake `hello`/`hello_ok` négocie `PROTOCOL_VERSION`. `parseClientMessage` valide/sanitise tout message entrant (bornes sur dims, longueurs) — toute nouvelle commande client doit y être validée.
### PtyManager (`packages/server/src/core/pty-manager.ts`)
Lance `claude` (ou `bash`) dans node-pty. Sessions vivantes en mémoire (`Map`) ; l'historique est persisté dans la table `sessions` (sqlite). Chaque session a un `RingBuffer` (2 Mo) ; à l'attach, le client reçoit un **resync** = reset terminal + replay de la queue du ring (`REPLAY_TAIL_BYTES`). Outil mono-utilisateur : tout client interactif peut écrire, les observers sont read-only. `kill` envoie SIGTERM puis SIGKILL après un délai de grâce.
### claude-launcher (`packages/server/src/core/claude-launcher.ts`)
Couture volontairement abstraite : Arboretum enveloppe le **CLI `claude` interactif** dans un PTY (pas l'Agent SDK, pas le mode headless). La commande `bash` sert aux tests sans quota. C'est ici que se brancherait un éventuel plan B.
### Détails fastify à connaître
- La route `/ws` est enregistrée **après** le plugin `@fastify/websocket` dans un contexte encapsulé (`app.register(async (scoped) => ...)`) ; sinon le handler reçoit la signature REST `(request, reply)` au lieu de `(socket, req)`.
- `notFoundHandler` renvoie l'`index.html` de la SPA pour tout ce qui n'est pas `/api/` ou `/ws` (routing client-side).
### Base de données (`packages/server/src/db/index.ts`)
`node:sqlite` en mode WAL. Migrations idempotentes versionnées dans le tableau `MIGRATIONS` + table `schema_migrations`. Tables : `settings`, `auth_tokens`, `sessions`.
## Architecture web
SPA Vue 3. Un **singleton `wsClient`** (`src/lib/ws-client.ts`) gère l'unique connexion : handshake, reconnexion avec backoff, ré-attache des terminaux ouverts, corrélation FIFO des `attached`, et le **flow control par ACK côté client** (compteur d'octets réellement traités par xterm, remis à zéro à chaque resync, avec un ACK traînant débouncé anti-deadlock). En dev, `vite.config.ts` proxifie `/api` et `/ws` vers le daemon en **réécrivant l'en-tête Origin** vers celle du daemon (sinon le check Origin strict rejette l'origine de Vite). Le garde de routeur vérifie la session via `GET /api/v1/auth/me`.
## Spikes & roadmap
Les `spikes/sN-*/VERDICT.md` documentent des décisions qui contraignent l'implémentation à venir, notamment :
- **`--resume` doit toujours s'exécuter dans le cwd d'origine** de la session (lu dans le JSONL).
- La **vivacité** d'une session se déduit de `pid` + `procStart`, **jamais** de la présence du fichier registre.
- La distinction d'états fins (busy / waiting / idle) du futur `claude-adapter` (P3) nécessite une lecture d'écran via `@xterm/headless` (le strip ANSI naïf mange les espaces) + le registre `~/.claude/sessions`.
Les états de session du protocole sont aujourd'hui un sous-ensemble P1 (`starting`/`running`/`exited`) à étendre en P3.
-285
View File
@@ -1,285 +0,0 @@
<p align="center">
<img src="brand/arboretum-logo-on-dark.png" alt="Arboretum" width="300">
</p>
<p align="center">
Un dashboard web auto-hébergé pour vos worktrees git et les sessions Claude Code qui tournent dessus — depuis n'importe quel appareil.
</p>
<p align="center">
<a href="README.md">English</a> · <strong>Français</strong>
</p>
**Statut : MVP.** Le dashboard worktree-first, la découverte et la reprise de sessions, le cycle de vie des worktrees multi-repo, le démarrage de sessions sur votre branche principale ou n'importe quel worktree, les états de session en temps réel, le terminal web, la supervision mobile (PWA installable, Web Push quand une session vous attend, répondre à une demande sans ouvrir de terminal) et les groupes de travail (piloter plusieurs repos liés depuis une seule session Claude) sont implémentés et testés.
---
## Le problème
Travailler avec des agents de code IA a changé notre usage de git : une feature = un worktree = une session Claude Code, plusieurs en parallèle. Mais l'outillage n'a pas suivi :
- `git worktree list` sur plusieurs repos est fastidieux, les worktrees s'accumulent, chacun a besoin de ses `node_modules` et `.env`.
- Les sessions Claude Code sont éparpillées : certaines tournent dans des terminaux, d'autres sont reprenables depuis l'historique, sans vue consolidée de *celle qui attend votre intervention*.
- Quand vous vous éloignez de votre poste, une session bloquée sur une demande de permission reste bloquée.
## Ce que fait Arboretum
Un unique daemon Node.js que vous lancez sur votre machine de dev (`npx @johanleroy/git-arboretum`), servant une interface web utilisable depuis votre ordinateur, téléphone ou tablette :
- **Dashboard worktree-first, multi-repo** — chaque worktree de chaque repo enregistré, avec son état git (branche, ahead/behind, fichiers modifiés) *et* l'état de sa session Claude Code (busy / en attente d'entrée / idle / reprenable).
- **Cycle de vie complet des worktrees** — créer (avec des hooks post-création par repo : `npm ci`, copie de `.env`…), adopter des worktrees créés à la main, supprimer avec garde-fous, élaguer les orphelins.
- **Découverte & reprise de sessions** — les sessions lancées dans votre propre terminal apparaissent automatiquement ; reprenez les sessions mortes, observez ou forkez les vivantes. Ne corrompt jamais une session vivante. Masquez les anciennes qui encombrent la liste (un clic efface tout l'historique externe ; elles restent reprenables).
- **Terminal web** — terminal xterm.js complet vers chaque session managée, qui survit aux déconnexions du navigateur ; vraiment plein écran, avec l'invite ancrée en bas et tout l'historique défilable au-dessus.
- **Supervision depuis votre téléphone** — PWA installable avec notifications push quand une session vous attend ; répondez à une demande (ses options, ou refusez) sans ouvrir de terminal.
- **Groupes de travail** — regroupez des repos liés (ex. une API, son frontend web et sa doc) dans un groupe nommé, puis lancez **une seule session Claude qui les couvre tous à la fois** (via le flag `--add-dir` du CLI) : une conversation unique avec un contexte partagé travaillant à travers chaque repo, plus une vue unifiée de tous leurs worktrees et une grille multi-terminaux côte à côte. Une session de groupe peut d'abord créer le même worktree de branche dans chaque repo, ou tourner directement sur les checkouts principaux.
- **Extension VS Code** — une extension native (pas un webview) qui amène l'arbre en direct, les terminaux de session natifs, les alertes d'attente et les actions git directement dans votre éditeur. Voir [Extension VS Code](#extension-vs-code).
---
## Prérequis
- **Node.js ≥ 22.16** — requis, pas seulement recommandé. Arboretum persiste son état avec `node:sqlite` (`DatabaseSync`), natif et stable seulement à partir de cette version. (`.nvmrc` fixe `22`.)
- **Le CLI `claude`** sur votre `PATH` si vous voulez qu'Arboretum lance et gère des sessions Claude Code. Arboretum enveloppe le CLI interactif que vous utilisez déjà — installez-le et authentifiez-le comme d'habitude.
- Un **dépôt git** (ou plusieurs) que vous voulez gérer.
## Démarrage rapide
Deux chemins, selon ce que vous voulez :
- **Juste l'utiliser (la plupart des gens).** Arboretum est un paquet npm publié — vous **n'avez pas besoin de cloner ce dépôt**. Pointez npm vers le registre et lancez-le (ci-dessous). À faire sur la machine où tournent vos sessions Claude Code.
- **Lancer depuis les sources.** Ne clonez le dépôt que pour développer Arboretum ou lancer une version non publiée.
### Le lancer (recommandé)
Arboretum est publié sur un registre npm Gitea auto-hébergé. Pointez le scope `@johanleroy` dessus une fois par machine — ajoutez à `~/.npmrc` :
```
@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/
```
Aucun token nécessaire — le paquet est en lecture publique. Puis lancez-le depuis n'importe où :
```bash
npx @johanleroy/git-arboretum
```
Au premier démarrage, Arboretum affiche un **token d'accès** unique et l'URL à ouvrir :
```
┌──────────────────────────────────────────────────────────────────┐
│ First start — your access token (shown once, store it safely): │
└──────────────────────────────────────────────────────────────────┘
<votre-token-ici>
Login at: http://127.0.0.1:7317/
```
Ouvrez l'URL, collez le token pour vous connecter, et c'est parti. Le token est stocké **hashé** — il n'est affiché qu'une seule fois, alors gardez-le en lieu sûr (un gestionnaire de mots de passe). Vous pourrez gérer vos tokens plus tard depuis les **Réglages**.
`npx` télécharge et lance la dernière version publiée à chaque fois. Pour l'installer une bonne fois — et obtenir la commande `arboretum` sur votre `PATH`, dont se sert le [service d'arrière-plan](#le-faire-tourner-en-service-darrière-plan) —, installez-le plutôt globalement :
```bash
npm i -g @johanleroy/git-arboretum
arboretum # identique à la commande npx, depuis le binaire installé
```
### Lancer depuis les sources
Nécessaire uniquement pour **développer** Arboretum ou lancer une version non publiée — pas pour simplement l'utiliser. Clonez le dépôt, installez les dépendances, buildez, puis démarrez le daemon :
```bash
git clone https://git.lidge.fr/johanleroy/arboretum.git
cd arboretum
nvm use # ou assurez-vous d'avoir Node ≥ 22.16
npm install
npm run build # build shared → server → web (l'ordre compte)
node packages/server/dist/index.js
```
## Utiliser Arboretum
1. **Ajoutez un dépôt.** Depuis le dashboard, enregistrez un repo git local par son chemin. Configurez éventuellement des **hooks post-création** (ex. `npm ci`, `cp ../.env .env`) exécutés automatiquement à chaque création d'un nouveau worktree pour ce repo.
2. **Créez ou adoptez des worktrees.** Créez un nouveau worktree + branche en un clic (les hooks s'exécutent pour vous), ou adoptez un worktree créé à la main. Chaque worktree affiche sa branche, son ahead/behind et son nombre de fichiers modifiés.
3. **Démarrez ou reprenez une session.** Lancez une session Claude Code sur la branche principale du repo ou n'importe quel worktree, ou reprenez-en une démarrée dans votre terminal — Arboretum découvre les sessions existantes automatiquement et les reprend toujours dans leur répertoire de travail d'origine.
4. **Suivez les états en direct.** Chaque session indique si elle est *busy*, *en attente de votre entrée* ou *idle*. Ouvrez le **terminal web** pour interagir directement ; il survit aux déconnexions du navigateur (fermer l'onglet ne tue pas la session).
5. **Supervisez depuis votre téléphone.** Installez la PWA, et quand une session bascule en *attente*, vous recevez une notification push. Répondez à la demande — choisissez l'une de ses options ou refusez-la — directement depuis le dashboard, sans terminal.
## Extension VS Code
Vous préférez rester dans votre éditeur ? Arboretum fournit une **extension VS Code native** (`packages/vscode`) — pas un webview. Elle se connecte au même daemon et l'expose avec les primitives natives de VS Code :
- Un arbre **Repositories** et **Groups** en direct (repos → worktrees → sessions) dans l'Activity Bar, mis à jour en temps réel via le WebSocket du daemon.
- **Terminaux natifs** : attachez-vous (ou observez) n'importe quelle session dans un vrai terminal VS Code — vous bénéficiez du rendu, du scrollback et du copier-coller de VS Code gratuitement.
- Un compteur en **status bar** et des **notifications** natives quand une session attend, avec réponses Oui/Non sans ouvrir de terminal.
- Les mutations git (créer un worktree, commit, push, promouvoir) et la **conscience du workspace** — le worktree de votre dossier ouvert est mis en évidence, avec « démarrer une session / créer un worktree ici » en un clic.
Elle est distribuée en **VSIX privé**. Buildez-la et packagez-la depuis le monorepo :
```bash
npm run build:vscode
cd packages/vscode && npx @vscode/vsce package --no-dependencies # → git-arboretum-0.1.0.vsix
```
Puis installez-la via **Extensions : Installer à partir d'un VSIX…** (ou `code --install-extension git-arboretum-0.1.0.vsix`), lancez **Arboretum: Sign In** et collez un token. Détails complets dans [`packages/vscode/README.md`](packages/vscode/README.md).
## Accès distant depuis votre téléphone
Arboretum se bind sur `127.0.0.1` par défaut et **refuse** de se binder sur une adresse non-loopback sans dérogation explicite. La façon recommandée (et sûre) de l'atteindre depuis d'autres appareils est **[Tailscale Serve](https://tailscale.com/kb/1242/tailscale-serve)** — HTTPS valide, identité tailnet, aucun port ouvert :
```bash
# Expose le daemon local en HTTPS dans votre tailnet
tailscale serve --bg 7317
```
Puis démarrez Arboretum en autorisant l'origine de votre tailnet (le check Origin strict doit la connaître) :
```bash
npx @johanleroy/git-arboretum --allow-origin https://<machine>.<tailnet>.ts.net
```
Ouvrez `https://<machine>.<tailnet>.ts.net` depuis n'importe quel appareil de votre tailnet. **Web Push exige HTTPS**, donc Tailscale Serve (ou un autre front HTTPS) est aussi ce qui active les notifications mobiles. Sur **iOS**, installez d'abord l'app à l'écran d'accueil, puis autorisez les notifications.
> ⚠️ Un terminal web, c'est de l'exécution de code à distance **par conception**. N'exposez jamais Arboretum directement sur l'internet public.
## Le faire tourner en service d'arrière-plan
Le plus rapide pour faire tourner Arboretum en service qui survit à la déconnexion et redémarre au boot, c'est l'installeur intégré. Installez une version figée globalement, puis lancez `install` — il détecte votre OS, écrit le fichier de service, le démarre et affiche le token unique :
```bash
npm i -g @johanleroy/git-arboretum
arboretum install --allow-origin https://MACHINE.TAILNET.ts.net
```
Cela met en place un **service systemd utilisateur** sous Linux (`~/.config/systemd/user/arboretum.service`) ou un **LaunchAgent launchd** sous macOS (`~/Library/LaunchAgents/fr.lidge.arboretum.plist`). Tous les flags du daemon (`--port`, `--allow-origin`, `--db`, …) sont propagés au service. Gérez-le avec :
```bash
arboretum status # état du service (+ où lire les logs)
arboretum uninstall # arrête et supprime le service
```
Les logs vivent dans `journalctl --user -u arboretum -f` (Linux) ou `~/Library/Logs/arboretum/` (macOS). Lancez d'abord `arboretum install --dry-run …` pour afficher le unit/plist et les commandes exactes sans rien modifier.
<details>
<summary>Vous préférez configurer systemd à la main ? (Linux)</summary>
Créez `~/.config/systemd/user/arboretum.service` :
```ini
[Unit]
Description=Arboretum — git worktree & Claude Code dashboard
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=%h/.local/bin/arboretum --port 7317 --allow-origin https://MACHINE.TAILNET.ts.net
Restart=on-failure
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=10
Environment=NODE_ENV=production
[Install]
WantedBy=default.target
```
```bash
which arboretum # ajustez ExecStart au vrai chemin si besoin
systemctl --user daemon-reload
systemctl --user enable --now arboretum
loginctl enable-linger "$USER" # démarre le service au boot, sans session ouverte
journalctl --user -u arboretum -f # logs
```
</details>
> Le **token d'accès** unique est affiché par `arboretum install` (et au tout premier lancement manuel sur base vierge). Le token est hashé et n'est jamais réaffiché — conservez-le en lieu sûr.
## Configuration
Commandes : `arboretum` démarre le daemon (par défaut), `arboretum serve` en est un alias explicite, `arboretum install` / `uninstall` / `status` gèrent le service d'arrière-plan, et `arboretum help` affiche l'aide.
Les options du daemon sont des flags CLI :
| Flag | Défaut | Description |
|---|---|---|
| `--port <n>` | `7317` | Port d'écoute. |
| `--bind <addr>` | `127.0.0.1` | Adresse de bind. Une adresse non-loopback est refusée sauf si `--i-know-this-exposes-a-terminal` est défini. |
| `--allow-origin <url>` | — | Origine `Origin` autorisée supplémentaire (répétable). Nécessaire pour l'accès Tailscale/HTTPS. |
| `--db <path>` | `<data>/arboretum.db` | Chemin de la base SQLite. |
| `--vapid-contact <mailto/url>` | `mailto:arboretum@localhost` | Sujet de contact VAPID pour le Web Push. |
| `--print-token` | `false` | Indication sur le réaffichage du token (les tokens sont hashés et ne peuvent pas être réaffichés). |
| `--i-know-this-exposes-a-terminal` | `false` | Reconnaître le bind sur une adresse non-loopback. **À éviter** — préférez Tailscale Serve. |
`arboretum install` accepte tous les flags du daemon ci-dessus (propagés tels quels au service), plus :
| Flag | Description |
|---|---|
| `--bin-path <path>` | Utilise ce binaire dans le service au lieu de `node` + le script embarqué. |
| `--label <id>` | Label launchd (macOS uniquement, défaut `fr.lidge.arboretum`). |
| `--dry-run` | Affiche le unit/plist et les commandes sans rien appliquer. |
| `--no-enable` | Écrit le fichier de service sans l'activer/le démarrer. |
L'état (la base SQLite) vit dans `$XDG_DATA_HOME/arboretum` (par défaut `~/.local/share/arboretum`).
## Modèle de sécurité
Un terminal web, c'est de l'exécution de code à distance *par conception*. Les garde-fous d'Arboretum sont structurants :
- Se bind sur `127.0.0.1` par défaut ; refuse les binds non-loopback sans flag explicite.
- Authentifie **chaque** requête `/api/**` **et** chaque upgrade `/ws` avec des tokens révocables, et applique un **check `Origin` strict** (le cookie `SameSite=Strict` ne couvre pas les upgrades WebSocket — c'est le garde-fou anti cross-site hijacking).
- Les tokens sont stockés **hashés** (sha256) et comparés en temps constant ; le bootstrap token n'est affiché qu'une seule fois. Le cookie de session est un payload signé HMAC, `HttpOnly` et `SameSite=Strict`, et reçoit automatiquement le flag `Secure` quand la requête arrive en HTTPS (p. ex. derrière Tailscale Serve). Le login est rate-limité avec backoff exponentiel.
- Envoie des en-têtes HTTP durcis (CSP, `X-Frame-Options`, `nosniff`, `Referrer-Policy`, HSTS conditionnel, `no-store` sur l'API), restreint le dossier de données à `0o700` et la base à `0o600`, et **chiffre les secrets sensibles au repos** (AES-256-GCM).
- Tient un **journal d'audit** des opérations sensibles et offre l'**export/effacement RGPD** des données (Réglages → Sécurité & conformité).
Tailscale Serve est **la** façon d'atteindre Arboretum depuis d'autres appareils — pas seulement une recommandation : HTTPS valide, identité tailnet, aucun port ouvert. Le flag `--i-know-this-exposes-a-terminal` est une trappe de secours, pas un mode de déploiement ; n'exposez jamais Arboretum directement sur internet.
Voir [`SECURITY.md`](SECURITY.md) pour le modèle de menace complet et [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md) pour le durcissement en environnement réglementé.
## Ce qui le distingue
| | Arboretum | GitKraken Agent Mode / Conductor / Nimbalyst | Happy / CloudCLI | Anthropic Remote Control |
|---|---|---|---|---|
| Interface web, tout appareil | ✅ | ❌ apps desktop | ✅ | ✅ |
| Gestion visuelle des worktrees (multi-repo) | ✅ | ✅ (mono-repo, desktop) | ❌ | ❌ |
| Découvre & reprend les sessions de terminal *existantes* | ✅ | ❌ | partiel | ❌ |
| 100 % auto-hébergé — zéro trafic via des serveurs tiers | ✅ | ✅ | serveur relais | ❌ relayé via Anthropic |
| Linux-first | ✅ | variable | ✅ | l'app desktop n'a pas de build Linux |
| Open source | MIT | ❌ / partiel | MIT / AGPL | ❌ |
Le Remote Control d'Anthropic est excellent pour piloter *une* session depuis votre téléphone. Arboretum est la couche qu'il ne fournit pas : le tableau consolidé et auto-hébergé de tous vos worktrees et sessions, à travers tous vos repos.
## Une note sur l'usage de Claude
Arboretum enveloppe le CLI Claude Code **interactif** dans un PTY — la même chose que vous lancez dans votre terminal, affichée dans votre navigateur. Il n'utilise pas l'Agent SDK ni le mode headless. Les politiques d'usage d'Anthropic autour de l'usage programmatique peuvent évoluer ; Arboretum suivra les sorties du CLI et documentera tout impact de façon transparente.
## Développement
Arboretum est un monorepo npm workspaces : `@arboretum/shared` (protocole WS/REST, source de vérité), `@johanleroy/git-arboretum` (le daemon Fastify, le paquet publié), `@arboretum/web` (la SPA Vue 3) et `git-arboretum` (l'extension VS Code — buildée séparément avec `npm run build:vscode`).
```bash
npm run build # build shared → server → web (l'ordre compte)
npm run typecheck # tsc -b shared + server
npm test # vitest sur les packages
npm run dev:server # daemon en watch
npm run dev:web # serveur de dev Vite (proxifie /api et /ws vers le daemon sur :7317)
```
Scripts d'acceptation end-to-end (lancez `npm run build` d'abord) :
```bash
node packages/server/scripts/acceptance-p1.mjs # cœur : daemon + client WS réel
node packages/server/scripts/acceptance-p2.mjs # découverte & reprise de sessions
node packages/server/scripts/acceptance-p3.mjs # worktrees & corrélation de sessions
node packages/server/scripts/acceptance-p4.mjs # Web Push + commande WS `answer`
node packages/server/scripts/acceptance-p5.mjs # groupes de travail : CRUD + broadcast WS + CASCADE
```
## Soutenir le projet
Arboretum est un projet personnel libre et auto-financé. S'il vous fait gagner du temps, vous pouvez soutenir son développement :
[![Buy Me a Coffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-johanleroy-FFDD00?logo=buymeacoffee&logoColor=black)](https://buymeacoffee.com/johanleroy)
## Licence
MIT — voir [LICENSE](LICENSE).
+11 -248
View File
@@ -1,18 +1,8 @@
<p align="center">
<img src="brand/arboretum-logo-on-dark.png" alt="Arboretum" width="300">
</p>
# Arboretum
<p align="center">
A self-hosted web dashboard for your git worktrees and the Claude Code sessions running on them — from any device.
</p>
> A self-hosted web dashboard for your git worktrees and the Claude Code sessions running on them — from any device.
<p align="center">
<strong>English</strong> · <a href="README.fr.md">Français</a>
</p>
**Status: MVP.** The worktree-first dashboard, session discovery & resume, multi-repo worktree lifecycle, sessions on your main branch or any worktree, live session states, the web terminal, mobile supervision (installable PWA, Web Push when a session needs you, answer a prompt without opening a terminal), and work groups (drive several related repos from a single Claude session) are implemented and tested.
---
**Status: early development (pre-MVP).** The design study and architecture are complete; implementation is in progress. Not usable yet.
## The problem
@@ -24,216 +14,13 @@ Working with AI coding agents changed how we use git: one feature = one worktree
## What Arboretum does
A single Node.js daemon you run on your dev machine (`npx @johanleroy/git-arboretum`), serving a web UI usable from your desktop, phone or tablet:
A single Node.js daemon you run on your dev machine (`npx git-arboretum`), serving a web UI usable from your desktop, phone or tablet:
- **Worktree-first, multi-repo dashboard** — every worktree of every registered repo, with its git state (branch, ahead/behind, dirty files) *and* the state of its Claude Code session (busy / waiting for input / idle / resumable).
- **Full worktree lifecycle** — create (with per-repo post-create hooks: `npm ci`, copy `.env`…), adopt worktrees created by hand, delete with guardrails, prune orphans.
- **Session discovery & resume** — sessions you launched in your own terminal show up automatically; resume dead ones, observe or fork live ones. Never corrupts a live session. Hide the old ones that clutter the list (one click clears the whole external history; they stay resumable).
- **Web terminal** — full xterm.js terminal to every managed session, surviving browser disconnects; truly fullscreen, with the prompt pinned to the bottom and full scrollback above.
- **Supervision from your phone** — installable PWA with push notifications when a session needs you; answer a prompt (its options, or deny) without opening a terminal.
- **Work groups** — bundle related repos (e.g. an API, its web frontend and its docs) into a named group, then launch **one Claude session that spans all of them at once** (via the CLI's `--add-dir`): a single conversation with one shared context working across every repo, plus a unified view of all their worktrees and a side-by-side multi-terminal grid. Group sessions can either create the same branch worktree in each repo first, or run straight on the main checkouts.
- **VS Code extension** — a native extension (not a webview) that brings the live tree, native session terminals, waiting alerts and git actions right into your editor. See [VS Code extension](#vs-code-extension).
---
## Requirements
- **Node.js ≥ 22.16** — required, not just recommended. Arboretum persists state with `node:sqlite` (`DatabaseSync`), which is native and stable only from this version. (`.nvmrc` pins `22`.)
- **The `claude` CLI** on your `PATH` if you want Arboretum to launch and manage Claude Code sessions. Arboretum wraps the interactive CLI you already use — install and authenticate it as usual.
- A **git** repository (or several) you want to manage.
## Quick start
Two paths, depending on what you want:
- **Just use it (most people).** Arboretum is a published npm package — you **don't need to clone this repo**. Point npm at the registry and run it (below). Do this on the machine where your Claude Code sessions run.
- **Run from source.** Clone the repo only to hack on Arboretum or run an unreleased build.
### Run it (recommended)
Arboretum is published to a self-hosted Gitea npm registry. Point the `@johanleroy` scope at it once per machine — add to `~/.npmrc`:
```
@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/
```
No token needed — the package is publicly readable. Then run it from anywhere:
```bash
npx @johanleroy/git-arboretum
```
On first start, Arboretum prints a one-time **access token** and the URL to open:
```
┌──────────────────────────────────────────────────────────────────┐
│ First start — your access token (shown once, store it safely): │
└──────────────────────────────────────────────────────────────────┘
<your-token-here>
Login at: http://127.0.0.1:7317/
```
Open the URL, paste the token to log in, and you're in. The token is stored **hashed** — it is shown only once, so save it somewhere safe (a password manager). You can manage tokens later from **Settings**.
`npx` fetches and runs the latest published version each time. To install it once — and get the `arboretum` command on your `PATH`, which the [background service](#running-it-as-a-background-service) relies on — install it globally instead:
```bash
npm i -g @johanleroy/git-arboretum
arboretum # identical to the npx command, from the installed binary
```
### Run from source
Only needed to **develop** Arboretum or run an unreleased build — not required just to use it. Clone the repo, install dependencies, build, then start the daemon:
```bash
git clone https://git.lidge.fr/johanleroy/arboretum.git
cd arboretum
nvm use # or ensure Node ≥ 22.16
npm install
npm run build # builds shared → server → web (order matters)
node packages/server/dist/index.js
```
## Using Arboretum
1. **Add a repository.** From the dashboard, register a local git repo by its path. Optionally configure **post-create hooks** (e.g. `npm ci`, `cp ../.env .env`) that run automatically every time you create a new worktree for that repo.
2. **Create or adopt worktrees.** Spin up a new worktree + branch in one click (hooks run for you), or adopt a worktree you created by hand. Each worktree shows its branch, ahead/behind, and dirty-file count.
3. **Start or resume a session.** Launch a Claude Code session on the repo's main branch or any worktree, or resume one that was started in your terminal — Arboretum discovers existing sessions automatically and always resumes them in their original working directory.
4. **Watch the live states.** Each session reports whether it's *busy*, *waiting for your input*, or *idle*. Open the **web terminal** to interact directly; it survives browser disconnects (closing the tab does not kill the session).
5. **Supervise from your phone.** Install the PWA, and when a session flips to *waiting* you get a push notification. Answer the prompt — pick one of its options or deny it — straight from the dashboard, no terminal required.
## VS Code extension
Prefer to stay in your editor? Arboretum ships a **native VS Code extension** (`packages/vscode`) — not a webview. It connects to the same daemon and surfaces it with VS Code's own primitives:
- A live **Repositories** and **Groups** tree (repos → worktrees → sessions) in the Activity Bar, updated in real time over the daemon's WebSocket.
- **Native terminals**: attach to (or observe) any session in a real VS Code terminal — you get VS Code's rendering, scrollback and copy/paste for free.
- A **status-bar** counter and native **notifications** when a session is waiting, with Yes/No answers without opening a terminal.
- Git mutations (create worktree, commit, push, promote) and **workspace awareness** — the worktree for your open folder is highlighted, with one-click "start session / create worktree here".
It is distributed as a **private VSIX**. Build and package it from the monorepo:
```bash
npm run build:vscode
cd packages/vscode && npx @vscode/vsce package --no-dependencies # → git-arboretum-0.1.0.vsix
```
Then install it via **Extensions: Install from VSIX…** (or `code --install-extension git-arboretum-0.1.0.vsix`), run **Arboretum: Sign In** and paste a token. Full details in [`packages/vscode/README.md`](packages/vscode/README.md).
## Remote access from your phone
Arboretum binds to `127.0.0.1` by default and **refuses** to bind to a non-loopback address without an explicit override. The recommended (and safe) way to reach it from other devices is **[Tailscale Serve](https://tailscale.com/kb/1242/tailscale-serve)** — valid HTTPS, tailnet identity, no open ports:
```bash
# Expose the local daemon over HTTPS inside your tailnet
tailscale serve --bg 7317
```
Then start Arboretum allowing your tailnet origin (the strict Origin check needs to know about it):
```bash
npx @johanleroy/git-arboretum --allow-origin https://<machine>.<tailnet>.ts.net
```
Open `https://<machine>.<tailnet>.ts.net` from any device on your tailnet. **Web Push requires HTTPS**, so Tailscale Serve (or another HTTPS front) is also what enables mobile notifications. On **iOS**, install the app to your home screen first, then allow notifications.
> ⚠️ A web terminal is remote code execution **by design**. Never expose Arboretum directly to the public internet.
## Running it as a background service
The quickest way to run Arboretum as a service that survives logout and restarts on boot is the built-in installer. Install a pinned version globally, then run `install` — it detects your OS, writes the service file, starts it, and prints the one-time token:
```bash
npm i -g @johanleroy/git-arboretum
arboretum install --allow-origin https://MACHINE.TAILNET.ts.net
```
This sets up a **systemd user service** on Linux (`~/.config/systemd/user/arboretum.service`) or a **launchd LaunchAgent** on macOS (`~/Library/LaunchAgents/fr.lidge.arboretum.plist`). Every daemon flag (`--port`, `--allow-origin`, `--db`, …) is propagated to the service. Manage it with:
```bash
arboretum status # service status (+ where to read logs)
arboretum uninstall # stop and remove the service
```
Logs live in `journalctl --user -u arboretum -f` (Linux) or `~/Library/Logs/arboretum/` (macOS). Run `arboretum install --dry-run …` first to print the unit/plist and the exact commands without touching anything.
<details>
<summary>Prefer to set up systemd by hand? (Linux)</summary>
Create `~/.config/systemd/user/arboretum.service`:
```ini
[Unit]
Description=Arboretum — git worktree & Claude Code dashboard
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=%h/.local/bin/arboretum --port 7317 --allow-origin https://MACHINE.TAILNET.ts.net
Restart=on-failure
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=10
Environment=NODE_ENV=production
[Install]
WantedBy=default.target
```
```bash
which arboretum # adjust ExecStart to the real path if needed
systemctl --user daemon-reload
systemctl --user enable --now arboretum
loginctl enable-linger "$USER" # start the service at boot, without an open session
journalctl --user -u arboretum -f # logs
```
</details>
> The one-time **access token is printed by `arboretum install`** (and on the very first manual run with an empty database). The token is hashed and never shown again — store it safely.
## Configuration
Commands: `arboretum` starts the daemon (the default), `arboretum serve` is an explicit alias, `arboretum install` / `uninstall` / `status` manage the background service, and `arboretum help` prints usage.
Daemon options are CLI flags:
| Flag | Default | Description |
|---|---|---|
| `--port <n>` | `7317` | Port to listen on. |
| `--bind <addr>` | `127.0.0.1` | Bind address. Non-loopback is refused unless `--i-know-this-exposes-a-terminal` is set. |
| `--allow-origin <url>` | — | Additional allowed `Origin` (repeatable). Needed for Tailscale/HTTPS access. |
| `--db <path>` | `<data>/arboretum.db` | SQLite database path. |
| `--vapid-contact <mailto/url>` | `mailto:arboretum@localhost` | VAPID contact subject for Web Push. |
| `--print-token` | `false` | Hint about token re-printing (tokens are hashed and cannot be re-shown). |
| `--i-know-this-exposes-a-terminal` | `false` | Acknowledge binding to a non-loopback address. **Avoid** — prefer Tailscale Serve. |
`arboretum install` accepts every daemon flag above (propagated verbatim to the service) plus:
| Flag | Description |
|---|---|
| `--bin-path <path>` | Use this binary in the service instead of `node` + the bundled script. |
| `--label <id>` | launchd label (macOS only, default `fr.lidge.arboretum`). |
| `--dry-run` | Print the unit/plist and commands without applying anything. |
| `--no-enable` | Write the service file but do not enable/start it. |
State (the SQLite database) lives in `$XDG_DATA_HOME/arboretum` (default `~/.local/share/arboretum`).
## Security model
A web terminal is remote code execution *by design*. Arboretum's guardrails are structural:
- Binds to `127.0.0.1` by default; refuses non-loopback binds without an explicit flag.
- Authenticates **every** `/api/**` request **and** every `/ws` upgrade with revocable tokens, and applies a **strict `Origin` check** (the `SameSite=Strict` cookie does not cover WebSocket upgrades — this is the anti cross-site hijacking guard).
- Tokens are stored **hashed** (sha256) and compared in constant time; the bootstrap token is shown only once. The session cookie is an HMAC-signed payload, `HttpOnly` and `SameSite=Strict`, and it automatically gains the `Secure` flag when the request arrives over HTTPS (e.g. behind Tailscale Serve). Login is rate-limited with exponential backoff.
- Sends hardened HTTP headers (CSP, `X-Frame-Options`, `nosniff`, `Referrer-Policy`, conditional HSTS, `no-store` on the API), restricts the data directory to `0o700` and the database to `0o600`, and **encrypts sensitive secrets at rest** (AES-256-GCM).
- Keeps an **audit log** of sensitive operations and offers **GDPR** data export/erasure (Settings → Security & compliance).
Tailscale Serve is **the** way to reach Arboretum from other devices — not just a recommendation: valid HTTPS, tailnet identity, no open ports. The `--i-know-this-exposes-a-terminal` flag is an escape hatch, not a deployment mode; never expose Arboretum directly to the internet.
See [`SECURITY.md`](SECURITY.md) for the full threat model and [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md) for hardening in regulated environments.
- **Session discovery & resume** — sessions you launched in your own terminal show up automatically; resume dead ones, observe or fork live ones. Never corrupts a live session.
- **Web terminal** — full xterm.js terminal to every managed session, surviving browser disconnects.
- **Supervision from your phone** *(post-MVP)* — PWA with push notifications when a session needs you, approve/deny without opening a terminal.
## What makes it different
@@ -248,38 +35,14 @@ See [`SECURITY.md`](SECURITY.md) for the full threat model and [`docs/ENTERPRISE
Anthropic's Remote Control is great at piloting *one* session from your phone. Arboretum is the layer it doesn't provide: the consolidated, self-hosted board of all your worktrees and sessions across all your repos.
## Security model
A web terminal is remote code execution *by design*. Arboretum binds to `127.0.0.1` by default, authenticates every request **and** every WebSocket upgrade with revocable tokens, and strictly checks the `Origin` header. The recommended way to reach it from other devices is [Tailscale Serve](docs/tailscale.md) (valid HTTPS, tailnet identity, no open ports). Never expose it directly to the internet.
## A note on Claude usage
Arboretum wraps the **interactive** Claude Code CLI in a PTY — the same thing you run in your terminal, displayed in your browser. It does not use the Agent SDK or headless mode. Anthropic's usage policies around programmatic use may evolve; Arboretum will track CLI releases and document any impact transparently.
## Development
Arboretum is an npm-workspaces monorepo: `@arboretum/shared` (WS/REST protocol, source of truth), `@johanleroy/git-arboretum` (the Fastify daemon, the published package), `@arboretum/web` (the Vue 3 SPA), and `git-arboretum` (the VS Code extension — built separately with `npm run build:vscode`).
```bash
npm run build # build shared → server → web (order matters)
npm run typecheck # tsc -b shared + server
npm test # vitest across packages
npm run dev:server # daemon in watch mode
npm run dev:web # Vite dev server (proxies /api and /ws to the daemon on :7317)
```
End-to-end acceptance scripts (run `npm run build` first):
```bash
node packages/server/scripts/acceptance-p1.mjs # core: daemon + real WS client
node packages/server/scripts/acceptance-p2.mjs # session discovery & resume
node packages/server/scripts/acceptance-p3.mjs # worktrees & session correlation
node packages/server/scripts/acceptance-p4.mjs # Web Push + WS `answer` command
node packages/server/scripts/acceptance-p5.mjs # work groups: CRUD + WS broadcast + CASCADE
```
## Support
Arboretum is a free, self-funded side project. If it saves you time, you can support its development:
[![Buy Me a Coffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-johanleroy-FFDD00?logo=buymeacoffee&logoColor=black)](https://buymeacoffee.com/johanleroy)
## License
MIT — see [LICENSE](LICENSE).
-61
View File
@@ -1,61 +0,0 @@
# Security Policy
Arboretum is a self-hosted daemon that serves a web dashboard to drive git worktrees and the
Claude Code sessions running on them. **A web terminal is remote code execution by design** — that
is the product, not a bug. Arboretum's security model is therefore built on *structural* guards
(loopback-only binding, authenticated access, strict Origin checks) far more than on cryptography
alone.
This document describes the threat model, the controls that are implemented, the deliberate
trade-offs, and how to report a vulnerability. For hardening a deployment in a regulated
environment, see [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md).
## Threat model
- **Single-user by design.** Arboretum runs on the owner's machine and is meant for one operator.
There is no multi-tenant isolation and no RBAC — and none is claimed.
- **Loopback by default.** The server binds `127.0.0.1`; `config.ts` *refuses* any non-loopback bind
unless you pass `--i-know-this-exposes-a-terminal`. Remote access is expected via **Tailscale Serve**
(TLS + tailnet identity), never by opening a port.
- **The terminal is RCE.** Anyone who can authenticate can run code. The controls below exist to make
sure only the authenticated operator reaches it, and that the surrounding surface (cookies, headers,
data at rest) is hardened.
## Implemented controls
| Area | Control | Where |
| --- | --- | --- |
| Network | Loopback-only default; non-loopback refused without explicit flag | `packages/server/src/config.ts` |
| AuthN | Global guard on **all** `/api/**` and `/ws` (only login is public, and rate-limited) | `packages/server/src/app.ts` |
| AuthN | Tokens stored **hashed** (SHA-256), compared in constant time; bootstrap token shown once | `packages/server/src/auth/service.ts` |
| Sessions | Cookie is an HMAC-SHA256 signed payload, `HttpOnly` + `SameSite=Strict`, `Secure` when HTTPS | `packages/server/src/routes/auth.ts` |
| CSRF / WS | Strict `Origin` check on every `/api/**` and `/ws` request (anti cross-site WS hijacking) | `packages/server/src/app.ts` |
| CSRF | Mutations carrying a body must be `application/json` | `packages/server/src/app.ts` |
| Rate limit | Global login rate limit with exponential backoff (not per-IP — Tailscale fronts everything as 127.0.0.1) | `packages/server/src/auth/service.ts` |
| HTTP headers | CSP, `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy`, `Permissions-Policy`, conditional HSTS, `Cache-Control: no-store` on API; `Server` header stripped | `packages/server/src/app.ts` |
| Injection | All SQL is parameterized; all git calls use `execFile` (no shell); path-traversal guards | `packages/server/src/**` |
| Data at rest | DB file/dir forced to `0o600`/`0o700`; sensitive secrets (server secret, VAPID private key) encrypted with AES-256-GCM | `packages/server/src/db/index.ts`, `core/secret-box.ts` |
| Audit | Persistent audit log of sensitive mutations (tokens, settings, secrets, push, groups) | `packages/server/src/core/audit-log.ts` |
| Privacy | GDPR export (`/api/v1/data/export`) and erasure (`/api/v1/data/delete-my-data`) | `packages/server/src/routes/data.ts` |
| Install | Runs as a **user** service (systemd user unit / launchd LaunchAgent), never root | `packages/server/src/cli/install.ts` |
## Deliberate trade-offs
- **Long-lived API tokens.** Tokens do not expire by age (CLI automation stability) but can be revoked
instantly, and `last_used_at` is tracked. Review and rotate tokens periodically.
- **Encryption-at-rest key management.** With no `ARBORETUM_SECRET_KEY` set, the encryption key lives in
`dataDir/secret.key` (`0o600`) next to the database — this protects a leaked database *copy* (backup,
WAL) but not a full `dataDir` compromise. For strong protection, set `ARBORETUM_SECRET_KEY` and store it
separately from database backups. Full-DB SQLCipher is intentionally avoided (it breaks the `npx`
prebuilt portability).
- **No multi-user model.** If you need multiple operators with isolation, Arboretum is not the right tool.
## Reporting a vulnerability
Please report security issues **privately** — do not open a public issue.
- Email: **security@johanleroy.fr** (or `contact@johanleroy.fr`).
- Include a description, affected version, and reproduction steps.
- Expect an acknowledgement within **7 days** and a coordinated disclosure window of up to **90 days**.
Thank you for helping keep Arboretum users safe.
-42
View File
@@ -1,42 +0,0 @@
# Brand assets
Logo and icon assets for Arboretum. Source artwork is a neon circuit-tree (green
branches, cyan session nodes, a `>_` prompt at the base) on a dark background.
| File | Use |
| --- | --- |
| `arboretum-logo-source.png` | Master artwork (opaque dark background). Keep; everything else derives from it. |
| `arboretum-logo.png` | Full logo, **transparent**. Best on dark surfaces (the wordmark is light). |
| `arboretum-logo-on-dark.png` | Full logo on the app background `#09090b`. Safe on any theme — used in the README. |
| `arboretum-mark.png` | Square, **transparent**, tree only (no wordmark). Ideal **Gitea repo avatar** — reads on both light and dark. |
The transparent versions are extracted by luminance (alpha ∝ brightness), the clean
way to lift glow-on-black artwork: the dark background becomes fully transparent, the
bright strokes stay opaque, and the glow halos stay semi-transparent so the logo sits
correctly on any dark surface.
## Gitea
Upload `arboretum-mark.png` as the repository avatar (Settings → uploads a square image;
the tree-only mark stays legible at small sizes and works on Gitea's light and dark themes).
Use `arboretum-logo.png` (transparent) on dark pages, or `arboretum-logo-on-dark.png`
when the surrounding background might be light.
## App / favicon assets
The web-facing assets live in `packages/web/public/` and are wired into the SPA:
- `icon.svg` — scalable favicon, redrawn to match the brand (vector, glow, `>_`).
- `icon-192.png` / `icon-512.png` — maskable PWA icons (tree on `#09090b`, content in the safe zone).
- `apple-touch-icon.png` — iOS home-screen icon (180×180).
- `favicon.ico` — multi-size favicon (16/32/48), transparent.
- `logo.png` — transparent full logo for in-app use.
## Regenerate
```bash
python3 brand/build-assets.py # uses brand/arboretum-logo-source.png
python3 brand/build-assets.py other.png # or pass another source
```
Requires Python with Pillow + numpy. Writes both `brand/` and `packages/web/public/`.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 959 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 561 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 184 KiB

-100
View File
@@ -1,100 +0,0 @@
#!/usr/bin/env python3
"""Génère le jeu complet d'assets de marque Arboretum depuis le logo source.
Source : un PNG « néon sur fond sombre » (arbre-circuit + texte « Arboretum »).
On extrait l'alpha par luminance (méthode propre pour ce type d'artwork glow-on-black) :
chaque pixel reçoit une transparence proportionnelle à sa luminosité, ce qui rend le
fond sombre totalement transparent, garde le cœur des traits opaque et conserve le halo
en semi-transparent — donc lisible sur n'importe quel fond.
Sorties :
brand/arboretum-logo.png logo complet transparent (haute déf) — Gitea / README
brand/arboretum-mark.png marque carrée transparente (arbre seul) — avatar Gitea
brand/arboretum-logo-on-dark.png logo complet sur fond #09090b (fallback fond clair)
packages/web/public/logo.png logo complet transparent, optimisé pour l'UI
packages/web/public/icon-192.png icône PWA maskable (arbre, fond #09090b)
packages/web/public/icon-512.png icône PWA maskable (arbre, fond #09090b)
packages/web/public/apple-touch-icon.png icône iOS 180 (arbre, fond #09090b)
packages/web/public/favicon.ico favicon transparent (arbre, 16/32/48)
Usage : python3 brand/build-assets.py <source.png>
"""
import sys
import numpy as np
from PIL import Image
SRC = sys.argv[1] if len(sys.argv) > 1 else "brand/arboretum-logo-source.png"
BG = (9, 9, 11) # #09090b — couleur de fond du dashboard (manifest background_color/theme_color)
# Découpe verticale arbre / texte (mesurée sur la source)
TREE_Y = (130, 930) # arbre + curseur >_
FULL_Y = (130, 1060) # arbre + texte
def extract_rgba(path):
"""Charge la source et calcule l'alpha par luminance (floor + knee)."""
rgb = np.asarray(Image.open(path).convert("RGB"), dtype=np.float32)
maxc = rgb.max(axis=2)
# floor > canal max du fond (~14) pour annuler totalement le fond ; knee = seuil d'opacité.
floor, knee = 20.0, 185.0 # < floor : transparent ; >= knee : opaque
alpha = np.clip((maxc - floor) / (knee - floor), 0.0, 1.0) * 255.0
alpha[alpha < 8] = 0.0 # gate anti-bruit : un vrai fond transparent et une bbox serrée
out = np.dstack([rgb, alpha]).astype(np.uint8)
return Image.fromarray(out, "RGBA")
def crop_band(rgba, y0, y1):
"""Recadre une bande verticale puis serre sur le contenu non transparent."""
band = rgba.crop((0, y0, rgba.width, y1))
bbox = band.getbbox() # bbox sur l'alpha
return band.crop(bbox)
def square(content, pad_frac, bg=None):
"""Centre `content` dans un carré ; bg=None → transparent, sinon fond plein."""
side = round(max(content.size) / (1 - 2 * pad_frac))
fill = (0, 0, 0, 0) if bg is None else (*bg, 255)
canvas = Image.new("RGBA", (side, side), fill)
canvas.paste(content, ((side - content.width) // 2, (side - content.height) // 2), content)
return canvas
def save(img, path, size=None):
if size:
img = img.resize((size, size), Image.LANCZOS)
img.save(path)
print(f" {path} {img.size[0]}x{img.size[1]}")
def main():
rgba = extract_rgba(SRC)
full = crop_band(rgba, *FULL_Y) # logo complet transparent serré
tree = crop_band(rgba, *TREE_Y) # arbre seul transparent serré
print("brand/")
save(full, "brand/arboretum-logo.png")
save(square(tree, 0.08), "brand/arboretum-mark.png")
# logo complet sur fond sombre (pour surfaces claires où la transparence gêne)
on_dark = Image.new("RGBA", (full.width + 160, full.height + 160), (*BG, 255))
on_dark.paste(full, (80, 80), full)
save(on_dark, "brand/arboretum-logo-on-dark.png")
print("packages/web/public/")
# logo UI : largeur max 600 px, transparent
ui = full.copy()
ui.thumbnail((600, 600), Image.LANCZOS)
ui.save("packages/web/public/logo.png")
print(f" packages/web/public/logo.png {ui.size[0]}x{ui.size[1]}")
# icônes maskable : arbre dans la zone sûre (contenu ~80 %), fond #09090b
mask = square(tree, 0.12, bg=BG)
save(mask, "packages/web/public/icon-192.png", 192)
save(mask, "packages/web/public/icon-512.png", 512)
save(mask, "packages/web/public/apple-touch-icon.png", 180)
# favicon : arbre transparent, multi-tailles
fav = square(tree, 0.04)
fav.save("packages/web/public/favicon.ico", sizes=[(16, 16), (32, 32), (48, 48)])
print(" packages/web/public/favicon.ico 16/32/48")
if __name__ == "__main__":
main()
-95
View File
@@ -1,95 +0,0 @@
# Enterprise deployment guide
This guide complements [`../SECURITY.md`](../SECURITY.md) with the operational steps a regulated or
security-conscious organization needs to deploy Arboretum with confidence.
## 1. Remote access: Tailscale Serve (recommended)
Never open a public port. Keep the default `127.0.0.1` bind and put Arboretum behind Tailscale Serve:
```bash
# on the host running arboretum (default bind 127.0.0.1:7317)
tailscale serve --bg 7317
```
This gives you TLS, a stable `*.ts.net` hostname, and tailnet identity. Then add that origin to the
allow-list so the strict Origin check accepts it:
```bash
arboretum --allow-origin https://my-host.tailnet.ts.net
```
The `--i-know-this-exposes-a-terminal` flag exists only as an escape hatch for non-loopback binds; it
is **never** a deployment mode and is never injected automatically by `arboretum install`.
## 2. Encryption at rest
Sensitive secrets (the HMAC server secret and the VAPID private key) are encrypted with AES-256-GCM
before being stored in SQLite. Token values are never stored — only their SHA-256 hashes.
For **strong** protection (key not co-located with the database), provide a passphrase via the
environment instead of the on-disk key file:
```bash
ARBORETUM_SECRET_KEY='<a long random passphrase from your secrets manager>' arboretum
```
- Store this passphrase in your secrets manager / KMS, **separately** from database backups.
- Without it, the key is auto-generated in `dataDir/secret.key` (`0o600`). This still protects a leaked
database copy, but not a full `dataDir` compromise.
- Rotating the passphrase requires re-encrypting existing values; the simplest path is to revoke and
recreate the bootstrap token after rotation.
## 3. Filesystem permissions
On startup Arboretum forces `dataDir` to `0o700` and the database files (`*.db`, `-wal`, `-shm`) to
`0o600`. Verify after first run:
```bash
stat -c '%a %n' ~/.local/share/arboretum ~/.local/share/arboretum/*.db
# expect: 700 …/arboretum and 600 …/arboretum.db
```
Keep `$HOME` private (standard `0o700`). If you relocate data with `--db` or `XDG_DATA_HOME`, make sure
the target directory is not world-readable.
## 4. Audit logging
All sensitive mutations are recorded in an append-only `audit_logs` table: token create/revoke, login
success/failure, settings changes, secret generation, push subscribe/unsubscribe, group CRUD, and data
erasure. Query it via the API (paginated):
```bash
curl -s -H "Authorization: Bearer $TOKEN" \
'http://127.0.0.1:7317/api/v1/audit-logs?limit=100'
```
The audit log never contains secret values — only non-sensitive metadata (ids, labels, counters). It is
also visible in the dashboard under **Settings → Security & compliance**.
## 5. GDPR (data subject requests)
- **Export**: `GET /api/v1/data/export` returns every record tied to the authenticated token (token
metadata, push subscriptions, session history, settings) as JSON. Also available as a one-click
download in **Settings → Security & compliance**.
- **Erasure**: `POST /api/v1/data/delete-my-data` is a two-step call — the first response returns a
`confirm` code that must be POSTed back to execute. It purges the token's push subscriptions and
revokes the token (unless it is the last active one).
## 6. Backups & retention
- Back up the SQLite database (`arboretum.db`) with the WAL checkpointed. Treat backups as sensitive.
- If you use `ARBORETUM_SECRET_KEY`, back the key up **separately** — a database backup is useless (and
safe) without it, which is the point.
- Session history is retained until the database is reset. To start clean, stop the service and remove
the database file.
## 7. Logging hygiene
The log level is controlled by `ARBORETUM_LOG` (default `info`). Do **not** run `debug`/`trace` in
production: verbose levels may log request metadata. Keep `info` or higher.
## 8. Supply chain
Each published release ships with a CycloneDX SBOM (`sbom.json`) generated in CI, so you can scan the
dependency tree for known vulnerabilities before deploying.
+123 -3803
View File
File diff suppressed because it is too large Load Diff
+4 -9
View File
@@ -10,17 +10,12 @@
"node": ">=22.16"
},
"scripts": {
"build": "npm run build -w @arboretum/shared -w @johanleroy/git-arboretum -w @arboretum/web",
"build": "npm run build -w @arboretum/shared -w git-arboretum -w @arboretum/web",
"typecheck": "tsc -b packages/shared packages/server",
"pack": "npm run build && npm pack -w @johanleroy/git-arboretum",
"pack": "npm run build && npm pack -w git-arboretum",
"test": "vitest run",
"dev:server": "npm run dev -w @johanleroy/git-arboretum",
"dev:web": "npm run dev -w @arboretum/web",
"build:site": "npm run build -w @arboretum/site",
"dev:site": "npm run dev -w @arboretum/site",
"preview:site": "npm run preview -w @arboretum/site",
"build:vscode": "npm run build -w @arboretum/shared -w git-arboretum",
"dev:vscode": "npm run dev -w git-arboretum"
"dev:server": "npm run dev -w git-arboretum",
"dev:web": "npm run dev -w @arboretum/web"
},
"devDependencies": {
"@types/node": "^22.10.0",
+7 -40
View File
@@ -1,68 +1,35 @@
{
"name": "@johanleroy/git-arboretum",
"version": "1.9.0",
"name": "git-arboretum",
"version": "0.1.0",
"description": "Self-hosted web dashboard for git worktrees and the Claude Code sessions running on them",
"license": "MIT",
"type": "module",
"author": "Johan LEROY <contact@johanleroy.fr>",
"homepage": "https://git.lidge.fr/johanleroy/arboretum#readme",
"repository": {
"type": "git",
"url": "git+https://git.lidge.fr/johanleroy/arboretum.git",
"directory": "packages/server"
},
"bugs": {
"url": "https://git.lidge.fr/johanleroy/arboretum/issues"
},
"funding": {
"type": "buymeacoffee",
"url": "https://buymeacoffee.com/johanleroy"
},
"keywords": [
"git",
"worktree",
"claude",
"claude-code",
"dashboard",
"self-hosted",
"pty",
"terminal",
"cli",
"daemon",
"pwa"
],
"bin": {
"arboretum": "./dist/index.js"
},
"main": "./dist/app.js",
"files": [
"dist/**/*.js",
"dist",
"public"
],
"engines": {
"node": ">=22.16"
},
"publishConfig": {
"registry": "https://git.lidge.fr/api/packages/johanleroy/npm/"
},
"scripts": {
"build": "tsc -b",
"dev": "tsc -b --watch & node --watch dist/index.js",
"prepack": "node scripts/copy-web.mjs && node scripts/inline-shared.mjs && node scripts/copy-meta.mjs",
"prepack": "node scripts/copy-web.mjs",
"test": "vitest run"
},
"dependencies": {
"@arboretum/shared": "0.1.0",
"@fastify/cookie": "^11.0.0",
"@fastify/static": "^9.0.0",
"@fastify/static": "^8.0.0",
"@fastify/websocket": "^11.0.0",
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
"@xterm/headless": "^6.0.0",
"fastify": "^5.0.0",
"web-push": "^3.6.7"
"fastify": "^5.0.0"
},
"devDependencies": {
"@arboretum/shared": "0.1.0",
"@types/web-push": "^3.6.4",
"@types/ws": "^8.5.0"
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ const check = (name, ok, detail = '') => {
};
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-'));
const srv = spawn('node', [join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--no-discover'], {
const srv = spawn('node', [join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db')], {
env: { ...process.env, ARBORETUM_LOG: 'warn' },
stdio: ['ignore', 'pipe', 'pipe'],
});
+1 -32
View File
@@ -62,7 +62,7 @@ writeFileSync(
const srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', claudeHome, '--no-discover'],
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', claudeHome],
{ env: { ...process.env, ARBORETUM_LOG: 'warn', PATH: `${fakeBin}:${process.env.PATH}` }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let srvOut = '';
@@ -144,37 +144,6 @@ try {
const out = c.state.outputs.get(att?.channel) ?? '';
check('resume lance `--resume sid-dead` dans le bon cwd', out.includes('args=[--resume sid-dead]') && out.includes(`cwd=${workDir}`), out.replace(/\s+/g, ' ').slice(0, 120));
// --- Régression « Reprendre » : reprise d'une session MANAGÉE morte par son UUID Arboretum ---
// (le bouton web envoie l'UUID managé, pas le claudeSessionId ; le serveur doit le résoudre en DB).
const createManaged = await fetch(`${ORIGIN}/api/v1/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: ORIGIN, Cookie: cookie },
body: JSON.stringify({ cwd: workDir, command: 'claude' }),
});
const managed = (await createManaged.json()).session;
check('création session managée claude → 201 (pid)', createManaged.status === 201 && managed?.pid > 0);
// Simule la capture du claudeSessionId : entrée registre pour le pid du PTY managé (pollée toutes les 400ms).
writeFileSync(
join(sessions, `${managed.pid}.json`),
JSON.stringify({ pid: managed.pid, sessionId: 'sid-managed', cwd: workDir, status: 'idle' }),
);
const captured = await c.waitMsg(
(m) => m.type === 'session_update' && m.session?.id === managed.id && m.session?.claudeSessionId === 'sid-managed',
);
check('claudeSessionId capturé depuis le registre (session managée)', !!captured);
// Fermeture (kill) puis reprise par UUID managé → 201 dans le cwd d'origine (avant le fix : 404).
const killManaged = await fetch(`${ORIGIN}/api/v1/sessions/${managed.id}`, { method: 'DELETE', headers: { Origin: ORIGIN, Cookie: cookie } });
check('kill session managée → 200', killManaged.status === 200);
await sleep(400); // laisse handleExit persister ended_at
const resumeManaged = await postJson(`/api/v1/sessions/${managed.id}/resume`, cookie);
const resumedManaged = (await resumeManaged.json()).session;
check(
'resume d’une session MANAGÉE morte par UUID → 201',
resumeManaged.status === 201 && resumedManaged?.command === 'claude' && resumedManaged?.source === 'managed' && resumedManaged?.cwd === workDir,
);
// Broadcast : une nouvelle session découverte est poussée via session_update au rafraîchissement périodique.
writeJsonl(workDir, 'sid-new');
const pushed = await c.waitMsg((m) => m.type === 'session_update' && m.session?.id === 'sid-new', 13000);
-159
View File
@@ -1,159 +0,0 @@
#!/usr/bin/env node
// Acceptation P3 (sans navigateur, sans quota Claude) : worktrees multi-repo + dashboard.
// Vrai daemon + vrai repo git tmp. Couvre : enregistrement repo, création worktree avec hook
// post-create, broadcast WS worktree_update, corrélation worktree↔session (bash), suppression.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, existsSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname, basename } 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 = 7543;
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-p3-'));
const repo = join(tmp, 'demo-repo');
const wtPath = join(tmp, 'demo-repo-wt-feat');
execFileSync('mkdir', ['-p', repo]);
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');
execFileSync('bash', ['-lc', 'echo "# demo" > README.md'], { cwd: repo });
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: ['sessions', 'worktrees'] });
// Enregistrement du repo (avec un hook post-create).
const addRepo = await j('/api/v1/repos', 'POST', cookie, {
path: repo,
postCreateHooks: [{ id: 'h1', label: 'touch', run: 'touch hook-ok.txt', enabled: true }],
});
const repoSummary = (await addRepo.json()).repo;
check('POST /repos → 201 (repo valide)', addRepo.status === 201 && repoSummary?.valid === true);
const wlist0 = await (await j('/api/v1/worktrees', 'GET', cookie)).json();
check('GET /worktrees → main worktree présent', wlist0.worktrees.some((w) => w.isMain && w.branch === 'main'));
// Création d'un worktree + hook + session bash.
const created = await j(`/api/v1/repos/${repoSummary.id}/worktrees`, 'POST', cookie, {
branch: 'feat',
newBranch: true,
runHooks: true,
startSession: 'bash',
});
const createdBody = await created.json();
check('POST worktree → 201', created.status === 201 && createdBody.worktree?.branch === 'feat');
check('hook post-create exécuté', createdBody.hookResults?.[0]?.exitCode === 0 && existsSync(join(wtPath, 'hook-ok.txt')));
check('startSession bash → session managée', createdBody.session?.command === 'bash');
const pushed = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.branch === 'feat');
check('broadcast WS worktree_update', !!pushed);
// Corrélation worktree ↔ session par cwd.
await sleep(300);
const wlist1 = await (await j('/api/v1/worktrees', 'GET', cookie)).json();
const feat = wlist1.worktrees.find((w) => w.branch === 'feat');
check('corrélation worktree ↔ session (cwd)', feat?.sessions?.some((s) => s.command === 'bash' && s.live));
// Session sur le checkout principal (« bosser sur la branche principale ») avec création de branche.
const mainSess = await j(`/api/v1/repos/${repoSummary.id}/session`, 'POST', cookie, { command: 'bash', branch: 'mainfeat', newBranch: true });
const mainBody = await mainSess.json();
check('POST repo session → 201 (bash)', mainSess.status === 201 && mainBody.session?.command === 'bash');
check('session de branche principale : cwd = checkout principal', mainBody.session?.cwd === repoSummary.path);
const mainPush = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.isMain && m.worktree?.branch === 'mainfeat');
check('broadcast worktree_update (branche principale basculée)', !!mainPush);
await sleep(300);
const wlistM = await (await j('/api/v1/worktrees', 'GET', cookie)).json();
const mainWt = wlistM.worktrees.find((w) => w.isMain);
check('session corrélée au checkout principal', mainWt?.branch === 'mainfeat' && mainWt.sessions.some((s) => s.id === mainBody.session.id));
// Refus 409 quand le checkout principal est sale.
writeFileSync(join(repo, 'scratch.txt'), 'wip\n');
const dirtyRefused = await j(`/api/v1/repos/${repoSummary.id}/session`, 'POST', cookie, { command: 'bash', branch: 'other', newBranch: true });
check('repo session sur checkout sale → 409', dirtyRefused.status === 409);
rmSync(join(repo, 'scratch.txt'), { force: true });
// Suppression forcée (une session vit dans le worktree).
const refused = await j(`/api/v1/repos/${repoSummary.id}/worktrees?path=${encodeURIComponent(wtPath)}&force=false`, 'DELETE', cookie);
check('delete sans force (session live) → 409', refused.status === 409);
const del = await j(`/api/v1/repos/${repoSummary.id}/worktrees?path=${encodeURIComponent(wtPath)}&force=true`, 'DELETE', cookie);
check('delete force → 200', del.status === 200);
const removed = await c.waitMsg((m) => m.type === 'worktree_removed', 8000);
check('broadcast WS worktree_removed', !!removed);
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 P3: ALL GREEN' : `\nACCEPTANCE P3: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
-135
View File
@@ -1,135 +0,0 @@
#!/usr/bin/env node
// Acceptation P4 (sans navigateur, sans quota Claude) : Web Push + commande WS `answer`.
// Vrai daemon. Couvre : garde auth + Origin sur les routes push, clé VAPID exposée, subscribe
// idempotent / malformé / unsubscribe, et la commande `answer` (rejets INVALID_ANSWER /
// NOT_CONTROLLING — la validation fine `select` vit dans les tests vitest sur fixtures).
import { spawn } from 'node:child_process';
import { mkdtempSync, rmSync } 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 = 7544;
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-p4-'));
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));
const j = (path, method, cookie, body) =>
fetch(`${ORIGIN}${path}`, {
method,
headers: { Origin: ORIGIN, ...(cookie ? { Cookie: cookie } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
});
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)) };
}
try {
await sleep(1500);
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
check('boot + token bootstrap', !!token);
// Garde d'auth globale : route push sans cookie → 401.
const noAuth = await j('/api/v1/push/vapid-public-key', 'GET', '');
check('GET vapid-public-key sans cookie → 401', noAuth.status === 401);
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);
// Check Origin strict : origine non autorisée (même avec cookie) → 403.
const badOrigin = await fetch(`${ORIGIN}/api/v1/push/vapid-public-key`, { headers: { Origin: 'http://evil.example', Cookie: cookie } });
check('Origin invalide → 403', badOrigin.status === 403);
// Clé VAPID publique exposée (sûre).
const vapid = await j('/api/v1/push/vapid-public-key', 'GET', cookie);
const vapidBody = await vapid.json();
check('GET vapid-public-key → 200 + clé non triviale', vapid.status === 200 && typeof vapidBody.key === 'string' && vapidBody.key.length > 20);
// Abonnement : 201, UPSERT idempotent, rejet du malformé, désabonnement.
const sub = { endpoint: 'https://push.example/endpoint-1', keys: { p256dh: 'BPp256dhKeyDummy', auth: 'authDummy' } };
const s1 = await j('/api/v1/push/subscribe', 'POST', cookie, sub);
check('POST subscribe → 201', s1.status === 201);
const s2 = await j('/api/v1/push/subscribe', 'POST', cookie, sub);
check('subscribe idempotent (même endpoint) → 201', s2.status === 201);
const badSub = await j('/api/v1/push/subscribe', 'POST', cookie, { endpoint: 'x' });
check('subscribe sans keys → 400', badSub.status === 400);
const uns = await j('/api/v1/push/unsubscribe', 'POST', cookie, { endpoint: sub.endpoint });
check('POST unsubscribe → 200', uns.status === 200);
// Commande WS `answer` : rejets sur une session bash managée (pas d'état waiting) et en observer.
const created = await j('/api/v1/sessions', 'POST', cookie, { cwd: tmp, command: 'bash' });
const sess = (await created.json()).session;
check('POST /sessions bash → 201', created.status === 201 && sess?.command === 'bash');
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: 'attach', sessionId: sess.id, mode: 'interactive', cols: 80, rows: 24 });
const att = await c.waitMsg((m) => m.type === 'attached');
check('attach interactive (contrôleur)', !!att && att.controlling === true);
c.send({ type: 'answer', channel: att.channel, action: 'deny' });
const invalid = await c.waitMsg((m) => m.type === 'error' && m.code === 'INVALID_ANSWER');
check('answer sur session non-waiting → INVALID_ANSWER', !!invalid);
c.send({ type: 'attach', sessionId: sess.id, mode: 'observer', cols: 80, rows: 24 });
const obs = await c.waitMsg((m) => m.type === 'attached' && m.mode === 'observer');
check('attach observer (read-only)', !!obs && obs.controlling === false);
c.send({ type: 'answer', channel: obs.channel, action: 'deny' });
const notCtrl = await c.waitMsg((m) => m.type === 'error' && m.code === 'NOT_CONTROLLING' && m.channel === obs.channel);
check('answer en observer → NOT_CONTROLLING', !!notCtrl);
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 P4: ALL GREEN' : `\nACCEPTANCE P4: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
-216
View File
@@ -1,216 +0,0 @@
#!/usr/bin/env node
// Acceptation P5 (sans navigateur, sans quota Claude) : groupes de travail.
// Vrai daemon + vrai repo git tmp. Couvre : CRUD groupe via REST, broadcast WS group_update/
// group_removed sur le topic 'groups', ajout/retrait de repo, et purge CASCADE de la membership
// quand le repo est supprimé (PRAGMA foreign_keys = ON).
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } 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 = 7545;
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-p5-'));
function initRepo(path) {
execFileSync('mkdir', ['-p', path]);
const git = (...args) => execFileSync('git', args, { cwd: path, stdio: 'pipe' });
git('init', '-b', 'main');
git('config', 'user.email', 'test@arboretum.dev');
git('config', 'user.name', 'Test');
execFileSync('bash', ['-lc', 'echo "# demo" > README.md'], { cwd: path });
git('add', '-A');
git('commit', '-m', 'init');
}
const repo = join(tmp, 'demo-repo');
const repo2 = join(tmp, 'demo-repo-2');
initRepo(repo);
initRepo(repo2);
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: ['sessions', 'worktrees', 'groups'] });
// Enregistrement d'un repo (cible de la membership).
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
const repoSummary = (await addRepo.json()).repo;
check('POST /repos → 201', addRepo.status === 201 && repoSummary?.valid === true);
// Création d'un groupe vide via REST → broadcast WS group_update.
const created = await j('/api/v1/groups', 'POST', cookie, { label: 'Sprint 42', color: '#4f46e5' });
const group = (await created.json()).group;
check('POST /groups → 201', created.status === 201 && group?.label === 'Sprint 42' && group?.repoIds.length === 0);
const pushedCreate = await c.waitMsg((m) => m.type === 'group_update' && m.group?.id === group.id);
check('broadcast WS group_update (création)', !!pushedCreate);
const list = await (await j('/api/v1/groups', 'GET', cookie)).json();
check('GET /groups → groupe présent', list.groups?.some((g) => g.id === group.id));
// Ajout du repo au groupe → group_update avec repoIds peuplé.
const added = await j(`/api/v1/groups/${group.id}/repos`, 'POST', cookie, { repoId: repoSummary.id });
const addedBody = await added.json();
check('POST /groups/:id/repos → repoIds', added.status === 200 && addedBody.group?.repoIds.includes(repoSummary.id));
const pushedAdd = await c.waitMsg((m) => m.type === 'group_update' && m.group?.repoIds?.includes(repoSummary.id));
check('broadcast WS group_update (ajout repo)', !!pushedAdd);
// ---- P6 : session de groupe multi-repo (UNE session couvrant tous les repos via --add-dir) ----
// Enregistre un 2e repo, l'ajoute au groupe, puis lance UNE session de groupe (bash, sans quota).
const addRepo2 = await j('/api/v1/repos', 'POST', cookie, { path: repo2 });
const repo2Summary = (await addRepo2.json()).repo;
check('POST /repos (2e repo) → 201', addRepo2.status === 201 && repo2Summary?.valid === true);
await j(`/api/v1/groups/${group.id}/repos`, 'POST', cookie, { repoId: repo2Summary.id });
// Mode « checkouts principaux » (pas de branch) : couvre le worktree principal de chaque repo.
const gsRes = await j(`/api/v1/groups/${group.id}/session`, 'POST', cookie, { command: 'bash' });
const gsBody = await gsRes.json();
const gsession = gsBody.session;
check('POST /groups/:id/session → 201', gsRes.status === 201 && !!gsession);
check('session de groupe : 2 répertoires couverts', Array.isArray(gsBody.dirs) && gsBody.dirs.length === 2);
// cwd = parent commun des repos (P6), chaque repo relié en --add-dir → 2 addedDirs.
check('session de groupe : cwd = parent commun des repos', gsession?.cwd === tmp);
check('session de groupe : addedDirs = les 2 repos', (gsession?.addedDirs?.length ?? 0) === 2);
check('session de groupe : groupId posé', gsession?.groupId === group.id);
check('session de groupe : cwd parent + 2 repos addedDirs = 3 chemins distincts', new Set([gsession?.cwd, ...(gsession?.addedDirs ?? [])]).size === 3);
// La session apparaît dans la liste globale avec son groupId.
const sessList = await (await j('/api/v1/sessions', 'GET', cookie)).json();
const listed = sessList.sessions?.find((s) => s.id === gsession.id);
check('GET /sessions : session de groupe présente avec groupId', listed?.groupId === group.id);
// broadcast WS session_update reçu pour la session de groupe.
const pushedSession = await c.waitMsg((m) => m.type === 'session_update' && m.session?.id === gsession.id);
check('broadcast WS session_update (session de groupe)', !!pushedSession);
// ---- Worktree de groupe sur une NOUVELLE branche (scénario corrigé : mode auto, plus de -b raté) ----
const wtA = await j(`/api/v1/repos/${repoSummary.id}/worktrees`, 'POST', cookie, { branch: 'feature/cross', mode: 'auto', startSession: null });
const wtABody = await wtA.json();
check('POST /repos/:id/worktrees (branche neuve) → 201 + action=created', wtA.status === 201 && wtABody.action === 'created');
const wtB = await j(`/api/v1/repos/${repo2Summary.id}/worktrees`, 'POST', cookie, { branch: 'feature/cross', mode: 'auto', startSession: null });
check('POST /repos (2e repo) worktree branche neuve → 201', wtB.status === 201);
// GET /branches : la nouvelle branche apparaît (alimente le sélecteur de base côté UI).
const branchesA = await (await j(`/api/v1/repos/${repoSummary.id}/branches`, 'GET', cookie)).json();
check('GET /repos/:id/branches : feature/cross présente', Array.isArray(branchesA.local) && branchesA.local.includes('feature/cross'));
// session de groupe SUR cette branche → résout les worktrees créés (le cas qui échouait avant).
const gsBranch = await j(`/api/v1/groups/${group.id}/session`, 'POST', cookie, { command: 'bash', branch: 'feature/cross' });
const gsBranchBody = await gsBranch.json();
check('POST /groups/:id/session (branche) → 201 + 2 dirs', gsBranch.status === 201 && gsBranchBody.dirs?.length === 2);
await j(`/api/v1/sessions/${gsBranchBody.session.id}`, 'DELETE', cookie);
// commit : fichier neuf dans le worktree de repo1 puis commit via l'endpoint.
writeFileSync(join(wtABody.worktree.path, 'cross.txt'), 'wip\n');
const commitRes = await j(`/api/v1/repos/${repoSummary.id}/worktrees/commit`, 'POST', cookie, { path: wtABody.worktree.path, message: 'wip cross' });
check('POST /worktrees/commit → 200 + dirty=0', commitRes.status === 200 && (await commitRes.json()).worktree?.git?.dirtyCount === 0);
// promotion « en principal » : feature/cross devient le checkout principal de repo1, worktree supprimé.
const promRes = await j(`/api/v1/repos/${repoSummary.id}/worktrees/promote`, 'POST', cookie, { path: wtABody.worktree.path });
check('POST /worktrees/promote → 200', promRes.status === 200);
const wtsAfter = await (await j(`/api/v1/repos/${repoSummary.id}/worktrees`, 'GET', cookie)).json();
check('promotion : checkout principal désormais sur feature/cross', wtsAfter.worktrees?.find((w) => w.isMain)?.branch === 'feature/cross');
// groupe sans worktree résolu (branche inexistante) → 400.
const gsBad = await j(`/api/v1/groups/${group.id}/session`, 'POST', cookie, { command: 'bash', branch: 'no/such/branch' });
check('POST /groups/:id/session branche absente → 400', gsBad.status === 400);
// Arrêt de la session de groupe + nettoyage du 2e repo (CASCADE retire repo2 de la membership).
const killSession = await j(`/api/v1/sessions/${gsession.id}`, 'DELETE', cookie);
check('DELETE session de groupe → 200', killSession.status === 200);
await j(`/api/v1/repos/${repo2Summary.id}`, 'DELETE', cookie);
// Renommage via PATCH.
const patched = await j(`/api/v1/groups/${group.id}`, 'PATCH', cookie, { label: 'Renamed' });
check('PATCH /groups/:id → 200 (renommé)', patched.status === 200 && (await patched.json()).group?.label === 'Renamed');
// repoId inexistant → 404.
const bad = await j(`/api/v1/groups/${group.id}/repos`, 'POST', cookie, { repoId: 'does-not-exist' });
check('POST repo inexistant → 404', bad.status === 404);
// Suppression du repo → CASCADE purge la membership.
const delRepo = await j(`/api/v1/repos/${repoSummary.id}`, 'DELETE', cookie);
check('DELETE /repos/:id → 200', delRepo.status === 200);
await sleep(200);
const afterCascade = await (await j(`/api/v1/groups/${group.id}`, 'GET', cookie)).json();
check('CASCADE : membership purgée à la suppression du repo', afterCascade.group?.repoIds.length === 0);
// Suppression du groupe → broadcast WS group_removed.
const delGroup = await j(`/api/v1/groups/${group.id}`, 'DELETE', cookie);
check('DELETE /groups/:id → 200', delGroup.status === 200);
const removed = await c.waitMsg((m) => m.type === 'group_removed' && m.groupId === group.id);
check('broadcast WS group_removed', !!removed);
const delAgain = await j(`/api/v1/groups/${group.id}`, 'DELETE', cookie);
check('DELETE groupe inconnu → 404', delAgain.status === 404);
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 P5: ALL GREEN' : `\nACCEPTANCE P5: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
-36
View File
@@ -1,36 +0,0 @@
#!/usr/bin/env node
// Copie le README et la LICENSE racine dans packages/server/ avant le pack, pour que
// la page du paquet (registre Gitea) ne soit pas nue et que la licence soit jointe.
// npm inclut automatiquement README* et LICENSE* dans le tarball s'ils sont présents.
// Branché sur le hook "prepack". Ces copies sont gitignorées (générées, non versionnées).
import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
const rootDir = join(serverDir, '..', '..');
// README : réécrit les chemins d'images relatifs (brand/…) en URL absolue Gitea raw,
// sinon le logo est cassé hors du repo (sur la page du paquet).
const readmeSrc = join(rootDir, 'README.md');
if (existsSync(readmeSrc)) {
const rawBase = 'https://git.lidge.fr/johanleroy/arboretum/raw/branch/main/';
const srcBase = 'https://git.lidge.fr/johanleroy/arboretum/src/branch/main/';
const readme = readFileSync(readmeSrc, 'utf8')
.replaceAll('src="brand/', `src="${rawBase}brand/`)
.replaceAll('href="README.fr.md"', `href="${srcBase}README.fr.md"`);
writeFileSync(join(serverDir, 'README.md'), readme);
console.log('copy-meta: README.md copié (chemins images + lien FR réécrits en absolu)');
} else {
console.error(`copy-meta: ${readmeSrc} introuvable`);
process.exit(1);
}
const licenseSrc = join(rootDir, 'LICENSE');
if (existsSync(licenseSrc)) {
copyFileSync(licenseSrc, join(serverDir, 'LICENSE'));
console.log('copy-meta: LICENSE copié');
} else {
console.error(`copy-meta: ${licenseSrc} introuvable`);
process.exit(1);
}
-71
View File
@@ -1,71 +0,0 @@
#!/usr/bin/env node
// Inline @arboretum/shared (paquet workspace NON publié) directement dans le dist du serveur,
// pour que le tarball npm soit 100 % autonome. Branché sur le hook "prepack".
//
// Pourquoi PAS bundleDependencies : embarquer une dépendance qui est aussi un *workspace* via
// bundleDependencies est instable selon l'environnement npm (mode -w, exécution en root sur un
// runner CI, version d'arborist) — npm voit le nœud comme un lien workspace et n'embarque parfois
// AUCUN fichier ("bundled files: 0"), produisant un paquet cassé chez le consommateur. On élimine
// donc toute magie de bundling : on copie le JS compilé de shared dans dist/_shared et on réécrit
// l'import bare '@arboretum/shared' du serveur vers ce chemin relatif. Zéro node_modules embarqué,
// zéro symlink, résultat identique partout.
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join, dirname, relative, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
const serverDist = join(serverDir, 'dist');
const sharedDist = join(serverDir, '..', 'shared', 'dist');
const inlineDir = join(serverDist, '_shared');
for (const [label, p] of [['dist serveur', serverDist], ['dist shared', sharedDist]]) {
if (!existsSync(p)) {
console.error(`inline-shared: ${label} introuvable (${p}) — lance "npm run build" avant le pack.`);
process.exit(1);
}
}
// 1) Copier le JS compilé de shared dans dist/_shared (uniquement *.js : seul le runtime compte ;
// les .d.ts/.map ne sont de toute façon pas publiés via le glob `files`). index.js réexporte
// ./protocol.js et ./api.js en relatif → la copie complète préserve la résolution interne.
rmSync(inlineDir, { recursive: true, force: true });
mkdirSync(inlineDir, { recursive: true });
let copied = 0;
for (const name of readdirSync(sharedDist)) {
if (name.endsWith('.js')) {
cpSync(join(sharedDist, name), join(inlineDir, name));
copied++;
}
}
if (copied === 0) {
console.error(`inline-shared: aucun .js dans ${sharedDist} — shared n'est pas compilé.`);
process.exit(1);
}
// 2) Réécrire l'import bare '@arboretum/shared' de chaque .js du serveur vers le chemin relatif
// (POSIX) pointant sur dist/_shared/index.js, calculé par fichier (profondeur variable).
const walk = (dir) =>
readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
const p = join(dir, e.name);
if (e.isDirectory()) return p === inlineDir ? [] : walk(p); // ne pas se réécrire soi-même
return e.name.endsWith('.js') ? [p] : [];
});
let rewritten = 0;
for (const file of walk(serverDist)) {
const src = readFileSync(file, 'utf8');
if (!src.includes('@arboretum/shared')) continue;
let rel = relative(dirname(file), join(inlineDir, 'index.js')).split(sep).join('/');
if (!rel.startsWith('.')) rel = `./${rel}`;
const out = src.replaceAll(`'@arboretum/shared'`, `'${rel}'`).replaceAll(`"@arboretum/shared"`, `"${rel}"`);
if (out !== src) {
writeFileSync(file, out);
rewritten++;
}
}
if (rewritten === 0) {
console.error(`inline-shared: aucun import '@arboretum/shared' réécrit dans ${serverDist} — build manquant ?`);
process.exit(1);
}
console.log(`inline-shared: ${copied} fichier(s) shared -> dist/_shared, import réécrit dans ${rewritten} fichier(s) serveur`);
+7 -105
View File
@@ -1,4 +1,4 @@
import Fastify, { type FastifyError, type FastifyInstance, type FastifyRequest } from 'fastify';
import Fastify, { type FastifyInstance, type FastifyRequest } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import fastifyWebsocket from '@fastify/websocket';
import fastifyStatic from '@fastify/static';
@@ -10,50 +10,9 @@ import type { Db } from './db/index.js';
import { AuthService, LoginRateLimiter, type AuthContext } from './auth/service.js';
import { PtyManager } from './core/pty-manager.js';
import { DiscoveryService } from './core/discovery-service.js';
import { WorktreeManager } from './core/worktree-manager.js';
import { RepoDiscoveryService } from './core/repo-discovery.js';
import { GroupManager } from './core/group-manager.js';
import { PushService } from './core/push-service.js';
import { loadSecretBox } from './core/secret-box.js';
import { registerAuthRoutes } from './routes/auth.js';
import { registerSessionRoutes } from './routes/sessions.js';
import { registerRepoRoutes } from './routes/repos.js';
import { registerGroupRoutes } from './routes/groups.js';
import { registerWorktreeRoutes } from './routes/worktrees.js';
import { registerPushRoutes } from './routes/push.js';
import { registerSettingsRoutes } from './routes/settings.js';
import { registerFsRoutes } from './routes/fs.js';
import { registerAuditRoutes } from './routes/audit.js';
import { registerDataRoutes } from './routes/data.js';
import { registerWsGateway } from './ws/gateway.js';
import { isHttpsRequest } from './routes/auth.js';
// En-têtes de sécurité posés sur TOUTES les réponses (defense-in-depth + conformité scanners
// entreprise). Le terminal web reste du RCE par conception : ces en-têtes durcissent la SPA et
// le transport, ils ne remplacent pas le modèle loopback + auth + Origin.
const SECURITY_HEADERS: Record<string, string> = {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'no-referrer',
'Cross-Origin-Opener-Policy': 'same-origin',
'Permissions-Policy': 'geolocation=(), microphone=(), camera=(), payment=()',
// CSP calibrée pour la SPA : Tailwind/xterm injectent du style inline ; le WebSocket impose
// ws:/wss: en connect-src ; le service worker push impose worker-src 'self'.
'Content-Security-Policy': [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data:",
"font-src 'self' data:",
"connect-src 'self' ws: wss:",
"worker-src 'self'",
"manifest-src 'self'",
"frame-ancestors 'none'",
"base-uri 'self'",
"object-src 'none'",
"form-action 'self'",
].join('; '),
};
declare module 'fastify' {
interface FastifyRequest {
@@ -69,67 +28,18 @@ export interface AppBundle {
auth: AuthService;
manager: PtyManager;
discovery: DiscoveryService;
repoDiscovery: RepoDiscoveryService;
worktrees: WorktreeManager;
groups: GroupManager;
push: PushService;
}
export function buildApp(config: Config, db: Db, serverVersion: string): AppBundle {
const app = Fastify({ logger: { level: process.env.ARBORETUM_LOG ?? 'info' } });
// Chiffrement au repos des secrets (server_secret, clé privée VAPID) dans la base.
const box = loadSecretBox(config.dataDir);
const auth = new AuthService(db, box);
const auth = new AuthService(db);
const limiter = new LoginRateLimiter();
const push = new PushService(db, config.vapidContact, undefined, box);
const manager = new PtyManager(db, config.claudeSessionsDir, push);
const manager = new PtyManager(db, config.claudeSessionsDir);
const discovery = new DiscoveryService({
db,
ptyManager: manager,
projectsDir: config.claudeProjectsDir,
sessionsDir: config.claudeSessionsDir,
});
const worktrees = new WorktreeManager(db, manager, discovery);
// Démarré dans runDaemon() (jamais ici) → le scan ne tourne pas pendant les tests qui appellent buildApp.
const repoDiscovery = new RepoDiscoveryService(db, worktrees);
const groups = new GroupManager(db);
// En-têtes de sécurité sur toute réponse + no-store sur les réponses sensibles (API/WS).
// onSend DOIT retourner le payload (sinon Fastify vide la réponse).
app.addHook('onSend', async (req, reply, payload) => {
reply.removeHeader('Server'); // anti-fingerprinting (no-op si absent)
for (const [k, v] of Object.entries(SECURITY_HEADERS)) reply.header(k, v);
if (isHttpsRequest(req)) {
reply.header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
if (req.url.startsWith('/api/') || req.url.startsWith('/ws')) {
reply.header('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0');
}
return payload;
});
// Garde CSRF defense-in-depth : une mutation porteuse d'un corps DOIT être en application/json
// (bloque les soumissions de formulaire cross-site en text/plain, que Fastify parserait sinon).
app.addHook('preHandler', async (req, reply) => {
if (!['POST', 'PATCH', 'PUT', 'DELETE'].includes(req.method)) return;
const len = req.headers['content-length'];
if (!len || len === '0') return; // pas de corps : rien à valider
const ct = (req.headers['content-type'] ?? '').toLowerCase();
if (!ct.startsWith('application/json')) {
return reply.status(415).send({ error: { code: 'UNSUPPORTED_MEDIA_TYPE', message: 'Content-Type must be application/json' } });
}
});
// Handler d'erreur : ne jamais fuiter de stack/chemin au client ; détail complet côté logs.
app.setErrorHandler((err: FastifyError, req, reply) => {
const status = err.statusCode && err.statusCode >= 400 && err.statusCode < 600 ? err.statusCode : 500;
if (status >= 500) {
req.log.error({ err }, 'unhandled error');
return reply.status(status).send({ error: { code: 'INTERNAL', message: 'Internal Server Error' } });
}
// erreurs client (4xx) : code générique, message court non sensible.
return reply.status(status).send({ error: { code: err.code ?? 'BAD_REQUEST', message: err.message } });
});
void app.register(fastifyCookie);
void app.register(fastifyWebsocket, {
@@ -168,20 +78,12 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
}
});
registerAuthRoutes(app, auth, limiter, serverVersion, db);
registerSessionRoutes(app, manager, discovery, db);
registerRepoRoutes(app, worktrees, db);
registerGroupRoutes(app, groups, db, worktrees, manager);
registerWorktreeRoutes(app, worktrees, db);
registerPushRoutes(app, push, db);
registerSettingsRoutes(app, db, config, serverVersion, push);
registerFsRoutes(app);
registerAuditRoutes(app, db);
registerDataRoutes(app, db, auth);
registerAuthRoutes(app, auth, limiter, serverVersion);
registerSessionRoutes(app, manager, discovery);
// La route websocket doit être déclarée APRÈS le chargement du plugin (contexte
// encapsulé) — sinon le handler reçoit la signature REST (request, reply).
void app.register(async (scoped) => {
registerWsGateway(scoped, manager, discovery, worktrees, groups, serverVersion);
registerWsGateway(scoped, manager, discovery, serverVersion);
});
// SPA buildée embarquée dans le paquet npm (public/) — absente en dev (vite dev sert le front)
@@ -196,5 +98,5 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
});
}
return { app, auth, manager, discovery, repoDiscovery, worktrees, groups, push };
return { app, auth, manager, discovery };
}
+6 -67
View File
@@ -1,7 +1,5 @@
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
import { type Db, getSetting, setSetting } from '../db/index.js';
import type { SecretBox } from '../core/secret-box.js';
import { recordAudit } from '../core/audit-log.js';
const COOKIE_NAME = 'arb_session';
const COOKIE_TTL_MS = 30 * 24 * 3600 * 1000;
@@ -14,21 +12,11 @@ export interface AuthContext {
export class AuthService {
private readonly secret: Buffer;
constructor(
private readonly db: Db,
box?: SecretBox,
) {
// server_secret chiffré au repos quand un SecretBox est fourni (prod). Migration douce :
// une valeur en clair pré-existante est re-chiffrée à la lecture.
const stored = getSetting(db, 'server_secret');
let secretHex: string;
if (!stored) {
constructor(private readonly db: Db) {
let secretHex = getSetting(db, 'server_secret');
if (!secretHex) {
secretHex = randomBytes(32).toString('hex');
setSetting(db, 'server_secret', box ? box.encrypt(secretHex) : secretHex);
recordAudit(db, { actor: 'system', action: 'secret.generate', resourceId: 'server_secret' });
} else {
secretHex = box ? box.decrypt(stored) : stored;
if (box && !box.isEncrypted(stored)) setSetting(db, 'server_secret', box.encrypt(secretHex));
setSetting(db, 'server_secret', secretHex);
}
this.secret = Buffer.from(secretHex, 'hex');
}
@@ -47,60 +35,11 @@ export class AuthService {
}
createToken(label: string): string {
return this.createTokenRecord(label).token;
}
/** Comme createToken mais renvoie aussi l'id (pour l'API de gestion des tokens). */
createTokenRecord(label: string): { id: string; token: string } {
const id = randomUUID();
const raw = `arb_${randomBytes(24).toString('hex')}`;
this.db
.prepare('INSERT INTO auth_tokens (id, label, token_hash, created_at) VALUES (?, ?, ?, ?)')
.run(id, label, sha256(raw), new Date().toISOString());
return { id, token: raw };
}
/** Tokens actifs (non révoqués), du plus ancien au plus récent. Ne renvoie JAMAIS le hash. */
listTokens(): Array<{ id: string; label: string; createdAt: string; lastUsedAt: string | null }> {
return this.db
.prepare(
'SELECT id, label, created_at AS createdAt, last_used_at AS lastUsedAt FROM auth_tokens WHERE revoked_at IS NULL ORDER BY created_at',
)
.all() as Array<{ id: string; label: string; createdAt: string; lastUsedAt: string | null }>;
}
/** Nombre de tokens actifs (non révoqués). */
countActiveTokens(): number {
return (this.db.prepare('SELECT COUNT(*) AS n FROM auth_tokens WHERE revoked_at IS NULL').get() as { n: number }).n;
}
/**
* Révoque un token. Refuse de révoquer le DERNIER token actif (sinon lock-out total) → 'last'.
* 'ok' = révoqué ; 'not_found' = id inconnu ou déjà révoqué.
*/
revokeToken(id: string): 'ok' | 'last' | 'not_found' {
// Transaction : le check « dernier token » et l'UPDATE doivent être atomiques (garde
// anti lock-out robuste, même si un refactor futur introduisait de la concurrence).
this.db.exec('BEGIN IMMEDIATE');
try {
const row = this.db.prepare('SELECT id FROM auth_tokens WHERE id = ? AND revoked_at IS NULL').get(id) as
| { id: string }
| undefined;
let result: 'ok' | 'last' | 'not_found';
if (!row) {
result = 'not_found';
} else if (this.countActiveTokens() <= 1) {
result = 'last';
} else {
this.db.prepare('UPDATE auth_tokens SET revoked_at = ? WHERE id = ?').run(new Date().toISOString(), id);
result = 'ok';
}
this.db.exec('COMMIT');
return result;
} catch (err) {
this.db.exec('ROLLBACK');
throw err;
}
.run(randomUUID(), label, sha256(raw), new Date().toISOString());
return raw;
}
verifyRawToken(raw: string): AuthContext | null {
-363
View File
@@ -1,363 +0,0 @@
import { parseArgs } from 'node:util';
import { spawnSync } from 'node:child_process';
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadConfig } from '../config.js';
import { openDb } from '../db/index.js';
import { AuthService } from '../auth/service.js';
// Nom de l'unit systemd (Linux) et label launchd par défaut (macOS, surchargeable via --label).
const SERVICE_NAME = 'arboretum';
const LAUNCHD_LABEL = 'fr.lidge.arboretum';
export type SupportedPlatform = 'linux' | 'darwin';
export interface InstallFlags {
port?: string | undefined;
bind?: string | undefined;
allowOrigin: string[];
db?: string | undefined;
vapidContact?: string | undefined;
claudeHome?: string | undefined;
binPath?: string | undefined;
label: string;
dryRun: boolean;
noEnable: boolean;
}
// ─── Fonctions pures (génération de contenu / chemins) ────────────────────────────────
/** macOS (launchd) et Linux (systemd) uniquement ; sinon throw avec un message pédagogique. */
export function detectPlatform(platform: NodeJS.Platform = process.platform): SupportedPlatform {
if (platform === 'linux' || platform === 'darwin') return platform;
throw new Error(
`Automatic service installation is supported on Linux (systemd) and macOS (launchd) only.\n` +
`On ${platform}, run \`arboretum\` manually or set up your own supervisor.`,
);
}
export function parseInstallArgs(argv: string[]): InstallFlags {
const { values } = parseArgs({
args: argv,
options: {
port: { type: 'string' },
bind: { type: 'string' },
'allow-origin': { type: 'string', multiple: true },
db: { type: 'string' },
'vapid-contact': { type: 'string' },
'claude-home': { type: 'string' },
'bin-path': { type: 'string' },
label: { type: 'string' },
'dry-run': { type: 'boolean', default: false },
'no-enable': { type: 'boolean', default: false },
},
strict: true,
});
return {
port: values.port,
bind: values.bind,
allowOrigin: values['allow-origin'] ?? [],
db: values.db,
vapidContact: values['vapid-contact'],
claudeHome: values['claude-home'],
binPath: values['bin-path'],
label: values.label ?? LAUNCHD_LABEL,
dryRun: values['dry-run'] ?? false,
noEnable: values['no-enable'] ?? false,
};
}
/**
* Flags propagés au service : UNIQUEMENT ceux fournis par l'utilisateur (ordre stable,
* ExecStart déterministe). On n'ajoute JAMAIS --i-know-this-exposes-a-terminal automatiquement
* (cf. modèle de sécurité : un service exposé doit être un choix conscient et explicite).
*/
export function buildServiceArgs(flags: InstallFlags): string[] {
const args: string[] = [];
if (flags.port) args.push('--port', flags.port);
if (flags.bind) args.push('--bind', flags.bind);
for (const origin of flags.allowOrigin) args.push('--allow-origin', origin);
if (flags.db) args.push('--db', flags.db);
if (flags.vapidContact) args.push('--vapid-contact', flags.vapidContact);
if (flags.claudeHome) args.push('--claude-home', flags.claudeHome);
return args;
}
/** Le `dist/index.js` réellement installé (depuis dist/cli/install.js). */
export function resolveScriptPath(): string {
return fileURLToPath(new URL('../index.js', import.meta.url));
}
/**
* Cible exécutable du service. Par défaut node + script (immunisé contre un PATH minimal sous
* systemd/launchd) ; --bin-path force le wrapper `arboretum` global (suit les upgrades npm i -g).
*/
export function resolveBin(flags: Pick<InstallFlags, 'binPath'>): { exec: string; args: string[] } {
if (flags.binPath) return { exec: flags.binPath, args: [] };
return { exec: process.execPath, args: [resolveScriptPath()] };
}
export function systemdUnitPath(): string {
const configHome = process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config');
return join(configHome, 'systemd', 'user', `${SERVICE_NAME}.service`);
}
export function launchAgentPlistPath(label: string): string {
return join(homedir(), 'Library', 'LaunchAgents', `${label}.plist`);
}
export function launchdLogPaths(): { dir: string; out: string; err: string } {
const dir = join(homedir(), 'Library', 'Logs', 'arboretum');
return { dir, out: join(dir, 'out.log'), err: join(dir, 'err.log') };
}
export function xmlEscape(s: string): string {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
// systemd accepte les doubles quotes dans ExecStart ; on ne quote que les tokens à espaces.
function quoteIfNeeded(token: string): string {
return /\s/.test(token) ? `"${token}"` : token;
}
export function renderSystemdUnit(input: { exec: string; scriptArgs: string[] }): string {
const execStart = [input.exec, ...input.scriptArgs].map(quoteIfNeeded).join(' ');
// KillSignal=SIGTERM + TimeoutStopSec=10 collent au drain de runDaemon (SIGTERM → drain 1s → close).
return `[Unit]
Description=Arboretum — git worktree & Claude Code dashboard
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=${execStart}
Restart=on-failure
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=10
Environment=NODE_ENV=production
[Install]
WantedBy=default.target
`;
}
export function renderLaunchAgentPlist(input: {
label: string;
programArguments: string[];
stdoutPath: string;
stderrPath: string;
}): string {
const args = input.programArguments.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n');
// KeepAlive/SuccessfulExit=false ≈ Restart=on-failure (ne relance pas après un drain volontaire).
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>${xmlEscape(input.label)}</string>
<key>ProgramArguments</key>
<array>
${args}
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>StandardOutPath</key>
<string>${xmlEscape(input.stdoutPath)}</string>
<key>StandardErrorPath</key>
<string>${xmlEscape(input.stderrPath)}</string>
<key>EnvironmentVariables</key>
<dict>
<key>NODE_ENV</key>
<string>production</string>
</dict>
</dict>
</plist>
`;
}
export function printTokenBanner(token: string, url: string): void {
console.log('\n┌──────────────────────────────────────────────────────────────────┐');
console.log('│ First start — your access token (shown once, store it safely): │');
console.log('└──────────────────────────────────────────────────────────────────┘');
console.log(`\n ${token}\n`);
console.log(` Login at: ${url}/\n`);
}
export function printUsage(version: string): void {
console.log(`Arboretum v${version} — git worktree & Claude Code dashboard
Usage:
arboretum [flags] Start the daemon (default)
arboretum serve [flags] Start the daemon (explicit alias)
arboretum install [flags] Install & start a user service (systemd on Linux, launchd on macOS)
arboretum uninstall Stop & remove the user service
arboretum status Show the service status
arboretum help Show this help
Daemon flags:
--port <n> Port to listen on (default 7317)
--bind <addr> Bind address (default 127.0.0.1)
--allow-origin <url> Additional allowed Origin (repeatable)
--db <path> SQLite database path
--vapid-contact <mailto|url> VAPID contact subject for Web Push
--i-know-this-exposes-a-terminal Acknowledge a non-loopback bind (avoid — prefer Tailscale Serve)
Install flags (daemon flags above are propagated to the service):
--bin-path <path> Use this binary in the service instead of node + script
--label <id> launchd label (macOS only, default ${LAUNCHD_LABEL})
--dry-run Print the unit/plist and commands without applying anything
--no-enable Write the service file but do not enable/start it
`);
}
// ─── Effets de bord (fs + exec) ───────────────────────────────────────────────────────
function run(cmd: string, args: string[], opts?: { check?: boolean }): number {
const res = spawnSync(cmd, args, { stdio: 'inherit' });
if (res.error) {
if ((res.error as NodeJS.ErrnoException).code === 'ENOENT') {
throw new Error(`Command not found: ${cmd}. Is it installed and on your PATH?`);
}
throw res.error;
}
const code = res.status ?? 0;
if (opts?.check && code !== 0) {
throw new Error(`Command failed (exit ${code}): ${cmd} ${args.join(' ')}`);
}
return code;
}
/**
* Bootstrap du token avec EXACTEMENT les flags du service (même db). Valide aussi le bind
* (garde-fou de loadConfig). Affiche le token une fois, puis ferme la db avant que le service
* ne l'ouvre. Skippé en --dry-run par l'appelant.
*/
function bootstrapToken(serviceArgs: string[]): void {
const config = loadConfig(serviceArgs);
const url = `http://${config.bind === '0.0.0.0' ? '127.0.0.1' : config.bind}:${config.port}`;
const db = openDb(config.dbPath);
try {
const token = new AuthService(db).ensureBootstrapToken();
if (token) printTokenBanner(token, url);
else console.log('\nAn access token already exists in this database — manage tokens from Settings.\n');
} finally {
db.close();
}
}
export async function runInstall(argv: string[]): Promise<void> {
const platform = detectPlatform();
const flags = parseInstallArgs(argv);
const serviceArgs = buildServiceArgs(flags);
const { exec, args: binArgs } = resolveBin(flags);
const scriptArgs = [...binArgs, ...serviceArgs];
if (platform === 'linux') {
const unit = renderSystemdUnit({ exec, scriptArgs });
const unitPath = systemdUnitPath();
if (flags.dryRun) {
console.log(`# ${unitPath}\n${unit}\n# commands:`);
console.log('systemctl --user daemon-reload');
if (!flags.noEnable) {
console.log(`systemctl --user enable --now ${SERVICE_NAME}`);
console.log(`loginctl enable-linger ${process.env.USER ?? '$USER'}`);
}
return;
}
bootstrapToken(serviceArgs);
mkdirSync(dirname(unitPath), { recursive: true });
writeFileSync(unitPath, unit);
console.log(`Wrote ${unitPath}`);
run('systemctl', ['--user', 'daemon-reload'], { check: true });
if (!flags.noEnable) {
run('systemctl', ['--user', 'enable', '--now', SERVICE_NAME], { check: true });
// enable-linger best-effort : absent en CI / sans session loginctl, non bloquant.
if (run('loginctl', ['enable-linger', process.env.USER ?? '']) !== 0) {
console.warn('Warning: could not enable linger — the service may not start at boot.');
}
}
console.log(`\nArboretum service installed. Logs: journalctl --user -u ${SERVICE_NAME} -f`);
return;
}
// macOS (launchd)
const logs = launchdLogPaths();
const programArguments = [exec, ...scriptArgs];
const plist = renderLaunchAgentPlist({
label: flags.label,
programArguments,
stdoutPath: logs.out,
stderrPath: logs.err,
});
const plistPath = launchAgentPlistPath(flags.label);
const uid = process.getuid?.() ?? 0;
const target = `gui/${uid}/${flags.label}`;
if (flags.dryRun) {
console.log(`# ${plistPath}\n${plist}\n# commands:`);
console.log(`launchctl bootout ${target} # best-effort`);
if (!flags.noEnable) {
console.log(`launchctl bootstrap gui/${uid} ${plistPath}`);
console.log(`launchctl enable ${target}`);
console.log(`launchctl kickstart -k ${target}`);
}
return;
}
bootstrapToken(serviceArgs);
mkdirSync(dirname(plistPath), { recursive: true });
mkdirSync(logs.dir, { recursive: true });
writeFileSync(plistPath, plist);
console.log(`Wrote ${plistPath}`);
if (!flags.noEnable) {
run('launchctl', ['bootout', target]); // best-effort : ignore "not loaded" (rend bootstrap idempotent)
run('launchctl', ['bootstrap', `gui/${uid}`, plistPath], { check: true });
run('launchctl', ['enable', target]);
run('launchctl', ['kickstart', '-k', target]);
}
console.log(`\nArboretum service installed. Logs: ${logs.out}`);
}
export async function runUninstall(argv: string[]): Promise<void> {
const platform = detectPlatform();
const flags = parseInstallArgs(argv);
if (platform === 'linux') {
const unitPath = systemdUnitPath();
run('systemctl', ['--user', 'disable', '--now', SERVICE_NAME]); // best-effort
if (existsSync(unitPath)) {
rmSync(unitPath);
console.log(`Removed ${unitPath}`);
}
run('systemctl', ['--user', 'daemon-reload']);
console.log('Arboretum service removed.');
return;
}
const plistPath = launchAgentPlistPath(flags.label);
const uid = process.getuid?.() ?? 0;
run('launchctl', ['bootout', `gui/${uid}/${flags.label}`]); // best-effort
if (existsSync(plistPath)) {
rmSync(plistPath);
console.log(`Removed ${plistPath}`);
}
console.log('Arboretum service removed.');
}
export async function runStatus(argv: string[]): Promise<void> {
const platform = detectPlatform();
const flags = parseInstallArgs(argv);
if (platform === 'linux') {
const code = run('systemctl', ['--user', 'status', SERVICE_NAME, '--no-pager']);
console.log(`\nLogs: journalctl --user -u ${SERVICE_NAME} -f`);
process.exitCode = code;
return;
}
const uid = process.getuid?.() ?? 0;
const code = run('launchctl', ['print', `gui/${uid}/${flags.label}`]);
console.log(`\nLogs: ${launchdLogPaths().out}`);
process.exitCode = code;
}
+1 -19
View File
@@ -1,7 +1,7 @@
import { parseArgs } from 'node:util';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { chmodSync, mkdirSync } from 'node:fs';
import { mkdirSync } from 'node:fs';
export interface Config {
port: number;
@@ -15,10 +15,6 @@ export interface Config {
claudeProjectsDir: string;
/** ~/.claude/sessions (registre des sessions CLI vivantes). */
claudeSessionsDir: string;
/** sujet VAPID des notifications Web Push (mailto: ou URL). */
vapidContact: string;
/** découverte auto des repos au démarrage + périodique (désactivable via --no-discover). */
autoDiscover: boolean;
}
export function loadConfig(argv = process.argv.slice(2)): Config {
@@ -33,10 +29,6 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
'i-know-this-exposes-a-terminal': { type: 'boolean', default: false },
// racine de l'install Claude (~/.claude par défaut) — surchargée par les tests d'acceptation.
'claude-home': { type: 'string' },
// sujet VAPID des notifications push (contact requis par la spec Web Push).
'vapid-contact': { type: 'string' },
// désactive la découverte auto des repos (boot + périodique) — utilisé par les tests d'acceptation.
'no-discover': { type: 'boolean', default: false },
},
strict: true,
});
@@ -53,14 +45,6 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
const dataDir = join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), 'arboretum');
mkdirSync(dataDir, { recursive: true });
// La DB contient des secrets (server_secret, clé privée VAPID, hashs de tokens) : le dossier de
// données ne doit jamais être lisible par d'autres utilisateurs du système. chmod best-effort
// (peut échouer sur certains FS Windows/montés ; le démarrage avertit alors sans bloquer).
try {
chmodSync(dataDir, 0o700);
} catch {
/* FS sans permissions POSIX : ignoré, cf. avertissement dans db.openDb */
}
const claudeHome = values['claude-home'] ?? join(homedir(), '.claude');
return {
port: Number(values.port),
@@ -71,7 +55,5 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
printToken: values['print-token'] ?? false,
claudeProjectsDir: join(claudeHome, 'projects'),
claudeSessionsDir: join(claudeHome, 'sessions'),
vapidContact: values['vapid-contact'] ?? 'mailto:arboretum@localhost',
autoDiscover: !(values['no-discover'] ?? false),
};
}
-65
View File
@@ -1,65 +0,0 @@
// Journal d'audit : trace persistante des opérations sensibles (création/révocation de tokens,
// changements de réglages, génération de secrets, abonnements push, CRUD groupes). Exigence de
// conformité entreprise (GDPR/SOX/ISO 27001). Règle ABSOLUE : ne JAMAIS journaliser un secret en
// clair — `details` ne contient que des métadonnées non sensibles (ids, labels, compteurs).
import { randomUUID } from 'node:crypto';
import type { AuditLogEntry } from '@arboretum/shared';
import type { Db } from '../db/index.js';
export type AuditResult = 'ok' | 'denied' | 'error';
export interface AuditEntry {
/** tokenId de l'acteur, ou 'system' (opérations automatiques), ou 'anonymous' (avant auth). */
actor: string;
/** verbe.objet, ex. 'token.create', 'settings.update', 'login.failure'. */
action: string;
resourceId?: string | null;
details?: Record<string, unknown> | null;
result?: AuditResult;
}
/** Enregistre une entrée d'audit. Best-effort : une erreur d'écriture ne casse jamais l'opération métier. */
export function recordAudit(db: Db, e: AuditEntry): void {
try {
db.prepare(
'INSERT INTO audit_logs (id, ts, actor, action, resource_id, details, result) VALUES (?, ?, ?, ?, ?, ?, ?)',
).run(
randomUUID(),
new Date().toISOString(),
e.actor,
e.action,
e.resourceId ?? null,
e.details ? JSON.stringify(e.details) : null,
e.result ?? 'ok',
);
} catch {
/* l'audit ne doit jamais faire échouer l'action auditée */
}
}
/** Liste paginée par date décroissante (curseur `before` = ts strictement inférieur). */
export function listAudit(db: Db, opts: { limit: number; before?: string | null }): AuditLogEntry[] {
const limit = Math.min(Math.max(Math.trunc(opts.limit) || 50, 1), 200);
const rows = (
opts.before
? db
.prepare(
'SELECT id, ts, actor, action, resource_id AS resourceId, details, result FROM audit_logs WHERE ts < ? ORDER BY ts DESC LIMIT ?',
)
.all(opts.before, limit)
: db
.prepare(
'SELECT id, ts, actor, action, resource_id AS resourceId, details, result FROM audit_logs ORDER BY ts DESC LIMIT ?',
)
.all(limit)
) as Array<{ id: string; ts: string; actor: string; action: string; resourceId: string | null; details: string | null; result: string }>;
return rows.map((r) => ({ ...r, details: r.details ? safeParse(r.details) : null }));
}
function safeParse(s: string): unknown {
try {
return JSON.parse(s);
} catch {
return s;
}
}
@@ -1,90 +0,0 @@
// claude-adapter : déduit l'état fin d'une session (busy / waiting / idle) + le dialogue typé.
// Source PRIMAIRE = le registre ~/.claude/sessions (status stable inter-versions) ; l'écran reconstruit
// (@xterm/headless) sert uniquement à TYPER le dialogue et à couvrir le cas Trust (qui précède le
// registre). Un tracker par session vive claude, alimenté par le flux PTY (pas de re-replay du ring).
import type { SessionActivity, SessionDialog } from '@arboretum/shared';
import { ScreenReader } from './screen-reader.js';
import { classifyDialog } from './dialog-classifier.js';
import { findByPid } from './session-registry.js';
const DEBOUNCE_MS = 200; // coalescence des rafales d'output avant ré-évaluation
const POLL_MS = 700; // capte les transitions busy↔idle qui n'émettent pas d'output discriminant
export interface AdapterState {
activity: SessionActivity | null;
waitingFor: string | null;
dialog: SessionDialog | null;
}
const EMPTY: AdapterState = { activity: null, waitingFor: null, dialog: null };
function sameState(a: AdapterState, b: AdapterState): boolean {
return a.activity === b.activity && a.waitingFor === b.waitingFor && JSON.stringify(a.dialog) === JSON.stringify(b.dialog);
}
export class SessionActivityTracker {
private readonly reader = new ScreenReader(120, 32);
private state: AdapterState = EMPTY;
private debounce: NodeJS.Timeout | null = null;
private readonly poll: NodeJS.Timeout;
private disposed = false;
constructor(
private readonly pid: number,
private readonly sessionsDir: string,
private readonly onChange: () => void,
) {
this.poll = setInterval(() => this.evaluate(), POLL_MS);
this.poll.unref();
}
feed(chunk: Uint8Array): void {
if (this.disposed) return;
void this.reader.feed(chunk);
if (this.debounce) return;
this.debounce = setTimeout(() => {
this.debounce = null;
this.evaluate();
}, DEBOUNCE_MS);
this.debounce.unref();
}
resize(cols: number, rows: number): void {
if (!this.disposed) this.reader.resize(cols, rows);
}
snapshot(): AdapterState {
return this.state;
}
/** Évalue l'état courant (debounce → snapshot fiable). Public pour les tests déterministes. */
evaluate(): void {
if (this.disposed) return;
const reg = findByPid(this.sessionsDir, this.pid);
const next = this.derive(reg?.status ?? null, reg?.waitingFor ?? null);
if (!sameState(this.state, next)) {
this.state = next;
this.onChange();
}
}
private derive(status: 'busy' | 'idle' | 'waiting' | null, waitingFor: string | null): AdapterState {
if (status === 'busy') return { activity: 'busy', waitingFor: null, dialog: null };
if (status === 'idle') return { activity: 'idle', waitingFor: null, dialog: null };
if (status === 'waiting') {
const c = classifyDialog(this.reader.snapshotLines());
return { activity: 'waiting', waitingFor, dialog: c ? { kind: c.kind, waitingFor, options: c.options } : null };
}
// Pas (encore) de registre : seul le dialogue Trust le précède (spike S1).
const c = classifyDialog(this.reader.snapshotLines());
if (c?.kind === 'trust') return { activity: 'waiting', waitingFor: 'trust', dialog: { kind: 'trust', waitingFor: 'trust', options: c.options } };
return EMPTY;
}
dispose(): void {
this.disposed = true;
if (this.debounce) clearTimeout(this.debounce);
clearInterval(this.poll);
this.reader.dispose();
}
}
@@ -10,8 +10,6 @@ export interface SpawnOptions {
command: 'claude' | 'bash';
/** reprise d'une session existante (P2) : `--resume <id>`, `--fork-session` si fork. */
resume?: { claudeSessionId: string; fork?: boolean };
/** répertoires supplémentaires à relier dans une seule session (P6) : `--add-dir <path>` répété. */
addDirs?: string[];
}
let cachedClaudeBin: string | null = null;
@@ -44,7 +42,5 @@ export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
args.push('--resume', opts.resume.claudeSessionId);
if (opts.resume.fork) args.push('--fork-session');
}
// Session de groupe : relie plusieurs repos/worktrees dans une seule session (P6).
for (const dir of opts.addDirs ?? []) args.push('--add-dir', dir);
return { file: resolveClaudeBin(), args, env };
}
-41
View File
@@ -1,41 +0,0 @@
// Pré-trust programmatique (spike S3) : écrit projects["<worktree>"].hasTrustDialogAccepted = true
// dans ~/.claude.json pour éviter le dialogue Trust au 1er lancement de `claude` dans un worktree neuf.
// Écriture ATOMIQUE (tmp + rename). Le chemin est injectable pour les tests (jamais le vrai HOME).
import { readFileSync, writeFileSync, renameSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
export function claudeConfigPath(): string {
return join(homedir(), '.claude.json');
}
/**
* Marque un worktree comme déjà approuvé. Tolérant : fichier absent → on le crée ; fichier corrompu
* → on ABANDONNE le pré-trust (on ne l'écrase pas, pour ne pas perdre la config existante). Retourne
* true si le pré-trust a été écrit, false sinon (l'appelant continue : ce n'est pas bloquant).
*/
export function preTrustProject(worktreePath: string, filePath = claudeConfigPath()): boolean {
let data: Record<string, unknown> = {};
try {
const parsed = JSON.parse(readFileSync(filePath, 'utf8')) as unknown;
if (typeof parsed !== 'object' || parsed === null) return false; // contenu inattendu : on n'écrase pas
data = parsed as Record<string, unknown>;
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return false; // corrompu/illisible : abandon
data = {}; // fichier absent : on part d'un objet vide
}
const projects =
typeof data.projects === 'object' && data.projects !== null
? (data.projects as Record<string, Record<string, unknown>>)
: {};
projects[worktreePath] = { ...(projects[worktreePath] ?? {}), hasTrustDialogAccepted: true };
data.projects = projects;
try {
const tmp = `${filePath}.arb-tmp`;
writeFileSync(tmp, JSON.stringify(data, null, 2));
renameSync(tmp, filePath); // rename atomique : jamais de fichier à moitié écrit
return true;
} catch {
return false;
}
}
@@ -1,46 +0,0 @@
// Typage de dialogue à partir de l'écran reconstruit (ScreenReader) — fonctions PURES.
// L'écran sert à TYPER le dialogue et extraire ses options ; l'état (waiting vrai/faux) vient du
// registre (source primaire). Tolérant aux variations de rendu inter-versions (texte aplati + regex).
import type { DialogKind, DialogOption } from '@arboretum/shared';
export interface ClassifiedDialog {
kind: DialogKind;
options: DialogOption[];
}
// Option numérotée, éventuellement préfixée du curseur ❯ : « ❯ 1. Yes », « 2) No »…
const OPTION_RE = /^\s*(❯)?\s*(\d+)[.)]\s+(.*\S)\s*$/;
export function parseOptions(lines: string[]): DialogOption[] {
const out: DialogOption[] = [];
for (const line of lines) {
const m = OPTION_RE.exec(line);
if (m && m[2] && m[3]) out.push({ n: Number(m[2]), label: m[3].trim(), selected: Boolean(m[1]) });
}
return out;
}
/**
* Retourne le dialogue typé visible à l'écran, ou null si aucun. `trust` et `question` priment sur
* `permission` (un écran AskUserQuestion contient aussi « Esc to cancel »). Un écran numéroté non
* typé est traité en `permission` générique (best-effort — le fallback reste le terminal web).
*/
export function classifyDialog(lines: string[]): ClassifiedDialog | null {
const text = lines.join('\n');
const flat = text.replace(/\s+/g, '').toLowerCase();
const options = parseOptions(lines);
const isTrust = flat.includes('trust') && (text.includes('❯') || flat.includes('entertoconfirm') || flat.includes('trustthisfolder'));
const isQuestion = flat.includes('entertoselect') || flat.includes('tonavigate') || text.includes('↑/↓');
const isPermission = flat.includes('doyouwant') || flat.includes('esctocancel') || flat.includes('tabtoamend');
const isPlan = flat.includes('readytocode') || flat.includes('wouldyouliketoproceed');
let kind: DialogKind | null = null;
if (isTrust) kind = 'trust';
else if (isQuestion) kind = 'question';
else if (isPlan) kind = 'plan';
else if (isPermission) kind = 'permission';
else if (options.length > 0) kind = 'permission';
return kind ? { kind, options } : null;
}
@@ -7,7 +7,6 @@ import { join } from 'node:path';
import type { SessionSummary } from '@arboretum/shared';
import { scanProjects, type DiscoveredJsonl } from './jsonl-discovery.js';
import { readRegistry, type RegistryEntry } from './session-registry.js';
import { listHiddenSessionIds, type Db } from '../db/index.js';
import type { PtyManager } from './pty-manager.js';
const DEFAULT_REFRESH_MS = 10_000;
@@ -18,7 +17,6 @@ export interface DiscoveryServiceEvents {
}
export interface DiscoveryOptions {
db: Db;
ptyManager: PtyManager;
projectsDir?: string;
sessionsDir?: string;
@@ -26,7 +24,6 @@ export interface DiscoveryOptions {
}
export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
private readonly db: Db;
private readonly projectsDir: string;
private readonly sessionsDir: string;
private readonly ptyManager: PtyManager;
@@ -38,7 +35,6 @@ export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
constructor(opts: DiscoveryOptions) {
super();
this.db = opts.db;
this.ptyManager = opts.ptyManager;
this.projectsDir = opts.projectsDir ?? join(homedir(), '.claude', 'projects');
this.sessionsDir = opts.sessionsDir ?? join(homedir(), '.claude', 'sessions');
@@ -85,9 +81,6 @@ export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
if (r.claudeSessionId) regBySid.set(r.claudeSessionId, r);
}
const known = this.ptyManager.knownClaudeSessionIds();
// Sessions masquées par l'utilisateur : on les garde dans le cache (resume/fork possibles) mais
// marquées `hidden` → la route /sessions les exclut par défaut.
const hiddenIds = listHiddenSessionIds(this.db);
// Dédoublonnage des JSONL par claudeSessionId (on retient le plus récent).
const latest = new Map<string, DiscoveredJsonl>();
@@ -120,7 +113,6 @@ export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
resumable: !live, // morte → --resume direct ; vivante → fork/observe (jamais resume : corruption)
attachable: false, // Arboretum ne tient pas le PTY d'une session externe
registryStatus: r?.status ?? null,
hidden: hiddenIds.has(d.claudeSessionId),
});
}
-313
View File
@@ -1,313 +0,0 @@
// Couche git sûre : tout passe par execFile (JAMAIS de shell), arguments en tableau, `--` avant
// les chemins/refs utilisateur. Fonctions pures sans état, prenant un cwd déjà validé par l'appelant.
import { execFile } from 'node:child_process';
import { resolve, sep } from 'node:path';
import type { WorktreeGitStatus, WorktreeBranchAction, WorktreeBranchMode } from '@arboretum/shared';
const GIT_TIMEOUT_MS = 10_000;
// `push` peut dialoguer avec un remote (réseau) : on lui laisse une marge bien plus large.
const GIT_PUSH_TIMEOUT_MS = 120_000;
const GIT_MAX_BUFFER = 8 * 1024 * 1024;
interface GitError extends Error {
stderr?: string;
code?: number | string;
}
function git(cwd: string, args: string[], timeoutMs: number = GIT_TIMEOUT_MS): Promise<string> {
return new Promise((resolveP, reject) => {
execFile(
'git',
args,
{
cwd,
timeout: timeoutMs,
maxBuffer: GIT_MAX_BUFFER,
// GIT_OPTIONAL_LOCKS=0 : pas de prise de verrou par `status` (perf + concurrence avec une
// session claude active) ; LC_ALL=C : sortie stable pour le parsing.
env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' },
},
(err, stdout, stderr) => {
if (err) {
(err as GitError).stderr = String(stderr);
reject(err);
} else {
resolveP(stdout.toString());
}
},
);
});
}
export interface ParsedWorktree {
path: string;
head: string | null;
branch: string | null;
detached: boolean;
locked: boolean;
prunable: boolean;
bare: boolean;
}
/** Parse la sortie `git worktree list --porcelain` (testable isolément, sans repo réel). */
export function parseWorktreePorcelain(stdout: string): ParsedWorktree[] {
const out: ParsedWorktree[] = [];
let cur: Partial<ParsedWorktree> | null = null;
const flush = (): void => {
if (cur?.path) {
out.push({
path: cur.path,
head: cur.head ?? null,
branch: cur.branch ?? null,
detached: cur.detached ?? false,
locked: cur.locked ?? false,
prunable: cur.prunable ?? false,
bare: cur.bare ?? false,
});
}
cur = null;
};
for (const line of stdout.split('\n')) {
if (line === '') {
flush();
continue;
}
const sp = line.indexOf(' ');
const key = sp === -1 ? line : line.slice(0, sp);
const val = sp === -1 ? '' : line.slice(sp + 1);
switch (key) {
case 'worktree':
flush();
cur = { path: val };
break;
case 'HEAD':
if (cur) cur.head = val;
break;
case 'branch':
if (cur) cur.branch = val.replace(/^refs\/heads\//, '');
break;
case 'detached':
if (cur) cur.detached = true;
break;
case 'bare':
if (cur) cur.bare = true;
break;
case 'locked':
if (cur) cur.locked = true;
break;
case 'prunable':
if (cur) cur.prunable = true;
break;
}
}
flush();
return out;
}
/** Refuse les noms de branche dangereux (défense en profondeur ; git valide déjà côté lui). */
export function isValidBranchName(name: string): boolean {
return (
/^[A-Za-z0-9._/-]+$/.test(name) &&
!name.startsWith('-') &&
!name.startsWith('/') &&
!name.endsWith('/') &&
!name.endsWith('.lock') &&
!name.includes('..') &&
!name.includes('//')
);
}
/** Chemin absolu sans segment `..` après résolution (évite l'échappement d'arborescence). */
export function isSafeAbsolutePath(p: string): boolean {
return p.startsWith('/') && resolve(p) === p && !p.split(sep).includes('..');
}
/** true si `path` est la racine d'un dépôt git (main worktree) accessible. */
export async function isRepo(path: string): Promise<boolean> {
try {
const top = (await git(path, ['rev-parse', '--show-toplevel'])).trim();
return resolve(top) === resolve(path);
} catch {
return false;
}
}
/** Branche par défaut (origin/HEAD) en nom court, ou null si indéterminée. */
export async function defaultBranch(repoPath: string): Promise<string | null> {
try {
const ref = (await git(repoPath, ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'])).trim();
return ref.replace(/^refs\/remotes\/origin\//, '') || null;
} catch {
return null;
}
}
/** Branche courante (nom court) du checkout en `repoPath`, ou null si HEAD détaché. */
export async function currentBranch(repoPath: string): Promise<string | null> {
try {
const b = (await git(repoPath, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim();
return b === 'HEAD' ? null : b;
} catch {
return null;
}
}
/** Existence d'une branche, en local (`refs/heads`) et/ou suivie du remote (`refs/remotes/origin`). */
export async function branchExists(repoPath: string, branch: string): Promise<{ local: boolean; remote: boolean }> {
const verify = async (ref: string): Promise<boolean> => {
try {
await git(repoPath, ['rev-parse', '--verify', '--quiet', ref]);
return true;
} catch {
return false;
}
};
const [local, remote] = await Promise.all([verify(`refs/heads/${branch}`), verify(`refs/remotes/origin/${branch}`)]);
return { local, remote };
}
/** Branches locales + suivies de `origin` (noms courts) + branche par défaut — pour un sélecteur de base. */
export async function listBranches(repoPath: string): Promise<{ local: string[]; remote: string[]; default: string | null }> {
const local: string[] = [];
const remote: string[] = [];
try {
const out = await git(repoPath, ['for-each-ref', '--format=%(refname:short)', 'refs/heads', 'refs/remotes/origin']);
for (const line of out.split('\n')) {
const name = line.trim();
if (!name) continue;
if (name.startsWith('origin/')) {
const short = name.slice('origin/'.length);
if (short && short !== 'HEAD') remote.push(short);
} else {
local.push(name);
}
}
} catch {
/* dépôt sans refs encore (premier commit absent) → listes vides */
}
return { local, remote, default: await defaultBranch(repoPath) };
}
export async function listWorktrees(repoPath: string): Promise<ParsedWorktree[]> {
return parseWorktreePorcelain(await git(repoPath, ['worktree', 'list', '--porcelain']));
}
/** État git d'un worktree : ahead/behind vs upstream + nombre de fichiers modifiés. */
export async function worktreeStatus(worktreePath: string): Promise<WorktreeGitStatus> {
let upstream: string | null = null;
let ahead = 0;
let behind = 0;
try {
upstream = (await git(worktreePath, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'])).trim() || null;
} catch {
upstream = null;
}
if (upstream) {
try {
// left = commits de l'upstream absents de HEAD (behind) ; right = HEAD non poussés (ahead).
const out = (await git(worktreePath, ['rev-list', '--left-right', '--count', `${upstream}...HEAD`])).trim();
const [left, right] = out.split(/\s+/);
behind = Number(left) || 0;
ahead = Number(right) || 0;
} catch {
/* refs inaccessibles : on laisse 0/0 */
}
}
let dirtyCount = 0;
try {
const status = await git(worktreePath, ['status', '--porcelain=v1', '--untracked-files=all']);
dirtyCount = status.split('\n').filter((l) => l.trim() !== '').length;
} catch {
/* ignore */
}
return { ahead, behind, dirtyCount, upstream };
}
/** Point de départ d'une branche créée : `baseRef` explicite, sinon la branche par défaut du dépôt
* (locale ou suivie de `origin`), sinon undefined (git part alors du HEAD courant). */
async function resolveStartPoint(repoPath: string, baseRef?: string): Promise<string | undefined> {
if (baseRef) return baseRef;
const def = await defaultBranch(repoPath);
if (!def) return undefined;
const { local, remote } = await branchExists(repoPath, def);
if (local) return def;
if (remote) return `origin/${def}`;
return undefined;
}
/**
* Crée un worktree en résolvant la branche selon `mode` (voir `WorktreeBranchMode`). Renvoie l'action
* effective. En mode `auto`, on choisit checkout / suivi-remote / création selon l'existence réelle de
* la branche — indispensable pour les groupes hétérogènes (branche présente dans certains dépôts seulement).
*/
export async function addWorktree(
repoPath: string,
opts: { path: string; branch: string; mode: WorktreeBranchMode; baseRef?: string },
): Promise<WorktreeBranchAction> {
const { local, remote } = await branchExists(repoPath, opts.branch);
let action: WorktreeBranchAction;
if (opts.mode === 'create') action = 'created';
else if (opts.mode === 'checkout') action = local ? 'reused' : 'tracked';
else action = local ? 'reused' : remote ? 'tracked' : 'created'; // auto
const args = ['worktree', 'add'];
if (action === 'reused') {
args.push('--', opts.path, opts.branch);
} else if (action === 'tracked') {
args.push('--track', '-b', opts.branch, '--', opts.path, `origin/${opts.branch}`);
} else {
const start = await resolveStartPoint(repoPath, opts.baseRef);
args.push('-b', opts.branch, '--', opts.path);
if (start) args.push(start);
}
await git(repoPath, args);
return action;
}
/** `git add -A` puis commit. L'appelant garantit qu'il y a quelque chose à committer. */
export async function commitAll(repoPath: string, message: string): Promise<void> {
await git(repoPath, ['add', '-A']);
await git(repoPath, ['commit', '-m', message]);
}
/** Pousse la branche courante. Si aucun upstream n'est configuré : `git push -u origin <branche>`. */
export async function push(repoPath: string): Promise<void> {
let hasUpstream = false;
try {
await git(repoPath, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
hasUpstream = true;
} catch {
hasUpstream = false;
}
if (hasUpstream) {
await git(repoPath, ['push'], GIT_PUSH_TIMEOUT_MS);
} else {
const branch = await currentBranch(repoPath);
if (!branch) throw new Error('cannot push a detached HEAD');
await git(repoPath, ['push', '-u', 'origin', branch], GIT_PUSH_TIMEOUT_MS);
}
}
/**
* Crée/bascule une branche dans le checkout (worktree) en `repoPath` — utilisé pour démarrer une
* session sur la branche principale sans worktree dédié. `create` → `git switch -c <branch>` (échoue
* si la branche existe) ; sinon `git switch <branch>` (branche existante). Pas de `--` : l'argument
* est une réf (pas un pathspec) et le nom est déjà filtré en amont par `isValidBranchName` (anti-flag).
*/
export async function switchBranch(repoPath: string, opts: { branch: string; create: boolean }): Promise<void> {
await git(repoPath, opts.create ? ['switch', '-c', opts.branch] : ['switch', opts.branch]);
}
export async function removeWorktree(repoPath: string, worktreePath: string, force: boolean): Promise<void> {
await git(repoPath, ['worktree', 'remove', ...(force ? ['--force'] : []), '--', worktreePath]);
}
export async function pruneWorktrees(repoPath: string): Promise<void> {
await git(repoPath, ['worktree', 'prune']);
}
/** true si l'erreur git d'un `worktree remove` est due à des changements non sauvegardés. */
export function isDirtyWorktreeError(err: unknown): boolean {
const msg = `${(err as GitError)?.stderr ?? ''} ${(err as Error)?.message ?? ''}`;
return /contains modified or untracked files|is dirty|use --force/i.test(msg);
}
-203
View File
@@ -1,203 +0,0 @@
// Gestion des groupes de travail (P5) : un groupe = collection nommée de repos (many-to-many).
// Membership légère et persistée ; les worktrees/sessions du groupe ne sont PAS stockés ici —
// ils restent servis par WorktreeManager/PtyManager et filtrés côté client par repoId.
// Tout est synchrone : aucune I/O git/fs, node:sqlite est synchrone.
import { EventEmitter } from 'node:events';
import { randomUUID } from 'node:crypto';
import type { GroupSummary } from '@arboretum/shared';
import type { Db } from '../db/index.js';
const LABEL_MAX = 100;
const DESCRIPTION_MAX = 2000;
const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
interface GroupRow {
id: string;
label: string;
description: string | null;
color: string | null;
position: number;
created_at: string;
updated_at: string;
}
export interface GroupManagerEvents {
group_update: [GroupSummary];
group_removed: [string];
}
/** Erreur portant un statusCode + code pour mapping HTTP direct par les routes (cf. sendManagerError). */
function httpError(statusCode: number, code: string, message: string): Error {
return Object.assign(new Error(message), { statusCode, code });
}
/** Valide un label : non vide après trim, borné. */
function normLabel(label: unknown): string {
if (typeof label !== 'string') throw httpError(400, 'BAD_REQUEST', 'label is required');
const v = label.trim();
if (v === '') throw httpError(400, 'BAD_REQUEST', 'label must not be empty');
if (v.length > LABEL_MAX) throw httpError(400, 'BAD_REQUEST', `label must be at most ${LABEL_MAX} characters`);
return v;
}
/** Normalise une description : vide/absente → null, bornée sinon. */
function normDescription(description: string | null | undefined): string | null {
if (description === null || description === undefined) return null;
const v = description.trim();
if (v === '') return null;
if (v.length > DESCRIPTION_MAX) throw httpError(400, 'BAD_REQUEST', `description must be at most ${DESCRIPTION_MAX} characters`);
return v;
}
/** Normalise une couleur : vide/absente → null, doit être un hex `#rrggbb` sinon. */
function normColor(color: string | null | undefined): string | null {
if (color === null || color === undefined) return null;
const v = color.trim();
if (v === '') return null;
if (!COLOR_RE.test(v)) throw httpError(400, 'BAD_REQUEST', 'color must be a hex string like #4f46e5');
return v;
}
export class GroupManager extends EventEmitter<GroupManagerEvents> {
constructor(private readonly db: Db) {
super();
}
private getGroupRow(id: string): GroupRow | null {
return (this.db.prepare('SELECT * FROM groups WHERE id = ?').get(id) as unknown as GroupRow | undefined) ?? null;
}
private repoIdsFor(groupId: string): string[] {
const rows = this.db
.prepare('SELECT repo_id FROM group_repos WHERE group_id = ? ORDER BY position ASC, created_at ASC')
.all(groupId) as Array<{ repo_id: string }>;
return rows.map((r) => r.repo_id);
}
private rowToSummary(row: GroupRow): GroupSummary {
return {
id: row.id,
label: row.label,
description: row.description,
color: row.color,
repoIds: this.repoIdsFor(row.id),
createdAt: row.created_at,
updatedAt: row.updated_at,
};
}
/** Garde-fou : le repo doit exister (meilleur message que de laisser la FK lever une contrainte opaque). */
private assertRepoExists(repoId: string): void {
if (typeof repoId !== 'string' || repoId === '') throw httpError(400, 'BAD_REQUEST', 'repoId is required');
const exists = this.db.prepare('SELECT 1 FROM repos WHERE id = ?').get(repoId);
if (!exists) throw httpError(404, 'REPO_NOT_FOUND', 'No repo with this id');
}
/** Position d'insertion suivante dans un groupe (append en queue). */
private nextPosition(groupId: string): number {
const row = this.db.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM group_repos WHERE group_id = ?').get(groupId) as {
pos: number;
};
return row.pos;
}
listGroups(): GroupSummary[] {
const rows = this.db.prepare('SELECT * FROM groups ORDER BY position ASC, created_at ASC').all() as unknown as GroupRow[];
return rows.map((r) => this.rowToSummary(r));
}
getGroup(id: string): GroupSummary {
const row = this.getGroupRow(id);
if (!row) throw httpError(404, 'NOT_FOUND', 'No group with this id');
return this.rowToSummary(row);
}
createGroup(opts: { label: string; description?: string; color?: string; repoIds?: string[] }): GroupSummary {
const label = normLabel(opts.label);
const description = normDescription(opts.description);
const color = normColor(opts.color);
const repoIds = opts.repoIds ?? [];
if (!Array.isArray(repoIds)) throw httpError(400, 'BAD_REQUEST', 'repoIds must be an array');
for (const repoId of repoIds) this.assertRepoExists(repoId);
const now = new Date().toISOString();
const id = randomUUID();
const position = this.db.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM groups').get() as { pos: number };
this.db.exec('BEGIN');
try {
this.db
.prepare('INSERT INTO groups (id, label, description, color, position, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
.run(id, label, description, color, position.pos, now, now);
const insertRepo = this.db.prepare('INSERT OR IGNORE INTO group_repos (group_id, repo_id, position, created_at) VALUES (?, ?, ?, ?)');
let pos = 0;
const seen = new Set<string>();
for (const repoId of repoIds) {
if (seen.has(repoId)) continue;
seen.add(repoId);
insertRepo.run(id, repoId, pos++, now);
}
this.db.exec('COMMIT');
} catch (err) {
this.db.exec('ROLLBACK');
throw err;
}
const summary = this.getGroup(id);
this.emit('group_update', summary);
return summary;
}
updateGroup(id: string, patch: { label?: string; description?: string | null; color?: string | null }): GroupSummary {
const row = this.getGroupRow(id);
if (!row) throw httpError(404, 'NOT_FOUND', 'No group with this id');
if (patch.label !== undefined) row.label = normLabel(patch.label);
if (patch.description !== undefined) row.description = normDescription(patch.description);
if (patch.color !== undefined) row.color = normColor(patch.color);
const now = new Date().toISOString();
this.db
.prepare('UPDATE groups SET label = ?, description = ?, color = ?, updated_at = ? WHERE id = ?')
.run(row.label, row.description, row.color, now, id);
const summary = this.getGroup(id);
this.emit('group_update', summary);
return summary;
}
deleteGroup(id: string): boolean {
// CASCADE (PRAGMA foreign_keys = ON) purge group_repos.
const res = this.db.prepare('DELETE FROM groups WHERE id = ?').run(id);
if (res.changes === 0) return false;
// Les sessions de groupe (P6) ne sont pas en FK : on désorpheline leur group_id manuellement.
this.db.prepare('UPDATE sessions SET group_id = NULL WHERE group_id = ?').run(id);
this.emit('group_removed', id);
return true;
}
addRepo(groupId: string, repoId: string): GroupSummary {
if (!this.getGroupRow(groupId)) throw httpError(404, 'NOT_FOUND', 'No group with this id');
this.assertRepoExists(repoId);
const now = new Date().toISOString();
// INSERT OR IGNORE → idempotent (PRIMARY KEY (group_id, repo_id)).
this.db
.prepare('INSERT OR IGNORE INTO group_repos (group_id, repo_id, position, created_at) VALUES (?, ?, ?, ?)')
.run(groupId, repoId, this.nextPosition(groupId), now);
this.touch(groupId, now);
const summary = this.getGroup(groupId);
this.emit('group_update', summary);
return summary;
}
removeRepo(groupId: string, repoId: string): GroupSummary {
if (!this.getGroupRow(groupId)) throw httpError(404, 'NOT_FOUND', 'No group with this id');
// DELETE no-op si absent → idempotent.
this.db.prepare('DELETE FROM group_repos WHERE group_id = ? AND repo_id = ?').run(groupId, repoId);
this.touch(groupId, new Date().toISOString());
const summary = this.getGroup(groupId);
this.emit('group_update', summary);
return summary;
}
private touch(groupId: string, now: string): void {
this.db.prepare('UPDATE groups SET updated_at = ? WHERE id = ?').run(now, groupId);
}
}
-37
View File
@@ -1,37 +0,0 @@
import { parse, resolve, sep } from 'node:path';
/**
* Plus long ancêtre commun d'un ensemble de chemins absolus (par segments, jamais par préfixe
* de chaîne — `/a/bc` n'est PAS un ancêtre de `/a/bcd`). Pour un seul chemin, renvoie ce chemin.
*/
export function commonAncestorDir(paths: string[]): string {
const first = paths[0];
if (first === undefined) throw new Error('commonAncestorDir: empty input');
const firstSegs = resolve(first).split(sep);
let common = firstSegs.length;
for (let i = 1; i < paths.length; i++) {
const segs = resolve(paths[i]!).split(sep);
let k = 0;
while (k < common && k < segs.length && segs[k] === firstSegs[k]) k++;
common = k;
}
const joined = firstSegs.slice(0, common).join(sep);
// `['', 'a', 'b'].slice(0,1).join('/')` === '' → racine POSIX ; rétablir le séparateur racine.
return joined === '' ? parse(resolve(first)).root : joined;
}
/**
* Politique de répertoire de travail d'une session de groupe (P6) : le `cwd` est le PARENT COMMUN
* des répertoires couverts (racine neutre, chemins relatifs cross-repo naturels), chaque répertoire
* étant ensuite relié via `--add-dir` (le dédoublonnage + filtrage du cwd est fait par `PtyManager`).
* Garde-fou : si le parent commun est la racine du FS (repos éparpillés sur des racines différentes),
* on retombe sur le premier répertoire pour ne pas accorder à Claude la permission sur tout le disque.
*/
export function resolveGroupCwd(dirs: string[]): { cwd: string; addDirs: string[] } {
const first = dirs[0];
if (first === undefined) throw new Error('resolveGroupCwd: empty input');
const ancestor = commonAncestorDir(dirs);
const root = parse(resolve(first)).root;
const cwd = ancestor === root ? first : ancestor;
return { cwd, addDirs: dirs };
}
+15 -194
View File
@@ -2,37 +2,20 @@ import { EventEmitter } from 'node:events';
import { existsSync, statSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
import { homedir } from 'node:os';
import { basename, join } from 'node:path';
import { join } from 'node:path';
import pty from '@homebridge/node-pty-prebuilt-multiarch';
import { FLOW, REPLAY_TAIL_BYTES, type SessionActivity, type SessionSummary } from '@arboretum/shared';
import { FLOW, REPLAY_TAIL_BYTES, type SessionSummary } from '@arboretum/shared';
import { RingBuffer } from './ring-buffer.js';
import { buildSpawnSpec } from './claude-launcher.js';
import { findByPid } from './session-registry.js';
import { SessionActivityTracker } from './claude-adapter.js';
import type { PushService } from './push-service.js';
import type { Db } from '../db/index.js';
// 4 Mo : conserve assez d'historique pour que le replay (REPLAY_TAIL_BYTES = 1 Mo) reste largement
// dans le ring et qu'on puisse remonter une conversation Claude après ré-attache.
const RING_CAPACITY = 4 * 1024 * 1024;
const RING_CAPACITY = 2 * 1024 * 1024;
const KILL_GRACE_MS = 5000;
/** Délai avant envoi d'une notif push sur passage en `waiting` : annulé si la session repart (faux positif). */
const NOTIFY_DEBOUNCE_MS = 1500;
/** Capture du claudeSessionId après spawn : poll du registre par pid (waitReady validé S1). */
const CLAUDE_ID_POLL_MS = 400;
const CLAUDE_ID_TIMEOUT_MS = 60_000;
/** Parse la colonne `added_dirs` (JSON array de chemins) de façon défensive ; [] si NULL/invalide. */
function parseAddedDirs(raw: string | null): string[] {
if (!raw) return [];
try {
const v = JSON.parse(raw);
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
} catch {
return [];
}
}
/** Lien entre un client WS attaché et une session. La gateway fournit les callbacks d'envoi. */
export interface ClientBinding {
channel: number;
@@ -61,16 +44,6 @@ interface ManagedSession {
killTimer: NodeJS.Timeout | null;
/** ID interne du CLI claude, résolu via le registre après spawn (null pour bash / pas encore prêt). */
claudeSessionId: string | null;
/** répertoires supplémentaires reliés dans la session (--add-dir) ; [] pour une session mono-repo (P6). */
addedDirs: string[];
/** groupe propriétaire d'une session de groupe multi-repo ; null sinon (P6). */
groupId: string | null;
/** détection d'état fin (busy/waiting/idle + dialogue) ; null pour bash (P3-B). */
tracker: SessionActivityTracker | null;
/** dernière activité notifiée (détection du front montant vers `waiting` pour le push P4-B). */
prevActivity: SessionActivity | null;
/** timer de notif push débouncée (annulé si la session quitte `waiting` avant l'échéance). */
notifyTimer: NodeJS.Timeout | null;
}
export interface PtyManagerEvents {
@@ -84,38 +57,18 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
constructor(
private readonly db: Db,
private readonly sessionsDir: string = join(homedir(), '.claude', 'sessions'),
private readonly push: PushService | null = null,
) {
super();
}
spawn(opts: {
cwd: string;
command?: 'claude' | 'bash';
resume?: { claudeSessionId: string; fork?: boolean };
/** répertoires supplémentaires à relier (session de groupe multi-repo, P6). */
addDirs?: string[];
/** groupe propriétaire (session de groupe, P6). */
groupId?: string;
}): SessionSummary {
spawn(opts: { cwd: string; command?: 'claude' | 'bash'; resume?: { claudeSessionId: string; fork?: boolean } }): SessionSummary {
const cwd = opts.cwd;
if (!existsSync(cwd) || !statSync(cwd).isDirectory()) {
throw Object.assign(new Error(`Not a directory: ${cwd}`), { statusCode: 400 });
}
// Dédoublonne et écarte le cwd primaire ; valide chaque répertoire supplémentaire (comme le cwd).
const addedDirs = [...new Set(opts.addDirs ?? [])].filter((d) => d !== cwd);
for (const dir of addedDirs) {
if (!existsSync(dir) || !statSync(dir).isDirectory()) {
throw Object.assign(new Error(`Not a directory: ${dir}`), { statusCode: 400 });
}
}
// Un resume/fork est toujours une session claude (le cwd d'origine est garanti par l'appelant — S1).
const command = opts.resume ? 'claude' : (opts.command ?? 'claude');
const spec = buildSpawnSpec({
command,
...(opts.resume ? { resume: opts.resume } : {}),
...(addedDirs.length ? { addDirs: addedDirs } : {}),
});
const spec = buildSpawnSpec({ command, ...(opts.resume ? { resume: opts.resume } : {}) });
const id = randomUUID();
const proc = pty.spawn(spec.file, spec.args, {
name: 'xterm-256color',
@@ -137,33 +90,11 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
exited: null,
killTimer: null,
claudeSessionId: null,
addedDirs,
groupId: opts.groupId ?? null,
tracker: null,
prevActivity: null,
notifyTimer: null,
};
// Détection d'état fin (P3-B) : uniquement pour claude (bash n'a pas de registre).
if (command === 'claude') {
session.tracker = new SessionActivityTracker(proc.pid, this.sessionsDir, () => {
if (session.exited) return;
const summary = this.summarize(session);
this.maybeNotify(session, summary.activity ?? null);
this.emit('session_update', summary);
});
}
this.live.set(id, session);
this.db
.prepare('INSERT INTO sessions (id, cwd, command, created_at, resumed_from, added_dirs, group_id) VALUES (?, ?, ?, ?, ?, ?, ?)')
.run(
id,
cwd,
command,
session.createdAt,
opts.resume?.claudeSessionId ?? null,
addedDirs.length ? JSON.stringify(addedDirs) : null,
session.groupId,
);
.prepare('INSERT INTO sessions (id, cwd, command, created_at, resumed_from) VALUES (?, ?, ?, ?, ?)')
.run(id, cwd, command, session.createdAt, opts.resume?.claudeSessionId ?? null);
proc.onData((data) => this.handleOutput(session, Buffer.from(data, 'utf8')));
proc.onExit(({ exitCode, signal }) => this.handleExit(session, exitCode, signal ?? null));
@@ -191,36 +122,6 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
setTimeout(tick, CLAUDE_ID_POLL_MS).unref();
}
/**
* Contexte de session de groupe (P6) à réinjecter au resume : derniers `added_dirs`/`group_id`
* persistés pour ce claudeSessionId. Permet à `--resume` de re-relier les mêmes répertoires.
*/
groupSessionContext(claudeSessionId: string): { addedDirs: string[]; groupId: string | null } | null {
const row = this.db
.prepare('SELECT added_dirs, group_id FROM sessions WHERE claude_session_id = ? AND added_dirs IS NOT NULL ORDER BY created_at DESC LIMIT 1')
.get(claudeSessionId) as { added_dirs: string | null; group_id: string | null } | undefined;
if (!row) return null;
return { addedDirs: parseAddedDirs(row.added_dirs), groupId: row.group_id };
}
/**
* Cible de reprise d'une session managée MORTE (P2/P6), résolue par UUID Arboretum : son cwd
* d'origine, son claudeSessionId et son contexte de groupe, lus en DB. null si l'id ne correspond
* pas à une session managée morte, reprenable (claude + claudeSessionId connu).
* Complète `DiscoveryService.getDiscovered`, qui ne couvre QUE les sessions claude EXTERNES
* (une managée connue est justement exclue de la découverte).
*/
resumeTargetById(id: string): { cwd: string; claudeSessionId: string; addedDirs: string[]; groupId: string | null } | null {
if (this.live.has(id)) return null; // vivante : pas de resume direct (fork via le même chemin)
const row = this.db
.prepare(
"SELECT cwd, claude_session_id, added_dirs, group_id FROM sessions WHERE id = ? AND ended_at IS NOT NULL AND claude_session_id IS NOT NULL AND command = 'claude'",
)
.get(id) as { cwd: string; claude_session_id: string; added_dirs: string | null; group_id: string | null } | undefined;
if (!row) return null;
return { cwd: row.cwd, claudeSessionId: row.claude_session_id, addedDirs: parseAddedDirs(row.added_dirs), groupId: row.group_id };
}
/** Session managée VIVANTE portant ce claudeSessionId (garde-fou anti-resume d'une session vivante). */
findLiveByClaudeSessionId(claudeSessionId: string): SessionSummary | null {
for (const s of this.live.values()) {
@@ -246,34 +147,29 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
const liveSummaries = [...this.live.values()].map((s) => this.summarize(s));
const liveIds = new Set(this.live.keys());
const rows = this.db
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id FROM sessions ORDER BY created_at DESC LIMIT 100')
.all() as Array<{ id: string; cwd: string; command: string; title: string | null; created_at: string; ended_at: string | null; exit_code: number | null; claude_session_id: string | null; added_dirs: string | null; group_id: string | null }>;
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id FROM sessions ORDER BY created_at DESC LIMIT 100')
.all() as Array<{ id: string; cwd: string; command: string; title: string | null; created_at: string; ended_at: string | null; exit_code: number | null; claude_session_id: string | null }>;
const historical: SessionSummary[] = rows
.filter((r) => !liveIds.has(r.id))
.map((r) => {
const addedDirs = parseAddedDirs(r.added_dirs);
return {
.map((r) => ({
id: r.id,
cwd: r.cwd,
command: r.command,
title: r.title,
status: 'exited' as const,
status: 'exited',
live: false,
createdAt: r.created_at,
endedAt: r.ended_at,
exitCode: r.exit_code,
clients: 0,
source: 'managed' as const,
source: 'managed',
claudeSessionId: r.claude_session_id,
pid: null,
// une session claude morte avec un claudeSessionId connu est reprenable (--resume direct).
resumable: r.command === 'claude' && r.claude_session_id != null,
attachable: false,
registryStatus: null,
...(addedDirs.length ? { addedDirs } : {}),
groupId: r.group_id,
};
});
}));
return [...liveSummaries, ...historical];
}
@@ -316,10 +212,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
const hasController = [...s.clients].some((c) => c.controlling);
binding.controlling = binding.mode === 'interactive' && !hasController;
s.clients.add(binding);
if (binding.controlling) {
s.proc.resize(cols, rows);
s.tracker?.resize(cols, rows);
}
if (binding.controlling) s.proc.resize(cols, rows);
// Replay : reset terminal + queue du ring (l'écran TUI courant se reconstitue)
binding.sendResync(s.ring.tail(REPLAY_TAIL_BYTES));
binding.sentBytes = 0;
@@ -350,41 +243,10 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
return 'ok';
}
/**
* Répond à un dialogue Claude sans clavier (P4-A) : traduit une intention de haut
* niveau en keystrokes PTY, validée contre l'état fin du tracker (P3-B).
* - 'select' N : positionne le curseur sur l'option N puis confirme (`"N\r"`) — protocole acté spike S3.
* - 'confirm' : valide l'option pré-sélectionnée (`"\r"`).
* - 'deny' : refus universel (Esc).
* Réutilise le chemin write (mono-utilisateur : tout interactif peut répondre, observers non).
*/
answer(
sessionId: string,
binding: ClientBinding,
action: 'select' | 'confirm' | 'deny',
optionN?: number,
): 'ok' | 'not_controlling' | 'gone' | 'invalid' {
const s = this.live.get(sessionId);
if (!s || s.exited) return 'gone';
if (binding.mode !== 'interactive') return 'not_controlling';
const act = s.tracker?.snapshot();
if (action === 'select') {
// L'option doit exister dans le dialogue courant (anti-frappe fantôme mobile).
if (!act?.dialog?.options.some((o) => o.n === optionN)) return 'invalid';
s.proc.write(`${optionN}\r`);
return 'ok';
}
// confirm/deny n'exigent qu'un état d'attente (le dialogue Trust précède le registre — S1).
if (act?.activity !== 'waiting') return 'invalid';
s.proc.write(action === 'deny' ? '\x1b' : '\r');
return 'ok';
}
resize(sessionId: string, binding: ClientBinding, cols: number, rows: number): void {
const s = this.live.get(sessionId);
if (!s || s.exited || !binding.controlling) return;
s.proc.resize(cols, rows);
s.tracker?.resize(cols, rows);
}
ack(sessionId: string, binding: ClientBinding, bytes: number): void {
@@ -402,39 +264,8 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
// ---- interne ----
/**
* Push P4-B : notifie sur le FRONT MONTANT vers `waiting` uniquement (le tracker réémet
* souvent le même état), avec un debounce annulable — un `waiting` ultra-bref (Claude répond
* tout seul) ne déclenche pas de notif. Cible tous les abonnements (un seul utilisateur).
*/
private maybeNotify(s: ManagedSession, next: SessionActivity | null): void {
const prev = s.prevActivity;
s.prevActivity = next;
if (!this.push) return;
if (next === 'waiting' && prev !== 'waiting') {
if (s.notifyTimer) clearTimeout(s.notifyTimer);
s.notifyTimer = setTimeout(() => {
s.notifyTimer = null;
const act = s.tracker?.snapshot();
if (s.exited || act?.activity !== 'waiting') return; // faux positif : annulé
void this.push?.notify({
sessionId: s.id,
title: basename(s.cwd) || s.cwd,
body: act.dialog?.waitingFor ?? act.waitingFor ?? 'waiting for your input',
kind: act.dialog?.kind ?? null,
url: `/sessions/${s.id}`,
});
}, NOTIFY_DEBOUNCE_MS);
s.notifyTimer.unref();
} else if (next !== 'waiting' && s.notifyTimer) {
clearTimeout(s.notifyTimer);
s.notifyTimer = null;
}
}
private handleOutput(s: ManagedSession, chunk: Buffer): void {
s.ring.write(chunk);
s.tracker?.feed(chunk);
for (const c of s.clients) {
if (c.lagging) continue;
c.sendOutput(chunk);
@@ -471,10 +302,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
private handleExit(s: ManagedSession, exitCode: number | null, signal: number | null): void {
s.exited = { exitCode, signal };
s.tracker?.dispose();
s.tracker = null;
if (s.killTimer) clearTimeout(s.killTimer);
if (s.notifyTimer) clearTimeout(s.notifyTimer);
const endedAt = new Date().toISOString();
this.db.prepare('UPDATE sessions SET ended_at = ?, exit_code = ? WHERE id = ?').run(endedAt, exitCode, s.id);
for (const c of s.clients) c.onDetached('session_exit');
@@ -485,7 +313,6 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
}
private summarize(s: ManagedSession): SessionSummary {
const act = s.tracker?.snapshot();
return {
id: s.id,
cwd: s.cwd,
@@ -503,13 +330,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
// une managée vivante ne se resume pas (corruption) ; une managée claude morte oui.
resumable: !!s.exited && s.command === 'claude' && s.claudeSessionId != null,
attachable: !s.exited,
// statut brut du registre dérivé de l'activité fine (P3-B) ; null pour bash.
registryStatus: act?.activity ?? null,
activity: act?.activity ?? null,
waitingFor: act?.waitingFor ?? null,
dialog: act?.dialog ?? null,
...(s.addedDirs.length ? { addedDirs: s.addedDirs } : {}),
groupId: s.groupId,
registryStatus: null, // P2 : statut fin des managées via claude-adapter (P3-B)
};
}
}
-124
View File
@@ -1,124 +0,0 @@
// PushService : notifications Web Push (VAPID). Clés VAPID générées une fois au bootstrap
// et stockées dans `settings` (comme le server_secret de l'auth) ; abonnements liés au token
// d'auth (token_id). Quand une session managée passe en `waiting`, pty-manager appelle notify().
import { randomUUID } from 'node:crypto';
import { createRequire } from 'node:module';
import { type Db, getSetting, setSetting } from '../db/index.js';
import type { SecretBox } from './secret-box.js';
import { recordAudit } from './audit-log.js';
// web-push est publié en CommonJS : on le charge via require (verbatimModuleSyntax + NodeNext),
// typé par l'import type — même pattern que @xterm/headless dans screen-reader.ts.
const require = createRequire(import.meta.url);
const webpush = require('web-push') as typeof import('web-push');
export interface PushSubscriptionInput {
endpoint: string;
keys: { p256dh: string; auth: string };
}
/** Charge utile JSON poussée au service worker (cf. packages/web/src/sw.ts). */
export interface PushPayload {
sessionId: string;
title: string;
body: string;
kind: string | null;
url: string;
}
interface SubRow {
id: string;
endpoint: string;
p256dh: string;
auth: string;
}
/** Envoi d'une notif à un abonnement — injectable pour les tests ; défaut = web-push réel. */
export type PushSender = (
subscription: { endpoint: string; keys: { p256dh: string; auth: string } },
payload: string,
options: unknown,
) => Promise<unknown>;
export class PushService {
private readonly vapidPublic: string;
private readonly vapidPrivate: string;
private readonly send: PushSender;
constructor(
private readonly db: Db,
private readonly contact: string = 'mailto:arboretum@localhost',
sender?: PushSender,
box?: SecretBox,
) {
this.send = sender ?? ((sub, payload, options) => webpush.sendNotification(sub, payload, options as Parameters<typeof webpush.sendNotification>[2]));
let pub = getSetting(db, 'vapid_public'); // clé publique : jamais chiffrée (sûre à exposer)
const storedPriv = getSetting(db, 'vapid_private');
let priv = storedPriv ? (box ? box.decrypt(storedPriv) : storedPriv) : null;
if (!pub || !priv) {
const keys = webpush.generateVAPIDKeys();
pub = keys.publicKey;
priv = keys.privateKey;
setSetting(db, 'vapid_public', pub);
setSetting(db, 'vapid_private', box ? box.encrypt(priv) : priv);
recordAudit(db, { actor: 'system', action: 'secret.generate', resourceId: 'vapid' });
} else if (box && storedPriv && !box.isEncrypted(storedPriv)) {
// migration douce : clé privée pré-existante en clair → re-chiffrée.
setSetting(db, 'vapid_private', box.encrypt(priv));
}
this.vapidPublic = pub;
this.vapidPrivate = priv;
}
/** Clé publique VAPID — sûre à exposer (applicationServerKey côté navigateur). */
publicKey(): string {
return this.vapidPublic;
}
/** Enregistre (ou ré-associe) un abonnement, lié au token authentifié. */
subscribe(tokenId: string, sub: PushSubscriptionInput, userAgent: string | null): void {
this.db
.prepare(
`INSERT INTO push_subscriptions (id, token_id, endpoint, p256dh, auth, user_agent, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(endpoint) DO UPDATE SET
token_id = excluded.token_id, p256dh = excluded.p256dh,
auth = excluded.auth, user_agent = excluded.user_agent`,
)
.run(randomUUID(), tokenId, sub.endpoint, sub.keys.p256dh, sub.keys.auth, userAgent, new Date().toISOString());
}
unsubscribe(endpoint: string): void {
this.db.prepare('DELETE FROM push_subscriptions WHERE endpoint = ?').run(endpoint);
}
count(): number {
return (this.db.prepare('SELECT COUNT(*) AS n FROM push_subscriptions').get() as { n: number }).n;
}
/**
* Pousse une notification à TOUS les abonnements (un seul utilisateur, plusieurs appareils).
* Un abonnement expiré (404/410 Gone) est purgé ; les autres erreurs sont ignorées (best-effort,
* un appareil injoignable ne doit pas bloquer les autres).
*/
async notify(payload: PushPayload): Promise<void> {
const rows = this.db.prepare('SELECT id, endpoint, p256dh, auth FROM push_subscriptions').all() as unknown as SubRow[];
if (rows.length === 0) return;
const body = JSON.stringify(payload);
const options = {
vapidDetails: { subject: this.contact, publicKey: this.vapidPublic, privateKey: this.vapidPrivate },
TTL: 60,
};
await Promise.all(
rows.map(async (r) => {
try {
await this.send({ endpoint: r.endpoint, keys: { p256dh: r.p256dh, auth: r.auth } }, body, options);
this.db.prepare('UPDATE push_subscriptions SET last_ok_at = ? WHERE id = ?').run(new Date().toISOString(), r.id);
} catch (err) {
const code = (err as { statusCode?: number }).statusCode;
if (code === 404 || code === 410) this.db.prepare('DELETE FROM push_subscriptions WHERE id = ?').run(r.id);
}
}),
);
}
}
@@ -1,42 +0,0 @@
// Planificateur de la découverte auto des repos : scan au démarrage + re-scan périodique.
// Calqué sur DiscoveryService (sessions) — start()/stop() avec timer .unref(). Démarré depuis
// runDaemon() UNIQUEMENT (jamais buildApp), ce qui isole naturellement les tests vitest du scan.
// Lui-même sans état : il lit les racines/l'intervalle dans `settings` et délègue à WorktreeManager.
import type { Db } from '../db/index.js';
import type { WorktreeManager } from './worktree-manager.js';
import { readScanIntervalMin, readScanRoots } from './scan-settings.js';
export class RepoDiscoveryService {
private timer: NodeJS.Timeout | null = null;
constructor(
private readonly db: Db,
private readonly worktrees: WorktreeManager,
) {}
start(): void {
if (this.timer) return;
void this.refresh(); // scan initial asynchrone : ne bloque pas le boot
const intervalMin = readScanIntervalMin(this.db);
if (intervalMin > 0) {
this.timer = setInterval(() => void this.refresh(), intervalMin * 60_000);
this.timer.unref(); // ne maintient pas le process en vie
}
}
stop(): void {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
/** Relit les racines (changement effectif sans redémarrage) et lance un scan. Ne lève jamais. */
private async refresh(): Promise<void> {
try {
await this.worktrees.discoverRepos({ roots: readScanRoots(this.db) });
} catch {
/* scan tolérant : une erreur ne doit pas tuer le timer */
}
}
}
-97
View File
@@ -1,97 +0,0 @@
// Découverte auto des dépôts git : marche bornée du système de fichiers à la recherche de `.git`.
// Fonction PURE et tolérante (ne lève jamais) — testable isolément comme parseWorktreePorcelain.
// N'appelle JAMAIS git (détection par présence de `.git`) : la validation réelle (isRepo) et la
// résolution de default_branch se font paresseusement à l'enregistrement, pas par dépôt scanné.
import { readdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
export interface ScanLimits {
/** profondeur maximale de descente sous chaque racine (la racine = 0). */
maxDepth: number;
/** nombre maximal de repos retournés (garde-fou anti-explosion d'un FS pathologique). */
maxRepos: number;
/** noms de dossiers à ne jamais ouvrir (en plus des dotdirs, toujours exclus). */
excludeDirs?: Set<string>;
}
/** Dossiers jamais explorés : grosses arborescences sans repos racine, ou bruit de build. */
export const DEFAULT_EXCLUDE_DIRS = new Set<string>([
'node_modules',
'vendor',
'target',
'dist',
'build',
'.cache',
'venv',
'.venv',
'__pycache__',
]);
interface Frame {
dir: string;
depth: number;
}
/**
* Parcours itératif (pile explicite, jamais de récursion non bornée) des `roots`.
* Règles :
* - un dossier contenant `.git` (fichier OU dossier → couvre les worktrees liés) est un repo :
* on l'enregistre ; en profondeur on NE descend PAS dedans (sous-modules/worktrees imbriqués
* ignorés). EXCEPTION : une racine fournie (depth 0) qui est elle-même un repo est aussi un
* conteneur — on l'enregistre ET on continue de descendre pour trouver les repos internes ;
* - on n'empile que les vrais sous-dossiers (`d.isDirectory()`), donc les symlinks ne sont PAS
* suivis (anti-cycle + anti-sortie de racine), et on saute dotdirs + excludeDirs ;
* - bornes : `maxDepth`, `maxRepos`, et un éventuel `signal` (timeout global) ;
* - tolérance : un `readdir` qui échoue (EACCES/ENOENT) est ignoré, le scan continue ;
* - racine inexistante/illisible : ignorée silencieusement.
* Retourne les chemins absolus dédupliqués des racines de repos, et `truncated` si une borne a coupé.
*/
export async function scanForRepos(
roots: string[],
limits: ScanLimits,
signal?: AbortSignal,
): Promise<{ paths: string[]; truncated: boolean }> {
const excludes = limits.excludeDirs ?? DEFAULT_EXCLUDE_DIRS;
const found = new Set<string>();
const seen = new Set<string>(); // ceinture-bretelles anti-cycle (chemins déjà visités)
let truncated = false;
// pile partagée entre toutes les racines : un seul plafond global maxRepos.
const stack: Frame[] = [];
for (const root of roots) stack.push({ dir: root, depth: 0 });
while (stack.length > 0) {
if (signal?.aborted || found.size >= limits.maxRepos) {
truncated = true;
break;
}
const { dir, depth } = stack.pop() as Frame;
if (seen.has(dir)) continue;
seen.add(dir);
// Un dossier avec `.git` est un repo. En PROFONDEUR (depth > 0) c'est une feuille : on
// l'enregistre sans descendre (on n'ouvre pas les sous-modules/worktrees imbriqués). Mais une
// RACINE fournie explicitement (depth 0) est un CONTENEUR de scan : si elle est elle-même un
// repo on l'enregistre, puis on CONTINUE de descendre pour découvrir les dépôts qu'elle contient.
if (existsSync(join(dir, '.git'))) {
found.add(dir);
if (depth > 0) continue;
}
if (depth >= limits.maxDepth) continue;
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
continue; // EACCES/ENOENT/… : dossier ignoré, on poursuit
}
for (const e of entries) {
if (!e.isDirectory()) continue; // symlinks non suivis (isDirectory() est false pour un lien)
if (e.name.startsWith('.') || excludes.has(e.name)) continue;
stack.push({ dir: join(dir, e.name), depth: depth + 1 });
}
}
return { paths: [...found], truncated };
}
-66
View File
@@ -1,66 +0,0 @@
// Réglages de la découverte auto des repos, persistés dans la table `settings` (clé/valeur).
// Frontière de sécurité : ces clés sont NON sensibles et n'entrent dans l'allow-list du PATCH
// /api/v1/settings que via les validateurs ci-dessous. Aucun secret ne transite par ici.
import { getSetting } from '../db/index.js';
import type { Db } from '../db/index.js';
import { isSafeAbsolutePath } from './git.js';
export const SCAN_ROOTS_KEY = 'scan_roots';
export const SCAN_INTERVAL_KEY = 'scan_interval_min';
/** Intervalle par défaut du re-scan périodique (minutes). 0 = désactivé. */
export const DEFAULT_SCAN_INTERVAL_MIN = 5;
/** Borne haute de l'intervalle (24 h) et nombre maximal de racines. */
export const MAX_SCAN_INTERVAL_MIN = 1440;
export const MAX_SCAN_ROOTS = 16;
/**
* Racines à scanner. Défaut : AUCUNE racine → aucun scan (clean install).
* L'utilisateur ajoute ses racines via Réglages → Découverte. Lecture tolérante (JSON malformé → []).
*/
export function readScanRoots(db: Db): string[] {
const raw = getSetting(db, SCAN_ROOTS_KEY);
if (!raw) return [];
return normalizeScanRoots(safeParse(raw)) ?? [];
}
/** Intervalle périodique en minutes (0 = désactivé). Défaut DEFAULT_SCAN_INTERVAL_MIN. */
export function readScanIntervalMin(db: Db): number {
const raw = getSetting(db, SCAN_INTERVAL_KEY);
if (raw === null) return DEFAULT_SCAN_INTERVAL_MIN;
const n = Number(raw);
return Number.isInteger(n) && n >= 0 && n <= MAX_SCAN_INTERVAL_MIN ? n : DEFAULT_SCAN_INTERVAL_MIN;
}
/**
* Valide/normalise une liste de racines : tableau de chemins absolus normalisés (isSafeAbsolutePath),
* jamais `/` (scan catastrophique), dédupliqués, ≤ MAX_SCAN_ROOTS. Retourne null si invalide (⇒ 400).
* Une liste vide est valide (revient au défaut côté lecture).
*/
export function normalizeScanRoots(raw: unknown): string[] | null {
if (!Array.isArray(raw)) return null;
if (raw.length > MAX_SCAN_ROOTS) return null;
const out: string[] = [];
for (const item of raw) {
if (typeof item !== 'string') return null;
const p = item.trim();
if (!isSafeAbsolutePath(p) || p === '/') return null;
if (!out.includes(p)) out.push(p);
}
return out;
}
/** Valide un intervalle (entier 0–MAX_SCAN_INTERVAL_MIN). Retourne null si invalide. */
export function normalizeScanIntervalMin(raw: unknown): number | null {
if (typeof raw !== 'number' || !Number.isInteger(raw)) return null;
if (raw < 0 || raw > MAX_SCAN_INTERVAL_MIN) return null;
return raw;
}
function safeParse(raw: string): unknown {
try {
return JSON.parse(raw);
} catch {
return null;
}
}
-45
View File
@@ -1,45 +0,0 @@
// Reconstruction d'écran via @xterm/headless : terminal headless PERSISTANT par session, alimenté
// incrémentalement par le flux PTY. Remplace le strip ANSI naïf (qui « mange les espaces » et casse
// la détection des dialogues — verdict S1/S3). Aucune dépendance DOM (usage Node).
import { createRequire } from 'node:module';
import type { Terminal as XtermTerminal } from '@xterm/headless';
// @xterm/headless est publié en CommonJS : sous Node ESM natif l'import nommé échoue
// (cjs-module-lexer ne détecte pas l'export). On charge via require, typé par l'import type.
const require = createRequire(import.meta.url);
const { Terminal } = require('@xterm/headless') as { Terminal: typeof XtermTerminal };
export class ScreenReader {
private readonly term: XtermTerminal;
constructor(cols = 120, rows = 40) {
this.term = new Terminal({ cols, rows, scrollback: 0, allowProposedApi: true });
}
/**
* Alimente le terminal avec un chunk PTY brut (la frontière UTF-8 et les séquences ANSI coupées
* sont gérées par xterm). La promesse se résout quand le chunk a été parsé (snapshot fiable ensuite).
*/
feed(chunk: Uint8Array | string): Promise<void> {
return new Promise((resolve) => this.term.write(chunk as Uint8Array, resolve));
}
resize(cols: number, rows: number): void {
this.term.resize(cols, rows);
}
/** Lignes visibles du viewport courant, espaces préservés (trim à droite uniquement). */
snapshotLines(): string[] {
const buf = this.term.buffer.active;
const lines: string[] = [];
for (let y = 0; y < this.term.rows; y++) {
const line = buf.getLine(buf.baseY + y);
lines.push(line ? line.translateToString(true) : '');
}
return lines;
}
dispose(): void {
this.term.dispose();
}
}
-69
View File
@@ -1,69 +0,0 @@
// Chiffrement au repos des secrets applicatifs (server_secret HMAC, clé privée VAPID) stockés dans
// la table `settings`. node:sqlite (DatabaseSync) ne supporte pas sqlcipher → on chiffre au niveau
// applicatif les VALEURS sensibles, en AES-256-GCM (authentifié), avant insertion.
//
// Gestion de clé (par ordre de priorité) :
// 1. ARBORETUM_SECRET_KEY (variable d'env) → vraie protection : la clé ne vit pas sur le disque,
// donc une fuite de la base seule (backup, WAL) ne révèle pas les secrets ;
// 2. sinon, fichier clé `dataDir/secret.key` (0o600), généré au 1er démarrage. Protection partielle :
// couvre la fuite de la base seule, PAS celle du dossier de données complet (clé + base ensemble).
// Compromis assumé et documenté (docs/ENTERPRISE_DEPLOYMENT.md) : pour une protection forte, fournir
// ARBORETUM_SECRET_KEY et sauvegarder cette clé séparément des backups de la base.
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto';
import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
const PREFIX = 'v1:'; // versionne le format ; absence de préfixe = valeur en clair (legacy → migration douce)
const SCRYPT_SALT = 'arboretum-secret-box-v1'; // sel fixe : l'entropie vient de la passphrase fournie
export class SecretBox {
constructor(private readonly key: Buffer) {}
/** Chiffre en `v1:<iv>:<tag>:<ciphertext>` (hex). */
encrypt(plaintext: string): string {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', this.key, iv);
const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return `${PREFIX}${iv.toString('hex')}:${tag.toString('hex')}:${ct.toString('hex')}`;
}
/** Déchiffre une valeur `v1:` ; une valeur sans préfixe est retournée telle quelle (clair legacy). */
decrypt(stored: string): string {
if (!this.isEncrypted(stored)) return stored;
const [, ivHex, tagHex, ctHex] = stored.split(':');
if (!ivHex || !tagHex || !ctHex) throw new Error('secret-box: format chiffré invalide');
const decipher = createDecipheriv('aes-256-gcm', this.key, Buffer.from(ivHex, 'hex'));
decipher.setAuthTag(Buffer.from(tagHex, 'hex'));
return Buffer.concat([decipher.update(Buffer.from(ctHex, 'hex')), decipher.final()]).toString('utf8');
}
isEncrypted(stored: string): boolean {
return stored.startsWith(PREFIX);
}
}
/**
* Construit le SecretBox de production : clé dérivée d'ARBORETUM_SECRET_KEY si fournie, sinon
* d'un fichier clé `dataDir/secret.key` (0o600) généré au besoin.
*/
export function loadSecretBox(dataDir: string): SecretBox {
const passphrase = process.env.ARBORETUM_SECRET_KEY;
if (passphrase && passphrase.length > 0) {
return new SecretBox(scryptSync(passphrase, SCRYPT_SALT, 32));
}
const keyPath = join(dataDir, 'secret.key');
let keyHex: string;
if (existsSync(keyPath)) {
keyHex = readFileSync(keyPath, 'utf8').trim();
} else {
keyHex = randomBytes(32).toString('hex');
writeFileSync(keyPath, keyHex + '\n', { mode: 0o600 });
}
try {
chmodSync(keyPath, 0o600);
} catch {
/* FS sans permissions POSIX : ignoré */
}
return new SecretBox(Buffer.from(keyHex, 'hex'));
}
@@ -1,548 +0,0 @@
// Gestion des repos enregistrés et de leurs worktrees git.
// Source de vérité des worktrees = git (dérivés à la volée + cache court par repo) ; seuls les repos
// sont persistés. Corrélation worktree ↔ sessions par cwd. Mutations sérialisées par repo.
import { EventEmitter } from 'node:events';
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { basename, dirname, join, resolve } from 'node:path';
import { existsSync } from 'node:fs';
import type {
DiscoverReposResponse,
HookRunResult,
PostCreateHook,
RepoSummary,
SessionSummary,
WorktreeBranchAction,
WorktreeBranchMode,
WorktreeGitStatus,
WorktreeSummary,
} from '@arboretum/shared';
import type { Db } from '../db/index.js';
import type { PtyManager } from './pty-manager.js';
import { DiscoveryService, mergeSessions } from './discovery-service.js';
import { scanForRepos } from './repo-scanner.js';
import { preTrustProject } from './claude-trust.js';
import {
addWorktree,
commitAll,
defaultBranch,
isDirtyWorktreeError,
isRepo,
isSafeAbsolutePath,
isValidBranchName,
listBranches,
listWorktrees,
pruneWorktrees,
push,
removeWorktree,
switchBranch,
worktreeStatus,
type ParsedWorktree,
} from './git.js';
const FACTS_TTL_MS = 2500;
const HOOK_TIMEOUT_MS = 5 * 60_000;
const HOOK_OUTPUT_MAX = 64 * 1024;
// Bornes du scan de découverte (anti-explosion sur un home volumineux).
const SCAN_MAX_DEPTH = 6;
const SCAN_MAX_REPOS = 2000;
const SCAN_TIMEOUT_MS = 30_000;
interface RepoRow {
id: string;
path: string;
label: string;
default_branch: string | null;
post_create_hooks: string;
pre_trust: number;
created_at: string;
hidden: number;
}
export interface WorktreeManagerEvents {
repo_update: [RepoSummary];
repo_removed: [string];
worktree_update: [{ repoId: string; worktree: WorktreeSummary }];
worktree_removed: [{ repoId: string; path: string }];
}
/** Erreur portant un statusCode + code pour mapping HTTP direct par les routes. */
function httpError(statusCode: number, code: string, message: string): Error {
return Object.assign(new Error(message), { statusCode, code });
}
function parseHooks(json: string): PostCreateHook[] {
try {
const arr = JSON.parse(json) as unknown;
if (!Array.isArray(arr)) return [];
return arr.filter(
(h): h is PostCreateHook =>
!!h && typeof h.id === 'string' && typeof h.label === 'string' && typeof h.run === 'string' && typeof h.enabled === 'boolean',
);
} catch {
return [];
}
}
function runHook(cwd: string, hook: PostCreateHook): Promise<HookRunResult> {
return new Promise((resolveP) => {
const t0 = Date.now();
execFile(
'bash',
['-lc', hook.run],
{ cwd, timeout: HOOK_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, env: process.env },
(err, stdout, stderr) => {
const output = `${stdout ?? ''}${stderr ?? ''}`.slice(-HOOK_OUTPUT_MAX);
const e = err as (Error & { code?: number | string }) | null;
resolveP({
hookId: hook.id,
label: hook.label,
exitCode: e ? (typeof e.code === 'number' ? e.code : 1) : 0,
output,
durationMs: Date.now() - t0,
});
},
);
});
}
export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
private readonly factsCache = new Map<string, { facts: Array<{ w: ParsedWorktree; status: WorktreeGitStatus }>; at: number }>();
private readonly locks = new Map<string, Promise<unknown>>();
/** Scan de découverte en cours : coalesce boot + bouton + périodique sur un seul scan. */
private scanInFlight: Promise<DiscoverReposResponse> | null = null;
constructor(
private readonly db: Db,
private readonly ptyManager: PtyManager,
private readonly discovery: DiscoveryService,
) {
super();
}
// ---- repos ----
private getRepoRow(id: string): RepoRow | null {
return (this.db.prepare('SELECT * FROM repos WHERE id = ?').get(id) as unknown as RepoRow | undefined) ?? null;
}
private async rowToSummary(row: RepoRow): Promise<RepoSummary> {
return {
id: row.id,
path: row.path,
label: row.label,
defaultBranch: row.default_branch,
postCreateHooks: parseHooks(row.post_create_hooks),
preTrust: row.pre_trust === 1,
createdAt: row.created_at,
valid: await isRepo(row.path),
hidden: row.hidden === 1,
};
}
async listRepos(): Promise<RepoSummary[]> {
const rows = this.db.prepare('SELECT * FROM repos ORDER BY created_at ASC').all() as unknown as RepoRow[];
return Promise.all(rows.map((r) => this.rowToSummary(r)));
}
async addRepo(opts: { path: string; label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean }): Promise<RepoSummary> {
const path = opts.path;
if (!isSafeAbsolutePath(path)) throw httpError(400, 'BAD_REQUEST', 'path must be an absolute, normalized path');
if (!(await isRepo(path))) throw httpError(400, 'NOT_A_REPO', `Not a git repository root: ${path}`);
const existing = this.db.prepare('SELECT id FROM repos WHERE path = ?').get(path) as { id: string } | undefined;
if (existing) throw httpError(409, 'ALREADY_REGISTERED', 'This repository is already registered');
const row: RepoRow = {
id: randomUUID(),
path,
label: opts.label?.trim() || basename(path),
default_branch: await defaultBranch(path),
post_create_hooks: JSON.stringify(opts.postCreateHooks ?? []),
pre_trust: opts.preTrust ? 1 : 0,
created_at: new Date().toISOString(),
hidden: 0,
};
try {
this.db
.prepare('INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at, hidden) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
.run(row.id, row.path, row.label, row.default_branch, row.post_create_hooks, row.pre_trust, row.created_at, row.hidden);
} catch (err) {
// Course possible avec un scan concurrent qui aurait inséré le même path entre le SELECT
// d'unicité et cet INSERT (contrainte UNIQUE sur path) → on rend le même 409 explicite.
if (String((err as { code?: string }).code).includes('CONSTRAINT')) {
throw httpError(409, 'ALREADY_REGISTERED', 'This repository is already registered');
}
throw err;
}
const summary = await this.rowToSummary(row);
this.emit('repo_update', summary);
return summary;
}
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean; hidden?: boolean }): Promise<RepoSummary> {
const row = this.getRepoRow(id);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
if (patch.label !== undefined) row.label = patch.label.trim() || row.label;
if (patch.postCreateHooks !== undefined) row.post_create_hooks = JSON.stringify(patch.postCreateHooks);
if (patch.preTrust !== undefined) row.pre_trust = patch.preTrust ? 1 : 0;
if (patch.hidden !== undefined) row.hidden = patch.hidden ? 1 : 0;
this.db
.prepare('UPDATE repos SET label = ?, post_create_hooks = ?, pre_trust = ?, hidden = ? WHERE id = ?')
.run(row.label, row.post_create_hooks, row.pre_trust, row.hidden, id);
const summary = await this.rowToSummary(row);
this.emit('repo_update', summary);
return summary;
}
removeRepo(id: string): boolean {
const res = this.db.prepare('DELETE FROM repos WHERE id = ?').run(id);
if (res.changes === 0) return false;
this.factsCache.delete(id);
this.emit('repo_removed', id);
return true;
}
/**
* Découvre les repos git sous `roots` et auto-enregistre les NOUVEAUX (path absent de la DB).
* Idempotent et anti-résurrection : un path déjà présent — visible OU masqué — n'est jamais
* réécrit (INSERT ... ON CONFLICT DO NOTHING). Les scans concurrents sont coalescés. Tolérant :
* ne lève pas (le scanner avale les erreurs FS). N'appelle aucun git pendant le scan
* (default_branch=NULL, résolu paresseusement par rowToSummary à l'affichage).
*/
discoverRepos(opts: { roots: string[]; maxDepth?: number; maxRepos?: number }): Promise<DiscoverReposResponse> {
if (this.scanInFlight) return this.scanInFlight;
this.scanInFlight = this.runDiscovery(opts).finally(() => {
this.scanInFlight = null;
});
return this.scanInFlight;
}
private async runDiscovery(opts: { roots: string[]; maxDepth?: number; maxRepos?: number }): Promise<DiscoverReposResponse> {
const t0 = Date.now();
const { paths, truncated } = await scanForRepos(
opts.roots,
{ maxDepth: opts.maxDepth ?? SCAN_MAX_DEPTH, maxRepos: opts.maxRepos ?? SCAN_MAX_REPOS },
AbortSignal.timeout(SCAN_TIMEOUT_MS),
);
const insert = this.db.prepare(
`INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at, hidden)
VALUES (?, ?, ?, NULL, '[]', 0, ?, 0) ON CONFLICT(path) DO NOTHING`,
);
let added = 0;
for (const path of paths) {
const row: RepoRow = {
id: randomUUID(),
path,
label: basename(path),
default_branch: null,
post_create_hooks: '[]',
pre_trust: 0,
created_at: new Date().toISOString(),
hidden: 0,
};
const res = insert.run(row.id, row.path, row.label, row.created_at);
if (res.changes === 1) {
added++;
this.emit('repo_update', await this.rowToSummary(row)); // nouveaux uniquement
}
}
return { scanned: paths.length, added, durationMs: Date.now() - t0, truncated };
}
// ---- worktrees ----
/**
* Sessions (managées + découvertes) dont le cwd correspond à ce chemin de worktree.
* Les sessions explicitement masquées (`hidden`) sont exclues — cohérent avec `/api/v1/sessions`
* (sans quoi le masquage était ignoré dans les fiches worktree). Le tri managées/externes est laissé
* au client (interrupteur « afficher les externes »), qui dispose du champ `source`. La garde de
* suppression réclame en revanche TOUTES les sessions vivantes (`includeHidden`) pour rester sûre.
*/
private sessionsForCwd(path: string, opts?: { includeHidden?: boolean }): SessionSummary[] {
const rp = resolve(path);
return mergeSessions(this.ptyManager.list(), this.discovery.list())
.filter((s) => resolve(s.cwd) === rp)
.filter((s) => opts?.includeHidden || !s.hidden);
}
private toSummary(repoId: string, repoPath: string, w: ParsedWorktree, status: WorktreeGitStatus): WorktreeSummary {
return {
repoId,
path: w.path,
branch: w.branch,
head: w.head ?? '',
detached: w.detached,
locked: w.locked,
prunable: w.prunable,
isMain: resolve(w.path) === resolve(repoPath),
git: status,
sessions: this.sessionsForCwd(w.path),
};
}
private async repoFacts(row: RepoRow, noCache = false): Promise<Array<{ w: ParsedWorktree; status: WorktreeGitStatus }>> {
const cached = this.factsCache.get(row.id);
if (!noCache && cached && Date.now() - cached.at < FACTS_TTL_MS) return cached.facts;
const parsed = (await listWorktrees(row.path)).filter((w) => !w.bare);
const facts = await Promise.all(parsed.map(async (w) => ({ w, status: await worktreeStatus(w.path) })));
this.factsCache.set(row.id, { facts, at: Date.now() });
return facts;
}
async listRepoWorktrees(repoId: string, noCache = false): Promise<WorktreeSummary[]> {
const row = this.getRepoRow(repoId);
if (!row) return [];
const facts = await this.repoFacts(row, noCache);
return facts.map(({ w, status }) => this.toSummary(row.id, row.path, w, status));
}
async listAllWorktrees(): Promise<WorktreeSummary[]> {
// Les repos masqués sont exclus du dashboard : inutile de calculer leurs worktrees (sous-process
// git par repo). Le front charge paresseusement ceux d'un repo masqué via listRepoWorktrees
// quand l'utilisateur active « afficher les masqués ».
const rows = this.db.prepare('SELECT id FROM repos WHERE hidden = 0 ORDER BY created_at ASC').all() as Array<{ id: string }>;
// Tolérance par repo : avec la découverte auto, un repo douteux (git en échec, chemin disparu,
// permission) ne doit JAMAIS faire planter tout l'endpoint — il ne contribue alors aucun worktree.
const lists = await Promise.all(rows.map((r) => this.listRepoWorktrees(r.id).catch(() => [])));
return lists.flat();
}
/** Sérialise les mutations d'un même repo (évite les courses sur .git/worktrees). */
private withLock<T>(repoId: string, fn: () => Promise<T>): Promise<T> {
const prev = this.locks.get(repoId) ?? Promise.resolve();
const next = prev.then(fn, fn);
this.locks.set(
repoId,
next.then(
() => undefined,
() => undefined,
),
);
return next;
}
private async findWorktree(row: RepoRow, path: string): Promise<ParsedWorktree | null> {
const rp = resolve(path);
return (await listWorktrees(row.path)).find((w) => resolve(w.path) === rp) ?? null;
}
private async emitWorktree(row: RepoRow, path: string): Promise<WorktreeSummary | null> {
const w = await this.findWorktree(row, path);
if (!w) return null;
const summary = this.toSummary(row.id, row.path, w, await worktreeStatus(w.path));
this.emit('worktree_update', { repoId: row.id, worktree: summary });
return summary;
}
async createWorktree(
repoId: string,
req: { branch: string; mode?: WorktreeBranchMode; baseRef?: string; path?: string; runHooks?: boolean; preTrust?: boolean; startSession?: 'claude' | 'bash' | null },
): Promise<{ worktree: WorktreeSummary; hookResults: HookRunResult[]; session: SessionSummary | null; action: WorktreeBranchAction }> {
const row = this.getRepoRow(repoId);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
if (!isValidBranchName(req.branch)) throw httpError(400, 'BAD_BRANCH', `Invalid branch name: ${req.branch}`);
const path = req.path ?? join(dirname(row.path), `${basename(row.path)}-wt-${req.branch.replace(/\//g, '-')}`);
if (!isSafeAbsolutePath(path)) throw httpError(400, 'BAD_PATH', 'Worktree path must be absolute and normalized');
if (existsSync(path)) throw httpError(409, 'PATH_EXISTS', `Path already exists: ${path}`);
return this.withLock(repoId, async () => {
let action: WorktreeBranchAction;
try {
action = await addWorktree(row.path, { path, branch: req.branch, mode: req.mode ?? 'auto', ...(req.baseRef ? { baseRef: req.baseRef } : {}) });
} catch (err) {
throw httpError(400, 'WORKTREE_ADD_FAILED', (err as Error).message);
}
this.factsCache.delete(repoId);
if (req.preTrust ?? row.pre_trust === 1) preTrustProject(path);
const hookResults: HookRunResult[] = [];
if (req.runHooks ?? true) {
for (const hook of parseHooks(row.post_create_hooks)) {
if (hook.enabled) hookResults.push(await runHook(path, hook));
}
}
let session: SessionSummary | null = null;
if (req.startSession) session = this.ptyManager.spawn({ cwd: path, command: req.startSession });
const worktree = (await this.emitWorktree(row, path)) ?? this.toSummary(row.id, row.path, { path, head: null, branch: req.branch, detached: false, locked: false, prunable: false, bare: false }, { ahead: 0, behind: 0, dirtyCount: 0, upstream: null });
return { worktree, hookResults, session, action };
});
}
/** Branches locales/remote + branche par défaut d'un repo — alimente le sélecteur de base côté UI. */
async listRepoBranches(repoId: string): Promise<{ local: string[]; remote: string[]; default: string | null }> {
const row = this.getRepoRow(repoId);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
return listBranches(row.path);
}
/** `git add -A` + commit dans le worktree visé (le checkout principal est un worktree valide ici). */
async commitWorktree(repoId: string, path: string, message: string): Promise<WorktreeSummary> {
const row = this.getRepoRow(repoId);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
const w = await this.findWorktree(row, path);
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
return this.withLock(repoId, async () => {
if ((await worktreeStatus(w.path)).dirtyCount === 0) {
throw httpError(409, 'NOTHING_TO_COMMIT', 'Nothing to commit — working tree is clean');
}
try {
await commitAll(w.path, message);
} catch (err) {
throw httpError(400, 'COMMIT_FAILED', (err as Error).message);
}
this.factsCache.delete(repoId);
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
});
}
/** Pousse la branche du worktree visé (upstream auto si absent). */
async pushWorktree(repoId: string, path: string): Promise<WorktreeSummary> {
const row = this.getRepoRow(repoId);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
const w = await this.findWorktree(row, path);
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
return this.withLock(repoId, async () => {
try {
await push(w.path);
} catch (err) {
throw httpError(400, 'PUSH_FAILED', (err as Error).message);
}
this.factsCache.delete(repoId);
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
});
}
/**
* « Passer en principal » : la branche du worktree devient le checkout principal du dépôt. Une branche
* ne pouvant être extraite qu'à un seul endroit, on retire d'abord le worktree (libère la branche) puis
* on bascule le checkout principal dessus. Sans merge ni conflit possible. L'ancienne branche principale
* est conservée (jamais supprimée). Garde-fous d'arbre sale outrepassables par `force`.
*/
async promoteWorktree(repoId: string, path: string, force = false): Promise<WorktreeSummary | null> {
const row = this.getRepoRow(repoId);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
const w = await this.findWorktree(row, path);
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
if (resolve(w.path) === resolve(row.path)) throw httpError(400, 'IS_MAIN_WORKTREE', 'This is already the main checkout');
if (!w.branch || w.detached) throw httpError(400, 'DETACHED_WORKTREE', 'Worktree has no branch to promote (detached HEAD)');
const branch = w.branch;
return this.withLock(repoId, async () => {
if (!force) {
if ((await worktreeStatus(w.path)).dirtyCount > 0) {
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes — commit or pass force');
}
if ((await worktreeStatus(row.path)).dirtyCount > 0) {
throw httpError(409, 'DIRTY_TREE', 'Main checkout has uncommitted changes — commit/stash or pass force');
}
}
try {
await removeWorktree(row.path, w.path, force);
} catch (err) {
if (!force && isDirtyWorktreeError(err)) {
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes — pass force to promote anyway');
}
throw httpError(500, 'WORKTREE_REMOVE_FAILED', (err as Error).message);
}
try {
await switchBranch(row.path, { branch, create: false });
} catch (err) {
throw httpError(500, 'SWITCH_FAILED', (err as Error).message);
}
this.factsCache.delete(repoId);
this.emit('worktree_removed', { repoId, path: w.path });
return this.emitWorktree(row, row.path); // le checkout principal est désormais sur `branch`
});
}
/**
* Lance UNE session dans le checkout principal du repo (`repo.path`) — pour « bosser sur la branche
* principale » sans créer de worktree. Si `branch` est fourni, crée/bascule d'abord cette branche
* dans ce checkout (`git switch[-c]`), refusé si l'arbre est sale (on n'écrase pas un HEAD modifié).
* Volontairement SANS hooks ni pré-trust (contraste avec createWorktree) : le checkout principal
* est le dépôt réel de l'utilisateur, déjà configuré/approuvé. Sérialisé par repo (withLock).
*/
async startMainSession(
repoId: string,
req: { command?: 'claude' | 'bash'; branch?: string; newBranch?: boolean },
): Promise<{ session: SessionSummary; worktree: WorktreeSummary | null }> {
const row = this.getRepoRow(repoId);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
const branch = req.branch?.trim() || undefined;
if (branch !== undefined && !isValidBranchName(branch)) throw httpError(400, 'BAD_BRANCH', `Invalid branch name: ${branch}`);
return this.withLock(repoId, async () => {
if (branch !== undefined) {
// garde-fou : ne pas basculer le HEAD du checkout principal s'il a des changements non sauvegardés.
if ((await worktreeStatus(row.path)).dirtyCount > 0) {
throw httpError(409, 'DIRTY_TREE', 'Main checkout has uncommitted changes — commit or stash before switching branch');
}
try {
await switchBranch(row.path, { branch, create: req.newBranch ?? true });
} catch (err) {
throw httpError(400, 'SWITCH_FAILED', (err as Error).message);
}
this.factsCache.delete(repoId);
}
const session = this.ptyManager.spawn({ cwd: row.path, command: req.command ?? 'claude' });
const worktree = await this.emitWorktree(row, row.path);
return { session, worktree };
});
}
async adoptWorktree(repoId: string, req: { path: string; runHooks?: boolean; preTrust?: boolean }): Promise<{ worktree: WorktreeSummary; hookResults: HookRunResult[] }> {
const row = this.getRepoRow(repoId);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
const w = await this.findWorktree(row, req.path);
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
if (req.preTrust ?? row.pre_trust === 1) preTrustProject(w.path);
const hookResults: HookRunResult[] = [];
if (req.runHooks) {
for (const hook of parseHooks(row.post_create_hooks)) {
if (hook.enabled) hookResults.push(await runHook(w.path, hook));
}
}
const worktree = (await this.emitWorktree(row, w.path)) as WorktreeSummary;
return { worktree, hookResults };
}
async deleteWorktree(repoId: string, path: string, force: boolean): Promise<void> {
const row = this.getRepoRow(repoId);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
const w = await this.findWorktree(row, path);
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
if (resolve(w.path) === resolve(row.path)) throw httpError(400, 'IS_MAIN_WORKTREE', 'Cannot remove the main worktree');
// garde-fou : une session vivante tourne dans ce worktree → exiger une confirmation explicite.
if (!force && this.sessionsForCwd(w.path, { includeHidden: true }).some((s) => s.live)) {
throw httpError(409, 'SESSION_LIVE_IN_WORKTREE', 'A live session runs in this worktree — pass force to delete anyway');
}
return this.withLock(repoId, async () => {
try {
await removeWorktree(row.path, w.path, force);
} catch (err) {
if (!force && isDirtyWorktreeError(err)) {
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes — pass force to delete anyway');
}
throw httpError(500, 'WORKTREE_REMOVE_FAILED', (err as Error).message);
}
this.factsCache.delete(repoId);
this.emit('worktree_removed', { repoId, path: w.path });
});
}
async prune(repoId: string): Promise<void> {
const row = this.getRepoRow(repoId);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
return this.withLock(repoId, async () => {
const before = await listWorktrees(row.path);
await pruneWorktrees(row.path);
this.factsCache.delete(repoId);
const after = new Set((await listWorktrees(row.path)).map((w) => resolve(w.path)));
for (const w of before) {
if (!after.has(resolve(w.path))) this.emit('worktree_removed', { repoId, path: w.path });
}
});
}
}
-143
View File
@@ -1,5 +1,4 @@
import { DatabaseSync } from 'node:sqlite';
import { chmodSync, existsSync } from 'node:fs';
const MIGRATIONS: Array<{ id: number; sql: string }> = [
{
@@ -37,111 +36,6 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
CREATE INDEX idx_sessions_claude_session_id ON sessions(claude_session_id);
`,
},
{
// P3 — repos enregistrés. Les worktrees sont dérivés à la volée de git (non persistés).
id: 3,
sql: `
CREATE TABLE repos (
id TEXT PRIMARY KEY,
path TEXT NOT NULL UNIQUE,
label TEXT NOT NULL,
default_branch TEXT,
post_create_hooks TEXT NOT NULL DEFAULT '[]',
pre_trust INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL
);
`,
},
{
// P4 — abonnements Web Push. Liés au token d'auth (token_id) ; clés VAPID en settings.
id: 4,
sql: `
CREATE TABLE push_subscriptions (
id TEXT PRIMARY KEY,
token_id TEXT NOT NULL,
endpoint TEXT NOT NULL UNIQUE,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
user_agent TEXT,
created_at TEXT NOT NULL,
last_ok_at TEXT
);
CREATE INDEX idx_push_subs_token ON push_subscriptions(token_id);
`,
},
{
// P5 — groupes de travail. Un groupe = collection de repos (many-to-many).
// Worktrees/sessions NON persistés ici : servis par WorktreeManager/PtyManager
// et filtrés côté client par repoId. CASCADE s'appuie sur PRAGMA foreign_keys = ON (cf. openDb).
id: 5,
sql: `
CREATE TABLE groups (
id TEXT PRIMARY KEY,
label TEXT NOT NULL,
description TEXT,
color TEXT,
position INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE group_repos (
group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
position INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
PRIMARY KEY (group_id, repo_id)
);
CREATE INDEX idx_group_repos_repo ON group_repos(repo_id);
`,
},
{
// Découverte auto : un repo masqué reste en DB (exclu du dashboard) pour qu'un
// re-scan ne le ressuscite pas. hidden=1 = masqué.
id: 6,
sql: `ALTER TABLE repos ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0;`,
},
{
// Journal d'audit (conformité entreprise : GDPR/SOX/ISO 27001). Trace les mutations
// sensibles (tokens, réglages, secrets, abonnements push, groupes). Ne contient JAMAIS
// de secret en clair — `details` est un JSON de métadonnées non sensibles.
id: 7,
sql: `
CREATE TABLE audit_logs (
id TEXT PRIMARY KEY,
ts TEXT NOT NULL,
actor TEXT NOT NULL,
action TEXT NOT NULL,
resource_id TEXT,
details TEXT,
result TEXT NOT NULL
);
CREATE INDEX idx_audit_ts ON audit_logs(ts);
`,
},
{
// P6 — session de groupe multi-repo. Une session peut couvrir plusieurs répertoires (--add-dir)
// et appartenir à un groupe. `added_dirs` : JSON array de chemins absolus (NULL si mono-repo).
// `group_id` : pas de FK (ALTER ADD COLUMN sqlite n'en pose pas) ; nettoyé à la suppression du groupe.
id: 8,
sql: `
ALTER TABLE sessions ADD COLUMN added_dirs TEXT;
ALTER TABLE sessions ADD COLUMN group_id TEXT;
CREATE INDEX idx_sessions_group_id ON sessions(group_id);
`,
},
{
// Masquage des sessions Claude découvertes (lancées en CLI hors Arboretum) qui polluent la liste.
// Calqué sur repos.hidden (#6) : la session masquée reste connue (resume/fork possibles) mais est
// exclue de la liste par défaut, et un re-scan ne la ressuscite pas. Clé = claudeSessionId (stable,
// partagé entre une découverte et sa reprise managée).
id: 9,
sql: `
CREATE TABLE hidden_sessions (
claude_session_id TEXT PRIMARY KEY,
hidden_at TEXT NOT NULL
);
`,
},
];
export type Db = DatabaseSync;
@@ -150,27 +44,10 @@ export function openDb(path: string): Db {
const db = new DatabaseSync(path);
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
hardenDbPermissions(path);
migrate(db);
return db;
}
/**
* Restreint la base (et ses fichiers WAL/SHM) à 0o600 — proprio uniquement. La base contient des
* secrets (server_secret, clé privée VAPID, hashs de tokens) : elle ne doit jamais être lisible par
* d'autres utilisateurs du système. Best-effort : ignoré sur les FS sans permissions POSIX.
*/
function hardenDbPermissions(path: string): void {
if (path === ':memory:') return;
for (const p of [path, `${path}-wal`, `${path}-shm`]) {
try {
if (existsSync(p)) chmodSync(p, 0o600);
} catch {
/* FS sans permissions POSIX (Windows / montage) : ignoré */
}
}
}
function migrate(db: DatabaseSync): void {
db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (id INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)');
const applied = new Set(
@@ -198,23 +75,3 @@ export function getSetting(db: Db, key: string): string | null {
export function setSetting(db: Db, key: string, value: string): void {
db.prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value);
}
// ---- Sessions masquées (par claudeSessionId) ----
/** Ensemble des claudeSessionId masqués par l'utilisateur. */
export function listHiddenSessionIds(db: Db): Set<string> {
const rows = db.prepare('SELECT claude_session_id FROM hidden_sessions').all() as Array<{ claude_session_id: string }>;
return new Set(rows.map((r) => r.claude_session_id));
}
/** Masque une session (idempotent). */
export function hideSession(db: Db, claudeSessionId: string): void {
db.prepare(
'INSERT INTO hidden_sessions (claude_session_id, hidden_at) VALUES (?, ?) ON CONFLICT(claude_session_id) DO NOTHING',
).run(claudeSessionId, new Date().toISOString());
}
/** Ré-affiche une session masquée (idempotent). */
export function unhideSession(db: Db, claudeSessionId: string): void {
db.prepare('DELETE FROM hidden_sessions WHERE claude_session_id = ?').run(claudeSessionId);
}
+9 -38
View File
@@ -2,30 +2,32 @@
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadConfig, type Config } from './config.js';
import { loadConfig } from './config.js';
import { openDb } from './db/index.js';
import { buildApp } from './app.js';
import { runInstall, runUninstall, runStatus, printUsage, printTokenBanner } from './cli/install.js';
const pkg = JSON.parse(
readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8'),
) as { version: string };
/** Démarre le daemon : écoute HTTP, scan des sessions, drain propre au SIGTERM/SIGINT. */
export async function runDaemon(config: Config): Promise<void> {
async function main(): Promise<void> {
const config = loadConfig();
const db = openDb(config.dbPath);
const { app, auth, manager, discovery, repoDiscovery } = buildApp(config, db, pkg.version);
const { app, auth, manager, discovery } = buildApp(config, db, pkg.version);
const bootstrapToken = auth.ensureBootstrapToken();
await app.listen({ port: config.port, host: config.bind });
discovery.start(); // scan initial + rafraîchissement périodique des sessions découvertes
if (config.autoDiscover) repoDiscovery.start(); // découverte auto des repos : scan au boot + re-scan périodique
const url = `http://${config.bind === '0.0.0.0' ? '127.0.0.1' : config.bind}:${config.port}`;
app.log.info(`Arboretum v${pkg.version} — ${url}`);
if (bootstrapToken) {
// Affiché une seule fois : le hash seul est stocké.
printTokenBanner(bootstrapToken, url);
console.log('\n┌──────────────────────────────────────────────────────────────────┐');
console.log('│ First start — your access token (shown once, store it safely): │');
console.log('└──────────────────────────────────────────────────────────────────┘');
console.log(`\n ${bootstrapToken}\n`);
console.log(` Login at: ${url}/\n`);
} else if (config.printToken) {
console.log('Tokens are stored hashed and cannot be re-printed. Create a new one from Settings (or reset the db).');
}
@@ -36,7 +38,6 @@ export async function runDaemon(config: Config): Promise<void> {
shuttingDown = true;
app.log.info(`${signal} received — draining sessions then exiting`);
discovery.stop();
repoDiscovery.stop();
manager.shutdown();
setTimeout(() => {
void app.close().then(() => process.exit(0));
@@ -46,36 +47,6 @@ export async function runDaemon(config: Config): Promise<void> {
process.on('SIGTERM', () => shutdown('SIGTERM'));
}
// Routeur de sous-commandes. On inspecte argv[0] AVANT loadConfig (parseArgs strict throw sur
// un positionnel inconnu). Aucune sous-commande (ou un flag en tête) → daemon : rétrocompat stricte
// de `arboretum`, `arboretum --port 8080`, `npx @johanleroy/git-arboretum --allow-origin …`.
async function main(): Promise<void> {
const argv = process.argv.slice(2);
const cmd = argv[0];
switch (cmd) {
case 'install':
return runInstall(argv.slice(1));
case 'uninstall':
return runUninstall(argv.slice(1));
case 'status':
return runStatus(argv.slice(1));
case 'serve':
return runDaemon(loadConfig(argv.slice(1)));
case 'help':
case '--help':
case '-h':
printUsage(pkg.version);
return;
default:
if (cmd && !cmd.startsWith('-')) {
console.error(`Unknown command: ${cmd}\n`);
printUsage(pkg.version);
process.exit(1);
}
return runDaemon(loadConfig(argv));
}
}
main().catch((err) => {
console.error(err instanceof Error ? err.message : err);
process.exit(1);
-17
View File
@@ -1,17 +0,0 @@
// Consultation du journal d'audit (onglet Réglages / outils de conformité). Lecture seule, sous
// l'auth globale. Pagination par curseur `before` (ts décroissant).
import type { FastifyInstance } from 'fastify';
import type { AuditLogsResponse } from '@arboretum/shared';
import type { Db } from '../db/index.js';
import { listAudit } from '../core/audit-log.js';
export function registerAuditRoutes(app: FastifyInstance, db: Db): void {
app.get('/api/v1/audit-logs', async (req): Promise<AuditLogsResponse> => {
const q = req.query as { limit?: string; before?: string };
const limit = Math.min(Math.max(Math.trunc(Number(q.limit) || 50), 1), 200);
const entries = listAudit(db, { limit, before: q.before ?? null });
// s'il reste potentiellement des entrées (page pleine), expose le curseur suivant.
const nextBefore = entries.length === limit ? entries[entries.length - 1]!.ts : null;
return { entries, nextBefore };
});
}
+5 -68
View File
@@ -1,31 +1,12 @@
import type { FastifyInstance, FastifyRequest } from 'fastify';
import type {
CreateTokenRequest,
CreateTokenResponse,
LoginRequest,
LoginResponse,
MeResponse,
TokensListResponse,
} from '@arboretum/shared';
import type { FastifyInstance } from 'fastify';
import type { LoginRequest, LoginResponse, MeResponse } from '@arboretum/shared';
import type { AuthService, LoginRateLimiter } from '../auth/service.js';
import type { Db } from '../db/index.js';
import { recordAudit } from '../core/audit-log.js';
// Tailscale Serve / un reverse-proxy TLS posent x-forwarded-proto. On ne sert jamais
// en TLS direct : `secure` n'est posé que derrière un front HTTPS, jamais en localhost http
// (sinon le navigateur refuserait le cookie sur http://127.0.0.1 et le login local casserait).
export function isHttpsRequest(req: FastifyRequest): boolean {
const xfp = req.headers['x-forwarded-proto'];
const proto = (Array.isArray(xfp) ? xfp[0] : xfp)?.split(',')[0]?.trim();
return proto === 'https';
}
export function registerAuthRoutes(
app: FastifyInstance,
auth: AuthService,
limiter: LoginRateLimiter,
serverVersion: string,
db: Db,
): void {
app.post('/api/v1/auth/login', { config: { public: true } }, async (req, reply) => {
const wait = limiter.check();
@@ -36,16 +17,13 @@ export function registerAuthRoutes(
const ctx = typeof body?.token === 'string' ? auth.verifyRawToken(body.token) : null;
if (!ctx) {
limiter.recordFailure();
recordAudit(db, { actor: 'anonymous', action: 'login.failure', result: 'denied' });
return reply.status(401).send({ error: { code: 'BAD_TOKEN', message: 'Invalid token' } });
}
limiter.recordSuccess();
recordAudit(db, { actor: ctx.tokenId, action: 'login.success' });
void reply.setCookie(auth.cookieName, auth.issueCookie(ctx), {
path: '/',
httpOnly: true,
sameSite: 'strict',
secure: isHttpsRequest(req),
maxAge: 30 * 24 * 3600,
});
const res: LoginResponse = { ok: true, label: ctx.label };
@@ -53,53 +31,12 @@ export function registerAuthRoutes(
});
app.get('/api/v1/auth/me', async (req, reply) => {
const res: MeResponse = {
ok: true,
tokenId: req.authContext?.tokenId ?? '',
tokenLabel: req.authContext?.label ?? 'unknown',
serverVersion,
};
const res: MeResponse = { ok: true, tokenLabel: req.authContext?.label ?? 'unknown', serverVersion };
return reply.send(res);
});
app.post('/api/v1/auth/logout', async (req, reply) => {
// Les attributs doivent matcher ceux posés au login pour que le navigateur efface bien le cookie.
void reply.clearCookie(auth.cookieName, { path: '/', secure: isHttpsRequest(req) });
return reply.send({ ok: true });
});
// ---- Gestion des tokens d'accès (onglet Réglages) ----
// Sous l'auth globale (preValidation). On ne renvoie jamais le hash ; la valeur en clair
// d'un nouveau token n'est exposée qu'une seule fois, à la création.
app.get('/api/v1/auth/tokens', async (req): Promise<TokensListResponse> => {
const current = req.authContext?.tokenId;
return { tokens: auth.listTokens().map((t) => ({ ...t, current: t.id === current })) };
});
app.post('/api/v1/auth/tokens', async (req, reply) => {
const body = req.body as Partial<CreateTokenRequest> | null;
const label = typeof body?.label === 'string' ? body.label.trim() : '';
if (label.length < 1 || label.length > 64) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'label must be 1–64 characters' } });
}
const { id, token } = auth.createTokenRecord(label);
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'token.create', resourceId: id, details: { label } });
return reply.status(201).send({ id, label, token } satisfies CreateTokenResponse);
});
app.delete('/api/v1/auth/tokens/:id', async (req, reply) => {
const { id } = req.params as { id: string };
const result = auth.revokeToken(id);
const actor = req.authContext?.tokenId ?? 'unknown';
if (result === 'not_found') {
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No active token with this id' } });
}
if (result === 'last') {
recordAudit(db, { actor, action: 'token.revoke', resourceId: id, result: 'denied', details: { reason: 'last_active_token' } });
return reply.status(409).send({ error: { code: 'LAST_TOKEN', message: 'Cannot revoke the last active token' } });
}
recordAudit(db, { actor, action: 'token.revoke', resourceId: id });
// 200 + corps JSON (pas 204) : le mini-client REST du front parse toujours la réponse.
app.post('/api/v1/auth/logout', async (_req, reply) => {
void reply.clearCookie(auth.cookieName, { path: '/' });
return reply.send({ ok: true });
});
}
-54
View File
@@ -1,54 +0,0 @@
// RGPD (droits d'accès & d'effacement) : export et suppression des données rattachées au token
// authentifié. Modèle mono-utilisateur → le détenteur du token EST le sujet des données. Sous l'auth
// globale. La suppression se fait en deux temps (code de confirmation) pour éviter les clics accidentels.
import { createHash } from 'node:crypto';
import type { FastifyInstance } from 'fastify';
import type { DataExportResponse, DeleteMyDataRequest, DeleteMyDataResponse } from '@arboretum/shared';
import type { Db } from '../db/index.js';
import type { AuthService } from '../auth/service.js';
import { readScanIntervalMin, readScanRoots } from '../core/scan-settings.js';
import { recordAudit } from '../core/audit-log.js';
export function registerDataRoutes(app: FastifyInstance, db: Db, auth: AuthService): void {
app.get('/api/v1/data/export', async (req): Promise<DataExportResponse> => {
const current = req.authContext!.tokenId;
const tokens = auth.listTokens().map((t) => ({ ...t, current: t.id === current }));
const pushSubscriptions = db
.prepare(
'SELECT endpoint, user_agent AS userAgent, created_at AS createdAt, last_ok_at AS lastOkAt FROM push_subscriptions WHERE token_id = ?',
)
.all(current) as DataExportResponse['pushSubscriptions'];
const sessions = db
.prepare(
'SELECT id, cwd, command, title, created_at AS createdAt, ended_at AS endedAt, exit_code AS exitCode FROM sessions ORDER BY created_at',
)
.all() as DataExportResponse['sessions'];
return {
exportedAt: new Date().toISOString(),
tokens,
pushSubscriptions,
sessions,
settings: { scanRoots: readScanRoots(db), scanIntervalMin: readScanIntervalMin(db) },
};
});
app.post('/api/v1/data/delete-my-data', async (req, reply) => {
const current = req.authContext!.tokenId;
// code déterministe lié au token (sans état serveur) : renvoyé au 1er appel, exigé au 2nd.
const code = createHash('sha256').update(`delete:${current}`).digest('hex').slice(0, 12);
const body = (req.body as DeleteMyDataRequest | null) ?? {};
const subsCount = (db.prepare('SELECT COUNT(*) AS n FROM push_subscriptions WHERE token_id = ?').get(current) as { n: number }).n;
if (body.confirm !== code) {
const res: DeleteMyDataResponse = { status: 'pending', confirm: code, summary: { pushSubscriptions: subsCount, tokenRevoked: false } };
return reply.send(res);
}
db.prepare('DELETE FROM push_subscriptions WHERE token_id = ?').run(current);
// révoque le token courant (sauf si c'est le dernier actif → garde anti lock-out conservée).
const revoked = auth.revokeToken(current) === 'ok';
recordAudit(db, { actor: current, action: 'data.delete', details: { pushSubscriptions: subsCount, tokenRevoked: revoked } });
const res: DeleteMyDataResponse = { status: 'done', summary: { pushSubscriptions: subsCount, tokenRevoked: revoked } };
return reply.send(res);
});
}
-82
View File
@@ -1,82 +0,0 @@
import type { FastifyInstance } from 'fastify';
import { readdir, stat } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, dirname, resolve } from 'node:path';
import type { FsEntry, FsListResponse } from '@arboretum/shared';
/**
* Navigation du système de fichiers pour le sélecteur de dossier côté web.
* Ne renvoie QUE des noms de sous-dossiers (jamais de contenu de fichier) ; authentifié
* par le hook preValidation global comme tout /api/**. Un utilisateur authentifié dispose
* déjà d'un terminal (RCE par conception) : lister des dossiers n'élargit pas le modèle de menace.
*
* GET /api/v1/fs/list?path=<abs>&markRepos=1&showHidden=1
* - path absent → home de l'utilisateur
* - markRepos → annote les sous-dossiers qui sont des dépôts git (présence d'un `.git`)
* - showHidden → inclut les dotfiles (masqués par défaut)
*/
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 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' } });
}
// resolve() normalise et clampe à la racine : aucun échappement d'arborescence via `..`.
const abs = resolve(raw);
let st;
try {
st = await stat(abs);
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code === 'ENOENT') return reply.status(404).send({ error: { code: 'NOT_FOUND', message: `No such directory: ${abs}` } });
if (code === 'EACCES') return reply.status(403).send({ error: { code: 'FORBIDDEN', message: `Permission denied: ${abs}` } });
return reply.status(400).send({ error: { code: 'BAD_PATH', message: (err as Error).message } });
}
if (!st.isDirectory()) {
return reply.status(400).send({ error: { code: 'NOT_A_DIRECTORY', message: `Not a directory: ${abs}` } });
}
const markRepos = q.markRepos === '1' || q.markRepos === 'true';
const showHidden = q.showHidden === '1' || q.showHidden === 'true';
let dirents;
try {
dirents = await readdir(abs, { withFileTypes: true });
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code === 'EACCES') return reply.status(403).send({ error: { code: 'FORBIDDEN', message: `Permission denied: ${abs}` } });
return reply.status(400).send({ error: { code: 'BAD_PATH', message: (err as Error).message } });
}
const entries: FsEntry[] = [];
for (const d of dirents) {
if (!showHidden && d.name.startsWith('.')) continue;
let isDir = d.isDirectory();
// symlink éventuel vers un dossier : résolu par stat (tolérant aux liens cassés).
if (!isDir && d.isSymbolicLink()) {
try {
isDir = (await stat(join(abs, d.name))).isDirectory();
} catch {
isDir = false;
}
}
if (!isDir) continue;
const full = join(abs, d.name);
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()));
const res: FsListResponse = {
path: abs,
parent: abs === '/' ? null : dirname(abs),
home: homedir(),
entries,
};
return reply.send(res);
});
}
-162
View File
@@ -1,162 +0,0 @@
import type { FastifyInstance } from 'fastify';
import type {
AddRepoRequest,
CreateGroupRequest,
CreateGroupSessionRequest,
GroupResponse,
GroupSessionResponse,
GroupsListResponse,
UpdateGroupRequest,
} from '@arboretum/shared';
import type { GroupManager } from '../core/group-manager.js';
import type { WorktreeManager } from '../core/worktree-manager.js';
import type { PtyManager } from '../core/pty-manager.js';
import type { Db } from '../db/index.js';
import { recordAudit } from '../core/audit-log.js';
import { resolveGroupCwd } from '../core/group-session.js';
import { sendManagerError } from './repos.js';
export function registerGroupRoutes(
app: FastifyInstance,
gm: GroupManager,
db: Db,
wt: WorktreeManager,
manager: PtyManager,
): void {
app.get('/api/v1/groups', async (): Promise<GroupsListResponse> => ({ groups: gm.listGroups() }));
app.get('/api/v1/groups/:id', async (req, reply) => {
const { id } = req.params as { id: string };
try {
return reply.send({ group: gm.getGroup(id) } satisfies GroupResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
app.post('/api/v1/groups', async (req, reply) => {
const body = req.body as Partial<CreateGroupRequest> | null;
if (!body || typeof body.label !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'label is required' } });
}
try {
const group = gm.createGroup({
label: body.label,
...(body.description !== undefined ? { description: body.description } : {}),
...(body.color !== undefined ? { color: body.color } : {}),
...(Array.isArray(body.repoIds) ? { repoIds: body.repoIds } : {}),
});
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.create', resourceId: group.id, details: { label: group.label } });
return reply.status(201).send({ group } satisfies GroupResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
app.patch('/api/v1/groups/:id', async (req, reply) => {
const { id } = req.params as { id: string };
const body = (req.body as Partial<UpdateGroupRequest> | null) ?? {};
try {
const group = gm.updateGroup(id, {
...(body.label !== undefined ? { label: body.label } : {}),
...(body.description !== undefined ? { description: body.description } : {}),
...(body.color !== undefined ? { color: body.color } : {}),
});
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.update', resourceId: id });
return reply.send({ group } satisfies GroupResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
app.delete('/api/v1/groups/:id', async (req, reply) => {
const { id } = req.params as { id: string };
if (!gm.deleteGroup(id)) {
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No group with this id' } });
}
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.delete', resourceId: id });
return reply.send({ ok: true });
});
app.post('/api/v1/groups/:id/repos', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<AddRepoRequest> | null;
if (!body || typeof body.repoId !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'repoId is required' } });
}
try {
return reply.send({ group: gm.addRepo(id, body.repoId) } satisfies GroupResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
app.delete('/api/v1/groups/:id/repos/:repoId', async (req, reply) => {
const { id, repoId } = req.params as { id: string; repoId: string };
try {
return reply.send({ group: gm.removeRepo(id, repoId) } satisfies GroupResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Session de groupe (P6) : UNE session Claude couvrant tous les repos du groupe (--add-dir).
// Les répertoires sont résolus côté serveur depuis les propres worktrees du groupe — le client
// ne passe jamais de chemin brut. `branch` présent → worktree de cette branche par repo ;
// absent → le worktree principal de chaque repo.
app.post('/api/v1/groups/:id/session', async (req, reply) => {
const { id } = req.params as { id: string };
const body = (req.body as Partial<CreateGroupSessionRequest> | null) ?? {};
const command = body.command ?? 'claude';
if (command !== 'claude' && command !== 'bash') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'command must be claude or bash' } });
}
const branch = typeof body.branch === 'string' && body.branch.trim() !== '' ? body.branch.trim() : null;
let group;
try {
group = gm.getGroup(id);
} catch (err) {
return sendManagerError(reply, err);
}
const dirs: string[] = [];
const skipped: Array<{ repoId: string; reason: string }> = [];
for (const repoId of group.repoIds) {
let worktrees;
try {
worktrees = await wt.listRepoWorktrees(repoId);
} catch (err) {
skipped.push({ repoId, reason: err instanceof Error ? err.message : String(err) });
continue;
}
const match = branch ? worktrees.find((w) => w.branch === branch) : worktrees.find((w) => w.isMain);
if (!match) {
skipped.push({ repoId, reason: branch ? `no worktree on branch ${branch}` : 'no main worktree' });
continue;
}
if (!dirs.includes(match.path)) dirs.push(match.path);
}
if (dirs.length === 0) {
const detail = branch ? `no repo has a worktree on branch "${branch}" (create it first)` : 'no repo has a resolvable main checkout';
return reply.status(400).send({ error: { code: 'NO_RESOLVABLE_WORKTREE', message: `Cannot start group session: ${detail}` } });
}
// cwd = parent commun des repos couverts, chacun relié en --add-dir (P6). Voir resolveGroupCwd.
const { cwd, addDirs } = resolveGroupCwd(dirs);
try {
const session = manager.spawn({ cwd, addDirs, command, groupId: id });
recordAudit(db, {
actor: req.authContext?.tokenId ?? 'unknown',
action: 'group.session.create',
resourceId: id,
details: { command, dirs: dirs.length, ...(branch ? { branch } : {}) },
});
return reply.status(201).send({ session, dirs, skipped } satisfies GroupSessionResponse);
} catch (err) {
const statusCode = (err as { statusCode?: number }).statusCode ?? 500;
return reply.status(statusCode).send({ error: { code: 'SPAWN_FAILED', message: (err as Error).message } });
}
});
}
-39
View File
@@ -1,39 +0,0 @@
// Routes Web Push (P4). Toutes sous l'auth globale (preValidation) : aucune route publique.
// L'abonnement est lié au token authentifié (req.authContext.tokenId).
import type { FastifyInstance } from 'fastify';
import type { PushSubscribeRequest, PushUnsubscribeRequest, VapidKeyResponse } from '@arboretum/shared';
import type { PushService } from '../core/push-service.js';
import type { Db } from '../db/index.js';
import { recordAudit } from '../core/audit-log.js';
export function registerPushRoutes(app: FastifyInstance, push: PushService, db: Db): void {
app.get('/api/v1/push/vapid-public-key', async (): Promise<VapidKeyResponse> => ({ key: push.publicKey() }));
app.post('/api/v1/push/subscribe', async (req, reply) => {
const body = req.body as Partial<PushSubscribeRequest> | null;
if (!body || typeof body.endpoint !== 'string' || !body.keys || typeof body.keys.p256dh !== 'string' || typeof body.keys.auth !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'endpoint and keys{p256dh,auth} are required' } });
}
// garanti non-null : la route est protégée par le preValidation global.
const tokenId = req.authContext!.tokenId;
push.subscribe(tokenId, { endpoint: body.endpoint, keys: { p256dh: body.keys.p256dh, auth: body.keys.auth } }, req.headers['user-agent'] ?? null);
recordAudit(db, { actor: tokenId, action: 'push.subscribe' });
return reply.status(201).send({ ok: true });
});
app.post('/api/v1/push/unsubscribe', async (req, reply) => {
const body = req.body as Partial<PushUnsubscribeRequest> | null;
if (!body || typeof body.endpoint !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'endpoint is required' } });
}
push.unsubscribe(body.endpoint);
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'push.unsubscribe' });
return reply.send({ ok: true });
});
// Notification de test (diagnostic mobile) : pousse vers tous les abonnements de l'utilisateur.
app.post('/api/v1/push/test', async (_req, reply) => {
await push.notify({ sessionId: 'test', title: 'Arboretum', body: 'Push notifications are working.', kind: null, url: '/' });
return reply.send({ ok: true });
});
}
-69
View File
@@ -1,69 +0,0 @@
import type { FastifyInstance, FastifyReply } from 'fastify';
import type { CreateRepoRequest, DiscoverReposResponse, RepoResponse, ReposListResponse, UpdateRepoRequest } from '@arboretum/shared';
import type { WorktreeManager } from '../core/worktree-manager.js';
import type { Db } from '../db/index.js';
import { readScanRoots } from '../core/scan-settings.js';
/** Mappe une erreur du manager (statusCode + code) vers une réponse REST normalisée. */
export function sendManagerError(reply: FastifyReply, err: unknown): FastifyReply {
const e = err as { statusCode?: number; code?: string; message?: string };
return reply.status(e.statusCode ?? 500).send({ error: { code: e.code ?? 'INTERNAL', message: e.message ?? 'Internal error' } });
}
export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
app.get('/api/v1/repos', async (): Promise<ReposListResponse> => ({ repos: await wt.listRepos() }));
// Scan manuel : découvre et auto-enregistre les repos sous les racines configurées (settings).
app.post('/api/v1/repos/discover', async (_req, reply) => {
try {
const res: DiscoverReposResponse = await wt.discoverRepos({ roots: readScanRoots(db) });
return reply.send(res);
} catch (err) {
return sendManagerError(reply, err);
}
});
app.post('/api/v1/repos', async (req, reply) => {
const body = req.body as Partial<CreateRepoRequest> | null;
if (!body || typeof body.path !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path (absolute) is required' } });
}
try {
const repo = await wt.addRepo({
path: body.path,
...(body.label !== undefined ? { label: body.label } : {}),
...(body.postCreateHooks !== undefined ? { postCreateHooks: body.postCreateHooks } : {}),
...(body.preTrust !== undefined ? { preTrust: body.preTrust } : {}),
});
const res: RepoResponse = { repo };
return reply.status(201).send(res);
} catch (err) {
return sendManagerError(reply, err);
}
});
app.patch('/api/v1/repos/:id', async (req, reply) => {
const { id } = req.params as { id: string };
const body = (req.body as Partial<UpdateRepoRequest> | null) ?? {};
try {
const repo = await wt.updateRepo(id, {
...(body.label !== undefined ? { label: body.label } : {}),
...(body.postCreateHooks !== undefined ? { postCreateHooks: body.postCreateHooks } : {}),
...(body.preTrust !== undefined ? { preTrust: body.preTrust } : {}),
...(typeof body.hidden === 'boolean' ? { hidden: body.hidden } : {}),
});
const res: RepoResponse = { repo };
return reply.send(res);
} catch (err) {
return sendManagerError(reply, err);
}
});
app.delete('/api/v1/repos/:id', async (req, reply) => {
const { id } = req.params as { id: string };
if (!wt.removeRepo(id)) {
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No repo with this id' } });
}
return reply.send({ ok: true });
});
}
+13 -83
View File
@@ -1,24 +1,13 @@
import type { FastifyInstance } from 'fastify';
import type { CreateSessionRequest, HideDiscoveredResponse, SessionResponse, SessionsListResponse } from '@arboretum/shared';
import type { CreateSessionRequest, SessionResponse, SessionsListResponse } from '@arboretum/shared';
import type { PtyManager } from '../core/pty-manager.js';
import { mergeSessions, type DiscoveryService } from '../core/discovery-service.js';
import { hideSession, unhideSession, type Db } from '../db/index.js';
import { recordAudit } from '../core/audit-log.js';
export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager, discovery: DiscoveryService, db: Db): void {
app.get('/api/v1/sessions', async (req): Promise<SessionsListResponse> => {
const includeHidden = (req.query as { includeHidden?: string }).includeHidden === 'true';
const all = mergeSessions(manager.list(), discovery.list());
return { sessions: includeHidden ? all : all.filter((s) => !s.hidden) };
export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager, discovery: DiscoveryService): void {
app.get('/api/v1/sessions', async (): Promise<SessionsListResponse> => {
return { sessions: mergeSessions(manager.list(), discovery.list()) };
});
// Résout le claudeSessionId d'un :id de session (managée par UUID, ou découverte dont l'id EST le sid).
const resolveClaudeSid = (id: string): string | null => {
const managed = manager.resumeTargetById(id);
if (managed?.claudeSessionId) return managed.claudeSessionId;
return discovery.getDiscovered(id) ? id : null;
};
app.post('/api/v1/sessions', async (req, reply) => {
const body = req.body as Partial<CreateSessionRequest> | null;
if (!body || typeof body.cwd !== 'string' || !body.cwd.startsWith('/')) {
@@ -37,32 +26,20 @@ export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager,
}
});
// Reprise d'une session morte : nouveau PTY managé `--resume <claudeSessionId>` DANS SON CWD D'ORIGINE
// (spike S1). Le cwd n'est JAMAIS fourni par le client. Deux origines d'id possibles :
// - session managée morte (id = UUID Arboretum) → cwd + claudeSessionId + groupe lus en DB ;
// - session claude EXTERNE découverte (id = claudeSessionId) → cwd lu sur disque.
// Reprise d'une session morte : nouveau PTY managé `--resume <id>` DANS SON CWD D'ORIGINE (spike S1).
// Le cwd n'est jamais fourni par le client : il est lu sur disque via la découverte.
app.post('/api/v1/sessions/:id/resume', async (req, reply) => {
const { id } = req.params as { id: string };
const managed = manager.resumeTargetById(id);
const discovered = managed ? null : discovery.getDiscovered(id);
if (!managed && !discovered) {
const discovered = discovery.getDiscovered(id);
if (!discovered) {
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No resumable session with this id' } });
}
const cwd = managed ? managed.cwd : discovered!.cwd;
const claudeSessionId = managed ? managed.claudeSessionId : id;
// Garde-fou anti-corruption : jamais de resume direct d'une session vivante (vérif FRAÎCHE).
if (discovery.isClaudeSessionLive(claudeSessionId) || manager.findLiveByClaudeSessionId(claudeSessionId)) {
if (discovery.isClaudeSessionLive(id) || manager.findLiveByClaudeSessionId(id)) {
return reply.status(409).send({ error: { code: 'SESSION_LIVE', message: 'Session is live — fork it instead' } });
}
try {
// Session de groupe (P6) : re-relie les mêmes répertoires (--add-dir) et son groupe au resume.
const ctx = managed ? { addedDirs: managed.addedDirs, groupId: managed.groupId } : manager.groupSessionContext(claudeSessionId);
const session = manager.spawn({
cwd,
resume: { claudeSessionId },
...(ctx?.addedDirs.length ? { addDirs: ctx.addedDirs } : {}),
...(ctx?.groupId ? { groupId: ctx.groupId } : {}),
});
const session = manager.spawn({ cwd: discovered.cwd, resume: { claudeSessionId: id } });
const res: SessionResponse = { session };
return reply.status(201).send(res);
} catch (err) {
@@ -72,18 +49,14 @@ export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager,
});
// Fork : duplique une session (vivante ou morte) sans la corrompre (`--resume <id> --fork-session`).
// Même résolution d'id que /resume (managée morte par UUID, sinon externe découverte par claudeSessionId).
app.post('/api/v1/sessions/:id/fork', async (req, reply) => {
const { id } = req.params as { id: string };
const managed = manager.resumeTargetById(id);
const discovered = managed ? null : discovery.getDiscovered(id);
if (!managed && !discovered) {
const discovered = discovery.getDiscovered(id);
if (!discovered) {
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No session with this id to fork' } });
}
const cwd = managed ? managed.cwd : discovered!.cwd;
const claudeSessionId = managed ? managed.claudeSessionId : id;
try {
const session = manager.spawn({ cwd, resume: { claudeSessionId, fork: true } });
const session = manager.spawn({ cwd: discovered.cwd, resume: { claudeSessionId: id, fork: true } });
const res: SessionResponse = { session };
return reply.status(201).send(res);
} catch (err) {
@@ -92,49 +65,6 @@ export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager,
}
});
// Masque une session découverte (ou managée morte) : exclue de la liste sauf ?includeHidden=true.
// Reste reprenable/forkable — c'est un filtre d'affichage, pas une suppression.
app.post('/api/v1/sessions/:id/hide', async (req, reply) => {
const { id } = req.params as { id: string };
const sid = resolveClaudeSid(id);
if (!sid) {
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No session with this id to hide' } });
}
hideSession(db, sid);
await discovery.refresh(); // rediffuse l'état (hidden) aux clients
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.hide', resourceId: sid });
return reply.send({ ok: true });
});
// Ré-affiche une session masquée.
app.delete('/api/v1/sessions/:id/hide', async (req, reply) => {
const { id } = req.params as { id: string };
const sid = resolveClaudeSid(id);
if (!sid) {
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No session with this id to unhide' } });
}
unhideSession(db, sid);
await discovery.refresh();
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.unhide', resourceId: sid });
return reply.send({ ok: true });
});
// Masquage de masse : nettoie d'un coup tout l'historique externe actuellement visible. Les futures
// sessions externes réapparaîtront (sinon --no-discover). Renvoie le nombre de sessions masquées.
app.post('/api/v1/sessions/hide-discovered', async (req, reply) => {
const sids = discovery
.list()
.filter((s) => !s.hidden && s.claudeSessionId)
.map((s) => s.claudeSessionId as string);
for (const sid of sids) hideSession(db, sid);
await discovery.refresh();
if (sids.length > 0) {
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.hideDiscovered', resourceId: null, details: { count: sids.length } });
}
const res: HideDiscoveredResponse = { hidden: sids.length };
return reply.send(res);
});
app.delete('/api/v1/sessions/:id', async (req, reply) => {
const { id } = req.params as { id: string };
if (!manager.kill(id)) {
-69
View File
@@ -1,69 +0,0 @@
// Réglages exposés à l'UI (onglet Réglages). Frontière de sécurité CENTRALE : la table `settings`
// contient aussi des SECRETS (server_secret, vapid_private). Ces routes n'exposent QUE des champs
// non sensibles et n'écrivent QUE des clés explicitement allow-listées — jamais les secrets.
import type { FastifyInstance } from 'fastify';
import type { ServerInfo, SettingsResponse, UpdateSettingsRequest } from '@arboretum/shared';
import type { Config } from '../config.js';
import { type Db, setSetting } from '../db/index.js';
import type { PushService } from '../core/push-service.js';
import { recordAudit } from '../core/audit-log.js';
import {
SCAN_INTERVAL_KEY,
SCAN_ROOTS_KEY,
normalizeScanIntervalMin,
normalizeScanRoots,
readScanIntervalMin,
readScanRoots,
} from '../core/scan-settings.js';
// Réglages modifiables via l'API (allow-list stricte). Les secrets ne figurent JAMAIS ici.
export function registerSettingsRoutes(
app: FastifyInstance,
db: Db,
config: Config,
serverVersion: string,
push: PushService,
): void {
const serverInfo = (): ServerInfo => ({
version: serverVersion,
port: config.port,
bind: config.bind,
allowedOrigins: config.allowedOrigins,
dataDir: config.dataDir,
vapidPublicKey: push.publicKey() || null,
vapidContact: config.vapidContact,
});
const snapshot = (): SettingsResponse => ({
settings: {
scanRoots: readScanRoots(db),
scanIntervalMin: readScanIntervalMin(db),
},
server: serverInfo(),
});
app.get('/api/v1/settings', async (): Promise<SettingsResponse> => snapshot());
app.patch('/api/v1/settings', async (req, reply) => {
const body = (req.body as Partial<UpdateSettingsRequest> | null) ?? {};
if ('scanRoots' in body) {
const roots = normalizeScanRoots(body.scanRoots);
if (!roots) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'scanRoots must be an array of ≤16 absolute, normalized paths (never "/")' } });
}
setSetting(db, SCAN_ROOTS_KEY, JSON.stringify(roots));
}
if ('scanIntervalMin' in body) {
const interval = normalizeScanIntervalMin(body.scanIntervalMin);
if (interval === null) {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'scanIntervalMin must be an integer between 0 and 1440' } });
}
setSetting(db, SCAN_INTERVAL_KEY, String(interval));
}
recordAudit(db, {
actor: req.authContext?.tokenId ?? 'unknown',
action: 'settings.update',
details: { keys: Object.keys(body) },
});
return reply.send(snapshot());
});
}
-194
View File
@@ -1,194 +0,0 @@
import type { FastifyInstance } from 'fastify';
import type {
AdoptWorktreeRequest,
CommitWorktreeRequest,
CreateWorktreeRequest,
CreateWorktreeResponse,
PromoteWorktreeRequest,
PushWorktreeRequest,
RepoBranchesResponse,
SessionResponse,
StartRepoSessionRequest,
WorktreeBranchMode,
WorktreeResponse,
WorktreesListResponse,
} 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';
/** Mappe l'API (mode prioritaire ; `newBranch` déprécié) vers la stratégie de résolution de branche. */
function resolveMode(body: { mode?: unknown; newBranch?: unknown }): WorktreeBranchMode {
if (body.mode === 'auto' || body.mode === 'create' || body.mode === 'checkout') return body.mode;
if (body.newBranch === true) return 'create';
if (body.newBranch === false) return 'checkout';
return 'auto';
}
export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
app.get('/api/v1/worktrees', async (): Promise<WorktreesListResponse> => ({ worktrees: await wt.listAllWorktrees() }));
app.get('/api/v1/repos/:id/worktrees', async (req): Promise<WorktreesListResponse> => {
const { id } = req.params as { id: string };
return { worktrees: await wt.listRepoWorktrees(id) };
});
app.post('/api/v1/repos/:id/worktrees', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<CreateWorktreeRequest> | null;
if (!body || typeof body.branch !== 'string' || body.branch.trim() === '') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'branch is required' } });
}
if (body.startSession != null && body.startSession !== 'claude' && body.startSession !== 'bash') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'startSession must be claude, bash or null' } });
}
try {
const out = await wt.createWorktree(id, {
branch: body.branch,
mode: resolveMode(body), // défaut : auto (détecte créer / checkout / suivi remote)
...(body.baseRef !== undefined ? { baseRef: body.baseRef } : {}),
...(body.path !== undefined ? { path: body.path } : {}),
...(body.runHooks !== undefined ? { runHooks: body.runHooks } : {}),
...(body.preTrust !== undefined ? { preTrust: body.preTrust } : {}),
...(body.startSession !== undefined ? { startSession: body.startSession } : {}),
});
const res: CreateWorktreeResponse = out;
return reply.status(201).send(res);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Branches du repo (locales + suivies de origin + défaut) — alimente le sélecteur de base côté UI.
app.get('/api/v1/repos/:id/branches', async (req, reply) => {
const { id } = req.params as { id: string };
try {
const out = await wt.listRepoBranches(id);
return reply.send(out satisfies RepoBranchesResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Session sur le checkout principal (« bosser sur la branche principale » sans worktree),
// avec création/bascule de branche optionnelle côté serveur.
app.post('/api/v1/repos/:id/session', async (req, reply) => {
const { id } = req.params as { id: string };
const body = (req.body as Partial<StartRepoSessionRequest> | null) ?? {};
if (body.command != null && body.command !== 'claude' && body.command !== 'bash') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'command must be claude or bash' } });
}
if (body.branch != null && typeof body.branch !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'branch must be a string' } });
}
if (body.newBranch != null && typeof body.newBranch !== 'boolean') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'newBranch must be a boolean' } });
}
try {
const out = await wt.startMainSession(id, {
...(body.command !== undefined ? { command: body.command } : {}),
...(body.branch !== undefined ? { branch: body.branch } : {}),
...(body.newBranch !== undefined ? { newBranch: body.newBranch } : {}),
});
const res: SessionResponse = { session: out.session };
return reply.status(201).send(res);
} catch (err) {
return sendManagerError(reply, err);
}
});
app.post('/api/v1/repos/:id/worktrees/adopt', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<AdoptWorktreeRequest> | null;
if (!body || typeof body.path !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
}
try {
const out = await wt.adoptWorktree(id, {
path: body.path,
...(body.runHooks !== undefined ? { runHooks: body.runHooks } : {}),
...(body.preTrust !== undefined ? { preTrust: body.preTrust } : {}),
});
const res: WorktreeResponse & { hookResults: typeof out.hookResults } = { worktree: out.worktree, hookResults: out.hookResults };
return reply.send(res);
} catch (err) {
return sendManagerError(reply, err);
}
});
app.post('/api/v1/repos/:id/worktrees/prune', async (req, reply) => {
const { id } = req.params as { id: string };
try {
await wt.prune(id);
return reply.send({ ok: true });
} catch (err) {
return sendManagerError(reply, err);
}
});
// Commit (git add -A + commit) dans un worktree (ou le checkout principal).
app.post('/api/v1/repos/:id/worktrees/commit', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<CommitWorktreeRequest> | null;
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() === '') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'message is required' } });
}
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 } });
return reply.send({ worktree } satisfies WorktreeResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Push de la branche d'un worktree (upstream auto si absent).
app.post('/api/v1/repos/:id/worktrees/push', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<PushWorktreeRequest> | 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.pushWorktree(id, body.path);
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.push', resourceId: id, details: { path: body.path } });
return reply.send({ worktree } satisfies WorktreeResponse);
} catch (err) {
return sendManagerError(reply, err);
}
});
// Promotion « en principal » : la branche du worktree devient le checkout principal (worktree supprimé).
app.post('/api/v1/repos/:id/worktrees/promote', async (req, reply) => {
const { id } = req.params as { id: string };
const body = req.body as Partial<PromoteWorktreeRequest> | 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.promoteWorktree(id, body.path, body.force === true);
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.promote', resourceId: id, details: { path: body.path } });
return reply.send({ worktree });
} catch (err) {
return sendManagerError(reply, err);
}
});
app.delete('/api/v1/repos/:id/worktrees', async (req, reply) => {
const { id } = req.params as { id: string };
const query = req.query as { path?: string; force?: string };
if (typeof query.path !== 'string') {
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path query param is required' } });
}
try {
await wt.deleteWorktree(id, query.path, query.force === 'true');
return reply.send({ ok: true });
} catch (err) {
return sendManagerError(reply, err);
}
});
}
-57
View File
@@ -5,16 +5,11 @@ import {
PROTOCOL_VERSION,
encodeBinaryFrame,
parseClientMessage,
type GroupSummary,
type RepoSummary,
type ServerMessage,
type SessionSummary,
type WorktreeSummary,
} from '@arboretum/shared';
import type { ClientBinding, PtyManager } from '../core/pty-manager.js';
import type { DiscoveryService } from '../core/discovery-service.js';
import type { WorktreeManager } from '../core/worktree-manager.js';
import type { GroupManager } from '../core/group-manager.js';
const HEARTBEAT_MS = 30_000;
@@ -27,8 +22,6 @@ export function registerWsGateway(
app: FastifyInstance,
manager: PtyManager,
discovery: DiscoveryService,
worktrees: WorktreeManager,
groups: GroupManager,
serverVersion: string,
): void {
app.get('/ws', { websocket: true }, (socket: WebSocket, req) => {
@@ -37,8 +30,6 @@ export function registerWsGateway(
let nextChannel = 1;
let helloDone = false;
let subscribedSessions = false;
let subscribedWorktrees = false;
let subscribedGroups = false;
let alive = true;
const send = (msg: ServerMessage): void => {
@@ -58,33 +49,9 @@ export function registerWsGateway(
const onDiscoveryUpdate = (session: SessionSummary): void => {
if (subscribedSessions) send({ type: 'session_update', session });
};
const onRepoUpdate = (repo: RepoSummary): void => {
if (subscribedWorktrees) send({ type: 'repo_update', repo });
};
const onRepoRemoved = (repoId: string): void => {
if (subscribedWorktrees) send({ type: 'repo_removed', repoId });
};
const onWorktreeUpdate = (e: { repoId: string; worktree: WorktreeSummary }): void => {
if (subscribedWorktrees) send({ type: 'worktree_update', ...e });
};
const onWorktreeRemoved = (e: { repoId: string; path: string }): void => {
if (subscribedWorktrees) send({ type: 'worktree_removed', ...e });
};
const onGroupUpdate = (group: GroupSummary): void => {
if (subscribedGroups) send({ type: 'group_update', group });
};
const onGroupRemoved = (groupId: string): void => {
if (subscribedGroups) send({ type: 'group_removed', groupId });
};
manager.on('session_update', onSessionUpdate);
manager.on('session_exit', onSessionExit);
discovery.on('discovery_update', onDiscoveryUpdate);
worktrees.on('repo_update', onRepoUpdate);
worktrees.on('repo_removed', onRepoRemoved);
worktrees.on('worktree_update', onWorktreeUpdate);
worktrees.on('worktree_removed', onWorktreeRemoved);
groups.on('group_update', onGroupUpdate);
groups.on('group_removed', onGroupRemoved);
const heartbeat = setInterval(() => {
if (!alive) {
@@ -122,8 +89,6 @@ export function registerWsGateway(
}
case 'sub': {
subscribedSessions = msg.topics.includes('sessions');
subscribedWorktrees = msg.topics.includes('worktrees');
subscribedGroups = msg.topics.includes('groups');
return;
}
case 'attach': {
@@ -174,22 +139,6 @@ export function registerWsGateway(
}
return;
}
case 'answer': {
const st = channels.get(msg.channel);
if (!st) {
send({ type: 'error', code: 'NOT_ATTACHED', message: 'Unknown channel', channel: msg.channel });
return;
}
const r = manager.answer(st.sessionId, st.binding, msg.action, msg.optionN);
if (r === 'not_controlling') {
send({ type: 'error', code: 'NOT_CONTROLLING', message: 'Observer mode is read-only', channel: msg.channel });
} else if (r === 'gone') {
send({ type: 'error', code: 'SESSION_EXITED', message: 'Session has exited', channel: msg.channel });
} else if (r === 'invalid') {
send({ type: 'error', code: 'INVALID_ANSWER', message: 'No such option in the current dialog', channel: msg.channel });
}
return;
}
case 'resize': {
const st = channels.get(msg.channel);
if (st) manager.resize(st.sessionId, st.binding, msg.cols, msg.rows);
@@ -211,12 +160,6 @@ export function registerWsGateway(
manager.off('session_update', onSessionUpdate);
manager.off('session_exit', onSessionExit);
discovery.off('discovery_update', onDiscoveryUpdate);
worktrees.off('repo_update', onRepoUpdate);
worktrees.off('repo_removed', onRepoRemoved);
worktrees.off('worktree_update', onWorktreeUpdate);
worktrees.off('worktree_removed', onWorktreeRemoved);
groups.off('group_update', onGroupUpdate);
groups.off('group_removed', onGroupRemoved);
for (const [, st] of channels) manager.detach(st.sessionId, st.binding);
channels.clear();
});
+1 -89
View File
@@ -7,7 +7,6 @@ import { openDb, type Db } from '../src/db/index.js';
import { munge } from '../src/core/jsonl-discovery.js';
import { readProcStart } from '../src/core/session-registry.js';
import type { Config } from '../src/config.js';
import type { DiscoverReposResponse, RepoResponse, ReposListResponse } from '@arboretum/shared';
// resolveClaudeBin() fait `which claude` : on le stub pour ne pas dépendre d'un claude réel en PATH.
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
@@ -92,25 +91,9 @@ describe('app e2e — auth, origin et sessions', () => {
expect(cookie).toBeDefined();
expect(cookie?.httpOnly).toBe(true);
expect(cookie?.sameSite).toBe('Strict');
// Login local (http, pas de x-forwarded-proto) → pas de Secure, sinon le cookie casserait en localhost.
expect(cookie?.secure).toBeFalsy();
cookieValue = cookie!.value;
});
it('cookie Secure posé derrière un front HTTPS (x-forwarded-proto)', async () => {
const res = await t.bundle.app.inject({
method: 'POST',
url: '/api/v1/auth/login',
headers: { 'x-forwarded-proto': 'https' },
payload: { token: t.token },
});
expect(res.statusCode).toBe(200);
const cookie = res.cookies.find((c) => c.name === 'arb_session');
expect(cookie?.secure).toBe(true);
expect(cookie?.httpOnly).toBe(true);
expect(cookie?.sameSite).toBe('Strict');
});
it('routes API sans auth → 401', async () => {
for (const url of ['/api/v1/sessions', '/api/v1/auth/me']) {
const res = await t.bundle.app.inject({ method: 'GET', url });
@@ -128,8 +111,7 @@ describe('app e2e — auth, origin et sessions', () => {
cookies: { arb_session: cookieValue },
});
expect(me.statusCode).toBe(200);
expect(me.json()).toMatchObject({ ok: true, tokenLabel: 'initial', serverVersion: '0.0.0-test' });
expect(typeof (me.json() as { tokenId: string }).tokenId).toBe('string');
expect(me.json()).toEqual({ ok: true, tokenLabel: 'initial', serverVersion: '0.0.0-test' });
});
it('cookie altéré → 401', async () => {
@@ -148,20 +130,6 @@ describe('app e2e — auth, origin et sessions', () => {
expect(res.json()).toEqual({ sessions: [] });
});
it('masquage des sessions : hide-discovered (vide), includeHidden, hide d’un id inconnu → 404', async () => {
const headers = { authorization: `Bearer ${t.token}` };
const mass = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/sessions/hide-discovered', headers });
expect(mass.statusCode).toBe(200);
expect(mass.json()).toEqual({ hidden: 0 });
const withHidden = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/sessions?includeHidden=true', headers });
expect(withHidden.statusCode).toBe(200);
expect(withHidden.json()).toEqual({ sessions: [] });
const unknown = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/sessions/nope/hide', headers });
expect(unknown.statusCode).toBe(404);
});
it('Origin interdite → 403 même avec un Bearer valide, et même sur la route publique de login', async () => {
const res = await t.bundle.app.inject({
method: 'GET',
@@ -369,59 +337,3 @@ describe('app e2e — découverte, resume & fork (P2)', () => {
expect(fork.statusCode).toBe(201);
});
});
describe('app e2e — découverte auto des repos & masquage', () => {
let t: TestApp;
let scanRoot: string;
const bearer = (): Record<string, string> => ({ authorization: `Bearer ${t.token}` });
beforeAll(() => {
t = makeApp('repos-discover');
// un « repo » côté scanner = un dossier avec .git (le scanner ne lance pas git).
scanRoot = join(dir, 'scan-root');
mkdirSync(join(scanRoot, 'alpha', '.git'), { recursive: true });
mkdirSync(join(scanRoot, 'beta', '.git'), { recursive: true });
});
it('POST /repos/discover enregistre les repos sous les racines configurées', async () => {
// configure la racine de scan via l'allow-list settings, désactive le périodique
const patch = await t.bundle.app.inject({
method: 'PATCH',
url: '/api/v1/settings',
headers: bearer(),
payload: { scanRoots: [scanRoot], scanIntervalMin: 0 },
});
expect(patch.statusCode).toBe(200);
const disc = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/repos/discover', headers: bearer() });
expect(disc.statusCode).toBe(200);
const body = disc.json() as DiscoverReposResponse;
expect(body.added).toBe(2);
expect(body.scanned).toBe(2);
const list = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/repos', headers: bearer() });
const repos = (list.json() as ReposListResponse).repos;
expect(repos.map((r) => r.label).sort()).toEqual(['alpha', 'beta']);
expect(repos.every((r) => r.hidden === false)).toBe(true);
// re-scan : idempotent (aucun nouveau)
const disc2 = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/repos/discover', headers: bearer() });
expect((disc2.json() as DiscoverReposResponse).added).toBe(0);
});
it('PATCH /repos/:id { hidden } masque le repo', async () => {
const list = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/repos', headers: bearer() });
const repo = (list.json() as ReposListResponse).repos[0];
const patch = await t.bundle.app.inject({
method: 'PATCH',
url: `/api/v1/repos/${repo.id}`,
headers: bearer(),
payload: { hidden: true },
});
expect(patch.statusCode).toBe(200);
expect((patch.json() as RepoResponse).repo.hidden).toBe(true);
// toujours listé (les masqués restent récupérables) mais avec hidden=true
const after = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/repos', headers: bearer() });
expect((after.json() as ReposListResponse).repos.find((r) => r.id === repo.id)?.hidden).toBe(true);
});
});
@@ -1,164 +0,0 @@
// Lot 5 — sécurité enterprise : en-têtes de sécurité, journal d'audit, RGPD (export/suppression),
// garde Content-Type. Vérifie le câblage de bout en bout via buildApp + token bootstrap.
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { buildApp, type AppBundle } from '../src/app.js';
import { openDb, type Db } from '../src/db/index.js';
import type { Config } from '../src/config.js';
import type { AuditLogsResponse, DataExportResponse, DeleteMyDataResponse } from '@arboretum/shared';
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
class FakePty {
pid = 424242;
write = vi.fn();
resize = vi.fn();
pause = vi.fn();
resume = vi.fn();
kill = vi.fn();
onData(): { dispose: () => void } {
return { dispose: () => {} };
}
onExit(): { dispose: () => void } {
return { dispose: () => {} };
}
}
return { default: { spawn: (): FakePty => new FakePty() } };
});
process.env.ARBORETUM_LOG = 'silent';
let dir: string;
let bundle: AppBundle;
let db: Db;
let token: string;
const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` });
beforeAll(() => {
dir = mkdtempSync(join(tmpdir(), 'arboretum-audit-'));
const dbPath = join(dir, 'audit.db');
db = openDb(dbPath);
const config: Config = {
port: 9998,
bind: '127.0.0.1',
dbPath,
dataDir: dir,
allowedOrigins: ['https://host.tailnet.ts.net'],
printToken: false,
claudeProjectsDir: join(dir, 'claude', 'projects'),
claudeSessionsDir: join(dir, 'claude', 'sessions'),
vapidContact: 'mailto:test@localhost',
autoDiscover: false,
};
bundle = buildApp(config, db, '1.2.3-test');
const t = bundle.auth.ensureBootstrapToken();
if (!t) throw new Error('bootstrap token attendu');
token = t;
});
afterAll(async () => {
await bundle.app.close();
db.close();
rmSync(dir, { recursive: true, force: true });
});
describe('En-têtes de sécurité', () => {
it('pose les en-têtes durs + no-store sur /api, sans header Server', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: auth() });
expect(res.statusCode).toBe(200);
expect(res.headers['x-content-type-options']).toBe('nosniff');
expect(res.headers['x-frame-options']).toBe('DENY');
expect(res.headers['referrer-policy']).toBe('no-referrer');
expect(res.headers['content-security-policy']).toContain("default-src 'self'");
expect(res.headers['content-security-policy']).toContain("frame-ancestors 'none'");
expect(String(res.headers['cache-control'])).toContain('no-store');
expect(res.headers['server']).toBeUndefined();
});
it('pose HSTS uniquement derrière HTTPS (x-forwarded-proto)', async () => {
const http = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: auth() });
expect(http.headers['strict-transport-security']).toBeUndefined();
const https = await bundle.app.inject({
method: 'GET',
url: '/api/v1/auth/me',
headers: { ...auth(), 'x-forwarded-proto': 'https' },
});
expect(String(https.headers['strict-transport-security'])).toContain('max-age=');
});
it('rejette une mutation avec corps non-JSON (415)', async () => {
const res = await bundle.app.inject({
method: 'POST',
url: '/api/v1/auth/tokens',
headers: { ...auth(), 'content-type': 'text/plain' },
payload: 'label=pwned',
});
expect(res.statusCode).toBe(415);
});
});
describe('Journal d’audit', () => {
it('journalise la création de token et l’expose via GET /audit-logs', async () => {
const create = await bundle.app.inject({
method: 'POST',
url: '/api/v1/auth/tokens',
headers: auth(),
payload: { label: 'ci-extra' },
});
expect(create.statusCode).toBe(201);
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/audit-logs', headers: auth() });
expect(res.statusCode).toBe(200);
const body = res.json() as AuditLogsResponse;
const actions = body.entries.map((e) => e.action);
expect(actions).toContain('token.create');
expect(actions).toContain('secret.generate'); // généré au bootstrap (system)
// aucune VALEUR secrète en clair : pas de chaîne hex de 64 caractères (server_secret / clé).
// (les ids sont des UUID avec tirets → non concernés ; 'server_secret' est un nom de ressource.)
expect(res.body).not.toMatch(/[a-f0-9]{64}/i);
});
it('journalise les échecs de login (actor anonymous)', async () => {
await bundle.app.inject({ method: 'POST', url: '/api/v1/auth/login', payload: { token: 'arb_invalid_xxx' } });
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/audit-logs?limit=200', headers: auth() });
const body = res.json() as AuditLogsResponse;
expect(body.entries.some((e) => e.action === 'login.failure' && e.actor === 'anonymous')).toBe(true);
});
});
describe('RGPD', () => {
it('exporte les données du token authentifié', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/data/export', headers: auth() });
expect(res.statusCode).toBe(200);
const body = res.json() as DataExportResponse;
expect(Array.isArray(body.tokens)).toBe(true);
expect(body.tokens.some((t) => t.current)).toBe(true);
expect(Array.isArray(body.pushSubscriptions)).toBe(true);
expect(Array.isArray(body.sessions)).toBe(true);
expect(body.settings).toHaveProperty('scanRoots');
});
it('supprime en deux temps (pending → confirm → done) et révoque le token', async () => {
const pending = await bundle.app.inject({ method: 'POST', url: '/api/v1/data/delete-my-data', headers: auth(), payload: {} });
const p = pending.json() as DeleteMyDataResponse;
expect(p.status).toBe('pending');
expect(p.confirm).toBeTruthy();
// un 2e token existe (créé plus haut) → révoquer le token courant est autorisé.
const done = await bundle.app.inject({
method: 'POST',
url: '/api/v1/data/delete-my-data',
headers: auth(),
payload: { confirm: p.confirm },
});
const d = done.json() as DeleteMyDataResponse;
expect(d.status).toBe('done');
expect(d.summary.tokenRevoked).toBe(true);
// le token courant est désormais révoqué → 401.
const after = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: auth() });
expect(after.statusCode).toBe(401);
});
});
-143
View File
@@ -1,143 +0,0 @@
// Gestion des tokens d'accès via l'API REST (onglet Réglages) : create → list → revoke,
// flag « courant », jamais de hash exposé, garde anti lock-out sur le dernier token.
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { buildApp, type AppBundle } from '../src/app.js';
import { openDb, type Db } from '../src/db/index.js';
import type { Config } from '../src/config.js';
import type { CreateTokenResponse, MeResponse, TokensListResponse } from '@arboretum/shared';
// Mêmes stubs que les autres tests de routes : pas de vrai claude ni de vrai PTY.
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
class FakePty {
pid = 424242;
write = vi.fn();
resize = vi.fn();
pause = vi.fn();
resume = vi.fn();
kill = vi.fn();
onData(): { dispose: () => void } {
return { dispose: () => {} };
}
onExit(): { dispose: () => void } {
return { dispose: () => {} };
}
}
return { default: { spawn: (): FakePty => new FakePty() } };
});
process.env.ARBORETUM_LOG = 'silent';
let dir: string;
let bundle: AppBundle;
let db: Db;
let token: string;
const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` });
beforeAll(() => {
dir = mkdtempSync(join(tmpdir(), 'arboretum-tokens-'));
const dbPath = join(dir, 'tokens.db');
db = openDb(dbPath);
const config: Config = {
port: 7317,
bind: '127.0.0.1',
dbPath,
dataDir: dir,
allowedOrigins: [],
printToken: false,
claudeProjectsDir: join(dir, 'claude', 'projects'),
claudeSessionsDir: join(dir, 'claude', 'sessions'),
vapidContact: 'mailto:test@localhost',
};
bundle = buildApp(config, db, '0.0.0-test');
const t = bundle.auth.ensureBootstrapToken();
if (!t) throw new Error('bootstrap token attendu sur une base vierge');
token = t;
});
afterAll(async () => {
await bundle.app.close();
db.close();
rmSync(dir, { recursive: true, force: true });
});
describe('routes de gestion des tokens', () => {
it('GET /auth/me expose le tokenId courant', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: auth() });
expect(res.statusCode).toBe(200);
const me = res.json() as MeResponse;
expect(typeof me.tokenId).toBe('string');
expect(me.tokenId.length).toBeGreaterThan(0);
});
it('liste le token initial et le marque « courant », sans jamais exposer de hash', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() });
expect(res.statusCode).toBe(200);
const body = res.json() as TokensListResponse;
expect(body.tokens).toHaveLength(1);
expect(body.tokens[0]?.label).toBe('initial');
expect(body.tokens[0]?.current).toBe(true);
// aucune fuite de hash / valeur en clair
expect(JSON.stringify(body)).not.toMatch(/token_hash|tokenHash/);
});
it('crée un token (valeur en clair renvoyée une fois), puis utilisable pour s’authentifier', async () => {
const res = await bundle.app.inject({
method: 'POST',
url: '/api/v1/auth/tokens',
headers: auth(),
payload: { label: 'laptop' },
});
expect(res.statusCode).toBe(201);
const created = res.json() as CreateTokenResponse;
expect(created.label).toBe('laptop');
expect(created.token).toMatch(/^arb_[0-9a-f]{48}$/);
// le nouveau token authentifie réellement
const me = await bundle.app.inject({
method: 'GET',
url: '/api/v1/auth/me',
headers: { authorization: `Bearer ${created.token}` },
});
expect((me.json() as MeResponse).tokenLabel).toBe('laptop');
});
it('rejette un label vide ou trop long (400)', async () => {
const empty = await bundle.app.inject({ method: 'POST', url: '/api/v1/auth/tokens', headers: auth(), payload: { label: ' ' } });
expect(empty.statusCode).toBe(400);
const tooLong = await bundle.app.inject({ method: 'POST', url: '/api/v1/auth/tokens', headers: auth(), payload: { label: 'x'.repeat(65) } });
expect(tooLong.statusCode).toBe(400);
});
it('révoque un token non courant (204), qui disparaît de la liste et n’authentifie plus', async () => {
const before = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse;
const victim = before.tokens.find((t) => !t.current);
expect(victim).toBeDefined();
const del = await bundle.app.inject({ method: 'DELETE', url: `/api/v1/auth/tokens/${victim!.id}`, headers: auth() });
expect(del.statusCode).toBe(200);
const after = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse;
expect(after.tokens.find((t) => t.id === victim!.id)).toBeUndefined();
});
it('404 sur un id inconnu', async () => {
const res = await bundle.app.inject({ method: 'DELETE', url: '/api/v1/auth/tokens/nope-xyz', headers: auth() });
expect(res.statusCode).toBe(404);
});
it('409 LAST_TOKEN : refuse de révoquer le dernier token actif', async () => {
const list = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse;
expect(list.tokens).toHaveLength(1); // seul le token courant subsiste
const res = await bundle.app.inject({ method: 'DELETE', url: `/api/v1/auth/tokens/${list.tokens[0]!.id}`, headers: auth() });
expect(res.statusCode).toBe(409);
expect(res.json()).toMatchObject({ error: { code: 'LAST_TOKEN' } });
});
it('sans authentification → 401', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens' });
expect(res.statusCode).toBe(401);
});
});
@@ -1,74 +0,0 @@
import { describe, expect, it, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SessionActivityTracker } from '../src/core/claude-adapter.js';
const PID = 999_999;
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
function writeRegistry(dir: string, status: string, waitingFor?: string): void {
writeFileSync(
join(dir, `${PID}.json`),
JSON.stringify({ pid: PID, procStart: '123', sessionId: 'sid', cwd: '/x', status, ...(waitingFor ? { waitingFor } : {}) }),
);
}
describe('SessionActivityTracker', () => {
let dir: string;
let tracker: SessionActivityTracker;
let changes: number;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'arb-adapter-'));
changes = 0;
tracker = new SessionActivityTracker(PID, dir, () => {
changes++;
});
});
afterEach(() => {
tracker.dispose();
rmSync(dir, { recursive: true, force: true });
});
it('registre busy → idle : transitions d’activité + onChange sur changement uniquement', () => {
writeRegistry(dir, 'busy');
tracker.evaluate();
expect(tracker.snapshot().activity).toBe('busy');
expect(changes).toBe(1);
tracker.evaluate(); // rien n'a changé
expect(changes).toBe(1);
writeRegistry(dir, 'idle');
tracker.evaluate();
expect(tracker.snapshot().activity).toBe('idle');
expect(changes).toBe(2);
});
it('registre waiting + écran permission → activity waiting, dialog typé permission', async () => {
await tracker['reader'].feed('\x1b[2J\x1b[HDo you want to create x.txt?\r\n❯ 1. Yes\r\n2. No\r\nEsc to cancel · Tab to amend\r\n');
await sleep(30);
writeRegistry(dir, 'waiting', 'permission prompt');
tracker.evaluate();
const s = tracker.snapshot();
expect(s.activity).toBe('waiting');
expect(s.waitingFor).toBe('permission prompt');
expect(s.dialog?.kind).toBe('permission');
expect(s.dialog?.options.find((o) => o.n === 1)).toMatchObject({ selected: true });
});
it('pas de registre + écran Trust → waiting/trust (le Trust précède le registre)', async () => {
await tracker['reader'].feed('\x1b[2J\x1b[HDo you trust the files in this folder?\r\n❯ 1. Yes, I trust this folder\r\n2. No, exit\r\n');
await sleep(30);
tracker.evaluate();
const s = tracker.snapshot();
expect(s.activity).toBe('waiting');
expect(s.dialog?.kind).toBe('trust');
});
it('pas de registre + pas de dialogue → état vide (inconnu)', () => {
tracker.evaluate();
expect(tracker.snapshot()).toMatchObject({ activity: null, dialog: null });
});
});
@@ -1,29 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import { buildSpawnSpec } from '../src/core/claude-launcher.js';
// resolveClaudeBin() fait `which claude` : on le stub pour ne pas dépendre d'un claude réel en PATH.
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
describe('buildSpawnSpec — session de groupe multi-repo (P6)', () => {
it('émet un --add-dir par répertoire supplémentaire (claude)', () => {
const spec = buildSpawnSpec({ command: 'claude', addDirs: ['/a', '/b', '/c'] });
expect(spec.file).toBe('/usr/bin/claude');
expect(spec.args).toEqual(['--add-dir', '/a', '--add-dir', '/b', '--add-dir', '/c']);
});
it('combine --resume et --add-dir (reprise d’une session de groupe)', () => {
const spec = buildSpawnSpec({ command: 'claude', resume: { claudeSessionId: 'sid' }, addDirs: ['/x'] });
expect(spec.args).toEqual(['--resume', 'sid', '--add-dir', '/x']);
});
it('aucun --add-dir quand addDirs est vide/absent', () => {
expect(buildSpawnSpec({ command: 'claude' }).args).toEqual([]);
expect(buildSpawnSpec({ command: 'claude', addDirs: [] }).args).toEqual([]);
});
it('ignore addDirs pour bash (pas de --add-dir)', () => {
const spec = buildSpawnSpec({ command: 'bash', addDirs: ['/a', '/b'] });
expect(spec.file).toBe('bash');
expect(spec.args).toEqual(['--norc']);
});
});
-39
View File
@@ -1,39 +0,0 @@
import { describe, expect, it, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, readFileSync, writeFileSync, rmSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { preTrustProject } from '../src/core/claude-trust.js';
describe('preTrustProject', () => {
let dir: string;
let cfg: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'arb-trust-'));
cfg = join(dir, '.claude.json');
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
it('crée le fichier s’il est absent et marque le worktree approuvé', () => {
expect(preTrustProject('/home/u/proj-wt-x', cfg)).toBe(true);
const data = JSON.parse(readFileSync(cfg, 'utf8'));
expect(data.projects['/home/u/proj-wt-x'].hasTrustDialogAccepted).toBe(true);
});
it('préserve la config existante (autres clés et projets)', () => {
writeFileSync(cfg, JSON.stringify({ theme: 'dark', projects: { '/other': { foo: 1 } } }));
expect(preTrustProject('/home/u/new', cfg)).toBe(true);
const data = JSON.parse(readFileSync(cfg, 'utf8'));
expect(data.theme).toBe('dark');
expect(data.projects['/other']).toEqual({ foo: 1 });
expect(data.projects['/home/u/new'].hasTrustDialogAccepted).toBe(true);
});
it('fichier corrompu → abandon SANS écraser (retourne false)', () => {
writeFileSync(cfg, '{ this is not json');
expect(preTrustProject('/home/u/x', cfg)).toBe(false);
expect(readFileSync(cfg, 'utf8')).toBe('{ this is not json'); // intact
expect(existsSync(`${cfg}.arb-tmp`)).toBe(false);
});
});
-166
View File
@@ -1,166 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest';
import { homedir } from 'node:os';
import { join } from 'node:path';
import {
detectPlatform,
parseInstallArgs,
buildServiceArgs,
resolveBin,
resolveScriptPath,
renderSystemdUnit,
renderLaunchAgentPlist,
xmlEscape,
systemdUnitPath,
launchAgentPlistPath,
} from '../src/cli/install.js';
describe('cli install — detectPlatform', () => {
it('accepte linux et darwin', () => {
expect(detectPlatform('linux')).toBe('linux');
expect(detectPlatform('darwin')).toBe('darwin');
});
it('rejette les autres plateformes avec un message clair', () => {
expect(() => detectPlatform('win32')).toThrow(/Linux \(systemd\) and macOS \(launchd\)/);
expect(() => detectPlatform('freebsd')).toThrow(/freebsd/);
});
});
describe('cli install — buildServiceArgs', () => {
it('aucun flag → aucun argument (le service garde les défauts loopback)', () => {
expect(buildServiceArgs(parseInstallArgs([]))).toEqual([]);
});
it('propage --port et --allow-origin (répétable) dans un ordre stable', () => {
const flags = parseInstallArgs(['--port', '8080', '--allow-origin', 'a', '--allow-origin', 'b']);
expect(buildServiceArgs(flags)).toEqual(['--port', '8080', '--allow-origin', 'a', '--allow-origin', 'b']);
});
it("n'injecte JAMAIS --i-know-this-exposes-a-terminal (modèle de sécurité)", () => {
const flags = parseInstallArgs(['--bind', '0.0.0.0', '--port', '7317']);
expect(buildServiceArgs(flags)).not.toContain('--i-know-this-exposes-a-terminal');
});
it("ne propage pas les flags propres à l'install (bin-path, label, dry-run, no-enable)", () => {
const flags = parseInstallArgs(['--bin-path', '/usr/local/bin/arboretum', '--label', 'x', '--dry-run', '--no-enable']);
expect(buildServiceArgs(flags)).toEqual([]);
});
});
describe('cli install — resolveBin', () => {
it('par défaut : node (process.execPath) + dist/index.js', () => {
const { exec, args } = resolveBin({});
expect(exec).toBe(process.execPath);
expect(args).toHaveLength(1);
expect(args[0]).toBe(resolveScriptPath());
expect(args[0]).toMatch(/index\.(js|ts)$/);
});
it('--bin-path force le wrapper, sans argument de script', () => {
expect(resolveBin({ binPath: '/usr/local/bin/arboretum' })).toEqual({
exec: '/usr/local/bin/arboretum',
args: [],
});
});
});
describe('cli install — renderSystemdUnit', () => {
it('contient le ExecStart calculé et les directives clés', () => {
const unit = renderSystemdUnit({ exec: '/usr/bin/node', scriptArgs: ['/opt/arboretum/index.js', '--port', '7317'] });
expect(unit).toContain('ExecStart=/usr/bin/node /opt/arboretum/index.js --port 7317');
expect(unit).toContain('Restart=on-failure');
expect(unit).toContain('KillSignal=SIGTERM');
expect(unit).toContain('TimeoutStopSec=10');
expect(unit).toContain('WantedBy=default.target');
});
it('quote les tokens contenant un espace', () => {
const unit = renderSystemdUnit({ exec: '/path with space/node', scriptArgs: ['/s.js'] });
expect(unit).toContain('ExecStart="/path with space/node" /s.js');
});
it('snapshot du unit pour un jeu de flags fixe', () => {
const unit = renderSystemdUnit({
exec: '/usr/bin/node',
scriptArgs: ['/opt/arboretum/index.js', '--port', '7317', '--allow-origin', 'https://m.ts.net'],
});
expect(unit).toMatchInlineSnapshot(`
"[Unit]
Description=Arboretum — git worktree & Claude Code dashboard
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=/usr/bin/node /opt/arboretum/index.js --port 7317 --allow-origin https://m.ts.net
Restart=on-failure
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=10
Environment=NODE_ENV=production
[Install]
WantedBy=default.target
"
`);
});
});
describe('cli install — renderLaunchAgentPlist', () => {
const base = {
label: 'fr.lidge.arboretum',
programArguments: ['/usr/bin/node', '/opt/index.js', '--port', '7317'],
stdoutPath: '/Users/me/Library/Logs/arboretum/out.log',
stderrPath: '/Users/me/Library/Logs/arboretum/err.log',
};
it('contient le label, les ProgramArguments ordonnés et les clés launchd', () => {
const plist = renderLaunchAgentPlist(base);
expect(plist).toContain('<string>fr.lidge.arboretum</string>');
const idxNode = plist.indexOf('<string>/usr/bin/node</string>');
const idxScript = plist.indexOf('<string>/opt/index.js</string>');
expect(idxNode).toBeGreaterThan(0);
expect(idxScript).toBeGreaterThan(idxNode);
expect(plist).toContain('<key>RunAtLoad</key>');
expect(plist).toContain('<key>KeepAlive</key>');
expect(plist).toContain('<key>StandardOutPath</key>');
});
it('échappe les caractères XML dans les arguments (URL avec &)', () => {
const plist = renderLaunchAgentPlist({
...base,
programArguments: ['/usr/bin/node', '/opt/index.js', '--allow-origin', 'https://a?b&c=d'],
});
expect(plist).toContain('https://a?b&amp;c=d');
expect(plist).not.toContain('b&c=d');
});
});
describe('cli install — xmlEscape', () => {
it('échappe &, < et >', () => {
expect(xmlEscape('a & b < c > d')).toBe('a &amp; b &lt; c &gt; d');
});
});
describe('cli install — chemins', () => {
const savedXdg = process.env.XDG_CONFIG_HOME;
afterEach(() => {
if (savedXdg === undefined) delete process.env.XDG_CONFIG_HOME;
else process.env.XDG_CONFIG_HOME = savedXdg;
});
it('systemdUnitPath respecte XDG_CONFIG_HOME', () => {
process.env.XDG_CONFIG_HOME = '/tmp/xdg';
expect(systemdUnitPath()).toBe('/tmp/xdg/systemd/user/arboretum.service');
});
it('systemdUnitPath retombe sur ~/.config sans XDG_CONFIG_HOME', () => {
delete process.env.XDG_CONFIG_HOME;
expect(systemdUnitPath()).toBe(join(homedir(), '.config', 'systemd', 'user', 'arboretum.service'));
});
it('launchAgentPlistPath place le plist dans ~/Library/LaunchAgents', () => {
expect(launchAgentPlistPath('fr.lidge.arboretum')).toBe(
join(homedir(), 'Library', 'LaunchAgents', 'fr.lidge.arboretum.plist'),
);
});
});
@@ -1,115 +0,0 @@
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { DialogKind } from '@arboretum/shared';
import { ScreenReader } from '../src/core/screen-reader.js';
import { classifyDialog, parseOptions, type ClassifiedDialog } from '../src/core/dialog-classifier.js';
const capturesDir = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'dialogs');
/** Rejoue un flux PTY brut par segments (comme l'adapter en prod) et collecte écran+dialogue détecté. */
async function replay(fixture: string): Promise<Array<{ dialog: ClassifiedDialog; text: string }>> {
const data = readFileSync(join(capturesDir, fixture));
const reader = new ScreenReader(120, 40);
const seen: Array<{ dialog: ClassifiedDialog; text: string }> = [];
const STEP = 512;
for (let i = 0; i < data.length; i += STEP) {
await reader.feed(data.subarray(i, i + STEP)); // xterm gère les séquences coupées en frontière
const lines = reader.snapshotLines();
const d = classifyDialog(lines);
if (d) seen.push({ dialog: d, text: lines.join('\n') });
}
reader.dispose();
return seen;
}
describe('ScreenReader (@xterm/headless) — anti strip-ANSI naïf', () => {
it('préserve les espaces du dialogue (« Do you want to create », pas « Doyouwant »)', async () => {
const seen = await replay('perm-write2.raw');
expect(seen.length).toBeGreaterThan(0);
expect(seen.some((s) => /Do you want to create/.test(s.text))).toBe(true);
});
});
describe('classifyDialog — unitaire (lignes synthétiques)', () => {
it('trust', () => {
const d = classifyDialog(['Do you trust the files in this folder?', '❯ 1. Yes, I trust this folder', '2. No, exit']);
expect(d?.kind).toBe('trust');
expect(d?.options).toHaveLength(2);
expect(d?.options[0]).toMatchObject({ n: 1, selected: true });
});
it('permission', () => {
const d = classifyDialog(['Do you want to create s3-edit.txt?', '❯ 1. Yes', '3. No', 'Esc to cancel · Tab to amend']);
expect(d?.kind).toBe('permission');
});
it('question (prime sur permission malgré « Esc to cancel »)', () => {
const d = classifyDialog(['☐ Couleur', '❯ 1. Rouge', '2. Bleu', 'Enter to select · ↑/↓ to navigate · Esc to cancel']);
expect(d?.kind).toBe('question');
});
it('aucun dialogue → null', () => {
expect(classifyDialog(['just some output', 'no options here'])).toBeNull();
});
it('parseOptions tolère « ❯ 2) Label » et trim', () => {
expect(parseOptions([' ❯ 2) Yes, allow all '])).toEqual([{ n: 2, label: 'Yes, allow all', selected: true }]);
});
});
describe('détection sur fixtures réelles S3 (replay headless)', () => {
it('perm-write2 → permission avec options Yes/…/No, option 1 sélectionnée', async () => {
const perms = (await replay('perm-write2.raw')).filter((s) => s.dialog.kind === 'permission');
expect(perms.length).toBeGreaterThan(0);
const withOpts = perms.find((s) => s.dialog.options.length >= 2);
expect(withOpts).toBeDefined();
const labels = withOpts!.dialog.options.map((o) => o.label).join(' | ');
expect(labels).toMatch(/Yes/);
expect(labels).toMatch(/No/);
expect(withOpts!.dialog.options.find((o) => o.n === 1)?.selected).toBe(true);
});
it('ask2 → question avec une option « Rouge »', async () => {
const qs = (await replay('ask2.raw')).filter((s) => s.dialog.kind === 'question');
expect(qs.length).toBeGreaterThan(0);
expect(qs.some((s) => s.dialog.options.some((o) => /Rouge/.test(o.label)))).toBe(true);
});
it('trust → dialogue trust détecté', async () => {
const seen = await replay('trust.raw');
expect(seen.some((s) => s.dialog.kind === 'trust')).toBe(true);
});
});
// Campagne de fiabilité P4-C : chaque type de dialogue ciblé par la supervision mobile doit être
// classifié de façon fiable (cf. « reste à faire P4 » du verdict S3 : couvrir le refus Esc et le plan).
describe('campagne de fiabilité P4-C — tous les types de dialogue', () => {
const realCaptures: Array<{ fixture: string; kind: DialogKind }> = [
{ fixture: 'trust.raw', kind: 'trust' },
{ fixture: 'perm-write2.raw', kind: 'permission' },
{ fixture: 'perm-bash2.raw', kind: 'permission' },
{ fixture: 'ask2.raw', kind: 'question' },
];
for (const c of realCaptures) {
it(`${c.fixture} → ${c.kind} détecté (capture réelle)`, async () => {
const seen = await replay(c.fixture);
expect(seen.some((s) => s.dialog.kind === c.kind)).toBe(true);
});
}
it('refus par Esc (deny-esc2) : un dialogue est bien affiché avant l’annulation', async () => {
// un dialogue détecté = l'utilisateur peut répondre « deny » (Esc) depuis le mobile sans terminal.
const seen = await replay('deny-esc2.raw');
expect(seen.length).toBeGreaterThan(0);
});
it('plan (synthétique — pas de capture réelle) : « Would you like to proceed? »', () => {
const d = classifyDialog([
'Here is my implementation plan:',
' - step one',
'❯ 1. Yes, proceed',
'2. No, keep planning',
'Would you like to proceed?',
]);
expect(d?.kind).toBe('plan');
expect(d?.options.find((o) => o.n === 1)).toMatchObject({ selected: true, label: 'Yes, proceed' });
});
});
+2 -25
View File
@@ -7,7 +7,7 @@ import { DiscoveryService, mergeSessions } from '../src/core/discovery-service.j
import { munge } from '../src/core/jsonl-discovery.js';
import { readProcStart } from '../src/core/session-registry.js';
import { PtyManager } from '../src/core/pty-manager.js';
import { openDb, hideSession, unhideSession, listHiddenSessionIds, type Db } from '../src/db/index.js';
import { openDb, type Db } from '../src/db/index.js';
function writeJsonl(projectsDir: string, cwd: string, sid: string): void {
const dir = join(projectsDir, munge(cwd));
@@ -30,7 +30,7 @@ describe('DiscoveryService', () => {
sessionsDir = mkdtempSync(join(tmpdir(), 'arb-sess-'));
db = openDb(':memory:');
manager = new PtyManager(db, sessionsDir);
svc = new DiscoveryService({ db, ptyManager: manager, projectsDir, sessionsDir });
svc = new DiscoveryService({ ptyManager: manager, projectsDir, sessionsDir });
});
afterEach(() => {
svc.stop();
@@ -71,29 +71,6 @@ describe('DiscoveryService', () => {
expect(svc.list().find((x) => x.id === 'managed-sid')).toBeUndefined();
});
it('marque hidden une session masquée mais la garde résoluble (resume/fork)', async () => {
writeJsonl(projectsDir, '/home/u/old', 'old-sid');
hideSession(db, 'old-sid');
await svc.refresh();
const s = svc.list().find((x) => x.id === 'old-sid');
expect(s?.hidden).toBe(true);
// toujours connue : la reprise/le fork doivent rester possibles
expect(svc.getDiscovered('old-sid')?.cwd).toBe('/home/u/old');
// ré-affichage
unhideSession(db, 'old-sid');
await svc.refresh();
expect(svc.list().find((x) => x.id === 'old-sid')?.hidden).toBe(false);
});
it('hideSession est idempotent et listHiddenSessionIds reflète l’état', () => {
hideSession(db, 'a');
hideSession(db, 'a');
hideSession(db, 'b');
expect(listHiddenSessionIds(db)).toEqual(new Set(['a', 'b']));
unhideSession(db, 'a');
expect(listHiddenSessionIds(db)).toEqual(new Set(['b']));
});
it('émet discovery_update sur changement uniquement', async () => {
writeJsonl(projectsDir, '/home/u/x', 'sid-x');
const seen: SessionSummary[] = [];
-572
View File
@@ -1,572 +0,0 @@
78[?25h[?25l[?2004h[?1004h[?2031h[?2026h␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
Accessingworkspace:␍
␍
/tmp/spike-s3-ask2␍
␍
Quicksafetycheck:Isthisaprojectyoucreatedoroneyoutrust?(Likeyourowncode,awell-knownopensource␍
project,orworkfromyourteam).Ifnot,takeamomenttoreviewwhat'sinthisfolderfirst.␍
␍
ClaudeCode'llbeabletoread,edit,andexecutefileshere.␍
␍
]8;id=zaxmda;https://code.claude.com/docs/en/securitySecurity guide]8;;␍
␍
❯1.Yes,Itrustthisfolder␍
2.No,exit␍
␍
Entertoconfirm·Esctocancel␍
[?2026l[>0q[?2026h␍Yes, I trust this folder✔␍
[?2026l]0;✳ Claude Code[?2026h␍╭───Claude Codev2.1.173─────────────────────────────────────────────────────────────────────────────────────────────╮␍│ │ Tips for getting started │␍│ Welcome back Devon!│Run/inittocreateaCLAUDE.mdfilewithinstructionsforCla…│␍││───────────────────────────────────────────────────────────────│␍│  ▐▛███▜▌│What's new│␍│▝▜█████▛▘│FixedFable5modelnameswitha`[1m]`suffixnotbeingnorma…│␍│     ▘▘ ▝▝     │ Fixed a spurious "sandbox depenncies missing"startup warnin…│␍│ Opus 4.8 (1M context) with xh… · Claude Team ·  │ Sub-agnts can nowspawn their own sub-agents(upto5levels…│␍│Example│/release-notes for more│␍│   /tmp/spike-s3-ask2    │  │␍╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯␍␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍❯ Try "fix lint errors"␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍? for shortcuts · ← for agents◉ xhigh · /effort␍[?25h[?2026l[?2026h[?25l␍␍
[?25h[?2026l[?2026h[?25l␍ ⚠ 2 setup issues: MCP · /doctor␍␍ ▎ Meet Fable 5, our newest model for complex, long-running work. Try anytime with /model.␍▎ Included in yourplan limits until Jun 22, then switch to usage credits to continue.␍
␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
?forshortcuts·←foragents◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍UsetheAskUserQuestiontooltoaskmewhetherIpreferredorblue.Offerexactlythosetwooptions.␍ ␍
[?25h[?2026l]0;⠂ Claude Code[?2026h[?25l␍❯ Use the AskUserQuestion tool to ask me whether I prefer red or blue. Offer exactly those two options. ␍␍✽ Simmering… ␍␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerrupt◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍…␍
[?25h[?2026l[?2026h[?25l␍…␍
[?25h[?2026l[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍✶␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l[?2026h[?25l␍·␍
[?25h[?2026l]0;⠐ Claude Code]0;⠐ Demander la couleur préférée red ou blue[?2026h[?25l␍S␍
[?25h[?2026l[?2026h[?25l␍i␍
[?25h[?2026l[?2026h[?25l␍Smm␍
[?25h[?2026l[?2026h[?25l␍ie␍
[?25h[?2026l[?2026h[?25l␍✢mr␍
[?25h[?2026l[?2026h[?25l␍mein␍
[?25h[?2026l[?2026h[?25l␍rg␍
[?25h[?2026l[?2026h[?25l␍*i…␍
[?25h[?2026l[?2026h[?25l␍n␍
[?25h[?2026l[?2026h[?25l␍✶g…␍
[?25h[?2026l[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍✽␍
[?25h[?2026l]0;⠂ Demander la couleur préférée red ou blue[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍✶␍
[?25h[?2026l[?2026h[?25l␍S␍
[?25h[?2026l[?2026h[?25l␍*i␍
[?25h[?2026l[?2026h[?25l␍m␍
[?25h[?2026l[?2026h[?25l␍✢Sm␍
[?25h[?2026l[?2026h[?25l␍imer␍
[?25h[?2026l[?2026h[?25l␍mi␍
[?25h[?2026l]0;⠐ Demander la couleur préférée red ou blue[?2026h[?25l␍·en␍
[?25h[?2026l[?2026h[?25l␍Simrin(2s · thinking with xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍m3thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍✢i↓ 38 tokens · thinking with xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍57thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍*S6␍
[?25h[?2026l[?2026h[?25l␍✶74␍
[?25h[?2026l[?2026h[?25l␍✻91thinking with xhigh effort␍
[?25h[?2026l]0;⠂ Demander la couleur préférée red ou blue[?2026h[?25l␍✽9thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍102 tokens · thinking with xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍44thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍6thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍✻19thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍✶2thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍36␍
[?25h[?2026l[?2026h[?25l␍*41␍
[?25h[?2026l]0;✳ Demander la couleur préférée red ou blue[?2026h[?25l␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍ ☐ Couleur ␍Préférez-vous le rouge ou le bleu ?␍␍❯ 1. Rouge␍ Vous préférez le rouge.␍
2.Bleu␍
Vouspréférezlebleu.␍
3.Typesomething.␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
4.Chataboutthis␍
␍
Entertoselect·↑/↓tonavigate·Esctocancel␍
[?2026l(B[?2026h␍ Rouge␍❯Bleu␍
[?2026l]0;⠂ Demander la couleur préférée red ou blue[?2026h╭───ClaudeCodev2.1.173─────────────────────────────────────────────────────────────────────────────────────────────╮␍
││Tipsforgettingstarted│␍
│WelcomebackDevon!│Run/inittocreateaCLAUDE.mdfilewithinstructionsforCla…│␍
││───────────────────────────────────────────────────────────────│␍
│ ▐▛███▜▌│What'snew│␍
│▝▜█████▛▘│FixedFable5modelnameswitha`[1m]`suffixnotbeingnorma…│␍
│ ▘▘▝▝│Fixedaspurious"sandboxdependenciesmissing"startupwarnin…│␍
│Opus4.8(1Mcontext)withxh…·ClaudeTeam·│Sub-agentscannowspawntheirownsub-agents(upto5levels…│␍
│Example│/release-notesformore│␍
│/tmp/spike-s3-ask2││␍
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯␍
␍
⚠2setupissues:MCP ·/doctor␍
␍
▎MeetFable5,ournewestmodelforcomplex,long-runningwork.Tryanytimewith/model.␍
▎IncludedinyourplanlimitsuntilJun22,thenswitchtousagecreditstocontinue.␍
␍
❯ Use the AskUserQuestion tool to ask me whether I prefer red or blue. Offer exactly those two options. ␍
␍
✻Bunning… (4s·↓215tokens)␍
␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerruptYou'veused96%ofyoursessionlimit·resets7pm(America/Lima)·/usage-creditstorequestmore␍
[?25h[?2026l[?2026h[?25l␍✶Bunning…␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍● User answered Claude's questions:␍ ⎿  · Préférez-vous le rouge ou le bleu ? → Bleu␍␍✢ Bunning… (4s · ↑215 tokens)␍␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerruptYou'veused96%ofyoursessionlimit·resets7pm(America/Lima)·/usage-creditstorequestmore␍
[?25h[?2026l[?2026h[?25l␍nn␍
[?25h[?2026l[?2026h[?25l␍·nig…5␍
[?25h[?2026l[?2026h[?25l␍n␍
[?25h[?2026l[?2026h[?25l␍g␍
[?25h[?2026l[?2026h[?25l␍…␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l]0;⠐ Demander la couleur préférée red ou blue[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍✶␍
[?25h[?2026l[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍6␍
[?25h[?2026l[?2026h[?25l␍✽␍
[?25h[?2026l[?2026h[?25l␍B␍
[?25h[?2026l[?2026h[?25l␍un␍
[?25h[?2026l[?2026h[?25l␍Bn␍
[?25h[?2026l[?2026h[?25l␍ui␍
[?25h[?2026l[?2026h[?25l␍nnng␍
[?25h[?2026l[?2026h[?25l␍✻i…␍
[?25h[?2026l[?2026h[?25l␍n␍
[?25h[?2026l]0;⠂ Demander la couleur préférée red ou blue[?2026h[?25l␍g␍
[?25h[?2026l[?2026h[?25l␍✶…␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l[?2026h[?25l␍7␍
[?25h[?2026l[?2026h[?25l␍·␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l]0;⠐ Demander la couleur préférée red ou blue[?2026h[?25l␍Bu␍
[?25h[?2026l[?2026h[?25l␍n␍
[?25h[?2026l[?2026h[?25l␍*Bn␍
[?25h[?2026l[?2026h[?25l␍ui␍
[?25h[?2026l[?2026h[?25l␍✶nnng␍
[?25h[?2026l[?2026h[?25l␍i…␍
[?25h[?2026l[?2026h[?25l␍✻n␍
[?25h[?2026l[?2026h[?25l␍g…␍
[?25h[?2026l[?2026h[?25l␍✽8␍
[?25h[?2026l[?2026h[?25l␍●Vous avez choisile bleu 🔵␍✽ Bunning… (running stop hook · 8s · ↓ 218 tokens)␍␍❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerruptYou'veused96%ofyoursessionlimit·resets7pm(America/Lima)·/usage-creditstorequestmore␍
[?25h[?2026l]0;✳ Demander la couleur préférée red ou blue[?2026h[?25l␍✻Sautéed fo 8s␍❯ ␍? for shortcuts · ← for agents␍
You'veused96%ofyoursessionlimit·resets7pm(America/Lima)·/usage-creditstorequestmore␍
[?25h[?2026l
-482
View File
@@ -1,482 +0,0 @@
78[?25h[?25l[?2004h[?1004h[?2031h[?2026h␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
Accessingworkspace:␍
␍
/tmp/spike-s3-deny2␍
␍
Quicksafetycheck:Isthisaprojectyoucreatedoroneyoutrust?(Likeyourowncode,awell-knownopensource␍
project,orworkfromyourteam).Ifnot,takeamomenttoreviewwhat'sinthisfolderfirst.␍
␍
ClaudeCode'llbeabletoread,edit,andexecutefileshere.␍
␍
]8;id=zaxmda;https://code.claude.com/docs/en/securitySecurity guide]8;;␍
␍
❯1.Yes,Itrustthisfolder␍
2.No,exit␍
␍
Entertoconfirm·Esctocancel␍
[?2026l[>0q[?2026h␍Yes, I trust this folder✔␍
[?2026l]0;✳ Claude Code[?2026h␍╭───Claude Codev2.1.173─────────────────────────────────────────────────────────────────────────────────────────────╮␍│ │ Tips for getting started │␍│ Welcome back Devon!│Run/inittocreateaCLAUDE.mdfilewithinstructionsforCla…│␍││───────────────────────────────────────────────────────────────│␍│  ▐▛███▜▌│What's new│␍│▝▜█████▛▘│FixedFable5modelnameswitha`[1m]`suffixnotbeingnorma…│␍│     ▘▘ ▝▝     │ Fixed a spurious "sandbox depenncies missing"startup warnin…│␍│ Opus 4.8 (1M context) with xh… · Claude Team ·  │ Sub-agnts can nowspawn their own sub-agents(upto5levels…│␍│Example│/release-notes for more│␍│   /tmp/spike-s3-deny2    │  │␍╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯␍␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍❯ Try "create a util logging.py that..."␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍? for shortcuts · ← for agents◉ xhigh · /effort␍[?25h[?2026l[?2026h[?25l␍␍
[?25h[?2026l[?2026h[?25l␍ ⚠ 2 setup issues: MCP · /doctor␍␍ ▎ Meet Fable 5, our newest model for complex, long-running work. Try anytime with /model.␍▎ Included in yourplan limits until Jun 22, then switch to usage credits to continue.␍
␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
?forshortcuts·←foragents◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍Runthisexactbashcommandandshowmeitsoutput:node-e"console.log('should-be-denied')"—donotdoanything␍ else.␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
◉xhigh·/effort␍
[?25h[?2026l]0;⠂ Claude Code[?2026h[?25l␍❯ Run this exact bash command and show me its output: node -e "console.log('should-be-denied')" — do not do anything  ␍ else. ␍␍✽ Unfurling… ␍␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerrupt◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍…␍
[?25h[?2026l[?2026h[?25l␍…␍
[?25h[?2026l[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍✶␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l[?2026h[?25l␍·␍
[?25h[?2026l]0;⠐ Claude Code[?2026h[?25l␍U␍
[?25h[?2026l]0;⠐ Execute Node.js command in bash[?2026h[?25l␍n␍
[?25h[?2026l[?2026h[?25l␍Ufu␍
[?25h[?2026l[?2026h[?25l␍nr␍
[?25h[?2026l[?2026h[?25l␍✢fl␍
[?25h[?2026l[?2026h[?25l␍urin␍
[?25h[?2026l[?2026h[?25l␍lg␍
[?25h[?2026l[?2026h[?25l␍*i…␍
[?25h[?2026l[?2026h[?25l␍n␍
[?25h[?2026l[?2026h[?25l␍✶g…␍
[?25h[?2026l[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍✽␍
[?25h[?2026l]0;⠂ Execute Node.js command in bash[?2026h[?25l␍rli␍
[?25h[?2026l[?2026h[?25l␍(2s · thinking with xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍✻uithinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍✶fl␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍✢nrthinking with xhigh effort␍
[?25h[?2026l]0;⠐ Execute Node.js command in bash[?2026h[?25l␍·Uuthinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍3␍
[?25h[?2026l[?2026h[?25l␍f↓ 25 tokens · thinking with xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍50thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍✢n76thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍8thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍*U93␍
[?25h[?2026l[?2026h[?25l␍✶104 tokens · thinking with xhigh efort)␍
[?25h[?2026l[?2026h[?25l␍✻16thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍●Bash(node -e "console.log('should-be-denied')")␍ ⎿  Waiting…␍␍✻ Unfurling… (3s · ↓116 tokens · thinking with xhigh effort)␍␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerrupt◉xhigh·/effort␍
[?25h[?2026l]0;⠂ Execute Node.js command in bash[?2026h[?25l␍ ␍Runn␍)␍
[?25h[?2026l[?2026h[?25l␍Unfurling…␍
[?25h[?2026l[?2026h[?25l␍✽Unfurling…35␍
[?25h[?2026l[?2026h[?25l␍●␍
[?25h[?2026l[?2026h[?25l␍●␍should-be-denied␍Unfurling…↑41 · thinking with xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍6thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍U50thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍4thought for 1s)␍
[?25h[?2026l[?2026h[?25l␍nf7␍
[?25h[?2026l[?2026h[?25l␍Uu␍
[?25h[?2026l[?2026h[?25l␍nr8␍
[?25h[?2026l[?2026h[?25l␍✻fl60␍
[?25h[?2026l[?2026h[?25l␍urin␍
[?25h[?2026l[?2026h[?25l␍✶lg1␍
[?25h[?2026l[?2026h[?25l␍i…2␍
[?25h[?2026l[?2026h[?25l␍*ng3␍
[?25h[?2026l[?2026h[?25l␍…4␍
[?25h[?2026l[?2026h[?25l␍✢5␍
[?25h[?2026l[?2026h[?25l␍6␍
[?25h[?2026l]0;⠐ Execute Node.js command in bash[?2026h[?25l␍7␍
[?25h[?2026l[?2026h[?25l␍·8␍
[?25h[?2026l[?2026h[?25l␍9␍
[?25h[?2026l[?2026h[?25l␍70␍
[?25h[?2026l[?2026h[?25l␍1␍
[?25h[?2026l[?2026h[?25l␍52␍
[?25h[?2026l[?2026h[?25l␍✢3␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍U␍
[?25h[?2026l[?2026h[?25l␍✶n␍
[?25h[?2026l[?2026h[?25l␍f␍
[?25h[?2026l[?2026h[?25l␍✻Unur␍
[?25h[?2026l[?2026h[?25l␍fur↓␍
[?25h[?2026l]0;⠂ Execute Node.js command in bash[?2026h[?25l␍●Voici la sortie dela commande :␍ should-be-denied␍␍✻ Unfurling… (5s · ↓ 173 tokens · thought for 1s)␍␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerrupt◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍4␍
[?25h[?2026l[?2026h[?25l␍Unfurling…running stop hook5s · ↓ 174 tokens · thought for 1s)␍
[?25h[?2026l]0;✳ Execute Node.js command in bash[?2026h[?25l␍✻Churned for 5s␍❯ ␍? for shortcuts · ← for agents␍
[?25h[?2026l[?2026h[?25l␍␍
You'veused94%ofyoursessionlimit·resets7pm(America/Lima)·/usage-creditstorequestmore␍
[?25h[?2026l[?2026h[?25l[?25h[?2026l[?1006l[?1003l[?1002l[?1000l(B[>4m[<u[?1004l[?2031l[?2004l[?25h78]0;
Resume this session with:
claude --resume 68c4db8a-2120-4ab9-9c03-cd3313675be5

-442
View File
@@ -1,442 +0,0 @@
78[?25h[?25l[?2004h[?1004h[?2031h[?2026h␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
Accessingworkspace:␍
␍
/tmp/spike-s3-bash2␍
␍
Quicksafetycheck:Isthisaprojectyoucreatedoroneyoutrust?(Likeyourowncode,awell-knownopensource␍
project,orworkfromyourteam).Ifnot,takeamomenttoreviewwhat'sinthisfolderfirst.␍
␍
ClaudeCode'llbeabletoread,edit,andexecutefileshere.␍
␍
]8;id=zaxmda;https://code.claude.com/docs/en/securitySecurity guide]8;;␍
␍
❯1.Yes,Itrustthisfolder␍
2.No,exit␍
␍
Entertoconfirm·Esctocancel␍
[?2026l[>0q[?2026h␍Yes, I trust this folder✔␍
[?2026l]0;✳ Claude Code[?2026h␍╭───Claude Codev2.1.173─────────────────────────────────────────────────────────────────────────────────────────────╮␍│ │ Tips for getting started │␍│ Welcome back Devon!│Run/inittocreateaCLAUDE.mdfilewithinstructionsforCla…│␍││───────────────────────────────────────────────────────────────│␍│  ▐▛███▜▌│What's new│␍│▝▜█████▛▘│FixedFable5modelnameswitha`[1m]`suffixnotbeingnorma…│␍│     ▘▘ ▝▝     │ Fixed a spurious "sandbox depenncies missing"startup warnin…│␍│ Opus 4.8 (1M context) with xh… · Claude Team ·  │ Sub-agnts can nowspawn their own sub-agents(upto5levels…│␍│Example│/release-notes for more│␍│   /tmp/spike-s3-bash2    │  │␍╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯␍␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍❯ Try "edit <filepath> to..."␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍? for shortcuts · ← for agents◉ xhigh · /effort␍[?25h[?2026l[?2026h[?25l␍␍
[?25h[?2026l[?2026h[?25l␍ ⚠ 2 setup issues: MCP · /doctor␍␍ ▎ Meet Fable 5, our newest model for complex, long-running work. Try anytime with /model.␍▎ Included in yourplan limits until Jun 22, then switch to usage credits to continue.␍
␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
?forshortcuts·←foragents◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍Runthisexactbashcommandandshowmeitsoutput:node-e"console.log('spike-s3-marker-xyz')"—donotdo␍ anything else.␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
◉xhigh·/effort␍
[?25h[?2026l]0;⠂ Claude Code[?2026h[?25l␍❯ Run this exact bash command and show me its output: node -e "console.log('spike-s3-marker-xyz')" — do not do anything ␍ else. ␍␍✽ Envisioning… ␍␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerrupt◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍ng…␍
[?25h[?2026l[?2026h[?25l␍n␍
[?25h[?2026l[?2026h[?25l␍g…␍
[?25h[?2026l[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍✶␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l]0;⠐ Claude Code[?2026h[?25l␍·␍
[?25h[?2026l[?2026h[?25l␍En␍
[?25h[?2026l[?2026h[?25l␍v␍
[?25h[?2026l[?2026h[?25l␍✢Ei␍
[?25h[?2026l[?2026h[?25l␍nvsi␍
[?25h[?2026l[?2026h[?25l␍io␍
[?25h[?2026l[?2026h[?25l␍*sn␍
[?25h[?2026l[?2026h[?25l␍ii␍
[?25h[?2026l]0;⠐ Exécuter commande Node.js et afficher résultat[?2026h[?25l␍✶onng␍
[?25h[?2026l[?2026h[?25l␍i…␍
[?25h[?2026l[?2026h[?25l␍✻n␍
[?25h[?2026l[?2026h[?25l␍g…␍
[?25h[?2026l[?2026h[?25l␍✽␍
[?25h[?2026l]0;⠂ Exécuter commande Node.js et afficher résultat[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍✶␍
[?25h[?2026l[?2026h[?25l␍sio␍
[?25h[?2026l[?2026h[?25l␍(2s · thinking with xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍✢iothinking with xhigh effort␍
[?25h[?2026l]0;⠐ Exécuter commande Node.js et afficher résultat[?2026h[?25l␍·vithinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍ns3thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍✢Eithinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍↓ 25 tokens · thinking with xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍●Bash(node -e "console.log('spike-s3-marker-xyz')")␍ ⎿  Waiting…␍␍✢ Envisioning… (3s · ↓25 tokens · thinking with xhigh effort)␍␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerrupt◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍*v50␍
[?25h[?2026l[?2026h[?25l␍ ␍Runn␍visioning…)␍
[?25h[?2026l[?2026h[?25l␍✶75␍
[?25h[?2026l[?2026h[?25l␍●␍spike-s3-marker-xyz␍Envisioning…↑88 · thinking with xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍✻95thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍101 tokens · thinking with xhigh efort)␍
[?25h[?2026l]0;⠂ Exécuter commande Node.js et afficher résultat[?2026h[?25l␍✽1thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍5␍
[?25h[?2026l[?2026h[?25l␍8thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍421thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍2thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍3␍
[?25h[?2026l[?2026h[?25l␍4thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍✻5thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍En6␍
[?25h[?2026l[?2026h[?25l␍✶v7thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍Ei8␍
[?25h[?2026l[?2026h[?25l␍thought for 1s)␍
[?25h[?2026l[?2026h[?25l␍*nvsi9␍
[?25h[?2026l[?2026h[?25l␍io30␍
[?25h[?2026l[?2026h[?25l␍✢sn1␍
[?25h[?2026l]0;⠐ Exécuter commande Node.js et afficher résultat[?2026h[?25l␍ii2␍
[?25h[?2026l[?2026h[?25l␍onng3␍
[?25h[?2026l[?2026h[?25l␍·i…4␍
[?25h[?2026l[?2026h[?25l␍n␍
[?25h[?2026l[?2026h[?25l␍g…6␍
[?25h[?2026l[?2026h[?25l␍5␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍↓␍
[?25h[?2026l[?2026h[?25l␍✶␍
[?25h[?2026l]0;⠂ Exécuter commande Node.js et afficher résultat[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍✽␍
[?25h[?2026l[?2026h[?25l␍●Sortie de la commande :␍ spike-s3-marker-xyz␍␍✽ Envisioning… (running stop hook · 5s · ↓ 136 tokens · thought for 1s)␍␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerrupt◉xhigh·/effort␍
[?25h[?2026l]0;✳ Exécuter commande Node.js et afficher résultat[?2026h[?25l␍✻Brewed for 5s␍❯ ␍? for shortcuts · ← for agents␍
[?25h[?2026l[?2026h[?25l␍␍
[?25h[?2026l[?1006l[?1003l[?1002l[?1000l(B[>4m[<u[?1004l[?2031l[?2004l[?25h78]0;
Resume this session with:
claude --resume 614ec96a-bc4c-42d7-a18e-eb5d291540f1

-469
View File
@@ -1,469 +0,0 @@
78[?25h[?25l[?2004h[?1004h[?2031h[?2026h␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
Accessingworkspace:␍
␍
/tmp/spike-s3-write2␍
␍
Quicksafetycheck:Isthisaprojectyoucreatedoroneyoutrust?(Likeyourowncode,awell-knownopensource␍
project,orworkfromyourteam).Ifnot,takeamomenttoreviewwhat'sinthisfolderfirst.␍
␍
ClaudeCode'llbeabletoread,edit,andexecutefileshere.␍
␍
]8;id=zaxmda;https://code.claude.com/docs/en/securitySecurity guide]8;;␍
␍
❯1.Yes,Itrustthisfolder␍
2.No,exit␍
␍
Entertoconfirm·Esctocancel␍
[?2026l[>0q[?2026h␍Yes, I trust this folder✔␍
[?2026l]0;✳ Claude Code[?2026h␍╭───Claude Codev2.1.173─────────────────────────────────────────────────────────────────────────────────────────────╮␍│ │ Tips for getting started │␍│ Welcome back Devon!│Run/inittocreateaCLAUDE.mdfilewithinstructionsforCla…│␍││───────────────────────────────────────────────────────────────│␍│  ▐▛███▜▌│What's new│␍│▝▜█████▛▘│FixedFable5modelnameswitha`[1m]`suffixnotbeingnorma…│␍│     ▘▘ ▝▝     │ Fixed a spurious "sandbox depenncies missing"startup warnin…│␍│ Opus 4.8 (1M context) with xh… · Claude Team ·  │ Sub-agnts can nowspawn their own sub-agents(upto5levels…│␍│Example│/release-notes for more│␍│   /tmp/spike-s3-write2    │  │␍╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯␍␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍❯ Try "edit <filepath> to..."␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍? for shortcuts · ← for agents◉ xhigh · /effort␍[?25h[?2026l[?2026h[?25l␍␍
[?25h[?2026l[?2026h[?25l␍ ⚠ 2 setup issues: MCP · /doctor␍␍ ▎ Meet Fable 5, our newest model for complex, long-running work. Try anytime with /model.␍▎ Included in yourplan limits until Jun 22, then switch to usage credits to continue.␍
␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ Createafilenameds3-edit.txtcontainingexactlythewordhello.UsetheWritetool.Donotdoanythingelse.␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
◉xhigh·/effort␍
[?25h[?2026l]0;⠂ Claude Code[?2026h[?25l␍❯ Create a file named s3-edit.txt containing exactly the word hello. Use the Write tool. Do not do anything else. ␍␍✽ Swooping… ␍␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerrupt◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍✶␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l[?2026h[?25l␍·␍
[?25h[?2026l]0;⠐ Claude Code[?2026h[?25l␍S␍
[?25h[?2026l[?2026h[?25l␍w␍
[?25h[?2026l[?2026h[?25l␍o␍
[?25h[?2026l[?2026h[?25l␍Swop␍
[?25h[?2026l[?2026h[?25l␍oi␍
[?25h[?2026l[?2026h[?25l␍✢on␍
[?25h[?2026l[?2026h[?25l␍pig…␍
[?25h[?2026l[?2026h[?25l␍n␍
[?25h[?2026l]0;⠐ Créer un fichier s3-edit.txt avec hello[?2026h[?25l␍*g␍
[?25h[?2026l[?2026h[?25l␍…␍
[?25h[?2026l[?2026h[?25l␍✶␍
[?25h[?2026l[?2026h[?25l␍✻␍
[?25h[?2026l[?2026h[?25l␍✽␍
[?25h[?2026l]0;⠂ Créer un fichier s3-edit.txt avec hello[?2026h[?25l␍pin␍
[?25h[?2026l[?2026h[?25l␍(1s · thinking with xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍on2thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍✻oithinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍✶wp␍
[?25h[?2026l[?2026h[?25l␍*↓ 25 tokens · tnking wih xhigh effort)␍
[?25h[?2026l[?2026h[?25l␍✢So57thinking with xhigh effort␍
[?25h[?2026l]0;⠐ Créer un fichier s3-edit.txt avec hello[?2026h[?25l␍·o68thinking with xhigh effort␍
[?25h[?2026l[?2026h[?25l␍76thinking with xhigh effort␍
[?25h[?2026l]0;✳ Créer un fichier s3-edit.txt avec hello[?2026h[?25l␍●Write(]8;id=vlvau2;file:///tmp/spike-s3-write2/s3-edit.txts3-edit.txt]8;;)␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍ Create file␍ s3-edit.txt␍╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌␍
 1hello␍
╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌␍
Doyouwanttocreates3-edit.txt?␍
❯1.Yes␍
2.Yes,allowalleditsduringthissession(shift+tab)␍
3.No␍
␍
Esctocancel·Tabtoamend␍
[?2026l]0;⠐ Créer un fichier s3-edit.txt avec hello[?2026h╭───ClaudeCodev2.1.173─────────────────────────────────────────────────────────────────────────────────────────────╮␍
││Tipsforgettingstarted│␍
│WelcomebackDevon!│Run/inittocreateaCLAUDE.mdfilewithinstructionsforCla…│␍
││───────────────────────────────────────────────────────────────│␍
│ ▐▛███▜▌│What'snew│␍
│▝▜█████▛▘│FixedFable5modelnameswitha`[1m]`suffixnotbeingnorma…│␍
│ ▘▘▝▝│Fixedaspurious"sandboxdependenciesmissing"startupwarnin…│␍
│Opus4.8(1Mcontext)withxh…·ClaudeTeam·│Sub-agentscannowspawntheirownsub-agents(upto5levels…│␍
│Example│/release-notesformore│␍
│/tmp/spike-s3-write2││␍
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯␍
␍
⚠2setupissues:MCP ·/doctor␍
␍
▎MeetFable5,ournewestmodelforcomplex,long-runningwork.Tryanytimewith/model.␍
▎IncludedinyourplanlimitsuntilJun22,thenswitchtousagecreditstocontinue.␍
␍
❯ Create a file named s3-edit.txt containing exactly the word hello. Use the Write tool. Do not do anything else. ␍
␍
●Write(]8;id=vlvau2;file:///tmp/spike-s3-write2/s3-edit.txts3-edit.txt]8;;)␍
␍
✻Seasoning… (3s·↓147tokens)␍
␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerruptYou'veused91%ofyoursessionlimit·resets7pm(America/Lima)·/usage-creditstorequestmore␍
[?25h[?2026l[?2026h[?25l␍✶Seasoning…␍
[?25h[?2026l[?2026h[?25l␍●␍ ⎿  Wrote1linestos3-edit.txt␍   1 hello␍✶ Seasoning… (3s · ↑ 147 tokens)␍␍❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerruptYou'veused91%ofyoursessionlimit·resets7pm(America/Lima)·/usage-creditstorequestmore␍
[?25h[?2026l[?2026h[?25l␍i…␍
[?25h[?2026l[?2026h[?25l␍*ng␍
[?25h[?2026l[?2026h[?25l␍…␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l[?2026h[?25l␍·␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l]0;⠂ Créer un fichier s3-edit.txt avec hello[?2026h[?25l␍4␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍S␍
[?25h[?2026l[?2026h[?25l␍✶e␍
[?25h[?2026l[?2026h[?25l␍a␍
[?25h[?2026l[?2026h[?25l␍✻Seso␍
[?25h[?2026l[?2026h[?25l␍an␍
[?25h[?2026l[?2026h[?25l␍si␍
[?25h[?2026l[?2026h[?25l␍✽on␍
[?25h[?2026l[?2026h[?25l␍nig…␍
[?25h[?2026l[?2026h[?25l␍n␍
[?25h[?2026l[?2026h[?25l␍g␍
[?25h[?2026l[?2026h[?25l␍…␍
[?25h[?2026l[?2026h[?25l␍✻␍
[?25h[?2026l]0;⠐ Créer un fichier s3-edit.txt avec hello[?2026h[?25l␍5␍
[?25h[?2026l[?2026h[?25l␍✶␍
[?25h[?2026l[?2026h[?25l␍*␍
[?25h[?2026l[?2026h[?25l␍✢␍
[?25h[?2026l[?2026h[?25l␍·␍
[?25h[?2026l[?2026h[?25l␍↓␍
[?25h[?2026l[?2026h[?25l␍…␍
[?25h[?2026l]0;⠂ Créer un fichier s3-edit.txt avec hello[?2026h[?25l␍●Fichier s3-edit.txt créé avec lecontenuhello.␍· Seasoning… (5s · ↓ 147 tokens)␍␍❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
esctointerruptYou'veused91%ofyoursessionlimit·resets7pm(America/Lima)·/usage-creditstorequestmore␍
[?25h[?2026l[?2026h[?25l␍✢g69␍
[?25h[?2026l[?2026h[?25l␍Seasoning…running stop hook · 6s · ↓149 tokens)␍
[?25h[?2026l]0;✳ Créer un fichier s3-edit.txt avec hello[?2026h[?25l␍✻Cooked for 6s␍❯ ␍? for shortcuts · ← for agents␍
You'veused91%ofyoursessionlimit·resets7pm(America/Lima)·/usage-creditstorequestmore␍
[?25h[?2026l[?2026h[?25l╭───ClaudeCodev2.1.173─────────────────────────────────────────────────────────────────────────────────────────────╮␍
││Tipsforgettingstarted│␍
│WelcomebackDevon!│Run/inittocreateaCLAUDE.mdfilewithinstructionsforCla…│␍
││───────────────────────────────────────────────────────────────│␍
│ ▐▛███▜▌│What'snew│␍
│▝▜█████▛▘│FixedFable5modelnameswitha`[1m]`suffixnotbeingnorma…│␍
│ ▘▘▝▝│Fixedaspurious"sandboxdependenciesmissing"startupwarnin…│␍
│Opus4.8(1Mcontext)withxh…·ClaudeTeam·│Sub-agentscannowspawntheirownsub-agents(upto5levels…│␍
│Example│/release-notesformore│␍
│/tmp/spike-s3-write2││␍
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯␍
␍
⚠2setupissues:MCP ·/doctor␍
␍
▎MeetFable5,ournewestmodelforcomplex,long-runningwork.Tryanytimewith/model.␍
▎IncludedinyourplanlimitsuntilJun22,thenswitchtousagecreditstocontinue.␍
␍
❯ Create a file named s3-edit.txt containing exactly the word hello. Use the Write tool. Do not do anything else. ␍
␍
●Write(]8;id=vlvau2;file:///tmp/spike-s3-write2/s3-edit.txts3-edit.txt]8;;)␍
 ⎿ Wrote1linestos3-edit.txt␍
 1hello␍
␍
●Fichiers3-edit.txtcrééaveclecontenuhello.␍
␍
✻Cookedfor6s␍
␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
?forshortcuts·←foragents◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍␍
[?25h[?2026l[?1006l[?1003l[?1002l[?1000l(B[>4m[<u[?1004l[?2031l[?2004l[?25h78]0;
Resume this session with:
claude --resume 4c722fa4-a25b-4cbd-9435-d98ec8cf2a50

-37
View File
@@ -1,37 +0,0 @@
78[?25h[?25l[?2004h[?1004h[?2031h[?2026h␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
Accessingworkspace:␍
␍
/tmp/spike-s3-trust␍
␍
Quicksafetycheck:Isthisaprojectyoucreatedoroneyoutrust?(Likeyourowncode,awell-knownopensource␍
project,orworkfromyourteam).Ifnot,takeamomenttoreviewwhat'sinthisfolderfirst.␍
␍
ClaudeCode'llbeabletoread,edit,andexecutefileshere.␍
␍
]8;id=zaxmda;https://code.claude.com/docs/en/securitySecurity guide]8;;␍
␍
❯1.Yes,Itrustthisfolder␍
2.No,exit␍
␍
Entertoconfirm·Esctocancel␍
[?2026l[>0q[?2026h␍Yes, I trust this folder✔␍
[?2026l]0;✳ Claude Code[?2026h␍╭───Claude Codev2.1.173─────────────────────────────────────────────────────────────────────────────────────────────╮␍│ │ Tips for getting started │␍│ Welcome back Devon!│Run/inittocreateaCLAUDE.mdfilewithinstructionsforCla…│␍││───────────────────────────────────────────────────────────────│␍│  ▐▛███▜▌│What's new│␍│▝▜█████▛▘│FixedFable5modelnameswitha`[1m]`suffixnotbeingnorma…│␍│     ▘▘ ▝▝     │ Fixed a spurious "sandbox depenncies missing"startup warnin…│␍│ Opus 4.8 (1M context) with xh… · Claude Team ·  │ Sub-agnts can nowspawn their own sub-agents(upto5levels…│␍│Example│/release-notes for more│␍│   /tmp/spike-s3-trust    │  │␍╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯␍␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍❯ Try "create a util logging.py that..."␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍? for shortcuts · ← for agents◉ xhigh · /effort␍[?25h[?2026l[?2026h[?25l␍␍
[?25h[?2026l[?2026h[?25l␍ ⚠ 2 setup issues: MCP · /doctor␍␍ ▎ Meet Fable 5, our newest model for complex, long-running work. Try anytime with /model.␍▎ Included in yourplan limits until Jun 22, then switch to usage credits to continue.␍
␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
?forshortcuts·←foragents◉xhigh·/effort␍
[?25h[?2026l[?2026h[?25l␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍❯ ␍────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍ ? for shortcuts ·← for agents ◉ xhigh · /effort␍␍␍␍␍␍[?25h[?2026l[?2026h[?25l␍ ⚠ 2 setup issues: MCP · /doctor␍␍ ▎ Meet Fable 5, our newest model for complex, long-running work. Try anytime with /model.␍▎ Included in yourplan limits until Jun 22, then switch to usage credits to continue.␍
␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
❯ ␍
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────␍
?forshortcuts·←foragents◉xhigh·/effort␍
[?25h[?2026l[?1006l[?1003l[?1002l[?1000l(B[>4m[<u[?1004l[?2031l[?2004l[?25h78]0;
-143
View File
@@ -1,143 +0,0 @@
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { buildApp, type AppBundle } from '../src/app.js';
import { openDb, type Db } from '../src/db/index.js';
import type { Config } from '../src/config.js';
import type { FsListResponse } from '@arboretum/shared';
// Mêmes stubs que app.e2e : pas de vrai claude ni de vrai PTY en CI.
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
class FakePty {
pid = 424242;
write = vi.fn();
resize = vi.fn();
pause = vi.fn();
resume = vi.fn();
kill = vi.fn();
onData(): { dispose: () => void } {
return { dispose: () => {} };
}
onExit(): { dispose: () => void } {
return { dispose: () => {} };
}
}
return { default: { spawn: (): FakePty => new FakePty() } };
});
process.env.ARBORETUM_LOG = 'silent';
let dir: string;
let root: string;
let bundle: AppBundle;
let db: Db;
let token: string;
const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` });
beforeAll(() => {
dir = mkdtempSync(join(tmpdir(), 'arboretum-fs-'));
// Arbo de test : root/{alpha, Beta, .hidden, a-repo/.git, file.txt}
root = join(dir, 'root');
mkdirSync(join(root, 'alpha'), { recursive: true });
mkdirSync(join(root, 'Beta'), { recursive: true });
mkdirSync(join(root, '.hidden'), { recursive: true });
mkdirSync(join(root, 'a-repo', '.git'), { recursive: true });
writeFileSync(join(root, 'file.txt'), 'x');
const dbPath = join(dir, 'fs.db');
db = openDb(dbPath);
const config: Config = {
port: 7317,
bind: '127.0.0.1',
dbPath,
dataDir: dir,
allowedOrigins: [],
printToken: false,
claudeProjectsDir: join(dir, 'claude', 'projects'),
claudeSessionsDir: join(dir, 'claude', 'sessions'),
vapidContact: 'mailto:test@localhost',
};
bundle = buildApp(config, db, '0.0.0-test');
const t = bundle.auth.ensureBootstrapToken();
if (!t) throw new Error('bootstrap token attendu sur une base vierge');
token = t;
});
afterAll(async () => {
await bundle.app.close();
db.close();
rmSync(dir, { recursive: true, force: true });
});
describe('GET /api/v1/fs/list', () => {
it('liste les sous-dossiers triés, masque les dotfiles et les fichiers', async () => {
const res = await bundle.app.inject({ method: 'GET', url: `/api/v1/fs/list?path=${encodeURIComponent(root)}`, headers: auth() });
expect(res.statusCode).toBe(200);
const body = res.json() as FsListResponse;
const names = body.entries.map((e) => e.name);
expect(names).toEqual(['a-repo', 'alpha', 'Beta']); // tri insensible à la casse, fichiers/dotfiles exclus
expect(body.path).toBe(root);
expect(body.parent).toBe(dir);
expect(typeof body.home).toBe('string');
});
it('showHidden=1 inclut les dossiers cachés', async () => {
const res = await bundle.app.inject({ method: 'GET', url: `/api/v1/fs/list?path=${encodeURIComponent(root)}&showHidden=1`, headers: auth() });
const body = res.json() as FsListResponse;
expect(body.entries.map((e) => e.name)).toContain('.hidden');
});
it('markRepos=1 annote le dossier contenant un .git', async () => {
const res = await bundle.app.inject({ method: 'GET', url: `/api/v1/fs/list?path=${encodeURIComponent(root)}&markRepos=1`, headers: auth() });
const body = res.json() as FsListResponse;
expect(body.entries.find((e) => e.name === 'a-repo')?.isRepo).toBe(true);
expect(body.entries.find((e) => e.name === 'alpha')?.isRepo).toBeUndefined();
});
it('sans markRepos, aucune annotation isRepo', async () => {
const res = await bundle.app.inject({ method: 'GET', url: `/api/v1/fs/list?path=${encodeURIComponent(root)}`, headers: auth() });
const body = res.json() as FsListResponse;
expect(body.entries.every((e) => e.isRepo === undefined)).toBe(true);
});
it('path absent → liste le home (réponse 200 cohérente)', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/fs/list', headers: auth() });
expect(res.statusCode).toBe(200);
const body = res.json() as FsListResponse;
expect(body.path).toBe(body.home);
});
it('chemin relatif → 400 BAD_PATH', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/fs/list?path=relatif/x', headers: auth() });
expect(res.statusCode).toBe(400);
expect(res.json()).toMatchObject({ error: { code: 'BAD_PATH' } });
});
it('échappement par `..` neutralisé : resolve clampe, pas de fuite (200 sur un dossier réel)', async () => {
// `<root>/../..` résout vers un ancêtre réel : la requête réussit mais ne contient jamais de `..`.
const res = await bundle.app.inject({ method: 'GET', url: `/api/v1/fs/list?path=${encodeURIComponent(join(root, '..', '..'))}`, headers: auth() });
expect(res.statusCode).toBe(200);
expect((res.json() as FsListResponse).path).not.toContain('..');
});
it('chemin inexistant → 404 NOT_FOUND', async () => {
const res = await bundle.app.inject({ method: 'GET', url: `/api/v1/fs/list?path=${encodeURIComponent(join(root, 'nope-xyz'))}`, headers: auth() });
expect(res.statusCode).toBe(404);
expect(res.json()).toMatchObject({ error: { code: 'NOT_FOUND' } });
});
it('cible non-dossier → 400 NOT_A_DIRECTORY', async () => {
const res = await bundle.app.inject({ method: 'GET', url: `/api/v1/fs/list?path=${encodeURIComponent(join(root, 'file.txt'))}`, headers: auth() });
expect(res.statusCode).toBe(400);
expect(res.json()).toMatchObject({ error: { code: 'NOT_A_DIRECTORY' } });
});
it('sans authentification → 401', async () => {
const res = await bundle.app.inject({ method: 'GET', url: `/api/v1/fs/list?path=${encodeURIComponent(root)}` });
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: { code: 'UNAUTHORIZED' } });
});
});
-196
View File
@@ -1,196 +0,0 @@
import { describe, expect, it, afterEach } from 'vitest';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve, basename, dirname } from 'node:path';
import {
parseWorktreePorcelain,
isValidBranchName,
isSafeAbsolutePath,
isRepo,
listWorktrees,
worktreeStatus,
addWorktree,
removeWorktree,
pruneWorktrees,
switchBranch,
isDirtyWorktreeError,
branchExists,
currentBranch,
listBranches,
commitAll,
} from '../src/core/git.js';
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
function makeTmpRepo(): string {
const dir = mkdtempSync(join(tmpdir(), 'arb-git-'));
dirs.push(dir);
const run = (...args: string[]): void => void execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
run('init', '-b', 'main');
run('config', 'user.email', 'test@arboretum.dev');
run('config', 'user.name', 'Test');
writeFileSync(join(dir, 'README.md'), '# test\n');
run('add', '-A');
run('commit', '-m', 'init');
return dir;
}
describe('parseWorktreePorcelain', () => {
it('parse le bloc principal, détaché, locked et prunable', () => {
const out = [
'worktree /repo',
'HEAD abc123',
'branch refs/heads/main',
'',
'worktree /repo-wt-x',
'HEAD def456',
'detached',
'locked reason here',
'',
'worktree /repo-wt-gone',
'HEAD 000',
'prunable gitdir file points to non-existent location',
'', // bloc final terminé par une ligne vide
].join('\n');
const wts = parseWorktreePorcelain(out);
expect(wts).toHaveLength(3);
expect(wts[0]).toMatchObject({ path: '/repo', branch: 'main', detached: false });
expect(wts[1]).toMatchObject({ path: '/repo-wt-x', detached: true, locked: true, branch: null });
expect(wts[2]).toMatchObject({ path: '/repo-wt-gone', prunable: true });
});
it('tolère un bloc final sans ligne vide', () => {
const wts = parseWorktreePorcelain('worktree /a\nHEAD x\nbranch refs/heads/dev');
expect(wts).toEqual([
{ path: '/a', head: 'x', branch: 'dev', detached: false, locked: false, prunable: false, bare: false },
]);
});
});
describe('validation', () => {
it('isValidBranchName', () => {
expect(isValidBranchName('feature/foo-1.2')).toBe(true);
expect(isValidBranchName('-foo')).toBe(false);
expect(isValidBranchName('a..b')).toBe(false);
expect(isValidBranchName('a/')).toBe(false);
expect(isValidBranchName('x.lock')).toBe(false);
expect(isValidBranchName('a b')).toBe(false);
});
it('isSafeAbsolutePath', () => {
expect(isSafeAbsolutePath('/home/u/proj-wt-x')).toBe(true);
expect(isSafeAbsolutePath('relative/x')).toBe(false);
expect(isSafeAbsolutePath('/home/u/../etc')).toBe(false);
});
});
describe('opérations git (repo tmp réel)', () => {
it('isRepo : racine vs non-repo', async () => {
const repo = makeTmpRepo();
expect(await isRepo(repo)).toBe(true);
const notRepo = mkdtempSync(join(tmpdir(), 'arb-nogit-'));
dirs.push(notRepo);
expect(await isRepo(notRepo)).toBe(false);
});
it('add → list → status (dirty) → remove (refus dirty puis force)', async () => {
const repo = makeTmpRepo();
const wtPath = join(dirname(repo), `${basename(repo)}-wt-feat`);
dirs.push(wtPath);
await addWorktree(repo, { path: wtPath, branch: 'feat', mode: 'create' });
const list = await listWorktrees(repo);
const wt = list.find((w) => resolve(w.path) === resolve(wtPath));
expect(wt?.branch).toBe('feat');
// worktree propre
expect((await worktreeStatus(wtPath)).dirtyCount).toBe(0);
// un fichier non suivi → dirty
writeFileSync(join(wtPath, 'scratch.txt'), 'wip\n');
expect((await worktreeStatus(wtPath)).dirtyCount).toBeGreaterThan(0);
// remove sans --force refusé (worktree sale)
let dirtyErr: unknown;
await removeWorktree(repo, wtPath, false).catch((e) => (dirtyErr = e));
expect(dirtyErr).toBeDefined();
expect(isDirtyWorktreeError(dirtyErr)).toBe(true);
// remove --force réussit
await removeWorktree(repo, wtPath, true);
expect((await listWorktrees(repo)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
});
it('switchBranch : create=true crée une branche, create=false bascule sur une existante', async () => {
const repo = makeTmpRepo();
const cur = (): string => execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim();
await switchBranch(repo, { branch: 'feature/new', create: true });
expect(cur()).toBe('feature/new');
await switchBranch(repo, { branch: 'main', create: false });
expect(cur()).toBe('main');
// créer une branche déjà existante échoue (git refuse).
await expect(switchBranch(repo, { branch: 'feature/new', create: true })).rejects.toBeDefined();
});
it('prune retire un worktree dont le dossier a disparu', async () => {
const repo = makeTmpRepo();
const wtPath = join(dirname(repo), `${basename(repo)}-wt-gone`);
await addWorktree(repo, { path: wtPath, branch: 'gone', mode: 'create' });
rmSync(wtPath, { recursive: true, force: true }); // suppression "à la main"
await pruneWorktrees(repo);
expect((await listWorktrees(repo)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
});
});
describe('branche : existence, liste, courante, commit', () => {
it('branchExists / currentBranch / listBranches', async () => {
const repo = makeTmpRepo();
expect(await currentBranch(repo)).toBe('main');
expect(await branchExists(repo, 'main')).toEqual({ local: true, remote: false });
expect(await branchExists(repo, 'nope')).toEqual({ local: false, remote: false });
execFileSync('git', ['branch', 'dev'], { cwd: repo });
const b = await listBranches(repo);
expect(b.local).toContain('main');
expect(b.local).toContain('dev');
expect(b.remote).toEqual([]);
});
it('commitAll : add -A + commit, fait baisser dirtyCount à 0', async () => {
const repo = makeTmpRepo();
writeFileSync(join(repo, 'new.txt'), 'hello\n');
expect((await worktreeStatus(repo)).dirtyCount).toBeGreaterThan(0);
await commitAll(repo, 'add new.txt');
expect((await worktreeStatus(repo)).dirtyCount).toBe(0);
});
});
describe('addWorktree : résolution auto (créer / réutiliser)', () => {
it('auto crée la branche si absente, la réutilise si présente', async () => {
const repo = makeTmpRepo();
// branche absente → création (renvoie "created")
const wt1 = join(dirname(repo), `${basename(repo)}-wt-feat`);
dirs.push(wt1);
expect(await addWorktree(repo, { path: wt1, branch: 'feat', mode: 'auto' })).toBe('created');
expect((await listWorktrees(repo)).find((w) => resolve(w.path) === resolve(wt1))?.branch).toBe('feat');
// la même branche existe désormais ; un AUTRE worktree dessus → checkout (renvoie "reused")
await removeWorktree(repo, wt1, true); // libère la branche
const wt2 = join(dirname(repo), `${basename(repo)}-wt-feat2`);
dirs.push(wt2);
expect(await addWorktree(repo, { path: wt2, branch: 'feat', mode: 'auto' })).toBe('reused');
});
it('mode create échoue si la branche existe déjà', async () => {
const repo = makeTmpRepo();
execFileSync('git', ['branch', 'dup'], { cwd: repo });
const wt = join(dirname(repo), `${basename(repo)}-wt-dup`);
dirs.push(wt);
await expect(addWorktree(repo, { path: wt, branch: 'dup', mode: 'create' })).rejects.toBeDefined();
});
});
-45
View File
@@ -1,45 +0,0 @@
import { describe, expect, it } from 'vitest';
import { commonAncestorDir, resolveGroupCwd } from '../src/core/group-session.js';
describe('commonAncestorDir', () => {
it('renvoie le chemin lui-même pour un seul répertoire', () => {
expect(commonAncestorDir(['/home/johan/WebstormProjects/arboretum'])).toBe('/home/johan/WebstormProjects/arboretum');
});
it('renvoie le parent commun de deux siblings', () => {
expect(commonAncestorDir(['/p/a', '/p/b'])).toBe('/p');
});
it('gère un répertoire ancêtre d’un autre', () => {
expect(commonAncestorDir(['/p/a', '/p/a/b'])).toBe('/p/a');
});
it('compare par segments, pas par préfixe de chaîne', () => {
// /a/bc n'est PAS un ancêtre de /a/bcd : ancêtre commun = /a
expect(commonAncestorDir(['/a/bc', '/a/bcd'])).toBe('/a');
});
it('renvoie la racine quand aucun segment n’est commun', () => {
expect(commonAncestorDir(['/x/a', '/y/b'])).toBe('/');
});
});
describe('resolveGroupCwd', () => {
it('mono-repo : cwd = le repo, addDirs sera filtré à vide par PtyManager', () => {
const { cwd, addDirs } = resolveGroupCwd(['/p/a']);
expect(cwd).toBe('/p/a');
expect(addDirs).toEqual(['/p/a']);
});
it('multi-repos sous un parent commun : cwd = parent, addDirs = tous les repos', () => {
const dirs = ['/home/johan/WebstormProjects/beehelp_lambdas', '/home/johan/WebstormProjects/beehelp_api'];
const { cwd, addDirs } = resolveGroupCwd(dirs);
expect(cwd).toBe('/home/johan/WebstormProjects');
expect(addDirs).toEqual(dirs);
});
it('garde-fou : repos sur des racines différentes → retombe sur le premier répertoire', () => {
const { cwd } = resolveGroupCwd(['/x/a', '/y/b']);
expect(cwd).toBe('/x/a');
});
});
-111
View File
@@ -1,111 +0,0 @@
import { describe, expect, it, beforeEach, vi } from 'vitest';
import { GroupManager } from '../src/core/group-manager.js';
import { openDb, type Db } from '../src/db/index.js';
/** Insère un repo minimal directement (le GroupManager n'a besoin que de repos.id). */
function insertRepo(db: Db, id: string, path: string): void {
db.prepare(
"INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at) VALUES (?, ?, ?, NULL, '[]', 0, ?)",
).run(id, path, id, new Date().toISOString());
}
describe('GroupManager', () => {
let db: Db;
let gm: GroupManager;
beforeEach(() => {
db = openDb(':memory:');
insertRepo(db, 'repo-a', '/tmp/a');
insertRepo(db, 'repo-b', '/tmp/b');
gm = new GroupManager(db);
});
it('createGroup : groupe vide, persisté, événement group_update émis', () => {
const spy = vi.fn();
gm.on('group_update', spy);
const g = gm.createGroup({ label: 'Sprint 42' });
expect(g).toMatchObject({ label: 'Sprint 42', description: null, color: null, repoIds: [] });
expect(gm.listGroups()).toHaveLength(1);
expect(spy).toHaveBeenCalledWith(expect.objectContaining({ id: g.id }));
});
it('createGroup : repoIds initiaux ordonnés et dédoublonnés', () => {
const g = gm.createGroup({ label: 'Eco', repoIds: ['repo-b', 'repo-a', 'repo-b'] });
expect(g.repoIds).toEqual(['repo-b', 'repo-a']);
});
it('createGroup : repoId inexistant → 404', () => {
expect(() => gm.createGroup({ label: 'X', repoIds: ['nope'] })).toThrow(
expect.objectContaining({ statusCode: 404, code: 'REPO_NOT_FOUND' }),
);
expect(gm.listGroups()).toHaveLength(0); // rollback de la transaction
});
it('createGroup : validations (label vide / trop long, couleur invalide)', () => {
expect(() => gm.createGroup({ label: ' ' })).toThrow(expect.objectContaining({ statusCode: 400 }));
expect(() => gm.createGroup({ label: 'x'.repeat(101) })).toThrow(expect.objectContaining({ statusCode: 400 }));
expect(() => gm.createGroup({ label: 'X', color: 'red' })).toThrow(expect.objectContaining({ statusCode: 400 }));
expect(gm.createGroup({ label: 'X', color: '#4f46e5' }).color).toBe('#4f46e5');
});
it('getGroup : id inconnu → 404', () => {
expect(() => gm.getGroup('nope')).toThrow(expect.objectContaining({ statusCode: 404, code: 'NOT_FOUND' }));
});
it('updateGroup : modifie label/description/color et bump updatedAt', () => {
const g = gm.createGroup({ label: 'A' });
const updated = gm.updateGroup(g.id, { label: 'B', description: 'hello', color: '#000000' });
expect(updated).toMatchObject({ label: 'B', description: 'hello', color: '#000000' });
expect(gm.updateGroup(g.id, { description: '' }).description).toBeNull(); // '' → null
});
it('addRepo : idempotent (PRIMARY KEY), émet group_update', () => {
const g = gm.createGroup({ label: 'A' });
const spy = vi.fn();
gm.on('group_update', spy);
expect(gm.addRepo(g.id, 'repo-a').repoIds).toEqual(['repo-a']);
expect(gm.addRepo(g.id, 'repo-a').repoIds).toEqual(['repo-a']); // pas de doublon
expect(gm.addRepo(g.id, 'repo-b').repoIds).toEqual(['repo-a', 'repo-b']);
expect(spy).toHaveBeenCalledTimes(3);
});
it('addRepo : groupe ou repo inexistant → 404', () => {
const g = gm.createGroup({ label: 'A' });
expect(() => gm.addRepo('nope', 'repo-a')).toThrow(expect.objectContaining({ statusCode: 404, code: 'NOT_FOUND' }));
expect(() => gm.addRepo(g.id, 'nope')).toThrow(expect.objectContaining({ statusCode: 404, code: 'REPO_NOT_FOUND' }));
});
it('removeRepo : idempotent (retrait d’un repo absent = no-op)', () => {
const g = gm.createGroup({ label: 'A', repoIds: ['repo-a'] });
expect(gm.removeRepo(g.id, 'repo-a').repoIds).toEqual([]);
expect(gm.removeRepo(g.id, 'repo-a').repoIds).toEqual([]); // déjà absent → succès
});
it('deleteGroup : true + group_removed ; id inconnu → false', () => {
const g = gm.createGroup({ label: 'A' });
const spy = vi.fn();
gm.on('group_removed', spy);
expect(gm.deleteGroup(g.id)).toBe(true);
expect(spy).toHaveBeenCalledWith(g.id);
expect(gm.deleteGroup(g.id)).toBe(false);
expect(gm.listGroups()).toHaveLength(0);
});
it('CASCADE : supprimer un repo purge la membership (PRAGMA foreign_keys = ON)', () => {
const g = gm.createGroup({ label: 'A', repoIds: ['repo-a', 'repo-b'] });
expect(gm.getGroup(g.id).repoIds).toEqual(['repo-a', 'repo-b']);
db.prepare('DELETE FROM repos WHERE id = ?').run('repo-a');
expect(gm.getGroup(g.id).repoIds).toEqual(['repo-b']);
});
it('deleteGroup : désorpheline le group_id des sessions de groupe (P6)', () => {
const g = gm.createGroup({ label: 'A' });
// session de groupe liée à g (insérée directement, comme le ferait PtyManager.spawn).
db.prepare(
'INSERT INTO sessions (id, cwd, command, created_at, group_id) VALUES (?, ?, ?, ?, ?)',
).run('sess-1', '/tmp/a', 'claude', new Date().toISOString(), g.id);
expect(gm.deleteGroup(g.id)).toBe(true);
const row = db.prepare('SELECT group_id FROM sessions WHERE id = ?').get('sess-1') as { group_id: string | null };
expect(row.group_id).toBeNull();
});
});
+1 -1
View File
@@ -13,7 +13,7 @@ function writeJsonl(projectsDir: string, cwd: string, sid: string, lines: object
describe('munge', () => {
it('reproduit le nom de dossier ~/.claude/projects', () => {
expect(munge('/home/x/My Project!')).toBe('-home-x-My-Project-');
expect(munge('/home/user/projects/demo')).toBe('-home-user-projects-demo');
expect(munge('/home/johan/WebstormProjects/arboretum')).toBe('-home-johan-WebstormProjects-arboretum');
});
});
+1 -176
View File
@@ -4,7 +4,6 @@ import { join } from 'node:path';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { FLOW, REPLAY_TAIL_BYTES, type SessionSummary } from '@arboretum/shared';
import { PtyManager, type ClientBinding } from '../src/core/pty-manager.js';
import type { PushPayload, PushService } from '../src/core/push-service.js';
import { openDb, type Db } from '../src/db/index.js';
// resolveClaudeBin() fait `which claude` : on le stub pour ne pas dépendre d'un claude réel en PATH.
@@ -74,8 +73,6 @@ type BindingSpies = ClientBinding & {
onControlChanged: Mock<(controlling: boolean) => void>;
};
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
let channelSeq = 1;
function makeBinding(mode: 'interactive' | 'observer'): BindingSpies {
return {
@@ -187,34 +184,6 @@ describe('PtyManager (pty mocké)', () => {
expect(listed).toMatchObject({ live: false, resumable: true, claudeSessionId: 'sid-known' });
});
it('resumeTargetById : session claude morte → cwd + claudeSessionId + groupe ; null sinon', () => {
const d1 = mkdtempSync(join(tmpdir(), 'arb-rt-'));
try {
const summary = manager.spawn({ cwd, command: 'claude', addDirs: [d1], groupId: 'grpR' });
db.prepare('UPDATE sessions SET claude_session_id = ? WHERE id = ?').run('cs-resume', summary.id);
// vivante → null (resume direct interdit ; fork passe par le même chemin)
expect(manager.resumeTargetById(summary.id)).toBeNull();
lastPty().emitExit(0);
// morte avec claudeSessionId connu → cible complète
expect(manager.resumeTargetById(summary.id)).toEqual({
cwd,
claudeSessionId: 'cs-resume',
addedDirs: [d1],
groupId: 'grpR',
});
// id inconnu → null
expect(manager.resumeTargetById('nope')).toBeNull();
} finally {
rmSync(d1, { recursive: true, force: true });
}
});
it('resumeTargetById : session bash morte (sans claudeSessionId) → null', () => {
const { summary, pty } = spawnBash();
pty.emitExit(0);
expect(manager.resumeTargetById(summary.id)).toBeNull();
});
it('capture le claudeSessionId via le registre (poll par pid) → findLiveByClaudeSessionId', () => {
vi.useFakeTimers();
const sessDir = mkdtempSync(join(tmpdir(), 'arb-sess-'));
@@ -243,11 +212,7 @@ describe('PtyManager (pty mocké)', () => {
it('resync à l’attach = queue du ring (REPLAY_TAIL_BYTES max)', () => {
const { summary, pty } = spawnBash();
// on écrit volontairement PLUS que REPLAY_TAIL_BYTES (mais < RING_CAPACITY) pour vérifier
// le plafonnement de la queue rejouée. Tailles dérivées de la constante → robuste aux bumps.
const chunkSize = 256 * 1024;
const chunkCount = Math.ceil(REPLAY_TAIL_BYTES / chunkSize) + 2;
const chunks = Array.from({ length: chunkCount }, (_, i) => String.fromCharCode(65 + (i % 26)).repeat(chunkSize));
const chunks = ['A', 'B', 'C'].map((c) => c.repeat(100 * 1024));
for (const c of chunks) pty.emitData(c);
const b = makeBinding('interactive');
@@ -325,97 +290,6 @@ describe('PtyManager (pty mocké)', () => {
});
});
describe('answer (P4-A)', () => {
it('select → "N\\r" si l’option existe, deny → Esc ; rejets gone/not_controlling/invalid', async () => {
const sessDir = mkdtempSync(join(tmpdir(), 'arb-answer-'));
const m = new PtyManager(db, sessDir);
try {
const summary = m.spawn({ cwd, command: 'claude' });
const p = lastPty();
// écran : dialogue de permission à 2 options (la 1re est sélectionnée ❯)
p.emitData('\x1b[2J\x1b[HDo you want to create x.txt?\r\n❯ 1. Yes\r\n2. No\r\nEsc to cancel\r\n');
writeFileSync(
join(sessDir, `${p.pid}.json`),
JSON.stringify({ pid: p.pid, procStart: '1', sessionId: 'sid', cwd, status: 'waiting', waitingFor: 'permission prompt' }),
);
await sleep(260); // laisse le screen reader + le debounce (200ms) du tracker établir l’état
const a = makeBinding('interactive');
m.attach(summary.id, a, 80, 24);
p.write.mockClear();
// option inexistante → invalid (anti-frappe fantôme), aucun write
expect(m.answer(summary.id, a, 'select', 9)).toBe('invalid');
expect(p.write).not.toHaveBeenCalled();
// option existante → "1\r"
expect(m.answer(summary.id, a, 'select', 1)).toBe('ok');
expect(p.write).toHaveBeenCalledWith('1\r');
// deny → Esc
expect(m.answer(summary.id, a, 'deny')).toBe('ok');
expect(p.write).toHaveBeenCalledWith('\x1b');
// observer read-only
const obs = makeBinding('observer');
m.attach(summary.id, obs, 80, 24);
expect(m.answer(summary.id, obs, 'deny')).toBe('not_controlling');
// session inconnue → gone
expect(m.answer('nope', a, 'deny')).toBe('gone');
} finally {
m.shutdown();
rmSync(sessDir, { recursive: true, force: true });
}
});
it('session sans état waiting (bash, pas de tracker) → invalid', () => {
const { summary, pty } = spawnBash();
const a = makeBinding('interactive');
manager.attach(summary.id, a, 80, 24);
pty.write.mockClear();
expect(manager.answer(summary.id, a, 'deny')).toBe('invalid');
expect(manager.answer(summary.id, a, 'select', 1)).toBe('invalid');
expect(pty.write).not.toHaveBeenCalled();
});
});
describe('push trigger (P4-B)', () => {
it('une notif sur le front montant busy→waiting, après le debounce ; pas de notif en restant busy', async () => {
const sessDir = mkdtempSync(join(tmpdir(), 'arb-push-'));
const notifies: PushPayload[] = [];
const fakePush = {
notify: async (p: PushPayload) => {
notifies.push(p);
},
} as unknown as PushService;
const m = new PtyManager(db, sessDir, fakePush);
try {
const summary = m.spawn({ cwd, command: 'claude' });
const p = lastPty();
const regFile = join(sessDir, `${p.pid}.json`);
const writeReg = (status: string, waitingFor?: string): void =>
writeFileSync(regFile, JSON.stringify({ pid: p.pid, procStart: '1', sessionId: 'sid', cwd, status, ...(waitingFor ? { waitingFor } : {}) }));
// busy : front montant vers busy, pas de notif
writeReg('busy');
p.emitData('working…');
await sleep(260);
expect(notifies).toHaveLength(0);
// waiting + écran permission : front montant vers waiting → planifie la notif (debounce 1500ms)
writeReg('waiting', 'permission prompt');
p.emitData('\x1b[2J\x1b[HDo you want to create x.txt?\r\n❯ 1. Yes\r\n2. No\r\n');
await sleep(260);
expect(notifies).toHaveLength(0); // pas encore : debounce en cours
await sleep(1500); // dépasse le debounce
expect(notifies).toHaveLength(1);
expect(notifies[0]).toMatchObject({ sessionId: summary.id, kind: 'permission', url: `/sessions/${summary.id}` });
} finally {
m.shutdown();
rmSync(sessDir, { recursive: true, force: true });
}
});
});
describe('flow control', () => {
it('pause() UNIQUEMENT quand tous les interactifs dépassent HIGH ; resume() quand le min repasse sous LOW', () => {
const { summary, pty } = spawnBash();
@@ -606,53 +480,4 @@ describe('PtyManager (pty mocké)', () => {
expect(manager.attach(summary.id, makeBinding('interactive'), 80, 24)).toEqual({ ok: false, code: 'NOT_FOUND' });
});
});
describe('session de groupe multi-repo (P6)', () => {
it('spawn avec addDirs : --add-dir au pty, addedDirs + groupId résumés et persistés', () => {
const d1 = mkdtempSync(join(tmpdir(), 'arb-g1-'));
const d2 = mkdtempSync(join(tmpdir(), 'arb-g2-'));
try {
const summary = manager.spawn({ cwd, command: 'claude', addDirs: [d1, d2], groupId: 'grp1' });
expect(lastPty().args).toEqual(['--add-dir', d1, '--add-dir', d2]);
expect(summary.addedDirs).toEqual([d1, d2]);
expect(summary.groupId).toBe('grp1');
const row = db.prepare('SELECT added_dirs, group_id FROM sessions WHERE id = ?').get(summary.id) as {
added_dirs: string | null;
group_id: string | null;
};
expect(JSON.parse(row.added_dirs as string)).toEqual([d1, d2]);
expect(row.group_id).toBe('grp1');
} finally {
rmSync(d1, { recursive: true, force: true });
rmSync(d2, { recursive: true, force: true });
}
});
it('dédoublonne et écarte le cwd primaire des addDirs', () => {
const d1 = mkdtempSync(join(tmpdir(), 'arb-g4-'));
try {
const summary = manager.spawn({ cwd, command: 'claude', addDirs: [d1, d1, cwd] });
expect(summary.addedDirs).toEqual([d1]);
} finally {
rmSync(d1, { recursive: true, force: true });
}
});
it('rejette un addDir inexistant (400)', () => {
expect(() => manager.spawn({ cwd, command: 'bash', addDirs: ['/no/such/dir/xyz-arb'] })).toThrow();
});
it('groupSessionContext renvoie les addedDirs/groupId persistés (resume)', () => {
const d1 = mkdtempSync(join(tmpdir(), 'arb-g5-'));
try {
const summary = manager.spawn({ cwd, command: 'claude', addDirs: [d1], groupId: 'grpX' });
// simule la capture du claudeSessionId (normalement résolue via le registre)
db.prepare('UPDATE sessions SET claude_session_id = ? WHERE id = ?').run('cs-1', summary.id);
expect(manager.groupSessionContext('cs-1')).toEqual({ addedDirs: [d1], groupId: 'grpX' });
expect(manager.groupSessionContext('unknown')).toBeNull();
} finally {
rmSync(d1, { recursive: true, force: true });
}
});
});
});
-79
View File
@@ -1,79 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import { PushService, type PushSender, type PushPayload } from '../src/core/push-service.js';
import { openDb, getSetting, type Db } from '../src/db/index.js';
function sub(endpoint: string): { endpoint: string; keys: { p256dh: string; auth: string } } {
return { endpoint, keys: { p256dh: `p-${endpoint}`, auth: `a-${endpoint}` } };
}
const payload: PushPayload = { sessionId: 's1', title: 't', body: 'b', kind: 'permission', url: '/sessions/s1' };
describe('PushService', () => {
it('génère les clés VAPID une seule fois (idempotent) et les persiste', () => {
const db: Db = openDb(':memory:');
const a = new PushService(db);
const pub = a.publicKey();
expect(pub).toMatch(/.{20,}/); // clé base64url non triviale
expect(getSetting(db, 'vapid_private')).not.toBeNull();
// une seconde instance sur la même db réutilise les clés (pas de régénération)
const b = new PushService(db);
expect(b.publicKey()).toBe(pub);
});
it('subscribe (UPSERT par endpoint), count et unsubscribe', () => {
const db = openDb(':memory:');
const p = new PushService(db);
p.subscribe('tok1', sub('https://push/a'), 'UA');
p.subscribe('tok1', sub('https://push/b'), null);
expect(p.count()).toBe(2);
// ré-abonnement du même endpoint → pas de doublon
p.subscribe('tok2', sub('https://push/a'), 'UA2');
expect(p.count()).toBe(2);
p.unsubscribe('https://push/a');
expect(p.count()).toBe(1);
});
it('notify : supprime l’abonnement sur 410 Gone, conserve sur autre erreur, marque last_ok_at sur succès', async () => {
const db = openDb(':memory:');
const sender: PushSender = vi.fn(async (s) => {
if (s.endpoint.endsWith('/gone')) throw Object.assign(new Error('gone'), { statusCode: 410 });
if (s.endpoint.endsWith('/flaky')) throw Object.assign(new Error('boom'), { statusCode: 500 });
return { statusCode: 201 };
});
const p = new PushService(db, 'mailto:test@x', sender);
p.subscribe('tok', sub('https://push/ok'), null);
p.subscribe('tok', sub('https://push/gone'), null);
p.subscribe('tok', sub('https://push/flaky'), null);
await p.notify(payload);
expect(sender).toHaveBeenCalledTimes(3);
// 410 → purgé ; 500 → conservé ; ok → conservé
expect(p.count()).toBe(2);
const rows = db.prepare('SELECT endpoint, last_ok_at FROM push_subscriptions ORDER BY endpoint').all() as Array<{ endpoint: string; last_ok_at: string | null }>;
const byEndpoint = Object.fromEntries(rows.map((r) => [r.endpoint, r.last_ok_at]));
expect(byEndpoint['https://push/ok']).not.toBeNull(); // succès horodaté
expect(byEndpoint['https://push/flaky']).toBeNull(); // échec transitoire : pas d'horodatage, mais conservé
expect(byEndpoint['https://push/gone']).toBeUndefined();
});
it('notify sans abonnement : ne touche pas au sender', async () => {
const db = openDb(':memory:');
const sender: PushSender = vi.fn(async () => ({}));
const p = new PushService(db, 'mailto:test@x', sender);
await p.notify(payload);
expect(sender).not.toHaveBeenCalled();
});
it('le payload poussé est le JSON sérialisé de PushPayload', async () => {
const db = openDb(':memory:');
let captured = '';
const sender: PushSender = async (_s, body) => {
captured = body;
return {};
};
const p = new PushService(db, 'mailto:test@x', sender);
p.subscribe('tok', sub('https://push/ok'), null);
await p.notify(payload);
expect(JSON.parse(captured)).toEqual(payload);
});
});
-104
View File
@@ -1,104 +0,0 @@
import { describe, expect, it, afterEach } from 'vitest';
import { mkdtempSync, mkdirSync, rmSync, symlinkSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { scanForRepos } from '../src/core/repo-scanner.js';
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
function tmpRoot(): string {
const d = mkdtempSync(join(tmpdir(), 'arb-scan-'));
dirs.push(d);
return d;
}
// un « repo » pour le scanner = un dossier contenant `.git` (le scanner ne lance jamais git).
function makeRepo(...segs: string[]): void {
mkdirSync(join(...segs, '.git'), { recursive: true });
}
const limits = { maxDepth: 6, maxRepos: 2000 };
describe('scanForRepos', () => {
it('trouve un repo simple', async () => {
const root = tmpRoot();
makeRepo(root, 'proj');
const { paths, truncated } = await scanForRepos([root], limits);
expect(paths).toEqual([join(root, 'proj')]);
expect(truncated).toBe(false);
});
it('ne descend pas dans un repo trouvé (sous-repo ignoré)', async () => {
const root = tmpRoot();
makeRepo(root, 'a');
makeRepo(root, 'a', 'sub'); // imbriqué : doit être ignoré
const { paths } = await scanForRepos([root], limits);
expect(paths).toEqual([join(root, 'a')]);
});
it('descend dans une racine qui est elle-même un repo (workspace + sous-repos)', async () => {
const root = tmpRoot();
makeRepo(root); // la racine fournie contient elle-même un .git (cas WebstormProjects)
makeRepo(root, 'a');
makeRepo(root, 'b');
const { paths } = await scanForRepos([root], limits);
// la racine ET ses dépôts internes sont découverts (la racine n'arrête pas le scan)
expect([...paths].sort()).toEqual([root, join(root, 'a'), join(root, 'b')].sort());
});
it('ignore node_modules et les dotdirs', async () => {
const root = tmpRoot();
makeRepo(root, 'node_modules', 'pkg');
makeRepo(root, '.hidden', 'x');
makeRepo(root, 'real');
const { paths } = await scanForRepos([root], limits);
expect(paths).toEqual([join(root, 'real')]);
});
it('respecte maxDepth', async () => {
const root = tmpRoot();
makeRepo(root, 'a', 'b', 'c', 'deep'); // repo à profondeur 4
const shallow = await scanForRepos([root], { maxDepth: 2, maxRepos: 2000 });
expect(shallow.paths).toEqual([]);
const deep = await scanForRepos([root], { maxDepth: 4, maxRepos: 2000 });
expect(deep.paths).toEqual([join(root, 'a', 'b', 'c', 'deep')]);
});
it('ne suit pas les symlinks (cycle terminé, pas de doublon)', async () => {
const root = tmpRoot();
makeRepo(root, 'proj');
try {
symlinkSync(root, join(root, 'loop')); // cycle vers la racine
} catch {
/* symlink non autorisé sous certains CI : le test reste valide sans le lien */
}
const { paths } = await scanForRepos([root], limits);
expect(paths).toEqual([join(root, 'proj')]);
});
it('tronque à maxRepos', async () => {
const root = tmpRoot();
makeRepo(root, 'r1');
makeRepo(root, 'r2');
makeRepo(root, 'r3');
const { paths, truncated } = await scanForRepos([root], { maxDepth: 6, maxRepos: 2 });
expect(truncated).toBe(true);
expect(paths.length).toBeLessThanOrEqual(2);
});
it('ignore une racine inexistante sans lever', async () => {
const { paths } = await scanForRepos(['/nope/does/not/exist'], limits);
expect(paths).toEqual([]);
});
it('scanne plusieurs racines', async () => {
const r1 = tmpRoot();
const r2 = tmpRoot();
makeRepo(r1, 'one');
makeRepo(r2, 'two');
const { paths } = await scanForRepos([r1, r2], limits);
expect([...paths].sort()).toEqual([join(r1, 'one'), join(r2, 'two')].sort());
});
});
-37
View File
@@ -1,37 +0,0 @@
import { describe, expect, it } from 'vitest';
import { randomBytes } from 'node:crypto';
import { SecretBox } from '../src/core/secret-box.js';
const box = (): SecretBox => new SecretBox(randomBytes(32));
describe('SecretBox', () => {
it('chiffre puis déchiffre (round-trip)', () => {
const b = box();
const secret = 'deadbeef'.repeat(8);
const enc = b.encrypt(secret);
expect(enc.startsWith('v1:')).toBe(true);
expect(enc).not.toContain(secret); // le clair n'apparaît pas
expect(b.decrypt(enc)).toBe(secret);
});
it('produit un chiffré différent à chaque fois (IV aléatoire)', () => {
const b = box();
expect(b.encrypt('x')).not.toBe(b.encrypt('x'));
});
it('retourne tel quel une valeur en clair (legacy) et la détecte', () => {
const b = box();
expect(b.isEncrypted('plain-secret')).toBe(false);
expect(b.decrypt('plain-secret')).toBe('plain-secret');
expect(b.isEncrypted(b.encrypt('x'))).toBe(true);
});
it('échoue si la clé ne correspond pas (GCM authentifié)', () => {
const enc = box().encrypt('secret');
expect(() => box().decrypt(enc)).toThrow();
});
it('échoue sur un format chiffré corrompu', () => {
expect(() => box().decrypt('v1:zzz')).toThrow();
});
});
@@ -1,139 +0,0 @@
// Routes Réglages : GET expose la config non sensible (jamais les secrets), PATCH n'écrit que
// l'allow-list (découverte des dépôts) et ignore toute clé hors allow-list.
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { buildApp, type AppBundle } from '../src/app.js';
import { getSetting, openDb, type Db } from '../src/db/index.js';
import type { Config } from '../src/config.js';
import type { SettingsResponse } from '@arboretum/shared';
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
class FakePty {
pid = 424242;
write = vi.fn();
resize = vi.fn();
pause = vi.fn();
resume = vi.fn();
kill = vi.fn();
onData(): { dispose: () => void } {
return { dispose: () => {} };
}
onExit(): { dispose: () => void } {
return { dispose: () => {} };
}
}
return { default: { spawn: (): FakePty => new FakePty() } };
});
process.env.ARBORETUM_LOG = 'silent';
let dir: string;
let bundle: AppBundle;
let db: Db;
let token: string;
const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` });
beforeAll(() => {
dir = mkdtempSync(join(tmpdir(), 'arboretum-settings-'));
const dbPath = join(dir, 'settings.db');
db = openDb(dbPath);
const config: Config = {
port: 9999,
bind: '127.0.0.1',
dbPath,
dataDir: dir,
allowedOrigins: ['https://host.tailnet.ts.net'],
printToken: false,
claudeProjectsDir: join(dir, 'claude', 'projects'),
claudeSessionsDir: join(dir, 'claude', 'sessions'),
vapidContact: 'mailto:test@localhost',
};
bundle = buildApp(config, db, '1.2.3-test');
const t = bundle.auth.ensureBootstrapToken();
if (!t) throw new Error('bootstrap token attendu');
token = t;
});
afterAll(async () => {
await bundle.app.close();
db.close();
rmSync(dir, { recursive: true, force: true });
});
describe('GET /api/v1/settings', () => {
it('renvoie la config serveur non sensible et aucune racine de scan par défaut', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() });
expect(res.statusCode).toBe(200);
const body = res.json() as SettingsResponse;
expect(body.server.version).toBe('1.2.3-test');
expect(body.server.port).toBe(9999);
expect(body.server.bind).toBe('127.0.0.1');
expect(body.server.allowedOrigins).toEqual(['https://host.tailnet.ts.net']);
expect(body.server.vapidPublicKey).toBeTruthy(); // clé publique = sûre à exposer
// défauts de découverte : AUCUNE racine (clean install → pas de scan) + intervalle 5 min
expect(body.settings.scanRoots).toEqual([]);
expect(body.settings.scanIntervalMin).toBe(5);
});
it('n’expose AUCUN secret (server_secret, clé privée VAPID)', async () => {
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() });
const raw = res.body;
const secret = getSetting(db, 'server_secret');
const vapidPrivate = getSetting(db, 'vapid_private');
expect(secret).toBeTruthy();
expect(raw).not.toContain(secret as string);
expect(raw).not.toContain(vapidPrivate as string);
expect(raw).not.toMatch(/server_secret|vapid_private|privateKey/);
});
});
describe('PATCH /api/v1/settings — sécurité', () => {
it('ignore toute clé hors allow-list (ne touche pas aux secrets)', async () => {
const before = getSetting(db, 'server_secret');
await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { server_secret: 'pwned', vapid_private: 'pwned' } });
expect(getSetting(db, 'server_secret')).toBe(before); // inchangé
expect(getSetting(db, 'vapid_private')).not.toBe('pwned');
});
it('sans authentification → 401', async () => {
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', payload: { scanRoots: ['/home/u/work'] } });
expect(res.statusCode).toBe(401);
});
});
describe('PATCH /api/v1/settings — découverte des dépôts', () => {
it('enregistre des scanRoots et un intervalle valides et les renvoie', async () => {
const res = await bundle.app.inject({
method: 'PATCH',
url: '/api/v1/settings',
headers: auth(),
payload: { scanRoots: ['/home/u/work', '/srv/code'], scanIntervalMin: 10 },
});
expect(res.statusCode).toBe(200);
const body = res.json() as SettingsResponse;
expect(body.settings.scanRoots).toEqual(['/home/u/work', '/srv/code']);
expect(body.settings.scanIntervalMin).toBe(10);
// persisté
const get = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() });
expect((get.json() as SettingsResponse).settings.scanRoots).toEqual(['/home/u/work', '/srv/code']);
});
it('rejette des racines non absolues, "/", avec ".." ou en surnombre (400)', async () => {
const bads: unknown[] = [['relative/path'], ['/'], ['/a/../b'], Array.from({ length: 17 }, (_, i) => `/r${i}`)];
for (const scanRoots of bads) {
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { scanRoots } });
expect(res.statusCode).toBe(400);
}
});
it('rejette un intervalle hors borne (400)', async () => {
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { scanIntervalMin: 5000 } });
expect(res.statusCode).toBe(400);
const neg = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { scanIntervalMin: -1 } });
expect(neg.statusCode).toBe(400);
});
});
@@ -1,311 +0,0 @@
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, basename, dirname, resolve } from 'node:path';
import type { RepoSummary, WorktreeSummary } from '@arboretum/shared';
import { WorktreeManager } from '../src/core/worktree-manager.js';
import { PtyManager } from '../src/core/pty-manager.js';
import { DiscoveryService } from '../src/core/discovery-service.js';
import { openDb, type Db } from '../src/db/index.js';
// node-pty inerte (la corrélation de session n'a besoin que d'un pid et d'un cwd).
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
let pid = 50_000;
class FakePty {
pid = pid++;
write = vi.fn();
resize = vi.fn();
pause = vi.fn();
resume = vi.fn();
kill = vi.fn();
onData(): { dispose: () => void } {
return { dispose: () => {} };
}
onExit(): { dispose: () => void } {
return { dispose: () => {} };
}
}
return { default: { spawn: (): FakePty => new FakePty() } };
});
const dirs: string[] = [];
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
function gitInit(dir: string): void {
const run = (...args: string[]): void => void execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
run('init', '-b', 'main');
run('config', 'user.email', 'test@arboretum.dev');
run('config', 'user.name', 'Test');
writeFileSync(join(dir, 'README.md'), '# test\n');
run('add', '-A');
run('commit', '-m', 'init');
}
function makeTmpRepo(): string {
const dir = mkdtempSync(join(tmpdir(), 'arb-wtm-'));
dirs.push(dir);
gitInit(dir);
return dir;
}
/** Crée un vrai repo git à un chemin donné (sous une racine de scan contrôlée). */
function makeRepoAt(path: string): void {
mkdirSync(path, { recursive: true });
gitInit(path);
}
describe('WorktreeManager', () => {
let db: Db;
let pty: PtyManager;
let discovery: DiscoveryService;
let wt: WorktreeManager;
let claudeHome: string;
beforeEach(() => {
db = openDb(':memory:');
claudeHome = mkdtempSync(join(tmpdir(), 'arb-ch-'));
dirs.push(claudeHome);
pty = new PtyManager(db, join(claudeHome, 'sessions'));
discovery = new DiscoveryService({ db, ptyManager: pty, projectsDir: join(claudeHome, 'projects'), sessionsDir: join(claudeHome, 'sessions') });
wt = new WorktreeManager(db, pty, discovery);
});
it('addRepo : repo valide enregistré ; non-repo rejeté (400)', async () => {
const repo = makeTmpRepo();
const summary = await wt.addRepo({ path: repo });
expect(summary).toMatchObject({ path: repo, label: basename(repo), valid: true });
expect((await wt.listRepos())).toHaveLength(1);
const notRepo = mkdtempSync(join(tmpdir(), 'arb-nogit-'));
dirs.push(notRepo);
await expect(wt.addRepo({ path: notRepo })).rejects.toMatchObject({ statusCode: 400 });
// doublon
await expect(wt.addRepo({ path: repo })).rejects.toMatchObject({ statusCode: 409 });
});
it('createWorktree : worktree + hook exécuté + event worktree_update', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({
path: repo,
postCreateHooks: [{ id: 'h1', label: 'touch', run: 'touch hook-ran.txt', enabled: true }],
});
const events: Array<{ repoId: string; worktree: WorktreeSummary }> = [];
wt.on('worktree_update', (e) => events.push(e));
const wtPath = join(dirname(repo), `${basename(repo)}-wt-feat`);
dirs.push(wtPath);
const out = await wt.createWorktree(r.id, { branch: 'feat', mode: 'create', runHooks: true });
expect(out.action).toBe('created');
expect(resolve(out.worktree.path)).toBe(resolve(wtPath));
expect(out.worktree.branch).toBe('feat');
expect(out.hookResults).toHaveLength(1);
expect(out.hookResults[0]).toMatchObject({ exitCode: 0 });
expect(existsSync(join(wtPath, 'hook-ran.txt'))).toBe(true);
expect(events.some((e) => resolve(e.worktree.path) === resolve(wtPath))).toBe(true);
const list = await wt.listRepoWorktrees(r.id, true);
expect(list.some((w) => resolve(w.path) === resolve(wtPath))).toBe(true);
});
it('createWorktree : branche invalide → 400', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
await expect(wt.createWorktree(r.id, { branch: '../evil', mode: 'create' })).rejects.toMatchObject({ statusCode: 400 });
});
it('startMainSession : session dans le checkout principal (branche actuelle, sans mutation git)', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
const out = await wt.startMainSession(r.id, { command: 'bash' });
expect(resolve(out.session.cwd)).toBe(resolve(repo));
expect(out.session).toMatchObject({ command: 'bash', live: true });
// pas de bascule de branche → toujours sur main.
expect(execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim()).toBe('main');
const main = (await wt.listRepoWorktrees(r.id, true)).find((w) => w.isMain);
expect(main?.sessions.some((s) => s.id === out.session.id)).toBe(true);
});
it('startMainSession : newBranch crée et bascule la branche dans le checkout principal + event', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
const events: Array<{ worktree: WorktreeSummary }> = [];
wt.on('worktree_update', (e) => events.push(e));
const out = await wt.startMainSession(r.id, { command: 'bash', branch: 'feature/x', newBranch: true });
expect(execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim()).toBe('feature/x');
expect(out.worktree?.branch).toBe('feature/x');
expect(events.some((e) => e.worktree.isMain && e.worktree.branch === 'feature/x')).toBe(true);
});
it('startMainSession : checkout principal sale → 409 DIRTY_TREE (pas de bascule)', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
writeFileSync(join(repo, 'scratch.txt'), 'wip\n'); // arbre sale
await expect(wt.startMainSession(r.id, { command: 'bash', branch: 'feature/y', newBranch: true })).rejects.toMatchObject({
statusCode: 409,
code: 'DIRTY_TREE',
});
expect(execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim()).toBe('main');
});
it('startMainSession : branche invalide → 400', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
await expect(wt.startMainSession(r.id, { command: 'bash', branch: '../evil', newBranch: true })).rejects.toMatchObject({ statusCode: 400 });
});
it('deleteWorktree : main refusé (400), dirty refusé (409) puis force OK', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
await expect(wt.deleteWorktree(r.id, repo, false)).rejects.toMatchObject({ statusCode: 400, code: 'IS_MAIN_WORKTREE' });
const wtPath = join(dirname(repo), `${basename(repo)}-wt-x`);
dirs.push(wtPath);
await wt.createWorktree(r.id, { branch: 'x', mode: 'create', runHooks: false });
writeFileSync(join(wtPath, 'scratch.txt'), 'wip\n'); // worktree sale
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'WORKTREE_DIRTY' });
await wt.deleteWorktree(r.id, wtPath, true);
expect((await wt.listRepoWorktrees(r.id, true)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
});
it('corrélation : une session dont le cwd = worktree apparaît dans worktree.sessions', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
const wtPath = join(dirname(repo), `${basename(repo)}-wt-sess`);
dirs.push(wtPath);
await wt.createWorktree(r.id, { branch: 'sess', mode: 'create', runHooks: false });
pty.spawn({ cwd: wtPath, command: 'bash' });
const list = await wt.listRepoWorktrees(r.id, true);
const target = list.find((w) => resolve(w.path) === resolve(wtPath));
expect(target?.sessions).toHaveLength(1);
expect(target?.sessions[0]).toMatchObject({ source: 'managed', live: true });
});
it('deleteWorktree : session live dans le worktree → 409 sans force', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
const wtPath = join(dirname(repo), `${basename(repo)}-wt-busy`);
dirs.push(wtPath);
await wt.createWorktree(r.id, { branch: 'busy', mode: 'create', runHooks: false });
pty.spawn({ cwd: wtPath, command: 'bash' });
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'SESSION_LIVE_IN_WORKTREE' });
});
it('listRepoBranches : renvoie les branches locales (dont main)', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
const b = await wt.listRepoBranches(r.id);
expect(b.local).toContain('main');
});
it('commitWorktree : arbre propre → 409 NOTHING_TO_COMMIT ; arbre sale → commit (dirty=0)', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
await expect(wt.commitWorktree(r.id, repo, 'noop')).rejects.toMatchObject({ statusCode: 409, code: 'NOTHING_TO_COMMIT' });
writeFileSync(join(repo, 'f.txt'), 'x\n');
const w = await wt.commitWorktree(r.id, repo, 'add f');
expect(w.git.dirtyCount).toBe(0);
});
it('promoteWorktree : la branche du worktree devient le checkout principal, worktree supprimé, ancienne branche conservée', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
const wtPath = join(dirname(repo), `${basename(repo)}-wt-prom`);
dirs.push(wtPath);
await wt.createWorktree(r.id, { branch: 'prom', mode: 'create', runHooks: false });
await wt.promoteWorktree(r.id, wtPath);
expect(execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim()).toBe('prom');
expect((await wt.listRepoWorktrees(r.id, true)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
const branches = await wt.listRepoBranches(r.id);
expect(branches.local).toContain('main'); // ancienne branche principale conservée
expect(branches.local).toContain('prom');
});
it('promoteWorktree : checkout principal refusé (400 IS_MAIN_WORKTREE)', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
await expect(wt.promoteWorktree(r.id, repo)).rejects.toMatchObject({ statusCode: 400, code: 'IS_MAIN_WORKTREE' });
});
it('addRepo renvoie hidden:false ; updateRepo({hidden}) bascule et émet repo_update', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
expect(r.hidden).toBe(false);
const updates: RepoSummary[] = [];
wt.on('repo_update', (s) => updates.push(s));
const u = await wt.updateRepo(r.id, { hidden: true });
expect(u.hidden).toBe(true);
expect(updates.some((s) => s.id === r.id && s.hidden)).toBe(true);
});
it('listAllWorktrees exclut les repos masqués', async () => {
const repo = makeTmpRepo();
const r = await wt.addRepo({ path: repo });
expect((await wt.listAllWorktrees()).length).toBeGreaterThan(0); // main worktree présent
await wt.updateRepo(r.id, { hidden: true });
expect(await wt.listAllWorktrees()).toHaveLength(0);
});
it('discoverRepos : auto-ajoute les nouveaux, idempotent, masqué non ressuscité, supprimé re-découvrable', async () => {
const root = mkdtempSync(join(tmpdir(), 'arb-scan-'));
dirs.push(root);
makeRepoAt(join(root, 'a'));
makeRepoAt(join(root, 'b'));
const updates: RepoSummary[] = [];
wt.on('repo_update', (s) => updates.push(s));
const res = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(res.added).toBe(2);
expect(res.scanned).toBe(2);
expect(await wt.listRepos()).toHaveLength(2);
expect(updates).toHaveLength(2); // un repo_update par nouveau
// re-scan : idempotent (aucun ajout, aucune émission)
updates.length = 0;
const res2 = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(res2.added).toBe(0);
expect(updates).toHaveLength(0);
expect(await wt.listRepos()).toHaveLength(2);
// masquer 'a' puis re-scan : reste masqué, jamais ré-ajouté (invariant central)
const repoA = (await wt.listRepos()).find((r) => resolve(r.path) === resolve(join(root, 'a')));
await wt.updateRepo(repoA!.id, { hidden: true });
updates.length = 0;
const res3 = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(res3.added).toBe(0);
expect((await wt.listRepos()).find((r) => r.id === repoA!.id)?.hidden).toBe(true);
// supprimer 'b' puis re-scan : re-découvert (volontaire)
const repoB = (await wt.listRepos()).find((r) => resolve(r.path) === resolve(join(root, 'b')));
wt.removeRepo(repoB!.id);
expect(await wt.listRepos()).toHaveLength(1);
const res4 = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(res4.added).toBe(1);
expect(await wt.listRepos()).toHaveLength(2);
});
it('discoverRepos : repo disparu du disque conservé en DB (valid=false), non re-trouvé', async () => {
const root = mkdtempSync(join(tmpdir(), 'arb-scan-'));
dirs.push(root);
makeRepoAt(join(root, 'gone'));
await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(await wt.listRepos()).toHaveLength(1);
rmSync(join(root, 'gone'), { recursive: true, force: true }); // disparaît du disque
const res = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
expect(res.added).toBe(0); // plus trouvé par le scan
const repos = await wt.listRepos();
expect(repos).toHaveLength(1); // mais la ligne est conservée (pas de suppression auto)
expect(repos[0].valid).toBe(false);
// robustesse : un repo dont le chemin a disparu ne fait pas planter /worktrees (git échoue → [])
await expect(wt.listAllWorktrees()).resolves.toEqual([]);
});
});
File diff suppressed because one or more lines are too long
+2 -298
View File
@@ -1,5 +1,5 @@
// Types REST partagés (préfixe /api/v1).
import type { GroupSummary, PostCreateHook, RepoSummary, SessionSummary, WorktreeSummary } from './protocol.js';
// Types REST partagés (préfixe /api/v1) — sous-ensemble P1.
import type { SessionSummary } from './protocol.js';
export interface ApiError {
error: { code: string; message: string; details?: unknown };
@@ -14,34 +14,10 @@ export interface LoginResponse {
}
export interface MeResponse {
ok: true;
/** id du token de la session courante — sert à marquer « courant » dans la liste des tokens. */
tokenId: string;
tokenLabel: string;
serverVersion: string;
}
// ---- Gestion des tokens d'accès (onglet Réglages) ----
export interface TokenInfo {
id: string;
label: string;
createdAt: string;
lastUsedAt: string | null;
/** true pour le token de la session courante. */
current: boolean;
}
export interface TokensListResponse {
tokens: TokenInfo[];
}
export interface CreateTokenRequest {
label: string;
}
export interface CreateTokenResponse {
id: string;
label: string;
/** valeur en clair — affichée une seule fois, jamais re-récupérable. */
token: string;
}
export interface CreateSessionRequest {
cwd: string;
/** binaire à lancer — défaut "claude" ; "bash" sert aux tests d'acceptation sans quota */
@@ -53,280 +29,8 @@ export interface SessionsListResponse {
export interface SessionResponse {
session: SessionSummary;
}
/** POST /sessions/hide-discovered — masque tout l'historique de sessions externes visible. */
export interface HideDiscoveredResponse {
/** nombre de sessions effectivement masquées. */
hidden: number;
}
// POST /sessions/:id/resume et /sessions/:id/fork (P2) : aucun corps — cwd et command
// sont TOUJOURS dérivés du :id (lu sur disque), jamais fournis par le client (cf. spike S1).
export type ResumeSessionRequest = Record<string, never>;
export type ForkSessionRequest = Record<string, never>;
// ---- Repos & worktrees (P3) ----
export interface ReposListResponse {
repos: RepoSummary[];
}
export interface RepoResponse {
repo: RepoSummary;
}
export interface CreateRepoRequest {
path: string;
label?: string;
postCreateHooks?: PostCreateHook[];
preTrust?: boolean;
}
export interface UpdateRepoRequest {
label?: string;
postCreateHooks?: PostCreateHook[];
preTrust?: boolean;
/** true = masquer le repo (exclu du dashboard, conservé en DB) ; false = ré-afficher. */
hidden?: boolean;
}
/** Résultat d'un scan de découverte (POST /api/v1/repos/discover). */
export interface DiscoverReposResponse {
/** dossiers-repos trouvés sur disque. */
scanned: number;
/** repos réellement insérés (nouveaux, non déjà enregistrés). */
added: number;
durationMs: number;
/** true si la limite (maxRepos / timeout) a été atteinte avant la fin du scan. */
truncated: boolean;
}
export interface WorktreesListResponse {
worktrees: WorktreeSummary[];
}
export interface WorktreeResponse {
worktree: WorktreeSummary;
}
export interface HookRunResult {
hookId: string;
label: string;
exitCode: number | null;
output: string;
durationMs: number;
}
/**
* Stratégie de résolution de la branche d'un nouveau worktree :
* - `auto` (défaut) : détecte l'existence de la branche — checkout si elle existe en local, suivi de
* `origin/<branch>` si elle n'existe que sur le remote, sinon création (`-b`). Robuste pour les
* groupes hétérogènes où la branche peut déjà exister dans certains dépôts mais pas d'autres.
* - `create` : force la création (`-b`), échoue si la branche existe déjà.
* - `checkout` : force le checkout d'une branche existante, échoue si elle est absente.
*/
export type WorktreeBranchMode = 'auto' | 'create' | 'checkout';
/** Action réellement effectuée par la résolution `auto` (feedback UI). */
export type WorktreeBranchAction = 'created' | 'reused' | 'tracked';
export interface CreateWorktreeRequest {
branch: string;
/** stratégie de résolution de la branche (défaut : `auto`). Voir {@link WorktreeBranchMode}. */
mode?: WorktreeBranchMode;
/** @deprecated remplacé par `mode` ; mappé : true→create, false→checkout, absent→auto. */
newBranch?: boolean;
/** point de départ d'une branche créée (défaut : branche par défaut du dépôt, sinon HEAD). */
baseRef?: string;
/** chemin cible du worktree (défaut : `<parent>/<repo>-wt-<branch>`). */
path?: string;
runHooks?: boolean;
preTrust?: boolean;
/** lancer une session dans le worktree créé (défaut : aucune). */
startSession?: 'claude' | 'bash' | null;
}
export interface CreateWorktreeResponse {
worktree: WorktreeSummary;
hookResults: HookRunResult[];
session: SessionSummary | null;
/** action effective de la résolution de branche (créée / réutilisée / suivie du remote). */
action: WorktreeBranchAction;
}
/** GET /api/v1/repos/:id/branches — branches locales/remote pour alimenter un sélecteur de base. */
export interface RepoBranchesResponse {
local: string[];
remote: string[];
/** branche par défaut du dépôt (origin/HEAD), ou null si indéterminée. */
default: string | null;
}
/** POST /api/v1/repos/:id/worktrees/commit — `git add -A` puis commit dans le worktree visé. */
export interface CommitWorktreeRequest {
path: string;
message: string;
}
/** POST /api/v1/repos/:id/worktrees/push — pousse la branche du worktree (upstream auto si absent). */
export interface PushWorktreeRequest {
path: string;
}
/**
* POST /api/v1/repos/:id/worktrees/promote — « passer en principal » : la branche du worktree devient
* le checkout principal du dépôt (le worktree est supprimé, l'ancienne branche principale est conservée).
*/
export interface PromoteWorktreeRequest {
path: string;
/** outrepasse les garde-fous d'arbre sale (worktree/checkout principal). */
force?: boolean;
}
export interface AdoptWorktreeRequest {
path: string;
runHooks?: boolean;
preTrust?: boolean;
}
/**
* POST /api/v1/repos/:id/session — lance UNE session dans le checkout principal du repo
* (`repo.path`) pour « bosser sur la branche principale » sans créer de worktree.
* Réponse : `SessionResponse`.
*/
export interface StartRepoSessionRequest {
/** binaire à lancer — défaut "claude" ; "bash" sert aux tests sans quota. */
command?: 'claude' | 'bash';
/** si fourni : crée/bascule cette branche dans le checkout principal avant la session. */
branch?: string;
/** true (défaut quand `branch` fourni) : `git switch -c` ; false : bascule sur une branche existante. */
newBranch?: boolean;
}
// ---- Groupes de travail (P5) ----
export interface GroupsListResponse {
groups: GroupSummary[];
}
export interface GroupResponse {
group: GroupSummary;
}
export interface CreateGroupRequest {
label: string;
description?: string;
color?: string;
/** ids de repos initiaux (défaut : []). */
repoIds?: string[];
}
export interface UpdateGroupRequest {
label?: string;
/** null pour effacer. */
description?: string | null;
color?: string | null;
}
export interface AddRepoRequest {
repoId: string;
}
// ---- Session de groupe multi-repo (P6) ----
/** Lance UNE session Claude couvrant tous les repos du groupe (via `--add-dir`). */
export interface CreateGroupSessionRequest {
/** défaut : claude. */
command?: 'claude' | 'bash';
/** présent → couvre le worktree de cette branche dans chaque repo ; absent → les checkouts principaux. */
branch?: string;
}
export interface GroupSessionResponse {
session: SessionSummary;
/** répertoires effectivement couverts par la session (cwd primaire en tête). */
dirs: string[];
/** repos du groupe pour lesquels aucun worktree n'a pu être résolu. */
skipped: Array<{ repoId: string; reason: string }>;
}
// ---- Navigateur de répertoires (sélecteur de dossier côté web) ----
export interface FsEntry {
name: string;
/** chemin absolu du dossier */
path: string;
/** présent (true) uniquement en mode markRepos quand le dossier est un dépôt git */
isRepo?: boolean;
}
export interface FsListResponse {
/** chemin absolu listé (normalisé) */
path: string;
/** parent (null à la racine `/`) — pour le bouton « remonter » */
parent: string | null;
/** home de l'utilisateur côté serveur — point de départ par défaut */
home: string;
/** sous-dossiers uniquement, triés sans tenir compte de la casse */
entries: FsEntry[];
}
// ---- Web Push (P4) ----
export interface VapidKeyResponse {
/** clé publique VAPID (applicationServerKey côté navigateur). */
key: string;
}
export interface PushSubscribeRequest {
endpoint: string;
keys: { p256dh: string; auth: string };
}
export interface PushUnsubscribeRequest {
endpoint: string;
}
// ---- Réglages & info serveur (onglet Réglages) ----
/** Config runtime non sensible du daemon — lecture seule (changée via flags CLI + redémarrage). */
export interface ServerInfo {
version: string;
port: number;
bind: string;
allowedOrigins: string[];
dataDir: string;
/** clé publique VAPID (sûre à exposer) ; null si push indisponible. */
vapidPublicKey: string | null;
vapidContact: string;
}
export interface SettingsResponse {
/** réglages modifiables à chaud (allow-list serveur — jamais les secrets). */
settings: {
/** racines absolues scannées pour la découverte auto des repos (défaut : aucune → pas de scan). */
scanRoots: string[];
/** intervalle du re-scan périodique en minutes ; 0 = périodique désactivé. */
scanIntervalMin: number;
};
server: ServerInfo;
}
export interface UpdateSettingsRequest {
/** racines absolues à scanner (chemins normalisés, ≤ 16) ; remplace la liste. */
scanRoots?: string[];
/** intervalle du re-scan périodique en minutes (0–1440 ; 0 désactive). */
scanIntervalMin?: number;
}
// ---- Journal d'audit (conformité entreprise) ----
export interface AuditLogEntry {
id: string;
/** horodatage ISO 8601 */
ts: string;
/** tokenId de l'acteur, 'system' (auto) ou 'anonymous' (avant auth) */
actor: string;
/** verbe.objet, ex. 'token.create', 'settings.update' */
action: string;
resourceId: string | null;
/** métadonnées non sensibles (jamais de secret) */
details: unknown;
result: string;
}
export interface AuditLogsResponse {
entries: AuditLogEntry[];
/** curseur de pagination (ts à passer en `before`) ; null si fin de liste. */
nextBefore: string | null;
}
// ---- RGPD : export / suppression des données liées au token authentifié ----
export interface DataExportResponse {
exportedAt: string;
tokens: Array<{ id: string; label: string; createdAt: string; lastUsedAt: string | null; current: boolean }>;
pushSubscriptions: Array<{ endpoint: string; userAgent: string | null; createdAt: string; lastOkAt: string | null }>;
sessions: Array<{ id: string; cwd: string; command: string; title: string | null; createdAt: string; endedAt: string | null; exitCode: number | null }>;
settings: { scanRoots: string[]; scanIntervalMin: number };
}
export interface DeleteMyDataRequest {
/** code de confirmation renvoyé par un premier appel sans `confirm` ; doit être renvoyé pour exécuter. */
confirm?: string;
}
export interface DeleteMyDataResponse {
/** 'pending' = confirmation requise (renvoie `confirm`) ; 'done' = suppression effectuée. */
status: 'pending' | 'done';
confirm?: string;
/** récapitulatif de ce qui sera/a été supprimé. */
summary: { pushSubscriptions: number; tokenRevoked: boolean };
}
+5 -122
View File
@@ -51,12 +51,8 @@ export const FLOW = {
LAGGING_BYTES: 2 * 1024 * 1024,
} as const;
/**
* Replay à l'attach : reset terminal + queue du ring (l'écran TUI se repeint en continu).
* 1 Mo (≈ 10–15k lignes) pour permettre de remonter une vraie conversation Claude dans le terminal ;
* reste < LAGGING_BYTES (pas de faux lagging) et bien dans RING_CAPACITY.
*/
export const REPLAY_TAIL_BYTES = 1024 * 1024;
/** Replay à l'attach : reset terminal + queue du ring (l'écran TUI se repeint en continu) */
export const REPLAY_TAIL_BYTES = 256 * 1024;
// ---- États de session (sous-ensemble P1 ; étendu en P3) ----
export type SessionRuntimeStatus =
@@ -72,21 +68,6 @@ export type SessionSource =
/** Statut brut tel qu'écrit par le CLI dans ~/.claude/sessions (interprété finement en P3). */
export type SessionRegistryStatus = 'busy' | 'idle' | 'waiting';
// ---- États fins de session (P3-B, claude-adapter) ----
/** busy = Claude traite ; waiting = bloqué sur un dialogue ; idle = prêt pour une instruction. */
export type SessionActivity = 'busy' | 'waiting' | 'idle';
export type DialogKind = 'trust' | 'permission' | 'question' | 'plan';
export interface DialogOption {
n: number;
label: string;
selected: boolean;
}
export interface SessionDialog {
kind: DialogKind;
waitingFor: string | null;
options: DialogOption[];
}
export interface SessionSummary {
id: string;
cwd: string;
@@ -111,83 +92,6 @@ export interface SessionSummary {
attachable: boolean;
/** statut brut du registre ~/.claude/sessions (P2) ; interprété finement en P3 (claude-adapter). */
registryStatus: SessionRegistryStatus | null;
// ---- P3-B : états fins (optionnels, remplis par le claude-adapter) ----
/** absent/null = inconnu (bash, démarrage, historique). */
activity?: SessionActivity | null;
waitingFor?: string | null;
/** dialogue typé en cours (présent quand activity === 'waiting'). */
dialog?: SessionDialog | null;
// ---- P6 : session de groupe multi-repo (additif) ----
/** répertoires supplémentaires couverts via `--add-dir` ; absent/[] pour une session mono-repo. */
addedDirs?: string[];
/** groupe propriétaire d'une session de groupe (couvre plusieurs repos) ; null/absent sinon. */
groupId?: string | null;
// ---- Masquage (additif) ----
/** true = session découverte masquée par l'utilisateur (exclue de la liste sauf includeHidden). */
hidden?: boolean;
}
// ---- Worktrees & repos (P3) ----
/** Hook lancé après création d'un worktree (commande shell exécutée dans le nouveau worktree). */
export interface PostCreateHook {
id: string;
label: string;
run: string;
enabled: boolean;
}
export interface RepoSummary {
id: string;
/** chemin absolu de la racine du repo (main worktree). */
path: string;
label: string;
defaultBranch: string | null;
postCreateHooks: PostCreateHook[];
/** pré-écrire hasTrustDialogAccepted dans ~/.claude.json à la création d'un worktree. */
preTrust: boolean;
createdAt: string;
/** false si le chemin n'est plus un repo git accessible. */
valid: boolean;
/** true = masqué du dashboard (conservé en DB → non ré-ajouté au re-scan). */
hidden: boolean;
}
export interface WorktreeGitStatus {
ahead: number;
behind: number;
dirtyCount: number;
upstream: string | null;
}
export interface WorktreeSummary {
repoId: string;
/** chemin absolu du worktree (clé de corrélation avec le cwd des sessions). */
path: string;
branch: string | null;
head: string;
detached: boolean;
locked: boolean;
prunable: boolean;
isMain: boolean;
git: WorktreeGitStatus;
/** sessions corrélées par cwd (managées + découvertes) ; leur `activity` est remplie en P3-B. */
sessions: SessionSummary[];
}
// ---- Groupes de travail (P5) ----
// Un groupe regroupe plusieurs repos pour piloter des sessions Claude en simultané sur
// plusieurs worktrees. Membership légère : seule la liste d'ids de repos est persistée ;
// les repos/worktrees/sessions du groupe sont dérivés par filtrage sur `repoId` côté client.
export interface GroupSummary {
id: string;
label: string;
description: string | null;
/** couleur d'accent UI (hex `#rrggbb`) ou null. */
color: string | null;
/** ids de repos membres, ordonnés par leur position dans le groupe. */
repoIds: string[];
createdAt: string;
updatedAt: string;
}
// ---- Messages client → serveur ----
@@ -196,13 +100,9 @@ export type ClientMessage =
| { type: 'attach'; sessionId: string; mode: 'interactive' | 'observer'; cols: number; rows: number }
| { type: 'detach'; channel: number }
| { type: 'stdin'; channel: number; data: string }
// P4-A : répondre à un dialogue Claude sans clavier. Le serveur traduit l'intention
// en keystrokes (chiffre+Entrée pour 'select', Entrée pour 'confirm', Esc pour 'deny')
// et valide l'option contre le dialogue courant (anti-frappe fantôme mobile).
| { type: 'answer'; channel: number; action: 'select' | 'confirm' | 'deny'; optionN?: number }
| { type: 'resize'; channel: number; cols: number; rows: number }
| { type: 'ack'; channel: number; bytes: number }
| { type: 'sub'; topics: Array<'sessions' | 'worktrees' | 'groups'> }
| { type: 'sub'; topics: Array<'sessions'> }
| { type: 'ping' };
// ---- Messages serveur → client ----
@@ -213,12 +113,6 @@ export type ServerMessage =
| { type: 'control_changed'; channel: number; controlling: boolean }
| { type: 'session_update'; session: SessionSummary }
| { type: 'session_exit'; sessionId: string; exitCode: number | null; signal: number | null }
| { type: 'repo_update'; repo: RepoSummary }
| { type: 'repo_removed'; repoId: string }
| { type: 'worktree_update'; repoId: string; worktree: WorktreeSummary }
| { type: 'worktree_removed'; repoId: string; path: string }
| { type: 'group_update'; group: GroupSummary }
| { type: 'group_removed'; groupId: string }
| { type: 'error'; code: ErrorCode; message: string; channel?: number }
| { type: 'pong' };
@@ -229,7 +123,6 @@ export type ErrorCode =
| 'NOT_ATTACHED'
| 'NOT_CONTROLLING'
| 'SESSION_EXITED'
| 'INVALID_ANSWER'
| 'INTERNAL';
export function parseClientMessage(raw: string): ClientMessage | null {
@@ -257,16 +150,6 @@ export function parseClientMessage(raw: string): ClientMessage | null {
return isU32(m.channel) && typeof m.data === 'string' && m.data.length <= 65536
? { type: 'stdin', channel: m.channel, data: m.data }
: null;
case 'answer': {
if (!isU32(m.channel)) return null;
if (m.action === 'select')
return isCount(m.optionN) && (m.optionN as number) >= 1 && (m.optionN as number) <= 99
? { type: 'answer', channel: m.channel, action: 'select', optionN: m.optionN as number }
: null;
return m.action === 'confirm' || m.action === 'deny'
? { type: 'answer', channel: m.channel, action: m.action }
: null;
}
case 'resize':
return isU32(m.channel) && isDim(m.cols) && isDim(m.rows)
? { type: 'resize', channel: m.channel, cols: m.cols, rows: m.rows }
@@ -276,8 +159,8 @@ export function parseClientMessage(raw: string): ClientMessage | null {
? { type: 'ack', channel: m.channel, bytes: m.bytes }
: null;
case 'sub':
return Array.isArray(m.topics) && m.topics.every((t) => t === 'sessions' || t === 'worktrees' || t === 'groups')
? { type: 'sub', topics: m.topics as Array<'sessions' | 'worktrees' | 'groups'> }
return Array.isArray(m.topics) && m.topics.every((t) => t === 'sessions')
? { type: 'sub', topics: m.topics as Array<'sessions'> }
: null;
case 'ping':
return { type: 'ping' };
+6 -42
View File
@@ -42,15 +42,6 @@ function assertInvariants(msg: ClientMessage): void {
expect(typeof msg.data).toBe('string');
expect(msg.data.length).toBeLessThanOrEqual(65536);
break;
case 'answer':
expect(isU32(msg.channel)).toBe(true);
expect(['select', 'confirm', 'deny']).toContain(msg.action);
if (msg.action === 'select') {
expect(typeof msg.optionN).toBe('number');
expect(msg.optionN).toBeGreaterThanOrEqual(1);
expect(msg.optionN).toBeLessThanOrEqual(99);
}
break;
case 'resize':
expect(isU32(msg.channel)).toBe(true);
expect(isDim(msg.cols)).toBe(true);
@@ -62,7 +53,7 @@ function assertInvariants(msg: ClientMessage): void {
expect(msg.bytes).toBeGreaterThanOrEqual(0);
break;
case 'sub':
expect(msg.topics.every((t) => t === 'sessions' || t === 'worktrees' || t === 'groups')).toBe(true);
expect(msg.topics.every((t) => t === 'sessions')).toBe(true);
break;
case 'ping':
break;
@@ -101,30 +92,12 @@ describe('parseClientMessage — cas valides', () => {
.toEqual({ type: 'resize', channel: 3, cols: 120, rows: 32 });
});
it('answer select / confirm / deny', () => {
expect(parseClientMessage('{"type":"answer","channel":2,"action":"select","optionN":3}'))
.toEqual({ type: 'answer', channel: 2, action: 'select', optionN: 3 });
expect(parseClientMessage('{"type":"answer","channel":2,"action":"confirm"}'))
.toEqual({ type: 'answer', channel: 2, action: 'confirm' });
expect(parseClientMessage('{"type":"answer","channel":2,"action":"deny"}'))
.toEqual({ type: 'answer', channel: 2, action: 'deny' });
// optionN n'est porté que par 'select' (ignoré pour confirm/deny)
expect(parseClientMessage('{"type":"answer","channel":2,"action":"deny","optionN":3}'))
.toEqual({ type: 'answer', channel: 2, action: 'deny' });
});
it('ack à zéro octet', () => {
expect(parseClientMessage('{"type":"ack","channel":1,"bytes":0}')).toEqual({ type: 'ack', channel: 1, bytes: 0 });
});
it('sub avec topics sessions/worktrees/groups (et tableau vide accepté)', () => {
it('sub avec topics sessions (et tableau vide accepté)', () => {
expect(parseClientMessage('{"type":"sub","topics":["sessions"]}')).toEqual({ type: 'sub', topics: ['sessions'] });
expect(parseClientMessage('{"type":"sub","topics":["sessions","worktrees"]}')).toEqual({ type: 'sub', topics: ['sessions', 'worktrees'] });
expect(parseClientMessage('{"type":"sub","topics":["groups"]}')).toEqual({ type: 'sub', topics: ['groups'] });
expect(parseClientMessage('{"type":"sub","topics":["sessions","worktrees","groups"]}')).toEqual({
type: 'sub',
topics: ['sessions', 'worktrees', 'groups'],
});
expect(parseClientMessage('{"type":"sub","topics":[]}')).toEqual({ type: 'sub', topics: [] });
});
@@ -179,15 +152,6 @@ describe('parseClientMessage — cas malformés', () => {
expect(parseClientMessage('{"type":"stdin","channel":1}')).toBeNull();
});
it('answer : action inconnue, optionN manquant/hors bornes, channel invalide', () => {
expect(parseClientMessage('{"type":"answer","channel":1,"action":"select"}')).toBeNull(); // optionN requis
expect(parseClientMessage('{"type":"answer","channel":1,"action":"select","optionN":0}')).toBeNull();
expect(parseClientMessage('{"type":"answer","channel":1,"action":"select","optionN":100}')).toBeNull();
expect(parseClientMessage('{"type":"answer","channel":1,"action":"select","optionN":1.5}')).toBeNull();
expect(parseClientMessage('{"type":"answer","channel":1,"action":"nope"}')).toBeNull();
expect(parseClientMessage('{"type":"answer","channel":-1,"action":"deny"}')).toBeNull();
});
it('ack : bytes négatif ou non numérique', () => {
expect(parseClientMessage('{"type":"ack","channel":1,"bytes":-1}')).toBeNull();
expect(parseClientMessage('{"type":"ack","channel":1,"bytes":"0"}')).toBeNull();
@@ -203,16 +167,16 @@ describe('parseClientMessage — cas malformés', () => {
describe('parseClientMessage — fuzz rapide', () => {
it('ne lève jamais et tout message accepté respecte les invariants', () => {
const rand = mulberry32(0xa5b0e7);
const types = ['hello', 'attach', 'detach', 'stdin', 'answer', 'resize', 'ack', 'sub', 'ping', 'unknown', '', 'HELLO', 42, null];
const types = ['hello', 'attach', 'detach', 'stdin', 'resize', 'ack', 'sub', 'ping', 'unknown', '', 'HELLO', 42, null];
const values: unknown[] = [
undefined, null, true, false, 0, -1, 1, 1.5, 2, 99, 100, 999, 1000, 1001, 0xffffffff, 0x100000000,
-0.0001, 1e21, '', 'x', '42', 'interactive', 'observer', 'sessions', 'select', 'confirm', 'deny', {}, [], ['sessions'],
undefined, null, true, false, 0, -1, 1, 1.5, 2, 999, 1000, 1001, 0xffffffff, 0x100000000,
-0.0001, 1e21, '', 'x', '42', 'interactive', 'observer', 'sessions', {}, [], ['sessions'],
['sessions', 'sessions'], ['sessions', 'other'], [42], 'a'.repeat(70000),
];
const pick = <T>(arr: T[]): T => arr[Math.floor(rand() * arr.length)] as T;
for (let i = 0; i < 1000; i++) {
const obj: Record<string, unknown> = { type: pick(types) };
for (const key of ['protocol', 'sessionId', 'mode', 'cols', 'rows', 'channel', 'data', 'bytes', 'topics', 'action', 'optionN']) {
for (const key of ['protocol', 'sessionId', 'mode', 'cols', 'rows', 'channel', 'data', 'bytes', 'topics']) {
if (rand() < 0.7) obj[key] = pick(values);
}
const raw = JSON.stringify(obj);
File diff suppressed because one or more lines are too long
-53
View File
@@ -1,53 +0,0 @@
<!doctype html>
<html lang="en" style="background-color: #09090b">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark" />
<meta name="theme-color" content="#09090b" />
<title>Arboretum — Mission control for your AI coding agents</title>
<meta
name="description"
content="Arboretum is a local-first daemon you launch with npx that serves a web dashboard to run and supervise many Claude Code sessions across git worktrees — from any device, even your phone."
/>
<link rel="canonical" href="https://git-arboretum.com/" />
<!-- Open Graph / Twitter -->
<meta property="og:type" content="website" />
<meta property="og:url" content="https://git-arboretum.com/" />
<meta property="og:title" content="Arboretum — Mission control for your AI coding agents" />
<meta
property="og:description"
content="Run and supervise many Claude Code sessions across every git worktree — from any device, even your phone."
/>
<meta property="og:site_name" content="Arboretum" />
<meta property="og:image" content="https://git-arboretum.com/assets/og-cover.png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:image:alt" content="Arboretum — mission control for your AI coding agents" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Arboretum — Mission control for your AI coding agents" />
<meta
name="twitter:description"
content="Run and supervise many Claude Code sessions across every git worktree — from any device, even your phone."
/>
<meta name="twitter:image" content="https://git-arboretum.com/assets/og-cover.png" />
<!-- Icons -->
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<!-- Polices JetBrains Mono self-host via @fontsource (importées dans src/main.ts). -->
</head>
<body>
<div id="app"></div>
<noscript>
<div style="padding: 24px; font-family: system-ui, sans-serif; color: #f4f4f5; text-align: center">
Arboretum — mission control for your AI coding agents.
<a href="https://git.lidge.fr/johanleroy/arboretum" style="color: #34d399">View on Gitea</a>.
</div>
</noscript>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
-24
View File
@@ -1,24 +0,0 @@
{
"name": "@arboretum/site",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.5.38",
"vue-i18n": "^11.4.5"
},
"devDependencies": {
"@fontsource/jetbrains-mono": "^5.1.0",
"@tailwindcss/vite": "^4.3.0",
"@vitejs/plugin-vue": "^6.0.7",
"tailwindcss": "^4.3.0",
"typescript": "^5.7.0",
"vite": "^8.0.16",
"vue-tsc": "^3.3.4"
}
}
-16
View File
@@ -1,16 +0,0 @@
# git-arboretum.com — site vitrine statique (Vue 3 / Vite).
#
# Google PageSpeed (mod_pagespeed) renvoie un corps HTML VIDE sur ce domaine Plesk
# (la home répond 200 mais 0 octet → page blanche), alors que les assets statiques
# passent. Les bundles Vite sont déjà minifiés, hashés et gzippés : PageSpeed
# n'apporte rien ici et casse le rendu. On le désactive pour ce vhost.
#
# NB : si l'hébergement interdit ces directives en .htaccess (AllowOverride
# restrictif), Apache renverra une 500 → dans ce cas, supprimer ce fichier et
# désactiver PageSpeed depuis Plesk (Apache & nginx Settings).
<IfModule pagespeed_module>
ModPagespeed off
</IfModule>
<IfModule ngx_pagespeed_module>
pagespeed off;
</IfModule>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

-46
View File
@@ -1,46 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" role="img" aria-label="Arboretum">
<defs>
<!-- glow néon : flou doux derrière les traits et les nœuds -->
<filter id="glow" x="-30%" y="-30%" width="160%" height="160%">
<feGaussianBlur stdDeviation="6" result="b"/>
<feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
</filter>
<linearGradient id="branch" x1="256" y1="430" x2="256" y2="90" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#10b981"/>
<stop offset="1" stop-color="#34d399"/>
</linearGradient>
</defs>
<rect width="512" height="512" fill="#09090b"/>
<!-- branches / circuit (tronc + fourches symétriques), tracées dans la zone sûre maskable -->
<g fill="none" stroke="url(#branch)" stroke-width="17" stroke-linecap="round" stroke-linejoin="round" filter="url(#glow)">
<!-- tronc : du nœud sommet jusqu'à la base avec le curseur >_ -->
<path d="M256 96 V392"/>
<!-- paire haute -->
<path d="M256 232 L150 232 V150"/>
<path d="M256 232 L362 232 V150"/>
<!-- paire médiane -->
<path d="M256 300 L104 300 V214"/>
<path d="M256 300 L408 300 V214"/>
<!-- paire basse -->
<path d="M256 356 L150 356 V300"/>
<path d="M256 356 L362 356 V300"/>
<!-- base : invite de commande >_ -->
<path d="M232 404 L246 418 L232 432" stroke-width="14"/>
<path d="M258 434 H286" stroke-width="14"/>
</g>
<!-- nœuds (sessions) : anneaux cyan lumineux, centre sombre -->
<g filter="url(#glow)">
<g fill="#09090b" stroke="#22d3ee" stroke-width="9">
<circle cx="256" cy="96" r="20"/>
<circle cx="150" cy="150" r="16"/>
<circle cx="362" cy="150" r="16"/>
<circle cx="104" cy="214" r="16"/>
<circle cx="408" cy="214" r="16"/>
<circle cx="150" cy="300" r="16"/>
<circle cx="362" cy="300" r="16"/>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.9 KiB

-4
View File
@@ -1,4 +0,0 @@
User-agent: *
Allow: /
Sitemap: https://git-arboretum.com/sitemap.xml

Some files were not shown because too many files have changed in this diff Show More