@wooojin/forgen 0.6.7 → 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 (223) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +23 -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/stop-triggers.d.ts +1 -1
  153. package/dist/hooks/shared/stop-triggers.js +2 -1
  154. package/dist/hooks/shared/tool-response.d.ts +6 -0
  155. package/dist/hooks/shared/tool-response.js +30 -0
  156. package/dist/hooks/slop-detector.js +6 -3
  157. package/dist/hooks/solution-injector.d.ts +23 -0
  158. package/dist/hooks/solution-injector.js +102 -101
  159. package/dist/hooks/stop-guard.d.ts +11 -1
  160. package/dist/hooks/stop-guard.js +28 -11
  161. package/dist/hooks/subagent-stop-guard.js +2 -1
  162. package/dist/hooks/subagent-tracker.js +2 -1
  163. package/dist/host/capabilities-codex.js +1 -0
  164. package/dist/host/claude-shim.d.ts +24 -0
  165. package/dist/host/claude-shim.js +68 -0
  166. package/dist/host/codex-hook-shim.d.ts +3 -1
  167. package/dist/host/codex-hook-shim.js +7 -5
  168. package/dist/host/codex-notify.js +1 -1
  169. package/dist/host/codex-rules-context.d.ts +6 -4
  170. package/dist/host/codex-rules-context.js +11 -24
  171. package/dist/host/exec-host.d.ts +5 -1
  172. package/dist/host/exec-host.js +15 -4
  173. package/dist/host/install-claude.d.ts +47 -14
  174. package/dist/host/install-claude.js +302 -155
  175. package/dist/host/install-codex.d.ts +20 -0
  176. package/dist/host/install-codex.js +32 -1
  177. package/dist/host/install-opencode.d.ts +3 -1
  178. package/dist/host/install-opencode.js +6 -3
  179. package/dist/host/install-orchestrator.js +14 -1
  180. package/dist/host/opencode/translate.d.ts +1 -1
  181. package/dist/host/opencode/translate.js +5 -3
  182. package/dist/host/projection.d.ts +9 -1
  183. package/dist/host/projection.js +19 -2
  184. package/dist/mcp/server.js +5 -0
  185. package/dist/mcp/solution-reader.d.ts +5 -5
  186. package/dist/mcp/solution-reader.js +13 -35
  187. package/dist/mcp/tools.js +18 -1
  188. package/dist/renderer/inspect-renderer.js +4 -2
  189. package/dist/renderer/render-report.d.ts +22 -0
  190. package/dist/renderer/render-report.js +29 -0
  191. package/dist/renderer/rule-renderer.d.ts +28 -2
  192. package/dist/renderer/rule-renderer.js +91 -76
  193. package/dist/store/evidence-store.js +34 -6
  194. package/dist/store/rule-lifecycle.d.ts +3 -1
  195. package/dist/store/rule-lifecycle.js +10 -0
  196. package/dist/store/rule-scope.d.ts +7 -0
  197. package/dist/store/rule-scope.js +54 -0
  198. package/dist/store/rule-store.d.ts +29 -3
  199. package/dist/store/rule-store.js +110 -26
  200. package/dist/store/types.d.ts +22 -2
  201. package/dist/way/cli.d.ts +1 -0
  202. package/dist/way/cli.js +313 -0
  203. package/dist/way/compile.d.ts +22 -0
  204. package/dist/way/compile.js +408 -0
  205. package/dist/way/conflict.d.ts +2 -0
  206. package/dist/way/conflict.js +18 -0
  207. package/dist/way/draft.d.ts +43 -0
  208. package/dist/way/draft.js +335 -0
  209. package/dist/way/extract.d.ts +17 -0
  210. package/dist/way/extract.js +172 -0
  211. package/dist/way/io.d.ts +79 -0
  212. package/dist/way/io.js +425 -0
  213. package/dist/way/similar.d.ts +2 -0
  214. package/dist/way/similar.js +30 -0
  215. package/dist/way/types.d.ts +98 -0
  216. package/dist/way/types.js +2 -0
  217. package/package.json +1 -1
  218. package/plugin.json +1 -1
  219. package/scripts/postinstall.js +78 -900
  220. package/dist/core/health-cli.d.ts +0 -25
  221. package/dist/core/health-cli.js +0 -90
  222. package/dist/host/parity-harness.d.ts +0 -70
  223. package/dist/host/parity-harness.js +0 -287
@@ -4,7 +4,7 @@
4
4
  * Extracted from solution-matcher.ts — test/CI infrastructure for measuring
5
5
  * matcher quality against labeled fixtures. No production side-effects.
6
6
  */
7
- import { extractTags } from './solution-format.js';
7
+ import { extractSolutionTags } from './solution-format.js';
8
8
  import { rankCandidates } from './ranking-pipeline.js';
9
9
  /**
10
10
  * Round 3 baseline metrics, recorded against the current `term-normalizer`
@@ -41,7 +41,7 @@ function computeBucketMetrics(queries, solutions) {
41
41
  let reciprocalSum = 0;
42
42
  let noResultCount = 0;
43
43
  for (const q of queries) {
44
- const promptTags = extractTags(q.query);
44
+ const promptTags = extractSolutionTags(q.query);
45
45
  const ranked = rankCandidates(promptTags, q.query.toLowerCase(), solutions);
46
46
  if (ranked.length === 0) {
47
47
  noResultCount++;
@@ -68,7 +68,7 @@ function computeBucketMetrics(queries, solutions) {
68
68
  * and return the top-5 ranked candidates with their relevance + matched tags.
69
69
  */
70
70
  export function evaluateQuery(query, solutions) {
71
- const promptTags = extractTags(query);
71
+ const promptTags = extractSolutionTags(query);
72
72
  return rankCandidates(promptTags, query.toLowerCase(), solutions).map((c) => ({
73
73
  name: c.solution.name,
74
74
  relevance: c.relevance,
@@ -98,7 +98,7 @@ export function evaluateSolutionMatcher(fixture) {
98
98
  : 0;
99
99
  let negAnyResult = 0;
100
100
  for (const q of fixture.negative) {
101
- const promptTags = extractTags(q.query);
101
+ const promptTags = extractSolutionTags(q.query);
102
102
  const ranked = rankCandidates(promptTags, q.query.toLowerCase(), fixture.solutions);
103
103
  if (ranked.length >= 1)
104
104
  negAnyResult++;
@@ -12,10 +12,10 @@
12
12
  * solution-matcher-eval.ts — EvalSolution/Query/Fixture/Result, ROUND3_BASELINE, evaluateQuery, evaluateSolutionMatcher
13
13
  * meta-learning/matcher-weight-loader.ts — loadTunedMatcherWeights
14
14
  */
15
- import * as path from 'node:path';
16
- import { ME_SOLUTIONS, PACKS_DIR } from '../core/paths.js';
17
- import { extractTags } from './solution-format.js';
18
- import { getOrBuildIndex } from './solution-index.js';
15
+ import { projectKeyFor } from '../store/rule-scope.js';
16
+ import { solutionInScope, solutionProjectWeight } from './solution-scope.js';
17
+ import { extractSolutionTags } from './solution-format.js';
18
+ import { getOrBuildIndex, defaultSolutionDirs } from './solution-index.js';
19
19
  import { defaultNormalizer } from './term-normalizer.js';
20
20
  import { rankCandidates } from './ranking-pipeline.js';
21
21
  import { loadTunedMatcherWeights } from './meta-learning/matcher-weight-loader.js';
@@ -44,15 +44,17 @@ function applyCandidateExplorationBonus(entries) {
44
44
  }
45
45
  // ── Public API ──
46
46
  export function matchSolutions(prompt, scope, cwd, contextTokens = []) {
47
- const dirs = [{ dir: ME_SOLUTIONS, scope: 'me' }];
48
- if (scope.team) {
49
- dirs.push({ dir: path.join(PACKS_DIR, scope.team.name, 'solutions'), scope: 'team' });
50
- }
51
- dirs.push({ dir: path.join(cwd, '.compound', 'solutions'), scope: 'project' });
47
+ // hook 과 MCP 가 같은 디렉터리 목록(me + 설치된 팩 + cwd project)을 쓴다.
48
+ const dirs = defaultSolutionDirs(cwd);
49
+ void scope;
50
+ const projectKey = projectKeyFor(cwd);
52
51
  const index = getOrBuildIndex(dirs);
53
- const allSolutions = applyCandidateExplorationBonus(index.entries.map((e) => ({ ...e })));
54
- const promptTags = extractTags(prompt);
55
- const promptLower = prompt.toLowerCase();
52
+ const allSolutions = applyCandidateExplorationBonus(index.entries.filter((e) => solutionInScope(e.projects, projectKey)).map((e) => ({ ...e })));
53
+ // 맨 앞 슬래시 명령 이름(`/plugin install x`)은 호출이지 주제가 아니다 — 이름이 주제 태그로 매치되어
54
+ // 명령어 프롬프트에 무관한 솔루션이 붙던 것을 막는다(실측: /plugin 프롬프트가 plugin 솔루션 2건 오주입).
55
+ const topicText = prompt.replace(/^\s*\/[A-Za-z][\w:.-]*/, ' ');
56
+ const promptTags = extractSolutionTags(topicText);
57
+ const promptLower = topicText.toLowerCase();
56
58
  const tunedWeights = loadTunedMatcherWeights();
57
59
  const ranked = rankCandidates(promptTags, promptLower, allSolutions, tunedWeights, contextTokens);
58
60
  // ADR-010 W3-1 (F2): 저 ROI 강등 — ranking-pipeline 은 순수 유지, 여기서
@@ -61,7 +63,7 @@ export function matchSolutions(prompt, scope, cwd, contextTokens = []) {
61
63
  name: c.solution.name,
62
64
  path: c.solution.filePath,
63
65
  scope: c.solution.scope,
64
- relevance: c.relevance,
66
+ relevance: c.relevance * solutionProjectWeight(c.solution.projects, projectKey),
65
67
  summary: c.solution.name,
66
68
  status: c.solution.status,
67
69
  confidence: c.solution.confidence,
@@ -0,0 +1,11 @@
1
+ /**
2
+ * 솔루션의 프로젝트 범위 (D5). 룰의 rule-scope 와 같은 규칙:
3
+ * - 프로젝트 안: 전역(projects 없음) + 그 프로젝트 솔루션만. 다른 프로젝트 것은 제외하고, 같은 프로젝트 것은 가중치를 더한다.
4
+ * - 프로젝트 밖: 어떤 작업인지 모르니 제외하지 않고 가중치만 낮춘다.
5
+ */
6
+ export declare const PROJECT_MATCH_WEIGHT = 1.15;
7
+ export declare const PROJECT_OUTSIDE_WEIGHT = 0.85;
8
+ /** 이 솔루션이 주어진 프로젝트 컨텍스트에서 후보가 될 수 있는가. */
9
+ export declare function solutionInScope(projects: readonly string[] | undefined, projectKey: string | null): boolean;
10
+ /** relevance 에 곱할 가중치. 전역 솔루션은 1. */
11
+ export declare function solutionProjectWeight(projects: readonly string[] | undefined, projectKey: string | null): number;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 솔루션의 프로젝트 범위 (D5). 룰의 rule-scope 와 같은 규칙:
3
+ * - 프로젝트 안: 전역(projects 없음) + 그 프로젝트 솔루션만. 다른 프로젝트 것은 제외하고, 같은 프로젝트 것은 가중치를 더한다.
4
+ * - 프로젝트 밖: 어떤 작업인지 모르니 제외하지 않고 가중치만 낮춘다.
5
+ */
6
+ export const PROJECT_MATCH_WEIGHT = 1.15;
7
+ export const PROJECT_OUTSIDE_WEIGHT = 0.85;
8
+ /** 이 솔루션이 주어진 프로젝트 컨텍스트에서 후보가 될 수 있는가. */
9
+ export function solutionInScope(projects, projectKey) {
10
+ if (!projects?.length || projectKey === null)
11
+ return true;
12
+ return projects.includes(projectKey);
13
+ }
14
+ /** relevance 에 곱할 가중치. 전역 솔루션은 1. */
15
+ export function solutionProjectWeight(projects, projectKey) {
16
+ if (!projects?.length)
17
+ return 1;
18
+ return projectKey === null ? PROJECT_OUTSIDE_WEIGHT : PROJECT_MATCH_WEIGHT;
19
+ }
@@ -49,7 +49,9 @@ export type SolutionMutator = (solution: SolutionV3) => boolean;
49
49
  * 결함이 발생하면 false 반환 (lock timeout, parse 실패, mutator throw 모두).
50
50
  * 운영 관측성은 PR2c 후속 hardening에서 다룬다 (현재는 log.debug로만).
51
51
  */
52
- export declare function mutateSolutionFile(filePath: string, mutator: SolutionMutator): boolean;
52
+ export declare function mutateSolutionFile(filePath: string, mutator: SolutionMutator, opts?: {
53
+ touchUpdated?: boolean;
54
+ }): boolean;
53
55
  /**
54
56
  * 솔루션 이름으로 .md 파일을 찾아 mutate한다.
55
57
  *
@@ -44,7 +44,7 @@ const log = createLogger('solution-writer');
44
44
  * 결함이 발생하면 false 반환 (lock timeout, parse 실패, mutator throw 모두).
45
45
  * 운영 관측성은 PR2c 후속 hardening에서 다룬다 (현재는 log.debug로만).
46
46
  */
47
- export function mutateSolutionFile(filePath, mutator) {
47
+ export function mutateSolutionFile(filePath, mutator, opts = {}) {
48
48
  try {
49
49
  return withFileLockSync(filePath, () => {
50
50
  let content;
@@ -70,7 +70,8 @@ export function mutateSolutionFile(filePath, mutator) {
70
70
  }
71
71
  if (!modified)
72
72
  return false;
73
- solution.frontmatter.updated = new Date().toISOString().split('T')[0];
73
+ if (opts.touchUpdated !== false)
74
+ solution.frontmatter.updated = new Date().toISOString().split('T')[0];
74
75
  atomicWriteText(filePath, serializeSolutionV3(solution));
75
76
  return true;
76
77
  });
@@ -162,6 +162,55 @@ export const DEFAULT_MATCH_TERMS = [
162
162
  { canonical: 'validation', matchTerms: ['validate', 'check', 'sanitize', '검증', '유효성'] },
163
163
  // ── Logging ──
164
164
  { canonical: 'logging', matchTerms: ['log', 'trace', 'monitor', '로깅', '로그'] },
165
+ // ── D5 한영 동의어 (짧은 사전) ──
166
+ // 원칙: 한국어↔영어 1:1 짝만 둔다. 평가 픽스처에 나온 낱말·넓은 일반어(access, limit, rate, store, 변경 등)는 넣지 않는다.
167
+ // 실측: 솔루션 태그는 한국어·영어가 섞여 저장되고 프롬프트는 어느 쪽으로도 온다. 같은 개념의 한 쌍만 묶는다.
168
+ // 넓은 계열(예: '상태' ↔ 'state' ↔ 'store')은 오탐을 키우므로 만들지 않는다.
169
+ { canonical: 'widget', matchTerms: ['위젯'] },
170
+ { canonical: 'loading', matchTerms: ['로딩', 'skeleton', '스켈레톤'] },
171
+ { canonical: 'empty', matchTerms: ['빈상태', '빈화면'] },
172
+ { canonical: 'token', matchTerms: ['토큰'] },
173
+ { canonical: 'darkmode', matchTerms: ['다크모드', 'dark-mode', '다크', '어두운'] },
174
+ { canonical: 'color', matchTerms: ['색상', '배경색', '컬러', '색'] },
175
+ { canonical: 'scroll', matchTerms: ['스크롤'] },
176
+ { canonical: 'render', matchTerms: ['렌더', '렌더링', '리렌더', '리렌더링', 'rerender', 'rendering'] },
177
+ { canonical: 'event', matchTerms: ['이벤트'] },
178
+ { canonical: 'frame', matchTerms: ['프레임', 'fps', 'raf'] },
179
+ { canonical: 'subagent', matchTerms: ['서브에이전트', 'sub-agent'] },
180
+ { canonical: 'parallel', matchTerms: ['병렬', 'concurrent', 'concurrency'] },
181
+ { canonical: 'ratelimit', matchTerms: ['rate-limit', '429', '레이트리밋'] },
182
+ { canonical: 'mock', matchTerms: ['stub', 'fake', '더블'] },
183
+ { canonical: 'inheritance', matchTerms: ['상속', 'extends'] },
184
+ { canonical: 'composition', matchTerms: ['합성', 'compose'] },
185
+ { canonical: 'stream', matchTerms: ['스트림', 'sse', '실시간', 'realtime', 'streaming'] },
186
+ { canonical: 'query', matchTerms: ['쿼리', 'react-query', 'tanstack'] },
187
+ { canonical: 'parse', matchTerms: ['파싱', 'parsing'] },
188
+ { canonical: 'codeblock', matchTerms: ['코드블록', '펜스', 'fence', '마크다운', 'markdown', 'codefence'] },
189
+ { canonical: 'mutex', matchTerms: ['락'] },
190
+ { canonical: 'bot', matchTerms: ['봇'] },
191
+ { canonical: 'model', matchTerms: ['모델'] },
192
+ { canonical: 'measure', matchTerms: ['측정', 'benchmark'] },
193
+ { canonical: 'plugin', matchTerms: ['플러그인'] },
194
+ { canonical: 'duplicate', matchTerms: ['중복', 'dedupe', 'dedup'] },
195
+ { canonical: 'zombie', matchTerms: ['좀비', 'orphan', '고아'] },
196
+ { canonical: 'block', matchTerms: ['차단', 'blocked', 'blocking'] },
197
+ { canonical: 'falsepositive', matchTerms: ['오탐', 'false-positive'] },
198
+ { canonical: 'feed', matchTerms: ['피드', 'rss'] },
199
+ { canonical: 'preset', matchTerms: ['프리셋'] },
200
+ { canonical: 'onboarding', matchTerms: ['온보딩'] },
201
+ { canonical: 'filter', matchTerms: ['필터', 'filtering'] },
202
+ { canonical: 'commit', matchTerms: ['커밋'] },
203
+ { canonical: 'diff', matchTerms: ['변경사항'] },
204
+ { canonical: 'download', matchTerms: ['다운로드'] },
205
+ { canonical: 'redirect', matchTerms: ['리다이렉트'] },
206
+ { canonical: 'mobile', matchTerms: ['모바일', '폰', 'phone'] },
207
+ { canonical: 'collapse', matchTerms: ['접기', '접고', 'accordion', '펼침'] },
208
+ { canonical: 'forbidden', matchTerms: ['403', '거절'] },
209
+ { canonical: 'privacy', matchTerms: ['privacy', '프라이버시', '개인정보'] },
210
+ { canonical: 'delete', matchTerms: ['삭제'] },
211
+ { canonical: 'save', matchTerms: ['저장', 'persist'] },
212
+ { canonical: 'design', matchTerms: ['설계'] },
213
+ { canonical: 'source', matchTerms: ['출처', 'citation'] },
165
214
  ];
166
215
  /**
167
216
  * Pre-built normalizer for the default registry. Modules that need the
package/dist/fgx.js CHANGED
@@ -16,7 +16,7 @@ const args = process.argv.slice(2);
16
16
  const FORGEN_SUBCOMMANDS = new Set([
17
17
  // Wave 1 통합(feature-audit 2026-07-21): status(←stats/health/dashboard/me/
18
18
  // recall/explain/last-block/watch), dev(←probe-workflow/parity/migrate/regress-map).
19
- 'forge', 'compound', 'skill', 'block', 'status', 'learn', 'statusline', 'rules',
19
+ 'forge', 'compound', 'skill', 'way', 'block', 'status', 'learn', 'statusline', 'rules',
20
20
  'config', 'mcp', 'init', 'install', 'maintenance', 'dev',
21
21
  'notepad', 'inspect', 'doctor', 'uninstall', 'rule',
22
22
  'classify-enforce', 'rule-meta-scan', 'lifecycle-scan',
package/dist/forge/cli.js CHANGED
@@ -11,10 +11,30 @@
11
11
  import { loadProfile, profileExists } from '../store/profile-store.js';
12
12
  import { renderProfile } from '../renderer/inspect-renderer.js';
13
13
  import { runOnboarding } from './onboarding-cli.js';
14
+ const KNOWN_FLAGS = new Set(['--onboarding', '--profile', '--export', '--reset', '--yes', '-y']);
15
+ const RESET_LEVELS = new Set(['soft', 'learning', 'full']);
16
+ function fail(message) {
17
+ console.error(`[forgen] ${message}`);
18
+ process.exitCode = 1;
19
+ }
20
+ /** 온보딩은 대화형 입력이 필요하다. 파이프·CI 에서는 조용히 끝내지 말고 이유를 말한다. */
21
+ function requireTty(what) {
22
+ if (process.stdin.isTTY)
23
+ return true;
24
+ fail(`${what} 은 대화형 터미널(TTY)에서만 실행할 수 있습니다. stdin 이 파이프/리다이렉트라 질문을 받을 수 없습니다. 터미널에서 직접 \`forgen forge --onboarding\` 을 실행하세요.`);
25
+ return false;
26
+ }
14
27
  export async function handleForge(args) {
28
+ const unknown = args.filter((a) => a.startsWith('-') && !KNOWN_FLAGS.has(a));
29
+ if (unknown.length > 0) {
30
+ fail(`알 수 없는 옵션: ${unknown.join(' ')}\n 사용법: forgen forge [--onboarding|--profile|--export|--reset [soft|learning|full] [--yes]]`);
31
+ return;
32
+ }
15
33
  // W1-4 (feature-audit 2026-07-21): forge 를 개인화 단일 관문으로.
16
34
  // --onboarding 은 프로필 유무와 무관하게 4질문 온보딩을 재실행 (구 `forgen onboarding`).
17
35
  if (args.includes('--onboarding')) {
36
+ if (!requireTty('온보딩'))
37
+ return;
18
38
  await runOnboarding();
19
39
  return;
20
40
  }
@@ -27,15 +47,16 @@ export async function handleForge(args) {
27
47
  return;
28
48
  }
29
49
  if (args.includes('--reset')) {
30
- const level = args[args.indexOf('--reset') + 1] ?? 'soft';
31
- await handleReset(level);
50
+ const next = args[args.indexOf('--reset') + 1];
51
+ const level = next && !next.startsWith('-') ? next : 'soft';
52
+ await handleReset(level, args.includes('--yes') || args.includes('-y'));
32
53
  return;
33
54
  }
34
55
  // Default: profile이 있으면 보여주고, 없으면 onboarding
35
56
  if (profileExists()) {
36
57
  handleShowProfile();
37
58
  }
38
- else {
59
+ else if (requireTty('온보딩')) {
39
60
  await runOnboarding();
40
61
  }
41
62
  }
@@ -55,13 +76,35 @@ function handleExport() {
55
76
  }
56
77
  console.log(JSON.stringify(profile, null, 2));
57
78
  }
58
- async function handleReset(level) {
59
- const validLevels = ['soft', 'learning', 'full'];
60
- if (!validLevels.includes(level)) {
61
- console.log(` Invalid reset level: ${level}`);
62
- console.log(` Valid levels: ${validLevels.join(', ')}`);
79
+ const RESET_SCOPE = {
80
+ soft: '프로필 + 룰 + 추천 + 세션 상태',
81
+ learning: '프로필 + 룰 + 교정/행동 기록(behavior) + 추천 + 세션 상태 + 원본 로그',
82
+ full: '프로필 + 룰 + 교정/행동 기록 + 추천 + 세션 상태 + 원본 로그 + 솔루션(compound 전체)',
83
+ };
84
+ async function confirmReset(level, yes) {
85
+ console.log(`\n forge --reset ${level} 은 되돌릴 수 없는 삭제입니다: ${RESET_SCOPE[level]}`);
86
+ if (yes)
87
+ return true;
88
+ if (!process.stdin.isTTY) {
89
+ fail('확인할 수 없어 중단했습니다 (비대화형). 진행하려면 --yes 를 붙이세요. 백업: forgen rule snapshot');
90
+ return false;
91
+ }
92
+ const rl = (await import('node:readline')).createInterface({ input: process.stdin, output: process.stdout });
93
+ const answer = await new Promise((resolve) => rl.question(` 계속하려면 "${level}" 를 입력하세요: `, resolve));
94
+ rl.close();
95
+ if (answer.trim() !== level) {
96
+ console.log(' 취소했습니다. 아무것도 삭제하지 않았습니다.\n');
97
+ return false;
98
+ }
99
+ return true;
100
+ }
101
+ async function handleReset(level, yes) {
102
+ if (!RESET_LEVELS.has(level)) {
103
+ fail(`Invalid reset level: ${level}. Valid levels: soft, learning, full`);
63
104
  return;
64
105
  }
106
+ if (!(await confirmReset(level, yes)))
107
+ return;
65
108
  // 동적 import로 store 모듈 로드
66
109
  const fs = await import('node:fs');
67
110
  const { FORGE_PROFILE, ME_RULES, ME_BEHAVIOR, V1_RECOMMENDATIONS_DIR, V1_SESSIONS_DIR, V1_RAW_LOGS_DIR, ME_SOLUTIONS } = await import('../core/paths.js');
@@ -31,6 +31,10 @@ export function processCorrection(req) {
31
31
  direction: req.kind === 'avoid-this' ? 'opposite' : 'same',
32
32
  // ADR-017 D0: 사용자 발화 원문(있을 때만). rule-origin 이 "당신의 말" 인용에 사용.
33
33
  ...(req.user_quote ? { user_quote: req.user_quote } : {}),
34
+ ...(req.rule_id ? { target_rule_id: req.rule_id } : {}),
35
+ ...(req.projects?.length ? { projects: req.projects } : {}),
36
+ // 모델은 자기 세션 ID 를 확실히 알 수 없다. ID 가 어긋나도 승급되도록 표시한다(소비되면 다시 승급되지 않음).
37
+ ...(req.kind === 'prefer-from-now' || req.kind === 'avoid-this' ? { pending_promotion: true } : {}),
34
38
  },
35
39
  });
36
40
  appendEvidence(evidence); // T1 lifecycle trigger fires here for explicit_correction
@@ -58,6 +62,8 @@ export function processCorrection(req) {
58
62
  strength: req.kind === 'avoid-this' ? 'strong' : 'default',
59
63
  source: 'explicit_correction',
60
64
  evidence_refs: [evidence.evidence_id],
65
+ session_id: req.session_id,
66
+ ...(req.projects?.length ? { projects: req.projects } : {}),
61
67
  render_key: `${req.axis_hint ?? 'workflow'}.${req.target.toLowerCase().replace(/\s+/g, '-').slice(0, 30)}`,
62
68
  });
63
69
  // ADR-001 auto-classify on creation — 교정 즉시 enforce_via 가 붙어야 다음 턴부터 Mech-A/B 발화.
@@ -22,28 +22,6 @@ export declare const RATE_LIMIT_REGEX: RegExp;
22
22
  * @returns ISO timestamp 또는 null
23
23
  */
24
24
  export declare function parseRateLimitResetAt(msg: string, now?: number): string | null;
25
- /** 경고 표시 여부 판정 (순수 함수) */
26
- export declare function shouldWarn(contextPercent: {
27
- promptCount: number;
28
- totalChars: number;
29
- lastWarningAt: number;
30
- }, thresholds?: {
31
- promptThreshold?: number;
32
- charsThreshold?: number;
33
- cooldownMs?: number;
34
- }): boolean;
35
- /** auto-compact 트리거 여부 판정 (순수 함수) */
36
- export declare function shouldAutoCompact(state: {
37
- totalChars: number;
38
- lastAutoCompactAt: number;
39
- }, thresholds?: {
40
- charsThreshold?: number;
41
- cooldownMs?: number;
42
- }): boolean;
43
- /** auto-compact 지시 메시지 생성 (순수 함수) */
44
- export declare function buildAutoCompactMessage(totalChars: number): string;
45
- /** 경고 메시지 생성 (순수 함수) */
46
- export declare function buildContextWarningMessage(promptCount: number, totalChars: number): string;
47
25
  export declare function main(): Promise<void>;
48
26
  /**
49
27
  * 세션 종료 시 forgen *활동*을 요약 (관찰 — 인과 효과/절약 미주장).
@@ -16,8 +16,9 @@ import { fileURLToPath } from 'node:url';
16
16
  import { createLogger } from '../core/logger.js';
17
17
  import { readStdinJSON } from './shared/read-stdin.js';
18
18
  import { atomicWriteJSON } from './shared/atomic-write.js';
19
- import { loadHookConfig, isHookEnabled } from './hook-config.js';
20
- import { approve, approveWithContext, approveWithWarning, failOpenWithTracking } from './shared/hook-response.js';
19
+ import { isHookEnabled } from './hook-config.js';
20
+ import { buildContextNotice, readContextUsage, shouldNoticeContext } from './context-usage.js';
21
+ import { approve, approveWithWarning, failOpenWithTracking } from './shared/hook-response.js';
21
22
  import { HANDOFFS_DIR, STATE_DIR } from '../core/paths.js';
22
23
  import { recordHookTiming } from './shared/hook-timing.js';
23
24
  import { sanitizeId } from './shared/sanitize-id.js';
@@ -156,41 +157,6 @@ function appendPromptHistory(sessionId, prompt) {
156
157
  log.debug('prompt-history append 실패', e);
157
158
  }
158
159
  }
159
- // 경고 임계값: 프롬프트 50회 또는 총 문자 수 200K 이상
160
- const PROMPT_WARNING_THRESHOLD = 50;
161
- const CHARS_WARNING_THRESHOLD = 200_000;
162
- const WARNING_COOLDOWN_MS = 10 * 60 * 1000; // 10분 쿨다운
163
- // Auto-compact 임계값: 추적된 문자 120K ≈ 실제 context ~20%
164
- const AUTO_COMPACT_CHARS_THRESHOLD = 120_000;
165
- const AUTO_COMPACT_COOLDOWN_MS = 5 * 60 * 1000; // 5분 쿨다운
166
- /** 경고 표시 여부 판정 (순수 함수) */
167
- export function shouldWarn(contextPercent, thresholds = {}) {
168
- const promptThreshold = thresholds.promptThreshold ?? PROMPT_WARNING_THRESHOLD;
169
- const charsThreshold = thresholds.charsThreshold ?? CHARS_WARNING_THRESHOLD;
170
- const cooldownMs = thresholds.cooldownMs ?? WARNING_COOLDOWN_MS;
171
- const now = Date.now();
172
- return ((contextPercent.promptCount >= promptThreshold || contextPercent.totalChars >= charsThreshold) &&
173
- (now - contextPercent.lastWarningAt > cooldownMs));
174
- }
175
- /** auto-compact 트리거 여부 판정 (순수 함수) */
176
- export function shouldAutoCompact(state, thresholds = {}) {
177
- const charsThreshold = thresholds.charsThreshold ?? AUTO_COMPACT_CHARS_THRESHOLD;
178
- const cooldownMs = thresholds.cooldownMs ?? AUTO_COMPACT_COOLDOWN_MS;
179
- const now = Date.now();
180
- return state.totalChars >= charsThreshold && (now - state.lastAutoCompactAt > cooldownMs);
181
- }
182
- /** auto-compact 지시 메시지 생성 (순수 함수) */
183
- export function buildAutoCompactMessage(totalChars) {
184
- return `<forgen-auto-compact>
185
- [Forgen] Context 사용량이 ${Math.round(totalChars / 1000)}K 문자에 도달했습니다 (추정 ~20%+).
186
- 지금 즉시 /compact를 실행하여 컨텍스트를 압축하세요. 이 지시는 자동으로 생성되었습니다.
187
- 현재 작업을 마무리하지 말고, 다음 응답에서 바로 compact를 실행하세요.
188
- </forgen-auto-compact>`;
189
- }
190
- /** 경고 메시지 생성 (순수 함수) */
191
- export function buildContextWarningMessage(promptCount, totalChars) {
192
- return `<compound-context-warning>\n[Forgen] Context limit approaching: ${promptCount} prompts, ${Math.round(totalChars / 1000)}K characters.\nIf you have important progress, save it now:\n- Use cancelforgen to reset mode state and start a new session\n- Or continue current work (auto compaction may occur)\n</compound-context-warning>`;
193
- }
194
160
  function loadContextState(sessionId) {
195
161
  try {
196
162
  if (fs.existsSync(CONTEXT_STATE_PATH)) {
@@ -202,7 +168,7 @@ function loadContextState(sessionId) {
202
168
  catch (e) {
203
169
  log.debug('context state 파일 읽기/파싱 실패', e);
204
170
  }
205
- return { promptCount: 0, totalChars: 0, lastWarningAt: 0, lastAutoCompactAt: 0, sessionId };
171
+ return { promptCount: 0, lastWarningAt: 0, sessionId };
206
172
  }
207
173
  function saveContextState(state) {
208
174
  atomicWriteJSON(CONTEXT_STATE_PATH, state);
@@ -334,26 +300,17 @@ export async function main() {
334
300
  }
335
301
  // UserPromptSubmit 훅: 대화 길이 추적
336
302
  if (input.prompt) {
337
- const config = loadHookConfig('context-guard');
338
- // maxTokens가 설정되어 있으면 chars threshold로 사용 (토큰 ≈ 4자 기준 환산)
339
- const charsThreshold = typeof config?.maxTokens === 'number' ? config.maxTokens * 4 : undefined;
340
303
  const state = loadContextState(sessionId);
341
304
  state.promptCount++;
342
- state.totalChars += input.prompt.length;
343
305
  // ADR-008 / docs/codex-integration.md — prompt-history writer 활성화
344
306
  appendPromptHistory(sessionId, input.prompt);
345
- // auto-compact: 추적 문자 120K 이상이면 compact 지시 주입
346
- const autoCompactThreshold = typeof config?.autoCompactChars === 'number' ? config.autoCompactChars : undefined;
347
- if (shouldAutoCompact(state, autoCompactThreshold !== undefined ? { charsThreshold: autoCompactThreshold } : {})) {
348
- state.lastAutoCompactAt = Date.now();
349
- saveContextState(state);
350
- console.log(approveWithContext(buildAutoCompactMessage(state.totalChars), 'UserPromptSubmit'));
351
- return;
352
- }
353
- if (shouldWarn(state, charsThreshold !== undefined ? { charsThreshold } : {})) {
307
+ // 컨텍스트 안내: 실제 사용량(statusline 페이로드 또는 transcript usage)이 창 대비 높을 때만, 사용자에게 보이는 안내로만.
308
+ // 사용량을 모르면 아무것도 하지 않는다. 모델에게는 아무 지시도 주입하지 않는다.
309
+ const usage = readContextUsage(sessionId, input.transcript_path);
310
+ if (usage && shouldNoticeContext(usage, state.lastWarningAt)) {
354
311
  state.lastWarningAt = Date.now();
355
312
  saveContextState(state);
356
- console.log(approveWithContext(buildContextWarningMessage(state.promptCount, state.totalChars), 'UserPromptSubmit'));
313
+ console.log(approveWithWarning(buildContextNotice(usage)));
357
314
  return;
358
315
  }
359
316
  saveContextState(state);
@@ -406,7 +363,7 @@ const FORGE_LOOP_STATE_PATH = path.join(STATE_DIR, 'forge-loop.json');
406
363
  * Stop hook 에서 auto-compound-runner 를 debounced 로 spawn.
407
364
  *
408
365
  * 호출 조건:
409
- * - promptCount ≥ 10 (의미있는 세션)
366
+ * - promptCount ≥ 1 (D9: 짧은 세션도 교정 승급 대상)
410
367
  * - transcript_path 유효
411
368
  * - last-auto-compound.json 의 sessionId 가 다르거나 5분 전
412
369
  *
@@ -442,8 +399,11 @@ export function effectiveCooldownMs(parsed, currentPromptCount = 0) {
442
399
  export async function maybeSpawnAutoCompound(sessionId, transcriptPath, promptCount,
443
400
  /** ADR-016 D1: notify 폴백은 훅 env(FORGEN_CWD) 없이 돌므로 페이로드의 cwd 를 넘긴다. */
444
401
  cwdOverride) {
445
- if (!transcriptPath || promptCount < 10)
402
+ // D9: 메시지 수 게이트 제거 — 짧은 세션의 교정도 승급돼야 한다. 비용은 러너가 새 내용의 양으로 제어한다.
403
+ if (!transcriptPath || promptCount < 1)
446
404
  return false;
405
+ if (process.env.FORGEN_DOCTOR_PROBE === '1')
406
+ return false; // doctor 프로브는 백그라운드 스폰 금지
447
407
  const markerPath = path.join(STATE_DIR, 'last-auto-compound.json');
448
408
  try {
449
409
  const raw = fs.readFileSync(markerPath, 'utf-8');
@@ -456,6 +416,13 @@ cwdOverride) {
456
416
  }
457
417
  }
458
418
  catch { /* first time or corrupt — proceed */ }
419
+ // 마지막 러너 실행 이후 transcript 가 안 자랐고 못 넘긴 구간도 없으면 러너를 띄우지 않는다 (spawn.runAutoCompound 와 같은 판정).
420
+ try {
421
+ const { sessionNeedsRun, transcriptSignature } = await import('../core/extraction-queue.js');
422
+ if (!sessionNeedsRun(sessionId, fs.statSync(transcriptPath).size, { sig: transcriptSignature(transcriptPath) }))
423
+ return false;
424
+ }
425
+ catch { /* stat 실패·이력 없음 — 진행 (fail-open) */ }
459
426
  const { spawn: spawnProcess } = await import('node:child_process');
460
427
  const cwd = cwdOverride ?? process.env.FORGEN_CWD ?? process.env.COMPOUND_CWD ?? process.cwd();
461
428
  // 기본: 번들된 auto-compound-runner. 프로덕션 빌드는 이 경로만 실행.
@@ -491,7 +458,7 @@ cwdOverride) {
491
458
  return false;
492
459
  }
493
460
  try {
494
- const child = spawnProcess('node', [runnerPath, cwd, transcriptPath, sessionId, String(promptCount)], {
461
+ const child = spawnProcess(process.execPath, [runnerPath, cwd, transcriptPath, sessionId, String(promptCount)], {
495
462
  detached: true,
496
463
  stdio: 'ignore',
497
464
  });
@@ -0,0 +1,21 @@
1
+ export interface ContextUsage {
2
+ /** 0~100 */
3
+ percent: number;
4
+ windowSize: number;
5
+ source: 'statusline' | 'transcript';
6
+ }
7
+ /** statusline 이 매 갱신마다 호출. 값이 없으면 아무것도 쓰지 않는다. */
8
+ export declare function writeContextWindow(sessionId: string, cw: {
9
+ used_percentage?: number | null;
10
+ context_window_size?: number;
11
+ } | undefined): void;
12
+ /** 실제 값으로 판단 가능하면 사용량, 아니면 null (= 모름 → 아무것도 하지 않는다). */
13
+ export declare function readContextUsage(sessionId: string, transcriptPath?: string, now?: number): ContextUsage | null;
14
+ /** 알림 여부 (순수 함수). 모르면 false. */
15
+ export declare function shouldNoticeContext(usage: ContextUsage | null, lastNoticeAt: number, opts?: {
16
+ percent?: number;
17
+ cooldownMs?: number;
18
+ now?: number;
19
+ }): boolean;
20
+ /** 사용자에게만 보이는 안내. 모델에게 주는 지시가 아니다. */
21
+ export declare function buildContextNotice(usage: ContextUsage): string;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * 실제 컨텍스트 사용량 — 창 대비 비율.
3
+ *
4
+ * 예전 context-guard 는 사용자가 친 프롬프트의 글자 수를 모아 "120K 문자 ≈ 컨텍스트 20%"라며 모델에게 지금 즉시 /compact 를
5
+ * 하라고 지시했다. 프롬프트 글자 수는 컨텍스트 크기가 아니고(도구 결과·응답·캐시가 대부분이다), 모델은 /compact 를 실행할 수 없으며,
6
+ * 1M 창에서 12% 수준에서도 작업을 끊으라고 했다. 여기서는 실제 값만 쓴다.
7
+ *
8
+ * 1) statusline 페이로드(context_window.used_percentage / context_window_size) — statusline 이 세션별 파일에 남긴다.
9
+ * 2) transcript 마지막 assistant usage(input + cache_read + cache_creation) — 창 크기는 모른다.
10
+ * 토큰이 200K 를 넘으면 창은 1M 이어야 하므로 그때만 비율을 낸다. 200K 이하는 200K 창인지 1M 창인지 알 수 없어 모른다고 한다.
11
+ * 모르면 null — 호출자는 아무것도 하지 않는다. 알림은 사용자에게 보이는 안내(systemMessage)뿐이고 모델에는 아무것도 주지 않는다.
12
+ */
13
+ import * as fs from 'node:fs';
14
+ import * as path from 'node:path';
15
+ import { STATE_DIR } from '../core/paths.js';
16
+ import { sanitizeId } from './shared/sanitize-id.js';
17
+ /** statusline 값이 이보다 오래됐으면 transcript 로 넘어간다. */
18
+ const STATUSLINE_FRESH_MS = 30 * 60 * 1000;
19
+ const NOTICE_PERCENT = 70;
20
+ const NOTICE_COOLDOWN_MS = 10 * 60 * 1000;
21
+ const TRANSCRIPT_TAIL_BYTES = 512 * 1024;
22
+ const SMALL_WINDOW = 200_000;
23
+ const BIG_WINDOW = 1_000_000;
24
+ function pathFor(sessionId) {
25
+ return path.join(STATE_DIR, `context-window-${sanitizeId(sessionId)}.json`);
26
+ }
27
+ /** statusline 이 매 갱신마다 호출. 값이 없으면 아무것도 쓰지 않는다. */
28
+ export function writeContextWindow(sessionId, cw) {
29
+ if (!cw || typeof cw.used_percentage !== 'number' || typeof cw.context_window_size !== 'number' || cw.context_window_size <= 0)
30
+ return;
31
+ try {
32
+ fs.mkdirSync(STATE_DIR, { recursive: true });
33
+ fs.writeFileSync(pathFor(sessionId), JSON.stringify({ at: Date.now(), used_percentage: cw.used_percentage, context_window_size: cw.context_window_size }));
34
+ }
35
+ catch { /* fail-open */ }
36
+ }
37
+ function fromStatusline(sessionId, now) {
38
+ try {
39
+ const j = JSON.parse(fs.readFileSync(pathFor(sessionId), 'utf-8'));
40
+ if (typeof j.at !== 'number' || now - j.at > STATUSLINE_FRESH_MS)
41
+ return null;
42
+ if (typeof j.used_percentage !== 'number' || typeof j.context_window_size !== 'number')
43
+ return null;
44
+ return { percent: j.used_percentage, windowSize: j.context_window_size, source: 'statusline' };
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ function fromTranscript(transcriptPath) {
51
+ if (!transcriptPath)
52
+ return null;
53
+ try {
54
+ const fd = fs.openSync(transcriptPath, 'r');
55
+ let text;
56
+ try {
57
+ const size = fs.fstatSync(fd).size;
58
+ const len = Math.min(size, TRANSCRIPT_TAIL_BYTES);
59
+ const buf = Buffer.alloc(len);
60
+ fs.readSync(fd, buf, 0, len, size - len);
61
+ text = buf.toString('utf-8');
62
+ }
63
+ finally {
64
+ fs.closeSync(fd);
65
+ }
66
+ const lines = text.split('\n');
67
+ for (let i = lines.length - 1; i >= 0; i--) {
68
+ if (!lines[i].includes('"usage"'))
69
+ continue;
70
+ let u;
71
+ try {
72
+ u = JSON.parse(lines[i]).message?.usage;
73
+ }
74
+ catch {
75
+ continue;
76
+ }
77
+ if (!u)
78
+ continue;
79
+ const tokens = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
80
+ if (tokens <= SMALL_WINDOW)
81
+ return null; // 200K 창인지 1M 창인지 알 수 없다
82
+ return { percent: Math.min(100, Math.round((tokens / BIG_WINDOW) * 100)), windowSize: BIG_WINDOW, source: 'transcript' };
83
+ }
84
+ }
85
+ catch { /* 읽기 실패 = 모름 */ }
86
+ return null;
87
+ }
88
+ /** 실제 값으로 판단 가능하면 사용량, 아니면 null (= 모름 → 아무것도 하지 않는다). */
89
+ export function readContextUsage(sessionId, transcriptPath, now = Date.now()) {
90
+ return fromStatusline(sessionId, now) ?? fromTranscript(transcriptPath);
91
+ }
92
+ /** 알림 여부 (순수 함수). 모르면 false. */
93
+ export function shouldNoticeContext(usage, lastNoticeAt, opts = {}) {
94
+ if (!usage)
95
+ return false;
96
+ const now = opts.now ?? Date.now();
97
+ return usage.percent >= (opts.percent ?? NOTICE_PERCENT) && now - lastNoticeAt > (opts.cooldownMs ?? NOTICE_COOLDOWN_MS);
98
+ }
99
+ /** 사용자에게만 보이는 안내. 모델에게 주는 지시가 아니다. */
100
+ export function buildContextNotice(usage) {
101
+ const size = usage.windowSize >= 1_000_000 ? `${Math.round(usage.windowSize / 1_000_000)}M` : `${Math.round(usage.windowSize / 1000)}K`;
102
+ return `[Forgen] 컨텍스트 ${Math.round(usage.percent)}% 사용 중 (창 ${size}). 여유가 줄고 있습니다. 편한 시점에 직접 /compact 를 실행하거나 새 세션을 여세요.`;
103
+ }