chore(review): 1105 가드레일·CI 조치 브랜치를 합친다
This commit is contained in:
@@ -300,11 +300,11 @@
|
||||
},
|
||||
{
|
||||
"name": "feature-and-app-roots-do-not-reach-adapters",
|
||||
"comment": "12-03. The graph checks one edge at a time, so a module that presentation may import must not re-export a concrete adapter: presentation would then reach it with every direct rule passing. That covers the files outside a feature's layer folders (src/features/*.ts, src/features/<feature>/*.ts), src/contexts and src/apps. Inside a feature, only its adapters/ folder reaches src/adapters; the product composes adapters in bootstrap. Exception: src/features/feature-adapter-contribution.ts imports the InstalledHttpOperationExecutor type that bootstrap hands to feature adapters (type only). Owner: frontend-platform. Revisit when that type moves to an application port.",
|
||||
"comment": "12-03. The graph checks one edge at a time, so a module that presentation may import must not re-export a concrete adapter: presentation would then reach it with every direct rule passing. That covers every file under src/features outside a feature's adapters/ folder (the root files, and any folder that is not a layer, such as support/: 0929/12-03), src/contexts and src/apps. Inside a feature, only its adapters/ folder reaches src/adapters; the product composes adapters in bootstrap. Exception: src/features/feature-adapter-contribution.ts imports the InstalledHttpOperationExecutor type that bootstrap hands to feature adapters (type only). Owner: frontend-platform. Revisit when that type moves to an application port.",
|
||||
"severity": "error",
|
||||
"from": {
|
||||
"path": "^src/(features/[^/]+\\.tsx?$|features/[^/]+/[^/]+\\.tsx?$|contexts/|apps/)",
|
||||
"pathNot": "^src/features/feature-adapter-contribution\\.ts$"
|
||||
"path": "^src/(features/|contexts/|apps/)",
|
||||
"pathNot": "^src/features/([^/]+/adapters/|feature-adapter-contribution\\.ts$)"
|
||||
},
|
||||
"to": {
|
||||
"path": "^src/adapters/"
|
||||
|
||||
@@ -333,7 +333,7 @@ bubblewrap may create unprivileged user and network namespaces, which Ubuntu
|
||||
23.10 and later refuse by default — its first step says so, and
|
||||
`docs/operations/ci-quality-gates.md` lists the fixes). Product checks listed in
|
||||
`config/ci/product-gates.json` (`PRODUCT-GATE-NNN`) run in the workflow's own
|
||||
`product_merge_gate` job:
|
||||
`product_merge_gate` job, which the release stage waits for:
|
||||
|
||||
```bash
|
||||
for gate in 001 002 003 004 005 006 007 008 009 010 011 012 013 020; do
|
||||
|
||||
+5
-2
@@ -43,8 +43,11 @@ README와 입구 문서는 영어, recipe·ledger·스타일 문서는 한국어
|
||||
`verify:documentation`은 이 파일과 이 절에서 링크한 문서(폴더 링크는 그 안의 `.md` 전부)에
|
||||
적힌 repo 경로·링크·package script·FE-GATE ID가 실제로 있는지 검사한다. 명령(인라인 코드와
|
||||
셸 코드 블록) 안의 경로 인자도 본다. 짝 백엔드 템플릿(`clean-architecture-backend-template`)의
|
||||
경로와 링크는 그 checkout이 이 checkout 옆에 있을 때만 확인하고, 없으면 실패 대신 확인하지
|
||||
못한 것으로 출력과 `artifacts/quality/documentation-review.json`에 남긴다. `CHANGELOG.md`는
|
||||
경로와 링크는 `config/contracts/backend-contract-pin.json`이 고정한 커밋의 트리에서 찾는다.
|
||||
이 checkout 옆에 있는 짝 checkout의 git 기록을 읽고, 그 작업 트리와 HEAD는 보지 않는다. 짝
|
||||
checkout이 없거나 그 커밋이 없으면 실패 대신 확인하지 못한 것으로 출력과
|
||||
`artifacts/quality/documentation-review.json`에 남긴다. repo 밖으로 나가는 링크가 짝 저장소를
|
||||
가리키지 않으면(저장소 이름 오타 포함) 실패한다. `CHANGELOG.md`는
|
||||
지난 상태를 적는 문서라 빼고, git이 무시하는 생성 산출물과 복사한 프로젝트가 지운 작업 이력은
|
||||
없어도 된다. 설명·수치가 코드와 맞는지는 검사하지 않는다. 규칙과 예외의 정본은
|
||||
`scripts/verify-documentation-readiness.ts`다.
|
||||
|
||||
@@ -63,7 +63,7 @@ Each row is one `forbidden` rule in `.dependency-cruiser.json`, by its `name`.
|
||||
| `adapter-groups-are-reached-through-their-barrel` | code outside `src/adapters` | adapter files other than a group's `index.ts` and the `storage/indexeddb` and `storage/opfs` sub-barrels |
|
||||
| `features-do-not-import-other-features` | each feature | another feature |
|
||||
| `contexts-do-not-import-other-contexts` | each context | another context |
|
||||
| `feature-and-app-roots-do-not-reach-adapters` | `src/features/*.ts`, `src/features/<id>/*.ts`, `src/contexts`, `src/apps`, except the type-only `src/features/feature-adapter-contribution.ts` | `src/adapters` |
|
||||
| `feature-and-app-roots-do-not-reach-adapters` | every file in `src/features` outside a feature's `adapters/` folder (the root files and any folder that is not a layer, such as `support/`), `src/contexts`, `src/apps`, except the type-only `src/features/feature-adapter-contribution.ts` | `src/adapters` |
|
||||
| `presentation-does-not-import-apps-or-contexts` | generic and feature presentation, except `src/presentation/routes/app-router.tsx`, which mounts the app's route tree | `src/apps`, `src/contexts` |
|
||||
| `observability-vendors-live-behind-adapters` | code outside `src/adapters` | vendor telemetry SDKs |
|
||||
| `platform-kernel-is-product-neutral` | `src/platform`, except `routing/`, which reads app descriptors by type | features, contexts, apps, adapters, bootstrap, presentation, application |
|
||||
|
||||
@@ -380,7 +380,7 @@ projectRequest: (input) => Object.freeze({
|
||||
|
||||
- presentation이 기능 `adapters/`를 import하면 `feature-presentation-does-not-know-outbound-adapters`로 막는다.
|
||||
- adapters가 presentation을 import하면 `feature-adapters-do-not-know-presentation`으로 막는다.
|
||||
- 기능 루트 파일(`feature-module.ts` 등)이 `src/adapters`에 닿으면 `feature-and-app-roots-do-not-reach-adapters`로 막는다.
|
||||
- 기능 루트 파일(`feature-module.ts` 등)이나 계층이 아닌 폴더(`support/` 등)의 파일이 `src/adapters`에 닿으면 `feature-and-app-roots-do-not-reach-adapters`로 막는다. 기능 안에서 `src/adapters`에 닿을 수 있는 곳은 `adapters/` 폴더뿐이다.
|
||||
- operation ID·route ID·입력 타입을 틀리면 `check:types`가 막는다. 음성 fixture: `check:types:fixture:http-operation-id`, `check:types:fixture:http-route-id`, `check:types:fixture:http-operation-input`.
|
||||
- 호스트가 주지 않는 capability를 `needs`에 적으면 조립이 실패한다.
|
||||
- 메시지: `feature <id> needs <capability>, which the host did not provide`
|
||||
|
||||
@@ -132,7 +132,9 @@ DOCUMENTATION_READY (off-chain)
|
||||
- 입구 문서가 실제 `src` 최상위 폴더와 `.dependency-cruiser.json` 규칙 이름을
|
||||
적는지
|
||||
- `docs/README.md` 1절의 현재 계약 문서에 적힌 repo 경로·링크·package script·
|
||||
FE-GATE ID가 실제로 있는지
|
||||
FE-GATE ID가 실제로 있는지. 짝 백엔드 경로는 옆 checkout의 작업 트리가 아니라
|
||||
`config/contracts/backend-contract-pin.json`이 고정한 커밋에서 찾고, 그 커밋을
|
||||
읽을 수 없으면 확인하지 못한 것으로 남긴다
|
||||
- 2026-07-18 diagram 리뷰 기록의 두 사본(`docs/architecture/review-ledger.json`,
|
||||
`review-evidence.md`)이 같은 해시·점수를 담는지. 원본 diagram은 repo 밖에
|
||||
있으므로 이 항목은 구조가 바뀌어도 통과한다
|
||||
@@ -419,9 +421,14 @@ the paired backend: `{ "id": "PRODUCT-GATE-001", "name": "backend-contract",
|
||||
`FE-GATE-NNN` ids, their commands, artifacts and readiness formula stay the
|
||||
template's. Each runs as `corepack pnpm <script>` in the `product_merge_gate`
|
||||
job, on the same condition as `merge_gate`, without browsers and without the
|
||||
gate log and evidence artifacts of `ci:gate`. Make that job a required check
|
||||
of the branch where it has to block a merge. `check:ci` refuses a script that
|
||||
`package.json` does not define and counts these scripts as gated.
|
||||
gate log and evidence artifacts of `ci:gate`. `release_gate` waits for that job
|
||||
as it waits for `merge_gate`, so a failing product gate also stops the release
|
||||
build, promotion and deployment of the same run (1105/13-02); with no product
|
||||
gates the workflow is the template's own. A required check of the branch is
|
||||
what blocks a pull request merge, so make the job one where it has to. `check:ci`
|
||||
refuses a script that `package.json` does not define, and a workflow whose
|
||||
`release_gate` does not wait for the product job, and counts these scripts as
|
||||
gated.
|
||||
|
||||
The slot as stored in `config/ci/gates.json` still follows the same contract
|
||||
rules. The contract allows the steps `checkout`, `setup-node`,
|
||||
|
||||
@@ -768,8 +768,10 @@ tests/factories/
|
||||
| `server-terminal-503` | 503. 조회는 retry 2회 뒤 소진, 명령은 retry 없이 결과 불명(`MAYBE_APPLIED`) |
|
||||
|
||||
이 표는 `tests/mocks/scenarios/catalog.ts`의 `HTTP_SCENARIO_IDS`와 같은 순서다.
|
||||
401 뒤 인증 복구 흐름은 catalog가 아니라 `tests/integration/auth-recovery.test.ts`가
|
||||
다룬다.
|
||||
401 뒤 세션을 복구하고 다시 보내는 흐름은 없다. V3 실행기는 401을 `UNAUTHENTICATED`로
|
||||
끝내고 재전송하지 않는다(`src/adapters/http/http-execution-v3.ts`). 그 판정은
|
||||
`tests/unit/http-execution-v3.test.ts`가 검사한다. 복구 흐름을 검사하던 V2의
|
||||
auth-recovery 통합 테스트는 V2 클라이언트와 함께 지웠다.
|
||||
|
||||
### 11.3 Catalog 규칙
|
||||
|
||||
|
||||
@@ -820,6 +820,24 @@ async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
|
||||
target === "src/adapters/telemetry/index.ts",
|
||||
),
|
||||
},
|
||||
// 0929/12-03. A feature folder that is not a layer (support/) had no rule,
|
||||
// so presentation reached the http adapter barrel through it with the
|
||||
// graph and ESLint both passing.
|
||||
{
|
||||
name: "feature non-layer folder re-export of a concrete adapter is rejected",
|
||||
passed: blockingViolations(crossBoundaryGraph).some(
|
||||
({ rule, source, target }) =>
|
||||
rule === "feature-and-app-roots-do-not-reach-adapters" &&
|
||||
source === "src/features/alpha/support/telemetry.ts" &&
|
||||
target === "src/adapters/telemetry/index.ts",
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "feature adapters folder import of a concrete adapter is accepted",
|
||||
passed: !blockingViolations(crossBoundaryGraph).some(
|
||||
({ source }) => source === "src/features/alpha/adapters/telemetry-sink.ts",
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "context re-export of a concrete adapter is rejected",
|
||||
passed: blockingViolations(crossBoundaryGraph).some(
|
||||
|
||||
@@ -1463,8 +1463,9 @@ export const documentationReviewArtifactSchema = z
|
||||
.object({
|
||||
path: nonEmptyString,
|
||||
missingPaths: z.array(nonEmptyString),
|
||||
// 1103/12-05. References into a paired repository that is not
|
||||
// checked out beside this one. Reported, not failed.
|
||||
// 1103/12-05, 1105/12-02. References into a paired repository
|
||||
// whose pinned commit cannot be read beside this checkout (no
|
||||
// checkout, or one without that commit). Reported, not failed.
|
||||
unverifiedLinks: z.array(nonEmptyString),
|
||||
missingScripts: z.array(nonEmptyString),
|
||||
unknownGateIds: z.array(nonEmptyString),
|
||||
|
||||
@@ -65,6 +65,18 @@ const defaultFileSystem: CiWorkflowFileSystem = Object.freeze({
|
||||
rm: async (target) => rm(target, { force: true }),
|
||||
});
|
||||
|
||||
const PRODUCT_GATE_JOB = "product_merge_gate";
|
||||
/**
|
||||
* 1105/13-02. The job that waits for the product gates. A failing product
|
||||
* gate stopped nothing but a PR merge: the same run went on to release, build,
|
||||
* promote and deploy, and the fixed job graph left a product no way to link
|
||||
* them. release_gate is the first release-stage job, and every later one
|
||||
* depends on it as it depends on merge_gate. The link is rendered from the
|
||||
* overlay, so the template contract's job graph (and its check) stays the
|
||||
* template's, and without product gates the workflow bytes do not change.
|
||||
*/
|
||||
const PRODUCT_GATES_HOLD = "release_gate";
|
||||
|
||||
export function renderCiWorkflow(
|
||||
contract: CiGateContract,
|
||||
productGates: readonly ProductGate[] = [],
|
||||
@@ -76,6 +88,8 @@ export function renderCiWorkflow(
|
||||
if (step.kind === "upload") transfers.set(step.transferId, { name: step.name });
|
||||
}
|
||||
}
|
||||
// 1105/13-02. With product gates, the release stage waits for them too.
|
||||
const productNeeds = productGates.length > 0 ? [PRODUCT_GATE_JOB] : [];
|
||||
const lines = [
|
||||
"# GENERATED FILE — edit config/ci/gates.json and run `corepack pnpm generate:ci-workflow`.",
|
||||
"name: frontend-quality-gates",
|
||||
@@ -113,7 +127,7 @@ export function renderCiWorkflow(
|
||||
];
|
||||
for (const [jobIndex, job] of contract.jobs.entries()) {
|
||||
if (jobIndex > 0) lines.push("");
|
||||
lines.push(...renderJob(job, index, transfers));
|
||||
lines.push(...renderJob(job, index, transfers, job.id === PRODUCT_GATES_HOLD ? productNeeds : []));
|
||||
}
|
||||
if (productGates.length > 0) lines.push("", ...renderProductGateJob(productGates));
|
||||
return `${lines.join("\n").replace(/\n+$/u, "")}\n`;
|
||||
@@ -123,12 +137,13 @@ export function renderCiWorkflow(
|
||||
* 1103/12-07. The product's merge gates (config/ci/product-gates.json) run in
|
||||
* a job after every template job, on the same merge condition. A product gate
|
||||
* is one package script; it has no log artifact or evidence of the template
|
||||
* gate contract and is not part of its readiness formula, so the product makes
|
||||
* this job a required check where it wants it to block a merge.
|
||||
* gate contract and is not part of its readiness formula. The release stage
|
||||
* waits for this job (1105/13-02); the product makes it a required check where
|
||||
* it wants it to block a merge.
|
||||
*/
|
||||
function renderProductGateJob(productGates: readonly ProductGate[]): string[] {
|
||||
return [
|
||||
" product_merge_gate:",
|
||||
` ${PRODUCT_GATE_JOB}:`,
|
||||
` name: ${yamlScalar("${{ matrix.gate }} / ${{ matrix.name }}")}`,
|
||||
` if: ${renderCondition("merge")}`,
|
||||
" runs-on: ubuntu-latest",
|
||||
@@ -161,10 +176,12 @@ function renderJob(
|
||||
job: CiWorkflowJob,
|
||||
index: ReturnType<typeof indexCiGateContract>,
|
||||
transfers: ReadonlyMap<string, Readonly<{ name: string }>>,
|
||||
productNeeds: readonly string[],
|
||||
): string[] {
|
||||
const lines = [` ${yamlKey(job.id)}:`, ` name: ${yamlScalar(job.displayName)}`];
|
||||
if (job.needs.length === 1) lines.push(` needs: ${yamlKey(job.needs[0]!)}`);
|
||||
if (job.needs.length > 1) lines.push(` needs: [${job.needs.map(yamlKey).join(", ")}]`);
|
||||
const needs = [...job.needs, ...productNeeds];
|
||||
if (needs.length === 1) lines.push(` needs: ${yamlKey(needs[0]!)}`);
|
||||
if (needs.length > 1) lines.push(` needs: [${needs.map(yamlKey).join(", ")}]`);
|
||||
const condition = renderCondition(job.condition);
|
||||
if (condition) lines.push(` if: ${condition}`);
|
||||
lines.push(
|
||||
@@ -480,7 +497,7 @@ export function workflowGateExecutionFailures(
|
||||
): string[] {
|
||||
const executed = new Set<string>();
|
||||
const jobs = workflow.split(/^(?= {2}[a-z_]+:$)/mu);
|
||||
const productJob = jobs.find((job) => job.startsWith(" product_merge_gate:\n")) ?? "";
|
||||
const productJob = jobs.find((job) => job.startsWith(` ${PRODUCT_GATE_JOB}:\n`)) ?? "";
|
||||
const productRuns = /^ {8}run: corepack pnpm \$\{\{ matrix\.script \}\}$/mu.test(productJob);
|
||||
const productFailures = productGates
|
||||
.filter(
|
||||
@@ -490,7 +507,17 @@ export function workflowGateExecutionFailures(
|
||||
` - { gate: ${gate.id}, name: ${gate.name}, script: ${yamlScalar(gate.script)} }\n`,
|
||||
),
|
||||
)
|
||||
.map(({ id }) => `product gate is not executed by the product_merge_gate job: ${id}`);
|
||||
.map(({ id }) => `product gate is not executed by the ${PRODUCT_GATE_JOB} job: ${id}`);
|
||||
// 1105/13-02. Run is not enough: a failing product gate must also hold the
|
||||
// release stage.
|
||||
const holdingJob = jobs.find((job) => job.startsWith(` ${PRODUCT_GATES_HOLD}:\n`)) ?? "";
|
||||
const heldBy = /^ {4}needs: (?:\[([^\]\n]*)\]|(\S+))$/mu.exec(holdingJob);
|
||||
if (
|
||||
productGates.length > 0 &&
|
||||
!(heldBy?.[1] ?? heldBy?.[2] ?? "").split(", ").includes(PRODUCT_GATE_JOB)
|
||||
) {
|
||||
productFailures.push(`product gates do not hold the release stage: ${PRODUCT_GATES_HOLD} does not need ${PRODUCT_GATE_JOB}`);
|
||||
}
|
||||
for (const job of jobs) {
|
||||
for (const match of job.matchAll(/^ +run: corepack pnpm ci:gate -- (FE-GATE-\d{3})$/gmu)) {
|
||||
executed.add(match[1]!);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, readdir, readFile } from "node:fs/promises";
|
||||
import { dirname, join, matchesGlob, normalize, resolve } from "node:path/posix";
|
||||
@@ -207,12 +208,58 @@ const deletedHistory = [
|
||||
.flatMap(([, cell = ""]) => [...cell.matchAll(/`([^`]+)`/gu)].map(([, entry = ""]) => entry.replace(/\/$/u, "")))
|
||||
.filter((entry) => !exists(entry));
|
||||
|
||||
// 1103/12-05. The paired templates a document may name (`<name>/docs/…`) or
|
||||
// link (`../../../<name>/…`). They are looked up beside the checkout the
|
||||
// documents are read from; where none is checked out (CI, a nested worktree)
|
||||
// the reference is reported as not verified instead of passing silently.
|
||||
const SIBLING_REPOSITORIES = new Set(["clean-architecture-backend-template"]);
|
||||
// 1103/12-05, 1105/12-02. The paired templates a document may name
|
||||
// (`<name>/docs/…`) or link (`../../../<name>/…`) are the ones
|
||||
// config/contracts/backend-contract-pin.json pins. It is read with the
|
||||
// documents, since it says which commit they describe. A reference is looked
|
||||
// up in the tree of the pinned commit, read from the object store of the
|
||||
// checkout beside the documents, never from that checkout's working tree or
|
||||
// HEAD: those differ per machine, and the same commit failed on one whose
|
||||
// sibling was months behind with uncommitted changes and passed elsewhere.
|
||||
// Where the checkout or the pinned commit is missing (CI, a nested worktree, a
|
||||
// stale clone) the reference is reported as not verified. A link that leaves
|
||||
// the repository for anything else is broken (a misspelled repository too).
|
||||
const PAIRED_PIN = "config/contracts/backend-contract-pin.json";
|
||||
const pairedPins = new Map<string, string>();
|
||||
const pairedPin = await readFile(PAIRED_PIN, "utf8").catch(() => null);
|
||||
if (pairedPin !== null) {
|
||||
const { backend } = JSON.parse(pairedPin) as { backend: { repository: string; commit: string } };
|
||||
pairedPins.set(backend.repository, backend.commit);
|
||||
}
|
||||
const siblingsRoot = resolve(process.cwd(), "..");
|
||||
type PairedTree = Readonly<{ paths: ReadonlySet<string> }> | Readonly<{ unverified: string }>;
|
||||
const pairedTrees = new Map<string, PairedTree>();
|
||||
function readPairedTree(repository: string, commit: string): PairedTree {
|
||||
const checkout = resolve(siblingsRoot, repository);
|
||||
if (!existsSync(join(checkout, ".git"))) return { unverified: `no checkout at ${checkout}` };
|
||||
// The checkout's own repository only: a GIT_DIR set by a hook would point
|
||||
// git at another one.
|
||||
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_")));
|
||||
const git = (...args: string[]) =>
|
||||
spawnSync("git", ["-C", checkout, ...args], { encoding: "utf8", env, maxBuffer: 64 * 1024 * 1024 });
|
||||
if (git("cat-file", "-e", `${commit}^{commit}`).status !== 0) {
|
||||
const head = git("rev-parse", "--short=12", "HEAD");
|
||||
return {
|
||||
unverified: `${checkout} at HEAD ${head.status === 0 ? head.stdout.trim() : "(unreadable)"} does not have the pinned commit; fetch it to check these`,
|
||||
};
|
||||
}
|
||||
const listing = git("ls-tree", "-r", "-t", "-z", "--name-only", commit);
|
||||
if (listing.status !== 0) return { unverified: `git ls-tree failed in ${checkout}: ${listing.stderr.trim()}` };
|
||||
return { paths: new Set(listing.stdout.split("\0").filter((entry) => entry !== "")) };
|
||||
}
|
||||
/** Whether `reference` (`../<name>/<path>`) is in the pinned tree, or null when it cannot be checked here. */
|
||||
function pairedReferenceExists(reference: string): boolean | null {
|
||||
const [, repository = "", ...inside] = reference.split("/");
|
||||
const commit = pairedPins.get(repository);
|
||||
if (commit === undefined) return false;
|
||||
let tree = pairedTrees.get(repository);
|
||||
if (tree === undefined) {
|
||||
tree = readPairedTree(repository, commit);
|
||||
pairedTrees.set(repository, tree);
|
||||
}
|
||||
if ("unverified" in tree) return null;
|
||||
return inside.length === 0 || tree.paths.has(inside.join("/"));
|
||||
}
|
||||
|
||||
// A backtick span is a path when it starts at a top-level entry, at an entry
|
||||
// beside the document or at a paired repository; line numbers and anchors are
|
||||
@@ -223,13 +270,13 @@ function namedPath(token: string, document: string): string | null {
|
||||
if (!candidate.includes("/") || candidate.startsWith("/") || /[\s*<>{}$()|]|\.\.\./u.test(candidate)) return null;
|
||||
const first = candidate.split("/")[0] ?? "";
|
||||
if (topLevelEntries.has(first)) return candidate;
|
||||
if (SIBLING_REPOSITORIES.has(first)) return `../${candidate}`;
|
||||
if (pairedPins.has(first)) return `../${candidate}`;
|
||||
return first !== "." && first !== ".." && exists(join(dirname(document), first))
|
||||
? join(dirname(document), candidate)
|
||||
: null;
|
||||
}
|
||||
// A link that leaves the repository is kept (`../…`); the caller looks it up
|
||||
// beside the checkout.
|
||||
// in the paired repositories.
|
||||
function linkedPath(target: string, document: string): string | null {
|
||||
if (/^(?:[a-z][a-z+.-]*:|#)/iu.test(target)) return null;
|
||||
return normalize(join(dirname(document), target.replace(/#.*$/u, "")));
|
||||
@@ -304,16 +351,10 @@ for (const document of contractDocuments) {
|
||||
if (file === null) continue;
|
||||
const trimmed = file.replace(/\/$/u, "");
|
||||
if (trimmed.startsWith("../")) {
|
||||
// Outside this repository: the first folder past the `..` steps is the
|
||||
// paired checkout. Without it the reference cannot be checked here.
|
||||
const segments = trimmed.split("/");
|
||||
const checkout = segments.slice(0, segments.findIndex((segment) => segment !== "..") + 1).join("/");
|
||||
const relativeToSiblings = trimmed.replace(/^\.\.\//u, "");
|
||||
if (!existsSync(resolve(siblingsRoot, checkout.replace(/^\.\.\//u, "")))) {
|
||||
unverifiedLinks.add(trimmed);
|
||||
} else if (!existsSync(resolve(siblingsRoot, relativeToSiblings))) {
|
||||
missingPaths.add(trimmed);
|
||||
}
|
||||
// Outside this repository: `../<paired repository>/<path at its pin>`.
|
||||
const found = pairedReferenceExists(trimmed);
|
||||
if (found === null) unverifiedLinks.add(trimmed);
|
||||
else if (!found) missingPaths.add(trimmed);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
@@ -416,6 +457,15 @@ if (!passed) {
|
||||
);
|
||||
}
|
||||
}
|
||||
if (documentReferences.some((entry) => entry.missingPaths.some((file) => file.startsWith("../")))) {
|
||||
const checked = [...pairedTrees]
|
||||
.filter(([, tree]) => "paths" in tree)
|
||||
.map(([repository]) => `${repository} ${pairedPins.get(repository)?.slice(0, 12)}`);
|
||||
process.stderr.write(
|
||||
`A path outside this repository must be in a repository ${PAIRED_PIN} pins, at the pinned commit` +
|
||||
`${checked.length > 0 ? ` (looked up in ${checked.join(", ")})` : ""}\n`,
|
||||
);
|
||||
}
|
||||
if (!reportDigestValid) {
|
||||
process.stderr.write(
|
||||
`${ledger.evidenceReport.repoPath} does not contain the ledger's canonicalSha256\n`,
|
||||
@@ -438,9 +488,12 @@ if (!passed) {
|
||||
}
|
||||
const unverified = documentReferences.flatMap((entry) => entry.unverifiedLinks);
|
||||
if (unverified.length > 0) {
|
||||
const reasons = [...pairedTrees].flatMap(([repository, tree]) =>
|
||||
"unverified" in tree ? [`${repository} pinned at ${pairedPins.get(repository)?.slice(0, 12)}: ${tree.unverified}`] : [],
|
||||
);
|
||||
process.stdout.write(
|
||||
`Documentation readiness: ${unverified.length} reference(s) into paired repositories not verified ` +
|
||||
`(no checkout beside ${process.cwd()}): ${[...new Set(unverified)].join(", ")}\n`,
|
||||
`(${reasons.join("; ")}): ${[...new Set(unverified)].join(", ")}\n`,
|
||||
);
|
||||
}
|
||||
process.stdout.write("Documentation readiness: PASS_SCOPED\n");
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
/**
|
||||
* 0929/12-03. The graph checks one edge at a time, so a file that feature
|
||||
* presentation may import must not reach a concrete adapter. The rule covered
|
||||
* the feature root files only: a file in a feature folder that is not a layer
|
||||
* (`support/`) imported the http adapter barrel, presentation imported it,
|
||||
* and check:architecture and ESLint both passed (review 1105, 12-R3). This
|
||||
* reads the rule as check:architecture does (`from.path`, `from.pathNot` and
|
||||
* `to.path` as unicode regular expressions).
|
||||
*/
|
||||
type DependencyRule = Readonly<{
|
||||
name: string;
|
||||
from: Readonly<{ path?: string; pathNot?: string }>;
|
||||
to: Readonly<{ path?: string }>;
|
||||
}>;
|
||||
|
||||
async function rule(name: string): Promise<(source: string, target: string) => boolean> {
|
||||
const { forbidden } = JSON.parse(await readFile(".dependency-cruiser.json", "utf8")) as {
|
||||
forbidden: DependencyRule[];
|
||||
};
|
||||
const found = forbidden.find((candidate) => candidate.name === name);
|
||||
if (!found) throw new Error(`no rule ${name}`);
|
||||
const from = new RegExp(found.from.path ?? "", "u");
|
||||
const fromNot = found.from.pathNot === undefined ? null : new RegExp(found.from.pathNot, "u");
|
||||
const to = new RegExp(found.to.path ?? "", "u");
|
||||
return (source, target) => from.test(source) && !(fromNot?.test(source) ?? false) && to.test(target);
|
||||
}
|
||||
|
||||
const HTTP_BARREL = "src/adapters/http/index.ts";
|
||||
|
||||
describe("feature-and-app-roots-do-not-reach-adapters (0929/12-03)", () => {
|
||||
it("rejects a concrete adapter import from a feature folder that is not a layer", async () => {
|
||||
const applies = await rule("feature-and-app-roots-do-not-reach-adapters");
|
||||
expect(applies("src/features/catalog/support/direct-http.ts", HTTP_BARREL)).toBe(true);
|
||||
expect(applies("src/features/catalog/support/nested/direct-http.tsx", HTTP_BARREL)).toBe(true);
|
||||
});
|
||||
|
||||
it("still rejects the feature root files, contexts and apps", async () => {
|
||||
const applies = await rule("feature-and-app-roots-do-not-reach-adapters");
|
||||
expect(applies("src/features/installed-feature-adapters.ts", HTTP_BARREL)).toBe(true);
|
||||
expect(applies("src/features/catalog/feature-runtime.ts", HTTP_BARREL)).toBe(true);
|
||||
expect(applies("src/contexts/commerce/context-module.ts", HTTP_BARREL)).toBe(true);
|
||||
expect(applies("src/apps/template-app.ts", HTTP_BARREL)).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves a feature's adapters folder and the type-only contribution file to reach adapters", async () => {
|
||||
const applies = await rule("feature-and-app-roots-do-not-reach-adapters");
|
||||
expect(applies("src/features/catalog/adapters/catalog-http-gateway.ts", HTTP_BARREL)).toBe(false);
|
||||
expect(applies("src/features/feature-adapter-contribution.ts", HTTP_BARREL)).toBe(false);
|
||||
// Only the adapters folder: a folder merely named like it elsewhere is not.
|
||||
expect(applies("src/features/catalog/support/adapters/x.ts", HTTP_BARREL)).toBe(true);
|
||||
// A feature's presentation-side query adapter is not a concrete adapter.
|
||||
expect(applies("src/features/catalog/support/x.ts", "src/presentation/adapters/query/index.ts")).toBe(false);
|
||||
});
|
||||
});
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
// A feature's adapters/ folder is where a feature reaches src/adapters.
|
||||
export { telemetryAdapter as alphaTelemetrySink } from "../../../adapters/telemetry/index.ts";
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
// 0929/12-03: every direct rule passes on this edge; the support file is where
|
||||
// the adapter leaks in.
|
||||
export { telemetryAdapter } from "../support/telemetry.ts";
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
// 0929/12-03: a file in a feature folder that is not a layer, re-exporting a
|
||||
// concrete adapter. Feature presentation may import it.
|
||||
export * from "../../../adapters/telemetry/index.ts";
|
||||
@@ -1,33 +1,36 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { devNull, tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const INPUTS = ["README.md", "docs", "artifacts/tests/a11y-manual"];
|
||||
// The pin says which commit of the paired backend the documents describe.
|
||||
const INPUTS = ["README.md", "docs", "artifacts/tests/a11y-manual", "config/contracts/backend-contract-pin.json"];
|
||||
const PAIRED_BACKEND = "clean-architecture-backend-template";
|
||||
|
||||
type Changes = Readonly<Record<string, (text: string) => string>>;
|
||||
|
||||
/**
|
||||
* Runs verify:documentation on a copy of its inputs, each `changes` entry
|
||||
* applied to its document and every `removed` file deleted. Code facts (src,
|
||||
* package.json, gates.json) are read from this repository, not the copy. The
|
||||
* copy is a `frontend` folder; `siblings` are files written beside it, where a
|
||||
* checkout of the paired repositories would be.
|
||||
* copy is a `frontend` folder; `paired` builds what sits beside it, where a
|
||||
* checkout of the paired repositories would be, and returns more changes (a
|
||||
* pin to its commit).
|
||||
*/
|
||||
async function verify(
|
||||
changes: Readonly<Record<string, (text: string) => string>>,
|
||||
changes: Changes,
|
||||
removed: readonly string[] = [],
|
||||
siblings: Readonly<Record<string, string>> = {},
|
||||
paired: (parent: string) => Changes = () => ({}),
|
||||
) {
|
||||
const parent = await mkdtemp(path.join(tmpdir(), "documentation-readiness-"));
|
||||
const root = path.join(parent, "frontend");
|
||||
try {
|
||||
for (const [file, content] of Object.entries(siblings)) {
|
||||
await mkdir(path.dirname(path.join(parent, file)), { recursive: true });
|
||||
await writeFile(path.join(parent, file), content);
|
||||
}
|
||||
const pairedChanges = paired(parent);
|
||||
for (const input of INPUTS) await cp(input, path.join(root, input), { recursive: true });
|
||||
for (const [document, mutate] of Object.entries(changes)) {
|
||||
for (const [document, mutate] of Object.entries({ ...changes, ...pairedChanges })) {
|
||||
const target = path.join(root, document);
|
||||
await writeFile(target, mutate(await readFile(target, "utf8")));
|
||||
}
|
||||
@@ -51,6 +54,63 @@ function verifyWithReadme(mutate: (readme: string) => string, document = "README
|
||||
return verify({ [document]: mutate });
|
||||
}
|
||||
|
||||
const gitEnvironment = {
|
||||
...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_"))),
|
||||
GIT_CONFIG_GLOBAL: devNull,
|
||||
GIT_CONFIG_NOSYSTEM: "1",
|
||||
};
|
||||
function git(cwd: string, ...args: string[]): string {
|
||||
const result = spawnSync(
|
||||
"git",
|
||||
["-c", "user.name=fixture", "-c", "user.email=fixture@example.invalid", "-c", "commit.gpgsign=false", ...args],
|
||||
{ cwd, encoding: "utf8", env: gitEnvironment },
|
||||
);
|
||||
if (result.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${result.stderr}`);
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* A git checkout of the paired backend beside the copy: one commit per
|
||||
* `history` entry (a file set to null is deleted), then `uncommitted` written
|
||||
* to its working tree. Returns the commit ids.
|
||||
*/
|
||||
function pairedCheckout(
|
||||
parent: string,
|
||||
history: readonly Readonly<Record<string, string | null>>[],
|
||||
uncommitted: Readonly<Record<string, string>> = {},
|
||||
): string[] {
|
||||
const root = path.join(parent, PAIRED_BACKEND);
|
||||
const write = (files: Readonly<Record<string, string | null>>) => {
|
||||
for (const [file, content] of Object.entries(files)) {
|
||||
const target = path.join(root, file);
|
||||
if (content === null) {
|
||||
rmSync(target);
|
||||
} else {
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, content);
|
||||
}
|
||||
}
|
||||
};
|
||||
mkdirSync(root, { recursive: true });
|
||||
git(root, "init", "-q");
|
||||
const commits: string[] = [];
|
||||
for (const files of history) {
|
||||
write(files);
|
||||
git(root, "add", "-A");
|
||||
git(root, "commit", "-q", "--allow-empty", "-m", `fixture ${commits.length}`);
|
||||
commits.push(git(root, "rev-parse", "HEAD"));
|
||||
}
|
||||
write(uncommitted);
|
||||
return commits;
|
||||
}
|
||||
|
||||
function pinnedTo(commit: string): Changes {
|
||||
return {
|
||||
"config/contracts/backend-contract-pin.json": (pin) =>
|
||||
pin.replace(/"commit": "[0-9a-f]+"/u, `"commit": "${commit}"`),
|
||||
};
|
||||
}
|
||||
|
||||
// 1101/14-06. A route missing from a scope document used to fail with only
|
||||
// "canonical scoped-review evidence is incomplete", which points at the
|
||||
// diagram review instead of the file to fix.
|
||||
@@ -171,11 +231,10 @@ describe("verify:documentation commands and sibling links (1103/12-05)", () => {
|
||||
it("checks a link or a path into a paired repository checked out beside this one", async () => {
|
||||
const naming = (target: string) => (text: string) =>
|
||||
`${text}\n[contract](../../../${target}) and \`${target}\`\n`;
|
||||
const present = await verify(
|
||||
{ [CI_DOC]: naming(BACKEND) },
|
||||
[],
|
||||
{ [BACKEND]: "# contract\n" },
|
||||
);
|
||||
// 1105/12-02. The checkout is looked up at the pinned commit.
|
||||
const pinnedBackend = (parent: string) =>
|
||||
pinnedTo(pairedCheckout(parent, [{ "docs/web/http-contract.md": "# contract\n" }])[0]!);
|
||||
const present = await verify({ [CI_DOC]: naming(BACKEND) }, [], pinnedBackend);
|
||||
// Only this document is under test: other documents name paired-backend
|
||||
// paths the stub checkout does not have.
|
||||
expect(present.stderr).not.toContain(`${CI_DOC} names paths that do not exist`);
|
||||
@@ -186,7 +245,7 @@ describe("verify:documentation commands and sibling links (1103/12-05)", () => {
|
||||
const broken = await verify(
|
||||
{ [CI_DOC]: naming("clean-architecture-backend-template/docs/web/no-such.md") },
|
||||
[],
|
||||
{ [BACKEND]: "# contract\n" },
|
||||
pinnedBackend,
|
||||
);
|
||||
expect(broken.status).toBe(1);
|
||||
expect(broken.stderr).toContain(
|
||||
@@ -205,6 +264,72 @@ describe("verify:documentation commands and sibling links (1103/12-05)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// 1105/12-02. Paired references were looked up in the working tree of the
|
||||
// checkout beside this one, so the same commit failed on the desktop (a
|
||||
// sibling months behind with uncommitted changes), passed with 17 references
|
||||
// unverified where no sibling was, and a misspelled repository passed as
|
||||
// unverified. They are looked up at the commit the pin names.
|
||||
describe("verify:documentation paired references at the pinned commit (1105/12-02)", () => {
|
||||
const CI_DOC = "docs/operations/ci-quality-gates.md";
|
||||
const naming = (...targets: string[]) => (text: string) =>
|
||||
`${text}\n${targets.map((target) => `[link](../../../${target}) and \`${target}\``).join("\n")}\n`;
|
||||
const entryOf = (result: Awaited<ReturnType<typeof verify>>) =>
|
||||
result.report?.documentReferences.find((entry) => entry.path === CI_DOC);
|
||||
|
||||
it("looks a reference up in the pinned commit, not in a later HEAD or the working tree", async () => {
|
||||
const result = await verify(
|
||||
{
|
||||
[CI_DOC]: naming(
|
||||
`${PAIRED_BACKEND}/docs/web/http-contract.md`,
|
||||
`${PAIRED_BACKEND}/docs/web/after-pin.md`,
|
||||
`${PAIRED_BACKEND}/docs/web/uncommitted.md`,
|
||||
),
|
||||
},
|
||||
[],
|
||||
(parent) => {
|
||||
const [pinned] = pairedCheckout(
|
||||
parent,
|
||||
[
|
||||
{ "docs/web/http-contract.md": "# contract\n" },
|
||||
{ "docs/web/http-contract.md": null, "docs/web/after-pin.md": "# later\n" },
|
||||
],
|
||||
{ "docs/web/uncommitted.md": "# draft\n" },
|
||||
);
|
||||
return pinnedTo(pinned!);
|
||||
},
|
||||
);
|
||||
// Other documents name paired paths the stub does not have, so only this
|
||||
// document's entry is compared.
|
||||
expect(entryOf(result)?.missingPaths).toEqual([
|
||||
`../${PAIRED_BACKEND}/docs/web/after-pin.md`,
|
||||
`../${PAIRED_BACKEND}/docs/web/uncommitted.md`,
|
||||
]);
|
||||
expect(entryOf(result)?.unverifiedLinks).toEqual([]);
|
||||
expect(result.stderr).toContain("at the pinned commit (looked up in clean-architecture-backend-template ");
|
||||
});
|
||||
|
||||
it("reports the references as not verified when the checkout does not have the pinned commit", async () => {
|
||||
// The desktop case: a sibling whose history stops before the pin, with
|
||||
// none of the files the documents name.
|
||||
const result = await verify({ [CI_DOC]: naming(`${PAIRED_BACKEND}/docs/web/no-such.md`) }, [], (parent) => {
|
||||
pairedCheckout(parent, [{ "README.md": "# an older backend\n" }]);
|
||||
return {};
|
||||
});
|
||||
expect(result.status, result.stderr).toBe(0);
|
||||
expect(entryOf(result)?.missingPaths).toEqual([]);
|
||||
expect(entryOf(result)?.unverifiedLinks).toEqual([`../${PAIRED_BACKEND}/docs/web/no-such.md`]);
|
||||
expect(result.stdout).toContain("not verified");
|
||||
expect(result.stdout).toContain("does not have the pinned commit");
|
||||
});
|
||||
|
||||
it("fails a link out of the repository into a repository that is not paired", async () => {
|
||||
const misspelled = "clean-architecture-backend-templat/docs/web/http-contract.md";
|
||||
const result = await verify({ [CI_DOC]: (text) => `${text}\n[contract](../../../${misspelled})\n` });
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain(`${CI_DOC} names paths that do not exist: ../${misspelled}`);
|
||||
});
|
||||
});
|
||||
|
||||
// 1101/14-03. The entry documents drew a top-level domain layer that does not
|
||||
// exist, left out three of the nine src folders, and layers.md named a
|
||||
// minority of the architecture rules while claiming it could not drift.
|
||||
|
||||
@@ -54,6 +54,8 @@ const DEPLOYMENT = {
|
||||
const DEPLOY_SCRIPTS = { "deploy:desktop": "node scripts/deploy-desktop.ts" };
|
||||
const GATE = { id: "PRODUCT-GATE-001", name: "backend-contract", script: "check:backend-contract" };
|
||||
const GATE_SCRIPTS = { "check:backend-contract": "node scripts/check-backend-contract.ts" };
|
||||
const RELEASE_HELD_BY_TEMPLATE = " needs: merge_gate\n";
|
||||
const RELEASE_HELD_BY_PRODUCT = " needs: [merge_gate, product_merge_gate]\n";
|
||||
|
||||
describe("product CI overlay (1103/12-07)", () => {
|
||||
it("ships empty, so the template's own workflow is unchanged", async () => {
|
||||
@@ -143,14 +145,49 @@ describe("product CI overlay (1103/12-07)", () => {
|
||||
expect(job).toContain(" run: corepack pnpm ${{ matrix.script }}");
|
||||
expect(job).toContain(` if: ${"${{ gitea.event_name != 'workflow_dispatch' || inputs.stage != 'documentation' }}"}`);
|
||||
expect(workflowGateExecutionFailures(contract, workflow, mergeGates)).toEqual([]);
|
||||
// The template part of the workflow is the same bytes with or without the overlay.
|
||||
expect(workflow.startsWith(renderCiWorkflow(contract).trimEnd())).toBe(true);
|
||||
// The template part of the workflow is the same bytes with or without the
|
||||
// overlay, except that the release stage waits for the product job (1105/13-02).
|
||||
expect(
|
||||
workflow.replace(RELEASE_HELD_BY_PRODUCT, RELEASE_HELD_BY_TEMPLATE).startsWith(renderCiWorkflow(contract).trimEnd()),
|
||||
).toBe(true);
|
||||
|
||||
expect(workflowGateExecutionFailures(contract, renderCiWorkflow(contract), mergeGates)).toEqual([
|
||||
"product gate is not executed by the product_merge_gate job: PRODUCT-GATE-001",
|
||||
"product gates do not hold the release stage: release_gate does not need product_merge_gate",
|
||||
]);
|
||||
});
|
||||
|
||||
// 1105/13-02. A failing product gate stopped only a PR merge (as a required
|
||||
// check): the same run went on to release, promote and deploy, and the fixed
|
||||
// job graph left the product no way to link them.
|
||||
it("holds the release stage until the product merge gates pass", async () => {
|
||||
const root = await productRoot(
|
||||
{ schemaVersion: 1, deployment: DEPLOYMENT, mergeGates: [GATE] },
|
||||
{ ...DEPLOY_SCRIPTS, ...GATE_SCRIPTS },
|
||||
);
|
||||
const contract = await loadCiGateContract(root);
|
||||
const { mergeGates } = await loadProductCiOverlay(root);
|
||||
const releaseJob = (workflow: string) =>
|
||||
workflow.slice(workflow.indexOf(" release_gate:\n"), workflow.indexOf(" immutable_build:\n"));
|
||||
|
||||
const workflow = renderCiWorkflow(contract, mergeGates);
|
||||
expect(releaseJob(workflow)).toContain(RELEASE_HELD_BY_PRODUCT);
|
||||
// immutable_build, and through it every later release-stage job
|
||||
// (deployment included), needs release_gate.
|
||||
expect(contract.jobs.find(({ id }) => id === "immutable_build")?.needs).toEqual(["release_gate"]);
|
||||
// Without product gates the template's own graph is rendered.
|
||||
expect(releaseJob(renderCiWorkflow(contract))).toContain(RELEASE_HELD_BY_TEMPLATE);
|
||||
|
||||
// check:ci refuses a workflow that runs the product gates without the link.
|
||||
expect(
|
||||
workflowGateExecutionFailures(
|
||||
contract,
|
||||
workflow.replace(RELEASE_HELD_BY_PRODUCT, RELEASE_HELD_BY_TEMPLATE),
|
||||
mergeGates,
|
||||
),
|
||||
).toEqual(["product gates do not hold the release stage: release_gate does not need product_merge_gate"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a template gate id", { mergeGates: [{ ...GATE, id: "FE-GATE-030" }] }, /PRODUCT-GATE-NNN/u],
|
||||
["a duplicate gate id", { mergeGates: [GATE, { ...GATE, name: "other" }] }, /duplicate product gate/u],
|
||||
|
||||
Reference in New Issue
Block a user