Metadata-Version: 2.4
Name: b4user
Version: 0.1.2
Summary: B4User synthetic persona evidence workbench
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: pydantic>=2.7
Requires-Dist: PyYAML>=6.0.1
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Provides-Extra: hf
Requires-Dist: datasets>=3.0; extra == "hf"
Requires-Dist: pyarrow>=15.0; extra == "hf"
Provides-Extra: gui
Provides-Extra: web
Requires-Dist: fastapi>=0.115; extra == "web"
Requires-Dist: uvicorn>=0.32; extra == "web"
Provides-Extra: ml
Requires-Dist: joblib>=1.3; extra == "ml"
Requires-Dist: scikit-learn>=1.4; extra == "ml"
Requires-Dist: sentence-transformers>=3.0; extra == "ml"
Provides-Extra: gbm
Requires-Dist: lightgbm>=4.0; extra == "gbm"
Provides-Extra: mcp
Requires-Dist: mcp<2,>=1.27; extra == "mcp"
Provides-Extra: llm-train
Requires-Dist: accelerate>=0.30; extra == "llm-train"
Requires-Dist: datasets>=3.0; extra == "llm-train"
Requires-Dist: peft>=0.11; extra == "llm-train"
Requires-Dist: transformers>=4.41; extra == "llm-train"
Requires-Dist: trl>=0.9; extra == "llm-train"

# B4User

<p align="center">
  <img src="logo1.png" alt="B4User logo" width="720">
</p>

B4User는 "내가 만든 agent가 실효성이 있는지 검증하고 싶다"는 질문에 답하기 위한 offline-first EvaluationOps 워크벤치입니다. 한국형 synthetic persona로 AI agent의 응답 품질과 사용자 적합성을 반복 평가하고, run 비교, release gate, confidence, 개선 ticket 후보까지 한 번에 확인합니다.

> Repository 운영/공개 배포 정책은 [`REPOSITORY_POLICY.md`](REPOSITORY_POLICY.md)를 따릅니다. 현재 private working repo를 public으로 전환하지 말고, 공개용 repository는 clean export로 별도 생성합니다.

기본 경로는 API key 없이 deterministic하게 동작합니다. OpenAI, OpenAI-compatible endpoint, Ollama, Hermes Agent bridge는 사용자가 명시적으로 설정했을 때만 호출됩니다.

> B4User 결과는 synthetic persona 기반 평가 가설입니다. 실제 사용자 조사, 시장 수요 예측, 직원 인터뷰, production safety review를 대체하지 않습니다.

## 무엇을 평가하나

B4User의 핵심 질문은 단순합니다.

```text
내가 만든 agent가 우리가 신경 쓰는 사용자에게 실제로 도움이 되는가?
```

주요 workflow:

- **Response Eval**: AI agent 답변이 명확성, 실행 가능성, risk disclosure, persona fit, 다음 행동 안내를 충분히 갖췄는지 평가합니다.
- **Market Fit**: agent 또는 service concept가 persona의 문제와 맞는지, 구매와 도입 장벽이 무엇인지 가설화합니다.
- **AX Discovery**: 기업 AI 전환과 업무 자동화 전 직원에게 물어볼 interview question 후보를 만듭니다.
- **EvaluationOps**: baseline/candidate run을 기록하고 비교하며, gate, confidence, failed criteria, suggested tickets를 확인합니다.
- **Repo Evaluation**: agent repository를 정적으로 분석해 service/concept 초안을 만들고 persona 기반 평가를 실행합니다.

## 권장 v1 경로

처음 사용하는 경우에는 local deterministic demo path를 권장합니다.

1. Demo Korean personas를 불러옵니다.
2. mock target으로 Response Eval을 실행합니다.
3. Runs 또는 Compare Runs를 엽니다.
4. score trend, gate evidence, confidence, failed criteria, suggested tickets를 확인합니다.
5. agent, prompt, model, service 설명, interview plan을 수정합니다.

적합한 사용:

- prompt/model 변경 전후를 release 전에 비교합니다.
- persona segment별 response-quality regression을 찾습니다.
- 실제 고객 또는 직원 interview question 초안을 만듭니다.
- PoC 전에 adoption blocker와 trust risk를 정리합니다.
- Response Eval 또는 Market Fit 결과에서 Sales Pack을 만들고, 외부 공유 전에 사람이 검토합니다.

부적합한 사용:

- synthetic persona score를 실제 수요 예측으로 해석합니다.
- 실제 고객 조사나 직원 인터뷰를 생략합니다.
- 높은 점수만으로 market validation을 주장합니다.

## 설치

### 일반 PC에서 빠른 CLI 설치

다른 Windows PC에서 CMD/PowerShell만 열고 쓰고 싶다면 npm launcher를 권장합니다. npm package는 작은 wrapper이고, 설치 시 B4User 전용 Python runtime을 `%LOCALAPPDATA%\b4user\runtime` 아래에 만듭니다.

```cmd
npm install -g @b4user/cli
b4user --help
```

요구사항:

- Node.js/npm
- Python 3.11 이상

Python이 없다면 먼저 설치합니다.

```cmd
winget install Python.Python.3.11
npm install -g @b4user/cli
b4user --help
```

개발 중인 GitHub 버전을 npm wrapper로 설치하려면 Python package source를 지정할 수 있습니다.

```cmd
set B4USER_PYTHON_PACKAGE_SPEC=git+https://github.com/ORG/b4user.git
npm install -g @b4user/cli
b4user --help
```

> PyPI/npm에 정식 publish하기 전에는 `ORG/b4user`를 실제 repository URL로 바꾸거나, repository checkout에서 다음처럼 설치하세요.
>
> ```cmd
> cd F:\korean_simulator
> npm install -g .\npm\b4user-cli
> b4user --help
> ```

### Windows PowerShell에서 PyPI 설치

Windows PowerShell에서는 `python3` 또는 `pipx` 명령이 기본으로 없을 수 있습니다. 먼저 Python launcher인 `py`를 확인합니다.

```powershell
py --version
```

`py`가 없다면 Python 3.11 이상을 설치한 뒤 PowerShell을 새로 여세요.

```powershell
winget install Python.Python.3.11
```

가장 PATH 문제가 적은 확인 방법은 module 실행입니다. 이 방식은 `b4user.exe`가 아직 PATH에 없어도 동작합니다.

```powershell
py -m pip install --user --upgrade b4user
py -m b4user
```

인자 없이 실행하면 첫 실행 메뉴가 열립니다. PATH 문제 없이 바로 명령 목록을 보려면 다음도 사용할 수 있습니다.

```powershell
py -m b4user --help
```

`b4user --help`까지 바로 쓰고 싶다면 Python user Scripts 폴더를 사용자 PATH에 추가합니다.

```powershell
$userScripts = Join-Path (py -m site --user-base) "Scripts"
$currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
if ($currentPath -notlike "*$userScripts*") {
  [Environment]::SetEnvironmentVariable("Path", "$currentPath;$userScripts", "User")
}
Write-Host "Added to User PATH: $userScripts"
```

PowerShell 창을 완전히 닫고 새로 연 뒤 확인합니다.

```powershell
b4user --help
```

### Python/pipx 설치

Python CLI 표준 방식으로는 `pipx`가 가장 깔끔합니다. Windows에서는 `py -m pipx`로 실행하면 PATH에 `pipx` 명령이 아직 없어도 설치/설정할 수 있습니다.

```powershell
py -m pip install --user pipx
py -m pipx ensurepath
py -m pipx install b4user
```

PowerShell을 새로 연 뒤:

```powershell
b4user --help
```

PATH 반영 전이라면 다음처럼 직접 실행할 수 있습니다.

```powershell
py -m pipx run b4user --help
```

### Repository local 개발 설치

아래 순서는 Windows PowerShell에서 repository root인 `F:\korean_simulator` 기준입니다. 처음 설치하는 경우에는 1단계부터 따라가고, 이미 `.venv`가 있으면 목적별 설치만 확인하면 됩니다.

```powershell
Set-Location F:\korean_simulator
py -3.11 -m venv .venv
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"
b4user --help
```

| 목적 | 설치 명령 | 추가 요구사항 |
| --- | --- | --- |
| CLI demo와 Python test | `python -m pip install -e ".[dev]"` | 없음 |
| React Workbench | `python -m pip install -e ".[dev,web]"` | Node.js, npm |
| Nemotron/Hugging Face import | `python -m pip install -e ".[dev,hf]"` | 인터넷 또는 local dataset cache |
| MCP stdio server | `python -m pip install -e ".[dev,mcp]"` | MCP client |
| 전체 local workbench | `python -m pip install -e ".[dev,web,hf,mcp]"` | Node.js, npm |

기본 runtime dependency는 작게 유지합니다. 현재 기본 dependency는 `PyYAML`, `pydantic`입니다.

## 실행

### 가장 빠른 offline demo

API key 없이 agent 응답 평가 흐름을 먼저 확인합니다.

```powershell
b4user run `
  --personas data/personas_sample.jsonl `
  --service configs/service.yaml `
  --domain-pack generic `
  --n-personas 20 `
  --questions-per-persona 2 `
  --output-dir outputs/demo `
  --seed 42
```

명령이 끝나면 CLI가 생성된 artifact path를 출력합니다. 기본적으로 `outputs/demo` 아래에서 `run_config.json`, response quality 결과 JSONL, Markdown report, registry record를 확인합니다.

### 주요 워크플로

```powershell
# market-fit hypothesis 평가
b4user evaluate-concept `
  --personas data/personas_sample.jsonl `
  --concept configs/agent_concept.yaml `
  --domain-pack small_business_automation `
  --n-personas 20 `
  --sampling-strategy configs/sampling/small_business.yaml `
  --output-dir outputs/small_business_market_fit `
  --seed 42

# AX Discovery interview question 생성
b4user generate-discovery-questions `
  --personas data/personas_sample.jsonl `
  --service configs/service.yaml `
  --domain-pack ax_discovery `
  --n-personas 20 `
  --questions-per-persona 3 `
  --output-dir outputs/ax_discovery_demo `
  --seed 42

# 두 run 비교
b4user compare-runs `
  --baseline outputs/run_001 `
  --candidate outputs/run_002 `
  --output outputs/comparisons/cmp_001.md

# run summary export
b4user export-report `
  --run-dir outputs/demo `
  --format json `
  --output outputs/demo/summary.json
```

### Agent Repo Evaluation

B4User는 repo를 실행하지 않고 정적으로 inspection할 수 있습니다.

```powershell
b4user inspect-repo `
  --repo F:\my_agent_service `
  --output-dir outputs\repo_inspect_my_agent
```

Repo 기반 전체 평가:

```powershell
b4user evaluate-repo `
  --repo https://github.com/user/my-agent `
  --personas data/personas_sample.jsonl `
  --domain-pack small_business_automation `
  --n-personas 30 `
  --questions-per-persona 2 `
  --output-dir outputs\my_agent_repo_eval `
  --seed 42
```

주요 옵션:

- `--repo-ref`: branch, tag, commit 지정.
- `--refresh-repo`: output directory 아래 기존 shallow clone을 다시 만듭니다.
- `--clone-timeout`: clone timeout seconds. 기본값은 `120`.
- `--generate-discovery`: 추론한 service spec으로 AX Discovery question도 함께 생성합니다.

Private repo는 사용자의 Git Credential Manager 또는 SSH key 설정을 사용합니다. URL에 포함된 token/credential은 output metadata에서 masking합니다.

### Optional Target And LLM Calls

B4User에는 서로 다른 두 opt-in 호출 경로가 있습니다.

- `--target-*`: 평가 대상 agent가 synthetic persona 질문에 답합니다.
- `--llm-*`: B4User가 report 또는 structured analysis text 보강에만 LLM을 사용합니다.

OpenAI-compatible target-agent evaluation 예시:

```powershell
$env:OPENAI_API_KEY="your_api_key"

b4user run `
  --personas data/personas_sample.jsonl `
  --service configs/service.yaml `
  --domain-pack generic `
  --n-personas 3 `
  --questions-per-persona 1 `
  --output-dir outputs/openai_target_eval `
  --seed 42 `
  --target-provider openai-compatible `
  --target-base-url https://api.openai.com/v1 `
  --target-model <model_name> `
  --target-name openai-agent
```

LLM report enhancement 예시:

```powershell
b4user evaluate-concept `
  --personas data/personas_sample.jsonl `
  --concept configs/agent_concept.yaml `
  --domain-pack generic `
  --n-personas 10 `
  --output-dir outputs/llm_enhanced_market_fit `
  --seed 42 `
  --llm-provider openai-compatible `
  --llm-model <model_name> `
  --llm-enhance all
```

Remote OpenAI-compatible URL은 API key가 필요합니다. Ollama처럼 local base URL인 OpenAI-compatible target은 API key 없이 사용할 수 있습니다.

### Hermes And Ollama

Ollama/OpenHermes check는 선택 사항입니다.

```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\check_ollama.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\hermes_smoke.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\run_hermes_eval.ps1
```

Hermes Agent bridge target은 `--target-provider hermes-agent`를 명시한 경우에만 사용합니다.

```powershell
b4user target-smoke `
  --target-provider hermes-agent `
  --target-name hermes `
  --target-hermes-bridge-command "wsl python /path/to/hermes_agent_bridge.py" `
  --target-hermes-enabled-toolsets safe `
  --target-hermes-max-iterations 8 `
  --output outputs/hermes_agent_target_smoke.json
```

기본 bridge safety setting은 보수적입니다. `enabled_toolsets=safe`, memory off, context files off를 기본으로 두고, API key, raw system prompt, bridge command, runtime path는 run metadata, profile, report, export에 저장하지 않습니다.

자세한 bridge 계약과 운영 절차는 [Hermes 운영 가이드](docs/HERMES_OPERATIONS.md)와 [Hermes Agent Integration Plan](docs/HERMES_AGENT_INTEGRATION_PLAN.md)을 참고하세요.

## MCP 사용법

B4User MCP는 HTTP endpoint가 아니라 MCP client가 실행하는 stdio server입니다.

### 1. MCP extra 설치

```powershell
Set-Location F:\korean_simulator
.\.venv\Scripts\Activate.ps1
python -m pip install -e ".[dev,mcp]"
Get-Command b4user-mcp
```

`b4user-mcp` script는 `pyproject.toml`의 `b4user-mcp = "b4user.mcp.server:main"` entrypoint로 설치됩니다.

### 2. MCP client 등록

MCP client 설정 예시:

```json
{
  "mcpServers": {
    "b4user-agent-evaluator": {
      "command": "F:\\korean_simulator\\.venv\\Scripts\\b4user-mcp.exe",
      "args": [],
      "cwd": "F:\\korean_simulator"
    }
  }
}
```

### 3. 제공 tool group

Tool group:

- Agent/repo: `inspect_agent_repo`, `evaluate_agent_repo`, `analyze_repo_with_personas`, `analyze_repo_with_persona_batches`, `target_smoke`.
- Direct workflows: `run_response_quality`, `run_market_fit`, `run_ax_discovery`, `prompt_compare`, `prompt_batch_compare`.
- Runs and artifacts: `list_runs`, `resolve_run`, `list_run_insights`, `compare_runs`, `export_report`, `read_artifact`, `list_domain_packs`.
- EvaluationOps: `build_panel`, `register_panel`, `list_panels`, `export_training_data`, `validate_training_data`, `run_evaluator_baseline`, `train_evaluator`, `predict_evaluator`, `compare_evaluators`, `register_evaluator_model`, `list_evaluator_models`, `select_evaluator_threshold`, `triage_evaluations`.
- Human review and profiles: `load_human_review`, `save_human_review`, `apply_human_review`, `list_provider_profiles`.

## GUI 사용법

### React Workbench

React Workbench는 v1 EvaluationOps 경로의 기본 local UI입니다. Python API server와 Vite frontend를 각각 다른 PowerShell 터미널에서 실행합니다.

터미널 1: API server

```powershell
Set-Location F:\korean_simulator
.\.venv\Scripts\Activate.ps1
python -m pip install -e ".[dev,web]"
b4user api --host 127.0.0.1 --port 8000
```

터미널 2: frontend dev server

```powershell
Set-Location F:\korean_simulator\frontend
npm install
npm run dev
```

브라우저에서 `http://127.0.0.1:5173`을 엽니다. Frontend는 기본적으로 local API `http://127.0.0.1:8000`을 호출합니다.

첫 사용자는 Workbench에서 다음 순서로 따라가면 됩니다.

1. `Dataset`에서 demo personas 또는 JSONL path를 확인합니다.
2. `Response Eval`에서 mock target 기본값으로 offline evaluation을 실행합니다.
3. `Runs`에서 생성된 run과 score trend를 확인합니다.
4. `Compare Runs`에서 baseline/candidate를 비교합니다.
5. Gate evidence, confidence, failed criteria, suggested tickets를 보고 agent나 prompt를 수정합니다.

Local API auth를 켜려면 API server 실행 전에 token을 설정합니다.

```powershell
$env:B4USER_API_TOKEN="local-token"
b4user api --host 127.0.0.1 --port 8000
```

API token을 켠 경우에만 frontend dev server 쪽에도 같은 token을 넘깁니다.

```powershell
$env:VITE_B4USER_API_TOKEN="local-token"
npm run dev
```

### React Workbench 범위

현재 Workbench가 다루는 범위:

- Dataset preview, JSON text upload, Nemotron import.
- Service와 Agent Concept YAML editing.
- Response Eval, Market Fit, AX Discovery.
- Agent Repo inspect/evaluate.
- Research Ops panel, training export, evaluator workflow.
- Runs, Reports, Compare Runs, Prompt Compare, Prompt Batch Compare.
- Target Smoke, async workflow progress polling.
- Provider profiles, LLM enhancement settings.
- OpenAI-compatible/Ollama target settings, Hermes Agent bridge target settings.
- Sales Pack generation.

Provider secret은 request-scoped입니다. API key와 Hermes bridge command는 단일 작업을 위해 local API로 전송될 수 있지만, response, provider profile, run artifact, report, registry, export, prompt comparison metadata에는 저장하지 않습니다.

## 자주 막히는 지점

- `b4user` 명령을 찾지 못하면 `.venv`가 활성화되어 있는지 확인하고 `python -m pip install -e ".[dev]"`를 다시 실행합니다.
- React가 API offline으로 보이면 `b4user api --host 127.0.0.1 --port 8000`이 켜져 있는지 확인합니다.
- `b4user api`가 `Errno 10048` 또는 "포트는 하나만 사용할 수 있습니다"로 종료되면 이미 8000 포트에 서버가 떠 있는지 확인합니다.

  ```powershell
  Invoke-RestMethod http://127.0.0.1:8000/api/health
  ```

  `{"status":"ok","app":"b4user-api"}`가 나오면 API는 이미 실행 중이므로 새로 띄우지 말고 frontend만 실행하면 됩니다. 별도 서버가 필요하면 포트를 바꿉니다.

  ```powershell
  b4user api --host 127.0.0.1 --port 8001

  cd frontend
  $env:VITE_B4USER_API_URL="http://127.0.0.1:8001"
  npm run dev
  ```

- API health는 정상인데 Workbench가 `API offline` 또는 `Failed to fetch`를 계속 보이면 stale dev server가 8000 포트를 잡고 있을 수 있습니다. 현재 점유 프로세스를 확인합니다.

  ```powershell
  Get-NetTCPConnection -LocalAddress 127.0.0.1 -LocalPort 8000 |
    Select-Object LocalAddress,LocalPort,State,OwningProcess
  ```

  `wslrelay`가 잡고 있다면 WSL 안의 오래된 uvicorn일 수 있습니다.

  ```powershell
  wsl -e ss -ltnp | findstr ":8000"
  ```

  본인이 띄운 B4User dev server가 맞고 응답이 멈춘 상태라면 해당 WSL `python -m uvicorn b4user.api.app:app` 프로세스를 종료한 뒤 Windows `.venv`에서 다시 실행합니다.

  ```powershell
  b4user api --host 127.0.0.1 --port 8000
  ```

- frontend dependency가 깨졌다면 `frontend`에서 `npm install`을 다시 실행합니다. CI처럼 lockfile 기준 재설치가 필요하면 `npm ci`를 사용합니다.
- PowerShell script 실행이 막히면 현재 터미널에서 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass`를 먼저 실행합니다.
- Hermes Agent bridge에서 `Hermes runtime path must stay inside API workspace`가 나오면 Hermes checkout이 프로젝트 밖에 있기 때문입니다. local 개발에서는 API 실행 전에 allowlist를 명시합니다.

  ```powershell
  $env:KPEH_HERMES_RUNTIME_ALLOWLIST="C:\Users\<you>\.hermes\hermes-agent"
  ```

  WSL에서는 예를 들어 다음처럼 둡니다.

  ```bash
  export KPEH_HERMES_RUNTIME_ALLOWLIST=/home/daily/.hermes/hermes-agent
  ```

  또는 `hermes_runtime_path`를 비우고 `hermes_bridge_command` 안에서 `cd /path/to/hermes-agent && python /path/to/hermes_agent_bridge.py` 형태로 실행해도 됩니다.
- Hermes Agent smoke가 `HTTP 403`, `backend-api/codex`, `Enable JavaScript and cookies`를 반환하면 Hermes 기본 provider가 ChatGPT/Codex 웹 backend를 보고 있는 상태입니다. Target 설정에 `base_url`, `model`, `api_key`를 명시하거나 Hermes config를 안정적인 API provider로 바꿉니다.
- Hermes Agent smoke가 `failed or incomplete result`를 반환하면 `hermes_max_iterations`를 3 이상으로 올립니다. 실제 repo 평가 루프에서는 6~12를 권장합니다.

## Verification

Backend:

```powershell
python -m pytest
python -m compileall -q src tests
```

Frontend:

```powershell
cd frontend
npm test
npm run e2e -- --project=chromium --project=mobile-chromium
npm run build
```

Vite production build는 현재 통과하지만 main Workbench bundle의 chunk-size warning은 남아 있습니다. Bundle splitting은 다음 performance refactor 후보입니다.

전체 local verification script:

```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\verify_all.ps1
```

Live check는 명시적으로 opt-in합니다.

```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\verify_all.ps1 -WithHermesSmoke -WithModelCompare
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\verify_all.ps1 -WithNemotronLarge
```

## Outputs And Security Rules

- Generated artifact는 `outputs/` 아래에 생성합니다.
- Nemotron conversion file은 `data/processed/` 아래에 생성합니다.
- `outputs/`와 `data/processed/`는 Git에 커밋하지 않습니다.
- API key는 `run_config.json`, registry, report, export, smoke output, target response output에 저장하지 않습니다.
- Hermes bridge command와 runtime path는 run metadata, provider profile, report, export에 저장하지 않습니다.
- Optional LLM과 target-agent 호출은 명시적 opt-in입니다.
- Domain-specific knowledge는 `src/kpeh/domain_packs/` 아래 domain pack에 둡니다. Core evaluation logic에 새 domain rule을 직접 넣지 않습니다.

오래된 generated artifact는 dry-run으로 먼저 확인한 뒤 정리합니다.

```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\cleanup_outputs.ps1 -OlderThanDays 14
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\cleanup_outputs.ps1 -OlderThanDays 14 -ArchiveZip -Force
```

## 상세 문서

- [Hermes 운영 가이드](docs/HERMES_OPERATIONS.md)
- [Hermes Agent Integration Plan](docs/HERMES_AGENT_INTEGRATION_PLAN.md)
- [Nemotron 실험 가이드](docs/NEMOTRON_EXPERIMENTS.md)
- [GUI Workbench 가이드](docs/GUI_WORKBENCH.md)
- [Implementation Roadmap](docs/IMPLEMENTATION_ROADMAP.md)
- [Product Roadmap](docs/PRODUCT_ROADMAP.md)
