@tyhld/conductor 0.12.169 → 0.12.171

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/dist/selfcheck.js CHANGED
@@ -1037,10 +1037,82 @@ const DANGER_STOP_CLEAR = [
1037
1037
  ' for data in json.load(sys.stdin):',
1038
1038
  ' clear(*key(data))',
1039
1039
  ].join('\n');
1040
+ /** 入っている番人の入口(cc2_guard.py)の道筋。 */
1041
+ function guardPath(d) {
1042
+ return path.join(d.home, '.tyhld', 'hooks', 'cc2_guard.py');
1043
+ }
1044
+ /** 番人に1件判定させ、答え(deny / allow / ask / none=何も返さない=委譲)を返す。 */
1045
+ function askGuard(d, guard, probe, env) {
1046
+ const r = d.exec('python3', [guard], { input: JSON.stringify(probe), env, timeoutMs: 30_000 });
1047
+ try {
1048
+ return JSON.parse(r.stdout).hookSpecificOutput?.permissionDecision ?? 'none';
1049
+ }
1050
+ catch {
1051
+ return 'none'; // 何も返さない=委譲(allow ではない)
1052
+ }
1053
+ }
1054
+ // ── 完了の知らせを、この機体の名前のまま番人が通すか(便 12526bb8) ──
1055
+ // 【何が起きたか(実地 便 ba854574・TYHLD-GOTO)】claude.ai のコネクタだけの機体では、管制の道具は
1056
+ // `mcp__claude_ai_ai-kana__conductor_complete` の名前になる。番人は danger のあとに
1057
+ // `mcp__ai-kana__…` の形の読み込みしか通さなかったので、職人が完了の知らせを送れなかった。
1058
+ // 【どう確かめるか】この機体で職人に見える ai-kana の登録の名前から道具の名前を作り、
1059
+ // 番人に「danger で止めたあと」の状態で、呼び出しと ToolSearch の読み込みを当てる。
1060
+ // ★通る名前の決まりは番人(cc2_guard.py の CONDUCTOR_TOOL_PREFIXES)が正本=ここでは写さない。
1061
+ // 通らなければ fault で落とす=管制の「PCの状態」の落ちた項目に出る(便を出す前に分かる)。
1062
+ /** 完了の知らせの道具(管制の道具の名前の後ろ)。 */
1063
+ const COMPLETE_TOOL = 'conductor_complete';
1064
+ /** 登録の一覧が無い回に確かめる、ai-kana の登録の名前(MCP として入れた形/claude.ai のコネクタの形)。 */
1065
+ export const AI_KANA_SERVER_NAMES = ['ai-kana', 'claude.ai ai-kana'];
1066
+ /** MCP の登録の名前から、職人に見える道具の名前を作る(★Claude Code は英数字・`_`・`-` 以外を `_` にする)。 */
1067
+ export function mcpToolName(server, tool) {
1068
+ return `mcp__${server.replace(/[^A-Za-z0-9_-]/g, '_')}__${tool}`;
1069
+ }
1070
+ /**
1071
+ * 確かめる完了の知らせの道具の名前。つながっている ai-kana の登録があれば、その名前(=この機体で職人に見える物)。
1072
+ * 無い・一覧が無い回は、在り得る2通り(AI_KANA_SERVER_NAMES)。
1073
+ */
1074
+ export function completeToolNames(list) {
1075
+ const connected = (list ?? []).filter((s) => /ai-kana/i.test(s.name) && s.status === 'connected').map((s) => s.name);
1076
+ const servers = connected.length > 0 ? connected : [...AI_KANA_SERVER_NAMES];
1077
+ return [...new Set(servers.map((s) => mcpToolName(s, COMPLETE_TOOL)))];
1078
+ }
1079
+ /** +番人:danger で止めたあとでも、この機体の完了の知らせ(呼び出し・読み込み)を通すか。 */
1080
+ export function checkCompleteToolGuard(d, item, work, list) {
1081
+ const guard = guardPath(d);
1082
+ if (!existsSync(guard))
1083
+ return; // 番人が無いことは checkGuard が落としている
1084
+ const env = { ...d.env, PYTHONDONTWRITEBYTECODE: '1' };
1085
+ const names = completeToolNames(list);
1086
+ const [session] = guardProbeSessionIds(d, 1);
1087
+ const ev = (tool_name, tool_input) => ({ hook_event_name: 'PreToolUse', tool_name, tool_input, cwd: work, session_id: session });
1088
+ // ① danger で止めて印を置かせる → ② 印が効いている(ふつうの一覧が止まる)→ ③ 名前ごとに呼び出しと読み込み
1089
+ const probes = [ev('Bash', { command: 'rm -rf ~/.tyhld/hooks' }), ev('Bash', { command: 'ls' })];
1090
+ const first = askGuard(d, guard, probes[0], env);
1091
+ const latched = askGuard(d, guard, probes[1], env) === 'deny';
1092
+ if (first !== 'deny' || !latched) {
1093
+ note(item, `完了の知らせの確かめ: danger のあとの状態を作れませんでした(${first}/印 ${latched ? 'あり' : 'なし'})`);
1094
+ }
1095
+ else {
1096
+ for (const name of names) {
1097
+ const call = ev(name, { commandId: 'selfcheck' });
1098
+ const load = ev('ToolSearch', { query: `select:${name}`, max_results: 1 });
1099
+ probes.push(call, load);
1100
+ const got = [askGuard(d, guard, call, env), askGuard(d, guard, load, env)];
1101
+ if (got.every((g) => g !== 'deny'))
1102
+ pass(item, `danger のあとも完了の知らせ ${name}(呼び出し・読み込み)を通します`);
1103
+ else
1104
+ fail(item, 'fault', `danger のあとに完了の知らせ ${name} を番人が通しません(呼び出し ${got[0]}・読み込み ${got[1]})=この機体の職人は止まった便を完了にできません`);
1105
+ }
1106
+ }
1107
+ // ★自分が置かせた印を自分で片付ける(checkGuard と同じ・この回の session_id の分だけ)。
1108
+ const cleared = d.exec('python3', ['-c', DANGER_STOP_CLEAR, guard], { input: JSON.stringify(probes), env, timeoutMs: 30_000 });
1109
+ if (cleared.status !== 0)
1110
+ note(item, `完了の知らせの確かめが置いた印を片付けられませんでした(終了 ${cleared.status}・12時間で自然に無効になります)`);
1111
+ }
1040
1112
  /** +番人:入っている番人に、止めるべき物と通すべき物を1つずつ判定させる。 */
1041
1113
  export function checkGuard(d, work) {
1042
1114
  const item = { key: 'guard', label: '番人', ok: null, detail: [] };
1043
- const guard = path.join(d.home, '.tyhld', 'hooks', 'cc2_guard.py');
1115
+ const guard = guardPath(d);
1044
1116
  const resync = 'APPLY=1 bash "$(npm root -g)/@tyhld/conductor/scripts/update-guard.sh"';
1045
1117
  if (!existsSync(guard)) {
1046
1118
  fail(item, 'human', `番人が入っていません(${guard})`, { machine: d.machine, what: 'Ubuntu で番人を配り直す', command: resync });
@@ -1062,14 +1134,7 @@ export function checkGuard(d, work) {
1062
1134
  session_id: sessions[i],
1063
1135
  }));
1064
1136
  for (const [i, c] of cases.entries()) {
1065
- const r = d.exec('python3', [guard], { input: JSON.stringify(probes[i]), env, timeoutMs: 30_000 });
1066
- let got = 'none';
1067
- try {
1068
- got = JSON.parse(r.stdout).hookSpecificOutput?.permissionDecision ?? 'none';
1069
- }
1070
- catch {
1071
- // 何も返さない=委譲(allow ではない)
1072
- }
1137
+ const got = askGuard(d, guard, probes[i], env);
1073
1138
  const ok = c.want === 'deny' ? got === 'deny' : got === 'allow' || got === 'none';
1074
1139
  if (ok)
1075
1140
  pass(item, `${c.label} → ${got}`);
@@ -1794,6 +1859,8 @@ export async function runSelfcheck(d, trigger, opts = {}) {
1794
1859
  note(headless, 'お客さまの機の定期の確かめでは Claude を呼びません(版を入れ替えた直後の1回だけ流します・使用量の上限)');
1795
1860
  note(sandbox, '囲いの中からの書き込みは、Claude を呼ぶ回(版を入れ替えた直後)にだけ確かめます');
1796
1861
  note(network, '囲いの内側からの通信は、Claude を呼ぶ回(版を入れ替えた直後)にだけ確かめます');
1862
+ // +完了の知らせを番人が通すか(★MCP の一覧を見ない回なので、在り得る2通りの名前で・便 12526bb8)
1863
+ checkCompleteToolGuard(d, guard, path.join(runDir, 'work'), null);
1797
1864
  const items = [conductor, claude.item, central, sandbox, network, headless, guard, managed, unsafe, units, siteGuard, accounts];
1798
1865
  return {
1799
1866
  schema: 'conductor-selfcheck/1',
@@ -1880,6 +1947,8 @@ export async function runSelfcheck(d, trigger, opts = {}) {
1880
1947
  fail(central, 'fault', `ai-kana の MCP につながりません(failed・${seen})`);
1881
1948
  else
1882
1949
  note(central, 'MCP の状態を読めませんでした(小さな試験の最初の行が無い)');
1950
+ // +完了の知らせを番人が通すか(★この機体でつながっている登録の名前で=職人に見える名前・便 12526bb8)
1951
+ checkCompleteToolGuard(d, guard, path.join(runDir, 'work'), mcp.list);
1883
1952
  // ④ 書き込み
1884
1953
  if (h.outsideWrite === 'blocked')
1885
1954
  pass(sandbox, '囲いの中から作業場所の外への書き込みが止まりました');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tyhld/conductor",
3
- "version": "0.12.169",
3
+ "version": "0.12.171",
4
4
  "description": "采配くん管制の見守りアプリ(conductor-agent)。各PCで常駐し、中央(devlog-tracker)へ定期的に生存報告(heartbeat)を送る常駐CLI。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -100,7 +100,6 @@
100
100
  "Edit(**/.ssh/**)",
101
101
  "Edit(**/*.pem)",
102
102
  "Edit(**/*.key)",
103
- "Edit(**/.npmrc)",
104
103
  "Read(**/.env)",
105
104
  "Read(**/.env.local)",
106
105
  "Read(**/.env.development)",
@@ -611,7 +611,13 @@ DENY** です。読み込み先は公式の説明と道具の実体で確かめ
611
611
  | ① | 報告の置き場の中のファイルへの `Write`/`Edit`/`MultiEdit`/`NotebookEdit` | 報告を書く・直す |
612
612
  | ② | 報告の置き場の中のファイルの `Read`/`NotebookRead` | `Edit` は先に読む必要がある |
613
613
  | ③ | `mkdir -p <報告の置き場の中>` の1コマンドだけ(Bash) | 置き場のフォルダを作る |
614
- | ④ | 道具の名前が `conductor_complete` で終わる物 | 完了の知らせ |
614
+ | ④ | 管制の完了の知らせ `mcp__ai-kana__conductor_complete`/`mcp__claude_ai_ai-kana__conductor_complete` とちょうど同じ名前の道具と、それだけを名指しする ToolSearch の読み込み(`select:<その名前>[,<その名前>]`) | 完了の知らせ |
615
+
616
+ ★④の名前は機体ごとに2通りあります(Claude Code に MCP として入れた機体は `mcp__ai-kana__`、claude.ai の
617
+ コネクタだけの機体は `mcp__claude_ai_ai-kana__`・実地 便 ba854574)。正本は `cc2_guard.py` の
618
+ `CONDUCTOR_TOOL_PREFIXES` の1か所です。ほかのコネクタの同じ名前(`mcp__other__conductor_complete`)・前後に
619
+ 文字が付いた名前・ほかの道具が混ざった読み込みは通しません(便 12526bb8)。自己診断の番人の項目が、
620
+ その機体で職人に見える名前のまま番人が通すかを確かめます(通らなければ fault で落ちる)。
615
621
 
616
622
  ★報告の置き場の決め方は **`finish_gate.report_dirs` が正本**です(字面を2か所に置きません)。
617
623
  ★`build_output`(判定だけ)は1文字も変えていません。足したのは `guard_output` の1層だけで、
@@ -856,6 +862,28 @@ TYHLD-platform の2便が、**読むだけの検索**で同じ `danger` に止
856
862
  - **`-f` / `--file` と `-e` が混ざった形では、1つも外しません**(安全側に倒したまま)。
857
863
  - **番人が古い機体では効きません。** 各PCで人が1回配布を流すまで、その機では今までどおりです。
858
864
 
865
+ ## 1-13. ★値の入っていない `.npmrc` は、作る・直す・記録に入れるのを通す(便 5751e7ae・えふさん決定 2026-11-03)
866
+
867
+ 共通部品(`@tyhld/*`)を取ってくる `.npmrc` は、中身が取り寄せ先の行と鍵の置き場の名前(`${NPM_TOKEN}`)だけで、
868
+ 鍵の値はありません。それでも名前だけで秘密と判定していたので、職人の Write(便 9ca0acd2・禁止の一覧の `Edit(**/.npmrc)`)も
869
+ `git add`(便 6a4e2122・`danger: secret file (.npmrc) sent by git add`)も止まり、そのたびにえふさんの手番になっていました。
870
+
871
+ | 形 | 前 | 後 |
872
+ |---|---|---|
873
+ | Write/Edit/MultiEdit で、許す形の行だけの `.npmrc` を作る・直す(元も許す形だけか、まだ無い) | 止まる | **通る** |
874
+ | 名指しの `git add`・`git stage`・`git commit <名指し>` で、許す形の行だけの `.npmrc` を記録に入れる | `danger` | **通る** |
875
+ | `_authToken` の右が実物/`_auth`・`_password`・`always-auth`・`username`・未知の行/URL に名前や合言葉 | `danger` | `danger`(変えない) |
876
+ | 元の `.npmrc` に実物の値が在る(値なしで上書き・直し=本物の鍵を消す形) | `danger` | `danger`(変えない) |
877
+ | `~/.npmrc`・ホームの隠しフォルダの下・秘密の置き場の下・近道・作業場所が変数の `git -C "$DIR"` | `danger` | `danger`(変えない) |
878
+ | 読む(Read・`cat`)・Bash で書く(`cp`・`tee`・`>`)・`git hash-object -w` | `danger` | `danger`(変えない) |
879
+
880
+ - 許す形の行=空行・注釈(`#`・`;`)・`registry=<URL>`・`@<scope>:registry=<URL>`・`//<ホスト>/:_authToken=${<名前>}` だけ。
881
+ 番人は中身を読みますが、判定の「はい/いいえ」にしか使わず、中身は1文字も外に出しません(`npmrc_text_is_ref_only`)。
882
+ - **禁止の一覧の `Edit(**/.npmrc)` は退役しました**(`update-guard.sh` の `RETIRED_DENY`・各現場からも外す)。この行は中身を見られないので、
883
+ 値なしの Write まで止めていました。値の入った書き込みは番人の中身の判定が止めます(`test_npmrc_ref_only.py` で確かめた)。
884
+ ★2枚目の守りは残します:現場の `.npmrc` に実物の値が入っていれば、配り直しが `Read(/.npmrc)` と `Edit(/.npmrc)` を狙い撃ちで戻します。
885
+ - 試験:`scripts/hooks/test_npmrc_ref_only.py`・`test/site-npmrc-edit-retire.test.ts`・`test/write-deny-retired.test.ts`。
886
+
859
887
  ## 2. ファイルの役割
860
888
 
861
889
  | ファイル | 役割 |
@@ -302,7 +302,8 @@ def build_output(data, datalink=hook_datalink, codex=False):
302
302
  # ① 報告の置き場の中のファイルへの Write / Edit / MultiEdit(=報告を書く・直す)
303
303
  # ② 報告の置き場の中のファイルの Read(Edit は先に読む必要があるため)
304
304
  # ③ 報告の置き場のフォルダを作る Bash(`mkdir -p <報告の置き場…>` の1コマンドだけ)
305
- # ④ 完了の知らせ(道具の名前が `conductor_complete` で終わる物)
305
+ # ④ 完了の知らせ(管制の道具の名前の決まり=CONDUCTOR_TOOL_PREFIXES の2通りの頭+`conductor_complete`
306
+ # とちょうど同じ物だけ・ほかのコネクタの同じ名前は通さない=便 12526bb8)と、その読み込みの ToolSearch
306
307
  # ★報告の置き場の決め方は finish_gate.report_dirs が正本(字面を2か所に置かない)。
307
308
  #
308
309
  # 【効かない範囲】ほかの便・ほかの現場・別のセッションには効かない(印の名前が変わる)。
@@ -317,8 +318,47 @@ _REPORT_READ_TOOLS = frozenset({'Read', 'NotebookRead'})
317
318
  #: 報告の置き場を作る形で許す道具(これ以外の Bash は通さない)。
318
319
  _REPORT_MKDIR = 'mkdir'
319
320
  _REPORT_MKDIR_FLAGS = frozenset({'-p', '--parents', '-pv', '-v', '--verbose'})
320
- #: 完了の知らせの道具を読み込む ToolSearch の query(これちょうどのときだけ通す)。
321
- _COMPLETE_TOOL_SELECT = 'select:mcp__ai-kana__conductor_complete'
321
+ # ── 管制(ai-kana)の道具の名前の決まり(★正本はここ1か所・便 12526bb8) ──
322
+ # 【なぜ2通りか(実地 便 ba854574・TYHLD-GOTO)】ai-kana の道具は、機体によって名前の頭が違う。
323
+ # Claude Code に MCP として入れた機体(えふさん・太田さん)は `mcp__ai-kana__<道具>`、
324
+ # claude.ai のコネクタだけの機体(後藤さん)は `mcp__claude_ai_ai-kana__<道具>`。
325
+ # 前は ToolSearch の読み込みを `mcp__ai-kana__` の形だけで通していたので、コネクタだけの機体では
326
+ # danger の後に完了の知らせを読み込めず、便を報告で終えられなかった。
327
+ # ★通すのは下の頭+決められた道具の名前と【ちょうど同じ】物だけ。ほかのコネクタの同じ名前の道具
328
+ # (`mcp__other__conductor_complete`)や、前後に文字が付いた名前は通さない。
329
+ #: 管制の道具の名前の頭(MCP として入れた形/claude.ai のコネクタから来た形)。
330
+ CONDUCTOR_TOOL_PREFIXES = ('mcp__ai-kana__', 'mcp__claude_ai_ai-kana__')
331
+ #: danger のあとでも通す管制の道具(これだけ)。
332
+ _AFTER_DANGER_CONDUCTOR_TOOLS = ('conductor_complete',)
333
+ #: ToolSearch で道具を名指しして読み込む query の頭。
334
+ _SELECT_PREFIX = 'select:'
335
+
336
+
337
+ def conductor_tool_names(tools=_AFTER_DANGER_CONDUCTOR_TOOLS):
338
+ """管制の道具の、機体ごとに在り得る名前をすべて返す(頭2通り × 道具)。"""
339
+ return tuple(p + t for t in tools for p in CONDUCTOR_TOOL_PREFIXES)
340
+
341
+
342
+ def is_conductor_tool(name, tools=_AFTER_DANGER_CONDUCTOR_TOOLS):
343
+ """その名前が、決められた管制の道具の名前と【ちょうど同じ】なら True。"""
344
+ return isinstance(name, str) and name in conductor_tool_names(tools)
345
+
346
+
347
+ def is_conductor_tool_select(query, tools=_AFTER_DANGER_CONDUCTOR_TOOLS):
348
+ """ToolSearch の query が、決められた管制の道具【だけ】を名指しで読み込む形なら True。
349
+
350
+ `select:<名前>[,<名前>…]` の名前がすべて管制の決められた道具のときだけ通す
351
+ (1つでもほかの道具が混ざれば通さない=ほかの道具の読み込みは今までどおり止める)。
352
+ """
353
+ q = str(query or '')
354
+ if not q.startswith(_SELECT_PREFIX):
355
+ return False
356
+ names = [n.strip() for n in q[len(_SELECT_PREFIX):].split(',')]
357
+ return bool(names) and all(is_conductor_tool(n, tools) for n in names)
358
+
359
+
360
+ #: 止めたときの文に出す読み込みの形(機体ごとに名前が違うので2通りとも出す)。
361
+ _COMPLETE_TOOL_SELECTS = tuple(_SELECT_PREFIX + n for n in conductor_tool_names())
322
362
 
323
363
 
324
364
  def _report_store_dirs(env=None):
@@ -379,13 +419,14 @@ def after_danger_allowed(data, env=None):
379
419
  tin = data.get('tool_input')
380
420
  if not isinstance(tin, dict):
381
421
  tin = {}
382
- if tool.rsplit('__', 1)[-1] == 'conductor_complete':
422
+ # ★管制の完了の知らせ(名前は機体ごとに2通り・ちょうど同じ物だけ=便 12526bb8)。
423
+ if is_conductor_tool(tool):
383
424
  return True
384
425
  # ★完了の知らせの道具を読み込むだけの ToolSearch(便 e338e926・実地 便 0d887e4e・11265a0a・4cde5905)。
385
426
  # 読み込まないと conductor_complete を呼べず、止まった便を報告で終えられない。
386
- # query がこの1つちょうどのときだけ通す(ほかの道具の読み込みは今までどおり止める)。
427
+ # query が管制の完了の知らせだけを名指しするときだけ通す(ほかの道具の読み込みは今までどおり止める)。
387
428
  if tool == 'ToolSearch':
388
- return str(tin.get('query') or '') == _COMPLETE_TOOL_SELECT
429
+ return is_conductor_tool_select(tin.get('query'))
389
430
  if tool in _REPORT_WRITE_TOOLS or tool in _REPORT_READ_TOOLS:
390
431
  return inside_report_store(tin.get('file_path') or tin.get('notebook_path') or '', env)
391
432
  if tool == 'Bash':
@@ -416,7 +457,7 @@ def danger_stop_reason(key, base, env=None):
416
457
  '止められた命令の全文と番人の文を報告して停止してください(鉄則4・鉄則の常連 ⑤-2)。'
417
458
  'いま通すのは、報告の置き場の中のファイルを書く・直す・読む/その置き場を作る mkdir -p/'
418
459
  '完了の知らせ(conductor_complete と、その読み込み=ToolSearch の '
419
- f'{_COMPLETE_TOOL_SELECT})だけです。'
460
+ f'{" または ".join(_COMPLETE_TOOL_SELECTS)})だけです。'
420
461
  f'★誤って止まったときは、人が自分のターミナルで印を消します: rm -r {marker}'
421
462
  f'{base_reason}'
422
463
  )
@@ -451,6 +451,137 @@ def secret_reason(path: str, cwd=None):
451
451
  return None
452
452
 
453
453
 
454
+ # ─────────────────────────────────────────────────────────────────────────────
455
+ # 値の入っていない .npmrc は、作る・直す・記録に入れるのを通す(えふさん決定 2026-11-03・便 5751e7ae)
456
+ #
457
+ # 【何が起きていたか】共通部品(@tyhld/*)を取ってくる .npmrc は、中身が「取り寄せ先の行」と
458
+ # 「鍵の置き場の名前(${NPM_TOKEN})」だけで、鍵の値は無い。それでも名前だけで秘密と判定していた
459
+ # ので、職人の Write(便 9ca0acd2)も git add(便 6a4e2122・danger: secret file (.npmrc) sent by git add)
460
+ # も止まり、そのたびにえふさんの手番になっていた。
461
+ # 【どう直したか】番人が中身を読んで(★外には1文字も出さない)、許す形の行【だけ】のときに限って通す。
462
+ # 許す形=空行・注釈・`registry=<URL>`・`@<scope>:registry=<URL>`・`//<ホスト>/:_authToken=${<名前>}`。
463
+ # ★それ以外の行(鍵の実物・_auth・_password・always-auth・username・email・未知の行)が1行でも在れば、
464
+ # 今までどおり秘密として止める。URL に名前や合言葉を書く形(https://u:p@host)も止める。
465
+ # 【通すのは次の4つがそろうときだけ】
466
+ # ① 字面も実体も名前が .npmrc で、ほかの秘密の理由(秘密の置き場の下 等)が無い
467
+ # ② 近道(symlink)ではない・ホームの直下(~/.npmrc=人の本物の鍵の置き場)ではない
468
+ # ③ 中身(書いた後・記録に入る物)が許す形だけ
469
+ # ④ 上書き・直しなら、元の中身も許す形だけ(実物の鍵が入った .npmrc は消させない・書き換えさせない)
470
+ # ★読む(Read・cat)は今までどおり止める(職人が中身を読む必要は無い。判定は番人がする)。
471
+ # ★Bash で書く(cp・tee・>)は今までどおり止める(ここで通すのは Write/Edit と git add・git commit だけ)。
472
+ # ─────────────────────────────────────────────────────────────────────────────
473
+
474
+ #: 番人が読んで確かめる .npmrc の大きさの上限(これより大きければ確かめない=止める)。
475
+ _NPMRC_MAX_BYTES = 8 * 1024
476
+
477
+ #: 取り寄せ先の URL(名前・合言葉・問い合わせ・${} を含む形は当たらない)。
478
+ _NPMRC_URL = r'https?://[A-Za-z0-9.-]+(:[0-9]{1,5})?(/[A-Za-z0-9._~%/-]*)?'
479
+ _NPMRC_REGISTRY_RE = re.compile(
480
+ r'^(@[a-z0-9][a-z0-9._-]*:)?registry\s*=\s*' + _NPMRC_URL + r'$')
481
+ #: 鍵の行は「鍵の置き場の名前の参照」だけ。★右が ${名前} ちょうどでなければ当たらない。
482
+ _NPMRC_TOKEN_REF_RE = re.compile(
483
+ r'^//[A-Za-z0-9.-]+(:[0-9]{1,5})?(/[A-Za-z0-9._~%-]+)*/:_authToken\s*=\s*'
484
+ r'\$\{[A-Za-z_][A-Za-z0-9_]*\}$')
485
+ _NPMRC_SECRET_REASON = 'secret file (.npmrc)'
486
+
487
+
488
+ def npmrc_text_is_ref_only(text) -> bool:
489
+ """.npmrc の中身が許す形の行だけか。★中身は返さない・どこにも出さない(はい/いいえだけ)。"""
490
+ if not isinstance(text, str) or len(text.encode('utf-8', 'replace')) > _NPMRC_MAX_BYTES:
491
+ return False
492
+ if '\x00' in text:
493
+ return False
494
+ for raw in text.splitlines():
495
+ line = raw.strip()
496
+ if not line or line.startswith('#') or line.startswith(';'):
497
+ continue
498
+ if _NPMRC_REGISTRY_RE.match(line) or _NPMRC_TOKEN_REF_RE.match(line):
499
+ continue
500
+ return False
501
+ return True
502
+
503
+
504
+ def _npmrc_read_text(path):
505
+ """番人が .npmrc の中身を読む(★中身は判定にだけ使う)。無ければ ''、読めなければ None。"""
506
+ try:
507
+ if not os.path.lexists(path):
508
+ return ''
509
+ if os.path.islink(path) or not os.path.isfile(path):
510
+ return None
511
+ if os.path.getsize(path) > _NPMRC_MAX_BYTES:
512
+ return None
513
+ with open(path, 'rb') as f:
514
+ data = f.read(_NPMRC_MAX_BYTES + 1)
515
+ return data.decode('utf-8')
516
+ except Exception: # noqa: BLE001
517
+ return None
518
+
519
+
520
+ def _npmrc_place_ok(path: str) -> bool:
521
+ """①② 名前が .npmrc で、ほかの秘密の理由が無く、近道でもホームの直下でもない。"""
522
+ if not path or not os.path.isabs(path):
523
+ return False
524
+ if os.path.basename(path) != '.npmrc' or secret_reason(path) != _NPMRC_SECRET_REASON:
525
+ return False
526
+ try:
527
+ if os.path.islink(path):
528
+ return False
529
+ real = os.path.realpath(path)
530
+ except Exception: # noqa: BLE001
531
+ return False
532
+ if os.path.basename(real) != '.npmrc' or secret_reason(real) != _NPMRC_SECRET_REASON:
533
+ return False
534
+ # ★名前の判定が先に当たるので、置き場(.ssh などの下)は親のフォルダで測り直す。
535
+ if secret_reason(os.path.dirname(path)) or secret_reason(os.path.dirname(real)):
536
+ return False
537
+ home = _home_dir()
538
+ if home and (os.path.dirname(real) == home or _under_home_dot_dir(real)):
539
+ return False
540
+ return True
541
+
542
+
543
+ def npmrc_file_is_ref_only(path: str) -> bool:
544
+ """在る .npmrc(記録に入れる物)が、許す場所の、許す形の中身だけか。"""
545
+ if not _npmrc_place_ok(path):
546
+ return False
547
+ text = _npmrc_read_text(path)
548
+ return bool(text) and npmrc_text_is_ref_only(text)
549
+
550
+
551
+ def _npmrc_apply_edits(text, edits):
552
+ """Edit/MultiEdit の置き換えを順に当てた後の中身。当てられなければ None(=止める)。"""
553
+ for e in edits:
554
+ if not isinstance(e, dict):
555
+ return None
556
+ old, new = e.get('old_string'), e.get('new_string')
557
+ if not isinstance(old, str) or not isinstance(new, str) or not old:
558
+ return None
559
+ n = text.count(old)
560
+ if n == 0 or (n > 1 and not e.get('replace_all')):
561
+ return None
562
+ text = text.replace(old, new) if e.get('replace_all') else text.replace(old, new, 1)
563
+ return text
564
+
565
+
566
+ def npmrc_write_is_ref_only(path: str, tool, tool_input) -> bool:
567
+ """Write/Edit/MultiEdit の後の中身と、元の中身の両方が許す形だけか(③④)。"""
568
+ if not _npmrc_place_ok(path) or not isinstance(tool_input, dict):
569
+ return False
570
+ before = _npmrc_read_text(path)
571
+ if before is None or (before and not npmrc_text_is_ref_only(before)):
572
+ return False
573
+ if tool == 'Write':
574
+ after = tool_input.get('content')
575
+ elif tool == 'Edit':
576
+ after = _npmrc_apply_edits(before, [tool_input]) if before else None
577
+ elif tool == 'MultiEdit':
578
+ edits = tool_input.get('edits')
579
+ after = _npmrc_apply_edits(before, edits) if before and isinstance(edits, list) else None
580
+ else:
581
+ return False
582
+ return isinstance(after, str) and bool(after.strip()) and npmrc_text_is_ref_only(after)
583
+
584
+
454
585
  # システム領域だが書いても無害な特殊ファイル(捨て先・標準出力など)。
455
586
  # ★ここを除外しないと `... > /dev/null` という日常操作が止まる(実際に止まった)。
456
587
  _HARMLESS_DEVICES = frozenset({
@@ -4327,6 +4458,9 @@ def _vcs_file_danger(tokens, cwd=None):
4327
4458
  verb = _exe_base(tokens[vi])
4328
4459
  args = tokens[vi + 1:]
4329
4460
  where = cwd
4461
+ # 記録に入れる名指しのうち、値の入っていない .npmrc なら通してよい物(便 5751e7ae)。
4462
+ # ★作業場所を確かめられない形(git -C "$DIR")は、番人が読む物と記録に入る物が違い得るので数えない。
4463
+ ref_ok_paths = set()
4330
4464
  if verb == 'git':
4331
4465
  sub, rest = _git_subcommand(args)
4332
4466
  got = _git_cwd(args, cwd)
@@ -4341,9 +4475,14 @@ def _vcs_file_danger(tokens, cwd=None):
4341
4475
  vals = _flag_values(rest, *spec)
4342
4476
  if sub == 'commit':
4343
4477
  # git commit の名指し(便 16b2f958)。pathspec の頭(`:(top)`)は外し、除く指定は見ない。
4344
- vals = vals + [b for b in map(_pathspec_body, _git_commit_paths(rest)) if b]
4478
+ named = [b for b in map(_pathspec_body, _git_commit_paths(rest)) if b]
4479
+ vals = vals + named
4480
+ if got is not _UNKNOWN_DIR:
4481
+ ref_ok_paths = set(named)
4345
4482
  elif staged is not None:
4346
4483
  vals = staged # 記録に入れる名指し(便 9faa1627)
4484
+ if sub in ('add', 'stage') and got is not _UNKNOWN_DIR:
4485
+ ref_ok_paths = set(staged)
4347
4486
  else:
4348
4487
  return None
4349
4488
  label = f'git {sub}'
@@ -4365,6 +4504,9 @@ def _vcs_file_danger(tokens, cwd=None):
4365
4504
  if not v or v == '-':
4366
4505
  continue
4367
4506
  sr = secret_reason(v, where)
4507
+ if sr == _NPMRC_SECRET_REASON and v in ref_ok_paths and npmrc_file_is_ref_only(
4508
+ norm_path(v, where if (where and os.path.isabs(where)) else None)):
4509
+ continue
4368
4510
  if sr:
4369
4511
  return f'{sr} sent by {label}'
4370
4512
  return None
@@ -7145,7 +7287,7 @@ def norm_path(file_path: str, cwd=None) -> str:
7145
7287
  return os.path.normpath(p)
7146
7288
 
7147
7289
 
7148
- def decide_write(file_path: str, cwd=None):
7290
+ def decide_write(file_path: str, cwd=None, tool=None, tool_input=None):
7149
7291
  if not file_path or not isinstance(file_path, str) or not file_path.strip():
7150
7292
  return _r(ALLOW, 'empty file_path')
7151
7293
  try:
@@ -7154,6 +7296,11 @@ def decide_write(file_path: str, cwd=None):
7154
7296
  return _r(DENY, 'danger: unnormalizable path')
7155
7297
 
7156
7298
  sr = secret_reason(path)
7299
+ # ★値の入っていない .npmrc だけは、書いた後と元の中身を番人が確かめて通す(便 5751e7ae)。
7300
+ # 通した後も、下のシステム領域・番人の設定・.tyhld の判定はそのまま掛かる。
7301
+ npmrc_ok = sr == _NPMRC_SECRET_REASON and npmrc_write_is_ref_only(path, tool, tool_input)
7302
+ if npmrc_ok:
7303
+ sr = None
7157
7304
  if sr:
7158
7305
  return _r(DENY, f'danger: write to {sr}')
7159
7306
  syr = system_write_reason(path)
@@ -7176,7 +7323,7 @@ def decide_write(file_path: str, cwd=None):
7176
7323
  return _r(DENY, 'danger: write to guard directory (.tyhld)')
7177
7324
  # ★.env 類(雛形を含む)への書き込みは、Bash と同じく止める(便 3d11f913・番人でも結果を一致)。
7178
7325
  # 読み込みは変えない(secret_reason は雛形を通す)。
7179
- if _is_write_protected_name(_env_base(path)):
7326
+ if _is_write_protected_name(_env_base(path)) and not npmrc_ok:
7180
7327
  return _r(DENY, f'danger: secret file write ({_env_base(path)})')
7181
7328
  return _r(ALLOW, 'no gate, no danger')
7182
7329
 
@@ -7369,7 +7516,7 @@ def decide_event(data):
7369
7516
  fp = tin.get('file_path', '')
7370
7517
  if not fp:
7371
7518
  return _r(ALLOW, 'no file_path')
7372
- return decide_write(fp, data.get('cwd'))
7519
+ return decide_write(fp, data.get('cwd'), tool, tin)
7373
7520
  if tool in READ_TOOLS:
7374
7521
  fp = tin.get('file_path') or tin.get('notebook_path') or ''
7375
7522
  if not fp:
@@ -0,0 +1,216 @@
1
+ #!/usr/bin/env python3
2
+ """番人の直し(便 12526bb8)の検査: 管制(ai-kana)の道具の名前が機体ごとに2通りあっても、
3
+ danger のあとに完了の知らせ・その読み込みを通す。
4
+
5
+ 実行: python3 scripts/hooks/test_guard_conductor_tool_names.py
6
+ 1件でも期待と違えば exit 1。
7
+
8
+ 【なぜ要るか(実地 便 ba854574・TYHLD-GOTO・現場 kenzokun)】
9
+ claude.ai のコネクタだけの機体では、管制の道具は `mcp__claude_ai_ai-kana__<道具>` の名前になる。
10
+ 番人が danger のあとに通す読み込みは `select:mcp__ai-kana__conductor_complete` ちょうどだけだったので、
11
+ ・select:mcp__claude_ai_ai-kana__conductor_complete … danger で止められた
12
+ ・select:mcp__ai-kana__conductor_complete … その機体には無い名前(No matching deferred tools found)
13
+ となり、職人が完了の知らせを管制へ送れなかった。
14
+
15
+ 【ここで固定すること】
16
+ (n) 名前の決まり … 2通りの頭+決められた道具とちょうど同じ名前だけが管制の道具。
17
+ ほかのコネクタの同じ名前・前後に文字が付いた名前・ほかの管制の道具は当たらない。
18
+ (a) danger のあと … 2通りとも完了の知らせ・その読み込み(両方を1回で名指しする形も)が通る。
19
+ ほかのコネクタの同じ名前・似た名前・ほかの道具が混ざった読み込みは止まる。
20
+ (s) 秘密の守りは今までどおり … danger の前でも後でも、秘密の値を見る命令は止まる。
21
+ (b) danger の前 … 2通りとも完了の知らせは止めない(今までどおり)。
22
+ (v) ★空振り確認 … コネクタの形の頭を外すと、コネクタの名前の読み込み・呼び出しが止まる。
23
+
24
+ ★本物のホーム・本物の秘密には1バイトも触れない。作り物の置き場で判定する。
25
+ """
26
+ import json
27
+ import os
28
+ import shutil
29
+ import sys
30
+ import tempfile
31
+
32
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
33
+
34
+ failures = []
35
+
36
+
37
+ def check(label, got, want):
38
+ ok = got == want
39
+ if not ok:
40
+ failures.append(f'{label}: got={got!r} want={want!r}')
41
+ print(f'{"OK " if ok else "NG "} {label:72} {str(got)[:40]}')
42
+
43
+
44
+ def truthy(label, got):
45
+ check(label, bool(got), True)
46
+
47
+
48
+ # ─────────────────────────────────────────────────────────────────────────────
49
+ # 作り物の置き場(★本物のホーム・本物の秘密には触れない)
50
+ # ─────────────────────────────────────────────────────────────────────────────
51
+ ROOT = tempfile.mkdtemp(prefix='guard-12526bb8-',
52
+ dir='/tmp/claude-1000' if os.path.isdir('/tmp/claude-1000') else None)
53
+ HOME = os.path.join(ROOT, 'home', 'tester')
54
+ STATE = os.path.join(ROOT, 'state')
55
+ WORK = os.path.join(HOME, 'projects', 'demo')
56
+ SITE = 'demo'
57
+ JOB = '12526bb8-6ba1-49ff-aec7-119b687ed026'
58
+ SESSION = 'se-12526bb8'
59
+
60
+
61
+ def mk(path, body=''):
62
+ os.makedirs(os.path.dirname(path), exist_ok=True)
63
+ with open(path, 'w', encoding='utf-8') as f:
64
+ f.write(body)
65
+ return path
66
+
67
+
68
+ os.makedirs(os.path.join(WORK, '.git'), exist_ok=True)
69
+ mk(os.path.join(WORK, 'src', 'a.ts'), 'export const a = 1\n')
70
+ os.environ['HOME'] = HOME
71
+ os.environ['TMPDIR'] = ROOT
72
+ os.environ['XDG_STATE_HOME'] = STATE
73
+ os.environ['CONDUCTOR_SITE'] = SITE
74
+ os.environ['CONDUCTOR_GUARD_LOG'] = os.path.join(ROOT, 'guard.log')
75
+ os.environ.pop('CONDUCTOR_REPORT_DIR', None)
76
+ os.environ.pop('CONDUCTOR_URL', None)
77
+ os.environ.pop('CONDUCTOR_TOKEN', None)
78
+ mk(os.path.join(STATE, 'conductor', f'active-job-{SITE}.json'),
79
+ json.dumps({'commandId': JOB, 'site': SITE, 'body': 'x'}))
80
+
81
+ import cc2_guard # noqa: E402
82
+ import hook_datalink # noqa: E402
83
+
84
+ MCP = 'mcp__ai-kana__conductor_complete' # Claude Code に MCP として入れた機体
85
+ CONNECTOR = 'mcp__claude_ai_ai-kana__conductor_complete' # claude.ai のコネクタだけの機体
86
+ LOOK_ALIKES = [
87
+ ('ほかのコネクタの同じ名前', 'mcp__claude_ai_Other__conductor_complete'),
88
+ ('ほかの MCP の同じ名前', 'mcp__evil__conductor_complete'),
89
+ ('頭に余計な文字', 'xmcp__ai-kana__conductor_complete'),
90
+ ('頭に余計な文字(コネクタ)', 'mcp__claude_ai_ai-kana-x__conductor_complete'),
91
+ ('後ろに余計な文字', 'mcp__ai-kana__conductor_complete2'),
92
+ ('後ろに余計な文字(コネクタ)', 'mcp__claude_ai_ai-kana__conductor_complete_x'),
93
+ ('前後に空白', ' mcp__ai-kana__conductor_complete '),
94
+ ('大文字に変えた', 'mcp__claude_ai_AI-KANA__conductor_complete'),
95
+ ('頭だけ', 'mcp__claude_ai_ai-kana__'),
96
+ ('ほかの管制の道具(返事)', 'mcp__claude_ai_ai-kana__conductor_reply'),
97
+ ('ほかの管制の道具(本番操作)', 'mcp__ai-kana__conductor_prod_op_request'),
98
+ ]
99
+
100
+ # ─────────────────────────────────────────────────────────────────────────────
101
+ # (n) 名前の決まり
102
+ # ─────────────────────────────────────────────────────────────────────────────
103
+ print('── (n) 名前の決まり ' + '─' * 50)
104
+ check('n1 在り得る名前は2通りだけ', sorted(cc2_guard.conductor_tool_names()), sorted([MCP, CONNECTOR]))
105
+ truthy('n2 MCP として入れた形は管制の道具', cc2_guard.is_conductor_tool(MCP))
106
+ truthy('n3 コネクタから来た形は管制の道具', cc2_guard.is_conductor_tool(CONNECTOR))
107
+ for label, name in LOOK_ALIKES:
108
+ check(f'n4 {label} は当たらない', cc2_guard.is_conductor_tool(name), False)
109
+ check('n5 名前でない物は当たらない', cc2_guard.is_conductor_tool(None), False)
110
+
111
+ # ─────────────────────────────────────────────────────────────────────────────
112
+ # (a) danger のあと
113
+ # ─────────────────────────────────────────────────────────────────────────────
114
+ print('── (a) danger のあと ' + '─' * 49)
115
+ KEY = (SESSION, SITE, JOB)
116
+
117
+
118
+ def ev(tool, tin, session=SESSION, cwd=WORK):
119
+ return {'tool_name': tool, 'tool_input': tin, 'cwd': cwd, 'session_id': session}
120
+
121
+
122
+ def run(data):
123
+ out = cc2_guard.guard_output(data)
124
+ if not out:
125
+ return 'defer', ''
126
+ spec = out['hookSpecificOutput']
127
+ return spec['permissionDecision'], spec.get('permissionDecisionReason', '')
128
+
129
+
130
+ def load(query):
131
+ return ev('ToolSearch', {'query': query, 'max_results': 2})
132
+
133
+
134
+ hook_datalink.clear_danger_stop(*KEY)
135
+ # ★便 ba854574 で正しく止められた形(秘密の値の有無を調べる)で danger にする。
136
+ dec, _ = run(ev('Bash', {'command': 'printenv NPM_TOKEN'}))
137
+ check('a0 秘密の名前を調べる命令は止まる(今までどおり)', dec, 'deny')
138
+ truthy('a0 印が置かれた', hook_datalink.danger_stop_active(*KEY))
139
+
140
+ A_PASS = [
141
+ ('a1 完了の知らせ(MCP の形)', ev(MCP, {'commandId': JOB})),
142
+ ('a2 完了の知らせ(コネクタの形)', ev(CONNECTOR, {'commandId': JOB})),
143
+ ('a3 読み込み(MCP の形)', load(f'select:{MCP}')),
144
+ ('a4 読み込み(コネクタの形)', load(f'select:{CONNECTOR}')),
145
+ ('a5 読み込み(両方を1回で名指し)', load(f'select:{MCP},{CONNECTOR}')),
146
+ ('a6 読み込み(両方・区切りに空白)', load(f'select:{CONNECTOR}, {MCP}')),
147
+ ]
148
+ for label, data in A_PASS:
149
+ truthy(label + ' は通る', run(data)[0] != 'deny')
150
+
151
+ A_DENY = [(f'a10 {label}(呼び出し)', ev(name.strip() if label == '前後に空白' else name,
152
+ {'commandId': JOB}))
153
+ for label, name in LOOK_ALIKES if label != '前後に空白']
154
+ A_DENY += [(f'a11 {label}(読み込み)', load(f'select:{name}')) for label, name in LOOK_ALIKES
155
+ if name.strip() not in (MCP, CONNECTOR)]
156
+ A_DENY += [
157
+ ('a12 コネクタの形にほかの道具を混ぜた読み込み', load(f'select:{CONNECTOR},WebFetch')),
158
+ ('a13 ほかのコネクタの道具を混ぜた読み込み',
159
+ load(f'select:{MCP},mcp__claude_ai_Supabase__execute_sql')),
160
+ ('a14 空の名指しを混ぜた読み込み', load(f'select:{CONNECTOR},')),
161
+ ('a15 名指しが空', load('select:')),
162
+ ('a16 select の前に文字', load(f'xselect:{CONNECTOR}')),
163
+ ('a17 言葉で探す読み込み(コネクタの名前)', load(CONNECTOR)),
164
+ ('a18 ほかの道具', ev('Bash', {'command': 'ls'})),
165
+ ]
166
+ for label, data in A_DENY:
167
+ check(label + ' は止まる', run(data)[0], 'deny')
168
+
169
+ why = run(ev('Bash', {'command': 'ls'}))[1]
170
+ truthy('a19 止めた文に、コネクタの形の読み込みも書いてある', f'select:{CONNECTOR}' in why)
171
+ truthy('a19 止めた文に、MCP の形の読み込みも書いてある', f'select:{MCP}' in why)
172
+
173
+ # ─────────────────────────────────────────────────────────────────────────────
174
+ # (s) 秘密の守りは今までどおり
175
+ # ─────────────────────────────────────────────────────────────────────────────
176
+ print('── (s) 秘密の守り ' + '─' * 52)
177
+ check('s1 danger のあとも秘密の名前を調べる命令は止まる',
178
+ run(ev('Bash', {'command': 'printenv NPM_TOKEN'}))[0], 'deny')
179
+ hook_datalink.clear_danger_stop(*KEY)
180
+ OTHER = 'se-12526bb8-before'
181
+ check('s2 danger の前でも秘密の名前を調べる命令は止まる',
182
+ run(ev('Bash', {'command': 'printenv NPM_TOKEN'}, session=OTHER))[0], 'deny')
183
+ hook_datalink.clear_danger_stop(OTHER, SITE, JOB)
184
+
185
+ # ─────────────────────────────────────────────────────────────────────────────
186
+ # (b) danger の前は今までどおり
187
+ # ─────────────────────────────────────────────────────────────────────────────
188
+ print('── (b) danger の前 ' + '─' * 51)
189
+ FRESH = 'se-12526bb8-fresh'
190
+ for name in (MCP, CONNECTOR):
191
+ truthy(f'b1 {name} は止めない', run(ev(name, {'commandId': JOB}, session=FRESH))[0] != 'deny')
192
+ truthy('b2 印は置かれていない', not hook_datalink.danger_stop_active(FRESH, SITE, JOB))
193
+
194
+ # ─────────────────────────────────────────────────────────────────────────────
195
+ # (v) ★空振り確認 … コネクタの形の頭を外すと、コネクタの名前が止まる(便 ba854574 の形に戻る)
196
+ # ─────────────────────────────────────────────────────────────────────────────
197
+ print('── (v) 空振り確認 ' + '─' * 52)
198
+ run(ev('Bash', {'command': 'printenv NPM_TOKEN'}))
199
+ saved = cc2_guard.CONDUCTOR_TOOL_PREFIXES
200
+ cc2_guard.CONDUCTOR_TOOL_PREFIXES = ('mcp__ai-kana__',)
201
+ check('v1 頭を外すとコネクタの形の読み込みが止まる', run(load(f'select:{CONNECTOR}'))[0], 'deny')
202
+ check('v2 頭を外すとコネクタの形の呼び出しが止まる', run(ev(CONNECTOR, {'commandId': JOB}))[0], 'deny')
203
+ cc2_guard.CONDUCTOR_TOOL_PREFIXES = saved
204
+ truthy('v3 戻すと読み込みが通る', run(load(f'select:{CONNECTOR}'))[0] != 'deny')
205
+ truthy('v3 戻すと呼び出しが通る', run(ev(CONNECTOR, {'commandId': JOB}))[0] != 'deny')
206
+
207
+ hook_datalink.clear_danger_stop(*KEY)
208
+ shutil.rmtree(ROOT, ignore_errors=True) # ★作り物は毎回片付ける
209
+
210
+ print()
211
+ if failures:
212
+ print(f'NG {len(failures)} 件')
213
+ for f in failures:
214
+ print(' ', f)
215
+ sys.exit(1)
216
+ print('すべて期待どおり')
@@ -19,7 +19,8 @@ danger のあとの完了の知らせの読み込み。
19
19
  (g) `*`・変数 … 展開して当たった物を今の判定に当てる。秘密に当たれば止まる。
20
20
  当たり0件・名前が決まらない変数は、今までどおり作業場所に倒して止まる。
21
21
  (d) danger のあと … ToolSearch の query が select:mcp__ai-kana__conductor_complete ちょうどの
22
- ときだけ通る。ほかの道具の読み込みは止まる。
22
+ ときだけ通る。ほかの道具の読み込みは止まる(★コネクタの名前の形は
23
+ test_guard_conductor_tool_names.py=便 12526bb8)。
23
24
  (v) ★空振り確認 … 直した所を外すと、上の期待が実際に崩れる。
24
25
 
25
26
  ★本物のホーム・本物の秘密には1バイトも触れない。作り物の置き場で判定する。
@@ -245,10 +246,10 @@ check('v2 展開を外すと `*` の検索が作業場所に倒れて止まる'
245
246
  policy._expand_read_arg = saved_ex
246
247
  check('v2 戻すと通る', decide(G_ALLOW[0][1]), policy.ALLOW)
247
248
 
248
- saved_sel = cc2_guard._COMPLETE_TOOL_SELECT
249
- cc2_guard._COMPLETE_TOOL_SELECT = '(外した)'
249
+ saved_sel = cc2_guard.CONDUCTOR_TOOL_PREFIXES
250
+ cc2_guard.CONDUCTOR_TOOL_PREFIXES = ('(外した)',)
250
251
  check('v3 一覧から外すと完了の知らせの読み込みが止まる', run(COMPLETE_LOAD)[0], 'deny')
251
- cc2_guard._COMPLETE_TOOL_SELECT = saved_sel
252
+ cc2_guard.CONDUCTOR_TOOL_PREFIXES = saved_sel
252
253
  truthy('v3 戻すと通る', run(COMPLETE_LOAD)[0] != 'deny')
253
254
 
254
255
  hook_datalink.clear_danger_stop(*KEY)
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env python3
2
+ """便 5751e7ae: 値の入っていない .npmrc は、職人が作る・直す・記録に入れるのを通す試験。
3
+
4
+ 実行: python3 scripts/hooks/test_npmrc_ref_only.py
5
+ 1件でも期待と違えば exit 1。
6
+
7
+ 【背景】共通部品(@tyhld/*)を取ってくる .npmrc は「取り寄せ先の行」と「鍵の置き場の名前(${NPM_TOKEN})」
8
+ だけで、鍵の値は無い。それでも名前だけで秘密と判定していたので、職人の Write(便 9ca0acd2)も
9
+ git add(便 6a4e2122・danger: secret file (.npmrc) sent by git add)も止まり、えふさんの手番になっていた。
10
+
11
+ 【固定すること】
12
+ ① 値なしの .npmrc は Write・Edit・MultiEdit・git add・git commit が通る。
13
+ ② _authToken の右が実物の文字列/未知の行/_auth・_password・always-auth・username の行/
14
+ URL に名前・合言葉を書いた形 が1つでも混じれば、今までどおり止まる。
15
+ ③ 元の中身に実物が在る .npmrc は、値なしの中身でも上書き・直しで消させない。
16
+ ④ 近道(symlink)・ホームの直下(~/.npmrc)・秘密の置き場の下・作業場所を確かめられない git -C "$DIR" は止まる。
17
+ ⑤ 読む(Read・cat)・Bash で書く(cp・tee・>)は今までどおり止まる。
18
+ ⑥ .env など他の秘密のファイルの Write・git add は今までどおり止まる。
19
+ ⑦ 禁止の一覧(sales-template/settings.json)から Edit(**/.npmrc) を外し、退役の一覧に入れた。
20
+
21
+ ★鍵はすべて作り物。本物の .npmrc・~/.npmrc は1バイトも読まない・書かない(場所は /tmp の下の使い捨て)。
22
+ """
23
+ import json
24
+ import os
25
+ import shutil
26
+ import subprocess
27
+ import sys
28
+ import tempfile
29
+
30
+ HERE = os.path.dirname(os.path.abspath(__file__))
31
+ sys.path.insert(0, HERE)
32
+
33
+ import policy # noqa: E402
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)[:24]}')
43
+
44
+
45
+ NAME = '.npm' + 'rc'
46
+ ENV = '.e' + 'nv'
47
+ FAKE = 'FAKE_npm_' + 'x' * 20 # 作り物の鍵(実物の形に似せない)
48
+ REG = '@tyhld:registry=https://npm.pkg.github.com\n'
49
+ REF = '//npm.pkg.github.com/:_authToken=${NPM_TOKEN}\n'
50
+ SAFE = REG + REF
51
+
52
+ BASE = tempfile.mkdtemp(prefix='npmrc-ref-only-', dir='/tmp')
53
+ REPO = os.path.join(BASE, 'site')
54
+ os.makedirs(REPO)
55
+ subprocess.run(['git', 'init', '-q', REPO], check=True)
56
+ P = os.path.join(REPO, NAME)
57
+
58
+
59
+ def put(text, path=P):
60
+ with open(path, 'w', encoding='utf-8') as f:
61
+ f.write(text)
62
+
63
+
64
+ def gone(path=P):
65
+ if os.path.lexists(path):
66
+ os.remove(path)
67
+
68
+
69
+ def ev(tool, tin, cwd=REPO):
70
+ return policy.decide_event({'tool_name': tool, 'cwd': cwd, 'tool_input': tin})['decision']
71
+
72
+
73
+ def bash(cmd, cwd=REPO):
74
+ return policy.decide_bash(cmd, cwd)['decision']
75
+
76
+
77
+ A, D = policy.ALLOW, policy.DENY
78
+
79
+ try:
80
+ print('── 中身の判定(はい/いいえだけ・中身は返さない) ' + '─' * 20)
81
+ for label, text, want in [
82
+ ('取り寄せ先+鍵の置き場の名前', SAFE, True),
83
+ ('取り寄せ先だけ', REG, True),
84
+ ('既定の取り寄せ先', 'registry=https://registry.npmjs.org/\n', True),
85
+ ('空行・注釈(# と ;)', '# 注釈\n\n; 注釈\n' + SAFE, True),
86
+ ('= の前後に空白', '@tyhld:registry = https://npm.pkg.github.com\n'
87
+ '//npm.pkg.github.com/:_authToken = ${NPM_TOKEN}\n', True),
88
+ ('CRLF の行末', SAFE.replace('\n', '\r\n'), True),
89
+ ('鍵の実物', REG + f'//npm.pkg.github.com/:_authToken={FAKE}\n', False),
90
+ ('参照の前後に実物', REG + '//npm.pkg.github.com/:_authToken=x${NPM_TOKEN}\n', False),
91
+ ('参照が2つ', REG + '//npm.pkg.github.com/:_authToken=${A}${B}\n', False),
92
+ ('$NAME の形(括弧なし)', REG + '//npm.pkg.github.com/:_authToken=$NPM_TOKEN\n', False),
93
+ ('_auth の行', REG + '//npm.pkg.github.com/:_auth=${NPM_AUTH}\n', False),
94
+ ('_password の行', REG + '//npm.pkg.github.com/:_password=${P}\n', False),
95
+ ('always-auth の行', SAFE + 'always-auth=true\n', False),
96
+ ('username の行', SAFE + '//npm.pkg.github.com/:username=u\n', False),
97
+ ('未知の行', SAFE + 'foo=bar\n', False),
98
+ ('URL に名前と合言葉', '@tyhld:registry=https://u:p@npm.pkg.github.com\n', False),
99
+ ('URL に問い合わせ', '@tyhld:registry=https://npm.pkg.github.com/?token=x\n', False),
100
+ ('取り寄せ先に参照', '@tyhld:registry=${REG_URL}\n', False),
101
+ ('鍵の行の先がホームでない', REG + 'npm.pkg.github.com/:_authToken=${NPM_TOKEN}\n', False),
102
+ ('大きすぎる', '#' + 'x' * 9000 + '\n', False),
103
+ ]:
104
+ check(f'中身: {label}', policy.npmrc_text_is_ref_only(text), want)
105
+
106
+ print('── ① 値なしの .npmrc は Write・Edit・MultiEdit が通る ' + '─' * 16)
107
+ gone()
108
+ check('Write: 新しく作る(値なし)', ev('Write', {'file_path': P, 'content': SAFE}), A)
109
+ check('Write: 相対の名前で作る(値なし)', ev('Write', {'file_path': NAME, 'content': SAFE}), A)
110
+ put(REG)
111
+ check('Write: 値なしの上に値なしを書く', ev('Write', {'file_path': P, 'content': SAFE}), A)
112
+ check('Edit: 値なしへ鍵の置き場の名前の行を足す',
113
+ ev('Edit', {'file_path': P, 'old_string': REG, 'new_string': SAFE}), A)
114
+ check('MultiEdit: 値なしのまま2か所を直す',
115
+ ev('MultiEdit', {'file_path': P, 'edits': [
116
+ {'old_string': '@tyhld', 'new_string': '@tyhld'},
117
+ {'old_string': 'npm.pkg', 'new_string': 'npm.pkg'}]}), A)
118
+
119
+ print('── ② 書いた後に値・未知の行が入る形は止まる ' + '─' * 24)
120
+ gone()
121
+ check('Write: 鍵の実物', ev('Write', {'file_path': P, 'content':
122
+ REG + f'//npm.pkg.github.com/:_authToken={FAKE}\n'}), D)
123
+ check('Write: 未知の行が混じる', ev('Write', {'file_path': P, 'content': SAFE + 'foo=bar\n'}), D)
124
+ check('Write: always-auth が混じる', ev('Write', {'file_path': P, 'content': SAFE + 'always-auth=true\n'}), D)
125
+ check('Write: 中身が空', ev('Write', {'file_path': P, 'content': ''}), D)
126
+ check('Write: 中身が無い', ev('Write', {'file_path': P}), D)
127
+ put(SAFE)
128
+ check('Edit: 参照を実物に替える',
129
+ ev('Edit', {'file_path': P, 'old_string': '${NPM_TOKEN}', 'new_string': FAKE}), D)
130
+ check('Edit: 当てる文字が無い', ev('Edit', {'file_path': P, 'old_string': 'zzz', 'new_string': 'y'}), D)
131
+ check('MultiEdit: 2つ目で実物が入る', ev('MultiEdit', {'file_path': P, 'edits': [
132
+ {'old_string': '@tyhld', 'new_string': '@tyhld'},
133
+ {'old_string': '${NPM_TOKEN}', 'new_string': FAKE}]}), D)
134
+ check('NotebookEdit は今までどおり止まる', ev('NotebookEdit', {'file_path': P, 'new_source': SAFE}), D)
135
+ gone()
136
+ check('Edit: まだ無いファイル', ev('Edit', {'file_path': P, 'old_string': 'a', 'new_string': 'b'}), D)
137
+
138
+ print('── ③ 元に実物が在る .npmrc は消させない・書き換えさせない ' + '─' * 10)
139
+ put(REG + f'//npm.pkg.github.com/:_authToken={FAKE}\n')
140
+ check('Write: 実物の上に値なしを書く', ev('Write', {'file_path': P, 'content': SAFE}), D)
141
+ check('Edit: 実物を参照へ替える',
142
+ ev('Edit', {'file_path': P, 'old_string': FAKE, 'new_string': '${NPM_TOKEN}'}), D)
143
+
144
+ print('── ① 値なしの .npmrc は git add・git commit が通る ' + '─' * 18)
145
+ put(SAFE)
146
+ check('git add .npmrc', bash(f'git add {NAME}'), A)
147
+ check('git add ほかと並べて名指し', bash(f'git add package.json src/App.tsx {NAME}'), A)
148
+ check('git add -- .npmrc', bash(f'git add -- {NAME}'), A)
149
+ check('git -C <実際の場所> add .npmrc', bash(f'git -C {REPO} add {NAME}', BASE), A)
150
+ check('git add <絶対パス>', bash(f'git add {P}'), A)
151
+ check('git stage .npmrc', bash(f'git stage {NAME}'), A)
152
+ check('git commit -m x .npmrc', bash(f'git commit -m x {NAME}'), A)
153
+ check('git commit -m x -- .npmrc', bash(f'git commit -m x -- {NAME}'), A)
154
+
155
+ print('── ② 中身が許す形でない .npmrc の git add・git commit は止まる ' + '─' * 6)
156
+ for label, text in [('鍵の実物', REG + f'//npm.pkg.github.com/:_authToken={FAKE}\n'),
157
+ ('未知の行', SAFE + 'foo=bar\n'),
158
+ ('_auth の行', SAFE + '//npm.pkg.github.com/:_auth=${A}\n')]:
159
+ put(text)
160
+ check(f'git add({label})', bash(f'git add {NAME}'), D)
161
+ check(f'git commit -m x({label})', bash(f'git commit -m x {NAME}'), D)
162
+ gone()
163
+ check('git add(まだ無い .npmrc)', bash(f'git add {NAME}'), D)
164
+
165
+ print('── ④ 場所で止まる形 ' + '─' * 46)
166
+ put(SAFE)
167
+ check('git -C "$DIR" add .npmrc(作業場所を確かめられない)', bash(f'git -C "$DIR" add {NAME}'), D)
168
+ check('git hash-object -w .npmrc(記録の別の入口は今までどおり)', bash(f'git hash-object -w {NAME}'), D)
169
+ link_dir = os.path.join(BASE, 'linked')
170
+ os.makedirs(link_dir)
171
+ os.symlink(P, os.path.join(link_dir, NAME))
172
+ check('Write: 近道の .npmrc', ev('Write', {'file_path': os.path.join(link_dir, NAME), 'content': SAFE},
173
+ link_dir), D)
174
+ check('git add: 近道の .npmrc', bash(f'git add {NAME}', link_dir), D)
175
+ ssh_dir = os.path.join(BASE, '.ssh')
176
+ os.makedirs(ssh_dir)
177
+ check('Write: 秘密の置き場の下の .npmrc',
178
+ ev('Write', {'file_path': os.path.join(ssh_dir, NAME), 'content': SAFE}, ssh_dir), D)
179
+ home_rc = os.path.join(os.path.realpath(os.path.expanduser('~')), NAME)
180
+ check('Write: ホームの直下(~/.npmrc)', ev('Write', {'file_path': home_rc, 'content': SAFE}), D)
181
+ check('Write: ~/.npmrc の書き方', ev('Write', {'file_path': '~/' + NAME, 'content': SAFE}), D)
182
+ check('Write: ホームの隠しフォルダの下',
183
+ ev('Write', {'file_path': os.path.expanduser('~/.config/x/' + NAME), 'content': SAFE}), D)
184
+
185
+ print('── ⑤ 読む・Bash で書くのは今までどおり止まる ' + '─' * 22)
186
+ put(SAFE)
187
+ check('Read .npmrc', ev('Read', {'file_path': P}), D)
188
+ check(f'cat {NAME}', bash(f'cat {NAME}'), D)
189
+ check(f'cp a {NAME}', bash(f'cp a {NAME}'), D)
190
+ check(f'echo x > {NAME}', bash(f'echo x > {NAME}'), D)
191
+ check(f'tee {NAME}', bash(f'tee {NAME} < a'), D)
192
+
193
+ print('── ⑥ .env など他の秘密のファイルは今までどおり止まる ' + '─' * 14)
194
+ for other in (ENV, ENV + '.local', 'id_' + 'rsa', 'server.pem', '.dev.vars', '.net' + 'rc'):
195
+ put('x=1\n', os.path.join(REPO, other))
196
+ check(f'Write {other}', ev('Write', {'file_path': os.path.join(REPO, other), 'content': SAFE}), D)
197
+ check(f'git add {other}', bash(f'git add {other}'), D)
198
+
199
+ print('── ⑦ 禁止の一覧から Edit(**/.npmrc) を外し、退役の一覧に入れた ' + '─' * 4)
200
+ root = os.path.dirname(os.path.dirname(HERE))
201
+ with open(os.path.join(root, 'sales-template', 'settings.json'), encoding='utf-8') as f:
202
+ deny = json.load(f)['permissions']['deny']
203
+ check('正本の禁止の一覧に Edit(**/.npmrc) が無い', f'Edit(**/{NAME})' in deny, False)
204
+ check('正本の禁止の一覧に Read(**/.npmrc) が無い(前の退役のまま)', f'Read(**/{NAME})' in deny, False)
205
+ with open(os.path.join(root, 'scripts', 'update-guard.sh'), encoding='utf-8') as f:
206
+ ug = f.read()
207
+ check('退役の一覧に "Edit(**/.npmrc)" が在る(各現場からも外す)', f'"Edit(**/{NAME})"' in ug, True)
208
+ check('実物の入った現場には Edit(/.npmrc) を狙い撃ちで戻す', f'"Edit(/{NAME})"' in ug, True)
209
+ finally:
210
+ shutil.rmtree(BASE, ignore_errors=True)
211
+
212
+ print()
213
+ if failures:
214
+ print(f'FAIL {len(failures)} 件')
215
+ for x in failures:
216
+ print(' ' + x)
217
+ sys.exit(1)
218
+ print('PASS')
@@ -223,7 +223,7 @@ def classify(head, work, ctx):
223
223
  if not isinstance(wd, list) or not isinstance(hd, list):
224
224
  why.append("permissions.deny が一覧ではない")
225
225
  else:
226
- allowed = set(ctx["canonical_deny"]) | set(ctx["retired"]) | {"Read(/.npmrc)"}
226
+ allowed = set(ctx["canonical_deny"]) | set(ctx["retired"]) | {"Read(/.npmrc)", "Edit(/.npmrc)"}
227
227
  added = [x for x in wd if x not in hd]
228
228
  odd = [x for x in added if x not in allowed]
229
229
  if odd:
@@ -1576,6 +1576,11 @@ RETIRED_DENY = frozenset({
1576
1576
  "Write(services/!(analytics)/**)",
1577
1577
  "Edit(/home/fshim/projects/TYHLD-platform/services/!(analytics)/**)",
1578
1578
  "Write(/home/fshim/projects/TYHLD-platform/services/!(analytics)/**)",
1579
+ # ★えふさん決定 2026-11-03(便 5751e7ae): 値の入っていない .npmrc は職人が作れる・記録に入れられる。
1580
+ # この行は中身を見られないので、値なしの .npmrc の Write まで止めていた(便 9ca0acd2)。守りは番人の
1581
+ # 中身の判定(policy.py の npmrc_write_is_ref_only)が持つ=値・未知の行が入る書き込みは今までどおり止まる。
1582
+ # ★実物の値が入った現場には、下の (2a-2) が Edit(/.npmrc) を狙い撃ちで戻す(2枚目の守りを残す)。
1583
+ "Edit(**/.npmrc)",
1579
1584
  })
1580
1585
 
1581
1586
  # ★git の状態(読むだけ)。記録されている settings.json には1バイトも書かない(②-b)。
@@ -1860,11 +1865,13 @@ try:
1860
1865
  del _v
1861
1866
  except OSError:
1862
1867
  pass
1863
- _targeted = "Read(/.npmrc)"
1864
- if _has_literal and _targeted not in cur:
1865
- cur = cur + [_targeted]
1866
- perms["deny"] = cur
1867
- changes.append("この現場の .npmrc に実値が直書きされているため Read(/.npmrc) を追記(秘密を守る)")
1868
+ # ★Edit(/.npmrc) も同じ時だけ戻す(便 5751e7ae)。丸ごとの Edit(**/.npmrc) は退役したので、実値の入った
1869
+ # .npmrc を書き換える・消す形は、番人の中身の判定に加えてこの行でも止める(2枚目の守り)。
1870
+ for _targeted in ("Read(/.npmrc)", "Edit(/.npmrc)"):
1871
+ if _has_literal and _targeted not in cur:
1872
+ cur = cur + [_targeted]
1873
+ perms["deny"] = cur
1874
+ changes.append(f"この現場の .npmrc に実値が直書きされているため {_targeted} を追記(秘密を守る)")
1868
1875
 
1869
1876
  # (2a-3) 書き方が壊れて【何も止めていない】禁止の行を、同じ守りが効く正しい書き方へ直す。
1870
1877
  # 【なぜ要るか(実地 2026-10-07)】現場 kenzokun と utatane-backend の禁止の一覧に、ホームに
@@ -260,6 +260,9 @@ description: 采配くんの便(プロンプト末尾に CONDUCTOR_JOB:<id>
260
260
  - ★**除外指定では通らない**(実測 2026-09-27)。`grep -rn 語 . --exclude=.npmrc` は、`.` の再帰でまず止まり、さらに**秘密のファイル名を引数に書いた事自体**でも止まる。「除いて探す」ではなく「場所を名指しする」が正解。
261
261
  - ★**上の形は最初から選ぶ物。** ただし全体を指す形が**書き方の決まりで止められた**(番人の文が `discipline` で始まり、理由と直し方が書いてある)ときは、冒頭④の(ア)〜(エ)をすべて満たす限り、上の形へ書き直して続けてよい(⑥のとおり報告に3つを書く)。★**フォルダ名を名指しした形でも止められたなら、それは書き方の決まりの種類ではない**(場所を名指しした形は書き方の決まりでは止まらない)ので、探す場所や道具を替えて打ち直さず、止められた命令の全文と番人の文を報告して止まる(冒頭の①〜③と⑤・便 b53481c2 §8 の1番がこの形だった)。
262
262
  - **秘密のファイルを読む・引数に名前を書く**(`cat ~/.npmrc`・`--exclude=.npmrc`)→ 止まる。**中身は見に行かない。** 差分は対象を名指しで `git diff -- src docs`、全体で見たいときは除いて `git diff -- . ':(exclude).npmrc'`(`git diff` は中身を読み出す動詞ではないので、この形は通る・鉄則1)。
263
+ - ★**値の入っていない `.npmrc` は、作る・直す・記録に入れるのが通る**(えふさん決定 2026-11-03・便 5751e7ae)。中身が「取り寄せ先の行(`@tyhld:registry=https://npm.pkg.github.com`)」と「`//<ホスト>/:_authToken=${NPM_TOKEN}`」の形の行だけ(空行・注釈は可)なら、**Write/Edit の道具**で作る・直す、**名指しの `git add .npmrc`・`git commit -m 説明 .npmrc`** で記録に入れる、が通る(番人が中身を見て決める・中身は外に出さない)。
264
+ - 通る例: Write の道具で `<現場>/.npmrc` に上の2行を書く / `git -C <実際のパス> add package.json .npmrc`
265
+ - ★止まる形(今までどおり): `_authToken` の右が `${…}` でなく実物の文字列/未知の行・`_auth`・`_password`・`always-auth`・`username` の行が混じる/元の `.npmrc` に実物の値が在る(上書き・直しで消させない)/`~/.npmrc`・近道・作業場所が変数の `git -C "$DIR"`/**読む**(Read の道具・`cat`)/**Bash で書く**(`cp`・`tee`・`>`=別の作業場所へ写すときも、Write の道具で同じ2行を書く)。★止められたら回避せず止めて報告する(`danger`)。
263
266
  - **標準エラーの捨て先を、あとで文字列の途中に差し込む変数やコマンド置換の中に入れる**(`S="$(何か 2>/dev/null)"` と置き、別の行で `"repos/<その変数>/branches/…"` のように使う/`gh api "repos/$(何か 2>/dev/null)/branches/main"` と直に書く)→ 止まる。番人は字面を展開してから測り直すので、捨て先が `/dev/null` ではなく**その後ろのパスが貼り付いた別の名前**として取り出され、`/dev` 直下への書き込みに見える(実測 2026-09-27。鉄則7の塊がこれで6便すべて止まっていた)。**文句を捨てる所を、小さな関数1か所に寄せる。**
264
267
  - 通る例: 先に `q() { "$@" 2>/dev/null; }` を置き、以後は `S="$(q 何か)"` と書く(★変数の値に捨て先が入らないので、どこに差し込んでも止まらない)。
265
268
  - ★**この形の番人の文は `discipline`(書き方の注意・直し方つき)になった**(便 227aeebb・2026-10-10)。それまでは `danger: redirect into system path (/dev)` と出ており、実態(無害)と合っていなかった。**止まること自体は変わらない。**④の(ア)〜(エ)がそろう限り、上の通る例へ書き直して続けてよい(⑥のとおり報告に3つを書く)。