Files
apf_portal/CLAUDE.md
T
julien 883c5151de
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m20s
CI / check (push) Successful in 4m2s
CI / a11y (push) Successful in 1m23s
CI / perf (push) Successful in 6m0s
Docs site / build (push) Successful in 2m56s
feat(portal-bff): ai-bridge controller — SSE chat + JSON rag/models (#196)
## Summary

Step 3 of the AI-relay chantier (after #194 ADR and #195 client skeleton). Wires the BFF-side **live surface** that the SPA's future chatbot widget will consume. [ADR-0024](docs/decisions/0024-ai-service-relay-grpc-sse-bridge.md) is promoted from `proposed` to `accepted` in the same change.

Three end-user routes under `/api/ai/*`, gated by the active portal session (no `@RequireAdmin` — AI is a regular-user surface):

| Route | Verb | Wire | Maps to |
|---|---|---|---|
| `/api/ai/chat` | `POST` | `text/event-stream` | `apf.ai.v1.ChatService.Chat` (server-stream) |
| `/api/ai/rag/search` | `GET` | `application/json` | `apf.ai.v1.RagService.Search` (unary) |
| `/api/ai/models` | `GET` | `application/json` | `apf.ai.v1.ModelsService.ListModels` (unary) |

CSRF and session validation are delegated to the global middleware mounted in `main.ts` (per [ADR-0009](docs/decisions/0009-auth-flow-oidc-pkce-msal-node.md) and [ADR-0021](docs/decisions/0021-phase-2-security-baseline.md)); the controller asserts `req.session.user` and emits 401 if absent.

## What lands

### `apps/portal-bff/src/grpc/ai-bridge/`

```
ai-bridge/
├── ai-bridge.module.ts         imports AiClientModule, exports the controller
├── ai-bridge.controller.ts     3 routes — POST chat (SSE), GET rag/search, GET models
├── sse.writer.ts               ChatEvent oneof → SSE frame translator
├── sse.writer.spec.ts          unit tests for the codec
├── ai-bridge.controller.spec.ts  end-to-end against an in-process fake gRPC server
└── dto/
    ├── chat-request.dto.ts     class-validator body shape (POST /chat)
    └── rag-search-query.dto.ts class-validator query shape (GET /rag/search)
```

### SSE codec (`sse.writer.ts`)

Each `ChatEvent` oneof case becomes one SSE frame with a kebab-case `event:` name and a JSON-encoded `data:` payload:

```
event: token
data: {"token":"…","value":"…"}

event: agent-step
data: {"agent":"…","step":"…","stepId":"…"}

event: tool-call
data: {"callId":"…","name":"…","args":{…}}

event: done
data: {"stats":{"tokensIn":…,"tokensOut":…,"chunksRetrieved":…}}
```

A helper `relayErrorFrame(code, message, retriable)` synthesises a relay-side `event: error` frame that matches the AI service's own `ErrorEvent` shape — the SPA's renderer needs no second code path for relay-level failures vs upstream model errors. gRPC status codes map into the `urn:apf-ai:*` namespace (`UNAVAILABLE` → `urn:apf-ai:unavailable`, `DEADLINE_EXCEEDED` → `urn:apf-ai:timeout`, `PERMISSION_DENIED` → `urn:apf-ai:permission_denied`, `RESOURCE_EXHAUSTED` → `urn:apf-ai:rate_limited`, `INVALID_ARGUMENT` → `urn:apf-ai:invalid_argument`, anything else → `urn:apf-ai:relay_error`).

The terminal `done` frame closes the stream — no `[DONE]` sentinel, per ADR-0024.

### Controller (`ai-bridge.controller.ts`)

- `POST /api/ai/chat` — builds an `apf.ai.v1.ChatRequest` from the validated DTO + session-derived Principal, calls `ChatClient.chat()`, drains the `ClientReadableStream<ChatEvent>` into SSE frames written on the raw Express `Response`. `req.on('close', …)` propagates browser disconnect through an `AbortController` into `call.cancel()` so the upstream LLM stops (per `apf-ai-service/docs/streaming.md`).
- `GET /api/ai/rag/search` — unary RAG call. `topK` defaults to 0 (server picks the default). `source` and `documentId` query params surface the same filter fields the upstream RPC accepts.
- `GET /api/ai/models` — unary lookup of the provider catalogue.

The SSE writes happen on the raw Express response (manual `setHeader` + `flushHeaders` + `write` + `end`) rather than through NestJS's `@Sse()` decorator, because `@Sse()` is GET-only and the chat endpoint is POST (the SPA carries the conversation history in the body).

### Lifecycle hooks

`AiClientModule` now implements `OnApplicationShutdown` and closes the four gRPC stubs (Chat / Rag / Ingestion / Models). The four stubs share the same HTTP/2 channel (gRPC-js dedups on `endpoint + credentials`), so the `close()` calls are cheap, but kept explicit so adding a fifth stub later is an obvious one-line addition. `main.ts` now calls `app.enableShutdownHooks()` so `SIGTERM` / `SIGINT` / `SIGHUP` actually route through the lifecycle interface.

### DTOs

`ChatRequestDto` constrains:
- `messages` — 1 to 64 entries; each has `role ∈ {user, assistant, system}` (no `tool` — tool messages are constructed BFF-side per ADR-0024 §"Tool-dispatch contract") and `content` ≤ 16 KB.
- `conversationId`, `model`, `provider` — optional, ≤ 64 / 128 chars.

`RagSearchQueryDto`:
- `query` — required, non-empty.
- `topK` — optional, integer in `[1, 50]` (the AI service has its own cap; the BFF rejects out-of-range values early).
- `source` / `documentId` — optional pass-through filters.

### Documentation

- ADR-0024 frontmatter: `status: proposed` → `accepted`.
- `docs/decisions/README.md` index reflects the new status.
- `CLAUDE.md` Architecture section grows an "AI service relay" bullet; the roll-up line moves from "ADRs 0001 → 0023" to "0001 → 0024"; the shipped-on-main list grows an "AI relay surface" entry.
- `apps/portal-bff/.env.example` documents `AI_SERVICE_GRPC_ENDPOINT` / `AI_SERVICE_CLIENT_ID` / `AI_SERVICE_GRPC_TLS` and points operators at `apf-ai-service`'s own docker-compose for the runtime dependency.

## Notes for the reviewer

- **No live AI service in this PR's local-dev stack.** `apf-ai-service` runs from its own repo (`/home/jgautier/Works/apf-ai-service`) with its own `infra/docker-compose.yml`. The BFF dials `localhost:8080` by default — the host-published port of the AI service's container. This is option (a) from ADR-0024 §"Open question — Compose orchestration": two independent stacks, dial across via host networking. Merging the compose files into one would couple two release cadences without operational payoff.
- **Tests run against an in-process fake `grpc.Server`.** All five spec cases on the controller wire it up against a fake `ChatService` + `RagService` + `ModelsService` server bound to `127.0.0.1:0` (random port). No mocks — the controller's gRPC client makes a real connection, real serialisation, real cancellation propagation. Cost: ~0.5 s overhead from the gRPC server setup.
- **CSRF + session middleware are unchanged.** The new POST endpoint is protected by the existing double-submit CSRF middleware mounted in `main.ts` (per [ADR-0021](docs/decisions/0021-phase-2-security-baseline.md)). The SPA's fetch call needs to send the `X-CSRF-Token` header matching the `__Host-portal_csrf` cookie — same protocol as every other POST in the BFF. No per-controller wiring required.
- **Manual session check rather than a guard.** Three reasons: (1) matches the existing pattern in `me.controller.ts`; (2) the session check is the only authorization gate (no roles to evaluate) — a guard would add ceremony without payoff; (3) the SSE controller already takes control of the response object (`@Res()`), which `UseGuards` interacts with awkwardly. Throwing `UnauthorizedException` lets `StructuredErrorFilter` produce the 401 envelope before any header is flushed.
- **Why the controller does NOT use `@Sse()`.** NestJS's `@Sse()` decorator is GET-only and emits frames from `Observable<MessageEvent>`. The chat endpoint is POST (the SPA sends conversation history in the body) and the source is a Node `Readable` stream from `@grpc/grpc-js`. Manual response handling is simpler than adapting to / from `Observable` for a single consumer.
- **Cancellation contract.** When the SPA aborts the fetch, the browser closes the TCP connection, Express emits `'close'` on the request, the controller's `AbortController.abort()` triggers, `ChatClient` calls `.cancel()` on the gRPC stream, the AI service's `ServerCallContext.CancellationToken` cancels the upstream LLM. The spec covers the `'close'` → server-side `cancelled` event end-to-end.
- **No ingestion route in the BFF.** Per ADR-0024 §"Out of scope", v1 admin ingestion uses the `apf-ai-service/tools/Apf.Ai.Ingest/` CLI. A future PR adds the BFF endpoint when the admin "manage AI corpus" surface ships. `IngestionClient` remains in `AiClientModule` so that future PR is one new file, not a new module plus a new client.
- **No bundle-size or perf surprise.** The BFF is a Node process, not a SPA chunk — bundle budgets don't apply. The gRPC channel is opened lazily on first call; idle BFFs incur no upstream TCP cost.

## Test plan

- [x] `pnpm nx test portal-bff` — **461 specs pass** (was 443; +13 new: 8 SSE writer cases + 5 controller end-to-end cases against the in-process fake server). Worker-exit-leak warning persists from the gRPC server's slow shutdown — pre-existing pattern from PR #195; harmless.
- [x] `pnpm nx lint portal-bff` — 6 pre-existing warnings, no new ones from the diff.
- [x] `pnpm nx build portal-bff` — clean webpack compile.
- [x] Module wiring: `AppModule` imports `AiBridgeModule`, which imports `AiClientModule`. Resolves cleanly through DI; the audit-side `HashUserIdService` is satisfied by `AiClientModule`'s local provider (per the rationale recorded in PR #195's `AiClientModule` docstring).
- [ ] **Manual smoke** — bring up `apf-ai-service` from its own repo (`cd ../apf-ai-service && docker compose -f infra/docker-compose.yml up`), set `AI_SERVICE_GRPC_ENDPOINT=localhost:8080` in `apps/portal-bff/.env`, run `pnpm nx serve portal-bff`. Sign in to `portal-shell`, then in a terminal:
  ```bash
  curl --cookie-jar /tmp/portal-session http://localhost:3000/api/auth/login    # follow Entra…
  curl -N \
       -H 'Content-Type: application/json' \
       -H 'X-CSRF-Token: <copied from cookie>' \
       --cookie /tmp/portal-session \
       -d '{"messages":[{"role":"user","content":"hello"}]}' \
       http://localhost:3000/api/ai/chat
  ```
  Expect a streamed SSE response terminated by an `event: done` frame. Verify `GET /api/ai/rag/search?query=test` returns a JSON response. Verify `GET /api/ai/models` lists the configured providers.

## What's next

1. **PR (frontend chantier)** — chatbot widget on `portal-shell` consuming the SSE endpoint. Will use `fetch` + `ReadableStream` parsing (not native `EventSource`, since POST is needed). Drag / fullscreen / suggestion UX carries forward from the stargate POC's `ChatbotWidget.tsx`.
2. **PR (post-v1)** — proto-drift CI gate that diffs `proto/apf-ai/` against an upstream tag of `apf-ai-service`.
3. **Coordinated amendment** — when the first production deployment is in scope, both repos record the same prod-hardening choice (signed `Principal` envelope vs mTLS) on the same date.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #196
2026-05-19 22:39:35 +02:00

19 KiB
Raw Blame History

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project rules (durable)

These constraints were set by the project lead at kickoff. They apply to every change.

  • Scale & quality bar. Treat this as a large-scale portal for a sizable organization, not a prototype. No bricolage, no exotic stacks. Default to stable, recognized, battle-tested choices. Cutting-edge / "à la pointe" alternatives must always be evaluated alongside the stable option, but are only adopted when the trade-off is captured in an ADR (drivers, risk, exit strategy). Pre-1.0 dependencies and one-maintainer projects are rejected unless an ADR justifies the exception.
  • Security, performance, accessibility. All three are first-class concerns from day one — never bolted on. Architecture, dependency, and feature decisions must explicitly consider their impact on these axes and document the trade-offs.
  • Project name. Currently apf_portal, provisional. Do not hardcode it outside repo/workspace-level metadata so a rename stays a one-line change.
  • Language. All code, identifiers, comments, documentation, commit messages, and PR descriptions are written in English. (Conversation with the project lead happens in French — but artifacts shipped in the repo are English-only.)
  • Commits / PRs. Never add a Co-Authored-By: Claude trailer or a 🤖 Generated with Claude Code footer to commits or PR bodies.
  • Be a peer, not a typist. Challenge requests when a better approach exists; surface trade-offs frankly. Don't silently execute a suboptimal directive — propose, then execute the agreed plan.

Documentation

  • All documentation lives in .md files under docs/, indexed by docs/README.md. The index is maintained automatically whenever a doc is added, renamed, or removed — no need to be asked.
  • Documentation is written proactively whenever it is genuinely useful (architecture, runbooks, onboarding, security/perf/a11y rationales). It is not created for trivial things just to tick a box.
  • The folder notes/ is the project lead's personal scratchpad — git-ignored and not part of project artifacts. Never write project documentation there.

Architectural Decision Records (ADRs)

  • Format: MADR 4.0.0 (https://adr.github.io/, https://github.com/adr/madr). Template at docs/decisions/template.md.
  • Location: flat folder docs/decisions/, indexed by docs/decisions/README.md.
  • Filename convention: NNNN-kebab-title.md with globally sequential 4-digit numbers. Numbers are never reset and never reused — even when an ADR is superseded or deprecated.
  • Categorization: via the tags: array in the MADR frontmatter (e.g. [frontend, security]). The canonical tag vocabulary lives in docs/decisions/README.md; never invent ad-hoc tags inline.
  • Proactivity. Any non-trivial development decision (tool/library choice, framework pattern, security control, perf budget, a11y target, naming convention, deprecation, breaking change) warrants proposing an ADR before implementation. Don't wait to be asked. Update the index in the same change.

Architecture (recorded in ADRs)

The structural, security, observability, and quality choices are recorded as ADRs and summarized below. Any change to these requires updating the corresponding ADR.

  • Workspace: Nx monorepo with the apps preset, managed by pnpm — see ADR-0002.
  • Naming: workspace apf-portal; apps portal-shell (end-user SPA), portal-admin (admin SPA, skeleton in place — see ADR-0020), and portal-bff (backend); libs feature-<name> and shared-<scope> — see ADR-0003.
  • Frontend (portal-shell): Angular at the latest LTS major — standalone APIs, zoneless change detection, Signals, CSR only (no SSR), Vitest, SCSS — see ADR-0004.
  • Backend (portal-bff): NestJS at the latest stable major, mounted on the Express adapter (Fastify adapter swappable later) — see ADR-0005.
  • Persistence: PostgreSQL (latest stable major) via Prisma — see ADR-0006.
  • Sessions: opaque session id in __Host-portal_session, payload in self-hosted Redis (Sentinel HA in prod, single node in dev), tokens encrypted at rest with AES-256-GCM, idle 30 min sliding + absolute 12 h — see ADR-0010.
  • MFA: enforced by Entra ID Conditional Access (org-side policy, P1 licensing required); BFF sanity-checks the amr claim at session creation; @RequireMfa() decorator and freshness-based step-up are designed-in for future sensitive routes (no v1 consumer) — see ADR-0011.
  • Identity: multi-tenant Microsoft Entra ID with B2B invitation for workforce in v1, dual-audience design ready for future External ID activation — see ADR-0008.
  • Authentication flow: OIDC Authorization Code + PKCE via @azure/msal-node, executed entirely on the BFF; SPA never holds tokens; __Host- prefixed cookies, double-submit CSRF, RP-initiated logout — see ADR-0009.
  • Observability: Pino + nestjs-pino for structured JSON logs, OpenTelemetry SDK + auto-instrumentations for traces, W3C Trace Context propagation across SPA → BFF → DB → Redis, nestjs-cls for request-scoped context (trace_id, session_id, user_id_hash, audience), 100 % sampling at the app with tail sampling deferred to the OTel Collector, stdout + OTLP shipping — see ADR-0012.
  • Audit trail: dedicated audit.events schema in the same Postgres instance, append-only by Postgres role grants (audit_writer INSERT, audit_reader SELECT, audit_archiver DELETE older than retention; no UPDATE/TRUNCATE to anyone); 365-day retention default; cross-referenced with app logs via trace_id and actor_id_hash (same salt); blocking writes (no audit ⇒ no action) — see ADR-0013.
  • Downstream API access: unified DownstreamApiClient (@nestjs/axios + cockatiel), per-service DownstreamApiConfig; default auth strategy is OBO via MSAL Node for Entra-protected APIs (downstream-scoped tokens cached in Redis with AES-256-GCM under a dedicated key); fallback strategy is service credential + signed X-User-Assertion JWT (BFF JWKS at /.well-known/jwks.json); per-call audience pre-check; no axios/fetch outside src/downstream/ — see ADR-0014.
  • CI/CD: Gitea Actions (level-2 implementation; will be superseded by a GitLab migration ADR within 6-18 months). Trunk-based with squash-merge, branch protection on main, all CI gates blocking. Thin YAML — orchestration logic lives in package.json scripts (ci:check, ci:scan, ci:commits) and Nx targets, runnable locally. Gates: format / lint / type-check / test / build / audit / secret-scan / commit-lint, plus a11y (per ADR-0016) and future perf. Self-hosted act_runner on-prem. Conventional Commits validated locally (hook) and in CI (defense in depth). Required reviewer count = 0 in v1, raised to ≥1 once a second contributor joins. Signed commits recommended, revisited at GitLab migration — see ADR-0015.
  • Accessibility: WCAG 2.2 AA baseline + targeted AAA on criteria with high impact for APF's user base (1.4.6 Contrast Enhanced, 2.2.3 No Timing, 2.3.3 Animation, 3.1.5 Reading Level, 1.4.8 Visual Presentation, 2.4.9 Link Purpose, 3.3.5 Help). RGAA 4.1 alignment for French audit. UI stack: Angular CDK + TailwindCSS (spartan-ng library deferred until it reaches 1.0.0; v1 components are written in-house in libs/shared/ui/ on Angular CDK, applying the spartan-ng philosophy of headless primitives + utility CSS + copy-paste). User-preferences panel (contrast / text size / motion / spacing / cognitive simplification / reading focus) persisted in session. Tooling: @angular-eslint/template/* lint, @axe-core/playwright e2e (blocking on critical/serious), token-contrast CI check, touch-target check (44×44 min). Manual testing cadence with APF's internal user panel before each major release. Public accessibility statement page at /accessibility and /accessibilite — see ADR-0016.
  • Performance budgets: Core Web Vitals at Google "Good" thresholds (LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1, TBT ≤ 200 ms, TTFB ≤ 800 ms), Lighthouse Performance ≥ 90 on critical routes. Lighthouse CI (@lhci/cli) runs in CI with median-of-3 mitigation, blocking on threshold breach. Angular bundle budgets (type: "error"): initial ≤ 300 KB gzip, lazy chunks ≤ 100 KB gzip. BFF p95/p99 SLOs per endpoint family observed via OTel (advisory in CI, alerting in prod). Weekly scheduled Lighthouse run on prod env. a11y wins over perf when they conflict — see ADR-0017.
  • Environment configuration: SPA per-environment values via Angular environment.ts + fileReplacements at build time (no runtime config-fetch). BFF reads process.env directly with small per-key boot-time validators (no @nestjs/config overhead at this scale). The audit log uses a separate AUDIT_DATABASE_URL connection pool in production (audit_writer-only login, defense in depth) and falls back to the shared pool + SET LOCAL ROLE in dev — see ADR-0018.
  • Internationalisation: @angular/localize in build-time mode, two locales (fr default served at /, en), source locale = English (project English-only rule). Path-based URLs always prefixed (/fr/..., /en/...); / smart-redirects via cookie → Accept-Languagefr. UI strings live in XLIFF (messages.fr.xlf); editorial / CMS content is BFF-served already localised (see admin app). Footer hosts the locale switcher; switching writes a __Host-portal_locale cookie and hard-refreshes — see ADR-0019.
  • Admin application (portal-admin): dedicated Angular SPA alongside portal-shell, sharing the same portal-bff via /api/admin/* routes guarded by an Entra Portal.Admin role + @RequireMfa({ freshness: 600 }) at entry. Distinct origin / cookie / session from portal-shell (__Host-portal_admin_session). v1 modules: CMS for static pages (multilingual), menu management, user list (read-only), audit log viewer. Bundle budget relaxed to ≤ 500 KB gzip (vs 300 KB for portal-shell); same a11y + dark-mode baseline. Shared UI primitives (Icon, LayoutStateService, brand tokens) graduate to libs/shared/* as both apps need them — see ADR-0020.
  • Local quality gates: Husky + lint-staged + commitlint with Conventional Commits — see ADR-0007.
  • Documentation site: docs/**/*.md rendered as a separate static site via VitePress (Vite-based, Node-only toolchain, Markdown-first). Mermaid diagrams via vitepress-plugin-mermaid. Deployed on its own hostname behind the shared reverse-proxy; CI hook on docs/ changes rebuilds + publishes. Decoupled from the apps — content lives in docs/, no in-app Markdown viewer — see ADR-0022.
  • Charts + dashboards: D3 + Observable Plot wrapped in libs/shared/charts/, one Angular component per chart type (bar, donut, line, stacked-bar, …). A11y baked in by the lib (SVG <title>/<desc>, <details> tabular fallback, colour-blind-safe palettes, AA-contrast text, prefers-reduced-motion gate). Bundle stays under ADR-0017's lazy-chunk cap via per-d3-* module tree-shaking. Future bespoke visualisations land in raw D3 inside the same lib — see ADR-0023.
  • AI service relay: dedicated apf-ai-service repo (ASP.NET Core, Microsoft Agent Framework) consumed via native gRPC HTTP/2 only — proto contract vendored under apps/portal-bff/src/grpc/proto/apf-ai/ with ts-proto codegen committed alongside. BFF dials with @grpc/grpc-js (h2c in dev, h2 + TLS in prod), bridges ChatService.Chat to text/event-stream for the SPA, exposes RagService.Search and ModelsService.ListModels as plain JSON endpoints. Identity travels as an unsigned Principal (subject, roles, attributes) in the proto body for the POC, hashed via the audit module's HashUserIdService so portal and AI service audit trails join on the same actor_id_hash. Production hardening (signed envelope vs mTLS) deferred — see ADR-0024.
  • Runtime: Node.js latest LTS major.

Repository status

The Nx workspace is scaffolded and operational. The three apps (portal-shell, portal-admin, portal-bff) and the four lib roots (libs/feature/, libs/shared/state, libs/shared/tokens, libs/shared/ui, libs/shared/util) are in place; CI runs format:check / lint / test / build on every PR.

ADRs 0001 → 0024 are accepted and cover the structural, security, observability, quality, i18n, admin-app, docs-site, charts, and AI-relay choices. Shipped on main:

  • Phase-1 foundation — Nx workspace, Angular portal-shell, NestJS portal-bff, Prisma + Postgres, Pino + OpenTelemetry, Husky/lint-staged/commitlint, Gitea Actions CI.
  • Phase-2 auth + audit + security — OIDC Auth Code + PKCE via MSAL Node, Redis sessions with AES-256-GCM at rest, idle 30 min sliding + absolute 12 h hard ceiling, RP-initiated logout, double-submit CSRF, audit.events append-only schema with role-based grants, helmet + env-driven CORS allowlist + rate limiting + structured error envelope (see ADR-0021).
  • Phase-3a admin app skeletonportal-admin SPA exists with brand tokens and routing; business modules (CMS, menu management, user list, audit log viewer) not yet implemented.
  • AI relay surface — vendored protos + AiClientModule (gRPC clients, Principal mapper, metadata builder) + AiBridgeController exposing POST /api/ai/chat (SSE), GET /api/ai/rag/search, GET /api/ai/models (see ADR-0024). Live consumer (chatbot widget on portal-shell) and the proto-drift CI gate ship next.

Still on the roadmap:

  • DownstreamApiClient + OBO (ADR-0014) — no v1 consumer yet; will land when the first business route needs an Entra-protected API.
  • @RequireMfa() / @RequireAdmin() guards (ADR-0011, ADR-0020) — designed-in, awaiting first consumer route.
  • Docs static-site implementation (ADR-0022) — ADR accepted, chantier (VitePress install + .vitepress/config.ts + docs-site.yml workflow) lands next.
  • Charts lib + audit-page dashboards (ADR-0023) — ADR accepted; chantier next: libs/shared/charts/ foundations + 3 starter components (bar, donut, stacked-bar), then /audit-page integration with daily-volume + outcome-breakdown + event-type-over-time charts.
  • Strategic security baseline ADR — separate from the implementation-level ADR-0021. Remains paused awaiting RSSI input on the OWASP ASVS reference level and adjacent frameworks (HDS, GDPR, possibly NIS 2). When it lands it will either confirm 0021 or supersede pieces of it.

Commands once the workspace exists

App-scoped — <app> is one of portal-shell, portal-admin, portal-bff:

pnpm nx serve <app>      # dev server
pnpm nx build <app>
pnpm nx test <app>       # Vitest, all tests for the app
pnpm nx lint <app>

Run a single test file:

pnpm nx test <app> --testFile=path/to/file.spec.ts

Workspace-wide:

pnpm nx run-many -t lint test build
pnpm nx affected -t lint test build   # only projects affected by current changes
pnpm nx format:check

Environment conventions

  • Never install Angular globally. Use pnpm dlx for one-off CLI invocations and project-local pnpm nx ... for everything else — versions stay pinned per project.
  • Work inside the WSL filesystem (~/dev/...), never under /mnt/c — the latter has severe I/O penalties that break Nx caching and dev-server reload times.
  • pnpm is mandatory (activated via corepack enable); do not introduce npm or yarn lockfiles.
  • Prettier config target: singleQuote: true, semi: true, printWidth: 100.

General Guidelines for working with Nx

  • For navigating/exploring the workspace, invoke the nx-workspace skill first - it has patterns for querying projects, targets, and dependencies
  • When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task through nx (i.e. nx run, nx run-many, nx affected) instead of using the underlying tooling directly
  • Prefix nx commands with the workspace's package manager (e.g., pnpm nx build, npm exec nx test) - avoids using globally installed CLI
  • You have access to the Nx MCP server and its tools, use them to help the user
  • For Nx plugin best practices, check node_modules/@nx/<plugin>/PLUGIN.md. Not all plugins have this file - proceed without it if unavailable.
  • NEVER guess CLI flags - always check nx_docs or --help first when unsure

Scaffolding & Generators

  • For scaffolding tasks (creating apps, libs, project structure, setup), ALWAYS invoke the nx-generate skill FIRST before exploring or calling MCP tools

When to use nx_docs

  • USE for: advanced config options, unfamiliar flags, migration guides, plugin configuration, edge cases
  • DON'T USE for: basic generator syntax (nx g @nx/react:app), standard commands, things you already know
  • The nx-generate skill handles generator discovery internally - don't call nx_docs just to look up generator syntax