thuthi-plugin 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/.claude-plugin/marketplace.json +55 -0
  2. package/README.md +13 -2
  3. package/bin/parallel-browser.js +109 -0
  4. package/extension/background.js +1329 -0
  5. package/extension/config.json +1 -0
  6. package/extension/guard.js +44 -0
  7. package/extension/manifest.json +10 -0
  8. package/extension/overlay.js +104 -0
  9. package/extension/popup.html +34 -0
  10. package/extension/popup.js +39 -0
  11. package/extension-reloader/manifest.json +13 -0
  12. package/extension-reloader/sw.js +17 -0
  13. package/package.json +13 -4
  14. package/plugins/thuthi/.claude-plugin/plugin.json +8 -0
  15. package/plugins/thuthi/context.md +3 -0
  16. package/plugins/thuthi/hooks/hooks.json +15 -0
  17. package/plugins/thuthi/skills/setup/SKILL.md +55 -0
  18. package/plugins/thuthi/skills/setup/scripts/doctor.py +249 -0
  19. package/plugins/thuthi/skills/setup/scripts/selftest.py +188 -0
  20. package/plugins/thuthi/tools/claude-switch/claude_switch.py +8 -0
  21. package/plugins/thuthi/tools/legacy_launcher.py +65 -0
  22. package/plugins/thuthi/tools/statusline/statusline.py +8 -0
  23. package/plugins/thuthi-accounts/.claude-plugin/plugin.json +9 -0
  24. package/plugins/thuthi-accounts/bin/claude-switch +5 -0
  25. package/plugins/thuthi-accounts/bin/claude-switch.cmd +4 -0
  26. package/plugins/thuthi-accounts/hooks/hooks.json +15 -0
  27. package/plugins/thuthi-accounts/lib/tls.py +68 -0
  28. package/plugins/thuthi-accounts/lib/usage_store.py +150 -0
  29. package/plugins/thuthi-accounts/setup_check.py +21 -0
  30. package/plugins/thuthi-accounts/skills/claude-switch/SKILL.md +48 -0
  31. package/plugins/thuthi-accounts/tools/claude-switch/claude-switch-tui.py +397 -0
  32. package/plugins/thuthi-accounts/tools/claude-switch/claude_switch.py +1204 -0
  33. package/plugins/thuthi-accounts/tools/claude-switch/credstore.py +417 -0
  34. package/plugins/thuthi-accounts/tools/claude-switch/install.py +301 -0
  35. package/plugins/thuthi-accounts/tools/claude-switch/tests/selftest.py +491 -0
  36. package/plugins/thuthi-accounts/tools/statusline/statusline.py +212 -0
  37. package/plugins/thuthi-agenda-picker/.claude-plugin/plugin.json +9 -0
  38. package/plugins/thuthi-agenda-picker/context.md +3 -0
  39. package/plugins/thuthi-agenda-picker/hooks/hooks.json +15 -0
  40. package/plugins/thuthi-agenda-picker/lib/pbpage.py +397 -0
  41. package/plugins/thuthi-agenda-picker/setup_check.py +18 -0
  42. package/plugins/thuthi-agenda-picker/skills/agenda-picker/SKILL.md +280 -0
  43. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/design-rules.md +110 -0
  44. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/diagram/base.css +33 -0
  45. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/agenda.json +146 -0
  46. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-dark.svg +5 -0
  47. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-light.svg +5 -0
  48. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-dark.svg +5 -0
  49. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-light.svg +5 -0
  50. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-dark.svg +5 -0
  51. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-light.svg +5 -0
  52. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/base.css +33 -0
  53. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/name-B.html +15 -0
  54. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-dark.svg +5 -0
  55. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-light.svg +5 -0
  56. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/picker.py +1286 -0
  57. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/selftest.py +771 -0
  58. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/shot.py +117 -0
  59. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/template.html +1029 -0
  60. package/plugins/thuthi-arch-diagram/.claude-plugin/plugin.json +9 -0
  61. package/plugins/thuthi-arch-diagram/lib/pbpage.py +397 -0
  62. package/plugins/thuthi-arch-diagram/lib/tls.py +68 -0
  63. package/plugins/thuthi-arch-diagram/setup_check.py +10 -0
  64. package/plugins/thuthi-arch-diagram/skills/arch-diagram/SKILL.md +125 -0
  65. package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/design-rules.md +110 -0
  66. package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/example-shop.py +167 -0
  67. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/check.py +194 -0
  68. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/diagramkit.py +682 -0
  69. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/interact_test.py +115 -0
  70. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/render.py +113 -0
  71. package/plugins/thuthi-browser/.claude-plugin/plugin.json +9 -0
  72. package/plugins/thuthi-browser/context.md +3 -0
  73. package/plugins/thuthi-browser/hooks/hooks.json +15 -0
  74. package/plugins/thuthi-browser/lib/pbpage.py +397 -0
  75. package/plugins/thuthi-browser/setup_check.py +93 -0
  76. package/plugins/thuthi-browser/skills/parallel-browser/SKILL.md +271 -0
  77. package/plugins/thuthi-browser/skills/parallel-browser/references/api.md +243 -0
  78. package/plugins/thuthi-browser/skills/parallel-browser/references/install.md +106 -0
  79. package/plugins/thuthi-demo-video/.claude-plugin/plugin.json +9 -0
  80. package/plugins/thuthi-demo-video/lib/pbpage.py +397 -0
  81. package/plugins/thuthi-demo-video/setup_check.py +14 -0
  82. package/plugins/thuthi-demo-video/skills/demo-video/SKILL.md +261 -0
  83. package/plugins/thuthi-demo-video/skills/demo-video/scripts/caption.html +16 -0
  84. package/plugins/thuthi-demo-video/skills/demo-video/scripts/cursor.js +132 -0
  85. package/plugins/thuthi-demo-video/skills/demo-video/scripts/demo_video.py +2416 -0
  86. package/plugins/thuthi-demo-video/skills/demo-video/scripts/example_scenario.py +97 -0
  87. package/plugins/thuthi-demo-video/skills/demo-video/scripts/frame.html +95 -0
  88. package/plugins/thuthi-demo-video/skills/demo-video/scripts/overlay.js +129 -0
  89. package/plugins/thuthi-demo-video/skills/demo-video/scripts/title.html +30 -0
  90. package/plugins/thuthi-no-more-slop/.claude-plugin/plugin.json +9 -0
  91. package/plugins/thuthi-no-more-slop/setup_check.py +10 -0
  92. package/plugins/thuthi-no-more-slop/skills/no-more-slop/LICENSE +21 -0
  93. package/plugins/thuthi-no-more-slop/skills/no-more-slop/SKILL.md +235 -0
  94. package/plugins/thuthi-no-more-slop/skills/no-more-slop/SOURCE.txt +1 -0
  95. package/plugins/thuthi-no-more-slop/skills/no-more-slop/agents/openai.yaml +6 -0
  96. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/examples.md +289 -0
  97. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/tokens.md +46 -0
  98. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/unslop-fallback.md +36 -0
  99. package/plugins/thuthi-no-more-slop/skills/no-more-slop/scripts/count_tells.py +426 -0
  100. package/plugins/thuthi-orca/.claude-plugin/plugin.json +9 -0
  101. package/plugins/thuthi-orca/context.md +5 -0
  102. package/plugins/thuthi-orca/hooks/hooks.json +18 -0
  103. package/plugins/thuthi-orca/hooks/orca-team-grid.ts +21 -0
  104. package/plugins/thuthi-orca/setup_check.py +12 -0
  105. package/plugins/thuthi-orca/skills/orca-new-work/SKILL.md +492 -0
  106. package/plugins/thuthi-orca/tools/orca-team-grid/bin/tmux +338 -0
  107. package/plugins/thuthi-orca/tools/orca-team-grid/tests/selftest.py +299 -0
  108. package/runtime/client.js +69 -0
  109. package/runtime/daemon.js +503 -0
  110. package/runtime/focus-monitor.js +53 -0
  111. package/runtime/keys.js +86 -0
  112. package/runtime/owner.js +64 -0
  113. package/runtime/recorder.js +267 -0
  114. package/runtime/relay.js +95 -0
  115. package/runtime/session.js +1599 -0
@@ -0,0 +1,110 @@
1
+ # 디자인 규칙 — arch-diagram 이 따르는 것
2
+
3
+ `scripts/diagramkit.py` 가 아래 값과 규칙을 코드로 들고 있다. 이 문서는 "왜 그렇게 그리는가"를 사람이 읽는 판이다. 기본 스타일은 **타일 스타일**이다: 모눈 바탕 위에 공식 로고 타일, 색 묶음, 직각 선, 번호 매긴 흐름, 명령 칩 (github.com/caru-ini/stack-diagram 의 결을 따르고 2026-11-02 사용자가 승인한 aidu-test 구조도에서 굳혔다). 옛 에디토리얼 스타일(`node` · `zone` · `hline` …, `svg(grid=False)`, `build_page(theme='paper')`)도 그대로 돌지만 새 그림에는 쓰지 않는다. 한글 · 팝업 · 호버 · 문체 규칙은 두 스타일에 같다.
4
+
5
+ ## 1. 토큰 (밝은 화면만, 어두운 모드 없음)
6
+
7
+ | 역할 | 값 | 쓰임 |
8
+ |---|---|---|
9
+ | 바탕 | `#f8fafc` + 48px 모눈 `#e5e7eb` | `svg(..., grid=True)` 가 깐다 |
10
+ | 타일 | 흰색, 테두리 `#d4d4d8` 1.5px, 반지름 14, 옅은 그림자 | 컴포넌트 하나 |
11
+ | 이름 · 보조줄 | `#18181b` 19px 700 산세리프 · `#71717a` 13.5px 모노 | 타일 아래 두 줄 |
12
+ | 주 흐름 선 | `#1d74f5` | 요청이 지나가는 길, 번호 ①②③ |
13
+ | 내부 · 보조 선 | `#52525b` | 조회 · 저장 같은 곁가지 |
14
+ | 외부 · 흐름 밖 선 | `#b45309` 점선 | 외부 서비스, 사람 손 단계, 비동기 되돌림 |
15
+ | 칩 | `#f4f4f5` 바탕, `#d4d4d8` 테두리, 굵은 모노 14px | 명령 · 스킬 이름 |
16
+
17
+ 선 색은 이 셋만 쓴다. 강조가 더 필요하면 타일 `tint` (옅은 색 바탕) 를 1~2곳에.
18
+
19
+ ## 2. 타일 · 묶음 · 칩
20
+
21
+ **타일** (`tile(x, y, name, sub, logo_spec=…, icon_kind=…)`): 100px 정사각 안에 그 컴포넌트의 **공식 로고**, 아래에 굵은 이름과 회색 모노 보조줄(경로 · 기술 · 한 마디 역할).
22
+
23
+ - 로고는 `logo_spec='react'` (devicon) · `'si:stripe'` (simple-icons, 브랜드 색 그대로) · 로컬 `.svg/.png` 경로. 처음 한 번 받아 `~/.cache/thuthi-arch-diagram/logos` (Windows `%LOCALAPPDATA%`) 에 두고 `data:image/svg+xml;base64` 로 박는다. **로고 색을 바꾸지 않는다.** 회사 TLS 검사 아래에서도 받도록 `lib/tls.py` (키체인 · `NODE_EXTRA_CA_CERTS`) 를 쓴다.
24
+ - 로고가 없거나 못 받으면 선 아이콘 (`icon_kind`): `person` `users` `server` `robot` `laptop` `studio` `window` `folder` `file` `film` `database` `queue` `globe` `cloud` `mail` `card` `box` `gear` `terminal` `lock` `bell` `phone` `clock` `list`. 받기 실패는 WARN 을 찍고 이 아이콘으로 그린다.
25
+ - **사람과 기계를 한눈에 가른다.** 사람은 `person` 아이콘 타일, 서버 · 프로세스는 `server`, 프로그램 · 에이전트는 로고 또는 `robot`. 로고 타일이 사람인지 기계인지 헷갈리면 `badge_kind='server'|'robot'|'person'` 으로 오른쪽 위에 작은 뱃지를 단다.
26
+ - 같은 상자를 여러 번 그리지 않는다. 워커 3개, 테스터 PC N 대는 타일 하나에 `count=3` (이름 뒤 `× 3`) 또는 묶음 메모 `× N`.
27
+ - 차지하는 높이는 `tile_h(sub, chips)`. 타일 아래로 나가는 선은 보조줄 아래(타일 y + 166)에서 시작한다. 그보다 위에서 나가면 선이 이름을 가른다.
28
+
29
+ **묶음** (`group(x, y, w, h, label, kind, note=…)`): 반지름 16 옅은 색 사각, 왼쪽 위에 작은 아이콘 + 굵은 라벨(묶음 색), 오른쪽 위에 회색 모노 메모(선택).
30
+
31
+ | kind | 바탕 / 테두리 | 쓰임 |
32
+ |---|---|---|
33
+ | `server` | `#eff6ff` / `#93c5fd` | 서버 · 서비스 한 곳 |
34
+ | `pc` | `#f5f3ff` / `#c4b5fd` | 사용자 PC (사람마다 한 대) |
35
+ | `external` | `#fff7ed` / `#fdba74` 점선 | 외부 SaaS · 남의 시스템 |
36
+ | `outside` | `#fffbeb` / `#f59e0b` 점선 | 이 구조 밖, 사람이 손으로 하는 단계 |
37
+ | `data` · `neutral` | 초록 · 회색 | 저장소 묶음, 기타 |
38
+
39
+ **칩** (`tile(..., chips=['aidu-test-run-case'])` 또는 `chip(cx, y, text)`): 그 명령 · 스킬을 **돌리는 타일 바로 아래**에 둔다. 앞에 `/` 를 붙인다 (빠져 있으면 `chip()` 이 붙인다). 보조줄을 줄이다가 스킬 이름을 빼지 않는다. 칩이 그 자리다.
40
+
41
+ ## 3. 연결선 (`edge(points, text, kind=…, num=…)`)
42
+
43
+ 1. **수평 · 수직 마디만.** `points` 는 꺾이는 점 목록이고, 대각선 마디는 WARN 이 난다. 모서리는 둥글리지 않는다.
44
+ 2. **색은 세 종류.** `main` (파랑, 주 흐름) · `int` (회색, 내부) · `ext` (주황, 기본 점선). 양방향은 `both=True`.
45
+ 3. **주 흐름에는 번호.** `num=1` 이면 라벨 앞에 `①` 이 붙어 읽는 순서가 보인다. 원 도형 안에 숫자를 따로 그리지 않는다 (원 안 숫자 글리프는 깨져 보였다). `①` 글자 하나만 쓴다.
46
+ 4. **라벨은 선 위에 얹지 않는다.** 가로 마디면 선 12px 위, 세로 마디면 선 오른쪽 10px 이 기본이고, 겹치면 `at=(x, y)` · `anchor=` 로 옮긴다. 라벨 글자에는 바탕색 테두리(`paint-order: stroke`)가 둘러 있어 혹시 선이 지나가도 읽히지만, 그건 안전망이다. 다른 선, 이름, 칩, **묶음 테두리** 위에도 두지 않는다. `check.py` 가 잡는다.
47
+ 5. **끝점이 아닌 타일을 가로지르지 않는다.** 돌아간다. 선끼리 교차도 없게 열 · 행을 먼저 정한다.
48
+ 6. 그리는 순서: 묶음 → 선 → 타일 (선이 타일 아래로 깔린다).
49
+
50
+ ## 4. 배치 · 범례
51
+
52
+ - **곧은 층 · 줄.** 열(C0, C1, …) 과 행(R1, R2, …) 상수를 먼저 정하고 타일을 그 칸에 놓는다. 열 간격은 270 안팎 (타일 100 + 라벨 자리), 행 간격은 260 안팎 (칩이 있으면 더).
53
+ - 주 흐름은 왼쪽 → 오른쪽 한 줄로 시작하고, 곁가지는 아래 줄로 내린다. 교차가 생기면 타일 자리를 바꾼다.
54
+ - **구조 밖 단계는 따로 상자.** 사람이 손으로 하는 일(시나리오 뽑기, 카탈로그 등록, 재발송)은 주 구조 옆이나 아래의 `outside` 묶음에 두고, 그 결과가 시스템에 들어가는 곳으로 **진짜 선 하나** (`git pull` 등) 를 잇는다. 떨어진 메모 상자로 두지 않는다.
55
+ - 범례는 `legend_tiles(x, y, [('main', …), ('int', …), ('ext', …), ('chip', …)])` 한 줄로 그림 아래에.
56
+
57
+ ## 5. 한 그림의 크기
58
+
59
+ 노드 · 화살표 · 묶음 개수 상한을 두지 않는다 (옛 "복잡도 예산" 은 2026-09-27 사용자 요청으로 삭제). 원본에 따로 있는 컴포넌트를 개수 때문에 합치지 않고, 한 구획은 한 팝업 안에 다 넣는다 (같은 것 여러 개는 `× N` 한 타일). 기본 캔버스 폭은 1600 (`PAGE_W`) 이고, 흐름이 길면 더 넓게 준다. 그러면 줄이지 않고 제 폭으로 그려 `.diagram-container` 가 좌우 스크롤된다. 범례는 첫 화면에서 보이게 왼쪽에 둔다.
60
+
61
+ ## 6. 한글 타이포그래피 (사용자 요구로 굳힌 것)
62
+
63
+ - 글꼴 계열: `Pretendard → Pretendard Variable → Apple SD Gothic Neo → Noto Sans KR → Malgun Gothic`. 한글 문서의 흔한 기본 계열이고, 라틴 Geist + 한글 Noto 혼용은 한 줄 안에서 두 서체가 어긋나 보인다.
64
+ - 제목(h1 · h2)은 **세리프 쓰지 않는다.** 산세리프 700, 자간 −0.02em. 라틴 세리프 + 한글 세리프가 한 줄에서 어긋나는 게 원인이다.
65
+ - **한글은 12px 아래로 내려가지 않는다.** 안 맞으면 글자를 줄이지 크기를 줄이지 않는다. 7~9px 슬롯(옛 스타일의 태그 · 뱃지 · 모노 보조줄 · 존 라벨 · 스윔레인 레인 부제)에는 라틴만. 타일 스타일은 가장 작은 글자가 13.5px 라 한글을 써도 된다.
66
+ - 모노(Geist Mono → SF Mono → Menlo)는 기술어에만: 보조줄의 경로 · 기술, 선 라벨, 명령 칩, 파일명, 포트, 필드.
67
+ - Pretendard 웹폰트 링크(jsdelivr)는 넣지 않는다 — 단일 파일 규칙(외부 자원은 Google Fonts 만)에 걸린다. 로컬 설치돼 있으면 잡히고, 없으면 macOS 는 Apple SD Gothic Neo, 그 외는 Noto Sans KR(웹폰트)로 떨어진다.
68
+
69
+ ## 7. 이름 규칙
70
+
71
+ 섹션 제목 · 팝업 제목 · svg `<title>` · 노드 이름에 **원본이 쓰는 전체 식별자를 그대로** 쓴다. 원본에 `shop-01-domain-catalog` 라 돼 있으면 제목에서 `catalog` 로 줄이지 않는다 — 읽는 사람은 그림 제목에서 자기 시스템의 이름을 찾는다. 원본이 이름 규칙을 명시하고 있으면(예: "모든 이름은 `shop-{nn}-{layer}-{name}` 규칙을 따른다") 그 문장을 페이지 부제에 옮겨 적는다.
72
+
73
+ ## 8. 페이지 패턴 — Overview + 팝업
74
+
75
+ - **제목 위에 눈썹(작은 대문자 라벨)을 얹지 않는다.** 제목-부제-본문 3단을 섹션마다 반복하면 내용은 한 겹인데 머리말만 세 겹이 된다. 한 덩어리에 제목은 하나, 그 아래 바로 본문이다. 카드도 마찬가지로 제목 한 줄 + 목록이다.
76
+ - 섹션 제목은 `1.` `2.` 로 번호를 매긴다. 번호가 위계를 보여주므로 눈썹도 색 점도 필요 없다.
77
+ - 팝업 제목은 `A.` `B.` 처럼 구획 기호로 시작한다. 본문 위에 "구획 A" 를 따로 적지 않는다.
78
+ - 카드에 색 점(`card-dot`)을 달지 않는다. 점이 뜻하는 게 없으면 장식이고, 뜻이 있으면 그림에 있어야 한다.
79
+ - 메인 페이지에는 **짧은 도입(한두 문장) + Overview 한 장 + 작은 표 하나(선택, `build_page(table=…)` "누가 무엇을 맡나")** 만. 상세 그림은 팝업. 긴 산문 섹션을 두지 않는다. 그림과 표가 설명이다.
80
+ - 카드는 어느 구획에도 속하지 않는 공통 정보에만 쓴다. 구획에 딸린 부가 정보(정본 문서 위치, 엔진 · API 목록, 운영 규칙)는 그 구획 팝업의 `aside` 에 넣는다. "그림에 담지 못한 것들" 같은 모음 섹션에 구획별 정보를 몰면 읽는 사람이 팝업과 카드를 오가야 한다는 지적을 받았다.
81
+ - Overview 의 상세 대상 타일을 `link('#popup-x', tile(...))` 로 감싼다. 상세가 없는 타일은 감싸지 않는다. 팝업 안 타일은 링크로 감싸지 않는다 (숨은 팝업의 링크는 누를 수 없다).
82
+ - 팝업은 CSS `:target` 이 기본. `href="#popup-a"` 로 열고, 닫기 버튼 · 배경은 `href="#overview"` 로 돌아온다. 인라인 JS 가 ESC 닫기를 더한다 (JS 가 꺼져도 열고 닫힌다).
83
+ - 팝업이 열린 동안 `body:has(.modal:target){overflow:hidden}` 으로 배경 스크롤을 잠그고, 패널에 `overscroll-behavior: contain`. (이게 없으면 팝업 안을 스크롤할 때 뒤 페이지가 같이 밀린다.)
84
+ - 링크 타일 hover: `transform: scale(1.1)` (transform-box: fill-box, 중심 기준) + 타일 테두리 2.4px 파랑 (`.tile-box`, 옛 노드는 `.node-box` 에 accent), 0.18s 트랜지션. `prefers-reduced-motion` 이면 확대 없이 테두리만.
85
+ - SVG 는 그리는 순서가 z-order 라 확대된 타일이 뒤에 그려진 이웃에 몇 px 가려질 수 있다. 열 간격 270 이면 문제없다.
86
+ - **JS 로 hover 한 노드를 `appendChild` 해 맨 앞으로 올리지 말 것** — SVG 요소를 DOM 에서 옮기면 Chrome 이 `:hover` 를 잃고 클릭도 취소된다 (실측).
87
+ - 인쇄 시 팝업이 모두 펼쳐져 순서대로 나오도록 print 스타일이 들어 있다.
88
+
89
+ ## 9. 접근성 · 단일 파일 계약
90
+
91
+ - 모든 `<svg>` 에 `role="img"` + `aria-labelledby="<slug>-title <slug>-desc"`, `<title>` 이 첫 자식. `svg()` 가 채운다.
92
+ - 마커 · 모눈 · 그림자 id 는 `<slug>-dk-ar-main` 처럼 슬러그 접두. 한 페이지에 svg 여러 장이 있어도 id 가 안 겹친다. 직접 `<marker>` 를 쓰지 않는다.
93
+ - 선 아이콘은 중첩 `<svg>` 가 아니라 `<g transform>` 이다. `check.py` · `render.py` 가 바깥 `<svg>…</svg>` 를 잘라 보기 때문이다.
94
+ - 인라인 `<script>` 하나(ESC 닫기)만, `src` 달린 외부 스크립트와 `on*` 속성 없음. 외부 자원은 `fonts.googleapis.com` 만이고, 로고는 `data:image/…` 로 박는다 (`data:` 는 이미지만). `check.py` 가 검사한다.
95
+
96
+ ## 10. 한국어 문체 (사용자 요구로 굳힌 것)
97
+
98
+ 읽는 사람이 사내 문서로 받아들일 수 있어야 한다. 아래는 실제로 지적받은 습관들이다.
99
+
100
+ - **em dash 로 부연하지 않는다.** `02 는 evidence-first — branch-explorer 가 …` 같은 문장은 한국어에서 안 쓰는 구두점이다. 쉼표로 잇거나, 괄호에 넣거나, 문장을 끊는다. 화살표 `→` 는 흐름을 나타낼 때만 쓰고 접속에는 쓰지 않는다.
101
+ - **"A가 아니라 B" 로 재정의하지 않는다.** `상류 완료가 아니라 필수 입력 충족이다`, `계층이 아니라 각 층이 따르는 규약 본문` 처럼 대조로 뜻을 세우는 구문은 한 페이지에 한 번도 많다. 그냥 B 를 서술한다. 사실을 바로잡는 경우(`pipeline 은 도메인이 아닌 오케스트레이터 스킬이다`)만 예외다.
102
+ - **추상 명사를 새로 만들지 않는다.** 표면, 정본 축, 두 축, 규약 본문, 무게중심 같은 말은 뜻이 없고 분위기만 만든다. `manifest 의 common: 에 올라오는 스킬과 sub-agent` 처럼 가리키는 것을 그대로 쓴다.
103
+ - **제목과 부제를 시적 명사구로 쓰지 않는다.** `LLM 밖에서 일의 대부분을 맡는 곳` 대신 `LLM 밖에서 도는 엔진과 검수`. 제목은 안에 뭐가 있는지 알려주는 라벨이다.
104
+ - **가운뎃점 `·` 은 식별자 나열에만.** `docs/a · docs/b · docs/c` 는 되지만 `수집 · 추출 · 정제 · 검증은` 처럼 문장 속 나열은 쉼표로 쓴다. 한 페이지에 수십 개가 찍히면 그것만 보인다.
105
+ - 문장은 평서형 `-다` 로 끝내고, 목록 항목도 완결된 문장으로 쓴다. 명사로 끊어 놓으면 읽는 사람이 관계를 추측해야 한다.
106
+ - 라틴 식별자 뒤 조사는 한 칸 띄운다(`main 이`, `sub-agent 를`). 기존 페이지와 맞추기 위한 규칙이다.
107
+ - **식별자는 `<code>` 칩으로 감싸 본문 한글과 분리한다.** 스킬 · agent 이름, 파일 · 경로, 명령, 필드 · enum 값, 티켓 번호(`IT250218R-735`) 가 대상이다. 칩은 줄 안에서 끊기지 않으므로(`white-space: nowrap`) 좁은 카드에 들어갈 긴 명령은 칩 둘로 나눈다. 사용자 지적(2026-09-28, "일반 한글과 agent 이름 · 티켓 이름을 분리해 달라").
108
+ - **카드 항목도 한 문단으로 몰지 않는다.** `<b>소제목</b>` 한 줄(카드에서는 줄바꿈된다) + 짧은 문장 + 하위 목록으로 나눈다. 같은 날 "가독성이 너무 안 좋다"는 지적이 있었다.
109
+ - **설명 본문도 같다.** `intro` · `overview_body` · 팝업 `body` · `aside` 를 한 문단으로 쓰지 않는다. 짧은 도입 문단 하나 + `<b>소제목</b>` 을 앞에 단 항목 목록으로 나눈다(팝업 · 개요에서는 소제목이 같은 줄 앞에 붙는다). 사용자 지적(2026-09-28, "줄바꿈 없이 쭈루룩이라 읽기 힘들다").
110
+ - **코드가 하지 않는 동작을 암시하는 말을 만들지 않는다.** 여러 동작을 한 낱말로 줄이면 뜻이 바뀐다 — 원본에서 다시 맞추고 일부 값은 이어 받는 동작을 "전수 재생성" 이나 "최종화" 로 적었다가 "처음부터 다시 만드는 거냐, 왜 다시 만드냐" 는 반문을 받았다. 명령이 무엇을 읽고 무엇을 쓰는지, 무엇을 그대로 두는지를 그대로 적는다. 노드 보조줄처럼 짧게 써야 하는 자리도 같다.
@@ -0,0 +1,167 @@
1
+ # -*- coding: utf-8 -*-
2
+ """워크드 예제 — 가상의 온라인 주문 서비스를 타일 스타일(기본)로 Overview 1장 + 팝업 2장 + "누가 무엇을 맡나" 표 하나로 그린다.
3
+
4
+ 타일 스타일: 모눈 바탕(svg(grid=True)) · 공식 로고 타일(tile) · 색 묶음(group) · 직각 선(edge, 주 흐름에 ①②③)
5
+ · 명령 칩(tile(chips=[...]), 앞에 '/') · 구조 밖 사람 손 단계는 따로 점선 상자(group kind='outside') + 진짜 선 하나.
6
+ 로고는 devicon · simple-icons 에서 한 번 받아 ~/.cache/thuthi-arch-diagram/logos 에 두고 data URI 로 박는다
7
+ (못 받으면 WARN 과 함께 선 아이콘으로 그린다).
8
+ 실행: python3 example-shop.py [out.html]
9
+
10
+ 새 작업은 이 파일을 복사해 그림 함수(overview · popup_api · popup_worker)의 좌표 · 문구를 바꾼다.
11
+ 좌표 잡는 법: 열(C) · 행(R) 상수를 먼저 정하고, 타일 아래쪽에서 나가는 선은 보조줄 아래(타일 y + 166)에서 시작한다.
12
+ """
13
+ import sys, os
14
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'scripts'))
15
+ from diagramkit import *
16
+
17
+ PERSON = '#334155'
18
+
19
+
20
+ # ───────────────────────── 1. OVERVIEW ─────────────────────────
21
+ def overview():
22
+ C0, C1, C2, C3, CX = 40, 310, 580, 850, 1300 # 열: 사람 · 서비스 3열 · 외부
23
+ CM = 80 # 사람 손 상자 안 첫 열
24
+ R1, R2, R3, R4 = 180, 440, 700, 1010 # 행
25
+ B = lambda y: y + 166 # 타일 아래로 나가는 선의 시작 y (이름 · 보조줄 아래)
26
+ o = []
27
+ # 묶음 (맨 먼저)
28
+ o.append(group(270, 100, 810, 800, '주문 서비스', 'server', note='ap-northeast-2'))
29
+ o.append(group(1190, 100, 360, 800, '외부 서비스', 'external'))
30
+ o.append(group(40, 950, 1060, 300, '이 구조 밖 · 상품 등록', 'outside', note='운영자가 직접'))
31
+ # 선 (타일보다 먼저 그려 타일 아래로 깔리게)
32
+ o.append(edge([(C0+100, R1+50), (C1, R1+50)], 'HTTPS', num=1))
33
+ o.append(edge([(C1+100, R1+50), (C2, R1+50)], 'REST', num=2, both=True))
34
+ o.append(edge([(C2+100, R1+50), (CX, R1+50)], '결제 승인', num=3))
35
+ o.append(edge([(CX, R1+84), (C2+100, R1+84)], 'webhook', kind='ext', at=(990, R1+108)))
36
+ o.append(edge([(C2+20, B(R1)), (C2+20, R1+210), (C1+50, R1+210), (C1+50, R2)], '재고 조회', kind='int'))
37
+ o.append(edge([(C2+50, B(R1)), (C2+50, R2)], 'SQL', kind='int', at=(C2+62, R2-16), anchor='start'))
38
+ o.append(edge([(C2+80, B(R1)), (C2+80, R1+210), (C3+50, R1+210), (C3+50, R2)], '주문 이벤트', num=4))
39
+ o.append(edge([(C3+50, B(R2)), (C3+50, R3)], '소비', num=5))
40
+ o.append(edge([(C3+100, R3+50), (CX, R3+50)], '메일 발송', num=6))
41
+ o.append(edge([(CM+100, R4+50), (C1, R4+50)], None, kind='ext', dashed=False))
42
+ o.append(edge([(C1+100, R4+50), (C2, R4+50)], 'push', kind='ext', dashed=False))
43
+ o.append(edge([(C2+100, R4+50), (780, R4+50), (780, R2+60), (C2+100, R2+60)], 'git pull', kind='ext', at=(792, 655), anchor='start'))
44
+ # 타일
45
+ o.append(tile(C0, R1, '고객', '브라우저', icon_kind='person', color=PERSON))
46
+ o.append(tile(C1, R1, '웹 스토어', 'web/ · react', logo_spec='react'))
47
+ o.append(link('#popup-api', tile(C2, R1, '주문 API', 'api/ · express', logo_spec='nodejs')))
48
+ o.append(tile(CX, R1, 'Stripe', '결제', logo_spec='si:stripe'))
49
+ o.append(tile(C1, R2, '캐시', 'redis · 재고 수량', logo_spec='redis'))
50
+ o.append(tile(C2, R2, '주문 DB', 'postgresql', logo_spec='postgresql'))
51
+ o.append(tile(C3, R2, '메시지 큐', 'order.paid', logo_spec='rabbitmq'))
52
+ o.append(link('#popup-worker', tile(C3, R3, '알림 워커', 'worker/ · python', logo_spec='python', badge_kind='server', count=3)))
53
+ o.append(tile(CX, R3, 'Mailgun', '메일 발송', logo_spec='si:mailgun'))
54
+ o.append(tile(CM, R4, '운영자', '직접 실행', icon_kind='person', color='#b45309'))
55
+ o.append(tile(C1, R4, 'Claude Code', '운영자 PC 세션', logo_spec='si:claude', badge_kind='robot',
56
+ chips=['shop-import-catalog']))
57
+ o.append(tile(C2, R4, '저장소', 'catalog/*.json', logo_spec='git'))
58
+ o.append(legend_tiles(40, 1300, [('main', '주 흐름 (번호 순서)'), ('int', '내부 호출'),
59
+ ('ext', '외부 서비스 · 사람 손 단계'), ('chip', '그 타일이 돌리는 명령 · 스킬')]))
60
+ return svg('shop-overview', '주문 서비스 구성 — 고객 주문에서 알림 메일까지',
61
+ '고객이 웹 스토어에서 주문하면 주문 API 가 Stripe 로 결제를 승인받고 주문을 저장한 뒤 이벤트를 큐에 올리고, '
62
+ '알림 워커 3개가 그것을 받아 Mailgun 으로 메일을 보낸다. 상품 카탈로그는 운영자가 Claude Code 로 만들어 저장소에 올리고 DB 가 git pull 로 읽는다.',
63
+ 1600, 1330, '\n'.join(o), grid=True)
64
+
65
+
66
+ # ───────────────────────── 2. 팝업 A — 주문 API 안 ─────────────────────────
67
+ def popup_api():
68
+ C0, C1, C2, C3, CX = 40, 330, 600, 870, 1300
69
+ R1, R2 = 170, 470
70
+ K = R1 + 232 # 아래 행으로 꺾는 y (묶음 아래 테두리 360 과 라벨이 안 겹치게)
71
+ B = lambda y: y + 166
72
+ o = []
73
+ o.append(group(310, 90, 700, 270, 'api/ (주문 API)', 'server', note='node 20 · express'))
74
+ o.append(group(1180, 90, 360, 270, '외부 서비스', 'external'))
75
+ o.append(edge([(C0+100, R1+50), (C1, R1+50)], 'POST /orders', num=1))
76
+ o.append(edge([(C1+100, R1+50), (C2, R1+50)], '검증 통과', num=2))
77
+ o.append(edge([(C2+100, R1+50), (C3, R1+50)], '결제 요청', num=3))
78
+ o.append(edge([(C3+100, R1+50), (CX, R1+50)], 'charge', num=4))
79
+ o.append(edge([(CX, R1+84), (C3+100, R1+84)], 'webhook', kind='ext', at=(1135, R1+108)))
80
+ o.append(edge([(C2+20, B(R1)), (C2+20, K), (C1+50, K), (C1+50, R2)], '재고 확인', kind='int'))
81
+ o.append(edge([(C2+50, B(R1)), (C2+50, R2)], '주문 저장', num=5, at=(C2+62, R2-16), anchor='start'))
82
+ o.append(edge([(C2+80, B(R1)), (C2+80, K), (C3+50, K), (C3+50, R2)], 'order.paid 발행', num=6))
83
+ o.append(tile(C0, R1, '웹 스토어', 'web/ · react', logo_spec='react'))
84
+ o.append(tile(C1, R1, '라우터', 'routes/orders.ts', logo_spec='express'))
85
+ o.append(tile(C2, R1, '주문 서비스', 'services/order.ts', icon_kind='box', color='#1d4ed8'))
86
+ o.append(tile(C3, R1, '결제 어댑터', 'adapters/stripe.ts', icon_kind='card', color='#1d4ed8'))
87
+ o.append(tile(CX, R1, 'Stripe', 'PaymentIntent', logo_spec='si:stripe'))
88
+ o.append(tile(C1, R2, '캐시', 'redis · 재고 수량', logo_spec='redis'))
89
+ o.append(tile(C2, R2, '주문 DB', 'orders · payments', logo_spec='postgresql'))
90
+ o.append(tile(C3, R2, '메시지 큐', 'outbox → order.paid', logo_spec='rabbitmq'))
91
+ return svg('shop-api', 'A. 주문 API 안에서 주문 하나가 지나가는 길',
92
+ '라우터가 요청을 검증하고, 주문 서비스가 재고를 확인한 뒤 결제 어댑터로 Stripe 결제를 요청하고, 주문을 저장하고 order.paid 를 발행한다.',
93
+ 1600, 690, '\n'.join(o), grid=True)
94
+
95
+
96
+ # ───────────────────────── 3. 팝업 B — 알림 워커 ─────────────────────────
97
+ def popup_worker():
98
+ C0, C1, C2, C3, CX, CP = 40, 330, 600, 870, 1250, 1490
99
+ CM = 80
100
+ R1, R2, R3 = 170, 440, 770
101
+ B = lambda y: y + 166
102
+ o = []
103
+ o.append(group(310, 90, 480, 560, 'worker/ (알림 워커)', 'server', note='× 3'))
104
+ o.append(group(1210, 90, 160, 270, '외부', 'external'))
105
+ o.append(group(40, 700, 500, 300, '이 구조 밖 · 재발송', 'outside', note='실패 건만'))
106
+ o.append(edge([(C0+100, R1+50), (C1, R1+50)], 'order.paid', num=1))
107
+ o.append(edge([(C1+70, B(R1)), (C1+70, R1+210), (C3+50, R1+210), (C3+50, R2)], '주문 · 고객 조회', num=2))
108
+ o.append(edge([(C1+40, B(R1)), (C1+40, R1+230), (C2+50, R1+230), (C2+50, R2)], '렌더', num=3, at=(510, R1+256)))
109
+ o.append(edge([(C1+100, R1+50), (CX, R1+50)], '발송 요청', num=4))
110
+ o.append(edge([(CX+100, R1+50), (CP, R1+50)], '메일', num=5))
111
+ o.append(edge([(CM+100, R3+50), (C1, R3+50)], None, kind='ext', dashed=False))
112
+ o.append(edge([(C1+50, R3), (C1+50, 560), (230, 560), (230, R1+84), (C0+100, R1+84)], '재발행', kind='ext',
113
+ at=(220, 430), anchor='end'))
114
+ o.append(tile(C0, R1, '메시지 큐', 'order.paid', logo_spec='rabbitmq'))
115
+ o.append(tile(C1, R1, '알림 워커', 'worker/main.py', logo_spec='python', badge_kind='server', count=3))
116
+ o.append(tile(C2, R2, '메일 템플릿', 'templates/*.html', icon_kind='file', color='#1d4ed8'))
117
+ o.append(tile(C3, R2, '주문 DB', 'postgresql · 읽기만', logo_spec='postgresql'))
118
+ o.append(tile(CX, R1, 'Mailgun', 'messages API', logo_spec='si:mailgun'))
119
+ o.append(tile(CP, R1, '고객', '메일 받음', icon_kind='person', color=PERSON))
120
+ o.append(tile(CM, R3, '운영자', '직접 실행', icon_kind='person', color='#b45309'))
121
+ o.append(tile(C1, R3, 'Claude Code', '운영자 PC 세션', logo_spec='si:claude', badge_kind='robot',
122
+ chips=['shop-replay-failed']))
123
+ return svg('shop-worker', 'B. 알림 워커 × 3 — order.paid 에서 고객 메일까지',
124
+ '워커 3개가 order.paid 를 받아 주문을 조회하고 템플릿을 렌더해 Mailgun 으로 보낸다. 실패 건은 운영자가 Claude Code 로 다시 큐에 올린다.',
125
+ 1600, 1040, '\n'.join(o), grid=True)
126
+
127
+
128
+ if __name__ == '__main__':
129
+ out_path = sys.argv[1] if len(sys.argv) > 1 else 'shop.html'
130
+
131
+ # 설명 속 식별자를 코드 칩으로. 기본 패턴이 못 잡는 짧은 이름은 names 로, 스킬 이름은 '/' 를 붙여 patterns 로.
132
+ NAMES = ['order.paid', 'webhook', 'outbox', 'charge']
133
+ PATTERNS = [r'/shop-[a-z-]+']
134
+ cz = lambda s: codeify(s, names=NAMES, patterns=PATTERNS)
135
+
136
+ # 긴 산문은 쓰지 않는다. 짧은 도입 한두 문장 + 그림 + 작은 표 하나 (design-rules §8).
137
+ INTRO = cz('<p>고객 주문이 결제, 저장, 알림 메일까지 가는 길이다. 번호 ①~⑥ 이 주문 하나가 지나가는 순서다. '
138
+ '상품 카탈로그는 운영자가 /shop-import-catalog 로 만들어 저장소에 올린다.</p>')
139
+
140
+ html_out = build_page(
141
+ title='주문 서비스 구성',
142
+ meta='2026-01-01 작성. <code>main</code> abc1234 기준.',
143
+ h1='주문 서비스 구성',
144
+ intro=INTRO,
145
+ overview_h2='구성도',
146
+ overview_body='',
147
+ overview_svg=overview(),
148
+ hint='<b>주문 API</b> 나 <b>알림 워커</b> 타일을 누르면 안쪽 그림이 팝업으로 열린다.',
149
+ popups=[
150
+ dict(id='popup-api', title='A. 주문 API 안 (api/)',
151
+ body=cz('<p>주문 하나가 라우터에서 order.paid 발행까지 가는 순서다. Stripe 결과는 webhook 으로 한 번 더 받아 결제 상태를 맞춘다.</p>'),
152
+ svg=popup_api()),
153
+ dict(id='popup-worker', title='B. 알림 워커 × 3 (worker/)',
154
+ body=cz('<p>워커 3개가 같은 큐를 나눠 받는다. 실패 건은 운영자가 /shop-replay-failed 로 다시 큐에 올린다.</p>'),
155
+ svg=popup_worker()),
156
+ ],
157
+ table=dict(title='누가 무엇을 맡나', head=['부분', '맡는 것', '맡지 않는 것'], rows=[
158
+ ['주문 API', '주문 검증, 결제 요청, 주문 저장, <code>order.paid</code> 발행', '메일을 보내지 않는다'],
159
+ ['알림 워커 × 3', '<code>order.paid</code> 를 받아 메일 렌더 · 발송', '주문 · 결제 상태를 바꾸지 않는다'],
160
+ ['운영자 (사람)', 'Claude Code 에서 <code>/shop-import-catalog</code> · <code>/shop-replay-failed</code> 실행', '주문 흐름에 끼지 않는다'],
161
+ ]),
162
+ footer_left='주문 서비스 구성',
163
+ footer_right='2026-01-01 · main abc1234 기준',
164
+ )
165
+ open(out_path, 'w', encoding='utf-8').write(html_out)
166
+ print('wrote', out_path, len(html_out))
167
+ report_warnings()
@@ -0,0 +1,194 @@
1
+ #!/usr/bin/env python3
2
+ """arch-diagram 산출물 검사기 — 접근성 계약 · 단일 파일 안전(외부 자원·외부 스크립트 금지, 인라인 JS 허용,
3
+ data:image 로 박은 로고는 허용) · 라벨/노드 겹침 · 타일 스타일 겹침(타일 · 이름 · 칩 · 선 라벨 · 묶음 라벨끼리, 선이 글자나
4
+ 남의 타일을 지나가는 것) · 한글 크기 · 팝업 링크.
5
+
6
+ python3 check.py out.html
7
+
8
+ exit 0 = 통과, 1 = 실패 항목 있음. 경고(WARN)는 exit 에 영향 없음.
9
+ """
10
+ import re, sys
11
+ from html.parser import HTMLParser
12
+
13
+ PAPER = '#f5f5f5'
14
+ ALLOWED_HOSTS = ('fonts.googleapis.com', 'fonts.gstatic.com')
15
+
16
+
17
+ class P(HTMLParser):
18
+ def __init__(self):
19
+ super().__init__()
20
+ self.svgs = [] # list of dict(attrs, children order list)
21
+ self.cur = None
22
+ self.errors, self.warns = [], []
23
+ self.ids = {}
24
+ self.links = []
25
+ self.text_stack = []
26
+
27
+ def handle_starttag(self, tag, attrs):
28
+ a = dict(attrs)
29
+ if tag == 'script' and a.get('src'):
30
+ self.errors.append('외부 script src 금지 — 인라인만 허용')
31
+ for k, v in attrs:
32
+ if k.startswith('on'):
33
+ self.errors.append(f'<{tag} {k}=…> 인라인 이벤트 금지')
34
+ if k in ('src', 'href', 'xlink:href') and v and v.startswith('data:') and not v.startswith('data:image/'):
35
+ self.errors.append(f'data: 는 이미지만 허용: {v[:40]}')
36
+ if k in ('src', 'href', 'xlink:href') and v and re.match(r'(https?:)?//', v):
37
+ host = re.sub(r'^(https?:)?//', '', v).split('/')[0]
38
+ if host not in ALLOWED_HOSTS:
39
+ self.errors.append(f'외부 자원 금지: {v[:80]}')
40
+ if 'id' in a:
41
+ self.ids[a['id']] = self.ids.get(a['id'], 0) + 1
42
+ if tag == 'a' and a.get('href', '').startswith('#'):
43
+ self.links.append(a['href'][1:])
44
+ if tag == 'svg':
45
+ self.cur = dict(attrs=a, children=[], rects=[], texts=[], order=0, boxes=[], edges=[], groups=[])
46
+ self.svgs.append(self.cur)
47
+ elif self.cur is not None:
48
+ if tag in ('title', 'desc', 'defs', 'rect', 'path', 'line', 'text', 'g', 'a', 'marker', 'polygon'):
49
+ self.cur['children'].append((tag, a))
50
+ if tag == 'rect':
51
+ self.cur['order'] += 1
52
+ self.cur['rects'].append((self.cur['order'], a))
53
+ if tag == 'text':
54
+ self.text_stack.append(a)
55
+ if a.get('data-box'):
56
+ try:
57
+ x, y, w, h = (float(v) for v in a['data-box'].split())
58
+ self.cur['boxes'].append((a.get('data-kind', ''), x, y, w, h, tag))
59
+ except ValueError:
60
+ pass
61
+ if tag == 'rect' and 'group-box' in (a.get('class') or '').split():
62
+ self.cur['groups'].append(tuple(f(a, k) for k in ('x', 'y', 'width', 'height')))
63
+ if tag == 'path' and 'edge' in (a.get('class') or '').split():
64
+ pts = [tuple(float(n) for n in m) for m in re.findall(r'(-?[\d.]+)[ ,](-?[\d.]+)', a.get('d', ''))]
65
+ self.cur['edges'].append(pts)
66
+
67
+ def handle_data(self, data):
68
+ if self.cur is not None and self.text_stack and data.strip():
69
+ self.cur['texts'].append((self.text_stack[-1], data.strip()))
70
+
71
+ def handle_endtag(self, tag):
72
+ if tag == 'text' and self.text_stack:
73
+ self.text_stack.pop()
74
+ if tag == 'svg':
75
+ self.cur = None
76
+
77
+
78
+ def f(a, k, d=0.0):
79
+ try:
80
+ return float(a.get(k, d))
81
+ except ValueError:
82
+ return d
83
+
84
+
85
+ def check(path):
86
+ p = P()
87
+ src = open(path, encoding='utf-8').read()
88
+ p.feed(src)
89
+ E, W = p.errors, p.warns
90
+ for m in re.finditer(r'(?:url\(\s*[\'"]?|@import\s+[\'"])((?:https?:)?//[^\'")\s]+)', src):
91
+ host = re.sub(r'^(https?:)?//', '', m.group(1)).split('/')[0]
92
+ if host not in ALLOWED_HOSTS:
93
+ E.append(f'CSS 외부 자원 금지: {m.group(1)[:80]}')
94
+ for i, s in enumerate(p.svgs):
95
+ a = s['attrs']
96
+ tags = [t for t, _ in s['children']]
97
+ if a.get('role') != 'img':
98
+ E.append(f'svg#{i}: role="img" 없음')
99
+ lab = a.get('aria-labelledby', '').split()
100
+ first = [t for t in tags if t in ('title', 'desc', 'defs', 'rect', 'path')][:2]
101
+ if not first or first[0] != 'title':
102
+ E.append(f'svg#{i}: <title> 이 첫 자식이 아님')
103
+ tid = [x.get('id') for t, x in s['children'] if t == 'title']
104
+ did = [x.get('id') for t, x in s['children'] if t == 'desc']
105
+ if not tid or not did or tid[0] not in lab or did[0] not in lab:
106
+ E.append(f'svg#{i}: aria-labelledby 가 title/desc id 와 안 맞음 ({lab})')
107
+ for x in tid + did:
108
+ if x in ('title', 'desc'):
109
+ E.append(f'svg#{i}: id 가 맨몸 "{x}" — 슬러그 접두어 필요')
110
+ # 한글 최소 12px
111
+ for ta, txt in s['texts']:
112
+ if re.search(r'[가-힣]', txt) and f(ta, 'font-size', 12) < 12:
113
+ E.append(f'svg#{i}: 한글 텍스트 {f(ta,"font-size")}px < 12px: "{txt[:24]}"')
114
+ # 라벨 마스크 vs 뒤에 그려진 노드
115
+ rects = s['rects']
116
+ nodes = [(o, r) for o, r in rects if r.get('rx') == '6' and r.get('stroke')]
117
+ masks = [(o, r) for o, r in rects if r.get('rx') == '2' and r.get('fill') == PAPER and r.get('height') in ('12', '16') and f(r, 'width') >= 20]
118
+ for mo, m in masks:
119
+ mx, my, mw, mh = f(m, 'x'), f(m, 'y'), f(m, 'width'), f(m, 'height')
120
+ for no, n in nodes:
121
+ if no < mo:
122
+ continue
123
+ nx, ny, nw, nh = f(n, 'x'), f(n, 'y'), f(n, 'width'), f(n, 'height')
124
+ if mx < nx + nw and mx + mw > nx and my < ny + nh and my + mh > ny:
125
+ # 완전히 노드 안이면 뱃지(허용)
126
+ inside = mx >= nx and mx + mw <= nx + nw and my >= ny and my + mh <= ny + nh
127
+ if not inside:
128
+ E.append(f'svg#{i}: 라벨 마스크 ({mx:.0f},{my:.0f} {mw:.0f}×{mh:.0f}) 가 뒤에 그려진 노드 ({nx:.0f},{ny:.0f} {nw:.0f}×{nh:.0f}) 와 겹침')
129
+ # 노드끼리 겹침
130
+ for j in range(len(nodes)):
131
+ for k in range(j + 1, len(nodes)):
132
+ A, B = nodes[j][1], nodes[k][1]
133
+ if f(A, 'x') < f(B, 'x') + f(B, 'width') and f(A, 'x') + f(A, 'width') > f(B, 'x') and f(A, 'y') < f(B, 'y') + f(B, 'height') and f(A, 'y') + f(A, 'height') > f(B, 'y'):
134
+ E.append(f'svg#{i}: 노드 겹침 ({f(A,"x"):.0f},{f(A,"y"):.0f}) vs ({f(B,"x"):.0f},{f(B,"y"):.0f})')
135
+ # 타일 스타일: 타일 · 이름 · 칩 · 라벨 · 묶음 라벨 상자끼리 겹침
136
+ bx = s['boxes']
137
+ def hit(a, b, pad=1):
138
+ return a[1] < b[1] + b[3] - pad and a[1] + a[3] > b[1] + pad and a[2] < b[2] + b[4] - pad and a[2] + a[4] > b[2] + pad
139
+ def desc(b):
140
+ return f'{b[0]}({b[1]:.0f},{b[2]:.0f} {b[3]:.0f}×{b[4]:.0f})'
141
+ for j in range(len(bx)):
142
+ for k in range(j + 1, len(bx)):
143
+ if hit(bx[j], bx[k]):
144
+ E.append(f'svg#{i}: 겹침 {desc(bx[j])} ↔ {desc(bx[k])}')
145
+ # 선 마디가 글자 위를 지나가거나, 끝점이 아닌 타일을 가로지르는가
146
+ for pts in s['edges']:
147
+ ends = (pts[0], pts[-1]) if pts else ()
148
+ for (x1, y1), (x2, y2) in zip(pts, pts[1:]):
149
+ sx0, sx1, sy0, sy1 = min(x1, x2), max(x1, x2), min(y1, y2), max(y1, y2)
150
+ for b in bx:
151
+ kind, bx0, by0, bw, bh = b[:5]
152
+ if kind == 'tile':
153
+ ix0, iy0, ix1, iy1 = bx0 + 3, by0 + 3, bx0 + bw - 3, by0 + bh - 3
154
+ near = any(bx0 - 10 <= ex <= bx0 + bw + 10 and by0 - 10 <= ey <= by0 + bh + 10 for ex, ey in ends)
155
+ if not near and sx0 < ix1 and sx1 > ix0 and sy0 < iy1 and sy1 > iy0:
156
+ E.append(f'svg#{i}: 선 ({x1:.0f},{y1:.0f})→({x2:.0f},{y2:.0f}) 이 끝점이 아닌 타일 {desc(b)} 을 가로지름')
157
+ elif sx0 <= bx0 + bw - 1 and sx1 >= bx0 + 1 and sy0 <= by0 + bh - 1 and sy1 >= by0 + 1:
158
+ E.append(f'svg#{i}: 선 ({x1:.0f},{y1:.0f})→({x2:.0f},{y2:.0f}) 이 글자 {desc(b)} 위를 지나감 — 라벨을 선에서 떼어 놓는다')
159
+ # 글자(선 라벨 · 이름 · 칩)가 묶음 테두리에 걸치는가 — 테두리 선이 글자를 가른다
160
+ for gx, gy, gw, gh in s['groups']:
161
+ sides = [((gx, gy), (gx + gw, gy)), ((gx, gy + gh), (gx + gw, gy + gh)), ((gx, gy), (gx, gy + gh)), ((gx + gw, gy), (gx + gw, gy + gh))]
162
+ for b in bx:
163
+ kind, bx0, by0, bw, bh = b[:5]
164
+ if kind in ('tile', 'glabel'):
165
+ continue
166
+ for (x1, y1), (x2, y2) in sides:
167
+ if min(x1, x2) <= bx0 + bw - 1 and max(x1, x2) >= bx0 + 1 and min(y1, y2) <= by0 + bh - 1 and max(y1, y2) >= by0 + 1:
168
+ E.append(f'svg#{i}: 글자 {desc(b)} 가 묶음 테두리 ({gx:.0f},{gy:.0f} {gw:.0f}×{gh:.0f}) 에 걸침 — 글자나 묶음을 옮긴다')
169
+ break
170
+ # 대각선 <line>
171
+ for t, x in s['children']:
172
+ if t == 'line' and f(x, 'x1') != f(x, 'x2') and f(x, 'y1') != f(x, 'y2'):
173
+ E.append(f'svg#{i}: 대각선 <line> 금지 ({x.get("x1")},{x.get("y1")})→({x.get("x2")},{x.get("y2")})')
174
+ for k, v in p.ids.items():
175
+ if v > 1:
176
+ E.append(f'id 중복: {k}')
177
+ for h in p.links:
178
+ if h and h not in p.ids:
179
+ E.append(f'끊긴 링크 #{h}')
180
+ for e in E:
181
+ print('FAIL', e)
182
+ for w in W:
183
+ print('WARN', w)
184
+ print(('FAIL' if E else 'OK'), path, f'(svg {len(p.svgs)}개)')
185
+ return 1 if E else 0
186
+
187
+
188
+ if __name__ == '__main__':
189
+ for _f in (sys.stdout, sys.stderr): # Windows 콘솔(cp949)
190
+ try:
191
+ _f.reconfigure(encoding='utf-8', errors='replace')
192
+ except (AttributeError, ValueError):
193
+ pass
194
+ sys.exit(check(sys.argv[1]))