@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.
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +23 -0
- package/README.ja.md +15 -10
- package/README.ko.md +15 -10
- package/README.md +19 -14
- package/README.zh.md +13 -8
- package/dist/checks/dangerous-response-pattern.d.ts +2 -1
- package/dist/checks/dangerous-response-pattern.js +27 -3
- package/dist/cli.js +133 -17
- package/dist/core/auto-compound-runner.js +502 -397
- package/dist/core/block-cli.js +7 -3
- package/dist/core/compound-consent.d.ts +18 -0
- package/dist/core/compound-consent.js +101 -6
- package/dist/core/compound-sweep-cli.d.ts +16 -0
- package/dist/core/compound-sweep-cli.js +67 -5
- package/dist/core/config-hooks.js +28 -10
- package/dist/core/correction-signals.d.ts +9 -0
- package/dist/core/correction-signals.js +37 -0
- package/dist/core/dev-cli.d.ts +1 -2
- package/dist/core/dev-cli.js +9 -28
- package/dist/core/doctor-verify.d.ts +35 -0
- package/dist/core/doctor-verify.js +502 -0
- package/dist/core/doctor.d.ts +4 -6
- package/dist/core/doctor.js +103 -184
- package/dist/core/explain-cli.js +8 -0
- package/dist/core/extraction-haiku.d.ts +64 -0
- package/dist/core/extraction-haiku.js +208 -0
- package/dist/core/extraction-queue.d.ts +68 -0
- package/dist/core/extraction-queue.js +300 -0
- package/dist/core/flow-status.d.ts +93 -0
- package/dist/core/flow-status.js +368 -0
- package/dist/core/harness.js +14 -42
- package/dist/core/inspect-cli.js +37 -13
- package/dist/core/lifecycle-classifier.d.ts +5 -1
- package/dist/core/lifecycle-classifier.js +13 -2
- package/dist/core/migrate-cli.d.ts +1 -1
- package/dist/core/migrate-cli.js +11 -11
- package/dist/core/migrate-tenetx.d.ts +1 -1
- package/dist/core/migrate-tenetx.js +2 -2
- package/dist/core/node-engine.d.ts +3 -0
- package/dist/core/node-engine.js +8 -0
- package/dist/core/observability-store.d.ts +15 -0
- package/dist/core/observability-store.js +73 -0
- package/dist/core/paths.d.ts +2 -0
- package/dist/core/paths.js +2 -0
- package/dist/core/rendered-rules-manifest.d.ts +7 -1
- package/dist/core/rendered-rules-manifest.js +45 -1
- package/dist/core/session-store.d.ts +13 -11
- package/dist/core/session-store.js +103 -119
- package/dist/core/settings-injector.d.ts +5 -2
- package/dist/core/settings-injector.js +21 -88
- package/dist/core/spawn.d.ts +9 -1
- package/dist/core/spawn.js +33 -33
- package/dist/core/stats-cli.d.ts +7 -0
- package/dist/core/stats-cli.js +66 -93
- package/dist/core/status-cli.d.ts +1 -1
- package/dist/core/status-cli.js +23 -4
- package/dist/core/statusline-cli.js +5 -0
- package/dist/core/statusline-install.d.ts +10 -2
- package/dist/core/statusline-install.js +27 -4
- package/dist/core/transcript-summary.d.ts +84 -9
- package/dist/core/transcript-summary.js +283 -49
- package/dist/core/uninstall.d.ts +4 -0
- package/dist/core/uninstall.js +68 -36
- package/dist/core/v1-bootstrap.d.ts +1 -1
- package/dist/core/v1-bootstrap.js +38 -9
- package/dist/engine/acted-on-evidence.d.ts +8 -0
- package/dist/engine/acted-on-evidence.js +38 -0
- package/dist/engine/block-judge.d.ts +3 -1
- package/dist/engine/block-judge.js +4 -3
- package/dist/engine/compound-cli.d.ts +26 -2
- package/dist/engine/compound-cli.js +143 -19
- package/dist/engine/compound-lifecycle.d.ts +36 -2
- package/dist/engine/compound-lifecycle.js +131 -11
- package/dist/engine/compound-loop.d.ts +4 -0
- package/dist/engine/compound-loop.js +93 -18
- package/dist/engine/correction-cluster-runner.d.ts +11 -1
- package/dist/engine/correction-cluster-runner.js +39 -15
- package/dist/engine/correction-clustering.d.ts +11 -0
- package/dist/engine/correction-clustering.js +20 -3
- package/dist/engine/lifecycle/lifecycle-cli.js +10 -3
- package/dist/engine/lifecycle/meta-reclassifier.d.ts +9 -0
- package/dist/engine/lifecycle/meta-reclassifier.js +15 -3
- package/dist/engine/lifecycle/orchestrator.js +3 -2
- package/dist/engine/lifecycle/signals.d.ts +19 -1
- package/dist/engine/lifecycle/signals.js +61 -2
- package/dist/engine/lifecycle/trigger-t1-correction.d.ts +1 -1
- package/dist/engine/lifecycle/trigger-t1-correction.js +9 -28
- package/dist/engine/lifecycle/trigger-t5-conflict.d.ts +8 -0
- package/dist/engine/lifecycle/trigger-t5-conflict.js +60 -2
- package/dist/engine/roi-demotion.d.ts +11 -0
- package/dist/engine/roi-demotion.js +50 -8
- package/dist/engine/rule-detectability.d.ts +39 -0
- package/dist/engine/rule-detectability.js +66 -0
- package/dist/engine/rule-project-cli.d.ts +25 -0
- package/dist/engine/rule-project-cli.js +148 -0
- package/dist/engine/rule-recovery-cli.d.ts +21 -0
- package/dist/engine/rule-recovery-cli.js +265 -0
- package/dist/engine/rule-toggle-cli.d.ts +14 -2
- package/dist/engine/rule-toggle-cli.js +94 -6
- package/dist/engine/skill-promoter.d.ts +14 -8
- package/dist/engine/skill-promoter.js +57 -85
- package/dist/engine/solution-format.d.ts +26 -1
- package/dist/engine/solution-format.js +65 -3
- package/dist/engine/solution-habit.d.ts +1 -0
- package/dist/engine/solution-habit.js +22 -0
- package/dist/engine/solution-index.d.ts +5 -0
- package/dist/engine/solution-index.js +32 -0
- package/dist/engine/solution-matcher-eval.js +4 -4
- package/dist/engine/solution-matcher.js +15 -13
- package/dist/engine/solution-scope.d.ts +11 -0
- package/dist/engine/solution-scope.js +19 -0
- package/dist/engine/solution-writer.d.ts +3 -1
- package/dist/engine/solution-writer.js +3 -2
- package/dist/engine/term-normalizer.js +49 -0
- package/dist/fgx.js +1 -1
- package/dist/forge/cli.js +51 -8
- package/dist/forge/evidence-processor.js +6 -0
- package/dist/hooks/context-guard.d.ts +0 -22
- package/dist/hooks/context-guard.js +22 -55
- package/dist/hooks/context-usage.d.ts +21 -0
- package/dist/hooks/context-usage.js +103 -0
- package/dist/hooks/dangerous-patterns.json +1 -16
- package/dist/hooks/db-guard.d.ts +1 -1
- package/dist/hooks/db-guard.js +21 -30
- package/dist/hooks/hook-config.d.ts +2 -0
- package/dist/hooks/hook-config.js +5 -1
- package/dist/hooks/hooks-generator.d.ts +4 -0
- package/dist/hooks/hooks-generator.js +10 -4
- package/dist/hooks/permission-handler.js +23 -3
- package/dist/hooks/post-tool-use.js +14 -10
- package/dist/hooks/pre-tool-use.d.ts +17 -3
- package/dist/hooks/pre-tool-use.js +143 -30
- package/dist/hooks/rate-limiter.js +12 -7
- package/dist/hooks/secret-filter.js +15 -4
- package/dist/hooks/session-end.d.ts +2 -2
- package/dist/hooks/session-end.js +13 -7
- package/dist/hooks/session-recovery.js +79 -50
- package/dist/hooks/shared/command-analyzer.d.ts +45 -0
- package/dist/hooks/shared/command-analyzer.js +972 -0
- package/dist/hooks/shared/command-parser.d.ts +5 -29
- package/dist/hooks/shared/command-parser.js +65 -35
- package/dist/hooks/shared/commit-guard.d.ts +15 -0
- package/dist/hooks/shared/commit-guard.js +176 -0
- package/dist/hooks/shared/hook-response.d.ts +6 -0
- package/dist/hooks/shared/hook-response.js +12 -0
- package/dist/hooks/shared/hook-timing.js +9 -3
- package/dist/hooks/shared/injection-caps.d.ts +32 -2
- package/dist/hooks/shared/injection-caps.js +73 -2
- package/dist/hooks/shared/is-main.d.ts +8 -0
- package/dist/hooks/shared/is-main.js +20 -0
- package/dist/hooks/shared/stop-triggers.d.ts +1 -1
- package/dist/hooks/shared/stop-triggers.js +2 -1
- package/dist/hooks/shared/tool-response.d.ts +6 -0
- package/dist/hooks/shared/tool-response.js +30 -0
- package/dist/hooks/slop-detector.js +6 -3
- package/dist/hooks/solution-injector.d.ts +23 -0
- package/dist/hooks/solution-injector.js +102 -101
- package/dist/hooks/stop-guard.d.ts +11 -1
- package/dist/hooks/stop-guard.js +28 -11
- package/dist/hooks/subagent-stop-guard.js +2 -1
- package/dist/hooks/subagent-tracker.js +2 -1
- package/dist/host/capabilities-codex.js +1 -0
- package/dist/host/claude-shim.d.ts +24 -0
- package/dist/host/claude-shim.js +68 -0
- package/dist/host/codex-hook-shim.d.ts +3 -1
- package/dist/host/codex-hook-shim.js +7 -5
- package/dist/host/codex-notify.js +1 -1
- package/dist/host/codex-rules-context.d.ts +6 -4
- package/dist/host/codex-rules-context.js +11 -24
- package/dist/host/exec-host.d.ts +5 -1
- package/dist/host/exec-host.js +15 -4
- package/dist/host/install-claude.d.ts +47 -14
- package/dist/host/install-claude.js +302 -155
- package/dist/host/install-codex.d.ts +20 -0
- package/dist/host/install-codex.js +32 -1
- package/dist/host/install-opencode.d.ts +3 -1
- package/dist/host/install-opencode.js +6 -3
- package/dist/host/install-orchestrator.js +14 -1
- package/dist/host/opencode/translate.d.ts +1 -1
- package/dist/host/opencode/translate.js +5 -3
- package/dist/host/projection.d.ts +9 -1
- package/dist/host/projection.js +19 -2
- package/dist/mcp/server.js +5 -0
- package/dist/mcp/solution-reader.d.ts +5 -5
- package/dist/mcp/solution-reader.js +13 -35
- package/dist/mcp/tools.js +18 -1
- package/dist/renderer/inspect-renderer.js +4 -2
- package/dist/renderer/render-report.d.ts +22 -0
- package/dist/renderer/render-report.js +29 -0
- package/dist/renderer/rule-renderer.d.ts +28 -2
- package/dist/renderer/rule-renderer.js +91 -76
- package/dist/store/evidence-store.js +34 -6
- package/dist/store/rule-lifecycle.d.ts +3 -1
- package/dist/store/rule-lifecycle.js +10 -0
- package/dist/store/rule-scope.d.ts +7 -0
- package/dist/store/rule-scope.js +54 -0
- package/dist/store/rule-store.d.ts +29 -3
- package/dist/store/rule-store.js +110 -26
- package/dist/store/types.d.ts +22 -2
- package/dist/way/cli.d.ts +1 -0
- package/dist/way/cli.js +313 -0
- package/dist/way/compile.d.ts +22 -0
- package/dist/way/compile.js +408 -0
- package/dist/way/conflict.d.ts +2 -0
- package/dist/way/conflict.js +18 -0
- package/dist/way/draft.d.ts +43 -0
- package/dist/way/draft.js +335 -0
- package/dist/way/extract.d.ts +17 -0
- package/dist/way/extract.js +172 -0
- package/dist/way/io.d.ts +79 -0
- package/dist/way/io.js +425 -0
- package/dist/way/similar.d.ts +2 -0
- package/dist/way/similar.js +30 -0
- package/dist/way/types.d.ts +98 -0
- package/dist/way/types.js +2 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/scripts/postinstall.js +78 -900
- package/dist/core/health-cli.d.ts +0 -25
- package/dist/core/health-cli.js +0 -90
- package/dist/host/parity-harness.d.ts +0 -70
- package/dist/host/parity-harness.js +0 -287
package/dist/core/uninstall.js
CHANGED
|
@@ -3,7 +3,11 @@ import * as os from 'node:os';
|
|
|
3
3
|
import * as path from 'node:path';
|
|
4
4
|
import * as readline from 'node:readline';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { FORGEN_RUN_MARKER, forgenRunShimPath, isForgenRunCommand } from '../host/claude-shim.js';
|
|
6
7
|
import { hasManagedSkillMarker, listDevGuideSkillNames, removeSkillFile } from '../host/managed-marker.js';
|
|
8
|
+
import { isForgenStatusline } from './statusline-install.js';
|
|
9
|
+
import { reclaimRenderedRuleFiles } from './rendered-rules-manifest.js';
|
|
10
|
+
import { removeForgenHooks } from '../host/install-claude.js';
|
|
7
11
|
import { SETTINGS_PATH, acquireLock, releaseLock, atomicWriteFileSync, } from './settings-lock.js';
|
|
8
12
|
/** 플러그인 제거 (plugin-installer.ts 삭제 후 인라인) */
|
|
9
13
|
function uninstallPlugin() {
|
|
@@ -144,7 +148,9 @@ export function cleanClaudeJsonMcp(homeDir = os.homedir()) {
|
|
|
144
148
|
if (!entry)
|
|
145
149
|
return false;
|
|
146
150
|
const args = Array.isArray(entry.args) ? entry.args : [];
|
|
147
|
-
const
|
|
151
|
+
const command = entry.command;
|
|
152
|
+
const isForgenServer = (typeof command === 'string' && isForgenRunCommand(command))
|
|
153
|
+
|| args.some((a) => typeof a === 'string' && /[\\/]dist[\\/]mcp[\\/]server\.js$/.test(a));
|
|
148
154
|
if (!isForgenServer)
|
|
149
155
|
return false; // 사용자가 같은 이름으로 다른 서버를 등록
|
|
150
156
|
delete data.mcpServers?.['forgen-compound'];
|
|
@@ -192,38 +198,12 @@ function cleanSettings() {
|
|
|
192
198
|
delete settings.env;
|
|
193
199
|
}
|
|
194
200
|
}
|
|
195
|
-
// hooks에서 forgen
|
|
196
|
-
const hookMarkers = ['forgen', 'compound-harness'];
|
|
197
|
-
function isCHCommand(cmd) {
|
|
198
|
-
return hookMarkers.some(m => cmd.includes(m));
|
|
199
|
-
}
|
|
200
|
-
function isCHHookEntry(entry) {
|
|
201
|
-
// 직접 형식: { type, command }
|
|
202
|
-
if (typeof entry.command === 'string' && isCHCommand(entry.command))
|
|
203
|
-
return true;
|
|
204
|
-
// 래핑 형식: { matcher, hooks: [{ command }] }
|
|
205
|
-
const innerHooks = entry.hooks;
|
|
206
|
-
if (Array.isArray(innerHooks)) {
|
|
207
|
-
return innerHooks.some(h => typeof h.command === 'string' && isCHCommand(h.command));
|
|
208
|
-
}
|
|
209
|
-
return false;
|
|
210
|
-
}
|
|
201
|
+
// hooks 에서 forgen 항목만 제거한다. 같은 그룹의 사용자 hook 과 다른 도구 hook 은 남긴다.
|
|
211
202
|
const hooks = settings.hooks;
|
|
212
203
|
if (hooks) {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
continue;
|
|
216
|
-
const filtered = entries.filter((h) => !isCHHookEntry(h));
|
|
217
|
-
if (filtered.length === 0) {
|
|
218
|
-
delete hooks[hookType];
|
|
219
|
-
}
|
|
220
|
-
else {
|
|
221
|
-
hooks[hookType] = filtered;
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
if (Object.keys(hooks).length === 0) {
|
|
204
|
+
removeForgenHooks(hooks, path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..'));
|
|
205
|
+
if (Object.keys(hooks).length === 0)
|
|
225
206
|
delete settings.hooks;
|
|
226
|
-
}
|
|
227
207
|
}
|
|
228
208
|
// statusLine이 forgen이 설치한 command 중 하나면 제거.
|
|
229
209
|
//
|
|
@@ -231,10 +211,16 @@ function cleanSettings() {
|
|
|
231
211
|
// 실제 install은 `settings-injector.ts:59`에서 `'forgen me'`를 주입한다.
|
|
232
212
|
// command 문자열이 `forgen`으로 시작하는 경우를 모두 forgen 소유로 보고
|
|
233
213
|
// 제거 — 사용자 커스텀 statusLine(예: `custom-cli ...`)은 건드리지 않음.
|
|
214
|
+
// 구형(`forgen statusline`, 절대경로 dist/cli.js)과 shim 형식 모두 forgen 소유. 설치 때 보관한 원본(statusLine_backup)이 있으면 복원.
|
|
234
215
|
const statusLine = settings.statusLine;
|
|
235
|
-
if (typeof statusLine?.command === 'string' &&
|
|
236
|
-
|
|
237
|
-
|
|
216
|
+
if (typeof statusLine?.command === 'string' && statusLine.command.trim() && isForgenStatusline(statusLine.command)) {
|
|
217
|
+
if (typeof settings.statusLine_backup === 'string') {
|
|
218
|
+
settings.statusLine = { type: 'command', command: settings.statusLine_backup };
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
delete settings.statusLine;
|
|
222
|
+
}
|
|
223
|
+
delete settings.statusLine_backup;
|
|
238
224
|
}
|
|
239
225
|
// enabledPlugins에서 forgen@forgen-local 제거
|
|
240
226
|
const enabledPlugins = settings.enabledPlugins;
|
|
@@ -291,6 +277,43 @@ function cleanAgents(cwd) {
|
|
|
291
277
|
console.log(' - No agent files found');
|
|
292
278
|
}
|
|
293
279
|
}
|
|
280
|
+
/** 고정 shim(<FORGEN_HOME>/bin/forgen-run) 제거 — 표식이 있는 forgen 파일만. 빈 bin 디렉토리도 정리. */
|
|
281
|
+
export function cleanForgenRunShim(homeDir = os.homedir()) {
|
|
282
|
+
const shim = forgenRunShimPath(homeDir);
|
|
283
|
+
try {
|
|
284
|
+
if (!fs.readFileSync(shim, 'utf-8').includes(FORGEN_RUN_MARKER))
|
|
285
|
+
return false;
|
|
286
|
+
fs.unlinkSync(shim);
|
|
287
|
+
try {
|
|
288
|
+
fs.rmdirSync(path.dirname(shim));
|
|
289
|
+
}
|
|
290
|
+
catch { /* 비어 있지 않음 */ }
|
|
291
|
+
return true;
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
return false; // 없음
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/** 전역 ~/.claude/agents/ch-*.md — forgen 표식이 있는 것만 지운다(사용자 파일 보존). */
|
|
298
|
+
export function cleanGlobalAgents(homeDir = os.homedir()) {
|
|
299
|
+
const dir = path.join(homeDir, '.claude', 'agents');
|
|
300
|
+
let removed = 0;
|
|
301
|
+
try {
|
|
302
|
+
for (const name of fs.readdirSync(dir)) {
|
|
303
|
+
if (!name.startsWith('ch-') || !name.endsWith('.md'))
|
|
304
|
+
continue;
|
|
305
|
+
const f = path.join(dir, name);
|
|
306
|
+
if (fs.lstatSync(f).isSymbolicLink() || !hasManagedSkillMarker(fs.readFileSync(f, 'utf-8')))
|
|
307
|
+
continue;
|
|
308
|
+
fs.unlinkSync(f);
|
|
309
|
+
removed += 1;
|
|
310
|
+
}
|
|
311
|
+
if (fs.readdirSync(dir).length === 0)
|
|
312
|
+
fs.rmdirSync(dir);
|
|
313
|
+
}
|
|
314
|
+
catch { /* 없음 */ }
|
|
315
|
+
return removed;
|
|
316
|
+
}
|
|
294
317
|
/** .claude/rules/ 의 forgen 규칙 파일 및 레거시 compound-rules.md 제거 */
|
|
295
318
|
function cleanCompoundRules(cwd) {
|
|
296
319
|
const ruleFiles = [
|
|
@@ -358,11 +381,11 @@ function cleanClaudeMd(cwd) {
|
|
|
358
381
|
export async function handleUninstall(cwd, options) {
|
|
359
382
|
console.log('\n[forgen] Uninstalling Forgen\n');
|
|
360
383
|
console.log('The following items will be cleaned up:');
|
|
361
|
-
console.log(' 1. Remove CH env vars/hooks/statusLine/enabledPlugins from ~/.claude/settings.json');
|
|
362
|
-
console.log(' 2. Delete .claude/agents/
|
|
384
|
+
console.log(' 1. Remove CH env vars/hooks/statusLine (shim or absolute-path form)/enabledPlugins from ~/.claude/settings.json');
|
|
385
|
+
console.log(' 2. Delete ch-*.md agent files (project .claude/agents and global ~/.claude/agents; only forgen-managed ones)');
|
|
363
386
|
console.log(' 3. Delete .claude/rules/ rule files (project-context, routing, forge-*)');
|
|
364
387
|
console.log(' 4. Remove forgen block from CLAUDE.md');
|
|
365
|
-
console.log(' 5. Remove slash commands (~/.claude/commands/forgen/) and the forgen-managed verify skill (~/.claude/skills/verify/)');
|
|
388
|
+
console.log(' 5. Remove the hook/MCP shim (~/.forgen/bin/forgen-run), global rule files generated by forgen, slash commands (~/.claude/commands/forgen/) and the forgen-managed verify skill (~/.claude/skills/verify/)');
|
|
366
389
|
console.log(' 6. Remove plugin artifacts (cache, installed_plugins.json, plugin directory), dev-guide skills, and the forgen-compound MCP entry in ~/.claude.json');
|
|
367
390
|
console.log(' 7. Codex (if $CODEX_HOME or ~/.codex exists): forgen hooks in hooks.json, the MCP/notify blocks in config.toml, forgen skills, ch-*.toml agents, and the AGENTS.md blocks (every project recorded at install time) — hooks and files from other tools are kept');
|
|
368
391
|
console.log(' OpenCode (if its config dir exists): the forgen plugin, the forgen-compound MCP entry, AGENTS.md blocks');
|
|
@@ -393,6 +416,13 @@ export async function handleUninstall(cwd, options) {
|
|
|
393
416
|
cleanCompoundRules(cwd);
|
|
394
417
|
cleanClaudeMd(cwd);
|
|
395
418
|
cleanSlashCommands();
|
|
419
|
+
const agents = cleanGlobalAgents();
|
|
420
|
+
if (agents > 0)
|
|
421
|
+
console.log(` ✓ Removed ${agents} global agent(s) (~/.claude/agents/ch-*.md)`);
|
|
422
|
+
// 전역 ~/.claude/rules 의 forgen 생성 파일(생성 표제로 판정)은 backups 로 옮긴다 — 방치하면 uninstall 후에도 주입된다.
|
|
423
|
+
const reclaimed = reclaimRenderedRuleFiles(cwd).filter((f) => f.startsWith(path.join(os.homedir(), '.claude', 'rules')));
|
|
424
|
+
if (reclaimed.length > 0)
|
|
425
|
+
console.log(` ✓ Moved ${reclaimed.length} global rule file(s) out of ~/.claude/rules (backup under ~/.forgen/backups/)`);
|
|
396
426
|
if (cleanVerifySkill())
|
|
397
427
|
console.log(' ✓ Removed forgen verify skill (~/.claude/skills/verify/)');
|
|
398
428
|
const pkgRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
@@ -401,6 +431,8 @@ export async function handleUninstall(cwd, options) {
|
|
|
401
431
|
console.log(` ✓ Removed ${devGuide} dev-guide skill(s) (~/.claude/skills/forgen-*)`);
|
|
402
432
|
if (cleanClaudeJsonMcp())
|
|
403
433
|
console.log(' ✓ Removed forgen-compound MCP server from ~/.claude.json');
|
|
434
|
+
if (cleanForgenRunShim())
|
|
435
|
+
console.log(' ✓ Removed hook/MCP shim (~/.forgen/bin/forgen-run)');
|
|
404
436
|
// ADR-016 D4 — Codex 에 등록한 것도 되돌린다 (다른 도구의 훅과 그 신뢰는 보존)
|
|
405
437
|
try {
|
|
406
438
|
const { planCodexUninstall, renderCodexUninstall } = await import('../host/uninstall-codex.js');
|
|
@@ -14,14 +14,16 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import * as fs from 'node:fs';
|
|
16
16
|
import * as path from 'node:path';
|
|
17
|
+
import { promoteSessionCandidates } from '../store/evidence-store.js';
|
|
17
18
|
import * as crypto from 'node:crypto';
|
|
18
19
|
import { FORGEN_HOME, ME_DIR, ME_RULES, ME_BEHAVIOR, V1_RECOMMENDATIONS_DIR, V1_SESSIONS_DIR, STATE_DIR, V1_RAW_LOGS_DIR, ME_SOLUTIONS, SESSIONS_DIR } from './paths.js';
|
|
19
20
|
import { checkLegacyProfile, runLegacyCutover } from './legacy-detector.js';
|
|
20
21
|
import { detectRuntimeCapability } from './runtime-detector.js';
|
|
21
22
|
import { backupCorruptProfile, loadProfile, profileExists, recomputeIfNeverReclassified } from '../store/profile-store.js';
|
|
22
|
-
import {
|
|
23
|
+
import { loadContextRules, cleanupStaleSessionRules, markRulesInjected } from '../store/rule-store.js';
|
|
23
24
|
import { composeSession } from '../preset/preset-manager.js';
|
|
24
|
-
import {
|
|
25
|
+
import { renderRulesDetailed, DEFAULT_CONTEXT } from '../renderer/rule-renderer.js';
|
|
26
|
+
import { recordRenderReport } from '../renderer/render-report.js';
|
|
25
27
|
import { saveSessionState, loadRecentSessions } from '../store/session-state-store.js';
|
|
26
28
|
import { loadEvidenceBySession } from '../store/evidence-store.js';
|
|
27
29
|
import { computeSessionSignals, detectMismatch } from '../forge/mismatch-detector.js';
|
|
@@ -41,7 +43,25 @@ export function ensureV1Directories() {
|
|
|
41
43
|
}
|
|
42
44
|
}
|
|
43
45
|
// ── Main Bootstrap ──
|
|
44
|
-
|
|
46
|
+
/**
|
|
47
|
+
* 프로필이 없어도(온보딩 전, 손상) 쌓아 둔 룰은 주입한다. 프로필은 4축 표시용이고 룰 본문과 무관하다.
|
|
48
|
+
* 프로필이 없다고 교정이 전부 무시되면 환경에 따라 규칙이 사라지는 셈이다.
|
|
49
|
+
*/
|
|
50
|
+
function renderWithoutProfile(cwd) {
|
|
51
|
+
try {
|
|
52
|
+
const rules = loadContextRules(cwd);
|
|
53
|
+
if (rules.length === 0)
|
|
54
|
+
return null;
|
|
55
|
+
const state = { warnings: [] };
|
|
56
|
+
const result = renderRulesDetailed(rules, state, null, DEFAULT_CONTEXT);
|
|
57
|
+
recordRenderReport(result);
|
|
58
|
+
return result.text;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export function bootstrapV1Session(cwd) {
|
|
45
65
|
// 0. 디렉토리 준비
|
|
46
66
|
ensureV1Directories();
|
|
47
67
|
// 1. Legacy 감지
|
|
@@ -50,6 +70,13 @@ export function bootstrapV1Session() {
|
|
|
50
70
|
if (legacyCheck.isLegacy) {
|
|
51
71
|
legacyBackupPath = runLegacyCutover();
|
|
52
72
|
}
|
|
73
|
+
// 세션 종료 추출이 못 돈 환경에서도 교정을 잃지 않게 먼저 승급한다. 프로필이 없어도 룰은 주입되므로 프로필 확인보다 앞선다.
|
|
74
|
+
try {
|
|
75
|
+
promoteSessionCandidates(crypto.randomUUID());
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// 승급 실패는 세션 시작을 막지 않음. 표시가 남아 있어 다음 기회에 다시 시도한다.
|
|
79
|
+
}
|
|
53
80
|
// 2. Profile 로드
|
|
54
81
|
if (!profileExists()) {
|
|
55
82
|
return {
|
|
@@ -57,7 +84,7 @@ export function bootstrapV1Session() {
|
|
|
57
84
|
legacyBackupPath,
|
|
58
85
|
corruptProfileBackupPath: null,
|
|
59
86
|
session: null,
|
|
60
|
-
renderedRules:
|
|
87
|
+
renderedRules: renderWithoutProfile(cwd),
|
|
61
88
|
profile: null,
|
|
62
89
|
mismatch: null,
|
|
63
90
|
};
|
|
@@ -80,7 +107,7 @@ export function bootstrapV1Session() {
|
|
|
80
107
|
legacyBackupPath,
|
|
81
108
|
corruptProfileBackupPath,
|
|
82
109
|
session: null,
|
|
83
|
-
renderedRules:
|
|
110
|
+
renderedRules: renderWithoutProfile(cwd),
|
|
84
111
|
profile: null,
|
|
85
112
|
mismatch: null,
|
|
86
113
|
};
|
|
@@ -89,14 +116,14 @@ export function bootstrapV1Session() {
|
|
|
89
116
|
const runtime = detectRuntimeCapability();
|
|
90
117
|
// 4. Rules 로드 + Session 합성
|
|
91
118
|
const sessionId = crypto.randomUUID();
|
|
92
|
-
// 이전 세션의 scope:'session' 임시 규칙
|
|
119
|
+
// 이전 세션의 scope:'session' 임시 규칙 정리.
|
|
93
120
|
try {
|
|
94
121
|
cleanupStaleSessionRules(sessionId);
|
|
95
122
|
}
|
|
96
123
|
catch {
|
|
97
124
|
// 정리 실패는 세션 시작을 막지 않음
|
|
98
125
|
}
|
|
99
|
-
const personalRules =
|
|
126
|
+
const personalRules = loadContextRules(cwd);
|
|
100
127
|
const session = composeSession({
|
|
101
128
|
session_id: sessionId,
|
|
102
129
|
profile,
|
|
@@ -108,13 +135,15 @@ export function bootstrapV1Session() {
|
|
|
108
135
|
saveSessionState(session);
|
|
109
136
|
// 6. Rule 렌더링
|
|
110
137
|
const allRules = [...personalRules];
|
|
111
|
-
const
|
|
138
|
+
const rendered = renderRulesDetailed(allRules, session, profile, DEFAULT_CONTEXT);
|
|
139
|
+
const renderedRules = rendered.text;
|
|
112
140
|
// 6b. Inject tracking (ADR-002 Meta signal) — rendered rules count as injected.
|
|
113
141
|
// Fail-open: tracking failure must not block bootstrap.
|
|
114
142
|
try {
|
|
115
|
-
const injected =
|
|
143
|
+
const injected = rendered.included.map((r) => r.rule_id);
|
|
116
144
|
if (injected.length > 0)
|
|
117
145
|
markRulesInjected(injected);
|
|
146
|
+
recordRenderReport(rendered);
|
|
118
147
|
}
|
|
119
148
|
catch { /* ignore */ }
|
|
120
149
|
// 7. Mismatch 감지 (최근 3세션 rolling)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* acted_on 신호의 증거 기준 (D6). "솔루션이 실제로 행동에 쓰였다"고 말하려면 우연히 겹친 단어로는 부족하다.
|
|
3
|
+
*
|
|
4
|
+
* 예전 판정은 솔루션 태그 중 **하나라도** 텍스트에 부분 문자열로 들어 있으면 acted_on 이었다. 사용자의 다음 프롬프트
|
|
5
|
+
* (prompt-keyword)가 같은 주제를 이어 말하기만 해도 걸려, 실데이터에서 오탐 솔루션 하나에 16건이 쌓였다. 이 기준은:
|
|
6
|
+
* - 식별자(함수·파일 이름 리터럴, 4자 이상)가 들어 있으면 증거,
|
|
7
|
+
* - 아니면 **흔하지 않은 태그가 서로 다른 2개 이상** 들어 있어야 증거 (흔한 태그·3자 미만은 세지 않는다).
|
|
8
|
+
* 영문 태그는 단어 경계로, 한글 태그는 부분 문자열로 찾는다.
|
|
9
|
+
*/
|
|
10
|
+
import { COMMON_TAGS } from './scoring-algorithms.js';
|
|
11
|
+
export const MIN_DISTINCT_TAG_HITS = 2;
|
|
12
|
+
/** camelCase 경계에 `_` 를 넣어(testDouble → test_double) snake_case·kebab-case 와 같은 모양으로 맞춘다. */
|
|
13
|
+
function splitCamel(text) {
|
|
14
|
+
return text.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
|
|
15
|
+
}
|
|
16
|
+
/** `test-double`·`test_double`·`testDouble`·`test double` 은 같은 태그다. 영문은 단어 경계(`_` 도 경계), 한글은 부분 문자열. */
|
|
17
|
+
function tagInText(tag, text) {
|
|
18
|
+
const t = tag.toLowerCase();
|
|
19
|
+
if (/^[a-z0-9_ -]+$/.test(t)) {
|
|
20
|
+
const parts = t.split(/[-_ ]+/).filter(Boolean);
|
|
21
|
+
if (parts.length === 0)
|
|
22
|
+
return false;
|
|
23
|
+
return new RegExp(`(^|[^a-z0-9])${parts.join('[-_ ]?')}($|[^a-z0-9])`).test(splitCamel(text));
|
|
24
|
+
}
|
|
25
|
+
return text.toLowerCase().includes(t);
|
|
26
|
+
}
|
|
27
|
+
/** 한글 등 비ASCII 태그는 2자(캐시·배포)부터, 영문은 3자부터 센다. */
|
|
28
|
+
function taggable(t) {
|
|
29
|
+
return /\P{ASCII}/u.test(t) ? t.length >= 2 : t.length >= 3;
|
|
30
|
+
}
|
|
31
|
+
export function actedOnEvidence(sol, text) {
|
|
32
|
+
const lower = text.toLowerCase();
|
|
33
|
+
const idHits = sol.identifiers.filter((id) => id.length >= 4 && lower.includes(id.toLowerCase()));
|
|
34
|
+
if (idHits.length > 0)
|
|
35
|
+
return { ok: true, hits: idHits };
|
|
36
|
+
const tagHits = [...new Set(sol.tags)].filter((t) => taggable(t) && !COMMON_TAGS.has(t.toLowerCase()) && tagInText(t, text));
|
|
37
|
+
return { ok: tagHits.length >= MIN_DISTINCT_TAG_HITS, hits: tagHits };
|
|
38
|
+
}
|
|
@@ -52,7 +52,7 @@ export declare function judgeViolation(violationId: string, deps?: {
|
|
|
52
52
|
}): Promise<Verdict | null>;
|
|
53
53
|
/**
|
|
54
54
|
* precision 강등: 7d 판정 ≥ DEMOTE_MIN_JUDGED 이고 precision < DEMOTE_PRECISION_BELOW 이면 enforce_mode='advise'.
|
|
55
|
-
* 하드 룰·builtin 제외(ADR-017 D1). 이미 advise 면 no-op.
|
|
55
|
+
* 하드 룰·builtin 제외(ADR-017 D1). 이미 advise 면 no-op. 사용자가 `forgen rule enforce` 로 켠 룰(명시 block)도 제외.
|
|
56
56
|
*/
|
|
57
57
|
export declare function maybeDemote(ruleId: string, now?: number): boolean;
|
|
58
58
|
/** 가장 최근 강등 기록(표시용). 없으면 null. */
|
|
@@ -60,6 +60,8 @@ export declare function lastDemotion(ruleId: string): {
|
|
|
60
60
|
at: string;
|
|
61
61
|
precision: number;
|
|
62
62
|
judged: number;
|
|
63
|
+
prev_mode?: 'block' | 'advise';
|
|
64
|
+
reason?: string;
|
|
63
65
|
} | null;
|
|
64
66
|
/**
|
|
65
67
|
* 훅에서 호출: detached 로 심판 프로세스를 띄운다. 훅 지연 0. 조건 미충족이면 즉시 return.
|
|
@@ -190,11 +190,11 @@ async function defaultExec(prompt) {
|
|
|
190
190
|
}
|
|
191
191
|
/**
|
|
192
192
|
* precision 강등: 7d 판정 ≥ DEMOTE_MIN_JUDGED 이고 precision < DEMOTE_PRECISION_BELOW 이면 enforce_mode='advise'.
|
|
193
|
-
* 하드 룰·builtin 제외(ADR-017 D1). 이미 advise 면 no-op.
|
|
193
|
+
* 하드 룰·builtin 제외(ADR-017 D1). 이미 advise 면 no-op. 사용자가 `forgen rule enforce` 로 켠 룰(명시 block)도 제외.
|
|
194
194
|
*/
|
|
195
195
|
export function maybeDemote(ruleId, now = Date.now()) {
|
|
196
196
|
const rule = loadRule(ruleId);
|
|
197
|
-
if (!rule || rule.strength === 'hard' || rule.enforce_mode
|
|
197
|
+
if (!rule || rule.strength === 'hard' || rule.enforce_mode)
|
|
198
198
|
return false;
|
|
199
199
|
const violations = readViolationsWindow(7, now);
|
|
200
200
|
const p = precisionByRule(violations, readVerdicts(), 7, now).get(ruleId);
|
|
@@ -202,11 +202,12 @@ export function maybeDemote(ruleId, now = Date.now()) {
|
|
|
202
202
|
return false;
|
|
203
203
|
if (p.correct + p.false_positive < DEMOTE_MIN_JUDGED || p.precision >= DEMOTE_PRECISION_BELOW)
|
|
204
204
|
return false;
|
|
205
|
+
const prevMode = rule.enforce_mode ?? 'block';
|
|
205
206
|
rule.enforce_mode = 'advise';
|
|
206
207
|
saveRule(rule);
|
|
207
208
|
try {
|
|
208
209
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
209
|
-
fs.appendFileSync(path.join(STATE_DIR, 'enforcement', 'demotions.jsonl'), `${JSON.stringify({ at: new Date(now).toISOString(), rule_id: ruleId, precision: p.precision, judged: p.correct + p.false_positive })}\n`);
|
|
210
|
+
fs.appendFileSync(path.join(STATE_DIR, 'enforcement', 'demotions.jsonl'), `${JSON.stringify({ at: new Date(now).toISOString(), rule_id: ruleId, precision: p.precision, judged: p.correct + p.false_positive, prev_mode: prevMode, reason: 'precision-auto' })}\n`);
|
|
210
211
|
}
|
|
211
212
|
catch { /* best-effort */ }
|
|
212
213
|
return true;
|
|
@@ -18,8 +18,22 @@ export declare function removeSolution(name: string): void;
|
|
|
18
18
|
* results until the user manually deletes them.
|
|
19
19
|
*/
|
|
20
20
|
export declare function cleanStaleSolutions(): void;
|
|
21
|
-
/**
|
|
22
|
-
|
|
21
|
+
/**
|
|
22
|
+
* 기존 솔루션의 태그를 현재 extractTags(조사·템플릿 단어·잘린 어간 정리 반영)로 다시 계산한다.
|
|
23
|
+
* 상태를 바꾸는 명령이라 기본은 미리보기 — `--apply` 를 줘야 쓴다. 입력은 저장 시와 같은 "제목 + 본문"이다
|
|
24
|
+
* (제목은 파일 이름 슬러그로 복원). 바뀌는 항목만 추가/제거 태그를 보여 준다.
|
|
25
|
+
*/
|
|
26
|
+
export declare function retagSolutions(apply?: boolean): {
|
|
27
|
+
changed: number;
|
|
28
|
+
total: number;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* 습관 로그(`works-with-typescript` 류)를 솔루션에서 behavior 로 옮긴다. 기본은 미리보기.
|
|
32
|
+
* 원본은 삭제하지 않고 me/solutions-archive/ 로 옮긴다(되돌릴 수 있게).
|
|
33
|
+
*/
|
|
34
|
+
export declare function migrateHabitLogs(apply?: boolean): {
|
|
35
|
+
moved: string[];
|
|
36
|
+
};
|
|
23
37
|
/** Result of a rollback operation — used by tests and callers that need counts. */
|
|
24
38
|
export interface RollbackCliResult {
|
|
25
39
|
archived: string[];
|
|
@@ -47,3 +61,13 @@ export interface RollbackCliResult {
|
|
|
47
61
|
export declare function rollbackSolutions(sinceDate: string, opts?: {
|
|
48
62
|
dryRun?: boolean;
|
|
49
63
|
}): RollbackCliResult;
|
|
64
|
+
export declare function listRetired(): Array<{
|
|
65
|
+
name: string;
|
|
66
|
+
reason: string;
|
|
67
|
+
confidence: number;
|
|
68
|
+
injected: number;
|
|
69
|
+
reflected: number;
|
|
70
|
+
negative: number;
|
|
71
|
+
created: string;
|
|
72
|
+
advice: string;
|
|
73
|
+
}>;
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import * as fs from 'node:fs';
|
|
2
2
|
import * as path from 'node:path';
|
|
3
|
-
import {
|
|
3
|
+
import { extractSolutionTags, parseFrontmatterOnly, parseSolutionV3 } from './solution-format.js';
|
|
4
4
|
import { mutateSolutionFile } from './solution-writer.js';
|
|
5
|
-
import { ARCHIVED_DIR, ME_SOLUTIONS, ME_RULES } from '../core/paths.js';
|
|
5
|
+
import { ARCHIVED_DIR, ME_SOLUTIONS, ME_RULES, ME_BEHAVIOR } from '../core/paths.js';
|
|
6
|
+
import { isHabitLog } from './solution-habit.js';
|
|
7
|
+
import { createSnapshot } from './rule-recovery-cli.js';
|
|
8
|
+
import { classifyBehaviorKind } from '../core/behavior-classifier.js';
|
|
6
9
|
/** Scan saved compound entries and return summaries */
|
|
7
10
|
function scanEntries() {
|
|
8
11
|
const summaries = [];
|
|
@@ -205,29 +208,116 @@ export function cleanStaleSolutions() {
|
|
|
205
208
|
console.log(' Tip: retired files are excluded from index + MCP search but');
|
|
206
209
|
console.log(' remain on disk. Use `forgen compound remove <name>` to delete.\n');
|
|
207
210
|
}
|
|
208
|
-
/**
|
|
209
|
-
|
|
211
|
+
/**
|
|
212
|
+
* 기존 솔루션의 태그를 현재 extractTags(조사·템플릿 단어·잘린 어간 정리 반영)로 다시 계산한다.
|
|
213
|
+
* 상태를 바꾸는 명령이라 기본은 미리보기 — `--apply` 를 줘야 쓴다. 입력은 저장 시와 같은 "제목 + 본문"이다
|
|
214
|
+
* (제목은 파일 이름 슬러그로 복원). 바뀌는 항목만 추가/제거 태그를 보여 준다.
|
|
215
|
+
*/
|
|
216
|
+
export function retagSolutions(apply = false) {
|
|
210
217
|
const entries = scanEntries().filter(e => e.category === 'solution');
|
|
211
218
|
if (entries.length === 0) {
|
|
212
219
|
console.log('\n No solutions to retag.\n');
|
|
213
|
-
return;
|
|
220
|
+
return { changed: 0, total: 0 };
|
|
214
221
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
let retagged = 0;
|
|
222
|
+
let changed = 0;
|
|
223
|
+
let snapshot = null;
|
|
218
224
|
for (const entry of entries) {
|
|
219
|
-
const
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
225
|
+
const parsed = parseSolutionV3(fs.readFileSync(entry.filePath, 'utf-8'));
|
|
226
|
+
if (!parsed || parsed.frontmatter.status === 'retired')
|
|
227
|
+
continue; // 은퇴본은 매칭 대상이 아니다
|
|
228
|
+
const title = parsed.frontmatter.name.replace(/-/g, ' ');
|
|
229
|
+
const text = `${title} ${parsed.content}`;
|
|
230
|
+
const extracted = extractSolutionTags(text);
|
|
231
|
+
const old = parsed.frontmatter.tags;
|
|
232
|
+
// 수동 태그 보존: 자동 추출 태그는 언제나 제목·본문에서 나온다. 본문에 없는 태그는 사람이 붙인 것으로 보고 남긴다.
|
|
233
|
+
const lower = `${text} ${parsed.context}`.toLowerCase();
|
|
234
|
+
const manual = old.filter(t => !lower.includes(t.toLowerCase()));
|
|
235
|
+
const newTags = [...new Set([...extracted, ...manual])];
|
|
236
|
+
const added = newTags.filter(t => !old.includes(t));
|
|
237
|
+
const removed = old.filter(t => !newTags.includes(t));
|
|
238
|
+
if (added.length === 0 && removed.length === 0)
|
|
239
|
+
continue;
|
|
240
|
+
changed++;
|
|
241
|
+
console.log(` ${entry.name}: +[${added.join(', ')}] -[${removed.join(', ')}]${manual.length ? ` (수동 태그 유지: ${manual.join(', ')})` : ''}`);
|
|
242
|
+
if (apply) {
|
|
243
|
+
// 적용 전 스냅샷 (forgen rule restore 로 되돌린다). 첫 변경 직전에 한 번만.
|
|
244
|
+
if (!snapshot) {
|
|
245
|
+
snapshot = createSnapshot('pre-retag');
|
|
246
|
+
console.log(` 스냅샷: ${snapshot} (되돌리기: forgen rule restore ${snapshot} --yes)`);
|
|
247
|
+
}
|
|
248
|
+
// PR2b: solution-writer.mutateSolutionFile 로 lock + fresh re-read. updated 는 건드리지 않는다 (오래됨 판정 기준이라).
|
|
249
|
+
const ok = mutateSolutionFile(entry.filePath, sol => {
|
|
250
|
+
sol.frontmatter.tags = newTags;
|
|
251
|
+
return true;
|
|
252
|
+
}, { touchUpdated: false });
|
|
253
|
+
if (!ok)
|
|
254
|
+
console.log(` Failed: ${entry.name}`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
console.log(`\n ${apply ? 'Retagged' : '[preview] would retag'} ${changed}/${entries.length} solutions.`);
|
|
258
|
+
if (!apply && changed > 0)
|
|
259
|
+
console.log(' 적용하려면: forgen compound retag --apply');
|
|
260
|
+
console.log();
|
|
261
|
+
return { changed, total: entries.length };
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* 습관 로그(`works-with-typescript` 류)를 솔루션에서 behavior 로 옮긴다. 기본은 미리보기.
|
|
265
|
+
* 원본은 삭제하지 않고 me/solutions-archive/ 로 옮긴다(되돌릴 수 있게).
|
|
266
|
+
*/
|
|
267
|
+
export function migrateHabitLogs(apply = false) {
|
|
268
|
+
const moved = [];
|
|
269
|
+
if (!fs.existsSync(ME_SOLUTIONS))
|
|
270
|
+
return { moved };
|
|
271
|
+
const archive = path.join(path.dirname(ME_SOLUTIONS), 'solutions-archive');
|
|
272
|
+
let snapshot = null;
|
|
273
|
+
for (const file of fs.readdirSync(ME_SOLUTIONS).filter(f => f.endsWith('.md'))) {
|
|
274
|
+
const filePath = path.join(ME_SOLUTIONS, file);
|
|
275
|
+
let raw;
|
|
276
|
+
try {
|
|
277
|
+
raw = fs.readFileSync(filePath, 'utf-8');
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
const parsed = parseSolutionV3(raw);
|
|
283
|
+
if (!parsed || !isHabitLog(parsed.frontmatter.name, raw))
|
|
284
|
+
continue;
|
|
285
|
+
const name = parsed.frontmatter.name;
|
|
286
|
+
// 파일 이름은 영숫자·한글·`-`·`_` 만 남긴다 (이름에 `/`, `..`, 따옴표 등이 있어도 behavior 밖으로 나가거나 frontmatter 를 깨지 않게).
|
|
287
|
+
const safe = name.replace(/[^\p{L}\p{N}_-]+/gu, '-').replace(/^-+|-+$/g, '') || 'unnamed';
|
|
288
|
+
const slug = `habit-${safe}`;
|
|
289
|
+
const dest = path.join(ME_BEHAVIOR, `${slug}.md`);
|
|
290
|
+
if (apply && fs.existsSync(dest)) {
|
|
291
|
+
console.log(` ${name} → 건너뜀: behavior/${slug}.md 가 이미 있다 (덮어쓰지 않음)`);
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
moved.push(name);
|
|
295
|
+
console.log(` ${name} → behavior (observed ${parsed.frontmatter.evidence.reflected})`);
|
|
296
|
+
if (!apply)
|
|
297
|
+
continue;
|
|
298
|
+
if (!snapshot) {
|
|
299
|
+
snapshot = createSnapshot('pre-habits');
|
|
300
|
+
console.log(` 스냅샷: ${snapshot} (되돌리기: forgen rule restore ${snapshot} --yes)`);
|
|
301
|
+
}
|
|
302
|
+
const today = new Date().toISOString().split('T')[0];
|
|
303
|
+
const kind = classifyBehaviorKind(parsed.content);
|
|
304
|
+
fs.mkdirSync(ME_BEHAVIOR, { recursive: true });
|
|
305
|
+
const q = (v) => JSON.stringify(v);
|
|
306
|
+
const body = `---\nname: ${q(slug)}\nversion: 1\nkind: ${q(kind)}\nobservedCount: ${Math.max(1, parsed.frontmatter.evidence.reflected)}\nconfidence: 0.6\ntags: ["auto-observed", "habit"]\ncreated: ${q(parsed.frontmatter.created)}\nupdated: ${q(today)}\nsource: "migrated-habit-log"\n---\n\n## Content\n${parsed.content}\n${parsed.context ? `\n## Origin\n${parsed.context}\n` : ''}`;
|
|
307
|
+
fs.writeFileSync(dest, body, { flag: 'wx' });
|
|
308
|
+
fs.mkdirSync(archive, { recursive: true });
|
|
309
|
+
let archived = path.join(archive, file);
|
|
310
|
+
if (fs.existsSync(archived))
|
|
311
|
+
archived = path.join(archive, `${Date.now()}-${file}`); // 덮어쓰지 않는다
|
|
312
|
+
fs.renameSync(filePath, archived);
|
|
229
313
|
}
|
|
230
|
-
console.log(`\n
|
|
314
|
+
console.log(`\n ${apply ? 'Moved' : '[preview] would move'} ${moved.length} habit log(s) to behavior.`);
|
|
315
|
+
if (!apply && moved.length > 0)
|
|
316
|
+
console.log(' 적용하려면: forgen compound habits --apply');
|
|
317
|
+
if (apply && snapshot)
|
|
318
|
+
console.log(` 되돌리기: forgen rule restore ${snapshot} --yes (원본은 me/solutions-archive/ 에도 남아 있다)`);
|
|
319
|
+
console.log();
|
|
320
|
+
return { moved };
|
|
231
321
|
}
|
|
232
322
|
/**
|
|
233
323
|
* Rollback auto-extracted solutions created since a given date.
|
|
@@ -302,3 +392,37 @@ export function rollbackSolutions(sinceDate, opts = {}) {
|
|
|
302
392
|
console.log(`\n ${result.archived.length}/${toRollback.length} archived. Restore from ${archiveDir} if needed.\n`);
|
|
303
393
|
return result;
|
|
304
394
|
}
|
|
395
|
+
/**
|
|
396
|
+
* 은퇴한 솔루션 목록과 복구 후보 판정. 읽기 전용 — 적용은 `forgen compound reopen <name>` 로만 한다.
|
|
397
|
+
* 사유(retiredReason)가 없는 구버전 은퇴는 "unknown" 으로 표시하고, 기록된 증거로 복구 우선순위를 낸다.
|
|
398
|
+
*/
|
|
399
|
+
const ageDays = (created) => (Date.now() - new Date(created).getTime()) / 86_400_000;
|
|
400
|
+
export function listRetired() {
|
|
401
|
+
const rows = [];
|
|
402
|
+
if (!fs.existsSync(ME_SOLUTIONS))
|
|
403
|
+
return rows;
|
|
404
|
+
for (const file of fs.readdirSync(ME_SOLUTIONS).filter(f => f.endsWith('.md'))) {
|
|
405
|
+
const fm = parseFrontmatterOnly(fs.readFileSync(path.join(ME_SOLUTIONS, file), 'utf-8'));
|
|
406
|
+
if (!fm || fm.status !== 'retired')
|
|
407
|
+
continue;
|
|
408
|
+
const ev = fm.evidence;
|
|
409
|
+
const reason = fm.retiredReason ?? 'unknown';
|
|
410
|
+
// 반증 증거(negative)가 있으면 복구 비추천. 없고 사용 흔적/최근성이 있으면 복구 후보.
|
|
411
|
+
const advice = isHabitLog(fm.name, fs.readFileSync(path.join(ME_SOLUTIONS, file), 'utf-8')) ? '복구 비추천 (습관 로그 — 솔루션이 아니라 behavior. compound habits 이관 대상)'
|
|
412
|
+
: ev.negative > 0 || reason === 'contradicted' ? '복구 비추천 (반증 증거)'
|
|
413
|
+
: reason === 'manual' ? '유지 (사용자가 끔)'
|
|
414
|
+
: ev.reflected > 0 || ev.injected > 0 ? '복구 후보 (사용 흔적 있음)'
|
|
415
|
+
: ageDays(fm.created) > 90 ? '복구 후보 (생성 90일 넘음 + 사용 흔적 없음 = 기간 경과 은퇴로 추정 — 내용 확인 후 결정)'
|
|
416
|
+
: '확인 필요 (생성 90일 안인데 은퇴됨 — 기간 경과가 아니라 수동·다른 경로로 끈 것으로 추정, 사유 기록 없음)';
|
|
417
|
+
rows.push({ name: fm.name, reason, confidence: fm.confidence, injected: ev.injected, reflected: ev.reflected, negative: ev.negative, created: fm.created, advice });
|
|
418
|
+
}
|
|
419
|
+
if (rows.length === 0)
|
|
420
|
+
console.log('\n 은퇴한 솔루션이 없습니다.\n');
|
|
421
|
+
else {
|
|
422
|
+
console.log(`\n 은퇴한 솔루션 ${rows.length}개 (읽기 전용):\n`);
|
|
423
|
+
for (const r of rows)
|
|
424
|
+
console.log(` ${r.name} [사유 ${r.reason}] conf=${r.confidence} injected=${r.injected} reflected=${r.reflected} negative=${r.negative} created=${r.created}\n → ${r.advice}`);
|
|
425
|
+
console.log('\n 복구: forgen compound reopen <name>\n');
|
|
426
|
+
}
|
|
427
|
+
return rows;
|
|
428
|
+
}
|