Files
clean-architecture-frontend…/docs/architecture/starter-experience.md
T
DongHyeonka c06338956e fix(contracts): 참조 기능 밖의 TEMPLATE_FIXTURE 기여를 거부한다 (07-04)
문제
조립기(composeContractContributions)의 TEMPLATE_FIXTURE 분기는
fixtureId·revision·이벤트 0개만 보고 featureId를 보지 않는다. 참조 기여
파일을 복사한 제품 기능(order)이 fixture 출처 그대로 조립을 통과한다.
fixture 기여는 계약 집합(externalPackages)에 들어가지 않으므로 그 API는
실행되지만 부팅 때 릴리스 계약 정합 검사에서 경고 없이 빠진다. 설계서
§4.8은 "product feature는 반드시 EXTERNAL_PACKAGE", §24.5는 정적 검사가
product TEMPLATE_FIXTURE를 거부한다고 적지만 구현이 없다.

고른 방법
- 조립기 fixture 분기에서 featureId가 fixture의 주인과 다르면
  ContractContributionError로 실패한다. 메시지가 EXTERNAL_PACKAGE를
  쓰라고 안내한다.
- fixture 기여가 둘 이상이면 실패한다(설계서의 "유일한 예외").
- 15-01 뒤 조립은 기능 적재 때마다 전체를 다시 조립하므로 두 검사 모두
  기능이 따로 적재돼도 걸린다. registry.install의 featureId 일치 검사가
  있어 다른 기능이 참조 기능 id를 빌려 쓰는 길도 막혀 있다.
- 주인 featureId는 리터럴로 쓰지 않고 fixtureId에서 만든다
  (REFERENCE_FEATURE_V1 -> 대문자 스네이크를 소문자 kebab으로, _V1 제거).
  이유를 주석에 적었다.
- starter-experience.md "Adding a feature"에 제품 기여는
  EXTERNAL_PACKAGE라는 문장을 넣었다.
- contract-snapshot-bypass의 "iterator에 숨긴 이벤트" 테스트는
  featureId test-feature의 fixture를 썼다. 새 검사가 그 행을 먼저 막아
  테스트가 아무것도 확인하지 못하게 되므로 EXTERNAL_PACKAGE 출처로
  바꿨다. 패키지 출처는 이벤트를 받으므로 숨긴 이벤트를 읽으면 설치되어
  단언이 실패한다. 예전 fixture 출처는 이벤트가 하나라도 있으면 던져서
  읽었는지 아닌지를 구분하지 못했다.

버린 대안
- 리뷰 문서 그대로 featureId !== "reference-feature" 리터럴 비교:
  test:sample-removal이 샘플 제거 뒤 src/·tests/ 전체에서
  /REFERENCE_RESOURCE|reference-feature|reference-resource/i를 찾아
  잔여물로 실패시킨다(scripts/test-sample-removal.ts:95). 플랫폼 코드와
  남는 단위 테스트에 그 id를 쓰면 이 게이트가 깨진다.
- 조립기에 허용 featureId 인자를 추가하거나 feature module에 fixture 표시
  필드를 추가: 공개 함수·타입 변경이라 이번 범위를 넘는다.
- 정적 검사(dependency-cruiser) 규칙: 출처 종류는 import가 아니라 값이라
  depcruise로 볼 수 없다.

위험·한계
- 실패 시점은 15-01 구조에 따라 부팅이 아니라 그 기능의 런타임 적재
  (라우트 진입) 때다. Node 쪽 loaded-feature-runtimes와 레지스트리
  스크립트는 import 때 전부 조립하므로 CI에서는 바로 드러난다.
- scripts/scale/measure-feature-shape-growth.ts는 참조 기능을 이름만 바꿔
  복사하고 REFERENCE_FEATURE_V1을 그대로 둔다. 그 복사본은 이제 조립에서
  거부된다. 이 스크립트는 tsc와 vite build만 하고 기여를 조립하지 않아
  측정에는 영향이 없다(실행하지 않음).
- 주인 id 유도는 fixtureId가 "<기능 id 대문자 스네이크>_V<revision>"
  꼴이라는 이름 규칙에 기댄다. fixtureId는 닫힌 리터럴 하나라 지금은
  참조 기능 id 하나로만 풀린다.

검증
- RED(수정 전 조립기): 새 테스트 2건 실패.
  external-contract-runtime "rejects a fixture copied into a product
  feature" -> "Expected contract composition to fail."
  reference-fixture-provenance "rejects a second fixture contribution"
  -> "expected undefined to be 'reference-feature: only one
  TEMPLATE_FIXTURE contribution is allowed'".
- GREEN: 같은 3파일 22/22 통과.
- 회귀(298201f 위로 rebase 뒤): run-vitest tests/unit tests/features
  tests/platform tests/component tests/contract tests/runtime-schema
  tests/integration (pnpm·corepack을 띄우는 fixture-node-modules,
  security-followup-archive, deployment-admission, lab-performance 제외)
  267 files / 3107 tests 중 3106 통과. 실패 1건은
  provider-guardian-transaction(guardian exit=126, 단독 실행도 같음)으로
  scripts/lib 프로세스 테스트라 이 변경과 무관하다. tsc app/test rc=0. 바꾼 파일 eslint rc=0.
- 바꾼 src·tests/unit 파일에 샘플 잔여물 정규식 일치 0건(grep).
- 미실행: test:sample-removal, check:architecture(pnpm 필요).

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

8.6 KiB

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

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 and the TypeScript, state, and data-flow target 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). 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.