keystone-relation 0.0.0-stage → 0.2.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 +21 -0
- package/dist/graph-cmd.d.ts +19 -0
- package/dist/graph-cmd.js +63 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +738 -0
- package/package.json +51 -6
- package/README.md +0 -3
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
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,738 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { getHeapStatistics } from "node:v8";
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
import picomatch from "picomatch";
|
|
7
|
+
import { computeDiff, graphCmd } from "./graph-cmd.js";
|
|
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";
|
|
9
|
+
// 큰 프로젝트에서 메모리 부족으로 죽지 않도록, 기본 한도가 낮으면 한도를 올려 자기 자신을 다시 실행한다.
|
|
10
|
+
{
|
|
11
|
+
const limitMb = getHeapStatistics().heap_size_limit / 1048576;
|
|
12
|
+
if (limitMb < 4000 && !process.env.KEYSTONE_HEAP_SET) {
|
|
13
|
+
const r = spawnSync(process.execPath, ["--max-old-space-size=8192", ...process.argv.slice(1)], { stdio: "inherit", env: { ...process.env, KEYSTONE_HEAP_SET: "1" } });
|
|
14
|
+
process.exit(r.status ?? 1);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const USAGE = `usage: keystone <command> [options]
|
|
18
|
+
|
|
19
|
+
처음이라면: "keystone init --all" 한 번으로 준비. 그 뒤엔 명령 3개면 충분해요:
|
|
20
|
+
keystone explain <함수> --down 2 이 함수가 어떻게 흘러가는지 (실행 흐름 파악)
|
|
21
|
+
keystone calls <함수> 누가 부르고 무엇을 부르는지 (같은 이름 함수도 구분)
|
|
22
|
+
keystone before-edit <함수|파일> 고치기 전에: 영향 범위·테스트·보호된 곳 확인
|
|
23
|
+
(고친 뒤: keystone graph diff = 사라진/바뀐 관계 확인, keystone test --precise = 영향받는 테스트만)
|
|
24
|
+
|
|
25
|
+
commands:
|
|
26
|
+
hook init Claude Code가 파일을 고치기 직전에 before-edit을 자동으로 보여 주는 설정 예시 출력 (파일은 안 건드림)
|
|
27
|
+
before-edit <함수|파일> 고치기 전 확인 (영향 범위, 관련 테스트, pinned/관계 카드, 추정 연결)
|
|
28
|
+
check 경계 규칙 + pinned + 불변조건 + 추적성 + 관계 카드 검사
|
|
29
|
+
test 변경 파일의 영향을 받는 테스트만 실행
|
|
30
|
+
map 구조 지도(목차) 출력
|
|
31
|
+
explain <파일|함수> 코드 이해용 설명: 누가 부르나/무엇을 부르나/영향 범위/모르는 호출/관계 카드
|
|
32
|
+
--down N: 이 함수가 부르는 것을 N단계 아래까지 나무로 펼침(실행 흐름 파악용)
|
|
33
|
+
--up N: 이 함수를 부르는 곳을 N단계 위까지 펼침
|
|
34
|
+
calls <함수> 이 함수를 부르는 곳과 이 함수가 부르는 곳의 목록 (줄 번호 포함). 함수 이름만 써도 됨
|
|
35
|
+
trace -- <명령> 테스트(또는 아무 명령)를 실제로 실행하면서 일어난 호출을 기록 (예: keystone trace -- npm test). 기록은 calls/explain/test에 자동 반영
|
|
36
|
+
trace show 저장된 실행 기록 요약
|
|
37
|
+
ci init PR/병합 때 자동으로 돌리는 GitHub Actions 설정 파일 생성 (--test-command, --cli, --out)
|
|
38
|
+
graph <sub> 관계 변화 비교 (snapshot | diff): 사라진 관계 / 새 관계 / 이름 변경
|
|
39
|
+
relations <sub> 관계 카드 관리 (scan | list | show | set | add | propose | approve | reject | prune)
|
|
40
|
+
|
|
41
|
+
공통 options:
|
|
42
|
+
--root <dir> 프로젝트 루트 (기본: 현재 디렉토리)
|
|
43
|
+
--base <ref> 이 git ref 대비 변경 파일 사용 (기본: HEAD)
|
|
44
|
+
--files a,b,c git 대신 변경 파일을 직접 지정
|
|
45
|
+
--json JSON 출력
|
|
46
|
+
check: --strict-pins (pin을 바이트 단위로) · --allow-pinned (pinned 변경을 경고로)
|
|
47
|
+
test: --precise (함수 단위 정밀 선택) · --all (전체) · --list (실행 없이 선택 결과만)
|
|
48
|
+
relations scan: --min-blast N (새 카드 기준, 기본 3) · --all (모든 관계 저장) · --same-file · --follow-renames (이름만 바뀐 관계는 카드를 옮김, --base 기준)
|
|
49
|
+
graph diff: --base <ref> · --include-inferred · --include-tests · --fail (pinned 관계 손실/경계 위반이면 exit 1) · --json
|
|
50
|
+
relations list: --status active|stale · --importance core|high|normal|low · --unreviewed · --proposals
|
|
51
|
+
relations set <id> key=value ... (${HUMAN_FIELDS.join(", ")})
|
|
52
|
+
type=${RELATION_TYPES.join("|")}
|
|
53
|
+
importance=${IMPORTANCE.join("|")} mutability=${MUTABILITY.join("|")}
|
|
54
|
+
relations propose <id> key=value ... [--by 이름] [--note 메모] 에이전트용: 적용하지 않고 제안으로만 저장
|
|
55
|
+
relations add <from> <to> key=value ... 자동으로 못 찾는 숨은 연결을 직접 추가`;
|
|
56
|
+
function parseArgs(argv0) {
|
|
57
|
+
// `keystone trace -- npm test` : -- 뒤는 실행할 명령이다
|
|
58
|
+
const dd = argv0.indexOf("--");
|
|
59
|
+
const argv = dd >= 0 ? argv0.slice(0, dd) : argv0;
|
|
60
|
+
const traceCommand = dd >= 0 ? argv0.slice(dd + 1).join(" ") : "";
|
|
61
|
+
const o = { root: process.cwd(), positional: [], strictPins: false, allowPinned: false, all: false, precise: false, list: false, json: false,
|
|
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 };
|
|
63
|
+
for (let i = 0; i < argv.length; i++) {
|
|
64
|
+
const a = argv[i];
|
|
65
|
+
const val = () => { if (i + 1 >= argv.length) {
|
|
66
|
+
console.error(`${a}: 값이 필요합니다`);
|
|
67
|
+
process.exit(2);
|
|
68
|
+
} return argv[++i]; };
|
|
69
|
+
if (a === "--root")
|
|
70
|
+
o.root = resolve(val());
|
|
71
|
+
else if (a === "--base")
|
|
72
|
+
o.base = val();
|
|
73
|
+
else if (a === "--files")
|
|
74
|
+
o.files = val().split(",").filter(Boolean);
|
|
75
|
+
else if (a === "--strict-pins")
|
|
76
|
+
o.strictPins = true;
|
|
77
|
+
else if (a === "--allow-pinned")
|
|
78
|
+
o.allowPinned = true;
|
|
79
|
+
else if (a === "--all")
|
|
80
|
+
o.all = true;
|
|
81
|
+
else if (a === "--precise")
|
|
82
|
+
o.precise = true;
|
|
83
|
+
else if (a === "--list")
|
|
84
|
+
o.list = true;
|
|
85
|
+
else if (a === "--json")
|
|
86
|
+
o.json = true;
|
|
87
|
+
else if (a === "--min-blast")
|
|
88
|
+
o.minBlast = Number(val());
|
|
89
|
+
else if (a === "--no-trace")
|
|
90
|
+
o.noTrace = true;
|
|
91
|
+
else if (a === "--keep")
|
|
92
|
+
o.keep = true;
|
|
93
|
+
else if (a === "--test-command")
|
|
94
|
+
o.testCommand = val();
|
|
95
|
+
else if (a === "--cli")
|
|
96
|
+
o.cliCmd = val();
|
|
97
|
+
else if (a === "--down")
|
|
98
|
+
o.down = Number(val());
|
|
99
|
+
else if (a === "--up")
|
|
100
|
+
o.up = Number(val());
|
|
101
|
+
else if (a === "--same-file")
|
|
102
|
+
o.sameFile = true;
|
|
103
|
+
else if (a === "--out")
|
|
104
|
+
o.out = val();
|
|
105
|
+
else if (a === "--include-inferred")
|
|
106
|
+
o.includeInferred = true;
|
|
107
|
+
else if (a === "--include-tests")
|
|
108
|
+
o.includeTests = true;
|
|
109
|
+
else if (a === "--fail")
|
|
110
|
+
o.fail = true;
|
|
111
|
+
else if (a === "--follow-renames")
|
|
112
|
+
o.followRenames = true;
|
|
113
|
+
else if (a === "--status")
|
|
114
|
+
o.status = val();
|
|
115
|
+
else if (a === "--importance")
|
|
116
|
+
o.importance = val();
|
|
117
|
+
else if (a === "--unreviewed")
|
|
118
|
+
o.unreviewed = true;
|
|
119
|
+
else if (a === "--proposals")
|
|
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());
|
|
133
|
+
else if (a === "--by")
|
|
134
|
+
o.by = val();
|
|
135
|
+
else if (a === "--note")
|
|
136
|
+
o.note = val();
|
|
137
|
+
else if (!a.startsWith("--"))
|
|
138
|
+
o.positional.push(a);
|
|
139
|
+
else {
|
|
140
|
+
console.error(`unknown option: ${a}\n\n${USAGE}`);
|
|
141
|
+
process.exit(2);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
o.traceCommand = traceCommand;
|
|
145
|
+
return o;
|
|
146
|
+
}
|
|
147
|
+
/** 호출 그래프를 만들고, 실행 기록(keystone trace)이 있으면 합친다 */
|
|
148
|
+
function buildCalls(o, files) {
|
|
149
|
+
const { graph: calls, cached } = buildCallGraphCached(o.root, files);
|
|
150
|
+
if (cached && !o.json)
|
|
151
|
+
console.error("ℹ 코드가 그대로라서 저장해 둔 분석 결과를 불러왔어요.");
|
|
152
|
+
const trace = o.noTrace ? null : loadTrace(o.root);
|
|
153
|
+
if (trace) {
|
|
154
|
+
const r = applyTrace(calls, trace);
|
|
155
|
+
if (!o.json)
|
|
156
|
+
console.error(`ℹ 실행 기록(${trace.createdAt.slice(0, 10)}, \`${trace.command}\`)을 반영했어요: 실제로 확인된 호출 ${r.matched}건, 코드 읽기로 못 찾은 호출 ${r.added}건 추가${r.stale ? `, 코드가 바뀌어 맞지 않는 옛 기록 ${r.stale}건 제외` : ""}. (끄려면 --no-trace)`);
|
|
157
|
+
}
|
|
158
|
+
return { calls, trace };
|
|
159
|
+
}
|
|
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 를 돌려 실패하면 에이전트에게 알려 줌 */
|
|
171
|
+
function hookCmd(o) {
|
|
172
|
+
const sub = o.positional[1];
|
|
173
|
+
if (sub === "init") {
|
|
174
|
+
console.log("아래를 프로젝트의 .claude/settings.json 에 넣으세요 (또는 `keystone init --hook` 으로 자동 병합):\n");
|
|
175
|
+
console.log(JSON.stringify(hookSettings(), null, 2));
|
|
176
|
+
console.log("\n설명: 세션 시작 때 보호 규칙을 알려 주고, 파일을 고치기 직전에 영향 범위를, 고친 직후에 검사 결과를 알려 줍니다. 작업을 막지는 않고 알려 주기만 해요.");
|
|
177
|
+
return 0;
|
|
178
|
+
}
|
|
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;
|
|
189
|
+
}
|
|
190
|
+
if (sub === "run") {
|
|
191
|
+
const inp = JSON.parse(readStdin() || "{}");
|
|
192
|
+
const fp = inp.tool_input?.file_path;
|
|
193
|
+
if (!fp)
|
|
194
|
+
return 0;
|
|
195
|
+
const rel = relPath(o.root, fp);
|
|
196
|
+
const project = loadProject(o.root);
|
|
197
|
+
if (!project.graph.files.includes(rel))
|
|
198
|
+
return 0;
|
|
199
|
+
const { calls } = buildCalls({ ...o, json: true }, project.graph.files);
|
|
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;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
return 0;
|
|
244
|
+
} // 훅은 절대 작업을 막지 않는다
|
|
245
|
+
console.error("usage: keystone hook <init|session|run|post>");
|
|
246
|
+
return 2;
|
|
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
|
+
}
|
|
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}?)`}` +
|
|
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}` : ""}` : ""}`;
|
|
383
|
+
function relationsCmd(o) {
|
|
384
|
+
const [, sub, ...rest] = o.positional;
|
|
385
|
+
const project = loadProject(o.root);
|
|
386
|
+
const store = loadStore(o.root);
|
|
387
|
+
const isTest = picomatch(project.config.tests, { dot: true });
|
|
388
|
+
if (sub === "scan") {
|
|
389
|
+
const calls = buildCallGraph(o.root, project.graph.files);
|
|
390
|
+
const renames = o.followRenames ? renameMapOf(computeDiff(o)) : undefined;
|
|
391
|
+
const rep = scanRelations(store, calls, project.config, (f) => isTest(f), { minBlast: o.minBlast, all: o.all, includeSameFile: o.sameFile, renames });
|
|
392
|
+
saveStore(o.root, store);
|
|
393
|
+
console.log(`keystone relations scan: 새 카드 ${rep.added.length} · 갱신 ${rep.refreshed} · 낡음 ${rep.stale.length} · 되살아남 ${rep.revived.length} (후보 ${rep.candidates})`);
|
|
394
|
+
for (const id of rep.added.slice(0, 15))
|
|
395
|
+
console.log(` + ${id}`);
|
|
396
|
+
if (rep.added.length > 15)
|
|
397
|
+
console.log(` … 외 ${rep.added.length - 15}개`);
|
|
398
|
+
for (const m of rep.moved)
|
|
399
|
+
console.log(` ↦ 이름 변경 따라감: ${m.from}\n → ${m.to}`);
|
|
400
|
+
for (const id of rep.stale)
|
|
401
|
+
console.log(` ✗ 낡음: ${id}`);
|
|
402
|
+
console.log(`\n저장: .keystone/relations.yml — 사람이 쓴 필드(${HUMAN_FIELDS.join(", ")})는 다시 스캔해도 보존됩니다.`);
|
|
403
|
+
return 0;
|
|
404
|
+
}
|
|
405
|
+
if (sub === "list") {
|
|
406
|
+
let rels = store.relations;
|
|
407
|
+
if (o.status)
|
|
408
|
+
rels = rels.filter((r) => r.status === o.status);
|
|
409
|
+
if (o.importance)
|
|
410
|
+
rels = rels.filter((r) => (r.importance ?? r.importanceHint) === o.importance);
|
|
411
|
+
if (o.unreviewed)
|
|
412
|
+
rels = rels.filter((r) => !r.reviewed);
|
|
413
|
+
if (o.proposals)
|
|
414
|
+
rels = rels.filter((r) => r.proposal);
|
|
415
|
+
if (o.json) {
|
|
416
|
+
console.log(JSON.stringify(rels, null, 2));
|
|
417
|
+
return 0;
|
|
418
|
+
}
|
|
419
|
+
console.log(`관계 카드 ${rels.length}개 (전체 ${store.relations.length}) — ✓검토됨 · 미검토 ✗낡음 / (?)는 자동 추정`);
|
|
420
|
+
for (const r of rels)
|
|
421
|
+
console.log(relLine(r));
|
|
422
|
+
return 0;
|
|
423
|
+
}
|
|
424
|
+
if (sub === "show") {
|
|
425
|
+
const r = findRelation(store, rest[0] ?? "");
|
|
426
|
+
console.log(JSON.stringify(r, null, 2));
|
|
427
|
+
return 0;
|
|
428
|
+
}
|
|
429
|
+
if (sub === "set") {
|
|
430
|
+
const r = findRelation(store, rest[0] ?? "");
|
|
431
|
+
editRelation(r, parseAssignments(rest.slice(1)));
|
|
432
|
+
saveStore(o.root, store);
|
|
433
|
+
console.log("적용됨:\n" + relLine(r));
|
|
434
|
+
return 0;
|
|
435
|
+
}
|
|
436
|
+
if (sub === "propose") {
|
|
437
|
+
const r = findRelation(store, rest[0] ?? "");
|
|
438
|
+
proposeChange(r, o.by, parseAssignments(rest.slice(1)), o.note);
|
|
439
|
+
saveStore(o.root, store);
|
|
440
|
+
console.log(`제안으로 저장됨 (적용되지 않음, 사람이 approve 해야 함):\n` + relLine(r));
|
|
441
|
+
return 0;
|
|
442
|
+
}
|
|
443
|
+
if (sub === "approve") {
|
|
444
|
+
const r = findRelation(store, rest[0] ?? "");
|
|
445
|
+
approveProposal(r);
|
|
446
|
+
saveStore(o.root, store);
|
|
447
|
+
console.log("승인되어 적용됨:\n" + relLine(r));
|
|
448
|
+
return 0;
|
|
449
|
+
}
|
|
450
|
+
if (sub === "reject") {
|
|
451
|
+
const r = findRelation(store, rest[0] ?? "");
|
|
452
|
+
rejectProposal(r);
|
|
453
|
+
saveStore(o.root, store);
|
|
454
|
+
console.log("제안을 거절했습니다");
|
|
455
|
+
return 0;
|
|
456
|
+
}
|
|
457
|
+
if (sub === "add") {
|
|
458
|
+
const [from, to, ...kv] = rest;
|
|
459
|
+
if (!from || !to)
|
|
460
|
+
throw new Error("usage: keystone relations add <from> <to> key=value ...");
|
|
461
|
+
const r = addManualRelation(store, from, to, parseAssignments(kv));
|
|
462
|
+
saveStore(o.root, store);
|
|
463
|
+
console.log("추가됨:\n" + relLine(r));
|
|
464
|
+
return 0;
|
|
465
|
+
}
|
|
466
|
+
if (sub === "prune") {
|
|
467
|
+
const before = store.relations.length;
|
|
468
|
+
store.relations = store.relations.filter((r) => !(r.status === "stale" && r.mutability !== "pinned" && !r.reviewed));
|
|
469
|
+
saveStore(o.root, store);
|
|
470
|
+
console.log(`낡은 미검토 카드 ${before - store.relations.length}개 삭제 (pinned/검토된 카드는 유지)`);
|
|
471
|
+
return 0;
|
|
472
|
+
}
|
|
473
|
+
console.error(`relations: 알 수 없는 하위 명령 '${sub ?? ""}'\n\n${USAGE}`);
|
|
474
|
+
return 2;
|
|
475
|
+
}
|
|
476
|
+
function ciCmd(o) {
|
|
477
|
+
if (o.positional[1] !== "init") {
|
|
478
|
+
console.error("usage: keystone ci init [--test-command \"npm test\"] [--cli \"npx keystone-relation\"] [--out .github/workflows/keystone.yml]");
|
|
479
|
+
return 2;
|
|
480
|
+
}
|
|
481
|
+
const project = loadProject(o.root);
|
|
482
|
+
const out = resolve(o.root, o.out ?? ".github/workflows/keystone.yml");
|
|
483
|
+
const testCommand = o.testCommand ?? project.config.test.command ?? "npm test";
|
|
484
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
485
|
+
writeFileSync(out, renderCiWorkflow({ testCommand, cli: o.cliCmd }));
|
|
486
|
+
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로 실행 경로를 지정했는지 확인하세요.`);
|
|
487
|
+
return 0;
|
|
488
|
+
}
|
|
489
|
+
function traceCmd(o) {
|
|
490
|
+
const sub = o.positional[1];
|
|
491
|
+
if (sub === "show") {
|
|
492
|
+
const t = loadTrace(o.root, o.out ?? TRACE_PATH);
|
|
493
|
+
if (!t) {
|
|
494
|
+
console.log("저장된 실행 기록이 없어요. keystone trace -- <테스트 명령> 으로 먼저 기록하세요.");
|
|
495
|
+
return 1;
|
|
496
|
+
}
|
|
497
|
+
const top = Object.entries(t.executed).sort((a, b) => b[1] - a[1]).slice(0, 10);
|
|
498
|
+
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 가장 많이 실행된 함수:`);
|
|
499
|
+
for (const [id, c] of top)
|
|
500
|
+
console.log(` ${String(c).padStart(8)}회 ${id}`);
|
|
501
|
+
return 0;
|
|
502
|
+
}
|
|
503
|
+
const project = loadProject(o.root);
|
|
504
|
+
const command = o.traceCommand || project.config.test.command;
|
|
505
|
+
if (!command) {
|
|
506
|
+
console.error("실행할 명령이 없어요. `keystone trace -- npm test` 처럼 -- 뒤에 테스트 명령을 쓰거나, keystone.yml의 test.command를 설정하세요.");
|
|
507
|
+
return 2;
|
|
508
|
+
}
|
|
509
|
+
console.log(`실행 기록을 시작합니다: 프로젝트를 임시 폴더로 복사하고, 함수마다 기록 코드를 끼워 넣은 뒤 \`${command}\` 를 실행해요 (원본은 바뀌지 않아요).`);
|
|
510
|
+
const r = runTrace(o.root, { command, testGlobs: project.config.tests, keep: o.keep });
|
|
511
|
+
const path = saveTrace(o.root, r.data, o.out ?? TRACE_PATH);
|
|
512
|
+
console.log(`\n실행 기록 저장: ${path}\n 기록 코드를 끼운 함수 ${r.instrumentedFunctions}개 (파일 ${r.instrumentedFiles}개) · 실제로 실행된 함수 ${Object.keys(r.data.executed).length}개 · 호출 관계 ${r.data.edges.length}개 · 기록한 프로세스 ${r.processes}개 · 명령 종료코드 ${r.data.exitCode}`);
|
|
513
|
+
if (!r.processes)
|
|
514
|
+
console.log("⚠ 기록이 하나도 없어요. 명령이 Node.js로 실행되는지(예: npm test → node/vitest/jest) 확인하세요.");
|
|
515
|
+
if (r.workDir)
|
|
516
|
+
console.log(` (복사본 보관: ${r.workDir})`);
|
|
517
|
+
console.log("이제 `keystone calls <함수>`, `keystone explain <함수> --down 3`, `keystone test --precise` 가 이 기록을 자동으로 반영해요.");
|
|
518
|
+
return r.data.exitCode ?? 1;
|
|
519
|
+
}
|
|
520
|
+
function main() {
|
|
521
|
+
const o = parseArgs(process.argv.slice(2));
|
|
522
|
+
const cmd = o.positional[0];
|
|
523
|
+
if (!cmd || !["check", "test", "map", "explain", "calls", "before-edit", "hook", "init", "stats", "feedback", "relations", "graph", "trace", "ci"].includes(cmd)) {
|
|
524
|
+
console.log(USAGE);
|
|
525
|
+
return cmd ? 2 : 0;
|
|
526
|
+
}
|
|
527
|
+
if (cmd === "hook")
|
|
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);
|
|
535
|
+
if (cmd === "relations")
|
|
536
|
+
return relationsCmd(o);
|
|
537
|
+
if (cmd === "graph")
|
|
538
|
+
return graphCmd(o);
|
|
539
|
+
if (cmd === "ci")
|
|
540
|
+
return ciCmd(o);
|
|
541
|
+
if (cmd === "trace")
|
|
542
|
+
return traceCmd(o);
|
|
543
|
+
const project = loadProject(o.root);
|
|
544
|
+
if (!project.configFound && !o.json)
|
|
545
|
+
console.error(`ℹ ${MISSING_CONFIG_HINT}`);
|
|
546
|
+
if (cmd === "map") {
|
|
547
|
+
console.log(renderMap(project.config, project.graph));
|
|
548
|
+
return 0;
|
|
549
|
+
}
|
|
550
|
+
if (cmd === "before-edit") {
|
|
551
|
+
const target = o.positional[1];
|
|
552
|
+
if (!target) {
|
|
553
|
+
console.error("usage: keystone before-edit <함수|파일>");
|
|
554
|
+
return 2;
|
|
555
|
+
}
|
|
556
|
+
const { calls } = buildCalls(o, project.graph.files);
|
|
557
|
+
console.log(beforeEdit(calls, project.config, loadStore(o.root), target));
|
|
558
|
+
logEvent(o.root, { kind: "before-edit", target, by: "cli" });
|
|
559
|
+
return 0;
|
|
560
|
+
}
|
|
561
|
+
if (cmd === "explain" || cmd === "calls") {
|
|
562
|
+
const target = o.positional[1];
|
|
563
|
+
if (!target) {
|
|
564
|
+
console.error(`usage: keystone ${cmd} <${cmd === "calls" ? "함수" : "파일|함수"}>`);
|
|
565
|
+
return 2;
|
|
566
|
+
}
|
|
567
|
+
const { calls, trace } = buildCalls(o, project.graph.files);
|
|
568
|
+
if (cmd === "explain") {
|
|
569
|
+
if (o.down || o.up) {
|
|
570
|
+
console.log(treeReport(calls, target, { down: o.down, up: o.up, includeInferred: o.includeInferred, traceLoaded: !!trace }));
|
|
571
|
+
return 0;
|
|
572
|
+
}
|
|
573
|
+
console.log(explain(calls, project.graph, project.config, loadStore(o.root), target, { includeInferred: o.includeInferred }));
|
|
574
|
+
return 0;
|
|
575
|
+
}
|
|
576
|
+
const ids = findUnits(calls, target);
|
|
577
|
+
if (!ids.length) {
|
|
578
|
+
console.log(`'${target}'에 해당하는 함수를 찾지 못했습니다.`);
|
|
579
|
+
return 1;
|
|
580
|
+
}
|
|
581
|
+
if (o.json) {
|
|
582
|
+
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));
|
|
583
|
+
return 0;
|
|
584
|
+
}
|
|
585
|
+
const isTestFile = isTestFor(project.config);
|
|
586
|
+
for (const id of ids) {
|
|
587
|
+
for (const line of renderCalls(calls, id, isTestFile, { includeInferred: o.includeInferred }))
|
|
588
|
+
console.log(line);
|
|
589
|
+
console.log();
|
|
590
|
+
}
|
|
591
|
+
return 0;
|
|
592
|
+
}
|
|
593
|
+
const changed = o.files ?? changedFiles(o.root, o.base);
|
|
594
|
+
if (cmd === "check") {
|
|
595
|
+
const useBase = !o.files && !o.strictPins;
|
|
596
|
+
const readBase = useBase ? baseReader(o.root, o.base) : undefined;
|
|
597
|
+
const store = loadStore(o.root);
|
|
598
|
+
const needCalls = project.config.traceability.length > 0 || store.relations.some((r) => r.mutability);
|
|
599
|
+
const calls = needCalls ? buildCallGraph(o.root, project.graph.files) : undefined;
|
|
600
|
+
const res = runCheck(project.config, project.graph, changed, { readBase, calls });
|
|
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)
|
|
613
|
+
let relFindings = [];
|
|
614
|
+
const changedUnits = new Set();
|
|
615
|
+
if (calls && store.relations.length) {
|
|
616
|
+
for (const f of changed.filter((x) => project.graph.importers.has(x))) {
|
|
617
|
+
const d = diffUnits(o.root, f, readBase);
|
|
618
|
+
d.changed.forEach((id) => changedUnits.add(id));
|
|
619
|
+
if (d.fileLevel)
|
|
620
|
+
calls.byFile.get(f)?.forEach((id) => changedUnits.add(id));
|
|
621
|
+
}
|
|
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
|
+
}
|
|
638
|
+
}
|
|
639
|
+
const relFail = relFindings.some((f) => f.level === "error");
|
|
640
|
+
// 함수 입출력(시그니처) 변경: 바뀌었으면 호출하는 곳을 보여준다 (git 기준 내용이 있을 때만)
|
|
641
|
+
let sigFindings = [];
|
|
642
|
+
if (readBase) {
|
|
643
|
+
const diffs = diffSignatures(o.root, changed.filter((x) => project.graph.importers.has(x)), readBase);
|
|
644
|
+
if (diffs.length)
|
|
645
|
+
sigFindings = signatureFindings(o.root, diffs, calls ?? buildCallGraph(o.root, project.graph.files), readBase);
|
|
646
|
+
}
|
|
647
|
+
const sigFail = signatureFailed(sigFindings, project.config.signatures.failOn);
|
|
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}`) : [];
|
|
659
|
+
if (o.json) {
|
|
660
|
+
console.log(JSON.stringify({ ok: !failed, verdict, ...res, relations: relFindings, signatures: sigFindings, ...(overridden ? { overridden: o.reason } : {}) }, null, 2));
|
|
661
|
+
return failed ? 1 : 0;
|
|
662
|
+
}
|
|
663
|
+
// 첫 줄에 판정을 둔다 (자세한 근거는 아래)
|
|
664
|
+
console.log(verdict === "OK" ? `keystone check: OK (${changed.length}개 파일 변경)` : `keystone check: ${verdict}${parts.length ? ` — ${parts.join(" · ")}` : ""}${overridden ? ` (알고도 진행: ${o.reason})` : ""}`);
|
|
665
|
+
for (const v of res.violations)
|
|
666
|
+
console.log(`✗ boundary ${v.file} → ${v.imports}${v.via ? `\n path: ${v.via.join(" → ")}` : ""}\n rule: ${v.rule}${v.reason ? ` (${v.reason})` : ""}`);
|
|
667
|
+
for (const t of res.trace)
|
|
668
|
+
console.log(`✗ trace ${t.file}:${t.line} [${t.code}] ${t.text}${t.reason ? `\n rule: ${t.reason}` : ""}`);
|
|
669
|
+
for (const p of res.pinnedChanges)
|
|
670
|
+
console.log(`${o.allowPinned ? "!" : "✗"} pinned ${p.file}${p.detail ? ` [${p.detail}]` : ""}\n pin: ${p.pattern}${p.reason ? ` (${p.reason})` : ""}`);
|
|
671
|
+
for (const c of res.cosmetic)
|
|
672
|
+
console.log(`ℹ pinned ${c.file} [${c.detail}] — 허용`);
|
|
673
|
+
for (const i of res.invariants) {
|
|
674
|
+
if (i.missing)
|
|
675
|
+
console.log(`✗ invariant "${i.name}": 검증 테스트가 하나도 없음 (keystone.yml의 tests 확인)`);
|
|
676
|
+
else
|
|
677
|
+
console.log(`ℹ invariant "${i.name}": ${i.triggeredBy.join(", ")} 변경 → 검증 테스트 ${i.tests.length}개: ${i.tests.join(", ")}`);
|
|
678
|
+
}
|
|
679
|
+
for (const line of renderSignatureFindings(sigFindings))
|
|
680
|
+
console.log(line);
|
|
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
|
+
}
|
|
685
|
+
if (project.graph.unresolved.length)
|
|
686
|
+
console.log(`ℹ 해석하지 못한 동적 import ${project.graph.unresolved.length}건 (keystone map에서 확인)`);
|
|
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(", ")}`);
|
|
693
|
+
return failed ? 1 : 0;
|
|
694
|
+
}
|
|
695
|
+
// test
|
|
696
|
+
const deleted = o.files ? [] : deletedFiles(o.root, o.base);
|
|
697
|
+
const precise = o.precise
|
|
698
|
+
? (() => { const { calls, trace } = buildCalls(o, project.graph.files); return { calls, trace, readBase: o.files ? undefined : baseReader(o.root, o.base) }; })()
|
|
699
|
+
: undefined;
|
|
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
|
+
}
|
|
707
|
+
if (o.json) {
|
|
708
|
+
console.log(JSON.stringify(sel, null, 2));
|
|
709
|
+
if (o.list)
|
|
710
|
+
return 0;
|
|
711
|
+
}
|
|
712
|
+
else {
|
|
713
|
+
const cmp = sel.fileLevelCount !== undefined ? ` (정밀 모드: 파일 기준 ${sel.fileLevelCount}개 → ${sel.tests.length}개)` : "";
|
|
714
|
+
console.log(`keystone test: 변경 ${changed.length}개 → 테스트 ${sel.tests.length}개${sel.all ? " (전체)" : ""}${cmp}`);
|
|
715
|
+
for (const t of sel.tests)
|
|
716
|
+
console.log(` - ${t}\n ${sel.reasons[t]}`);
|
|
717
|
+
if (sel.untracked.length)
|
|
718
|
+
console.log(`\n⚠ 그래프 밖 변경 ${sel.untracked.length}건 (영향 추적 불가): ${sel.untracked.join(", ")}\n → 테스트에 영향을 준다면 keystone.yml의 links에 연결을 선언하거나, 무관하면 ignore에 추가하세요.`);
|
|
719
|
+
for (const n of sel.notes)
|
|
720
|
+
console.log(`ℹ ${n}`);
|
|
721
|
+
}
|
|
722
|
+
if (o.list || sel.tests.length === 0)
|
|
723
|
+
return 0;
|
|
724
|
+
const cmdline = project.config.test.command;
|
|
725
|
+
if (!cmdline) {
|
|
726
|
+
console.log("\n(keystone.yml에 test.command가 없어 실행하지 않음)");
|
|
727
|
+
return 0;
|
|
728
|
+
}
|
|
729
|
+
const full = cmdline.includes("{files}") ? cmdline.replace("{files}", sel.tests.join(" ")) : `${cmdline} ${sel.tests.join(" ")}`;
|
|
730
|
+
return spawnSync(full, { cwd: o.root, shell: true, stdio: "inherit" }).status ?? 1;
|
|
731
|
+
}
|
|
732
|
+
try {
|
|
733
|
+
process.exit(main());
|
|
734
|
+
}
|
|
735
|
+
catch (e) {
|
|
736
|
+
console.error(`keystone: ${e.message}`);
|
|
737
|
+
process.exit(2);
|
|
738
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "keystone-relation",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "keystone-relation",
|
|
3
|
+
"version": "0.2.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.2.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