@tyhld/conductor 0.12.132 → 0.12.134

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.
@@ -1202,7 +1202,8 @@ def _wrapper_danger(command: str, depth: int = 0, cwd=None):
1202
1202
  toks = tokens_of(seg)
1203
1203
  v = verb_of(toks)
1204
1204
  hit = (_secret_danger(seg, v, toks, cwd) or _bulk_copy_danger(v, toks, cwd)
1205
- or _recursive_read_danger(v, toks, cwd) or _admin_merge_danger(v, toks))
1205
+ or _recursive_read_danger(v, toks, cwd, seg)
1206
+ or _admin_merge_danger(v, toks))
1206
1207
  if hit:
1207
1208
  return f'{hit} ({where})'
1208
1209
  # ★抜け道も包みの中で測り直す(`bash -c "git push origin main"` を素通りさせない)。
@@ -1285,7 +1286,8 @@ def _var_expansion_danger(command: str, cwd=None):
1285
1286
  toks = tokens_of(seg)
1286
1287
  v = verb_of(toks)
1287
1288
  hit = (_secret_danger(seg, v, toks, cwd) or _bulk_copy_danger(v, toks, cwd)
1288
- or _recursive_read_danger(v, toks, cwd) or _admin_merge_danger(v, toks))
1289
+ or _recursive_read_danger(v, toks, cwd, seg)
1290
+ or _admin_merge_danger(v, toks))
1289
1291
  if hit:
1290
1292
  return hit
1291
1293
  hit = (_guard_write_scan(expanded, cwd) or _env_write_scan(expanded, cwd)
@@ -1407,6 +1409,20 @@ def _existing_dir(arg: str, cwd=None):
1407
1409
  return None
1408
1410
 
1409
1411
 
1412
+ def _existing_file(arg: str, cwd=None):
1413
+ """引数が実在のファイル(近道を解いた先を含む)なら、その場所を返す。
1414
+
1415
+ ★「実在が確かめられた」ときだけ返す(確かめられない道のりは None=守る側へ倒す)。
1416
+ """
1417
+ if not arg or arg.startswith('-'):
1418
+ return None
1419
+ real = resolved_path(arg, cwd)
1420
+ try:
1421
+ return real if os.path.isfile(real) else None
1422
+ except Exception: # noqa: BLE001
1423
+ return None
1424
+
1425
+
1410
1426
  def _bulk_copy_danger(verb: str, tokens, cwd=None):
1411
1427
  """フォルダごとの複製・固め・同期・リンクで、中に秘密が在れば理由を返す。"""
1412
1428
  if verb not in _BULK_VERBS:
@@ -1465,7 +1481,43 @@ def _search_excludes(args):
1465
1481
  return [x.strip().strip('"').strip("'") for x in out if x]
1466
1482
 
1467
1483
 
1468
- def _recursive_read_danger(verb: str, tokens, cwd=None):
1484
+ def _quote_fragment(seg) -> bool:
1485
+ """この区切りが【引用符の途中で千切れた切れ端】か(閉じていない引用符で終わる)。
1486
+
1487
+ 【なぜ要るか(実測 便 3be099ba・2026-10-10)】
1488
+ 止める側の区切り(split_segments)は引用符の中でも機械的に割る(便 ad6b5db9・正しい設計)。
1489
+ そのため探す言葉に当て字の縦棒(`\\|`)を書いた形
1490
+ <検索の道具> -rn "a\\|b" <実在のフォルダ>
1491
+ は `"a\\` と `b" <実在のフォルダ>` に千切れ、**検索の道具の側に場所が1つも残らない**。
1492
+ すると「探す場所を書いていない」と読めてしまい、作業場所(リポの根)に倒れて
1493
+ 根の秘密ファイルに当たり、読むだけの検索が danger で止まっていた(実地 便 3bbde2e3)。
1494
+
1495
+ 【どう使うか】切れ端では**作業場所に倒さない**(その切れ端だけでは場所が読めないため)。
1496
+ ★止める側は1件も減らない:同じ命令は本物の区切り(split_commands・引用符を守る割り方)でも
1497
+ 測り直すので(_real_segments)、場所を本当に書いていない形
1498
+ (`<検索の道具> -rn "a\\|b"` だけ)は、そちらで今までどおり作業場所として止まる。
1499
+ """
1500
+ text = seg or ''
1501
+ quote = None
1502
+ i, n = 0, len(text)
1503
+ while i < n:
1504
+ c = text[i]
1505
+ if quote:
1506
+ if c == '\\' and quote != "'" and i + 1 < n:
1507
+ i += 2
1508
+ continue
1509
+ if c == quote:
1510
+ quote = None
1511
+ elif c in ('"', "'"):
1512
+ quote = c
1513
+ elif c == '\\' and i + 1 < n:
1514
+ i += 2
1515
+ continue
1516
+ i += 1
1517
+ return quote is not None
1518
+
1519
+
1520
+ def _recursive_read_danger(verb: str, tokens, cwd=None, seg=None):
1469
1521
  """名前を書かずにフォルダの中を読む検索で、中に秘密が在れば理由を返す。
1470
1522
 
1471
1523
  ・grep 系は -r / -R / --recursive のとき
@@ -1475,6 +1527,10 @@ def _recursive_read_danger(verb: str, tokens, cwd=None):
1475
1527
  (★旗が無ければ追跡済みのファイルしか読まないので、今までどおり通す・便 227aeebb)
1476
1528
  ・探す場所が書かれていなければ、作業場所(cwd)を探す場所とみなす
1477
1529
  ★除外の指定(--exclude=.env* など)で外した名前は数えない=「秘密を除いて探す」は通る。
1530
+
1531
+ ★名指しの先が【実在のファイル】なら、そのファイル自体だけを判定する(便 3be099ba)。
1532
+ 再帰の旗が付いていても、読まれるのは名指しのファイルだけだからである(便 401fdc65 と同じ考え方=
1533
+ 実在が確かめられたときだけ狭める)。秘密の名前のファイルを名指しすれば今までどおり止まる。
1478
1534
  """
1479
1535
  args = tokens[1:] if tokens else []
1480
1536
  label = verb
@@ -1505,6 +1561,7 @@ def _recursive_read_danger(verb: str, tokens, cwd=None):
1505
1561
  patterns = _search_excludes(args)
1506
1562
  skip = pattern_arg_index(verb, args)
1507
1563
  roots = []
1564
+ files = []
1508
1565
  named = 0
1509
1566
  for pos, a in enumerate(args):
1510
1567
  if pos == skip or a.startswith('-'):
@@ -1513,11 +1570,28 @@ def _recursive_read_danger(verb: str, tokens, cwd=None):
1513
1570
  d = _existing_dir(a, cwd)
1514
1571
  if d:
1515
1572
  roots.append(d)
1573
+ continue
1574
+ f = _existing_file(a, cwd)
1575
+ if f:
1576
+ files.append(f)
1577
+ # ★名指しの先がファイルなら、そのファイル自体だけを判定する(便 3be099ba)。
1578
+ for f in files:
1579
+ sr = secret_reason(f)
1580
+ if sr:
1581
+ return f'{sr} touched by {label}'
1516
1582
  # ★探す場所が【読み切れなかった】ときも作業場所に倒す(安全側・前からの振る舞い)。
1517
1583
  # そのときは理由の文にそう書く=職人が「名指ししたのに違う場所の名前が出た」と
1518
1584
  # 読み違えないため(便 623cfb85・833c280c の実地。判定は1つも変えていない)。
1519
1585
  note = ''
1520
1586
  if not roots:
1587
+ # 名指しの先が実在のファイルだけ=読むのはそのファイルだけなので、作業場所に倒さない
1588
+ # (上で1つずつ判定済み=秘密なら止めてある・便 3be099ba の原因①)。
1589
+ if files:
1590
+ return None
1591
+ # 引用符の途中で千切れた切れ端は、場所をこの切れ端から読めないだけなので倒さない
1592
+ # (本物の区切りで測り直す側が、場所を書いていない形を今までどおり止める・原因②)。
1593
+ if _quote_fragment(seg):
1594
+ return None
1521
1595
  base = cwd if (cwd and os.path.isabs(cwd)) else os.getcwd()
1522
1596
  roots = [os.path.realpath(base)]
1523
1597
  note = ('(書かれた場所を読み切れないので作業場所として判定)' if named
@@ -4887,6 +4961,11 @@ _DISC_WORKCOPY = ('リポジトリの中の部品の置き場(node_modules な
4887
4961
  '(記録される場所の中に出来る・片付けも番人に止められる)。'
4888
4962
  '使い捨ての置き場は /tmp/claude-1000/ の下にする(鉄則13)。'
4889
4963
  '例: git clone --no-hardlinks <リポの実在のパス> /tmp/claude-1000/karaburi-<便IDの頭8文字>')
4964
+ _DISC_WAIT_LOOP = (
4965
+ 'CI・合流・配備・公開の完了を、繰り返し(until・while・for + sleep)で待たない。'
4966
+ 'CI は gh run watch --exit-status を1回打って前面で待ち切る。'
4967
+ '状態を見るだけなら gh pr checks・gh pr view・gh run view を1回ずつ打つ(どれも即返る)。'
4968
+ '背景で走らせたときは、その命令の完了の知らせをこの手番の中で待つ(鉄則の「便の終え方」⓪(c))')
4890
4969
 
4891
4970
 
4892
4971
  def _discipline_tokens(command: str):
@@ -5290,12 +5369,161 @@ def _workcopy_scan(command: str, cwd=None, depth: int = 0):
5290
5369
  return None
5291
5370
 
5292
5371
 
5372
+ # ═════════════════════════════════════════════════════════════════════════════
5373
+ # 待ちの繰り返し(作法・便 de82bc3a・けいさん確定 2026-10-10)
5374
+ #
5375
+ # 【なぜ要るか(実地2便・どちらも devlog の規則の例外として未承認)】
5376
+ # ・812c68de … 合流の完了待ちに `until … ; do sleep …; done` を使った。
5377
+ # ・3c93bfc1 … CI の完了待ちに `until grep -q 'exit=' <CI の記録>; do sleep 20; done` を使った。
5378
+ # 便の禁止「CI や合流を待つ時は繰り返しを使わず、gh pr checks・gh pr view を1回ずつ打つ」が
5379
+ # 2便続けて破られたのに、番人はこの形を1度も止めていなかった(=職人の自制だけに任せていた)。
5380
+ #
5381
+ # 【止める形】until / while / for の繰り返しの中に sleep が在り、かつ その繰り返しの
5382
+ # 【条件か中身】で CI・合流・配備・公開の状態(またはその記録ファイル)を見に行く形。
5383
+ # ・道具で直に見る形 … gh pr / gh run / gh workflow / gh release / gh api、
5384
+ # git ls-remote / merge-base / fetch、npm view / info / dist-tag、配備の道具
5385
+ # ・記録ファイルで見る形 … 読むだけの道具(grep・cat・tail・jq・[ など)の引数に、
5386
+ # CI・合流・配備・公開の記録だと読める名前(ci / pr / merge / deploy / release /
5387
+ # publish / workflow / actions)が入っている形
5388
+ #
5389
+ # 【止めない形(通常の待機は1つも巻き込まない)】
5390
+ # ・sleep の無い繰り返し(`for f in test_*.py; do python3 "$f"; done`)
5391
+ # ・CI と関係の無い繰り返し(`until [ -f /tmp/claude-1000/ready.flag ]; do sleep 2; done`)
5392
+ # ・1回だけの sleep(`sleep 60`=配信の読み置きを待つ)
5393
+ # ・道具自身が1回の命令で待つ形(`gh run watch --exit-status`・`gh pr checks --watch`)
5394
+ # ・状態を1回打つ形(`gh pr checks 301`・`gh pr view 301 --json state`・`gh run view 123`)
5395
+ #
5396
+ # 【★どこまで見えるか(限界・README にも書く)】番人は字面で測るので、
5397
+ # 繰り返しの中の呼び出しを【関数に寄せた形】(鉄則7 の4段の塊の `V state .state` など)には
5398
+ # 当たらない。塊は上限(WAIT)付きで段の結果を出す決められた待ちなので、通したままにする。
5399
+ # 見る先が変数で決まる形(`until grep -q x "$LOG"`)にも当たらない。
5400
+ # ═════════════════════════════════════════════════════════════════════════════
5401
+
5402
+ #: 繰り返しの頭に立つ語と、その終わりの語。
5403
+ _LOOP_HEADS = frozenset({'until', 'while', 'for'})
5404
+ _LOOP_END = 'done'
5405
+
5406
+ #: 繰り返しの中で「CI・合流・配備・公開の状態」を見に行く道具(頭の語 → 続く語の集合)。
5407
+ _WAIT_WATCH_SUBS = {
5408
+ 'gh': frozenset({'pr', 'run', 'workflow', 'release', 'api'}),
5409
+ 'git': frozenset({'ls-remote', 'merge-base', 'fetch'}),
5410
+ 'npm': frozenset({'view', 'info', 'dist-tag'}),
5411
+ }
5412
+ #: 続く語を問わず「配備の状態」を見に行く道具。
5413
+ _WAIT_WATCH_HEADS = frozenset({'vercel', 'wrangler'})
5414
+ #: 記録ファイルを読むだけの道具(繰り返しの条件によく使う形)。
5415
+ _WAIT_READ_HEADS = frozenset({'grep', 'egrep', 'fgrep', 'rg', 'ag', 'cat', 'tac', 'tail', 'head',
5416
+ 'wc', 'jq', 'test', '[', '[[', 'stat', 'awk', 'sed'})
5417
+ #: CI・合流・配備・公開の記録だと読める名前の部品(名前を `-_.` で割った1つと丸ごと一致する物)。
5418
+ _WAIT_RECORD_WORDS = frozenset({'ci', 'pr', 'merge', 'deploy', 'release', 'publish',
5419
+ 'workflow', 'workflows', 'actions'})
5420
+ _WAIT_NAME_SPLIT_RE = re.compile(r'[-_.]+')
5421
+ _WAIT_TRAILING_DIGITS_RE = re.compile(r'\d+$')
5422
+
5423
+
5424
+ def _wait_record_arg(words):
5425
+ """引数に「CI・合流・配備・公開の記録」と読める名前が在れば True。"""
5426
+ for a in words[1:]:
5427
+ name = str(a).rstrip('/').rsplit('/', 1)[-1]
5428
+ if not name:
5429
+ continue
5430
+ for part in _WAIT_NAME_SPLIT_RE.split(name):
5431
+ if _WAIT_TRAILING_DIGITS_RE.sub('', part) in _WAIT_RECORD_WORDS:
5432
+ return True
5433
+ return False
5434
+
5435
+
5436
+ def _wait_watch_words(words):
5437
+ """この道具が「CI・合流・配備・公開の状態」を見る形なら、その名前を返す。"""
5438
+ if not words:
5439
+ return None
5440
+ head = words[0]
5441
+ subs = _WAIT_WATCH_SUBS.get(head)
5442
+ if subs is not None:
5443
+ nxt = words[1] if len(words) > 1 else ''
5444
+ return f'{head} {nxt}' if nxt in subs else None
5445
+ if head in _WAIT_WATCH_HEADS:
5446
+ return head
5447
+ if head in _WAIT_READ_HEADS and _wait_record_arg(words):
5448
+ return f'{head} <CI・合流・配備の記録>'
5449
+ return None
5450
+
5451
+
5452
+ def _wait_segments(texts):
5453
+ """与えた字面を、本物の区切りだけで割った1コマンドずつにして並べる。"""
5454
+ out = []
5455
+ for text in texts:
5456
+ out.extend(split_commands(text, bodies=False))
5457
+ return out
5458
+
5459
+
5460
+ def _wait_watch_hit(segments, depth=0):
5461
+ """繰り返しの中に「状態を見に行く形」が在れば、その名前を返す。"""
5462
+ for seg in segments:
5463
+ hit = _wait_watch_words(_tool_words(tokens_of(seg)))
5464
+ if hit:
5465
+ return hit
5466
+ if depth < _UNWRAP_MAX_DEPTH:
5467
+ inner = _subst_payloads(seg)
5468
+ if inner:
5469
+ hit = _wait_watch_hit(_wait_segments(inner), depth + 1)
5470
+ if hit:
5471
+ return hit
5472
+ return None
5473
+
5474
+
5475
+ def _wait_has_sleep(segments):
5476
+ """繰り返しの中で sleep を呼んでいれば True。"""
5477
+ for seg in segments:
5478
+ words = _tool_words(tokens_of(seg))
5479
+ if words and words[0] == 'sleep':
5480
+ return True
5481
+ return False
5482
+
5483
+
5484
+ def _loop_regions(command: str):
5485
+ """until / while / for … done の範囲ごとに、その中の1コマンドの並びを返す。
5486
+
5487
+ ★入れ子は外側にも内側にも同じセグメントが入る(どちらで当たっても同じ形なので、
5488
+ どちらを先に見ても結果は変わらない)。
5489
+ """
5490
+ regions, stack = [], []
5491
+ for seg in split_commands(command, bodies=False):
5492
+ toks = tokens_of(seg)
5493
+ if not toks:
5494
+ continue
5495
+ head = toks[0].lower()
5496
+ if head in _LOOP_HEADS:
5497
+ stack.append([])
5498
+ for region in stack:
5499
+ region.append(seg)
5500
+ if head == _LOOP_END and stack:
5501
+ regions.append(stack.pop())
5502
+ regions.extend(region for region in stack if region) # done が足りない形も見る
5503
+ return regions
5504
+
5505
+
5506
+ def _disc_wait_loop(command: str):
5507
+ """CI・合流・配備・公開の完了を繰り返しで待つ形なら、職人へ返す1行を返す。"""
5508
+ for region in _loop_regions(command):
5509
+ if not _wait_has_sleep(region):
5510
+ continue
5511
+ hit = _wait_watch_hit(region)
5512
+ if hit:
5513
+ return f'{_DISC_WAIT_LOOP}(当たった形: 繰り返しの中の {hit} + sleep)'
5514
+ return None
5515
+
5516
+
5293
5517
  def _discipline_scan(command: str, cwd=None):
5294
- """作法の4件(git add -A・cd の && とリダイレクト・全体の再帰検索・部品の置き場への写し)。
5518
+ """作法の5件(git add -A・cd の && とリダイレクト・全体の再帰検索・部品の置き場への写し・
5519
+ CI や合流の完了を繰り返しで待つ形)。
5295
5520
 
5296
5521
  当たれば職人へ返す1行、無ければ None。
5297
5522
  """
5298
5523
  hit = _workcopy_scan(command, cwd)
5524
+ if hit:
5525
+ return hit
5526
+ hit = _disc_wait_loop(command)
5299
5527
  if hit:
5300
5528
  return hit
5301
5529
  toks = _discipline_tokens(command)
@@ -5345,7 +5573,7 @@ def _bash_danger(command: str, cwd=None):
5345
5573
  if hit:
5346
5574
  return hit
5347
5575
  # ★フォルダごとの持ち出し(名前を書かない複製・固め・同期・リンク)。
5348
- hit = (_bulk_copy_danger(v, toks, cwd) or _recursive_read_danger(v, toks, cwd)
5576
+ hit = (_bulk_copy_danger(v, toks, cwd) or _recursive_read_danger(v, toks, cwd, seg)
5349
5577
  or _admin_merge_danger(v, toks))
5350
5578
  if hit:
5351
5579
  return hit
@@ -0,0 +1,314 @@
1
+ #!/usr/bin/env python3
2
+ """名指しした先を読み切る検索の判定の検査(便 3be099ba)。
3
+
4
+ 実行: python3 scripts/hooks/test_named_target_search.py
5
+ 1件でも期待と違えば exit 1。
6
+
7
+ 【なぜ要るか(実地2便・2026-10-10)】
8
+ TYHLD-platform の2便が、読むだけの検索で同じ `danger` に止められ、作業が0件で終わった
9
+ (どちらも職人は便の定めどおり正しく停止した)。
10
+
11
+ 便 1ff7b915 … <検索の道具> -rn '語' <実在のファイル1つ> | head -3
12
+ 便 3bbde2e3 … <検索の道具> -rn "a\\|b\\|c" <実在のフォルダ3つ> 2>/dev/null | head -60
13
+ 番人の文(2便とも同じ)… danger: secret file (…) inside <リポの根> read without naming it by …
14
+
15
+ 原因は2つで、どちらも「名指しした先を読み切れずに作業場所(リポの根)へ倒した」結果だった。
16
+ ① 名指しの先が【ファイル】だと、実在のフォルダを探す読み方では1件も拾えず、場所を書いて
17
+ いない形と同じに扱われて作業場所に倒れた。
18
+ ② 探す言葉に当て字の縦棒(`\\|`)が入ると、止める側の区切り(引用符の中でも機械的に割る=
19
+ 便 ad6b5db9 の正しい設計)が `"a\\` と `b\\` と `c" <フォルダ>` に千切り、検索の道具の側に
20
+ 場所が1つも残らなくなって、やはり作業場所に倒れた。
21
+
22
+ 【ここで固定すること】
23
+ (a) 名指しの先が実在のファイルなら、そのファイル自体だけを判定する(=通る)
24
+ (b) 秘密の名前のファイルを名指しすれば、今までどおり止まる
25
+ (c) 引用符の途中で千切れた切れ端では作業場所に倒さず、本物の区切りの側で名指しの場所を判定する
26
+ (d) 安全側の振る舞いは1つも外さない(場所を書かない・実在しない場所・しるし入りの場所・
27
+ 作業場所の根・点1つ・秘密を含むフォルダ・包みの中・変数ごし)
28
+ (e) ほかの危険の判定(秘密のファイルの読み・保護ブランチへの push など)は、同じ行に
29
+ 混ざっていても今までどおり先に当たる
30
+ (f) 空振り確認(直しを外すと、この台本が落ちる)
31
+
32
+ ★秘密として扱う名前の判定は1文字も変えていない(本物が探す先の中に在れば今までどおり止まる)。
33
+ ★この台本は検索の道具の名前を素の字で置かない(組み立てて使う=既存の作法)。
34
+ """
35
+ import os
36
+ import subprocess
37
+ import sys
38
+ import tempfile
39
+
40
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
41
+
42
+ import policy # noqa: E402
43
+
44
+ failures = []
45
+
46
+
47
+ def check(label, got, want):
48
+ ok = got == want
49
+ if not ok:
50
+ failures.append(f'{label}: got={got!r} want={want!r}')
51
+ print(f'{"OK " if ok else "NG "} {label:62} {str(got)[:40]}')
52
+
53
+
54
+ # ── 使い捨ての作り物(この台本のコードが作る=職人の命令の字面には出ない)────────
55
+ ROOT = tempfile.mkdtemp(prefix='named-target-')
56
+ SITE = os.path.join(ROOT, 'site') # 作業場所(根に秘密の形の名前が在る)
57
+ SUBS = ('services/calendar', 'packages/calendar', 'packages/notify', 'services/lp/src/lib')
58
+ for _s in SUBS:
59
+ os.makedirs(os.path.join(SITE, _s))
60
+ os.makedirs(os.path.join(SITE, 'sub', 'inner'))
61
+ ENV = '.env'
62
+ NPMRC = '.npm' + 'rc'
63
+ with open(os.path.join(SITE, NPMRC), 'w') as f:
64
+ f.write('DUMMY=placeholder\n')
65
+ with open(os.path.join(SITE, 'sub', 'inner', ENV + '.local'), 'w') as f:
66
+ f.write('DUMMY=placeholder\n')
67
+ with open(os.path.join(SITE, '.gitignore'), 'w') as f:
68
+ f.write(ENV + '.local\n')
69
+ for _s in SUBS:
70
+ with open(os.path.join(SITE, _s, 'a.ts'), 'w') as f:
71
+ f.write('needle\n')
72
+ CLEAN = os.path.join(ROOT, 'clean') # 秘密の形の名前を含まない場所
73
+ os.makedirs(os.path.join(CLEAN, 'deep'))
74
+ with open(os.path.join(CLEAN, 'deep', 'b.md'), 'w') as f:
75
+ f.write('needle\n')
76
+ _env = dict(os.environ, GIT_AUTHOR_NAME='p', GIT_AUTHOR_EMAIL='p@x',
77
+ GIT_COMMITTER_NAME='p', GIT_COMMITTER_EMAIL='p@x')
78
+ for _argv in (['git', 'init', '-q'], ['git', 'add', 'services', '.gitignore'],
79
+ ['git', 'commit', '-q', '-m', 'init']):
80
+ subprocess.run(_argv, cwd=SITE, env=_env, capture_output=True)
81
+
82
+ G = 'g' + 'rep'
83
+ RG = 'r' + 'g'
84
+ AG = 'a' + 'g'
85
+ GG = 'git ' + 'grep'
86
+ NULL = '/dev/' + 'null'
87
+ D1 = os.path.join(SITE, 'services/calendar')
88
+ D3 = ' '.join(os.path.join(SITE, s) for s in SUBS[:3])
89
+ FILE1 = os.path.join(SITE, 'services/lp/src/lib/a.ts')
90
+ FILE2 = os.path.join(SITE, 'services/calendar/a.ts')
91
+ SECRET = os.path.join(SITE, NPMRC)
92
+ SUB = os.path.join(SITE, 'sub')
93
+
94
+
95
+ def decide(cmd, cwd=SITE):
96
+ return policy.decide_bash(cmd, cwd)
97
+
98
+
99
+ def kind(cmd, cwd=SITE):
100
+ """allow / gate / deny:<種類> を返す(deny は理由の頭で分ける)。"""
101
+ r = decide(cmd, cwd)
102
+ if r['decision'] != 'deny':
103
+ return r['decision']
104
+ return 'deny:' + (r['reason'] or '').split(':', 1)[0]
105
+
106
+
107
+ # ═════════════════════════════════════════════════════════════════════════════
108
+ # (a) 名指しの先が実在のファイルなら、そのファイル自体だけを判定する
109
+ # ═════════════════════════════════════════════════════════════════════════════
110
+ print('── (a) 名指しの先がファイルなら、そのファイルだけを判定する ' + '─' * 20)
111
+ NAMED_FILE = [
112
+ ('a1 実地 便 1ff7b915 の形(再帰の旗つき・ファイル1つ・後ろに別の命令)',
113
+ G + " -rn 'needle' " + FILE1 + ' | head -3'),
114
+ ('a2 実地 便 1ff7b915 の全文の形(前に別の命令・ファイル1つ)',
115
+ "node -e 'console.log(1)' ; " + G + " -rn 'needle' " + FILE1 + ' | head -3'),
116
+ ('a3 ファイル2つを名指し', G + " -rn 'needle' " + FILE1 + ' ' + FILE2),
117
+ ('a4 ファイル1つ(行の番号と名前だけの旗)', G + ' -rln needle ' + FILE1),
118
+ ('a5 ファイル1つ(--recursive の長い旗)', G + ' --recursive -n needle ' + FILE1),
119
+ ('a6 ファイル1つ(隠しも読む旗つきの別の道具)', RG + ' --hidden needle ' + FILE1),
120
+ ('a7 ファイル1つ(記録から外した物まで読む旗つき)', RG + ' -uu needle ' + FILE1),
121
+ ('a8 ファイル1つ(別の道具 ag)', AG + ' --hidden needle ' + FILE1),
122
+ ('a9 ファイル1つ(記録の外まで読む旗つきの git grep)',
123
+ GG + ' --untracked -n needle -- services/lp/src/lib/a.ts'),
124
+ ('a10 ファイルと秘密を含まないフォルダを並べる', G + ' -rn needle ' + FILE1 + ' ' + CLEAN),
125
+ ('a11 ファイル(近道を解いた先・.. 入りの道のり)',
126
+ G + ' -rn needle ' + os.path.join(SITE, 'services', '..', 'services/lp/src/lib/a.ts')),
127
+ ]
128
+ for label, cmd in NAMED_FILE:
129
+ check(label, kind(cmd), 'allow')
130
+
131
+ # ═════════════════════════════════════════════════════════════════════════════
132
+ # (b) 秘密の名前のファイルを名指しすれば、今までどおり止まる
133
+ # ═════════════════════════════════════════════════════════════════════════════
134
+ print('── (b) 秘密の名前のファイルを名指しすれば止まる ' + '─' * 28)
135
+ check('b1 秘密のファイルを名指し(再帰の旗つき)', kind(G + " -rn 'x' " + SECRET), 'deny:danger')
136
+ check('b2 秘密のファイルを名指し(隠しも読む旗つき)',
137
+ kind(RG + ' --hidden x ' + SECRET), 'deny:danger')
138
+ check('b3 秘密のファイルを名指し(記録の外まで読む旗つき)',
139
+ kind(GG + ' --untracked -n x -- ' + NPMRC), 'deny:danger')
140
+ check('b4 秘密のファイルと普通のファイルを並べる', kind(G + ' -rn x ' + FILE1 + ' ' + SECRET),
141
+ 'deny:danger')
142
+ check('b5 下の階層の秘密のファイルを名指し',
143
+ kind(G + ' -rn x ' + os.path.join(SITE, 'sub', 'inner', ENV + '.local')), 'deny:danger')
144
+ check('b6 名指しの先がファイルでも理由は「名指しの先に当たった」形',
145
+ decide(G + " -rn 'x' " + SECRET)['reason'].startswith('danger: secret file'), True)
146
+ check('b7 その理由に作業場所の名前(倒した印)が出ない',
147
+ 'inside ' in decide(G + " -rn 'x' " + SECRET)['reason'], False)
148
+
149
+ # ═════════════════════════════════════════════════════════════════════════════
150
+ # (c) 引用符の途中で千切れた切れ端では作業場所に倒さない
151
+ # ═════════════════════════════════════════════════════════════════════════════
152
+ print('── (c) 切れ端では作業場所に倒さず、名指しの場所を判定する ' + '─' * 18)
153
+ FRAGMENT_OK = [
154
+ ('c1 実地 便 3bbde2e3 の形(当て字の縦棒+実在の3フォルダ)',
155
+ G + ' -rn "a\\|b\\|c" ' + D3 + ' 2>' + NULL + ' | head -60'),
156
+ ('c2 当て字の縦棒+実在の1フォルダ', G + ' -rn "a\\|b" ' + D1),
157
+ ('c3 当て字の縦棒+単引用符+実在の3フォルダ', G + " -rn 'a\\|b\\|c' " + D3),
158
+ ('c4 当て字の縦棒+名指しのファイル', G + ' -rn "a\\|b" ' + FILE1),
159
+ ('c5 引用符の中の素の縦棒+実在のフォルダ', G + ' -rn "a|b" ' + D1),
160
+ ('c6 引用符の中の semicolon+実在のフォルダ', G + ' -rn "a;b" ' + D1),
161
+ ('c7 当て字の縦棒+秘密を含まないフォルダ', G + ' -rn "a\\|b" ' + CLEAN),
162
+ ]
163
+ for label, cmd in FRAGMENT_OK:
164
+ check(label, kind(cmd), 'allow')
165
+
166
+ print('── (c) 切れ端でも、名指しの先に秘密が在れば止まる ' + '─' * 26)
167
+ check('c8 当て字の縦棒+秘密を含むフォルダ', kind(G + ' -rn "a\\|b" ' + SUB), 'deny:danger')
168
+ check('c9 当て字の縦棒+作業場所の根', kind(G + ' -rn "a\\|b" ' + SITE), 'deny:danger')
169
+ check('c10 当て字の縦棒+秘密の名前のファイル', kind(G + ' -rn "a\\|b" ' + SECRET), 'deny:danger')
170
+ check('c11 当て字の縦棒+場所を1つも書かない', kind(G + ' -rn "a\\|b"'), 'deny:danger')
171
+ check('c12 当て字の縦棒+実在しない場所',
172
+ kind(G + ' -rn "a\\|b" ' + os.path.join(SITE, 'nope')), 'deny:danger')
173
+ check('c13 当て字の縦棒+点1つ(作業場所)', kind(G + ' -rn "a\\|b" .'), 'deny:danger')
174
+ check('c14 当て字の縦棒+しるし(*)を含む場所',
175
+ kind(G + ' -rn "a\\|b" ' + SITE + '/services/*/x'), 'deny:danger')
176
+
177
+ # ═════════════════════════════════════════════════════════════════════════════
178
+ # (d) 安全側の振る舞いは1つも外していない
179
+ # ═════════════════════════════════════════════════════════════════════════════
180
+ print('── (d) 安全側の振る舞いは1つも外していない ' + '─' * 32)
181
+ SAFE = [
182
+ ('d1 場所を1つも書かない(作業場所を探す)', G + " -rn 'needle'"),
183
+ ('d2 作業場所の根を名指し', G + " -rn 'needle' " + SITE),
184
+ ('d3 点1つ(作業場所)を名指し', G + " -rn 'needle' ."),
185
+ ('d4 実在しない場所を名指し', G + " -rn 'needle' " + os.path.join(SITE, 'nope')),
186
+ ('d5 しるし(*)を含む場所', G + " -rn 'needle' " + SITE + '/services/*/x'),
187
+ ('d6 秘密を含む下の階層のフォルダを名指し', G + " -rn 'needle' " + SUB),
188
+ ('d7 隠しも読む旗つきの道具で根を探す', RG + ' --hidden needle ' + SITE),
189
+ ('d8 記録の外まで読む旗つきで根を探す', GG + ' --untracked -n needle'),
190
+ ('d9 名前を並べて読ませる形', 'find ' + SITE + ' -type f -exec cat {} +'),
191
+ ('d10 名前を並べて渡す形(探す道具)', 'find ' + SITE + ' -type f | xargs ' + RG + ' -l needle'),
192
+ ('d11 包みの中の再帰検索', 'bash -c "' + G + ' -rn needle ' + SITE + '"'),
193
+ ('d12 変数ごしの再帰検索', 'D=' + SITE + '; ' + G + ' -rn needle "$D"'),
194
+ ('d13 フォルダごとの複製', 'cp -r ' + SITE + ' /tmp/claude-1000/x'),
195
+ ('d14 秘密のファイルを読む', 'cat ' + SECRET),
196
+ ]
197
+ for label, cmd in SAFE:
198
+ check(label, kind(cmd), 'deny:danger')
199
+
200
+ print('── (d) 通っていた形は1つも止まる側に変わっていない ' + '─' * 24)
201
+ PASS_THROUGH = [
202
+ ('d15 秘密を含まない場所の再帰検索', G + " -rn 'needle' " + CLEAN),
203
+ ('d16 場所を名指しした既定の検索', RG + ' needle ' + os.path.join(SITE, 'services')),
204
+ ('d17 記録の中だけを探す', GG + ' -n needle'),
205
+ ('d18 記録の中だけを探す(場所を名指し)', GG + ' -n needle -- services'),
206
+ ('d19 名指しのファイルを読む', 'cat ' + FILE1),
207
+ ('d20 名指しのファイルを探す(再帰の旗なし)', G + " -n 'needle' " + FILE1),
208
+ ('d21 秘密を含まない場所の find と読み', 'find ' + CLEAN + ' -type f -exec cat {} +'),
209
+ ('d22 探す言葉に引用符が1つ入る形(切れ端ではない)', G + ' -rn "it' + "'" + 's" ' + CLEAN),
210
+ ('d23 名指しの git add', 'git add services/calendar/a.ts'),
211
+ ('d24 状態を1回見る', 'gh pr checks 301'),
212
+ ]
213
+ for label, cmd in PASS_THROUGH:
214
+ check(label, kind(cmd), 'allow')
215
+
216
+ # ═════════════════════════════════════════════════════════════════════════════
217
+ # (e) ほかの危険の判定は、同じ行に混ざっていても先に当たる
218
+ # ═════════════════════════════════════════════════════════════════════════════
219
+ print('── (e) 混ざった形は今までどおり先に止まる ' + '─' * 32)
220
+ MIXED = [
221
+ ('e1 名指しのファイルの検索+秘密のファイルの読み',
222
+ G + ' -rn needle ' + FILE1 + '; cat ' + SECRET),
223
+ ('e2 名指しのファイルの検索+保護ブランチへの push',
224
+ G + ' -rn needle ' + FILE1 + '; git push origin main'),
225
+ ('e3 切れ端+保護ブランチへの push', G + ' -rn "a\\|b" ' + D1 + '; git push origin main'),
226
+ ('e4 切れ端+秘密のファイルの読み', 'cat ' + SECRET + ' | ' + G + ' "a\\|b"'),
227
+ ('e5 名指しのファイルの検索+フォルダごとの複製',
228
+ G + ' -rn needle ' + FILE1 + '; cp -r ' + SITE + ' /tmp/claude-1000/x'),
229
+ ('e6 名指しのファイルの検索+環境変数の露出',
230
+ G + ' -rn needle ' + FILE1 + '; echo $DATABASE_URL'),
231
+ ('e7 切れ端+保護を迂回する合流', G + ' -rn "a\\|b" ' + D1 + '; gh pr merge 1 --admin --merge'),
232
+ ]
233
+ for label, cmd in MIXED:
234
+ check(label, kind(cmd), 'deny:danger')
235
+ check('e8 名指しのファイルの検索+繰り返しで CI を待つ形(作法が当たる)',
236
+ kind(G + ' -rn needle ' + FILE1 + '; until gh pr checks 1; do sleep 20; done'),
237
+ 'deny:discipline')
238
+ check('e9 切れ端+繰り返しで CI を待つ形(作法が当たる)',
239
+ kind(G + ' -rn "a\\|b" ' + D1 + '; until gh pr checks 1; do sleep 20; done'),
240
+ 'deny:discipline')
241
+
242
+ # ═════════════════════════════════════════════════════════════════════════════
243
+ # (f) 空振り確認(直しを外すと落ちる)★関数を一時的に差し替えるだけ・ファイルは変えない
244
+ # ═════════════════════════════════════════════════════════════════════════════
245
+ print('── (f) 空振り確認(直しを外すと落ちる) ' + '─' * 34)
246
+ _real_existing_file = policy._existing_file
247
+ _real_quote_fragment = policy._quote_fragment
248
+
249
+ policy._existing_file = lambda arg, cwd=None: None # ①を外す
250
+ check('f1 ①を外すと「名指しのファイル」が作業場所に倒れて止まる',
251
+ kind(G + " -rn 'needle' " + FILE1), 'deny:danger')
252
+ check('f2 ①を外すと実地 便 1ff7b915 の形が止まる',
253
+ kind(G + " -rn 'needle' " + FILE1 + ' | head -3'), 'deny:danger')
254
+ check('f3 ①を外しても切れ端の形は通る(②は別の直し)', kind(G + ' -rn "a\\|b" ' + D1), 'allow')
255
+ policy._existing_file = _real_existing_file
256
+
257
+ policy._quote_fragment = lambda seg: False # ②を外す
258
+ check('f4 ②を外すと実地 便 3bbde2e3 の形が止まる',
259
+ kind(G + ' -rn "a\\|b\\|c" ' + D3 + ' 2>' + NULL + ' | head -60'), 'deny:danger')
260
+ check('f5 ②を外すと当て字の縦棒+実在のフォルダが止まる', kind(G + ' -rn "a\\|b" ' + D1),
261
+ 'deny:danger')
262
+ check('f6 ②を外しても名指しのファイルは通る(①は別の直し)',
263
+ kind(G + " -rn 'needle' " + FILE1), 'allow')
264
+ policy._quote_fragment = _real_quote_fragment
265
+
266
+ policy._existing_file = lambda arg, cwd=None: None
267
+ policy._quote_fragment = lambda seg: False # ①②の両方を外す
268
+ check('f7 ①②を外すと2便の形が2つとも止まる(直す前と同じ)',
269
+ (kind(G + " -rn 'needle' " + FILE1 + ' | head -3'),
270
+ kind(G + ' -rn "a\\|b\\|c" ' + D3 + ' 2>' + NULL + ' | head -60')),
271
+ ('deny:danger', 'deny:danger'))
272
+ policy._existing_file = _real_existing_file
273
+ policy._quote_fragment = _real_quote_fragment
274
+ check('f8 戻したら2便の形が2つとも通る',
275
+ (kind(G + " -rn 'needle' " + FILE1 + ' | head -3'),
276
+ kind(G + ' -rn "a\\|b\\|c" ' + D3 + ' 2>' + NULL + ' | head -60')),
277
+ ('allow', 'allow'))
278
+
279
+ # ═════════════════════════════════════════════════════════════════════════════
280
+ # (g) 切れ端の見分けそのもの(部品の単体)
281
+ # ═════════════════════════════════════════════════════════════════════════════
282
+ print('── (g) 切れ端の見分けの単体 ' + '─' * 44)
283
+ FRAG_UNIT = [
284
+ ('g1 閉じていない二重引用符で終わる', G + ' -rn "a\\', True),
285
+ ('g2 閉じていない単引用符で終わる', G + " -rn 'a\\", True),
286
+ ('g3 二重引用符が閉じている', G + ' -rn "a|b" ' + D1, False),
287
+ ('g4 引用符が1つも無い', G + ' -rn a ' + D1, False),
288
+ ('g5 二重引用符の中に単引用符が1つ', G + ' -rn "it\'s" ' + CLEAN, False),
289
+ ('g6 単引用符の中に二重引用符が1つ', G + " -rn 'a\"b' " + CLEAN, False),
290
+ ('g7 空の文字列', '', False),
291
+ ('g8 None', None, False),
292
+ ]
293
+ for label, seg, want in FRAG_UNIT:
294
+ check(label, policy._quote_fragment(seg), want)
295
+ check('g9 実在のファイルを返す(単体)', bool(policy._existing_file(FILE1)), True)
296
+ check('g10 実在のフォルダはファイルとして返さない(単体)', policy._existing_file(D1), None)
297
+ check('g11 実在しない道のりは返さない(単体)',
298
+ policy._existing_file(os.path.join(SITE, 'nope')), None)
299
+ check('g12 旗はファイルとして見ない(単体)', policy._existing_file('-rn'), None)
300
+
301
+ # ─────────────────────────────────────────────────────────────────────────────
302
+ # ★作り物を片付ける(使い捨ての場所に残骸を残さない・便 de82bc3a のコミット a5118c7 と同じ作法)
303
+ import shutil # noqa: E402
304
+
305
+ shutil.rmtree(ROOT, ignore_errors=True)
306
+ check('z1 作り物を片付けた', os.path.isdir(ROOT), False)
307
+
308
+ print()
309
+ if failures:
310
+ print(f'NG {len(failures)} 件')
311
+ for line in failures:
312
+ print(' ' + line)
313
+ sys.exit(1)
314
+ print('すべて OK')