@tyhld/conductor 0.12.148 → 0.12.150

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tyhld/conductor",
3
- "version": "0.12.148",
3
+ "version": "0.12.150",
4
4
  "description": "采配くん管制の見守りアプリ(conductor-agent)。各PCで常駐し、中央(devlog-tracker)へ定期的に生存報告(heartbeat)を送る常駐CLI。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -317,6 +317,8 @@ _REPORT_READ_TOOLS = frozenset({'Read', 'NotebookRead'})
317
317
  #: 報告の置き場を作る形で許す道具(これ以外の Bash は通さない)。
318
318
  _REPORT_MKDIR = 'mkdir'
319
319
  _REPORT_MKDIR_FLAGS = frozenset({'-p', '--parents', '-pv', '-v', '--verbose'})
320
+ #: 完了の知らせの道具を読み込む ToolSearch の query(これちょうどのときだけ通す)。
321
+ _COMPLETE_TOOL_SELECT = 'select:mcp__ai-kana__conductor_complete'
320
322
 
321
323
 
322
324
  def _report_store_dirs(env=None):
@@ -379,6 +381,11 @@ def after_danger_allowed(data, env=None):
379
381
  tin = {}
380
382
  if tool.rsplit('__', 1)[-1] == 'conductor_complete':
381
383
  return True
384
+ # ★完了の知らせの道具を読み込むだけの ToolSearch(便 e338e926・実地 便 0d887e4e・11265a0a・4cde5905)。
385
+ # 読み込まないと conductor_complete を呼べず、止まった便を報告で終えられない。
386
+ # query がこの1つちょうどのときだけ通す(ほかの道具の読み込みは今までどおり止める)。
387
+ if tool == 'ToolSearch':
388
+ return str(tin.get('query') or '') == _COMPLETE_TOOL_SELECT
382
389
  if tool in _REPORT_WRITE_TOOLS or tool in _REPORT_READ_TOOLS:
383
390
  return inside_report_store(tin.get('file_path') or tin.get('notebook_path') or '', env)
384
391
  if tool == 'Bash':
@@ -408,7 +415,8 @@ def danger_stop_reason(key, base, env=None):
408
415
  'danger: この便は番人が danger で止めたあとです。書き直さず・別の方法も別の道具も試さず、'
409
416
  '止められた命令の全文と番人の文を報告して停止してください(鉄則4・鉄則の常連 ⑤-2)。'
410
417
  'いま通すのは、報告の置き場の中のファイルを書く・直す・読む/その置き場を作る mkdir -p/'
411
- '完了の知らせ(conductor_complete)だけです。'
418
+ '完了の知らせ(conductor_complete と、その読み込み=ToolSearch の '
419
+ f'{_COMPLETE_TOOL_SELECT})だけです。'
412
420
  f'★誤って止まったときは、人が自分のターミナルで印を消します: rm -r {marker}'
413
421
  f'{base_reason}'
414
422
  )
@@ -1289,7 +1289,7 @@ def _wrapper_danger(command: str, depth: int = 0, cwd=None):
1289
1289
  toks = tokens_of(seg)
1290
1290
  v = verb_of(toks)
1291
1291
  hit = (_secret_danger(seg, v, toks, cwd) or _bulk_copy_danger(v, toks, cwd)
1292
- or _recursive_read_danger(v, toks, cwd, seg)
1292
+ or _recursive_read_danger(v, toks, cwd, seg, inner)
1293
1293
  or _admin_merge_danger(v, toks))
1294
1294
  if hit:
1295
1295
  return f'{hit} ({where})'
@@ -1338,14 +1338,23 @@ def _expand_local_vars(command: str, rounds: int = _VAR_EXPAND_ROUNDS) -> str:
1338
1338
 
1339
1339
  ★分からない変数はそのまま残す(勝手に空へ潰さない=別のコマンドに化けさせない)。
1340
1340
  """
1341
- text = command or ''
1341
+ return _expand_with_values(command or '', _local_var_values(command), rounds)
1342
+
1343
+
1344
+ def _local_var_values(command: str) -> dict:
1345
+ """同じコマンドの中の代入(`F=値` / `export F=値`)を {名前: 値} で返す。"""
1342
1346
  values = {}
1343
- for m in _VAR_ASSIGN_RE.finditer(text):
1347
+ for m in _VAR_ASSIGN_RE.finditer(command or ''):
1344
1348
  raw = m.group(2) or ''
1345
1349
  if len(raw) >= 2 and raw[0] in ('"', "'") and raw[-1] == raw[0]:
1346
1350
  raw = raw[1:-1]
1347
1351
  if raw:
1348
1352
  values[m.group(1)] = raw
1353
+ return values
1354
+
1355
+
1356
+ def _expand_with_values(text: str, values: dict, rounds: int = _VAR_EXPAND_ROUNDS) -> str:
1357
+ """values に在る変数だけを展開する(分からない変数はそのまま残す)。"""
1349
1358
  if not values:
1350
1359
  return text
1351
1360
 
@@ -1373,7 +1382,7 @@ def _var_expansion_danger(command: str, cwd=None):
1373
1382
  toks = tokens_of(seg)
1374
1383
  v = verb_of(toks)
1375
1384
  hit = (_secret_danger(seg, v, toks, cwd) or _bulk_copy_danger(v, toks, cwd)
1376
- or _recursive_read_danger(v, toks, cwd, seg)
1385
+ or _recursive_read_danger(v, toks, cwd, seg, expanded)
1377
1386
  or _admin_merge_danger(v, toks))
1378
1387
  if hit:
1379
1388
  return hit
@@ -1613,7 +1622,38 @@ def _quote_fragment(seg) -> bool:
1613
1622
  return _open_quote(seg) is not None
1614
1623
 
1615
1624
 
1616
- def _recursive_read_danger(verb: str, tokens, cwd=None, seg=None):
1625
+ #: `*` を展開して当てる数の上限(超えたら決まらない扱い=作業場所に倒す)。
1626
+ _READ_GLOB_LIMIT = 200
1627
+
1628
+
1629
+ def _expand_read_arg(arg: str, values: dict, cwd=None):
1630
+ """探す場所1つを展開する。返り: 確かめる道のりの一覧/None(決まらない)。
1631
+
1632
+ ・`$名前`・`${名前}` は values(同じ命令の中の代入)で展開する。残れば決まらない。
1633
+ ・`*` は glob で展開する(★隠しファイルは当てない=シェルと同じ)。0件・上限超えは決まらない。
1634
+ ・どちらも含まない引数は、そのまま1つ返す(今までどおり)。
1635
+ """
1636
+ a = arg
1637
+ if '$' in a:
1638
+ a = _expand_with_values(a, values)
1639
+ if '$' in a:
1640
+ return None
1641
+ if '*' not in a:
1642
+ return [arg] if a == arg else [a]
1643
+ pat = os.path.expanduser(a)
1644
+ if not os.path.isabs(pat):
1645
+ base = cwd if (cwd and os.path.isabs(cwd)) else os.getcwd()
1646
+ pat = os.path.join(base, pat)
1647
+ try:
1648
+ hits = glob.glob(pat)
1649
+ except Exception: # noqa: BLE001
1650
+ return None
1651
+ if not hits or len(hits) > _READ_GLOB_LIMIT:
1652
+ return None
1653
+ return sorted(hits)
1654
+
1655
+
1656
+ def _recursive_read_danger(verb: str, tokens, cwd=None, seg=None, command=None):
1617
1657
  """名前を書かずにフォルダの中を読む検索で、中に秘密が在れば理由を返す。
1618
1658
 
1619
1659
  ・grep 系は -r / -R / --recursive のとき
@@ -1627,6 +1667,11 @@ def _recursive_read_danger(verb: str, tokens, cwd=None, seg=None):
1627
1667
  ★名指しの先が【実在のファイル】なら、そのファイル自体だけを判定する(便 3be099ba)。
1628
1668
  再帰の旗が付いていても、読まれるのは名指しのファイルだけだからである(便 401fdc65 と同じ考え方=
1629
1669
  実在が確かめられたときだけ狭める)。秘密の名前のファイルを名指しすれば今までどおり止まる。
1670
+
1671
+ ★`*` と変数は展開してから判定する(便 e338e926・実地 便 1ce88b73・10905140)。
1672
+ `$名前`・`${名前}` は同じ命令(command)の中の代入で展開し、`*` はシェルと同じく
1673
+ 隠しファイルを当てずに展開する。当たった物は1つずつ今の判定に当てる。
1674
+ 当たり0件・上限超え・名前が決まらない変数のどれかが1つでも在れば、今までどおり作業場所に倒す。
1630
1675
  """
1631
1676
  args = tokens[1:] if tokens else []
1632
1677
  label = verb
@@ -1659,17 +1704,28 @@ def _recursive_read_danger(verb: str, tokens, cwd=None, seg=None):
1659
1704
  roots = []
1660
1705
  files = []
1661
1706
  named = 0
1707
+ unresolved = False
1708
+ values = _local_var_values(command) if command else {}
1662
1709
  for pos, a in enumerate(args):
1663
1710
  if pos in skips or a.startswith('-'):
1664
1711
  continue
1665
1712
  named += 1
1666
- d = _existing_dir(a, cwd)
1667
- if d:
1668
- roots.append(d)
1713
+ paths = _expand_read_arg(a, values, cwd)
1714
+ if paths is None:
1715
+ unresolved = True # 決まらない場所が1つでも在る=下で作業場所に倒す
1669
1716
  continue
1670
- f = _existing_file(a, cwd)
1671
- if f:
1672
- files.append(f)
1717
+ for p in paths:
1718
+ if p is not a:
1719
+ sr = secret_reason(p) # 展開で当たった物そのもの(フォルダを含む)
1720
+ if sr:
1721
+ return f'{sr} touched by {label}'
1722
+ d = _existing_dir(p, cwd)
1723
+ if d:
1724
+ roots.append(d)
1725
+ continue
1726
+ f = _existing_file(p, cwd)
1727
+ if f:
1728
+ files.append(f)
1673
1729
  # ★名指しの先がファイルなら、そのファイル自体だけを判定する(便 3be099ba)。
1674
1730
  for f in files:
1675
1731
  sr = secret_reason(f)
@@ -1679,17 +1735,17 @@ def _recursive_read_danger(verb: str, tokens, cwd=None, seg=None):
1679
1735
  # そのときは理由の文にそう書く=職人が「名指ししたのに違う場所の名前が出た」と
1680
1736
  # 読み違えないため(便 623cfb85・833c280c の実地。判定は1つも変えていない)。
1681
1737
  note = ''
1682
- if not roots:
1738
+ if unresolved or not roots:
1683
1739
  # 名指しの先が実在のファイルだけ=読むのはそのファイルだけなので、作業場所に倒さない
1684
1740
  # (上で1つずつ判定済み=秘密なら止めてある・便 3be099ba の原因①)。
1685
- if files:
1741
+ if files and not unresolved:
1686
1742
  return None
1687
1743
  # 引用符の途中で千切れた切れ端は、場所をこの切れ端から読めないだけなので倒さない
1688
1744
  # (本物の区切りで測り直す側が、場所を書いていない形を今までどおり止める・原因②)。
1689
1745
  if _quote_fragment(seg):
1690
1746
  return None
1691
1747
  base = cwd if (cwd and os.path.isabs(cwd)) else os.getcwd()
1692
- roots = [os.path.realpath(base)]
1748
+ roots.append(os.path.realpath(base))
1693
1749
  note = ('(書かれた場所を読み切れないので作業場所として判定)' if named
1694
1750
  else '(探す場所を書いていないので作業場所として判定)')
1695
1751
  for d in roots:
@@ -1930,8 +1986,7 @@ def _danger_patterns(low: str):
1930
1986
  return 'gh secret'
1931
1987
  if re.search(r'\bsudo\s+rm\b', low):
1932
1988
  return 'sudo rm'
1933
- if re.search(r'\bprintenv\b', low):
1934
- return 'printenv (環境変数の一括露出)'
1989
+ # ★printenv は字面ではなく区切りごとに見る(_printenv_danger・便 e338e926)。
1935
1990
  # ★CLI が持っている合言葉を画面に出すコマンド(便 230c3175・D2)。
1936
1991
  # gh・git・npm は職人の通常作業で自分の認証の置き場を読む必要があるので、置き場そのものは
1937
1992
  # 締め出せない(~/.config/gh/hosts.yml・~/.npmrc)。代わりに「中身を出すコマンド」を止める。
@@ -1952,6 +2007,57 @@ def _danger_patterns(low: str):
1952
2007
  return None
1953
2008
 
1954
2009
 
2010
+ _PRINTENV_RE = re.compile(r'\bprintenv\b')
2011
+ _PRINTENV_REASON = 'printenv (環境変数の一括露出)'
2012
+ #: 1つの名前だけを出す形の名前(`printenv HOME`)。
2013
+ _ENV_VAR_NAME_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
2014
+
2015
+
2016
+ def _printenv_one_safe_name(toks) -> bool:
2017
+ """実際に打った printenv が「秘密でない名前を1つだけ出す」形か。"""
2018
+ if verb_of(toks) != 'printenv':
2019
+ return False
2020
+ idx = [i for i, t in enumerate(toks) if _PRINTENV_RE.search(t.lower())]
2021
+ if len(idx) != 1:
2022
+ return False
2023
+ rest = toks[idx[0] + 1:]
2024
+ if len(rest) != 1 or not _ENV_VAR_NAME_RE.match(rest[0]):
2025
+ return False # 名前なし(一括)・2つ以上・旗
2026
+ return not _SECRET_ENV_RE.search('$' + rest[0].upper())
2027
+
2028
+
2029
+ def _printenv_danger(command: str):
2030
+ """printenv を区切りごとに見て、環境変数を出しうる形なら理由を返す(便 e338e926)。
2031
+
2032
+ 【なぜ要るか(実地 便 0d887e4e・11265a0a・4cde5905)】前は全文に printenv の字があるだけで
2033
+ danger だったので、調べる・確かめる命令の探す言葉の中の字でも止まっていた。
2034
+ ・引用符を空白にしても printenv が残る区切り=本物として測る。通すのは、動詞が printenv で
2035
+ 後ろが名前1つ・秘密の名前の決まり(_SECRET_ENV_RE)に当たらないときだけ。
2036
+ ・引用符の中だけに在る区切りは、探すだけの道具(_is_search_only)で、置き換えの実行
2037
+ (`$(`・逆引用符)を含まないときだけ免じる(_rm_only_in_search_words と同じ考え方)。
2038
+ ・どの区切りにも見つからない字(ヒアドキュメントの本文・注釈など)が在れば止める側に倒す。
2039
+ """
2040
+ total = len(_PRINTENV_RE.findall((command or '').lower()))
2041
+ if not total:
2042
+ return None
2043
+ seen = 0
2044
+ for seg in split_commands(command, bodies=False):
2045
+ n = len(_PRINTENV_RE.findall(seg.lower()))
2046
+ if not n:
2047
+ continue
2048
+ seen += n
2049
+ toks = tokens_of(seg)
2050
+ if _PRINTENV_RE.search(_blank_quoted(seg).lower()):
2051
+ if not _printenv_one_safe_name(toks):
2052
+ return _PRINTENV_REASON
2053
+ continue
2054
+ if '$(' in seg or '`' in seg or not _is_search_only(toks):
2055
+ return _PRINTENV_REASON
2056
+ if seen < total:
2057
+ return _PRINTENV_REASON
2058
+ return None
2059
+
2060
+
1955
2061
  def _admin_merge_danger(verb: str, tokens):
1956
2062
  """保護を迂回する合流(`gh pr merge --admin`)。★職人には禁止(えふさん確定 2026-09-17)。
1957
2063
 
@@ -5693,7 +5799,7 @@ def _bash_danger(command: str, cwd=None):
5693
5799
  ★本番 DB の直接変更(1e)は deny とは別の結果(人に聞く)を返すので、ここには入れない。
5694
5800
  """
5695
5801
  # ---- 1) 危険(全文) ----
5696
- hit = _danger_patterns(command.lower())
5802
+ hit = _danger_patterns(command.lower()) or _printenv_danger(command)
5697
5803
  if hit:
5698
5804
  return hit
5699
5805
  hit = _rm_danger(command)
@@ -5709,7 +5815,8 @@ def _bash_danger(command: str, cwd=None):
5709
5815
  if hit:
5710
5816
  return hit
5711
5817
  # ★フォルダごとの持ち出し(名前を書かない複製・固め・同期・リンク)。
5712
- hit = (_bulk_copy_danger(v, toks, cwd) or _recursive_read_danger(v, toks, cwd, seg)
5818
+ hit = (_bulk_copy_danger(v, toks, cwd)
5819
+ or _recursive_read_danger(v, toks, cwd, seg, command)
5713
5820
  or _admin_merge_danger(v, toks))
5714
5821
  if hit:
5715
5822
  return hit
@@ -305,8 +305,10 @@ STOP = [
305
305
  G + ' -rn ' + DQ + 'x ' + WORD + "\\|y' " + WITHSECRET),
306
306
  ('e8 形Aの書き方で実在しない場所を名指し',
307
307
  G + ' -rn ' + DQ + 'x ' + WORD + "\\|y' " + os.path.join(SITE, 'nosuch')),
308
- ('e9 形Aの書き方でしるし(*)を含む場所',
309
- G + ' -rn ' + DQ + 'x ' + WORD + "\\|y' " + os.path.join(SITE, 'src', '*.ts')),
308
+ # ★`*` は展開してから判定する(便 e338e926)。実在の .ts に当たる形は通るので、
309
+ # 当たり0件(=作業場所に倒す)の形で止まる側を確かめる。
310
+ ('e9 形Aの書き方でしるし(*)の当たりが0件の場所',
311
+ G + ' -rn ' + DQ + 'x ' + WORD + "\\|y' " + os.path.join(SITE, 'src', '*.nosuch')),
310
312
  ('e10 探す文字がファイルに在る旗(-f の値が秘密)',
311
313
  G + ' -rn -f ' + SECRET + ' ' + SRC),
312
314
  ('e11 形Aの書き方で記録の外まで読む旗つき・場所なし',
@@ -0,0 +1,263 @@
1
+ #!/usr/bin/env python3
2
+ """番人の直し(便 e338e926)の検査: printenv の区切りごとの判定・`*` と変数の展開・
3
+ danger のあとの完了の知らせの読み込み。
4
+
5
+ 実行: python3 scripts/hooks/test_guard_search_glob_after_danger.py
6
+ 1件でも期待と違えば exit 1。
7
+
8
+ 【なぜ要るか(実地)】
9
+ ① 便 0d887e4e・11265a0a・4cde5905 … 調べる・確かめる命令の【探す言葉】の中の printenv の字だけで
10
+ danger になり、便が止まった(全文の字面で見ていた)。
11
+ ② 便 1ce88b73・10905140 … 再帰の検索の場所に `*` や変数を書くと、字面のまま実在を確かめて
12
+ 解けず、作業場所に倒れて根の秘密ファイルに当たって止まった。
13
+ ③ 便 0d887e4e・11265a0a・4cde5905 … danger のあと、完了の知らせの道具を読み込む ToolSearch が
14
+ 止められ、conductor_complete を呼べなかった。
15
+
16
+ 【ここで固定すること】
17
+ (p) printenv … 名前なし・名前2つ以上・旗・秘密の名前は止まる。秘密でない名前1つは通る。
18
+ 探すだけの道具の引用符の中の字は通る。実際に打った物・ヒアドキュメントの本文は止まる。
19
+ (g) `*`・変数 … 展開して当たった物を今の判定に当てる。秘密に当たれば止まる。
20
+ 当たり0件・名前が決まらない変数は、今までどおり作業場所に倒して止まる。
21
+ (d) danger のあと … ToolSearch の query が select:mcp__ai-kana__conductor_complete ちょうどの
22
+ ときだけ通る。ほかの道具の読み込みは止まる。
23
+ (v) ★空振り確認 … 直した所を外すと、上の期待が実際に崩れる。
24
+
25
+ ★本物のホーム・本物の秘密には1バイトも触れない。作り物の置き場で判定する。
26
+ """
27
+ import json
28
+ import os
29
+ import shutil
30
+ import sys
31
+ import tempfile
32
+
33
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
34
+
35
+ failures = []
36
+
37
+
38
+ def check(label, got, want):
39
+ ok = got == want
40
+ if not ok:
41
+ failures.append(f'{label}: got={got!r} want={want!r}')
42
+ print(f'{"OK " if ok else "NG "} {label:72} {str(got)[:40]}')
43
+
44
+
45
+ def truthy(label, got):
46
+ check(label, bool(got), True)
47
+
48
+
49
+ # ─────────────────────────────────────────────────────────────────────────────
50
+ # 作り物の置き場(★本物のホーム・本物の秘密には触れない)
51
+ # ─────────────────────────────────────────────────────────────────────────────
52
+ ROOT = tempfile.mkdtemp(prefix='guard-e338e926-',
53
+ dir='/tmp/claude-1000' if os.path.isdir('/tmp/claude-1000') else None)
54
+ HOME = os.path.join(ROOT, 'home', 'tester')
55
+ STATE = os.path.join(ROOT, 'state')
56
+ WORK = os.path.join(HOME, 'projects', 'demo')
57
+ SITE = 'demo'
58
+ JOB = 'e338e926-93fd-476e-bdf6-5245c74e6cb8'
59
+ SESSION = 'se-e338e926'
60
+
61
+
62
+ def mk(path, body=''):
63
+ os.makedirs(os.path.dirname(path), exist_ok=True)
64
+ with open(path, 'w', encoding='utf-8') as f:
65
+ f.write(body)
66
+ return path
67
+
68
+
69
+ os.makedirs(os.path.join(WORK, '.git'), exist_ok=True)
70
+ mk(os.path.join(WORK, '.npmrc'), 'dummy\n') # 偽の秘密(作業場所の根)
71
+ mk(os.path.join(WORK, 'pkg', '.npmrc'), 'dummy\n') # 偽の秘密(フォルダの中)
72
+ mk(os.path.join(WORK, 'src', 'a.ts'), 'export const a = 1\n')
73
+ mk(os.path.join(WORK, 'src', 'b.ts'), 'export const b = 2\n')
74
+ mk(os.path.join(WORK, 'docs', 'x.md'), '# x\n')
75
+ os.environ['HOME'] = HOME
76
+ os.environ['TMPDIR'] = ROOT
77
+ os.environ['XDG_STATE_HOME'] = STATE
78
+ os.environ['CONDUCTOR_SITE'] = SITE
79
+ os.environ['CONDUCTOR_GUARD_LOG'] = os.path.join(ROOT, 'guard.log')
80
+ os.environ.pop('CONDUCTOR_REPORT_DIR', None)
81
+ os.environ.pop('CONDUCTOR_URL', None)
82
+ os.environ.pop('CONDUCTOR_TOKEN', None)
83
+ mk(os.path.join(STATE, 'conductor', f'active-job-{SITE}.json'),
84
+ json.dumps({'commandId': JOB, 'site': SITE, 'body': 'x'}))
85
+
86
+ import cc2_guard # noqa: E402
87
+ import hook_datalink # noqa: E402
88
+ import policy # noqa: E402
89
+
90
+
91
+ def decide(cmd, cwd=WORK):
92
+ return policy.decide_bash(cmd, cwd)['decision']
93
+
94
+
95
+ def reason(cmd, cwd=WORK):
96
+ return policy.decide_bash(cmd, cwd)['reason']
97
+
98
+
99
+ # ─────────────────────────────────────────────────────────────────────────────
100
+ # (p) printenv
101
+ # ─────────────────────────────────────────────────────────────────────────────
102
+ print('── (p) printenv ' + '─' * 54)
103
+ P_ALLOW = [
104
+ # 実地の形(探す言葉の中の字・調べる/確かめる命令)
105
+ ('p1 探す言葉の中(grep・名指しのファイル)', "grep -n 'printenv' src/a.ts"),
106
+ ('p2 探す言葉の中(grep -rn・名指しのフォルダ)', 'grep -rn "\\bprintenv\\b" src docs'),
107
+ ('p3 探す言葉の中(git grep)', "git grep -n 'printenv' -- src"),
108
+ ('p4 探す言葉の中(rg)', "rg -n 'printenv|_danger_patterns' src"),
109
+ ('p5 探す言葉の中(grep -e を2つ)', "grep -n -e 'printenv' -e 'home' src/a.ts"),
110
+ ('p6 秘密でない名前を1つだけ出す', 'printenv HOME'),
111
+ ('p7 秘密でない名前を1つだけ出す(PATH)', 'printenv PATH'),
112
+ ]
113
+ for label, cmd in P_ALLOW:
114
+ check(label, decide(cmd), policy.ALLOW)
115
+
116
+ P_DENY = [
117
+ ('p10 名前なし(一括)', 'printenv'),
118
+ ('p11 名前2つ以上', 'printenv HOME PATH'),
119
+ ('p12 旗', 'printenv -0'),
120
+ ('p13 秘密の名前(TOKEN)', 'printenv GITHUB_TOKEN'),
121
+ ('p14 秘密の名前(DATABASE_URL)', 'printenv DATABASE_URL'),
122
+ ('p15 秘密の名前(小文字で書いても)', 'printenv api_key'),
123
+ ('p16 探した後で実際に打つ(;)', 'grep x src/a.ts; printenv'),
124
+ ('p17 探した後で実際に打つ(&&)', "grep -n 'printenv' src/a.ts && printenv"),
125
+ ('p18 流し込む先で打つ(|)', "grep -n 'printenv' src/a.ts | printenv"),
126
+ ('p19 ヒアドキュメントの本文', 'cat <<EOF\nprintenv\nEOF'),
127
+ ('p20 探すだけでない道具の引用符の中', "echo 'printenv'"),
128
+ ('p21 包みの中', "bash -c 'printenv'"),
129
+ ('p22 探す言葉に見せた置き換えの実行', 'grep x "$(printenv)" src/a.ts'),
130
+ ('p23 逆引用符の置き換え', 'grep x `printenv` src/a.ts'),
131
+ ('p24 引用符の外の探す言葉(字が本物の位置に在る)', 'grep -n printenv src/a.ts'),
132
+ ('p25 名前を置き換えで渡す', 'printenv $(cat names.txt)'),
133
+ ('p26 流し込みで名前を並べる', 'echo HOME | xargs printenv'),
134
+ ('p27 注釈の中(どの区切りにも見つからない字)', 'git status # printenv'),
135
+ ]
136
+ for label, cmd in P_DENY:
137
+ check(label, decide(cmd), policy.DENY)
138
+ truthy('p★ 止めた理由は今までどおりの文', reason('printenv').startswith('danger: printenv'))
139
+
140
+ # env の一括表示は今の判定を変えない(★この便では触っていない・今の判定を記録して固定する)。
141
+ # ★番人は今これを止めていない(allow)。止めるかどうかは持ち主の判断(便 e338e926 の報告の要判断)。
142
+ # 止める側へ直したときは、この期待を DENY へ書き換える。
143
+ ENV_BULK = 'env'
144
+ print(f' (記録)env の一括の判定: {policy.decide_bash(ENV_BULK, WORK)}')
145
+ check('p30 env の一括は今の判定のまま(変えていない)', decide(ENV_BULK), policy.ALLOW)
146
+
147
+ # ─────────────────────────────────────────────────────────────────────────────
148
+ # (g) `*` と変数
149
+ # ─────────────────────────────────────────────────────────────────────────────
150
+ print('── (g) `*` と変数 ' + '─' * 52)
151
+ G_ALLOW = [
152
+ ('g1 `*` が秘密でないファイルだけに当たる', 'grep -rn export src/*.ts'),
153
+ ('g2 `*` が秘密でないフォルダだけに当たる', 'grep -rn export s*'),
154
+ ('g4 変数で書いた場所($名前)', 'D=src; grep -rn export "$D"'),
155
+ ('g5 変数で書いた場所(${名前})', 'D=src; grep -rn export ${D}/a.ts'),
156
+ ('g6 変数と `*`', 'D=src; grep -rn export "$D"/*.ts'),
157
+ ('g7 rg の隠しを読む旗でも当たりが秘密でなければ通る', 'rg --hidden export src/*'),
158
+ ]
159
+ for label, cmd in G_ALLOW:
160
+ check(label, decide(cmd), policy.ALLOW)
161
+ # 根の `*` は隠しファイル(.npmrc)を当てない=シェルと同じ(★隠しでない秘密入りのフォルダが無い場所)
162
+ SUB = os.path.join(WORK, 'sub')
163
+ mk(os.path.join(SUB, '.npmrc'), 'dummy\n')
164
+ mk(os.path.join(SUB, 'c.ts'), 'export const c = 3\n')
165
+ mk(os.path.join(SUB, 'lib', 'd.ts'), 'export const d = 4\n')
166
+ check('g3 根の `*` は隠しファイルを当てない(シェルと同じ)',
167
+ decide('grep -rn export *', SUB), policy.ALLOW)
168
+ check('g3 同じ場所で隠しを当てる `.*` は止まる', decide('grep -rn export .*', SUB), policy.DENY)
169
+ check('g3 同じ場所で `*` を外すと作業場所として止まる', decide('grep -rn export', SUB), policy.DENY)
170
+ check('g3 `*` が秘密入りのフォルダ(pkg)に当たる根は止まる',
171
+ decide('grep -rn export *'), policy.DENY)
172
+
173
+ G_DENY = [
174
+ ('g10 `*` が秘密のファイル(.npmrc)に当たる', 'grep -rn x .n*'),
175
+ ('g11 `*` が秘密を含むフォルダに当たる', 'grep -rn x pk*'),
176
+ ('g12 変数で書いた場所が秘密を含む', 'D=pkg; grep -rn x "$D"'),
177
+ ('g13 変数で書いた場所が作業場所の根', 'D=.; grep -rn x $D'),
178
+ ('g14 変数で書いた場所が秘密のファイル', 'F=.npmrc; grep -rn x "$F"'),
179
+ ('g15 当たり0件の `*`', 'grep -rn x nothing-here*'),
180
+ ('g16 名前が決まらない変数', 'grep -rn x "$NOPE"'),
181
+ ('g17 名前が決まらない変数を名指しの場所に混ぜる', 'grep -rn x src "$NOPE"'),
182
+ ('g18 場所を書かない(今までどおり)', 'grep -rn x'),
183
+ ]
184
+ for label, cmd in G_DENY:
185
+ check(label, decide(cmd), policy.DENY)
186
+ truthy('g★ 決まらないときは作業場所として判定したと書く',
187
+ '作業場所として判定' in reason('grep -rn x "$NOPE"'))
188
+
189
+ # ─────────────────────────────────────────────────────────────────────────────
190
+ # (d) danger のあとでも、完了の知らせの読み込みだけは通る
191
+ # ─────────────────────────────────────────────────────────────────────────────
192
+ print('── (d) danger のあと ' + '─' * 49)
193
+ KEY = (SESSION, SITE, JOB)
194
+
195
+
196
+ def ev(tool, tin, session=SESSION, cwd=WORK):
197
+ return {'tool_name': tool, 'tool_input': tin, 'cwd': cwd, 'session_id': session}
198
+
199
+
200
+ def run(data):
201
+ out = cc2_guard.guard_output(data)
202
+ if not out:
203
+ return 'defer', ''
204
+ spec = out['hookSpecificOutput']
205
+ return spec['permissionDecision'], spec.get('permissionDecisionReason', '')
206
+
207
+
208
+ COMPLETE_LOAD = ev('ToolSearch', {'query': 'select:mcp__ai-kana__conductor_complete',
209
+ 'max_results': 1})
210
+ hook_datalink.clear_danger_stop(*KEY)
211
+ dec, why = run(ev('Bash', {'command': 'printenv'}))
212
+ check('d1 一括の printenv は danger で止まる', dec, 'deny')
213
+ truthy('d1 印が置かれた', hook_datalink.danger_stop_active(*KEY))
214
+
215
+ truthy('d2 完了の知らせの読み込みは通る', run(COMPLETE_LOAD)[0] != 'deny')
216
+ truthy('d2 止めた文に、通す物として読み込みが書いてある',
217
+ 'select:mcp__ai-kana__conductor_complete' in run(ev('Bash', {'command': 'ls'}))[1])
218
+ D_DENY = [
219
+ ('d3 ほかの道具の読み込み', ev('ToolSearch', {'query': 'select:WebFetch', 'max_results': 1})),
220
+ ('d4 完了の知らせに別の道具を混ぜた読み込み',
221
+ ev('ToolSearch', {'query': 'select:mcp__ai-kana__conductor_complete,WebFetch',
222
+ 'max_results': 2})),
223
+ ('d5 言葉で探す読み込み', ev('ToolSearch', {'query': 'conductor_complete', 'max_results': 5})),
224
+ ('d6 query が無い読み込み', ev('ToolSearch', {'max_results': 5})),
225
+ ]
226
+ for label, data in D_DENY:
227
+ check(label, run(data)[0], 'deny')
228
+ check('d7 完了の知らせそのものは今までどおり通る',
229
+ run(ev('mcp__ai-kana__conductor_complete', {'commandId': JOB}))[0], 'allow')
230
+
231
+ # ─────────────────────────────────────────────────────────────────────────────
232
+ # (v) ★空振り確認 … 直した所を外すと期待が崩れる
233
+ # ─────────────────────────────────────────────────────────────────────────────
234
+ print('── (v) 空振り確認 ' + '─' * 52)
235
+ saved_pe = policy._printenv_danger
236
+ policy._printenv_danger = lambda command: None
237
+ check('v1 printenv の判定を外すと一括が通ってしまう', decide('printenv'), policy.ALLOW)
238
+ policy._printenv_danger = saved_pe
239
+ check('v1 戻すと止まる', decide('printenv'), policy.DENY)
240
+
241
+ saved_ex = policy._expand_read_arg
242
+ policy._expand_read_arg = lambda arg, values, cwd=None: [arg]
243
+ check('v2 展開を外すと `*` の検索が作業場所に倒れて止まる',
244
+ decide(G_ALLOW[0][1]), policy.DENY)
245
+ policy._expand_read_arg = saved_ex
246
+ check('v2 戻すと通る', decide(G_ALLOW[0][1]), policy.ALLOW)
247
+
248
+ saved_sel = cc2_guard._COMPLETE_TOOL_SELECT
249
+ cc2_guard._COMPLETE_TOOL_SELECT = '(外した)'
250
+ check('v3 一覧から外すと完了の知らせの読み込みが止まる', run(COMPLETE_LOAD)[0], 'deny')
251
+ cc2_guard._COMPLETE_TOOL_SELECT = saved_sel
252
+ truthy('v3 戻すと通る', run(COMPLETE_LOAD)[0] != 'deny')
253
+
254
+ hook_datalink.clear_danger_stop(*KEY)
255
+ shutil.rmtree(ROOT, ignore_errors=True) # ★作り物は毎回片付ける
256
+
257
+ print()
258
+ if failures:
259
+ print(f'NG {len(failures)} 件')
260
+ for f in failures:
261
+ print(' ', f)
262
+ sys.exit(1)
263
+ print('すべて期待どおり')
@@ -175,7 +175,10 @@ SAFE = [
175
175
  ('d4 点1つ', G + ' -rn x .'),
176
176
  ('d5 作業場所の根を名指し', G + ' -rn x ' + SITE + '/.'),
177
177
  ('d6 実在しない場所を名指し', G + ' -rn x ' + os.path.join(SITE, 'nope')),
178
- ('d7 しるし入りの場所', G + ' -rn x ' + SITE + '/*'),
178
+ # ★`*` は展開してから判定する(便 e338e926)。隠しを当てない `SITE/*` は src・clean だけに
179
+ # なって通るので、隠しを当てる印と当たり0件の形で、止まる側を確かめる。
180
+ ('d7 しるし入りの場所(隠しを当てる印で秘密に当たる)', G + ' -rn x ' + SITE + '/.*'),
181
+ ('d7b しるし入りの場所(当たり0件=作業場所に倒す)', G + ' -rn x ' + SITE + '/nope*'),
179
182
  ('d8 記録の外まで読む旗つきで根を探す', GG + ' --untracked -n x'),
180
183
  ('d9 -f の値が秘密のファイル(探す文字が書いてあるファイル=パス)',
181
184
  G + ' -n -f ' + SECRET + ' ' + FILE1),
@@ -1714,10 +1714,15 @@ has_sandbox = isinstance(shared.get("sandbox"), dict) or isinstance(local.get("s
1714
1714
  # ADR-012 が否定した形そのものなので、この1件だけを同期モードにも乗せる。
1715
1715
  # ★だから位置も ④ の先頭にする(この直後で同期モードを打ち切る=ほかの段に1バイトも触らない)。
1716
1716
  #
1717
- # ★足すのは報告の置き場1件だけ($REPORT_STORE_SRC が出す物)。
1718
- # 部品の置き場(pnpm・npm の控え)・/tmp/claude-1000 は【足さない】。
1717
+ # ★足すのは2件だけ=報告の置き場($REPORT_STORE_SRC が出す物)と npm の控え(~/.npm/_cacache)。
1718
+ # 【npm の控えを足す理由(えふさん確定 2026-10-26・便 a3e93165)】以前は「部品の置き場(pnpm・npm の控え)は
1719
+ # 足さない」と決めていたが、npm の控えが許可に無いと職人の npm install が囲いで止まる
1720
+ # (mebukia 便 d395a0d6 で実発生)。この確定で npm の控えの部分だけを上書きした。
1721
+ # 字面は雛形(gen-managed-settings-template.py の ALLOW_WRITE_HOME)と同じ物で、試験が食い違いを見張る。
1722
+ # ★npm の記録(~/.npm/_logs)・~/.npm 全体・~/.npmrc は足さない(守る対象のまま)。
1723
+ # ★pnpm の置き場・/tmp/claude-1000 は今も【足さない】。
1719
1724
  # それらは要るかの判断が別(雛形 gen-managed-settings-template.py の側に在る)で、
1720
- # ここで一緒に広げると「報告を残すため」の最小の許可でなくなる。
1725
+ # ここで一緒に広げると、確定した2件を超える許可になる。
1721
1726
  # ★sandbox セクションが「既に在る現場」だけを対象にする((3)・(3b) と同じ理由=ADR-004)。
1722
1727
  # ★書く先は settings.local.json(②-b)。一覧は段をまたいで足し合わせになるので、ここに足せば効く。
1723
1728
  # ★既存の allowWrite の行は1行も外さない・並べ替えない(不足分を後ろに足すだけ)。
@@ -1729,7 +1734,10 @@ def _allow_write_broken(data):
1729
1734
  _f = _s.get("filesystem") if isinstance(_s, dict) else None
1730
1735
  return isinstance(_f, dict) and "allowWrite" in _f and not isinstance(_f.get("allowWrite"), list)
1731
1736
 
1732
- if has_sandbox and report_store:
1737
+ #: npm の控え(★えふさん確定 2026-10-26。雛形の ALLOW_WRITE_HOME と同じ字面=試験が見張る)。
1738
+ NPM_CACHE_ALLOW = "~/.npm/_cacache"
1739
+
1740
+ if has_sandbox:
1733
1741
  _lsb = local.get("sandbox")
1734
1742
  _fs = _lsb.get("filesystem") if isinstance(_lsb, dict) else None
1735
1743
  _has_allow = isinstance(_fs, dict) and "allowWrite" in _fs
@@ -1737,10 +1745,13 @@ if has_sandbox and report_store:
1737
1745
  _broken_at = [p for p, d in ((dst_path, shared), (local_path, local)) if _allow_write_broken(d)]
1738
1746
  if _broken_at:
1739
1747
  print(f"[update-guard] ※ {_broken_at[0]}: sandbox.filesystem.allowWrite が一覧ではないので"
1740
- f"報告の置き場は足しません(人の判断待ち)")
1748
+ f"報告の置き場・npm の控えは足しません(人の判断待ち)")
1741
1749
  else:
1742
1750
  _cur_allow = _fs.get("allowWrite") if _has_allow else []
1743
- _missing_write = [p for p in report_store if p not in _cur_allow]
1751
+ # ★報告の置き場は正本を読めた機体だけ(読めなければ足さない)。npm の控えはそれと別に足す。
1752
+ _missing_store = [p for p in (report_store or []) if p not in _cur_allow]
1753
+ _missing_npm = [NPM_CACHE_ALLOW] if NPM_CACHE_ALLOW not in _cur_allow else []
1754
+ _missing_write = _missing_store + _missing_npm
1744
1755
  if _missing_write:
1745
1756
  if not isinstance(_lsb, dict):
1746
1757
  _lsb = {}
@@ -1749,12 +1760,17 @@ if has_sandbox and report_store:
1749
1760
  _fs = {}
1750
1761
  _lsb["filesystem"] = _fs
1751
1762
  _fs["allowWrite"] = list(_cur_allow) + _missing_write
1763
+ if _missing_store:
1764
+ changes.append(
1765
+ f"囲いの中でも書ける場所に報告の置き場を {len(_missing_store)} 件追記"
1766
+ f"({' / '.join(_missing_store)}。足さないと職人の報告が1件も残らない)")
1767
+ if _missing_npm:
1752
1768
  changes.append(
1753
- f"囲いの中でも書ける場所に報告の置き場を {len(_missing_write)} 件追記"
1754
- f"({' / '.join(_missing_write)}。足さないと職人の報告が1件も残らない)")
1769
+ f"囲いの中でも書ける場所に npm の控えを追記"
1770
+ f"({NPM_CACHE_ALLOW}。足さないと職人の npm install が囲いで止まる)")
1755
1771
 
1756
1772
  # ★同期モード(無人・1時間ごと)はここで打ち切る。この先は権限ルールの整理=人が見ている時だけ。
1757
- # ここまでで触ったのは、移行で移した守りと sandbox.filesystem.allowWrite の1件だけ。
1773
+ # ここまでで触ったのは、移行で移した守りと sandbox.filesystem.allowWrite(報告の置き場・npm の控え)だけ。
1758
1774
  if sync_only:
1759
1775
  finish(changes)
1760
1776