keystone-relation 0.1.0 → 1.1.0
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/dist/index.js +287 -35
- package/package.json +51 -51
package/dist/index.js
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
3
|
import { getHeapStatistics } from "node:v8";
|
|
4
|
-
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
|
-
import { dirname } from "node:path";
|
|
6
|
-
import { resolve } from "node:path";
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
7
6
|
import picomatch from "picomatch";
|
|
8
7
|
import { computeDiff, graphCmd } from "./graph-cmd.js";
|
|
9
|
-
import { addManualRelation, applyTrace, isTestFor, renderCalls, approveProposal, loadTrace, renderCiWorkflow, runTrace, saveTrace, TRACE_PATH, renameMapOf, treeReport, MISSING_CONFIG_HINT, baseReader, beforeEdit, buildCallGraph, buildCallGraphCached, changedFiles, checkFailed, checkRelations, deletedFiles, diffSignatures, diffUnits, editRelation, explain, findRelation, findUnits, loadProject, loadStore, parseAssignments, proposeChange, rejectProposal, renderMap, renderSignatureFindings, runCheck, signatureFailed, signatureFindings, saveStore, scanRelations, selectTests, HUMAN_FIELDS, IMPORTANCE, MUTABILITY, RELATION_TYPES, } from "keystone-relation-core";
|
|
8
|
+
import { addManualRelation, applyTrace, demotedTargets, editRelevance, trustTag, hookSettings, logEvent, mergeHookSettings, readEvents, renderSummary, sessionContext, starterConfig, summarize, upsertClaudeMd, isTestFor, renderCalls, approveProposal, loadTrace, renderCiWorkflow, runTrace, saveTrace, TRACE_PATH, renameMapOf, treeReport, MISSING_CONFIG_HINT, baseReader, beforeEdit, buildCallGraph, buildCallGraphCached, changedFiles, checkFailed, checkRelations, deletedFiles, diffSignatures, diffUnits, editRelation, explain, findRelation, findUnits, loadProject, loadStore, parseAssignments, proposeChange, rejectProposal, renderMap, renderSignatureFindings, runCheck, signatureFailed, signatureFindings, saveStore, scanRelations, selectTests, HUMAN_FIELDS, IMPORTANCE, MUTABILITY, RELATION_TYPES, } from "keystone-relation-core";
|
|
10
9
|
// 큰 프로젝트에서 메모리 부족으로 죽지 않도록, 기본 한도가 낮으면 한도를 올려 자기 자신을 다시 실행한다.
|
|
11
10
|
{
|
|
12
11
|
const limitMb = getHeapStatistics().heap_size_limit / 1048576;
|
|
@@ -17,7 +16,7 @@ import { addManualRelation, applyTrace, isTestFor, renderCalls, approveProposal,
|
|
|
17
16
|
}
|
|
18
17
|
const USAGE = `usage: keystone <command> [options]
|
|
19
18
|
|
|
20
|
-
|
|
19
|
+
처음이라면: "keystone init --all" 한 번으로 준비. 그 뒤엔 명령 3개면 충분해요:
|
|
21
20
|
keystone explain <함수> --down 2 이 함수가 어떻게 흘러가는지 (실행 흐름 파악)
|
|
22
21
|
keystone calls <함수> 누가 부르고 무엇을 부르는지 (같은 이름 함수도 구분)
|
|
23
22
|
keystone before-edit <함수|파일> 고치기 전에: 영향 범위·테스트·보호된 곳 확인
|
|
@@ -60,7 +59,7 @@ function parseArgs(argv0) {
|
|
|
60
59
|
const argv = dd >= 0 ? argv0.slice(0, dd) : argv0;
|
|
61
60
|
const traceCommand = dd >= 0 ? argv0.slice(dd + 1).join(" ") : "";
|
|
62
61
|
const o = { root: process.cwd(), positional: [], strictPins: false, allowPinned: false, all: false, precise: false, list: false, json: false,
|
|
63
|
-
sameFile: false, noTrace: false, keep: false, traceCommand: "", includeInferred: false, includeTests: false, fail: false, followRenames: false, unreviewed: false, proposals: false, by: "agent", note: "" };
|
|
62
|
+
sameFile: false, noTrace: false, keep: false, traceCommand: "", includeInferred: false, includeTests: false, fail: false, followRenames: false, unreviewed: false, proposals: false, by: "agent", note: "", trace: false, hook: false, ci: false, claudeMd: false };
|
|
64
63
|
for (let i = 0; i < argv.length; i++) {
|
|
65
64
|
const a = argv[i];
|
|
66
65
|
const val = () => { if (i + 1 >= argv.length) {
|
|
@@ -119,6 +118,18 @@ function parseArgs(argv0) {
|
|
|
119
118
|
o.unreviewed = true;
|
|
120
119
|
else if (a === "--proposals")
|
|
121
120
|
o.proposals = true;
|
|
121
|
+
else if (a === "--reason")
|
|
122
|
+
o.reason = val();
|
|
123
|
+
else if (a === "--trace")
|
|
124
|
+
o.trace = true;
|
|
125
|
+
else if (a === "--hook")
|
|
126
|
+
o.hook = true;
|
|
127
|
+
else if (a === "--ci")
|
|
128
|
+
o.ci = true;
|
|
129
|
+
else if (a === "--claude-md")
|
|
130
|
+
o.claudeMd = true;
|
|
131
|
+
else if (a === "--days")
|
|
132
|
+
o.days = Number(val());
|
|
122
133
|
else if (a === "--by")
|
|
123
134
|
o.by = val();
|
|
124
135
|
else if (a === "--note")
|
|
@@ -146,44 +157,227 @@ function buildCalls(o, files) {
|
|
|
146
157
|
}
|
|
147
158
|
return { calls, trace };
|
|
148
159
|
}
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
160
|
+
const relPath = (root, fp) => relative(root, resolve(root, fp)).split(sep).join("/");
|
|
161
|
+
const readStdin = () => { try {
|
|
162
|
+
return readFileSync(0, "utf8");
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return "";
|
|
166
|
+
} };
|
|
167
|
+
/** keystone hook init → 설정 예시 출력 (파일은 건드리지 않음; 적용은 `keystone init --hook`)
|
|
168
|
+
* keystone hook session → SessionStart 훅: 보호 규칙과 중요한 카드를 에이전트에게 알려 줌
|
|
169
|
+
* keystone hook run → PreToolUse 훅: 고칠 파일의 영향 범위를 알려 줌
|
|
170
|
+
* keystone hook post → PostToolUse 훅: 고친 직후 check 를 돌려 실패하면 에이전트에게 알려 줌 */
|
|
154
171
|
function hookCmd(o) {
|
|
155
172
|
const sub = o.positional[1];
|
|
156
173
|
if (sub === "init") {
|
|
157
|
-
console.log("아래를 프로젝트의 .claude/settings.json 에
|
|
158
|
-
console.log(JSON.stringify(
|
|
159
|
-
console.log("\n설명:
|
|
174
|
+
console.log("아래를 프로젝트의 .claude/settings.json 에 넣으세요 (또는 `keystone init --hook` 으로 자동 병합):\n");
|
|
175
|
+
console.log(JSON.stringify(hookSettings(), null, 2));
|
|
176
|
+
console.log("\n설명: 세션 시작 때 보호 규칙을 알려 주고, 파일을 고치기 직전에 영향 범위를, 고친 직후에 검사 결과를 알려 줍니다. 작업을 막지는 않고 알려 주기만 해요.");
|
|
160
177
|
return 0;
|
|
161
178
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
179
|
+
const emit = (event, text) => console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } }));
|
|
180
|
+
try {
|
|
181
|
+
if (sub === "session") {
|
|
182
|
+
const project = loadProject(o.root);
|
|
183
|
+
const tr = loadTrace(o.root);
|
|
184
|
+
const ageDays = tr ? (Date.now() - Date.parse(tr.createdAt)) / 86400000 : Infinity;
|
|
185
|
+
const hint = !tr ? "\n(실행 기록이 없어요. `keystone trace -- <테스트 명령>` 으로 만들면 이벤트/콜백처럼 코드만으로 못 찾는 호출이 확인된 연결로 보강돼요.)" : ageDays > 30 ? `\n(실행 기록이 ${Math.floor(ageDays)}일 전 것이에요. 다시 만들면 더 정확해요: keystone trace -- <테스트 명령>)` : "";
|
|
186
|
+
emit("SessionStart", sessionContext(project.config, loadStore(o.root)) + hint);
|
|
187
|
+
logEvent(o.root, { kind: "hook-session", by: "hook" });
|
|
188
|
+
return 0;
|
|
166
189
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
const inp = JSON.parse(raw || "{}");
|
|
190
|
+
if (sub === "run") {
|
|
191
|
+
const inp = JSON.parse(readStdin() || "{}");
|
|
170
192
|
const fp = inp.tool_input?.file_path;
|
|
171
193
|
if (!fp)
|
|
172
194
|
return 0;
|
|
173
|
-
const rel =
|
|
195
|
+
const rel = relPath(o.root, fp);
|
|
174
196
|
const project = loadProject(o.root);
|
|
175
197
|
if (!project.graph.files.includes(rel))
|
|
176
198
|
return 0;
|
|
177
199
|
const { calls } = buildCalls({ ...o, json: true }, project.graph.files);
|
|
178
|
-
const
|
|
179
|
-
|
|
200
|
+
const store = loadStore(o.root);
|
|
201
|
+
const rv = editRelevance(calls, project.config, store, rel);
|
|
202
|
+
if (!rv.relevant)
|
|
203
|
+
return 0; // 보호된 곳도, 카드도, 영향이 큰 곳도 아니면 조용히 둔다
|
|
204
|
+
emit("PreToolUse", `[Keystone] 주의가 필요한 파일이에요: ${rv.reasons.join(" · ")}\n` + beforeEdit(calls, project.config, store, rel));
|
|
205
|
+
logEvent(o.root, { kind: "hook-pre", target: rel, by: "hook" });
|
|
206
|
+
return 0;
|
|
207
|
+
}
|
|
208
|
+
if (sub === "post") {
|
|
209
|
+
const inp = JSON.parse(readStdin() || "{}");
|
|
210
|
+
const fp = inp.tool_input?.file_path;
|
|
211
|
+
if (!fp)
|
|
212
|
+
return 0;
|
|
213
|
+
const rel = relPath(o.root, fp);
|
|
214
|
+
const r = spawnSync(process.execPath, [process.argv[1], "check", "--base", "HEAD", "--json", "--root", o.root], { encoding: "utf8", maxBuffer: 1 << 26, env: { ...process.env, KEYSTONE_NO_LOG: "1" } });
|
|
215
|
+
let res;
|
|
216
|
+
try {
|
|
217
|
+
res = JSON.parse(r.stdout || "{}");
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
return 0;
|
|
221
|
+
}
|
|
222
|
+
if (res.ok !== false) {
|
|
223
|
+
logEvent(o.root, { kind: "hook-post", ok: true, target: rel, by: "hook" });
|
|
224
|
+
return 0;
|
|
225
|
+
}
|
|
226
|
+
const blocked = { pinned: res.pinnedChanges?.length ?? 0, boundaries: res.violations?.length ?? 0, relations: (res.relations ?? []).filter((f) => f.level === "error").length };
|
|
227
|
+
const lines = [`[Keystone] 방금 수정한 뒤 검사(check)가 실패했어요 (${rel}). 문서화된 관계나 보호 규칙이 깨졌을 수 있어요. 멈추고 확인하세요:`];
|
|
228
|
+
for (const p of res.pinnedChanges ?? [])
|
|
229
|
+
lines.push(` - 보호된 곳 변경: ${p.file}${p.detail ? ` [${p.detail}]` : ""}${p.reason ? ` — ${p.reason}` : ""}`);
|
|
230
|
+
for (const v of res.violations ?? [])
|
|
231
|
+
lines.push(` - 경계 위반: ${v.file} → ${v.imports}${v.reason ? ` — ${v.reason}` : ""}`);
|
|
232
|
+
for (const f of (res.relations ?? []).filter((x) => x.level === "error"))
|
|
233
|
+
lines.push(` - 관계: ${f.id} — ${f.message}`);
|
|
234
|
+
if (lines.length === 1)
|
|
235
|
+
lines.push(" - 함수 입출력 변경이 호출하는 곳에 반영되지 않았을 수 있어요 (`keystone check --base HEAD` 로 자세히 확인).");
|
|
236
|
+
lines.push("의도한 변경이면 이유를 보고서에 남기세요. 아니면 되돌리세요.");
|
|
237
|
+
emit("PostToolUse", lines.join("\n"));
|
|
238
|
+
logEvent(o.root, { kind: "hook-post", ok: false, blocked, target: rel, by: "hook" });
|
|
239
|
+
return 0;
|
|
180
240
|
}
|
|
181
|
-
catch { /* 훅은 절대 작업을 막지 않는다 */ }
|
|
182
|
-
return 0;
|
|
183
241
|
}
|
|
184
|
-
|
|
242
|
+
catch {
|
|
243
|
+
return 0;
|
|
244
|
+
} // 훅은 절대 작업을 막지 않는다
|
|
245
|
+
console.error("usage: keystone hook <init|session|run|post>");
|
|
185
246
|
return 2;
|
|
186
247
|
}
|
|
248
|
+
/** keystone init [--hook] [--ci] [--claude-md] [--all] : 처음 쓰는 저장소를 한 번에 준비 */
|
|
249
|
+
function initCmd(o) {
|
|
250
|
+
const all = o.all;
|
|
251
|
+
const doHook = all || o.hook, doCi = all || o.ci, doMd = all || o.claudeMd, doTrace = o.trace;
|
|
252
|
+
const done = [], skipped = [];
|
|
253
|
+
const cfgPath = join(o.root, "keystone.yml");
|
|
254
|
+
if (existsSync(cfgPath))
|
|
255
|
+
skipped.push("keystone.yml (이미 있음, 그대로 둠)");
|
|
256
|
+
else {
|
|
257
|
+
const hasTestsDir = ["tests", "test", "__tests__"].some((d) => existsSync(join(o.root, d)));
|
|
258
|
+
writeFileSync(cfgPath, starterConfig({ hasTestsDir }));
|
|
259
|
+
done.push("keystone.yml 만들기 (규칙은 주석 예시만, 비워 둠)");
|
|
260
|
+
}
|
|
261
|
+
// 관계 카드 후보를 자동으로 만든다 (이미 있으면 갱신만 하고 사람이 쓴 칸은 보존)
|
|
262
|
+
try {
|
|
263
|
+
const project = loadProject(o.root);
|
|
264
|
+
const { calls } = buildCalls({ ...o, json: true }, project.graph.files);
|
|
265
|
+
const store = loadStore(o.root);
|
|
266
|
+
const isTest = picomatch(project.config.tests, { dot: true });
|
|
267
|
+
scanRelations(store, calls, project.config, (f) => isTest(f), { minBlast: 3 });
|
|
268
|
+
saveStore(o.root, store);
|
|
269
|
+
done.push(`관계 카드 후보 ${store.relations.length}개 (.keystone/relations.yml; 자동 후보는 '미검토' 표시)`);
|
|
270
|
+
}
|
|
271
|
+
catch (e) {
|
|
272
|
+
skipped.push(`관계 카드 스캔 건너뜀 (${e.message})`);
|
|
273
|
+
}
|
|
274
|
+
// 캐시/로그는 커밋하지 않는다
|
|
275
|
+
const gi = join(o.root, ".gitignore");
|
|
276
|
+
const ignoreLines = [".keystone/cache/", ".keystone/log.jsonl"];
|
|
277
|
+
try {
|
|
278
|
+
const cur = existsSync(gi) ? readFileSync(gi, "utf8") : "";
|
|
279
|
+
const need = ignoreLines.filter((l) => !cur.split(/\r?\n/).includes(l));
|
|
280
|
+
if (need.length) {
|
|
281
|
+
writeFileSync(gi, cur.replace(/\s*$/, "\n") + need.join("\n") + "\n");
|
|
282
|
+
done.push(`.gitignore에 ${need.join(", ")} 추가`);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
catch { /* 무시 */ }
|
|
286
|
+
if (doHook) {
|
|
287
|
+
const sp = join(o.root, ".claude", "settings.json");
|
|
288
|
+
let cur = null;
|
|
289
|
+
try {
|
|
290
|
+
cur = existsSync(sp) ? JSON.parse(readFileSync(sp, "utf8")) : null;
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
skipped.push(".claude/settings.json 을 읽을 수 없어 훅을 넣지 않았어요 (JSON 형식 확인)");
|
|
294
|
+
cur = undefined;
|
|
295
|
+
}
|
|
296
|
+
if (cur !== undefined) {
|
|
297
|
+
const { settings, added } = mergeHookSettings(cur);
|
|
298
|
+
if (added.length) {
|
|
299
|
+
mkdirSync(dirname(sp), { recursive: true });
|
|
300
|
+
writeFileSync(sp, JSON.stringify(settings, null, 2) + "\n");
|
|
301
|
+
done.push(`Claude Code 훅 연결 (${added.join(", ")}) → .claude/settings.json`);
|
|
302
|
+
}
|
|
303
|
+
else
|
|
304
|
+
skipped.push("Claude Code 훅 (이미 연결돼 있음)");
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (doMd) {
|
|
308
|
+
const mp = join(o.root, "CLAUDE.md");
|
|
309
|
+
const r = upsertClaudeMd(existsSync(mp) ? readFileSync(mp, "utf8") : null);
|
|
310
|
+
if (r.changed) {
|
|
311
|
+
writeFileSync(mp, r.text);
|
|
312
|
+
done.push("CLAUDE.md에 에이전트용 안내 추가/갱신");
|
|
313
|
+
}
|
|
314
|
+
else
|
|
315
|
+
skipped.push("CLAUDE.md (이미 최신)");
|
|
316
|
+
}
|
|
317
|
+
if (doCi) {
|
|
318
|
+
const out = join(o.root, ".github", "workflows", "keystone.yml");
|
|
319
|
+
if (existsSync(out))
|
|
320
|
+
skipped.push(".github/workflows/keystone.yml (이미 있음)");
|
|
321
|
+
else {
|
|
322
|
+
let testCommand = "npm test";
|
|
323
|
+
try {
|
|
324
|
+
testCommand = loadProject(o.root).config.test.command ?? "npm test";
|
|
325
|
+
}
|
|
326
|
+
catch { /* 기본값 */ }
|
|
327
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
328
|
+
writeFileSync(out, renderCiWorkflow({ testCommand, cli: o.cliCmd }));
|
|
329
|
+
done.push("GitHub Actions 설정 (.github/workflows/keystone.yml)");
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (doTrace) {
|
|
333
|
+
try {
|
|
334
|
+
const project = loadProject(o.root);
|
|
335
|
+
const command = o.testCommand ?? project.config.test.command ?? "npm test";
|
|
336
|
+
console.log(`실행 기록을 한 번 만들어요 (\`${command}\`, 시간이 걸릴 수 있어요)...`);
|
|
337
|
+
const r = runTrace(o.root, { command, testGlobs: project.config.tests, keep: false });
|
|
338
|
+
saveTrace(o.root, r.data, TRACE_PATH);
|
|
339
|
+
done.push(`실행 기록 저장: 실제로 실행된 함수 ${Object.keys(r.data.executed).length}개, 호출 관계 ${r.data.edges.length}개 (이후 calls/explain/test가 자동 반영)`);
|
|
340
|
+
}
|
|
341
|
+
catch (e) {
|
|
342
|
+
skipped.push(`실행 기록 건너뜀 (${e.message})`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
console.log("Keystone 준비:");
|
|
346
|
+
for (const d of done)
|
|
347
|
+
console.log(` ✓ ${d}`);
|
|
348
|
+
for (const d of skipped)
|
|
349
|
+
console.log(` · ${d}`);
|
|
350
|
+
console.log("\n다음 단계:");
|
|
351
|
+
console.log(" 1) 지켜야 할 곳을 keystone.yml 의 pins 에 적고, 중요한 숨은 관계는 `keystone relations add <from> <to> name=... does=... importance=high mutability=pinned` 로 남겨요.");
|
|
352
|
+
console.log(" 2) 고치기 전 `keystone before-edit <함수>`, 고친 뒤 `keystone check --base HEAD`.");
|
|
353
|
+
if (!doHook)
|
|
354
|
+
console.log(" 3) 에이전트(Claude Code)가 자동으로 안내받게 하려면: `keystone init --hook` (.claude/settings.json 에 훅 병합)");
|
|
355
|
+
if (!doMd)
|
|
356
|
+
console.log(" 4) 에이전트 지침에 넣으려면: `keystone init --claude-md`");
|
|
357
|
+
console.log(" 전체를 한 번에: `keystone init --all` · 쌓인 활동 보기: `keystone stats`");
|
|
358
|
+
return 0;
|
|
359
|
+
}
|
|
360
|
+
/** keystone feedback <규칙> <false-positive|useful> [--note 메모] : 경보가 틀렸는지/도움이 됐는지 알린다. 규칙은 pin:<경로> 또는 rel:<관계 id>. */
|
|
361
|
+
function feedbackCmd(o) {
|
|
362
|
+
const [, target, verdict] = o.positional;
|
|
363
|
+
if (!target || (verdict !== "false-positive" && verdict !== "useful")) {
|
|
364
|
+
console.error("usage: keystone feedback <규칙(pin:<경로>|rel:<관계 id>)> <false-positive|useful> [--note 메모]");
|
|
365
|
+
return 2;
|
|
366
|
+
}
|
|
367
|
+
logEvent(o.root, { kind: "feedback", target, verdict, note: o.note || undefined, by: "cli" });
|
|
368
|
+
console.log(`기록했어요: ${target} → ${verdict === "false-positive" ? "오경보" : "도움이 됨"}. 오경보가 3건 이상 쌓이고 도움 신고가 없으면 그 규칙은 차단하지 않고 알림만 합니다.`);
|
|
369
|
+
return 0;
|
|
370
|
+
}
|
|
371
|
+
function statsCmd(o) {
|
|
372
|
+
const days = o.days;
|
|
373
|
+
const sum = summarize(readEvents(o.root, days));
|
|
374
|
+
if (o.json) {
|
|
375
|
+
console.log(JSON.stringify(sum, null, 2));
|
|
376
|
+
return 0;
|
|
377
|
+
}
|
|
378
|
+
console.log(renderSummary(sum, days));
|
|
379
|
+
return 0;
|
|
380
|
+
}
|
|
187
381
|
const relLine = (r) => `${r.status === "stale" ? "✗낡음" : r.reviewed ? " ✓" : " ·"} ${r.name ? `"${r.name}" ` : ""}${r.id}\n ${r.edge} · 유형=${r.type ?? `(${r.typeGuess}?)`} · 중요도=${r.importance ?? `(${r.importanceHint}?)`}` +
|
|
188
382
|
`${r.mutability ? ` · ${r.mutability}` : ""} · 영향 ${r.blast}${r.does ? `\n ${r.does}` : ""}${r.proposal ? `\n ⏳ 제안(${r.proposal.by}): ${JSON.stringify(r.proposal.changes)}${r.proposal.note ? ` — ${r.proposal.note}` : ""}` : ""}`;
|
|
189
383
|
function relationsCmd(o) {
|
|
@@ -326,12 +520,18 @@ function traceCmd(o) {
|
|
|
326
520
|
function main() {
|
|
327
521
|
const o = parseArgs(process.argv.slice(2));
|
|
328
522
|
const cmd = o.positional[0];
|
|
329
|
-
if (!cmd || !["check", "test", "map", "explain", "calls", "before-edit", "hook", "relations", "graph", "trace", "ci"].includes(cmd)) {
|
|
523
|
+
if (!cmd || !["check", "test", "map", "explain", "calls", "before-edit", "hook", "init", "stats", "feedback", "relations", "graph", "trace", "ci"].includes(cmd)) {
|
|
330
524
|
console.log(USAGE);
|
|
331
525
|
return cmd ? 2 : 0;
|
|
332
526
|
}
|
|
333
527
|
if (cmd === "hook")
|
|
334
528
|
return hookCmd(o);
|
|
529
|
+
if (cmd === "init")
|
|
530
|
+
return initCmd(o);
|
|
531
|
+
if (cmd === "stats")
|
|
532
|
+
return statsCmd(o);
|
|
533
|
+
if (cmd === "feedback")
|
|
534
|
+
return feedbackCmd(o);
|
|
335
535
|
if (cmd === "relations")
|
|
336
536
|
return relationsCmd(o);
|
|
337
537
|
if (cmd === "graph")
|
|
@@ -355,6 +555,7 @@ function main() {
|
|
|
355
555
|
}
|
|
356
556
|
const { calls } = buildCalls(o, project.graph.files);
|
|
357
557
|
console.log(beforeEdit(calls, project.config, loadStore(o.root), target));
|
|
558
|
+
logEvent(o.root, { kind: "before-edit", target, by: "cli" });
|
|
358
559
|
return 0;
|
|
359
560
|
}
|
|
360
561
|
if (cmd === "explain" || cmd === "calls") {
|
|
@@ -397,10 +598,21 @@ function main() {
|
|
|
397
598
|
const needCalls = project.config.traceability.length > 0 || store.relations.some((r) => r.mutability);
|
|
398
599
|
const calls = needCalls ? buildCallGraph(o.root, project.graph.files) : undefined;
|
|
399
600
|
const res = runCheck(project.config, project.graph, changed, { readBase, calls });
|
|
400
|
-
//
|
|
601
|
+
// 오경보 신고가 쌓인 규칙은 차단하지 않고 알림만 한다
|
|
602
|
+
const events = readEvents(o.root);
|
|
603
|
+
const demoted = demotedTargets(events);
|
|
604
|
+
const demotedNotes = [];
|
|
605
|
+
for (const pc of [...res.pinnedChanges]) {
|
|
606
|
+
if (demoted.has(`pin:${pc.pattern}`)) {
|
|
607
|
+
res.pinnedChanges.splice(res.pinnedChanges.indexOf(pc), 1);
|
|
608
|
+
res.cosmetic.push({ ...pc, detail: `${pc.detail ?? ""} (오경보 신고로 알림만)` });
|
|
609
|
+
demotedNotes.push(`pin:${pc.pattern}`);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
// 관계 카드 검사: pinned 관계가 사라졌나 / careful 관계의 끝점이 바뀌었나 / 카드의 검증 명령(verify)
|
|
401
613
|
let relFindings = [];
|
|
614
|
+
const changedUnits = new Set();
|
|
402
615
|
if (calls && store.relations.length) {
|
|
403
|
-
const changedUnits = new Set();
|
|
404
616
|
for (const f of changed.filter((x) => project.graph.importers.has(x))) {
|
|
405
617
|
const d = diffUnits(o.root, f, readBase);
|
|
406
618
|
d.changed.forEach((id) => changedUnits.add(id));
|
|
@@ -408,6 +620,21 @@ function main() {
|
|
|
408
620
|
calls.byFile.get(f)?.forEach((id) => changedUnits.add(id));
|
|
409
621
|
}
|
|
410
622
|
relFindings = checkRelations(store, calls, changedUnits);
|
|
623
|
+
for (const r of store.relations) {
|
|
624
|
+
if (!r.verify || r.status === "stale" || !(changedUnits.has(r.from) || changedUnits.has(r.to)))
|
|
625
|
+
continue;
|
|
626
|
+
const v = spawnSync(r.verify, { cwd: o.root, shell: true, encoding: "utf8", timeout: 180000 });
|
|
627
|
+
if (v.status === 0)
|
|
628
|
+
relFindings.push({ id: r.id, level: "info", message: `검증 명령 통과: ${r.verify}` });
|
|
629
|
+
else
|
|
630
|
+
relFindings.push({ id: r.id, level: "error", message: `검증 명령 실패 (${r.verify})${r.does ? ` — ${r.does}` : ""}\n ${(v.stdout + v.stderr).trim().split("\n").slice(-4).join("\n ")}` });
|
|
631
|
+
}
|
|
632
|
+
for (const f of relFindings)
|
|
633
|
+
if (f.level === "error" && demoted.has(`rel:${f.id}`)) {
|
|
634
|
+
f.level = "warn";
|
|
635
|
+
f.message += " (오경보 신고로 알림만)";
|
|
636
|
+
demotedNotes.push(`rel:${f.id}`);
|
|
637
|
+
}
|
|
411
638
|
}
|
|
412
639
|
const relFail = relFindings.some((f) => f.level === "error");
|
|
413
640
|
// 함수 입출력(시그니처) 변경: 바뀌었으면 호출하는 곳을 보여준다 (git 기준 내용이 있을 때만)
|
|
@@ -418,11 +645,23 @@ function main() {
|
|
|
418
645
|
sigFindings = signatureFindings(o.root, diffs, calls ?? buildCallGraph(o.root, project.graph.files), readBase);
|
|
419
646
|
}
|
|
420
647
|
const sigFail = signatureFailed(sigFindings, project.config.signatures.failOn);
|
|
421
|
-
const
|
|
648
|
+
const rawFailed = checkFailed(res, o.allowPinned) || relFail || sigFail;
|
|
649
|
+
const overridden = rawFailed && !!o.reason;
|
|
650
|
+
const failed = rawFailed && !overridden;
|
|
651
|
+
const warns = relFindings.some((f) => f.level === "warn") || sigFindings.length > 0;
|
|
652
|
+
const verdict = overridden ? "OVERRIDE" : failed ? "BLOCK" : warns ? "WARN" : "OK";
|
|
653
|
+
const blocked = rawFailed ? {
|
|
654
|
+
pinned: o.allowPinned ? 0 : res.pinnedChanges.length, boundaries: res.violations.length, relations: relFindings.filter((f) => f.level === "error").length,
|
|
655
|
+
signatures: sigFail ? 1 : 0, invariants: res.invariants.filter((i) => i.missing).length
|
|
656
|
+
} : undefined;
|
|
657
|
+
logEvent(o.root, { kind: "check", ok: !rawFailed, by: "cli", blocked, ...(overridden ? { overridden: o.reason } : {}) });
|
|
658
|
+
const parts = blocked ? [["보호된 곳 변경", blocked.pinned], ["관계 사라짐/검증 실패", blocked.relations], ["경계 위반", blocked.boundaries], ["함수 입출력 변경", blocked.signatures], ["불변조건", blocked.invariants]].filter(([, n]) => n > 0).map(([k, n]) => `${k} ${n}`) : [];
|
|
422
659
|
if (o.json) {
|
|
423
|
-
console.log(JSON.stringify({ ok: !failed, ...res, relations: relFindings, signatures: sigFindings }, null, 2));
|
|
660
|
+
console.log(JSON.stringify({ ok: !failed, verdict, ...res, relations: relFindings, signatures: sigFindings, ...(overridden ? { overridden: o.reason } : {}) }, null, 2));
|
|
424
661
|
return failed ? 1 : 0;
|
|
425
662
|
}
|
|
663
|
+
// 첫 줄에 판정을 둔다 (자세한 근거는 아래)
|
|
664
|
+
console.log(verdict === "OK" ? `keystone check: OK (${changed.length}개 파일 변경)` : `keystone check: ${verdict}${parts.length ? ` — ${parts.join(" · ")}` : ""}${overridden ? ` (알고도 진행: ${o.reason})` : ""}`);
|
|
426
665
|
for (const v of res.violations)
|
|
427
666
|
console.log(`✗ boundary ${v.file} → ${v.imports}${v.via ? `\n path: ${v.via.join(" → ")}` : ""}\n rule: ${v.rule}${v.reason ? ` (${v.reason})` : ""}`);
|
|
428
667
|
for (const t of res.trace)
|
|
@@ -439,11 +678,18 @@ function main() {
|
|
|
439
678
|
}
|
|
440
679
|
for (const line of renderSignatureFindings(sigFindings))
|
|
441
680
|
console.log(line);
|
|
442
|
-
for (const f of relFindings)
|
|
443
|
-
|
|
681
|
+
for (const f of relFindings) {
|
|
682
|
+
const rel = store.relations.find((r) => r.id === f.id);
|
|
683
|
+
console.log(`${f.level === "error" ? "✗" : f.level === "warn" ? "!" : "ℹ"} relation ${f.id}${rel ? ` ${trustTag(rel)}` : ""}\n ${f.message}`);
|
|
684
|
+
}
|
|
444
685
|
if (project.graph.unresolved.length)
|
|
445
686
|
console.log(`ℹ 해석하지 못한 동적 import ${project.graph.unresolved.length}건 (keystone map에서 확인)`);
|
|
446
|
-
|
|
687
|
+
if (failed) {
|
|
688
|
+
const what = [...res.pinnedChanges.map((p) => `보호된 곳 ${p.file}${p.detail ? ` [${p.detail}]` : ""}`), ...relFindings.filter((f) => f.level === "error").map((f) => `관계 ${f.id}`), ...res.violations.map((v) => `경계 ${v.file} → ${v.imports}`)].slice(0, 3).join(", ") || "문서화된 규칙";
|
|
689
|
+
console.log(`\n다음 행동:\n 1) 의도하지 않은 변경이면 되돌리세요.\n 2) 의도한 변경이면 먼저 사용자에게 이렇게 확인하세요: "이 수정은 ${what}에 영향을 줍니다. 진행할까요?"\n 승인받았다면: keystone check --base HEAD --reason "<이유>" (이유는 .keystone/log.jsonl에 기록되고 keystone stats에 보입니다)\n 3) 이 경고가 틀렸다면: keystone feedback <규칙> false-positive (규칙: ${[...res.pinnedChanges.map((p) => `pin:${p.pattern}`), ...relFindings.filter((f) => f.level === "error").map((f) => `rel:${f.id}`)].slice(0, 2).join(" · ") || "pin:<경로> 또는 rel:<관계 id>"})`);
|
|
690
|
+
}
|
|
691
|
+
if (demotedNotes.length)
|
|
692
|
+
console.log(`ℹ 오경보 신고로 알림만 하는 규칙: ${demotedNotes.join(", ")}`);
|
|
447
693
|
return failed ? 1 : 0;
|
|
448
694
|
}
|
|
449
695
|
// test
|
|
@@ -452,6 +698,12 @@ function main() {
|
|
|
452
698
|
? (() => { const { calls, trace } = buildCalls(o, project.graph.files); return { calls, trace, readBase: o.files ? undefined : baseReader(o.root, o.base) }; })()
|
|
453
699
|
: undefined;
|
|
454
700
|
const sel = selectTests(project.config, project.graph, changed, { all: o.all, deleted, precise });
|
|
701
|
+
{
|
|
702
|
+
const isT = picomatch(project.config.tests, { dot: true });
|
|
703
|
+
const total = project.graph.files.filter((f) => isT(f)).length;
|
|
704
|
+
if (total > 0)
|
|
705
|
+
logEvent(o.root, { kind: "test", by: "cli", tests: { total, selected: Math.min(sel.tests.length, total) } });
|
|
706
|
+
}
|
|
455
707
|
if (o.json) {
|
|
456
708
|
console.log(JSON.stringify(sel, null, 2));
|
|
457
709
|
if (o.list)
|
package/package.json
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "keystone-relation",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "Keystone: track the relationships between functions, see who calls what, check what a change affects, and catch broken relationships before they become bugs. (JS/TS)",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"bin": {
|
|
7
|
-
"keystone-relation": "dist/index.js",
|
|
8
|
-
"keystone": "dist/index.js",
|
|
9
|
-
"krl": "dist/index.js"
|
|
10
|
-
},
|
|
11
|
-
"files": [
|
|
12
|
-
"dist"
|
|
13
|
-
],
|
|
14
|
-
"dependencies": {
|
|
15
|
-
"keystone-relation-core": "^
|
|
16
|
-
"picomatch": "^4.0.7"
|
|
17
|
-
},
|
|
18
|
-
"devDependencies": {
|
|
19
|
-
"@types/picomatch": "^4.0.3"
|
|
20
|
-
},
|
|
21
|
-
"license": "MIT",
|
|
22
|
-
"engines": {
|
|
23
|
-
"node": ">=20"
|
|
24
|
-
},
|
|
25
|
-
"publishConfig": {
|
|
26
|
-
"access": "public"
|
|
27
|
-
},
|
|
28
|
-
"keywords": [
|
|
29
|
-
"code-relations",
|
|
30
|
-
"call-graph",
|
|
31
|
-
"impact-analysis",
|
|
32
|
-
"test-selection",
|
|
33
|
-
"typescript",
|
|
34
|
-
"javascript",
|
|
35
|
-
"mcp",
|
|
36
|
-
"claude-code"
|
|
37
|
-
],
|
|
38
|
-
"scripts": {
|
|
39
|
-
"prepublishOnly": "cd ../.. && npm run build"
|
|
40
|
-
},
|
|
41
|
-
"author": "Vamp-pire",
|
|
42
|
-
"repository": {
|
|
43
|
-
"type": "git",
|
|
44
|
-
"url": "git+https://github.com/Vamp-pire/keystone-relation.git",
|
|
45
|
-
"directory": "packages/cli"
|
|
46
|
-
},
|
|
47
|
-
"homepage": "https://github.com/Vamp-pire/keystone-relation#readme",
|
|
48
|
-
"bugs": {
|
|
49
|
-
"url": "https://github.com/Vamp-pire/keystone-relation/issues"
|
|
50
|
-
}
|
|
51
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "keystone-relation",
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Keystone: track the relationships between functions, see who calls what, check what a change affects, and catch broken relationships before they become bugs. (JS/TS)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"keystone-relation": "dist/index.js",
|
|
8
|
+
"keystone": "dist/index.js",
|
|
9
|
+
"krl": "dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist"
|
|
13
|
+
],
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"keystone-relation-core": "^1.1.0",
|
|
16
|
+
"picomatch": "^4.0.7"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@types/picomatch": "^4.0.3"
|
|
20
|
+
},
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=20"
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"code-relations",
|
|
30
|
+
"call-graph",
|
|
31
|
+
"impact-analysis",
|
|
32
|
+
"test-selection",
|
|
33
|
+
"typescript",
|
|
34
|
+
"javascript",
|
|
35
|
+
"mcp",
|
|
36
|
+
"claude-code"
|
|
37
|
+
],
|
|
38
|
+
"scripts": {
|
|
39
|
+
"prepublishOnly": "cd ../.. && npm run build"
|
|
40
|
+
},
|
|
41
|
+
"author": "Vamp-pire",
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "git+https://github.com/Vamp-pire/keystone-relation.git",
|
|
45
|
+
"directory": "packages/cli"
|
|
46
|
+
},
|
|
47
|
+
"homepage": "https://github.com/Vamp-pire/keystone-relation#readme",
|
|
48
|
+
"bugs": {
|
|
49
|
+
"url": "https://github.com/Vamp-pire/keystone-relation/issues"
|
|
50
|
+
}
|
|
51
|
+
}
|