@routinecrew/routinecode 2.31.57 → 2.31.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/bin/cli.sh +71 -41
  2. package/bin/prompt-vault.js +1 -1
  3. package/bin/rc-credit-turn.js +30 -4
  4. package/bin/rc-grant.js +79 -0
  5. package/bin/rc-login.js +23 -32
  6. package/bin/rc-team.js +592 -0
  7. package/bin/seal-open.js +5 -2
  8. package/hooks/lib/block_message.py +21 -19
  9. package/hooks/lib/i18n.py +17 -10
  10. package/hooks/lib/rt_cleanup.py +61 -0
  11. package/hooks/lib/scrub_stream.py +43 -0
  12. package/hooks/lib/secret_filter.py +443 -1
  13. package/hooks/lib/supplements_sig.py +70 -0
  14. package/hooks/post-knowledge-query.sh +14 -0
  15. package/hooks/post-secret-detect.sh +12 -27
  16. package/hooks/pre-account-guard.sh +6 -2
  17. package/hooks/pre-agent-spawn.mjs +1 -1
  18. package/hooks/pre-bash-guard.sh +11 -0
  19. package/hooks/pre-credit-guard.sh +36 -30
  20. package/hooks/pre-edit-domain-gate.sh +3 -1
  21. package/hooks/pre-edit-knowledge-gate.sh +3 -1
  22. package/hooks/pre-grep-guard.sh +18 -0
  23. package/hooks/pre-read-guard.sh +17 -0
  24. package/hooks/pre-read-knowledge-inject.sh +3 -1
  25. package/hooks/session-start.sh +47 -7
  26. package/hooks/stop-knowledge-remind.sh +45 -10
  27. package/hooks/tests/design09-client.test.py +10 -0
  28. package/hooks/tests/in-project-relax.test.py +2 -1
  29. package/hooks/tests/knowledge-loop.test.sh +89 -0
  30. package/hooks/tests/secret-guard-bypass.test.sh +107 -0
  31. package/hooks/tests/secret-guard.test.sh +2 -1
  32. package/hooks/tests/secret-premask.test.py +179 -0
  33. package/hooks/user-prompt-submit.sh +25 -19
  34. package/mcp-db-manager/dist/analyzers/duplicate-detector.js +1 -1
  35. package/mcp-db-manager/dist/core/model-parser.js +1 -1
  36. package/mcp-db-manager/dist/core/schema-reader.js +1 -1
  37. package/mcp-db-manager/dist/executors/migration-executor.js +1 -1
  38. package/mcp-db-manager/dist/generators/migration-generator.js +1 -1
  39. package/mcp-db-manager/dist/index.js +1 -1
  40. package/mcp-db-manager/dist/validators/schema-validator.js +1 -1
  41. package/mcp-dev-tester/dist/analyzers/auth-diagnoser.js +1 -1
  42. package/mcp-dev-tester/dist/analyzers/backend-analyzer.js +1 -1
  43. package/mcp-dev-tester/dist/analyzers/endpoint-diagnoser.js +1 -1
  44. package/mcp-dev-tester/dist/analyzers/frontend-analyzer.js +1 -1
  45. package/mcp-dev-tester/dist/analyzers/runtime-diagnoser.js +1 -1
  46. package/mcp-dev-tester/dist/analyzers/type-comparator.js +1 -1
  47. package/mcp-dev-tester/dist/analyzers/validation-diagnoser.js +1 -1
  48. package/mcp-dev-tester/dist/attestation.js +1 -1
  49. package/mcp-dev-tester/dist/browser/playwright-manager.js +1 -1
  50. package/mcp-dev-tester/dist/browser/ui-tester.js +1 -1
  51. package/mcp-dev-tester/dist/config/project-config.js +1 -1
  52. package/mcp-dev-tester/dist/index.js +1 -1
  53. package/mcp-dev-tester/dist/testers/api-tester.js +1 -1
  54. package/mcp-doc-fetcher/dist/index.js +1 -1
  55. package/mcp-html-renderer/dist/index.js +1 -1
  56. package/mcp-html-renderer/dist/preview.js +1 -1
  57. package/mcp-html-renderer/dist/template-engine.js +1 -1
  58. package/mcp-intelligence/dist/concept-catalog.js +1 -1
  59. package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
  60. package/mcp-intelligence/dist/config-auth.js +1 -1
  61. package/mcp-intelligence/dist/contracts.generated.js +1 -1
  62. package/mcp-intelligence/dist/domain-templates.js +1 -1
  63. package/mcp-intelligence/dist/grounding.d.ts +1 -0
  64. package/mcp-intelligence/dist/grounding.d.ts.map +1 -1
  65. package/mcp-intelligence/dist/grounding.js +1 -1
  66. package/mcp-intelligence/dist/handlers.js +1 -1
  67. package/mcp-intelligence/dist/index.js +1 -1
  68. package/mcp-intelligence/dist/intelligence-file.js +1 -1
  69. package/mcp-intelligence/dist/knowledge-critic.js +1 -1
  70. package/mcp-intelligence/dist/knowledge-handlers.d.ts +20 -0
  71. package/mcp-intelligence/dist/knowledge-handlers.d.ts.map +1 -1
  72. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  73. package/mcp-intelligence/dist/mention-extractor.js +1 -1
  74. package/mcp-intelligence/dist/provenance.js +1 -1
  75. package/mcp-intelligence/dist/semantic-embedder.js +1 -1
  76. package/mcp-log-watcher/dist/config-auth.js +1 -1
  77. package/mcp-log-watcher/dist/file-watcher.js +1 -1
  78. package/mcp-log-watcher/dist/index.js +1 -1
  79. package/mcp-log-watcher/dist/known-solutions.js +1 -1
  80. package/mcp-log-watcher/dist/log-store.js +1 -1
  81. package/mcp-log-watcher/dist/websocket-server.js +1 -1
  82. package/mcp-plan-manager/dist/__tests__/plan-parser.test.js +1 -1
  83. package/mcp-plan-manager/dist/file-ops.js +1 -1
  84. package/mcp-plan-manager/dist/index.js +1 -1
  85. package/mcp-plan-manager/dist/plan-parser.js +1 -1
  86. package/mcp-project-context/dist/git-ops.js +1 -1
  87. package/mcp-project-context/dist/index.js +1 -1
  88. package/mcp-project-context/dist/project-analysis.js +1 -1
  89. package/mcp-routinecode/dist/agent-tracker.js +1 -1
  90. package/mcp-routinecode/dist/attestation.js +1 -1
  91. package/mcp-routinecode/dist/blast-radius.js +1 -1
  92. package/mcp-routinecode/dist/changeset.js +1 -1
  93. package/mcp-routinecode/dist/config-auth.js +1 -1
  94. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  95. package/mcp-routinecode/dist/coverage.js +1 -1
  96. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  97. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  98. package/mcp-routinecode/dist/file-lock-registry.js +1 -1
  99. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  100. package/mcp-routinecode/dist/index.js +1 -1
  101. package/mcp-routinecode/dist/known-solutions.js +1 -1
  102. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  103. package/mcp-routinecode/dist/observed-draft.js +1 -1
  104. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  105. package/mcp-routinecode/dist/route-match.js +1 -1
  106. package/mcp-routinecode/dist/routines.js +1 -1
  107. package/mcp-routinecode/dist/rule-engine.js +1 -1
  108. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  109. package/mcp-routinecode/dist/telemetry-analyzer.js +1 -1
  110. package/mcp-routinecode/dist/test-runner.js +1 -1
  111. package/mcp-routinecode/dist/verification.js +0 -0
  112. package/mcp-routinecode/dist/viral-loop.d.ts +68 -0
  113. package/mcp-routinecode/dist/viral-loop.js +1 -1
  114. package/package.json +1 -1
  115. package/plugin/agents/analyzer.md.sealed +1 -0
  116. package/plugin/agents/crawler.md.sealed +1 -0
  117. package/plugin/agents/explorer.md.sealed +1 -0
  118. package/plugin/agents/implementor.md.sealed +1 -0
  119. package/plugin/agents/looker.md.sealed +1 -0
  120. package/plugin/agents/planner.md.sealed +1 -0
  121. package/plugin/agents/recorder.md.sealed +1 -0
  122. package/plugin/agents/reviewer.md.sealed +1 -0
  123. package/plugin/agents/verifier.md.sealed +1 -0
  124. package/plugin/commands/analyze.md.sealed +1 -0
  125. package/plugin/commands/plan.md.sealed +1 -0
  126. package/plugin/commands/rc.md.sealed +1 -0
  127. package/plugin/commands/receipt.md.sealed +1 -0
  128. package/plugin/commands/recharge.md.sealed +1 -0
  129. package/plugin/commands/routines.md.sealed +1 -0
  130. package/plugin/commands/share.md.sealed +1 -0
  131. package/plugin/routinecode-prompt.md.sealed +1 -0
  132. package/bin/setup.js +0 -3
@@ -65,53 +65,62 @@ fi
65
65
  # W3: save_evidence/score_verification/auto_score 추가 — 게이트 필수 검증은 무과금
66
66
  # attestation 전환: 점수 증거는 build_check/run_tests/test_endpoint/test_ui_flow 실행만 인정 → 동일 원칙으로 무과금
67
67
  # (engine action-cost-map.ts TOOL_FREE_LIST와 동기 유지 필수)
68
- FREE_TOOLS="credit_check|share_generate_candidates|share_issue|share_verify_status|share_confirm_post|block_screen_render|check_escalation|get_verification_state|classify_task|lock_files|release_files|check_conflicts|save_evidence|score_verification|auto_score|build_check|run_tests|test_endpoint|test_ui_flow"
68
+ FREE_TOOLS="credit_check|share_generate_candidates|share_issue|share_verify_status|share_confirm_post|recharge_status|recharge_submit_insight|recharge_invite_link|block_screen_render|check_escalation|get_verification_state|classify_task|lock_files|release_files|check_conflicts|save_evidence|score_verification|auto_score|build_check|run_tests|test_endpoint|test_ui_flow"
69
69
  BASE_TOOL=$(echo "$TOOL_NAME" | sed -E 's/^mcp__[a-zA-Z0-9_]+__//')
70
70
  if echo "$BASE_TOOL" | grep -qE "^($FREE_TOOLS)$"; then
71
71
  exit 0
72
72
  fi
73
73
 
74
- if [ "${ROUTINECODE_CREDIT_BYPASS:-}" = "true" ]; then
74
+ _RC_PKG="$(cd "$(dirname "$0")/.." 2>/dev/null && pwd)"
75
+ _rc_dev_bypass() { # 우회 변수는 개발용 소스 체크아웃에서만 유효(설치본 고객은 무시) — 2026-10-16 결정
76
+ [ "${ROUTINECODE_CREDIT_BYPASS:-}" = "true" ] && [ -d "$_RC_PKG/engine/src" ] && { [ -d "$_RC_PKG/.sources" ] || [ -d "$_RC_PKG/mcp-intelligence/src" ]; }
77
+ }
78
+ if _rc_dev_bypass; then
75
79
  exit 0
76
80
  fi
77
81
 
78
82
  # 서버 권위 per-turn 판정 우선 — 러너(rc-credit-turn)가 매 턴 서버 consume 결과를
79
- # credit-decision.json 에 기록한다. remote-flags(세션시작 1회 캐시)와 무관하게 '이미 열려
80
- # 있는 세션'에서도 50 소진 즉시 차단이 반영된다(실효성). 서버 gate=off면 러너가 blocked=false
81
- # 를 쓰므로 이 경로는 자동 비활성(서버 권위) — 클라 플래그 미동기화와 무관. Pro/구독은 면제.
82
- _RC_DEC=$(python3 -c "
83
- import json, os
83
+ # credit-decision.json 에 (HMAC 서명과 함께) 기록한다. remote-flags(세션시작 1회 캐시)와 무관하게
84
+ # '이미 열려 있는 세션'에서도 50 소진 즉시 차단이 반영된다(실효성).
85
+ # 판정 순서(2026-10-16): 서버가 이번 턴에 내린 결정이 로컬 구독/잔액 파일보다 우선한다.
86
+ # - 1시간 이내 '차단' 결정 → 차단(서명 무관 — 안전 방향).
87
+ # - 서명 유효 + 1시간 이내 '허용' 결정 → 허용(Pro 면제는 서버가 subscription_bypass_until 로 판정).
88
+ # - 그 외(무서명·위조 허용, 오래됨, 없음) → 아래 폴백(세션시작 동기화 기반).
89
+ # 과거엔 config.json 의 plan=pro 한 줄·무서명 subscription.json 이 서버 차단을 덮었다
90
+ # (config.plan 은 어떤 코드도 쓰지 않는 죽은 플래그였다) → 제거.
91
+ _RC_DEC=$(RC_KDIR="${ROUTINECODE_KNOWLEDGE_DIR:-$HOME/.routinecode/knowledge}" python3 -c "
92
+ import json, os, hmac, hashlib
84
93
  from datetime import datetime, timezone
85
94
  try:
86
- c = json.load(open(os.path.expanduser('~/.routinecode/config.json')))
87
- if c.get('plan') == 'pro':
88
- print('OK'); raise SystemExit
89
- try:
90
- sub = json.load(open(os.path.expanduser('~/.routinecode/subscription.json')))
91
- if sub.get('status') in ('active', 'trialing') and sub.get('planCode') in ('pro', 'team', 'enterprise'):
92
- print('OK'); raise SystemExit
93
- except SystemExit:
94
- raise
95
- except Exception:
96
- pass
97
95
  d = json.load(open(os.path.expanduser('~/.routinecode/credit-decision.json')))
98
- if not d.get('blocked'):
99
- print('OK'); raise SystemExit
100
- at = d.get('at'); fresh = True
96
+ at = d.get('at'); fresh = False
101
97
  if at:
102
98
  try:
103
99
  fresh = (datetime.now(timezone.utc) - datetime.fromisoformat(str(at).replace('Z', '+00:00'))).total_seconds() < 3600
104
100
  except Exception:
105
101
  fresh = False
106
- print('BLOCK' if fresh else 'OK')
107
- except SystemExit:
108
- raise
102
+ signed = False
103
+ try:
104
+ key = open(os.path.join(os.environ['RC_KDIR'], 'attest', '.key'), 'rb').read()
105
+ payload = 'credit-decision|%d|%s' % (1 if d.get('blocked') else 0, at)
106
+ exp = hmac.new(key, payload.encode('utf-8'), hashlib.sha256).hexdigest()
107
+ signed = isinstance(d.get('mac'), str) and hmac.compare_digest(d['mac'], exp)
108
+ except Exception:
109
+ signed = False
110
+ if fresh and d.get('blocked'):
111
+ print('BLOCK')
112
+ elif fresh and signed:
113
+ print('OK')
114
+ else:
115
+ print('FALLBACK')
109
116
  except Exception:
110
- print('OK')
117
+ print('FALLBACK')
111
118
  " 2>/dev/null)
112
119
 
113
120
  if [ "$_RC_DEC" = "BLOCK" ]; then
114
121
  GATE_RESULT="BLOCK"
122
+ elif [ "$_RC_DEC" = "OK" ]; then
123
+ GATE_RESULT="OK"
115
124
  else
116
125
 
117
126
  # userId + plan + remoteFlag + balance 통합 확인 (python3 1회) — 폴백(세션시작 동기화 기반)
@@ -122,9 +131,6 @@ try:
122
131
  if not c.get('userId'):
123
132
  print('SKIP')
124
133
  raise SystemExit
125
- if c.get('plan') == 'pro':
126
- print('SKIP')
127
- raise SystemExit
128
134
  # 유료 구독(subscription.json) 단일 소스 — 개인 Pro / 기업 Team·Enterprise (isProSubscriber 동일 의미)
129
135
  try:
130
136
  sub = json.load(open(os.path.expanduser('~/.routinecode/subscription.json')))
@@ -222,12 +228,12 @@ except Exception:
222
228
  from i18n import t
223
229
  msg = t('credit.block_fallback')
224
230
  except Exception:
225
- msg = '[CREDIT-GUARD] Credit exhausted. Run /share to recharge.'
231
+ msg = '[CREDIT-GUARD] Credit exhausted. Run /recharge to refill.'
226
232
  # PreToolUse: hookSpecificOutput.permissionDecision=deny DISPLAYS the reason to
227
233
  # the user (legacy {'decision':'block'} only feeds it to the model).
228
234
  print(json.dumps({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'deny', 'permissionDecisionReason': msg}}))
229
235
  " 2>/dev/null)
230
- [ -z "$BLOCK_JSON" ] && BLOCK_JSON='{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"[CREDIT-GUARD] Credit exhausted. Write one line at https://routinecode.routinecrew.net/recharge for instant +50, or run /share."}}'
236
+ [ -z "$BLOCK_JSON" ] && BLOCK_JSON='{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"[CREDIT-GUARD] Credit exhausted. Type /recharge for the easiest way to refill (+50), or visit https://routinecode.routinecrew.net/recharge"}}'
231
237
  echo "$BLOCK_JSON"
232
238
 
233
239
  exit 0
@@ -33,11 +33,13 @@ def allow():
33
33
  print('{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}')
34
34
  sys.exit(0)
35
35
 
36
+ # systemMessage 는 사용자 화면 표시용이라 모델이 못 본다 → 지식이 에이전트에 닿지 않았다.
37
+ # 모델 컨텍스트 채널(hookSpecificOutput.additionalContext)에도 같은 내용을 싣는다.
36
38
  def allow_with_message(msg):
37
39
  out = {
38
40
  "hookSpecificOutput": {
39
41
  "hookEventName": "PreToolUse",
40
- "permissionDecision": "allow"
42
+ "permissionDecision": "allow", "additionalContext": msg
41
43
  },
42
44
  "systemMessage": msg
43
45
  }
@@ -21,11 +21,13 @@ def allow():
21
21
  print('{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}')
22
22
  sys.exit(0)
23
23
 
24
+ # systemMessage 는 사용자 화면 표시용이라 모델이 못 본다 → 지식이 에이전트에 닿지 않았다.
25
+ # 모델 컨텍스트 채널(hookSpecificOutput.additionalContext)에도 같은 내용을 싣는다.
24
26
  def allow_with_message(msg):
25
27
  out = {
26
28
  "hookSpecificOutput": {
27
29
  "hookEventName": "PreToolUse",
28
- "permissionDecision": "allow"
30
+ "permissionDecision": "allow", "additionalContext": msg
29
31
  },
30
32
  "systemMessage": msg
31
33
  }
@@ -72,6 +72,8 @@ policy = sf.load_policy()
72
72
  # CORE-first: kill-switch(is_disabled)로 우회 불가한 자기 소스보호(dev 완화 유지).
73
73
  for cand in candidates:
74
74
  core_banned, core_rule = sf.core_only_check_path(cand, policy)
75
+ if not core_banned and sf.core_dir_scope(cand):
76
+ core_banned, core_rule = True, '**/routinecode/' # 설치물 디렉터리 통째 검색
75
77
  if core_banned:
76
78
  display_rule = 'internal' if sf.is_internal_rule(core_rule) else core_rule
77
79
  reason = t('secret.read_block', path=cand, rule=display_rule)
@@ -88,5 +90,21 @@ for cand in candidates:
88
90
  reason = t('secret.read_block', path=cand, rule=display_rule)
89
91
  emit({'decision': 'block', 'reason': reason})
90
92
 
93
+ # 비밀 파일 하나를 직접 grep → 값이 마스킹된 사본을 대신 검색(키 이름 검색은 그대로 동작).
94
+ _gp = tool_input.get('path', '') if isinstance(tool_input, dict) else ''
95
+ if isinstance(_gp, str) and _gp and os.path.isfile(os.path.expanduser(_gp)) and sf.is_secret_file(_gp, policy):
96
+ _masked = sf.masked_copy_path(_gp)
97
+ if _masked:
98
+ _nti = dict(tool_input)
99
+ _nti['path'] = _masked
100
+ emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow', 'updatedInput': _nti}})
101
+ # 보호 파일이 아니어도 보호 값을 담은 파일 하나(Bash 로 만든 사본 등)를 grep → 값만 가린 사본을 검색.
102
+ if isinstance(_gp, str) and _gp and os.path.isfile(os.path.expanduser(_gp)):
103
+ _vm = sf.value_masked_copy_path(_gp, policy)
104
+ if _vm:
105
+ _nti = dict(tool_input)
106
+ _nti['path'] = _vm
107
+ emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow', 'updatedInput': _nti}})
108
+
91
109
  emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow'}})
92
110
  PYEOF
@@ -79,5 +79,22 @@ if banned:
79
79
  reason = t('secret.read_block', path=file_path, rule=display_rule)
80
80
  emit({'decision': 'block', 'reason': reason})
81
81
 
82
+ # 비밀 파일(.env·키·자격증명) Read → 값이 마스킹된 사본을 대신 읽힌다(키 이름·구조는 그대로).
83
+ # PostToolUse 스크럽은 이미 전달된 출력을 못 바꾸므로 값은 읽기 '전'에 가린다.
84
+ if tool_name == 'Read' and isinstance(tool_input, dict) and sf.is_secret_file(file_path, policy):
85
+ _masked = sf.masked_copy_path(file_path)
86
+ if _masked:
87
+ _nti = dict(tool_input)
88
+ _nti['file_path'] = _masked
89
+ emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow', 'updatedInput': _nti}})
90
+
91
+ # 보호 파일이 아니어도 보호 값을 담은 파일(Bash 로 만든 사본·덤프 등) → 그 값만 가린 사본을 읽힌다.
92
+ if tool_name == 'Read' and isinstance(tool_input, dict):
93
+ _vm = sf.value_masked_copy_path(file_path, policy)
94
+ if _vm:
95
+ _nti = dict(tool_input)
96
+ _nti['file_path'] = _vm
97
+ emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow', 'updatedInput': _nti}})
98
+
82
99
  emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow'}})
83
100
  PYEOF
@@ -20,9 +20,11 @@ def allow():
20
20
  print('{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}')
21
21
  sys.exit(0)
22
22
 
23
+ # systemMessage 는 사용자 화면 표시용이라 모델이 못 본다 → 지식이 에이전트에 닿지 않았다.
24
+ # 모델 컨텍스트 채널(hookSpecificOutput.additionalContext)에도 같은 내용을 싣는다.
23
25
  def allow_with_message(msg):
24
26
  print(json.dumps({
25
- "hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "allow"},
27
+ "hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "allow", "additionalContext": msg},
26
28
  "systemMessage": msg,
27
29
  }, ensure_ascii=False))
28
30
  sys.exit(0)
@@ -30,9 +30,9 @@ if not active:
30
30
  # SECURITY(R10): 예측/공유 /tmp 대신 per-user 0700 런타임 디렉터리(훅 간 좌표 유지, symlink race 차단)
31
31
  RC_RUNDIR="${XDG_RUNTIME_DIR:-$HOME/.routinecode/run}"
32
32
  if ! mkdir -p "$RC_RUNDIR" 2>/dev/null; then RC_RUNDIR="/tmp"; else chmod 700 "$RC_RUNDIR" 2>/dev/null; fi
33
- # --- Sealed Core: stale temp 복호본(.rt) 정리 (>60분). exec 로 대체된 세션의 잔존분 회수, 활성분 보존. ---
33
+ # --- Sealed Core: 종료된 세션의 임시 복호본(.rt) 정리 — 실행 중인 세션 것은 시간이 지나도 보존(PID 기준). ---
34
34
  if [ -d "$HOME/.routinecode/.rt" ]; then
35
- find "$HOME/.routinecode/.rt" -mindepth 1 -maxdepth 1 -type d -mmin +60 -exec rm -rf {} + 2>/dev/null || true
35
+ python3 "$(dirname "$0")/lib/rt_cleanup.py" 2>/dev/null || true
36
36
  fi
37
37
  # SessionStart hook
38
38
  # 1. 에스컬레이션 상태 복원
@@ -592,14 +592,43 @@ try:
592
592
 
593
593
  url = f'{server_url}/api/v1/provision'
594
594
 
595
- def _provision(tok):
596
- req = urllib.request.Request(url, data=json.dumps({}).encode(), method='POST', headers={
595
+ # 팀 귀속(docs/30 §3.5): 이전 config 의 teamTenantId 로 재발급해야 자가치유가 팀 사용자를
596
+ # 개인으로 되돌리지 않는다. 개인 사용자(teamTenantId 없음)는 기존과 동일하게 빈 본문.
597
+ team_tid = None
598
+ team_name = None
599
+ try:
600
+ _pc = json.load(open(config_path))
601
+ _t = _pc.get('teamTenantId')
602
+ if isinstance(_t, int) and _t > 0:
603
+ team_tid, team_name = _t, _pc.get('teamName')
604
+ except Exception:
605
+ pass
606
+
607
+ def _provision_once(tok, tid):
608
+ req = urllib.request.Request(url, data=json.dumps({'tenantId': tid} if tid else {}).encode(), method='POST', headers={
597
609
  'Authorization': f'Bearer {tok}',
598
610
  'Content-Type': 'application/json',
599
611
  })
600
612
  resp = urllib.request.urlopen(req, timeout=5)
601
613
  return json.loads(resp.read().decode())
602
614
 
615
+ def _provision(tok):
616
+ global team_tid
617
+ if not team_tid:
618
+ return _provision_once(tok, None)
619
+ try:
620
+ return _provision_once(tok, team_tid)
621
+ except urllib.error.HTTPError as te:
622
+ # 팀에서 빠진 경우(403 TEAM_TENANT_FORBIDDEN)만 개인으로 재발급. 토큰 만료 403 은 그대로 위로.
623
+ try:
624
+ code = json.loads(te.read().decode() or '{}').get('code')
625
+ except Exception:
626
+ code = None
627
+ if te.code == 403 and code == 'TEAM_TENANT_FORBIDDEN':
628
+ team_tid = None
629
+ return _provision_once(tok, None)
630
+ raise
631
+
603
632
  def _save_creds():
604
633
  import tempfile as _tf
605
634
  cd = os.path.dirname(creds_path)
@@ -717,6 +746,11 @@ try:
717
746
  # 기존에 사용자가 지정한 authUrl 은 보존(있으면).
718
747
  if prior.get('authUrl'):
719
748
  config['authUrl'] = prior['authUrl']
749
+ # 팀 귀속 보존: 팀으로 재발급이 실제 적용됐을 때만(teamApplied!=False) 팀 필드를 유지.
750
+ if team_tid and result.get('teamApplied') is not False:
751
+ config['teamTenantId'] = result.get('issuedTenantId') or team_tid
752
+ if team_name:
753
+ config['teamName'] = team_name
720
754
  # 무효화 잔재는 새 config 에 절대 싣지 않는다(명시).
721
755
  config.pop('apiKeyInvalidReason', None)
722
756
  config.pop('apiKeyInvalidatedAt', None)
@@ -1238,15 +1272,20 @@ try:
1238
1272
  supplements = result.get('supplements', [])
1239
1273
  content_hash = result.get('hash', '')
1240
1274
 
1241
- # check if content changed
1242
- if os.path.isfile(hash_path):
1275
+ _lib_s = os.environ.get('ROUTINECODE_LIB_DIR', '')
1276
+ if _lib_s and _lib_s not in sys.path:
1277
+ sys.path.insert(0, _lib_s)
1278
+ import supplements_sig as _ssig
1279
+
1280
+ # check if content changed — 로컬 파일 서명이 깨졌으면(외부 수정) 서버본으로 다시 쓴다
1281
+ if os.path.isfile(hash_path) and (not os.path.isfile(supplements_path) or _ssig.verify(supplements_path)):
1243
1282
  existing_hash = open(hash_path).read().strip()
1244
1283
  if existing_hash == content_hash:
1245
1284
  sys.exit(0)
1246
1285
 
1247
1286
  if not supplements:
1248
1287
  # no rules -> remove file
1249
- for p in [supplements_path, hash_path]:
1288
+ for p in [supplements_path, hash_path, supplements_path + '.sig']:
1250
1289
  if os.path.isfile(p):
1251
1290
  os.remove(p)
1252
1291
  sys.exit(0)
@@ -1281,6 +1320,7 @@ try:
1281
1320
  with os.fdopen(fd, 'w') as f:
1282
1321
  f.write('\n'.join(lines) + '\n')
1283
1322
  os.replace(tmp, supplements_path)
1323
+ _ssig.sign(supplements_path) # cli.sh 는 서명이 맞을 때만 시스템 프롬프트에 덧붙인다
1284
1324
 
1285
1325
  # atomic write hash
1286
1326
  fd2, tmp2 = tempfile.mkstemp(dir=d, suffix='.tmp')
@@ -97,6 +97,48 @@ for e in entries:
97
97
  if len(record_tools_called) >= len(RECORD_TOOL_NAMES):
98
98
  emit({"continue": True})
99
99
 
100
+ # ─── transcript 형식 어댑터 ───────────────────────────────────────
101
+ # Claude Code transcript 에는 최상위 type='tool_result'/'human' 이나 role 키가 없다.
102
+ # 도구 결과 = type:'user' 엔트리의 message.content[] 중 type:'tool_result' 블록,
103
+ # 사용자 발화 = type:'user' 엔트리의 문자열 content 또는 text 블록.
104
+ # 과거 파서는 레거시 키만 찾아 error_fix/domain_knowledge 신호가 구조적으로 0 이었다.
105
+ def _block_text(c):
106
+ if isinstance(c, list):
107
+ return ' '.join(str(b.get('text', '')) for b in c if isinstance(b, dict))
108
+ return str(c or '')
109
+
110
+ def iter_tool_result_texts(e):
111
+ t = e.get('type')
112
+ if t in ('tool_result', 'tool_response'): # 레거시 형식 호환
113
+ yield _block_text(e.get('content', '') or e.get('message', {}).get('content', ''))
114
+ return
115
+ if t != 'user':
116
+ return
117
+ content = (e.get('message') or {}).get('content')
118
+ if isinstance(content, list):
119
+ for b in content:
120
+ if isinstance(b, dict) and b.get('type') == 'tool_result':
121
+ yield _block_text(b.get('content', ''))
122
+
123
+ _SYS_BLOCK = re.compile(r'<(system-reminder|pasted_content[^>]*|command-[a-z-]+|local-command-[a-z-]+)>.*?</[^>]+>', re.DOTALL)
124
+
125
+ def human_text(e):
126
+ """사용자가 직접 입력한 텍스트만(도구 결과·메타·시스템 주입 제외). 없으면 None."""
127
+ if e.get('isMeta'):
128
+ return None
129
+ if e.get('type') == 'human' or e.get('role') == 'user': # 레거시 형식 호환
130
+ return _SYS_BLOCK.sub('', _block_text(e.get('content', '') or e.get('message', {}).get('content', '')))
131
+ if e.get('type') != 'user':
132
+ return None
133
+ content = (e.get('message') or {}).get('content')
134
+ if isinstance(content, str):
135
+ return _SYS_BLOCK.sub('', content)
136
+ if isinstance(content, list):
137
+ if any(isinstance(b, dict) and b.get('type') == 'tool_result' for b in content):
138
+ return None
139
+ return _SYS_BLOCK.sub('', _block_text(content))
140
+ return None
141
+
100
142
  # ─── 3. 에러 수정 시그널 감지 ────────────────────────────────────
101
143
  # 시그널 A: build failure → success 전환
102
144
  # 시그널 B: 에러 메시지가 있는 Bash 실행 후 수정 → 성공
@@ -121,12 +163,8 @@ ERROR_PATTERNS = re.compile(
121
163
  last_error_idx = -1
122
164
 
123
165
  for i, e in enumerate(entries):
124
- if e.get('type') == 'tool_result' or e.get('type') == 'tool_response':
166
+ for content_str in iter_tool_result_texts(e):
125
167
  # build_check 결과 파싱
126
- content = e.get('content', '') or e.get('message', {}).get('content', '')
127
- if isinstance(content, list):
128
- content = ' '.join(str(b.get('text', '')) for b in content if isinstance(b, dict))
129
- content_str = str(content)
130
168
 
131
169
  if 'build_check' in content_str or 'build' in content_str:
132
170
  if '"success":false' in content_str or '"success": false' in content_str:
@@ -222,11 +260,8 @@ DOMAIN_PATTERNS = re.compile(
222
260
  has_domain_signal = False
223
261
  domain_snippet = None
224
262
  for e in entries:
225
- if e.get('role') == 'user' or e.get('type') == 'human':
226
- msg_content = e.get('content', '') or e.get('message', {}).get('content', '')
227
- if isinstance(msg_content, list):
228
- msg_content = ' '.join(str(b.get('text', '')) for b in msg_content if isinstance(b, dict))
229
- msg_str = str(msg_content)
263
+ msg_str = human_text(e)
264
+ if msg_str:
230
265
  if DOMAIN_PATTERNS.search(msg_str) and 'record_domain_knowledge' not in ' '.join(str(r) for r in record_tools_called):
231
266
  has_domain_signal = True
232
267
  match = DOMAIN_PATTERNS.search(msg_str)
@@ -81,9 +81,19 @@ def fresh_home(config=None, credit_state=None, flags=None):
81
81
  return home
82
82
 
83
83
 
84
+ # 차단(BLOCK) 케이스는 hook 이 재충전 페이지를 브라우저로 연다(하루 1회 표시 파일은 가짜 HOME 마다 새로 없음).
85
+ # 테스트가 실제 Mac 브라우저를 띄우지 않도록 open/xdg-open 을 무동작 스텁으로 가린다.
86
+ _NO_BROWSER = tempfile.mkdtemp(prefix="rc-nobrowser-")
87
+ for _b in ("open", "xdg-open"):
88
+ with open(os.path.join(_NO_BROWSER, _b), "w") as _f:
89
+ _f.write("#!/bin/sh\nexit 0\n")
90
+ os.chmod(os.path.join(_NO_BROWSER, _b), 0o755)
91
+
92
+
84
93
  def base_env(home, server_url=None, extra=None):
85
94
  env = dict(os.environ)
86
95
  env["HOME"] = home
96
+ env["PATH"] = _NO_BROWSER + ":" + env.get("PATH", "")
87
97
  env["ROUTINECODE_SERVER_URL"] = server_url or f"http://127.0.0.1:{PORT}"
88
98
  for k in ("ROUTINECODE_TELEMETRY", "ROUTINECODE_CREDIT_BYPASS", "ROUTINECODE_CREDIT_GATE"):
89
99
  env.pop(k, None)
@@ -77,7 +77,8 @@ try:
77
77
  reason = json.loads(r.stdout).get("reason", "")
78
78
  except Exception:
79
79
  reason = ""
80
- check("Read nested-response masked end-to-end (collect_text)", PW not in reason and "PROTECTED_FILE_VALUE" in reason)
80
+ # 2026-10-16: reason 은 본문을 되풀이하지 않는다 — 값 미노출 + 감지 건수로 검증
81
+ check("Read nested-response detected end-to-end (collect_text)", PW not in reason and "protected_file_value=" in reason)
81
82
 
82
83
  # 5. in-repo config 참조 배포 명령 통과
83
84
  cmd = 'sshpass -p "$(cat %s)" ssh rms@1.2.3.4' % fpath
@@ -0,0 +1,89 @@
1
+ #!/bin/bash
2
+ # Regression test — 지식 수집/소비 훅이 실제 Claude Code 데이터 형식을 파싱하는가.
3
+ # 1) stop-knowledge-remind: type:'user' + tool_result 블록 / 문자열 content → error_fix·domain_knowledge 신호
4
+ # 2) post-knowledge-query: MCP 결과 content 블록 리스트 → community-usage.json 기록
5
+ # 3) pre-read/pre-edit 주입: additionalContext 채널 사용 (정적 검사)
6
+
7
+ set -u
8
+
9
+ HOOKS="$(cd "$(dirname "$0")/.." && pwd)"
10
+ WORK=$(mktemp -d)
11
+ trap 'rm -rf "$WORK"' EXIT
12
+
13
+ pass_count=0
14
+ fail_count=0
15
+ check() {
16
+ local name="$1" cond="$2"
17
+ if eval "$cond"; then
18
+ echo " ✓ $name"; pass_count=$((pass_count + 1))
19
+ else
20
+ echo " ✗ $name"; fail_count=$((fail_count + 1))
21
+ fi
22
+ }
23
+
24
+ fresh_home() {
25
+ local h; h=$(mktemp -d "$WORK/home.XXXX")
26
+ mkdir -p "$h/.routinecode/knowledge"
27
+ echo "$h"
28
+ }
29
+
30
+ # ── 1. stop-knowledge-remind ─────────────────────────────────────
31
+ T="$WORK/t1.jsonl"
32
+ cat > "$T" <<'EOF'
33
+ {"type":"user","message":{"role":"user","content":"이 API는 분당 30건 제한이야, 기억해"}}
34
+ {"type":"assistant","message":{"content":[{"type":"tool_use","id":"a","name":"Bash","input":{"command":"npm run build"}}]}}
35
+ {"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"a","content":"src/x.ts(3,1): error TS2304: Cannot find name 'foo'"}]}}
36
+ {"type":"assistant","message":{"content":[{"type":"tool_use","id":"b","name":"Edit","input":{"file_path":"/p/src/x.ts"}}]}}
37
+ {"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"b","content":[{"type":"text","text":"ok"}]}]}}
38
+ EOF
39
+ H=$(fresh_home)
40
+ echo "{\"session_id\":\"s1\",\"transcript_path\":\"$T\"}" | HOME="$H" ROUTINECODE_KNOWLEDGE_DIR="$H/.routinecode/knowledge" bash "$HOOKS/stop-knowledge-remind.sh" >/dev/null
41
+ Q="$H/.routinecode/knowledge/recorder-queue.jsonl"
42
+ check "stop: 실제 형식 transcript → error_fix 신호" "grep -q '\"error_fix\"' '$Q' 2>/dev/null"
43
+ check "stop: 사용자 발화 → domain_knowledge 신호" "grep -q '\"domain_knowledge\"' '$Q' 2>/dev/null"
44
+ check "stop: errorSignature 캡처" "grep -q 'TS2304' '$Q' 2>/dev/null"
45
+
46
+ # system-reminder 안의 키워드는 사용자 발화로 보지 않는다
47
+ T2="$WORK/t2.jsonl"
48
+ cat > "$T2" <<'EOF'
49
+ {"type":"user","message":{"role":"user","content":"<system-reminder>remember: daily limit constraint</system-reminder>안녕"}}
50
+ {"type":"assistant","message":{"content":[{"type":"text","text":"hi"}]}}
51
+ EOF
52
+ H=$(fresh_home)
53
+ echo "{\"session_id\":\"s2\",\"transcript_path\":\"$T2\"}" | HOME="$H" ROUTINECODE_KNOWLEDGE_DIR="$H/.routinecode/knowledge" bash "$HOOKS/stop-knowledge-remind.sh" >/dev/null
54
+ check "stop: system-reminder 키워드는 domain 신호 아님" "! grep -q 'domain_knowledge' '$H/.routinecode/knowledge/recorder-queue.jsonl' 2>/dev/null"
55
+
56
+ # 도구 결과(tool_result) 안의 키워드도 사용자 발화가 아님
57
+ T3="$WORK/t3.jsonl"
58
+ cat > "$T3" <<'EOF'
59
+ {"type":"assistant","message":{"content":[{"type":"tool_use","id":"a","name":"Read","input":{"file_path":"/x"}}]}}
60
+ {"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"a","content":"rate limit: remember to throttle"}]}}
61
+ EOF
62
+ H=$(fresh_home)
63
+ echo "{\"session_id\":\"s3\",\"transcript_path\":\"$T3\"}" | HOME="$H" ROUTINECODE_KNOWLEDGE_DIR="$H/.routinecode/knowledge" bash "$HOOKS/stop-knowledge-remind.sh" >/dev/null
64
+ check "stop: tool_result 텍스트는 domain 신호 아님" "! grep -q 'domain_knowledge' '$H/.routinecode/knowledge/recorder-queue.jsonl' 2>/dev/null"
65
+
66
+ # ── 2. post-knowledge-query ──────────────────────────────────────
67
+ H=$(fresh_home)
68
+ P='{"session_id":"s1","tool_name":"mcp__mcp-intelligence__get_similar_errors","tool_input":{"errorMessage":"ECONNREFUSED"},"tool_response":[{"type":"text","text":"{\"local\":[],\"community\":[{\"id\":42,\"errorSignature\":\"ECONNREFUSED 127.0.0.1\"}],\"total\":1}"}]}'
69
+ echo "$P" | HOME="$H" bash "$HOOKS/post-knowledge-query.sh" >/dev/null
70
+ check "query: content 블록 리스트 → community-usage 기록" "grep -q '\"id\": 42' '$H/.routinecode/knowledge/community-usage.json' 2>/dev/null"
71
+
72
+ H=$(fresh_home)
73
+ P='{"session_id":"s1","tool_name":"mcp__mcp-intelligence__get_similar_errors","tool_input":{},"tool_response":{"content":[{"type":"text","text":"{\"community\":[{\"id\":7,\"errorSignature\":\"E\"}]}"}]}}'
74
+ echo "$P" | HOME="$H" bash "$HOOKS/post-knowledge-query.sh" >/dev/null
75
+ check "query: {content:[...]} 래핑 형식" "grep -q '\"id\": 7' '$H/.routinecode/knowledge/community-usage.json' 2>/dev/null"
76
+
77
+ H=$(fresh_home)
78
+ P='{"session_id":"s1","tool_name":"mcp__mcp-intelligence__get_similar_errors","tool_input":{},"tool_response":"{\"community\":[{\"id\":9,\"errorSignature\":\"E\"}]}"}'
79
+ echo "$P" | HOME="$H" bash "$HOOKS/post-knowledge-query.sh" >/dev/null
80
+ check "query: 문자열 형식(하위호환)" "grep -q '\"id\": 9' '$H/.routinecode/knowledge/community-usage.json' 2>/dev/null"
81
+
82
+ # ── 3. 주입 채널 ─────────────────────────────────────────────────
83
+ for f in pre-read-knowledge-inject.sh pre-edit-domain-gate.sh pre-edit-knowledge-gate.sh; do
84
+ check "inject: $f 가 additionalContext 사용" "grep -q '\"additionalContext\": msg' '$HOOKS/$f'"
85
+ done
86
+
87
+ echo
88
+ echo "$pass_count passed, $fail_count failed"
89
+ [ "$fail_count" -eq 0 ]
@@ -0,0 +1,107 @@
1
+ #!/bin/bash
2
+ # secret-guard 우회 접근 방어 테스트 (2026-10-16)
3
+ #
4
+ # 보호 파일 값이 "경로를 숨긴 접근"으로도 모델 출력에 실리지 않는지 검증한다.
5
+ # - Bash: 따옴표 조각 경로 · 변수 경로 · 글롭 · 디렉토리 · 인라인 인터프리터 · base64 인코딩
6
+ # - Read/Grep: Bash 로 만든 사본 파일
7
+ # - 회귀: 무관한 명령은 감싸지 않고, 차단(block)은 새로 생기지 않는다(scrub-only 경계)
8
+ #
9
+ # 실행: bash hooks/tests/secret-guard-bypass.test.sh
10
+
11
+ set -u
12
+ HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
13
+ LIB_DIR="$HOOK_DIR/lib"
14
+ PASS=0; FAIL=0
15
+ ok() { printf ' \033[32m✓\033[0m %s\n' "$1"; PASS=$((PASS+1)); }
16
+ ng() { printf ' \033[31m✗\033[0m %s\n' "$1"; FAIL=$((FAIL+1)); }
17
+
18
+ W=$(mktemp -d "${TMPDIR:-/tmp}/rc-bypass.XXXXXX")
19
+ trap 'rm -rf "${W:?}"' EXIT
20
+ mkdir -p "$W/vault"
21
+ SECRET="sk-ant-oat01-$(LC_ALL=C tr -dc 'A-Za-z0-9' </dev/urandom | head -c 90)AA"
22
+ OTHER="npm_$(LC_ALL=C tr -dc 'A-Za-z0-9' </dev/urandom | head -c 36)"
23
+ CFG="$W/vault/my.cfg"
24
+ printf 'notes\nclaude setup-token = %s\nNPM = %s\n' "$SECRET" "$OTHER" > "$CFG"
25
+ chmod 600 "$CFG"
26
+ POL="$W/policy.json"
27
+ printf '{"mode":"warn","redact_only_paths":["%s"]}' "$CFG" > "$POL"
28
+ export ROUTINECODE_SECRET_POLICY_PATH="$POL"
29
+
30
+ targets() { # stdout: "<탐지 파일 수> <강제 래핑 여부>"
31
+ printf '%s' "$1" | python3 -c "
32
+ import sys; sys.path.insert(0, '$LIB_DIR')
33
+ import secret_filter as sf
34
+ f, force = sf.bash_secret_targets(sys.stdin.read())
35
+ print(len(f), force)"
36
+ }
37
+ expect_targets() { local got; got=$(targets "$2"); [ "$got" = "$3" ] && ok "$1 → $got" || ng "$1 — 기대 [$3] 실제 [$got]"; }
38
+
39
+ echo ""
40
+ echo "=== bash_secret_targets: 우회 경로 해석 ==="
41
+ expect_targets "리터럴 경로" "cat $CFG" "1 False"
42
+ expect_targets "따옴표 조각 경로" "cat \"$W/vault/my.\"\"cfg\"" "1 True"
43
+ expect_targets "변수 대입 경로" "C=$W/vault/my.cfg; awk '{print}' \"\$C\"" "1 False"
44
+ expect_targets "변수 조립 경로" "D=$W/vault; F=my.cfg; tail -1 \"\$D/\$F\"" "1 False"
45
+ expect_targets "글롭" "head -2 $W/vault/my.c*" "1 False"
46
+ expect_targets "디렉토리 재귀 grep" "grep -r token $W" "1 False"
47
+ expect_targets "python -c 인라인" "python3 -c \"print(open('x'+'y').read())\"" "0 True"
48
+ expect_targets "node -e 인라인" "node -e \"console.log(1)\"" "0 True"
49
+ expect_targets "python heredoc" "python3 - <<'EOF'
50
+ print(1)
51
+ EOF" "0 True"
52
+ expect_targets "eval" "eval \"cat x\"" "0 True"
53
+ expect_targets "base64 디코딩" "echo eA== | base64 -d" "0 True"
54
+ expect_targets "find -exec" "find /tmp -name x -exec cat {} \\;" "0 True"
55
+ expect_targets "회귀: 무관 명령" "ls -la /tmp && echo \"a\" \"b\"" "0 False"
56
+ expect_targets "회귀: git" "git status --short" "0 False"
57
+ expect_targets "알려진 한계: 백그라운드 &" "python3 -c \"print(1)\" &" "0 False"
58
+
59
+ echo ""
60
+ echo "=== pre-bash-guard 실행: 출력에서 값이 가려지는가 ==="
61
+ run_guarded() { # 훅이 재작성한 명령(없으면 원본)을 실행해 출력
62
+ local cmd="$1" input out newcmd
63
+ input=$(python3 -c "import json,sys; print(json.dumps({'tool_name':'Bash','tool_input':{'command':sys.argv[1]},'session_id':'t'}))" "$cmd")
64
+ out=$(printf '%s' "$input" | "$HOOK_DIR/pre-bash-guard.sh" 2>/dev/null)
65
+ if printf '%s' "$out" | grep -q '"decision": *"block"'; then echo "__BLOCKED__"; return; fi
66
+ newcmd=$(printf '%s' "$out" | python3 -c "
67
+ import sys,json
68
+ try:
69
+ d=json.loads(sys.stdin.read() or '{}'); print(d.get('hookSpecificOutput',{}).get('updatedInput',{}).get('command',''))
70
+ except Exception: print('')")
71
+ [ -n "$newcmd" ] || newcmd="$cmd"
72
+ bash -c "$newcmd" 2>&1
73
+ }
74
+ expect_masked() {
75
+ local name="$1" cmd="$2" out
76
+ out=$(run_guarded "$cmd")
77
+ if [ "$out" = "__BLOCKED__" ]; then ng "$name — 차단됨(scrub-only 경계 위반)"; return; fi
78
+ if printf '%s' "$out" | grep -qF -e "$SECRET" -e "$OTHER"; then ng "$name — 값 노출"; return; fi
79
+ printf '%s' "$out" | grep -q 'MASKED\|PROTECTED\|REDACTED' && ok "$name — 가려짐" || ng "$name — 마스크 흔적 없음: $(printf '%s' "$out" | head -c 80)"
80
+ }
81
+ expect_masked "따옴표 조각 cat" "cat \"$W/vault/my.\"\"cfg\""
82
+ expect_masked "변수 경로 awk" "C=$W/vault/my.cfg; awk -F' = ' '/setup-token/{print \$2}' \"\$C\""
83
+ expect_masked "python 문자열 조립" "python3 -c \"print(open('$W/vault/my.'+'cfg').read())\""
84
+ expect_masked "node 인라인" "node -e \"console.log(require('fs').readFileSync('$W/vault/my'+'.cfg','utf8'))\""
85
+ expect_masked "base64 인코딩 덤프" "python3 -c \"import base64;print(base64.b64encode(open('$W/vault/my.'+'cfg','rb').read()).decode())\""
86
+ expect_masked "디렉토리 grep" "grep -rh token $W"
87
+
88
+ echo ""
89
+ echo "=== Read / Grep: Bash 로 만든 사본 ==="
90
+ COPY="$W/copy.txt"; cp "$CFG" "$COPY"; chmod 644 "$COPY"
91
+ read_redirect() {
92
+ local tool="$1" key="$2" input out
93
+ input=$(python3 -c "import json,sys; print(json.dumps({'tool_name':sys.argv[1],'tool_input':{sys.argv[2]:sys.argv[3],'pattern':'token'},'session_id':'t'}))" "$tool" "$key" "$COPY")
94
+ out=$(printf '%s' "$input" | "$HOOK_DIR/$3" 2>/dev/null)
95
+ printf '%s' "$out" | python3 -c "import sys,json; print(json.loads(sys.stdin.read() or '{}').get('hookSpecificOutput',{}).get('updatedInput',{}).get(sys.argv[1],''))" "$key"
96
+ }
97
+ R=$(read_redirect Read file_path pre-read-guard.sh)
98
+ if [ -n "$R" ] && [ "$R" != "$COPY" ] && ! grep -qF "$SECRET" "$R" && grep -q "setup-token" "$R"; then ok "Read 사본 → 값만 가린 사본으로 대체(키 이름 유지)"; else ng "Read 사본 대체 실패 [$R]"; fi
99
+ G=$(read_redirect Grep path pre-grep-guard.sh)
100
+ if [ -n "$G" ] && [ "$G" != "$COPY" ] && ! grep -qF "$SECRET" "$G"; then ok "Grep 사본 → 값만 가린 사본 검색"; else ng "Grep 사본 대체 실패 [$G]"; fi
101
+ PLAIN="$W/plain.txt"; echo "hello" > "$PLAIN"
102
+ P=$(COPY="$PLAIN"; input=$(python3 -c "import json,sys; print(json.dumps({'tool_name':'Read','tool_input':{'file_path':sys.argv[1]},'session_id':'t'}))" "$PLAIN"); printf '%s' "$input" | "$HOOK_DIR/pre-read-guard.sh" 2>/dev/null | grep -c updatedInput)
103
+ [ "$P" = "0" ] && ok "회귀: 보호 값 없는 파일 Read 는 그대로" || ng "회귀: 일반 파일이 재작성됨"
104
+
105
+ echo ""
106
+ echo "결과: PASS $PASS / FAIL $FAIL"
107
+ [ "$FAIL" -eq 0 ]