leejunyoung5819mc-paper-plugin-test-mcp-26.3

공개

마인크래프트 26.3 Paper 서버의 플러그인 테스트를 하려는 AI 에이전트를 위한 MCP 도구

mc-tester: QA harness for AI agents on Minecraft 26.3 Paper servers

Drives real Minecraft 26.3 clients (Fabric + QA Bridge mod) against a local
Paper test server so QA agents can test plugins the way players use them.

- qa-bridge: Fabric client mod exposing a localhost HTTP API (screen/GUI as
  JSON, container clicks via handleContainerInput, real mouse/keyboard
  injection, chat, entity/block interaction, screenshots, toast hiding,
  server resource pack auto-accept)
- harness: launcher (Mojang/Fabric metadata, hash-verified cache), Paper
  server management with RCON and world snapshots, shared daemon, MCP server
  (38 tools), CLI, YAML scenario runner with failure screenshots and reports
- plugin jars resolved per plugin name (newest build wins); agents can view
  and change them with plugins_list / plugins_set
- fixtures/demo-shop: NPC chest-GUI shop used to self-test the harness
- scenarios/demo-shop.yaml: purchase + GUI exploit regression test

Co-Authored-By: Claude Opus 5.5 <[email protected]>
작성자
LeeJunyoung
작성 시각
커밋
dfc82482d8390afd891f444e5172c19968defd1f
부모
없음 (첫 커밋)
이 시점의 파일 보기

변경된 파일 56개

+2,618-0

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

추가.gitignore+3-0
@@ -0,0 +1,3 @@
1추가: node_modules/
2추가: .mct/
3추가: *.log
추가.mcp.json+8-0
@@ -0,0 +1,8 @@
1추가: {
2추가: "mcpServers": {
3추가: "mc-tester": {
4추가: "command": "node",
5추가: "args": ["harness/mcp.ts"]
6추가: }
7추가: }
8추가: }
추가QA_AGENT.md+44-0
@@ -0,0 +1,44 @@
1추가: # QA 에이전트 역할 지침 (초안)
2추가:
3추가: 이 문서를 QA 역할 에이전트의 시스템 프롬프트나 역할 설명에 넣어 쓰세요. mc-tester MCP 서버(`mc-tester`)가 연결되어 있다고 가정합니다.
4추가:
5추가: ---
6추가:
7추가: 너는 마인크래프트 야생 서버(Paper 26.3 + 팀이 만든 플러그인)의 QA 담당이다. `mc-tester` 도구로 **실제 마인크래프트 클라이언트**를 조작해서 기능을 검증하고, 버그를 재현 가능한 형태로 보고한다.
8추가:
9추가: ## 작업 순서
10추가: 1. `server_status`와 `plugins_list`로 상태와 로드될 플러그인 jar를 확인한다. 테스트할 플러그인이 목록에 없거나 경로가 틀렸으면 `plugins_set`(add/remove)으로 고친다. 플러그인이 새로 빌드됐으면 `server_restart`를 해서 최신 jar를 반영한다.
11추가: 2. 테스트 플레이어는 `client_launch {name: "Bot1"}`로 띄운다. 플레이어가 여럿 필요한 기능(거래, 수표 양도, 송금)은 Bot2, Bot3을 추가한다.
12추가: 3. 상태는 `rcon`으로 준비한다(`give`, `tp`, 플러그인 관리 명령). 결정적인 테스트가 필요하면 `world_reset base`부터 한다.
13추가: 4. 사람처럼 조작한다.
14추가: - NPC: `teleport`로 2~3블록 앞까지 간 뒤 `interact_entity`
15추가: - GUI: `screen`으로 읽고 `click_item`/`click_slot`으로 클릭
16추가: - 입력창: `type_text` 다음 `key enter`
17추가: - 아이템 사용: `hotbar`로 고른 뒤 `use`
18추가: 5. 매 단계 결과를 두 쪽에서 확인한다.
19추가: - **서버의 진실**: `rcon`(플러그인 조회 명령, `data get entity`, `clear <player> <item> 0`으로 개수 세기)
20추가: - **클라이언트의 체감**: `screen`, `state`, `chat_log`/`wait_for {chat}`, 필요하면 `screenshot`
21추가: 6. 끝나면 `server_log {errors_only: true}`로 예외가 없는지 확인한다.
22추가:
23추가: ## 반드시 시도할 것 (GUI/경제 기능)
24추가: - 정상 흐름, 잔액이나 재료가 부족할 때, 인벤토리가 가득 찼을 때
25추가: - 악용 클릭:
26추가: - QUICK_MOVE(쉬프트)
27추가: - SWAP(숫자키, button 0-8과 40)
28추가: - PICKUP button 1(우클릭)
29추가: - PICKUP_ALL(더블클릭)
30추가: - THROW
31추가: - slot -999(창 밖)
32추가: - 빠른 연타(같은 클릭 여러 번)
33추가: - 거래 도중 `close_screen`이나 `client_disconnect` 후 재접속했을 때 상태가 일관적인지
34추가: - 두 클라이언트가 같은 자원(재고, 주식, 계좌)에 동시에 접근할 때
35추가: - 각 시도 후 **불변식**: 아이템 총량과 화폐 총량이 의도한 만큼만 바뀌었는지
36추가:
37추가: ## 보고 형식
38추가: - 버그마다: 재현 단계(도구 호출 순서), 기대 결과, 실제 결과(RCON 출력, 화면 JSON), 스크린샷 경로, 관련 서버 로그
39추가: - 재현이 확인된 버그와 중요한 정상 흐름은 `scenarios/<기능>.yaml` 회귀 테스트로 남기고 `run_scenario`로 통과/실패를 확인한다. 고친 뒤에는 같은 시나리오로 다시 검증한다.
40추가:
41추가: ## 주의
42추가: - 클라이언트 화면은 서버보다 한두 틱 늦을 수 있다. 판정은 서버 쪽 값으로 하고, `wait_for`나 짧은 `sleep`으로 동기화한다.
43추가: - 클라이언트 실행은 수십 초 걸리고 무겁다. 필요한 만큼만 띄우고 다 쓰면 `client_stop`한다.
44추가: - 정품 계정(`account: "microsoft"`)은 사람이 미리 로그인해 둔 경우에만 쓸 수 있다. 로그인이 필요하다는 에러가 나면 사람에게 요청한다.
추가README.md+149-0
@@ -0,0 +1,149 @@
1추가: # mc-tester
2추가:
3추가: QA 역할의 AI 에이전트가 **실제 Minecraft 26.3 클라이언트**로 Paper 야생 서버(직접 만든 플러그인 포함)를 테스트하는 하네스입니다.
4추가:
5추가: - 진짜 클라이언트를 씁니다(Fabric + **QA Bridge** 모드). 그래서 상자 GUI 상점, NPC 클릭, 표지판·모루 입력, 서버 리소스팩까지 사람이 하는 것과 같은 패킷과 화면으로 테스트됩니다.
6추가: - 에이전트는 **MCP 도구 38개**로 조작합니다. GUI는 JSON(슬롯, 아이템 이름, lore, 툴팁)으로 읽고, 필요하면 **스크린샷 이미지**를 받습니다.
7추가: - 서버 쪽 진실은 **RCON**과 서버 로그로 확인합니다(잔액, 인벤토리, 예외).
8추가: - 재현 가능한 검사는 **YAML 시나리오**로 남겨 회귀 테스트로 돌립니다.
9추가:
10추가: ```
11추가: QA 에이전트 ──MCP(stdio)──▶ harness/mcp.ts ─┐
12추가: CLI / CI ───────────────▶ harness/cli.ts ──┼─HTTP─▶ harness/daemon.ts (서버·클라이언트 소유, 여러 에이전트가 공유)
13추가: │ ├─ Paper 26.3 테스트 서버 (127.0.0.1:25565, RCON 25575)
14추가: │ └─ 클라이언트 N개 (Xvfb 가상 화면 또는 데스크톱 창)
15추가: │ └─ QA Bridge 모드: 127.0.0.1:7800+ HTTP API
16추가: ```
17추가:
18추가: ## 요구 사항
19추가:
20추가: - Linux, Java 25, Node 24 이상, `Xvfb`(`sudo apt install xvfb`). 이 PC에서는 모두 확인했습니다.
21추가: - 첫 실행 때 Mojang/Fabric/PaperMC 공식 저장소에서 클라이언트, 라이브러리, 에셋(약 5천 개), Paper jar를 받아 `.mct/cache/`에 캐시합니다. 모든 파일은 해시로 검증합니다.
22추가:
23추가: ## 빠른 시작
24추가:
25추가: ```bash
26추가: npm install
27추가: npm run build:mods # qa-bridge 모드 + 데모 상점 플러그인 빌드
28추가: npm run mct -- scenario scenarios/demo-shop.yaml # 서버 실행 → 클라이언트 접속 → 상점 테스트 (약 20~30초)
29추가: ```
30추가:
31추가: 수동으로 조작할 때:
32추가:
33추가: ```bash
34추가: npm run mct -- server_start
35추가: npm run mct -- client_launch name=Bot1
36추가: npm run mct -- rcon command='give Bot1 emerald 10'
37추가: npm run mct -- interact_entity name=상점 screenshot=true
38추가: npm run mct -- screen
39추가: npm run mct -- click_item name=다이아몬드
40추가: npm run mct -- daemon-stop # 클라이언트·서버·데몬 모두 종료
41추가: ```
42추가:
43추가: 결과물:
44추가: - 스크린샷: `.mct/artifacts/<플레이어>/`
45추가: - 시나리오 리포트(JSON): `.mct/reports/`
46추가: - 클라이언트 로그: `.mct/clients/<플레이어>/mct-client.log`
47추가: - 데몬 로그: `.mct/run/daemon.log`
48추가:
49추가: ## 에이전트에 연결하기 (MCP)
50추가:
51추가: 이 저장소 안에서 실행하는 에이전트는 루트의 `.mcp.json`이 자동으로 잡힙니다. 다른 저장소에서 일하는 QA 에이전트에는 이 저장소를 clone한 위치의 절대 경로로 등록하세요.
52추가:
53추가: ```json
54추가: {
55추가: "mcpServers": {
56추가: "mc-tester": {
57추가: "command": "node",
58추가: "args": ["/absolute/path/to/mc-tester/harness/mcp.ts"]
59추가: }
60추가: }
61추가: }
62추가: ```
63추가:
64추가: QA 에이전트의 역할 지침(시스템 프롬프트) 초안은 [QA_AGENT.md](QA_AGENT.md)에 있습니다.
65추가:
66추가: MCP 서버들은 하나의 데몬을 공유합니다. 처음 호출할 때 데몬이 자동으로 뜨고, 여러 에이전트가 같은 서버와 클라이언트를 함께 봅니다.
67추가:
68추가: ## 직접 만든 플러그인 연결
69추가:
70추가: 플러그인 jar 경로는 `mct.config.json`의 `server.plugins`에 들어가고, **처음 한 번만 정하면 됩니다.** 파일 이름에 `*`를 쓸 수 있어서 버전이 바뀌어도 그대로 동작해요. `server_start`/`server_restart` 때마다 패턴으로 jar를 다시 찾아 복사하므로, **플러그인을 다시 빌드하고 `server_restart`만 하면 새 코드가 테스트됩니다.**
71추가:
72추가: 경로는 AI 에이전트가 직접 설정할 수 있습니다.
73추가: - `plugins_list`: 설정된 패턴, 실제로 로드될 jar(플러그인 이름, 버전, 빌드 시각), 건너뛴 jar, 아무것도 못 찾은 패턴을 보여줌
74추가: - `plugins_set`: 목록 전체 교체(`plugins`) 또는 `add`/`remove`. `mct.config.json`에 저장되고, `restart: true`면 바로 재시작해 반영함. 존재하지 않는 경로는 저장을 거부함(아직 빌드 전이면 `allow_unmatched: true`)
75추가:
76추가: ```bash
77추가: npm run mct -- plugins_set add='["../my-survival-server/build/libs/MySurvival-*.jar"]' restart=true
78추가: ```
79추가:
80추가: 직접 편집해도 됩니다(`mct.config.example.json` 참고).
81추가:
82추가: ```json
83추가: {
84추가: "server": {
85추가: "plugins": [
86추가: "../my-survival-server/build/libs/MySurvival-*.jar",
87추가: "../libs/*.jar"
88추가: ]
89추가: }
90추가: }
91추가: ```
92추가:
93추가: **같은 플러그인의 jar가 여러 개 잡히면** 가장 최근에 빌드된 하나만 설치합니다. `build/libs`에 남은 예전 버전이나, shadow 플러그인의 `-all.jar`와 일반 jar가 같이 있는 경우가 그래요. 같은 플러그인인지는 jar 안의 `plugin.yml`/`paper-plugin.yml`의 `name`으로 판단하므로, `../libs/*.jar`처럼 서로 다른 플러그인 여러 개를 한 패턴으로 넣는 것도 됩니다. 건너뛴 jar는 `server_start` 결과의 `skippedJars`와 `plugins_list`에 나옵니다.
94추가:
95추가: 설정 항목 전체는 [harness/config.ts](harness/config.ts)에 기본값과 함께 있습니다. 주요 기본값:
96추가: - 평지 월드, peaceful, 시간·날씨 고정, 몹 스폰 끔
97추가: - 127.0.0.1에만 바인드, offline-mode
98추가: - 클라이언트 언어 `ko_kr`, 1280x720, GUI 배율 2
99추가: - 토스트 숨김, 서버 리소스팩 자동 수락
100추가:
101추가: ## 도구 목록
102추가:
103추가: | 분류 | 도구 |
104추가: |---|---|
105추가: | 서버 | `server_start` `server_stop` `server_restart` `server_status` `rcon` `server_log` `world_snapshot` `world_reset` |
106추가: | 플러그인 | `plugins_list` `plugins_set` |
107추가: | 클라이언트 | `client_launch` `client_stop` `client_list` `client_connect` `client_disconnect` |
108추가: | 관찰 | `state` `screen` `screenshot` `chat_log` `entities` `wait_for` |
109추가: | GUI 입력 | `click_slot` `click_item` `mouse` `click_widget` `key` `type_text` `close_screen` |
110추가: | 월드 입력 | `chat` `teleport` `look` `interact_entity` `use_on_block` `use` `attack` `hold_keys` `hotbar` |
111추가: | 회귀 | `run_scenario` |
112추가:
113추가: - `click_slot`과 `click_item`은 클라이언트의 `MultiPlayerGameMode.handleContainerInput`(GUI가 실제로 호출하는 함수)을 거칩니다. PICKUP, QUICK_MOVE(쉬프트), SWAP(숫자키), CLONE, THROW, QUICK_CRAFT(드래그), PICKUP_ALL(더블클릭)을 모두 보낼 수 있습니다.
114추가: - `mouse`, `key`, `type_text`는 SDL 이벤트 핸들러가 호출하는 `MouseHandler`/`KeyboardHandler`에 그대로 주입되므로 실제 입력과 같은 경로입니다.
115추가: - 행동 도구에 `screenshot: true`를 주면 결과 직후의 화면 이미지가 함께 돌아옵니다.
116추가:
117추가: ## 시나리오
118추가:
119추가: [scenarios/README.md](scenarios/README.md)를 보세요. 예제는 [scenarios/demo-shop.yaml](scenarios/demo-shop.yaml)입니다. NPC 상점 구매에 더해 쉬프트, 숫자키, 우클릭 악용 시도를 하고, RCON으로 아이템이 보존되는지 확인합니다.
120추가:
121추가: `fixtures/demo-shop/`은 하네스 자체를 검증하기 위한 작은 Paper 플러그인입니다. `/demoshop bug on`으로 일부러 복사 버그를 켜면 위 시나리오가 `diamond = 2, expected 1`로 실패하고, 실패 순간 스크린샷이 남습니다.
122추가:
123추가: ## 정품(Microsoft) 계정
124추가:
125추가: offline 테스트 플레이어로 대부분 테스트할 수 있습니다. 실제 인증, UUID, 스킨이 필요한 테스트에만 정품 계정을 씁니다.
126추가:
127추가: ```bash
128추가: npm run mct -- login # 표시된 URL을 브라우저로 열고 코드를 입력 (사람이 해야 함)
129추가: npm run mct -- client_launch name=me account=microsoft
130추가: ```
131추가:
132추가: - 토큰은 `.mct/auth/`에 캐시됩니다(권한 700, git 제외). 하네스는 토큰을 출력하지 않습니다.
133추가: - 같은 계정으로 동시에 접속할 수 있는 클라이언트는 하나뿐입니다. 테스트 중에 그 계정으로 직접 플레이하면 둘 중 하나가 튕깁니다.
134추가: - 실제 인증 서버로 테스트하려면 `mct.config.json`에 `"server": {"onlineMode": true}`를 넣으세요. 이 모드에서는 offline 플레이어가 접속할 수 없습니다.
135추가:
136추가: ## 디렉터리
137추가:
138추가: - `qa-bridge/`: Fabric 26.3 클라이언트 모드(Java). 127.0.0.1 HTTP API를 제공합니다.
139추가: - `harness/`: TypeScript(Node가 직접 실행). 런처, Paper 관리, RCON, 데몬, MCP, CLI, 시나리오 러너가 들어 있습니다.
140추가: - `fixtures/demo-shop/`: 검증용 Paper 플러그인
141추가: - `scenarios/`: YAML 회귀 테스트
142추가: - `tests/mcp-smoke.ts`: MCP 연결 스모크 테스트
143추가: - `.mct/`: 런타임 데이터(캐시, 서버, 클라이언트, 스크린샷, 리포트). git에서 제외됩니다.
144추가:
145추가: ## 알려진 한계
146추가:
147추가: - 클라이언트 하나에 RAM 약 2~3GB가 들고, Xvfb에서는 CPU 렌더링(llvmpipe, 약 10fps)이라 무겁습니다. 동시에 여러 명이 필요한 테스트(거래, 수표 양도, 동시 구매)는 몇 개 정도가 적당하고, 수십 명 부하 테스트에는 맞지 않습니다.
148추가: - 긴 거리 이동은 `teleport`(RCON)로 합니다. 경로 탐색은 없습니다.
149추가: - Minecraft 버전을 올리면 QA Bridge가 쓰는 클라이언트 내부 API가 바뀔 수 있습니다. `qa-bridge/gradle.properties`의 버전을 올리고 다시 빌드한 다음 `scenarios/demo-shop.yaml`로 확인하세요.
추가bin/mct.mjs+7-0
@@ -0,0 +1,7 @@
1추가: #!/usr/bin/env node
2추가: // Wrapper so `npx mct ...` / a global link works: runs the TypeScript CLI with Node's type stripping.
3추가: import { spawnSync } from 'node:child_process';
4추가: import path from 'node:path';
5추가: const cli = path.join(import.meta.dirname, '..', 'harness', 'cli.ts');
6추가: const r = spawnSync(process.execPath, [cli, ...process.argv.slice(2)], { stdio: 'inherit' });
7추가: process.exit(r.status ?? 1);
추가fixtures/demo-shop/.gitignore+6-0
@@ -0,0 +1,6 @@
1추가: .gradle/
2추가: build/
3추가: run/
4추가: out/
5추가: *.iml
6추가: .idea/
추가fixtures/demo-shop/build.gradle+21-0
@@ -0,0 +1,21 @@
1추가: plugins { id 'java' }
2추가:
3추가: group = 'dev.mctester'
4추가: version = '0.1.0'
5추가:
6추가: repositories {
7추가: maven { url = 'https://repo.papermc.io/repository/maven-public/' }
8추가: mavenCentral()
9추가: }
10추가:
11추가: dependencies {
12추가: compileOnly 'io.papermc.paper:paper-api:26.3.build.262-stable'
13추가: }
14추가:
15추가: java { toolchain { languageVersion = JavaLanguageVersion.of(25) } }
16추가: tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8'; options.release = 25 }
17추가: processResources {
18추가: def v = project.version
19추가: inputs.property 'version', v
20추가: filesMatching('plugin.yml') { expand version: v }
21추가: }
추가fixtures/demo-shop/gradle.properties+2-0
@@ -0,0 +1,2 @@
1추가: org.gradle.jvmargs=-Xmx1G
2추가: org.gradle.configuration-cache=true
추가fixtures/demo-shop/gradle/wrapper/gradle-wrapper.jar

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가fixtures/demo-shop/gradle/wrapper/gradle-wrapper.properties+9-0
@@ -0,0 +1,9 @@
1추가: distributionBase=GRADLE_USER_HOME
2추가: distributionPath=wrapper/dists
3추가: distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip
4추가: networkTimeout=10000
5추가: retries=0
6추가: retryBackOffMs=500
7추가: validateDistributionUrl=true
8추가: zipStoreBase=GRADLE_USER_HOME
9추가: zipStorePath=wrapper/dists
추가fixtures/demo-shop/gradlew+248-0
@@ -0,0 +1,248 @@
1추가: #!/bin/sh
2추가:
3추가: #
4추가: # Copyright © 2015 the original authors.
5추가: #
6추가: # Licensed under the Apache License, Version 2.0 (the "License");
7추가: # you may not use this file except in compliance with the License.
8추가: # You may obtain a copy of the License at
9추가: #
10추가: # https://www.apache.org/licenses/LICENSE-2.0
11추가: #
12추가: # Unless required by applicable law or agreed to in writing, software
13추가: # distributed under the License is distributed on an "AS IS" BASIS,
14추가: # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15추가: # See the License for the specific language governing permissions and
16추가: # limitations under the License.
17추가: #
18추가: # SPDX-License-Identifier: Apache-2.0
19추가: #
20추가:
21추가: ##############################################################################
22추가: #
23추가: # gradlew start up script for POSIX generated by Gradle.
24추가: #
25추가: # Important for running:
26추가: #
27추가: # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
28추가: # noncompliant, but you have some other compliant shell such as ksh or
29추가: # bash, then to run this script, type that shell name before the whole
30추가: # command line, like:
31추가: #
32추가: # ksh gradlew
33추가: #
34추가: # Busybox and similar reduced shells will NOT work, because this script
35추가: # requires all of these POSIX shell features:
36추가: # * functions;
37추가: # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
38추가: # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
39추가: # * compound commands having a testable exit status, especially «case»;
40추가: # * various built-in commands including «command», «set», and «ulimit».
41추가: #
42추가: # Important for patching:
43추가: #
44추가: # (2) This script targets any POSIX shell, so it avoids extensions provided
45추가: # by Bash, Ksh, etc; in particular arrays are avoided.
46추가: #
47추가: # The "traditional" practice of packing multiple parameters into a
48추가: # space-separated string is a well documented source of bugs and security
49추가: # problems, so this is (mostly) avoided, by progressively accumulating
50추가: # options in "$@", and eventually passing that to Java.
51추가: #
52추가: # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
53추가: # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
54추가: # see the in-line comments for details.
55추가: #
56추가: # There are tweaks for specific operating systems such as AIX, CygWin,
57추가: # Darwin, MinGW, and NonStop.
58추가: #
59추가: # (3) This script is generated from the Groovy template
60추가: # https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
61추가: # within the Gradle project.
62추가: #
63추가: # You can find Gradle at https://github.com/gradle/gradle/.
64추가: #
65추가: ##############################################################################
66추가:
67추가: # Attempt to set APP_HOME
68추가:
69추가: # Resolve links: $0 may be a link
70추가: app_path=$0
71추가:
72추가: # Need this for daisy-chained symlinks.
73추가: while
74추가: APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
75추가: [ -h "$app_path" ]
76추가: do
77추가: ls=$( ls -ld "$app_path" )
78추가: link=${ls#*' -> '}
79추가: case $link in #(
80추가: /*) app_path=$link ;; #(
81추가: *) app_path=$APP_HOME$link ;;
82추가: esac
83추가: done
84추가:
85추가: # This is normally unused
86추가: # shellcheck disable=SC2034
87추가: APP_BASE_NAME=${0##*/}
88추가: # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
89추가: APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
90추가:
91추가: # Use the maximum available, or set MAX_FD != -1 to use that value.
92추가: MAX_FD=maximum
93추가:
94추가: warn () {
95추가: echo "$*"
96추가: } >&2
97추가:
98추가: die () {
99추가: echo
100추가: echo "$*"
101추가: echo
102추가: exit 1
103추가: } >&2
104추가:
105추가: # OS specific support (must be 'true' or 'false').
106추가: cygwin=false
107추가: msys=false
108추가: darwin=false
109추가: nonstop=false
110추가: case "$( uname )" in #(
111추가: CYGWIN* ) cygwin=true ;; #(
112추가: Darwin* ) darwin=true ;; #(
113추가: MSYS* | MINGW* ) msys=true ;; #(
114추가: NONSTOP* ) nonstop=true ;;
115추가: esac
116추가:
117추가:
118추가:
119추가: # Determine the Java command to use to start the JVM.
120추가: if [ -n "$JAVA_HOME" ] ; then
121추가: if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
122추가: # IBM's JDK on AIX uses strange locations for the executables
123추가: JAVACMD=$JAVA_HOME/jre/sh/java
124추가: else
125추가: JAVACMD=$JAVA_HOME/bin/java
126추가: fi
127추가: if [ ! -x "$JAVACMD" ] ; then
128추가: die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
129추가:
130추가: Please set the JAVA_HOME variable in your environment to match the
131추가: location of your Java installation."
132추가: fi
133추가: else
134추가: JAVACMD=java
135추가: if ! command -v java >/dev/null 2>&1
136추가: then
137추가: die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
138추가:
139추가: Please set the JAVA_HOME variable in your environment to match the
140추가: location of your Java installation."
141추가: fi
142추가: fi
143추가:
144추가: # Increase the maximum file descriptors if we can.
145추가: if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
146추가: case $MAX_FD in #(
147추가: max*)
148추가: # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
149추가: # shellcheck disable=SC2039,SC3045
150추가: MAX_FD=$( ulimit -H -n ) ||
151추가: warn "Could not query maximum file descriptor limit"
152추가: esac
153추가: case $MAX_FD in #(
154추가: '' | soft) :;; #(
155추가: *)
156추가: # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
157추가: # shellcheck disable=SC2039,SC3045
158추가: ulimit -n "$MAX_FD" ||
159추가: warn "Could not set maximum file descriptor limit to $MAX_FD"
160추가: esac
161추가: fi
162추가:
163추가: # Collect all arguments for the java command, stacking in reverse order:
164추가: # * args from the command line
165추가: # * the main class name
166추가: # * -classpath
167추가: # * -D...appname settings
168추가: # * --module-path (only if needed)
169추가: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
170추가:
171추가: # For Cygwin or MSYS, switch paths to Windows format before running java
172추가: if "$cygwin" || "$msys" ; then
173추가: APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
174추가:
175추가: JAVACMD=$( cygpath --unix "$JAVACMD" )
176추가:
177추가: # Now convert the arguments - kludge to limit ourselves to /bin/sh
178추가: for arg do
179추가: if
180추가: case $arg in #(
181추가: -*) false ;; # don't mess with options #(
182추가: /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183추가: [ -e "$t" ] ;; #(
184추가: *) false ;;
185추가: esac
186추가: then
187추가: arg=$( cygpath --path --ignore --mixed "$arg" )
188추가: fi
189추가: # Roll the args list around exactly as many times as the number of
190추가: # args, so each arg winds up back in the position where it started, but
191추가: # possibly modified.
192추가: #
193추가: # NB: a `for` loop captures its iteration list before it begins, so
194추가: # changing the positional parameters here affects neither the number of
195추가: # iterations, nor the values presented in `arg`.
196추가: shift # remove old arg
197추가: set -- "$@" "$arg" # push replacement arg
198추가: done
199추가: fi
200추가:
201추가:
202추가: # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203추가: DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204추가:
205추가: # Collect all arguments for the java command:
206추가: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207추가: # and any embedded shellness will be escaped.
208추가: # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209추가: # treated as '${Hostname}' itself on the command line.
210추가:
211추가: set -- \
212추가: "-Dorg.gradle.appname=$APP_BASE_NAME" \
213추가: -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
214추가: "$@"
215추가:
216추가: # Stop when "xargs" is not available.
217추가: if ! command -v xargs >/dev/null 2>&1
218추가: then
219추가: die "xargs is not available"
220추가: fi
221추가:
222추가: # Use "xargs" to parse quoted args.
223추가: #
224추가: # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
225추가: #
226추가: # In Bash we could simply go:
227추가: #
228추가: # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
229추가: # set -- "${ARGS[@]}" "$@"
230추가: #
231추가: # but POSIX shell has neither arrays nor command substitution, so instead we
232추가: # post-process each arg (as a line of input to sed) to backslash-escape any
233추가: # character that might be a shell metacharacter, then use eval to reverse
234추가: # that process (while maintaining the separation between arguments), and wrap
235추가: # the whole thing up as a single "set" statement.
236추가: #
237추가: # This will of course break if any of these variables contains a newline or
238추가: # an unmatched quote.
239추가: #
240추가:
241추가: eval "set -- $(
242추가: printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
243추가: xargs -n1 |
244추가: sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
245추가: tr '\n' ' '
246추가: )" '"$@"'
247추가:
248추가: exec "$JAVACMD" "$@"
추가fixtures/demo-shop/settings.gradle+1-0
@@ -0,0 +1 @@
1추가: rootProject.name = 'demo-shop'
추가fixtures/demo-shop/src/main/java/dev/mctester/demoshop/DemoShopPlugin.java+166-0
@@ -0,0 +1,166 @@
1추가: package dev.mctester.demoshop;
2추가:
3추가: import net.kyori.adventure.text.Component;
4추가: import net.kyori.adventure.text.format.NamedTextColor;
5추가: import net.kyori.adventure.text.format.TextDecoration;
6추가: import org.bukkit.Bukkit;
7추가: import org.bukkit.Location;
8추가: import org.bukkit.Material;
9추가: import org.bukkit.NamespacedKey;
10추가: import org.bukkit.command.Command;
11추가: import org.bukkit.command.CommandSender;
12추가: import org.bukkit.entity.Entity;
13추가: import org.bukkit.entity.Player;
14추가: import org.bukkit.entity.Villager;
15추가: import org.bukkit.event.EventHandler;
16추가: import org.bukkit.event.Listener;
17추가: import org.bukkit.event.inventory.ClickType;
18추가: import org.bukkit.event.inventory.InventoryClickEvent;
19추가: import org.bukkit.event.inventory.InventoryDragEvent;
20추가: import org.bukkit.event.player.PlayerInteractEntityEvent;
21추가: import org.bukkit.inventory.EquipmentSlot;
22추가: import org.bukkit.inventory.Inventory;
23추가: import org.bukkit.inventory.InventoryHolder;
24추가: import org.bukkit.inventory.ItemStack;
25추가: import org.bukkit.inventory.meta.ItemMeta;
26추가: import org.bukkit.persistence.PersistentDataType;
27추가: import org.bukkit.plugin.java.JavaPlugin;
28추가:
29추가: import java.util.List;
30추가:
31추가: /**
32추가: * Fixture plugin for mc-tester. Not a real shop: it exists so the harness has a
33추가: * realistic NPC -> chest GUI -> purchase flow to drive and assert against.
34추가: *
35추가: * /demoshop spawn [x y z] spawn the shop NPC (villager named "상점")
36추가: * /demoshop balance <player> print JSON item counts (for RCON assertions)
37추가: * /demoshop bug <on|off> when on, shift-click on the shop is NOT cancelled (dupe bug on purpose)
38추가: */
39추가: public final class DemoShopPlugin extends JavaPlugin implements Listener {
40추가: static final int PRICE = 5;
41추가: static final int SLOT_DIAMOND = 11;
42추가: static final int SLOT_INFO = 15;
43추가: static final Component TITLE = Component.text("데모 상점");
44추가:
45추가: private NamespacedKey npcKey;
46추가: private volatile boolean bug = false;
47추가:
48추가: static final class ShopHolder implements InventoryHolder {
49추가: Inventory inv;
50추가: @Override public Inventory getInventory() { return inv; }
51추가: }
52추가:
53추가: @Override
54추가: public void onEnable() {
55추가: npcKey = new NamespacedKey(this, "shop_npc");
56추가: Bukkit.getPluginManager().registerEvents(this, this);
57추가: }
58추가:
59추가: @Override
60추가: public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
61추가: if (args.length == 0) return false;
62추가: switch (args[0]) {
63추가: case "spawn" -> {
64추가: Location loc;
65추가: if (args.length >= 4) {
66추가: loc = new Location(Bukkit.getWorlds().getFirst(), Double.parseDouble(args[1]), Double.parseDouble(args[2]), Double.parseDouble(args[3]));
67추가: } else if (sender instanceof Player p) {
68추가: loc = p.getLocation();
69추가: } else {
70추가: loc = Bukkit.getWorlds().getFirst().getSpawnLocation();
71추가: }
72추가: Villager v = loc.getWorld().spawn(loc, Villager.class, e -> {
73추가: e.customName(Component.text("상점"));
74추가: e.setCustomNameVisible(true);
75추가: e.setAI(false);
76추가: e.setInvulnerable(true);
77추가: e.setSilent(true);
78추가: e.setPersistent(true);
79추가: e.getPersistentDataContainer().set(npcKey, PersistentDataType.BYTE, (byte) 1);
80추가: });
81추가: sender.sendMessage("{\"spawned\":\"" + v.getUniqueId() + "\"}");
82추가: }
83추가: case "balance" -> {
84추가: if (args.length < 2) return false;
85추가: Player p = Bukkit.getPlayerExact(args[1]);
86추가: if (p == null) { sender.sendMessage("{\"error\":\"offline\"}"); return true; }
87추가: sender.sendMessage("{\"player\":\"" + p.getName() + "\",\"emerald\":" + count(p, Material.EMERALD)
88추가: + ",\"diamond\":" + count(p, Material.DIAMOND) + "}");
89추가: }
90추가: case "bug" -> {
91추가: bug = args.length > 1 && args[1].equalsIgnoreCase("on");
92추가: sender.sendMessage("{\"bug\":" + bug + "}");
93추가: }
94추가: default -> { return false; }
95추가: }
96추가: return true;
97추가: }
98추가:
99추가: private static int count(Player p, Material m) {
100추가: int n = 0;
101추가: for (ItemStack s : p.getInventory().getStorageContents()) if (s != null && s.getType() == m) n += s.getAmount();
102추가: ItemStack cursor = p.getItemOnCursor();
103추가: if (cursor.getType() == m) n += cursor.getAmount();
104추가: return n;
105추가: }
106추가:
107추가: private Inventory createShop() {
108추가: ShopHolder holder = new ShopHolder();
109추가: Inventory inv = Bukkit.createInventory(holder, 27, TITLE);
110추가: holder.inv = inv;
111추가: inv.setItem(SLOT_DIAMOND, named(Material.DIAMOND, Component.text("다이아몬드", NamedTextColor.AQUA),
112추가: List.of(Component.text("가격: 에메랄드 " + PRICE + "개", NamedTextColor.GRAY),
113추가: Component.text("좌클릭: 구매", NamedTextColor.YELLOW))));
114추가: inv.setItem(SLOT_INFO, named(Material.PAPER, Component.text("안내", NamedTextColor.WHITE),
115추가: List.of(Component.text("에메랄드로 다이아몬드를 삽니다", NamedTextColor.GRAY))));
116추가: ItemStack pane = named(Material.GRAY_STAINED_GLASS_PANE, Component.text(" "), List.of());
117추가: for (int i = 0; i < 27; i++) if (inv.getItem(i) == null) inv.setItem(i, pane);
118추가: return inv;
119추가: }
120추가:
121추가: private static ItemStack named(Material m, Component name, List<Component> lore) {
122추가: ItemStack s = new ItemStack(m);
123추가: ItemMeta meta = s.getItemMeta();
124추가: meta.itemName(name.decoration(TextDecoration.ITALIC, false));
125추가: meta.lore(lore.stream().map(c -> c.decoration(TextDecoration.ITALIC, false)).toList());
126추가: s.setItemMeta(meta);
127추가: return s;
128추가: }
129추가:
130추가: @EventHandler
131추가: public void onInteract(PlayerInteractEntityEvent e) {
132추가: Entity en = e.getRightClicked();
133추가: if (!en.getPersistentDataContainer().has(npcKey)) return;
134추가: e.setCancelled(true);
135추가: if (e.getHand() != EquipmentSlot.HAND) return;
136추가: Player p = e.getPlayer();
137추가: Bukkit.getScheduler().runTask(this, () -> p.openInventory(createShop()));
138추가: }
139추가:
140추가: @EventHandler
141추가: public void onClick(InventoryClickEvent e) {
142추가: if (!(e.getView().getTopInventory().getHolder() instanceof ShopHolder)) return;
143추가: Player p = (Player) e.getWhoClicked();
144추가: boolean top = e.getClickedInventory() == e.getView().getTopInventory();
145추가: if (bug && e.getClick() == ClickType.SHIFT_LEFT) {
146추가: // Intentional dupe bug for harness self-test: shift-click is let through.
147추가: return;
148추가: }
149추가: e.setCancelled(true);
150추가: if (!top) return;
151추가: if (e.getRawSlot() == SLOT_DIAMOND && e.getClick() == ClickType.LEFT) {
152추가: if (count(p, Material.EMERALD) < PRICE) {
153추가: p.sendMessage(Component.text("에메랄드가 부족합니다", NamedTextColor.RED));
154추가: return;
155추가: }
156추가: p.getInventory().removeItem(new ItemStack(Material.EMERALD, PRICE));
157추가: p.getInventory().addItem(new ItemStack(Material.DIAMOND, 1));
158추가: p.sendMessage(Component.text("구매 완료: 다이아몬드 1개", NamedTextColor.GREEN));
159추가: }
160추가: }
161추가:
162추가: @EventHandler
163추가: public void onDrag(InventoryDragEvent e) {
164추가: if (e.getView().getTopInventory().getHolder() instanceof ShopHolder) e.setCancelled(true);
165추가: }
166추가: }
추가fixtures/demo-shop/src/main/resources/plugin.yml+13-0
@@ -0,0 +1,13 @@
1추가: name: DemoShop
2추가: version: '${version}'
3추가: main: dev.mctester.demoshop.DemoShopPlugin
4추가: api-version: '26.3'
5추가: description: mc-tester fixture - a tiny NPC chest-GUI shop used to verify the QA harness.
6추가: commands:
7추가: demoshop:
8추가: description: DemoShop admin/test commands
9추가: usage: /demoshop <spawn|balance|bug> ...
10추가: permission: demoshop.admin
11추가: permissions:
12추가: demoshop.admin:
13추가: default: op
추가harness/auth.ts+76-0
@@ -0,0 +1,76 @@
1추가: // Player identities for launched clients.
2추가: // - offline: any name, UUID derived like the server does for offline players. Only works with online-mode=false.
3추가: // - microsoft: your real Minecraft account via Microsoft device-code login (prismarine-auth).
4추가: // Tokens are cached under .mct/auth (mode 700). The harness never prints them.
5추가: import crypto from 'node:crypto';
6추가: import fs from 'node:fs';
7추가: import path from 'node:path';
8추가: import { DIRS } from './config.ts';
9추가:
10추가: export interface Identity {
11추가: name: string;
12추가: uuid: string;
13추가: accessToken: string;
14추가: userType: 'msa' | 'legacy';
15추가: xuid: string;
16추가: online: boolean;
17추가: }
18추가:
19추가: export function offlineIdentity(name: string): Identity {
20추가: if (!/^[A-Za-z0-9_]{3,16}$/.test(name)) throw new Error(`invalid player name '${name}' (3-16 chars, A-Z a-z 0-9 _)`);
21추가: // Same as Java UUID.nameUUIDFromBytes("OfflinePlayer:" + name): MD5, version 3, IETF variant.
22추가: const h = crypto.createHash('md5').update('OfflinePlayer:' + name, 'utf8').digest();
23추가: h[6] = (h[6] & 0x0f) | 0x30;
24추가: h[8] = (h[8] & 0x3f) | 0x80;
25추가: const hex = h.toString('hex');
26추가: const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
27추가: return { name, uuid, accessToken: '0', userType: 'legacy', xuid: '0', online: false };
28추가: }
29추가:
30추가: export interface LoginPrompt {
31추가: verificationUri: string;
32추가: userCode: string;
33추가: message: string;
34추가: }
35추가:
36추가: /**
37추가: * Microsoft login. On first use this needs a human: `onCode` receives the device-code prompt
38추가: * (open the URL, enter the code). Later calls reuse/refresh the cached tokens silently.
39추가: */
40추가: export async function microsoftIdentity(profileKey = 'default', onCode?: (p: LoginPrompt) => void, interactive = true): Promise<Identity> {
41추가: const { Authflow, Titles } = await import('prismarine-auth');
42추가: const cache = path.join(DIRS.auth, profileKey);
43추가: fs.mkdirSync(cache, { recursive: true, mode: 0o700 });
44추가: let needLogin: (e: Error) => void = () => {};
45추가: const loginRequired = new Promise<never>((_, reject) => (needLogin = reject));
46추가: const flow = new Authflow(
47추가: profileKey,
48추가: cache,
49추가: { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' },
50추가: (res: any) => {
51추가: const p: LoginPrompt = {
52추가: verificationUri: res.verification_uri ?? res.verificationUri,
53추가: userCode: res.user_code ?? res.userCode,
54추가: message: res.message,
55추가: };
56추가: if (!interactive) {
57추가: needLogin(new Error(`Microsoft login required for profile '${profileKey}'. A human must run: npm run mct -- login ${profileKey}`));
58추가: return;
59추가: }
60추가: if (onCode) onCode(p);
61추가: else console.error(p.message);
62추가: },
63추가: );
64추가: const tok: any = await Promise.race([flow.getMinecraftJavaToken({ fetchProfile: true }), loginRequired]);
65추가: if (!tok?.profile?.id) {
66추가: throw new Error('Microsoft account has no Minecraft: Java Edition profile (does this account own Java Edition?)');
67추가: }
68추가: const raw = String(tok.profile.id).replace(/-/g, '');
69추가: const uuid = `${raw.slice(0, 8)}-${raw.slice(8, 12)}-${raw.slice(12, 16)}-${raw.slice(16, 20)}-${raw.slice(20)}`;
70추가: return { name: tok.profile.name, uuid, accessToken: tok.token, userType: 'msa', xuid: '0', online: true };
71추가: }
72추가:
73추가: export function hasMicrosoftCache(profileKey = 'default'): boolean {
74추가: const dir = path.join(DIRS.auth, profileKey);
75추가: return fs.existsSync(dir) && fs.readdirSync(dir).length > 0;
76추가: }
추가harness/cli.ts+68-0
@@ -0,0 +1,68 @@
1추가: // CLI for humans, CI and agents without MCP:
2추가: // npm run mct -- <tool> [key=value ... | '{json}']
3추가: // npm run mct -- scenario scenarios/demo-shop.yaml
4추가: // npm run mct -- login [profile] (Microsoft device-code login, needs a human)
5추가: // npm run mct -- tools | daemon-stop | daemon-status
6추가: import { TOOLS, TOOL_MAP } from './tools.ts';
7추가: import { call, daemonUp, shutdownDaemon } from './rpc.ts';
8추가: import { ensureDirs } from './config.ts';
9추가: import { microsoftIdentity } from './auth.ts';
10추가:
11추가: function parseArgs(rest: string[]): Record<string, unknown> {
12추가: if (rest.length === 1 && rest[0].trim().startsWith('{')) return JSON.parse(rest[0]);
13추가: const out: Record<string, unknown> = {};
14추가: for (const a of rest) {
15추가: const i = a.indexOf('=');
16추가: if (i < 0) throw new Error(`expected key=value, got '${a}'`);
17추가: const k = a.slice(0, i);
18추가: const v = a.slice(i + 1);
19추가: if (v === 'true' || v === 'false') out[k] = v === 'true';
20추가: else if (v !== '' && !Number.isNaN(Number(v)) && /^-?[\d.]+$/.test(v)) out[k] = Number(v);
21추가: else if (v.startsWith('[') || v.startsWith('{')) out[k] = JSON.parse(v);
22추가: else out[k] = v;
23추가: }
24추가: return out;
25추가: }
26추가:
27추가: async function main() {
28추가: const [cmd, ...rest] = process.argv.slice(2);
29추가: if (!cmd || cmd === 'help' || cmd === '--help') {
30추가: console.log('usage: npm run mct -- <tool> [key=value ...]\n npm run mct -- scenario <file.yaml>\n npm run mct -- login [profile]\n npm run mct -- tools | daemon-status | daemon-stop');
31추가: return;
32추가: }
33추가: if (cmd === 'tools') {
34추가: for (const t of TOOLS) console.log(`${t.name.padEnd(18)} ${Object.keys(t.shape).join(', ')}`);
35추가: return;
36추가: }
37추가: if (cmd === 'daemon-status') {
38추가: console.log(JSON.stringify({ running: await daemonUp() }));
39추가: return;
40추가: }
41추가: if (cmd === 'daemon-stop') {
42추가: console.log(JSON.stringify({ stopped: await shutdownDaemon() }));
43추가: return;
44추가: }
45추가: if (cmd === 'login') {
46추가: ensureDirs();
47추가: const profile = rest[0] ?? 'default';
48추가: const id = await microsoftIdentity(profile, (p) => {
49추가: console.log(`\nOpen ${p.verificationUri} and enter the code: ${p.userCode}\n`);
50추가: });
51추가: console.log(JSON.stringify({ loggedIn: true, profile, minecraftName: id.name, uuid: id.uuid }));
52추가: return;
53추가: }
54추가: if (cmd === 'scenario') {
55추가: const r = await call('run_scenario', { file: rest[0], stop_on_fail: true });
56추가: console.log(JSON.stringify(r, null, 2));
57추가: process.exitCode = r.passed ? 0 : 1;
58추가: return;
59추가: }
60추가: if (!TOOL_MAP.has(cmd)) throw new Error(`unknown tool '${cmd}' (npm run mct -- tools)`);
61추가: const r = await call(cmd, parseArgs(rest));
62추가: console.log(JSON.stringify(r, null, 2));
63추가: }
64추가:
65추가: main().catch((e) => {
66추가: console.error(`error: ${(e as Error).message}`);
67추가: process.exitCode = 1;
68추가: });
추가harness/clients.ts+270-0
@@ -0,0 +1,270 @@
1추가: // Launches and talks to real Minecraft clients (each with the QA Bridge mod on its own localhost port).
2추가: import fs from 'node:fs';
3추가: import path from 'node:path';
4추가: import net from 'node:net';
5추가: import { spawn, type ChildProcess } from 'node:child_process';
6추가: import { DIRS, type Config } from './config.ts';
7추가: import { install, plan, redactArgs } from './launcher.ts';
8추가: import { hasMicrosoftCache, microsoftIdentity, offlineIdentity, type Identity } from './auth.ts';
9추가: import { sleep } from './paper.ts';
10추가:
11추가: export interface LaunchOptions {
12추가: account?: 'offline' | 'microsoft';
13추가: /** Microsoft token cache profile (see `mct login`). */
14추가: msProfile?: string;
15추가: /** Server to join on startup; true/undefined = the harness server, false = stay on title screen. */
16추가: connect?: boolean | string;
17추가: display?: 'xvfb' | 'host';
18추가: timeoutMs?: number;
19추가: }
20추가:
21추가: interface ClientProc {
22추가: key: string;
23추가: name: string;
24추가: account: 'offline' | 'microsoft';
25추가: port: number;
26추가: proc: ChildProcess;
27추가: xvfb: ChildProcess | null;
28추가: display: string;
29추가: gameDir: string;
30추가: startedAt: number;
31추가: tail: string[];
32추가: exit: string | null;
33추가: }
34추가:
35추가: export class BridgeError extends Error {
36추가: status: number;
37추가: constructor(message: string, status: number) {
38추가: super(message);
39추가: this.status = status;
40추가: }
41추가: }
42추가:
43추가: function portFree(port: number): Promise<boolean> {
44추가: return new Promise((resolve) => {
45추가: const s = net.createServer();
46추가: s.once('error', () => resolve(false));
47추가: s.listen(port, '127.0.0.1', () => s.close(() => resolve(true)));
48추가: });
49추가: }
50추가:
51추가: export class ClientManager {
52추가: private cfg: Config;
53추가: private clients = new Map<string, ClientProc>();
54추가: private serverAddress: () => string;
55추가: log: (m: string) => void;
56추가:
57추가: constructor(cfg: Config, serverAddress: () => string, log: (m: string) => void = () => {}) {
58추가: this.cfg = cfg;
59추가: this.serverAddress = serverAddress;
60추가: this.log = log;
61추가: }
62추가:
63추가: list() {
64추가: return [...this.clients.values()].map((c) => ({
65추가: name: c.name,
66추가: account: c.account,
67추가: bridgePort: c.port,
68추가: display: c.display,
69추가: pid: c.proc.pid,
70추가: running: c.proc.exitCode === null,
71추가: exit: c.exit,
72추가: uptimeSec: Math.round((Date.now() - c.startedAt) / 1000),
73추가: }));
74추가: }
75추가:
76추가: /** Resolve a client by name; if omitted and exactly one client runs, use it. */
77추가: get(name?: string): ClientProc {
78추가: if (!name) {
79추가: const running = [...this.clients.values()].filter((c) => c.proc.exitCode === null);
80추가: if (running.length === 1) return running[0];
81추가: if (running.length === 0) throw new Error('no client is running (call client_launch first)');
82추가: throw new Error(`several clients are running (${running.map((c) => c.name).join(', ')}); pass client`);
83추가: }
84추가: const c = this.clients.get(name.toLowerCase());
85추가: if (!c) throw new Error(`no client named '${name}'. Running: ${this.list().map((x) => x.name).join(', ') || '(none)'}`);
86추가: if (c.proc.exitCode !== null) throw new Error(`client '${name}' has exited (${c.exit}). Last output:\n${c.tail.slice(-30).join('\n')}`);
87추가: return c;
88추가: }
89추가:
90추가: async call(name: string | undefined, route: string, body: object = {}, timeoutMs = 30_000): Promise<any> {
91추가: const c = this.get(name);
92추가: return this.callPort(c.port, route, body, timeoutMs);
93추가: }
94추가:
95추가: private async callPort(port: number, route: string, body: object, timeoutMs: number): Promise<any> {
96추가: const res = await fetch(`http://127.0.0.1:${port}/${route.replace(/^\//, '')}`, {
97추가: method: 'POST',
98추가: headers: { 'Content-Type': 'application/json' },
99추가: body: JSON.stringify(body),
100추가: signal: AbortSignal.timeout(timeoutMs),
101추가: });
102추가: const json: any = await res.json();
103추가: if (!json.ok) throw new BridgeError(json.error ?? `bridge ${route} failed`, res.status);
104추가: delete json.ok;
105추가: return json;
106추가: }
107추가:
108추가: private async nextPort(): Promise<number> {
109추가: const used = new Set([...this.clients.values()].filter((c) => c.proc.exitCode === null).map((c) => c.port));
110추가: for (let p = this.cfg.client.bridgeBasePort; p < this.cfg.client.bridgeBasePort + 100; p++) {
111추가: if (!used.has(p) && (await portFree(p))) return p;
112추가: }
113추가: throw new Error('no free bridge port');
114추가: }
115추가:
116추가: private async startXvfb(): Promise<{ proc: ChildProcess; display: string }> {
117추가: const { width, height } = this.cfg.client;
118추가: for (let n = 140; n < 240; n++) {
119추가: if (fs.existsSync(`/tmp/.X11-unix/X${n}`) || fs.existsSync(`/tmp/.X${n}-lock`)) continue;
120추가: const proc = spawn('Xvfb', [`:${n}`, '-screen', '0', `${width}x${height}x24`, '-nolisten', 'tcp', '-noreset', '+extension', 'GLX'], {
121추가: stdio: 'ignore',
122추가: });
123추가: const t0 = Date.now();
124추가: while (Date.now() - t0 < 5000) {
125추가: if (fs.existsSync(`/tmp/.X11-unix/X${n}`)) return { proc, display: `:${n}` };
126추가: if (proc.exitCode !== null) break;
127추가: await sleep(100);
128추가: }
129추가: proc.kill();
130추가: }
131추가: throw new Error('could not start Xvfb (is it installed? `sudo apt install xvfb`)');
132추가: }
133추가:
134추가: async launch(name: string, opts: LaunchOptions = {}): Promise<object> {
135추가: const key = name.toLowerCase();
136추가: const existing = this.clients.get(key);
137추가: if (existing && existing.proc.exitCode === null) return { alreadyRunning: true, ...(await this.call(name, 'state')) };
138추가:
139추가: const account = opts.account ?? 'offline';
140추가: let who: Identity;
141추가: if (account === 'microsoft') {
142추가: const profile = opts.msProfile ?? 'default';
143추가: if (!hasMicrosoftCache(profile)) {
144추가: throw new Error(`Microsoft account not logged in for profile '${profile}'. A human must run: npm run mct -- login ${profile}`);
145추가: }
146추가: who = await microsoftIdentity(profile, undefined, false);
147추가: } else {
148추가: if (this.cfg.server.onlineMode && opts.connect !== false && typeof opts.connect !== 'string') {
149추가: throw new Error('server is online-mode: offline test players cannot join. Use account "microsoft" or set server.onlineMode=false');
150추가: }
151추가: who = offlineIdentity(name);
152추가: }
153추가:
154추가: this.log(`client ${who.name}: preparing install`);
155추가: const inst = await install(this.cfg, this.log);
156추가: const port = await this.nextPort();
157추가: const gameDir = path.join(DIRS.clients, who.name);
158추가: const connect = opts.connect === false ? null : typeof opts.connect === 'string' ? opts.connect : this.serverAddress();
159추가: const lp = await plan(this.cfg, inst, who, { gameDir, bridgePort: port, connect });
160추가:
161추가: const displayMode = opts.display ?? this.cfg.client.display;
162추가: let xvfb: ChildProcess | null = null;
163추가: const env: NodeJS.ProcessEnv = { ...process.env, QA_BRIDGE_PORT: String(port) };
164추가: let display = 'host';
165추가: if (displayMode === 'xvfb') {
166추가: const x = await this.startXvfb();
167추가: xvfb = x.proc;
168추가: display = x.display;
169추가: env.DISPLAY = x.display;
170추가: delete env.WAYLAND_DISPLAY;
171추가: env.SDL_VIDEODRIVER = 'x11';
172추가: env.__GLX_VENDOR_LIBRARY_NAME = 'mesa';
173추가: env.LIBGL_ALWAYS_SOFTWARE = '1';
174추가: }
175추가:
176추가: const outFile = path.join(gameDir, 'mct-client.log');
177추가: fs.writeFileSync(outFile, `# ${new Date().toISOString()} java ${redactArgs(lp.args).join(' ')}\n`);
178추가: const proc = spawn(lp.command, lp.args, { cwd: lp.cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
179추가: const c: ClientProc = {
180추가: key,
181추가: name: who.name,
182추가: account,
183추가: port,
184추가: proc,
185추가: xvfb,
186추가: display,
187추가: gameDir,
188추가: startedAt: Date.now(),
189추가: tail: [],
190추가: exit: null,
191추가: };
192추가: this.clients.set(key, c);
193추가: const out = fs.createWriteStream(outFile, { flags: 'a' });
194추가: const onData = (d: Buffer) => {
195추가: out.write(d);
196추가: for (const line of d.toString('utf8').split('\n')) if (line.trim()) c.tail.push(line);
197추가: if (c.tail.length > 400) c.tail.splice(0, c.tail.length - 400);
198추가: };
199추가: proc.stdout!.on('data', onData);
200추가: proc.stderr!.on('data', onData);
201추가: proc.on('exit', (code, sig) => {
202추가: c.exit = `code=${code} signal=${sig}`;
203추가: out.end();
204추가: xvfb?.kill();
205추가: });
206추가:
207추가: const timeout = opts.timeoutMs ?? 240_000;
208추가: const t0 = Date.now();
209추가: this.log(`client ${who.name}: starting (bridge :${port}, display ${display})`);
210추가: // 1) wait for the bridge HTTP server (mod initialised)
211추가: for (;;) {
212추가: if (proc.exitCode !== null) throw new Error(`client exited during startup (${c.exit}). Log: ${outFile}\n${c.tail.slice(-40).join('\n')}`);
213추가: if (Date.now() - t0 > timeout) throw new Error(`client bridge not up after ${timeout}ms. Log: ${outFile}`);
214추가: try {
215추가: await this.callPort(port, 'health', {}, 2000);
216추가: break;
217추가: } catch {
218추가: await sleep(500);
219추가: }
220추가: }
221추가: // 2) optionally wait until we are in the world
222추가: let state: any = await this.callPort(port, 'state', {}, 10_000);
223추가: if (connect) {
224추가: for (;;) {
225추가: if (proc.exitCode !== null) throw new Error(`client exited while connecting (${c.exit}). Log: ${outFile}`);
226추가: state = await this.callPort(port, 'state', {}, 10_000);
227추가: if (state.inWorld && !state.screen?.open) break;
228추가: if (state.inWorld && state.screen?.class && !/Loading|Receiving|Connect/i.test(state.screen.class)) break;
229추가: if (state.screen?.class === 'DisconnectedScreen') {
230추가: const scr = await this.callPort(port, 'screen', {}, 10_000);
231추가: throw new Error(`client was disconnected while joining ${connect}: ${JSON.stringify(scr.widgets?.map((w: any) => w.label))}`);
232추가: }
233추가: if (Date.now() - t0 > timeout) throw new Error(`client not in world after ${timeout}ms (screen: ${state.screen?.class})`);
234추가: await sleep(500);
235추가: }
236추가: }
237추가: return { launched: who.name, account, bridgePort: port, display, seconds: (Date.now() - t0) / 1000, connectedTo: connect, state };
238추가: }
239추가:
240추가: async stop(name: string | undefined): Promise<object> {
241추가: const c = this.get(name);
242추가: try {
243추가: await this.callPort(c.port, 'quit', {}, 3000);
244추가: } catch {
245추가: /* ignore */
246추가: }
247추가: const t0 = Date.now();
248추가: while (c.proc.exitCode === null && Date.now() - t0 < 20_000) await sleep(200);
249추가: if (c.proc.exitCode === null) c.proc.kill('SIGKILL');
250추가: c.xvfb?.kill();
251추가: this.clients.delete(c.key);
252추가: return { stopped: c.name };
253추가: }
254추가:
255추가: async stopAll(): Promise<void> {
256추가: for (const c of [...this.clients.values()]) {
257추가: if (c.proc.exitCode === null) await this.stop(c.name).catch(() => c.proc.kill('SIGKILL'));
258추가: c.xvfb?.kill();
259추가: }
260추가: this.clients.clear();
261추가: }
262추가:
263추가: running(): string[] {
264추가: return [...this.clients.values()].filter((c) => c.proc.exitCode === null).map((c) => c.name);
265추가: }
266추가:
267추가: artifactsDir(): string {
268추가: return DIRS.artifacts;
269추가: }
270추가: }
추가harness/config.ts+166-0
@@ -0,0 +1,166 @@
1추가: // Loads mct.config.json (optional) and resolves every runtime path under .mct/.
2추가: import fs from 'node:fs';
3추가: import path from 'node:path';
4추가: import crypto from 'node:crypto';
5추가:
6추가: export const ROOT = path.resolve(import.meta.dirname, '..');
7추가:
8추가: export interface Config {
9추가: mcVersion: string;
10추가: fabricLoader: string;
11추가: fabricApi: string;
12추가: daemonPort: number;
13추가: server: {
14추가: paperBuild: 'latest' | number;
15추가: port: number;
16추가: rconPort: number;
17추가: memory: string;
18추가: /** false = offline mode on 127.0.0.1 (many test players). true = real auth (Microsoft account clients only). */
19추가: onlineMode: boolean;
20추가: /** Plugin jars to copy into plugins/ on every start. Globs relative to the repo root (only * in the file name). */
21추가: plugins: string[];
22추가: /** Extra server.properties overrides. */
23추가: properties: Record<string, string | number | boolean>;
24추가: /** Commands run over RCON right after every start (gamerules etc.). */
25추가: onStart: string[];
26추가: /** What a world snapshot captures, relative to the server dir. `dir/*` = every subdirectory. */
27추가: snapshotInclude: string[];
28추가: };
29추가: client: {
30추가: memory: string;
31추가: /** "xvfb" = invisible virtual display per client, "host" = open a window on your desktop. */
32추가: display: 'xvfb' | 'host';
33추가: width: number;
34추가: height: number;
35추가: guiScale: number;
36추가: /** Auto-accept server resource packs (no confirmation screen blocking automated joins). */
37추가: acceptServerResourcePacks: boolean;
38추가: /** Suppress toast popups (recipe unlocked, chat warnings) so they don't cover screenshots. */
39추가: hideToasts: boolean;
40추가: /** Client UI language, e.g. ko_kr / en_us. */
41추가: lang: string;
42추가: bridgeBasePort: number;
43추가: /** Extra mod jars (globs relative to repo root) to load in every client, e.g. a client-side resource helper. */
44추가: extraMods: string[];
45추가: };
46추가: }
47추가:
48추가: const DEFAULTS: Config = {
49추가: mcVersion: '26.3',
50추가: fabricLoader: '0.20.1',
51추가: fabricApi: '0.166.2+26.3',
52추가: daemonPort: 7770,
53추가: server: {
54추가: paperBuild: 'latest',
55추가: port: 25565,
56추가: rconPort: 25575,
57추가: memory: '4G',
58추가: onlineMode: false,
59추가: plugins: ['fixtures/demo-shop/build/libs/demo-shop-*.jar'],
60추가: properties: {},
61추가: onStart: [
62추가: 'gamerule advance_time false',
63추가: 'gamerule advance_weather false',
64추가: 'gamerule spawn_mobs false',
65추가: 'time set day',
66추가: 'weather clear',
67추가: ],
68추가: snapshotInclude: ['world', 'world_nether', 'world_the_end', 'plugins/*'],
69추가: },
70추가: client: {
71추가: memory: '3G',
72추가: display: 'xvfb',
73추가: width: 1280,
74추가: height: 720,
75추가: guiScale: 2,
76추가: lang: 'ko_kr',
77추가: hideToasts: true,
78추가: acceptServerResourcePacks: true,
79추가: bridgeBasePort: 7800,
80추가: extraMods: [],
81추가: },
82추가: };
83추가:
84추가: function merge<T>(base: T, over: unknown): T {
85추가: if (over === undefined || over === null) return base;
86추가: if (typeof base !== 'object' || Array.isArray(base) || base === null) return over as T;
87추가: const out: Record<string, unknown> = { ...(base as Record<string, unknown>) };
88추가: for (const [k, v] of Object.entries(over as Record<string, unknown>)) {
89추가: out[k] = merge((base as Record<string, unknown>)[k], v);
90추가: }
91추가: return out as T;
92추가: }
93추가:
94추가: export function configPath(): string {
95추가: return process.env.MCT_CONFIG ?? path.join(ROOT, 'mct.config.json');
96추가: }
97추가:
98추가: /** Read mct.config.json as the user wrote it (only their overrides, no defaults). */
99추가: export function readUserConfig(): Record<string, any> {
100추가: const file = configPath();
101추가: return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
102추가: }
103추가:
104추가: /** Apply a change to mct.config.json, keeping everything else the user wrote. */
105추가: export function updateUserConfig(change: (c: Record<string, any>) => void): string {
106추가: const file = configPath();
107추가: const c = readUserConfig();
108추가: change(c);
109추가: const tmp = file + '.tmp';
110추가: fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + '\n');
111추가: fs.renameSync(tmp, file);
112추가: return file;
113추가: }
114추가:
115추가: export function loadConfig(): Config {
116추가: const file = configPath();
117추가: let user: unknown = {};
118추가: if (fs.existsSync(file)) user = JSON.parse(fs.readFileSync(file, 'utf8'));
119추가: const cfg = merge(DEFAULTS, user);
120추가: if (process.env.MCT_DISPLAY === 'host' || process.env.MCT_DISPLAY === 'xvfb') cfg.client.display = process.env.MCT_DISPLAY;
121추가: return cfg;
122추가: }
123추가:
124추가: export const DIRS = {
125추가: root: path.join(ROOT, '.mct'),
126추가: cache: path.join(ROOT, '.mct', 'cache'),
127추가: server: path.join(ROOT, '.mct', 'server'),
128추가: snapshots: path.join(ROOT, '.mct', 'snapshots'),
129추가: clients: path.join(ROOT, '.mct', 'clients'),
130추가: artifacts: path.join(ROOT, '.mct', 'artifacts'),
131추가: reports: path.join(ROOT, '.mct', 'reports'),
132추가: auth: path.join(ROOT, '.mct', 'auth'),
133추가: run: path.join(ROOT, '.mct', 'run'),
134추가: };
135추가:
136추가: export function ensureDirs(): void {
137추가: for (const d of Object.values(DIRS)) fs.mkdirSync(d, { recursive: true });
138추가: }
139추가:
140추가: /** Local secrets (RCON password). Never printed by the harness. */
141추가: export function secrets(): { rconPassword: string } {
142추가: const file = path.join(DIRS.root, 'secrets.json');
143추가: if (fs.existsSync(file)) return JSON.parse(fs.readFileSync(file, 'utf8'));
144추가: const s = { rconPassword: crypto.randomBytes(18).toString('base64url') };
145추가: fs.mkdirSync(DIRS.root, { recursive: true });
146추가: fs.writeFileSync(file, JSON.stringify(s, null, 2), { mode: 0o600 });
147추가: return s;
148추가: }
149추가:
150추가: /** Expand `dir/name-*.jar` style globs (wildcards only in the last path segment). */
151추가: export function expandGlob(pattern: string, base = ROOT): string[] {
152추가: const abs = path.isAbsolute(pattern) ? pattern : path.join(base, pattern);
153추가: const dir = path.dirname(abs);
154추가: const name = path.basename(abs);
155추가: if (!name.includes('*')) return fs.existsSync(abs) ? [abs] : [];
156추가: if (!fs.existsSync(dir)) return [];
157추가: const re = new RegExp('^' + name.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$');
158추가: return fs
159추가: .readdirSync(dir)
160추가: .filter((f) => re.test(f) && !/-(sources|javadoc|dev)\.jar$/.test(f))
161추가: .map((f) => path.join(dir, f));
162추가: }
163추가:
164추가: export function stamp(): string {
165추가: return new Date().toISOString().replace(/[:.]/g, '-');
166추가: }
추가harness/daemon.ts+101-0
@@ -0,0 +1,101 @@
1추가: // Long-lived harness daemon: owns the Paper server and all clients so several agents / MCP sessions
2추가: // can share them. JSON RPC over http://127.0.0.1:<daemonPort>.
3추가: import http from 'node:http';
4추가: import fs from 'node:fs';
5추가: import path from 'node:path';
6추가: import { z } from 'zod';
7추가: import { DIRS, ensureDirs, loadConfig } from './config.ts';
8추가: import { PaperServer } from './paper.ts';
9추가: import { ClientManager } from './clients.ts';
10추가: import { TOOLS, TOOL_MAP, type Ctx } from './tools.ts';
11추가: import { runScenario } from './scenario.ts';
12추가:
13추가: ensureDirs();
14추가: const cfg = loadConfig();
15추가: const logFile = fs.createWriteStream(path.join(DIRS.run, 'daemon.log'), { flags: 'a' });
16추가: const log = (m: string) => {
17추가: const line = `${new Date().toISOString()} ${m}\n`;
18추가: logFile.write(line);
19추가: process.stderr.write(line);
20추가: };
21추가:
22추가: const server = new PaperServer(cfg);
23추가: const clients = new ClientManager(cfg, () => server.status().address, log);
24추가: const ctx: Ctx = {
25추가: server,
26추가: clients,
27추가: marks: new Map(),
28추가: runScenario: (file, opts) => runScenario(ctx, file, opts),
29추가: };
30추가:
31추가: function readBody(req: http.IncomingMessage): Promise<string> {
32추가: return new Promise((resolve, reject) => {
33추가: const chunks: Buffer[] = [];
34추가: req.on('data', (c) => chunks.push(c));
35추가: req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
36추가: req.on('error', reject);
37추가: });
38추가: }
39추가:
40추가: function send(res: http.ServerResponse, status: number, body: unknown) {
41추가: const s = JSON.stringify(body);
42추가: res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
43추가: res.end(s);
44추가: }
45추가:
46추가: let shuttingDown = false;
47추가: async function shutdown(code = 0) {
48추가: if (shuttingDown) return;
49추가: shuttingDown = true;
50추가: log('shutting down: stopping clients and server');
51추가: httpServer.close(); // stop accepting new requests right away
52추가: await clients.stopAll().catch((e) => log(`stopAll: ${e}`));
53추가: await server.stop().catch((e) => log(`server stop: ${e}`));
54추가: fs.rmSync(path.join(DIRS.run, 'daemon.json'), { force: true });
55추가: process.exit(code);
56추가: }
57추가:
58추가: const httpServer = http.createServer(async (req, res) => {
59추가: try {
60추가: const url = new URL(req.url ?? '/', 'http://localhost');
61추가: if (shuttingDown) return send(res, 503, { ok: false, error: 'daemon is shutting down' });
62추가: if (url.pathname === '/health') return send(res, 200, { ok: true, pid: process.pid });
63추가: if (url.pathname === '/tools') return send(res, 200, { ok: true, tools: TOOLS.map((t) => ({ name: t.name, description: t.description })) });
64추가: if (url.pathname === '/shutdown' && req.method === 'POST') {
65추가: send(res, 200, { ok: true });
66추가: setTimeout(() => void shutdown(0), 50);
67추가: return;
68추가: }
69추가: if (url.pathname !== '/rpc' || req.method !== 'POST') return send(res, 404, { ok: false, error: 'POST /rpc {tool, params}' });
70추가: const { tool, params } = JSON.parse((await readBody(req)) || '{}');
71추가: const t = TOOL_MAP.get(tool);
72추가: if (!t) return send(res, 400, { ok: false, error: `unknown tool '${tool}'` });
73추가: const parsed = z.object(t.shape).strict().safeParse(params ?? {});
74추가: if (!parsed.success) return send(res, 400, { ok: false, error: `invalid params for ${tool}: ${parsed.error.message}` });
75추가: const t0 = Date.now();
76추가: try {
77추가: const result = await t.run(ctx, parsed.data);
78추가: log(`${tool} ok ${Date.now() - t0}ms`);
79추가: send(res, 200, { ok: true, result });
80추가: } catch (e) {
81추가: log(`${tool} FAILED ${Date.now() - t0}ms: ${(e as Error).message.split('\n')[0]}`);
82추가: send(res, 200, { ok: false, error: (e as Error).message });
83추가: }
84추가: } catch (e) {
85추가: send(res, 500, { ok: false, error: (e as Error).stack ?? String(e) });
86추가: }
87추가: });
88추가: httpServer.requestTimeout = 0;
89추가: httpServer.headersTimeout = 0;
90추가:
91추가: httpServer.listen(cfg.daemonPort, '127.0.0.1', () => {
92추가: fs.writeFileSync(path.join(DIRS.run, 'daemon.json'), JSON.stringify({ pid: process.pid, port: cfg.daemonPort }));
93추가: log(`mc-tester daemon listening on 127.0.0.1:${cfg.daemonPort} (client display: ${cfg.client.display})`);
94추가: });
95추가: httpServer.on('error', (e) => {
96추가: log(`daemon failed to listen: ${e.message}`);
97추가: process.exit(1);
98추가: });
99추가:
100추가: process.on('SIGINT', () => void shutdown(0));
101추가: process.on('SIGTERM', () => void shutdown(0));
추가harness/download.ts+64-0
@@ -0,0 +1,64 @@
1추가: // Small download helper: hash-verified, cached, with bounded concurrency.
2추가: import fs from 'node:fs';
3추가: import path from 'node:path';
4추가: import crypto from 'node:crypto';
5추가:
6추가: export async function fetchJson<T = any>(url: string): Promise<T> {
7추가: const res = await fetch(url, { headers: { 'User-Agent': 'mc-tester/0.1' } });
8추가: if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`);
9추가: return (await res.json()) as T;
10추가: }
11추가:
12추가: function hashFile(file: string, algo: 'sha1' | 'sha256'): string {
13추가: return crypto.createHash(algo).update(fs.readFileSync(file)).digest('hex');
14추가: }
15추가:
16추가: export interface DownloadSpec {
17추가: url: string;
18추가: dest: string;
19추가: sha1?: string;
20추가: sha256?: string;
21추가: }
22추가:
23추가: export async function download(spec: DownloadSpec): Promise<string> {
24추가: const { url, dest } = spec;
25추가: const algo = spec.sha256 ? 'sha256' : spec.sha1 ? 'sha1' : null;
26추가: const want = spec.sha256 ?? spec.sha1;
27추가: if (fs.existsSync(dest)) {
28추가: if (!algo || hashFile(dest, algo) === want) return dest;
29추가: }
30추가: fs.mkdirSync(path.dirname(dest), { recursive: true });
31추가: let lastErr: unknown;
32추가: for (let attempt = 1; attempt <= 3; attempt++) {
33추가: try {
34추가: const res = await fetch(url, { headers: { 'User-Agent': 'mc-tester/0.1' } });
35추가: if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`);
36추가: const buf = Buffer.from(await res.arrayBuffer());
37추가: if (algo) {
38추가: const got = crypto.createHash(algo).update(buf).digest('hex');
39추가: if (got !== want) throw new Error(`hash mismatch for ${url}: ${got} != ${want}`);
40추가: }
41추가: const tmp = dest + '.part';
42추가: fs.writeFileSync(tmp, buf);
43추가: fs.renameSync(tmp, dest);
44추가: return dest;
45추가: } catch (e) {
46추가: lastErr = e;
47추가: }
48추가: }
49추가: throw lastErr;
50추가: }
51추가:
52추가: export async function downloadAll(specs: DownloadSpec[], concurrency = 16, onProgress?: (done: number, total: number) => void): Promise<void> {
53추가: let i = 0;
54추가: let done = 0;
55추가: const worker = async () => {
56추가: while (i < specs.length) {
57추가: const s = specs[i++];
58추가: await download(s);
59추가: done++;
60추가: if (onProgress && (done % 200 === 0 || done === specs.length)) onProgress(done, specs.length);
61추가: }
62추가: };
63추가: await Promise.all(Array.from({ length: Math.min(concurrency, specs.length) }, worker));
64추가: }
추가harness/launcher.ts+289-0
@@ -0,0 +1,289 @@
1추가: // Minimal Minecraft + Fabric launcher: resolves 26.x version metadata, downloads (cached, hash-verified)
2추가: // client jar / libraries / assets / Fabric loader, and builds the java command line for one client.
3추가: import fs from 'node:fs';
4추가: import path from 'node:path';
5추가: import os from 'node:os';
6추가: import { DIRS, ROOT, expandGlob, type Config } from './config.ts';
7추가: import { download, downloadAll, fetchJson, type DownloadSpec } from './download.ts';
8추가: import type { Identity } from './auth.ts';
9추가:
10추가: const MANIFEST = 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json';
11추가: const OS_NAME = process.platform === 'darwin' ? 'osx' : process.platform === 'win32' ? 'windows' : 'linux';
12추가: const ARCH = os.arch() === 'x64' ? 'x86_64' : os.arch();
13추가:
14추가: interface Rule {
15추가: action: 'allow' | 'disallow';
16추가: os?: { name?: string; arch?: string };
17추가: features?: Record<string, boolean>;
18추가: }
19추가:
20추가: function rulesAllow(rules: Rule[] | undefined, features: Record<string, boolean> = {}): boolean {
21추가: if (!rules || rules.length === 0) return true;
22추가: let allowed = false;
23추가: for (const r of rules) {
24추가: let match = true;
25추가: if (r.os?.name && r.os.name !== OS_NAME) match = false;
26추가: if (r.os?.arch && r.os.arch !== (ARCH === 'x86_64' ? 'x86_64' : ARCH)) match = false;
27추가: if (r.features) for (const [k, v] of Object.entries(r.features)) if ((features[k] ?? false) !== v) match = false;
28추가: if (match) allowed = r.action === 'allow';
29추가: }
30추가: return allowed;
31추가: }
32추가:
33추가: function mavenPath(coord: string): string {
34추가: const [group, artifact, version, classifier] = coord.split(':');
35추가: const file = `${artifact}-${version}${classifier ? '-' + classifier : ''}.jar`;
36추가: return [...group.split('.'), artifact, version, file].join('/');
37추가: }
38추가:
39추가: function libKey(coord: string): string {
40추가: const [g, a, , c] = coord.split(':');
41추가: return `${g}:${a}${c ? ':' + c : ''}`;
42추가: }
43추가:
44추가: export interface Installation {
45추가: version: any;
46추가: fabric: any;
47추가: classpath: string[];
48추가: clientJar: string;
49추가: assetsDir: string;
50추가: assetIndex: string;
51추가: logConfig: string | null;
52추가: mods: string[];
53추가: }
54추가:
55추가: let cached: Promise<Installation> | null = null;
56추가:
57추가: /** Download/verify everything needed to run the client. Safe to call repeatedly (cached per process). */
58추가: export function install(cfg: Config, log: (m: string) => void = () => {}): Promise<Installation> {
59추가: if (!cached) cached = doInstall(cfg, log).catch((e) => {
60추가: cached = null;
61추가: throw e;
62추가: });
63추가: return cached;
64추가: }
65추가:
66추가: async function doInstall(cfg: Config, log: (m: string) => void): Promise<Installation> {
67추가: const v = cfg.mcVersion;
68추가: const vdir = path.join(DIRS.cache, 'versions', v);
69추가: const vjsonPath = path.join(vdir, `${v}.json`);
70추가: let version: any;
71추가: if (fs.existsSync(vjsonPath)) {
72추가: version = JSON.parse(fs.readFileSync(vjsonPath, 'utf8'));
73추가: } else {
74추가: const manifest = await fetchJson(MANIFEST);
75추가: const entry = manifest.versions.find((x: any) => x.id === v);
76추가: if (!entry) throw new Error(`Minecraft version ${v} not in Mojang manifest`);
77추가: await download({ url: entry.url, dest: vjsonPath, sha1: entry.sha1 });
78추가: version = JSON.parse(fs.readFileSync(vjsonPath, 'utf8'));
79추가: }
80추가:
81추가: const clientJar = path.join(vdir, `${v}.jar`);
82추가: await download({ url: version.downloads.client.url, dest: clientJar, sha1: version.downloads.client.sha1 });
83추가:
84추가: // Fabric loader profile (26.x is unobfuscated: no intermediary needed).
85추가: const fabricPath = path.join(DIRS.cache, 'fabric', `${v}-${cfg.fabricLoader}.json`);
86추가: if (!fs.existsSync(fabricPath)) {
87추가: const prof = await fetchJson(`https://meta.fabricmc.net/v2/versions/loader/${v}/${cfg.fabricLoader}/profile/json`);
88추가: fs.mkdirSync(path.dirname(fabricPath), { recursive: true });
89추가: fs.writeFileSync(fabricPath, JSON.stringify(prof, null, 2));
90추가: }
91추가: const fabric = JSON.parse(fs.readFileSync(fabricPath, 'utf8'));
92추가:
93추가: const libDir = path.join(DIRS.cache, 'libraries');
94추가: const specs: DownloadSpec[] = [];
95추가: const cp = new Map<string, string>();
96추가: for (const lib of version.libraries) {
97추가: if (!rulesAllow(lib.rules)) continue;
98추가: const a = lib.downloads?.artifact;
99추가: if (!a) continue;
100추가: const dest = path.join(libDir, a.path);
101추가: specs.push({ url: a.url, dest, sha1: a.sha1 });
102추가: cp.set(libKey(lib.name), dest);
103추가: }
104추가: for (const lib of fabric.libraries) {
105추가: const rel = mavenPath(lib.name);
106추가: const dest = path.join(libDir, rel);
107추가: const base = (lib.url as string).endsWith('/') ? lib.url : lib.url + '/';
108추가: specs.push({ url: base + rel, dest, sha1: lib.sha1 });
109추가: cp.set(libKey(lib.name), dest); // Fabric's versions win over vanilla duplicates (e.g. ASM)
110추가: }
111추가: log(`libraries: ${specs.length}`);
112추가: await downloadAll(specs, 16);
113추가:
114추가: // Assets
115추가: const assetsDir = path.join(DIRS.cache, 'assets');
116추가: const ai = version.assetIndex;
117추가: const indexPath = path.join(assetsDir, 'indexes', `${ai.id}.json`);
118추가: await download({ url: ai.url, dest: indexPath, sha1: ai.sha1 });
119추가: const index = JSON.parse(fs.readFileSync(indexPath, 'utf8'));
120추가: const assetSpecs: DownloadSpec[] = Object.values<any>(index.objects).map((o) => ({
121추가: url: `https://resources.download.minecraft.net/${o.hash.slice(0, 2)}/${o.hash}`,
122추가: dest: path.join(assetsDir, 'objects', o.hash.slice(0, 2), o.hash),
123추가: sha1: o.hash,
124추가: }));
125추가: const missing = assetSpecs.filter((s) => !fs.existsSync(s.dest));
126추가: if (missing.length) {
127추가: log(`assets: downloading ${missing.length} objects`);
128추가: await downloadAll(missing, 32, (d, t) => log(`assets ${d}/${t}`));
129추가: }
130추가:
131추가: let logConfig: string | null = null;
132추가: const lc = version.logging?.client?.file;
133추가: if (lc) {
134추가: logConfig = path.join(assetsDir, 'log_configs', lc.id);
135추가: await download({ url: lc.url, dest: logConfig, sha1: lc.sha1 });
136추가: }
137추가:
138추가: // Mods: QA Bridge + Fabric API + user extras
139추가: const mods: string[] = [];
140추가: const bridge = expandGlob('qa-bridge/build/libs/qa-bridge-*.jar');
141추가: if (bridge.length === 0) throw new Error('qa-bridge jar not built: run `npm run build:mods` (or ./gradlew build in qa-bridge/)');
142추가: mods.push(bridge.sort().at(-1)!);
143추가: const fa = cfg.fabricApi;
144추가: const faUrl = `https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api/${encodeURIComponent(fa)}/fabric-api-${encodeURIComponent(fa)}.jar`;
145추가: const faSha1 = (await (await fetch(faUrl + '.sha1')).text()).trim().slice(0, 40);
146추가: const faDest = path.join(DIRS.cache, 'mods', `fabric-api-${fa}.jar`);
147추가: await download({ url: faUrl, dest: faDest, sha1: faSha1 });
148추가: mods.push(faDest);
149추가: for (const g of cfg.client.extraMods) mods.push(...expandGlob(g));
150추가:
151추가: return {
152추가: version,
153추가: fabric,
154추가: classpath: [...cp.values(), clientJar],
155추가: clientJar,
156추가: assetsDir,
157추가: assetIndex: ai.id,
158추가: logConfig,
159추가: mods,
160추가: };
161추가: }
162추가:
163추가: export interface LaunchPlan {
164추가: command: string;
165추가: args: string[];
166추가: cwd: string;
167추가: gameDir: string;
168추가: }
169추가:
170추가: function writeOptions(gameDir: string, cfg: Config): void {
171추가: const file = path.join(gameDir, 'options.txt');
172추가: const existing = new Map<string, string>();
173추가: if (fs.existsSync(file)) {
174추가: for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
175추가: const i = line.indexOf(':');
176추가: if (i > 0) existing.set(line.slice(0, i), line.slice(i + 1));
177추가: }
178추가: }
179추가: const forced: Record<string, string> = {
180추가: onboardAccessibility: 'false',
181추가: skipMultiplayerWarning: 'true',
182추가: joinedFirstServer: 'true',
183추가: tutorialStep: 'none',
184추가: pauseOnLostFocus: 'false',
185추가: guiScale: String(cfg.client.guiScale),
186추가: renderDistance: '6',
187추가: simulationDistance: '5',
188추가: maxFps: '30',
189추가: inactivityFpsLimit: '"afk"',
190추가: enableVsync: 'false',
191추가: narrator: '0',
192추가: narratorHotkey: 'false',
193추가: realmsNotifications: 'false',
194추가: telemetryOptInExtra: 'false',
195추가: fullscreen: 'false',
196추가: soundCategory_master: '0.0',
197추가: musicToast: '"never"',
198추가: lang: cfg.client.lang,
199추가: chatLinksPrompt: 'false',
200추가: autoJump: 'false',
201추가: startedCleanly: 'true',
202추가: hideSplashTexts: 'true',
203추가: darkMojangStudiosBackground: 'true',
204추가: };
205추가: for (const [k, val] of Object.entries(forced)) existing.set(k, val);
206추가: fs.writeFileSync(file, [...existing].map(([k, val]) => `${k}:${val}`).join('\n') + '\n');
207추가: }
208추가:
209추가: function syncMods(gameDir: string, mods: string[]): void {
210추가: const dir = path.join(gameDir, 'mods');
211추가: fs.mkdirSync(dir, { recursive: true });
212추가: for (const f of fs.readdirSync(dir)) if (f.endsWith('.jar')) fs.rmSync(path.join(dir, f));
213추가: for (const m of mods) fs.copyFileSync(m, path.join(dir, path.basename(m)));
214추가: }
215추가:
216추가: export async function plan(
217추가: cfg: Config,
218추가: inst: Installation,
219추가: who: Identity,
220추가: opts: { gameDir: string; bridgePort: number; connect?: string | null },
221추가: ): Promise<LaunchPlan> {
222추가: const { gameDir } = opts;
223추가: fs.mkdirSync(gameDir, { recursive: true });
224추가: writeOptions(gameDir, cfg);
225추가: syncMods(gameDir, inst.mods);
226추가: const natives = path.join(gameDir, 'natives');
227추가: for (const sub of ['java', 'jna', 'lwjgl', 'netty']) fs.mkdirSync(path.join(natives, sub), { recursive: true });
228추가:
229추가: const features: Record<string, boolean> = {
230추가: has_custom_resolution: true,
231추가: is_quick_play_multiplayer: !!opts.connect,
232추가: };
233추가: const vars: Record<string, string> = {
234추가: natives_directory: natives,
235추가: launcher_name: 'mc-tester',
236추가: launcher_version: '0.1.0',
237추가: classpath: inst.classpath.join(path.delimiter),
238추가: classpath_separator: path.delimiter,
239추가: library_directory: path.join(DIRS.cache, 'libraries'),
240추가: auth_player_name: who.name,
241추가: version_name: cfg.mcVersion,
242추가: game_directory: gameDir,
243추가: assets_root: inst.assetsDir,
244추가: assets_index_name: inst.assetIndex,
245추가: auth_uuid: who.uuid,
246추가: auth_access_token: who.accessToken,
247추가: clientid: '0',
248추가: auth_xuid: who.xuid,
249추가: user_type: who.userType,
250추가: version_type: 'release',
251추가: resolution_width: String(cfg.client.width),
252추가: resolution_height: String(cfg.client.height),
253추가: quickPlayMultiplayer: opts.connect ?? '',
254추가: };
255추가: const sub = (s: string) => s.replace(/\$\{([^}]+)\}/g, (_, k) => vars[k] ?? '');
256추가: const expand = (list: any[]): string[] => {
257추가: const out: string[] = [];
258추가: for (const a of list) {
259추가: if (typeof a === 'string') out.push(sub(a));
260추가: else if (rulesAllow(a.rules, features)) out.push(...(Array.isArray(a.value) ? a.value : [a.value]).map(sub));
261추가: }
262추가: return out;
263추가: };
264추가:
265추가: const jvm = [
266추가: `-Xms1G`,
267추가: `-Xmx${cfg.client.memory}`,
268추가: '-XX:+UseZGC',
269추가: ...expand(inst.version.arguments.jvm),
270추가: ...(inst.fabric.arguments?.jvm ?? []),
271추가: `-Dqabridge.port=${opts.bridgePort}`,
272추가: `-Dqabridge.hideToasts=${cfg.client.hideToasts}`,
273추가: `-Dqabridge.acceptServerPacks=${cfg.client.acceptServerResourcePacks}`,
274추가: ];
275추가: if (inst.logConfig) jvm.push(sub(inst.version.logging.client.argument.replace('${path}', inst.logConfig)));
276추가: // quickPlayPath is feature-gated; we never enable it.
277추가: const game = expand(inst.version.arguments.game).filter((a) => a !== '--quickPlayPath');
278추가: const args = [...jvm, inst.fabric.mainClass, ...game];
279추가: return { command: 'java', args, cwd: gameDir, gameDir };
280추가: }
281추가:
282추가: export function redactArgs(args: string[]): string[] {
283추가: const out = [...args];
284추가: const i = out.indexOf('--accessToken');
285추가: if (i >= 0 && i + 1 < out.length) out[i + 1] = '<redacted>';
286추가: return out;
287추가: }
288추가:
289추가: export { ROOT };
추가harness/mcp.ts+42-0
@@ -0,0 +1,42 @@
1추가: // MCP stdio server for QA agents. Thin proxy: every tool call goes to the shared daemon
2추가: // (auto-started), screenshots come back as image content.
3추가: import fs from 'node:fs';
4추가: import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5추가: import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6추가: import { TOOLS } from './tools.ts';
7추가: import { call } from './rpc.ts';
8추가:
9추가: const INSTRUCTIONS = `mc-tester drives REAL Minecraft 26.3 clients against a local Paper test server running the plugin under test.
10추가: Plugins under test: plugins_list shows which jars load; plugins_set (add/remove, restart:true) changes them and saves mct.config.json.
11추가: Typical loop: server_start -> client_launch {name:"Bot1"} -> rcon (give items / set state) -> teleport next to an NPC -> interact_entity -> screen (read the GUI as JSON) -> click_item / click_slot -> wait_for {chat: ...} -> verify with rcon (server truth) and state/screen (client view) -> screenshot when visual proof helps.
12추가: - Prefer server-side verification (rcon + the plugin's admin/debug commands) for balances and inventories; the client view can lag.
13추가: - Every action tool accepts screenshot:true to get an image of the result.
14추가: - world_snapshot once ("base"), then world_reset "base" before tests that must be deterministic.
15추가: - Turn reproducible checks into YAML scenarios under scenarios/ and run them with run_scenario.`;
16추가:
17추가: const server = new McpServer({ name: 'mc-tester', version: '0.1.0' }, { instructions: INSTRUCTIONS });
18추가:
19추가: function imageFor(p: unknown) {
20추가: if (typeof p !== 'string' || !p.endsWith('.png') || !fs.existsSync(p)) return null;
21추가: return { type: 'image' as const, data: fs.readFileSync(p).toString('base64'), mimeType: 'image/png' };
22추가: }
23추가:
24추가: for (const t of TOOLS) {
25추가: server.registerTool(t.name, { description: t.description, inputSchema: t.shape }, async (args: any) => {
26추가: try {
27추가: const result = await call(t.name, args ?? {});
28추가: const content: any[] = [{ type: 'text', text: JSON.stringify(result, null, 2) }];
29추가: const imgs = [result?.screenshot, t.name === 'screenshot' ? result?.path : null];
30추가: if (Array.isArray(result?.screenshots)) imgs.push(...result.screenshots.slice(-4));
31추가: for (const p of imgs) {
32추가: const img = imageFor(p);
33추가: if (img) content.push(img);
34추가: }
35추가: return { content };
36추가: } catch (e) {
37추가: return { isError: true, content: [{ type: 'text', text: (e as Error).message }] };
38추가: }
39추가: });
40추가: }
41추가:
42추가: await server.connect(new StdioServerTransport());
추가harness/paper.ts+317-0
@@ -0,0 +1,317 @@
1추가: // Paper test server: download, configure, start/stop, logs, RCON, world snapshots.
2추가: import fs from 'node:fs';
3추가: import path from 'node:path';
4추가: import { spawn, type ChildProcess } from 'node:child_process';
5추가: import { DIRS, secrets, type Config } from './config.ts';
6추가: import { resolvePlugins } from './plugins.ts';
7추가: import { download, fetchJson } from './download.ts';
8추가: import { Rcon } from './rcon.ts';
9추가:
10추가: export interface LogLine {
11추가: seq: number;
12추가: time: number;
13추가: text: string;
14추가: }
15추가:
16추가: const ERROR_RE = /(\bERROR\]|Exception|Caused by:|\bat [\w.$]+\([\w.]+:\d+\))/;
17추가:
18추가: export class PaperServer {
19추가: private cfg: Config;
20추가: private proc: ChildProcess | null = null;
21추가: private rcon: Rcon | null = null;
22추가: private lines: LogLine[] = [];
23추가: private seq = 0;
24추가: private ready = false;
25추가: private exitInfo: string | null = null;
26추가:
27추가: constructor(cfg: Config) {
28추가: this.cfg = cfg;
29추가: }
30추가:
31추가: get dir(): string {
32추가: return DIRS.server;
33추가: }
34추가:
35추가: /** Live config shared with the daemon (plugins_set edits server.plugins in place). */
36추가: get config(): Config {
37추가: return this.cfg;
38추가: }
39추가:
40추가: get running(): boolean {
41추가: return this.proc !== null && this.proc.exitCode === null;
42추가: }
43추가:
44추가: status() {
45추가: return {
46추가: running: this.running,
47추가: ready: this.ready,
48추가: pid: this.proc?.pid ?? null,
49추가: address: `127.0.0.1:${this.cfg.server.port}`,
50추가: onlineMode: this.cfg.server.onlineMode,
51추가: logSeq: this.seq,
52추가: lastExit: this.exitInfo,
53추가: plugins: this.installedPlugins(),
54추가: };
55추가: }
56추가:
57추가: private installedPlugins(): string[] {
58추가: const p = path.join(this.dir, 'plugins');
59추가: if (!fs.existsSync(p)) return [];
60추가: return fs.readdirSync(p).filter((f) => f.endsWith('.jar'));
61추가: }
62추가:
63추가: async ensureJar(): Promise<string> {
64추가: const v = this.cfg.mcVersion;
65추가: const builds = await fetchJson<any[]>(`https://fill.papermc.io/v3/projects/paper/versions/${v}/builds`);
66추가: const want = this.cfg.server.paperBuild;
67추가: const build = want === 'latest' ? builds.find((b) => b.channel === 'STABLE') ?? builds[0] : builds.find((b) => b.id === want);
68추가: if (!build) throw new Error(`Paper build ${want} for ${v} not found`);
69추가: const dl = build.downloads['server:default'];
70추가: const dest = path.join(DIRS.cache, 'paper', dl.name);
71추가: await download({ url: dl.url, dest, sha256: dl.checksums?.sha256 });
72추가: return dest;
73추가: }
74추가:
75추가: private writeConfig(): void {
76추가: const s = this.cfg.server;
77추가: fs.mkdirSync(this.dir, { recursive: true });
78추가: // The user accepted the Minecraft EULA (https://aka.ms/MinecraftEULA) when setting up this harness.
79추가: fs.writeFileSync(path.join(this.dir, 'eula.txt'), 'eula=true\n');
80추가: const propsFile = path.join(this.dir, 'server.properties');
81추가: const props: Record<string, string> = {};
82추가: if (fs.existsSync(propsFile)) {
83추가: for (const line of fs.readFileSync(propsFile, 'utf8').split('\n')) {
84추가: const m = line.match(/^([^#=]+)=(.*)$/);
85추가: if (m) props[m[1].trim()] = m[2];
86추가: }
87추가: }
88추가: const forced: Record<string, string | number | boolean> = {
89추가: 'server-ip': '127.0.0.1',
90추가: 'server-port': s.port,
91추가: 'online-mode': s.onlineMode,
92추가: 'enforce-secure-profile': s.onlineMode,
93추가: 'enable-rcon': true,
94추가: 'rcon.port': s.rconPort,
95추가: 'rcon.password': secrets().rconPassword,
96추가: 'broadcast-rcon-to-ops': false,
97추가: 'level-seed': 'mc-tester',
98추가: 'level-type': 'minecraft\\:flat',
99추가: 'generator-settings': JSON.stringify({
100추가: layers: [
101추가: { block: 'minecraft:bedrock', height: 1 },
102추가: { block: 'minecraft:dirt', height: 2 },
103추가: { block: 'minecraft:grass_block', height: 1 },
104추가: ],
105추가: biome: 'minecraft:plains',
106추가: }).replace(/:/g, '\\:'),
107추가: 'spawn-protection': 0,
108추가: 'view-distance': 6,
109추가: 'simulation-distance': 6,
110추가: 'allow-flight': true,
111추가: 'difficulty': 'peaceful',
112추가: 'gamemode': 'survival',
113추가: 'motd': 'mc-tester QA server',
114추가: 'max-players': 50,
115추가: 'white-list': false,
116추가: 'enforce-whitelist': false,
117추가: 'sync-chunk-writes': false,
118추가: ...s.properties,
119추가: };
120추가: // Drop keys that came from a previous `server.properties` override but are no longer configured,
121추가: // so removing an override really reverts it (Paper re-adds the default on start).
122추가: const overridesFile = path.join(this.dir, '.mct-properties.json');
123추가: const previousOverrides: string[] = fs.existsSync(overridesFile) ? JSON.parse(fs.readFileSync(overridesFile, 'utf8')) : [];
124추가: for (const k of previousOverrides) if (!(k in s.properties)) delete props[k];
125추가: fs.writeFileSync(overridesFile, JSON.stringify(Object.keys(s.properties)));
126추가: for (const [k, v] of Object.entries(forced)) props[k] = String(v);
127추가: fs.writeFileSync(propsFile, Object.entries(props).map(([k, v]) => `${k}=${v}`).join('\n') + '\n');
128추가: }
129추가:
130추가: /** Copy the resolved plugin jars (one per plugin, newest build) into plugins/, removing what we copied last time. */
131추가: private syncPlugins(): { copied: string[]; skipped: { file: string; reason: string }[] } {
132추가: const res = resolvePlugins(this.cfg.server.plugins);
133추가: if (res.unmatched.length) {
134추가: throw new Error(`plugin pattern(s) matched no jar: ${res.unmatched.join(', ')} (build the plugin first, or fix the path with plugins_set)`);
135추가: }
136추가: const pdir = path.join(this.dir, 'plugins');
137추가: fs.mkdirSync(pdir, { recursive: true });
138추가: const manifest = path.join(this.dir, '.mct-plugins.json');
139추가: const previous: string[] = fs.existsSync(manifest) ? JSON.parse(fs.readFileSync(manifest, 'utf8')) : [];
140추가: for (const f of previous) fs.rmSync(path.join(pdir, f), { force: true });
141추가: const copied: string[] = [];
142추가: for (const j of res.selected) {
143추가: const name = path.basename(j.file);
144추가: fs.copyFileSync(j.file, path.join(pdir, name));
145추가: copied.push(name);
146추가: }
147추가: fs.writeFileSync(manifest, JSON.stringify(copied));
148추가: return { copied, skipped: res.skipped.map((j) => ({ file: j.file, reason: j.reason })) };
149추가: }
150추가:
151추가: private push(text: string): void {
152추가: this.lines.push({ seq: ++this.seq, time: Date.now(), text });
153추가: if (this.lines.length > 20000) this.lines.splice(0, this.lines.length - 20000);
154추가: }
155추가:
156추가: async start(timeoutMs = 180_000): Promise<object> {
157추가: if (this.running) return { alreadyRunning: true, ...this.status() };
158추가: const jar = await this.ensureJar();
159추가: this.writeConfig();
160추가: const plugins = this.syncPlugins();
161추가: this.ready = false;
162추가: this.exitInfo = null;
163추가: const mem = this.cfg.server.memory;
164추가: const proc = spawn('java', [`-Xms${mem}`, `-Xmx${mem}`, '-Dterminal.jline=false', '-Dterminal.ansi=false', '-jar', jar, '--nogui'], {
165추가: cwd: this.dir,
166추가: stdio: ['pipe', 'pipe', 'pipe'],
167추가: env: { ...process.env, TERM: 'dumb' },
168추가: });
169추가: this.proc = proc;
170추가: const startSeq = this.seq;
171추가: let partial = '';
172추가: const onChunk = (d: Buffer) => {
173추가: partial += d.toString('utf8');
174추가: const parts = partial.split('\n');
175추가: partial = parts.pop() ?? '';
176추가: for (const raw of parts) {
177추가: // Strip ANSI and the console prompt redraw ("> \r \r") that JLine interleaves.
178추가: const line = (raw.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').split('\r').filter((x) => x.trim()).pop() ?? '').replace(/^> /, '');
179추가: this.push(line);
180추가: if (/Done \([\d.,]+s\)! For help/.test(line)) this.ready = true;
181추가: }
182추가: };
183추가: proc.stdout!.on('data', onChunk);
184추가: proc.stderr!.on('data', onChunk);
185추가: proc.on('exit', (code, sig) => {
186추가: this.exitInfo = `exited code=${code} signal=${sig}`;
187추가: this.push(`[mc-tester] server ${this.exitInfo}`);
188추가: this.ready = false;
189추가: this.rcon?.close();
190추가: this.rcon = null;
191추가: });
192추가: const t0 = Date.now();
193추가: while (!this.ready) {
194추가: if (!this.running) throw new Error(`server exited during startup (${this.exitInfo}). Last log:\n${this.tail(40, startSeq)}`);
195추가: if (Date.now() - t0 > timeoutMs) throw new Error(`server not ready after ${timeoutMs}ms. Last log:\n${this.tail(40, startSeq)}`);
196추가: await sleep(250);
197추가: }
198추가: const onStart: Record<string, string> = {};
199추가: for (const c of this.cfg.server.onStart) onStart[c] = await this.command(c);
200추가: return { ...this.status(), started: true, seconds: (Date.now() - t0) / 1000, copiedPlugins: plugins.copied, skippedJars: plugins.skipped, onStart };
201추가: }
202추가:
203추가: async stop(timeoutMs = 60_000): Promise<object> {
204추가: if (!this.running) return { running: false };
205추가: const proc = this.proc!;
206추가: try {
207추가: await this.command('stop', 5000);
208추가: } catch {
209추가: proc.stdin?.write('stop\n');
210추가: }
211추가: const t0 = Date.now();
212추가: while (proc.exitCode === null && Date.now() - t0 < timeoutMs) await sleep(200);
213추가: if (proc.exitCode === null) proc.kill('SIGKILL');
214추가: return { stopped: true, seconds: (Date.now() - t0) / 1000 };
215추가: }
216추가:
217추가: async command(cmd: string, timeoutMs = 15_000): Promise<string> {
218추가: if (!this.running) throw new Error('server is not running (call server_start)');
219추가: const c = cmd.replace(/^\//, '');
220추가: for (let attempt = 1; ; attempt++) {
221추가: if (!this.rcon || !this.rcon.connected) {
222추가: this.rcon = new Rcon('127.0.0.1', this.cfg.server.rconPort, secrets().rconPassword);
223추가: }
224추가: try {
225추가: return await this.rcon.command(c, timeoutMs);
226추가: } catch (e) {
227추가: // The server drops idle RCON sockets; reconnect once and retry.
228추가: const msg = (e as Error).message;
229추가: if (attempt >= 2 || !/closed|ECONNRESET|EPIPE|ECONNREFUSED/.test(msg) || !this.running) throw e;
230추가: this.rcon?.close();
231추가: this.rcon = null;
232추가: }
233추가: }
234추가: }
235추가:
236추가: log(since = 0, grep?: string, limit = 200): { next: number; lines: LogLine[] } {
237추가: let out = this.lines.filter((l) => l.seq > since);
238추가: if (grep) {
239추가: const re = new RegExp(grep, 'i');
240추가: out = out.filter((l) => re.test(l.text));
241추가: }
242추가: return { next: this.seq, lines: out.slice(-limit) };
243추가: }
244추가:
245추가: errors(since: number): LogLine[] {
246추가: return this.lines.filter((l) => l.seq > since && ERROR_RE.test(l.text));
247추가: }
248추가:
249추가: get logSeq(): number {
250추가: return this.seq;
251추가: }
252추가:
253추가: tail(n: number, since = 0): string {
254추가: return this.lines.filter((l) => l.seq > since).slice(-n).map((l) => l.text).join('\n');
255추가: }
256추가:
257추가: // ---------------------------------------------------------------- snapshots
258추가:
259추가: private snapshotEntries(): string[] {
260추가: const out: string[] = [];
261추가: for (const inc of this.cfg.server.snapshotInclude) {
262추가: if (inc.endsWith('/*')) {
263추가: const base = inc.slice(0, -2);
264추가: const abs = path.join(this.dir, base);
265추가: if (!fs.existsSync(abs)) continue;
266추가: for (const e of fs.readdirSync(abs, { withFileTypes: true })) if (e.isDirectory()) out.push(path.join(base, e.name));
267추가: } else if (fs.existsSync(path.join(this.dir, inc))) {
268추가: out.push(inc);
269추가: }
270추가: }
271추가: return out;
272추가: }
273추가:
274추가: async snapshot(name: string): Promise<object> {
275추가: if (!/^[\w.-]+$/.test(name)) throw new Error('snapshot name must be [A-Za-z0-9_.-]');
276추가: const wasRunning = this.running;
277추가: if (wasRunning) {
278추가: await this.command('save-off');
279추가: await this.command('save-all flush', 60_000);
280추가: }
281추가: try {
282추가: const dest = path.join(DIRS.snapshots, name);
283추가: fs.rmSync(dest, { recursive: true, force: true });
284추가: const entries = this.snapshotEntries();
285추가: for (const e of entries) {
286추가: fs.cpSync(path.join(this.dir, e), path.join(dest, e), { recursive: true, filter: (src) => !src.endsWith('session.lock') });
287추가: }
288추가: fs.writeFileSync(path.join(dest, '.mct-snapshot.json'), JSON.stringify({ entries, created: new Date().toISOString() }));
289추가: return { snapshot: name, entries };
290추가: } finally {
291추가: if (wasRunning) await this.command('save-on');
292추가: }
293추가: }
294추가:
295추가: listSnapshots(): string[] {
296추가: if (!fs.existsSync(DIRS.snapshots)) return [];
297추가: return fs.readdirSync(DIRS.snapshots).filter((d) => fs.existsSync(path.join(DIRS.snapshots, d, '.mct-snapshot.json')));
298추가: }
299추가:
300추가: /** Stop -> replace snapshot paths -> start. Caller reconnects clients. */
301추가: async restore(name: string): Promise<object> {
302추가: const src = path.join(DIRS.snapshots, name);
303추가: const metaFile = path.join(src, '.mct-snapshot.json');
304추가: if (!fs.existsSync(metaFile)) throw new Error(`no snapshot '${name}'. Existing: ${this.listSnapshots().join(', ') || '(none)'}`);
305추가: const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8')) as { entries: string[] };
306추가: const wasRunning = this.running;
307추가: if (wasRunning) await this.stop();
308추가: for (const e of this.snapshotEntries()) fs.rmSync(path.join(this.dir, e), { recursive: true, force: true });
309추가: for (const e of meta.entries) fs.cpSync(path.join(src, e), path.join(this.dir, e), { recursive: true });
310추가: const started = wasRunning ? await this.start() : null;
311추가: return { restored: name, entries: meta.entries, restarted: wasRunning, started };
312추가: }
313추가: }
314추가:
315추가: export function sleep(ms: number): Promise<void> {
316추가: return new Promise((r) => setTimeout(r, ms));
317추가: }
추가harness/plugins.ts+121-0
@@ -0,0 +1,121 @@
1추가: // Resolve configured plugin jar patterns to the exact jars to install.
2추가: // Each jar's plugin.yml / paper-plugin.yml is read so that several builds of the SAME plugin
3추가: // (old versions left in build/libs, shadow "-all" + plain jar) collapse to the newest one,
4추가: // while a pattern like "../libs/*.jar" can still bring in many different plugins.
5추가: import fs from 'node:fs';
6추가: import path from 'node:path';
7추가: import zlib from 'node:zlib';
8추가: import YAML from 'yaml';
9추가: import { expandGlob } from './config.ts';
10추가:
11추가: /** Read one entry from a zip/jar without dependencies. Returns null if missing or unreadable. */
12추가: export function readZipEntry(file: string, wanted: string): Buffer | null {
13추가: let buf: Buffer;
14추가: try {
15추가: buf = fs.readFileSync(file);
16추가: } catch {
17추가: return null;
18추가: }
19추가: // End of central directory: signature 0x06054b50, within the last 64KB + 22 bytes.
20추가: let eocd = -1;
21추가: for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65_557); i--) {
22추가: if (buf.readUInt32LE(i) === 0x06054b50) {
23추가: eocd = i;
24추가: break;
25추가: }
26추가: }
27추가: if (eocd < 0) return null;
28추가: const count = buf.readUInt16LE(eocd + 10);
29추가: let p = buf.readUInt32LE(eocd + 16);
30추가: for (let n = 0; n < count && p + 46 <= buf.length; n++) {
31추가: if (buf.readUInt32LE(p) !== 0x02014b50) return null;
32추가: const method = buf.readUInt16LE(p + 10);
33추가: const csize = buf.readUInt32LE(p + 20);
34추가: const nameLen = buf.readUInt16LE(p + 28);
35추가: const extraLen = buf.readUInt16LE(p + 30);
36추가: const commentLen = buf.readUInt16LE(p + 32);
37추가: const local = buf.readUInt32LE(p + 42);
38추가: const name = buf.subarray(p + 46, p + 46 + nameLen).toString('utf8');
39추가: if (name === wanted) {
40추가: const lNameLen = buf.readUInt16LE(local + 26);
41추가: const lExtraLen = buf.readUInt16LE(local + 28);
42추가: const start = local + 30 + lNameLen + lExtraLen;
43추가: const data = buf.subarray(start, start + csize);
44추가: try {
45추가: if (method === 0) return Buffer.from(data);
46추가: if (method === 8) return zlib.inflateRawSync(data);
47추가: } catch {
48추가: return null;
49추가: }
50추가: return null;
51추가: }
52추가: p += 46 + nameLen + extraLen + commentLen;
53추가: }
54추가: return null;
55추가: }
56추가:
57추가: export interface PluginJar {
58추가: file: string;
59추가: pattern: string;
60추가: /** Plugin name from the descriptor, or the file name when the jar has none. */
61추가: plugin: string;
62추가: version: string | null;
63추가: descriptor: 'paper-plugin.yml' | 'plugin.yml' | null;
64추가: mtime: string;
65추가: }
66추가:
67추가: export function describeJar(file: string, pattern = file): PluginJar {
68추가: let plugin = path.basename(file);
69추가: let version: string | null = null;
70추가: let descriptor: PluginJar['descriptor'] = null;
71추가: for (const d of ['paper-plugin.yml', 'plugin.yml'] as const) {
72추가: const raw = readZipEntry(file, d);
73추가: if (!raw) continue;
74추가: try {
75추가: const y = YAML.parse(raw.toString('utf8'));
76추가: if (y?.name) {
77추가: plugin = String(y.name);
78추가: version = y.version !== undefined ? String(y.version) : null;
79추가: descriptor = d;
80추가: break;
81추가: }
82추가: } catch {
83추가: /* fall through */
84추가: }
85추가: }
86추가: return { file, pattern, plugin, version, descriptor, mtime: fs.statSync(file).mtime.toISOString() };
87추가: }
88추가:
89추가: export interface Resolution {
90추가: /** Jars that will be installed: one per plugin, the most recently built. */
91추가: selected: PluginJar[];
92추가: /** Other jars of an already-selected plugin (older builds, duplicates). */
93추가: skipped: (PluginJar & { reason: string })[];
94추가: /** Patterns that matched no file. */
95추가: unmatched: string[];
96추가: }
97추가:
98추가: export function resolvePlugins(patterns: string[]): Resolution {
99추가: const all: PluginJar[] = [];
100추가: const unmatched: string[] = [];
101추가: for (const pattern of patterns) {
102추가: const files = expandGlob(pattern);
103추가: if (files.length === 0) unmatched.push(pattern);
104추가: for (const f of files) if (!all.some((j) => j.file === f)) all.push(describeJar(f, pattern));
105추가: }
106추가: const byPlugin = new Map<string, PluginJar[]>();
107추가: for (const j of all) {
108추가: const key = j.plugin.toLowerCase();
109추가: byPlugin.set(key, [...(byPlugin.get(key) ?? []), j]);
110추가: }
111추가: const selected: PluginJar[] = [];
112추가: const skipped: Resolution['skipped'] = [];
113추가: for (const group of byPlugin.values()) {
114추가: group.sort((a, b) => b.mtime.localeCompare(a.mtime));
115추가: selected.push(group[0]);
116추가: for (const j of group.slice(1)) {
117추가: skipped.push({ ...j, reason: `older build of plugin '${group[0].plugin}' (using ${path.basename(group[0].file)})` });
118추가: }
119추가: }
120추가: return { selected, skipped, unmatched };
121추가: }
추가harness/rcon.ts+118-0
@@ -0,0 +1,118 @@
1추가: // Minimal Source RCON client (what Minecraft servers speak on rcon.port).
2추가: import net from 'node:net';
3추가:
4추가: const AUTH = 3;
5추가: const EXEC = 2;
6추가:
7추가: export class Rcon {
8추가: private sock: net.Socket | null = null;
9추가: private buf = Buffer.alloc(0);
10추가: private nextId = 1;
11추가: private pending = new Map<number, { resolve: (s: string) => void; reject: (e: Error) => void; parts: string[]; sentinel?: number }>();
12추가: private host: string;
13추가: private port: number;
14추가: private password: string;
15추가:
16추가: constructor(host: string, port: number, password: string) {
17추가: this.host = host;
18추가: this.port = port;
19추가: this.password = password;
20추가: }
21추가:
22추가: get connected(): boolean {
23추가: return this.sock !== null && !this.sock.destroyed;
24추가: }
25추가:
26추가: async connect(): Promise<void> {
27추가: if (this.connected) return;
28추가: await new Promise<void>((resolve, reject) => {
29추가: const s = net.createConnection({ host: this.host, port: this.port }, () => resolve());
30추가: s.once('error', reject);
31추가: s.on('data', (d) => this.onData(d as Buffer));
32추가: s.on('close', () => {
33추가: this.sock = null;
34추가: for (const p of this.pending.values()) p.reject(new Error('RCON connection closed'));
35추가: this.pending.clear();
36추가: });
37추가: this.sock = s;
38추가: });
39추가: const id = this.nextId++;
40추가: const res = new Promise<string>((resolve, reject) => this.pending.set(id, { resolve, reject, parts: [] }));
41추가: this.write(id, AUTH, this.password);
42추가: await res;
43추가: }
44추가:
45추가: private write(id: number, type: number, body: string): void {
46추가: const payload = Buffer.from(body, 'utf8');
47추가: const pkt = Buffer.alloc(14 + payload.length);
48추가: pkt.writeInt32LE(10 + payload.length, 0);
49추가: pkt.writeInt32LE(id, 4);
50추가: pkt.writeInt32LE(type, 8);
51추가: payload.copy(pkt, 12);
52추가: pkt.writeInt16LE(0, 12 + payload.length);
53추가: this.sock!.write(pkt);
54추가: }
55추가:
56추가: private onData(d: Buffer): void {
57추가: this.buf = Buffer.concat([this.buf, d]);
58추가: while (this.buf.length >= 4) {
59추가: const len = this.buf.readInt32LE(0);
60추가: if (this.buf.length < 4 + len) return;
61추가: const id = this.buf.readInt32LE(4);
62추가: const type = this.buf.readInt32LE(8);
63추가: const body = this.buf.subarray(12, 4 + len - 2).toString('utf8');
64추가: this.buf = this.buf.subarray(4 + len);
65추가: if (id === -1) {
66추가: for (const p of this.pending.values()) p.reject(new Error('RCON authentication failed'));
67추가: this.pending.clear();
68추가: continue;
69추가: }
70추가: // Fragmented responses: we send a sentinel (id+1 empty) after each command; collect until it echoes.
71추가: const sentinelFor = this.pending.get(id - 1);
72추가: if (sentinelFor && sentinelFor.sentinel === id) {
73추가: this.pending.delete(id - 1);
74추가: sentinelFor.resolve(sentinelFor.parts.join(''));
75추가: continue;
76추가: }
77추가: const p = this.pending.get(id);
78추가: if (!p) continue;
79추가: if (p.sentinel) {
80추가: p.parts.push(body);
81추가: } else {
82추가: void type;
83추가: this.pending.delete(id);
84추가: p.resolve(body);
85추가: }
86추가: }
87추가: }
88추가:
89추가: async command(cmd: string, timeoutMs = 15000): Promise<string> {
90추가: await this.connect();
91추가: const id = this.nextId;
92추가: this.nextId += 2;
93추가: const res = new Promise<string>((resolve, reject) => {
94추가: const entry = { resolve, reject, parts: [] as string[], sentinel: id + 1 };
95추가: this.pending.set(id, entry);
96추가: setTimeout(() => {
97추가: if (this.pending.get(id) === entry) {
98추가: this.pending.delete(id);
99추가: reject(new Error(`RCON command timed out: ${cmd}`));
100추가: }
101추가: }, timeoutMs);
102추가: });
103추가: this.write(id, EXEC, cmd);
104추가: // An invalid packet type makes the server answer "Unknown request" with the same id, after the real reply.
105추가: this.write(id + 1, 200, '');
106추가: const raw = await res;
107추가: return stripFormatting(raw).trim();
108추가: }
109추가:
110추가: close(): void {
111추가: this.sock?.destroy();
112추가: this.sock = null;
113추가: }
114추가: }
115추가:
116추가: export function stripFormatting(s: string): string {
117추가: return s.replace(/§[0-9a-fk-orx]/gi, '');
118추가: }
추가harness/rpc.ts+89-0
@@ -0,0 +1,89 @@
1추가: // Client side of the daemon RPC, with auto-start of the daemon.
2추가: import http from 'node:http';
3추가: import fs from 'node:fs';
4추가: import path from 'node:path';
5추가: import { spawn } from 'node:child_process';
6추가: import { DIRS, ROOT, ensureDirs, loadConfig } from './config.ts';
7추가:
8추가: const cfg = loadConfig();
9추가:
10추가: function request(method: string, route: string, body?: unknown): Promise<any> {
11추가: return new Promise((resolve, reject) => {
12추가: const data = body === undefined ? undefined : Buffer.from(JSON.stringify(body));
13추가: const req = http.request(
14추가: { host: '127.0.0.1', port: cfg.daemonPort, path: route, method, headers: data ? { 'Content-Type': 'application/json', 'Content-Length': data.length } : {} },
15추가: (res) => {
16추가: const chunks: Buffer[] = [];
17추가: res.on('data', (c) => chunks.push(c));
18추가: res.on('end', () => {
19추가: try {
20추가: resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
21추가: } catch (e) {
22추가: reject(e);
23추가: }
24추가: });
25추가: },
26추가: );
27추가: req.on('error', reject);
28추가: if (data) req.write(data);
29추가: req.end();
30추가: });
31추가: }
32추가:
33추가: export async function daemonUp(): Promise<boolean> {
34추가: try {
35추가: const r = await request('GET', '/health');
36추가: return !!r.ok;
37추가: } catch {
38추가: return false;
39추가: }
40추가: }
41추가:
42추가: export async function ensureDaemon(): Promise<void> {
43추가: if (await daemonUp()) return;
44추가: ensureDirs();
45추가: const out = fs.openSync(path.join(DIRS.run, 'daemon.out'), 'a');
46추가: const child = spawn(process.execPath, [path.join(ROOT, 'harness', 'daemon.ts')], {
47추가: cwd: ROOT,
48추가: detached: true,
49추가: stdio: ['ignore', out, out],
50추가: env: process.env,
51추가: });
52추가: child.unref();
53추가: const t0 = Date.now();
54추가: while (Date.now() - t0 < 15_000) {
55추가: if (await daemonUp()) return;
56추가: await new Promise((r) => setTimeout(r, 200));
57추가: }
58추가: throw new Error(`daemon did not start; see ${path.join(DIRS.run, 'daemon.out')}`);
59추가: }
60추가:
61추가: export async function call(tool: string, params: object = {}): Promise<any> {
62추가: await ensureDaemon();
63추가: const r = await request('POST', '/rpc', { tool, params });
64추가: if (!r.ok) throw new Error(r.error);
65추가: return r.result;
66추가: }
67추가:
68추가: /** Ask the daemon to stop clients + server and exit; waits until the process is gone. */
69추가: export async function shutdownDaemon(timeoutMs = 90_000): Promise<boolean> {
70추가: let pid: number | null = null;
71추가: try {
72추가: const h = await request('GET', '/health');
73추가: if (!h.ok) return false;
74추가: pid = h.pid;
75추가: } catch {
76추가: return false;
77추가: }
78추가: await request('POST', '/shutdown', {});
79추가: const t0 = Date.now();
80추가: while (Date.now() - t0 < timeoutMs) {
81추가: try {
82추가: process.kill(pid!, 0);
83추가: } catch {
84추가: return true; // process gone
85추가: }
86추가: await new Promise((r) => setTimeout(r, 300));
87추가: }
88추가: throw new Error(`daemon pid ${pid} still running after ${timeoutMs}ms`);
89추가: }
추가harness/scenario.ts+220-0
@@ -0,0 +1,220 @@
1추가: // YAML scenario runner: ordered tool calls + assertions, with failure screenshots and a JSON report.
2추가: import fs from 'node:fs';
3추가: import path from 'node:path';
4추가: import YAML from 'yaml';
5추가: import { DIRS, ROOT, stamp } from './config.ts';
6추가: import { TOOL_MAP, type Ctx } from './tools.ts';
7추가: import { sleep } from './paper.ts';
8추가:
9추가: /** For `- tool: "string"` shorthand: which parameter the string fills. */
10추가: const DEFAULT_ARG: Record<string, string> = {
11추가: rcon: 'command',
12추가: chat: 'text',
13추가: type_text: 'text',
14추가: key: 'key',
15추가: screenshot: 'label',
16추가: world_reset: 'name',
17추가: world_snapshot: 'name',
18추가: client_launch: 'name',
19추가: client_stop: 'client',
20추가: expect_rcon: 'command',
21추가: expect_chat: 'chat',
22추가: run_scenario: 'file',
23추가: };
24추가:
25추가: interface StepResult {
26추가: phase: string;
27추가: index: number;
28추가: label?: string;
29추가: tool: string;
30추가: args: any;
31추가: ok: boolean;
32추가: ms: number;
33추가: result?: any;
34추가: error?: string;
35추가: skipped?: boolean;
36추가: }
37추가:
38추가: function short(v: any, max = 1500): any {
39추가: const s = JSON.stringify(v);
40추가: if (s === undefined || s.length <= max) return v;
41추가: return s.slice(0, max) + `... (${s.length} chars)`;
42추가: }
43추가:
44추가: function parseStep(raw: any): { tool: string; args: any; label?: string } {
45추가: if (typeof raw === 'string') return { tool: raw, args: {} };
46추가: const keys = Object.keys(raw).filter((k) => k !== 'label');
47추가: if (keys.length !== 1) throw new Error(`a step must have exactly one tool key (plus optional label): ${JSON.stringify(raw)}`);
48추가: const tool = keys[0];
49추가: let args = raw[tool];
50추가: if (args === null || args === undefined) args = {};
51추가: else if (typeof args !== 'object') {
52추가: if (tool === 'sleep') args = { ms: Number(args) };
53추가: else if (DEFAULT_ARG[tool]) args = { [DEFAULT_ARG[tool]]: args };
54추가: else throw new Error(`step '${tool}' needs an object of arguments`);
55추가: }
56추가: return { tool, args, label: raw.label };
57추가: }
58추가:
59추가: function itemMatches(item: any, q: any): boolean {
60추가: if (!item) return false;
61추가: if (q.id && item.id !== q.id && item.id !== `minecraft:${q.id}`) return false;
62추가: if (q.name && !String(item.name).includes(q.name)) return false;
63추가: if (q.lore && !(item.lore ?? []).concat(item.tooltip ?? []).some((l: string) => l.includes(q.lore))) return false;
64추가: return true;
65추가: }
66추가:
67추가: function compareCount(actual: number, q: any): boolean {
68추가: if (q.count !== undefined && actual !== q.count) return false;
69추가: if (q.min !== undefined && actual < q.min) return false;
70추가: if (q.max !== undefined && actual > q.max) return false;
71추가: return true;
72추가: }
73추가:
74추가: export async function runScenario(ctx: Ctx, file: string, opts: { stopOnFail?: boolean } = {}): Promise<object> {
75추가: const abs = path.isAbsolute(file) ? file : path.join(ROOT, file);
76추가: const doc = YAML.parse(fs.readFileSync(abs, 'utf8')) ?? {};
77추가: const name = doc.name ?? path.basename(abs);
78추가: const stopOnFail = opts.stopOnFail ?? true;
79추가: const startSeq = ctx.server.running ? ctx.server.logSeq : 0;
80추가: const results: StepResult[] = [];
81추가: const screenshots: string[] = [];
82추가: const t0 = Date.now();
83추가: let failed = false;
84추가:
85추가: const asserts: Record<string, (a: any) => Promise<any>> = {
86추가: sleep: async (a) => {
87추가: await sleep(a.ms ?? 500);
88추가: return { slept: a.ms ?? 500 };
89추가: },
90추가: expect_rcon: async (a) => {
91추가: const out: string = await ctx.server.command(a.command);
92추가: if (a.contains !== undefined && !out.includes(a.contains)) throw new Error(`rcon output does not contain ${JSON.stringify(a.contains)}: ${out}`);
93추가: if (a.not_contains !== undefined && out.includes(a.not_contains)) throw new Error(`rcon output contains ${JSON.stringify(a.not_contains)}: ${out}`);
94추가: if (a.matches !== undefined && !new RegExp(a.matches).test(out)) throw new Error(`rcon output does not match /${a.matches}/: ${out}`);
95추가: if (a.json !== undefined) {
96추가: const m = out.match(/\{.*\}/s);
97추가: if (!m) throw new Error(`rcon output has no JSON object: ${out}`);
98추가: const obj = JSON.parse(m[0]);
99추가: for (const [k, v] of Object.entries(a.json)) {
100추가: if (JSON.stringify(obj[k]) !== JSON.stringify(v)) throw new Error(`json.${k} = ${JSON.stringify(obj[k])}, expected ${JSON.stringify(v)} (full: ${m[0]})`);
101추가: }
102추가: }
103추가: return { output: out };
104추가: },
105추가: expect_chat: async (a) => TOOL_MAP.get('wait_for')!.run(ctx, { client: a.client, chat: a.chat, since: a.since, timeout_ms: a.timeout_ms ?? 5000 }),
106추가: expect_screen: async (a) => {
107추가: const scr = await ctx.clients.call(a.client, 'screen');
108추가: if (a.closed === true) {
109추가: if (scr.open) throw new Error(`expected no screen, but ${scr.class} "${scr.title}" is open`);
110추가: return { closed: true };
111추가: }
112추가: if (!scr.open) throw new Error('expected a screen to be open, but none is');
113추가: if (a.title !== undefined && !new RegExp(a.title).test(scr.title)) throw new Error(`screen title "${scr.title}" does not match /${a.title}/`);
114추가: if (a.has_item) {
115추가: const q = a.has_item;
116추가: const area = q.area ?? 'container';
117추가: const hits = (scr.slots ?? []).filter((s: any) => (area === 'any' || s.area === area) && itemMatches(s.item, q));
118추가: if (hits.length === 0) throw new Error(`no ${area} slot with ${JSON.stringify(q)}`);
119추가: if (q.slot !== undefined && !hits.some((h: any) => h.slot === q.slot)) throw new Error(`item found but not in slot ${q.slot}: ${hits.map((h: any) => h.slot)}`);
120추가: }
121추가: if (a.carried !== undefined) {
122추가: if (a.carried === null && scr.carried) throw new Error(`expected empty cursor, carrying ${JSON.stringify(scr.carried)}`);
123추가: if (a.carried && !itemMatches(scr.carried, a.carried)) throw new Error(`cursor item ${JSON.stringify(scr.carried)} != ${JSON.stringify(a.carried)}`);
124추가: }
125추가: return { title: scr.title, class: scr.class };
126추가: },
127추가: expect_inventory: async (a) => {
128추가: const st = await ctx.clients.call(a.client, 'state');
129추가: const total = (st.player?.inventory ?? [])
130추가: .filter((e: any) => itemMatches(e.item, a))
131추가: .reduce((n: number, e: any) => n + e.item.count, 0);
132추가: if (!compareCount(total, a)) throw new Error(`inventory has ${total} of ${JSON.stringify({ id: a.id, name: a.name })}, expected ${JSON.stringify({ count: a.count, min: a.min, max: a.max })}`);
133추가: return { count: total };
134추가: },
135추가: expect_no_server_errors: async (a) => {
136추가: const errs = ctx.server.errors(a.since ?? startSeq).filter((l) => !(a.ignore ?? []).some((ig: string) => new RegExp(ig).test(l.text)));
137추가: if (errs.length) throw new Error(`server logged ${errs.length} error line(s):\n${errs.slice(0, 20).map((l) => l.text).join('\n')}`);
138추가: return { errors: 0 };
139추가: },
140추가: expect_error: async (a) => {
141추가: // Run a nested step that MUST fail (e.g. clicking something that should be rejected).
142추가: const inner = parseStep(a.step);
143추가: try {
144추가: await exec(inner.tool, inner.args);
145추가: } catch (e) {
146추가: const msg = (e as Error).message;
147추가: if (a.matches && !new RegExp(a.matches).test(msg)) throw new Error(`step failed, but message /${a.matches}/ not matched: ${msg}`);
148추가: return { failedAsExpected: msg };
149추가: }
150추가: throw new Error(`expected step ${inner.tool} to fail, but it succeeded`);
151추가: },
152추가: };
153추가:
154추가: async function exec(tool: string, args: any): Promise<any> {
155추가: if (asserts[tool]) return asserts[tool](args);
156추가: const t = TOOL_MAP.get(tool);
157추가: if (!t) throw new Error(`unknown step '${tool}'. Tools: ${[...TOOL_MAP.keys()].join(', ')}; assertions: ${Object.keys(asserts).join(', ')}`);
158추가: if (tool === 'run_scenario') throw new Error('nested run_scenario is not supported');
159추가: return t.run(ctx, args);
160추가: }
161추가:
162추가: async function phase(phaseName: string, steps: any[] | undefined, always = false) {
163추가: for (const [i, raw] of (steps ?? []).entries()) {
164추가: let parsed: { tool: string; args: any; label?: string };
165추가: try {
166추가: parsed = parseStep(raw);
167추가: } catch (e) {
168추가: results.push({ phase: phaseName, index: i, tool: '?', args: raw, ok: false, ms: 0, error: (e as Error).message });
169추가: failed = true;
170추가: if (stopOnFail && !always) return;
171추가: continue;
172추가: }
173추가: if (failed && stopOnFail && !always) {
174추가: results.push({ phase: phaseName, index: i, label: parsed.label, tool: parsed.tool, args: parsed.args, ok: false, ms: 0, skipped: true });
175추가: continue;
176추가: }
177추가: const s0 = Date.now();
178추가: try {
179추가: const result = await exec(parsed.tool, parsed.args);
180추가: if (result?.screenshot) screenshots.push(result.screenshot);
181추가: if (parsed.tool === 'screenshot' && result?.path) screenshots.push(result.path);
182추가: results.push({ phase: phaseName, index: i, label: parsed.label, tool: parsed.tool, args: parsed.args, ok: true, ms: Date.now() - s0, result: short(result) });
183추가: } catch (e) {
184추가: failed = failed || !always;
185추가: const err = (e as Error).message;
186추가: results.push({ phase: phaseName, index: i, label: parsed.label, tool: parsed.tool, args: parsed.args, ok: false, ms: Date.now() - s0, error: err });
187추가: // Evidence: screenshot every running client at the moment of failure.
188추가: for (const c of ctx.clients.running()) {
189추가: try {
190추가: const r = await TOOL_MAP.get('screenshot')!.run(ctx, { client: c, label: `FAIL-${parsed.tool}` });
191추가: screenshots.push(r.path);
192추가: } catch {
193추가: /* ignore */
194추가: }
195추가: }
196추가: }
197추가: }
198추가: }
199추가:
200추가: await phase('setup', doc.setup);
201추가: await phase('steps', doc.steps);
202추가: await phase('teardown', doc.teardown, true);
203추가:
204추가: const passed = !failed && results.every((r) => r.ok || r.phase === 'teardown');
205추가: const serverErrors = ctx.server.running || ctx.server.logSeq > 0 ? ctx.server.errors(startSeq).slice(0, 50).map((l) => l.text) : [];
206추가: const report = {
207추가: name,
208추가: file: path.relative(ROOT, abs),
209추가: passed,
210추가: durationMs: Date.now() - t0,
211추가: failures: results.filter((r) => !r.ok && !r.skipped).map((r) => ({ phase: r.phase, index: r.index, label: r.label, tool: r.tool, error: r.error })),
212추가: steps: results,
213추가: screenshots,
214추가: serverErrors,
215추가: };
216추가: fs.mkdirSync(DIRS.reports, { recursive: true });
217추가: const reportPath = path.join(DIRS.reports, `${stamp()}-${path.basename(abs).replace(/\.ya?ml$/, '')}.json`);
218추가: fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
219추가: return { ...report, report: reportPath };
220추가: }
추가harness/tools.ts

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가mct.config.example.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가package-lock.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가package.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/.gitignore

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/build.gradle

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/gradle.properties

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/gradle/wrapper/gradle-wrapper.jar

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가qa-bridge/gradle/wrapper/gradle-wrapper.properties

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/gradlew

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/gradlew.bat

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/settings.gradle

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/Actions.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/BridgeException.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/BridgeServer.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/ChatLog.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/Keys.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/QaBridgeClient.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/Ticks.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/mixin/AbstractContainerScreenAccessor.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/mixin/KeyMappingAccessor.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/mixin/ServerDataMixin.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/java/dev/mctester/bridge/mixin/ToastManagerMixin.java

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/resources/fabric.mod.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가qa-bridge/src/main/resources/qa_bridge.mixins.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가scenarios/README.md

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가scenarios/demo-shop.yaml

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/mcp-smoke.ts

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tsconfig.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기