merge: sprint-015 dashboard v3 redesign

This commit is contained in:
2026-04-06 20:25:39 +09:00
47 changed files with 3163 additions and 434 deletions

View File

@@ -16,14 +16,14 @@
- 장기 문서: `docs/`
## 활성 작업
- **SPRINT-014**: Hermes 전환 + 프로젝트 IA/파일 구조 리뉴얼
- **SPRINT-015**: Master Dashboard v3 정보 구조 리디자인
## 이번 Sprint 핵심 요구사항
1. OpenClaw → Hermes 전환 후 자매 상태가 전부 offline으로 보이는 문제 해결
2. 자매 프로필 사진 탐색 경로/fallback 재정비
3. 변경된 파일 구조에 맞춘 프로젝트 진행률 / Sprint / Hotfix UI 개편
4. 프로젝트를 네비게이션 두 번째 페이지로 고정
5. 다랑 QA 완료 후 `main`이 배포 상태가 되고, 이랑은 최신 `main`을 pull해서 재배포만 수행하도록 흐름 고정
1. 메인 대시보드를 4자매 운영 관제의 대표 화면으로 재정의
2. 현행 미니멀 터미널 UI를 유지한 채 레퍼런스의 강한 정보 구조를 흡수
3. 상단 global status bar / 4자매 상태 카드 / `ACTIVE PIPELINE` 중심 구조 도입
4. `ACTIVITY FEED`, `SPRINT METRICS`, `INFRASTRUCTURE OVERVIEW`, `MISTAKE LOG & HARNESS`를 운영 문맥으로 재배치
5. 데스크톱 우선 설계 후 모바일 세로 흐름까지 함께 정리
## 이행 전략
- 코드에서는 구 구조와 신 구조를 일정 기간 동시 지원
@@ -34,5 +34,6 @@
## 문서 맵
- 구조 기준: `../ARCHITECTURE.md`
- 디자인 인덱스: `./design/index.md`
- Sprint 계획: `./sprints/SPRINT-014.md`
- Sprint 계획: `./sprints/SPRINT-015.md`
- 나랑 handoff: `./sprints/SPRINT-015-NARANG-HANDOFF.md`
- 배포 플로우: `./deploy/main-release-flow.md`

View File

@@ -16,8 +16,11 @@
- `ui/settings-design.md`
- `ui/admin-design.md`
## Sprint 014에서 반드시 반영할 화면
- 대시보드 메인: Hermes 상태/프로젝트 요약/두 번째 네비 반영
- 프로젝트 목록: 프로젝트를 두 번째 페이지로 이동한 기준 재배치
- 프로젝트 상세: Sprint / Hotfix / QA / Deploy 분리 구조 반영
- 자매 페이지: Hermes 상태 판정과 아바타 fallback 반영
## 레퍼런스
- `references/07-master-dashboard-v3-reference.md`
## Sprint 015에서 반드시 반영할 화면
- 대시보드 메인: Master Dashboard v3 구조 반영
- 핵심 섹션: Global Status Bar / 4자매 상태 카드 / `ACTIVE PIPELINE`
- 운영 패널: `ACTIVITY FEED`, `SPRINT METRICS`, `INFRASTRUCTURE OVERVIEW`, `MISTAKE LOG & HARNESS`
- 모바일: 데스크톱 구조를 억지로 축소하지 말고 세로 읽기 흐름으로 재배열

View File

@@ -0,0 +1,33 @@
# Master Dashboard v3 Reference Notes
## 출처
자기야가 2026-04-06에 공유한 레퍼런스 시안.
## 핵심 인상
- 짙은 다크 배경 위에 운영 패널을 촘촘하게 배치
- 상단 global status bar + 중앙 sprint progress + 우측 runtime connection 구조
- 4자매 상태 카드를 1행에서 동시에 노출
- `ACTIVE PIPELINE`을 중심으로 4자매 협업 흐름을 시각화
- `ACTIVITY FEED` / `SPRINT METRICS` / `INFRASTRUCTURE OVERVIEW` / `MISTAKE LOG & HARNESS`를 한 화면에서 모두 판단 가능
## 채택 결정
- **채택:** 정보 구조, 섹션 구성, 운영 화면다운 밀도, Active Pipeline 개념
- **부분 채택:** 색 강조, pulse/flow 애니메이션, 상단 진행률 표현
- **비채택:** 과한 glow, glassmorphism 회귀, 장식 위주의 다이어그램화
## 제품 적용 원칙
- 하나랑 대시보드는 현행 미니멀 터미널 UI 톤을 유지
- 레퍼런스는 `레이아웃/정보 위계/흐름 표현` 위주로 번역 적용
- 비주얼 차용 비율은 대략 70% 이내로 제한
- 실데이터 기반 운영 화면으로 느껴져야 하며 mock showcase처럼 보이면 안 됨
## 특히 강한 섹션
1. Sister Status Cards
2. Active Pipeline
3. Activity Feed + Metrics 병렬 비교
4. Infra + Mistake Log 하단 운영 패널
## 구현 시 주의
- 실제 데이터 밀도에 비해 컴포넌트가 과장되면 안 됨
- 첫 스크롤 안에 가장 중요한 판단 정보가 모여야 함
- 모바일에서는 같은 구조를 억지로 축소하지 말고 세로 흐름으로 재배열

View File

@@ -1,31 +1,225 @@
# 대시보드 메인 (`/`) — Sprint 014 리뉴얼 포인트
# 대시보드 메인 (`/`) — Sprint 015 Master Dashboard v3
## 유지 요소
- 미니멀 터미널 UI
- 4자매 상태 카드
- 프로젝트 요약 + 활동 피드
- 모바일 하단 탭바
## 목적
대시보드 메인은 단순 요약 화면이 아니라, 자기야가 들어오자마자 `지금 4자매 파이프라인이 어디까지 와 있는지` 즉시 판단할 수 있는 대표 운영 화면이어야 해.
## 수정 포인트
### 1. 자매 상태 판정
- Hermes 런타임 기준 상태를 읽어야 함
- OpenClaw만 보는 하드코딩 제거
- 상태 카드가 전원 `OFFLINE`으로 고정되지 않게 실제 상태/uptime/cpu를 노출
이번 v3의 핵심은 **현행 미니멀 터미널 UI를 유지하면서, 더 강한 정보 구조와 흐름 시각화로 메인 화면을 재구성하는 것**이야.
### 2. 자매 아바타
- 실사/프로필 이미지가 있으면 사용
- 없으면 fallback SVG
- broken image 상태 금지
## 유지할 것
- 현재 제품의 미니멀 터미널 톤
- 짙은 배경 + 얇은 border + mono 보조 텍스트
- 4자매 중심 세계관/역할 구분
- 모바일 하단 탭바와 기존 페이지 동선
### 3. 프로젝트 요약 영역
- 프로젝트는 네비게이션 두 번째 페이지와 동일한 정보 구조를 축약해서 보여줌
- 단순 퍼센트만이 아니라 현재 phase가 드러나야 함
## 강하게 가져올 것
- 상단 global status bar 구조
- 4자매 카드 1행 배치
- `ACTIVE PIPELINE` 중심 운영 다이어그램
- `ACTIVITY FEED` + `SPRINT METRICS` 병렬 구조
- `INFRASTRUCTURE OVERVIEW` + `MISTAKE LOG & HARNESS` 하단 운영 패널 구조
### 4. 네비게이션 순서
- `대시 → 프로 → 활동 → 자매 → 조직 → 설정 → 관리`
- 모바일 하단 탭바도 같은 순서 유지
## 줄일 것
- 과한 glow
- 장식성 애니메이션 남발
- 의미 없이 많은 뱃지/배경 장식
- mock 대시보드처럼 보이는 가짜 숫자 강조
## 모바일 기준
- 2열 상태 카드 유지
- 프로젝트 요약은 phase 우선, 활동 피드는 그 아래
- 하단 탭에서 프로젝트가 두 번째 탭으로 보여야 함
---
## 전체 레이아웃
### 1. Top Global Status Bar
한 줄 또는 반응형 2단 구조.
#### 좌측
- 브랜드/제품명
- 현재 페이지 정체성 (`Master Dashboard`)
#### 중앙
- 현재 Sprint / Day / focus summary
- 진행률 bar 또는 current cycle 요약
#### 우측
- Discord/Runtime 연결 상태
- 알림 진입점
- operator/avatar 요약
#### UX 기준
- 상단에서 현재 운영 국면을 짧게 읽을 수 있어야 함
- 모바일에서는 좌/중/우를 무리하게 한 줄에 우겨넣지 말고 2단으로 자연스럽게 접기
---
### 2. Sister Status Cards Row
4자매 카드는 1행 핵심 상태 영역.
#### 공통 정보
- 이름
- 역할
- 상태 (`IDLE`, `WORKING`, `REVIEWING`, `OFFLINE`, `DEPLOYING` 등)
- CPU / RAM 또는 대응 리소스 지표
- 현재 작업 한 줄 요약
#### 역할별 색 기준
- Harang: amber
- Narang: sky
- Darang: pink
- Irang: violet
#### 상태 표현 규칙
- 색은 역할 + 현재 상태를 같이 전달해야 함
- working/reviewing처럼 active 상태일 때만 강한 강조
- idle은 조용하게
- offline은 회색/경고 계열로 분명히 구분
#### 카드 UX 기준
- 네 카드의 높이/구조는 최대한 동일
- 긴 텍스트는 1줄 또는 2줄 clamp
- CPU/RAM은 숫자와 bar를 함께 보여줘도 되지만 과장하지 말 것
- 아바타/아이콘은 보조 요소고, 상태 텍스트가 주인공이어야 함
---
### 3. `ACTIVE PIPELINE`
이번 v3의 대표 섹션.
#### 목적
User → Harang → Narang → Darang → Irang 흐름과, maker-checker loop, escalation 조건을 한눈에 보여준다.
#### 기본 노드
- User
- Harang (`Plan & Assign`)
- Narang (`Implement` or active task id)
- Darang (`Review / QA`)
- Irang (`Deploy / Idle`)
#### 보여줄 정보
- 현재 active task 또는 ticket id
- Narang ↔ Darang review loop
- escalation 조건 또는 누적 실패 횟수
- Irang이 아직 idle인지, redeploy 대기인지
#### 구현 기준
- SVG 기반 라인/화살표 허용
- active state가 있을 때만 제한적 pulse/flow
- 정적인 설명보다 실제 운영 상태가 우선
- loop / escalation은 읽히되 과하게 복잡하면 안 됨
#### 금지
- 예쁘기만 한 다이어그램
- 현재 상태를 읽을 수 없는 장식형 선/화살표
---
### 4. Middle Row — `ACTIVITY FEED` + `SPRINT METRICS`
운영 근거와 정량 판단을 나란히 배치한다.
#### A. Activity Feed
운영 이벤트 타임라인.
##### 우선 정보
- 시각
- 주체/대상 (예: Narang → Darang)
- 이벤트 타입 (`handoff`, `review_request`, `review_fail`, `deploy`, `hotfix` 등)
- 관련 task/sprint/hotfix id
- 실패/경고 시 짧은 원인
##### UX 기준
- 텍스트 로그가 아니라 읽히는 이벤트 카드여야 함
- event type 색은 통일감 있게 관리
- 필요하면 details/JSON 결과는 접어서 보여줌
#### B. Sprint Metrics
한 Sprint의 진행 체감치를 운영 지표로 압축.
##### 포함 후보
- total tasks
- done / in progress / review / planning 비중
- sister별 completed count
- avg iterations
- first-pass rate
- escalation count
##### UX 기준
- 차트는 보조, 숫자 읽기가 우선
- donut + mini bar + stat box 조합 허용
- `활동 피드와 같은 행에서 비교`했을 때 자연스러워야 함
---
### 5. Bottom Row — `INFRASTRUCTURE OVERVIEW` + `MISTAKE LOG & HARNESS`
운영 기반과 학습 자산을 하단에 둔다.
#### A. Infrastructure Overview
##### 목적
현재 시스템이 어디서 어떻게 돌아가는지 빠르게 파악.
##### 포함 요소
- gateway
- sisters runtime host/lxc/vm
- deploy access path
- health / load / uptime 요약
##### 표현 방식
- 단순 카드 나열보다 연결 관계가 보이는 가벼운 맵 구조 선호
- 다만 실제 데이터가 빈약하면 과장된 네트워크 다이어그램으로 만들지 말 것
#### B. Mistake Log & Harness
##### 목적
운영 중 쌓인 실수/규칙/학습 자산을 한 눈에 보여줌.
##### 포함 요소
- 최신 mistake/harness rule 몇 개
- 작성 시점
- 누가 추가했는지
- category (`DB Schema`, `Frontend`, `Deployment` 등)
- 필요하면 작은 trend visualization
##### UX 기준
- 단순 문서 링크가 아니라 운영 학습 보드처럼 보여야 함
- `View Full` 또는 상세 문서 링크는 보조로 유지
---
## 데스크톱 정보 순서
1. Top Global Status Bar
2. Sister Status Cards
3. Active Pipeline
4. Activity Feed / Sprint Metrics
5. Infrastructure Overview / Mistake Log & Harness
## 모바일 정보 순서
1. Top Status Summary
2. Sister Status Cards (2열 또는 1열)
3. Active Pipeline
4. Activity Feed
5. Sprint Metrics
6. Infrastructure Overview
7. Mistake Log & Harness
모바일에서는 복잡한 수평 관계보다 세로 읽기 흐름이 우선이야.
---
## 데이터 연결 원칙
- mock 텍스트/숫자로 고정하지 말고 실제 데이터가 들어올 자리를 먼저 설계할 것
- 값이 없을 때는 `No recent activity`, `No active deployment`, `No harness rules yet`처럼 조용한 empty state 제공
- offline / missing / unavailable 상태는 숨기지 말고 명확히 드러낼 것
## 인터랙션 원칙
- hover 없어도 핵심 정보가 읽혀야 함
- 클릭 가능한 영역은 페이지 이동 또는 상세 패널 열기처럼 의미가 분명해야 함
- notification / details / expand는 보조 수단
## 스타일 원칙
- background는 현행 다크 톤 유지
- border 1px 중심
- 그림자/glow는 active state 강조용 최소치만 사용
- 하드한 터미널 감성과 현대적 운영 패널 느낌 사이 균형 유지
## 연결 페이지
- 프로젝트 페이지는 phase/QA/deploy 세부 판단용
- 활동 페이지는 장기 로그 열람용
- 자매 상세는 개별 runtime/세션 분석용
- 관리 페이지는 조작/재시작/관리용
즉, 홈은 모든 걸 다 보여주는 곳이 아니라 **지금 어디를 눌러야 하는지 판단시키는 운영 출발점**이어야 해.

View File

@@ -0,0 +1,49 @@
# SPRINT-015 Narang Handoff
## repo / branch
- repo: `https://git.nabomhalang.co.kr/hanarang/hanarang-dashboard`
- branch: `feature/sprint-015-v3-redesign-plan`
## 읽을 문서
1. `.plans/sprints/SPRINT-015.md`
2. `.plans/design/ui/dashboard-design.md`
3. `.plans/design/index.md`
4. 기존 구현 참조가 필요하면 `.plans/sprints/SPRINT-014.md`
## 이번에 해야 하는 일
대시보드 메인(`/`)을 v3 정보 구조로 재설계해.
핵심은 이거야.
- 현행 미니멀 터미널 톤 유지
- 레퍼런스의 정보 구조 적극 채택
- `ACTIVE PIPELINE`을 대표 섹션으로 도입
- 4자매 상태 카드 / Activity Feed / Sprint Metrics / Infra / Mistake Log를 운영 화면답게 재배치
- 장식은 줄이고 실데이터 연결 가능한 구조로 구현
## 절대 기준
- glassmorphism으로 회귀하지 마
- styled-components 체계 유지
- fake mock 느낌 강한 장식 UI로 끝내지 마
- hover 없이도 핵심 정보 읽혀야 해
- 데스크톱 먼저 맞추고 모바일 세로 흐름까지 꼭 정리해
- 기존 페이지 동선 숨기지 마
## 구현 우선순위
1. 상단 Global Status Bar / Hero Summary
2. 4자매 상태 카드 v3
3. `ACTIVE PIPELINE`
4. `ACTIVITY FEED` / `SPRINT METRICS`
5. `INFRASTRUCTURE OVERVIEW` / `MISTAKE LOG & HARNESS`
6. 반응형/빈 상태/오프라인 상태 정리
## 확인 포인트
- 첫 화면 첫 스크롤 안에서 자매 상태 + 현재 파이프라인이 읽혀야 함
- 색은 상태 의미가 있을 때만 강하게 사용
- Activity / Metrics / Infra / Mistake가 각각 따로 노는 패널이 아니라 운영 맥락으로 이어져야 함
- `ACTIVE PIPELINE`은 예쁘기만 한 다이어그램이 아니라 현재 handoff / review loop / escalation을 보여줘야 함
## QA 전 필수
- `npm run build` 통과
- 반응형 확인
- 데이터 없을 때/길 때/오프라인일 때 레이아웃 확인
- 외부 URL 기준으로 실제 읽기 흐름 확인

View File

@@ -0,0 +1,180 @@
# SPRINT-015: Master Dashboard v3 정보 구조 리디자인
## 목표
기존 미니멀 터미널 UI를 유지하면서, 자기야가 제안한 레퍼런스의 강한 정보 구조를 흡수해 메인 대시보드를 `4자매 운영 관제의 대표 화면`으로 재정의한다.
## 핵심 방향
- glassmorphism으로 회귀하지 않음
- 현재 프로덕션의 미니멀 터미널 톤 유지
- 대신 레이아웃/정보 위계/운영 흐름 표현은 새 레퍼런스를 적극 반영
- 장식보다 운영 가독성을 우선
- 데스크톱 우선 설계 후 모바일 세로 흐름까지 함께 정리
## 디자인 원칙
1. **정보 구조 우선**
- 예쁜 카드보다 `지금 무엇이 진행 중인지`가 먼저 읽혀야 함
2. **운영 화면다운 밀도**
- 한 화면에서 자매 상태 / 현재 파이프라인 / 활동 / 지표 / 인프라를 함께 판단 가능해야 함
3. **현행 톤 유지**
- 배경, border, mono 보조 텍스트, 브라켓/터미널 감성은 유지
4. **애니메이션 절제**
- 상태 강조용 pulse/flow만 제한적으로 사용
- 불필요한 glow, 과한 색 번짐, 반복 뱃지는 줄임
5. **실데이터 우선**
- 예시 숫자가 아니라 실제 runtime/task/project/deploy 데이터를 붙일 수 있는 구조로 설계
## 범위
- 메인 대시보드(`/`) 레이아웃 v3 개편
- 상단 global status bar 재설계
- 4자매 상태 카드 재배치/요약 정보 재정의
- `ACTIVE PIPELINE` 섹션 신설
- `ACTIVITY FEED` / `SPRINT METRICS` 병렬 구조 재정렬
- `INFRASTRUCTURE OVERVIEW` / `MISTAKE LOG & HARNESS` 하단 운영 영역 재구성
- 기존 프로젝트/활동/자매/관리 페이지와 연결되는 진입 동선 재정리
## 제외 범위
- 이번 Sprint에서 새 도메인 기능 추가는 하지 않음
- 백엔드 데이터 모델을 대규모로 갈아엎지 않음
- 기존 페이지 전체를 동시 리디자인하지 않음
- chart 라이브러리 교체는 필요할 때만 제한적으로 수행
## 태스크
### TASK-070: 대시보드 v3 IA 확정 및 섹션 맵 정리
- **담당:** 하랑이 → 나랑이
- **상태:** pending
- **설명:** 레퍼런스를 현행 제품에 맞게 번역한 섹션 구조/우선순위를 확정한다.
- **산출물:**
- `.plans/design/ui/dashboard-design.md` 갱신
- 섹션별 데이터 소스 매핑 표
- **완료 기준:**
- 상단바 / 자매 카드 / Active Pipeline / Activity Feed / Metrics / Infra / Mistake Log의 역할이 문서로 명확함
### TASK-071: 상단 Global Status Bar + Hero Summary 개편
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `frontend/app/page.tsx`
- `frontend/components/**` 내 dashboard 공통 헤더/요약 관련 컴포넌트
- **설명:**
- 좌측 브랜드/페이지 아이덴티티
- 중앙 sprint/day 또는 현재 운영 focus
- 우측 연결 상태/알림/관리자 프로필 요약
구조를 재정의한다.
- **완료 기준:**
- 첫 화면 상단에서 현재 스프린트/연결 상태를 즉시 읽을 수 있음
- 모바일에서 세로 스택 또는 2단 구조로 무너지지 않음
### TASK-072: 4자매 상태 카드 v3 재설계
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `frontend/app/page.tsx`
- `frontend/components/sisters/**` 또는 대시보드 상태 카드 컴포넌트
- **설명:** 각 자매 카드에 아래 정보를 안정적으로 담는다.
- 이름 / 역할
- 현재 상태 (`IDLE`, `WORKING`, `REVIEWING`, `OFFLINE` 등)
- CPU / RAM 또는 대응 운영 지표
- 현재 작업 한 줄 요약
- **완료 기준:**
- 카드 4개가 한 세트로 읽힘
- 색상/강조는 자매별 역할과 상태를 동시에 표현함
- 아바타/아이콘/텍스트 길이 차이로 카드 높이가 깨지지 않음
### TASK-073: `ACTIVE PIPELINE` 시각화 도입
- **담당:** 나랑이
- **상태:** pending
- **의존성:** TASK-070
- **주요 파일:**
- `frontend/app/page.tsx`
- 새 공통 컴포넌트 생성 가능 (`frontend/components/dashboard/ActivePipeline.tsx` 등)
- **설명:**
- User → Harang → Narang → Darang → Irang 흐름을 운영 그래프로 표현
- maker-checker loop, escalation 조건, 현재 active task를 읽을 수 있게 구성
- **구현 메모:**
- SVG/HTML 혼합 구현 허용
- 애니메이션은 실제 active state가 있을 때만 제한적으로 사용
- 정적인 장식보다 상태 전달이 우선
- **완료 기준:**
- 현재 누가 받고/처리하고/검토 중인지 한눈에 보임
- 3회 실패 escalation 같은 운영 규칙이 과하지 않게 드러남
### TASK-074: `ACTIVITY FEED` / `SPRINT METRICS` 병렬 재배치
- **담당:** 나랑이
- **상태:** pending
- **주요 파일:**
- `frontend/app/page.tsx`
- 기존 activity/task/metrics 컴포넌트
- **설명:** 활동 피드와 지표를 같은 행에서 비교하는 운영 레이아웃으로 정렬한다.
- **완료 기준:**
- 활동 피드는 이벤트 타입/주체/대상 task를 읽기 쉬움
- metrics는 total tasks, 완료율, 반복 횟수, first-pass rate, escalation 수를 빠르게 읽을 수 있음
- mock처럼 보이지 않도록 실제 데이터 연결 포인트가 드러남
### TASK-075: `INFRASTRUCTURE OVERVIEW` / `MISTAKE LOG & HARNESS` 하단 운영 영역 구성
- **담당:** 나랑이
- **상태:** pending
- **설명:** 인프라 상태 맵과 mistake/harness 규칙 영역을 하단 2열 운영 패널로 정리한다.
- **주요 파일:**
- `frontend/app/page.tsx`
- 관련 API 데이터를 읽는 서비스/타입
- **완료 기준:**
- Gateway / sisters infra / deploy access 흐름이 읽힘
- MISTAKE.md/하네스 규칙 로그는 운영 학습 자산처럼 보여야 함
- 모바일에서는 Infra → Mistake Log 순 세로 배치
### TASK-076: 현행 디자인 시스템과 v3 레이아웃 정합화
- **담당:** 나랑이
- **상태:** pending
- **의존성:** TASK-071 ~ TASK-075
- **설명:** 새 레이아웃이 기존 미니멀 터미널 UI와 충돌하지 않게 색/간격/타이포/테두리 규칙을 정리한다.
- **완료 기준:**
- 기존 프로젝트/활동/설정 페이지와 같은 제품군처럼 보임
- Tailwind 레퍼런스의 분위기를 가져오되 styled-components 기반 현행 톤과 충돌하지 않음
### TASK-077: 반응형/실데이터 QA 준비
- **담당:** 나랑이 → 다랑이
- **상태:** pending
- **의존성:** TASK-071 ~ TASK-076
- **설명:** 데스크톱/태블릿/모바일 반응형과 실데이터 연결 상태를 확인하고 QA 요청 준비를 마친다.
- **완료 기준:**
- Desktop / Tablet / Mobile 주요 breakpoints 확인
- 빈 상태 / 긴 텍스트 / offline 상태 / 데이터 없음 상태가 깨지지 않음
- QA 전달 시 스크린샷 또는 확인 포인트 포함
## 데이터 매핑 기준
| 섹션 | 우선 데이터 |
|---|---|
| Global Status Bar | current sprint, connection status, notifications, current operator |
| Sister Cards | runtime status, role, usage metrics, current work summary |
| Active Pipeline | latest handoff, active implementation, active review, escalation count |
| Activity Feed | latest activities/log events/task transitions |
| Sprint Metrics | total tasks, completion, review loops, first-pass rate, escalations |
| Infrastructure Overview | gateway/node/server/process summary |
| Mistake Log & Harness | latest MISTAKE/Harness rules or derived operational lessons |
## UX 규칙
- 정보 순서는 `지금 상태 → 흐름 → 근거 이벤트 → 정량 지표 → 인프라/학습 자산`
- 카드 하나하나보다 섹션 간 관계가 더 중요함
- hover가 없어도 중요한 정보는 보여야 함
- 색은 상태 의미가 있을 때만 강하게 쓴다
- `Working`, `Reviewing`, `Ready for Deploy` 같은 운영 단어는 전체 제품에서 같은 표현을 유지한다
## 구현 제약
- styled-components 구조 유지
- 기존 공통 토큰/색 변수 최대한 재사용
- 새 레이아웃 때문에 기존 페이지 진입 동선이 숨지면 안 됨
- 과한 애니메이션/지속적인 repaint 유발 구현 지양
- fake 숫자 하드코딩으로 끝내지 말고 실데이터 연결 지점을 남길 것
## 검증 기준
- 홈 화면 진입 시 `하나랑 대시보드가 무엇을 운영하는지` 즉시 이해됨
- 4자매 상태와 현재 파이프라인이 첫 스크롤 안에서 읽힘
- 활동/지표/인프라/학습 로그가 운영자 관점에서 자연스럽게 이어짐
- 데스크톱/모바일 모두 정보 손실 없이 읽힘
- 현행 미니멀 터미널 UI와 충돌하지 않음
## 참고
- 레퍼런스는 `정보 구조`를 강하게 채택
- 비주얼은 현재 제품 톤을 유지한 상태로 70%만 차용
- `ACTIVE PIPELINE`은 이번 v3 리디자인의 대표 섹션으로 취급

View File

@@ -6,6 +6,9 @@
"private": true,
"license": "UNLICENSED",
"scripts": {
"prisma:generate": "prisma generate",
"prebuild": "npm run prisma:generate",
"pretest": "npm run prisma:generate",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",

View File

@@ -6,10 +6,7 @@ export class ActivityController {
constructor(private readonly activityService: ActivityService) {}
@Get('activity')
getFeed(
@Query('limit') limit?: string,
@Query('offset') offset?: string,
) {
getFeed(@Query('limit') limit?: string, @Query('offset') offset?: string) {
return this.activityService.getFeed(
limit ? parseInt(limit, 10) : 50,
offset ? parseInt(offset, 10) : 0,

View File

@@ -7,7 +7,9 @@ describe('ActivityService', () => {
const mockPrisma = {
activityLog: {
create: jest.fn().mockResolvedValue({ id: 1, action: 'test', createdAt: new Date() }),
create: jest
.fn()
.mockResolvedValue({ id: 1, action: 'test', createdAt: new Date() }),
findMany: jest.fn().mockResolvedValue([]),
count: jest.fn().mockResolvedValue(0),
},

View File

@@ -15,7 +15,11 @@ function sanitizeActivityDetail(detail?: string | null): string | undefined {
const raw = detail.trim();
// 내부 stderr/명령문 직접 노출 금지
if (/stderr:/i.test(raw) || /command not found/i.test(raw) || /bash:\s*line/i.test(raw)) {
if (
/stderr:/i.test(raw) ||
/command not found/i.test(raw) ||
/bash:\s*line/i.test(raw)
) {
return '내부 작업 중 오류가 발생했어. 자세한 시스템 로그는 관리자 로그에서 확인할 수 있어.';
}
@@ -66,7 +70,10 @@ export class ActivityService {
this.prisma.activityLog.count(),
]);
return {
items: items.map((item) => ({ ...item, detail: sanitizeActivityDetail(item.detail) })),
items: items.map((item) => ({
...item,
detail: sanitizeActivityDetail(item.detail),
})),
total,
limit,
offset,
@@ -87,7 +94,10 @@ export class ActivityService {
this.prisma.activityLog.count({ where: { projectId } }),
]);
return {
items: items.map((item) => ({ ...item, detail: sanitizeActivityDetail(item.detail) })),
items: items.map((item) => ({
...item,
detail: sanitizeActivityDetail(item.detail),
})),
total,
limit,
offset,

View File

@@ -10,9 +10,16 @@ describe('AdminService', () => {
let service: AdminService;
const mockSister = {
id: 2, name: 'narang', ip: '10.10.10.216', user: 'narang',
lxcId: 105, status: 'online', lastSeen: new Date(),
sshKeyPath: null, createdAt: new Date(), updatedAt: new Date(),
id: 2,
name: 'narang',
ip: '10.10.10.216',
user: 'narang',
lxcId: 105,
status: 'online',
lastSeen: new Date(),
sshKeyPath: null,
createdAt: new Date(),
updatedAt: new Date(),
};
const mockPrisma = {
@@ -30,7 +37,9 @@ describe('AdminService', () => {
{ provide: ActivityService, useValue: mockActivity },
{
provide: ConfigService,
useValue: { get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa') },
useValue: {
get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa'),
},
},
],
}).compile();
@@ -41,7 +50,11 @@ describe('AdminService', () => {
});
it('restartSister: SSH 성공 시 success=true', async () => {
mockSsh.executeCommand.mockResolvedValue({ stdout: 'RESTART_OK', stderr: '', code: 0 });
mockSsh.executeCommand.mockResolvedValue({
stdout: 'RESTART_OK',
stderr: '',
code: 0,
});
const result = await service.restartSister('narang');

View File

@@ -5,7 +5,13 @@ import { SshService } from '../sisters/ssh.service';
import { ActivityService } from '../activity/activity.service';
import { SisterName } from '../common/sister-name.pipe';
const ALLOWED_HARNESS_FILES = ['AGENTS.md', 'SOUL.md', 'PROTOCOL.md', 'TOOLS.md', 'HEARTBEAT.md'] as const;
const ALLOWED_HARNESS_FILES = [
'AGENTS.md',
'SOUL.md',
'PROTOCOL.md',
'TOOLS.md',
'HEARTBEAT.md',
] as const;
type HarnessFile = (typeof ALLOWED_HARNESS_FILES)[number];
@Injectable()
@@ -36,7 +42,9 @@ export class AdminService {
await this.activity.log({
sisterId: sister.id,
action: 'gateway_restart',
detail: success ? 'Gateway restart successful' : `stderr: ${result.stderr}`,
detail: success
? 'Gateway restart successful'
: `stderr: ${result.stderr}`,
});
return { success, output: result.stdout, error: result.stderr || null };
@@ -68,7 +76,9 @@ export class AdminService {
await this.activity.log({
sisterId: sister.id,
action: 'session_reset',
detail: success ? 'Session reset successful' : `stderr: ${result.stderr}`,
detail: success
? 'Session reset successful'
: `stderr: ${result.stderr}`,
});
return { success, output: result.stdout, error: result.stderr || null };
@@ -102,7 +112,7 @@ export class AdminService {
const keyPath = this.getKeyPath();
// 내용에서 위험한 셸 escape + null byte 방지
const escaped = content.replace(/\x00/g, '').replace(/'/g, "'\\''");
const escaped = content.split('\0').join('').replace(/'/g, "'\\''");
try {
const result = await this.ssh.executeCommand(
@@ -162,7 +172,9 @@ export class AdminService {
}
private async getSister(name: SisterName) {
const sister = await this.prisma.sisterConfig.findUnique({ where: { name } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name },
});
if (!sister) throw new Error(`Sister ${name} not found`);
return sister;
}

View File

@@ -17,6 +17,7 @@ import { EventsModule } from './events/events.module';
import { CostsModule } from './costs/costs.module';
import { GiteaSyncModule } from './gitea-sync/gitea-sync.module';
import { SettingsModule } from './settings/settings.module';
import { DashboardModule } from './dashboard/dashboard.module';
@Module({
imports: [
@@ -36,6 +37,7 @@ import { SettingsModule } from './settings/settings.module';
CostsModule,
GiteaSyncModule,
SettingsModule,
DashboardModule,
],
controllers: [AppController],
providers: [AppService],

View File

@@ -8,10 +8,15 @@ import {
Request,
BadRequestException,
} from '@nestjs/common';
import type { Request as ExpressRequest } from 'express';
import { AuthService, LoginDto } from './auth.service';
import { JwtGuard } from './jwt.guard';
import { Throttle, ThrottlerGuard } from '@nestjs/throttler';
interface AuthenticatedRequest extends ExpressRequest {
user: { userId: number };
}
@Controller('api/auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@@ -31,7 +36,7 @@ export class AuthController {
@UseGuards(JwtGuard)
@Get('me')
getMe(@Request() req: any) {
getMe(@Request() req: AuthenticatedRequest) {
return this.authService.getMe(req.user.userId);
}
}

View File

@@ -6,10 +6,12 @@ import * as bcrypt from 'bcrypt';
import { IsString, IsNotEmpty } from 'class-validator';
export class LoginDto {
@IsString() @IsNotEmpty()
@IsString()
@IsNotEmpty()
username!: string;
@IsString() @IsNotEmpty()
@IsString()
@IsNotEmpty()
password!: string;
}
@@ -22,7 +24,9 @@ export class AuthService {
) {}
async login(dto: LoginDto) {
const user = await this.prisma.user.findUnique({ where: { username: dto.username } });
const user = await this.prisma.user.findUnique({
where: { username: dto.username },
});
if (!user) throw new UnauthorizedException('Invalid credentials');
const ok = await bcrypt.compare(dto.password, user.password);
@@ -33,11 +37,16 @@ export class AuthService {
async refresh(refreshToken: string) {
try {
const payload = this.jwt.verify<{ sub: number; username: string; role: string }>(
refreshToken,
{ secret: this.config.get<string>('JWT_SECRET') + '_refresh' },
);
const user = await this.prisma.user.findUnique({ where: { id: payload.sub } });
const payload = this.jwt.verify<{
sub: number;
username: string;
role: string;
}>(refreshToken, {
secret: this.config.get<string>('JWT_SECRET') + '_refresh',
});
const user = await this.prisma.user.findUnique({
where: { id: payload.sub },
});
if (!user) throw new UnauthorizedException();
return this.signTokens(user.id, user.username, user.role);
} catch {
@@ -60,7 +69,10 @@ export class AuthService {
const payload = { sub: userId, username, role };
const accessToken = this.jwt.sign(payload, { secret, expiresIn: '15m' });
const refreshToken = this.jwt.sign(payload, { secret: secret + '_refresh', expiresIn: '7d' });
const refreshToken = this.jwt.sign(payload, {
secret: secret + '_refresh',
expiresIn: '7d',
});
return { accessToken, refreshToken, username, role };
}

View File

@@ -23,6 +23,10 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
validate(payload: JwtPayload) {
if (!payload?.sub) throw new UnauthorizedException();
return { userId: payload.sub, username: payload.username, role: payload.role };
return {
userId: payload.sub,
username: payload.username,
role: payload.role,
};
}
}

View File

@@ -1,28 +1,46 @@
import { Injectable, CanActivate, ExecutionContext, ForbiddenException, SetMetadata } from '@nestjs/common';
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
SetMetadata,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { Request as ExpressRequest } from 'express';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
interface RoleUser {
role: string;
}
interface RequestWithUser extends ExpressRequest {
user?: RoleUser;
}
@Injectable()
export class RoleGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles || requiredRoles.length === 0) return true;
const request = context.switchToHttp().getRequest();
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
if (!user) throw new ForbiddenException('Authentication required');
const hasRole = requiredRoles.includes(user.role);
if (!hasRole) throw new ForbiddenException(`Role '${user.role}' not authorized. Required: ${requiredRoles.join(', ')}`);
if (!hasRole)
throw new ForbiddenException(
`Role '${user.role}' not authorized. Required: ${requiredRoles.join(', ')}`,
);
return true;
}

View File

@@ -14,7 +14,9 @@ export class CostsController {
@Get()
getCosts(@Query('period') period?: string) {
const validPeriods: CostPeriod[] = ['day', 'week', 'month'];
const p = validPeriods.includes(period as CostPeriod) ? (period as CostPeriod) : 'week';
const p = validPeriods.includes(period as CostPeriod)
? (period as CostPeriod)
: 'week';
return this.costsService.getCosts(p);
}

View File

@@ -14,8 +14,6 @@ const MODEL_PRICING: Record<string, { input: number; output: number }> = {
default: { input: 3.0, output: 15.0 },
};
const SISTER_NAMES: SisterName[] = ['harang', 'narang', 'darang', 'erang'];
export type CostPeriod = 'day' | 'week' | 'month';
@Injectable()
@@ -38,14 +36,23 @@ export class CostsService {
this.getTimeline(since, period),
]);
return { period, since: since.toISOString(), summary, bySister, byModel, timeline };
return {
period,
since: since.toISOString(),
summary,
bySister,
byModel,
timeline,
};
}
async recordCosts(sisterName: SisterName) {
const keyPath = this.config.get<string>('SSH_KEY_PATH');
if (!keyPath) return;
const sister = await this.prisma.sisterConfig.findUnique({ where: { name: sisterName } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name: sisterName },
});
if (!sister) return;
try {
@@ -99,7 +106,12 @@ export class CostsService {
private async getSummary(since: Date) {
const result = await this.prisma.costLog.aggregate({
where: { recordedAt: { gte: since } },
_sum: { inputTokens: true, outputTokens: true, totalTokens: true, estimatedUsd: true },
_sum: {
inputTokens: true,
outputTokens: true,
totalTokens: true,
estimatedUsd: true,
},
_count: true,
});
@@ -145,14 +157,23 @@ export class CostsService {
}
private async getTimeline(since: Date, period: CostPeriod) {
void period;
const logs = await this.prisma.costLog.findMany({
where: { recordedAt: { gte: since } },
orderBy: { recordedAt: 'asc' },
select: { sisterName: true, totalTokens: true, estimatedUsd: true, recordedAt: true },
select: {
sisterName: true,
totalTokens: true,
estimatedUsd: true,
recordedAt: true,
},
});
// 날짜별 집계
const grouped: Record<string, { date: string; totalTokens: number; estimatedUsd: number }> = {};
const grouped: Record<
string,
{ date: string; totalTokens: number; estimatedUsd: number }
> = {};
for (const log of logs) {
const dateKey = log.recordedAt.toISOString().slice(0, 10);
@@ -172,9 +193,12 @@ export class CostsService {
private getSince(period: CostPeriod): Date {
const now = new Date();
switch (period) {
case 'day': return new Date(now.getTime() - 24 * 60 * 60 * 1000);
case 'week': return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
case 'month': return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
case 'day':
return new Date(now.getTime() - 24 * 60 * 60 * 1000);
case 'week':
return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
case 'month':
return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
}
}
}

View File

@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { DashboardService } from './dashboard.service';
@Controller('api/dashboard')
export class DashboardController {
constructor(private readonly dashboardService: DashboardService) {}
@Get('ops')
getOpsBoard(): Promise<any> {
return this.dashboardService.getOpsBoard();
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { DashboardController } from './dashboard.controller';
import { DashboardService } from './dashboard.service';
import { PrismaModule } from '../prisma/prisma.module';
import { ProjectsModule } from '../projects/projects.module';
import { GiteaModule } from '../gitea/gitea.module';
@Module({
imports: [PrismaModule, ProjectsModule, GiteaModule],
controllers: [DashboardController],
providers: [DashboardService],
exports: [DashboardService],
})
export class DashboardModule {}

View File

@@ -0,0 +1,303 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { ProjectsService } from '../projects/projects.service';
import { GiteaService } from '../gitea/gitea.service';
interface ActivityRecord {
id: number;
action: string;
detail: string | null;
createdAt: Date;
sister: { name: string } | null;
project: { name: string } | null;
}
interface OpsBoardItem {
id: string;
title: string;
body: string;
tone: 'default' | 'warn' | 'ok' | 'active';
author: string;
time: string;
category: string;
source: string;
}
const QA_PATH_CANDIDATES = ['.plans/qa/', '.qa/'];
const SISTER_ROLES: Record<string, string> = {
harang: 'Plan & Assign',
narang: 'Implement',
darang: 'Review / QA',
erang: 'Deploy / Infra',
};
function toneFromText(text: string): 'default' | 'warn' | 'ok' | 'active' {
const normalized = text.toLowerCase();
if (/(fail|error|blocker|offline|invalid|drift)/.test(normalized))
return 'warn';
if (/(passed|deploy|merged|restart_ok|write_ok|successful)/.test(normalized))
return 'ok';
if (/(review|qa|handoff|sync|update)/.test(normalized)) return 'active';
return 'default';
}
function nodeStateFromEvidence(params: {
sisterStatus?: string;
activity?: ActivityRecord | null;
name: string;
}): 'idle' | 'active' | 'review' | 'blocked' | 'ready' {
const { sisterStatus, activity, name } = params;
const text =
`${activity?.action ?? ''} ${activity?.detail ?? ''}`.toLowerCase();
if (name !== 'user' && sisterStatus === 'offline') return 'blocked';
if (/(review|qa)/.test(text)) return 'review';
if (
name === 'erang' &&
/(deploy|merged|ready for deploy|deployed)/.test(text)
)
return 'ready';
if (sisterStatus === 'working') return 'active';
if (activity) return 'ready';
return 'idle';
}
function summarizeActivity(
activity?: ActivityRecord | null,
fallback = '최근 이벤트 없음',
) {
return (
activity?.detail?.trim() || activity?.action?.replace(/_/g, ' ') || fallback
);
}
function parseQaSummary(content: string): string {
const lines = content.split(/\r?\n/).map((line) => line.trim());
const taskLine = lines.find((line) => /^###\s+/.test(line));
if (taskLine) return taskLine.replace(/^###\s+/, '').trim();
const bullet = lines.find((line) => /^-\s+/.test(line));
if (bullet) return bullet.replace(/^-\s+/, '').trim();
return (
lines.find((line) => line.length > 0 && !line.startsWith('#')) ?? 'QA note'
);
}
function inferQaAuthor(path: string, content: string): string {
if (/darang/i.test(path) || /다랑/i.test(content)) return '다랑이';
if (/harang/i.test(path) || /하랑/i.test(content)) return '하랑이';
return 'QA Doc';
}
function extractRepoName(repoUrl: string): string {
return repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
}
@Injectable()
export class DashboardService {
constructor(
private readonly prisma: PrismaService,
private readonly projectsService: ProjectsService,
private readonly gitea: GiteaService,
) {}
async getOpsBoard() {
const [projects, sisters, rawActivities] = await Promise.all([
this.projectsService.getProjects(),
this.prisma.sisterConfig.findMany({ orderBy: { id: 'asc' } }),
this.prisma.activityLog.findMany({
orderBy: { createdAt: 'desc' },
take: 40,
include: {
sister: { select: { name: true } },
project: { select: { name: true } },
},
}),
]);
const activities = rawActivities as ActivityRecord[];
const latestProjectActivity =
activities.find((item) => item.project?.name) ?? null;
const latestBySister = new Map<string, ActivityRecord>();
for (const item of activities) {
if (item.sister?.name && !latestBySister.has(item.sister.name)) {
latestBySister.set(item.sister.name, item);
}
}
const focusProject = latestProjectActivity?.project?.name
? (projects.find(
(project) => project.name === latestProjectActivity.project?.name,
) ?? null)
: (projects.find((project) =>
['IMPLEMENT', 'QA', 'READY FOR DEPLOY'].includes(project.phase),
) ?? null);
const reviewLoopCount = activities.filter((item) =>
/(review|qa)/i.test(`${item.action} ${item.detail ?? ''}`),
).length;
const escalationCount = projects.filter(
(project) => (project.blockerCount ?? 0) > 0,
).length;
const nodes = [
{
id: 'user',
label: 'User',
role: 'Request / Approval',
state: nodeStateFromEvidence({
name: 'user',
activity: latestProjectActivity,
}),
detail: latestProjectActivity
? `${latestProjectActivity.project?.name ?? 'project'} · ${summarizeActivity(latestProjectActivity, '최근 프로젝트 이벤트 없음')}`
: '명시적으로 기록된 handoff / request 로그가 아직 없어.',
},
...sisters.map((sister) => {
const activity = latestBySister.get(sister.name) ?? null;
return {
id: sister.name,
label:
sister.name === 'erang'
? 'Irang'
: `${sister.name.slice(0, 1).toUpperCase()}${sister.name.slice(1)}`,
role: SISTER_ROLES[sister.name] ?? 'Unknown',
state: nodeStateFromEvidence({
name: sister.name,
sisterStatus: sister.status,
activity,
}),
detail: activity
? summarizeActivity(activity)
: sister.status === 'offline'
? '최근 런타임 응답이 없어서 offline 상태야.'
: sister.lastSeen
? `최근 활동 기록은 ${new Date(sister.lastSeen).toISOString()} 체크 기준이야.`
: '최근 활동 로그가 아직 없어.',
};
}),
];
const harnessItems = activities
.filter((item) => item.action === 'harness_updated')
.slice(0, 4)
.map(
(item) =>
({
id: `harness-${item.id}`,
title: item.detail ?? 'Harness updated',
body: '관리자 harness 편집 로그에서 직접 가져온 기록이야.',
tone: toneFromText(`${item.action} ${item.detail ?? ''}`),
author: item.sister?.name
? this.toDisplayName(item.sister.name)
: 'System',
time: item.createdAt.toISOString(),
category: 'harness',
source: `activity:${item.action}`,
}) satisfies OpsBoardItem,
);
const qaItems = await this.getLatestQaBoardItems(
projects.map((project) => ({
name: project.name,
repoName: extractRepoName(project.repoUrl),
updatedAt: project.updatedAt,
})),
);
const board = [...harnessItems, ...qaItems]
.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime())
.slice(0, 6);
return {
focusProject: focusProject
? {
name: focusProject.name,
ownerSister: focusProject.ownerSister ?? null,
phase: focusProject.phase,
currentSprint: focusProject.currentSprint ?? null,
progress: focusProject.progress ?? 0,
deployStatus: focusProject.deployStatus,
}
: null,
pipeline: {
activeTask: focusProject
? `${focusProject.name} · ${focusProject.currentSprint ?? focusProject.phase}`
: 'No active pipeline',
focus: latestProjectActivity
? summarizeActivity(
latestProjectActivity,
'최근 프로젝트 이벤트 없음',
)
: '최근 프로젝트 activity 기준으로 확정된 handoff가 아직 없어.',
reviewLoopCount,
escalationCount,
deployState: focusProject?.deployStatus ?? 'standby',
nodes,
},
board,
};
}
private async getLatestQaBoardItems(
projects: { name: string; repoName: string; updatedAt: string }[],
) {
const docs = await Promise.all(
projects.map(async (project) => {
if (!project.repoName) return [] as OpsBoardItem[];
const pathGroups = await Promise.all(
QA_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(project.repoName, path),
),
);
const qaFiles = Array.from(
new Set(
pathGroups
.flat()
.filter((path) =>
/(?:SPRINT|HOTFIX)-\d+.*(?:review|qa).*\.md$/i.test(path),
),
),
);
const latestPath = qaFiles.sort().at(-1);
if (!latestPath) return [] as OpsBoardItem[];
const content = await this.gitea.getRawFile(
project.repoName,
latestPath,
);
if (!content) return [] as OpsBoardItem[];
const summary = parseQaSummary(content);
const label =
latestPath.split('/').pop()?.replace(/\.md$/i, '') ?? latestPath;
const tone = toneFromText(content);
return [
{
id: `qa-${project.repoName}-${label}`,
title: label,
body: summary,
tone,
author: inferQaAuthor(latestPath, content),
time: project.updatedAt,
category: 'qa-log',
source: `${project.repoName}:${latestPath}`,
} satisfies OpsBoardItem,
];
}),
);
return docs.flat();
}
private toDisplayName(name: string) {
if (name === 'harang') return '하랑이';
if (name === 'narang') return '나랑이';
if (name === 'darang') return '다랑이';
if (name === 'erang') return '이랑이';
return name;
}
}

View File

@@ -11,6 +11,16 @@ import { Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
interface SocketUserPayload {
username?: string;
role?: string;
sub?: number;
}
interface SocketWithUser extends Socket {
user?: SocketUserPayload;
}
@WebSocketGateway({
cors: {
origin: (process.env.CORS_ORIGINS ?? 'http://localhost:3004')
@@ -37,11 +47,14 @@ export class EventsGateway
this.logger.log('WebSocket Gateway initialized');
}
handleConnection(client: Socket) {
handleConnection(client: SocketWithUser) {
// JWT 인증 필수 — 토큰 없거나 유효하지 않으면 disconnect
const token =
(client.handshake.auth?.token as string) ??
(client.handshake.headers.authorization as string)?.replace('Bearer ', '');
(client.handshake.headers.authorization as string)?.replace(
'Bearer ',
'',
);
if (!token) {
this.logger.debug(`WS rejected (no token): ${client.id}`);
@@ -56,9 +69,13 @@ export class EventsGateway
}
try {
const payload = this.jwtService.verify(token, { secret });
(client as any).user = payload;
this.logger.debug(`WS client connected: ${client.id} (${payload.username})`);
const payload = this.jwtService.verify<SocketUserPayload>(token, {
secret,
});
client.user = payload;
this.logger.debug(
`WS client connected: ${client.id} (${payload.username ?? 'unknown'})`,
);
} catch {
this.logger.debug(`WS rejected (invalid token): ${client.id}`);
client.disconnect();

View File

@@ -13,7 +13,11 @@ import { SistersModule } from '../sisters/sisters.module';
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: (() => { const s = config.get<string>('JWT_SECRET'); if (!s) throw new Error('JWT_SECRET is not configured'); return s; })(),
secret: (() => {
const s = config.get<string>('JWT_SECRET');
if (!s) throw new Error('JWT_SECRET is not configured');
return s;
})(),
}),
}),
],

View File

@@ -1,4 +1,9 @@
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import {
Injectable,
Logger,
OnModuleInit,
OnModuleDestroy,
} from '@nestjs/common';
import { SistersService } from '../sisters/sisters.service';
import { EventsGateway } from './events.gateway';
@@ -6,7 +11,10 @@ import { EventsGateway } from './events.gateway';
export class EventsScheduler implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(EventsScheduler.name);
private timer: NodeJS.Timeout | null = null;
private readonly INTERVAL_MS = parseInt(process.env.WS_POLL_INTERVAL_MS ?? '30000', 10);
private readonly INTERVAL_MS = parseInt(
process.env.WS_POLL_INTERVAL_MS ?? '30000',
10,
);
constructor(
private readonly sistersService: SistersService,
@@ -14,8 +22,12 @@ export class EventsScheduler implements OnModuleInit, OnModuleDestroy {
) {}
onModuleInit() {
this.timer = setInterval(() => this.tick(), this.INTERVAL_MS);
this.logger.log(`WebSocket scheduler started (interval: ${this.INTERVAL_MS}ms)`);
this.timer = setInterval(() => {
void this.tick();
}, this.INTERVAL_MS);
this.logger.log(
`WebSocket scheduler started (interval: ${this.INTERVAL_MS}ms)`,
);
}
onModuleDestroy() {

View File

@@ -14,13 +14,17 @@ export class SistersScheduler {
start() {
if (this.timer) return;
this.timer = setInterval(async () => {
try {
const sisters = await this.sistersService.getAllSistersStatus();
this.eventsGateway.broadcastSisterStatus(sisters);
} catch {
this.logger.warn('Failed to broadcast sisters update');
}
this.timer = setInterval(() => {
void this.broadcast();
}, 30000);
}
private async broadcast() {
try {
const sisters = await this.sistersService.getAllSistersStatus();
this.eventsGateway.broadcastSisterStatus(sisters);
} catch {
this.logger.warn('Failed to broadcast sisters update');
}
}
}

View File

@@ -8,7 +8,13 @@ import { AuthModule } from '../auth/auth.module';
import { ProjectsModule } from '../projects/projects.module';
@Module({
imports: [PrismaModule, GiteaModule, ActivityModule, AuthModule, ProjectsModule],
imports: [
PrismaModule,
GiteaModule,
ActivityModule,
AuthModule,
ProjectsModule,
],
controllers: [GiteaSyncController],
providers: [GiteaSyncService],
exports: [GiteaSyncService],

View File

@@ -1,5 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../prisma/prisma.service';
import { GiteaService } from '../gitea/gitea.service';
import { ActivityService } from '../activity/activity.service';
@@ -17,7 +16,11 @@ export class GiteaSyncService {
private readonly sprintSync: SprintSyncService,
) {}
async syncRepos(): Promise<{ synced: number; created: number; updated: number }> {
async syncRepos(): Promise<{
synced: number;
created: number;
updated: number;
}> {
const repos = await this.gitea.getOrgRepos();
if (!repos.length) {
@@ -71,11 +74,14 @@ export class GiteaSyncService {
});
}
this.logger.log(`Gitea sync: ${repos.length} repos, ${created} new, ${updated} updated`);
this.logger.log(
`Gitea sync: ${repos.length} repos, ${created} new, ${updated} updated`,
);
// Sprint 동기화도 함께 수행
await this.sprintSync.syncAllProjectSprints().catch((e) => {
this.logger.warn(`Sprint sync failed: ${e.message}`);
await this.sprintSync.syncAllProjectSprints().catch((e: unknown) => {
const message = e instanceof Error ? e.message : String(e);
this.logger.warn(`Sprint sync failed: ${message}`);
});
return { synced: repos.length, created, updated };

View File

@@ -45,7 +45,7 @@ export interface GiteaBranch {
@Injectable()
export class GiteaService {
private readonly logger = new Logger(GiteaService.name);
private readonly client: AxiosInstance;
private readonly client: AxiosInstance | null;
private readonly org: string;
constructor(private readonly config: ConfigService) {
@@ -54,8 +54,10 @@ export class GiteaService {
this.org = config.get<string>('GITEA_ORG') ?? 'hanarang';
if (!baseURL || !token) {
this.logger.warn('GITEA_BASE_URL or GITEA_TOKEN not set — Gitea features disabled');
this.client = null as any;
this.logger.warn(
'GITEA_BASE_URL or GITEA_TOKEN not set — Gitea features disabled',
);
this.client = null;
return;
}
@@ -66,27 +68,30 @@ export class GiteaService {
});
}
private isAvailable(): boolean {
return this.client !== null;
}
async getOrgRepos(): Promise<GiteaRepo[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaRepo[]>(`/orgs/${this.org}/repos`, {
params: { limit: 50 },
});
const { data } = await client.get<GiteaRepo[]>(
`/orgs/${this.org}/repos`,
{
params: { limit: 50 },
},
);
return data;
} catch (error) {
} catch {
this.logger.warn('Failed to fetch Gitea repos');
return [];
}
}
async getRepo(repoName: string): Promise<GiteaRepo | null> {
if (!this.isAvailable()) return null;
const client = this.client;
if (!client) return null;
try {
const { data } = await this.client.get<GiteaRepo>(`/repos/${this.org}/${repoName}`);
const { data } = await client.get<GiteaRepo>(
`/repos/${this.org}/${repoName}`,
);
return data;
} catch {
return null;
@@ -94,9 +99,10 @@ export class GiteaService {
}
async getOpenPRs(repoName: string): Promise<GiteaPR[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaPR[]>(
const { data } = await client.get<GiteaPR[]>(
`/repos/${this.org}/${repoName}/pulls`,
{ params: { state: 'open', limit: 20 } },
);
@@ -107,9 +113,10 @@ export class GiteaService {
}
async getCommits(repoName: string, limit = 20): Promise<GiteaCommit[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaCommit[]>(
const { data } = await client.get<GiteaCommit[]>(
`/repos/${this.org}/${repoName}/commits`,
{ params: { limit } },
);
@@ -121,9 +128,10 @@ export class GiteaService {
}
async getBranches(repoName: string): Promise<GiteaBranch[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaBranch[]>(
const { data } = await client.get<GiteaBranch[]>(
`/repos/${this.org}/${repoName}/branches`,
{ params: { limit: 50 } },
);
@@ -133,10 +141,14 @@ export class GiteaService {
}
}
async getPulls(repoName: string, state: 'open' | 'closed' | 'all' = 'open'): Promise<GiteaPR[]> {
if (!this.isAvailable()) return [];
async getPulls(
repoName: string,
state: 'open' | 'closed' | 'all' = 'open',
): Promise<GiteaPR[]> {
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<GiteaPR[]>(
const { data } = await client.get<GiteaPR[]>(
`/repos/${this.org}/${repoName}/pulls`,
{ params: { state, limit: 30, type: 'pulls' } },
);
@@ -147,22 +159,27 @@ export class GiteaService {
}
async getRepoTree(repoName: string, treePath: string): Promise<string[]> {
if (!this.isAvailable()) return [];
const client = this.client;
if (!client) return [];
try {
const { data } = await this.client.get<{ tree: { path: string; type: string }[] }>(
`/repos/${this.org}/${repoName}/git/trees/HEAD`,
{ params: { recursive: true } },
);
return (data.tree ?? []).filter((e) => e.path.startsWith(treePath) && e.type === 'blob').map((e) => e.path);
const { data } = await client.get<{
tree: { path: string; type: string }[];
}>(`/repos/${this.org}/${repoName}/git/trees/HEAD`, {
params: { recursive: true },
});
return (data.tree ?? [])
.filter((e) => e.path.startsWith(treePath) && e.type === 'blob')
.map((e) => e.path);
} catch {
return [];
}
}
async getRawFile(repoName: string, filePath: string): Promise<string | null> {
if (!this.isAvailable()) return null;
const client = this.client;
if (!client) return null;
try {
const { data } = await this.client.get<string>(
const { data } = await client.get<string>(
`/repos/${this.org}/${repoName}/raw/${filePath}`,
{ params: { ref: 'main' }, responseType: 'text' },
);

View File

@@ -3,18 +3,25 @@ import { Logger, ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
import helmet from 'helmet';
function getAllowedOrigins() {
return (process.env.CORS_ORIGINS ?? 'http://localhost:3004')
.split(',')
.map((origin) => origin.trim())
.filter((origin): origin is string => origin.length > 0);
}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(helmet());
const allowedOrigins = (process.env.CORS_ORIGINS ?? 'http://localhost:3004')
.split(',')
.map((o) => o.trim())
.filter(Boolean);
const allowedOrigins = getAllowedOrigins();
app.enableCors({
origin: (origin, callback) => {
origin: (
origin: string | undefined,
callback: (err: Error | null, allow?: boolean) => void,
) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
@@ -25,10 +32,17 @@ async function bootstrap() {
credentials: true,
});
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
const port = process.env.BACKEND_PORT ?? 3005;
const port = Number(process.env.BACKEND_PORT ?? 3005);
await app.listen(port);
Logger.log(`🚀 Backend running on port ${port}`, 'Bootstrap');
}
bootstrap();
void bootstrap();

View File

@@ -4,7 +4,10 @@ import { PrismaClient } from '@prisma/client';
import { PrismaMariaDb } from '@prisma/adapter-mariadb';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
constructor(config: ConfigService) {
const dbUrl = config.get<string>('DATABASE_URL');
if (!dbUrl) {

View File

@@ -1,4 +1,12 @@
import { Controller, Get, Param, Query, ParseIntPipe, UseGuards, Post } from '@nestjs/common';
import {
Controller,
Get,
Param,
Query,
ParseIntPipe,
UseGuards,
Post,
} from '@nestjs/common';
import { ProjectsService } from './projects.service';
import { SprintSyncService } from './sprint-sync.service';
import { JwtGuard } from '../auth/jwt.guard';

View File

@@ -3,7 +3,12 @@ import { PrismaService } from '../prisma/prisma.service';
import { GiteaService } from '../gitea/gitea.service';
type QaStatus = 'passed' | 'failed' | 'unknown';
type ProjectPhase = 'PLANNING' | 'IMPLEMENT' | 'QA' | 'READY FOR DEPLOY' | 'DEPLOYED';
type ProjectPhase =
| 'PLANNING'
| 'IMPLEMENT'
| 'QA'
| 'READY FOR DEPLOY'
| 'DEPLOYED';
export interface RepoDocumentMeta {
path: string;
@@ -36,7 +41,10 @@ function normalizeRepoName(repoUrl: string): string {
return repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
}
function extractDocOrder(path: string, kind: 'sprint' | 'hotfix' | 'qa'): number {
function extractDocOrder(
path: string,
kind: 'sprint' | 'hotfix' | 'qa',
): number {
const name = path.split('/').pop() ?? '';
if (kind === 'hotfix') {
const hotfix = name.match(/HOTFIX-(\d+)/i);
@@ -81,7 +89,8 @@ function parseTaskSummary(content: string): string | null {
function parseQaStatus(content: string): QaStatus {
if (/passed\s*[:=]\s*true/i.test(content)) return 'passed';
if (/passed\s*[:=]\s*false/i.test(content)) return 'failed';
if (/\bPASSED\b/i.test(content) && !/\bFAILED\b/i.test(content)) return 'passed';
if (/\bPASSED\b/i.test(content) && !/\bFAILED\b/i.test(content))
return 'passed';
if (/\bFAILED\b/i.test(content)) return 'failed';
return 'unknown';
}
@@ -89,19 +98,27 @@ function parseQaStatus(content: string): QaStatus {
function parseBlockerCount(content: string): number {
const jsonMatch = content.match(/"errors"\s*:\s*\[(.*?)\]/is);
if (jsonMatch) {
const items = jsonMatch[1].split(',').map((item) => item.trim()).filter(Boolean);
const items = jsonMatch[1]
.split(',')
.map((item) => item.trim())
.filter(Boolean);
if (items.length > 0) return items.length;
}
const errorLines = content
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => /^[-*]\s+/.test(line) && /(error|blocker|실패|문제)/i.test(line));
.filter(
(line) =>
/^[-*]\s+/.test(line) && /(error|blocker|실패|문제)/i.test(line),
);
return errorLines.length;
}
function isRepoDocumentMeta(value: RepoDocumentMeta | null): value is RepoDocumentMeta {
function isRepoDocumentMeta(
value: RepoDocumentMeta | null,
): value is RepoDocumentMeta {
return value !== null;
}
@@ -141,11 +158,12 @@ function buildProjectMeta(params: {
phase = 'IMPLEMENT';
}
const deployStatus = phase === 'DEPLOYED'
? 'DEPLOYED ON MAIN'
: phase === 'READY FOR DEPLOY'
? 'READY FOR DEPLOY'
: 'REDEPLOY REQUIRED';
const deployStatus =
phase === 'DEPLOYED'
? 'DEPLOYED ON MAIN'
: phase === 'READY FOR DEPLOY'
? 'READY FOR DEPLOY'
: 'REDEPLOY REQUIRED';
return {
phase,
@@ -177,17 +195,30 @@ export class ProjectsService {
const [repoMetaMap, repoDocsMap] = await Promise.all([
this.getRepoMetaMap(),
this.getRepoDocumentMap(dbProjects.map((project) => normalizeRepoName(project.repoUrl))),
this.getRepoDocumentMap(
dbProjects.map((project) => normalizeRepoName(project.repoUrl)),
),
]);
return dbProjects.map((project) => {
const totalSprints = project.sprints.length;
const doneSprints = project.sprints.filter((sprint) => sprint.status === 'done').length;
const inProgressSprint = project.sprints.find((sprint) => sprint.status === 'in_progress');
const ownerSister = project.sprints.flatMap((sprint) => sprint.tasks).find((task) => task.assignee)?.assignee ?? 'narang';
const progress = totalSprints > 0 ? Math.round((doneSprints / totalSprints) * 100) : 0;
const doneSprints = project.sprints.filter(
(sprint) => sprint.status === 'done',
).length;
const inProgressSprint = project.sprints.find(
(sprint) => sprint.status === 'in_progress',
);
const ownerSister =
project.sprints
.flatMap((sprint) => sprint.tasks)
.find((task) => task.assignee)?.assignee ?? 'narang';
const progress =
totalSprints > 0 ? Math.round((doneSprints / totalSprints) * 100) : 0;
const repoMeta = repoMetaMap[project.giteaId];
const docs = repoDocsMap.get(normalizeRepoName(project.repoUrl)) ?? { hotfixes: [], qas: [] };
const docs = repoDocsMap.get(normalizeRepoName(project.repoUrl)) ?? {
hotfixes: [],
qas: [],
};
const latestHotfix = docs.hotfixes.at(-1) ?? null;
const latestQa = docs.qas.at(-1) ?? null;
const meta = buildProjectMeta({
@@ -213,7 +244,11 @@ export class ProjectsService {
totalSprints,
doneSprints,
sprintCount: totalSprints,
currentSprint: inProgressSprint?.name ?? (doneSprints === totalSprints && totalSprints > 0 ? 'COMPLETED' : null),
currentSprint:
inProgressSprint?.name ??
(doneSprints === totalSprints && totalSprints > 0
? 'COMPLETED'
: null),
ownerSister,
openPRs: repoMeta?.openPRs ?? 0,
updatedAt: repoMeta?.updatedAt ?? project.updatedAt.toISOString(),
@@ -253,8 +288,12 @@ export class ProjectsService {
]);
const totalSprints = project.sprints.length;
const doneSprints = project.sprints.filter((sprint) => sprint.status === 'done').length;
const activeSprint = project.sprints.find((sprint) => sprint.status === 'in_progress');
const doneSprints = project.sprints.filter(
(sprint) => sprint.status === 'done',
).length;
const activeSprint = project.sprints.find(
(sprint) => sprint.status === 'in_progress',
);
const meta = buildProjectMeta({
totalSprints,
doneSprints,
@@ -276,7 +315,8 @@ export class ProjectsService {
label: docs.qas.at(-1)?.label ?? null,
status: docs.qas.at(-1)?.qaStatus ?? 'unknown',
blockerCount: docs.qas.at(-1)?.blockerCount ?? 0,
summary: docs.qas.at(-1)?.summary ?? docs.qas.at(-1)?.description ?? null,
summary:
docs.qas.at(-1)?.summary ?? docs.qas.at(-1)?.description ?? null,
}
: null,
deploy: {
@@ -310,17 +350,23 @@ export class ProjectsService {
const repoName = normalizeRepoName(project.repoUrl);
const docs = await this.collectRepoDocuments(repoName);
return [...docs.sprints, ...docs.hotfixes].filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order);
return [...docs.sprints, ...docs.hotfixes]
.filter(isRepoDocumentMeta)
.sort((a, b) => a.order - b.order);
}
private async getProjectMeta(id: number) {
const project = await this.prisma.project.findUnique({ where: { id }, select: { id: true, repoUrl: true } });
const project = await this.prisma.project.findUnique({
where: { id },
select: { id: true, repoUrl: true },
});
if (!project) throw new NotFoundException(`Project ${id} not found`);
return project;
}
private async getRepoMetaMap() {
const repoMetaMap: Record<number, { openPRs: number; updatedAt: string }> = {};
const repoMetaMap: Record<number, { openPRs: number; updatedAt: string }> =
{};
try {
const repos = await this.gitea.getOrgRepos();
for (const repo of repos) {
@@ -337,35 +383,80 @@ export class ProjectsService {
private async getRepoDocumentMap(repoNames: string[]) {
const uniqueRepoNames = Array.from(new Set(repoNames.filter(Boolean)));
const entries = await Promise.all(uniqueRepoNames.map(async (repoName) => [repoName, await this.collectRepoDocuments(repoName)] as const));
const entries = await Promise.all(
uniqueRepoNames.map(
async (repoName) =>
[repoName, await this.collectRepoDocuments(repoName)] as const,
),
);
return new Map(entries);
}
private async collectRepoDocuments(repoName: string) {
const [sprintPaths, hotfixPathGroups, qaPathGroups] = await Promise.all([
this.gitea.getRepoTree(repoName, SPRINT_PATH),
Promise.all(HOTFIX_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(QA_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(
HOTFIX_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
Promise.all(
QA_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
]);
const sprintFiles = sprintPaths.filter((path) => /SPRINT-\d+\.md$/i.test(path));
const hotfixFiles = Array.from(new Set(hotfixPathGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path))));
const qaFiles = Array.from(new Set(qaPathGroups.flat().filter((path) => /(?:SPRINT|HOTFIX)-\d+.*(?:review|qa).*\.md$/i.test(path))));
const sprintFiles = sprintPaths.filter((path) =>
/SPRINT-\d+\.md$/i.test(path),
);
const hotfixFiles = Array.from(
new Set(
hotfixPathGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path)),
),
);
const qaFiles = Array.from(
new Set(
qaPathGroups
.flat()
.filter((path) =>
/(?:SPRINT|HOTFIX)-\d+.*(?:review|qa).*\.md$/i.test(path),
),
),
);
const [sprints, hotfixes, qas] = await Promise.all([
Promise.all(sprintFiles.map((path) => this.readRepoDocument(repoName, path, 'sprint'))),
Promise.all(hotfixFiles.map((path) => this.readRepoDocument(repoName, path, 'hotfix'))),
Promise.all(qaFiles.map((path) => this.readRepoDocument(repoName, path, 'qa'))),
Promise.all(
sprintFiles.map((path) =>
this.readRepoDocument(repoName, path, 'sprint'),
),
),
Promise.all(
hotfixFiles.map((path) =>
this.readRepoDocument(repoName, path, 'hotfix'),
),
),
Promise.all(
qaFiles.map((path) => this.readRepoDocument(repoName, path, 'qa')),
),
]);
return {
sprints: sprints.filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order),
hotfixes: hotfixes.filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order),
sprints: sprints
.filter(isRepoDocumentMeta)
.sort((a, b) => a.order - b.order),
hotfixes: hotfixes
.filter(isRepoDocumentMeta)
.sort((a, b) => a.order - b.order),
qas: qas.filter(isRepoDocumentMeta).sort((a, b) => a.order - b.order),
};
}
private async readRepoDocument(repoName: string, path: string, kind: 'sprint' | 'hotfix' | 'qa'): Promise<RepoDocumentMeta | null> {
private async readRepoDocument(
repoName: string,
path: string,
kind: 'sprint' | 'hotfix' | 'qa',
): Promise<RepoDocumentMeta | null> {
const content = await this.gitea.getRawFile(repoName, path);
if (!content) return null;

View File

@@ -6,6 +6,15 @@ import { GiteaService } from '../gitea/gitea.service';
describe('SprintSyncService', () => {
let service: SprintSyncService;
type TaskWriteArgs = {
data: {
taskId?: string;
assignee: string;
status: string;
};
where?: { id: number };
};
const mockPrisma = {
project: { findUnique: jest.fn(), findMany: jest.fn() },
sprint: { findFirst: jest.fn(), create: jest.fn(), update: jest.fn() },
@@ -29,8 +38,13 @@ describe('SprintSyncService', () => {
service = module.get<SprintSyncService>(SprintSyncService);
jest.clearAllMocks();
mockPrisma.project.findUnique.mockResolvedValue({ id: 1, repoUrl: 'https://gitea.example.com/hanarang/project-alpha' });
mockPrisma.project.findMany.mockResolvedValue([{ id: 1, repoUrl: 'https://gitea.example.com/hanarang/project-alpha' }]);
mockPrisma.project.findUnique.mockResolvedValue({
id: 1,
repoUrl: 'https://gitea.example.com/hanarang/project-alpha',
});
mockPrisma.project.findMany.mockResolvedValue([
{ id: 1, repoUrl: 'https://gitea.example.com/hanarang/project-alpha' },
]);
mockPrisma.sprint.findFirst.mockResolvedValue(null);
mockPrisma.sprint.create.mockResolvedValue({ id: 101, status: 'pending' });
mockPrisma.sprint.update.mockResolvedValue({ id: 101, status: 'pending' });
@@ -38,65 +52,107 @@ describe('SprintSyncService', () => {
mockPrisma.task.create.mockResolvedValue({});
mockPrisma.task.update.mockResolvedValue({});
mockGitea.getRepoTree.mockImplementation(async (_repoName: string, path: string) => {
if (path === '.plans/sprints/') return ['.plans/sprints/SPRINT-005.md', '.plans/sprints/HOTFIX-001.md'];
if (path === '.plans/qa/') return ['.plans/qa/SPRINT-005-review-darang.md'];
if (path === '.qa/') return [];
if (path === '.plans/hotfix/') return ['.plans/hotfix/HOTFIX-001.md'];
return [];
});
mockGitea.getRepoTree.mockImplementation(
(_repoName: string, path: string) => {
if (path === '.plans/sprints/') {
return [
'.plans/sprints/SPRINT-005.md',
'.plans/sprints/HOTFIX-001.md',
];
}
if (path === '.plans/qa/') {
return ['.plans/qa/SPRINT-005-review-darang.md'];
}
if (path === '.qa/') return [];
if (path === '.plans/hotfix/') return ['.plans/hotfix/HOTFIX-001.md'];
return [];
},
);
});
it('담당 라인을 읽어 assignee를 저장한다', async () => {
mockGitea.getRawFile.mockImplementation(async (_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 이랑이\n- **설명:** deploy\n\n### TASK-020: QA 자동화\n- **담당:** darang\n- **설명:** qa\n`;
}
if (path.includes('review')) return 'passed: true';
return '# HOTFIX-001: sample';
});
mockGitea.getRawFile.mockImplementation(
(_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 이랑이\n- **설명:** deploy\n\n### TASK-020: QA 자동화\n- **담당:** darang\n- **설명:** qa\n`;
}
if (path.includes('review')) return 'passed: true';
return '# HOTFIX-001: sample';
},
);
await service.syncProjectSprints(1);
expect(mockPrisma.task.create).toHaveBeenNthCalledWith(1, expect.objectContaining({
data: expect.objectContaining({ taskId: 'TASK-019', assignee: 'erang', status: 'done' }),
}));
expect(mockPrisma.task.create).toHaveBeenNthCalledWith(2, expect.objectContaining({
data: expect.objectContaining({ taskId: 'TASK-020', assignee: 'darang', status: 'done' }),
}));
const createCalls = mockPrisma.task.create.mock.calls as Array<
[TaskWriteArgs]
>;
expect(createCalls[0]?.[0]).toMatchObject({
data: {
taskId: 'TASK-019',
assignee: 'erang',
status: 'done',
},
});
expect(createCalls[1]?.[0]).toMatchObject({
data: {
taskId: 'TASK-020',
assignee: 'darang',
status: 'done',
},
});
});
it('기존 task도 assignee를 갱신한다', async () => {
mockPrisma.task.findFirst.mockResolvedValue({ id: 500, assignee: 'narang', status: 'pending' });
mockGitea.getRawFile.mockImplementation(async (_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 하랑이\n`;
}
if (path.includes('review')) return 'passed: false';
return '# HOTFIX-001: sample';
mockPrisma.task.findFirst.mockResolvedValue({
id: 500,
assignee: 'narang',
status: 'pending',
});
mockGitea.getRawFile.mockImplementation(
(_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- **담당:** 하랑이\n`;
}
if (path.includes('review')) return 'passed: false';
return '# HOTFIX-001: sample';
},
);
await service.syncProjectSprints(1);
expect(mockPrisma.task.update).toHaveBeenCalledWith(expect.objectContaining({
const updateCalls = mockPrisma.task.update.mock.calls as Array<
[TaskWriteArgs]
>;
expect(updateCalls[0]?.[0]).toMatchObject({
where: { id: 500 },
data: expect.objectContaining({ assignee: 'harang' }),
}));
data: { assignee: 'harang' },
});
});
it('담당 라인이 없으면 narang fallback', async () => {
mockGitea.getRawFile.mockImplementation(async (_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- 설명만 있음\n`;
}
if (path.includes('review')) return 'FAILED';
return '# HOTFIX-001: sample';
});
mockGitea.getRawFile.mockImplementation(
(_repoName: string, path: string) => {
if (path.includes('SPRINT-005.md')) {
return `# SPRINT-005: Infra\n\n## 목표\n테스트\n\n## 태스크\n\n### TASK-019: 인프라 배포\n- 설명만 있음\n`;
}
if (path.includes('review')) return 'FAILED';
return '# HOTFIX-001: sample';
},
);
await service.syncProjectSprints(1);
expect(mockPrisma.task.create).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ assignee: 'narang', status: 'pending' }),
}));
const createCalls = mockPrisma.task.create.mock.calls as Array<
[TaskWriteArgs]
>;
expect(createCalls[0]?.[0]).toMatchObject({
data: {
assignee: 'narang',
status: 'pending',
},
});
});
});

View File

@@ -13,46 +13,64 @@ const QA_PATH_CANDIDATES = ['.plans/qa/', '.qa/'];
const HOTFIX_PATH_CANDIDATES = ['.plans/hotfix/', '.plans/sprints/'];
const SISTER_NAME_MAP: Record<string, string> = {
harang: 'harang',
'하랑': 'harang',
'하랑이': 'harang',
: 'harang',
: 'harang',
narang: 'narang',
'나랑': 'narang',
'나랑이': 'narang',
: 'narang',
: 'narang',
darang: 'darang',
'다랑': 'darang',
'다랑이': 'darang',
: 'darang',
: 'darang',
erang: 'erang',
'이랑': 'erang',
'이랑이': 'erang',
: 'erang',
: 'erang',
};
function parseSprintName(content: string, filename: string, number: number): string {
const headingMatch = content.match(/^#\s+(?:SPRINT-\d+|Sprint\s+\d+)[:\s—\-]+(.+)/m);
function parseSprintName(
content: string,
filename: string,
number: number,
): string {
const headingMatch = content.match(
/^#\s+(?:SPRINT-\d+|Sprint\s+\d+)[:\s—-]+(.+)/m,
);
if (headingMatch) return headingMatch[1].trim();
return filename.replace('.md', '') || `SPRINT-${String(number).padStart(3, '0')}`;
return (
filename.replace('.md', '') || `SPRINT-${String(number).padStart(3, '0')}`
);
}
function parseTaskAssignee(taskLines: string[]): string {
for (const rawLine of taskLines) {
const line = rawLine.trim();
const match = line.match(/^-\s*(?:\*\*)?(?:담당|assignee)\s*:(?:\*\*)?\s*(.+)$/i);
const match = line.match(
/^-\s*(?:\*\*)?(?:담당|assignee)\s*:(?:\*\*)?\s*(.+)$/i,
);
if (!match) continue;
const assignee = match[1]
.trim()
.replace(/[()\[\],]/g, ' ')
.replace(/[()[\],]/g, ' ')
.split(/\s+/)
.find((token) => SISTER_NAME_MAP[token.toLowerCase()] ?? SISTER_NAME_MAP[token]);
.find(
(token) =>
SISTER_NAME_MAP[token.toLowerCase()] ?? SISTER_NAME_MAP[token],
);
if (assignee) {
return SISTER_NAME_MAP[assignee.toLowerCase()] ?? SISTER_NAME_MAP[assignee];
return (
SISTER_NAME_MAP[assignee.toLowerCase()] ?? SISTER_NAME_MAP[assignee]
);
}
}
return 'narang';
}
function parseTasks(content: string, sprintStatus: 'pending' | 'done'): ParsedTask[] {
function parseTasks(
content: string,
sprintStatus: 'pending' | 'done',
): ParsedTask[] {
const lines = content.split(/\r?\n/);
const tasks: ParsedTask[] = [];
const seen = new Set<string>();
@@ -66,7 +84,9 @@ function parseTasks(content: string, sprintStatus: 'pending' | 'done'): ParsedTa
if (match) status = sprintStatus;
if (!match) {
match = line.match(/^-\s*\[([ xX])\]\s*(TASK-\d+[A-Z]?)\s*[:\-]?\s*(.+)$/i);
match = line.match(
/^-\s*\[([ xX])\]\s*(TASK-\d+[A-Z]?)\s*[:-]?\s*(.+)$/i,
);
if (match) status = /x/i.test(match[1]) ? 'done' : 'pending';
}
@@ -89,7 +109,11 @@ function parseTasks(content: string, sprintStatus: 'pending' | 'done'): ParsedTa
const taskBlock: string[] = [];
for (let lookahead = index + 1; lookahead < lines.length; lookahead += 1) {
const nextLine = lines[lookahead].trim();
if (/^#{2,6}\s+TASK-\d+[A-Z]?\s*:/i.test(nextLine) || /^-\s*\[?[ xX]?\]?\s*TASK-\d+[A-Z]?\s*[:\-]?/i.test(nextLine) || /^TASK-\d+[A-Z]?\s*:/i.test(nextLine)) {
if (
/^#{2,6}\s+TASK-\d+[A-Z]?\s*:/i.test(nextLine) ||
/^-\s*\[?[ xX]?\]?\s*TASK-\d+[A-Z]?\s*[:-]?/i.test(nextLine) ||
/^TASK-\d+[A-Z]?\s*:/i.test(nextLine)
) {
break;
}
if (/^##\s+/.test(nextLine) && !/^##\s+목표/.test(nextLine)) {
@@ -126,8 +150,12 @@ export class SprintSyncService {
private readonly gitea: GiteaService,
) {}
async syncProjectSprints(projectId: number): Promise<{ synced: number; created: number; updated: number }> {
const project = await this.prisma.project.findUnique({ where: { id: projectId } });
async syncProjectSprints(
projectId: number,
): Promise<{ synced: number; created: number; updated: number }> {
const project = await this.prisma.project.findUnique({
where: { id: projectId },
});
if (!project) return { synced: 0, created: 0, updated: 0 };
const repoName = project.repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
@@ -135,11 +163,14 @@ export class SprintSyncService {
}
async syncAllProjectSprints(): Promise<{ projects: number; synced: number }> {
const projects = await this.prisma.project.findMany({ select: { id: true, repoUrl: true } });
const projects = await this.prisma.project.findMany({
select: { id: true, repoUrl: true },
});
let totalSynced = 0;
for (const project of projects) {
const repoName = project.repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
const repoName =
project.repoUrl.replace(/\/+$/, '').split('/').pop() ?? '';
const result = await this.syncRepo(project.id, repoName);
totalSynced += result.synced;
}
@@ -147,16 +178,39 @@ export class SprintSyncService {
return { projects: projects.length, synced: totalSynced };
}
private async syncRepo(projectId: number, repoName: string): Promise<{ synced: number; created: number; updated: number }> {
private async syncRepo(
projectId: number,
repoName: string,
): Promise<{ synced: number; created: number; updated: number }> {
const [sprintFilePaths, qaGroups, hotfixGroups] = await Promise.all([
this.gitea.getRepoTree(repoName, '.plans/sprints/'),
Promise.all(QA_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(HOTFIX_PATH_CANDIDATES.map((path) => this.gitea.getRepoTree(repoName, path))),
Promise.all(
QA_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
Promise.all(
HOTFIX_PATH_CANDIDATES.map((path) =>
this.gitea.getRepoTree(repoName, path),
),
),
]);
const sprintFiles = sprintFilePaths.filter((path) => /SPRINT-\d+\.md$/i.test(path));
const qaFiles = Array.from(new Set(qaGroups.flat().filter((path) => /SPRINT-\d+.*(?:review|qa).*\.md$/i.test(path))));
const hotfixFiles = Array.from(new Set(hotfixGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path))));
const sprintFiles = sprintFilePaths.filter((path) =>
/SPRINT-\d+\.md$/i.test(path),
);
const qaFiles = Array.from(
new Set(
qaGroups
.flat()
.filter((path) => /SPRINT-\d+.*(?:review|qa).*\.md$/i.test(path)),
),
);
const hotfixFiles = Array.from(
new Set(
hotfixGroups.flat().filter((path) => /HOTFIX-\d+\.md$/i.test(path)),
),
);
if (!sprintFiles.length) {
this.logger.warn(`No sprint files found in ${repoName}/.plans/sprints/`);
@@ -186,14 +240,20 @@ export class SprintSyncService {
const number = parseInt(numberMatch[1], 10);
const name = parseSprintName(content, filename, number);
const status: 'pending' | 'done' = passedMap.get(number) ? 'done' : 'pending';
const status: 'pending' | 'done' = passedMap.get(number)
? 'done'
: 'pending';
const parsedTasks = parseTasks(content, status);
const existingSprint = await this.prisma.sprint.findFirst({ where: { projectId, number } });
const existingSprint = await this.prisma.sprint.findFirst({
where: { projectId, number },
});
let sprintId = existingSprint?.id ?? 0;
if (!existingSprint) {
const createdSprint = await this.prisma.sprint.create({ data: { projectId, number, name, status } });
const createdSprint = await this.prisma.sprint.create({
data: { projectId, number, name, status },
});
sprintId = createdSprint.id;
created += 1;
} else {
@@ -209,7 +269,9 @@ export class SprintSyncService {
}
for (const task of parsedTasks) {
const existingTask = await this.prisma.task.findFirst({ where: { sprintId, taskId: task.taskId } });
const existingTask = await this.prisma.task.findFirst({
where: { sprintId, taskId: task.taskId },
});
if (!existingTask) {
await this.prisma.task.create({
data: {
@@ -233,7 +295,9 @@ export class SprintSyncService {
}
}
this.logger.log(`${repoName}: ${sprintFiles.length} sprints, ${hotfixFiles.length} hotfix docs, ${passedMap.size} QA passed → ${created} created, ${updated} updated`);
this.logger.log(
`${repoName}: ${sprintFiles.length} sprints, ${hotfixFiles.length} hotfix docs, ${passedMap.size} QA passed → ${created} created, ${updated} updated`,
);
return { synced: sprintFiles.length, created, updated };
}
}

View File

@@ -24,7 +24,9 @@ export class SettingsService {
) {}
async getAll() {
const rows = await this.prisma.systemSettings.findMany({ orderBy: { key: 'asc' } });
const rows = await this.prisma.systemSettings.findMany({
orderBy: { key: 'asc' },
});
const merged = { ...DEFAULT_SETTINGS };
for (const row of rows) merged[row.key] = row.value;
return merged;
@@ -33,7 +35,9 @@ export class SettingsService {
async saveAll(payload: Record<string, string>) {
// DEFAULT_SETTINGS에 있는 키만 허용
const allowed = Object.keys(DEFAULT_SETTINGS);
const entries = Object.entries(payload).filter(([key]) => allowed.includes(key));
const entries = Object.entries(payload).filter(([key]) =>
allowed.includes(key),
);
await this.prisma.$transaction(
entries.map(([key, value]) =>
this.prisma.systemSettings.upsert({

View File

@@ -9,9 +9,16 @@ describe('SisterDetailService', () => {
let service: SisterDetailService;
const mockSister = {
id: 2, name: 'narang', ip: '10.10.10.216', user: 'narang',
lxcId: 105, status: 'online', lastSeen: new Date(),
sshKeyPath: null, createdAt: new Date(), updatedAt: new Date(),
id: 2,
name: 'narang',
ip: '10.10.10.216',
user: 'narang',
lxcId: 105,
status: 'online',
lastSeen: new Date(),
sshKeyPath: null,
createdAt: new Date(),
updatedAt: new Date(),
};
const mockPrisma = {
@@ -35,7 +42,9 @@ describe('SisterDetailService', () => {
{ provide: PrismaService, useValue: mockPrisma },
{
provide: ConfigService,
useValue: { get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa') },
useValue: {
get: jest.fn().mockReturnValue('/home/narang/.ssh/id_rsa'),
},
},
],
}).compile();
@@ -58,7 +67,9 @@ describe('SisterDetailService', () => {
it('getSisterConfig: sister 없으면 NotFoundException', async () => {
mockPrisma.sisterConfig.findUnique.mockResolvedValue(null);
await expect(service.getSisterConfig('narang')).rejects.toThrow(NotFoundException);
await expect(service.getSisterConfig('narang')).rejects.toThrow(
NotFoundException,
);
});
it('getSisterSessions: SSH 실패 시 빈 배열', async () => {

View File

@@ -3,8 +3,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { SshService } from './ssh.service';
import { ConfigService } from '@nestjs/config';
const SISTER_NAMES = ['harang', 'narang', 'darang', 'erang'] as const;
type SisterName = (typeof SISTER_NAMES)[number];
type SisterName = 'harang' | 'narang' | 'darang' | 'erang';
const SISTER_ROLES: Record<SisterName, string> = {
harang: 'Orchestrator',
@@ -14,7 +13,8 @@ const SISTER_ROLES: Record<SisterName, string> = {
};
const SISTER_DESCRIPTIONS: Record<SisterName, string> = {
harang: '기획과 오케스트레이션. 스프린트를 설계하고 자매들에게 작업을 배분한다.',
harang:
'기획과 오케스트레이션. 스프린트를 설계하고 자매들에게 작업을 배분한다.',
narang: '코드 생성과 개발. 스프린트를 구현하고 PR을 만든다.',
darang: '품질 검증. 코드 리뷰와 보안 감사를 수행한다.',
erang: '인프라와 배포. 서버 관리, merge, 프로덕션 배포를 담당한다.',
@@ -70,15 +70,19 @@ export class SisterDetailService {
'SESSION_DIR=~/.hermes/sessions; [ -d "$SESSION_DIR" ] || SESSION_DIR=~/.openclaw/sessions; ls -lt "$SESSION_DIR"/ 2>/dev/null | head -20 || echo ""',
);
const lines = result.stdout.split('\n').filter((l) => l && !l.startsWith('total'));
return lines.map((line) => {
const parts = line.trim().split(/\s+/);
return {
name: parts[parts.length - 1] ?? '',
modified: parts.slice(5, 8).join(' '),
size: parts[4] ?? '0',
};
}).filter((s) => s.name && s.name !== '');
const lines = result.stdout
.split('\n')
.filter((l) => l && !l.startsWith('total'));
return lines
.map((line) => {
const parts = line.trim().split(/\s+/);
return {
name: parts[parts.length - 1] ?? '',
modified: parts.slice(5, 8).join(' '),
size: parts[4] ?? '0',
};
})
.filter((s) => s.name && s.name !== '');
} catch {
return [];
}
@@ -96,8 +100,13 @@ export class SisterDetailService {
'AGENT_DIR=~/.hermes/workspace/agents; [ -d "$AGENT_DIR" ] || AGENT_DIR=~/.openclaw/workspace/agents; ls "$AGENT_DIR"/ 2>/dev/null || echo ""',
);
const agents = result.stdout.split('\n').filter((l) => l.trim().endsWith('.md'));
return agents.map((a) => ({ name: a.trim().replace('.md', ''), file: a.trim() }));
const agents = result.stdout
.split('\n')
.filter((l) => l.trim().endsWith('.md'));
return agents.map((a) => ({
name: a.trim().replace('.md', ''),
file: a.trim(),
}));
} catch {
return [];
}
@@ -140,7 +149,9 @@ export class SisterDetailService {
}
private async getSisterRecord(name: SisterName) {
const sister = await this.prisma.sisterConfig.findUnique({ where: { name } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name },
});
if (!sister) throw new NotFoundException(`Sister ${name} not found`);
return sister;
}

View File

@@ -21,7 +21,7 @@ export class SistersController {
@Get(':name/system')
async getSystemInfo(@Param('name', SisterNamePipe) name: SisterName) {
return this.sistersService.getSystemInfo(name as SisterName);
return this.sistersService.getSystemInfo(name);
}
@Get(':name/avatar')
@@ -29,7 +29,7 @@ export class SistersController {
@Param('name', SisterNamePipe) name: SisterName,
@Res() res: Response,
) {
const sister = await this.sistersService.findByName(name as SisterName);
const sister = await this.sistersService.findByName(name);
if (!sister) {
return res.status(404).json({ message: 'Sister not found' });
}
@@ -42,21 +42,21 @@ export class SistersController {
@Get(':name/config')
async getSisterConfig(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterConfig(name as SisterName);
return this.sisterDetail.getSisterConfig(name);
}
@Get(':name/sessions')
async getSisterSessions(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterSessions(name as SisterName);
return this.sisterDetail.getSisterSessions(name);
}
@Get(':name/subagents')
async getSisterSubagents(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterSubagents(name as SisterName);
return this.sisterDetail.getSisterSubagents(name);
}
@Get(':name/activity')
async getSisterActivity(@Param('name', SisterNamePipe) name: SisterName) {
return this.sisterDetail.getSisterActivityLog(name as SisterName);
return this.sisterDetail.getSisterActivityLog(name);
}
}

View File

@@ -7,13 +7,56 @@ import { ConfigService } from '@nestjs/config';
describe('SistersService', () => {
let service: SistersService;
let sshService: jest.Mocked<SshService>;
let prismaService: jest.Mocked<PrismaService>;
const mockSisters = [
{ id: 1, name: 'harang', ip: '10.10.10.112', user: 'harang', lxcId: 104, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{ id: 2, name: 'narang', ip: '10.10.10.216', user: 'narang', lxcId: 105, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{ id: 3, name: 'darang', ip: '10.10.10.136', user: 'darang', lxcId: 106, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{ id: 4, name: 'erang', ip: '10.10.10.163', user: 'erang', lxcId: 107, sshKeyPath: null, lastSeen: null, status: 'unknown', createdAt: new Date(), updatedAt: new Date() },
{
id: 1,
name: 'harang',
ip: '10.10.10.112',
user: 'harang',
lxcId: 104,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: 2,
name: 'narang',
ip: '10.10.10.216',
user: 'narang',
lxcId: 105,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: 3,
name: 'darang',
ip: '10.10.10.136',
user: 'darang',
lxcId: 106,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: 4,
name: 'erang',
ip: '10.10.10.163',
user: 'erang',
lxcId: 107,
sshKeyPath: null,
lastSeen: null,
status: 'unknown',
createdAt: new Date(),
updatedAt: new Date(),
},
];
beforeEach(async () => {
@@ -35,22 +78,28 @@ describe('SistersService', () => {
{ provide: PrismaService, useValue: mockPrisma },
{
provide: ConfigService,
useValue: { get: jest.fn().mockImplementation((key: string) => {
if (key === 'SSH_KEY_PATH') return '/home/narang/.ssh/id_rsa';
if (key === 'DATABASE_URL') return 'mysql://test:test@localhost:3306/test';
return undefined;
}) },
useValue: {
get: jest.fn().mockImplementation((key: string) => {
if (key === 'SSH_KEY_PATH') return '/home/narang/.ssh/id_rsa';
if (key === 'DATABASE_URL')
return 'mysql://test:test@localhost:3306/test';
return undefined;
}),
},
},
],
}).compile();
service = module.get<SistersService>(SistersService);
sshService = module.get(SshService);
prismaService = module.get(PrismaService);
});
it('SSH 성공 시 online 상태 반환', async () => {
sshService.executeCommand.mockResolvedValue({ stdout: 'active', stderr: '', code: 0 });
sshService.executeCommand.mockResolvedValue({
stdout: 'active',
stderr: '',
code: 0,
});
const result = await service.getAllSistersStatus();
@@ -58,11 +107,13 @@ describe('SistersService', () => {
expect(result[0].status).toBe('online');
expect(result[0].name).toBe('harang');
expect(result[0].role).toBe('Orchestrator');
expect((result[0] as any).ip).toBeUndefined(); // IP 노출 제거 확인
expect(result[0]).not.toHaveProperty('ip'); // IP 노출 제거 확인
});
it('SSH 실패 시 offline graceful fallback', async () => {
sshService.executeCommand.mockRejectedValue(new Error('Connection refused'));
sshService.executeCommand.mockRejectedValue(
new Error('Connection refused'),
);
const result = await service.getAllSistersStatus();
@@ -73,13 +124,13 @@ describe('SistersService', () => {
it('일부 SSH 실패 시 실패한 자매만 offline', async () => {
sshService.executeCommand
.mockResolvedValueOnce({ stdout: 'active', stderr: '', code: 0 }) // harang
.mockRejectedValueOnce(new Error('timeout')) // narang
.mockRejectedValueOnce(new Error('timeout')) // narang
.mockResolvedValueOnce({ stdout: 'inactive', stderr: '', code: 1 }) // darang
.mockRejectedValueOnce(new Error('timeout')); // erang
.mockRejectedValueOnce(new Error('timeout')); // erang
const result = await service.getAllSistersStatus();
expect(result[0].status).toBe('online'); // harang
expect(result[0].status).toBe('online'); // harang
expect(result[1].status).toBe('offline'); // narang (SSH 실패)
expect(result[2].status).toBe('offline'); // darang (inactive)
expect(result[3].status).toBe('offline'); // erang (SSH 실패)

View File

@@ -67,16 +67,54 @@ export class SistersService {
}
async getSystemInfo(name: string) {
const sister = await this.prisma.sisterConfig.findUnique({ where: { name } });
const sister = await this.prisma.sisterConfig.findUnique({
where: { name },
});
if (!sister) return null;
const sshKeyPath = this.config.get<string>('SSH_KEY_PATH');
if (!sshKeyPath) return null;
const [uptimeRes, cpuRes, memRes, diskRes] = await Promise.all([
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, 'cat /proc/uptime 2>/dev/null || echo "0 0"').catch(() => ({ stdout: '0 0', stderr: '', code: 0 })),
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, "top -bn1 | grep Cpu || echo '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id'").catch(() => ({ stdout: '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id', stderr: '', code: 0 })),
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, 'free -m | grep Mem || echo "Mem: 0 0 0 0 0 0"').catch(() => ({ stdout: 'Mem: 0 0 0 0 0 0', stderr: '', code: 0 })),
this.ssh.executeCommand(sister.ip, sister.user, sshKeyPath, "df -h / | tail -1 || echo '/dev/root 0G 0G 0G 0% /'").catch(() => ({ stdout: '/dev/root 0G 0G 0G 0% /', stderr: '', code: 0 })),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
'cat /proc/uptime 2>/dev/null || echo "0 0"',
)
.catch(() => ({ stdout: '0 0', stderr: '', code: 0 })),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
"top -bn1 | grep Cpu || echo '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id'",
)
.catch(() => ({
stdout: '%Cpu(s): 0.0 us, 0.0 sy, 100.0 id',
stderr: '',
code: 0,
})),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
'free -m | grep Mem || echo "Mem: 0 0 0 0 0 0"',
)
.catch(() => ({ stdout: 'Mem: 0 0 0 0 0 0', stderr: '', code: 0 })),
this.ssh
.executeCommand(
sister.ip,
sister.user,
sshKeyPath,
"df -h / | tail -1 || echo '/dev/root 0G 0G 0G 0% /'",
)
.catch(() => ({
stdout: '/dev/root 0G 0G 0G 0% /',
stderr: '',
code: 0,
})),
]);
return {
@@ -88,7 +126,15 @@ export class SistersService {
}
private async checkSisterStatus(
sister: { id: number; name: string; ip: string; user: string; lxcId: number; lastSeen: Date | null; status: string },
sister: {
id: number;
name: string;
ip: string;
user: string;
lxcId: number;
lastSeen: Date | null;
status: string;
},
sshKeyPath: string,
): Promise<SisterStatus> {
try {
@@ -110,11 +156,13 @@ export class SistersService {
});
if (prevStatus !== status && this.activity) {
await this.activity.log({
sisterId: sister.id,
action: 'status_changed',
detail: `[${sister.name}] status: ${prevStatus}${status}`,
}).catch(() => {});
await this.activity
.log({
sisterId: sister.id,
action: 'status_changed',
detail: `[${sister.name}] status: ${prevStatus}${status}`,
})
.catch(() => {});
}
return {

View File

@@ -1,4 +1,12 @@
import { Controller, Get, Post, Patch, Param, Body, ParseIntPipe } from '@nestjs/common';
import {
Controller,
Get,
Post,
Patch,
Param,
Body,
ParseIntPipe,
} from '@nestjs/common';
import { TasksService, CreateSprintDto, UpdateTaskDto } from './tasks.service';
@Controller('api')

View File

@@ -8,15 +8,27 @@ describe('TasksService', () => {
let service: TasksService;
const mockTask = {
id: 1, taskId: 'TASK-001', title: 'Test', assignee: 'narang',
status: 'pending', iteration: 0, sprintId: 1,
createdAt: new Date(), updatedAt: new Date(),
id: 1,
taskId: 'TASK-001',
title: 'Test',
assignee: 'narang',
status: 'pending',
iteration: 0,
sprintId: 1,
createdAt: new Date(),
updatedAt: new Date(),
};
const mockSprint = {
id: 1, projectId: 1, number: 1, name: 'Sprint 001',
status: 'in_progress', startedAt: null, completedAt: null,
createdAt: new Date(), updatedAt: new Date(),
id: 1,
projectId: 1,
number: 1,
name: 'Sprint 001',
status: 'in_progress',
startedAt: null,
completedAt: null,
createdAt: new Date(),
updatedAt: new Date(),
tasks: [mockTask],
};
@@ -57,7 +69,9 @@ describe('TasksService', () => {
it('getTaskLedger: sprint + task + progress 반환', async () => {
mockPrisma.project.findUnique.mockResolvedValue({
id: 1,
sprints: [{ ...mockSprint, tasks: [{ ...mockTask, status: 'done' }, mockTask] }],
sprints: [
{ ...mockSprint, tasks: [{ ...mockTask, status: 'done' }, mockTask] },
],
});
const result = await service.getTaskLedger(1);
@@ -67,8 +81,15 @@ describe('TasksService', () => {
});
it('updateTask: 상태 변경 시 ActivityLog 기록', async () => {
mockPrisma.task.findUnique.mockResolvedValue({ ...mockTask, status: 'in_progress' });
mockPrisma.task.update.mockResolvedValue({ ...mockTask, status: 'done', sprintId: 1 });
mockPrisma.task.findUnique.mockResolvedValue({
...mockTask,
status: 'in_progress',
});
mockPrisma.task.update.mockResolvedValue({
...mockTask,
status: 'done',
sprintId: 1,
});
await service.updateTask(1, { status: 'done' });

View File

@@ -13,7 +13,15 @@ export class CreateSprintDto {
name!: string;
}
const VALID_STATUSES = ['pending', 'in_progress', 'review', 'done', 'failed', 'blocked', 'escalated'] as const;
const VALID_STATUSES = [
'pending',
'in_progress',
'review',
'done',
'failed',
'blocked',
'escalated',
] as const;
export class UpdateTaskDto {
@IsOptional()
@@ -58,14 +66,21 @@ export class TasksService {
startedAt: sprint.startedAt,
completedAt: sprint.completedAt,
tasks: sprint.tasks,
progress: sprint.tasks.length > 0
? Math.round(sprint.tasks.filter((t) => t.status === 'done').length / sprint.tasks.length * 100)
: 0,
progress:
sprint.tasks.length > 0
? Math.round(
(sprint.tasks.filter((t) => t.status === 'done').length /
sprint.tasks.length) *
100,
)
: 0,
}));
}
async createSprint(projectId: number, dto: CreateSprintDto) {
const project = await this.prisma.project.findUnique({ where: { id: projectId } });
const project = await this.prisma.project.findUnique({
where: { id: projectId },
});
if (!project) throw new NotFoundException(`Project ${projectId} not found`);
const sprint = await this.prisma.sprint.create({
@@ -90,9 +105,10 @@ export class TasksService {
where: { id: taskId },
data: {
...dto,
iteration: dto.status && dto.status !== prevStatus && prevStatus !== 'pending'
? { increment: 1 }
: undefined,
iteration:
dto.status && dto.status !== prevStatus && prevStatus !== 'pending'
? { increment: 1 }
: undefined,
},
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,294 @@
'use client';
import React from 'react';
import styled, { keyframes } from 'styled-components';
export interface PipelineNode {
id: string;
label: string;
role: string;
state: 'idle' | 'active' | 'review' | 'blocked' | 'ready';
detail: string;
}
interface ActivePipelineProps {
activeTask: string;
focus: string;
reviewLoopCount: number;
escalationCount: number;
deployState: string;
nodes: PipelineNode[];
}
const flow = keyframes`
0% { transform: translateX(0); opacity: 0.15; }
40% { opacity: 0.8; }
100% { transform: translateX(20px); opacity: 0; }
`;
const PipelineCard = styled.section`
border: 1px solid var(--border-color);
background: var(--bg-surface);
padding: var(--space-lg);
display: flex;
flex-direction: column;
gap: var(--space-lg);
`;
const Header = styled.div`
display: flex;
justify-content: space-between;
gap: var(--space-md);
align-items: flex-start;
flex-wrap: wrap;
`;
const Eyebrow = styled.div`
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
const Title = styled.h2`
font-size: 24px;
font-weight: 600;
color: var(--text-primary);
letter-spacing: -0.02em;
margin-top: 6px;
`;
const Summary = styled.p`
font-size: 13px;
color: var(--text-secondary);
line-height: 1.6;
max-width: 780px;
`;
const HeaderStats = styled.div`
display: grid;
grid-template-columns: repeat(3, minmax(110px, 1fr));
gap: var(--space-sm);
@media (max-width: 767px) {
width: 100%;
grid-template-columns: repeat(3, minmax(0, 1fr));
}
`;
const StatBox = styled.div`
border: 1px solid var(--border-color);
padding: 10px 12px;
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
`;
const StatLabel = styled.span`
font-family: var(--font-mono);
font-size: 10px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
const StatValue = styled.span`
font-size: 15px;
color: var(--text-primary);
font-weight: 600;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
const FlowMap = styled.div`
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 14px;
align-items: stretch;
@media (max-width: 1199px) {
grid-template-columns: 1fr;
}
`;
const NodeWrap = styled.div`
display: flex;
align-items: center;
gap: 10px;
@media (max-width: 1199px) {
flex-direction: column;
align-items: stretch;
}
`;
const Connector = styled.div<{ $active?: boolean }>`
flex: 1;
min-width: 36px;
height: 1px;
background: ${({ $active }) => ($active ? 'rgba(245,245,245,0.45)' : 'var(--border-color)')};
position: relative;
overflow: hidden;
&::after {
content: '';
position: absolute;
top: -2px;
left: -18px;
width: 18px;
height: 5px;
background: ${({ $active }) => ($active ? 'rgba(245,245,245,0.85)' : 'transparent')};
animation: ${({ $active }) => ($active ? flow : 'none')} 1.6s linear infinite;
}
@media (max-width: 1199px) {
width: 1px;
height: 24px;
min-width: 1px;
margin: 0 auto;
&::after {
top: -8px;
left: -2px;
width: 5px;
height: 10px;
animation: none;
}
}
`;
const stateBorder: Record<PipelineNode['state'], string> = {
idle: 'var(--border-color)',
active: '#6fc3ff',
review: '#ff7ac6',
blocked: '#ff8d7a',
ready: '#8dffb2',
};
const stateText: Record<PipelineNode['state'], string> = {
idle: 'IDLE',
active: 'ACTIVE',
review: 'REVIEW',
blocked: 'BLOCKED',
ready: 'READY',
};
const NodeCard = styled.div<{ $state: PipelineNode['state'] }>`
border: 1px solid ${({ $state }) => stateBorder[$state]};
padding: 14px;
display: flex;
flex-direction: column;
gap: 10px;
min-height: 148px;
background: linear-gradient(180deg, rgba(255,255,255,0.015) 0%, rgba(255,255,255,0) 100%);
`;
const NodeTop = styled.div`
display: flex;
justify-content: space-between;
gap: var(--space-sm);
align-items: flex-start;
`;
const NodeLabel = styled.div`
display: flex;
flex-direction: column;
gap: 4px;
`;
const NodeName = styled.div`
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
`;
const NodeRole = styled.div`
font-size: 12px;
color: var(--text-secondary);
`;
const StateBadge = styled.span<{ $state: PipelineNode['state'] }>`
font-family: var(--font-mono);
font-size: 10px;
color: ${({ $state }) => stateBorder[$state]};
border: 1px solid ${({ $state }) => stateBorder[$state]};
padding: 4px 6px;
text-transform: uppercase;
letter-spacing: 0.08em;
white-space: nowrap;
`;
const NodeDetail = styled.div`
font-size: 13px;
line-height: 1.6;
color: var(--text-primary);
`;
const NodeHint = styled.div`
margin-top: auto;
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.08em;
`;
export default function ActivePipeline({
activeTask,
focus,
reviewLoopCount,
escalationCount,
deployState,
nodes,
}: ActivePipelineProps) {
return (
<PipelineCard>
<Header>
<div>
<Eyebrow>Master flow / active pipeline</Eyebrow>
<Title>{activeTask}</Title>
<Summary>{focus}</Summary>
</div>
<HeaderStats>
<StatBox>
<StatLabel>review loop</StatLabel>
<StatValue>{reviewLoopCount}x</StatValue>
</StatBox>
<StatBox>
<StatLabel>escalations</StatLabel>
<StatValue>{escalationCount}</StatValue>
</StatBox>
<StatBox>
<StatLabel>deploy state</StatLabel>
<StatValue>{deployState}</StatValue>
</StatBox>
</HeaderStats>
</Header>
<FlowMap>
{nodes.map((node, index) => {
const connectorActive = node.state === 'active' || node.state === 'review' || node.state === 'ready';
return (
<NodeWrap key={node.id}>
<NodeCard $state={node.state}>
<NodeTop>
<NodeLabel>
<NodeName>{node.label}</NodeName>
<NodeRole>{node.role}</NodeRole>
</NodeLabel>
<StateBadge $state={node.state}>{stateText[node.state]}</StateBadge>
</NodeTop>
<NodeDetail>{node.detail}</NodeDetail>
<NodeHint>stage {String(index + 1).padStart(2, '0')}</NodeHint>
</NodeCard>
{index < nodes.length - 1 && <Connector $active={connectorActive} />}
</NodeWrap>
);
})}
</FlowMap>
</PipelineCard>
);
}

8
qa/test-plan.md Normal file
View File

@@ -0,0 +1,8 @@
# QA Test Plan
실제 기준 문서는 `.plans/qa/test-plan.md`야.
이 파일은 QA 도구/사람이 루트 `qa/test-plan.md`를 찾을 때 바로 보이게 둔 미러 엔트리야.
- canonical: `../.plans/qa/test-plan.md`
- purpose: QA lookup compatibility