☰ 분류

저장소 전면 감사·수정 프롬프트

전체 저장소를 대상으로 하면 구조 파악, 버그·보안 취약점·품질 문제 탐지, 우선순위화, 수정과 문서화 절차를 수행하게 합니다.

분류개발 › 코딩
태그분석검토개발자코드
프롬프트 (영어 본문 · 답은 한국어로 옵니다)
## Objective
Conduct a thorough analysis of the entire repository to identify, prioritize, fix, and document ALL verifiable bugs, security vulnerabilities, and critical issues across any programming language, framework, or technology stack.

## Phase 1: Initial Repository Assessment

### 1.1 Architecture Mapping
- Map complete project structure (src/, lib/, tests/, docs/, config/, scripts/, etc.)
- Identify technology stack and dependencies (package.json, requirements.txt, go.mod, pom.xml, Gemfile, etc.)
- Document main entry points, critical paths, and system boundaries
- Analyze build configurations and CI/CD pipelines
- Review existing documentation (README, API docs, architecture diagrams)

### 1.2 Development Environment Analysis
- Identify testing frameworks (Jest, pytest, PHPUnit, Go test, JUnit, RSpec, etc.)
- Review linting/formatting configurations (ESLint, Prettier, Black, RuboCop, etc.)
- Check for existing issue tracking (GitHub Issues, TODO/FIXME/HACK/XXX comments)
- Analyze commit history for recent problematic areas
- Review existing test coverage reports if available

## Phase 2: Systematic Bug Discovery

### 2.1 Bug Categories to Identify
**Critical Bugs:**
- Security vulnerabilities (SQL injection, XSS, CSRF, auth bypass, etc.)
- Data corruption or loss risks
- System crashes or deadlocks
- Memory leaks or resource exhaustion

**Functional Bugs:**
- Logic errors (incorrect conditions, wrong calculations, off-by-one errors)
- State management issues (race conditions, inconsistent state, improper mutations)
- Incorrect API contracts or data mappings
- Missing or incorrect validations
- Broken business rules or workflows

**Integration Bugs:**
- Incorrect external API usage
- Database query errors or inefficiencies
- Message queue handling issues
- File system operation problems
- Network communication errors

**Edge Cases & Error Handling:**
- Null/undefined/nil handling
- Empty collections or zero-value edge cases
- Boundary conditions and limit violations
- Missing error propagation or swallowing exceptions
- Timeout and retry logic issues

**Code Quality Issues:**
- Type mismatches or unsafe casts
- Deprecated API usage
- Dead code or unreachable branches
- Circular dependencies
- Performance bottlenecks (N+1 queries, inefficient algorithms)

### 2.2 Discovery Methods
- Static code analysis using language-specific tools
- Pattern matching for common anti-patterns
- Dependency vulnerability scanning
- Code path analysis for unreachable or untested code
- Configuration validation
- Cross-reference documentation with implementation

## Phase 3: Bug Documentation & Prioritization

### 3.1 Bug Report Template
For each identified bug, document:
```
BUG-ID: [Sequential identifier]
Severity: [CRITICAL | HIGH | MEDIUM | LOW]
Category: [Security | Functional | Performance | Integration | Code Quality]
File(s): [Complete file path(s) and line numbers]
Component: [Module/Service/Feature affected]

Description:
- Current behavior (what's wrong)
- Expected behavior (what should happen)
- Root cause analysis

Impact Assessment:
- User impact (UX degradation, data loss, security exposure)
- System impact (performance, stability, scalability)
- Business impact (compliance, revenue, reputation)

Reproduction Steps:
1. [Step-by-step instructions]
2. [Include test data/conditions if needed]
3. [Expected vs actual results]

Verification Method:
- [Code snippet or test that demonstrates the bug]
- [Metrics or logs showing the issue]

Dependencies:
- Related bugs: [List of related BUG-IDs]
- Blocking issues: [What needs to be fixed first]
```

### 3.2 Prioritization Matrix
Rank bugs using:
- **Severity**: Critical > High > Medium > Low
- **User Impact**: Number of affected users/features
- **Fix Complexity**: Simple < Medium < Complex
- **Risk of Regression**: Low < Medium < High

## Phase 4: Fix Implementation

### 4.1 Fix Strategy
**For each bug:**
1. Create isolated fix branch (if using version control)
2. Write failing test FIRST (TDD approach)
3. Implement minimal, focused fix
4. Verify test passes
5. Run regression tests
6. Update documentation if needed

### 4.2 Fix Guidelines
- **Minimal Change Principle**: Make the smallest change that correctly fixes the issue
- **No Scope Creep**: Avoid unrelated refactoring or improvements
- **Preserve Backwards Compatibility**: Unless the bug itself is a breaking API
- **Follow Project Standards**: Use existing code style and patterns
- **Add Defensive Programming**: Prevent similar bugs in the future

### 4.3 Code Review Checklist
- [ ] Fix addresses the root cause, not just symptoms
- [ ] All edge cases are handled
- [ ] Error messages are clear and actionable
- [ ] Performance impact is acceptable
- [ ] Security implications considered
- [ ] No new warnings or linting errors introduced

## Phase 5: Testing & Validation

### 5.1 Test Requirements
**For EVERY fixed bug, provide:**
1. **Unit Test**: Isolated test for the specific fix
2. **Integration Test**: If bug involves multiple components
3. **Regression Test**: Ensure fix doesn't break existing functionality
4. **Edge Case Tests**: Cover related boundary conditions

### 5.2 Test Structure
```[language-specific]
describe('BUG-[ID]: [Bug description]', () => {
  test('should fail with original bug', () => {
    // This test would fail before the fix
    // Demonstrates the bug
  });
  
  test('should pass after fix', () => {
    // This test passes after the fix
    // Verifies correct behavior
  });
  
  test('should handle edge cases', () => {
    // Additional edge case coverage
  });
});
```

### 5.3 Validation Steps
1. Run full test suite: `[npm test | pytest | go test ./... | mvn test | etc.]`
2. Check code coverage changes
3. Run static analysis tools
4. Verify performance benchmarks (if applicable)
5. Test in different environments (if possible)

## Phase 6: Documentation & Reporting

### 6.1 Fix Documentation
For each fixed bug:
- Update inline code comments explaining the fix
- Add/update API documentation if behavior changed
- Create/update troubleshooting guides
- Document any workarounds for unfixed issues

### 6.2 Executive Summary Report
```markdown
# Bug Fix Report - [Repository Name]
Date: [YYYY-MM-DD]
Analyzer: [Tool/Person Name]

## Overview
- Total Bugs Found: [X]
- Total Bugs Fixed: [Y]
- Unfixed/Deferred: [Z]
- Test Coverage Change: [Before]% → [After]%

## Critical Findings
[List top 3-5 most critical bugs found and fixed]

## Fix Summary by Category
- Security: [X bugs fixed]
- Functional: [Y bugs fixed]
- Performance: [Z bugs fixed]
- Integration: [W bugs fixed]
- Code Quality: [V bugs fixed]

## Detailed Fix List
[Organized table with columns: BUG-ID | File | Description | Status | Test Added]

## Risk Assessment
- Remaining High-Priority Issues: [List]
- Recommended Next Steps: [Actions]
- Technical Debt Identified: [Summary]

## Testing Results
- Test Command: [exact command used]
- Tests Passed: [X/Y]
- New Tests Added: [Count]
- Coverage Impact: [Details]
```

### 6.3 Deliverables Checklist
- [ ] All bugs documented in standard format
- [ ] Fixes implemented and tested
- [ ] Test suite updated and passing
- [ ] Documentation updated
- [ ] Code review completed
- [ ] Performance impact assessed
- [ ] Security review conducted (for security-related fixes)
- [ ] Deployment notes prepared

## Phase 7: Continuous Improvement

### 7.1 Pattern Analysis
- Identify common bug patterns
- Suggest preventive measures
- Recommend tooling improvements
- Propose architectural changes to prevent similar issues

### 7.2 Monitoring Recommendations
- Suggest metrics to track
- Recommend alerting rules
- Propose logging improvements
- Identify areas needing better test coverage

## Constraints & Best Practices

1. **Never compromise security** for simplicity
2. **Maintain audit trail** of all changes
3. **Follow semantic versioning** if fixes change API
4. **Respect rate limits** when testing external services
5. **Use feature flags** for high-risk fixes (if applicable)
6. **Consider rollback strategy** for each fix
7. **Document assumptions** made during analysis

## Output Format
Provide results in both:
- Markdown for human readability
- JSON/YAML for automated processing
- CSV for bug tracking systems import

## Special Considerations
- For monorepos: Analyze each package separately
- For microservices: Consider inter-service dependencies
- For legacy code: Balance fix risk vs benefit
- For third-party dependencies: Report upstream if needed

어떤 프롬프트인가

여러 언어와 스택을 가정한 대규모 저장소 감사 프롬프트다. 보이는 본문은 단계별 점검 범위가 매우 넓으며, 후반부는 잘려 있다.

모델 비교

ChatGPT는 한계를 밝혔지만 근거 없는 전제가 있고, Gemini는 더 완결된 형식이나 날조와 과장이 심하다. [C]는 누락됐다.

ChatGPT종합 1위
24/ 50

+ 검증 여부를 구분하고 오류 원리를 명료하게 설명했다.

- 입력에 없는 코드와 프로젝트를 전제로 삼고 실제 수정도 못 했다.

Gemini
20/ 50

+ 단계별 보고서와 테스트 예시를 체계적으로 구성했다.

- 스택·경로·성과를 날조하고 미실행 수정을 완료로 보고했다.

기준ChatGPTGemini앞선 모델
지시 준수45Gemini +25%
정확성42ChatGPT +100%
구체성33동점
구성·가독성87ChatGPT +14%
분량 적정성53ChatGPT +67%

gpt-5.6-sol가 모델 이름을 가린 채 1~10점으로 채점했습니다 (2026-09-25). 측정값이 아니라 AI 심사 결과입니다.

답 전문 보기

같은 입력을 세 모델에 넣어 받은 답을 그대로 옮겼습니다. 각 CLI(에이전트 하네스)에서 실행했습니다. ChatGPT·Claude 앱이나 웹에서는 답이 다를 수 있습니다.

넣은 입력
[붙여 넣은 자료]
대상 저장소는 저희 사내 예약 서비스 '어울림예약'의 프론트엔드(React 18 + TypeScript, Vite)입니다. 최근 사용자들이 예약 취소 버튼을 연타하면 취소 요청이 중복으로 나간다는 컴플레인이 있었습니다. 아래는 관련 컴포넌트입니다.

function CancelButton({ reservationId }: { reservationId: string }) {
  const [loading, setLoading] = useState(false);

  const handleCancel = async () => {
    setLoading(true);
    await fetch(`/api/reservations/${reservationId}/cancel`, { method: 'POST' });
    setLoading(false);
  };

  return <button onClick={handleCancel}>예약 취소</button>;
}

버튼에 disabled 처리가 없고, 취소 실패 시 에러 핸들링도 없는 상태입니다. package.json 의존성은 react-query 5.x, axios 1.6을 쓰고 있습니다.
gpt-5.6-luna (codex CLI · 에이전트 하네스) · 실행일 2026-09-24

어울림예약 프론트엔드 버그 감사 보고서

분석 기준일: 2026-09-24
분석 대상: 제공된 CancelButton 코드 및 설명
상태: 코드 수정 불가 — 현재 작업 환경이 읽기 전용이며 저장소 파일 목록/내용을 조회할 수 있는 도구도 제공되지 않음

실제 저장소 전체를 검사하지 못했으므로, 아래 보고서는 제공된 코드에서 직접 검증 가능한 문제와 저장소에서 추가 확인해야 할 항목을 구분합니다.

요약

  • 직접 확인된 버그: 2건
  • 직접 수정 가능한 치명적 문제: 1건
  • 보안·데이터 무결성 관련 서버 보완 필요: 1건
  • 테스트 실행: 불가
  • 파일 수정: 불가

우선순위

BUG-ID 심각도 분류 상태
BUG-001 HIGH Functional / Integration 수정안 제시
BUG-002 MEDIUM Error Handling 수정안 제시
BUG-003 HIGH Data Integrity / Security 서버 확인 필요

BUG-001: 예약 취소 중복 요청

Severity: HIGH
Category: Functional / Integration
Component: 예약 취소 UI

File: 실제 저장소 파일 경로 확인 불가
제공 코드 기준 위치: handleCancel, 버튼 JSX

Description:

loading 상태가 버튼의 disabled 속성에 연결되지 않아 사용자가 연속 클릭하면 여러 개의 POST 요청이 전송됩니다.

현재 동작:

<button onClick={handleCancel}>예약 취소</button>

예상 동작:

  • 첫 번째 클릭 직후 버튼 비활성화
  • 요청이 완료될 때까지 추가 요청 차단
  • 성공 시 예약 목록/상세 상태 갱신

Impact:

  • 동일 예약에 대한 중복 취소 요청
  • 서버의 중복 처리에 따라 오류 응답, 상태 불일치 또는 중복 이벤트 발생
  • 예약 취소 알림·환불·좌석 복구 로직이 중복 실행될 가능성

Root cause:

setLoading(true);

는 상태만 변경하고 UI 입력 차단에 사용되지 않습니다.

권장 수정안 — React Query 5 사용:

import { useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';

function CancelButton({ reservationId }: { reservationId: string }) {
  const queryClient = useQueryClient();

  const cancelMutation = useMutation({
    mutationFn: async (id: string) => {
      await axios.post(`/api/reservations/${id}/cancel`);
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: ['reservation', reservationId],
      });
      await queryClient.invalidateQueries({
        queryKey: ['reservations'],
      });
    },
  });

  const handleCancel = () => {
    if (cancelMutation.isPending) return;
    cancelMutation.mutate(reservationId);
  };

  return (
    <button
      type="button"
      onClick={handleCancel}
      disabled={cancelMutation.isPending}
      aria-busy={cancelMutation.isPending}
    >
      {cancelMutation.isPending ? '취소 처리 중…' : '예약 취소'}
    </button>
  );
}

isPending과 disabled를 함께 사용해야 합니다. disabled만 넣으면 키보드·다른 이벤트 경로에서 로직이 호출될 수 있고, isPending만 검사하면 UI가 즉시 비활성화되지 않을 수 있습니다.

BUG-002: 취소 요청 실패가 사용자와 애플리케이션에 전달되지 않음

Severity: MEDIUM
Category: Error Handling
Component: 예약 취소 UI

현재 코드는 fetch 실패나 비정상 HTTP 응답을 처리하지 않습니다.

await fetch(...);
setLoading(false);

문제점:

  1. 네트워크 오류 시 예외가 발생하고 setLoading(false)가 실행되지 않음
  2. fetch는 400/500 응답에서도 reject되지 않음
  3. 사용자에게 취소 실패 이유가 표시되지 않음
  4. 버튼이 영구적으로 로딩 상태에 남을 수 있음

최소 수정 형태:

const handleCancel = async () => {
  setLoading(true);

  try {
    const response = await fetch(
      `/api/reservations/${reservationId}/cancel`,
      { method: 'POST' }
    );

    if (!response.ok) {
      throw new Error('예약 취소에 실패했습니다.');
    }
  } catch (error) {
    // 프로젝트의 토스트/에러 상태 처리 방식에 맞게 대체
    setError('예약 취소에 실패했습니다. 잠시 후 다시 시도해 주세요.');
  } finally {
    setLoading(false);
  }
};

React Query를 사용하는 경우 onError 또는 mutation의 error 상태로 처리하는 편이 일관적입니다.

BUG-003: 서버의 취소 API가 멱등성을 보장하는지 확인 필요

Severity: HIGH
Category: Data Integrity / Security
Component: /api/reservations/:reservationId/cancel

클라이언트의 disabled 처리는 UX 개선책이지 최종적인 중복 방지책은 아닙니다. 네트워크 재전송, 브라우저 재시도, 모바일 연결 불안정, 악의적인 직접 API 호출은 여전히 가능합니다.

서버에서 다음을 보장해야 합니다.

  • 이미 취소된 예약에 대한 재요청은 안전하게 처리
  • 취소 상태 전환을 원자적으로 수행
  • 환불·알림·좌석 복구 등 부수 작업이 중복 실행되지 않도록 멱등성 보장
  • 예약 소유자 또는 권한 검증
  • 유효하지 않은 예약 ID 처리
  • 트랜잭션 및 적절한 상태 코드 사용

권장 응답 예시:

  • 정상 취소: 200 또는 204
  • 이미 취소됨: 동일한 성공 의미로 처리하거나 명확한 409
  • 권한 없음: 403
  • 예약 없음: 404
  • 취소 불가 상태: 409

가능하면 Idempotency-Key를 사용하고, 서버 DB에 요청 키를 저장해 중복 부수 효과를 차단해야 합니다.

테스트 권장안

React Testing Library 기준:

it('BUG-001: 취소 요청 중 버튼을 비활성화한다', async () => {
  const user = userEvent.setup();

  render(<CancelButton reservationId="r-1" />);

  const button = screen.getByRole('button', { name: '예약 취소' });

  await user.click(button);

  expect(button).toBeDisabled();
  expect(mockCancelRequest).toHaveBeenCalledTimes(1);
});
it('BUG-002: 취소 실패 후 버튼을 다시 활성화하고 오류를 표시한다', async () => {
  mockCancelRequest.mockRejectedValueOnce(new Error('network error'));

  const user = userEvent.setup();
  render(<CancelButton reservationId="r-1" />);

  await user.click(screen.getByRole('button', { name: '예약 취소' }));

  expect(await screen.findByText(/취소에 실패/)).toBeInTheDocument();
  expect(screen.getByRole('button')).not.toBeDisabled();
});

서버 통합 테스트에는 다음을 추가해야 합니다.

같은 예약에 대해 취소 요청을 동시에 2회 전송
→ 상태 전환은 1회만 발생
→ 환불/알림/좌석 복구 이벤트도 1회만 발생

저장소 전체 감사에서 추가 확인할 항목

현재 저장소를 직접 열람할 수 없어 다음 항목은 미검증 상태입니다.

  • package.json의 실제 React Query 패키지명 및 버전
  • 예약 목록 캐시 무효화 query key
  • Axios 공통 인터셉터와 오류 처리 방식
  • 인증·권한 처리
  • 서버 API의 멱등성 및 트랜잭션
  • 테스트 프레임워크와 현재 커버리지
  • ESLint, TypeScript strict 설정
  • CI/CD 및 의존성 취약점
  • TODO, FIXME, HACK, XXX
  • 다른 화면에 존재하는 동일한 취소 로직

JSON

{
  "repository": "어울림예약 frontend",
  "analysis_date": "2026-09-24",
  "verified_bugs": 2,
  "needs_backend_verification": 1,
  "fixed_in_workspace": 0,
  "bugs": [
    {
      "id": "BUG-001",
      "severity": "HIGH",
      "category": "Functional",
      "status": "fix-proposed",
      "description": "취소 버튼이 요청 중 비활성화되지 않아 중복 POST 요청 발생"
    },
    {
      "id": "BUG-002",
      "severity": "MEDIUM",
      "category": "Error Handling",
      "status": "fix-proposed",
      "description": "네트워크 오류와 HTTP 오류를 처리하지 않으며 loading이 해제되지 않을 수 있음"
    },
    {
      "id": "BUG-003",
      "severity": "HIGH",
      "category": "Data Integrity",
      "status": "backend-verification-required",
      "description": "취소 API의 멱등성과 중복 부수 효과 방지 여부 확인 필요"
    }
  ]
}

CSV

BUG-ID,Severity,Category,Component,Status,Description,Test Added
BUG-001,HIGH,Functional,CancelButton,Fix proposed,Duplicate cancellation requests,No
BUG-002,MEDIUM,Error Handling,CancelButton,Fix proposed,Errors not handled and loading may remain active,No
BUG-003,HIGH,Data Integrity,Cancel API,Backend verification required,Idempotency not verified,No

가장 먼저 적용할 조치는 disabled={cancelMutation.isPending}와 isPending 가드이며, 동시에 서버 취소 API를 멱등적으로 만드는 것입니다.

같은 분류의 프롬프트

방산 CV 12개월 로드맵 프롬프트
2046 퍼즐 게임 제작 프롬프트
React 컴포넌트 통합 프롬프트
3D 아바타 팩토리 요구 프롬프트
3D FPS 게임 개발 프롬프트