@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
@@ -1,32 +1,3 @@
1
- /**
2
- * Command-token parser — quote-aware shell command preprocessing.
3
- *
4
- * 목적: PreToolUse enforce_via 룰의 정규식이 quote된 인자 텍스트와
5
- * 명령 토큰을 구분 못 해서 false positive block 발생 (TEST-6, RC5).
6
- *
7
- * 사례: forgen compound --solution "title" "본문에 rm -rf 텍스트 포함" 명령이
8
- * "rm\s+-rf" 패턴에 매칭되어 차단됨. 실제 rm 명령이 아닌데도.
9
- *
10
- * 해법: quote된 문자열을 마스킹한 뒤 패턴 매칭. 99% 케이스 커버.
11
- * 완벽한 shell 파싱은 아니지만 정직하게 한정된 범위.
12
- */
13
- /**
14
- * Mask quoted string contents in a shell command so that text inside
15
- * single/double quotes, backticks, or $(...) is not matched by patterns
16
- * intended for command tokens.
17
- *
18
- * Examples:
19
- * maskQuotedContent('rm -rf /') → 'rm -rf /'
20
- * maskQuotedContent('echo "rm -rf foo"') → 'echo ""'
21
- * maskQuotedContent("forgen save 'rm -rf body'") → "forgen save ''"
22
- * maskQuotedContent('rm -rf $(pwd)') → 'rm -rf $()'
23
- * maskQuotedContent('echo `rm -rf x`') → 'echo ``'
24
- *
25
- * Limitations (documented, not silently broken):
26
- * - escaped quotes inside quoted strings: best-effort only
27
- * - heredoc bodies (<<EOF ... EOF): masked as `<<HEREDOC>>` (v0.4.1+)
28
- * - nested $(...) / `...`: outer level masked
29
- */
30
1
  export declare function maskQuotedContent(cmd: string): string;
31
2
  /**
32
3
  * Decide if a verifier should match against the raw command, masked command,
@@ -51,5 +22,10 @@ export declare function preprocessForMatch(cmd: string, target: MatchTarget | un
51
22
  * 디렉터리 자체, 실존 경로의 realpath 가 임시 루트 밖(symlink 탈출). 빈 대상·rm 없음도 false.
52
23
  */
53
24
  export declare function isTempOnlyRm(cmd: string, cwd?: string): boolean;
25
+ /**
26
+ * 단일 삭제 대상(변수 치환 끝난 문자열)이 Claude 임시 루트 **하위**인지. `..`/glob/brace/백틱/`$()`/미해석 변수/
27
+ * 루트 자체/symlink 탈출이면 false (보수적). 상대 경로는 base(cwd)로 해석, base 모르면 false.
28
+ */
29
+ export declare function isClaudeTempPath(t: string, base: string): boolean;
54
30
  /** `..`·glob·brace 가 섞인 재귀 삭제 — 빌트인 /tmp 예외를 우회하려는 모양. 호출자가 차단에 쓴다. */
55
31
  export declare function isSuspiciousRm(cmd: string): boolean;
@@ -28,6 +28,22 @@ import * as fs from 'node:fs';
28
28
  * - heredoc bodies (<<EOF ... EOF): masked as `<<HEREDOC>>` (v0.4.1+)
29
29
  * - nested $(...) / `...`: outer level masked
30
30
  */
31
+ /** `$(...)` → `$()` (닫는 `)` 가 없으면 그대로). 정규식 `\$\([^)]*\)` 는 `$(` 가 많고 `)` 가 없을 때 이차 시간이라 선형으로 다시 썼다. */
32
+ function maskCommandSubstitutions(src) {
33
+ let out = '';
34
+ let i = 0;
35
+ while (i < src.length) {
36
+ const open = src.indexOf('$(', i);
37
+ if (open < 0)
38
+ break;
39
+ const close = src.indexOf(')', open + 2);
40
+ if (close < 0)
41
+ break;
42
+ out += `${src.slice(i, open)}$()`;
43
+ i = close + 1;
44
+ }
45
+ return out + src.slice(i);
46
+ }
31
47
  export function maskQuotedContent(cmd) {
32
48
  if (!cmd)
33
49
  return cmd;
@@ -36,9 +52,12 @@ export function maskQuotedContent(cmd) {
36
52
  // 처럼 heredoc 본문이 command string 에 포함돼 false-positive block 발생.
37
53
  // 지원 형식: <<EOF / <<'EOF' / <<"EOF" / <<-EOF (indent 무시 변종).
38
54
  // <<-MARK 은 indent 허용 (terminator 앞 whitespace). `\n\s*\2` 로 반영.
39
- out = out.replace(/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[\s\S]*?\n\s*\2\b/g, '<<HEREDOC>>');
55
+ // 성능: `<<` 가 많은 입력에서 종결자 없는 lazy 매칭이 이차 시간이 된다 → 개수 상한(초과 시 마스킹 생략 = 더 많이 잡는 쪽).
56
+ if ((out.match(/<</g)?.length ?? 0) <= 100) {
57
+ out = out.replace(/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[\s\S]*?\n\s*\2\b/g, '<<HEREDOC>>');
58
+ }
40
59
  // Order matters: command substitution before plain quotes (they may contain quotes themselves).
41
- out = out.replace(/\$\([^)]*\)/g, '$()');
60
+ out = maskCommandSubstitutions(out);
42
61
  out = out.replace(/`[^`]*`/g, '``');
43
62
  out = out.replace(/'[^']*'/g, "''");
44
63
  out = out.replace(/"[^"]*"/g, '""');
@@ -54,7 +73,8 @@ export function preprocessForMatch(cmd, target) {
54
73
  * `/tmp/claude-*` (Claude Code scratchpad) 와 `$TMPDIR/claude-*` 로 좁힌다 (critic D1: `/tmp/*` 전체는 너무 넓다).
55
74
  */
56
75
  function tempRoots() {
57
- const roots = ['/tmp/claude-', '/private/tmp/claude-', '/var/tmp/claude-', '/var/folders/'];
76
+ // macOS 의 /tmp·/var 는 /private 아래로 가는 링크다. 아래 symlink 탈출 검사가 realpath 로 판정하므로 양쪽 다 필요하다.
77
+ const roots = ['/tmp/claude-', '/private/tmp/claude-', '/var/tmp/claude-', '/private/var/tmp/claude-', '/var/folders/', '/private/var/folders/'];
58
78
  const t = process.env.TMPDIR?.replace(/\/+$/, '');
59
79
  if (t && t !== '/tmp')
60
80
  roots.push(`${t}/claude-`);
@@ -98,42 +118,52 @@ export function isTempOnlyRm(cmd, cwd) {
98
118
  for (const raw of targets) {
99
119
  found = true;
100
120
  const t = expand(raw.replace(/^["']|["']$/g, ''), vars);
101
- if (t.includes('$'))
102
- return false; // 미해석 변수
103
- if (UNSAFE_TARGET_RE.test(t))
104
- return false; // `..`, glob, brace, 백틱, $(), ~
105
- let abs = t;
106
- if (!abs.startsWith('/')) {
107
- if (!base)
108
- return false; // 상대 경로인데 cwd 를 모름
109
- abs = `${base}/${t === '.' ? '' : t}`;
110
- }
111
- abs = normalizePosix(abs);
112
- if (!roots.some((r) => abs.startsWith(r)))
113
- return false;
114
- // 루트 디렉터리 자체(/tmp/claude-1001 등)는 제외 — 하위만
115
- if (!roots.some((r) => abs.length > r.length && abs.slice(r.length).includes('/')))
116
- return false;
117
- // symlink 탈출: 가장 깊은 **실존 조상**의 realpath 에 나머지(미존재) 경로를 다시 붙인 결과가 임시 루트 아래여야
118
- // 한다. (CI 처럼 /tmp/claude-* 가 아직 없으면 조상은 /tmp 이고, /tmp 의 realpath(+나머지)로 판정 — v0.6.0 의
119
- // 릴리스 CI 가 바로 이 경우에 false 를 내 실패했다.)
120
- try {
121
- let probe = abs;
122
- while (probe !== '/' && !fs.existsSync(probe))
123
- probe = probe.slice(0, probe.lastIndexOf('/')) || '/';
124
- if (probe !== '/') {
125
- const realAbs = fs.realpathSync(probe) + abs.slice(probe.length);
126
- if (!roots.some((r) => realAbs.startsWith(r)))
127
- return false;
128
- }
129
- }
130
- catch {
121
+ if (!isClaudeTempPath(t, base))
131
122
  return false;
132
- }
133
123
  }
134
124
  }
135
125
  return found;
136
126
  }
127
+ /**
128
+ * 단일 삭제 대상(변수 치환 끝난 문자열)이 Claude 임시 루트 **하위**인지. `..`/glob/brace/백틱/`$()`/미해석 변수/
129
+ * 루트 자체/symlink 탈출이면 false (보수적). 상대 경로는 base(cwd)로 해석, base 모르면 false.
130
+ */
131
+ export function isClaudeTempPath(t, base) {
132
+ const roots = tempRoots();
133
+ if (t.includes('$'))
134
+ return false; // 미해석 변수
135
+ if (UNSAFE_TARGET_RE.test(t))
136
+ return false; // `..`, glob, brace, 백틱, $(), ~
137
+ let abs = t;
138
+ if (!abs.startsWith('/')) {
139
+ if (!base)
140
+ return false; // 상대 경로인데 cwd 를 모름
141
+ abs = `${base}/${t === '.' ? '' : t}`;
142
+ }
143
+ abs = normalizePosix(abs);
144
+ if (!roots.some((r) => abs.startsWith(r)))
145
+ return false;
146
+ // 루트 디렉터리 자체(/tmp/claude-1001 등)는 제외 — 하위만
147
+ if (!roots.some((r) => abs.length > r.length && abs.slice(r.length).includes('/')))
148
+ return false;
149
+ // symlink 탈출: 가장 깊은 **실존 조상**의 realpath 에 나머지(미존재) 경로를 다시 붙인 결과가 임시 루트 아래여야
150
+ // 한다. (CI 처럼 /tmp/claude-* 가 아직 없으면 조상은 /tmp 이고, /tmp 의 realpath(+나머지)로 판정 — v0.6.0 의
151
+ // 릴리스 CI 가 바로 이 경우에 false 를 내 실패했다.)
152
+ try {
153
+ let probe = abs;
154
+ while (probe !== '/' && !fs.existsSync(probe))
155
+ probe = probe.slice(0, probe.lastIndexOf('/')) || '/';
156
+ if (probe !== '/') {
157
+ const realAbs = fs.realpathSync(probe) + abs.slice(probe.length);
158
+ if (!roots.some((r) => realAbs.startsWith(r)))
159
+ return false;
160
+ }
161
+ }
162
+ catch {
163
+ return false;
164
+ }
165
+ return true;
166
+ }
137
167
  /** `..`·glob·brace 가 섞인 재귀 삭제 — 빌트인 /tmp 예외를 우회하려는 모양. 호출자가 차단에 쓴다. */
138
168
  export function isSuspiciousRm(cmd) {
139
169
  if (!cmd)
@@ -143,7 +173,7 @@ export function isSuspiciousRm(cmd) {
143
173
  if (!/(^|\s)-[a-zA-Z]*r|--recursive/i.test(m[1]))
144
174
  continue;
145
175
  for (const t of m[2].trim().split(/\s+/)) {
146
- if (/(^|\/)\.\.(\/|$)|[{}*?[\]]|\$\(|`/.test(t) && /^\/?(tmp|private\/tmp|var\/tmp|var\/folders)(\/|$)|\/tmp\//.test(t.replace(/^["']|["']$/g, '')))
176
+ if (/(^|\/)\.\.(\/|$)|[{}*?[\]]|\$\(|`/.test(t) && /^\/?(tmp|private\/tmp|var\/tmp|private\/var\/tmp|var\/folders|private\/var\/folders)(\/|$)|\/tmp\//.test(t.replace(/^["']|["']$/g, '')))
147
177
  return true;
148
178
  }
149
179
  }
@@ -0,0 +1,15 @@
1
+ import type { GitOp } from './command-analyzer.js';
2
+ export interface CommitSecretHit {
3
+ file: string;
4
+ reasons: string[];
5
+ }
6
+ export interface CommitCheckResult {
7
+ hits: CommitSecretHit[]; /** 시간 예산(2초)을 넘겨 끝까지 검사하지 못했다 — 호출자는 fail-open 하지 말고 확인(ask)해야 한다. */
8
+ timedOut: boolean;
9
+ }
10
+ /** git 호출 + 파일 읽기 합산 시간 예산. PreToolUse hook timeout(3초) 안에 끝내기 위해 2초. */
11
+ export declare const COMMIT_GUARD_BUDGET_MS = 2000;
12
+ /** 이름만으로 비밀 파일인 것 (.env 계열, 자격증명, SSH 개인키, 키스토어, 서비스 계정). */
13
+ export declare function secretFileReason(file: string): string | null;
14
+ export declare function checkGitSecrets(ops: GitOp[], hookCwd?: string): CommitSecretHit[];
15
+ export declare function checkGitSecretsBudgeted(ops: GitOp[], hookCwd?: string, budgetMs?: number): CommitCheckResult;
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Commit guard (D12-B) — `git add` / `git commit` 가 비밀 파일·키를 저장소에 넣으려 할 때 PreToolUse 에서 막는다.
3
+ *
4
+ * 명령 문자열만 보는 게 아니라 **실제 git 상태**를 확인한다:
5
+ * - add: pathspec(또는 -A/./-u)이 가리키는 untracked/modified 파일 중 .gitignore 로 제외되지 않은 것
6
+ * (-f 이면 제외된 파일도). 이름 규칙 + 내용(고신뢰 키 패턴) 검사.
7
+ * - commit: `git diff --cached`(staged), -a 이면 tracked 변경까지. 추가된 줄에서 고신뢰 키 패턴 검사.
8
+ * 비밀 "값"은 결과에 담지 않는다 — 파일 경로와 패턴 이름만 돌려준다.
9
+ */
10
+ import { execFileSync } from 'node:child_process';
11
+ import * as fs from 'node:fs';
12
+ import * as path from 'node:path';
13
+ import { SECRET_PATTERNS } from '../secret-filter.js';
14
+ /** git 호출 + 파일 읽기 합산 시간 예산. PreToolUse hook timeout(3초) 안에 끝내기 위해 2초. */
15
+ export const COMMIT_GUARD_BUDGET_MS = 2000;
16
+ class BudgetExceeded extends Error {
17
+ }
18
+ let deadline = Infinity;
19
+ function checkBudget() { if (Date.now() > deadline)
20
+ throw new BudgetExceeded('commit-guard time budget exceeded'); }
21
+ const STRICT_NAMES = new Set(['Private Key', 'AWS Access Key', 'GitHub Token', 'Google API Key', 'Slack Token', 'Connection String']);
22
+ const STRICT_PATTERNS = [
23
+ ...SECRET_PATTERNS.filter((p) => STRICT_NAMES.has(p.name)),
24
+ { name: 'API Key (sk-)', pattern: /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/ },
25
+ ];
26
+ const ENV_SAFE_SUFFIX = /\.(example|sample|template|dist|defaults?|tpl|schema)$/i;
27
+ /** 이름만으로 비밀 파일인 것 (.env 계열, 자격증명, SSH 개인키, 키스토어, 서비스 계정). */
28
+ export function secretFileReason(file) {
29
+ const base = path.basename(file);
30
+ if (/^\.env(\..+)?$/i.test(base) && !ENV_SAFE_SUFFIX.test(base))
31
+ return '.env file';
32
+ if (/^credentials(\.json)?$/i.test(base) || base === '.git-credentials' || base === '.netrc')
33
+ return 'credentials file';
34
+ if (/^id_(rsa|dsa|ecdsa|ed25519)$/.test(base))
35
+ return 'SSH private key';
36
+ if (/\.(p12|pfx|jks|keystore|ppk)$/i.test(base))
37
+ return 'key store';
38
+ if (/^(service[-_]?account|serviceAccount).*\.json$/i.test(base) || /^secrets?\.(json|ya?ml)$/i.test(base))
39
+ return 'secrets file';
40
+ return null;
41
+ }
42
+ function git(dir, args, max = 4_000_000) {
43
+ checkBudget();
44
+ const remaining = Math.max(50, Math.min(5000, deadline - Date.now()));
45
+ try {
46
+ return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf-8', timeout: remaining, maxBuffer: max, stdio: ['ignore', 'pipe', 'ignore'] });
47
+ }
48
+ catch (e) {
49
+ // 시간 초과로 죽은 git 을 "출력 없음 = 안전" 으로 읽으면 fail-open — 예산 초과로 올려 보낸다.
50
+ if (e.code === 'ETIMEDOUT' || e.signal === 'SIGTERM')
51
+ throw new BudgetExceeded('git timed out');
52
+ return '';
53
+ }
54
+ }
55
+ /** 문서·테스트에 흔한 예제 값 — 진짜 비밀이 아니므로 차단하지 않는다. */
56
+ const PLACEHOLDER_RE = /EXAMPLE|example\.(com|org|net)|\blocalhost\b|127\.0\.0\.1|user(name)?:pass(word)?@|\bxxx+|\*{4,}|<[A-Za-z_ -]+>|\b(YOUR|MY|REPLACE|CHANGE)[_-]/i;
57
+ function scanText(text) {
58
+ const names = [];
59
+ for (const sp of STRICT_PATTERNS) {
60
+ checkBudget();
61
+ const re = new RegExp(sp.pattern.source, sp.pattern.flags.includes('g') ? sp.pattern.flags : `${sp.pattern.flags}g`);
62
+ let real = false;
63
+ for (const m of text.matchAll(re)) {
64
+ // 연결 문자열은 매치가 `scheme://user:pw@` 까지라 호스트(localhost 등)를 보려면 뒤 문맥이 필요하다.
65
+ const ctx = sp.name === 'Connection String' ? text.slice(m.index, m.index + m[0].length + 80) : m[0];
66
+ if (!PLACEHOLDER_RE.test(ctx)) {
67
+ real = true;
68
+ break;
69
+ }
70
+ }
71
+ if (real)
72
+ names.push(sp.name);
73
+ }
74
+ return names;
75
+ }
76
+ function addedLines(diff) {
77
+ return diff.split('\n').filter((l) => l.startsWith('+') && !l.startsWith('+++')).join('\n');
78
+ }
79
+ export function checkGitSecrets(ops, hookCwd) {
80
+ return checkGitSecretsBudgeted(ops, hookCwd).hits;
81
+ }
82
+ export function checkGitSecretsBudgeted(ops, hookCwd, budgetMs = COMMIT_GUARD_BUDGET_MS) {
83
+ deadline = Date.now() + budgetMs;
84
+ const hits = new Map();
85
+ let timedOut = false;
86
+ try {
87
+ collectHits(ops, hookCwd, hits);
88
+ }
89
+ catch (e) {
90
+ if (e instanceof BudgetExceeded)
91
+ timedOut = true;
92
+ else
93
+ throw e;
94
+ }
95
+ finally {
96
+ deadline = Infinity;
97
+ }
98
+ return { hits: [...hits.entries()].map(([file, r]) => ({ file, reasons: [...r] })), timedOut };
99
+ }
100
+ function collectHits(ops, hookCwd, hits) {
101
+ const add = (f, r) => { if (!hits.has(f))
102
+ hits.set(f, new Set()); hits.get(f).add(r); };
103
+ for (const op of ops) {
104
+ if (op.sub !== 'add' && op.sub !== 'commit')
105
+ continue;
106
+ const base = op.cwd || hookCwd || '';
107
+ const dir = op.dir ? (op.dir.startsWith('/') ? op.dir : path.join(base, op.dir)) : base;
108
+ if (!dir || !fs.existsSync(dir))
109
+ continue;
110
+ if (!git(dir, ['rev-parse', '--git-dir']).trim())
111
+ continue; // git 저장소 아님
112
+ if (op.sub === 'add') {
113
+ const force = op.args.some((a) => a === '-f' || a === '--force' || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(a));
114
+ const all = op.args.some((a) => a === '-A' || a === '--all' || a === '-u' || a === '--update');
115
+ const specs = op.args.filter((a) => !a.startsWith('-'));
116
+ if (!all && specs.length === 0)
117
+ continue;
118
+ const pathArgs = specs.length ? ['--', ...specs] : [];
119
+ const candidates = new Set();
120
+ const lsOthers = git(dir, ['ls-files', '-z', '--others', '--exclude-standard', ...pathArgs]).split('\0');
121
+ const lsMod = git(dir, ['ls-files', '-z', '--modified', ...pathArgs]).split('\0');
122
+ for (const f of [...lsOthers, ...lsMod])
123
+ if (f)
124
+ candidates.add(f);
125
+ if (force && specs.length) {
126
+ for (const f of git(dir, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', ...pathArgs]).split('\0'))
127
+ if (f)
128
+ candidates.add(f);
129
+ }
130
+ let n = 0;
131
+ for (const f of candidates) {
132
+ if (n++ >= 200)
133
+ break;
134
+ checkBudget();
135
+ const reason = secretFileReason(f);
136
+ if (reason)
137
+ add(f, reason);
138
+ try {
139
+ const abs = path.join(dir, f);
140
+ const st = fs.statSync(abs);
141
+ if (st.isFile() && st.size <= 512 * 1024 && !reason) {
142
+ for (const nm of scanText(fs.readFileSync(abs, 'utf-8')))
143
+ add(f, nm);
144
+ }
145
+ }
146
+ catch (e) {
147
+ if (e instanceof BudgetExceeded)
148
+ throw e; /* unreadable → skip */
149
+ }
150
+ }
151
+ }
152
+ else {
153
+ const withAll = op.args.some((a) => a === '-a' || a === '--all' || /^-[a-zA-Z]*a[a-zA-Z]*$/.test(a) && !a.startsWith('--'));
154
+ const diffArgs = (cached) => ['diff', ...(cached ? ['--cached'] : []), '-U0', '--no-color', '--no-ext-diff'];
155
+ const files = [
156
+ ...git(dir, ['diff', '--cached', '--name-only', '-z']).split('\0'),
157
+ ...(withAll ? git(dir, ['diff', '--name-only', '-z']).split('\0') : []),
158
+ ].filter(Boolean);
159
+ for (const f of files) {
160
+ const r = secretFileReason(f);
161
+ if (r)
162
+ add(f, r);
163
+ }
164
+ const parts = [git(dir, diffArgs(true)), ...(withAll ? [git(dir, diffArgs(false))] : [])];
165
+ // 파일별로 쪼개 어느 파일인지 알린다
166
+ for (const part of parts) {
167
+ for (const chunk of part.split(/^diff --git /m).slice(1)) {
168
+ const m = /^a\/(.+?) b\//.exec(chunk);
169
+ const f = m ? m[1] : '(staged diff)';
170
+ for (const nm of scanText(addedLines(chunk)))
171
+ add(f, nm);
172
+ }
173
+ }
174
+ }
175
+ }
176
+ }
@@ -25,6 +25,12 @@ export declare function approve(): string;
25
25
  * 에게 가시화한다.
26
26
  */
27
27
  export declare function approveWithContext(context: string, eventName: string, userNotice?: string): string;
28
+ /**
29
+ * PostToolUse 통과 + 모델에 컨텍스트 전달 (D12-B).
30
+ * 이전 secret-filter/slop-detector 는 systemMessage(사용자 화면 전용)만 써서 모델이 경고를 못 받았다.
31
+ * PostToolUse 의 hookSpecificOutput.additionalContext 는 모델에 도달한다.
32
+ */
33
+ export declare function approveWithPostToolContext(context: string, userNotice?: string): string;
28
34
  /**
29
35
  * 통과 + UI 경고 표시 (모델에는 전달되지 않음).
30
36
  * PostToolUse, PreToolUse 경고 등 모델 도달이 불필요한 경우 사용.
@@ -37,6 +37,18 @@ export function approveWithContext(context, eventName, userNotice) {
37
37
  ...(userNotice ? { systemMessage: userNotice } : {}),
38
38
  });
39
39
  }
40
+ /**
41
+ * PostToolUse 통과 + 모델에 컨텍스트 전달 (D12-B).
42
+ * 이전 secret-filter/slop-detector 는 systemMessage(사용자 화면 전용)만 써서 모델이 경고를 못 받았다.
43
+ * PostToolUse 의 hookSpecificOutput.additionalContext 는 모델에 도달한다.
44
+ */
45
+ export function approveWithPostToolContext(context, userNotice) {
46
+ return JSON.stringify({
47
+ continue: true,
48
+ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: context },
49
+ ...(userNotice ? { systemMessage: userNotice } : {}),
50
+ });
51
+ }
40
52
  /**
41
53
  * 통과 + UI 경고 표시 (모델에는 전달되지 않음).
42
54
  * PostToolUse, PreToolUse 경고 등 모델 도달이 불필요한 경우 사용.
@@ -8,13 +8,15 @@ import * as fs from 'node:fs';
8
8
  import * as path from 'node:path';
9
9
  import { STATE_DIR } from '../../core/paths.js';
10
10
  const TIMING_LOG = path.join(STATE_DIR, 'hook-timing.jsonl');
11
- const MAX_LINES = 500;
11
+ // H13: 500줄 회전은 hook 호출이 잦으면 몇 시간치뿐이라 30일 p95 집계가 불가능했다.
12
+ // 엔트리는 ~80바이트 — 30일 × 일 5,000회 ≈ 150,000줄 ≈ 12MB. 상한을 200,000줄로 두고 오래된 쪽부터 버린다.
13
+ const MAX_LINES = 200_000;
12
14
  // P0-2 fix (2026-04-20): rotate를 size gate로 보호. 이전에는 매 hook 완료마다
13
15
  // full-file read + length split + write까지 실행해 steady-state(500줄 근처)에서
14
16
  // 매 tool call당 ~40KB의 불필요 I/O가 발생했다. statSync 한 번으로 크기만 보고
15
17
  // threshold 이하면 read/write 둘 다 skip한다. threshold는 ~80바이트/엔트리 기준
16
18
  // MAX_LINES × 1.5 여유를 둠.
17
- const ROTATE_SIZE_BYTES = MAX_LINES * 80 * 2; // ~80KB
19
+ const ROTATE_SIZE_BYTES = MAX_LINES * 90; // ~18MB 를 넘을 때만 회전 검사(대부분 호출은 stat 한 번)
18
20
  export function recordHookTiming(hookName, durationMs, event) {
19
21
  // ADR-015 C-G1 (critic #2): 중첩 추출 run 의 빠른 early-approve 타이밍이 p95 를 왜곡하지 않도록 기록 생략.
20
22
  if (process.env.FORGEN_NESTED_RUN === '1')
@@ -33,7 +35,11 @@ export function recordHookTiming(hookName, durationMs, event) {
33
35
  const content = fs.readFileSync(TIMING_LOG, 'utf-8');
34
36
  const lines = content.trim().split('\n');
35
37
  if (lines.length > MAX_LINES) {
36
- fs.writeFileSync(TIMING_LOG, `${lines.slice(-MAX_LINES).join('\n')}\n`);
38
+ // 목표의 90% 로 줄여 매 호출마다 재회전하지 않게 한다. tmp + rename 으로 동시 append 와의 충돌 최소화.
39
+ const keep = lines.slice(-Math.floor(MAX_LINES * 0.9));
40
+ const tmp = `${TIMING_LOG}.${process.pid}.tmp`;
41
+ fs.writeFileSync(tmp, `${keep.join('\n')}\n`);
42
+ fs.renameSync(tmp, TIMING_LOG);
37
43
  }
38
44
  }
39
45
  catch { /* skip rotation on error */ }
@@ -28,8 +28,13 @@ export declare const INJECTION_CAPS: {
28
28
  export declare const RULE_FILE_CAPS: {
29
29
  /** .claude/rules/ 파일 1개당 최대 글자 수 */
30
30
  readonly perRuleFile: 3000;
31
- /** .claude/rules/에 forgen가 쓸 수 있는 총량 (글자) */
32
- readonly totalRuleFiles: 15000;
31
+ /**
32
+ * 사용자 룰 파일(v1-rules.md) 상한. 룰 렌더러가 이 안에서 우선순위로 고르고 빠진 룰을 표시하므로,
33
+ * 파일 합성에서 중간이 잘리지 않는다. 3000 자에서는 활성 룰 20개가 이미 잘렸다(2026-11-04 실측).
34
+ */
35
+ readonly perUserRuleFile: 8000;
36
+ /** 룰 블록 총량 (글자). SESSION_CONTEXT_MAX 안쪽에 복구 메시지 자리를 남긴다. */
37
+ readonly totalRuleFiles: 8500;
33
38
  /** compound.md에 포함할 rule summary 최대 수 */
34
39
  readonly maxRuleSummaries: 10;
35
40
  };
@@ -37,3 +42,28 @@ export declare const RULE_FILE_CAPS: {
37
42
  export declare const TRUNCATION_SUFFIX = "\n... (truncated)";
38
43
  /** 주어진 content를 maxChars로 잘라서 반환. 초과 시 truncation suffix 추가. */
39
44
  export declare function truncateContent(content: string, maxChars: number): string;
45
+ /**
46
+ * SessionStart additionalContext 상한. Claude Code 2.1.318 실측(2026-11-04): 9,500자는 모델에 도달하고
47
+ * 10,500자부터는 내용 전체가 사라진다(잘리는 게 아니라 통째로). 이 값을 넘기면 룰이 전부 끊기므로 불변식이다.
48
+ */
49
+ export declare const SESSION_CONTEXT_MAX = 9500;
50
+ /**
51
+ * 룰 블록 + 복구 메시지 → 최종 컨텍스트. 룰을 항상 먼저 지키고, 넘치는 메시지는 빼고 표시한다.
52
+ * 어떤 입력이어도 SESSION_CONTEXT_MAX 를 넘지 않는다.
53
+ */
54
+ export declare function fitSessionContext(rulesBlock: string | null, messages: string[]): string;
55
+ /** 파일 이름별 상한. */
56
+ export declare function ruleFileCap(filename: string): number;
57
+ export interface ComposedRuleFile {
58
+ filename: string;
59
+ content: string;
60
+ truncated: boolean;
61
+ }
62
+ /**
63
+ * 룰 파일 맵 → 실제 주입본. Claude 파일 쓰기와 Codex 컨텍스트 블록이 같이 쓴다.
64
+ * 사용자 룰을 먼저 배치해 총량 상한에 밀리지 않게 하고, 자를 때는 줄 경계에서 자른다.
65
+ */
66
+ export declare function composeRuleFiles(ruleFiles: Record<string, string>): {
67
+ files: ComposedRuleFile[];
68
+ omitted: string[];
69
+ };
@@ -28,8 +28,13 @@ export const INJECTION_CAPS = {
28
28
  export const RULE_FILE_CAPS = {
29
29
  /** .claude/rules/ 파일 1개당 최대 글자 수 */
30
30
  perRuleFile: 3000,
31
- /** .claude/rules/에 forgen가 쓸 수 있는 총량 (글자) */
32
- totalRuleFiles: 15000,
31
+ /**
32
+ * 사용자 룰 파일(v1-rules.md) 상한. 룰 렌더러가 이 안에서 우선순위로 고르고 빠진 룰을 표시하므로,
33
+ * 파일 합성에서 중간이 잘리지 않는다. 3000 자에서는 활성 룰 20개가 이미 잘렸다(2026-11-04 실측).
34
+ */
35
+ perUserRuleFile: 8000,
36
+ /** 룰 블록 총량 (글자). SESSION_CONTEXT_MAX 안쪽에 복구 메시지 자리를 남긴다. */
37
+ totalRuleFiles: 8500,
33
38
  /** compound.md에 포함할 rule summary 최대 수 */
34
39
  maxRuleSummaries: 10,
35
40
  };
@@ -50,3 +55,69 @@ export function truncateContent(content, maxChars) {
50
55
  }
51
56
  return sliced + TRUNCATION_SUFFIX;
52
57
  }
58
+ /**
59
+ * SessionStart additionalContext 상한. Claude Code 2.1.318 실측(2026-11-04): 9,500자는 모델에 도달하고
60
+ * 10,500자부터는 내용 전체가 사라진다(잘리는 게 아니라 통째로). 이 값을 넘기면 룰이 전부 끊기므로 불변식이다.
61
+ */
62
+ export const SESSION_CONTEXT_MAX = 9500;
63
+ /**
64
+ * 룰 블록 + 복구 메시지 → 최종 컨텍스트. 룰을 항상 먼저 지키고, 넘치는 메시지는 빼고 표시한다.
65
+ * 어떤 입력이어도 SESSION_CONTEXT_MAX 를 넘지 않는다.
66
+ */
67
+ export function fitSessionContext(rulesBlock, messages) {
68
+ const NOTE_RESERVE = 80;
69
+ const parts = [];
70
+ let used = 0;
71
+ if (rulesBlock) {
72
+ const block = rulesBlock.length > SESSION_CONTEXT_MAX - NOTE_RESERVE
73
+ ? `${rulesBlock.slice(0, rulesBlock.lastIndexOf('\n', SESSION_CONTEXT_MAX - NOTE_RESERVE - 40))}\n... (capped)`
74
+ : rulesBlock;
75
+ parts.push(block);
76
+ used = block.length;
77
+ }
78
+ let dropped = 0;
79
+ for (const message of messages) {
80
+ if (used + message.length + 2 > SESSION_CONTEXT_MAX - NOTE_RESERVE) {
81
+ dropped++;
82
+ continue;
83
+ }
84
+ parts.push(message);
85
+ used += message.length + 2;
86
+ }
87
+ if (dropped > 0)
88
+ parts.push(`(forgen: 컨텍스트 상한으로 복구 메시지 ${dropped}개 생략)`);
89
+ return parts.join('\n\n');
90
+ }
91
+ /** 파일 이름별 상한. */
92
+ export function ruleFileCap(filename) {
93
+ return filename === 'v1-rules.md' ? RULE_FILE_CAPS.perUserRuleFile : RULE_FILE_CAPS.perRuleFile;
94
+ }
95
+ /**
96
+ * 룰 파일 맵 → 실제 주입본. Claude 파일 쓰기와 Codex 컨텍스트 블록이 같이 쓴다.
97
+ * 사용자 룰을 먼저 배치해 총량 상한에 밀리지 않게 하고, 자를 때는 줄 경계에서 자른다.
98
+ */
99
+ export function composeRuleFiles(ruleFiles) {
100
+ const entries = Object.entries(ruleFiles)
101
+ .filter(([, c]) => typeof c === 'string' && c.trim().length > 0)
102
+ .sort(([a], [b]) => Number(b === 'v1-rules.md') - Number(a === 'v1-rules.md'));
103
+ const files = [];
104
+ const omitted = [];
105
+ let total = 0;
106
+ for (const [filename, content] of entries) {
107
+ const cap = ruleFileCap(filename);
108
+ let finalContent = content;
109
+ let truncated = false;
110
+ if (content.length > cap) {
111
+ const cut = content.lastIndexOf('\n', cap);
112
+ finalContent = `${content.slice(0, cut > 0 ? cut : cap)}\n... (capped at rule file limit)\n`;
113
+ truncated = true;
114
+ }
115
+ if (total + finalContent.length > RULE_FILE_CAPS.totalRuleFiles) {
116
+ omitted.push(filename);
117
+ continue;
118
+ }
119
+ total += finalContent.length;
120
+ files.push({ filename, content: finalContent, truncated });
121
+ }
122
+ return { files, omitted };
123
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * 이 모듈이 node 의 진입점으로 실행됐는가.
3
+ *
4
+ * `import.meta.url === \`file://${argv[1]}\`` 는 쓰지 않는다. URL 은 공백·한글을 인코딩하고
5
+ * argv[1] 은 심링크를 풀지 않아서, 설치 경로에 이런 문자가 있거나 심링크를 거치면 항상 false 가 되고
6
+ * hook 이 출력 없이 끝난다(룰 강제가 조용히 사라짐).
7
+ */
8
+ export declare function isMainModule(metaUrl: string, argv1?: string | undefined): boolean;
@@ -0,0 +1,20 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ /**
5
+ * 이 모듈이 node 의 진입점으로 실행됐는가.
6
+ *
7
+ * `import.meta.url === \`file://${argv[1]}\`` 는 쓰지 않는다. URL 은 공백·한글을 인코딩하고
8
+ * argv[1] 은 심링크를 풀지 않아서, 설치 경로에 이런 문자가 있거나 심링크를 거치면 항상 false 가 되고
9
+ * hook 이 출력 없이 끝난다(룰 강제가 조용히 사라짐).
10
+ */
11
+ export function isMainModule(metaUrl, argv1 = process.argv[1]) {
12
+ if (!argv1)
13
+ return false;
14
+ try {
15
+ return fs.realpathSync(path.resolve(argv1)) === fs.realpathSync(fileURLToPath(metaUrl));
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * PostToolUse 의 tool_response 는 도구마다 문자열이거나 객체다 (Bash: {stdout, stderr, interrupted, …},
3
+ * Write: {filePath, content, …}). 객체를 템플릿 문자열에 넣으면 `[object Object]` 가 되어 비밀 탐지가
4
+ * 통째로 우회됐다(H3). 모든 문자열 리프를 줄바꿈으로 이어 붙여 스캔 가능한 텍스트로 만든다.
5
+ */
6
+ export declare function stringifyToolResponse(resp: unknown, maxChars?: number): string;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * PostToolUse 의 tool_response 는 도구마다 문자열이거나 객체다 (Bash: {stdout, stderr, interrupted, …},
3
+ * Write: {filePath, content, …}). 객체를 템플릿 문자열에 넣으면 `[object Object]` 가 되어 비밀 탐지가
4
+ * 통째로 우회됐다(H3). 모든 문자열 리프를 줄바꿈으로 이어 붙여 스캔 가능한 텍스트로 만든다.
5
+ */
6
+ export function stringifyToolResponse(resp, maxChars = 2_000_000) {
7
+ const parts = [];
8
+ let total = 0;
9
+ const visit = (v, depth) => {
10
+ if (total > maxChars || depth > 6 || v === null || v === undefined)
11
+ return;
12
+ if (typeof v === 'string') {
13
+ parts.push(v);
14
+ total += v.length;
15
+ return;
16
+ }
17
+ if (typeof v === 'number' || typeof v === 'boolean')
18
+ return;
19
+ if (Array.isArray(v)) {
20
+ for (const x of v)
21
+ visit(x, depth + 1);
22
+ return;
23
+ }
24
+ if (typeof v === 'object')
25
+ for (const x of Object.values(v))
26
+ visit(x, depth + 1);
27
+ };
28
+ visit(resp, 0);
29
+ return parts.join('\n');
30
+ }