@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
@@ -0,0 +1,208 @@
1
+ /**
2
+ * 추출용 중첩 Haiku 호출 (D4) + 호출 가능 여부 판정 (D2).
3
+ *
4
+ * - 중첩 호출은 사용자의 플러그인·hook·MCP·슬래시 명령·도구를 전혀 끌어오지 않는다:
5
+ * `--tools "" --strict-mcp-config --setting-sources "" --disable-slash-commands --no-session-persistence`
6
+ * (실측 2026-11-04: init 이벤트 tools=[] mcp_servers=[] skills=[] slash_commands=[], 로그인 유지).
7
+ * 프롬프트는 argv 가 아니라 stdin 으로 넘긴다(32K자 한글은 argv 상한 128KB 에 근접).
8
+ * - 호출마다 소요 ms·결과·사유를 extraction-events.jsonl 에 남긴다. 실패는 분류해서 돌려주고, 재시도 정책은
9
+ * 호출자(러너 + 대기열)가 가진다.
10
+ */
11
+ import * as fs from 'node:fs';
12
+ import * as path from 'node:path';
13
+ import { spawnSync, execFileSync } from 'node:child_process';
14
+ import { FORGEN_HOME, STATE_DIR } from './paths.js';
15
+ import { rotateIfBig } from '../engine/lifecycle/signals.js';
16
+ import { NESTED_RUN_ENV, execHost } from '../host/exec-host.js';
17
+ import { resolveDefaultHost } from '../store/profile-store.js';
18
+ /**
19
+ * 호출당 타임아웃. 실측(재생 13회, 2026-11-04): 입력 0.9~17K자에서 응답 3~35초(최대 34.8초, 17K자 학습 단계).
20
+ * 최악의 3.4배 여유로 120초. 이보다 오래 걸리면 호출이 아니라 환경 문제이므로 대기열로 보낸다.
21
+ */
22
+ export const HAIKU_TIMEOUT_MS = 120_000;
23
+ /** 재생/장애 주입 실험용 재정의 (1초 미만은 무시). */
24
+ function timeoutOverride() {
25
+ const n = Number(process.env.FORGEN_HAIKU_TIMEOUT_MS);
26
+ return Number.isFinite(n) && n >= 1000 ? n : undefined;
27
+ }
28
+ export const NESTED_ISOLATION_ARGS = [
29
+ '--tools', '', '--no-session-persistence', '--strict-mcp-config', '--setting-sources', '', '--disable-slash-commands',
30
+ ];
31
+ /** 격리 옵션을 빼면 사용자 플러그인·hook·MCP·도구가 중첩 호출로 새어 들어오므로, 이 옵션을 모르는 CLI 에서는 재호출하지 않고 멈춘다. */
32
+ const ISOLATION_CRITICAL_OPTIONS = new Set(['--tools', '--strict-mcp-config', '--setting-sources']);
33
+ /** 값을 받는 옵션 (빼면 값도 함께 뺀다). */
34
+ const OPTIONS_WITH_VALUE = new Set(['--tools', '--setting-sources', '--model']);
35
+ const UNKNOWN_OPTION_RE = /unknown (?:option|argument|flag)[:\s'"`]*(--[a-z][a-z0-9-]*)|unrecognized (?:option|argument)[:\s'"`]*(--[a-z][a-z0-9-]*)|(--[a-z][a-z0-9-]*)['"`]?\s+(?:is not|not a) (?:a )?(?:valid|recognized|supported)/i;
36
+ /** stderr 에서 CLI 가 모른다고 한 옵션 이름을 뽑는다 (없으면 null). */
37
+ export function parseUnknownOption(text) {
38
+ const m = text.match(UNKNOWN_OPTION_RE);
39
+ return m ? (m[1] ?? m[2] ?? m[3] ?? null) : null;
40
+ }
41
+ /** args 에서 옵션(과 값)을 제거한다. */
42
+ export function dropOption(args, opt) {
43
+ const out = [];
44
+ for (let i = 0; i < args.length; i++) {
45
+ if (args[i] === opt) {
46
+ if (OPTIONS_WITH_VALUE.has(opt))
47
+ i++;
48
+ continue;
49
+ }
50
+ out.push(args[i]);
51
+ }
52
+ return out;
53
+ }
54
+ /**
55
+ * 인증이 settings 파일(apiKeyHelper·프록시 base URL/토큰)에서 오는가. 중첩 호출은 `--setting-sources ""` 로 settings 를
56
+ * 읽지 않으므로 이런 환경에서는 인증이 빠져 실패한다 — "로그인 필요"와 다른 원인이라 구분해 보여 준다.
57
+ */
58
+ export function settingsProvidedAuth() {
59
+ const dirs = [process.env.CLAUDE_CONFIG_DIR, path.join(process.env.HOME ?? '', '.claude')].filter((d) => !!d);
60
+ for (const dir of dirs) {
61
+ for (const f of ['settings.json', 'settings.local.json']) {
62
+ try {
63
+ const j = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf-8'));
64
+ if (j.apiKeyHelper)
65
+ return 'apiKeyHelper';
66
+ if (j.env && (j.env.ANTHROPIC_BASE_URL || j.env.ANTHROPIC_AUTH_TOKEN || j.env.ANTHROPIC_API_KEY))
67
+ return 'env(프록시/토큰)';
68
+ }
69
+ catch { /* 없음 */ }
70
+ }
71
+ }
72
+ return null;
73
+ }
74
+ const AUTH_RE = /not logged in|please run \/login|invalid api key|authentication|unauthorized|credit balance/i;
75
+ const RATE_RE = /usage limit|rate.?limit|429|overloaded|quota/i;
76
+ export function classifyFailure(err) {
77
+ const text = `${err.stderr ?? ''}\n${err.stdout ?? ''}\n${err.message ?? ''}`;
78
+ if (err.code === 'ENOENT')
79
+ return { outcome: 'unavailable', reason: 'claude CLI 를 찾지 못함', retriable: false };
80
+ if (err.code === 'ETIMEDOUT' || err.signal === 'SIGTERM')
81
+ return { outcome: 'timeout', reason: `타임아웃 ${(timeoutOverride() ?? HAIKU_TIMEOUT_MS) / 1000}s`, retriable: true };
82
+ const unknownOpt = parseUnknownOption(text);
83
+ if (unknownOpt)
84
+ return { outcome: 'unavailable', reason: `claude CLI 가 옵션 ${unknownOpt} 를 모름 — claude 업데이트 필요`, retriable: false };
85
+ if (AUTH_RE.test(text)) {
86
+ const viaSettings = settingsProvidedAuth();
87
+ if (viaSettings)
88
+ return { outcome: 'unavailable', reason: `인증이 settings(${viaSettings})에서 오는데 추출 호출은 격리를 위해 settings 를 읽지 않음 — 환경변수로 인증을 주거나 forgen compound consent off`, retriable: false };
89
+ return { outcome: 'unavailable', reason: 'claude 로그인 필요 (claude /login)', retriable: false };
90
+ }
91
+ if (RATE_RE.test(text))
92
+ return { outcome: 'rate-limited', reason: '사용량 한도/과부하', retriable: true };
93
+ return { outcome: 'error', reason: (text.trim().split('\n')[0] || 'unknown').slice(0, 160), retriable: true };
94
+ }
95
+ export function appendExtractionEvent(ev) {
96
+ const p = path.join(FORGEN_HOME, 'state', 'extraction-events.jsonl');
97
+ fs.mkdirSync(path.dirname(p), { recursive: true });
98
+ rotateIfBig(p);
99
+ fs.appendFileSync(p, `${JSON.stringify({ at: new Date().toISOString(), ...ev })}\n`);
100
+ }
101
+ /** 마지막 호출 결과 — status/세션 시작이 "왜 Haiku 가 안 도는지"를 말하는 근거. */
102
+ export function writeHaikuStatus(s) {
103
+ try {
104
+ fs.mkdirSync(STATE_DIR, { recursive: true });
105
+ fs.writeFileSync(path.join(STATE_DIR, 'haiku-status.json'), JSON.stringify({ at: new Date().toISOString(), ...s }));
106
+ }
107
+ catch { /* 기록 실패는 무시 */ }
108
+ }
109
+ export function readHaikuStatus() {
110
+ try {
111
+ return JSON.parse(fs.readFileSync(path.join(STATE_DIR, 'haiku-status.json'), 'utf-8'));
112
+ }
113
+ catch {
114
+ return null;
115
+ }
116
+ }
117
+ /** 호출 없이 판정: claude 미설치 / 미로그인(`claude auth status`는 모델을 호출하지 않는다). */
118
+ export function probeClaudeAvailability() {
119
+ try {
120
+ const out = execFileSync('claude', ['auth', 'status'], { encoding: 'utf-8', timeout: 8000, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...NESTED_RUN_ENV } });
121
+ try {
122
+ const j = JSON.parse(out);
123
+ if (j.loggedIn === false)
124
+ return { available: false, reason: 'claude 로그인 필요 (claude /login)' };
125
+ }
126
+ catch { /* 형식이 달라도 성공 종료면 가용으로 본다 */ }
127
+ return { available: true };
128
+ }
129
+ catch (e) {
130
+ const er = e;
131
+ if (er.code === 'ENOENT')
132
+ return { available: false, reason: 'claude CLI 를 PATH 에서 찾지 못함' };
133
+ if (er.code === 'ETIMEDOUT')
134
+ return { available: true }; // 판정 불가 → 시도는 허용
135
+ const text = `${er.stdout ?? ''}${er.stderr ?? ''}`;
136
+ if (/loggedIn"?\s*:\s*false|not logged in/i.test(text))
137
+ return { available: false, reason: 'claude 로그인 필요 (claude /login)' };
138
+ return { available: true };
139
+ }
140
+ }
141
+ /**
142
+ * Haiku 한 번 호출 (동기). 러너는 detached 프로세스라 이 대기는 다른 세션을 막지 않는다.
143
+ * prompt 는 stdin 으로 전달한다.
144
+ */
145
+ export function callHaiku(phase, prompt, opts) {
146
+ const t0 = Date.now();
147
+ const timeout = opts.timeoutMs ?? timeoutOverride() ?? HAIKU_TIMEOUT_MS;
148
+ if (resolveDefaultHost() === 'codex')
149
+ return callCodex(phase, prompt, opts.cwd, timeout, opts.attempt ?? 0, opts.sessionId);
150
+ const run = (args) => spawnSync('claude', args, {
151
+ input: prompt, cwd: opts.cwd, encoding: 'utf-8', timeout, maxBuffer: 8 * 1024 * 1024,
152
+ env: { ...process.env, ...NESTED_RUN_ENV },
153
+ });
154
+ let args = ['-p', '--model', 'haiku', ...NESTED_ISOLATION_ARGS];
155
+ let r = run(args);
156
+ // 구버전 Claude Code 가 격리 옵션 중 일부를 모를 때(`unknown option`): 격리에 필수가 아닌 옵션이면 그것만 빼고 **1회만** 다시 부른다.
157
+ // 필수 격리 옵션(--tools/--strict-mcp-config/--setting-sources)이면 격리 없이 돌릴 수 없으니 재시도하지 않고 사유를 남긴다.
158
+ const droppedOptions = [];
159
+ // 옵션을 거절한 CLI 는 stdin 을 읽기 전에 끝나므로 프롬프트 쓰기가 EPIPE 로 실패할 수 있다. 프로세스는 정상 종료했으니 실행 실패가 아니다.
160
+ const firstRunFailed = r.error && r.error.code !== 'EPIPE';
161
+ if (r.status !== 0 && !firstRunFailed) {
162
+ const unknownOpt = parseUnknownOption(`${r.stderr ?? ''}\n${r.stdout ?? ''}`);
163
+ if (unknownOpt && args.includes(unknownOpt) && !ISOLATION_CRITICAL_OPTIONS.has(unknownOpt)) {
164
+ args = dropOption(args, unknownOpt);
165
+ droppedOptions.push(unknownOpt);
166
+ r = run(args);
167
+ }
168
+ }
169
+ const ms = Date.now() - t0;
170
+ let res;
171
+ const errObj = r.error;
172
+ if (!errObj && r.status === 0 && typeof r.stdout === 'string' && r.stdout.trim().length > 0) {
173
+ res = { ok: true, outcome: 'ok', output: r.stdout, ms, retriable: false };
174
+ }
175
+ else {
176
+ const c = classifyFailure({
177
+ code: errObj?.code, signal: r.signal, stderr: r.stderr, stdout: r.stdout,
178
+ message: errObj?.message ?? (r.status === 0 ? '빈 응답' : `exit ${r.status}`),
179
+ });
180
+ res = { ok: false, outcome: c.outcome, output: '', ms, reason: c.reason, retriable: c.retriable };
181
+ }
182
+ try {
183
+ appendExtractionEvent({ kind: 'haiku-call', phase, ms, outcome: res.outcome, ...(res.reason ? { reason: res.reason } : {}), attempt: opts.attempt ?? 0, promptChars: prompt.length, ...(opts.sessionId ? { sessionId: opts.sessionId } : {}), ...(droppedOptions.length ? { droppedOptions } : {}) });
184
+ }
185
+ catch { /* 기록 실패는 무시 */ }
186
+ writeHaikuStatus({ ok: res.ok, outcome: res.outcome, reason: res.reason });
187
+ return res;
188
+ }
189
+ /** Codex 호스트 사용자: 같은 경계(소요·사유 기록)로 codex exec 를 쓴다. 격리는 exec-host 의 ephemeral/read-only. */
190
+ function callCodex(phase, prompt, cwd, timeout, attempt, sessionId) {
191
+ const t0 = Date.now();
192
+ let res;
193
+ try {
194
+ const r = execHost({ prompt: prompt.slice(0, 36_000), host: 'codex', timeout, cwd });
195
+ res = { ok: true, outcome: 'ok', output: r.message, ms: Date.now() - t0, retriable: false };
196
+ }
197
+ catch (e) {
198
+ const er = e;
199
+ const c = classifyFailure({ code: er.code, signal: er.signal, stderr: String(er.stderr ?? ''), stdout: String(er.stdout ?? ''), message: er.message });
200
+ res = { ok: false, outcome: c.outcome, output: '', ms: Date.now() - t0, reason: c.reason, retriable: c.retriable };
201
+ }
202
+ try {
203
+ appendExtractionEvent({ kind: 'haiku-call', host: 'codex', phase, ms: res.ms, outcome: res.outcome, ...(res.reason ? { reason: res.reason } : {}), attempt, promptChars: prompt.length, ...(sessionId ? { sessionId } : {}) });
204
+ }
205
+ catch { /* ignore */ }
206
+ writeHaikuStatus({ ok: res.ok, outcome: res.outcome, reason: res.reason });
207
+ return res;
208
+ }
@@ -0,0 +1,68 @@
1
+ export declare const MAX_ATTEMPTS = 3;
2
+ export declare const BACKOFF_MS: number[];
3
+ export declare const MAX_QUEUE = 20;
4
+ export declare const MAX_AGE_MS: number;
5
+ type Phase_ = 'solution' | 'behavior' | 'learning';
6
+ /** transcript 앞 32KB 의 해시 + 크기. 이어 붙이기(append)는 바꾸지 않고, 같은 크기 교체는 바꾼다. */
7
+ export declare function transcriptSignature(filePath: string): string;
8
+ export declare function getCursor(sessionId: string): number;
9
+ export declare function setCursor(sessionId: string, offset: number): void;
10
+ /**
11
+ * 러너가 이 크기의 transcript 를 **처리 끝낸 뒤** 표시한다 (승급·인덱싱·추출 결과가 확정된 다음).
12
+ * 추출 전에 찍으면 "아직 못 넘긴 구간"이 처리된 것으로 보여 영영 건너뛰었다 (5단계 리뷰).
13
+ * blocked 를 주면 새 구간이 남았다는 뜻이다(동의 OFF·미로그인) — 풀리면 같은 구간을 다시 처리한다.
14
+ */
15
+ export declare function markRun(sessionId: string, size: number, opts?: {
16
+ sig?: string;
17
+ blocked?: string | null;
18
+ }): void;
19
+ /** 저장된 지문과 다르면 내용이 교체된 것이다 → 커서·처리 기록을 처음으로 되돌린다. 되돌렸으면 true. */
20
+ export declare function resetIfReplaced(sessionId: string, sig: string): boolean;
21
+ export declare function getDonePhases(sessionId: string, endOffset: number): Phase_[];
22
+ export declare function setDonePhases(sessionId: string, endOffset: number, phases: Phase_[]): void;
23
+ export declare const BLOCKED_RETRY_MS: number;
24
+ /**
25
+ * 이 세션을 러너가 처리해야 하는가. 트리거 경로(Stop·세션 시작·종료) 공통 판정.
26
+ * - 처리 이력 없음 / transcript 가 마지막 처리 이후 자람 / 같은 크기로 내용이 교체됨(sig) → 예
27
+ * - 자라지 않았어도 커서가 파일 끝에 못 미치면 (조금이라 미뤘거나 동의 OFF·미로그인으로 못 넘긴 구간) → 예.
28
+ * 단 동의가 여전히 OFF 이거나 미로그인 사유가 1시간 안이면 불필요한 러너를 띄우지 않는다.
29
+ */
30
+ export declare function sessionNeedsRun(sessionId: string, size: number, opts?: {
31
+ sig?: string;
32
+ now?: number;
33
+ consentEnabled?: boolean;
34
+ }): boolean;
35
+ export declare const RUNNER_LOCK_TTL_MS: number;
36
+ export declare function acquireRunnerLock(sessionId: string, now?: number, pid?: number): boolean;
37
+ export declare function releaseRunnerLock(sessionId: string, pid?: number): void;
38
+ export type Phase = 'solution' | 'behavior' | 'learning';
39
+ export interface QueueEntry {
40
+ id: string;
41
+ sessionId: string;
42
+ cwd: string;
43
+ /** 비밀 마스킹·<private> 제거를 마친 요약만 저장한다. */
44
+ summary: string;
45
+ phases: Phase[];
46
+ createdAt: string;
47
+ attempts: number;
48
+ nextAt: number;
49
+ claimedUntil?: number;
50
+ lastError?: string;
51
+ }
52
+ export declare function readQueue(): QueueEntry[];
53
+ /** 같은 세션 항목이 있으면 합친다(요약은 새것으로, 단계는 합집합). 상한 초과분은 반환해 이벤트로 남기게 한다. */
54
+ export declare function enqueue(job: {
55
+ sessionId: string;
56
+ cwd: string;
57
+ summary: string;
58
+ phases: Phase[];
59
+ error: string;
60
+ }, now?: number): {
61
+ dropped: QueueEntry[];
62
+ };
63
+ /** 기한이 된 항목 1건을 점유한다(다른 러너가 같은 항목을 동시에 잡지 못하게). */
64
+ export declare function claimDue(now?: number): QueueEntry | null;
65
+ export declare function completeEntry(id: string, remaining?: Phase[], error?: string, now?: number): {
66
+ dropped: boolean;
67
+ };
68
+ export {};
@@ -0,0 +1,300 @@
1
+ /**
2
+ * 추출 상태 저장소 (D3 커서 + D4 대기열). 전부 FORGEN_HOME/state 아래, 파일 락으로 다중 러너 안전.
3
+ *
4
+ * 커서: 세션별로 "어디까지 요약에 넣었는가"(바이트 오프셋). 재실행은 새 부분만 읽는다.
5
+ * 대기열: Haiku 호출이 타임아웃/실패한 작업을 비밀 마스킹된 요약과 함께 보관했다가 다음 러너 실행
6
+ * (세션 시작·종료·Stop)에서 재시도한다. 비용 폭주 방지: 시도 3회, 백오프 10분→1시간→6시간, 한 러너가
7
+ * 재시도하는 건 1건, 대기열 20건/7일 상한. 상한을 넘겨 버려지는 건 사유와 함께 이벤트로 남긴다.
8
+ */
9
+ import * as fs from 'node:fs';
10
+ import * as path from 'node:path';
11
+ import { randomBytes, createHash } from 'node:crypto';
12
+ import { STATE_DIR } from './paths.js';
13
+ import { isHaikuCompoundEnabled } from './compound-consent.js';
14
+ import { withFileLockSync } from '../hooks/shared/file-lock.js';
15
+ import { atomicWriteJSON } from '../hooks/shared/atomic-write.js';
16
+ const CURSOR_PATH = () => path.join(STATE_DIR, 'extraction-cursors.json');
17
+ const QUEUE_PATH = () => path.join(STATE_DIR, 'extraction-queue.json');
18
+ export const MAX_ATTEMPTS = 3;
19
+ export const BACKOFF_MS = [10 * 60_000, 60 * 60_000, 6 * 60 * 60_000];
20
+ export const MAX_QUEUE = 20;
21
+ export const MAX_AGE_MS = 7 * 24 * 60 * 60_000;
22
+ const CLAIM_MS = 10 * 60_000;
23
+ const MAX_CURSORS = 500;
24
+ /**
25
+ * JSON 읽기. 파일이 없으면 fallback. **있는데 깨졌으면** 손상본을 `.corrupt-<ts>.bak` 으로 보존하고(최근 3개),
26
+ * 마지막 정상 스냅샷(`.bak`)으로 복구한다. 예전에는 조용히 fallback 을 돌려줘 다음 쓰기가 손상본째 덮어썼다.
27
+ */
28
+ function readJson(p, fallback) {
29
+ let raw;
30
+ try {
31
+ raw = fs.readFileSync(p, 'utf-8');
32
+ }
33
+ catch {
34
+ return fallback;
35
+ }
36
+ try {
37
+ return JSON.parse(raw);
38
+ }
39
+ catch { /* 손상 — 아래 복구 */ }
40
+ try {
41
+ if (raw.trim().length > 0) {
42
+ fs.writeFileSync(`${p}.corrupt-${Date.now()}.bak`, raw);
43
+ const old = fs.readdirSync(path.dirname(p)).filter((f) => f.startsWith(`${path.basename(p)}.corrupt-`)).sort();
44
+ for (const f of old.slice(0, Math.max(0, old.length - 3)))
45
+ fs.rmSync(path.join(path.dirname(p), f), { force: true });
46
+ }
47
+ }
48
+ catch { /* 보존 실패는 무시 */ }
49
+ try {
50
+ return JSON.parse(fs.readFileSync(`${p}.bak`, 'utf-8'));
51
+ }
52
+ catch {
53
+ return fallback;
54
+ }
55
+ }
56
+ /** 정상 파일이면 쓰기 전에 직전 상태를 `.bak` 스냅샷으로 남긴다 (손상 시 복구용). */
57
+ function snapshotGood(p) {
58
+ try {
59
+ const raw = fs.readFileSync(p, 'utf-8');
60
+ JSON.parse(raw);
61
+ fs.writeFileSync(`${p}.bak`, raw);
62
+ }
63
+ catch { /* 없거나 손상이면 스냅샷하지 않는다 — 이전 .bak 유지 */ }
64
+ }
65
+ function writeJson(p, value) {
66
+ snapshotGood(p);
67
+ atomicWriteJSON(p, value);
68
+ }
69
+ function locked(p, fn) {
70
+ fs.mkdirSync(path.dirname(p), { recursive: true });
71
+ return withFileLockSync(p, fn, { timeoutMs: 5000, staleMs: 15000 });
72
+ }
73
+ /** transcript 앞 32KB 의 해시 + 크기. 이어 붙이기(append)는 바꾸지 않고, 같은 크기 교체는 바꾼다. */
74
+ export function transcriptSignature(filePath) {
75
+ try {
76
+ const fd = fs.openSync(filePath, 'r');
77
+ try {
78
+ const buf = Buffer.alloc(32 * 1024);
79
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
80
+ return createHash('sha1').update(buf.subarray(0, n)).digest('hex').slice(0, 16);
81
+ }
82
+ finally {
83
+ fs.closeSync(fd);
84
+ }
85
+ }
86
+ catch {
87
+ return '';
88
+ }
89
+ }
90
+ export function getCursor(sessionId) {
91
+ const c = readJson(CURSOR_PATH(), {})[sessionId];
92
+ return c && Number.isFinite(c.offset) ? c.offset : 0;
93
+ }
94
+ export function setCursor(sessionId, offset) {
95
+ const p = CURSOR_PATH();
96
+ locked(p, () => {
97
+ const all = readJson(p, {});
98
+ all[sessionId] = { ...all[sessionId], offset, at: new Date().toISOString() };
99
+ const keys = Object.keys(all);
100
+ if (keys.length > MAX_CURSORS) {
101
+ keys.sort((a, b) => (all[a].at < all[b].at ? -1 : 1)).slice(0, keys.length - MAX_CURSORS).forEach((k) => { delete all[k]; });
102
+ }
103
+ writeJson(p, all);
104
+ });
105
+ }
106
+ /**
107
+ * 러너가 이 크기의 transcript 를 **처리 끝낸 뒤** 표시한다 (승급·인덱싱·추출 결과가 확정된 다음).
108
+ * 추출 전에 찍으면 "아직 못 넘긴 구간"이 처리된 것으로 보여 영영 건너뛰었다 (5단계 리뷰).
109
+ * blocked 를 주면 새 구간이 남았다는 뜻이다(동의 OFF·미로그인) — 풀리면 같은 구간을 다시 처리한다.
110
+ */
111
+ export function markRun(sessionId, size, opts = {}) {
112
+ const p = CURSOR_PATH();
113
+ locked(p, () => {
114
+ const all = readJson(p, {});
115
+ const prev = all[sessionId];
116
+ const next = { ...prev, offset: prev?.offset ?? 0, at: new Date().toISOString(), runSize: size };
117
+ if (opts.sig !== undefined)
118
+ next.sig = opts.sig;
119
+ if (opts.blocked) {
120
+ next.blocked = opts.blocked;
121
+ next.blockedAt = Date.now();
122
+ }
123
+ else if (opts.blocked === null) {
124
+ delete next.blocked;
125
+ delete next.blockedAt;
126
+ }
127
+ all[sessionId] = next;
128
+ writeJson(p, all);
129
+ });
130
+ }
131
+ /** 저장된 지문과 다르면 내용이 교체된 것이다 → 커서·처리 기록을 처음으로 되돌린다. 되돌렸으면 true. */
132
+ export function resetIfReplaced(sessionId, sig) {
133
+ if (!sig)
134
+ return false;
135
+ const p = CURSOR_PATH();
136
+ return locked(p, () => {
137
+ const all = readJson(p, {});
138
+ const c = all[sessionId];
139
+ if (!c?.sig || c.sig === sig)
140
+ return false;
141
+ all[sessionId] = { offset: 0, at: new Date().toISOString(), sig };
142
+ writeJson(p, all);
143
+ return true;
144
+ });
145
+ }
146
+ export function getDonePhases(sessionId, endOffset) {
147
+ const d = readJson(CURSOR_PATH(), {})[sessionId]?.done;
148
+ return d && d.endOffset === endOffset ? d.phases : [];
149
+ }
150
+ export function setDonePhases(sessionId, endOffset, phases) {
151
+ const p = CURSOR_PATH();
152
+ locked(p, () => {
153
+ const all = readJson(p, {});
154
+ const prev = all[sessionId] ?? { offset: 0, at: new Date().toISOString() };
155
+ if (phases.length === 0)
156
+ delete prev.done;
157
+ else
158
+ prev.done = { endOffset, phases };
159
+ all[sessionId] = prev;
160
+ writeJson(p, all);
161
+ });
162
+ }
163
+ export const BLOCKED_RETRY_MS = 60 * 60_000;
164
+ /**
165
+ * 이 세션을 러너가 처리해야 하는가. 트리거 경로(Stop·세션 시작·종료) 공통 판정.
166
+ * - 처리 이력 없음 / transcript 가 마지막 처리 이후 자람 / 같은 크기로 내용이 교체됨(sig) → 예
167
+ * - 자라지 않았어도 커서가 파일 끝에 못 미치면 (조금이라 미뤘거나 동의 OFF·미로그인으로 못 넘긴 구간) → 예.
168
+ * 단 동의가 여전히 OFF 이거나 미로그인 사유가 1시간 안이면 불필요한 러너를 띄우지 않는다.
169
+ */
170
+ export function sessionNeedsRun(sessionId, size, opts = {}) {
171
+ const c = readJson(CURSOR_PATH(), {})[sessionId];
172
+ if (!c || typeof c.runSize !== 'number' || size > c.runSize)
173
+ return true;
174
+ if (opts.sig && c.sig && opts.sig !== c.sig)
175
+ return true;
176
+ if (c.offset >= size)
177
+ return false;
178
+ const now = opts.now ?? Date.now();
179
+ if (c.blocked?.startsWith('haiku-disabled'))
180
+ return opts.consentEnabled ?? isHaikuCompoundEnabled();
181
+ if (c.blocked?.startsWith('haiku-unavailable'))
182
+ return now - (c.blockedAt ?? 0) >= BLOCKED_RETRY_MS;
183
+ return true;
184
+ }
185
+ // ── 세션별 러너 락 (중복 Haiku 호출·중복 솔루션 차단) ──
186
+ // spawn 쪽 in-flight 표식은 spawn 시점의 게이트일 뿐이라, 표식이 만료되거나 다른 경로(세션 시작·sweep)가 띄운 러너는 겹칠 수 있다.
187
+ // 러너 자신이 시작할 때 잡는 락이 최종 방어선이다. 만료(30분) + 소유 프로세스 생존 확인으로 죽은 러너의 락을 회수한다.
188
+ export const RUNNER_LOCK_TTL_MS = 30 * 60_000;
189
+ const RUNNER_LOCK_DIR = () => path.join(STATE_DIR, 'runner-locks');
190
+ const runnerLockPath = (sessionId) => path.join(RUNNER_LOCK_DIR(), `${sessionId.replace(/[^a-zA-Z0-9_-]/g, '_')}.lock`);
191
+ function pidAlive(pid) {
192
+ try {
193
+ process.kill(pid, 0);
194
+ return true;
195
+ }
196
+ catch (e) {
197
+ return e.code === 'EPERM';
198
+ }
199
+ }
200
+ export function acquireRunnerLock(sessionId, now = Date.now(), pid = process.pid) {
201
+ const lp = runnerLockPath(sessionId);
202
+ fs.mkdirSync(path.dirname(lp), { recursive: true });
203
+ // 점검→회수→생성을 짧은 파일 락으로 직렬화해 두 러너가 동시에 회수하는 경쟁을 막는다.
204
+ return withFileLockSync(lp, () => {
205
+ try {
206
+ const held = JSON.parse(fs.readFileSync(lp, 'utf-8'));
207
+ const fresh = typeof held.at === 'number' && now - held.at < RUNNER_LOCK_TTL_MS;
208
+ if (fresh && typeof held.pid === 'number' && pidAlive(held.pid))
209
+ return false;
210
+ }
211
+ catch { /* 없음/손상 — 새로 잡는다 */ }
212
+ fs.writeFileSync(lp, JSON.stringify({ pid, at: now }));
213
+ return true;
214
+ }, { timeoutMs: 3000, staleMs: 10_000 });
215
+ }
216
+ export function releaseRunnerLock(sessionId, pid = process.pid) {
217
+ const lp = runnerLockPath(sessionId);
218
+ try {
219
+ const held = JSON.parse(fs.readFileSync(lp, 'utf-8'));
220
+ if (held.pid === pid)
221
+ fs.rmSync(lp, { force: true });
222
+ }
223
+ catch { /* 이미 없음 */ }
224
+ }
225
+ export function readQueue() {
226
+ return readJson(QUEUE_PATH(), { entries: [] }).entries ?? [];
227
+ }
228
+ /** 같은 세션 항목이 있으면 합친다(요약은 새것으로, 단계는 합집합). 상한 초과분은 반환해 이벤트로 남기게 한다. */
229
+ export function enqueue(job, now = Date.now()) {
230
+ const p = QUEUE_PATH();
231
+ return locked(p, () => {
232
+ const q = readJson(p, { entries: [] });
233
+ const dropped = [];
234
+ const fresh = q.entries.filter((e) => {
235
+ if (now - Date.parse(e.createdAt) > MAX_AGE_MS) {
236
+ dropped.push(e);
237
+ return false;
238
+ }
239
+ return true;
240
+ });
241
+ const same = fresh.find((e) => e.sessionId === job.sessionId);
242
+ if (same) {
243
+ same.summary = job.summary.slice(0, 40_000);
244
+ same.phases = [...new Set([...same.phases, ...job.phases])];
245
+ same.lastError = job.error.slice(0, 200);
246
+ }
247
+ else {
248
+ fresh.push({
249
+ id: randomBytes(6).toString('hex'), sessionId: job.sessionId, cwd: job.cwd,
250
+ summary: job.summary.slice(0, 40_000), phases: job.phases, createdAt: new Date(now).toISOString(),
251
+ attempts: 0, nextAt: now + BACKOFF_MS[0], lastError: job.error.slice(0, 200),
252
+ });
253
+ }
254
+ while (fresh.length > MAX_QUEUE)
255
+ dropped.push(fresh.shift());
256
+ writeJson(p, { entries: fresh });
257
+ return { dropped };
258
+ });
259
+ }
260
+ /** 기한이 된 항목 1건을 점유한다(다른 러너가 같은 항목을 동시에 잡지 못하게). */
261
+ export function claimDue(now = Date.now()) {
262
+ const p = QUEUE_PATH();
263
+ if (!fs.existsSync(p))
264
+ return null;
265
+ return locked(p, () => {
266
+ const q = readJson(p, { entries: [] });
267
+ const e = q.entries.find((x) => x.nextAt <= now && (x.claimedUntil ?? 0) <= now);
268
+ if (!e)
269
+ return null;
270
+ e.claimedUntil = now + CLAIM_MS;
271
+ writeJson(p, q);
272
+ return { ...e };
273
+ });
274
+ }
275
+ export function completeEntry(id, remaining = [], error, now = Date.now()) {
276
+ const p = QUEUE_PATH();
277
+ return locked(p, () => {
278
+ const q = readJson(p, { entries: [] });
279
+ const e = q.entries.find((x) => x.id === id);
280
+ if (!e)
281
+ return { dropped: false };
282
+ if (remaining.length === 0) {
283
+ q.entries = q.entries.filter((x) => x.id !== id);
284
+ writeJson(p, q);
285
+ return { dropped: false };
286
+ }
287
+ e.attempts += 1;
288
+ e.phases = remaining;
289
+ e.claimedUntil = undefined;
290
+ e.lastError = error?.slice(0, 200);
291
+ if (e.attempts >= MAX_ATTEMPTS) {
292
+ q.entries = q.entries.filter((x) => x.id !== id);
293
+ writeJson(p, q);
294
+ return { dropped: true };
295
+ }
296
+ e.nextAt = now + BACKOFF_MS[Math.min(e.attempts, BACKOFF_MS.length - 1)];
297
+ writeJson(p, q);
298
+ return { dropped: false };
299
+ });
300
+ }
@@ -0,0 +1,93 @@
1
+ export declare const FLOW_WINDOW_DAYS = 7;
2
+ export interface TimedRead {
3
+ /** epoch ms of each recorded event */
4
+ times: number[];
5
+ /** 읽기 실패 사유 (있으면 0건이 아니라 "읽을 수 없음") */
6
+ error?: string;
7
+ }
8
+ /** 디렉터리/파일을 읽을 수 없는 사유. 없으면(정상 또는 부재) null. */
9
+ export declare function unreadable(p: string): string | null;
10
+ /**
11
+ * 현재 로그 + 회전본. 회전 방식이 둘이다: rotateIfBig(`<p>.<timestamp>`)와 state-gc(`<p>.1`, `<p>.2`).
12
+ * 둘 다 읽어야 회전 직후에도 최근 기록이 사라지지 않는다. 오래된 것부터.
13
+ */
14
+ export declare function logFilesWithRotated(p: string, days?: number, now?: number): string[];
15
+ export declare function readJsonlTimes(p: string, key: string, filter?: (e: Record<string, unknown>) => boolean): TimedRead;
16
+ /** frontmatter 시각 파싱. `2026-11-01` 처럼 날짜만 있으면 UTC 가 아니라 로컬 자정으로 본다 (시간대에 따라 하루 어긋나지 않게). */
17
+ export declare function parseCreated(raw: string): number;
18
+ /** 로컬 시각 `YYYY-MM-DD HH:mm` */
19
+ export declare function localStamp(t: number): string;
20
+ /** hook 경로에서 후보가 1개 이상 나온 recall — 흐름의 "주입"과 통계의 "Recall hits"/주간 추세가 같은 정의를 쓴다. */
21
+ export declare function isInjectedRecall(e: Record<string, unknown>): boolean;
22
+ /** 새로 저장된 것(솔루션 created + 룰 created_at)의 시각 — 흐름의 "저장"과 통계의 "Saved"가 같은 정의를 쓴다. */
23
+ export declare function readSavedTimes(): TimedRead & {
24
+ undated: number;
25
+ };
26
+ /** 솔루션 생성 시각 — frontmatter `created`. mtime 은 복사·touch 로 바뀌므로 쓰지 않는다. */
27
+ export declare function readSolutionCreations(): TimedRead & {
28
+ total: number;
29
+ undated: number;
30
+ };
31
+ export interface EvidenceCounts {
32
+ /** 사용자가 직접 한 교정 (hook 기록) */
33
+ user: TimedRead;
34
+ /** Haiku 채굴 추론 — 사용자 발화가 아니다 */
35
+ mined: TimedRead;
36
+ /** 행동 관찰·세션 요약 */
37
+ other: TimedRead;
38
+ }
39
+ export declare function readEvidenceCounts(): EvidenceCounts;
40
+ export declare const countSince: (times: number[], days: number, now?: number) => number;
41
+ export declare const lastOf: (times: number[]) => number | null;
42
+ export declare function formatWhen(t: number | null, now?: number): string;
43
+ export interface ExtractionEvents {
44
+ ok: number[];
45
+ failed: number[]; /** 실행됐지만 입력 부족 등으로 일찍 끝난 건 (사유별) — ok 에도 포함 */
46
+ skipped: Record<string, number>;
47
+ trailingFailures: number;
48
+ lastError?: string;
49
+ error?: string;
50
+ }
51
+ export declare function readExtractionEvents(): ExtractionEvents;
52
+ /** 마지막 추출 완료 시각 — last-auto-compound.json(completedAt) 단일 소스. status·inspect 가 같은 값을 쓴다. */
53
+ export declare function lastExtractionTime(): number | null;
54
+ export declare function formatLastExtraction(now?: number): string;
55
+ export interface HaikuCallStats {
56
+ today: number;
57
+ failedToday: number;
58
+ maxPerSession: number;
59
+ sessionsToday: number;
60
+ }
61
+ /**
62
+ * 오늘(로컬 날짜) Haiku 호출 수. 호출 하나하나가 extraction-events 의 `haiku-call` 이벤트라 그대로 센다.
63
+ * 세션별 호출 수(한 세션이 하루에 몇 번 불렀나)도 집계해 과다 호출을 눈으로 볼 수 있게 한다.
64
+ */
65
+ export declare function haikuCallStats(now?: number): HaikuCallStats;
66
+ export declare function haikuUsageLine(now?: number): string;
67
+ export type HaikuStatus = {
68
+ state: 'off' | 'on' | 'unavailable' | 'failing';
69
+ detail: string;
70
+ };
71
+ export declare function haikuStatus(ev?: ExtractionEvents): HaikuStatus;
72
+ export interface FlowStage {
73
+ label: string;
74
+ input: string;
75
+ last: number | null;
76
+ count: number;
77
+ /** 읽기 실패 사유 — 있으면 count 는 의미 없음 */
78
+ error?: string;
79
+ note?: string;
80
+ }
81
+ export declare function computeFlow(days?: number, now?: number): FlowStage[];
82
+ /** 이 홈에 남은 세션 기록 수 (state/sessions + sessions). 큰 쪽을 쓴다. */
83
+ export declare function flowSessionCount(): number;
84
+ /** 경고를 내려면 필요한 최소 세션 수. 이보다 적으면 0건이 정상일 수 있다. */
85
+ export declare const FLOW_MIN_SESSIONS = 3;
86
+ /**
87
+ * 0건 경고 판정. 활동이 충분할 때만, 그리고 그 단계가 정상적으로 0일 수 없을 때만 낸다.
88
+ * 추출·저장·주입: 세션이 충분한데 0건이면 경고.
89
+ * 사용: 주입이 있는데 인용이 0건일 때만 (주입이 없으면 쓸 것도 없다).
90
+ * 수집·피드백: 사용자가 교정·차단을 만나야 쌓이는 값이라 0건이 정상 — 경고하지 않는다.
91
+ */
92
+ export declare function flowWarning(stage: FlowStage, stages: FlowStage[], sessions: number): string | null;
93
+ export declare function renderFlow(stages: FlowStage[], days?: number, now?: number, sessions?: number): string[];