@routinecrew/routinecode 2.31.56 → 2.31.58

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 (149) hide show
  1. package/bin/cli.sh +65 -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 +19 -1
  6. package/bin/seal-open.js +5 -2
  7. package/bin/setup.js +1 -1
  8. package/hooks/hooks-config.json +31 -4
  9. package/hooks/lib/anchors.json +523 -126
  10. package/hooks/lib/attest_reader.py +695 -0
  11. package/hooks/lib/completion_log.py +130 -0
  12. package/hooks/lib/evidence.py +12 -0
  13. package/hooks/lib/i18n.py +7 -0
  14. package/hooks/lib/rt_cleanup.py +61 -0
  15. package/hooks/lib/scrub_stream.py +43 -0
  16. package/hooks/lib/secret_filter.py +300 -1
  17. package/hooks/lib/supplements_sig.py +70 -0
  18. package/hooks/post-edit-track.sh +35 -5
  19. package/hooks/post-knowledge-query.sh +14 -0
  20. package/hooks/post-secret-detect.sh +12 -27
  21. package/hooks/post-tool-universal.sh +6 -0
  22. package/hooks/pre-account-guard.sh +13 -1
  23. package/hooks/pre-agent-spawn.mjs +1 -1
  24. package/hooks/pre-bash-guard.sh +11 -0
  25. package/hooks/pre-credit-guard.sh +45 -28
  26. package/hooks/pre-edit-domain-gate.sh +3 -1
  27. package/hooks/pre-edit-knowledge-gate.sh +3 -1
  28. package/hooks/pre-edit-snapshot.sh +29 -0
  29. package/hooks/pre-grep-guard.sh +11 -0
  30. package/hooks/pre-mark-complete.sh +170 -72
  31. package/hooks/pre-read-guard.sh +9 -0
  32. package/hooks/pre-read-knowledge-inject.sh +3 -1
  33. package/hooks/session-start.sh +66 -10
  34. package/hooks/stop-claim-check.v3.sh +81 -0
  35. package/hooks/stop-knowledge-remind.sh +45 -10
  36. package/hooks/tests/gate-integration.test.sh +183 -2
  37. package/hooks/tests/in-project-relax.test.py +2 -1
  38. package/hooks/tests/knowledge-loop.test.sh +89 -0
  39. package/hooks/tests/mcp-name-wiring.test.sh +64 -0
  40. package/hooks/tests/secret-guard.test.sh +2 -1
  41. package/hooks/tests/secret-premask.test.py +166 -0
  42. package/hooks/tests/stop-autoproceed.test.sh +60 -0
  43. package/hooks/user-prompt-submit.sh +18 -12
  44. package/mcp-db-manager/dist/analyzers/duplicate-detector.js +1 -1
  45. package/mcp-db-manager/dist/core/model-parser.js +1 -1
  46. package/mcp-db-manager/dist/core/schema-reader.js +1 -1
  47. package/mcp-db-manager/dist/executors/migration-executor.js +1 -1
  48. package/mcp-db-manager/dist/generators/migration-generator.js +1 -1
  49. package/mcp-db-manager/dist/index.js +1 -1
  50. package/mcp-db-manager/dist/validators/schema-validator.js +1 -1
  51. package/mcp-dev-tester/dist/analyzers/auth-diagnoser.js +1 -1
  52. package/mcp-dev-tester/dist/analyzers/backend-analyzer.js +1 -1
  53. package/mcp-dev-tester/dist/analyzers/endpoint-diagnoser.js +1 -1
  54. package/mcp-dev-tester/dist/analyzers/frontend-analyzer.js +1 -1
  55. package/mcp-dev-tester/dist/analyzers/runtime-diagnoser.js +1 -1
  56. package/mcp-dev-tester/dist/analyzers/type-comparator.js +1 -1
  57. package/mcp-dev-tester/dist/analyzers/validation-diagnoser.js +1 -1
  58. package/mcp-dev-tester/dist/attestation.d.ts +36 -0
  59. package/mcp-dev-tester/dist/attestation.d.ts.map +1 -0
  60. package/mcp-dev-tester/dist/attestation.js +1 -0
  61. package/mcp-dev-tester/dist/browser/playwright-manager.js +1 -1
  62. package/mcp-dev-tester/dist/browser/ui-tester.js +1 -1
  63. package/mcp-dev-tester/dist/config/project-config.js +1 -1
  64. package/mcp-dev-tester/dist/index.js +1 -1
  65. package/mcp-dev-tester/dist/testers/api-tester.js +1 -1
  66. package/mcp-doc-fetcher/dist/index.js +1 -1
  67. package/mcp-html-renderer/dist/index.js +1 -1
  68. package/mcp-html-renderer/dist/preview.js +1 -1
  69. package/mcp-html-renderer/dist/template-engine.js +1 -1
  70. package/mcp-intelligence/dist/concept-catalog.js +1 -1
  71. package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
  72. package/mcp-intelligence/dist/config-auth.js +1 -1
  73. package/mcp-intelligence/dist/contracts.generated.js +1 -1
  74. package/mcp-intelligence/dist/domain-templates.js +1 -1
  75. package/mcp-intelligence/dist/grounding.d.ts +1 -0
  76. package/mcp-intelligence/dist/grounding.d.ts.map +1 -1
  77. package/mcp-intelligence/dist/grounding.js +1 -1
  78. package/mcp-intelligence/dist/handlers.js +1 -1
  79. package/mcp-intelligence/dist/index.js +1 -1
  80. package/mcp-intelligence/dist/intelligence-file.js +1 -1
  81. package/mcp-intelligence/dist/knowledge-critic.js +1 -1
  82. package/mcp-intelligence/dist/knowledge-handlers.d.ts +20 -0
  83. package/mcp-intelligence/dist/knowledge-handlers.d.ts.map +1 -1
  84. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  85. package/mcp-intelligence/dist/mention-extractor.js +1 -1
  86. package/mcp-intelligence/dist/provenance.js +1 -1
  87. package/mcp-intelligence/dist/semantic-embedder.js +1 -1
  88. package/mcp-log-watcher/dist/config-auth.js +1 -1
  89. package/mcp-log-watcher/dist/file-watcher.js +1 -1
  90. package/mcp-log-watcher/dist/index.js +1 -1
  91. package/mcp-log-watcher/dist/known-solutions.js +1 -1
  92. package/mcp-log-watcher/dist/log-store.js +1 -1
  93. package/mcp-log-watcher/dist/websocket-server.js +1 -1
  94. package/mcp-plan-manager/dist/__tests__/plan-parser.test.js +1 -1
  95. package/mcp-plan-manager/dist/file-ops.js +1 -1
  96. package/mcp-plan-manager/dist/index.js +1 -1
  97. package/mcp-plan-manager/dist/plan-parser.js +1 -1
  98. package/mcp-project-context/dist/git-ops.js +1 -1
  99. package/mcp-project-context/dist/index.js +1 -1
  100. package/mcp-project-context/dist/project-analysis.js +1 -1
  101. package/mcp-routinecode/dist/agent-tracker.js +1 -1
  102. package/mcp-routinecode/dist/attestation.d.ts +37 -0
  103. package/mcp-routinecode/dist/attestation.js +1 -0
  104. package/mcp-routinecode/dist/blast-radius.js +1 -1
  105. package/mcp-routinecode/dist/changeset.d.ts +86 -0
  106. package/mcp-routinecode/dist/changeset.js +1 -0
  107. package/mcp-routinecode/dist/config-auth.js +1 -1
  108. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  109. package/mcp-routinecode/dist/coverage.d.ts +49 -0
  110. package/mcp-routinecode/dist/coverage.js +1 -0
  111. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  112. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  113. package/mcp-routinecode/dist/file-lock-registry.js +1 -1
  114. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  115. package/mcp-routinecode/dist/index.js +1 -1
  116. package/mcp-routinecode/dist/known-solutions.js +1 -1
  117. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  118. package/mcp-routinecode/dist/observed-draft.js +1 -1
  119. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  120. package/mcp-routinecode/dist/route-match.d.ts +24 -0
  121. package/mcp-routinecode/dist/route-match.js +1 -0
  122. package/mcp-routinecode/dist/routines.d.ts +1 -0
  123. package/mcp-routinecode/dist/routines.js +1 -1
  124. package/mcp-routinecode/dist/rule-engine.js +1 -1
  125. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  126. package/mcp-routinecode/dist/telemetry-analyzer.js +1 -1
  127. package/mcp-routinecode/dist/test-runner.d.ts +66 -0
  128. package/mcp-routinecode/dist/test-runner.js +1 -0
  129. package/mcp-routinecode/dist/verification.d.ts +65 -0
  130. package/mcp-routinecode/dist/verification.js +0 -0
  131. package/mcp-routinecode/dist/viral-loop.js +1 -1
  132. package/package.json +1 -1
  133. package/plugin/.claude-plugin/plugin.json +1 -1
  134. package/plugin/agents/analyzer.md.sealed +1 -0
  135. package/plugin/agents/crawler.md.sealed +1 -0
  136. package/plugin/agents/explorer.md.sealed +1 -0
  137. package/plugin/agents/implementor.md.sealed +1 -0
  138. package/plugin/agents/looker.md.sealed +1 -0
  139. package/plugin/agents/planner.md.sealed +1 -0
  140. package/plugin/agents/recorder.md.sealed +1 -0
  141. package/plugin/agents/reviewer.md.sealed +1 -0
  142. package/plugin/agents/verifier.md.sealed +1 -0
  143. package/plugin/commands/analyze.md.sealed +1 -0
  144. package/plugin/commands/plan.md.sealed +1 -0
  145. package/plugin/commands/rc.md.sealed +1 -0
  146. package/plugin/commands/receipt.md.sealed +1 -0
  147. package/plugin/commands/routines.md.sealed +1 -0
  148. package/plugin/commands/share.md.sealed +1 -0
  149. package/plugin/routinecode-prompt.md.sealed +1 -0
@@ -0,0 +1,130 @@
1
+ """Completion log — 결함 유출률(escaped-defect rate) 실측의 원천 기록.
2
+
3
+ mark_task_complete 가 허용될 때마다 1행 append:
4
+ {v, taskId, ts(ms), tier, score, forcedPass, dims, files, preEditFailure, hadFailure}
5
+
6
+ - preEditFailure: 이 태스크 창에서 **첫 편집 전에** 이미 빌드/테스트 실패 attestation 이 있었는가
7
+ = "시작 시점 코드가 깨져 있었다" → 이 태스크가 고친 파일을 이전에 완료 처리한 태스크의 결함 유출 신호.
8
+ - 판정(유출 여부)은 mcp-routinecode verification.ts escapedDefectReport 가 수행.
9
+ fail-open: 어떤 오류도 게이트 판정에 영향을 주지 않는다.
10
+ """
11
+
12
+ import json
13
+ import os
14
+ import sys
15
+ import time
16
+
17
+ _HERE = os.path.dirname(os.path.abspath(__file__))
18
+ if _HERE not in sys.path:
19
+ sys.path.insert(0, _HERE)
20
+
21
+ WINDOW_MS = 7 * 24 * 3600 * 1000
22
+
23
+
24
+ def _kdir():
25
+ return os.environ.get('ROUTINECODE_KNOWLEDGE_DIR') or os.path.join(
26
+ os.path.expanduser('~'), '.routinecode', 'knowledge')
27
+
28
+
29
+ def _last_ts(log_path):
30
+ try:
31
+ with open(log_path, 'rb') as f:
32
+ f.seek(0, 2)
33
+ size = f.tell()
34
+ f.seek(max(0, size - 8192))
35
+ tail = f.read().decode('utf-8', 'ignore').strip().split('\n')
36
+ for line in reversed(tail):
37
+ try:
38
+ return int(json.loads(line).get('ts') or 0)
39
+ except Exception:
40
+ continue
41
+ except Exception:
42
+ pass
43
+ return 0
44
+
45
+
46
+ def _first_edit_ms(since_ms, files):
47
+ try:
48
+ from ledger_reader import query_evidence
49
+ rows = query_evidence(categories=['code_change'], since_ts_ns=since_ms * 1_000_000, limit=5000)
50
+ except Exception:
51
+ return None
52
+ fs = set(files)
53
+ ts = [r.get('ts_ns', 0) // 1_000_000 for r in rows
54
+ if not fs or (r.get('payload') or {}).get('file') in fs]
55
+ ts = [t for t in ts if t > 0]
56
+ return min(ts) if ts else None
57
+
58
+
59
+ def record_completion(task_id, tier, tracker_path):
60
+ now = int(time.time() * 1000)
61
+ kdir = _kdir()
62
+ vdir = os.path.join(kdir, 'verification')
63
+ log_path = os.path.join(vdir, 'completions.jsonl')
64
+
65
+ files = []
66
+ try:
67
+ files = [f for f in json.load(open(tracker_path)).get('files', []) if isinstance(f, str)]
68
+ except Exception:
69
+ pass
70
+
71
+ prev = max(_last_ts(log_path), now - WINDOW_MS)
72
+
73
+ score = None
74
+ forced = False
75
+ dims = None
76
+ try:
77
+ v = json.load(open(os.path.join(vdir, f'development-{task_id}.json')))
78
+ from attest_reader import verify_state
79
+ if not verify_state(v):
80
+ raise ValueError('unsigned score file') # 위조 점수로 유출률 밴드 오염 방지
81
+ score = v.get('currentScore')
82
+ forced = bool(v.get('forcedPass'))
83
+ auto = [i for i in v.get('iterations', []) if i.get('autoScored')]
84
+ if auto:
85
+ dims = auto[-1].get('dimensions')
86
+ except Exception:
87
+ pass
88
+
89
+ # None = 판정 불가(ledger 없음) — 유출률 집계에서 unknown 으로 분리 (False 로 과소집계 방지)
90
+ pre_edit_failure = None
91
+ had_failure = False
92
+ try:
93
+ from attest_reader import read_attestations
94
+ dirs = {os.path.realpath(os.path.dirname(f)) for f in files}
95
+
96
+ def related(pd):
97
+ if not pd or not dirs:
98
+ return True
99
+ pd = os.path.realpath(pd)
100
+ return any(d == pd or d.startswith(pd + os.sep) or pd.startswith(d + os.sep) for d in dirs)
101
+
102
+ # 이 태스크가 고친 파일과 관련된 프로젝트의 실패만 (다른 레포 실패 혼입 방지)
103
+ fails = [a for a in read_attestations(since_ms=prev, kinds=['build', 'tests', 'typecheck'])
104
+ if a.get('success') is False and related(a.get('projectDir'))]
105
+ had_failure = bool(fails)
106
+ first_edit = _first_edit_ms(prev, files)
107
+ if first_edit is not None:
108
+ # 실행 시작 시각 기준 (ts 는 종료 시각)
109
+ pre_edit_failure = any(int((a.get('detail') or {}).get('startedAt') or a.get('ts', 0)) < first_edit for a in fails)
110
+ except Exception:
111
+ pass
112
+
113
+ row = {
114
+ 'v': 1, 'taskId': task_id, 'ts': now, 'tier': tier,
115
+ 'score': score, 'forcedPass': forced, 'dims': dims, 'files': files[:200],
116
+ 'preEditFailure': pre_edit_failure, 'hadFailure': had_failure,
117
+ }
118
+ try:
119
+ os.makedirs(vdir, exist_ok=True)
120
+ with open(log_path, 'a', encoding='utf-8') as f:
121
+ f.write(json.dumps(row, ensure_ascii=False) + '\n')
122
+ except Exception:
123
+ pass
124
+
125
+
126
+ if __name__ == '__main__':
127
+ try:
128
+ record_completion(sys.argv[1], sys.argv[2], sys.argv[3])
129
+ except Exception:
130
+ pass
@@ -168,6 +168,16 @@ BASH_COMMAND_DOMAIN = [
168
168
  (re.compile(r'\bgh\s+pr\s+create\b', re.IGNORECASE), 'pr_create'),
169
169
  ]
170
170
 
171
+ def normalize_mcp_tool_name(name):
172
+ """mcp__mcp-project-context__x → mcp__project_context__x (서버키 'mcp-*' 등록 세션 호환)."""
173
+ if isinstance(name, str) and name.startswith('mcp__mcp-'):
174
+ rest = name[len('mcp__mcp-'):]
175
+ srv, sep, tool = rest.partition('__')
176
+ if sep:
177
+ return 'mcp__' + srv.replace('-', '_') + '__' + tool
178
+ return name
179
+
180
+
171
181
  # MCP tool name → domain mapping (언어 무관)
172
182
  MCP_TOOL_DOMAIN = {
173
183
  'mcp__routinecode__build_check': 'build_ok',
@@ -205,6 +215,8 @@ def _transcript_tool_evidence(entries, last_user_idx, last_asst_idx):
205
215
  tool_input = block.get('input', {})
206
216
 
207
217
  # MCP 도구는 이름만으로도 증거 승격 가능
218
+ # 대화형 세션 도구명 mcp__mcp-routinecode__x → 정규형 mcp__routinecode__x
219
+ tool_name = normalize_mcp_tool_name(tool_name)
208
220
  if tool_name in MCP_TOOL_DOMAIN:
209
221
  tool_id_to_domain[tool_id] = MCP_TOOL_DOMAIN[tool_name]
210
222
  continue
package/hooks/lib/i18n.py CHANGED
@@ -241,6 +241,13 @@ STRINGS = {
241
241
  "zh": "[SECRET-GUARD:{severity}] 在 {tool_name} 响应中检测到 {count} 个敏感信息({summary})— 已在服务器传输前脱敏。以下是脱敏内容:",
242
242
  "es": "[SECRET-GUARD:{severity}] {count} secreto(s) ({summary}) detectado(s) en respuesta de {tool_name} — redactado antes de transmisión. Contenido redactado:",
243
243
  },
244
+ "secret.detect_notice": {
245
+ "en": "[SECRET-GUARD:{severity}] {count} secret-like value(s) ({summary}) appeared in the {tool_name} output. Do not repeat them in replies, commits, files or logs. To view a secret file safely, Read it (values are masked automatically).",
246
+ "ko": "[SECRET-GUARD:{severity}] {tool_name} 출력에 민감값으로 보이는 항목 {count}건({summary})이 있습니다. 응답·커밋·파일·로그에 옮기지 마세요. 비밀 파일은 Read 로 열면 값이 자동 마스킹됩니다.",
247
+ "ja": "[SECRET-GUARD:{severity}] {tool_name} の出力に機密値と思われる項目が {count}件({summary})あります。返信・コミット・ファイル・ログに転記しないでください。秘密ファイルは Read で開くと値が自動マスクされます。",
248
+ "zh": "[SECRET-GUARD:{severity}] {tool_name} 输出中出现 {count} 个疑似敏感值({summary})。请勿在回复、提交、文件或日志中重复。用 Read 打开秘密文件会自动遮盖值。",
249
+ "es": "[SECRET-GUARD:{severity}] {count} valor(es) sensibles ({summary}) aparecieron en la salida de {tool_name}. No los repitas en respuestas, commits, archivos ni logs. Usa Read para ver archivos secretos (los valores se enmascaran).",
250
+ },
244
251
  "secret.redact_footer": {
245
252
  "en": "[SECRET-GUARD] The content above was read locally but only the redacted version is sent to Anthropic API. If you need the original, check directly in your local shell/editor.",
246
253
  "ko": "[SECRET-GUARD] 위 본문은 local에서는 정상 읽혔으나 Anthropic API로는 redact된 버전만 전송된다. secret 원문이 필요하면 local shell/editor에서 직접 확인할 것.",
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env python3
2
+ """Sealed Core 세션 임시 복호본(~/.routinecode/.rt/*) 정리.
3
+
4
+ bin/cli.sh 는 seal-open 에 RC_LAUNCH_PID=$$ 를 넘기고, 곧 exec 로 Claude Code 가 된다(PID 유지).
5
+ 그래서 복호본 폴더 이름 '<pid>-<rand>' 의 pid 는 그 세션의 Claude Code 프로세스다.
6
+ - pid 프로세스가 살아 있으면 보존(세션 중 프롬프트 파일을 다시 읽어도 안전).
7
+ - pid 가 종료됐으면 삭제.
8
+ - pid 재사용 대비: 7일 지난 것은 무조건 삭제.
9
+ - pid 없는 이전 형식: 기존 규칙대로 60분 지나면 삭제.
10
+ 항상 exit 0 (session-start 를 막지 않는다).
11
+ """
12
+ import os
13
+ import re
14
+ import shutil
15
+ import sys
16
+ import time
17
+
18
+ RT = os.path.join(os.path.expanduser('~'), '.routinecode', '.rt')
19
+ MAX_AGE = 7 * 24 * 3600
20
+ LEGACY_AGE = 60 * 60
21
+
22
+
23
+ def alive(pid):
24
+ try:
25
+ os.kill(pid, 0)
26
+ return True
27
+ except ProcessLookupError:
28
+ return False
29
+ except PermissionError:
30
+ return True # 존재하지만 다른 사용자 — 보수적으로 살아 있음
31
+ except Exception:
32
+ return True
33
+
34
+
35
+ def main():
36
+ if not os.path.isdir(RT):
37
+ return
38
+ now = time.time()
39
+ for name in os.listdir(RT):
40
+ p = os.path.join(RT, name)
41
+ if not os.path.isdir(p) or os.path.islink(p):
42
+ continue
43
+ try:
44
+ age = now - os.stat(p).st_mtime
45
+ except Exception:
46
+ continue
47
+ m = re.match(r'^(\d+)-', name)
48
+ if m:
49
+ remove = age > MAX_AGE or not alive(int(m.group(1)))
50
+ else:
51
+ remove = age > LEGACY_AGE
52
+ if remove:
53
+ shutil.rmtree(p, ignore_errors=True)
54
+
55
+
56
+ if __name__ == '__main__':
57
+ try:
58
+ main()
59
+ except Exception:
60
+ pass
61
+ sys.exit(0)
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env python3
2
+ """scrub_stream — Bash 출력 필터 (pre-bash-guard 가 비밀 파일·환경변수 덤프 명령을 감쌀 때 사용).
3
+
4
+ stdin 을 줄 단위로 읽어 비밀 값을 MASK_TOKEN 으로 바꿔 stdout 에 즉시 흘린다.
5
+ 가리는 값: argv 로 받은 비밀 파일에서 뽑은 값 + 이름이 비밀스러운 환경변수 값 + 알려진 토큰 패턴.
6
+ 출력이 모델에 도달하기 '전'에 가려지는 유일한 Bash 경로다(PostToolUse 는 이미 전달된 출력을 못 바꾼다).
7
+
8
+ 사용: <cmd> 2>&1 | python3 scrub_stream.py [secret_file ...]
9
+ """
10
+ import os
11
+ import sys
12
+
13
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
14
+
15
+
16
+ def main():
17
+ try:
18
+ import secret_filter as sf
19
+ values = sf.scrub_values_for(sys.argv[1:])
20
+ policy = sf.load_policy()
21
+ token = sf.MASK_TOKEN
22
+ except Exception:
23
+ sf = None
24
+ values, policy, token = [], None, '***MASKED***'
25
+ out = sys.stdout
26
+ for line in sys.stdin:
27
+ for v in values:
28
+ if v in line:
29
+ line = line.replace(v, token)
30
+ if sf is not None:
31
+ try:
32
+ line, _ = sf.redact(line, policy)
33
+ except Exception:
34
+ pass
35
+ out.write(line)
36
+ out.flush()
37
+
38
+
39
+ if __name__ == '__main__':
40
+ try:
41
+ main()
42
+ except (BrokenPipeError, KeyboardInterrupt):
43
+ pass
@@ -113,7 +113,7 @@ REDACT_PATTERNS: List[Tuple[re.Pattern, str, str]] = [
113
113
  # 값 separator `:` 또는 `=` 모두. 값은 4자 이상.
114
114
  # 값에서 `*` 제외 + 뒤에 `*` 없음 → 이미 마스킹된 토큰(예: ghp_***REDACTED***)을
115
115
  # 다시 매칭하는 이중 카운트를 방지(특정 토큰 패턴이 먼저 실행되어 마스킹됨).
116
- (re.compile(r'(?i)(?<![\w-])([a-z0-9_.-]*(?:passwords?|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|client[_-]?secret|access[_-]?token|auth[_-]?token|passphrase|credentials?))\s*[:=]\s*["\']?(?!(?:ghp_|gho_|ghs_|ghu_|github_pat_|npm_|sk-|sk_live_|rk_live_|pk_live_|AKIA|ASIA|xox|SG\.|eyJ))([^\s"\'&;,}*]{4,})(?!\*)["\']?'),
116
+ (re.compile(r'(?i)(?<![\w-])([a-z0-9_.-]*(?:passwords?|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|client[_-]?secret|access[_-]?token|auth[_-]?token|passphrase|credentials?))\s*[:=]\s*["\']?(?!(?:ghp_|gho_|ghs_|ghu_|github_pat_|npm_|sk-|sk_live_|rk_live_|pk_live_|AKIA|ASIA|xox|SG\.|eyJ))(?!(?:process\.env|import\.meta\.env|os\.environ|os\.getenv|getenv\(|env\(|ENV\[|z\.|Joi\.|new |await |\(|\$\{|\{\{|<|`))(?!(?:string|number|boolean|undefined|null|None|str|int|bool|Optional|required|function|Secret|SecretStr)\b)(?![A-Za-z_$][\w$]*(?:\.[\w$]+)+(?:[\s,;)\]}]|$)|[A-Za-z_$][\w$]*(?:\.[\w$]+)*\()([^\s"\'&;,}*]{4,})(?!\*)["\']?'),
117
117
  r'\1=***REDACTED***', 'kv_secret'),
118
118
  # --token / --password CLI flags
119
119
  (re.compile(r'(--(?:token|password|pass|secret|api-key)[= ])[^\s"\']+'), r'\1***REDACTED***', 'cli_flag'),
@@ -220,6 +220,9 @@ CORE_PROTECTED_PATH_GLOBS = [
220
220
  # 사용자 홈 내부 config — .routinecode/ 하위 모든 json (런타임 apiKey·정책 등 모든 설정)
221
221
  '**/.routinecode/*.json',
222
222
  '**/.routinecode/**/*.json',
223
+ '**/.routinecode/*.json.*',
224
+ # Sealed Core 세션 임시 복호본(메인 프롬프트 평문) — 세션 동안만 존재, 모델 경유 읽기 차단
225
+ '**/.routinecode/.rt/**',
223
226
  # RoutineCode 설치물 hooks — 방어 로직 전체 (routinecode/ 로 스코프).
224
227
  # prefix 열거 대신 hooks/ 하위 모든 로직·설정 파일을 포괄 → 신규 훅 추가 시 자동 보호.
225
228
  '**/routinecode/hooks/*.sh',
@@ -227,6 +230,9 @@ CORE_PROTECTED_PATH_GLOBS = [
227
230
  '**/routinecode/hooks/*.js',
228
231
  '**/routinecode/hooks/*.json',
229
232
  '**/routinecode/hooks/lib/*',
233
+ # Claude Code 플러그인 캐시 — setup 이 마켓플레이스로 등록하면 CC 가 plugin/ 을 여기로 복사한다
234
+ # (프롬프트·에이전트 정의 평문 사본). 설치본과 같은 자산이므로 같은 수준으로 보호.
235
+ '**/plugins/cache/routinecode-marketplace/**',
230
236
  ]
231
237
 
232
238
  # 명시적 허용 (공개 키는 민감 아님)
@@ -292,6 +298,8 @@ CORE_PROTECTED_COMMAND_PATTERNS = [
292
298
  # dd if=CORE / stdin redirect read (python3 - < file, node < file)
293
299
  r'\bdd\s+[^|&;]*\bif=[^|&;]*routinecode[/\\](?:hooks|plugin|mcp-[\w.-]+|engine)',
294
300
  r'(?:python3?|node|bash|sh|ruby|perl)\b[^|&;]*<\s*[^|&;]*routinecode[/\\](?:hooks|plugin|mcp-[\w.-]+[/\\]dist|engine)',
301
+ # 검증 증거(attestation) 위조 차단 — 서버가 직접 실행한 결과만 점수가 된다.
302
+ r'\bappendAttestation\b|\battestations\.jsonl\b|\battest[/\\]\.key\b',
295
303
  ]
296
304
 
297
305
 
@@ -1017,6 +1025,50 @@ def _is_runtime_config_rule(rule):
1017
1025
  return '.routinecode/' in _normalize_rule(rule)
1018
1026
 
1019
1027
 
1028
+ _RC_PKG_NAME = '@routinecrew/' + 'routinecode'
1029
+ _RC_SEG_RE = re.compile(r'(?:^|[/\\])routinecode(?=[/\\])')
1030
+ _pkg_root_cache: dict = {}
1031
+
1032
+
1033
+ def _is_rc_package_dir(d: str) -> bool:
1034
+ """d 가 실제 RoutineCode 패키지(설치본·dev 체크아웃) 루트인가 — package.json name 으로 판정."""
1035
+ if d in _pkg_root_cache:
1036
+ return _pkg_root_cache[d]
1037
+ ok = False
1038
+ try:
1039
+ with open(os.path.join(d, 'package.json'), encoding='utf-8') as fh:
1040
+ ok = json.load(fh).get('name') == _RC_PKG_NAME
1041
+ except Exception:
1042
+ ok = False
1043
+ _pkg_root_cache[d] = ok
1044
+ return ok
1045
+
1046
+
1047
+ def _rc_scoped_rule(rule: str) -> bool:
1048
+ """`routinecode/` 세그먼트나 plugin/routinecode-prompt.md 로 스코프된 '설치물' 규칙인가.
1049
+ (홈 런타임 config·플러그인 캐시 규칙은 패키지 판정 대상이 아님)"""
1050
+ r = _normalize_rule(rule)
1051
+ return ('/routinecode/' in r or r.endswith('/plugin/routinecode-prompt.md')) and \
1052
+ '.routinecode/' not in r and 'plugins/cache/' not in r
1053
+
1054
+
1055
+ def _path_in_rc_package(p: str) -> bool:
1056
+ """경로가 실제 RoutineCode 패키지 안인가. 이름만 같은 사용자 레포(예: ~/work/routinecode)는 False.
1057
+ 존재하지 않는 경로도 False — 보호할 실물이 없다."""
1058
+ if not p:
1059
+ return False
1060
+ # npm 설치 위치(node_modules/@routinecrew/routinecode)는 존재 여부와 무관하게 설치물로 본다
1061
+ if '/node_modules/' + _RC_PKG_NAME + '/' in p.replace('\\', '/') + '/':
1062
+ return True
1063
+ cands = []
1064
+ for m in _RC_SEG_RE.finditer(p):
1065
+ cands.append(p[:m.end()])
1066
+ i = p.rfind('/plugin/')
1067
+ if i > 0:
1068
+ cands.append(p[:i])
1069
+ return any(_is_rc_package_dir(c) for c in cands)
1070
+
1071
+
1020
1072
  def _core_path_verdict(path: str, policy: Policy) -> Tuple[bool, Optional[str]]:
1021
1073
  """CORE 소스보호 판정만 수행. (banned, rule).
1022
1074
 
@@ -1045,17 +1097,56 @@ def _core_path_verdict(path: str, policy: Policy) -> Tuple[bool, Optional[str]]:
1045
1097
  continue
1046
1098
  elif _dev_mode() or _is_dev_source_path(real):
1047
1099
  continue
1100
+ # 이름만 'routinecode' 인 사용자 레포/가상 경로는 보호 대상 아님(거짓 차단 방지)
1101
+ if _rc_scoped_rule(rule) and not any(_path_in_rc_package(t) for t in targets):
1102
+ continue
1048
1103
  return True, rule
1049
1104
  return False, None
1050
1105
 
1051
1106
 
1107
+ def _rc_mentions_all_benign(cmd: str) -> bool:
1108
+ """명령 속 `routinecode/<자산>` 언급이 전부 '실물 RoutineCode 패키지가 아닌' 리터럴 경로인가.
1109
+ 변수·명령치환·글롭이 섞인 단어는 해석 불가 → 실물로 간주(False). 상대경로는 선두 cd·cwd 기준.
1110
+ True 면 사용자 레포 이름이 routinecode 이거나 테스트 문자열일 뿐이므로 CORE 차단하지 않는다."""
1111
+ words = re.findall(r'\S*routinecode[/\\]\S*', cmd)
1112
+ if not words:
1113
+ return False
1114
+ m_cd = re.match(r'\s*cd\s+([^\s;&|]+)\s*(?:&&|;|\|)', cmd)
1115
+ base = os.path.abspath(os.path.expanduser(m_cd.group(1))) if m_cd else os.getcwd()
1116
+ for w in words:
1117
+ if any(ch in w for ch in '$`*?[{()'):
1118
+ return False
1119
+ w = w.strip('\'"`;&|<>)')
1120
+ if '=' in w:
1121
+ w = w.split('=', 1)[1]
1122
+ p = os.path.expanduser(w)
1123
+ if not os.path.isabs(p):
1124
+ p = os.path.join(base, p)
1125
+ p = os.path.normpath(p)
1126
+ try:
1127
+ rp = os.path.realpath(p)
1128
+ except Exception:
1129
+ rp = p
1130
+ if _path_in_rc_package(p) or _path_in_rc_package(rp):
1131
+ return False
1132
+ return True
1133
+
1134
+
1052
1135
  def _core_command_verdict(cmd: str, policy: Policy) -> Tuple[bool, Optional[str]]:
1053
1136
  """CORE 명령 패턴 판정만 수행. (banned, rule). dev 소스 대상 명령은 완화(config 리터럴 제외)."""
1054
1137
  _dev = _dev_mode() or _cmd_targets_dev_source(cmd)
1055
1138
  _touches_cfg = bool(re.search(r'\.routinecode[/\\]', cmd))
1139
+ _benign = None
1056
1140
  for raw_pat in policy.core_commands:
1057
1141
  try:
1058
1142
  if re.search(raw_pat, cmd, re.IGNORECASE):
1143
+ # 설치물 패턴(routinecode/hooks·plugin·mcp-·engine)인데 언급된 경로가 전부 실물 패키지가
1144
+ # 아니면(이름만 같은 사용자 레포·테스트 문자열) 차단하지 않는다.
1145
+ if 'routinecode[' in raw_pat and not _touches_cfg:
1146
+ if _benign is None:
1147
+ _benign = _rc_mentions_all_benign(cmd)
1148
+ if _benign:
1149
+ continue
1059
1150
  # .routinecode/ 리터럴을 건드리는 bash 명령은 dev 모드여도 계속 차단한다.
1060
1151
  # 이유: 값-스크럽(collect_protected_values)이 **-glob(.routinecode/*.json)을
1061
1152
  # 성능상 건너뛰어 bash stdout 에는 apiKey 백스톱이 없다. Read 는
@@ -1296,6 +1387,214 @@ def check_bash_command(cmd: str, policy: Optional[Policy] = None) -> Tuple[bool,
1296
1387
  return False, None, []
1297
1388
 
1298
1389
 
1390
+ # ─── 비밀 파일 사전 마스킹 (2026-10-16) ─────────────────────────────────
1391
+ # PostToolUse 는 이미 모델에 전달된 도구 출력을 바꾸지 못한다(실측: 원본과 사본이 둘 다 전달됨).
1392
+ # 그래서 비밀 '값'은 도구가 실행되기 전에 막는다:
1393
+ # - Read/Grep 이 비밀 파일을 가리키면 → 값이 마스킹된 사본 경로로 바꿔 읽힌다(키 이름은 그대로).
1394
+ # - Bash 명령이 비밀 파일·환경변수 덤프를 건드리면 → 출력이 scrub_stream.py 를 거쳐 나오게 감싼다.
1395
+ # 접근 자체는 막지 않는다(개발자는 자기 설정을 참조할 수 있어야 한다) — 값만 모델에 가지 않는다.
1396
+
1397
+ _TEMPLATE_SUFFIXES = ('.example', '.sample', '.template', '.tmpl', '.dist', '.defaults')
1398
+ MASK_TOKEN = '***MASKED***'
1399
+ MASK_HEADER = '# [RoutineCode] 값이 마스킹된 사본입니다(키 이름만 표시). 값 변경은 사용자에게 요청하세요.\n'
1400
+ _MASK_MAX_BYTES = 1024 * 1024
1401
+ _KV_LINE_RE = re.compile(r'^(\s*(?:export\s+)?[A-Za-z_][\w.\-]*\s*[=:]\s*)(.*?)(\s*)$')
1402
+ _JSON_STR_KV_RE = re.compile(r'("(?:[^"\\]|\\.)*"\s*:\s*)"((?:[^"\\]|\\.)*)"')
1403
+ _PEM_RE = re.compile(r'(-----BEGIN [^-]+-----)(.*?)(-----END [^-]+-----)', re.S)
1404
+ _URL_CRED_RE = re.compile(r'^([a-z][a-z0-9+.\-]*://)([^/@\s]+)@', re.I)
1405
+ _PUBLIC_VALUE_RE = re.compile(r'^(?:-?\d+(?:\.\d+)?|true|false|yes|no|on|off|null|none|development|production|test|staging|local|localhost|127\.0\.0\.1|0\.0\.0\.0)$', re.I)
1406
+ _SECRET_ENV_NAME_RE = re.compile(r'(SECRET|TOKEN|PASSWORD|PASSWD|PASS|PWD|API_?KEY|PRIVATE|CREDENTIAL|AUTH|SESSION|COOKIE|DSN|DATABASE_URL|_KEY$)', re.I)
1407
+
1408
+
1409
+ def is_secret_file(path: str, policy: Optional[Policy] = None) -> bool:
1410
+ """generic 비밀 파일(.env·키·자격증명 등)인가. 템플릿(.env.example 등)과 allowlist 는 제외."""
1411
+ if not isinstance(path, str) or not path:
1412
+ return False
1413
+ if policy is None:
1414
+ policy = load_policy()
1415
+ real = _normalize_path(path)
1416
+ lexical = _lexical_path(path)
1417
+ targets = {real, lexical}
1418
+ basenames = {os.path.basename(t) for t in targets}
1419
+ if any(b.lower().endswith(_TEMPLATE_SUFFIXES) for b in basenames):
1420
+ return False
1421
+
1422
+ def _m(rule):
1423
+ nr = _normalize_rule(rule)
1424
+ return any(fnmatch.fnmatch(t, nr) for t in targets) or any(fnmatch.fnmatch(b, nr) for b in basenames)
1425
+
1426
+ if any(_m(r) for r in policy.path_allowlist):
1427
+ return False
1428
+ return any(_m(r) for r in list(policy.secret_paths) + list(policy.redact_only_paths))
1429
+
1430
+
1431
+ def core_dir_scope(path: str) -> bool:
1432
+ """Grep 등 '디렉터리 단위' 검색이 RoutineCode 설치물(또는 그것을 담은 상위 디렉터리)을 훑는가.
1433
+ dev 소스 체크아웃은 제외(개발자 무마찰). 파일 경로 판정은 _core_path_verdict 가 담당."""
1434
+ if not isinstance(path, str) or not path:
1435
+ return False
1436
+ try:
1437
+ real = os.path.realpath(os.path.expanduser(path))
1438
+ except Exception:
1439
+ return False
1440
+ if not os.path.isdir(real) or _is_dev_source_path(real):
1441
+ return False
1442
+ if _is_rc_package_dir(real) or _path_in_rc_package(real + '/'):
1443
+ return True
1444
+ if '/plugins/cache/routinecode-marketplace' in real + '/':
1445
+ return True
1446
+ for sub in ('routinecode', os.path.join('@routinecrew', 'routinecode'),
1447
+ os.path.join('node_modules', '@routinecrew', 'routinecode'),
1448
+ 'routinecode-marketplace'):
1449
+ c = os.path.join(real, sub)
1450
+ if os.path.isdir(c) and (_is_rc_package_dir(c) or sub == 'routinecode-marketplace'):
1451
+ return True
1452
+ return False
1453
+
1454
+
1455
+ def _mask_value(v: str) -> str:
1456
+ raw = v.strip()
1457
+ q = ''
1458
+ if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in '"\'':
1459
+ q, raw = raw[0], raw[1:-1]
1460
+ if not raw or _PUBLIC_VALUE_RE.match(raw):
1461
+ return v
1462
+ m = _URL_CRED_RE.match(raw)
1463
+ if m: # 접속 URL — 자격(user:pass)만 가리고 호스트·DB 명은 남김(개발 참조용)
1464
+ return q + m.group(1) + MASK_TOKEN + '@' + raw[m.end():] + q
1465
+ return q + MASK_TOKEN + q
1466
+
1467
+
1468
+ def mask_secret_text(content: str) -> Tuple[str, int]:
1469
+ """비밀 파일 내용에서 값만 마스킹. (masked, count). 키 이름·주석·구조는 유지."""
1470
+ n = 0
1471
+
1472
+ def _pem(m):
1473
+ nonlocal n
1474
+ n += 1
1475
+ return m.group(1) + '\n' + MASK_TOKEN + '\n' + m.group(3)
1476
+
1477
+ content = _PEM_RE.sub(_pem, content)
1478
+ stripped = content.lstrip()
1479
+ if stripped.startswith('{') or stripped.startswith('['): # JSON 자격증명 파일
1480
+ def _js(m):
1481
+ nonlocal n
1482
+ mv = _mask_value(m.group(2))
1483
+ if mv != m.group(2):
1484
+ n += 1
1485
+ return m.group(1) + '"' + mv + '"'
1486
+ return _JSON_STR_KV_RE.sub(_js, content), n
1487
+ out = []
1488
+ for line in content.splitlines(keepends=True):
1489
+ body = line.rstrip('\r\n')
1490
+ nl = line[len(body):]
1491
+ st = body.strip()
1492
+ if not st or st.startswith(('#', ';', '//')) or st == MASK_TOKEN or st.startswith('-----'):
1493
+ out.append(line)
1494
+ continue
1495
+ m = _KV_LINE_RE.match(body)
1496
+ if m:
1497
+ mv = _mask_value(m.group(2))
1498
+ if mv != m.group(2):
1499
+ n += 1
1500
+ out.append(m.group(1) + mv + m.group(3) + nl)
1501
+ continue
1502
+ # 구조 없는 줄(키 파일 본문·토큰 한 줄 등) — 값 토큰만 가린다
1503
+ toks = [t for t in _VALUE_SPLIT_RE.split(body) if _is_value_token(t.strip('"\'`'))]
1504
+ for t in sorted(set(toks), key=len, reverse=True):
1505
+ body = body.replace(t, MASK_TOKEN)
1506
+ n += 1
1507
+ out.append(body + nl)
1508
+ return ''.join(out), n
1509
+
1510
+
1511
+ def masked_copy_path(path: str) -> Optional[str]:
1512
+ """비밀 파일의 값-마스킹 사본을 만들어 경로 반환. 원본이 없거나 너무 크면 None."""
1513
+ import hashlib
1514
+ import tempfile
1515
+ try:
1516
+ real = os.path.realpath(os.path.expanduser(path))
1517
+ if not os.path.isfile(real) or os.path.getsize(real) > _MASK_MAX_BYTES:
1518
+ return None
1519
+ with open(real, 'rb') as fh:
1520
+ raw = fh.read()
1521
+ if b'\x00' in raw[:8192]: # 바이너리 키스토어(.p12/.jks) — 내용 대신 안내만
1522
+ masked = MASK_HEADER + '# (binary secret file — content not shown)\n'
1523
+ else:
1524
+ masked = MASK_HEADER + mask_secret_text(raw.decode('utf-8', errors='replace'))[0]
1525
+ d = os.path.join(tempfile.gettempdir(), 'rc-masked-%d' % os.getuid(),
1526
+ hashlib.sha256(real.encode('utf-8')).hexdigest()[:16])
1527
+ os.makedirs(d, mode=0o700, exist_ok=True)
1528
+ out = os.path.join(d, os.path.basename(real) or 'secret')
1529
+ fd = os.open(out + '.tmp', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
1530
+ with os.fdopen(fd, 'w', encoding='utf-8') as fh:
1531
+ fh.write(masked)
1532
+ os.replace(out + '.tmp', out)
1533
+ return out
1534
+ except Exception:
1535
+ return None
1536
+
1537
+
1538
+ _ENV_DUMP_RE = re.compile(
1539
+ r'(?:^|[\s;|&(])(?:printenv|export\s+-p|declare\s+-x|set)\s*(?:$|[;|&)>])'
1540
+ r'|(?:^|[\s;|&(])env\s*(?:$|[;|&)>])'
1541
+ r'|/proc/[^\s]*/environ'
1542
+ r'|docker\s+(?:inspect|compose\s+config)|kubectl\s+get\s+secrets?'
1543
+ r'|\$\{?[A-Z_]*(?:SECRET|TOKEN|PASSWORD|PASS|API_?KEY|PRIVATE|CREDENTIAL)[A-Z_]*')
1544
+
1545
+
1546
+ def bash_secret_targets(cmd: str, policy: Optional[Policy] = None) -> Tuple[List[str], bool]:
1547
+ """명령이 읽을 수 있는 비밀 파일 목록(실존) + 환경변수 덤프 여부. 변수 경로는 해석하지 않는다."""
1548
+ if not isinstance(cmd, str) or not cmd:
1549
+ return [], False
1550
+ if policy is None:
1551
+ policy = load_policy()
1552
+ files = []
1553
+ seen = set()
1554
+ m_cd = re.match(r'\s*cd\s+([^\s;&|]+)\s*(?:&&|;|\|)', cmd)
1555
+ base = os.path.abspath(os.path.expanduser(m_cd.group(1))) if m_cd else os.getcwd()
1556
+ cands = list(_iter_command_path_tokens(cmd))
1557
+ cands += [t for t in re.findall(r'(?<![\w$/~.\-])(\.?[\w.\-]+(?:/[\w.\-]+)*)', cmd)
1558
+ if not t.startswith(('/', '~', '-'))]
1559
+ for tok in cands:
1560
+ tok = tok.strip('\'"`')
1561
+ p = os.path.expanduser(tok)
1562
+ if not os.path.isabs(p):
1563
+ p = os.path.join(base, p)
1564
+ p = os.path.normpath(p)
1565
+ if p in seen:
1566
+ continue
1567
+ seen.add(p)
1568
+ try:
1569
+ if os.path.isfile(p) and is_secret_file(p, policy):
1570
+ files.append(p)
1571
+ except Exception:
1572
+ continue
1573
+ return files, bool(_ENV_DUMP_RE.search(cmd))
1574
+
1575
+
1576
+ def wrap_bash_for_scrub(cmd: str, files: List[str], lib_dir: str) -> str:
1577
+ """명령 출력을 scrub_stream.py 로 통과시키도록 감싼다. 종료코드는 pipefail 로 보존(bash·zsh 공통).
1578
+ 원 명령은 base64 로 실어 따옴표 문제를 없앤다. 파이프 안이라 cd 등 셸 상태는 유지되지 않는다."""
1579
+ import shlex
1580
+ b64 = base64.b64encode(cmd.encode('utf-8')).decode('ascii')
1581
+ scrub = 'python3 ' + shlex.quote(os.path.join(lib_dir, 'scrub_stream.py')) + \
1582
+ ''.join(' ' + shlex.quote(f) for f in files)
1583
+ return ("( set -o pipefail; { eval \"$(printf '%s' '" + b64 + "' | base64 --decode)\"; } 2>&1 | " + scrub + " )")
1584
+
1585
+
1586
+ def scrub_values_for(files: List[str]) -> List[str]:
1587
+ """scrub_stream 이 가릴 값: 비밀 파일에서 뽑은 값 + 이름이 비밀스러운 환경변수 값."""
1588
+ vals = set()
1589
+ for f in files:
1590
+ plain, _enc = _extract_values_from_file(f)
1591
+ vals |= set(plain)
1592
+ for k, v in os.environ.items():
1593
+ if v and len(v) >= 6 and _SECRET_ENV_NAME_RE.search(k) and not _PUBLIC_VALUE_RE.match(v):
1594
+ vals.add(v)
1595
+ return sorted(vals, key=len, reverse=True)
1596
+
1597
+
1299
1598
  def summarize_matches(matches: List[SecretMatch]) -> str:
1300
1599
  """Build a user-facing summary of detected secrets."""
1301
1600
  if not matches: