Files
clean-architecture-frontend…/docs/architecture/starter-experience.md
T
DongHyeonka 3c31576940 test(contracts): V2 행과 V3 descriptor를 양방향과 스키마 id까지 맞춰 본다 (07-02)
문제
HTTP API 하나를 V2 행(check:registries가 보는 선언)과 V3 descriptor(실제로
실행되는 사본)에 두 번 쓴다. 15-01 뒤에도 둘은 feature-runtime.ts의
apiContract와 contractContributions로 나뉘어 그대로 두 벌이다. 둘을 잇는
parity 테스트는 V2 행에서 V3를 찾는 한 방향이고 6필드만 비교한다. 그래서
V3 검증기의 schemaId를 바꾸거나(L1) V3에만 API를 추가해도(L6) 테스트가
통과한다. V3에만 있는 API는 공개 경로·메서드가 FE-REG-API 게이트 밖에서
실행된다. "V2는 게이트용, V3는 실행용"이라는 사실은 테스트 주석에만 있다.

고른 방법 (리뷰 5.1절의 B, 1단계)
- 두 사본의 operation id 집합이 같아야 한다(양방향). V3만 있는 API와
  V2만 있는 API가 각각 실패한다.
- 비교 필드에 같은 사실의 사본 넷을 더했다: 쓰기 여부(V2 semantics ↔ V3
  commandEffect 유무, 실행기가 쓰기를 메서드가 아니라 effect로 정하므로),
  요청 본문(V2 requestSource body ↔ V3 requestBody JSON), 입력 스키마 id
  (V2 pathSchema/requestSchema 중 NoRequest가 아닌 것 ↔ V3 inputValidator),
  응답 스키마 id(V2 responseSchema ↔ V3 outputValidator).
- V2가 path와 request 스키마를 둘 다 가진 operation은 V3 입력 스키마 하나와
  대응 규칙이 아직 없다. 조용히 넘기지 않고 테스트가 실패하며 규칙을
  정하라고 알린다. 지금 설치된 operation에는 없다.
- RestOperationV2 위와 starter-experience.md "Adding a feature"에 V2는
  게이트용 선언, V3는 실행 사본이고 둘 다 쓴다는 것을 적었다.

버린 대안
- V2 행을 V3에서 생성(5.1절 C)하거나 FE-REG-API 스냅샷을 V3에서 투영하고
  V2 행을 없애기(D): 생성기·투영 함수와 기준선 재승인이 필요한 구조
  변경이라 이번 범위를 넘는다. 15-01로 V2와 V3가 같은
  defineFeatureRuntime 객체에 모였으므로 D로 갈 때 기능 단위 투영 지점은
  생겼다.
- "V2 행이 1개 이상" 단언: test:sample-removal이 참조 기능을 지운 사본에서
  이 파일을 돌리면 두 집합이 모두 비어 정상인데 실패한다. 양방향 집합
  비교가 한쪽만 빈 경우를 잡는다.
- 두 번째 기능 테스트(second-api-feature-registries)에 V3 기여 넣기:
  fixture 복사본에서 check:registries를 도는 테스트라 V3 기여를 넣어도 이
  parity 검사가 그 사본에서 돌지 않는다. 비용 대비 효과가 작아 뺐다.

위험·한계
- 시간 제한(V2 timeoutMs null ↔ V3 totalDeadlineMs 10000, L3)은 비교하지
  않는다. 맞추려면 V2 행 값을 바꿔야 하고 FE-REG-API 기준선이 바뀐다.
  주석에 비교하지 않는다고 적었다.
- 응답 스키마 본문, unknownFieldPolicy ↔ zod strip/strict(L7), 손 guard ↔
  zod DTO 차이는 여전히 대조하지 않는다.
- 설치된 기능에 대한 테스트다. CI 밖에서 V3만 추가한 다운스트림은 이
  파일을 돌려야 걸린다.

검증
- RED: 기존 테스트와 새 테스트를 같은 변이에 돌렸다.
  L1(V3 GET_REFERENCE_RESOURCE outputValidator schemaId를
  ReferenceResourcePayloadV2로): 기존 통과, 새 테스트 실패
  ("responseSchema": "ReferenceResourcePayload" vs "...V2").
  L6(V3에만 GET_REFERENCE_RESOURCE_V3_ONLY 추가): 기존 통과, 새 테스트
  "cover the same operations" 실패(+ "GET_REFERENCE_RESOURCE_V3_ONLY").
- GREEN: 변이 없이 2/2 통과.
- 회귀: tsc test rc=0, 바꾼 파일 eslint rc=0. 전체 회귀는 다음 커밋들과
  함께 마지막에 돌렸다(이 커밋의 src 변경은 주석뿐).

Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md
2026-11-01 22:35:54 +09:00

176 lines
8.9 KiB
Markdown

# Starter experience contract
The repository provides a runnable, domain-neutral application rather than
only infrastructure contracts. The starter experience is intentionally
replaceable at the page level while the shell, providers, boundaries,
primitives, and state surfaces remain reusable.
## Runtime composition
```text
validated config + coherent release manifest
-> concrete adapters
-> QueryClientProvider
-> ApplicationProvider
-> RouterProvider
-> ThemeProvider
-> SessionProvider
-> AppShell
-> lazy route boundary
```
Boot stops before product mount when configuration or release coherence fails.
Each lazy page renders inside Suspense and a telemetry-aware route boundary.
Route changes move focus to the new page heading; the skip link and landmarks
remain stable in the shell.
## Registered routes
The route list is `ROUTE_REGISTRY` (`src/features/installed-feature-contracts.ts`):
the platform routes of `src/contracts/routes.ts` plus the routes of every
installed feature. The platform overview page (`/examples/platform`) shows the
composed list at runtime, so this document does not keep a copy of it.
Navigation labels and order come from `ROUTE_REGISTRY`; the sidebar does not
maintain a second route list. The client access decision never claims to be
authorization.
## Authentication seam
The session port exposes state subscription, sign-in start, sign-out,
credential attachment, recovery, and unauthenticated notification. Credentials
remain opaque to the application and presentation layers.
- `demo`: local/development-only state transition with no credentials
- `external`: delegates to `globalThis.__CA_FRONTEND_AUTH_OWNER__`
- missing/invalid external owner: fails closed as `integration-failed`
An external owner implements `readState`, `readSubject`, `subscribe`,
`beginSignIn`, `signOut`, `attachCredential`, `recoverSession`, and
`notifyUnauthenticated`. It owns token acquisition and storage. An owner that
lacks any of these methods is rejected, and the session fails closed as
`integration-failed`.
`readSubject()` is required. The server-state cache is cleared only when the
session state or the subject changes, so a token refresh for the same user
keeps cached data. `readSubject()` must return:
- an opaque, non-empty string that stays the same for one user across token
refreshes and differs between users: the OIDC `sub` claim, Supabase
`session.user.id`, or Firebase `user.uid`
- `null` when nobody is signed in
- never an access token, refresh token, or any other credential
If `readSubject()` returns `null` or `""` while the owner reports
`authenticated`, the runtime cannot tell a refresh from an account switch. It
fails closed: every such notification clears server state, and each one records
the `cache.operation.failed` diagnostic with `operation: SCOPE_FENCE` and
`reason: SUBJECT_MISSING`. Seeing that diagnostic means the owner is not
reporting its subject. The `demo` adapter reports one fixed demo user as its
subject.
Migration: `readSubject()` used to be optional. An owner written for an earlier
release must add it; without it the owner is rejected at startup (the session
becomes `integration-failed`) and a TypeScript owner no longer compiles
against `ExternalSessionOwner`. A code path that implements `AuthSessionPort`
or `SessionGateway` directly must add `getSubject()` the same way.
## Extending the starter
New platform work should follow
[routing, page templates, and reusable patterns](./routing-pages-and-patterns.md)
and the
[TypeScript, state, and data-flow target](./typescript-state-and-data-flow.md)
rather than adding another independent route or data-loading convention.
### Ownership declarations
Features, contexts and apps are discovered by
`scripts/generate-product-feature-index.ts`. Each boundary declares only its
parent, as exported string or integer literals the generator reads:
| File | Exports |
| --- | --- |
| `src/apps/<app>/app-module.ts` | `APP_MODULE_ID`, `APP_MAX_CONTEXTS` |
| `src/contexts/<context>/context-module.ts` | `CONTEXT_MODULE_ID`, `CONTEXT_APP_ID`, `CONTEXT_ROUTE_PATH`, `CONTEXT_MAX_FEATURES` |
| `src/features/<feature>/feature-module.ts` | `FEATURE_MODULE_ID`, `FEATURE_CONTEXT_ID`, `FEATURE_MODULE` |
| `src/features/<feature>/feature-runtime.ts` | `FEATURE_RUNTIME` (imported only by `feature-module.ts`, dynamically) |
| `src/features/<feature>/context-routes.ts` | `FEATURE_CONTEXT_ROUTES` |
The generator writes `src/.generated/` (git-ignored): the feature index the
installed catalogs import, the context index the router loads lazily, and the
selected app. Every build and check script runs it first; run it yourself with
`corepack pnpm generate:feature-index`. It fails, naming the file, when:
- a directory under `src/features/` has no `feature-module.ts` and no
`NOT_INSTALLED` marker file (`src/features/local-draft-feature/NOT_INSTALLED`
is the one intentional example);
- a feature names an undeclared context, or a context an undeclared app;
- a context or app exceeds its declared budget;
- `VITE_PRODUCT_FEATURES` names a feature the app does not declare. The
variable narrows the installed set here, before anything is compiled.
### Adding a feature
1. Create `src/features/<feature>/feature-module.ts`. Build `FEATURE_MODULE`
with `defineFeatureModule` (`src/features/feature-module.ts`). This is the
feature's declaration, and it is in the initial chunk, so it holds data
only: the declaration contract (routes, route runtime contracts,
invalidation, topic versions and the external `contractPackages` the
release manifest is checked against at boot), its message catalogs, and
`loadRuntime`, which imports `feature-runtime.ts` dynamically.
`src/features/reference-feature/feature-module.ts` is the complete example.
2. Create `src/features/<feature>/feature-runtime.ts` with
`defineFeatureRuntime`: the API contract (operations, schema metadata,
runtime schemas, mappers), the adapter contributions
(`defineFeatureAdapterContribution`, with `needs` naming the platform
capabilities it receives) and the contract contributions. The router loads
it (`application.features.load`) when one of the feature's routes is
entered. Do not import it statically from anywhere: each feature would add
its whole executable code to the initial chunk again, about 3.9 KB gzip
(`tests/unit/feature-shape-growth.test.ts` bounds one feature at 1 KiB).
An HTTP API is written twice: its API contract operation (V2) is what
`check:registries` governs, and its contract contribution descriptor (V3)
is what executes. `tests/unit/http-operation-v2-v3-parity.test.ts` fails
when one exists without the other or when they disagree.
A product feature's contract contribution uses an `EXTERNAL_PACKAGE`
source. `TEMPLATE_FIXTURE` belongs to `reference-feature` only and never
joins the release contract set; the composer rejects it anywhere else.
3. Create `src/features/<feature>/context-routes.ts` exporting
`FEATURE_CONTEXT_ROUTES`. Page components are imported lazily here, and each
route handle carries the route's params/search `codecs`; the owning context
loads this file only when its route root is visited
(`src/features/reference-feature/context-routes.ts`).
4. Name the owning context in `FEATURE_CONTEXT_ID`. Use an existing context or
add `src/contexts/<context>/context-module.ts` owned by the app.
5. If the feature has application input, augment `ApplicationFeatureInputs`
from the feature (`src/features/local-draft-feature/application/local-draft-api.ts`).
6. Run `corepack pnpm check:architecture`, `corepack pnpm check:types`,
`corepack pnpm check:registries` and the tests. `tests/unit/two-feature-install-typecheck.test.ts`
keeps the installed catalogs compiling with more than one feature.
7. Run `corepack pnpm test:sample-removal -- --feature=<feature id>` to prove
the product still builds and passes its gates without the feature.
Files outside the feature directory:
| File | Change |
| --- | --- |
| `src/.generated/*` | regenerated automatically |
| `src/contexts/<context>/context-module.ts` | only when the feature needs a new context |
| `config/runtime/<profile>.json` | optional `FEATURE_OVERRIDES` entry to switch the feature off |
| `src/bootstrap/runtime-adapters.ts` | only when `needs` includes `indexedDb`: add the capability, built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts` |
The central catalogs (`src/features/installed-*.ts`) and the registry
governance file do not change: consumer directories there are globs over every
feature (`src/features/*/adapters`, `config/contracts/registry-governance.json`).
### Before shipping
- Use the semantic tokens, UI primitives, and state surfaces before adding a
project-specific variant.
- Add component behavior, all-engine E2E, automated axe, and signed manual
route evidence.
Theme preference is the public `COLOR_SCHEME` storage contract. Authentication
tokens and other secrets remain forbidden storage keys.