Files
clean-architecture-frontend…/src/bootstrap/load-release-manifest.ts
T
DongHyeonka b26517e6f2 fix(docs): 설계 주석에 문서 이름을 붙이고 지운 뒤 끊기는 링크를 없앤다 (1101/14-01)
문제: 코드 주석 87곳(74파일, .dependency-cruiser.json 포함)이 "Spec §N"
처럼 문서 이름 없이 절 번호만 적는다(대문자 83, 소문자 "spec §" 4).
가리키는 설계서는 README가 복사 뒤 지워도 된다고 한 docs/reviews/ 안에
있었다. 지울 수 있는 기록 검사는 경로 문자열만 찾아 이 참조를 잡지
못했다. 현재 계약 문서도 지울 수 있는 파일로 링크한다:
docs/reviews/adapters/INVENTORY.md 145행이 옆의 adapter 리뷰로,
docs/operations/adapter-remediation-ledger.md가 adapter 리뷰와
docs/superpowers/plans의 계획으로.

고른 방법:
- 주석의 "Spec §"/"spec §"를 "scale-architecture.md §"로 바꾼다(앞
  커밋이 옮긴 docs/architecture/scale-architecture.md). 설명 문장과 절
  번호는 그대로다. 절 번호가 없는 "Spec §"는 없었다.
- tests/unit/deletable-history-documents.test.ts에 "spec" + 선택 공백 +
  "§"(대소문자 무시)를 거부하는 검사를 더하고, 검사 대상에
  .dependency-cruiser.json을 넣는다.
- README "Files you can delete after copying"에서 INVENTORY.md 한 파일
  대신 docs/reviews/adapters/ 폴더를 남기게 하고 이유(INVENTORY 행과
  ledger가 그 리뷰로 링크한다)를 적는다. docs/README.md §3도 같게 고친다.
  INVENTORY의 행 구조는 바꾸지 않는다.
- 남긴 adapter 리뷰와 ledger가 docs/superpowers/plans로 거는 링크 5곳은
  링크를 풀고 "작업 이력 계획, 복사본은 지울 수 있다"로 적는다.
버린 대안: INVENTORY 145칸의 링크를 그룹 이름으로 바꾸기. 템플릿에서도
상세 리뷰로 가는 길이 없어지고 수정이 145곳이다. 계획 3개도 지우기
목록에서 빼기. 지울 수 있는 폴더 안에 예외가 흩어지고, 계획이 다시
다른 이력을 가리키면 남길 목록이 계속 커진다.

위험·한계: 검사는 "HTML spec §4"처럼 다른 명세를 "spec §"로 부르는
주석도 거부한다. 그때는 "HTML Standard §4"처럼 이름을 쓴다.
src/contracts/storage-keys.ts:79의 "release-coherence plan Task 6"처럼
이름 없는 계획 참조는 이 검사가 잡지 않는다. 복사한 프로젝트가 이미
docs/reviews/adapters/를 지웠다면 링크는 계속 끊겨 있다. CHANGELOG.md의
이력 언급 4곳(:15 두 경로, :75 PRODUCT.md, :93)은 고치지 않았다.
check:remediation-ledger는 이 변경 전후 같은 4줄로 실패한다(이미 있던
실패, 게이트 밖). tests/unit/telemetry.test.ts의 describe 이름 하나가
바뀐다.

검증:
- RED: 치환 전 새 검사가 87줄을 들어 실패(1 failed | 1 passed).
- GREEN: 같은 테스트 2 passed. 변이 "// Spec §4. budgets live here"를
  src/platform/errors/app-error.ts에 넣으면 그 한 줄로 실패, 되돌림.
- 치환 diff: 바뀐 87줄 쌍이 토큰 외에 같음(스크립트 대조, 불일치 0).
- 삭제 실험(작업 트리 복사본에서 README 목록대로 지움): 끊긴 링크
  148→0, 끊긴 경로 언급 10→4(남은 4는 CHANGELOG.md), 이름 없는 설계
  참조 87→0, scale-architecture.md §N 87곳 중 없는 절 0. 같은 복사본에서
  verify-documentation-readiness PASS_SCOPED, 지울 수 있는 기록 테스트
  2 passed.
- node scripts/verify-documentation-readiness.ts: PASS_SCOPED
- node scripts/check-adapter-inventory.ts: PASS
- node scripts/run-vitest.ts run tests/unit/deletable-history-documents.test.ts
  tests/unit/documentation-readiness.test.ts tests/unit/telemetry.test.ts:
  50 passed. tests/architecture: 39 passed.
- npx tsc --noEmit (app·node·test): 모두 통과. 바꾼 TS 74파일 eslint 통과.
  .dependency-cruiser.json JSON 파싱 통과.
- 미실행: check:architecture(pnpm 필요).
2026-11-03 07:17:49 +09:00

310 lines
9.8 KiB
TypeScript

import {
verifyContractSet,
type ContractSet,
type ContractSetFailureCode,
} from "../contracts/contract-set.ts";
import type { ContractSetPackage } from "../contracts/contract-set-canonical.ts";
import {
releaseManifestV1ArtifactSchema,
releaseManifestV2ArtifactSchema,
type ReleaseManifestV1Artifact,
type ReleaseManifestV2Artifact,
} from "../contracts/release-artifacts.ts";
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../features/installed-contract-contributions.ts";
import {
BOOT_JSON_POLICIES,
readBoundedBootJson,
type BootLoadFailure,
} from "./read-bounded-boot-json.ts";
import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts";
import {
checkReleaseCoherence,
type ReleaseIdentity,
type ReleaseIdentityField,
} from "../platform/release/release-coherence.ts";
const MISMATCH_CODE: Readonly<Record<ReleaseIdentityField, ReleaseManifestErrorCode>> =
Object.freeze({
buildId: "MANIFEST_BUILD_MISMATCH",
configSchemaVersion: "MANIFEST_CONFIG_SCHEMA_MISMATCH",
releaseId: "MANIFEST_RELEASE_MISMATCH",
assetManifestHash: "MANIFEST_ASSET_MISMATCH",
});
/** §5.8. Retained for one compatibility window; carries the removed scalar. */
export const releaseManifestV1Schema = releaseManifestV1ArtifactSchema;
/** §5.2. The frontend build's compiled external contract package set. */
export const releaseManifestV2Schema = releaseManifestV2ArtifactSchema;
export type ReleaseManifestV1 = ReleaseManifestV1Artifact;
export type ReleaseManifestV2 = ReleaseManifestV2Artifact;
/**
* The composition-facing manifest. A V1 document is normalized onto it with a
* null contract set so downstream runtime never branches on schema version.
*/
export type ReleaseManifest = Readonly<{
schemaVersion: 1 | 2;
appVersion: string;
buildId: string;
commitSha: string;
configSchemaVersion: string;
assetManifestHash: string;
releaseId: string;
builtAt: string;
routeChunks: Readonly<Record<string, string>>;
contractSet: ContractSet | null;
legacyApiContractVersion?: string;
}>;
export type ReleaseManifestErrorCode =
| "MANIFEST_BUILD_MISMATCH"
| "MANIFEST_PROTOCOL_PAIR_MISMATCH"
| "MANIFEST_CONFIG_SCHEMA_MISMATCH"
| "MANIFEST_API_CONTRACT_MISMATCH"
| "MANIFEST_RELEASE_MISMATCH"
| "MANIFEST_ASSET_MISMATCH"
| "MANIFEST_FETCH_FAILED"
| "MANIFEST_TIMEOUT"
| "MANIFEST_HTTP_FAILED"
| "MANIFEST_CONTENT_TYPE_INVALID"
| "MANIFEST_BODY_TOO_LARGE"
| "MANIFEST_UTF8_INVALID"
| "MANIFEST_JSON_INVALID"
| "MANIFEST_SCHEMA_INVALID"
| ContractSetFailureCode;
export type ReleaseManifestFailureKind =
| "BUILD_MISMATCH"
| "PROTOCOL_PAIR_MISMATCH"
| "CONFIG_MISMATCH"
| "API_CONTRACT_MISMATCH"
| "RELEASE_MISMATCH"
| "ASSET_MISMATCH"
| "CONTRACT_SET_MISMATCH"
| "RELEASE_MANIFEST_FAILURE";
export type ReleaseManifestSafe = Readonly<{
kind: ReleaseManifestFailureKind;
code: ReleaseManifestErrorCode;
buildId: string;
releaseId?: string;
supportReference: string;
}>;
type ReleaseManifestSafeInput = Readonly<{
buildId: string;
releaseId?: string;
}>;
function failureKindFor(
code: ReleaseManifestErrorCode,
): ReleaseManifestFailureKind {
switch (code) {
case "MANIFEST_BUILD_MISMATCH":
return "BUILD_MISMATCH";
case "MANIFEST_PROTOCOL_PAIR_MISMATCH":
return "PROTOCOL_PAIR_MISMATCH";
case "MANIFEST_CONFIG_SCHEMA_MISMATCH":
return "CONFIG_MISMATCH";
case "MANIFEST_API_CONTRACT_MISMATCH":
return "API_CONTRACT_MISMATCH";
case "MANIFEST_RELEASE_MISMATCH":
return "RELEASE_MISMATCH";
case "MANIFEST_ASSET_MISMATCH":
return "ASSET_MISMATCH";
default:
return code.startsWith("CONTRACT_")
? "CONTRACT_SET_MISMATCH"
: "RELEASE_MANIFEST_FAILURE";
}
}
export class ReleaseManifestError extends Error {
readonly kind: ReleaseManifestFailureKind;
readonly code: ReleaseManifestErrorCode;
readonly safe: ReleaseManifestSafe;
constructor(code: ReleaseManifestErrorCode, safe: ReleaseManifestSafeInput) {
super("Release manifest could not be loaded");
this.name = "ReleaseManifestError";
this.kind = failureKindFor(code);
this.code = code;
this.safe = Object.freeze({
kind: this.kind,
code,
buildId: safe.buildId,
releaseId: safe.releaseId,
supportReference: `${safe.buildId}:${code}`,
});
}
}
const READ_FAILURE_CODE: Readonly<
Record<BootLoadFailure, ReleaseManifestErrorCode>
> = Object.freeze({
FETCH_FAILED: "MANIFEST_FETCH_FAILED",
TIMEOUT: "MANIFEST_TIMEOUT",
HTTP_STATUS_INVALID: "MANIFEST_HTTP_FAILED",
CONTENT_TYPE_INVALID: "MANIFEST_CONTENT_TYPE_INVALID",
BODY_TOO_LARGE: "MANIFEST_BODY_TOO_LARGE",
UTF8_INVALID: "MANIFEST_UTF8_INVALID",
JSON_INVALID: "MANIFEST_JSON_INVALID",
SHAPE_INVALID: "MANIFEST_SCHEMA_INVALID",
SECRET_NAME_REJECTED: "MANIFEST_SCHEMA_INVALID",
SCHEMA_INVALID: "MANIFEST_SCHEMA_INVALID",
BUILD_MISMATCH: "MANIFEST_BUILD_MISMATCH",
RELEASE_MISMATCH: "MANIFEST_RELEASE_MISMATCH",
ASSET_MISMATCH: "MANIFEST_ASSET_MISMATCH",
CONTRACT_SET_MISMATCH: "CONTRACT_SET_DIGEST_MISMATCH",
});
export type FetchReleaseManifestOptions = Readonly<{
fetcher?: typeof fetch;
buildId: string;
releaseId?: string;
signal?: AbortSignal;
}>;
/**
* Fetches and validates the active manifest without imposing the current build
* tuple. Chunk recovery uses this no-store view to detect a new release.
*/
export async function fetchReleaseManifest(
url: string,
options: FetchReleaseManifestOptions,
): Promise<ReleaseManifest> {
const outcome = await readBoundedBootJson(
url,
BOOT_JSON_POLICIES.RELEASE_MANIFEST,
{
...(options.fetcher ? { fetcher: options.fetcher } : {}),
...(options.signal ? { signal: options.signal } : {}),
},
);
if (!outcome.ok) {
throw new ReleaseManifestError(READ_FAILURE_CODE[outcome.failure], options);
}
if (outcome.value.schemaVersion === 2) {
const parsed = releaseManifestV2Schema.safeParse(outcome.value);
if (!parsed.success) {
throw new ReleaseManifestError("MANIFEST_SCHEMA_INVALID", options);
}
return Object.freeze(structuredClone(parsed.data));
}
const parsed = releaseManifestV1Schema.safeParse(outcome.value);
if (!parsed.success) {
throw new ReleaseManifestError("MANIFEST_SCHEMA_INVALID", options);
}
const { apiContractVersion, ...rest } = structuredClone(parsed.data);
return Object.freeze({
...rest,
contractSet: null,
legacyApiContractVersion: apiContractVersion,
});
}
export type LoadReleaseManifestOptions = Readonly<{
fetcher?: typeof fetch;
expectedAssetManifestHash?: string;
expectedContractSetPackages?: readonly ContractSetPackage[];
signal?: AbortSignal;
}>;
export async function loadReleaseManifest(
runtime: RuntimeConfigLoadResult,
options: LoadReleaseManifestOptions = {},
): Promise<ReleaseManifest> {
const identity: ReleaseManifestSafeInput = {
buildId: runtime.build.buildId,
...(runtime.config.RELEASE_ID
? { releaseId: runtime.config.RELEASE_ID }
: {}),
};
const manifest = await fetchReleaseManifest(
runtime.config.RELEASE_MANIFEST_URL,
{
...(options.fetcher ? { fetcher: options.fetcher } : {}),
...(options.signal ? { signal: options.signal } : {}),
buildId: runtime.build.buildId,
...(runtime.config.RELEASE_ID
? { releaseId: runtime.config.RELEASE_ID }
: {}),
},
);
const expectedManifestVersion = runtime.configSchema === "V1" ? 1 : 2;
if (manifest.schemaVersion !== expectedManifestVersion) {
throw new ReleaseManifestError(
"MANIFEST_PROTOCOL_PAIR_MISMATCH",
identity,
);
}
// §6.7 steps 5-6, in order: build, config, release, assets, then contractSet.
// scale-architecture.md §45. Every identity comparison is delegated to the one pure,
// fail-closed release-coherence validator; only the V1 scalar API contract
// pair (which has no place in the release identity) stays local.
const identities: Readonly<Record<"html" | "config" | "manifest", ReleaseIdentity>> = {
html: {
buildId: runtime.build.buildId,
...(options.expectedAssetManifestHash
? { assetManifestHash: options.expectedAssetManifestHash }
: {}),
},
config: {
...(runtime.config.BUILD_ID ? { buildId: runtime.config.BUILD_ID } : {}),
...(runtime.config.RELEASE_ID ? { releaseId: runtime.config.RELEASE_ID } : {}),
configSchemaVersion: runtime.config.CONFIG_SCHEMA_VERSION,
},
manifest: {
buildId: manifest.buildId,
releaseId: manifest.releaseId,
configSchemaVersion: manifest.configSchemaVersion,
assetManifestHash: manifest.assetManifestHash,
},
};
const mismatchFor = (
fields: readonly ReleaseIdentityField[],
): ReleaseManifestErrorCode | null => {
const result = checkReleaseCoherence(identities, fields);
return result.coherent ? null : MISMATCH_CODE[result.field];
};
let mismatchCode: ReleaseManifestErrorCode | null = mismatchFor([
"buildId",
"configSchemaVersion",
]);
if (
!mismatchCode &&
runtime.configSchema === "V1" &&
(manifest.legacyApiContractVersion === undefined ||
runtime.config.LEGACY_API_CONTRACT_VERSION === undefined ||
manifest.legacyApiContractVersion !==
runtime.config.LEGACY_API_CONTRACT_VERSION)
) {
mismatchCode = "MANIFEST_API_CONTRACT_MISMATCH";
}
mismatchCode ??= mismatchFor(["releaseId", "assetManifestHash"]);
if (mismatchCode) {
throw new ReleaseManifestError(mismatchCode, identity);
}
if (manifest.schemaVersion === 2 && manifest.contractSet) {
const verification = await verifyContractSet({
expected:
options.expectedContractSetPackages ??
(EXPECTED_CONTRACT_SET_PACKAGES as readonly ContractSetPackage[]),
manifest: manifest.contractSet,
});
if (!verification.ok) {
throw new ReleaseManifestError(verification.code, identity);
}
}
return manifest;
}