@acceler-digital/karura 0.0.0-stage → 0.2.1

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 (75) hide show
  1. package/.claude/hooks/lint-text-style.py +876 -0
  2. package/.claude/settings.json +17 -0
  3. package/.claude/skills/d0-create-artifact-skill/SKILL.md +123 -0
  4. package/.claude/skills/d0-create-artifact-skill/skill-writing-rules.md +67 -0
  5. package/.claude/skills/d0-create-artifact-skill/template.md +63 -0
  6. package/.claude/skills/d1-actor-list/SKILL.md +66 -0
  7. package/.claude/skills/d1-actor-list/template.md +54 -0
  8. package/.claude/skills/d1-business-requirement-document/SKILL.md +116 -0
  9. package/.claude/skills/d1-business-requirement-document/template.md +251 -0
  10. package/.claude/skills/d1-domain-common-requirement-document/SKILL.md +112 -0
  11. package/.claude/skills/d1-domain-common-requirement-document/template.md +120 -0
  12. package/.claude/skills/d1-domain-definition-document/SKILL.md +67 -0
  13. package/.claude/skills/d1-domain-definition-document/template.md +113 -0
  14. package/.claude/skills/d1-domain-requirement-document/SKILL.md +119 -0
  15. package/.claude/skills/d1-domain-requirement-document/template.md +135 -0
  16. package/.claude/skills/d1-product-requirement-document/SKILL.md +104 -0
  17. package/.claude/skills/d1-product-requirement-document/template.md +287 -0
  18. package/.claude/skills/d1-screen-concepts/SKILL.md +154 -0
  19. package/.claude/skills/d1-screen-concepts/template.md +112 -0
  20. package/.claude/skills/d1-use-case-list/SKILL.md +137 -0
  21. package/.claude/skills/d1-use-case-list/template.md +29 -0
  22. package/.claude/skills/d1-user-story-list/SKILL.md +119 -0
  23. package/.claude/skills/d1-user-story-list/template.md +27 -0
  24. package/.claude/skills/d2-c4-level1-sequences/SKILL.md +162 -0
  25. package/.claude/skills/d2-c4-level1-sequences/example.md +83 -0
  26. package/.claude/skills/d2-c4-level1-sequences/template.md +47 -0
  27. package/.claude/skills/d2-c4-level1-system-context/SKILL.md +51 -0
  28. package/.claude/skills/d2-c4-level1-system-context/template.md +48 -0
  29. package/.claude/skills/d2-conceptual-data-model/SKILL.md +138 -0
  30. package/.claude/skills/d2-conceptual-data-model/example.md +75 -0
  31. package/.claude/skills/d2-conceptual-data-model/template.md +60 -0
  32. package/.claude/skills/d2-external-system-list/SKILL.md +33 -0
  33. package/.claude/skills/d2-external-system-list/template.md +15 -0
  34. package/.claude/skills/d2-function-list/SKILL.md +50 -0
  35. package/.claude/skills/d2-function-list/template.md +15 -0
  36. package/.claude/skills/d2-non-functional-requirements/SKILL.md +129 -0
  37. package/.claude/skills/d2-non-functional-requirements/template-chapter.md +32 -0
  38. package/.claude/skills/d2-non-functional-requirements/template-general.md +56 -0
  39. package/.claude/skills/d2-screen-flow-diagram/SKILL.md +85 -0
  40. package/.claude/skills/d2-screen-flow-diagram/template.md +32 -0
  41. package/.claude/skills/d2-screen-list/SKILL.md +93 -0
  42. package/.claude/skills/d2-screen-list/template.md +15 -0
  43. package/.claude/skills/d3-application-architecture/SKILL.md +110 -0
  44. package/.claude/skills/d3-application-architecture/template.md +123 -0
  45. package/.claude/skills/d3-c4-level2-container/SKILL.md +90 -0
  46. package/.claude/skills/d3-c4-level2-container/template.md +62 -0
  47. package/.claude/skills/d3-c4-level2-sequences/SKILL.md +121 -0
  48. package/.claude/skills/d3-c4-level2-sequences/template.md +85 -0
  49. package/.claude/skills/d3-er-diagram/SKILL.md +123 -0
  50. package/.claude/skills/d3-er-diagram/template.md +61 -0
  51. package/.claude/skills/d8-system-test-plan/SKILL.md +98 -0
  52. package/.claude/skills/d8-system-test-plan/template.md +128 -0
  53. package/.claude/skills/d9-test-data-requirements/SKILL.md +97 -0
  54. package/.claude/skills/d9-test-data-requirements/template.md +11 -0
  55. package/.claude/skills/d9-test-data-tool/SKILL.md +92 -0
  56. package/.claude/skills/d9-test-data-tool/template.md +23 -0
  57. package/.claude/skills/d9-test-perspectives/SKILL.md +118 -0
  58. package/.claude/skills/d9-test-perspectives/template.md +11 -0
  59. package/.claude/skills/d9-test-specification/SKILL.md +111 -0
  60. package/.claude/skills/d9-test-specification/template.md +11 -0
  61. package/CLAUDE.md +355 -0
  62. package/LICENSE +201 -0
  63. package/README.md +197 -2
  64. package/cli/assets/logo-ascii.txt +13 -0
  65. package/cli/assets/logo-wide-ascii.txt +14 -0
  66. package/cli/assets/logo-wide.txt +14 -0
  67. package/cli/assets/logo.txt +13 -0
  68. package/cli/bin/karura.js +163 -0
  69. package/cli/lib/banner.js +241 -0
  70. package/cli/lib/init.js +230 -0
  71. package/cli/lib/terminal.js +65 -0
  72. package/docs/D0.project-management/artifact-flow.drawio.svg +5263 -0
  73. package/docs/D0.project-management/artifact-flow.md +3 -0
  74. package/package.json +48 -4
  75. package/scripts/check-markers.sh +74 -0
@@ -0,0 +1,876 @@
1
+ #!/usr/bin/env python3
2
+ """Markdownの表記規約とリンクを機械的に扱うPostToolUseフック(ファイル作成かファイル編集した直後に走るフック)兼、一括修正・一括検査のCLI。
3
+
4
+ 直し方が一意に決まるものは自動で修正し、判断を要するものは検出して差し戻す。対象はリポジトリ内のMarkdownのみ。
5
+
6
+ §6: 和欧間スペース → 自動修正
7
+ 見出しのアンカー → 自動修正(和欧間スペースの削除で見出しのアンカーが変わったら、そのアンカーへのリンクを書き換える)
8
+ リンク切れ → 検出のみ(リンク先のファイルや見出しが無い)
9
+ §2: HTMLコメント破壊 → 検出のみ
10
+ 強調記法の不成立 → 検出のみ
11
+ コードブロックの閉じ忘れ → 検出のみ
12
+ 表の列数の不一致 → 検出のみ
13
+ §1: プレースホルダ残存 → 検出のみ(docs/配下)
14
+ §7: ID形式 → 検出のみ(docs/配下)
15
+
16
+ スコープの粒度・文体・参照元の境界のような判断を要する規約は扱わない。
17
+
18
+ 一括修正: python3 -I lint-text-style.py --fix [<path>...]
19
+ 一括検査: python3 -I lint-text-style.py --check [<path>...] ファイルは書き換えず、問題があれば終了コード1を返す
20
+ <path>を省くと、リポジトリ内のMarkdownすべてが対象になる。
21
+ """
22
+ import io
23
+ import json
24
+ import os
25
+ import posixpath
26
+ import re
27
+ import subprocess
28
+ import sys
29
+ import unicodedata
30
+ from urllib.parse import quote, unquote
31
+
32
+ JP = r'ぁ-んァ-ヶー一-龥々〆'
33
+ JP_CHAR = re.compile(r'[' + JP + r']')
34
+ ALNUM = re.compile(r'[0-9A-Za-z]')
35
+ MAX_REPORT = 8
36
+
37
+ # 自動修正の対象となる空白(キャプチャ1が削除対象)
38
+ SPACE_PATTERNS = [
39
+ re.compile(r'(?<=[' + JP + r'])( +)(?=[0-9A-Za-z`%])'),
40
+ re.compile(r'(?<=[0-9A-Za-z`%])( +)(?=[' + JP + r'])'),
41
+ ]
42
+
43
+ # 正規表現の補足
44
+ # マークダウンにおいて`**`が太字になるには、内側(太字にする文字列の側)が空白でないことに加えて、
45
+ # 内側が記号(「 ( 、 等)なら外側も空白か記号である必要がある
46
+ #
47
+ # 太字になる ...を **「なぜやるのか」** と... 内側=「 外側=空白
48
+ # 太字になる ...は**候補者評価**を... 内側=候(記号でない)
49
+ # ならない ...を**「なぜやるのか」**と... 内側=「 外側=を
50
+ #
51
+ # そのため、和欧間の半角スペースを詰める際、内側が記号になっている`**`については、
52
+ # 外側の空白を残す。消すと太字が効かなくなったり、開始と終了の対応がずれて別の範囲が太字になったりする。
53
+ # また、英単語どうしの間の空白(`use **strict** mode`)は和欧間ではないため残す。
54
+ BOLD_CLOSE = re.compile(r'\*\*( +)(?=\S)') # `**`の後ろの空白(閉じ側)
55
+ BOLD_OPEN = re.compile(r'( +)\*\*(?=\S)') # `**`の前の空白(開き側)
56
+
57
+ ASCII_PUNCT = set('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
58
+
59
+
60
+ # 見出しの先頭の番号と見出し名の間の空白(`#### 2.1 上流を読む`)は、和欧間の空白の例外として残す
61
+ HEADING_NUMBER = re.compile(r'^#{1,6} [0-9]+(?:\.[0-9]+)*\.?( +)')
62
+
63
+
64
+ def base_before(sh, i):
65
+ """位置iの直前の文字を返す。異体字セレクタなどの結合文字は飛ばし、その前の文字を返す。
66
+
67
+ `⚠️`は`⚠`の後ろに見えない異体字セレクタが付いた2文字で、セレクタだけを見ると記号と判定できない。
68
+ """
69
+ i -= 1
70
+ while i >= 0 and unicodedata.category(sh[i])[0] == 'M':
71
+ i -= 1
72
+ return sh[i] if i >= 0 else ''
73
+
74
+
75
+ def is_punct(ch):
76
+ """記号か(括弧・句読点を含む)。空文字は行頭・行末を表す。"""
77
+ if not ch:
78
+ return True
79
+ if ch in ASCII_PUNCT:
80
+ return True
81
+ return unicodedata.category(ch)[0] in 'PS'
82
+
83
+
84
+ def is_jp(ch):
85
+ return bool(ch) and JP_CHAR.match(ch) is not None
86
+
87
+
88
+ def is_alnum(ch):
89
+ return bool(ch) and ALNUM.match(ch) is not None
90
+
91
+
92
+ def removable_pair(a, b):
93
+ """空白を挟む2文字が、空白を詰めてよい組か。片方が和文で、もう片方が和文か英数字の場合に限る。
94
+
95
+ 記号を含む組(太字が効かなくなる)と、英数字どうしの組(英単語の区切り)は詰めない。
96
+ """
97
+ return (is_jp(a) and (is_jp(b) or is_alnum(b))) or (is_alnum(a) and is_jp(b))
98
+
99
+
100
+ def bold_space_spans(sh):
101
+ """強調記法に隣接する削除可能な空白の範囲を返す。"""
102
+ spans = []
103
+ for m in BOLD_CLOSE.finditer(sh): # 内側=`**`の直前、外側=空白の直後
104
+ inner = base_before(sh, m.start())
105
+ outer = sh[m.end():m.end() + 1]
106
+ if removable_pair(inner, outer):
107
+ spans.append(m.span(1))
108
+ for m in BOLD_OPEN.finditer(sh): # 外側=空白の直前、内側=`**`の直後
109
+ outer = base_before(sh, m.start())
110
+ inner = sh[m.end():m.end() + 1]
111
+ if removable_pair(outer, inner):
112
+ spans.append(m.span(1))
113
+ return spans
114
+
115
+ CODE_SPAN = re.compile(r'``.*?``|`[^`]*`')
116
+ URL = re.compile(r'(?:https?://|www\.)[^\s<>]*')
117
+ PAT_ROW = re.compile(r'^\|\s*([A-Za-z0-9_-]+)\s*\|')
118
+ PAT_ID_NOHYPHEN = re.compile(r'^[A-Z]{2,}[0-9]+$')
119
+ PAT_ID_LOWER = re.compile(r'^[a-z][a-z0-9]*(-[a-z0-9]+)+$')
120
+
121
+
122
+ def shadow(line):
123
+ """インラインコードの中身とURLを中立文字に置いた同じ長さの文字列を返す。
124
+
125
+ インラインコードは前後のバッククォートを残すため、和文とコードの境界は判定できる。
126
+ URLは全体を置き換え、前後の空白を残す。空白を詰めるとURLが自動リンクにならないか、後ろの和文までURLに含まれるため。
127
+ """
128
+ buf = list(line)
129
+ for m in CODE_SPAN.finditer(line):
130
+ s, e = m.span()
131
+ n = 2 if line[s:s + 2] == '``' else 1
132
+ for i in range(s + n, e - n):
133
+ buf[i] = '\x01'
134
+ # インラインコードの中のURLは置き換え済みのため、置き換え後の文字列から探す
135
+ for m in URL.finditer(''.join(buf)):
136
+ for i in range(*m.span()):
137
+ buf[i] = '\x01'
138
+ return ''.join(buf)
139
+
140
+
141
+ def fix_line(line):
142
+ """1行から和欧間スペースを取り除く。コードブロック外の行にのみ適用する。"""
143
+ sh = shadow(line)
144
+ spans = []
145
+ for pat in SPACE_PATTERNS:
146
+ spans.extend(m.span(1) for m in pat.finditer(sh))
147
+ spans.extend(bold_space_spans(sh))
148
+ m = HEADING_NUMBER.match(sh)
149
+ if m:
150
+ spans = [s for s in spans if s != m.span(1)]
151
+ if not spans:
152
+ return line, 0
153
+ for s, e in sorted(set(spans), reverse=True):
154
+ line = line[:s] + line[e:]
155
+ return line, len(set(spans))
156
+
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # 行の分類(コードブロック・HTMLコメント・フロントマター)
160
+
161
+ FENCE_OPEN = re.compile(r'^\s*(`{3,}|~{3,})')
162
+
163
+
164
+ def code_block_flags(lines):
165
+ """各行がフェンスコードブロック(開始行・終了行を含む)に入っているかを返す。
166
+
167
+ 戻り値は (行ごとの真偽値のリスト, 閉じられていないブロックの開始行番号。無ければ0)。
168
+ """
169
+ flags, fence, start = [], None, 0
170
+ for no, ln in enumerate(lines, 1):
171
+ if fence is None:
172
+ m = FENCE_OPEN.match(ln)
173
+ # バッククォートのフェンスは、情報文字列にバッククォートを含められない(含むならインラインコード)
174
+ if m and not (m.group(1)[0] == '`' and '`' in ln[m.end():]):
175
+ fence, start = m.group(1), no
176
+ flags.append(True)
177
+ else:
178
+ flags.append(False)
179
+ continue
180
+ flags.append(True)
181
+ s = ln.strip()
182
+ if s and set(s) == {fence[0]} and len(s) >= len(fence):
183
+ fence = None
184
+ return flags, (start if fence else 0)
185
+
186
+
187
+ def content_lines(lines):
188
+ """フロントマター・コードブロック・HTMLコメントを除いた本文の行を (行番号, 行) で返す。
189
+
190
+ 行内のHTMLコメントは同じ長さの空白に置き換えるため、列位置は元の行と一致する。
191
+ """
192
+ flags, _ = code_block_flags(lines)
193
+ front_end = 0
194
+ if lines and lines[0].strip() == '---':
195
+ for i in range(1, len(lines)):
196
+ if lines[i].strip() in ('---', '...'):
197
+ front_end = i + 1
198
+ break
199
+ out, in_comment = [], False
200
+ for no, (ln, code) in enumerate(zip(lines, flags), 1):
201
+ if no <= front_end or code:
202
+ continue
203
+ if in_comment:
204
+ end = ln.find('-->')
205
+ if end < 0:
206
+ continue
207
+ ln = ' ' * (end + 3) + ln[end + 3:]
208
+ in_comment = False
209
+ ln = re.sub(r'<!--.*?-->', lambda m: ' ' * len(m.group()), ln)
210
+ start = ln.find('<!--')
211
+ if start >= 0:
212
+ ln = ln[:start]
213
+ in_comment = True
214
+ out.append((no, ln))
215
+ return out
216
+
217
+
218
+ def fix_text(text):
219
+ """本文全体を修正し、(修正後テキスト, [(行番号, 修正前, 修正後)]) を返す。"""
220
+ lines = text.split('\n')
221
+ flags, _ = code_block_flags(lines)
222
+ out, changes = [], []
223
+ for no, (ln, code) in enumerate(zip(lines, flags), 1):
224
+ if code:
225
+ out.append(ln)
226
+ continue
227
+ fixed, n = fix_line(ln)
228
+ if n:
229
+ changes.append((no, ln.strip(), fixed.strip()))
230
+ out.append(fixed)
231
+ return '\n'.join(out), changes
232
+
233
+
234
+ def outside_fence(lines):
235
+ flags, _ = code_block_flags(lines)
236
+ return [(i, ln) for i, (ln, code) in enumerate(zip(lines, flags), 1) if not code]
237
+
238
+
239
+ def blank_fences(lines):
240
+ """フェンスコードブロックの行を空行に置き換える(行番号は保つ)。"""
241
+ flags, _ = code_block_flags(lines)
242
+ return ['' if code else ln for ln, code in zip(lines, flags)]
243
+
244
+
245
+ # ---------------------------------------------------------------------------
246
+ # 見出しのアンカー
247
+ #
248
+ # GitHubは、見出しのアンカーをgithub-sluggerで作る。github-sluggerは見出しの文字列を小文字にし、
249
+ # 下記slug_removedの文字を取り除き、半角スペースをハイフンに置き換える。同じアンカーが続くと末尾に-1, -2…を付ける。
250
+
251
+ def slug_removed(ch):
252
+ """github-sluggerがアンカーを作るときに取り除く文字か。
253
+
254
+ github-slugger 1.5の正規表現と、日本語の文書に現れる範囲(ASCII・全角記号・かな・漢字)で一致することを確かめてある。
255
+ """
256
+ if ch in ' -':
257
+ return False
258
+ cat = unicodedata.category(ch)
259
+ if cat == 'So' and ch.lower() != ch.upper(): # 丸囲みの英字(Ⓐ等)は残る
260
+ return False
261
+ return cat == 'No' or (cat[0] in 'PSZC' and cat != 'Pc')
262
+
263
+
264
+ class Slugger:
265
+ """1文書分のアンカーを順に作る。同じアンカーには-1, -2…を付けて区別する。"""
266
+
267
+ def __init__(self):
268
+ self.seen = {}
269
+
270
+ def slug(self, text):
271
+ base = ''.join(ch for ch in text.lower() if not slug_removed(ch)).replace(' ', '-')
272
+ slug = base
273
+ while slug in self.seen:
274
+ self.seen[base] += 1
275
+ slug = '%s-%d' % (base, self.seen[base])
276
+ self.seen[slug] = 0
277
+ return slug
278
+
279
+
280
+ ATX_HEADING = re.compile(r'^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$')
281
+ EXPLICIT_ID = re.compile(r'[ \t]*\{#([^}\s]+)\}$')
282
+
283
+
284
+ def code_content(s):
285
+ """インラインコードの中身を返す。前後に空白が1つずつあれば取り除く(CommonMarkの規則)。"""
286
+ if len(s) >= 2 and s[0] == ' ' and s[-1] == ' ' and s.strip():
287
+ return s[1:-1]
288
+ return s
289
+
290
+
291
+ def heading_text(raw):
292
+ """見出しのMarkdownから、画面に表示される文字列を取り出す。"""
293
+ keep = []
294
+
295
+ def protect(s):
296
+ keep.append(s)
297
+ return '\x00%d\x00' % (len(keep) - 1)
298
+
299
+ t = re.sub(r'(`+)(.+?)\1', lambda m: protect(code_content(m.group(2))), raw)
300
+ t = re.sub(r'\\([!-/:-@\[-`{-~])', lambda m: protect(m.group(1)), t) # エスケープした記号
301
+ t = re.sub(r'!?\[([^\]]*)\](?:\([^)]*\)|\[[^\]]*\])', r'\1', t) # リンク・画像は表示文字列だけ残す
302
+ t = re.sub(r'<[^>]+>', '', t) # HTMLタグ
303
+ t = t.replace('*', '') # 強調記法
304
+ t = re.sub(r'(?<![^\W_])_+|_+(?![^\W_])', '', t) # 単語の端の`_`は強調記法
305
+ t = re.sub(r'\x00(\d+)\x00', lambda m: keep[int(m.group(1))], t)
306
+ return t.strip()
307
+
308
+
309
+ def heading_slugs(lines):
310
+ """見出しを (行番号, アンカー) で返す。"""
311
+ slugger, out = Slugger(), []
312
+ for no, ln in content_lines(lines):
313
+ m = ATX_HEADING.match(ln)
314
+ if not m:
315
+ continue
316
+ text = re.sub(r'(?:^|[ \t]+)#+$', '', m.group(2) or '') # 閉じの`#`
317
+ explicit = EXPLICIT_ID.search(text)
318
+ if explicit:
319
+ slugger.seen[explicit.group(1)] = 0
320
+ out.append((no, explicit.group(1)))
321
+ else:
322
+ out.append((no, slugger.slug(heading_text(text))))
323
+ return out
324
+
325
+
326
+ def anchor_changes(before_lines, after_lines):
327
+ """修正の前後で変わった見出しのアンカーを {旧: 新} で返す。"""
328
+ before, after = heading_slugs(before_lines), heading_slugs(after_lines)
329
+ if len(before) != len(after):
330
+ return {}
331
+ return {b: a for (_, b), (_, a) in zip(before, after) if b != a}
332
+
333
+
334
+ # ---------------------------------------------------------------------------
335
+ # リンク
336
+
337
+ LINK_OPEN = re.compile(r'!?\[(?:[^\[\]\\]|\\.|\[(?:[^\[\]\\]|\\.)*\])*\]\(')
338
+ REF_DEF = re.compile(r'^ {0,3}\[(?:[^\]\\]|\\.)+\]:[ \t]*(<[^>]*>|\S+)')
339
+ SCHEME = re.compile(r'^[A-Za-z][A-Za-z0-9+.-]*:')
340
+
341
+
342
+ def link_dest_span(s, i):
343
+ """s[i]から始まるインラインリンクのリンク先を読み、(開始, 終了) を返す。リンクとして閉じていなければNoneを返す。"""
344
+ n = len(s)
345
+ while i < n and s[i] in ' \t':
346
+ i += 1
347
+ if i < n and s[i] == '<':
348
+ j = s.find('>', i + 1)
349
+ if j < 0:
350
+ return None
351
+ start, end, k = i + 1, j, j + 1
352
+ else:
353
+ start, depth, k = i, 0, i
354
+ while k < n:
355
+ c = s[k]
356
+ if c == '\\':
357
+ k += 2
358
+ continue
359
+ if c in ' \t':
360
+ break
361
+ if c == '(':
362
+ depth += 1
363
+ elif c == ')':
364
+ if depth == 0:
365
+ break
366
+ depth -= 1
367
+ k += 1
368
+ k = min(k, n)
369
+ end = k
370
+ while k < n and s[k] in ' \t':
371
+ k += 1
372
+ if k < n and s[k] in '"\'(':
373
+ j = s.find({'"': '"', "'": "'", '(': ')'}[s[k]], k + 1)
374
+ if j < 0:
375
+ return None
376
+ k = j + 1
377
+ while k < n and s[k] in ' \t':
378
+ k += 1
379
+ if k >= n or s[k] != ')':
380
+ return None
381
+ return start, end
382
+
383
+
384
+ def extract_links(lines):
385
+ """本文中のリンク(画像と参照リンクの定義を含む)を (行番号, 開始列, 終了列, リンク先) で返す。
386
+
387
+ コードとHTMLコメントの中は除く。
388
+ """
389
+ out = []
390
+ for no, ln in content_lines(lines):
391
+ sh = CODE_SPAN.sub(lambda m: '\x01' * len(m.group()), ln)
392
+ m = REF_DEF.match(sh)
393
+ if m:
394
+ s, e = m.span(1)
395
+ if sh[s] == '<':
396
+ s, e = s + 1, e - 1
397
+ out.append((no, s, e, ln[s:e]))
398
+ continue
399
+ for m in LINK_OPEN.finditer(sh):
400
+ span = link_dest_span(sh, m.end())
401
+ if span:
402
+ out.append((no, span[0], span[1], ln[span[0]:span[1]]))
403
+ return out
404
+
405
+
406
+ def resolve_link(src_rel, dest):
407
+ """リンク先を (リポジトリ基準のパス, 見出しアンカー) に分ける。外部URLやプレースホルダはNoneを返す。"""
408
+ if not dest or SCHEME.match(dest) or dest.startswith('//') or '{{' in dest:
409
+ return None
410
+ path, _, anchor = dest.partition('#')
411
+ path = unquote(path.split('?', 1)[0])
412
+ if not path:
413
+ target = src_rel
414
+ elif path.startswith('/'):
415
+ target = posixpath.normpath(path.lstrip('/'))
416
+ else:
417
+ target = posixpath.normpath(posixpath.join(posixpath.dirname(src_rel), path))
418
+ return target, (unquote(anchor) or None)
419
+
420
+
421
+ def is_template(rel):
422
+ """テンプレートか。テンプレートのリンクは生成先の文書から見た相対パスのため、テンプレートの場所からは解決できない。"""
423
+ base = posixpath.basename(rel)
424
+ return base.startswith('template') and base.endswith('.md')
425
+
426
+
427
+ SKIP_DIR = ('.git/', 'node_modules/', 'build/', 'dist/', '.docusaurus/',
428
+ '__pycache__/', '.pnpm-store/')
429
+
430
+
431
+ def in_scope(rel):
432
+ """リポジトリ内のMarkdownファイルか。
433
+
434
+ コードや設定ファイルは対象にしない。シェルの引数のように、和文と英数字の間の空白が区切りとして意味を持つことがあるため。
435
+ """
436
+ if rel.startswith('..') or os.path.isabs(rel):
437
+ return False
438
+ norm = rel.replace(os.sep, '/')
439
+ if any(part in norm for part in SKIP_DIR):
440
+ return False
441
+ return norm.endswith('.md')
442
+
443
+
444
+ def read_lines(path):
445
+ return io.open(path, encoding='utf-8').read().split('\n')
446
+
447
+
448
+ def write_lines(path, lines):
449
+ io.open(path, 'w', encoding='utf-8').write('\n'.join(lines))
450
+
451
+
452
+ class Repo:
453
+ """リポジトリ内のMarkdownの一覧と、パスの有無・見出しのアンカーの問い合わせを受け持つ。"""
454
+
455
+ def __init__(self, root):
456
+ self.root = root
457
+ self._files = None
458
+ self._dirs = {}
459
+ self._slugs = {}
460
+
461
+ def rel(self, path):
462
+ return os.path.relpath(os.path.abspath(path), self.root).replace(os.sep, '/')
463
+
464
+ def markdown_files(self):
465
+ """リポジトリ内のMarkdownを返す。gitが使えれば.gitignoreで除外したものを含めない。"""
466
+ if self._files is None:
467
+ try:
468
+ out = subprocess.run(
469
+ ['git', '-C', self.root, 'ls-files', '-co', '--exclude-standard', '-z', '--', '*.md'],
470
+ capture_output=True, check=True).stdout.decode('utf-8')
471
+ rels = [p for p in out.split('\0') if p]
472
+ except (OSError, subprocess.CalledProcessError):
473
+ rels = []
474
+ for d, _, names in os.walk(self.root):
475
+ rels.extend(self.rel(os.path.join(d, n)) for n in names)
476
+ self._files = sorted(r for r in set(rels)
477
+ if in_scope(r) and os.path.isfile(os.path.join(self.root, r)))
478
+ return self._files
479
+
480
+ def _listdir(self, d):
481
+ if d not in self._dirs:
482
+ try:
483
+ self._dirs[d] = {unicodedata.normalize('NFC', n): n for n in os.listdir(d)}
484
+ except OSError:
485
+ self._dirs[d] = None
486
+ return self._dirs[d]
487
+
488
+ def exists(self, rel):
489
+ """リポジトリ内にパスがあるか。大文字小文字を区別する(CIのLinuxと同じ判定にするため)。"""
490
+ if rel in ('', '.'):
491
+ return True
492
+ cur = self.root
493
+ for part in rel.split('/'):
494
+ names = self._listdir(cur)
495
+ hit = names and names.get(unicodedata.normalize('NFC', part))
496
+ if not hit:
497
+ return False
498
+ cur = os.path.join(cur, hit)
499
+ return True
500
+
501
+ def slugs(self, rel):
502
+ if rel not in self._slugs:
503
+ path = os.path.join(self.root, rel)
504
+ self._slugs[rel] = ({s for _, s in heading_slugs(read_lines(path))}
505
+ if os.path.isfile(path) else set())
506
+ return self._slugs[rel]
507
+
508
+ def set_slugs(self, rel, lines):
509
+ self._slugs[rel] = {s for _, s in heading_slugs(lines)}
510
+
511
+
512
+ def link_problem(repo, src_rel, dest):
513
+ """リンク先の問題を文で返す。問題が無ければNoneを返す。"""
514
+ r = resolve_link(src_rel, dest)
515
+ if not r:
516
+ return None
517
+ target, anchor = r
518
+ if target == '..' or target.startswith('../'):
519
+ return 'リポジトリの外を指している'
520
+ if not repo.exists(target):
521
+ return 'リンク先が無い'
522
+ if anchor and target.endswith('.md') and os.path.isfile(os.path.join(repo.root, target)):
523
+ if anchor not in repo.slugs(target):
524
+ return '見出し「#%s」が無い' % anchor
525
+ return None
526
+
527
+
528
+ def check_outgoing(repo, rel, lines):
529
+ """このファイルから出ていくリンクの切れを検出する。"""
530
+ hits = []
531
+ for no, _, _, dest in extract_links(lines):
532
+ problem = link_problem(repo, rel, dest)
533
+ if problem:
534
+ hits.append((no, '%s: %s' % (dest, problem)))
535
+ return hits
536
+
537
+
538
+ def check_incoming(repo, rel):
539
+ """ほかのファイルからこのファイルの見出しへ入ってくるリンクの切れを検出する。"""
540
+ hits, slugs = [], repo.slugs(rel)
541
+ for other in repo.markdown_files():
542
+ if other == rel or is_template(other):
543
+ continue
544
+ for no, _, _, dest in extract_links(read_lines(os.path.join(repo.root, other))):
545
+ r = resolve_link(other, dest)
546
+ if r and r[0] == rel and r[1] and r[1] not in slugs:
547
+ hits.append(('%s:L%d' % (other, no), '%s: 見出し「#%s」が無い' % (dest, r[1])))
548
+ return hits
549
+
550
+
551
+ def rewrite_anchor_links(repo, target_rel, mapping):
552
+ """target_relの見出しのアンカーがmapping({旧: 新})のとおり変わったとき、そこへのリンクを書き換える。
553
+
554
+ 書き換えた箇所を ('ファイル:L行番号', 旧リンク先, 新リンク先) で返す。
555
+ """
556
+ updated = []
557
+ for rel in repo.markdown_files():
558
+ if is_template(rel):
559
+ continue
560
+ path = os.path.join(repo.root, rel)
561
+ lines = read_lines(path)
562
+ edits = []
563
+ for no, s, e, dest in extract_links(lines):
564
+ r = resolve_link(rel, dest)
565
+ if not r or r[0] != target_rel or r[1] not in mapping:
566
+ continue
567
+ base, _, raw = dest.partition('#')
568
+ new = mapping[r[1]]
569
+ if '%' in raw: # 元がパーセントエンコードなら合わせる
570
+ new = quote(new, safe='')
571
+ edits.append((no, s, e, dest, base + '#' + new))
572
+ if not edits:
573
+ continue
574
+ for no, s, e, _, new_dest in sorted(edits, reverse=True):
575
+ lines[no - 1] = lines[no - 1][:s] + new_dest + lines[no - 1][e:]
576
+ write_lines(path, lines)
577
+ updated.extend(('%s:L%d' % (rel, no), old, new) for no, _, _, old, new in edits)
578
+ return updated
579
+
580
+
581
+ # ---------------------------------------------------------------------------
582
+ # フォーマットの検出
583
+
584
+ def check_html_comment(raw_lines):
585
+ lines = blank_fences(raw_lines)
586
+ hits, i, n = [], 0, len(lines)
587
+ while i < n:
588
+ pos = lines[i].find('<!--')
589
+ if pos < 0:
590
+ i += 1
591
+ continue
592
+ if '-->' in lines[i][pos + 4:]:
593
+ i += 1
594
+ continue
595
+ j, close = i + 1, -1
596
+ while j < n:
597
+ if '-->' in lines[j]:
598
+ close = j
599
+ break
600
+ if '<!--' in lines[j]:
601
+ break
602
+ j += 1
603
+ if close < 0:
604
+ hits.append((i + 1, 'HTMLコメントが閉じられていない'))
605
+ i += 1
606
+ continue
607
+ k = close + 1
608
+ while k < n and k <= close + 40:
609
+ if '<!--' in lines[k]:
610
+ break
611
+ if lines[k].strip() == '-->':
612
+ hits.append((close + 1, 'コメント本文中の`-->`でコメントが早期に閉じている'))
613
+ break
614
+ k += 1
615
+ i = close + 1
616
+ return hits
617
+
618
+
619
+ def is_space(ch):
620
+ """空白か。行頭・行末(空文字)も空白と同じ扱いにする。"""
621
+ return not ch or ch.isspace()
622
+
623
+
624
+ def check_emphasis(lines):
625
+ """太字にならない強調記法を検出する。条件はBOLD_CLOSE手前のコメント参照。"""
626
+ hits = []
627
+ for no, ln in outside_fence(lines):
628
+ sh = shadow(ln)
629
+ runs = list(re.finditer(r'\*{2,}', sh))
630
+ # 個数が奇数の行はペアを特定できないため判定しない(誤検出を避ける)
631
+ if not runs or len(runs) % 2:
632
+ continue
633
+ for k, m in enumerate(runs):
634
+ prev = sh[m.start() - 1] if m.start() > 0 else ''
635
+ nxt = sh[m.end():m.end() + 1]
636
+ if k % 2 == 0: # 開き側: 内側=直後、外側=直前
637
+ ok = (not is_space(nxt)
638
+ and (not is_punct(nxt) or is_space(prev) or is_punct(prev)))
639
+ else: # 閉じ側: 内側=直前、外側=直後
640
+ ok = (not is_space(prev)
641
+ and (not is_punct(prev) or is_space(nxt) or is_punct(nxt)))
642
+ if not ok:
643
+ hits.append((no, '`%s`の外側に空白が要る: %s'
644
+ % (m.group(0), ln.strip()[:80])))
645
+ break
646
+ return hits
647
+
648
+
649
+ DELIM_ROW = re.compile(r'^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$')
650
+
651
+
652
+ def count_cells(row):
653
+ """表の行のセル数を返す。`\\|`以外の`|`はインラインコードの中でもセルの区切りになる(GFMの規則)。"""
654
+ s = row.strip().replace('\\|', '')
655
+ if s.startswith('|'):
656
+ s = s[1:]
657
+ if s.endswith('|'):
658
+ s = s[:-1]
659
+ return s.count('|') + 1
660
+
661
+
662
+ def check_tables(lines):
663
+ """表の列数の不一致を検出する。列数が見出し行と違う行は、セルが欠けるか、はみ出したセルが表示されない。"""
664
+ hits, rows, i = [], content_lines(lines), 0
665
+ while i < len(rows) - 1:
666
+ (no, head), (no2, delim) = rows[i], rows[i + 1]
667
+ if not ('|' in head and '|' in delim and no2 == no + 1 and DELIM_ROW.match(delim)):
668
+ i += 1
669
+ continue
670
+ cols = count_cells(delim)
671
+ if count_cells(head) != cols:
672
+ hits.append((no, '見出し行と区切り行の列数が違う(%d列/%d列)。表として表示されない'
673
+ % (count_cells(head), cols)))
674
+ j = i + 2
675
+ while j < len(rows) and rows[j][0] == rows[j - 1][0] + 1 and rows[j][1].strip().startswith('|'):
676
+ n = count_cells(rows[j][1])
677
+ if n != cols:
678
+ hits.append((rows[j][0], '%d列ある(見出し行は%d列)。`|`をセルに書くなら`\\|`にする'
679
+ % (n, cols)))
680
+ j += 1
681
+ i = j
682
+ return hits
683
+
684
+
685
+ def check_placeholder(lines):
686
+ return [(no, ln.strip()) for no, ln in outside_fence(lines)
687
+ if '{{' in shadow(ln)]
688
+
689
+
690
+ def check_id_format(lines):
691
+ hits = []
692
+ for no, ln in outside_fence(lines):
693
+ m = PAT_ROW.match(ln)
694
+ if not m:
695
+ continue
696
+ cell = m.group(1)
697
+ if PAT_ID_NOHYPHEN.match(cell):
698
+ hits.append((no, '%s: 成果物略号とカテゴリ/連番をハイフンで区切る' % cell))
699
+ elif PAT_ID_LOWER.match(cell):
700
+ hits.append((no, '%s: IDの英字は大文字で書く' % cell))
701
+ return hits
702
+
703
+
704
+ def render(title, ref, hits, limit=MAX_REPORT):
705
+ body = ['[%s] %s (%d件)' % (ref, title, len(hits))]
706
+ for where, text in hits[:limit]:
707
+ label = 'L%d' % where if isinstance(where, int) else where
708
+ body.append(' %s: %s' % (label, text[:160]))
709
+ if len(hits) > limit:
710
+ body.append(' ... ほか%d件' % (len(hits) - limit))
711
+ return '\n'.join(body)
712
+
713
+
714
+ def inspect(repo, rel, lines, incoming=False, limit=MAX_REPORT):
715
+ """自動修正できない問題を検出し、報告文のリストを返す。"""
716
+ reports = []
717
+
718
+ def add(title, ref, hits):
719
+ if hits:
720
+ reports.append(render(title, ref, hits, limit))
721
+
722
+ _, unclosed = code_block_flags(lines)
723
+ add('コードブロックが閉じられていない。以降がすべてコードとして表示される', 'Markdown',
724
+ [(unclosed, 'ここで開いたコードブロック')] if unclosed else [])
725
+ add('HTMLコメントの閉じ方が不正', 'CLAUDE.md §2', check_html_comment(lines))
726
+ add('強調記法が太字にならない', 'Markdown', check_emphasis(lines))
727
+ add('表の列数が揃っていない', 'Markdown', check_tables(lines))
728
+ if not is_template(rel):
729
+ add('リンク切れ', 'Markdown', check_outgoing(repo, rel, lines))
730
+ if incoming:
731
+ add('このファイルの見出しへのリンクが切れている', 'Markdown', check_incoming(repo, rel))
732
+ if rel.startswith('docs/'):
733
+ add('未置換のプレースホルダ`{{`が残っている', 'CLAUDE.md §1', check_placeholder(lines))
734
+ add('IDの表記が規約外', 'CLAUDE.md §7', check_id_format(lines))
735
+ return reports
736
+
737
+
738
+ # ---------------------------------------------------------------------------
739
+ # 実行
740
+
741
+ def repo_root():
742
+ return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
743
+
744
+
745
+ def fix_file(repo, path, rel):
746
+ """和欧間スペースを修正し、見出しのアンカーが変わったらリンクも書き換える。
747
+
748
+ (修正内容, リンクの書き換え, 修正後の行) を返す。
749
+ """
750
+ src = io.open(path, encoding='utf-8').read()
751
+ fixed, changes = fix_text(src)
752
+ rewrites = []
753
+ if changes:
754
+ io.open(path, 'w', encoding='utf-8').write(fixed)
755
+ repo.set_slugs(rel, fixed.split('\n'))
756
+ mapping = anchor_changes(src.split('\n'), fixed.split('\n'))
757
+ if mapping:
758
+ rewrites = rewrite_anchor_links(repo, rel, mapping)
759
+ lines = read_lines(path) # 同じファイル内のリンクを書き換えた場合に備えて読み直す
760
+ return changes, rewrites, lines
761
+
762
+
763
+ def target_paths(repo, args):
764
+ if not args:
765
+ return [os.path.join(repo.root, r) for r in repo.markdown_files()]
766
+ return [p for p in args if os.path.isfile(p) and in_scope(repo.rel(p))]
767
+
768
+
769
+ def run_fix(args):
770
+ repo = Repo(repo_root())
771
+ total = 0
772
+ for path in target_paths(repo, args):
773
+ rel = repo.rel(path)
774
+ changes, rewrites, lines = fix_file(repo, path, rel)
775
+ total += len(changes)
776
+ if changes:
777
+ print('%-60s %d行を修正' % (rel, len(changes)))
778
+ for where, old, new in rewrites:
779
+ print(' リンクを書き換え %s: %s -> %s' % (where, old, new))
780
+ for r in inspect(repo, rel, lines):
781
+ print(' ! %s' % r.replace('\n', '\n '))
782
+ print('---\n合計%d行を修正' % total)
783
+ return 0
784
+
785
+
786
+ def run_check(args):
787
+ repo = Repo(repo_root())
788
+ problems = files = 0
789
+ for path in target_paths(repo, args):
790
+ rel = repo.rel(path)
791
+ src = io.open(path, encoding='utf-8').read()
792
+ lines = src.split('\n')
793
+ reports = inspect(repo, rel, lines, limit=10 ** 9)
794
+ _, changes = fix_text(src)
795
+ if changes:
796
+ reports.insert(0, render('和欧間スペースが残っている(--fixで直る)', 'CLAUDE.md §6',
797
+ [(no, after) for no, _, after in changes], 10 ** 9))
798
+ if reports:
799
+ files += 1
800
+ problems += sum(int(re.search(r'\((\d+)件\)', r.split('\n')[0]).group(1)) for r in reports)
801
+ print(rel)
802
+ for r in reports:
803
+ print(' ' + r.replace('\n', '\n '))
804
+ if problems:
805
+ print('---\n%dファイルに%d件の問題があります' % (files, problems))
806
+ return 1
807
+ print('問題はありません')
808
+ return 0
809
+
810
+
811
+ def run_hook():
812
+ try:
813
+ payload = json.load(sys.stdin)
814
+ except Exception:
815
+ return 0
816
+ ti = payload.get('tool_input') or {}
817
+ tr = payload.get('tool_response') or {}
818
+ path = tr.get('filePath') or ti.get('file_path')
819
+ if not path:
820
+ return 0
821
+ repo = Repo(repo_root())
822
+ try:
823
+ rel = repo.rel(path)
824
+ except ValueError:
825
+ return 0
826
+ if not in_scope(rel) or not os.path.isfile(path):
827
+ return 0
828
+
829
+ try:
830
+ changes, rewrites, lines = fix_file(repo, path, rel)
831
+ reports = inspect(repo, rel, lines, incoming=True)
832
+ except Exception as e:
833
+ sys.stderr.write('lint-text-style.py: %sの検査中にエラーが発生しました: %r\n' % (rel, e))
834
+ return 1
835
+
836
+ notes = []
837
+ if changes:
838
+ detail = '\n'.join(' L%d: %s' % (no, after[:120]) for no, _, after in changes[:MAX_REPORT])
839
+ if len(changes) > MAX_REPORT:
840
+ detail += '\n ... ほか%d行' % (len(changes) - MAX_REPORT)
841
+ notes.append('%sの和欧間スペースを自動削除しました(CLAUDE.md §6・%d行)。\n'
842
+ 'ファイルは書き換わっているため、以降の編集は最新内容を前提にしてください。\n%s'
843
+ % (rel, len(changes), detail))
844
+ if rewrites:
845
+ notes.append('見出しのアンカーが変わったため、そこへのリンクを書き換えました(%d件)。'
846
+ '書き換えたファイルを編集するときは、先に読み直してください。\n%s'
847
+ % (len(rewrites), '\n'.join(' %s: %s -> %s' % w for w in rewrites)))
848
+ note = '\n\n'.join(notes)
849
+
850
+ if reports:
851
+ sys.stderr.write(
852
+ ((note + '\n\n') if note else '')
853
+ + '自動修正できない問題があります: %s\n\n%s\n\n'
854
+ '該当箇所を修正してください。まだ作成していないファイルへのリンクは、作成すれば解消します。'
855
+ '検出が誤りだと判断した場合は、自分で修正を繰り返さず、その旨をユーザーに伝えてください。\n'
856
+ % (rel, '\n\n'.join(reports)))
857
+ return 2
858
+
859
+ if note:
860
+ print(json.dumps({
861
+ 'systemMessage': '表記規約: %sを自動修正しました(和欧間スペース%d行・リンク%d件)'
862
+ % (rel, len(changes), len(rewrites)),
863
+ 'hookSpecificOutput': {
864
+ 'hookEventName': 'PostToolUse',
865
+ 'additionalContext': note,
866
+ },
867
+ }, ensure_ascii=False))
868
+ return 0
869
+
870
+
871
+ if __name__ == '__main__':
872
+ if len(sys.argv) > 1 and sys.argv[1] == '--fix':
873
+ sys.exit(run_fix(sys.argv[2:]))
874
+ if len(sys.argv) > 1 and sys.argv[1] == '--check':
875
+ sys.exit(run_check(sys.argv[2:]))
876
+ sys.exit(run_hook())