f04ea3b3이 경로·명령 판정 함수를 scripts/lib/documentation-readiness- checks.ts로 옮기고 facts 인자를 붙였다. 그런데 scripts/tests/ test_check_work_docs.py의 TypeScriptRulesTest는 그 코드 조각과 COMMAND_HEADS를 여전히 verify-documentation-readiness.ts에서 찾아 `scripts/verify.sh hooks`의 시험 둘(조각 21개)이 실패한다. CI는 이 단계를 돌리지 않아 merge 게이트로는 안 잡힌다. 문서 넷도 옛 위치를 가리킨다: 매뉴얼 03 7단계의 NOT_CREATED, docs/README.md· docs/work/reference/gates.md·docs/operations/ci-quality-gates.md의 문서 검사 코드 정본. - TypeScriptRulesTest: 옮긴 조각과 COMMAND_HEADS를 새 모듈에서 찾고, facts 인자가 붙은 꼴(`facts.topLevelEntries`, `facts.exists`, `namedPath(…, document, facts)`)로 고친다. 그대로 남은 조각(색인 절, livingDocuments, checkDocsSystem 호출)은 script에서 찾는다. - 문서 넷이 새 모듈을 가리키게 한다. - documentation-readiness-checks.test.ts에 거절 사례를 더한다: 앞붙임(`CI=true VERIFY_SNAPSHOT=1 node …`) 뒤의 없는 경로와 `--out=<없는 경로>`. 앞붙임 사례가 통과 쪽에만 있어 `while (…) head += 1;`을 지워도, `--flag=` 벗기기를 지워도 시험이 다 통과했다. 지운 자식 프로세스 시험이 잡던 앞의 변이를 다시 잡는다. 버린 안: TypeScriptRulesTest에서 조각 대조를 빼기 — Python 쪽 검사 (check-work-docs.py)가 TypeScript 규칙과 같은지 보는 유일한 시험이다. 위험·한계: scripts/check-work-docs.py:167 주석도 옛 script만 적지만 이 항목 범위 밖 파일이라 두었다(PR memo). 검증: python3 -m unittest scripts.tests.test_check_work_docs OK, scripts/verify.sh hooks rc=0(91개), scripts/verify.sh docs rc=0. 노트북 node 탐침으로 새 거절 사례가 통과하고, 변이 둘(`while` 줄 삭제, `--flag=` 벗기기 삭제)이 각각 실패. vitest와 RED는 PR의 desktop 묶음에서 돈다. Refs: REV-FE-0011, REV-FE-0022
421 lines
25 KiB
Python
421 lines
25 KiB
Python
"""scripts/check-work-docs.py의 시험. 이 repo의 작업 매뉴얼이 통과하고, 고장 낸 사본이 실패하는지 본다.
|
|
|
|
python3 -m unittest discover -s scripts/tests
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import importlib.util
|
|
import json
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
SCRIPTS = Path(__file__).resolve().parent.parent
|
|
REPO = SCRIPTS.parent
|
|
CHECKER = SCRIPTS / "check-work-docs.py"
|
|
_spec = importlib.util.spec_from_file_location("check_work_docs", CHECKER)
|
|
check = importlib.util.module_from_spec(_spec)
|
|
_spec.loader.exec_module(check)
|
|
|
|
|
|
def history(line: str) -> tuple[str, str] | None:
|
|
return check.history_match(line, "")
|
|
|
|
|
|
class HistoryPatternTest(unittest.TestCase):
|
|
def test_this_repository_history_ids_are_caught(self) -> None:
|
|
for line in ("1103/11-07처럼 고쳤다", "1105 README 11.4절", "1103 조치의 고침", "결함 패턴 P-43",
|
|
"0925 라운드 D-14", "소유자 O-12", "4라운드 리뷰", "결정 D8을 따른다", "리뷰 12-03에서",
|
|
"(05-01, 04-01)", "커밋 ad3a071f"):
|
|
with self.subTest(line=line):
|
|
self.assertIsNotNone(history(line))
|
|
|
|
def test_ordinary_sentences_are_not_history(self) -> None:
|
|
for line in ("FE-GATE-013은 desktop에서 실패한다", "소유자 결정 2026-11-05", "P1과 P0~P3", "M0~M4, E0~E4",
|
|
"결정 대기로 남긴다", "Node 24.14.0", "결함 패턴 G13", "세 라운드를 더", "3라운드마다",
|
|
"`MMDD/NN-MM` 꼴", "초기 JS 206,848 B", "a11y·e2e", "9~15분"):
|
|
with self.subTest(line=line):
|
|
self.assertIsNone(history(line))
|
|
|
|
|
|
class RepositoryManualTest(unittest.TestCase):
|
|
def test_the_manual_in_this_repository_passes(self) -> None:
|
|
result = subprocess.run([sys.executable, str(CHECKER)], capture_output=True, text=True, timeout=30)
|
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
|
|
|
|
|
class BrokenCopyTest(unittest.TestCase):
|
|
"""A copy of the manual with one thing broken at a time; the checker in the copy must fail on it."""
|
|
|
|
def setUp(self) -> None:
|
|
self._directory = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self._directory.cleanup)
|
|
self.root = Path(self._directory.name)
|
|
for path in ("AGENTS.md", "CLAUDE.md", "docs/work", ".claude/rules", ".claude/skills", ".claude/agents"):
|
|
source = REPO / path
|
|
target = self.root / path
|
|
if not source.exists():
|
|
continue
|
|
if source.is_dir():
|
|
shutil.copytree(source, target)
|
|
else:
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copy(source, target)
|
|
(self.root / "scripts").mkdir()
|
|
shutil.copy(CHECKER, self.root / "scripts/check-work-docs.py")
|
|
|
|
def run_checker(self) -> subprocess.CompletedProcess:
|
|
return subprocess.run([sys.executable, str(self.root / "scripts/check-work-docs.py")], capture_output=True,
|
|
text=True, timeout=30)
|
|
|
|
def append(self, path: str, text: str) -> None:
|
|
with (self.root / path).open("a", encoding="utf-8") as handle:
|
|
handle.write(text)
|
|
|
|
def test_the_copy_passes_before_it_is_broken(self) -> None:
|
|
self.assertEqual(self.run_checker().returncode, 0)
|
|
|
|
def test_a_long_map_fails(self) -> None:
|
|
self.append("AGENTS.md", "\n" * 10)
|
|
self.assertIn("AGENTS.md: ", self.run_checker().stderr)
|
|
|
|
def test_claude_md_must_start_with_the_import(self) -> None:
|
|
text = (self.root / "CLAUDE.md").read_text(encoding="utf-8")
|
|
(self.root / "CLAUDE.md").write_text("# CLAUDE.md\n" + text, encoding="utf-8")
|
|
self.assertIn("the first line must be '@AGENTS.md'", self.run_checker().stderr)
|
|
|
|
def test_a_history_id_in_a_playbook_or_rule_fails_but_not_in_the_evidence(self) -> None:
|
|
self.append("docs/work/evidence.md", "\n1103/11-07\n")
|
|
self.assertEqual(self.run_checker().returncode, 0)
|
|
for path in ("docs/work/improve.md", ".claude/rules/tests.md", "docs/work/reference/gates.md"):
|
|
with self.subTest(path=path):
|
|
original = (self.root / path).read_text(encoding="utf-8")
|
|
self.append(path, "\n고친 방법은 1105/12-04와 같다.\n")
|
|
self.assertIn(f"{path}:", self.run_checker().stderr)
|
|
(self.root / path).write_text(original, encoding="utf-8")
|
|
|
|
def test_a_playbook_without_the_skeleton_fails(self) -> None:
|
|
path = self.root / "docs/work/operate.md"
|
|
path.write_text(path.read_text(encoding="utf-8").replace("## 6. 하지 말 것", "## 6. 금지"), encoding="utf-8")
|
|
self.assertIn("sections must be exactly", self.run_checker().stderr)
|
|
|
|
def test_a_broken_relative_link_fails(self) -> None:
|
|
self.append("docs/work/README.md", "\n[x](missing.md)\n")
|
|
self.assertIn("broken relative link 'missing.md'", self.run_checker().stderr)
|
|
|
|
def test_a_folder_rule_book_needs_its_import_beside_it_and_no_history(self) -> None:
|
|
guide = self.root / "src/adapters/AGENTS.md"
|
|
guide.parent.mkdir(parents=True)
|
|
guide.write_text("# AGENTS.md\n\n- 규칙\n", encoding="utf-8")
|
|
self.assertIn("src/adapters/CLAUDE.md: missing", self.run_checker().stderr)
|
|
(self.root / "src/adapters/CLAUDE.md").write_text("@AGENTS.md\n", encoding="utf-8")
|
|
self.assertEqual(self.run_checker().returncode, 0)
|
|
(self.root / "src/adapters/CLAUDE.md").write_text("@AGENTS.md\n- 둘째 규칙\n", encoding="utf-8")
|
|
self.assertIn("must be exactly '@AGENTS.md'", self.run_checker().stderr)
|
|
(self.root / "src/adapters/CLAUDE.md").write_text("@AGENTS.md\n", encoding="utf-8")
|
|
guide.write_text("# AGENTS.md\n\n- 1105/12-04처럼 고친다\n", encoding="utf-8")
|
|
self.assertIn("src/adapters/AGENTS.md:3:", self.run_checker().stderr)
|
|
|
|
def test_a_missing_reference_fails(self) -> None:
|
|
(self.root / "docs/work/reference/testing.md").unlink()
|
|
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 (documentation-readiness-checks.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"
|
|
CHECKS = "scripts/lib/documentation-readiness-checks.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.CHECKS, "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.CHECKS, f'...[...text.matchAll(/{c.SPAN.pattern}/gu)].flatMap(([, token = ""]) => [ namedPath(token,'
|
|
" document, facts), ...commandPaths(token, document, facts), ]),"),
|
|
(self.CHECKS, "...fencedCommands(text).flatMap((command) => commandPaths(command, document, facts)),"),
|
|
(self.CHECKS, f'...[...text.matchAll(/{c.DOCUMENT_LINK.pattern}/gu)].map(([, target = ""]) =>'
|
|
" linkedPath(target, document)),"),
|
|
(self.CHECKS, f'const candidate = token.replace(/{c.ANCHOR.pattern}/u, "")'
|
|
f'.replace(/{c.LINE_NUMBER.pattern}/u, "");'),
|
|
(self.CHECKS, f'if (!candidate.includes("/") || candidate.startsWith("/") || /{c.NOT_A_PATH.pattern}/u'
|
|
".test(candidate)) return null;"),
|
|
(self.CHECKS, "if (facts.topLevelEntries.has(first)) return candidate;"),
|
|
(self.CHECKS, "if (facts.pairedRepositories.has(first)) return `../${candidate}`;"),
|
|
(self.CHECKS, 'return first !== "." && first !== ".." && facts.exists(join(dirname(document), first))'
|
|
" ? join(dirname(document), candidate) : null;"),
|
|
(self.CHECKS, f"if (/{c.OUTSIDE_LINK.pattern}/iu.test(target)) return null;"),
|
|
(self.CHECKS, f'return normalize(join(dirname(document), target.replace(/{c.ANCHOR.pattern}/u, "")));'),
|
|
(self.CHECKS, f"const VERIFY_ENTRY = /{c.VERIFY_ENTRY.pattern}/u;"),
|
|
(self.CHECKS, f'const words = command.trim().replace(/{c.PROMPT.pattern}/u, "").split(/\\s+/u);'),
|
|
(self.CHECKS, f'while (/{c.ASSIGNMENT.pattern}/u.test(words[head] ?? "")) head += 1;'),
|
|
(self.CHECKS, 'const separator = words.indexOf("--", head + 1);'),
|
|
(self.CHECKS, 'const executed = words[head + 1] === "exec" && separator > head ?'
|
|
' words.slice(separator + 1).join(" ") : "";'),
|
|
(self.CHECKS, 'return [namedPath(first, document, facts), ...(executed === "" ? [] :'
|
|
' commandPaths(executed, document, facts))];'),
|
|
(self.CHECKS, "if (!COMMAND_HEADS.has(first)) return [];"),
|
|
(self.CHECKS, f'.slice(head + 1) .map((word) => namedPath(word.replace(/{c.FLAG.pattern}/u, "")'
|
|
f'.replace(/{c.QUOTES.pattern}/gu, ""), document, facts));'),
|
|
(self.CHECKS, f"const marker = /{c.FENCE.pattern}/u.exec(line);"),
|
|
(self.CHECKS, 'fence = fence === null ? (marker[1] ?? "") : null;'),
|
|
(self.CHECKS, 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()
|