From 7ee1df56f1e267c8bf08f51b25730d6df9fb1197 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:07:24 +0900 Subject: [PATCH 01/16] =?UTF-8?q?test(component):=20UI=20=EA=B0=A4?= =?UTF-8?q?=EB=9F=AC=EB=A6=AC=20=ED=99=94=EB=A9=B4=EC=9D=98=20=EA=B2=80?= =?UTF-8?q?=EC=A6=9D=C2=B7=EC=83=81=ED=83=9C=20=EC=A0=84=ED=99=98=EC=9D=84?= =?UTF-8?q?=20component=20=ED=85=8C=EC=8A=A4=ED=8A=B8=EB=A1=9C=20=EB=A7=89?= =?UTF-8?q?=EB=8A=94=EB=8B=A4=20(1101/14.4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: `src/presentation/examples/ui-gallery-page.tsx`는 component 커버리지가 0%였다. e2e(`tests/e2e/ui-gallery.spec.ts`, 폼 검증과 모달 포커스 2건)와 시각 회귀만 이 화면을 봤다. 화면이 primitive에 연결한 규칙(공백 이름 거절, 알림 줄 문구, 알림 숨김·다시 표시, 모달 확인만 알림 줄을 바꿈, 메뉴의 toast)은 게이트 안 단위 실행에서 아무도 확인하지 않았다. 고른 방법: `tests/component/starter-ui-gallery-page.test.tsx` 9건. 화면을 LocaleProvider만으로 그리고 사용자 동작(user-event)으로 확인한다. 섹션 5개와 토큰 7개 렌더, 버튼 3개의 알림 문구, 빈 이름·공백 이름 거절과 trim한 이름 수락, controlled 입력 6종, 알림 숨김·복원, 모달의 취소·닫기·확인, 메뉴 두 항목, 수동 탭 활성화, tooltip 설명. 파일 이름은 starter 화면 테스트 규칙 (`docs/architecture/starter-experience.md`, `starter-*.test.tsx`)을 따라 화면을 지울 때 같이 지운다. 버린 대안: 스냅샷 테스트. 문구가 바뀔 때마다 깨지고 동작은 확인하지 않는다. 앱 라우터(`/examples/ui`)로 띄우기. 라우팅은 router 테스트가 보고, 이 화면은 provider가 locale 하나만 필요하다. 화면 코드는 고치지 않았다. 위험·한계: primitive 자체 동작(포커스 트랩, Esc, 화살표 이동)은 각 primitive 테스트와 e2e가 보고 여기서는 다시 세지 않는다. jsdom이라 실제 레이아웃과 `showModal()`의 top layer는 확인하지 않는다(e2e 몫). 검증: - 커버리지(`node scripts/run-vitest.ts run tests/component --coverage --coverage.include=src/presentation/examples/ui-gallery-page.tsx`): 전 lines 0/38, functions 0/19, branches 0/8 후 lines 38/38, functions 19/19, branches 8/8 (100%) - 일부러 화면을 깨 봄(되돌림): fieldError의 trim 제거, 알림 onDismiss 무효화, 메뉴 "상태 확인" onSelect 무효화 → 9건 중 3건 실패 - tests/component 전체 38파일 253건 통과 - `npx eslint` 새 파일, `npx tsc --project tsconfig.test.json --noEmit` 통과 --- .../starter-ui-gallery-page.test.tsx | 227 ++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 tests/component/starter-ui-gallery-page.test.tsx diff --git a/tests/component/starter-ui-gallery-page.test.tsx b/tests/component/starter-ui-gallery-page.test.tsx new file mode 100644 index 00000000..dfff44fa --- /dev/null +++ b/tests/component/starter-ui-gallery-page.test.tsx @@ -0,0 +1,227 @@ +// @vitest-environment jsdom + +import { render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it } from "vitest"; + +import UiGalleryPage from "../../src/presentation/examples/ui-gallery-page.tsx"; +import { LocaleProvider } from "../../src/presentation/i18n/index.ts"; + +/** + * A starter screen (0929/10-02): `/examples/ui` is template content, so a + * product that replaces it deletes this file with it. The primitives have + * their own suites; this one checks what the page wires them to — the + * validation rule, the shared notice line and the show/hide state. + */ + +function renderPage() { + const user = userEvent.setup(); + const view = render( + + + , + ); + // The Alert is a status too; the page's notice line is the ``. + const notice = view.container.querySelector("output.gallery-notice"); + if (!(notice instanceof HTMLOutputElement)) { + throw new Error("The gallery notice output is missing"); + } + return { user, notice }; +} + +describe("starter UI gallery page", () => { + it("renders every gallery section and the colour token swatches", () => { + const { notice } = renderPage(); + + expect( + screen.getByRole("heading", { level: 1, name: "UI 구성요소" }), + ).toBeVisible(); + for (const section of [ + "버튼과 입력", + "폼과 선택 컨트롤", + "피드백과 모달", + "탐색 패턴", + "디자인 토큰", + ]) { + expect(screen.getByRole("region", { name: section })).toBeVisible(); + } + const tokens = screen.getByRole("region", { name: "디자인 토큰" }); + expect(within(tokens).getAllByRole("article")).toHaveLength(7); + expect(within(tokens).getByText("--color-focus")).toBeVisible(); + expect(notice).toHaveAttribute("aria-live", "polite"); + expect(notice).toHaveTextContent( + "구성요소를 조작하면 결과가 여기에 표시됩니다.", + ); + }); + + it("reports each button action on the notice line", async () => { + const { user, notice } = renderPage(); + + await user.click(screen.getByRole("button", { name: "기본 작업" })); + expect(notice).toHaveTextContent("기본 작업을 실행했습니다."); + await user.click(screen.getByRole("button", { name: "보조 작업" })); + expect(notice).toHaveTextContent("보조 작업을 실행했습니다."); + await user.click(screen.getByRole("button", { name: "위험 작업" })); + expect(notice).toHaveTextContent("위험 작업 예제를 선택했습니다."); + expect(screen.getByRole("button", { name: "사용 불가" })).toBeDisabled(); + }); + + it("rejects a blank project name and accepts a trimmed one", async () => { + const { user, notice } = renderPage(); + const field = screen.getByRole("textbox", { name: "프로젝트 이름" }); + const submit = screen.getByRole("button", { name: "입력 확인" }); + + // Untouched: no error yet, even though the field is empty. + expect(field).not.toHaveAttribute("aria-invalid", "true"); + + await user.click(submit); + expect(field).toHaveAttribute("aria-invalid", "true"); + expect(field).toHaveAccessibleDescription( + /프로젝트 이름을 입력해 주세요\./u, + ); + expect(notice).toHaveTextContent("입력값을 확인해 주세요."); + + // Whitespace is still blank. + await user.type(field, " "); + await user.click(submit); + expect(field).toHaveAttribute("aria-invalid", "true"); + + await user.type(field, "Starter "); + expect(field).not.toHaveAttribute("aria-invalid", "true"); + await user.click(submit); + expect(notice).toHaveTextContent("“Starter” 입력을 확인했습니다."); + }); + + it("keeps the form and choice controls controlled by page state", async () => { + const { user } = renderPage(); + + const description = screen.getByRole("textbox", { name: "설명" }); + await user.type(description, "공통 예제"); + expect(description).toHaveValue("공통 예제"); + + const template = screen.getByRole("combobox", { name: "시작 템플릿" }); + expect(template).toHaveValue("application"); + await user.selectOptions(template, "library"); + expect(template).toHaveValue("library"); + + const reviewed = screen.getByRole("checkbox", { + name: "접근성 계약을 확인했습니다.", + }); + expect(reviewed).not.toBeChecked(); + await user.click(reviewed); + expect(reviewed).toBeChecked(); + + expect(screen.getByRole("radio", { name: "여유롭게" })).toBeChecked(); + await user.click(screen.getByRole("radio", { name: "조밀하게" })); + expect(screen.getByRole("radio", { name: "조밀하게" })).toBeChecked(); + expect(screen.getByRole("radio", { name: "여유롭게" })).not.toBeChecked(); + + const notifications = screen.getByRole("switch", { name: "알림 사용" }); + expect(notifications).toBeChecked(); + await user.click(notifications); + expect(notifications).not.toBeChecked(); + + // Native ; the label shows the rounded share. + const readiness = screen.getByRole("progressbar", { name: "설정 준비도" }); + expect(readiness).toHaveAttribute("value", "3"); + expect(readiness).toHaveAttribute("max", "4"); + expect(screen.getByText("75%")).toBeVisible(); + }); + + it("dismisses the alert and shows it again", async () => { + const { user } = renderPage(); + + await user.click( + screen.getByRole("button", { name: "설정이 저장되었습니다. 알림 닫기" }), + ); + expect( + screen.queryByText("설정이 저장되었습니다."), + ).not.toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: "알림 다시 표시" })); + expect(screen.getByText("설정이 저장되었습니다.")).toBeVisible(); + expect( + screen.queryByRole("button", { name: "알림 다시 표시" }), + ).not.toBeInTheDocument(); + }); + + it("closes the dialog by cancel, close and confirm, and only confirm reports", async () => { + const { user, notice } = renderPage(); + const trigger = screen.getByRole("button", { name: "모달 열기" }); + const initial = notice.textContent; + + await user.click(trigger); + let dialog = screen.getByRole("dialog", { name: "연동 확인" }); + expect(dialog).toHaveAttribute("open"); + await user.click(within(dialog).getByRole("button", { name: "취소" })); + expect(screen.getByRole("dialog", { hidden: true })).not.toHaveAttribute( + "open", + ); + expect(notice).toHaveTextContent(initial ?? ""); + await waitFor(() => expect(trigger).toHaveFocus()); + + await user.click(trigger); + dialog = screen.getByRole("dialog", { name: "연동 확인" }); + await user.click( + within(dialog).getByRole("button", { name: "연동 확인 닫기" }), + ); + expect(screen.getByRole("dialog", { hidden: true })).not.toHaveAttribute( + "open", + ); + expect(notice).toHaveTextContent(initial ?? ""); + + await user.click(trigger); + dialog = screen.getByRole("dialog", { name: "연동 확인" }); + await user.click(within(dialog).getByRole("button", { name: "확인" })); + expect(screen.getByRole("dialog", { hidden: true })).not.toHaveAttribute( + "open", + ); + expect(notice).toHaveTextContent("모달의 확인 작업을 실행했습니다."); + }); + + it("runs the menu actions: one reports on the notice, one pushes a toast", async () => { + const { user, notice } = renderPage(); + const trigger = screen.getByRole("button", { name: "작업 메뉴" }); + + await user.click(trigger); + await user.click(screen.getByRole("menuitem", { name: "상태 확인" })); + expect(notice).toHaveTextContent("메뉴 작업을 실행했습니다."); + expect(screen.queryByRole("menu")).not.toBeInTheDocument(); + + await user.click(trigger); + await user.click(screen.getByRole("menuitem", { name: "Toast 표시" })); + const region = screen.getByRole("region", { name: "알림" }); + expect( + within(region).getByText("예제가 저장되었습니다."), + ).toBeVisible(); + }); + + it("switches tab panels only on explicit activation", async () => { + const { user } = renderPage(); + const tokens = screen.getByRole("tab", { name: "토큰" }); + expect(tokens).toHaveAttribute("aria-selected", "true"); + + tokens.focus(); + await user.keyboard("{ArrowRight}"); + const primitives = screen.getByRole("tab", { name: "프리미티브" }); + expect(primitives).toHaveFocus(); + expect(primitives).toHaveAttribute("aria-selected", "false"); + + await user.keyboard("{Enter}"); + expect(primitives).toHaveAttribute("aria-selected", "true"); + expect( + screen.getByRole("tabpanel", { name: "프리미티브" }), + ).toHaveTextContent("native semantics와 interaction을 닫습니다."); + }); + + it("describes the help button with its tooltip", async () => { + const { user } = renderPage(); + const help = screen.getByRole("button", { name: "도움말" }); + + await user.hover(help); + expect(screen.getByRole("tooltip")).toHaveTextContent( + "이 설명은 필수 정보가 아닙니다.", + ); + expect(help).toHaveAccessibleDescription("이 설명은 필수 정보가 아닙니다."); + }); +}); From 13350875c67de46f7daf7ad7c34c2b8182f70b30 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:08:56 +0900 Subject: [PATCH 02/16] =?UTF-8?q?fix(docs):=20=EC=A0=95=EB=B9=84=20?= =?UTF-8?q?=EC=9B=90=EC=9E=A5=20TR-02~04=20=EC=A6=9D=EA=B1=B0=EB=A5=BC=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=EA=B0=80=20=EC=98=AE=EA=B2=A8=20?= =?UTF-8?q?=EA=B0=84=20=ED=8C=8C=EC=9D=BC=EB=A1=9C=20=EB=B0=94=EA=BE=BC?= =?UTF-8?q?=EB=8B=A4=20(1101/14.3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: `check:remediation-ledger`가 3건 실패한다. TR-02: tests/unit/presigned-transfer.test.ts does not mention TR-02 TR-03: tests/unit/image-cdn-runtime.test.ts does not mention X-AUDIT-01 or X-AUDIT-02 TR-04: tests/unit/resumable-upload-runtime.test.ts does not mention TR-04 원인은 ID 표시가 지워진 것이 아니다. 2026-09-18 테스트 분할(`5cc41467`, `ec7f20e2`)이 세 테스트를 표시째 다른 파일로 옮겼고, 원장과 dispositions JSON은 옛 파일을 가리킨 채 남았다. 지금 위치: TR-02 → tests/unit/presigned-transfer-delivery.test.ts:220 TR-03 이미지 probe → tests/unit/image-cdn-browser-probe.test.ts:579 (X-AUDIT-02) TR-04 → tests/unit/resumable-upload-runtime-teardown.test.ts:80 분할 전 파일(`5cc41467^`)에 같은 주석과 테스트가 있었음을 확인했다. 고른 방법: 원장 행이 테스트가 실제로 있는 파일을 가리키게 한다. `docs/operations/adapter-remediation-dispositions.json`의 evidence 3곳과 `docs/operations/adapter-remediation-ledger.md`의 같은 행 3개를 고치고, 머리말의 "옮긴 suite" 메모에 이번 분할을 더했다. 앞 절의 실행 명령은 그 실행이 쓴 파일 그대로 둔다(그 시점 기록). 버린 대안: 옛 파일에 TR-02·TR-04·X-AUDIT ID를 적기. 그 파일에는 해당 테스트가 없어서, 검사기가 막으려는 "관계없는 suite를 가리켜 증거처럼 보이기"를 그대로 만든다. 검사기와 markers 규칙은 바꾸지 않았다. 위험·한계: 테스트를 다시 쪼개거나 옮기면 같은 식으로 깨진다. 이 검사는 게이트 밖이라 그때도 아무도 모른다. `config/ci/ungated-scripts.json`의 이 검사 사유("Later fixes removed those markers … reports stale claims")는 이제 사실과 다르지만 이 커밋 범위 밖이라 고치지 않았다. 검증: - RED(`ec7435c`): `node scripts/check-remediation-ledger.ts` 3건 실패, exit 1 - GREEN: "25 dispositions joined …; 0 open; evidence paths verified", exit 0 - 증거 suite 5개 77건 통과(`node scripts/run-vitest.ts run` 해당 파일) - `verify-documentation-readiness.ts` PASS_SCOPED, `check-ci-contract.ts` PASS, `check-adapter-inventory.ts` PASS, `tests/unit/ungated-scripts.test.ts` 10건 통과 --- .../adapter-remediation-dispositions.json | 6 +++--- docs/operations/adapter-remediation-ledger.md | 13 +++++++++---- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/docs/operations/adapter-remediation-dispositions.json b/docs/operations/adapter-remediation-dispositions.json index d0e9edca..3c8140f9 100644 --- a/docs/operations/adapter-remediation-dispositions.json +++ b/docs/operations/adapter-remediation-dispositions.json @@ -113,7 +113,7 @@ "previous": "PARTIAL", "disposition": "FIXED", "summary": "A source lease that arrives after the delivery ended is closed exactly once by a compensator.", - "evidence": ["tests/unit/presigned-transfer.test.ts"] + "evidence": ["tests/unit/presigned-transfer-delivery.test.ts"] }, { "id": "TR-03", @@ -123,7 +123,7 @@ "markers": ["X-AUDIT-01", "X-AUDIT-02"], "evidence": [ "tests/unit/abortable-operation.test.ts", - "tests/unit/image-cdn-runtime.test.ts", + "tests/unit/image-cdn-browser-probe.test.ts", "tests/unit/resumable-upload-fetch-transport.test.ts" ] }, @@ -132,7 +132,7 @@ "previous": "PARTIAL", "disposition": "FIXED", "summary": "Teardown proves quiescence of the raw provider registry, not only of the wrappers that bound it.", - "evidence": ["tests/unit/resumable-upload-runtime.test.ts"] + "evidence": ["tests/unit/resumable-upload-runtime-teardown.test.ts"] }, { "id": "TR-05", diff --git a/docs/operations/adapter-remediation-ledger.md b/docs/operations/adapter-remediation-ledger.md index 5a958f5f..6628a54c 100644 --- a/docs/operations/adapter-remediation-ledger.md +++ b/docs/operations/adapter-remediation-ledger.md @@ -10,7 +10,12 @@ > Test paths are given at their current location. Two suites moved after > these runs: `ci-artifact-contract.test.ts` from `tests/unit/` to > `tests/system/ci-runner/`, and `provider-guardian-transaction.test.ts` from -> `tests/unit/` to `tests/integration/`. +> `tests/unit/` to `tests/integration/`. Three suites were split on +> 2026-09-18 (`5cc41467`, `ec7f20e2`) and the third re-review rows follow the +> tests that moved: TR-02 to `presigned-transfer-delivery.test.ts`, TR-03's +> image probe to `image-cdn-browser-probe.test.ts`, TR-04 to +> `resumable-upload-runtime-teardown.test.ts` (all in `tests/unit/`). The run +> commands in the earlier sections keep the file each run used. ## Containment state (plan Task 1, Step 1) @@ -431,9 +436,9 @@ than authored. | RT-01 | `PARTIAL` | `FIXED` | `tests/unit/realtime/stream-coordinator.test.ts` — an authority that re-entered `close()` from inside its own invocation got `{ok:true}` while its effect was pending; the task is registered before the collaborator is called. | | RT-02 | `NEW` | `FIXED` | Same suite — a throwing `scheduleTimeout` started a recovery that overlapped the running apply and made `close()` reject with a native `TypeError`; an uninstallable deadline now fails closed inside the result contract. | | TR-01 | `PARTIAL` | `FIXED` | `tests/unit/presigned-transfer.test.ts` — a stateful issuer could show an allowed header set to the forbidden-header check and store `Authorization`; the registration and everything nested in it is snapshotted before validation. | -| TR-02 | `PARTIAL` | `FIXED` | Same suite — a source lease that resolved after an abort was never closed; a compensator sharing the holder's close-once latch closes it exactly once. | -| TR-03 | `PARTIAL` | `FIXED` | `tests/unit/abortable-operation.test.ts`, `tests/unit/image-cdn-runtime.test.ts`, `tests/unit/resumable-upload-fetch-transport.test.ts` — the outcome depended on a hard-coded four-microtask drain, and a throwing scheduler rejected `probe()`/`execute()` natively while leaking a caller listener. The primitive now settles once by observation order, and all four consumers use it with construction-time bound timer snapshots. | -| TR-04 | `PARTIAL` | `FIXED` | `tests/unit/resumable-upload-runtime.test.ts` — a provider outliving its attempt deadline let `dispose()` report a drained runtime and close the checkpoint store; raw provider work is now its own registry and both must be quiescent. | +| TR-02 | `PARTIAL` | `FIXED` | `tests/unit/presigned-transfer-delivery.test.ts` — a source lease that resolved after an abort was never closed; a compensator sharing the holder's close-once latch closes it exactly once. | +| TR-03 | `PARTIAL` | `FIXED` | `tests/unit/abortable-operation.test.ts`, `tests/unit/image-cdn-browser-probe.test.ts`, `tests/unit/resumable-upload-fetch-transport.test.ts` — the outcome depended on a hard-coded four-microtask drain, and a throwing scheduler rejected `probe()`/`execute()` natively while leaking a caller listener. The primitive now settles once by observation order, and all four consumers use it with construction-time bound timer snapshots. | +| TR-04 | `PARTIAL` | `FIXED` | `tests/unit/resumable-upload-runtime-teardown.test.ts` — a provider outliving its attempt deadline let `dispose()` report a drained runtime and close the checkpoint store; raw provider work is now its own registry and both must be quiescent. | | TR-05 | `PARTIAL` | `FIXED` | `tests/unit/resumable-upload-http-control-plane.test.ts` — a stateful `sessionId` passed the regex and returned `../../unsafe`; the decoder validates an owned snapshot read exactly once. | | SW-01 | `PARTIAL` | `FIXED` | `tests/unit/service-worker-runtime.test.ts` — a single 1 MiB chunk was retained before the 257-byte ceiling was compared, a declared oversize left the body open and the reader lock was never released. | | SW-02 | `PARTIAL` | `FIXED` | `tests/unit/service-worker-web-push-remediation.test.ts` — the generator emitted `/assets/bad@name-abcdefgh.js` and the decoder then refused the manifest it had just produced; both share one canonical path predicate and the generator self-validates its output. | From 2eb010ae88458684b071de03f8b329dc83954e38 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:10:50 +0900 Subject: [PATCH 03/16] =?UTF-8?q?chore(ci):=20=EC=A0=95=EB=B9=84=20?= =?UTF-8?q?=EC=9B=90=EC=9E=A5=20=EA=B2=80=EC=82=AC=EB=A5=BC=20=EA=B2=8C?= =?UTF-8?q?=EC=9D=B4=ED=8A=B8=20=EB=B0=96=EC=97=90=20=EB=91=90=EB=8A=94=20?= =?UTF-8?q?=EC=9D=B4=EC=9C=A0=EB=A5=BC=20=EC=A7=80=EA=B8=88=20=EC=82=AC?= =?UTF-8?q?=EC=8B=A4=EB=A1=9C=20=EA=B3=A0=EC=B9=9C=EB=8B=A4=20(1101/14.3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: config/ci/ungated-scripts.json은 check:remediation-ledger를 게이트 밖에 두는 이유로 "표시가 지워져 지금 커밋에서 낡은 주장을 보고한다"를 적는다. 1335087 뒤로 이 검사는 통과하고, 실패 원인도 표시 삭제가 아니라 테스트 분할로 파일이 옮겨 간 것이었다. 고른 방법: 게이트 밖에 두고 이유만 사실대로 고친다. 지금 통과한다는 것, 게이트에 넣지 않는 실제 이유(제품이 선택 레시피 file-transfer를 빼거나 테스트 분할로 표시한 테스트가 옮겨 가면 실패한다), 언제 손으로 돌리는지를 적는다. 버린 대안: FE-GATE-010에 넣기. 1초 안에 끝나고 이번 같은 분할을 바로 잡았겠지만, 이 검사는 file-transfer 레시피 예산을 읽어 그 레시피를 뺀 제품의 merge를 막는다. 선택 레시피를 빼는 것은 템플릿이 허용한 경로다. 위험·한계: 다음 테스트 분할 때 원장이 다시 낡아도 게이트는 모른다. 이 검사는 작업 이력 원장이라 그 비용을 받아들인다. 검증: node scripts/check-remediation-ledger.ts 통과(25 dispositions, 0 open), tests/unit/ungated-scripts.test.ts 10건 통과 --- config/ci/ungated-scripts.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/ci/ungated-scripts.json b/config/ci/ungated-scripts.json index bb787a51..5abf98f9 100644 --- a/config/ci/ungated-scripts.json +++ b/config/ci/ungated-scripts.json @@ -15,7 +15,7 @@ }, { "script": "check:remediation-ledger", - "reason": "Checks the prose ledger of the 2026-08-14 adapter re-review (docs/operations/adapter-remediation-ledger.md) against test-file markers and the file-transfer bundle budget. Later fixes removed those markers and the budget is re-set at integration, so the check reports stale claims at this commit. It is a history record run by hand, not a current contract; wiring it into a gate first needs the ledger or the markers brought up to date." + "reason": "Checks the prose ledger of the 2026-08-14 adapter re-review (docs/operations/adapter-remediation-ledger.md) against test-file markers and the file-transfer bundle budget. It passes at this commit, but it is a history record run by hand, not a current contract: it fails when a product removes the optional file-transfer recipe or when a test split moves a marked test to another file, and neither should block a merge. Run it after moving those tests or changing that budget, and point the ledger rows at the new files." }, { "script": "check:scale:baseline", From ed0e4b1923f4edab17447b90b5941be8f94eb4a5 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:17:15 +0900 Subject: [PATCH 04/16] =?UTF-8?q?docs(contract):=20=EA=B1=B0=EC=A0=88=20co?= =?UTF-8?q?de=EB=B3=84=20=EC=A0=81=EC=9A=A9=20=EC=97=AC=EB=B6=80=EB=A5=BC?= =?UTF-8?q?=20=EB=B0=B1=EC=97=94=EB=93=9C=20=EC=BD=94=EB=93=9C=EB=A1=9C=20?= =?UTF-8?q?=EC=A0=95=ED=95=9C=EB=8B=A4=20(1101/14.4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 "검증 거절은 적용 안 됨" 판정(64e98ee)의 근거가 추론이었다. 백엔드 http-contract.md 4절은 VALIDATION_FAILED의 출처를 적지만 "상태를 바꾸지 않는다"는 문장이 없다. 그 밖의 400·409·422 code는 어느 단계에서 나오는지 적힌 곳이 없었다. 계약 4.1·6절은 백엔드 커밋이 없어 기준을 결정일로 적었다. 고른 방법 - 백엔드 5786126c 코드에서 400·409·422를 내는 곳을 모두 찾고, code마다 단계(쓰기 전 / 쓰기 뒤 가능)와 프론트 결과(NOT_APPLIED / MAYBE_APPLIED), 백엔드 파일:줄을 6.1절 표에 적었다. 같은 code가 쓰기 전과 뒤에서 모두 나오면 쓰기 뒤 가능으로 둔다. 프론트는 code만으로 둘을 가르지 못한다. - 4.1·6절 기준을 결정일에서 백엔드 SHA 5786126c로 바꿨다. - 표와 지금 프론트 판정이 다른 곳을 같은 절에 적었다. client.ts는 다른 작업이 고치고 있어 이 변경에서 건드리지 않았다. 찾은 것 - 쓰기 전: VALIDATION_FAILED(출처 5곳 모두 바인딩·검증 단계, CVE handler는 지금 요청 경로 출처 없음), IDEMPOTENCY_KEY_INVALID, IDEMPOTENT_REQUEST_ MISMATCH. IDEMPOTENT_IN_FLIGHT도 이번 요청은 쓰기 전이지만 앞선 요청이 적용될 수 있어 MAYBE_APPLIED다. - 쓰기 뒤 가능: BAD_PARAMETER(모든 층의 IllegalArgumentException), MAPPING_FAILED(멱등성 응답 직렬화는 action이 끝난 뒤), DB_* 409 8종, LOCK_ACQUISITION_TIMEOUT, 참조 도메인 400·409 6종, 선택 모듈 11종. fileserver INTEGRITY_MISMATCH·MALWARE_DETECTED(422)는 레코드를 REJECTED로 쓴 뒤 던진다. - 프론트와 다른 곳: 필드 목록 없는 400 VALIDATION_FAILED는 표로 NOT_APPLIED인데 V2는 effect가 없다. V2는 422 전체를 NOT_APPLIED로 보지만 fileserver 422는 MAYBE_APPLIED다. V3 참조 분류기는 400·422 전체를 NOT_APPLIED로 본다(참조 fixture용, 짝 백엔드에는 맞지 않는다). 버린 대안 - 백엔드 문서 표를 프론트 문서에 복사: 단계 정보는 백엔드 문서에 없다. 복사할 것이 아니라 프론트가 코드에서 읽은 판정이라 SHA와 파일:줄로 적었다. - 프론트에 백엔드 소스를 읽는 검사 추가: 두 repo가 나란히 있어야만 돈다. 표를 SHA에 묶고, SHA를 올릴 때 표를 다시 확인하라고 적었다. 위험·한계 - "쓰기 전"은 지금 코드에서 handler에 닿는 출처를 센 결과다. 백엔드가 application bean에 @Validated를 달거나 JPA entity에 Bean Validation 제약을 넣으면 필드 목록 있는 VALIDATION_FAILED가 use case 안에서도 나온다. 백엔드에 이것을 막는 검사는 없다. - 줄 번호는 5786126c 기준이다. 백엔드가 바뀌면 어긋난다. 검증 - node scripts/generate-product-feature-index.ts && node scripts/verify-documentation-readiness.ts: PASS_SCOPED - 표의 파일:줄은 백엔드 5786126c에서 grep·sed로 다시 열어 확인했다. Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.3, 14.4 --- .../backend-api-and-server-state-contract.md | 76 +++++++++++++++++-- 1 file changed, 71 insertions(+), 5 deletions(-) diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index 13d88ca9..a9838086 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -165,12 +165,13 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정 - 정본: [`clean-architecture-backend-template/docs/web/http-contract.md`](../../../clean-architecture-backend-template/docs/web/http-contract.md) 1절 "Envelope 키 존재 규칙" -- 기준 버전: 백엔드 성숙도 리뷰 2026-11-01의 15절 결정(2026-11-03)을 반영한 본. - 값이 null인 필드는 키째 생략한다. 백엔드에 이 변경의 커밋이 생기면 그 SHA로 - 바꾼다. +- 기준 커밋: 백엔드 `5786126c`. `http-contract.md`는 `34565130`에서 들어왔고 + `1400dc15`에서 마지막으로 바뀌었다. 값이 null인 필드는 키째 생략한다. 백엔드 + 기준 커밋을 올리면 6.1절 표를 같은 변경에서 다시 확인한다. - 프론트에서 Envelope를 읽는 곳: V2 `src/adapters/http/schema-registry.ts`와 `src/adapters/http/client.ts`. V3 실행기는 Envelope 없이 DTO를 검증한다 (`src/adapters/http/index.ts` V2 주석). +- 실패 Envelope의 `error.code`가 "적용 안 됨"인지는 6.1절이 정한다. ### 4.2 Status와 error @@ -241,16 +242,81 @@ backend idempotency를 대체하지 않는다. - 정본: [`clean-architecture-backend-template/docs/web/http-contract.md`](../../../clean-architecture-backend-template/docs/web/http-contract.md) 2절 "멱등성 응답", 4절 "web 전용 오류 코드" -- 기준 버전: 4.1절과 같다(백엔드 리뷰 2026-11-01 15절 결정, 2026-11-03). +- 기준 커밋: 4.1절과 같다(백엔드 `5786126c`). - 프론트가 그 응답을 읽는 곳: - 키 생성·검사: `src/contracts/mutation-intent.ts` `isValidIdempotencyKey` - 결과 불명 재전송이 같은 키를 쓰고 `Retry-After`까지 기다리는 곳: `src/presentation/adapters/query/application-query.ts` - - V2 거절 판정: `src/adapters/http/client.ts` `IDEMPOTENCY_REFUSALS` + - V2 거절 판정: `src/adapters/http/client.ts` `IDEMPOTENCY_REFUSALS`와 + `fieldValidation` - V3 참조 기능 판정: `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts` (effect), `src/features/reference-feature/adapters/reference-http-gateway.ts` (code) +### 6.1 거절 code와 적용 여부 + +mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐는지 정해야 한다. + +- `NOT_APPLIED`: 쓰기 전에 거절됐다. 다음 저장은 새 `Idempotency-Key`를 쓴다. +- `MAYBE_APPLIED`: 쓰기 뒤에도 나올 수 있다. mutation 코디네이터가 키를 붙들고 + 결과 불명으로 보인다. effect가 없는 실패도 이 값이다. + +백엔드 `http-contract.md`는 code가 어느 단계에서 나오는지 적지 않는다. 아래 표는 +프론트가 백엔드 `5786126c`의 코드를 읽고 정한 판정이다. 같은 code가 쓰기 전과 +뒤에서 모두 나오면 "쓰기 뒤 가능"으로 둔다. 프론트는 code만 보고 둘을 가를 수 +없다. + +| code (status) | 나오는 곳 | 단계 | 프론트 결과 | 백엔드 파일:줄 | +| --- | --- | --- | --- | --- | +| `VALIDATION_FAILED` (400), details = 필드 목록 | 요청 본문 `@Valid` 실패, 컨트롤러 파라미터 제약 실패. 컨트롤러 메서드가 불리기 전 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:218-231`, `:346-368` | +| `VALIDATION_FAILED` (400), details = 필드 목록 | `ConstraintViolationException`. 어느 층에서 던져도 이 handler가 받는다. 요청 경로에서 던지는 코드는 없다(application bean에 `@Validated` 없음, JPA entity에 Bean Validation 제약 없음, 직접 throw 없음) | 쓰기 전(현재 출처 없음) | `NOT_APPLIED` | `GlobalExceptionHandler.java:101-106` | +| `VALIDATION_FAILED` (400), details = `{cause}` 또는 없음 | 본문을 읽지 못함(`HttpMessageNotReadableException`) | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:233-251` | +| `VALIDATION_FAILED` (400), details = `{field, code}` | 페이지·정렬 파라미터. 목록 GET 컨트롤러가 use case 전에 검사한다 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:149-153`, `PageParams.java:27-33`, `SortParam.java:16-43` | +| `IDEMPOTENCY_KEY_INVALID` (400) | KEYED 컨트롤러 첫 줄의 키 파싱 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyKeyHeader.java:32-38`, `PosterImagePublicationController.java:64` | +| `IDEMPOTENT_REQUEST_MISMATCH` (422) | 멱등성 executor가 action 전에 판정 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyExecutor.java:102-103`, `:134-135` | +| `IDEMPOTENT_IN_FLIGHT` (409) | 멱등성 executor가 action 전에 판정. 같은 키의 앞선 요청이 실행 중이다 | 이번 요청은 쓰기 전. 앞선 요청은 적용될 수 있다 | `MAYBE_APPLIED` | `IdempotencyExecutor.java:104-105`, `:136-137` | +| `BAD_PARAMETER` (400) | 타입 변환 실패, 필수 파라미터·헤더 없음(쓰기 전). **어느 층이든 `IllegalArgumentException`**(use case·domain 포함) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `GlobalExceptionHandler.java:92-99`, `:108-116`, `:397-438` | +| `MAPPING_FAILED` (400) | web 매퍼(쓰기 전), outbound ACL 매퍼(use case 안), 멱등성 응답 직렬화(action이 끝난 뒤) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `WorkLogWebMapper.java:36`, `RepoStatsAclMapper.java:14`, `JsonIdempotentResponseCodec.java:32`, `IdempotencyExecutor.java:229` | +| `DB_SERIALIZATION_FAILURE`, `DB_DEADLOCK`, `DB_LOCK_TIMEOUT`, `DB_NULL_VIOLATION`, `DB_FK_VIOLATION`, `DB_UNIQUE_VIOLATION`, `DB_CHECK_VIOLATION`, `DB_OPTIMISTIC_CONFLICT` (409) | persistence 어댑터가 SQL·JPA 실패를 바꾼 것. 트랜잭션 안이나 commit에서 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `FailureCategory.java:79-95`, `StandardSqlStateErrorMapping.java:46-52`, `PersistenceExceptionTranslator.java:131` | +| `LOCK_ACQUISITION_TIMEOUT` (409) | 분산 락 대기 초과. use case 안 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `LockRegistryDistributedLock.java:50`, `:53` | +| 참조 도메인 `WORKLOG_INVALID`, `POSTER_INVALID_STATE`, `POSTER_IMAGE_REQUIRED` (400), `WORKLOG_CONFLICT`, `POSTER_ALREADY_EXISTS`, `POSTER_IMAGE_ALREADY_PUBLISHED` (409) | application·domain 예외 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `DomainExceptionHandler.java:52-90` | +| 선택 모듈 web-advanced `PATCH_REJECTED` (400), `PATCH_TEST_FAILED` (409) | patch 라이브러리. 부르는 코드가 단계를 정한다 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `src/adapter/inbound/web-advanced/README.md` 「오류 응답」 | +| 선택 모듈 fileserver `BAD_REQUEST` (400), `FILE_ALREADY_EXISTS`, `FILE_NOT_READY`, `UPLOAD_OFFSET_MISMATCH`, `CONCURRENT_MODIFICATION` (409), `INTEGRITY_MISMATCH`, `MALWARE_DETECTED`, `INVALID_PATH`, `PATH_OUTSIDE_NAMESPACE` (422) | application·outbound 층. `INTEGRITY_MISMATCH`·`MALWARE_DETECTED`는 레코드를 `REJECTED`로 쓴 뒤 던진다 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `FileserverErrorCode.java:26-44`, `FinalizeUploadApplicationUseCase.java:211-224`, `:336-341` | + +- application-notification의 `VALIDATION_FAILED`(`NotificationFailureCode`)는 + `ApiErrorCarrier`가 아니다. HTTP로는 500 `INTERNAL_ERROR`로 나가므로 표에 없다. +- 표에 없는 400·409·422 code는 `MAYBE_APPLIED`로 본다. +- 파일 위치(백엔드 repo 기준): + - `GlobalExceptionHandler.java`: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/` + - `PageParams.java`, `SortParam.java`: 같은 모듈 `.../web/pagination/` + - `IdempotencyKeyHeader.java`: 같은 모듈 `.../web/http/` + - `IdempotencyExecutor.java`: `src/application-core/src/main/java/dev/caskeleton/application/idempotency/` + - `JsonIdempotentResponseCodec.java`: `src/adapter/inbound/web-advanced/.../advanced/idempotency/` + - `FailureCategory.java`, `StandardSqlStateErrorMapping.java`, + `PersistenceExceptionTranslator.java`, `LockRegistryDistributedLock.java`: + `src/adapter/outbound/persistence-jpa/` + - `PosterImagePublicationController.java`, `WorkLogWebMapper.java`, + `RepoStatsAclMapper.java`, `DomainExceptionHandler.java`: `src/sample-portfolio/` + - `FileserverErrorCode.java`, `FinalizeUploadApplicationUseCase.java`: + `src/application-fileserver/` + +프론트 판정과 표가 다른 곳(고치면 이 줄을 지운다): + +- 필드 목록이 없는 400 `VALIDATION_FAILED`(`{cause}`, details 없음, + `{field, code}`)는 표로는 `NOT_APPLIED`다. V2(`client.ts` `fieldValidation`)는 + effect를 붙이지 않아 `MAYBE_APPLIED`가 된다. +- V2는 code와 상관없이 422를 모두 `NOT_APPLIED`로 본다. 기본 배포의 422는 + `IDEMPOTENT_REQUEST_MISMATCH` 하나라 맞다. fileserver를 실은 배포의 422 4종은 + 표로는 `MAYBE_APPLIED`다. +- V3 참조 기능 분류기(`classifyProblem`)는 참조 fixture(problem+json)용이라 + 400·422를 모두 `NOT_APPLIED`로 본다. V3를 짝 백엔드에 붙이면 + `BAD_PARAMETER`, `MAPPING_FAILED`, 도메인 400이 틀린다. + +남은 위험: "쓰기 전"은 현재 코드에서 그 handler에 닿는 출처를 센 결과다. 백엔드가 +application bean에 `@Validated`를 달거나 JPA entity에 Bean Validation 제약을 +넣으면, 필드 목록이 있는 400 `VALIDATION_FAILED`가 use case 안에서도 나온다. +백엔드에는 이것을 막는 검사가 없다. + ## 7. Cursor pagination과 snapshot Backend가 pagination을 선택할 때 새 response schema/operation version으로 다음 From 8a09c903791e17c454fe2aeae8bb7a57a5337d89 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:17:35 +0900 Subject: [PATCH 05/16] =?UTF-8?q?fix(forms):=20=EC=A7=9D=20=EB=B0=B1?= =?UTF-8?q?=EC=97=94=EB=93=9C=20=ED=95=84=EB=93=9C=20=EA=B2=80=EC=A6=9D=20?= =?UTF-8?q?code=EB=A7=88=EB=8B=A4=20=EB=AC=B8=EA=B5=AC=EB=A5=BC=20?= =?UTF-8?q?=EB=B3=B4=EC=9D=B8=EB=8B=A4=20(1101/14.4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 짝 백엔드는 필드 검증 실패의 details[].code에 NOT_BLANK, SIZE 같은 자기 code를 싣는다(백엔드 5786126c ClientSafeValidationDetails.java RULES 18-42와 INVALID). 폼 문구 표(form-contracts.ts VALIDATION_COPY)에는 zod code와 REQUIRED만 있어서, 백엔드 code는 모두 form.validation.unknown("입력값을 확인해 주세요.")이 된다. 필드 위치는 맞지만 무엇이 틀렸는지 알 수 없다. 고른 방법 - VALIDATION_COPY에 백엔드 code 20개를 모두 넣었다. 뜻이 같은 것은 기존 키를 쓴다: NOT_NULL·NOT_BLANK·NOT_EMPTY → required, PATTERN → invalidFormat, TYPE_MISMATCH → invalidType, ASSERT_TRUE·ASSERT_FALSE → invalidValue. - 나머지 13개는 새 키로 ko-KR·en-US 문구를 넣었다(size, min, max, positive, positiveOrZero, negative, negativeOrZero, email, past, pastOrPresent, future, futureOrPresent, invalid). ar-EG는 en-US 표를 그대로 쓴다. - 모르는 code는 그대로 form.validation.unknown이다. - 백엔드 code를 쓰는 곳은 V2 client가 이미 details[].code를 issue code로 넘기는 경로(errors.ts safeValidationIssues)라 표 한 곳만 바꿨다. 버린 대안 - SIZE를 tooSmall·tooBig에 맞추기: SIZE는 짧은지 긴지 말하지 않는다. 한쪽 문구를 고르면 틀린 말을 할 수 있다. - 백엔드가 보낸 message를 보여 주기: 백엔드 문구를 화면에 그리지 않는 규칙 (check-i18n rawFailureRender, errors.ts)을 깬다. 한국어만 있다. - 백엔드 소스에서 code 목록을 읽는 검사: 두 repo가 나란히 있어야 돈다. 목록은 테스트에 SHA와 함께 적었다. 위험·한계 - 백엔드가 code를 더하면 프론트는 알지 못하고 기본 문구가 나온다. 알아챌 방법은 백엔드가 code 목록을 문서나 레지스트리로 내주는 것이다(최종 보고에 제안). - 페이지·정렬 파라미터 code(PAGE_NEGATIVE, SIZE_EXCEEDS_MAX 등)는 details가 배열이 아니라 폼 issue가 되지 않으므로 넣지 않았다. - 초기 JS gzip 202,770 → 203,165 B(+395, 예산 204,800). i18n catalog가 초기 청크에 있다. 검증 - RED: tests/component/form-foundation.test.tsx 3행 실패. ko-KR·en-US 모두 백엔드 code 20개가 기본 문구였고, 400 VALIDATION_FAILED NOT_BLANK 행은 "Name: 입력값을 확인해 주세요."를 보였다. - GREEN: 위 3행과 "keeps the default copy for a code it does not know" 통과. tests/component·unit·features 237 files 2951 tests 통과. - node scripts/generate-product-feature-index.ts && node scripts/check-i18n.ts: 237 keys across 4 locales PASS. node scripts/check-registries.ts: PASS, compatibility=none. - tsc app·test 통과, 바꾼 파일 eslint 통과. - 초기 JS는 기준 트리와 이 트리를 각각 build-frontend.ts로 빌드하고 check-bundle.ts와 같은 방식(classifyViteJavascript initialFiles, gzipSync)으로 쟀다. check-bundle.ts는 pnpm이 만드는 bundle.json이 필요해 돌리지 않았다. Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.4 --- src/presentation/forms/form-contracts.ts | 24 ++++++++++ src/presentation/i18n/catalog.ts | 26 +++++++++++ tests/component/form-foundation.test.tsx | 58 ++++++++++++++++++++++++ 3 files changed, 108 insertions(+) diff --git a/src/presentation/forms/form-contracts.ts b/src/presentation/forms/form-contracts.ts index c432ef1b..d424b6e3 100644 --- a/src/presentation/forms/form-contracts.ts +++ b/src/presentation/forms/form-contracts.ts @@ -37,6 +37,30 @@ const VALIDATION_COPY = Object.freeze({ invalid_type: "form.validation.invalidType", invalid_format: "form.validation.invalidFormat", invalid_value: "form.validation.invalidValue", + // 1101/14.4. The paired backend's field codes, every one it can send + // (clean-architecture-backend-template 5786126c, + // ClientSafeValidationDetails.java RULES and INVALID). A code it adds later + // shows form.validation.unknown until it gets a row here. + NOT_NULL: "form.validation.required", + NOT_BLANK: "form.validation.required", + NOT_EMPTY: "form.validation.required", + SIZE: "form.validation.size", + MIN: "form.validation.min", + MAX: "form.validation.max", + POSITIVE: "form.validation.positive", + POSITIVE_OR_ZERO: "form.validation.positiveOrZero", + NEGATIVE: "form.validation.negative", + NEGATIVE_OR_ZERO: "form.validation.negativeOrZero", + PATTERN: "form.validation.invalidFormat", + EMAIL: "form.validation.email", + PAST: "form.validation.past", + PAST_OR_PRESENT: "form.validation.pastOrPresent", + FUTURE: "form.validation.future", + FUTURE_OR_PRESENT: "form.validation.futureOrPresent", + ASSERT_TRUE: "form.validation.invalidValue", + ASSERT_FALSE: "form.validation.invalidValue", + TYPE_MISMATCH: "form.validation.invalidType", + INVALID: "form.validation.invalid", }); type MessageResolver = (key: ParameterlessMessageKey) => string; diff --git a/src/presentation/i18n/catalog.ts b/src/presentation/i18n/catalog.ts index 03a0f202..7f31d496 100644 --- a/src/presentation/i18n/catalog.ts +++ b/src/presentation/i18n/catalog.ts @@ -140,6 +140,19 @@ const PLATFORM_KO_MESSAGES = { "form.validation.invalidType": "입력 형식을 확인해 주세요.", "form.validation.invalidFormat": "입력 형식을 확인해 주세요.", "form.validation.invalidValue": "허용된 값을 선택해 주세요.", + "form.validation.size": "길이나 개수가 허용 범위를 벗어났습니다.", + "form.validation.min": "허용된 최솟값보다 작습니다.", + "form.validation.max": "허용된 최댓값보다 큽니다.", + "form.validation.positive": "0보다 큰 값을 입력해 주세요.", + "form.validation.positiveOrZero": "0 이상의 값을 입력해 주세요.", + "form.validation.negative": "0보다 작은 값을 입력해 주세요.", + "form.validation.negativeOrZero": "0 이하의 값을 입력해 주세요.", + "form.validation.email": "이메일 주소 형식을 확인해 주세요.", + "form.validation.past": "지난 시각을 입력해 주세요.", + "form.validation.pastOrPresent": "앞으로의 시각은 입력할 수 없습니다.", + "form.validation.future": "앞으로의 시각을 입력해 주세요.", + "form.validation.futureOrPresent": "지난 시각은 입력할 수 없습니다.", + "form.validation.invalid": "올바른 값을 입력해 주세요.", "form.validation.unknown": "입력값을 확인해 주세요.", "form.validation.retry": "입력값을 다시 확인해 주세요.", "form.validation.unknownField": @@ -339,6 +352,19 @@ const PLATFORM_EN_MESSAGES = { "form.validation.invalidType": "Check the input type.", "form.validation.invalidFormat": "Check the input format.", "form.validation.invalidValue": "Choose an allowed value.", + "form.validation.size": "The length or count is outside the allowed range.", + "form.validation.min": "This value is below the allowed minimum.", + "form.validation.max": "This value is above the allowed maximum.", + "form.validation.positive": "Enter a value greater than 0.", + "form.validation.positiveOrZero": "Enter 0 or a greater value.", + "form.validation.negative": "Enter a value less than 0.", + "form.validation.negativeOrZero": "Enter 0 or a smaller value.", + "form.validation.email": "Check the email address format.", + "form.validation.past": "Enter a time in the past.", + "form.validation.pastOrPresent": "A future time is not allowed.", + "form.validation.future": "Enter a time in the future.", + "form.validation.futureOrPresent": "A past time is not allowed.", + "form.validation.invalid": "Enter a valid value.", "form.validation.unknown": "Check the entered value.", "form.validation.retry": "Review the entered values.", "form.validation.unknownField": diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index 26c0bca2..df0233e1 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -22,7 +22,12 @@ import { FormField, useAppForm, useDirtyNavigationGuard, + validationMessage, } from "../../src/presentation/forms/index.ts"; +import { + formatMessage, + type ParameterlessMessageKey, +} from "../../src/presentation/i18n/index.ts"; type Values = Readonly>; @@ -206,6 +211,8 @@ describe("local form facade", () => { expect(screen.getByRole("textbox", { name: /Note/ })).not.toHaveAttribute( "aria-invalid", ); + // NOT_BLANK has its own copy, not the "check the value" default. + expect(screen.getByRole("alert")).toHaveTextContent("필수 입력값입니다."); // A class-level error names no form field. expect(screen.getByRole("alert")).toHaveTextContent( "서버가 확인하지 못한 입력 항목", @@ -448,6 +455,57 @@ describe("local form facade", () => { }); }); +// 1101/14.4. Every code the paired backend can put in a field error's +// details[].code: clean-architecture-backend-template 5786126c, +// ClientSafeValidationDetails.java RULES (18-42) and its INVALID fallback. +// http-contract.md §4 names the shape, not the list. A code missing from the +// form copy table shows the "check the value" default instead. +const BACKEND_FIELD_CODES = [ + "NOT_NULL", + "NOT_BLANK", + "NOT_EMPTY", + "SIZE", + "MIN", + "MAX", + "POSITIVE", + "POSITIVE_OR_ZERO", + "NEGATIVE", + "NEGATIVE_OR_ZERO", + "PATTERN", + "EMAIL", + "PAST", + "PAST_OR_PRESENT", + "FUTURE", + "FUTURE_OR_PRESENT", + "ASSERT_TRUE", + "ASSERT_FALSE", + "TYPE_MISMATCH", + "INVALID", +] as const; + +describe("paired backend field codes", () => { + it.each(["ko-KR", "en-US"] as const)( + "gives every backend field code its own %s copy", + (locale) => { + const message = (key: ParameterlessMessageKey) => + formatMessage(locale, key); + const fallback = message("form.validation.unknown"); + + expect( + BACKEND_FIELD_CODES.filter( + (code) => validationMessage(code, message) === fallback, + ), + ).toEqual([]); + }, + ); + + it("keeps the default copy for a code it does not know", () => { + expect(validationMessage("SOME_FUTURE_CODE")).toBe( + formatMessage("ko-KR", "form.validation.unknown"), + ); + }); +}); + describe("dirty navigation guard", () => { it("blocks navigation, restores focus on stay and proceeds explicitly", async () => { const user = userEvent.setup(); From e5b7b3e8570851dc7c74a70515ad3aa8ab79a134 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:18:49 +0900 Subject: [PATCH 06/16] =?UTF-8?q?fix(storage):=20partition=20=EC=82=AD?= =?UTF-8?q?=EC=A0=9C=EA=B0=80=20=EB=8B=A4=EB=A5=B8=20=ED=83=AD=EC=9D=98=20?= =?UTF-8?q?=EC=A7=84=ED=96=89=20=EC=A4=91=EC=9D=B8=20put=EC=9D=84=20?= =?UTF-8?q?=EA=B8=B0=EB=8B=A4=EB=A6=B0=EB=8B=A4=20(0929/05-01)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 손상 때문에 끝나지 못한 LOGOUT·ACCOUNT_DELETION purge의 partition 삭제는 두 단계다. 디렉터리를 origin lease 안에서 지우고, 이어서 journal row를 lease 밖에서 지운다. origin lease는 put의 BEGIN~FINISH만 막는다. 그래서 다른 탭에서 journal `begin`을 끝낸 put이 두 단계 사이에 BEGIN을 하면 새 디렉터리에 파일을 쓰고, 두 번째 단계가 그 put의 row를 지운다. put은 다음 journal 단계에서 `CONFLICT`로 실패하지만 파일을 치울 주체가 없다. - markFilesReady 전에 row가 지워지면: 보상이 manifest·staging을 지우고 chunk가 남는다. - commitPut 전에 지워지면: 보상이 없어 manifest·FILES_READY staging receipt·chunk가 남는다. staging receipt가 chunk를 GC·sweep에서 지키고 row가 없어 reconcile도 보지 않으므로 영원히 남는다. 다음 LOGOUT purge는 `chunkSweep: COMPLETED`를 보고하면서 이 bytes를 남긴다. - commit 뒤 complete 전에 지워지면: put은 성공하지만 object는 없고 manifest·chunk가 남는다. 삭제 전체가 put의 FINISH~commit 사이에 들어가는 경우(72edb55가 가정한 경우)는 수정 전에도 put이 `CONFLICT`로 실패하고 bytes가 남지 않았다. 고른 방법: partition 단위 Web Lock (`:partition:::

`)을 둔다. 모든 put·delete는 `withTransactionLock` 안에서 journal `begin`부터 끝날 때까지 shared로 쥐고, partition 삭제는 디렉터리·journal 두 단계를 exclusive로 쥔 채 한다. mutation은 삭제 전체보다 앞이거나 뒤에만 놓인다. 진행 중이던 put은 끝난 뒤 삭제가 지우고, 삭제가 lock을 요청한 뒤 온 put은 삭제 뒤에 돈다. lock 순서는 partition lock → origin lease 하나뿐이라 교착이 없다 (per-transaction lock은 `ifAvailable`이라 기다리지 않는다). 기다리는 동안 purge `signal`을 abort하면 `ABORTED`를 반환한다. 버린 대안: - commitPut `CONFLICT`면 보상: commitPut 전 경우만 고치고 chunk와 commit 뒤 경우가 남는다. 또 port가 "CONFLICT = 아무것도 commit 안 됨"을 약속하지 않아 동봉 구현에 기대는 숨은 결합이 생긴다. - commit까지 origin lease 쥐기: lease는 worker 안에 있고 journal은 page 쪽이다. 두 번째 단계(row 삭제)가 lease를 쓰지 않아 commitPut 전 경우가 그대로다. - row를 먼저 지우고 디렉터리를 나중에: 그 사이 begin한 put이 디렉터리 단계 전에 FINISH하면 파일 없는 COMMITTED row가 생긴다. 중간 실패 뒤 재호출로 이어서 끝나는 성질도 잃는다. - 디렉터리 → row → 디렉터리: 같은 이유로 파일 없는 commit이 생긴다. 위험·한계: - 삭제는 진행 중인 put·delete를 기다린다. source가 멈춘 put은 put idle bound(05-07)까지 삭제를 붙잡는다. 수정 전에도 그 put은 origin lease를 쥐고 있어 디렉터리 단계가 같은 시간을 기다렸다. - reconcile은 partition lock을 쥐지 않는다. reconcile은 파일을 새로 쓰지 않으므로(검증·정리·finalize만) 삭제와 겹쳐도 bytes를 남기지 않는다고 보았고, 이 경우는 테스트하지 않았다. - put·delete마다 Web Lock 요청이 하나 늘어난다. - offline-indexeddb 레시피 gzip 37,327 → 37,423 B(한도 38,500). - 공개 타입·배럴 변경 없음. 검증: - RED(수정 전, put 결과 단언을 넣기 전): 새 it.each 5건 중 3건 실패. 디렉터리를 put BEGIN 전에 지운 경우만 실패했다. markFilesReady 앞: chunk 1개 남음. commitPut 앞: staging receipt·chunk· manifest 남음. complete 앞: chunk·manifest 남음. 삭제 전체가 FINISH~commit 사이인 2건은 통과(put CONFLICT, bytes 0). "put은 삭제 앞에 끝난다" 단언을 더한 뒤 수정 전 코드: 5건 모두 실패. - GREEN: 5건 + abort 테스트 1건 통과. 같은 5건 10회 반복 10/10. - `node scripts/run-vitest.ts run tests/unit/opfs-worker-runtime.test.ts tests/unit/opfs-byte-store.test.ts tests/unit/indexeddb-opfs-journal.test.ts tests/recipes` 136건 통과. - tsc app·test·web-worker·recipes 통과. 바꾼 파일 eslint 통과. `check-adapter-inventory` PASS, `check-optional-recipes`(source) PASS, `verify-documentation-readiness` PASS_SCOPED. - 미실행: `check:browser-file-storage-boundaries`·`check:architecture` (pnpm 필요), Playwright OPFS spec(webServer가 pnpm). Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.4 --- .../browser-file-storage-recovery.md | 26 ++- .../storage/opfs/opfs-byte-store-adapter.ts | 68 ++++++-- tests/unit/opfs-worker-runtime.test.ts | 161 ++++++++++++++++++ 3 files changed, 238 insertions(+), 17 deletions(-) diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index 9a99dff5..66ae77e5 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -462,12 +462,26 @@ VD-15 목표 runtime을 먼저 구현한다. `corruptObjects`. 이 report면 그 partition의 bytes는 모두 지워진 것이다. `chunkSweep`은 없다. 디렉터리는 지웠는데 journal 정리가 실패하면 실패를 반환한다. 같은 purge를 다시 호출하면 이어서 끝난다. - - 한계: lease는 put의 streaming 구간(BEGIN~FINISH)만 막는다. 그 밖에 있던 다른 - tab의 같은 partition put은 journal row가 지워져 다음 journal 단계에서 - fencing 검사에 걸려 실패할 것으로 본다. 이 경합은 실행으로 확인하지 않았다. - purge가 시작된 뒤 새로 시작한 put의 데이터는 다른 purge처럼 남는다 - (point-in-time). purge 전에 그 partition의 쓰기를 멈추는 것이 composition의 - 몫이다. + - 다른 tab의 put·delete와의 순서: 모든 put·delete는 journal `begin`부터 끝날 + 때까지 partition lock(Web Lock + `:partition:::`)을 + shared로 쥐고, partition 삭제는 디렉터리·journal 두 단계를 그 lock을 + exclusive로 쥔 채 한다. 그래서 진행 중이던 put은 삭제 전에 끝나고 삭제가 + 그 결과까지 지운다. 삭제가 기다리는 동안 새로 온 put은 삭제 뒤에 돈다 + ([0929] 05-01, `opfs-byte-store-adapter.ts` `withPartitionLock`). + origin lease는 put의 BEGIN~FINISH만 막으므로 이 lock이 없을 때는, 삭제의 + 디렉터리 단계가 다른 tab put의 BEGIN보다 먼저 끝나면 그 put이 새 디렉터리에 + 파일을 쓰고 journal 단계가 그 row를 지워 파일을 치울 주체가 없었다(commit + 전이면 manifest·staging receipt·chunk, commit 뒤면 manifest·chunk가 남음). + 삭제 전체가 put의 FINISH~commit 사이에 들어가는 경우는 그때도 put이 + `CONFLICT`로 실패하고 bytes가 남지 않았다. 막는 테스트: + `tests/unit/opfs-worker-runtime.test.ts` "leaves no partition bytes when an + approved purge meets another tab's put parked before …"(5가지 순서). + - 한계: 삭제는 진행 중인 put·delete를 기다린다. source가 멈춘 put은 put idle + bound(05-07)까지 삭제를 붙잡는다. purge의 `signal`을 abort하면 기다림을 + 멈추고 `ABORTED`를 반환한다. 삭제가 lock을 요청한 뒤 온 put의 데이터는 다른 + purge처럼 남는다(point-in-time). purge 전에 그 partition의 쓰기를 멈추는 + 것이 composition의 몫이다. - lock/worker 문제면 OPFS write off → approved capped fallback 또는 online-only - scope binding mismatch면 affected scope를 read-only로 격리하고 registry/ composition을 forward fix; 다른 token path로 bytes를 이동하거나 추측 복구 금지 diff --git a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts index 14afe5ab..0f68c3f6 100644 --- a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts +++ b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts @@ -101,6 +101,8 @@ export type OpfsByteStoreDependencies = Readonly<{ * holds an exclusive per-transaction lock from journal `begin` until it * returns; reconcile only touches rows whose lock it can take at once, so a * live transaction in any tab is never cleaned up underneath its owner. + * [0929] 05-01. It also holds the partition lock shared over the same span; + * a partition delete takes that lock exclusive (`withPartitionLock`). */ lockManager?: Pick; now?: () => number; @@ -914,23 +916,30 @@ export function createOpfsByteStoreAdapter( // under the origin lease and then the partition's journal rows. Both // are keyed by this partition's tokens alone; no other partition is // touched. Like that delete, this step is not bounded by the budget. + // Both steps run under the exclusive partition lock, so they first + // wait for every put and delete of the partition in any tab. const partitionDeleted = sweeping && (corruptObjects > 0 || damaged) && !request.signal?.aborted; if (partitionDeleted) { - const removedFiles = await dependencies.worker.removePartition( - dependencies.scope, + const removed = await withPartitionLock( + "exclusive", + "OBJECT_RECONCILE", request.signal, + async () => { + const removedFiles = await dependencies.worker.removePartition( + dependencies.scope, + request.signal, + ); + if (!removedFiles.ok) return removedFiles; + return await dependencies.journal.removePartition( + dependencies.scope, + ); + }, ); - if (!removedFiles.ok) { - return rebaseFailure(removedFiles.error, "OBJECT_RECONCILE"); - } - const removedRows = await dependencies.journal.removePartition( - dependencies.scope, - ); - if (!removedRows.ok) { - return rebaseFailure(removedRows.error, "OBJECT_RECONCILE"); + if (!removed.ok) { + return rebaseFailure(removed.error, "OBJECT_RECONCILE"); } chunkSweep = undefined; moreObjectsAvailable = false; @@ -1106,12 +1115,49 @@ export function createOpfsByteStoreAdapter( // A fresh transaction id is never held; a holder means a duplicate id. if (!release) return browserDataFailure("CONFLICT", operation); try { - return await run(); + return await withPartitionLock("shared", operation, undefined, run); } finally { release(); } } + /** + * [0929] 05-01. Every put and delete of this partition holds this lock + * shared from journal `begin` until it returns, and the partition delete + * holds it exclusive over both of its steps, so a mutation lies wholly + * before or wholly after that delete. The origin lease covers a put only + * from BEGIN to FINISH: without this, a put begun in another tab wrote its + * files after the directory went, the second step took its journal row, and + * nothing was left to clean those files. Tested by "leaves no partition + * bytes when an approved purge meets another tab's put parked before …". + */ + async function withPartitionLock( + mode: LockMode, + operation: BrowserDataOperation, + signal: AbortSignal | undefined, + run: () => Promise>, + ): Promise> { + let granted = false; + try { + return await requestLock( + `${policy.mutationLockName}:partition:${scope.authorityToken}:${scope.namespaceToken}:${scope.partitionToken}`, + { mode, ...(signal ? { signal } : {}) }, + async () => { + granted = true; + return await run(); + }, + ); + } catch (error) { + if (granted) throw error; + return signal?.aborted + ? browserDataFailure("ABORTED", operation) + : browserDataFailure("UNAVAILABLE", operation, { + retryable: true, + recovery: "RETRY", + }); + } + } + /** * STO-01. The compensating half of the put saga. * diff --git a/tests/unit/opfs-worker-runtime.test.ts b/tests/unit/opfs-worker-runtime.test.ts index 07059c1a..e3514111 100644 --- a/tests/unit/opfs-worker-runtime.test.ts +++ b/tests/unit/opfs-worker-runtime.test.ts @@ -2651,8 +2651,169 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh expect(root.has(partitionPath(scopeP2))).toBe(true); expect(leases.held).toBe(false); }); + + // [0929] 05-01. The origin lease covers a put only from BEGIN to FINISH, and + // the partition delete runs in two steps: the directory under that lease, + // then the journal rows. Another tab's put that had begun before the purge + // was not checked once it left the lease. Each case parks that put at a + // journal step past FINISH, and optionally lets the purge remove the + // directory before the put reaches BEGIN, so the rows go while it is parked. + it.each([ + ["markFilesReady", false], + ["commitPut", false], + ["markFilesReady", true], + ["commitPut", true], + ["complete", true], + ] as const)( + "leaves no partition bytes when an approved purge meets another tab's put parked before %s (directory removed before its BEGIN: %s)", + async (parkedStep, directoryFirst) => { + const { root, leases, idb, tab } = sharedRootTabs(); + const runtime = () => + createOpfsWorkerRuntime({ + root: root as unknown as FileSystemDirectoryHandle, + crypto: globalThis.crypto, + policy: runtimePolicy, + leaseManager: leases, + dedicatedWorker: true, + supportsSynchronousAccessHandles: false, + }); + const journal = createIndexedDbOpfsJournal({ + authorityToken: scopeA.authorityToken, + factory: idb.factory, + keyRange: idb.keyRange, + }); + const beforeBegin = checkpoint(); + const parked = checkpoint(); + const rowsPending = checkpoint(); + const writerWorker = loopbackGateway(runtime()); + const writer = tab("w", { + journal: { + ...journal, + [parkedStep]: async ( + ...input: Parameters + ) => { + await parked.pass(); + return await ( + journal[parkedStep] as (...args: typeof input) => unknown + )(...input); + }, + } as OpfsJournalPort, + worker: { + ...writerWorker, + async preparePut(input) { + if (directoryFirst) await beforeBegin.pass(); + return await writerWorker.preparePut(input); + }, + }, + }); + const purgerWorker = loopbackGateway(runtime()); + const purger = tab("p", { + ...authority, + worker: { + ...purgerWorker, + async removePartition(scope, signal) { + const removed = await purgerWorker.removePartition(scope, signal); + await rowsPending.pass(); + return removed; + }, + }, + }); + expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true }); + idb.seed("opfs-objects", corruptObjectRow(scopeA, "object_secret_2")); + const settle = (step: Promise) => + Promise.race([ + step, + new Promise((resolve) => setTimeout(resolve, 100)), + ]); + + const put = putBytes(writer, "object_inflight1", [8, 8]); + let purge: ReturnType; + if (directoryFirst) { + // The put's journal row is PREPARING; it has written nothing yet. + await beforeBegin.reached; + purge = purger.maintenance.enforcePolicies({ reason: "ACCOUNT_DELETION" }); + await settle(rowsPending.reached); + beforeBegin.open(); + await parked.reached; + } else { + await parked.reached; + purge = purger.maintenance.enforcePolicies({ reason: "ACCOUNT_DELETION" }); + } + rowsPending.open(); + await settle(purge); + parked.open(); + const [report, written] = await Promise.all([purge, put]); + + // The put lies wholly before the partition delete, which then takes it. + expect(written).toMatchObject({ ok: true, value: { generation: 1 } }); + expect(report).toMatchObject({ + ok: true, + value: { partitionDeleted: true, moreObjectsAvailable: false }, + }); + expect(filesUnder(root, scopeA)).toEqual([]); + expect(idb.readRaw("opfs-journal", "transaction_w_1")).toBeUndefined(); + expect(await openedBytes(writer, "object_inflight1")).toBe("NOT_FOUND"); + }, + ); + + it("stops a partition delete that waits on another tab's put when the purge is aborted", async () => { + const { root, idb, tab } = sharedRootTabs(); + const purger = tab("p", authority); + expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true }); + idb.seed("opfs-objects", corruptObjectRow(scopeA, "object_secret_2")); + const lockName = `${runtimePolicy.mutationLockName}:partition:${scopeA.authorityToken}:${scopeA.namespaceToken}:${scopeA.partitionToken}`; + const putHolding = checkpoint(); + // Stands in for a put of this partition in another tab. + const holder = navigator.locks.request(lockName, { mode: "shared" }, () => + putHolding.pass(), + ); + await putHolding.reached; + const controller = new AbortController(); + + const purge = purger.maintenance.enforcePolicies({ + reason: "ACCOUNT_DELETION", + signal: controller.signal, + }); + while ( + !(await navigator.locks.query()).pending?.some( + (lock) => lock.name === lockName && lock.mode === "exclusive", + ) + ) { + await new Promise((resolve) => setTimeout(resolve, 1)); + } + controller.abort(); + + expect(await purge).toMatchObject({ ok: false, error: { code: "ABORTED" } }); + expect(filesUnder(root, scopeA)).not.toEqual([]); + putHolding.open(); + await holder; + }); }); +/** A step that parks until opened and says when something reached it. */ +function checkpoint(): Readonly<{ + reached: Promise; + pass: () => Promise; + open: () => void; +}> { + let reach!: () => void; + const reached = new Promise((resolve) => { + reach = resolve; + }); + let open!: () => void; + const opened = new Promise((resolve) => { + open = resolve; + }); + return { + reached, + open, + async pass() { + reach(); + await opened; + }, + }; +} + describe("05-07 a put whose source stops lets go of the origin lock", () => { afterEach(() => { vi.useRealTimers(); From 17fa8d1f653e59ea1fdb75162e3cf973ef8b8da2 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:21:30 +0900 Subject: [PATCH 07/16] =?UTF-8?q?fix(realtime):=20live-poll=20handoff=20?= =?UTF-8?q?=EB=A7=88=EA=B0=90=20=EC=8B=A4=ED=8C=A8=EB=A5=BC=2013.1?= =?UTF-8?q?=EC=9D=98=20kind=EB=A1=9C=20=EB=B3=B4=EA=B3=A0=ED=95=9C?= =?UTF-8?q?=EB=8B=A4=20(04-02)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 1196b86은 stream coordinator의 마감 실패만 13.1 어휘로 바꿨다. live↔Poll handoff coordinator는 아직 네 마감을 모두 `IDLE_TIMEOUT`으로 보고한다. 설계 13.1에서 `IDLE_TIMEOUT`은 전송 idle(heartbeat/byte deadline → close + bounded reconnect)이다. 그래서 관측에서 "서버가 조용함"과 "우리 effect·checkpoint가 멈춤"을 kind로 나눌 수 없다. - switchToPoll quiescence 마감: IDLE_TIMEOUT/RECOVER - activateProbe quiescence 마감: IDLE_TIMEOUT/RECOVER - checkpoint 마감: IDLE_TIMEOUT/RECOVER - close drain 마감: IDLE_TIMEOUT/CLOSE 고른 방법: 결정 (a)를 1196b86과 같은 방식으로 적용한다. kind만 바꾸고 operation, retryable(전과 같이 true), fail-close 동작은 그대로 둔다. - quiescence 마감 → APPLY_FAILED/RECOVER. 기다리는 것은 이전 writer의 apply effect tail이다. stream coordinator의 effect 마감과 같은 kind다. APPLY_FAILED의 기본 retryable은 false라 true를 명시했다. 두 곳의 같은 분기를 `quiescenceFailure` 하나로 합쳤다. - checkpoint 마감 → PROVIDER_UNAVAILABLE/RECOVER. checkpoint authority가 throw할 때와 같은 kind다. - close drain 마감 → PROVIDER_UNAVAILABLE/CLOSE. stream·reconnect coordinator의 drain 상한과 같다. 이전부터 timer 실패도 같은 값이라 두 분기를 하나로 합쳤다. - 13.1 표: IDLE_TIMEOUT 행에서 handoff를 빼고 "내부 task 마감에는 쓰지 않는다"로 적었다. APPLY_FAILED·PROVIDER_UNAVAILABLE 행에 handoff 마감과 retryable 값, 뒤 동작을 적었다. 남은 IDLE_TIMEOUT 생성 지점은 SSE·WS의 RECEIVE·SUBSCRIBE(전송 idle)뿐이다. 버린 대안: - retryable도 kind 기본값으로(quiescence가 false가 됨): 결정 범위는 어휘다. 재시도 판단 변경은 따로 정한다. - close 마감에 CLOSED: 1196b86과 같은 이유로 버렸다. 아직 writer가 settle하지 않았는데 "닫힘"으로 읽힌다. 위험·한계: - 배럴로 공개된 handoff coordinator 결과의 kind가 바뀐다. IDLE_TIMEOUT을 보던 조합 코드는 APPLY_FAILED·PROVIDER_UNAVAILABLE을 봐야 한다. repo 안에 소비자는 없다(AVAILABLE_NOT_COMPOSED). - handoff에는 observer가 없어 관측 reason은 바뀌는 것이 없다. - 같은 APPLY_FAILED라도 stream coordinator는 retryable:false, handoff는 true다. 13.1 표에 둘 다 적었다. - realtime 레시피 gzip 40,902 → 40,878 B(한도 42,200). 검증: - RED: 기대값을 먼저 바꾸고 activateProbe quiescence 마감 테스트를 새로 넣은 뒤 live-poll-handoff-coordinator.test.ts 실행 → 7 failed | 9 passed. 7건 모두 received kind IDLE_TIMEOUT(close 4건, switchToPoll quiescence, activateProbe quiescence, checkpoint). - GREEN: `node scripts/run-vitest.ts run tests/unit/realtime` 14 files, 231 passed. - tsc app·test·recipes 통과, 바꾼 두 파일 eslint 통과, `check-optional-recipes`(source) PASS, `verify-documentation-readiness` PASS_SCOPED, `check-adapter-inventory` PASS. - 미실행: `check:architecture`(pnpm 필요). Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.1 04-02, 14.4 --- ...ime-events-web-push-and-bounded-polling.md | 6 +-- .../realtime/live-poll-handoff-coordinator.ts | 46 +++++++++++-------- .../live-poll-handoff-coordinator.test.ts | 43 ++++++++++++++--- 3 files changed, 65 insertions(+), 30 deletions(-) diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index fd1db869..0f192bd5 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1895,11 +1895,11 @@ credential을 보호할 수 있다고 주장하지 않는다. | `UNSUPPORTED` | browser capability 없음 | declared fallback | | `OFFLINE` | network hint/attempt failure | online hint 뒤 bounded check | | `CONNECT_TIMEOUT` | open deadline 초과 | bounded reconnect | -| `IDLE_TIMEOUT` | transport: heartbeat/byte/unsubscribe deadline 초과(operation `RECEIVE`·`SUBSCRIBE`). handoff coordinator의 quiescence·checkpoint·close deadline 초과(operation `RECOVER`·`CLOSE`) | transport: close + bounded reconnect. handoff 마감은 재연결로 풀리지 않는다: 그 전환을 fail-close한다(결과는 kind 기본값대로 retryable). 두 뜻은 `operation`으로 구분한다 | +| `IDLE_TIMEOUT` | transport: heartbeat/byte/unsubscribe deadline 초과(operation `RECEIVE`·`SUBSCRIBE`). 내부 task 마감에는 쓰지 않는다 | close + bounded reconnect | | `AUTH_REQUIRED` | session expired/recovery 실패 | sign-in UX | | `FORBIDDEN` | stream/resource 거절 | retry 없음 | | `RATE_LIMITED` | connection/request/provider limit | bounded server hint | -| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다 | +| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`). live↔Poll handoff coordinator의 checkpoint deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: true`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다. handoff checkpoint 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다. handoff close 마감 뒤에는 writer·checkpoint task가 settle하면 다시 부른 `close()`가 성공한다 | | `PROTOCOL_MISMATCH` | version/subprotocol/content type | terminal/rollout rollback | | `MALFORMED_EVENT` | state-bearing syntax/schema/exact-key 실패 | cursor 미진행, freshness `UNKNOWN`, close + registered recovery | | `MAPPING_CONTRACT_VIOLATION` | validated DTO의 registered mapper 실패 | effect/cache/cursor write 0, close + registered recovery | @@ -1910,7 +1910,7 @@ credential을 보호할 수 있다고 주장하지 않는다. | `SEQUENCE_GAP` | missing event | snapshot resync | | `CURSOR_EXPIRED` | replay retention 밖 | snapshot reset | | `QUEUE_OVERFLOW` | backpressure ceiling | close + registered snapshot/session rebuild | -| `APPLY_FAILED` | feature effect 실패. stream coordinator의 effect deadline 초과(operation `APPLY`, `retryable: false`)도 이 kind다 | cursor 미commit, bounded registered recovery. deadline 초과는 recovery를 바로 하지 않는다: task가 settle할 때까지 `DRAINING`을 유지하고, settle 뒤 다음 event가 recovery부터 한다 | +| `APPLY_FAILED` | feature effect 실패. stream coordinator의 effect deadline 초과(operation `APPLY`, `retryable: false`)도 이 kind다. live↔Poll handoff coordinator에서 이전 writer의 effect가 quiescence deadline 안에 끝나지 않은 것(operation `RECOVER`, `retryable: true`)도 이 kind다 | cursor 미commit, bounded registered recovery. deadline 초과는 recovery를 바로 하지 않는다: task가 settle할 때까지 `DRAINING`을 유지하고, settle 뒤 다음 event가 recovery부터 한다. handoff quiescence 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다 | | `POLL_BUDGET_EXHAUSTED` | lease 한도 도달 | stale/manual retry | | `PUSH_PERMISSION_DENIED` | 사용자 거절 | foreground fallback | | `PUSH_SUBSCRIPTION_STALE` | rotation/expiry/provider gone | bounded re-registration | diff --git a/src/adapters/realtime/live-poll-handoff-coordinator.ts b/src/adapters/realtime/live-poll-handoff-coordinator.ts index 5ab77f7c..9dbb9b83 100644 --- a/src/adapters/realtime/live-poll-handoff-coordinator.ts +++ b/src/adapters/realtime/live-poll-handoff-coordinator.ts @@ -398,12 +398,7 @@ export function createLivePollHandoffCoordinator( } if (quiescence !== "QUIESCED") { failClosed(); - return handoffFailure( - quiescence === "TIMED_OUT" - ? "IDLE_TIMEOUT" - : "PROVIDER_UNAVAILABLE", - "RECOVER", - ); + return quiescenceFailure(quiescence); } quiescing = null; const checkpoint = await establishCheckpoint( @@ -497,12 +492,7 @@ export function createLivePollHandoffCoordinator( } if (quiescence !== "QUIESCED") { failClosed(); - return handoffFailure( - quiescence === "TIMED_OUT" - ? "IDLE_TIMEOUT" - : "PROVIDER_UNAVAILABLE", - "RECOVER", - ); + return quiescenceFailure(quiescence); } quiescing = null; const checkpoint = await establishCheckpoint( @@ -588,8 +578,10 @@ export function createLivePollHandoffCoordinator( return handoffFailure("ABORTED", "RECOVER"); } if (selected.kind === "TIMEOUT") { + // 1101/04-02. Design 13.1: the checkpoint authority did not answer in + // time, the same kind as when it throws. candidate.controller.abort(); - return handoffFailure("IDLE_TIMEOUT", "RECOVER"); + return handoffFailure("PROVIDER_UNAVAILABLE", "RECOVER"); } if (selected.kind !== "VALUE") { candidate.controller.abort(); @@ -691,13 +683,12 @@ export function createLivePollHandoffCoordinator( quiescing = null; transitionCandidate = null; transitioning = false; - if (outcomes.includes("TIMED_OUT")) { - return handoffFailure("IDLE_TIMEOUT", "CLOSE"); - } - if (outcomes.includes("TIMER_FAILED")) { - return handoffFailure("PROVIDER_UNAVAILABLE", "CLOSE"); - } - return realtimeSuccess(undefined); + // 1101/04-02. A drain past its bound is PROVIDER_UNAVAILABLE/CLOSE, as in + // the stream and reconnect coordinators, never the transport's + // IDLE_TIMEOUT. + return outcomes.every((outcome) => outcome === "QUIESCED") + ? realtimeSuccess(undefined) + : handoffFailure("PROVIDER_UNAVAILABLE", "CLOSE"); } function inspect(): LivePollHandoffInspection { @@ -871,6 +862,21 @@ function handoffFailure( : realtimeFailure(kind, operation, retryable); } +/** + * 1101/04-02. Design 13.1: a prior writer that does not quiesce in time is a + * stalled effect, APPLY_FAILED, never the transport's IDLE_TIMEOUT. Retryable + * as before: the handoff fail-closes and only a new one can run. + */ +function quiescenceFailure( + outcome: Exclude, +): Extract, { ok: false }> { + return handoffFailure( + outcome === "TIMED_OUT" ? "APPLY_FAILED" : "PROVIDER_UNAVAILABLE", + "RECOVER", + true, + ); +} + function remapFailure( failure: RealtimeFailure, operation: RealtimeOperation, diff --git a/tests/unit/realtime/live-poll-handoff-coordinator.test.ts b/tests/unit/realtime/live-poll-handoff-coordinator.test.ts index 49a1eacd..410757d6 100644 --- a/tests/unit/realtime/live-poll-handoff-coordinator.test.ts +++ b/tests/unit/realtime/live-poll-handoff-coordinator.test.ts @@ -266,7 +266,7 @@ describe("live/poll authoritative writer handoff", () => { harness.clock.advance(100); await expect(closing).resolves.toMatchObject({ ok: false, - error: { kind: "IDLE_TIMEOUT", operation: "CLOSE" }, + error: { kind: "PROVIDER_UNAVAILABLE", operation: "CLOSE", retryable: true }, }); release?.(realtimeSuccess(undefined)); @@ -356,9 +356,11 @@ describe("live/poll authoritative writer handoff", () => { expect(harness.clock.sleepers).toHaveLength(1); harness.clock.advance(100); + // 1101/04-02. The prior writer's effect stalled (design 13.1), not the + // transport's IDLE_TIMEOUT. await expect(transition).resolves.toMatchObject({ ok: false, - error: { kind: "IDLE_TIMEOUT", operation: "RECOVER" }, + error: { kind: "APPLY_FAILED", operation: "RECOVER", retryable: true }, }); expect(harness.recover).not.toHaveBeenCalled(); expect(harness.coordinator.inspect()).toMatchObject({ @@ -367,6 +369,32 @@ describe("live/poll authoritative writer handoff", () => { }); }); + it("fails a probe activation closed when poll cannot quiesce before the bound", async () => { + const harness = createHarness({ + initial: "POLL", + apply: vi.fn(async ({ writer }) => + writer === "POLL" + ? await new Promise>(() => {}) + : realtimeSuccess(undefined), + ), + }); + void harness.coordinator.currentWriter()!.write("hung-poll", 4); + const live = expectProbe(harness.coordinator.beginLiveProbe()); + await flush(); + + const activation = live.activate(); + await flush(); + expect(harness.clock.sleepers).toHaveLength(1); + harness.clock.advance(100); + + await expect(activation).resolves.toMatchObject({ + ok: false, + error: { kind: "APPLY_FAILED", operation: "RECOVER", retryable: true }, + }); + expect(harness.recover).not.toHaveBeenCalled(); + expect(harness.coordinator.inspect().state).toBe("CLOSED"); + }); + it("keeps poll authoritative while probing, then recovers and drains live values serially", async () => { const firstLive = deferred>(); const order: string[] = []; @@ -550,9 +578,10 @@ describe("live/poll authoritative writer handoff", () => { expect(harness.clock.sleepers).toHaveLength(1); harness.clock.advance(100); + // 1101/04-02. The checkpoint authority did not answer in time. await expect(transition).resolves.toMatchObject({ ok: false, - error: { kind: "IDLE_TIMEOUT", operation: "RECOVER" }, + error: { kind: "PROVIDER_UNAVAILABLE", operation: "RECOVER", retryable: true }, }); expect(checkpointIsCurrent?.()).toBe(false); expect(harness.coordinator.inspect().state).toBe("CLOSED"); @@ -579,7 +608,7 @@ describe("live/poll authoritative writer handoff", () => { harness.clock.advance(100); await expect(closing).resolves.toMatchObject({ ok: false, - error: { kind: "IDLE_TIMEOUT", operation: "CLOSE" }, + error: { kind: "PROVIDER_UNAVAILABLE", operation: "CLOSE", retryable: true }, }); // RT-RR-03. A second close re-runs rather than replaying a cached verdict. // The writer is still hung, so it still reports a timeout. @@ -588,7 +617,7 @@ describe("live/poll authoritative writer handoff", () => { harness.clock.advance(100); await expect(second).resolves.toMatchObject({ ok: false, - error: { kind: "IDLE_TIMEOUT", operation: "CLOSE" }, + error: { kind: "PROVIDER_UNAVAILABLE", operation: "CLOSE", retryable: true }, }); }); @@ -616,7 +645,7 @@ describe("live/poll authoritative writer handoff", () => { harness.clock.advance(100); await expect(first).resolves.toMatchObject({ ok: false, - error: { kind: "IDLE_TIMEOUT", operation: "CLOSE" }, + error: { kind: "PROVIDER_UNAVAILABLE", operation: "CLOSE", retryable: true }, }); // The writer finishes after the first close gave up. @@ -654,7 +683,7 @@ describe("live/poll authoritative writer handoff", () => { harness.clock.advance(100); await expect(closing).resolves.toMatchObject({ ok: false, - error: { kind: "IDLE_TIMEOUT", operation: "CLOSE" }, + error: { kind: "PROVIDER_UNAVAILABLE", operation: "CLOSE", retryable: true }, }); harness.clock.advance(100); From ece944d08b8ea006b545634023ddc18d567e76fe Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:22:29 +0900 Subject: [PATCH 08/16] =?UTF-8?q?feat(bootstrap):=20=EC=A0=9C=ED=92=88=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20owner=EC=99=80=20FE-REG-ENV=20=ED=96=89?= =?UTF-8?q?=EC=9D=84=20=EC=A0=9C=ED=92=88=20=ED=8C=8C=EC=9D=BC=EB=A1=9C=20?= =?UTF-8?q?=EB=B0=9B=EB=8A=94=EB=8B=A4=20(1101/09-02)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 09-02(da1e128) 뒤에도 tech-log가 하는 일 두 가지는 템플릿 파일을 고쳐야 한다(리뷰 1101 README 14.4 "09-02 이식"). - 제품 설정 키의 FE-REG-ENV 행: tech-log는 템플릿 src/contracts/env.ts의 ENV_REGISTRY에 TECH_LOG_STUDIO_SOURCE·TECH_LOG_PUBLIC_SOURCE 행을 직접 넣었다(tech-log env.ts:63-70). - 부트 전 BFF 세션 owner: 세션이 httpOnly 쿠키라 owner가 백엔드에 묻는다. tech-log는 템플릿 create-runtime-composition.ts에서 AUTH_MODE external이고 Studio가 HTTP일 때 createRuntimeAdapters 전에 host 전역 __CA_FRONTEND_AUTH_OWNER__에 owner를 넣는다(:2, :36-52, bff-session-owner.ts:188-194). composeProduct는 http가 생긴 뒤에 불리고 http는 세션이 필요해서 이 일을 받을 수 없다. 고른 방법 - product-contracts.ts에 PRODUCT_ENV_REGISTRY를 빈 값으로 둔다. env.ts는 PRODUCT_REST_AUTH_PROFILES·PRODUCT_RUNTIME_CONFIG_FIELDS와 같은 모양으로 그 행을 ENV_REGISTRY에 합친다. 템플릿 키와 이름이 겹치면 모듈 로드 때 throw한다. check:registries와 vite.config.ts가 같은 객체를 읽으므로 제품 행도 같은 필드 검사를 받는다. 행을 더하기만 하면 additive라 기준선을 고치지 않는다(실험: 제품 행 2개 → compatibility=additive PASS, 허용 밖 classification → 실패). - product-composition.ts에 composeProductSessionOwner(context)를 둔다. 템플릿은 null을 돌려준다. 조립 루트가 세션을 고르기 전에, AUTH_MODE가 external일 때만 부른다. 제품 owner가 host 전역보다 먼저다. null이면 지금처럼 host 전역, 없으면 unavailable이다. demo 모드는 묻지 않는다. context는 config와 fetcher뿐이다(http 전이라 capability가 없다). 버린 대안 - owner를 composeProduct 반환값에 넣기: http가 세션을 쓰므로 순서가 꼬인다. - 제품이 host 전역에 계속 넣게 두고 문서화: 부트 전 훅이 템플릿 파일 (create-runtime-composition.ts)에 남는다. - FE-REG-ENV 행을 PRODUCT_RUNTIME_CONFIG_FIELDS에서 자동으로 만들기: zod 필드로는 classification·required를 알 수 없다. - 행 타입·도우미를 product-contracts.ts가 env.ts에서 import: 순환 의존 (no-circular-dependencies)이다. 타입 검사는 env.ts의 대입에서 한다. 위험·한계 - product-composition.ts에 export가 하나 늘었다. 이 파일을 이미 복사한 제품은 composeProductSessionOwner를 더해야 한다. da1e128은 아직 main에 없고 두 다운스트림 모두 받지 않았다. - 제품 행을 as const 없이 쓰면 phase가 string으로 넓어져 tsc 오류가 env.ts:78(템플릿 파일)에서 난다. 메시지에 키 이름은 나온다. product- contracts.ts 주석에 as const를 적었다. - 제품 설정 키에 FE-REG-ENV 행이 있는지 요구하는 검사는 여전히 없다. 템플릿 키도 RELEASE_ID·BUILD_ID는 행이 없어서 이 변경에서 넣지 않았다. - 제품 owner가 throw하면 createRuntimeAdapters가 실패해 부트 실패 화면이 된다. composeProduct와 같다. - tech-log의 owner는 subject를 null로 돌려준다(템플릿 동작대로 매 변경 fence). 이 변경과 무관하다. 검증 - RED: tests/unit/product-composition-fixture.test.ts 13건 중 3건 실패. FE-REG-ENV 행 없음, external 모드 세션이 authenticated가 아니라 integration-failed, env 이름 충돌을 거절하지 않음. - GREEN: 같은 파일 13/13, runtime-adapters-credential-order 7/7(mock에 composeProductSessionOwner: () => null 추가). - fixture는 vi.mock 대상이 제품 소유 두 파일(머리 주석 "Product-owned.")과 설치 기능 seam 두 개뿐이고, tech-log가 고친 템플릿 파일 4개(env.ts, create-runtime-composition.ts, runtime-config-schema.ts, runtime-adapters.ts)는 대상이 아님을 이 파일의 소스를 읽어 확인한다. - 회귀: tests/unit·contract·runtime-schema·integration 198 files 2861 tests 통과(heavy lock 아래). - tsc app·node·test 통과, 바꾼 파일 eslint 통과, check:registries PASS (compatibility=none, 재승인 불필요), verify:documentation PASS_SCOPED, check:adapter-inventory PASS. - 초기 JS gzip 202,770 → 202,931 B(+161, 예산 204,800). 같은 방법(dist manifest의 초기 파일 26개, gzipSync 기본 레벨)으로 전·후를 쟀다. - 미실행: check:architecture(pnpm 필요), test:component, e2e. --- .../frontend-application-foundation.md | 11 +- docs/architecture/starter-experience.md | 4 +- src/bootstrap/product-composition-contract.ts | 19 ++ src/bootstrap/product-composition.ts | 8 + src/bootstrap/runtime-adapters.ts | 16 +- src/contracts/env.ts | 22 +- src/contracts/product-contracts.ts | 10 +- .../unit/product-composition-fixture.test.ts | 222 +++++++++++++++++- .../runtime-adapters-credential-order.test.ts | 1 + 9 files changed, 293 insertions(+), 20 deletions(-) diff --git a/docs/architecture/frontend-application-foundation.md b/docs/architecture/frontend-application-foundation.md index affa03ae..d9fe275e 100644 --- a/docs/architecture/frontend-application-foundation.md +++ b/docs/architecture/frontend-application-foundation.md @@ -176,9 +176,14 @@ The same file is where a product adds any other capability (it augments `FeaturePlatformCapabilities`) and the credential provider for a product auth profile. The composition root keeps the order: scope fence, `ANONYMOUS` profile, product provider, session, scope fence again -(`tests/unit/runtime-adapters-credential-order.test.ts`). Product auth profiles -and runtime-config keys go in `src/contracts/product-contracts.ts`; both join -the template's registries under the same checks +(`tests/unit/runtime-adapters-credential-order.test.ts`). A product that owns +the session itself (a BFF whose session is an httpOnly cookie) returns its +session owner from `composeProductSessionOwner` in the same file. It is asked +first, before `http` exists, only when `AUTH_MODE` is `external`, and it comes +before the host's `__CA_FRONTEND_AUTH_OWNER__`; `null` leaves the session to +that global. Product auth profiles, runtime-config keys and the keys' +FE-REG-ENV rows go in `src/contracts/product-contracts.ts`; each joins the +template's registry under the same checks (`tests/unit/product-composition-fixture.test.ts`). ## Presentation consumer surface diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index 620edd09..76bac2e1 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -183,8 +183,8 @@ Files outside the feature directory. Everything else a feature needs is in | `src/contexts//context-layout.tsx` | the context needs its own frame instead of `AppShell` (see "Product home and layouts" below) | nothing: without it the context renders in `AppShell` | | `artifacts/tests/a11y-manual/.md` | every route the feature adds. Copy a record and reset it to `Status: pending-manual-review` | `test:unit` (`tests/unit/manual-a11y-evidence.test.ts`), `verify:documentation` (names the route IDs) and FE-GATE-009 (`review:a11y-manual -- --format-only`). FE-GATE-028 requires the signed review at release | | `tests/e2e/accessibility.spec.ts` | a route path has a parameter other than `:resourceId`, or a protected page cannot render while every API answers `[]` | `test:a11y` (FE-GATE-009): the spec fills in only `:resourceId` and answers every API with `[]` | -| `src/bootstrap/product-composition.ts` (product-owned) | `needs` names a capability the template does not build: augment `FeaturePlatformCapabilities` and return the capability here. `indexedDb` is built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts`. Credentials for a product auth profile are returned here too | `check:types`; at runtime `feature needs , which the host did not provide` | -| `src/contracts/product-contracts.ts` (product-owned) | a product auth profile or a product runtime-config key | auth profile: every gate that loads the operation, with `REST security profiles are incoherent for : unknown authProfileId …`. Config key: `check:types` where it is read | +| `src/bootstrap/product-composition.ts` (product-owned) | `needs` names a capability the template does not build: augment `FeaturePlatformCapabilities` and return the capability here. `indexedDb` is built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts`. Credentials for a product auth profile are returned here too. A product that owns the session (a BFF's httpOnly cookie) returns its session owner from `composeProductSessionOwner` instead of installing it on the host global before boot | `check:types`; at runtime `feature needs , which the host did not provide`. Without the session owner, `AUTH_MODE: "external"` boots with the session `integration-failed` | +| `src/contracts/product-contracts.ts` (product-owned) | a product auth profile, or a product runtime-config key and its FE-REG-ENV row (`PRODUCT_ENV_REGISTRY`) | auth profile: every gate that loads the operation, with `REST security profiles are incoherent for : unknown authProfileId …`. Config key: `check:types` where it is read. FE-REG-ENV row: `check:registries` checks its fields; nothing requires the row | | `config/runtime/.json` | optional: a `FEATURE_OVERRIDES` entry switches the feature off | nothing | | `package.json`, the lockfile, `config/security/dependency-change-evidence.json` | the contract contribution imports a generated `@org-contracts/*` package as a production dependency | `generate:supply-chain` (in `check:bundle`): `high-risk dependency missing review: add:` | diff --git a/src/bootstrap/product-composition-contract.ts b/src/bootstrap/product-composition-contract.ts index 7ff68812..0f5190b3 100644 --- a/src/bootstrap/product-composition-contract.ts +++ b/src/bootstrap/product-composition-contract.ts @@ -1,3 +1,4 @@ +import type { ExternalSessionOwner } from "../adapters/auth/index.ts"; import type { ContractHttpExecutorDependencies, InstalledHttpOperationExecutor, @@ -11,6 +12,24 @@ import type { RuntimeConfig } from "./runtime-config-schema.ts"; * profiles and runtime-config keys) and never edits `runtime-adapters.ts`. */ +/** + * What a product session owner is built from. It is asked first, before + * `http` exists (`http` needs the session), so it gets no capability. + */ +export type ProductSessionOwnerContext = Readonly<{ + /** Validated runtime config, product keys included. */ + config: RuntimeConfig; + fetcher?: typeof fetch; +}>; + +/** + * The session owner when the product owns the session itself, such as a BFF + * whose session is an httpOnly cookie only the backend can read. Asked only + * when `AUTH_MODE` is `external`; it comes before the host's + * `__CA_FRONTEND_AUTH_OWNER__`, and `null` leaves the session to that global. + */ +export type ProductSessionOwner = ExternalSessionOwner | null; + /** Built by the template; a product cannot return or replace them. */ export type TemplatePlatformCapabilityId = "http" | "telemetry"; diff --git a/src/bootstrap/product-composition.ts b/src/bootstrap/product-composition.ts index 11708fc3..7d0c12ce 100644 --- a/src/bootstrap/product-composition.ts +++ b/src/bootstrap/product-composition.ts @@ -1,12 +1,20 @@ import type { ProductComposition, ProductCompositionContext, + ProductSessionOwner, + ProductSessionOwnerContext, } from "./product-composition-contract.ts"; /** * Product-owned. The template ships it empty and does not change it after a * copy; the contract is in `product-composition-contract.ts`. */ +export function composeProductSessionOwner( + context: ProductSessionOwnerContext, +): ProductSessionOwner { + return null; +} + export function composeProduct(context: ProductCompositionContext) { return { capabilities: {}, diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 3563b814..8cdff959 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -64,7 +64,10 @@ import { } from "./load-release-manifest.ts"; import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts"; import { createServerStateGenerationStore } from "./server-state-generation-store.ts"; -import { composeProduct } from "./product-composition.ts"; +import { + composeProduct, + composeProductSessionOwner, +} from "./product-composition.ts"; import type { ProductComposition } from "./product-composition-contract.ts"; import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts"; import { @@ -343,7 +346,16 @@ export async function createRuntimeAdapters( context.host ?? (globalThis as unknown as Record); const config = context.runtime.config; const mutationIntentFactory = createBrowserMutationIntentFactory(); - const externalOwner = externalOwnerFrom(host); + // 09-02. A product that owns the session (a BFF's httpOnly cookie) returns + // its owner before anything resolves the session; the host global is the + // fallback. Demo mode keeps its own session and never asks. + const externalOwner = + config.AUTH_MODE === "demo" + ? null + : (composeProductSessionOwner({ + config, + ...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }), + }) ?? externalOwnerFrom(host)); const authSession = config.AUTH_MODE === "demo" ? createDemoSessionAdapter() diff --git a/src/contracts/env.ts b/src/contracts/env.ts index 56c63159..9c86dc71 100644 --- a/src/contracts/env.ts +++ b/src/contracts/env.ts @@ -1,3 +1,5 @@ +import { PRODUCT_ENV_REGISTRY } from "./product-contracts.ts"; + /** * §6.3. Case-insensitive key fragments that can never appear in a client * configuration document. @@ -39,7 +41,7 @@ export type EnvironmentDefinition = Readonly<{ defaultValue: unknown; }>; -export const ENV_REGISTRY = Object.freeze({ +export const ENV_REGISTRY = Object.freeze(withProductRows({ // F-6. Required: a staging or production build fails without it // (scripts/generate-runtime-config.ts). Local and development builds fall // back to the placeholder, which admission refuses for public targets. @@ -64,7 +66,23 @@ export const ENV_REGISTRY = Object.freeze({ // scripts/generate-product-feature-index.ts (09-02). A feature left out here // is not imported by any registry and never reaches the bundle. VITE_PRODUCT_FEATURES: build("compile-time", false, null), -}); +})); + +/** + * 09-02. The product's rows (`product-contracts.ts`) join FE-REG-ENV and are + * checked with it. A product row cannot take a template key's name. + */ +function withProductRows>>( + rows: Rows, +) { + const product: Readonly> = + PRODUCT_ENV_REGISTRY; + const reused = Object.keys(product).find((name) => Object.hasOwn(rows, name)); + if (reused !== undefined) { + throw new TypeError(`Product env key ${reused} is a template key.`); + } + return { ...rows, ...product }; +} function build( classification: string, diff --git a/src/contracts/product-contracts.ts b/src/contracts/product-contracts.ts index 05d12598..56ead834 100644 --- a/src/contracts/product-contracts.ts +++ b/src/contracts/product-contracts.ts @@ -1,9 +1,15 @@ /** - * Product-owned. The template ships both values empty and does not change + * Product-owned. The template ships every value empty and does not change * this file after a copy. * * - `PRODUCT_RUNTIME_CONFIG_FIELDS`: zod fields joined to the strict runtime * config document (`release-artifacts.ts`). + * - `PRODUCT_ENV_REGISTRY`: FE-REG-ENV rows joined to `ENV_REGISTRY` + * (`env.ts`), one per product key, in the template's row shape: + * `KEY: { phase: "runtime", classification: "public", required: false, + * defaultValue: "MOCK" }`, the whole object `as const` so `phase` stays a + * literal. `check:registries` checks them like the template's rows; adding + * rows is additive and needs no baseline change. * - `PRODUCT_REST_AUTH_PROFILES`: auth profiles installed next to the * template's (`rest-profiles.ts`); credentials for them come from * `src/bootstrap/product-composition.ts`. @@ -11,4 +17,6 @@ export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({}); +export const PRODUCT_ENV_REGISTRY = Object.freeze({}); + export const PRODUCT_REST_AUTH_PROFILES = Object.freeze({}); diff --git a/tests/unit/product-composition-fixture.test.ts b/tests/unit/product-composition-fixture.test.ts index 0088f31f..3d301c44 100644 --- a/tests/unit/product-composition-fixture.test.ts +++ b/tests/unit/product-composition-fixture.test.ts @@ -1,9 +1,13 @@ +import { readFile } from "node:fs/promises"; + import { afterEach, describe, expect, it, vi } from "vitest"; import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts"; import type { ProductComposition, ProductCompositionContext, + ProductSessionOwner, + ProductSessionOwnerContext, } from "../../src/bootstrap/product-composition-contract.ts"; import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.ts"; @@ -14,11 +18,14 @@ import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts /** * 09-02 completion check. The two products' current needs — memento's * `offsetUpload` and `runtime` capabilities and its BFF cookie XSRF write, - * tech-log's Studio CSRF and its product runtime-config key — expressed by - * filling only the two product-owned files: + * tech-log's Studio CSRF, its product runtime-config key with its FE-REG-ENV + * row, and its BFF session owner installed before boot — expressed by filling + * only the two product-owned files: * - * - `src/contracts/product-contracts.ts`: product auth profiles and config keys - * - `src/bootstrap/product-composition.ts`: capabilities and credential providers + * - `src/contracts/product-contracts.ts`: product auth profiles, config keys + * and their FE-REG-ENV rows + * - `src/bootstrap/product-composition.ts`: the session owner, capabilities and + * credential providers * * Both are replaced below by what a product would write in them. Everything * else is the template as shipped; only the installed contract set (adds the @@ -47,6 +54,7 @@ const PRODUCT_NEEDS: readonly FeaturePlatformCapabilityId[] = [ const fixture = vi.hoisted(() => ({ capabilities: undefined as Record | undefined, + sessionOwnerRequests: 0, withProfile( contract: T, operationId: string, @@ -78,6 +86,15 @@ vi.mock("../../src/contracts/product-contracts.ts", async () => { PRODUCT_RUNTIME_CONFIG_FIELDS: Object.freeze({ TECH_LOG_STUDIO_SOURCE: z.enum(["MOCK", "HTTP"]).default("MOCK"), }), + // tech-log added this row to the template's `env.ts`. + PRODUCT_ENV_REGISTRY: Object.freeze({ + TECH_LOG_STUDIO_SOURCE: Object.freeze({ + phase: "runtime", + classification: "public", + required: false, + defaultValue: "MOCK", + }), + }), PRODUCT_REST_AUTH_PROFILES: Object.freeze({ MEMENTO_BFF_READ: cookieProfile("MEMENTO_BFF_READ", []), // The paired backend's default CSRF header (Spring CookieCsrfTokenRepository). @@ -102,6 +119,47 @@ vi.mock("../../src/bootstrap/product-composition.ts", async () => { ); const studioSession = fixture.withProfile(detail, ...OPERATIONS.studioSession); + /** + * tech-log's BFF session owner (`bff-session-owner.ts`), which it put on the + * host global from the template's `create-runtime-composition.ts`. The + * session is an httpOnly cookie, so the owner asks the backend. + */ + function composeProductSessionOwner( + context: ProductSessionOwnerContext, + ): ProductSessionOwner { + fixture.sessionOwnerRequests += 1; + if (Reflect.get(context.config, "TECH_LOG_STUDIO_SOURCE") !== "HTTP") return null; + const fetcher = context.fetcher ?? fetch; + let state: "recovery-pending" | "authenticated" | "unauthenticated" = + "recovery-pending"; + const listeners = new Set<() => void>(); + const probe = async () => { + const response = await fetcher( + new URL("api/v1/studio/session", context.config.API_BASE_URL), + { method: "GET", credentials: "include" }, + ); + state = response.ok ? "authenticated" : "unauthenticated"; + for (const listener of listeners) listener(); + return response.ok ? ("restored" as const) : ("no-session" as const); + }; + void probe(); + return Object.freeze({ + readState: () => state, + readSubject: () => (state === "authenticated" ? "studio-user" : null), + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: async () => ({ headers: {} }), + recoverSession: probe, + notifyUnauthenticated() { + state = "unauthenticated"; + }, + }); + } + function composeProduct(context: ProductCompositionContext) { // tech-log: one Studio CSRF token per session, fetched through `http` with // the credential-free bootstrap profile and dropped on 401/403. @@ -187,7 +245,7 @@ vi.mock("../../src/bootstrap/product-composition.ts", async () => { }, } satisfies ProductComposition; } - return { composeProduct }; + return { composeProduct, composeProductSessionOwner }; }); vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => { @@ -272,16 +330,30 @@ afterEach(() => { current?.infrastructure.dispose(); current = undefined; fixture.capabilities = undefined; + fixture.sessionOwnerRequests = 0; }); -async function compose(options: Readonly<{ cookie?: string; studioStatus?: number }> = {}) { +async function compose( + options: Readonly<{ + cookie?: string; + studioStatus?: number; + authMode?: "demo" | "external"; + studioSource?: "MOCK" | "HTTP"; + studioSessionStatus?: number; + host?: Record; + }> = {}, +) { const validated = validateRuntimeConfig({ ...CONFIG_DOCUMENT, - TECH_LOG_STUDIO_SOURCE: "HTTP", + AUTH_MODE: options.authMode ?? CONFIG_DOCUMENT.AUTH_MODE, + TECH_LOG_STUDIO_SOURCE: options.studioSource ?? "HTTP", }); if (!validated.success) throw new Error(JSON.stringify(validated.issues)); const fetcher = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => { const url = String(input); + if (url.endsWith("/api/v1/studio/session")) { + return new Response(null, { status: options.studioSessionStatus ?? 200 }); + } if (url.endsWith("/api/test-entities/session")) { return Response.json({ id: "studio-csrf", name: "session" }); } @@ -306,7 +378,10 @@ async function compose(options: Readonly<{ cookie?: string; studioStatus?: numbe validationDurationMs: 0, }, release, - host: options.cookie === undefined ? {} : { document: { cookie: options.cookie } }, + host: { + ...options.host, + ...(options.cookie === undefined ? {} : { document: { cookie: options.cookie } }), + }, fetcher: fetcher as unknown as typeof fetch, }); const capabilities = fixture.capabilities; @@ -436,8 +511,129 @@ describe("09-02 product needs through the product-owned files only", () => { runtimeConfigV2ArtifactSchema.parse({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "HTTP" }), ).toMatchObject({ TECH_LOG_STUDIO_SOURCE: "HTTP" }); }); + + it("tech-log: the config key's FE-REG-ENV row joins ENV_REGISTRY", async () => { + // check:registries and vite.config.ts read this same object. + const { ENV_REGISTRY } = await import("../../src/contracts/env.ts"); + + expect(ENV_REGISTRY).toMatchObject({ + APP_ENV: { phase: "runtime", classification: "public", required: true }, + TECH_LOG_STUDIO_SOURCE: { + phase: "runtime", + classification: "public", + required: false, + defaultValue: "MOCK", + }, + }); + }); + + it("tech-log: the BFF session owner is the session from boot, in external mode only", async () => { + const session = async (options: Parameters[0]) => { + const { fetcher } = await compose(options); + const port = current?.outputPorts.session; + if (!port) throw new Error("not composed"); + await vi.waitFor(() => expect(port.getState()).not.toBe("recovery-pending")); + const state = port.getState(); + current?.infrastructure.dispose(); + current = undefined; + return { state, fetcher }; + }; + + const signedIn = await session({ authMode: "external" }); + expect(signedIn.state).toBe("authenticated"); + expect(sent(signedIn.fetcher, 0)).toMatchObject({ + url: "http://localhost:8080/api/v1/studio/session", + credentials: "include", + }); + await expect( + session({ authMode: "external", studioSessionStatus: 401 }), + ).resolves.toMatchObject({ state: "unauthenticated" }); + // The product's owner comes before the host's global owner. + await expect( + session({ authMode: "external", host: { __CA_FRONTEND_AUTH_OWNER__: hostOwner() } }), + ).resolves.toMatchObject({ state: "authenticated" }); + // The product returns none: the host's owner, or no owner, as before. + await expect( + session({ + authMode: "external", + studioSource: "MOCK", + host: { __CA_FRONTEND_AUTH_OWNER__: hostOwner() }, + }), + ).resolves.toMatchObject({ state: "unauthenticated" }); + await expect( + session({ authMode: "external", studioSource: "MOCK" }), + ).resolves.toMatchObject({ state: "integration-failed" }); + expect(fixture.sessionOwnerRequests).toBe(5); + + // Demo mode keeps its own session and does not ask the product. + fixture.sessionOwnerRequests = 0; + await expect(session({})).resolves.toMatchObject({ state: "unauthenticated" }); + expect(fixture.sessionOwnerRequests).toBe(0); + }); }); +/** A host-published owner that is signed out. */ +function hostOwner() { + return { + readState: () => "unauthenticated", + readSubject: () => null, + subscribe: () => () => {}, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: async () => ({ headers: {} }), + recoverSession: async () => "no-session", + notifyUnauthenticated() {}, + }; +} + +/** + * The template files tech-log edited (af3d8e6 sync) for the needs above. They + * stay template-owned; this fixture reaches the same result without them. + */ +const TECH_LOG_EDITED_TEMPLATE_FILES = [ + "src/contracts/env.ts", + "src/bootstrap/create-runtime-composition.ts", + "src/bootstrap/runtime-config-schema.ts", + "src/bootstrap/runtime-adapters.ts", +]; +/** Stand in for an installed feature and observe its capabilities; not product code. */ +const INSTALLED_FEATURE_SEAMS = [ + "src/features/installed-contract-contributions.ts", + "src/features/installed-feature-adapters.ts", +]; + +describe("09-02 the fixture replaces product-owned files only", () => { + const source = (file: string) => readFile(new URL(`../../${file}`, import.meta.url), "utf8"); + + it("mocks the two product-owned files and none tech-log edited", async () => { + const mocked = [ + ...(await source("tests/unit/product-composition-fixture.test.ts")).matchAll( + /vi\.(?:doMock|mock)\(\s*"\.\.\/\.\.\/(src\/[^"]+)"/g, + ), + ].flatMap((match) => (match[1] === undefined ? [] : [match[1]])); + const product = [...new Set(mocked)] + .filter((file) => !INSTALLED_FEATURE_SEAMS.includes(file)) + .sort(); + + expect(product).toEqual([ + "src/bootstrap/product-composition.ts", + "src/contracts/product-contracts.ts", + ]); + for (const file of product) { + expect(await source(file), file).toContain("Product-owned."); + } + for (const file of TECH_LOG_EDITED_TEMPLATE_FILES) { + expect(await source(file), file).not.toContain("Product-owned."); + } + }); +}); + +const EMPTY_PRODUCT = { + PRODUCT_RUNTIME_CONFIG_FIELDS: {}, + PRODUCT_REST_AUTH_PROFILES: {}, + PRODUCT_ENV_REGISTRY: {}, +}; + describe("09-02 a product row cannot take a template name", () => { afterEach(() => { vi.doUnmock("../../src/contracts/product-contracts.ts"); @@ -448,15 +644,21 @@ describe("09-02 a product row cannot take a template name", () => { { registry: "auth profiles", load: () => import("../../src/contracts/rest-profiles.ts"), - product: { PRODUCT_RUNTIME_CONFIG_FIELDS: {}, PRODUCT_REST_AUTH_PROFILES: { ANONYMOUS: {} } }, + product: { ...EMPTY_PRODUCT, PRODUCT_REST_AUTH_PROFILES: { ANONYMOUS: {} } }, error: "Product REST auth profile ANONYMOUS reuses a template profile id.", }, { registry: "runtime config", load: () => import("../../src/contracts/release-artifacts.ts"), - product: { PRODUCT_RUNTIME_CONFIG_FIELDS: { APP_ENV: {} }, PRODUCT_REST_AUTH_PROFILES: {} }, + product: { ...EMPTY_PRODUCT, PRODUCT_RUNTIME_CONFIG_FIELDS: { APP_ENV: {} } }, error: "Product runtime config key APP_ENV is a template key.", }, + { + registry: "FE-REG-ENV", + load: () => import("../../src/contracts/env.ts"), + product: { ...EMPTY_PRODUCT, PRODUCT_ENV_REGISTRY: { APP_ENV: {} } }, + error: "Product env key APP_ENV is a template key.", + }, ])("refuses to load ($registry)", async ({ load, product, error }) => { vi.resetModules(); vi.doMock("../../src/contracts/product-contracts.ts", () => product); diff --git a/tests/unit/runtime-adapters-credential-order.test.ts b/tests/unit/runtime-adapters-credential-order.test.ts index 2fc7f2bf..489b23c2 100644 --- a/tests/unit/runtime-adapters-credential-order.test.ts +++ b/tests/unit/runtime-adapters-credential-order.test.ts @@ -77,6 +77,7 @@ vi.mock("../../src/features/installed-feature-adapters.ts", async (importOrigina /** The product-owned file, filled the way a product fills it. */ vi.mock("../../src/bootstrap/product-composition.ts", () => ({ + composeProductSessionOwner: () => null, composeProduct: () => ({ capabilities: {}, credentialProviders: fixture.providers, From d0414c85f9f56d62ab49f2e6d192028095692d5f Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:24:48 +0900 Subject: [PATCH 09/16] =?UTF-8?q?fix(contracts):=20=EB=9F=B0=ED=83=80?= =?UTF-8?q?=EC=9E=84=20=EC=84=A4=EC=A0=95=20=ED=82=A4=EB=A7=88=EB=8B=A4=20?= =?UTF-8?q?FE-REG-ENV=20=ED=96=89=EC=9D=84=20=EC=9A=94=EA=B5=AC=ED=95=9C?= =?UTF-8?q?=EB=8B=A4=20(1101/09-02)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: config.json V2 스키마의 키 중 RELEASE_ID와 BUILD_ID에는 FE-REG-ENV(ENV_REGISTRY) 행이 없다. 이를 잡는 검사도 없다. 그래서 제품이 PRODUCT_RUNTIME_CONFIG_FIELDS에만 키를 더하고 PRODUCT_ENV_REGISTRY 행을 빠뜨려도 check:registries가 그 키를 보지 못한다. ece944d를 검토하다 찾았다. 고른 방법: - tests/unit/env-registry-coverage.test.ts를 더한다. runtimeConfigV2 ArtifactSchema의 모든 최상위 키에 phase "runtime" 행이 있어야 한다. 제품 필드는 withProductFields로 같은 shape에 들어가므로 같이 검사된다. - RELEASE_ID, BUILD_ID 행을 public-metadata, 선택, 기본값 null로 더한다. 빌드가 config.json에 쓰는 릴리스 신원이고, VITE_BUILD_ID와 같은 분류다. 버린 대안: check-registries.ts에서 검사하기. 그 검사기는 registry-governance.json에 적힌 레지스트리 export를 같은 규칙으로 읽는 일반 검사기다. 스키마와 레지스트리를 맞대는 규칙을 넣으면 FE-REG-ENV 하나만을 위한 분기가 생긴다. 테스트 하나로 같은 실패를 낸다. 위험·한계: V1 전용 키(API_CONTRACT_VERSION)는 검사하지 않는다. 그 행은 FE-REG-ENV 변경 증거로 지워졌고, V1 reader는 지울 예정이다. 행을 더한 것은 additive라 기준선을 고치지 않는다. 검증: - RED: 새 테스트가 ["RELEASE_ID", "BUILD_ID"]를 보고하며 실패 - GREEN: 통과. env 관련 unit 4파일 43건 통과 - node scripts/check-registries.ts: 11 registries PASS, additive - tsc app·test, eslint 통과 --- src/contracts/env.ts | 5 +++++ tests/unit/env-registry-coverage.test.ts | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 tests/unit/env-registry-coverage.test.ts diff --git a/src/contracts/env.ts b/src/contracts/env.ts index 9c86dc71..48c874be 100644 --- a/src/contracts/env.ts +++ b/src/contracts/env.ts @@ -58,6 +58,11 @@ export const ENV_REGISTRY = Object.freeze(withProductRows({ AUTH_MODE: runtime("public", true, "external"), CONFIG_SCHEMA_VERSION: runtime("public", true, null), RELEASE_MANIFEST_URL: runtime("public", true, "/release-manifest.json"), + // F-6. The release identity the build writes into config.json. It must match + // the deployed HTML and release manifest, or boot stops with + // CONFIG_BUILD_MISMATCH (scripts/check-release-admission.ts). + RELEASE_ID: runtime("public-metadata", false, null), + BUILD_ID: runtime("public-metadata", false, null), // §3.5: overrides may only disable an installed capability, never enable one. CAPABILITY_OVERRIDES: runtime("public", false, null), // §3.5: likewise for features — subtractive, keyed by installed feature id. diff --git a/tests/unit/env-registry-coverage.test.ts b/tests/unit/env-registry-coverage.test.ts new file mode 100644 index 00000000..f28118d0 --- /dev/null +++ b/tests/unit/env-registry-coverage.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; + +import { ENV_REGISTRY } from "../../src/contracts/env.ts"; +import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts"; + +// 09-02. A key the deployed config.json may carry needs an FE-REG-ENV row, so +// check:registries sees it. A product key added to +// PRODUCT_RUNTIME_CONFIG_FIELDS without a PRODUCT_ENV_REGISTRY row fails here. +describe("FE-REG-ENV coverage", () => { + it("has a runtime row for every V2 runtime config key", () => { + const missing = Object.keys(runtimeConfigV2ArtifactSchema.shape).filter( + (key) => + !Object.hasOwn(ENV_REGISTRY, key) || + ENV_REGISTRY[key as keyof typeof ENV_REGISTRY].phase !== "runtime", + ); + + expect(missing).toEqual([]); + }); +}); From 27f45233f9c0205bafcc6573acc3a037fb9ab9b8 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:11:55 +0900 Subject: [PATCH 10/16] =?UTF-8?q?test(layouts):=20=EB=AA=A8=EB=93=A0=20?= =?UTF-8?q?=EB=A0=88=EC=9D=B4=EC=95=84=EC=9B=83=EC=9D=98=20skip=20link?= =?UTF-8?q?=EC=99=80=20main=20=ED=95=98=EB=82=98=EB=A5=BC=20=EC=8B=A4?= =?UTF-8?q?=ED=96=89=EC=9C=BC=EB=A1=9C=20=EA=B2=80=EC=82=AC=ED=95=9C?= =?UTF-8?q?=EB=8B=A4=20(1101/14.4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 라우터는 경로가 바뀔 때마다 `#main-content`로 focus를 옮긴다. 그래서 라우터가 붙이는 모든 레이아웃은 skip link와 `

` 하나를 그려야 한다. ca16187이 context 레이아웃을 열면서 이 규칙을 타입 주석과 starter-experience.md, fixture로만 지켰다. 레이아웃에서 `
`을 빼도 실패하는 테스트가 없다(리뷰 README 14.4 09-03 첫 줄). 고른 방법: 등록된 레이아웃을 읽어 도는 component 테스트 `tests/component/layout-landmarks.test.tsx`. - 대상: `AppShell`, 설치된 제품(`TEMPLATE_APP_MODULE.contexts`)의 각 `loadLayout`, fixture 제품(`LAYOUT_PRODUCT_CONTEXT_MODULES`)의 각 `loadLayout`. 제품이 `context-layout.tsx`를 추가하면 이 파일을 고치지 않아도 검사 대상이 된다. - 각 레이아웃을 메모리 라우터에 붙이고 자식 페이지(probe h1)를 그린다. 확인: `main`/`role="main"`이 정확히 하나, 그 id가 `main-content`, 자식 페이지가 그 안에 있음, `href="#main-content"` 링크가 있음. - fixture의 offline 레이아웃은 청크가 오지 않도록 만든 것이라 id로 뺐다. 버린 대안: - context-layouts.test.tsx에 넣기: 그 파일은 생성 인덱스를 fixture로 mock한다. 설치된 제품의 레이아웃은 그 안에서 읽을 수 없고, 읽더라도 fixture 레지스트리 아래라 제품 라우트를 가리키는 레이아웃(`routePath`)이 다른 이유로 깨진다. - `AppRouter`로 레이아웃마다 URL을 열기: 레이아웃마다 파라미터 없는 경로를 골라야 하고 설치된 제품과 fixture를 한 파일에서 돌릴 수 없다. 위험·한계: - 레이아웃 단독 렌더라 페이지가 자기 `
`을 하나 더 그리는 경우는 이 테스트가 못 잡는다. 라우터를 거친 확인은 context-layouts.test.tsx가 fixture로 한다. - skip link가 첫 focus 대상인지는 보지 않는다. - 템플릿 자체에는 레이아웃을 선언한 context가 없어, 설치된 제품 쪽은 지금 `AppShell`만 돈다. 검증: - RED(변이): fixture 레이아웃의 `
`을 `
`로 바꾸면 4건 중 3건 실패 ("expected to have a length of 1 but got +0"). AppShell skip link href를 `#content`로 바꾸면 1건 실패("expected null not to be null"). 둘 다 되돌렸다. - GREEN: 4건 통과(AppShell, context site, topics, studio). - tsc test 통과. 새 파일 eslint 통과. verify-documentation-readiness PASS_SCOPED. --- docs/architecture/starter-experience.md | 2 + tests/component/layout-landmarks.test.tsx | 62 +++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 tests/component/layout-landmarks.test.tsx diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index 76bac2e1..f8f7f75d 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -235,6 +235,8 @@ than `AppShell`, declares it. The router and the catalogs do not change. exactly one `
` around ``. The router moves focus there on every route change. Layout routes are siblings of `AppShell`, never inside it. + `tests/component/layout-landmarks.test.tsx` renders `AppShell` and the + layout of every installed context and fails one without them. - **Failures.** A layout chunk a deploy removed gets the reload-once recovery of a route chunk. Route and feature boundaries work as they do in `AppShell`. diff --git a/tests/component/layout-landmarks.test.tsx b/tests/component/layout-landmarks.test.tsx new file mode 100644 index 00000000..5aa1803d --- /dev/null +++ b/tests/component/layout-landmarks.test.tsx @@ -0,0 +1,62 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import type { ComponentType } from "react"; +import { createMemoryRouter, RouterProvider } from "react-router-dom"; +import { describe, expect, it } from "vitest"; + +import { TEMPLATE_APP_MODULE } from "../../src/apps/template-app.ts"; +import { AppShell } from "../../src/presentation/layouts/app-shell.tsx"; +import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; +import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; +import { SessionProvider } from "../../src/presentation/providers/session-provider.tsx"; +import { createTestApplication } from "../helpers/create-test-application.ts"; +import { LAYOUT_PRODUCT_CONTEXT_MODULES } from "../helpers/fixture-layout-product.tsx"; + +/** + * 09-03 (1101/14.4). The router moves focus to `#main-content` on every route + * change, so every layout it mounts has to render a skip link to it and make + * it the one main landmark around the page. The layouts are read from the + * contexts of the installed product and of the fixture product, so a new + * `context-layout.tsx` is checked without being named here. + */ +const contexts = [ + ...TEMPLATE_APP_MODULE.contexts, + // The fixture's offline layout chunk never arrives, by design. + ...LAYOUT_PRODUCT_CONTEXT_MODULES.filter((context) => context.id !== "offline"), +]; +const LAYOUTS: readonly (readonly [string, ComponentType])[] = [ + ["AppShell", AppShell], + ...(await Promise.all( + contexts.flatMap((context) => { + const loadLayout = context.route?.loadLayout; + return loadLayout + ? [loadLayout().then((Layout) => [`context ${context.id}`, Layout] as const)] + : []; + }), + )), +]; + +describe("every layout the router mounts", () => { + it.each(LAYOUTS)("%s links its skip link to its one main landmark", async (_name, Layout) => { + const router = createMemoryRouter([ + { path: "/", element: , children: [{ index: true, element:

Probe page

}] }, + ]); + render( + + + + + + + , + ); + + const page = await screen.findByRole("heading", { name: "Probe page", level: 1 }); + const mains = document.querySelectorAll('main, [role="main"]'); + expect(mains).toHaveLength(1); + expect(mains[0]).toHaveAttribute("id", "main-content"); + expect(mains[0]).toContainElement(page); + expect(document.querySelector('a[href="#main-content"]')).not.toBeNull(); + }); +}); From 7d85589ec106bb7f616321d43b4e428a5cf6caa1 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:17:28 +0900 Subject: [PATCH 11/16] =?UTF-8?q?fix(apps):=20=ED=94=8C=EB=9E=AB=ED=8F=BC?= =?UTF-8?q?=20=EB=9D=BC=EC=9A=B0=ED=8A=B8=EA=B0=80=20=EA=B0=80=EB=A6=AC?= =?UTF-8?q?=EB=8A=94=20=EA=B8=B0=EB=8A=A5=20=EB=9D=BC=EC=9A=B0=ED=8A=B8?= =?UTF-8?q?=EB=A5=BC=20=EC=A1=B0=EB=A6=BD=20=EB=95=8C=20=EB=A7=89=EB=8A=94?= =?UTF-8?q?=EB=8B=A4=20(1101/14.4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 라우터는 `AppShell` 아래 플랫폼 라우트를 모든 context보다 먼저 붙인다. 그래서 기능 라우트를 플랫폼 라우트도 받으면 오류 없이 플랫폼 화면이 나온다. React Router `matchRoutes`로 라우터와 같은 구조를 만들어 확인했다. - 같은 경로: context `examples/*`의 `/examples/ui`는 `EXAMPLES_UI`가 받는다. 레이아웃 아래에서도 순위가 같으면 앞에 있는 `AppShell`이 이긴다. - `APP_HOME`이 아닌 id로 선언한 `/`는 플랫폼 홈이 받는다(ca16187 한계). - 레이아웃 없는 `*` 루트 context는 모든 URL을 NOT_FOUND splat에 뺏긴다. splat끼리 순위가 같고 플랫폼 쪽이 먼저다. 7139c7c의 루트 검사는 context 루트끼리만 비교해 이 셋을 통과시킨다. 고른 방법: 라우트 조립 런타임, 곧 `defineDeployableAppModule`의 09-06 검사 (`assertFeatureRoutesReachOwningContext`)에 한 단계를 더한다. 기능 라우트 경로마다 `[대체되지 않은 플랫폼 라우트..., context가 붙는 자리]`로 `matchRoutes`를 돌려, 그 context가 받지 않으면 route id, 경로, 기능, context, 가로챈 플랫폼 라우트를 담아 TypeError로 실패한다. context가 붙는 자리는 라우터와 같다. 레이아웃이 없으면 루트이고, 있으면 그 라우트의 경로다. 기능이 대신한 `APP_HOME`은 플랫폼 쪽에서 빼고, `APP_HOME` 라우트 자체는 지금처럼 건너뛴다. - 앱 모듈을 평가할 때 실패하므로 부트와 앱 모듈을 불러오는 모든 테스트가 막힌다(fail-closed). 기존 09-06 검사와 같은 자리이고, 라우트 정의는 이미 초기 그래프에 있다. 버린 대안: - 라우터(`createRegisteredRoutes`)에서 검사: 라우터 표 자체로 보니 순위가 정확하다. 하지만 `AppRouter`가 마운트될 때에야 실패하고, 앱 모듈을 fixture로 바꿔 끼우는 테스트를 따로 만들어야 한다. - 아키텍처 테스트: 템플릿에 설치된 기능만 보고, 다운스트림이 기능을 더한 빌드는 실행 때 지켜지지 않는다. - 레지스트리 검사(`check:registries`) 또는 생성기: 생성기는 정규식으로 리터럴만 읽어 라우트 경로를 모른다. - 경로 문자열 비교: `*` 루트와 파라미터 모양이 같은 경로를 놓친다. 위험·한계: - 라우터 순서를 이 함수가 따라 한다. `app-router.tsx`가 플랫폼 라우트를 context 뒤로 옮기면 이 검사도 같이 바꿔야 한다. 주석에 적었다. - 일부만 겹치는 경우(`/examples/:slug`의 `ui` 값)는 막지 않는다. 그 기능 라우트는 다른 값으로는 닿는다. - 기능끼리 같은 경로는 이 커밋 범위가 아니다. 검증: - RED: tests/architecture/context-route-roots.test.ts 새 5건 중 거절 4건이 "expected [Function] to throw an error"로 실패(21건 중 4 실패). - GREEN: 21건 통과. 메시지 예: "Route EXAMPLES_UI_COPY (/examples/ui) of feature examples-feature in context examples is answered by platform route EXAMPLES_UI (/examples/ui). A feature replaces a platform route only by declaring its id (APP_HOME)." - 회귀: tests/{architecture,unit,features,platform,component,contract, runtime-schema,integration,scripts,scale}(pnpm을 띄우는 3개 제외) 306 files 중 3,569 통과, 1 실패. 실패는 telemetry-storm.test.ts 10초 timeout(부하 44)이고 단독 재실행에서 4건 통과했다. - tsc app·test·node 통과. 바꾼 파일 eslint 통과. check-registries 통과. verify-documentation-readiness PASS_SCOPED. --- docs/architecture/starter-experience.md | 12 ++-- src/apps/deployable-app-module.ts | 47 ++++++++++++++-- .../architecture/context-route-roots.test.ts | 55 +++++++++++++++++++ 3 files changed, 104 insertions(+), 10 deletions(-) diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index f8f7f75d..129a7cc7 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -161,10 +161,14 @@ selected app. Every build and check script runs it first; run it yourself with Every route path in the feature contract must sit at or under that context's `CONTEXT_ROUTE_PATH` and must not fall under another context's identical or more specific root: the router renders feature routes only - inside the owning context. The app module refuses anything else when it - loads, naming the route, feature and context - (`src/apps/deployable-app-module.ts`). A route that takes over the platform - home is the exception ("Product home and layouts"). + inside the owning context. No platform route may answer it either: the + router tries `AppShell`'s platform routes first, so the same path as a + platform route, `/` under an id other than `APP_HOME`, or a `*` root + without a layout (the not-found route takes every URL) never renders the + feature. The app module refuses anything else when it loads, naming the + route, feature and context (`src/apps/deployable-app-module.ts`). A route + that takes over the platform home is the exception ("Product home and + layouts"). 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`, diff --git a/src/apps/deployable-app-module.ts b/src/apps/deployable-app-module.ts index 2a2fdbd2..c3766b0c 100644 --- a/src/apps/deployable-app-module.ts +++ b/src/apps/deployable-app-module.ts @@ -4,7 +4,10 @@ import { contractRoutePaths, type BoundedContextModule, } from "../contexts/bounded-context-module.ts"; -import { FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS } from "../contracts/routes.ts"; +import { + FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS, + PLATFORM_ROUTE_REGISTRY, +} from "../contracts/routes.ts"; import { assertWithinCardinalityBudget } from "../platform/cardinality/cardinality-budget.ts"; export type DeployableAppModule = Readonly<{ @@ -55,6 +58,13 @@ export function defineDeployableAppModule context.route ? [{ id: context.id, path: context.route.path }] : [], ); + const featureRouteIds = new Set( + contexts.flatMap((context) => + context.features.flatMap((feature) => + contractRoutePaths(feature.contracts).map(([routeId]) => routeId), + ), + ), + ); + const platformRoutes = Object.values(PLATFORM_ROUTE_REGISTRY).flatMap( + ({ routeId, path }) => + FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS.includes(routeId) && + featureRouteIds.has(routeId) + ? [] + : [{ id: routeId, path }], + ); for (const context of contexts) { for (const feature of context.features) { for (const [routeId, path] of contractRoutePaths(feature.contracts)) { if (FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS.includes(routeId)) continue; const reached = matchRoutes(roots, path)?.[0]?.route; - if (reached?.id === context.id) continue; + if (reached?.id !== context.id || !context.route) { + throw new TypeError( + `Route ${routeId} (${path}) of feature ${feature.id} is not under the route root of its context ${context.id} (${context.route?.path ?? "no route root"}): ` + + (reached + ? `context ${reached.id} (${reached.path}) takes that URL.` + : "the router would answer NOT_FOUND."), + ); + } + const mount = { + id: context.id, + path: context.route.loadLayout ? path : context.route.path, + }; + const answered = matchRoutes([...platformRoutes, mount], path)?.[0]?.route; + if (answered === mount) continue; throw new TypeError( - `Route ${routeId} (${path}) of feature ${feature.id} is not under the route root of its context ${context.id} (${context.route?.path ?? "no route root"}): ` + - (reached - ? `context ${reached.id} (${reached.path}) takes that URL.` - : "the router would answer NOT_FOUND."), + `Route ${routeId} (${path}) of feature ${feature.id} in context ${context.id} is answered by platform route ${answered?.id} (${answered?.path}). ` + + `A feature replaces a platform route only by declaring its id (${FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS.join(", ")}).`, ); } } diff --git a/tests/architecture/context-route-roots.test.ts b/tests/architecture/context-route-roots.test.ts index b74ebc32..0d66c849 100644 --- a/tests/architecture/context-route-roots.test.ts +++ b/tests/architecture/context-route-roots.test.ts @@ -180,6 +180,61 @@ describe("context route roots under layouts", () => { }); }); +/** + * 09-03 (1101/14.4). AppShell mounts the platform routes ahead of every + * context, so a feature route a platform route also answers is never + * rendered: the router picks the platform route without an error. Only the + * home a feature takes over by its id is allowed. + */ +describe("feature routes and platform routes", () => { + const layout = async () => () => null; + + it("rejects a feature route at a platform route's path, naming both", () => { + expect(() => + app( + context("examples", "examples/*", [ + feature("examples-feature", { EXAMPLES_UI_COPY: "/examples/ui" }), + ]), + ), + ).toThrow(/EXAMPLES_UI_COPY.*\/examples\/ui.*examples-feature.*examples.*EXAMPLES_UI/); + }); + + it("rejects the same path under a layout of its own", () => { + // Layout routes sit after AppShell, so the tie goes to the platform. + expect(() => + app( + context("examples", "examples/*", [ + feature("examples-feature", { EXAMPLES_UI_COPY: "/examples/ui" }), + ], layout), + ), + ).toThrow(/EXAMPLES_UI_COPY.*EXAMPLES_UI/); + }); + + it("rejects `/` under another id, which the platform home answers", () => { + expect(() => + app(context("site", "*", [feature("site", { SITE_HOME: "/" })], layout)), + ).toThrow(/SITE_HOME.*\/.*site.*APP_HOME/); + }); + + it("rejects a `*` root without a layout, which NOT_FOUND answers", () => { + // AppShell's NOT_FOUND splat comes before the context's `*` gateway. + expect(() => + app(context("site", "*", [feature("site", { EXPLORE: "/explore" })])), + ).toThrow(/EXPLORE.*\/explore.*site.*NOT_FOUND/); + }); + + it("accepts `/` once a feature took over the platform home", () => { + expect(() => + app( + context("site", "*", [feature("site", { APP_HOME: "/", EXPLORE: "/explore" })], layout), + context("examples", "examples/*", [ + feature("examples-feature", { EXAMPLES_REFERENCE: "/examples/reference" }), + ]), + ), + ).not.toThrow(); + }); +}); + /** 09-03. The platform names the routes a feature may take over; one feature may. */ describe("replaceable platform routes", () => { const contract = (featureId: string, ...routeIds: string[]) => ({ From 7c8cb19e94535658d34c0de04f9c9ceb6f02e95e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:23:17 +0900 Subject: [PATCH 12/16] =?UTF-8?q?fix(routes):=20=EB=93=B1=EB=A1=9D=20?= =?UTF-8?q?=EB=9D=BC=EC=9A=B0=ED=8A=B8=20=EC=97=86=EB=8A=94=20URL=EC=9D=98?= =?UTF-8?q?=20=EC=A0=81=EC=9E=AC=20=EC=8B=A4=ED=8C=A8=EB=A5=BC=20UNREGISTE?= =?UTF-8?q?RED=5FROUTE=EB=A1=9C=20=EC=A0=81=EB=8A=94=EB=8B=A4=20(1101/14.3?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: context gateway가 라우트 적재 실패를 `ui.render.failed`로 남길 때 `route_id`를 URL에서 고른다. 고르는 곳이 세 군데이고 결과가 서로 다르다. - 청크 누락이 아닌 실패: `registeredRouteIdAt(...) ?? routeModule.id`. 레지스트리의 NOT_FOUND splat이 모든 URL에 맞아서 등록 라우트가 없는 URL은 `NOT_FOUND`가 되고 대체값은 한 번도 쓰이지 않는다. 운영에서는 not-found 화면이 깨진 것처럼 읽혀 플랫폼 담당에게 간다. 실제로 실패한 것은 context의 라우트 모듈이다. - 복구하지 못한 청크 실패: 늘 `routeModule.id`(context id). telemetry는 `route_id`를 `^[A-Z][A-Z0-9_]{0,63}$`로만 받는다. 그래서 이 이벤트는 `invalid-attribute-value`로 버려진다(`projectTelemetryEvent`로 확인). - 레이아웃 청크 실패: `?? "NOT_FOUND"`. 레이아웃 아래 context는 등록 경로에만 붙어서 지금은 닿지 않는 값이다. 이 진단이 구분해야 하는 것은 둘이다. 어느 화면(그래서 어느 기능)이 실패했나, 그리고 not-found 화면 자체가 실패했나. 그 값은 telemetry까지 가야 한다. 고른 방법: 세 곳이 `failedRouteIdAt(pathname)` 하나를 쓴다. URL의 등록 라우트 id를 쓰고, 등록 라우트가 없으면(NOT_FOUND만 맞으면) 명시값 `UNREGISTERED_ROUTE`(`UNREGISTERED_ROUTE_ID`, src/contracts/routes.ts)를 쓴다. 등록 URL의 청크 실패는 context id 대신 그 라우트 id가 된다. 라우트 id로 소유 기능과 context를 찾을 수 있다. 청크 복구의 chunkId 선택은 바꾸지 않았다. 버린 대안: - context id(`routeModule.id`, 원래 의도한 대체값): 실패한 모듈을 정확히 가리키지만 telemetry가 버린다. 받게 하려면 `route_id` 문법을 소문자 kebab까지 넓혀야 한다. 그러면 `api.request.failed` 등 모든 이벤트의 `route_id` 검사가 약해진다. - context id를 대문자 snake로 바꿔 쓰기: 숨은 이름 규칙이 생기고 실제 라우트 id와 섞인다. - `context_id` 속성 추가: 진단·telemetry 허용 목록과 레지스트리 기준선을 바꿔야 한다. 기준선 재승인은 이 작업 범위가 아니다. 위험·한계: - 등록 라우트가 없는 URL의 실패는 어느 context인지 진단에 남지 않는다. 같은 결함은 그 context의 등록 URL에서도 나므로 그 보고로 찾는다. - [계약] `ui.render.failed`의 `route_id`에 `UNREGISTERED_ROUTE` 값이 생긴다. 복구하지 못한 context 라우트 청크 실패는 context id 대신 라우트 id를 적는다. `route_id` 이름과 허용 문법은 그대로다. - 기능이 `UNREGISTERED_ROUTE`라는 route id를 선언하면 구분되지 않는다. 막지 않았다. 검증: - RED: context-boundary-diagnostics "unregistered handle" 1건이 `"route_id": "NOT_FOUND"`로 실패. context-route-gateway 새 2건이 `"route_id": "context-offline"`로 실패(8건 중 3 실패). - GREEN: 두 파일과 context-layouts 14건 통과. 각 보고는 telemetry 투영 (`projectTelemetryEvent`)도 통과한다. - 회귀: tests/{architecture,unit,features,platform,component,contract, runtime-schema,integration,scripts,scale}(pnpm을 띄우는 3개 제외) 306 files, 3,572건 통과. - tsc app·test 통과. 바꾼 파일 eslint 통과. check-registries, check-diagnostics 통과. verify-documentation-readiness PASS_SCOPED. --- .../routing-pages-and-patterns.md | 4 +++ src/contracts/routes.ts | 8 +++++ src/presentation/routes/app-router.tsx | 19 ++++++++-- .../context-boundary-diagnostics.test.tsx | 12 +++++-- .../component/context-route-gateway.test.tsx | 35 +++++++++++++++++++ 5 files changed, 72 insertions(+), 6 deletions(-) diff --git a/docs/architecture/routing-pages-and-patterns.md b/docs/architecture/routing-pages-and-patterns.md index bb5cfe0c..fdc9a828 100644 --- a/docs/architecture/routing-pages-and-patterns.md +++ b/docs/architecture/routing-pages-and-patterns.md @@ -290,6 +290,10 @@ chunk recovery 순서: "한 번 새로고침" 버튼이 있다(`app-router.tsx`의 `RouteFailureSurface`). - 복구하지 못한 청크 실패: 같은 형식이다. `ChunkRecoveryBoundary`의 `onUnrecovered`가 같은 ID로 `ui.render.failed`를 기록한다. +- context가 라우트나 레이아웃을 불러오지 못한 실패: `route_id`는 그 URL의 등록 + 라우트 id다. 등록 라우트가 없는 URL이면 `UNREGISTERED_ROUTE`다. not-found + 화면이 실패한 것이 아니므로 `NOT_FOUND`를 쓰지 않는다(`app-router.tsx`의 + `failedRouteIdAt`). - 조회 실패: `AppFailure.requestId`. HTTP 진단의 `correlation_id`와 같은 값이다 (`async-surface.tsx`의 `TerminalErrorSurface`). diff --git a/src/contracts/routes.ts b/src/contracts/routes.ts index 8abbad36..e4bcf431 100644 --- a/src/contracts/routes.ts +++ b/src/contracts/routes.ts @@ -97,6 +97,14 @@ export const PLATFORM_ROUTE_REGISTRY = Object.freeze({ }), }); +/** + * 1101/14.3. The `route_id` a render failure reports when no registered route + * names the URL: a context failed to load at an address none of its routes + * has. NOT_FOUND would say the not-found page failed, and a context id is not + * a route id, which telemetry drops. + */ +export const UNREGISTERED_ROUTE_ID = "UNREGISTERED_ROUTE"; + /** * 09-03. Platform routes an installed feature may take over by declaring the * same route id: a product whose home is a feature screen. The feature's diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx index 1ecff079..d391d1a8 100644 --- a/src/presentation/routes/app-router.tsx +++ b/src/presentation/routes/app-router.tsx @@ -30,6 +30,7 @@ import { import { PLATFORM_ROUTE_REGISTRY, type RouteDefinition, + UNREGISTERED_ROUTE_ID, } from "../../contracts/routes.ts"; import { TEMPLATE_APP_MODULE } from "../../apps/template-app.ts"; import { @@ -468,6 +469,18 @@ function registeredRouteIdAt(pathname: string): string | undefined { return matchRoutes(routes, pathname)?.at(-1)?.route.id; } +/** + * 1101/14.3. The route a gateway or layout failure is reported under. The + * NOT_FOUND splat matches every URL, but there the context failed, not the + * not-found page. + */ +function failedRouteIdAt(pathname: string): string { + const routeId = registeredRouteIdAt(pathname); + return routeId === undefined || routeId === "NOT_FOUND" + ? UNREGISTERED_ROUTE_ID + : routeId; +} + /** The chunk that route recovers, to key chunk recovery on it. */ function routeChunkId(pathname: string): string | undefined { const routeId = registeredRouteIdAt(pathname); @@ -567,7 +580,7 @@ function ContextRouteGateway({ buildId={buildId} onUnrecovered={(incidentId) => diagnostics.reportRenderFailure({ - routeId: routeModule.id, + routeId: failedRouteIdAt(location.pathname), buildId, boundaryName: "route", incidentId, @@ -581,7 +594,7 @@ function ContextRouteGateway({ // evaluates, a feature runtime that does not load) escalates to the // context boundary, which reports it. withinContext( - registeredRouteIdAt(location.pathname) ?? routeModule.id, + failedRouteIdAt(location.pathname), , ) ); @@ -639,7 +652,7 @@ function ContextLayout({ buildId={buildId} onUnrecovered={(incidentId) => diagnostics.reportRenderFailure({ - routeId: registeredRouteIdAt(pathname) ?? "NOT_FOUND", + routeId: failedRouteIdAt(pathname), buildId, boundaryName: "route", incidentId, diff --git a/tests/component/context-boundary-diagnostics.test.tsx b/tests/component/context-boundary-diagnostics.test.tsx index 23f92f00..b71c1afb 100644 --- a/tests/component/context-boundary-diagnostics.test.tsx +++ b/tests/component/context-boundary-diagnostics.test.tsx @@ -3,6 +3,7 @@ import { render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { projectTelemetryEvent } from "../../src/contracts/telemetry.ts"; import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; import { AppRouter } from "../../src/presentation/routes/app-router.tsx"; @@ -105,10 +106,11 @@ async function expectReportedFailure( // React logs every caught render error; the assertions below are the point. vi.spyOn(console, "error").mockImplementation(() => {}); const record = vi.fn(); + const emit = vi.fn(); window.history.pushState({}, "", url); render( @@ -133,6 +135,9 @@ async function expectReportedFailure( }, }, ]); + // The same failure reaches telemetry, which takes route ids only. + const [telemetry] = emit.mock.calls.filter(([name]) => name === "ui.render.failed"); + expect(projectTelemetryEvent(telemetry?.[0], telemetry?.[1])).toMatchObject({ success: true }); } describe("context gateway failure diagnostics", () => { @@ -158,9 +163,10 @@ describe("context gateway failure diagnostics", () => { }); it("reports an unregistered handle refused while the routes load", async () => { - // No feature route owns this URL; the registry's NOT_FOUND splat does. + // 1101/14.3. No registered route names this URL. The context failed, not + // the not-found page, so the report must not say NOT_FOUND. await expectReportedFailure("/fixture/checked", { - routeId: "NOT_FOUND", + routeId: "UNREGISTERED_ROUTE", boundary: "route", }); }); diff --git a/tests/component/context-route-gateway.test.tsx b/tests/component/context-route-gateway.test.tsx index b4cba8d6..8295b0e1 100644 --- a/tests/component/context-route-gateway.test.tsx +++ b/tests/component/context-route-gateway.test.tsx @@ -3,6 +3,7 @@ import { act, render, screen, waitFor } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; +import { projectTelemetryEvent } from "../../src/contracts/telemetry.ts"; import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; import { AppRouter } from "../../src/presentation/routes/app-router.tsx"; @@ -147,4 +148,38 @@ describe("context route gateway", () => { await screen.findByText("새 버전으로 한 번만 전환합니다."), ).toBeVisible(); }); + + // 1101/14.3. Without a new deploy the download stays failed. The report + // names the route at the URL, or UNREGISTERED_ROUTE when no route does + // (not NOT_FOUND, whose page did not fail), and telemetry takes it: it + // accepts route ids only, so the context id was dropped there. + it.each([ + ["/fixture/items/new", "FIXTURE_ITEM_FORM"], + ["/fixture/items/new/unknown", "UNREGISTERED_ROUTE"], + ])("reports an unrecovered routes-module download at %s as %s", async (url, routeId) => { + const record = vi.fn(); + const emit = vi.fn(); + window.history.pushState({}, "", url); + render( + + + + + , + ); + + await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/); + expect(record).toHaveBeenCalledWith( + expect.objectContaining({ + eventId: "ui.render.failed", + context: expect.objectContaining({ route_id: routeId }), + }), + ); + const [telemetry] = emit.mock.calls.filter(([name]) => name === "ui.render.failed"); + expect(projectTelemetryEvent(telemetry?.[0], telemetry?.[1])).toMatchObject({ + success: true, + }); + }); }); From 846955498d759513fdbc920ca8cc6b316c488369 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:32:46 +0900 Subject: [PATCH 13/16] =?UTF-8?q?fix(apps):=20=EB=91=90=20=EA=B8=B0?= =?UTF-8?q?=EB=8A=A5=20=EB=9D=BC=EC=9A=B0=ED=8A=B8=EA=B0=80=20=EA=B0=99?= =?UTF-8?q?=EC=9D=80=20=EA=B2=BD=EB=A1=9C=EB=A5=BC=20=EC=93=B0=EB=A9=B4=20?= =?UTF-8?q?=EC=A1=B0=EB=A6=BD=20=EB=95=8C=20=EB=A7=89=EB=8A=94=EB=8B=A4=20?= =?UTF-8?q?(1101/14.4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 7d85589는 플랫폼 라우트가 가리는 기능 라우트를 막지만, 기능 라우트 둘이 같은 경로를 쓰는 경우는 막지 않는다. 라우터는 순위가 같은 경로를 선언 순서로 고르므로 뒤의 라우트는 그려지지 않는다. 메뉴와 레지스트리에는 그 라우트가 나온다. 파라미터 이름(`:orderId`와 `:itemId`)은 순위를 바꾸지 않으므로 이름만 다른 경로도 같은 경로다. R-B가 남긴 것으로 보고했다. 고른 방법: 같은 함수(assertFeatureRoutesReachOwningContext)에서 플랫폼 검사를 통과한 라우트마다 파라미터 이름을 지운 경로 모양을 기록하고, 이미 있으면 두 라우트와 기능 이름을 담아 throw한다. 앱 모듈을 평가할 때 실패하므로 09-06·09-03 검사와 같이 fail-closed다. APP_HOME 대체는 이 함수의 앞쪽 continue로 빠지고, 두 기능이 같은 플랫폼 라우트를 가져가는 경우는 기존 검사(withoutTakenOverPlatformRoutes)가 막는다. 버린 대안: 레지스트리 검사(check:routes)에서 경로 중복 보기. 그 검사는 route ID 중복만 보고, 라우터가 실제로 어떤 순위로 고르는지는 모른다. 위험·한계: 일부만 겹치는 경로(`/a/new`와 `/a/:id`)는 라우터가 정적 경로를 먼저 고르므로 막지 않는다. 그 경우는 accepts 테스트로 고정했다. splat(`*`) 기능 라우트끼리의 겹침은 모양 비교로만 본다. 검증: - RED: 새 테스트 2건 중 "같은 경로 거절"이 실패(22/23 통과) - GREEN: tests/architecture와 라우트 component 테스트 75건 통과 - tests/unit·component·integration·features 253파일 3,153건 통과 - tsc app·test, eslint 통과 --- src/apps/deployable-app-module.ts | 24 ++++++++++++----- .../architecture/context-route-roots.test.ts | 26 +++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/apps/deployable-app-module.ts b/src/apps/deployable-app-module.ts index c3766b0c..d25f93b5 100644 --- a/src/apps/deployable-app-module.ts +++ b/src/apps/deployable-app-module.ts @@ -64,7 +64,8 @@ export function defineDeployableAppModule(); for (const context of contexts) { for (const feature of context.features) { for (const [routeId, path] of contractRoutePaths(feature.contracts)) { @@ -104,11 +106,21 @@ function assertFeatureRoutesReachOwningContext( path: context.route.loadLayout ? path : context.route.path, }; const answered = matchRoutes([...platformRoutes, mount], path)?.[0]?.route; - if (answered === mount) continue; - throw new TypeError( - `Route ${routeId} (${path}) of feature ${feature.id} in context ${context.id} is answered by platform route ${answered?.id} (${answered?.path}). ` + - `A feature replaces a platform route only by declaring its id (${FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS.join(", ")}).`, - ); + if (answered !== mount) { + throw new TypeError( + `Route ${routeId} (${path}) of feature ${feature.id} in context ${context.id} is answered by platform route ${answered?.id} (${answered?.path}). ` + + `A feature replaces a platform route only by declaring its id (${FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS.join(", ")}).`, + ); + } + // Parameter names do not change how the router ranks a path. + const shape = path.replace(/:[^/]+/g, ":"); + const earlier = claimed.get(shape); + if (earlier !== undefined) { + throw new TypeError( + `Route ${routeId} (${path}) of feature ${feature.id} has the same path as route ${earlier}: the router renders only the first.`, + ); + } + claimed.set(shape, `${routeId} (${path}) of feature ${feature.id}`); } } } diff --git a/tests/architecture/context-route-roots.test.ts b/tests/architecture/context-route-roots.test.ts index 0d66c849..2f97c373 100644 --- a/tests/architecture/context-route-roots.test.ts +++ b/tests/architecture/context-route-roots.test.ts @@ -210,6 +210,32 @@ describe("feature routes and platform routes", () => { ).toThrow(/EXAMPLES_UI_COPY.*EXAMPLES_UI/); }); + it("rejects two feature routes with the same path, naming both", () => { + // The router ranks equal paths by order, so the second is never rendered. + // Parameter names do not change the rank. + expect(() => + app( + context("shop", "shop/*", [ + feature("orders", { ORDER_DETAIL: "/shop/items/:orderId" }), + feature("items", { ITEM_DETAIL: "/shop/items/:itemId" }), + ]), + ), + ).toThrow(/ITEM_DETAIL.*\/shop\/items\/:itemId.*items.*ORDER_DETAIL.*orders/); + }); + + it("accepts a static path next to a parameter at the same depth", () => { + expect(() => + app( + context("shop", "shop/*", [ + feature("items", { + ITEM_NEW: "/shop/items/new", + ITEM_DETAIL: "/shop/items/:itemId", + }), + ]), + ), + ).not.toThrow(); + }); + it("rejects `/` under another id, which the platform home answers", () => { expect(() => app(context("site", "*", [feature("site", { SITE_HOME: "/" })], layout)), From 267c72459eef4c7d13fa81c29348c0fb5a8012fd Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:47:03 +0900 Subject: [PATCH 14/16] =?UTF-8?q?test(e2e):=20=EB=B9=A0=EC=A7=84=20?= =?UTF-8?q?=ED=8E=98=EC=9D=B4=EC=A7=80=EC=99=80=20=EA=B0=99=EC=9D=B4=20pre?= =?UTF-8?q?load=ED=95=9C=20=EC=B2=AD=ED=81=AC=EC=9D=98=20WebKit=20?= =?UTF-8?q?=EA=B2=BD=EA=B3=A0=EB=A5=BC=20=ED=97=88=EC=9A=A9=ED=95=9C?= =?UTF-8?q?=EB=8B=A4=20(1101/14.3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 webkit에서 old-tab-chunk-recovery.spec.ts가 가끔 실패한다. WebKit은 문서의 load 이벤트 3초 뒤에 한 번, 아직 쓰지 않은 link preload마다 경고를 남기고 strict console 검사가 그 경고를 실패로 본다. - A 탭에서 B를 배포하고 플랫폼 화면을 누르면, Vite preload helper가 페이지 청크와 그 청크가 import하는 badge·card·schema-registry·server-state를 같이 preload한다. 페이지 청크가 404라 import가 실패하고, 같이 받은 청크는 끝까지 쓰이지 않는다. 복구가 release manifest를 읽는 동안 A 문서가 load+3초를 넘기면 경고 4줄이 나온다. B 탭의 UI 화면에서도 같은 일이 생긴다 (text-field). - 그 청크들은 플랫폼 화면이 실제로 import한다(.vite/manifest.json). 앱이 쓰지 않는 청크를 preload하는 것이 아니다. 경고는 테스트가 일부러 지운 청크의 결과다. - 08-08과의 관계: 원인이 아니다. 08-08 전(e1a4580) 빌드에서도 플랫폼 화면은 lazy 청크 schema-registry·server-state를 같이 preload한다. 08-08은 목록에 badge·card를 더했을 뿐이고, 목록이 비어 있지 않으면 같은 경고가 나온다. - 간헐인 이유: 클릭이 load+3초 전에 일어나고 문서가 load+3초 뒤까지 남을 때만 경고가 나온다. 부하가 높을수록 자주 맞는다. 고른 방법 - 이 spec의 허용 목록에 WebKit 경고 문구 하나를 더한다. WebKit에서만, 빠진 두 페이지가 import하는 청크 이름만 허용한다. 이름은 고정하지 않고 각 빌드의 .vite/manifest.json에서 정적 import를 따라가 구한다(A의 플랫폼 화면, B의 UI 화면). 다른 청크의 같은 경고와 다른 브라우저는 그대로 실패한다. 버린 대안 - preload를 끄거나 줄이기(build.modulePreload): 모든 lazy 화면에서 페이지 청크를 받은 뒤 import를 다시 받는 왕복이 하나 는다. 테스트 경고 하나 때문에 세 브라우저의 화면 전환을 느리게 할 이유가 없다. - B 배포 전에 3초 넘게 기다리기: "오래 열린 탭"에는 맞지만 WebKit 내부 상수 (3초)에 묶인 고정 대기이고, 경고를 설명하지 않고 피한다. - strict-browser-test.ts 전역 허용: 다른 spec의 진짜 unused preload까지 덮는다. 위험·한계 - 허용 범위는 manifest에서 구한 청크 목록이다. 실제 preload 목록은 Vite가 만드는 __vite__mapDeps이고, 둘이 갈라지면 경고가 다시 실패로 나온다(덮이지 않는 쪽으로 틀린다). - WebKit 문구가 바뀌면 다시 실패한다. 검증 - RED(ec7435c, webkit, flock, workers 1) - 그대로 30회: 2회 실패(경고 4줄, badge·card·schema-registry·server-state), loadavg 14.8~17. - 시점 고정 재현(scratch spec, 원본 수정 없음): 복구의 manifest 응답을 3.5초 늦추면 3/3 실패(같은 4줄). UI 오류 뒤 3.5초 기다리면 2/2 실패 (text-field 1줄). - GREEN - 시점 고정 재현 두 가지를 고친 spec으로: 6/6 통과. - 그대로 30회: workers 1에서 30/30 통과(loadavg 3.9~8.4), workers 3에서 30/30 통과(loadavg 9.0~18.0, 평균 14). - chromium·firefox: 각 3회 통과. 시점 고정 재현도 두 엔진에서 경고 없이 통과한다(이 경고는 WebKit만 낸다). - webkit e2e 전체(preview 빌드, 11 workers): 63/63 통과(loadavg 5.2~19.9). - npx tsc --project tsconfig.test.json --noEmit, npx eslint (바꾼 파일) 통과. --- tests/e2e/old-tab-chunk-recovery.spec.ts | 68 ++++++++++++++++++------ 1 file changed, 52 insertions(+), 16 deletions(-) diff --git a/tests/e2e/old-tab-chunk-recovery.spec.ts b/tests/e2e/old-tab-chunk-recovery.spec.ts index 9ef45f8c..142eed2f 100644 --- a/tests/e2e/old-tab-chunk-recovery.spec.ts +++ b/tests/e2e/old-tab-chunk-recovery.spec.ts @@ -21,10 +21,9 @@ import { startBuildServer } from "./support/service-worker-builds.ts"; const PLATFORM = ROUTE_REGISTRY.EXAMPLES_PLATFORM; const UI = ROUTE_REGISTRY.EXAMPLES_UI; -const PAGES = [ - "src/presentation/examples/platform-overview-page.tsx", - "src/presentation/examples/ui-gallery-page.tsx", -] as const; +const PLATFORM_PAGE = "src/presentation/examples/platform-overview-page.tsx"; +const UI_PAGE = "src/presentation/examples/ui-gallery-page.tsx"; +const PAGES = [PLATFORM_PAGE, UI_PAGE] as const; let builds: FixtureBuilds<"a" | "b"> | undefined; @@ -60,20 +59,57 @@ async function routeChunk(dist: string, chunkId: string): Promise { // Each missing page chunk fails its request and the dynamic import. Chromium // may also log the 404 itself (without its URL), Firefox logs the error // object React caught, and WebKit logs its own import error without the URL. -// Nothing else is allowed. +// Nothing else is allowed, but for the WebKit warning below. const MISSING_PAGE = String.raw`/assets/(?:platform-overview|ui-gallery)-page-[\w-]+\.js`; +const MISSING_PAGE_FAILURES = [ + String.raw`^requestfailed:GET:${MISSING_PAGE}:`, + String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${MISSING_PAGE}$`, + String.raw`^console:error:\[JavaScript Error: "Loading module from “http://127\.0\.0\.1:\d+${MISSING_PAGE}” was blocked`, + String.raw`^console:error:Failed to load resource: the server responded with a status of 404 \(Not Found\)$`, + String.raw`^console:error:JSHandle@object$`, + String.raw`^console:error:TypeError: Importing a module script failed\.$`, +]; + +/** The chunks Vite preloads with `page`: its static imports in `dist`. */ +async function preloadedWith(dist: string, page: string): Promise { + const manifest = JSON.parse( + await readFile(path.join(dist, ".vite/manifest.json"), "utf8"), + ) as Record; + if (!manifest[page]) throw new Error(`${page} is not in ${dist}'s manifest.`); + const files = new Set(); + const pending = [...(manifest[page].imports ?? [])]; + for (let key = pending.pop(); key !== undefined; key = pending.pop()) { + const entry = manifest[key]; + if (!entry || files.has(entry.file)) continue; + files.add(entry.file); + pending.push(...(entry.imports ?? [])); + } + return [...files]; +} + +// WebKit only. Three seconds after a document's load event, WebKit warns once +// for each link-preloaded resource the document has not used yet. Vite +// preloads a page chunk together with the chunks it imports, so a missing page +// leaves the chunks preloaded with it unused: in the A tab those of A's +// platform page (the tab is still on A while recovery reads the release +// manifest), in the B tab those of B's UI page. Whether that check runs before +// the reload, or before the test ends, is timing, so the warnings come and go. +// They are the provoked failure's own effect; only those chunks are allowed. test.use({ - allowedBrowserFailure: new RegExp( - [ - String.raw`^requestfailed:GET:${MISSING_PAGE}:`, - String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${MISSING_PAGE}$`, - String.raw`^console:error:\[JavaScript Error: "Loading module from “http://127\.0\.0\.1:\d+${MISSING_PAGE}” was blocked`, - String.raw`^console:error:Failed to load resource: the server responded with a status of 404 \(Not Found\)$`, - String.raw`^console:error:JSHandle@object$`, - String.raw`^console:error:TypeError: Importing a module script failed\.$`, - ].join("|"), - "u", - ), + allowedBrowserFailure: async ({ browserName }, provide) => { + const patterns = [...MISSING_PAGE_FAILURES]; + if (browserName === "webkit") { + if (!builds) throw new Error("Fixture builds were not prepared."); + const files = [ + ...(await preloadedWith(builds.dist.a, PLATFORM_PAGE)), + ...(await preloadedWith(builds.dist.b, UI_PAGE)), + ].map((file) => file.replaceAll(".", String.raw`\.`)); + patterns.push( + String.raw`^console:warning:The resource http://127\.0\.0\.1:\d+/(?:${files.join("|")}) was preloaded using link preload but not used within a few seconds from the window's load event\. Please make sure it wasn't preloaded for nothing\.$`, + ); + } + await provide(new RegExp(patterns.join("|"), "u")); + }, }); test("an old tab reloads once into the new build, then stops reloading", async ({ From 3f9c0877985ee8337d0e7282d3b17db2d558cb49 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:47:08 +0900 Subject: [PATCH 15/16] =?UTF-8?q?docs(performance):=20=EC=B4=88=EA=B8=B0?= =?UTF-8?q?=20=EC=B2=AD=ED=81=AC=20=EC=88=98=EC=9D=98=20HTTP/1.1=20?= =?UTF-8?q?=EB=B9=84=EC=9A=A9=EC=9D=84=20=EC=9E=AC=EA=B3=A0=20=EB=AC=B6?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EB=8A=94=20=EA=B7=BC=EA=B1=B0=EB=A5=BC=20?= =?UTF-8?q?=EC=A0=81=EB=8A=94=EB=8B=A4=20(1101/14.4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 08-08은 초기 JS 바이트를 줄이는 대신 초기 파일을 16개에서 25개(entry 포함 26개)로 늘렸고, "HTTP/1.1 호스팅이면 다시 본다"를 남겼다. vite preview도 HTTP/1.1이다. 비용을 잰 적이 없어 위험이 열려 있었다. 고른 방법 - 지금 빌드와 묶은 빌드 두 가지를 쟀다. (가) 08-08이 나눈 초기 primitive 청크 4개(field·button·select·page-templates)를 하나로. (나) 묶을 수 있는 초기 청크 14개를 하나로(entry·preload-helper·boot, 부트 실패 화면 closure, 15-01 그룹은 뺐다). 같은 커밋을 임시 복사본에서 그룹 하나만 더해 빌드했다. - 측정: vite preview(HTTP/1.1, gzip), Chromium CDP 네트워크 에뮬레이션 (DevTools Fast 3G·Fast 4G 값), 새 context·캐시 없음, 첫 화면 = boot 셸이 사라지고 route h1이 들어온 시각. 세 빌드를 번갈아 7번씩, 중앙값. HTTP/2(node:http2, 자체 서명 인증서, gzip)도 같은 방법으로 쟀다. - 결과(Fast 3G / Fast 4G 중앙값) - 지금 26개 202,782 B: 5,887 / 1,874 ms - (가) 23개 201,818 B: 5,426 / 1,764 ms - (나) 13개 198,673 B: 4,930 / 1,535 ms - HTTP/2: 지금 4,793 / 1,444, (가) 4,769 / 1,440, (나) 4,708 / 1,422 ms - 판단: 묶지 않는다. 측정값과 판단을 performance-evidence.md에 적고, vite.config.ts의 "재검토" 주석이 그 절을 가리키게 한다. - (가)·(나)는 이 빌드의 청크 안 모듈 목록을 그대로 적어 만들었다. 규칙으로 고를 방법이 없었다. boot 정적 closure는 design-system 배럴을 지나 갤러리 전용 primitive까지 잡는다. rolldown `$initial` 태그는 entry가 앱을 dynamic import로 읽어서(09-03) 아무것도 잡지 않는다. boot.tsx를 entry로 더하면 manifest 분류가 lazy 화면까지 초기로 센다(28개, 216,820 B, 예산 초과). - 고정 목록은 셸이 쓰는 primitive가 바뀔 때마다 맞춰야 하고, 낡아도 실패하는 검사가 없다. 08-08이 같은 이유로 manualChunks 이름 고정을 버렸다. - 템플릿은 HTTP/2 이상 서빙을 전제로 본다. HTTP/1.1로만 서빙하는 제품은 (나) 같은 그룹을 넣고 셸을 바꿀 때마다 다시 잰다고 문서에 적었다. 버린 대안 - (나)를 고정 목록으로 넣기: HTTP/1.1에서 Fast 3G 0.96초 빠르지만 숨은 결합이다(위). - (가)만 넣기: 0.46초. 같은 이유. 위험·한계 - HTTP/1.1로 서빙하는 다운스트림은 첫 화면이 Fast 3G에서 약 1초 늦다. 이 커밋은 그 비용을 없애지 않고 숫자와 전제를 적는다. 호스팅 HTTP 버전을 검사하는 게이트는 없다(FE-GATE-019 probe 밖). - 측정은 이 머신의 loopback과 CDP 에뮬레이션이다. 연결 수립(TCP·TLS) 비용은 CDP 지연에 들어가지 않는다. loadavg는 HTTP/1.1 측정 6~20, HTTP/2 측정 3~6이라 두 표끼리는 비교하지 않는다. 각 표 안은 번갈아 재서 비교할 수 있다. 검증 - 빌드 바이트: classify-vite-bundle + gzipSync(check:bundle과 같은 계산). 지금 빌드는 기준 202,770 B(local-build)와 맞다. - 측정 스크립트와 로그는 커밋하지 않았다(worktree의 .tmp/ra/, 일회성). - node scripts/verify-documentation-readiness.ts: PASS_SCOPED. - npx eslint vite.config.ts, npx tsc --project tsconfig.node.json --noEmit 통과. --- docs/operations/performance-evidence.md | 61 +++++++++++++++++++++++++ vite.config.ts | 7 +-- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/docs/operations/performance-evidence.md b/docs/operations/performance-evidence.md index be7cf23e..6bf1c888 100644 --- a/docs/operations/performance-evidence.md +++ b/docs/operations/performance-evidence.md @@ -96,3 +96,64 @@ threshold-decision references, and contain only non-negative route-ID samples. The environment threshold must be a positive integer equal to the approved decision embedded in the input. Invalid metadata fails as `FAIL_UNVERIFIED`; the example can never serve as production evidence. + +## 초기 청크 수와 HTTP/1.1 + +리뷰 1101/14.4. 08-08은 초기 JS 바이트를 줄이는 대신 초기 파일 수를 늘렸다 +(`vite.config.ts`의 `moduleSideEffects` 주석). HTTP/1.1에서 브라우저는 한 +호스트에 연결을 6개까지만 연다. 파일이 많으면 요청이 줄을 서서 왕복이 는다. +그래서 지금 빌드와 작은 초기 청크를 하나로 묶은 빌드를 쟀다(2026-11-03, +커밋 `ec7435c`). + +| 빌드 | 초기 JS 파일(entry 포함) | 초기 JS gzip(B) | 첫 화면까지 JS 요청 | Fast 3G 첫 화면 | Fast 4G 첫 화면 | +|---|---:|---:|---:|---:|---:| +| 지금 | 26 | 202,782 | 27 | 5,887 ms | 1,874 ms | +| (가) 08-08이 나눈 초기 primitive 청크 4개(`field`·`button`·`select`·`page-templates`)를 하나로 | 23 | 201,818 | 24 | 5,426 ms | 1,764 ms | +| (나) 묶을 수 있는 초기 청크 14개를 하나로 | 13 | 198,673 | 14 | 4,930 ms | 1,535 ms | + +같은 빌드를 HTTP/2로 서빙하면(`node:http2`, 자체 서명 인증서, gzip) 차이가 +거의 없다. + +| 빌드 | Fast 3G 첫 화면 | Fast 4G 첫 화면 | +|---|---:|---:| +| 지금 | 4,793 ms | 1,444 ms | +| (가) | 4,769 ms | 1,440 ms | +| (나) | 4,708 ms | 1,422 ms | + +측정 조건: + +- `vite preview`(HTTP/1.1, gzip 응답)로 띄우고 Chromium으로 잰다. 네트워크는 + CDP `Network.emulateNetworkConditions`에 DevTools 프리셋 값을 넣었다. Fast + 3G는 지연 562.5 ms·내려받기 180,000 B/s, Fast 4G는 165 ms·1,012,500 B/s다. +- 매번 새 browser context에서 캐시 없이 `/`를 연다. 첫 화면은 boot 셸이 + 사라지고 `#main-content h1[data-route-heading]`가 DOM에 들어온 시각이다 + (`performance.now()`). +- 세 빌드를 번갈아 7번씩 재고 중앙값을 적었다. 7번의 범위는 지금 5,866~6,077 ms, + (가) 5,384~5,652 ms, (나) 4,891~5,032 ms다(Fast 3G). loadavg는 HTTP/1.1 + 측정 때 6~20, HTTP/2 측정 때 3~6이었다. 그래서 두 표끼리는 비교하지 않는다. +- CDP 지연은 요청마다 붙는다. 연결 수립(TCP·TLS) 비용은 따로 재지 않았다. +- (나)에서 묶지 않은 것: entry·`preload-helper`·`boot`, 부트 실패 화면이 쓰는 + 모듈(`render-boot-failure`·react·react-dom·`jsx-runtime`·`operation-id`· + `diagnostics`·`boot-messages`, 09-03), 15-01의 `feature-declarations`· + `feature-platform`. + +판단: 지금은 묶지 않는다. + +- HTTP/1.1에서는 묶는 편이 빠르다. Fast 3G에서 (가) 0.46초, (나) 0.96초 + 빨라지고 초기 JS도 조금 준다. +- 그러나 (가)·(나)는 이 빌드의 청크 안 모듈 목록을 그대로 적어 만들었다. + 규칙으로 고르는 방법은 찾지 못했다. + - 모듈 그래프로 boot의 정적 closure를 따라가면 design-system 배럴을 지나 + 갤러리 전용 primitive까지 잡힌다. 그 primitive가 다시 초기 청크로 간다. + - rolldown의 `$initial` 태그는 entry가 앱을 dynamic import로 읽어서(09-03) + 아무것도 잡지 않는다. + - `boot.tsx`를 entry로 더하면 manifest 분류가 lazy 화면까지 초기로 센다 + (28개, 216,820 B로 예산 초과). +- 고정 목록은 셸이 쓰는 primitive가 바뀔 때마다 다시 맞춰야 한다. 목록이 + 낡아도 실패하는 검사가 없다. 08-08이 같은 이유로 `manualChunks` 이름 고정을 + 버렸다. +- HTTP/2에서는 (나)도 Fast 3G 85 ms, Fast 4G 22 ms 차이다(위 둘째 표). + +그래서 템플릿은 HTTP/2 이상으로 서빙한다고 본다. HTTP/1.1로만 서빙해야 하는 +제품은 (나)처럼 초기 청크를 묶는 그룹을 `vite.config.ts`에 넣는다. 그 목록은 +셸을 바꿀 때마다 위 방법으로 다시 잰다. diff --git a/vite.config.ts b/vite.config.ts index 6794e7f2..86bdfe88 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -161,9 +161,10 @@ export default defineConfig(({ mode }) => { * * Trade: at 08-08 the initial JavaScript fell by 2,718 gzip bytes * and the initial chunks rose from 16 to 25. The entry preloads them - * in parallel, so over HTTP/2 they add no round trip. Revisit when - * the app is served over HTTP/1.1, where every chunk costs a - * connection slot. + * in parallel, so over HTTP/2 they add no round trip. Over HTTP/1.1 + * they queue for six connections; 1101/14.4 measured that cost and + * why the chunks stay split ("초기 청크 수와 HTTP/1.1" in + * docs/operations/performance-evidence.md). */ treeshake: { moduleSideEffects: [ From 8c39e773768a388d0f899b7361440dc3becb83da Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:48:19 +0900 Subject: [PATCH 16/16] =?UTF-8?q?docs(delivery):=20=EC=A0=95=EC=A0=81=20?= =?UTF-8?q?=EB=B0=B0=ED=8F=AC=20=EB=AC=B8=EC=84=9C=EC=97=90=20HTTP/2=20?= =?UTF-8?q?=EC=84=9C=EB=B9=99=20=EC=A0=84=EC=A0=9C=EB=A5=BC=20=EC=A0=81?= =?UTF-8?q?=EB=8A=94=EB=8B=A4=20(1101/14.4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 3f9c087은 초기 청크를 묶지 않는 근거로 "템플릿은 HTTP/2 이상으로 서빙한다"를 정했다. 그런데 이 전제는 작업 기록인 performance-evidence.md 에만 있다. 호스팅을 정하는 사람이 읽는 현재 계약 문서(static-delivery.md) 에는 서빙 프로토콜 이야기가 없다. 고른 방법: static-delivery.md 끝에 한 단락을 더한다. HTTP/2 이상으로 서빙한다는 것, HTTP/1.1에서 늦어지는 정도(Fast 3G 약 1초), HTTP/2에서의 차이(100 ms 미만), HTTP/1.1만 되는 제품이 할 일을 적고 측정 기록으로 링크한다. 버린 대안: README의 배포 절에 적기. README는 배포 변수와 명령을 다루고, 호스트 동작은 static-delivery.md가 다룬다. 위험·한계: 수치는 2026-11-03 한 번의 측정이다. 셸이 바뀌면 달라진다. 검증: node scripts/verify-documentation-readiness.ts PASS_SCOPED --- docs/architecture/static-delivery.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/architecture/static-delivery.md b/docs/architecture/static-delivery.md index ebbfde80..44e0b685 100644 --- a/docs/architecture/static-delivery.md +++ b/docs/architecture/static-delivery.md @@ -39,3 +39,13 @@ that the host serves that release; while the slot is empty FE-GATE-019 is Rollback changes the active pointer only after confirming that the prior immutable release has a coherent HTML/assets/config/API/manifest tuple. + +Serve the app over HTTP/2 or later. The entry preloads about 26 initial +JavaScript files in parallel. Over HTTP/1.1 they queue for six connections per +host, and the first screen on Fast 3G came about one second later than with the +initial chunks grouped (2026-11-03). Over HTTP/2 the difference was under +100 ms, so the template keeps the chunks split. A product that can only serve +HTTP/1.1 groups its initial chunks in `vite.config.ts` and measures again +whenever the shell changes ("초기 청크 수와 HTTP/1.1" in +[`performance-evidence.md`](../operations/performance-evidence.md), review +1101/14.4).