@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
@@ -6,7 +6,7 @@
6
6
  * 통합해 표면을 줄이고 진입점을 일원화한다. 기존 render/compute 함수는 재사용만
7
7
  * 하고 재작성하지 않는다.
8
8
  *
9
- * forgen status 요약 (health 헤더 + one-screen stats)
9
+ * forgen status 요약 (학습 흐름 6단계 + one-screen stats)
10
10
  * forgen status --compound compound 상태 + 최근 회상 이력
11
11
  * forgen status --profile 4축 프로필 + 최근 교정
12
12
  * forgen status --rules 활성 룰
@@ -48,6 +48,12 @@ export async function handleStatus(args) {
48
48
  return;
49
49
  }
50
50
  const view = resolveView(args);
51
+ const unknownFlags = args.filter((a) => a.startsWith('-') && !resolveView([a]) && !['--watch', '--json', '--interval', '--limit', '--show'].includes(a.split('=')[0]));
52
+ if (unknownFlags.length > 0) {
53
+ console.error(`[forgen] 알 수 없는 status 옵션: ${unknownFlags.join(' ')}\n views: --compound | --profile | --rules | --blocks [N] | --overview | --live | --turn`);
54
+ process.exitCode = 1;
55
+ return;
56
+ }
51
57
  switch (view) {
52
58
  case '--compound': {
53
59
  const { runDashboard } = await import('./dashboard-cli.js');
@@ -98,10 +104,23 @@ export async function handleStatus(args) {
98
104
  return;
99
105
  }
100
106
  default: {
101
- // 요약: health 헤더 + one-screen stats (둘 다 computeStats() 기반).
102
- const { computeHealth, renderHealthLine } = await import('./health-cli.js');
107
+ // 요약: 학습 흐름(단계별 입력·마지막 성공·최근 건수) + one-screen stats. 점수(X/100)는 없다.
108
+ const { computeFlow, renderFlow, haikuStatus } = await import('./flow-status.js');
103
109
  const { computeStats, renderStats } = await import('./stats-cli.js');
104
- console.log(renderHealthLine(computeHealth()));
110
+ console.log('\n forgen status');
111
+ for (const l of renderFlow(computeFlow()))
112
+ console.log(l);
113
+ console.log(` Haiku 추출 ${haikuStatus().detail}`);
114
+ try {
115
+ const { queryGateDistribution } = await import('./observability-store.js');
116
+ const dist = queryGateDistribution(30);
117
+ const total = Object.values(dist).reduce((a, b) => a + b, 0);
118
+ if (total > 0) {
119
+ const ordered = Object.entries(dist).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v}`).join(' · ');
120
+ console.log(` 회수 게이트 최근 30일 후보 ${total}건: ${ordered}`);
121
+ }
122
+ }
123
+ catch { /* 관측 DB 없음 */ }
105
124
  console.log(renderStats(computeStats()));
106
125
  console.log(` ${dim('views:')} forgen status --compound | --profile | --rules | --blocks [N] | --live | --turn`);
107
126
  return;
@@ -373,6 +373,11 @@ export async function handleStatuslineWith(payload, nowMs = Date.now(), chain =
373
373
  const { sanitizeId } = await import('../hooks/shared/sanitize-id.js');
374
374
  cacheSessionModel(sanitizeId(payload.session_id), payload.model.id);
375
375
  }
376
+ // (1b) 실제 컨텍스트 사용량 — context-guard 가 창 대비 비율로 판단하도록 세션별 파일에 남긴다.
377
+ if (payload.session_id) {
378
+ const { writeContextWindow } = await import('../hooks/context-usage.js');
379
+ writeContextWindow(payload.session_id, payload.context_window);
380
+ }
376
381
  // (2) D5 샘플 기록 — 매 호출. 압축은 **append 앞**에서(critic r2: append 직후면 mtime 이 항상 신선해
377
382
  // 정적 가드가 영원히 막혔다). 크기 ≥256KB·60초 정적일 때만 재작성, 2% 확률.
378
383
  const samples = samplesFromPayload(payload.rate_limits, nowMs);
@@ -18,9 +18,17 @@ export interface StatusLineInstallResult {
18
18
  backedUp?: boolean;
19
19
  message: string;
20
20
  }
21
- /** 이 패키지의 cli.js 절대 경로로 만든 statusline 명령 — PATH/nvm 무관. */
22
- export declare function forgenStatuslineCommand(): string;
21
+ /**
22
+ * statusline 명령. 고정 shim 경유(`"<shim>" "cli.js" statusline`)라 node 버전·패키지 위치와 무관하다.
23
+ * shim 을 못 쓰는 환경(Windows)은 이 패키지 cli.js 절대경로.
24
+ */
25
+ export declare function forgenStatuslineCommand(shimPath?: string | null): string;
23
26
  export declare function isForgenStatusline(command: unknown): boolean;
27
+ /**
28
+ * settings 객체의 statusLine 을 제자리에서 갱신(설치·래퍼 공용). 없거나 forgen 소유면 `command` 로,
29
+ * 체인(`… statusline --after '<원본>'`)이면 forgen 부분만 갱신하고 --after 이후는 보존, 커스텀이면 그대로 둔다.
30
+ */
31
+ export declare function applyStatusLineAuto(settings: Record<string, unknown>, command: string): 'installed' | 'updated' | 'unchanged' | 'custom';
24
32
  /** POSIX 단일 인용 — 내부 `'` 는 `'\''` 로. `$(…)`·`"`·`\` 도 리터럴로 보존된다. */
25
33
  export declare function shQuote(s: string): string;
26
34
  /** 원본 statusLine 명령을 `--after` 로 감싼 forgen 체인 명령. */
@@ -14,16 +14,39 @@
14
14
  import * as fs from 'node:fs';
15
15
  import * as path from 'node:path';
16
16
  import { fileURLToPath } from 'node:url';
17
+ import { forgenRunShimPath, isForgenRunCommand, shimSupported } from '../host/claude-shim.js';
17
18
  import { CLAUDE_DIR } from './paths.js';
18
- /** 이 패키지의 cli.js 절대 경로로 만든 statusline 명령 — PATH/nvm 무관. */
19
- export function forgenStatuslineCommand() {
19
+ import { quoteArg } from '../hooks/hooks-generator.js';
20
+ /**
21
+ * statusline 명령. 고정 shim 경유(`"<shim>" "cli.js" statusline`)라 node 버전·패키지 위치와 무관하다.
22
+ * shim 을 못 쓰는 환경(Windows)은 이 패키지 cli.js 절대경로.
23
+ */
24
+ export function forgenStatuslineCommand(shimPath = shimSupported() ? forgenRunShimPath() : null) {
25
+ if (shimPath)
26
+ return `${quoteArg(shimPath)} "cli.js" statusline`;
20
27
  const cli = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'cli.js');
21
28
  return `"${process.execPath}" "${cli}" statusline`;
22
29
  }
23
30
  export function isForgenStatusline(command) {
24
31
  if (typeof command !== 'string' || !command.trim())
25
32
  return true; // 없음 = forgen 이 가져가도 됨
26
- return /^forgen(\s|$)/.test(command.trim()) || /[\\/]dist[\\/]cli\.js"?\s+statusline(\s|$)/.test(command);
33
+ return /^forgen(\s|$)/.test(command.trim()) || /[\\/]dist[\\/]cli\.js"?\s+statusline(\s|$)/.test(command)
34
+ || (isForgenRunCommand(command) && /"?cli\.js"?\s+statusline(\s|$)/.test(command));
35
+ }
36
+ /**
37
+ * settings 객체의 statusLine 을 제자리에서 갱신(설치·래퍼 공용). 없거나 forgen 소유면 `command` 로,
38
+ * 체인(`… statusline --after '<원본>'`)이면 forgen 부분만 갱신하고 --after 이후는 보존, 커스텀이면 그대로 둔다.
39
+ */
40
+ export function applyStatusLineAuto(settings, command) {
41
+ const existing = settings.statusLine?.command;
42
+ if (existing && !isForgenStatusline(existing))
43
+ return 'custom';
44
+ const chainAt = existing ? String(existing).search(CHAIN_RE) : -1;
45
+ const next = chainAt >= 0 ? `${command}${String(existing).slice(chainAt + ' statusline'.length)}` : command;
46
+ if (existing === next)
47
+ return 'unchanged';
48
+ settings.statusLine = { type: 'command', command: next };
49
+ return existing ? 'updated' : 'installed';
27
50
  }
28
51
  /** POSIX 단일 인용 — 내부 `'` 는 `'\''` 로. `$(…)`·`"`·`\` 도 리터럴로 보존된다. */
29
52
  export function shQuote(s) {
@@ -35,7 +58,7 @@ export function forgenChainCommand(original) {
35
58
  }
36
59
  const CHAIN_RE = /\sstatusline\s+--after\s/;
37
60
  export function isChainedStatusline(command) {
38
- return typeof command === 'string' && /[\\/]cli\.js"?\s+statusline\s+--after\s/.test(command);
61
+ return typeof command === 'string' && /[\\/"]cli\.js"?\s+statusline\s+--after\s/.test(command);
39
62
  }
40
63
  export function installStatusline(opts = {}) {
41
64
  const settingsPath = opts.settingsPath ?? path.join(CLAUDE_DIR, 'settings.json');
@@ -1,18 +1,93 @@
1
1
  /**
2
- * Transcript → 요약 텍스트 (순수, IO 없음 — 테스트 가능).
2
+ * Transcript → 추출 입력 요약 (D3, 2026-11-04 재설계).
3
3
  *
4
- * auto-compound-runner 의 extractSummary 에서 분리(2026-08-04). 분리 이유: 실 Claude
5
- * transcript 스키마 버그(text 가 `entry.message.content` 에 있는데 top-level `entry.content`
6
- * 만 읽어 전 user/assistant 턴 누락 → auto-compound 가 실데이터에서 dead)를 회귀 테스트로
7
- * 고정하기 위함. 러너 본문은 process.argv 실행부와 묶여 있어 직접 unit-test 불가였다.
4
+ * 약속: 요약에는 사용자가 실제로 한 말과 어시스턴트가 실제로 한 말만 들어간다. 그 안에서
5
+ * 1) 세션 끝 구간, 2) 교정 메시지와 그 앞 어시스턴트 발화, 3) 나머지 사용자 발화 순으로 예산을 쓴다.
6
+ * 예산은 "읽은 길이"가 아니라 "남긴 길이"로 센다 — 예전 구현은 원문 길이로 세다 첫 몇 턴(주로 주입
7
+ * 텍스트)에서 조기 종료해 123MB 세션의 0.1%만 요약에 들었다.
8
+ *
9
+ * 제외(주입 텍스트): 스킬 본문, 슬래시 명령 표식, caveat, system-reminder, hook 컨텍스트, forgen-rules,
10
+ * stop-hook 메시지, 서브에이전트/피어/태스크 알림, 컴팩션 요약, AGENTS.md 주입(Codex).
8
11
  *
9
12
  * 스키마:
10
- * Claude: {type:'user'|'assistant', message:{role, content: string | [{type:'text',text}]}}
11
- * (일부 queue-operation 등은 top-level `content` 에 저장 → fallback)
12
- * Codex: {type:'response_item', payload:{role, content:[{type:'input_text', text}]}}
13
+ * Claude: {type:'user'|'assistant', message:{role, content: string | [{type:'text',text}|tool_result...]}}
14
+ * (queue-operation 등은 top-level `content` 에 저장 → fallback)
15
+ * Codex: {type:'response_item', payload:{role, content:[{type:'input_text'|'output_text', text}]}}
16
+ *
17
+ * 파일은 스트림으로 읽고(`digestTranscriptFile`) 바이트 커서로 이어 읽는다 — 123MB 도 메모리 상수.
13
18
  */
14
19
  export declare function extractText(c: unknown): string;
15
20
  /** Codex content array → flat string. content: [{type:'input_text', text}] */
16
21
  export declare function extractCodexText(content: unknown): string;
17
- /** JSONL 원문 → `[User]/[Assistant]` 요약. maxChars 초과 시 조기 종료. */
22
+ /** 주입 블록을 걷어낸 사람 발화. 남는 게 없거나 전체가 주입이면 ''. */
23
+ export declare function stripInjected(text: string): string;
24
+ interface TranscriptEntry {
25
+ type?: string;
26
+ operation?: string;
27
+ content?: unknown;
28
+ isMeta?: boolean;
29
+ isSidechain?: boolean;
30
+ isCompactSummary?: boolean;
31
+ origin?: {
32
+ kind?: string;
33
+ };
34
+ message?: {
35
+ role?: string;
36
+ content?: unknown;
37
+ };
38
+ payload?: {
39
+ role?: string;
40
+ type?: string;
41
+ content?: unknown;
42
+ };
43
+ }
44
+ /** 한 JSONL 엔트리 → {role,text} (주입/비대화는 null). */
45
+ export declare function classifyEntry(entry: TranscriptEntry): {
46
+ role: 'user' | 'assistant';
47
+ text: string;
48
+ } | null;
49
+ export interface DigestItem {
50
+ line: number;
51
+ role: 'user' | 'assistant';
52
+ /** MAX_KEEP 으로 잘린 본문 */
53
+ text: string;
54
+ /** 사용자 발화의 교정 신호 점수 (0 = 없음) */
55
+ score: number;
56
+ }
57
+ export interface Digest {
58
+ items: DigestItem[];
59
+ totalLines: number;
60
+ /** 다음 증분 읽기 시작 바이트 (완결된 마지막 줄 끝) */
61
+ endOffset: number;
62
+ userMessages: number;
63
+ correctionCandidates: number;
64
+ }
65
+ export interface DigestState {
66
+ items: DigestItem[];
67
+ lineNo: number;
68
+ userMessages: number;
69
+ correctionCandidates: number;
70
+ recentUser: string[];
71
+ }
72
+ export declare function newDigestState(): DigestState;
73
+ /** 한 줄을 먹인다. 파싱 실패/비대화 줄은 줄 번호만 올린다. */
74
+ export declare function feedLine(st: DigestState, line: string): void;
75
+ export declare function finishDigest(st: DigestState, endOffset: number): Digest;
76
+ /** 교정 후보가 많은 세션일수록 예산을 늘린다(상한 32K자). 남긴 길이 기준. */
77
+ export declare function budgetFor(d: Pick<Digest, 'correctionCandidates'>, base?: number): number;
78
+ /**
79
+ * 다이제스트 → 예산 안 요약 문자열(시간순). 우선순위:
80
+ * 1) 세션 끝 20% 구간(예산 25% 상한, 늦은 것부터) 2) 교정 발화(강한 신호 먼저, 등간격)와 직전 어시스턴트
81
+ * 3) 나머지 사용자 발화(등간격) 4) 남으면 어시스턴트 응답.
82
+ */
83
+ export declare function renderDigest(d: Digest, budget?: number): string;
84
+ /**
85
+ * JSONL 파일을 fromOffset 바이트부터 스트림으로 읽어 줄마다 콜백. 반환값 = 다음 증분 읽기 시작 바이트.
86
+ * 개행 없이 끝난 마지막 줄이 JSON 으로 깨져 있으면(쓰는 중) 그 줄은 커서에 넣지 않는다.
87
+ */
88
+ export declare function streamTranscriptLines(filePath: string, fromOffset: number, onLine: (line: string) => void): Promise<number>;
89
+ /** 파일 → 다이제스트 (스트림, fromOffset 바이트부터). */
90
+ export declare function digestTranscriptFile(filePath: string, fromOffset?: number): Promise<Digest>;
91
+ /** 문자열 JSONL → 요약 (테스트·소형 입력용 동기 경로). */
18
92
  export declare function summarizeTranscript(rawText: string, maxChars?: number): string;
93
+ export {};
@@ -1,16 +1,23 @@
1
1
  /**
2
- * Transcript → 요약 텍스트 (순수, IO 없음 — 테스트 가능).
2
+ * Transcript → 추출 입력 요약 (D3, 2026-11-04 재설계).
3
3
  *
4
- * auto-compound-runner 의 extractSummary 에서 분리(2026-08-04). 분리 이유: 실 Claude
5
- * transcript 스키마 버그(text 가 `entry.message.content` 에 있는데 top-level `entry.content`
6
- * 만 읽어 전 user/assistant 턴 누락 → auto-compound 가 실데이터에서 dead)를 회귀 테스트로
7
- * 고정하기 위함. 러너 본문은 process.argv 실행부와 묶여 있어 직접 unit-test 불가였다.
4
+ * 약속: 요약에는 사용자가 실제로 한 말과 어시스턴트가 실제로 한 말만 들어간다. 그 안에서
5
+ * 1) 세션 끝 구간, 2) 교정 메시지와 그 앞 어시스턴트 발화, 3) 나머지 사용자 발화 순으로 예산을 쓴다.
6
+ * 예산은 "읽은 길이"가 아니라 "남긴 길이"로 센다 — 예전 구현은 원문 길이로 세다 첫 몇 턴(주로 주입
7
+ * 텍스트)에서 조기 종료해 123MB 세션의 0.1%만 요약에 들었다.
8
+ *
9
+ * 제외(주입 텍스트): 스킬 본문, 슬래시 명령 표식, caveat, system-reminder, hook 컨텍스트, forgen-rules,
10
+ * stop-hook 메시지, 서브에이전트/피어/태스크 알림, 컴팩션 요약, AGENTS.md 주입(Codex).
8
11
  *
9
12
  * 스키마:
10
- * Claude: {type:'user'|'assistant', message:{role, content: string | [{type:'text',text}]}}
11
- * (일부 queue-operation 등은 top-level `content` 에 저장 → fallback)
12
- * Codex: {type:'response_item', payload:{role, content:[{type:'input_text', text}]}}
13
+ * Claude: {type:'user'|'assistant', message:{role, content: string | [{type:'text',text}|tool_result...]}}
14
+ * (queue-operation 등은 top-level `content` 에 저장 → fallback)
15
+ * Codex: {type:'response_item', payload:{role, content:[{type:'input_text'|'output_text', text}]}}
16
+ *
17
+ * 파일은 스트림으로 읽고(`digestTranscriptFile`) 바이트 커서로 이어 읽는다 — 123MB 도 메모리 상수.
13
18
  */
19
+ import * as fs from 'node:fs';
20
+ import { correctionScore } from './correction-signals.js';
14
21
  export function extractText(c) {
15
22
  if (typeof c === 'string')
16
23
  return c;
@@ -34,48 +41,275 @@ export function extractCodexText(content) {
34
41
  }
35
42
  return parts.join('\n');
36
43
  }
37
- /** JSONL 원문 → `[User]/[Assistant]` 요약. maxChars 초과 시 조기 종료. */
38
- export function summarizeTranscript(rawText, maxChars = 8000) {
39
- const lines = rawText.split('\n').filter(Boolean);
40
- const messages = [];
41
- let totalChars = 0;
42
- for (const line of lines) {
44
+ // ── 주입 텍스트 판정 ──
45
+ const INJECTED_BLOCK_RE = /<(system-reminder|forgen-rules|user-prompt-submit-hook|session-start-hook|task-notification|local-command-caveat|local-command-stdout|command-name|command-message|command-args|compound-handoff|teammate-message|environment_context|user_instructions|INSTRUCTIONS)\b[^>]*>[\s\S]*?<\/\1>/gi;
46
+ const INJECTED_PREFIX_RE = new RegExp('^(' + [
47
+ '<(command-name|command-message|command-args|local-command|system-reminder|task-notification|forgen-rules|user-prompt-submit-hook|session-start-hook|bash-input|bash-stdout|bash-stderr|ide_|teammate-message|agent-message|INSTRUCTIONS|environment_context|user_instructions|compound-handoff)',
48
+ 'Caveat:',
49
+ 'Base directory for this skill',
50
+ '# AGENTS\\.md instructions',
51
+ 'Stop hook (feedback|error|blocking)',
52
+ '\\[Request interrupted',
53
+ 'Another Claude session sent a message',
54
+ 'This session is being continued from a previous conversation',
55
+ 'Your claude\\.ai usage limit has reset',
56
+ '\\[forgen\\]',
57
+ '\\[Forgen\\]',
58
+ ].join('|') + ')', 'i');
59
+ /** 주입 블록을 걷어낸 사람 발화. 남는 게 없거나 전체가 주입이면 ''. */
60
+ export function stripInjected(text) {
61
+ if (!text)
62
+ return '';
63
+ const trimmed = text.trim();
64
+ if (INJECTED_PREFIX_RE.test(trimmed))
65
+ return '';
66
+ const cleaned = trimmed.replace(INJECTED_BLOCK_RE, '').trim();
67
+ if (!cleaned || INJECTED_PREFIX_RE.test(cleaned))
68
+ return '';
69
+ return cleaned;
70
+ }
71
+ /** 한 JSONL 엔트리 → {role,text} (주입/비대화는 null). */
72
+ export function classifyEntry(entry) {
73
+ if (entry.type === 'user' || entry.type === 'queue-operation') {
74
+ if (entry.isSidechain || entry.isMeta || entry.isCompactSummary)
75
+ return null;
76
+ if (entry.origin?.kind && entry.origin.kind !== 'human')
77
+ return null;
78
+ if (entry.type === 'queue-operation' && entry.operation && entry.operation !== 'enqueue')
79
+ return null;
80
+ const text = stripInjected(extractText(entry.message?.content ?? entry.content));
81
+ return text ? { role: 'user', text } : null;
82
+ }
83
+ if (entry.type === 'assistant') {
84
+ if (entry.isSidechain)
85
+ return null;
86
+ const text = extractText(entry.message?.content ?? entry.content).trim();
87
+ return text ? { role: 'assistant', text } : null;
88
+ }
89
+ if (entry.type === 'response_item' && entry.payload && (entry.payload.type === undefined || entry.payload.type === 'message')) {
90
+ const role = entry.payload.role;
91
+ if (role !== 'user' && role !== 'assistant')
92
+ return null;
93
+ const raw = extractCodexText(entry.payload.content);
94
+ const text = role === 'user' ? stripInjected(raw) : raw.trim();
95
+ return text ? { role, text } : null;
96
+ }
97
+ return null;
98
+ }
99
+ const MAX_KEEP = 600;
100
+ const RECENT_DEDUP = 64;
101
+ export function newDigestState() {
102
+ return { items: [], lineNo: 0, userMessages: 0, correctionCandidates: 0, recentUser: [] };
103
+ }
104
+ /** 한 줄을 먹인다. 파싱 실패/비대화 줄은 줄 번호만 올린다. */
105
+ export function feedLine(st, line) {
106
+ st.lineNo++;
107
+ // 값싼 선필터: 큰 줄(attachment, 스냅샷 등)은 JSON.parse 하지 않는다.
108
+ if (!(line.includes('"type":"user"') || line.includes('"type":"assistant"')
109
+ || line.includes('"type":"queue-operation"') || line.includes('"type":"response_item"')
110
+ || line.includes('"type": "user"') || line.includes('"type": "assistant"')
111
+ || line.includes('"type": "queue-operation"') || line.includes('"type": "response_item"')))
112
+ return;
113
+ let entry;
114
+ try {
115
+ entry = JSON.parse(line);
116
+ }
117
+ catch {
118
+ return;
119
+ }
120
+ const c = classifyEntry(entry);
121
+ if (!c)
122
+ return;
123
+ const text = c.text.length > MAX_KEEP ? c.text.slice(0, MAX_KEEP) : c.text;
124
+ let score = 0;
125
+ if (c.role === 'user') {
126
+ const key = text.slice(0, 120);
127
+ if (st.recentUser.includes(key))
128
+ return; // queue-operation + user 이중 기록 제거
129
+ st.recentUser.push(key);
130
+ if (st.recentUser.length > RECENT_DEDUP)
131
+ st.recentUser.shift();
132
+ st.userMessages++;
133
+ score = correctionScore(text);
134
+ if (score > 0)
135
+ st.correctionCandidates++;
136
+ }
137
+ st.items.push({ line: st.lineNo, role: c.role, text, score });
138
+ }
139
+ export function finishDigest(st, endOffset) {
140
+ return {
141
+ items: st.items, totalLines: st.lineNo, endOffset,
142
+ userMessages: st.userMessages, correctionCandidates: st.correctionCandidates,
143
+ };
144
+ }
145
+ /** 교정 후보가 많은 세션일수록 예산을 늘린다(상한 32K자). 남긴 길이 기준. */
146
+ export function budgetFor(d, base = 12_000) {
147
+ return Math.min(32_000, base + 60 * d.correctionCandidates);
148
+ }
149
+ const TAIL_FRACTION = 0.2;
150
+ const TAIL_BUDGET_SHARE = 0.25;
151
+ function fmt(it, cap) {
152
+ const body = it.text.length > cap ? `${it.text.slice(0, cap)}…` : it.text;
153
+ return `[${it.role === 'user' ? 'User' : 'Assistant'}] ${body}`;
154
+ }
155
+ /** 등간격 추출: 후보 중 예산에 맞게 n개만, 시간축 전체에 퍼지도록. */
156
+ function stride(arr, n) {
157
+ if (n >= arr.length)
158
+ return arr;
159
+ if (n <= 0)
160
+ return [];
161
+ const out = [];
162
+ for (let k = 0; k < n; k++)
163
+ out.push(arr[Math.floor((k * arr.length) / n)]);
164
+ return out;
165
+ }
166
+ /**
167
+ * 다이제스트 → 예산 안 요약 문자열(시간순). 우선순위:
168
+ * 1) 세션 끝 20% 구간(예산 25% 상한, 늦은 것부터) 2) 교정 발화(강한 신호 먼저, 등간격)와 직전 어시스턴트
169
+ * 3) 나머지 사용자 발화(등간격) 4) 남으면 어시스턴트 응답.
170
+ */
171
+ export function renderDigest(d, budget = budgetFor(d)) {
172
+ const chosen = new Set();
173
+ let used = 0;
174
+ const cost = (it, cap) => Math.min(it.text.length, cap) + 14;
175
+ const take = (it, cap) => {
176
+ if (chosen.has(it))
177
+ return true;
178
+ const c = cost(it, cap);
179
+ if (used + c > budget)
180
+ return false;
181
+ chosen.add(it);
182
+ used += c;
183
+ return true;
184
+ };
185
+ const caps = new Map();
186
+ const takeCap = (it, cap) => {
187
+ const ok = take(it, cap);
188
+ if (ok)
189
+ caps.set(it, Math.max(caps.get(it) ?? 0, cap));
190
+ return ok;
191
+ };
192
+ const tailStart = d.totalLines * (1 - TAIL_FRACTION);
193
+ const tail = d.items.filter((i) => i.line > tailStart);
194
+ const tailBudget = budget * TAIL_BUDGET_SHARE;
195
+ let tailUsed = 0;
196
+ for (let k = tail.length - 1; k >= 0; k--) {
197
+ const c = cost(tail[k], 300);
198
+ if (tailUsed + c > tailBudget) {
199
+ if (chosen.size > 0)
200
+ continue;
201
+ }
202
+ if (takeCap(tail[k], 300))
203
+ tailUsed += c;
204
+ }
205
+ const idxOf = new Map();
206
+ d.items.forEach((it, i) => idxOf.set(it, i));
207
+ const corr = d.items.filter((i) => i.role === 'user' && i.score > 0 && !chosen.has(i));
208
+ for (const tier of [3, 2]) {
209
+ const group = corr.filter((i) => i.score === tier);
210
+ if (group.length === 0)
211
+ continue;
212
+ const avg = Math.max(30, group.reduce((s, i) => s + cost(i, 200), 0) / group.length);
213
+ // 교정 발화 자체에 예산의 80% 까지, 나머지는 앞뒤 맥락/일반 발화에.
214
+ const room = Math.max(0, budget * 0.8 - used);
215
+ const n = Math.floor(room / avg);
216
+ for (const it of stride(group, n))
217
+ takeCap(it, 200);
218
+ }
219
+ // 교정 직전 어시스턴트 발화(맥락) — 남은 예산의 일부
220
+ const ctxBudgetEnd = used + (budget - used) * 0.5;
221
+ for (const it of [...chosen]) {
222
+ if (it.role !== 'user' || it.score < 3)
223
+ continue;
224
+ const prev = d.items[(idxOf.get(it) ?? 0) - 1];
225
+ if (prev && prev.role === 'assistant' && used + cost(prev, 140) <= ctxBudgetEnd)
226
+ takeCap(prev, 140);
227
+ }
228
+ const rest = d.items.filter((i) => i.role === 'user' && !chosen.has(i));
229
+ if (rest.length > 0) {
230
+ const avg = Math.max(30, rest.reduce((s, i) => s + cost(i, 200), 0) / rest.length);
231
+ const n = Math.floor((budget - used) / avg);
232
+ for (const it of stride(rest, n))
233
+ takeCap(it, 200);
234
+ }
235
+ const asst = d.items.filter((i) => i.role === 'assistant' && !chosen.has(i));
236
+ if (asst.length > 0 && budget - used > 200) {
237
+ const n = Math.floor((budget - used) / 170);
238
+ for (const it of stride(asst, n))
239
+ takeCap(it, 140);
240
+ }
241
+ const ordered = d.items.filter((i) => chosen.has(i));
242
+ return ordered.map((i) => fmt(i, caps.get(i) ?? MAX_KEEP)).join('\n\n');
243
+ }
244
+ /**
245
+ * JSONL 파일을 fromOffset 바이트부터 스트림으로 읽어 줄마다 콜백. 반환값 = 다음 증분 읽기 시작 바이트.
246
+ * 개행 없이 끝난 마지막 줄이 JSON 으로 깨져 있으면(쓰는 중) 그 줄은 커서에 넣지 않는다.
247
+ */
248
+ export async function streamTranscriptLines(filePath, fromOffset, onLine) {
249
+ const size = fs.statSync(filePath).size;
250
+ const start = fromOffset > size ? 0 : fromOffset; // 파일이 줄었으면 처음부터
251
+ if (start >= size)
252
+ return size;
253
+ const stream = fs.createReadStream(filePath, { start, end: size - 1, highWaterMark: 1 << 20 });
254
+ // readline 은 줄 끝(\n / \r\n)을 지워 버려 실제 바이트 수를 알 수 없다 — CRLF 파일에서 커서가 줄마다 1바이트씩 어긋났다.
255
+ // 직접 \n 바이트로 나누고, 커서는 원본 바이트(종결자 포함)로 센다.
256
+ let offset = start;
257
+ let carry = Buffer.alloc(0);
258
+ const emit = (raw) => {
259
+ let line = raw.toString('utf-8');
260
+ if (line.endsWith('\r'))
261
+ line = line.slice(0, -1);
262
+ onLine(line);
263
+ };
264
+ for await (const chunk of stream) {
265
+ let buf = carry.length ? Buffer.concat([carry, chunk]) : chunk;
266
+ let nl;
267
+ // biome-ignore lint/suspicious/noAssignInExpressions: 바이트 스캔 관용구
268
+ while ((nl = buf.indexOf(0x0a)) !== -1) {
269
+ emit(buf.subarray(0, nl));
270
+ offset += nl + 1;
271
+ buf = buf.subarray(nl + 1);
272
+ }
273
+ carry = Buffer.from(buf);
274
+ }
275
+ let endOffset = offset;
276
+ if (carry.length > 0) {
277
+ // 개행 없이 끝난 마지막 줄: JSON 으로 온전하면 처리하고 커서에 넣고, 깨져 있으면(쓰는 중) 커서에 넣지 않는다.
278
+ const tail = carry.toString('utf-8').replace(/\r$/, '');
279
+ let ok = true;
43
280
  try {
44
- const entry = JSON.parse(line);
45
- // Claude schema — text 는 message.content 우선(실버그 수정), top-level 은 fallback.
46
- if (entry.type === 'user' || entry.type === 'queue-operation') {
47
- const text = extractText(entry.message?.content ?? entry.content);
48
- if (text) {
49
- messages.push(`[User] ${text.slice(0, 500)}`);
50
- totalChars += text.length;
51
- }
52
- }
53
- else if (entry.type === 'assistant') {
54
- const text = extractText(entry.message?.content ?? entry.content);
55
- if (text) {
56
- messages.push(`[Assistant] ${text.slice(0, 500)}`);
57
- totalChars += text.length;
58
- }
59
- }
60
- // Codex schema
61
- else if (entry.type === 'response_item' && entry.payload?.role === 'user') {
62
- const text = extractCodexText(entry.payload.content);
63
- if (text) {
64
- messages.push(`[User] ${text.slice(0, 500)}`);
65
- totalChars += text.length;
66
- }
67
- }
68
- else if (entry.type === 'response_item' && entry.payload?.role === 'assistant') {
69
- const text = extractCodexText(entry.payload.content);
70
- if (text) {
71
- messages.push(`[Assistant] ${text.slice(0, 500)}`);
72
- totalChars += text.length;
73
- }
74
- }
281
+ JSON.parse(tail);
75
282
  }
76
- catch { /* skip malformed line */ }
77
- if (totalChars > maxChars)
78
- break;
283
+ catch {
284
+ ok = false;
285
+ }
286
+ if (tail.length > 0)
287
+ onLine(tail);
288
+ if (ok)
289
+ endOffset = offset + carry.length;
290
+ }
291
+ return Math.min(endOffset, size);
292
+ }
293
+ /** 파일 → 다이제스트 (스트림, fromOffset 바이트부터). */
294
+ export async function digestTranscriptFile(filePath, fromOffset = 0) {
295
+ const st = newDigestState();
296
+ const end = await streamTranscriptLines(filePath, fromOffset, (line) => {
297
+ if (line)
298
+ feedLine(st, line);
299
+ else
300
+ st.lineNo++;
301
+ });
302
+ return finishDigest(st, end);
303
+ }
304
+ /** 문자열 JSONL → 요약 (테스트·소형 입력용 동기 경로). */
305
+ export function summarizeTranscript(rawText, maxChars) {
306
+ const st = newDigestState();
307
+ for (const line of rawText.split('\n')) {
308
+ if (line)
309
+ feedLine(st, line);
310
+ else
311
+ st.lineNo++;
79
312
  }
80
- return messages.join('\n\n');
313
+ const d = finishDigest(st, Buffer.byteLength(rawText));
314
+ return renderDigest(d, maxChars ?? budgetFor(d));
81
315
  }
@@ -10,6 +10,10 @@ export declare function cleanDevGuideSkills(pkgRoot: string, homeDir?: string):
10
10
  * 여기에 등록하는데 uninstall 은 settings.json 만 정리하고 있었다. forgen 서버 경로를 가리킬 때만 지운다.
11
11
  */
12
12
  export declare function cleanClaudeJsonMcp(homeDir?: string): boolean;
13
+ /** 고정 shim(<FORGEN_HOME>/bin/forgen-run) 제거 — 표식이 있는 forgen 파일만. 빈 bin 디렉토리도 정리. */
14
+ export declare function cleanForgenRunShim(homeDir?: string): boolean;
15
+ /** 전역 ~/.claude/agents/ch-*.md — forgen 표식이 있는 것만 지운다(사용자 파일 보존). */
16
+ export declare function cleanGlobalAgents(homeDir?: string): number;
13
17
  /** forgen uninstall 메인 */
14
18
  export declare function handleUninstall(cwd: string, options: {
15
19
  force?: boolean;