diff --git a/.dependency-cruiser.json b/.dependency-cruiser.json
index ea20ba8..f3ffd9d 100644
--- a/.dependency-cruiser.json
+++ b/.dependency-cruiser.json
@@ -191,6 +191,19 @@
"pathNot": "^src/adapters/($1/|platform/|browser-file-storage/result\\.ts$|cross-context-invalidation/index\\.ts$)"
}
},
+ {
+ "name": "adapter-groups-are-reached-through-their-barrel",
+ "comment": "어댑터 그룹의 공개 표면은 그 그룹의 index.ts다. 그룹 바깥(bootstrap, features, presentation)은 배럴만 import한다. 배럴이 없던 시절 bootstrap은 어댑터 내부 파일 15곳을 직접 겨눴고, 그래서 어떤 파일이 공개이고 어떤 파일이 내부 헬퍼인지 아무 데도 적혀 있지 않았다. 출발점에서 src/adapters를 뺀 이유는 어댑터끼리의 간선은 바로 위 adapters-do-not-know-other-concrete-adapters가 이미 담당하고, 커널(platform/**)은 파일 단위로 공유되기 때문이다 — scripts/check-adapter-inventory.ts가 네 소비자에게 platform/abortable-operation.ts로 해석되는 specifier를 직접 요구한다. 도착점에서 1단계 중첩 index.ts를 허용한 이유는 storage/indexeddb와 storage/opfs가 각자 독립적으로 제거 가능한 런타임이고(scripts/test-browser-file-storage-runtime-removal.ts), 그래서 각자의 배럴이 곧 경계이기 때문이다.",
+ "severity": "error",
+ "from": {
+ "path": "^src/",
+ "pathNot": "^src/adapters/"
+ },
+ "to": {
+ "path": "^src/adapters/[^/]+/",
+ "pathNot": "^src/adapters/[^/]+/index\\.ts$|^src/adapters/[^/]+/[^/]+/index\\.ts$"
+ }
+ },
{
"name": "no-circular-dependencies",
"severity": "error",
diff --git a/.storybook/preview.tsx b/.storybook/preview.tsx
index 3dca769..2d0e868 100644
--- a/.storybook/preview.tsx
+++ b/.storybook/preview.tsx
@@ -2,8 +2,8 @@ import type { Preview } from "@storybook/react-vite";
import { QueryClientProvider } from "@tanstack/react-query";
import { MemoryRouter } from "react-router-dom";
-import { createAnonymousSessionAdapter } from "../src/adapters/auth/external-session-adapter.ts";
-import { createQueryClient } from "../src/adapters/query-cache/tanstack-query-cache.ts";
+import { createAnonymousSessionAdapter } from "../src/adapters/auth/index.ts";
+import { createQueryClient } from "../src/adapters/query-cache/index.ts";
import { createApplication } from "../src/application/create-application.ts";
import { LocaleProvider } from "../src/presentation/i18n/index.ts";
import { ApplicationProvider } from "../src/presentation/providers/application-provider.tsx";
diff --git a/README.md b/README.md
index ff96f28..af69d01 100644
--- a/README.md
+++ b/README.md
@@ -132,16 +132,22 @@ hand-written:
## Architecture
+This repository is a **Frontend Application Foundation**: a starter/composition
+skeleton plus a reusable capability platform. Platform capabilities stay
+horizontal while product business features use vertical slices.
+
Dependencies point inward:
```text
presentation -> application -> domain
adapters -----^
bootstrap composes concrete adapters
-contracts own cross-cutting registries
+feature use case -> feature port <- feature-owned capability binding
```
-See `docs/architecture/overview.md`, `docs/architecture/layers.md`, and
+See
+`docs/architecture/frontend-application-foundation.md`,
+`docs/architecture/overview.md`, `docs/architecture/layers.md`, and
`docs/architecture/starter-experience.md`. TechLog is one feature boundary
under `src/features/tech-log`. Its immutable Public catalog and session-scoped
Studio mock gateway are injected through the application feature input;
@@ -190,6 +196,7 @@ corepack pnpm check:types:node
corepack pnpm check:types:test
corepack pnpm check:architecture
corepack pnpm test:all
+corepack pnpm test:contract
corepack pnpm test:e2e
corepack pnpm test:a11y
corepack pnpm build
@@ -205,6 +212,11 @@ corepack pnpm exec playwright test tests/e2e/tech-log-public-discovery.spec.ts t
corepack pnpm test:visual
```
+`test:all` is the ordinary product-development loop and intentionally excludes
+host-level CI-runner assurance. Run `corepack pnpm test:system` only on the
+compatible Linux assurance host described in
+[`docs/testing/taxonomy.md`](docs/testing/taxonomy.md).
+
`check:types`는 source, Node scripts/config와 tests를 분리된 TypeScript
project로 모두 검사한다. type/architecture/security/registry의 invalid
fixture는 `config/ci/gates.json`에서 “실패해야 통과”하는 negative gate로
@@ -251,7 +263,7 @@ Live release verification additionally requires `HOSTING_BASE_URL`.
## CI and evidence
-The 26-gate registry is `config/ci/gates.json`; the Gitea workflow is
+The 27-gate registry is `config/ci/gates.json`; the Gitea workflow is
`.gitea/workflows/quality-gates.yml`. It follows:
```text
diff --git a/config/ci/gates.json b/config/ci/gates.json
index 814bf30..934f074 100644
--- a/config/ci/gates.json
+++ b/config/ci/gates.json
@@ -81,6 +81,55 @@
"script": "check:types:fixture:reference-operation",
"expect": "fail",
"expectedExitCode": 1,
+ "expectedDiagnosticId": "error TS2741:"
+ },
+ {
+ "id": "check-types-fixture-http-operation-input",
+ "script": "check:types:fixture:http-operation-input",
+ "expect": "fail",
+ "expectedExitCode": 1,
+ "expectedDiagnosticId": "error TS2353:"
+ },
+ {
+ "id": "check-types-fixture-http-wire-mapper",
+ "script": "check:types:fixture:http-wire-mapper",
+ "expect": "fail",
+ "expectedExitCode": 1,
+ "expectedDiagnosticId": "error TS2322:"
+ },
+ {
+ "id": "check-types-fixture-http-operation-id",
+ "script": "check:types:fixture:http-operation-id",
+ "expect": "fail",
+ "expectedExitCode": 1,
+ "expectedDiagnosticId": "error TS2345:"
+ },
+ {
+ "id": "check-types-fixture-http-route-id",
+ "script": "check:types:fixture:http-route-id",
+ "expect": "fail",
+ "expectedExitCode": 1,
+ "expectedDiagnosticId": "error TS2322:"
+ },
+ {
+ "id": "check-types-fixture-feature-contribution-input",
+ "script": "check:types:fixture:feature-contribution-input",
+ "expect": "fail",
+ "expectedExitCode": 1,
+ "expectedDiagnosticId": "error TS2322:"
+ },
+ {
+ "id": "check-types-fixture-feature-capability-selection",
+ "script": "check:types:fixture:feature-capability-selection",
+ "expect": "fail",
+ "expectedExitCode": 1,
+ "expectedDiagnosticId": "error TS2339:"
+ },
+ {
+ "id": "check-types-fixture-direct-feature-composition",
+ "script": "check:types:fixture:direct-feature-composition",
+ "expect": "fail",
+ "expectedExitCode": 1,
"expectedDiagnosticId": "error TS2345:"
},
{
@@ -95,7 +144,7 @@
"script": "check:types:fixture:route-runtime",
"expect": "fail",
"expectedExitCode": 1,
- "expectedDiagnosticId": "error TS2353:"
+ "expectedDiagnosticId": "error TS2740:"
},
{
"id": "check-types-fixture-page-action",
@@ -142,6 +191,11 @@
"script": "test:unit",
"expect": "pass"
},
+ {
+ "id": "test-contract",
+ "script": "test:contract",
+ "expect": "pass"
+ },
{
"id": "test-coverage",
"script": "test:coverage",
@@ -164,6 +218,11 @@
"script": "test:integration",
"expect": "pass"
},
+ {
+ "id": "test-system",
+ "script": "test:system",
+ "expect": "pass"
+ },
{
"id": "test-http-scenario-evidence",
"script": "test:http-scenario-evidence",
@@ -809,6 +868,15 @@
"test-unit"
]
},
+ {
+ "id": "artifact-artifacts-tests-contract-xml",
+ "path": "artifacts/tests/contract.xml",
+ "schemaId": "junit",
+ "production": "command-generated",
+ "producerCommandIds": [
+ "test-contract"
+ ]
+ },
{
"id": "artifact-artifacts-tests-coverage-xml",
"path": "artifacts/tests/coverage.xml",
@@ -875,6 +943,15 @@
"test-integration"
]
},
+ {
+ "id": "artifact-artifacts-tests-system-xml",
+ "path": "artifacts/tests/system.xml",
+ "schemaId": "junit",
+ "production": "command-generated",
+ "producerCommandIds": [
+ "test-system"
+ ]
+ },
{
"id": "artifact-artifacts-tests-http-scenario-executions-json",
"path": "artifacts/tests/http-scenario-executions.json",
@@ -1862,6 +1939,13 @@
"check-types-fixture-feature-input",
"check-types-fixture-failure-kind",
"check-types-fixture-reference-operation",
+ "check-types-fixture-http-operation-input",
+ "check-types-fixture-http-wire-mapper",
+ "check-types-fixture-http-operation-id",
+ "check-types-fixture-http-route-id",
+ "check-types-fixture-feature-contribution-input",
+ "check-types-fixture-feature-capability-selection",
+ "check-types-fixture-direct-feature-composition",
"check-types-fixture-async-overlay",
"check-types-fixture-route-runtime",
"check-types-fixture-page-action",
@@ -1893,12 +1977,14 @@
"name": "unit",
"commandIds": [
"test-unit",
+ "test-contract",
"test-coverage",
"check-coverage-fixture"
],
"logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-005-txt",
"evidenceArtifactIds": [
"artifact-artifacts-tests-unit-xml",
+ "artifact-artifacts-tests-contract-xml",
"artifact-artifacts-tests-coverage-xml",
"artifact-artifacts-tests-coverage-coverage-summary-json",
"artifact-artifacts-quality-risk-coverage-json",
@@ -2098,6 +2184,7 @@
"id": "FE-GATE-013",
"name": "security",
"commandIds": [
+ "test-system",
"verify-reproducible-build",
"build-release-candidate",
"verify-local-evidence",
@@ -2108,6 +2195,7 @@
],
"logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-013-txt",
"evidenceArtifactIds": [
+ "artifact-artifacts-tests-system-xml",
"artifact-artifacts-security-scan-sarif",
"artifact-artifacts-release-dependency-inventory-json",
"artifact-artifacts-release-sbom-cdx-json",
diff --git a/config/testing/risk-coverage.json b/config/testing/risk-coverage.json
index e2ef978..11cbb03 100644
--- a/config/testing/risk-coverage.json
+++ b/config/testing/risk-coverage.json
@@ -12,97 +12,192 @@
{
"path": "src/adapters/http/bounded-body-reader.ts",
"owner": "http-runtime",
- "minimum": { "lines": 95, "statements": 95, "functions": 95, "branches": 90 }
+ "minimum": {
+ "lines": 95,
+ "statements": 95,
+ "functions": 95,
+ "branches": 90
+ }
},
{
"path": "src/adapters/http/bounded-json.ts",
"owner": "http-runtime",
- "minimum": { "lines": 85, "statements": 84, "functions": 95, "branches": 78 }
+ "minimum": {
+ "lines": 85,
+ "statements": 84,
+ "functions": 95,
+ "branches": 78
+ }
},
{
"path": "src/adapters/http/http-execution-v3.ts",
"owner": "http-runtime",
- "minimum": { "lines": 75, "statements": 73, "functions": 70, "branches": 52 }
+ "minimum": {
+ "lines": 75,
+ "statements": 73,
+ "functions": 70,
+ "branches": 52
+ }
},
{
"path": "src/adapters/http/request-builder.ts",
"owner": "http-runtime",
- "minimum": { "lines": 85, "statements": 85, "functions": 95, "branches": 82 }
+ "minimum": {
+ "lines": 85,
+ "statements": 85,
+ "functions": 95,
+ "branches": 82
+ }
},
{
"path": "src/adapters/http/retry-policy.ts",
"owner": "http-runtime",
- "minimum": { "lines": 80, "statements": 78, "functions": 95, "branches": 78 }
+ "minimum": {
+ "lines": 80,
+ "statements": 78,
+ "functions": 95,
+ "branches": 78
+ }
},
{
"path": "src/adapters/query-cache/server-state-scope-runtime.ts",
"owner": "server-state-runtime",
- "minimum": { "lines": 85, "statements": 85, "functions": 85, "branches": 75 }
+ "minimum": {
+ "lines": 85,
+ "statements": 85,
+ "functions": 85,
+ "branches": 75
+ }
},
{
"path": "src/adapters/service-worker/service-worker-lifecycle.ts",
"owner": "service-worker-runtime",
- "minimum": { "lines": 64, "statements": 60, "functions": 65, "branches": 43 }
+ "minimum": {
+ "lines": 64,
+ "statements": 60,
+ "functions": 65,
+ "branches": 43
+ }
},
{
"path": "src/adapters/storage/browser-storage-adapter.ts",
"owner": "storage-runtime",
- "minimum": { "lines": 60, "statements": 60, "functions": 70, "branches": 60 }
+ "minimum": {
+ "lines": 60,
+ "statements": 60,
+ "functions": 70,
+ "branches": 60
+ }
},
{
"path": "src/adapters/telemetry/best-effort-telemetry.ts",
"owner": "telemetry-runtime",
- "minimum": { "lines": 85, "statements": 85, "functions": 70, "branches": 75 }
+ "minimum": {
+ "lines": 85,
+ "statements": 85,
+ "functions": 70,
+ "branches": 75
+ }
},
{
"path": "src/application/create-application.ts",
"owner": "application-runtime",
- "minimum": { "lines": 90, "statements": 90, "functions": 80, "branches": 68 }
+ "minimum": {
+ "lines": 90,
+ "statements": 90,
+ "functions": 80,
+ "branches": 68
+ }
},
{
- "path": "src/application/policies/compatibility.ts",
- "owner": "application-policy",
- "minimum": { "lines": 95, "statements": 95, "functions": 95, "branches": 75 }
+ "path": "src/contracts/compatibility.ts",
+ "owner": "compatibility-contracts",
+ "minimum": {
+ "lines": 95,
+ "statements": 95,
+ "functions": 95,
+ "branches": 75
+ }
},
{
"path": "src/application/policies/performance-budgets.ts",
"owner": "application-policy",
- "minimum": { "lines": 80, "statements": 80, "functions": 80, "branches": 40 }
+ "minimum": {
+ "lines": 80,
+ "statements": 80,
+ "functions": 80,
+ "branches": 40
+ }
},
{
"path": "src/application/policies/promotion-readiness.ts",
"owner": "release-runtime",
- "minimum": { "lines": 95, "statements": 95, "functions": 95, "branches": 95 }
+ "minimum": {
+ "lines": 95,
+ "statements": 95,
+ "functions": 95,
+ "branches": 95
+ }
},
{
"path": "src/application/use-cases/decide-chunk-recovery.ts",
"owner": "application-runtime",
- "minimum": { "lines": 90, "statements": 90, "functions": 95, "branches": 85 }
+ "minimum": {
+ "lines": 90,
+ "statements": 90,
+ "functions": 95,
+ "branches": 85
+ }
},
{
"path": "src/bootstrap/load-release-manifest.ts",
"owner": "release-runtime",
- "minimum": { "lines": 90, "statements": 90, "functions": 90, "branches": 80 }
+ "minimum": {
+ "lines": 90,
+ "statements": 90,
+ "functions": 90,
+ "branches": 80
+ }
},
{
"path": "src/bootstrap/read-bounded-boot-json.ts",
"owner": "bootstrap-runtime",
- "minimum": { "lines": 71, "statements": 66, "functions": 48, "branches": 57 }
+ "minimum": {
+ "lines": 71,
+ "statements": 66,
+ "functions": 48,
+ "branches": 57
+ }
},
{
"path": "src/contracts/diagnostics.ts",
"owner": "diagnostics-contracts",
- "minimum": { "lines": 68, "statements": 68, "functions": 95, "branches": 58 }
+ "minimum": {
+ "lines": 68,
+ "statements": 68,
+ "functions": 95,
+ "branches": 58
+ }
},
{
"path": "src/features/reference-feature/adapters/reference-http-gateway.ts",
"owner": "reference-feature",
- "minimum": { "lines": 90, "statements": 90, "functions": 90, "branches": 90 }
+ "minimum": {
+ "lines": 90,
+ "statements": 90,
+ "functions": 90,
+ "branches": 90
+ }
},
{
"path": "src/presentation/adapters/query/application-query.ts",
"owner": "presentation-runtime",
- "minimum": { "lines": 90, "statements": 90, "functions": 90, "branches": 80 }
+ "minimum": {
+ "lines": 90,
+ "statements": 90,
+ "functions": 90,
+ "branches": 80
+ }
}
],
"highRiskPaths": [
@@ -116,7 +211,7 @@
"src/adapters/storage/browser-storage-adapter.ts",
"src/adapters/telemetry/best-effort-telemetry.ts",
"src/application/create-application.ts",
- "src/application/policies/compatibility.ts",
+ "src/contracts/compatibility.ts",
"src/application/policies/performance-budgets.ts",
"src/application/policies/promotion-readiness.ts",
"src/application/use-cases/decide-chunk-recovery.ts",
diff --git a/docs/architecture/browser-file-and-origin-storage.md b/docs/architecture/browser-file-and-origin-storage.md
index 14f7677..e3e787b 100644
--- a/docs/architecture/browser-file-and-origin-storage.md
+++ b/docs/architecture/browser-file-and-origin-storage.md
@@ -247,6 +247,8 @@ domain, application state, query cache, global store, diagnostics에 넣지 않
### 3.2 picker baseline과 enhancement
- 접근 가능한 ``가 모든 browser의 canonical baseline이다.
+ baseline adapter는 `input.click()`으로 이 경로를 활성화한다. `showPicker()`
+ 존재 여부는 portable baseline capability의 판정 기준으로 사용하지 않는다.
- `showOpenFilePicker()`와 `showSaveFilePicker()`는 runtime method별 feature
detection을 거친 progressive enhancement다. UA sniffing을 사용하지 않는다.
- picker 호출은 click/keyboard handler의 첫 browser action이어야 한다. 그 전에
@@ -987,7 +989,7 @@ recipe의 공통 code는 UI/telemetry에 raw DOMException을 노출하지 않기
| `PERMISSION_DENIED` | picker/save permission | baseline/manual fallback |
| `LIMIT_EXCEEDED` | count/bytes/page/buffer budget | 입력 축소 |
| `POLICY_REJECTED` | type/cache/data policy | 저장·전송 금지 |
-| `BLOCKED` | IndexedDB older context | 다른 탭 close/retry UI |
+| `BLOCKED` | IndexedDB older context가 live open/upgrade를 막는 중 | 다른 탭 close/retry UI |
| `CONFLICT` | revision/generation/idempotency conflict | authoritative re-read |
| `MIGRATION_FAILED` | schema/data migration | read-only/online-only |
| `QUOTA_EXCEEDED` | actual write failure | rollback, reconstructable GC, bounded retry |
@@ -999,6 +1001,12 @@ recipe의 공통 code는 UI/telemetry에 raw DOMException을 노출하지 않기
| `UNAVAILABLE` | browser/worker/storage temporarily unavailable | documented fallback |
| `UNSUPPORTED` | capability absence | baseline/online-only |
+`IndexedDbConnectionStatus.BLOCKED`는 대기 중인 live attempt의 observable
+상태다. blocked deadline이 끝나 `open()`이 `BLOCKED` failure로 settle되면
+그 attempt는 더 이상 열리는 중이 아니므로 status는
+`CLOSED / NOT_OPENED`로 전이한다. 늦게 성공한 native connection은 즉시 닫고
+settled status를 되살리지 않는다.
+
user dismissal은 failure가 아니라 outcome이다. browser DOMException name은
adapter에서 이 vocabulary로 mapping하고 raw message/stack은 local bounded
diagnostic에도 기본 저장하지 않는다.
@@ -1085,18 +1093,17 @@ Playwright Chromium, Firefox, WebKit에서 실제 secure-origin API를 검사한
`test:browser-capabilities`의 JUnit을
`verify:browser-capability-evidence`가 읽어 세 engine의 testcase 집합 동일성,
양수 실행 수, zero failure/error/skipped와 skipped/failure node 부재를 강제한다.
-현재 checkout의 source suite는 engine마다 정확히 같은 14개 case(File 2,
-IndexedDB 4, OPFS/Cache/StorageManager 각 1, cross-context invalidation 2,
-presigned streaming download/multipart upload/Image CDN 각 1)를 정의한다.
-promotion artifact는 Chromium/Firefox/WebKit의 14개씩, 총 42개가 모두
-실행되어야 한다. 이 host의
-WebKit은 필수 native libraries(예:
-`libbacktrace.so.0`, `libevent-2.1.so.7`, `libjxl.so.0.8`,
-`libavif.so.16`과 WPE 계열) 부재로 실행되지 않았고 현재 보존 artifact도
-Chromium/Firefox 14개씩 총 28개만 통과한 상태다. 따라서 promotion evidence를
-충족하지 않으며 verifier가 실패하는 것이 정상이다. `INSTALLED` 전에는 필요한
-system dependency가 있는 CI/device에서 세 engine 전체 evidence를 새로 생성해야
-한다.
+browser capability promotion은 source suite에서 관찰된 동일 testcase set을
+Chromium/Firefox/WebKit에서 모두 실행하는 규칙으로 관리한다. case 수를 문서
+상수로 복제하지 않고 `verify:browser-capability-evidence`가 Chromium 결과를
+baseline set으로 계산해 Firefox/WebKit의 set 동일성, 양수 실행 수,
+failure/error/skipped 0과 failure/skipped node 부재를 검증한다.
+
+capability absence도 skip 사유가 아니다. 예를 들어 어떤 engine에서
+`navigator.storage`가 없다면 동일 testcase 안에서 adapter의
+`UNSUPPORTED / STORAGE_ESTIMATE / ONLINE_ONLY` 결과를 browser truth로
+검증한다. 세 engine을 실행할 수 없는 host의 artifact는 promotion evidence로
+사용하지 않는다.
- native input keyboard/focus/same-file reselection/multiple/dismissal
- Chromium conditional picker/save enhancement와 다른 engine fallback
diff --git a/docs/architecture/capability-consumer-experience.md b/docs/architecture/capability-consumer-experience.md
new file mode 100644
index 0000000..f9f2e82
--- /dev/null
+++ b/docs/architecture/capability-consumer-experience.md
@@ -0,0 +1,156 @@
+# Capability consumer experience baseline
+
+Correctness inside a reusable capability is not sufficient. The platform is
+also evaluated by how much of that correctness a normal feature developer must
+understand.
+
+These measurements are baselines, not score targets. A lower line count is not
+automatically better if it hides business semantics or creates a universal
+repository abstraction.
+
+## Scenario A — reference REST feature
+
+The existing reference feature is the executable REST consumer.
+
+It covers list/detail/create behavior, mapping, typed operation inputs,
+application ports and an optimistic mutation path.
+
+Current source size:
+
+| Feature-owned area | LOC |
+| --- | ---: |
+| `application/reference-feature-api.ts` | 91 |
+| `contracts/reference-mapper.ts` | 109 |
+| `adapters/reference-http-gateway.ts` | 65 |
+| `adapters/create-reference-feature-input.ts` | 41 |
+| Total measured boundary/application source | 306 |
+
+The important boundary metric is not the raw total. It is what those files need
+to know about the platform.
+
+Current result:
+
+- HTTP platform imports in the feature adapter layer: 2 files,
+- canonical import path used by both:
+ `src/adapters/http/index.ts`,
+- direct imports of `http-execution-v3.ts`, retry scheduler, response reader,
+ auth admission or effect-certainty internals: 0,
+- feature gateway owns transport failure projection: 0,
+- feature gateway chooses operation ID, route ID, exact input/value type and
+ mapper: yes,
+- central installed files own feature-specific adapter/runtime wiring: no;
+ feature-owned contributions are aggregated centrally.
+
+The reusable HTTP capability now owns execution-outcome normalization through
+`createFeatureHttpBinding`. A feature may still implement a custom outbound
+adapter behind its application port when the reusable contract does not match
+its business requirement.
+
+## Scenario B — IndexedDB local draft
+
+The original executable consumer probe remains at:
+
+`tests/contract/consumer-experience/indexeddb-local-draft.test.ts`
+
+with its isolated fixture:
+
+`tests/contract/consumer-experience/fixtures/local-draft-feature.ts`
+
+The architecture is now also exercised by a real vertical slice under:
+
+`src/features/local-draft-feature`
+
+It owns the Local Draft domain/application API and binds an
+`IndexedDbRepositoryPort` in its feature adapter. The
+cross-capability composition contract lives at:
+
+`tests/contract/reusable-capability/feature-adapter-composition.test.ts`
+
+That test composes one HTTP-only contribution and the IndexedDB-only Local Draft
+contribution through the same generic catalog path.
+
+The browser-level composition proof lives at:
+
+`tests/browser-capabilities/local-draft-composition.spec.ts`
+
+It runs against native browser IndexedDB. The test creates the platform
+`createIndexedDbRuntime`, exposes that runtime through the typed
+`createIndexedDbRepositoryProvider`, composes
+`LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION`, then executes Local Draft
+save/find/remove through the feature API. The Local Draft feature still does
+not import the IndexedDB runtime or native browser API.
+
+Measured probe result:
+
+| Metric | Result |
+| --- | ---: |
+| feature-owned fixture LOC | 97 |
+| platform import statements | 1 |
+| native IndexedDB API references | 0 |
+| `src/adapters/storage/indexeddb/**` imports | 0 |
+| runtime-internal IndexedDB types imported by feature | 0 |
+
+The feature depends only on the public application boundary:
+
+`src/application/ports/browser-file-storage/index.ts`
+
+and specifically `IndexedDbRepositoryPort`.
+
+The contract test rejects feature source that reaches for
+`globalThis.indexedDB`, `IDBFactory`, `IDBDatabase`, `IDBTransaction`,
+`IDBObjectStore` or the concrete IndexedDB adapter directory.
+
+## What this does and does not prove
+
+The contract probe confirms that **feature business code does not need native
+IndexedDB knowledge** once an `IndexedDbRepositoryPort` has been composed.
+The browser-capability proof additionally confirms that the same feature
+contribution works when that port is backed by the repository's real
+`createIndexedDbRuntime` and native IndexedDB implementation.
+
+It does not prove that composition of `createIndexedDbRuntime` is cheap.
+That constructor still owns substantial infrastructure policy:
+
+- dataset scope and storage policy,
+- physical store governance,
+- retention/idempotency stores,
+- schema migrations,
+- codec and query policy,
+- lifecycle authority,
+- durability, scheduling and observation.
+
+That complexity belongs at the composition/platform boundary, not in the
+feature. The Local Draft vertical slice is now the second concrete consumer, and
+it confirms that the stable seam is the typed repository provider plus a
+feature-owned repository identity. It does **not** show that dataset scope,
+retention, migration, codec or lifecycle-authority configuration can be safely
+collapsed into one universal `create...Repository` factory.
+
+A convenience profile should therefore be introduced only after another
+IndexedDB-backed product feature repeats the same infrastructure policy, not
+merely because two features consume the same repository port.
+
+## Consumer-quality review checklist
+
+For each new product feature, record:
+
+- feature-owned adapter LOC,
+- platform glue LOC,
+- files changed,
+- central catalog edits,
+- direct imports from capability-internal modules,
+- native browser/network API references,
+- duplicated failure/retry/lifecycle policy.
+
+A healthy feature path should look like:
+
+1. domain type and invariant,
+2. use case,
+3. business port,
+4. feature-owned mapper/codec and policy,
+5. capability-specific binding,
+6. presentation controller/page.
+
+The feature should not need the retry scheduler, abort ownership,
+effect-certainty machinery, IndexedDB transaction lifecycle, OPFS journal,
+reconnect coordinator or provider process model.
diff --git a/docs/architecture/contract-ownership.md b/docs/architecture/contract-ownership.md
new file mode 100644
index 0000000..fec11de
--- /dev/null
+++ b/docs/architecture/contract-ownership.md
@@ -0,0 +1,110 @@
+# Contract ownership
+
+`src/contracts` is not a default destination for every shared-looking type.
+A contract belongs there only when the change authority is genuinely shared
+across layers, capabilities, build tooling, or runtime composition.
+
+## Decision rule
+
+For every proposed contract, ask:
+
+1. Which requirement can cause this type or policy to change?
+2. Is there one clear capability or feature owner?
+3. Does another runtime/tooling boundary consume the same semantic contract?
+4. Is the contract a wire/artifact authority shared by browser runtime and
+ build/release tooling?
+
+The placement rule is:
+
+- one feature owner -> keep it under that feature,
+- one reusable capability owner -> keep it under that adapter/capability and
+ export it through the capability public entry point,
+- multiple independent capability/layer owners -> `src/contracts`,
+- browser/build/release wire or artifact authority -> `src/contracts` even
+ when the browser source graph alone looks small.
+
+Consumer count alone is not sufficient. Scripts, generated artifacts and
+release gates are semantic consumers too.
+
+## Audit result
+
+The September 2026 architecture review triggered an import-graph audit of all
+39 contract files.
+
+### Capability-owned contract moved
+
+`cursor-pagination.ts` had one production owner:
+`src/adapters/query-cache/cursor-pagination-runtime.ts`.
+
+It moved to:
+
+`src/adapters/query-cache/cursor-pagination-contract.ts`
+
+and is exported through:
+
+`src/adapters/query-cache/index.ts`
+
+Tests use that public capability entry point. Pagination vocabulary no longer
+occupies the global contract bucket merely because it is reusable inside one
+adapter.
+
+### Contracts intentionally kept global
+
+The following examples have multiple semantic owners and remain global:
+
+- `errors.ts` — application, presentation and several adapters,
+- `result.ts` — common success/failure carrier below application,
+- `boundary-mapper.ts` — HTTP, browser RPC, realtime and feature registries,
+- `mutation-intent.ts` — application, presentation, HTTP, platform and
+ bootstrap,
+- `exact-snapshot.ts` — HTTP, query-cache and browser-transfer,
+- `rest-profiles.ts` — auth, HTTP, bootstrap and feature contract validation,
+- `query-invalidation.ts` / `query-keys.ts` — query-cache, presentation,
+ bootstrap and features,
+- `cache-invalidation.ts` — cross-context wire protocol plus query
+ invalidation policy,
+- `storage-keys.ts` — browser storage and cross-context invalidation,
+- `telemetry.ts` / `diagnostics.ts` — runtime adapters, application and
+ bootstrap.
+
+Some contracts appear to have few browser-source consumers but are still shared
+authorities:
+
+- `env.ts` is consumed by bootstrap, runtime-schema/security tests and
+ registry governance,
+- `deployment-admission.ts` is shared by runtime-config generation and release
+ admission,
+- `release-tokens.ts` is shared by runtime coherence tooling and tests,
+- `service-worker-static-manifest.ts` is a runtime-neutral canonical format
+ shared by build generation, validation and service-worker evidence.
+
+Moving those based only on `src/**` import counts would split one semantic
+authority across processes.
+
+## Feature contracts
+
+Feature-specific contracts stay inside the vertical slice:
+
+`features//contracts`
+
+The reference feature owns routes, schemas, mapper definitions, message
+catalogs and contribution identities. Central installed files aggregate those
+contributions; they do not own their semantics.
+
+The message catalog is a deliberate special case: the compiled catalog remains
+total even when a feature is build-time disabled so the typed message lookup
+does not become partial. The central message file therefore aggregates compiled
+message keys rather than treating runtime installation as message ownership.
+
+## Review rule for future additions
+
+A new file under `src/contracts` should be rejected during review when all of
+the following are true:
+
+- one feature or one capability is the only semantic owner,
+- no build/release/runtime wire authority needs the same definition,
+- moving the definition to that owner does not create an inward dependency
+ violation.
+
+Do not move a contract merely to reduce the number 39. The goal is explicit
+ownership, not a smaller directory.
diff --git a/docs/architecture/decisions/VD-11-browser-file-and-origin-storage.md b/docs/architecture/decisions/VD-11-browser-file-and-origin-storage.md
index 6c5e8dc..91e2c6f 100644
--- a/docs/architecture/decisions/VD-11-browser-file-and-origin-storage.md
+++ b/docs/architecture/decisions/VD-11-browser-file-and-origin-storage.md
@@ -189,17 +189,18 @@ chunk별 `CapabilityResult`를 반환한다. backend upload example
실제 upload feature는 이 예시를 그대로 import하지 않고 purpose와 backend
protocol에 맞게 contract를 더 좁힌다.
-현재 checkout의 browser source suite는 engine마다 같은 14개 case(File 2,
-IndexedDB 4, OPFS/Cache/StorageManager 각 1, cross-context invalidation 2,
-presigned streaming download/multipart upload/Image CDN 각 1)를 정의한다.
-promotion artifact는 Chromium/Firefox/WebKit 각각 14개, 총 42개를 모두
-실행해야 한다. WebKit은 현재
-host의 필수 native libraries(예:
-`libbacktrace.so.0`, `libevent-2.1.so.7`, `libjxl.so.0.8`,
-`libavif.so.16`과 WPE 계열) 부재로 실행되지 않았다. 보존 artifact는
-Chromium/Firefox 14개씩 총 28개만 통과했으므로
-`verify:browser-capability-evidence`가 실패하는 것이 정상이다. 세 engine
-evidence가 완성되기 전에는 product 상태를 `INSTALLED`로 올리지 않는다.
+browser capability promotion은 source suite가 정의한 동일 testcase set을
+Chromium/Firefox/WebKit에서 모두 실행해야 한다. 구체적인 case 개수는 이 결정
+문서에 고정하지 않는다. `verify:browser-capability-evidence`가 Chromium
+artifact에서 baseline set을 계산하고 Firefox/WebKit과의 set 동일성 및
+failure/error/skipped 0을 기계적으로 검증한다.
+
+engine별 native capability 차이는 testcase를 skip하는 이유가 아니다. capability가
+없으면 adapter의 명시적 unsupported/degraded result를 같은 testcase에서
+검증한다. baseline `` activation은 portable한
+`input.click()` 경로를 사용하고, `showOpenFilePicker()` 같은 API는 별도
+progressive enhancement로 유지한다. 세 engine evidence가 완성되기 전에는
+product 상태를 `INSTALLED`로 올리지 않는다.
## 선택 이후 필요한 구현
diff --git a/docs/architecture/frontend-application-foundation.md b/docs/architecture/frontend-application-foundation.md
new file mode 100644
index 0000000..6cb3ca2
--- /dev/null
+++ b/docs/architecture/frontend-application-foundation.md
@@ -0,0 +1,252 @@
+# Frontend Application Foundation
+
+This repository is not treated as a minimal React project template and it is not
+an independent general-purpose SDK. Its architectural role is:
+
+> Frontend Application Foundation = Starter / Composition Skeleton + Reusable Capability Platform
+
+The starter side owns bootstrap, routing, providers, project conventions and a
+removable reference feature. The capability side owns reusable technical
+problems such as HTTP execution, Server State, authentication boundaries,
+IndexedDB/OPFS, Cache Storage, realtime, browser RPC, transfer and diagnostics.
+
+The cost of a sophisticated capability is acceptable only when product features
+do not have to understand that internal sophistication.
+
+## Hybrid architecture
+
+Platform code is horizontal:
+
+- `application`: generic application inputs/policies/ports
+- `contracts`: genuinely cross-capability shared vocabulary and registries
+- `adapters`: reusable capability runtimes
+- `presentation`: generic UI/routing/query integration
+- `bootstrap`: concrete composition
+
+Product business code is vertical:
+
+- `features//domain`
+- `features//application`
+- `features//contracts`
+- `features//adapters`
+- `features//presentation`
+
+The dependency model is:
+
+ Domain / Use case
+ |
+ | owns
+ v
+ Business port
+ ^
+ | implements / binds
+ |
+ Feature-owned adapter binding
+ |
+ | generic type + mapper/codec + policy
+ v
+ Reusable capability runtime
+ |
+ v
+ Browser / network / native API
+
+A use case never imports a platform adapter. Generic binding happens in the
+feature adapter/composition seam.
+
+## Capability-specific typed bindings
+
+Do not introduce one universal `Repository` abstraction for HTTP,
+storage, realtime and transfer. Their lifecycle and failure semantics differ.
+
+A reusable capability boundary is composed from:
+
+- generic input/output types,
+- feature-owned mapper or codec,
+- feature-selected policy,
+- one capability-specific runtime.
+
+The HTTP reference path is the first concrete example.
+`src/adapters/http/feature-http-binding.ts` owns transport/outcome
+normalization. The reference feature contributes only:
+
+- operation ID,
+- route ID,
+- exact request input type,
+- exact success value type,
+- wire-to-domain mapper.
+
+The feature gateway therefore does not reimplement timeout, cancellation,
+transport failure, authentication failure or contract-violation projection.
+
+Storage, realtime and transfer may gain their own typed binders only after
+actual feature repetition demonstrates the need. They must not be forced
+through the HTTP abstraction.
+
+## Custom adapter escape hatch
+
+A product feature uses a reusable capability when the capability preserves the
+business requirement.
+
+If a platform contract would require changing or weakening the business model,
+the feature implements a custom outbound adapter behind the same application
+port. The architecture boundary remains stable; platform reuse is optional.
+
+## Feature installation
+
+A feature owns its contract, runtime and adapter contributions.
+
+Central installed catalogs are aggregation points only:
+
+- `installed-product-manifest.ts`: which product features are compiled/selected
+- `installed-feature-contracts.ts`: contract aggregation
+- `installed-feature-runtimes.tsx`: runtime contribution aggregation
+- `installed-feature-adapters.ts`: application-input contribution aggregation
+
+Feature-specific composition belongs under the feature itself. Central
+catalogs must not grow feature-specific branching logic.
+
+Adapter contributions declare the platform capabilities they consume through
+`needs`. The generic contribution seam in
+`src/features/feature-adapter-contribution.ts` derives the context from that
+list, so an HTTP-only feature cannot reach IndexedDB and an IndexedDB-only
+feature does not receive the HTTP executor. It also binds
+`featureId -> ApplicationFeatureInputs[featureId]` at the contribution
+definition site instead of recovering that relationship with a final catalog
+cast.
+
+A contribution becomes composable only through
+`defineFeatureAdapterContribution()`. That factory adds the private
+contribution brand required by `composeFeatureAdapterInputs()`; a raw object
+with the same visible fields is rejected by TypeScript and checked again at
+runtime. The negative type fixture
+`invalid-direct-feature-composition.ts` is part of FE-GATE-003 so this
+authority cannot be bypassed by calling the composer directly.
+
+For IndexedDB-backed features, `createIndexedDbRepositoryProvider()` is the
+composition helper that maps feature-owned repository identities to typed
+`IndexedDbRepositoryPort` instances. It does not create a universal storage
+repository or move dataset/migration/lifecycle policy into the feature.
+
+The repository now has two executable contribution shapes:
+
+- Reference feature: `needs: ["http"]`
+- Local Draft feature: `needs: ["indexedDb"]`
+
+Local Draft is a compiled architecture consumer used to prove the second
+capability shape; it is not added to the default product manifest. Its
+browser-capability test composes the feature over the real
+`createIndexedDbRuntime` and native IndexedDB, proving that this seam is not
+limited to an in-memory contract fixture.
+
+## Presentation consumer surface
+
+`ApplicationProvider` remains the composition root for presentation, but new
+consumers should not navigate a root `ApplicationApi` service locator.
+
+Use the narrow hooks in
+`src/presentation/providers/application-provider.tsx`:
+
+- `useApplicationSession`
+- `useApplicationPreferences`
+- `useApplicationDiagnostics`
+- `useApplicationRuntime`
+- `useApplicationRecovery`
+- `useApplicationFeature`
+
+`useApplication` exists only as a deprecated compatibility escape hatch.
+
+## Canonical imports
+
+New feature code should use capability public entry points rather than deep
+runtime modules. For HTTP the canonical path is
+`src/adapters/http/index.ts`.
+
+Compatibility re-exports may exist during a migration window, but they must be
+marked as compatibility/deprecated paths and should not expand into an
+unbounded public barrel.
+
+## Policy ownership
+
+Duplication is judged by ownership, not by syntax percentage.
+
+Small local validators can remain duplicated when locality improves auditing.
+Business or concurrency policy must have one owner. For example the reference
+create mutation keeps definition ID, idempotency requirement, duplicate policy
+and invalidation policy in one feature-owned definition and binds only
+`scope` and `execute` per usage site.
+
+## Runtime decomposition rule
+
+Large runtime files are not split by line count.
+
+Extract a boundary when it has its own state machine, lifecycle owner, failure
+model or compensation/recovery responsibility. Candidate seams include:
+
+- connection/open/upgrade lifecycle,
+- transaction ownership,
+- migration state machine,
+- reconnect/backoff and heartbeat,
+- subscription ownership,
+- retry/deadline/cancellation ownership,
+- settlement/reconciliation/cleanup.
+
+A cohesive 2,000-line state machine can remain together. A 300-line file with
+multiple lifecycle owners is a better extraction candidate.
+
+### Current runtime boundary audit
+
+The current large-runtime inventory was reviewed using that rule.
+
+- IndexedDB remains large, but connection, transaction, migration, maintenance
+ and failure translation already have separate owners/modules.
+- resumable upload already separates runtime policy, checkpoint persistence,
+ HTTP control-plane transport, part execution, cancellation and mutation
+ locking.
+- realtime already separates reconnect policy/coordinator, event codec/consumer
+ and stream coordination.
+- OPFS is separated into browser runtime, journal, byte-store, policy and worker
+ protocol/runtime responsibilities.
+- HTTP V3 still owned retry eligibility/backoff inside the execution state
+ machine, so that responsibility moved to
+ `src/adapters/http/http-retry-lifecycle.ts`.
+
+No other runtime is split merely because of its line count.
+
+## Consumer quality metrics
+
+Before adding another abstraction, implement or model multiple real feature
+uses and measure:
+
+- feature-owned adapter LOC,
+- repeated platform glue,
+- number of platform-internal types exposed to the feature,
+- central catalog edits,
+- files changed for one normal query/command,
+- whether native browser/network APIs leak into the feature.
+
+The target feature-development path is:
+
+1. domain type and invariant,
+2. use case,
+3. port,
+4. transport/storage schema plus mapper/codec,
+5. capability binding,
+6. presentation controller/page.
+
+A product feature should not need to know the retry scheduler, abort ownership,
+effect-certainty machinery, transaction leases, reconnect coordinator, OPFS
+journal or provider lifecycle.
+
+The executable REST and IndexedDB consumer baselines are recorded in
+[`capability-consumer-experience.md`](./capability-consumer-experience.md).
+Contract placement and the global-vs-owner-local audit are recorded in
+[`contract-ownership.md`](./contract-ownership.md).
+
+## Verification paths
+
+Product-development verification, capability verification and release assurance
+are intentionally separate. See
+[`docs/testing/taxonomy.md`](../testing/taxonomy.md).
+
+Host-level CI-runner tests belong to `tests/system`, not `tests/unit`.
+Reusable capability consumer contracts belong to `tests/contract`.
diff --git a/docs/architecture/layers.md b/docs/architecture/layers.md
index 56a2c3f..2734d97 100644
--- a/docs/architecture/layers.md
+++ b/docs/architecture/layers.md
@@ -44,6 +44,36 @@ registries today, and the two collaborator types `query-cache` reads from
`cross-context-invalidation`. Both lists are frozen — a new edge of either kind
fails the gate.
+## 어댑터 그룹의 공개 경계
+
+각 어댑터 그룹의 공개 표면은 그 그룹의 `index.ts`다. 그룹 바깥
+(`bootstrap`, `features`, `presentation`)은 배럴만 import한다.
+`adapter-groups-are-reached-through-their-barrel` 규칙이 이를 강제하고,
+`tests/fixtures/architecture/dependency-graph/barrel`이 거부와 허용을
+각각 고정한다 — 규칙을 지우면 그 회귀 검사가 먼저 깨진다.
+
+두 가지 예외가 있고 둘 다 의도된 것이다.
+
+- **그룹 내부 파일끼리**는 파일 경로로 직접 import한다. 배럴은 바깥을 위한
+ 문이지 내부 규율이 아니다.
+- **어댑터 → 커널(`platform/**`)** 간선도 파일 경로를 유지한다. 커널은
+ 런타임 합성물이 아니라 프리미티브이고, `check:adapter-inventory`가 네
+ 소비자에게 `platform/abortable-operation.ts`로 해석되는 specifier를
+ 직접 요구한다. 커널 배럴(`platform/index.ts`)은 bootstrap과 테스트를
+ 위한 것이다.
+
+`storage`는 최상위 배럴이 `indexeddb/`·`opfs/` 서브배럴을 재수출하지
+않는다. 두 런타임이 각자 독립적으로 제거 가능하고
+(`test:browser-file-storage-removal`), 그래서 각 서브배럴이 곧 경계다.
+규칙의 도착점 정규식이 1단계 중첩 `index.ts`를 배럴로 인정하는 이유가
+이것이다.
+
+`service-worker/index.ts`는 `tsconfig.service-worker.json`의 `exclude`에
+들어 있다. 그 설정이 그룹 폴더를 통째로 WebWorker lib로 컴파일하면서 페이지
+realm 파일만 빼는 구조라, 배럴이 그 파일을 다시 끌어들이면 워커 타입체크가
+`document`를 찾지 못한다. 배럴의 타입 커버리지는 `tsconfig.app.json`이
+담당하고, 워커 진입점은 배럴을 쓰지 않는다.
+
`bootstrap` contains composition only. Business rules and page-specific
orchestration belong to domain/application.
diff --git a/docs/operations/adapter-remediation-dispositions.json b/docs/operations/adapter-remediation-dispositions.json
index d0e9edc..3c8140f 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 862c5e3..94e784c 100644
--- a/docs/operations/adapter-remediation-ledger.md
+++ b/docs/operations/adapter-remediation-ledger.md
@@ -337,7 +337,14 @@ Run on the landed tree. Only what actually passed is claimed as passing.
| --- | --- | --- |
| `tests/unit/ci-workflow-generation.test.ts` | 82 failed / 325 passed | Identical on the pre-change baseline (`git stash` comparison). The subprocess gates it spawns cannot run in this sandbox. |
| `tests/unit/ci-artifact-contract.test.ts` | fails | Unchanged pre-existing sandbox, cgroup and `/tmp` permission behaviour. |
-| `tests/unit/security-followup.test.ts`, `tests/unit/provider-guardian-transaction.test.ts`, `tests/unit/risk-coverage.test.ts` | flaky under full-suite load | All three pass in a fresh process (78 passed together). They spawn and reap process groups, so their timing assertions are load sensitive. |
+| `tests/unit/security-followup.test.ts`, `tests/unit/provider-guardian-transaction.test.ts`, `tests/unit/risk-coverage.test.ts` | flaky under full-suite load | Historical baseline result. All three passed in a fresh process (78 passed together). |
+
+> Current classification update (2026-09-18): the provider guardian transaction
+> suite moved to `tests/integration/provider-guardian-transaction.test.ts`.
+> It spawns child processes and exercises filesystem/IPC/process lifecycle, so it
+> is not part of the pure unit pool. Its READY/PUBLISHED wait uses a dedicated
+> test watchdog rather than treating a 1-second scheduler delay as a production
+> protocol deadline.
### Destructive fixture hazard — fixed
@@ -375,7 +382,7 @@ files above plus the two flaky-under-load ones:
| `tests/unit/ci-workflow-generation.test.ts` | 82 | Identical on the pre-change baseline (`git stash` comparison). Its subprocess gates cannot run in this sandbox. |
| `tests/unit/ci-artifact-contract.test.ts` | 19 | Unchanged pre-existing sandbox, cgroup and `/tmp` permission behaviour. |
| `tests/unit/security-followup.test.ts` | 2 | Passes in isolation. |
-| `tests/unit/provider-guardian-transaction.test.ts` | 1 | Passes in isolation. |
+| `tests/unit/provider-guardian-transaction.test.ts` (historical path; now `tests/integration/provider-guardian-transaction.test.ts`) | 1 | Historical baseline: passed in isolation; current suite is classified as process integration. |
1619 passed / 1723 total, and `tests/unit/removal-fixture.test.ts`,
`tests/unit/supply-chain.test.ts` and
diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md
index 56b6623..6a58321 100644
--- a/docs/operations/browser-file-storage-recovery.md
+++ b/docs/operations/browser-file-storage-recovery.md
@@ -148,6 +148,9 @@ read-only나 online-only가 사용자 작성 내용을 잃게 한다면 먼저 e
### 신호
- `BLOCKED`, `UPGRADE_BLOCKED` 또는 blocked duration bucket 증가
+ - live attempt가 기다리는 동안 status는 `BLOCKED`
+ - blocked deadline settle 뒤에는 open result가 `BLOCKED` failure여도
+ runtime status는 `CLOSED / NOT_OPENED`
- `versionchange` 뒤 connection이 남음
- repeated reload/update loop
- open/maintenance의 `POLICY_REJECTED`: immutable dataset binding missing/mismatch
@@ -500,16 +503,13 @@ browser engine/version, fixture ID, fault phase, bounded counts/buckets와 PASS/
promotion 직전에는 다음 repository evidence도 함께 보존한다.
-- `test:browser-capabilities`가 만든 JUnit에서 Chromium, Firefox, WebKit이 동일
- 14개 testcase set(File 2, IndexedDB 4, OPFS/Cache/StorageManager 각 1,
- cross-context invalidation 2, presigned streaming download/multipart
- upload/Image CDN 각 1)을 실제 실행해 총 42개이며 failure/error/skipped가 모두
- 0이어야 한다.
- `verify:browser-capability-evidence`가 engine 집합과 testcase 동일성을
- 기계적으로 검증한다. 현재 artifact는 Chromium/Firefox 14개씩 총 28개가
- 통과했지만 WebKit 실행에 필요한 native libraries(예:
- `libbacktrace.so.0`, `libevent-2.1.so.7`, `libjxl.so.0.8`,
- `libavif.so.16`과 WPE 계열)가 이 host에 없으므로 아직 promotion 가능 상태가
+- `test:browser-capabilities`가 만든 JUnit에서 Chromium, Firefox, WebKit이
+ source suite의 동일 testcase set을 실제 실행하고 failure/error/skipped가 모두
+ 0이어야 한다. 구체적인 case 수는 이 runbook에 복제하지 않는다.
+ `verify:browser-capability-evidence`가 Chromium을 baseline으로 testcase set과
+ engine 집합을 동적으로 검증한다. native capability가 없는 engine도 testcase를
+ skip하지 않고 adapter의 명시적 `UNSUPPORTED`/degraded 결과를 검증해야 한다.
+ 세 engine 중 하나라도 실행되지 않은 artifact는 promotion 가능 상태가
아니다.
- `artifacts/quality/vite-module-inventory.json`에서 optional runtime source root가
production chunk에 없음을 `check:optional-recipes`로 검증한다.
diff --git a/docs/operations/template-sync-2026-09-21.md b/docs/operations/template-sync-2026-09-21.md
new file mode 100644
index 0000000..902d3fd
--- /dev/null
+++ b/docs/operations/template-sync-2026-09-21.md
@@ -0,0 +1,315 @@
+# Template sync — `5434760` → `ebea300`
+
+Record of how the frontend template's 21 pending commits were transplanted into
+this product, and of every decision taken where the two trees disagreed.
+
+## Starting state
+
+| | |
+| --- | --- |
+| template pin before | `5434760` (`template.lock.json`) |
+| template pin after | `ebea300` |
+| template commits carried | 21 |
+| template delta | 205 files, +22,729 / −9,969 |
+| this product's divergence since the last sync | 618 files (`bdee07a..b297d65`) |
+| files touched by both | 27 |
+| applied to this product | 195 files, +21,527 / −9,980 |
+
+Rollback ref created before touching anything:
+
+```
+backup/main-before-template-ebea300 → b297d65
+```
+
+The two histories share no commit — `git merge-base main template/main` is
+empty — so this is a patch transplant, not a merge, the same way every previous
+sync was. `template.lock.json` calls it `tracked-snapshot`; there is no sync
+script.
+
+### Pre-transplant baseline
+
+Captured in a clean worktree at `b297d65` so a pre-existing failure could not be
+mistaken for a transplant regression.
+
+| Gate | Result |
+| --- | --- |
+| `check:types` | pass |
+| `lint` | pass |
+| `test:unit` | 1825 passed / 4 failed / 16 skipped |
+| `test:component` | 152 passed |
+| `test:tech-log` | 415 passed |
+
+The four failures were `ci-artifact-contract` (2), `provider-guardian-transaction`
+(1) and `removal-fixture` (1) — sandbox- and artifact-dependent checks that do
+not run on this machine.
+
+## What the template brought
+
+| Group | Commits | Substance |
+| --- | --- | --- |
+| Frontend refactor | `ec7f20e` | Feature adapter contribution model, the `local-draft-feature` demonstration slice, a large set of typecheck fixtures, and several oversized test files split apart |
+| Template refactor | `5cc4146` | `feature-http-binding`, reference feature restructured, `run-vitest.ts`, three new architecture documents |
+| IndexedDB kernel | `cb62bfb` + 6 | A shared connection/transaction kernel; the OPFS journal, upload checkpoint store, maintenance and runtime moved onto it |
+| Adapter barrel boundary | `b29a471` + 5 | A public `index.ts` per adapter group, enforced by the architecture gate |
+| Other | `d777fb8`, `ebea300` | Abort-wiring ratchet; release identity derived from the package name |
+
+## What was deliberately not carried
+
+| Path | Why |
+| --- | --- |
+| `artifacts/tests/coverage-gateway/**` (10 files) | A coverage run the template committed by accident. Nothing outside `artifacts/` references it. |
+| `docs/superpowers/specs/2026-09-20-memento-frontend-template-bootstrap-design.md` | A design for deriving a different product from the template. |
+| `src/presentation/pages/home-page.tsx`, `src/presentation/examples/platform-overview-page.tsx`, `src/features/reference-feature/presentation/**` | Deleted by this product's UI migration. The template modified them; the deletions stand. |
+
+## Conflicts and how each was decided
+
+19 conflicts. The rule applied throughout is the one the previous sync wrote
+down: **keep the template's mechanism, keep the product's content, and never
+invent a third state that neither branch would accept.**
+
+### The platform HTTP executor — `src/bootstrap/runtime-adapters.ts`
+
+The substantive change of this sync. The template turned `contractOperations`
+from a string-id executor into `InstalledHttpOperationExecutor`, which takes the
+installed contract itself so a feature's Input/WireOutput/Problem types flow
+through `createFeatureHttpBinding`.
+
+TechLog's four HTTP gateways address operations by id through their own
+`StudioOperationExecutor` — six call sites across
+`http-studio-gateway.ts`, `http-studio-asset-gateway.ts`,
+`http-management-gateway.ts` and `http-public-content-gateway.ts`. Porting them
+onto the typed binding is a rewrite of TechLog's HTTP layer, and nothing about
+that is decided here.
+
+So the platform executor is the template's, verbatim, and the composition root
+adapts it for TechLog: `techLogOperations` resolves the id against
+`COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId` and delegates. The
+resolution happens at the one place that already owns the registry rather than
+inside the executor for every caller, and an unregistered id returns the same
+`FINAL_REQUEST_INVARIANT_FAILED` violation on both paths.
+
+The product's `let` + throwing-stub forward reference — which exists to break
+the CSRF construction cycle, and which the file documents at length — moved to
+`techLogOperations`, where the cycle actually is. `contractOperations` is now a
+plain `const`.
+
+The template's barrel imports were adopted; TechLog's imports were kept.
+
+### `src/features/installed-feature-adapters.ts`
+
+The template composes contributions through `composeFeatureAdapterInputs`,
+selecting by `featureId` against the manifest. That mechanism is adopted.
+
+TechLog is composed directly on top of it, and its input stays total, because
+TechLog is this product's own domain rather than a `SelectableProductFeature` —
+the same split the previous sync recorded, now expressed through the template's
+mechanism instead of a hand-written ternary.
+
+`InstalledFeatureInputs` became `Partial` upstream, so
+the return type is that intersected with a total `Pick` of TechLog's entry.
+
+### `src/features/installed-contract-contributions.ts`
+
+Same shape. The manifest-governed contributions are filtered by their own
+`featureId` — the template's improvement over this file naming the reference
+feature — and TechLog's three contributions are appended unconditionally, where
+the filter cannot drop them.
+
+### `src/features/installed-feature-runtimes.tsx`
+
+The template compiles the reference feature's runtime contribution here and
+filters it through the manifest. This product deleted that feature's
+presentation layer, so there is no contribution to compile and the import would
+not resolve. Carrying an empty list plus the filter would be dead code neither
+repository runs, so the previous sync's decision stands: the aggregation comes
+back the day those screens do.
+
+A second reason not to adopt it as written: the template's
+`Object.assign(..., ...contributions.map(...))` widens both catalogs to `any`,
+and this product's router resolves codecs and components by route id off them.
+The object spread keeps them typed.
+
+### `src/presentation/routes/app-router.tsx`, `src/presentation/layouts/app-shell.tsx`
+
+The template split `useApplication()` into `useApplicationRuntime()`,
+`useApplicationDiagnostics()` and `useApplicationRecovery()`. Adopted.
+
+The template also added an `AppShell` import to the router; this product's
+router never mounts it (the public site has its own header and the studio its
+own shell), so the import was not carried — it would be dead.
+
+### Release identity — `ebea300`
+
+Three files hard-coded `tech-log-frontend/…` verifier ids because a previous
+sync replaced the template's own hard-coded name. The template now derives them
+from the package name. Taking the template's side produces the identical value
+and removes the hard-coding: `scripts/generate-supply-chain.ts`,
+`scripts/lib/local-release-evidence.ts`, `scripts/lib/provider-evidence.ts`.
+
+### `package.json`
+
+The template's mechanisms are kept — `node scripts/run-vitest.ts` in place of
+bare `vitest`, the new `tests/contract` and `tests/system` suites, and the
+typecheck fixtures moved onto per-fixture `tsconfig` files. This product's
+entries are kept: `test:tech-log`, `check:tech-log-contract` in `test:all`, and
+`tests/features/tech-log` in `test:coverage`.
+
+### `tests/unit/security-followup.test.ts`
+
+The template split this file into `security-followup-fixture.ts`,
+`security-promotion-staging.test.ts` and `security-provider-evidence.test.ts`.
+The product's only additions to it were the two hard-coded verifier ids (now
+derived upstream) and `PROCESS_HEAVY_TIMEOUT_MS`, which the template's fixture
+already carries. The file is byte-identical to the template's.
+
+### `tests/component/router.test.tsx`
+
+The template's hunk asserts `/examples/ui`, a screen this product deleted. The
+product's Studio-layout assertions are kept.
+
+### Derived baselines — recomputed, not chosen
+
+`scripts/contracts/ci-gates.ts`, `tests/unit/ci-workflow-generation.test.ts` and
+`tests/unit/task3-selective-integration.test.ts` pin counts and a digest
+describing `config/ci/gates.json`. **Neither side's numbers describe the merged
+file.** They were recomputed from it, and the method was checked by first
+reproducing this product's pre-merge values from the pre-merge `gates.json`.
+
+| Value | This product | The template | Merged |
+| --- | --- | --- | --- |
+| gates | 27 | 27 | 27 |
+| command definitions | 85 | 91 | **94** |
+| command references | 97 | 103 | **106** |
+| commands expecting failure | 23 | 30 | **30** |
+| evidence artifact references | 118 | 88 | **120** |
+| artifacts | 139 | 109 | **141** |
+| canonical gate shape SHA-256 | `8a1a5479…` | `43dc4ed1…` | **`629e5898f6a38d5056fc6a4bee834c47f363669ce9925a2c0dabeddd64d11879`** |
+
+## Fixes the transplant required
+
+### The adapter barrel boundary caught three TechLog files
+
+`27ab17d` makes the architecture gate refuse an import that reaches past an
+adapter group's barrel. Three TechLog files did:
+`http-studio-gateway.ts` and `studio-error-mapping.ts` imported
+`HttpExecutionOutcome` from `adapters/http/http-execution-v3.ts`, and
+`studio-session-credentials.ts` imported `CredentialPatchOutcome` from
+`adapters/http/http-contract-bridge.ts`. The barrel exports all three types;
+the imports now go through it.
+
+### A relative import went stale when a test moved
+
+`tests/unit/ci-artifact-contract.test.ts` moved to
+`tests/system/ci-runner/`. Its product-only import of
+`scripts/lib/provider-sandbox-probe.ts` — a file the template does not have —
+kept the old `../../` depth and had to become `../../../`.
+
+### The remediation ledger pointed at files that had been split
+
+`ec7f20e` split `presigned-transfer.test.ts`, `image-cdn-runtime.test.ts` and
+`resumable-upload-runtime.test.ts`, moving the TR-02, TR-03 and TR-04 markers
+into the new files, **but did not update
+`docs/operations/adapter-remediation-dispositions.json`** — so
+`check:remediation-ledger` is broken upstream as well. The three evidence paths
+now name the files that actually carry the markers.
+
+### `tests/features/tech-log/runtime-composition.test.ts`
+
+Two changes. The composition call passes `http`, the platform capability the
+manifest-governed contributions declare in `needs`.
+
+And its type assertion no longer uses `keyof`. The composed map became
+`Partial` and the template's new local-draft feature
+declares a third key, so every declared feature is a key whether installed or
+not. What the product needs held is the split itself, so the assertion is now
+that the *required* keys are exactly `"tech-log"` and that `"reference-feature"`
+is not among them.
+
+## Gates on the transplanted tree
+
+| Gate | Result |
+| --- | --- |
+| `check:types` | pass (6 projects) |
+| `lint` | pass, `--max-warnings=0` |
+| `check:architecture` | 490 modules, 1630 dependencies, 14 fixtures pass |
+| `check:adapter-inventory` | 133 files, 9 importers of the shared abort primitive, 21/21 abort ratchet |
+| `check:ci` | 27 gates, artifact schemas and generated workflow pass |
+| `check:design-system` | 48 tokens |
+| `check:diagnostics` | 8 diagnostics, 5 telemetry producers |
+| `check:remediation-ledger` | 25 dispositions, 0 open |
+| `check:browser-security` | pass |
+| `build` | pass |
+| `test:unit` | 1789 passed in the working checkout; 1788 passed / 1 failed in the fresh worktree, where `removal-fixture` has no evidence tree to read |
+| `test:component` | 152 passed |
+| `test:tech-log` | 415 passed |
+| `test:contract` | 7 passed (new suite) |
+| `test:integration` | 102 passed |
+| `test:reference-feature` | 19 passed |
+| `test:recipes` | 17 passed |
+| `test:runtime-schema` | 44 passed / 1 failed |
+
+Two of the pre-transplant failures disappeared because the template moved those
+files out of `tests/unit`: `provider-guardian-transaction` now passes inside
+`test:integration`, and `ci-artifact-contract` moved to `tests/system`, which
+`test:all` does not run.
+
+## Failures this sync did not cause, and did not fix
+
+Each was reproduced at `b297d65` in a separate worktree before being classified.
+
+| Gate | State |
+| --- | --- |
+| `check:i18n` | Fails at `b297d65` identically. Its rule is `/[가-힣]/` over whole files in `src/presentation/**`, so the Korean comment block in `app-shell.tsx:181` trips it. The gate matches comments, not just user-facing literals. |
+| `check:registries` | Fails at `b297d65` with byte-identical output: `TechLogTopicVariantParams`, `TechLogStudioDocumentsSearch` and `TechLogStudioPublicationsSearch` are referenced by routes but absent from the schema registry, plus six breaking changes without evidence. |
+| `test:runtime-schema` | Fails at `b297d65`: the vendored TechLog Studio contract is at `3.1.0` and `release-manifest.test.ts:117` still expects `3.0.0`. |
+| `tests/unit/removal-fixture.test.ts` | Only fails in a fresh worktree, which has no release evidence artifacts. In the working checkout `test:unit` is 1789/1789. |
+| `verify:documentation` | `FAIL_UNVERIFIED` at `b297d65` and after, in both a fresh worktree and the working checkout. `reportDigestValid` is true and both ledger results pass; the single cause is `routeScopeDocumented: false`. Ten TechLog routes — `TECH_LOG_CONCEPT`, `TECH_LOG_SETUP`, `TECH_LOG_STUDIO_ASSETS`, `TECH_LOG_STUDIO_PROJECT_EDIT`, `TECH_LOG_STUDIO_RELEASES`, `TECH_LOG_STUDIO_RELEASE_EDIT`, `TECH_LOG_STUDIO_TAXONOMY`, `TECH_LOG_STUDIO_TOPIC_EDIT`, `TECH_LOG_TOPICS`, `TECH_LOG_TOPIC_VARIANT` — shipped without being added to `README.md` or `docs/accessibility/manual-checklist.md`, and the gate requires both to name every installed route id. Adding them to the checklist means writing a manual accessibility check per route, which is product work, not a transcription. |
+
+### `test:sample-removal` (FE-GATE-020)
+
+Broken before this sync — at `b297d65` the fixture's `vite build` fails outright,
+so the gate never reaches its checks. After the transplant the fixture builds and
+reports four named failures:
+
+| Check | Cause |
+| --- | --- |
+| `registry-structure` | The pre-existing registry defect above. `check:registries:structure` fails on the ordinary tree too, so this can never pass until that is fixed. |
+| `typecheck` | `tests/features/tech-log/http-studio-gateway.test.ts` imports `tests/mocks/handlers/tech-log-studio.ts`, and `tests/mocks` is deleted whole as feature-owned. Pre-existing coupling in files this sync did not touch. |
+| `unit-integration`, `coverage` | Downstream of that typecheck failure. |
+
+Three of its checks were repaired along the way, because the transplant is what
+made them visible:
+
+- `common-test-evidence` — `tests/integration/http-execution-v3-observability.test.ts`
+ was in both `commonTestPaths` (must survive) and `featureOwnedPaths` (gets
+ deleted), so the check could never pass. The file names nothing of the
+ reference feature, so the `featureOwnedPaths` entry was stale and was removed.
+- `fixture-id-residue` — `tests/features/tech-log/studio-csrf-composition.test.ts`
+ imports the reference feature's contract contribution on purpose: it proves a
+ 403 on *another* feature's operation does not discard TechLog's CSRF token,
+ which needs a second feature to exist. With the feature gone the premise is
+ gone, so it is now feature-owned. The last residue was one comment in
+ `studio-session-credentials.ts` naming the feature by id; it now says "other
+ features'".
+- The exclusion list still named `tests/unit/ci-artifact-contract.test.ts` at its
+ old path.
+
+## Follow-ups this sync deliberately did not decide
+
+1. **TechLog's HTTP gateways still address operations by id.** The typed
+ `createFeatureHttpBinding` path is what the template now expects of a feature;
+ TechLog reaches it through a shim at the composition root. Porting the four
+ gateways is its own change.
+2. **The schema registry defect keeps two gates red.** `check:registries` and,
+ through it, `test:sample-removal` cannot pass until the three TechLog schema
+ ids are registered and the six breaking changes carry evidence.
+3. **`tests/mocks` is feature-owned but TechLog imports it.** Either the TechLog
+ handlers move out of `tests/mocks`, or the directory stops being deleted
+ wholesale.
+4. **`check:i18n` cannot distinguish a comment from a user-facing literal.**
+ Either the rule scans string literals and JSX text, or product comments stop
+ being written in Korean. Today the gate is simply red.
+5. **The template's `local-draft-feature` is carried but not installed.** It is a
+ demonstration slice with its own IndexedDB store; nothing in this product
+ composes it. It declares a third `ApplicationFeatureInputs` key, which is why
+ the composition test's `keyof` assertion had to change.
diff --git a/docs/reviews/2026-09-17-senior-frontend-architecture-review.md b/docs/reviews/2026-09-17-senior-frontend-architecture-review.md
new file mode 100644
index 0000000..15380c6
--- /dev/null
+++ b/docs/reviews/2026-09-17-senior-frontend-architecture-review.md
@@ -0,0 +1,1050 @@
+# Clean Architecture Frontend Template — Senior Architecture Review
+
+> 검토일: 2026-09-17
+>
+> 검토 기준: `develop` / `c10a709f2cdea9d58d2f4816b48b4c41d0b5268b`
+>
+> 검토 관점: 장기 유지보수, Clean Architecture 경계, reusable adapter/capability 설계, TypeScript 타입 안전성, 테스트 품질과 실행 신뢰성, 개발자 경험
+
+## 1. 결론
+
+이 저장소를 단순한 **React 프로젝트 템플릿**으로 평가하면 현재 구조는 지나치게 크고 복잡하다. 그러나 실제 목적을 반영하면 평가는 달라진다.
+
+이 저장소의 목표는 다음에 더 가깝다.
+
+> **비즈니스 use case와 domain을 기술 세부사항에서 보호하면서, HTTP·Server State·IndexedDB·OPFS·WebSocket·Upload/Download 같은 클라이언트 capability를 미리 구현해 두고, 새 제품 기능에서는 비즈니스 타입과 mapper/codec/policy를 결합해 최대한 재사용할 수 있는 Frontend Application Foundation.**
+
+즉 `Starter Template + Reusable Capability Platform`의 혼합형이다.
+
+따라서 IndexedDB runtime이 크다거나 WebSocket 구현이 복잡하다는 이유만으로 제거하거나 단순화해서는 안 된다. 이런 복잡성은 여러 feature에서 한 번 구현한 기술 문제를 재사용하기 위한 비용일 수 있다.
+
+진짜 판정 기준은 다음이다.
+
+1. feature/use case 개발자가 adapter 내부 구현을 알아야 하는가.
+2. use case가 요구하는 비즈니스 타입을 TypeScript generic으로 안전하게 adapter binding에 적용할 수 있는가.
+3. 기능별 차이를 mapper/codec/policy만 주입해 표현할 수 있는가.
+4. 공통 capability가 요구사항에 맞지 않을 때 custom adapter를 자연스럽게 구현할 수 있는가.
+5. 플랫폼 내부의 registry, lifecycle, retry, storage, browser API 복잡도가 application/domain으로 새지 않는가.
+6. 플랫폼을 사용하는 비용이 플랫폼을 직접 새로 구현하는 비용보다 충분히 낮은가.
+
+이 기준으로 보면 현재 저장소는 **방향은 맞고 기술적 기반도 강하지만, consumer surface와 검증 구조가 플랫폼 내부 복잡도를 충분히 숨기지 못하고 있다.**
+
+현재 가장 중요한 문제는 “플랫폼 기능이 너무 많다”가 아니라 다음 세 가지다.
+
+- **공통 capability를 사용하는 feature 작성 경로가 아직 충분히 작지 않다.**
+- **테스트 taxonomy와 실행 환경이 self-contained하지 않아 테스트 결과를 신뢰하기 어렵게 만든다.**
+- **플랫폼 내부 구현과 CI assurance가 매우 커졌는데, 이 복잡성이 명확한 모듈 경계로 격리되지 않았다.**
+
+---
+
+## 2. 검토 기준선
+
+현재 저장소 규모는 다음과 같다.
+
+| 영역 | 파일 수 | LOC |
+| --- | ---: | ---: |
+| `src/**` | 311 | 83,947 |
+| `src/adapters/**` | 129 | 59,120 |
+| `src/application/**` | 41 | 3,525 |
+| `src/bootstrap/**` | 13 | 1,880 |
+| `src/contracts/**` | 39 | 8,144 |
+| `src/features/**` | 24 | 2,096 |
+| `src/presentation/**` | 65 | 9,182 |
+| `tests/**` TypeScript | 308 | 72,120 |
+| `scripts/**` TypeScript | 123 | 28,397 |
+| `package.json` scripts | 114 | - |
+
+제품 dependency는 6개, dev dependency는 29개다. 외부 라이브러리 숫자를 무작정 늘린 구조는 아니다. 복잡성의 상당 부분을 저장소가 직접 소유하고 있다는 의미다.
+
+가장 큰 production source는 다음과 같다.
+
+| 파일 | LOC |
+| --- | ---: |
+| `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | 2,744 |
+| `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts` | 2,298 |
+| `src/adapters/realtime/websocket/websocket-connection.ts` | 2,003 |
+| `src/adapters/storage/opfs/opfs-worker-runtime.ts` | 1,971 |
+| `src/adapters/cache-storage/public-response-cache-adapter.ts` | 1,949 |
+| `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | 1,881 |
+| `src/adapters/realtime/reconnect-coordinator.ts` | 1,796 |
+| `src/adapters/browser-rpc/browser-rpc-runtime.ts` | 1,696 |
+| `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | 1,649 |
+| `src/adapters/http/http-execution-v3.ts` | 1,602 |
+
+큰 파일 자체를 결함으로 판정하지 않는다. 다만 이 규모에서는 내부 책임 분리가 명확하지 않으면 수정 시 regression 위험이 빠르게 증가한다.
+
+---
+
+## 3. 현재 구조에서 잘된 부분
+
+### 3.1 Clean Architecture 경계가 실제로 집행된다
+
+이 저장소의 가장 강한 부분이다.
+
+`presentation`, `application`, feature code가 `fetch`, `IndexedDB`, `WebSocket`, browser storage 같은 native I/O를 임의로 직접 호출하는 구조가 아니며, 정적 architecture gate가 dependency 방향을 검사한다.
+
+검토 시점 `check:architecture`는 다음 기준선을 통과했다.
+
+```text
+307 modules
+929 dependencies
+PASS
+```
+
+금지 dependency fixture도 실제로 거절된다.
+
+즉 폴더 이름만 `domain/application/adapter`로 만든 구조가 아니라 **의존 방향을 executable rule로 만든 구조**다.
+
+### 3.2 TypeScript generic을 이미 핵심 계약에 사용하고 있다
+
+사용자가 원하는 “use case에서 결정되는 비즈니스 타입을 공통 adapter capability에 적용”할 기반은 이미 존재한다.
+
+예를 들어 V3 HTTP executor는 다음 형태다.
+
+```ts
+interface ContractHttpExecutor {
+ execute(
+ operation: InstalledHttpContract,
+ input: Input,
+ context: HttpExecutionContext,
+ ): Promise>;
+}
+```
+
+즉 HTTP runtime은 특정 `User`, `Order`, `ReferenceResource`를 알지 않는다. `Input`, `WireOutput`, `Problem` 타입 파라미터만 안다.
+
+Server State도 `BoundMutation`와 같이 feature의 command/result 타입을 generic으로 받는다.
+
+또 `ApplicationFeatureInputs`는 module augmentation을 이용해 concrete feature를 generic application에 직접 import하지 않고도 typed feature API를 등록한다.
+
+이 방향은 유지할 가치가 높다.
+
+### 3.3 reference feature가 vertical slice의 실제 증거 역할을 한다
+
+`reference-feature`는 단순 데모 화면이 아니다.
+
+- domain은 외부 DTO/React를 모른다.
+- application은 input/gateway 계약을 가진다.
+- outbound adapter가 HTTP executor를 feature gateway로 투영한다.
+- mapper가 transport payload와 domain/application value 사이를 분리한다.
+- presentation은 application input을 호출하며 HTTP나 storage를 직접 알지 않는다.
+- sample removal test로 feature를 제거했을 때 generic platform이 유지되는지 확인한다.
+
+즉 목표 아키텍처를 실제 실행 가능한 vertical slice로 증명하고 있다는 점은 좋다.
+
+### 3.4 테스트의 사고방식은 깊다
+
+테스트는 단순 mock 호출 횟수 검증에 머무르지 않는다.
+
+예를 들어 query/mutation test는 cancellation, scope fence, stale data, optimistic mutation, effect certainty, reconciliation, duplicate submission을 실제 lifecycle 관점에서 검증한다.
+
+HTTP/storage/realtime도 정상 경로뿐 아니라 timeout, late settlement, retry, mutation effect, lifecycle cleanup 등을 검증한다.
+
+따라서 테스트의 핵심 문제는 **검증 깊이가 부족한 것**이 아니다. 오히려 검증 범위가 커지면서 **분류와 실행 경계가 무너진 것**이 문제다.
+
+---
+
+## 4. 이 저장소의 정체성을 명확히 해야 한다
+
+현재 문서와 코드에는 `template`, `platform`, `reference feature`, `optional capability`라는 표현이 모두 존재한다. 각각 틀린 표현은 아니지만, 최상위 모델이 명확하지 않으면 이후 리팩터링에서 서로 반대 방향의 결론을 낼 수 있다.
+
+이 저장소는 다음 두 축을 동시에 가진다고 정의하는 것이 가장 정확하다.
+
+```text
+Frontend Application Foundation
+│
+├── Starter / Composition Skeleton
+│ ├── bootstrap
+│ ├── routing
+│ ├── application provider
+│ ├── reference feature
+│ └── project conventions
+│
+└── Reusable Capability Platform
+ ├── HTTP
+ ├── Server State
+ ├── Auth boundary
+ ├── IndexedDB / OPFS
+ ├── Cache Storage
+ ├── Realtime / WebSocket
+ ├── Browser RPC
+ ├── Upload / Download
+ ├── Diagnostics / Telemetry
+ └── optional browser capabilities
+```
+
+중요한 점은 **둘을 물리적으로 반드시 별도 repository/package로 분리해야 한다는 의미가 아니다.**
+
+먼저 코드와 문서에서 책임을 명확히 해야 한다.
+
+- Starter는 “어떻게 조립하는가”를 보여준다.
+- Feature는 “비즈니스 요구를 어떻게 표현하는가”를 보여준다.
+- Capability Platform은 “기술 문제를 어떻게 재사용하는가”를 책임진다.
+- CI/Assurance는 “이 계약이 깨지지 않았음을 어떻게 증명하는가”를 책임진다.
+
+이 네 영역이 같은 repository 안에 있어도 된다. 문제는 한 영역을 사용하기 위해 다른 세 영역의 내부 구현을 알아야 하는 경우다.
+
+---
+
+## 5. 목표 Adapter 모델
+
+### 5.1 use case가 adapter에 의존하면 안 된다
+
+사용자의 표현인 “use case에서 나오는 비즈니스 타입을 adapter에 바로 적용한다”는 의도는 맞다. 다만 dependency 방향은 정확히 구분해야 한다.
+
+원하는 구조는 다음이다.
+
+```text
+Domain / UseCase
+ │
+ │ owns
+ ▼
+Business Port
+ ▲
+ │ implements / binds
+ │
+Feature Adapter Binding
+ │
+ │ supplies generic types + mapper + policy
+ ▼
+Reusable Capability Runtime
+```
+
+use case가 `HttpAdapter`를 직접 생성하거나 import하는 구조가 아니다.
+
+use case는 자신의 port만 안다.
+
+```ts
+interface UserRepository {
+ findById(id: UserId): Promise>;
+}
+```
+
+그리고 feature-owned outbound adapter/composition이 reusable HTTP capability를 구체화한다.
+
+```ts
+createHttpBinding({
+ contract,
+ decode: decodeUserWireDto,
+ map: mapUser,
+ mapFailure,
+});
+```
+
+이때 `User`는 generic type argument로 capability에 들어갈 수 있지만 capability source가 `User` domain module을 import하지는 않는다.
+
+### 5.2 제네릭만으로 해결하지 않는다
+
+재사용 adapter의 목표를 `Repository` 하나로 모든 기술을 추상화하는 것으로 잡으면 실패한다.
+
+HTTP, IndexedDB, WebSocket, Upload는 failure semantics와 lifecycle 자체가 다르다.
+
+공통화 단위는 다음 조합이 적절하다.
+
+```text
+Generic Type
++ Codec / Mapper
++ Policy
++ Capability Runtime
+```
+
+예를 들어 HTTP는 다음을 공통 runtime이 책임질 수 있다.
+
+- timeout/deadline
+- cancellation
+- retry
+- auth attachment
+- bounded response read
+- effect certainty
+- diagnostics/telemetry
+- transport failure normalization
+
+Feature는 다음만 책임져야 한다.
+
+- operation identity
+- request input
+- wire schema
+- wire → domain mapper
+- feature-specific failure mapping
+- 필요한 retry/idempotency policy 선택
+
+IndexedDB는 HTTP와 다른 capability factory를 가져야 한다.
+
+- key extraction
+- encode/decode
+- schema/migration policy
+- domain-specific repository operation
+
+WebSocket/realtime은 다시 다른 API가 맞다.
+
+- event decoder
+- event authority/revision policy
+- subscription ownership
+- reconnect/resume policy
+
+즉 **“하나의 generic repository”가 아니라 “capability-specific typed factory”**를 목표로 하는 것이 맞다.
+
+### 5.3 custom adapter escape hatch는 반드시 남긴다
+
+Reusable capability가 80~90%의 일반 요구를 해결하더라도 제품 요구가 capability contract와 맞지 않을 수 있다.
+
+따라서 platform API는 다음을 강제해서는 안 된다.
+
+> 모든 HTTP/storage/realtime 구현은 반드시 platform factory를 사용해야 한다.
+
+정확한 규칙은 다음이 좋다.
+
+> 공통 capability contract가 요구사항을 보존할 수 있으면 재사용한다. 요구사항을 왜곡해야 사용할 수 있다면 feature-owned custom adapter를 구현한다. 단 application port와 architecture boundary는 동일하게 유지한다.
+
+이 원칙이 있어야 platform abstraction이 business model을 끌어당기지 않는다.
+
+---
+
+## 6. 현재 구현이 목표 모델에 근접한 부분과 남은 간극
+
+### 6.1 이미 근접한 부분
+
+현재 `ContractHttpExecutor`은 좋은 기반이다.
+
+feature에서는 `ReferenceOperationMap`을 통해 operation마다 request/value type을 묶고, raw executor 결과를 domain type으로 투영한다.
+
+`ApplicationFeatureInputs`도 concrete feature를 generic application에서 분리한다.
+
+즉 **타입을 parameterize하는 방향 자체는 이미 맞다.**
+
+### 6.2 아직 feature adapter boilerplate가 크다
+
+`reference-http-gateway.ts`를 보면 feature가 다음을 모두 직접 작성한다.
+
+- operation map
+- request type projection
+- result type projection
+- `execute` 호출
+- result guard
+- mapping contract failure 생성
+
+이 중 일부는 feature-owned이어야 한다. 그러나 동일한 형태가 feature마다 반복된다면 재사용 platform의 consumer API가 충분히 올라오지 않은 것이다.
+
+향후 실제 feature 2~3개를 추가해 다음을 측정해야 한다.
+
+- HTTP feature 하나 추가 시 작성해야 하는 adapter glue LOC
+- 동일 패턴 반복 비율
+- platform 내부 type 이름을 feature 개발자가 알아야 하는 개수
+- 등록해야 하는 중앙 registry 수
+- 정상 query 하나를 연결하기 위해 건드리는 파일 수
+
+이 지표가 platform usability를 판단하는 핵심이다.
+
+### 6.3 설치 지점이 여러 곳으로 나뉜다
+
+현재 reference feature README가 명시하는 설치 지점은 세 곳이다.
+
+- `installed-feature-contracts.ts`
+- `installed-feature-runtimes.tsx`
+- `installed-feature-adapters.ts`
+
+현재 총 181 LOC라 파일 크기 자체는 크지 않다. 문제는 feature가 늘었을 때 **한 기능 설치가 여러 중앙 catalog 수정으로 확산되는 구조**라는 점이다.
+
+이 구조는 계약/runtime/composition을 분리한다는 장점이 있으므로 무작정 한 객체로 합치면 안 된다.
+
+대신 다음 목표가 필요하다.
+
+> feature-owned contribution을 각 boundary가 소비하되, 새 feature 개발자가 중앙 설치 파일의 내부 구조를 반복해서 편집하지 않게 한다.
+
+예를 들어 feature가 contract/runtime/adapter contribution을 각각 export하고, installed catalog는 단순 aggregation만 담당하는 구조가 적절하다.
+
+### 6.4 `ApplicationApi`는 지금은 관리 가능하지만 Service Locator로 성장할 수 있다
+
+현재 `ApplicationApi`는 다음 플랫폼 기능을 직접 노출한다.
+
+- session
+- preferences
+- diagnostics
+- runtime
+- recovery
+- features
+
+구조 자체는 잘못이 아니다. presentation에서 concrete adapter를 숨기는 역할을 한다.
+
+그러나 기능이 계속 추가되며 모든 application capability가 하나의 root object 아래 들어가면 다음과 같은 사용 패턴이 일반화될 수 있다.
+
+```ts
+const application = useApplication();
+```
+
+이후 모든 presentation 코드가 거대한 application service locator를 바라보게 된다.
+
+권장 방향은 root provider를 유지하더라도 consumer API를 좁히는 것이다.
+
+```text
+useSession()
+useRuntimeCapabilities()
+useReferenceFeature()
+```
+
+즉 composition은 하나여도 presentation dependency surface는 필요한 capability만 노출한다.
+
+---
+
+## 7. P0 — 테스트 실행 환경이 self-contained하지 않다
+
+이 문제는 다른 리팩터링보다 먼저 고치는 것이 좋다. 테스트가 신뢰되지 않으면 이후 구조 변경의 안전망도 신뢰할 수 없다.
+
+### 7.1 Component test가 host `NODE_ENV`에 영향을 받는다
+
+검토 환경의 host에는 다음이 설정되어 있었다.
+
+```text
+NODE_ENV=production
+```
+
+현재 `package.json`의 `test:component`는 다음과 같이 Vitest를 바로 실행하며 test environment를 고정하지 않는다.
+
+```text
+vitest run tests/component ...
+```
+
+그 결과:
+
+```text
+pnpm test:component
+→ React.act is not a function
+→ 119 tests failed
+```
+
+반면 같은 checkout에서:
+
+```text
+NODE_ENV=test pnpm test:component
+→ 20 test files passed
+→ 130 tests passed
+```
+
+했다.
+
+이것은 119개 component가 각각 잘못된 것이 아니라 **test runner가 외부 shell environment를 그대로 받아 React production test path를 로드한 것**이다.
+
+템플릿/플랫폼 저장소의 테스트는 개발자 머신의 우연한 환경 값에 따라 의미가 바뀌면 안 된다.
+
+### 권장
+
+- component/unit/integration runner가 필요한 environment를 명시적으로 소유한다.
+- test bootstrap 단계에서 잘못된 `NODE_ENV`를 fail-fast하거나 고정한다.
+- CI에서만 성립하는 environment assumption을 일반 test script와 분리한다.
+
+---
+
+## 8. P0 — `unit` test taxonomy가 실제 실행 특성과 맞지 않는다
+
+현재 `docs/testing/taxonomy.md`는 `test:unit`을 별도 test level로 정의하지만 `tests/unit` 안에는 실제로 host-level system assurance가 포함된다.
+
+검토 환경에서:
+
+```text
+pnpm test:unit
+→ 99 failures
+```
+
+가 발생했다.
+
+하지만 주요 실패는 business/application logic regression이 아니었다.
+
+대표 원인은 다음과 같다.
+
+```text
+provider sandbox unavailable: /usr/bin/bwrap is required
+systemctl list-units failed: Failed to connect to bus
+npm_config_userconfig / npm_config_prefix / npm_config_globalconfig host environment
+```
+
+`ci-artifact-contract.test.ts`는 다음을 검증한다.
+
+- bubblewrap sandbox
+- systemd unit
+- cgroup/resource limit
+- process guardian/supervisor
+- background process kill/collection
+- archive/provider isolation
+- host path protection
+
+이 테스트들은 가치가 있다. 제거할 대상이 아니다.
+
+그러나 **unit test가 아니다.**
+
+권장 taxonomy는 다음과 같다.
+
+```text
+tests/
+├── unit/
+│ ├── domain
+│ ├── application
+│ └── pure-policy
+│
+├── contract/
+│ └── reusable-capability contracts
+│
+├── component/
+│ └── React / hook / UI behavior
+│
+├── integration/
+│ ├── HTTP/MSW
+│ ├── IndexedDB
+│ └── browser runtime boundaries
+│
+├── system/
+│ └── ci-runner/
+│ ├── sandbox
+│ ├── cgroup
+│ ├── process-supervision
+│ └── supply-chain
+│
+└── e2e/
+```
+
+특히 `pnpm test:unit`은 **지원 Node 환경만 있으면 일반 개발 머신에서 deterministic하게 실행**되어야 한다.
+
+systemd/bwrap/cgroup이 필요하면 `test:ci-runner` 또는 `test:system`처럼 요구사항이 이름에 드러나야 한다.
+
+---
+
+## 9. P1 — Adapter runtime은 “크기”가 아니라 내부 경계를 기준으로 재검토해야 한다
+
+기존에 2,000~2,700 LOC 파일을 단순히 작게 나누는 것은 권장하지 않는다.
+
+이미 adapter review의 D-07이 적절한 원칙을 가지고 있다.
+
+> state machine과 Saga 경계로만 큰 runtime을 나누고, public capability identity/failure taxonomy/persisted schema/wire semantics를 유지한다.
+
+이 원칙을 그대로 적용하는 것이 맞다.
+
+예를 들어 `indexeddb-runtime.ts`를 다음 이유만으로 분리해서는 안 된다.
+
+> 2,744줄이니까 500줄씩 다섯 파일로 나누자.
+
+대신 다음 책임이 독립적으로 설명되고 테스트 가능한지 본다.
+
+- connection/open/upgrade lifecycle
+- transaction ownership
+- schema/migration state machine
+- quota/budget policy
+- serialization/codec
+- mutation settlement
+- cleanup/compensation
+- recovery/reconciliation
+
+WebSocket도 같은 기준이다.
+
+- connection state machine
+- reconnect/backoff policy
+- heartbeat
+- subscription ownership
+- writer/lease lifecycle
+- resume/gap policy
+- message codec
+
+**하나의 변경 이유와 하나의 failure model을 공유한다면 같은 모듈에 있어도 된다.**
+
+반대로 독립 lifecycle을 가진 책임이 같은 2,000줄 파일에서 mutable state를 공유한다면 추출 우선순위가 높다.
+
+---
+
+## 10. P1 — 테스트 파일도 behavior contract 단위로 분리해야 한다
+
+현재 가장 큰 테스트 파일은 다음과 같다.
+
+| 파일 | LOC |
+| --- | ---: |
+| `ci-artifact-contract.test.ts` | 2,538 |
+| `presigned-transfer.test.ts` | 2,518 |
+| `image-cdn-runtime.test.ts` | 2,430 |
+| `application-query.test.tsx` | 2,196 |
+| `security-followup.test.ts` | 1,859 |
+| `public-response-cache.test.ts` | 1,711 |
+| `ci-workflow-generation.test.ts` | 1,635 |
+
+테스트 파일이 production 파일보다 커지는 것 자체는 문제가 아니다. 복잡한 state machine은 많은 테스트를 필요로 한다.
+
+문제는 서로 다른 behavior가 하나의 파일 안에 섞이면 실패 메시지가 ownership을 알려주지 못한다는 점이다.
+
+예를 들어 `application-query.test.tsx`는 사실상 다음 여러 계약을 검증한다.
+
+```text
+query initial/background state
+query scope fence
+result budget
+mutation scope fence
+optimistic mutation
+unknown effect reconciliation
+concurrency / duplicate submission
+cache invalidation
+```
+
+따라서 다음처럼 behavior 단위로 분리하는 것이 더 낫다.
+
+```text
+application-query/
+├── query-state.test.tsx
+├── query-scope-fence.test.tsx
+├── query-budget.test.tsx
+├── mutation-scope-fence.test.tsx
+├── optimistic-mutation.test.tsx
+├── mutation-reconciliation.test.tsx
+├── duplicate-submission.test.tsx
+└── fixtures.ts
+```
+
+테스트 분리의 목표도 LOC가 아니다.
+
+> 하나의 실패 파일명이 “어떤 계약이 깨졌는지”를 설명해야 한다.
+
+---
+
+## 11. P1 — Capability consumer API를 실제 feature 개발 비용으로 평가해야 한다
+
+현재 플랫폼은 내부 correctness에 대한 검증은 매우 강하다. 반면 앞으로는 **새 feature를 만드는 개발자의 비용**을 별도 품질 지표로 봐야 한다.
+
+추천하는 평가 시나리오는 실제 sample feature 2개를 추가해보는 것이다.
+
+### 시나리오 A — 일반 REST CRUD
+
+필요 조건:
+
+- list/detail/create/update
+- pagination
+- error mapping
+- optimistic mutation 하나
+
+측정:
+
+- feature-owned LOC
+- platform glue LOC
+- 수정 파일 수
+- 중앙 registry 수정 수
+- transport/runtime type을 직접 알아야 하는 횟수
+
+### 시나리오 B — IndexedDB local draft
+
+필요 조건:
+
+- domain draft type
+- save/find/remove
+- codec
+- migration 없는 단순 store
+
+측정:
+
+- IndexedDB native API를 feature가 알아야 하는가
+- runtime internal type을 import해야 하는가
+- `create...Repository` 계열 binding만으로 해결되는가
+
+이 실험 결과가 다음 platform API 리팩터링의 근거가 되어야 한다.
+
+---
+
+## 12. P1 — `contracts`는 계속 커지면 제2의 `shared/common`이 된다
+
+현재 `src/contracts`는 39개 파일, 약 8,144 LOC다.
+
+`contracts`라는 이름은 편리하지만 ownership을 잃기 쉽다.
+
+특히 다음이 모두 한 bucket으로 들어가면 문제가 된다.
+
+- error vocabulary
+- server-state contracts
+- capability registry
+- boundary mapper
+- mutation intent
+- runtime descriptor
+- compatibility metadata
+
+공통 계약이 실제로 여러 capability가 공유하는 SSOT라면 `contracts`에 있어도 된다.
+
+그러나 **특정 feature/adapter만 소비하는 contract는 owner 쪽에 두는 것이 더 낫다.**
+
+판정 질문은 단순하다.
+
+> 이 타입을 바꾸는 이유가 어떤 모듈의 요구사항 변화 때문인가?
+
+답이 항상 특정 feature/storage/http라면 global contracts가 아닐 가능성이 높다.
+
+---
+
+## 13. P1 — CI/Assurance는 가치가 있지만 product development path와 격리해야 한다
+
+현재 package script는 114개, `scripts/**/*.ts`는 123개 / 약 28K LOC다.
+
+이는 단순 frontend build script 수준을 넘어선다.
+
+현재 저장소는 다음을 자체적으로 검증한다.
+
+- architecture graph
+- registry compatibility
+- artifact semantic validation
+- supply-chain evidence
+- reproducible build
+- provider sandbox
+- promotion/finalization
+- archive traversal/symlink/hardlink
+- release admission
+- security fixtures
+
+이 기능을 단순화한다는 이유로 제거할 필요는 없다. 플랫폼 품질과 supply-chain assurance를 강하게 가져가겠다면 정당한 투자다.
+
+다만 개발자가 일반 feature를 수정할 때 이 전체 영역을 알아야 해서는 안 된다.
+
+권장 구조적 목표는 다음이다.
+
+```text
+Product development path
+ feature → focused test → type/lint/architecture
+
+Platform capability path
+ adapter → capability contract/integration tests
+
+Assurance path
+ CI runner → supply-chain/system/promotion tests
+```
+
+세 경로의 명령과 실패 메시지가 명확히 분리되어야 한다.
+
+---
+
+## 14. P2 — 실제 중복은 정책 중복부터 제거한다
+
+중복 제거의 목표를 “같은 코드 한 줄도 두 번 쓰지 않는다”로 잡으면 이 프로젝트에서는 오히려 abstraction이 과해진다.
+
+특히 security/protocol boundary의 작은 validator는 local duplication이 가독성과 auditability에 도움이 될 수 있다.
+
+반대로 **정책 중복은 제거해야 한다.**
+
+현재 `use-reference-feature.ts`에는 `CREATE_REFERENCE_RESOURCE` mutation definition이 두 경로에 반복된다.
+
+반복되는 핵심 값은 다음과 같다.
+
+```text
+definitionId
+operationId
+requiresIdempotencyKey
+owner
+duplicatePolicy
+invalidate
+```
+
+이것은 단순 syntax 중복이 아니라 하나의 mutation policy다.
+
+한쪽만 수정되면 같은 feature 안에서 서로 다른 concurrency/idempotency 동작을 할 수 있다.
+
+따라서 feature-owned mutation definition 또는 factory로 단일화하는 것이 맞다.
+
+반대로 `isPlainRecord` 같은 3~5줄 helper는 모든 adapter에서 무조건 한 global utility로 합칠 필요가 없다.
+
+---
+
+## 15. P2 — compatibility re-export는 canonical import path를 흐릴 수 있다
+
+현재 일부 UI와 Result 계층에는 canonical 정의와 compatibility re-export가 동시에 존재한다.
+
+이런 구조가 migration window를 위해 필요하다면 괜찮다.
+
+하지만 템플릿 출발점에서 두 경로가 모두 정식 API처럼 보이면 새 개발자가 어떤 import를 사용해야 하는지 판단해야 한다.
+
+원칙은 다음이 적절하다.
+
+- public import path는 capability마다 하나를 canonical로 둔다.
+- compatibility export는 deprecated/migration purpose임을 명시한다.
+- migration 종료 조건이 충족되면 제거한다.
+- 테스트 편의를 위해 barrel export를 무한히 확장하지 않는다.
+
+---
+
+## 16. Hybrid Architecture를 공식 모델로 문서화할 필요가 있다
+
+현재 저장소는 순수 horizontal Clean Architecture가 아니다.
+
+실제 구조는 다음 hybrid에 가깝다.
+
+```text
+Platform horizontal layers
+├── application
+├── contracts
+├── adapters
+├── presentation
+└── bootstrap
+
+Feature vertical slices
+└── features/
+ ├── domain
+ ├── application
+ ├── adapters
+ ├── contracts
+ └── presentation
+```
+
+이 구조는 프론트엔드에서 합리적이다.
+
+공통 HTTP/storage/query runtime을 모든 feature 안에 복사할 이유는 없고, feature domain/application은 vertical slice로 격리할 수 있기 때문이다.
+
+따라서 전역 `src/domain`이 없다는 이유로 억지로 생성할 필요도 없다.
+
+대신 문서에서 다음을 명시해야 한다.
+
+> platform은 horizontal capability layer를 사용하고, product business feature는 vertical slice를 사용한다. feature는 platform capability를 port 뒤에서 소비하며 platform은 concrete feature를 알지 않는다.
+
+이 문장이 공식 architecture model이 되면 “왜 여기에는 domain이 없고 feature 안에는 domain이 있는가” 같은 혼란이 줄어든다.
+
+---
+
+## 17. 권장 리팩터링 순서
+
+### Phase 0 — 테스트 신뢰성 정상화
+
+먼저 구조를 바꾸지 않고 검증 기반을 고친다.
+
+1. test runner의 `NODE_ENV` 등 필수 environment를 deterministic하게 만든다.
+2. `tests/unit`에서 systemd/bwrap/cgroup 의존 테스트를 분리한다.
+3. `test:unit`, `test:component`, `test:integration`, `test:system`, `test:e2e`의 의미를 다시 고정한다.
+4. Node version requirement와 local runner requirement를 명확하게 fail-fast한다.
+
+이 단계가 끝나야 이후 refactoring failure를 실제 regression으로 믿을 수 있다.
+
+### Phase 1 — reference feature를 platform consumer UX 기준으로 리팩터링
+
+새 abstraction을 먼저 만들지 않는다.
+
+현재 reference feature를 기준으로 다음을 측정하고 줄인다.
+
+- HTTP gateway boilerplate
+- mapper/result guard 중복
+- query/mutation definition duplication
+- installed contribution 수정 지점
+- platform internal type exposure
+
+이 단계에서 capability API의 이상적인 최소 사용 형태를 결정한다.
+
+### Phase 2 — capability-specific typed factory 정리
+
+반복이 확인된 경우에만 factory를 만든다.
+
+후보:
+
+```text
+HTTP operation/gateway binder
+IndexedDB typed repository/storage binder
+Realtime event source binder
+Transfer command/session binder
+```
+
+하나의 범용 repository/framework로 합치지 않는다.
+
+### Phase 3 — Application/Feature installation surface 축소
+
+- root ApplicationProvider는 유지 가능
+- feature consumer hook은 narrow API 제공
+- installed catalog는 aggregation 역할로 제한
+- feature-owned contribution 정의를 강화
+- concrete feature를 generic platform에서 import하지 않는 규칙 유지
+
+### Phase 4 — 거대 runtime 내부 경계 추출
+
+characterization test를 먼저 고정한다.
+
+우선순위 후보:
+
+1. IndexedDB runtime
+2. resumable upload
+3. WebSocket connection/reconnect
+4. HTTP execution V3
+5. OPFS runtime/journal
+
+파일 크기가 아니라 state machine/Saga/lifecycle ownership을 기준으로 추출한다.
+
+### Phase 5 — 거대 테스트 분해
+
+production runtime extraction과 같은 behavior boundary에 맞춰 test suite도 분리한다.
+
+### Phase 6 — CI/Assurance 경로 분리
+
+product feature 개발 loop와 release/supply-chain system assurance loop를 명령, 테스트 디렉터리, prerequisite 측면에서 명확히 구분한다.
+
+---
+
+## 18. 명시적으로 하지 말아야 할 리팩터링
+
+### 18.1 모든 adapter를 하나의 generic repository로 통합하지 않는다
+
+HTTP, IndexedDB, Realtime, Upload는 lifecycle과 failure semantics가 다르다.
+
+타입 파라미터가 비슷하다는 이유로 하나의 abstraction으로 합치면 business 요구를 기술 abstraction에 맞추게 된다.
+
+### 18.2 use case가 platform adapter를 직접 import하지 않는다
+
+`UseCase → HttpAdapter` 구조가 되면 Clean Architecture의 핵심 목적을 잃는다.
+
+Generic type binding은 feature adapter/composition에서 일어나야 한다.
+
+### 18.3 단순화를 이유로 hardening을 제거하지 않는다
+
+현재 retry/effect certainty/bounded read/recovery/sandbox 같은 계약은 대부분 실제 failure mode를 막기 위해 존재한다.
+
+필요한 것은 삭제가 아니라 **internal complexity encapsulation**이다.
+
+### 18.4 파일 길이만 보고 나누지 않는다
+
+2,000줄이어도 하나의 cohesive state machine이면 함부로 분리하지 않는다.
+
+반대로 300줄이어도 서로 다른 lifecycle owner가 섞여 있으면 분리 대상이다.
+
+### 18.5 중복률 0%를 목표로 하지 않는다
+
+local protocol validator의 작은 중복보다 policy가 여러 곳에 존재하는 중복이 더 위험하다.
+
+---
+
+## 19. 최종 목표 개발 경험
+
+이 Foundation이 잘 리팩터링됐을 때 새 feature 개발자는 대략 다음만 작성하면 되어야 한다.
+
+```text
+1. Domain type / invariant
+2. UseCase
+3. Port
+4. Transport/storage schema와 mapper
+5. Capability binding 설정
+6. Presentation controller/page
+```
+
+그리고 HTTP/IndexedDB/WebSocket 내부의 다음 내용을 몰라도 되어야 한다.
+
+```text
+retry scheduler
+abort ownership
+effect certainty
+transaction lease
+reconnect coordinator
+OPFS journal
+provider lifecycle
+telemetry delivery
+```
+
+개념적으로 다음 형태가 목표다.
+
+```text
+Business Domain
+ ↓
+UseCase
+ ↓
+Port
+ ↓
+Feature-owned Binding
+
+ + mapper/codec
+ + policy
+ ↓
+Reusable Capability Runtime
+ ↓
+Browser / Network / Native API
+```
+
+이 구조가 성립하면 내부 runtime이 복잡하다는 사실은 문제가 아니다.
+
+오히려 복잡한 기술 문제를 한 곳에서 해결했기 때문에 각 제품 feature는 더 단순해진다.
+
+---
+
+## 20. 우선순위 요약
+
+| 우선순위 | Finding | 조치 방향 |
+| --- | --- | --- |
+| P0 | 테스트가 host `NODE_ENV` 영향을 받음 | test environment deterministic하게 고정 |
+| P0 | unit suite에 systemd/bwrap/cgroup 테스트 혼재 | system/CI-runner suite로 분리 |
+| P1 | capability consumer API의 실제 개발 비용이 불명확 | reference + 추가 feature로 사용성 측정 |
+| P1 | feature 설치가 여러 중앙 catalog로 확산 | feature-owned contribution + 단순 aggregation |
+| P1 | 거대 runtime 내부 책임 추적 비용 | state machine/Saga/lifecycle 기준 extraction |
+| P1 | 2K+ LOC test file 다수 | behavior contract별 suite 분리 |
+| P1 | `contracts`가 generic bucket으로 성장 가능 | ownership 기준 재배치 |
+| P1 | product dev path와 CI assurance path가 뒤섞임 | command/test prerequisite 격리 |
+| P2 | `ApplicationApi`의 Service Locator 성장 위험 | narrow consumer hooks/API |
+| P2 | feature mutation policy 중복 | feature-owned definition SSOT |
+| P2 | compatibility/re-export 경로 | canonical public API 지정 |
+| P2 | hybrid architecture 설명 부족 | platform horizontal + feature vertical 공식화 |
+
+---
+
+## 21. 이번 검토에서 확인한 검증 결과
+
+코드 변경 전 기준선에서 확인한 결과다.
+
+```text
+check:architecture
+→ PASS
+→ 307 modules / 929 dependencies
+```
+
+앞선 검토에서 다음도 통과했다.
+
+```text
+check:types
+→ PASS
+
+lint
+→ PASS
+```
+
+Component test는 host environment를 그대로 사용하면 실패했다.
+
+```text
+pnpm test:component
+→ FAIL
+→ React.act is not a function
+→ host NODE_ENV=production
+```
+
+동일 checkout에서 test environment를 명시하면 통과했다.
+
+```text
+NODE_ENV=test pnpm test:component
+→ 20 files PASS
+→ 130 tests PASS
+```
+
+Unit 전체는 현재 Coka host에서 green이 아니다.
+
+```text
+pnpm test:unit
+→ FAIL
+→ 99 failures
+```
+
+대표 원인은 다음이다.
+
+- `/usr/bin/bwrap` 미설치
+- systemd bus 사용 불가
+- host `npm_config_*` 환경 오염
+
+따라서 이 결과를 application/domain regression 99건으로 해석하면 안 된다.
+
+또한 저장소가 요구하는 Node 범위는 `>=24.11.0 <25.0.0`인데, 현재 Coka host는 Node `22.23.2`다. 정식 full verification은 지원 Node 환경에서 다시 수행해야 한다.
+
+---
+
+## 22. 최종 평가
+
+현재 저장소는 설계가 부족해서 문제가 생긴 코드베이스가 아니다.
+
+오히려 반대다.
+
+**실제 브라우저와 네트워크에서 발생할 수 있는 많은 실패를 플랫폼이 직접 책임지려 하면서 내부 correctness와 assurance가 매우 강해졌고, 그 결과 플랫폼 사용성과 유지보수 비용이 다음 병목이 된 상태**다.
+
+따라서 앞으로의 리팩터링 목표는 abstraction을 더 추가하는 것이 아니다.
+
+다음 세 가지가 핵심이다.
+
+1. **비즈니스 개발자가 보는 API를 더 작게 만든다.**
+2. **플랫폼 내부의 복잡성은 capability boundary 안에서 더 명확하게 격리한다.**
+3. **테스트와 CI를 실제 실행 성격에 맞게 분리해 검증 결과를 신뢰할 수 있게 만든다.**
+
+특히 이 프로젝트의 성공 여부는 “몇 개의 capability를 구현했는가”보다 다음 질문으로 판단해야 한다.
+
+> 새로운 비즈니스 기능을 구현할 때, 개발자가 domain과 use case에 집중한 채 이미 구현된 capability를 타입 안전하게 조립할 수 있는가?
+
+그 답이 지속적으로 `예`가 되도록 만드는 것이 이후 리팩터링의 기준이 되어야 한다.
diff --git a/docs/reviews/adapters/INVENTORY.md b/docs/reviews/adapters/INVENTORY.md
index ccfa8bf..48a0c0f 100644
--- a/docs/reviews/adapters/INVENTORY.md
+++ b/docs/reviews/adapters/INVENTORY.md
@@ -9,127 +9,140 @@
| # | full path | 상세 리뷰 |
| ---: | --- | --- |
| 1 | `src/adapters/auth/external-session-adapter.ts` | [Network/state](./01-network-and-state.md) |
-| 2 | `src/adapters/browser-file-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 3 | `src/adapters/browser-file-storage/result.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 4 | `src/adapters/browser-file-storage/storage-manager-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 5 | `src/adapters/browser-files/browser-file-picker.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 6 | `src/adapters/browser-files/browser-file-policy-registry.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 7 | `src/adapters/browser-files/browser-file-vault.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 8 | `src/adapters/browser-files/create-browser-file-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 9 | `src/adapters/browser-files/download-delivery-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 10 | `src/adapters/browser-files/file-observer.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 11 | `src/adapters/browser-files/file-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 12 | `src/adapters/browser-files/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 13 | `src/adapters/browser-files/object-url-lease.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 14 | `src/adapters/browser-rpc/browser-rpc-runtime.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 15 | `src/adapters/browser-rpc/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 16 | `src/adapters/browser-rpc/transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 17 | `src/adapters/browser-rpc/unavailable-browser-rpc-transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 18 | `src/adapters/browser-transfer/image-cdn/README.md` | [Browser transfer](./04-browser-transfer.md) |
-| 19 | `src/adapters/browser-transfer/image-cdn/browser-image-probe.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 20 | `src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 21 | `src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 22 | `src/adapters/browser-transfer/image-cdn/image-header-metadata.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 23 | `src/adapters/browser-transfer/image-cdn/index.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 24 | `src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 25 | `src/adapters/browser-transfer/index.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 26 | `src/adapters/browser-transfer/presigned/incremental-sha256.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 27 | `src/adapters/browser-transfer/presigned/index.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 28 | `src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 29 | `src/adapters/browser-transfer/presigned/presigned-capability-vault.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 30 | `src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 31 | `src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 32 | `src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 33 | `src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 34 | `src/adapters/browser-transfer/resumable-upload/index.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 35 | `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 36 | `src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 37 | `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 38 | `src/adapters/browser-transfer/resumable-upload/runtime-policy.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 39 | `src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 40 | `src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 41 | `src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts` | [Browser transfer](./04-browser-transfer.md) |
-| 42 | `src/adapters/cache-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 43 | `src/adapters/cache-storage/public-cache-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 44 | `src/adapters/cache-storage/public-response-cache-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 45 | `src/adapters/cross-context-invalidation/browser-cross-context-host.ts` | [Network/state](./01-network-and-state.md) |
-| 46 | `src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts` | [Network/state](./01-network-and-state.md) |
-| 47 | `src/adapters/cross-context-invalidation/index.ts` | [Network/state](./01-network-and-state.md) |
-| 48 | `src/adapters/diagnostics/bounded-diagnostics.ts` | [Network/state](./01-network-and-state.md) |
-| 49 | `src/adapters/http/bounded-body-reader.ts` | [Network/state](./01-network-and-state.md) |
-| 50 | `src/adapters/http/bounded-json.ts` | [Network/state](./01-network-and-state.md) |
-| 51 | `src/adapters/http/client.ts` | [Network/state](./01-network-and-state.md) |
-| 52 | `src/adapters/http/http-contract-bridge.ts` | [Network/state](./01-network-and-state.md) |
-| 53 | `src/adapters/http/http-effect-certainty.ts` | [Network/state](./01-network-and-state.md) |
-| 54 | `src/adapters/http/http-execution-v3.ts` | [Network/state](./01-network-and-state.md) |
-| 55 | `src/adapters/http/request-builder.ts` | [Network/state](./01-network-and-state.md) |
-| 56 | `src/adapters/http/resource-mapper.ts` | [Network/state](./01-network-and-state.md) |
-| 57 | `src/adapters/http/retry-policy.ts` | [Network/state](./01-network-and-state.md) |
-| 58 | `src/adapters/http/schema-registry.ts` | [Network/state](./01-network-and-state.md) |
-| 59 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) |
-| 60 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
-| 61 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) |
-| 62 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) |
-| 63 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) |
-| 64 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) |
-| 65 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) |
-| 66 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) |
-| 67 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) |
-| 68 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) |
-| 69 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 70 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 71 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 72 | `src/adapters/realtime/json-member-scanner.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 73 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 74 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 75 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 76 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 77 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 78 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 79 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 80 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 81 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 82 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 83 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 84 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 85 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
-| 86 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 87 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 88 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 89 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 90 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 91 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 92 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 93 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 94 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 95 | `src/adapters/storage/indexeddb/indexeddb-failure.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 96 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 97 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 98 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 99 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 100 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 101 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 102 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 103 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 104 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 105 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 106 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 107 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 108 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
-| 109 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) |
-| 110 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 111 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 112 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 113 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 114 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 115 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 116 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 117 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 118 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 119 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-| 120 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 2 | `src/adapters/auth/index.ts` | [Network/state](./01-network-and-state.md) |
+| 3 | `src/adapters/browser-file-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 4 | `src/adapters/browser-file-storage/result.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 5 | `src/adapters/browser-file-storage/storage-manager-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 6 | `src/adapters/browser-files/browser-file-picker.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 7 | `src/adapters/browser-files/browser-file-policy-registry.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 8 | `src/adapters/browser-files/browser-file-vault.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 9 | `src/adapters/browser-files/create-browser-file-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 10 | `src/adapters/browser-files/download-delivery-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 11 | `src/adapters/browser-files/file-observer.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 12 | `src/adapters/browser-files/file-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 13 | `src/adapters/browser-files/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 14 | `src/adapters/browser-files/object-url-lease.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 15 | `src/adapters/browser-rpc/browser-rpc-runtime.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 16 | `src/adapters/browser-rpc/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 17 | `src/adapters/browser-rpc/transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 18 | `src/adapters/browser-rpc/unavailable-browser-rpc-transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 19 | `src/adapters/browser-transfer/image-cdn/README.md` | [Browser transfer](./04-browser-transfer.md) |
+| 20 | `src/adapters/browser-transfer/image-cdn/browser-image-probe.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 21 | `src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 22 | `src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 23 | `src/adapters/browser-transfer/image-cdn/image-header-metadata.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 24 | `src/adapters/browser-transfer/image-cdn/index.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 25 | `src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 26 | `src/adapters/browser-transfer/index.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 27 | `src/adapters/browser-transfer/presigned/incremental-sha256.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 28 | `src/adapters/browser-transfer/presigned/index.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 29 | `src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 30 | `src/adapters/browser-transfer/presigned/presigned-capability-vault.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 31 | `src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 32 | `src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 33 | `src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 34 | `src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 35 | `src/adapters/browser-transfer/resumable-upload/index.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 36 | `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 37 | `src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 38 | `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 39 | `src/adapters/browser-transfer/resumable-upload/runtime-policy.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 40 | `src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 41 | `src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 42 | `src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts` | [Browser transfer](./04-browser-transfer.md) |
+| 43 | `src/adapters/cache-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 44 | `src/adapters/cache-storage/public-cache-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 45 | `src/adapters/cache-storage/public-response-cache-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 46 | `src/adapters/cross-context-invalidation/browser-cross-context-host.ts` | [Network/state](./01-network-and-state.md) |
+| 47 | `src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts` | [Network/state](./01-network-and-state.md) |
+| 48 | `src/adapters/cross-context-invalidation/index.ts` | [Network/state](./01-network-and-state.md) |
+| 49 | `src/adapters/diagnostics/bounded-diagnostics.ts` | [Network/state](./01-network-and-state.md) |
+| 50 | `src/adapters/diagnostics/index.ts` | [Network/state](./01-network-and-state.md) |
+| 51 | `src/adapters/http/bounded-body-reader.ts` | [Network/state](./01-network-and-state.md) |
+| 52 | `src/adapters/http/bounded-json.ts` | [Network/state](./01-network-and-state.md) |
+| 53 | `src/adapters/http/client.ts` | [Network/state](./01-network-and-state.md) |
+| 54 | `src/adapters/http/feature-http-binding.ts` | [Network/state](./01-network-and-state.md) |
+| 55 | `src/adapters/http/http-contract-bridge.ts` | [Network/state](./01-network-and-state.md) |
+| 56 | `src/adapters/http/http-effect-certainty.ts` | [Network/state](./01-network-and-state.md) |
+| 57 | `src/adapters/http/http-execution-v3.ts` | [Network/state](./01-network-and-state.md) |
+| 58 | `src/adapters/http/http-retry-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
+| 59 | `src/adapters/http/index.ts` | [Network/state](./01-network-and-state.md) |
+| 60 | `src/adapters/http/request-builder.ts` | [Network/state](./01-network-and-state.md) |
+| 61 | `src/adapters/http/resource-mapper.ts` | [Network/state](./01-network-and-state.md) |
+| 62 | `src/adapters/http/retry-policy.ts` | [Network/state](./01-network-and-state.md) |
+| 63 | `src/adapters/http/schema-registry.ts` | [Network/state](./01-network-and-state.md) |
+| 64 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) |
+| 65 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) |
+| 66 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
+| 67 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) |
+| 68 | `src/adapters/platform/index.ts` | [Network/state](./01-network-and-state.md) |
+| 69 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) |
+| 70 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) |
+| 71 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) |
+| 72 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) |
+| 73 | `src/adapters/query-cache/cursor-pagination-contract.ts` | [Network/state](./01-network-and-state.md) |
+| 74 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) |
+| 75 | `src/adapters/query-cache/index.ts` | [Network/state](./01-network-and-state.md) |
+| 76 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) |
+| 77 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) |
+| 78 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) |
+| 79 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 80 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 81 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 82 | `src/adapters/realtime/json-member-scanner.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 83 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 84 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 85 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 86 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 87 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 88 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 89 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 90 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 91 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 92 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 93 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 94 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 95 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
+| 96 | `src/adapters/service-worker/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 97 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 98 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 99 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 100 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 101 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 102 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 103 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 104 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 105 | `src/adapters/storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 106 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 107 | `src/adapters/storage/indexeddb/indexeddb-failure.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 108 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 109 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 110 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 111 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 112 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 113 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 114 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 115 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 116 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 117 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 118 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 119 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 120 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
+| 121 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) |
+| 122 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) |
+| 123 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 124 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 125 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 126 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 127 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 128 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 129 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 130 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 131 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 132 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
+| 133 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
-합계: **120/120**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
+합계: **133/133**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
## Feature-scoped adapter 리뷰 (`src/adapters/**` 밖)
diff --git a/docs/reviews/adapters/README.md b/docs/reviews/adapters/README.md
index 3a35e1a..1c70e9b 100644
--- a/docs/reviews/adapters/README.md
+++ b/docs/reviews/adapters/README.md
@@ -133,3 +133,15 @@ listener/timer 정리, first-terminal-owner, late rejection 관찰, late native
- cleanup 실패를 observation만 남기고 success로 바꾸지 않는다.
- schema/database version을 downgrade하거나 broad prefix/root/database 전체 삭제를 rollback으로 사용하지 않는다.
- SSE↔WebSocket, Connect↔gRPC-Web↔REST를 장애 중 자동 전환하지 않는다.
+
+## 테스트의 어댑터 import
+
+`tests/` 아래 어댑터 import는 배럴로 일괄 이관하지 않는다. `check:architecture`는
+`src`만 스캔하므로 강제되지 않고, 단위 테스트의 상당수가 배럴에 없는 내부
+심볼을 의도적으로 겨눈다.
+
+어떤 테스트 파일을 **다른 이유로** 수정하거나 분할할 때, 그 파일이 쓰는
+심볼이 해당 그룹 배럴에 있으면 그 파일 안에서만 배럴 경로로 바꾼다.
+배럴에 없는 심볼이면 깊은 경로를 유지한다. 배럴에 추가하고 싶으면 그 심볼이
+공개 표면임을 먼저 논증한다 — 테스트 편의로 배럴을 키우면 배럴이 경계가
+아니라 재수출 덤프가 된다.
diff --git a/docs/superpowers/plans/2026-09-16-adapter-barrel-boundary.md b/docs/superpowers/plans/2026-09-16-adapter-barrel-boundary.md
new file mode 100644
index 0000000..b9968a9
--- /dev/null
+++ b/docs/superpowers/plans/2026-09-16-adapter-barrel-boundary.md
@@ -0,0 +1,712 @@
+# 어댑터 배럴 공개 경계 확립 Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** 어댑터 16개 그룹 전부에 `index.ts` 공개 경계를 세우고, 그룹 바깥은 배럴만 import하도록 게이트로 강제한다.
+
+**Architecture:** 각 어댑터 그룹의 `index.ts`가 그 그룹의 공개 표면이 된다. 그룹 내부 파일끼리, 그리고 어댑터→커널(`platform/**`) 간선은 지금처럼 파일 직접 import를 유지한다 — 커널의 정체성은 파일이고 `check:adapter-inventory`가 그것을 파일 경로로 검증하기 때문이다. `.dependency-cruiser.json`에 규칙 하나를 추가하고 회귀 fixture로 그 거부를 고정한다.
+
+**Tech Stack:** TypeScript (NodeNext/Bundler), dependency-cruiser, 자체 TypeScript 인지 import 그래프(`scripts/check-architecture.ts`), Vite, Vitest
+
+**Spec:** [`docs/superpowers/specs/2026-09-16-adapter-barrel-boundary-design.md`](../specs/2026-09-16-adapter-barrel-boundary-design.md)
+
+## Global Constraints
+
+- 기준선(2026-09-16, `develop` `5434760`): `check:architecture` PASS(297 모듈 / 897 의존 / 미해결 0), `check:types:app` PASS, `check:adapter-inventory` PASS(120 파일). **이 셋을 깨면 안 된다.**
+- `docs/reviews/adapters/INVENTORY.md`는 `git ls-files src/adapters`와 **집합이 정확히 일치**해야 한다. 소스 파일을 추가/이동하면 같은 커밋에서 이 표와 하단 합계를 고친다.
+- 어댑터→커널 import는 **파일 직접 경로를 유지**한다. `scripts/check-adapter-inventory.ts:63-83`이 4개 소비자에게 `platform/abortable-operation.ts`로 해석되는 specifier를 정규식으로 요구한다.
+- `src/adapters/storage/index.ts`는 `indexeddb/`·`opfs/` 서브배럴을 **재수출하지 않는다.** `scripts/test-browser-file-storage-runtime-removal.ts:23-34`가 그 두 폴더만 삭제한 뒤 잔존 import를 예외로 잡는다.
+- `src/adapters/service-worker/index.ts`는 `service-worker-entry.ts`를 참조하지 않는다. `tsconfig.app.json:18`이 제외한 파일이다.
+- 번들 예산: `config/performance/budgets.json`의 `bundle.initialJsGzipBytes = 204800`.
+- 프로젝트 소스는 TypeScript/TSX만. `allowJs` 비활성. 로컬 import는 명시적 `.ts`/`.tsx` 확장자 필수.
+- 커밋 메시지 끝에 붙일 것:
+ `Co-Authored-By: Claude Opus 5 (1M context) `
+
+---
+
+### Task 1: 배럴 8개 생성 + INVENTORY 등록
+
+없는 8개 그룹에 `index.ts`를 만든다. 이 태스크는 **파일 추가만** 한다 — 기존 import는 건드리지 않으므로 런타임 동작이 바뀌지 않는다.
+
+**Files:**
+- Create: `src/adapters/auth/index.ts`
+- Create: `src/adapters/diagnostics/index.ts`
+- Create: `src/adapters/telemetry/index.ts`
+- Create: `src/adapters/platform/index.ts`
+- Create: `src/adapters/query-cache/index.ts`
+- Create: `src/adapters/service-worker/index.ts`
+- Create: `src/adapters/storage/index.ts`
+- Create: `src/adapters/http/index.ts`
+- Modify: `docs/reviews/adapters/INVENTORY.md` (행 8개 추가 + 합계)
+
+**Interfaces:**
+- Produces: 위 8개 배럴이 내보내는 심볼 82개. Task 2가 이 경로들로 import를 바꾼다. 심볼 존재는 spec §7에서 82/82 기계 대조 완료(누락 0, 오타 0).
+- Consumes: 없음 (첫 태스크)
+
+- [x] **Step 1: 배럴 5개 생성 (단일 파일 그룹 + query-cache)**
+
+`src/adapters/auth/index.ts`:
+```ts
+export {
+ createAnonymousSessionAdapter,
+ createDemoSessionAdapter,
+ createExternalAuthSessionAdapter,
+ createUnavailableSessionAdapter,
+ DEMO_AUTHORIZATION_MARKER,
+ type DemoSessionAdapter,
+ type ExternalSessionOwner,
+} from "./external-session-adapter.ts";
+```
+
+`src/adapters/diagnostics/index.ts`:
+```ts
+export {
+ createDiagnosticsAdapter,
+ getLastBootEvidence,
+ MAX_DIAGNOSTIC_ENTRIES,
+ noOpDiagnostics,
+ recordBootFailure,
+} from "./bounded-diagnostics.ts";
+```
+
+`src/adapters/telemetry/index.ts`:
+```ts
+export {
+ createTelemetryAdapter,
+ MAX_TELEMETRY_QUEUE,
+ noOpTelemetry,
+ type TelemetryAdapter,
+ type TelemetryAdapterOptions,
+} from "./best-effort-telemetry.ts";
+```
+
+`src/adapters/storage/index.ts`:
+```ts
+/**
+ * 최상위 storage 배럴은 Web Storage 어댑터만 내보낸다.
+ *
+ * `./indexeddb/index.ts`와 `./opfs/index.ts`를 여기서 재수출하지 말 것.
+ * `scripts/test-browser-file-storage-runtime-removal.ts:23-34`가 그 두 폴더만
+ * 삭제한 뒤 잔존 import를 예외로 잡는다 — 재수출하면 제거 드릴이 죽는다.
+ * 두 서브배럴이 각자 제거 가능한 런타임의 경계다.
+ */
+export {
+ createBrowserStorageAdapter,
+ type BrowserStorageDependencies,
+} from "./browser-storage-adapter.ts";
+```
+
+`src/adapters/query-cache/index.ts`:
+```ts
+export {
+ createConditionalValidatorStore,
+ type ConditionalValidatorBinding,
+ type ConditionalValidatorStore,
+} from "./conditional-validator-store.ts";
+export { createCursorPaginationRuntime } from "./cursor-pagination-runtime.ts";
+export {
+ createServerStateScopeRuntime,
+ type ScopeResetParticipant,
+ type ServerStateScopeDependencies,
+} from "./server-state-scope-runtime.ts";
+export {
+ createTanStackCacheCoordinator,
+ type TanStackCacheCoordinatorDependencies,
+} from "./tanstack-cache-coordinator.ts";
+export {
+ createQueryCacheAdapter,
+ createQueryClient,
+ QUERY_CACHE_DEFAULTS,
+ type QueryCacheDependencies,
+} from "./tanstack-query-cache.ts";
+```
+
+- [x] **Step 2: 배럴 3개 생성 (주석이 계약인 것들)**
+
+`src/adapters/platform/index.ts`:
+```ts
+/**
+ * 어댑터 커널의 공개 경계.
+ *
+ * `src/adapters/**` 안에서는 이 배럴을 쓰지 않는다. 커널 프리미티브는 파일
+ * 경로로 직접 import한다 — `scripts/check-adapter-inventory.ts:63-83`이
+ * `platform/abortable-operation.ts`로 해석되는 specifier를 네 소비자에게
+ * 요구하고, `.dependency-cruiser.json`의 kernel carve-out도 폴더 단위다.
+ * 이 배럴은 bootstrap·features·tests 같은 그룹 바깥 소비자를 위한 문이다.
+ */
+export {
+ compensateLateHandle,
+ createAbortableOperation,
+ snapshotAbortTimers,
+ type AbortableOperation,
+ type AbortableOperationInput,
+ type AbortRace,
+ type AbortTerminalReason,
+ type AbortTimerSnapshot,
+} from "./abortable-operation.ts";
+export { assertBoundedCapacity } from "./bounded-capacity.ts";
+export {
+ createBrowserLifecycleRuntime,
+ type BrowserLifecycleEvent,
+ type BrowserLifecycleRuntime,
+ type BrowserLifecycleSnapshot,
+} from "./browser-lifecycle.ts";
+export {
+ createBrowserMutationIntentFactory,
+ type BrowserMutationIntentFactoryDependencies,
+} from "./browser-mutation-intent-factory.ts";
+export { systemClock } from "./system-clock.ts";
+```
+
+`src/adapters/service-worker/index.ts`:
+```ts
+/**
+ * `service-worker-entry.ts`는 여기서 참조하지 않는다. `tsconfig.app.json:18`이
+ * 제외한 파일이라 참조하면 app 타입체크가 제외 대상을 끌어들인다. 그 파일은
+ * export가 0개이므로 넣을 것도 없다.
+ */
+export {
+ createServiceWorkerRuntime,
+ type WorkerClientLike,
+ type WorkerRuntimeConfig,
+ type WorkerScopeLike,
+} from "./service-worker-lifecycle.ts";
+export {
+ createServiceWorkerPageController,
+ type ActivationBlocker,
+ type PageControllerDependencies,
+} from "./service-worker-page-controller.ts";
+export {
+ createNonceRegistry,
+ createServiceWorkerMessage,
+ parseServiceWorkerMessage,
+ type ParsedMessage,
+} from "./service-worker-protocol.ts";
+```
+
+`src/adapters/http/index.ts`:
+```ts
+/**
+ * §7–§8. 권장 경로는 V3 계약 실행기(`createContractHttpExecutor`)다. 설치된
+ * 계약과 타입 입력을 받아 상한·전체 데드라인·재시도 권한·효과 확실성 판정을
+ * 런타임이 소유한다.
+ */
+export {
+ createContractHttpExecutor,
+ type AuthIntegrationFailureReason,
+ type AuthOperationContext,
+ type CancellationOwner,
+ type ContractHttpExecutor,
+ type ContractHttpExecutorDependencies,
+ type HttpContractViolation,
+ type HttpContractViolationKind,
+ type HttpEffectCertainty,
+ type HttpExecutionContext,
+ type HttpExecutionObservation,
+ type HttpExecutionOutcome,
+ type HttpTransportFailure,
+ type SafeResponseMetadata,
+} from "./http-execution-v3.ts";
+/** V3 `attachCredentials` 콜백이 반환해야 하는 결과 타입. */
+export type { CredentialPatchOutcome } from "./http-contract-bridge.ts";
+/**
+ * V2 legacy. operationId + `LegacyHttpInput`으로 호출하는 범용 클라이언트다.
+ * 새 코드는 위의 V3 실행기를 쓴다. 남아 있는 이유는 계약이 아직 없는
+ * 오퍼레이션을 위한 이행 경로이기 때문이다.
+ */
+export {
+ createHttpClient,
+ type HttpClient,
+ type HttpClientDependencies,
+ type HttpFailure,
+ type HttpResult,
+ type LegacyHttpInput,
+ type Scheduler,
+} from "./client.ts";
+/** V2 `HttpClient.execute`의 첫 인자 타입. */
+export type { OperationRequestInput } from "./request-builder.ts";
+```
+
+- [x] **Step 3: 타입체크로 심볼 존재를 검증한다**
+
+Run: `corepack pnpm check:types:app`
+Expected: PASS. 실패하면 존재하지 않는 심볼을 재수출한 것이다 — 에러가 지목한 이름을 해당 소스 파일에서 확인하고 배럴에서 빼라. spec §7의 대조표와 대조할 것.
+
+- [x] **Step 4: 게이트가 새 파일 8개를 거부하는 것을 확인한다 (의도된 실패)**
+
+Run: `git add -A && corepack pnpm check:adapter-inventory`
+Expected: **FAIL.** `git ls-files src/adapters`가 128개를 보고하는데 INVENTORY.md는 120행이므로 불일치를 보고한다. 이 실패를 본 뒤 Step 5로 간다. (실패하지 않으면 `git add`가 안 된 것이다.)
+
+- [x] **Step 5: INVENTORY.md에 행 8개 추가**
+
+`docs/reviews/adapters/INVENTORY.md`의 표에 경로 알파벳 순서 위치로 끼워 넣고 번호를 다시 매긴다. 상세 리뷰 링크는 같은 그룹의 기존 행과 동일하게 쓴다.
+
+| 추가할 경로 | 상세 리뷰 링크 |
+|---|---|
+| `src/adapters/auth/index.ts` | `[Network/state](./01-network-and-state.md)` |
+| `src/adapters/diagnostics/index.ts` | `[Network/state](./01-network-and-state.md)` |
+| `src/adapters/http/index.ts` | `[Network/state](./01-network-and-state.md)` |
+| `src/adapters/platform/index.ts` | `[Network/state](./01-network-and-state.md)` |
+| `src/adapters/query-cache/index.ts` | `[Network/state](./01-network-and-state.md)` |
+| `src/adapters/service-worker/index.ts` | `[Worker/push](./05-service-worker-and-web-push.md)` |
+| `src/adapters/storage/index.ts` | `[Storage/files](./03-storage-and-browser-files.md)` |
+| `src/adapters/telemetry/index.ts` | `[Network/state](./01-network-and-state.md)` |
+
+그리고 `docs/reviews/adapters/INVENTORY.md:132`의 `합계: **120/120**` → `합계: **128/128**`.
+
+- [x] **Step 6: 게이트 3종 통과 확인**
+
+Run: `corepack pnpm check:adapter-inventory && corepack pnpm check:types:app && corepack pnpm check:architecture`
+Expected: 셋 다 PASS. `check:adapter-inventory`가 `128 files PASS`를 출력한다.
+
+- [x] **Step 7: 워커 realm 타입체크 — 실행 중 발견한 필수 단계**
+
+> 2026-09-16 실행 중 발견. 계획 초안에는 없었다.
+> `tsconfig.service-worker.json`은 `src/adapters/service-worker` 폴더를 통째로
+> WebWorker lib로 컴파일하면서 페이지 realm 파일 2개만 `exclude`로 뺀다.
+> 새 `index.ts`가 그 폴더 안에서 `service-worker-page-controller.ts`를
+> import하므로, 제외하지 않으면 페이지 realm 파일이 WebWorker lib 컴파일에
+> 끌려 들어와 `Cannot find name 'document'`로 실패한다.
+> (M6 리뷰의 "realm 경계가 폴더가 아니라 tsconfig exclude 2줄로만 표현된다"가
+> 그대로 발현된 것이다.)
+
+`tsconfig.service-worker.json`의 `exclude` 배열 맨 앞에 추가한다:
+
+```json
+ "src/adapters/service-worker/index.ts",
+```
+
+타입 커버리지는 `tsconfig.app.json`이 이 배럴을 포함하므로 유지된다. 워커 진입점
+`service-worker-entry.ts`는 배럴을 쓰지 않고 파일을 직접 import하므로 워커 번들에
+영향이 없다.
+
+Run: `corepack pnpm check:types:service-worker`
+Expected: PASS
+
+- [x] **Step 8: 제거 드릴이 살아 있는지 확인한다**
+
+`storage/index.ts`를 새로 만들었으므로 제거 드릴을 돌려 서브폴더 삭제가 여전히 성립하는지 본다.
+
+Run: `corepack pnpm test:browser-file-storage-removal`
+Expected: 드릴 출력에 `error TS`가 0건이어야 한다. `storage/index.ts`가 `indexeddb/`나 `opfs/`를 참조하면 `still imported`로 죽는다 — Step 1의 주석대로 재수출을 제거하라.
+
+> **이 환경의 알려진 제약.** `tests/unit/ci-artifact-contract.test.ts`의 16건은
+> `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`로 실패한다.
+> 샌드박스가 네트워크 네임스페이스를 못 만들기 때문이며 `develop` `5434760`
+> 기준선에서도 동일하게 16건 실패한다(2026-09-16 확인). 이 드릴은 내부적으로
+> `test:unit`을 돌리므로 그 16건 때문에 항상 exit 1이 된다.
+> **판정 기준은 드릴의 exit code가 아니라 `error TS` 0건과 `still imported` 부재다.**
+> CI 환경에서는 전체 PASS를 확인할 것.
+
+- [x] **Step 9: 커밋**
+
+```bash
+git add src/adapters/*/index.ts docs/reviews/adapters/INVENTORY.md tsconfig.service-worker.json
+git commit -m "$(cat <<'EOF'
+feat: give every adapter group a public barrel
+
+각 어댑터 그룹의 공개 표면을 index.ts로 선언한다. 소비자는 아직 바꾸지
+않았으므로 런타임 동작은 그대로다. storage 배럴은 서브배럴을 재수출하지
+않는다 — 제거 드릴이 indexeddb/와 opfs/만 삭제하기 때문이다.
+
+Co-Authored-By: Claude Opus 5 (1M context)
+EOF
+)"
+```
+
+---
+
+### Task 2: 그룹 바깥 소비자 15줄을 배럴 경로로 치환
+
+**Files:**
+- Modify: `src/bootstrap/runtime-adapters.ts:6-29` (12줄, 블록 병합 포함)
+- Modify: `src/bootstrap/main.tsx:3`
+- Modify: `src/bootstrap/optional-runtime-host.ts:4`
+- Modify: `src/bootstrap/register-service-worker.ts:5`
+- Modify: `src/features/reference-feature/adapters/create-reference-feature-input.ts:9`
+- Modify: `.storybook/preview.tsx:5-6` (게이트 범위 밖, 일관성 목적)
+
+**Interfaces:**
+- Consumes: Task 1이 만든 8개 배럴의 심볼 82개
+- Produces: `src/` 안에 어댑터 내부 파일을 직접 겨누는 import 0건. Task 3의 게이트 규칙이 이 상태를 전제로 통과한다.
+
+- [x] **Step 1: 치환 전 위반 건수를 기록한다**
+
+Run:
+```bash
+grep -rn 'from "[^"]*adapters/[^"]*"' src/ | grep -v '^src/adapters/' | grep -v 'index\.ts"' | wc -l
+```
+Expected: `15`. 이 숫자가 Step 4에서 `0`이 되어야 한다.
+
+- [x] **Step 2: `runtime-adapters.ts`의 import 블록을 다시 쓴다**
+
+`src/bootstrap/runtime-adapters.ts`의 `:6`~`:29` 구간이 한 덩어리다. 아래에서 위로 편집하거나 블록 전체를 한 번에 교체한다 — 위에서부터 고치면 줄 번호가 밀린다.
+
+치환 내용:
+
+| 현재 specifier | 바뀔 specifier |
+|---|---|
+| `../adapters/auth/external-session-adapter.ts` | `../adapters/auth/index.ts` |
+| `../adapters/diagnostics/bounded-diagnostics.ts` | `../adapters/diagnostics/index.ts` |
+| `../adapters/http/client.ts` | `../adapters/http/index.ts` |
+| `../adapters/http/http-execution-v3.ts` | `../adapters/http/index.ts` (위와 **한 블록으로 병합**) |
+| `../adapters/query-cache/tanstack-cache-coordinator.ts` | `../adapters/query-cache/index.ts` |
+| `../adapters/query-cache/tanstack-query-cache.ts` | `../adapters/query-cache/index.ts` |
+| `../adapters/query-cache/server-state-scope-runtime.ts` | `../adapters/query-cache/index.ts` |
+| `../adapters/query-cache/conditional-validator-store.ts` | `../adapters/query-cache/index.ts` (위 넷을 **한 블록으로 병합**) |
+| `../adapters/storage/browser-storage-adapter.ts` | `../adapters/storage/index.ts` |
+| `../adapters/platform/browser-mutation-intent-factory.ts` | `../adapters/platform/index.ts` |
+| `../adapters/telemetry/best-effort-telemetry.ts` | `../adapters/telemetry/index.ts` |
+
+`../adapters/cross-context-invalidation/index.ts` 2줄은 이미 배럴이므로 **건드리지 않는다.**
+
+- [x] **Step 3: 나머지 4개 파일을 치환한다**
+
+| 파일:줄 | 현재 | 바뀔 것 |
+|---|---|---|
+| `src/bootstrap/main.tsx:3` | `../adapters/diagnostics/bounded-diagnostics.ts` | `../adapters/diagnostics/index.ts` |
+| `src/bootstrap/optional-runtime-host.ts:4` | `../adapters/platform/browser-lifecycle.ts` | `../adapters/platform/index.ts` |
+| `src/bootstrap/register-service-worker.ts:5` | `../adapters/service-worker/service-worker-page-controller.ts` | `../adapters/service-worker/index.ts` |
+| `src/features/reference-feature/adapters/create-reference-feature-input.ts:9` | `../../../adapters/http/http-execution-v3.ts` | `../../../adapters/http/index.ts` |
+| `.storybook/preview.tsx:5` | `../src/adapters/auth/external-session-adapter.ts` | `../src/adapters/auth/index.ts` |
+| `.storybook/preview.tsx:6` | `../src/adapters/query-cache/tanstack-query-cache.ts` | `../src/adapters/query-cache/index.ts` |
+
+- [x] **Step 4: 위반이 0이 된 것을 확인한다**
+
+Run:
+```bash
+grep -rn 'from "[^"]*adapters/[^"]*"' src/ | grep -v '^src/adapters/' | grep -v 'index\.ts"' | wc -l
+```
+Expected: `0`
+
+- [x] **Step 5: 타입·린트·아키텍처 게이트**
+
+Run: `corepack pnpm check:types:app && corepack pnpm lint && corepack pnpm check:architecture`
+Expected: 셋 다 PASS.
+
+- [x] **Step 6: 번들 예산을 확인한다 — 이 태스크의 최대 위험**
+
+배럴 재수출이 트리셰이킹을 무력화하면 초기 청크가 커진다. `package.json`에 `sideEffects` 선언이 없어 번들러가 모든 모듈을 부작용 있는 것으로 본다.
+
+Run: `corepack pnpm check:bundle`
+Expected: PASS (`bundle.initialJsGzipBytes` 상한 204800).
+
+**FAIL한 경우 순서대로 시도한다:**
+1. `package.json`에 `"sideEffects": false`를 추가한다. 추가 전에 `src/adapters` 아래 최상위 부작용이 있는지 확인하고, CSS import가 있으면 `"sideEffects": ["*.css"]` 형태로 보존한다.
+2. 그래도 넘치면 `src/adapters/service-worker/index.ts`에서 `service-worker-lifecycle.ts` 블록을 빼고, 워커 realm은 파일 직접 import를 유지한다. 그리고 Task 3의 게이트 규칙 `from.pathNot`에 워커 진입점을 추가한다. (근거: realm이 다르면 문도 다르다 — `platform`과 같은 논리.)
+3. 1·2로 안 되면 이 태스크를 중단하고 보고한다. 예산 초과를 안고 진행하지 않는다.
+
+- [x] **Step 7: 단위·통합 테스트**
+
+Run: `corepack pnpm test:unit && corepack pnpm test:integration`
+Expected: PASS. 이 태스크는 import 경로만 바꿨으므로 테스트 결과가 달라질 이유가 없다. 깨지면 배럴이 내보내는 심볼이 원본과 다른 것이다.
+
+- [x] **Step 8: 커밋**
+
+```bash
+git add src/bootstrap src/features .storybook
+git commit -m "$(cat <<'EOF'
+refactor: reach adapter groups through their barrel
+
+bootstrap과 feature 어댑터가 어댑터 내부 파일을 직접 겨누던 15곳을 그룹
+배럴로 바꾼다. 커널(platform/**) 간선과 그룹 내부 import는 파일 경로를
+유지한다 — check:adapter-inventory가 그 경로를 직접 검증한다.
+
+Co-Authored-By: Claude Opus 5 (1M context)
+EOF
+)"
+```
+
+---
+
+### Task 3: 게이트 규칙 + 회귀 fixture
+
+규칙만 추가하면 다음 사람이 규칙을 지워도 아무도 모른다. 이 레포는 거부 규칙마다 회귀 fixture를 두는 방식(`docs/architecture/layers.md`)이므로 fixture까지 같이 넣는다.
+
+**Files:**
+- Modify: `.dependency-cruiser.json` (`:193`과 `:194` 사이에 규칙 1개)
+- Create: `tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-deep.ts`
+- Create: `tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-barrel.ts`
+- Create: `tests/fixtures/architecture/dependency-graph/barrel/adapters/http/client.ts`
+- Create: `tests/fixtures/architecture/dependency-graph/barrel/adapters/http/index.ts`
+- Modify: `scripts/check-architecture.ts` (`runGraphFixtureChecks`에 그래프 1개 + assertion 2개)
+
+**Interfaces:**
+- Consumes: Task 2가 만든 "위반 0건" 상태. 위반이 남아 있으면 이 규칙 추가가 곧바로 게이트를 깬다.
+- Produces: `adapter-groups-are-reached-through-their-barrel` 규칙과 그 회귀 fixture 2종
+
+- [x] **Step 1: fixture 트리를 만든다 (규칙보다 먼저 — 실패를 먼저 본다)**
+
+`tests/fixtures/architecture/dependency-graph/barrel/adapters/http/client.ts`:
+```ts
+export function createFixtureHttpClient(): string {
+ return "fixture";
+}
+```
+
+`tests/fixtures/architecture/dependency-graph/barrel/adapters/http/index.ts`:
+```ts
+export { createFixtureHttpClient } from "./client.ts";
+```
+
+`tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-deep.ts` — 규칙이 **잡아야 할** 형태:
+```ts
+import { createFixtureHttpClient } from "../adapters/http/client.ts";
+
+export const deepComposition = createFixtureHttpClient;
+```
+
+`tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-barrel.ts` — 규칙이 **통과시켜야 할** 형태:
+```ts
+import { createFixtureHttpClient } from "../adapters/http/index.ts";
+
+export const barrelComposition = createFixtureHttpClient;
+```
+
+> fixture는 `analyzeSourceGraph(dir, "src")`로 분석되어 경로가 `src/...`로 보고된다(`scripts/check-architecture.ts:821-833`). 그래서 `^src/`로 시작하는 규칙이 fixture 트리에 그대로 적용된다.
+
+- [x] **Step 2: `.dependency-cruiser.json`에 규칙을 추가한다**
+
+`forbidden` 배열의 `adapters-do-not-know-other-concrete-adapters` **바로 다음**, `no-circular-dependencies` **앞**에 넣는다.
+
+```json
+ {
+ "name": "adapter-groups-are-reached-through-their-barrel",
+ "comment": "어댑터 그룹의 공개 표면은 그 그룹의 index.ts다. 그룹 바깥(bootstrap, features, presentation)은 배럴만 import한다. 배럴이 없던 시절 bootstrap은 어댑터 내부 파일 15곳을 직접 겨눴고, 그래서 어떤 파일이 공개이고 어떤 파일이 내부 헬퍼인지 아무 데도 적혀 있지 않았다. 출발점에서 src/adapters를 뺀 이유는 어댑터끼리의 간선은 바로 위 adapters-do-not-know-other-concrete-adapters가 이미 담당하고, 커널(platform/**)은 파일 단위로 공유되기 때문이다 — scripts/check-adapter-inventory.ts가 네 소비자에게 platform/abortable-operation.ts로 해석되는 specifier를 직접 요구한다. 도착점에서 1단계 중첩 index.ts를 허용한 이유는 storage/indexeddb와 storage/opfs가 각자 독립적으로 제거 가능한 런타임이고(scripts/test-browser-file-storage-runtime-removal.ts), 그래서 각자의 배럴이 곧 경계이기 때문이다.",
+ "severity": "error",
+ "from": {
+ "path": "^src/",
+ "pathNot": "^src/adapters/"
+ },
+ "to": {
+ "path": "^src/adapters/[^/]+/",
+ "pathNot": "^src/adapters/[^/]+/(?:[^/]+/)?index\\.ts$"
+ }
+ },
+```
+
+> 규칙 형태 적합성: `scripts/check-architecture.ts:799-815`의 `validateArchitectureRules`는 `from`에 `path`/`pathNot`, `to`에 `path`/`pathNot`/`circular`만 허용한다. 정규식은 `new RegExp(pattern, "u")`로 평가되므로 비캡처 그룹 `(?:...)`이 허용된다. `$1` 역참조는 쓰지 않았다.
+
+- [x] **Step 3: 규칙이 실제 소스에서 위반 0인지 확인한다**
+
+Run: `corepack pnpm check:architecture`
+Expected: PASS. FAIL하면 Task 2에서 놓친 import가 있다는 뜻이다 — 출력이 지목한 파일을 배럴 경로로 고쳐라.
+
+- [x] **Step 4: fixture 검사를 `check-architecture.ts`에 배선한다**
+
+`runGraphFixtureChecks()`의 `Promise.all` 블록(`scripts/check-architecture.ts:826-833`)에 `barrelGraph`를 추가한다:
+
+```ts
+ const [allowedGraph, unresolvedGraph, layerGraph, cycleGraph, barrelGraph] =
+ await Promise.all([
+ analyzeSourceGraph(allowedRoot, "src"),
+ analyzeSourceGraph(resolve(fixtureRoot, "unresolved"), "src"),
+ analyzeSourceGraph(resolve(fixtureRoot, "layer"), "src"),
+ analyzeSourceGraph(resolve(fixtureRoot, "cycle"), "src"),
+ analyzeSourceGraph(resolve(fixtureRoot, "barrel"), "src"),
+ ]);
+```
+
+그리고 `assertions` 배열에 두 항목을 추가한다:
+
+```ts
+ {
+ name: "deep adapter import from outside the group is rejected",
+ passed: blockingViolations(barrelGraph).some(
+ ({ rule, source, target }) =>
+ rule === "adapter-groups-are-reached-through-their-barrel" &&
+ source === "src/bootstrap/compose-deep.ts" &&
+ target === "src/adapters/http/client.ts",
+ ),
+ },
+ {
+ name: "barrel import from outside the group is accepted",
+ passed: !blockingViolations(barrelGraph).some(
+ ({ source }) => source === "src/bootstrap/compose-barrel.ts",
+ ),
+ },
+```
+
+> 필드명 근거: `ArchitectureViolation`은 `rule` / `severity` / `source` / `target`을 갖는다 (`scripts/check-architecture.ts:35`, 생성부 `:734-739`). `from`/`to`가 아니다.
+
+- [x] **Step 5: fixture 회귀 검사가 통과하는지 확인한다**
+
+Run: `corepack pnpm check:architecture`
+Expected: `Architecture graph fixtures: 14 regression checks PASS` (기존 12 + 신규 2). 그리고 전체 PASS.
+
+- [x] **Step 6: fixture가 실제로 무언가를 잡는지 역검증한다**
+
+규칙을 잠시 무력화해서 fixture가 FAIL하는지 본다. fixture가 항상 통과하면 회귀 검사가 아니다.
+
+```bash
+# 규칙 이름을 일시적으로 바꿔 매칭되지 않게 한다
+sed -i 's/"adapter-groups-are-reached-through-their-barrel"/"temporarily-disabled-barrel-rule"/' .dependency-cruiser.json
+corepack pnpm check:architecture; echo "EXIT=$?"
+# 되돌린다
+sed -i 's/"temporarily-disabled-barrel-rule"/"adapter-groups-are-reached-through-their-barrel"/' .dependency-cruiser.json
+corepack pnpm check:architecture; echo "EXIT=$?"
+```
+Expected: 첫 번째 EXIT는 0이 아니어야 하고(assertion 실패), 되돌린 뒤 EXIT는 0이어야 한다.
+
+- [x] **Step 7: 커밋**
+
+```bash
+git add .dependency-cruiser.json scripts/check-architecture.ts tests/fixtures/architecture/dependency-graph/barrel
+git commit -m "$(cat <<'EOF'
+feat: enforce the adapter barrel boundary in the architecture gate
+
+그룹 바깥에서 어댑터 내부 파일을 직접 import하면 check:architecture가
+거부한다. 회귀 fixture 2개가 거부와 허용을 각각 고정한다 — 규칙을 지우면
+fixture 검사가 먼저 깨진다.
+
+Co-Authored-By: Claude Opus 5 (1M context)
+EOF
+)"
+```
+
+---
+
+### Task 4: 규칙을 문서에 명문화
+
+코드로 강제되는 규칙이 문서에 없으면 다음 사람은 게이트 에러를 보고서야 규칙을 알게 된다.
+
+**Files:**
+- Modify: `docs/architecture/layers.md` (배럴 경계 절 추가)
+- Modify: `docs/reviews/adapters/README.md` (테스트 이관 규칙)
+
+**Interfaces:**
+- Consumes: Task 3의 규칙 이름 `adapter-groups-are-reached-through-their-barrel`
+- Produces: 없음 (문서만)
+
+- [x] **Step 1: `layers.md`에 배럴 경계 절을 추가한다**
+
+"The adapter kernel" 절 **다음에** 아래를 넣는다:
+
+```markdown
+## 어댑터 그룹의 공개 경계
+
+각 어댑터 그룹의 공개 표면은 그 그룹의 `index.ts`다. 그룹 바깥
+(`bootstrap`, `features`, `presentation`)은 배럴만 import한다.
+`adapter-groups-are-reached-through-their-barrel` 규칙이 이를 강제하고,
+`tests/fixtures/architecture/dependency-graph/barrel`이 거부와 허용을
+각각 고정한다.
+
+두 가지 예외가 있고 둘 다 의도된 것이다.
+
+- **그룹 내부 파일끼리**는 파일 경로로 직접 import한다. 배럴은 바깥을 위한
+ 문이지 내부 규율이 아니다.
+- **어댑터 → 커널(`platform/**`)** 간선도 파일 경로를 유지한다. 커널은
+ 런타임 합성물이 아니라 프리미티브이고, `check:adapter-inventory`가 네
+ 소비자에게 `platform/abortable-operation.ts`로 해석되는 specifier를
+ 직접 요구한다. 커널 배럴(`platform/index.ts`)은 bootstrap과 테스트를
+ 위한 것이다.
+
+`storage`는 최상위 배럴이 `indexeddb/`·`opfs/` 서브배럴을 재수출하지
+않는다. 두 런타임이 각자 독립적으로 제거 가능하고
+(`test:browser-file-storage-removal`), 그래서 각 서브배럴이 곧 경계다.
+규칙의 도착점 정규식이 1단계 중첩 `index.ts`를 배럴로 인정하는 이유가
+이것이다.
+```
+
+- [x] **Step 2: 테스트 이관 규칙을 적는다**
+
+`docs/reviews/adapters/README.md` 끝에 추가:
+
+```markdown
+## 테스트의 어댑터 import
+
+`tests/` 아래 어댑터 import는 배럴로 일괄 이관하지 않는다. `check:architecture`는
+`src`만 스캔하므로 강제되지 않고, 단위 테스트의 상당수가 배럴에 없는 내부
+심볼을 의도적으로 겨눈다.
+
+어떤 테스트 파일을 **다른 이유로** 수정하거나 분할할 때, 그 파일이 쓰는
+심볼이 해당 그룹 배럴에 있으면 그 파일 안에서만 배럴 경로로 바꾼다.
+배럴에 없는 심볼이면 깊은 경로를 유지한다. 배럴에 추가하고 싶으면 그 심볼이
+공개 표면임을 먼저 논증한다 — 테스트 편의로 배럴을 키우면 배럴이 경계가
+아니라 재수출 덤프가 된다.
+```
+
+- [x] **Step 3: 문서 게이트 확인**
+
+Run: `corepack pnpm lint && corepack pnpm check:architecture`
+Expected: PASS. (문서 링크 검증이 있으면 `corepack pnpm verify:documentation`도 돌린다.)
+
+- [x] **Step 4: 커밋**
+
+```bash
+git add docs/architecture/layers.md docs/reviews/adapters/README.md
+git commit -m "$(cat <<'EOF'
+docs: write down the adapter barrel boundary and its two exceptions
+
+Co-Authored-By: Claude Opus 5 (1M context)
+EOF
+)"
+```
+
+---
+
+## 완료 판정
+
+네 태스크가 끝나면 아래가 전부 PASS여야 한다.
+
+```bash
+corepack pnpm check:types
+corepack pnpm lint
+corepack pnpm check:architecture
+corepack pnpm check:adapter-inventory
+corepack pnpm check:bundle
+corepack pnpm test:unit
+corepack pnpm test:integration
+corepack pnpm test:browser-file-storage-removal
+corepack pnpm test:realtime-removal
+```
+
+그리고 아래가 `0`이어야 한다.
+```bash
+grep -rn 'from "[^"]*adapters/[^"]*"' src/ | grep -v '^src/adapters/' | grep -v 'index\.ts"' | wc -l
+```
+
+## 이 계획이 하지 않는 것
+
+- `tests/` 166줄의 배럴 이관 — Task 4 Step 2의 규칙대로 파일을 손댈 때만 한다.
+- 대형 파일 분할 — 별도 계획. 이 계획이 그 선행조건이다.
+- spec §6이 남긴 부수 발견 4건(`telemetry:49`의 잉여 재수출, `browser-files/index.ts`의 포트 재수출, `opfs/index.ts` 누락 심볼 3개, `.dependency-cruiser.json:141`의 존재하지 않는 `web-worker` 경로) — 각각 별도 티켓.
+
+---
+
+## 실행 기록 (2026-09-16 완료)
+
+네 태스크 전부 실행했다. 커밋 5개: `a42d961` (spec·plan), `b29a471` (배럴 8개),
+`1606d9b` (소비자 15줄), `27ab17d` (게이트 규칙 + fixture), `eb40bc9` (문서).
+
+**계획과 달랐던 것 2건.**
+
+1. **워커 realm 타입체크 실패** — 계획 초안에 없던 Task 1 Step 7이 여기서 나왔다.
+ `service-worker/index.ts`가 `tsconfig.service-worker.json`의 WebWorker lib
+ 컴파일에 페이지 realm 파일을 끌어들여 `Cannot find name 'document'`로 실패했다.
+ 배럴을 그 tsconfig의 `exclude`에 추가해 해결.
+2. **spec의 정규식이 게이트에 거부당함** — spec §5.1이 제시한
+ `^src/adapters/[^/]+/(?:[^/]+/)?index\.ts$`를 dependency-cruiser가
+ "unsafe regular expression"으로 거부했다(`(?:[^/]+/)?` 안의 `+`가 star height 2).
+ 중첩 없는 교대로 바꿔 통과시켰다:
+ `^src/adapters/[^/]+/index\.ts$|^src/adapters/[^/]+/[^/]+/index\.ts$`
+ spec은 이 규칙을 실제로 실행해 본 적이 없었다.
+
+**측정 결과.**
+
+- 번들 영향 **0바이트**: 배럴 도입 전후 모두 초기 JS 181114 / 204800 gzip bytes.
+ `sideEffects` 선언이 없는데도 Rollup이 재수출을 트리셰이킹했다. 계획이 지목한
+ 최대 위험은 현실화되지 않았고 대응 3단계는 쓰지 않았다.
+- import 그래프: 297 모듈 / 897 의존 → 305 모듈 / 914 의존 (배럴 8개 + fixture 4개).
+- 회귀 검사: 12 → 14. 규칙 이름을 바꿔 fixture가 실제로 깨지는 것을 확인했다.
+- 배럴 미경유 import: `src/` 15건 → **0건**.
+
+**PASS:** `check:types` `lint` `check:architecture` `check:adapter-inventory`
+`check:bundle` `test:integration`(81) `test:component`(130) `verify:documentation`
+
+**이 환경에서 판정 불가:** `test:unit`, `test:browser-file-storage-removal`,
+`test:realtime-removal`. 셋 다 `tests/unit/ci-artifact-contract.test.ts`의 16건이
+`bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`로 실패해 exit 1이
+된다. `develop` `5434760` 기준선에서도 동일하게 16건 실패함을 stash 후 실행해
+확인했다. 어댑터 관련 테스트는 전부 통과했고(`test:unit` 1796 passed), 제거 드릴의
+`error TS`는 0건이다. **CI 환경에서 이 셋의 전체 PASS를 확인해야 한다.**
diff --git a/docs/superpowers/plans/2026-09-16-indexeddb-kernel-promotion.md b/docs/superpowers/plans/2026-09-16-indexeddb-kernel-promotion.md
new file mode 100644
index 0000000..dbdd736
--- /dev/null
+++ b/docs/superpowers/plans/2026-09-16-indexeddb-kernel-promotion.md
@@ -0,0 +1,464 @@
+# IndexedDB 커널 승격 Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** 어댑터 4곳이 각자 구현한 IndexedDB 연결·트랜잭션 메커니즘을 `src/adapters/platform/`의 커널 2파일로 모으고, 4벌이 서로 다른 답을 내던 지점을 하나로 만든다.
+
+**Architecture:** 커널은 **메커니즘만** 갖는다 — open 요청을 Promise로 바꾸기, blocked 데드라인, upgrade/error/success 라우팅, 늦게 도착한 연결 닫기, 트랜잭션 상태기계, 커서 펌프. 데이터베이스 이름·스키마·마이그레이션·governance·**실패 분류(taxonomy)**는 각 서브시스템에 남는다. 실패 매핑은 `translate` 콜백으로 주입하므로 `mapIndexedDbException`과 `mapBrowserDataException`이 서로 다른 답을 내는 현 상태가 보존된다.
+
+**Tech Stack:** TypeScript, IndexedDB, Vitest, `tests/helpers/memory-indexeddb.ts`(가짜 IDB)
+
+**Spec:** [`docs/superpowers/specs/2026-09-16-indexeddb-kernel-promotion-design.md`](../specs/2026-09-16-indexeddb-kernel-promotion-design.md)
+
+## Global Constraints
+
+- **`src/adapters/platform/`은 이미 dependency-cruiser의 kernel carve-out이다.** 커널에 파일을 추가하는 데 규칙 변경이 필요 없다(spec §5.3).
+- **`IDBFactory`는 필수 주입 파라미터다.** `globalThis.indexedDB`를 읽으면 안 된다 — `eslint.config.ts:40-63`이 모든 브라우저 루트에서 그 속성을 막고, 예외는 `platform/browser-lifecycle.ts` **한 파일**에만 부여돼 있다. 주입받으면 `eslint.config.ts`를 건드릴 필요가 없다(spec §5.1).
+- **소스 파일을 추가하면 `docs/reviews/adapters/INVENTORY.md`에 행을 추가하고 하단 합계를 고친다.** `check:adapter-inventory`가 `git ls-files src/adapters`와 집합을 정확히 대조한다.
+- **`check:adapter-inventory`에 abort 래칫이 있다.** `addEventListener("abort")`를 쓰는 어댑터 파일이 24개를 넘으면 실패한다. `platform/`은 세지 않는다.
+- **실패 매핑 4벌을 통일하지 마라.** `mapIndexedDbException`(RT/MT/OP)과 `mapBrowserDataException`(CP)은 같은 에러에 다른 답을 낸다 — `ConstraintError` recovery가 NONE vs REOPEN, `QuotaExceeded` retryable이 false vs true, `NotFound`가 MIGRATION_FAILED vs NOT_FOUND. 통일은 별건이고 이 계획의 범위가 아니다.
+- **`deleteDatabase`를 나머지 3벌에 추가하지 마라.** CP에만 있는 것이 의도다(spec §2.3).
+- **이 환경의 알려진 제약:** `tests/unit/ci-artifact-contract.test.ts` 16건이 `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`로 실패한다. `develop` `5434760` 기준선에서도 동일하다. **판정 기준은 그 파일 외의 실패가 0인지**다.
+- 커밋 메시지 끝에 붙일 것: `Co-Authored-By: Claude Opus 5 (1M context) `
+
+## 왜 이 작업을 하는가 — LOC로 정당화하지 않는다
+
+> **2026-09-16 갱신 — 사양의 추정이 빗나갔다.** 커널을 실제로 구현하니
+> 2파일 **1,132줄**(코드 751줄)이다. 사양 추정 470줄의 2.4배다. 사양 §3.1이
+> "470 LOC라 2분할한다"고 쓴 논거도 사실이 아니었다(2분할 자체는 테스트 셋업이
+> 갈린다는 별도 근거로 유지). 그래서 아래 표의 순증감이 뒤집힌다.
+
+| | 사양 추정 | 실제 |
+|---|---:|---:|
+| 4벌에서 삭제 | ~974 | (미측정, 이행 후 확정) |
+| 4벌에 추가 (커널 호출부·콜백) | ~281 | (미측정) |
+| 4벌 순감 | −693 | (미측정) |
+| 커널 신규 2파일 | +470 | **+1,132** |
+| 신규 커널 테스트 2파일 | (미기재) | **+1,602** |
+| **레포 순증감 (소스만)** | **−223** | **약 +439** |
+
+**이 리팩토링은 줄 수를 줄이지 않는다. 늘린다.** 소스 약 +439줄, 테스트까지 하면
+약 +2,041줄이다. 사양은 "절감이 작다"고 썼지만 실제로는 절감이 아니라 증가다.
+
+**그래서 이 작업의 근거는 오로지 하나다: 트랜잭션 상태기계가 4개에서 1개가 되는 것.**
+줄 수로 정당화하려는 시도는 이제 불가능하다. 근거가 성립하는 이유는 오늘 그 4개가
+이미 서로 다른 답을 내고 있기 때문이다:
+
+| 상황 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| 트랜잭션 안 개별 요청 실패 | 본다 | 기록만 | **안 본다** | 즉시 abort |
+| 값 없이 완료 | UNAVAILABLE | UNAVAILABLE | UNAVAILABLE | **CORRUPT_DATA** |
+| `deleteDatabase` | 없음 | 없음 | 없음 | **있음** |
+
+리뷰가 "이미 갈라졌다"고 판정한 근거가 이 표다.
+
+**그리고 이행을 멈추면 최악이다.** 커널만 넣고 사본을 안 옮기면 +1,132줄의
+쓰이지 않는 코드가 남는다. 이 레포가 이미 `abortable-operation.ts`로 겪고 있는
+병(커널은 있는데 24개 파일이 안 씀)을 하나 더 만드는 것이다. 되돌리려면 지금이
+가장 싸다 — 커널 커밋 하나를 revert하면 끝이고 사본은 아직 안 건드렸다.
+
+---
+
+### Task 1: 커널 2파일 + 단위 테스트
+
+사본은 **손대지 않는다.** 코드 추가만 하므로 런타임 동작이 바뀌지 않는다.
+
+**Files:**
+- Create: `src/adapters/platform/indexeddb-connection.ts` (~240 LOC)
+- Create: `src/adapters/platform/indexeddb-transaction.ts` (~230 LOC)
+- Create: `tests/unit/indexeddb-connection.test.ts`
+- Create: `tests/unit/indexeddb-transaction.test.ts`
+- Modify: `docs/reviews/adapters/INVENTORY.md` (행 2개 + 합계 `128/128` → `130/130`)
+
+**Interfaces:**
+- Produces: spec §3.2·§3.3의 전체 export 시그니처. Task 2~5가 이것만 쓴다.
+- Consumes: 기존 커널 `snapshotAbortTimers`(`platform/abortable-operation.ts`), `contracts/result.ts`의 `Result`
+
+- [x] **Step 1: 기존 커널 관례를 읽는다**
+
+`src/adapters/platform/`의 5파일을 읽고 주석 스타일(왜 이 규칙이 있는지를 근거와 함께 적는 방식), 에러 처리, 의존성 주입 방식을 파악한다. 새 파일은 그 관례를 따른다.
+
+- [x] **Step 2: 가짜 IDB의 오류 배선을 확인한다**
+
+`tests/helpers/memory-indexeddb.ts`를 읽는다. 커널은 요청 레벨 `onerror`를 새로 보게 되므로 가짜가 `request.error`를 채우는지가 전제다.
+
+확인됨(2026-09-16): 채운다. `:167-170`이 `request.error = asException(error)` 후 `queueMicrotask`로 `onerror` 발화, `:309-311`이 같은 일을 **동기로** 한다. **두 경로의 타이밍이 다르므로** 테스트에서 주의한다.
+
+- [x] **Step 3: 실패하는 테스트를 먼저 쓴다**
+
+최소한 아래를 고정한다. 각각 먼저 실패하는 것을 확인한 뒤 구현한다.
+
+연결(`tests/unit/indexeddb-connection.test.ts`):
+- open 성공 / `onerror` / native throw
+- `onblocked` — deadline 미설정 시 `BLOCKED`, deadline 경과 시 `BLOCKED_DEADLINE`
+- upgrade `APPLIED`
+- upgrade `REJECTED` — **versionchange 트랜잭션이 abort되어 스키마가 커밋되지 않는 것까지** 확인
+- upgrade가 throw → `REJECTED` + `detail`에 thrown value
+- `newVersion`이 null → `upgrade` 실행 **전에** `UPGRADE_REJECTED`
+- admission `ADMIT` / `REJECT` / `FAIL` — 거부 시 연결이 **닫히는지**
+- 호출자가 포기한 뒤 늦게 도착한 연결이 닫히는지
+- `CALLER_ABORT`
+- `translate`가 각 cause에 대해 호출되는지
+
+트랜잭션(`tests/unit/indexeddb-transaction.test.ts`):
+- 커밋 / abort
+- `succeed()` 없이 완료 → `NO_VALUE_PRODUCED`
+- 첫 결과가 이긴다(`succeed` 이후 `fail` 무시)
+- 커서 순회와 `SUSPEND` 스텝(중첩 요청 체인)
+- 예산 콜백이 "삭제 행 기준"과 "스캔 행 기준" 양쪽을 표현할 수 있는지
+- **CP-4 필수 요건:** `abort()`가 throw하면 caller-abort 표시를 세우지 않고 transaction 이벤트가 결과를 정한다
+
+- [x] **Step 4: 구현한다 — 좁은 커널 함정을 피한다**
+
+기존 커널 `abortable-operation.ts:11`은 `AbortTerminalReason` 3멤버를 **반환 타입**에 박아서 5종이 필요한 `http-execution-v3`가 아예 못 썼다. 같은 실수를 반복하면 이 작업은 실패다.
+
+구현 후 아래를 확인한다:
+- `IndexedDbFailureCause`가 어떤 공개 **반환 타입**에도 나타나지 않는가 (`translate`의 입력으로만 쓰이는가)
+- spec §3.4의 4개 사본 예시(RT/MT/OP/CP)가 **전부** 수용되는가
+
+하나라도 수용되지 않으면 **구현을 멈추고 보고한다.** spec에 억지로 맞추지 않는다.
+
+- [x] **Step 5: INVENTORY 갱신**
+
+`docs/reviews/adapters/INVENTORY.md`에 두 행을 알파벳 위치에 넣고 번호를 다시 매긴다. 링크는 같은 그룹(`platform/`) 기존 행과 동일하게 `[Network/state](./01-network-and-state.md)`. 하단 합계를 `130/130`으로.
+
+- [x] **Step 6: 게이트**
+
+```bash
+corepack pnpm check:types:app && corepack pnpm check:types:test \
+ && corepack pnpm lint && corepack pnpm check:architecture \
+ && corepack pnpm check:adapter-inventory
+corepack pnpm test:unit
+```
+Expected: 앞 묶음 전부 PASS. `test:unit`은 `ci-artifact-contract.test.ts` 외 실패 0.
+
+- [x] **Step 7: 커밋**
+
+```bash
+git add src/adapters/platform tests/unit/indexeddb-*.test.ts docs/reviews/adapters/INVENTORY.md
+git commit -m "$(cat <<'EOF'
+feat: add the shared IndexedDB connection and transaction kernel
+
+네 어댑터가 각자 구현한 open/blocked/upgrade/트랜잭션 메커니즘을 커널로
+모은다. 사본은 아직 이행하지 않았으므로 런타임 동작은 그대로다.
+
+실패 분류는 커널에 넣지 않고 translate 콜백으로 주입한다. RT/MT/OP의
+mapIndexedDbException과 CP의 mapBrowserDataException이 같은 에러에 다른
+답을 내며, 그 차이를 통일하는 것은 별건이기 때문이다.
+
+Co-Authored-By: Claude Opus 5 (1M context)
+EOF
+)"
+```
+
+---
+
+### Task 2: CP 이행 — `indexeddb-checkpoint-store.ts` (712 → 약 570)
+
+**CP를 먼저 하는 이유:** 가장 작고, 동작 변화 지점이 가장 명확하며, 커널의 CP-4 요건(abort가 throw하면 caller-abort를 세우지 않는다)을 조기에 검증한다.
+
+**Files:**
+- Modify: `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts`
+- Modify: `tests/unit/resumable-upload-checkpoint.test.ts` (동작 변화 지점 고정)
+
+**Interfaces:**
+- Consumes: Task 1의 `openIndexedDbDatabase`, `runIndexedDbTransaction`, `deleteIndexedDbDatabase`
+- Produces: 없음 (공개 포트 형태 불변)
+
+- [x] **Step 1: 동작 변화 지점을 테스트로 먼저 고정한다**
+
+구현 전에 아래 5개가 현재 동작대로 통과하는지 확인한다. 이행 후에도 같아야 한다.
+
+| # | 지점 | 현재 동작 | 깨지면 |
+|---|---|---|---|
+| CP-1 | 값 없는 완료 | `CORRUPT_DATA/RECONCILE` (L541-547) | 번역기가 `NO_VALUE_PRODUCED → CORRUPT_DATA`를 명시 매핑 안 하면 UNAVAILABLE로 바뀜 |
+| CP-2 | `durability` | 옵션 bag 없음 (L512) | 커널 기본이나 `"strict"`를 넣으면 체크포인트 쓰기가 조용히 느려짐 (성능 회귀) |
+| CP-3 | `nativeFailure` | 기록 후 **즉시 abort** (L577-588) | `requestFailed`(abort 안 함)로 바꾸면 요청 실패 후에도 뒤 요청이 커밋됨. `compareAndSwap`의 `get→put` 체인(L321-343)에서 특히 위험 |
+| CP-4 | `abort()`가 throw | `failure`를 **되돌린다** (L528, L536) | 커밋된 체크포인트를 ABORTED로 보고 |
+| CP-5 | `deletePartition` blocked 타이머 | 네이티브 `setTimeout` (L450) | 주입형 `timers`로 바뀜. `tests/unit/resumable-upload-checkpoint.test.ts:194`가 이 경로를 봄 |
+
+기존 단언 위치: `:142` CONFLICT/RECONCILE, `:190` UNAVAILABLE/RESUME, `:194` blocked PENDING, `:238` false-abort 금지.
+
+- [x] **Step 2: 삭제 대상 블록을 커널 호출로 바꾼다**
+
+| 블록 | 줄 | 대체 |
+|---|---|---|
+| `TransactionContext` 타입 | L491-495 | 커널 타입 |
+| `openAndBind`의 open 요청 Promise 배선 | L163-175, L198-217 | `openIndexedDbDatabase` (upgrade 본문 L176-197은 `upgrade` 콜백으로, `bindScope` 호출은 `admit`으로) |
+| `runCheckpointTransaction` | L497-596 | `runIndexedDbTransaction` |
+| `bindScope`의 트랜잭션 배선 | L602-623 | `runIndexedDbTransaction` (검증 로직 L624-652는 `queue`로 그대로) |
+| `deletePartition`의 blocked/settle 배선 | L431-462, L472-483 | `deleteIndexedDbDatabase` |
+
+**남길 것:** `PENDING_DELETIONS` 레지스트리(L31-41) + 생성 시 검사(L116-122), `uploadCheckpointDatabaseName`(L73-83), `sameScopeBinding`(L656-672), `snapshotScope`(L674-691), `snapshotCheckpoint`(L693-711).
+
+- [x] **Step 3: 게이트 + 표적 테스트**
+
+```bash
+corepack pnpm check:types:app && corepack pnpm lint && corepack pnpm check:architecture
+npx vitest run tests/unit/resumable-upload-checkpoint.test.ts --reporter=default
+```
+Expected: 전부 PASS. CP-1~CP-5가 이행 전과 같은 답을 내야 한다.
+
+- [x] **Step 4: 커밋**
+
+```bash
+git add src/adapters/browser-transfer tests/unit/resumable-upload-checkpoint.test.ts
+git commit -m "refactor: move the upload checkpoint store onto the IndexedDB kernel
+
+Co-Authored-By: Claude Opus 5 (1M context) "
+```
+
+---
+
+### Task 3: MT 이행 — `indexeddb-maintenance.ts` (1558 → 약 1370)
+
+**MT를 두 번째로 하는 이유:** 커널 사용자 중 연결 핸들을 안 쓰는 유일한 사본이라 `openIndexedDbDatabase` 단독 사용 경로를 검증한다.
+
+**Files:**
+- Modify: `src/adapters/storage/indexeddb/indexeddb-maintenance.ts`
+- Modify: `tests/unit/indexeddb-maintenance.test.ts`
+
+**Interfaces:**
+- Consumes: Task 1의 `openIndexedDbDatabase`, `openIndexedDbTransaction`, `runIndexedDbTransaction`, `walkIndexedDbCursor`
+
+- [x] **Step 1: 두 개의 함정을 먼저 이해한다**
+
+**MT-1 (가장 위험).** `blockedTimeoutMs`를 **넘기지 마라.** 안 넘겨야 오늘 동작(blocked 이벤트 즉시 `BLOCKED`, L485-492)이 유지된다. 넘기면 배치가 최대 그 시간만큼 매달린다. `tests/unit/indexeddb-maintenance.test.ts:289-290`이 `BLOCKED/retryable:true/RELOAD_OTHER_CONTEXTS`를 **즉시** 받길 기대하므로 값을 넣으면 타임아웃으로 실패한다.
+
+**MT-2.** `upgrade` 콜백을 **생략하라.** 생략해야 오늘의 "upgrade는 곧 실패"(L477-484)가 유지된다. 커널은 생략을 `UPGRADE_REJECTED`로 해석한다. 실수로 `upgrade: () => ({kind:"APPLIED"})`를 넣으면 **잘못된 스키마로 열린다.**
+
+- [x] **Step 2: 삭제 대상 블록을 커널 호출로 바꾼다**
+
+| 블록 | 줄 | 대체 |
+|---|---|---|
+| `TransactionContext` 타입 | L97-101 | 커널 타입 |
+| `openExactVersion`의 배선분 | L434-508, L551-585 | `openIndexedDbDatabase` (L509-550을 `admit`으로 이식) |
+| `createTransaction` | L587-604 | `openIndexedDbTransaction` |
+| `runTransaction` | L606-705 | `runIndexedDbTransaction` |
+| 커서 2곳의 deadline/maxRows/abort 보일러플레이트 | L799-833, L1451-1479 | `walkIndexedDbCursor` |
+
+**MT-3.** `database.onversionchange = () => database.close()`(L543)를 `admit` 안으로 옮긴다. `admit`은 성공 경로에서만 실행되므로 등록 시점이 오늘과 같다.
+
+**남길 것:** 체크포인트 상태기계(`readCheckpoint` L707-756, `commitPrepared` L969-1251), `prepareRecords`(L863-967), `clock`/`epochClock`(L401-421), `countBucket`(L239-245), 저장 술어(L118-223).
+
+- [x] **Step 3: 게이트 + 표적 테스트**
+
+```bash
+corepack pnpm check:types:app && corepack pnpm lint && corepack pnpm check:architecture
+npx vitest run tests/unit/indexeddb-maintenance.test.ts --reporter=default
+```
+Expected: 전부 PASS. 특히 `:289-290`이 **즉시** BLOCKED를 받아야 한다(타임아웃이 아니라).
+
+- [x] **Step 4: 커밋**
+
+```bash
+git add src/adapters/storage tests/unit/indexeddb-maintenance.test.ts
+git commit -m "refactor: move IndexedDB maintenance onto the kernel
+
+Co-Authored-By: Claude Opus 5 (1M context) "
+```
+
+---
+
+### Task 4: OP 이행 — `indexeddb-opfs-journal.ts` (1817 → 약 1690)
+
+**이 계획에서 동작 변화가 가장 큰 태스크다.**
+
+**Files:**
+- Modify: `src/adapters/storage/opfs/indexeddb-opfs-journal.ts`
+- Modify: `tests/unit/indexeddb-opfs-journal.test.ts`
+- 가능성: `tests/helpers/memory-indexeddb.ts` 보강
+
+**Interfaces:**
+- Consumes: Task 1의 `openIndexedDbDatabase`, `createIndexedDbConnection`, `runIndexedDbTransaction`, `openIndexedDbTransaction`, `walkIndexedDbCursor`
+
+- [x] **Step 1: OP-1을 테스트로 먼저 드러낸다 — 이 태스크의 핵심**
+
+오늘 OP는 트랜잭션 안의 개별 요청에 `.onerror`를 **하나도** 안 단다(파일 전체에서 request `.onerror`는 L1042의 open 요청 하나뿐). 요청 실패는 `transaction.onabort`로만 흘러 `mapIndexedDbException(transaction.error)`(L1158)가 된다.
+
+커널을 쓰면 **요청 자신의 오류가 보고된다.** 구체적으로 `LOGICAL_KEY_INDEX`가 `unique: true`(L1000-1004)이므로 **중복 put은 요청 레벨 `ConstraintError` → `CONFLICT`**가 되고, 오늘은 `transaction.error`가 무엇이냐에 따라 달라진다.
+
+이행 **전에** 중복 put 테스트를 `tests/unit/indexeddb-opfs-journal.test.ts`에 추가해 현재 답을 기록하고, 이행 후 달라진 답을 의도된 변경으로 승인한다. 가짜 IDB가 이 경로를 표현하지 못하면 `tests/helpers/memory-indexeddb.ts`를 먼저 보강한다.
+
+- [x] **Step 2: OP-2를 확인한다**
+
+오늘 OP의 `runTransaction`은 `succeed` 이후 `fail`이 와도 `explicitFailure`가 이기지만(L1133-1141, `hasValue`는 true 유지) `oncomplete`는 값을 반환한다(L1143-1153). 커널의 "첫 결과가 이긴다" 규칙을 따르면 **`succeed` 후의 `fail`이 무시된다.**
+
+현재 OP 코드에 그 순서가 실제로 발생하는 경로가 있는지 **확인하라**(spec은 미확인으로 남겼다). 없으면 변화 없음으로 기록하고 넘어간다.
+
+- [x] **Step 3: 삭제 대상 블록을 커널 호출로 바꾼다**
+
+| 블록 | 줄 | 대체 |
+|---|---|---|
+| `TransactionContext` 타입 | L48-51 | 커널 타입 |
+| scheduler 기본값 인라인 | L144-153 | `snapshotAbortTimers` |
+| `openDatabase`의 배선분 | L961-996, L1031-1072 | `openIndexedDbDatabase` + `createIndexedDbConnection` (upgrade 본문 L997-1029는 `upgrade` 콜백으로 그대로 이동) |
+| `runTransaction` | L1098-1174 | `runIndexedDbTransaction` |
+| `strictReadwriteTransaction` | L1176-1190 | `openIndexedDbTransaction(…, "strict")` |
+| 커서 2곳의 limit 루프 | L604-633, L677-712 | `walkIndexedDbCursor` |
+
+**OP-4.** `signal`은 **넣지 않는다.** 오늘 없는 취소를 새로 만들지 않는다.
+
+- [x] **Step 4: 게이트 + 표적 테스트**
+
+```bash
+corepack pnpm check:types:app && corepack pnpm lint && corepack pnpm check:architecture
+npx vitest run tests/unit/indexeddb-opfs-journal.test.ts tests/unit/opfs-byte-store.test.ts --reporter=default
+```
+Expected: PASS. OP-1로 인한 답 변화는 Step 1에서 승인한 것만 있어야 한다.
+
+- [x] **Step 5: 커밋**
+
+```bash
+git add src/adapters/storage tests
+git commit -m "refactor: move the OPFS journal onto the IndexedDB kernel
+
+요청 레벨 오류를 처음으로 보게 된다. unique 인덱스 위반이 트랜잭션 abort
+사유가 아니라 요청 자신의 ConstraintError로 보고된다.
+
+Co-Authored-By: Claude Opus 5 (1M context) "
+```
+
+---
+
+### Task 5: RT 이행 — `indexeddb-runtime.ts` (2902 → 약 2665)
+
+**가장 크고 마지막이다.** 다른 셋이 커널을 전부 검증한 뒤에 옮긴다.
+
+**Files:**
+- Modify: `src/adapters/storage/indexeddb/indexeddb-runtime.ts`
+- Modify: `tests/unit/indexeddb-runtime.test.ts`
+
+- [x] **Step 1: RT-1을 번역기에 명시한다**
+
+`close()`가 진행 중 open을 끝내는 원인이 `unavailable(operation)`(L743)에서 `translate({kind:"CLOSED"})`로 바뀐다. 번역기가 **`CLOSED → unavailable`을 명시 매핑**해야 오늘 동작이 유지된다. 빠뜨리면 `close()` 중 open이 ABORTED로 보고된다.
+
+기존 실패 코드 단언 위치: `tests/unit/indexeddb-runtime.test.ts:339-340, :371-372, :454, :534, :549-550, :734-735`.
+
+- [x] **Step 2: 삭제 대상 블록을 커널 호출로 바꾼다**
+
+| 블록 | 줄 | 대체 |
+|---|---|---|
+| `defaultScheduler` | L108-117 | `snapshotAbortTimers(scheduler)` |
+| `TransactionContext` 타입 | L85-89 | `IndexedDbTransactionContext` |
+| `waitForOpeningAttempt` | L659-682 | `connection.acquire(signal)` |
+| `startOpeningAttempt`의 배선분 | L684-745, L776-843, L872-921 중 배선분 | `openIndexedDbDatabase` (upgrade/admit 콜백 본문은 그대로) |
+| `createTransaction` | L957-974 | `openIndexedDbTransaction` |
+| `runTransaction` | L976-1074 | `runIndexedDbTransaction` |
+| 커서 5곳의 보일러플레이트 | L1374-1382, L1454-1471, L2364-2389, L2531-2548, L2573-2590, L2644-2661, L2718-2735 | `walkIndexedDbCursor` + `budget.admit` |
+
+**RT-2.** `settleNativeRequest`/`activeOpeningGeneration`(L595, L691-697)이 사라진다. 커널의 settle-once와 단일 비행이 같은 역할을 한다. **의미는 같지만 경합 순서가 달라질 수 있다** — 동시 open 테스트를 주의해서 본다.
+
+**RT-3.** `openingRequest` 필드(L593)는 오늘도 L712·L2878의 대입 외에 읽는 곳이 없다. 삭제한다.
+
+**남길 것:** 코덱/영수증/보존/예산(bytes)/governance/migration 목록/상태 브로드캐스트/`monotonicClock`/`countBucket`/저장 레코드 술어/`purgePartitionRecords`의 스토어 순서 로직 — 전부 정책이다.
+
+- [x] **Step 3: 게이트 + 전체 테스트**
+
+```bash
+corepack pnpm check:types && corepack pnpm lint && corepack pnpm check:architecture \
+ && corepack pnpm check:adapter-inventory
+corepack pnpm test:unit
+corepack pnpm test:integration
+```
+Expected: `ci-artifact-contract.test.ts` 외 실패 0.
+
+- [x] **Step 4: 커밋**
+
+```bash
+git add src/adapters/storage tests/unit/indexeddb-runtime.test.ts
+git commit -m "refactor: move the IndexedDB runtime onto the kernel
+
+Co-Authored-By: Claude Opus 5 (1M context) "
+```
+
+---
+
+## 완료 판정
+
+```bash
+corepack pnpm check:types
+corepack pnpm lint
+corepack pnpm check:architecture
+corepack pnpm check:adapter-inventory
+corepack pnpm check:bundle
+corepack pnpm test:unit # ci-artifact-contract.test.ts 외 실패 0
+corepack pnpm test:integration
+corepack pnpm test:component
+corepack pnpm test:browser-file-storage-removal # error TS 0건
+corepack pnpm test:realtime-removal # error TS 0건
+```
+
+그리고 아래가 **0**이어야 한다 — 커널 밖에 남은 open 요청 배선:
+```bash
+grep -rn "createObjectStore\|onupgradeneeded" src/adapters --include='*.ts' \
+ | grep -v "src/adapters/platform/" | grep -v "upgrade" | wc -l
+```
+
+**실브라우저 확인이 필요하다.** 이 계획은 가짜 IDB 위에서만 검증된다. `tests/browser-capabilities/indexeddb-runtime.spec.ts`(1033 LOC), `opfs-runtime.spec.ts`(221), `resumable-upload.spec.ts`(526)를 실브라우저에서 돌려야 blocked/versionchange 실동작 회귀를 잡는다.
+
+## 이 계획이 하지 않는 것
+
+- **실패 매핑 4벌 통일** — `mapIndexedDbException`과 `mapBrowserDataException`이 같은 에러에 다른 답을 내는 것은 별건이다. 이 계획은 그 차이를 `translate` 주입으로 **보존**한다.
+- **`deleteDatabase`를 3벌에 추가** — CP에만 있는 것이 의도다(spec §2.3).
+- 대형 파일 분할 — 커널 이행으로 RT가 2902 → 2665가 되지만 여전히 크다. 분할은 별도 계획이다.
+
+
+---
+
+## 실행 기록 (2026-09-16 — 5개 태스크 전부 완료)
+
+커밋 5개: `cb62bfb`(커널) · `bb6080b`(CP) · `3366a81`(MT) · `217c1dd`(OP) · `a91e78f`(RT).
+
+### 실측 LOC — 사양 추정은 전부 빗나갔다
+
+| 사본 | 사양 추정 | 실제(전체 줄) | 실제(코드 줄) |
+|---|---:|---:|---:|
+| CP `indexeddb-checkpoint-store.ts` | −142 | 712 → 612 = **−100** | |
+| MT `indexeddb-maintenance.ts` | −188 | 1558 → 1430 = **−128** | |
+| OP `indexeddb-opfs-journal.ts` | −127 | 1817 → 1881 = **+64** | 1744 → 1724 = −20 |
+| RT `indexeddb-runtime.ts` | −235 | 2902 → 2744 = **−158** | 2807 → 2563 = −244 |
+| 4벌 합 | **−693** | **−322** | |
+| 커널 2파일 | +470 | **+1,132** | +751 |
+| **소스 순증감** | **−223** | **+810** | |
+| 커널 테스트 2파일 | (미기재) | +1,602 | |
+
+**공통 원인:** 사양이 `translate`/실패 헬퍼 어댑터 함수 비용을 세지 않았다. CP는 4개(~37줄), MT는 6개가 필요했다. 그리고 이행된 파일들의 주석이 크게 늘었다(OP 6→90줄, RT 12→111줄) — 이 레포 관례상 부풀림이 아니라 개선이지만, 줄 수 예측은 무너뜨린다.
+
+**결론은 바뀌지 않는다.** 이 작업의 근거는 처음부터 줄 수가 아니라 상태기계 통합이었고, 그건 달성됐다. 다만 **줄 수가 준다는 기대는 완전히 틀렸다**는 것을 기록해 둔다.
+
+### 부수 성과
+
+- **abort 래칫이 24 → 21로 세 칸 조여졌다.** CP·MT·RT가 각각 자기 abort 리스너를 지웠다. 래칫이 설계대로 작동했다.
+- **가짜 IndexedDB가 unique 인덱스를 전혀 강제하지 않는 것을 찾아 고쳤다**(`tests/helpers/memory-indexeddb.ts`). 보강 전에는 중복 `begin`이 `ok:true`로 성공했다 — 브라우저가 거부할 상태를 테스트가 조용히 허용하고 있었다. 이 발견이 커널 이행 자체보다 가치가 클 수 있다.
+- 사양이 빠뜨린 함정 하나를 CP에서 막았다: `bindScope`는 `succeed()`에 해당하는 것이 없어 그대로 옮기면 정상 바인딩이 `CORRUPT_DATA`로 보고된다. 이후 MT·OP·RT는 성공 출구를 전수 대조했다.
+
+### 사양이 틀린 것으로 판명된 항목 3건
+
+1. **OP-1** — 사양은 "이 리팩토링에서 가장 큰 동작 변화"로 지목하며 중복 put의 답이 달라진다고 봤다. **틀렸다.** 이행 전후 모두 `CONFLICT / retryable:false / recovery:NONE`이다. 요청 오류를 아무도 처리하지 않으면 스토어가 바로 그 에러로 abort해서 `transaction.error === request.error`이기 때문이다. 바뀐 것은 답이 아니라 출처다.
+2. **RT-2** — 사양은 "의미 동일"이라고 썼다. **틀렸다.** 아래 참조.
+3. **§3.1의 파일 분할 논거** — "470 LOC라 1파일은 폴더 관례를 깬다"고 썼으나 실제 구현은 1,132줄이다. 2분할 자체는 유지할 값이 있지만(테스트 셋업이 갈린다) 그 논거는 사실이 아니었다.
+
+### 보존하지 못한 동작 1건 — RT-2 (의도적으로 남김)
+
+blocked 데드라인 이후 재시도가 새 `factory.open()`을 띄운다. 이행 전에는 안 띄웠다. 커널에 "settle 이후에도 살아 있는 요청"을 알려줄 훅이 없기 때문이다.
+
+**복원하지 않기로 했다.** 근거:
+- 이행 전후 모두 10초 blocked 데드라인이 있고, 차이는 두 번째 네이티브 open을 띄우는지뿐이다.
+- 늦게 도착한 연결은 커널이 `closeQuietly`로 닫으므로 **연결 누수도 데이터 위험도 없다.**
+- 재시도가 10초 데드라인에 게이트되므로 쌓이는 속도가 제한적이다.
+- 반면 지금 커널을 고치면 **이미 검증이 끝난 4개 사본을 전부 재검증**해야 한다. 이익 대비 위험이 맞지 않는다.
+
+복원하려면 `openIndexedDbDatabase`에 `onSettled`를 추가하면 된다(`deleteIndexedDbDatabase`에는 이미 있다). 다만 그러면 "blocked 데드라인 실패가 버려진 요청이 끝날 때까지 다음 acquire를 막는가"라는 설계 질문이 따라온다 — 막는다면 다른 탭이 영영 안 닫힐 때 재시도가 영구 차단되어 **지금보다 나쁘다.** 착수 전 그 답부터 정해야 한다.
+
+### 테스트로 덮지 못한 경로 1건
+
+RT의 `POLICY_REJECTED` upgrade 거절 경로. `queueIndexedDbUpgradeBinding`의 `onRejected`가 비동기라 `.then` 후처리로 보존했으나, **가짜 IDB의 upgrade 트랜잭션이 동기라 단위 테스트로 검증할 수 없다.** 레포 전체에 이 경로를 덮는 테스트가 없다. **실브라우저 확인이 필요하다.**
+
+### 검증 결과
+
+**PASS:** `check:types` `lint` `check:architecture` `check:adapter-inventory`(21/21 래칫) `check:bundle`(181114/204800, 이행 전과 동일) `test:integration`(81) `test:component`(130)
+
+**`test:unit`:** 실패 파일은 `tests/unit/ci-artifact-contract.test.ts` 하나뿐(16~18건, 실행마다 흔들림 — `bwrap: loopback: Failed RTM_NEWADDR`). `develop` `5434760` 기준선에서도 동일함을 stash 후 실행해 확인했다. **그 파일 밖 실패 0.**
+
+**실브라우저 미검증:** `tests/browser-capabilities/indexeddb-runtime.spec.ts`(1033) · `opfs-runtime.spec.ts`(221) · `resumable-upload.spec.ts`(526). 전부 가짜 IDB 위에서만 검증됐다. blocked/versionchange 실동작과 위 upgrade 경로는 여기서만 잡힌다. **CI 또는 로컬 브라우저 실행이 남은 과제다.**
diff --git a/docs/superpowers/specs/2026-09-16-adapter-barrel-boundary-design.md b/docs/superpowers/specs/2026-09-16-adapter-barrel-boundary-design.md
new file mode 100644
index 0000000..92ac715
--- /dev/null
+++ b/docs/superpowers/specs/2026-09-16-adapter-barrel-boundary-design.md
@@ -0,0 +1,751 @@
+# 어댑터 배럴(`index.ts`)을 공개 경계로 승격 — 설계서
+
+- 대상 레포: `/home/donghyeon/workspace/desktop-server-git/clean-architecture-frontend-template`
+- 브랜치: `develop` (기준 커밋 `5434760`)
+- 전제(이미 확정): 배럴 폐지안은 기각. `src/adapters//index.ts`를 **진짜 공개 경계**로 만든다.
+- 게이트 기준선: `check:architecture` PASS, `check:types:app` PASS 유지.
+- 이 문서는 설계만 한다. 소스 수정·빌드·테스트 실행 없음.
+
+---
+
+## 0. 요약 (먼저 읽을 것)
+
+| 항목 | 판정 |
+|---|---|
+| 배럴 표기 표준 | **명명 재수출(named re-export)**. `export *`는 "이미 명시적인 서브배럴을 합칠 때"만 허용 |
+| 새로 만들 배럴 | 8개, 합계 114줄 (auth 9 / diagnostics 7 / telemetry 7 / storage 4 / service-worker 17 / query-cache 21 / platform 22 / http 27) |
+| `platform/` | 배럴은 만든다. 단 **어댑터→커널 간선은 파일 직접 import를 유지**한다 (게이트가 그걸 요구함) |
+| `storage/` | 최상위 배럴은 **서브폴더를 재수출하지 않는다**. `indexeddb/index.ts`·`opfs/index.ts`가 곧 경계다 |
+| `http/` | V3(`createContractHttpExecutor`)가 권장 경로, V2(`createHttpClient`)는 legacy 보존. 둘 다 배럴에 넣고 주석으로 표시 |
+| 치환할 import | `src/` 15줄 (배럴 경유 2줄은 이미 합격) + `.storybook/` 2줄(선택) |
+| 게이트 | `.dependency-cruiser.json`에 규칙 1개 추가. `tests/`는 대상 아님(스캔 범위가 `src`뿐) |
+| 최대 위험 | 번들 예산. `package.json`에 `sideEffects` 선언이 없어 배럴이 초기 청크를 키울 수 있다 |
+
+---
+
+## 1. 기존 배럴 8개의 지배적 관례
+
+읽은 파일: `src/adapters/{browser-files,browser-file-storage,browser-rpc,browser-transfer,cache-storage,cross-context-invalidation,realtime,web-push}/index.ts`
+추가로 서브배럴 8개: `browser-transfer/{image-cdn,presigned,resumable-upload}/index.ts`, `realtime/{polling,sse,websocket}/index.ts`, `storage/{indexeddb,opfs}/index.ts`
+
+### 1.1 관례 (문장으로)
+
+1. **소스 파일 단위로 블록을 만들고, 블록마다 `export { ... } from "./파일.ts";` 로 이름을 전부 적는다.**
+ 블록이 전부 타입이면 `export type { ... } from "...";` 형태를 쓴다 (`browser-files/index.ts:1`, `:28`, `:52`, `:53`).
+2. **블록 안 순서는 「값 먼저, 타입 나중」이고 각각 대소문자 무시 알파벳순이다.**
+ 근거: `web-push/index.ts:42-51` — `createLinkedAbortController, failureCode, nativeFailure, observeWebPush, systemTimeoutScheduler, withAbortableDeadline, type LinkedAbortController, type TimeoutScheduler`.
+ 상수도 값이므로 같은 줄에 섞인다: `realtime/index.ts:13-22` — `parseRetryAfterDelay, REALTIME_RECONNECT_CEILINGS, reconnectBudgetRemaining` (대소문자 무시로 `parse < realtime_ < reconnect`).
+ 타입은 인라인 `type X` 접두어로 쓴다 (`browser-rpc/index.ts:9-18`).
+3. **블록(파일) 순서는 대체로 알파벳순이되 엄격하지 않다.** 하위 폴더 블록은 뒤로 몰아둔다 (`web-push/index.ts:59`, `:66`의 `./inbound/*`).
+ 엄격하지 않은 실례: `cross-context-invalidation/index.ts`는 `browser-cross-context-invalidation.ts`(:1) 다음에 `browser-cross-context-host.ts`(:20) — 역순.
+4. **배럴은 그룹의 전체 export 목록이 아니다.** 그룹 안에 배럴에 없는 파일이 실제로 존재한다.
+ 근거: `src/adapters/realtime/result.ts`는 export를 가지지만 `realtime/index.ts` 어디에도 없다. `browser-files/browser-file-vault.ts`도 `browser-files/index.ts`에 없다.
+ → 즉 이 레포는 이미 "배럴 = 선별된 공개 표면"을 실천하고 있다. 새 배럴도 같은 기준으로 고르면 된다.
+5. (참고, 따라하지 말 것) `browser-files/index.ts:1-16`은 어댑터가 아니라 **application 포트 타입**을 재수출한다. 배럴이 하위 레이어의 통로가 되는 형태라 새 배럴에서는 재현하지 않는다. 필요하면 소비자가 포트에서 직접 가져오면 된다.
+
+### 1.2 `export *`는 표준인가 — 판정
+
+**표준은 명명 재수출이다. `export *`는 예외가 아니라 "서브배럴 합성" 전용 관용구다.**
+
+근거:
+
+- `export *`가 쓰인 곳은 단 두 파일, 여섯 줄이다.
+ - `src/adapters/browser-transfer/index.ts:1-3` — `./image-cdn/index.ts`, `./presigned/index.ts`, `./resumable-upload/index.ts`
+ - `src/adapters/realtime/index.ts:56-58` — `./polling/index.ts`, `./sse/index.ts`, `./websocket/index.ts`
+- **여섯 줄 전부 대상이 `index.ts`(서브배럴)다.** 구현 파일(`.ts`)을 `export *`로 푼 사례는 0건이다.
+- 그리고 그 서브배럴들은 자기 자신이 전부 명명 재수출이다 (`browser-transfer/image-cdn/index.ts:1-6`, `realtime/sse/index.ts:1-9` 등).
+- `realtime/index.ts`는 한 파일 안에서 두 형태를 동시에 쓴다: 1-55줄은 구현 파일에 대한 명명 재수출, 56-58줄은 서브배럴에 대한 `export *`. 즉 `browser-transfer`만 특이한 게 아니라, **대상이 서브배럴이냐 구현 파일이냐**가 형태를 가른다.
+
+왜 이 구분이 옳은가: 지시대로 `export *`는 "무엇이 공개되는지 파일을 열어야 안다"는 문제가 있다. 그런데 대상이 서브배럴이면 그 파일 자체가 이미 명시적 목록이므로, `export *` 한 줄을 따라가면 곧바로 명시적 목록에 도달한다. 목록이 사라지는 게 아니라 한 단계 아래에 있는 것뿐이다. 반대로 구현 파일을 `export *`하면 목록이 어디에도 없어진다.
+
+**채택 규칙**
+
+> 배럴은 구현 파일(`*.ts`)에 대해서는 반드시 이름을 하나씩 적는다.
+> `export *`는 대상이 같은 그룹의 서브배럴(`*/index.ts`)일 때만 쓴다.
+
+새로 만드는 8개 중 `export *`를 쓸 자리는 **없다** (아래 §3.7에서 `storage`가 서브배럴을 재수출하지 않기로 판정하므로).
+
+---
+
+## 2. 공개/내부 판정 기준
+
+판정 근거는 실제 사용처다. 측정 명령:
+
+```
+grep -rnE 'from "[^"]*adapters/(auth|browser-files|browser-file-storage|browser-rpc|browser-transfer|cache-storage|cross-context-invalidation|diagnostics|http|platform|query-cache|realtime|service-worker|storage|telemetry|web-push)/' src/ --include='*.ts' --include='*.tsx' | grep -v '^src/adapters/'
+```
+
+- **공개**: `src/bootstrap/**`, `src/features/**`, `src/presentation/**`이 import하는 심볼 + 그 심볼의 시그니처에 이름으로 등장하는 타입(의존성/옵션/반환 파사드).
+- **내부**: 그룹 안에서만 쓰이는 헬퍼.
+- **내부(테스트 전용)**: `tests/`만 import하는 심볼. 배럴에 넣지 않고, 테스트는 깊은 경로를 유지한다. 각 그룹에서 별도로 표시했다.
+
+예외 처리 하나: 같은 파일의 동급 팩토리 형제는 오늘 테스트만 쓰더라도 공개로 올린다(예 `createAnonymousSessionAdapter`). 근거는 §3.1.
+
+---
+
+## 3. 새로 만들 배럴 8개 (전문)
+
+아래 내용은 전부 **그대로 파일로 저장 가능**하다. 모든 심볼은 기계 대조로 존재를 확인했다(82개 전수, §7).
+
+### 3.1 `src/adapters/auth/index.ts`
+
+그룹 파일: `external-session-adapter.ts` 1개.
+
+| 심볼 | 위치 | 판정 | 근거 |
+|---|---|---|---|
+| `createExternalAuthSessionAdapter` | `external-session-adapter.ts:51` | 공개 | `src/bootstrap/runtime-adapters.ts:3` |
+| `createDemoSessionAdapter` | `:104` | 공개 | `src/bootstrap/runtime-adapters.ts:2`, `:279` |
+| `createUnavailableSessionAdapter` | `:140` | 공개 | `src/bootstrap/runtime-adapters.ts:4` |
+| `createAnonymousSessionAdapter` | `:77` | 공개(승격) | 위 셋과 같은 파일·같은 반환형(`AuthSessionPort`)의 형제 팩토리. 오늘 `src` 소비자는 `.storybook/preview.tsx:5`뿐이라 배럴이 없으면 깊은 경로가 남는다 |
+| `DEMO_AUTHORIZATION_MARKER` | `:98` | 공개 | 계약 문서가 이름으로 참조: `docs/architecture/decisions/VD-23-api-transport-selection-and-rest-execution.md:305` |
+| `ExternalSessionOwner` | `:10` | 공개 | `src/bootstrap/runtime-adapters.ts:5` |
+| `DemoSessionAdapter` | `:89` | 공개 | `createDemoSessionAdapter`의 반환 타입 |
+| `validateCredentialPatch` | `:26` | **내부** | `src/`·`tests/` 어디서도 import하지 않음 |
+
+```ts
+export {
+ createAnonymousSessionAdapter,
+ createDemoSessionAdapter,
+ createExternalAuthSessionAdapter,
+ createUnavailableSessionAdapter,
+ DEMO_AUTHORIZATION_MARKER,
+ type DemoSessionAdapter,
+ type ExternalSessionOwner,
+} from "./external-session-adapter.ts";
+```
+
+---
+
+### 3.2 `src/adapters/diagnostics/index.ts`
+
+그룹 파일: `bounded-diagnostics.ts` 1개. export 5개 전부 공개.
+
+| 심볼 | 위치 | 판정 | 근거 |
+|---|---|---|---|
+| `createDiagnosticsAdapter` | `bounded-diagnostics.ts:18` | 공개 | `src/bootstrap/runtime-adapters.ts:7` |
+| `recordBootFailure` | `:80` | 공개 | `src/bootstrap/main.tsx:3` |
+| `getLastBootEvidence` | `:108` | 공개 | `recordBootFailure`의 짝(부팅 증거 읽기). 오늘 사용처는 `tests/`만 |
+| `noOpDiagnostics` | `:11` | 공개 | `DiagnosticsPort`의 null object. 다른 그룹이 기본값으로 기대하는 형태 |
+| `MAX_DIAGNOSTIC_ENTRIES` | `:16` | 공개 | 선언된 상한값(계약 수치) |
+
+```ts
+export {
+ createDiagnosticsAdapter,
+ getLastBootEvidence,
+ MAX_DIAGNOSTIC_ENTRIES,
+ noOpDiagnostics,
+ recordBootFailure,
+} from "./bounded-diagnostics.ts";
+```
+
+---
+
+### 3.3 `src/adapters/telemetry/index.ts`
+
+그룹 파일: `best-effort-telemetry.ts` 1개.
+
+| 심볼 | 위치 | 판정 | 근거 |
+|---|---|---|---|
+| `createTelemetryAdapter` | `best-effort-telemetry.ts:52` | 공개 | `src/bootstrap/runtime-adapters.ts:29` |
+| `noOpTelemetry` | `:31` | 공개 | null object |
+| `MAX_TELEMETRY_QUEUE` | `:47` | 공개 | 선언된 상한값 |
+| `TelemetryAdapter` | `:10` | 공개 | 팩토리 반환 타입 |
+| `TelemetryAdapterOptions` | `:20` | 공개 | 팩토리 인자 타입 |
+| `safeTraceparent` | `:229` | **내부(테스트 전용)** | `tests/`만 import. traceparent 정규화는 어댑터 내부 동작 |
+| `assertBoundedCapacity` 재수출 | `:49` | **배럴에 넣지 않음** | 이건 telemetry의 export가 아니라 **커널(`../platform/bounded-capacity.ts`) 심볼의 재수출**이다. 배럴에 올리면 커널로 가는 두 번째 문이 생긴다 |
+
+> **부수 발견 / 별도 처리 권고**
+> `src/adapters/telemetry/best-effort-telemetry.ts:49`
+> ```ts
+> export { assertBoundedCapacity } from "../platform/bounded-capacity.ts";
+> ```
+> 이 줄은 이 배럴 작업과 무관하게 지우는 게 맞다. 같은 파일 `:8`에서 이미 같은 심볼을 import해서 `:61`에서 쓰고 있으므로 재수출은 순수 잉여이고, 실제 소비자도 없다(`grep -rn 'assertBoundedCapacity' src/ tests/` → `platform/bounded-capacity.ts` 정의부, `telemetry:8,49,61`, `diagnostics:9,25`가 전부). 이 문서 범위에서는 **건드리지 않고** 배럴에서 제외만 한다.
+
+```ts
+export {
+ createTelemetryAdapter,
+ MAX_TELEMETRY_QUEUE,
+ noOpTelemetry,
+ type TelemetryAdapter,
+ type TelemetryAdapterOptions,
+} from "./best-effort-telemetry.ts";
+```
+
+---
+
+### 3.4 `src/adapters/platform/index.ts` — 커널
+
+#### 판정: 배럴은 만들되, **어댑터→커널 간선은 파일 직접 import를 유지한다.**
+
+질문은 "`browser-transfer/presigned/presigned-transfer-executor.ts:15`의 `../../platform/abortable-operation.ts`가 `../../platform/index.ts`로 바뀌어야 하는가"였다. **아니다. 바꾸면 게이트가 깨진다.**
+
+**근거 1 (결정적) — `check:adapter-inventory`가 파일 경로를 직접 검증한다.**
+`scripts/check-adapter-inventory.ts:63-83`:
+
+```ts
+const PRIMITIVE_PATH = path.resolve("src/adapters/platform/abortable-operation.ts");
+for (const consumer of REQUIRED_ABORT_CONSUMERS) {
+ ...
+ const specifiers = [...source.matchAll(/from\s+"([^"]*platform\/abortable-operation\.ts)"/gu)]...;
+ const resolved = specifiers.some(
+ (specifier) => path.resolve(path.dirname(consumer), specifier) === PRIMITIVE_PATH,
+ );
+ if (!resolved) { problems.push(`abortable-operation: ${consumer} does not resolve...`); }
+}
+```
+
+`REQUIRED_ABORT_CONSUMERS`(`scripts/check-adapter-inventory.ts:134-137`)는 정확히 네 파일이다:
+`browser-transfer/presigned/presigned-capability-http-provider.ts`, `.../presigned-transfer-executor.ts`, `browser-transfer/image-cdn/browser-image-probe.ts`, `browser-transfer/resumable-upload/fetch-json-transport.ts`.
+이들이 `../../platform/index.ts`로 바뀌면 정규식이 매칭되지 않아 `check:adapter-inventory`가 실패한다.
+
+**근거 2 — 규칙상으로는 둘 다 가능하지만, 커널의 정체성은 "파일"이다.**
+`.dependency-cruiser.json:191`의 carve-out은 `^src/adapters/($1/|platform/|browser-file-storage/result\.ts$|cross-context-invalidation/index\.ts$)` 로 `platform/` 폴더 전체를 허용한다. 즉 규칙은 중립이다.
+그런데 `docs/architecture/layers.md:34`는 커널을 "the system clock, the shared abort primitive and the bounded-capacity guard" — **세 개의 프리미티브**로 정의한다. 런타임 합성물이 아니라 원시 도구다. 원시 도구는 "어느 파일에서 왔는지"가 곧 정체성이고, 실제로 위 게이트가 그 정체성을 파일 경로로 확인한다.
+
+**근거 3 — 그래서 새 게이트 규칙은 `src/adapters/**`를 출발점에서 제외한다.**
+어댑터끼리의 간선은 이미 `adapters-do-not-know-other-concrete-adapters`(`.dependency-cruiser.json:183-193`)가 담당한다. 새 규칙이 그 위에 겹칠 이유가 없다. §5의 `from.pathNot: "^src/adapters/"`가 이 판정의 실행형이다.
+
+#### 그러면 배럴에는 뭘 넣나
+
+커널 프리미티브도 **전부** 넣는다. 이유: 배럴을 쓰는 쪽은 `src/bootstrap`과 `tests`인데, 이들은 `systemClock`(tests), `createAbortableOperation`(tests), `createBrowserLifecycleRuntime`(`src/bootstrap/optional-runtime-host.ts:2`), `createBrowserMutationIntentFactory`(`src/bootstrap/runtime-adapters.ts:28`)를 쓴다. 일부만 넣으면 "바깥은 배럴만"이라는 규칙에 예외가 생긴다. 두 개의 문이 생기는 게 아니라 **문이 소비자별로 하나씩**이다: 어댑터는 파일, 그 외는 배럴.
+
+| 파일 | 공개 심볼 | 소비자 근거 |
+|---|---|---|
+| `abortable-operation.ts` | `createAbortableOperation:90`, `compensateLateHandle:261`, `snapshotAbortTimers:70`, `AbortableOperation:24`, `AbortableOperationInput:51`, `AbortRace:19`, `AbortTerminalReason:11`, `AbortTimerSnapshot:59` | 어댑터 4곳(직접 경로 유지) + `tests/` |
+| `bounded-capacity.ts` | `assertBoundedCapacity:10` | `diagnostics:9`, `telemetry:8` (직접 경로 유지) |
+| `browser-lifecycle.ts` | `createBrowserLifecycleRuntime:57`, `BrowserLifecycleEvent:20`, `BrowserLifecycleRuntime:36`, `BrowserLifecycleSnapshot:13` | `src/bootstrap/optional-runtime-host.ts:1-4` |
+| `browser-mutation-intent-factory.ts` | `createBrowserMutationIntentFactory:9`, `BrowserMutationIntentFactoryDependencies:4` | `src/bootstrap/runtime-adapters.ts:28` |
+| `system-clock.ts` | `systemClock:3` | 어댑터 6곳(직접 경로 유지) + `tests/` |
+
+내부: 없음. 이 그룹은 모든 export가 커널 표면이다.
+
+```ts
+/**
+ * 어댑터 커널의 공개 경계.
+ *
+ * `src/adapters/**` 안에서는 이 배럴을 쓰지 않는다. 커널 프리미티브는 파일
+ * 경로로 직접 import한다 — `scripts/check-adapter-inventory.ts`가
+ * `platform/abortable-operation.ts`로 해석되는 specifier를 네 소비자에게
+ * 요구하고, `.dependency-cruiser.json`의 kernel carve-out도 폴더 단위다.
+ * 이 배럴은 bootstrap·features·tests 같은 그룹 바깥 소비자를 위한 문이다.
+ */
+export {
+ compensateLateHandle,
+ createAbortableOperation,
+ snapshotAbortTimers,
+ type AbortableOperation,
+ type AbortableOperationInput,
+ type AbortRace,
+ type AbortTerminalReason,
+ type AbortTimerSnapshot,
+} from "./abortable-operation.ts";
+export { assertBoundedCapacity } from "./bounded-capacity.ts";
+export {
+ createBrowserLifecycleRuntime,
+ type BrowserLifecycleEvent,
+ type BrowserLifecycleRuntime,
+ type BrowserLifecycleSnapshot,
+} from "./browser-lifecycle.ts";
+export {
+ createBrowserMutationIntentFactory,
+ type BrowserMutationIntentFactoryDependencies,
+} from "./browser-mutation-intent-factory.ts";
+export { systemClock } from "./system-clock.ts";
+```
+
+---
+
+### 3.5 `src/adapters/query-cache/index.ts`
+
+파일 5개, 파일마다 팩토리 1~3개. 전부 공개(4개는 bootstrap이 직접, `createCursorPaginationRuntime`·`createQueryCacheAdapter`는 동급 팩토리).
+
+| 심볼 | 위치 | 근거 |
+|---|---|---|
+| `createConditionalValidatorStore` | `conditional-validator-store.ts:55` | `src/bootstrap/runtime-adapters.ts:26` |
+| `ConditionalValidatorBinding` / `ConditionalValidatorStore` | `:3` / `:10` | 위 팩토리의 반환·요소 타입 |
+| `createCursorPaginationRuntime` | `cursor-pagination-runtime.ts:49` | 동급 런타임 팩토리(오늘 소비자는 `tests/`만) |
+| `createServerStateScopeRuntime` | `server-state-scope-runtime.ts:34` | `src/bootstrap/runtime-adapters.ts:25` |
+| `ScopeResetParticipant` / `ServerStateScopeDependencies` | `:19` / `:26` | 위 팩토리의 인자 타입 |
+| `createTanStackCacheCoordinator` | `tanstack-cache-coordinator.ts:33` | `src/bootstrap/runtime-adapters.ts:22` |
+| `TanStackCacheCoordinatorDependencies` | `:21` | 인자 타입 |
+| `createQueryClient` | `tanstack-query-cache.ts:21` | `src/bootstrap/runtime-adapters.ts:24`, `.storybook/preview.tsx:6` |
+| `createQueryCacheAdapter` | `:59` | 동급 팩토리(`QueryCachePort` 구현) |
+| `QUERY_CACHE_DEFAULTS` | `:12` | 선언된 기본값 |
+| `QueryCacheDependencies` | `:8` | 인자 타입 |
+
+내부: 없음.
+
+> 주의: 이 그룹은 `.dependency-cruiser.json:184`가 명시적으로 이름 붙인 미해결 간선의 출발점이다 — `tanstack-cache-coordinator.ts:19`가 `../cross-context-invalidation/index.ts`에서 협력자 타입 2개를 읽는다. 배럴 작업은 이 간선을 건드리지 않는다(어댑터→어댑터 간선이므로 새 규칙 범위 밖).
+
+```ts
+export {
+ createConditionalValidatorStore,
+ type ConditionalValidatorBinding,
+ type ConditionalValidatorStore,
+} from "./conditional-validator-store.ts";
+export { createCursorPaginationRuntime } from "./cursor-pagination-runtime.ts";
+export {
+ createServerStateScopeRuntime,
+ type ScopeResetParticipant,
+ type ServerStateScopeDependencies,
+} from "./server-state-scope-runtime.ts";
+export {
+ createTanStackCacheCoordinator,
+ type TanStackCacheCoordinatorDependencies,
+} from "./tanstack-cache-coordinator.ts";
+export {
+ createQueryCacheAdapter,
+ createQueryClient,
+ QUERY_CACHE_DEFAULTS,
+ type QueryCacheDependencies,
+} from "./tanstack-query-cache.ts";
+```
+
+---
+
+### 3.6 `src/adapters/service-worker/index.ts`
+
+#### 제약 하나 먼저
+
+`tsconfig.app.json:14-19`의 `exclude`에 `src/adapters/service-worker/service-worker-entry.ts`가 들어 있다. **배럴은 이 파일을 절대 참조하면 안 된다** — 참조하면 app 타입체크가 제외된 파일을 끌어들인다. 다행히 `service-worker-entry.ts`는 export가 0개라(`grep -n '^export ' → 없음`) 넣을 것도 없다.
+
+| 파일 | 판정 | 근거 |
+|---|---|---|
+| `service-worker-page-controller.ts` | 공개 | `src/bootstrap/register-service-worker.ts:5`가 `createServiceWorkerPageController`를 씀 |
+| `service-worker-lifecycle.ts` | 공개 | 워커 realm 진입점(`service-worker-entry.ts:11`)이 합성하는 런타임. 그룹 바깥(워커 번들·tests)이 실제 소비자 |
+| `service-worker-protocol.ts` | 공개 | 페이지↔워커 메시지 코덱. 양쪽 realm이 공유하는 어휘 |
+| `service-worker-removal.ts` | **내부** | 소비자는 `service-worker-page-controller.ts:20`(그룹 내) + `tests/`뿐 |
+| `service-worker-static-assets.ts` | **내부** | 소비자는 `service-worker-lifecycle.ts:17`(그룹 내) + `tests/`뿐 |
+| `service-worker-entry.ts` | 대상 아님 | export 0개 + `tsconfig.app.json` 제외 |
+
+내부(테스트 전용)로 남아 깊은 경로를 유지할 심볼: `removeOwnedRegistration`, `purgeOwnedResources`, `isOwnedRegistration`, `expectedServiceWorkerUrls`(`service-worker-removal.ts:33,65,89,138`), `installStaticAssets`, `classifyFetch`, `validateStaticAssetManifest`, `selectCachesToDelete`(`service-worker-static-assets.ts:35,85,119,377`).
+
+```ts
+export {
+ createServiceWorkerRuntime,
+ type WorkerClientLike,
+ type WorkerRuntimeConfig,
+ type WorkerScopeLike,
+} from "./service-worker-lifecycle.ts";
+export {
+ createServiceWorkerPageController,
+ type ActivationBlocker,
+ type PageControllerDependencies,
+} from "./service-worker-page-controller.ts";
+export {
+ createNonceRegistry,
+ createServiceWorkerMessage,
+ parseServiceWorkerMessage,
+ type ParsedMessage,
+} from "./service-worker-protocol.ts";
+```
+
+---
+
+### 3.7 `src/adapters/storage/index.ts`
+
+#### 판정: 최상위 배럴은 서브폴더를 재수출하지 **않는다**. 서브폴더 배럴이 곧 경계다.
+
+`browser-transfer/index.ts:1-3`과 `realtime/index.ts:56-58`의 선례를 따라 `export * from "./indexeddb/index.ts"`를 넣고 싶어지지만, **storage에서는 그게 게이트를 깬다.**
+
+**근거 (결정적) — 제거 드릴이 서브폴더만 삭제한다.**
+`scripts/test-browser-file-storage-runtime-removal.ts:23-34`:
+
+```ts
+const runtimePaths = [
+ ...
+ "src/adapters/storage/indexeddb",
+ "src/adapters/storage/opfs",
+ ...
+] as const;
+```
+
+이 스크립트는 fixture 트리에서 위 경로를 `rm -rf`한 뒤(`:56-61`) `assertNoRuntimeImports(fixtureRoot, runtimeSourceRoots, ...)`를 호출한다(`:129-133`). 그 함수는 `scripts/lib/removal-fixture.ts:251-260`:
+
+```ts
+const graph = await runtimeImportGraph(root, runtimeSourceRoots);
+if (graph.importingFiles.length > 0) {
+ throw new Error(`Removed ${capability} runtime is still imported by: ...`);
+}
+```
+
+즉 `src/adapters/storage/index.ts`가 `./indexeddb/index.ts`를 재수출하면, 삭제 후에도 그 파일이 살아남아 삭제된 런타임을 import하는 상태가 되어 드릴이 **즉시 예외로 실패**한다. 그 뒤에 이어지는 `check:types` / `lint` / `check:architecture` / `build`(`:135-143`)까지 전부 못 간다.
+
+**대조 — realtime·browser-transfer는 왜 괜찮은가.**
+`scripts/test-realtime-runtime-removal.ts:21-31`은 `src/adapters/realtime` **폴더 전체**를 지운다. `browser-file-storage` 드릴도 `src/adapters/browser-transfer` 전체를 지운다(`test-browser-file-storage-runtime-removal.ts:28`). 배럴이 폴더와 함께 사라지므로 문제가 없다. **storage만 부분 삭제 대상**이다 — 최상위 `browser-storage-adapter.ts`(localStorage/sessionStorage KV)는 남고 IndexedDB·OPFS 런타임만 빠진다.
+
+**따라서:**
+- `src/adapters/storage/index.ts` = 최상위 파일들만.
+- `src/adapters/storage/indexeddb/index.ts`, `src/adapters/storage/opfs/index.ts` = 각 제거 가능 런타임의 공개 경계. **이미 존재하고 이미 명명 재수출이다.** 새로 만들 필요 없다.
+- §5의 게이트 정규식은 그래서 1단계 중첩 `index.ts`까지 배럴로 인정해야 한다.
+
+| 심볼 | 위치 | 판정 | 근거 |
+|---|---|---|---|
+| `createBrowserStorageAdapter` | `browser-storage-adapter.ts:35` | 공개 | `src/bootstrap/runtime-adapters.ts:27` |
+| `BrowserStorageDependencies` | `:20` | 공개 | 팩토리 인자 타입. 필드가 전부 원시형/포트라 codec 타입을 노출하지 않는다(`:20-27` 확인) |
+| `browser-storage-codec.ts` 전체 (`DEFAULT_BROWSER_STORAGE_MAX_SERIALIZED_BYTES:1`, `encodeBrowserStorageEnvelope:31`, `decodeBrowserStorageEnvelope:57`, `assertValidBrowserStorageByteLimit:88`, `BrowserStorageEnvelope:11`, `BrowserStorageCodecFailure:17`, `BrowserStorageCodecResult:22`) | — | **내부** | 유일한 소비자가 `browser-storage-adapter.ts:14-18`(그룹 내). `src/`·`tests/` 어디서도 직접 import 없음 |
+
+```ts
+export {
+ createBrowserStorageAdapter,
+ type BrowserStorageDependencies,
+} from "./browser-storage-adapter.ts";
+```
+
+> **서브배럴 보완 권고 (별건, 이 문서 범위 밖)**
+> `tests/unit/opfs-byte-store.test.ts:25,28`가 `OPFS_WORKER_PROTOCOL_VERSION`(`opfs/opfs-worker-protocol.ts:23`), `PreparePhysicalObjectRequest`(`:179`), `writeWithSyncAccessHandle`(`opfs/opfs-worker-runtime.ts:1363`)를 쓰는데 이 셋은 `opfs/index.ts`에 없다. 테스트를 배럴로 옮길 때(§4.2) 함께 결정해야 한다 — 올리거나, 내부로 확정하고 테스트가 깊은 경로를 유지하거나.
+
+---
+
+### 3.8 `src/adapters/http/index.ts`
+
+#### V2 / V3 판정
+
+**V3(`createContractHttpExecutor`, `http-execution-v3.ts:377`)가 권장 경로.** V2(`createHttpClient`, `client.ts:138`)는 legacy 보존.
+
+근거:
+1. `src/adapters/http/client.ts:121`에 `LegacyHttpInput`이라는 타입이 있고, 공개 시그니처 `HttpClient.execute`(`:131-137`)가 그걸 두 번째 인자로 받는다. 파일이 스스로 legacy라고 말한다.
+2. `src/adapters/http/http-execution-v3.ts:45-51` 헤더 주석: "§7–§8. Descriptor-driven HTTP execution. ... the runtime owns bounds, the total deadline, the single retry authority and the effect-certainty verdict." — 계약 기반 실행이 V3에 있다.
+3. 라이브 경로가 V3다. `src/bootstrap/runtime-adapters.ts:423`이 `createContractHttpExecutor`를 조립해 실제 런타임에 넣는다. 반면 V2 래퍼 `createRuntimeHttpClient`(`src/bootstrap/runtime-adapters.ts:163`)의 유일한 호출자는 `tests/unit/runtime-adapters.test.ts:371`이다 (`grep -rn 'createRuntimeHttpClient' src/ tests/` 결과 3줄: 정의 1 + 테스트 2).
+4. V3 타입은 이미 feature 경계를 넘는다: `src/features/reference-feature/adapters/create-reference-feature-input.ts:9`가 `HttpExecutionOutcome`를 import한다.
+
+둘 다 배럴에 넣되 **블록 순서로 V3를 먼저 두고 주석으로 표시**한다.
+
+#### 공개 표면
+
+| 파일 | 판정 | 근거 |
+|---|---|---|
+| `http-execution-v3.ts` | 공개 | `src/bootstrap/runtime-adapters.ts:10,11`, `src/features/reference-feature/adapters/create-reference-feature-input.ts:9` |
+| `client.ts` | 공개(legacy) | `src/bootstrap/runtime-adapters.ts:8` |
+| `http-contract-bridge.ts` | `CredentialPatchOutcome`만 공개 | `http-execution-v3.ts:292`의 공개 시그니처 `attachCredentials(...): Promise \| CredentialPatchOutcome`에 이름으로 등장 → bootstrap이 그 콜백을 구현한다(`src/bootstrap/runtime-adapters.ts:434` 부근) |
+| `request-builder.ts` | `OperationRequestInput`만 공개 | `client.ts:133`의 공개 시그니처 `execute(request: string \| OperationRequestInput, ...)`에 이름으로 등장 |
+| `bounded-body-reader.ts` | **내부** | 소비자는 `bounded-json.ts:1`, `http-execution-v3.ts:18-20`(그룹 내) + `tests/` |
+| `bounded-json.ts` | **내부** | 소비자는 `client.ts:45`(그룹 내) + `tests/` |
+| `http-effect-certainty.ts` | **내부** | 소비자는 `http-execution-v3.ts:38-42`(그룹 내) + `tests/` |
+| `retry-policy.ts` | **내부** | 소비자는 `client.ts:9`, `http-execution-v3.ts:43`(그룹 내) + `tests/` |
+| `schema-registry.ts` | **내부** | 소비자는 `client.ts:14`(그룹 내) + `tests/` |
+| `resource-mapper.ts` | **내부** | 소비자는 `client.ts:8`(그룹 내) + `tests/` |
+| `http-contract-bridge.ts` 나머지 11개 | **내부** | 그룹 내 + `tests/` |
+| `request-builder.ts` 나머지 2개 (`buildRequestTarget:28`, `RequestTargetResult:14`) | **내부(테스트 전용)** | `tests/`만 |
+
+```ts
+/**
+ * §7–§8. 권장 경로는 V3 계약 실행기(`createContractHttpExecutor`)다. 설치된
+ * 계약과 타입 입력을 받아 상한·전체 데드라인·재시도 권한·효과 확실성 판정을
+ * 런타임이 소유한다.
+ */
+export {
+ createContractHttpExecutor,
+ type AuthIntegrationFailureReason,
+ type AuthOperationContext,
+ type CancellationOwner,
+ type ContractHttpExecutor,
+ type ContractHttpExecutorDependencies,
+ type HttpContractViolation,
+ type HttpContractViolationKind,
+ type HttpEffectCertainty,
+ type HttpExecutionContext,
+ type HttpExecutionObservation,
+ type HttpExecutionOutcome,
+ type HttpTransportFailure,
+ type SafeResponseMetadata,
+} from "./http-execution-v3.ts";
+/** V3 `attachCredentials` 콜백이 반환해야 하는 결과 타입. */
+export type { CredentialPatchOutcome } from "./http-contract-bridge.ts";
+/**
+ * V2 legacy. operationId + `LegacyHttpInput`으로 호출하는 범용 클라이언트다.
+ * 새 코드는 위의 V3 실행기를 쓴다. 남아 있는 이유는 계약이 아직 없는
+ * 오퍼레이션을 위한 이행 경로이기 때문이다.
+ */
+export {
+ createHttpClient,
+ type HttpClient,
+ type HttpClientDependencies,
+ type HttpFailure,
+ type HttpResult,
+ type LegacyHttpInput,
+ type Scheduler,
+} from "./client.ts";
+/** V2 `HttpClient.execute`의 첫 인자 타입. */
+export type { OperationRequestInput } from "./request-builder.ts";
+```
+
+---
+
+## 4. 호출처 치환 목록
+
+### 4.1 `src/` — 전수 (17줄)
+
+측정: §2의 grep. 17줄 중 2줄은 이미 배럴 경유라 변경 없음. 실제 치환 대상 **15줄**.
+
+| # | 파일:줄 | 현재 specifier | 바뀔 specifier | 비고 |
+|---:|---|---|---|---|
+| 1 | `src/bootstrap/main.tsx:3` | `../adapters/diagnostics/bounded-diagnostics.ts` | `../adapters/diagnostics/index.ts` | `recordBootFailure` |
+| 2 | `src/bootstrap/optional-runtime-host.ts:4` | `../adapters/platform/browser-lifecycle.ts` | `../adapters/platform/index.ts` | 블록 시작은 `:1` |
+| 3 | `src/bootstrap/register-service-worker.ts:5` | `../adapters/service-worker/service-worker-page-controller.ts` | `../adapters/service-worker/index.ts` | `createServiceWorkerPageController` |
+| 4 | `src/bootstrap/runtime-adapters.ts:6` | `../adapters/auth/external-session-adapter.ts` | `../adapters/auth/index.ts` | 블록 시작 `:1` |
+| 5 | `src/bootstrap/runtime-adapters.ts:7` | `../adapters/diagnostics/bounded-diagnostics.ts` | `../adapters/diagnostics/index.ts` | `createDiagnosticsAdapter` |
+| 6 | `src/bootstrap/runtime-adapters.ts:8` | `../adapters/http/client.ts` | `../adapters/http/index.ts` | **7번과 한 블록으로 합칠 것** |
+| 7 | `src/bootstrap/runtime-adapters.ts:12` | `../adapters/http/http-execution-v3.ts` | `../adapters/http/index.ts` | 블록 시작 `:9` |
+| 8 | `src/bootstrap/runtime-adapters.ts:20` | `../adapters/cross-context-invalidation/index.ts` | (변경 없음) | 이미 배럴 |
+| 9 | `src/bootstrap/runtime-adapters.ts:23` | `../adapters/query-cache/tanstack-cache-coordinator.ts` | `../adapters/query-cache/index.ts` | 블록 시작 `:21`. **9~12를 한 블록으로 합칠 것** |
+| 10 | `src/bootstrap/runtime-adapters.ts:24` | `../adapters/query-cache/tanstack-query-cache.ts` | `../adapters/query-cache/index.ts` | `createQueryClient` |
+| 11 | `src/bootstrap/runtime-adapters.ts:25` | `../adapters/query-cache/server-state-scope-runtime.ts` | `../adapters/query-cache/index.ts` | `createServerStateScopeRuntime` |
+| 12 | `src/bootstrap/runtime-adapters.ts:26` | `../adapters/query-cache/conditional-validator-store.ts` | `../adapters/query-cache/index.ts` | `createConditionalValidatorStore` |
+| 13 | `src/bootstrap/runtime-adapters.ts:27` | `../adapters/storage/browser-storage-adapter.ts` | `../adapters/storage/index.ts` | `createBrowserStorageAdapter` |
+| 14 | `src/bootstrap/runtime-adapters.ts:28` | `../adapters/platform/browser-mutation-intent-factory.ts` | `../adapters/platform/index.ts` | `createBrowserMutationIntentFactory` |
+| 15 | `src/bootstrap/runtime-adapters.ts:29` | `../adapters/telemetry/best-effort-telemetry.ts` | `../adapters/telemetry/index.ts` | `createTelemetryAdapter` |
+| 16 | `src/bootstrap/server-state-generation-store.ts:3` | `../adapters/cross-context-invalidation/index.ts` | (변경 없음) | 이미 배럴 |
+| 17 | `src/features/reference-feature/adapters/create-reference-feature-input.ts:9` | `../../../adapters/http/http-execution-v3.ts` | `../../../adapters/http/index.ts` | `type HttpExecutionOutcome` |
+
+**작업 순서 주의.** `runtime-adapters.ts`는 12줄이 한 덩어리(`:6`~`:29`)다. 6·7을 합치고 9~12를 합치면 그 아래 줄 번호가 전부 밀린다. **아래에서 위로 편집**하거나 `:1`~`:29` 블록을 한 번에 다시 쓴다.
+
+**선택 사항 (게이트 범위 밖, 일관성 목적).** `check:architecture`는 `src`만 스캔하므로(`scripts/check-architecture.ts:69`, `:116-123`) 아래 두 줄은 강제되지 않는다. 같은 커밋에서 정리하는 걸 권한다.
+
+| 파일:줄 | 현재 | 바뀔 것 |
+|---|---|---|
+| `.storybook/preview.tsx:5` | `../src/adapters/auth/external-session-adapter.ts` | `../src/adapters/auth/index.ts` |
+| `.storybook/preview.tsx:6` | `../src/adapters/query-cache/tanstack-query-cache.ts` | `../src/adapters/query-cache/index.ts` |
+
+**곁다리 정리 기회 하나.** `src/bootstrap/runtime-adapters.ts:65`가 `type HttpClientDependencies = Parameters[0];`로 타입을 역추출한다. 배럴이 `HttpClientDependencies`를 직접 내보내므로 이 줄은 지우고 import로 대체할 수 있다. 필수는 아니다.
+
+### 4.2 `tests/` — 그룹별 집계와 권고
+
+측정(2026-09-16, `develop` `5434760`):
+
+```
+grep -rnE 'from "[^"]*adapters/<16개 그룹>/' tests/ --include='*.ts' --include='*.tsx' | grep -v '^tests/fixtures/'
+```
+
+**166줄 / 83개 파일.** (`tests/fixtures` 포함 시 169줄. 지시문의 184와 다른데, `tests/fixtures`는 `.dependency-cruiser.json:208`에서 제외 대상이고 그 안의 `indexeddb-repository.ts` 같은 경로는 존재하지 않는 금지 recipe fixture다.)
+
+| 그룹 | 줄 수 | 배럴 존재 | 배럴 경유 |
+|---|---:|---|---:|
+| browser-transfer | 26 | 기존 | 0 |
+| realtime | 24 | 기존 | 1 |
+| http | 22 | **신규** | 0 |
+| storage | 20 | **신규**(+서브배럴 2) | 0 |
+| web-push | 17 | 기존 | 0 |
+| browser-files | 17 | 기존 | 1 |
+| query-cache | 9 | **신규** | 0 |
+| auth | 9 | **신규** | 0 |
+| browser-file-storage | 5 | 기존 | 0 |
+| service-worker | 4 | **신규** | 0 |
+| platform | 3 | **신규** | 0 |
+| browser-rpc | 3 | 기존 | 2 |
+| diagnostics | 2 | **신규** | 0 |
+| cross-context-invalidation | 2 | 기존 | 2 |
+| cache-storage | 2 | 기존 | 0 |
+| telemetry | 1 | **신규** | 0 |
+| **합계** | **166** | | **6** |
+
+배럴 경유 6줄의 정확한 위치:
+`tests/unit/browser-file-runtime.test.ts:13`, `tests/unit/browser-rpc/browser-rpc-remediation.test.ts:9`, `tests/unit/browser-rpc/browser-rpc-runtime.test.ts:11`, `tests/unit/cross-tab-invalidation.test.ts:21`, `tests/unit/realtime/realtime-reconnect-coordinator.test.ts:20`, `tests/unit/tanstack-cache-coordinator.test.ts:7`.
+
+#### 권고: 한꺼번에 옮기지 않는다. 파일을 건드릴 때 그 파일 것만 옮긴다.
+
+이유 셋:
+
+1. **게이트가 강제하지 않는다.** `check:architecture`는 `src`만 본다(`scripts/check-architecture.ts:69`, `:116-123`). 테스트를 지금 옮겨도 검증되는 게 없고, 안 옮겨도 깨지는 게 없다. 강제되지 않는 대량 변경은 리뷰 비용만 남는다.
+2. **테스트의 절반 이상이 내부 심볼을 쓴다.** 예: `tests/unit/opfs-byte-store.test.ts:25,28`의 `PreparePhysicalObjectRequest`·`writeWithSyncAccessHandle`은 `opfs/index.ts`에 없다. http의 `retry-policy`·`schema-registry`·`bounded-body-reader` 테스트도 마찬가지로 §3.8에서 내부로 판정한 심볼을 직접 겨눈다. 일괄 치환은 곧 "배럴에 내부 심볼을 밀어넣자"는 압력이 되고, 그러면 배럴이 경계가 아니라 재수출 덤프가 된다.
+3. **내부 심볼을 직접 겨누는 단위 테스트는 그래도 된다.** 배럴 규칙은 "그룹 바깥 **프로덕션 코드**는 배럴만"이지 "아무도 내부를 못 본다"가 아니다. 테스트는 구현 계약을 검증하는 게 일이다.
+
+**실행 규칙 (문서에 남길 문장)**
+
+> `tests/` 아래 어댑터 import는 배럴로 일괄 이관하지 않는다.
+> 어떤 테스트 파일을 **다른 이유로** 수정하거나 분할할 때, 그 파일이 쓰는 심볼이 해당 그룹 배럴에 있으면 그 파일 안에서만 배럴 경로로 바꾼다.
+> 배럴에 없는 심볼이면 깊은 경로를 유지한다. 배럴에 추가하고 싶으면 §2 기준으로 "공개"임을 논증하는 게 먼저다.
+
+우선순위를 굳이 매긴다면: `auth`(9줄, 전부 공개 심볼), `diagnostics`(2줄), `telemetry`(1줄), `query-cache`(9줄) — 이 넷은 배럴이 그룹 표면을 100% 덮으므로 기계적 치환이 가능하다. 21줄. `http`·`storage`·`service-worker`는 내부 심볼 비중이 커서 파일 단위로만 접근한다.
+
+---
+
+## 5. 게이트로 강제하기
+
+### 5.1 추가할 규칙 (그대로 붙여넣기)
+
+`.dependency-cruiser.json`의 `forbidden` 배열에서 **`adapters-do-not-know-other-concrete-adapters` 바로 다음, `no-circular-dependencies` 앞**에 넣는다 (현재 `:193`과 `:194` 사이).
+
+```json
+ {
+ "name": "adapter-groups-are-reached-through-their-barrel",
+ "comment": "docs/architecture/layers.md §4: 어댑터 그룹의 공개 표면은 그 그룹의 `index.ts`다. 그룹 바깥(bootstrap, features, presentation)은 배럴만 import한다. 배럴이 없던 시절 bootstrap은 어댑터 내부 파일 15곳을 직접 겨눴고, 그래서 어떤 파일이 공개이고 어떤 파일이 내부 헬퍼인지 아무 데도 적혀 있지 않았다. 출발점에서 `src/adapters`를 뺀 이유는 어댑터끼리의 간선은 바로 위 `adapters-do-not-know-other-concrete-adapters`가 이미 담당하고, 커널(`platform/**`)은 파일 단위로 공유되기 때문이다 — `scripts/check-adapter-inventory.ts`가 네 소비자에게 `platform/abortable-operation.ts`로 해석되는 specifier를 직접 요구한다. 도착점에서 1단계 중첩 `index.ts`를 허용한 이유는 `storage/indexeddb`와 `storage/opfs`가 각자 독립적으로 제거 가능한 런타임이고(scripts/test-browser-file-storage-runtime-removal.ts), 그래서 각자의 배럴이 곧 경계이기 때문이다.",
+ "severity": "error",
+ "from": {
+ "path": "^src/",
+ "pathNot": "^src/adapters/"
+ },
+ "to": {
+ "path": "^src/adapters/[^/]+/",
+ "pathNot": "^src/adapters/[^/]+/(?:[^/]+/)?index\\.ts$"
+ }
+ },
+```
+
+규칙 형태 적합성: `scripts/check-architecture.ts:799-815`의 `validateArchitectureRules`는 `from`에 `path`/`pathNot`, `to`에 `path`/`pathNot`/`circular`만 허용한다. 이 규칙은 그 안에 있다. 정규식은 `new RegExp(pattern, "u")`로 평가되므로(`:739`, `:747`) 비캡처 그룹 `(?:...)`도 문제없다. `$1` 역참조는 쓰지 않았다.
+
+### 5.2 이 규칙이 무엇을 잡고 무엇을 안 잡는가 — 실측
+
+레포의 실제 import 그래프(`src` 전체, 상대 specifier 해석)에 규칙을 그대로 돌려본 결과:
+
+**잡는 것 — 오늘 기준 위반 15건** (= §4.1의 치환 대상 15줄과 정확히 일치)
+
+```
+src/bootstrap/main.tsx:3 -> src/adapters/diagnostics/bounded-diagnostics.ts
+src/bootstrap/optional-runtime-host.ts:4 -> src/adapters/platform/browser-lifecycle.ts
+src/bootstrap/register-service-worker.ts:5 -> src/adapters/service-worker/service-worker-page-controller.ts
+src/bootstrap/runtime-adapters.ts:6 -> src/adapters/auth/external-session-adapter.ts
+src/bootstrap/runtime-adapters.ts:7 -> src/adapters/diagnostics/bounded-diagnostics.ts
+src/bootstrap/runtime-adapters.ts:8 -> src/adapters/http/client.ts
+src/bootstrap/runtime-adapters.ts:12 -> src/adapters/http/http-execution-v3.ts
+src/bootstrap/runtime-adapters.ts:23 -> src/adapters/query-cache/tanstack-cache-coordinator.ts
+src/bootstrap/runtime-adapters.ts:24 -> src/adapters/query-cache/tanstack-query-cache.ts
+src/bootstrap/runtime-adapters.ts:25 -> src/adapters/query-cache/server-state-scope-runtime.ts
+src/bootstrap/runtime-adapters.ts:26 -> src/adapters/query-cache/conditional-validator-store.ts
+src/bootstrap/runtime-adapters.ts:27 -> src/adapters/storage/browser-storage-adapter.ts
+src/bootstrap/runtime-adapters.ts:28 -> src/adapters/platform/browser-mutation-intent-factory.ts
+src/bootstrap/runtime-adapters.ts:29 -> src/adapters/telemetry/best-effort-telemetry.ts
+src/features/reference-feature/adapters/create-reference-feature-input.ts:9 -> src/adapters/http/http-execution-v3.ts
+```
+
+§4.1을 적용하면 이 15건이 0이 된다. **즉 배럴 8개 생성 + import 15줄 치환 + 규칙 추가를 한 커밋에 넣어야 `check:architecture`가 계속 PASS한다.** 순서를 나누면 중간 커밋이 빨간불이 된다.
+
+**안 잡는 것 (의도대로)**
+
+| 경우 | 건수 | 왜 안 잡히나 |
+|---|---:|---|
+| 같은 그룹 내부 파일끼리 | 229건 중 189건 | `from.pathNot: "^src/adapters/"`가 출발점을 제외 |
+| 어댑터 → 커널 (`platform/**`, `browser-file-storage/result.ts`, `cross-context-invalidation/index.ts`) | 40건 | 같은 이유. 이 간선들은 `adapters-do-not-know-other-concrete-adapters`(`:183-193`)의 `pathNot` carve-out이 계속 담당 |
+| 바깥 → 배럴 (이미 합격) | 2건 | `to.pathNot`이 `index.ts`를 면제. `src/bootstrap/runtime-adapters.ts:20`, `src/bootstrap/server-state-generation-store.ts:3` |
+| `tests/**` | 166줄 전부 | 스캔 범위 밖 (아래 §5.3) |
+| `src/presentation/adapters/query/**` | — | 경로가 `src/presentation/...`이라 `to.path` `^src/adapters/`에 매칭 자체가 안 됨 |
+
+세 가지 질문에 대한 명시적 답:
+
+1. **같은 그룹 내부 import — 허용된다.** 출발점이 `^src/adapters/`이면 규칙이 아예 평가되지 않는다.
+2. **커널 접근 — 허용된다.** `platform/`은 위와 같은 이유로 통과. `browser-file-storage/result.ts`와 `cross-context-invalidation/index.ts`도 출발점이 어댑터이므로 통과. (참고: `cross-context-invalidation/index.ts`는 마침 `index.ts`라 도착점 면제에도 걸린다 — 이중으로 안전.)
+3. **`tests/`는 대상이 아니다.** `scripts/check-architecture.ts:69`가 `sourceRoot = resolve(projectRoot, "src")`이고 `:116-123`이 `depcruise src --config ...`를 돌린다. 두 그래프 모두 `src`만 본다.
+
+### 5.3 기존 규칙과의 충돌 검토
+
+`.dependency-cruiser.json` 전체(18개 규칙)를 읽고 대조했다.
+
+| 기존 규칙 | 줄 | 충돌 |
+|---|---:|---|
+| `domain-is-framework-neutral` | 4 | 없음. domain→adapters는 어차피 전면 금지 |
+| `application-does-not-know-concrete-runtime` | 13 | 없음. 동일 |
+| `presentation-does-not-know-adapters` | 24 | 없음. presentation→adapters 전면 금지가 상위 |
+| `page-templates-own-layout-only` | 34 | 없음 |
+| `icon-vendor-is-facade-only` | 44 | 없음 (외부 패키지 대상) |
+| `adapters-do-not-know-presentation` | 54 | 없음 (방향 반대) |
+| `feature-*` 4개 | 64–103 | 없음. feature adapters→`src/adapters`는 이 규칙들이 막지 않으므로 새 규칙이 유효하게 작동 (실측 15번째 위반이 그 경우) |
+| `concrete-adapters-compose-only-in-bootstrap` | 104 | 없음. `src/(domain\|application\|presentation\|contracts)` → `^src/adapters` 전면 금지. 새 규칙은 그 나머지(`bootstrap`, `features`)에서만 실효 |
+| `external-contract-package-single-import-path` | 114 | 없음 |
+| `presentation-does-not-fetch-directly` | 126 | 없음. `^src/adapters/(http\|realtime\|service-worker\|web-worker\|storage)` 를 겨누는데 presentation은 이미 전면 금지 |
+| `generic-worker-has-no-network-or-credentials` | 137 | 없음. `^src/adapters/web-worker` 출발이라 새 규칙 출발점 제외와 겹칠 뿐. (`src/adapters/web-worker`는 현재 존재하지 않는 예방 규칙) |
+| `service-worker-entry-is-not-page-code` | 148 | 없음 |
+| `contracts-do-not-know-application` | 159 | 없음 |
+| `generic-presentation-does-not-compose-the-product` | 170 | 없음 |
+| **`adapters-do-not-know-other-concrete-adapters`** | **183** | **없음 — 상보적.** 저쪽은 `from: ^src/adapters/([^/]+)/`, 이쪽은 `from.pathNot: ^src/adapters/`. 정확히 반대 집합이라 이중 판정이 생기지 않는다 |
+| `no-circular-dependencies` | 194 | 주의 필요 → 아래 |
+
+**순환 검토.** `no-circular-dependencies`(`:194-201`)가 error다. 배럴 도입이 순환을 만들려면 그룹 안 파일이 자기 그룹 `index.ts`를 import해야 한다.
+
+```
+grep -rn 'from "\./index\.ts"\|from "\.\./index\.ts"' src/adapters/ --include='*.ts' → 0건
+```
+
+또 `src/bootstrap/**`는 어댑터에서 import되지 않는다(`adapters-do-not-know-presentation`이 `^src/(presentation|bootstrap)`을 막음, `:54-62`). 따라서 **새 순환 없음.** 단 §3.7의 판정을 뒤집어 `storage/index.ts`가 서브배럴을 재수출하면, 순환은 아니지만 제거 드릴이 깨진다(§6 위험 2).
+
+### 5.4 ESLint 쪽은 손대지 않는다
+
+`eslint.config.ts:9-34`의 `layerPatterns`는 레이어 단위(`**/adapters/**`)만 다루고 그룹 내부 경로를 구분하지 않는다. 배럴 규칙을 여기에도 복제하면 두 곳에서 같은 사실을 관리하게 된다. dependency-cruiser 쪽 한 곳만 유지한다.
+
+---
+
+## 6. 위험과 부수 작업
+
+### 위험 1 (최대) — 번들 예산
+
+`package.json`에 `"sideEffects"` 필드가 없다. 번들러는 모든 모듈을 부작용 있을 수 있는 것으로 보고, 배럴 재수출을 통해 들어온 모듈을 트리셰이킹에서 살려둘 수 있다.
+
+구체적으로 위험한 세 곳:
+- `src/bootstrap/register-service-worker.ts`가 `service-worker/index.ts`를 import하면 `service-worker-lifecycle.ts`(666줄) → `service-worker-static-assets.ts`(394줄)가 **페이지 번들 그래프**에 들어온다. 지금은 `service-worker-page-controller.ts`(494줄) → `service-worker-protocol.ts` + `service-worker-removal.ts`만 들어온다.
+- `src/bootstrap/runtime-adapters.ts`가 `http/index.ts`를 import하면 V2·V3가 항상 함께 들어온다 (`client.ts` 1107줄 + `http-execution-v3.ts` 1602줄). 지금도 둘 다 import하긴 한다.
+- `query-cache/index.ts`는 `cursor-pagination-runtime.ts`(234줄)를 추가로 끌어온다.
+
+예산: `config/performance/budgets.json`의 `bundle.initialJsGzipBytes = 204800`. `check:bundle`(`scripts/check-bundle.ts:47`)이 초과 시 실패한다.
+
+**대응 (권장 순서)**
+1. 배럴 커밋에서 `corepack pnpm check:bundle`을 반드시 돌린다. 이 문서에서는 실행하지 않았다.
+2. 넘치면 `package.json`에 `"sideEffects": false`를 추가한다. `src/adapters` 아래에 최상위 부작용이 있는지 먼저 확인해야 한다(`presentation/styles/theme.css` 같은 CSS import는 `"sideEffects": ["*.css"]` 형태로 보존).
+3. 그래도 넘치면 `service-worker/index.ts`에서 `service-worker-lifecycle.ts` 블록을 빼고, 워커 realm은 파일 직접 import를 유지한다(`platform`과 같은 논리 — realm이 다르면 문도 다르다).
+
+### 위험 2 — `storage/index.ts`에 서브배럴을 넣고 싶은 충동
+
+`browser-transfer`/`realtime` 선례만 보고 `export * from "./indexeddb/index.ts"`를 넣으면 `test:browser-file-storage-removal`이 `assertNoRuntimeImports` 단계에서 예외로 죽는다(§3.7). 배럴 파일에 그 이유를 주석으로 못 박아 두는 걸 권한다.
+
+### 위험 3 — `check:adapter-inventory`가 새 파일 8개를 거부한다
+
+`scripts/check-adapter-inventory.ts:58-74`가 `git ls-files src/adapters` 결과와 `docs/reviews/adapters/INVENTORY.md`의 행 목록을 **정확히 일치**시키고, `합계: **N/N**` 숫자도 파일 수와 같아야 한다.
+
+**같은 커밋에서 해야 할 일:**
+1. 새 `index.ts` 8개를 `git add` 한다 (추적되지 않으면 `git ls-files`에 안 잡혀서 오히려 통과하지만, 커밋하는 순간 깨진다).
+2. `docs/reviews/adapters/INVENTORY.md`에 행 8개 추가:
+
+| 추가할 경로 | 상세 리뷰 링크 (같은 그룹 기존 행과 동일하게) |
+|---|---|
+| `src/adapters/auth/index.ts` | `[Network/state](./01-network-and-state.md)` — 기존 행 `:11` |
+| `src/adapters/diagnostics/index.ts` | `[Network/state](./01-network-and-state.md)` — `:58` |
+| `src/adapters/http/index.ts` | `[Network/state](./01-network-and-state.md)` — `:59-68` |
+| `src/adapters/platform/index.ts` | `[Network/state](./01-network-and-state.md)` — `:69-73` |
+| `src/adapters/query-cache/index.ts` | `[Network/state](./01-network-and-state.md)` — `:74-78` |
+| `src/adapters/telemetry/index.ts` | `[Network/state](./01-network-and-state.md)` — `:119` |
+| `src/adapters/service-worker/index.ts` | `[Worker/push](./05-service-worker-and-web-push.md)` — `:96-101` |
+| `src/adapters/storage/index.ts` | `[Storage/files](./03-storage-and-browser-files.md)` — `:102-103` |
+
+3. `docs/reviews/adapters/INVENTORY.md:132`의 `합계: **120/120**` → `합계: **128/128**`.
+
+행 번호(`| N |`)는 `inventoryRows`(`scripts/check-adapter-inventory.ts:33-40`)가 아래 정규식으로 **경로만** 뽑고 순서·연속성은 검사하지 않는다.
+
+```
+^\|\s*\d+\s*\|\s*`([^`]+)`\s*\|
+```
+
+그래도 읽는 사람을 위해 정렬 위치에 끼워 넣고 번호를 다시 매기는 걸 권한다.
+
+### 위험 4 — `tsconfig.app.json` 제외 파일
+
+`tsconfig.app.json:18`이 `src/adapters/service-worker/service-worker-entry.ts`를 제외한다. `service-worker/index.ts`가 이 파일을 참조하면 app 타입체크가 제외 대상을 끌어들인다. §3.6의 배럴은 참조하지 않는다(그 파일은 export가 0개다). 나중에 누가 "완전성"을 이유로 추가하지 않도록 배럴에 주석을 남기는 것도 방법이다.
+
+### 부수 발견 (이 문서 범위 밖, 별도 티켓)
+
+1. `src/adapters/telemetry/best-effort-telemetry.ts:49` — 커널 심볼 재수출. 소비자 0, 같은 파일 `:8`에 import가 이미 있음. 삭제 후보.
+2. `src/adapters/browser-files/index.ts:1-16` — 배럴이 application 포트 타입을 재수출. 어댑터 배럴이 하위 레이어의 통로가 되는 형태.
+3. `src/adapters/storage/opfs/index.ts` — `tests/unit/opfs-byte-store.test.ts:25,28`이 쓰는 `OPFS_WORKER_PROTOCOL_VERSION`·`PreparePhysicalObjectRequest`·`writeWithSyncAccessHandle` 3개가 빠져 있다.
+4. `.dependency-cruiser.json:141` — `^src/adapters/web-worker` 를 겨누는 규칙이 있으나 해당 디렉터리는 존재하지 않는다(어댑터 그룹은 16개). 예방 규칙인지 잔재인지 확인 필요.
+
+---
+
+## 7. 심볼 존재 검증 (기계 대조)
+
+제시한 8개 배럴의 **모든 재수출 심볼 82개**를, 각 대상 파일의 실제 `export` 선언과 이름 단위로 대조했다.
+
+- 대조 방법: 각 `export { ... } from "./X.ts"` 블록의 이름을 뽑아, `src/adapters//X.ts`에서 `^export (declare )?(async function|function|const|let|var|class|type|interface|enum) ` 으로 선언된 이름 집합에 들어 있는지 확인.
+- 결과: **82/82 존재. 누락 0, 오타 0.**
+- 대상 파일 존재 여부도 함께 확인(8개 배럴이 참조하는 소스 파일 16개 전부 존재).
+
+그룹별 심볼 수: auth 7, diagnostics 5, telemetry 5, platform 16, query-cache 13, storage 2, service-worker 11, http 23.
+
+---
+
+## 8. 실행 체크리스트 (한 커밋)
+
+1. `src/adapters/{auth,diagnostics,http,platform,query-cache,service-worker,storage,telemetry}/index.ts` 8개 생성 (§3 내용 그대로).
+2. §4.1 표의 15줄 치환. `src/bootstrap/runtime-adapters.ts`는 아래에서 위로 편집하거나 `:1-29` 블록 전체를 다시 쓴다.
+3. (선택) `.storybook/preview.tsx:5,6` 2줄 치환.
+4. `.dependency-cruiser.json`에 §5.1 규칙 추가 (현재 `:193`과 `:194` 사이).
+5. `docs/reviews/adapters/INVENTORY.md`에 행 8개 추가 + `:132`의 합계를 `128/128`로.
+6. `docs/architecture/layers.md`에 "어댑터 그룹의 공개 표면은 그 그룹의 `index.ts`다. 커널은 예외로 파일 단위로 공유된다"를 한 문단 추가 (`:29-45`의 adapter kernel 절 뒤). 이 문서 규칙들은 실행 규칙과 짝을 이루게 되어 있다(`layers.md:39-45`).
+7. 게이트 실행: `check:architecture` → `check:types:app` → `check:adapter-inventory` → `lint` → `check:bundle` → `test:browser-file-storage-removal`.
+ 마지막 두 개가 이번 변경의 실제 리스크 지점이다(§6 위험 1, 2).
diff --git a/docs/superpowers/specs/2026-09-16-indexeddb-kernel-promotion-design.md b/docs/superpowers/specs/2026-09-16-indexeddb-kernel-promotion-design.md
new file mode 100644
index 0000000..ffde878
--- /dev/null
+++ b/docs/superpowers/specs/2026-09-16-indexeddb-kernel-promotion-design.md
@@ -0,0 +1,1154 @@
+# IndexedDB 커널 승격 — 구체 설계
+
+> 대상 브랜치: `develop` (5434760)
+> 이 문서는 설계만 담는다. 소스는 수정하지 않았고 빌드/테스트도 돌리지 않았다.
+> 모든 주장에 `파일:줄번호` 근거를 달았다. 근거를 못 단 항목은 **미확인**이라고 표시했다.
+
+---
+
+## 0. 사본 개수 확정: 5벌이 아니라 **4벌**
+
+`src/adapters/web-push/push-association-fence-store.ts`는 IndexedDB 사본이 **아니다.**
+
+```
+$ grep -n "indexedDB|IDBDatabase|IDBTransaction|IDBRequest|IDBObjectStore|IDBKeyRange|IDBFactory|deleteDatabase|onupgradeneeded|objectStore" \
+ src/adapters/web-push/push-association-fence-store.ts
+→ 매치 없음
+```
+
+이 파일은 IndexedDB API를 한 줄도 쓰지 않는다. 대신 `PushControlRepository`라는 **구조적 포트**를 자기가 선언하고
+(`push-association-fence-store.ts:59-87`) 합성 루트에서 주입받는다. 파일 자신의 주석이 그 의도를 명시한다:
+
+> `push-association-fence-store.ts:49-58`
+> "It is declared here, structurally, rather than imported from the browser file/storage port so the two capabilities stay
+> independently removable. The generic IndexedDB repository satisfies it as-is; the composition root is where the two are
+> joined, and it owns connection, migration, transaction, timeout, codec and version-change policy."
+
+즉 이 파일은 **이번 리팩토링이 지향하는 모범 사례의 예시**이지 중복 사본이 아니다. 커널 이행 대상에서 제외한다.
+(다만 `tests/helpers/fake-push-control-repository.ts`, `tests/unit/web-push-store-port-compatibility.test.ts`는
+runtime의 공개 형태에 구조적으로 의존하므로 §5의 위험 목록에는 남긴다.)
+
+한편 **실제 IndexedDB 코드를 가진 5번째 파일은 따로 있다**: `src/adapters/storage/indexeddb/indexeddb-governance.ts`
+(`queueIndexedDbUpgradeBinding` L160-215, `verifyIndexedDbDatasetBinding` L220-338). 이건 `indexeddb/` 폴더 내부
+헬퍼라 runtime과 maintenance가 **이미 공유**하고 있다. 중복이 아니므로 대조표에는 참고 열로만 넣는다.
+
+---
+
+## 1. 4벌 대조표
+
+열 약어:
+- **RT** = `src/adapters/storage/indexeddb/indexeddb-runtime.ts` (2902 LOC)
+- **MT** = `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` (1558 LOC)
+- **OP** = `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` (1817 LOC)
+- **CP** = `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts` (712 LOC)
+
+### 1.1 연결 수립
+
+| 기능 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| `factory.open()` → Promise | 있음 `L684-921` | 있음 `L434-585` | 있음 `L961-1072` | 있음 `L156-239` |
+| `factory` 기본값을 전역에서 해석 | 있음 `L565-569` | 있음 `L359-363` | 있음 `L130-134` | 있음 `L95-97` |
+| `IDBKeyRange` 기본값을 전역에서 해석 | 있음 `L570-574` | 있음 `L364-368` | 있음 `L135-139` | **없음** (범위 질의 없음) |
+| 단일 비행(single-flight) 오픈 캐시 | 있음 `L594` `L942-951` | **없음 — 의도적**. 배치마다 열고 `finally`에서 닫음 `L1364-1366` `L1549-1551` | 있음 `L166` `L1067-1071` | 있음 `L129` `L144-148` |
+| 진행 중 open 취소 훅 | 있음 `cancelPendingOpen L596,L741-744`, `close()`에서 호출 `L2876` | 있음 `signal`→`request.transaction?.abort()` `L467-474` | **없음** | **없음** |
+| open generation 토큰(늦게 온 요청 무시) | 있음 `L595,L691-697` | **없음** | **없음** | **없음** |
+| 늦게 도착한 connection 강제 close | 있음 `L835-841,L896-902` | 있음 `L505-508,L577-580` | 있음 `L1050-1053` | 있음 `L168-171,L219-224` |
+
+### 1.2 blocked 처리
+
+| 기능 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| `onblocked` 핸들러 | 있음 `L776-799` | 있음 `L485-492` | 있음 `L1031-1041` | 있음 `L198-207` |
+| blocked 후 **대기 타이머** | 있음, 주입형 scheduler `L789-798`, 기본 10_000ms `L576` | **다르게 구현 — 타이머 없이 blocked 이벤트 즉시 실패** `L485-492` | 있음, 주입형 scheduler `L1032-1040`, 기본 10_000ms `L143` | **다르게 구현 — 네이티브 `setTimeout` 하드코딩(주입 불가)** `L199-206`, 기본 5_000ms `L23,L98-99` |
+| blocked를 관측 이벤트로 발행 | 있음 `L782-788` | **없음** (결과 매핑에서만 `observeResult` `L391-392`) | **없음** | **없음** |
+| blocked 시 연결 상태 전이 | 있음 `{kind:"BLOCKED"}` `L777-781` | **없음** | **없음** | **없음** |
+
+### 1.3 버전 마이그레이션 / 스키마
+
+| 기능 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| `onupgradeneeded` 훅 | 있음 `L746-774` | 있음 `L477-484` | 있음 `L991-1030` | 있음 `L176-197` |
+| upgrade 내부 동작 | **선언적 migration 목록 적용** `applyIndexedDbMigrations L754-760` + governance binding queue `L761-769` | **upgrade 자체를 실패로 취급** — `unexpectedUpgrade=true` 후 abort `L477-484`, 결과 `MIGRATION_FAILED` `L495-496` | **인라인 하드코딩된 createObjectStore 6개 + index 3개** `L997-1029`, `oldVersion!==0`이면 abort `L993-996` | **인라인 `contains` 체크 후 createObjectStore 2개** `L179-188` |
+| upgrade 실패 플래그 → 결과 코드 | 있음 `migrationFailed` `L714,L811-819` | 있음 `unexpectedUpgrade` `L460,L495-496` | **없음** (abort가 onerror로 흐름) | **없음** (catch 후 `finish` `L189-196`) |
+| open 후 스토어 존재 검증 | 있음 `assertIndexedDbRuntimeStores L844-853` (구현은 `indexeddb-migrations.ts:162-207`) | **다르게 구현 — 인라인 `objectStoreNames.contains` 5개 + index 접근 `L509-542`** | **없음** | **없음** |
+| governance/scope binding 검증 | 있음 `verifyIndexedDbDatasetBinding L866-871` | 있음 동일 함수 `L545-550` | **없음** (open 경로에서는 안 함; scope 바인딩은 트랜잭션 내부 로직 `L1310-1347`) | **다르게 구현 — 자체 `bindScope` 별도 트랜잭션 `L598-654`** |
+| 마이그레이션 개수를 결과로 반환 | 있음 `appliedMigrations L716,L910-916` | 해당 없음 | 해당 없음 | 해당 없음 |
+
+### 1.4 versionchange / 연결 무효화
+
+| 기능 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| `onversionchange` | 있음 `L904` → `handleVersionChange L637-651` (상태 브로드캐스트 + 콜백) | 있음 `L543` — `() => database.close()` 한 줄 | 있음 `L1055-1059` — 캐시 무효화(`database=null; opening=null`) | 있음 `L230-233` — 캐시 무효화 |
+| `onclose` (강제 종료) | 있음 `L905` → `handleForcedClose L653-657` | **없음** | 있음 `L1060-1063` | 있음 `L234-236` |
+| 연결 상태 구독 API | 있음 `getStatus/subscribeStatus L2893-2899` | **없음** | **없음** | **없음** |
+| `close()`/dispose | 있음 `L2873-2884` (pending open 취소 + DISPOSED 브로드캐스트) | **없음** (배치마다 자동 close) | 있음 `L757-761` | 있음 `L395-399` + `deletePartition`에서도 `L411-413` |
+
+### 1.5 트랜잭션 실행
+
+| 기능 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| `createTransaction` + durability 폴백 | 있음 `L957-974` | **RT와 문자 단위로 동일** `L587-604` | **다르게 구현 — readwrite만 `durability:"strict"` 하드코딩, readonly는 옵션 없음** `L1176-1190` | **다르게 구현 — durability 옵션 자체가 없음** `L512` |
+| durability를 의존성으로 주입 | 있음 `dependencies.durability?.read/.write` `L962-965` | 있음 동일 `L592-595` | **없음** (하드코딩) | **없음** |
+| `runTransaction` (트랜잭션→Promise) | 있음 `L976-1074` | 있음 `L606-705` — RT와 구조 동일, `operation`이 `"INDEXEDDB_MIGRATE"` 고정이고 `database`를 인자로 받음 | 있음 `L1098-1174` — **모듈 최상위 자유함수** | 있음 `runCheckpointTransaction L497-596` — **단일 스토어 `CHECKPOINT_STORE` 고정** `L512,L591` |
+| `TransactionContext` 타입 | `L85-89` (`succeed`/`fail`/`requestFailed`) | `L97-101` (동일 3종) | `L48-51` (**`succeed`/`fail` 2종 — `requestFailed` 없음**) | `L491-495` (`succeed`/`fail`/`nativeFailure`) |
+| caller `AbortSignal` → transaction.abort | 있음 `L1010-1017,L1041` | 있음 `L640-650,L676` | **없음 — signal 인자 자체가 없음** | 있음 `L527-539` |
+| `oncomplete`인데 값이 없을 때 | `UNAVAILABLE/retryable:true/REOPEN` `L1020` (`unavailable` `L397-404`) | `UNAVAILABLE/retryable:true/REOPEN` `L653` (`unavailable` `L257-262`) | `UNAVAILABLE/retryable:true/REOPEN` `L1144-1151` | **다르게 구현 — `CORRUPT_DATA/RECONCILE`** `L541-547` |
+| 요청 오류 기록 후 abort 여부 | **abort 안 함** — `requestFailed`는 기록만 `L1055-1060` | **abort 안 함** `L686-694` | 해당 없음 (요청 오류를 안 봄) | **abort 함** — `nativeFailure`가 즉시 abort `L577-588` |
+| `queue` 콜백이 throw할 때 | 있음 `L1063-1072` | 있음 `L697-703` | 있음 `L1163-1172` | 있음 `L590-594` |
+
+### 1.6 요청 → 콜백 변환
+
+| 기능 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| `request.onsuccess` 인라인 배선 | 있음, 수십 곳 (예 `L1134,L1782,L1878,L1932`) | 있음 (예 `L721,L799,L1033,L1079`) | 있음 (예 `L187,L497,L604,L790`) | 있음 (예 `L265,L323,L372`) |
+| `request.onerror` 인라인 배선 | 있음, 거의 모든 요청에 (예 `L1133,L1780,L1876`) | 있음 (예 `L720,L798,L1031`) | **없음 — 파일 전체에서 request `.onerror`는 open 요청 1개뿐** (`L1042`; `L1160`은 transaction.onerror) | 있음 (예 `L264,L322,L341,L371,L387`) |
+| 요청→콜백 공통 헬퍼 | **없음** | **없음** | **없음** | **없음** |
+
+### 1.7 커서 순회
+
+| 기능 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| `openCursor` 순회 루프 | 있음 4곳: `query L1364-1527`, `purgeEligibleRecords L2345-2472`, `purgePartitionRecords` 내부 4개 루프 `L2528-2566,L2570-2638,L2641-2713,L2715-2809` | 있음 2곳: `scanBatch L795-858`, `pruneExpiredReceipts L1429-1542` | 있음 2곳: `listIncomplete L600-633`, `listCommittedObjects L673-712` | **없음** |
+| 행 수 예산(maxRows) | 있음 — **삭제 행 기준** `deletedRows >= input.maxRows` `L2384,L2543,L2585,L2656,L2730` | 있음 — **스캔 행 기준** `rows.length >= input.maxRows` `L823`, 삭제 행 기준 `L1471` | **다르게 구현 — `limit`만, 예산 개념 없음** `L622,L699` | 해당 없음 |
+| 시간 예산(deadline) | 있음 `monotonicClock() L2260-2269`, 비교 `L2385,L2544` 등 | 있음 `clock() L401-410`, 비교 `L824,L1472` | **없음** | **없음** |
+| 스캔 상한(방어적) | 있음 `MAX_QUERY_SCANNED_ROWS=5_000 L105`, 계산 `L1349-1352`, 비교 `L1454` | **없음** | **없음** | 해당 없음 |
+| 커서 재개 방식 3종 (`continue`/`continue(key)`/`continuePrimaryKey`) | 있음 `L1430-1445` | **없음** (`continue()`만 `L852`) | **없음** (`continue()`만 `L632,L711`) | 해당 없음 |
+| 커서 중간에 중첩 요청 체인 실행 | 있음 (모든 순회가 그렇게 함, 예 `L1487-1526`, `L2406-2471`) | 있음 (`L1490-1541`) | **없음** (`push` 후 즉시 `continue()`) | 해당 없음 |
+| 순회 중 `signal.aborted` 체크 | 있음 `L1375-1382,L2365-2372` | 있음 `L800-807,L1452-1459` | **없음** | 해당 없음 |
+
+### 1.8 실패 매핑
+
+| 기능 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| 예외→실패 매핑 함수 | `mapIndexedDbException` `indexeddb-failure.ts:23-72` | 동일 함수 `L15` | 동일 함수 `L21` | **다르게 구현 — `mapBrowserDataException`** `browser-file-storage/result.ts:43-90` (`L11`에서 import) |
+| 매핑 테이블이 실제로 다른 지점 | — | — | — | `ConstraintError`: IDB=`CONFLICT/recovery:NONE`(`indexeddb-failure.ts:30-31`) vs BD=`CONFLICT/recovery:REOPEN`(`result.ts:58-60`) · `QuotaExceededError`: IDB=`retryable:false`(`:56-60`) vs BD=`retryable:true`(`:74-79`) · `NotFoundError`: IDB=`MIGRATION_FAILED`(`:41-45`) vs BD=`NOT_FOUND`(`:67-68`) · BD는 `DOMException`이 아니면 전부 `UNAVAILABLE`(`:47-52`), IDB는 name만 보고 판단(`:7-17`) |
+| `operation` 라벨 | 호출처마다 다름: `INDEXEDDB_OPEN/READ/WRITE/MIGRATE` | `INDEXEDDB_MIGRATE` 고정 `L248,L252,L258` 등 | 호출처마다 다름: `INDEXEDDB_OPEN/READ/WRITE` | `UPLOAD_RECONCILE` 고정 |
+| abort 단축 헬퍼 | `abortedResult` `L19` | `abortedResult` `L11` | **없음** (`signal` 미사용) | **없음** (인라인 `signal?.aborted` `L140-142,L408-410,L506-508`) |
+
+### 1.9 deleteDatabase
+
+| 기능 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| `factory.deleteDatabase` | **없음** | **없음** | **없음** | **있음** `L110-113`, `deletePartition L403-485` |
+| 파티션 전체 삭제를 다른 방식으로 구현 | 있음 — **행 단위 순회 삭제** `purgePartitionRecords L2477-2812` | **없음** | **없음** | 해당 없음 |
+| 삭제 blocked 처리 | 해당 없음 | 해당 없음 | 해당 없음 | 있음 — blocked 데드라인 후 `PENDING/UNKNOWN/BLOCKED_DEADLINE` 반환 `L449-462` (open의 `L198-207`과 동일 패턴 재작성) |
+| 진행 중 삭제 레지스트리 | 해당 없음 | 해당 없음 | 해당 없음 | 있음 `PENDING_DELETIONS WeakMap L31-41`, 생성 시 검사 `L116-122` |
+
+### 1.10 관측 / 구성 검증
+
+| 기능 | RT | MT | OP | CP |
+|---|---|---|---|---|
+| observe 래퍼 | 있음 `L599-605` + `observeResult L607-624` | 있음 `L373-379` + `observeResult L381-399` — **RT와 형태 동일** | **다르게 구현 — 이벤트 shape가 다름** (`SUCCEEDED/FAILED`, countBucket 없음) `L1074-1091` | **없음** |
+| `countBucket` | 있음 `L119-125` | **RT와 문자 단위로 동일** `L239-245` | **없음** | **없음** |
+| 식별자 정규식 | `SAFE_DATABASE_NAME` `L91` `{0,63}` | `SAFE_IDENTIFIER` `L103` `{0,127}` | `SAFE_DATABASE_NAME` `L110` `{0,255}`, `SAFE_BOUNDARY_ID` `L111` | `SAFE_OPAQUE_ID`/`SAFE_UPLOAD_KEY` (`checkpoint-schema.ts`) |
+| 구성 불변식 검사 후 `TypeError` | 있음 `L530-563` | 있음 `L331-357` | 있음 `L155-163` | 있음 `L100-106,L116-122` |
+| 의존성 메서드 bind 스냅샷 | 있음 `L474-527` | 있음 `L290-326` | **없음** | 있음 (부분) `L108-113` |
+| 저장 레코드 검증 술어 | 있음 `L223-301` | **거의 동일하지만 별도 구현** `L118-223` | 있음, 도메인 고유 `L1406-1665` | 있음, 도메인 고유 (`checkpoint-schema.ts`) |
+
+### 1.11 대조표 결론
+
+**4벌 전부가 같은 의미로 필요로 하는 것** (커널 후보):
+`factory.open→Promise`, `onupgradeneeded` 훅, `onblocked` 처리, 늦게 온 connection 강제 close,
+`onversionchange`/`onclose` 배선, `transaction→Promise` 상태기계(succeed/fail/settle-once/queue throw),
+`request→콜백` 배선.
+
+**3벌** (커널 후보): 단일 비행 오픈 캐시(MT 제외 — 의도적), durability 폴백을 가진 트랜잭션 팩토리(CP 제외),
+커서 순회(CP 제외), caller signal → transaction.abort(OP 제외 — 결함).
+
+**2벌 이하** (커널 아님): open 후 스토어 존재 검증(2), governance binding(2, 이미 `indexeddb-governance.ts`로 공유),
+observe/countBucket(2), 시간 예산 클럭(2), 상태 구독 API(1), `deleteDatabase`(1), 저장 레코드 술어(전부 도메인 고유).
+
+**그리고 가장 중요한 결론: 실패 매핑은 공통이 아니다.** 3벌이 `mapIndexedDbException`, 1벌이
+`mapBrowserDataException`을 쓰고 두 테이블은 §1.8에 적은 대로 실제로 다른 답을 낸다. 커널이 매핑을 고르면
+CP의 동작이 조용히 바뀐다. → **매핑은 주입한다.**
+
+---
+
+## 2. 커널 경계선
+
+판단 기준은 「4벌 중 3벌 이상이 **같은 의미로** 필요로 하는가」다.
+
+### 2.1 커널로 올릴 것
+
+| 항목 | 벌 수 | 근거 |
+|---|---|---|
+| `IDBOpenDBRequest` → Promise (settle-once, blocked 데드라인, upgrade 훅, 늦은 connection close, signal→upgrade abort) | 4/4 | §1.1 §1.2 §1.3 |
+| 단일 비행 연결 핸들 (+ versionchange/close 무효화, close()가 진행 중 open 취소) | 3/4 | §1.1 §1.4. MT는 의도적으로 안 씀 → 커널의 open 함수만 쓰고 핸들은 안 쓴다 |
+| 트랜잭션 팩토리 + durability 폴백 | 3/4 | §1.5. CP는 `durability: undefined`를 넘겨 오늘 동작 유지 |
+| `transaction` → Promise 상태기계 | 4/4 | §1.5 |
+| `request` → 콜백 배선(성공/오류) | 4/4 | §1.6 |
+| 커서 펌프(순회 + 예산 + 중첩 체인 재개) | 3/4 | §1.7 |
+
+### 2.2 남길 것 (근거 포함)
+
+| 항목 | 벌 수 | 남기는 이유 |
+|---|---|---|
+| 실패 매핑 테이블 | 3 + 1 | 두 테이블이 실제로 다른 값을 낸다(§1.8). 통일은 **별도 결정**이고 별도의 테스트 낙진을 만든다. 커널은 **원인(cause)만 알리고 코드를 고르지 않는다.** |
+| `operation` 라벨 | 4/4 다름 | 호출처마다 다르다. 커널이 알 필요가 없다. |
+| open 후 스토어/인덱스 존재 검증 | 2/4 | RT는 `indexeddb-migrations.ts:162-207`, MT는 인라인. 검증 대상 스토어 목록이 도메인 스키마다. 커널에는 `admit` 콜백만 둔다. |
+| governance / scope binding | 2/4 + 1 자체구현 | `indexeddb-governance.ts`가 이미 RT/MT 공유분이다. CP의 `bindScope`는 스코프 모델 자체가 다르다(`L60-66` vs `IndexedDbDatasetScope`). |
+| observe / countBucket | 2/4 | RT·MT는 동일하지만 OP는 shape가 다르고 CP는 없다. 2벌은 올리지 않는다. RT·MT 간 중복은 `indexeddb-types.ts`로 내리는 **별건**이다. |
+| 시간 예산 클럭 | 2/4 | 커널의 커서 펌프가 예산 판정을 **콜백으로 받는다**. 클럭·deadline·실패값은 호출처가 소유한다. |
+| 연결 상태 구독(`getStatus`/`subscribeStatus`) | 1/4 | RT의 포트 계약(`IndexedDbRepositoryPort`)이다. |
+| 저장 레코드 검증 술어, 코덱, 예산(bytes), 보존, 영수증 | 도메인 | 커널은 **정책을 하나도 안 갖는다**(§5.3의 방어선). |
+
+### 2.3 `deleteDatabase` — 규칙의 명시적 예외 (1/4)
+
+「≥3벌만 커널」 규칙을 그대로 적용하면 `deleteDatabase`는 탈락이다. **그럼에도 커널에 둔다.** 근거:
+
+1. 이건 **새 기능 발명이 아니라 이동**이다. 규칙이 막으려는 건 아무도 안 쓰는 추상화인데, 이건 오늘 호출자가
+ 실제로 존재한다(`indexeddb-checkpoint-store.ts:403-485`).
+2. `deleteDatabase`는 `open`과 **같은 `IDBOpenDBRequest` 상태기계**다. CP는 blocked 데드라인 + settle-once
+ 로직을 `L198-207`(open)과 `L449-462`(delete)에 **두 번** 적었다. 커널이 open만 가져가면 CP 안에 그 로직의
+ 세 번째 사본이 남는다.
+3. **드러난 발산 자체의 진짜 원인은 `deleteDatabase`가 아니다.** 리뷰가 "한쪽에만 있다"고 잡은 건 표면 차이다.
+ RT는 파티션 삭제를 `purgePartitionRecords`(`L2477-2812`)의 행 단위 순회로 **의도적으로** 다르게 한다.
+ 따라서 **`deleteDatabase`를 나머지 3벌에 새로 넣지 않는다.** 이행 계획(§4)에 그런 항목은 없다.
+4. 별도 export라 나중에 떼어내도 나머지 커널이 안 흔들린다.
+
+`PENDING_DELETIONS` WeakMap 레지스트리(`L31-41`)는 **커널로 올리지 않는다.** 그건 realm 정책이고 CP에만 있는 판단이다.
+
+---
+
+## 3. 실제 TypeScript 시그니처
+
+### 3.1 파일 구성: **2개**
+
+```
+src/adapters/platform/indexeddb-connection.ts (~240 LOC) 연결 수명주기
+src/adapters/platform/indexeddb-transaction.ts (~230 LOC) 연결 안에서 벌어지는 일
+```
+
+**기각한 대안 1 — 단일 `indexeddb-kernel.ts`(~470 LOC):** `platform/`의 현재 최대 파일은
+`abortable-operation.ts` 269 LOC다. 470 LOC는 1.7배로 폴더 관례를 깬다. 더 중요한 건 테스트 셋업이 갈린다는
+점이다: 연결 쪽은 가짜 `IDBFactory`가 필요하고 트랜잭션 쪽은 가짜 `IDBDatabase`면 충분하다.
+
+**기각한 대안 2 — 3분할(`open-request`/`connection`/`transaction`):** open 요청과 연결 핸들은 같은 수명주기
+개념이고, 분리하면 `IndexedDbFailureCause`가 두 파일에 걸치거나 세 번째 타입 파일이 필요해진다. 또 inventory
+행이 하나 더 는다(§5.2).
+
+### 3.2 `src/adapters/platform/indexeddb-connection.ts`
+
+```ts
+/**
+ * IDB-X-01. Shared IndexedDB connection mechanics.
+ *
+ * Four adapters independently reimplemented "turn an open request into a
+ * promise, hold a blocked deadline, route upgrade/error/success, close a
+ * connection that arrives after the caller gave up, and drop the cached handle
+ * when the browser takes it away". Only the mechanics are shared here. Database
+ * naming, schema, migrations, governance binding and the failure taxonomy stay
+ * with each subsystem, so this module imports none of them and is not a
+ * generic storage layer.
+ *
+ * The `IDBFactory` is a required parameter rather than a read of
+ * `globalThis.indexedDB`. `eslint.config.ts:40-63` bans that property on every
+ * browser root and `eslint.config.ts:519-530` grants the owned-adapter escape
+ * hatch to `src/adapters/platform/browser-lifecycle.ts` as a single file, not
+ * to this folder. Requiring the factory is also what all four callers already
+ * do, so nothing in eslint.config.ts has to change.
+ */
+
+import type { Result } from "../../contracts/result.ts";
+import type { AbortTimerSnapshot } from "./abortable-operation.ts";
+
+/**
+ * Everything that can end an IndexedDB operation without the caller getting a
+ * value. The kernel reports the cause; the caller's `translate` turns it into
+ * that subsystem's failure code.
+ *
+ * This union is the extension point. `abortable-operation.ts:11` baked a closed
+ * three-member `AbortTerminalReason` into its return type, so http v3 needed
+ * five owners and could not use the kernel at all. Here the owner vocabulary is
+ * never in a return type: adding a member is a compile error in every
+ * `translate` (they are total functions over the union) rather than a silent
+ * behavior change, and no consumer has to fork.
+ */
+export type IndexedDbFailureCause =
+ /** A native throw or a `request.error` / `transaction.error`. */
+ | Readonly<{ kind: "NATIVE_EXCEPTION"; error: unknown }>
+ /** `onblocked` fired and no deadline was configured. */
+ | Readonly<{ kind: "BLOCKED"; oldVersion: number; newVersion: number | null }>
+ /** `onblocked` fired and the configured deadline then elapsed. */
+ | Readonly<{ kind: "BLOCKED_DEADLINE" }>
+ /** The caller's own `AbortSignal` fired. */
+ | Readonly<{ kind: "CALLER_ABORT" }>
+ /** The connection handle was closed, which is not the caller aborting. */
+ | Readonly<{ kind: "CLOSED" }>
+ /** `upgrade` returned `REJECTED`, or a version change happened unexpectedly. */
+ | Readonly<{ kind: "UPGRADE_REJECTED"; oldVersion: number; newVersion: number | null; detail?: unknown }>
+ /** `admit` returned `REJECT`. `detail` is opaque to the kernel. */
+ | Readonly<{ kind: "ADMISSION_REJECTED"; detail?: unknown }>
+ /** A transaction completed without `succeed()` ever being called. */
+ | Readonly<{ kind: "NO_VALUE_PRODUCED" }>
+ /** No `IDBFactory`, or a required `IDBKeyRange` the caller did not supply. */
+ | Readonly<{ kind: "UNSUPPORTED" }>;
+
+/**
+ * Turns a cause into this subsystem's failure value. Built per call site so the
+ * kernel never learns an operation label or a failure code; a caller that needs
+ * `INDEXEDDB_READ` and one that needs `UPLOAD_RECONCILE` differ only here.
+ */
+export type IndexedDbTranslate = (
+ cause: IndexedDbFailureCause,
+) => Failure;
+
+export type IndexedDbUpgradeContext = Readonly<{
+ database: IDBDatabase;
+ transaction: IDBTransaction;
+ oldVersion: number;
+ /** Never `null`: a null `newVersion` is reported as `UPGRADE_REJECTED` before `upgrade` runs. */
+ newVersion: number;
+}>;
+
+/**
+ * `REJECTED` aborts the versionchange transaction, so a schema change can never
+ * commit under a rejected policy. A throw from `upgrade` is equivalent to
+ * `REJECTED` with the thrown value as `detail`.
+ */
+export type IndexedDbUpgradeOutcome =
+ | Readonly<{ kind: "APPLIED" }>
+ | Readonly<{ kind: "REJECTED"; detail?: unknown }>;
+
+/**
+ * Post-open validation. It runs after `onsuccess` and may be asynchronous, so
+ * store/index assertions and governance reads both fit. A rejected or failed
+ * admission closes the connection before the caller ever sees it.
+ */
+export type IndexedDbAdmission =
+ | Readonly<{ kind: "ADMIT" }>
+ | Readonly<{ kind: "REJECT"; detail?: unknown }>
+ | Readonly<{ kind: "FAIL"; cause: IndexedDbFailureCause }>;
+
+export type IndexedDbOpenInput = Readonly<{
+ /** Required. See the module comment for why this is not read from a global. */
+ factory: IDBFactory;
+ databaseName: string;
+ /** Omit to open whatever version exists. */
+ version?: number;
+ translate: IndexedDbTranslate;
+ /**
+ * Called inside the versionchange transaction. Omitting it means any upgrade
+ * is unexpected and the open fails with `UPGRADE_REJECTED` — which is what
+ * `indexeddb-maintenance.ts:477-484` does by hand today.
+ */
+ upgrade?: (context: IndexedDbUpgradeContext) => IndexedDbUpgradeOutcome;
+ /** Post-open validation. Omitting it admits every successful open. */
+ admit?: (database: IDBDatabase) => IndexedDbAdmission | Promise;
+ /** Aborts a pending upgrade transaction and settles with `CALLER_ABORT`. */
+ signal?: AbortSignal;
+ /**
+ * `undefined` or `0`: the `onblocked` event itself is terminal and settles
+ * with `BLOCKED` (maintenance's behavior). A positive value waits that long
+ * before settling with `BLOCKED_DEADLINE` (runtime/opfs/checkpoint).
+ */
+ blockedTimeoutMs?: number;
+ /**
+ * Required when `blockedTimeoutMs` is positive. Build it with
+ * `snapshotAbortTimers` from `./abortable-operation.ts`, which binds the
+ * callables once so replacing a method after composition cannot change how an
+ * open already in flight is bounded.
+ */
+ timers?: AbortTimerSnapshot;
+ /** Observation only; it cannot change the outcome and its throw is swallowed. */
+ onBlocked?: (
+ event: Readonly<{ oldVersion: number; newVersion: number | null }>,
+ ) => void;
+}>;
+
+/**
+ * Settles exactly once. A connection that arrives after the settle — a late
+ * `onsuccess`, a rejected admission, an abort — is closed rather than leaked.
+ */
+export function openIndexedDbDatabase(
+ input: IndexedDbOpenInput,
+): Promise>;
+
+export type IndexedDbConnection = Readonly<{
+ /**
+ * Single-flight: concurrent callers share one in-flight open, and a cached
+ * live connection is returned without touching the factory.
+ */
+ acquire(signal?: AbortSignal): Promise>;
+ /** The cached connection, or `null` while none is live. Live accessor, not a snapshot. */
+ current(): IDBDatabase | null;
+ /**
+ * Idempotent. Closes the cached connection and settles any in-flight open
+ * with `CLOSED` — not `CALLER_ABORT`, because the two have different codes in
+ * `indexeddb-runtime.ts` (`L743` resolves UNAVAILABLE while `L676` resolves
+ * ABORTED), and collapsing them would change one of them.
+ */
+ close(): void;
+ isClosed(): boolean;
+}>;
+
+export type IndexedDbConnectionInput = Readonly<{
+ /**
+ * How to produce a connection. Normally a closure over
+ * `openIndexedDbDatabase`. It is a seam rather than a fixed body so a caller
+ * can retry, decorate or fake the open without faking an `IDBFactory`.
+ */
+ open: (signal: AbortSignal | undefined) => Promise>;
+ translate: IndexedDbTranslate;
+ /**
+ * Fired after the handle has already dropped its cached connection, so a
+ * listener cannot keep a connection the browser is taking back. The next
+ * `acquire()` opens again.
+ */
+ onVersionChange?: (event: IDBVersionChangeEvent) => void;
+ /** `onclose`: the browser closed the connection without a version change. */
+ onForcedClose?: () => void;
+}>;
+
+export function createIndexedDbConnection(
+ input: IndexedDbConnectionInput,
+): IndexedDbConnection;
+
+export type IndexedDbDeleteOutcome =
+ | Readonly<{ kind: "DELETED" }>
+ /**
+ * The request is still live in the browser. It is not a failure and it is not
+ * "not applied": `deleteDatabase` cannot be cancelled after dispatch, so the
+ * effect is unknown. `indexeddb-checkpoint-store.ts:449-462` makes the same
+ * distinction and its comment explains why.
+ */
+ | Readonly<{ kind: "BLOCKED_DEADLINE" }>;
+
+export type IndexedDbDeleteInput = Readonly<{
+ factory: IDBFactory;
+ databaseName: string;
+ translate: IndexedDbTranslate;
+ blockedTimeoutMs?: number;
+ timers?: AbortTimerSnapshot;
+ /**
+ * Called exactly once when the native request truly settles, success or
+ * error — never on a blocked deadline. The caller uses it to release a
+ * pending-deletion registration; the kernel does not own such a registry
+ * because whether a realm may recreate the database is the caller's policy.
+ */
+ onSettled?: () => void;
+}>;
+
+/**
+ * In this module because it is the same `IDBOpenDBRequest` state machine as
+ * `openIndexedDbDatabase`, not because three subsystems need it — only
+ * `indexeddb-checkpoint-store.ts` deletes a database, and nothing here asks the
+ * other three to start. Leaving it out would leave a third hand-written copy of
+ * the settle-once blocked-deadline latch eight lines away from the kernel's.
+ *
+ * There is deliberately no `signal`: the request cannot be cancelled after
+ * dispatch, so reporting ABORTED while the deletion may still commit would be a
+ * lie. Callers check their signal before calling.
+ */
+export function deleteIndexedDbDatabase(
+ input: IndexedDbDeleteInput,
+): Promise>;
+```
+
+핵심 구현 로직 (본문은 생략, 분기만):
+
+```ts
+export function openIndexedDbDatabase(
+ input: IndexedDbOpenInput,
+): Promise> {
+ const { factory, databaseName, translate } = input;
+ if (input.signal?.aborted) {
+ return Promise.resolve(fail(translate({ kind: "CALLER_ABORT" })));
+ }
+ return new Promise((resolve) => {
+ let settled = false;
+ let blockedTimer: unknown;
+ let upgradeRejection: IndexedDbFailureCause | null = null;
+
+ const settle = (result: Result) => {
+ if (settled) {
+ // A connection that lost the race is closed, never leaked.
+ if (result.ok) closeQuietly(result.value);
+ return;
+ }
+ settled = true;
+ if (blockedTimer !== undefined) input.timers?.clearTimer(blockedTimer);
+ input.signal?.removeEventListener("abort", onCallerAbort);
+ resolve(result);
+ };
+
+ let request: IDBOpenDBRequest;
+ try {
+ request = input.version === undefined
+ ? factory.open(databaseName)
+ : factory.open(databaseName, input.version);
+ } catch (error) {
+ settle(fail(translate({ kind: "NATIVE_EXCEPTION", error })));
+ return;
+ }
+
+ function onCallerAbort(): void {
+ // An upgrade transaction is the only cancellable part of an open request.
+ try { request.transaction?.abort(); } catch { /* the error path owns it */ }
+ settle(fail(translate({ kind: "CALLER_ABORT" })));
+ }
+ input.signal?.addEventListener("abort", onCallerAbort, { once: true });
+
+ request.onupgradeneeded = (event) => { /* upgrade ?? reject; abort on REJECTED */ };
+ request.onblocked = (event) => { /* onBlocked hook; timer or immediate BLOCKED */ };
+ request.onerror = () => { /* upgradeRejection ?? NATIVE_EXCEPTION(request.error) */ };
+ request.onsuccess = () => { /* settled/closed → close; else await admit → settle */ };
+ });
+}
+```
+
+### 3.3 `src/adapters/platform/indexeddb-transaction.ts`
+
+```ts
+/**
+ * IDB-X-02. Shared IndexedDB transaction and cursor mechanics.
+ *
+ * The same settle-once transaction state machine exists four times
+ * (`indexeddb-runtime.ts:976-1074`, `indexeddb-maintenance.ts:606-705`,
+ * `indexeddb-opfs-journal.ts:1098-1174`,
+ * `indexeddb-checkpoint-store.ts:497-596`) and the four already disagree: one
+ * of them never routes a request error at all, one aborts on a request error
+ * while two only record it, and one reports a value-less completion as
+ * CORRUPT_DATA while three report UNAVAILABLE. This module owns the mechanics
+ * and keeps every one of those choices at the call site.
+ */
+
+import type { Result } from "../../contracts/result.ts";
+import type {
+ IndexedDbFailureCause,
+ IndexedDbTranslate,
+} from "./indexeddb-connection.ts";
+
+export type IndexedDbDurability = "default" | "strict" | "relaxed";
+
+/**
+ * The failure half of a transaction context. Split out so helpers that only
+ * need to report failure (`onIndexedDbRequest`, `walkIndexedDbCursor`) do not
+ * have to be generic over the transaction's success type.
+ */
+export type IndexedDbRequestSink = Readonly<{
+ /**
+ * Records the failure and aborts the transaction. The first failure wins.
+ * This is `indexeddb-runtime.ts:1047-1054`'s `fail`.
+ */
+ fail(failure: Failure): void;
+ /**
+ * Records a request-level error **without aborting**: the transaction is left
+ * to complete or abort on its own, and the recorded error becomes the reported
+ * failure if it aborts. This is `indexeddb-runtime.ts:1055-1060`'s
+ * `requestFailed`.
+ *
+ * `indexeddb-checkpoint-store.ts:577-588` deliberately aborts instead. It
+ * keeps doing so by calling `fail(translate({kind:"NATIVE_EXCEPTION", error}))`.
+ * The kernel does not pick.
+ */
+ requestFailed(error: unknown): void;
+}>;
+
+export type IndexedDbTransactionContext =
+ IndexedDbRequestSink &
+ Readonly<{
+ /** The first `succeed` wins; later ones are ignored. */
+ succeed(value: Value): void;
+ /** For callers that need `objectStore()`/`index()` directly. */
+ readonly transaction: IDBTransaction;
+ }>;
+
+export type IndexedDbTransactionInput = Readonly<{
+ database: IDBDatabase;
+ stores: readonly string[];
+ mode: "readonly" | "readwrite";
+ translate: IndexedDbTranslate;
+ /** Aborts the transaction; the outcome is `CALLER_ABORT` unless completion won. */
+ signal?: AbortSignal;
+ /**
+ * `undefined` opens with **no options bag at all**, which is
+ * `indexeddb-checkpoint-store.ts:512`'s current behavior — not the same as
+ * `"default"`, which passes `{durability:"default"}`. A named value falls back
+ * to the no-options form when the engine rejects the bag with a `TypeError`.
+ */
+ durability?: IndexedDbDurability;
+ queue: (
+ transaction: IDBTransaction,
+ context: IndexedDbTransactionContext,
+ ) => void;
+}>;
+
+/**
+ * A transaction that completes without `succeed()` is reported through
+ * `translate({kind:"NO_VALUE_PRODUCED"})`. Three callers map that to
+ * UNAVAILABLE and `indexeddb-checkpoint-store.ts:541-547` maps it to
+ * CORRUPT_DATA; the kernel never picks.
+ */
+export function runIndexedDbTransaction(
+ input: IndexedDbTransactionInput,
+): Promise>;
+
+/**
+ * The durability fallback on its own, for a caller that manages its own
+ * transaction. `undefined` omits the options bag entirely.
+ */
+export function openIndexedDbTransaction(
+ database: IDBDatabase,
+ stores: readonly string[],
+ mode: "readonly" | "readwrite",
+ durability?: IndexedDbDurability,
+): IDBTransaction;
+
+/**
+ * Wires `onsuccess`/`onerror` in one place. The four copies write this pair by
+ * hand at roughly 70 sites and `indexeddb-opfs-journal.ts` omits `onerror`
+ * everywhere, which is how a request-level error there becomes whatever
+ * `transaction.error` happens to hold.
+ */
+export function onIndexedDbRequest(
+ request: IDBRequest,
+ sink: IndexedDbRequestSink,
+ onSuccess: (value: Value) => void,
+): void;
+
+/** How the visitor wants the cursor advanced. */
+export type IndexedDbCursorStep =
+ | Readonly<{ kind: "CONTINUE" }>
+ | Readonly<{ kind: "CONTINUE_FROM"; key: IDBValidKey }>
+ | Readonly<{ kind: "CONTINUE_PRIMARY"; key: IDBValidKey; primaryKey: IDBValidKey }>
+ /** End the walk here; `done` gets `reason: "STOPPED"`. */
+ | Readonly<{ kind: "STOP" }>
+ /**
+ * The visitor started its own request chain and will call `resume(step)` when
+ * that chain finishes. Without this the pump is unusable by three of the four
+ * callers: every walk in `indexeddb-runtime.ts` and `indexeddb-maintenance.ts`
+ * issues nested requests before advancing (e.g. `L1487-1526`, `L2406-2471`,
+ * `L1490-1541`). A pump that only understood `CONTINUE` would be the
+ * too-narrow-to-adopt failure again.
+ */
+ | Readonly<{ kind: "SUSPEND" }>;
+
+export type IndexedDbBudgetVerdict = "CONTINUE" | "ROW_BUDGET" | "TIME_BUDGET";
+
+export type IndexedDbBudget = Readonly<{
+ /**
+ * Checked before each row. The kernel counts nothing itself: runtime bounds
+ * on rows it deleted (`indexeddb-runtime.ts:2384`) while maintenance bounds on
+ * rows it scanned (`indexeddb-maintenance.ts:823`), so the counter, the clock
+ * and the deadline all belong to the caller. A clock that cannot be read is a
+ * failure rather than a `false`, which is what `monotonicClock()`
+ * (`indexeddb-runtime.ts:2260-2269`) already does.
+ */
+ admit(scannedRows: number): Result;
+}>;
+
+export type IndexedDbCursorVisit = Readonly<{
+ cursor: IDBCursorWithValue;
+ /** Rows handed to `visit` so far, this row included. */
+ scannedRows: number;
+ /** Only meaningful after the visitor returned `SUSPEND`. Idempotent. */
+ resume(step: IndexedDbCursorStep): void;
+}>;
+
+export type IndexedDbWalkSummary = Readonly<{
+ reason: "EXHAUSTED" | "STOPPED" | "ROW_BUDGET" | "TIME_BUDGET" | "ABORTED";
+ scannedRows: number;
+}>;
+
+export type IndexedDbWalkInput = Readonly<{
+ request: IDBRequest;
+ sink: IndexedDbRequestSink;
+ translate: IndexedDbTranslate;
+ budget?: IndexedDbBudget;
+ /**
+ * Checked at each row. An aborted signal aborts the transaction and ends the
+ * walk with `reason: "ABORTED"`, which is what `indexeddb-runtime.ts:1375-1382`
+ * does inline today.
+ */
+ signal?: AbortSignal;
+ visit: (visit: IndexedDbCursorVisit) => IndexedDbCursorStep;
+ /** The only success exit. The caller routes it into its own `succeed`. */
+ done: (summary: IndexedDbWalkSummary) => void;
+}>;
+
+/**
+ * Drives an open cursor. It reports a native advance failure through `sink` and
+ * never decides what a finished walk means — `reason` distinguishes a row budget
+ * from a time budget so a caller can keep reporting `budgetExhausted` exactly as
+ * it does now (`indexeddb-runtime.ts:2387`).
+ */
+export function walkIndexedDbCursor(
+ input: IndexedDbWalkInput,
+): void;
+```
+
+### 3.4 확장점이 4벌의 요구를 어떻게 다 받는지 — 사본별 예시
+
+**(a) RT: `mapIndexedDbException` + 호출처별 operation + 상태 브로드캐스트 + blocked 타이머**
+
+```ts
+// 연산마다 번역기 하나. 커널은 "INDEXEDDB_OPEN"이라는 문자열을 모른다.
+const translateFor = (operation: BrowserDataOperation): IndexedDbTranslate =>
+ (cause) => {
+ switch (cause.kind) {
+ case "NATIVE_EXCEPTION":
+ return unwrap(mapIndexedDbException(cause.error, operation));
+ case "BLOCKED":
+ case "BLOCKED_DEADLINE":
+ return unwrap(browserDataFailure("BLOCKED", operation, {
+ retryable: true, recovery: "RELOAD_OTHER_CONTEXTS",
+ }));
+ case "CALLER_ABORT":
+ return unwrap(browserDataFailure("ABORTED", operation));
+ case "CLOSED":
+ case "NO_VALUE_PRODUCED":
+ // runtime L743 / L1020: close와 값 없는 완료는 둘 다 UNAVAILABLE이다.
+ return unwrap(unavailable(operation));
+ case "UPGRADE_REJECTED":
+ return unwrap(browserDataFailure("MIGRATION_FAILED", "INDEXEDDB_MIGRATE", { recovery: "READ_ONLY" }));
+ case "ADMISSION_REJECTED":
+ // detail이 governance 거절인지 store 검증 실패인지는 RT만 안다.
+ return cause.detail === "POLICY"
+ ? unwrap(browserDataFailure("POLICY_REJECTED", operation, {
+ recovery: storagePolicySnapshot.unavailableFallback }))
+ : unwrap(mapIndexedDbException(cause.detail, "INDEXEDDB_MIGRATE"));
+ case "UNSUPPORTED":
+ return unwrap(browserDataFailure("UNSUPPORTED", operation, { recovery: "ONLINE_ONLY" }));
+ }
+ };
+
+const connection = createIndexedDbConnection({
+ open: (signal) => openIndexedDbDatabase({
+ factory, databaseName, version: dependencies.schemaVersion,
+ translate: translateFor("INDEXEDDB_OPEN"),
+ signal,
+ blockedTimeoutMs, // L576
+ timers: snapshotAbortTimers(scheduler), // L514-527를 대체
+ onBlocked: (event) => { // L777-788 그대로
+ updateStatus({ kind: "BLOCKED", currentVersion: event.oldVersion,
+ targetVersion: event.newVersion ?? dependencies.schemaVersion });
+ observe({ operation: "INDEXEDDB_OPEN", outcome: "BLOCKED",
+ schemaVersion: dependencies.schemaVersion, countBucket: "0", failureCode: "BLOCKED" });
+ },
+ upgrade: ({ database, transaction, oldVersion, newVersion }) => { // L746-774 그대로
+ let rejected = false;
+ try {
+ appliedMigrations = applyIndexedDbMigrations(
+ database, transaction, oldVersion, newVersion, dependencies.migrations);
+ queueIndexedDbUpgradeBinding(
+ transaction, dependencies.governanceStore, expectedBinding, oldVersion,
+ () => { rejected = true; });
+ } catch (error) {
+ return { kind: "REJECTED", detail: error };
+ }
+ return rejected ? { kind: "REJECTED", detail: "POLICY" } : { kind: "APPLIED" };
+ },
+ admit: async (database) => { // L844-895 그대로
+ try {
+ assertIndexedDbRuntimeStores(database, /* … 8개 인자 … */);
+ } catch (error) { return { kind: "FAIL", cause: { kind: "ADMISSION_REJECTED", detail: error } }; }
+ const binding = await verifyIndexedDbDatasetBinding(
+ database, dependencies.governanceStore, expectedBinding, undefined);
+ if (binding.ok) return { kind: "ADMIT" };
+ return binding.reason === "ABORTED"
+ ? { kind: "FAIL", cause: { kind: "CALLER_ABORT" } }
+ : binding.reason === "NATIVE_ERROR"
+ ? { kind: "FAIL", cause: { kind: "NATIVE_EXCEPTION", error: binding.error } }
+ : { kind: "REJECT", detail: "POLICY" };
+ },
+ }),
+ translate: translateFor("INDEXEDDB_OPEN"),
+ onVersionChange: () => { // L637-651에서 db.close()/connection=null 부분을 뺀 나머지
+ const next = Object.freeze({ kind: "CLOSED" as const, reason: "VERSION_CHANGE" as const });
+ updateStatus(next);
+ try { dependencies.onVersionChange?.(next); } catch { /* 알림과 종료는 독립 */ }
+ },
+ onForcedClose: () => updateStatus({ kind: "CLOSED", reason: "FORCED" }),
+});
+```
+
+RT의 커서 예산(삭제 행 기준 + 모노토닉 deadline)은 `budget.admit`으로:
+
+```ts
+// purgeEligibleRecords L2378-2389 → budget 하나로
+const budget: IndexedDbBudget = {
+ admit: () => {
+ const clock = monotonicClock(); // L2260-2269 그대로 남는다
+ if (!clock.ok) return clock;
+ if (clock.value >= deadline) return ok("TIME_BUDGET");
+ if (deletedRows >= input.maxRows) return ok("ROW_BUDGET"); // 삭제 행 기준 유지
+ return ok("CONTINUE");
+ },
+};
+```
+
+**(b) MT: blocked 타이머 없음 + upgrade 자체가 실패 + `INDEXEDDB_MIGRATE` 고정 + 연결 캐시 안 씀**
+
+```ts
+// 핸들을 만들지 않는다. openIndexedDbDatabase만 직접 부른다. (L1294-1296, finally L1364-1366 유지)
+const opened = await openIndexedDbDatabase({
+ factory, databaseName, version: dependencies.schemaVersion,
+ translate, // operation이 상수라 번역기도 하나
+ signal: input.signal,
+ // blockedTimeoutMs 생략 → BLOCKED 원인이 blocked 이벤트에서 바로 나온다 (L485-492 동작 보존)
+ // upgrade 생략 → 어떤 upgrade든 UPGRADE_REJECTED (L477-484, L495-496 동작 보존)
+ admit: async (database) => { // L509-550 그대로
+ for (const store of [recordStore, governanceStore, retentionStore, checkpointStore, idempotencyStore]) {
+ if (!database.objectStoreNames.contains(store)) return { kind: "REJECT", detail: "STORE" };
+ }
+ try {
+ openIndexedDbTransaction(database, [dependencies.idempotencyStore], "readonly")
+ .objectStore(dependencies.idempotencyStore).index(dependencies.idempotencyExpiryIndex);
+ } catch { return { kind: "REJECT", detail: "INDEX" }; }
+ database.onversionchange = () => database.close(); // L543 그대로
+ const binding = await verifyIndexedDbDatasetBinding(
+ database, dependencies.governanceStore, expectedBinding, input.signal);
+ return binding.ok ? { kind: "ADMIT" } : { kind: "REJECT", detail: binding };
+ },
+});
+```
+
+**(c) OP: signal 없음 + readwrite만 strict + 자체 observe shape**
+
+```ts
+// listIncomplete L600-633 → walk. signal도 budget도 안 넘긴다: 지금 없는 걸 새로 만들지 않는다.
+runIndexedDbTransaction({
+ database: db, stores: [JOURNAL_STORE], mode: "readonly",
+ translate: translateFor("INDEXEDDB_READ"),
+ durability: undefined, // readonly는 오늘도 옵션 없음 (L1118)
+ queue: (transaction, context) => {
+ const rows: OpfsJournalTransaction[] = [];
+ walkIndexedDbCursor({
+ request: transaction.objectStore(JOURNAL_STORE).index(STARTED_AT_INDEX).openCursor(),
+ sink: context, translate: translateFor("INDEXEDDB_READ"),
+ visit: ({ cursor }) => {
+ if (!isStoredJournalRow(cursor.value) || !isBoundScope(cursor.value.scope)) {
+ context.fail(unwrap(corrupt("INDEXEDDB_READ")));
+ return { kind: "STOP" };
+ }
+ if (rows.length === limit) return { kind: "STOP" };
+ rows.push(cursor.value);
+ return { kind: "CONTINUE" };
+ },
+ done: (summary) => context.succeed(Object.freeze({
+ transactions: Object.freeze(rows),
+ moreAvailable: summary.reason === "STOPPED" && rows.length === limit,
+ })),
+ });
+ },
+});
+// readwrite 쪽만 durability: "strict" (L1181-1183 동작 보존)
+```
+
+**(d) CP: 다른 매핑 테이블 + 값 없는 완료가 CORRUPT_DATA + durability 없음 + 요청 오류에 즉시 abort**
+
+```ts
+const translate: IndexedDbTranslate = (cause) => {
+ switch (cause.kind) {
+ case "NATIVE_EXCEPTION":
+ return unwrap(mapBrowserDataException(cause.error, "UPLOAD_RECONCILE")); // ← 다른 테이블 유지
+ case "NO_VALUE_PRODUCED":
+ return unwrap(browserDataFailure("CORRUPT_DATA", "UPLOAD_RECONCILE", { recovery: "RECONCILE" }));
+ case "BLOCKED":
+ case "BLOCKED_DEADLINE":
+ return unwrap(browserDataFailure("BLOCKED", "UPLOAD_RECONCILE", { retryable: true, recovery: "RESUME" }));
+ case "CALLER_ABORT":
+ return unwrap(browserDataFailure("ABORTED", "UPLOAD_RECONCILE"));
+ case "CLOSED":
+ return unwrap(browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", { recovery: "RESUME" }));
+ /* … */
+ }
+};
+
+runIndexedDbTransaction({
+ database, stores: [CHECKPOINT_STORE], mode: "readonly", translate, signal,
+ durability: undefined, // L512: 오늘도 옵션 없음. 커널 기본값을 상속하지 않는다.
+ queue: (transaction, context) => {
+ const store = transaction.objectStore(CHECKPOINT_STORE);
+ const request = store.get(uploadKey);
+ // nativeFailure(= 기록 후 즉시 abort) 유지: requestFailed가 아니라 fail을 쓴다.
+ request.onerror = () => context.fail(translate({ kind: "NATIVE_EXCEPTION", error: request.error }));
+ request.onsuccess = () => { /* L265-283 그대로 */ };
+ },
+});
+```
+
+이 네 예시가 보여주는 것: **커널은 operation 라벨, 실패 코드, 매핑 테이블, blocked 정책, upgrade 정책,
+예산 기준, abort 정책, durability 정책을 하나도 안 정한다.** `abortable-operation.ts:11`이
+`AbortTerminalReason`을 반환 타입에 박아 넣어 http v3가 못 쓴 것과 정확히 반대 구조다.
+
+---
+
+## 4. 사본별 이행 계획
+
+LOC 감소는 **추정**이다. 근거로 삭제 대상 블록의 줄 범위를 함께 적었다.
+
+### 4.1 RT — `indexeddb-runtime.ts` (2902 → 약 2665, **−235**)
+
+**삭제:**
+
+| 블록 | 줄 | LOC | 대체 |
+|---|---|---:|---|
+| `defaultScheduler` | L108-117 | 10 | `snapshotAbortTimers(scheduler)` |
+| `TransactionContext` 타입 | L85-89 | 5 | `IndexedDbTransactionContext` |
+| `waitForOpeningAttempt` | L659-682 | 24 | `connection.acquire(signal)` |
+| `startOpeningAttempt` 중 배선 부분 (settle-once, generation 부기, blocked 타이머, onerror 라우팅, 늦은 close) | L684-745, L776-843, L872-921 중 배선분 | ~110 | `openIndexedDbDatabase` (upgrade/admit 콜백 본문은 그대로 남음) |
+| `createTransaction` | L957-974 | 18 | `openIndexedDbTransaction` |
+| `runTransaction` | L976-1074 | 99 | `runIndexedDbTransaction` |
+| 커서 5곳의 deadline/maxRows/abort 보일러플레이트 | L1374-1382, L1454-1471, L2364-2389, L2531-2548, L2573-2590, L2644-2661, L2718-2735 | ~60 | `walkIndexedDbCursor` + `budget.admit` |
+| 소계 삭제 | | **~326** | |
+| 커널 호출부·콜백 추가 | | ~90 | |
+| **순감** | | **~−235** | |
+
+**남는 것:** 코덱/영수증/보존/예산(bytes)/governance/migration 목록/상태 브로드캐스트/`monotonicClock`/
+`countBucket`/저장 레코드 술어/`purgePartitionRecords`의 스토어 순서 로직 — 전부 정책이라 그대로.
+
+**동작 변화 지점:**
+- **RT-1.** `close()`가 진행 중 open을 끝내는 원인이 `unavailable(operation)`(L743)에서
+ `translate({kind:"CLOSED"})`로 바뀐다. 위 번역기는 `CLOSED → unavailable`로 매핑해 **동일하게 유지**한다.
+ 이 매핑을 빠뜨리면 `close()` 중 open이 ABORTED로 보고된다. **테스트가 잡아야 할 지점.**
+- **RT-2.** `settleNativeRequest`/`activeOpeningGeneration`(L595, L691-697)이 사라진다. 늦게 온 open의 무해화를
+ 커널의 settle-once가 대신한다. RT의 generation 토큰은 `openingPromise` 정리 시점 제어용이었고
+ `createIndexedDbConnection`의 단일 비행이 같은 역할을 한다. **의미 동일. 단 경합 순서가 달라질 수 있다.**
+- **RT-3.** `openingRequest` 필드(L593)가 쓰이지 않게 된다(오늘도 L712와 L2878 대입 외에 읽는 곳 없음). 삭제.
+
+### 4.2 MT — `indexeddb-maintenance.ts` (1558 → 약 1370, **−188**)
+
+**삭제:**
+
+| 블록 | 줄 | LOC | 대체 |
+|---|---|---:|---|
+| `TransactionContext` 타입 | L97-101 | 5 | 커널 타입 |
+| `openExactVersion` 중 배선분 | L434-508, L551-585 | ~95 | `openIndexedDbDatabase` (`admit`에 L509-550 이식) |
+| `createTransaction` | L587-604 | 18 | `openIndexedDbTransaction` |
+| `runTransaction` | L606-705 | 100 | `runIndexedDbTransaction` |
+| 커서 2곳의 deadline/maxRows/abort 보일러플레이트 | L799-833, L1451-1479 | ~30 | `walkIndexedDbCursor` |
+| 소계 삭제 | | **~248** | |
+| 커널 호출부·콜백 추가 | | ~60 | |
+| **순감** | | **~−188** | |
+
+**남는 것:** 체크포인트 상태기계(`readCheckpoint` L707-756, `commitPrepared` L969-1251),
+`prepareRecords` L863-967, `clock`/`epochClock` L401-421, `countBucket` L239-245, 저장 술어 L118-223.
+
+**동작 변화 지점:**
+- **MT-1. (가장 위험)** `blockedTimeoutMs`를 안 넘기면 오늘 동작(blocked 이벤트 즉시 BLOCKED, L485-492)이
+ 유지된다. **넘기면 배치가 최대 그 시간만큼 매달린다.** `tests/unit/indexeddb-maintenance.test.ts:289-290`이
+ `BLOCKED/retryable:true/RELOAD_OTHER_CONTEXTS`를 즉시 받길 기대하므로 값을 잘못 넣으면 타임아웃 실패한다.
+- **MT-2.** `upgrade` 콜백을 **생략**해야 오늘의 "upgrade는 곧 실패"(L477-484)가 유지된다. 커널은 생략을
+ `UPGRADE_REJECTED`로 해석하므로 실수로 빈 `upgrade: () => ({kind:"APPLIED"})`를 넣으면 잘못된 스키마로
+ 열린다. **테스트가 잡아야 할 지점.**
+- **MT-3.** `database.onversionchange = () => database.close()`(L543)를 `admit` 안으로 옮긴다. `admit`은
+ 성공 경로에서만 실행되므로 등록 시점이 오늘과 같다.
+
+### 4.3 OP — `indexeddb-opfs-journal.ts` (1817 → 약 1690, **−127**)
+
+**삭제:**
+
+| 블록 | 줄 | LOC | 대체 |
+|---|---|---:|---|
+| `TransactionContext` 타입 | L48-51 | 4 | 커널 타입 |
+| scheduler 기본값 인라인 | L144-153 | 10 | `snapshotAbortTimers` |
+| `openDatabase` 중 배선분 | L961-996, L1031-1072 | ~79 | `openIndexedDbDatabase` + `createIndexedDbConnection` (upgrade 본문 L997-1029는 `upgrade` 콜백으로 그대로 이동) |
+| `runTransaction` | L1098-1174 | 77 | `runIndexedDbTransaction` |
+| `strictReadwriteTransaction` | L1176-1190 | 15 | `openIndexedDbTransaction(…, "strict")` |
+| 커서 2곳의 limit 루프 | L604-633, L677-712 | ~20 | `walkIndexedDbCursor` |
+| 소계 삭제 | | **~205** | |
+| 커널 호출부 + **누락된 요청 오류 배선 추가** | | ~78 | |
+| **순감** | | **~−127** | |
+
+**동작 변화 지점:**
+- **OP-1. (이 리팩토링에서 가장 큰 동작 변화)** 오늘 OP는 트랜잭션 안의 개별 요청에 `.onerror`를 **하나도**
+ 안 단다(파일 전체 request `.onerror`는 L1042 open 요청뿐). 요청 실패는 `transaction.onabort`로만 흘러
+ `mapIndexedDbException(transaction.error)`(L1158)가 된다. 커널을 쓰면 **요청 자신의 오류가 보고된다.**
+ 구체적으로 `LOGICAL_KEY_INDEX`가 `unique:true`(L1000-1004)이므로 중복 put은 요청 레벨
+ `ConstraintError` → `CONFLICT`가 되고, 오늘은 `transaction.error`가 무엇이냐에 따라 달라진다.
+ **`tests/unit/indexeddb-opfs-journal.test.ts`가 잡아야 할 지점.**
+- **OP-2.** 오늘 OP의 `runTransaction`은 `succeed` 이후 `fail`이 와도 `explicitFailure`가 이기지만
+ (L1133-1141, `hasValue`는 그대로 true) `oncomplete`는 값을 반환한다(L1143-1153). 커널의
+ "첫 결과가 이긴다" 규칙(RT L1044-1054와 동일)을 따르면 **`succeed` 후의 `fail`이 무시된다.**
+ 현재 OP 코드에서 그 순서가 실제로 발생하는 경로가 있는지는 **미확인** — 이행 시 확인 필요.
+- **OP-3.** `context.fail` 시 abort가 실패하면 오늘은 즉시 `settle(result)`(L1139)한다. 커널(RT식)은
+ `finish(candidate ?? …)`로 같은 결과를 낸다. 의미 동일.
+- **OP-4.** `signal`은 **넣지 않는다.** 오늘 없는 취소를 새로 만들지 않는다.
+
+### 4.4 CP — `indexeddb-checkpoint-store.ts` (712 → 약 570, **−142**)
+
+**삭제:**
+
+| 블록 | 줄 | LOC | 대체 |
+|---|---|---:|---|
+| `TransactionContext` 타입 | L491-495 | 5 | 커널 타입 |
+| `openAndBind` 중 open 요청 Promise 배선 | L163-175, L198-217 | ~33 | `openIndexedDbDatabase` (upgrade 본문 L176-197은 콜백으로 이동, `bindScope` 호출은 `admit`으로 이동) |
+| `runCheckpointTransaction` | L497-596 | 100 | `runIndexedDbTransaction` |
+| `bindScope`의 트랜잭션 배선 | L602-623 | ~22 | `runIndexedDbTransaction` (검증 로직 L624-652는 `queue`로 그대로) |
+| `deletePartition`의 blocked/settle 배선 | L431-462, L472-483 | ~35 | `deleteIndexedDbDatabase` |
+| 소계 삭제 | | **~195** | |
+| 커널 호출부·콜백 추가 | | ~53 | |
+| **순감** | | **~−142** | |
+
+**남는 것:** `PENDING_DELETIONS` 레지스트리 L31-41 + 생성 시 검사 L116-122, `uploadCheckpointDatabaseName`
+L73-83, `sameScopeBinding` L656-672, `snapshotScope` L674-691, `snapshotCheckpoint` L693-711.
+
+**동작 변화 지점:**
+- **CP-1.** 값 없는 완료가 `CORRUPT_DATA/RECONCILE`(L541-547)로 유지되려면 번역기가
+ `NO_VALUE_PRODUCED → CORRUPT_DATA`를 **명시적으로** 매핑해야 한다. 안 하면 UNAVAILABLE로 바뀐다.
+ **테스트가 잡아야 할 지점.**
+- **CP-2.** `durability: undefined`를 **명시적으로** 넘겨야 오늘 동작(옵션 bag 없음, L512)이 유지된다.
+ 커널 기본을 상속하거나 `"strict"`를 넣으면 체크포인트 쓰기가 조용히 strict가 되어 느려진다. 정확성은
+ 안 깨지지만 성능 회귀다.
+- **CP-3.** `nativeFailure`(L577-588, 기록 후 즉시 abort)는 `context.fail(translate(NATIVE_EXCEPTION))`으로
+ 표현한다. `requestFailed`(abort 안 함)로 잘못 바꾸면 **요청이 실패했는데도 뒤 요청이 커밋될 수 있다.**
+ `compareAndSwap`의 `get → put` 체인(L321-343)에서 특히 위험하다. **테스트가 잡아야 할 지점.**
+- **CP-4.** `abort()` 호출이 throw했을 때 오늘은 `failure`를 **되돌린다**(L528, L536: "durably committed while
+ its completion event is still queued" — 커밋된 변경을 ABORTED로 보고하지 않기 위함). 커널의
+ RT식 `onAbort`(L1010-1017)에는 이 되돌림이 없다. **커널의 signal abort 처리는 CP의 이 규칙을 채택해야 한다:
+ abort가 throw하면 caller-abort 표시를 세우지 않고 transaction 이벤트가 결과를 정한다.** 이건 커널 구현의
+ 필수 요건이고, 놓치면 CP가 커밋된 체크포인트를 ABORTED로 보고한다.
+ → `tests/unit/resumable-upload-checkpoint.test.ts:238` "never reports a false abort after irreversible
+ deleteDatabase dispatch"가 인접 케이스를 이미 지킨다.
+- **CP-5.** `deletePartition`의 blocked 타이머가 네이티브 `setTimeout`(L450)에서 주입형 `timers`로 바뀐다.
+ `tests/unit/resumable-upload-checkpoint.test.ts:194`가 이 경로를 본다.
+- **CP-6.** `deleteDatabase`를 나머지 3벌에 **추가하지 않는다.** §2.3 근거.
+
+### 4.5 전체 합계
+
+| | LOC |
+|---|---:|
+| 4벌에서 삭제 | ~974 |
+| 4벌에 추가 (커널 호출부·콜백) | ~281 |
+| 4벌 순감 | **~−693** |
+| 커널 신규 2파일 | +~470 |
+| **레포 순증감** | **~−223** |
+
+**솔직한 평가:** LOC 절감은 크지 않다. 이 작업의 성과는 줄 수가 아니라 **트랜잭션 상태기계가 4개에서 1개가
+되는 것**이다. 오늘 그 4개는 §1.5에서 본 대로 이미 4가지 다른 답을 낸다(요청 오류를 안 봄 / 기록만 / 즉시
+abort, 값 없는 완료가 UNAVAILABLE / CORRUPT_DATA). LOC로 정당화하면 안 된다.
+
+---
+
+## 5. 위험과 선행조건
+
+### 5.1 선행조건 P1 — ESLint (**가장 놓치기 쉬움**)
+
+`eslint.config.ts:40-63`의 `restrictedBrowserDataProperties`는 `globalThis`/`window`/`self` 세 루트 전부에서
+`indexedDB` **속성 접근**을 금지한다. 추가로 `eslint.config.ts:112-…`의 커스텀 규칙
+`browser-data-boundary/no-capability-alias`가 지역 별칭까지 따라간다
+(`const host = globalThis; host.indexedDB`도 잡힌다 — 규칙 주석 `eslint.config.ts:107-111`).
+
+두 개의 예외 목록(`eslint.config.ts:519-530`, `eslint.config.ts:677-691`)은 `src/adapters/platform/`을
+**폴더가 아니라 `browser-lifecycle.ts` 한 파일로** 열어 놨다.
+
+→ **설계 결론: 커널은 `globalThis.indexedDB`를 절대 읽지 않는다.** `IDBFactory`는 필수 주입 파라미터다
+(§3.2). 네 사본은 이미 전역 해석을 자기가 한다(RT L565-569, MT L359-363, OP L130-134, CP L95-97).
+**이 설계대로면 `eslint.config.ts`를 한 줄도 안 고쳐도 된다.**
+
+확인해 둔 것: `IDBFactory`·`IDBDatabase`·`IDBTransaction`·`IDBRequest`·`IDBKeyRange`·`IDBCursorWithValue`는
+어느 금지 목록에도 없다(`eslint.config.ts:40-63`, `:544-561`). 커널이 이 타입들을 이름으로 쓰는 건 문제없다.
+
+대안(커널이 전역을 읽게 하기)을 택하면 `eslint.config.ts`의 **두 목록 모두**에 신규 파일 2개를 추가해야 한다.
+한쪽만 고치면 `no-capability-alias`나 `no-restricted-properties` 중 하나가 남아서 `pnpm lint`가 깨진다.
+
+### 5.2 선행조건 P2 — `docs/reviews/adapters/INVENTORY.md` **갱신 필요**
+
+`scripts/check-adapter-inventory.ts:23-31`이 `git ls-files src/adapters`와 inventory 행을 **집합으로** 대조하고
+(`:41-53`), 중복을 거부하며(`:62-64`), `합계: **N/N**`의 두 숫자가 파일 수와 같아야 한다(`:65-72`).
+
+현재 총계는 `INVENTORY.md:132`의 `합계: **120/120**`이다. 신규 파일 2개 → **`122/122`**.
+
+확인해 둔 유용한 사실: 행 번호 정규식은 `/^\|\s*\d+\s*\|\s*` + 백틱 경로다(`:35`). 번호는 **위치와 대조되지
+않고** 순서도 무관하다(실제로 현재 `platform/` 행 59-63은 `git ls-files` 정렬과 순서가 다르다 —
+`INVENTORY.md:69-73`). → **기존 행을 재번호할 필요 없이 121, 122번 행을 추가하면 된다.**
+
+추가할 행(기존 `platform/` 행들과 같은 상세 리뷰 링크):
+
+```
+| 121 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) |
+| 122 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) |
+```
+
+`INVENTORY.md:132`의 안내문이 "해당 상세 리뷰 inventory를 같은 변경에서 갱신한다"고 요구한다.
+→ `docs/reviews/adapters/01-network-and-state.md`에도 두 행이 필요하다. 다만 **그 파일에 구조적 게이트가
+걸려 있는지는 미확인**이다 (`check-adapter-inventory.ts`는 `INVENTORY.md`만 읽는다, `:20`).
+
+### 5.3 선행조건 P3 — dependency-cruiser **변경 불필요**
+
+`adapters-do-not-know-other-concrete-adapters`의 `pathNot`이
+`^src/adapters/($1/|platform/|browser-file-storage/result\.ts$|cross-context-invalidation/index\.ts$)`이므로
+`src/adapters/platform/` 전체가 이미 허용 대상이다. 네 사본 전부 커널을 import할 수 있다.
+
+커널이 `src/contracts/result.ts`를 import하는 것도 허용된다:
+- dependency-cruiser에서 contracts를 언급하는 유일한 규칙은 `concrete-adapters-compose-only-in-bootstrap`인데,
+ 이건 `contracts → adapters`를 막지 `adapters → contracts`를 막지 않는다.
+- eslint `layerPatterns.adapters`는 `["**/presentation/**", "**/bootstrap/**"]`뿐이다(`eslint.config.ts:33`).
+- 선례: `src/adapters/web-push/push-association-fence-store.ts:12`가 `../../contracts/web-push.ts`를 import한다.
+
+그리고 `Result`(`src/contracts/result.ts:13-15`)를 쓰면
+`Result`가 정의상 `BrowserDataResult`와 **같은 타입**이다
+(`src/application/ports/browser-file-storage/shared.ts:95`). 변환 코드가 0줄이다.
+
+### 5.4 깨질 수 있는 기존 테스트 (grep으로 확인한 목록)
+
+| 파일 | LOC | 위험 |
+|---|---:|---|
+| `tests/helpers/memory-indexeddb.ts` | 922 | **최고 위험.** 단위 테스트 전부가 도는 가짜 IDB. OP-1(요청 레벨 `onerror`를 새로 달게 됨)이 이 가짜가 `request.error`를 실제로 채우는지에 의존한다. 오늘 OP는 요청 오류를 안 보므로 그 경로가 **한 번도 행사되지 않았을 수 있다.** 채우지 않으면 `NATIVE_EXCEPTION{error: null}` → `UNAVAILABLE`로 뭉개진다. **이행 전에 이 파일을 먼저 읽어야 한다 (이번 조사에서는 미확인).** |
+| `tests/unit/indexeddb-runtime.test.ts` | 1140 | RT-1(CLOSED 매핑). 실패 코드 단언은 `:339-340, :371-372, :454, :534, :549-550, :734-735` |
+| `tests/unit/indexeddb-maintenance.test.ts` | 842 | MT-1(blocked 즉시 실패). `:289-290`이 `BLOCKED/retryable:true/RELOAD_OTHER_CONTEXTS`를 단언. MT-2(upgrade 거절)도 여기 |
+| `tests/unit/indexeddb-opfs-journal.test.ts` | 431 | **OP-1, OP-2.** 요청 오류가 새 코드로 보고되는 건 이 테스트가 잡아야 한다 |
+| `tests/unit/resumable-upload-checkpoint.test.ts` | 265 | **CP-1, CP-3, CP-4, CP-5.** `:142` CONFLICT/RECONCILE, `:190` UNAVAILABLE/RESUME, `:194` blocked PENDING, `:238` false-abort 금지 |
+| `tests/unit/runtime-adapters.test.ts` | — | `storage/indexeddb` import. 공개 형태가 안 바뀌면 영향 없음 |
+| `tests/helpers/fake-push-control-repository.ts`, `tests/unit/web-push-store-port-compatibility.test.ts` | — | RT의 공개 포트 형태에만 의존. §0대로 IDB 코드 없음. 공개 형태 불변이면 영향 없음 |
+| `tests/unit/abortable-operation.test.ts`, `tests/unit/system-clock.test.ts` | — | 기존 커널 테스트. `snapshotAbortTimers` 재사용은 계약을 안 바꾸므로 영향 없음 |
+| `tests/browser-capabilities/indexeddb-runtime.spec.ts` | 1033 | 실브라우저 Playwright. `deleteDatabase`는 정리용(`:443, :832, :923, :1019`)이라 이번 변경과 무관. 다만 RT의 blocked/versionchange 실동작을 보므로 회귀 감지망 |
+| `tests/browser-capabilities/opfs-runtime.spec.ts` | 221 | 동 (`:137`) |
+| `tests/browser-capabilities/resumable-upload.spec.ts` | 526 | CP 실동작 |
+| `tests/fixtures/optional-recipes/forbidden/runtime-composition/src/bootstrap/bad-runtime.ts` | — | 픽스처. 경로 변경이 없으므로 영향 없음 |
+
+**신규 테스트:** `tests/unit/indexeddb-connection.test.ts`, `tests/unit/indexeddb-transaction.test.ts`가
+관례상 필요하다(`abortable-operation.test.ts`, `system-clock.test.ts` 선례). `check:test-evidence` /
+`check:risk-coverage`가 신규 소스 파일당 테스트를 **강제하는지는 미확인**.
+
+### 5.5 "커널이 커진다"는 반론과 답
+
+**반론:** 오늘 `src/adapters/platform/`은 5파일 550 LOC이고 전부 진짜 원시 요소다 — 시계 24줄, abort 269줄,
+용량 가드 21줄, 라이프사이클 186줄, UUID 50줄. 여기에 IndexedDB 전용 470 LOC를 넣으면 "platform"이라는 이름이
+거짓말이 된다. IndexedDB는 플랫폼 원시 요소가 아니라 **하나의 저장 기술**이다.
+
+**답 1 — 이 레포의 커널 기준은 "보편성"이 아니라 "네이티브 표면의 단일 소유자"다.** 같은 반론이
+`browser-lifecycle.ts`(186 LOC, `visibilitychange`/`online`/`pagehide` 전용)에도 그대로 적용되지만 그 파일은
+이미 커널이고, 자기 주석이 근거를 밝힌다(`browser-lifecycle.ts:4-7`: "No capability adds its own listener…
+so the listener count stays constant"). dependency-cruiser 규칙 주석도 같은 말을 한다:
+"Only the adapter kernel is shared — `src/adapters/platform` (clock, abort primitive, capacity guard)".
+
+**답 2 — 다른 위치는 전부 더 나쁘다.**
+- `src/adapters/storage/indexeddb/`에 두면 `adapters-do-not-know-other-concrete-adapters`가
+ `browser-transfer/`와 `storage/opfs/`의 import를 금지한다. **중복이 존재하는 이유가 바로 이것이다.**
+- 새 최상위 `src/adapters/indexeddb-kernel/`은 dependency-cruiser 규칙 변경이 필요한데, 리뷰가 이미 그 비용을
+ 이유로 기각했다.
+
+**답 3 (실제로 위험을 한정하는 답) — 커널은 IndexedDB "정책"을 하나도 갖지 않는다.**
+커널이 소유하는 것: 이벤트 배선(request→콜백), 트랜잭션 상태기계, 커서 펌프, settle-once, blocked 래치.
+커널이 소유하지 **않는** 것: DB 이름, 스키마, 마이그레이션, governance 바인딩, 코덱, 바이트 예산, 보존 정책,
+멱등 영수증, 실패 코드 테이블, operation 라벨, 관측 이벤트 shape, durability 기본값, 예산 기준.
+**나중에 이 목록 중 하나를 커널에 넣고 싶어지면, 그게 멈춰야 한다는 신호다.** 이 문장을 커널 파일 최상단
+주석에 넣는다.
+
+**답 4 — `abortable-operation.ts`의 실패를 반복하지 않는 구체적 차이.**
+`abortable-operation.ts:11`의 `AbortTerminalReason`은 3멤버 닫힌 union이고 `AbortRace`(`:19-22`)의
+**반환 타입에 박혀 있다.** 소비자가 5종이 필요하면 커널을 수정하거나 포기하는 두 길뿐이고, http v3는 포기했다.
+커널의 `IndexedDbFailureCause`는 **반환 타입에 안 나온다.** 반환 타입은 `Result`이고 `Failure`는
+호출처가 정한다. cause는 `translate` 함수의 **입력**일 뿐이라, 멤버를 추가하면 모든 `translate`에서
+**컴파일 에러**가 나고(전역 함수이므로) 조용한 동작 변화가 안 생긴다. 확장이 커널 수정 없이도 되고,
+커널 수정이 필요할 때도 누락이 타입 검사로 잡힌다.
+
+**남는 솔직한 위험:** 그래도 4개 어댑터가 공통으로 의존하는 470 LOC가 생긴다. 여기 버그가 나면 폭발 반경이
+4배다. 이걸 없앨 방법은 없고, 대가로 얻는 건 §1.5의 4가지 다른 답이 1가지가 되는 것이다. 그 교환이
+받아들일 만한지가 이 리팩토링의 진짜 판단이다.
+
+---
+
+## 6. 이행 순서 권고
+
+1. 커널 2파일 + 단위 테스트 추가. 사본은 손대지 않는다. → 게이트 기준선 유지 확인
+ (`check:architecture`, `check:types:app`, `lint`, `check:adapter-inventory`).
+ 이 단계에서 INVENTORY.md(+`01-network-and-state.md`)를 같이 갱신한다.
+2. **CP 먼저** 이행. 가장 작고(712), 동작 변화 지점(CP-1~CP-6)이 가장 명확하며, 커널의 CP-4 요건
+ (abort가 throw하면 caller-abort를 세우지 않는다)을 조기에 검증한다.
+3. **MT.** 커널 사용자 중 연결 핸들을 안 쓰는 유일한 사본이라 `openIndexedDbDatabase` 단독 사용 경로를 검증한다.
+4. **OP.** OP-1 때문에 `tests/helpers/memory-indexeddb.ts` 보강이 선행될 가능성이 높다.
+5. **RT 마지막.** 가장 크고 다른 셋이 커널을 다 검증한 뒤에 옮긴다.
diff --git a/docs/testing/frontend-platform-testing-strategy.md b/docs/testing/frontend-platform-testing-strategy.md
index 6003f36..1b33612 100644
--- a/docs/testing/frontend-platform-testing-strategy.md
+++ b/docs/testing/frontend-platform-testing-strategy.md
@@ -90,13 +90,39 @@ production Playwright profile은 source fixture가 아니라 `build` + `preview`
#### TanStack Query의 React integration test 기반
-`tests/component/application-query.test.tsx`는 production query inbound
-adapter의 query/mutation lifecycle을 검증한다. cancellation, initial terminal
-failure, background stale-failure latch와 retry 복구, duplicate submit,
-optimistic commit/rollback, conflict 해제와 namespace invalidation이 실제
-QueryClient 위에서 실행된다. HTTP 자동 retry가 소유자이므로 이 adapter의
+production query inbound adapter의 React integration은 behavior owner별
+component suite로 분리되어 있다.
+
+- `application-query-bridge.test.tsx`: initial/background state, cancellation
+- `application-query-scope-fence.test.tsx`: scope commit fence와 result budget
+- `application-mutation-scope-fence.test.tsx`: mutation scope fence
+- `application-query.test.tsx`: unknown-effect reconciliation
+- `application-mutation-admission.test.tsx`: intent/duplicate admission
+- `application-mutation-optimistic-cache.test.tsx`: optimistic cache commit/rollback
+- `application-query-fixture.tsx`: 공통 QueryClient/scope fixture
+
+각 실패 파일명이 깨진 behavior contract를 직접 드러내며, 동일한 52개 계약을
+실제 QueryClient 위에서 검증한다. HTTP 자동 retry가 소유자이므로 이 adapter의
query/mutation vendor retry는 꺼져 있다.
+같은 기준을 대형 unit suite에도 적용한다. 줄 수를 기준으로 자르지 않고 실패가
+가리켜야 하는 behavior owner를 기준으로 분리한다.
+
+- `public-response-cache.test.ts`: 일반 stage/activate/lookup/cache contract
+- `public-response-cache-repair.test.ts`: active release repair의 failure atomicity
+- `resumable-upload-runtime.test.ts`: upload/reconcile/control-plane 흐름
+- `resumable-upload-runtime-teardown.test.ts`: bounded drain/raw provider teardown
+- `security-followup.test.ts`: archived local evidence
+- `security-provider-evidence.test.ts`: provider signature/supervision/process lifecycle
+- `security-promotion-staging.test.ts`: private staging seal/replay/CLI identity
+- `tests/integration/provider-guardian-transaction.test.ts`: child process,
+ filesystem, IPC frame, READY/PUBLISHED handshake와 process lifecycle. pure unit
+ pool에 두지 않으며 handshake budget은 protocol timeout이 아닌 test watchdog이다.
+- 각 `*-fixture.ts`: 해당 owner들 사이에서만 공유하는 deterministic test fixture
+
+이 분리는 production owner와 test failure surface를 맞추기 위한 것이며, 단순
+LOC 감축 목적이 아니다.
+
#### Form과 route 위험
form component/reference feature test가 error summary, 첫 오류 focus, Zod
diff --git a/docs/testing/taxonomy.md b/docs/testing/taxonomy.md
index 8a4b847..421a3d6 100644
--- a/docs/testing/taxonomy.md
+++ b/docs/testing/taxonomy.md
@@ -3,14 +3,72 @@
Each gate is blocking in its declared scope. Failures are not downgraded with
`continue-on-error` or warning-only scripts.
-| Level | Command | Evidence |
-| --- | --- | --- |
-| runtime schema | `pnpm test:runtime-schema` | `artifacts/tests/runtime-schema.xml` |
-| unit | `pnpm test:unit` | `artifacts/tests/unit.xml` |
-| component | `pnpm test:component` | `artifacts/tests/component.xml` |
-| integration | `pnpm test:integration` | `artifacts/tests/integration.xml` |
-| end-to-end | `pnpm test:e2e` | `artifacts/tests/e2e/` |
-| accessibility | `pnpm test:a11y` | `artifacts/tests/a11y.json` |
+## Executable levels
+
+| Level | Command | Ownership / prerequisite | Evidence |
+| --- | --- | --- | --- |
+| runtime schema | `pnpm test:runtime-schema` | pure runtime schema contracts | `artifacts/tests/runtime-schema.xml` |
+| unit | `pnpm test:unit` | Node-only domain/application/pure policy/runtime units; no systemd/bwrap/cgroup prerequisite | `artifacts/tests/unit.xml` |
+| capability contract | `pnpm test:contract` | reusable capability consumer contracts | `artifacts/tests/contract.xml` |
+| component | `pnpm test:component` | React/hook/UI behavior | `artifacts/tests/component.xml` |
+| integration | `pnpm test:integration` | HTTP/MSW, IndexedDB, composed browser-runtime boundaries, child-process/filesystem/IPC integration | `artifacts/tests/integration.xml` |
+| system / CI runner | `pnpm test:system` | compatible Linux host with systemd, bubblewrap, cgroup v2 and CI-provider process controls | `artifacts/tests/system.xml` |
+| end-to-end | `pnpm test:e2e` | pinned browser engines | `artifacts/tests/e2e/` |
+| accessibility | `pnpm test:a11y` | pinned browser engines | `artifacts/tests/a11y.json` |
+
+`test:all` is the normal product-development loop. It intentionally includes
+runtime-schema, unit, capability-contract, component, integration, reference
+feature and recipe suites, but does not include `test:system`. CI-runner and
+supply-chain assurance has different host prerequisites and is invoked
+explicitly in the assurance path.
+
+## Deterministic test process
+
+All Vitest package scripts launch through `scripts/run-vitest.ts`.
+
+That runner:
+
+1. rejects Node versions outside the repository-supported
+ `>=24.11.0 <25.0.0` range before the suite starts,
+2. owns `NODE_ENV=test` rather than trusting the parent shell,
+3. removes host-specific `npm_config_userconfig`, `npm_config_prefix` and
+ `npm_config_globalconfig` values before Vitest starts.
+
+`vitest.config.ts` also fixes `NODE_ENV=test` so a direct Vitest invocation
+cannot accidentally select React's production behavior.
+
+The system suite additionally runs
+`scripts/check-system-test-prerequisites.ts` and fails with one prerequisite
+report when the CI-runner host does not provide its required Linux facilities.
+
+## Development paths
+
+Product feature:
+
+- focused feature/unit/component test
+- capability contract test when a reusable boundary changes
+- type/lint/architecture
+- `test:all`
+
+Reusable capability:
+
+- focused unit tests
+- capability contract tests
+- integration tests
+- type/lint/architecture
+
+CI / release assurance:
+
+- `test:system`
+- supply-chain / promotion / release gates
+
+A host-level process/sandbox test must not be placed in `tests/unit` merely
+because it uses Vitest. The classification follows the system boundary and
+prerequisites, not the test framework. Process-heavy tests that spawn child
+processes but do not require privileged host facilities belong in
+`tests/integration`; for example the provider guardian transaction protocol
+lives at `tests/integration/provider-guardian-transaction.test.ts`. Its
+handshake timeout is a test watchdog, not a production protocol deadline.
End-to-end and automated accessibility scenarios run on the pinned Chromium,
Firefox, and WebKit engines. The responsive contract explicitly exercises
@@ -30,9 +88,6 @@ Promotion is an AND graph:
3. release gates plus rollback/runbook drills
4. production promotion plus eligible field Web Vitals evidence
-This file describes the currently registered taxonomy. The
-[frontend platform testing strategy](./frontend-platform-testing-strategy.md)
-documents the target additions: test TypeScript projects, real bootstrap
-composition tests, shared MSW scenarios, query/mutation/form/router coverage,
-Storybook interaction and accessibility checks, visual regression, and a
-built-output Playwright profile.
+The [frontend platform testing strategy](./frontend-platform-testing-strategy.md)
+contains the broader testing design. This file is the executable taxonomy for
+where a test belongs and which environment is allowed to run it.
diff --git a/package.json b/package.json
index d3c04e5..b9ef85c 100644
--- a/package.json
+++ b/package.json
@@ -31,29 +31,31 @@
"check:types:node": "tsc --project tsconfig.node.json",
"check:types:test": "tsc --project tsconfig.test.json",
"check:types:recipes": "node scripts/check-optional-recipe-types.ts",
- "check:types:fixture": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext tests/fixtures/typecheck/invalid-port-call.ts",
- "check:types:fixture:ts-port": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-port-implementation.ts",
- "check:types:fixture:ts-result": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-result-narrowing.ts",
- "check:types:fixture:application-output": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-output.ts",
- "check:types:fixture:application-input": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-input.ts",
- "check:types:fixture:feature-input": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-feature-input.ts",
- "check:types:fixture:failure-kind": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-failure-kind.ts",
- "check:types:fixture:reference-operation": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-reference-operation.ts",
- "check:types:fixture:async-overlay": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-async-overlay.ts",
- "check:types:fixture:route-runtime": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-route-runtime.ts",
- "check:types:fixture:page-action": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-page-action.tsx",
- "check:types:fixture:icon-button": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-icon-button.tsx",
- "check:types:fixture:i18n-key": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-message-key.ts",
- "check:types:fixture:i18n-params": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-message-params.ts",
- "check:types:fixture:diagnostics": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-diagnostics-port.ts",
- "check:types:fixture:image-resolve-signal": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-image-cdn-resolve-signal.ts",
- "test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests",
- "test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml",
- "test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml",
- "test:integration": "vitest run tests/integration --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/integration.xml",
- "test:http-scenario-catalog": "vitest run tests/integration/http-scenario-catalog.test.ts --reporter=default --maxWorkers=1",
+ "check:types:fixture": "tsc -p tests/fixtures/typecheck/tsconfig.port-call.json",
+ "check:types:fixture:ts-port": "tsc -p tests/fixtures/typecheck/tsconfig.port-implementation.json",
+ "check:types:fixture:ts-result": "tsc -p tests/fixtures/typecheck/tsconfig.result-narrowing.json",
+ "check:types:fixture:application-output": "tsc -p tests/fixtures/typecheck/tsconfig.application-output.json",
+ "check:types:fixture:application-input": "tsc -p tests/fixtures/typecheck/tsconfig.application-input.json",
+ "check:types:fixture:feature-input": "tsc -p tests/fixtures/typecheck/tsconfig.feature-input.json",
+ "check:types:fixture:failure-kind": "tsc -p tests/fixtures/typecheck/tsconfig.failure-kind.json",
+ "check:types:fixture:reference-operation": "tsc -p tests/fixtures/typecheck/tsconfig.reference-operation.json",
+ "check:types:fixture:async-overlay": "tsc -p tests/fixtures/typecheck/tsconfig.async-overlay.json",
+ "check:types:fixture:route-runtime": "tsc -p tests/fixtures/typecheck/tsconfig.route-runtime.json",
+ "check:types:fixture:page-action": "tsc -p tests/fixtures/typecheck/tsconfig.page-action.json",
+ "check:types:fixture:icon-button": "tsc -p tests/fixtures/typecheck/tsconfig.icon-button.json",
+ "check:types:fixture:i18n-key": "tsc -p tests/fixtures/typecheck/tsconfig.message-key.json",
+ "check:types:fixture:i18n-params": "tsc -p tests/fixtures/typecheck/tsconfig.message-params.json",
+ "check:types:fixture:diagnostics": "tsc -p tests/fixtures/typecheck/tsconfig.diagnostics-port.json",
+ "check:types:fixture:image-resolve-signal": "tsc -p tests/fixtures/typecheck/tsconfig.image-cdn-resolve-signal.json",
+ "test:runtime-schema": "node scripts/run-vitest.ts run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests",
+ "test:unit": "node scripts/run-vitest.ts run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml",
+ "test:contract": "node scripts/run-vitest.ts run tests/contract --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/contract.xml",
+ "test:system": "node scripts/check-system-test-prerequisites.ts && node scripts/run-vitest.ts run tests/system --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/system.xml",
+ "test:component": "node scripts/run-vitest.ts run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml",
+ "test:integration": "node scripts/run-vitest.ts run tests/integration --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/integration.xml",
+ "test:http-scenario-catalog": "node scripts/run-vitest.ts run tests/integration/http-scenario-catalog.test.ts --reporter=default --maxWorkers=1",
"test:http-scenario-evidence": "node scripts/run-http-scenario-evidence.ts",
- "test:recipes": "vitest run tests/recipes --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/optional-recipes.xml --passWithNoTests",
+ "test:recipes": "node scripts/run-vitest.ts run tests/recipes --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/optional-recipes.xml --passWithNoTests",
"test:e2e": "playwright test",
"test:e2e:dev": "playwright test --config playwright.dev.config.ts",
"test:browser-capabilities": "playwright test --config playwright.capabilities.config.ts",
@@ -75,12 +77,12 @@
"test:optional-recipe-removal": "node scripts/test-optional-recipe-removal.ts",
"test:browser-file-storage-removal": "node scripts/test-browser-file-storage-runtime-removal.ts",
"test:realtime-removal": "node scripts/test-realtime-runtime-removal.ts",
- "test:reference-feature": "vitest run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests",
- "test:tech-log": "vitest run tests/features/tech-log --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/tech-log.xml",
+ "test:reference-feature": "node scripts/run-vitest.ts run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests",
+ "test:tech-log": "node scripts/run-vitest.ts run tests/features/tech-log --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/tech-log.xml",
"check:v8-coverage-counter-semantics": "node scripts/check-v8-coverage-counter-semantics.ts",
- "test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && vitest run tests/runtime-schema tests/unit tests/component tests/integration tests/features/reference-feature tests/features/tech-log --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.ts",
+ "test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && node scripts/run-vitest.ts run tests/runtime-schema tests/unit tests/contract tests/component tests/integration tests/features/reference-feature tests/features/tech-log --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.ts",
"check:coverage:fixture": "node scripts/check-risk-coverage.ts --summary tests/fixtures/coverage/below-threshold.json --artifact artifacts/quality/risk-coverage-fixture.json",
- "test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:component && corepack pnpm test:integration && corepack pnpm test:reference-feature && corepack pnpm check:tech-log-contract && corepack pnpm test:tech-log && corepack pnpm test:recipes",
+ "test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:contract && corepack pnpm test:component && corepack pnpm test:integration && corepack pnpm test:reference-feature && corepack pnpm check:tech-log-contract && corepack pnpm test:tech-log && corepack pnpm test:recipes",
"verify:lockfile": "corepack pnpm install --frozen-lockfile --ignore-scripts",
"check:frozen-lockfile:fixture": "node scripts/check-frozen-lockfile-fixture.ts",
"generate:artifact-schemas": "node scripts/generate-artifact-schemas.ts",
@@ -130,7 +132,14 @@
"build:app-only": "vite build && node scripts/generate-build-manifest.ts",
"generate:contract-set": "node scripts/generate-contract-set.ts",
"check:types:web-worker": "tsc --project tsconfig.web-worker.json",
- "check:types:service-worker": "tsc --project tsconfig.service-worker.json"
+ "check:types:service-worker": "tsc --project tsconfig.service-worker.json",
+ "check:types:fixture:http-operation-input": "tsc -p tests/fixtures/typecheck/tsconfig.http-operation-input.json",
+ "check:types:fixture:http-wire-mapper": "tsc -p tests/fixtures/typecheck/tsconfig.http-wire-mapper.json",
+ "check:types:fixture:http-operation-id": "tsc -p tests/fixtures/typecheck/tsconfig.http-operation-id.json",
+ "check:types:fixture:http-route-id": "tsc -p tests/fixtures/typecheck/tsconfig.http-route-id.json",
+ "check:types:fixture:feature-contribution-input": "tsc -p tests/fixtures/typecheck/tsconfig.feature-contribution-input.json",
+ "check:types:fixture:feature-capability-selection": "tsc -p tests/fixtures/typecheck/tsconfig.feature-capability-selection.json",
+ "check:types:fixture:direct-feature-composition": "tsc -p tests/fixtures/typecheck/tsconfig.direct-feature-composition.json"
},
"dependencies": {
"@fontsource/ibm-plex-mono": "5.3.0",
diff --git a/scripts/check-adapter-inventory.ts b/scripts/check-adapter-inventory.ts
index 07009a4..c520019 100644
--- a/scripts/check-adapter-inventory.ts
+++ b/scripts/check-adapter-inventory.ts
@@ -130,6 +130,12 @@ async function main(): Promise {
// let an unrelated production import satisfy the gate while Image and
// Resumable kept their own diverging copies of the same mechanics — which is
// exactly how the four hand-written versions drifted apart in the first place.
+ //
+ // 이 목록은 재검토가 이름으로 지목한 네 파일만 덮는다. 같은 두 그룹의
+ // `image-cdn-runtime.ts`와 `resumable-upload-runtime.ts`는 여기 없고 지금도
+ // 자기 abort 사본을 들고 있다. 어댑터 전체로는 23개 파일이 그렇다. 그 전수
+ // 이행은 abort 의미론을 바꾸는 별도 작업이라 이 목록으로 강제하지 않고,
+ // 아래 래칫이 개수가 늘어나는 것만 막는다.
const REQUIRED_ABORT_CONSUMERS: readonly string[] = [
"src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts",
"src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts",
@@ -164,6 +170,7 @@ async function main(): Promise {
const PRIMITIVE_PATH = path.resolve(
"src/adapters/platform/abortable-operation.ts",
);
+ const PRIMITIVE_SPECIFIER = "platform/abortable-operation.ts";
for (const consumer of REQUIRED_ABORT_CONSUMERS) {
if (!importerSet.has(consumer)) continue;
const source = readFileSync(consumer, "utf8");
@@ -181,6 +188,43 @@ async function main(): Promise {
}
}
+ // 손수 짠 abort 배선은 줄어들기만 해야 한다.
+ //
+ // 커널 `platform/abortable-operation.ts`가 있는데도 어댑터 23개 파일이
+ // `addEventListener("abort")`로 같은 race/cleanup을 각자 짠다. 그 전수 이행은
+ // 동작이 바뀌는 큰 작업이라 한 번에 하지 않는다. 대신 개수를 여기 고정해
+ // 되돌아가지 못하게 한다. 이행으로 숫자가 내려가면 이 상수도 같이 내린다.
+ // `platform/`은 커널 자신이므로 세지 않는다.
+ //
+ // 24 → 23: `browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts`가
+ // IndexedDB 커널로 옮겨가면서 자기 abort 리스너를 지웠다.
+ // 23 → 22: `storage/indexeddb/indexeddb-maintenance.ts`가 같은 이유로 지웠다.
+ // 22 → 21: `storage/indexeddb/indexeddb-runtime.ts`가 같은 이유로 지웠다.
+ // 이것으로 IndexedDB 어댑터 4벌이 모두 커널을 쓴다.
+ const HAND_ROLLED_ABORT_CEILING = 21;
+ const handRolledScan = spawnSync(
+ "git",
+ ["grep", "-l", 'addEventListener("abort"', "--", "src/adapters"],
+ { encoding: "utf8" },
+ );
+ const handRolledFiles = (
+ handRolledScan.status === 0 ? handRolledScan.stdout : ""
+ )
+ .split("\n")
+ .filter(Boolean)
+ .filter((file) => !file.startsWith("src/adapters/platform/"))
+ .filter((file) => !readFileSync(file, "utf8").includes(PRIMITIVE_SPECIFIER))
+ .sort();
+ if (handRolledFiles.length > HAND_ROLLED_ABORT_CEILING) {
+ problems.push(
+ `abortable-operation: hand-rolled abort wiring grew to ` +
+ `${handRolledFiles.length} files (ceiling ${HAND_ROLLED_ABORT_CEILING}). ` +
+ `Use platform/abortable-operation.ts instead of a new listener pair. ` +
+ `Current offenders (the new one is whichever this change added): ` +
+ `${handRolledFiles.join(", ")}`,
+ );
+ }
+
if (problems.length > 0) {
for (const problem of problems) console.error(problem);
process.exitCode = 1;
@@ -195,7 +239,9 @@ async function main(): Promise {
} shared extensions PASS; ` +
`fixture node_modules linking PASS; ` +
`shared abort primitive: ${importers.length} importers ` +
- `(${importers.join(", ")}) PASS`,
+ `(${importers.join(", ")}) PASS; ` +
+ `hand-rolled abort wiring: ${handRolledFiles.length}/` +
+ `${HAND_ROLLED_ABORT_CEILING} files (ratchet) PASS`,
);
}
diff --git a/scripts/check-architecture.ts b/scripts/check-architecture.ts
index 6b2957a..ee4c14f 100644
--- a/scripts/check-architecture.ts
+++ b/scripts/check-architecture.ts
@@ -824,12 +824,13 @@ async function runGraphFixtureChecks(): Promise {
"tests/fixtures/architecture/dependency-graph",
);
const allowedRoot = resolve(fixtureRoot, "allowed");
- const [allowedGraph, unresolvedGraph, layerGraph, cycleGraph] =
+ const [allowedGraph, unresolvedGraph, layerGraph, cycleGraph, barrelGraph] =
await Promise.all([
analyzeSourceGraph(allowedRoot, "src"),
analyzeSourceGraph(resolve(fixtureRoot, "unresolved"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "layer"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "cycle"), "src"),
+ analyzeSourceGraph(resolve(fixtureRoot, "barrel"), "src"),
]);
const allowedFiles = new Set(await listFiles(allowedRoot));
const allowedSourceFile = resolve(
@@ -850,6 +851,21 @@ async function runGraphFixtureChecks(): Promise {
),
);
const assertions = [
+ {
+ name: "deep adapter import from outside the group is rejected",
+ passed: blockingViolations(barrelGraph).some(
+ ({ rule, source, target }) =>
+ rule === "adapter-groups-are-reached-through-their-barrel" &&
+ source === "src/bootstrap/compose-deep.ts" &&
+ target === "src/adapters/http/client.ts",
+ ),
+ },
+ {
+ name: "barrel import from outside the group is accepted",
+ passed: !blockingViolations(barrelGraph).some(
+ ({ source }) => source === "src/bootstrap/compose-barrel.ts",
+ ),
+ },
{
name: "explicit TS specifier resolves to a TS module",
passed: allowedGraph.dependencies.some(
diff --git a/scripts/check-compatibility.ts b/scripts/check-compatibility.ts
index dc2a79a..32f3a9b 100644
--- a/scripts/check-compatibility.ts
+++ b/scripts/check-compatibility.ts
@@ -1,6 +1,6 @@
import { mkdir, readFile } from "node:fs/promises";
-import { classifyObjectSchemaChange } from "../src/application/policies/compatibility.ts";
+import { classifyObjectSchemaChange } from "../src/contracts/compatibility.ts";
import { compatibilityFixturesArtifactSchema } from "./contracts/release-artifacts.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
diff --git a/scripts/check-system-test-prerequisites.ts b/scripts/check-system-test-prerequisites.ts
new file mode 100644
index 0000000..c43e32f
--- /dev/null
+++ b/scripts/check-system-test-prerequisites.ts
@@ -0,0 +1,55 @@
+import { constants } from "node:fs";
+import { access, readFile } from "node:fs/promises";
+import { spawnSync } from "node:child_process";
+
+const failures: string[] = [];
+
+async function requireExecutable(path: string, label: string): Promise {
+ try {
+ await access(path, constants.X_OK);
+ } catch {
+ failures.push(`${label} is required at ${path}`);
+ }
+}
+
+await Promise.all([
+ requireExecutable("/usr/bin/bwrap", "bubblewrap"),
+ requireExecutable("/usr/bin/systemctl", "systemctl"),
+ requireExecutable("/usr/bin/tar", "tar"),
+]);
+
+try {
+ const controllers = await readFile("/sys/fs/cgroup/cgroup.controllers", "utf8");
+ if (controllers.trim().length === 0) {
+ failures.push("cgroup v2 controllers are unavailable");
+ }
+} catch {
+ failures.push("cgroup v2 is required at /sys/fs/cgroup/cgroup.controllers");
+}
+
+if (!failures.some((failure) => failure.includes("systemctl"))) {
+ const probe = spawnSync("/usr/bin/systemctl", ["show-environment"], {
+ encoding: "utf8",
+ timeout: 3_000,
+ });
+ if (probe.error || probe.status !== 0) {
+ failures.push("a reachable systemd manager bus is required");
+ }
+}
+
+if (failures.length > 0) {
+ process.stderr.write(
+ [
+ "System/CI-runner test prerequisites are unavailable:",
+ ...failures.map((failure) => ` - ${failure}`),
+ "",
+ "Run test:unit/test:contract/test:component/test:integration for the",
+ "developer loop. test:system is intentionally reserved for a compatible",
+ "Linux CI-runner host.",
+ "",
+ ].join("\n"),
+ );
+ process.exit(1);
+}
+
+process.stdout.write("System test prerequisites: PASS\n");
diff --git a/scripts/contracts/ci-gates.ts b/scripts/contracts/ci-gates.ts
index f3fc962..81adcf9 100644
--- a/scripts/contracts/ci-gates.ts
+++ b/scripts/contracts/ci-gates.ts
@@ -482,7 +482,13 @@ const CANONICAL_GATE_SHAPE_SHA256 =
// 주제 화면 셋(`/topics`, `/topics/:slug/:variant`, `/studio/topics/:id`): FE-GATE-009 가 각
// 라우트의 수동 접근성 증거를 얻어 다시 계산했다. 같은 방법이다 — 87a22f68… 을 이전
// gates.json 에서 먼저 재현해 계산이 맞는지 확인한 뒤 새 파일을 해싱했다.
- "8a1a5479041cbce479b59d669c97921a5ba83dd7cac309131723acc221903528";
+ // Template sync (ebea300). Both sides again carried a digest of their own
+ // gate set — 8a1a5479… here, 43dc4ed1… upstream — and neither describes the
+ // merged config/ci/gates.json. Recomputed from the merged file by the same
+ // method: 8a1a5479… was first reproduced from the pre-merge gates.json, so
+ // the computation that produced this value is the one the constant is
+ // pinned under.
+ "629e5898f6a38d5056fc6a4bee834c47f363669ce9925a2c0dabeddd64d11879";
function canonicalGateShapeSha256(gates: CiGateContract["gates"]): string {
const normalized = gates.map(
@@ -527,9 +533,11 @@ function canonicalAuthorityBaselineFailures(contract: CiGateContract): string[]
// `check-dev-release-manifest`. No gate read `public/*.json` at all, so a
// fixture that did not declare the compiled contract set broke `pnpm dev`
// outright while every static gate stayed green.
- if (contract.commands.length !== 85 || commandReferenceCount !== 97) {
+ // Template sync (ebea300). The template's own baseline was 91/103; this
+ // product's was 85/97. Recomputed from the merged config/ci/gates.json.
+ if (contract.commands.length !== 94 || commandReferenceCount !== 106) {
failures.push(
- `command authority baseline must contain exactly 85 definitions and 97 references; received ${contract.commands.length} definitions and ${commandReferenceCount} references`,
+ `command authority baseline must contain exactly 94 definitions and 106 references; received ${contract.commands.length} definitions and ${commandReferenceCount} references`,
);
}
// Template merge. 126 product artifacts plus the two the template added.
@@ -548,8 +556,10 @@ function canonicalAuthorityBaselineFailures(contract: CiGateContract): string[]
// 그리고 Studio 의 주제 편집 `/studio/topics/:id`.
// 환경 구성(SETUP) 문서 종류가 `/setups/:slug` 를 더했다 — 설치된 라우트마다 수동 접근성
// 증거를 하나씩 갖는 규칙이 그대로 적용된다.
- if (contract.artifacts.length !== 139) {
- failures.push(`artifact authority baseline must contain exactly 139 artifacts; received ${contract.artifacts.length}`);
+ // Template sync (ebea300). The template's own baseline was 109 artifacts;
+ // this product's was 139. Recomputed from the merged config/ci/gates.json.
+ if (contract.artifacts.length !== 141) {
+ failures.push(`artifact authority baseline must contain exactly 141 artifacts; received ${contract.artifacts.length}`);
}
if (contract.stages.length !== 5) {
failures.push(`stage authority baseline must contain exactly 5 stages; received ${contract.stages.length}`);
diff --git a/scripts/drill-runbook.ts b/scripts/drill-runbook.ts
index 4a967ef..1c1a5a6 100644
--- a/scripts/drill-runbook.ts
+++ b/scripts/drill-runbook.ts
@@ -3,7 +3,7 @@ import { pathToFileURL } from "node:url";
import { shouldRetry } from "../src/adapters/http/retry-policy.ts";
import { createTelemetryAdapter } from "../src/adapters/telemetry/best-effort-telemetry.ts";
-import { verifyCompatibilityTuple } from "../src/application/policies/compatibility.ts";
+import { verifyCompatibilityTuple } from "../src/contracts/compatibility.ts";
import type { StoragePort } from "../src/application/ports/storage-port.ts";
import { decideChunkRecovery } from "../src/application/use-cases/decide-chunk-recovery.ts";
import { validateRuntimeConfig } from "../src/bootstrap/runtime-config-schema.ts";
diff --git a/scripts/generate-supply-chain.ts b/scripts/generate-supply-chain.ts
index 18a33e5..24682bd 100644
--- a/scripts/generate-supply-chain.ts
+++ b/scripts/generate-supply-chain.ts
@@ -21,6 +21,7 @@ import {
flattenPnpmDependencyTree,
isValidSha512Integrity,
parsePnpmLockfilePackages,
+ PROJECT_NAME,
supplyChainDigest,
verifySupplyChainCoherence,
} from "./lib/supply-chain.ts";
@@ -270,7 +271,7 @@ const provenance = {
],
},
runDetails: {
- builder: { id: "local:tech-log-frontend" },
+ builder: { id: `local:${PROJECT_NAME}` },
metadata: { invocationId: "LOCAL_UNSIGNED" },
},
materials: {
diff --git a/scripts/lib/local-release-evidence.ts b/scripts/lib/local-release-evidence.ts
index 3ab0018..50b1f47 100644
--- a/scripts/lib/local-release-evidence.ts
+++ b/scripts/lib/local-release-evidence.ts
@@ -66,6 +66,7 @@ import { secretScanRules } from "./secret-scan.ts";
import {
isValidSha512Integrity,
parsePnpmLockfilePackages,
+ PROJECT_NAME,
supplyChainDigest,
verifySupplyChainCoherence,
} from "./supply-chain.ts";
@@ -304,8 +305,7 @@ export async function verifyLocalSupplyChainEvidence(
});
}
-export const LOCAL_EVIDENCE_VERIFIER_ID =
- "tech-log-frontend/local-evidence-verifier";
+export const LOCAL_EVIDENCE_VERIFIER_ID = `${PROJECT_NAME}/local-evidence-verifier`;
export const LOCAL_EVIDENCE_VERIFIER_VERSION = "1";
export {
LOCAL_EVIDENCE_POLICY_INPUT_PATHS,
diff --git a/scripts/lib/provider-evidence.ts b/scripts/lib/provider-evidence.ts
index 7d63eb6..afb8d1a 100644
--- a/scripts/lib/provider-evidence.ts
+++ b/scripts/lib/provider-evidence.ts
@@ -4,13 +4,13 @@ import { z } from "zod";
import {
canonicalizeSupplyChainValue,
+ PROJECT_NAME,
supplyChainDigest,
} from "./supply-chain.ts";
export const PROVIDER_FUTURE_SKEW_MS = 5 * 60 * 1_000;
export const PROVIDER_MAX_LIFETIME_MS = 2 * 60 * 60 * 1_000;
-export const PROMOTION_VERIFIER_ID =
- "tech-log-frontend/promotion-verifier";
+export const PROMOTION_VERIFIER_ID = `${PROJECT_NAME}/promotion-verifier`;
export const PROMOTION_VERIFIER_VERSION = "3";
const sha256 = z.string().regex(/^[a-f0-9]{64}$/u);
diff --git a/scripts/lib/release-runtime-coherence.ts b/scripts/lib/release-runtime-coherence.ts
index 35f103f..857cf53 100644
--- a/scripts/lib/release-runtime-coherence.ts
+++ b/scripts/lib/release-runtime-coherence.ts
@@ -1,4 +1,4 @@
-import { isVersionCompatible } from "../../src/application/policies/compatibility.ts";
+import { isVersionCompatible } from "../../src/contracts/compatibility.ts";
import { verifyContractSet } from "../../src/contracts/contract-set.ts";
import type { InstalledContractPackageIdentity } from "../../src/contracts/external-contract-runtime.ts";
import type { ReleaseArtifact } from "../../src/contracts/release-artifacts.ts";
diff --git a/scripts/lib/supply-chain.ts b/scripts/lib/supply-chain.ts
index 2150ca0..da88f30 100644
--- a/scripts/lib/supply-chain.ts
+++ b/scripts/lib/supply-chain.ts
@@ -1,6 +1,27 @@
import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
+function readProjectName(): string {
+ const manifest: unknown = JSON.parse(
+ readFileSync(new URL("../../package.json", import.meta.url), "utf8"),
+ );
+ const name =
+ typeof manifest === "object" && manifest !== null
+ ? (manifest as { name?: unknown }).name
+ : undefined;
+ if (typeof name !== "string" || name.length === 0) {
+ throw new TypeError("package.json must declare a non-empty \"name\"");
+ }
+ return name;
+}
+
+/**
+ * Identity every release artifact is attributed to. A project derived from this
+ * template renames itself by editing `name` in package.json and nothing else.
+ */
+export const PROJECT_NAME = readProjectName();
+
export type DependencyScope = "production" | "development";
export type LockfilePackage = Readonly<{
name: string;
diff --git a/scripts/run-vitest.ts b/scripts/run-vitest.ts
new file mode 100644
index 0000000..09cd3c1
--- /dev/null
+++ b/scripts/run-vitest.ts
@@ -0,0 +1,67 @@
+import { spawnSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+
+function assertSupportedNode(): void {
+ const [majorText = "0", minorText = "0"] = process.versions.node.split(".");
+ const major = Number(majorText);
+ const minor = Number(minorText);
+
+ if (major !== 24 || minor < 11) {
+ process.stderr.write(
+ [
+ `Unsupported Node.js runtime for tests: ${process.versions.node}`,
+ "Required by package.json: >=24.11.0 <25.0.0",
+ "Use the repository-supported Node.js runtime before running a test suite.",
+ "",
+ ].join("\n"),
+ );
+ process.exit(1);
+ }
+}
+
+assertSupportedNode();
+
+const vitestEntry = fileURLToPath(
+ new URL("../node_modules/vitest/vitest.mjs", import.meta.url),
+);
+if (!existsSync(vitestEntry)) {
+ process.stderr.write(
+ "Vitest is not installed. Run the repository package installation first.\n",
+ );
+ process.exit(1);
+}
+
+const testEnvironment: NodeJS.ProcessEnv = {
+ ...process.env,
+ NODE_ENV: "test",
+};
+for (const key of [
+ "npm_config_userconfig",
+ "npm_config_prefix",
+ "npm_config_globalconfig",
+ "NPM_CONFIG_USERCONFIG",
+ "NPM_CONFIG_PREFIX",
+ "NPM_CONFIG_GLOBALCONFIG",
+]) {
+ delete testEnvironment[key];
+}
+
+const result = spawnSync(
+ process.execPath,
+ [vitestEntry, ...process.argv.slice(2)],
+ {
+ stdio: "inherit",
+ env: testEnvironment,
+ },
+);
+
+if (result.error) {
+ throw result.error;
+}
+if (result.signal) {
+ process.stderr.write(`Vitest terminated by signal ${result.signal}.\n`);
+ process.exit(1);
+}
+
+process.exit(result.status ?? 1);
diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts
index 6f653e4..70e52e7 100644
--- a/scripts/test-sample-removal.ts
+++ b/scripts/test-sample-removal.ts
@@ -42,24 +42,53 @@ const featureOwnedPaths = [
featureSource,
featureTests,
"tests/integration/http-scenario-catalog.test.ts",
- "tests/integration/http-execution-v3-observability.test.ts",
"tests/features/tech-log/runtime-composition.test.ts",
+ // Template sync (ebea300). The kill-switch test attributes a real route to a
+ // real installed feature id; with the sample feature gone there is no
+ // installed feature left to attribute to, so it goes with it.
+ "tests/component/product-feature-switch.test.tsx",
+ // Same sync. This TechLog test imports the sample feature's contract
+ // contribution on purpose — it proves a 403 on *another* feature's operation
+ // does not discard TechLog's CSRF token, which needs a second feature to
+ // exist. With the sample feature gone the premise is gone, so the test goes
+ // with it rather than being rewritten around a feature that is not there.
+ "tests/features/tech-log/studio-csrf-composition.test.ts",
"tests/e2e/reference-form.spec.ts",
"tests/e2e/reference-route.spec.ts",
"tests/mocks",
"tests/fixtures/typecheck/invalid-feature-input.ts",
"tests/fixtures/typecheck/invalid-reference-operation.ts",
+ "tests/fixtures/typecheck/invalid-http-operation-input.ts",
+ "tests/fixtures/typecheck/invalid-http-wire-mapper.ts",
+ "tests/fixtures/typecheck/invalid-http-operation-id.ts",
+ "tests/fixtures/typecheck/invalid-http-route-id.ts",
+ "tests/fixtures/typecheck/invalid-feature-contribution-input.ts",
+ "tests/fixtures/typecheck/invalid-feature-capability-selection.ts",
+ "tests/fixtures/typecheck/tsconfig.feature-input.json",
+ "tests/fixtures/typecheck/tsconfig.reference-operation.json",
+ "tests/fixtures/typecheck/tsconfig.http-operation-input.json",
+ "tests/fixtures/typecheck/tsconfig.http-wire-mapper.json",
+ "tests/fixtures/typecheck/tsconfig.http-operation-id.json",
+ "tests/fixtures/typecheck/tsconfig.http-route-id.json",
+ "tests/fixtures/typecheck/tsconfig.feature-contribution-input.json",
+ "tests/fixtures/typecheck/tsconfig.feature-capability-selection.json",
];
+const emptyProductManifest = `export const COMPILED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze([]);
+export const INSTALLED_PRODUCT_FEATURES: readonly never[] = Object.freeze([]);
+export const INSTALLED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze([]);
+`;
+
const emptyContracts = `import type { RouteDefinition } from "../contracts/routes.ts";
import { PLATFORM_SCHEMA_REGISTRY } from "../contracts/schema-registry.ts";
+import { INSTALLED_PRODUCT_FEATURES } from "./installed-product-manifest.ts";
import {
TECH_LOG_ROUTE_REGISTRY,
TECH_LOG_ROUTE_RUNTIME_CONTRACT,
TECH_LOG_ROUTE_SCHEMA_REGISTRY,
} from "./tech-log/contracts/tech-log-route-contract.ts";
-export const INSTALLED_FEATURE_CONTRACTS: readonly unknown[] = Object.freeze([]);
+export const INSTALLED_FEATURE_CONTRACTS = INSTALLED_PRODUCT_FEATURES;
export const ROUTE_REGISTRY = TECH_LOG_ROUTE_REGISTRY;
export const ROUTE_RUNTIME_CONTRACT = TECH_LOG_ROUTE_RUNTIME_CONTRACT;
export const API_OPERATIONS = Object.freeze({});
@@ -73,6 +102,7 @@ export const SCHEMA_REGISTRY = Object.freeze({
...PLATFORM_SCHEMA_REGISTRY,
...TECH_LOG_ROUTE_SCHEMA_REGISTRY,
});
+export const ROUTE_FEATURE_OWNER: Readonly> = Object.freeze({});
export const NAVIGATION_ROUTES = Object.freeze(
Object.values(ROUTE_REGISTRY)
.filter((definition) => definition.navigationOrder !== null)
@@ -103,12 +133,37 @@ export const ROUTE_CODECS = Object.freeze({
export const ROUTE_RUNTIME = TECH_LOG_ROUTE_RUNTIME;
`;
-const emptyAdapters = `import { createTechLogFeatureInstalledInput } from "./tech-log/adapters/create-tech-log-feature-input.ts";
+const emptyAdapters = `import type { InstalledHttpOperationExecutor } from "../adapters/http/index.ts";
+import type { ApplicationFeatureInputs } from "../application/ports/in/application-api.ts";
+import {
+ composeFeatureAdapterInputs,
+ type InstalledFeatureInputs,
+} from "./feature-adapter-contribution.ts";
+import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts";
+import {
+ createTechLogFeatureInstalledInput,
+ type TechLogInstallContext,
+} from "./tech-log/adapters/create-tech-log-feature-input.ts";
+import { TECH_LOG_FEATURE_ID } from "./tech-log/application/tech-log-feature-input.ts";
-export function createInstalledFeatureInputs(_context: unknown) {
- void _context;
- const techLog = createTechLogFeatureInstalledInput();
- return Object.freeze({ [techLog.featureId]: techLog.input });
+const COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS = Object.freeze([] as const);
+
+type ProductFeatureInputs = InstalledFeatureInputs &
+ Readonly>;
+
+export function createInstalledFeatureInputs(
+ context: TechLogInstallContext &
+ Readonly<{ http: InstalledHttpOperationExecutor }>,
+): ProductFeatureInputs {
+ const techLog = createTechLogFeatureInstalledInput(context);
+ return Object.freeze({
+ ...composeFeatureAdapterInputs(
+ COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS,
+ INSTALLED_PRODUCT_FEATURE_IDS,
+ context,
+ ),
+ [techLog.featureId]: techLog.input,
+ }) as ProductFeatureInputs;
}
`;
@@ -117,9 +172,17 @@ const emptyContractContributions = `import {
type InstalledContractContribution,
type InstalledContractPackageIdentity,
} from "../contracts/external-contract-runtime.ts";
+import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts";
+
+const COMPILED_CONTRACT_CONTRIBUTIONS: readonly InstalledContractContribution[] =
+ Object.freeze([]);
export const INSTALLED_CONTRACT_CONTRIBUTIONS: readonly InstalledContractContribution[] =
- Object.freeze([]);
+ Object.freeze(
+ COMPILED_CONTRACT_CONTRIBUTIONS.filter((contribution) =>
+ INSTALLED_PRODUCT_FEATURE_IDS.includes(contribution.featureId),
+ ),
+ );
export const COMPOSED_CONTRACT_CONTRIBUTIONS = composeContractContributions(
INSTALLED_CONTRACT_CONTRIBUTIONS,
@@ -168,7 +231,9 @@ try {
await prepareRemovalFixture(fixtureRoot);
for (const excludedFixtureTest of [
"tests/integration/security-followup-archive.test.ts",
- "tests/unit/ci-artifact-contract.test.ts",
+ // Template sync (ebea300). `ci-artifact-contract` moved to
+ // `tests/system/ci-runner/`, which `test:all` does not run, so it no longer
+ // needs excluding — upstream dropped it from this list for the same reason.
"tests/unit/ci-workflow-generation.test.ts",
"tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap",
"tests/unit/removal-fixture.test.ts",
@@ -202,6 +267,10 @@ try {
force: true,
});
}
+ await writeFile(
+ path.join(fixtureRoot, "src/features/installed-product-manifest.ts"),
+ emptyProductManifest,
+ );
await writeFile(
path.join(fixtureRoot, "src/features/installed-feature-contracts.ts"),
emptyContracts,
@@ -223,6 +292,34 @@ try {
emptyContractContributions,
);
+ // Runtime profiles are product configuration. Once the feature is physically
+ // removed, its override key must disappear too or the built config still
+ // advertises a source capability that no longer exists.
+ for (const profile of [
+ "local",
+ "development",
+ "staging",
+ "production",
+ ] as const) {
+ const profilePath = path.join(
+ fixtureRoot,
+ "config/runtime",
+ `${profile}.json`,
+ );
+ const runtimeConfig = JSON.parse(
+ await readFile(profilePath, "utf8"),
+ ) as {
+ FEATURE_OVERRIDES?: Record;
+ };
+ if (runtimeConfig.FEATURE_OVERRIDES) {
+ delete runtimeConfig.FEATURE_OVERRIDES["reference-feature"];
+ }
+ await writeFile(
+ profilePath,
+ `${JSON.stringify(runtimeConfig, null, 2)}\n`,
+ );
+ }
+
const retainedCriticalModules = coveragePolicy.criticalModules.filter(
(modulePolicy) => !modulePolicy.path?.startsWith(`${featureSource}/`),
);
@@ -317,6 +414,12 @@ try {
const removedCiScripts = new Set([
"check:types:fixture:feature-input",
"check:types:fixture:reference-operation",
+ "check:types:fixture:http-operation-input",
+ "check:types:fixture:http-wire-mapper",
+ "check:types:fixture:http-operation-id",
+ "check:types:fixture:http-route-id",
+ "check:types:fixture:feature-contribution-input",
+ "check:types:fixture:feature-capability-selection",
"test:http-scenario-evidence",
"test:reference-feature",
]);
@@ -391,13 +494,17 @@ try {
["build", runPnpm("build")],
];
const builtResidue: string[] = [];
- for (const file of await filesBelow(path.join(fixtureRoot, "dist"))) {
- if (!/\.(?:js|css|html|json)$/.test(file)) continue;
- const content = await readFile(file, "utf8");
- if (
- /REFERENCE_RESOURCE|reference-feature|reference-resource/i.test(content)
- ) {
- builtResidue.push(path.relative(fixtureRoot, file));
+ const buildSucceeded =
+ checks.find(([name]) => name === "build")?.[1] === true;
+ if (buildSucceeded) {
+ for (const file of await filesBelow(path.join(fixtureRoot, "dist"))) {
+ if (!/\.(?:js|css|html|json)$/.test(file)) continue;
+ const content = await readFile(file, "utf8");
+ if (
+ /REFERENCE_RESOURCE|reference-feature|reference-resource/i.test(content)
+ ) {
+ builtResidue.push(path.relative(fixtureRoot, file));
+ }
}
}
const routeCatalog = await import(
diff --git a/scripts/verify-release.ts b/scripts/verify-release.ts
index ae4eda2..dbc6c5e 100644
--- a/scripts/verify-release.ts
+++ b/scripts/verify-release.ts
@@ -5,7 +5,7 @@ import { pathToFileURL } from "node:url";
import {
verifyCompatibilityTuple,
type CompatibilityTuple,
-} from "../src/application/policies/compatibility.ts";
+} from "../src/contracts/compatibility.ts";
import type { InstalledContractPackageIdentity } from "../src/contracts/external-contract-runtime.ts";
import {
parseBuildManifestArtifact,
diff --git a/src/adapters/auth/index.ts b/src/adapters/auth/index.ts
new file mode 100644
index 0000000..cb8b996
--- /dev/null
+++ b/src/adapters/auth/index.ts
@@ -0,0 +1,9 @@
+export {
+ createAnonymousSessionAdapter,
+ createDemoSessionAdapter,
+ createExternalAuthSessionAdapter,
+ createUnavailableSessionAdapter,
+ DEMO_AUTHORIZATION_MARKER,
+ type DemoSessionAdapter,
+ type ExternalSessionOwner,
+} from "./external-session-adapter.ts";
diff --git a/src/adapters/browser-files/browser-file-picker.ts b/src/adapters/browser-files/browser-file-picker.ts
index 00ef001..c99270c 100644
--- a/src/adapters/browser-files/browser-file-picker.ts
+++ b/src/adapters/browser-files/browser-file-picker.ts
@@ -108,14 +108,12 @@ export class NativeInputFilePicker implements DisposableFilePicker {
const addInputEvent = options.input.addEventListener;
const removeInputEvent = options.input.removeEventListener;
const getInputAttribute = options.input.getAttribute;
- const showPicker = options.input.showPicker;
const click = options.input.click;
if (
typeof addInputEvent !== "function" ||
typeof removeInputEvent !== "function" ||
typeof getInputAttribute !== "function" ||
- (typeof showPicker !== "function" &&
- typeof click !== "function")
+ typeof click !== "function"
) {
throw new TypeError("Native file input API is invalid.");
}
@@ -123,10 +121,11 @@ export class NativeInputFilePicker implements DisposableFilePicker {
add: addInputEvent.bind(options.input),
remove: removeInputEvent.bind(options.input),
getAttribute: getInputAttribute.bind(options.input),
- activate:
- typeof showPicker === "function"
- ? showPicker.bind(options.input)
- : click.bind(options.input),
+ // The baseline path intentionally uses click().
+ // showPicker() exists in multiple engines but is not a portable
+ // automation/event-interception contract. Enhanced native picking is a
+ // separate capability owned by EnhancedFilePicker.
+ activate: click.bind(options.input),
});
const windowHost = options.window ?? globalThis.window;
if (windowHost) {
diff --git a/src/adapters/browser-rpc/browser-rpc-runtime.ts b/src/adapters/browser-rpc/browser-rpc-runtime.ts
index 21b6057..1341c1d 100644
--- a/src/adapters/browser-rpc/browser-rpc-runtime.ts
+++ b/src/adapters/browser-rpc/browser-rpc-runtime.ts
@@ -8,7 +8,7 @@ import type {
BrowserRpcUnaryPort,
} from "../../application/ports/browser-rpc/index.ts";
import type { ClockPort } from "../../application/ports/clock-port.ts";
-import type { Result } from "../../application/result.ts";
+import type { Result } from "../../contracts/result.ts";
import {
installBrowserRpcContractBindings,
type InstalledBrowserRpcContractBindings,
diff --git a/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts b/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts
index ee95180..1861697 100644
--- a/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts
+++ b/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts
@@ -4,12 +4,26 @@ import type {
ResumableUploadCheckpointStore,
PartitionDeleteOutcome,
} from "../../../application/ports/browser-transfer/resumable-upload.ts";
-import type { BrowserDataResult } from "../../../application/ports/browser-file-storage/shared.ts";
+import type {
+ BrowserDataFailure,
+ BrowserDataFailureCode,
+ BrowserDataRecovery,
+ BrowserDataResult,
+} from "../../../application/ports/browser-file-storage/shared.ts";
+import { isBrowserDataFailureCode } from "../../../application/ports/browser-file-storage/shared.ts";
import {
browserDataFailure,
browserDataSuccess,
mapBrowserDataException,
} from "../../browser-file-storage/result.ts";
+import { snapshotAbortTimers } from "../../platform/abortable-operation.ts";
+import {
+ createIndexedDbConnection,
+ deleteIndexedDbDatabase,
+ openIndexedDbDatabase,
+ type IndexedDbTranslate,
+} from "../../platform/indexeddb-connection.ts";
+import { runIndexedDbTransaction } from "../../platform/indexeddb-transaction.ts";
import {
isResumableUploadCheckpoint,
SAFE_OPAQUE_ID,
@@ -20,6 +34,7 @@ const DATABASE_VERSION = 1;
const CHECKPOINT_STORE = "checkpoints";
const GOVERNANCE_STORE = "governance";
const GOVERNANCE_KEY = "scope-binding";
+const OPERATION = "UPLOAD_RECONCILE";
const DEFAULT_BLOCKED_TIMEOUT_MS = 5_000;
/**
@@ -65,10 +80,94 @@ type ScopeBinding = Readonly<{
partitionToken: string;
}>;
-type OpenFactory = (
- name: string,
- version?: number,
-) => IDBOpenDBRequest;
+/**
+ * `browserDataFailure` and `mapBrowserDataException` build a `Result`, while the
+ * kernel's `translate` contract wants the failure on its own. Both only ever
+ * build the failure arm, so the branch below is a narrowing, not a claim.
+ */
+function failureOf(result: BrowserDataResult): BrowserDataFailure {
+ if (result.ok) {
+ throw new TypeError("A browser data failure was expected.");
+ }
+ return result.error;
+}
+
+function checkpointFailure(
+ code: BrowserDataFailureCode,
+ options: Readonly<{
+ retryable?: boolean;
+ recovery?: BrowserDataRecovery;
+ }> = {},
+): BrowserDataFailure {
+ return failureOf(browserDataFailure(code, OPERATION, options));
+}
+
+function mappedFailure(error: unknown): BrowserDataFailure {
+ return failureOf(mapBrowserDataException(error, OPERATION));
+}
+
+/**
+ * The kernel keeps an admission's `detail` opaque, so a rejected scope binding
+ * carries its own failure through it and the guard hands that failure straight
+ * back. Any other shape would mean a second taxonomy grew beside this one.
+ */
+function admissionFailure(detail: unknown): BrowserDataFailure | null {
+ if (!detail || typeof detail !== "object") return null;
+ const record = detail as Record;
+ return isBrowserDataFailureCode(record.code) && record.operation === OPERATION
+ ? (detail as BrowserDataFailure)
+ : null;
+}
+
+/**
+ * BT-UP-03. The checkpoint store keeps its own failure table rather than the
+ * `mapIndexedDbException` the other three IndexedDB adapters share: the same
+ * native error is a different answer here (a `ConstraintError` recovers by
+ * REOPEN, a quota failure is retryable), and unifying the four tables is a
+ * separate change from moving the mechanics onto the kernel.
+ */
+const translate: IndexedDbTranslate = (cause) => {
+ switch (cause.kind) {
+ case "NATIVE_EXCEPTION":
+ return mappedFailure(cause.error);
+ case "NO_VALUE_PRODUCED":
+ // Three adapters call this UNAVAILABLE. Here a checkpoint transaction
+ // that committed without producing a value read a row it could not turn
+ // into a checkpoint, so reconciling is the only way forward; retrying
+ // would read the same row again.
+ return checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" });
+ case "BLOCKED":
+ case "BLOCKED_DEADLINE":
+ return checkpointFailure("BLOCKED", {
+ retryable: true,
+ recovery: "RESUME",
+ });
+ case "CALLER_ABORT":
+ return checkpointFailure("ABORTED");
+ case "CLOSED":
+ // A closed handle is not the caller aborting: the upload can resume once
+ // a new store is built over the partition.
+ return checkpointFailure("UNAVAILABLE", { recovery: "RESUME" });
+ case "UPGRADE_REJECTED":
+ // The schema body's own throw is what the caller sees. A rejection with
+ // no detail can only come from a null `newVersion`, which an open request
+ // never reports.
+ return cause.detail === undefined
+ ? checkpointFailure("MIGRATION_FAILED", { recovery: "READ_ONLY" })
+ : mappedFailure(cause.detail);
+ case "ADMISSION_REJECTED":
+ return (
+ admissionFailure(cause.detail) ??
+ checkpointFailure("POLICY_REJECTED", { recovery: "READ_ONLY" })
+ );
+ case "UNSUPPORTED":
+ return checkpointFailure("UNSUPPORTED", { recovery: "READ_ONLY" });
+ default: {
+ const exhaustive: never = cause;
+ return exhaustive;
+ }
+ }
+};
export function uploadCheckpointDatabaseName(
scope: IndexedDbUploadCheckpointScope,
@@ -104,13 +203,19 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
) {
throw new TypeError("Upload checkpoint blocked timeout is invalid.");
}
- const openFactory: OpenFactory | undefined = factory
- ? factory.open.bind(factory)
- : undefined;
- const deleteFactory =
- factory && typeof factory.deleteDatabase === "function"
- ? factory.deleteDatabase.bind(factory)
- : undefined;
+ // X-AUDIT-02. The timer callables are captured once, bound to their receiver,
+ // so replacing a global after composition cannot change how a blocked open or
+ // a blocked deletion already in flight is bounded. The kernel throws at
+ // construction if a positive deadline arrives without them.
+ const timers = snapshotAbortTimers({
+ setTimeout: (callback: () => void, milliseconds: number) =>
+ globalThis.setTimeout(callback, milliseconds),
+ clearTimeout: (handle: ReturnType) => {
+ globalThis.clearTimeout(handle);
+ },
+ });
+ const canDelete =
+ factory !== undefined && typeof factory.deleteDatabase === "function";
const databaseName = uploadCheckpointDatabaseName(scope);
const pendingDeletions = pendingDeletionsFor(factory);
if (pendingDeletions.has(databaseName)) {
@@ -125,118 +230,60 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
schemaVersion: 1,
...scope,
});
- let database: IDBDatabase | null = null;
- let opening: Promise> | null = null;
- let closed = false;
- async function open(
- signal?: AbortSignal,
- ): Promise> {
- if (closed || !openFactory) {
- return browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", {
- recovery: "RESUME",
- });
- }
- if (signal?.aborted) {
- return browserDataFailure("ABORTED", "UPLOAD_RECONCILE");
- }
- if (database) return browserDataSuccess(database);
- if (!opening) {
- opening = openAndBind().finally(() => {
- opening = null;
- });
- }
- const result = await opening;
- if (signal?.aborted) {
- return browserDataFailure("ABORTED", "UPLOAD_RECONCILE");
- }
- return result;
- }
-
- async function openAndBind(): Promise> {
- let request: IDBOpenDBRequest;
- try {
- request = openFactory!(databaseName, DATABASE_VERSION);
- } catch (error) {
- return mapBrowserDataException(error, "UPLOAD_RECONCILE");
- }
- const opened = await new Promise>(
- (resolve) => {
- let settled = false;
- let blockedTimer: ReturnType | undefined;
- const finish = (result: BrowserDataResult) => {
- if (settled) {
- if (result.ok) result.value.close();
- return;
- }
- settled = true;
- if (blockedTimer) clearTimeout(blockedTimer);
- resolve(result);
- };
- request.onupgradeneeded = () => {
- try {
- const db = request.result;
- if (!db.objectStoreNames.contains(CHECKPOINT_STORE)) {
- db.createObjectStore(CHECKPOINT_STORE, {
- keyPath: "uploadKey",
- });
- }
- if (!db.objectStoreNames.contains(GOVERNANCE_STORE)) {
- db.createObjectStore(GOVERNANCE_STORE, {
- keyPath: "key",
- });
- }
- } catch (error) {
- try {
- request.transaction?.abort();
- } catch {
- // The open request will surface the original closed failure.
- }
- finish(mapBrowserDataException(error, "UPLOAD_RECONCILE"));
- }
- };
- request.onblocked = () => {
- blockedTimer = setTimeout(() => {
- finish(
- browserDataFailure("BLOCKED", "UPLOAD_RECONCILE", {
- retryable: true,
- recovery: "RESUME",
- }),
- );
- }, blockedTimeoutMs);
- };
- request.onerror = () =>
- finish(
- mapBrowserDataException(
- request.error,
- "UPLOAD_RECONCILE",
- ),
- );
- request.onsuccess = () => finish(browserDataSuccess(request.result));
- },
- );
- if (!opened.ok) return opened;
- if (closed) {
- opened.value.close();
- return browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", {
- recovery: "RESUME",
- });
- }
- const bound = await bindScope(opened.value, expectedBinding);
- if (!bound.ok) {
- opened.value.close();
- return bound;
- }
- opened.value.onversionchange = () => {
- opened.value.close();
- if (database === opened.value) database = null;
- };
- opened.value.onclose = () => {
- if (database === opened.value) database = null;
- };
- database = opened.value;
- return browserDataSuccess(opened.value);
- }
+ /**
+ * The handle owns the cached connection, the single-flight open and the
+ * `versionchange`/`close` invalidation this file used to wire by hand. No
+ * `onVersionChange` callback is passed because closing the connection and
+ * dropping the cached handle — which the kernel already does — was this
+ * store's entire listener body; registering one inside `admit` instead would
+ * be overwritten when the handle adopts the connection.
+ */
+ const connection = createIndexedDbConnection({
+ translate,
+ open: (signal) =>
+ factory === undefined
+ ? Promise.resolve(
+ browserDataFailure("UNAVAILABLE", OPERATION, {
+ recovery: "RESUME",
+ }),
+ )
+ : openIndexedDbDatabase({
+ factory,
+ databaseName,
+ version: DATABASE_VERSION,
+ translate,
+ signal,
+ blockedTimeoutMs,
+ timers,
+ upgrade: ({ database }) => {
+ try {
+ if (!database.objectStoreNames.contains(CHECKPOINT_STORE)) {
+ database.createObjectStore(CHECKPOINT_STORE, {
+ keyPath: "uploadKey",
+ });
+ }
+ if (!database.objectStoreNames.contains(GOVERNANCE_STORE)) {
+ database.createObjectStore(GOVERNANCE_STORE, {
+ keyPath: "key",
+ });
+ }
+ } catch (error) {
+ return { kind: "REJECTED", detail: error };
+ }
+ return { kind: "APPLIED" };
+ },
+ // The binding runs before the caller ever sees the connection, so a
+ // partition bound to another scope can never serve a read. A
+ // rejected admission closes the connection inside the kernel.
+ admit: async (database) => {
+ const bound = await bindScope(database, expectedBinding);
+ return bound.ok
+ ? { kind: "ADMIT" }
+ : { kind: "REJECT", detail: bound.error };
+ },
+ }),
+ });
const storeValue: ResumableUploadCheckpointStore = {
async read(
@@ -246,12 +293,9 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
BrowserDataResult
> {
if (!SAFE_UPLOAD_KEY.test(uploadKey)) {
- return browserDataFailure(
- "INVALID_INPUT",
- "UPLOAD_RECONCILE",
- );
+ return browserDataFailure("INVALID_INPUT", OPERATION);
}
- const opened = await open(signal);
+ const opened = await connection.acquire(signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction<
ResumableUploadCheckpoint | null
@@ -261,7 +305,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
signal,
(nativeStore, context) => {
const request = nativeStore.get(uploadKey);
- request.onerror = () => context.nativeFailure(request.error);
+ request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
if (request.result === undefined) {
context.succeed(null);
@@ -269,11 +313,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
}
if (!isResumableUploadCheckpoint(request.result)) {
context.fail(
- browserDataFailure(
- "CORRUPT_DATA",
- "UPLOAD_RECONCILE",
- { recovery: "RECONCILE" },
- ),
+ checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" }),
);
return;
}
@@ -294,10 +334,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
try {
checkpoint = snapshotCheckpoint(inputValue.checkpoint);
} catch {
- return browserDataFailure(
- "INVALID_INPUT",
- "UPLOAD_RECONCILE",
- );
+ return browserDataFailure("INVALID_INPUT", OPERATION);
}
const expectedRevision = inputValue.expectedRevision;
if (
@@ -306,12 +343,9 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
expectedRevision < 1)) ||
checkpoint.revision !== (expectedRevision ?? 0) + 1
) {
- return browserDataFailure(
- "INVALID_INPUT",
- "UPLOAD_RECONCILE",
- );
+ return browserDataFailure("INVALID_INPUT", OPERATION);
}
- const opened = await open(inputValue.signal);
+ const opened = await connection.acquire(inputValue.signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction(
opened.value,
@@ -319,7 +353,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
inputValue.signal,
(nativeStore, context) => {
const request = nativeStore.get(checkpoint.uploadKey);
- request.onerror = () => context.nativeFailure(request.error);
+ request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
const current = request.result;
if (
@@ -329,16 +363,12 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
current.revision !== expectedRevision))
) {
context.fail(
- browserDataFailure(
- "CONFLICT",
- "UPLOAD_RECONCILE",
- { recovery: "RECONCILE" },
- ),
+ checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
);
return;
}
const put = nativeStore.put(checkpoint);
- put.onerror = () => context.nativeFailure(put.error);
+ put.onerror = () => context.fail(mappedFailure(put.error));
put.onsuccess = () => context.succeed(checkpoint);
};
},
@@ -355,12 +385,9 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
!Number.isSafeInteger(inputValue.expectedRevision) ||
inputValue.expectedRevision < 1
) {
- return browserDataFailure(
- "INVALID_INPUT",
- "UPLOAD_RECONCILE",
- );
+ return browserDataFailure("INVALID_INPUT", OPERATION);
}
- const opened = await open(inputValue.signal);
+ const opened = await connection.acquire(inputValue.signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction(
opened.value,
@@ -368,24 +395,20 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
inputValue.signal,
(nativeStore, context) => {
const request = nativeStore.get(inputValue.uploadKey);
- request.onerror = () => context.nativeFailure(request.error);
+ request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
if (
!isResumableUploadCheckpoint(request.result) ||
request.result.revision !== inputValue.expectedRevision
) {
context.fail(
- browserDataFailure(
- "CONFLICT",
- "UPLOAD_RECONCILE",
- { recovery: "RECONCILE" },
- ),
+ checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
);
return;
}
const deletion = nativeStore.delete(inputValue.uploadKey);
deletion.onerror = () =>
- context.nativeFailure(deletion.error);
+ context.fail(mappedFailure(deletion.error));
deletion.onsuccess = () => context.succeed(undefined);
};
},
@@ -393,9 +416,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
},
close() {
- closed = true;
- database?.close();
- database = null;
+ connection.close();
},
};
const store = Object.freeze(storeValue);
@@ -405,82 +426,50 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
): Promise<
BrowserDataResult
> {
+ // IDB deleteDatabase cannot be cancelled after dispatch. AbortSignal is
+ // intentionally observed only before dispatch so the adapter never
+ // reports ABORTED while deletion may still commit — which is also why the
+ // kernel's delete takes no signal.
if (signal?.aborted) {
- return browserDataFailure("ABORTED", "UPLOAD_RECONCILE");
+ return browserDataFailure("ABORTED", OPERATION);
}
- closed = true;
- database?.close();
- database = null;
- if (!deleteFactory) {
- return browserDataFailure(
- "UNSUPPORTED",
- "UPLOAD_RECONCILE",
- { recovery: "READ_ONLY" },
+ connection.close();
+ if (factory === undefined || !canDelete) {
+ return browserDataFailure("UNSUPPORTED", OPERATION, {
+ recovery: "READ_ONLY",
+ });
+ }
+ // BT-UP-03. Once dispatched the deletion may still commit after this call
+ // returns, so the pending registration is installed before the promise
+ // settles and is only released by the real native completion — which is
+ // exactly what `onSettled` reports and a blocked deadline never does.
+ pendingDeletions.add(databaseName);
+ const deleted = await deleteIndexedDbDatabase({
+ factory,
+ databaseName,
+ translate,
+ blockedTimeoutMs,
+ timers,
+ onSettled: () => {
+ pendingDeletions.delete(databaseName);
+ },
+ });
+ if (!deleted.ok) return deleted;
+ if (deleted.value.kind === "DELETED") {
+ return browserDataSuccess(
+ Object.freeze({
+ state: "DELETED" as const,
+ effect: "APPLIED" as const,
+ }),
);
}
- let request: IDBOpenDBRequest;
- try {
- request = deleteFactory(databaseName);
- } catch (error) {
- return mapBrowserDataException(error, "UPLOAD_RECONCILE");
- }
- // BT-UP-03. Once dispatched the deletion may still commit after this
- // call returns, so the pending registration is installed before the
- // promise settles and is only released by the real native completion.
- pendingDeletions.add(databaseName);
- return await new Promise>(
- (resolve) => {
- let settled = false;
- let blockedTimer: ReturnType | undefined;
- const finish = (
- result: BrowserDataResult,
- ) => {
- if (settled) return;
- settled = true;
- if (blockedTimer) clearTimeout(blockedTimer);
- resolve(result);
- };
- const releasePending = () => {
- pendingDeletions.delete(databaseName);
- };
- // IDB deleteDatabase cannot be cancelled after dispatch. AbortSignal
- // is intentionally observed only before dispatch so the adapter never
- // reports ABORTED while deletion may still commit.
- request.onblocked = () => {
- blockedTimer = setTimeout(() => {
- // Not NOT_APPLIED: the request is still live in the browser.
- finish(
- browserDataSuccess(
- Object.freeze({
- state: "PENDING" as const,
- effect: "UNKNOWN" as const,
- reason: "BLOCKED_DEADLINE" as const,
- }),
- ),
- );
- }, blockedTimeoutMs);
- };
- request.onerror = () => {
- releasePending();
- finish(
- mapBrowserDataException(
- request.error,
- "UPLOAD_RECONCILE",
- ),
- );
- };
- request.onsuccess = () => {
- releasePending();
- finish(
- browserDataSuccess(
- Object.freeze({
- state: "DELETED" as const,
- effect: "APPLIED" as const,
- }),
- ),
- );
- };
- },
+ // Not NOT_APPLIED: the request is still live in the browser.
+ return browserDataSuccess(
+ Object.freeze({
+ state: "PENDING" as const,
+ effect: "UNKNOWN" as const,
+ reason: "BLOCKED_DEADLINE" as const,
+ }),
);
},
};
@@ -488,168 +477,79 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
return Object.freeze({ store, admin });
}
-type TransactionContext = Readonly<{
- succeed(value: Value): void;
- fail(result: BrowserDataResult): void;
- nativeFailure(error: unknown): void;
-}>;
-
+/**
+ * `durability` is deliberately `undefined` rather than `"default"`: that opens
+ * the transaction with no options bag at all, which is what checkpoint writes
+ * have always done. Passing a named value would quietly move them onto a
+ * different flush policy and slow every checkpoint write down.
+ *
+ * A request error goes through `fail`, which aborts, rather than through the
+ * kernel's `requestFailed`, which only records. `compareAndSwap` issues its put
+ * inside the get's success handler, so a transaction left running after a
+ * failed request is a transaction that can still commit half of a swap.
+ */
async function runCheckpointTransaction(
database: IDBDatabase,
- mode: IDBTransactionMode,
+ mode: "readonly" | "readwrite",
signal: AbortSignal | undefined,
execute: (
store: IDBObjectStore,
- context: TransactionContext,
+ context: Readonly<{
+ succeed(value: Value): void;
+ fail(failure: BrowserDataFailure): void;
+ }>,
) => void,
): Promise> {
- if (signal?.aborted) {
- return browserDataFailure("ABORTED", "UPLOAD_RECONCILE");
- }
- return await new Promise>((resolve) => {
- let transaction: IDBTransaction;
- try {
- transaction = database.transaction(CHECKPOINT_STORE, mode);
- } catch (error) {
- resolve(mapBrowserDataException(error, "UPLOAD_RECONCILE"));
- return;
- }
- let value: Value | undefined;
- let hasValue = false;
- let failure: BrowserDataResult | null = null;
- let settled = false;
- const finish = (result: BrowserDataResult) => {
- if (settled) return;
- settled = true;
- signal?.removeEventListener("abort", abort);
- resolve(result);
- };
- const abort = () => {
- const previousFailure = failure;
- failure = browserDataFailure("ABORTED", "UPLOAD_RECONCILE");
- try {
- transaction.abort();
- } catch {
- // The transaction may already be durably committed while its
- // completion event is still queued. Wait for oncomplete/onabort so we
- // never report ABORTED for a mutation that actually committed.
- failure = previousFailure;
- }
- };
- signal?.addEventListener("abort", abort, { once: true });
- transaction.oncomplete = () => {
- if (!hasValue) {
- finish(
- browserDataFailure("CORRUPT_DATA", "UPLOAD_RECONCILE", {
- recovery: "RECONCILE",
- }),
- );
- return;
- }
- finish(browserDataSuccess(value as Value));
- };
- transaction.onerror = () => {
- // onabort is the terminal transaction signal.
- };
- transaction.onabort = () =>
- finish(
- failure ??
- mapBrowserDataException(
- transaction.error,
- "UPLOAD_RECONCILE",
- ),
- );
- const context: TransactionContext = Object.freeze({
- succeed(next) {
- if (failure) return;
- value = next;
- hasValue = true;
- },
- fail(result) {
- if (failure) return;
- failure = result;
- try {
- transaction.abort();
- } catch {
- finish(result);
- }
- },
- nativeFailure(error) {
- if (failure) return;
- failure = mapBrowserDataException(
- error,
- "UPLOAD_RECONCILE",
- );
- try {
- transaction.abort();
- } catch {
- finish(failure);
- }
- },
- });
- try {
+ return await runIndexedDbTransaction({
+ database,
+ stores: [CHECKPOINT_STORE],
+ mode,
+ translate,
+ signal,
+ durability: undefined,
+ queue: (transaction, context) => {
execute(transaction.objectStore(CHECKPOINT_STORE), context);
- } catch (error) {
- context.nativeFailure(error);
- }
+ },
});
}
+/**
+ * No `signal`: the binding is part of opening the connection, and an open the
+ * caller gave up on is already ended by the kernel's own abort path.
+ */
async function bindScope(
database: IDBDatabase,
expected: ScopeBinding,
): Promise> {
- return await new Promise>((resolve) => {
- let transaction: IDBTransaction;
- try {
- transaction = database.transaction(GOVERNANCE_STORE, "readwrite");
- } catch (error) {
- resolve(mapBrowserDataException(error, "UPLOAD_RECONCILE"));
- return;
- }
- let failure: BrowserDataResult | null = null;
- transaction.onerror = () => {
- // onabort owns terminal resolution.
- };
- transaction.onabort = () =>
- resolve(
- failure ??
- mapBrowserDataException(
- transaction.error,
- "UPLOAD_RECONCILE",
- ),
- );
- transaction.oncomplete = () => resolve(browserDataSuccess(undefined));
- const store = transaction.objectStore(GOVERNANCE_STORE);
- const request = store.get(GOVERNANCE_KEY);
- request.onerror = () => {
- failure = mapBrowserDataException(
- request.error,
- "UPLOAD_RECONCILE",
- );
- transaction.abort();
- };
- request.onsuccess = () => {
- if (request.result === undefined) {
- const add = store.add(expected);
- add.onerror = () => {
- failure = mapBrowserDataException(
- add.error,
- "UPLOAD_RECONCILE",
+ return await runIndexedDbTransaction({
+ database,
+ stores: [GOVERNANCE_STORE],
+ mode: "readwrite",
+ translate,
+ durability: undefined,
+ queue: (transaction, context) => {
+ const store = transaction.objectStore(GOVERNANCE_STORE);
+ const request = store.get(GOVERNANCE_KEY);
+ request.onerror = () => context.fail(mappedFailure(request.error));
+ request.onsuccess = () => {
+ if (request.result === undefined) {
+ const add = store.add(expected);
+ add.onerror = () => context.fail(mappedFailure(add.error));
+ // The binding is the value: without this the committed transaction
+ // would report NO_VALUE_PRODUCED, which this store reads as
+ // CORRUPT_DATA.
+ add.onsuccess = () => context.succeed(undefined);
+ return;
+ }
+ if (!sameScopeBinding(request.result, expected)) {
+ context.fail(
+ checkpointFailure("POLICY_REJECTED", { recovery: "READ_ONLY" }),
);
- transaction.abort();
- };
- return;
- }
- if (!sameScopeBinding(request.result, expected)) {
- failure = browserDataFailure(
- "POLICY_REJECTED",
- "UPLOAD_RECONCILE",
- { recovery: "READ_ONLY" },
- );
- transaction.abort();
- }
- };
+ return;
+ }
+ context.succeed(undefined);
+ };
+ },
});
}
diff --git a/src/adapters/diagnostics/index.ts b/src/adapters/diagnostics/index.ts
new file mode 100644
index 0000000..57f0af5
--- /dev/null
+++ b/src/adapters/diagnostics/index.ts
@@ -0,0 +1,7 @@
+export {
+ createDiagnosticsAdapter,
+ getLastBootEvidence,
+ MAX_DIAGNOSTIC_ENTRIES,
+ noOpDiagnostics,
+ recordBootFailure,
+} from "./bounded-diagnostics.ts";
diff --git a/src/adapters/http/feature-http-binding.ts b/src/adapters/http/feature-http-binding.ts
new file mode 100644
index 0000000..838a461
--- /dev/null
+++ b/src/adapters/http/feature-http-binding.ts
@@ -0,0 +1,400 @@
+import type {
+ InstalledHttpContract,
+} from "../../contracts/external-contract-runtime.ts";
+import type { Result } from "../../contracts/result.ts";
+import type { MappingResult } from "../../contracts/boundary-mapper.ts";
+import {
+ createFailure,
+ kindForStatus,
+ type ApiFailure,
+ type FailureEffectCertainty,
+ type FailureKind,
+} from "../../contracts/errors.ts";
+import type { MutationIntent } from "../../contracts/mutation-intent.ts";
+import type {
+ HttpExecutionOutcome,
+ SafeResponseMetadata,
+} from "./http-execution-v3.ts";
+
+type ValidatorValue =
+ Validator extends Readonly<{
+ safeParse(value: unknown): infer ParseResult;
+ }>
+ ? Extract<
+ ParseResult,
+ Readonly<{ success: true; data: unknown }>
+ > extends Readonly<{ data: infer Value }>
+ ? Value
+ : never
+ : never;
+
+export type HttpContractInput =
+ Contract extends Readonly<{
+ contract: Readonly<{ inputValidator: infer Validator }>;
+ }>
+ ? ValidatorValue
+ : never;
+
+export type HttpContractWireOutput =
+ Contract extends Readonly<{
+ contract: Readonly<{ outputValidator: infer Validator }>;
+ }>
+ ? ValidatorValue
+ : never;
+
+export type HttpContractProblem =
+ Contract extends Readonly<{
+ contract: Readonly<{ problemValidator: infer Validator }>;
+ }>
+ ? ValidatorValue
+ : never;
+
+export type HttpContractOperationId =
+ Contract extends Readonly<{
+ contract: Readonly<{ operationId: infer OperationId extends string }>;
+ }>
+ ? OperationId
+ : never;
+
+export type InstalledHttpOperationExecutor = Readonly<{
+ execute(
+ contract: InstalledHttpContract,
+ input: Input,
+ context: Readonly<{
+ routeId: string;
+ signal?: AbortSignal;
+ intent?: MutationIntent;
+ }>,
+ ): Promise>;
+}>;
+
+export type FeatureHttpProblemMapping = Readonly<{
+ kind: FailureKind;
+ code: string;
+}>;
+
+type FeatureHttpOperationSpec<
+ Contract,
+ Value,
+ RouteId extends string,
+> = Readonly<{
+ contract: Contract;
+ routeId: RouteId;
+ mapSuccess(
+ value: HttpContractWireOutput,
+ ): MappingResult;
+ mapProblem?(
+ problem: HttpContractProblem,
+ metadata: SafeResponseMetadata,
+ ): FeatureHttpProblemMapping | undefined;
+}>;
+
+export type FeatureHttpOperation<
+ Contract,
+ Value,
+ RouteId extends string = string,
+> = FeatureHttpOperationSpec &
+ Readonly<{
+ operationId: HttpContractOperationId;
+ /**
+ * Compile-time only carrier. The runtime object has no extra type payload;
+ * the contract remains the authority for input/wire/problem types.
+ */
+ __types?: Readonly<{
+ value: Value;
+ }>;
+ }>;
+
+type ContractValidity =
+ HttpContractOperationId extends never
+ ? never
+ : HttpContractInput extends never
+ ? never
+ : HttpContractWireOutput extends never
+ ? never
+ : HttpContractProblem extends never
+ ? never
+ : unknown;
+
+function defineFeatureHttpOperationForRoute<
+ const RouteId extends string,
+ const Contract,
+ Value,
+>(
+ spec: FeatureHttpOperationSpec &
+ ContractValidity,
+): FeatureHttpOperation {
+ return Object.freeze({
+ ...spec,
+ operationId: (spec.contract as Readonly<{
+ contract: Readonly<{ operationId: HttpContractOperationId }>;
+ }>).contract.operationId,
+ }) as FeatureHttpOperation;
+}
+
+export function defineFeatureHttpOperation<
+ const Contract,
+ Value,
+ const RouteId extends string,
+>(
+ spec: FeatureHttpOperationSpec &
+ ContractValidity,
+): FeatureHttpOperation {
+ return defineFeatureHttpOperationForRoute(spec);
+}
+
+/**
+ * Feature-local route typing without introducing a dependency from the HTTP
+ * capability to the presentation route registry.
+ */
+export function defineFeatureHttpOperationForRoutes<
+ const RouteId extends string,
+>() {
+ return function defineRouteBoundFeatureHttpOperation<
+ const Contract,
+ Value,
+ >(
+ spec: FeatureHttpOperationSpec &
+ ContractValidity,
+ ): FeatureHttpOperation {
+ return defineFeatureHttpOperationForRoute(spec);
+ };
+}
+
+type FeatureHttpOperationShape = Readonly<{
+ contract: object;
+ operationId: string;
+ routeId: string;
+ mapSuccess: (...args: never[]) => unknown;
+ mapProblem?: (...args: never[]) => unknown;
+}>;
+
+type OperationContract =
+ Operation extends Readonly<{ contract: infer Contract }> ? Contract : never;
+
+type OperationInput = HttpContractInput>;
+type OperationWireOutput =
+ HttpContractWireOutput>;
+type OperationProblem =
+ HttpContractProblem>;
+
+type OperationValue =
+ Operation extends FeatureHttpOperation
+ ? Value
+ : never;
+
+type InvalidOperationRegistryKeys<
+ Operations extends Readonly>,
+> = {
+ [OperationId in keyof Operations & string]:
+ OperationId extends Operations[OperationId]["operationId"]
+ ? Operations[OperationId]["operationId"] extends OperationId
+ ? never
+ : OperationId
+ : OperationId;
+}[keyof Operations & string];
+
+type ValidOperationRegistry<
+ Operations extends Readonly>,
+> = InvalidOperationRegistryKeys extends never
+ ? unknown
+ : Readonly<{
+ __operationRegistryKeyMismatch: InvalidOperationRegistryKeys;
+ }>;
+
+export type FeatureHttpBinding<
+ Operations extends Readonly>,
+> = Readonly<{
+ execute(
+ operationId: OperationId,
+ input: OperationInput,
+ context?: Readonly<{
+ signal?: AbortSignal;
+ intent?: MutationIntent;
+ }>,
+ ): Promise, ApiFailure>>;
+}>;
+
+/**
+ * Capability-specific feature binding for the installed HTTP runtime.
+ *
+ * The installed contract is the single type authority. A feature contributes
+ * only a route identity plus wire-to-domain/problem interpretation. Transport,
+ * retry, validation and effect-certainty stay in the reusable HTTP capability.
+ */
+export function createFeatureHttpBinding<
+ const Operations extends Readonly>,
+>(
+ executor: InstalledHttpOperationExecutor,
+ operations: Operations & ValidOperationRegistry,
+): FeatureHttpBinding {
+ for (const [registryId, operation] of Object.entries(operations)) {
+ if (registryId !== operation.operationId) {
+ throw new TypeError(
+ `Feature HTTP operation key mismatch: ${registryId} !== ${operation.operationId}`,
+ );
+ }
+ }
+
+ return Object.freeze({
+ async execute(
+ operationId: OperationId,
+ input: OperationInput,
+ context: Readonly<{
+ signal?: AbortSignal;
+ intent?: MutationIntent;
+ }> = {},
+ ): Promise, ApiFailure>> {
+ const operation = operations[operationId];
+ type SelectedOperation = Operations[OperationId];
+ type Input = OperationInput;
+ type WireOutput = OperationWireOutput;
+ type Problem = OperationProblem;
+ type Value = OperationValue;
+
+ const contract = operation.contract as InstalledHttpContract<
+ Input,
+ WireOutput,
+ Problem
+ >;
+ const outcome = await executor.execute(contract, input, {
+ routeId: operation.routeId,
+ ...(context.signal === undefined ? {} : { signal: context.signal }),
+ ...(context.intent === undefined ? {} : { intent: context.intent }),
+ });
+ return projectExecutionOutcome(
+ operation.operationId,
+ operation.mapSuccess as (value: WireOutput) => MappingResult,
+ operation.mapProblem as
+ | ((
+ problem: Problem,
+ metadata: SafeResponseMetadata,
+ ) => FeatureHttpProblemMapping | undefined)
+ | undefined,
+ outcome,
+ );
+ },
+ });
+}
+
+function projectExecutionOutcome(
+ operationId: string,
+ mapSuccess: (value: WireOutput) => MappingResult,
+ mapProblem:
+ | ((
+ problem: Problem,
+ metadata: SafeResponseMetadata,
+ ) => FeatureHttpProblemMapping | undefined)
+ | undefined,
+ outcome: HttpExecutionOutcome,
+): Result {
+ switch (outcome.kind) {
+ case "SUCCESS": {
+ const mapped = mapSuccess(outcome.value);
+ return mapped.ok
+ ? Object.freeze({ ok: true as const, value: mapped.value })
+ : failure(
+ "MAPPING_CONTRACT_VIOLATION",
+ operationId,
+ mapped.code,
+ { effect: outcome.effect },
+ );
+ }
+ case "PROBLEM": {
+ const mapped = mapProblem?.(outcome.problem, outcome.metadata);
+ return failure(
+ mapped?.kind ?? kindForStatus(outcome.metadata.status),
+ operationId,
+ mapped?.code ?? "CONTRACT_PROBLEM",
+ { httpStatus: outcome.metadata.status, effect: outcome.effect },
+ );
+ }
+ case "UNAUTHENTICATED":
+ return failure("AUTH_REQUIRED", operationId, "UNAUTHENTICATED", {
+ effect: outcome.effect,
+ });
+ case "FORBIDDEN":
+ return failure("FORBIDDEN", operationId, "FORBIDDEN", {
+ effect: outcome.effect,
+ });
+ case "RATE_LIMITED":
+ return failure("RATE_LIMITED", operationId, "RATE_LIMITED", {
+ ...(outcome.retryAfterMs === undefined
+ ? {}
+ : { retryAfterMs: outcome.retryAfterMs }),
+ effect: outcome.effect,
+ });
+ case "CANCELLED":
+ return failure("REQUEST_ABORTED", operationId, "REQUEST_ABORTED", {
+ effect: outcome.effect,
+ });
+ case "AUTH_INTEGRATION_FAILURE":
+ return failure(
+ "AUTH_INTEGRATION_FAILURE",
+ operationId,
+ outcome.reason,
+ { effect: outcome.effect },
+ );
+ case "TRANSPORT_FAILURE":
+ return failure(
+ outcome.failure.kind === "TIMEOUT"
+ ? "REQUEST_TIMEOUT"
+ : outcome.failure.kind === "ABORTED_BY_SCOPE"
+ ? "SCOPE_GENERATION_CHANGED"
+ : "NETWORK_UNREACHABLE",
+ operationId,
+ outcome.failure.kind,
+ { effect: outcome.effect },
+ );
+ case "CONTRACT_VIOLATION":
+ return failure(
+ failureKindForViolation(outcome.violation.kind),
+ operationId,
+ outcome.violation.kind,
+ { effect: outcome.effect },
+ );
+ }
+}
+
+function failureKindForViolation(
+ violation: Extract<
+ HttpExecutionOutcome,
+ { kind: "CONTRACT_VIOLATION" }
+ >["violation"]["kind"],
+): FailureKind {
+ switch (violation) {
+ case "CONTENT_TYPE_MISMATCH":
+ return "CONTENT_TYPE_MISMATCH";
+ case "RESPONSE_TOO_LARGE":
+ return "RESPONSE_BODY_LIMIT";
+ case "UTF8_INVALID":
+ case "JSON_INVALID":
+ return "MALFORMED_JSON";
+ case "MAPPING_CONTRACT_VIOLATION":
+ return "MAPPING_CONTRACT_VIOLATION";
+ case "SCOPE_FENCED":
+ return "SCOPE_GENERATION_CHANGED";
+ case "SUCCESS_SCHEMA_INVALID":
+ case "PROBLEM_SCHEMA_INVALID":
+ case "VALIDATOR_RUNTIME_FAILURE":
+ return "SCHEMA_MISMATCH";
+ default:
+ return "ENVELOPE_MISMATCH";
+ }
+}
+
+function failure(
+ kind: FailureKind,
+ operationId: string,
+ code: string,
+ details: Readonly<{
+ httpStatus?: number;
+ retryAfterMs?: number;
+ effect?: FailureEffectCertainty;
+ }> = {},
+): Result {
+ return Object.freeze({
+ ok: false as const,
+ error: createFailure(kind, operationId, 0, { code, ...details }),
+ });
+}
diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts
index 9cb8070..74d6d3e 100644
--- a/src/adapters/http/http-execution-v3.ts
+++ b/src/adapters/http/http-execution-v3.ts
@@ -41,6 +41,13 @@ import {
type PhysicalAttemptState,
} from "./http-effect-certainty.ts";
import { parseRetryAfter } from "./retry-policy.ts";
+import {
+ canRetryTransport,
+ isRetryableHttpStatus,
+ isRetryableSemantics,
+ jitteredDelay,
+ retryDelayFor,
+} from "./http-retry-lifecycle.ts";
/**
* §7–§8. Descriptor-driven HTTP execution.
@@ -299,14 +306,6 @@ export type ContractHttpExecutorDependencies = Readonly<{
observe?: (observation: HttpExecutionObservation) => void;
}>;
-const RETRYABLE_STATUSES: ReadonlySet = new Set([
- 408, 425, 429, 502, 503, 504,
-]);
-
-const RETRY_BASE_DELAY_MS = 250;
-const RETRY_MAX_LOCAL_DELAY_MS = 2_000;
-const RETRY_AFTER_CEILING_MS = 5_000;
-
type MutationIntentValidation =
| Readonly<{ ok: true; intent?: MutationIntent }>
| Readonly<{
@@ -1347,7 +1346,7 @@ async function admitProblem(
): Promise> {
const contract = operation.contract;
const isCommand = contract.commandEffect !== null;
- const retryable = RETRYABLE_STATUSES.has(status);
+ const retryable = isRetryableHttpStatus(status);
const bytes = await readResponseBytes(
response,
@@ -1434,56 +1433,6 @@ async function admitProblem(
});
}
-/**
- * §8.3. `SAFE` and `IDEMPOTENT` may replay the same frozen request. `KEYED`
- * must not automatically retry once an attempt was dispatched and its response
- * was lost; that path goes to inspect/reconciliation instead. `NEVER` is zero.
- */
-function canRetryTransport(
- semantics: InstalledHttpContract<
- unknown,
- unknown,
- unknown
- >["contract"]["retrySemantics"],
- attemptState: PhysicalAttemptState,
-): boolean {
- if (semantics === "NEVER") return false;
- if (semantics === "KEYED") {
- return attemptState === "PREPARING" || attemptState === "READY_TO_SEND";
- }
- return true;
-}
-
-function isRetryableSemantics(
- semantics: InstalledHttpContract<
- unknown,
- unknown,
- unknown
- >["contract"]["retrySemantics"],
-): boolean {
- return semantics === "SAFE" || semantics === "IDEMPOTENT";
-}
-
-/** §8.2. Full jitter over `min(2000, 250 * 2^index)`. */
-function jitteredDelay(retryIndex: number, random: () => number): number {
- const ceiling = Math.min(
- RETRY_MAX_LOCAL_DELAY_MS,
- RETRY_BASE_DELAY_MS * 2 ** retryIndex,
- );
- return Math.floor(random() * ceiling);
-}
-
-function retryDelayFor(
- retryAfterMs: number | null,
- retryIndex: number,
- random: () => number,
-): number | null {
- const local = jitteredDelay(retryIndex, random);
- if (retryAfterMs === null) return local;
- if (retryAfterMs > RETRY_AFTER_CEILING_MS) return null;
- return Math.max(local, retryAfterMs);
-}
-
/** §7.12. No raw header map, URL, cookie, traceparent or ETag value escapes. */
function safeMetadata(
response: Response,
diff --git a/src/adapters/http/http-retry-lifecycle.ts b/src/adapters/http/http-retry-lifecycle.ts
new file mode 100644
index 0000000..ec7139b
--- /dev/null
+++ b/src/adapters/http/http-retry-lifecycle.ts
@@ -0,0 +1,57 @@
+import type { RetrySemantics } from "../../contracts/external-contract-runtime.ts";
+import type { PhysicalAttemptState } from "./http-effect-certainty.ts";
+
+const RETRYABLE_STATUSES: ReadonlySet = new Set([
+ 408, 425, 429, 502, 503, 504,
+]);
+const RETRY_BASE_DELAY_MS = 250;
+const RETRY_MAX_LOCAL_DELAY_MS = 2_000;
+const RETRY_AFTER_CEILING_MS = 5_000;
+
+export function isRetryableHttpStatus(status: number): boolean {
+ return RETRYABLE_STATUSES.has(status);
+}
+
+/**
+ * Transport replay authority.
+ *
+ * KEYED commands may retry only before a physical dispatch. Once dispatched,
+ * an uncertain result belongs to reconciliation rather than automatic replay.
+ */
+export function canRetryTransport(
+ semantics: RetrySemantics,
+ attemptState: PhysicalAttemptState,
+): boolean {
+ if (semantics === "NEVER") return false;
+ if (semantics === "KEYED") {
+ return attemptState === "PREPARING" || attemptState === "READY_TO_SEND";
+ }
+ return true;
+}
+
+export function isRetryableSemantics(semantics: RetrySemantics): boolean {
+ return semantics === "SAFE" || semantics === "IDEMPOTENT";
+}
+
+/** Full jitter over min(2000, 250 * 2^retryIndex). */
+export function jitteredDelay(
+ retryIndex: number,
+ random: () => number,
+): number {
+ const ceiling = Math.min(
+ RETRY_MAX_LOCAL_DELAY_MS,
+ RETRY_BASE_DELAY_MS * 2 ** retryIndex,
+ );
+ return Math.floor(random() * ceiling);
+}
+
+export function retryDelayFor(
+ retryAfterMs: number | null,
+ retryIndex: number,
+ random: () => number,
+): number | null {
+ const local = jitteredDelay(retryIndex, random);
+ if (retryAfterMs === null) return local;
+ if (retryAfterMs > RETRY_AFTER_CEILING_MS) return null;
+ return Math.max(local, retryAfterMs);
+}
diff --git a/src/adapters/http/index.ts b/src/adapters/http/index.ts
new file mode 100644
index 0000000..626f326
--- /dev/null
+++ b/src/adapters/http/index.ts
@@ -0,0 +1,55 @@
+/**
+ * §7–§8. 권장 경로는 V3 계약 실행기(`createContractHttpExecutor`)다. 설치된
+ * 계약과 타입 입력을 받아 상한·전체 데드라인·재시도 권한·효과 확실성 판정을
+ * 런타임이 소유한다.
+ */
+export {
+ createContractHttpExecutor,
+ type AuthIntegrationFailureReason,
+ type AuthOperationContext,
+ type CancellationOwner,
+ type ContractHttpExecutor,
+ type ContractHttpExecutorDependencies,
+ type HttpContractViolation,
+ type HttpContractViolationKind,
+ type HttpEffectCertainty,
+ type HttpExecutionContext,
+ type HttpExecutionObservation,
+ type HttpExecutionOutcome,
+ type HttpTransportFailure,
+ type SafeResponseMetadata,
+} from "./http-execution-v3.ts";
+export {
+ createFeatureHttpBinding,
+ defineFeatureHttpOperation,
+ defineFeatureHttpOperationForRoutes,
+ type FeatureHttpBinding,
+ type FeatureHttpOperation,
+ type FeatureHttpProblemMapping,
+ type HttpContractInput,
+ type HttpContractOperationId,
+ type HttpContractProblem,
+ type HttpContractWireOutput,
+ type InstalledHttpOperationExecutor,
+} from "./feature-http-binding.ts";
+/** V3 `attachCredentials` 콜백이 반환해야 하는 결과 타입. */
+export type { CredentialPatchOutcome } from "./http-contract-bridge.ts";
+/**
+ * V2 legacy. operationId + `LegacyHttpInput`으로 호출하는 범용 클라이언트다.
+ * 새 코드는 위의 V3 실행기를 쓴다.
+ *
+ * 이 템플릿은 V2의 오퍼레이션 레지스트리와 payload 매퍼를 비워서 출하한다.
+ * 제품이 `RuntimeHttpContract`(`src/bootstrap/runtime-adapters.ts`)의 네
+ * 슬롯을 주입해야 동작한다 — 주입 없이 V3에서 되돌리면 모든 요청이 실패한다.
+ */
+export {
+ createHttpClient,
+ type HttpClient,
+ type HttpClientDependencies,
+ type HttpFailure,
+ type HttpResult,
+ type LegacyHttpInput,
+ type Scheduler,
+} from "./client.ts";
+/** V2 `HttpClient.execute`의 첫 인자 타입. */
+export type { OperationRequestInput } from "./request-builder.ts";
diff --git a/src/adapters/platform/index.ts b/src/adapters/platform/index.ts
new file mode 100644
index 0000000..015735f
--- /dev/null
+++ b/src/adapters/platform/index.ts
@@ -0,0 +1,31 @@
+/**
+ * 어댑터 커널의 공개 경계.
+ *
+ * `src/adapters/**` 안에서는 이 배럴을 쓰지 않는다. 커널 프리미티브는 파일
+ * 경로로 직접 import한다 — `scripts/check-adapter-inventory.ts:63-83`이
+ * `platform/abortable-operation.ts`로 해석되는 specifier를 네 소비자에게
+ * 요구하고, `.dependency-cruiser.json`의 kernel carve-out도 폴더 단위다.
+ * 이 배럴은 bootstrap·features·tests 같은 그룹 바깥 소비자를 위한 문이다.
+ */
+export {
+ compensateLateHandle,
+ createAbortableOperation,
+ snapshotAbortTimers,
+ type AbortableOperation,
+ type AbortableOperationInput,
+ type AbortRace,
+ type AbortTerminalReason,
+ type AbortTimerSnapshot,
+} from "./abortable-operation.ts";
+export { assertBoundedCapacity } from "./bounded-capacity.ts";
+export {
+ createBrowserLifecycleRuntime,
+ type BrowserLifecycleEvent,
+ type BrowserLifecycleRuntime,
+ type BrowserLifecycleSnapshot,
+} from "./browser-lifecycle.ts";
+export {
+ createBrowserMutationIntentFactory,
+ type BrowserMutationIntentFactoryDependencies,
+} from "./browser-mutation-intent-factory.ts";
+export { systemClock } from "./system-clock.ts";
diff --git a/src/adapters/platform/indexeddb-connection.ts b/src/adapters/platform/indexeddb-connection.ts
new file mode 100644
index 0000000..c53b3dc
--- /dev/null
+++ b/src/adapters/platform/indexeddb-connection.ts
@@ -0,0 +1,699 @@
+/**
+ * IDB-X-01. Shared IndexedDB connection mechanics.
+ *
+ * Four adapters independently reimplemented "turn an open request into a
+ * promise, hold a blocked deadline, route upgrade/error/success, close a
+ * connection that arrives after the caller gave up, and drop the cached handle
+ * when the browser takes it away". Only the mechanics are shared here. Database
+ * naming, schema, migrations, governance binding and the failure taxonomy stay
+ * with each subsystem, so this module imports none of them and is not a
+ * generic storage layer.
+ *
+ * The `IDBFactory` is a required parameter rather than a read of
+ * `globalThis.indexedDB`. `eslint.config.ts:40-63` bans that property on every
+ * browser root and `eslint.config.ts:519-530` grants the owned-adapter escape
+ * hatch to `src/adapters/platform/browser-lifecycle.ts` as a single file, not
+ * to this folder. Requiring the factory is also what all four callers already
+ * do, so nothing in eslint.config.ts has to change.
+ *
+ * What this module owns: event wiring, the settle-once latch, the blocked
+ * deadline and the cached-handle lifecycle. What it must never own: database
+ * names, schemas, migrations, governance bindings, codecs, byte budgets,
+ * retention, idempotency receipts, failure code tables, operation labels,
+ * observation event shapes, durability defaults and budget criteria. Wanting to
+ * move one of those in here is the signal to stop.
+ */
+
+import type { Result } from "../../contracts/result.ts";
+import type { AbortTimerSnapshot } from "./abortable-operation.ts";
+
+/**
+ * Everything that can end an IndexedDB operation without the caller getting a
+ * value. The kernel reports the cause; the caller's `translate` turns it into
+ * that subsystem's failure code.
+ *
+ * This union is the extension point. `abortable-operation.ts:11` baked a closed
+ * three-member `AbortTerminalReason` into its return type, so http v3 needed
+ * five owners and could not use the kernel at all. Here the owner vocabulary is
+ * never in a return type: adding a member is a compile error in every
+ * `translate` (they are total functions over the union) rather than a silent
+ * behavior change, and no consumer has to fork.
+ */
+export type IndexedDbFailureCause =
+ /** A native throw or a `request.error` / `transaction.error`. */
+ | Readonly<{ kind: "NATIVE_EXCEPTION"; error: unknown }>
+ /** `onblocked` fired and no deadline was configured. */
+ | Readonly<{ kind: "BLOCKED"; oldVersion: number; newVersion: number | null }>
+ /** `onblocked` fired and the configured deadline then elapsed. */
+ | Readonly<{ kind: "BLOCKED_DEADLINE" }>
+ /** The caller's own `AbortSignal` fired. */
+ | Readonly<{ kind: "CALLER_ABORT" }>
+ /** The connection handle was closed, which is not the caller aborting. */
+ | Readonly<{ kind: "CLOSED" }>
+ /** `upgrade` returned `REJECTED`, or a version change happened unexpectedly. */
+ | Readonly<{
+ kind: "UPGRADE_REJECTED";
+ oldVersion: number;
+ newVersion: number | null;
+ detail?: unknown;
+ }>
+ /** `admit` returned `REJECT`. `detail` is opaque to the kernel. */
+ | Readonly<{ kind: "ADMISSION_REJECTED"; detail?: unknown }>
+ /** A transaction completed without `succeed()` ever being called. */
+ | Readonly<{ kind: "NO_VALUE_PRODUCED" }>
+ /**
+ * No `IDBFactory`, or a required `IDBKeyRange` the caller did not supply.
+ * The kernel never raises this itself — the factory is a required parameter,
+ * so the condition can only exist before the kernel is called. It is part of
+ * the vocabulary so a caller that resolves those globals has one place to
+ * name the failure instead of a second taxonomy beside `translate`.
+ */
+ | Readonly<{ kind: "UNSUPPORTED" }>;
+
+/**
+ * Turns a cause into this subsystem's failure value. Built per call site so the
+ * kernel never learns an operation label or a failure code; a caller that needs
+ * `INDEXEDDB_READ` and one that needs `UPLOAD_RECONCILE` differ only here.
+ */
+export type IndexedDbTranslate = (
+ cause: IndexedDbFailureCause,
+) => Failure;
+
+export type IndexedDbUpgradeContext = Readonly<{
+ database: IDBDatabase;
+ transaction: IDBTransaction;
+ oldVersion: number;
+ /** Never `null`: a null `newVersion` is reported as `UPGRADE_REJECTED` before `upgrade` runs. */
+ newVersion: number;
+}>;
+
+/**
+ * `REJECTED` aborts the versionchange transaction, so a schema change can never
+ * commit under a rejected policy. A throw from `upgrade` is equivalent to
+ * `REJECTED` with the thrown value as `detail`.
+ */
+export type IndexedDbUpgradeOutcome =
+ | Readonly<{ kind: "APPLIED" }>
+ | Readonly<{ kind: "REJECTED"; detail?: unknown }>;
+
+/**
+ * Post-open validation. It runs after `onsuccess` and may be asynchronous, so
+ * store/index assertions and governance reads both fit. A rejected or failed
+ * admission closes the connection before the caller ever sees it.
+ */
+export type IndexedDbAdmission =
+ | Readonly<{ kind: "ADMIT" }>
+ | Readonly<{ kind: "REJECT"; detail?: unknown }>
+ | Readonly<{ kind: "FAIL"; cause: IndexedDbFailureCause }>;
+
+export type IndexedDbOpenInput = Readonly<{
+ /** Required. See the module comment for why this is not read from a global. */
+ factory: IDBFactory;
+ databaseName: string;
+ /** Omit to open whatever version exists. */
+ version?: number;
+ translate: IndexedDbTranslate;
+ /**
+ * Called inside the versionchange transaction. Omitting it means any upgrade
+ * is unexpected and the open fails with `UPGRADE_REJECTED` — which is what
+ * `indexeddb-maintenance.ts:477-484` does by hand today.
+ */
+ upgrade?: (context: IndexedDbUpgradeContext) => IndexedDbUpgradeOutcome;
+ /** Post-open validation. Omitting it admits every successful open. */
+ admit?: (
+ database: IDBDatabase,
+ ) => IndexedDbAdmission | Promise;
+ /** Aborts a pending upgrade transaction and settles with `CALLER_ABORT`. */
+ signal?: AbortSignal;
+ /**
+ * `undefined` or `0`: the `onblocked` event itself is terminal and settles
+ * with `BLOCKED` (maintenance's behavior). A positive value waits that long
+ * before settling with `BLOCKED_DEADLINE` (runtime/opfs/checkpoint).
+ */
+ blockedTimeoutMs?: number;
+ /**
+ * Required when `blockedTimeoutMs` is positive. Build it with
+ * `snapshotAbortTimers` from `./abortable-operation.ts`, which binds the
+ * callables once so replacing a method after composition cannot change how an
+ * open already in flight is bounded.
+ */
+ timers?: AbortTimerSnapshot;
+ /** Observation only; it cannot change the outcome and its throw is swallowed. */
+ onBlocked?: (
+ event: Readonly<{ oldVersion: number; newVersion: number | null }>,
+ ) => void;
+}>;
+
+export type IndexedDbConnection = Readonly<{
+ /**
+ * Single-flight: concurrent callers share one in-flight open, and a cached
+ * live connection is returned without touching the factory.
+ */
+ acquire(signal?: AbortSignal): Promise>;
+ /** The cached connection, or `null` while none is live. Live accessor, not a snapshot. */
+ current(): IDBDatabase | null;
+ /**
+ * Idempotent. Closes the cached connection and settles any in-flight open
+ * with `CLOSED` — not `CALLER_ABORT`, because the two have different codes in
+ * `indexeddb-runtime.ts` (`L743` resolves UNAVAILABLE while `L676` resolves
+ * ABORTED), and collapsing them would change one of them.
+ */
+ close(): void;
+ isClosed(): boolean;
+}>;
+
+export type IndexedDbConnectionInput = Readonly<{
+ /**
+ * How to produce a connection. Normally a closure over
+ * `openIndexedDbDatabase`. It is a seam rather than a fixed body so a caller
+ * can retry, decorate or fake the open without faking an `IDBFactory`.
+ */
+ open: (
+ signal: AbortSignal | undefined,
+ ) => Promise>;
+ translate: IndexedDbTranslate;
+ /**
+ * Fired after the handle has already dropped its cached connection, so a
+ * listener cannot keep a connection the browser is taking back. The next
+ * `acquire()` opens again.
+ */
+ onVersionChange?: (event: IDBVersionChangeEvent) => void;
+ /** `onclose`: the browser closed the connection without a version change. */
+ onForcedClose?: () => void;
+}>;
+
+export type IndexedDbDeleteOutcome =
+ | Readonly<{ kind: "DELETED" }>
+ /**
+ * The request is still live in the browser. It is not a failure and it is not
+ * "not applied": `deleteDatabase` cannot be cancelled after dispatch, so the
+ * effect is unknown. `indexeddb-checkpoint-store.ts:449-462` makes the same
+ * distinction and its comment explains why.
+ */
+ | Readonly<{ kind: "BLOCKED_DEADLINE" }>;
+
+export type IndexedDbDeleteInput = Readonly<{
+ factory: IDBFactory;
+ databaseName: string;
+ translate: IndexedDbTranslate;
+ blockedTimeoutMs?: number;
+ timers?: AbortTimerSnapshot;
+ /**
+ * Called exactly once when the native request truly settles, success or
+ * error — never on a blocked deadline. The caller uses it to release a
+ * pending-deletion registration; the kernel does not own such a registry
+ * because whether a realm may recreate the database is the caller's policy.
+ */
+ onSettled?: () => void;
+}>;
+
+function succeeded(value: Value): Result {
+ return Object.freeze({ ok: true as const, value });
+}
+
+function failed(error: Failure): Result {
+ return Object.freeze({ ok: false as const, error });
+}
+
+/**
+ * A connection that lost a race is closed, never leaked. The close itself is
+ * best effort: a handle the browser already tore down cannot be closed again,
+ * and that must not replace the outcome the caller was given.
+ */
+function closeQuietly(database: IDBDatabase): void {
+ try {
+ database.close();
+ } catch {
+ // A connection that cannot be closed is already gone.
+ }
+}
+
+/**
+ * A positive deadline with no scheduler leaves the open unbounded, which is the
+ * same class of configuration defect `assertBoundedCapacity` and
+ * `snapshotAbortTimers` reject at construction rather than at runtime. It is a
+ * throw instead of a `Failure` because no `translate` could describe it without
+ * the caller first deciding it is acceptable to run unbounded.
+ */
+function assertBlockedDeadline(
+ blockedTimeoutMs: number | undefined,
+ timers: AbortTimerSnapshot | undefined,
+): boolean {
+ const bounded =
+ blockedTimeoutMs !== undefined &&
+ Number.isFinite(blockedTimeoutMs) &&
+ blockedTimeoutMs > 0;
+ if (bounded && !timers) {
+ throw new TypeError(
+ "A positive blockedTimeoutMs requires a timer snapshot.",
+ );
+ }
+ return bounded;
+}
+
+/**
+ * Settles exactly once. A connection that arrives after the settle — a late
+ * `onsuccess`, a rejected admission, an abort — is closed rather than leaked.
+ */
+export function openIndexedDbDatabase(
+ input: IndexedDbOpenInput,
+): Promise> {
+ const { factory, databaseName, translate } = input;
+ const bounded = assertBlockedDeadline(input.blockedTimeoutMs, input.timers);
+ if (input.signal?.aborted) {
+ return Promise.resolve(failed(translate({ kind: "CALLER_ABORT" })));
+ }
+
+ return new Promise>((resolve) => {
+ let settled = false;
+ let blockedTimer: unknown;
+ let blockedTimerSet = false;
+ let upgradeRejection: IndexedDbFailureCause | null = null;
+
+ const settle = (result: Result) => {
+ if (settled) {
+ if (result.ok) closeQuietly(result.value);
+ return;
+ }
+ settled = true;
+ if (blockedTimerSet) {
+ blockedTimerSet = false;
+ try {
+ input.timers?.clearTimer(blockedTimer);
+ } catch {
+ // A throwing scheduler cannot keep the open unresolved.
+ }
+ }
+ try {
+ input.signal?.removeEventListener("abort", onCallerAbort);
+ } catch {
+ // A hostile signal facade cannot block cleanup.
+ }
+ resolve(result);
+ };
+ const settleFailure = (cause: IndexedDbFailureCause) => {
+ settle(failed(translate(cause)));
+ };
+
+ let request: IDBOpenDBRequest;
+ try {
+ request =
+ input.version === undefined
+ ? factory.open(databaseName)
+ : factory.open(databaseName, input.version);
+ } catch (error) {
+ settleFailure({ kind: "NATIVE_EXCEPTION", error });
+ return;
+ }
+
+ /**
+ * An upgrade transaction is the only cancellable part of an open request:
+ * aborting it makes the request fail through `onerror`, and there is no
+ * other way to stop a dispatched open.
+ */
+ const abortUpgrade = () => {
+ try {
+ request.transaction?.abort();
+ } catch {
+ // The request's own error path owns whatever happens next.
+ }
+ };
+
+ function onCallerAbort(): void {
+ abortUpgrade();
+ settleFailure({ kind: "CALLER_ABORT" });
+ }
+ input.signal?.addEventListener("abort", onCallerAbort, { once: true });
+
+ request.onupgradeneeded = (event) => {
+ const transaction = request.transaction;
+ const oldVersion = event.oldVersion;
+ const newVersion = event.newVersion;
+ // A null `newVersion` means a delete is in progress, and no `upgrade`
+ // policy can be applied to a schema that is going away. It is reported
+ // before the callback runs so a caller never sees a half-open upgrade.
+ if (!transaction || newVersion === null || !input.upgrade) {
+ upgradeRejection = { kind: "UPGRADE_REJECTED", oldVersion, newVersion };
+ abortUpgrade();
+ return;
+ }
+ let outcome: IndexedDbUpgradeOutcome;
+ try {
+ outcome = input.upgrade({
+ database: request.result,
+ transaction,
+ oldVersion,
+ newVersion,
+ });
+ } catch (error) {
+ outcome = { kind: "REJECTED", detail: error };
+ }
+ if (outcome.kind === "APPLIED") return;
+ upgradeRejection = {
+ kind: "UPGRADE_REJECTED",
+ oldVersion,
+ newVersion,
+ detail: outcome.detail,
+ };
+ abortUpgrade();
+ };
+
+ request.onblocked = (event) => {
+ const blocked = Object.freeze({
+ oldVersion: event.oldVersion,
+ newVersion: event.newVersion,
+ });
+ if (input.onBlocked) {
+ try {
+ input.onBlocked(blocked);
+ } catch {
+ // Observation cannot change the outcome.
+ }
+ }
+ if (!bounded) {
+ settleFailure({ kind: "BLOCKED", ...blocked });
+ return;
+ }
+ if (blockedTimerSet || settled) return;
+ try {
+ blockedTimer = input.timers?.setTimer(() => {
+ settleFailure({ kind: "BLOCKED_DEADLINE" });
+ }, input.blockedTimeoutMs as number);
+ blockedTimerSet = true;
+ } catch {
+ // A scheduler that cannot install the deadline leaves the open
+ // unbounded, so the deadline is treated as already elapsed.
+ settleFailure({ kind: "BLOCKED_DEADLINE" });
+ }
+ };
+
+ request.onerror = () => {
+ settleFailure(
+ upgradeRejection ?? { kind: "NATIVE_EXCEPTION", error: request.error },
+ );
+ };
+
+ const routeAdmission = (
+ database: IDBDatabase,
+ admission: IndexedDbAdmission,
+ ) => {
+ if (settled) {
+ closeQuietly(database);
+ return;
+ }
+ if (admission.kind === "ADMIT") {
+ settle(succeeded(database));
+ return;
+ }
+ // A connection the caller will never see is closed before the failure is
+ // reported, so a rejected admission cannot leak a live handle.
+ closeQuietly(database);
+ settleFailure(
+ admission.kind === "REJECT"
+ ? { kind: "ADMISSION_REJECTED", detail: admission.detail }
+ : admission.cause,
+ );
+ };
+
+ request.onsuccess = () => {
+ const database = request.result;
+ if (settled) {
+ closeQuietly(database);
+ return;
+ }
+ if (!input.admit) {
+ settle(succeeded(database));
+ return;
+ }
+ let admission: IndexedDbAdmission | Promise;
+ try {
+ admission = input.admit(database);
+ } catch (error) {
+ closeQuietly(database);
+ settleFailure({ kind: "NATIVE_EXCEPTION", error });
+ return;
+ }
+ void Promise.resolve(admission).then(
+ (resolved) => routeAdmission(database, resolved),
+ (error: unknown) => {
+ closeQuietly(database);
+ settleFailure({ kind: "NATIVE_EXCEPTION", error });
+ },
+ );
+ };
+ });
+}
+
+export function createIndexedDbConnection(
+ input: IndexedDbConnectionInput,
+): IndexedDbConnection {
+ let connection: IDBDatabase | null = null;
+ let attempt: Promise> | null = null;
+ let controller: AbortController | null = null;
+ let closed = false;
+ const closeWaiters = new Set<() => void>();
+
+ /**
+ * The browser is taking the connection back. The cached handle is dropped
+ * before the subsystem is told, so a notification callback cannot hand out a
+ * connection that is already gone. The next `acquire()` opens again.
+ */
+ const invalidate = (database: IDBDatabase, notify: () => void) => {
+ if (connection !== database) return;
+ connection = null;
+ try {
+ notify();
+ } catch {
+ // Losing the connection is independent from announcing it.
+ }
+ };
+
+ const adopt = (database: IDBDatabase): IDBDatabase => {
+ database.onversionchange = (event) => {
+ // The connection has to go for the other context's upgrade to proceed,
+ // so it is closed here rather than left to a listener's discretion.
+ closeQuietly(database);
+ invalidate(database, () => input.onVersionChange?.(event));
+ };
+ database.onclose = () => {
+ // `onclose` means the browser already tore the connection down, so there
+ // is nothing left to close — only a cached handle to drop.
+ invalidate(database, () => input.onForcedClose?.());
+ };
+ return database;
+ };
+
+ const start = (): Promise> => {
+ const openController = new AbortController();
+ controller = openController;
+ const started = input.open(openController.signal).then(
+ (result) => {
+ if (attempt === started) {
+ attempt = null;
+ controller = null;
+ }
+ if (!result.ok) return result;
+ if (closed) {
+ // The handle was closed while the open was in flight; the connection
+ // that arrived belongs to nobody.
+ closeQuietly(result.value);
+ return result;
+ }
+ connection = adopt(result.value);
+ return result;
+ },
+ (error: unknown) => {
+ if (attempt === started) {
+ attempt = null;
+ controller = null;
+ }
+ return failed(
+ input.translate({ kind: "NATIVE_EXCEPTION", error }),
+ );
+ },
+ );
+ attempt = started;
+ return started;
+ };
+
+ return Object.freeze({
+ acquire(signal) {
+ if (closed) {
+ return Promise.resolve(
+ failed(input.translate({ kind: "CLOSED" })),
+ );
+ }
+ if (signal?.aborted) {
+ return Promise.resolve(
+ failed(
+ input.translate({ kind: "CALLER_ABORT" }),
+ ),
+ );
+ }
+ const live = connection;
+ if (live) return Promise.resolve(succeeded(live));
+
+ const shared = attempt ?? start();
+ // The shared open is not cancelled by one caller giving up: another
+ // caller may still want the connection, and the request cannot be
+ // un-dispatched anyway.
+ return new Promise>((resolve) => {
+ let callerSettled = false;
+ const finishCaller = (result: Result) => {
+ if (callerSettled) return;
+ callerSettled = true;
+ try {
+ signal?.removeEventListener("abort", onAbort);
+ } catch {
+ // A hostile signal facade cannot block cleanup.
+ }
+ resolve(result);
+ };
+ function onAbort(): void {
+ finishCaller(
+ failed(input.translate({ kind: "CALLER_ABORT" })),
+ );
+ }
+ function onClose(): void {
+ finishCaller(failed(input.translate({ kind: "CLOSED" })));
+ }
+ signal?.addEventListener("abort", onAbort, { once: true });
+ closeWaiters.add(onClose);
+ void shared.then(
+ (result) => {
+ closeWaiters.delete(onClose);
+ // A handle closed mid-open reports CLOSED even if the open itself
+ // succeeded: the connection is already gone.
+ finishCaller(
+ closed
+ ? failed(input.translate({ kind: "CLOSED" }))
+ : result,
+ );
+ },
+ () => {
+ closeWaiters.delete(onClose);
+ finishCaller(failed(input.translate({ kind: "CLOSED" })));
+ },
+ );
+ });
+ },
+ current: () => connection,
+ close() {
+ if (closed) return;
+ closed = true;
+ const live = connection;
+ connection = null;
+ if (live) closeQuietly(live);
+ // Cancelling the in-flight open aborts a pending upgrade transaction, so
+ // a closed handle does not leave a versionchange transaction running.
+ try {
+ controller?.abort();
+ } catch {
+ // A cancelled open still reports CLOSED to its waiters below.
+ }
+ controller = null;
+ for (const waiter of [...closeWaiters]) {
+ closeWaiters.delete(waiter);
+ waiter();
+ }
+ },
+ isClosed: () => closed,
+ });
+}
+
+/**
+ * In this module because it is the same `IDBOpenDBRequest` state machine as
+ * `openIndexedDbDatabase`, not because three subsystems need it — only
+ * `indexeddb-checkpoint-store.ts` deletes a database, and nothing here asks the
+ * other three to start. Leaving it out would leave a third hand-written copy of
+ * the settle-once blocked-deadline latch eight lines away from the kernel's.
+ *
+ * There is deliberately no `signal`: the request cannot be cancelled after
+ * dispatch, so reporting ABORTED while the deletion may still commit would be a
+ * lie. Callers check their signal before calling.
+ */
+export function deleteIndexedDbDatabase(
+ input: IndexedDbDeleteInput,
+): Promise> {
+ const { factory, databaseName, translate } = input;
+ const bounded = assertBlockedDeadline(input.blockedTimeoutMs, input.timers);
+
+ return new Promise>((resolve) => {
+ let settled = false;
+ let notified = false;
+ let blockedTimer: unknown;
+ let blockedTimerSet = false;
+
+ /**
+ * Independent of `settle`: a blocked deadline resolves the caller while the
+ * request is still live, and the registration must be released when the
+ * request actually lands, not when the caller stopped waiting.
+ */
+ const notifySettled = () => {
+ if (notified) return;
+ notified = true;
+ try {
+ input.onSettled?.();
+ } catch {
+ // Releasing a registration cannot change the deletion outcome.
+ }
+ };
+
+ const settle = (result: Result) => {
+ if (settled) return;
+ settled = true;
+ if (blockedTimerSet) {
+ blockedTimerSet = false;
+ try {
+ input.timers?.clearTimer(blockedTimer);
+ } catch {
+ // A throwing scheduler cannot keep the deletion unresolved.
+ }
+ }
+ resolve(result);
+ };
+
+ let request: IDBOpenDBRequest;
+ try {
+ request = factory.deleteDatabase(databaseName);
+ } catch (error) {
+ notifySettled();
+ settle(failed(translate({ kind: "NATIVE_EXCEPTION", error })));
+ return;
+ }
+
+ request.onsuccess = () => {
+ notifySettled();
+ settle(succeeded({ kind: "DELETED" as const }));
+ };
+ request.onerror = () => {
+ notifySettled();
+ settle(
+ failed(translate({ kind: "NATIVE_EXCEPTION", error: request.error })),
+ );
+ };
+ request.onblocked = (event) => {
+ if (!bounded) {
+ settle(
+ failed(
+ translate({
+ kind: "BLOCKED",
+ oldVersion: event.oldVersion,
+ newVersion: event.newVersion,
+ }),
+ ),
+ );
+ return;
+ }
+ if (blockedTimerSet || settled) return;
+ try {
+ blockedTimer = input.timers?.setTimer(() => {
+ settle(succeeded({ kind: "BLOCKED_DEADLINE" as const }));
+ }, input.blockedTimeoutMs as number);
+ blockedTimerSet = true;
+ } catch {
+ settle(succeeded({ kind: "BLOCKED_DEADLINE" as const }));
+ }
+ };
+ });
+}
diff --git a/src/adapters/platform/indexeddb-transaction.ts b/src/adapters/platform/indexeddb-transaction.ts
new file mode 100644
index 0000000..1570e9a
--- /dev/null
+++ b/src/adapters/platform/indexeddb-transaction.ts
@@ -0,0 +1,433 @@
+/**
+ * IDB-X-02. Shared IndexedDB transaction and cursor mechanics.
+ *
+ * The same settle-once transaction state machine exists four times
+ * (`indexeddb-runtime.ts:976-1074`, `indexeddb-maintenance.ts:606-705`,
+ * `indexeddb-opfs-journal.ts:1098-1174`,
+ * `indexeddb-checkpoint-store.ts:497-596`) and the four already disagree: one
+ * of them never routes a request error at all, one aborts on a request error
+ * while two only record it, and one reports a value-less completion as
+ * CORRUPT_DATA while three report UNAVAILABLE. This module owns the mechanics
+ * and keeps every one of those choices at the call site.
+ *
+ * Like `indexeddb-connection.ts`, it owns no policy: not a store name, not a
+ * durability default, not a budget criterion, not a failure code.
+ */
+
+import type { Result } from "../../contracts/result.ts";
+import type { IndexedDbTranslate } from "./indexeddb-connection.ts";
+
+export type IndexedDbDurability = "default" | "strict" | "relaxed";
+
+/**
+ * The failure half of a transaction context. Split out so helpers that only
+ * need to report failure (`onIndexedDbRequest`, `walkIndexedDbCursor`) do not
+ * have to be generic over the transaction's success type.
+ */
+export type IndexedDbRequestSink = Readonly<{
+ /**
+ * Records the failure and aborts the transaction. The first failure wins.
+ * This is `indexeddb-runtime.ts:1047-1054`'s `fail`.
+ */
+ fail(failure: Failure): void;
+ /**
+ * Records a request-level error **without aborting**: the transaction is left
+ * to complete or abort on its own, and the recorded error becomes the reported
+ * failure if it aborts. This is `indexeddb-runtime.ts:1055-1060`'s
+ * `requestFailed`.
+ *
+ * `indexeddb-checkpoint-store.ts:577-588` deliberately aborts instead. It
+ * keeps doing so by calling `fail(translate({kind:"NATIVE_EXCEPTION", error}))`.
+ * The kernel does not pick.
+ */
+ requestFailed(error: unknown): void;
+}>;
+
+export type IndexedDbTransactionContext =
+ IndexedDbRequestSink &
+ Readonly<{
+ /** The first `succeed` wins; later ones are ignored. */
+ succeed(value: Value): void;
+ /** For callers that need `objectStore()`/`index()` directly. */
+ readonly transaction: IDBTransaction;
+ }>;
+
+export type IndexedDbTransactionInput = Readonly<{
+ database: IDBDatabase;
+ stores: readonly string[];
+ mode: "readonly" | "readwrite";
+ translate: IndexedDbTranslate;
+ /** Aborts the transaction; the outcome is `CALLER_ABORT` unless completion won. */
+ signal?: AbortSignal;
+ /**
+ * `undefined` opens with **no options bag at all**, which is
+ * `indexeddb-checkpoint-store.ts:512`'s current behavior — not the same as
+ * `"default"`, which passes `{durability:"default"}`. A named value falls back
+ * to the no-options form when the engine rejects the bag with a `TypeError`.
+ */
+ durability?: IndexedDbDurability;
+ queue: (
+ transaction: IDBTransaction,
+ context: IndexedDbTransactionContext,
+ ) => void;
+}>;
+
+/** How the visitor wants the cursor advanced. */
+export type IndexedDbCursorStep =
+ | Readonly<{ kind: "CONTINUE" }>
+ | Readonly<{ kind: "CONTINUE_FROM"; key: IDBValidKey }>
+ | Readonly<{
+ kind: "CONTINUE_PRIMARY";
+ key: IDBValidKey;
+ primaryKey: IDBValidKey;
+ }>
+ /** End the walk here; `done` gets `reason: "STOPPED"`. */
+ | Readonly<{ kind: "STOP" }>
+ /**
+ * The visitor started its own request chain and will call `resume(step)` when
+ * that chain finishes. Without this the pump is unusable by three of the four
+ * callers: every walk in `indexeddb-runtime.ts` and `indexeddb-maintenance.ts`
+ * issues nested requests before advancing (e.g. `L1487-1526`, `L2406-2471`,
+ * `L1490-1541`). A pump that only understood `CONTINUE` would be the
+ * too-narrow-to-adopt failure again.
+ */
+ | Readonly<{ kind: "SUSPEND" }>;
+
+export type IndexedDbBudgetVerdict = "CONTINUE" | "ROW_BUDGET" | "TIME_BUDGET";
+
+export type IndexedDbBudget = Readonly<{
+ /**
+ * Checked before each row, with the number of rows already handed to `visit`.
+ * The kernel counts nothing itself: runtime bounds on rows it deleted
+ * (`indexeddb-runtime.ts:2384`) while maintenance bounds on rows it scanned
+ * (`indexeddb-maintenance.ts:823`), so the counter, the clock and the deadline
+ * all belong to the caller. A clock that cannot be read is a failure rather
+ * than a `false`, which is what `monotonicClock()`
+ * (`indexeddb-runtime.ts:2260-2269`) already does.
+ */
+ admit(scannedRows: number): Result;
+}>;
+
+export type IndexedDbCursorVisit = Readonly<{
+ cursor: IDBCursorWithValue;
+ /** Rows handed to `visit` so far, this row included. */
+ scannedRows: number;
+ /** Only meaningful after the visitor returned `SUSPEND`. Idempotent. */
+ resume(step: IndexedDbCursorStep): void;
+}>;
+
+export type IndexedDbWalkSummary = Readonly<{
+ reason: "EXHAUSTED" | "STOPPED" | "ROW_BUDGET" | "TIME_BUDGET" | "ABORTED";
+ scannedRows: number;
+}>;
+
+export type IndexedDbWalkInput = Readonly<{
+ request: IDBRequest;
+ sink: IndexedDbRequestSink