Metadata-Version: 2.5
Name: arclith-cli
Version: 0.29.0
Summary: CLI scaffolding tool for arclith — hexagonal architecture framework
Author-email: Killian KOPP <killiankopp@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and its Derivative Works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submitted" means any form of electronic, verbal,
              or written communication sent to the Licensor or its representatives,
              including but not limited to communication on electronic mailing lists,
              source code control systems, and issue tracking systems that are managed
              by, or on behalf of, the Licensor for the purpose of developing and
              refining the Work, but excluding communication that is conspicuously
              marked or designated in writing by the copyright owner as "Not a
              Contribution."
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and included
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent contributions
              Licensable by such Contributor that are necessarily infringed by
              their Contribution(s) alone or by the combination of their
              Contribution(s) with the Work to which such Contribution(s) was
              submitted. If You institute patent litigation against any entity
              (including a cross-claim or counterclaim in a lawsuit) alleging that
              the Work or any Contribution embodied within the Work constitutes
              direct or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate as
              of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, You must include a readable copy of the
                  attribution notices contained within such NOTICE file, in
                  at least one of the following places: within a NOTICE text
                  file distributed as part of the Derivative Works; within
                  the Source form or documentation, if provided along with the
                  Derivative Works; or, within a display generated by the
                  Derivative Works, if and wherever such third-party notices
                  normally appear. The contents of the NOTICE file are for
                  informational purposes only and do not modify the License.
                  You may add Your own attribution notices within Derivative
                  Works that You distribute, alongside or in addition to the
                  NOTICE text from the Work, provided that such additional
                  attribution notices cannot be construed as modifying the License.
        
              You may add Your own license statement for Your modifications and
              may provide additional grant of rights to use, copy, modify, merge,
              publish, distribute, sublicense, and/or sell copies of the Work.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or reproducing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or exemplary damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or all other
              commercial damages or losses), even if such Contributor has been
              advised of the possibility of such damages.
        
           9. Accepting Warranty or Liability. While redistributing the Work or
              Derivative Works thereof, You may choose to offer, and charge a fee
              for, acceptance of support, warranty, indemnity, or other liability
              obligations and/or rights consistent with this License. However, in
              accepting such obligations, You may offer only conditions that
              You alone are responsible for, and not on behalf of any other
              Contributor.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2026 Killian KOPP
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
License-File: LICENSE
Keywords: arclith,cli,ddd,hexagonal-architecture,scaffold
Requires-Python: >=3.13
Requires-Dist: arclith>=0.32.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: questionary<3.0.0,>=2.1.1
Requires-Dist: rich<15.0.0,>=14.2.0
Requires-Dist: textual<9.0.0,>=8.2.8
Requires-Dist: typer>=0.15.0
Description-Content-Type: text/markdown

# arclith-cli

`arclith-cli` construit un projet Python hexagonal par étapes. `init` pose uniquement le socle
installable ; chaque adapter, transport et dépendance optionnelle est ensuite ajouté explicitement.
`new` reste disponible comme raccourci compatible pour `init` suivi de `add-entity`, sans adapter
implicite.

## Installation

```bash
uv tool install "git+https://github.com/karned-rekipe/arclith.git#subdirectory=cli"
```

## Cockpit plein écran

Exécuter `arclith-cli` sans argument dans un vrai terminal ouvre une TUI
persistante. Le cockpit propose un résultat (socle minimal, API CRUD, API sur
mesure, serveur MCP, agent LangGraph ou worker RabbitMQ), puis avance réellement
par étapes : intention, domaine, stockage, transport et vérification. Les actions
restent visibles dans les terminaux compacts. Le cockpit affiche le plan et les
commandes équivalentes avant d'écrire :

```bash
arclith-cli
# ou explicitement pour la TUI
arclith-cli tui
# interface Questionary compacte et catalogue avancé
arclith-cli guide
```

Après la création, le cockpit ouvre le tableau de bord du projet. Il affiche les
entités, use cases, features, adapters et diagnostics, puis permet de démarrer,
arrêter ou redémarrer les transports disponibles avec leurs logs. Depuis ce
même écran, `a` ouvre le catalogue pour ajouter un adapter et `o` permet de
choisir un autre projet existant avec un navigateur de dossiers. Ces deux
actions restent visibles dans un terminal compact.

Le formulaire d'adapter est entièrement piloté par le catalogue : paramètres,
choix, booléens, profils et secrets. Les adapters déjà installés sont masqués et
la commande reproductible reste affichée avant l'écriture. Ajouter un second
adapter pour une capability ne remplace pas l'adapter actif par défaut ; cette
activation reste une décision explicite, sauf pour l'observabilité cumulative.
Le cockpit avertit séparément lorsqu'un provider partage et remplacera le même
fichier de configuration qu'un adapter déjà présent.
Chaque installation réussie alimente `arclith.recipe.yaml` et les secrets y
restent expurgés.

Le bouton « Guide complet » rejoint l'interface compacte pour les autres
mutations avancées. Une création ou un replay complet utilise un staging
atomique : la cible finale n'apparaît qu'après la réussite de toutes les étapes
et une cible existante n'est jamais écrasée.

Dans un pipe, un script, une CI ou avec `TERM=dumb`, l'appel sans argument reste
non interactif : il affiche l'aide et termine avec succès. Toutes les commandes
directes restent stables et sont montrées dans le plan du guide.

Le projet courant peut aussi être inspecté sans ouvrir le menu :

```bash
arclith-cli status
arclith-cli status --json
arclith-cli doctor
arclith-cli run api
```

`run` retrouve la racine du projet, vérifie le transport installé, synchronise
l'environnement avec `uv` et conserve le runtime en avant-plan. Les modes
`mcp_http`, `mcp_sse`, `bus` et `all` sont proposés lorsque leurs adapters sont
présents. Les logs et le code de sortie restent ceux du processus généré ;
`Ctrl+C` l'arrête normalement.

La documentation complète est disponible dans le
[guide interactif](https://karned-rekipe.github.io/arclith/cli-guide/).

## Commandes

### `init` — Initialiser un projet minimal

Crée un projet Arclith vide de métier, avec le layout canonique `src/<package>/...`, une
configuration minimale et un `main.py` prêt à recevoir les adapters. Les fichiers du runtime
Docker (`Dockerfile`, `.dockerignore`, `arclith-run`) ne sont ajoutés que par
`add-adapter --capability runtime --adapter docker-image`.

```bash
# Mode interactif
arclith-cli init

# Mode direct
arclith-cli init todo-list-service
arclith-cli init todo-list-service --dir ~/projects
```

Cette commande ne crée aucune entité, aucun CRUD et aucun endpoint métier. Elle sert quand on veut
construire le projet étape par étape avec `add-entity`, `add-blueprint`, `add-usecase`, puis
`add-adapter`.
Elle ne crée pas non plus FastAPI ou FastMCP et n'installe aucun de leurs extras.

#### Pourquoi `src/<package>/...` ?

`src/` est la racine des imports du projet installé ; `<package>` est le namespace propre au
service. Les couches restent donc importées comme `todo_service.domain` ou
`todo_service.application`, au lieu de créer des packages Python globaux et génériques nommés
`domain`, `application` et `adapters`. Cette structure évite les collisions, empêche les tests
d'importer accidentellement le dépôt courant à la place du package installé et suit le `src layout`
standard de l'écosystème Python.

#### Parcours complet vers une API

```bash
arclith-cli init todo-api
cd todo-api
arclith-cli add-entity Todo
arclith-cli add-usecase CreateTodo --entity Todo

# Choisir explicitement la persistance et le transport utilisés.
arclith-cli add-adapter --capability repository --adapter memory --yes
arclith-cli add-adapter --capability api --adapter fastapi --param port=8765 --yes

arclith-cli expose-usecase create-todo --via fastapi --feature todos \
  --path /v1/todos --method POST --status-code 201
uv sync
MODE=api uv run python main.py
```

Le parcours fonctionne avec les seuls champs techniques de `Entity`. Le composition root typé
est régénéré automatiquement pour un use case sans dépendance ou avec une dépendance
`Repository[Entity]`. Une composition plus riche reste explicite. Voir le
[guide des bindings](https://karned-rekipe.github.io/arclith/deep-dives/use-case-bindings/).

Pour initialiser plutôt les cinq opérations CRUD, utiliser
`add-entity Todo --profile crud`. Ce blueprint crée le cœur applicatif et sa
composition, mais aucun endpoint. Après installation explicite de FastAPI, la
projection REST complète tient en une commande distincte :

```bash
arclith-cli add-entity Todo --profile crud
arclith-cli add-adapter --capability api --adapter fastapi --yes
arclith-cli expose-feature todo --via fastapi --path /v1/todos
```

Les projections FastMCP, RabbitMQ ou LangGraph restent des décisions distinctes
avec une sémantique propre au transport.

---

### `new` — Raccourci minimal compatible

`new` exécute le même scaffold canonique que `init`, puis ajoute l'entité
demandée avec le profil `minimal` par défaut. Le profil `crud` reste explicite.
Aucun adapter, transport ou runtime Docker n'est créé implicitement.

```bash
# Mode interactif — l'outil pose les questions
arclith-cli new

# Mode direct
arclith-cli new Recipe my-recipe-service
arclith-cli new RecipeStep meal-planner --port 8400
arclith-cli new MealPlan meal-plan-service --dir ~/projects --port 8500
arclith-cli new Todo todo-service --profile crud

# Créer la spec dans le répertoire courant avant le preflight de `new`.
cat > invoice-lifecycle.yaml <<'YAML'
version: 1
state_field: status
initial_state: draft
states: [draft, submitted]
transitions:
  - name: submit
    from: [draft]
    to: submitted
YAML
arclith-cli new Invoice invoice-service --profile state-machine \
  --spec invoice-lifecycle.yaml
```

| Option | Défaut | Description |
|--------|--------|-------------|
| `--port` / `-p` | `8000` | Port à proposer lors du futur ajout explicite de FastAPI |
| `--dir` / `-d` | `.` | Répertoire parent |
| `--profile` | `minimal` | Profil initial (`minimal`, `crud`, `append-only` ou `state-machine`) |
| `--spec` | — | Spec YAML requise par `state-machine` |

Le projet généré utilise un layout `src/<package>/...` pour le code applicatif et un dossier
`config/` structuré par adapter (voir section [Configuration](#configuration)). Utiliser ensuite
`add-usecase`, `add-adapter` puis `expose-usecase`, ou le couple
`add-entity --profile crud` puis `expose-feature`; un Dockerfile n'apparaît que
via l'adapter `runtime/docker-image`.

---

### `add-entity` — Ajouter une entité métier

Crée un squelette minimal et guidé dans `src/<package>/domain/models/`. Le fichier
signale où déclarer les champs et invariants, rappelle les champs déjà fournis par
`Entity` et renvoie vers les guides Arclith et Pydantic. L'exemple `Field(...)`
reste commenté, donc aucun import inutilisé n'est ajouté.

```bash
cd my-recipe-service
arclith-cli add-entity ShoppingItem
arclith-cli add-entity Todo --profile crud
arclith-cli add-entity Invoice --profile state-machine \
  --spec invoice-lifecycle.yaml
```

Fichier généré :

```text
src/<package>/domain/models/shopping_item.py
```

Sans `--profile`, le mode direct conserve le profil `minimal` et ne génère aucun
CRUD, port repository, adapter ou endpoint. En interactif, la CLI demande de
choisir `minimal`, `crud`, `append-only` ou `state-machine`. Ce dernier demande
ensuite le chemin de sa spec. Le profil `crud` initialise les ports inbound, use
cases, erreurs, composition et tests du cycle `create/get/list/update/delete`,
sans créer d'adapter.

Pour des faits immuables, le profil `append-only` crée un `ImmutableRecord` (pas
une `Entity` CRUD), son use case `append`, les contrats typés, une composition par
injection explicite du store et des tests :

```bash
arclith-cli add-entity Measurement --profile append-only
# Ou dans un nouveau service :
arclith-cli new Measurement measurement-service --profile append-only
```

Un record déjà déclaré peut recevoir une feature avec `add-blueprint append-only
--entity Measurement --feature measurement_ingestion`. Le store mémoire est une
référence locale non durable. Aucun transport ni query n'est généré. Consulter le
[contrat append-only](https://karned-rekipe.github.io/arclith/blueprints/append-only/)
pour l'immutabilité, l'idempotence, les timestamps et les limites.

Pour un cycle de vie métier, `state-machine` résout une spec YAML canonique et
génère un enum d'état, un service de domaine, un port/use case par verbe, un port
outbound `compare_and_swap` et une matrice complète :

```bash
arclith-cli add-entity Invoice --profile state-machine \
  --spec invoice-lifecycle.yaml
# Ou pour une entité existante dont le champ status est déjà typé et frozen :
arclith-cli add-blueprint state-machine --entity Invoice \
  --feature invoice_lifecycle --spec invoice-lifecycle.yaml
```

Le modèle généré refuse l'affectation et les mises à jour `model_copy` génériques
du champ d'état. Le manifeste V2 et la recette embarquent les paramètres résolus,
pas le chemin local de la spec. Aucun adapter ou transport n'est ajouté. Consulter le
[contrat state-machine](https://karned-rekipe.github.io/arclith/blueprints/state-machine/)
pour les gardes, le CAS et l'évolution des états persistés.

---

### `blueprints` et `add-blueprint` — Initialiser un comportement applicatif

Le catalogue des blueprints est distinct du catalogue des capabilities et des
adapters :

```bash
arclith-cli blueprints
arclith-cli blueprints --json
arclith-cli add-blueprint crud --entity ShoppingItem --dry-run
arclith-cli add-blueprint crud --entity ShoppingItem
arclith-cli add-blueprint state-machine --entity Invoice \
  --feature invoice_lifecycle --spec invoice-lifecycle.yaml
```

La première application écrit `.arclith/features/shopping_item.yaml`. Un replay
préserve les fichiers applicatifs déjà personnalisés et complète uniquement les
fichiers manquants. CRUD, append-only, state-machine, job, synchronization et workflow sont des comportements
explicites ; aucun n'est inféré depuis un adapter. Voir le
[contrat détaillé](https://karned-rekipe.github.io/arclith/blueprints/).

Pour un job suivi, la feature peut être transverse ou liée à une entité :

```yaml
# report-job.yaml
version: 1
request: GenerateReportRequest
result: GenerateReportResult
cancellable: true
max_attempts: 1
retention_days: 7
```

```bash
arclith-cli add-blueprint job --feature report_generation \
  --no-entity --spec report-job.yaml --dry-run
arclith-cli add-blueprint job --feature report_generation \
  --no-entity --spec report-job.yaml
# Variante, avec Document déjà créé :
arclith-cli add-blueprint job --feature document_analysis \
  --entity Document --spec report-job.yaml
```

`--entity` et `--no-entity` s'excluent ; `job` n'est pas un profil `add-entity`.
Le manifeste V3 déclare la cible et les paramètres, avec replay sans fichier
spec d'origine. Les cinq opérations utilisent les ports JobRunnerPort et
JobStorePort ; aucun broker ou transport n'est installé. Le handler métier
initial lève NotImplementedError et les tests injectent un fake explicite.
Le runner mémoire est **non durable**, avec exécution contrôlée par
`await runner.run(job_id)`, annulation coopérative et retry explicite borné.

Cette fonctionnalité est disponible avec Arclith ≥ 0.32.0 et CLI ≥ 0.29.0. Le
[guide job](https://karned-rekipe.github.io/arclith/blueprints/job/) détaille
l'installation depuis PyPI, le smoke test, la rétention et les futurs adapters.

---

Pour une réconciliation pull, appliquer `synchronization` à une entité existante :

```yaml
# customer-sync.yaml
version: 1
direction: pull
modes: [full, incremental]
external_key: external_id
page_size: 100
conflict_policy: source_wins
missing_policy: deactivate
execution: job
```

```bash
arclith-cli add-blueprint synchronization --entity Customer \
  --feature customer_sync --spec customer-sync.yaml --dry-run
arclith-cli add-blueprint synchronization --entity Customer \
  --feature customer_sync --spec customer-sync.yaml
```

Les quatre opérations `start_sync`, `get_sync_status`, `cancel_sync` et
`get_sync_report` réutilisent le contrat Job. Le mapper reste à compléter,
les tests utilisent des fakes explicites, et aucun adapter/transport n'est
installé. Le checkpoint incrémental n'avance qu'après une page entièrement
appliquée ; le full recommence du début après échec, avec clés vues bornées
et désactivation atomique après réussite de toutes les pages. Le manifeste V2
et la recette V1 conservent les paramètres canoniques et les digests.

Cette capacité est disponible avec Arclith ≥ 0.32.0 et CLI ≥ 0.29.0 ; suivre le
[guide synchronization](https://karned-rekipe.github.io/arclith/blueprints/synchronization/).
Le CLI refuse explicitement une génération/reprise sur un framework incompatible.

### `expose-feature` — Projeter Un Blueprint Applicatif

Consomme le manifeste `.arclith/features/<feature>.yaml` créé par un blueprint
et projette ses opérations vers un adapter déjà installé. La première version
supporte le blueprint `crud` vers FastAPI :

```bash
arclith-cli add-entity Todo --profile crud
arclith-cli add-adapter --capability api --adapter fastapi --yes
arclith-cli expose-feature todo --via fastapi --path /v1/todos --dry-run
arclith-cli expose-feature todo --via fastapi --path /v1/todos
```

Sans `--path`, la collection utilise `/v1/<feature-en-kebab-case>` :
`shopping_item` devient `/v1/shopping-item`, sans pluralisation automatique. La
commande planifie ensemble les routes `POST`, `GET` collection,
`GET` item, `PATCH` et `DELETE`, leurs DTO et leur composition partagée, puis
n'écrit qu'après validation complète du lot. Les
erreurs applicatives `NotFound` et `VersionConflict` deviennent `404` et `409`.
Elle ne crée ni adapter ni repository. Les fichiers développeur sont préservés
à la relance et la recette n'enregistre que la première mutation effective.

Utiliser `expose-usecase` pour une opération isolée ou un comportement qui ne
provient pas d'un blueprint.

---

### `add-usecase` — Ajouter un cas d'usage

Crée un port inbound guidé dans `src/<package>/domain/ports/inbound/`, puis le
cas d'usage dans `src/<package>/application/use_cases/`. Sans option de liaison,
la commande interactive propose les entités détectées par analyse AST, la
création d'une nouvelle entité ou un cas d'usage transverse.

```bash
cd my-recipe-service

# Mode interactif : choisir une entité détectée, en créer une ou rester transverse
arclith-cli add-usecase PlanShoppingList

# Modes directs, complets pour les agents et la CI
arclith-cli add-usecase CreateTodo --entity Todo
arclith-cli add-usecase CreateRecipe --new-entity Recipe
arclith-cli add-usecase RunMaintenance --no-entity
```

| Option | Effet |
|---|---|
| `--entity Todo` | lie le use case à une entité détectée et échoue si elle est absente |
| `--new-entity Todo` | crée l'entité si nécessaire, puis génère le use case lié |
| `--no-entity` | génère un `Command`, un `Result` et un use case transverse sans repository |

Ces options sont mutuellement exclusives. `--new-entity` réutilise une entité
valide déjà présente, mais refuse un fichier homonyme qui ne déclare pas la
classe `Entity` attendue.

Fichier généré :

```text
src/<package>/domain/ports/inbound/plan_shopping_list.py
src/<package>/application/use_cases/plan_shopping_list.py
```

Le nom peut être fourni en PascalCase, snake_case ou kebab-case. Le suffixe
`UseCase` est normalisé : `PlanShoppingListUseCase` et
`plan-shopping-list-use-case` génèrent tous les deux
`PlanShoppingListUseCase`.

Pour une entité principale, le squelette injecte explicitement
`Repository[Entity]` et type `execute` avec un `Command` Pydantic et l'entité en
retour. Le mode transverse génère plutôt un `Command` et un `Result` Pydantic,
sans repository implicite. Aucun mode ne câble FastAPI, FastMCP ou LangGraph.
Les exemples complets et les règles de séparation sont dans le
[deep dive du scaffold CLI](https://karned-rekipe.github.io/arclith/deep-dives/cli-scaffold/).

---

### `add-intent-interpreter` — Ajouter un interpréteur d'intention

Crée uniquement le fichier minimal d'un interpréteur d'intention dans
`src/<package>/application/intent_interpreters/`.

```bash
cd my-recipe-service
arclith-cli add-intent-interpreter IngredientIntent
arclith-cli add-intent-interpreter command-router
```

Fichier généré :

```text
src/<package>/application/intent_interpreters/ingredient_intent.py
```

L'interpréteur d'intention est le composant applicatif qui transforme une demande naturelle en
commande ou DTO structuré. Il ne remplace pas LangGraph : LangGraph orchestre les nœuds, tandis que
l'interpréteur porte la traduction d'intention. Le fichier généré reste volontairement vide de
logique métier.

---

### `add-adapter` — Ajouter un adapter

Wizard interactif à lancer **depuis la racine du projet cible**. Sans option, il affiche toutes les
capabilities et leurs adapters, notamment `api/fastapi` et `mcp/fastmcp`, puis demande le choix.
Il scaffold uniquement le code, la configuration et l'extra de dépendance du choix effectué.

```bash
cd my-recipe-service
arclith-cli add-adapter
```

Mode direct, utile pour CI, scripts de migration ou commandes reproductibles :

```bash
arclith-cli add-adapter --adapter mongodb --db-name my_recipe_service --param collection_name=recipes --yes
arclith-cli add-adapter --adapter duckdb --path data/ --no-activate --yes
arclith-cli add-adapter --adapter mariadb --param database=my_recipe_service --param user=app --yes
arclith-cli add-adapter --capability api --adapter fastapi --param port=8080 --yes
arclith-cli add-adapter --capability mcp --adapter fastmcp --param port=8081 --yes
arclith-cli add-adapter --capability llm --adapter lmstudio --param model_name=qwen/qwen3.5-9b --yes
arclith-cli add-adapter --capability agent --adapter langgraph --param graph_name=recipe_agent --param stream_mode=updates,custom --yes
arclith-cli add-adapter --capability observability --adapter langsmith
arclith-cli add-adapter --capability observability --adapter opentelemetry --param service_name=my_recipe_service --yes
arclith-cli add-adapter --capability runtime --adapter docker-image --yes
arclith-cli add-adapter --capability cache --adapter memory --yes
arclith-cli add-adapter --capability cache --adapter redis --param redis_url=redis://redis:6379 --yes
arclith-cli add-adapter --capability repository --adapter memory --yes
```

**Étapes du wizard :**

1. **Capability** — toutes les capabilities du catalogue sont proposées avec leurs adapters
2. **Type d'adapter** — selon la capability : `memory` · `mongodb` · `duckdb` · `mariadb` · `fastapi` · `fastmcp` · `rabbitmq` · `docker-image` · `lmstudio` · `openai` · `anthropic` · `langgraph` · `langsmith` · `opentelemetry`
3. **Entité(s) cible(s)** — uniquement pour une extension explicitement déclarée entity-scoped ; les repositories génériques et les transports ne demandent pas d'entité
4. **Paramètres** — questions spécifiques à l'adapter :
   - `mongodb` → `db_name`, `collection_name`, `multitenant`
   - `duckdb` → `path`
   - `mariadb` → `host`, `port`, `database`, `user`, `driver`, `table_prefix`
     (`url` et `password` sont mappés via `config/secrets.yaml`)
   - `cache/memory` → `jwks_ttl`, `tenant_uri_ttl`
   - `cache/redis` → `redis_url`, `jwks_ttl`, `tenant_uri_ttl`
   - `fastapi` → `host`, `port`, `reload`
   - `fastmcp` → `host`, `port`
   - `lmstudio` → `model_name`, `base_url`, `api_key`
   - `openai` → `model_name`, `base_url`, `OPENAI_API_KEY`
   - `anthropic` → `model_name`, `ANTHROPIC_API_KEY`
   - `langgraph` → `graph_name`, `stream_mode`
   - `langsmith` → `tracing`, `project`, `endpoint`, `LANGSMITH_API_KEY`
   - `opentelemetry` → `service_name`, `endpoint`, `traces_endpoint`, `metrics_endpoint`, `protocol`, `traces`, `metrics`, `instrument_fastapi`
   - `command-bus/rabbitmq` → `url`, `exchange`, `exchange_type`, `queue`, `routing_key`, `prefetch`, `consumer_name`, `concurrency`, `publisher_confirms`, `durable`, `retry_enabled`, `retry_requeue`, `dead_letter_exchange`, `dead_letter_routing_key`
   - `runtime/docker-image` → `uv_version`, `api_port`, `mcp_port`, `probe_port`, `agent_port`
   - `repository/memory` → aucun paramètre
5. **Activation** — met à jour `config/adapters/adapters.yaml` pour les capacités activables (`repository: <adapter>` ou `observability.enabled: [<adapter>, ...]`) ; `api/fastapi`, `mcp/fastmcp`, `cache/*`, `llm/*`, `agent/langgraph`, `command-bus/rabbitmq` et `runtime/docker-image` sont exposés par leurs fichiers dédiés
6. **Récapitulatif** — liste des fichiers créés ou remplacés avant confirmation

| Option | Défaut | Description |
|--------|--------|-------------|
| `--capability` | interactif | Capacité cible du catalogue standardisé (`repository`, `cache`, `api`, `mcp`, `http`, `command-bus`, `runtime`, `llm`, `agent`, `observability`) |
| `--adapter` / `-a` | interactif | Adapter du catalogue : `memory`, `mongodb`, `duckdb`, `mariadb`, `fastapi`, `fastmcp`, `idempotency`, `etag`, `cache-control`, `rabbitmq`, `docker-image`, `lmstudio`, `openai`, `anthropic`, `langgraph`, `langsmith`, `opentelemetry` |
| `--activate/--no-activate` | `--activate` | Met à jour `config/adapters/adapters.yaml` quand la capacité expose une clé d'activation |
| `--db-name` | nom du projet | Nom de base pour MongoDB |
| `--multitenant/--single-tenant` | `--single-tenant` | Mode MongoDB multitenant |
| `--path` | `data/` | Chemin DuckDB |
| `--param` | - | Paramètre adapter `key=value`, répétable pour les adapters du catalogue |
| `--yes` / `-y` | `false` | Skip la confirmation et utilise les valeurs fournies ou par défaut |

**Contrat d'un repository intégré :**

```
config/adapters/outbound/<adapter>.yaml          # config scopée si l'adapter en a besoin
src/<package>/adapters/outbound/<adapter>/__init__.py
src/<package>/adapters/outbound/<adapter>/README.md
src/<package>/adapters/outbound/<adapter>/repositories/        # extensions custom uniquement
src/<package>/infrastructure/use_cases_generated.py            # composition des use cases exposés
```

Les implémentations CRUD sont fournies par Arclith et sélectionnées par
`arclith.repository(Entity)`. Aucun repository par entité, container ou adapter
`memory` de secours n'est généré. Le README de chaque rôle définit les seuls
emplacements autorisés pour une extension provider spécifique.

**Runtime Docker :**

```bash
arclith-cli add-adapter --capability runtime --adapter docker-image --yes
uv lock
docker build -t my-recipe-service:local .
docker run --rm -p 8000:8000 -p 9000:9000 my-recipe-service:local api
```

L'adapter `runtime/docker-image` génère `Dockerfile`, `.dockerignore` et `arclith-run`. Une seule
image peut démarrer `api`, `mcp_http`, `mcp_sse`, `bus`, `agent` ou `all` par argument ou via
`ARCLITH_RUNTIME_MODE`. Les secrets restent hors build; `.env`, `secrets.yaml` et les clés privées
sont exclus du contexte Docker.

**LangGraph / LangSmith :**

```bash
uv add "arclith[langgraph]"
arclith-cli add-adapter --capability llm --adapter lmstudio --param model_name=qwen/qwen3.5-9b --yes
arclith-cli add-adapter --capability agent --adapter langgraph
arclith-cli add-adapter --capability observability --adapter langsmith
uv run langgraph dev --no-browser --allow-blocking --port 2024
```

L'adapter `llm/lmstudio` génère `config/adapters/outbound/lm.yaml`, chargé dans
`AppConfig.adapters.lm`. Adapter `model_name` au modèle chargé dans LM Studio et utiliser
`host.docker.internal` comme `base_url` si le projet tourne dans Docker alors que LM Studio tourne
sur l'hôte. Les adapters `llm/openai` et `llm/anthropic` génèrent aussi un mapping
`config/secrets.yaml` vers `OPENAI_API_KEY` ou `ANTHROPIC_API_KEY`; la clé réelle reste dans `.env`
local gitignoré, l'environnement runtime ou Vault.
Utiliser `llm/anthropic` pour Claude via le provider Anthropic; utiliser `llm/openai` pour OpenAI,
LM Studio ou tout endpoint OpenAI-compatible avec `base_url`.

L'adapter `repository/mongodb` génère `config/adapters/outbound/mongodb.yaml` avec `uri: null`, puis
mappe `adapters.mongodb.uri` vers `MONGODB_URI` dans `config/secrets.yaml`. L'URI réelle reste dans
l'environnement, un fichier local de secrets ou Vault selon le resolver choisi.
Il ne génère pas de repository `memory` applicatif. L'implémentation mémoire du framework peut être
utilisée directement dans des tests ; une spécialisation mémoire du projet n'est créée que par un
choix explicite de `repository/memory`.

L'adapter `agent/langgraph` génère `langgraph.json`, `config/adapters/inbound/langgraph.yaml` et
`src/<package>/adapters/inbound/langgraph/agent.py`. Le projet ne modifie ensuite que ce fichier pour
son agent. Comme `fastapi` et `fastmcp`, LangGraph est configuré par son nom produit dans
`AppConfig.langgraph`, sans `adapters.agent`. `stream_mode` vaut `updates` par défaut et accepte une
liste CSV comme `updates,custom` pour exposer les sorties de nodes et les événements
`get_stream_writer()`. L'adapter `observability/langsmith` génère
`config/adapters/outbound/langsmith.yaml`, l'ajoute à `observability.enabled`, met
à jour `.env` et ajoute `.env` au `.gitignore` si besoin. LangSmith Studio devient l'endroit standard
pour tester les agents. Une `LANGSMITH_API_KEY` déjà présente est conservée si aucune nouvelle valeur
n'est fournie.

**OpenTelemetry :**

```bash
uv add "arclith[opentelemetry]"
arclith-cli add-adapter --capability observability --adapter opentelemetry --param service_name=my-recipe-service --yes
```

L'adapter `observability/opentelemetry` génère `config/adapters/outbound/opentelemetry.yaml`, met à
jour `.env`, l'ajoute à `observability.enabled` et branche l'instrumentation FastAPI quand
`Arclith.fastapi()` construit l'application. Il peut être activé en même temps que LangSmith.
Le fichier `opentelemetry.yaml` ne porte pas de flag `enabled`: l'activation se fait uniquement dans
`observability.enabled`.
L'endpoint global est utilisé par défaut; `traces_endpoint` et `metrics_endpoint` peuvent cibler des
routes OTLP distinctes. Pour taguer l'environnement, définir
`OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=local` dans l'environnement runtime.

Parcours complet avec entité, API, LangGraph, LangSmith et LM Studio:
[`docs/agent-quickstart.md`](../docs/agent-quickstart.md).

---

### `capabilities` — Lister le catalogue standardisé

Affiche les capacités et adapters connus par la CLI.

```bash
arclith-cli capabilities
arclith-cli capabilities --json
```

Le catalogue est la source de vérité pour les adapters supportés, leurs paramètres, leur chemin de configuration et la clé d'activation.

---

### `export-config` — Générer `config.yaml` pour K8s

Fusionne le dossier `config/` en un fichier YAML unique, à lancer **depuis la racine du projet**.

```bash
arclith-cli export-config                        # → ./config.yaml
arclith-cli export-config --output dist/app.yaml # chemin personnalisé
```

Le fichier généré peut être monté directement comme **ConfigMap** Kubernetes.
Arclith le lit au même titre que le dossier `config/` :

```python
# dev
arclith = Arclith("config/")

# K8s (ConfigMap monté sur /app/config.yaml)
arclith = Arclith("config.yaml")
```

> ⚠️ `config.yaml` est un **artefact généré** — l'ajouter à `.gitignore`.
> La source de vérité reste `config/`.

---

### `history` et `replay` — Relire et rejouer les décisions CLI

`init`, `new`, `add-entity`, `add-blueprint`, `add-usecase`,
`add-intent-interpreter`, `add-adapter`, `expose-usecase` et `expose-feature`
ajoutent une étape à
`arclith.recipe.yaml` uniquement après leur
succès complet. La recette est un historique fonctionnel rejouable ; Git reste
l'historique du code et `export-config` reste la configuration consolidée de
déploiement.

```bash
arclith-cli history
arclith-cli replay arclith.recipe.yaml --dir ../rebuilt-service --dry-run
arclith-cli replay arclith.recipe.yaml --dir ../rebuilt-service
```

Sélectionner une plage avec `--from-step 0003` et `--to-step 0008`. Utiliser
`--strict` pour refuser une commande non supportée.

Les paramètres secrets sont remplacés par `<redacted>` et référencent une
variable d'environnement. Le dry-run liste les variables requises sans lire
leur valeur ; le replay réel exige qu'elles soient définies. Les chemins de
fichiers générés restent relatifs à la racine du projet et les étapes rejouées
ne sont pas enregistrées une seconde fois.

Voir la documentation complète :
[Recettes Arclith CLI](https://karned-rekipe.github.io/arclith/cli-recipe/).

---

### `update` — Mettre à jour le CLI

```bash
arclith-cli update
```

### `version` — Afficher la version

```bash
arclith-cli version
```

---

Pour un workflow séquentiel, fournir une spec et choisir une cible explicite :

```yaml
version: 1
context: PublicationContext
result: PublicationResult
steps:
  - name: validate
    max_attempts: 1
  - name: publish
    max_attempts: 2
```

```bash
arclith-cli add-blueprint workflow --feature publication \
  --no-entity --spec publication-workflow.yaml --dry-run
arclith-cli add-blueprint workflow --feature publication \
  --no-entity --spec publication-workflow.yaml
```

`--entity Document` permet aussi une feature liée à une entité. Workflow utilise
le manifeste V3 et génère `start`, `get_status`, `cancel`, `resume`, `get_result`,
les étapes et une projection de résultat à implémenter. Aucun transport, moteur
ou store durable n'est installé. Les tests injectent des fakes explicites.

Une reprise conserve les étapes confirmées, utilise une clé d'exécution stable
pour les effets non confirmés et respecte le budget par étape. La définition et
les schémas sont versionnés. Le [guide workflow](https://karned-rekipe.github.io/arclith/blueprints/workflow/)
fournit la spec, la composition, les limites et un exemple exécutable.
Ce blueprint est disponible avec Arclith ≥ 0.32.0 et CLI ≥ 0.29.0.

## Configuration

Les projets arclith utilisent un dossier `config/` à la place d'un `config.yaml` monolithique. Chaque fichier est **scopé** : son chemin détermine la section `AppConfig` dans laquelle son contenu est injecté.

```
config/
  app.yaml                        # app: { name, version, description }
  soft_delete.yaml                # soft_delete: { retention_days }
  secrets.yaml                    # secrets: { resolver, mappings, vault, yaml }
  adapters/
    adapters.yaml                 # adapters: { logger, repository, observability.enabled }
    outbound/
      mongodb.yaml                # adapters.mongodb: { db_name, multitenant }
      duckdb.yaml                 # adapters.duckdb: { path, multitenant }
      mariadb.yaml                # adapters.mariadb: { host, port, database, user, ... }
      lm.yaml                     # adapters.lm: { provider, model_name, api_key, base_url }
      langsmith.yaml              # adapters.langsmith: { tracing, project, endpoint, ... }
      opentelemetry.yaml          # adapters.opentelemetry: { endpoint, protocol, traces, metrics, ... }
    inbound/
      fastapi.yaml                # api: { host, port, reload }
      fastmcp.yaml                # mcp: { host, port }
      probe.yaml                  # probe: { host, port, enabled }
      keycloak.yaml               # keycloak: { url, realm }
      tenant.yaml                 # tenant: { vault_addr, … }
      license.yaml                # license: { role }
      cache.yaml                  # cache: { backend, redis_url, … }
```

`cache/memory` génère `config/adapters/inbound/cache.yaml` avec `backend: memory` et les TTL JWKS /
tenant. Ce cache est strictement local au processus Python: il suffit pour le développement, les
tests et un worker unique. Passer à Redis dès qu'il faut partager le cache entre plusieurs workers,
réplicas, ou processus séparés API/MCP/agent.

`cache/redis` génère le même fichier avec `backend: redis`, mappe `cache.redis_url` vers
`REDIS_URL` dans `config/secrets.yaml` et écrit la valeur fournie dans `.env` local gitignoré.
Installer l'extra avant de lancer le service:

```bash
uv add "arclith[cache]"
```

Pour changer l'adapter actif sans passer par le wizard :

```yaml
# config/adapters/adapters.yaml
repository: duckdb   # memory | mongodb | duckdb | mariadb
observability:
  enabled:
    - langsmith
    - opentelemetry
```

Pour MariaDB, ne committez pas le mot de passe ni l'URL complète si elle contient des identifiants.
La CLI mappe `adapters.mariadb.password` vers `MARIADB_PASSWORD` et `adapters.mariadb.url` vers
`MARIADB_URL` dans `config/secrets.yaml`; remplacer le resolver `env` par Vault selon l'environnement.
