@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
|
@@ -10,8 +10,8 @@ import { originTag } from '../store/rule-origin.js';
|
|
|
10
10
|
import { initLocaleFromConfig, getLocale, RULE_RENDERER } from '../i18n/index.js';
|
|
11
11
|
export const DEFAULT_CONTEXT = {
|
|
12
12
|
surface: 'session_start',
|
|
13
|
-
max_rules:
|
|
14
|
-
max_chars:
|
|
13
|
+
max_rules: 60,
|
|
14
|
+
max_chars: 7000, // 룰 블록 상한 안쪽. 넘치면 우선순위로 고르고 빠진 룰을 표시한다.
|
|
15
15
|
include_pack_summary: false,
|
|
16
16
|
};
|
|
17
17
|
// ── Output Sections ──
|
|
@@ -26,8 +26,15 @@ const CATEGORY_TO_SECTION = {
|
|
|
26
26
|
};
|
|
27
27
|
// ── Dedupe: render_key 충돌 해소 ──
|
|
28
28
|
const SCOPE_RANK = { session: 0, me: 1 };
|
|
29
|
-
const STRENGTH_RANK = { hard: 0, strong: 1, default: 2, soft: 3 };
|
|
30
|
-
const SOURCE_RANK = { explicit_correction: 0, onboarding: 1, behavior_inference: 2, pack_overlay: 3 };
|
|
29
|
+
export const STRENGTH_RANK = { hard: 0, strong: 1, default: 2, soft: 3 };
|
|
30
|
+
const SOURCE_RANK = { explicit_correction: 0, onboarding: 1, behavior_inference: 2, pack_overlay: 3, imported: 2 };
|
|
31
|
+
export function compareRank(a, b) {
|
|
32
|
+
return (STRENGTH_RANK[a.strength] - STRENGTH_RANK[b.strength])
|
|
33
|
+
|| (SOURCE_RANK[a.source] - SOURCE_RANK[b.source])
|
|
34
|
+
|| b.updated_at.localeCompare(a.updated_at)
|
|
35
|
+
|| a.id.localeCompare(b.id);
|
|
36
|
+
}
|
|
37
|
+
export const rankKeyOf = (r) => ({ strength: r.strength, source: r.source, updated_at: r.updated_at, id: r.rule_id });
|
|
31
38
|
function dedupeByRenderKey(rules) {
|
|
32
39
|
const groups = new Map();
|
|
33
40
|
for (const r of rules) {
|
|
@@ -45,16 +52,7 @@ function dedupeByRenderKey(rules) {
|
|
|
45
52
|
const scopeDiff = SCOPE_RANK[a.scope] - SCOPE_RANK[b.scope];
|
|
46
53
|
if (scopeDiff !== 0)
|
|
47
54
|
return scopeDiff;
|
|
48
|
-
|
|
49
|
-
if (strengthDiff !== 0)
|
|
50
|
-
return strengthDiff;
|
|
51
|
-
const sourceDiff = SOURCE_RANK[a.source] - SOURCE_RANK[b.source];
|
|
52
|
-
if (sourceDiff !== 0)
|
|
53
|
-
return sourceDiff;
|
|
54
|
-
const timeDiff = b.updated_at.localeCompare(a.updated_at);
|
|
55
|
-
if (timeDiff !== 0)
|
|
56
|
-
return timeDiff;
|
|
57
|
-
return a.rule_id.localeCompare(b.rule_id);
|
|
55
|
+
return compareRank(rankKeyOf(a), rankKeyOf(b));
|
|
58
56
|
});
|
|
59
57
|
result.push(group[0]);
|
|
60
58
|
}
|
|
@@ -67,7 +65,8 @@ function ruleToText(rule) {
|
|
|
67
65
|
// ADR-017 D0: explicit 교정 룰엔 출처 날짜 꼬리표 — 사용자가 "내가 언제 말한 것" 을 식별.
|
|
68
66
|
if (rule.strength === 'hard')
|
|
69
67
|
return `${rule.policy}${originTag(rule)}`;
|
|
70
|
-
|
|
68
|
+
const project = rule.projects?.length ? `|${rule.projects.join(',')}` : '';
|
|
69
|
+
return `[${rule.category}|${rule.strength}${project}] ${rule.policy}${originTag(rule)}`;
|
|
71
70
|
}
|
|
72
71
|
function trustPolicySummary(policy) {
|
|
73
72
|
const s = RULE_RENDERER[getLocale()];
|
|
@@ -102,12 +101,15 @@ function communicationPackRules(pack) {
|
|
|
102
101
|
// 0.15/0.85 = 3 단계 강한 신호 누적 후에야 발화 → 노이즈에 둔감.
|
|
103
102
|
const FACET_HIGH = 0.85;
|
|
104
103
|
const FACET_LOW = 0.15;
|
|
105
|
-
function facetDrivenRules(profile) {
|
|
104
|
+
export function facetDrivenRules(profile) {
|
|
106
105
|
const out = [];
|
|
107
|
-
|
|
108
|
-
const
|
|
109
|
-
const
|
|
110
|
-
const
|
|
106
|
+
// 프로필이 없거나 축이 비어 있으면 생략(null 안전) — 렌더가 프로필 부재로 깨지면 안 된다.
|
|
107
|
+
const q = profile?.axes?.quality_safety?.facets;
|
|
108
|
+
const a = profile?.axes?.autonomy?.facets;
|
|
109
|
+
const j = profile?.axes?.judgment_philosophy?.facets;
|
|
110
|
+
const c = profile?.axes?.communication_style?.facets;
|
|
111
|
+
if (!q || !a || !j || !c)
|
|
112
|
+
return out;
|
|
111
113
|
// Quality
|
|
112
114
|
if (q.verification_depth >= FACET_HIGH) {
|
|
113
115
|
out.push({ section: 'How To Validate', rule: '완료 선언 전 실행 로그 / 테스트 결과 / e2e 증거를 응답에 첨부' });
|
|
@@ -159,73 +161,86 @@ function facetDrivenRules(profile) {
|
|
|
159
161
|
}
|
|
160
162
|
return out;
|
|
161
163
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
const deduped = dedupeByRenderKey(active);
|
|
168
|
-
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
164
|
+
/** 예산이 모자랄 때 먼저 지키는 순서: hard → strong → 사용자 교정 → 최신. */
|
|
165
|
+
function byPriority(a, b) {
|
|
166
|
+
return compareRank(rankKeyOf(a), rankKeyOf(b));
|
|
167
|
+
}
|
|
168
|
+
export function renderRulesDetailed(rules, state, profile, ctx = DEFAULT_CONTEXT) {
|
|
169
|
+
const deduped = dedupeByRenderKey(rules.filter((r) => r.status === 'active')).sort(byPriority);
|
|
170
|
+
initLocaleFromConfig();
|
|
171
|
+
const ecStrings = RULE_RENDERER[getLocale()];
|
|
172
|
+
// 교정 기록 지시는 학습 루프의 입구다. 룰 예산과 무관하게 항상 앞쪽에 둔다.
|
|
173
|
+
const evidenceBlock = [
|
|
174
|
+
`## ${ecStrings.evidenceCollectionHeader}`,
|
|
175
|
+
...ecStrings.evidenceCollectionRules.map((r) => `- ${r}`),
|
|
176
|
+
].join('\n');
|
|
177
|
+
const warningsBlock = state.warnings.length > 0
|
|
178
|
+
? `## Warnings\n${state.warnings.map((w) => `- ${w}`).join('\n')}`
|
|
179
|
+
: '';
|
|
172
180
|
const sections = new Map();
|
|
173
181
|
for (const name of SECTION_ORDER)
|
|
174
182
|
sections.set(name, []);
|
|
175
|
-
|
|
176
|
-
sections.get('Must Not')?.push(ruleToText(rule));
|
|
177
|
-
}
|
|
178
|
-
for (const rule of otherRules) {
|
|
179
|
-
const section = CATEGORY_TO_SECTION[rule.category] ?? 'Working Defaults';
|
|
180
|
-
sections.get(section)?.push(ruleToText(rule));
|
|
181
|
-
}
|
|
182
|
-
// 5. trust policy + pack 기본 규칙 주입
|
|
183
|
+
// pack 요약은 룰보다 먼저 예산을 쓴다(켜져 있을 때만).
|
|
183
184
|
if (ctx.include_pack_summary) {
|
|
184
|
-
sections.get('Working Defaults')?.
|
|
185
|
-
|
|
186
|
-
for (const rule of judgmentPackRules(state.judgment_pack)) {
|
|
185
|
+
sections.get('Working Defaults')?.push(`Trust: ${trustPolicySummary(state.effective_trust_policy)}`);
|
|
186
|
+
for (const rule of judgmentPackRules(state.judgment_pack))
|
|
187
187
|
sections.get('Working Defaults')?.push(rule);
|
|
188
|
-
|
|
189
|
-
// communication pack 기본 규칙
|
|
190
|
-
for (const rule of communicationPackRules(state.communication_pack)) {
|
|
188
|
+
for (const rule of communicationPackRules(state.communication_pack))
|
|
191
189
|
sections.get('How To Report')?.push(rule);
|
|
190
|
+
}
|
|
191
|
+
const OMITTED_NOTE_RESERVE = 120;
|
|
192
|
+
const headerChars = SECTION_ORDER.reduce((n, name) => n + name.length + 6, 0);
|
|
193
|
+
let used = evidenceBlock.length + warningsBlock.length + headerChars + OMITTED_NOTE_RESERVE;
|
|
194
|
+
for (const items of sections.values())
|
|
195
|
+
for (const item of items)
|
|
196
|
+
used += item.length + 3;
|
|
197
|
+
const included = [];
|
|
198
|
+
const omitted = [];
|
|
199
|
+
for (const rule of deduped) {
|
|
200
|
+
const text = ruleToText(rule);
|
|
201
|
+
if (used + text.length + 3 > ctx.max_chars || included.length >= ctx.max_rules) {
|
|
202
|
+
omitted.push(rule);
|
|
203
|
+
continue;
|
|
192
204
|
}
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
205
|
+
used += text.length + 3;
|
|
206
|
+
included.push(rule);
|
|
207
|
+
const section = rule.strength === 'hard'
|
|
208
|
+
? 'Must Not'
|
|
209
|
+
: (CATEGORY_TO_SECTION[rule.category] ?? 'Working Defaults');
|
|
210
|
+
sections.get(section)?.push(text);
|
|
211
|
+
}
|
|
212
|
+
// R8: 4축 프로필을 렌더에 연결한다. 이전에는 `include_pack_summary`(항상 false) 뒤에 있어 facet 값을 바꿔도
|
|
213
|
+
// 주입본이 같았다. 0.85/0.15 를 넘는 facet 의 규칙만 넣고, 룰이 예산을 다 쓴 뒤 남는 자리에만 들어간다(예산 최하위).
|
|
214
|
+
// 임계값 근거: 기본 0.5, 자동 갱신 ±0.1 단위 → 극단값은 여러 세션의 강한 신호가 누적된 뒤에만 도달한다.
|
|
215
|
+
let facetOmitted = 0;
|
|
216
|
+
for (const fr of facetDrivenRules(profile)) {
|
|
217
|
+
const text = `[profile] ${fr.rule}`;
|
|
218
|
+
if (used + text.length + 3 > ctx.max_chars) {
|
|
219
|
+
facetOmitted++;
|
|
220
|
+
continue;
|
|
198
221
|
}
|
|
222
|
+
used += text.length + 3;
|
|
223
|
+
sections.get(fr.section)?.push(text);
|
|
199
224
|
}
|
|
200
|
-
// 6. 섹션 조립 (AI-optimized: 간결한 태그 형식)
|
|
201
225
|
const parts = [];
|
|
202
|
-
|
|
203
|
-
|
|
226
|
+
const mustNot = sections.get('Must Not') ?? [];
|
|
227
|
+
if (mustNot.length > 0)
|
|
228
|
+
parts.push(`## Must Not\n${mustNot.map((i) => `- ${i}`).join('\n')}`);
|
|
229
|
+
parts.push(evidenceBlock);
|
|
204
230
|
for (const name of SECTION_ORDER) {
|
|
205
|
-
|
|
206
|
-
if (items.length === 0)
|
|
231
|
+
if (name === 'Must Not')
|
|
207
232
|
continue;
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
break;
|
|
215
|
-
parts.push(section);
|
|
216
|
-
totalChars += section.length;
|
|
217
|
-
totalRules += items.length;
|
|
218
|
-
}
|
|
219
|
-
// 7. Evidence Collection 지시 (항상 포함, 로케일)
|
|
220
|
-
initLocaleFromConfig();
|
|
221
|
-
const ecStrings = RULE_RENDERER[getLocale()];
|
|
222
|
-
parts.push([
|
|
223
|
-
`## ${ecStrings.evidenceCollectionHeader}`,
|
|
224
|
-
...ecStrings.evidenceCollectionRules.map(r => `- ${r}`),
|
|
225
|
-
].join('\n'));
|
|
226
|
-
// 8. warnings
|
|
227
|
-
if (state.warnings.length > 0) {
|
|
228
|
-
parts.push(`## Warnings\n${state.warnings.map(w => `- ${w}`).join('\n')}`);
|
|
233
|
+
const items = sections.get(name) ?? [];
|
|
234
|
+
if (items.length > 0)
|
|
235
|
+
parts.push(`## ${name}\n${items.map((i) => `- ${i}`).join('\n')}`);
|
|
236
|
+
}
|
|
237
|
+
if (omitted.length > 0 || facetOmitted > 0) {
|
|
238
|
+
parts.push(`## Omitted\n- ${omitted.length} lower-priority rules${facetOmitted ? ` and ${facetOmitted} profile rules` : ''} omitted (budget). List: forgen rule list`);
|
|
229
239
|
}
|
|
230
|
-
|
|
240
|
+
if (warningsBlock)
|
|
241
|
+
parts.push(warningsBlock);
|
|
242
|
+
return { text: parts.join('\n\n'), included, omitted };
|
|
243
|
+
}
|
|
244
|
+
export function renderRules(rules, state, profile, ctx = DEFAULT_CONTEXT) {
|
|
245
|
+
return renderRulesDetailed(rules, state, profile, ctx).text;
|
|
231
246
|
}
|
|
@@ -111,8 +111,9 @@ export function appendEvidence(evidence) {
|
|
|
111
111
|
appendLifecycleEvents(events);
|
|
112
112
|
return { saved: true, t1_events: events.length };
|
|
113
113
|
}
|
|
114
|
-
catch {
|
|
115
|
-
// best-effort: orchestrator 실패는 evidence 저장 자체를 막지 않는다.
|
|
114
|
+
catch (e) {
|
|
115
|
+
// best-effort: orchestrator 실패는 evidence 저장 자체를 막지 않는다. 다만 룰 전이 실패는 보이게 남긴다.
|
|
116
|
+
process.stderr.write(`[forgen] rule transition failed: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
116
117
|
return { saved: true, t1_events: 0 };
|
|
117
118
|
}
|
|
118
119
|
}
|
|
@@ -197,7 +198,7 @@ function retireStaleAutoMinedRules(now) {
|
|
|
197
198
|
const keep = [];
|
|
198
199
|
for (const item of byAge) {
|
|
199
200
|
if (item.age >= AUTO_MINED_TTL_MS) {
|
|
200
|
-
updateRuleStatus(item.r.rule_id, 'removed'); // TTL 초과 → 은퇴
|
|
201
|
+
updateRuleStatus(item.r.rule_id, 'removed', 'auto-mined-ttl', 'evidence-store'); // TTL 초과 → 은퇴
|
|
201
202
|
}
|
|
202
203
|
else {
|
|
203
204
|
keep.push(item);
|
|
@@ -206,7 +207,7 @@ function retireStaleAutoMinedRules(now) {
|
|
|
206
207
|
// 총량 상한 초과분(가장 오래된 것부터) 은퇴.
|
|
207
208
|
const excess = keep.length - AUTO_MINED_MAX_LIVE;
|
|
208
209
|
for (let i = 0; i < excess; i++)
|
|
209
|
-
updateRuleStatus(keep[i].r.rule_id, 'removed');
|
|
210
|
+
updateRuleStatus(keep[i].r.rule_id, 'removed', 'auto-mined-cap', 'evidence-store');
|
|
210
211
|
}
|
|
211
212
|
/**
|
|
212
213
|
* retire+dedupe+create 시퀀스 전체를 잠그는 lock 타깃. 실제 파일은 만들지 않고
|
|
@@ -216,6 +217,19 @@ function retireStaleAutoMinedRules(now) {
|
|
|
216
217
|
* create 를 하나의 critical section 으로 묶어 그 창을 없앤다.
|
|
217
218
|
*/
|
|
218
219
|
const RULE_STORE_MUTATE_LOCK = path.join(ME_RULES, '.rule-store-mutate');
|
|
220
|
+
/**
|
|
221
|
+
* 같은 render_key 교정을 기존 룰에 합칠 때의 적용 범위. 프로젝트 범위를 잃지 않게 합집합으로 합친다.
|
|
222
|
+
* 전역 룰은 전역으로 남고, 범위 없는 교정(this_project_only 기본값)이 프로젝트 룰을 전역으로 넓히지도 않는다.
|
|
223
|
+
* 꺼졌거나 은퇴한 룰이 되살아날 때는 예전 범위가 아니라 이번 교정의 범위를 따른다.
|
|
224
|
+
*/
|
|
225
|
+
function mergedRuleProjects(existing, incoming) {
|
|
226
|
+
const next = Array.isArray(incoming) && incoming.length > 0 ? incoming : undefined;
|
|
227
|
+
if (existing.status !== 'active')
|
|
228
|
+
return next;
|
|
229
|
+
if (!existing.projects?.length)
|
|
230
|
+
return undefined;
|
|
231
|
+
return next ? [...new Set([...existing.projects, ...next])] : existing.projects;
|
|
232
|
+
}
|
|
219
233
|
export function promoteSessionCandidates(sessionId) {
|
|
220
234
|
// withFileLockSync 는 O_CREAT 로 lock 파일을 만들 뿐 부모 디렉터리는 만들지 않는다 —
|
|
221
235
|
// 첫 rule 승급 이전(=아직 ME_RULES 없음)에도 락을 잡을 수 있어야 하므로 선행 mkdir.
|
|
@@ -228,7 +242,12 @@ export function promoteSessionCandidates(sessionId) {
|
|
|
228
242
|
// 조용한 세션에서도 wall-clock TTL 이 실제로 강제되도록. (auto-compound-runner 는 매
|
|
229
243
|
// 세션 종료 시 promoteSessionCandidates 를 호출하므로 이 경로가 세션당 1회 보장된다.)
|
|
230
244
|
retireStaleAutoMinedRules(Date.now());
|
|
231
|
-
const candidates = loadPromotionCandidates().filter(e =>
|
|
245
|
+
const candidates = loadPromotionCandidates().filter((e) => {
|
|
246
|
+
if (e.session_id === sessionId)
|
|
247
|
+
return true;
|
|
248
|
+
const pending = e.raw_payload?.pending_promotion === true;
|
|
249
|
+
return pending && (e.candidate_rule_refs ?? []).length === 0;
|
|
250
|
+
});
|
|
232
251
|
if (candidates.length === 0)
|
|
233
252
|
return 0;
|
|
234
253
|
let promoted = 0;
|
|
@@ -309,7 +328,15 @@ export function promoteSessionCandidates(sessionId) {
|
|
|
309
328
|
// rule_id/created_at 은 그대로 두고 status 만 'active' 로 되돌린다 — 재활성화된
|
|
310
329
|
// rule 은 다음 retireStaleAutoMinedRules() 호출 때 기존 나이 기준으로 다시
|
|
311
330
|
// 은퇴 여부가 평가된다(의도된 동작, thrash 아님: 최소 1세션은 유효하게 주입됨).
|
|
312
|
-
|
|
331
|
+
const { projects: _previousProjects, ...existingWithoutProjects } = existingRule;
|
|
332
|
+
const projects = mergedRuleProjects(existingRule, payload?.projects);
|
|
333
|
+
saveRule({
|
|
334
|
+
...existingWithoutProjects,
|
|
335
|
+
...(projects ? { projects } : {}),
|
|
336
|
+
status: 'active',
|
|
337
|
+
evidence_refs: evidenceRefs,
|
|
338
|
+
strength,
|
|
339
|
+
});
|
|
313
340
|
saveEvidence({
|
|
314
341
|
...candidate,
|
|
315
342
|
candidate_rule_refs: [...(candidate.candidate_rule_refs ?? []), existingRule.rule_id],
|
|
@@ -333,6 +360,7 @@ export function promoteSessionCandidates(sessionId) {
|
|
|
333
360
|
source,
|
|
334
361
|
evidence_refs: [candidate.evidence_id],
|
|
335
362
|
render_key: renderKey,
|
|
363
|
+
...(Array.isArray(payload.projects) ? { projects: payload.projects } : {}),
|
|
336
364
|
});
|
|
337
365
|
if (autoMined) {
|
|
338
366
|
// advisory-only (SEV-1 #2): classify() 를 돌리지 않고 enforce_via 를 비워, 채굴 룰이
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* 기본값 재합성이 N 군데에 분산" 이 R4-B2(음수 corruption)/R5-B1(orphan)/R5-B2(mutex)/api-H1
|
|
10
10
|
* 등 버그 클러스터의 공통 뿌리. 이 factory 가 그 뿌리를 차단.
|
|
11
11
|
*/
|
|
12
|
-
import type { Rule, LifecycleState, MetaPromotion } from './types.js';
|
|
12
|
+
import type { Rule, LifecycleState, MetaPromotion, RuleStatus } from './types.js';
|
|
13
13
|
/** safe non-negative integer normalization — 파일 corruption / 다중 writer race 방어. */
|
|
14
14
|
export declare function safeCount(n: unknown): number;
|
|
15
15
|
/**
|
|
@@ -21,3 +21,5 @@ export declare function initLifecycle(rule: Rule): LifecycleState;
|
|
|
21
21
|
export declare function bumpInject(lifecycle: LifecycleState, nowIso: string): LifecycleState;
|
|
22
22
|
/** meta_promotions 에 새 entry append (immutable). */
|
|
23
23
|
export declare function appendMetaPromotion(lifecycle: LifecycleState, promotion: MetaPromotion): LifecycleState;
|
|
24
|
+
/** 상태 전이 + 사유 기록. 순수. 룰 상태를 바꾸는 모든 경로는 이 함수를 거친다. */
|
|
25
|
+
export declare function withStatusChange(rule: Rule, to: RuleStatus, reason: string, by: string, nowIso?: string): Rule;
|
|
@@ -61,3 +61,13 @@ export function appendMetaPromotion(lifecycle, promotion) {
|
|
|
61
61
|
meta_promotions: [...lifecycle.meta_promotions, promotion],
|
|
62
62
|
};
|
|
63
63
|
}
|
|
64
|
+
/** 상태 전이 + 사유 기록. 순수. 룰 상태를 바꾸는 모든 경로는 이 함수를 거친다. */
|
|
65
|
+
export function withStatusChange(rule, to, reason, by, nowIso = new Date().toISOString()) {
|
|
66
|
+
if (rule.status === to)
|
|
67
|
+
return rule;
|
|
68
|
+
return {
|
|
69
|
+
...rule,
|
|
70
|
+
status: to,
|
|
71
|
+
status_history: [...(rule.status_history ?? []), { at: nowIso, from: rule.status, to, reason, by }],
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Rule } from './types.js';
|
|
2
|
+
/** cwd 의 프로젝트 키: git 저장소 폴더 이름(소문자). worktree 는 본 저장소 이름. 프로젝트가 아니면 null. */
|
|
3
|
+
export declare function projectKeyFor(cwd: string): string | null;
|
|
4
|
+
/** 컨텍스트로 넣을 룰인가. */
|
|
5
|
+
export declare function appliesForContext(rule: Rule, projectKey: string | null): boolean;
|
|
6
|
+
/** 차단·판정까지 할 룰인가. */
|
|
7
|
+
export declare function appliesForEnforcement(rule: Rule, projectKey: string | null): boolean;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 룰의 프로젝트 범위.
|
|
3
|
+
*
|
|
4
|
+
* 프로젝트 안: 전역 룰 + 그 프로젝트 룰만 주입·강제한다. 다른 프로젝트 룰이 무관한 응답을 막던 오탐의 원인이다.
|
|
5
|
+
* 프로젝트 밖(홈 디렉터리 등): 어떤 작업인지 알 수 없으니 전부 컨텍스트로 주되, 프로젝트 룰로 차단하지는 않는다.
|
|
6
|
+
*/
|
|
7
|
+
import * as fs from 'node:fs';
|
|
8
|
+
import * as os from 'node:os';
|
|
9
|
+
import * as path from 'node:path';
|
|
10
|
+
/** cwd 의 프로젝트 키: git 저장소 폴더 이름(소문자). worktree 는 본 저장소 이름. 프로젝트가 아니면 null. */
|
|
11
|
+
export function projectKeyFor(cwd) {
|
|
12
|
+
let dir;
|
|
13
|
+
try {
|
|
14
|
+
dir = fs.realpathSync(cwd);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
dir = path.resolve(cwd);
|
|
18
|
+
}
|
|
19
|
+
let home;
|
|
20
|
+
try {
|
|
21
|
+
home = fs.realpathSync(os.homedir());
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
home = os.homedir();
|
|
25
|
+
}
|
|
26
|
+
for (let cur = dir;; cur = path.dirname(cur)) {
|
|
27
|
+
if (cur === home)
|
|
28
|
+
return null; // 홈 자체가 git 저장소여도 프로젝트로 보지 않는다.
|
|
29
|
+
const gitPath = path.join(cur, '.git');
|
|
30
|
+
try {
|
|
31
|
+
const st = fs.statSync(gitPath);
|
|
32
|
+
if (st.isDirectory())
|
|
33
|
+
return path.basename(cur).toLowerCase();
|
|
34
|
+
const match = /gitdir:\s*(.+)/.exec(fs.readFileSync(gitPath, 'utf-8'));
|
|
35
|
+
const worktreeOf = match?.[1].trim().match(/(.+)[\\/]\.git[\\/]worktrees[\\/]/)?.[1];
|
|
36
|
+
return path.basename(worktreeOf ?? cur).toLowerCase();
|
|
37
|
+
}
|
|
38
|
+
catch { /* 상위로 */ }
|
|
39
|
+
if (cur === path.dirname(cur))
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** 컨텍스트로 넣을 룰인가. */
|
|
44
|
+
export function appliesForContext(rule, projectKey) {
|
|
45
|
+
if (!rule.projects?.length || projectKey === null)
|
|
46
|
+
return true;
|
|
47
|
+
return rule.projects.includes(projectKey);
|
|
48
|
+
}
|
|
49
|
+
/** 차단·판정까지 할 룰인가. */
|
|
50
|
+
export function appliesForEnforcement(rule, projectKey) {
|
|
51
|
+
if (!rule.projects?.length)
|
|
52
|
+
return true;
|
|
53
|
+
return projectKey !== null && rule.projects.includes(projectKey);
|
|
54
|
+
}
|
|
@@ -14,7 +14,13 @@ export declare function createRule(params: {
|
|
|
14
14
|
source: RuleSource;
|
|
15
15
|
evidence_refs?: string[];
|
|
16
16
|
render_key: string;
|
|
17
|
+
session_id?: string;
|
|
18
|
+
projects?: string[];
|
|
17
19
|
}): Rule;
|
|
20
|
+
/** 활성 룰을 사유 없이 비활성으로 바꾸려는 저장. 룰이 조용히 사라지는 것을 막는 불변식. */
|
|
21
|
+
export declare class RuleTransitionError extends Error {
|
|
22
|
+
constructor(ruleId: string, to: RuleStatus);
|
|
23
|
+
}
|
|
18
24
|
export declare function saveRule(rule: Rule): void;
|
|
19
25
|
/**
|
|
20
26
|
* ADR-002 T5 — rule 저장 + 기존 active rules 와 자연어 충돌 감지 + 양쪽 conflict_refs 기록.
|
|
@@ -31,6 +37,21 @@ export declare function appendRule(rule: Rule): Promise<{
|
|
|
31
37
|
conflicts_with: string[];
|
|
32
38
|
}>;
|
|
33
39
|
export declare function loadRule(ruleId: string): Rule | null;
|
|
40
|
+
/**
|
|
41
|
+
* 룰 디렉터리 스캔 — 읽기 실패와 진짜 0건을 구분한다.
|
|
42
|
+
* loadAllRules 는 깨진 파일을 조용히 건너뛴다. 진단·status 는 이 결과로 "깨진 N개"를 표시한다.
|
|
43
|
+
*/
|
|
44
|
+
export interface RuleScan {
|
|
45
|
+
rules: Rule[];
|
|
46
|
+
/** 파싱에 실패한 룰 파일 (파일명: 사유) */
|
|
47
|
+
broken: Array<{
|
|
48
|
+
file: string;
|
|
49
|
+
error: string;
|
|
50
|
+
}>;
|
|
51
|
+
/** 디렉터리를 읽지 못한 사유 (없으면 정상 — 디렉터리 부재도 정상 0건으로 본다) */
|
|
52
|
+
dirError?: string;
|
|
53
|
+
}
|
|
54
|
+
export declare function scanRuleFiles(): RuleScan;
|
|
34
55
|
export declare function loadAllRules(): Rule[];
|
|
35
56
|
/**
|
|
36
57
|
* 현재 프로젝트 cwd 의 `.forgen/rules/` 경로. FORGEN_CWD/COMPOUND_CWD 우선.
|
|
@@ -39,6 +60,10 @@ export declare function loadAllRules(): Rule[];
|
|
|
39
60
|
/** 이 룰을 덮어쓰는 프로젝트 룰 파일(<cwd>/.forgen/rules/<id>.json)이 있으면 그 경로. 없으면 null. */
|
|
40
61
|
export declare function projectRuleOverridePath(ruleId: string): string | null;
|
|
41
62
|
export declare function loadActiveRules(): Rule[];
|
|
63
|
+
/** 이 cwd 의 응답·도구 호출을 판정할 룰. 다른 프로젝트 룰은 제외한다. */
|
|
64
|
+
export declare function loadEnforcedRules(cwd?: string): Rule[];
|
|
65
|
+
/** 이 cwd 의 세션 컨텍스트에 넣을 룰. */
|
|
66
|
+
export declare function loadContextRules(cwd?: string): Rule[];
|
|
42
67
|
/**
|
|
43
68
|
* render_key(+source, +scope)로 기존 rule을 찾는다 — status 무관(active/suppressed/removed/
|
|
44
69
|
* superseded 전부 포함). ADR-013 채굴 룰 재생성 결함 수정(RCA): promoteSessionCandidates가
|
|
@@ -73,7 +98,7 @@ export declare function syncRuleCounters(ruleId: string, counters: {
|
|
|
73
98
|
bypass_count: number;
|
|
74
99
|
last_violation_at?: string;
|
|
75
100
|
}): boolean;
|
|
76
|
-
export declare function updateRuleStatus(ruleId: string, status: RuleStatus): boolean;
|
|
101
|
+
export declare function updateRuleStatus(ruleId: string, status: RuleStatus, reason: string, by?: string): boolean;
|
|
77
102
|
/**
|
|
78
103
|
* 현재 세션 ID와 다른 scope:'session' 규칙을 비활성화.
|
|
79
104
|
* 이전 세션의 임시 규칙이 새 세션에서 영향을 미치지 않도록 정리.
|
|
@@ -88,7 +113,8 @@ export interface PruneResult {
|
|
|
88
113
|
/** removed 룰 보관 기간 기본값 — 7일. TTL 로 은퇴된 지 이만큼 지나면 prune 대상. */
|
|
89
114
|
export declare const DEFAULT_PRUNE_RETENTION_MS: number;
|
|
90
115
|
/**
|
|
91
|
-
* status:'removed' 파일을 retention 기간이 지난 것만
|
|
116
|
+
* status:'removed' 파일을 retention 기간이 지난 것만 rules-archive 로 옮긴다(영구 삭제 금지).
|
|
117
|
+
* 교정 유실 조사(2026-11-04): 누적 1,352개가 unlink 되어 대조·복구가 불가능했다.
|
|
92
118
|
* RCA: retire(updateRuleStatus)는 status flip만 하고 파일을 지우지 않아 6,525개 죽은
|
|
93
119
|
* 파일이 ~/.forgen/me/rules 에 쌓여 loadAllRules() linear scan 비용을 키우고
|
|
94
120
|
* cross-process race 창을 넓혔다. status 전이 시각(updated_at) 기준으로 retention을
|
|
@@ -102,4 +128,4 @@ export declare function pruneRemovedRules(opts?: {
|
|
|
102
128
|
retentionMs?: number;
|
|
103
129
|
apply?: boolean;
|
|
104
130
|
}): PruneResult;
|
|
105
|
-
export declare function cleanupStaleSessionRules(
|
|
131
|
+
export declare function cleanupStaleSessionRules(currentSessionId: string, nowMs?: number): number;
|