keystone-relation 0.0.0-stage → 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vamp-pire
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,19 @@
1
+ import { type GraphDiff, type KeystoneConfig, type RelationStore } from "keystone-relation-core";
2
+ export interface GraphOpts {
3
+ root: string;
4
+ base?: string;
5
+ json: boolean;
6
+ positional: string[];
7
+ out?: string;
8
+ includeInferred: boolean;
9
+ includeTests: boolean;
10
+ fail: boolean;
11
+ }
12
+ /** keystone.yml이 없어도 동작한다 (규칙/카드 표시만 빠진다) */
13
+ export declare function loadOptional(root: string): {
14
+ config?: KeystoneConfig;
15
+ store?: RelationStore;
16
+ };
17
+ export declare function computeDiff(o: GraphOpts): GraphDiff;
18
+ /** graph snapshot | graph diff */
19
+ export declare function graphCmd(o: GraphOpts): number;
@@ -0,0 +1,63 @@
1
+ import { baseReader, buildCallGraph, changedFiles, diffSignatures, listProjectFiles, jsTsAdapter, renderSignatureFindings, signatureFindings, diffSnapshots, isTestFor, loadProject, loadStore, makeSnapshot, renderGraphDiff, snapshotAtRef, } from "keystone-relation-core";
2
+ import { writeFileSync } from "node:fs";
3
+ /** keystone.yml이 없어도 동작한다 (규칙/카드 표시만 빠진다) */
4
+ export function loadOptional(root) {
5
+ try {
6
+ const p = loadProject(root);
7
+ return { config: p.config, store: loadStore(root) };
8
+ }
9
+ catch {
10
+ return {};
11
+ }
12
+ }
13
+ export function computeDiff(o) {
14
+ const { config, store } = loadOptional(o.root);
15
+ const isTest = config ? isTestFor(config) : (f) => /(^|\/)(tests?|__tests__)\/|\.(test|spec)\./.test(f);
16
+ const base = snapshotAtRef(o.root, o.base ?? "HEAD");
17
+ const cur = makeSnapshot(o.root, "작업 폴더");
18
+ return diffSnapshots(base, cur, { config, store, isTest: (f) => isTest(f), includeInferred: o.includeInferred, includeTests: o.includeTests });
19
+ }
20
+ /** graph snapshot | graph diff */
21
+ export function graphCmd(o) {
22
+ const sub = o.positional[1];
23
+ if (sub === "snapshot") {
24
+ const snap = makeSnapshot(o.root, "작업 폴더");
25
+ if (o.out) {
26
+ writeFileSync(o.out, JSON.stringify(snap));
27
+ console.log(`스냅샷 저장: ${o.out} (단위 ${snap.units.length}, 관계 ${snap.edges.length})`);
28
+ }
29
+ else
30
+ console.log(JSON.stringify(snap));
31
+ return 0;
32
+ }
33
+ if (sub === "diff") {
34
+ const d = computeDiff(o);
35
+ // 입출력(시그니처)이 바뀐 함수와 그 호출자: git 기준 내용이 있을 때만
36
+ const readBase = baseReader(o.root, o.base ?? "HEAD");
37
+ const codeFiles = (() => { try {
38
+ return changedFiles(o.root, o.base ?? "HEAD");
39
+ }
40
+ catch {
41
+ return [];
42
+ } })();
43
+ const sigDiffs = diffSignatures(o.root, codeFiles, readBase);
44
+ const sigs = sigDiffs.length ? signatureFindings(o.root, sigDiffs, buildCallGraph(o.root, listProjectFiles(o.root, jsTsAdapter)), readBase) : [];
45
+ if (o.json)
46
+ console.log(JSON.stringify({ ...d, signatures: sigs }, null, 2));
47
+ else {
48
+ console.log(renderGraphDiff(d));
49
+ if (sigs.length)
50
+ console.log("\n입출력(시그니처)이 바뀐 함수\n" + renderSignatureFindings(sigs).join("\n"));
51
+ }
52
+ if (o.fail) {
53
+ const bad = d.removed.some((e) => e.card?.mutability === "pinned") || d.added.some((e) => e.boundary);
54
+ if (bad) {
55
+ console.log("\nkeystone graph diff: FAILED (pinned 관계가 사라졌거나 경계 규칙을 어기는 새 관계가 있음)");
56
+ return 1;
57
+ }
58
+ }
59
+ return 0;
60
+ }
61
+ console.error("usage: keystone graph <snapshot [--out file] | diff [--base ref] [--include-inferred] [--include-tests] [--fail] [--json]>");
62
+ return 2;
63
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,486 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
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";
7
+ import picomatch from "picomatch";
8
+ 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";
10
+ // 큰 프로젝트에서 메모리 부족으로 죽지 않도록, 기본 한도가 낮으면 한도를 올려 자기 자신을 다시 실행한다.
11
+ {
12
+ const limitMb = getHeapStatistics().heap_size_limit / 1048576;
13
+ if (limitMb < 4000 && !process.env.KEYSTONE_HEAP_SET) {
14
+ const r = spawnSync(process.execPath, ["--max-old-space-size=8192", ...process.argv.slice(1)], { stdio: "inherit", env: { ...process.env, KEYSTONE_HEAP_SET: "1" } });
15
+ process.exit(r.status ?? 1);
16
+ }
17
+ }
18
+ const USAGE = `usage: keystone <command> [options]
19
+
20
+ 처음이라면 (명령 3개면 충분해요):
21
+ keystone explain <함수> --down 2 이 함수가 어떻게 흘러가는지 (실행 흐름 파악)
22
+ keystone calls <함수> 누가 부르고 무엇을 부르는지 (같은 이름 함수도 구분)
23
+ keystone before-edit <함수|파일> 고치기 전에: 영향 범위·테스트·보호된 곳 확인
24
+ (고친 뒤: keystone graph diff = 사라진/바뀐 관계 확인, keystone test --precise = 영향받는 테스트만)
25
+
26
+ commands:
27
+ hook init Claude Code가 파일을 고치기 직전에 before-edit을 자동으로 보여 주는 설정 예시 출력 (파일은 안 건드림)
28
+ before-edit <함수|파일> 고치기 전 확인 (영향 범위, 관련 테스트, pinned/관계 카드, 추정 연결)
29
+ check 경계 규칙 + pinned + 불변조건 + 추적성 + 관계 카드 검사
30
+ test 변경 파일의 영향을 받는 테스트만 실행
31
+ map 구조 지도(목차) 출력
32
+ explain <파일|함수> 코드 이해용 설명: 누가 부르나/무엇을 부르나/영향 범위/모르는 호출/관계 카드
33
+ --down N: 이 함수가 부르는 것을 N단계 아래까지 나무로 펼침(실행 흐름 파악용)
34
+ --up N: 이 함수를 부르는 곳을 N단계 위까지 펼침
35
+ calls <함수> 이 함수를 부르는 곳과 이 함수가 부르는 곳의 목록 (줄 번호 포함). 함수 이름만 써도 됨
36
+ trace -- <명령> 테스트(또는 아무 명령)를 실제로 실행하면서 일어난 호출을 기록 (예: keystone trace -- npm test). 기록은 calls/explain/test에 자동 반영
37
+ trace show 저장된 실행 기록 요약
38
+ ci init PR/병합 때 자동으로 돌리는 GitHub Actions 설정 파일 생성 (--test-command, --cli, --out)
39
+ graph <sub> 관계 변화 비교 (snapshot | diff): 사라진 관계 / 새 관계 / 이름 변경
40
+ relations <sub> 관계 카드 관리 (scan | list | show | set | add | propose | approve | reject | prune)
41
+
42
+ 공통 options:
43
+ --root <dir> 프로젝트 루트 (기본: 현재 디렉토리)
44
+ --base <ref> 이 git ref 대비 변경 파일 사용 (기본: HEAD)
45
+ --files a,b,c git 대신 변경 파일을 직접 지정
46
+ --json JSON 출력
47
+ check: --strict-pins (pin을 바이트 단위로) · --allow-pinned (pinned 변경을 경고로)
48
+ test: --precise (함수 단위 정밀 선택) · --all (전체) · --list (실행 없이 선택 결과만)
49
+ relations scan: --min-blast N (새 카드 기준, 기본 3) · --all (모든 관계 저장) · --same-file · --follow-renames (이름만 바뀐 관계는 카드를 옮김, --base 기준)
50
+ graph diff: --base <ref> · --include-inferred · --include-tests · --fail (pinned 관계 손실/경계 위반이면 exit 1) · --json
51
+ relations list: --status active|stale · --importance core|high|normal|low · --unreviewed · --proposals
52
+ relations set <id> key=value ... (${HUMAN_FIELDS.join(", ")})
53
+ type=${RELATION_TYPES.join("|")}
54
+ importance=${IMPORTANCE.join("|")} mutability=${MUTABILITY.join("|")}
55
+ relations propose <id> key=value ... [--by 이름] [--note 메모] 에이전트용: 적용하지 않고 제안으로만 저장
56
+ relations add <from> <to> key=value ... 자동으로 못 찾는 숨은 연결을 직접 추가`;
57
+ function parseArgs(argv0) {
58
+ // `keystone trace -- npm test` : -- 뒤는 실행할 명령이다
59
+ const dd = argv0.indexOf("--");
60
+ const argv = dd >= 0 ? argv0.slice(0, dd) : argv0;
61
+ const traceCommand = dd >= 0 ? argv0.slice(dd + 1).join(" ") : "";
62
+ 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: "" };
64
+ for (let i = 0; i < argv.length; i++) {
65
+ const a = argv[i];
66
+ const val = () => { if (i + 1 >= argv.length) {
67
+ console.error(`${a}: 값이 필요합니다`);
68
+ process.exit(2);
69
+ } return argv[++i]; };
70
+ if (a === "--root")
71
+ o.root = resolve(val());
72
+ else if (a === "--base")
73
+ o.base = val();
74
+ else if (a === "--files")
75
+ o.files = val().split(",").filter(Boolean);
76
+ else if (a === "--strict-pins")
77
+ o.strictPins = true;
78
+ else if (a === "--allow-pinned")
79
+ o.allowPinned = true;
80
+ else if (a === "--all")
81
+ o.all = true;
82
+ else if (a === "--precise")
83
+ o.precise = true;
84
+ else if (a === "--list")
85
+ o.list = true;
86
+ else if (a === "--json")
87
+ o.json = true;
88
+ else if (a === "--min-blast")
89
+ o.minBlast = Number(val());
90
+ else if (a === "--no-trace")
91
+ o.noTrace = true;
92
+ else if (a === "--keep")
93
+ o.keep = true;
94
+ else if (a === "--test-command")
95
+ o.testCommand = val();
96
+ else if (a === "--cli")
97
+ o.cliCmd = val();
98
+ else if (a === "--down")
99
+ o.down = Number(val());
100
+ else if (a === "--up")
101
+ o.up = Number(val());
102
+ else if (a === "--same-file")
103
+ o.sameFile = true;
104
+ else if (a === "--out")
105
+ o.out = val();
106
+ else if (a === "--include-inferred")
107
+ o.includeInferred = true;
108
+ else if (a === "--include-tests")
109
+ o.includeTests = true;
110
+ else if (a === "--fail")
111
+ o.fail = true;
112
+ else if (a === "--follow-renames")
113
+ o.followRenames = true;
114
+ else if (a === "--status")
115
+ o.status = val();
116
+ else if (a === "--importance")
117
+ o.importance = val();
118
+ else if (a === "--unreviewed")
119
+ o.unreviewed = true;
120
+ else if (a === "--proposals")
121
+ o.proposals = true;
122
+ else if (a === "--by")
123
+ o.by = val();
124
+ else if (a === "--note")
125
+ o.note = val();
126
+ else if (!a.startsWith("--"))
127
+ o.positional.push(a);
128
+ else {
129
+ console.error(`unknown option: ${a}\n\n${USAGE}`);
130
+ process.exit(2);
131
+ }
132
+ }
133
+ o.traceCommand = traceCommand;
134
+ return o;
135
+ }
136
+ /** 호출 그래프를 만들고, 실행 기록(keystone trace)이 있으면 합친다 */
137
+ function buildCalls(o, files) {
138
+ const { graph: calls, cached } = buildCallGraphCached(o.root, files);
139
+ if (cached && !o.json)
140
+ console.error("ℹ 코드가 그대로라서 저장해 둔 분석 결과를 불러왔어요.");
141
+ const trace = o.noTrace ? null : loadTrace(o.root);
142
+ if (trace) {
143
+ const r = applyTrace(calls, trace);
144
+ if (!o.json)
145
+ console.error(`ℹ 실행 기록(${trace.createdAt.slice(0, 10)}, \`${trace.command}\`)을 반영했어요: 실제로 확인된 호출 ${r.matched}건, 코드 읽기로 못 찾은 호출 ${r.added}건 추가${r.stale ? `, 코드가 바뀌어 맞지 않는 옛 기록 ${r.stale}건 제외` : ""}. (끄려면 --no-trace)`);
146
+ }
147
+ return { calls, trace };
148
+ }
149
+ const HOOK_SNIPPET = {
150
+ hooks: { PreToolUse: [{ matcher: "Edit|Write|MultiEdit", hooks: [{ type: "command", command: "npx --no-install keystone hook run" }] }] },
151
+ };
152
+ /** keystone hook init → 설정 예시 출력 (파일은 건드리지 않음)
153
+ * keystone hook run → Claude Code 훅으로 호출됨: 고칠 파일의 영향 범위를 모델에게 알려 줌 */
154
+ function hookCmd(o) {
155
+ const sub = o.positional[1];
156
+ if (sub === "init") {
157
+ console.log("아래를 프로젝트의 .claude/settings.json 에 직접 넣으세요 (Keystone은 설정 파일을 수정하지 않아요):\n");
158
+ console.log(JSON.stringify(HOOK_SNIPPET, null, 2));
159
+ console.log("\n설명: 에이전트가 파일을 고치기 직전에 그 파일의 영향 범위(호출자, 관련 테스트, 보호된 곳)를 알려 줍니다. 차단하지 않고 알려 주기만 해요.");
160
+ return 0;
161
+ }
162
+ if (sub === "run") {
163
+ let raw = "";
164
+ try {
165
+ raw = readFileSync(0, "utf8");
166
+ }
167
+ catch { /* 입력 없음 */ }
168
+ try {
169
+ const inp = JSON.parse(raw || "{}");
170
+ const fp = inp.tool_input?.file_path;
171
+ if (!fp)
172
+ return 0;
173
+ const rel = fp.startsWith(o.root) ? fp.slice(o.root.length).replace(/^\/+/, "") : fp;
174
+ const project = loadProject(o.root);
175
+ if (!project.graph.files.includes(rel))
176
+ return 0;
177
+ const { calls } = buildCalls({ ...o, json: true }, project.graph.files);
178
+ const text = beforeEdit(calls, project.config, loadStore(o.root), rel);
179
+ console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: text } }));
180
+ }
181
+ catch { /* 훅은 절대 작업을 막지 않는다 */ }
182
+ return 0;
183
+ }
184
+ console.error("usage: keystone hook <init|run>");
185
+ return 2;
186
+ }
187
+ 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
+ `${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
+ function relationsCmd(o) {
190
+ const [, sub, ...rest] = o.positional;
191
+ const project = loadProject(o.root);
192
+ const store = loadStore(o.root);
193
+ const isTest = picomatch(project.config.tests, { dot: true });
194
+ if (sub === "scan") {
195
+ const calls = buildCallGraph(o.root, project.graph.files);
196
+ const renames = o.followRenames ? renameMapOf(computeDiff(o)) : undefined;
197
+ const rep = scanRelations(store, calls, project.config, (f) => isTest(f), { minBlast: o.minBlast, all: o.all, includeSameFile: o.sameFile, renames });
198
+ saveStore(o.root, store);
199
+ console.log(`keystone relations scan: 새 카드 ${rep.added.length} · 갱신 ${rep.refreshed} · 낡음 ${rep.stale.length} · 되살아남 ${rep.revived.length} (후보 ${rep.candidates})`);
200
+ for (const id of rep.added.slice(0, 15))
201
+ console.log(` + ${id}`);
202
+ if (rep.added.length > 15)
203
+ console.log(` … 외 ${rep.added.length - 15}개`);
204
+ for (const m of rep.moved)
205
+ console.log(` ↦ 이름 변경 따라감: ${m.from}\n → ${m.to}`);
206
+ for (const id of rep.stale)
207
+ console.log(` ✗ 낡음: ${id}`);
208
+ console.log(`\n저장: .keystone/relations.yml — 사람이 쓴 필드(${HUMAN_FIELDS.join(", ")})는 다시 스캔해도 보존됩니다.`);
209
+ return 0;
210
+ }
211
+ if (sub === "list") {
212
+ let rels = store.relations;
213
+ if (o.status)
214
+ rels = rels.filter((r) => r.status === o.status);
215
+ if (o.importance)
216
+ rels = rels.filter((r) => (r.importance ?? r.importanceHint) === o.importance);
217
+ if (o.unreviewed)
218
+ rels = rels.filter((r) => !r.reviewed);
219
+ if (o.proposals)
220
+ rels = rels.filter((r) => r.proposal);
221
+ if (o.json) {
222
+ console.log(JSON.stringify(rels, null, 2));
223
+ return 0;
224
+ }
225
+ console.log(`관계 카드 ${rels.length}개 (전체 ${store.relations.length}) — ✓검토됨 · 미검토 ✗낡음 / (?)는 자동 추정`);
226
+ for (const r of rels)
227
+ console.log(relLine(r));
228
+ return 0;
229
+ }
230
+ if (sub === "show") {
231
+ const r = findRelation(store, rest[0] ?? "");
232
+ console.log(JSON.stringify(r, null, 2));
233
+ return 0;
234
+ }
235
+ if (sub === "set") {
236
+ const r = findRelation(store, rest[0] ?? "");
237
+ editRelation(r, parseAssignments(rest.slice(1)));
238
+ saveStore(o.root, store);
239
+ console.log("적용됨:\n" + relLine(r));
240
+ return 0;
241
+ }
242
+ if (sub === "propose") {
243
+ const r = findRelation(store, rest[0] ?? "");
244
+ proposeChange(r, o.by, parseAssignments(rest.slice(1)), o.note);
245
+ saveStore(o.root, store);
246
+ console.log(`제안으로 저장됨 (적용되지 않음, 사람이 approve 해야 함):\n` + relLine(r));
247
+ return 0;
248
+ }
249
+ if (sub === "approve") {
250
+ const r = findRelation(store, rest[0] ?? "");
251
+ approveProposal(r);
252
+ saveStore(o.root, store);
253
+ console.log("승인되어 적용됨:\n" + relLine(r));
254
+ return 0;
255
+ }
256
+ if (sub === "reject") {
257
+ const r = findRelation(store, rest[0] ?? "");
258
+ rejectProposal(r);
259
+ saveStore(o.root, store);
260
+ console.log("제안을 거절했습니다");
261
+ return 0;
262
+ }
263
+ if (sub === "add") {
264
+ const [from, to, ...kv] = rest;
265
+ if (!from || !to)
266
+ throw new Error("usage: keystone relations add <from> <to> key=value ...");
267
+ const r = addManualRelation(store, from, to, parseAssignments(kv));
268
+ saveStore(o.root, store);
269
+ console.log("추가됨:\n" + relLine(r));
270
+ return 0;
271
+ }
272
+ if (sub === "prune") {
273
+ const before = store.relations.length;
274
+ store.relations = store.relations.filter((r) => !(r.status === "stale" && r.mutability !== "pinned" && !r.reviewed));
275
+ saveStore(o.root, store);
276
+ console.log(`낡은 미검토 카드 ${before - store.relations.length}개 삭제 (pinned/검토된 카드는 유지)`);
277
+ return 0;
278
+ }
279
+ console.error(`relations: 알 수 없는 하위 명령 '${sub ?? ""}'\n\n${USAGE}`);
280
+ return 2;
281
+ }
282
+ function ciCmd(o) {
283
+ if (o.positional[1] !== "init") {
284
+ console.error("usage: keystone ci init [--test-command \"npm test\"] [--cli \"npx keystone-relation\"] [--out .github/workflows/keystone.yml]");
285
+ return 2;
286
+ }
287
+ const project = loadProject(o.root);
288
+ const out = resolve(o.root, o.out ?? ".github/workflows/keystone.yml");
289
+ const testCommand = o.testCommand ?? project.config.test.command ?? "npm test";
290
+ mkdirSync(dirname(out), { recursive: true });
291
+ writeFileSync(out, renderCiWorkflow({ testCommand, cli: o.cliCmd }));
292
+ console.log(`자동 실행 설정을 만들었어요: ${out}\n - PR이 올라오면: keystone check + graph diff --fail (규칙 위반, 사라진 pinned 관계, 경계 위반이면 실패)\n - main에 병합되면: \`${testCommand}\` 를 실행하면서 호출을 기록하고 결과(keystone-trace.json)를 보관\n이 파일을 커밋하면 다음 PR부터 동작해요. Keystone 명령은 \`${o.cliCmd ?? "npx keystone-relation"}\` 로 부르도록 되어 있으니, 패키지를 설치했거나 --cli로 실행 경로를 지정했는지 확인하세요.`);
293
+ return 0;
294
+ }
295
+ function traceCmd(o) {
296
+ const sub = o.positional[1];
297
+ if (sub === "show") {
298
+ const t = loadTrace(o.root, o.out ?? TRACE_PATH);
299
+ if (!t) {
300
+ console.log("저장된 실행 기록이 없어요. keystone trace -- <테스트 명령> 으로 먼저 기록하세요.");
301
+ return 1;
302
+ }
303
+ const top = Object.entries(t.executed).sort((a, b) => b[1] - a[1]).slice(0, 10);
304
+ console.log(`실행 기록: ${t.createdAt} · 명령 \`${t.command}\` · 종료코드 ${t.exitCode}\n 실행된 함수 ${Object.keys(t.executed).length}개 · 기록된 호출 관계 ${t.edges.length}개 · 테스트 파일 ${Object.keys(t.roots).filter((r) => r !== "<outside>").length}개\n 가장 많이 실행된 함수:`);
305
+ for (const [id, c] of top)
306
+ console.log(` ${String(c).padStart(8)}회 ${id}`);
307
+ return 0;
308
+ }
309
+ const project = loadProject(o.root);
310
+ const command = o.traceCommand || project.config.test.command;
311
+ if (!command) {
312
+ console.error("실행할 명령이 없어요. `keystone trace -- npm test` 처럼 -- 뒤에 테스트 명령을 쓰거나, keystone.yml의 test.command를 설정하세요.");
313
+ return 2;
314
+ }
315
+ console.log(`실행 기록을 시작합니다: 프로젝트를 임시 폴더로 복사하고, 함수마다 기록 코드를 끼워 넣은 뒤 \`${command}\` 를 실행해요 (원본은 바뀌지 않아요).`);
316
+ const r = runTrace(o.root, { command, testGlobs: project.config.tests, keep: o.keep });
317
+ const path = saveTrace(o.root, r.data, o.out ?? TRACE_PATH);
318
+ console.log(`\n실행 기록 저장: ${path}\n 기록 코드를 끼운 함수 ${r.instrumentedFunctions}개 (파일 ${r.instrumentedFiles}개) · 실제로 실행된 함수 ${Object.keys(r.data.executed).length}개 · 호출 관계 ${r.data.edges.length}개 · 기록한 프로세스 ${r.processes}개 · 명령 종료코드 ${r.data.exitCode}`);
319
+ if (!r.processes)
320
+ console.log("⚠ 기록이 하나도 없어요. 명령이 Node.js로 실행되는지(예: npm test → node/vitest/jest) 확인하세요.");
321
+ if (r.workDir)
322
+ console.log(` (복사본 보관: ${r.workDir})`);
323
+ console.log("이제 `keystone calls <함수>`, `keystone explain <함수> --down 3`, `keystone test --precise` 가 이 기록을 자동으로 반영해요.");
324
+ return r.data.exitCode ?? 1;
325
+ }
326
+ function main() {
327
+ const o = parseArgs(process.argv.slice(2));
328
+ const cmd = o.positional[0];
329
+ if (!cmd || !["check", "test", "map", "explain", "calls", "before-edit", "hook", "relations", "graph", "trace", "ci"].includes(cmd)) {
330
+ console.log(USAGE);
331
+ return cmd ? 2 : 0;
332
+ }
333
+ if (cmd === "hook")
334
+ return hookCmd(o);
335
+ if (cmd === "relations")
336
+ return relationsCmd(o);
337
+ if (cmd === "graph")
338
+ return graphCmd(o);
339
+ if (cmd === "ci")
340
+ return ciCmd(o);
341
+ if (cmd === "trace")
342
+ return traceCmd(o);
343
+ const project = loadProject(o.root);
344
+ if (!project.configFound && !o.json)
345
+ console.error(`ℹ ${MISSING_CONFIG_HINT}`);
346
+ if (cmd === "map") {
347
+ console.log(renderMap(project.config, project.graph));
348
+ return 0;
349
+ }
350
+ if (cmd === "before-edit") {
351
+ const target = o.positional[1];
352
+ if (!target) {
353
+ console.error("usage: keystone before-edit <함수|파일>");
354
+ return 2;
355
+ }
356
+ const { calls } = buildCalls(o, project.graph.files);
357
+ console.log(beforeEdit(calls, project.config, loadStore(o.root), target));
358
+ return 0;
359
+ }
360
+ if (cmd === "explain" || cmd === "calls") {
361
+ const target = o.positional[1];
362
+ if (!target) {
363
+ console.error(`usage: keystone ${cmd} <${cmd === "calls" ? "함수" : "파일|함수"}>`);
364
+ return 2;
365
+ }
366
+ const { calls, trace } = buildCalls(o, project.graph.files);
367
+ if (cmd === "explain") {
368
+ if (o.down || o.up) {
369
+ console.log(treeReport(calls, target, { down: o.down, up: o.up, includeInferred: o.includeInferred, traceLoaded: !!trace }));
370
+ return 0;
371
+ }
372
+ console.log(explain(calls, project.graph, project.config, loadStore(o.root), target, { includeInferred: o.includeInferred }));
373
+ return 0;
374
+ }
375
+ const ids = findUnits(calls, target);
376
+ if (!ids.length) {
377
+ console.log(`'${target}'에 해당하는 함수를 찾지 못했습니다.`);
378
+ return 1;
379
+ }
380
+ if (o.json) {
381
+ console.log(JSON.stringify(ids.map((id) => ({ id, callers: calls.callers.get(id), callees: calls.callees.get(id), unresolved: calls.unresolved.filter((u) => u.from === id) })), null, 2));
382
+ return 0;
383
+ }
384
+ const isTestFile = isTestFor(project.config);
385
+ for (const id of ids) {
386
+ for (const line of renderCalls(calls, id, isTestFile, { includeInferred: o.includeInferred }))
387
+ console.log(line);
388
+ console.log();
389
+ }
390
+ return 0;
391
+ }
392
+ const changed = o.files ?? changedFiles(o.root, o.base);
393
+ if (cmd === "check") {
394
+ const useBase = !o.files && !o.strictPins;
395
+ const readBase = useBase ? baseReader(o.root, o.base) : undefined;
396
+ const store = loadStore(o.root);
397
+ const needCalls = project.config.traceability.length > 0 || store.relations.some((r) => r.mutability);
398
+ const calls = needCalls ? buildCallGraph(o.root, project.graph.files) : undefined;
399
+ const res = runCheck(project.config, project.graph, changed, { readBase, calls });
400
+ // 관계 카드 검사: pinned 관계가 사라졌나 / careful 관계의 끝점이 바뀌었나
401
+ let relFindings = [];
402
+ if (calls && store.relations.length) {
403
+ const changedUnits = new Set();
404
+ for (const f of changed.filter((x) => project.graph.importers.has(x))) {
405
+ const d = diffUnits(o.root, f, readBase);
406
+ d.changed.forEach((id) => changedUnits.add(id));
407
+ if (d.fileLevel)
408
+ calls.byFile.get(f)?.forEach((id) => changedUnits.add(id));
409
+ }
410
+ relFindings = checkRelations(store, calls, changedUnits);
411
+ }
412
+ const relFail = relFindings.some((f) => f.level === "error");
413
+ // 함수 입출력(시그니처) 변경: 바뀌었으면 호출하는 곳을 보여준다 (git 기준 내용이 있을 때만)
414
+ let sigFindings = [];
415
+ if (readBase) {
416
+ const diffs = diffSignatures(o.root, changed.filter((x) => project.graph.importers.has(x)), readBase);
417
+ if (diffs.length)
418
+ sigFindings = signatureFindings(o.root, diffs, calls ?? buildCallGraph(o.root, project.graph.files), readBase);
419
+ }
420
+ const sigFail = signatureFailed(sigFindings, project.config.signatures.failOn);
421
+ const failed = checkFailed(res, o.allowPinned) || relFail || sigFail;
422
+ if (o.json) {
423
+ console.log(JSON.stringify({ ok: !failed, ...res, relations: relFindings, signatures: sigFindings }, null, 2));
424
+ return failed ? 1 : 0;
425
+ }
426
+ for (const v of res.violations)
427
+ console.log(`✗ boundary ${v.file} → ${v.imports}${v.via ? `\n path: ${v.via.join(" → ")}` : ""}\n rule: ${v.rule}${v.reason ? ` (${v.reason})` : ""}`);
428
+ for (const t of res.trace)
429
+ console.log(`✗ trace ${t.file}:${t.line} [${t.code}] ${t.text}${t.reason ? `\n rule: ${t.reason}` : ""}`);
430
+ for (const p of res.pinnedChanges)
431
+ console.log(`${o.allowPinned ? "!" : "✗"} pinned ${p.file}${p.detail ? ` [${p.detail}]` : ""}\n pin: ${p.pattern}${p.reason ? ` (${p.reason})` : ""}`);
432
+ for (const c of res.cosmetic)
433
+ console.log(`ℹ pinned ${c.file} [${c.detail}] — 허용`);
434
+ for (const i of res.invariants) {
435
+ if (i.missing)
436
+ console.log(`✗ invariant "${i.name}": 검증 테스트가 하나도 없음 (keystone.yml의 tests 확인)`);
437
+ else
438
+ console.log(`ℹ invariant "${i.name}": ${i.triggeredBy.join(", ")} 변경 → 검증 테스트 ${i.tests.length}개: ${i.tests.join(", ")}`);
439
+ }
440
+ for (const line of renderSignatureFindings(sigFindings))
441
+ console.log(line);
442
+ for (const f of relFindings)
443
+ console.log(`${f.level === "error" ? "✗" : f.level === "warn" ? "!" : "ℹ"} relation ${f.id}\n ${f.message}`);
444
+ if (project.graph.unresolved.length)
445
+ console.log(`ℹ 해석하지 못한 동적 import ${project.graph.unresolved.length}건 (keystone map에서 확인)`);
446
+ console.log(failed ? `\nkeystone check: FAILED` : `\nkeystone check: ok (${changed.length} changed files)`);
447
+ return failed ? 1 : 0;
448
+ }
449
+ // test
450
+ const deleted = o.files ? [] : deletedFiles(o.root, o.base);
451
+ const precise = o.precise
452
+ ? (() => { const { calls, trace } = buildCalls(o, project.graph.files); return { calls, trace, readBase: o.files ? undefined : baseReader(o.root, o.base) }; })()
453
+ : undefined;
454
+ const sel = selectTests(project.config, project.graph, changed, { all: o.all, deleted, precise });
455
+ if (o.json) {
456
+ console.log(JSON.stringify(sel, null, 2));
457
+ if (o.list)
458
+ return 0;
459
+ }
460
+ else {
461
+ const cmp = sel.fileLevelCount !== undefined ? ` (정밀 모드: 파일 기준 ${sel.fileLevelCount}개 → ${sel.tests.length}개)` : "";
462
+ console.log(`keystone test: 변경 ${changed.length}개 → 테스트 ${sel.tests.length}개${sel.all ? " (전체)" : ""}${cmp}`);
463
+ for (const t of sel.tests)
464
+ console.log(` - ${t}\n ${sel.reasons[t]}`);
465
+ if (sel.untracked.length)
466
+ console.log(`\n⚠ 그래프 밖 변경 ${sel.untracked.length}건 (영향 추적 불가): ${sel.untracked.join(", ")}\n → 테스트에 영향을 준다면 keystone.yml의 links에 연결을 선언하거나, 무관하면 ignore에 추가하세요.`);
467
+ for (const n of sel.notes)
468
+ console.log(`ℹ ${n}`);
469
+ }
470
+ if (o.list || sel.tests.length === 0)
471
+ return 0;
472
+ const cmdline = project.config.test.command;
473
+ if (!cmdline) {
474
+ console.log("\n(keystone.yml에 test.command가 없어 실행하지 않음)");
475
+ return 0;
476
+ }
477
+ const full = cmdline.includes("{files}") ? cmdline.replace("{files}", sel.tests.join(" ")) : `${cmdline} ${sel.tests.join(" ")}`;
478
+ return spawnSync(full, { cwd: o.root, shell: true, stdio: "inherit" }).status ?? 1;
479
+ }
480
+ try {
481
+ process.exit(main());
482
+ }
483
+ catch (e) {
484
+ console.error(`keystone: ${e.message}`);
485
+ process.exit(2);
486
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
- {
2
- "name": "keystone-relation",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "keystone-relation",
3
+ "version": "0.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": "^0.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
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.