@wooojin/forgen 0.6.8 → 0.6.9

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 (221) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +17 -0
  3. package/README.ja.md +15 -10
  4. package/README.ko.md +15 -10
  5. package/README.md +19 -14
  6. package/README.zh.md +13 -8
  7. package/dist/checks/dangerous-response-pattern.d.ts +2 -1
  8. package/dist/checks/dangerous-response-pattern.js +27 -3
  9. package/dist/cli.js +133 -17
  10. package/dist/core/auto-compound-runner.js +502 -397
  11. package/dist/core/block-cli.js +7 -3
  12. package/dist/core/compound-consent.d.ts +18 -0
  13. package/dist/core/compound-consent.js +101 -6
  14. package/dist/core/compound-sweep-cli.d.ts +16 -0
  15. package/dist/core/compound-sweep-cli.js +67 -5
  16. package/dist/core/config-hooks.js +28 -10
  17. package/dist/core/correction-signals.d.ts +9 -0
  18. package/dist/core/correction-signals.js +37 -0
  19. package/dist/core/dev-cli.d.ts +1 -2
  20. package/dist/core/dev-cli.js +9 -28
  21. package/dist/core/doctor-verify.d.ts +35 -0
  22. package/dist/core/doctor-verify.js +502 -0
  23. package/dist/core/doctor.d.ts +4 -6
  24. package/dist/core/doctor.js +103 -184
  25. package/dist/core/explain-cli.js +8 -0
  26. package/dist/core/extraction-haiku.d.ts +64 -0
  27. package/dist/core/extraction-haiku.js +208 -0
  28. package/dist/core/extraction-queue.d.ts +68 -0
  29. package/dist/core/extraction-queue.js +300 -0
  30. package/dist/core/flow-status.d.ts +93 -0
  31. package/dist/core/flow-status.js +368 -0
  32. package/dist/core/harness.js +14 -42
  33. package/dist/core/inspect-cli.js +37 -13
  34. package/dist/core/lifecycle-classifier.d.ts +5 -1
  35. package/dist/core/lifecycle-classifier.js +13 -2
  36. package/dist/core/migrate-cli.d.ts +1 -1
  37. package/dist/core/migrate-cli.js +11 -11
  38. package/dist/core/migrate-tenetx.d.ts +1 -1
  39. package/dist/core/migrate-tenetx.js +2 -2
  40. package/dist/core/node-engine.d.ts +3 -0
  41. package/dist/core/node-engine.js +8 -0
  42. package/dist/core/observability-store.d.ts +15 -0
  43. package/dist/core/observability-store.js +73 -0
  44. package/dist/core/paths.d.ts +2 -0
  45. package/dist/core/paths.js +2 -0
  46. package/dist/core/rendered-rules-manifest.d.ts +7 -1
  47. package/dist/core/rendered-rules-manifest.js +45 -1
  48. package/dist/core/session-store.d.ts +13 -11
  49. package/dist/core/session-store.js +103 -119
  50. package/dist/core/settings-injector.d.ts +5 -2
  51. package/dist/core/settings-injector.js +21 -88
  52. package/dist/core/spawn.d.ts +9 -1
  53. package/dist/core/spawn.js +33 -33
  54. package/dist/core/stats-cli.d.ts +7 -0
  55. package/dist/core/stats-cli.js +66 -93
  56. package/dist/core/status-cli.d.ts +1 -1
  57. package/dist/core/status-cli.js +23 -4
  58. package/dist/core/statusline-cli.js +5 -0
  59. package/dist/core/statusline-install.d.ts +10 -2
  60. package/dist/core/statusline-install.js +27 -4
  61. package/dist/core/transcript-summary.d.ts +84 -9
  62. package/dist/core/transcript-summary.js +283 -49
  63. package/dist/core/uninstall.d.ts +4 -0
  64. package/dist/core/uninstall.js +68 -36
  65. package/dist/core/v1-bootstrap.d.ts +1 -1
  66. package/dist/core/v1-bootstrap.js +38 -9
  67. package/dist/engine/acted-on-evidence.d.ts +8 -0
  68. package/dist/engine/acted-on-evidence.js +38 -0
  69. package/dist/engine/block-judge.d.ts +3 -1
  70. package/dist/engine/block-judge.js +4 -3
  71. package/dist/engine/compound-cli.d.ts +26 -2
  72. package/dist/engine/compound-cli.js +143 -19
  73. package/dist/engine/compound-lifecycle.d.ts +36 -2
  74. package/dist/engine/compound-lifecycle.js +131 -11
  75. package/dist/engine/compound-loop.d.ts +4 -0
  76. package/dist/engine/compound-loop.js +93 -18
  77. package/dist/engine/correction-cluster-runner.d.ts +11 -1
  78. package/dist/engine/correction-cluster-runner.js +39 -15
  79. package/dist/engine/correction-clustering.d.ts +11 -0
  80. package/dist/engine/correction-clustering.js +20 -3
  81. package/dist/engine/lifecycle/lifecycle-cli.js +10 -3
  82. package/dist/engine/lifecycle/meta-reclassifier.d.ts +9 -0
  83. package/dist/engine/lifecycle/meta-reclassifier.js +15 -3
  84. package/dist/engine/lifecycle/orchestrator.js +3 -2
  85. package/dist/engine/lifecycle/signals.d.ts +19 -1
  86. package/dist/engine/lifecycle/signals.js +61 -2
  87. package/dist/engine/lifecycle/trigger-t1-correction.d.ts +1 -1
  88. package/dist/engine/lifecycle/trigger-t1-correction.js +9 -28
  89. package/dist/engine/lifecycle/trigger-t5-conflict.d.ts +8 -0
  90. package/dist/engine/lifecycle/trigger-t5-conflict.js +60 -2
  91. package/dist/engine/roi-demotion.d.ts +11 -0
  92. package/dist/engine/roi-demotion.js +50 -8
  93. package/dist/engine/rule-detectability.d.ts +39 -0
  94. package/dist/engine/rule-detectability.js +66 -0
  95. package/dist/engine/rule-project-cli.d.ts +25 -0
  96. package/dist/engine/rule-project-cli.js +148 -0
  97. package/dist/engine/rule-recovery-cli.d.ts +21 -0
  98. package/dist/engine/rule-recovery-cli.js +265 -0
  99. package/dist/engine/rule-toggle-cli.d.ts +14 -2
  100. package/dist/engine/rule-toggle-cli.js +94 -6
  101. package/dist/engine/skill-promoter.d.ts +14 -8
  102. package/dist/engine/skill-promoter.js +57 -85
  103. package/dist/engine/solution-format.d.ts +26 -1
  104. package/dist/engine/solution-format.js +65 -3
  105. package/dist/engine/solution-habit.d.ts +1 -0
  106. package/dist/engine/solution-habit.js +22 -0
  107. package/dist/engine/solution-index.d.ts +5 -0
  108. package/dist/engine/solution-index.js +32 -0
  109. package/dist/engine/solution-matcher-eval.js +4 -4
  110. package/dist/engine/solution-matcher.js +15 -13
  111. package/dist/engine/solution-scope.d.ts +11 -0
  112. package/dist/engine/solution-scope.js +19 -0
  113. package/dist/engine/solution-writer.d.ts +3 -1
  114. package/dist/engine/solution-writer.js +3 -2
  115. package/dist/engine/term-normalizer.js +49 -0
  116. package/dist/fgx.js +1 -1
  117. package/dist/forge/cli.js +51 -8
  118. package/dist/forge/evidence-processor.js +6 -0
  119. package/dist/hooks/context-guard.d.ts +0 -22
  120. package/dist/hooks/context-guard.js +22 -55
  121. package/dist/hooks/context-usage.d.ts +21 -0
  122. package/dist/hooks/context-usage.js +103 -0
  123. package/dist/hooks/dangerous-patterns.json +1 -16
  124. package/dist/hooks/db-guard.d.ts +1 -1
  125. package/dist/hooks/db-guard.js +21 -30
  126. package/dist/hooks/hook-config.d.ts +2 -0
  127. package/dist/hooks/hook-config.js +5 -1
  128. package/dist/hooks/hooks-generator.d.ts +4 -0
  129. package/dist/hooks/hooks-generator.js +10 -4
  130. package/dist/hooks/permission-handler.js +23 -3
  131. package/dist/hooks/post-tool-use.js +14 -10
  132. package/dist/hooks/pre-tool-use.d.ts +17 -3
  133. package/dist/hooks/pre-tool-use.js +143 -30
  134. package/dist/hooks/rate-limiter.js +12 -7
  135. package/dist/hooks/secret-filter.js +15 -4
  136. package/dist/hooks/session-end.d.ts +2 -2
  137. package/dist/hooks/session-end.js +13 -7
  138. package/dist/hooks/session-recovery.js +79 -50
  139. package/dist/hooks/shared/command-analyzer.d.ts +45 -0
  140. package/dist/hooks/shared/command-analyzer.js +972 -0
  141. package/dist/hooks/shared/command-parser.d.ts +5 -29
  142. package/dist/hooks/shared/command-parser.js +65 -35
  143. package/dist/hooks/shared/commit-guard.d.ts +15 -0
  144. package/dist/hooks/shared/commit-guard.js +176 -0
  145. package/dist/hooks/shared/hook-response.d.ts +6 -0
  146. package/dist/hooks/shared/hook-response.js +12 -0
  147. package/dist/hooks/shared/hook-timing.js +9 -3
  148. package/dist/hooks/shared/injection-caps.d.ts +32 -2
  149. package/dist/hooks/shared/injection-caps.js +73 -2
  150. package/dist/hooks/shared/is-main.d.ts +8 -0
  151. package/dist/hooks/shared/is-main.js +20 -0
  152. package/dist/hooks/shared/tool-response.d.ts +6 -0
  153. package/dist/hooks/shared/tool-response.js +30 -0
  154. package/dist/hooks/slop-detector.js +6 -3
  155. package/dist/hooks/solution-injector.d.ts +23 -0
  156. package/dist/hooks/solution-injector.js +102 -101
  157. package/dist/hooks/stop-guard.d.ts +11 -1
  158. package/dist/hooks/stop-guard.js +28 -11
  159. package/dist/hooks/subagent-stop-guard.js +2 -1
  160. package/dist/hooks/subagent-tracker.js +2 -1
  161. package/dist/host/capabilities-codex.js +1 -0
  162. package/dist/host/claude-shim.d.ts +24 -0
  163. package/dist/host/claude-shim.js +68 -0
  164. package/dist/host/codex-hook-shim.d.ts +3 -1
  165. package/dist/host/codex-hook-shim.js +7 -5
  166. package/dist/host/codex-notify.js +1 -1
  167. package/dist/host/codex-rules-context.d.ts +6 -4
  168. package/dist/host/codex-rules-context.js +11 -24
  169. package/dist/host/exec-host.d.ts +5 -1
  170. package/dist/host/exec-host.js +15 -4
  171. package/dist/host/install-claude.d.ts +47 -14
  172. package/dist/host/install-claude.js +302 -155
  173. package/dist/host/install-codex.d.ts +20 -0
  174. package/dist/host/install-codex.js +32 -1
  175. package/dist/host/install-opencode.d.ts +3 -1
  176. package/dist/host/install-opencode.js +6 -3
  177. package/dist/host/install-orchestrator.js +14 -1
  178. package/dist/host/opencode/translate.d.ts +1 -1
  179. package/dist/host/opencode/translate.js +5 -3
  180. package/dist/host/projection.d.ts +9 -1
  181. package/dist/host/projection.js +19 -2
  182. package/dist/mcp/server.js +5 -0
  183. package/dist/mcp/solution-reader.d.ts +5 -5
  184. package/dist/mcp/solution-reader.js +13 -35
  185. package/dist/mcp/tools.js +18 -1
  186. package/dist/renderer/inspect-renderer.js +4 -2
  187. package/dist/renderer/render-report.d.ts +22 -0
  188. package/dist/renderer/render-report.js +29 -0
  189. package/dist/renderer/rule-renderer.d.ts +28 -2
  190. package/dist/renderer/rule-renderer.js +91 -76
  191. package/dist/store/evidence-store.js +34 -6
  192. package/dist/store/rule-lifecycle.d.ts +3 -1
  193. package/dist/store/rule-lifecycle.js +10 -0
  194. package/dist/store/rule-scope.d.ts +7 -0
  195. package/dist/store/rule-scope.js +54 -0
  196. package/dist/store/rule-store.d.ts +29 -3
  197. package/dist/store/rule-store.js +110 -26
  198. package/dist/store/types.d.ts +22 -2
  199. package/dist/way/cli.d.ts +1 -0
  200. package/dist/way/cli.js +313 -0
  201. package/dist/way/compile.d.ts +22 -0
  202. package/dist/way/compile.js +408 -0
  203. package/dist/way/conflict.d.ts +2 -0
  204. package/dist/way/conflict.js +18 -0
  205. package/dist/way/draft.d.ts +43 -0
  206. package/dist/way/draft.js +335 -0
  207. package/dist/way/extract.d.ts +17 -0
  208. package/dist/way/extract.js +172 -0
  209. package/dist/way/io.d.ts +79 -0
  210. package/dist/way/io.js +425 -0
  211. package/dist/way/similar.d.ts +2 -0
  212. package/dist/way/similar.js +30 -0
  213. package/dist/way/types.d.ts +98 -0
  214. package/dist/way/types.js +2 -0
  215. package/package.json +1 -1
  216. package/plugin.json +1 -1
  217. package/scripts/postinstall.js +76 -899
  218. package/dist/core/health-cli.d.ts +0 -25
  219. package/dist/core/health-cli.js +0 -90
  220. package/dist/host/parity-harness.d.ts +0 -70
  221. package/dist/host/parity-harness.js +0 -287
@@ -0,0 +1,972 @@
1
+ /**
2
+ * Command analyzer — 셸 명령을 실제로 파싱해 "실행되는 위험 동작"만 찾는다 (D12).
3
+ *
4
+ * 정규식을 명령 문자열 전체에 대던 방식은 두 방향으로 틀렸다.
5
+ * - 미탐: `rm -r -f x`, `rm -fr`, `bash -c "rm -rf x"`, `xargs rm -rf`, `find -delete`, `shutil.rmtree` 통과.
6
+ * - 오탐: `echo pre_mkfs foo`, `grep "DROP TABLE" f`, 커밋 메시지 속 rm -rf 가 차단.
7
+ * 여기서는 따옴표·heredoc·주석·치환($(), 백틱, <())을 구분하는 토크나이저로 문장을 나눈 뒤,
8
+ * 명령어 단어(래퍼 sudo/env/nohup… 벗김)별로 의미를 해석한다. 실행 문맥(bash -c, eval, xargs, find -exec,
9
+ * python -c 안의 문자열)은 재귀 해석하고, 데이터 문맥(echo, grep, git commit -m)은 해석하지 않는다.
10
+ *
11
+ * 한계(정직하게): 외부 스크립트 파일 내용, 별칭, 난독화는 다 해석하지 못한다. 이 hook 은 사고 방지 장치이므로
12
+ * **판별할 수 없으면 통과시키지 않고 확인(ask)** 한다: 명령어 자리의 변수·치환 + 위험 인자, `| sh`, `<<<` → 셸,
13
+ * `sh -c "$(…)"`, 입력 길이·깊이·작업량 상한 초과, 분석 중 예외.
14
+ */
15
+ import { isClaudeTempPath } from './command-parser.js';
16
+ /** 입력 길이 상한 — 초과는 분석하지 않고 ask (fail-open 금지). pre-tool-use 의 정규식 경로도 같은 상한을 쓴다. */
17
+ export const MAX_COMMAND_LENGTH = 50_000;
18
+ const WORK_BUDGET = 3_000_000;
19
+ class LimitError extends Error {
20
+ }
21
+ let budget = Infinity;
22
+ function spend(n = 1) { if ((budget -= n) < 0)
23
+ throw new LimitError('work budget exceeded'); }
24
+ const MAX_DEPTH = 6;
25
+ function newStmt(sepBefore) {
26
+ return { words: [], sepBefore, heredocs: [], subs: [], procSubs: [], hereStrings: [] };
27
+ }
28
+ /** `(`·`$(` 의 짝 `)` 위치를 찾는다 (따옴표 인식). 못 찾으면 src.length. */
29
+ function matchParen(src, open) {
30
+ let depth = 0;
31
+ for (let i = open; i < src.length; i++) {
32
+ spend();
33
+ const c = src[i];
34
+ if (c === '\\') {
35
+ i++;
36
+ continue;
37
+ }
38
+ if (c === "'") {
39
+ const j = src.indexOf("'", i + 1);
40
+ if (j < 0)
41
+ return src.length;
42
+ i = j;
43
+ continue;
44
+ }
45
+ if (c === '"') {
46
+ for (i++; i < src.length && src[i] !== '"'; i++) {
47
+ spend();
48
+ if (src[i] === '\\')
49
+ i++;
50
+ }
51
+ continue;
52
+ }
53
+ if (c === '(')
54
+ depth++;
55
+ else if (c === ')') {
56
+ depth--;
57
+ if (depth === 0)
58
+ return i;
59
+ }
60
+ }
61
+ return src.length;
62
+ }
63
+ export function tokenize(src) {
64
+ const stmts = [];
65
+ let cur = newStmt('');
66
+ let buf = '';
67
+ let inWord = false;
68
+ let quoted = false;
69
+ let dyn = false;
70
+ const pending = [];
71
+ const pushWord = () => {
72
+ if (!inWord)
73
+ return;
74
+ cur.words.push({ text: buf, quoted, dynamic: dyn });
75
+ buf = '';
76
+ inWord = false;
77
+ quoted = false;
78
+ dyn = false;
79
+ };
80
+ const endStmt = (sep) => {
81
+ pushWord();
82
+ if (cur.words.length || cur.heredocs.length || pending.some((p) => p.stmt === cur))
83
+ stmts.push(cur);
84
+ cur = newStmt(sep);
85
+ };
86
+ let i = 0;
87
+ while (i < src.length) {
88
+ spend();
89
+ const c = src[i];
90
+ if (c === '\\') {
91
+ if (src[i + 1] === '\n') {
92
+ i += 2;
93
+ continue;
94
+ }
95
+ if (i + 1 < src.length) {
96
+ buf += src[i + 1];
97
+ inWord = true;
98
+ quoted = true;
99
+ }
100
+ i += 2;
101
+ continue;
102
+ }
103
+ if (c === "'") {
104
+ const j = src.indexOf("'", i + 1);
105
+ const end = j < 0 ? src.length : j;
106
+ buf += src.slice(i + 1, end);
107
+ inWord = true;
108
+ quoted = true;
109
+ i = end + 1;
110
+ continue;
111
+ }
112
+ if (c === '"') {
113
+ inWord = true;
114
+ quoted = true;
115
+ i++;
116
+ while (i < src.length && src[i] !== '"') {
117
+ spend();
118
+ const d = src[i];
119
+ if (d === '\\' && i + 1 < src.length) {
120
+ const n = src[i + 1];
121
+ buf += '$"\\`'.includes(n) ? n : `\\${n}`;
122
+ i += 2;
123
+ continue;
124
+ }
125
+ if (d === '$' && src[i + 1] === '(' && src[i + 2] !== '(') {
126
+ const e = matchParen(src, i + 1);
127
+ cur.subs.push(src.slice(i + 2, e));
128
+ buf += '$()';
129
+ dyn = true;
130
+ i = e + 1;
131
+ continue;
132
+ }
133
+ if (d === '`') {
134
+ let e = i + 1;
135
+ while (e < src.length && src[e] !== '`') {
136
+ if (src[e] === '\\')
137
+ e++;
138
+ e++;
139
+ }
140
+ cur.subs.push(src.slice(i + 1, e));
141
+ buf += '$()';
142
+ dyn = true;
143
+ i = e + 1;
144
+ continue;
145
+ }
146
+ if (d === '$')
147
+ dyn = true;
148
+ buf += d;
149
+ i++;
150
+ }
151
+ i++;
152
+ continue;
153
+ }
154
+ if (c === '$' && src[i + 1] === '(') {
155
+ if (src[i + 2] === '(') { // 산술 $(( ))
156
+ const e = src.indexOf('))', i);
157
+ buf += '$(())';
158
+ inWord = true;
159
+ dyn = true;
160
+ i = e < 0 ? src.length : e + 2;
161
+ continue;
162
+ }
163
+ const e = matchParen(src, i + 1);
164
+ cur.subs.push(src.slice(i + 2, e));
165
+ buf += '$()';
166
+ inWord = true;
167
+ dyn = true;
168
+ i = e + 1;
169
+ continue;
170
+ }
171
+ if (c === '`') {
172
+ let e = i + 1;
173
+ while (e < src.length && src[e] !== '`') {
174
+ if (src[e] === '\\')
175
+ e++;
176
+ e++;
177
+ }
178
+ cur.subs.push(src.slice(i + 1, e));
179
+ buf += '$()';
180
+ inWord = true;
181
+ dyn = true;
182
+ i = e + 1;
183
+ continue;
184
+ }
185
+ if ((c === '<' || c === '>') && src[i + 1] === '(') {
186
+ const e = matchParen(src, i + 1);
187
+ cur.procSubs.push(src.slice(i + 2, e));
188
+ buf += `${c}()`;
189
+ inWord = true;
190
+ i = e + 1;
191
+ continue;
192
+ }
193
+ if (c === '$') {
194
+ buf += c;
195
+ inWord = true;
196
+ dyn = true;
197
+ i++;
198
+ continue;
199
+ }
200
+ if (c === '#' && !inWord) {
201
+ while (i < src.length && src[i] !== '\n')
202
+ i++;
203
+ continue;
204
+ }
205
+ if (c === ' ' || c === '\t' || c === '\r') {
206
+ pushWord();
207
+ i++;
208
+ continue;
209
+ }
210
+ if (c === '\n') {
211
+ endStmt('\n');
212
+ i++;
213
+ for (const p of pending.splice(0)) {
214
+ const lines = [];
215
+ while (i < src.length) {
216
+ spend();
217
+ let e = src.indexOf('\n', i);
218
+ if (e < 0)
219
+ e = src.length;
220
+ const line = src.slice(i, e);
221
+ i = Math.min(e + 1, src.length);
222
+ if ((p.strip ? line.replace(/^\t+/, '') : line).trim() === p.delim)
223
+ break;
224
+ lines.push(line);
225
+ }
226
+ p.stmt.heredocs.push(lines.join('\n'));
227
+ }
228
+ continue;
229
+ }
230
+ if (c === '<' && src[i + 1] === '<' && src[i + 2] !== '<' && !inWord) {
231
+ let j = i + 2;
232
+ const strip = src[j] === '-';
233
+ if (strip)
234
+ j++;
235
+ while (src[j] === ' ' || src[j] === '\t')
236
+ j++;
237
+ let delim = '';
238
+ if (src[j] === "'" || src[j] === '"') {
239
+ const q = src[j];
240
+ const e = src.indexOf(q, j + 1);
241
+ delim = src.slice(j + 1, e < 0 ? src.length : e);
242
+ j = (e < 0 ? src.length : e) + 1;
243
+ }
244
+ else {
245
+ while (j < src.length && !/[\s;&|<>()]/.test(src[j])) {
246
+ delim += src[j] === '\\' ? '' : src[j];
247
+ j++;
248
+ }
249
+ }
250
+ pending.push({ delim, strip, stmt: cur });
251
+ i = j;
252
+ continue;
253
+ }
254
+ if (c === '<' && src[i + 1] === '<' && src[i + 2] === '<') {
255
+ pushWord();
256
+ cur.words.push({ text: '<<<', quoted: false, dynamic: false });
257
+ i += 3;
258
+ continue;
259
+ }
260
+ if (c === ';') {
261
+ endStmt(';');
262
+ i += src[i + 1] === ';' ? 2 : 1;
263
+ continue;
264
+ }
265
+ if (c === '&') {
266
+ if (src[i + 1] === '&') {
267
+ endStmt('&&');
268
+ i += 2;
269
+ continue;
270
+ }
271
+ if (buf.endsWith('>') || buf.endsWith('<') || src[i + 1] === '>') {
272
+ buf += c;
273
+ inWord = true;
274
+ i++;
275
+ continue;
276
+ }
277
+ endStmt('&');
278
+ i++;
279
+ continue;
280
+ }
281
+ if (c === '|') {
282
+ if (src[i + 1] === '|') {
283
+ endStmt('||');
284
+ i += 2;
285
+ continue;
286
+ }
287
+ if (buf.endsWith('>')) {
288
+ buf += c;
289
+ inWord = true;
290
+ i++;
291
+ continue;
292
+ }
293
+ endStmt('|');
294
+ i += src[i + 1] === '&' ? 2 : 1;
295
+ continue;
296
+ }
297
+ if ((c === '(' || c === ')') && !inWord) {
298
+ if (c === ')')
299
+ endStmt(';');
300
+ i++;
301
+ continue;
302
+ }
303
+ buf += c;
304
+ inWord = true;
305
+ i++;
306
+ }
307
+ endStmt('');
308
+ return stmts;
309
+ }
310
+ function expandVars(s, vars) {
311
+ return s.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (whole, a, b) => {
312
+ const v = vars.get(a ?? b);
313
+ return v === undefined ? whole : v;
314
+ });
315
+ }
316
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'ash', 'fish', 'csh', 'tcsh']);
317
+ const DB_CLIS = new Set(['psql', 'mysql', 'mariadb', 'sqlite', 'sqlite3', 'pg_restore', 'mongosh', 'mongo', 'cockroach', 'redis-cli', 'sqlcmd', 'clickhouse-client', 'duckdb', 'usql']);
318
+ const SCRIPT_EVAL = {
319
+ python: ['-c'], python2: ['-c'], python3: ['-c'], node: ['-e', '--eval', '-p'], nodejs: ['-e', '--eval'],
320
+ perl: ['-e', '-E'], ruby: ['-e'], php: ['-r'], deno: ['eval'], bun: ['-e'],
321
+ };
322
+ const REMOTE_RUNNERS = new Set(['ssh', 'docker', 'podman', 'kubectl', 'nsenter', 'chroot', 'su', 'watch', 'parallel', 'flock', 'script', 'unshare', 'systemd-run', 'nix-shell']);
323
+ const KNOWN_CMDS = new Set(['rm', 'find', 'git', 'xargs', 'dd', 'mv', 'tee', 'truncate', 'shred', 'wipefs', 'unlink', 'chmod', 'chown', 'chgrp', ...SHELLS, ...DB_CLIS]);
324
+ const FUNC_HEADER_RE = /^[A-Za-z_][\w.:-]*\(\)\{?$/;
325
+ const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{', '}', 'fi', 'done', 'esac', 'function', 'select']);
326
+ const FIND_FILTERS = /^-(i?name|i?path|i?regex|type|mtime|mmin|atime|ctime|newer|user|group|size|empty|perm|iname|maxdepth)$/;
327
+ /** 정체 불명 명령(`$X`, `$(…)`) 뒤에 오면 위험해 보이는 인자: 재귀/강제 플래그 조합, 루트·홈·시스템 경로, -delete. */
328
+ function isDangerousArgForUnknownCmd(a, home) {
329
+ if (/^-[a-zA-Z]*[rR][a-zA-Z]*[fF]|^-[a-zA-Z]*[fF][a-zA-Z]*[rR]/.test(a))
330
+ return true;
331
+ if (a === '--recursive' || a === '--force' || a === '--no-preserve-root' || a === '-delete')
332
+ return true;
333
+ const x = home && (a === '~' || a.startsWith('~/')) ? home + a.slice(1) : a;
334
+ const t = x.replace(/\/+$/, '').replace(/\/\*$/, '') || '/';
335
+ if (t === '/' || t === '~' || /^\$\{?(HOME|USERPROFILE)\}?$/.test(t) || (home && t === home))
336
+ return true;
337
+ return SYSTEM_PREFIX_RE.test(t) && !SAFE_DEVICE_RE.test(t) && !/^\/var\/(tmp|folders)(\/|$)/.test(t);
338
+ }
339
+ function baseName(p) {
340
+ const i = p.lastIndexOf('/');
341
+ return i >= 0 ? p.slice(i + 1) : p;
342
+ }
343
+ const DELETE_CODE_RE = /shutil\s*\.\s*rmtree|\bos\s*\.\s*(remove|unlink|rmdir|removedirs)\b|\.(unlink|rmdir)\s*\(|\.\s*(rmSync|rmdirSync|unlinkSync)\b|\bfs\s*\.\s*(promises\s*\.\s*)?(rm|rmdir|unlink)\b|\brimraf\b|FileUtils\s*\.\s*(rm_rf|rm_r|rm_f|remove_dir|remove_entry)|\bFile\s*\.\s*delete\b|\bunlink\s*[(\s]|\brmtree\b|remove_tree|File::Path/;
344
+ const RM_IN_CODE_RE = /\brm\s+-[a-zA-Z]*[rR]|["']rm["']\s*,\s*["']-[a-zA-Z]*[rR]|--recursive/;
345
+ const SQL_PATH_LITERAL_RE = /(["'])(\/[^"'\s]*)\1/g;
346
+ /** 쓰기가 무해한 가짜 장치. */
347
+ const SAFE_DEVICE_RE = /^\/(dev\/(null|zero|full|random|urandom|stdin|stdout|stderr|tty|fd\/\d+|pts\/\d+)|proc\/(self|\d+)\/fd\/\d+)$/;
348
+ /** 홈 아래에서 덮어쓰면 로그인·인증이 망가지는 경로. */
349
+ const HOME_CRITICAL_RE = /^(\.bashrc|\.bash_profile|\.bash_login|\.zshrc|\.zshenv|\.zprofile|\.profile|\.ssh|\.gnupg)(\/|$)/;
350
+ const SYSTEM_PREFIX_RE = /^\/(etc|usr|var|bin|sbin|lib|lib32|lib64|boot|dev|proc|sys|root|System|Library|Applications|opt\/homebrew)(\/|$)/;
351
+ function normalizeAbs(p) {
352
+ const parts = [];
353
+ for (const seg of p.split('/')) {
354
+ if (!seg || seg === '.')
355
+ continue;
356
+ if (seg === '..') {
357
+ parts.pop();
358
+ continue;
359
+ }
360
+ parts.push(seg);
361
+ }
362
+ return `/${parts.join('/')}`;
363
+ }
364
+ function classifyTargets(targets, ctx, filtered) {
365
+ const list = targets.map((t) => t.text);
366
+ if (targets.length === 0)
367
+ return { action: 'pass', reason: '', list };
368
+ let worst = 'pass';
369
+ let reason = '';
370
+ const raise = (a, r) => {
371
+ const eff = filtered && a === 'deny' ? 'ask' : a;
372
+ if (eff === 'deny' || (eff === 'ask' && worst === 'pass')) {
373
+ worst = eff;
374
+ reason = r;
375
+ }
376
+ };
377
+ const home = ctx.home.replace(/\/+$/, '');
378
+ for (const t of targets) {
379
+ let x = expandVars(t.text, ctx.vars).replace(/^["']|["']$/g, '');
380
+ if (home && (x === '~' || x.startsWith('~/')))
381
+ x = home + x.slice(1);
382
+ if (/(^|\/)\.\.(\/|$)/.test(x) && /^\/?(tmp|private\/tmp|var\/tmp|var\/folders)(\/|$)/.test(x)) {
383
+ raise('deny', 'path traversal out of a temp path');
384
+ continue;
385
+ }
386
+ if (x.startsWith('/') && /(^|\/)\.\.(\/|$)/.test(x))
387
+ x = normalizeAbs(x);
388
+ const stripped = x.replace(/\/+$/, '') || '/';
389
+ const noGlob = stripped.replace(/\/\*+$/, '') || '/';
390
+ if (x.includes('$')) {
391
+ if (/^\$\{?(HOME|USERPROFILE)\}?(\/\*?)?$/.test(x)) {
392
+ raise('deny', 'home directory');
393
+ continue;
394
+ }
395
+ raise('ask', 'unresolved target');
396
+ continue;
397
+ }
398
+ if (noGlob === '/' || x === '/*') {
399
+ raise('deny', 'filesystem root');
400
+ continue;
401
+ }
402
+ if (noGlob === home || (home && stripped === home)) {
403
+ raise('deny', 'home directory');
404
+ continue;
405
+ }
406
+ if (x === '.' || x === '..' || x === './' || x === './.' || x === '.*') {
407
+ raise('deny', 'current/parent directory');
408
+ continue;
409
+ }
410
+ if (SYSTEM_PREFIX_RE.test(noGlob) && !SAFE_DEVICE_RE.test(noGlob) && !/^\/var\/(tmp|folders)(\/|$)/.test(noGlob)) {
411
+ raise('deny', 'system directory');
412
+ continue;
413
+ }
414
+ if (home && noGlob.startsWith(`${home}/`) && HOME_CRITICAL_RE.test(noGlob.slice(home.length + 1))) {
415
+ raise('deny', 'home shell-config/credentials path');
416
+ continue;
417
+ }
418
+ if (noGlob === '/tmp' || noGlob === '/var/tmp') {
419
+ raise('ask', 'shared temp root');
420
+ continue;
421
+ }
422
+ if (/^\/[^/]+$/.test(noGlob) || /^\/(home|Users)\/[^/]+$/.test(noGlob)) {
423
+ raise('deny', 'system or home root path');
424
+ continue;
425
+ }
426
+ if (/[*?[\]{}`]/.test(x)) {
427
+ // 임시 경로 아래의 glob/치환은 isClaudeTempPath 가 보수적으로 거부 → 확인 요청
428
+ raise('ask', 'glob or substitution in target');
429
+ continue;
430
+ }
431
+ const base = ctx.cwd;
432
+ if (!isClaudeTempPath(x, base))
433
+ raise('ask', 'non-temporary path');
434
+ }
435
+ return { action: worst, reason, list };
436
+ }
437
+ function emitDelete(id, label, targets, ctx, out, filtered = false) {
438
+ if (targets.length === 0)
439
+ return;
440
+ const v = classifyTargets(targets, ctx, filtered);
441
+ if (v.action === 'pass')
442
+ return;
443
+ out.findings.push({
444
+ id, action: v.action, targets: v.list,
445
+ description: v.action === 'deny' ? `${label} on ${v.reason}` : `${label} — ${v.reason}: ${v.list.slice(0, 4).join(' ')}`,
446
+ });
447
+ }
448
+ /**
449
+ * 파괴적 쓰기/이동 계열. 시스템·홈 경로 대상은 deny. askOther 면 그 외(비임시) 경로는 ask, 아니면 통과
450
+ * (tee·리다이렉트처럼 흔한 쓰기는 위험 경로만 본다). 해석 안 되는 `$VAR` 대상은 askOther 일 때만 ask.
451
+ */
452
+ function emitWrite(id, label, targets, ctx, out, askOther) {
453
+ if (targets.length === 0)
454
+ return;
455
+ const usable = askOther ? targets : targets.filter((t) => !expandVars(t.text, ctx.vars).includes('$') && !SAFE_DEVICE_RE.test(t.text));
456
+ if (usable.length === 0)
457
+ return;
458
+ const v = classifyTargets(usable, ctx, false);
459
+ if (v.action === 'deny')
460
+ out.findings.push({ id, action: 'deny', targets: v.list, description: `${label} on ${v.reason}` });
461
+ else if (v.action === 'ask' && askOther)
462
+ out.findings.push({ id, action: 'ask', targets: v.list, description: `${label} — ${v.reason}: ${v.list.slice(0, 4).join(' ')}` });
463
+ }
464
+ function pushFinding(out, f) {
465
+ if (out.findings.length < 200 && !out.findings.some((x) => x.id === f.id && x.description === f.description))
466
+ out.findings.push(f);
467
+ }
468
+ function walk(src, ctx, out) {
469
+ if (!src.trim())
470
+ return;
471
+ if (ctx.depth > MAX_DEPTH) {
472
+ pushFinding(out, { id: 'analysis-limit', action: 'ask', description: 'command nested too deeply to analyze' });
473
+ return;
474
+ }
475
+ spend(10);
476
+ const stmts = tokenize(src);
477
+ for (let idx = 0; idx < stmts.length; idx++) {
478
+ const st = stmts[idx];
479
+ const sub = { ...ctx, depth: ctx.depth + 1 };
480
+ for (const s of st.subs)
481
+ walk(s, sub, out);
482
+ for (const s of st.procSubs) {
483
+ walk(s, sub, out);
484
+ if (/\b(curl|wget)\b/.test(s) && st.words.length && SHELLS.has(baseName(st.words[0].text))) {
485
+ out.findings.push({ id: 'pipe-to-shell', action: 'block', description: 'download piped to shell (process substitution)' });
486
+ }
487
+ }
488
+ analyzeStmt(stmts, idx, ctx, out);
489
+ }
490
+ }
491
+ function analyzeStmt(stmts, idx, ctx, out) {
492
+ const st = stmts[idx];
493
+ const words = st.words.slice();
494
+ // 리다이렉트 분리 + 장치 쓰기 탐지
495
+ const args = [];
496
+ for (let i = 0; i < words.length; i++) {
497
+ const w = words[i];
498
+ if (!w.quoted && w.text === '<<<') {
499
+ if (i + 1 < words.length) {
500
+ st.hereStrings.push(words[i + 1]);
501
+ i++;
502
+ }
503
+ continue;
504
+ }
505
+ const m = !w.quoted ? /^(?:\d*|&)(>>?|>\||<)(.*)$/.exec(w.text) : null;
506
+ if (m) {
507
+ let target = m[2];
508
+ if (!target && i + 1 < words.length) {
509
+ target = words[i + 1].text;
510
+ i++;
511
+ }
512
+ if (m[1] !== '<' && /^\/dev\/(sd[a-z]|nvme\d|hd[a-z]|vd[a-z]|mmcblk\d|disk\d)/.test(target)) {
513
+ out.findings.push({ id: 'device-write', action: 'block', description: 'write to block device' });
514
+ }
515
+ else if (m[1] !== '<' && target && !target.startsWith('&')) {
516
+ emitWrite('redirect-write', 'redirect write', [{ text: target, dynamic: false }], ctx, out, false);
517
+ }
518
+ continue;
519
+ }
520
+ if (!w.quoted && w.text === '<<') {
521
+ i++;
522
+ continue;
523
+ }
524
+ args.push(w);
525
+ }
526
+ analyzeWords(args, stmts, idx, ctx, out);
527
+ }
528
+ function isAssign(w) {
529
+ return /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(w.text);
530
+ }
531
+ function analyzeWords(wordsIn, stmts, idx, ctx, out, extraStdin = false) {
532
+ if (ctx.depth > MAX_DEPTH) {
533
+ pushFinding(out, { id: 'analysis-limit', action: 'ask', description: 'command nested too deeply to analyze' });
534
+ return;
535
+ }
536
+ const st = stmts ? stmts[idx] : null;
537
+ const words = wordsIn.slice();
538
+ // 선행 대입
539
+ const assigned = [];
540
+ while (words.length && isAssign(words[0])) {
541
+ const m = isAssign(words[0]);
542
+ assigned.push([m[1], expandVars(m[2], ctx.vars)]);
543
+ words.shift();
544
+ }
545
+ if (words.length === 0) {
546
+ for (const [k, v] of assigned)
547
+ ctx.vars.set(k, v);
548
+ return;
549
+ }
550
+ // 제어 키워드·래퍼 벗기기
551
+ for (let guard = 0; guard < 12 && words.length; guard++) {
552
+ // 명령어 자리 변수가 같은 명령 앞에서 대입된 값이면 치환해서 계속 해석 (`X=rm; $X -rf y`)
553
+ if (words[0].dynamic && /^\$\{?[A-Za-z_]/.test(words[0].text)) {
554
+ const ex = expandVars(words[0].text, ctx.vars);
555
+ if (ex !== words[0].text && !ex.includes('$')) {
556
+ words.splice(0, 1, ...ex.split(/\s+/).filter(Boolean).map((t) => ({ text: t, quoted: false, dynamic: false })));
557
+ if (!words.length)
558
+ return;
559
+ }
560
+ }
561
+ const w0 = words[0].text;
562
+ const b = baseName(w0);
563
+ if (FUNC_HEADER_RE.test(w0)) {
564
+ words.shift();
565
+ continue;
566
+ } // `f(){ …` / `f() { …` — 본문을 분석한다
567
+ if (w0 === 'function') {
568
+ words.shift();
569
+ words.shift();
570
+ continue;
571
+ }
572
+ if (KEYWORDS.has(w0)) {
573
+ words.shift();
574
+ continue;
575
+ }
576
+ if (b === 'sudo' || b === 'doas') {
577
+ words.shift();
578
+ while (words.length && words[0].text.startsWith('-')) {
579
+ const o = words.shift().text;
580
+ if (/^-[ughpCDRTU]$/.test(o) && words.length)
581
+ words.shift();
582
+ }
583
+ continue;
584
+ }
585
+ if (b === 'env') {
586
+ words.shift();
587
+ while (words.length && (words[0].text.startsWith('-') || isAssign(words[0]))) {
588
+ const o = words.shift().text;
589
+ if ((o === '-u' || o === '-C' || o === '-S') && words.length)
590
+ words.shift();
591
+ }
592
+ continue;
593
+ }
594
+ if (b === 'command' || b === 'builtin' || b === 'exec' || b === 'nohup' || b === 'time' || b === 'setsid' || b === 'stdbuf' || b === 'unbuffer' || b === 'busybox') {
595
+ words.shift();
596
+ while (words.length && words[0].text.startsWith('-'))
597
+ words.shift();
598
+ continue;
599
+ }
600
+ if (b === 'nice' || b === 'ionice') {
601
+ words.shift();
602
+ while (words.length && words[0].text.startsWith('-')) {
603
+ const o = words.shift().text;
604
+ if ((o === '-n' || o === '-c') && words.length)
605
+ words.shift();
606
+ }
607
+ continue;
608
+ }
609
+ if (b === 'timeout') {
610
+ words.shift();
611
+ while (words.length && words[0].text.startsWith('-')) {
612
+ const o = words.shift().text;
613
+ if ((o === '-s' || o === '-k') && words.length)
614
+ words.shift();
615
+ }
616
+ if (words.length)
617
+ words.shift(); // duration
618
+ continue;
619
+ }
620
+ break;
621
+ }
622
+ if (words.length === 0)
623
+ return;
624
+ const cmd = baseName(words[0].text);
625
+ const rest = words.slice(1);
626
+ const restText = rest.map((w) => w.text);
627
+ const sub = { ...ctx, depth: ctx.depth + 1 };
628
+ // 명령어 자리가 해석 안 되는 변수·치환이면 무엇을 실행하는지 알 수 없다 → 위험 인자가 함께 올 때만 ask
629
+ // (`$HOME/bin/tool --flag`, `npm run $SCRIPT` 같은 정상 사용은 건드리지 않는다).
630
+ if (words[0].dynamic && /^\$/.test(words[0].text) && words[0].text.includes('$')) {
631
+ if (rest.some((w) => isDangerousArgForUnknownCmd(expandVars(w.text, ctx.vars), ctx.home))) {
632
+ pushFinding(out, { id: 'dynamic-command', action: 'ask', description: `command name is a variable/substitution (${words[0].text}) with destructive-looking arguments: ${restText.slice(0, 4).join(' ')}` });
633
+ }
634
+ return;
635
+ }
636
+ if (cmd === 'cd') {
637
+ const d = rest.find((w) => !w.text.startsWith('-'));
638
+ if (d && !d.dynamic) {
639
+ const x = expandVars(d.text, ctx.vars);
640
+ ctx.cwd = x.startsWith('/') ? x : ctx.cwd ? `${ctx.cwd}/${x}` : '';
641
+ }
642
+ else
643
+ ctx.cwd = '';
644
+ return;
645
+ }
646
+ if (cmd === 'rm') {
647
+ let recursive = false;
648
+ let afterDD = false;
649
+ const targets = [];
650
+ for (const w of rest) {
651
+ if (!afterDD && w.text === '--') {
652
+ afterDD = true;
653
+ continue;
654
+ }
655
+ if (!afterDD && w.text.startsWith('--')) {
656
+ if (w.text === '--recursive')
657
+ recursive = true;
658
+ continue;
659
+ }
660
+ if (!afterDD && w.text.startsWith('-') && w.text.length > 1) {
661
+ if (/[rR]/.test(w.text))
662
+ recursive = true;
663
+ continue;
664
+ }
665
+ targets.push({ text: w.text, dynamic: w.dynamic });
666
+ }
667
+ if (extraStdin)
668
+ targets.push({ text: '<stdin>', dynamic: true });
669
+ if (recursive)
670
+ emitDelete('rm-recursive', 'recursive rm', targets, ctx, out);
671
+ return;
672
+ }
673
+ if (SHELLS.has(cmd)) {
674
+ let script = null;
675
+ let scriptWord = null;
676
+ for (let i = 0; i < rest.length; i++) {
677
+ const t = rest[i].text;
678
+ if (/^-[a-zA-Z]*c[a-zA-Z]*$/.test(t) && i + 1 < rest.length) {
679
+ scriptWord = rest[i + 1];
680
+ script = scriptWord.text;
681
+ break;
682
+ }
683
+ }
684
+ if (script !== null) {
685
+ const ex = expandVars(script, ctx.vars);
686
+ // `sh -c "$(curl …)"`, `bash -c "$CMD"` — 스크립트 본문이 통째로 동적이면 무엇을 실행하는지 알 수 없다
687
+ if (scriptWord.dynamic && /^\s*\$/.test(ex)) {
688
+ pushFinding(out, { id: 'dynamic-shell-script', action: 'ask', description: `${cmd} -c with a script that is only known at run time (${script.slice(0, 40)})` });
689
+ }
690
+ else
691
+ walk(ex, sub, out);
692
+ return;
693
+ }
694
+ if (st) {
695
+ for (const h of st.heredocs)
696
+ walk(h, sub, out);
697
+ for (const hs of st.hereStrings) {
698
+ if (hs.dynamic)
699
+ pushFinding(out, { id: 'dynamic-here-string', action: 'ask', description: `here-string with run-time content fed to ${cmd}` });
700
+ else
701
+ walk(hs.text, sub, out);
702
+ }
703
+ // 파이프로 흘러드는 입력(echo "…" | bash, curl … | sh) — 이 쉘이 stdin 을 스크립트로 읽을 때만
704
+ const readsStdin = rest.every((w) => w.text.startsWith('-')) || rest.some((w) => w.text === '-s');
705
+ if (st.sepBefore === '|' && idx > 0 && stmts) {
706
+ const prev = stmts[idx - 1];
707
+ const pc = prev.words.length ? baseName(prev.words[0].text) : '';
708
+ if (pc === 'curl' || pc === 'wget') {
709
+ out.findings.push({ id: 'pipe-to-shell', action: 'block', description: `${pc} piped to shell` });
710
+ }
711
+ else if (readsStdin) {
712
+ const pargs = prev.words.slice(1);
713
+ if (pc === 'echo' || pc === 'printf') {
714
+ if (pargs.some((w) => w.dynamic) || prev.subs.length)
715
+ pushFinding(out, { id: 'pipe-to-shell', action: 'ask', description: `run-time generated text piped to ${cmd}` });
716
+ else
717
+ walk([pargs.map((w) => w.text).join(' '), ...prev.heredocs].join('\n'), sub, out);
718
+ }
719
+ else if (pc === 'cat' && prev.heredocs.length && !pargs.some((w) => !w.text.startsWith('-'))) {
720
+ for (const h of prev.heredocs)
721
+ walk(h, sub, out);
722
+ }
723
+ else {
724
+ pushFinding(out, { id: 'pipe-to-shell', action: 'ask', description: `output of ${pc || 'a command'} piped to ${cmd} — cannot tell what will run` });
725
+ }
726
+ }
727
+ }
728
+ }
729
+ return;
730
+ }
731
+ if (cmd === 'eval') {
732
+ out.findings.push({ id: 'eval-string', action: 'warn', description: 'eval with string (injection risk)' });
733
+ walk(restText.join(' '), sub, out);
734
+ return;
735
+ }
736
+ if (cmd === 'xargs') {
737
+ let i = 0;
738
+ while (i < rest.length && rest[i].text.startsWith('-')) {
739
+ const o = rest[i].text;
740
+ i += /^-[ILnPsdEaJRS]$/.test(o) ? 2 : 1;
741
+ }
742
+ if (i < rest.length)
743
+ analyzeWords(rest.slice(i), null, 0, sub, out, true);
744
+ return;
745
+ }
746
+ if (cmd === 'find') {
747
+ const roots = [];
748
+ let i = 0;
749
+ while (i < rest.length && !/^(-|\(|!)/.test(rest[i].text)) {
750
+ roots.push({ text: rest[i].text, dynamic: rest[i].dynamic });
751
+ i++;
752
+ }
753
+ if (roots.length === 0)
754
+ roots.push({ text: '.', dynamic: false });
755
+ const filtered = rest.some((w) => FIND_FILTERS.test(w.text));
756
+ for (; i < rest.length; i++) {
757
+ const t = rest[i].text;
758
+ if (t === '-delete')
759
+ emitDelete('find-delete', 'find -delete', roots, ctx, out, filtered);
760
+ if (/^-(exec|execdir|ok|okdir)$/.test(t)) {
761
+ const inner = [];
762
+ let j = i + 1;
763
+ for (; j < rest.length && rest[j].text !== ';' && rest[j].text !== '+'; j++) {
764
+ if (rest[j].text === '{}')
765
+ inner.push(...roots.map((r) => ({ text: r.text, quoted: false, dynamic: r.dynamic })));
766
+ else
767
+ inner.push(rest[j]);
768
+ }
769
+ if (inner.length && baseName(inner[0].text) === 'rm') {
770
+ // find -exec rm 은 (플래그 없어도) 트리 아래를 지운다 → 재귀 삭제와 동일 취급
771
+ const targets = inner.slice(1).filter((w) => !w.text.startsWith('-')).map((w) => ({ text: w.text, dynamic: w.dynamic }));
772
+ emitDelete('find-exec-rm', 'find -exec rm', targets, ctx, out, filtered);
773
+ }
774
+ else if (inner.length) {
775
+ analyzeWords(inner, null, 0, sub, out);
776
+ }
777
+ i = j;
778
+ }
779
+ }
780
+ return;
781
+ }
782
+ if (cmd === 'git') {
783
+ let i = 0;
784
+ while (i < rest.length && rest[i].text.startsWith('-')) {
785
+ i += /^(-C|-c|--git-dir|--work-tree|--namespace|--exec-path)$/.test(rest[i].text) ? 2 : 1;
786
+ }
787
+ const sc = rest[i]?.text;
788
+ const flags = restText.slice(i + 1);
789
+ if (sc) {
790
+ const cIdx = rest.slice(0, i).findIndex((w) => w.text === '-C');
791
+ out.gitOps.push({ sub: sc, args: flags, cwd: ctx.cwd, ...(cIdx >= 0 && rest[cIdx + 1] ? { dir: rest[cIdx + 1].text } : {}) });
792
+ }
793
+ const short = flags.filter((f) => /^-[a-zA-Z]+$/.test(f)).join('');
794
+ if (sc === 'reset' && flags.includes('--hard'))
795
+ out.findings.push({ id: 'git-reset-hard', action: 'warn', description: 'git reset --hard' });
796
+ if (sc === 'clean' && (/f/.test(short) || flags.includes('--force')) && !(/n/.test(short) || flags.includes('--dry-run'))) {
797
+ out.findings.push({ id: 'git-clean', action: 'warn', description: 'git clean -f' });
798
+ }
799
+ if (sc === 'push') {
800
+ const plusRef = flags.some((f) => /^\+[^\s+]/.test(f));
801
+ if (flags.includes('--force') || /f/.test(short) || plusRef) {
802
+ out.findings.push({ id: 'git-force-push', action: 'ask', description: `git push ${plusRef ? '+refspec' : '--force'} (rewrites remote history)` });
803
+ }
804
+ else if (flags.some((f) => f === '--mirror' || f === '--delete' || f === '-d')) {
805
+ out.findings.push({ id: 'git-force-push', action: 'ask', description: `git push ${flags.find((f) => f === '--mirror' || f === '--delete' || f === '-d')} (deletes/overwrites remote refs)` });
806
+ }
807
+ }
808
+ return;
809
+ }
810
+ if (cmd === 'mkfs' || cmd.startsWith('mkfs.') || cmd === 'mke2fs') {
811
+ out.findings.push({ id: 'mkfs', action: 'block', description: 'mkfs (format filesystem)' });
812
+ return;
813
+ }
814
+ if (cmd === 'dd') {
815
+ if (restText.some((t) => /^of=\/dev\//.test(t)))
816
+ out.findings.push({ id: 'dd-device', action: 'block', description: 'dd write to device' });
817
+ return;
818
+ }
819
+ if (cmd === 'chmod' || cmd === 'chown' || cmd === 'chgrp') {
820
+ const recursiveOwn = rest.some((w) => w.text === '--recursive' || /^-[a-zA-Z]*R[a-zA-Z]*$/.test(w.text));
821
+ const nonFlag = rest.filter((w) => !w.text.startsWith('-'));
822
+ if (recursiveOwn && nonFlag.length >= 2) {
823
+ emitWrite('recursive-perm-change', `recursive ${cmd}`, nonFlag.slice(1).filter((w) => !/^\.{1,2}\/?$/.test(w.text)).map((w) => ({ text: w.text, dynamic: w.dynamic })), ctx, out, false);
824
+ }
825
+ if (cmd === 'chmod' && restText.some((t) => /^[0-7]*777$/.test(t) || t === 'a+rwx' || t === 'ugo+rwx')) {
826
+ out.findings.push({ id: 'chmod-777', action: 'warn', description: 'chmod 777 (overly permissive)' });
827
+ }
828
+ return;
829
+ }
830
+ if (cmd === 'mv') {
831
+ const nf = rest.filter((w) => !w.text.startsWith('-'));
832
+ if (nf.length >= 2) {
833
+ const dest = nf[nf.length - 1];
834
+ emitWrite('mv-system', 'mv source', nf.slice(0, -1).map((w) => ({ text: w.text, dynamic: w.dynamic })), ctx, out, false);
835
+ const dv = classifyTargets([{ text: dest.text, dynamic: dest.dynamic }].filter((t) => !expandVars(t.text, ctx.vars).includes('$')), ctx, false);
836
+ if (dv.action === 'deny')
837
+ out.findings.push({ id: 'mv-system', action: 'ask', targets: dv.list, description: `mv destination is ${dv.reason}: ${dv.list.join(' ')}` });
838
+ }
839
+ return;
840
+ }
841
+ if (cmd === 'tee') {
842
+ emitWrite('tee-system', 'tee write', rest.filter((w) => !w.text.startsWith('-')).map((w) => ({ text: w.text, dynamic: w.dynamic })), ctx, out, false);
843
+ return;
844
+ }
845
+ if (cmd === 'truncate' || cmd === 'shred' || cmd === 'unlink' || cmd === 'wipefs') {
846
+ const targets = [];
847
+ for (let i = 0; i < rest.length; i++) {
848
+ const t = rest[i].text;
849
+ if (t.startsWith('-')) {
850
+ if (/^(-s|-r|-n|-t|-o|--size|--reference|--iterations|--types|--offset)$/.test(t))
851
+ i++;
852
+ continue;
853
+ }
854
+ targets.push({ text: t, dynamic: rest[i].dynamic });
855
+ }
856
+ emitWrite(`${cmd}-target`, cmd, targets, ctx, out, true);
857
+ return;
858
+ }
859
+ // 따옴표 없는 맨 SQL 문장(`DROP TABLE users` 직접 입력)도 SQL 로 취급
860
+ if (!words[0].quoted && /^(drop|truncate|delete|alter|update|insert|create)$/i.test(words[0].text)) {
861
+ out.sqlTexts.push(words.map((w) => w.text).join(' '));
862
+ return;
863
+ }
864
+ if (DB_CLIS.has(cmd)) {
865
+ collectSql(rest, st, stmts, idx, out);
866
+ return;
867
+ }
868
+ const evalFlags = SCRIPT_EVAL[cmd.replace(/^(python|ruby|perl)[\d.]+$/, '$1')];
869
+ if (evalFlags) {
870
+ for (let i = 0; i < rest.length - 1; i++) {
871
+ const t = rest[i].text;
872
+ const clustered = /^-[a-zA-Z]{2,}$/.test(t) && evalFlags.some((f) => f.length === 2 && t.endsWith(f[1]));
873
+ if (evalFlags.includes(t) || clustered) {
874
+ analyzeCode(rest[i + 1].text, ctx, out);
875
+ break;
876
+ }
877
+ }
878
+ return;
879
+ }
880
+ if (REMOTE_RUNNERS.has(cmd)) {
881
+ for (const w of rest)
882
+ if (/\s/.test(w.text))
883
+ walk(w.text, sub, out);
884
+ for (let i = 0; i < rest.length; i++) {
885
+ const b = baseName(rest[i].text);
886
+ if (KNOWN_CMDS.has(b)) {
887
+ analyzeWords(rest.slice(i), null, 0, sub, out);
888
+ break;
889
+ }
890
+ }
891
+ return;
892
+ }
893
+ void st;
894
+ }
895
+ function collectSql(rest, st, stmts, idx, out) {
896
+ out.sqlTexts.push(rest.map((w) => w.text).join(' '));
897
+ if (st) {
898
+ for (const h of st.heredocs)
899
+ out.sqlTexts.push(h);
900
+ for (const hs of st.hereStrings)
901
+ out.sqlTexts.push(hs.text);
902
+ }
903
+ // echo "DROP TABLE x" | psql
904
+ if (st && stmts) {
905
+ let k = idx;
906
+ while (k > 0 && stmts[k].sepBefore === '|') {
907
+ const prev = stmts[k - 1];
908
+ const pc = prev.words.length ? baseName(prev.words[0].text) : '';
909
+ if (pc === 'echo' || pc === 'printf' || pc === 'cat') {
910
+ out.sqlTexts.push([...prev.words.slice(1).map((w) => w.text), ...prev.heredocs].join(' '));
911
+ }
912
+ k--;
913
+ }
914
+ }
915
+ }
916
+ /** python -c / node -e 등 인라인 코드: 삭제 API, 문자열 속 셸 명령, SQL 을 본다. */
917
+ function analyzeCode(code, ctx, out) {
918
+ out.sqlTexts.push(code);
919
+ const sub = { ...ctx, depth: ctx.depth + 1 };
920
+ const before = out.findings.length;
921
+ // 문자열 리터럴 속 셸 명령 (os.system("rm -rf x"), execSync('rm -rf x'))
922
+ const executes = /\b(system|popen|subprocess|exec\w*|spawn\w*|check_output|check_call|Popen|run|shell_exec|passthru|eval)\b|`/.test(code);
923
+ if (executes)
924
+ for (const m of code.matchAll(/(["'])((?:\\.|(?!\1).)*)\1/gs)) {
925
+ if (/\s/.test(m[2]) && /\b(rm|find|git|mkfs|dd|curl|wget)\b/.test(m[2]))
926
+ walk(m[2], sub, out);
927
+ }
928
+ if (out.findings.length === before && (DELETE_CODE_RE.test(code) || (executes && RM_IN_CODE_RE.test(code)))) {
929
+ const paths = [...code.matchAll(SQL_PATH_LITERAL_RE)].map((m) => m[2]);
930
+ const allTemp = paths.length > 0 && paths.every((p) => isClaudeTempPath(p, ctx.cwd));
931
+ if (!allTemp) {
932
+ const fatal = paths.find((p) => { const v = classifyTargets([{ text: p, dynamic: false }], ctx, false); return v.action === 'deny' && (v.reason === 'filesystem root' || v.reason === 'home directory'); });
933
+ out.findings.push(fatal
934
+ ? { id: 'script-delete', action: 'deny', description: `file deletion via inline script on ${fatal === '/' ? 'filesystem root' : 'root/home path'} (${fatal})`, targets: paths }
935
+ : { id: 'script-delete', action: 'ask', description: 'file deletion via inline script (shutil.rmtree/os.remove/fs.rm …)', targets: paths });
936
+ }
937
+ }
938
+ if (/import\s+os|subprocess|\bexec\b|\beval\b/.test(code)) {
939
+ out.findings.push({ id: 'script-dangerous-import', action: 'warn', description: 'python -c with dangerous imports' });
940
+ }
941
+ }
942
+ export function analyzeCommand(cmd, opts = {}) {
943
+ const out = { findings: [], gitOps: [], sqlTexts: [] };
944
+ if (!cmd)
945
+ return out;
946
+ if (cmd.length > MAX_COMMAND_LENGTH) {
947
+ out.findings.push({ id: 'analysis-limit', action: 'ask', description: `command too long to analyze (${cmd.length} > ${MAX_COMMAND_LENGTH} chars)` });
948
+ return out;
949
+ }
950
+ const home = opts.home ?? process.env.HOME ?? '';
951
+ const vars = new Map([['TMPDIR', process.env.TMPDIR?.replace(/\/+$/, '') || '/tmp']]);
952
+ if (home) {
953
+ vars.set('HOME', home);
954
+ }
955
+ const ctx = { vars, cwd: opts.cwd?.startsWith('/') ? opts.cwd : '', home, depth: 0 };
956
+ budget = WORK_BUDGET;
957
+ try {
958
+ walk(cmd, ctx, out);
959
+ }
960
+ catch (e) {
961
+ // 판별 불가는 통과가 아니라 확인(ask) — 분석이 터지거나 작업량 상한을 넘으면 사람이 본다.
962
+ pushFinding(out, { id: 'analysis-limit', action: 'ask', description: e instanceof LimitError ? 'command too complex to analyze safely' : 'command analysis failed — cannot verify safety' });
963
+ }
964
+ finally {
965
+ budget = Infinity;
966
+ }
967
+ return out;
968
+ }
969
+ const RANK = { block: 3, deny: 3, ask: 2, warn: 1 };
970
+ export function worstFinding(findings) {
971
+ return findings.slice().sort((a, b) => RANK[b.action] - RANK[a.action])[0];
972
+ }