triflux 3.2.0-dev.2 → 3.2.0-dev.5

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.
@@ -0,0 +1,234 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawnSync } from "node:child_process";
3
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import test from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { compileRules, loadRules, matchRules, resolveConflicts } from "../lib/keyword-rules.mjs";
9
+
10
+ const __dirname = dirname(fileURLToPath(import.meta.url));
11
+ const projectRoot = resolve(__dirname, "..", "..");
12
+ const rulesPath = join(projectRoot, "hooks", "keyword-rules.json");
13
+ const detectorScriptPath = join(projectRoot, "scripts", "keyword-detector.mjs");
14
+
15
+ // keyword-detector는 import 시 main()이 실행되므로, 테스트 로딩 단계에서만 안전하게 비활성화한다.
16
+ const previousDisable = process.env.TRIFLUX_DISABLE_MAGICWORDS;
17
+ const previousLog = console.log;
18
+ process.env.TRIFLUX_DISABLE_MAGICWORDS = "1";
19
+ console.log = () => {};
20
+ const detectorModule = await import("../keyword-detector.mjs");
21
+ console.log = previousLog;
22
+ if (previousDisable === undefined) {
23
+ delete process.env.TRIFLUX_DISABLE_MAGICWORDS;
24
+ } else {
25
+ process.env.TRIFLUX_DISABLE_MAGICWORDS = previousDisable;
26
+ }
27
+
28
+ const { extractPrompt, sanitizeForKeywordDetection } = detectorModule;
29
+
30
+ function loadCompiledRules() {
31
+ const rules = loadRules(rulesPath);
32
+ assert.equal(rules.length, 19);
33
+ return compileRules(rules);
34
+ }
35
+
36
+ function runDetector(prompt) {
37
+ const payload = { prompt, cwd: projectRoot };
38
+ const result = spawnSync(process.execPath, [detectorScriptPath], {
39
+ input: JSON.stringify(payload),
40
+ encoding: "utf8"
41
+ });
42
+
43
+ assert.equal(result.status, 0, result.stderr);
44
+ assert.ok(result.stdout.trim(), "keyword-detector 출력이 비어 있습니다.");
45
+ return JSON.parse(result.stdout.trim());
46
+ }
47
+
48
+ test("extractPrompt: prompt/message.content/parts[].text 우선순위", () => {
49
+ assert.equal(
50
+ extractPrompt({
51
+ prompt: "from prompt",
52
+ message: { content: "from message" },
53
+ parts: [{ text: "from parts" }]
54
+ }),
55
+ "from prompt"
56
+ );
57
+
58
+ assert.equal(
59
+ extractPrompt({
60
+ prompt: " ",
61
+ message: { content: "from message" },
62
+ parts: [{ text: "from parts" }]
63
+ }),
64
+ "from message"
65
+ );
66
+
67
+ assert.equal(
68
+ extractPrompt({
69
+ message: { content: [{ text: "from message-part" }] },
70
+ parts: [{ text: "from parts" }]
71
+ }),
72
+ "from message-part"
73
+ );
74
+
75
+ assert.equal(extractPrompt({ parts: [{ text: "from parts" }] }), "from parts");
76
+ });
77
+
78
+ test("sanitizeForKeywordDetection: 코드블록/URL/파일경로/XML 태그 제거", () => {
79
+ const input = [
80
+ "정상 문장",
81
+ "```sh",
82
+ "tfx team",
83
+ "```",
84
+ "https://example.com/path?q=1",
85
+ "C:\\Users\\SSAFY\\Desktop\\Projects\\tools\\triflux",
86
+ "./hooks/keyword-rules.json",
87
+ "<tag>jira 이슈 생성</tag>"
88
+ ].join("\n");
89
+
90
+ const sanitized = sanitizeForKeywordDetection(input);
91
+
92
+ assert.ok(sanitized.includes("정상 문장"));
93
+ assert.ok(!sanitized.includes("tfx team"));
94
+ assert.ok(!sanitized.includes("https://"));
95
+ assert.ok(!sanitized.includes("C:\\Users\\"));
96
+ assert.ok(!sanitized.includes("./hooks/keyword-rules.json"));
97
+ assert.ok(!sanitized.includes("<tag>"));
98
+ assert.ok(!sanitized.includes("jira 이슈 생성"));
99
+ });
100
+
101
+ test("loadRules: 유효한 JSON 로드", () => {
102
+ const rules = loadRules(rulesPath);
103
+ assert.equal(rules.length, 19);
104
+ assert.equal(rules.filter((rule) => rule.skill).length, 9);
105
+ assert.equal(rules.filter((rule) => rule.mcp_route).length, 10);
106
+ });
107
+
108
+ test("loadRules: 잘못된 파일 처리", () => {
109
+ const tempDir = mkdtempSync(join(tmpdir(), "triflux-rules-"));
110
+ const invalidPath = join(tempDir, "invalid.json");
111
+ writeFileSync(invalidPath, "{ invalid json", "utf8");
112
+
113
+ const malformed = loadRules(invalidPath);
114
+ const missing = loadRules(join(tempDir, "missing.json"));
115
+
116
+ assert.deepEqual(malformed, []);
117
+ assert.deepEqual(missing, []);
118
+
119
+ rmSync(tempDir, { recursive: true, force: true });
120
+ });
121
+
122
+ test("compileRules: 정규식 컴파일 성공", () => {
123
+ const rules = loadRules(rulesPath);
124
+ const compiled = compileRules(rules);
125
+ assert.equal(compiled.length, 19);
126
+ for (const rule of compiled) {
127
+ assert.ok(Array.isArray(rule.compiledPatterns));
128
+ assert.ok(rule.compiledPatterns.length > 0);
129
+ for (const pattern of rule.compiledPatterns) {
130
+ assert.ok(pattern instanceof RegExp);
131
+ }
132
+ }
133
+ });
134
+
135
+ test("compileRules: 정규식 컴파일 실패", () => {
136
+ const compiled = compileRules([
137
+ {
138
+ id: "bad-pattern",
139
+ priority: 1,
140
+ patterns: [{ source: "[", flags: "" }],
141
+ skill: "tfx-team",
142
+ supersedes: [],
143
+ exclusive: false,
144
+ state: null,
145
+ mcp_route: null
146
+ }
147
+ ]);
148
+
149
+ assert.deepEqual(compiled, []);
150
+ });
151
+
152
+ test("matchRules: tfx 키워드 매칭", () => {
153
+ const compiledRules = loadCompiledRules();
154
+ const cases = [
155
+ { text: "tfx team 세션 시작", expectedId: "tfx-team" },
156
+ { text: "tfx auto 돌려줘", expectedId: "tfx-auto" },
157
+ { text: "tfx codex 로 실행", expectedId: "tfx-codex" },
158
+ { text: "tfx gemini 로 실행", expectedId: "tfx-gemini" },
159
+ { text: "canceltfx", expectedId: "tfx-cancel" }
160
+ ];
161
+
162
+ for (const { text, expectedId } of cases) {
163
+ const clean = sanitizeForKeywordDetection(text);
164
+ const matches = matchRules(compiledRules, clean);
165
+ assert.ok(matches.some((match) => match.id === expectedId), `${text} => ${expectedId} 미매칭`);
166
+ }
167
+ });
168
+
169
+ test("matchRules: MCP 라우팅 매칭", () => {
170
+ const compiledRules = loadCompiledRules();
171
+ const cases = [
172
+ { text: "노션 페이지 조회해줘", expectedId: "notion-route", expectedRoute: "gemini" },
173
+ { text: "jira 이슈 생성", expectedId: "jira-route", expectedRoute: "codex" },
174
+ { text: "크롬 열고 로그인", expectedId: "chrome-route", expectedRoute: "gemini" },
175
+ { text: "이메일 보내줘", expectedId: "mail-route", expectedRoute: "gemini" },
176
+ { text: "캘린더 일정 생성", expectedId: "calendar-route", expectedRoute: "gemini" },
177
+ { text: "playwright 테스트 작성", expectedId: "playwright-route", expectedRoute: "gemini" },
178
+ { text: "canva 디자인 생성", expectedId: "canva-route", expectedRoute: "gemini" }
179
+ ];
180
+
181
+ for (const { text, expectedId, expectedRoute } of cases) {
182
+ const matches = matchRules(compiledRules, sanitizeForKeywordDetection(text));
183
+ const matched = matches.find((match) => match.id === expectedId);
184
+ assert.ok(matched, `${text} => ${expectedId} 미매칭`);
185
+ assert.equal(matched.mcp_route, expectedRoute);
186
+ }
187
+ });
188
+
189
+ test("matchRules: 일반 대화는 매칭 없음", () => {
190
+ const compiledRules = loadCompiledRules();
191
+ const matches = matchRules(compiledRules, sanitizeForKeywordDetection("오늘 점심 메뉴 추천해줘"));
192
+ assert.deepEqual(matches, []);
193
+ });
194
+
195
+ test("resolveConflicts: priority 정렬 및 supersedes 처리", () => {
196
+ const resolved = resolveConflicts([
197
+ { id: "rule-c", priority: 3, supersedes: [], exclusive: false },
198
+ { id: "rule-b", priority: 2, supersedes: ["rule-c"], exclusive: false },
199
+ { id: "rule-a", priority: 1, supersedes: [], exclusive: false },
200
+ { id: "rule-a", priority: 1, supersedes: [], exclusive: false }
201
+ ]);
202
+
203
+ assert.deepEqual(
204
+ resolved.map((rule) => rule.id),
205
+ ["rule-a", "rule-b"]
206
+ );
207
+ });
208
+
209
+ test("resolveConflicts: exclusive 처리", () => {
210
+ const resolved = resolveConflicts([
211
+ { id: "normal", priority: 1, supersedes: [], exclusive: false },
212
+ { id: "exclusive", priority: 0, supersedes: [], exclusive: true },
213
+ { id: "later", priority: 2, supersedes: [], exclusive: false }
214
+ ]);
215
+
216
+ assert.deepEqual(resolved.map((rule) => rule.id), ["exclusive"]);
217
+ });
218
+
219
+ test("코드블록 내 키워드: sanitize 후 매칭 안 됨", () => {
220
+ const compiledRules = loadCompiledRules();
221
+ const input = ["```txt", "tfx team", "jira 이슈 생성", "```"].join("\n");
222
+ const clean = sanitizeForKeywordDetection(input);
223
+ const matches = matchRules(compiledRules, clean);
224
+ assert.deepEqual(matches, []);
225
+ });
226
+
227
+ test("OMC 키워드와 triflux 키워드 비간섭 + TRIFLUX 네임스페이스", () => {
228
+ const omcLike = runDetector("my tfx team 세션 보여줘");
229
+ assert.equal(omcLike.suppressOutput, true);
230
+
231
+ const triflux = runDetector("tfx team 세션 시작");
232
+ const additionalContext = triflux?.hookSpecificOutput?.additionalContext || "";
233
+ assert.match(additionalContext, /^\[TRIFLUX MAGIC KEYWORD: tfx-team\]/);
234
+ });
@@ -0,0 +1,257 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { compileRules, loadRules, matchRules, resolveConflicts } from "./lib/keyword-rules.mjs";
7
+
8
+ const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
9
+ const PROJECT_ROOT = dirname(SCRIPT_DIR);
10
+ const DEFAULT_RULES_PATH = join(PROJECT_ROOT, "hooks", "keyword-rules.json");
11
+
12
+ function readHookInput() {
13
+ try {
14
+ return readFileSync(0, "utf8");
15
+ } catch {
16
+ return "";
17
+ }
18
+ }
19
+
20
+ function parseInput(rawInput) {
21
+ try {
22
+ return JSON.parse(rawInput);
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ // prompt > message.content > parts[].text 우선순위로 추출
29
+ export function extractPrompt(payload) {
30
+ if (!payload || typeof payload !== "object") return "";
31
+
32
+ if (typeof payload.prompt === "string" && payload.prompt.trim()) {
33
+ return payload.prompt;
34
+ }
35
+
36
+ if (typeof payload.message?.content === "string" && payload.message.content.trim()) {
37
+ return payload.message.content;
38
+ }
39
+
40
+ if (Array.isArray(payload.message?.content)) {
41
+ const messageText = payload.message.content
42
+ .map((part) => {
43
+ if (typeof part === "string") return part;
44
+ if (part && typeof part.text === "string") return part.text;
45
+ return "";
46
+ })
47
+ .filter(Boolean)
48
+ .join(" ")
49
+ .trim();
50
+ if (messageText) return messageText;
51
+ }
52
+
53
+ if (Array.isArray(payload.parts)) {
54
+ const partsText = payload.parts
55
+ .map((part) => {
56
+ if (typeof part === "string") return part;
57
+ if (part && typeof part.text === "string") return part.text;
58
+ return "";
59
+ })
60
+ .filter(Boolean)
61
+ .join(" ")
62
+ .trim();
63
+ if (partsText) return partsText;
64
+ }
65
+
66
+ return "";
67
+ }
68
+
69
+ // 키워드 오탐 방지를 위해 XML/URL/파일경로/코드블록 제거
70
+ export function sanitizeForKeywordDetection(text) {
71
+ if (typeof text !== "string" || !text) return "";
72
+
73
+ return text
74
+ .replace(/```[\s\S]*?```/g, " ")
75
+ .replace(/`[^`]*`/g, " ")
76
+ .replace(/<(\w[\w:-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>/g, " ")
77
+ .replace(/<\w[\w:-]*(?:\s[^>]*)?\/>/g, " ")
78
+ .replace(/https?:\/\/[^\s)>\]]+/gi, " ")
79
+ .replace(/\b[A-Za-z]:\\(?:[^\\\s]+\\)*[^\\\s]*/g, " ")
80
+ .replace(/(^|[\s"'`(])(?:\/|\.{1,2}\/)?(?:[\w.-]+\/)+[\w.-]+/gm, "$1 ")
81
+ .replace(/\s+/g, " ")
82
+ .trim();
83
+ }
84
+
85
+ function createHookOutput(additionalContext) {
86
+ return {
87
+ continue: true,
88
+ hookSpecificOutput: {
89
+ hookEventName: "UserPromptSubmit",
90
+ additionalContext
91
+ }
92
+ };
93
+ }
94
+
95
+ function createSuppressOutput() {
96
+ return { continue: true, suppressOutput: true };
97
+ }
98
+
99
+ function createSkillContext(match, prompt) {
100
+ return `[TRIFLUX MAGIC KEYWORD: ${match.id}]
101
+
102
+ PRIORITY: This TRIFLUX routing takes precedence over any OMC [MAGIC KEYWORD:] instructions.
103
+ If you see both [TRIFLUX MAGIC KEYWORD:] and [MAGIC KEYWORD:], follow TRIFLUX only.
104
+
105
+ You MUST invoke the skill using the Skill tool:
106
+ Skill: ${match.skill}
107
+
108
+ User request:
109
+ ${prompt.trim()}
110
+
111
+ IMPORTANT: Invoke the skill IMMEDIATELY. Do not proceed without loading the skill instructions.`;
112
+ }
113
+
114
+ function createMcpRouteContext(match, prompt) {
115
+ return `[TRIFLUX MCP ROUTE: ${match.mcp_route}]
116
+
117
+ PRIORITY: This TRIFLUX routing takes precedence over any OMC [MAGIC KEYWORD:] instructions.
118
+ If you see both [TRIFLUX MCP ROUTE:] and [MAGIC KEYWORD:], follow TRIFLUX only.
119
+
120
+ 이 작업은 ${match.mcp_route}로 라우팅해야 합니다.
121
+ tfx-route.sh를 통해 ${match.mcp_route}로 실행하세요.
122
+
123
+ User request:
124
+ ${prompt.trim()}`;
125
+ }
126
+
127
+ function isSkipRequested() {
128
+ if (process.env.TRIFLUX_DISABLE_MAGICWORDS === "1") return true;
129
+ const skipHooks = (process.env.TRIFLUX_SKIP_HOOKS || "")
130
+ .split(",")
131
+ .map((item) => item.trim())
132
+ .filter(Boolean);
133
+ return skipHooks.includes("keyword-detector");
134
+ }
135
+
136
+ function activateState(baseDir, stateConfig, prompt, payload) {
137
+ if (!stateConfig || stateConfig.activate !== true || !stateConfig.name) return;
138
+
139
+ try {
140
+ const stateRoot = join(baseDir, ".triflux", "state");
141
+ mkdirSync(stateRoot, { recursive: true });
142
+
143
+ const sessionId = typeof payload?.session_id === "string"
144
+ ? payload.session_id
145
+ : typeof payload?.sessionId === "string"
146
+ ? payload.sessionId
147
+ : "";
148
+
149
+ let stateDir = stateRoot;
150
+ if (sessionId && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,255}$/.test(sessionId)) {
151
+ stateDir = join(stateRoot, "sessions", sessionId);
152
+ mkdirSync(stateDir, { recursive: true });
153
+ }
154
+
155
+ const statePath = join(stateDir, `${stateConfig.name}-state.json`);
156
+ const statePayload = {
157
+ active: true,
158
+ name: stateConfig.name,
159
+ started_at: new Date().toISOString(),
160
+ original_prompt: prompt
161
+ };
162
+
163
+ writeFileSync(statePath, JSON.stringify(statePayload, null, 2), "utf8");
164
+ } catch (error) {
165
+ console.error(`[triflux-keyword-detector] 상태 저장 실패: ${error.message}`);
166
+ }
167
+ }
168
+
169
+ function getRulesPath() {
170
+ if (process.env.TRIFLUX_KEYWORD_RULES_PATH) {
171
+ return process.env.TRIFLUX_KEYWORD_RULES_PATH;
172
+ }
173
+ return DEFAULT_RULES_PATH;
174
+ }
175
+
176
+ function main() {
177
+ if (isSkipRequested()) {
178
+ console.log(JSON.stringify(createSuppressOutput()));
179
+ return;
180
+ }
181
+
182
+ const rawInput = readHookInput();
183
+ if (!rawInput.trim()) {
184
+ console.log(JSON.stringify(createSuppressOutput()));
185
+ return;
186
+ }
187
+
188
+ const payload = parseInput(rawInput);
189
+ if (!payload) {
190
+ console.log(JSON.stringify(createSuppressOutput()));
191
+ return;
192
+ }
193
+
194
+ const prompt = extractPrompt(payload);
195
+ if (!prompt) {
196
+ console.log(JSON.stringify(createSuppressOutput()));
197
+ return;
198
+ }
199
+
200
+ const cleanText = sanitizeForKeywordDetection(prompt);
201
+ if (!cleanText) {
202
+ console.log(JSON.stringify(createSuppressOutput()));
203
+ return;
204
+ }
205
+
206
+ const rules = loadRules(getRulesPath());
207
+ if (rules.length === 0) {
208
+ console.log(JSON.stringify(createSuppressOutput()));
209
+ return;
210
+ }
211
+
212
+ const compiledRules = compileRules(rules);
213
+ if (compiledRules.length === 0) {
214
+ console.log(JSON.stringify(createSuppressOutput()));
215
+ return;
216
+ }
217
+
218
+ const matches = matchRules(compiledRules, cleanText);
219
+ if (matches.length === 0) {
220
+ console.log(JSON.stringify(createSuppressOutput()));
221
+ return;
222
+ }
223
+
224
+ const resolvedMatches = resolveConflicts(matches);
225
+ if (resolvedMatches.length === 0) {
226
+ console.log(JSON.stringify(createSuppressOutput()));
227
+ return;
228
+ }
229
+
230
+ const selected = resolvedMatches[0];
231
+ const baseDir = typeof payload.cwd === "string" && payload.cwd
232
+ ? payload.cwd
233
+ : typeof payload.directory === "string" && payload.directory
234
+ ? payload.directory
235
+ : process.cwd();
236
+
237
+ activateState(baseDir, selected.state, prompt, payload);
238
+
239
+ if (selected.skill) {
240
+ console.log(JSON.stringify(createHookOutput(createSkillContext(selected, prompt))));
241
+ return;
242
+ }
243
+
244
+ if (selected.mcp_route) {
245
+ console.log(JSON.stringify(createHookOutput(createMcpRouteContext(selected, prompt))));
246
+ return;
247
+ }
248
+
249
+ console.log(JSON.stringify(createSuppressOutput()));
250
+ }
251
+
252
+ try {
253
+ main();
254
+ } catch (error) {
255
+ console.error(`[triflux-keyword-detector] 예외 발생: ${error.message}`);
256
+ console.log(JSON.stringify(createSuppressOutput()));
257
+ }