fix(docs): 드릴이 사본에서만 지우는 시험을 문서가 경로로 적으면 노트북에서 실패한다 #80

Merged
donghyeon.kang merged 3 commits from donghyeon.kang/ci/removal-drill-doc-paths AGit into main 2026-11-20 20:29:23 +00:00
6 changed files with 570 additions and 5 deletions
+1
View File
@@ -160,6 +160,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지
| `scripts/verify.sh`가 RELEASE_ID에 checkout 브랜치 이름을 넣지 않고 CI와 같은 꼴의 고정 ref(`refs/heads/verify-1-1`)를 쓴다. 같은 트리의 FE-GATE-008 결과가 브랜치 이름 길이로 갈렸다 | `scripts/verify.sh`, `scripts/tests/test_verify.py` | `4ab62f81` |
| 제거 drill의 사본 준비(`prepareRemovalFixture`)가 checkout에 없는 `optional` 등록부 항목(`recipes`)을 건너뛴다. 없는 필수 경로에서는 cp의 ENOENT 스택 대신, 사본 폴더를 비우기 전에 그 경로와 고르는 등록부 항목, 고칠 곳(경로를 되살리거나 항목을 지우거나 그 항목의 `setPaths`에서 빼기)을 대고 멈춘다. 등록부가 고르지 않는 경로도 이름으로 댄다. 매뉴얼 03 R1이 추적하는 항목도 drill 사본이나 제품 사본에 없을 수 있으면 `optional`로 적으라고 한다 | `scripts/lib/removal-fixture.ts`, `tests/unit/removal-fixture.test.ts`, `docs/manual/03-outside-feature-folder.md` | `44453592` |
| FE-GATE-013의 시스템 컨테이너 래퍼(`scripts/run-in-system-container.sh`)가 게이트 도중 TERM·INT·HUP(시간 초과, Ctrl-C, 터미널 끊김)을 받으면 그때까지 쌓인 `artifacts/`를 되가져오고 컨테이너를 지운 뒤 그 신호로 끝난다. 게이트 전에 받으면 컨테이너만 지우고 그 신호로 끝난다. 고치기 전에는 게이트 도중 TERM·HUP에 증거 없이 끝났고, 게이트 전 Ctrl-C에는 부팅·복사를 이어 가 게이트까지 돌았고, `docker run` 도중의 신호에는 컨테이너가 남았다. 컨테이너 이름은 `fe-system-container-<uuid>`이고 정리는 이름으로 지운다. 게이트 로그는 끝날 때 쓰므로 신호로 끊긴 실행에서는 오지 않는다. SIGKILL 뒤 남은 컨테이너를 찾아 지우는 명령은 운영 문서 FE-GATE-013 절에 있다 | `scripts/run-in-system-container.sh`, `tests/unit/ci-gate-host-environment.test.ts`, `docs/operations/ci-quality-gates.md` | `b5f28e52` |
| 노트북 `scripts/verify.sh docs`(`scripts/check-work-docs.py`)가, 기능 제거 드릴이 사본에서만 지우는 시험(`scripts/test-sample-removal.ts`의 `excludedFixtureTest` 목록)을 드릴 사본의 `verify:documentation`이 경로로 읽는 자리에 적으면 `file:line`으로 실패한다. 그 자리는 드릴이 복사하는 살아 있는 문서의 백틱 경로·명령 인자·상대 링크와 기록 문서 머리 블록의 「현재 정본」「대체」「대체됨」이다. 전에는 desktop FE-GATE-020에서야 드러났다. 그런 시험은 폴더와 파일 이름을 따로 적는다(`tests/unit/`의 `removal-fixture.test.ts`). 드릴은 `package.json`의 `test:sample-removal`로 찾는다. 그 script가 읽을 드릴 파일을 가리키지 않으면 「runs no drill file」, 목록을 못 찾으면 「was not found」, 목록에 큰따옴표 경로 말고 다른 것(펼침·작은따옴표)이 있으면 「holds more than double-quoted paths」로 실패한다. 이 규칙의 정본은 TypeScript이고, Python으로 다시 쓴 쪽과 어긋나면 `scripts/tests/test_check_work_docs.py`가 실패한다 | `scripts/check-work-docs.py`, `scripts/tests/test_check_work_docs.py`, `scripts/test-sample-removal.ts`, `docs/operations/adapter-remediation-ledger.md` | `d87f6792` |
## 미출시 — `8327e221` → 하네스와 작업 매뉴얼
+1
View File
@@ -17,3 +17,4 @@
{"date": "2026-11-14", "test": "tests/system/ci-runner/ci-artifact-contract.test.ts:892", "category": "fixed-time", "first_run": "294", "verdict": "runner 1회 실패(FE-GATE-013, 4271 ms, 상한 4000). 단언은 공급자가 4초 감독 시한 전에 스스로 끝났는지가 아니라 완료 뒤 trace 확인까지의 벽시계를 쟀다. desktop 탐침에서 감독은 2574 ms에 exit 0·timed out 없이 끝났는데 완료 뒤 2.6초를 두자 같은 줄이 5180 ms로 실패(결정적). 같은 모양 :1105(CPU rlimit 시험의 5초 상한)도 고침", "quarantined_until": "", "fixed_by": "프론트 #57"}
{"date": "2026-11-19", "test": "tests/browser-capabilities/cross-context-invalidation.spec.ts:223", "category": "concurrency-order", "first_run": "371", "verdict": "원인 확정(2026-11-19). [chromium] runner run 371 1회 실패(받은 deliveries []). desktop main f3de258d 단독 3회 모두 통과, CPU·메모리 hog 12개(nice 19, load 17.5) 아래 --repeat-each 20 중 1회 실패(같은 단언). Chromium은 탭의 첫 localStorage 읽기(CachedStorageArea::EnsureLoaded)에서 observer를 바꾸며 이미 도착한 다른 탭의 변경 알림을 버린다. 받는 page가 바쁠 때 그 page의 첫 읽기(발행 직후 snapshot, 또는 앱 부트의 설정 읽기)가 먼저 돌아 pulse를 잃었다(늦음이 아니라 잃음: 실패 회차에 raw storage 이벤트 0개). 받는 page를 막은 사이 발행하고 같은 작업에서 첫 읽기를 하는 탐침이 고치기 전 chromium 5/5 실패(firefox·webkit 10/10 통과). 고친 트리 ddda30a3에서 hog 12개 아래 chromium 그 spec 120회 실패 0", "quarantined_until": "", "fixed_by": "프론트 #63"}
{"date": "2026-11-19", "test": "tests/e2e/generated-feature.spec.ts:127", "category": "fixed-time", "first_run": "344", "verdict": "runner run 344(#60 62ba55d7, FE-GATE-008 webkit :276)에서 1회 실패. signInAt의 첫 h1 기본 5초 대기에서 h1 없음(429와 무관). 원인은 CPU 포화 — 세션 부하 실험(nice 없는 busy loop·메모리 hog, 01:06~02:0x)과 runner job이 겹쳤다(sar 01:40~02:00 idle 0.08~2.5%, runq 28, iowait 0.01%). 평시에는 재현 안 됨 0/~970(webkit goto→h1 최대 2.2s, load 32 이하). 일부러 포화시키면(busy loop 34, load 44~51) h1>5s 7~33/90이고, 청크 가로채기 유무와 무관(7/90·8/90). 시험은 고치지 않는다. 부하 실험을 nice -n 19로 돌리고 runner job이 없을 때 시작한다", "quarantined_until": "", "fixed_by": ""}
{"date": "2026-11-21", "test": "tests/unit/browser-rpc/browser-rpc-remediation.test.ts:577", "category": "fixed-time", "first_run": "455", "verdict": "재현 안 됨. runner run 455(main 945b70c0) FE-GATE-030 드릴 사본의 test에서 1회 실패(job 시작 load 8.04): RPC-01 「waitClosed returns a non-promise」의 :577 expect(probe.opened()).toBe(1)이 0을 받았다. desktop 같은 트리(31053211)에서 그 파일 단독 3회 모두 통과(load 5.65 9.78 11.59), busy loop 12개(nice 19, 12코어) 아래 20회 실패 0(load 12.1~15.9). 범주는 실패 모양으로 붙인 후보다: 시험이 실제 시계로 total·idle deadline 25 ms(shortDeadline)와 30 ms로 자른 sleep(cappedClock)을 쓰고, 물리 스트림이 열리기 전에 끝났다. 시험은 고치지 않고 다음 실패를 기다린다", "quarantined_until": "", "fixed_by": ""}
@@ -318,7 +318,7 @@ AssertionError: expected [] to deeply equal ArrayContaining{…}
| 게이트 | 상태 | 원인 |
| --- | --- | --- |
| tests/unit/ci-workflow-generation.test.ts | 82개 실패 / 325개 통과 | 변경 전 기준에서도 같다(`git stash` 비교). 이 파일이 띄우는 하위 프로세스 게이트는 이 sandbox에서 돌 수 없다. |
| `tests/unit/`의 `ci-workflow-generation.test.ts` | 82개 실패 / 325개 통과 | 변경 전 기준에서도 같다(`git stash` 비교). 이 파일이 띄우는 하위 프로세스 게이트는 이 sandbox에서 돌 수 없다. |
| `tests/system/ci-runner/ci-artifact-contract.test.ts` | 실패 | 원래 있던 그대로의 sandbox, cgroup, `/tmp` 권한 동작이다. |
| `tests/unit/security-followup.test.ts`, `tests/integration/provider-guardian-transaction.test.ts`, `tests/unit/risk-coverage.test.ts` | 전체 실행 부하에서 불안정(flaky) | 과거 기준 결과다. 셋 다 새 프로세스에서 통과했다(함께 돌려 78개 통과). |
@@ -345,12 +345,12 @@ AssertionError: expected [] to deeply equal ArrayContaining{…}
| 파일 | 실패 | 원인 |
| --- | ---: | --- |
| tests/unit/ci-workflow-generation.test.ts | 82 | 변경 전 기준에서도 같다(`git stash` 비교). 이 파일의 하위 프로세스 게이트는 이 sandbox에서 돌 수 없다. |
| `tests/unit/`의 `ci-workflow-generation.test.ts` | 82 | 변경 전 기준에서도 같다(`git stash` 비교). 이 파일의 하위 프로세스 게이트는 이 sandbox에서 돌 수 없다. |
| `tests/system/ci-runner/ci-artifact-contract.test.ts` | 19 | 원래 있던 그대로의 sandbox, cgroup, `/tmp` 권한 동작이다. |
| `tests/unit/security-followup.test.ts` | 2 | 따로 돌리면 통과한다. |
| `tests/integration/provider-guardian-transaction.test.ts` | 1 | 과거 기준: 따로 돌리면 통과했다. 지금은 프로세스 integration 테스트로 분류한다. |
전체 1723개 중 1619개 통과다. 전에는 빼야 했던 세 파일 tests/unit/removal-fixture.test.ts,
전체 1723개 중 1619개 통과다. 전에는 빼야 했던 세 파일 `tests/unit/`의 `removal-fixture.test.ts`,
`tests/unit/supply-chain.test.ts`,
`tests/integration/security-followup-archive.test.ts`도 이제 전체 실행에서 통과한다.
+262
View File
@@ -23,6 +23,13 @@ mistakes" section stays short, that `CLAUDE.md` starts with the import, that eve
`src/**/AGENTS.md` has a `CLAUDE.md` beside it that only imports it (so Claude Code reads the same
book) and stays under 200 lines, and that relative links in the checked files resolve. The same layout and limits as the paired backend template's checker.
One check is about the feature removal drill (FE-GATE-020, desktop): the drill deletes a few tests
from its copy only (the list in `scripts/test-sample-removal.ts`) and runs `verify:documentation`
there. A document the drill copies that names one of them where that check reads paths (a backtick
path, a command word, a link, a record's head block) fails that gate, so it fails here first with
its line. The rules for what the copy holds and reads are TypeScript; this file repeats them, and
`TypeScriptRulesTest` in `scripts/tests/test_check_work_docs.py` fails when the two drift apart.
Standard library only, so it runs on the laptop and in the edit hook (scripts/hooks/hooks.py, N2).
`verify:documentation` (FE-GATE-017) checks the paths, scripts and gate IDs these documents name.
@@ -33,6 +40,8 @@ Standard library only, so it runs on the laptop and in the edit hook (scripts/ho
from __future__ import annotations
import json
import posixpath
import re
import sys
from pathlib import Path
@@ -124,6 +133,57 @@ HISTORY_PATTERNS = [
]
LINK = re.compile(r"\[[^\]]*\]\(([^)\s]+)\)", re.ASCII)
# --- The removal drill's copy (FE-GATE-020). Each group repeats the TypeScript file named above it;
# TypeScriptRulesTest (scripts/tests/test_check_work_docs.py) reads those files and fails on a change
# made to one side only.
PACKAGE = REPO_ROOT / "package.json"
# The drill is the last file the package script runs with node (it first generates the feature index).
DRILL_SCRIPT = "test:sample-removal"
DRILL_RUNS = re.compile(r"\bnode\s+(\S+)")
# scripts/test-sample-removal.ts. The drill has other loops over array literals; this one is found by
# its variable, and it may hold only double-quoted paths.
DRILL_DELETIONS = re.compile(r"for \(const excludedFixtureTest of \[([^\]]*)\]\)")
DRILL_LIST = re.compile(r'\s*(?:"[^"\\\n]*"\s*,\s*)*(?:"[^"\\\n]*"\s*,?\s*)?')
DRILL_ITEM = re.compile(r'"([^"\\\n]*)"')
# scripts/lib/removal-fixture.ts (what prepareRemovalFixture copies) and scripts/lib/repository-layout.ts
# (selectRepositoryPaths: an entry in the set, or the entry's setPaths for it).
LAYOUT = REPO_ROOT / "config/repository-layout.json"
COPIED_SETS = ("fixture-copy", "fixture-documents")
# scripts/lib/docs-system.ts: which documents are living, which are records, and a record's head block.
RECORD_FOLDERS = ("docs/design/", "docs/history/", "docs/reviews/")
DECISION_FOLDER = "docs/adr/"
LIVING_IN_RECORDS = frozenset({"docs/reviews/adapters/INVENTORY.md"})
HISTORY_HOLDERS = frozenset({"CHANGELOG.md", "docs/architecture/review-evidence.md", "docs/work/evidence.md"})
NOT_DOCUMENT = re.compile(r"^docs\/accessibility\/route-reviews\/")
RECORD_KINDS = ("docs/design/", "docs/history/plans/", "docs/history/evidence/", "docs/history/packages/",
"docs/history/study/", "docs/adr/")
HEAD_START = "<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->"
HEAD_END = "<!-- 머리 블록 끝 -->"
HEAD_SEARCH_LINES = 20
HEAD_FIELD = re.compile(r"^- ([^:]+): (.+)$")
HEAD_CANONICAL = "현재 정본"
HEAD_OPTIONAL = ("대체", "대체됨")
HEAD_PATH = re.compile(r"`([^`]+)`")
# scripts/verify-documentation-readiness.ts: the documents it reads (the index's first section and the
# living documents) and where it reads paths in them.
DOCUMENT_INDEX = "docs/README.md"
INDEX_SECTION = re.compile(r"^## 1\.[\s\S]*?(?=^## )", re.MULTILINE)
INDEX_LINK = re.compile(r"\]\(([^)#\s]+)\)")
SPAN = re.compile(r"`([^`\n]+)`")
DOCUMENT_LINK = re.compile(r"\]\(([^)\s]+)\)")
ANCHOR = re.compile(r"#.*$")
LINE_NUMBER = re.compile(r":\d[\d,:-]*$")
NOT_A_PATH = re.compile(r"[\s*<>{}$()|…]|\.\.\.")
OUTSIDE_LINK = re.compile(r"^(?:[a-z][a-z+.-]*:|#)", re.IGNORECASE)
COMMAND_HEADS = frozenset({"corepack", "pnpm", "npx", "node", "vitest", "playwright", "tsc", "eslint", "bash", "sh",
"python3"})
VERIFY_ENTRY = re.compile(r"^(?:\.\/)?scripts\/verify\.sh$")
PROMPT = re.compile(r"^\$\s+")
ASSIGNMENT = re.compile(r"^[A-Z_][A-Z0-9_]*=")
FLAG = re.compile(r"^--?[\w.-]+=", re.ASCII)
QUOTES = re.compile(r"""^["']|["']$""")
FENCE = re.compile(r"^\s*```(\w*)", re.ASCII)
SHELL_FENCE = re.compile(r"^(?:bash|sh|shell|console|zsh)?$")
def rel(path: Path) -> str:
@@ -299,6 +359,207 @@ def check_links(errors: list[str], report: list[str]) -> None:
report.append(f"relative links checked: {checked}")
def drill_file(errors: list[str]) -> Path | None:
"""The drill the package script runs; none where a project removed it."""
if not PACKAGE.exists():
return None
script = json.loads(PACKAGE.read_text(encoding="utf-8")).get("scripts", {}).get(DRILL_SCRIPT)
if script is None:
return None
runs = DRILL_RUNS.findall(script)
if not runs or not (REPO_ROOT / runs[-1]).is_file():
errors.append(f"{rel(PACKAGE)}: `{DRILL_SCRIPT}` runs no drill file this check can read: {script!r}")
return None
return REPO_ROOT / runs[-1]
def drill_copy_only_deletions(errors: list[str]) -> tuple[Path | None, list[str]]:
"""The drill and the files it deletes from its copy only."""
drill = drill_file(errors)
if drill is None:
return None, []
match = DRILL_DELETIONS.search(drill.read_text(encoding="utf-8"))
if match is None:
errors.append(f"{rel(drill)}: the list of files the drill deletes from its copy was not found")
return drill, []
if not DRILL_LIST.fullmatch(match.group(1)):
errors.append(f"{rel(drill)}: the list of files the drill deletes from its copy holds more than"
" double-quoted paths, so this check cannot read it")
return drill, []
return drill, DRILL_ITEM.findall(match.group(1))
class DrillCopy:
"""What the drill's copy holds: the paths the layout's copied sets select, less its deletions."""
def __init__(self, targets: list[str], deleted: list[str]) -> None:
self.targets = [target for target in dict.fromkeys(targets) if (REPO_ROOT / target).exists()]
self.deleted = set(deleted)
self.top_level = {target.split("/")[0] for target in self.targets}
def has(self, path: str) -> bool:
return (path not in self.deleted and (REPO_ROOT / path).exists()
and any(path == target or path.startswith(f"{target}/") or target.startswith(f"{path}/")
for target in self.targets))
def documents(self) -> list[str]:
"""The copy's markdown files, as docs-system.ts readDocuments reads them."""
found = set()
for target in self.targets:
source = REPO_ROOT / target
for path in sorted(source.rglob("*.md")) if source.is_dir() else [source]:
name = rel(path)
if (name.endswith(".md") and path.is_file() and not SKIPPED_PARTS & set(Path(name).parts)
and not NOT_DOCUMENT.search(name)):
found.add(name)
return sorted(found)
def checked(self) -> list[str]:
"""The documents whose named paths the copy's verify:documentation checks."""
index = (REPO_ROOT / DOCUMENT_INDEX).read_text(encoding="utf-8") if self.has(DOCUMENT_INDEX) else ""
section = INDEX_SECTION.search(index)
named = {DOCUMENT_INDEX}
for target in INDEX_LINK.findall(section.group(0) if section else ""):
linked = posixpath.normpath(f"{posixpath.dirname(DOCUMENT_INDEX)}/{target}")
if (REPO_ROOT / linked).is_dir():
named.update(f"{linked}/{entry.name}" for entry in (REPO_ROOT / linked).iterdir()
if entry.name.endswith(".md"))
else:
named.add(linked)
named.update(path for path in self.documents() if checked_for_drift(path))
return sorted(path for path in named if path not in HISTORY_HOLDERS and self.has(path)
and (REPO_ROOT / path).is_file())
def records(self) -> list[str]:
"""The documents whose head block the copy's docs-system check reads."""
return [path for path in self.documents() if path.startswith(RECORD_KINDS)]
def checked_for_drift(path: str) -> bool:
living = path in LIVING_IN_RECORDS or not path.startswith(RECORD_FOLDERS)
return living and not path.startswith(DECISION_FOLDER) and path not in HISTORY_HOLDERS
def drill_copy(errors: list[str], deleted: list[str]) -> DrillCopy | None:
if not LAYOUT.exists():
errors.append(f"{rel(LAYOUT)}: missing (it lists what the removal drill copies)")
return None
targets = []
for entry in json.loads(LAYOUT.read_text(encoding="utf-8"))["entries"]:
for name in COPIED_SETS:
targets += [entry["path"]] if name in entry.get("sets", []) else entry.get("setPaths", {}).get(name, [])
return DrillCopy(targets, deleted)
def named_path(token: str, document: str, copy: DrillCopy) -> str | None:
"""A backtick span or a command word read as a path, as namedPath reads it; none for a paired repository."""
candidate = LINE_NUMBER.sub("", ANCHOR.sub("", token, count=1), count=1)
if "/" not in candidate or candidate.startswith("/") or NOT_A_PATH.search(candidate):
return None
first = candidate.split("/")[0]
if first in copy.top_level:
return candidate
beside = posixpath.dirname(document) or "."
if first not in (".", "..") and copy.has(posixpath.normpath(f"{beside}/{first}")):
return posixpath.normpath(f"{beside}/{candidate}")
return None
def linked_path(target: str, document: str) -> str | None:
if OUTSIDE_LINK.search(target):
return None
return posixpath.normpath(f"{posixpath.dirname(document) or '.'}/{ANCHOR.sub('', target, count=1)}")
def command_paths(command: str, document: str, copy: DrillCopy) -> list[str | None]:
"""The paths a command takes, as commandPaths reads them."""
words = PROMPT.sub("", command.strip(), count=1).split() or [""]
head = 0
while head < len(words) and ASSIGNMENT.search(words[head]):
head += 1
first = words[head] if head < len(words) else ""
if VERIFY_ENTRY.search(first):
separator = words.index("--", head + 1) if "--" in words[head + 1:] else -1
executed = (" ".join(words[separator + 1:])
if words[head + 1:head + 2] == ["exec"] and separator > head else "")
return [named_path(first, document, copy), *(command_paths(executed, document, copy) if executed else [])]
if first not in COMMAND_HEADS:
return []
return [named_path(QUOTES.sub("", FLAG.sub("", word, count=1)), document, copy) for word in words[head + 1:]]
def fenced_commands(text: str) -> list[tuple[int, str]]:
"""The lines of shell blocks, as fencedCommands reads them, with their line numbers."""
commands = []
fence = None
for number, line in enumerate(text.split("\n"), start=1):
marker = FENCE.search(line)
if marker:
fence = marker.group(1) if fence is None else None
continue
if fence is not None and SHELL_FENCE.search(fence):
commands.append((number, line))
return commands
def head_paths(text: str) -> list[tuple[int, str]]:
"""The paths a record's head block names in 「현재 정본」 and the optional fields, as checkHead reads them."""
lines = text.split("\n")
if lines[0] != HEAD_START or HEAD_END not in lines[:HEAD_SEARCH_LINES]:
return []
fields: dict[str, tuple[int, str]] = {}
for number, line in enumerate(lines[2:lines.index(HEAD_END)], start=3):
match = HEAD_FIELD.search(line)
if match and match.group(1).strip() not in fields:
fields[match.group(1).strip()] = (number, match.group(2).strip())
return [(fields[name][0], target) for name in (HEAD_CANONICAL, *HEAD_OPTIONAL) if name in fields
for target in HEAD_PATH.findall(fields[name][1])]
def drill_copy_hits(copy: DrillCopy) -> list[tuple[str, int, str]]:
"""(document, line, deleted file) where the copy's verify:documentation reads a path the copy lacks."""
hits = set()
def add(document: str, number: int, found: str | None) -> None:
name = posixpath.normpath(found) if found else None
if name in copy.deleted:
hits.add((document, number, name))
for document in copy.checked():
text = (REPO_ROOT / document).read_text(encoding="utf-8")
def line(offset: int) -> int:
return text.count("\n", 0, offset) + 1
for match in SPAN.finditer(text):
for found in (named_path(match.group(1), document, copy), *command_paths(match.group(1), document, copy)):
add(document, line(match.start()), found)
for number, command in fenced_commands(text):
for found in command_paths(command, document, copy):
add(document, number, found)
for match in DOCUMENT_LINK.finditer(text):
add(document, line(match.start()), linked_path(match.group(1), document))
for record in copy.records():
for number, target in head_paths((REPO_ROOT / record).read_text(encoding="utf-8")):
add(record, number, target)
return sorted(hits)
def check_drill_copy(errors: list[str], report: list[str]) -> None:
drill, deleted = drill_copy_only_deletions(errors)
copy = drill_copy(errors, deleted) if drill and deleted else None
if drill is None or copy is None:
return
for document, number, name in drill_copy_hits(copy):
folder, _, file = name.rpartition("/")
advice = ("Name a file the drill keeps" if document.startswith(RECORD_KINDS)
else f"Name the folder and the file apart: `{folder}/`의 `{file}`")
errors.append(f"{document}:{number}: '{name}' - the removal drill deletes it from its copy ({rel(drill)}),"
f" so the copy's verify:documentation fails FE-GATE-020. {advice}")
report.append(f"documents the removal drill copies, checked for its copy-only deletions: {len(copy.checked())},"
f" record head blocks: {len(copy.records())}")
def markdown_files(targets: list[str]) -> list[Path]:
files: list[Path] = []
for target in targets:
@@ -343,6 +604,7 @@ def main() -> int:
check_skeleton(errors)
check_history(errors, report)
check_links(errors, report)
check_drill_copy(errors, report)
for line in report:
print(line)
if errors:
+13 -2
View File
@@ -275,8 +275,19 @@ try {
...REMOVAL_FIXTURE_DOCUMENT_TARGETS,
]);
// Fixture-only deletions: a project that removes the sample keeps these.
// verify:documentation runs in this fixture, so a current contract document
// must not name them as backtick paths (docs/manual/reference/patterns.md).
// This copy checks its documents twice with no exceptions: the
// `documentation` check below, and the documentation-readiness unit test
// inside test:coverage, which starts verify:documentation itself (that test
// is not named here: removal-fixture.test.ts keeps the document-test list in
// scripts/lib/removal-fixture.ts only). A living
// document that names one of these files as a backtick path therefore fails
// FE-GATE-020 only. It names the folder and the file apart instead, as
// docs/operations/adapter-remediation-ledger.md does: the file name stays in
// backticks (.claude/rules/docs.md: 「검사를 피하려고 백틱을 빼지 않는다」)
// and, with no `/`, is not read as a path. scripts/check-work-docs.py finds
// this drill through package.json `test:sample-removal`, reads this list by
// `excludedFixtureTest` (double-quoted paths only) and fails such a line on
// the laptop first.
for (const excludedFixtureTest of [
"tests/unit/ci-workflow-generation.test.ts",
"tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap",
+290
View File
@@ -5,7 +5,10 @@
from __future__ import annotations
import contextlib
import importlib.util
import json
import re
import shutil
import subprocess
import sys
@@ -124,5 +127,292 @@ class BrokenCopyTest(unittest.TestCase):
self.assertIn("docs/work/reference/testing.md: missing", self.run_checker().stderr)
def typescript(path: str) -> str:
return (REPO / path).read_text(encoding="utf-8")
def ts_declaration(path: str, name: str) -> str:
"""The text right of `=` in `const <name> ... = ...;` of a TypeScript file."""
match = re.search(rf"^(?:export )?const {name}\b[^=]*= (.*?);$", typescript(path), re.MULTILINE | re.DOTALL)
if match is None:
raise AssertionError(f"{path}: no `const {name}`")
return match.group(1)
def ts_strings(path: str, name: str) -> list[str]:
return re.findall(r'"([^"\\\n]*)"', ts_declaration(path, name))
HEAD_START = ts_strings("scripts/lib/docs-system.ts", "HEAD_START")[0]
HEAD_END = ts_strings("scripts/lib/docs-system.ts", "HEAD_END")[0]
class DrillCopyTest(unittest.TestCase):
"""The same copy with the removal drill, its package script and the layout it copies by: a document the
drill copies must not name a file the drill deletes from its copy only where the copy's
verify:documentation reads paths, and may name it anywhere that check does not read."""
DELETED = "tests/unit/ci-workflow-generation.test.ts"
DECISIONS = "docs/work/reference/decisions.md"
run_checker = BrokenCopyTest.run_checker
def setUp(self) -> None:
BrokenCopyTest.setUp(self)
for path in ("package.json", "scripts/test-sample-removal.ts", "config/repository-layout.json"):
(self.root / path).parent.mkdir(parents=True, exist_ok=True)
shutil.copy(REPO / path, self.root / path)
# The drill's copy is made from a checkout that has the files it then deletes.
listed = check.DRILL_DELETIONS.search(typescript("scripts/test-sample-removal.ts")).group(1)
for path in check.DRILL_ITEM.findall(listed):
(self.root / path).parent.mkdir(parents=True, exist_ok=True)
(self.root / path).touch()
self.originals: dict[str, str | None] = {}
@contextlib.contextmanager
def case(self, **params: object):
"""A subtest that puts back every file edited in it, so the next one starts from setUp."""
with self.subTest(**params):
try:
yield
finally:
for path in self.originals:
self.restore(path)
def edit(self, path: str, text: str) -> int:
"""Sets `path` in the copy to its setUp text (none for a new file) plus `text`; case() and the test's
cleanup put it back. Returns the line `text` starts on."""
target = self.root / path
if path not in self.originals:
self.originals[path] = target.read_text(encoding="utf-8") if target.exists() else None
self.addCleanup(self.restore, path)
original = self.originals[path] or ""
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(original + text, encoding="utf-8")
return original.count("\n") + 1
def restore(self, path: str) -> None:
original = self.originals[path]
if original is None:
(self.root / path).unlink(missing_ok=True)
else:
(self.root / path).write_text(original, encoding="utf-8")
def assert_fails_at(self, path: str, text: str) -> None:
start = self.edit(path, text)
number = start + next(n for n, line in enumerate(text.split("\n")) if self.DELETED in line)
result = self.run_checker()
self.assertIn(f"{path}:{number}: '{self.DELETED}'", result.stderr, result.stdout + result.stderr)
# The line names no other document: N2 (scripts/hooks/hooks.py doc_findings) picks lines by the edited path.
line = next(line for line in result.stderr.splitlines() if f"{path}:{number}:" in line)
self.assertNotIn(".md", line.replace(path, ""), line)
def assert_passes(self, path: str, text: str) -> None:
self.edit(path, text)
result = self.run_checker()
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_the_copy_passes_before_it_is_broken(self) -> None:
result = self.run_checker()
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_a_path_the_copy_reads_fails(self) -> None:
deleted = self.DELETED
for text in (
f"\n`{deleted}`\n", f"\n`{deleted}:12`\n", f"\n`{deleted}#L3`\n",
f"\n`corepack pnpm exec vitest run {deleted}`\n",
# A `--flag=` prefix and quotes around a command word (verify-documentation-readiness.ts commandPaths).
f'\n`vitest run "{deleted}"`\n', f"\n`vitest run --dir={deleted}`\n",
f"\n`CI=true node scripts/run-vitest.ts run '{deleted}'`\n",
f"\n`scripts/verify.sh exec -- vitest run {deleted}`\n",
f"\n```bash\nvitest run {deleted}\n```\n",
f"\n```bash\nnode scripts/run-vitest.ts run '{deleted}'\n```\n",
f'\n```\n$ vitest run "{deleted}"\n```\n',
f"\n[x](../../../{deleted})\n",
# A link whose text runs onto the next line (the copy reads links in the whole text).
f"\n[the drill's\ncopy](../../../{deleted})\n",
):
with self.case(text=text):
self.assert_fails_at(self.DECISIONS, text)
def test_a_name_the_copy_does_not_read_as_a_path_passes(self) -> None:
deleted = self.DELETED
for path, text in (
(self.DECISIONS, "\n`tests/unit/`의 `ci-workflow-generation.test.ts`\n"),
# A span with a space that is not a command, a word after `echo`, a block that is not a shell block.
(self.DECISIONS, f"\n`see {deleted}`\n"),
(self.DECISIONS, f"\n```bash\necho {deleted}\n```\n"),
(self.DECISIONS, f"\n```ts\nvitest run {deleted}\n```\n"),
# The history holders, the records, the route reviews and what the drill does not copy.
("docs/work/evidence.md", f"\n`{deleted}`\n"),
("docs/history/old.md", f"\n`{deleted}`\n"),
("docs/reviews/old-review.md", f"\n`{deleted}`\n"),
("docs/adr/0000-old.md", f"\n`{deleted}`\n"),
("docs/accessibility/route-reviews/home.md", f"\n`{deleted}`\n"),
(".claude/rules/tests.md", f"\n`{deleted}`\n"),
):
with self.case(path=path, text=text):
self.assert_passes(path, text)
def test_every_document_the_drill_copies_is_read(self) -> None:
# src and scripts come by fixture-copy, the root README and docs by fixture-documents; INVENTORY is the
# one living file in the review records.
for path in ("src/adapters/AGENTS.md", "scripts/hooks/README.md", "README.md", "docs/README.md",
"docs/reviews/adapters/INVENTORY.md"):
with self.case(path=path):
self.assert_fails_at(path, f"\n`{self.DELETED}`\n")
def test_a_path_beside_the_document_is_read(self) -> None:
# namedPath: a path whose first folder is beside the document is read from there.
start = self.edit("tests/README.md", "\n`unit/ci-workflow-generation.test.ts`\n")
result = self.run_checker()
self.assertIn(f"tests/README.md:{start + 1}: '{self.DELETED}'", result.stderr, result.stdout + result.stderr)
def test_a_path_the_layout_selects_by_set_paths_is_copied(self) -> None:
layout = json.loads((self.root / "config/repository-layout.json").read_text(encoding="utf-8"))
entry = next(entry for entry in layout["entries"] if entry["path"] == "scripts")
entry["sets"] = [name for name in entry["sets"] if name != "fixture-copy"]
entry["setPaths"] = {**entry.get("setPaths", {}), "fixture-copy": ["scripts/hooks"]}
self.edit("config/repository-layout.json", "")
(self.root / "config/repository-layout.json").write_text(json.dumps(layout), encoding="utf-8")
self.assert_passes("scripts/notes.md", f"\n`{self.DELETED}`\n")
self.assert_fails_at("scripts/hooks/README.md", f"\n`{self.DELETED}`\n")
def test_a_record_head_block_path_the_copy_reads_fails(self) -> None:
# docs-system.ts checkHead: the copy knows only the files it holds.
for path, label in (("docs/design/drill-head.md", "설계서"), ("docs/adr/0000-drill-head.md", "결정 기록")):
for field in ("현재 정본", "대체", "대체됨"):
with self.case(path=path, field=field):
self.assert_fails_at(path, "\n".join([
HEAD_START, label, "- 상태: 채택", "- 작성일: 2026-11-21", "- 요약: 드릴 시험이다.",
f"- {field}: `{self.DELETED}`", HEAD_END, "", f"본문의 `{self.DELETED}`는 읽지 않는다.", ""]))
def test_the_drill_is_the_one_its_package_script_runs(self) -> None:
moved = "scripts/drills/sample-removal.ts"
(self.root / moved).parent.mkdir(parents=True)
(self.root / "scripts/test-sample-removal.ts").rename(self.root / moved)
package = json.loads((self.root / "package.json").read_text(encoding="utf-8"))
script = package["scripts"]["test:sample-removal"]
package["scripts"]["test:sample-removal"] = script.replace("scripts/test-sample-removal.ts", moved)
(self.root / "package.json").write_text(json.dumps(package), encoding="utf-8")
self.assert_fails_at(self.DECISIONS, f"\n`{self.DELETED}`\n")
package["scripts"]["test:sample-removal"] = "node scripts/missing-drill.ts"
(self.root / "package.json").write_text(json.dumps(package), encoding="utf-8")
self.assertIn("`test:sample-removal` runs no drill file", self.run_checker().stderr)
del package["scripts"]["test:sample-removal"]
(self.root / "package.json").write_text(json.dumps(package), encoding="utf-8")
self.assert_passes(self.DECISIONS, f"\n`{self.DELETED}`\n")
def test_a_drill_whose_list_cannot_be_read_fails(self) -> None:
drill = self.root / "scripts/test-sample-removal.ts"
original = drill.read_text(encoding="utf-8")
for old, new, message in (
("for (const excludedFixtureTest of [", "for ([", "the list of files the drill deletes from its copy was not found"),
(' "tests/unit/removal-fixture.test.ts",\n', " ...EXTRA_TESTS,\n", "holds more than double-quoted paths"),
(' "tests/unit/removal-fixture.test.ts",\n', " 'tests/unit/removal-fixture.test.ts',\n",
"holds more than double-quoted paths"),
):
with self.subTest(new=new):
self.assertIn(old, original)
drill.write_text(original.replace(old, new), encoding="utf-8")
self.assertIn(message, self.run_checker().stderr)
class TypeScriptRulesTest(unittest.TestCase):
"""check-work-docs.py repeats in Python what the drill's copy reads in TypeScript (its section on the removal
drill's copy). This reads that TypeScript: a list or a rule changed on one side only fails here."""
DOCS = "scripts/lib/docs-system.ts"
READINESS = "scripts/verify-documentation-readiness.ts"
def test_the_lists_are_the_same(self) -> None:
kinds = re.findall(r'\["([^"]+)", "[^"]+"\]', ts_declaration(self.DOCS, "RECORD_KINDS"))
for name, typescript_value, python_value in (
("RECORD_FOLDERS", ts_strings(self.DOCS, "RECORD_FOLDERS"), list(check.RECORD_FOLDERS)),
("DECISION_FOLDER", ts_strings(self.DOCS, "DECISION_FOLDER"), [check.DECISION_FOLDER]),
("LIVING_IN_RECORDS", set(ts_strings(self.DOCS, "LIVING_IN_RECORDS")), set(check.LIVING_IN_RECORDS)),
("HISTORY_HOLDERS", set(ts_strings(self.DOCS, "HISTORY_HOLDERS")), set(check.HISTORY_HOLDERS)),
("NOT_DOCUMENT", ts_declaration(self.DOCS, "NOT_DOCUMENT"), f"/{check.NOT_DOCUMENT.pattern}/u"),
("RECORD_KINDS", kinds, list(check.RECORD_KINDS)),
("HEAD_START", HEAD_START, check.HEAD_START),
("HEAD_END", HEAD_END, check.HEAD_END),
("HEAD_SEARCH_LINES", ts_declaration(self.DOCS, "HEAD_SEARCH_LINES"), str(check.HEAD_SEARCH_LINES)),
("HEAD_FIELDS", check.HEAD_CANONICAL in ts_strings(self.DOCS, "HEAD_FIELDS"), True),
("HEAD_OPTIONAL", ts_strings(self.DOCS, "HEAD_OPTIONAL"), list(check.HEAD_OPTIONAL)),
("COMMAND_HEADS", set(ts_strings(self.READINESS, "COMMAND_HEADS")), set(check.COMMAND_HEADS)),
("DOCUMENT_INDEX", ts_strings(self.READINESS, "DOCUMENT_INDEX"), [check.DOCUMENT_INDEX]),
("copied sets", re.findall(r'selectRepositoryPaths\("([^"]+)"\)', typescript("scripts/lib/removal-fixture.ts")),
list(check.COPIED_SETS)),
):
with self.subTest(name=name):
self.assertEqual(typescript_value, python_value)
def test_the_rules_are_written_as_the_checker_repeats_them(self) -> None:
c = check
for path, fragment in (
("scripts/test-sample-removal.ts", "await prepareRemovalFixture(fixtureRoot, [ ...REMOVAL_FIXTURE_COPY_TARGETS,"
" ...REMOVAL_FIXTURE_DOCUMENT_TARGETS, ]);"),
("scripts/test-sample-removal.ts", "for (const excludedFixtureTest of ["),
("scripts/test-sample-removal.ts", "await rm(path.join(fixtureRoot, excludedFixtureTest), { force: true });"),
("scripts/lib/repository-layout.ts", "entry.sets.includes(set) ? [entry.path] : [...(entry.setPaths[set] ?? [])],"),
("scripts/lib/removal-fixture.ts", "await cp(target, path.join(root, target), { recursive: true });"),
(self.DOCS, "return LIVING_IN_RECORDS.has(path) || !RECORD_FOLDERS.some((folder) => path.startsWith(folder));"),
(self.DOCS, "return isLiving(path) && !path.startsWith(DECISION_FOLDER) && !HISTORY_HOLDERS.has(path);"),
(self.DOCS, 'return treeFiles(root).filter((path) => path.endsWith(".md") && !NOT_DOCUMENT.test(path)'
" && checkedForDrift(path));"),
(self.DOCS, '.filter((path) => path.endsWith(".md") && !NOT_DOCUMENT.test(path))'),
(self.DOCS, "return RECORD_KINDS.find(([prefix]) => path.startsWith(prefix))?.[1] ?? null;"),
(self.DOCS, "const end = lines.slice(0, HEAD_SEARCH_LINES).indexOf(HEAD_END);"),
(self.DOCS, "if (lines[0] !== HEAD_START || end < 0) {"),
(self.DOCS, "const block = lines.slice(1, end);"),
(self.DOCS, "block.slice(1).forEach((line, offset) => {"),
(self.DOCS, f"const match = /{c.HEAD_FIELD.pattern}/u.exec(line);"),
(self.DOCS, "else if (fields.has(name)) fail(`field given twice: ${name}`, at);"),
(self.DOCS, f'const canonical = fields.get("{check.HEAD_CANONICAL}");'),
(self.DOCS, "const targets = backtickedPaths(canonical[0]);"),
(self.DOCS, "for (const name of HEAD_OPTIONAL) {"),
(self.DOCS, "const targets = backtickedPaths(field[0]);"),
(self.DOCS, f'return [...value.matchAll(/{c.HEAD_PATH.pattern}/gu)].map(([, path = ""]) => path);'),
(self.DOCS, 'return facts.knownPaths.has(normalize(path).replace(/\\/$/u, ""));'),
(self.READINESS, "const UNCHECKED_DOCUMENTS = HISTORY_HOLDERS;"),
(self.READINESS, f'for (const [, target = ""] of (index.match(/{c.INDEX_SECTION.pattern}/mu)?.[0] ?? "")'
f".matchAll(/{c.INDEX_LINK.pattern}/gu)) {{"),
(self.READINESS, "const linked = normalize(join(dirname(DOCUMENT_INDEX), target));"),
(self.READINESS, 'entries === null ? [linked] : entries.filter((name) => name.endsWith(".md"))'
".map((name) => join(linked, name));"),
(self.READINESS, "for (const document of livingDocuments(process.cwd())) {"),
(self.READINESS, "const documentsSystem = checkDocsSystem(process.cwd(), rootDirectory);"),
(self.READINESS, f'...[...text.matchAll(/{c.SPAN.pattern}/gu)].flatMap(([, token = ""]) => [ namedPath(token,'
" document), ...commandPaths(token, document), ]),"),
(self.READINESS, "...fencedCommands(text).flatMap((command) => commandPaths(command, document)),"),
(self.READINESS, f'...[...text.matchAll(/{c.DOCUMENT_LINK.pattern}/gu)].map(([, target = ""]) =>'
" linkedPath(target, document)),"),
(self.READINESS, f'const candidate = token.replace(/{c.ANCHOR.pattern}/u, "")'
f'.replace(/{c.LINE_NUMBER.pattern}/u, "");'),
(self.READINESS, f'if (!candidate.includes("/") || candidate.startsWith("/") || /{c.NOT_A_PATH.pattern}/u'
".test(candidate)) return null;"),
(self.READINESS, "if (topLevelEntries.has(first)) return candidate;"),
(self.READINESS, "if (pairedPins.has(first)) return `../${candidate}`;"),
(self.READINESS, 'return first !== "." && first !== ".." && exists(join(dirname(document), first))'
" ? join(dirname(document), candidate) : null;"),
(self.READINESS, f"if (/{c.OUTSIDE_LINK.pattern}/iu.test(target)) return null;"),
(self.READINESS, f'return normalize(join(dirname(document), target.replace(/{c.ANCHOR.pattern}/u, "")));'),
(self.READINESS, f"const VERIFY_ENTRY = /{c.VERIFY_ENTRY.pattern}/u;"),
(self.READINESS, f'const words = command.trim().replace(/{c.PROMPT.pattern}/u, "").split(/\\s+/u);'),
(self.READINESS, f'while (/{c.ASSIGNMENT.pattern}/u.test(words[head] ?? "")) head += 1;'),
(self.READINESS, 'const separator = words.indexOf("--", head + 1);'),
(self.READINESS, 'const executed = words[head + 1] === "exec" && separator > head ?'
' words.slice(separator + 1).join(" ") : "";'),
(self.READINESS, 'return [namedPath(first, document), ...(executed === "" ? [] : commandPaths(executed, document))];'),
(self.READINESS, "if (!COMMAND_HEADS.has(first)) return [];"),
(self.READINESS, f'.slice(head + 1) .map((word) => namedPath(word.replace(/{c.FLAG.pattern}/u, "")'
f'.replace(/{c.QUOTES.pattern}/gu, ""), document));'),
(self.READINESS, f"const marker = /{c.FENCE.pattern}/u.exec(line);"),
(self.READINESS, 'fence = fence === null ? (marker[1] ?? "") : null;'),
(self.READINESS, f"if (fence !== null && /{c.SHELL_FENCE.pattern}/u.test(fence)) commands.push(line);"),
):
with self.subTest(path=path, fragment=fragment):
self.assertIn(" ".join(fragment.split()), " ".join(typescript(path).split()))
if __name__ == "__main__":
unittest.main()