@wooojin/forgen 0.6.8 → 0.6.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +17 -0
  3. package/README.ja.md +15 -10
  4. package/README.ko.md +15 -10
  5. package/README.md +19 -14
  6. package/README.zh.md +13 -8
  7. package/dist/checks/dangerous-response-pattern.d.ts +2 -1
  8. package/dist/checks/dangerous-response-pattern.js +27 -3
  9. package/dist/cli.js +133 -17
  10. package/dist/core/auto-compound-runner.js +502 -397
  11. package/dist/core/block-cli.js +7 -3
  12. package/dist/core/compound-consent.d.ts +18 -0
  13. package/dist/core/compound-consent.js +101 -6
  14. package/dist/core/compound-sweep-cli.d.ts +16 -0
  15. package/dist/core/compound-sweep-cli.js +67 -5
  16. package/dist/core/config-hooks.js +28 -10
  17. package/dist/core/correction-signals.d.ts +9 -0
  18. package/dist/core/correction-signals.js +37 -0
  19. package/dist/core/dev-cli.d.ts +1 -2
  20. package/dist/core/dev-cli.js +9 -28
  21. package/dist/core/doctor-verify.d.ts +35 -0
  22. package/dist/core/doctor-verify.js +502 -0
  23. package/dist/core/doctor.d.ts +4 -6
  24. package/dist/core/doctor.js +103 -184
  25. package/dist/core/explain-cli.js +8 -0
  26. package/dist/core/extraction-haiku.d.ts +64 -0
  27. package/dist/core/extraction-haiku.js +208 -0
  28. package/dist/core/extraction-queue.d.ts +68 -0
  29. package/dist/core/extraction-queue.js +300 -0
  30. package/dist/core/flow-status.d.ts +93 -0
  31. package/dist/core/flow-status.js +368 -0
  32. package/dist/core/harness.js +14 -42
  33. package/dist/core/inspect-cli.js +37 -13
  34. package/dist/core/lifecycle-classifier.d.ts +5 -1
  35. package/dist/core/lifecycle-classifier.js +13 -2
  36. package/dist/core/migrate-cli.d.ts +1 -1
  37. package/dist/core/migrate-cli.js +11 -11
  38. package/dist/core/migrate-tenetx.d.ts +1 -1
  39. package/dist/core/migrate-tenetx.js +2 -2
  40. package/dist/core/node-engine.d.ts +3 -0
  41. package/dist/core/node-engine.js +8 -0
  42. package/dist/core/observability-store.d.ts +15 -0
  43. package/dist/core/observability-store.js +73 -0
  44. package/dist/core/paths.d.ts +2 -0
  45. package/dist/core/paths.js +2 -0
  46. package/dist/core/rendered-rules-manifest.d.ts +7 -1
  47. package/dist/core/rendered-rules-manifest.js +45 -1
  48. package/dist/core/session-store.d.ts +13 -11
  49. package/dist/core/session-store.js +103 -119
  50. package/dist/core/settings-injector.d.ts +5 -2
  51. package/dist/core/settings-injector.js +21 -88
  52. package/dist/core/spawn.d.ts +9 -1
  53. package/dist/core/spawn.js +33 -33
  54. package/dist/core/stats-cli.d.ts +7 -0
  55. package/dist/core/stats-cli.js +66 -93
  56. package/dist/core/status-cli.d.ts +1 -1
  57. package/dist/core/status-cli.js +23 -4
  58. package/dist/core/statusline-cli.js +5 -0
  59. package/dist/core/statusline-install.d.ts +10 -2
  60. package/dist/core/statusline-install.js +27 -4
  61. package/dist/core/transcript-summary.d.ts +84 -9
  62. package/dist/core/transcript-summary.js +283 -49
  63. package/dist/core/uninstall.d.ts +4 -0
  64. package/dist/core/uninstall.js +68 -36
  65. package/dist/core/v1-bootstrap.d.ts +1 -1
  66. package/dist/core/v1-bootstrap.js +38 -9
  67. package/dist/engine/acted-on-evidence.d.ts +8 -0
  68. package/dist/engine/acted-on-evidence.js +38 -0
  69. package/dist/engine/block-judge.d.ts +3 -1
  70. package/dist/engine/block-judge.js +4 -3
  71. package/dist/engine/compound-cli.d.ts +26 -2
  72. package/dist/engine/compound-cli.js +143 -19
  73. package/dist/engine/compound-lifecycle.d.ts +36 -2
  74. package/dist/engine/compound-lifecycle.js +131 -11
  75. package/dist/engine/compound-loop.d.ts +4 -0
  76. package/dist/engine/compound-loop.js +93 -18
  77. package/dist/engine/correction-cluster-runner.d.ts +11 -1
  78. package/dist/engine/correction-cluster-runner.js +39 -15
  79. package/dist/engine/correction-clustering.d.ts +11 -0
  80. package/dist/engine/correction-clustering.js +20 -3
  81. package/dist/engine/lifecycle/lifecycle-cli.js +10 -3
  82. package/dist/engine/lifecycle/meta-reclassifier.d.ts +9 -0
  83. package/dist/engine/lifecycle/meta-reclassifier.js +15 -3
  84. package/dist/engine/lifecycle/orchestrator.js +3 -2
  85. package/dist/engine/lifecycle/signals.d.ts +19 -1
  86. package/dist/engine/lifecycle/signals.js +61 -2
  87. package/dist/engine/lifecycle/trigger-t1-correction.d.ts +1 -1
  88. package/dist/engine/lifecycle/trigger-t1-correction.js +9 -28
  89. package/dist/engine/lifecycle/trigger-t5-conflict.d.ts +8 -0
  90. package/dist/engine/lifecycle/trigger-t5-conflict.js +60 -2
  91. package/dist/engine/roi-demotion.d.ts +11 -0
  92. package/dist/engine/roi-demotion.js +50 -8
  93. package/dist/engine/rule-detectability.d.ts +39 -0
  94. package/dist/engine/rule-detectability.js +66 -0
  95. package/dist/engine/rule-project-cli.d.ts +25 -0
  96. package/dist/engine/rule-project-cli.js +148 -0
  97. package/dist/engine/rule-recovery-cli.d.ts +21 -0
  98. package/dist/engine/rule-recovery-cli.js +265 -0
  99. package/dist/engine/rule-toggle-cli.d.ts +14 -2
  100. package/dist/engine/rule-toggle-cli.js +94 -6
  101. package/dist/engine/skill-promoter.d.ts +14 -8
  102. package/dist/engine/skill-promoter.js +57 -85
  103. package/dist/engine/solution-format.d.ts +26 -1
  104. package/dist/engine/solution-format.js +65 -3
  105. package/dist/engine/solution-habit.d.ts +1 -0
  106. package/dist/engine/solution-habit.js +22 -0
  107. package/dist/engine/solution-index.d.ts +5 -0
  108. package/dist/engine/solution-index.js +32 -0
  109. package/dist/engine/solution-matcher-eval.js +4 -4
  110. package/dist/engine/solution-matcher.js +15 -13
  111. package/dist/engine/solution-scope.d.ts +11 -0
  112. package/dist/engine/solution-scope.js +19 -0
  113. package/dist/engine/solution-writer.d.ts +3 -1
  114. package/dist/engine/solution-writer.js +3 -2
  115. package/dist/engine/term-normalizer.js +49 -0
  116. package/dist/fgx.js +1 -1
  117. package/dist/forge/cli.js +51 -8
  118. package/dist/forge/evidence-processor.js +6 -0
  119. package/dist/hooks/context-guard.d.ts +0 -22
  120. package/dist/hooks/context-guard.js +22 -55
  121. package/dist/hooks/context-usage.d.ts +21 -0
  122. package/dist/hooks/context-usage.js +103 -0
  123. package/dist/hooks/dangerous-patterns.json +1 -16
  124. package/dist/hooks/db-guard.d.ts +1 -1
  125. package/dist/hooks/db-guard.js +21 -30
  126. package/dist/hooks/hook-config.d.ts +2 -0
  127. package/dist/hooks/hook-config.js +5 -1
  128. package/dist/hooks/hooks-generator.d.ts +4 -0
  129. package/dist/hooks/hooks-generator.js +10 -4
  130. package/dist/hooks/permission-handler.js +23 -3
  131. package/dist/hooks/post-tool-use.js +14 -10
  132. package/dist/hooks/pre-tool-use.d.ts +17 -3
  133. package/dist/hooks/pre-tool-use.js +143 -30
  134. package/dist/hooks/rate-limiter.js +12 -7
  135. package/dist/hooks/secret-filter.js +15 -4
  136. package/dist/hooks/session-end.d.ts +2 -2
  137. package/dist/hooks/session-end.js +13 -7
  138. package/dist/hooks/session-recovery.js +79 -50
  139. package/dist/hooks/shared/command-analyzer.d.ts +45 -0
  140. package/dist/hooks/shared/command-analyzer.js +972 -0
  141. package/dist/hooks/shared/command-parser.d.ts +5 -29
  142. package/dist/hooks/shared/command-parser.js +65 -35
  143. package/dist/hooks/shared/commit-guard.d.ts +15 -0
  144. package/dist/hooks/shared/commit-guard.js +176 -0
  145. package/dist/hooks/shared/hook-response.d.ts +6 -0
  146. package/dist/hooks/shared/hook-response.js +12 -0
  147. package/dist/hooks/shared/hook-timing.js +9 -3
  148. package/dist/hooks/shared/injection-caps.d.ts +32 -2
  149. package/dist/hooks/shared/injection-caps.js +73 -2
  150. package/dist/hooks/shared/is-main.d.ts +8 -0
  151. package/dist/hooks/shared/is-main.js +20 -0
  152. package/dist/hooks/shared/tool-response.d.ts +6 -0
  153. package/dist/hooks/shared/tool-response.js +30 -0
  154. package/dist/hooks/slop-detector.js +6 -3
  155. package/dist/hooks/solution-injector.d.ts +23 -0
  156. package/dist/hooks/solution-injector.js +102 -101
  157. package/dist/hooks/stop-guard.d.ts +11 -1
  158. package/dist/hooks/stop-guard.js +28 -11
  159. package/dist/hooks/subagent-stop-guard.js +2 -1
  160. package/dist/hooks/subagent-tracker.js +2 -1
  161. package/dist/host/capabilities-codex.js +1 -0
  162. package/dist/host/claude-shim.d.ts +24 -0
  163. package/dist/host/claude-shim.js +68 -0
  164. package/dist/host/codex-hook-shim.d.ts +3 -1
  165. package/dist/host/codex-hook-shim.js +7 -5
  166. package/dist/host/codex-notify.js +1 -1
  167. package/dist/host/codex-rules-context.d.ts +6 -4
  168. package/dist/host/codex-rules-context.js +11 -24
  169. package/dist/host/exec-host.d.ts +5 -1
  170. package/dist/host/exec-host.js +15 -4
  171. package/dist/host/install-claude.d.ts +47 -14
  172. package/dist/host/install-claude.js +302 -155
  173. package/dist/host/install-codex.d.ts +20 -0
  174. package/dist/host/install-codex.js +32 -1
  175. package/dist/host/install-opencode.d.ts +3 -1
  176. package/dist/host/install-opencode.js +6 -3
  177. package/dist/host/install-orchestrator.js +14 -1
  178. package/dist/host/opencode/translate.d.ts +1 -1
  179. package/dist/host/opencode/translate.js +5 -3
  180. package/dist/host/projection.d.ts +9 -1
  181. package/dist/host/projection.js +19 -2
  182. package/dist/mcp/server.js +5 -0
  183. package/dist/mcp/solution-reader.d.ts +5 -5
  184. package/dist/mcp/solution-reader.js +13 -35
  185. package/dist/mcp/tools.js +18 -1
  186. package/dist/renderer/inspect-renderer.js +4 -2
  187. package/dist/renderer/render-report.d.ts +22 -0
  188. package/dist/renderer/render-report.js +29 -0
  189. package/dist/renderer/rule-renderer.d.ts +28 -2
  190. package/dist/renderer/rule-renderer.js +91 -76
  191. package/dist/store/evidence-store.js +34 -6
  192. package/dist/store/rule-lifecycle.d.ts +3 -1
  193. package/dist/store/rule-lifecycle.js +10 -0
  194. package/dist/store/rule-scope.d.ts +7 -0
  195. package/dist/store/rule-scope.js +54 -0
  196. package/dist/store/rule-store.d.ts +29 -3
  197. package/dist/store/rule-store.js +110 -26
  198. package/dist/store/types.d.ts +22 -2
  199. package/dist/way/cli.d.ts +1 -0
  200. package/dist/way/cli.js +313 -0
  201. package/dist/way/compile.d.ts +22 -0
  202. package/dist/way/compile.js +408 -0
  203. package/dist/way/conflict.d.ts +2 -0
  204. package/dist/way/conflict.js +18 -0
  205. package/dist/way/draft.d.ts +43 -0
  206. package/dist/way/draft.js +335 -0
  207. package/dist/way/extract.d.ts +17 -0
  208. package/dist/way/extract.js +172 -0
  209. package/dist/way/io.d.ts +79 -0
  210. package/dist/way/io.js +425 -0
  211. package/dist/way/similar.d.ts +2 -0
  212. package/dist/way/similar.js +30 -0
  213. package/dist/way/types.d.ts +98 -0
  214. package/dist/way/types.js +2 -0
  215. package/package.json +1 -1
  216. package/plugin.json +1 -1
  217. package/scripts/postinstall.js +76 -899
  218. package/dist/core/health-cli.d.ts +0 -25
  219. package/dist/core/health-cli.js +0 -90
  220. package/dist/host/parity-harness.d.ts +0 -70
  221. package/dist/host/parity-harness.js +0 -287
@@ -0,0 +1,368 @@
1
+ /**
2
+ * 학습 흐름 상태 (D8) — 수집 → 추출 → 저장 → 주입 → 사용 → 피드백.
3
+ *
4
+ * 점수(X/100) 대신 단계별로 "입력이 무엇이고, 마지막으로 성공한 때가 언제이고, 최근 N일에 몇 건인지"를 보여 준다.
5
+ * 0건이면 그 단계가 끊겼을 수 있다는 경고를 낸다. 읽기 실패는 0건과 구분해 사유를 표시한다.
6
+ * 모든 시각은 파일 mtime 이 아니라 기록된 이벤트/frontmatter 시각이다 (cp -r 로 숫자가 변하지 않게).
7
+ */
8
+ import * as fs from 'node:fs';
9
+ import * as path from 'node:path';
10
+ import { execFileSync } from 'node:child_process';
11
+ import { ME_BEHAVIOR, ME_SOLUTIONS, SESSIONS_DIR, STATE_DIR, V1_SESSIONS_DIR } from './paths.js';
12
+ import { logFilesWithin } from '../engine/lifecycle/rotated-logs.js';
13
+ import { scanRuleFiles } from '../store/rule-store.js';
14
+ import { getHaikuConsentState, apiBillingNote } from './compound-consent.js';
15
+ import { summarizeRenderReport } from '../renderer/render-report.js';
16
+ const DAY = 24 * 60 * 60 * 1000;
17
+ export const FLOW_WINDOW_DAYS = 7;
18
+ /** 디렉터리/파일을 읽을 수 없는 사유. 없으면(정상 또는 부재) null. */
19
+ export function unreadable(p) {
20
+ try {
21
+ if (!fs.existsSync(p))
22
+ return null;
23
+ fs.accessSync(p, fs.constants.R_OK | (fs.statSync(p).isDirectory() ? fs.constants.X_OK : 0));
24
+ if (fs.statSync(p).isDirectory())
25
+ fs.readdirSync(p);
26
+ return null;
27
+ }
28
+ catch (e) {
29
+ return e instanceof Error ? e.message : String(e);
30
+ }
31
+ }
32
+ /**
33
+ * 현재 로그 + 회전본. 회전 방식이 둘이다: rotateIfBig(`<p>.<timestamp>`)와 state-gc(`<p>.1`, `<p>.2`).
34
+ * 둘 다 읽어야 회전 직후에도 최근 기록이 사라지지 않는다. 오래된 것부터.
35
+ */
36
+ export function logFilesWithRotated(p, days = FLOW_WINDOW_DAYS * 2, now = Date.now()) {
37
+ const numbered = [`${p}.2`, `${p}.1`].filter((f) => fs.existsSync(f));
38
+ const stamped = logFilesWithin(p, days, now).filter((f) => f !== p);
39
+ return [...numbered, ...stamped, p];
40
+ }
41
+ export function readJsonlTimes(p, key, filter) {
42
+ const err = unreadable(p);
43
+ if (err)
44
+ return { times: [], error: err };
45
+ const files = logFilesWithRotated(p).filter((f) => fs.existsSync(f));
46
+ if (files.length === 0)
47
+ return { times: [] };
48
+ const times = [];
49
+ try {
50
+ for (const line of files.flatMap((f) => fs.readFileSync(f, 'utf-8').split('\n'))) {
51
+ if (!line.trim())
52
+ continue;
53
+ try {
54
+ const e = JSON.parse(line);
55
+ if (filter && !filter(e))
56
+ continue;
57
+ const raw = e[key];
58
+ const t = typeof raw === 'string' ? Date.parse(raw) : typeof raw === 'number' ? raw : NaN;
59
+ if (Number.isFinite(t))
60
+ times.push(t);
61
+ }
62
+ catch { /* 깨진 줄은 건너뜀 */ }
63
+ }
64
+ }
65
+ catch (e) {
66
+ return { times: [], error: e instanceof Error ? e.message : String(e) };
67
+ }
68
+ return { times };
69
+ }
70
+ /** frontmatter 시각 파싱. `2026-11-01` 처럼 날짜만 있으면 UTC 가 아니라 로컬 자정으로 본다 (시간대에 따라 하루 어긋나지 않게). */
71
+ export function parseCreated(raw) {
72
+ const m = raw.trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);
73
+ if (m)
74
+ return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])).getTime();
75
+ return Date.parse(raw);
76
+ }
77
+ const pad2 = (n) => String(n).padStart(2, '0');
78
+ /** 로컬 시각 `YYYY-MM-DD HH:mm` */
79
+ export function localStamp(t) {
80
+ const d = new Date(t);
81
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
82
+ }
83
+ /** 로컬 달력 기준 며칠 전인가 (자정 경계). */
84
+ function calendarDaysAgo(t, now) {
85
+ const mid = (x) => { const d = new Date(x); return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); };
86
+ return Math.round((mid(now) - mid(t)) / DAY);
87
+ }
88
+ /** hook 경로에서 후보가 1개 이상 나온 recall — 흐름의 "주입"과 통계의 "Recall hits"/주간 추세가 같은 정의를 쓴다. */
89
+ export function isInjectedRecall(e) {
90
+ return e.source === 'hook' && Array.isArray(e.candidates) && e.candidates.length > 0;
91
+ }
92
+ /** 새로 저장된 것(솔루션 created + 룰 created_at)의 시각 — 흐름의 "저장"과 통계의 "Saved"가 같은 정의를 쓴다. */
93
+ export function readSavedTimes() {
94
+ const sol = readSolutionCreations();
95
+ const rules = scanRuleFiles();
96
+ const ruleTimes = rules.rules.map((r) => Date.parse(r.created_at)).filter(Number.isFinite);
97
+ return { times: [...sol.times, ...ruleTimes], error: sol.error ?? rules.dirError, undated: sol.undated };
98
+ }
99
+ /** 솔루션 생성 시각 — frontmatter `created`. mtime 은 복사·touch 로 바뀌므로 쓰지 않는다. */
100
+ export function readSolutionCreations() {
101
+ const out = { times: [], total: 0, undated: 0 };
102
+ const err = unreadable(ME_SOLUTIONS);
103
+ if (err) {
104
+ out.error = err;
105
+ return out;
106
+ }
107
+ if (!fs.existsSync(ME_SOLUTIONS))
108
+ return out;
109
+ for (const f of fs.readdirSync(ME_SOLUTIONS)) {
110
+ if (!f.endsWith('.md'))
111
+ continue;
112
+ out.total++;
113
+ try {
114
+ const head = fs.readFileSync(path.join(ME_SOLUTIONS, f), 'utf-8').split('\n').slice(0, 60).join('\n');
115
+ const m = head.match(/^created:\s*["']?([^"'\n]+?)["']?\s*$/m);
116
+ const t = m ? parseCreated(m[1]) : NaN;
117
+ if (Number.isFinite(t))
118
+ out.times.push(t);
119
+ else
120
+ out.undated++;
121
+ }
122
+ catch {
123
+ out.undated++;
124
+ }
125
+ }
126
+ return out;
127
+ }
128
+ export function readEvidenceCounts() {
129
+ const r = { user: { times: [] }, mined: { times: [] }, other: { times: [] } };
130
+ const err = unreadable(ME_BEHAVIOR);
131
+ if (err) {
132
+ for (const k of ['user', 'mined', 'other'])
133
+ r[k].error = err;
134
+ return r;
135
+ }
136
+ if (!fs.existsSync(ME_BEHAVIOR))
137
+ return r;
138
+ for (const f of fs.readdirSync(ME_BEHAVIOR)) {
139
+ if (!f.endsWith('.json'))
140
+ continue;
141
+ try {
142
+ const e = JSON.parse(fs.readFileSync(path.join(ME_BEHAVIOR, f), 'utf-8'));
143
+ const t = Date.parse(e.timestamp ?? '');
144
+ if (!Number.isFinite(t))
145
+ continue;
146
+ if (e.type === 'explicit_correction')
147
+ (e.source_component === 'auto-compound-miner' ? r.mined : r.user).times.push(t);
148
+ else
149
+ r.other.times.push(t);
150
+ }
151
+ catch { /* 깨진 evidence 는 건너뜀 */ }
152
+ }
153
+ return r;
154
+ }
155
+ export const countSince = (times, days, now = Date.now()) => times.filter((t) => t >= now - days * DAY).length;
156
+ export const lastOf = (times) => (times.length ? Math.max(...times) : null);
157
+ export function formatWhen(t, now = Date.now()) {
158
+ if (t === null)
159
+ return '없음';
160
+ const d = calendarDaysAgo(t, now);
161
+ const date = localStamp(t);
162
+ return d <= 0 ? `${date} (오늘)` : `${date} (${d}일 전)`;
163
+ }
164
+ export function readExtractionEvents() {
165
+ const p = path.join(STATE_DIR, 'extraction-events.jsonl');
166
+ const r = { ok: [], failed: [], skipped: {}, trailingFailures: 0 };
167
+ const err = unreadable(p);
168
+ if (err) {
169
+ r.error = err;
170
+ return r;
171
+ }
172
+ const files = logFilesWithRotated(p, 60).filter((f) => fs.existsSync(f));
173
+ if (files.length === 0)
174
+ return r;
175
+ const seq = [];
176
+ for (const line of files.flatMap((f) => fs.readFileSync(f, 'utf-8').split('\n'))) {
177
+ if (!line.trim())
178
+ continue;
179
+ try {
180
+ const e = JSON.parse(line);
181
+ if (e.kind)
182
+ continue; // 호출별/대기열 이벤트(haiku-call, queued, queue-retry)는 러너 실행 횟수에 세지 않는다
183
+ const t = Date.parse(e.at ?? '');
184
+ if (!Number.isFinite(t))
185
+ continue;
186
+ seq.push({ t, ok: e.ok !== false, error: e.error });
187
+ if (typeof e.skipped === 'string')
188
+ r.skipped[e.skipped] = (r.skipped[e.skipped] ?? 0) + 1;
189
+ }
190
+ catch { /* skip */ }
191
+ }
192
+ seq.sort((a, b) => a.t - b.t);
193
+ for (const s of seq)
194
+ (s.ok ? r.ok : r.failed).push(s.t);
195
+ for (let i = seq.length - 1; i >= 0 && !seq[i].ok; i--) {
196
+ r.trailingFailures++;
197
+ r.lastError ??= seq[i].error;
198
+ }
199
+ return r;
200
+ }
201
+ /** 마지막 추출 완료 시각 — last-auto-compound.json(completedAt) 단일 소스. status·inspect 가 같은 값을 쓴다. */
202
+ export function lastExtractionTime() {
203
+ for (const name of ['last-auto-compound.json', 'last-extraction.json']) {
204
+ try {
205
+ const d = JSON.parse(fs.readFileSync(path.join(STATE_DIR, name), 'utf-8'));
206
+ const t = Date.parse(d.completedAt ?? d.timestamp ?? d.date ?? '');
207
+ if (Number.isFinite(t))
208
+ return t;
209
+ }
210
+ catch { /* 다음 후보 */ }
211
+ }
212
+ return null;
213
+ }
214
+ export function formatLastExtraction(now = Date.now()) {
215
+ const t = lastExtractionTime();
216
+ if (t === null)
217
+ return 'never';
218
+ const d = calendarDaysAgo(t, now);
219
+ const date = localStamp(t).slice(0, 10);
220
+ return d <= 0 ? `${date} (today)` : d === 1 ? `${date} (yesterday)` : `${date} (${d}d ago)`;
221
+ }
222
+ /**
223
+ * 오늘(로컬 날짜) Haiku 호출 수. 호출 하나하나가 extraction-events 의 `haiku-call` 이벤트라 그대로 센다.
224
+ * 세션별 호출 수(한 세션이 하루에 몇 번 불렀나)도 집계해 과다 호출을 눈으로 볼 수 있게 한다.
225
+ */
226
+ export function haikuCallStats(now = Date.now()) {
227
+ const r = { today: 0, failedToday: 0, maxPerSession: 0, sessionsToday: 0 };
228
+ const p = path.join(STATE_DIR, 'extraction-events.jsonl');
229
+ const files = logFilesWithRotated(p, 2, now).filter((f) => fs.existsSync(f));
230
+ const day = localStamp(now).slice(0, 10);
231
+ const per = new Map();
232
+ for (const line of files.flatMap((f) => fs.readFileSync(f, 'utf-8').split('\n'))) {
233
+ if (!line.includes('haiku-call'))
234
+ continue;
235
+ try {
236
+ const e = JSON.parse(line);
237
+ const t = Date.parse(e.at ?? '');
238
+ if (e.kind !== 'haiku-call' || !Number.isFinite(t) || localStamp(t).slice(0, 10) !== day)
239
+ continue;
240
+ r.today++;
241
+ if (e.outcome !== 'ok')
242
+ r.failedToday++;
243
+ const k = e.sessionId ?? '(unknown)';
244
+ per.set(k, (per.get(k) ?? 0) + 1);
245
+ }
246
+ catch { /* skip */ }
247
+ }
248
+ r.sessionsToday = per.size;
249
+ r.maxPerSession = Math.max(0, ...per.values());
250
+ return r;
251
+ }
252
+ export function haikuUsageLine(now = Date.now()) {
253
+ const u = haikuCallStats(now);
254
+ return `오늘 호출 ${u.today}회${u.failedToday ? ` (실패 ${u.failedToday})` : ''}${u.sessionsToday ? ` · 세션 ${u.sessionsToday}개, 세션당 최대 ${u.maxPerSession}회` : ''}`;
255
+ }
256
+ function claudeOnPath() {
257
+ try {
258
+ execFileSync(process.platform === 'win32' ? 'where' : 'which', ['claude'], { stdio: 'pipe' });
259
+ return true;
260
+ }
261
+ catch {
262
+ return false;
263
+ }
264
+ }
265
+ function readHaikuStatusSync() {
266
+ try {
267
+ return JSON.parse(fs.readFileSync(path.join(STATE_DIR, 'haiku-status.json'), 'utf-8'));
268
+ }
269
+ catch {
270
+ return null;
271
+ }
272
+ }
273
+ /** 재시도 대기 중인 추출 작업 수 (D4). */
274
+ function queueSuffix() {
275
+ try {
276
+ const q = JSON.parse(fs.readFileSync(path.join(STATE_DIR, 'extraction-queue.json'), 'utf-8')).entries ?? [];
277
+ return q.length > 0 ? ` · 재시도 대기 ${q.length}건` : '';
278
+ }
279
+ catch {
280
+ return '';
281
+ }
282
+ }
283
+ export function haikuStatus(ev = readExtractionEvents()) {
284
+ const c = getHaikuConsentState();
285
+ if (!c.enabled)
286
+ return { state: 'off', detail: `꺼짐 (${c.source}) — 결정론 룰 승급·세션 검색만 동작. 켜기: forgen compound consent on` };
287
+ if (!claudeOnPath())
288
+ return { state: 'unavailable', detail: '호출 불가 — claude CLI 를 PATH 에서 찾지 못함. 룰 승급·세션 검색은 계속 동작' };
289
+ const last = readHaikuStatusSync();
290
+ if (last && !last.ok && last.outcome === 'unavailable')
291
+ return { state: 'unavailable', detail: `호출 불가 — ${last.reason ?? '원인 미상'}. 룰 승급·세션 검색은 계속 동작` };
292
+ if (ev.trailingFailures >= 2)
293
+ return { state: 'failing', detail: `연속 실패 ${ev.trailingFailures}회${ev.lastError ? ` — ${ev.lastError.slice(0, 80)}` : ''}${queueSuffix()}` };
294
+ const billing = apiBillingNote();
295
+ return { state: 'on', detail: `켜짐 (${c.source === 'default' ? '기본값' : c.source}) — 세션 요약을 내 Haiku 로 전송${queueSuffix()} · ${haikuUsageLine()}${billing ? `\n ! API 과금 계정으로 호출됨 (ANTHROPIC_API_KEY 설정됨). 끄기: forgen compound consent off` : '. 끄기: forgen compound consent off'}` };
296
+ }
297
+ export function computeFlow(days = FLOW_WINDOW_DAYS, now = Date.now()) {
298
+ const ev = readEvidenceCounts();
299
+ const ext = readExtractionEvents();
300
+ const saved = readSavedTimes();
301
+ const matchLog = readJsonlTimes(path.join(STATE_DIR, 'match-eval-log.jsonl'), 'ts', isInjectedRecall);
302
+ const referenced = readJsonlTimes(path.join(STATE_DIR, 'implicit-feedback.jsonl'), 'at', (e) => e.type === 'recall_referenced');
303
+ const acks = readJsonlTimes(path.join(STATE_DIR, 'enforcement', 'acknowledgments.jsonl'), 'at');
304
+ const verdicts = readJsonlTimes(path.join(STATE_DIR, 'enforcement', 'verdicts.jsonl'), 'at');
305
+ const render = summarizeRenderReport();
306
+ const extractTimes = ext.ok;
307
+ const lastRun = lastExtractionTime();
308
+ const stage = (label, input, r, extra) => ({ label, input, last: lastOf(r.times), count: countSince(r.times, days, now), error: r.error, ...extra });
309
+ return [
310
+ stage('수집', '사용자 교정 (hook 기록)', ev.user),
311
+ stage('추출', 'auto-compound 실행 (세션 종료 후)', { times: extractTimes.length === 0 && !ext.failed.length && lastRun !== null ? [lastRun] : extractTimes, error: ext.error }, {
312
+ last: lastRun ?? lastOf(extractTimes),
313
+ note: ext.trailingFailures >= 1 ? `최근 ${ext.trailingFailures}회 연속 실패`
314
+ : Object.keys(ext.skipped).length > 0 ? `일찍 끝난 실행: ${Object.entries(ext.skipped).map(([k, v]) => `${k} ${v}`).join(', ')}`
315
+ : extractTimes.length === 0 && !ext.failed.length && lastRun !== null ? '실행 이력(extraction-events)은 이 버전부터 쌓임 — 마지막 1회만 확인됨' : undefined,
316
+ }),
317
+ stage('저장', '새 솔루션(created) + 새 룰(created_at)', saved, { note: saved.undated > 0 ? `created 없는 솔루션 ${saved.undated}개는 집계 제외` : undefined }),
318
+ stage('주입', '후보가 나온 recall (hook)', matchLog, {
319
+ note: render ? `룰 렌더 마지막 ${formatWhen(Date.parse(render.at), now)}: 포함 ${render.included} · 누락 ${render.omitted}${render.omitted ? ` (${Object.entries(render.omittedByStrength).map(([k, v]) => `${k} ${v}`).join(', ')})` : ''}` : '룰 렌더 기록 없음',
320
+ }),
321
+ stage('사용', '응답에 인용된 recall', referenced),
322
+ stage('피드백', '차단 승인(ack) + 차단 판정', { times: [...acks.times, ...verdicts.times], error: acks.error ?? verdicts.error }),
323
+ ];
324
+ }
325
+ /** 이 홈에 남은 세션 기록 수 (state/sessions + sessions). 큰 쪽을 쓴다. */
326
+ export function flowSessionCount() {
327
+ const n = (d) => { try {
328
+ return fs.readdirSync(d).filter((f) => f.endsWith('.json')).length;
329
+ }
330
+ catch {
331
+ return 0;
332
+ } };
333
+ return Math.max(n(V1_SESSIONS_DIR), n(SESSIONS_DIR));
334
+ }
335
+ /** 경고를 내려면 필요한 최소 세션 수. 이보다 적으면 0건이 정상일 수 있다. */
336
+ export const FLOW_MIN_SESSIONS = 3;
337
+ /**
338
+ * 0건 경고 판정. 활동이 충분할 때만, 그리고 그 단계가 정상적으로 0일 수 없을 때만 낸다.
339
+ * 추출·저장·주입: 세션이 충분한데 0건이면 경고.
340
+ * 사용: 주입이 있는데 인용이 0건일 때만 (주입이 없으면 쓸 것도 없다).
341
+ * 수집·피드백: 사용자가 교정·차단을 만나야 쌓이는 값이라 0건이 정상 — 경고하지 않는다.
342
+ */
343
+ export function flowWarning(stage, stages, sessions) {
344
+ if (stage.error || stage.count > 0 || sessions < FLOW_MIN_SESSIONS)
345
+ return null;
346
+ if (stage.label === '추출' || stage.label === '저장' || stage.label === '주입')
347
+ return '⚠ 0건 — 이 단계가 끊겼을 수 있음';
348
+ if (stage.label === '사용')
349
+ return (stages.find((x) => x.label === '주입')?.count ?? 0) > 0 ? '⚠ 주입은 있는데 인용 0건' : null;
350
+ return null;
351
+ }
352
+ export function renderFlow(stages, days = FLOW_WINDOW_DAYS, now = Date.now(), sessions = flowSessionCount()) {
353
+ const lines = [];
354
+ lines.push(` 흐름 (최근 ${days}일) 수집 → 추출 → 저장 → 주입 → 사용 → 피드백`);
355
+ if (sessions === 0)
356
+ lines.push(' 아직 세션 없음 — 첫 세션을 마치면 채워집니다');
357
+ for (const s of stages) {
358
+ if (s.error) {
359
+ lines.push(` ${s.label} 읽을 수 없음 — ${s.error.slice(0, 80)}`);
360
+ continue;
361
+ }
362
+ const w = flowWarning(s, stages, sessions);
363
+ lines.push(` ${s.label} ${String(s.count).padStart(4)}건 마지막 ${formatWhen(s.last, now)} ← ${s.input}${w ? ` ${w}` : ''}`);
364
+ if (s.note)
365
+ lines.push(` ${s.note}`);
366
+ }
367
+ return lines;
368
+ }
@@ -13,15 +13,14 @@ import * as fs from 'node:fs';
13
13
  import * as os from 'node:os';
14
14
  import * as path from 'node:path';
15
15
  import { fileURLToPath } from 'node:url';
16
- import { buildEnv, generateClaudeRuleFiles, registerTmuxBindings } from './config-injector.js';
16
+ import { buildEnv, registerTmuxBindings } from './config-injector.js';
17
17
  import { createLogger } from './logger.js';
18
18
  import { HANDOFFS_DIR, ME_BEHAVIOR, ME_DIR, ME_RULES, ME_SKILLS, ME_SOLUTIONS, SESSIONS_DIR, STATE_DIR, FORGEN_HOME } from './paths.js';
19
- import { RULE_FILE_CAPS } from '../hooks/shared/injection-caps.js';
20
- import { recordRenderedFiles } from './rendered-rules-manifest.js';
21
19
  import { rollbackSettings, } from './settings-lock.js';
22
20
  import { bootstrapV1Session, ensureV1Directories } from './v1-bootstrap.js';
23
21
  import { injectSettings } from './settings-injector.js';
24
- import { installAgents, installSlashCommands } from './installer.js';
22
+ import { installSlashCommands } from './installer.js';
23
+ import { installGlobalAgents } from '../host/install-claude.js';
25
24
  import { getHostCapabilities } from '../host/capabilities-registry.js';
26
25
  import { getProjection } from '../host/projection.js';
27
26
  const log = createLogger('harness');
@@ -107,40 +106,8 @@ function ensureDirectories() {
107
106
  ensureV1Directories();
108
107
  }
109
108
  export { rollbackSettings };
110
- // ── Rule File Injection ──
111
- function injectClaudeRuleFiles(cwd, ruleFiles) {
112
- const PER_RULE_CAP = RULE_FILE_CAPS.perRuleFile;
113
- const TOTAL_CAP = RULE_FILE_CAPS.totalRuleFiles;
114
- const projectRulesDir = path.join(cwd, '.claude', 'rules');
115
- fs.mkdirSync(projectRulesDir, { recursive: true });
116
- let totalWritten = 0;
117
- const writtenForManifest = {};
118
- for (const [filename, content] of Object.entries(ruleFiles)) {
119
- const capped = content.length > PER_RULE_CAP
120
- ? `${content.slice(0, PER_RULE_CAP)}\n... (capped at rule file limit)\n`
121
- : content;
122
- if (totalWritten + capped.length > TOTAL_CAP) {
123
- log.debug(`rules/ 총량 캡 도달, ${filename} 생략`);
124
- break;
125
- }
126
- // ADR-010 W1-3 (F6 수정): 모든 규칙 파일은 프로젝트 스코프로만 주입한다.
127
- // 이전에는 `forge-*` 파일명이 글로벌 ~/.claude/rules/ 로 라우팅되어
128
- // 프로젝트 맥락의 behavioral 패턴이 전 프로젝트 세션에 주입됐다.
129
- // 목표 상태: 글로벌 rules 디렉토리에 forgen 산출물 0개.
130
- const target = path.join(projectRulesDir, filename);
131
- fs.writeFileSync(target, capped);
132
- writtenForManifest[target] = capped;
133
- totalWritten += capped.length;
134
- }
135
- // ADR-010 W1-1: 쓴 그대로의 content-hash 를 manifest 에 기록 —
136
- // reclaimer 가 "forgen 산출물 그대로"와 "사용자 편집본"을 구분하는 근거.
137
- try {
138
- const pkg = JSON.parse(fs.readFileSync(path.join(getPackageRoot(), 'package.json'), 'utf-8'));
139
- recordRenderedFiles(writtenForManifest, String(pkg.version ?? '0.0.0'));
140
- }
141
- catch (e) {
142
- log.debug('rendered-rules manifest 기록 실패 (fail-open)', e);
143
- }
109
+ /** 옛 위치의 규칙 파일과 CLAUDE.md 마커 블록 정리. */
110
+ function cleanupLegacyRuleArtifacts(cwd) {
144
111
  // 마이그레이션 (W1-3): 구버전이 글로벌에 쓴 forge-behavioral.md 회수.
145
112
  // (tenetx 계열 글로벌 잔재는 W1-1 reclaimer 의 영역)
146
113
  const legacyGlobalBehavioral = path.join(os.homedir(), '.claude', 'rules', 'forge-behavioral.md');
@@ -378,9 +345,14 @@ async function prepareClaudeSession(ctx) {
378
345
  throw e;
379
346
  }
380
347
  }
381
- installAgents(cwd, pkgRoot);
382
- const ruleFiles = generateClaudeRuleFiles(cwd, v1Result.renderedRules);
383
- injectClaudeRuleFiles(cwd, ruleFiles);
348
+ // ch-* agents 는 프로젝트 cwd 가 아니라 전역(~/.claude/agents)에 둔다. 직접 실행에도 공급되고 프로젝트를 건드리지 않는다.
349
+ try {
350
+ installGlobalAgents({ pkgRoot, agentsDir: path.join(os.homedir(), '.claude', 'agents') });
351
+ }
352
+ catch (e) {
353
+ log.debug('전역 agents 설치 실패', e);
354
+ }
355
+ cleanupLegacyRuleArtifacts(cwd);
384
356
  installSlashCommands(cwd, pkgRoot);
385
357
  }
386
358
  /**
@@ -410,7 +382,7 @@ async function prepareOpencodeSession(_ctx) {
410
382
  * (예: OpenCode, P1) 엔트리 누락은 컴파일 타임에 걸린다.
411
383
  *
412
384
  * capabilities/projection 은 현재 prepareHarness 자체가 소비하지 않지만(각각
413
- * capabilities-registry.ts / parity-harness.ts 가 독립 소비), HostBinding 계약의
385
+ * capabilities-registry.ts 가 독립 소비), HostBinding 계약의
414
386
  * 일부로 함께 선언해 두어 향후 확장(§4.1 P1) 시 registry 엔트리 하나만 추가하면
415
387
  * 되는 형태를 만든다.
416
388
  */
@@ -7,12 +7,13 @@
7
7
  import * as fs from 'node:fs';
8
8
  import * as path from 'node:path';
9
9
  import { loadProfile } from '../store/profile-store.js';
10
- import { loadAllRules, loadActiveRules } from '../store/rule-store.js';
10
+ import { loadAllRules, loadActiveRules, scanRuleFiles } from '../store/rule-store.js';
11
+ import { formatLastExtraction } from './flow-status.js';
12
+ import { readJsonlWindow, isConfirmedBypass, ROTATED_KEEP_DAYS } from '../engine/lifecycle/signals.js';
11
13
  import { loadRecentEvidence, loadAllEvidence } from '../store/evidence-store.js';
12
14
  import { loadRecentSessions } from '../store/session-state-store.js';
13
15
  import * as inspect from '../renderer/inspect-renderer.js';
14
16
  import { ME_SOLUTIONS, STATE_DIR } from './paths.js';
15
- import { safeReadJSON } from '../hooks/shared/atomic-write.js';
16
17
  export async function handleInspect(args) {
17
18
  const sub = args[0];
18
19
  if (sub === 'profile') {
@@ -42,16 +43,8 @@ export async function handleInspect(args) {
42
43
  return 0;
43
44
  return fs.readdirSync(ME_SOLUTIONS).filter(f => f.endsWith('.md')).length;
44
45
  })();
45
- const lastExtractionData = safeReadJSON(path.join(STATE_DIR, 'last-extraction.json'), null);
46
- const lastExtractionTs = lastExtractionData?.timestamp ?? lastExtractionData?.date;
47
- const lastExtractionLabel = (() => {
48
- if (!lastExtractionTs)
49
- return 'never';
50
- const d = new Date(lastExtractionTs);
51
- const diffDays = Math.floor((Date.now() - d.getTime()) / (24 * 60 * 60 * 1000));
52
- const dateStr = d.toISOString().slice(0, 10);
53
- return diffDays === 0 ? `${dateStr} (today)` : `${dateStr} (${diffDays} day${diffDays > 1 ? 's' : ''} ago)`;
54
- })();
46
+ // status 와 같은 단일 소스 (이전엔 서로 다른 파일을 읽어 today/never 모순)
47
+ const lastExtractionLabel = formatLastExtraction();
55
48
  console.log('── Learning Loop Status ──');
56
49
  console.log(`Rules: ${activeRules.length} active (${rulesByScope.me} me, ${rulesByScope.session} session)`);
57
50
  console.log(`Evidence: ${evidenceCount} corrections (last 7 days: ${recentCount}; +${otherEvidenceCount} observations/summaries)`);
@@ -79,8 +72,20 @@ export async function handleInspect(args) {
79
72
  return;
80
73
  }
81
74
  if (sub === 'rules') {
75
+ // 읽기 실패·깨진 파일을 "No rules." 와 구분한다.
76
+ const scan = scanRuleFiles();
77
+ if (scan.dirError) {
78
+ console.error(`\n 룰 디렉터리를 읽을 수 없습니다 — ${scan.dirError}\n (룰이 0개인 것이 아니라 읽기 실패입니다)\n`);
79
+ process.exitCode = 1;
80
+ return;
81
+ }
82
82
  const rules = loadAllRules();
83
83
  console.log(`\n${inspect.renderRules(rules)}\n`);
84
+ if (scan.broken.length > 0) {
85
+ console.log(` ⚠ 읽지 못한 룰 파일 ${scan.broken.length}개 (위 목록에 없음): ${scan.broken.slice(0, 5).map((b) => b.file).join(', ')}${scan.broken.length > 5 ? ' …' : ''}`);
86
+ console.log(' forgen doctor 로 확인하고, 복구는 forgen rule restore 를 보세요.\n');
87
+ process.exitCode = 1;
88
+ }
84
89
  return;
85
90
  }
86
91
  // R9-IA2: user-facing name is "corrections"; "evidence" kept as back-compat alias.
@@ -106,6 +111,21 @@ export async function handleInspect(args) {
106
111
  bypass: 'bypass.jsonl',
107
112
  drift: 'drift.jsonl',
108
113
  };
114
+ // status 의 Bypass 와 같은 기준: FORGEN_USER_CONFIRMED=1 로 확인된 우회(violations.jsonl kind=bypass_confirmed).
115
+ // bypass.jsonl 은 자연어 휴리스틱 기록(실측 전량 오탐)이라 --raw 로만 본다.
116
+ if (sub === 'bypass' && !args.includes('--raw')) {
117
+ const confirmed = readJsonlWindow(path.join(STATE_DIR, 'enforcement', 'violations.jsonl'), ROTATED_KEEP_DAYS).filter(isConfirmedBypass);
118
+ const rawPath = path.join(STATE_DIR, 'enforcement', 'bypass.jsonl');
119
+ const rawCount = fs.existsSync(rawPath) ? fs.readFileSync(rawPath, 'utf-8').split('\n').filter(Boolean).length : 0;
120
+ console.log(`\n Confirmed bypass: ${confirmed.length} (status 의 Bypass 와 같은 기준)`);
121
+ for (const e of confirmed.slice(-limit)) {
122
+ console.log(` ${String(e.at ?? '').slice(0, 19)} ${String(e.rule_id ?? '-').slice(0, 24).padEnd(24)} ${String(e.reason_preview ?? e.message_preview ?? '').slice(0, 60)}`);
123
+ }
124
+ if (rawCount > 0)
125
+ console.log(`\n bypass.jsonl 휴리스틱 기록 ${rawCount}건은 집계에서 제외됨 (자연어 추정, 오탐 이력). 원본: forgen inspect bypass --raw`);
126
+ console.log('');
127
+ return;
128
+ }
109
129
  const p = path.join(STATE_DIR, 'enforcement', fileMap[sub]);
110
130
  if (!fs.existsSync(p)) {
111
131
  console.log(`\n No ${sub} data (${p} not found).\n`);
@@ -159,8 +179,12 @@ export async function handleInspect(args) {
159
179
  forgen inspect corrections — 최근 corrections / behavior 기록 (alias: evidence)
160
180
  forgen inspect session — 현재/최근 세션 상태
161
181
  forgen inspect violations [--last N] — 최근 block 기록
162
- forgen inspect bypass [--last N] — 사용자 우회 기록
182
+ forgen inspect bypass [--last N] [--raw] — 확인된 우회 (status Bypass 와 동일 기준; --raw=휴리스틱 로그)
163
183
  forgen inspect drift [--last N] — stuck-loop force-approve 기록`);
184
+ if (sub !== undefined) {
185
+ console.error(`[forgen] Unknown inspect target: ${sub}`);
186
+ process.exitCode = 1;
187
+ }
164
188
  }
165
189
  /**
166
190
  * v0.4.10 Receipts: correction → rule → inject 트리플.
@@ -16,8 +16,12 @@ export interface LifecycleClass {
16
16
  acted_90d: number;
17
17
  matched_180d: number;
18
18
  ageDays: number;
19
+ /** 전체 acted_on 신호가 너무 적어 acted 로 hot/warm/cold 를 가를 수 없는 기간이었는가 */
20
+ signalWeak?: boolean;
19
21
  }
22
+ /** 90일 동안 전체 솔루션의 acted_on 합이 이보다 적으면 "신호가 약한 기간"으로 본다. */
23
+ export declare const WEAK_SIGNAL_TOTAL_ACTED = 3;
20
24
  /** 분류 로직 — §5.2 */
21
- export declare function classifyOne(_solutionId: string, ageDays: number, rates: HitRateRow): Lifecycle;
25
+ export declare function classifyOne(_solutionId: string, ageDays: number, rates: HitRateRow, signalWeak?: boolean): Lifecycle;
22
26
  /** ~/.forgen/me/solutions/*.md 전체를 분류하여 반환 */
23
27
  export declare function classifySolutions(): LifecycleClass[];
@@ -9,14 +9,20 @@ import * as path from 'node:path';
9
9
  import { ME_SOLUTIONS } from './paths.js';
10
10
  import { parseFrontmatterOnly } from '../engine/solution-format.js';
11
11
  import { queryHitRate } from './observability-store.js';
12
+ /** 90일 동안 전체 솔루션의 acted_on 합이 이보다 적으면 "신호가 약한 기간"으로 본다. */
13
+ export const WEAK_SIGNAL_TOTAL_ACTED = 3;
12
14
  /** 분류 로직 — §5.2 */
13
- export function classifyOne(_solutionId, ageDays, rates) {
15
+ export function classifyOne(_solutionId, ageDays, rates, signalWeak = false) {
14
16
  // new: age ≤ 30d
15
17
  if (ageDays <= 30)
16
18
  return 'new';
17
19
  // dead: matched_180d == 0 AND age > 30d
18
20
  if (rates.matched_180d === 0)
19
21
  return 'dead';
22
+ // acted 신호가 약한 기간: acted 없음을 "안 쓰임"으로 읽으면 전부 cold 로 무너진다.
23
+ // 실제로 주입(surfaced)된 솔루션은 판정 보류(warm), 매칭만 되고 주입 안 된 것만 cold.
24
+ if (signalWeak)
25
+ return rates.surfaced_90d >= 1 ? 'warm' : 'cold';
20
26
  // hot: acted_90d >= 3 AND (acted_90d / max(surfaced_90d, 1)) >= 0.4
21
27
  const hitRate = rates.acted_90d / Math.max(rates.surfaced_90d, 1);
22
28
  if (rates.acted_90d >= 3 && hitRate >= 0.4)
@@ -54,6 +60,10 @@ export function classifySolutions() {
54
60
  // fail-open: DB 없으면 빈 map
55
61
  }
56
62
  const now = Date.now();
63
+ let totalActed = 0;
64
+ for (const r of rateMap.values())
65
+ totalActed += r.acted_90d;
66
+ const signalWeak = totalActed < WEAK_SIGNAL_TOTAL_ACTED;
57
67
  for (const file of files) {
58
68
  const filePath = path.join(ME_SOLUTIONS, file);
59
69
  let content;
@@ -85,7 +95,7 @@ export function classifySolutions() {
85
95
  matched_180d: 0, surfaced_180d: 0, acted_180d: 0,
86
96
  last_event_ts: 0,
87
97
  };
88
- const lifecycle = classifyOne(solutionId, ageDays, rates);
98
+ const lifecycle = classifyOne(solutionId, ageDays, rates, signalWeak);
89
99
  const hitRate = rates.surfaced_90d > 0
90
100
  ? rates.acted_90d / rates.surfaced_90d
91
101
  : null;
@@ -98,6 +108,7 @@ export function classifySolutions() {
98
108
  acted_90d: rates.acted_90d,
99
109
  matched_180d: rates.matched_180d,
100
110
  ageDays,
111
+ signalWeak,
101
112
  });
102
113
  }
103
114
  return results;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Forgen v0.4.1 — `forgen migrate` CLI
2
+ * Forgen v0.4.1 — `forgen dev migrate` CLI
3
3
  *
4
4
  * 데이터 스키마 업그레이드를 1회성으로 돌리는 관리 명령.
5
5
  * 현재 대상: