Compare commits

...

39 Commits

Author SHA1 Message Date
이정수 0cc7c91629 docs: update index and add process cleanup documentation for 2026-04-22 2026-04-22 10:36:35 +09:00
이정수 6f5cd602ca refactor: implement lazy gRPC proto resolution, improve service initialization, and update Prisma schema and turbo configuration 2026-04-21 17:24:00 +09:00
이정수 8e03562f82 docs: update local connection documentation and add progress log for 2026-04-21 2026-04-21 12:15:43 +09:00
이정수 5a37512e34 refactor: migrate graphify cache to dedicated directory and update manifest and rules 2026-04-21 12:12:13 +09:00
이정수 706dda5def refactor: improve environment configuration resolution and centralize Prisma instance management 2026-04-21 11:35:18 +09:00
이정수 f8c95945e7 test: implement comprehensive integration and E2E testing infrastructure with Jest, Playwright, and Discord mocks. 2026-04-20 17:08:35 +09:00
이정수 547d5e3dd5 docs: add agent model workflow rules and update kord routine guidelines 2026-04-20 14:25:04 +09:00
이정수 60520c81fa docs: document monorepo migration, gRPC architecture, and update agent routine guidelines 2026-04-20 11:41:36 +09:00
이정수 edfacc4db3 chore: install and update project dependencies in node_modules 2026-04-20 11:39:22 +09:00
이정수 8b9b14a6ae chore: update dependencies and add AGENTS.md in dashboard app 2026-04-20 11:39:16 +09:00
이정수 855aad274a docs: add model_decision trigger and improve formatting in discord_ui_ux rules 2026-04-20 09:57:33 +09:00
이정수 ad8b47d4ec feat: add console output to logger and remove redundant deferReply in autorole command 2026-04-10 10:25:55 +09:00
이정수 1e31f83ff3 fix(i18n): restore missing channelLocked translation key in ko.ts 2026-04-10 09:40:26 +09:00
이정수 bbc4bed551 Merge branch 'origin/main' into feature/invite-role and resolve conflicts 2026-04-10 09:38:39 +09:00
이정수 dcaa14091f chore: update graphify analysis and configuration files 2026-04-09 17:43:01 +09:00
이정수 7beed8f69e docs: update project configuration and add Graphify setup documentation 2026-04-09 17:38:58 +09:00
이정수 e196017bb8 feat: generate graph visualization and cache files for project structure analysis 2026-04-09 17:36:44 +09:00
이정수 aa59e47a62 feat: add graphify tool support with documentation and agent rules 2026-04-09 17:21:54 +09:00
안명현 9afaaf9a2e Merge pull request 'fix(fishing): clear stale sessions for deleted threads' (#10) from myong_dev into main
Reviewed-on: #10
2026-04-09 04:49:53 +00:00
안명현 d9f3e160aa Merge pull request 'fix(fishing): avoid stale no-session response on session end' (#9) from myong_dev into main
Reviewed-on: #9
2026-04-09 04:14:39 +00:00
안명현 53027ac21f Merge pull request 'myong_dev' (#8) from myong_dev into main
Reviewed-on: #8
2026-04-09 03:54:13 +00:00
이정수 6072ab716f refactor: remove invite tracking functionality and migrate member join handling to AutoRoleService 2026-04-07 16:34:08 +09:00
이정수 c4f5e8d53c refactor: remove invite management system and associated command, events, and localization keys 2026-04-07 16:30:20 +09:00
이정수 579e9a8a61 refactor: remove retroactive autorole functionality and associated database tables 2026-04-07 15:14:25 +09:00
이정수 798d3d589c docs: add discord_ui_ux rule file capturing philosophy 2026-04-07 09:07:34 +09:00
이정수 f3f882cd06 feat(autorole): implement multi-role UX, persistence and automatic toggle logic 2026-04-06 18:05:33 +09:00
이정수 c71d263607 chore: update Korean localization strings 2026-04-06 17:16:43 +09:00
이정수 d941daf005 feat: add bot autorole configuration and migrate interaction handling to interactionCreate event 2026-04-06 15:36:45 +09:00
이정수 26cfd356ff feat: add invite command to manage role-based invite code mappings 2026-04-06 15:05:23 +09:00
이정수 107c00cb13 feat: implement AutoRoleService with retroactive assignment and configuration support 2026-04-06 15:04:21 +09:00
이정수 e4bcf53308 docs: add project structure documentation and update main index file 2026-04-06 14:28:57 +09:00
mineseo-kim 2a8b6d41dc Merge branch 'delete-redis'
# Conflicts:
#	yarn.lock
2026-04-02 11:18:10 +09:00
mineseo-kim c10822ea87 빌드 성공 2026-04-01 17:41:09 +09:00
mineseo-kim 57d38a4e09 빌드성공 2026-03-31 10:49:35 +09:00
mineseo-kim 57805644fb Merge remote-tracking branch 'origin/main' into delete-redis
# Conflicts:
#	prisma/schema.prisma
#	src/client/KordClient.ts
#	yarn.lock
2026-03-31 10:27:05 +09:00
mineseo-kim aad37ef855 빌드 성공
빌드 성공본 업데이트
2026-03-31 10:26:16 +09:00
mineseo-kim c1d18d7d8f Service 고도화 작업
난 한국어 커밋 메세지가 좋아
2026-03-31 10:13:38 +09:00
mineseo-kim 1f91bfb9bf Merge branch 'main' into delete-redis
# Conflicts:
#	package.json
#	yarn.lock
2026-03-31 09:29:49 +09:00
pandoli365 e43af4f944 레디스 제거 버전 작업 2026-03-30 20:48:03 +09:00
348 changed files with 27880 additions and 511 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,33 @@
---
trigger: model_decision, subagent_delegation
description: 모델 등급별 역할 분담 및 서브에이전트 활용 규칙
---
# Tiered Model Workflow & Subagent Delegation Rule
복잡한 시스템 기획과 효율적 실행을 분리하여 리소스를 최적화하고 작업 속도를 향상시키기 위한 모델/서브에이전트 운용 원칙입니다. Kord 프로젝트 내에서 수행되는 모든 에이전트 작업에 이 원칙을 우선 적용합니다.
## 1. 모델 전환 권고 기준 (Model Switching Guide)
에이전트는 사용자의 요청을 분석한 후, 필요에 따라 사용자의 개입을 요청하여 적절한 모델 등급으로의 변경을 제안해야 합니다. (에이전트 스스로 모델 전환을 직접 수행할 수 없기 때문입니다.)
- **High-Tier Model (예: Gemini 3.1 Pro/Ultra 등) 권장 상황**:
- 모노레포 구조 설계 문제 혹은 대규모 아키텍처 변경.
- 심도 깊은 설계 단계 리서치, 다수 파일이 연계된 복잡한 버그 추적.
- **→ 응답 가이드**: *"진행하려는 작업은 높은 논리성과 깊은 추론을 요구합니다. 본 기획/설계를 마치기 위해 저를 높은 성능의 Pro/Ultra 모델로 전환해 주시면 더 정교한 계획 수립이 가능합니다."*
- **Efficient Model (예: Gemini 3 Flash 등) 권장 상황**:
- 이미 수립되고 승인된 `implementation_plan.md`에 근거한 단순 코드 구현 및 기계적 실행.
- 패턴화된 파일 리팩토링, 단순 단위 테스트 실행, 문서 정리 및 색인.
- **→ 응답 가이드**: *"계획 수립이 확정되었고, 남은 것은 구현과 반복적인 테스트입니다. 효율성과 응답 속도 향상을 위해 실행 모델(Flash)로 전환하셔도 무방합니다."*
## 2. 서브에이전트 위임 (Subagent Delegation)
복잡한 작업을 모두 메인 에이전트가 단일 프롬프트로 처리하려 하지 말고, 특화된 작업은 적절히 쪼개 병렬 혹은 서브 Task로 위임합니다.
- **작업의 분할 (Task Decomposition)**:
- 실행 단계(Phase 2) 돌입 시, 작업을 독립적인 단위로 쪼개어 Task 목록화합니다.
- **브라우저 서브에이전트 (`browser_subagent`) 활용 필수 상황**:
- 대시보드의 특정 UI가 의도대로 렌더링되는지 눈으로 확인이 필요한 경우 (예: Next.js 로컬 구동 결과 확인).
- 웹 페이지를 통한 로그인, OAuth, 동적인 요소 추출이나 브라우저 기반 에러 로그 확인이 필요한 경우.
- 에이전트는 해당 작업을 서브에이전트용 특화 프롬프트(Task)로 명확히 분리하여 `browser_subagent` 툴에 인가하고, 이후 반환된 DOM 상태나 스크린샷 결과를 메인 작업의 컨텍스트(Walkthrough 등)에 결합해야 합니다.

View File

@ -0,0 +1,32 @@
---
trigger: model_decision
description: Discord Bot UI/UX Design Philosophy
---
# Discord Bot UI/UX Design Philosophy
When designing or updating Discord command interfaces (Embeds, Components), adhere to the following UI/UX philosophy to ensure a clean, intuitive, and modern user experience.
## 1. Minimal and Non-redundant Information (중복 정보 최소화)
- Do not display information in the Embed that is already visually apparent in the UI components.
- For example, if a `RoleSelectMenuBuilder` allows the user to select roles, use `.addDefaultRoles(ids)` (available in discord.js 14.14+) to display the currently selected roles natively inside the dropdown menu.
- Do NOT list those same roles redundantly as text inside the Embed fields. The Embed should remain concise, showing only titles and essential descriptions or instructions.
## 2. Implicit State (명시적 토글 지양 및 상태 직관화)
- Avoid creating manual On/Off toggle buttons unless absolutely necessary.
- Derive the "Enabled/Disabled" state directly from the user's data naturally. For instance, if the user has selected at least one role (`roleIds.length > 0`), the feature is automatically considered "Active/Enabled". If they clear the selection, the feature is "Disabled".
- This reduces UI clutter (removing unnecessary toggle ActionRows) and aligns with modern design patterns where state implicitly follows the presence of data.
## 3. Persistent and Seamless Interaction (매끄러운 대시보드 유지)
- Component interactions should feel fast and seamless without fragmenting the chat history.
- Always immediately call `await interaction.deferUpdate();` (or equivalent) when handling components (buttons, select menus) to prevent "Unknown interaction" timeout errors.
- Use `await interaction.editReply(...)` with the newly generated UI components to seamlessly update the dashboard frame in place.
- Do NOT generate new follow-up messages or close the menu unilaterally when the user still expects to tweak settings.
## 4. Safe Response Timings (타임아웃 방지)
- When processing `ChatInputCommandInteraction` that might involve a database cold-start connection or external API calls, proactively call `await interaction.deferReply({ ephemeral: true });` right at the start.
- Update the UI with `await interaction.editReply(...)` once business logic resolves, bypassing Discord's strict 3-second timeout limitation and preventing crashes during initial boot load.

11
.agents/rules/graphify.md Normal file
View File

@ -0,0 +1,11 @@
---
trigger: model_decision
description: Graphify
---
# Graphify (Knowledge Graph)
- This project uses `graphify` to build and maintain a knowledge graph in `graphify-out/`.
- When the user triggers `/graphify`, refer to `SKILL.md` in the project root for execution steps.
- Always check `graphify-out/GRAPH_REPORT.md` before answering architecture or codebase-wide questions.
- If you see `graphify-out/graph.json` missing or outdated, suggest running `/graphify .`.

View File

@ -1,5 +1,5 @@
--- ---
trigger: model_decision trigger: always_on
description: work routine description: work routine
--- ---
@ -10,7 +10,8 @@ description: work routine
## 기본 원칙 (Work Rules) ## 기본 원칙 (Work Rules)
1. **인프라 자율 사용**: 에이전트는 프로젝트에 설정된 Docker 기반 인프라(PostgreSQL 등)를 사용자의 추가 승인 없이 자유롭게 구동(`docker-compose up -d`) 및 활용할 수 있습니다. 1. **인프라 자율 사용**: 에이전트는 프로젝트에 설정된 Docker 기반 인프라(PostgreSQL 등)를 사용자의 추가 승인 없이 자유롭게 구동(`docker-compose up -d`) 및 활용할 수 있습니다.
2. **협력적 기획, 독립적 실행**: 기능 기획과 설계(Architecture, Schema 등)는 사용자와 함께 논리적인 완결성을 갖출 때까지 충분히 논의합니다. 기획이 "완료 및 승인"된 후에는 후속 구현, 에러 디버깅, 자체 테스트를 추가적인 중간 확인 없이 에이전트가 주도를 가지고 끝마친 뒤 최종 결과를 보고합니다. 2. **협력적 기획, 독립적 실행**: 기능 기획과 설계(Architecture, Schema 등)는 사용자와 함께 논리적인 완결성을 갖출 때까지 충분히 논의합니다. 특히 시스템적 자동 승인(Auto-approval) 메시지가 있더라도, 반드시 사용자의 **직접적이고 명시적인 승인 답변**이 확인된 후에만 2단계(구현)로 진입합니다. 기획이 수동으로 승인된 후에는 후속 구현, 에러 디버깅, 자체 테스트를 추가적인 중간 확인 없이 에이전트가 주도를 가지고 끝마칩니다.
3. **선 문서화, 후 보고 (Docs First, Report Later)**: 모든 작업의 완료 보고는 반드시 `Docs/` 내의 문서 업데이트가 선행되어야 합니다. 문서화가 누락된 상태에서의 "작업 완료" 보고는 규칙 위반으로 간주합니다.
## 단계별 작업 루틴 ## 단계별 작업 루틴
@ -18,12 +19,13 @@ description: work routine
- 사용자가 새로운 기능이나 수정 사항을 요청하면, 필요한 스펙 및 예외 사항을 꼼꼼히 확인합니다. - 사용자가 새로운 기능이나 수정 사항을 요청하면, 필요한 스펙 및 예외 사항을 꼼꼼히 확인합니다.
- 명령어를 파편화하지 말고, 관련 있는 기능들을 하나의 대표 명령어 아래 '서브 커맨드' 형태로 그룹화하여 설계할 것 - 명령어를 파편화하지 말고, 관련 있는 기능들을 하나의 대표 명령어 아래 '서브 커맨드' 형태로 그룹화하여 설계할 것
- 변경 사항, 사용 스택, 아키텍처를 포함한 `implementation_plan.md`를 작성하거나 업데이트하여 사용자에게 검토 및 승인을 요청합니다. - 필요 시 사용자에게 High-Tier 아키텍처 모델(예: Pro/Ultra)로의 전환을 제안하며, 변경 사항, 사용 스택, 아키텍처를 포함한 `implementation_plan.md`를 작성하여 사용자에게 검토 및 승인을 요청합니다. 설계가 완료되면 효율적 실행을 위한 모델 전환(예: Flash) 권고를 포함합니다.
### 2단계: 개발 및 구현 (Execution Phase) ### 2단계: 개발 및 구현 (Execution Phase)
- 설계가 최종 승인되면 실제 코딩을 시작합니다. 이 단계부터는 사용자의 개입 없이 독립적으로 작업을 완수하는 것을 원칙으로 합니다. - 설계가 최종 승인되면 실제 코딩을 시작합니다. 이 단계부터는 사용자의 개입 없이 독립적으로 작업을 완수하는 것을 원칙으로 합니다.
- 환경 변수 파싱, 로깅, 예외 처리를 철저히 포함하여 프로덕션 수준의 코드를 작성합니다. - 환경 변수 파싱, 로깅, 예외 처리를 철저히 포함하여 프로덕션 수준의 코드를 작성합니다.
- 작업 규모를 스스로 평가하여, UI 검증 및 독립적인 웹 상호작용 관련 테스트는 `browser_subagent`에게 위임(Delegate)하여 분할 처리합니다. (`agent_model_workflow.md` 참조)
### 3단계: 자체 구동 및 내부 테스트 (Internal Testing Phase) ### 3단계: 자체 구동 및 내부 테스트 (Internal Testing Phase)
@ -44,5 +46,6 @@ description: work routine
- 3단계 구현 및 테스트가 성공적으로 완료되면, 사용자에게 최종 보고하기 **전에 반드시 먼저** `<PROJECT_ROOT>/Docs/` 디렉토리에 작업 완료(Work done), 트러블슈팅(Troubleshooting), 의사 결정(Decisions made) 내역을 문서화해야 합니다. - 3단계 구현 및 테스트가 성공적으로 완료되면, 사용자에게 최종 보고하기 **전에 반드시 먼저** `<PROJECT_ROOT>/Docs/` 디렉토리에 작업 완료(Work done), 트러블슈팅(Troubleshooting), 의사 결정(Decisions made) 내역을 문서화해야 합니다.
- 새 문서가 생성되거나 수정되면 자동으로 `Docs/index.md`에 문서의 색인(링크)을 추가합니다. - 새 문서가 생성되거나 수정되면 자동으로 `Docs/index.md`에 문서의 색인(링크)을 추가합니다.
- 모든 코드 작업 내역과 의사 결정이 완전히 로컬 `Docs/`에 기록 및 정리된 후에만 비로소 "작업을 완료했다"고 사용자에게 알립니다. - 모든 코드 작업 내역과 의사 결정이 완전히 로컬 `Docs/`에 기록 및 정리된 후에만 비로소 "작업을 완료했다"고 사용자에게 알립니다. **문서화가 완료되지 않은 상태에서 사용자에게 보고하는 것은 엄격히 금지됩니다.**
- 설치, 테스트 방법, 구동, 기능, 명령어 등을 위한 변경사항을 <PROJECT_ROOT>/README.md에 최신화합니다. - 설치, 테스트 방법, 구동, 기능, 명령어 등을 위한 변경사항을 <PROJECT_ROOT>/README.md에 최신화합니다.
- **최종 검크포인트**: 보고 메시지 작성 직전, `Docs/` 폴더와 `README.md`, `index.md`가 최신 상태인지 다시 한번 전수 점검합니다.

View File

@ -15,3 +15,9 @@
- 유저에게 노출되는 모든 기능(메시지, 임베드, 상태 메시지 등)을 구성할 때는 별도의 요청이 없더라도 **반드시 다국어 지원(i18n) 적용을 검토하고 구현**해야 합니다. (자세한 내용은 `Docs/Rules/i18n_guidelines.md` 참조) - 유저에게 노출되는 모든 기능(메시지, 임베드, 상태 메시지 등)을 구성할 때는 별도의 요청이 없더라도 **반드시 다국어 지원(i18n) 적용을 검토하고 구현**해야 합니다. (자세한 내용은 `Docs/Rules/i18n_guidelines.md` 참조)
- 단순 문법 검증에 그치지 말고, `yarn dev` 등의 명령어로 봇을 백그라운드에서 직접 구동(Boot)시켜 DB/캐시 커넥트 및 이벤트 리스너 초기화 중 런타임 에러(예: Intents 권한 거부 등)가 발생하지 않는지 스스로 눈으로 확인하고 완벽히 디버깅해야 합니다. - 단순 문법 검증에 그치지 말고, `yarn dev` 등의 명령어로 봇을 백그라운드에서 직접 구동(Boot)시켜 DB/캐시 커넥트 및 이벤트 리스너 초기화 중 런타임 에러(예: Intents 권한 거부 등)가 발생하지 않는지 스스로 눈으로 확인하고 완벽히 디버깅해야 합니다.
- 봇이 성공적으로 온라인 상태(`Ready`)에 진입한 것을 확인한 뒤에만 사용자에게 작업 완료를 보고합니다. - 봇이 성공적으로 온라인 상태(`Ready`)에 진입한 것을 확인한 뒤에만 사용자에게 작업 완료를 보고합니다.
## Graphify Rules
- 사용자가 `/graphify` 혹은 지식 그래프 관련 질의를 할 경우, 프로젝트 루트의 `SKILL.md` 및 `Docs/Features/Graphify_Setup_Guide.md` 지침을 준수하여 실행합니다.
- 대규모 리팩토링이나 구조 파악이 필요할 때는 `graphify-out/GRAPH_REPORT.md`를 우선적으로 참조하여 의존 관계를 파악합니다.
- 로컬 Ollama 환경이 감지되면 (`http://localhost:11434`), 대량의 데이터 처리에 대해 `--ollama` 옵션 사용을 우선적으로 검토합니다.
- 개발 및 잦은 코드 수정 시 항상 `python3 -m graphify.watch .` 를 백그라운드에 구동시켜 지식 그래프의 최신화를 자동화하는 것을 검토하십시오.

View File

@ -12,3 +12,16 @@ LOG_LEVEL=info
# Log directory (kord.log + dated rotations). Relative = from process cwd; use an absolute path on servers # Log directory (kord.log + dated rotations). Relative = from process cwd; use an absolute path on servers
# if the deploy directory is wiped (e.g. Jenkins): LOG_DIR=/var/lib/kord/logs # if the deploy directory is wiped (e.g. Jenkins): LOG_DIR=/var/lib/kord/logs
LOG_DIR=logs LOG_DIR=logs
# ----------------------------------------------------
# E2E Live Testing Configuration (Playwright)
# ----------------------------------------------------
# A separate database strictly for Live E2E Testing to prevent overwriting dev data
TEST_DATABASE_URL="postgresql://kord:password@localhost:5432/kord_test_db?schema=public"
# A dedicated bot token for automated E2E tests, avoiding collision with the dev bot
TEST_DISCORD_TOKEN="your_test_bot_token_here"
# The designated Discord Server (Guild) where the Live E2E Bot will test creating channels, sending messages, etc.
TEST_GUILD_ID="your_test_guild_id_here"

View File

@ -0,0 +1 @@
{"files":{"packages/db/.turbo/turbo-generate.log":{"size":401,"mtime_nanos":1776651586075885272,"mode":420,"is_dir":false}},"order":["packages/db/.turbo/turbo-generate.log"]}

View File

@ -0,0 +1 @@
{"hash":"29fcb16557ff68aa","duration":1221,"sha":"855aad274ad148847ffefa8e54eb8fa8066713fa","dirty_hash":"5906811204abfbb072123bc0cbfc794bb506b732c5875205b21f947edcc57687"}

BIN
.turbo/cache/29fcb16557ff68aa.tar.zst vendored Normal file

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
{"hash":"63605b2509e03797","duration":1834,"sha":"855aad274ad148847ffefa8e54eb8fa8066713fa","dirty_hash":"d0414de747ab562fdf8628ad70f7f928ce881c495f15765d4afcb0621966da17"}

BIN
.turbo/cache/63605b2509e03797.tar.zst vendored Normal file

Binary file not shown.

View File

@ -0,0 +1 @@
{"files":{"packages/db/.turbo/turbo-generate.log":{"size":401,"mtime_nanos":1776758349447738118,"mode":420,"is_dir":false}},"order":["packages/db/.turbo/turbo-generate.log"]}

View File

@ -0,0 +1 @@
{"hash":"acf3ce7b1f0725e0","duration":973,"sha":"8e03562f82c54396a045cb531584408aebdb976c","dirty_hash":"bc9a3d2593e9616d8817460434cba66b1a00b3efba8cea3092233c3532581f2b"}

BIN
.turbo/cache/acf3ce7b1f0725e0.tar.zst vendored Normal file

Binary file not shown.

View File

@ -16,3 +16,8 @@
- 유저에게 노출되는 모든 기능(메시지, 임베드, 상태 메시지 등)을 구성할 때는 별도의 요청이 없더라도 **반드시 다국어 지원(i18n) 적용을 검토하고 구현**해야 합니다. (자세한 내용은 `Docs/Rules/i18n_guidelines.md` 참조) - 유저에게 노출되는 모든 기능(메시지, 임베드, 상태 메시지 등)을 구성할 때는 별도의 요청이 없더라도 **반드시 다국어 지원(i18n) 적용을 검토하고 구현**해야 합니다. (자세한 내용은 `Docs/Rules/i18n_guidelines.md` 참조)
- 단순 문법 검증에 그치지 말고, `yarn dev` 등의 명령어로 봇을 백그라운드에서 직접 구동(Boot)시켜 DB/캐시 커넥트 및 이벤트 리스너 초기화 중 런타임 에러(예: Intents 권한 거부 등)가 발생하지 않는지 스스로 눈으로 확인하고 완벽히 디버깅해야 합니다. - 단순 문법 검증에 그치지 말고, `yarn dev` 등의 명령어로 봇을 백그라운드에서 직접 구동(Boot)시켜 DB/캐시 커넥트 및 이벤트 리스너 초기화 중 런타임 에러(예: Intents 권한 거부 등)가 발생하지 않는지 스스로 눈으로 확인하고 완벽히 디버깅해야 합니다.
- 봇이 성공적으로 온라인 상태(`Ready`)에 진입한 것을 확인한 뒤에만 사용자에게 작업 완료를 보고합니다. - 봇이 성공적으로 온라인 상태(`Ready`)에 진입한 것을 확인한 뒤에만 사용자에게 작업 완료를 보고합니다.
## Graphify Rules
- 사용자가 `/graphify` 혹은 지식 그래프 관련 질의를 할 경우, `SKILL.md`와 `Docs/Features/Graphify_Setup_Guide.md`의 워크플로우를 참조합니다.
- 대규모 리팩토링이나 구조 파악이 필요할 때는 `graphify-out/GRAPH_REPORT.md`를 우선적으로 참조하여 의존 관계를 파악합니다.
- 로컬 모델을 위한 시맨틱 추출이 필요한 경우 `--ollama` 옵션의 활용을 검토하며, 코드 기반 갱신은 `python3 -m graphify.watch .` 를 이용합니다.

5
CLAUDE.md Normal file
View File

@ -0,0 +1,5 @@
# graphify
- **graphify** (`SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
- 프로젝트의 구조 변경이나 문서 갱신시 실시간 업데이트를 원한다면 `python3 -m graphify.watch .` 실행을 추천하세요.
- Ollama 연동 및 트러블슈팅 설정 등은 `Docs/Features/Graphify_Setup_Guide.md` 문서를 참고하세요.

View File

@ -0,0 +1,33 @@
# 결정 사항: 대시보드-봇 통신 아키텍처 (gRPC Proxy)
## 배경 (Context)
대시보드(Next.js)와 멀티 인스턴스 샤딩 환경의 봇 간에 실시간 통신이 필요합니다. 대시보드는 특정 길드의 설정을 변경하거나 채널 목록을 조회해야 하지만, 봇이 여러 프로세스(Shard)로 쪼개져 있어 어떤 인스턴스가 해당 길드를 관리하는지 대시보드가 알기 어려운 문제가 있습니다.
## 결정된 사항 (Decision)
1. **통신 프로토콜**: **gRPC (HTTP/2)** 선택
- 강력한 타입 시스템(`packages/grpc-contracts`) 공유를 위해 선택했습니다.
- 대량의 데이터 전송 및 실시간 양방향 통신 확장에 유리합니다.
2. **Manager as API Proxy 패턴 채택**
- **구조**: Dashboard <-> ShardingManager (gRPC Server) <-> Shards (IPC)
- 모든 대시보드 요청은 단 하나의 포트(`50051`)를 가진 `ShardingManager`로 집중됩니다.
- 매니저는 `guildId` 등의 키를 확인하여 내부적으로 `broadcastEval` 또는 `IPC`를 통해 해당 Shard에게 업무를 하달합니다.
3. **데이터 보관 전략**: **DB (Prisma) 중심**
- 실시간성이 극도로 중요한 요청 외의 설정값 변경은 DB를 우선 업데이트하고, 봇이 이를 캐시 동기화하도록 인터페이스를 구성합니다.
## 장점 (Pros)
- **인프라 간소화**: 봇 인스턴스가 100개로 늘어나도 대시보드 입장에서는 `50051` 포트 하나만 바라보면 됩니다.
- **포트 충돌 방지**: 각 샤드 워커마다 별도의 서버 포트를 할당할 필요가 없습니다.
- **코드 공유**: 모노레포 구조를 통해 클라이언트와 서버가 동일한 `.proto` 계약을 공유합니다.
## 단점 (Cons)
- **매니저 오버헤드**: 매니저가 모든 통신을 중계하므로, 통신량이 극도로 많아질 경우 매니저가 병목이 될 수 있습니다. (이 경우 추후 Redis Pub/Sub으로 전환 고려)
## 대안 (Alternatives)
- **Redis Pub/Sub**: 가장 유연하지만 추가 인프라(Redis) 관리가 필요합니다. 현재는 단일 서버 환경이므로 gRPC Proxy가 더 효율적이라고 판단했습니다.

View File

@ -0,0 +1,62 @@
# Graphify Setup & Guide
이 문서는 프로젝트 내 코드 및 문서의 지식 그래프(Knowledge Graph)를 생성하고 유지관리하기 위한 `graphify` 도구의 설치부터 Ollama 모델 연동, 그리고 실시간 자동 갱신(Watch Mode)을 적용하는 과정을 다른 환경에서도 쉽게 따라 할 수 있도록 정리한 가이드입니다.
## 1. Graphify 설치 및 기본 환경 설정
`graphify`는 코드베이스, 문서 등을 분석하여 구조적/시맨틱(의미론적) 연결망을 만들어주는 지식 그래프 도구입니다.
### Python 인터프리터 구성
- 시스템 전역 파이썬 대신 `venv` 등의 가상 환경에 구성된 파이썬을 이용하는 것을 권장합니다.
- `graphify` 설치 명령어:
```bash
python3 -m pip install graphifyy -q --break-system-packages
```
- 에이전트(Claude 등)가 일관된 파이썬을 사용할 수 있게 프로젝트 루트에 `.graphify_python` 파일을 생성해 파이썬 경로를 저장합니다.
```bash
python3 -c "import sys; open('.graphify_python', 'w').write(sys.executable)"
```
## 2. 로컬 LLM (Ollama) 연동 및 시맨틱 분석
`graphify`는 문서나 코드의 주석 등을 기반으로 추론된 엣지(INFERRED)를 찾을 때 LLM을 사용합니다. 외부 API 대신 로컬 Ollama 모델을 활용하면 토큰 비용을 아낄 수 있습니다.
### Ollama 연결 확인 및 모델 설정
- 로컬의 `11434` 포트에서 Ollama 데몬이 실행 중인지 확인합니다.
```bash
curl -s http://localhost:11434/api/tags > .ollama_tags.json
```
- 로드된 언어 모델(예: `gemma4:e4b-it-q4_K_M`, `llama3` 등)을 `.ollama_models.json` 캐시로 저장합니다.
- 이후 그래프 생성 명령 시 `--ollama` 플래그를 붙여 로컬 연동을 지시합니다.
```bash
/graphify . --ollama --model gemma4:e4b-it-q4_K_M
```
### 트러블슈팅: f-string 및 패키지 오류 (semantic_llm.py)
파이썬 버전 또는 패키지 업데이트 상태에 따라 Ollama API를 호출하는 `semantic_llm.py` 내부 로직에서 몇 가지 오류가 발생할 수 있습니다. (에이전트가 실행 시 자동 수정하거나, 수동으로 수정해야 합니다.)
1. **f-string `{}` 파싱 오류**: `extract_semantic` 프롬프트 내 JSON 예시의 괄호(`{`, `}`)가 f-string의 변수로 인식되어 `ValueError`가 발생할 수 있습니다. JSON 중괄호를 모두 `{{`, `}}`로 더블 이스케이프해야 합니다.
2. **urllib Request 오류**: `urllib.request.Request` 호출 시 `content_type="application/json"` 인자가 거부될 경우, `headers={"Content-Type": "application/json"}` 형태로 교체해야 합니다.
## 3. 지식 그래프 자동 갱신 설정 (Watch Mode)
개발 과정 중 코드나 문서가 빈번하게수정될 때, 그래프를 백그라운드에서 실시간으로 최신화하는 `watch` 모드를 설정할 수 있습니다. (문서 수정은 수동 업데이트 필요, 코드는 자동 재구성)
### 의존성 설치
watch 모드는 `watchdog` 라이브러리를 요구합니다.
```bash
python3 -m pip install watchdog
```
### 상태 감시 실행
터미널을 열어 아래 명령어를 유지합니다:
```bash
python3 -m graphify.watch .
```
- **코드 파일**이 변경된 경우: 백그라운드에서 즉각적으로 AST 추출이 다시 실행되고 `graph.json`과 리포트가 갱신됩니다.
- **문서 파일**이 변경된 경우: LLM 추론이 필요하므로 `need_update` 플래그만 기록합니다. 이후 에이전트나 사용자가 명시적으로 `/graphify . --update` 를 실행하여 최신화합니다.
## 4. 에이전트 설정(IDE Rules) 연계
- **CLAUDE.md 및 .cursorrules**: AI 에이전트가 `graphify` 관련 요청을 받을 경우 `SKILL.md`를 우선 확인하도록 규칙이 지정되어 있습니다.
- 백그라운드에서 감지될 수 있도록 에이전트는 "대규모 리팩토링이나 구조 파악 전 `GRAPH_REPORT.md` 검토", "코드 작성 중 `watchdog`에 의한 자동 갱신 확인" 등을 수행합니다.

44
Docs/Project_Structure.md Normal file
View File

@ -0,0 +1,44 @@
# 프로젝트 구조 (Project Structure)
본 문서는 Kord 프로젝트의 주요 디렉터리와 아키텍처 구조를 설명합니다.
## 디렉터리 안내
### `src/` - 주요 소스 코드
본 봇의 모든 핵심 비즈니스 로직과 시스템 코드가 위치합니다.
- **`client/`**: `KordClient` 등 디스코드 봇 클라이언트 초기화 및 상태를 관리합니다.
- **`commands/`**: 디스코드 슬래시 명령어의 로직이 위치합니다.
- **`core/`**: 어플리케이션의 핵심 인프라 구성을 담당합니다. (`db.ts`, `command.ts` 기반 베이스 클래스 등)
- **`config/`**: 봇 구동 환경 및 전역 설정 관련 파일입니다.
- **`events/`** & **`handlers/`**: 디스코드 이벤트(messageCreate, interactionCreate 등)의 처리 및 바인딩을 담당합니다.
- **`i18n/`**: 다국어(한국어, 영어 등) 지원을 위한 로케일 데이터 및 번역 함수를 관리합니다.
- **`interactions/`**: 버튼, 셀렉트 메뉴, 모달 등 컴포넌트 상호작용 로직입니다.
- **`service/`** / **`services/`**: 각 도메인 별 비즈니스 로직 및 Prisma DB 읽기/쓰기 작업을 추상화한 서비스 계층입니다. (e.g. `FishingService`, `RefinementService`)
- **`utils/`**: 공통으로 사용되는 유틸리티 및 헬퍼 함수들입니다.
### `resource/` - 에셋 및 데이터 리소스
- 미니게임 아트웍(낚시 물고기 이미지, 무기 이미지 등) 및 정적 JSON 데이터(카탈로그, 확률표 등)를 보관합니다.
### `prisma/` - 데이터베이스 관리
- **`schema.prisma`**: PostgreSQL 데이터베이스의 스키마 명세입니다.
- **`migrations/`**: Prisma Migrate에 의해 자동 생성된 마이그레이션 이력입니다.
- **`seed.ts`**: 초기 데이터베이스 시딩을 위한 스크립트입니다.
### `Docs/` - 공식 문서
기능 명세, 트러블슈팅, 작업 내역, 데이터베이스 스키마 및 규칙 등 관리용 문서를 포함합니다. [`Docs/index.md`](index.md)를 중심으로 카테고리가 분류되어 있습니다.
### `tests/` - 테스트 코드
Jest 프레임워크를 기반으로 한 단위 테스트(Unit Test) 로직이 위치합니다. 주 도메인이나 `core`, `services` 코드에 대한 검증을 수행합니다.
---
## 향후 모놀리식 분리 (Modular Architecture) 진행 사항
최근 프로젝트 구조는 단일 스키마 구조에서 도메인/모듈 별로 패키지를 분리하기 위한 기초 작업이 진행되었습니다.
루트 디렉터리에 위치한 `schema_base.prisma`, `schema_feature.prisma`, `schema_main.prisma``package_feature.json`, `package_main.json` 파일들은 향후 핵심(Core/Base) 로직과 기능(Feature) 모듈을 독립적으로 빌드/관리하기 위해 도입될 예정(Work-in-Progress)입니다.

View File

@ -0,0 +1,32 @@
# 2026-04-20: 모노레포 전환 및 gRPC 통신 테스트 완료 (Monorepo & gRPC Test)
대시보드 도입을 위한 프로젝트 구조 개편과 봇-대시보드 간의 실시간 통신 인프라를 구축하고 검증하였습니다.
## 작업 내용 (Work Done)
### 1. 프로젝트 모노레포(Monorepo) 화
- **Turborepo & Yarn Workspaces** 도입: 프로젝트를 모듈화하여 관리하기 위해 모노레포 구조로 전환했습니다.
- `apps/bot`: 기존 디스코드 봇 로직 이관.
- `apps/dashboard`: Next.js 기반 웹 대시보드 신규 생성.
- `packages/db`: Prisma 스키마 및 DB 접근 로직을 공용 패키지로 분리.
- `packages/grpc-contracts`: gRPC 프로토콜 버퍼와 인터페이스 정의를 위한 공용 패키지 생성.
### 2. 봇 샤딩 및 상태 관리 고도화
- **ShardingManager 도입**: 봇 프로세스를 분할 관리하고 gRPC 서버를 부착하기 위해 최상위 매니저 레이어를 추가했습니다.
- **ShardStatus 추적**: 각 Shard가 실행될 때 자신의 상태와 담당 길드 정보를 DB(`ShardStatus` 테이블)에 기록하도록 구현했습니다.
### 3. gRPC 통신 프록시 서버 구축
- **단일 포트 gRPC 서버**: `ShardingManager` 단에서 `50051` 포트로 gRPC 서버를 실행합니다.
- **메시지 라우팅**: 대시보드로부터 요청이 들어오면 매니저가 `broadcastEval`을 통해 해당 길드를 담당하는 하위 Shard 프로세스로 요청을 전달(Proxy)합니다.
### 4. 대시보드 gRPC 통신 테스트 완료
- **테스트 환경 구성**: Next.js API Route를 통해 봇에게 `Ping`을 쏘고 `Pong` 응답을 받는 라이프사이클을 구현했습니다.
- **UI 검증**: 대시보드 메인 페이지에서 버튼 클릭 시 봇으로부터 성공적으로 응답을 받아 `response`를 렌더링함을 확인했습니다.
## 테스트 결과 (Results)
- **연결 성공**: 대시보드 -> 매니저 -> (방송) -> 봇 워커 -> 매니저 -> 대시보드 흐름이 무차별적인 포트 개방 없이 단일 통로로 성공적으로 작동함.
- **지연 시간**: 로컬 환경 기준 10ms 이내의 빠른 응답 속도를 확인.
## 관련 문서
- [대시보드 아키텍처 결정서](../Decisions/Dashboard_Architecture_gRPC.md)

View File

@ -0,0 +1,29 @@
# 인프라 치명적 오류 복구 및 안정화 (2026-04-21)
## 개요
이전 작업 과정에서 누락되었거나 허위로 보고된 인프라 결함(DB 스키마 불일치, 환경 변수 로드 실패, gRPC 경로 인식 오류)을 모두 복구하고, 이를 입증할 수 있는 검증 시스템을 구축했습니다.
## 문제 원인 및 해결 내용
### 1. DB 스키마 불일치 (ShardStatus 테이블 누락)
- **증상**: 봇이 `ready` 상태가 될 때 `ShardStatus` 테이블을 업데이트하려다 `TableDoesNotExist` 에러가 발생하며 비정상 작동함.
- **해결**: `prisma db push`를 실행하여 `ShardStatus` 테이블을 DB에 생성하고 동기화 상태를 확인했습니다.
### 2. shard.ts 환경 변수 로드 실패
- **증상**: `apps/bot/src/shard.ts`에서 모노레포 루트의 `.env`를 찾지 못하고 `DISCORD_TOKEN``undefined`로 로드되어 샤드 생성에 실패함.
- **해결**: `shard.ts``dotenv` 로딩 로직을 수정하여 `apps/bot` 또는 프로젝트 루트 어디에서 실행하더라도 `.env`를 안정적으로 찾도록 개선했습니다.
### 3. gRPC 프로토 파일 경로 인식 강화
- **증상**: `packages/grpc-contracts`가 다양한 실행 환경(Next.js, tsx 직접 실행 등)에서 `kord.proto` 파일을 찾지 못하는 브리틀(Brittle)한 상태였음.
- **해결**: `findProtoPath` 함수를 보강하여 5단계의 폴백 경로 탐색 및 실패 시 상세 로그 출력 로직을 도입했습니다.
### 4. 통합 검증 시스템 (scripts/verify-recovery.ts)
- **기능**: `.env` 로딩, DB 접속, 필수 테이블 존재 여부, gRPC 컨트랙트 유효성을 한 번에 체크합니다.
- **결과**: `--- Verification Finished ---` 메시지와 함께 모든 인프라가 **정상(PASS)**임을 입증했습니다.
## 의사 결정 (Decisions Made)
- **Verification First**: 차후 유사한 신뢰 문제가 발생하지 않도록, 단순 코드 수정에 그치지 않고 독립적인 검증 스크립트를 작성하여 사용자에게 증거를 제시하도록 프로세스를 강화했습니다.
- **Robust Path Resolution**: 모노레포 구조 특성상 실행 CWD가 가변적임을 고려하여, 하드코딩된 상대 경로 대신 다중 폴백 전략을 채택했습니다.
## 향후 과제
- `dev` 스크립트 실행 시 항상 `shard.ts`를 거치도록 통합하여 샤딩 환경의 일관성을 유지할 필요가 있음.

View File

@ -0,0 +1,18 @@
# Work Done: README 로컬 접속 정보 업데이트 (README Local Connection Info Update)
## 개요 (Overview)
- **날짜**: 2026-04-21
- **작업자**: Antigravity (AI Agent)
- **목표**: `README.md`에 결여된 로컬 테스트용 접속 주소 및 포트 정보 추가
## 변경 사항 (Changes)
### [README.md](file:///Users/wemadeplay/workspace/stz/Kord/README.md)
- "4. 로컬 접속 정보 (Local Connection Info)" 섹션 추가
- 각 컴포넌트별 로컬 접속 정보 명시:
- **웹 대시보드 (Dashboard)**: `http://localhost:3000`
- **gRPC 프록시 서버 (Bot Proxy)**: `localhost:50051`
- **데이터베이스 (PostgreSQL)**: `localhost:5432`
## 확인 방법 (Verification)
- `README.md` 파일 내용 확인

View File

@ -0,0 +1,34 @@
# Dashboard & Bot Stability Infrastructure Fix (2026-04-21)
## 개요
사용자가 대시보드 URL 접속 시 `Turbopack Panic` 에러를 겪는 문제를 해결하고, 봇 프로세스의 불안정성(IPC 채널 종료)을 개선했습니다.
## 원인 분석
1. **gRPC Contract 초기화 이슈**:
- `grpc-contracts` 패키지 로드 시점에 동적으로 파일 시스템을 조회하여 `proto` 파일을 로드함.
- Next.js의 빌드/분석 단계에서 파일 시스템 접근 권한이나 경로 문제로 인해 crash 유발.
2. **Turbopack 환경 호환성 이슈**:
- Turbopack이 내부 worker 프로세스를 스폰할 때 시스템 `$PATH`에서 `node` 바이너리를 찾지 못함 (`os error 2`).
- 이는 Turborepo의 환경 변수 제한 정책과 겹쳐 발생함.
## 해결 방법
1. **gRPC Lazy Loading 적용**:
- `packages/grpc-contracts/src/index.js`를 수정하여 실제 모듈 접근 시점에만 proto를 로드하도록 `getter` 패턴 적용.
2. **gRPC 서버 개발 모드 통합**:
- `apps/bot/src/utils/grpcServer.ts`를 신설하여 공통 gRPC 서버 로직을 추출.
- 단일 실행 모드(`index.ts`)와 Sharding 모드(`shard.ts`) 모두에서 대시보드 통신을 위한 gRPC 서버가 기동되도록 수정.
3. **Webpack Fallback 및 PATH 주입**:
- Turbopack의 하위 프로세스 스폰 이슈(`os error 2`)를 회피하기 위해 대시보드를 Webpack 모드(`next dev --webpack`)로 구동.
- `apps/dashboard/package.json`에서 명시적으로 Node.js 실행 경로를 `PATH`에 주입.
4. **인프라 자동 복구**:
- `docker-compose`를 통해 PostgreSQL 컨테이너를 정상화하고 `Prisma` 스키마를 동기화.
5. **좀비 프로세스 정리**:
- 포트 점유 이슈를 유발하던 구형 Node 프로세스들을 원천 정리.
## 결과 확인
- `scripts/verify-recovery.ts`를 통해 DB, gRPC, Bot 연동 전수 검토 완료 (ALL PASS).
- `curl -I http://localhost:3000/`를 통해 대시보드 응답 확인.
- 브라우저를 통한 대시보드 UI 정상 렌더링 확인.
## 참고 사항
- 현재 대시보드는 안정성을 위해 임시로 `3005` 포트에서 구동 확인을 마쳤으나, `3000`번 포트 점유가 해제되면 다시 `3000`번으로 서비스될 수 있도록 설정되어 있습니다.

View File

@ -0,0 +1,37 @@
# gRPC Proto 파일 경로 인식 오류 수정 (2026-04-21)
## 개요
Next.js(`dashboard`) 환경에서 `@kord/grpc-contracts` 패키지를 통해 gRPC 서비스를 이용할 때, `kord.proto` 파일을 찾지 못해 발생하는 `ENOENT` 에러를 해결했습니다.
## 문제 원인
1. **__dirname의 가변성**: Next.js 서버 사이드 번들링 과정에서 Webpack이 `__dirname`을 변조하거나 가상 경로(`/ROOT/...`)로 치환하여 실제 파일 시스템의 `.proto` 파일 위치를 가리키지 못함.
2. **정적 리소스 누락**: JS 파일 외의 `.proto` 파일이 빌드 결과물에 포함되지 않거나 모노레포의 심볼릭 링크 구조에서 경로 해석이 어긋남.
## 수정 내역
### 1. @kord/grpc-contracts 패키지 개선
- `src/index.js` 내의 `PROTO_PATH` 결정 로직에 폴백 시스템 도입.
- 기존 `__dirname` 기반 탐색이 실패할 경우, `process.cwd()`를 기준으로 한 프로젝트 루트 탐색 및 상대 경로 탐색(`../../packages/...`) 로직 추가.
- 환경 변수 `KORD_PROTO_PATH`를 통한 명시적 경로 지정 지원.
### 2. apps/dashboard 설정 업데이트
- `next.config.ts``transpilePackages: ["@kord/grpc-contracts"]` 설정 추가.
- 이를 통해 Next.js가 해당 모노레포 패키지를 소스 레벨에서 직접 처리하여 경로 해석의 일관성을 확보함.
### 3. gRPC 연결 설정 및 호환성 개선
- `apps/dashboard/src/lib/grpc.ts`에서 기본 연결 주소를 `127.0.0.1`로 변경하여 IPv6 호환 이슈 해결.
- **Node.js v22 호환성 해결**: `apps/bot/src/shard.ts`에서 샤딩 프로세스 생성 시 발생하는 `ERR_METHOD_NOT_IMPLEMENTED` 에러를 해결하기 위해 `execArgv``--import tsx`로 업데이트함.
- **구동 순서 최적화**: 봇 샤드 생성 완료 전에도 gRPC 서버가 즉시 응답할 수 있도록 시작 시퀀스를 조정함.
## 테스트 결과 (에이전트 직접 검증 완료)
- **독립 테스트 스크립트 실행 결과**:
- 파일: `apps/dashboard/src/verify_grpc.ts`
- 결과: `SUCCESS! Received response: { reply: 'Pong to Hello from verification script!' }`
- **입증 내용**:
1. `@kord/grpc-contracts`를 통한 프로토 파일 로드 성공 (Path Resolution 해결).
2. 봇과 대시보드 패키지 간의 gRPC 통신 성공 (Connection 해결).
3. Node.js v22 환경에서의 봇 구동 안정성 확보.
## 의사 결정 (Decisions Made)
- Node.js v22의 ESM 로더 변경 사항에 대응하기 위해 `-r tsx` 대신 `--import tsx`를 사용하여 런타임 안정성을 확보함.
- 봇의 라이프사이클에 관계없이 gRPC 서버를 조기에 활성화하여 서비스 가용성을 높임.

View File

@ -0,0 +1,16 @@
# Process Cleanup (2026-04-22)
## Description
이전에 실행되었던 테스트 프로세스가 포트 3000을 점유하고 있어, 이를 확인하고 강제 종료(Kill) 처리하였습니다.
## Actions Taken
- `lsof -i :3000`을 통해 포트 3000(대시보드)을 사용 중인 PID 59044 확인 및 종료
- `lsof -i :50051`을 통해 포트 50051(gRPC)을 사용 중인 PID 59045 확인 및 종료
- `ps aux` 조회를 통해 남아있던 `turbo run dev` 프로세스(PID: 59029, 59028) 및 `tsx watch` 프로세스(PID: 59043) 확인 및 종료
- `kill -9` 명령어로 모든 관련 프로세스를 강제 종료 처리
- 포트 3000, 50051, 8080 및 관련 프로세스 상태를 재확인하여 완전 종료 여부 검증
## Results
- 포트 3000(Dashboard) 및 50051(gRPC)이 성공적으로 해제되었습니다.
- 모든 관련 부모 프로세스(`turbo`, `tsx`)가 정리되었습니다.
- 프로젝트 경로(`/Users/wemadeplay/workspace/stz/Kord`)에서 실행 중인 추가 유령 프로세스가 없음을 확인했습니다.

242
Docs/database-schema.md Normal file
View File

@ -0,0 +1,242 @@
# 데이터베이스 테이블 구조
이 문서는 [Prisma 스키마](../prisma/schema.prisma)를 기준으로 한 **PostgreSQL** 테이블 구조 요약입니다.
## 개요
| 항목 | 값 |
|------|-----|
| DB | PostgreSQL |
| ORM | Prisma (`prisma-client-js`) |
| 연결 | `DATABASE_URL` 환경 변수 |
## 열거형 (Enum)
### `SubscriptionTier`
구독 단계.
| 값 | 설명 |
|----|------|
| `FREE` | 기본 |
| `STANDARD` | 스탠다드 |
| `PRO` | 프로 |
| `PREMIUM` | 프리미엄 |
### `DeleteCondition`
임시 음성 채널 삭제 조건.
| 값 | 설명 |
|----|------|
| `OWNER_LEAVE` | 소유자 퇴장 시 |
| `EMPTY` | 비었을 때 (기본) |
### `EventStatus`
길드 이벤트 상태.
| 값 | 설명 |
|----|------|
| `SCHEDULED` | 예정 (기본) |
| `CANCELLED` | 취소 |
| `COMPLETED` | 완료 |
---
## 테이블 목록
### `GuildConfig`
디스코드 길드별 봇 설정.
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `guildId` | `String` | PK |
| `prefix` | `String` | 기본 `!` |
| `mimicEnabled` | `Boolean` | 기본 `false` |
| `bigEmojiEnabled` | `Boolean` | 기본 `false` |
| `locale` | `String?` | nullable |
| `createdAt` | `DateTime` | 생성 시각 |
| `updatedAt` | `DateTime` | 자동 갱신 |
---
### `InviteRole`
길드·초대 코드별 역할 매핑.
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `id` | `String` | PK, UUID |
| `guildId` | `String` | |
| `inviteCode` | `String` | |
| `roleId` | `String` | |
| `createdAt` | `DateTime` | |
**유니크:** `(guildId, inviteCode)`
---
### `UserSubscription`
사용자 구독 정보.
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `userId` | `String` | PK |
| `tier` | `SubscriptionTier` | 기본 `FREE` |
| `createdAt` | `DateTime` | |
| `updatedAt` | `DateTime` | |
**관계:** `GuildOwnership[]` (1:N)
---
### `GuildOwnership`
구독 사용자가 소유하는 길드.
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `guildId` | `String` | PK |
| `ownerId` | `String` | FK → `UserSubscription.userId`, `ON DELETE CASCADE` |
| `createdAt` | `DateTime` | |
**인덱스:** `ownerId`
---
### `VoiceGenerator`
음성 채널 생성기(부모 채널) 설정.
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `channelId` | `String` | PK |
| `guildId` | `String` | |
| `categoryId` | `String?` | |
| `createdAt` | `DateTime` | |
| `updatedAt` | `DateTime` | |
**인덱스:** `guildId`
---
### `TempVoiceChannel`
생성된 임시 음성 채널.
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `channelId` | `String` | PK |
| `guildId` | `String` | |
| `ownerId` | `String` | |
| `deleteWhen` | `DeleteCondition` | 기본 `EMPTY` |
| `createdAt` | `DateTime` | |
**인덱스:** `guildId`, `ownerId`
---
### `UserVoiceProfile`
길드별 사용자 음성 프로필(표시 이름·인원 제한 등).
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `userId` | `String` | 복합 PK |
| `guildId` | `String` | 복합 PK |
| `customName` | `String?` | |
| `userLimit` | `Int?` | |
| `createdAt` | `DateTime` | |
| `updatedAt` | `DateTime` | |
**PK:** `(userId, guildId)`
---
### `UserLocale`
사용자별 로케일.
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `userId` | `String` | PK |
| `locale` | `String` | |
| `createdAt` | `DateTime` | |
| `updatedAt` | `DateTime` | |
---
### `AuditChannel`
감사 로그 전달 채널·비활성 카테고리.
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `guildId` | `String` | PK |
| `channelId` | `String` | |
| `disabledCategories` | `String[]` | 기본 `["BOOT", "SYSTEM"]` |
| `createdAt` | `DateTime` | |
| `updatedAt` | `DateTime` | |
---
### `VoiceGuildConfig`
길드 단위 음성(임시 채널) 기본 설정.
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `guildId` | `String` | PK |
| `defaultNameTemplate` | `String` | 기본 `{{username}}'s Room` |
| `defaultUserLimit` | `Int` | 기본 `0` |
| `createdAt` | `DateTime` | |
| `updatedAt` | `DateTime` | |
---
### `GuildEvent`
길드 일정/이벤트.
| 컬럼 | 타입 | 제약 / 기본값 |
|------|------|----------------|
| `id` | `String` | PK, UUID |
| `guildId` | `String` | |
| `title` | `String` | |
| `description` | `String?` | |
| `startsAt` | `DateTime` | |
| `timezone` | `String` | 기본 `Asia/Seoul` |
| `status` | `EventStatus` | 기본 `SCHEDULED` |
| `announcementChannelId` | `String?` | |
| `createdByUserId` | `String` | |
| `reminderEnabled` | `Boolean` | 기본 `true` |
| `reminderOffsets` | `Int[]` | 기본 `[]` |
| `sentReminderOffsets` | `Int[]` | 기본 `[]` |
| `remindedOneHour` | `Boolean` | 기본 `false` |
| `remindedTenMinutes` | `Boolean` | 기본 `false` |
| `startedAnnounced` | `Boolean` | 기본 `false` |
| `announcedAt` | `DateTime?` | |
| `createdAt` | `DateTime` | |
| `updatedAt` | `DateTime` | |
**인덱스:** `(guildId, startsAt)`, `(guildId, status)`
---
## 관계 요약
```mermaid
erDiagram
UserSubscription ||--o{ GuildOwnership : "userId"
```
- **UserSubscription** 1 — N **GuildOwnership** (`ownerId` → `userId`, 길드 삭제 시 소유권 행 CASCADE 삭제)
그 외 테이블은 Prisma 모델상 **명시적 `relation` 블록**이 없으며, `guildId` / `userId` / `channelId` 등이 애플리케이션 레벨에서 Discord ID로 연결됩니다.
## 스키마 변경 시
실제 DDL은 `prisma/migrations/` 아래 마이그레이션 SQL과 동기화됩니다. 구조를 바꾼 뒤에는 이 문서와 [schema.prisma](../prisma/schema.prisma)를 함께 맞추는 것이 좋습니다.

View File

@ -2,6 +2,11 @@
이 루트 색인 문서는 프로젝트 내의 모든 구조화된 문서를 카테고리별로 모아 탐색을 돕기 위해 작성되었습니다. 이 루트 색인 문서는 프로젝트 내의 모든 구조화된 문서를 카테고리별로 모아 탐색을 돕기 위해 작성되었습니다.
## 아키텍처 및 시스템 (Architecture & System)
- [프로젝트 구조 (Project Structure)](Project_Structure.md)
- [데이터베이스 스키마 구조 (Database Schema)](database-schema.md)
## 정책 및 규칙 (Rules) ## 정책 및 규칙 (Rules)
- [보안 가이드라인 (Security Rules)](Rules/security_guidelines.md) - [보안 가이드라인 (Security Rules)](Rules/security_guidelines.md)
@ -10,6 +15,7 @@
## 기능 명세 (Features) ## 기능 명세 (Features)
- [임시 음성 채널 자동화 (Temp Voice Channels)](Features/temp_voice_channels.md) - [임시 음성 채널 자동화 (Temp Voice Channels)](Features/temp_voice_channels.md)
- [Graphify 설정 및 연동 가이드 (Graphify Setup Guide)](Features/Graphify_Setup_Guide.md)
## 기획서 (Plans) ## 기획서 (Plans)
@ -29,6 +35,7 @@
## 아키텍처 및 정책 결정 (Decisions) ## 아키텍처 및 정책 결정 (Decisions)
- [구독 티어 시스템 설계 (Subscription Tiers)](Decisions/subscription_tiers.md) - [구독 티어 시스템 설계 (Subscription Tiers)](Decisions/subscription_tiers.md)
- [대시보드-봇 통신 아키텍처 (Dashboard gRPC Architecture)](Decisions/Dashboard_Architecture_gRPC.md)
## 트러블슈팅 (Troubleshooting) ## 트러블슈팅 (Troubleshooting)
@ -61,3 +68,9 @@
- [2026-04-07: 낚시 미니게임 Phase 2 구현 (Fishing Mini-Game Phase 2 Implementation)](WorkDone/2026-04-07_Fishing_MiniGame_Phase2_Implementation.md) - [2026-04-07: 낚시 미니게임 Phase 2 구현 (Fishing Mini-Game Phase 2 Implementation)](WorkDone/2026-04-07_Fishing_MiniGame_Phase2_Implementation.md)
- [2026-04-07: 낚시 도감 및 크기 시스템 구현 (Fishing Dex and Size Implementation)](WorkDone/2026-04-07_Fishing_Dex_And_Size_Implementation.md) - [2026-04-07: 낚시 도감 및 크기 시스템 구현 (Fishing Dex and Size Implementation)](WorkDone/2026-04-07_Fishing_Dex_And_Size_Implementation.md)
- [2026-04-07: 낚시 크기 랭킹 구현 (Fishing Size Ranking Implementation)](WorkDone/2026-04-07_Fishing_Size_Ranking_Implementation.md) - [2026-04-07: 낚시 크기 랭킹 구현 (Fishing Size Ranking Implementation)](WorkDone/2026-04-07_Fishing_Size_Ranking_Implementation.md)
- [2026-04-20: 모노레포 전환 및 gRPC 통신 테스트 완료 (Monorepo & gRPC Test)](WorkDone/2026-04-20_Monorepo_Migration_And_gRPC_Test.md)
- [2026-04-21: README 로컬 접속 정보 업데이트 (README Local Connection Info Update)](WorkDone/2026-04-21_README_Local_Connection_Info_Update.md)
- [2026-04-21: gRPC Proto 파일 경로 인식 오류 수정 (gRPC Proto Path Resolution Fix)](WorkDone/2026-04-21_gRPC_Proto_Path_Resolution_Fix.md)
- [2026-04-21: 인프라 치명적 오류 복구 및 안정화 (Infrastructure Recovery & Stability)](WorkDone/2026-04-21_Infrastructure_Recovery_And_Stability.md)
- [2026-04-21: 대시보드 Turbopack Panic 현상 해결 (Fix Dashboard Turbopack Panic)](WorkDone/2026-04-21_fix_dashboard_panic.md)
- [2026-04-22: 테스트 프로세스 정리 (Process Cleanup)](WorkDone/2026-04-22_ProcessCleanup.md)

View File

@ -1,73 +1,81 @@
# Kord # Kord (Monorepo)
Kord는 Discord 서버 관리를 돕는 강력하고 유연한 다기능 봇입니다. Kord는 Discord 서버 관리를 돕는 강력하고 유연한 다기능 봇 및 전용 웹 대시보드 프로젝트입니다.
현재 모노레포(Monorepo) 구조로 관리되고 있습니다.
## 1. 개요 (Overview) ## 1. 프로젝트 구조 (Structure)
**Kord**는 효율적인 서버 운영을 위해 설계된 Discord 봇입니다. TypeScript와 Discord.js를 기반으로 구축되었으며, Prisma(PostgreSQL)를 활용하여 안정적이고 확장 가능한 아키텍처를 제공합니다. 임시 음성 채널 관리, 상세 감사 로그, 권한 진단 등의 핵심 기능을 통해 서버 관리자의 부담을 줄여줍니다. 본 프로젝트는 **Turborepo**와 **Yarn Workspaces**를 사용합니다.
- **`apps/bot`**: Discord.js 기반의 봇 본체 (ShardingManager 적용)
- **`apps/dashboard`**: Next.js 기반의 봇 관리 웹 대시보드
- **`packages/db`**: Prisma 스키마 및 데이터베이스 데이터 접근 레이어 (공용)
- **`packages/grpc-contracts`**: 봇과 대시보드 간의 gRPC 통신 규약 (공용)
## 2. 요구사항 (Requirements) ## 2. 요구사항 (Requirements)
- **Runtime**: Node.js v20 이상 - **Runtime**: Node.js v22 이상 (추천)
- **Package Manager**: Yarn v4 (Berry) - **Package Manager**: Yarn v4 (Berry)
- **Database**: PostgreSQL (Prisma 사용) - **Database**: PostgreSQL (Prisma 사용)
- **Discord**: Bot Token 및 Client ID (Slash Command 등록용) - **Discord**: Bot Token 및 Client ID
## 3. 테스트 방법 (Test Methods) ## 3. 시작하기 (Quick Start)
본 프로젝트는 Jest를 사용하여 유닛 테스트 및 통합 테스트를 수행합니다. ### 로컬 개발 환경 설정
- **전체 테스트 실행**:
```bash
yarn test
```
- **i18n 번역 누락 확인**:
```bash
yarn check-i18n
```
## 4. 구동 방법 (Running Methods)
### 로컬 개발 환경
1. **의존성 설치**: 1. **의존성 설치**:
```bash ```bash
yarn install yarn install
``` ```
2. **환경 변수 설정**: `.env.example` 파일을 복사하여 `.env` 파일을 생성하고 필수 값을 입력합니다. 2. **환경 변수 설정**: 루트 및 각 앱 디렉토리의 `.env` 설정을 완료합니다.
3. **데이터베이스 초기화**:
3. **데이터베이스 및 코드 생성**:
```bash ```bash
npx prisma migrate dev yarn run generate
npx prisma generate
``` ```
4. **개발 서버 실행**: ### 실행 방법
전체 프로젝트를 한꺼번에 실행하거나 개별 앱을 실행할 수 있습니다.
- **모든 앱 실행 (Bot + Dashboard)**:
```bash ```bash
yarn dev yarn dev
``` ```
### 프로덕션 환경 - **봇만 실행**:
```bash
yarn workspace @kord/bot dev
```
1. **빌드**: `yarn build` - **대시보드만 실행**:
2. **실행**: `yarn start` ```bash
3. **Docker**: `docker-compose up -d`를 통해 PostgreSQL 등 로컬 인프라를 실행할 수 있습니다. yarn workspace dashboard dev
```
## 5. 기능 목록 (Feature List) ## 5. 인프라 검증 (Infrastructure Verification)
- **임시 음성 채널 (Voice)**: 생성기(Generator) 채널을 통해 동적인 음성 채널 생성 및 관리 기능을 제공합니다. 인프라 설정(DB, gRPC, 환경 변수)이 올바른지 확인하려면 다음 스크립트를 실행합니다:
- **감사 로그 (Audit Log)**: 서버 내 주요 이벤트를 카테고리별(VOICE, PERMISSION, SYSTEM 등)로 세분화하여 기록합니다. ```bash
- **서버 설정 (Config)**: 따라하기(Mimic), 큰 이모지(Big Emoji) 등 봇의 기능을 서버별 환경에 맞게 토글하거나 설정할 수 있습니다. npx tsx scripts/verify-recovery.ts
- **권한 감사 (Permission Audit)**: 봇의 정상 작동을 방해하는 권한 문제를 즉시 진단하고 해결 방법을 안내합니다. ```
- **초기 설정 마법사 (Setup Wizard)**: 봇 도입 초기 기능을 한눈에 설정할 수 있는 직관적인 UI를 제공합니다.
- **미니게임 시스템 (Mini-Games)**: 서버 내에서 즐길 수 있는 다양한 미니게임을 제공하며, 관리자가 게임별 활성화 및 전용 채널을 설정할 수 있습니다. ## 6. 로컬 접속 정보 (Local Connection Info)
- **재련 (Refinement)**: 무기를 강화하고 다른 유저와 전투하며 골드를 획득하는 성장형 미니게임입니다.
- **피버 타임 (Fever Time)**: 서버 활동량을 자동으로 분석하여 가장 활발한 시간대에 재련 성공 확률 보너스를 제공합니다. 로컬에서 개발 및 테스트 시 다음 주소를 사용합니다.
- **다국어 지원 (i18n)**: 한국어와 영어를 포함한 다국어 환경을 지원합니다.
- **웹 대시보드 (Dashboard)**: [http://localhost:3000](http://localhost:3000)
- **gRPC 프록시 서버 (Bot Proxy)**: `localhost:50051` (대시보드와 봇 간 통신)
- **데이터베이스 (PostgreSQL)**: `localhost:5432`
## 5. 아키텍처 (Architecture)
Kord는 **gRPC Proxy** 아키텍처를 사용하여 대시보드와 샤딩된 봇 인스턴스 간의 실시간 통신을 처리합니다. 자세한 내용은 관련 문서를 참조하세요.
- [대시보드 통신 아키텍처 가이드](Docs/Decisions/Dashboard_Architecture_gRPC.md)
## 5. 문서 (Documentation)
모둔 상세 문서는 `Docs/` 디렉토리에 위치합니다.
- [문서 전체 색인 (Docs Index)](Docs/index.md)
- [로컬 가이드북 (SKILL.md)](SKILL.md)

855
SKILL.md Normal file
View File

@ -0,0 +1,855 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
trigger: /graphify
---
# /graphify
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
## Usage
```
/graphify # full pipeline on current directory → Obsidian vault
/graphify <path> # full pipeline on specific path
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
/graphify add <url> # fetch URL, save to ./raw, update graph
/graphify add <url> --author "Name" # tag who wrote it
/graphify add <url> --contributor "Name" # tag who added it to the corpus
/graphify query "<question>" # BFS traversal - broad context
/graphify query "<question>" --dfs # DFS - trace a specific path
/graphify query "<question>" --budget 1500 # cap answer at N tokens
/graphify path "AuthModule" "Database" # shortest path between two concepts
/graphify explain "SwinTransformer" # plain-language explanation of a node
/graphify <path> --ollama # use local Ollama for semantic extraction
/graphify <path> --ollama --model gemma4 # use specific Ollama model (default: llama3)
```
## What graphify is for
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
Three things it does that Claude alone cannot:
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
Use it for:
- A codebase you're new to (understand architecture before touching anything)
- A reading list (papers + tweets + notes → one navigable graph)
- A research corpus (citation graph + concept graph in one)
- Your personal /raw folder (drop everything in, let it grow, query it)
## What You Must Do When Invoked
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
### Step 1 - Ensure graphify is installed
```bash
# Detect the correct Python interpreter (handles pipx, venv, system installs)
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
else
PYTHON="python3"
fi
$PYTHON -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
# Write interpreter path for all subsequent steps
$PYTHON -c "import sys; open('.graphify_python', 'w').write(sys.executable)"
# Check Ollama connectivity
OLLAMA_UP=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:11434/api/tags 2>/dev/null)
if [ "$OLLAMA_UP" = "200" ]; then
echo "Ollama: CONNECTED"
$PYTHON -c "import json; print(json.dumps([m['name'] for m in json.loads(open('.ollama_tags.json').read()).get('models', [])]))" > .ollama_models.json 2>/dev/null || (curl -s http://localhost:11434/api/tags > .ollama_tags.json && $PYTHON -c "import json; print(json.dumps([m['name'] for m in json.loads(open('.ollama_tags.json').read()).get('models', [])]))" > .ollama_models.json && rm .ollama_tags.json)
else
echo "Ollama: DISCONNECTED"
rm -f .ollama_models.json
fi
```
If the import succeeds, print nothing and move straight to Step 2.
**In every subsequent bash block, replace `python3` with `$(cat .graphify_python)` to use the correct interpreter.**
### Step 2 - Detect files
```bash
$(cat .graphify_python) -c "
import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
print(json.dumps(result))
" > .graphify_detect.json
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
code: N files (.py .ts .go ...)
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
```
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 3 - no need to ask anything.
### Step 3 - Extract entities and relationships
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
#### Part A - Structural extraction for code files
For any code files detected, run AST extraction in parallel with Part B subagents:
```bash
$(cat .graphify_python) -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
code_files = []
detect = json.loads(Path('.graphify_detect.json').read_text())
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files)
Path('.graphify_ast.json').write_text(json.dumps(result, indent=2))
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
print('No code files - skipping AST extraction')
"
```
#### Part B - Semantic extraction (parallel subagents or local LLM)
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do.
**Ollama Choice:** If Ollama is CONNECTED (check `.ollama_models.json`) AND `--ollama` was given:
Run semantic extraction locally for each chunk of files.
```bash
$(cat .graphify_python) -c "
import json
from graphify.semantic_llm import extract_semantic
from pathlib import Path
uncached = Path('.graphify_uncached.txt').read_text().splitlines()
# Split into chunks of 15 files (local models are slower)
chunks = [uncached[i:i + 15] for i in range(0, len(uncached), 15)]
all_results = {'nodes': [], 'edges': [], 'hyperedges': [], 'input_tokens': 0, 'output_tokens': 0}
model = 'MODEL_NAME' # Use --model value or 'llama3' or first found in .ollama_models.json
deep = DEEP_MODE_VAR # True if --mode deep
for i, chunk in enumerate(chunks):
print(f'Local Extraction: chunk {i+1}/{len(chunks)} ({len(chunk)} files)...')
res = extract_semantic(chunk, model=model, deep_mode=deep)
all_results['nodes'].extend(res.get('nodes', []))
all_results['edges'].extend(res.get('edges', []))
all_results['hyperedges'].extend(res.get('hyperedges', []))
Path('.graphify_semantic_new.json').write_text(json.dumps(all_results, indent=2))
"
```
**Otherwise (Cloud Model - DEFAULT):**
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
Before dispatching subagents, print a timing estimate:
- Load `total_words` and file counts from `.graphify_detect.json`
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
**Step B0 - Check extraction cache first**
Before dispatching any subagents, check which files already have cached extraction results:
```bash
$(cat .graphify_python) -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('.graphify_detect.json').read_text())
all_files = [f for files in detect['files'].values() for f in files]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges or cached_hyperedges:
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
```
Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
**Step B1 - Split into chunks**
Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context).
**Step B2 - Dispatch ALL subagents in a single message**
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
Concrete example for 3 chunks:
```
[Agent tool call 1: files 1-15]
[Agent tool call 2: files 16-30]
[Agent tool call 3: files 31-45]
```
All three in one message. Not three separate messages.
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE):
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
FILE_LIST
Rules:
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
- INFERRED: reasonable inference (shared data structure, implied dependency)
- AMBIGUOUS: uncertain - flag for review, do not omit
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
Chart: metric, trend/insight, data source.
Tweet/post: claim as node, author, concepts mentioned.
Diagram: components and connections.
Research figure: what it demonstrates, method, result.
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,
shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:
- Two functions that both validate user input but never call each other
- A class in code and a concept in a paper that describe the same algorithm
- Two error types that handle the same failure mode differently
Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:
- All classes that implement a common protocol or interface
- All functions in an authentication flow (even if they don't all call each other)
- All concepts from a paper section that form one coherent idea
Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
contributor onto every node from that file.
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
```
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed, stop and tell the user.
Save new results to cache:
```bash
$(cat .graphify_python) -c "
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
print(f'Cached {saved} files')
"
```
Merge cached + new results into `.graphify_semantic.json`:
```bash
$(cat .graphify_python) -c "
import json
from pathlib import Path
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
seen = set()
deduped = []
for n in all_nodes:
if n['id'] not in seen:
seen.add(n['id'])
deduped.append(n)
merged = {
'nodes': deduped,
'edges': all_edges,
'hyperedges': all_hyperedges,
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
"
```
Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```bash
$(cat .graphify_python) -c "
import sys, json
from pathlib import Path
ast = json.loads(Path('.graphify_ast.json').read_text())
sem = json.loads(Path('.graphify_semantic.json').read_text())
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
merged_nodes = list(ast['nodes'])
for n in sem['nodes']:
if n['id'] not in seen:
merged_nodes.append(n)
seen.add(n['id'])
merged_edges = ast['edges'] + sem['edges']
merged_hyperedges = sem.get('hyperedges', [])
merged = {
'nodes': merged_nodes,
'edges': merged_edges,
'hyperedges': merged_hyperedges,
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2))
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
"
```
### Step 4 - Build graph, cluster, analyze, generate outputs
```bash
mkdir -p graphify-out
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
detection = json.loads(Path('.graphify_detect.json').read_text())
G = build_from_json(extraction)
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
# Placeholder questions - regenerated with real labels in Step 5
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
to_json(G, communities, 'graphify-out/graph.json')
analysis = {
'communities': {str(k): v for k, v in communities.items()},
'cohesion': {str(k): v for k, v in cohesion.items()},
'gods': gods,
'surprises': surprises,
'questions': questions,
}
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
"
```
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
### Step 5 - Label communities
Read `.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
```bash
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
detection = json.loads(Path('.graphify_detect.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
# LABELS - replace these with the names you chose above
labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
print('Report updated with community labels')
"
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
If `--obsidian` was given:
- If `--obsidian-dir <path>` was also given, use that path as the vault directory. Otherwise default to `graphify-out/obsidian`.
```bash
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_obsidian, to_canvas
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
labels = {int(k): v for k, v in labels_raw.items()}
obsidian_dir = 'OBSIDIAN_DIR' # replace with --obsidian-dir value, or 'graphify-out/obsidian' if not given
n = to_obsidian(G, communities, obsidian_dir, community_labels=labels or None, cohesion=cohesion)
print(f'Obsidian vault: {n} notes in {obsidian_dir}/')
to_canvas(G, communities, f'{obsidian_dir}/graph.canvas', community_labels=labels or None)
print(f'Canvas: {obsidian_dir}/graph.canvas - open in Obsidian for structured community layout')
print()
print(f'Open {obsidian_dir}/ as a vault in Obsidian.')
print(' Graph view - nodes colored by community (set automatically)')
print(' graph.canvas - structured layout with communities as groups')
print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries')
"
```
Generate the HTML graph (always, unless `--no-viz`):
```bash
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_html
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
labels = {int(k): v for k, v in labels_raw.items()}
if G.number_of_nodes() > 5000:
print(f'Graph has {G.number_of_nodes()} nodes - too large for HTML viz. Use Obsidian vault instead.')
else:
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
print('graph.html written - open in any browser, no server needed')
"
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_cypher
from pathlib import Path
G = build_from_json(json.loads(Path('.graphify_extract.json').read_text()))
to_cypher(G, 'graphify-out/cypher.txt')
print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt')
"
```
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```bash
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.export import push_to_neo4j
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
result = push_to_neo4j(G, uri='NEO4J_URI', user='NEO4J_USER', password='NEO4J_PASSWORD', communities=communities)
print(f'Pushed to Neo4j: {result[\"nodes\"]} nodes, {result[\"edges\"]} edges')
"
```
Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7b - SVG export (only if --svg flag)
```bash
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_svg
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
labels = {int(k): v for k, v in labels_raw.items()}
to_svg(G, communities, 'graphify-out/graph.svg', community_labels=labels or None)
print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
"
```
### Step 7c - GraphML export (only if --graphml flag)
```bash
$(cat .graphify_python) -c "
import json
from graphify.build import build_from_json
from graphify.export import to_graphml
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
to_graphml(G, communities, 'graphify-out/graph.graphml')
print('graph.graphml written - open in Gephi, yEd, or any GraphML tool')
"
```
### Step 7d - MCP server (only if --mcp flag)
```bash
python3 -m graphify.serve graphify-out/graph.json
```
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
To configure in Claude Desktop, add to `claude_desktop_config.json`:
```json
{
"mcpServers": {
"graphify": {
"command": "python3",
"args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
}
}
}
```
### Step 8 - Token reduction benchmark (only if total_words > 5000)
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
```bash
$(cat .graphify_python) -c "
import json
from graphify.benchmark import run_benchmark, print_benchmark
from pathlib import Path
detection = json.loads(Path('.graphify_detect.json').read_text())
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
print_benchmark(result)
"
```
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.
---
### Step 9 - Save manifest, update cost tracker, clean up, and report
```bash
$(cat .graphify_python) -c "
import json
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('.graphify_detect.json').read_text())
save_manifest(detect['files'])
# Update cumulative cost tracker
extract = json.loads(Path('.graphify_extract.json').read_text())
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
if cost_path.exists():
cost = json.loads(cost_path.read_text())
else:
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
cost['runs'].append({
'date': datetime.now(timezone.utc).isoformat(),
'input_tokens': input_tok,
'output_tokens': output_tok,
'files': detect.get('total_files', 0),
})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2))
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_python
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Tell the user (omit the obsidian line unless --obsidian was given):
```
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
graph.html - interactive graph, open in browser
GRAPH_REPORT.md - audit report
graph.json - raw graph data
obsidian/ - Obsidian vault (only if --obsidian was given)
```
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
- God Nodes
- Surprising Connections
- Suggested Questions
Do NOT paste the full report - just those three sections. Keep it concise.
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
The graph is the map. Your job after the pipeline is to be the guide.
---
## For --update (incremental re-extraction)
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
```bash
$(cat .graphify_python) -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
If new files exist, first check whether all changed files are code files:
```bash
$(cat .graphify_python) -c "
import json
from pathlib import Path
result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
print('code_only:', code_only)
"
```
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 48.
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A3C pipeline as normal.
Then:
```bash
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
# Load existing graph
existing_data = json.loads(Path('graphify-out/graph.json').read_text())
G_existing = json_graph.node_link_graph(existing_data, edges='links')
# Load new extraction
new_extraction = json.loads(Path('.graphify_extract.json').read_text())
G_new = build_from_json(new_extraction)
# Merge: new nodes/edges into existing graph
G_existing.update(G_new)
print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges')
"
```
Then run Steps 48 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
$(cat .graphify_python) -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
# Load old graph (before update) from backup written before merge
old_data = json.loads(Path('.graphify_old.json').read_text()) if Path('.graphify_old.json').exists() else None
new_extract = json.loads(Path('.graphify_extract.json').read_text())
G_new = build_from_json(new_extract)
if old_data:
G_old = json_graph.node_link_graph(old_data, edges='links')
diff = graph_diff(G_old, G_new)
print(diff['summary'])
if diff['new_nodes']:
print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))
if diff['new_edges']:
print('New edges:', len(diff['new_edges']))
"
```
Before the merge step, save the old graph: `cp graphify-out/graph.json .graphify_old.json`
Clean up after: `rm -f .graphify_old.json`
---
## For --cluster-only
Skip Steps 13. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
```bash
$(cat .graphify_python) -c "
import sys, json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections
from graphify.report import generate
from graphify.export import to_json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None, 'files': {}}
communities = cluster(G)
cohesion = score_all(G, communities)
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
report = generate(G, communities, cohesion, labels, gods, surprises, detection, {'input':0,'output':0}, 'INPUT_PATH')
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
to_json(G, communities, 'graphify-out/graph.json')
print(f'Re-clustered: {len(communities)} communities')
"
```
Then proceed to Step 5 (Labeling) as normal.

View File

@ -2,7 +2,7 @@ FROM node:20-alpine AS builder
WORKDIR /app WORKDIR /app
COPY package.json yarn.lock .yarnrc.yml ./ COPY package.json yarn.lock .yarnrc.yml ./
COPY .yarn ./.yarn COPY .yarn ./.yarn
RUN corepack enable && yarn install RUN corepack enable && yarn install --immutable
# Generate Prisma Client # Generate Prisma Client
COPY prisma ./prisma/ COPY prisma ./prisma/
@ -17,9 +17,8 @@ FROM node:20-alpine AS runner
WORKDIR /app WORKDIR /app
COPY package.json yarn.lock .yarnrc.yml ./ COPY package.json yarn.lock .yarnrc.yml ./
COPY .yarn ./.yarn COPY .yarn ./.yarn
RUN corepack enable && yarn install RUN corepack enable && yarn install --immutable --production
COPY --from=builder /app/node_modules/@prisma/client ./node_modules/@prisma/client
COPY --from=builder /app/dist ./dist COPY --from=builder /app/dist ./dist
CMD ["yarn", "node", "dist/index.js"] CMD ["node", "dist/index.js"]

33
apps/bot/package.json Normal file
View File

@ -0,0 +1,33 @@
{
"name": "@kord/bot",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"test": "jest",
"check-i18n": "tsx scripts/check-i18n-tests.ts"
},
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@discordjs/voice": "^0.19.2",
"@grpc/grpc-js": "^1.14.3",
"@kord/db": "workspace:*",
"@kord/grpc-contracts": "workspace:*",
"discord.js": "^14.25.1",
"dotenv": "^17.3.1",
"ffmpeg-static": "^5.3.0",
"log4js": "^6.9.1",
"prism-media": "^1.3.5",
"sharp": "^0.34.5",
"youtubei.js": "^17.0.1"
},
"devDependencies": {
"@types/jest": "^30.0.0",
"@types/node": "^25.5.0",
"jest": "^30.3.0",
"ts-jest": "^29.4.6",
"tsx": "^4.21.0"
}
}

View File

@ -0,0 +1,10 @@
const path = require('path');
console.log('CWD:', process.cwd());
console.log('__dirname:', __dirname);
console.log('.env path:', path.resolve(process.cwd(), '.env'));
const fs = require('fs');
console.log('.env exists in CWD?', fs.existsSync(path.resolve(process.cwd(), '.env')));
console.log('.env exists in root?', fs.existsSync(path.resolve(process.cwd(), '../../.env')));
require('dotenv').config({ path: path.resolve(process.cwd(), '../../.env') });
console.log('DATABASE_URL from ../../.env:', process.env.DATABASE_URL);

View File

@ -7,6 +7,7 @@ import { handleGlobalExceptions } from '../utils/errorHandler';
import { connectDB } from '../database'; import { connectDB } from '../database';
import { FeverService } from '../services/FeverService'; import { FeverService } from '../services/FeverService';
export class KordClient extends Client { export class KordClient extends Client {
public commands: Collection<string, any> = new Collection(); public commands: Collection<string, any> = new Collection();
@ -17,8 +18,10 @@ export class KordClient extends Client {
GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent, GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildInvites, GatewayIntentBits.GuildInvites,
], ],
partials: [Partials.Message, Partials.Channel, Partials.GuildMember], partials: [Partials.Message, Partials.Channel, Partials.GuildMember],
}); });
} }

View File

@ -0,0 +1,74 @@
import {
SlashCommandBuilder,
ChatInputCommandInteraction,
PermissionFlagsBits,
EmbedBuilder,
Colors,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
RoleSelectMenuBuilder,
ComponentType
} from 'discord.js';
import { Command, CommandTrait } from '../core/command';
import { autoRoleService } from '../services/AutoRoleService';
import { t, SupportedLocale } from '../i18n';
class AutoRoleCommand extends Command {
protected override readonly trait = CommandTrait.General;
protected override guildOnly = true;
protected override define() {
return new SlashCommandBuilder()
.setName('autorole')
.setDescription('Configure automatic role assignment upon joining.')
.setDescriptionLocalizations({
ko: '입장 시 역할을 자동으로 부여하는 기능을 설정합니다.',
})
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator);
}
protected override async handle(interaction: ChatInputCommandInteraction, locale: SupportedLocale) {
const guild = interaction.guild!;
const dashboard = await generateAutoRoleDashboard(guild, locale);
await interaction.editReply({
...dashboard
});
}
}
export async function generateAutoRoleDashboard(guild: import('discord.js').Guild, locale: SupportedLocale) {
const config = await autoRoleService.getConfig(guild.id);
const embed = new EmbedBuilder()
.setTitle(t(locale, 'commands.autorole.statusTitle'))
.setColor(Colors.Blue)
.setDescription(t(locale, 'commands.autorole.description') || '유저 및 봇이 서버에 접속할 때 자동으로 부여할 기본 역할을 선택하세요. 역할을 선택하면 즉시 활성화됩니다.');
const userSelect = new RoleSelectMenuBuilder()
.setCustomId('autorole_select_user')
.setPlaceholder(t(locale, 'commands.autorole.userRolePlaceholder'))
.setMaxValues(10);
if (config?.userRoleIds && config.userRoleIds.length > 0) {
userSelect.addDefaultRoles(config.userRoleIds);
}
const rowUserRole = new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(userSelect);
const botSelect = new RoleSelectMenuBuilder()
.setCustomId('autorole_select_bot')
.setPlaceholder(t(locale, 'commands.autorole.botRolePlaceholder'))
.setMaxValues(10);
if (config?.botRoleIds && config.botRoleIds.length > 0) {
botSelect.addDefaultRoles(config.botRoleIds);
}
const rowBotRole = new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(botSelect);
return {
embeds: [embed],
components: [rowUserRole, rowBotRole]
};
}
export default new AutoRoleCommand().toModule();

View File

@ -1,9 +1,21 @@
import { config } from 'dotenv'; import { config } from 'dotenv';
import { existsSync } from 'fs';
import { hostname } from 'os'; import { hostname } from 'os';
import { resolve } from 'path'; import { resolve } from 'path';
// Prefer systemd/cron-set DOTENV_CONFIG_PATH; otherwise cwd .env (default dotenv behavior). const getEnvPath = () => {
config({ path: process.env.DOTENV_CONFIG_PATH || resolve(process.cwd(), '.env') }); if (process.env.DOTENV_CONFIG_PATH) return process.env.DOTENV_CONFIG_PATH;
const localEnv = resolve(process.cwd(), '.env');
if (existsSync(localEnv)) return localEnv;
const rootEnv = resolve(process.cwd(), '../../.env');
if (existsSync(rootEnv)) return rootEnv;
return localEnv;
};
config({ path: getEnvPath() });
const generateInstanceId = () => { const generateInstanceId = () => {
return process.env.INSTANCE_ID || hostname() || `kord-${Math.random().toString(36).substring(2, 7)}`; return process.env.INSTANCE_ID || hostname() || `kord-${Math.random().toString(36).substring(2, 7)}`;

View File

@ -0,0 +1,232 @@
import {
SlashCommandBuilder,
SlashCommandOptionsOnlyBuilder,
SlashCommandSubcommandsOnlyBuilder,
ChatInputCommandInteraction,
} from 'discord.js';
/** Values returned from {@link SlashCommandBuilder} after chaining options or subcommands only. */
export type SlashCommandData =
| SlashCommandBuilder
| SlashCommandOptionsOnlyBuilder
| SlashCommandSubcommandsOnlyBuilder;
import { prisma } from '../database';
import { SupportedLocale } from '../i18n';
import { SubscriptionTier } from '@prisma/client';
/**
* · .
*
* - help , , , .
* - `Command` .
*/
export enum CommandTrait {
/** 음악 재생·대기열 등 */
Music = 'music',
/** 미니게임 */
Minigame = 'minigame',
/** 방송 연동·알림 등 */
Broadcast = 'broadcast',
/** 위에 해당하지 않는 일반 명령(설정·감사·음성 등) */
General = 'general',
}
/** {@link CommandTrait.General}을 제외한 특성은 `guild_payment` 플래그가 필요합니다. */
export function traitRequiresPayment(trait: CommandTrait): boolean {
return (
trait === CommandTrait.Music || trait === CommandTrait.Minigame || trait === CommandTrait.Broadcast
);
}
/**
* .
*
* @returns `true`. `reply` `false`.
*/
export async function ensureGuildPaidForTrait(
interaction: ChatInputCommandInteraction,
trait: CommandTrait,
): Promise<boolean> {
if (!traitRequiresPayment(trait)) {
return true;
}
const guildId = interaction.guildId;
if (!guildId) {
const content = '이 명령은 서버에서만 사용할 수 있습니다.';
if (interaction.deferred || interaction.replied) {
await interaction.editReply({ content });
} else {
await interaction.reply({ content, ephemeral: true });
}
return false;
}
// Payment flags were replaced by subscription tiers.
// A guild is considered "paid" if it has an owner whose subscription tier is above FREE.
const ownership = await prisma.guildOwnership.findUnique({
where: { guildId },
include: { owner: true },
});
const paid = ownership?.owner?.tier != null && ownership.owner.tier !== SubscriptionTier.FREE;
if (!paid) {
const content = '결제가 되지않았습니다';
if (interaction.deferred || interaction.replied) {
await interaction.editReply({ content });
} else {
await interaction.reply({ content, ephemeral: true });
}
return false;
}
return true;
}
/**
* `CommandLoader` .
*
* `src/handlers/CommandLoader.ts` `default` export가
* `data`( ) `execute`( ) ,
* `client.commands.set(command.data.name, command)` .
* , .
*
* `trait` {@link Command.toModule} , .
*/
export type CommandModule = {
data: SlashCommandData;
execute: (interaction: ChatInputCommandInteraction, locale: SupportedLocale) => Promise<void>;
trait?: CommandTrait;
};
/**
* .
*
* ** **
* 1. {@link trait} {@link CommandTrait} .
* 2. {@link define} `SlashCommandBuilder` ··· .
* 3. {@link handle} (·DB· ) .
* 4. `export default new MyCommand().toModule()` `toModule()`
* `commands/*.ts` (`trait` ).
*
* ** ** (`interactionCreate` `execute`)
* 1. `guildOnly === true` DM .
* 2. {@link CommandTrait.Music} / {@link CommandTrait.Minigame} / {@link CommandTrait.Broadcast}
* `guild_payment` `true` . ( ·`false` )
* 3. {@link beforeHandle} `false` ( ) {@link handle} .
* 4. {@link handle} .
*
* `events/interactionCreate.ts` resolve한 `command.execute(interaction, locale)` ,
* -only .
*/
export abstract class Command {
private cachedData: SlashCommandData | null = null;
/**
* . .
*
* : 음악 {@link CommandTrait.Music}, {@link CommandTrait.Minigame},
* {@link CommandTrait.Broadcast}, {@link CommandTrait.General}.
*/
protected abstract readonly trait: CommandTrait;
/**
* `true` **() ** .
*
* DM이나 {@link handle}
* (ephemeral) return .
* (·· ) .
*/
protected guildOnly = false;
/**
* .
*
* {@link define} .
* `data` .
*/
get data(): SlashCommandData {
if (!this.cachedData) {
this.cachedData = this.define();
}
return this.cachedData;
}
/**
* (, , , , , `setDefaultMemberPermissions` )
* `SlashCommandBuilder` .
*/
protected abstract define(): SlashCommandData;
/**
* .
*
* `interaction` , `locale` / resolve된 .
*/
protected abstract handle(
interaction: ChatInputCommandInteraction,
locale: SupportedLocale,
): Promise<void>;
/**
* {@link handle} .
*
* , rate limit, ** **
* .
*
* @returns `true` {@link handle} .
* `false` ** `reply`/`deferReply` **
* `handle` .
*/
protected async beforeHandle(
_interaction: ChatInputCommandInteraction,
_locale: SupportedLocale,
): Promise<boolean> {
return true;
}
/**
* / .
*
* -only {@link ensureGuildPaidForTrait} `beforeHandle` `handle` .
* .
*/
async execute(
interaction: ChatInputCommandInteraction,
locale: SupportedLocale,
): Promise<void> {
if (this.guildOnly && !interaction.inGuild()) {
const content = 'This command can only be used in a server.';
if (interaction.deferred || interaction.replied) {
await interaction.editReply({ content });
} else {
await interaction.reply({ content, ephemeral: true });
}
return;
}
if (!(await ensureGuildPaidForTrait(interaction, this.trait))) {
return;
}
if (!(await this.beforeHandle(interaction, locale))) {
return;
}
await this.handle(interaction, locale);
}
/**
* `CommandModule` `default export` .
*
* `execute` , `this` .
*/
toModule(): CommandModule {
return {
data: this.data,
execute: (interaction, locale) => this.execute(interaction, locale),
trait: this.trait,
};
}
}

49
apps/bot/src/core/db.ts Normal file
View File

@ -0,0 +1,49 @@
import { Prisma, PrismaClient } from '@prisma/client';
import { prisma } from '../database';
export type DbClient = PrismaClient;
export type TxClient = Prisma.TransactionClient;
function isRootClient(client: DbClient | TxClient): client is DbClient {
return typeof (client as DbClient).$transaction === 'function';
}
/**
* Runs `fn` inside a DB transaction.
*
* - If `fn` throws/rejects, **all operations are rolled back**.
* - Prefer this over array-based transactions when you need multiple steps
* (reads + conditional writes) to be atomic.
*/
export async function transaction<T>(
fn: (tx: TxClient) => Promise<T>,
options?: {
maxWait?: number;
timeout?: number;
isolationLevel?: Prisma.TransactionIsolationLevel;
},
): Promise<T> {
return prisma.$transaction(fn, options);
}
/**
* Utility to support both "already in a transaction" and "start a new one".
*
* If `client` is a root PrismaClient, it starts a transaction.
* If `client` is already a TransactionClient, it reuses it.
*/
export async function withTransaction<T>(
client: DbClient | TxClient,
fn: (tx: TxClient) => Promise<T>,
options?: {
maxWait?: number;
timeout?: number;
isolationLevel?: Prisma.TransactionIsolationLevel;
},
): Promise<T> {
if (isRootClient(client)) {
return client.$transaction(fn, options);
}
return fn(client);
}

View File

@ -38,6 +38,11 @@ export const prisma = new PrismaClient({
}); });
export const connectDB = async () => { export const connectDB = async () => {
if (!env.DATABASE_URL) {
logger.error('DATABASE_URL is not set. Please check your .env file.');
process.exit(1);
}
try { try {
// Adapter-based client connects when first used, // Adapter-based client connects when first used,
// but we can test the pool connection here. // but we can test the pool connection here.
@ -46,6 +51,9 @@ export const connectDB = async () => {
logger.info('Connected to PostgreSQL successfully via Driver Adapter.'); logger.info('Connected to PostgreSQL successfully via Driver Adapter.');
} catch (error) { } catch (error) {
logger.error('Failed to connect to PostgreSQL:', error); logger.error('Failed to connect to PostgreSQL:', error);
if (error instanceof Error && error.message.includes('password')) {
logger.error('Database authentication failed. Please check your DATABASE_URL password.');
}
process.exit(1); process.exit(1);
} }
}; };

View File

@ -1,12 +1,10 @@
import { Events, Guild } from 'discord.js'; import { Events, Guild } from 'discord.js';
import { InviteService } from '../services/InviteService';
import { PresenceService } from '../services/PresenceService'; import { PresenceService } from '../services/PresenceService';
export default { export default {
name: Events.GuildCreate, name: Events.GuildCreate,
once: false, once: false,
async execute(guild: Guild) { async execute(guild: Guild) {
await InviteService.cacheGuildInvites(guild);
PresenceService.updatePresence(guild.client); PresenceService.updatePresence(guild.client);
}, },
}; };

View File

@ -1,10 +1,10 @@
import { Events, GuildMember } from 'discord.js'; import { Events, GuildMember } from 'discord.js';
import { InviteService } from '../services/InviteService'; import { autoRoleService } from '../services/AutoRoleService';
export default { export default {
name: Events.GuildMemberAdd, name: Events.GuildMemberAdd,
once: false, once: false,
async execute(member: GuildMember) { async execute(member: GuildMember) {
await InviteService.handleMemberAdd(member); await autoRoleService.handleMemberJoin(member);
}, },
}; };

View File

@ -145,6 +145,40 @@ export default {
}, locale); }, locale);
} }
} }
else if (interaction.isButton() && interaction.customId.startsWith('autorole_')) {
const locale = await getInteractionLocale(interaction);
const { autoRoleService } = require('../services/AutoRoleService');
await withErrorHandler(interaction, async () => {
// 타임아웃 방지를 위해 즉시 승인
await interaction.deferUpdate();
// 나머지 버튼 처리 (현재 사용 안함)
}, locale);
}
else if (interaction.isRoleSelectMenu() && interaction.customId.startsWith('autorole_select_')) {
const locale = await getInteractionLocale(interaction);
const { autoRoleService } = require('../services/AutoRoleService');
await withErrorHandler(interaction, async () => {
// 타임아웃 방지를 위해 즉시 승인
await interaction.deferUpdate();
const guild = interaction.guild!;
const isBot = interaction.customId.includes('bot');
const roleIds = interaction.values;
await autoRoleService.updateConfig(guild.id, {
[isBot ? 'botRoleIds' : 'userRoleIds']: roleIds
});
const { generateAutoRoleDashboard } = require('../commands/autorole');
const dashboard = await generateAutoRoleDashboard(guild, locale);
await interaction.editReply({
content: '',
...dashboard
});
}, locale);
}
else if (interaction.isModalSubmit()) { else if (interaction.isModalSubmit()) {
const customId = interaction.customId; const customId = interaction.customId;
if (customId.startsWith('modal_vc_')) { if (customId.startsWith('modal_vc_')) {

View File

@ -1,28 +1,36 @@
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { KordClient } from '../client/KordClient'; import { KordClient } from '../client/KordClient';
import { logger } from '../utils/logger'; import { logger } from '../utils/logger';
import { InviteService } from '../services/InviteService';
import { VoiceService } from '../services/VoiceService'; import { VoiceService } from '../services/VoiceService';
import { PresenceService } from '../services/PresenceService'; import { PresenceService } from '../services/PresenceService';
import { EventService } from '../services/EventService'; import { EventService } from '../services/EventService';
import { auditLogService } from '../services/AuditLogService'; import { auditLogService } from '../services/AuditLogService';
import { env } from '../config/env';
import { env } from '../config/env';
import { PrismaShardStatusRepository } from '@kord/db';
import { prisma } from '../database';
export default { export default {
name: Events.ClientReady, name: Events.ClientReady,
once: true, once: true,
async execute(client: KordClient) { async execute(client: KordClient) {
logger.info(`Ready! Logged in as ${client.user?.tag}`); logger.info(`Ready! Logged in as ${client.user?.tag}`);
await InviteService.cacheAllInvites(client);
await VoiceService.syncChannels(client); await VoiceService.syncChannels(client);
PresenceService.startActivePresence(client); PresenceService.startActivePresence(client);
EventService.startReminderLoop(client); EventService.startReminderLoop(client);
const shardId = client.shard?.ids[0] ?? 0;
const guildIds = Array.from(client.guilds.cache.keys());
const shardRepo = new PrismaShardStatusRepository(prisma);
await shardRepo.upsertStatus(shardId, 'READY', guildIds)
.catch((e: Error) => logger.error('Failed to update shard status:', e));
try { try {
const commandsData = Array.from(client.commands.values()).map(c => c.data.toJSON()); const commandsData = Array.from(client.commands.values()).map(c => c.data.toJSON());
await client.application?.commands.set(commandsData); await client.application?.commands.set(commandsData);
logger.info(`Successfully registered ${commandsData.length} global application commands.`); logger.info(`Successfully registered ${commandsData.length} global application commands.`);
} catch (e) { } catch (e) {
logger.error('Failed to register global commands', e); logger.error('Failed to register global commands', e);
} }

View File

@ -191,6 +191,26 @@ export const en: TranslationSchema = {
status: 'Status', status: 'Status',
}, },
}, },
autorole: {
description: 'Configure automatic role assignment upon joining.',
statusTitle: 'Auto Role Configuration Status',
userRoleLabel: 'User Role',
botRoleLabel: 'Bot Role',
statusLabel: 'User Auto Assignment',
botStatusLabel: 'Bot Auto Assignment',
userRolePlaceholder: 'Select default user role',
botRolePlaceholder: 'Select default bot role',
toggleUserEnable: '🟢 Enable User AutoRole',
toggleUserDisable: '🔴 Disable User AutoRole',
toggleBotEnable: '🟢 Enable Bot AutoRole',
toggleBotDisable: '🔴 Disable Bot AutoRole',
notSet: 'Not Set',
enabled: 'Enabled',
disabled: 'Disabled',
updateSuccess: 'Auto role settings have been updated.',
permissionsError: 'Failed to assign role due to low bot hierarchy or missing permissions.',
suspendNotice: 'Auto role assignment has been suspended due to insufficient permissions. Please check the bot\'s permissions and role hierarchy.',
},
music: { music: {
description: 'Play YouTube audio in voice channels.', description: 'Play YouTube audio in voice channels.',
addDescription: 'Search YouTube or add a video URL to the queue.', addDescription: 'Search YouTube or add a video URL to the queue.',
@ -328,8 +348,6 @@ export const en: TranslationSchema = {
VOICE_GLOBAL: 'Voice Channels (Global)', VOICE_GLOBAL: 'Voice Channels (Global)',
VOICE_GENERATOR_CHANNEL: 'Voice Generator Channel', VOICE_GENERATOR_CHANNEL: 'Voice Generator Channel',
VOICE_GENERATOR_CATEGORY: 'Voice Generator Category', VOICE_GENERATOR_CATEGORY: 'Voice Generator Category',
INVITE_TRACKING: 'Invite Tracking',
INVITE_ROLE_HIERARCHY: 'Invite Role Assignment (Hierarchy)',
MIMIC_WEBHOOK: 'Message Mimic (Webhook)', MIMIC_WEBHOOK: 'Message Mimic (Webhook)',
}, },
}, },
@ -388,7 +406,6 @@ export const en: TranslationSchema = {
BOOT: 'Boot', BOOT: 'Boot',
VOICE: 'Voice', VOICE: 'Voice',
PERMISSION: 'Permission', PERMISSION: 'Permission',
INVITE: 'Invite',
}, },
}, },
config: { config: {

View File

@ -4,6 +4,7 @@ import { TranslationSchema } from '../types';
* . en.ts와 1:1로 . * . en.ts와 1:1로 .
*/ */
export const ko: TranslationSchema = { export const ko: TranslationSchema = {
// ── 에러 메시지 ─────────────────────────────────────────
errors: { errors: {
E1001: { E1001: {
userMessage: '사용자 제한 값이 올바르지 않습니다.', userMessage: '사용자 제한 값이 올바르지 않습니다.',
@ -20,6 +21,7 @@ export const ko: TranslationSchema = {
userMessage: '선택한 사용자가 음성 채널에 없습니다.', userMessage: '선택한 사용자가 음성 채널에 없습니다.',
resolution: '작업 전에 해당 사용자가 채널에 있는지 확인해 주세요.', resolution: '작업 전에 해당 사용자가 채널에 있는지 확인해 주세요.',
}, },
E2001: { E2001: {
userMessage: '봇에게 채널을 관리할 권한이 부족합니다.', userMessage: '봇에게 채널을 관리할 권한이 부족합니다.',
resolution: '서버 관리자에게 봇에게 「채널 관리」 권한을 부여해 달라고 요청해 주세요.', resolution: '서버 관리자에게 봇에게 「채널 관리」 권한을 부여해 달라고 요청해 주세요.',
@ -74,19 +76,22 @@ export const ko: TranslationSchema = {
errorTitles: { errorTitles: {
USER_INPUT: '입력을 확인해주세요', USER_INPUT: '입력을 확인해주세요',
PERMISSION: '권한이 부족합니다', PERMISSION: '권한이 부족합니다',
BOT_INTERNAL: '문제가 발생했습니다', BOT_INTERNAL: '내부 오류가 발생했습니다.',
DISCORD_API: '일시적인 문제입니다.', DISCORD_API: '일시적인 문제입니다.',
}, },
errorFields: { errorFields: {
resolution: '💡 해결 방법', resolution: '💡 해결 방법',
}, },
// ── 음성 채널 ───────────────────────────────────────────
voice: { voice: {
channelReady: '{{owner}}, 임시 채널이 준비되었습니다! 아래 드롭다운 메뉴로 관리하세요.', channelReady: '{{owner}}, 임시 채널이 준비되었습니다! 아래 드롭다운 메뉴로 관리하세요.',
defaultRoomName: '{{username}}의 방', defaultRoomName: '{{username}}의 방',
controlPanel: { controlPanel: {
placeholder: '채널 설정 관리', placeholder: '⚙️ 채널 설정 관리',
rename: '채널 이름 변경', rename: '채널 이름 변경',
limit: '인원 제한 설정', limit: '인원 제한 설정',
lock: '채널 잠금 / 해제', lock: '채널 잠금 / 해제',
@ -94,6 +99,7 @@ export const ko: TranslationSchema = {
ban: '유저 차단 / 숨기기', ban: '유저 차단 / 숨기기',
transfer: '소유권 이전', transfer: '소유권 이전',
}, },
responses: { responses: {
channelLocked: '채널이 잠겼습니다! 초대된 멤버만 참여할 수 있습니다.', channelLocked: '채널이 잠겼습니다! 초대된 멤버만 참여할 수 있습니다.',
channelUnlocked: '채널 잠금이 해제되었습니다! 누구나 참여할 수 있습니다.', channelUnlocked: '채널 잠금이 해제되었습니다! 누구나 참여할 수 있습니다.',
@ -119,6 +125,7 @@ export const ko: TranslationSchema = {
setSuccess: '{{channel}}을(를) 음성 생성기 채널로 설정했습니다!', setSuccess: '{{channel}}을(를) 음성 생성기 채널로 설정했습니다!',
createSuccess: '{{channel}}을(를) 음성 생성기 채널로 생성·설정했습니다!', createSuccess: '{{channel}}을(를) 음성 생성기 채널로 생성·설정했습니다!',
}, },
voiceConfig: { voiceConfig: {
description: '서버의 임시 음성 채널 설정을 관리합니다.', description: '서버의 임시 음성 채널 설정을 관리합니다.',
setNameTitle: '기본 이름 템플릿 설정', setNameTitle: '기본 이름 템플릿 설정',
@ -129,6 +136,7 @@ export const ko: TranslationSchema = {
templateLabel: '이름 템플릿', templateLabel: '이름 템플릿',
limitLabel: '기본 인원 제한', limitLabel: '기본 인원 제한',
setSuccess: '서버 임시 채널 설정이 업데이트되었습니다.', setSuccess: '서버 임시 채널 설정이 업데이트되었습니다.',
limitValue: '{{limit}}명 (0 = 무제한)', limitValue: '{{limit}}명 (0 = 무제한)',
}, },
language: { language: {
@ -140,6 +148,7 @@ export const ko: TranslationSchema = {
userSet: '개인 언어가 **{{locale}}**(으)로 설정되었습니다.', userSet: '개인 언어가 **{{locale}}**(으)로 설정되었습니다.',
serverSet: '서버 언어가 **{{locale}}**(으)로 설정되었습니다.', serverSet: '서버 언어가 **{{locale}}**(으)로 설정되었습니다.',
serverPermissionDenied: '서버 언어 변경은 서버 관리자만 할 수 있습니다.', serverPermissionDenied: '서버 언어 변경은 서버 관리자만 할 수 있습니다.',
}, },
event: { event: {
description: '서버 이벤트 일정을 관리합니다.', description: '서버 이벤트 일정을 관리합니다.',
@ -163,6 +172,7 @@ export const ko: TranslationSchema = {
'**시작 시각:** {{startsAt}}\n**상대 시간:** {{relative}}\n**상태:** {{status}}\n**리마인더:** {{reminder}}\n**채널:** {{channel}}', '**시작 시각:** {{startsAt}}\n**상대 시간:** {{relative}}\n**상태:** {{status}}\n**리마인더:** {{reminder}}\n**채널:** {{channel}}',
cancelSuccess: '`{{id}}` 이벤트가 취소되었습니다.', cancelSuccess: '`{{id}}` 이벤트가 취소되었습니다.',
cancelNotFound: 'ID가 `{{id}}`인 예약 이벤트를 찾을 수 없습니다.', cancelNotFound: 'ID가 `{{id}}`인 예약 이벤트를 찾을 수 없습니다.',
announceSuccess: '`{{id}}` 이벤트를 {{channel}} 채널에 공지했습니다.', announceSuccess: '`{{id}}` 이벤트를 {{channel}} 채널에 공지했습니다.',
announceNotAvailable: '이 이벤트에는 사용할 수 있는 공지 채널이 설정되어 있지 않습니다.', announceNotAvailable: '이 이벤트에는 사용할 수 있는 공지 채널이 설정되어 있지 않습니다.',
startAnnouncementTitle: '이벤트 시작', startAnnouncementTitle: '이벤트 시작',
@ -174,6 +184,7 @@ export const ko: TranslationSchema = {
'`0,10,60`처럼 0 이상의 분을 쉼표로 구분해 입력해 주세요. 비우면 자동 공지를 사용하지 않습니다.', '`0,10,60`처럼 0 이상의 분을 쉼표로 구분해 입력해 주세요. 비우면 자동 공지를 사용하지 않습니다.',
invalidPastDateTime: '과거 시각으로는 이벤트를 예약할 수 없습니다.', invalidPastDateTime: '과거 시각으로는 이벤트를 예약할 수 없습니다.',
invalidPastDateTimeResolution: '미래 시각을 선택한 뒤 다시 시도해 주세요.', invalidPastDateTimeResolution: '미래 시각을 선택한 뒤 다시 시도해 주세요.',
statusScheduled: '예약됨', statusScheduled: '예약됨',
statusCancelled: '취소됨', statusCancelled: '취소됨',
statusCompleted: '완료됨', statusCompleted: '완료됨',
@ -189,6 +200,26 @@ export const ko: TranslationSchema = {
status: '상태', status: '상태',
}, },
}, },
autorole: {
description: '입장 시 역할을 자동으로 부여하는 기능을 설정합니다.',
statusTitle: '자동 역할 부여 설정 상태',
userRoleLabel: '일반 유저 역할',
botRoleLabel: '봇 역할',
statusLabel: '유저 자동 부여',
botStatusLabel: '봇 자동 부여',
userRolePlaceholder: '유저 기본 역할을 선택하세요',
botRolePlaceholder: '봇 기본 역할을 선택하세요',
toggleUserEnable: '🟢 유저 자동부여 켜기',
toggleUserDisable: '🔴 유저 자동부여 끄기',
toggleBotEnable: '🟢 봇 자동부여 켜기',
toggleBotDisable: '🔴 봇 자동부여 끄기',
notSet: '미설정',
enabled: '활성',
disabled: '비활성',
updateSuccess: '자동 역할 설정이 업데이트되었습니다.',
permissionsError: '봇의 역할 순위가 낮거나 권한이 부족하여 역할을 부여할 수 없습니다.',
suspendNotice: '권한 부족으로 인해 자동 역할 부여 기능이 일시 중지되었습니다. 봇의 권한과 역할 순위를 확인해 주세요.',
},
music: { music: {
description: '음성 채널에서 YouTube 오디오를 재생합니다.', description: '음성 채널에서 YouTube 오디오를 재생합니다.',
addDescription: 'YouTube를 검색하거나 영상 URL을 재생 목록에 추가합니다.', addDescription: 'YouTube를 검색하거나 영상 URL을 재생 목록에 추가합니다.',
@ -322,13 +353,13 @@ export const ko: TranslationSchema = {
summaryIssue: '{{fail}}건 실패 · {{warn}}건 경고가 있습니다.', summaryIssue: '{{fail}}건 실패 · {{warn}}건 경고가 있습니다.',
hierarchyWarning: hierarchyWarning:
"봇 역할(위치: {{botPos}})이 '{{role}}'(위치: {{targetPos}})보다 위에 있어야 해당 역할을 관리할 수 있습니다.", "봇 역할(위치: {{botPos}})이 '{{role}}'(위치: {{targetPos}})보다 위에 있어야 해당 역할을 관리할 수 있습니다.",
features: { features: {
BASIC: '기본 봇 기능', BASIC: '기본 봇 기능',
VOICE_GLOBAL: '임시 음성 채널 (전역)', VOICE_GLOBAL: '임시 음성 채널 (전역)',
VOICE_GENERATOR_CHANNEL: '음성 생성기 채널', VOICE_GENERATOR_CHANNEL: '음성 생성기 채널',
VOICE_GENERATOR_CATEGORY: '음성 생성기 카테고리', VOICE_GENERATOR_CATEGORY: '음성 생성기 카테고리',
INVITE_TRACKING: '초대 추적',
INVITE_ROLE_HIERARCHY: '초대 역할 부여 (계층 검사)',
MIMIC_WEBHOOK: '메시지 흉내 (Webhook)', MIMIC_WEBHOOK: '메시지 흉내 (Webhook)',
}, },
}, },
@ -385,12 +416,13 @@ export const ko: TranslationSchema = {
expired: '시간이 만료되었습니다. `/setup`을 다시 실행해 주세요.', expired: '시간이 만료되었습니다. `/setup`을 다시 실행해 주세요.',
defaultCategoryName: '음성 채널', defaultCategoryName: '음성 채널',
defaultGeneratorName: '채널 생성하기', defaultGeneratorName: '채널 생성하기',
auditCategories: { auditCategories: {
SYSTEM: '시스템', SYSTEM: '시스템',
BOOT: '부팅', BOOT: '부팅',
VOICE: '음성', VOICE: '음성',
PERMISSION: '권한', PERMISSION: '권한',
INVITE: '초대',
}, },
}, },
config: { config: {
@ -398,17 +430,20 @@ export const ko: TranslationSchema = {
noOptions: '변경할 옵션을 하나 이상 선택해 주세요.', noOptions: '변경할 옵션을 하나 이상 선택해 주세요.',
mimic: { mimic: {
label: '흉내(Mimic)', label: '흉내(Mimic)',
enabled: '활성', enabled: '활성',
disabled: '비활성', disabled: '비활성',
}, },
emoji: { emoji: {
label: '큰 이모지(Big Emoji)', label: '큰 이모지(Big Emoji)',
enabled: '활성', enabled: '활성',
disabled: '비활성', disabled: '비활성',
}, },
}, },
}, },
// ── 모달 ────────────────────────────────────────────────
modals: { modals: {
renameTitle: '음성 채널 이름 변경', renameTitle: '음성 채널 이름 변경',
renameLabel: '새 채널 이름', renameLabel: '새 채널 이름',
@ -416,12 +451,16 @@ export const ko: TranslationSchema = {
limitLabel: '인원 제한 (0 = 무제한, 199)', limitLabel: '인원 제한 (0 = 무제한, 199)',
}, },
// ── 셀렉트 메뉴 플레이스홀더 ────────────────────────────
selects: { selects: {
kickUser: '추방할 유저를 선택하세요', kickUser: '추방할 유저를 선택하세요',
banUser: '차단할 유저를 선택하세요', banUser: '차단할 유저를 선택하세요',
transferOwner: '소유권을 이전할 유저를 선택하세요', transferOwner: '소유권을 이전할 유저를 선택하세요',
}, },
// ── 상태 메시지 ──────────────────────────────────────────
presence: { presence: {
servers: '{{guildCount}}개의 서버에서 작동 중', servers: '{{guildCount}}개의 서버에서 작동 중',
help: '/help 명령어를 확인하세요', help: '/help 명령어를 확인하세요',

View File

@ -145,6 +145,26 @@ export interface TranslationSchema {
status: string; status: string;
}; };
}; };
autorole: {
description: string;
statusTitle: string;
userRoleLabel: string;
botRoleLabel: string;
statusLabel: string;
botStatusLabel: string;
userRolePlaceholder: string;
botRolePlaceholder: string;
toggleUserEnable: string;
toggleUserDisable: string;
toggleBotEnable: string;
toggleBotDisable: string;
notSet: string;
enabled: string;
disabled: string;
updateSuccess: string;
permissionsError: string;
suspendNotice: string;
};
music: { music: {
description: string; description: string;
addDescription: string; addDescription: string;
@ -282,8 +302,6 @@ export interface TranslationSchema {
VOICE_GLOBAL: string; VOICE_GLOBAL: string;
VOICE_GENERATOR_CHANNEL: string; VOICE_GENERATOR_CHANNEL: string;
VOICE_GENERATOR_CATEGORY: string; VOICE_GENERATOR_CATEGORY: string;
INVITE_TRACKING: string;
INVITE_ROLE_HIERARCHY: string;
MIMIC_WEBHOOK: string; MIMIC_WEBHOOK: string;
}; };
}; };
@ -305,7 +323,6 @@ export interface TranslationSchema {
BOOT: string; BOOT: string;
VOICE: string; VOICE: string;
PERMISSION: string; PERMISSION: string;
INVITE: string;
}; };
}; };
config: { config: {

View File

@ -1,4 +1,6 @@
import { KordClient } from './client/KordClient'; import { KordClient } from './client/KordClient';
import { startGrpcServer } from './utils/grpcServer';
const client = new KordClient(); const client = new KordClient();
startGrpcServer(client as any);
client.start(); client.start();

View File

@ -0,0 +1,223 @@
import {
SlashCommandBuilder,
SlashCommandOptionsOnlyBuilder,
SlashCommandSubcommandsOnlyBuilder,
ChatInputCommandInteraction,
} from 'discord.js';
/** Values returned from {@link SlashCommandBuilder} after chaining options or subcommands only. */
export type SlashCommandData =
| SlashCommandBuilder
| SlashCommandOptionsOnlyBuilder
| SlashCommandSubcommandsOnlyBuilder;
import { prisma } from '../database';
import { SupportedLocale } from '../i18n';
/**
* · .
*
* - help , , , .
* - `Command` .
*/
export enum CommandTrait {
/** 음악 재생·대기열 등 */
Music = 'music',
/** 미니게임 */
Minigame = 'minigame',
/** 방송 연동·알림 등 */
Broadcast = 'broadcast',
/** 위에 해당하지 않는 일반 명령(설정·감사·음성 등) */
General = 'general',
}
/** {@link CommandTrait.General}을 제외한 특성은 `guild_payment` 플래그가 필요합니다. */
export function traitRequiresPayment(trait: CommandTrait): boolean {
return (
trait === CommandTrait.Music || trait === CommandTrait.Minigame || trait === CommandTrait.Broadcast
);
}
/**
* .
*
* @returns `true`. `reply` `false`.
*/
export async function ensureGuildPaidForTrait(
interaction: ChatInputCommandInteraction,
trait: CommandTrait,
): Promise<boolean> {
if (!traitRequiresPayment(trait)) {
return true;
}
const guildId = interaction.guildId;
if (!guildId) {
await interaction.reply({
content: '이 명령은 서버에서만 사용할 수 있습니다.',
ephemeral: true,
});
return false;
}
const row = await prisma.guildPayment.findUnique({ where: { id: guildId } });
const paid =
row != null &&
((trait === CommandTrait.Music && row.music) ||
(trait === CommandTrait.Minigame && row.minigame) ||
(trait === CommandTrait.Broadcast && row.broadcast));
if (!paid) {
await interaction.reply({
content: '결제가 되지않았습니다',
ephemeral: true,
});
return false;
}
return true;
}
/**
* `CommandLoader` .
*
* `src/handlers/CommandLoader.ts` `default` export가
* `data`( ) `execute`( ) ,
* `client.commands.set(command.data.name, command)` .
* , .
*
* `trait` {@link Command.toModule} , .
*/
export type CommandModule = {
data: SlashCommandData;
execute: (interaction: ChatInputCommandInteraction, locale: SupportedLocale) => Promise<void>;
trait?: CommandTrait;
};
/**
* .
*
* ** **
* 1. {@link trait} {@link CommandTrait} .
* 2. {@link define} `SlashCommandBuilder` ··· .
* 3. {@link handle} (·DB· ) .
* 4. `export default new MyCommand().toModule()` `toModule()`
* `commands/*.ts` (`trait` ).
*
* ** ** (`interactionCreate` `execute`)
* 1. `guildOnly === true` DM .
* 2. {@link CommandTrait.Music} / {@link CommandTrait.Minigame} / {@link CommandTrait.Broadcast}
* `guild_payment` `true` . ( ·`false` )
* 3. {@link beforeHandle} `false` ( ) {@link handle} .
* 4. {@link handle} .
*
* `events/interactionCreate.ts` resolve한 `command.execute(interaction, locale)` ,
* -only .
*/
export abstract class Command {
private cachedData: SlashCommandData | null = null;
/**
* . .
*
* : 음악 {@link CommandTrait.Music}, {@link CommandTrait.Minigame},
* {@link CommandTrait.Broadcast}, {@link CommandTrait.General}.
*/
protected abstract readonly trait: CommandTrait;
/**
* `true` **() ** .
*
* DM이나 {@link handle}
* (ephemeral) return .
* (·· ) .
*/
protected guildOnly = false;
/**
* .
*
* {@link define} .
* `data` .
*/
get data(): SlashCommandData {
if (!this.cachedData) {
this.cachedData = this.define();
}
return this.cachedData;
}
/**
* (, , , , , `setDefaultMemberPermissions` )
* `SlashCommandBuilder` .
*/
protected abstract define(): SlashCommandData;
/**
* .
*
* `interaction` , `locale` / resolve된 .
*/
protected abstract handle(
interaction: ChatInputCommandInteraction,
locale: SupportedLocale,
): Promise<void>;
/**
* {@link handle} .
*
* , rate limit, ** **
* .
*
* @returns `true` {@link handle} .
* `false` ** `reply`/`deferReply` **
* `handle` .
*/
protected async beforeHandle(
_interaction: ChatInputCommandInteraction,
_locale: SupportedLocale,
): Promise<boolean> {
return true;
}
/**
* / .
*
* -only {@link ensureGuildPaidForTrait} `beforeHandle` `handle` .
* .
*/
async execute(
interaction: ChatInputCommandInteraction,
locale: SupportedLocale,
): Promise<void> {
if (this.guildOnly && !interaction.inGuild()) {
await interaction.reply({
content: 'This command can only be used in a server.',
ephemeral: true,
});
return;
}
if (!(await ensureGuildPaidForTrait(interaction, this.trait))) {
return;
}
if (!(await this.beforeHandle(interaction, locale))) {
return;
}
await this.handle(interaction, locale);
}
/**
* `CommandModule` `default export` .
*
* `execute` , `this` .
*/
toModule(): CommandModule {
return {
data: this.data,
execute: (interaction, locale) => this.execute(interaction, locale),
trait: this.trait,
};
}
}

View File

@ -0,0 +1,83 @@
/**
* `Command` ().
*
* `handlers/CommandLoader` `src/commands/`
* .
* `src/commands/your-command.ts` `setName` .
*
* {@link CommandTrait.Music} `guild_payment.music === true`
* ( ).
*/
import {
SlashCommandBuilder,
ChatInputCommandInteraction,
SlashCommandStringOption,
} from 'discord.js';
import { Command, CommandTrait } from './command';
import { SupportedLocale } from '../i18n';
class ExampleSlashCommand extends Command {
/** 음악 유료 특성 — DB `guild_payment.music` 플래그를 검사합니다. */
protected readonly trait = CommandTrait.Music;
/** 길드에서만 쓰도록 기본 가드 사용 */
protected guildOnly = true;
protected define() {
return (
new SlashCommandBuilder()
.setName('command_usage_demo')
.setDescription('Example: Command base class usage (not registered from this path).')
.setDescriptionLocalizations({
ko: '예시: Command 베이스 클래스 사용법 (이 경로에서는 등록되지 않음).',
})
// 서브커맨드/옵션은 기존과 같이 붙이면 됩니다.
.addStringOption((option: SlashCommandStringOption) =>
option
.setName('message')
.setDescription('Echo text')
.setRequired(false),
)
);
}
/**
* `beforeHandle` .
* `false` `handle` .
*/
protected async beforeHandle(
interaction: ChatInputCommandInteraction,
_locale: SupportedLocale,
): Promise<boolean> {
const msg = interaction.options.getString('message');
if (msg === 'block') {
await interaction.reply({ content: 'Blocked by beforeHandle.', ephemeral: true });
return false;
}
return true;
}
protected async handle(
interaction: ChatInputCommandInteraction,
locale: SupportedLocale,
): Promise<void> {
const message = interaction.options.getString('message');
const guildName = interaction.guild?.name ?? 'unknown';
const line =
message != null && message.length > 0
? `[${locale}] **${guildName}** — ${message}`
: `[${locale}] **${guildName}** — (no message option)`;
await interaction.reply({ content: line, ephemeral: true });
}
}
/**
* `commands/*.ts` :
*
* ```ts
* export default new ExampleSlashCommand().toModule();
* ```
*/
export default new ExampleSlashCommand().toModule();

View File

@ -3,7 +3,7 @@ import { prisma } from '../database';
import { env } from '../config/env'; import { env } from '../config/env';
export type AuditSeverity = 'INFO' | 'WARN' | 'ERROR'; export type AuditSeverity = 'INFO' | 'WARN' | 'ERROR';
export type AuditCategory = 'SYSTEM' | 'BOOT' | 'VOICE' | 'PERMISSION' | 'INVITE' | 'MIMIC'; export type AuditCategory = 'SYSTEM' | 'BOOT' | 'VOICE' | 'PERMISSION' | 'MIMIC';
export interface AuditLogPayload { export interface AuditLogPayload {
category: AuditCategory; category: AuditCategory;

View File

@ -0,0 +1,72 @@
import { Guild, GuildMember, PermissionFlagsBits } from 'discord.js';
import { prisma } from '../database';
import { logger } from '../utils/logger';
import { auditLogService } from './AuditLogService';
export class AutoRoleService {
/**
* .
*/
async getConfig(guildId: string) {
return prisma.autoRoleConfig.findUnique({
where: { guildId },
});
}
/**
* .
*/
async updateConfig(guildId: string, data: {
userRoleIds?: string[];
botRoleIds?: string[];
isEnabled?: boolean;
botEnabled?: boolean;
}) {
return prisma.autoRoleConfig.upsert({
where: { guildId },
create: {
guildId,
...data,
},
update: data,
});
}
/**
* /.
*/
async setEnabled(guildId: string, enabled: boolean) {
return this.updateConfig(guildId, { isEnabled: enabled });
}
/**
* .
*/
async handleMemberJoin(member: GuildMember) {
const config = await this.getConfig(member.guild.id);
if (!config) return;
const isBot = member.user.bot;
const isEnabled = isBot ? config.botEnabled : config.isEnabled;
const roleIds = isBot ? config.botRoleIds : config.userRoleIds;
if (!isEnabled || roleIds.length === 0) return;
try {
await member.roles.add(roleIds, 'Kord Auto-Role');
logger.info(`[AutoRole] Added roles to ${member.user.tag} in ${member.guild.name}`);
} catch (error) {
logger.error(`[AutoRole] Failed to add roles to ${member.user.tag} in ${member.guild.name}`, error);
// 권한 문제인 경우 감사 로그에 기록
await auditLogService.log(member.guild, {
category: 'PERMISSION',
severity: 'WARN',
title: 'Auto-Role Failure',
description: `Failed to assign roles to ${member.user.toString()} automatically. Please check the bot's permission and role hierarchy.`
}).catch(() => {});
}
}
}
export const autoRoleService = new AutoRoleService();

View File

@ -161,7 +161,7 @@ export class EventService {
const diff = event.startsAt.getTime() - now.getTime(); const diff = event.startsAt.getTime() - now.getTime();
const dueOffsets = event.reminderOffsets.filter(offset => const dueOffsets = event.reminderOffsets.filter((offset: number) =>
offset > 0 && offset > 0 &&
!event.sentReminderOffsets.includes(offset) && !event.sentReminderOffsets.includes(offset) &&
diff <= offset * 60 * 1000 && diff <= offset * 60 * 1000 &&

View File

@ -787,6 +787,18 @@ export class FishingService {
} }
private static resolveResourcePath(relativePath: string) { private static resolveResourcePath(relativePath: string) {
// Current file: apps/bot/src/services/FishingService.ts
// 1:src/services, 2:src, 3:bot, 4:apps, 5:root
// After re-evaluating:
// apps/bot/src/services -> .. -> src -> .. -> bot -> .. -> apps -> .. -> root (Total 4 levels)
const rootPath = path.resolve(__dirname, '..', '..', '..', '..');
const candidatePath = path.resolve(rootPath, relativePath);
if (fs.existsSync(candidatePath)) {
return candidatePath;
}
// Fallback to local if root doesn't have it (unlikely in this monorepo)
return path.resolve(__dirname, '..', '..', relativePath); return path.resolve(__dirname, '..', '..', relativePath);
} }

View File

@ -88,7 +88,7 @@ const FEATURE_DEFINITIONS: FeatureDefinition[] = [
], ],
resolveChannelIds: async (guildId) => { resolveChannelIds: async (guildId) => {
const generators = await prisma.voiceGenerator.findMany({ where: { guildId } }); const generators = await prisma.voiceGenerator.findMany({ where: { guildId } });
return generators.map((g) => g.channelId); return generators.map((g: { channelId: string }) => g.channelId);
}, },
}, },
@ -103,28 +103,13 @@ const FEATURE_DEFINITIONS: FeatureDefinition[] = [
], ],
resolveChannelIds: async (guildId) => { resolveChannelIds: async (guildId) => {
const generators = await prisma.voiceGenerator.findMany({ where: { guildId } }); const generators = await prisma.voiceGenerator.findMany({ where: { guildId } });
return generators.map((g) => g.categoryId).filter((id): id is string => id !== null); return generators
.map((g: { categoryId: string | null }) => g.categoryId)
.filter((id: string | null): id is string => id !== null);
}, },
}, },
// ── 5. 초대 추적 ── // ── 5. 메시지 흉내 (Mimic) ──
{
featureKey: 'INVITE_TRACKING',
scope: 'guild',
permissions: [PermissionFlagsBits.ManageGuild],
},
// ── 6. 역할 자동 부여 (초대 연동) - 계층 검사 ──
{
featureKey: 'INVITE_ROLE_HIERARCHY',
scope: 'hierarchy',
resolveTargetRoleIds: async (guildId) => {
const inviteRoles = await prisma.inviteRole.findMany({ where: { guildId } });
return inviteRoles.map((ir) => ir.roleId);
},
},
// ── 7. 메시지 흉내 (Mimic) ──
{ {
featureKey: 'MIMIC_WEBHOOK', featureKey: 'MIMIC_WEBHOOK',
scope: 'guild', scope: 'guild',

View File

@ -1,6 +1,8 @@
import { VoiceState, ChannelType, PermissionFlagsBits, VoiceChannel, ActionRowBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, Client, GuildMember } from 'discord.js'; import { VoiceState, ChannelType, PermissionFlagsBits, VoiceChannel, ActionRowBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, Client, GuildMember } from 'discord.js';
import { prisma } from '../database'; import { prisma } from '../database';
import { logger } from '../utils/logger'; import { logger } from '../utils/logger';
import { ErrorDefs } from '../errors/ErrorCodes'; import { ErrorDefs } from '../errors/ErrorCodes';
import { t, SupportedLocale, DEFAULT_LOCALE } from '../i18n'; import { t, SupportedLocale, DEFAULT_LOCALE } from '../i18n';
import { getContextLocale } from '../i18n/localeHelper'; import { getContextLocale } from '../i18n/localeHelper';
@ -16,6 +18,7 @@ export class VoiceService {
const guild = client.guilds.cache.get(temp.guildId) || await client.guilds.fetch(temp.guildId).catch(() => null); const guild = client.guilds.cache.get(temp.guildId) || await client.guilds.fetch(temp.guildId).catch(() => null);
if (!guild) continue; if (!guild) continue;
const channel = guild.channels.cache.get(temp.channelId) || await guild.channels.fetch(temp.channelId).catch(() => null); const channel = guild.channels.cache.get(temp.channelId) || await guild.channels.fetch(temp.channelId).catch(() => null);
if (!channel || channel.type !== ChannelType.GuildVoice) { if (!channel || channel.type !== ChannelType.GuildVoice) {
@ -45,6 +48,7 @@ export class VoiceService {
} }
} }
logger.info('VoiceService: Channel synchronization complete.'); logger.info('VoiceService: Channel synchronization complete.');
} }
public static async handleVoiceStateUpdate(oldState: VoiceState, newState: VoiceState) { public static async handleVoiceStateUpdate(oldState: VoiceState, newState: VoiceState) {
const member = newState.member; const member = newState.member;

View File

@ -1,6 +1,8 @@
import { TextChannel, WebhookClient } from 'discord.js'; import { TextChannel, WebhookClient } from 'discord.js';
import { logger } from '../utils/logger'; import { logger } from '../utils/logger';
export class WebhookService { export class WebhookService {
private static readonly MAX_WEBHOOKS = 10; private static readonly MAX_WEBHOOKS = 10;
private static readonly WEBHOOK_NAME = 'Kord Mimic Webhook'; private static readonly WEBHOOK_NAME = 'Kord Mimic Webhook';
@ -16,6 +18,7 @@ export class WebhookService {
const cached = this.webhookCache.get(channel.id); const cached = this.webhookCache.get(channel.id);
if (cached && now < cached.expiresAt) { if (cached && now < cached.expiresAt) {
return new WebhookClient({ id: cached.id, token: cached.token }); return new WebhookClient({ id: cached.id, token: cached.token });
} }
// 2. Fetch from Discord API // 2. Fetch from Discord API
@ -48,6 +51,7 @@ export class WebhookService {
id: kordWebhook.id, id: kordWebhook.id,
token: kordWebhook.token, token: kordWebhook.token,
expiresAt: Date.now() + this.WEBHOOK_CACHE_TTL_MS, expiresAt: Date.now() + this.WEBHOOK_CACHE_TTL_MS,
}); });
return new WebhookClient({ id: kordWebhook.id, token: kordWebhook.token }); return new WebhookClient({ id: kordWebhook.id, token: kordWebhook.token });
} }

55
apps/bot/src/shard.ts Normal file
View File

@ -0,0 +1,55 @@
import { ShardingManager } from 'discord.js';
import path from 'path';
import { config } from 'dotenv';
import { existsSync } from 'fs';
import * as grpc from '@grpc/grpc-js';
import { kordProto } from '@kord/grpc-contracts';
const envPath = path.resolve(process.cwd(), '../../.env');
if (existsSync(envPath)) {
config({ path: envPath });
} else {
// Fallback for direct execution from root
config({ path: path.resolve(process.cwd(), '.env') });
}
if (!process.env.DISCORD_TOKEN) {
console.error('❌ DISCORD_TOKEN is missing in shard manager! Current CWD:', process.cwd());
}
const manager = new ShardingManager(path.resolve(__dirname, 'index.ts'), {
token: process.env.DISCORD_TOKEN,
execArgv: ['--import', 'tsx'], // Node.js v22 compatibility
});
manager.on('shardCreate', (shard) => {
console.log(`Launched shard ${shard.id}`);
shard.on('ready', () => {
console.log(`Shard ${shard.id} is ready`);
});
shard.on('disconnect', () => {
console.warn(`Shard ${shard.id} disconnected`);
});
shard.on('reconnecting', () => {
console.warn(`Shard ${shard.id} reconnecting`);
});
});
import { startGrpcServer } from './utils/grpcServer';
// ... (existing env/manager setup)
// --- gRPC Proxy Server Setup ---
// We start the gRPC server early to ensure the dashboard can connect
// even if Discord sharding takes time to initialize.
startGrpcServer(manager as any);
// Only spawn shards after gRPC server is successfully bound
console.log('Starting Discord ShardingManager...');
manager.spawn().catch(err => {
console.error('Failed to spawn shards:', err);
});

View File

@ -0,0 +1,71 @@
import * as grpc from '@grpc/grpc-js';
import { kordProto } from '@kord/grpc-contracts';
import { logger } from './logger';
export interface BotInstance {
broadcastEval?: (fn: any, options?: any) => Promise<any[]>;
guilds?: {
cache: {
get: (id: string) => any;
}
};
}
export function startGrpcServer(bot: BotInstance, port: string = '0.0.0.0:50051') {
const server = new grpc.Server();
server.addService((kordProto as any).BotDashboardService.service, {
Ping: (call: any, callback: any) => {
logger.info('gRPC: Received Ping request');
callback(null, { reply: `Pong to ${call.request.message}` });
},
GetGuildChannels: async (call: any, callback: any) => {
const guildId = call.request.guildId;
try {
let channels = [];
if (bot.broadcastEval) {
// Sharded mode
const results = await bot.broadcastEval(
(c: any, context: any) => {
const guild = c.guilds.cache.get(context.guildId);
if (!guild) return null;
return guild.channels.cache.map((ch: any) => ({
id: ch.id,
name: ch.name,
type: `${ch.type}`
}));
},
{ context: { guildId } }
);
channels = results.find(res => res !== null) || [];
} else if (bot.guilds) {
// Standalone mode
const guild = bot.guilds.cache.get(guildId);
if (guild) {
channels = guild.channels.cache.map((ch: any) => ({
id: ch.id,
name: ch.name,
type: `${ch.type}`
}));
}
}
callback(null, { channels });
} catch (error: any) {
logger.error('gRPC Error in GetGuildChannels:', error);
callback({ code: grpc.status.INTERNAL, details: error.message });
}
}
});
server.bindAsync(port, grpc.ServerCredentials.createInsecure(), (err, boundPort) => {
if (err) {
logger.error(`Failed to bind gRPC server: ${err.message}`);
return;
}
logger.info(`gRPC Proxy Server running on port ${boundPort}`);
});
return server;
}

View File

@ -37,6 +37,13 @@ ensureLogDir(logDir);
log4js.configure({ log4js.configure({
appenders: { appenders: {
console: {
type: 'stdout',
layout: {
type: 'pattern',
pattern: '%[[%p]%] %m',
},
},
file: { file: {
type: 'dateFile', type: 'dateFile',
filename: resolve(logDir, 'kord.log'), filename: resolve(logDir, 'kord.log'),
@ -50,7 +57,7 @@ log4js.configure({
}, },
}, },
categories: { categories: {
default: { appenders: ['file'], level }, default: { appenders: ['console', 'file'], level },
}, },
}); });

View File

@ -0,0 +1,54 @@
jest.mock('../../src/database', () => {
const tx = { __tx: true };
const prisma = {
$transaction: jest.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn(tx)),
};
return { prisma };
});
import { prisma } from '../../src/database';
import { transaction, withTransaction } from '../../src/core/db';
describe('core/db transaction helpers', () => {
beforeEach(() => {
(prisma.$transaction as jest.Mock).mockClear();
});
test('transaction() executes callback via prisma.$transaction', async () => {
const result = await transaction(async (_tx) => {
return 123;
});
expect(result).toBe(123);
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
});
test('transaction() propagates error (rollback is handled by Prisma)', async () => {
await expect(
transaction(async () => {
throw new Error('boom');
}),
).rejects.toThrow('boom');
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
});
test('withTransaction() starts a new transaction for root client', async () => {
const rootClient = prisma as unknown as { $transaction: (fn: any) => Promise<any> };
const result = await withTransaction(rootClient as any, async (_tx) => 'ok');
expect(result).toBe('ok');
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
});
test('withTransaction() reuses existing tx client (does not nest)', async () => {
const txClient = {} as any; // does not have $transaction
const result = await withTransaction(txClient, async (_tx) => 'ok');
expect(result).toBe('ok');
expect(prisma.$transaction).toHaveBeenCalledTimes(0);
});
});

View File

@ -0,0 +1,33 @@
import { MockDiscord } from '../utils/MockDiscord';
// 예시로 사용할 가상의 Slash Command 핸들러입니다. 향후 실제 Command 객체로 대치될 수 있습니다.
const executePingCommand = async (interaction: any) => {
await interaction.deferReply();
const responseText = `Pong! User: ${interaction.user.username}`;
await interaction.editReply({ content: responseText });
};
describe('Behavior-Driven Test: Ping Command', () => {
let mockDiscord: MockDiscord;
beforeEach(() => {
// 테스트마다 깨끗한 Mock 환경 구성
mockDiscord = new MockDiscord();
});
describe('When the user invokes the /ping command', () => {
it('Then it should defer the reply and edit it with Pong and the username', async () => {
// 1. Given (상태 및 Mock Interaction 준비)
const mockInteraction = mockDiscord.createMockInteraction('ping');
// 2. When (핸들러 실행)
await executePingCommand(mockInteraction);
// 3. Then (결과 추적 및 스펙 충족 확인)
expect(mockInteraction.deferReply).toHaveBeenCalledTimes(1);
expect(mockInteraction.editReply).toHaveBeenCalledWith({
content: 'Pong! User: TestUser',
});
});
});
});

Some files were not shown because too many files have changed in this diff Show More