diff --git a/.gitignore b/.gitignore index 671ef1b..4dab103 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,9 @@ mosquitto/passwd agent/agent.yaml mosquitto/*.pwd +# --- Configuration locale du serveur (modèle versionné : server/config.example.yaml, « make config ») --- +server/config.yaml + # --- Données personnelles (voix = donnée biométrique) --- docs/test-suivi-perso.txt recordings/ diff --git a/CONTEXT.md b/CONTEXT.md index 1228892..aebf765 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -53,7 +53,8 @@ capteur R503 + bouton conservé) — mêmes règles de validation : | F4b | Suppression du code devenu inutile (VAD, diarisation, voix, mot de réveil, mains libres, firmware d'écoute continue, outils, extras) | **fait** | **oui (2026-10-18)** | | F5 | ESP32-S3 Mini (deuxième environnement PlatformIO) | **fait** (`dd268d2`) | **oui (2026-10-19)** | | F6 | Configuration en plusieurs fichiers : `include` (motifs admis), `server/conf/` | **fait** (`0d00b50`) | **oui (2026-10-19)** | -| F7 | Le serveur démarre avec la machine : service systemd (`make server-install`) | **fait** | **oui (2026-10-19)** | +| F7 | Le serveur démarre avec la machine : service systemd (`make server-install`) | **fait** (`311fde1`) | **oui (2026-10-19)** | +| F8 | `server/config.example.yaml` versionné, `server/config.yaml` ignoré par git, créé par `make install` / `make config` | **fait** | **oui (2026-10-19)** | **Exigence ajoutée par l'utilisateur (2026-09-30)** : l'assistant doit aussi pouvoir **commander des machines Linux du réseau**. Absente de la feuille de route du prompt. Proposition en discussion : @@ -206,6 +207,8 @@ server/voice_server/settings.py config.yaml (+ include, F6) + .env server/conf/home.yaml, machines.yaml, access.yaml sections home / machines / access + fingerprint [F6] server/tests/conftest.py, test_config_include.py copie de la config, 28 tests de l'inclusion [F6] server/voice-server.service modèle d'unité systemd (@USER@, @SERVER_DIR@) [F7] +server/config.example.yaml modèle de configuration versionné ; config.yaml = copie locale ignorée [F8] +server/tests/test_config_example.py modèle, .gitignore, make config / config-diff, message d'un config.yaml absent [F8] server/tests/test_service_unit.py rendu de l'unité, systemd-analyze, garde de « make run » [F7] server/voice_server/mqtt_link.py paho-mqtt 2.x, abonnement voice/+/... [étape 4] server/voice_server/audio_buffer.py PCM borné, niveaux, écriture WAV [étape 4] @@ -269,7 +272,7 @@ TLS (option de l'étape 15, non activée). ### État au 2026-10-19 (branche `fingerprint`) -- Branche `fingerprint` : **F1 à F4b, F5, F6 et F7 validées**. Commits : `67bd4a4` (F1), `19c935c` (F2), `0c7fae1` (F3), `6e432be` (F4), +- Branche `fingerprint` : **F1 à F4b, F5, F6, F7 et F8 validées**. Commits : `67bd4a4` (F1), `19c935c` (F2), `0c7fae1` (F3), `6e432be` (F4), `254fc09` (F4b), `dd268d2` (F5). F5 validée par l'utilisateur le 2026-10-19 après essai sur la carte, y compris « autre doigt = 3 éclairs rouges ». - F6 (configuration en plusieurs fichiers) **validée par l'utilisateur le 2026-10-19** ; `make test` : 300 tests, pyright 0 erreur ; @@ -277,9 +280,9 @@ TLS (option de l'étape 15, non activée). similarité). - Avant F6 : 272 tests, pyright 0 erreur, `make fw-check` SUCCESS pour `esp32dev` (RAM 36,9 % / Flash 33,2 %) et `esp32s3mini` (36,8 % / 32,8 %). -- Le `server/config.yaml` de travail de l'utilisateur garde `mqtt.host: 192.168.1.4` (non commité, le dépôt garde `10.42.0.1`) ; - `wake.enabled: false` sur la branche (le doigt remplace le mot de réveil). Pour commiter `config.yaml`, ne jamais embarquer cette - adresse (index forcé par `git hash-object -w` + `git update-index --cacheinfo`). +- Depuis F8, `server/config.yaml` n'est plus suivi par git : c'est la copie locale de l'utilisateur (`mqtt.host: 192.168.1.4`), + créée depuis `server/config.example.yaml` (modèle, `mqtt.host: 10.42.0.1`) par `make install` / `make config`. Plus besoin de + l'index forcé (`git hash-object` + `update-index`) : le modèle se commite normalement. `wake.enabled: false` sur la branche. - Après `git merge main` : le firmware de `main` n'a pas le capteur ; relire `main.cpp` en cas de conflit. - Décisions de l'utilisateur (2026-10-19) : le schéma WROOM (`wiring.svg`) **reste tel quel** (sans R503 ni LED de démonstration) ; **pas de liste de réseaux** dans le portail (le nom se recopie à l'identique). @@ -1152,3 +1155,15 @@ profils vocaux, enregistrements (wav/mp3), modèles, journaux et environnements travail de `server/config.yaml` porte de nouveau `192.168.1.4` (modification locale, non commitée) ; le dépôt garde `10.42.0.1`. `prompt-assistant-vocal-esp32.md` (fichier suivi par git) a été **supprimé volontairement par l'utilisateur** ; sa suppression n'est pas dans le commit de F7 (reste dans l'historique : `git show d20976f:prompt-assistant-vocal-esp32.md`). +- **2026-10-19** — **F8 écrite** (demande : « faire un config.example.yaml et mettre config.yaml dans .gitignore. Faire un cp + config.example vers config à l'install »). `server/config.example.yaml` = version du dépôt (`mqtt.host: 10.42.0.1`) + en-tête qui + explique le mécanisme ; `.gitignore` : `server/config.yaml` ; `Makefile` : `config` (copie sans jamais écraser), `config-diff`, + `install: venv config`, `MQTT_HOST` lu dans `config.yaml` ou, à défaut, dans le modèle, `server-install` exige `config.yaml` ; + `__main__.py` : un `config.yaml` absent dit « make config le crée depuis config.example.yaml ». **Les tests lisent le modèle** + (7 fichiers de tests + `conftest.py`) : ils ne dépendent plus de la copie locale et passent sur un clone neuf. Le fichier local de + l'utilisateur n'est pas touché (`git rm --cached` : il reste sur le disque, ignoré). `server/conf/*.yaml` restent versionnés. + **Autres machines** : au premier `git pull` de cette étape, git y supprime le `config.yaml` suivi jusque-là (à sauvegarder avant). +- **2026-10-19** — **F8 validée** par l'utilisateur (« uniquement commiter F8 et pousser ») : le commit retire `server/config.yaml` de + l'index (`git rm --cached`, le fichier local reste sur le disque), ajoute `config.example.yaml`, `.gitignore`, le Makefile, les + tests et la documentation. **Décision** : `server/conf/*.yaml` restent versionnés (pas de modèle `*.example.yaml` pour eux) ; à + reprendre si l'utilisateur enregistre d'autres personnes (`conf/access.yaml` porte les noms). diff --git a/Makefile b/Makefile index 6f41db3..f3e8308 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,9 @@ PIO_VENV := .pio-venv PIO := $(PIO_VENV)/bin/pio FW_DIR := firmware # Service systemd du serveur (étape F7) : compte qui le fait tourner, dossier server/ de ce dépôt. +# Configuration du serveur : le modèle est versionné, la copie locale (ignorée par git) est celle que le serveur lit. +CONFIG_FILE ?= server/config.yaml +CONFIG_EXAMPLE ?= server/config.example.yaml SERVICE := voice-server SERVICE_USER ?= $(shell id -un) SERVER_DIR = $(realpath server) @@ -28,9 +31,9 @@ JITTER ?= 0 VOICE ?= fr_FR-tom-medium SPEAKER ?= SAY_OUT ?= recordings/voix-test/phrase.wav -# Adresse du broker : UN seul réglage, mqtt.host de server/config.yaml, relu ici pour les +# Adresse du broker : UN seul réglage, mqtt.host de server/config.yaml (à défaut, du modèle), relu ici pour les # cibles mqtt-* (surcharge ponctuelle : make mqtt-watch MQTT_HOST=...). -MQTT_HOST ?= $(shell awk '/^mqtt:/{m=1;next} m && $$1=="host:"{print $$2; exit}' server/config.yaml) +MQTT_HOST ?= $(shell awk '/^mqtt:/{m=1;next} m && $$1=="host:"{print $$2; exit}' $(if $(wildcard $(CONFIG_FILE)),$(CONFIG_FILE),$(CONFIG_EXAMPLE))) MSG ?= {"cmd":"ping"} MOSQ_DIR ?= $(HOME)/srv/mosquitto MOSQ_COMPOSE ?= $(HOME)/srv/docker-compose.mosquitto.yml @@ -47,7 +50,7 @@ MQTT_AS = @echo "(compte MQTT : $(if $(MQTT_USERNAME),$(MQTT_USERNAME) de s .DEFAULT_GOAL := help .PHONY: help install-system mosquitto-config mosquitto-docker mqtt-user agent-run agent-install agent-log mqtt-agents mqtt-watch mqtt-transcript mqtt-home mqtt-control venv install install-dev install-speech models \ - say latency finger-list finger-enroll finger-delete speech-check transcribe run server-guard server-unit server-install server-uninstall server-status server-log test lint record play inspect play-esp tone-esp play-mqtt tone-mqtt run-echo pio-venv fw-build fw-check fw-upload \ + say latency finger-list finger-enroll finger-delete speech-check transcribe run config config-diff server-guard server-unit server-install server-uninstall server-status server-log test lint record play inspect play-esp tone-esp play-mqtt tone-mqtt run-echo pio-venv fw-build fw-check fw-upload \ fw-monitor clean ## ------------------------------------------------------------------ aide @@ -143,7 +146,7 @@ venv: ## Crée l'environnement virtuel Python python3 -m venv $(VENV) $(PIP) install --upgrade pip setuptools wheel -install: venv ## Installe le serveur Python (dépendances de base) +install: venv config ## Installe le serveur Python (dépendances de base) et crée server/config.yaml s'il manque $(PIP) install -e server @test -f server/.env || { cp server/.env.example server/.env; echo "server/.env créé depuis .env.example — renseigner MQTT_USERNAME/PASSWORD."; } @@ -153,6 +156,13 @@ install-dev: install pio-venv ## Installe en plus les outils de développement install-speech: install ## Installe faster-whisper et Piper (étape 6) $(PIP) install -e "server[speech]" +config: ## Crée server/config.yaml depuis config.example.yaml, sans jamais écraser un fichier existant + @if [ -f $(CONFIG_FILE) ]; then echo "$(CONFIG_FILE) existe deja : rien a faire (make config-diff le compare au modele)."; \ + else cp $(CONFIG_EXAMPLE) $(CONFIG_FILE) && echo "$(CONFIG_FILE) cree depuis $(notdir $(CONFIG_EXAMPLE)) : verifiez mqtt.host."; fi + +config-diff: ## Montre ce qui diffère entre le modèle config.example.yaml et votre server/config.yaml + @diff -u $(CONFIG_EXAMPLE) $(CONFIG_FILE) || true + models: ## Télécharge Whisper et la voix Piper de config.yaml dans server/models $(PY) tools/download_models.py @@ -200,6 +210,7 @@ server-install: ## Installe le serveur comme service (sudo) : démarre au boot, @if pgrep -f '[v]oice_server --config' >/dev/null; then \ echo "Un serveur tourne deja (make run ?) : arretez-le (Ctrl-C) avant, sinon les deux se chassent du broker."; exit 1; fi @test -x $(SERVER_DIR)/.venv/bin/python || { echo "server/.venv absent : make install"; exit 1; } + @test -f $(CONFIG_FILE) || { echo "$(CONFIG_FILE) absent : make config, puis verifiez mqtt.host"; exit 1; } $(RENDER_UNIT) | sudo tee /etc/systemd/system/$(SERVICE).service >/dev/null sudo systemctl daemon-reload sudo systemctl enable --now $(SERVICE) diff --git a/README-EN.md b/README-EN.md index 1e1908c..88e75a7 100644 --- a/README-EN.md +++ b/README-EN.md @@ -205,7 +205,7 @@ make run | File | Contents | |---|---| | `server/.env` | `MQTT_USERNAME`, `MQTT_PASSWORD` | -| `server/config.yaml` | general settings (audio, MQTT, voices, log) and the list of included files | +| `server/config.yaml` | **your local copy** (ignored by git, created by `make install` from `config.example.yaml`): general settings (audio, MQTT, voices, log) and the list of included files | | `server/conf/home.yaml` | rooms and the room of each board | | `server/conf/machines.yaml` | Linux machines on the network and their actions | | `server/conf/access.yaml` | rights per person (`access`) and the owner of each finger (`fingerprint`) | @@ -305,7 +305,36 @@ make lint # pyright type check The exact state of the project, step by step, lives in **[CONTEXT.md](CONTEXT.md)**. Current step: **done — steps 1 to 16 are validated** (`main` branch). -`fingerprint` branch: F1 to F4b, F5 (ESP32-S3 Mini), F6 (configuration in several files) and F7 (server under systemd) validated. +`fingerprint` branch: F1 to F4b, F5 (ESP32-S3 Mini), F6 (configuration in several files), F7 (server under systemd) and F8 (versioned configuration template, ignored local copy) validated + +### `fingerprint` branch — step F8: a versioned configuration template, an ignored local copy + +`server/config.example.yaml` is the **template** (versioned); `server/config.yaml` is **your copy** (ignored by git): the +server, the tools and the service read that one. No more risk of committing your broker address, or of losing it to a +"discard changes". + +```bash +make install # creates server/config.yaml from the template if missing (like server/.env), never overwriting it +make config # the same, alone +make config-diff # what differs between the template and your copy (re-read it when the template changes) +``` + +| Point | Detail | +|---|---| +| fresh clone | `make install` creates `server/config.yaml`; **check `mqtt.host`** (the template points at `10.42.0.1`, the Raspberry Pi) | +| the template changes | your copy is not touched: `make config-diff`, then carry the new keys over by hand | +| `server/conf/*.yaml` | stay versioned (starting values); only `config.yaml` is local | +| `make run`, service | a missing `config.yaml` gives `configuration invalide` and "`make config` creates it from config.example.yaml" | +| tests | they read the template: their results do not depend on your copy | + +**Another machine that already has this repository** (the Raspberry Pi, a second PC): on the first `git pull` that brings this +step, git removes the `server/config.yaml` it used to track. Copy it before (`cp server/config.yaml ~/config.yaml.backup`) +and put it back afterwards; without local changes, `make config` recreates a file from the template. + +1. `git pull` has nothing to do on your machine: your `server/config.yaml` stays (same content, `192.168.1.4`), and `git status` + no longer shows it. +2. `make config`: "existe deja: rien a faire"; `make config-diff`: shows only your differences (broker address…). +3. Fresh clone (temporary folder): `make config` creates `server/config.yaml` from the template. ### `fingerprint` branch — step F7: the server starts with the machine (systemd) @@ -331,7 +360,7 @@ make server-uninstall # removes the service (the repository and the recordings | `make run` | refused while the service runs: two servers with the same MQTT identifier kick each other out of the broker in a loop | | secrets | `.env` stays in `server/`, read by the server; nothing is copied into the unit or the log | -The service reads `server/config.yaml` **as it is at start-up**: check `mqtt.host` before installing (the repository's value is +The service reads `server/config.yaml` **as it is at start-up**: check `mqtt.host` before installing (the template's value is `10.42.0.1`, the Raspberry Pi). 1. Stop the server started by hand (Ctrl-C in the `make run` terminal), then `make server-install`: `active (running)`. diff --git a/README.md b/README.md index e2e26b5..b9fe415 100644 --- a/README.md +++ b/README.md @@ -207,7 +207,7 @@ make run | Fichier | Contenu | |---|---| | `server/.env` | `MQTT_USERNAME`, `MQTT_PASSWORD` | -| `server/config.yaml` | réglages généraux (audio, MQTT, voix, journal) et liste des fichiers inclus | +| `server/config.yaml` | **votre copie locale** (ignorée par git, créée par `make install` depuis `config.example.yaml`) : réglages généraux (audio, MQTT, voix, journal) et liste des fichiers inclus | | `server/conf/home.yaml` | pièces et pièce de chaque carte | | `server/conf/machines.yaml` | machines Linux du réseau et leurs actions | | `server/conf/access.yaml` | droits par personne (`access`) et propriétaire de chaque doigt (`fingerprint`) | @@ -307,7 +307,36 @@ make lint # typage pyright L'état exact du projet, étape par étape, est dans **[CONTEXT.md](CONTEXT.md)**. Étape courante : **terminée — les étapes 1 à 16 sont validées** (branche `main`). -Branche `fingerprint` : F1 à F4b, F5 (ESP32-S3 Mini), F6 (configuration en plusieurs fichiers) et F7 (serveur sous systemd) validées. +Branche `fingerprint` : F1 à F4b, F5 (ESP32-S3 Mini), F6 (configuration en plusieurs fichiers), F7 (serveur sous systemd) et F8 (modèle de configuration versionné, copie locale ignorée) validées + +### Branche `fingerprint` — étape F8 : un modèle de configuration versionné, une copie locale ignorée + +`server/config.example.yaml` est le **modèle** (versionné) ; `server/config.yaml` est **votre copie** (ignorée par git) : le serveur, +les outils et le service lisent celle-là. Plus de risque de commiter votre adresse de broker, ni de la perdre à un +« annuler les modifications ». + +```bash +make install # crée server/config.yaml depuis le modèle s'il manque (comme server/.env), sans jamais l'écraser +make config # la même chose, seule +make config-diff # ce qui diffère entre le modèle et votre copie (à relire quand le modèle change) +``` + +| Point | Détail | +|---|---| +| clone neuf | `make install` crée `server/config.yaml` ; **vérifiez `mqtt.host`** (le modèle vise `10.42.0.1`, le Raspberry Pi) | +| le modèle change | votre copie n'est pas touchée : `make config-diff`, puis reportez à la main les nouvelles clés | +| `server/conf/*.yaml` | restent versionnés (valeurs de départ) ; seul `config.yaml` est local | +| `make run`, service | un `config.yaml` absent donne `configuration invalide` et « `make config` le crée depuis config.example.yaml » | +| tests | ils lisent le modèle : leurs résultats ne dépendent pas de votre copie | + +**Autre machine qui a déjà ce dépôt** (le Raspberry Pi, un second PC) : au premier `git pull` qui apporte cette étape, git retire +le `server/config.yaml` suivi jusque-là. Copiez-le avant (`cp server/config.yaml ~/config.yaml.sauvegarde`) puis remettez-le +après ; sans modification locale, `make config` recrée un fichier depuis le modèle. + +1. `git pull` n'a rien à faire chez vous : votre `server/config.yaml` reste (même contenu, `192.168.1.4`), et `git status` ne le + montre plus. +2. `make config` : « existe deja : rien a faire » ; `make config-diff` : montre seulement vos différences (adresse du broker…). +3. Clone neuf (dossier temporaire) : `make config` crée `server/config.yaml` depuis le modèle. ### Branche `fingerprint` — étape F7 : le serveur démarre avec la machine (systemd) @@ -333,7 +362,7 @@ make server-uninstall # retire le service (le dépôt et les enregistrements re | `make run` | refusé tant que le service tourne : deux serveurs de même identifiant MQTT se chassent du broker en boucle | | secrets | `.env` reste dans `server/`, lu par le serveur ; rien n'est copié dans l'unité ni dans le journal | -Le service lit `server/config.yaml` **tel qu'il est au démarrage** : vérifiez `mqtt.host` avant d'installer (celui du dépôt est +Le service lit `server/config.yaml` **tel qu'il est au démarrage** : vérifiez `mqtt.host` avant d'installer (celui du modèle est `10.42.0.1`, le Raspberry Pi). 1. Arrêtez le serveur lancé à la main (Ctrl-C dans le terminal de `make run`), puis `make server-install` : `active (running)`. diff --git a/server/config.yaml b/server/config.example.yaml similarity index 89% rename from server/config.yaml rename to server/config.example.yaml index 35ef56c..96ada69 100644 --- a/server/config.yaml +++ b/server/config.example.yaml @@ -1,4 +1,7 @@ -# Configuration du serveur vocal. +# Configuration du serveur vocal : MODÈLE versionné (config.example.yaml). +# « make config » (lancé aussi par « make install ») en fait server/config.yaml, ignoré par git : c'est ce fichier +# que le serveur lit et que vous adaptez (mqtt.host, doigts, droits…). Il n'est jamais écrasé ; « make config-diff » +# montre ce qui diffère de ce modèle quand celui-ci change. # Les valeurs sensibles (mots de passe, jetons) vont dans .env, jamais ici. # Les sections marquées « étape N » ne sont lues qu'à partir de cette étape. # Branche fingerprint : pas de VAD, de diarisation, de voix ni de mot de réveil (étapes F3 à F4b). diff --git a/server/tests/conftest.py b/server/tests/conftest.py index 2610759..48df75b 100644 --- a/server/tests/conftest.py +++ b/server/tests/conftest.py @@ -12,12 +12,13 @@ SERVER_DIR = Path(__file__).resolve().parents[1] @pytest.fixture def config_copy(tmp_path: Path) -> Path: - """Copie de config.yaml et des fichiers qu'il inclut (server/conf) : modifiable sans toucher aux vrais. + """Copie du modèle config.example.yaml (sous le nom config.yaml) et des fichiers qu'il inclut (server/conf) : + modifiable sans toucher aux vrais, et indépendante de la copie locale de l'utilisateur. Rend le chemin du config.yaml copié ; les fichiers inclus sont dans le dossier conf voisin. """ destination = tmp_path / "server" destination.mkdir() - shutil.copy2(SERVER_DIR / "config.yaml", destination / "config.yaml") + shutil.copy2(SERVER_DIR / "config.example.yaml", destination / "config.yaml") shutil.copytree(SERVER_DIR / "conf", destination / "conf") return destination / "config.yaml" diff --git a/server/tests/test_access_control.py b/server/tests/test_access_control.py index 7686e62..8ca6ee9 100644 --- a/server/tests/test_access_control.py +++ b/server/tests/test_access_control.py @@ -159,8 +159,8 @@ def test_other_request_drops_the_pending_one(policy: AccessPolicy) -> None: def test_project_config_is_valid() -> None: - """Le config.yaml du dépôt se charge, et ses règles s'appliquent vraiment (profil standard).""" - settings = load_settings(Path(__file__).resolve().parents[1] / "config.yaml") + """Le modèle config.example.yaml se charge, et ses règles s'appliquent vraiment (profil standard).""" + settings = load_settings(Path(__file__).resolve().parents[1] / "config.example.yaml") policy = AccessPolicy(settings.access, settings.home, settings.machines) for action in ("on", "off"): # on/off nus en YAML = booléens : Pierre refusé à l'essai réel assert policy.check(DeviceCommand(action, "light", "salon"), "Pierre").allowed diff --git a/server/tests/test_config_example.py b/server/tests/test_config_example.py new file mode 100644 index 0000000..02a0498 --- /dev/null +++ b/server/tests/test_config_example.py @@ -0,0 +1,88 @@ +"""Étape F8 : config.example.yaml est le modèle versionné ; server/config.yaml est la copie locale, ignorée par git.""" + +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path + +import pytest + +from voice_server.__main__ import EXIT_SETUP, main +from voice_server.settings import load_settings + +SERVER_DIR = Path(__file__).resolve().parents[1] +REPO = SERVER_DIR.parent +EXAMPLE = SERVER_DIR / "config.example.yaml" + + +def make(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run(["make", "-s", *args], cwd=REPO, capture_output=True, text=True, check=False) + + +def test_example_loads_and_keeps_the_repository_broker() -> None: + """Le modèle se charge seul (un clone neuf n'a pas de config.yaml) et vise le broker du dépôt.""" + settings = load_settings(EXAMPLE) + + assert settings.mqtt.host == "10.42.0.1" + assert settings.home.rooms and settings.access.users + + +@pytest.mark.skipif(shutil.which("git") is None or not (REPO / ".git").exists(), reason="pas un dépôt git") +def test_local_config_is_ignored_by_git_and_the_example_is_not() -> None: + def ignored(path: str) -> bool: + return subprocess.run(["git", "check-ignore", "--no-index", "-q", path], cwd=REPO, check=False).returncode == 0 + + assert ignored("server/config.yaml") + assert not ignored("server/config.example.yaml") + + +@pytest.mark.skipif(shutil.which("make") is None, reason="make absent") +def test_make_config_creates_the_local_file_from_the_example(tmp_path: Path) -> None: + target = tmp_path / "config.yaml" + + result = make("config", f"CONFIG_FILE={target}", f"CONFIG_EXAMPLE={EXAMPLE}") + + assert result.returncode == 0, result.stderr + assert target.read_text(encoding="utf-8") == EXAMPLE.read_text(encoding="utf-8") + assert "verifiez mqtt.host" in result.stdout + + +@pytest.mark.skipif(shutil.which("make") is None, reason="make absent") +def test_make_config_never_overwrites_an_existing_file(tmp_path: Path) -> None: + target = tmp_path / "config.yaml" + target.write_text("mqtt:\n host: 192.168.1.4\n", encoding="utf-8") + + result = make("config", f"CONFIG_FILE={target}", f"CONFIG_EXAMPLE={EXAMPLE}") + + assert result.returncode == 0 + assert target.read_text(encoding="utf-8") == "mqtt:\n host: 192.168.1.4\n" + assert "existe deja" in result.stdout + + +@pytest.mark.skipif(shutil.which("make") is None, reason="make absent") +def test_make_install_creates_the_config() -> None: + """« make install » passe par la cible config (make -n n'exécute rien).""" + result = subprocess.run(["make", "-n", "install"], cwd=REPO, capture_output=True, text=True, check=False) + + assert "cp server/config.example.yaml server/config.yaml" in result.stdout + + +@pytest.mark.skipif(shutil.which("make") is None, reason="make absent") +def test_config_diff_shows_what_changed_from_the_example(tmp_path: Path) -> None: + local = tmp_path / "config.yaml" + local.write_text(EXAMPLE.read_text(encoding="utf-8").replace("10.42.0.1", "192.168.1.4"), encoding="utf-8") + + result = make("config-diff", f"CONFIG_FILE={local}", f"CONFIG_EXAMPLE={EXAMPLE}") + + assert "- host: 10.42.0.1" in result.stdout and "+ host: 192.168.1.4" in result.stdout + + +def test_server_says_how_to_create_a_missing_config(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Un clone neuf lance le serveur sans config.yaml : le message dit quoi faire.""" + shutil.copy2(EXAMPLE, tmp_path / "config.example.yaml") + shutil.copytree(SERVER_DIR / "conf", tmp_path / "conf") + + assert main(["--config", str(tmp_path / "config.yaml")]) == EXIT_SETUP + + assert "make config" in capsys.readouterr().err diff --git a/server/tests/test_config_include.py b/server/tests/test_config_include.py index f032586..3b233b4 100644 --- a/server/tests/test_config_include.py +++ b/server/tests/test_config_include.py @@ -181,24 +181,24 @@ def test_included_file_must_be_a_mapping(tmp_path: Path) -> None: read_config(config) -# --------------------------------------------------------------------------- le config.yaml du dépôt +# --------------------------------------------------------------------------- le modèle du dépôt def test_project_config_takes_its_sections_from_conf() -> None: """Les sections découpées arrivent bien de server/conf, et « include » ne reste pas dans le résultat.""" - config = read_config(SERVER_DIR / "config.yaml") + config = read_config(SERVER_DIR / "config.example.yaml") assert "include" not in config for section in ("audio", "mqtt", "stt", "home", "machines", "access", "fingerprint"): assert section in config, section - raw = (SERVER_DIR / "config.yaml").read_text(encoding="utf-8") + raw = (SERVER_DIR / "config.example.yaml").read_text(encoding="utf-8") for moved in ("home", "machines", "access", "fingerprint"): assert f"\n{moved}:" not in raw, f"{moved} devrait vivre dans conf/" def test_mqtt_host_stays_readable_by_the_makefile() -> None: - """Le Makefile lit mqtt.host dans config.yaml avec awk : la section mqtt doit y rester.""" + """Le Makefile lit mqtt.host dans config.yaml (à défaut, dans le modèle) avec awk : la section mqtt doit y rester.""" inside = False host = "" - for line in (SERVER_DIR / "config.yaml").read_text(encoding="utf-8").splitlines(): + for line in (SERVER_DIR / "config.example.yaml").read_text(encoding="utf-8").splitlines(): if line.startswith("mqtt:"): inside = True continue diff --git a/server/tests/test_finger_tool.py b/server/tests/test_finger_tool.py index bc2fffd..d65055d 100644 --- a/server/tests/test_finger_tool.py +++ b/server/tests/test_finger_tool.py @@ -18,7 +18,7 @@ if str(TOOLS_DIR) not in sys.path: from finger import command_delete, command_enroll, command_list, enrollment_message # noqa: E402 -CONFIG = Path(__file__).resolve().parents[1] / "config.yaml" +CONFIG = Path(__file__).resolve().parents[1] / "config.example.yaml" BOOK = FingerprintBook(FingerprintSettings(users={1: "Denis", 2: "Denis", 5: "Jessica"})) @@ -64,7 +64,7 @@ def test_free_id_skips_taken_and_named_slots_and_keeps_zero_free() -> None: def test_project_config_loads() -> None: - """Le config.yaml du dépôt se charge ; son contenu appartient à l'utilisateur (ses doigts).""" + """Le modèle config.example.yaml se charge (la copie locale server/config.yaml, elle, appartient à l'utilisateur).""" users = load_settings(CONFIG).fingerprint.users assert all(isinstance(number, int) and number >= 0 and name for number, name in users.items()) diff --git a/server/tests/test_home_control.py b/server/tests/test_home_control.py index cf73421..d359423 100644 --- a/server/tests/test_home_control.py +++ b/server/tests/test_home_control.py @@ -103,6 +103,6 @@ def test_assistant_prefers_home_commands_then_chat() -> None: def test_project_config_rooms_and_boards() -> None: - """Le config.yaml du dépôt déclare la pièce de la carte parmi les pièces connues.""" - home = load_settings(Path(__file__).resolve().parents[1] / "config.yaml").home + """Le modèle config.example.yaml déclare la pièce de la carte parmi les pièces connues.""" + home = load_settings(Path(__file__).resolve().parents[1] / "config.example.yaml").home assert home.boards["esp32-01"] in home.rooms diff --git a/server/tests/test_machine_control.py b/server/tests/test_machine_control.py index df02110..2d6be26 100644 --- a/server/tests/test_machine_control.py +++ b/server/tests/test_machine_control.py @@ -26,7 +26,7 @@ from voice_server.machine_control import ( from voice_server.mqtt_link import MqttLink from voice_server.settings import MachinesSettings, load_settings -SETTINGS = load_settings(Path(__file__).resolve().parents[1] / "config.yaml") +SETTINGS = load_settings(Path(__file__).resolve().parents[1] / "config.example.yaml") MACHINES = SETTINGS.machines ONLINE = AgentStatus(online=True, actions=("lock", "reboot", "shutdown")) ONLINE_PAYLOAD = json.dumps({"status": "online", "actions": ["lock", "reboot", "shutdown"]}).encode() diff --git a/server/tests/test_mqtt_link.py b/server/tests/test_mqtt_link.py index 1c79393..630e931 100644 --- a/server/tests/test_mqtt_link.py +++ b/server/tests/test_mqtt_link.py @@ -15,7 +15,7 @@ from voice_server.__main__ import setup_logging from voice_server.mqtt_link import presence_topic, refusal_hint, split_topic from voice_server.settings import load_settings -CONFIG = Path(__file__).resolve().parents[1] / "config.yaml" +CONFIG = Path(__file__).resolve().parents[1] / "config.example.yaml" def test_presence_topic_is_not_taken_for_a_board() -> None: diff --git a/server/tests/test_session_manager.py b/server/tests/test_session_manager.py index 1916492..fa12fa8 100644 --- a/server/tests/test_session_manager.py +++ b/server/tests/test_session_manager.py @@ -170,8 +170,8 @@ def test_split_topic(topic: str, expected: tuple[str, str] | None) -> None: def test_project_config_loads() -> None: - """Le config.yaml du dépôt se charge et reste cohérent avec le firmware.""" - settings = load_settings(Path(__file__).resolve().parents[1] / "config.yaml") + """Le modèle config.example.yaml se charge et reste cohérent avec le firmware.""" + settings = load_settings(Path(__file__).resolve().parents[1] / "config.example.yaml") assert settings.audio.bytes_per_second == 32000 assert settings.mqtt.topic_prefix == "voice" diff --git a/server/tests/test_speech_models.py b/server/tests/test_speech_models.py index e9eeae5..4773457 100644 --- a/server/tests/test_speech_models.py +++ b/server/tests/test_speech_models.py @@ -19,7 +19,7 @@ from voice_server.speech_to_text import SpeechToText from voice_server.text_normalize import normalize from voice_server.text_to_speech import TextToSpeech -SETTINGS: Settings = load_settings(Path(__file__).resolve().parents[1] / "config.yaml") +SETTINGS: Settings = load_settings(Path(__file__).resolve().parents[1] / "config.example.yaml") pytestmark = pytest.mark.skipif( not (SETTINGS.stt.model_dir / "model.bin").exists() or not SETTINGS.tts.model_path.exists(), diff --git a/server/voice_server/__main__.py b/server/voice_server/__main__.py index 74ec869..f96472b 100644 --- a/server/voice_server/__main__.py +++ b/server/voice_server/__main__.py @@ -159,6 +159,9 @@ def main(argv: list[str]) -> int: except (ValueError, OSError, yaml.YAMLError) as error: # Le journal n'est pas encore réglé (il dépend de la configuration) : message direct, sans trace d'appels. print(f"configuration invalide : {error}", file=sys.stderr) + example = args.config.with_name(f"{args.config.stem}.example{args.config.suffix}") + if isinstance(error, FileNotFoundError) and not args.config.exists() and example.exists(): + print(f"{args.config} n'existe pas : « make config » le crée depuis {example.name}", file=sys.stderr) return EXIT_SETUP setup_logging(settings) logging.getLogger("faster_whisper").setLevel(logging.WARNING) # une ligne par transcription sinon