@wooojin/forgen 0.6.8 → 0.6.10
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 +27 -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 +145 -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 +177 -0
- package/dist/hooks/shared/hook-response.d.ts +12 -2
- package/dist/hooks/shared/hook-response.js +19 -3
- 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/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 +76 -899
- 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/store/rule-store.js
CHANGED
|
@@ -7,10 +7,12 @@
|
|
|
7
7
|
import * as fs from 'node:fs';
|
|
8
8
|
import * as path from 'node:path';
|
|
9
9
|
import * as crypto from 'node:crypto';
|
|
10
|
-
import { ME_RULES } from '../core/paths.js';
|
|
10
|
+
import { ME_RULES, ME_RULES_ARCHIVE } from '../core/paths.js';
|
|
11
11
|
import { atomicWriteJSON, safeReadJSON } from '../hooks/shared/atomic-write.js';
|
|
12
12
|
import { CURRENT_RULE_SCHEMA_VERSION } from './types.js';
|
|
13
|
-
import { initLifecycle, bumpInject } from './rule-lifecycle.js';
|
|
13
|
+
import { initLifecycle, bumpInject, withStatusChange } from './rule-lifecycle.js';
|
|
14
|
+
import { withFileLockSync } from '../hooks/shared/file-lock.js';
|
|
15
|
+
import { appliesForContext, appliesForEnforcement, projectKeyFor } from './rule-scope.js';
|
|
14
16
|
function rulePath(ruleId) {
|
|
15
17
|
return path.join(ME_RULES, `${ruleId}.json`);
|
|
16
18
|
}
|
|
@@ -27,11 +29,30 @@ export function createRule(params) {
|
|
|
27
29
|
status: 'active',
|
|
28
30
|
evidence_refs: params.evidence_refs ?? [],
|
|
29
31
|
render_key: params.render_key,
|
|
32
|
+
...(params.session_id ? { session_id: params.session_id } : {}),
|
|
33
|
+
...(params.projects?.length ? { projects: params.projects } : {}),
|
|
30
34
|
created_at: now,
|
|
31
35
|
updated_at: now,
|
|
32
36
|
};
|
|
33
37
|
}
|
|
38
|
+
/** 활성 룰을 사유 없이 비활성으로 바꾸려는 저장. 룰이 조용히 사라지는 것을 막는 불변식. */
|
|
39
|
+
export class RuleTransitionError extends Error {
|
|
40
|
+
constructor(ruleId, to) {
|
|
41
|
+
super(`rule ${ruleId}: active → ${to} requires a reason (use withStatusChange)`);
|
|
42
|
+
this.name = 'RuleTransitionError';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
34
45
|
export function saveRule(rule) {
|
|
46
|
+
const previous = safeReadJSON(rulePath(rule.rule_id), null);
|
|
47
|
+
if (previous?.status === 'active' && rule.status !== 'active') {
|
|
48
|
+
// 이전 전이의 사유를 재사용하지 못하게, 디스크에 없는 새 기록이어야 한다.
|
|
49
|
+
// 호출자가 오래된 룰 객체를 들고 있어도 길이 비교처럼 오탐하지 않는다.
|
|
50
|
+
const last = rule.status_history?.at(-1);
|
|
51
|
+
const isNew = last && !previous.status_history?.some((h) => h.at === last.at && h.to === last.to && h.reason === last.reason);
|
|
52
|
+
if (!last?.reason || last.from !== 'active' || last.to !== rule.status || !isNew) {
|
|
53
|
+
throw new RuleTransitionError(rule.rule_id, rule.status);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
35
56
|
rule.updated_at = new Date().toISOString();
|
|
36
57
|
// v0.4.1 audit-trail 불변식: rule 저장 시 lifecycle state 가 null/undefined 이면
|
|
37
58
|
// active phase 기본값 주입. 이전에는 old rule 파일이 lifecycle 없이 존재해 쌤 이후
|
|
@@ -101,6 +122,32 @@ export async function appendRule(rule) {
|
|
|
101
122
|
export function loadRule(ruleId) {
|
|
102
123
|
return safeReadJSON(rulePath(ruleId), null);
|
|
103
124
|
}
|
|
125
|
+
export function scanRuleFiles() {
|
|
126
|
+
const scan = { rules: [], broken: [] };
|
|
127
|
+
let files;
|
|
128
|
+
try {
|
|
129
|
+
if (!fs.existsSync(ME_RULES))
|
|
130
|
+
return scan;
|
|
131
|
+
files = fs.readdirSync(ME_RULES).filter((f) => f.endsWith('.json'));
|
|
132
|
+
}
|
|
133
|
+
catch (e) {
|
|
134
|
+
scan.dirError = e instanceof Error ? e.message : String(e);
|
|
135
|
+
return scan;
|
|
136
|
+
}
|
|
137
|
+
for (const file of files) {
|
|
138
|
+
try {
|
|
139
|
+
const rule = JSON.parse(fs.readFileSync(path.join(ME_RULES, file), 'utf-8'));
|
|
140
|
+
if (!rule || typeof rule !== 'object' || typeof rule.rule_id !== 'string')
|
|
141
|
+
throw new Error('룰 객체가 아님');
|
|
142
|
+
if (isCompatibleSchema(rule, file))
|
|
143
|
+
scan.rules.push(rule);
|
|
144
|
+
}
|
|
145
|
+
catch (e) {
|
|
146
|
+
scan.broken.push({ file, error: e instanceof Error ? e.message : String(e) });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return scan;
|
|
150
|
+
}
|
|
104
151
|
export function loadAllRules() {
|
|
105
152
|
const rules = [];
|
|
106
153
|
// 1) 사용자 개인 rules: ~/.forgen/me/rules
|
|
@@ -170,7 +217,17 @@ function resolveProjectRulesDir() {
|
|
|
170
217
|
return path.join(cwd, '.forgen', 'rules');
|
|
171
218
|
}
|
|
172
219
|
export function loadActiveRules() {
|
|
173
|
-
return loadAllRules().filter(r => r.status === 'active');
|
|
220
|
+
return loadAllRules().filter((r) => r.status === 'active');
|
|
221
|
+
}
|
|
222
|
+
/** 이 cwd 의 응답·도구 호출을 판정할 룰. 다른 프로젝트 룰은 제외한다. */
|
|
223
|
+
export function loadEnforcedRules(cwd = process.env.FORGEN_CWD ?? process.cwd()) {
|
|
224
|
+
const key = projectKeyFor(cwd);
|
|
225
|
+
return loadActiveRules().filter((r) => appliesForEnforcement(r, key));
|
|
226
|
+
}
|
|
227
|
+
/** 이 cwd 의 세션 컨텍스트에 넣을 룰. */
|
|
228
|
+
export function loadContextRules(cwd = process.env.FORGEN_CWD ?? process.cwd()) {
|
|
229
|
+
const key = projectKeyFor(cwd);
|
|
230
|
+
return loadActiveRules().filter((r) => appliesForContext(r, key));
|
|
174
231
|
}
|
|
175
232
|
/**
|
|
176
233
|
* render_key(+source, +scope)로 기존 rule을 찾는다 — status 무관(active/suppressed/removed/
|
|
@@ -211,16 +268,22 @@ export function findRuleByRenderKey(renderKey, source, scope) {
|
|
|
211
268
|
*/
|
|
212
269
|
export function markRulesInjected(ruleIds, nowIso = new Date().toISOString()) {
|
|
213
270
|
for (const id of ruleIds) {
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
271
|
+
try {
|
|
272
|
+
// lock 없이 읽고 쓰면 다른 프로세스의 상태 전이를 되돌릴 수 있다. 카운터라 실패해도 건너뛴다.
|
|
273
|
+
withFileLockSync(rulePath(id), () => {
|
|
274
|
+
const rule = loadRule(id);
|
|
275
|
+
if (!rule)
|
|
276
|
+
return;
|
|
277
|
+
// R6-F1: initLifecycle 이 정규화(카운터 ≥0, 배열 보장) 까지 포함.
|
|
278
|
+
const lifecycle = initLifecycle(rule);
|
|
279
|
+
const updated = {
|
|
280
|
+
...rule,
|
|
281
|
+
lifecycle: bumpInject(lifecycle, nowIso),
|
|
282
|
+
};
|
|
283
|
+
atomicWriteJSON(rulePath(rule.rule_id), updated, { pretty: true });
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
catch { /* 주입 카운터는 best-effort */ }
|
|
224
287
|
}
|
|
225
288
|
}
|
|
226
289
|
/**
|
|
@@ -243,18 +306,23 @@ export function syncRuleCounters(ruleId, counters) {
|
|
|
243
306
|
atomicWriteJSON(rulePath(rule.rule_id), updated, { pretty: true });
|
|
244
307
|
return true;
|
|
245
308
|
}
|
|
246
|
-
export function updateRuleStatus(ruleId, status) {
|
|
247
|
-
const
|
|
248
|
-
if (!
|
|
309
|
+
export function updateRuleStatus(ruleId, status, reason, by = 'system') {
|
|
310
|
+
const filePath = rulePath(ruleId);
|
|
311
|
+
if (!fs.existsSync(filePath))
|
|
249
312
|
return false;
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
313
|
+
return withFileLockSync(filePath, () => {
|
|
314
|
+
const rule = loadRule(ruleId);
|
|
315
|
+
if (!rule)
|
|
316
|
+
return false;
|
|
317
|
+
saveRule(withStatusChange(rule, status, reason, by));
|
|
318
|
+
return true;
|
|
319
|
+
});
|
|
253
320
|
}
|
|
254
321
|
/** removed 룰 보관 기간 기본값 — 7일. TTL 로 은퇴된 지 이만큼 지나면 prune 대상. */
|
|
255
322
|
export const DEFAULT_PRUNE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
256
323
|
/**
|
|
257
|
-
* status:'removed' 파일을 retention 기간이 지난 것만
|
|
324
|
+
* status:'removed' 파일을 retention 기간이 지난 것만 rules-archive 로 옮긴다(영구 삭제 금지).
|
|
325
|
+
* 교정 유실 조사(2026-11-04): 누적 1,352개가 unlink 되어 대조·복구가 불가능했다.
|
|
258
326
|
* RCA: retire(updateRuleStatus)는 status flip만 하고 파일을 지우지 않아 6,525개 죽은
|
|
259
327
|
* 파일이 ~/.forgen/me/rules 에 쌓여 loadAllRules() linear scan 비용을 키우고
|
|
260
328
|
* cross-process race 창을 넓혔다. status 전이 시각(updated_at) 기준으로 retention을
|
|
@@ -291,7 +359,8 @@ export function pruneRemovedRules(opts = {}) {
|
|
|
291
359
|
candidates.push(rule.rule_id);
|
|
292
360
|
if (apply) {
|
|
293
361
|
try {
|
|
294
|
-
fs.
|
|
362
|
+
fs.mkdirSync(ME_RULES_ARCHIVE, { recursive: true });
|
|
363
|
+
fs.renameSync(filePath, path.join(ME_RULES_ARCHIVE, file));
|
|
295
364
|
deleted.push(rule.rule_id);
|
|
296
365
|
}
|
|
297
366
|
catch { /* best-effort — 다음 prune 에서 재시도 */ }
|
|
@@ -299,7 +368,13 @@ export function pruneRemovedRules(opts = {}) {
|
|
|
299
368
|
}
|
|
300
369
|
return { candidates, deleted };
|
|
301
370
|
}
|
|
302
|
-
|
|
371
|
+
/**
|
|
372
|
+
* 임시 룰 유예. 끝난 세션인지 판별할 수단이 없어 시간으로 판단한다.
|
|
373
|
+
* session_id 로 소유 세션을 가리지 않는다: 모델 입력·하네스 UUID·Claude Code 값이 서로 달라
|
|
374
|
+
* 믿을 수 없고, 다른 세션에 잠시 적용되는 것보다 교정이 자기 세션에서 무시되는 쪽이 더 나쁘다.
|
|
375
|
+
*/
|
|
376
|
+
const SESSION_RULE_GRACE_MS = 12 * 60 * 60 * 1000;
|
|
377
|
+
export function cleanupStaleSessionRules(currentSessionId, nowMs = Date.now()) {
|
|
303
378
|
if (!fs.existsSync(ME_RULES))
|
|
304
379
|
return 0;
|
|
305
380
|
let cleaned = 0;
|
|
@@ -308,12 +383,21 @@ export function cleanupStaleSessionRules(_currentSessionId) {
|
|
|
308
383
|
continue;
|
|
309
384
|
const filePath = path.join(ME_RULES, file);
|
|
310
385
|
const rule = safeReadJSON(filePath, null);
|
|
311
|
-
if (rule
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
386
|
+
if (!rule || rule.scope !== 'session' || rule.status !== 'active')
|
|
387
|
+
continue;
|
|
388
|
+
if (rule.session_id === currentSessionId)
|
|
389
|
+
continue;
|
|
390
|
+
if (rule.session_id && nowMs - Date.parse(rule.updated_at) < SESSION_RULE_GRACE_MS)
|
|
391
|
+
continue;
|
|
392
|
+
try {
|
|
393
|
+
withFileLockSync(filePath, () => {
|
|
394
|
+
const fresh = safeReadJSON(filePath, null);
|
|
395
|
+
if (fresh?.status === 'active')
|
|
396
|
+
saveRule(withStatusChange(fresh, 'suppressed', 'session-ended', 'session-cleanup'));
|
|
397
|
+
});
|
|
315
398
|
cleaned++;
|
|
316
399
|
}
|
|
400
|
+
catch { /* 다음 세션 시작에서 재시도 */ }
|
|
317
401
|
}
|
|
318
402
|
return cleaned;
|
|
319
403
|
}
|
package/dist/store/types.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ export type TrustPolicy = '가드레일 우선' | '승인 완화' | '완전 신
|
|
|
13
13
|
export type RuleCategory = 'quality' | 'autonomy' | 'communication' | 'workflow' | 'safety';
|
|
14
14
|
export type RuleScope = 'me' | 'session';
|
|
15
15
|
export type RuleStrength = 'soft' | 'default' | 'strong' | 'hard';
|
|
16
|
-
export type RuleSource = 'onboarding' | 'explicit_correction' | 'behavior_inference' | 'pack_overlay';
|
|
16
|
+
export type RuleSource = 'onboarding' | 'explicit_correction' | 'behavior_inference' | 'pack_overlay' | 'imported';
|
|
17
17
|
export type RuleStatus = 'active' | 'suppressed' | 'removed' | 'superseded';
|
|
18
18
|
export type EnforcementMech = 'A' | 'B' | 'C';
|
|
19
19
|
export type HookPoint = 'PreToolUse' | 'PostToolUse' | 'Stop' | 'UserPromptSubmit';
|
|
@@ -89,6 +89,13 @@ export interface LifecycleState {
|
|
|
89
89
|
* 만 비어있을 뿐 로드 가능). 미래 breaking change 시 이 값을 증가시키고 `migrate()` 체인으로 흡수.
|
|
90
90
|
*/
|
|
91
91
|
export declare const CURRENT_RULE_SCHEMA_VERSION = 1;
|
|
92
|
+
export interface RuleStatusChange {
|
|
93
|
+
at: string;
|
|
94
|
+
from: RuleStatus;
|
|
95
|
+
to: RuleStatus;
|
|
96
|
+
reason: string;
|
|
97
|
+
by: string;
|
|
98
|
+
}
|
|
92
99
|
export interface Rule {
|
|
93
100
|
/** R5-B3: 미래 breaking schema change 를 위한 version 필드. 없으면 v0 (pre-0.4.0) 으로 취급. */
|
|
94
101
|
schema_version?: number;
|
|
@@ -104,6 +111,14 @@ export interface Rule {
|
|
|
104
111
|
render_key: string;
|
|
105
112
|
created_at: string;
|
|
106
113
|
updated_at: string;
|
|
114
|
+
/** 이 프로젝트들에서만 적용. 없으면 전역. rule-scope.ts 참고. */
|
|
115
|
+
projects?: string[];
|
|
116
|
+
/** source 'imported' 일 때 가져온 곳(파일 경로 등). 사용자 발화가 아니라는 표시이기도 하다. */
|
|
117
|
+
imported_from?: string;
|
|
118
|
+
/** 세션 임시 룰의 소유 세션. 다른 실행 중인 세션의 임시 룰을 정리하지 않기 위해 쓴다. */
|
|
119
|
+
session_id?: string;
|
|
120
|
+
/** 상태 전이 기록. 활성 룰을 비활성으로 바꾸려면 사유가 있어야 한다(saveRule 이 강제). */
|
|
121
|
+
status_history?: RuleStatusChange[];
|
|
107
122
|
/**
|
|
108
123
|
* 이 rule 이 어떤 hook/verifier 로 강제되는가. optional — 기존 rule 은 null.
|
|
109
124
|
* `forgen classify-enforce` 명령이 기존 rule 을 자동 분류하여 채운다.
|
|
@@ -112,7 +127,8 @@ export interface Rule {
|
|
|
112
127
|
enforce_via?: EnforceSpec[];
|
|
113
128
|
/**
|
|
114
129
|
* ADR-017 D1: precision 자동 강등. 'advise' 면 Mech-A/B 가 차단 대신 기록(kind:'correction')만 한다.
|
|
115
|
-
* 하드 룰(strength 'hard')과 builtin 은 자동으로 'advise' 가 되지 않는다.
|
|
130
|
+
* 하드 룰(strength 'hard')과 builtin 은 자동으로 'advise' 가 되지 않는다.
|
|
131
|
+
* 미지정 = rule-detectability.effectiveEnforceMode 가 결정(의미 룰은 기록만, 결정적 탐지기·hard 는 차단).
|
|
116
132
|
*/
|
|
117
133
|
enforce_mode?: 'block' | 'advise';
|
|
118
134
|
/**
|
|
@@ -268,6 +284,10 @@ export interface CorrectionRequest {
|
|
|
268
284
|
* 차단 메시지가 "당신의 말" 로 인용한다. <private> 필터 후 저장.
|
|
269
285
|
*/
|
|
270
286
|
user_quote?: string;
|
|
287
|
+
/** 이 교정이 폐기·대체·수정하려는 기존 룰. 지목이 없으면 기존 룰은 바뀌지 않는다. */
|
|
288
|
+
rule_id?: string;
|
|
289
|
+
/** 이 프로젝트에만 적용되는 교정이면 프로젝트 키. */
|
|
290
|
+
projects?: string[];
|
|
271
291
|
}
|
|
272
292
|
export interface CorrectionResult {
|
|
273
293
|
temporary_rule: Rule | null;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function handleWay(args: string[]): Promise<void>;
|
package/dist/way/cli.js
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* forgen way — 내 방식 요약·내보내기·가져오기·메모리 수집 (ADR-020).
|
|
3
|
+
* forgen way [--all] [--json]
|
|
4
|
+
* forgen way export --target <t> [--project k] [--budget n] [--out dir] [--force] [--habits] [--item id]
|
|
5
|
+
* forgen way import <file.json> [--apply]
|
|
6
|
+
* forgen way collect-memory [--dir path] [--project key] [--apply] [--json]
|
|
7
|
+
* forgen way draft <skill|workflow> "<주제>" [--project k] [--out dir] [--force] [--no-llm]
|
|
8
|
+
*/
|
|
9
|
+
import * as fs from 'node:fs';
|
|
10
|
+
import * as path from 'node:path';
|
|
11
|
+
import { loadRenderReport } from '../renderer/render-report.js';
|
|
12
|
+
import { createSnapshot } from '../engine/rule-recovery-cli.js';
|
|
13
|
+
import { loadAllRules } from '../store/rule-store.js';
|
|
14
|
+
import { compile, projectSpecificSuspects } from './compile.js';
|
|
15
|
+
import { draftFiles, gatherSources, readTopic, writeDraft } from './draft.js';
|
|
16
|
+
import { buildWay } from './extract.js';
|
|
17
|
+
import { applyImport, candidateToItem, parseWayJson, planImport, readMemoryCandidates, writeFiles } from './io.js';
|
|
18
|
+
import { COMPILE_TARGETS } from './types.js';
|
|
19
|
+
function flag(args, name) {
|
|
20
|
+
const i = args.indexOf(name);
|
|
21
|
+
return i >= 0 && i + 1 < args.length && !args[i + 1].startsWith('--') ? args[i + 1] : undefined;
|
|
22
|
+
}
|
|
23
|
+
function flags(args, name) {
|
|
24
|
+
const out = [];
|
|
25
|
+
args.forEach((a, i) => { if (a === name && args[i + 1] && !args[i + 1].startsWith('--'))
|
|
26
|
+
out.push(args[i + 1]); });
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
function blockedMessage(b, hint) {
|
|
30
|
+
if (b.action === 'blocked-escape')
|
|
31
|
+
return `[forgen] 거부: ${b.abs} 는 --out 의 실경로 밖이다 (.. 또는 심링크). 쓰지 않는다.`;
|
|
32
|
+
if (b.action === 'blocked-foreign')
|
|
33
|
+
return `[forgen] 거부: ${b.abs} 는 forgen way 가 만든 파일이 아니다(파일 앞부분에 표식 줄이 없다). --force 로도 덮어쓰지 않는다.${hint}`;
|
|
34
|
+
return `[forgen] 거부: ${b.abs} 가 이미 있고 내용이 다르다. 덮어쓰려면 --force (기존 파일은 백업된다).`;
|
|
35
|
+
}
|
|
36
|
+
/** 대상별 전역(사용자 수준) 위치. 1차 문서 기준(ADR-020). `--out` 은 그 위치의 루트다. */
|
|
37
|
+
const GLOBAL_HINT = {
|
|
38
|
+
'agents-md': '전역(Codex): --out ~/.codex → ~/.codex/AGENTS.md ($CODEX_HOME). 같은 위치에 AGENTS.override.md 가 있으면 그것만 읽힌다. 프로젝트: --out <프로젝트 루트>',
|
|
39
|
+
'claude-rules': '전역(Claude Code): --out ~ → ~/.claude/rules/forgen-way.md. forgen 렌더(v1-rules.md)와 같은 룰이 두 번 들어갈 수 있다',
|
|
40
|
+
skill: '전역(Claude Code): --out ~ → ~/.claude/skills/<name>/SKILL.md. 프로젝트: --out <프로젝트 루트>',
|
|
41
|
+
gemini: '전역(Gemini CLI): --out ~/.gemini → ~/.gemini/GEMINI.md. 프로젝트: --out <프로젝트 루트>',
|
|
42
|
+
cursor: '전역 파일 없음: Cursor 의 User Rules 는 Customize → Rules 화면에 붙여넣는다. 프로젝트: --out <프로젝트 루트> (.cursor/rules)',
|
|
43
|
+
};
|
|
44
|
+
const clip = (s, n) => { const t = s.replace(/\s+/g, ' ').trim(); return t.length > n ? `${t.slice(0, n - 1)}…` : t; };
|
|
45
|
+
const scope = (i) => (i.projects.length ? i.projects.join(',') : '전역');
|
|
46
|
+
function summary(way, all) {
|
|
47
|
+
const rules = way.items.filter((i) => i.kind === 'rule' && i.status === 'active');
|
|
48
|
+
const said = rules.filter((i) => i.provenance.kind === 'you-said');
|
|
49
|
+
const mined = rules.filter((i) => i.provenance.kind === 'mined');
|
|
50
|
+
const imported = rules.filter((i) => i.provenance.kind === 'imported');
|
|
51
|
+
const sols = way.items.filter((i) => i.kind === 'solution');
|
|
52
|
+
const habits = way.items.filter((i) => i.kind === 'habit');
|
|
53
|
+
const cap = all ? Infinity : 4;
|
|
54
|
+
const out = [];
|
|
55
|
+
const mark = (i) => (i.enforceable ? '강제' : '자문');
|
|
56
|
+
const quoted = said.filter((i) => i.provenance.kind === 'you-said' && i.provenance.quote).length;
|
|
57
|
+
out.push(`내가 말한 규칙 ${said.length} (발화 원문 있음 ${quoted}, 날짜만 ${said.length - quoted})`);
|
|
58
|
+
const byScope = new Map();
|
|
59
|
+
for (const i of said)
|
|
60
|
+
byScope.set(scope(i), [...(byScope.get(scope(i)) ?? []), i]);
|
|
61
|
+
for (const [sc, list] of [...byScope].sort((a, b) => (a[0] === '전역' ? -1 : b[0] === '전역' ? 1 : a[0].localeCompare(b[0])))) {
|
|
62
|
+
out.push(` [${sc}] ${list.length}`);
|
|
63
|
+
list.slice(0, cap).forEach((i) => out.push(` ${i.strength.padEnd(7)} ${mark(i)} ${clip(i.statement, 74)}`));
|
|
64
|
+
if (list.length > cap)
|
|
65
|
+
out.push(` … 외 ${list.length - cap}개 (--all)`);
|
|
66
|
+
}
|
|
67
|
+
out.push('', `추론된 규칙 ${mined.length} (행동에서 채굴. 내가 한 말이 아님)`);
|
|
68
|
+
mined.slice(0, all ? Infinity : 3).forEach((i) => out.push(` ${i.strength.padEnd(7)} ${mark(i)} [${scope(i)}] ${clip(i.statement, 66)}`));
|
|
69
|
+
if (!all && mined.length > 3)
|
|
70
|
+
out.push(` … 외 ${mined.length - 3}개 (--all)`);
|
|
71
|
+
if (imported.length)
|
|
72
|
+
out.push('', `가져온 규칙 ${imported.length} (호스트 메모리 등)`);
|
|
73
|
+
out.push('', `검증된 솔루션 ${way.stats.solutions_verified} (미검증 ${way.stats.solutions_unverified}는 내보내지 않음)`);
|
|
74
|
+
if (all)
|
|
75
|
+
sols.forEach((i) => out.push(` ${clip(i.id.replace('solution:', ''), 70)}`));
|
|
76
|
+
out.push(`습관 ${habits.length} (기본 내보내기에서 제외, --habits 로 포함)`);
|
|
77
|
+
if (all)
|
|
78
|
+
habits.forEach((i) => out.push(` ${clip(i.statement, 74)}`));
|
|
79
|
+
const suspects = projectSpecificSuspects(way.items.filter((i) => i.kind === 'rule' && i.status === 'active'));
|
|
80
|
+
if (suspects.length) {
|
|
81
|
+
out.push('', `프로젝트 전용일 수 있는 전역 룰 ${suspects.length}개 (프로젝트 미지정 산출물에 섞인다). forgen rule classify-projects --project <키> --keywords a,b`);
|
|
82
|
+
if (all)
|
|
83
|
+
suspects.forEach((x) => out.push(` ${x.id.slice(0, 8)} ${x.why}`));
|
|
84
|
+
}
|
|
85
|
+
const habitConflicts = habits.filter((h) => h.conflicts_with);
|
|
86
|
+
if (habitConflicts.length)
|
|
87
|
+
out.push(`활성 룰과 상반되는 습관 ${habitConflicts.length}개 (내보내기에서 제외)`);
|
|
88
|
+
out.push('', `강제 중 ${way.stats.rules_enforceable} / 자문 ${way.stats.rules_active - way.stats.rules_enforceable} (강제 = 위반 시 실제로 막는 룰. 다른 모델 산출물에서는 모두 자문)`);
|
|
89
|
+
const rep = loadRenderReport();
|
|
90
|
+
if (!rep)
|
|
91
|
+
out.push('렌더: 기록 없음');
|
|
92
|
+
else {
|
|
93
|
+
const strong = rep.omitted.filter((o) => o.strength === 'strong' || o.strength === 'hard').length;
|
|
94
|
+
out.push(`렌더 누락: ${rep.omitted.length}개 (strong 이상 ${strong}) / 포함 ${rep.included.length} [${rep.at.slice(0, 16).replace('T', ' ')}]`);
|
|
95
|
+
if (all)
|
|
96
|
+
rep.omitted.forEach((o) => out.push(` ${o.strength.padEnd(7)} ${clip(o.policy, 70)}`));
|
|
97
|
+
}
|
|
98
|
+
return out.join('\n');
|
|
99
|
+
}
|
|
100
|
+
function cmdExport(args) {
|
|
101
|
+
const target = flag(args, '--target');
|
|
102
|
+
if (!target || !COMPILE_TARGETS.includes(target)) {
|
|
103
|
+
console.error(`[forgen] --target 이 필요하다: ${COMPILE_TARGETS.join(' | ')}`);
|
|
104
|
+
return 1;
|
|
105
|
+
}
|
|
106
|
+
const budgetRaw = flag(args, '--budget');
|
|
107
|
+
const budget = budgetRaw === undefined ? undefined : Number(budgetRaw);
|
|
108
|
+
if (budget !== undefined && (!Number.isFinite(budget) || budget <= 0)) {
|
|
109
|
+
console.error('[forgen] --budget 은 양의 정수');
|
|
110
|
+
return 1;
|
|
111
|
+
}
|
|
112
|
+
const only = flags(args, '--item');
|
|
113
|
+
const way = buildWay();
|
|
114
|
+
const res = compile(way, target, { project: flag(args, '--project')?.toLowerCase(), budget, habits: args.includes('--habits'), only: only.length ? only : undefined });
|
|
115
|
+
const out = flag(args, '--out');
|
|
116
|
+
const report = [];
|
|
117
|
+
const byReason = new Map();
|
|
118
|
+
for (const o of res.omitted)
|
|
119
|
+
byReason.set(o.reason, (byReason.get(o.reason) ?? 0) + 1);
|
|
120
|
+
const wayOf = (id) => way.items.find((i) => i.id === id);
|
|
121
|
+
report.push(`[forgen] ${target}: 파일 ${res.files.length}개, 빠진 항목 ${res.omitted.length}개${byReason.size ? ` (${[...byReason].map(([k, v]) => `${k} ${v}`).join(', ')})` : ''}, 자문 전환 ${res.degraded.length}개`);
|
|
122
|
+
for (const o of res.omitted.filter((x) => x.reason === 'budget'))
|
|
123
|
+
report.push(` 예산으로 뺌: ${clip(wayOf(o.id)?.statement ?? o.id, 70)}`);
|
|
124
|
+
for (const d of res.degraded.slice(0, 5))
|
|
125
|
+
report.push(` ${clip(wayOf(d.id)?.statement ?? d.id, 50)} → ${d.reason}`);
|
|
126
|
+
if (res.degraded.length > 5)
|
|
127
|
+
report.push(` … 외 ${res.degraded.length - 5}개`);
|
|
128
|
+
for (const w of res.warnings)
|
|
129
|
+
report.push(` 경고: ${w}`);
|
|
130
|
+
if (GLOBAL_HINT[target])
|
|
131
|
+
report.push(` 위치: ${GLOBAL_HINT[target]}`);
|
|
132
|
+
if (!res.files.length) {
|
|
133
|
+
console.error(`${report.join('\n')}\n[forgen] 내보낼 항목이 없다.`);
|
|
134
|
+
return 1;
|
|
135
|
+
}
|
|
136
|
+
if (!out) {
|
|
137
|
+
for (const f of res.files)
|
|
138
|
+
console.log(`===== ${f.path} =====\n${f.content}`);
|
|
139
|
+
console.error(`${report.join('\n')}\n[forgen] 미리보기. 파일로 쓰려면 --out <dir>`);
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
const outDir = path.resolve(out);
|
|
143
|
+
const { plan, written } = writeFiles(res.files, outDir, args.includes('--force'));
|
|
144
|
+
for (const p of plan)
|
|
145
|
+
console.log(` ${p.action.padEnd(15)} ${path.join(outDir, p.path)}`);
|
|
146
|
+
console.log(report.join('\n'));
|
|
147
|
+
const blocked = plan.filter((p) => p.action.startsWith('blocked'));
|
|
148
|
+
if (blocked.length) {
|
|
149
|
+
for (const b of blocked)
|
|
150
|
+
console.error(blockedMessage(b, ' 다른 --out 을 쓰거나 파일을 옮겨라.'));
|
|
151
|
+
console.error('[forgen] 아무 파일도 쓰지 않았다.');
|
|
152
|
+
return 1;
|
|
153
|
+
}
|
|
154
|
+
for (const p of plan.filter((x) => x.backup))
|
|
155
|
+
console.log(` 백업 ${p.backup}`);
|
|
156
|
+
console.log(`[forgen] ${written}개 작성 (${outDir})`);
|
|
157
|
+
return 0;
|
|
158
|
+
}
|
|
159
|
+
function cmdImport(args) {
|
|
160
|
+
const file = args.find((a, i) => !a.startsWith('--') && (i === 0 || !args[i - 1].startsWith('--')));
|
|
161
|
+
if (!file) {
|
|
162
|
+
console.error('[forgen] 사용법: forgen way import <file.json> [--apply] [--allow-enforced-edit]');
|
|
163
|
+
return 1;
|
|
164
|
+
}
|
|
165
|
+
let text;
|
|
166
|
+
try {
|
|
167
|
+
text = fs.readFileSync(file, 'utf-8');
|
|
168
|
+
}
|
|
169
|
+
catch (e) {
|
|
170
|
+
console.error(`[forgen] 파일을 읽을 수 없다: ${e.message}`);
|
|
171
|
+
return 1;
|
|
172
|
+
}
|
|
173
|
+
const parsed = parseWayJson(text);
|
|
174
|
+
if (!parsed.ok) {
|
|
175
|
+
console.error(`[forgen] 스키마 오류 ${parsed.errors.length}건:\n${parsed.errors.map((e) => ` - ${e}`).join('\n')}`);
|
|
176
|
+
return 1;
|
|
177
|
+
}
|
|
178
|
+
const plan = planImport(parsed.items, loadAllRules(), { allowEnforcedEdit: args.includes('--allow-enforced-edit') });
|
|
179
|
+
for (const c of plan.changes)
|
|
180
|
+
console.log(` ${c.field.padEnd(9)} ${c.id.slice(0, 8)} ${c.from !== undefined ? `${clip(c.from, 50)} → ` : ''}${clip(c.to, 60)}`);
|
|
181
|
+
for (const ig of plan.ignored)
|
|
182
|
+
console.log(` 무시 ${ig.id.slice(0, 8)} ${ig.reason}`);
|
|
183
|
+
for (const w of plan.warnings)
|
|
184
|
+
console.log(` 경고 ${w}`);
|
|
185
|
+
for (const e of plan.errors)
|
|
186
|
+
console.error(` 오류 ${e}`);
|
|
187
|
+
console.log(`[forgen] 변경 ${plan.changes.length}건, 무시 ${plan.ignored.length}건, 오류 ${plan.errors.length}건`);
|
|
188
|
+
if (plan.errors.length) {
|
|
189
|
+
console.error('[forgen] 오류가 있어 적용하지 않는다.');
|
|
190
|
+
return 1;
|
|
191
|
+
}
|
|
192
|
+
if (!args.includes('--apply')) {
|
|
193
|
+
console.log('[forgen] 미리보기. 적용하려면 --apply');
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
const snap = createSnapshot('pre-way-import');
|
|
197
|
+
console.log(`[forgen] 적용 전 스냅샷 ${snap} (복원: forgen rule restore ${snap} --yes)`);
|
|
198
|
+
const r = applyImport(parsed.items, plan);
|
|
199
|
+
console.log(`[forgen] 적용 ${r.applied}건${r.created.length ? ` (새 룰 ${r.created.length})` : ''}. 렌더는 다음 세션 시작 때 반영된다.`);
|
|
200
|
+
return 0;
|
|
201
|
+
}
|
|
202
|
+
const shown = (c) => (c.excluded?.reason === 'secret' ? '(비밀로 보여 내용 숨김)' : clip(c.statement, 50));
|
|
203
|
+
function cmdCollect(args) {
|
|
204
|
+
const rules = loadAllRules();
|
|
205
|
+
const { candidates, scanned } = readMemoryCandidates(flag(args, '--dir'), rules);
|
|
206
|
+
const override = flag(args, '--project')?.toLowerCase();
|
|
207
|
+
const fresh = candidates.filter((c) => !c.excluded);
|
|
208
|
+
const excluded = candidates.filter((c) => c.excluded);
|
|
209
|
+
if (args.includes('--json')) {
|
|
210
|
+
const items = fresh.map((c) => candidateToItem(c, override));
|
|
211
|
+
for (const c of excluded)
|
|
212
|
+
console.error(`제외 [${c.excluded?.reason}] ${shown(c)} (${c.source})`);
|
|
213
|
+
console.log(JSON.stringify({ schema: 'forgen-way/1', generator: 'forgen-way', generated_at: new Date().toISOString(), items }, null, 2));
|
|
214
|
+
return 0;
|
|
215
|
+
}
|
|
216
|
+
const byReason = new Map();
|
|
217
|
+
for (const c of excluded)
|
|
218
|
+
byReason.set(c.excluded?.reason ?? '', (byReason.get(c.excluded?.reason ?? '') ?? 0) + 1);
|
|
219
|
+
console.log(`메모리 파일 ${scanned.length}개 → 후보 ${candidates.length}개 (새 ${fresh.length}, 제외 ${excluded.length}${byReason.size ? `: ${[...byReason].map(([k, v]) => `${k} ${v}`).join(', ')}` : ''})`);
|
|
220
|
+
for (const c of fresh) {
|
|
221
|
+
const proj = override ?? c.project;
|
|
222
|
+
console.log(` + [${proj ?? '전역(확인 필요)'}] ${clip(c.statement, 70)}\n 근거: ${c.source}${override ? '' : ` (${c.projectGuess})`}`);
|
|
223
|
+
}
|
|
224
|
+
for (const c of excluded)
|
|
225
|
+
console.log(` - ${c.excluded?.reason.padEnd(18)} ${shown(c)} ${c.excluded?.detail}`);
|
|
226
|
+
if (!args.includes('--apply')) {
|
|
227
|
+
console.log('[forgen] 미리보기. 고치려면 `forgen way collect-memory --json > f.json` 로 내보내 projects·strength 를 고치고 `forgen way import f.json --apply`. 한 프로젝트 전용이면 --project <key>. 그대로 적용하려면 --apply');
|
|
228
|
+
return 0;
|
|
229
|
+
}
|
|
230
|
+
const items = fresh.map((c) => candidateToItem(c, override));
|
|
231
|
+
if (!items.length) {
|
|
232
|
+
console.log('[forgen] 추가할 룰이 없다.');
|
|
233
|
+
return 0;
|
|
234
|
+
}
|
|
235
|
+
const snap = createSnapshot('pre-collect-memory');
|
|
236
|
+
console.log(`[forgen] 적용 전 스냅샷 ${snap}`);
|
|
237
|
+
const r = applyImport(items, { changes: items.map((i) => ({ id: i.id, field: 'new', to: i.statement })), ignored: [], errors: [], warnings: [], newRules: items });
|
|
238
|
+
console.log(`[forgen] 룰 ${r.created.length}개 추가 (source: imported, 근거: 프로젝트/파일명). 고치려면 forgen way export --target json`);
|
|
239
|
+
return 0;
|
|
240
|
+
}
|
|
241
|
+
function cmdDraft(args) {
|
|
242
|
+
const kind = args[0];
|
|
243
|
+
if (kind !== 'skill' && kind !== 'workflow') {
|
|
244
|
+
console.error('[forgen] 사용법: forgen way draft <skill|workflow> "<주제>" [--project k] [--out dir] [--no-llm]');
|
|
245
|
+
return 1;
|
|
246
|
+
}
|
|
247
|
+
const topic = readTopic(args.slice(1));
|
|
248
|
+
if (!topic) {
|
|
249
|
+
console.error('[forgen] 주제가 필요하다: forgen way draft skill "격리 검증"');
|
|
250
|
+
return 1;
|
|
251
|
+
}
|
|
252
|
+
const project = flag(args, '--project')?.toLowerCase();
|
|
253
|
+
const { sources, excludedPrivate } = gatherSources(topic, { project });
|
|
254
|
+
const by = (k) => sources.filter((s) => s.kind === k).length;
|
|
255
|
+
console.error(`[forgen] 근거 ${sources.length}개 (룰 ${by('rule')}, 솔루션 ${by('solution')}, 교정 원문 ${by('correction')})${excludedPrivate ? `, private 제외 ${excludedPrivate}` : ''}. 전송 전 비밀 마스킹·<private> 제거.`);
|
|
256
|
+
if (sources.length === 0) {
|
|
257
|
+
console.error('[forgen] 주제와 관련된 룰·솔루션·교정을 찾지 못했다. 초안을 쓰지 않는다(호출·파일 없음). 주제어를 바꾸거나 --project 를 확인하라.');
|
|
258
|
+
return flag(args, '--out') ? 1 : 0;
|
|
259
|
+
}
|
|
260
|
+
const outcome = writeDraft(kind, topic, sources, { noLlm: args.includes('--no-llm') });
|
|
261
|
+
if (outcome.mode === 'deterministic')
|
|
262
|
+
console.error(`[forgen] 초안을 쓰지 못했다 (${outcome.reason}). 관련 항목 묶음을 대신 출력한다.`);
|
|
263
|
+
else
|
|
264
|
+
console.error(`[forgen] Haiku 초안 (${((outcome.ms ?? 0) / 1000).toFixed(1)}s)`);
|
|
265
|
+
const files = draftFiles(kind, topic, outcome, sources, excludedPrivate);
|
|
266
|
+
const out = flag(args, '--out');
|
|
267
|
+
if (!out) {
|
|
268
|
+
console.log(files[0].content);
|
|
269
|
+
console.log(`\n---- 근거 항목 ----\n${sources.map((s) => `${s.id}`).join('\n') || '(없음)'}`);
|
|
270
|
+
console.error('[forgen] 미리보기. 파일로 쓰려면 --out <dir> (근거는 옆 파일)');
|
|
271
|
+
return 0;
|
|
272
|
+
}
|
|
273
|
+
const outDir = path.resolve(out);
|
|
274
|
+
const { plan, written } = writeFiles(files, outDir, args.includes('--force'));
|
|
275
|
+
for (const p of plan)
|
|
276
|
+
console.log(` ${p.action.padEnd(15)} ${path.join(outDir, p.path)}`);
|
|
277
|
+
const blocked = plan.filter((p) => p.action.startsWith('blocked'));
|
|
278
|
+
if (blocked.length) {
|
|
279
|
+
for (const b of blocked)
|
|
280
|
+
console.error(blockedMessage(b, ''));
|
|
281
|
+
console.error('[forgen] 아무 파일도 쓰지 않았다.');
|
|
282
|
+
return 1;
|
|
283
|
+
}
|
|
284
|
+
for (const p of plan.filter((x) => x.backup))
|
|
285
|
+
console.log(` 백업 ${p.backup}`);
|
|
286
|
+
console.log(`[forgen] ${written}개 작성 (${outDir})`);
|
|
287
|
+
return 0;
|
|
288
|
+
}
|
|
289
|
+
export async function handleWay(args) {
|
|
290
|
+
const sub = args[0];
|
|
291
|
+
let code = 0;
|
|
292
|
+
if (sub === 'export')
|
|
293
|
+
code = cmdExport(args.slice(1));
|
|
294
|
+
else if (sub === 'import')
|
|
295
|
+
code = cmdImport(args.slice(1));
|
|
296
|
+
else if (sub === 'collect-memory')
|
|
297
|
+
code = cmdCollect(args.slice(1));
|
|
298
|
+
else if (sub === 'draft')
|
|
299
|
+
code = cmdDraft(args.slice(1));
|
|
300
|
+
else if (!sub || sub.startsWith('--')) {
|
|
301
|
+
const way = buildWay();
|
|
302
|
+
if (args.includes('--json'))
|
|
303
|
+
console.log(JSON.stringify({ ...way, render: loadRenderReport() }, null, 2));
|
|
304
|
+
else
|
|
305
|
+
console.log(`${summary(way, args.includes('--all'))}\n`);
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
console.error(`[forgen] 알 수 없는 way 하위 명령: ${sub}\n forgen way [--all|--json] | export | import | collect-memory | draft`);
|
|
309
|
+
code = 1;
|
|
310
|
+
}
|
|
311
|
+
if (code)
|
|
312
|
+
process.exitCode = code;
|
|
313
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { CompileOptions, CompileResult, CompileTarget, Way, WayItem } from './types.js';
|
|
2
|
+
/** forgen way 가 쓴 파일인가. 이 표식이 없는 파일은 덮어쓰지 않는다. */
|
|
3
|
+
export declare function isWayManaged(content: string): boolean;
|
|
4
|
+
export declare const DEFAULT_BUDGET: Partial<Record<CompileTarget, number>>;
|
|
5
|
+
/** 예산이 모자랄 때 먼저 지키는 순서. 룰끼리는 렌더러(byPriority)와 같은 비교를 쓴다: 강도 → 출처 → 최신. 다른 종류는 강도 다음에 룰 > 솔루션 > 습관. */
|
|
6
|
+
export declare function comparePriority(a: WayItem, b: WayItem): number;
|
|
7
|
+
/** 문장 끝에 붙은 호스트 전용 절(문장·대시·세미콜론·괄호 단위)만 떼어 낸다. 앞부분은 한 글자도 바꾸지 않는다. 남는 호스트 용어는 residual. */
|
|
8
|
+
export declare function scrubHostTail(statement: string): {
|
|
9
|
+
text: string;
|
|
10
|
+
removed: boolean;
|
|
11
|
+
residual: boolean;
|
|
12
|
+
};
|
|
13
|
+
/** 프로젝트가 지정되지 않은 전역 항목 중 프로젝트 전용일 수 있는 것: 알려진 프로젝트 키가 문장에 나오거나, 문장이 제품 이름으로 시작한다. */
|
|
14
|
+
export declare function projectSpecificSuspects(items: WayItem[]): Array<{
|
|
15
|
+
id: string;
|
|
16
|
+
why: string;
|
|
17
|
+
}>;
|
|
18
|
+
/** 국어의 로마자 표기(음운 변동 없이 글자 단위)로 슬러그용 ASCII 를 만든다. 의미는 못 살려도 사람이 구분할 수 있는 이름이 된다. */
|
|
19
|
+
export declare function romanize(s: string): string;
|
|
20
|
+
/** 스킬로 낼 만한가: 솔루션이고 실제 상황 문장(공백이 있는 Context)이 있어야 한다. 룰의 trigger 는 사용 시점이 아니다. */
|
|
21
|
+
export declare function isSkillable(i: WayItem): boolean;
|
|
22
|
+
export declare function compile(way: Way, target: CompileTarget, o?: CompileOptions): CompileResult;
|