diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d09cf39..482ccbac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,8 +46,10 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - New `init` options: `--level`, `--database`, `--feature AXIS=VALUE`, `--extra-package`, `--template`, `--in-place`, and `--name` for `--project-name`. `--database` matches its choices in any case. - Author and email default to `git config user.name` / `user.email`, and the package manager to uv when it is installed, otherwise pip. An empty author is left out of `pyproject.toml` for every package manager (Poetry also leaves out an email without a name). - `--save-config` works for every `init` run except `--dry-run` and records the level or template; `project_name` is the only required config key, a config can name a `level` or a `template`, and `--project-name`, `--author`, `--author-email` and `--description` override the file's values. +- A config file may set `version` (a PEP 440 version such as `1.2.0`, quoted in YAML) to give the generated project that version instead of `0.1.0`; an invalid value is reported and nothing is written. - A prompt that gets 10 invalid answers, or whose input ends, exits with status 1. `startdemo -y` also skips the creation prompt, and `runserver` rejects an invalid `app_module` in `[tool.fastapi-fastkit]`. - `init --template` and `startdemo` check the template name before they ask anything, suggest close matches and point to `fastkit list-templates`; the internal template path is shown only with `--debug`. +- After `init` or `startdemo` creates a project, fastkit prints a "Next steps" panel with the commands that apply to that run (project folder, environment, reviewing `.env`, database, server, tests, `addroute`, the next level), and puts the same list in the project's `README.md`. The old "To start your project" line is gone. - `runserver` in a project without `.venv` prints the commands that create it for the project's package manager (for PDM, ones that keep the `.venv` inside the project) before offering to continue. If you continue, it runs the uvicorn of the Python that runs fastkit and exits with a clear message if that Python has none. - `addroute` on a real single-file project such as `fastapi-hello` explains how to extend it by hand instead of adding packages. Projects that keep `main.py` at the root with their code in packages are handled as before. - `doctor` passed checks say only what was verified, with no severity, and checks that do not apply to a project (secrets, settings, `.gitattributes`) are skipped. JSON output is unchanged. @@ -69,9 +71,15 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - **Session-based:** logout invalidates the session, sessions have an absolute lifetime (`SESSION_ABSOLUTE_MAX_AGE`), and the demo account needs `ENABLE_DEMO_USERS=true` (refused outside development). **OAuth2** requires `OAUTH_REDIRECT_BASE_URL` outside development. - **Rate-Limiting** applies `RATE_LIMIT_DEFAULT` to every route and the stricter `RATE_LIMIT_AUTH` to the auth endpoints, using `limits` instead of slowapi. - **MongoDB** uses PyMongo's async client instead of Motor. The SQL session dependency no longer commits; services commit. -- The `layered`, `domain` and `production` levels (presets `classic-layered` and `domain-starter`) wire every selected feature into the template's `main.py`. +- The `single-file`, `layered`, `domain` and `production` levels (presets `single-module`, `classic-layered` and `domain-starter`) wire every selected feature into the template's `main.py`. +- **`single-file`** keeps its `src/main.py` when you add features. When a generated module reads the settings (database, authentication, tasks, cache, rate limiting, logging, telemetry), the settings move from `src/main.py` to `src/core/config.py` and the summary says so; with tooling-only selections `src/main.py` is unchanged. +- **Docker Compose with Alembic:** the generated compose file migrates the database in a one-shot step before the app (and worker) start, so `docker compose up --build` gives a working API with its tables. With SQLite and Docker Compose the database file is kept in a volume. +- **Selected features** each get a section in the project's `README.md` with the files and settings they add and a link to the FastAPI documentation. +- **Example `/items` with a database:** at the `layered`, `domain` and `production` levels with PostgreSQL, MySQL or SQLite, the example `/items` API stores its items in that database, and its tests run on in-memory SQLite; with MongoDB or Redis the items stay in their existing store and the README says so. `addroute` in such a project still adds an in-memory resource and prints a note that points to the database-backed items example. +- **Dependency versions:** a project generated from a feature selection keeps the minimum versions its template sets (for example `fastapi>=0.141.1`); a version you pin for the same package wins. Projects with PostgreSQL or MySQL list `aiosqlite` among the dev dependencies, because their tests run on in-memory SQLite, and MySQL projects install `aiomysql[rsa]`, which MySQL 8's default authentication needs. - Generated tests run against in-memory SQLite and do not export telemetry. - **Docker:** the image runs as a non-root user and has a healthcheck, `.dockerignore` is generated, compose points the app at its services, and `.env` is supplied at run time instead of copied into the image. **Loguru** is now configured at startup. +- **Docker Compose:** the containers always reach the compose database at its service name (a `DATABASE_URL` or `MONGODB_URL` in `.env` or the shell no longer redirects them), and the app, `migrate` and worker services share one image built once. - **Dev tools:** test and lint tools (pytest and its plugins, ruff, pre-commit) stay out of runtime dependencies. They go to the dev dependency group and to a new `requirements-dev.txt` that includes `requirements.txt`. Generated Dockerfiles install runtime dependencies only; the Makefile, GitHub Actions workflow and devcontainer install `requirements-dev.txt`. - **ruff:** projects created with the ruff option pass their own `ruff check`; generic classes use the Python 3.12 type parameter syntax. @@ -85,6 +93,7 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - `fastapi-llm-agent`: the SSE stream is declared in OpenAPI, the calculator tool and the conversation store are bounded (`MAX_CONVERSATIONS`, `MAX_MESSAGES_PER_CONVERSATION`), and there are hook points for authentication and rate limiting. - Templates that store items in a JSON file no longer reuse ids, write atomically, and their tests no longer overwrite the shipped data. - Unused dependencies and `setup.cfg` files are removed. Template Dockerfiles run as a non-root user and ship a `.dockerignore`. +- Generated code carries short comments that explain a FastAPI concept at its first use, each ending with a link to the matching FastAPI documentation page; a concept is explained once per project. - Every template ships a `requirements-dev.txt` for test and lint tools and keeps them out of `requirements.txt`, so the Docker images of `fastapi-sqlmodel`, `fastapi-auth-jwt` and `fastapi-llm-agent` no longer contain them. - Every template except `fastapi-hello` ships the ruff configuration that `init`'s ruff option writes. `fastapi-single-module` projects pass isort and `mypy src`, and `fastapi-custom-response` uses Python 3.12 generic syntax for its response envelope. @@ -104,7 +113,8 @@ Upgrading fastkit does not change an existing project. Run `fastkit doctor` in i 5. **Saved `--config` files** keep working: the CORS and Pagination options are accepted, and a `minimal` preset (or none) creates a `fastapi-single-module` project. 6. **Scripts that pipe answers into `fastkit init`** (or use `--interactive`) need options instead: `fastkit init --project-name api --level layered --database SQLite -y`, or `--config`. 7. **`startdemo` scripts** keep working. To switch, use `fastkit init --template --project-name `; `init` does not ask for author, email or description, so pass `--author`, `--author-email` and `--description`, or let git config fill author and email. -8. **The old stacks** added packages without code. The closest replacements are `--level single-file` for `minimal`, and a level with `--database` and `--feature migrations=Alembic` or `--feature async_tasks=Celery` for `standard` and `full`, which generate the code for those packages. +8. **`single-file` projects generated with features** now keep the template's `/health`, so in the OpenAPI schema its operation id is `health_health_get` and its summary is "Health" instead of `health_check_health_get` and "Health Check"; regenerate API clients that use operation ids. `tests/test_main.py` is the template's own. +9. **The old stacks** added packages without code. The closest replacements are `--level single-file` for `minimal`, and a level with `--database` and `--feature migrations=Alembic` or `--feature async_tasks=Celery` for `standard` and `full`, which generate the code for those packages. ## v1.5.2 (2026-12-01) diff --git a/docs/de/index.md b/docs/de/index.md index adb1773f..1e8da734 100644 --- a/docs/de/index.md +++ b/docs/de/index.md @@ -161,15 +161,25 @@ Installing dependencies... ╭─────────────────────── Success ───────────────────────╮ │ ✨ Dependencies installed successfully │ ╰───────────────────────────────────────────────────────╯ -╭─────────────────────── Success ───────────────────────╮ -│ ✨ FastAPI project 'my-awesome-project' has been │ -│ created successfully and saved to │ -│ ~your-project-path~! │ -╰───────────────────────────────────────────────────────╯ -╭──────────────────────── Info ────────────────────────╮ -│ ℹ To start your project, run 'fastkit runserver' at │ -│ newly created FastAPI project directory │ -╰──────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'my-awesome-project' from 'fastapi-hello' has been │ +│ created and saved to ~your-project-path~! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-project │ +│ 2. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 3. Run the tests. │ +│ uv run pytest │ +│ 4. Add a resource by imitation: copy the `Item` models, `create_item`, │ +│ `read_item` and their tests, and rename them for `/users`. │ +│ 5. Read `main.py` from top to bottom: each comment links the FastAPI │ +│ tutorial page that explains it. │ +│ 6. When you want more structure, create a project at the next level. │ +│ fastkit init --level single-file │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` @@ -442,6 +452,7 @@ Legen Sie sofort ein strukturiertes FastAPI-Demoprojekt an mit: ```console $ fastkit startdemo +Note: 'fastkit startdemo' is now 'fastkit init --template fastapi-default'. startdemo keeps working. Enter the project name: my-awesome-demo Enter the author name: John Doe Enter the author email: john@example.com @@ -490,6 +501,20 @@ FastAPI template project will deploy at '~your-project-path~' │ 'fastapi-default' has been created and saved to │ │ ~your-project-path~! │ ╰───────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-demo │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 4. Run the tests. │ +│ uv run pytest │ +│ 5. Add a resource with its route, schemas, data layer and tests. │ +│ fastkit addroute orders │ +│ 6. Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` │ +│ and `src/schemas/items.py`. │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/docs/en/contributing/development-setup.md b/docs/en/contributing/development-setup.md index 2880fa6d..122ce767 100644 --- a/docs/en/contributing/development-setup.md +++ b/docs/en/contributing/development-setup.md @@ -230,31 +230,30 @@ $ python scripts/inspect-templates.py --templates fastapi-sqlmodel --offline --n ### Generated code lives in Jinja2 fragments -Everything `fastkit init` writes into a project — `main.py`, -database and auth modules, Docker files, pytest configuration — is rendered -from templates under `src/fastapi_fastkit/fragments/`, not assembled from -strings in Python. `main.py.j2` hard-codes no feature: it iterates over the -`import_fragments`, `lifespan_fragments` and `setup_fragments` lists supplied -by `DynamicConfigGenerator` and includes each one, so features compose -freely. +Everything `fastkit init` writes into a project (database and auth modules, +Docker files, pytest configuration, the SQL-backed example `/items` in +`fragments/items_sql/` and `fragments/items_sql_classic/`) is rendered from templates under +`src/fastapi_fastkit/fragments/`, not assembled from strings in Python. No +`main.py` is generated: every level keeps its template's `main.py`, and +fastkit wires each selected feature into it at the `# fastkit:imports` / +`# fastkit:routes` anchors, so features compose freely. Adding a feature is roughly: -1. Drop the pieces into `main/imports/`, `main/lifespan/` and/or - `main/setup/` (lifespan fragments are indented by four spaces; the other - two are not). -2. Register them in `DynamicConfigGenerator._main_fragments()`, guarded by - the relevant config lookup. -3. For a standalone module, add `/.py.j2` and render it with - `self._render(...)`. +1. Add the option to `catalog/catalog.toml`. +2. For a standalone module, add `/.py.j2` and return it from + the generator, keyed by its project-relative path. +3. Add an `OverlayTarget` in `preset_layout.py` with the import and the + module-level lines that mount the feature in `main.py`. 4. Extend the combination matrix in `tests/test_backends/test_project_builder_config_generator.py` — it asserts every rendered Python file parses with `ast.parse`. Two constraints that are easy to trip over: every fragment must end with a trailing newline (the environment is built with `keep_trailing_newline=True`), -and `main.py.j2` must keep its `# fastkit:imports` / `# fastkit:routes` -anchors — `fastkit addroute` inserts at them. +and a template's `main.py` must keep its `# fastkit:imports` / +`# fastkit:routes` anchors, because `fastkit init` and `fastkit addroute` +insert at them. The authoritative procedure lives next to the fragments themselves, in [`src/fastapi_fastkit/fragments/README.md`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fragments/README.md). diff --git a/docs/en/index.md b/docs/en/index.md index 6f5102a3..7e244c29 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -106,14 +106,25 @@ Installing dependencies with UV... ---> 100% -╭─────────────────────── Success ───────────────────────╮ -│ ✨ FastAPI project 'hello_api' from 'fastapi-hello' │ -│ has been created and saved to /home/jane/work! │ -╰───────────────────────────────────────────────────────╯ -╭──────────────────────── Info ────────────────────────╮ -│ ℹ To start your project, run 'fastkit runserver' at │ -│ newly created FastAPI project directory │ -╰──────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'hello_api' from 'fastapi-hello' has been created and │ +│ saved to /home/jane/work! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd hello_api │ +│ 2. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 3. Run the tests. │ +│ uv run pytest │ +│ 4. Add a resource by imitation: copy the `Item` models, `create_item`, │ +│ `read_item` and their tests, and rename them for `/users`. │ +│ 5. Read `main.py` from top to bottom: each comment links the FastAPI │ +│ tutorial page that explains it. │ +│ 6. When you want more structure, create a project at the next level. │ +│ fastkit init --level single-file │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` @@ -214,6 +225,37 @@ Create the project in a new folder 'shop'? [Y/n]: └─────────────────┴────────────────────────────────────────────────────────────┘ Create the project? [Y/n]: +Creating virtual environment with UV... +Installing dependencies with UV... + +---> 100% + +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ Created .env from .env.example with a unique SECRET_KEY (git-ignored; │ +│ share .env.example instead) │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'shop' from 'fastapi-domain-starter' has been created │ +│ and saved to /home/jane/work! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd shop │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Start PostgreSQL and point the URL settings in .env at it. │ +│ 4. Create the database tables. │ +│ uv run alembic upgrade head │ +│ 5. Start the development server and open http://127.0.0.1:8000/docs. Or run │ +│ it in containers with Docker Compose: `docker compose up --build`. │ +│ fastkit runserver │ +│ 6. Run the tests. │ +│ uv run pytest │ +│ 7. Add a domain with its router, schemas, service, repository and tests. │ +│ fastkit addroute orders │ +│ 8. Read `src/app/main.py`, then `src/app/domains/items/`; README.md │ +│ describes each selected feature. │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` @@ -223,7 +265,7 @@ The same choices work as options (`--feature authentication=JWT --feature toolin The guided setup provides: - **Levels** that pick the base template and project layout (`single-file`, `layered`, `domain` and `production` map to `single-module`, `classic-layered` and `domain-starter` presets) -- **Auto-generated code** for selected features — varies by level (regenerated `main.py` for `single-file`; for `layered`, `domain` and `production` the template-shipped `main.py` is kept and every feature is wired into it) +- **Auto-generated code** for selected features — every level keeps the template-shipped `main.py` and wires each feature into it - **Level-aware Docker generation** — the generated `Dockerfile` `CMD` targets the actual entrypoint (`src.main:app` or `src.app.main:app`) - **Smart dependency management** with automatic pip compatibility - **Feature validation**: combinations that cannot be generated (FastAPI-Users without a SQL database) are rejected before anything is written @@ -345,11 +387,28 @@ Installing dependencies with UV... ---> 100% -╭─────────────────────── Success ───────────────────────╮ -│ ✨ FastAPI project 'my-awesome-demo' from │ -│ 'fastapi-default' has been created and saved to │ -│ /home/jane/work! │ -╰───────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ Created .env from .env.example with a unique SECRET_KEY (git-ignored; │ +│ share .env.example instead) │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'my-awesome-demo' from 'fastapi-default' has been │ +│ created and saved to /home/jane/work! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-demo │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 4. Run the tests. │ +│ uv run pytest │ +│ 5. Add a resource with its route, schemas, data layer and tests. │ +│ fastkit addroute orders │ +│ 6. Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` │ +│ and `src/schemas/items.py`. │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/docs/en/reference/preset-feature-matrix.md b/docs/en/reference/preset-feature-matrix.md index d21ed24c..3bc933df 100644 --- a/docs/en/reference/preset-feature-matrix.md +++ b/docs/en/reference/preset-feature-matrix.md @@ -16,7 +16,7 @@ land, and which feature combinations require manual wiring. | Level | Preset | Base template | Description | |---|---|---|---| -| `single-file` | `single-module` | `fastapi-single-module` | Single-file FastAPI app — `main.py` is regenerated. | +| `single-file` | `single-module` | `fastapi-single-module` | Single-file FastAPI app. Shipped `src/main.py` is preserved; its settings move to `src/core/config.py` when a generated feature needs them. | | `layered` | `classic-layered` | `fastapi-default` | Layered split (`api/routes`, `crud`, `schemas`, `core`). Shipped `main.py` is preserved. | | `domain` | `domain-starter` | `fastapi-domain-starter` | Domain-oriented (`src/app/domains//`). Shipped `main.py` is preserved. | | `production` | `domain-starter` | `fastapi-domain-starter` | The `domain` layout with PostgreSQL, Alembic, JWT, coverage, structured logs, ruff, GitHub Actions and Docker preselected. | @@ -29,7 +29,7 @@ of `single-module`, so saved configs that name it keep working. | Preset | `main.py` overlay | Settings module | Database module | Auth package | |---|---|---|---|---| -| `single-module` | regenerated at `src/main.py` | `src/core/config.py` (written by fastkit) | `src/config/database.py` | `src/auth/` | +| `single-module` | preserved (template-shipped) | `src/main.py`; moves to `src/core/config.py` once a generated module reads it | `src/core/database.py` | `src/auth/` | | `classic-layered` | preserved (template-shipped) | `src/core/config.py` | `src/core/database.py` | `src/auth/` | | `domain-starter` | preserved (template-shipped) | `src/app/core/config.py` | `src/app/core/database.py` | `src/app/domains/auth/` | @@ -39,17 +39,16 @@ module, which loads `.env`. ## Feature support per preset -Every feature is generated for every preset. `single-module` -regenerates `main.py` with everything wired. `classic-layered` and -`domain-starter` keep the template's `main.py` and fastkit splices each -feature into it through the `# fastkit:imports` / `# fastkit:routes` anchors: +Every feature is generated for every preset. Every preset keeps the +template's `main.py` and fastkit splices each feature into it through the +`# fastkit:imports` / `# fastkit:routes` anchors: routers are mounted under `settings.API_V1_PREFIX` (probes and `/ws` at the root), and middleware goes above the CORS block so CORS stays outermost. The summary line "Wired generated features into ..." lists what was added. | Feature | Generated | Wired into `main.py` | |---|---|---| -| **Database** (PostgreSQL, MySQL, SQLite, MongoDB) | Database module at the preset's path with a session / client dependency; the client is opened and closed with the app | Regenerated `main.py` closes it in its lifespan; a template `main.py` includes the module's `lifespan_router`. Your own routers use the dependency. With `classic-layered` / `domain-starter`, the template's example `/items` API keeps its own store; fastkit prints a note and adds it to `README.md` | +| **Database** (PostgreSQL, MySQL, SQLite, MongoDB) | Database module at the preset's path with a session / client dependency; the client is opened and closed with the app | The template `main.py` includes the module's `lifespan_router`. Your own routers use the dependency. With `classic-layered` or `domain-starter` and PostgreSQL, MySQL or SQLite, the example `/items` API stores its items in that database; with MongoDB or Redis it keeps its own JSON-file or in-memory store, and fastkit prints a note and adds it to `README.md` | | **Readiness** (with a database or Redis cache) | `features/readiness.py`: `GET /ready`, 200 or 503 within a 2-second timeout | Included at the root | | **Authentication** (JWT, FastAPI-Users, OAuth2, Session-based) | Auth package with routes and tests. Users (JWT, Session-based, FastAPI-Users) are stored in the selected SQL database or MongoDB, in memory otherwise; FastAPI-Users needs a SQL database | Auth routes under `/api/v1`; OAuth2 and Session-based also add the session middleware. A template router that already uses `/auth` or `/users` is reported as a conflict | | **Background tasks** (Celery, Dramatiq) | `worker.py` and `features/tasks.py` | Task router under `/api/v1/tasks` | @@ -57,28 +56,30 @@ summary line "Wired generated features into ..." lists what was added. | **Rate-Limiting** (utility) | `rate_limiting.py`, built on `limits`: `RATE_LIMIT_DEFAULT` for every route, `RATE_LIMIT_AUTH` for the auth endpoints | `setup_rate_limiting(app)` | | **WebSocket** (utility) | `features/websocket.py` | `/ws` at the root, `GET /api/v1/connections` | | **Pagination** (utility) | Nothing: list endpoints are always paginated. The menu no longer offers it; saved configs that list it still load | - | -| **CORS** (built in; no longer offered in the menu) | - | Regenerated `main.py`: `CORSMiddleware` only when `BACKEND_CORS_ORIGINS` lists origins; `*` turns credentials off. Template `main.py` files already contain the same block | +| **CORS** (built in; no longer offered in the menu) | - | Every template `main.py` already contains `CORSMiddleware`, enabled only when `BACKEND_CORS_ORIGINS` lists origins; `*` turns credentials off | | **Monitoring** | Loguru: `loguru_config.py` · OpenTelemetry: `telemetry.py` · Prometheus: none | `setup_loguru()` · `setup_telemetry(app)` · `Instrumentator().instrument(app).expose(app)` right after `app = FastAPI(...)` | | **Logging** (structured) | `logging_config.py` | `setup_logging(app)` (request-id middleware) | -| **Migrations** (Alembic) | `alembic.ini`, `alembic/env.py`, a baseline revision and `scripts/migrate.sh` for a SQL database | - | +| **Migrations** (Alembic) | `alembic.ini`, `alembic/env.py`, a baseline revision (with the `items` table for `classic-layered` and `domain-starter`) and `scripts/migrate.sh` for a SQL database | - | | **Testing** (Basic / Coverage / Advanced) | `pytest.ini`, a root `conftest.py` (in-memory SQLite, no telemetry export) and tests per feature; Advanced also adds `tests/factories.py` | - | | **Tooling** (ruff, pre-commit, github-actions, devcontainer, makefile) | The matching config files | - | -| **Deployment** (Docker, docker-compose) | `Dockerfile` (non-root user, healthcheck on `/health`, no `.env` in the image), `.dockerignore`, `docker-compose.yml` with service URLs and healthchecks | - | +| **Deployment** (Docker, docker-compose) | `Dockerfile` (non-root user, healthcheck on `/health`, no `.env` in the image), `.dockerignore`, `docker-compose.yml` with healthchecks and service URLs that take precedence over the URLs in `.env`; the app, `migrate` and worker share one image. With Alembic selected, a one-shot `migrate` service runs `alembic upgrade head` once the database is healthy, and the app (and worker) start only after it succeeded, so `docker compose up --build` gives a working API with its tables. With SQLite, the database file lives in the `sqlite_data` volume | - | | **`/health`** | Always present: `{"status": "ok"}` at the root | - | ## When you'll see a "Preset compatibility" warning -With `classic-layered` and `domain-starter`, fastkit warns only when it -cannot find the template's `main.py` (for example, after you moved it). The -warning lists every selection you then have to register yourself. -`single-module` never warns. +fastkit warns only when it cannot find the template's `main.py` (for example, +after you moved it). The warning lists every selection you then have to +register yourself. ## What fastkit never changes fastkit edits a template-shipped `main.py` only by adding import lines and single module-level statements at its anchors. It does not rewrite template code or the template's lifespan; features that need startup or shutdown work -bring it in their own router. The contract is: +bring it in their own router. The one exception is `single-module`: when a +generated module needs the settings, the settings block moves from +`src/main.py` to `src/core/config.py`, because the generated module would +otherwise import `src.main` circularly. The contract is: - Selected packages are always installed (so `pip freeze` matches the user's intent). diff --git a/docs/en/tutorial/getting-started.md b/docs/en/tutorial/getting-started.md index 48fe1aea..221a7f5c 100644 --- a/docs/en/tutorial/getting-started.md +++ b/docs/en/tutorial/getting-started.md @@ -123,7 +123,30 @@ Installing dependencies with UV... ---> 100% -✨ FastAPI project 'my-first-api' from 'fastapi-default' has been created. +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ Created .env from .env.example with a unique SECRET_KEY (git-ignored; │ +│ share .env.example instead) │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'my-first-api' from 'fastapi-default' has been │ +│ created and saved to /home/jane/work! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-first-api │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 4. Run the tests. │ +│ uv run pytest │ +│ 5. Add a resource with its route, schemas, data layer and tests. │ +│ fastkit addroute orders │ +│ 6. Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` │ +│ and `src/schemas/items.py`. │ +│ 7. When you want more structure, create a project at the next level. │ +│ fastkit init --level domain │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/docs/en/user-guide/adding-routes.md b/docs/en/user-guide/adding-routes.md index 6d503b51..9ca969e9 100644 --- a/docs/en/user-guide/adding-routes.md +++ b/docs/en/user-guide/adding-routes.md @@ -52,6 +52,13 @@ Files to modify (1): Both layouts generate the same CRUD resource with an in-memory repository and tests, and register the router automatically. +In a project with a SQL database the new resource still keeps its records +in memory, and `addroute` says so. The `items` example shows the SQL-backed +version: in a `layered` project `src/crud/items.py` with its model in +`src/models/items.py`, in a `domain` or `production` project the model, +repository, service and router of `domains/items/`. With Alembic, a revision +in `alembic/versions/` creates its table. + `classic-layer`: ```text diff --git a/docs/en/user-guide/choosing-a-starter.md b/docs/en/user-guide/choosing-a-starter.md index 2d2e4225..1b3c2427 100644 --- a/docs/en/user-guide/choosing-a-starter.md +++ b/docs/en/user-guide/choosing-a-starter.md @@ -89,7 +89,8 @@ No settings module and no secrets. ### `single-file` — script-style prototype (preset `single-module`) The whole application in one module, with settings and tests next to it. -`main.py` is regenerated from the features you select. +`src/main.py` is kept when you select features; the settings move to +`src/core/config.py` if a generated feature needs them. - 👤 **Who**: writing a glue script, a small webhook, or a one-day prototype that doesn't need package boundaries. @@ -103,7 +104,9 @@ The "Django-flavoured" layout — code is split horizontally by concern: all routers in `api/`, all CRUD logic in `crud/`, all pydantic schemas in `schemas/`, all configuration in `core/`. The shipped `main.py` is **preserved** (it already wires CORS for you); generated database/auth -configs land under `src/core/`. +configs land under `src/core/`. With PostgreSQL, MySQL or SQLite +(`--database`), the example `items` API stores its records in that database +(model in `src/models/items.py`); otherwise they stay in a JSON file. - 👤 **Who**: teams familiar with Django/Rails-style layouts, projects with many small endpoints sharing common CRUD plumbing. @@ -116,6 +119,8 @@ Code is split vertically by **business concept**: each domain owns its own router, service, repository, and schemas under `src/app/domains//`. Comes with a `/health` endpoint and an `items` example domain that you copy and rename for each new concept. +With PostgreSQL, MySQL or SQLite (`--database`), `items` stores its records +in that database; with MongoDB or Redis they stay in memory. The shipped `main.py` (under `src/app/`) is preserved; generated configs land under `src/app/core/`. @@ -129,6 +134,7 @@ land under `src/app/core/`. The `domain` layout with PostgreSQL, Alembic, JWT login, coverage, structured logs, ruff, GitHub Actions and Docker preselected. You can change any of them in the customise step, or pass another `--database`. +The example `items` API stores its records in the selected SQL database. - 👤 **Who**: people who want a deployable starting point and would rather remove what they do not need. @@ -145,7 +151,6 @@ A side-by-side at a glance. | Routers location | (inside `main.py`) | (inside `main.py`) | `src/api/routes/` | `src/app/domains//router.py` | | Per-domain folders | ❌ | ❌ | ❌ | ✅ | | Built-in `/health` endpoint | ❌ | ✅ | ✅ | ✅ | -| `main.py` regenerated from features | ❌ | ✅ | ❌ | ❌ | | CORS pre-wired in `main.py` | no | yes (env-driven) | yes (env-driven) | yes (env-driven) | | pyproject-first | ✅ | optional | optional | ✅ | | Best for | "one file to read" | "one-file prototype" | "split by concern" | "split by business concept" | diff --git a/docs/en/user-guide/cli-reference.md b/docs/en/user-guide/cli-reference.md index 945f5c77..e7064e8b 100644 --- a/docs/en/user-guide/cli-reference.md +++ b/docs/en/user-guide/cli-reference.md @@ -234,6 +234,7 @@ instead of being silently ignored. | `project_name` | string | Required | | `author`, `author_email` | string | Optional; default to `git config user.name` / `user.email`, and an empty value is left out of `pyproject.toml` | | `description` | string | Optional | +| `version` | string | Optional PEP 440 version (for example `1.2.0`), written to `[project].version` of the generated `pyproject.toml` (and Poetry's `[tool.poetry].version`); default `0.1.0`. Quote it in YAML (`version: "1.10"`). An invalid value is a config error and nothing is written | | `level` | `"hello"` \| `"single-file"` \| `"layered"` \| `"domain"` \| `"production"` | The level the project is created from; the keys below refine it. `hello` takes no feature keys | | `template` | a bundled template id | Copies the template as it is; takes no feature keys and cannot be combined with `level` | | `architecture_preset` (alias `preset`) | `"single-module"` \| `"classic-layered"` \| `"domain-starter"` | For configs written by fastkit 1.x; `"minimal"` is accepted and means `single-module`. The two spellings must agree if both are present, and a preset must agree with `level` | @@ -312,7 +313,9 @@ skips that confirmation and proceeds with the overwrite; it also creates the project without the "Create the project?" question. In a non-interactive environment (stdin is not a TTY, as in CI or a piped run), fastkit refuses to overwrite anything unless `--yes` is given: `init` exits with status 1 before writing any file. An existing `.env` is never overwritten (see -[Generated `.env` file](#generated-env-file)). +[Generated `.env` file](#generated-env-file)). An in-place `single-file` run +stops with an error when `src/core/config.py` already exists and does not +define `settings`. fastkit never writes through a symbolic link in the target directory. If a file it would write is a symlink, or one of its parent directories is a @@ -373,13 +376,12 @@ which is pre-selected as `Coverage`, and the choices a level bundles Every selection generates real code, not just installed packages — see the [architecture preset / feature matrix](../reference/preset-feature-matrix.md) -for how `single-file` (regenerated `main.py`) and -`layered` / `domain` / `production` (preserved `main.py`, manual-wiring -warnings) differ. +for where each level puts the generated files and when wiring warnings +appear. | Axis | Choices | Installed packages | Generated files | |---|---|---|---| -| `database` | PostgreSQL, MySQL, MongoDB, Redis, SQLite, None | PostgreSQL: `asyncpg`, `sqlalchemy[asyncio]` · MySQL: `aiomysql`, `sqlalchemy[asyncio]` · MongoDB: `pymongo>=4.13` (its async client) · Redis: `redis[hiredis]` · SQLite: `sqlalchemy[asyncio]`, `aiosqlite` | A database module at the preset's path (e.g. `src/config/database.py`) that opens and closes the client with the app; with a database or Redis cache, `GET /ready` | +| `database` | PostgreSQL, MySQL, MongoDB, Redis, SQLite, None | PostgreSQL: `asyncpg`, `sqlalchemy[asyncio]` · MySQL: `aiomysql[rsa]` (for MySQL 8's default authentication), `sqlalchemy[asyncio]` · MongoDB: `pymongo>=4.13` (its async client) · Redis: `redis[hiredis]` · SQLite: `sqlalchemy[asyncio]`, `aiosqlite` | A database module at the preset's path (e.g. `src/core/database.py`) that opens and closes the client with the app; with a database or Redis cache, `GET /ready` | | `authentication` | JWT, OAuth2, FastAPI-Users, Session-based, None | JWT: `pyjwt[crypto]`, `pwdlib[argon2]`, `email-validator`, `python-multipart` · OAuth2: `authlib`, `itsdangerous`, `httpx2` · FastAPI-Users: `fastapi-users[sqlalchemy]` · Session-based: `itsdangerous`, `pwdlib[argon2]`, `email-validator` | An auth package (`src/auth/`, or `src/app/domains/auth/` with `domain-starter`) with routes under `/api/v1` and tests. JWT: OAuth2 password flow (`POST /auth/register`, `POST /auth/token`, `GET /users/me`), users stored in the selected SQL database or MongoDB, in memory otherwise. FastAPI-Users: SQL databases only. Session-based: login, logout (204), demo account only with `ENABLE_DEMO_USERS=true`. OAuth2: needs `OAUTH_REDIRECT_BASE_URL` outside development | | `async_tasks` | Celery, Dramatiq, None | Celery: `celery[redis]`, `redis[hiredis]` · Dramatiq: `dramatiq[redis]`, `redis[hiredis]` | `/worker.py` (background worker) + `/features/tasks.py` (task routes) | | `testing` | Basic, Coverage, Advanced, None | Basic: `pytest`, `pytest-asyncio`, `httpx`, `httpx2` · Coverage: + `pytest-cov` · Advanced: + `faker`, `factory-boy` | `pytest.ini`, a root `conftest.py` that runs tests against in-memory SQLite without telemetry export, and tests for the selected features; Advanced also adds `tests/factories.py` and `tests/test_factories.py` | @@ -389,7 +391,7 @@ warnings) differ. | `migrations` | Alembic, None | Alembic: `alembic` | `alembic.ini`, `alembic/env.py`, `alembic/script.py.mako`, a baseline `alembic/versions/_initial.py`, `scripts/migrate.sh` — only when the database axis is a SQL database | | `tooling` (multi-select) | ruff, pre-commit, github-actions, devcontainer, makefile, None | ruff: `ruff` · pre-commit: `pre-commit` · github-actions / devcontainer / makefile: none | ruff merges a `[tool.ruff]` block into `pyproject.toml` (or writes `ruff.toml` for `pip` projects) that allows FastAPI's `Depends`, `Query`, ... defaults (B008); pre-commit writes `.pre-commit-config.yaml` without pinning a Python interpreter (without ruff, it also adds a missing `[tool.black]` table); github-actions writes `.github/workflows/test.yml`; devcontainer writes `.devcontainer/devcontainer.json`; makefile writes `Makefile` | | `logging` | structured, None | None (stdlib `logging` + `json` only) | `/logging_config.py` (structured JSON logging + request-id middleware), wired into `main.py` | -| `deployment` (multi-select) | Docker, docker-compose | none | `Dockerfile` (non-root user, healthcheck on `/health`, `ENVIRONMENT=production`, no `.env` in the image), `.dockerignore`; docker-compose adds `docker-compose.yml` with the database / cache services, healthchecks and service URLs, reading `.env` at run time | +| `deployment` (multi-select) | Docker, docker-compose | none | `Dockerfile` (non-root user, healthcheck on `/health`, `ENVIRONMENT=production`, no `.env` in the image), `.dockerignore`; docker-compose adds `docker-compose.yml` with the database / cache services, healthchecks and fixed service URLs (they take precedence over the URLs in `.env`, which is read at run time), one image shared by the app, `migrate` and worker services; with Alembic it also runs the migrations in a one-shot `migrate` service before the app starts, and with SQLite it keeps the database file in the `sqlite_data` volume | Test and lint tools (`pytest` and its plugins, `faker`, `factory-boy`, `ruff`, `pre-commit`) are development dependencies: they go to the dev dependency group and to `requirements-dev.txt` (which includes `requirements.txt`), not to the runtime dependencies. The generated `Dockerfile` installs `requirements.txt` only; the generated `Makefile`, GitHub Actions workflow and devcontainer install `requirements-dev.txt`. @@ -731,10 +733,32 @@ Enter the author name: Jane Smith Enter the author email: jane@example.com Enter the project description: Blog API with PostgreSQL -Select package manager (pip, uv, pdm, poetry) [uv]: poetry +Select package manager (pip, uv, pdm, poetry) [uv]: uv Do you want to proceed with project creation? [y/N]: y -✨ FastAPI project 'my-blog' from 'fastapi-sqlmodel' has been created! +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ Created .env from .env.example with a unique SECRET_KEY (git-ignored; │ +│ share .env.example instead) │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'my-blog' from 'fastapi-sqlmodel' has been created │ +│ and saved to /home/jane/work! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-blog │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Create the database tables. │ +│ uv run alembic upgrade head │ +│ 4. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 5. Run the tests. │ +│ uv run pytest │ +│ 6. Read `src/app/main.py`, then `src/app/domains/items/` and │ +│ `src/app/db/session.py`; the README explains how to switch to PostgreSQL │ +│ or MySQL. │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/docs/en/user-guide/creating-projects.md b/docs/en/user-guide/creating-projects.md index 7991eb78..0e337585 100644 --- a/docs/en/user-guide/creating-projects.md +++ b/docs/en/user-guide/creating-projects.md @@ -35,6 +35,8 @@ Select a level [1]: 3 Levels after `hello` then ask for a database ("None" is the default, except for `production`) and whether to customise features. Author name and email default to `git config user.name` / `user.email`; they are left out of `pyproject.toml` when empty. The package manager defaults to uv when it is installed, otherwise pip. +After the run, `init` prints a "Next steps" panel with the commands that apply to it, and the same list is in the project's `README.md`, between `` and `` (generating again into the same folder replaces only that block); a project created from a feature selection also gets a README section for each selected feature. The generated code carries short comments that link the FastAPI documentation page of each concept where it first appears. + Before anything is written, `init` prints a project summary and asks `Create the project?`. `--dry-run` prints the summary and the file list and writes nothing. ### 2. Levels diff --git a/docs/en/user-guide/quick-start.md b/docs/en/user-guide/quick-start.md index d3e81551..5981361c 100644 --- a/docs/en/user-guide/quick-start.md +++ b/docs/en/user-guide/quick-start.md @@ -62,7 +62,30 @@ Installing dependencies with UV... ---> 100% -✨ FastAPI project 'my-first-app' from 'fastapi-default' has been created. +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ Created .env from .env.example with a unique SECRET_KEY (git-ignored; │ +│ share .env.example instead) │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'my-first-app' from 'fastapi-default' has been │ +│ created and saved to /home/jane/work! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-first-app │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 4. Run the tests. │ +│ uv run pytest │ +│ 5. Add a resource with its route, schemas, data layer and tests. │ +│ fastkit addroute orders │ +│ 6. Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` │ +│ and `src/schemas/items.py`. │ +│ 7. When you want more structure, create a project at the next level. │ +│ fastkit init --level domain │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/docs/es/index.md b/docs/es/index.md index 691491fb..1c359e25 100644 --- a/docs/es/index.md +++ b/docs/es/index.md @@ -161,15 +161,25 @@ Installing dependencies... ╭─────────────────────── Success ───────────────────────╮ │ ✨ Dependencies installed successfully │ ╰───────────────────────────────────────────────────────╯ -╭─────────────────────── Success ───────────────────────╮ -│ ✨ FastAPI project 'my-awesome-project' has been │ -│ created successfully and saved to │ -│ ~your-project-path~! │ -╰───────────────────────────────────────────────────────╯ -╭──────────────────────── Info ────────────────────────╮ -│ ℹ To start your project, run 'fastkit runserver' at │ -│ newly created FastAPI project directory │ -╰──────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'my-awesome-project' from 'fastapi-hello' has been │ +│ created and saved to ~your-project-path~! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-project │ +│ 2. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 3. Run the tests. │ +│ uv run pytest │ +│ 4. Add a resource by imitation: copy the `Item` models, `create_item`, │ +│ `read_item` and their tests, and rename them for `/users`. │ +│ 5. Read `main.py` from top to bottom: each comment links the FastAPI │ +│ tutorial page that explains it. │ +│ 6. When you want more structure, create a project at the next level. │ +│ fastkit init --level single-file │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` @@ -454,6 +464,7 @@ Despliega de inmediato un proyecto de demo FastAPI estructurado con: ```console $ fastkit startdemo +Note: 'fastkit startdemo' is now 'fastkit init --template fastapi-default'. startdemo keeps working. Enter the project name: my-awesome-demo Enter the author name: John Doe Enter the author email: john@example.com @@ -502,6 +513,20 @@ FastAPI template project will deploy at '~your-project-path~' │ 'fastapi-default' has been created and saved to │ │ ~your-project-path~! │ ╰───────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-demo │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 4. Run the tests. │ +│ uv run pytest │ +│ 5. Add a resource with its route, schemas, data layer and tests. │ +│ fastkit addroute orders │ +│ 6. Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` │ +│ and `src/schemas/items.py`. │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/docs/fr/index.md b/docs/fr/index.md index 9b9116d6..38182f60 100644 --- a/docs/fr/index.md +++ b/docs/fr/index.md @@ -161,15 +161,25 @@ Installing dependencies... ╭─────────────────────── Success ───────────────────────╮ │ ✨ Dependencies installed successfully │ ╰───────────────────────────────────────────────────────╯ -╭─────────────────────── Success ───────────────────────╮ -│ ✨ FastAPI project 'my-awesome-project' has been │ -│ created successfully and saved to │ -│ ~your-project-path~! │ -╰───────────────────────────────────────────────────────╯ -╭──────────────────────── Info ────────────────────────╮ -│ ℹ To start your project, run 'fastkit runserver' at │ -│ newly created FastAPI project directory │ -╰──────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'my-awesome-project' from 'fastapi-hello' has been │ +│ created and saved to ~your-project-path~! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-project │ +│ 2. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 3. Run the tests. │ +│ uv run pytest │ +│ 4. Add a resource by imitation: copy the `Item` models, `create_item`, │ +│ `read_item` and their tests, and rename them for `/users`. │ +│ 5. Read `main.py` from top to bottom: each comment links the FastAPI │ +│ tutorial page that explains it. │ +│ 6. When you want more structure, create a project at the next level. │ +│ fastkit init --level single-file │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` @@ -442,6 +452,7 @@ Déployez immédiatement un projet de démonstration FastAPI structuré avec : ```console $ fastkit startdemo +Note: 'fastkit startdemo' is now 'fastkit init --template fastapi-default'. startdemo keeps working. Enter the project name: my-awesome-demo Enter the author name: John Doe Enter the author email: john@example.com @@ -490,6 +501,20 @@ FastAPI template project will deploy at '~your-project-path~' │ 'fastapi-default' has been created and saved to │ │ ~your-project-path~! │ ╰───────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-demo │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 4. Run the tests. │ +│ uv run pytest │ +│ 5. Add a resource with its route, schemas, data layer and tests. │ +│ fastkit addroute orders │ +│ 6. Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` │ +│ and `src/schemas/items.py`. │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/docs/ja/index.md b/docs/ja/index.md index d73ef88a..21d00852 100644 --- a/docs/ja/index.md +++ b/docs/ja/index.md @@ -161,15 +161,25 @@ Installing dependencies... ╭─────────────────────── Success ───────────────────────╮ │ ✨ Dependencies installed successfully │ ╰───────────────────────────────────────────────────────╯ -╭─────────────────────── Success ───────────────────────╮ -│ ✨ FastAPI project 'my-awesome-project' has been │ -│ created successfully and saved to │ -│ ~your-project-path~! │ -╰───────────────────────────────────────────────────────╯ -╭──────────────────────── Info ────────────────────────╮ -│ ℹ To start your project, run 'fastkit runserver' at │ -│ newly created FastAPI project directory │ -╰──────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'my-awesome-project' from 'fastapi-hello' has been │ +│ created and saved to ~your-project-path~! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-project │ +│ 2. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 3. Run the tests. │ +│ uv run pytest │ +│ 4. Add a resource by imitation: copy the `Item` models, `create_item`, │ +│ `read_item` and their tests, and rename them for `/users`. │ +│ 5. Read `main.py` from top to bottom: each comment links the FastAPI │ +│ tutorial page that explains it. │ +│ 6. When you want more structure, create a project at the next level. │ +│ fastkit init --level single-file │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` @@ -449,6 +459,7 @@ Do you want to add route 'user' to project 'my-awesome-project'? [Y/n]: y ```console $ fastkit startdemo +Note: 'fastkit startdemo' is now 'fastkit init --template fastapi-default'. startdemo keeps working. Enter the project name: my-awesome-demo Enter the author name: John Doe Enter the author email: john@example.com @@ -497,6 +508,20 @@ FastAPI template project will deploy at '~your-project-path~' │ 'fastapi-default' has been created and saved to │ │ ~your-project-path~! │ ╰───────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-demo │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 4. Run the tests. │ +│ uv run pytest │ +│ 5. Add a resource with its route, schemas, data layer and tests. │ +│ fastkit addroute orders │ +│ 6. Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` │ +│ and `src/schemas/items.py`. │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/docs/ko/index.md b/docs/ko/index.md index b3dc243c..7023310f 100644 --- a/docs/ko/index.md +++ b/docs/ko/index.md @@ -161,15 +161,25 @@ Installing dependencies... ╭─────────────────────── Success ───────────────────────╮ │ ✨ Dependencies installed successfully │ ╰───────────────────────────────────────────────────────╯ -╭─────────────────────── Success ───────────────────────╮ -│ ✨ FastAPI project 'my-awesome-project' has been │ -│ created successfully and saved to │ -│ ~your-project-path~! │ -╰───────────────────────────────────────────────────────╯ -╭──────────────────────── Info ────────────────────────╮ -│ ℹ To start your project, run 'fastkit runserver' at │ -│ newly created FastAPI project directory │ -╰──────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'my-awesome-project' from 'fastapi-hello' has been │ +│ created and saved to ~your-project-path~! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-project │ +│ 2. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 3. Run the tests. │ +│ uv run pytest │ +│ 4. Add a resource by imitation: copy the `Item` models, `create_item`, │ +│ `read_item` and their tests, and rename them for `/users`. │ +│ 5. Read `main.py` from top to bottom: each comment links the FastAPI │ +│ tutorial page that explains it. │ +│ 6. When you want more structure, create a project at the next level. │ +│ fastkit init --level single-file │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` @@ -415,6 +425,7 @@ Do you want to add route 'user' to project 'my-awesome-project'? [Y/n]: y ```console $ fastkit startdemo +Note: 'fastkit startdemo' is now 'fastkit init --template fastapi-default'. startdemo keeps working. Enter the project name: my-awesome-demo Enter the author name: John Doe Enter the author email: john@example.com @@ -463,6 +474,20 @@ FastAPI template project will deploy at '~your-project-path~' │ 'fastapi-default' has been created and saved to │ │ ~your-project-path~! │ ╰───────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-demo │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 4. Run the tests. │ +│ uv run pytest │ +│ 5. Add a resource with its route, schemas, data layer and tests. │ +│ fastkit addroute orders │ +│ 6. Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` │ +│ and `src/schemas/items.py`. │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/docs/zh/index.md b/docs/zh/index.md index 375a3f7b..ed485c16 100644 --- a/docs/zh/index.md +++ b/docs/zh/index.md @@ -161,15 +161,25 @@ Installing dependencies... ╭─────────────────────── Success ───────────────────────╮ │ ✨ Dependencies installed successfully │ ╰───────────────────────────────────────────────────────╯ -╭─────────────────────── Success ───────────────────────╮ -│ ✨ FastAPI project 'my-awesome-project' has been │ -│ created successfully and saved to │ -│ ~your-project-path~! │ -╰───────────────────────────────────────────────────────╯ -╭──────────────────────── Info ────────────────────────╮ -│ ℹ To start your project, run 'fastkit runserver' at │ -│ newly created FastAPI project directory │ -╰──────────────────────────────────────────────────────╯ +╭──────────────────────────────── Success ─────────────────────────────────╮ +│ ✨ FastAPI project 'my-awesome-project' from 'fastapi-hello' has been │ +│ created and saved to ~your-project-path~! │ +╰──────────────────────────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-project │ +│ 2. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 3. Run the tests. │ +│ uv run pytest │ +│ 4. Add a resource by imitation: copy the `Item` models, `create_item`, │ +│ `read_item` and their tests, and rename them for `/users`. │ +│ 5. Read `main.py` from top to bottom: each comment links the FastAPI │ +│ tutorial page that explains it. │ +│ 6. When you want more structure, create a project at the next level. │ +│ fastkit init --level single-file │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` @@ -442,6 +452,7 @@ Do you want to add route 'user' to project 'my-awesome-project'? [Y/n]: y ```console $ fastkit startdemo +Note: 'fastkit startdemo' is now 'fastkit init --template fastapi-default'. startdemo keeps working. Enter the project name: my-awesome-demo Enter the author name: John Doe Enter the author email: john@example.com @@ -490,6 +501,20 @@ FastAPI template project will deploy at '~your-project-path~' │ 'fastapi-default' has been created and saved to │ │ ~your-project-path~! │ ╰───────────────────────────────────────────────────────╯ +╭───────────────────────────────── Next steps ─────────────────────────────────╮ +│ 1. Go to the project folder. │ +│ cd my-awesome-demo │ +│ 2. Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY. │ +│ 3. Start the development server and open http://127.0.0.1:8000/docs. │ +│ fastkit runserver │ +│ 4. Run the tests. │ +│ uv run pytest │ +│ 5. Add a resource with its route, schemas, data layer and tests. │ +│ fastkit addroute orders │ +│ 6. Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` │ +│ and `src/schemas/items.py`. │ +│ README.md lists the steps for a fresh checkout of the project. │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/src/fastapi_fastkit/backend/interactive/__init__.py b/src/fastapi_fastkit/backend/interactive/__init__.py index c96da0d8..2e6bc692 100644 --- a/src/fastapi_fastkit/backend/interactive/__init__.py +++ b/src/fastapi_fastkit/backend/interactive/__init__.py @@ -1,11 +1,13 @@ # -------------------------------------------------------------------------- # Interactive module for FastAPI-fastkit # -# Provides the prompts, the guided ``init`` dialogue and the project summary -# used for interactive project creation. +# Provides the prompts, the guided ``init`` dialogue, the project summary +# used for interactive project creation and the "Next steps" panel printed +# after it. # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- +from .next_steps import render_next_steps from .prompts import ( prompt_authentication_selection, prompt_caching_selection, @@ -42,6 +44,7 @@ "prompt_monitoring_selection", "prompt_utilities_selection", "prompt_package_manager_selection", + "render_next_steps", "render_project_summary", "render_selection_table", "multi_select_prompt", diff --git a/src/fastapi_fastkit/backend/interactive/next_steps.py b/src/fastapi_fastkit/backend/interactive/next_steps.py new file mode 100644 index 00000000..31f8df9e --- /dev/null +++ b/src/fastapi_fastkit/backend/interactive/next_steps.py @@ -0,0 +1,101 @@ +# -------------------------------------------------------------------------- +# The "Next steps" panel ``fastkit init`` and ``fastkit startdemo`` print +# after a project was created. +# +# The steps come from ``fastapi_fastkit.generation.guide`` as data; this +# module only draws them. Step text is catalog text and is printed as it +# is, never parsed as Rich markup. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING, Optional, Sequence + +from rich.console import Console, Group, RenderableType +from rich.panel import Panel +from rich.table import Table +from rich.text import Text + +from fastapi_fastkit.catalog import Catalog, load_catalog +from fastapi_fastkit.utils.main import console as default_console + +if TYPE_CHECKING: + # Type-only: importing the generation package here would import the + # pipeline, which imports backend.main, which imports this package. + from fastapi_fastkit.generation.guide import Command, Step + +#: Spaces between a step's text column and its commands. +COMMAND_INDENT = " " + + +def command_line(command: "Command", windows: bool) -> str: + """The line of ``command`` for the current OS.""" + if windows and command.windows is not None: + return command.windows + return command.text + + +def _step_body(step: "Step", windows: bool) -> Group: + lines = [Text(step.text)] + lines.extend( + Text(f"{COMMAND_INDENT}{command_line(command, windows)}", style="cyan") + for command in step.commands + ) + return Group(*lines) + + +def next_steps_panel( + steps: Sequence["Step"], + *, + windows: bool = False, + readme: bool = True, + catalog: Optional[Catalog] = None, +) -> Panel: + """ + The panel for ``steps``: numbered items, each with its commands below it. + + :param steps: :func:`fastapi_fastkit.generation.guide.next_steps` output + :param windows: Show the Windows line of commands that have one + :param readme: End with the line that points to README.md + :param catalog: Text source for the title and that line; defaults to + the English catalog + """ + guide = (catalog or load_catalog()).guide + # A grid keeps wrapped text aligned under the step's first word. + grid = Table.grid(padding=(0, 1, 0, 0)) + grid.add_column(no_wrap=True) + grid.add_column() + for number, step in enumerate(steps, start=1): + grid.add_row(Text(f"{number}."), _step_body(step, windows)) + body: list[RenderableType] = [grid] + if readme: + body.append(Text(guide["same_in_readme"], style="dim")) + return Panel( + Group(*body), + title=Text(guide["next_steps"]), + border_style="green", + expand=False, + ) + + +def render_next_steps( + steps: Sequence["Step"], + *, + windows: bool = False, + readme: bool = True, + catalog: Optional[Catalog] = None, + console: Optional[Console] = None, +) -> None: + """ + Print the "Next steps" panel (see :func:`next_steps_panel`); nothing + when there are no steps. + + :param console: Where to print; defaults to fastkit's console + """ + if not steps: + return + (console or default_console).print( + next_steps_panel(steps, windows=windows, readme=readme, catalog=catalog) + ) + + +__all__ = ["command_line", "next_steps_panel", "render_next_steps"] diff --git a/src/fastapi_fastkit/backend/main.py b/src/fastapi_fastkit/backend/main.py index ab2492ae..22e63be3 100644 --- a/src/fastapi_fastkit/backend/main.py +++ b/src/fastapi_fastkit/backend/main.py @@ -1792,12 +1792,14 @@ def statement_present(content: str, statement: str) -> bool: matter); otherwise as text with the comments removed. """ try: - wanted = [ast.dump(node) for node in ast.parse(statement.strip()).body] + wanted_nodes = ast.parse(statement.strip()).body tree = ast.parse(content) except SyntaxError: return statement.strip() in code_without_comments(content) - if not wanted: + if not wanted_nodes: return True + wanted = [ast.dump(node) for node in wanted_nodes] + wanted_types = [type(node) for node in wanted_nodes] # A copy in a branch that never runs (``if TYPE_CHECKING:``) does not # count; one inside a function does (an app factory), and so does one in # any block of a ``try`` / ``for`` / ``while`` (``else``, ``finally``, @@ -1819,9 +1821,14 @@ def statement_present(content: str, statement: str) -> bool: if isinstance(block, list) ] for block in blocks: - dumped = [ast.dump(child) for child in block if isinstance(child, ast.stmt)] - for start in range(len(dumped) - len(wanted) + 1): - if dumped[start : start + len(wanted)] == wanted: + statements = [child for child in block if isinstance(child, ast.stmt)] + for start in range(len(statements) - len(wanted) + 1): + window = statements[start : start + len(wanted)] + # Node types first: dumping every statement (a whole Settings + # class) is what made this slow. + if [type(node) for node in window] != wanted_types: + continue + if [ast.dump(node) for node in window] == wanted: return True return False diff --git a/src/fastapi_fastkit/backend/package_managers/pyproject.py b/src/fastapi_fastkit/backend/package_managers/pyproject.py index 293bbb0d..a7025ca8 100644 --- a/src/fastapi_fastkit/backend/package_managers/pyproject.py +++ b/src/fastapi_fastkit/backend/package_managers/pyproject.py @@ -780,6 +780,82 @@ def replace_project_dependencies( return updated +#: Tables whose ``version`` key is the project's version. +_VERSION_TABLES: Tuple[KeyPath, ...] = (("project",), ("tool", "poetry")) + + +def replace_project_version(content: str, version: str) -> str: + """ + Set the project's version in pyproject text. + + ``[project].version`` is replaced, or added when the table has none and + ``[project].dynamic`` does not list it. Poetry's ``[tool.poetry].version`` + is replaced too when the file declares one, so both keep one value. + Everything else is kept byte for byte (checked with the semantic + post-condition). + + :param content: pyproject text + :param version: The version to write + :return: Updated text (unchanged without a ``[project]`` table and a + Poetry version, or when ``[project].version`` is dynamic) + :raises PyprojectMergeError: if ``content`` is invalid TOML or the key + cannot be replaced without changing anything else + """ + data = parse_toml(content) + newline = _newline_of(content) + rendered = f"version = {toml_string(version)}" + blocks = _split_blocks(content) + owned: List[KeyPath] = [] + for path in _VERSION_TABLES: + table: Any = data + for part in path: + table = table.get(part) if isinstance(table, dict) else None + if not isinstance(table, dict): + continue + is_project = path == ("project",) + if "version" not in table and (not is_project or _is_dynamic(table, "version")): + continue + block = next( + (item for item in blocks if item.parts == path and not item.is_array), + None, + ) + if block is None: + raise PyprojectMergeError( + f"[{'.'.join(path)}] is defined with dotted keys or as an inline " + "table; fastkit only edits a standard table" + ) + statement = next( + (item for item in _statements(block.text, True) if item.key == "version"), + None, + ) + if statement is None: + if "version" in table: + raise PyprojectMergeError( + f"[{'.'.join(path)}].version is declared in a form fastkit " + "cannot edit safely" + ) + block.text = _insert_statement(block.text, rendered, newline) + else: + block.text = ( + block.text[: statement.key_start] + + rendered + + block.text[statement.value_end :] + ) + owned.append(path + ("version",)) + + updated = "".join(item.text for item in blocks) + parsed = _check_preserved(content, updated, owned) + for path in owned: + value: Any = parsed + for part in path: + value = value.get(part) if isinstance(value, dict) else None + if value != version: + raise PyprojectMergeError( + f"[{'.'.join(path[:-1])}].version could not be set in pyproject.toml" + ) + return updated + + def update_pep621_pyproject( existing: Optional[str], generated: str, dependencies: List[str] ) -> str: @@ -1273,6 +1349,7 @@ def append_tool_table_to_file( "replace_declared_optional_dependencies", "replace_dependency_group", "replace_project_dependencies", + "replace_project_version", "split_toml_tables", "toml_string", "toml_string_array", diff --git a/src/fastapi_fastkit/backend/project_builder/config_generator.py b/src/fastapi_fastkit/backend/project_builder/config_generator.py index c3e16cfe..4229985c 100644 --- a/src/fastapi_fastkit/backend/project_builder/config_generator.py +++ b/src/fastapi_fastkit/backend/project_builder/config_generator.py @@ -2,11 +2,13 @@ # Dynamic configuration file generation based on user selections # # Turns one interactive-``init`` configuration mapping into the complete set -# of files a project needs for the features the user picked: ``main.py``, -# the settings the features read, database / auth modules, background -# workers and their routes, cache, WebSocket and readiness routers, rate -# limiting, logging and tracing setup, Alembic migrations, developer tooling -# and the Docker files. +# of files a project needs for the features the user picked: the settings +# the features read, database / auth modules, background workers and their +# routes, cache, WebSocket and readiness routers, rate limiting, logging and +# tracing setup, Alembic migrations, developer tooling, the Docker files and +# (domain starter with a SQL database) the SQL-backed example items API. +# The template's ``main.py`` is kept; ``preset_layout`` wires the features +# into it. # # Every artifact is rendered from a Jinja2 fragment stored in # ``src/fastapi_fastkit/fragments``. See ``fragments/README.md`` for the @@ -20,13 +22,15 @@ # -------------------------------------------------------------------------- import ast import hashlib +import io import json import re import sys -from dataclasses import dataclass, field +import tokenize +from dataclasses import dataclass from functools import lru_cache from pathlib import Path -from typing import Any, Dict, List, Optional, Sequence, Tuple +from typing import Any, Collection, Dict, List, Optional, Sequence, Tuple from jinja2 import Environment, PackageLoader @@ -36,8 +40,13 @@ parse_toml, split_toml_tables, ) +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, + _binds_at_top_level, +) from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import ( + MULTI_SELECT_AXES, NONE_CHOICE, AsyncTaskChoice, AuthChoice, @@ -76,20 +85,24 @@ DatabaseChoice.REDIS: "redis", } -#: Connection settings of the app and worker containers per compose -#: database service (the host is the service name, not localhost). +#: Connection settings of the app, migrate and worker containers per compose +#: database service. The host is the service name, never taken from ``.env`` +#: (Compose interpolates ``${...}`` from ``.env``, where ``DATABASE_URL`` +#: points at localhost for running the app on the host); only the +#: credentials and the database name are interpolated, as the database +#: service itself reads them. _COMPOSE_DB_ENVIRONMENT: Dict[str, str] = { "postgres": ( - "DATABASE_URL=${DATABASE_URL:-postgresql+asyncpg://" + "DATABASE_URL=postgresql+asyncpg://" "${POSTGRES_USER:-user}:${POSTGRES_PASSWORD:-password}" - "@postgres:5432/${POSTGRES_DB:-dbname}}" + "@postgres:5432/${POSTGRES_DB:-dbname}" ), "mysql": ( - "DATABASE_URL=${DATABASE_URL:-mysql+aiomysql://" + "DATABASE_URL=mysql+aiomysql://" "${MYSQL_USER:-user}:${MYSQL_PASSWORD:-password}" - "@mysql:3306/${MYSQL_DATABASE:-dbname}}" + "@mysql:3306/${MYSQL_DATABASE:-dbname}" ), - "mongodb": "MONGODB_URL=${MONGODB_URL:-mongodb://mongodb:27017}", + "mongodb": "MONGODB_URL=mongodb://mongodb:27017", } #: docker-compose named volume per database service. @@ -99,6 +112,13 @@ "mongodb": "mongo_data", } +#: Where the image keeps a SQLite database (the Dockerfile creates the +#: directory for the app user; docker-compose mounts a volume there). +_SQLITE_CONTAINER_DIR = "/app/data" +_SQLITE_CONTAINER_URL = f"sqlite+aiosqlite:///{_SQLITE_CONTAINER_DIR}/app.db" +#: docker-compose named volume that keeps the SQLite database. +_COMPOSE_SQLITE_VOLUME = "sqlite_data" + #: Default entrypoint when the caller does not describe the project layout. DEFAULT_MAIN_RELPATH = "src/main.py" DEFAULT_DB_CONFIG_RELPATH = "src/config/database.py" @@ -117,6 +137,30 @@ #: variables in. The local ``.env`` is derived from it afterwards. ENV_EXAMPLE_RELPATH = ".env.example" +#: Config key of the multi-select deployment choice (not a feature axis). +DEPLOYMENT_KEY = "deployment" + +#: The project README (its structure tree follows SQL-backed items). +README_RELPATH = "README.md" + +#: The example items domain's modules replaced by SQL-backed ones, and the +#: fragment each is rendered from. +_ITEMS_SQL_MODULES: Dict[str, Tuple[str, str]] = { + "models.py": ("items_sql/models.py.j2", "Items domain: ORM model"), + "repository.py": ("items_sql/repository.py.j2", "Items domain: SQL repository"), + "service.py": ("items_sql/service.py.j2", "Items domain: service layer"), + "router.py": ("items_sql/router.py.j2", "Items domain: HTTP transport"), +} + +#: The classic layout's item modules (relative to the package) replaced or +#: added by SQL-backed items, and the fragment each is rendered from. +_ITEMS_SQL_CLASSIC_MODULES: Dict[str, Tuple[str, str]] = { + "models/items.py": ("items_sql_classic/models.py.j2", "Item model"), + "crud/items.py": ("items_sql_classic/crud.py.j2", "Item CRUD methods"), + "api/deps.py": ("items_sql_classic/deps.py.j2", "Shared route dependencies"), + "api/routes/items.py": ("items_sql_classic/routes.py.j2", "Item CRUD endpoints"), +} + #: Auth choices whose module signs tokens or cookies with ``SECRET_KEY``. _SIGNING_AUTH_CHOICES = frozenset( {AuthChoice.JWT, AuthChoice.OAUTH2, AuthChoice.SESSION, AuthChoice.FASTAPI_USERS} @@ -146,6 +190,64 @@ #: Line length of the generated code (black / ruff default). _LINE_LENGTH = 88 +#: Lines of a single module's ``main.py`` around its settings (the settings +#: model, its helpers and ``settings = Settings()``). The block moves to the +#: settings module once a generated module imports the settings. +SETTINGS_START_ANCHOR = "# fastkit:settings-start" +SETTINGS_END_ANCHOR = "# fastkit:settings-end" + +#: The structure-tree lines of the domain starter's README describing the +#: in-memory store; SQL-backed items replace them (``apply_readme_structure``). +MEMORY_TREE_LINES: Tuple[str, str] = ( + "\u2502 \u251c\u2500\u2500 db/", + "\u2502 \u2502 \u2514\u2500\u2500 memory.py " + "# in-memory store stand-in for a real DB", +) +#: The line SQL-backed items add to the ``core/`` block of that tree. +DATABASE_TREE_LINE = ( + "\u2502 \u2502 \u251c\u2500\u2500 database.py " + "# SQLAlchemy engine, session dependency" +) +#: The tree's comment on ``domains/items/models.py`` and its SQL wording. +_ITEMS_MODEL_TREE_COMMENTS = ("# entity dataclass", "# SQLAlchemy model (items table)") + +#: fastapi-default's README lines about its JSON file store and what +#: SQL-backed items put in their place (``apply_readme_structure``). Each +#: block is replaced only where the README holds it verbatim. +CLASSIC_README_EDITS: Tuple[Tuple[Tuple[str, ...], Tuple[str, ...]], ...] = ( + ( + ( + "\u2502 \u251c\u2500\u2500 mocks", + "\u2502 \u2502 \u2514\u2500\u2500 mock_items.json", + ), + ( + "\u2502 \u251c\u2500\u2500 models", + "\u2502 \u2502 \u2514\u2500\u2500 items.py", + ), + ), + ( + ("\u2502 \u2502 \u251c\u2500\u2500 config.py",), + ( + "\u2502 \u2502 \u251c\u2500\u2500 config.py", + "\u2502 \u2502 \u251c\u2500\u2500 database.py", + ), + ), + ( + ("- Initial data loading with mock data",), + ("- Items stored in the selected database through async SQLAlchemy",), + ), + ( + ( + "- Integrated test cases (they run against a temporary copy of the " + "data, never `src/mocks`)", + ), + ( + "- Integrated test cases (they run on an in-memory SQLite database, " + "never the configured one)", + ), + ), +) + def _env_example_declares(content: str, variable: str) -> bool: """Whether ``.env.example`` already mentions ``variable``, even commented out.""" @@ -153,6 +255,23 @@ def _env_example_declares(content: str, variable: str) -> bool: return re.search(pattern, content, re.M) is not None +#: A variable assignment in an ``.env.example`` block, also commented out. +_ENV_ASSIGNMENT = re.compile( + r"^[ \t]*#?[ \t]*(?:export[ \t]+)?([A-Z][A-Z0-9_]*)[ \t]*=" +) + + +def _env_block_variables(variable: str, lines: Sequence[str]) -> List[str]: + """Every variable an ``.env.example`` block assigns, in its order; the + block's own ``variable`` first.""" + names = [variable] + for line in lines: + match = _ENV_ASSIGNMENT.match(line) + if match and match.group(1) not in names: + names.append(match.group(1)) + return names + + def _name_sort_key(name: str) -> Tuple[int, str]: """isort / ruff ``order-by-type``: CONSTANTS, then Classes, then the rest.""" if name.isupper() and len(name) > 1: @@ -235,27 +354,14 @@ def _dotted(relpath: str) -> str: return normalized.replace("/", ".") -def _import_group(line: str, first_party_root: str) -> int: - """Bucket an import line the way isort's ``profile=black`` would. +def compose_image_name(project_name: str) -> str: + """The image the compose services of a project share: ``-app``. - ``0`` standard library, ``1`` third party, ``2`` first party. Used to - emit an already-sorted import block so the generated ``main.py`` passes - ``isort``/``ruff check`` straight out of the generator. + Docker image names allow lowercase ASCII letters, digits and + separators only, so anything else becomes ``-``. """ - stripped = line.strip() - if stripped.startswith("from "): - module = stripped.split(" ", 2)[1] - elif stripped.startswith("import "): - module = stripped.split(" ", 1)[1].split(" as ")[0] - else: # comment lines ride along with the third-party block - return 1 - - root = module.split(".", 1)[0] - if root == first_party_root: - return 2 - if root in sys.stdlib_module_names: - return 0 - return 1 + slug = re.sub(r"[^a-z0-9]+", "-", project_name.lower()).strip("-") + return f"{slug or 'project'}-app" def _slugify(name: str) -> str: @@ -265,20 +371,6 @@ def _slugify(name: str) -> str: return slug or "app" -@dataclass -class MainSections: - """The fragments composing one generated ``main.py``.""" - - #: Fragments contributing import statements (sorted before rendering). - import_fragments: list[str] = field(default_factory=list) - #: 4-space-indented statements run by the lifespan before ``yield``. - startup_fragments: list[str] = field(default_factory=list) - #: 4-space-indented statements run by the lifespan after ``yield``. - shutdown_fragments: list[str] = field(default_factory=list) - #: Top-level statements placed right after ``app = FastAPI(...)``. - setup_fragments: list[str] = field(default_factory=list) - - @dataclass(frozen=True) class SettingField: """One configuration value a generated feature reads from ``settings``.""" @@ -308,6 +400,9 @@ class SettingGroup: title: str fields: Tuple[SettingField, ...] + #: ``"axis:option"`` of the selection that added the group (the README + #: section of that feature lists the fields). + feature: str = "" def _str_field(name: str, value: str, *doc: str) -> SettingField: @@ -911,6 +1006,227 @@ def auth_guard_lines(*, demo_users: bool, secret_key: bool = True) -> List[str]: return lines +def _comment_line_numbers(content: str, comment: str) -> List[int]: + """0-based numbers of the lines that hold only ``comment`` (a real comment). + + Tokenized, so a string that merely contains the text does not count. The + module must parse. + """ + tokens = list(tokenize.generate_tokens(io.StringIO(content).readline)) + lines = content.split("\n") + return [ + token.start[0] - 1 + for token in tokens + if token.type == tokenize.COMMENT + and token.string.strip() == comment + and lines[token.start[0] - 1].strip() == comment + ] + + +def _annotation_names(node: ast.AST) -> set[str]: + """Names inside string annotations (``-> "Settings"``) below ``node``.""" + names: set[str] = set() + annotations: List[Optional[ast.expr]] = [] + for child in ast.walk(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): + annotations.append(child.returns) + arguments = child.args + for arg in [ + *arguments.posonlyargs, + *arguments.args, + *arguments.kwonlyargs, + arguments.vararg, + arguments.kwarg, + ]: + if arg is not None: + annotations.append(arg.annotation) + elif isinstance(child, ast.AnnAssign): + annotations.append(child.annotation) + for annotation in annotations: + if isinstance(annotation, ast.Constant) and isinstance(annotation.value, str): + try: + parsed = ast.parse(annotation.value, mode="eval") + except SyntaxError: + continue + names.update(n.id for n in ast.walk(parsed) if isinstance(n, ast.Name)) + return names + + +def _referenced_names(tree: ast.AST) -> set[str]: + """Every name the code below ``tree`` reads (string annotations included).""" + names = { + node.id + for node in ast.walk(tree) + if isinstance(node, ast.Name) and not isinstance(node.ctx, ast.Store) + } + return names | _annotation_names(tree) + + +def _bound_names(nodes: Sequence[ast.stmt]) -> set[str]: + """Names the top-level statements among ``nodes`` bind.""" + names: set[str] = set() + for node in nodes: + if isinstance(node, (ast.Import, ast.ImportFrom)): + names.update( + alias.asname or alias.name.split(".", 1)[0] for alias in node.names + ) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.add(node.name) + else: + targets: List[ast.expr] = [] + if isinstance(node, ast.Assign): + targets = list(node.targets) + elif isinstance(node, (ast.AnnAssign, ast.AugAssign)): + targets = [node.target] + for target in targets: + names.update( + n.id + for n in ast.walk(target) + if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store) + ) + return names + + +def _alias_source(alias: ast.alias) -> str: + return f"{alias.name} as {alias.asname}" if alias.asname else alias.name + + +def _prune_unused_imports(content: str, unused: set[str]) -> str: + """Remove the top-level imports binding a name of ``unused``. + + ``from x import a, b`` loses only the unused names (and is rewritten, + wrapped when long); a statement left without names is removed with the + blank line that separated it from the next section when it opened its + section, so the import block keeps isort's layout. + """ + tree = ast.parse(content) + lines = content.split("\n") + replacements: List[Tuple[int, int, List[str]]] = [] + for node in tree.body: + if not isinstance(node, (ast.Import, ast.ImportFrom)): + continue + if isinstance(node, ast.ImportFrom) and node.module == "__future__": + continue + kept = [ + alias + for alias in node.names + if (alias.asname or alias.name.split(".", 1)[0]) not in unused + ] + if len(kept) == len(node.names): + continue + start, end = node.lineno - 1, node.end_lineno or node.lineno + if not kept: + replacements.append((start, end, [])) + elif isinstance(node, ast.ImportFrom): + module = "." * node.level + (node.module or "") + statement = _format_from_import(module, [_alias_source(a) for a in kept]) + replacements.append((start, end, statement.split("\n"))) + else: + replacements.append( + (start, end, [f"import {_alias_source(a)}" for a in kept]) + ) + + for start, end, new in reversed(replacements): + lines[start:end] = new + if new: + continue + # A removed statement leaves the blank line below it behind; drop it + # when it would now follow a blank line, a comment or the file start. + opens_section = ( + start == 0 + or not lines[start - 1].strip() + or (lines[start - 1].lstrip().startswith("#")) + ) + if opens_section and start < len(lines) and not lines[start].strip(): + del lines[start] + return "\n".join(lines) + + +#: The single-module template's header sentence, true until the settings move. +SINGLE_MODULE_HEADER = ( + "# The whole application lives in this one module: settings, app and routes." +) + + +def cut_settings_block(content: str, settings_module: str) -> str: + """Move a single module's settings out: ``main.py`` imports them instead. + + Removes the lines from ``# fastkit:settings-start`` to + ``# fastkit:settings-end`` (and the blank lines below the end anchor), + drops the imports only that block used, and imports ``settings`` from + ``settings_module``. The rest of the module is left as it was. + + Args: + content: Source of ``main.py`` (``\\n`` line endings) + settings_module: Dotted module that now defines ``settings`` + + Returns: + The updated source + + Raises: + SettingsInjectionError: the anchors are missing or misplaced, or the + rest of the module uses a name only the block defined + """ + try: + original = ast.parse(content) + except SyntaxError as exc: + raise SettingsInjectionError( + f"main.py does not parse ({exc.msg}, line {exc.lineno}); the settings " + "could not be moved out of it." + ) from exc + starts = _comment_line_numbers(content, SETTINGS_START_ANCHOR) + ends = _comment_line_numbers(content, SETTINGS_END_ANCHOR) + if len(starts) != 1 or len(ends) != 1 or starts[0] >= ends[0]: + raise SettingsInjectionError( + "The settings could not be moved out of main.py: it needs one " + f"'{SETTINGS_START_ANCHOR}' line above one '{SETTINGS_END_ANCHOR}' " + "line around the settings; nothing was written." + ) + lines = content.split("\n") + start, stop = starts[0], ends[0] + 1 + while stop < len(lines) and not lines[stop].strip(): + stop += 1 + # The blank lines above the block now separate what precedes it from + # what follows it: two before a function or class (black), one before + # anything else (isort puts one after the imports). + while start > 0 and not lines[start - 1].strip(): + start -= 1 + following = next( + (line.lstrip() for line in lines[stop:] if not line.lstrip().startswith("#")), + "", + ) + blank = 2 if following.startswith(("def ", "async def ", "class ", "@")) else 1 + kept = lines[:start] + [""] * (blank if start else 0) + lines[stop:] + remaining = "\n".join(kept) + try: + tree = ast.parse(remaining) + except SyntaxError as exc: + raise SettingsInjectionError( + "The settings anchors in main.py split a statement; the settings " + "could not be moved out of it." + ) from exc + + block = [ + node + for node in original.body + if start < node.lineno - 1 < ends[0] and not isinstance(node, ast.Expr) + ] + still_used = _referenced_names(tree) + lost = sorted((_bound_names(block) & still_used) - {"settings"}) + if lost: + raise SettingsInjectionError( + f"main.py uses {', '.join(lost)} outside its settings block; the " + "settings could not be moved out of it." + ) + only_block = _referenced_names(original) - still_used + updated = _prune_unused_imports(remaining, only_block) + + # Imported lazily: ``backend.main`` imports this package. + from fastapi_fastkit.backend.main import insert_import_line + + return insert_import_line(updated, f"from {settings_module} import settings") + + def _declares_tool_table(pyproject_text: str, tool: str) -> bool: """Whether pyproject text already configures ``[tool.]``. @@ -950,6 +1266,9 @@ def __init__( settings_relpath: str = DEFAULT_SETTINGS_RELPATH, shipped_paths: Sequence[str] = (), provide_pagination: bool = False, + settings_in_main: Optional[bool] = None, + sql_items: Optional[bool] = None, + items_layout: Optional[str] = None, ) -> None: """ Initialize config generator. @@ -967,13 +1286,24 @@ def __init__( configuration from it; the fields they need are added to the template's ``Settings`` class, or the module is generated when the template ships none. - shipped_paths: Paths a preserved template ``main.py`` already - serves (``"/ready"``); the matching generated router is then - not created. Ignored when ``main.py`` is regenerated. + shipped_paths: Paths the template ``main.py`` already serves + (``"/ready"``); the matching generated router is then not + created. provide_pagination: Whether the shared ``core/pagination.py`` and ``core/responses.py`` are written when the template does not ship them (presets whose base template has no list endpoint of its own). + settings_in_main: Whether ``main.py`` holds the settings between + the ``# fastkit:settings-start`` / ``-end`` anchors (single + module); they move to ``settings_relpath`` once a generated + module imports them. None: as the configured preset says. + sql_items: Whether the example items API is replaced by a + SQL-backed one when a SQL database is selected. None: as the + configured preset says. + items_layout: ``"domain"`` (``domains/items`` package) or + ``"classic"`` (model, CRUD module and routes of the layered + layout) for the SQL-backed items. None: as the configured + preset says. """ self.config = config self.project_dir = Path(project_dir) @@ -984,6 +1314,21 @@ def __init__( self.settings_relpath = settings_relpath self.shipped_paths = frozenset(shipped_paths) self.provide_pagination = provide_pagination + preset = str(config.get("architecture_preset") or "").strip() + profile = PresetLayoutStrategist(preset).profile if preset else None + self.settings_in_main = ( + (profile is not None and profile.settings_in_main) + if settings_in_main is None + else settings_in_main + ) + self.sql_items = ( + (profile is not None and profile.sql_items) + if sql_items is None + else sql_items + ) + if items_layout is None: + items_layout = profile.items_layout if profile is not None else "domain" + self.items_layout = items_layout # ----------------------------------------------------------------- # # Layout helpers @@ -1182,6 +1527,40 @@ def _uses_sql_database(self) -> bool: """Whether the selection is a relational database Alembic can migrate.""" return self._database_type in SQL_DATABASES + @property + def _uses_sql_items(self) -> bool: + """Whether the example items API is generated on the SQL database.""" + return self.sql_items and self._uses_sql_database + + @property + def items_dir(self) -> str: + """Project-relative directory of the example items domain.""" + return f"{self.package_dir}/domains/items" + + @property + def items_module(self) -> str: + """Dotted import path of the example items domain.""" + return _dotted(self.items_dir) + + @property + def _classic_items(self) -> bool: + """Whether the SQL-backed items follow the classic layered layout.""" + return self.items_layout == "classic" + + @property + def items_models_module(self) -> str: + """Dotted import path of the module defining the ``Item`` model.""" + if self._classic_items: + return f"{self.pkg}.models.items" + return f"{self.items_module}.models" + + @property + def _items_table(self) -> str: + """Which ``items`` table the initial revision creates ("" for none).""" + if not self._uses_sql_items: + return "" + return self.items_layout + @property def _uses_ruff(self) -> bool: """Whether ruff replaces black + isort in the generated tooling.""" @@ -1259,118 +1638,6 @@ def _worker_command(self) -> Optional[List[str]]: return ["dramatiq", f"{self.pkg}.worker"] return None - def _main_fragments(self) -> MainSections: - """ - Resolve the fragments composing ``main.py`` for this configuration. - - Setup statements keep a deliberate order: logging first, then auth, - rate limiting and instrumentation, then the routers, and CORS last so - its middleware wraps every other one (``add_middleware`` puts the - latest addition outermost). - - Returns: - The fragment paths for each section of the generated module - """ - imports: List[str] = [] - startup: List[str] = [] - shutdown: List[str] = [] - setup: List[str] = [] - - def use(name: str, *sections: str) -> None: - """Register ``main/imports/.j2`` and ``main/
/.j2``.""" - imports.append(f"main/imports/{name}.j2") - targets = {"startup": startup, "shutdown": shutdown, "setup": setup} - for section in sections: - targets[section].append(f"main/{section}/{name}.j2") - - db_type = self._database_type - if db_type in SQL_DATABASES: - use("sqlalchemy", "shutdown") - elif db_type == DatabaseChoice.MONGODB: - use("mongodb", "startup", "shutdown") - elif db_type == DatabaseChoice.REDIS: - use("redis_db", "shutdown") - - if self._uses_structured_logging: - use("structured_logging", "setup") - if self._uses_loguru: - use("loguru", "setup") - - auth_type = self._auth_type - if auth_type in _SESSION_AUTH_CHOICES: - use("session_middleware", "setup") - - utilities = self._choices(FeatureAxis.UTILITIES) - if UtilityChoice.RATE_LIMITING in utilities: - use("rate_limiting", "setup") - - monitoring_type = self._choice(FeatureAxis.MONITORING) - if monitoring_type == MonitoringChoice.PROMETHEUS: - # Module level, never in the lifespan: instrumenting adds - # middleware, which Starlette refuses once the app has started. - use("prometheus", "setup") - elif monitoring_type == MonitoringChoice.OPENTELEMETRY: - use("opentelemetry", "setup") - - if self._choice(FeatureAxis.ASYNC_TASKS) != NONE_CHOICE: - use("async_tasks", "setup") - if self._uses_redis_cache: - use("caching", "setup") - if UtilityChoice.WEBSOCKET in utilities: - use("websocket", "setup") - if self.generates_readiness: - use("readiness", "setup") - if auth_type != NONE_CHOICE: - use("auth", "setup") - - # Always, like every template's main.py: the middleware is only added - # when BACKEND_CORS_ORIGINS lists an origin, so without one nothing - # changes. The CORS utility additionally documents the variable. - use("cors", "setup") - - return MainSections( - import_fragments=imports, - startup_fragments=startup, - shutdown_fragments=shutdown, - setup_fragments=setup, - ) - - def _build_import_groups(self, import_fragments: List[str]) -> List[List[str]]: - """ - Render the import fragments into isort-ordered import blocks. - - Fragments are written independently of each other, so concatenating - them verbatim produced a jumbled import block that ``isort`` (and the - generated project's own ``make lint``) immediately rejected. Sorting - here keeps every fragment free to declare exactly what it needs. - - Args: - import_fragments: Fragment paths contributing import statements - - Returns: - Standard-library / third-party / first-party blocks, in order - """ - lines: List[str] = [ - "from collections.abc import AsyncIterator", - "from contextlib import asynccontextmanager", - "from fastapi import FastAPI", - f"from {self.settings_module} import settings", - ] - - for fragment in import_fragments: - rendered = self._render_module(fragment) - lines.extend(line for line in rendered.splitlines() if line.strip()) - - first_party_root = self.pkg.split(".", 1)[0] - groups: List[List[str]] = [[], [], []] - for line in dict.fromkeys(lines): # dedupe, preserving first sighting - groups[_import_group(line, first_party_root)].append(line) - - for group in groups: - group.sort(key=lambda line: (not line.startswith("import "), line)) - - return [group for group in groups if group] - # ----------------------------------------------------------------- # # Settings # ----------------------------------------------------------------- # @@ -1385,6 +1652,7 @@ def settings_groups(self) -> List[SettingGroup]: slug = _slugify(str(self.config.get("project_name", "app"))) db_type = self._database_type + db_key = f"{FeatureAxis.DATABASE}:{db_type}" if db_type in SQL_DATABASES: groups.append( SettingGroup( @@ -1406,6 +1674,7 @@ def settings_groups(self) -> List[SettingGroup]: ), ), ), + db_key, ) ) elif db_type == DatabaseChoice.MONGODB: @@ -1430,6 +1699,7 @@ def settings_groups(self) -> List[SettingGroup]: ("How long an operation waits for a reachable server.",), ), ), + db_key, ) ) @@ -1438,6 +1708,11 @@ def settings_groups(self) -> List[SettingGroup]: SettingGroup( "Redis", (_str_field("REDIS_URL", _REDIS_URL, "Redis server URL."),), + ( + db_key + if db_type == DatabaseChoice.REDIS + else f"{FeatureAxis.CACHING}:{CachingChoice.REDIS}" + ), ) ) @@ -1456,6 +1731,7 @@ def settings_groups(self) -> List[SettingGroup]: "Where Celery stores task results (empty: the broker).", ), ), + f"{FeatureAxis.ASYNC_TASKS}:{tasks}", ) ) elif tasks == AsyncTaskChoice.DRAMATIQ: @@ -1469,6 +1745,7 @@ def settings_groups(self) -> List[SettingGroup]: "Dramatiq broker and result backend.", ), ), + f"{FeatureAxis.ASYNC_TASKS}:{tasks}", ) ) @@ -1483,6 +1760,11 @@ def settings_groups(self) -> List[SettingGroup]: "DEBUG, INFO, WARNING, ERROR or CRITICAL.", ), ), + ( + f"{FeatureAxis.LOGGING}:{LoggingChoice.STRUCTURED}" + if self._uses_structured_logging + else f"{FeatureAxis.MONITORING}:{MonitoringChoice.LOGURU}" + ), ) ) @@ -1507,6 +1789,7 @@ def settings_groups(self) -> List[SettingGroup]: "otlp, or none to record spans without exporting them.", ), ), + f"{FeatureAxis.MONITORING}:{MonitoringChoice.OPENTELEMETRY}", ) ) @@ -1531,6 +1814,7 @@ def settings_groups(self) -> List[SettingGroup]: "async+redis://localhost:6379/0 (shared, needs limits[async-redis]).", ), ), + f"{FeatureAxis.UTILITIES}:{UtilityChoice.RATE_LIMITING}", ) ) @@ -1635,7 +1919,11 @@ def _auth_settings_group(self) -> Optional[SettingGroup]: ) if not fields: return None - return SettingGroup("Authentication", tuple(fields)) + return SettingGroup( + "Authentication", + tuple(fields), + f"{FeatureAxis.AUTHENTICATION}:{auth_type}", + ) def _base_settings_groups(self) -> List[SettingGroup]: """Fields every generated feature may rely on, added when missing.""" @@ -1704,13 +1992,29 @@ def generate_settings_module(self) -> str: ) ) + def imports_settings_module(self) -> bool: + """Whether a generated module imports the project's settings module.""" + needle = f"from {self.settings_module} import " + return any(needle in content for content in self.build_artifacts().values()) + + @property + def settings_moved(self) -> bool: + """Whether the settings move out of ``main.py`` into their own module. + + Only a single module keeps them in ``main.py``; they move once a + generated module imports them, since that module cannot import + ``main.py`` (which imports it). + """ + return self.settings_in_main and self.imports_settings_module() + def apply_settings_module(self) -> List[str]: """ Make the project's settings module declare every field features read. A template-shipped module gets the missing fields added to its ``Settings`` class (fields it already declares are kept); without - one, a complete module is generated. + one, a complete module is generated when a generated module imports + it. Returns: Project-relative paths written (the settings module, plus the @@ -1718,6 +2022,8 @@ def apply_settings_module(self) -> List[str]: """ path = self.project_dir / self.settings_relpath if not path.exists(): + if not self.imports_settings_module(): + return [] path.parent.mkdir(parents=True, exist_ok=True) written = self._ensure_package(path.parent) write_generated_text(path, self.generate_settings_module()) @@ -1806,23 +2112,18 @@ def _ensure_package(self, directory: Path) -> List[str]: # ----------------------------------------------------------------- # # Public generators # ----------------------------------------------------------------- # - def build_artifacts(self, include_main: bool = True) -> Dict[str, str]: + def build_artifacts(self) -> Dict[str, str]: """ Resolve every file this configuration produces. - Args: - include_main: Whether the dynamic ``main.py`` overlay is part of - the output. Presets that preserve their template-shipped - entrypoint pass ``False``. + The template's ``main.py`` is always kept (features are wired into + it), so it is never one of them. Returns: Mapping of project-relative path to file content """ artifacts: Dict[str, str] = {} - if include_main: - artifacts[self.main_py_relpath] = self.generate_main_py() - db_config = self.generate_database_config() if db_config is not None: artifacts[self.db_config_relpath] = db_config @@ -1833,14 +2134,7 @@ def build_artifacts(self, include_main: bool = True) -> Dict[str, str]: if test_config is not None: artifacts["pytest.ini"] = test_config - # The base template's own test_main.py asserts *its* root message and - # health payload. Once the overlay replaces main.py those tests are - # wrong, so the matching tests are regenerated with it. - if include_main and self._choice(FeatureAxis.TESTING) != NONE_CHOICE: - artifacts["tests/test_main.py"] = self._render_module( - "test/test_main.py.j2", title="Application entry point tests" - ) - + artifacts.update(self.generate_items_files()) artifacts.update(self.generate_feature_modules()) artifacts.update(self.generate_feature_tests()) artifacts.update(self.generate_test_isolation()) @@ -1850,17 +2144,14 @@ def build_artifacts(self, include_main: bool = True) -> Dict[str, str]: return artifacts - def planned_files(self, include_main: bool = True) -> List[str]: + def planned_files(self) -> List[str]: """ List the project-relative files a run would create, writing nothing. - Args: - include_main: See :meth:`build_artifacts` - Returns: Sorted list of project-relative paths """ - planned = set(self.build_artifacts(include_main=include_main)) + planned = set(self.build_artifacts()) deployment = self.config.get("deployment") or [] if "Docker" in deployment: @@ -1878,17 +2169,22 @@ def planned_files(self, include_main: bool = True) -> List[str]: planned.add("pyproject.toml") if self._mypy_overrides(): planned.add("pyproject.toml") - if self.env_example_blocks(include_main=include_main): + if self.env_example_blocks(): planned.add(ENV_EXAMPLE_RELPATH) if self._gitignore_additions(): planned.add(".gitignore") settings_path = self.project_dir / self.settings_relpath if not settings_path.exists(): - planned.add(self.settings_relpath) - planned.add(f"{self.settings_relpath.rsplit('/', 1)[0]}/__init__.py") + if self.imports_settings_module(): + planned.add(self.settings_relpath) + planned.add(f"{self.settings_relpath.rsplit('/', 1)[0]}/__init__.py") elif self._injected_settings(settings_path) is not None: planned.add(self.settings_relpath) + if self.settings_moved: + planned.add(self.main_py_relpath) + if self._uses_sql_items: + planned.add(README_RELPATH) missing_core = self._missing_core_modules() for name in missing_core: planned.add(f"{self.package_dir}/core/{name}") @@ -1901,7 +2197,7 @@ def planned_files(self, include_main: bool = True) -> List[str]: return sorted(planned) - def generate_all_files(self, include_main: bool = True) -> List[str]: + def generate_all_files(self) -> List[str]: """ Generate every file this configuration implies, on disk. @@ -1909,15 +2205,12 @@ def generate_all_files(self, include_main: bool = True) -> List[str]: has been deployed. Parent directories are created as needed and shell scripts are written executable. - Args: - include_main: See :meth:`build_artifacts` - Returns: Sorted list of project-relative paths that were written """ written: List[str] = [] - for relpath, content in self.build_artifacts(include_main=include_main).items(): + for relpath, content in self.build_artifacts().items(): target = self.project_dir / relpath target.parent.mkdir(parents=True, exist_ok=True) write_generated_text(target, content) @@ -1926,6 +2219,9 @@ def generate_all_files(self, include_main: bool = True) -> List[str]: written.append(relpath) written.extend(self.apply_settings_module()) + if self.settings_moved: + written.extend(self.move_settings_out_of_main()) + written.extend(self.apply_readme_structure()) written.extend(self.apply_pagination_module()) written.extend(self.generate_docker_files(app_module=self.app_module)) @@ -1942,7 +2238,7 @@ def generate_all_files(self, include_main: bool = True) -> List[str]: if mypy_target: written.append(mypy_target) - env_example = self.apply_env_example(include_main=include_main) + env_example = self.apply_env_example() if env_example: written.append(env_example) gitignore = self.apply_gitignore() @@ -1987,9 +2283,7 @@ def apply_gitignore(self) -> Optional[str]: write_text_preserving_newlines(path, content, newline) return ".gitignore" - def env_example_blocks( - self, include_main: bool = True - ) -> List[Tuple[str, List[str]]]: + def env_example_blocks(self) -> List[Tuple[str, List[str]]]: """ ``.env.example`` lines documenting the variables the selection reads. @@ -1999,19 +2293,19 @@ def env_example_blocks( when the local ``.env`` is generated from this file. Every preset reads these through its settings module (which loads - ``.env``), so the blocks do not depend on whether ``main.py`` is - regenerated. - - Args: - include_main: Accepted for symmetry with :meth:`build_artifacts`; - the documented variables are the same either way + ``.env``). Returns: ``(variable, lines)`` blocks, in the order they are appended """ - blocks: List[Tuple[str, List[str]]] = [] + return [(variable, lines) for variable, lines, _feature in self._env_blocks()] + + def _env_blocks(self) -> List[Tuple[str, List[str], str]]: + """:meth:`env_example_blocks` with the ``"axis:option"`` of each block.""" + blocks: List[Tuple[str, List[str], str]] = [] auth_type = self._auth_type + auth_key = f"{FeatureAxis.AUTHENTICATION}:{auth_type}" if auth_type in _SIGNING_AUTH_CHOICES: blocks.append( ( @@ -2021,6 +2315,7 @@ def env_example_blocks( "# value to .env; never deploy this example value.", "SECRET_KEY=changethis", ], + auth_key, ) ) blocks.append( @@ -2031,6 +2326,7 @@ def env_example_blocks( "# SECRET_KEY.", "ENVIRONMENT=development", ], + auth_key, ) ) if auth_type == AuthChoice.OAUTH2: @@ -2044,6 +2340,7 @@ def env_example_blocks( "GITHUB_CLIENT_ID=", "GITHUB_CLIENT_SECRET=", ], + auth_key, ) ) @@ -2057,6 +2354,7 @@ def env_example_blocks( "# without credentials (no cookies or Authorization headers).", "# BACKEND_CORS_ORIGINS=http://localhost:3000", ], + f"{FeatureAxis.UTILITIES}:{UtilityChoice.CORS}", ) ) @@ -2067,12 +2365,13 @@ def env_example_blocks( setting.name, [f"# {line}" for line in setting.doc] + [f"# {setting.name}={setting.env_value}"], + group.feature, ) ) return blocks - def apply_env_example(self, include_main: bool = True) -> Optional[str]: + def apply_env_example(self) -> Optional[str]: """ Append :meth:`env_example_blocks` to the project's ``.env.example``. @@ -2080,14 +2379,11 @@ def apply_env_example(self, include_main: bool = True) -> Optional[str]: comment), so the template's own entries win and re-running is a no-op. The file is created when the template ships none. - Args: - include_main: See :meth:`env_example_blocks` - Returns: ``".env.example"`` when the file holds the entries, None when the selection documents no variable """ - blocks = self.env_example_blocks(include_main=include_main) + blocks = self.env_example_blocks() if not blocks: return None @@ -2111,25 +2407,6 @@ def apply_env_example(self, include_main: bool = True) -> Optional[str]: write_text_preserving_newlines(path, content, newline) return ENV_EXAMPLE_RELPATH - def generate_main_py(self) -> str: - """ - Generate main.py with selected features. - - Returns: - Content of main.py as string - """ - sections = self._main_fragments() - return self._render_module( - "main.py.j2", - title="FastAPI Application Main Entry Point", - description=self.config.get("description", ""), - version=self.config.get("version", "0.1.0"), - import_groups=self._build_import_groups(sections.import_fragments), - startup_fragments=sections.startup_fragments, - shutdown_fragments=sections.shutdown_fragments, - setup_fragments=sections.setup_fragments, - ) - def generate_database_config(self) -> Optional[str]: """ Generate database configuration. @@ -2222,6 +2499,390 @@ def generate_auth_files(self) -> Dict[str, str]: ) return files + def generate_items_files(self) -> Dict[str, str]: + """ + Generate the SQL-backed example items API (domain starter). + + Replaces the template's in-memory ``domains/items`` modules, its + ``tests/test_items.py`` and ``tests/conftest.py`` (the tests run on + an in-memory SQLite database), and its ``tests/test_pagination.py``, + which tested the in-memory store, with the shared pagination tests. + Without Alembic the router creates the ``items`` table on startup; + with it the initial revision does. + + Returns: + Mapping of project-relative path to file content (empty unless + the preset stores its items in the selected SQL database) + """ + if not self._uses_sql_items: + return {} + if self._classic_items: + return self._generate_classic_items_files() + context = { + "items_module": self.items_module, + "create_item_table": not self._uses_alembic, + } + files = { + f"{self.items_dir}/{name}": self._render_module( + fragment, title=title, **context + ) + for name, (fragment, title) in _ITEMS_SQL_MODULES.items() + } + files["tests/test_items.py"] = self._render_module( + "items_sql/test_items.py.j2", title="Items domain: CRUD tests", **context + ) + files["tests/conftest.py"] = self._render_module( + "items_sql/conftest_items_sql.py.j2", + title="pytest fixtures", + **context, + ) + files["tests/test_pagination.py"] = self._render_module( + "test/test_pagination.py.j2", title="Pagination tests" + ) + return files + + def _generate_classic_items_files(self) -> Dict[str, str]: + """ + Generate the SQL-backed items of the classic layered layout. + + Adds the ``Item`` model (``models/items.py``) and replaces the + template's JSON-file CRUD module, the item store dependency, the item + routes (now ``async def``), ``tests/conftest.py`` and + ``tests/test_items.py`` (the tests run on an in-memory SQLite + database). The JSON file and its tests are not copied + (:meth:`PresetLayoutStrategist.skipped_template_files`). + + Returns: + Mapping of project-relative path to file content + """ + context = {"create_item_table": not self._uses_alembic} + files = {f"{self.package_dir}/models/__init__.py": ""} + for relpath, (fragment, title) in _ITEMS_SQL_CLASSIC_MODULES.items(): + files[f"{self.package_dir}/{relpath}"] = self._render_module( + fragment, title=title, **context + ) + files["tests/test_items.py"] = self._render_module( + "items_sql_classic/test_items.py.j2", title="Item endpoint tests", **context + ) + files["tests/conftest.py"] = self._render_module( + "items_sql_classic/conftest.py.j2", title="pytest fixtures", **context + ) + return files + + def settings_target_conflict(self) -> Optional[str]: + """ + Why the settings cannot move out of ``main.py``, or None. + + The move cuts the settings block from ``main.py``, which then imports + ``settings`` from the settings module. An existing settings module + (kept by an in-place run) must therefore already bind ``settings`` + at module level; fastkit's own module from an earlier run does. + + Returns: + The refusal message, or None when the move is safe (or not made) + """ + if not self.settings_moved: + return None + path = self.project_dir / self.settings_relpath + if not path.is_file(): + return None + try: + content, _ = read_text_preserving_newlines(path) + except (OSError, UnicodeDecodeError): + content = "" + if _binds_at_top_level(content, "settings"): + return None + return ( + f"{self.settings_relpath} already exists and does not define " + f"'settings'. Your selections move the settings of " + f"{self.main_py_relpath} into {self.settings_relpath}, and " + f"{self.main_py_relpath} would import 'settings' from it. Move or " + "rename that file, or create the project in a new folder." + ) + + def move_settings_out_of_main(self) -> List[str]: + """ + Cut the settings block out of a single module's ``main.py``. + + The generated settings module holds the same settings; ``main.py`` + imports ``settings`` from it (see :func:`cut_settings_block`). + + Returns: + ``[main.py]`` when it was rewritten, else nothing (no ``main.py``) + """ + path = self.project_dir / self.main_py_relpath + if not path.is_file(): + return [] + content, newline = read_text_preserving_newlines(path) + updated = cut_settings_block(content, self.settings_module) + # The module header must not claim the settings any more. + updated = updated.replace( + SINGLE_MODULE_HEADER, + f"# The app and its routes; the settings are in {self.settings_relpath}.", + 1, + ) + write_text_preserving_newlines(path, updated, newline) + return [self.main_py_relpath] + + def apply_readme_structure(self) -> List[str]: + """ + Make the README's structure tree describe the SQL-backed items. + + The ``db/memory.py`` lines (:data:`MEMORY_TREE_LINES`) go, the + ``core/`` block gains ``database.py`` and the items model is described + as the ORM model. A README without those lines is left alone. + + Returns: + ``["README.md"]`` when it was rewritten, else nothing + """ + path = self.project_dir / README_RELPATH + if not (self._uses_sql_items and path.is_file()): + return [] + content, newline = read_text_preserving_newlines(path) + lines = content.split("\n") + if self._classic_items: + return self._apply_classic_readme(path, lines, newline) + memory = list(MEMORY_TREE_LINES) + start = next( + ( + index + for index in range(len(lines) - 1) + if lines[index : index + 2] == memory + ), + None, + ) + if start is None: + return [] + del lines[start : start + 2] + core = next( + ( + index + for index, line in enumerate(lines) + if line.endswith("\u2500 core/") + ), + None, + ) + if core is not None: + at = core + 1 + if at < len(lines) and "config.py" in lines[at]: + at += 1 + lines.insert(at, DATABASE_TREE_LINE) + old, new = _ITEMS_MODEL_TREE_COMMENTS + lines = [ + line.replace(old, new) if "models.py" in line else line for line in lines + ] + write_text_preserving_newlines(path, "\n".join(lines), newline) + return [README_RELPATH] + + @staticmethod + def _apply_classic_readme(path: Path, lines: List[str], newline: str) -> List[str]: + """Apply :data:`CLASSIC_README_EDITS` to fastapi-default's README. + + A block already replaced (an earlier run) or missing is left alone. + + Returns: + ``["README.md"]`` when it was rewritten, else nothing + """ + + def find(block: Sequence[str]) -> Optional[int]: + size = len(block) + return next( + ( + index + for index in range(len(lines) - size + 1) + if lines[index : index + size] == list(block) + ), + None, + ) + + changed = False + for old, new in CLASSIC_README_EDITS: + start = find(old) + if start is None or find(new) is not None: + continue + lines[start : start + len(old)] = list(new) + changed = True + if not changed: + return [] + write_text_preserving_newlines(path, "\n".join(lines), newline) + return [README_RELPATH] + + # ----------------------------------------------------------------- # + # What the README's feature sections say (generation.guide) + # ----------------------------------------------------------------- # + def _selected_keys(self) -> List[str]: + """``"axis:option"`` of every selected option, in axis order.""" + keys: List[str] = [] + for axis in FeatureAxis: + if axis == FeatureAxis.DATABASE: + values = [self._database_type] + elif axis in MULTI_SELECT_AXES: + values = self._choices(axis) + elif axis == FeatureAxis.AUTHENTICATION: + values = [self._auth_type] + else: + values = [self._choice(axis)] + keys += [f"{axis}:{value}" for value in values if value != NONE_CHOICE] + deployment = self.config.get(DEPLOYMENT_KEY) or [] + keys += [ + f"{DEPLOYMENT_KEY}:{value}" for value in deployment if value != NONE_CHOICE + ] + return keys + + def _feature_paths(self) -> Dict[str, str]: + """Each overlay path a feature owns -> that feature's ``"axis:option"``. + + Files every feature shares (the settings module, ``core/``, + ``features/__init__.py``, ``.env.example``, ``.gitignore``, + ``pyproject.toml``, the requirements files, ``README.md``, ``main.py``) + belong to none. + """ + selected = set(self._selected_keys()) + pkg = self.package_dir + owned: Dict[str, str] = {} + + def own(key: str, *paths: str) -> None: + if key in selected: + for path in paths: + owned.setdefault(path, key) + + db_key = f"{FeatureAxis.DATABASE}:{self._database_type}" + cache_key = f"{FeatureAxis.CACHING}:{CachingChoice.REDIS}" + rate_key = f"{FeatureAxis.UTILITIES}:{UtilityChoice.RATE_LIMITING}" + otel_key = f"{FeatureAxis.MONITORING}:{MonitoringChoice.OPENTELEMETRY}" + own(db_key, self.db_config_relpath) + own(db_key, *self.generate_items_files()) + readiness = (f"{pkg}/features/readiness.py", "tests/test_readiness.py") + own(db_key, *readiness) + own(cache_key, *readiness, f"{pkg}/features/cache.py") + # The root conftest isolates the database first, then rate limits + # and tracing. + if self._uses_sql_database: + own(db_key, "conftest.py") + own(rate_key, "conftest.py") + own(otel_key, "conftest.py") + + auth_key = f"{FeatureAxis.AUTHENTICATION}:{self._auth_type}" + auth_files = self.generate_auth_files() + own(auth_key, *auth_files, "tests/test_auth.py") + + tasks_key = f"{FeatureAxis.ASYNC_TASKS}:{self._choice(FeatureAxis.ASYNC_TASKS)}" + own( + tasks_key, + f"{pkg}/worker.py", + f"{pkg}/features/tasks.py", + "tests/test_tasks.py", + ) + websocket_key = f"{FeatureAxis.UTILITIES}:{UtilityChoice.WEBSOCKET}" + own(websocket_key, f"{pkg}/features/websocket.py", "tests/test_websocket.py") + own(rate_key, f"{pkg}/rate_limiting.py", "tests/test_rate_limiting.py") + own( + f"{FeatureAxis.LOGGING}:{LoggingChoice.STRUCTURED}", + f"{pkg}/logging_config.py", + ) + own( + f"{FeatureAxis.MONITORING}:{MonitoringChoice.LOGURU}", + f"{pkg}/loguru_config.py", + ) + own(otel_key, f"{pkg}/telemetry.py") + + testing_key = f"{FeatureAxis.TESTING}:{self._choice(FeatureAxis.TESTING)}" + own(testing_key, "pytest.ini", "tests/factories.py", "tests/test_factories.py") + if self.provide_pagination: + own(testing_key, "tests/test_pagination.py") + + migrations = self.generate_migration_files() + own(f"{FeatureAxis.MIGRATIONS}:{MigrationsChoice.ALEMBIC}", *migrations) + + tooling = { + ToolingChoice.RUFF: ("ruff.toml",), + ToolingChoice.PRE_COMMIT: (".pre-commit-config.yaml",), + ToolingChoice.GITHUB_ACTIONS: (".github/workflows/test.yml",), + ToolingChoice.DEVCONTAINER: (".devcontainer/devcontainer.json",), + ToolingChoice.MAKEFILE: ("Makefile",), + } + for choice, paths in tooling.items(): + own(f"{FeatureAxis.TOOLING}:{choice}", *paths) + + own(f"{DEPLOYMENT_KEY}:Docker", "Dockerfile", ".dockerignore") + own(f"{DEPLOYMENT_KEY}:docker-compose", "docker-compose.yml", ".dockerignore") + return owned + + def feature_files(self, written: Collection[str]) -> Dict[str, Tuple[str, ...]]: + """ + The written files that belong to each selected feature. + + Args: + written: Project-relative POSIX paths the run wrote + + Returns: + ``"axis:option"`` -> its files among ``written``, sorted (only + features that own at least one written file); every file belongs + to one feature at most + """ + owned = self._feature_paths() + files: Dict[str, List[str]] = {} + for path in sorted(set(written)): + key = owned.get(path) + if key is not None: + files.setdefault(key, []).append(path) + return {key: tuple(paths) for key, paths in files.items()} + + def feature_settings(self) -> Dict[str, Tuple[str, ...]]: + """ + The ``.env`` variables each selected feature reads. + + Returns: + ``"axis:option"`` -> variable names, in ``.env.example`` order + """ + settings: Dict[str, List[str]] = {} + for variable, lines, feature in self._env_blocks(): + if not feature: + continue + names = settings.setdefault(feature, []) + for name in _env_block_variables(variable, lines): + if name not in names: + names.append(name) + return {key: tuple(names) for key, names in settings.items() if names} + + def _services(self) -> List[str]: + """Servers the selection needs running (display names), in order.""" + services: List[str] = [] + db_type = self._database_type + if db_type not in (NONE_CHOICE, DatabaseChoice.SQLITE): + services.append(db_type) + if self._needs_redis_service and DatabaseChoice.REDIS not in services: + services.append(DatabaseChoice.REDIS) + return services + + def guide_layout(self) -> Dict[str, Any]: + """ + Facts about the generated layout the next steps and README need. + + Returns: + ``services`` (servers to start, display names), + ``compose_services`` (their docker-compose service names, empty + without docker-compose), ``worker_command`` (the background + worker's command, empty without one), ``sql_items`` (the example + items API stores its items in the database), ``uses_alembic``, + ``single_file_split`` (the settings moved out of ``main.py``) and + ``compose`` (docker-compose.yml runs the app with its services) + """ + services = self._services() + compose: Tuple[str, ...] = () + has_compose = "docker-compose" in (self.config.get(DEPLOYMENT_KEY) or []) + if has_compose: + compose = tuple(COMPOSE_DB_SERVICES[name] for name in services) + return { + "services": tuple(services), + "compose_services": compose, + "compose": has_compose, + "worker_command": tuple(self._worker_command() or ()), + "sql_items": self._uses_sql_items, + "uses_alembic": self._uses_alembic, + "single_file_split": self.settings_moved, + } + def generate_feature_modules(self) -> Dict[str, str]: """ Generate the standalone modules the selected features import. @@ -2377,10 +3038,14 @@ def generate_test_isolation(self) -> Dict[str, str]: count rate limits in memory, reset before every test. Returns: - ``{"conftest.py": content}``, or nothing without testing or when - no generated feature reaches outside the process during tests + ``{"conftest.py": content}``, or nothing without testing (unless + the SQL-backed items API, whose template tests always run, is + generated) or when no generated feature reaches outside the + process during tests """ - if self._choice(FeatureAxis.TESTING) == NONE_CHOICE: + if self._choice(FeatureAxis.TESTING) == NONE_CHOICE and not ( + self._uses_sql_items + ): return {} sql = self._uses_sql_database otel = self._choice(FeatureAxis.MONITORING) == MonitoringChoice.OPENTELEMETRY @@ -2435,15 +3100,19 @@ def generate_migration_files(self) -> Dict[str, str]: "migrations/initial_revision.py.j2", revision_id=revision_id, users_table=self._auth_kind if self._has_users_table else "", + items_table=self._items_table, ), "scripts/migrate.sh": self._render_module("migrations/migrate_sh.j2"), } def _model_modules(self) -> List[str]: """Generated modules defining ORM models (imported by Alembic).""" + modules: List[str] = [] if self._has_users_table: - return [f"{self.auth_module}.models"] - return [] + modules.append(f"{self.auth_module}.models") + if self._uses_sql_items: + modules.append(self.items_models_module) + return modules def generate_tooling_files(self) -> Dict[str, str]: """ @@ -2738,7 +3407,7 @@ def _dockerfile_writable_dirs(self) -> List[Dict[str, str]]: if self._database_type == DatabaseChoice.SQLITE: dirs.append( { - "dir": "/app/data", + "dir": _SQLITE_CONTAINER_DIR, "comment": "The SQLite database lives in /app/data (mount a " "volume there to keep it).", } @@ -2749,7 +3418,7 @@ def _generate_dockerfile(self, app_module: str = "src.main:app") -> str: """Generate Dockerfile content with a layout-aware uvicorn target.""" env_lines: List[str] = [] if self._database_type == DatabaseChoice.SQLITE: - env_lines.append("DATABASE_URL=sqlite+aiosqlite:////app/data/app.db") + env_lines.append(f"DATABASE_URL={_SQLITE_CONTAINER_URL}") return self._render( "docker/dockerfile.j2", title="Dockerfile", @@ -2781,7 +3450,15 @@ def _generate_docker_compose(self) -> str: depends_on.append("redis") volumes.append("redis_data") + # SQLite has no server: the database file lives in the containers, in + # a named volume so it survives recreating them. The URL is set here, + # not left to .env, because it must name the mounted directory. + mounts: List[str] = [] environment: List[str] = [] + if self._database_type == DatabaseChoice.SQLITE: + mounts.append(f"{_COMPOSE_SQLITE_VOLUME}:{_SQLITE_CONTAINER_DIR}") + volumes.append(_COMPOSE_SQLITE_VOLUME) + environment.append(f"DATABASE_URL={_SQLITE_CONTAINER_URL}") if db_service in _COMPOSE_DB_ENVIRONMENT: environment.append(_COMPOSE_DB_ENVIRONMENT[db_service]) if self._database_type == DatabaseChoice.REDIS or self._uses_redis_cache: @@ -2792,6 +3469,11 @@ def _generate_docker_compose(self) -> str: elif tasks == AsyncTaskChoice.DRAMATIQ: environment.append("DRAMATIQ_BROKER_URL=redis://redis:6379/0") + # With Alembic the tables come from the migrations, so a one-shot + # ``migrate`` service applies them before the app starts. Never in + # the app's start command: several replicas would race. + migrate_depends_on = [db_service] if db_service else [] + return self._render( "docker/docker_compose.j2", title="docker-compose.yml", @@ -2801,6 +3483,10 @@ def _generate_docker_compose(self) -> str: depends_on=depends_on, volumes=volumes, environment=environment, + mounts=mounts, + migrate=self._uses_alembic, + migrate_depends_on=migrate_depends_on, + image=compose_image_name(str(self.config.get("project_name") or "")), ) def generate_test_config(self) -> Optional[str]: diff --git a/src/fastapi_fastkit/backend/project_builder/config_schema.py b/src/fastapi_fastkit/backend/project_builder/config_schema.py index 4372b617..f7cfa4fd 100644 --- a/src/fastapi_fastkit/backend/project_builder/config_schema.py +++ b/src/fastapi_fastkit/backend/project_builder/config_schema.py @@ -32,6 +32,7 @@ # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- +import re from typing import Any, Dict, List, Optional, Tuple from fastapi_fastkit.catalog import evaluate, load_catalog, selection_from_config @@ -220,6 +221,7 @@ def _normalize( errors.extend(_normalize_deployment(config, normalized)) errors.extend(_normalize_string_list(config, normalized, "custom_packages")) errors.extend(_normalize_string_list(config, normalized, "all_dependencies")) + errors.extend(_normalize_version(config, normalized)) if check_combinations: errors.extend(combination_errors(normalized)) @@ -406,6 +408,56 @@ def _normalize_package_manager( return [] +#: A PEP 440 version (the pattern of the ``packaging`` library, which +#: fastkit does not depend on), matched case-insensitively. +_PEP440_VERSION = re.compile( + r""" + v? + (?:(?P[0-9]+)!)? + (?P[0-9]+(?:\.[0-9]+)*) + (?P
[-_\.]?(?:a|b|c|rc|alpha|beta|pre|preview)[-_\.]?[0-9]*)?
+    (?P(?:-[0-9]+)|(?:[-_\.]?(?:post|rev|r)[-_\.]?[0-9]*))?
+    (?P[-_\.]?dev[-_\.]?[0-9]*)?
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?
+    """,
+    re.VERBOSE | re.IGNORECASE,
+)
+
+
+def version_error(value: Any) -> Optional[str]:
+    """
+    Why ``value`` is not a usable project version, or ``None`` when it is.
+
+    A version is a PEP 440 string (an integer is read as one); it becomes
+    ``[project].version`` of the generated ``pyproject.toml``.
+    """
+    if isinstance(value, bool) or not isinstance(value, (str, int)):
+        hint = ' (quote it: version: "1.10")' if isinstance(value, float) else ""
+        return (
+            f"Config key 'version' must be a string{hint}, got "
+            f"{type(value).__name__}"
+        )
+    if not _PEP440_VERSION.fullmatch(str(value).strip()):
+        return (
+            f"Config key 'version' must be a PEP 440 version such as 1.0.0, "
+            f"got '{value}'"
+        )
+    return None
+
+
+def _normalize_version(config: Dict[str, Any], normalized: Dict[str, Any]) -> List[str]:
+    """Validate ``version``; ``null`` and ``""`` mean "not set"."""
+    raw = config.get("version")
+    if raw is None or raw == "":
+        return []
+    error = version_error(raw)
+    if error:
+        normalized.pop("version", None)
+        return [error]
+    normalized["version"] = str(raw).strip()
+    return []
+
+
 def _normalize_deployment(
     config: Dict[str, Any], normalized: Dict[str, Any]
 ) -> List[str]:
diff --git a/src/fastapi_fastkit/backend/project_builder/preset_layout.py b/src/fastapi_fastkit/backend/project_builder/preset_layout.py
index 58c63567..5e540cbc 100644
--- a/src/fastapi_fastkit/backend/project_builder/preset_layout.py
+++ b/src/fastapi_fastkit/backend/project_builder/preset_layout.py
@@ -5,12 +5,13 @@
 # decisions interactive ``init`` makes:
 #
 #   - which template ships as the base scaffold,
-#   - whether the dynamic ``main.py`` overlay should overwrite the shipped one,
 #   - where database / auth config files and the settings module live, so
 #     they sit next to the template's existing structure,
-#   - which generated features are spliced into a preserved ``main.py``
+#   - which generated features are spliced into the template's ``main.py``
 #     through its ``# fastkit:`` anchors (a "wire this up manually" note is
-#     left only for a ``main.py`` that cannot be found).
+#     left only for a ``main.py`` that cannot be found),
+#   - whether the template keeps its settings in ``main.py`` (single module)
+#     and whether its example items API moves to the selected SQL database.
 #
 # Keeping every preset's layout knowledge in one place lets the CLI flow stay
 # linear ("ask the strategist where to write the file") instead of growing a
@@ -291,6 +292,20 @@ def _uses_session_auth(config: Dict[str, Any]) -> bool:
     target.label for target in OVERLAY_TARGETS if target.label != "CORS"
 )
 
+#: Where the example items API of the domain starter keeps its items when
+#: the selected database is not a SQL one (MongoDB, Redis).
+ITEMS_MEMORY_NOTE = (
+    "The example `/items` API keeps its items in memory: fastkit stores them "
+    "in the database only for PostgreSQL, MySQL and SQLite."
+)
+
+#: Shown when a single-module project's settings moved to their own module.
+SETTINGS_SPLIT_NOTE = (
+    "single-file: the settings moved from src/main.py to src/core/config.py "
+    "because the generated modules import them; src/main.py keeps the app and "
+    "its routes."
+)
+
 #: Shown once whenever the (former) Pagination utility is selected.
 PAGINATION_NOTE = (
     "Pagination: list endpoints are paginated by default "
@@ -305,22 +320,19 @@ class PresetProfile:
 
     preset_id: str
     base_template: str
-    regenerate_main: bool
     main_py_relpath: str
     db_config_relpath: str
     #: Directory of the generated authentication package.
     auth_package_relpath: str
-    # Hint shown when ``regenerate_main`` is False and the user picked a
-    # feature whose dynamic main.py overlay won't run. Empty string means
-    # "no special note for this preset".
+    # Hint shown when the template's ``main.py`` cannot be found, so the
+    # selected features could not be wired into it. Empty string means "no
+    # special note for this preset".
     manual_wiring_note: str = ""
     extra_warning_targets: Tuple[str, ...] = field(default_factory=tuple)
     #: The project's settings module (pydantic-settings, exports ``settings``).
     settings_relpath: str = "src/core/config.py"
-    #: Probe paths the preserved template ``main.py`` serves itself; a
-    #: generated router for the same path is skipped. Only meaningful when
-    #: ``regenerate_main`` is False (a regenerated main.py serves ``/health``
-    #: and mounts the generated ``/ready`` itself).
+    #: Probe paths the template ``main.py`` serves itself; a generated router
+    #: for the same path is skipped.
     shipped_paths: Tuple[str, ...] = field(default_factory=tuple)
     #: Write ``core/pagination.py`` when the base template has none (base
     #: templates without a list endpoint of their own).
@@ -328,6 +340,22 @@ class PresetProfile:
     #: Where the base template's example items API keeps its items, when
     #: that is not the selected database ("" when the template has none).
     items_store: str = ""
+    #: The template's ``main.py`` holds the settings between
+    #: ``# fastkit:settings-start`` / ``-end``; they move to
+    #: ``settings_relpath`` once a generated module imports them.
+    settings_in_main: bool = False
+    #: With a SQL database the example items API stores its items there
+    #: instead of the template's own store.
+    sql_items: bool = False
+    #: Shape of the SQL-backed items: ``"domain"`` (``fragments/items_sql``,
+    #: a ``domains/items`` package) or ``"classic"``
+    #: (``fragments/items_sql_classic``: model, CRUD module, routes).
+    items_layout: str = "domain"
+    #: Template files of the replaced store that SQL-backed items leave
+    #: unused (project-relative POSIX paths), and the template directories
+    #: holding nothing else.
+    store_files: Tuple[str, ...] = field(default_factory=tuple)
+    store_dirs: Tuple[str, ...] = field(default_factory=tuple)
 
 
 def _base_template(preset_id: str) -> str:
@@ -339,19 +367,26 @@ def _base_template(preset_id: str) -> str:
     "single-module": PresetProfile(
         preset_id="single-module",
         base_template=_base_template("single-module"),
-        regenerate_main=True,
         main_py_relpath="src/main.py",
-        db_config_relpath="src/config/database.py",
+        db_config_relpath="src/core/database.py",
         auth_package_relpath="src/auth",
-        # The template is a single module: when it ships no settings module,
-        # the generator writes one here (next to core/pagination.py).
+        manual_wiring_note=(
+            "fastapi-single-module's shipped src/main.py is preserved. The "
+            "selections below need manual wiring there (CORS is already "
+            "wired — set BACKEND_CORS_ORIGINS in .env to activate it)."
+        ),
+        extra_warning_targets=_NON_CORS_TARGETS,
+        # The template keeps its settings in src/main.py. Generated modules
+        # cannot import them from there (main.py imports those modules), so
+        # they move here as soon as one does (next to core/pagination.py).
         settings_relpath="src/core/config.py",
+        shipped_paths=("/health",),
         provide_pagination=True,
+        settings_in_main=True,
     ),
     "classic-layered": PresetProfile(
         preset_id="classic-layered",
         base_template=_base_template("classic-layered"),
-        regenerate_main=False,
         main_py_relpath="src/main.py",
         db_config_relpath="src/core/database.py",
         auth_package_relpath="src/auth",
@@ -368,11 +403,18 @@ def _base_template(preset_id: str) -> str:
         settings_relpath="src/core/config.py",
         shipped_paths=("/health",),
         items_store="in the JSON file src/mocks/mock_items.json",
+        sql_items=True,
+        items_layout="classic",
+        store_files=(
+            "src/mocks/__init__.py",
+            "src/mocks/mock_items.json",
+            "tests/test_item_store.py",
+        ),
+        store_dirs=("src/mocks",),
     ),
     "domain-starter": PresetProfile(
         preset_id="domain-starter",
         base_template=_base_template("domain-starter"),
-        regenerate_main=False,
         main_py_relpath="src/app/main.py",
         db_config_relpath="src/app/core/database.py",
         auth_package_relpath="src/app/domains/auth",
@@ -385,6 +427,9 @@ def _base_template(preset_id: str) -> str:
         settings_relpath="src/app/core/config.py",
         shipped_paths=("/health",),
         items_store="in process memory (src/app/db/memory.py)",
+        sql_items=True,
+        store_files=("src/app/db/__init__.py", "src/app/db/memory.py"),
+        store_dirs=("src/app/db",),
     ),
 }
 
@@ -466,9 +511,54 @@ def preset_id(self) -> str:
     def base_template(self) -> str:
         return self.profile.base_template
 
-    @property
-    def should_regenerate_main(self) -> bool:
-        return self.profile.regenerate_main
+    def generator_options(self) -> Dict[str, Any]:
+        """Layout keyword arguments of ``DynamicConfigGenerator`` for this preset."""
+        profile = self.profile
+        return {
+            "main_py_relpath": profile.main_py_relpath,
+            "db_config_relpath": profile.db_config_relpath,
+            "auth_package_relpath": profile.auth_package_relpath,
+            "settings_relpath": profile.settings_relpath,
+            "shipped_paths": profile.shipped_paths,
+            "provide_pagination": profile.provide_pagination,
+            "settings_in_main": profile.settings_in_main,
+            "sql_items": profile.sql_items,
+            "items_layout": profile.items_layout,
+        }
+
+    def uses_sql_items(self, config: Dict[str, Any]) -> bool:
+        """Whether the example items API stores its items in the SQL database."""
+        return self.profile.sql_items and _database_type(config) in _SQL_DATABASES
+
+    def skipped_template_files(self, config: Dict[str, Any]) -> Tuple[str, ...]:
+        """Template files the copy must leave out for this selection.
+
+        With SQL-backed items the template's own store has no user left: the
+        domain starter's in-memory store (``db/__init__.py``, ``db/memory.py``),
+        fastapi-default's JSON file (``mocks/``) and its tests.
+        Project-relative POSIX paths.
+        """
+        if not self.uses_sql_items(config):
+            return ()
+        return self.profile.store_files
+
+    def skipped_template_dirs(self, config: Dict[str, Any]) -> Tuple[str, ...]:
+        """Template directories left out because every file in them is skipped."""
+        if not self.uses_sql_items(config):
+            return ()
+        return self.profile.store_dirs
+
+    def settings_moved(self, config: Dict[str, Any]) -> bool:
+        """Whether generation moves the settings out of ``main.py`` (single module)."""
+        if not self.profile.settings_in_main:
+            return False
+        # Imported lazily: the generator module imports this one.
+        from fastapi_fastkit.backend.project_builder.config_generator import (
+            DynamicConfigGenerator,
+        )
+
+        generator = DynamicConfigGenerator(config, ".", **self.generator_options())
+        return generator.settings_moved
 
     def main_py_target(self, project_dir: str) -> Path:
         """Absolute path where the dynamic main.py overlay should land."""
@@ -494,11 +584,10 @@ def compatibility_warnings(
     ) -> List[str]:
         """Return user-facing warnings for selections left unwired.
 
-        The dynamic ``main.py`` overlay wires everything for presets that
-        regenerate ``main.py``. Presets that keep the template-shipped
-        ``main.py`` get most features spliced in through its anchors
-        (:meth:`wire_generated_routers`). Every target is wirable, so this
-        lists something only when ``main.py`` could not be found.
+        Every preset keeps its template's ``main.py`` and gets the features
+        spliced in through its anchors (:meth:`wire_generated_routers`).
+        Every target is wirable, so this lists something only when
+        ``main.py`` could not be found.
 
         Args:
             config: Interactive project configuration
@@ -508,9 +597,6 @@ def compatibility_warnings(
         Returns:
             Warning strings, empty when nothing needs manual attention
         """
-        if self.profile.regenerate_main:
-            return []
-
         already_wired = set(wired)
         affected = [
             label
@@ -548,10 +634,15 @@ def items_store_note(self, config: Dict[str, Any]) -> str:
         """One line saying the example items are not in the selected database.
 
         Empty unless a database is selected and the base template's items
-        API keeps its items somewhere else.
+        API keeps its items somewhere else (with SQL-backed items, only
+        MongoDB and Redis keep them in the template's store).
         """
         if not (self.profile.items_store and _uses_database(config)):
             return ""
+        if self.uses_sql_items(config):
+            return ""
+        if self.profile.items_layout == "domain":
+            return ITEMS_MEMORY_NOTE
         return (
             "The example /items API keeps its items "
             f"{self.profile.items_store}, not in the selected database "
@@ -566,29 +657,11 @@ def generation_notes(self, config: Dict[str, Any]) -> List[str]:
         items_note = self.items_store_note(config)
         if items_note:
             notes.append(items_note)
+        if self.settings_moved(config):
+            notes.append(SETTINGS_SPLIT_NOTE)
         notes.extend(auth_generation_notes(config, self.profile.auth_package_relpath))
         return notes
 
-    def append_readme_notes(self, project_dir: str, config: Dict[str, Any]) -> bool:
-        """Add the :meth:`items_store_note` to the project's ``README.md``.
-
-        Returns:
-            Whether the README was changed (False without a note, without a
-            README, or when it already carries the note)
-        """
-        note = self.items_store_note(config)
-        readme = Path(project_dir) / "README.md"
-        if not note or not readme.is_file():
-            return False
-        content, newline = read_text_preserving_newlines(readme)
-        if note in content:
-            return False
-        if content and not content.endswith("\n"):
-            content += "\n"
-        content += f"\n## Notes\n\n{note}\n"
-        write_text_preserving_newlines(readme, content, newline)
-        return True
-
     def auth_route_conflicts(
         self, project_dir: str, config: Dict[str, Any]
     ) -> List[str]:
@@ -637,7 +710,7 @@ def auth_route_conflicts(
     def wire_generated_routers(
         self, project_dir: str, config: Dict[str, Any]
     ) -> List[str]:
-        """Splice generated features into a preserved ``main.py``.
+        """Splice generated features into the template's ``main.py``.
 
         Templates ship ``# fastkit:imports`` / ``# fastkit:routes`` anchors
         precisely so generated code can be added without rewriting the file.
@@ -647,19 +720,18 @@ def wire_generated_routers(
         mounted under ``settings.API_V1_PREFIX`` except root-level probes and
         the WebSocket endpoint, and ``setup_*(app)`` calls into generated
         modules. Anything not safely wirable is left to
-        :meth:`compatibility_warnings`.
+        :meth:`compatibility_warnings`. The settings import is left out when
+        ``main.py`` binds ``settings`` itself (a single module that keeps
+        its settings).
 
         Args:
             project_dir: Absolute path of the generated project
             config: Interactive project configuration
 
         Returns:
-            Labels of the features actually wired (empty when the preset
-            regenerates ``main.py``, or when ``main.py`` is missing)
+            Labels of the features actually wired (empty when ``main.py`` is
+            missing)
         """
-        if self.profile.regenerate_main:
-            return []
-
         # Imported lazily: ``backend.main`` imports this module at load time.
         from fastapi_fastkit.backend.main import (
             insert_import_line,
@@ -679,6 +751,8 @@ def wire_generated_routers(
         content, newline = read_text_preserving_newlines(main_path)
         original = content
         wired: List[str] = []
+        settings_import = _SETTINGS_IMPORT.format(**fields)
+        settings_bound = _binds_at_top_level(content, "settings")
 
         affected = [
             _TARGETS_BY_LABEL[label]
@@ -700,7 +774,10 @@ def wire_generated_routers(
         for target in reversed(affected):
             imports, statements = target.wiring
             for line in imports:
-                content = insert_import_line(content, line.format(**fields))
+                line = line.format(**fields)
+                if line == settings_import and settings_bound:
+                    continue
+                content = insert_import_line(content, line)
             for line in reversed(statements):
                 content = insert_statement_line(content, line.format(**fields))
             wired.insert(0, target.label)
@@ -833,15 +910,44 @@ def auth_generation_notes(
     return notes
 
 
+def _binds_at_top_level(content: str, name: str) -> bool:
+    """Whether a top-level statement of the module binds ``name``.
+
+    Imports, assignments, functions and classes count; a module that does
+    not parse binds nothing.
+    """
+    try:
+        tree = ast.parse(content)
+    except SyntaxError:
+        return False
+    for node in tree.body:
+        if isinstance(node, (ast.Import, ast.ImportFrom)):
+            if any(
+                (alias.asname or alias.name.split(".", 1)[0]) == name
+                for alias in node.names
+            ):
+                return True
+        elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+            if node.name == name:
+                return True
+        elif isinstance(node, (ast.Assign, ast.AnnAssign)):
+            targets = node.targets if isinstance(node, ast.Assign) else [node.target]
+            if any(isinstance(t, ast.Name) and t.id == name for t in targets):
+                return True
+    return False
+
+
 def _dotted_module(relpath: str) -> str:
     """``src/app/core/config.py`` -> ``src.app.core.config``."""
     return relpath.replace("\\", "/").removesuffix(".py").replace("/", ".")
 
 
 __all__ = [
+    "ITEMS_MEMORY_NOTE",
     "OVERLAY_TARGETS",
     "OverlayTarget",
     "PAGINATION_NOTE",
+    "SETTINGS_SPLIT_NOTE",
     "PresetLayoutStrategist",
     "PresetProfile",
     "app_module_from_main_path",
diff --git a/src/fastapi_fastkit/backend/rollback.py b/src/fastapi_fastkit/backend/rollback.py
index c8ffa7f8..e9e83f22 100644
--- a/src/fastapi_fastkit/backend/rollback.py
+++ b/src/fastapi_fastkit/backend/rollback.py
@@ -189,7 +189,13 @@ def restore(self) -> List[str]:
         return failed
 
     def discard(self) -> None:
-        """Delete the backup copies (after success, or once restored)."""
+        """Delete the backup copies (after success, or once restored).
+
+        The snapshot records nothing afterwards, so a later :meth:`restore`
+        (a rollback interrupted after a successful run) changes nothing.
+        """
+        self.saved, self.absent = [], []
+        self.absent_dirs, self.absent_trees = [], []
         if self.backup_dir is not None:
             rmtree_force(self.backup_dir, ignore_errors=True)
             self.backup_dir = None
diff --git a/src/fastapi_fastkit/backend/route_generators.py b/src/fastapi_fastkit/backend/route_generators.py
index 14bdc36b..497a9aa2 100644
--- a/src/fastapi_fastkit/backend/route_generators.py
+++ b/src/fastapi_fastkit/backend/route_generators.py
@@ -12,7 +12,7 @@
 from abc import ABC, abstractmethod
 from dataclasses import dataclass
 from pathlib import Path
-from typing import Dict, List, Optional, Sequence, Set, Union
+from typing import Dict, List, Optional, Sequence, Set, Tuple, Union
 
 from fastapi_fastkit.backend import main as backend
 from fastapi_fastkit.backend.project_builder.preset_layout import PresetLayoutStrategist
@@ -612,11 +612,32 @@ def plan(
 
         for relative in ("api", "api/routes", "crud", "schemas"):
             _plan_package_init(plan, os.path.join(package_dir, *relative.split("/")))
+        sql_items = classic_sql_items(project_dir, package_dir)
+        alembic = _has_alembic(project_dir)
+        items_crud = items_model = ""
+        if sql_items is not None:
+            items_crud, items_model = (plan.display(path) for path in sql_items)
         for relative, content in contents.items():
+            if sql_items is not None and relative == "crud":
+                content = _with_classic_sql_items_pointer(
+                    content, items_crud, items_model, alembic
+                )
             target = os.path.join(
                 package_dir, *relative.split("/"), f"{names.route}.py"
             )
             plan.create(target, content)
+        if sql_items is not None:
+            crud = os.path.join(package_dir, "crud", f"{names.route}.py")
+            table = (
+                "; an Alembic revision in alembic/versions/ creates its table"
+                if alembic
+                else ""
+            )
+            plan.note(
+                f"{names.route} keeps its records in memory ({plan.display(crud)}); "
+                f"{items_crud} shows the SQL-backed version, with its model in "
+                f"{items_model}{table}."
+            )
 
         # An envelope project documents errors with its own error_responses().
         _plan_shared_core(plan, package_dir, skip=["responses.py"] if envelope else [])
@@ -637,6 +658,107 @@ def plan(
         _plan_main(plan, project_layout, names)
 
 
+#: Metadata features of the SQL databases the example items API can use.
+_SQL_DATABASE_FEATURES = frozenset(
+    f"database:{name}" for name in ("PostgreSQL", "MySQL", "SQLite")
+)
+
+#: Line of the domain repository's header after which the pointer to the
+#: SQL-backed items goes.
+_MEMORY_HEADER_LINE = "# Data is stored in memory"
+
+
+def _defines_sql_items(project_dir: str, models: str) -> bool:
+    """Whether the project's metadata names a SQL database and ``models``
+    (the module of the example ``Item``) defines a table."""
+    features = read_fastkit_metadata(project_dir).get("features")
+    if not isinstance(features, list) or not _SQL_DATABASE_FEATURES & set(features):
+        return False
+    try:
+        content, _ = read_text_preserving_newlines(models)
+    except (OSError, UnicodeDecodeError):
+        return False
+    return "__tablename__" in content
+
+
+def sql_items_dir(project_dir: str, package_dir: str) -> Optional[str]:
+    """The SQL-backed example items domain of a project, when it has one.
+
+    True for projects generated with a SQL database at the domain level:
+    their metadata names the database and ``domains/items/models.py``
+    defines a table.
+
+    :return: Absolute directory of the items domain, else None
+    """
+    items = os.path.join(package_dir, "domains", "items")
+    if _defines_sql_items(project_dir, os.path.join(items, "models.py")):
+        return items
+    return None
+
+
+def classic_sql_items(project_dir: str, package_dir: str) -> Optional[Tuple[str, str]]:
+    """The SQL-backed example items of a layered project, when it has them.
+
+    True for projects generated with a SQL database at the layered level:
+    their metadata names the database and ``models/items.py`` defines a
+    table.
+
+    :return: Absolute paths of ``crud/items.py`` and ``models/items.py``,
+        else None
+    """
+    models = os.path.join(package_dir, "models", "items.py")
+    if _defines_sql_items(project_dir, models):
+        return os.path.join(package_dir, "crud", "items.py"), models
+    return None
+
+
+def _has_alembic(project_dir: str) -> bool:
+    """Whether the project creates its tables with Alembic revisions."""
+    return os.path.isdir(os.path.join(project_dir, "alembic", "versions"))
+
+
+def _with_sql_items_pointer(content: str, items: str, alembic: bool) -> str:
+    """Add a pointer to the SQL-backed items to a repository's header."""
+    pointer = [f"# {items}/ shows the SQL-backed version (model, repository, service"]
+    if alembic:
+        pointer += [
+            "# and router); an Alembic revision in alembic/versions/ creates",
+            "# its table.",
+        ]
+    else:
+        pointer.append("# and router).")
+    lines = content.split("\n")
+    for index, line in enumerate(lines):
+        if line.startswith(_MEMORY_HEADER_LINE):
+            lines[index + 1 : index + 1] = pointer
+            break
+    return "\n".join(lines)
+
+
+#: Line of the classic CRUD module's header after which the pointer to the
+#: SQL-backed items goes.
+_CLASSIC_MEMORY_HEADER_LINE = "# when the resource needs persistence"
+
+
+def _with_classic_sql_items_pointer(
+    content: str, crud: str, model: str, alembic: bool
+) -> str:
+    """Add a pointer to the SQL-backed items to a CRUD module's header."""
+    pointer = [f"# {crud} shows the SQL-backed version, with its model in"]
+    if alembic:
+        pointer.append(
+            f"# {model}; an Alembic revision in alembic/versions/ creates its table."
+        )
+    else:
+        pointer.append(f"# {model}.")
+    lines = content.split("\n")
+    for index, line in enumerate(lines):
+        if line.startswith(_CLASSIC_MEMORY_HEADER_LINE):
+            lines[index + 1 : index + 1] = pointer
+            break
+    return "\n".join(lines)
+
+
 _DOMAIN_FILES = (
     "__init__.py",
     "models.py",
@@ -677,9 +799,28 @@ def plan(
         if not plan.exists(domains_init):
             plan.write(domains_init, "")
         domain_dir = os.path.join(domains_dir, names.route)
+        sql_items = sql_items_dir(project_dir, package)
+        alembic = _has_alembic(project_dir)
         for filename in _DOMAIN_FILES:
             content = _render_route_module(templates / f"{filename}-tpl", replacements)
+            if sql_items is not None and filename == "repository.py":
+                content = _with_sql_items_pointer(
+                    content, plan.display(sql_items), alembic
+                )
             plan.create(os.path.join(domain_dir, filename), content)
+        if sql_items is not None:
+            repository = os.path.join(domain_dir, "repository.py")
+            table = (
+                "; an Alembic revision in alembic/versions/ creates its table"
+                if alembic
+                else ""
+            )
+            plan.note(
+                f"{names.route} keeps its records in memory "
+                f"({plan.display(repository)}); {plan.display(sql_items)}/ shows "
+                f"the SQL-backed version (model, repository, service and router)"
+                f"{table}."
+            )
 
         _plan_shared_core(plan, package)
         _plan_tests(
@@ -824,8 +965,8 @@ def _refuse_single_file_project(
         f"This project keeps its whole application in {main_file}, so there is "
         f"no package to add route modules to. Add the endpoint to {main_file} "
         "by hand, next to the existing ones (copy one endpoint and its test), "
-        "or generate a project from a larger starter such as fastapi-default "
-        "(`fastkit list-templates` shows them all)."
+        "or create a project at a later level with `fastkit init --level "
+        "layered` (`fastkit list-templates` lists the templates)."
     )
 
 
diff --git a/src/fastapi_fastkit/backend/scaffolder.py b/src/fastapi_fastkit/backend/scaffolder.py
index f6348dcb..7ede645f 100644
--- a/src/fastapi_fastkit/backend/scaffolder.py
+++ b/src/fastapi_fastkit/backend/scaffolder.py
@@ -15,12 +15,13 @@
 import dataclasses
 import os
 from dataclasses import dataclass, field
-from typing import Any, Callable, Dict, Iterable, List, Optional
+from typing import Any, Callable, Dict, Iterable, List, Literal, Optional
 
 import click
 from rich.tree import Tree
 
 from fastapi_fastkit.backend.main import (
+    ENV_EXAMPLE_FILE,
     ENV_FILE,
     check_package_manager_supported,
     create_venv_with_manager,
@@ -41,6 +42,7 @@
 from fastapi_fastkit.generation import (
     GenerationError,
     GenerationPlan,
+    GenerationResult,
     GenerationSpec,
     ProjectInfo,
     generate,
@@ -48,6 +50,7 @@
     spec_from_config,
 )
 from fastapi_fastkit.generation.dependencies import resolve_dependencies
+from fastapi_fastkit.generation.guide import Environment
 from fastapi_fastkit.generation.metadata import app_module_for
 from fastapi_fastkit.generation.metadata import build_metadata as _build_metadata
 from fastapi_fastkit.generation.pipeline import (
@@ -57,6 +60,7 @@
     template_directories,
     writable_paths,
 )
+from fastapi_fastkit.utils import platform
 from fastapi_fastkit.utils.logging import debug_log
 from fastapi_fastkit.utils.main import (
     console,
@@ -74,6 +78,12 @@
 #: Files creating the virtualenv and installing may write into the project.
 SETUP_ARTIFACTS = ("uv.lock", "poetry.lock", "pdm.lock", ".pdm-python")
 
+#: What a run did about the virtualenv (:attr:`Environment.venv`).
+VenvState = Literal["none", "created", "installed"]
+
+#: What a run did about ``.env`` (:attr:`Environment.env_file`).
+EnvFileState = Literal["written", "kept", "absent"]
+
 
 def replay_messages(messages: Iterable[Message]) -> None:
     """Print messages that generation recorded, in order."""
@@ -216,6 +226,11 @@ class ScaffoldResult:
     dry_run: bool = False
     #: The development part of ``dependencies``.
     dev_dependencies: List[str] = field(default_factory=list)
+    #: What ``generate`` wrote; None for a preview.
+    generation: Optional[GenerationResult] = None
+    #: The state the run left behind (folder, virtualenv, ``.env``), for
+    #: the next steps; None for a preview.
+    environment: Optional[Environment] = None
 
 
 class ProjectScaffolder:
@@ -428,6 +443,8 @@ def run(self) -> ScaffoldResult:
         venv_kept = self.options.with_venv and os.path.lexists(
             os.path.join(project_dir, VENV_DIR)
         )
+        # Whether the user already had a .env, which generation never replaces.
+        env_existed = os.path.lexists(os.path.join(project_dir, ENV_FILE))
         try:
             # A fact, not a guess: a directory that appears between a check
             # and its creation is treated as the user's.
@@ -453,10 +470,8 @@ def run(self) -> ScaffoldResult:
             replay_messages(generated.messages)
 
             venv_path = self._setup_environment(project_dir, manager)
-            if snapshot is not None:
-                snapshot.discard()
 
-            return ScaffoldResult(
+            result = ScaffoldResult(
                 project_dir=project_dir,
                 template=self.options.template,
                 app_module=generated.app_module,
@@ -464,13 +479,61 @@ def run(self) -> ScaffoldResult:
                 metadata=dict(generated.metadata),
                 venv_path=venv_path,
                 dev_dependencies=list(generated.dependencies.dev),
+                generation=generated,
+                environment=self._environment(
+                    project_dir, generated, venv_path, env_existed
+                ),
             )
+            # Last: until here a failure (or Ctrl+C) restores from the copies.
+            if snapshot is not None:
+                snapshot.discard()
+            return result
 
         except BaseException as e:
             debug_log(f"Scaffolding failed, rolling back: {e!r}", "error")
             self._roll_back(project_dir, created_dirs, snapshot, venv_kept)
             raise
 
+    def _environment(
+        self,
+        project_dir: str,
+        generated: GenerationResult,
+        venv_path: str,
+        env_existed: bool,
+    ) -> Environment:
+        """
+        The state a completed run left behind, as the next steps need it.
+
+        :param project_dir: The generated project
+        :param generated: What generation wrote
+        :param venv_path: What :meth:`_setup_environment` returned ("" when
+            no virtualenv was created)
+        :param env_existed: Whether a ``.env`` was there before the run
+        """
+        # A failed creation or installation raises and rolls the run back,
+        # so a run that got here did what its options asked for.
+        venv: VenvState = "none"
+        if venv_path:
+            venv = "installed" if self.options.with_install else "created"
+        env_file: EnvFileState = "absent"
+        if ENV_FILE in generated.files:
+            env_file = "written"
+        elif env_existed and os.path.isfile(
+            os.path.join(project_dir, ENV_EXAMPLE_FILE)
+        ):
+            env_file = "kept"
+        return Environment(
+            folder=(
+                self.options.project_name
+                if self.options.create_project_folder
+                else None
+            ),
+            venv=venv,
+            env_file=env_file,
+            # Looked up on the module, so a test can patch it.
+            windows=platform.is_windows(),
+        )
+
     def _roll_back(
         self,
         project_dir: str,
diff --git a/src/fastapi_fastkit/backend/transducer.py b/src/fastapi_fastkit/backend/transducer.py
index 9c7247d7..9b6c1f1f 100644
--- a/src/fastapi_fastkit/backend/transducer.py
+++ b/src/fastapi_fastkit/backend/transducer.py
@@ -204,7 +204,11 @@ def _process_directory_tree(
             else os.path.join(target_path, relative_path)
         )
 
-        _ensure_directory_exists(destination_dir)
+        # A directory is created for the files copied into it (or when the
+        # template ships it empty), so one whose every file is skipped is
+        # not left behind empty.
+        if not files and not dirs:
+            _ensure_directory_exists(destination_dir)
 
         # Process files in current directory
         for file in files:
@@ -221,6 +225,7 @@ def _process_directory_tree(
                 debug_log(f"Keeping the existing {relative_file}", "debug")
                 continue
             src_file = os.path.join(root, file)
+            _ensure_directory_exists(destination_dir)
             dst_file = _copy_template_file(src_file, destination_dir, file)
             if dst_file:
                 copied.append(dst_file)
diff --git a/src/fastapi_fastkit/catalog/__main__.py b/src/fastapi_fastkit/catalog/__main__.py
index 5523e6a6..a6b018f6 100644
--- a/src/fastapi_fastkit/catalog/__main__.py
+++ b/src/fastapi_fastkit/catalog/__main__.py
@@ -25,11 +25,19 @@ def strings_toml(skeleton: Mapping[str, Any]) -> str:
     """
     Render :func:`~fastapi_fastkit.catalog.i18n.translatable_strings` as TOML.
 
-    :param skeleton: ``{kind: {id: {field: text}}}``
+    :param skeleton: ``{kind: {id: {field: text}}}``; ``guide`` is flat
+        (``{key: text}``)
     :return: TOML text with quoted table keys
     """
     lines: list[str] = []
     for kind, entries in skeleton.items():
+        if kind == "guide":
+            if entries:
+                lines.append("[guide]")
+                for key, text in entries.items():
+                    lines.append(f"{key} = {_toml_string(text)}")
+                lines.append("")
+            continue
         for item_id, fields in entries.items():
             header = f"{kind}.{_toml_string(item_id)}"
             lines.append(f"[{header}]")
diff --git a/src/fastapi_fastkit/catalog/catalog.toml b/src/fastapi_fastkit/catalog/catalog.toml
index 20295abc..4f7e82ff 100644
--- a/src/fastapi_fastkit/catalog/catalog.toml
+++ b/src/fastapi_fastkit/catalog/catalog.toml
@@ -16,8 +16,10 @@ package_manager = "uv"
 base_dependencies = ["fastapi", "uvicorn", "pydantic", "pydantic-settings"]
 
 # ---------------------------------------------------------------- concepts
-# Concept id -> official FastAPI documentation page. Stage 4 writes at most one
-# concept comment per concept per project, ending with this URL.
+# Concept id -> official FastAPI documentation page. A generated project has
+# at most one concept comment per concept, ending with this URL. The
+# ``concepts`` lists of levels, templates and options name the comments the
+# code they generate carries (tested).
 [[concepts]]
 id = "first-steps"
 title = "First steps"
@@ -58,6 +60,11 @@ id = "dependencies"
 title = "Dependencies"
 url = "https://fastapi.tiangolo.com/tutorial/dependencies/"
 
+[[concepts]]
+id = "dependencies-with-yield"
+title = "Dependencies with yield"
+url = "https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/"
+
 [[concepts]]
 id = "bigger-applications"
 title = "Bigger applications with multiple files"
@@ -118,6 +125,54 @@ id = "async"
 title = "Concurrency and async / await"
 url = "https://fastapi.tiangolo.com/async/"
 
+# ------------------------------------------------------------------- guide
+# Text of the "Next steps" list (CLI panel and README) and of the README
+# "Selected features" sections. Every key is required; the only placeholder
+# is {services} (in ``services``). Commands are
+# built in code and never translated.
+[guide]
+next_steps = "Next steps"
+open = "Go to the project folder."
+install = "Create the virtual environment and install the dependencies."
+install_pip = "Create a virtual environment, activate it and install the dependencies."
+install_into_venv = "Install the dependencies into the virtual environment fastkit created."
+activate = "Activate the virtual environment."
+env = "Create your local settings file from the example and keep it out of version control."
+env_written = "Review .env: fastkit wrote it from .env.example with a unique SECRET_KEY."
+env_kept = "Your existing .env was kept; compare it with .env.example for new settings."
+services = "Start {services} and point the URL settings in .env at it."
+migrate = "Create the database tables."
+worker = "Start the background worker in a second terminal."
+run = "Start the development server and open http://127.0.0.1:8000/docs."
+run_readme_alternative = "With fastkit installed, `fastkit runserver` does the same."
+# Appended to the run step when the project has docker-compose.yml.
+run_compose = "Or run it in containers with Docker Compose: `docker compose up --build`."
+test = "Run the tests."
+extend_classic = "Add a resource with its route, schemas, data layer and tests."
+extend_domain = "Add a domain with its router, schemas, service, repository and tests."
+# Appended to the extend step in README.md, which a teammate may read
+# without fastkit installed (the CLI panel leaves it out).
+needs_fastkit = "The command needs fastkit installed."
+next_level = "When you want more structure, create a project at the next level."
+items_sql = "The example `/items` API stores its items in this database."
+items_memory = "The example `/items` API keeps its items in memory: fastkit stores them in the database only for PostgreSQL, MySQL and SQLite."
+items_file = "The example `/items` API keeps its items in the JSON file `src/mocks/mock_items.json`, not in this database."
+tables_alembic = "`alembic upgrade head` creates the tables."
+tables_startup = "The tables are created when the app starts (no migrations selected)."
+# Appended to the docker-compose section.
+compose_urls = "In the containers the URLs of these services come from `docker-compose.yml`; the URLs in `.env` are for running the app on your machine."
+compose_migrate = "A one-shot `migrate` service applies the Alembic migrations before the app starts."
+compose_sqlite = "The SQLite database file is kept in the `sqlite_data` volume."
+read_single_file_split = "Read `src/main.py` for the app and its routes, then `src/core/config.py` for the settings."
+# Read step of layered projects whose /items API stores its items in the SQL database.
+read_layered_sql_items = "Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py`, `src/models/items.py` and `src/schemas/items.py`."
+single_file_split = "Your selections add modules that read the settings, so the settings moved from `src/main.py` to `src/core/config.py`; `src/main.py` keeps the app and its routes and includes the features."
+files = "Files"
+settings = "Settings"
+learn_more = "Learn more"
+selected_features = "Selected features"
+same_in_readme = "README.md lists the steps for a fresh checkout of the project."
+
 # ------------------------------------------------------------------ levels
 # A level uses either ``template`` (no preset, no feature overlay) or
 # ``preset`` (template comes from the preset). ``bundle`` holds feature
@@ -128,7 +183,9 @@ label = "Hello"
 description = "One main.py: 3 endpoints, in-memory data, tests."
 template = "fastapi-hello"
 asks_database = false
-concepts = ["first-steps", "path-parameters", "query-parameters", "request-body", "status-codes", "testing"]
+concepts = ["first-steps", "path-parameters", "query-parameters", "request-body", "response-model", "status-codes", "handling-errors", "testing"]
+read_first = "Read `main.py` from top to bottom: each comment links the FastAPI tutorial page that explains it."
+extend = "Add a resource by imitation: copy the `Item` models, `create_item`, `read_item` and their tests, and rename them for `/users`."
 
 [[levels]]
 id = "single-file"
@@ -136,7 +193,8 @@ label = "Single file"
 description = "The whole app in one module, with settings and tests."
 preset = "single-module"
 asks_database = true
-concepts = ["response-model", "handling-errors", "settings", "testing"]
+concepts = ["first-steps", "settings", "cors", "testing"]
+read_first = "Read `src/main.py`: the settings, the app and its routes in one module."
 
 [[levels]]
 id = "layered"
@@ -144,7 +202,21 @@ label = "Layered"
 description = "Separate layers: routes, CRUD, schemas, core config."
 preset = "classic-layered"
 asks_database = true
-concepts = ["bigger-applications", "dependencies", "response-model", "settings"]
+concepts = [
+  "first-steps",
+  "path-parameters",
+  "query-parameters",
+  "request-body",
+  "response-model",
+  "status-codes",
+  "handling-errors",
+  "dependencies",
+  "bigger-applications",
+  "settings",
+  "cors",
+  "testing",
+]
+read_first = "Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` and `src/schemas/items.py`."
 
 [[levels]]
 id = "domain"
@@ -152,7 +224,21 @@ label = "Domain"
 description = "One package per domain: router, service, repository."
 preset = "domain-starter"
 asks_database = true
-concepts = ["bigger-applications", "dependencies", "lifespan", "settings"]
+concepts = [
+  "first-steps",
+  "path-parameters",
+  "query-parameters",
+  "request-body",
+  "response-model",
+  "status-codes",
+  "handling-errors",
+  "dependencies",
+  "bigger-applications",
+  "settings",
+  "cors",
+  "testing",
+]
+read_first = "Read `src/app/main.py`, then `src/app/domains/items/`: `router.py`, `service.py` and `repository.py`."
 
 [[levels]]
 id = "production"
@@ -160,7 +246,30 @@ label = "Production"
 description = "domain plus PostgreSQL, Alembic, JWT, CI and Docker."
 preset = "domain-starter"
 asks_database = true
-concepts = ["bigger-applications", "dependencies", "sql-databases", "security-jwt", "deployment-docker"]
+concepts = [
+  "first-steps",
+  "path-parameters",
+  "query-parameters",
+  "request-body",
+  "response-model",
+  "status-codes",
+  "handling-errors",
+  "dependencies",
+  "bigger-applications",
+  "settings",
+  "cors",
+  "testing",
+  # Added by the bundle: the database, its SQL-backed /items API, JWT,
+  # structured logging and Docker.
+  "sql-databases",
+  "dependencies-with-yield",
+  "lifespan",
+  "async",
+  "security-jwt",
+  "middleware",
+  "deployment-docker",
+]
+read_first = "Read `src/app/main.py`, then `src/app/domains/items/`; README.md describes each selected feature."
 
 [levels.bundle]
 database = "PostgreSQL"
@@ -196,59 +305,100 @@ minimal = "single-module"
 # kind: "level" (reachable through a level), "example" (``--template`` only),
 # "internal" (bundled but not offered; no template uses it at the moment).
 # ``description`` equals the template README's first heading (tested).
+# ``read_first`` (required for "level" and "example") and ``extend`` are the
+# README / next-steps text; every path in backticks exists in the template
+# (tested). ``addroute = false``: next steps never suggest ``fastkit
+# addroute`` for the template. Example templates carry no concept comments
+# yet, so their ``concepts`` stay empty.
 [[templates]]
 id = "fastapi-hello"
 kind = "level"
 description = "Smallest FastAPI app: three endpoints, one model, their tests"
-concepts = ["first-steps", "path-parameters", "query-parameters", "request-body", "status-codes", "testing"]
+concepts = ["first-steps", "path-parameters", "query-parameters", "request-body", "response-model", "status-codes", "handling-errors", "testing"]
+read_first = "Read `main.py` from top to bottom: each comment links the FastAPI tutorial page that explains it."
+extend = "Add a resource by imitation: copy the `Item` models, `create_item`, `read_item` and their tests, and rename them for `/users`."
+addroute = false
 
 [[templates]]
 id = "fastapi-single-module"
 kind = "level"
 description = "FastAPI Single Module Template"
-concepts = ["response-model", "settings", "testing"]
+concepts = ["first-steps", "settings", "cors", "testing"]
+read_first = "Read `src/main.py`: the settings, the app and its routes in one module."
 
 [[templates]]
 id = "fastapi-default"
 kind = "level"
 description = "Simple FastAPI Project"
-concepts = ["bigger-applications", "dependencies", "response-model", "settings"]
+concepts = [
+  "first-steps",
+  "path-parameters",
+  "query-parameters",
+  "request-body",
+  "response-model",
+  "status-codes",
+  "handling-errors",
+  "dependencies",
+  "bigger-applications",
+  "settings",
+  "cors",
+  "testing",
+]
+read_first = "Read `src/main.py`, then `src/api/routes/items.py`, `src/crud/items.py` and `src/schemas/items.py`."
 
 [[templates]]
 id = "fastapi-domain-starter"
 kind = "level"
 description = "FastAPI Domain Starter"
-concepts = ["bigger-applications", "dependencies", "lifespan", "settings"]
+concepts = [
+  "first-steps",
+  "path-parameters",
+  "query-parameters",
+  "request-body",
+  "response-model",
+  "status-codes",
+  "handling-errors",
+  "dependencies",
+  "bigger-applications",
+  "settings",
+  "cors",
+  "testing",
+]
+read_first = "Read `src/app/main.py`, then `src/app/domains/items/`: `router.py`, `service.py` and `repository.py`."
 
 [[templates]]
 id = "fastapi-custom-response"
 kind = "example"
 description = "Async Item Management API with Custom Response System"
-concepts = ["response-model", "handling-errors", "async"]
+read_first = "Read `src/main.py`, then `src/helper/responses.py` and `src/api/routes/items.py` to see the response envelope."
 
 [[templates]]
 id = "fastapi-auth-jwt"
 kind = "example"
 description = "FastAPI JWT Authentication"
-concepts = ["security-jwt", "dependencies"]
+read_first = "Read `src/app/main.py`, then `src/app/domains/auth/` and `src/app/core/security.py`."
+addroute = false
 
 [[templates]]
 id = "fastapi-sqlmodel"
 kind = "example"
 description = "FastAPI SQLModel"
-concepts = ["sql-databases", "dependencies"]
+read_first = "Read `src/app/main.py`, then `src/app/domains/items/` and `src/app/db/session.py`; the README explains how to switch to PostgreSQL or MySQL."
+addroute = false
 
 [[templates]]
 id = "fastapi-mcp"
 kind = "example"
 description = "FastAPI MCP Project"
-concepts = ["security-jwt", "bigger-applications"]
+read_first = "Read `src/main.py`, then `src/mcp_server/router.py` and `src/auth/`."
+addroute = false
 
 [[templates]]
 id = "fastapi-llm-agent"
 kind = "example"
 description = "FastAPI LLM Agent"
-concepts = ["async", "settings"]
+read_first = "Read `src/app/main.py`, then `src/app/api/chat.py` and `src/app/llm/agent.py`."
+addroute = false
 
 # -------------------------------------------------------- package managers
 [[package_managers]]
@@ -283,7 +433,10 @@ description = "Python dependency management and packaging"
 # defaults depend on it). ``label`` defaults to the id. ``summary`` is the
 # text a prompt shows; options without one are shown with their packages.
 # ``runtime`` packages go to [project].dependencies / requirements.txt,
-# ``dev`` packages to the dev group / requirements-dev.txt.
+# ``dev`` packages to the dev group / requirements-dev.txt. ``guide`` is the
+# README section of a selected option (required unless the option is
+# ``none`` or ``built_in``); its link is the first concept's URL, else
+# ``docs`` (required for an option without a concept).
 # Package choices are based on recommendations from
 # https://github.com/mjhea0/awesome-fastapi
 [[axes]]
@@ -302,14 +455,16 @@ default = "None"
   # ``asyncio`` extra, and 2.0 skipped it on some platforms (macOS arm64).
   runtime = ["asyncpg", "sqlalchemy[asyncio]"]
   tags = ["sql"]
-  concepts = ["sql-databases"]
+  concepts = ["sql-databases", "dependencies-with-yield", "lifespan"]
+  guide = "Async SQLAlchemy engine with a request-scoped session (`SessionDep`) for PostgreSQL through asyncpg. Set `DATABASE_URL` in `.env`; `GET /ready` checks the connection."
 
   [[axes.options]]
   id = "MySQL"
   summary = "MySQL through async SQLAlchemy (aiomysql)"
-  runtime = ["aiomysql", "sqlalchemy[asyncio]"]
+  runtime = ["aiomysql[rsa]", "sqlalchemy[asyncio]"]
   tags = ["sql"]
-  concepts = ["sql-databases"]
+  concepts = ["sql-databases", "dependencies-with-yield", "lifespan"]
+  guide = "Async SQLAlchemy engine with a request-scoped session (`SessionDep`) for MySQL through aiomysql. Set `DATABASE_URL` in `.env`; `GET /ready` checks the connection."
 
   [[axes.options]]
   id = "MongoDB"
@@ -319,6 +474,9 @@ default = "None"
   # an older environment or constraint file from resolving to a release
   # without it (or with the beta API).
   runtime = ["pymongo>=4.13"]
+  concepts = ["lifespan"]
+  guide = "PyMongo's async client, opened and closed with the app. Set `MONGODB_URL` in `.env`; `GET /ready` pings the server."
+  docs = "https://pymongo.readthedocs.io/en/stable/"
 
   [[axes.options]]
   id = "Redis"
@@ -326,13 +484,17 @@ default = "None"
   # ``aioredis`` is abandoned (merged into redis-py) and does not install on
   # Python 3.12; redis[hiredis] ships the asyncio client.
   runtime = ["redis[hiredis]"]
+  concepts = ["lifespan"]
+  guide = "redis-py asyncio client (`redis_client`), closed with the app. Set `REDIS_URL` in `.env`."
+  docs = "https://redis.readthedocs.io/en/stable/"
 
   [[axes.options]]
   id = "SQLite"
   summary = "SQLite file through async SQLAlchemy (aiosqlite), no server needed"
   runtime = ["sqlalchemy[asyncio]", "aiosqlite"]
   tags = ["sql"]
-  concepts = ["sql-databases"]
+  concepts = ["sql-databases", "dependencies-with-yield", "lifespan"]
+  guide = "Async SQLAlchemy engine with a request-scoped session (`SessionDep`) for a SQLite file through aiosqlite; no server needed. `DATABASE_URL` in `.env` names the file."
 
   [[axes.options]]
   id = "None"
@@ -354,6 +516,7 @@ default = "None"
   # email-validator. PyJWT signs the tokens, pwdlib hashes (argon2).
   runtime = ["pyjwt[crypto]", "pwdlib[argon2]", "email-validator", "python-multipart"]
   concepts = ["security-jwt"]
+  guide = "OAuth2 password flow: `POST /api/v1/auth/token` returns a JWT signed with `SECRET_KEY`, and the `CurrentUser` dependency protects your endpoints."
 
   [[axes.options]]
   id = "OAuth2"
@@ -364,6 +527,7 @@ default = "None"
   # httpx2's errors, so httpx2 is what gets installed.
   runtime = ["authlib", "itsdangerous", "httpx2"]
   concepts = ["middleware"]
+  guide = "Login with Google or GitHub through Authlib. Set the `GOOGLE_*` or `GITHUB_*` credentials in `.env` to enable a provider."
 
   [[axes.options]]
   id = "FastAPI-Users"
@@ -372,12 +536,14 @@ default = "None"
   # PyJWT and python-multipart itself). SQL databases only.
   runtime = ["fastapi-users[sqlalchemy]>=15.0.5,<16"]
   concepts = ["security-jwt"]
+  guide = "Registration, login and user management from FastAPI-Users, stored in the SQL database."
 
   [[axes.options]]
   id = "Session-based"
   summary = "Traditional session-based authentication"
   runtime = ["itsdangerous", "pwdlib[argon2]", "email-validator"]
   concepts = ["middleware"]
+  guide = "Login sets a signed session cookie; logout ends every session of the account."
 
   [[axes.options]]
   id = "None"
@@ -396,11 +562,13 @@ default = "None"
   id = "Celery"
   runtime = ["celery[redis]", "redis[hiredis]"]
   concepts = ["background-tasks"]
+  guide = "A Celery worker and `/api/v1/tasks` endpoints that queue jobs on Redis; run the worker next to the API."
 
   [[axes.options]]
   id = "Dramatiq"
   runtime = ["dramatiq[redis]", "redis[hiredis]"]
   concepts = ["background-tasks"]
+  guide = "A Dramatiq worker and `/api/v1/tasks` endpoints that queue jobs on Redis; run the worker next to the API."
 
   [[axes.options]]
   id = "None"
@@ -423,18 +591,21 @@ default = "Coverage"
   # ASGITransport directly.
   dev = ["pytest", "pytest-asyncio", "httpx", "httpx2"]
   concepts = ["testing"]
+  guide = "pytest with a test module per feature (in-memory SQLite for SQL databases)."
 
   [[axes.options]]
   id = "Coverage"
   summary = "Basic + code coverage"
   dev = ["pytest", "pytest-asyncio", "pytest-cov", "httpx", "httpx2"]
   concepts = ["testing"]
+  guide = "pytest with a test module per feature (in-memory SQLite for SQL databases); `pytest --cov` reports coverage."
 
   [[axes.options]]
   id = "Advanced"
   summary = "Coverage + faker + factory-boy for fixtures"
   dev = ["pytest", "pytest-asyncio", "pytest-cov", "httpx", "httpx2", "faker", "factory-boy"]
   concepts = ["testing"]
+  guide = "pytest with a test module per feature (in-memory SQLite for SQL databases); `pytest --cov` reports coverage, and `tests/factories.py` holds faker and factory-boy factories."
 
   [[axes.options]]
   id = "None"
@@ -454,6 +625,8 @@ default = "None"
   # fastapi-cache2 imports starlette.templating at module scope, which
   # hard-requires jinja2; without it the app fails to import.
   runtime = ["redis[hiredis]", "fastapi-cache2", "jinja2"]
+  guide = "Response caching with fastapi-cache2 on Redis; the router under `/api/v1/cache` shows the decorator."
+  docs = "https://github.com/long2ice/fastapi-cache"
 
   [[axes.options]]
   id = "None"
@@ -471,6 +644,8 @@ default = "None"
   id = "Loguru"
   summary = "Enhanced logging with Loguru"
   runtime = ["loguru"]
+  guide = "Loguru takes over the application and Uvicorn log output."
+  docs = "https://loguru.readthedocs.io/en/stable/"
 
   [[axes.options]]
   id = "OpenTelemetry"
@@ -482,12 +657,14 @@ default = "None"
     "opentelemetry-exporter-otlp-proto-http",
   ]
   concepts = ["middleware"]
+  guide = "Traces every request and exports the spans over OTLP; set the exporter settings in `.env`."
 
   [[axes.options]]
   id = "Prometheus"
   summary = "Prometheus metrics instrumentation"
   runtime = ["prometheus-client", "prometheus-fastapi-instrumentator"]
-  concepts = ["middleware"]
+  guide = "Exposes request metrics at `/metrics`."
+  docs = "https://github.com/trallnag/prometheus-fastapi-instrumentator"
 
   [[axes.options]]
   id = "None"
@@ -518,6 +695,7 @@ default = "None"
   # where that works on Python 3.12 (older ones import ``pkg_resources``).
   runtime = ["limits>=3.4"]
   concepts = ["middleware"]
+  guide = "Per-client limits on every route (`RATE_LIMIT_DEFAULT`), stricter on the login endpoints when authentication is selected (`RATE_LIMIT_AUTH`); a client over its limit gets 429."
 
   [[axes.options]]
   id = "Pagination"
@@ -531,6 +709,7 @@ default = "None"
   summary = "Example WebSocket endpoint (websockets)"
   runtime = ["websockets"]
   concepts = ["websockets"]
+  guide = "A WebSocket endpoint at `/ws` and `GET /api/v1/connections`."
 
   [[axes.options]]
   id = "None"
@@ -550,7 +729,8 @@ default = "None"
   summary = "alembic.ini + async alembic/env.py + scripts/migrate.sh"
   # Runtime: the container's migrate script runs it.
   runtime = ["alembic"]
-  concepts = ["sql-databases"]
+  guide = "Alembic migrations in `alembic/`: `alembic upgrade head` creates the tables, `alembic revision --autogenerate -m \"add orders\"` records a model change."
+  docs = "https://alembic.sqlalchemy.org/en/latest/"
 
   [[axes.options]]
   id = "None"
@@ -569,26 +749,36 @@ default = "None"
   id = "ruff"
   summary = "ruff + ruff-format config in pyproject.toml (replaces black/isort)"
   dev = ["ruff"]
+  guide = "ruff lints and formats the code: `ruff check .` and `ruff format .`."
+  docs = "https://docs.astral.sh/ruff/"
 
   [[axes.options]]
   id = "pre-commit"
   summary = ".pre-commit-config.yaml"
   dev = ["pre-commit"]
+  guide = "Runs the checks before each commit once you run `pre-commit install`."
+  docs = "https://pre-commit.com/"
 
   [[axes.options]]
   id = "github-actions"
   # Workflow file only.
   summary = ".github/workflows/test.yml (Python 3.12)"
+  guide = "Runs the tests on pushes to `main` and on every pull request."
+  docs = "https://docs.github.com/en/actions"
 
   [[axes.options]]
   id = "devcontainer"
   # devcontainer.json only.
   summary = ".devcontainer/devcontainer.json"
+  guide = "Opens the project in a development container with the right Python."
+  docs = "https://containers.dev/"
 
   [[axes.options]]
   id = "makefile"
   # Makefile only.
   summary = "Makefile with install/test/lint/format/run"
+  guide = "Shortcuts: `make install`, `make test`, `make lint`, `make format`, `make run`."
+  docs = "https://www.gnu.org/software/make/manual/make.html"
 
   [[axes.options]]
   id = "None"
@@ -607,6 +797,7 @@ default = "None"
   summary = "JSON logs + X-Request-ID correlation middleware (stdlib only)"
   # Stdlib ``logging`` + ``json`` only; no third-party dependency.
   concepts = ["middleware"]
+  guide = "JSON log lines with an `X-Request-ID` per request (taken from the request or generated)."
 
   [[axes.options]]
   id = "None"
@@ -625,11 +816,15 @@ default = "None"
   id = "Docker"
   summary = "Generate Dockerfile"
   concepts = ["deployment-docker"]
+  #  is replaced with the project name (lower case: Docker
+  # image names are lower case).
+  guide = "Builds the app image (`docker build -t  .`); the container reads its settings from the environment, never from a copied `.env`."
 
   [[axes.options]]
   id = "docker-compose"
   summary = "Generate docker-compose.yml (includes Docker)"
   concepts = ["deployment-docker"]
+  guide = "`docker compose up --build` starts the app with its services."
 
   [[axes.options]]
   id = "None"
@@ -664,8 +859,10 @@ add = { deployment = ["Docker"] }
 id = "sqlite-for-tests"
 kind = "adds"
 # Generated tests run on in-memory SQLite (sqlite+aiosqlite://, set by the
-# root conftest.py), so PostgreSQL / MySQL projects with tests need aiosqlite.
-when = { testing = "*", database = ["PostgreSQL", "MySQL"] }
+# root conftest.py), and so do the template's own tests of a SQL-backed
+# /items API, also without a testing selection: PostgreSQL / MySQL projects
+# need aiosqlite.
+when = { database = ["PostgreSQL", "MySQL"] }
 dev = ["aiosqlite"]
 
 [[rules]]
diff --git a/src/fastapi_fastkit/catalog/export.py b/src/fastapi_fastkit/catalog/export.py
index 70d5b3a3..f0fa36ac 100644
--- a/src/fastapi_fastkit/catalog/export.py
+++ b/src/fastapi_fastkit/catalog/export.py
@@ -26,8 +26,8 @@ def catalog_to_dict(catalog: Catalog) -> dict[str, Any]:
     :param catalog: Catalog to export
     :return: Mapping with the keys ``schema_version``, ``fastkit_version``,
         ``lang``, ``defaults``, ``levels``, ``presets``, ``preset_aliases``,
-        ``templates``, ``package_managers``, ``axes``, ``rules`` and
-        ``concepts``
+        ``templates``, ``package_managers``, ``axes``, ``rules``,
+        ``concepts`` and ``guide``
     """
     # Imported here: the package ``__init__`` holds only the version string,
     # and the catalog must not import anything else from fastkit.
@@ -53,6 +53,8 @@ def catalog_to_dict(catalog: Catalog) -> dict[str, Any]:
                 "asks_database": level.asks_database,
                 "bundle": _values(level.bundle),
                 "concepts": list(level.concepts),
+                "read_first": level.read_first,
+                "extend": level.extend,
             }
             for level in catalog.levels
         ],
@@ -67,6 +69,9 @@ def catalog_to_dict(catalog: Catalog) -> dict[str, Any]:
                 "kind": template.kind,
                 "description": template.description,
                 "concepts": list(template.concepts),
+                "read_first": template.read_first,
+                "extend": template.extend,
+                "addroute": template.addroute,
             }
             for template in catalog.templates
         ],
@@ -97,6 +102,8 @@ def catalog_to_dict(catalog: Catalog) -> dict[str, Any]:
                         "concepts": list(option.concepts),
                         "none": option.none,
                         "built_in": option.built_in,
+                        "guide": option.guide,
+                        "docs": option.docs,
                     }
                     for option in axis.options
                 ],
@@ -120,6 +127,7 @@ def catalog_to_dict(catalog: Catalog) -> dict[str, Any]:
             {"id": concept.id, "title": concept.title, "url": concept.url}
             for concept in catalog.concepts
         ],
+        "guide": dict(catalog.guide),
     }
 
 
diff --git a/src/fastapi_fastkit/catalog/i18n.py b/src/fastapi_fastkit/catalog/i18n.py
index 0b2c418f..82601f1a 100644
--- a/src/fastapi_fastkit/catalog/i18n.py
+++ b/src/fastapi_fastkit/catalog/i18n.py
@@ -5,27 +5,34 @@
 # replace the text fields listed in ``_FIELDS``; a key the overlay leaves out
 # keeps its English text, and a key the base catalog does not have is an
 # error (no orphans). Ids, package names and URLs are never translated.
+# The ``[guide]`` table is flat (``key = "text"``); its placeholders must
+# match the English text.
 #
 # @author bnbong bbbong9@gmail.com
 # --------------------------------------------------------------------------
 import string
 from dataclasses import replace
+from types import MappingProxyType
 from typing import Any, Mapping, TypeVar
 
+from .loader import check_guide_text, guide_placeholders
 from .model import Axis, Catalog, CatalogError, Option
 from .rules import check_message
 
 #: Translatable fields per kind (the overlay's top-level tables).
 _FIELDS: dict[str, tuple[str, ...]] = {
-    "levels": ("label", "description"),
+    "levels": ("label", "description", "read_first", "extend"),
     "presets": ("summary",),
-    "templates": ("description",),
+    "templates": ("description", "read_first", "extend"),
     "package_managers": ("description",),
     "axes": ("label", "description"),
     "rules": ("message",),
     "concepts": ("title",),
 }
-_OPTION_FIELDS = ("label", "summary")
+_OPTION_FIELDS = ("label", "summary", "guide")
+
+#: The flat table of guide texts (``Catalog.guide``).
+_GUIDE = "guide"
 
 _T = TypeVar("_T")
 
@@ -58,7 +65,7 @@ def _text_fields(
 
 def _translated(item: _T, fields: dict[str, str], where: str) -> _T:
     for key in fields:
-        if getattr(item, key) is None:
+        if not getattr(item, key):
             raise CatalogError(
                 f"{where}.{key}: the base catalog has no English text to translate"
             )
@@ -80,6 +87,27 @@ def _overlay_options(axis: Axis, raw: Any, where: str) -> tuple[Option, ...]:
     return tuple(options)
 
 
+def _overlay_guide(catalog: Catalog, raw: Any, where: str) -> Mapping[str, str]:
+    if not isinstance(raw, Mapping):
+        raise CatalogError(f"{where}: expected a table")
+    guide = dict(catalog.guide)
+    for key, text in raw.items():
+        key_where = f"{where}.{key}"
+        if key not in guide:
+            raise CatalogError(f"{key_where}: unknown key")
+        if not isinstance(text, str) or not text:
+            raise CatalogError(f"{key_where}: must be a non-empty string")
+        check_guide_text(key, text, key_where)
+        english = guide_placeholders(guide[key], key_where)
+        if guide_placeholders(text, key_where) != english:
+            raise CatalogError(
+                f"{key_where}: placeholders must match the English text "
+                f"({', '.join(sorted(english)) or 'none'})"
+            )
+        guide[key] = text
+    return MappingProxyType(guide)
+
+
 def apply_overlay(catalog: Catalog, overlay: Mapping[str, Any], lang: str) -> Catalog:
     """
     Return ``catalog`` with the overlay's text applied (pure).
@@ -93,6 +121,9 @@ def apply_overlay(catalog: Catalog, overlay: Mapping[str, Any], lang: str) -> Ca
     """
     changes: dict[str, Any] = {"lang": lang}
     for kind, entries in overlay.items():
+        if kind == _GUIDE:
+            changes[_GUIDE] = _overlay_guide(catalog, entries, f"i18n/{lang}.guide")
+            continue
         if kind not in _FIELDS:
             raise CatalogError(f"i18n/{lang}: unknown table '{kind}'")
         if not isinstance(entries, Mapping):
@@ -129,22 +160,22 @@ def translatable_strings(catalog: Catalog) -> dict[str, Any]:
     """
     The overlay skeleton filled with the catalog's (English) text.
 
-    Covers every translatable field that has text: level labels and
-    descriptions, preset summaries, template and package-manager
-    descriptions, axis labels and descriptions, option summaries and the
-    labels of ``None`` options, rule messages and concept titles.
+    Covers every translatable field that has text: level labels,
+    descriptions and next-steps texts, preset summaries, template
+    descriptions and next-steps texts, package-manager descriptions, axis
+    labels and descriptions, option summaries, guide texts and the labels of
+    ``None`` options, rule messages, concept titles and the guide table.
 
     :param catalog: Catalog to read
-    :return: ``{kind: {id: {field: text}}}``; axes carry an ``options`` table
+    :return: ``{kind: {id: {field: text}}}``; axes carry an ``options``
+        table; ``guide`` is flat: ``{key: text}``
     """
     result: dict[str, Any] = {}
     for kind, fields in _FIELDS.items():
         entries: dict[str, Any] = {}
         for item in getattr(catalog, kind):
             values: dict[str, Any] = {
-                field: getattr(item, field)
-                for field in fields
-                if getattr(item, field) is not None
+                field: getattr(item, field) for field in fields if getattr(item, field)
             }
             if kind == "axes":
                 options: dict[str, Any] = {}
@@ -154,6 +185,8 @@ def translatable_strings(catalog: Catalog) -> dict[str, Any]:
                         texts["label"] = option.label
                     if option.summary is not None:
                         texts["summary"] = option.summary
+                    if option.guide is not None:
+                        texts["guide"] = option.guide
                     if texts:
                         options[option.id] = texts
                 if options:
@@ -161,4 +194,5 @@ def translatable_strings(catalog: Catalog) -> dict[str, Any]:
             if values:
                 entries[item.id] = values
         result[kind] = entries
+    result[_GUIDE] = dict(catalog.guide)
     return result
diff --git a/src/fastapi_fastkit/catalog/loader.py b/src/fastapi_fastkit/catalog/loader.py
index a1c6f41d..ab0ee5de 100644
--- a/src/fastapi_fastkit/catalog/loader.py
+++ b/src/fastapi_fastkit/catalog/loader.py
@@ -8,6 +8,7 @@
 #
 # @author bnbong bbbong9@gmail.com
 # --------------------------------------------------------------------------
+import string
 import tomllib
 from dataclasses import replace
 from functools import lru_cache
@@ -41,6 +42,54 @@
 #: Prefix every concept URL must start with (official FastAPI docs).
 CONCEPT_URL_PREFIX = "https://fastapi.tiangolo.com/"
 
+#: Prefix of an option's ``docs`` URL.
+DOCS_URL_PREFIX = "https://"
+
+#: Keys of the ``[guide]`` table and the placeholders each one may use.
+GUIDE_KEYS: Mapping[str, frozenset[str]] = MappingProxyType(
+    {
+        key: frozenset(placeholders)
+        for key, placeholders in {
+            "next_steps": (),
+            "open": (),
+            "install": (),
+            "install_pip": (),
+            "install_into_venv": (),
+            "activate": (),
+            "env": (),
+            "env_written": (),
+            "env_kept": (),
+            "services": ("services",),
+            "migrate": (),
+            "worker": (),
+            "run": (),
+            "run_readme_alternative": (),
+            "run_compose": (),
+            "test": (),
+            "extend_classic": (),
+            "extend_domain": (),
+            "needs_fastkit": (),
+            "next_level": (),
+            "items_sql": (),
+            "items_memory": (),
+            "items_file": (),
+            "tables_alembic": (),
+            "tables_startup": (),
+            "compose_urls": (),
+            "compose_migrate": (),
+            "compose_sqlite": (),
+            "read_single_file_split": (),
+            "read_layered_sql_items": (),
+            "single_file_split": (),
+            "files": (),
+            "settings": (),
+            "learn_more": (),
+            "selected_features": (),
+            "same_in_readme": (),
+        }.items()
+    }
+)
+
 _PACKAGE = "fastapi_fastkit.catalog"
 _CATALOG_FILE = "catalog.toml"
 _I18N_DIR = "i18n"
@@ -57,6 +106,7 @@
         "package_managers",
         "axes",
         "rules",
+        "guide",
     }
 )
 _RULE_KINDS = ("requires", "implies", "adds", "note")
@@ -197,11 +247,27 @@ def _build_option(table: _Table) -> Option:
         concepts=table.strings("concepts"),
         none=table.boolean("none", False),
         built_in=table.boolean("built_in", False),
+        guide=table.optional_string("guide"),
+        docs=table.optional_string("docs"),
     )
     table.finish()
     return option
 
 
+def _check_option_guide(option: Option, where: str) -> None:
+    """``guide`` on every offered option (none on ``none`` / ``built_in``
+    ones), and a ``docs`` URL where no concept gives the link."""
+    if option.none or option.built_in:
+        if option.guide is not None:
+            raise CatalogError(f"{where}: a none or built_in option takes no 'guide'")
+    elif option.guide is None:
+        raise CatalogError(f"{where}: missing required key 'guide'")
+    if option.docs is not None and not option.docs.startswith(DOCS_URL_PREFIX):
+        raise CatalogError(f"{where}: 'docs' must start with {DOCS_URL_PREFIX}")
+    if option.guide is not None and not option.concepts and option.docs is None:
+        raise CatalogError(f"{where}: an option without concepts needs a 'docs' URL")
+
+
 def _build_axis(table: _Table) -> Axis:
     axis_id = _with_id(table)
     label = table.string("label")
@@ -234,6 +300,7 @@ def _build_axis(table: _Table) -> Axis:
             raise CatalogError(
                 f"{table.where}: the none option '{option.id}' cannot add packages"
             )
+        _check_option_guide(option, f"{table.where} option '{option.id}'")
     return Axis(
         id=axis_id,
         label=label,
@@ -271,6 +338,8 @@ def _build_level(table: _Table) -> Level:
                     f"{bundle_table.where}.{key}: must be a string or a list of strings"
                 )
     concepts = table.strings("concepts")
+    read_first = table.string("read_first")
+    extend = table.optional_string("extend")
     table.finish()
     return Level(
         id=level_id,
@@ -281,6 +350,8 @@ def _build_level(table: _Table) -> Level:
         asks_database=asks_database,
         bundle=MappingProxyType(bundle),
         concepts=concepts,
+        read_first=read_first,
+        extend=extend,
     )
 
 
@@ -345,6 +416,57 @@ def _build_rule(table: _Table) -> Rule:
     )
 
 
+def guide_placeholders(text: str, where: str) -> set[str]:
+    """
+    The ``{name}`` placeholders of a guide text.
+
+    :raises CatalogError: If ``text`` is not a valid format string or uses a
+        positional, formatted or converted field
+    """
+    try:
+        parsed = list(string.Formatter().parse(text))
+    except ValueError as error:
+        raise CatalogError(f"{where}: not a valid format string ({error})") from error
+    names: set[str] = set()
+    for _, field, spec, conversion in parsed:
+        if field is None:
+            continue
+        if not field.isidentifier() or spec or conversion:
+            raise CatalogError(
+                f"{where}: placeholder '{{{field}}}' is not a plain name"
+            )
+        names.add(field)
+    return names
+
+
+def check_guide_text(key: str, text: str, where: str) -> None:
+    """
+    Check that the ``[guide]`` text of ``key`` (one of :data:`GUIDE_KEYS`)
+    uses only the placeholders allowed for it.
+
+    :raises CatalogError: For an unknown placeholder
+    """
+    unknown = sorted(guide_placeholders(text, where) - GUIDE_KEYS[key])
+    if unknown:
+        allowed = ", ".join(sorted(GUIDE_KEYS[key])) or "none"
+        raise CatalogError(
+            f"{where}: unknown placeholder(s) {', '.join(unknown)} "
+            f"(allowed: {allowed})"
+        )
+
+
+def _guide(table: "_Table") -> Mapping[str, str]:
+    """The ``[guide]`` table: every key of :data:`GUIDE_KEYS`, nothing else."""
+    for key in table.data:
+        if key not in GUIDE_KEYS:
+            raise CatalogError(f"{table.where}: unknown key '{key}'")
+    guide = {key: table.string(key) for key in GUIDE_KEYS}
+    table.finish()
+    for key, text in guide.items():
+        check_guide_text(key, text, f"{table.where}.{key}")
+    return MappingProxyType(guide)
+
+
 def _preset_aliases(table: "_Table | None") -> Mapping[str, str]:
     """The optional ``[preset_aliases]`` table: retired id -> preset id."""
     if table is None:
@@ -411,12 +533,21 @@ def _build(data: dict[str, Any], lang: str) -> Catalog:
             raise CatalogError(
                 f"{table.where}: 'kind' must be one of {', '.join(_TEMPLATE_KINDS)}"
             )
+        description = table.string("description")
+        template_concepts = table.strings("concepts")
+        if kind == "internal":
+            read_first = table.optional_string("read_first") or ""
+        else:
+            read_first = table.string("read_first")
         templates.append(
             Template(
                 id=template_id,
                 kind=kind,  # type: ignore[arg-type]
-                description=table.string("description"),
-                concepts=table.strings("concepts"),
+                description=description,
+                concepts=template_concepts,
+                read_first=read_first,
+                extend=table.optional_string("extend"),
+                addroute=table.boolean("addroute", True),
             )
         )
         table.finish()
@@ -435,6 +566,9 @@ def _build(data: dict[str, Any], lang: str) -> Catalog:
 
     axes = [_build_axis(table) for table in root.tables("axes")]
     rules = [_build_rule(table) for table in root.tables("rules")]
+    guide_table = root.table("guide", required=True)
+    assert guide_table is not None
+    guide = _guide(guide_table)
     root.finish()
 
     catalog = Catalog(
@@ -449,6 +583,7 @@ def _build(data: dict[str, Any], lang: str) -> Catalog:
         axes=tuple(axes),
         rules=tuple(rules),
         preset_aliases=preset_aliases,
+        guide=guide,
     )
     _check_references(catalog)
     return catalog
diff --git a/src/fastapi_fastkit/catalog/model.py b/src/fastapi_fastkit/catalog/model.py
index b06f065c..6a3b9f5a 100644
--- a/src/fastapi_fastkit/catalog/model.py
+++ b/src/fastapi_fastkit/catalog/model.py
@@ -64,6 +64,11 @@ class Option:
     concepts: tuple[str, ...]
     none: bool
     built_in: bool
+    #: README section text of a selected option (``None`` for ``none`` and
+    #: ``built_in`` options).
+    guide: str | None = None
+    #: Documentation URL for an option without a FastAPI concept.
+    docs: str | None = None
 
     @property
     def packages(self) -> tuple[str, ...]:
@@ -119,6 +124,11 @@ class Level:
     asks_database: bool
     bundle: Mapping[str, SelectionValue]
     concepts: tuple[str, ...]
+    #: Next-steps text naming the files to read first.
+    read_first: str = ""
+    #: Next-steps text on how to extend the project when ``fastkit
+    #: addroute`` does not apply (``None`` when there is none).
+    extend: str | None = None
 
 
 @dataclass(frozen=True, slots=True)
@@ -138,6 +148,12 @@ class Template:
     kind: Literal["level", "example", "internal"]
     description: str
     concepts: tuple[str, ...]
+    #: Next-steps text naming the files to read first ("" for ``internal``
+    #: templates that do not set it).
+    read_first: str = ""
+    extend: str | None = None
+    #: Whether next steps may suggest ``fastkit addroute`` for the template.
+    addroute: bool = True
 
 
 @dataclass(frozen=True, slots=True)
@@ -204,6 +220,8 @@ class Catalog:
     #: ``single-module``). Configs and project metadata written by older
     #: releases keep working through it.
     preset_aliases: Mapping[str, str]
+    #: Next-steps and README feature-section text by key (``[guide]``).
+    guide: Mapping[str, str]
 
     def axis(self, axis_id: str) -> Axis:
         """Return the axis with ``axis_id`` (``KeyError`` when unknown)."""
diff --git a/src/fastapi_fastkit/commands/common.py b/src/fastapi_fastkit/commands/common.py
index 94434dfb..fe41f02d 100644
--- a/src/fastapi_fastkit/commands/common.py
+++ b/src/fastapi_fastkit/commands/common.py
@@ -12,6 +12,7 @@
 import click
 from click import Context
 
+from fastapi_fastkit.backend.interactive.next_steps import render_next_steps
 from fastapi_fastkit.backend.main import get_deployment_success_message
 from fastapi_fastkit.backend.project_builder.config_schema import (
     ConfigSchemaError,
@@ -25,6 +26,8 @@
 )
 from fastapi_fastkit.catalog import load_catalog
 from fastapi_fastkit.core.settings import FastkitConfig
+from fastapi_fastkit.generation.guide import next_steps
+from fastapi_fastkit.generation.pipeline import README_FILE
 from fastapi_fastkit.generation.spec import (
     is_choice_config,
     is_template_name,
@@ -151,8 +154,8 @@ def scaffold(
         scripted callers can tell a failed run from a successful one. A user
         declining the in-place overwrite prompt is a cancel, not a failure,
         and keeps exit status 0.
-    :param report: Print the success message; a caller that reports the
-        result itself passes False.
+    :param report: Print the success message and the next steps; a caller
+        that reports the result itself passes False.
     :return: The scaffold result, or None when generation failed, was
         cancelled or was only previewed.
     """
@@ -185,9 +188,27 @@ def scaffold(
                 options.create_project_folder,
             )
         )
+        report_next_steps(result)
     return result
 
 
+def report_next_steps(result: ScaffoldResult) -> None:
+    """
+    Print the "Next steps" panel for a project a run created: true for that
+    run (folder, virtualenv, ``.env``) and the current OS.
+
+    :param result: A real run's result; a preview has nothing to report
+    """
+    if result.generation is None or result.environment is None:
+        return
+    environment = result.environment
+    render_next_steps(
+        next_steps(result.generation.facts, environment),
+        windows=environment.windows,
+        readme=README_FILE in result.generation.files,
+    )
+
+
 def load_config_file(
     path: str, overrides: Optional[Mapping[str, Optional[str]]] = None
 ) -> Optional[Dict[str, Any]]:
diff --git a/src/fastapi_fastkit/commands/init.py b/src/fastapi_fastkit/commands/init.py
index 5efcf890..e6d3d356 100644
--- a/src/fastapi_fastkit/commands/init.py
+++ b/src/fastapi_fastkit/commands/init.py
@@ -37,6 +37,7 @@
 from fastapi_fastkit.commands import defaults
 from fastapi_fastkit.commands.common import (
     load_config_file,
+    report_next_steps,
     scaffold,
     validate_template_name,
 )
@@ -376,7 +377,8 @@ def _report_created(
     new_folder: bool,
 ) -> None:
     """
-    What ``init`` prints after a project was created.
+    What ``init`` prints after a project was created: the success message
+    and the next steps.
 
     :param choice: The level or template choice (None for a 1.x config)
     :param result: What the scaffolder produced
@@ -389,9 +391,7 @@ def _report_created(
             result.template, project_name, workspace, new_folder
         )
     )
-    print_info(
-        "To start your project, run 'fastkit runserver' at newly created FastAPI project directory"
-    )
+    report_next_steps(result)
 
 
 def _create(
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl
index 6becb5c6..4819e884 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl
@@ -31,6 +31,8 @@ Pick this template when your API needs real accounts on day one:
 If you don't need authentication, start with `fastapi-domain-starter`. If you want
 database-backed CRUD without auth, use `fastapi-sqlmodel`.
 
+
+
 ## Project structure
 
 ```
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl
index 48e80053..913439c5 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl
@@ -2,6 +2,8 @@
 
 A FastAPI-based REST API demonstrating asynchronous processing and standardized response handling.
 
+
+
 ## Tech Stack
 
 - Python 3.12+
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl
index 76b7ee63..78221696 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl
@@ -2,6 +2,8 @@
 
 Simple CRUD API application using FastAPI
 
+
+
 ## Tech Stack
 
 - Python 3.12+
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/api.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/api.py-tpl
index 610135e0..b8436b07 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/api.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/api.py-tpl
@@ -7,6 +7,8 @@ from src.api.routes import items
 
 # fastkit:imports
 
+# One APIRouter collects the routers of every module; main.py mounts it once.
+# https://fastapi.tiangolo.com/tutorial/bigger-applications/
 api_router = APIRouter()
 api_router.include_router(items.router)
 # fastkit:routes
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/deps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/deps.py-tpl
index 39c53bdb..9e27b4df 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/deps.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/deps.py-tpl
@@ -13,4 +13,6 @@ def get_item_store() -> ItemStore:
     return item_store
 
 
+# An endpoint that declares `store: ItemStoreDep` gets what get_item_store() returns.
+# https://fastapi.tiangolo.com/tutorial/dependencies/
 ItemStoreDep = Annotated[ItemStore, Depends(get_item_store)]
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/routes/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/routes/items.py-tpl
index 04bd9605..074afe30 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/routes/items.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/routes/items.py-tpl
@@ -11,13 +11,19 @@ from src.schemas.items import ItemCreate, ItemRead, ItemUpdate
 router = APIRouter(prefix="/items", tags=["items"])
 
 
+# Endpoints raise this HTTPException to answer 404 with a JSON `detail` message.
+# https://fastapi.tiangolo.com/tutorial/handling-errors/
 def item_not_found() -> HTTPException:
     return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
 
 
+# The return annotation `Page[ItemRead]` is the response model: it shapes the JSON.
+# https://fastapi.tiangolo.com/tutorial/response-model/
 @router.get("")
 def list_items(
     store: ItemStoreDep,
+    # Arguments that are not in the path are query parameters: ?limit=20&offset=0
+    # https://fastapi.tiangolo.com/tutorial/query-params/
     limit: LimitParam = DEFAULT_LIMIT,
     offset: OffsetParam = 0,
 ) -> Page[ItemRead]:
@@ -30,6 +36,8 @@ def list_items(
     )
 
 
+# `{item_id}` in the path arrives as the `item_id` argument, converted to `int`.
+# https://fastapi.tiangolo.com/tutorial/path-params/
 @router.get("/{item_id}", responses=error_responses(404))
 def get_item(item_id: int, store: ItemStoreDep) -> ItemRead:
     item = store.get(item_id)
@@ -38,6 +46,8 @@ def get_item(item_id: int, store: ItemStoreDep) -> ItemRead:
     return ItemRead.model_validate(item)
 
 
+# `status_code` sets the status of a successful response: 201 Created.
+# https://fastapi.tiangolo.com/tutorial/response-status-code/
 @router.post("", status_code=status.HTTP_201_CREATED)
 def create_item(
     payload: ItemCreate, request: Request, response: Response, store: ItemStoreDep
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl
index ca0f5a58..6ed2d350 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl
@@ -61,6 +61,8 @@ _GENERATE_KEY_HINT = (
 )
 
 
+# BaseSettings fills each field from an environment variable or .env, else its default.
+# https://fastapi.tiangolo.com/advanced/settings/
 class Settings(BaseSettings):
     model_config = SettingsConfigDict(
         env_file=".env",
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/main.py-tpl
index e9aa39f5..35c3ba00 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/main.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/main.py-tpl
@@ -10,6 +10,8 @@ from src.core.config import settings
 
 # fastkit:imports
 
+# `app` is the FastAPI application that uvicorn serves: `uvicorn src.main:app`.
+# https://fastapi.tiangolo.com/tutorial/first-steps/
 app = FastAPI(
     title=settings.PROJECT_NAME,
 )
@@ -17,6 +19,8 @@ app = FastAPI(
 # Origins come only from BACKEND_CORS_ORIGINS; with none configured the
 # middleware is not installed at all.
 if settings.all_cors_origins:
+    # CORSMiddleware lets web pages from the listed origins call this API.
+    # https://fastapi.tiangolo.com/tutorial/cors/
     app.add_middleware(
         CORSMiddleware,
         allow_origins=settings.all_cors_origins,
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/schemas/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/schemas/items.py-tpl
index 13cc7fb8..908c903d 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/schemas/items.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/schemas/items.py-tpl
@@ -11,6 +11,8 @@ class ItemBase(BaseModel):
     category: str = Field(min_length=1, max_length=50)
 
 
+# The POST and PUT endpoints read and validate their JSON body with this model.
+# https://fastapi.tiangolo.com/tutorial/body/
 class ItemCreate(ItemBase):
     """POST and PUT body: every required field must be sent."""
 
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl
index f3a01a4a..4bec102b 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl
@@ -32,6 +32,8 @@ def store(tmp_path: Path) -> ItemStore:
 @pytest.fixture
 def client(store: ItemStore) -> Generator[TestClient, None, None]:
     app.dependency_overrides[get_item_store] = lambda: store
+    # TestClient sends requests straight to the app, without starting a server.
+    # https://fastapi.tiangolo.com/tutorial/testing/
     with TestClient(app) as c:
         yield c
     app.dependency_overrides.clear()
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl
index 4ae764ad..081943fd 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl
@@ -21,8 +21,12 @@ Pick this template when you want:
   `/health` probe, and paginated list endpoints.
 
 If you only need a quick CRUD demo, start with `fastapi-default`. If you
-need a database, start with `fastapi-sqlmodel`. If you want a single-file
-sandbox, use `fastapi-single-module`.
+need a database, `fastkit init --level domain --database PostgreSQL` (or
+MySQL, SQLite) stores the example items in it; `fastapi-sqlmodel` shows
+the same with SQLModel. If you want a single-file sandbox, use
+`fastapi-single-module`.
+
+
 
 ## Project structure
 
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/router.py-tpl
index 094d534a..e1775079 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/router.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/router.py-tpl
@@ -10,6 +10,8 @@ from src.app.domains.items import router as items_router
 
 # fastkit:imports
 
+# One APIRouter collects every domain's router; main.py mounts it under the prefix.
+# https://fastapi.tiangolo.com/tutorial/bigger-applications/
 api_router = APIRouter()
 api_router.include_router(items_router.router)
 # fastkit:routes
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl
index 4d470462..9a3c18f6 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl
@@ -44,6 +44,8 @@ _GENERATE_KEY_HINT = (
 )
 
 
+# BaseSettings fills each field from an environment variable or .env, else its default.
+# https://fastapi.tiangolo.com/advanced/settings/
 class Settings(BaseSettings):
     """Centralized configuration for the application.
 
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl
index 279a3b67..8116baeb 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl
@@ -21,16 +21,24 @@ def get_item_service() -> ItemService:
     return ItemService()
 
 
+# An endpoint that declares `service: ItemServiceDep` gets get_item_service()'s result.
+# https://fastapi.tiangolo.com/tutorial/dependencies/
 ItemServiceDep = Annotated[ItemService, Depends(get_item_service)]
 
 
+# Endpoints raise this HTTPException to answer 404 with a JSON `detail` message.
+# https://fastapi.tiangolo.com/tutorial/handling-errors/
 def _not_found(exc: ItemNotFoundError) -> HTTPException:
     return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
 
 
+# The return annotation `Page[ItemRead]` is the response model: it shapes the JSON.
+# https://fastapi.tiangolo.com/tutorial/response-model/
 @router.get("")
 def list_items(
     service: ItemServiceDep,
+    # Arguments that are not in the path are query parameters: ?limit=20&offset=0
+    # https://fastapi.tiangolo.com/tutorial/query-params/
     limit: LimitParam = DEFAULT_LIMIT,
     offset: OffsetParam = 0,
 ) -> Page[ItemRead]:
@@ -43,6 +51,8 @@ def list_items(
     )
 
 
+# `{item_id}` in the path arrives as the `item_id` argument, converted to `int`.
+# https://fastapi.tiangolo.com/tutorial/path-params/
 @router.get("/{item_id}", responses=error_responses(404))
 def get_item(item_id: int, service: ItemServiceDep) -> ItemRead:
     try:
@@ -51,6 +61,8 @@ def get_item(item_id: int, service: ItemServiceDep) -> ItemRead:
         raise _not_found(exc) from exc
 
 
+# `status_code` sets the status of a successful response: 201 Created.
+# https://fastapi.tiangolo.com/tutorial/response-status-code/
 @router.post("", status_code=status.HTTP_201_CREATED)
 def create_item(
     payload: ItemCreate,
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/schemas.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/schemas.py-tpl
index 820fc1f6..7494e43c 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/schemas.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/schemas.py-tpl
@@ -4,6 +4,8 @@
 from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator
 
 
+# The POST and PUT endpoints read and validate their JSON body with this model.
+# https://fastapi.tiangolo.com/tutorial/body/
 class ItemCreate(BaseModel):
     """Payload accepted on POST /items and PUT /items/{item_id}."""
 
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/main.py-tpl
index 99f8906f..109fef2a 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/main.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/main.py-tpl
@@ -10,6 +10,8 @@ from src.app.core.config import settings
 
 # fastkit:imports
 
+# `app` is the FastAPI application that uvicorn serves: `uvicorn src.app.main:app`.
+# https://fastapi.tiangolo.com/tutorial/first-steps/
 app = FastAPI(
     title=settings.PROJECT_NAME,
     description="",
@@ -17,6 +19,8 @@ app = FastAPI(
 )
 
 if settings.all_cors_origins:
+    # CORSMiddleware lets web pages from the listed origins call this API.
+    # https://fastapi.tiangolo.com/tutorial/cors/
     app.add_middleware(
         CORSMiddleware,
         allow_origins=settings.all_cors_origins,
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl
index 21a2be70..42665e56 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl
@@ -35,5 +35,7 @@ def reset_domain_stores() -> Generator[None, None, None]:
 
 @pytest.fixture
 def client() -> Generator[TestClient, None, None]:
+    # TestClient sends requests straight to the app, without starting a server.
+    # https://fastapi.tiangolo.com/tutorial/testing/
     with TestClient(app) as c:
         yield c
diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-hello/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-hello/README.md-tpl
index 9d0bc356..84e17cc8 100644
--- a/src/fastapi_fastkit/fastapi_project_template/fastapi-hello/README.md-tpl
+++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-hello/README.md-tpl
@@ -14,6 +14,8 @@ FastAPI tutorial page that explains it.
 
 Items are kept in memory, so they disappear when the server restarts.
 
+
+
 ## Structure
 ```
 .
@@ -48,15 +50,6 @@ pytest
 fastkit installs the test tools into the project's virtual environment. If you manage the
 environment yourself, install them with `pip install -r requirements-dev.txt`.
 
-## Next steps
-1. Add a resource by imitation: copy the item models, the `items` store, `create_item` and
-   `read_item` in `main.py`, rename them for users (`/users`, `/users/{user_id}`), and copy
-   their tests in `tests/test_main.py`. Run `pytest` and open `/docs` to see them.
-2. When one file starts to feel crowded, generate a larger starter with `fastkit init` (choose a
-   later level) or `fastkit init --template