Compare commits
No commits in common. "main" and "DB연결-정상화-완료" have entirely different histories.
main
...
DB연결-정상화-완
|
|
@ -1,33 +0,0 @@
|
|||
---
|
||||
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 등)에 결합해야 합니다.
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
---
|
||||
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.
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
---
|
||||
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 .`.
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
trigger: always_on
|
||||
trigger: model_decision
|
||||
description: work routine
|
||||
---
|
||||
|
||||
|
|
@ -10,8 +10,7 @@ description: work routine
|
|||
## 기본 원칙 (Work Rules)
|
||||
|
||||
1. **인프라 자율 사용**: 에이전트는 프로젝트에 설정된 Docker 기반 인프라(PostgreSQL 등)를 사용자의 추가 승인 없이 자유롭게 구동(`docker-compose up -d`) 및 활용할 수 있습니다.
|
||||
2. **협력적 기획, 독립적 실행**: 기능 기획과 설계(Architecture, Schema 등)는 사용자와 함께 논리적인 완결성을 갖출 때까지 충분히 논의합니다. 특히 시스템적 자동 승인(Auto-approval) 메시지가 있더라도, 반드시 사용자의 **직접적이고 명시적인 승인 답변**이 확인된 후에만 2단계(구현)로 진입합니다. 기획이 수동으로 승인된 후에는 후속 구현, 에러 디버깅, 자체 테스트를 추가적인 중간 확인 없이 에이전트가 주도를 가지고 끝마칩니다.
|
||||
3. **선 문서화, 후 보고 (Docs First, Report Later)**: 모든 작업의 완료 보고는 반드시 `Docs/` 내의 문서 업데이트가 선행되어야 합니다. 문서화가 누락된 상태에서의 "작업 완료" 보고는 규칙 위반으로 간주합니다.
|
||||
2. **협력적 기획, 독립적 실행**: 기능 기획과 설계(Architecture, Schema 등)는 사용자와 함께 논리적인 완결성을 갖출 때까지 충분히 논의합니다. 기획이 "완료 및 승인"된 후에는 후속 구현, 에러 디버깅, 자체 테스트를 추가적인 중간 확인 없이 에이전트가 주도를 가지고 끝마친 뒤 최종 결과를 보고합니다.
|
||||
|
||||
## 단계별 작업 루틴
|
||||
|
||||
|
|
@ -19,13 +18,12 @@ description: work routine
|
|||
|
||||
- 사용자가 새로운 기능이나 수정 사항을 요청하면, 필요한 스펙 및 예외 사항을 꼼꼼히 확인합니다.
|
||||
- 명령어를 파편화하지 말고, 관련 있는 기능들을 하나의 대표 명령어 아래 '서브 커맨드' 형태로 그룹화하여 설계할 것
|
||||
- 필요 시 사용자에게 High-Tier 아키텍처 모델(예: Pro/Ultra)로의 전환을 제안하며, 변경 사항, 사용 스택, 아키텍처를 포함한 `implementation_plan.md`를 작성하여 사용자에게 검토 및 승인을 요청합니다. 설계가 완료되면 효율적 실행을 위한 모델 전환(예: Flash) 권고를 포함합니다.
|
||||
- 변경 사항, 사용 스택, 아키텍처를 포함한 `implementation_plan.md`를 작성하거나 업데이트하여 사용자에게 검토 및 승인을 요청합니다.
|
||||
|
||||
### 2단계: 개발 및 구현 (Execution Phase)
|
||||
|
||||
- 설계가 최종 승인되면 실제 코딩을 시작합니다. 이 단계부터는 사용자의 개입 없이 독립적으로 작업을 완수하는 것을 원칙으로 합니다.
|
||||
- 환경 변수 파싱, 로깅, 예외 처리를 철저히 포함하여 프로덕션 수준의 코드를 작성합니다.
|
||||
- 작업 규모를 스스로 평가하여, UI 검증 및 독립적인 웹 상호작용 관련 테스트는 `browser_subagent`에게 위임(Delegate)하여 분할 처리합니다. (`agent_model_workflow.md` 참조)
|
||||
|
||||
### 3단계: 자체 구동 및 내부 테스트 (Internal Testing Phase)
|
||||
|
||||
|
|
@ -46,6 +44,5 @@ description: work routine
|
|||
|
||||
- 3단계 구현 및 테스트가 성공적으로 완료되면, 사용자에게 최종 보고하기 **전에 반드시 먼저** `<PROJECT_ROOT>/Docs/` 디렉토리에 작업 완료(Work done), 트러블슈팅(Troubleshooting), 의사 결정(Decisions made) 내역을 문서화해야 합니다.
|
||||
- 새 문서가 생성되거나 수정되면 자동으로 `Docs/index.md`에 문서의 색인(링크)을 추가합니다.
|
||||
- 모든 코드 작업 내역과 의사 결정이 완전히 로컬 `Docs/`에 기록 및 정리된 후에만 비로소 "작업을 완료했다"고 사용자에게 알립니다. **문서화가 완료되지 않은 상태에서 사용자에게 보고하는 것은 엄격히 금지됩니다.**
|
||||
- 모든 코드 작업 내역과 의사 결정이 완전히 로컬 `Docs/`에 기록 및 정리된 후에만 비로소 "작업을 완료했다"고 사용자에게 알립니다.
|
||||
- 설치, 테스트 방법, 구동, 기능, 명령어 등을 위한 변경사항을 <PROJECT_ROOT>/README.md에 최신화합니다.
|
||||
- **최종 검크포인트**: 보고 메시지 작성 직전, `Docs/` 폴더와 `README.md`, `index.md`가 최신 상태인지 다시 한번 전수 점검합니다.
|
||||
|
|
|
|||
|
|
@ -15,9 +15,3 @@
|
|||
- 유저에게 노출되는 모든 기능(메시지, 임베드, 상태 메시지 등)을 구성할 때는 별도의 요청이 없더라도 **반드시 다국어 지원(i18n) 적용을 검토하고 구현**해야 합니다. (자세한 내용은 `Docs/Rules/i18n_guidelines.md` 참조)
|
||||
- 단순 문법 검증에 그치지 말고, `yarn dev` 등의 명령어로 봇을 백그라운드에서 직접 구동(Boot)시켜 DB/캐시 커넥트 및 이벤트 리스너 초기화 중 런타임 에러(예: Intents 권한 거부 등)가 발생하지 않는지 스스로 눈으로 확인하고 완벽히 디버깅해야 합니다.
|
||||
- 봇이 성공적으로 온라인 상태(`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 .` 를 백그라운드에 구동시켜 지식 그래프의 최신화를 자동화하는 것을 검토하십시오.
|
||||
|
|
|
|||
20
.env.example
20
.env.example
|
|
@ -5,23 +5,3 @@ DISCORD_CLIENT_ID=your_client_id_here
|
|||
# Database Configuration (PostgreSQL)
|
||||
# User/pass from docker-compose.yml
|
||||
DATABASE_URL="postgresql://kord:password@localhost:5432/kord_db?schema=public"
|
||||
|
||||
# Logging (log4js — file only under LOG_DIR, no console appender)
|
||||
# Levels: trace, debug, info, warn, error, fatal
|
||||
LOG_LEVEL=info
|
||||
# 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
|
||||
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"
|
||||
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
{"files":{"packages/db/.turbo/turbo-generate.log":{"size":401,"mtime_nanos":1776651586075885272,"mode":420,"is_dir":false}},"order":["packages/db/.turbo/turbo-generate.log"]}
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"hash":"29fcb16557ff68aa","duration":1221,"sha":"855aad274ad148847ffefa8e54eb8fa8066713fa","dirty_hash":"5906811204abfbb072123bc0cbfc794bb506b732c5875205b21f947edcc57687"}
|
||||
Binary file not shown.
File diff suppressed because one or more lines are too long
|
|
@ -1 +0,0 @@
|
|||
{"hash":"63605b2509e03797","duration":1834,"sha":"855aad274ad148847ffefa8e54eb8fa8066713fa","dirty_hash":"d0414de747ab562fdf8628ad70f7f928ce881c495f15765d4afcb0621966da17"}
|
||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
{"files":{"packages/db/.turbo/turbo-generate.log":{"size":401,"mtime_nanos":1776758349447738118,"mode":420,"is_dir":false}},"order":["packages/db/.turbo/turbo-generate.log"]}
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"hash":"acf3ce7b1f0725e0","duration":973,"sha":"8e03562f82c54396a045cb531584408aebdb976c","dirty_hash":"bc9a3d2593e9616d8817460434cba66b1a00b3efba8cea3092233c3532581f2b"}
|
||||
Binary file not shown.
|
|
@ -16,8 +16,3 @@
|
|||
- 유저에게 노출되는 모든 기능(메시지, 임베드, 상태 메시지 등)을 구성할 때는 별도의 요청이 없더라도 **반드시 다국어 지원(i18n) 적용을 검토하고 구현**해야 합니다. (자세한 내용은 `Docs/Rules/i18n_guidelines.md` 참조)
|
||||
- 단순 문법 검증에 그치지 말고, `yarn dev` 등의 명령어로 봇을 백그라운드에서 직접 구동(Boot)시켜 DB/캐시 커넥트 및 이벤트 리스너 초기화 중 런타임 에러(예: Intents 권한 거부 등)가 발생하지 않는지 스스로 눈으로 확인하고 완벽히 디버깅해야 합니다.
|
||||
- 봇이 성공적으로 온라인 상태(`Ready`)에 진입한 것을 확인한 뒤에만 사용자에게 작업 완료를 보고합니다.
|
||||
|
||||
## Graphify Rules
|
||||
- 사용자가 `/graphify` 혹은 지식 그래프 관련 질의를 할 경우, `SKILL.md`와 `Docs/Features/Graphify_Setup_Guide.md`의 워크플로우를 참조합니다.
|
||||
- 대규모 리팩토링이나 구조 파악이 필요할 때는 `graphify-out/GRAPH_REPORT.md`를 우선적으로 참조하여 의존 관계를 파악합니다.
|
||||
- 로컬 모델을 위한 시맨틱 추출이 필요한 경우 `--ollama` 옵션의 활용을 검토하며, 코드 기반 갱신은 `python3 -m graphify.watch .` 를 이용합니다.
|
||||
|
|
|
|||
|
|
@ -1,5 +0,0 @@
|
|||
# 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` 문서를 참고하세요.
|
||||
|
|
@ -2,7 +2,7 @@ FROM node:20-alpine AS builder
|
|||
WORKDIR /app
|
||||
COPY package.json yarn.lock .yarnrc.yml ./
|
||||
COPY .yarn ./.yarn
|
||||
RUN corepack enable && yarn install --immutable
|
||||
RUN corepack enable && yarn install
|
||||
|
||||
# Generate Prisma Client
|
||||
COPY prisma ./prisma/
|
||||
|
|
@ -17,8 +17,9 @@ FROM node:20-alpine AS runner
|
|||
WORKDIR /app
|
||||
COPY package.json yarn.lock .yarnrc.yml ./
|
||||
COPY .yarn ./.yarn
|
||||
RUN corepack enable && yarn install --immutable --production
|
||||
RUN corepack enable && yarn install
|
||||
|
||||
COPY --from=builder /app/node_modules/@prisma/client ./node_modules/@prisma/client
|
||||
COPY --from=builder /app/dist ./dist
|
||||
|
||||
CMD ["node", "dist/index.js"]
|
||||
CMD ["yarn", "node", "dist/index.js"]
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
# 결정 사항: 대시보드-봇 통신 아키텍처 (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가 더 효율적이라고 판단했습니다.
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
# 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`에 의한 자동 갱신 확인" 등을 수행합니다.
|
||||
|
|
@ -182,9 +182,7 @@
|
|||
후속 버전에서는 아래 요소를 추가할 수 있습니다.
|
||||
|
||||
- 물고기 희귀도
|
||||
- 물고기 크기(cm) 시스템
|
||||
- 개별 물고기 인벤토리
|
||||
- 물고기 도감 / 컬렉션
|
||||
- 미끼 종류
|
||||
- 낚싯대 및 업그레이드
|
||||
- 물고기 판매 시스템
|
||||
|
|
@ -255,41 +253,6 @@ Phase 1에서는 직접 `gold`를 주는 방식이 가장 단순하고 호환성
|
|||
|
||||
이 정도면 초반 통계 추적에 충분하고, 너무 이르게 인벤토리를 과설계하지 않을 수 있습니다.
|
||||
|
||||
도감/크기 확장 시에는 아래 모델을 추가합니다.
|
||||
|
||||
- `FishingCollectionEntry`
|
||||
- `userId`
|
||||
- `guildId`
|
||||
- `fishId`
|
||||
- `catchCount`
|
||||
- `bestRarity`
|
||||
- `bestSizeCm`
|
||||
- `lastCaughtAt`
|
||||
- `createdAt`
|
||||
- `updatedAt`
|
||||
|
||||
이 모델은 유저가 어떤 물고기를 몇 번 잡았는지, 최고 레어도와 최고 크기가 무엇인지 추적하는 데 사용합니다.
|
||||
|
||||
### 물고기 크기 시스템
|
||||
|
||||
- 낚시 성공 시 물고기마다 `cm` 단위의 크기를 부여합니다.
|
||||
- 기본 크기 범위는 물고기별 데이터에서 관리합니다.
|
||||
- 최종 크기는 `물고기 기본 크기 범위 × 레어도 보정치`로 계산합니다.
|
||||
- 즉, 같은 물고기라도 레어도가 높을수록 더 큰 개체가 등장할 수 있습니다.
|
||||
- 성공 결과 메시지에는 잡은 물고기의 크기를 함께 표시합니다.
|
||||
- 도감에는 해당 물고기의 최고 크기를 기록합니다.
|
||||
|
||||
### 도감 (Dex / Collection)
|
||||
|
||||
- `/fishing dex` 명령을 통해 개인 도감을 조회할 수 있어야 합니다.
|
||||
- 도감에는 아래 정보를 보여줍니다.
|
||||
- 잡아본 물고기 목록
|
||||
- 각 물고기의 포획 횟수
|
||||
- 최고 레어도
|
||||
- 최고 크기(cm)
|
||||
- 마지막 포획 시각
|
||||
- 아직 잡지 못한 물고기는 후속 버전에서 실루엣/잠금 상태로 표시할 수 있습니다.
|
||||
|
||||
### 세션 모델
|
||||
|
||||
낚시 플레이 자체는 즉각적인 반응을 위해 메모리 세션 기반이 적합합니다.
|
||||
|
|
@ -355,23 +318,17 @@ Phase 1에서는 직접 `gold`를 주는 방식이 가장 단순하고 호환성
|
|||
### Phase 2
|
||||
|
||||
- `/fishing status` 추가
|
||||
- `/fishing ranking` 추가
|
||||
- 사용자별 낚시 통계 추가
|
||||
- 낚시 프로필 영속화
|
||||
- 물고기 이동 패턴 개선
|
||||
- 보상 밸런스 조정
|
||||
- `/fishing dex` 추가
|
||||
- 물고기 크기(cm) 시스템 추가
|
||||
- 도감용 포획 기록 저장
|
||||
- 길드 내 최고 크기 기준 Top 10 랭킹 표시
|
||||
|
||||
### Phase 3
|
||||
|
||||
- 희귀도 체계 추가
|
||||
- 인벤토리 / 도감 고도화
|
||||
- 인벤토리 / 도감 추가
|
||||
- 미끼 / 낚싯대 보정치 추가
|
||||
- 리더보드 지원
|
||||
- 미포획 물고기 잠금/실루엣 UI 추가
|
||||
|
||||
## 검증 / 테스트
|
||||
|
||||
|
|
|
|||
|
|
@ -1,44 +0,0 @@
|
|||
# 프로젝트 구조 (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)입니다.
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
# 2026-04-07 Fishing Dex and Size Implementation
|
||||
|
||||
## 요약
|
||||
|
||||
낚시 미니게임에 물고기 크기(`cm`) 시스템과 도감(`/fishing dex`) 기능을 추가했다.
|
||||
|
||||
## 구현 내용
|
||||
|
||||
- 물고기별 기본 크기 범위를 `fish_catalog.json`에 추가
|
||||
- 레어도별 크기 보정치를 `fish_rarities.json`에 추가
|
||||
- 낚시 성공 시 최종 물고기 크기를 계산하여 결과 메시지에 표시
|
||||
- `FishingCollectionEntry` 모델 추가
|
||||
- 물고기별 포획 수
|
||||
- 최고 레어도
|
||||
- 최고 크기
|
||||
- 마지막 포획 시각
|
||||
- `/fishing dex` 서브커맨드 추가
|
||||
- 유저별 물고기 도감 조회
|
||||
- 포획 수, 최고 레어도, 최고 크기 표시
|
||||
- 성공 결과 메시지에 크기 필드 추가
|
||||
|
||||
## 검증
|
||||
|
||||
- `yarn prisma generate`
|
||||
- `yarn build`
|
||||
- `yarn test --runInBand`
|
||||
- `yarn prisma migrate deploy`
|
||||
|
||||
모든 단계가 정상 통과했다.
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
# 2026-04-07 Fishing Mini-Game Phase 2 Implementation
|
||||
|
||||
## 요약
|
||||
|
||||
낚시 미니게임의 Phase 2로 `FishingProfile` 기반 통계 영속화와 `/fishing status` 조회 기능을 추가했다.
|
||||
|
||||
## 구현 내용
|
||||
|
||||
- `FishingProfile` Prisma 모델 추가
|
||||
- `userId`, `guildId` 복합 키
|
||||
- 총 시도 수, 성공/실패 수
|
||||
- 누적 획득 골드
|
||||
- 최고 보상
|
||||
- 레어도별 포획 수
|
||||
- 마지막 낚시 시각
|
||||
- `FishingService`에 프로필 저장 로직 추가
|
||||
- 성공 시 보상과 레어도별 포획 수 누적
|
||||
- 실패 시 실패 횟수 누적
|
||||
- 모든 세션 종료 시 총 시도 수와 마지막 낚시 시각 갱신
|
||||
- `/fishing status` 서브커맨드 추가
|
||||
- 본인 또는 지정 유저의 낚시 통계 조회
|
||||
- 총 시도, 성공률, 누적 골드, 최고 보상, 마지막 낚시 시각 표시
|
||||
- 레어도별 포획 수를 별도 필드로 표시
|
||||
- 낚시 i18n 문자열 추가
|
||||
- 통계 Embed 제목/필드명/빈 기록 메시지
|
||||
|
||||
## 검증
|
||||
|
||||
- `yarn prisma generate`
|
||||
- `yarn prisma migrate deploy`
|
||||
- `yarn build`
|
||||
- `yarn test --runInBand`
|
||||
|
||||
모든 단계가 정상 통과했다.
|
||||
|
||||
## 비고
|
||||
|
||||
- `FishingProfile`은 현재 낚시 진행 통계 전용 모델이다.
|
||||
- 이후 랭킹, 도감, 업적, 장비 시스템은 이 프로필을 기반으로 확장할 수 있다.
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
# 2026-04-07: 낚시 크기 랭킹 구현
|
||||
|
||||
## 개요
|
||||
|
||||
낚시 시스템에 `/fishing ranking` 명령을 추가해, 서버 내 최고 물고기 크기 기록 상위 10개를 조회할 수 있도록 구현했습니다.
|
||||
|
||||
랭킹은 `FishingCollectionEntry`에 저장된 각 유저의 물고기별 최고 크기 기록을 기준으로 정렬하며, 각 항목에는 아래 정보가 포함됩니다.
|
||||
|
||||
- 유저
|
||||
- 물고기 종류
|
||||
- 최고 레어도
|
||||
- 최고 크기(cm)
|
||||
|
||||
## 구현 내용
|
||||
|
||||
- `/fishing ranking` 서브커맨드 추가
|
||||
- 길드 기준 최고 크기 기록 Top 10 조회 서비스 추가
|
||||
- 같은 크기일 경우 최고 레어도, 포획 횟수 순으로 정렬
|
||||
- 랭킹이 비어 있을 때의 안내 메시지 추가
|
||||
- 낚시 기획서에 랭킹 항목 반영
|
||||
|
||||
## 사용자 확인 포인트
|
||||
|
||||
- `/fishing ranking` 실행 시 서버 기준 상위 10개 기록이 표시되는지
|
||||
- 각 항목에 유저, 물고기, 레어도, 크기가 함께 보이는지
|
||||
- 기록이 없는 서버에서는 빈 상태 안내가 표시되는지
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
# 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)
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
# 인프라 치명적 오류 복구 및 안정화 (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`를 거치도록 통합하여 샤딩 환경의 일관성을 유지할 필요가 있음.
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
# 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` 파일 내용 확인
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
# 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`번으로 서비스될 수 있도록 설정되어 있습니다.
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
# 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 서버를 조기에 활성화하여 서비스 가용성을 높임.
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
# 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`)에서 실행 중인 추가 유령 프로세스가 없음을 확인했습니다.
|
||||
|
|
@ -1,242 +0,0 @@
|
|||
# 데이터베이스 테이블 구조
|
||||
|
||||
이 문서는 [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)를 함께 맞추는 것이 좋습니다.
|
||||
|
|
@ -2,11 +2,6 @@
|
|||
|
||||
이 루트 색인 문서는 프로젝트 내의 모든 구조화된 문서를 카테고리별로 모아 탐색을 돕기 위해 작성되었습니다.
|
||||
|
||||
## 아키텍처 및 시스템 (Architecture & System)
|
||||
|
||||
- [프로젝트 구조 (Project Structure)](Project_Structure.md)
|
||||
- [데이터베이스 스키마 구조 (Database Schema)](database-schema.md)
|
||||
|
||||
## 정책 및 규칙 (Rules)
|
||||
|
||||
- [보안 가이드라인 (Security Rules)](Rules/security_guidelines.md)
|
||||
|
|
@ -15,7 +10,6 @@
|
|||
## 기능 명세 (Features)
|
||||
|
||||
- [임시 음성 채널 자동화 (Temp Voice Channels)](Features/temp_voice_channels.md)
|
||||
- [Graphify 설정 및 연동 가이드 (Graphify Setup Guide)](Features/Graphify_Setup_Guide.md)
|
||||
|
||||
## 기획서 (Plans)
|
||||
|
||||
|
|
@ -35,7 +29,6 @@
|
|||
## 아키텍처 및 정책 결정 (Decisions)
|
||||
|
||||
- [구독 티어 시스템 설계 (Subscription Tiers)](Decisions/subscription_tiers.md)
|
||||
- [대시보드-봇 통신 아키텍처 (Dashboard gRPC Architecture)](Decisions/Dashboard_Architecture_gRPC.md)
|
||||
|
||||
## 트러블슈팅 (Troubleshooting)
|
||||
|
||||
|
|
@ -65,12 +58,3 @@
|
|||
- [2026-03-30: 미니게임 시스템 및 재련 게임 구현 (Mini-Game System & Refinement Implementation)](WorkDone/2026-03-30_RefinementImplementation.md)
|
||||
- [2026-03-31: 낚시 미니게임 Phase 1 구현 (Fishing Mini-Game Phase 1 Implementation)](WorkDone/2026-03-31_Fishing_MiniGame_Phase1_Implementation.md)
|
||||
- [2026-03-31: 낚시 미니게임 Phase 1 완료 (Fishing Mini-Game Phase 1 Completion)](WorkDone/2026-03-31_Fishing_MiniGame_Phase1_Completion.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 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)
|
||||
|
|
|
|||
98
README.md
98
README.md
|
|
@ -1,81 +1,73 @@
|
|||
# Kord (Monorepo)
|
||||
# Kord
|
||||
|
||||
Kord는 Discord 서버 관리를 돕는 강력하고 유연한 다기능 봇 및 전용 웹 대시보드 프로젝트입니다.
|
||||
현재 모노레포(Monorepo) 구조로 관리되고 있습니다.
|
||||
Kord는 Discord 서버 관리를 돕는 강력하고 유연한 다기능 봇입니다.
|
||||
|
||||
## 1. 프로젝트 구조 (Structure)
|
||||
## 1. 개요 (Overview)
|
||||
|
||||
본 프로젝트는 **Turborepo**와 **Yarn Workspaces**를 사용합니다.
|
||||
|
||||
- **`apps/bot`**: Discord.js 기반의 봇 본체 (ShardingManager 적용)
|
||||
- **`apps/dashboard`**: Next.js 기반의 봇 관리 웹 대시보드
|
||||
- **`packages/db`**: Prisma 스키마 및 데이터베이스 데이터 접근 레이어 (공용)
|
||||
- **`packages/grpc-contracts`**: 봇과 대시보드 간의 gRPC 통신 규약 (공용)
|
||||
**Kord**는 효율적인 서버 운영을 위해 설계된 Discord 봇입니다. TypeScript와 Discord.js를 기반으로 구축되었으며, Prisma(PostgreSQL)를 활용하여 안정적이고 확장 가능한 아키텍처를 제공합니다. 임시 음성 채널 관리, 상세 감사 로그, 권한 진단 등의 핵심 기능을 통해 서버 관리자의 부담을 줄여줍니다.
|
||||
|
||||
## 2. 요구사항 (Requirements)
|
||||
|
||||
- **Runtime**: Node.js v22 이상 (추천)
|
||||
- **Runtime**: Node.js v20 이상
|
||||
- **Package Manager**: Yarn v4 (Berry)
|
||||
- **Database**: PostgreSQL (Prisma 사용)
|
||||
- **Discord**: Bot Token 및 Client ID
|
||||
- **Discord**: Bot Token 및 Client ID (Slash Command 등록용)
|
||||
|
||||
## 3. 시작하기 (Quick Start)
|
||||
## 3. 테스트 방법 (Test Methods)
|
||||
|
||||
### 로컬 개발 환경 설정
|
||||
본 프로젝트는 Jest를 사용하여 유닛 테스트 및 통합 테스트를 수행합니다.
|
||||
|
||||
- **전체 테스트 실행**:
|
||||
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
|
||||
- **i18n 번역 누락 확인**:
|
||||
|
||||
```bash
|
||||
yarn check-i18n
|
||||
```
|
||||
|
||||
## 4. 구동 방법 (Running Methods)
|
||||
|
||||
### 로컬 개발 환경
|
||||
|
||||
1. **의존성 설치**:
|
||||
|
||||
```bash
|
||||
yarn install
|
||||
```
|
||||
|
||||
2. **환경 변수 설정**: 루트 및 각 앱 디렉토리의 `.env` 설정을 완료합니다.
|
||||
2. **환경 변수 설정**: `.env.example` 파일을 복사하여 `.env` 파일을 생성하고 필수 값을 입력합니다.
|
||||
|
||||
3. **데이터베이스 초기화**:
|
||||
|
||||
3. **데이터베이스 및 코드 생성**:
|
||||
```bash
|
||||
yarn run generate
|
||||
npx prisma migrate dev
|
||||
npx prisma generate
|
||||
```
|
||||
|
||||
### 실행 방법
|
||||
4. **개발 서버 실행**:
|
||||
|
||||
전체 프로젝트를 한꺼번에 실행하거나 개별 앱을 실행할 수 있습니다.
|
||||
|
||||
- **모든 앱 실행 (Bot + Dashboard)**:
|
||||
```bash
|
||||
yarn dev
|
||||
```
|
||||
|
||||
- **봇만 실행**:
|
||||
```bash
|
||||
yarn workspace @kord/bot dev
|
||||
```
|
||||
### 프로덕션 환경
|
||||
|
||||
- **대시보드만 실행**:
|
||||
```bash
|
||||
yarn workspace dashboard dev
|
||||
```
|
||||
1. **빌드**: `yarn build`
|
||||
2. **실행**: `yarn start`
|
||||
3. **Docker**: `docker-compose up -d`를 통해 PostgreSQL 등 로컬 인프라를 실행할 수 있습니다.
|
||||
|
||||
## 5. 인프라 검증 (Infrastructure Verification)
|
||||
## 5. 기능 목록 (Feature List)
|
||||
|
||||
인프라 설정(DB, gRPC, 환경 변수)이 올바른지 확인하려면 다음 스크립트를 실행합니다:
|
||||
```bash
|
||||
npx tsx scripts/verify-recovery.ts
|
||||
```
|
||||
|
||||
## 6. 로컬 접속 정보 (Local Connection Info)
|
||||
|
||||
로컬에서 개발 및 테스트 시 다음 주소를 사용합니다.
|
||||
|
||||
- **웹 대시보드 (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)
|
||||
- **임시 음성 채널 (Voice)**: 생성기(Generator) 채널을 통해 동적인 음성 채널 생성 및 관리 기능을 제공합니다.
|
||||
- **감사 로그 (Audit Log)**: 서버 내 주요 이벤트를 카테고리별(VOICE, PERMISSION, SYSTEM 등)로 세분화하여 기록합니다.
|
||||
- **서버 설정 (Config)**: 따라하기(Mimic), 큰 이모지(Big Emoji) 등 봇의 기능을 서버별 환경에 맞게 토글하거나 설정할 수 있습니다.
|
||||
- **권한 감사 (Permission Audit)**: 봇의 정상 작동을 방해하는 권한 문제를 즉시 진단하고 해결 방법을 안내합니다.
|
||||
- **초기 설정 마법사 (Setup Wizard)**: 봇 도입 초기 기능을 한눈에 설정할 수 있는 직관적인 UI를 제공합니다.
|
||||
- **미니게임 시스템 (Mini-Games)**: 서버 내에서 즐길 수 있는 다양한 미니게임을 제공하며, 관리자가 게임별 활성화 및 전용 채널을 설정할 수 있습니다.
|
||||
- **재련 (Refinement)**: 무기를 강화하고 다른 유저와 전투하며 골드를 획득하는 성장형 미니게임입니다.
|
||||
- **피버 타임 (Fever Time)**: 서버 활동량을 자동으로 분석하여 가장 활발한 시간대에 재련 성공 확률 보너스를 제공합니다.
|
||||
- **다국어 지원 (i18n)**: 한국어와 영어를 포함한 다국어 환경을 지원합니다.
|
||||
|
|
|
|||
855
SKILL.md
855
SKILL.md
|
|
@ -1,855 +0,0 @@
|
|||
---
|
||||
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 4–8.
|
||||
|
||||
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C 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 4–8 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 1–3. 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.
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
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);
|
||||
|
|
@ -1,81 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Run ON THE SERVER as the same user that runs kord (e.g. psa), after: ssh psa@server
|
||||
# Switches kord user service from journal-only to append stdout/stderr under LOG_DIR/kord.log
|
||||
# LOG_DIR is read from $KORD_HOME/.env (LOG_DIR=...) when present, else $KORD_HOME/logs.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
KORD_HOME="${KORD_HOME:-$HOME/kord}"
|
||||
ENV_FILE="${KORD_ENV_FILE:-$KORD_HOME/.env}"
|
||||
UNIT="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/kord.service"
|
||||
|
||||
# Last LOG_DIR= line from .env; strip quotes and ~ ; relative paths are under KORD_HOME
|
||||
resolve_log_dir() {
|
||||
local default="${KORD_HOME}/logs" line raw
|
||||
[[ -f "$ENV_FILE" ]] || { echo "$default"; return; }
|
||||
line="$(grep -E '^[[:space:]]*LOG_DIR[[:space:]]*=' "$ENV_FILE" | tail -n1 || true)"
|
||||
[[ -z "$line" ]] && { echo "$default"; return; }
|
||||
raw="${line#*=}"
|
||||
raw="$(printf '%s' "$raw" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e $'s/\r$//')"
|
||||
if [[ "$raw" =~ ^\".*\"$ ]]; then raw="${raw#\"}"; raw="${raw%\"}"; fi
|
||||
if [[ "$raw" =~ ^\'.*\'$ ]]; then raw="${raw#\'}"; raw="${raw%\'}"; fi
|
||||
raw="${raw//\~/$HOME}"
|
||||
[[ -z "$raw" ]] && { echo "$default"; return; }
|
||||
if [[ "$raw" = /* ]]; then
|
||||
echo "$raw"
|
||||
else
|
||||
echo "${KORD_HOME}/${raw#./}"
|
||||
fi
|
||||
}
|
||||
|
||||
LOG_DIR="$(resolve_log_dir)"
|
||||
LOG_FILE="${LOG_DIR}/kord.log"
|
||||
|
||||
mkdir -p "$LOG_DIR"
|
||||
|
||||
if [[ ! -f "$UNIT" ]]; then
|
||||
echo "Unit not found: $UNIT" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp -a "$UNIT" "${UNIT}.bak.$(date +%Y%m%d%H%M%S)"
|
||||
|
||||
# Point journal or any previous append paths at the log file derived from .env LOG_DIR
|
||||
sed -i \
|
||||
-e "s|^StandardOutput=journal|StandardOutput=append:${LOG_FILE}|" \
|
||||
-e "s|^StandardError=journal|StandardError=append:${LOG_FILE}|" \
|
||||
"$UNIT"
|
||||
sed -i \
|
||||
-e "s|^StandardOutput=append:.*|StandardOutput=append:${LOG_FILE}|" \
|
||||
-e "s|^StandardError=append:.*|StandardError=append:${LOG_FILE}|" \
|
||||
"$UNIT"
|
||||
|
||||
# systemd opens StandardOutput=append before ExecStart; missing parent dir → status 209/STDOUT
|
||||
sed -i '/^ExecStartPre=-\/usr\/bin\/mkdir -p /d' "$UNIT"
|
||||
tmp="$(mktemp)"
|
||||
inserted=0
|
||||
while IFS= read -r line || [[ -n "$line" ]]; do
|
||||
if [[ "$line" =~ ^ExecStart= ]] && [[ "$inserted" -eq 0 ]]; then
|
||||
printf '%s\n' "ExecStartPre=-/usr/bin/mkdir -p ${LOG_DIR}"
|
||||
inserted=1
|
||||
fi
|
||||
printf '%s\n' "$line"
|
||||
done <"$UNIT" >"$tmp"
|
||||
mv "$tmp" "$UNIT"
|
||||
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user restart kord
|
||||
|
||||
sleep 2
|
||||
systemctl --user --no-pager status kord || true
|
||||
|
||||
echo "--- Last lines of $LOG_FILE (if any) ---"
|
||||
if [[ -f "$LOG_FILE" ]]; then
|
||||
tail -n 20 "$LOG_FILE"
|
||||
else
|
||||
echo "(file not created yet; check status above)"
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "LOG_DIR=$LOG_DIR"
|
||||
echo "Follow logs: tail -f $LOG_FILE"
|
||||
|
|
@ -1,74 +0,0 @@
|
|||
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();
|
||||
|
|
@ -1,291 +0,0 @@
|
|||
import {
|
||||
ChannelType,
|
||||
ChatInputCommandInteraction,
|
||||
EmbedBuilder,
|
||||
SlashCommandBuilder,
|
||||
} from 'discord.js';
|
||||
import { prisma } from '../database';
|
||||
import { SupportedLocale, t } from '../i18n';
|
||||
import { FishingService } from '../services/FishingService';
|
||||
|
||||
export default {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('fishing')
|
||||
.setDescription('Play the fishing mini-game.')
|
||||
.setDescriptionLocalizations({
|
||||
ko: '낚시 미니게임을 플레이합니다.',
|
||||
})
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('enter')
|
||||
.setDescription('Create or reopen your fishing thread.')
|
||||
.setDescriptionLocalizations({
|
||||
ko: '낚시 전용 스레드를 생성하거나 다시 엽니다.',
|
||||
}),
|
||||
)
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('cast')
|
||||
.setDescription('Start a fishing session inside your fishing thread.')
|
||||
.setDescriptionLocalizations({
|
||||
ko: '자신의 낚시 스레드 안에서 낚시 세션을 시작합니다.',
|
||||
}),
|
||||
)
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('end')
|
||||
.setDescription('End your active fishing session and delete the thread.')
|
||||
.setDescriptionLocalizations({
|
||||
ko: '진행 중인 낚시 세션을 종료하고 스레드를 삭제합니다.',
|
||||
}),
|
||||
)
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('status')
|
||||
.setDescription('View fishing statistics.')
|
||||
.setDescriptionLocalizations({
|
||||
ko: '낚시 통계를 확인합니다.',
|
||||
})
|
||||
.addUserOption((option) =>
|
||||
option
|
||||
.setName('user')
|
||||
.setDescription('User to view')
|
||||
.setDescriptionLocalizations({
|
||||
ko: '조회할 유저',
|
||||
}),
|
||||
),
|
||||
)
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('dex')
|
||||
.setDescription('View your fishing collection book.')
|
||||
.setDescriptionLocalizations({
|
||||
ko: '낚시 도감을 확인합니다.',
|
||||
})
|
||||
.addUserOption((option) =>
|
||||
option
|
||||
.setName('user')
|
||||
.setDescription('User to view')
|
||||
.setDescriptionLocalizations({
|
||||
ko: '조회할 유저',
|
||||
}),
|
||||
),
|
||||
)
|
||||
.addSubcommand((subcommand) =>
|
||||
subcommand
|
||||
.setName('ranking')
|
||||
.setDescription('View the biggest fish size ranking in this server.')
|
||||
.setDescriptionLocalizations({
|
||||
ko: '이 서버의 물고기 크기 랭킹을 확인합니다.',
|
||||
}),
|
||||
),
|
||||
|
||||
async execute(interaction: ChatInputCommandInteraction, locale: SupportedLocale) {
|
||||
if (!interaction.guildId) return;
|
||||
|
||||
const config = await prisma.miniGameConfig.findUnique({
|
||||
where: { guildId_gameKey: { guildId: interaction.guildId, gameKey: 'fishing' } },
|
||||
});
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
|
||||
if (subcommand === 'enter') {
|
||||
if (!config || !config.enabled) {
|
||||
await interaction.editReply({
|
||||
content: t(locale, 'commands.fishing.disabled'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (config.channelId && config.channelId !== interaction.channelId) {
|
||||
await interaction.editReply({
|
||||
content: t(locale, 'commands.fishing.restrictedChannel', {
|
||||
channel: `<#${config.channelId}>`,
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!interaction.channel || interaction.channel.type !== ChannelType.GuildText) {
|
||||
await interaction.editReply({
|
||||
content: t(locale, 'commands.fishing.enterTextChannelOnly'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await FishingService.enterThread(interaction);
|
||||
await interaction.editReply({
|
||||
content: result.existed
|
||||
? t(locale, 'commands.fishing.enterExistingThread', { thread: `<#${result.thread.id}>` })
|
||||
: t(locale, 'commands.fishing.enterCreated', { thread: `<#${result.thread.id}>` }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand === 'cast') {
|
||||
if (!config || !config.enabled) {
|
||||
await interaction.editReply({
|
||||
content: t(locale, 'commands.fishing.disabled'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!FishingService.isOwnedFishingThread(interaction.channel, interaction.user.username)) {
|
||||
await interaction.editReply({
|
||||
content: t(locale, 'commands.fishing.castThreadOnly'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await FishingService.startSessionInThread(interaction, locale);
|
||||
await interaction.editReply({
|
||||
content: result.existed
|
||||
? t(locale, 'commands.fishing.startExistingSession', { thread: `<#${result.thread.id}>` })
|
||||
: t(locale, 'commands.fishing.startCreated', { thread: `<#${result.thread.id}>` }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand === 'end') {
|
||||
const ended = await FishingService.endThreadByUser(interaction, locale);
|
||||
if (!ended) {
|
||||
await interaction.editReply({
|
||||
content: t(locale, 'commands.fishing.noActiveSession'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await interaction.editReply({
|
||||
content: t(locale, 'commands.fishing.endDeleted'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand === 'status') {
|
||||
const targetUser = interaction.options.getUser('user') ?? interaction.user;
|
||||
const profile = await FishingService.getProfile(targetUser.id, interaction.guildId);
|
||||
|
||||
const totalCasts = profile?.totalCastCount ?? 0;
|
||||
const successCount = profile?.successCount ?? 0;
|
||||
const failCount = profile?.failCount ?? 0;
|
||||
const totalGoldEarned = profile?.totalGoldEarned ?? 0;
|
||||
const bestCatchReward = profile?.bestCatchReward ?? 0;
|
||||
const successRate = totalCasts > 0 ? ((successCount / totalCasts) * 100).toFixed(1) : '0.0';
|
||||
const rarityBreakdown = [
|
||||
`⚪ ${profile?.commonCatchCount ?? 0}`,
|
||||
`🟢 ${profile?.uncommonCatchCount ?? 0}`,
|
||||
`🔵 ${profile?.rareCatchCount ?? 0}`,
|
||||
`🟣 ${profile?.epicCatchCount ?? 0}`,
|
||||
`🟠 ${profile?.legendaryCatchCount ?? 0}`,
|
||||
].join('\n');
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(0x3b82f6)
|
||||
.setTitle(t(locale, 'commands.fishing.profileTitle', { user: targetUser.username }))
|
||||
.setThumbnail(targetUser.displayAvatarURL())
|
||||
.addFields(
|
||||
{
|
||||
name: t(locale, 'commands.fishing.totalCasts'),
|
||||
value: String(totalCasts),
|
||||
inline: true,
|
||||
},
|
||||
{
|
||||
name: t(locale, 'commands.fishing.successRate'),
|
||||
value: `${successRate}% (${successCount}/${successCount + failCount})`,
|
||||
inline: true,
|
||||
},
|
||||
{
|
||||
name: t(locale, 'commands.fishing.totalGoldEarned'),
|
||||
value: `${totalGoldEarned} G`,
|
||||
inline: true,
|
||||
},
|
||||
{
|
||||
name: t(locale, 'commands.fishing.bestCatchReward'),
|
||||
value: `${bestCatchReward} G`,
|
||||
inline: true,
|
||||
},
|
||||
{
|
||||
name: t(locale, 'commands.fishing.lastCastAt'),
|
||||
value: profile?.lastCastAt
|
||||
? `<t:${Math.floor(profile.lastCastAt.getTime() / 1000)}:R>`
|
||||
: t(locale, 'commands.fishing.noRecord'),
|
||||
inline: true,
|
||||
},
|
||||
{
|
||||
name: t(locale, 'commands.fishing.rarityBreakdown'),
|
||||
value: rarityBreakdown,
|
||||
inline: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (!profile) {
|
||||
embed.setDescription(t(locale, 'commands.fishing.profileEmpty'));
|
||||
}
|
||||
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand === 'dex') {
|
||||
const targetUser = interaction.options.getUser('user') ?? interaction.user;
|
||||
const collection = await FishingService.getCollection(targetUser.id, interaction.guildId);
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(0x14b8a6)
|
||||
.setTitle(t(locale, 'commands.fishing.dexTitle', { user: targetUser.username }))
|
||||
.setThumbnail(targetUser.displayAvatarURL());
|
||||
|
||||
if (!collection.length) {
|
||||
embed.setDescription(t(locale, 'commands.fishing.dexEmpty'));
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of collection.slice(0, 10)) {
|
||||
const fishName = FishingService.getFishDisplayName(entry.fishId);
|
||||
const rarityName = FishingService.getRarityDisplayNameById(entry.bestRarityId, locale);
|
||||
embed.addFields({
|
||||
name: fishName,
|
||||
value: [
|
||||
`${t(locale, 'commands.fishing.catchCount')}: ${entry.catchCount}`,
|
||||
`${t(locale, 'commands.fishing.bestRarity')}: ${rarityName}`,
|
||||
`${t(locale, 'commands.fishing.bestSize')}: ${entry.bestSizeCm.toFixed(1)} cm`,
|
||||
].join('\n'),
|
||||
inline: true,
|
||||
});
|
||||
}
|
||||
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand === 'ranking') {
|
||||
const ranking = await FishingService.getSizeRanking(interaction.guildId);
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(0xf59e0b)
|
||||
.setTitle(t(locale, 'commands.fishing.rankingTitle'));
|
||||
|
||||
if (!ranking.length) {
|
||||
embed.setDescription(t(locale, 'commands.fishing.rankingEmpty'));
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [index, entry] of ranking.entries()) {
|
||||
const fishName = FishingService.getFishDisplayName(entry.fishId);
|
||||
const rarityName = FishingService.getRarityDisplayNameById(entry.bestRarityId, locale);
|
||||
embed.addFields({
|
||||
name: `#${index + 1} <@${entry.userId}>`,
|
||||
value: [
|
||||
`${t(locale, 'commands.fishing.targetFish')}: ${fishName}`,
|
||||
`${t(locale, 'commands.fishing.rarity')}: ${rarityName}`,
|
||||
`${t(locale, 'commands.fishing.size')}: ${entry.bestSizeCm.toFixed(1)} cm`,
|
||||
].join('\n'),
|
||||
inline: false,
|
||||
});
|
||||
}
|
||||
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
import { config } from 'dotenv';
|
||||
import { existsSync } from 'fs';
|
||||
import { hostname } from 'os';
|
||||
import { resolve } from 'path';
|
||||
|
||||
const getEnvPath = () => {
|
||||
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 = () => {
|
||||
return process.env.INSTANCE_ID || hostname() || `kord-${Math.random().toString(36).substring(2, 7)}`;
|
||||
};
|
||||
|
||||
export const env = {
|
||||
NODE_ENV: process.env.NODE_ENV || 'development',
|
||||
DISCORD_TOKEN: process.env.DISCORD_TOKEN || '',
|
||||
DISCORD_CLIENT_ID: process.env.DISCORD_CLIENT_ID || '',
|
||||
DATABASE_URL: process.env.DATABASE_URL || '',
|
||||
VOICE_WAITING_ROOM_ID: process.env.VOICE_WAITING_ROOM_ID || '',
|
||||
VOICE_CATEGORY_ID: process.env.VOICE_CATEGORY_ID || '',
|
||||
/** log4js level: trace | debug | info | warn | error | fatal */
|
||||
LOG_LEVEL: process.env.LOG_LEVEL || 'info',
|
||||
/**
|
||||
* Directory for log4js `kord.log` (created at startup). Relative paths resolve from `process.cwd()`.
|
||||
* For Jenkins or wipe-and-redeploy flows, set an absolute path **outside** the deploy tree (e.g. `/var/lib/kord/logs`)
|
||||
* so logs survive redeploys and match `StandardOutput=append` in systemd if you point it at the same file.
|
||||
*/
|
||||
LOG_DIR: process.env.LOG_DIR || 'logs',
|
||||
INSTANCE_ID: generateInstanceId(),
|
||||
};
|
||||
|
|
@ -1,232 +0,0 @@
|
|||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
import type { PoolConfig } from 'pg';
|
||||
import { Pool } from 'pg';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { env } from '../config/env';
|
||||
import { logger } from '../utils/logger';
|
||||
|
||||
/**
|
||||
* `?schema=` in DATABASE_URL is a Prisma URL extension. node-postgres does not apply it,
|
||||
* so connections default to `search_path=public`. PrismaPg also needs an explicit schema
|
||||
* option in some setups (see prisma/prisma#28611).
|
||||
*/
|
||||
function createPgPoolConfig(connectionString: string): { poolConfig: PoolConfig; prismaSchema?: string } {
|
||||
if (!connectionString) {
|
||||
return { poolConfig: { connectionString: '' } };
|
||||
}
|
||||
try {
|
||||
const url = new URL(connectionString);
|
||||
const schema = url.searchParams.get('schema')?.trim();
|
||||
const poolConfig: PoolConfig = { connectionString };
|
||||
if (schema) {
|
||||
const escaped = schema.replace(/"/g, '""');
|
||||
poolConfig.options = `-c search_path="${escaped}"`;
|
||||
}
|
||||
return { poolConfig, prismaSchema: schema || undefined };
|
||||
} catch {
|
||||
return { poolConfig: { connectionString } };
|
||||
}
|
||||
}
|
||||
|
||||
const { poolConfig, prismaSchema } = createPgPoolConfig(env.DATABASE_URL);
|
||||
const pool = new Pool(poolConfig);
|
||||
const adapter = prismaSchema ? new PrismaPg(pool, { schema: prismaSchema }) : new PrismaPg(pool);
|
||||
|
||||
export const prisma = new PrismaClient({
|
||||
adapter,
|
||||
log: ['warn', 'error'],
|
||||
});
|
||||
|
||||
export const connectDB = async () => {
|
||||
if (!env.DATABASE_URL) {
|
||||
logger.error('DATABASE_URL is not set. Please check your .env file.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
// Adapter-based client connects when first used,
|
||||
// but we can test the pool connection here.
|
||||
const client = await pool.connect();
|
||||
client.release();
|
||||
logger.info('Connected to PostgreSQL successfully via Driver Adapter.');
|
||||
} catch (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);
|
||||
}
|
||||
};
|
||||
|
|
@ -1,223 +0,0 @@
|
|||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,83 +0,0 @@
|
|||
/**
|
||||
* `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();
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
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();
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
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);
|
||||
});
|
||||
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
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;
|
||||
}
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
import { mkdirSync } from 'fs';
|
||||
import log4js from 'log4js';
|
||||
import { resolve } from 'path';
|
||||
import { env } from '../config/env';
|
||||
|
||||
const LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] as const;
|
||||
type LogLevel = (typeof LOG_LEVELS)[number];
|
||||
|
||||
function resolveLogLevel(): LogLevel {
|
||||
const raw = env.LOG_LEVEL.toLowerCase();
|
||||
return (LOG_LEVELS as readonly string[]).includes(raw) ? (raw as LogLevel) : 'info';
|
||||
}
|
||||
|
||||
/** Resolves LOG_DIR from .env: absolute paths unchanged; relative paths from cwd. */
|
||||
function resolveLogDir(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) {
|
||||
return resolve('logs');
|
||||
}
|
||||
return resolve(trimmed);
|
||||
}
|
||||
|
||||
function ensureLogDir(dir: string): void {
|
||||
try {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
process.stderr.write(`[kord] Failed to create LOG_DIR "${dir}": ${msg}\n`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const logDir = resolveLogDir(env.LOG_DIR);
|
||||
const level = resolveLogLevel();
|
||||
|
||||
ensureLogDir(logDir);
|
||||
|
||||
log4js.configure({
|
||||
appenders: {
|
||||
console: {
|
||||
type: 'stdout',
|
||||
layout: {
|
||||
type: 'pattern',
|
||||
pattern: '%[[%p]%] %m',
|
||||
},
|
||||
},
|
||||
file: {
|
||||
type: 'dateFile',
|
||||
filename: resolve(logDir, 'kord.log'),
|
||||
pattern: 'yyyy-MM-dd',
|
||||
alwaysIncludePattern: true,
|
||||
numBackups: 7,
|
||||
layout: {
|
||||
type: 'pattern',
|
||||
pattern: '%d{yyyy-MM-dd hh:mm:ss.SSS} [%p] %m',
|
||||
},
|
||||
},
|
||||
},
|
||||
categories: {
|
||||
default: { appenders: ['console', 'file'], level },
|
||||
},
|
||||
});
|
||||
|
||||
process.on('exit', () => {
|
||||
try {
|
||||
log4js.shutdown();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
});
|
||||
|
||||
export const logger = log4js.getLogger();
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
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);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
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',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,96 +0,0 @@
|
|||
import * as grpc from '@grpc/grpc-js';
|
||||
import { kordProto } from '@kord/grpc-contracts';
|
||||
|
||||
// In-Memory Test Service Definition
|
||||
class MockBotDashboardService {
|
||||
public Ping(call: any, callback: any) {
|
||||
if (!call.request.message) {
|
||||
return callback({ code: grpc.status.INVALID_ARGUMENT, details: 'Message is required' });
|
||||
}
|
||||
callback(null, { reply: `Pong to ${call.request.message}` });
|
||||
}
|
||||
|
||||
public GetGuildChannels(call: any, callback: any) {
|
||||
const guildId = call.request.guildId;
|
||||
if (guildId === '123') {
|
||||
callback(null, {
|
||||
channels: [
|
||||
{ id: '1', name: 'general', type: '0' },
|
||||
{ id: '2', name: 'voice', type: '2' },
|
||||
],
|
||||
});
|
||||
} else {
|
||||
callback({ code: grpc.status.NOT_FOUND, details: 'Guild not found' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('gRPC Integration: BotDashboardService', () => {
|
||||
let server: grpc.Server;
|
||||
let client: any;
|
||||
|
||||
beforeAll((done) => {
|
||||
// 1. Setup gRPC In-Memory Server for Tests
|
||||
server = new grpc.Server();
|
||||
const serviceImpl = new MockBotDashboardService();
|
||||
|
||||
server.addService((kordProto as any).BotDashboardService.service, {
|
||||
Ping: serviceImpl.Ping.bind(serviceImpl),
|
||||
GetGuildChannels: serviceImpl.GetGuildChannels.bind(serviceImpl),
|
||||
});
|
||||
|
||||
server.bindAsync('0.0.0.0:50052', grpc.ServerCredentials.createInsecure(), (err, port) => {
|
||||
if (err) return done(err);
|
||||
|
||||
// 2. Setup Client pointing to the test server
|
||||
client = new (kordProto as any).BotDashboardService(
|
||||
`localhost:${port}`,
|
||||
grpc.credentials.createInsecure()
|
||||
);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
server.forceShutdown();
|
||||
client.close();
|
||||
});
|
||||
|
||||
describe('When pinging the gRPC layer', () => {
|
||||
it('Then it should echo back with Pong', (done) => {
|
||||
client.Ping({ message: 'BDD_Test' }, (err: any, response: any) => {
|
||||
expect(err).toBeNull();
|
||||
expect(response.reply).toBe('Pong to BDD_Test');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('Then it should throw an INVALID_ARGUMENT error if message is missing', (done) => {
|
||||
client.Ping({ message: '' }, (err: any, response: any) => {
|
||||
expect(err).not.toBeNull();
|
||||
expect(err.code).toBe(grpc.status.INVALID_ARGUMENT);
|
||||
expect(response).toBeUndefined();
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('When fetching Guild Channels', () => {
|
||||
it('Then it should return channel boundaries if guild exists', (done) => {
|
||||
client.GetGuildChannels({ guildId: '123' }, (err: any, response: any) => {
|
||||
expect(err).toBeNull();
|
||||
expect(response.channels).toHaveLength(2);
|
||||
expect(response.channels[0].name).toBe('general');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('Then it should return NOT_FOUND if guild does not exist', (done) => {
|
||||
client.GetGuildChannels({ guildId: '999' }, (err: any, response: any) => {
|
||||
expect(err).not.toBeNull();
|
||||
expect(err.code).toBe(grpc.status.NOT_FOUND);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
import { CommandInteraction, Guild, GuildMember, User, TextChannel, Client, Collection, SnowflakeUtil } from 'discord.js';
|
||||
|
||||
export class MockDiscord {
|
||||
public client: Client;
|
||||
public guild: Guild;
|
||||
public channel: TextChannel;
|
||||
public user: User;
|
||||
public member: GuildMember;
|
||||
|
||||
constructor() {
|
||||
this.client = new Client({ intents: [] });
|
||||
|
||||
// Mock User
|
||||
this.user = {
|
||||
id: SnowflakeUtil.generate().toString(),
|
||||
bot: false,
|
||||
username: 'TestUser',
|
||||
discriminator: '1234',
|
||||
displayAvatarURL: jest.fn().mockReturnValue('avatar_url'),
|
||||
} as unknown as User;
|
||||
|
||||
// Mock Guild
|
||||
this.guild = {
|
||||
id: SnowflakeUtil.generate().toString(),
|
||||
name: 'Test Guild',
|
||||
client: this.client,
|
||||
members: {
|
||||
cache: new Collection(),
|
||||
fetch: jest.fn(),
|
||||
},
|
||||
channels: {
|
||||
cache: new Collection(),
|
||||
},
|
||||
} as unknown as Guild;
|
||||
|
||||
// Mock Member
|
||||
this.member = {
|
||||
id: this.user.id,
|
||||
user: this.user,
|
||||
guild: this.guild,
|
||||
roles: {
|
||||
cache: new Collection(),
|
||||
add: jest.fn(),
|
||||
remove: jest.fn(),
|
||||
},
|
||||
permissions: {
|
||||
has: jest.fn().mockReturnValue(true),
|
||||
},
|
||||
} as unknown as GuildMember;
|
||||
|
||||
(this.guild.members.cache as Collection<string, GuildMember>).set(this.member.id, this.member);
|
||||
|
||||
// Mock Channel
|
||||
this.channel = {
|
||||
id: SnowflakeUtil.generate().toString(),
|
||||
name: 'general',
|
||||
guild: this.guild,
|
||||
isTextBased: jest.fn().mockReturnValue(true),
|
||||
send: jest.fn(),
|
||||
} as unknown as TextChannel;
|
||||
}
|
||||
|
||||
public createMockInteraction(commandName: string, options: any = {}): CommandInteraction {
|
||||
const interaction: any = {
|
||||
id: SnowflakeUtil.generate().toString(),
|
||||
applicationId: '1234567890',
|
||||
type: 2, // ApplicationCommand
|
||||
commandName,
|
||||
user: this.user,
|
||||
member: this.member,
|
||||
guild: this.guild,
|
||||
channel: this.channel,
|
||||
deferred: false,
|
||||
replied: false,
|
||||
options: {
|
||||
getString: jest.fn((name) => options[name] ?? null),
|
||||
getInteger: jest.fn((name) => options[name] ?? null),
|
||||
getBoolean: jest.fn((name) => options[name] ?? null),
|
||||
getUser: jest.fn((name) => options[name] ?? null),
|
||||
getMember: jest.fn((name) => options[name] ?? null),
|
||||
},
|
||||
deferReply: jest.fn(async () => {
|
||||
interaction.deferred = true;
|
||||
}),
|
||||
reply: jest.fn(async () => {
|
||||
interaction.replied = true;
|
||||
}),
|
||||
editReply: jest.fn(async () => {}),
|
||||
followUp: jest.fn(async () => {}),
|
||||
isCommand: jest.fn(() => true),
|
||||
};
|
||||
|
||||
return interaction as CommandInteraction;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
# This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
|
|
@ -1 +0,0 @@
|
|||
@AGENTS.md
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "tailwind.config.ts",
|
||||
"css": "src/app/globals.css",
|
||||
"baseColor": "slate",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('BDD: E2E Dashboard Integration', () => {
|
||||
test('Given the Dashboard is running, When user visits the root, Then the title should resolve', async ({ page }) => {
|
||||
// Next.js 페이지 접속
|
||||
await page.goto('/');
|
||||
|
||||
// 랜딩 렌더링 확인
|
||||
// (현재 페이지 구조에 따라 expect 조건 변경 가능: 예: expect(page).toHaveTitle(/Kord/))
|
||||
await expect(page).not.toBeNull();
|
||||
});
|
||||
|
||||
test('Given the gRPC is exposed, When calling /api/grpc-test via E2E, Then it should proxy to Bot Layer', async ({ request }) => {
|
||||
// API Route 호출 시뮬레이션
|
||||
const response = await request.get('/api/grpc-test?msg=E2E_Test');
|
||||
|
||||
// HTTP 응답 검증
|
||||
expect(response.ok()).toBeTruthy();
|
||||
|
||||
// 서버측 Payload 검증 (Dashboard -> gRPC -> Bot 통신 성공 여부)
|
||||
const data = await response.json();
|
||||
// 봇 내부의 로컬 핑이 죽어있거나 연결이 안되면 실패하게 됨으로써 E2E 구간 검증 가능
|
||||
if (data.success) {
|
||||
expect(data.reply).toContain('E2E_Test');
|
||||
} else {
|
||||
// 로컬 Bot 레이어가 내려가 있을 경우 실패 안내 (또는 Mock 설정 연동)
|
||||
console.warn('Bot server might be offline, E2E gRPC test received: ', data.error);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
import nextJest from 'next/jest';
|
||||
|
||||
const createJestConfig = nextJest({
|
||||
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
|
||||
dir: './',
|
||||
});
|
||||
|
||||
// Add any custom config to be passed to Jest
|
||||
/** @type {import('jest').Config} */
|
||||
const config = {
|
||||
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
|
||||
testEnvironment: 'jest-environment-jsdom',
|
||||
moduleNameMapper: {
|
||||
'^@/(.*)$': '<rootDir>/src/$1',
|
||||
},
|
||||
};
|
||||
|
||||
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
|
||||
export default createJestConfig(config);
|
||||
|
|
@ -1 +0,0 @@
|
|||
import '@testing-library/jest-dom';
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
transpilePackages: ["@kord/grpc-contracts"],
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
{
|
||||
"name": "dashboard",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "PORT=3000 PATH=$PATH:/Users/wemadeplay/.nvm/versions/node/v22.18.0/bin next dev --webpack",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:e2e": "playwright test",
|
||||
"test:e2e:ui": "playwright test --ui"
|
||||
},
|
||||
"dependencies": {
|
||||
"@grpc/grpc-js": "^1.14.3",
|
||||
"@kord/grpc-contracts": "workspace:*",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.8.0",
|
||||
"next": "16.2.4",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"tailwind-merge": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.42.0",
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@testing-library/dom": "^10.0.0",
|
||||
"@testing-library/jest-dom": "^6.4.2",
|
||||
"@testing-library/react": "^15.0.0",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.2.4",
|
||||
"jest": "^29.7.0",
|
||||
"jest-environment-jsdom": "^29.7.0",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* See https://playwright.dev/docs/test-configuration.
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
fullyParallel: true,
|
||||
// CI 서버 환경일 때만 실패 시 재시도
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
// TDD 기반 개발 시 로컬에선 워커를 적당히 둡니다
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
reporter: 'html',
|
||||
use: {
|
||||
// 서버가 켜져있을 경우 기본 URL을 세팅
|
||||
baseURL: 'http://127.0.0.1:3000',
|
||||
trace: 'on-first-retry',
|
||||
},
|
||||
|
||||
globalSetup: require.resolve('./playwright.global-setup.ts'),
|
||||
|
||||
// Dashboard 웹서버와 gRPC Bot을 테스트 전에 띄우고 테스트가 끝나면 자동으로 종료하는 옵션
|
||||
webServer: {
|
||||
command: 'cd ../.. && yarn dev',
|
||||
url: 'http://127.0.0.1:3000',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120 * 1000,
|
||||
},
|
||||
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
import { execSync } from 'child_process';
|
||||
import 'dotenv/config';
|
||||
|
||||
async function globalSetup() {
|
||||
console.log('\n🚀 Starting E2E Live Environment Global Setup...');
|
||||
|
||||
if (!process.env.TEST_DATABASE_URL) {
|
||||
console.error('❌ TEST_DATABASE_URL is not set in environment blocks live E2E tests to protect dev data.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!process.env.TEST_DISCORD_TOKEN) {
|
||||
console.error('❌ TEST_DISCORD_TOKEN is missing. Live E2E tests require a bot token to simulate discord interactions.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Set the global database to the test specific one
|
||||
process.env.DATABASE_URL = process.env.TEST_DATABASE_URL;
|
||||
|
||||
try {
|
||||
console.log(`📦 Pushing Test Schema to ${process.env.TEST_DATABASE_URL}...`);
|
||||
// Run prisma db push in packages/db
|
||||
// Using string replacement or passing env dynamically
|
||||
execSync('yarn workspace @kord/db run prisma db push --accept-data-loss', {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, DATABASE_URL: process.env.TEST_DATABASE_URL }
|
||||
});
|
||||
|
||||
console.log(`🌱 Seeding Test Data...`);
|
||||
execSync('yarn workspace @kord/db run prisma db seed', {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, DATABASE_URL: process.env.TEST_DATABASE_URL }
|
||||
});
|
||||
|
||||
console.log('✅ Global Setup Complete!\n');
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to push schema or seed test database:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
export default globalSetup;
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
|
|
@ -1 +0,0 @@
|
|||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
Before Width: | Height: | Size: 391 B |
|
|
@ -1 +0,0 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
|
|
@ -1 +0,0 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
|
|
@ -1 +0,0 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
Before Width: | Height: | Size: 128 B |
|
|
@ -1 +0,0 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
Before Width: | Height: | Size: 385 B |
|
|
@ -1,38 +0,0 @@
|
|||
import { GET } from '@/app/api/grpc-test/route';
|
||||
import { pingBot } from '@/lib/grpc';
|
||||
|
||||
// Mock the pingBot function
|
||||
jest.mock('@/lib/grpc', () => ({
|
||||
pingBot: jest.fn(),
|
||||
}));
|
||||
|
||||
describe('GET /api/grpc-test', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should return 200 and mocked reply on success', async () => {
|
||||
(pingBot as jest.Mock).mockResolvedValue({ reply: 'Mocked Reply from Bot' });
|
||||
|
||||
const request = new Request('http://localhost:3000/api/grpc-test?msg=Hello');
|
||||
const response = await GET(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const json = await response.json();
|
||||
expect(json.success).toBe(true);
|
||||
expect(json.reply).toBe('Mocked Reply from Bot');
|
||||
expect(pingBot).toHaveBeenCalledWith('Hello');
|
||||
});
|
||||
|
||||
it('should return 500 on gRPC failure', async () => {
|
||||
(pingBot as jest.Mock).mockRejectedValue(new Error('gRPC connection failed'));
|
||||
|
||||
const request = new Request('http://localhost:3000/api/grpc-test');
|
||||
const response = await GET(request);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
const json = await response.json();
|
||||
expect(json.success).toBe(false);
|
||||
expect(json.error).toBe('gRPC connection failed');
|
||||
});
|
||||
});
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { pingBot } from '@/lib/grpc';
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const msg = searchParams.get('msg') || 'Dashboard-to-Bot';
|
||||
|
||||
try {
|
||||
const data = await pingBot(msg);
|
||||
return NextResponse.json({ success: true, ...data });
|
||||
} catch (error: any) {
|
||||
console.error('gRPC Ping Error:', error);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: error.message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 25 KiB |
|
|
@ -1,26 +0,0 @@
|
|||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html
|
||||
lang="en"
|
||||
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
|
||||
>
|
||||
<body className="min-h-full flex flex-col">{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
export default function Home() {
|
||||
const [response, setResponse] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const testGrpc = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch("/api/grpc-test?msg=HelloBot");
|
||||
const data = await res.json();
|
||||
setResponse(data);
|
||||
} catch (err) {
|
||||
setResponse({ success: false, error: "Fetch error" });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
|
||||
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start text-center sm:text-left">
|
||||
<h1 className="text-4xl font-bold">Kord Dashboard (gRPC Test)</h1>
|
||||
<p className="text-gray-500">대시보드와 봇 간의 gRPC 통신망을 테스트합니다.</p>
|
||||
|
||||
<div className="flex gap-4 items-center flex-col sm:flex-row w-full justify-center">
|
||||
<button
|
||||
onClick={testGrpc}
|
||||
disabled={loading}
|
||||
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-6 sm:px-8 font-medium"
|
||||
>
|
||||
{loading ? "통신 중..." : "봇에게 Ping 보내기"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{response && (
|
||||
<div className={`mt-8 p-6 rounded-lg border w-full max-w-md ${response.success ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'}`}>
|
||||
<h2 className="text-lg font-semibold mb-2">테스트 결과</h2>
|
||||
<pre className="text-sm font-mono whitespace-pre-wrap">
|
||||
{JSON.stringify(response, null, 2)}
|
||||
</pre>
|
||||
{response.success && (
|
||||
<p className="mt-2 text-green-700 font-medium text-sm">✅ 봇으로부터 성공적으로 응답을 받았습니다!</p>
|
||||
)}
|
||||
{!response.success && (
|
||||
<p className="mt-2 text-red-700 font-medium text-sm">❌ 봇과 통신에 실패했습니다. (봇 구동 여부를 확인하세요)</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
import * as grpc from '@grpc/grpc-js';
|
||||
import { kordProto } from '@kord/grpc-contracts';
|
||||
|
||||
const BOT_GRPC_URL = process.env.BOT_GRPC_URL || '127.0.0.1:50051';
|
||||
|
||||
export const botClient = new (kordProto as any).BotDashboardService(
|
||||
BOT_GRPC_URL,
|
||||
grpc.credentials.createInsecure()
|
||||
);
|
||||
|
||||
export const pingBot = (message: string): Promise<{ reply: string }> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
botClient.Ping({ message }, (err: any, response: any) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(response);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const getGuildChannels = (guildId: string): Promise<any> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
botClient.GetGuildChannels({ guildId }, (err: any, response: any) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(response.channels);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
import { type ClassValue, clsx } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
|
|
@ -1,15 +1,6 @@
|
|||
version: '3.8'
|
||||
|
||||
services:
|
||||
kord:
|
||||
build: .
|
||||
container_name: kord-bot
|
||||
env_file:
|
||||
- .env
|
||||
depends_on:
|
||||
- postgres
|
||||
restart: unless-stopped
|
||||
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
container_name: kord-postgres
|
||||
|
|
|
|||
|
|
@ -1,421 +0,0 @@
|
|||
# Graph Report - . (2026-04-21)
|
||||
|
||||
## Corpus Check
|
||||
- 163 files · ~121,820 words
|
||||
- Verdict: corpus is large enough that graph structure adds value.
|
||||
|
||||
## Summary
|
||||
- 369 nodes · 617 edges · 57 communities detected
|
||||
- Extraction: 77% EXTRACTED · 23% INFERRED · 0% AMBIGUOUS · INFERRED: 141 edges (avg confidence: 0.8)
|
||||
- Token cost: 0 input · 0 output
|
||||
|
||||
## Community Hubs (Navigation)
|
||||
- [[_COMMUNITY_Fishing System & UI|Fishing System & UI]]
|
||||
- [[_COMMUNITY_Music & i18n Testing|Music & i18n Testing]]
|
||||
- [[_COMMUNITY_Command Config & Audit|Command Config & Audit]]
|
||||
- [[_COMMUNITY_Interaction & i18n Core|Interaction & i18n Core]]
|
||||
- [[_COMMUNITY_Error Flow & Setup Wizard|Error Flow & Setup Wizard]]
|
||||
- [[_COMMUNITY_Activity & Fever Systems|Activity & Fever Systems]]
|
||||
- [[_COMMUNITY_Weapon Refinement RPG|Weapon Refinement RPG]]
|
||||
- [[_COMMUNITY_Client Lifecycle & Sharding|Client Lifecycle & Sharding]]
|
||||
- [[_COMMUNITY_Discord Event Management|Discord Event Management]]
|
||||
- [[_COMMUNITY_Infrastructure & Loaders|Infrastructure & Loaders]]
|
||||
- [[_COMMUNITY_Command Subscriptions|Command Subscriptions]]
|
||||
- [[_COMMUNITY_AutoRole Automation|AutoRole Automation]]
|
||||
- [[_COMMUNITY_Dashboard gRPC Routes|Dashboard gRPC Routes]]
|
||||
- [[_COMMUNITY_gRPC Integration Tests|gRPC Integration Tests]]
|
||||
- [[_COMMUNITY_Mock Interaction Testing|Mock Interaction Testing]]
|
||||
- [[_COMMUNITY_DB & Transaction Layer|DB & Transaction Layer]]
|
||||
- [[_COMMUNITY_Logging Infrastructure|Logging Infrastructure]]
|
||||
- [[_COMMUNITY_Configuration & Env|Configuration & Env]]
|
||||
- [[_COMMUNITY_Custom Exceptions|Custom Exceptions]]
|
||||
- [[_COMMUNITY_Dashboard UI Layout|Dashboard UI Layout]]
|
||||
- [[_COMMUNITY_Dashboard Development|Dashboard Development]]
|
||||
- [[_COMMUNITY_CSS & UI Utilities|CSS & UI Utilities]]
|
||||
- [[_COMMUNITY_Command Integration Tests|Command Integration Tests]]
|
||||
- [[_COMMUNITY_Mini-Game Mechanics|Mini-Game Mechanics]]
|
||||
- [[_COMMUNITY_Logging & Channel Ops|Logging & Channel Ops]]
|
||||
- [[_COMMUNITY_Contract Config|Contract Config]]
|
||||
- [[_COMMUNITY_Prisma Configuration|Prisma Configuration]]
|
||||
- [[_COMMUNITY_PostCSS Settings|PostCSS Settings]]
|
||||
- [[_COMMUNITY_TS Environment|TS Environment]]
|
||||
- [[_COMMUNITY_Jest Global Setup|Jest Global Setup]]
|
||||
- [[_COMMUNITY_Playwright Config|Playwright Config]]
|
||||
- [[_COMMUNITY_ESLint Rules|ESLint Rules]]
|
||||
- [[_COMMUNITY_Next.js Config|Next.js Config]]
|
||||
- [[_COMMUNITY_Test Configurations|Test Configurations]]
|
||||
- [[_COMMUNITY_E2E Testing|E2E Testing]]
|
||||
- [[_COMMUNITY_gRPC Ping Tests|gRPC Ping Tests]]
|
||||
- [[_COMMUNITY_Scratch Debugging|Scratch Debugging]]
|
||||
- [[_COMMUNITY_Bot Test Config|Bot Test Config]]
|
||||
- [[_COMMUNITY_DB Unit Tests|DB Unit Tests]]
|
||||
- [[_COMMUNITY_Error Logic Testing|Error Logic Testing]]
|
||||
- [[_COMMUNITY_Reporter Tests|Reporter Tests]]
|
||||
- [[_COMMUNITY_Locale Testing|Locale Testing]]
|
||||
- [[_COMMUNITY_Invite Service Tests|Invite Service Tests]]
|
||||
- [[_COMMUNITY_Fishing Session Tests|Fishing Session Tests]]
|
||||
- [[_COMMUNITY_Music Playback Tests|Music Playback Tests]]
|
||||
- [[_COMMUNITY_Mimic Logic Tests|Mimic Logic Tests]]
|
||||
- [[_COMMUNITY_Voice State Tests|Voice State Tests]]
|
||||
- [[_COMMUNITY_Shard Process|Shard Process]]
|
||||
- [[_COMMUNITY_Bot Entrypoint|Bot Entrypoint]]
|
||||
- [[_COMMUNITY_i18n Schema|i18n Schema]]
|
||||
- [[_COMMUNITY_English Assets|English Assets]]
|
||||
- [[_COMMUNITY_Korean Assets|Korean Assets]]
|
||||
- [[_COMMUNITY_Monorepo Architecture|Monorepo Architecture]]
|
||||
- [[_COMMUNITY_gRPC Bridge|gRPC Bridge]]
|
||||
- [[_COMMUNITY_Language Support|Language Support]]
|
||||
- [[_COMMUNITY_Fishing Mechanics|Fishing Mechanics]]
|
||||
- [[_COMMUNITY_Audit Diagnostic|Audit Diagnostic]]
|
||||
|
||||
## God Nodes (most connected - your core abstractions)
|
||||
1. `FishingService` - 55 edges
|
||||
2. `MusicService` - 38 edges
|
||||
3. `t()` - 30 edges
|
||||
4. `execute()` - 14 edges
|
||||
5. `RefinementService` - 13 edges
|
||||
6. `execute()` - 11 edges
|
||||
7. `execute()` - 9 edges
|
||||
8. `execute()` - 9 edges
|
||||
9. `execute()` - 8 edges
|
||||
10. `VoiceService` - 8 edges
|
||||
|
||||
## Surprising Connections (you probably didn't know these)
|
||||
- `Temporary Voice Channels` --logs_to--> `Centralized Audit Logging` [INFERRED]
|
||||
Docs/Features/temp_voice_channels.md → apps/bot/src/services/AuditLogService.ts
|
||||
- `Weapon Refinement System` --influenced_by--> `Fever Time System` [EXTRACTED]
|
||||
Docs/WorkDone/2026-03-30_RefinementImplementation.md → apps/bot/src/services/FeverService.ts
|
||||
- `handleSetupWizardInteraction()` --calls--> `t()` [INFERRED]
|
||||
apps/bot/src/interactions/handlers/setupWizardHandler.ts → apps/bot/src/i18n/index.ts
|
||||
- `execute()` --calls--> `t()` [INFERRED]
|
||||
apps/bot/src/commands/language.ts → apps/bot/src/i18n/index.ts
|
||||
- `buildErrorMessage()` --calls--> `t()` [INFERRED]
|
||||
apps/bot/src/commands/music.ts → apps/bot/src/i18n/index.ts
|
||||
|
||||
## Communities
|
||||
|
||||
### Community 0 - "Fishing System & UI"
|
||||
Cohesion: 0.08
|
||||
Nodes (4): execute(), buildFishingGauge(), buildFishingLane(), FishingService
|
||||
|
||||
### Community 1 - "Music & i18n Testing"
|
||||
Cohesion: 0.1
|
||||
Nodes (10): walk(), buildErrorMessage(), execute(), respond(), extractYouTubeVideoId(), formatDuration(), isYouTubePlaylistUrl(), MusicService (+2 more)
|
||||
|
||||
### Community 2 - "Command Config & Audit"
|
||||
Cohesion: 0.11
|
||||
Nodes (16): buildResultLine(), execute(), getOverallColor(), AuditLogService, execute(), buildStatusLabel(), execute(), formatReminderOffsets() (+8 more)
|
||||
|
||||
### Community 3 - "Interaction & i18n Core"
|
||||
Cohesion: 0.12
|
||||
Nodes (9): getNestedValue(), normalizeDiscordLocale(), resolveLocale(), StaticI18nProvider, execute(), getContextLocale(), getInteractionLocale(), VoiceService (+1 more)
|
||||
|
||||
### Community 4 - "Error Flow & Setup Wizard"
|
||||
Cohesion: 0.12
|
||||
Nodes (7): createBotError(), ErrorReporter, withErrorHandler(), PermissionAuditService, execute(), handleSetupWizardInteraction(), SetupWizardRenderer
|
||||
|
||||
### Community 5 - "Activity & Fever Systems"
|
||||
Cohesion: 0.11
|
||||
Nodes (6): ActivityTrackerService, BigEmojiService, FeverService, execute(), MimicService, WebhookService
|
||||
|
||||
### Community 6 - "Weapon Refinement RPG"
|
||||
Cohesion: 0.26
|
||||
Nodes (3): execute(), handleRefinementInteraction(), RefinementService
|
||||
|
||||
### Community 7 - "Client Lifecycle & Sharding"
|
||||
Cohesion: 0.12
|
||||
Nodes (5): execute(), execute(), PrismaShardStatusRepository, PresenceService, execute()
|
||||
|
||||
### Community 8 - "Discord Event Management"
|
||||
Cohesion: 0.22
|
||||
Nodes (6): buildEventEmbed(), EventService, resolveAnnouncementChannel(), toDiscordTimestamps(), globalSetup(), main()
|
||||
|
||||
### Community 9 - "Infrastructure & Loaders"
|
||||
Cohesion: 0.15
|
||||
Nodes (6): loadCommands(), handleGlobalExceptions(), loadEvents(), connectDB(), createPgPoolConfig(), KordClient
|
||||
|
||||
### Community 10 - "Command Subscriptions"
|
||||
Cohesion: 0.27
|
||||
Nodes (7): beforeHandle(), data(), ensureGuildPaidForTrait(), execute(), toModule(), traitRequiresPayment(), ExampleSlashCommand
|
||||
|
||||
### Community 11 - "AutoRole Automation"
|
||||
Cohesion: 0.19
|
||||
Nodes (4): AutoRoleCommand, generateAutoRoleDashboard(), AutoRoleService, execute()
|
||||
|
||||
### Community 12 - "Dashboard gRPC Routes"
|
||||
Cohesion: 0.4
|
||||
Nodes (2): pingBot(), GET()
|
||||
|
||||
### Community 13 - "gRPC Integration Tests"
|
||||
Cohesion: 0.5
|
||||
Nodes (1): MockBotDashboardService
|
||||
|
||||
### Community 14 - "Mock Interaction Testing"
|
||||
Cohesion: 0.5
|
||||
Nodes (1): MockDiscord
|
||||
|
||||
### Community 15 - "DB & Transaction Layer"
|
||||
Cohesion: 0.67
|
||||
Nodes (2): isRootClient(), withTransaction()
|
||||
|
||||
### Community 16 - "Logging Infrastructure"
|
||||
Cohesion: 0.5
|
||||
Nodes (0):
|
||||
|
||||
### Community 17 - "Configuration & Env"
|
||||
Cohesion: 0.67
|
||||
Nodes (0):
|
||||
|
||||
### Community 18 - "Custom Exceptions"
|
||||
Cohesion: 0.67
|
||||
Nodes (1): BotError
|
||||
|
||||
### Community 19 - "Dashboard UI Layout"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 20 - "Dashboard Development"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 21 - "CSS & UI Utilities"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 22 - "Command Integration Tests"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 23 - "Mini-Game Mechanics"
|
||||
Cohesion: 1.0
|
||||
Nodes (2): Fever Time System, Weapon Refinement System
|
||||
|
||||
### Community 24 - "Logging & Channel Ops"
|
||||
Cohesion: 1.0
|
||||
Nodes (2): Centralized Audit Logging, Temporary Voice Channels
|
||||
|
||||
### Community 25 - "Contract Config"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 26 - "Prisma Configuration"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 27 - "PostCSS Settings"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 28 - "TS Environment"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 29 - "Jest Global Setup"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 30 - "Playwright Config"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 31 - "ESLint Rules"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 32 - "Next.js Config"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 33 - "Test Configurations"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 34 - "E2E Testing"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 35 - "gRPC Ping Tests"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 36 - "Scratch Debugging"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 37 - "Bot Test Config"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 38 - "DB Unit Tests"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 39 - "Error Logic Testing"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 40 - "Reporter Tests"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 41 - "Locale Testing"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 42 - "Invite Service Tests"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 43 - "Fishing Session Tests"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 44 - "Music Playback Tests"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 45 - "Mimic Logic Tests"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 46 - "Voice State Tests"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 47 - "Shard Process"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 48 - "Bot Entrypoint"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 49 - "i18n Schema"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 50 - "English Assets"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 51 - "Korean Assets"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 52 - "Monorepo Architecture"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Kord Monorepo Architecture
|
||||
|
||||
### Community 53 - "gRPC Bridge"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): gRPC Communication Layer
|
||||
|
||||
### Community 54 - "Language Support"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Internationalization System
|
||||
|
||||
### Community 55 - "Fishing Mechanics"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Fishing Mini-Game
|
||||
|
||||
### Community 56 - "Audit Diagnostic"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Permission Audit Diagnostic
|
||||
|
||||
## Knowledge Gaps
|
||||
- **9 isolated node(s):** `Kord Monorepo Architecture`, `gRPC Communication Layer`, `Internationalization System`, `Fishing Mini-Game`, `Weapon Refinement System` (+4 more)
|
||||
These have ≤1 connection - possible missing edges or undocumented components.
|
||||
- **Thin community `Dashboard UI Layout`** (2 nodes): `layout.tsx`, `RootLayout()`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Dashboard Development`** (2 nodes): `page.tsx`, `testGrpc()`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `CSS & UI Utilities`** (2 nodes): `utils.ts`, `cn()`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Command Integration Tests`** (2 nodes): `Command.test.ts`, `executePingCommand()`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mini-Game Mechanics`** (2 nodes): `Fever Time System`, `Weapon Refinement System`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Logging & Channel Ops`** (2 nodes): `Centralized Audit Logging`, `Temporary Voice Channels`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Contract Config`** (1 nodes): `index.js`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Prisma Configuration`** (1 nodes): `prisma.config.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `PostCSS Settings`** (1 nodes): `postcss.config.mjs`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `TS Environment`** (1 nodes): `next-env.d.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Jest Global Setup`** (1 nodes): `jest.setup.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Playwright Config`** (1 nodes): `playwright.config.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `ESLint Rules`** (1 nodes): `eslint.config.mjs`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Next.js Config`** (1 nodes): `next.config.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Test Configurations`** (1 nodes): `jest.config.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `E2E Testing`** (1 nodes): `dashboard.spec.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `gRPC Ping Tests`** (1 nodes): `grpc-ping.test.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Scratch Debugging`** (1 nodes): `scratch_debug_env.js`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Bot Test Config`** (1 nodes): `jest.config.js`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `DB Unit Tests`** (1 nodes): `db.test.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Error Logic Testing`** (1 nodes): `BotError.test.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Reporter Tests`** (1 nodes): `ErrorReporter.test.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Locale Testing`** (1 nodes): `i18n.test.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Invite Service Tests`** (1 nodes): `InviteService.test.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Fishing Session Tests`** (1 nodes): `FishingService.test.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Music Playback Tests`** (1 nodes): `MusicService.test.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mimic Logic Tests`** (1 nodes): `MimicService.test.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Voice State Tests`** (1 nodes): `VoiceService.test.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Shard Process`** (1 nodes): `shard.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Bot Entrypoint`** (1 nodes): `index.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `i18n Schema`** (1 nodes): `types.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `English Assets`** (1 nodes): `en.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Korean Assets`** (1 nodes): `ko.ts`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Monorepo Architecture`** (1 nodes): `Kord Monorepo Architecture`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `gRPC Bridge`** (1 nodes): `gRPC Communication Layer`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Language Support`** (1 nodes): `Internationalization System`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Fishing Mechanics`** (1 nodes): `Fishing Mini-Game`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Audit Diagnostic`** (1 nodes): `Permission Audit Diagnostic`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
|
||||
## Suggested Questions
|
||||
_Questions this graph is uniquely positioned to answer:_
|
||||
|
||||
- **Why does `t()` connect `Command Config & Audit` to `Fishing System & UI`, `Music & i18n Testing`, `Interaction & i18n Core`, `Error Flow & Setup Wizard`, `Client Lifecycle & Sharding`, `AutoRole Automation`?**
|
||||
_High betweenness centrality (0.270) - this node is a cross-community bridge._
|
||||
- **Why does `createPgPoolConfig()` connect `Infrastructure & Loaders` to `Music & i18n Testing`?**
|
||||
_High betweenness centrality (0.048) - this node is a cross-community bridge._
|
||||
- **Are the 28 inferred relationships involving `t()` (e.g. with `handleSetupWizardInteraction()` and `execute()`) actually correct?**
|
||||
_`t()` has 28 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **Are the 11 inferred relationships involving `execute()` (e.g. with `t()` and `.addFromQuery()`) actually correct?**
|
||||
_`execute()` has 11 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **What connects `Kord Monorepo Architecture`, `gRPC Communication Layer`, `Internationalization System` to the rest of the system?**
|
||||
_9 weakly-connected nodes found - possible documentation gaps or missing edges._
|
||||
- **Should `Fishing System & UI` be split into smaller, more focused modules?**
|
||||
_Cohesion score 0.08 - nodes in this community are weakly interconnected._
|
||||
- **Should `Music & i18n Testing` be split into smaller, more focused modules?**
|
||||
_Cohesion score 0.1 - nodes in this community are weakly interconnected._
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "invitedelete", "label": "inviteDelete.ts", "file_type": "code", "source_file": "src/events/inviteDelete.ts", "source_location": "L1"}, {"id": "invitedelete_execute", "label": "execute()", "file_type": "code", "source_file": "src/events/inviteDelete.ts", "source_location": "L7"}], "edges": [{"source": "invitedelete", "target": "discord_js", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/events/inviteDelete.ts", "source_location": "L1", "weight": 1.0}, {"source": "invitedelete", "target": "inviteservice", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/events/inviteDelete.ts", "source_location": "L2", "weight": 1.0}, {"source": "invitedelete", "target": "invitedelete_execute", "relation": "contains", "confidence": "EXTRACTED", "source_file": "src/events/inviteDelete.ts", "source_location": "L7", "weight": 1.0}]}
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "kordclient", "label": "KordClient.ts", "file_type": "code", "source_file": "src/client/KordClient.ts", "source_location": "L1"}, {"id": "kordclient_kordclient", "label": "KordClient", "file_type": "code", "source_file": "src/client/KordClient.ts", "source_location": "L10"}, {"id": "kordclient_kordclient_constructor", "label": ".constructor()", "file_type": "code", "source_file": "src/client/KordClient.ts", "source_location": "L13"}, {"id": "kordclient_kordclient_start", "label": ".start()", "file_type": "code", "source_file": "src/client/KordClient.ts", "source_location": "L26"}], "edges": [{"source": "kordclient", "target": "discord_js", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L1", "weight": 1.0}, {"source": "kordclient", "target": "logger", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L2", "weight": 1.0}, {"source": "kordclient", "target": "env", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L3", "weight": 1.0}, {"source": "kordclient", "target": "commandloader", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L4", "weight": 1.0}, {"source": "kordclient", "target": "eventloader", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L5", "weight": 1.0}, {"source": "kordclient", "target": "errorhandler", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L6", "weight": 1.0}, {"source": "kordclient", "target": "database", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L7", "weight": 1.0}, {"source": "kordclient", "target": "feverservice", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L8", "weight": 1.0}, {"source": "kordclient", "target": "kordclient_kordclient", "relation": "contains", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L10", "weight": 1.0}, {"source": "kordclient_kordclient", "target": "kordclient_kordclient_constructor", "relation": "method", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L13", "weight": 1.0}, {"source": "kordclient_kordclient", "target": "kordclient_kordclient_start", "relation": "method", "confidence": "EXTRACTED", "source_file": "src/client/KordClient.ts", "source_location": "L26", "weight": 1.0}]}
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "apps_dashboard_jest_config_ts", "label": "jest.config.ts", "file_type": "code", "source_file": "apps/dashboard/jest.config.ts", "source_location": "L1"}], "edges": [{"source": "apps_dashboard_jest_config_ts", "target": "jest", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "apps/dashboard/jest.config.ts", "source_location": "L1", "weight": 1.0}], "raw_calls": []}
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "apps_dashboard_src_app_api_grpc_test_route_ts", "label": "route.ts", "file_type": "code", "source_file": "apps/dashboard/src/app/api/grpc-test/route.ts", "source_location": "L1"}, {"id": "route_get", "label": "GET()", "file_type": "code", "source_file": "apps/dashboard/src/app/api/grpc-test/route.ts", "source_location": "L4"}], "edges": [{"source": "apps_dashboard_src_app_api_grpc_test_route_ts", "target": "server", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "apps/dashboard/src/app/api/grpc-test/route.ts", "source_location": "L1", "weight": 1.0}, {"source": "apps_dashboard_src_app_api_grpc_test_route_ts", "target": "grpc", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "apps/dashboard/src/app/api/grpc-test/route.ts", "source_location": "L2", "weight": 1.0}, {"source": "apps_dashboard_src_app_api_grpc_test_route_ts", "target": "route_get", "relation": "contains", "confidence": "EXTRACTED", "source_file": "apps/dashboard/src/app/api/grpc-test/route.ts", "source_location": "L4", "weight": 1.0}], "raw_calls": [{"caller_nid": "route_get", "callee": "pingBot", "source_file": "apps/dashboard/src/app/api/grpc-test/route.ts", "source_location": "L9"}, {"caller_nid": "route_get", "callee": "json", "source_file": "apps/dashboard/src/app/api/grpc-test/route.ts", "source_location": "L10"}, {"caller_nid": "route_get", "callee": "error", "source_file": "apps/dashboard/src/app/api/grpc-test/route.ts", "source_location": "L12"}, {"caller_nid": "route_get", "callee": "json", "source_file": "apps/dashboard/src/app/api/grpc-test/route.ts", "source_location": "L13"}]}
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "error_guidance_ux", "label": "\uc5d0\ub7ec \uc548\ub0b4 UX \uac1c\uc120", "file_type": "document", "source_file": "Docs/WorkDone/2026-03-27_Error_Guidance_UX_Implementation.md"}, {"id": "BotError class", "label": "BotError \ud074\ub798\uc2a4", "file_type": "document", "source_file": "Docs/WorkDone/2026-03-27_Error_Guidance_UX_Implementation.md"}], "edges": [], "hyperedges": []}
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "AuditChannel", "label": "Audit Channel Model", "file_type": "document", "source_file": "Docs/WorkDone/2026-03-27_Audit_Log_Channel_Implementation.md"}, {"id": "AuditLogService", "label": "Audit Log Service", "file_type": "document", "source_file": "Docs/WorkDone/2026-03-27_Audit_Log_Channel_Implementation.md"}], "edges": [], "hyperedges": []}
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "Discord Bot Tokens", "label": "\ub514\uc2a4\ucf54\ub4dc \ubd07 \ud1a0\ud070", "file_type": "secret", "source_file": "Docs/Rules/security_guidelines.md"}, {"id": "Database Credentials", "label": "\ub370\uc774\ud130\ubca0\uc774\uc2a4 \ube44\ubc00\ubc88\ud638 \ubc0f \uc811\uc18d \uc8fc\uc18c", "file_type": "secret", "source_file": "Docs/Rules/security_guidelines.md"}, {"id": "Environment Variables", "label": "\ud658\uacbd \ubcc0\uc218", "file_type": "concept", "source_file": "Docs/Rules/security_guidelines.md"}], "edges": [{"source": "Environment Variables", "target": "Discord Bot Tokens", "relation": "is_preferred_storage_for", "confidence": "EXTRACTED", "confidence_score": 1.0, "source_file": "Docs/Rules/security_guidelines.md"}, {"source": "Environment Variables", "target": "Database Credentials", "relation": "is_preferred_storage_for", "confidence": "EXTRACTED", "confidence_score": 1.0, "source_file": "Docs/Rules/security_guidelines.md"}], "hyperedges": []}
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "apps_bot_src_services_mimicservice_ts", "label": "MimicService.ts", "file_type": "code", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L1"}, {"id": "mimicservice_mimicservice", "label": "MimicService", "file_type": "code", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L5"}, {"id": "mimicservice_mimicservice_handlemessage", "label": ".handleMessage()", "file_type": "code", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L6"}], "edges": [{"source": "apps_bot_src_services_mimicservice_ts", "target": "discord_js", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L1", "weight": 1.0}, {"source": "apps_bot_src_services_mimicservice_ts", "target": "apps_bot_src_services_webhookservice", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L2", "weight": 1.0}, {"source": "apps_bot_src_services_mimicservice_ts", "target": "apps_bot_src_utils_logger", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L3", "weight": 1.0}, {"source": "apps_bot_src_services_mimicservice_ts", "target": "mimicservice_mimicservice", "relation": "contains", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L5", "weight": 1.0}, {"source": "mimicservice_mimicservice", "target": "mimicservice_mimicservice_handlemessage", "relation": "method", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L6", "weight": 1.0}], "raw_calls": [{"caller_nid": "mimicservice_mimicservice_handlemessage", "callee": "includes", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L14"}, {"caller_nid": "mimicservice_mimicservice_handlemessage", "callee": "toLowerCase", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L14"}, {"caller_nid": "mimicservice_mimicservice_handlemessage", "callee": "replace", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L15"}, {"caller_nid": "mimicservice_mimicservice_handlemessage", "callee": "has", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L22"}, {"caller_nid": "mimicservice_mimicservice_handlemessage", "callee": "permissionsIn", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L22"}, {"caller_nid": "mimicservice_mimicservice_handlemessage", "callee": "getWebhookClient", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L26"}, {"caller_nid": "mimicservice_mimicservice_handlemessage", "callee": "send", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L28"}, {"caller_nid": "mimicservice_mimicservice_handlemessage", "callee": "displayAvatarURL", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L31"}, {"caller_nid": "mimicservice_mimicservice_handlemessage", "callee": "delete", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L35"}, {"caller_nid": "mimicservice_mimicservice_handlemessage", "callee": "error", "source_file": "apps/bot/src/services/MimicService.ts", "source_location": "L39"}]}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "event", "label": "event.ts", "file_type": "code", "source_file": "src/commands/event.ts", "source_location": "L1"}, {"id": "event_parseseouldatetime", "label": "parseSeoulDateTime()", "file_type": "code", "source_file": "src/commands/event.ts", "source_location": "L18"}, {"id": "event_todiscordtimestamps", "label": "toDiscordTimestamps()", "file_type": "code", "source_file": "src/commands/event.ts", "source_location": "L51"}, {"id": "event_parsereminderoffsets", "label": "parseReminderOffsets()", "file_type": "code", "source_file": "src/commands/event.ts", "source_location": "L59"}, {"id": "event_formatreminderoffsets", "label": "formatReminderOffsets()", "file_type": "code", "source_file": "src/commands/event.ts", "source_location": "L77"}, {"id": "event_buildstatuslabel", "label": "buildStatusLabel()", "file_type": "code", "source_file": "src/commands/event.ts", "source_location": "L85"}, {"id": "event_execute", "label": "execute()", "file_type": "code", "source_file": "src/commands/event.ts", "source_location": "L189"}], "edges": [{"source": "event", "target": "discord_js", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/commands/event.ts", "source_location": "L1", "weight": 1.0}, {"source": "event", "target": "database", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/commands/event.ts", "source_location": "L10", "weight": 1.0}, {"source": "event", "target": "i18n", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/commands/event.ts", "source_location": "L11", "weight": 1.0}, {"source": "event", "target": "eventservice", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "src/commands/event.ts", "source_location": "L12", "weight": 1.0}, {"source": "event", "target": "event_parseseouldatetime", "relation": "contains", "confidence": "EXTRACTED", "source_file": "src/commands/event.ts", "source_location": "L18", "weight": 1.0}, {"source": "event", "target": "event_todiscordtimestamps", "relation": "contains", "confidence": "EXTRACTED", "source_file": "src/commands/event.ts", "source_location": "L51", "weight": 1.0}, {"source": "event", "target": "event_parsereminderoffsets", "relation": "contains", "confidence": "EXTRACTED", "source_file": "src/commands/event.ts", "source_location": "L59", "weight": 1.0}, {"source": "event", "target": "event_formatreminderoffsets", "relation": "contains", "confidence": "EXTRACTED", "source_file": "src/commands/event.ts", "source_location": "L77", "weight": 1.0}, {"source": "event", "target": "event_buildstatuslabel", "relation": "contains", "confidence": "EXTRACTED", "source_file": "src/commands/event.ts", "source_location": "L85", "weight": 1.0}, {"source": "event", "target": "event_execute", "relation": "contains", "confidence": "EXTRACTED", "source_file": "src/commands/event.ts", "source_location": "L189", "weight": 1.0}, {"source": "event_execute", "target": "event_parseseouldatetime", "relation": "calls", "confidence": "INFERRED", "source_file": "src/commands/event.ts", "source_location": "L202", "weight": 0.8}, {"source": "event_execute", "target": "event_parsereminderoffsets", "relation": "calls", "confidence": "INFERRED", "source_file": "src/commands/event.ts", "source_location": "L217", "weight": 0.8}, {"source": "event_execute", "target": "event_todiscordtimestamps", "relation": "calls", "confidence": "INFERRED", "source_file": "src/commands/event.ts", "source_location": "L239", "weight": 0.8}, {"source": "event_execute", "target": "event_formatreminderoffsets", "relation": "calls", "confidence": "INFERRED", "source_file": "src/commands/event.ts", "source_location": "L247", "weight": 0.8}, {"source": "event_execute", "target": "event_buildstatuslabel", "relation": "calls", "confidence": "INFERRED", "source_file": "src/commands/event.ts", "source_location": "L286", "weight": 0.8}]}
|
||||
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "apps_bot_tests_services_inviteservice_test_ts", "label": "InviteService.test.ts", "file_type": "code", "source_file": "apps/bot/tests/services/InviteService.test.ts", "source_location": "L1"}], "edges": [{"source": "apps_bot_tests_services_inviteservice_test_ts", "target": "apps_bot_src_services_inviteservice", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "apps/bot/tests/services/InviteService.test.ts", "source_location": "L1", "weight": 1.0}], "raw_calls": []}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +0,0 @@
|
|||
{"nodes": [{"id": "apps_bot_src_services_feverservice_ts", "label": "FeverService.ts", "file_type": "code", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L1"}, {"id": "feverservice_feverservice", "label": "FeverService", "file_type": "code", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L5"}, {"id": "feverservice_feverservice_startscheduler", "label": ".startScheduler()", "file_type": "code", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L11"}, {"id": "feverservice_feverservice_updatefeverstate", "label": ".updateFeverState()", "file_type": "code", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L28"}, {"id": "feverservice_feverservice_getfeverbonus", "label": ".getFeverBonus()", "file_type": "code", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L64"}], "edges": [{"source": "apps_bot_src_services_feverservice_ts", "target": "apps_bot_src_database", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L1", "weight": 1.0}, {"source": "apps_bot_src_services_feverservice_ts", "target": "apps_bot_src_utils_logger", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L2", "weight": 1.0}, {"source": "apps_bot_src_services_feverservice_ts", "target": "apps_bot_src_services_activitytrackerservice", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L3", "weight": 1.0}, {"source": "apps_bot_src_services_feverservice_ts", "target": "feverservice_feverservice", "relation": "contains", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L5", "weight": 1.0}, {"source": "feverservice_feverservice", "target": "feverservice_feverservice_startscheduler", "relation": "method", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L11", "weight": 1.0}, {"source": "feverservice_feverservice", "target": "feverservice_feverservice_updatefeverstate", "relation": "method", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L28", "weight": 1.0}, {"source": "feverservice_feverservice", "target": "feverservice_feverservice_getfeverbonus", "relation": "method", "confidence": "EXTRACTED", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L64", "weight": 1.0}], "raw_calls": [{"caller_nid": "feverservice_feverservice_startscheduler", "callee": "setInterval", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L13"}, {"caller_nid": "feverservice_feverservice_updatefeverstate", "callee": "getPeakHour", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L29"}, {"caller_nid": "feverservice_feverservice_updatefeverstate", "callee": "getUTCHours", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L33"}, {"caller_nid": "feverservice_feverservice_updatefeverstate", "callee": "getTime", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L37"}, {"caller_nid": "feverservice_feverservice_updatefeverstate", "callee": "upsert", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L39"}, {"caller_nid": "feverservice_feverservice_updatefeverstate", "callee": "info", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L57"}, {"caller_nid": "feverservice_feverservice_getfeverbonus", "callee": "findUnique", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L65"}, {"caller_nid": "feverservice_feverservice_getfeverbonus", "callee": "update", "source_file": "apps/bot/src/services/FeverService.ts", "source_location": "L73"}]}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue