Răsfoiți Sursa

【初始】搭建 OneShot 插件骨架

OneShot 是 SPT 客户端 BepInEx 插件:本次 SPT 会话内进入过一次战局(含藏身处)后,禁止再开始战局。
本提交搭建工程骨架:Core 纯逻辑层(会话闸门、语言选择、内嵌中英文案)、Plugin 入口与配置、单元测试、构建/打包/发布脚本、Git 钩子与 CI。具体 Harmony 钩子待后续提交实现。
PJ568 1 lună în urmă
comite
a90919d554

+ 23 - 0
.githooks/commit-msg

@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+# commit-msg 钩子:检查提交信息(语法 + 排版)
+# 1. 语法检查:scripts/check-grammar.mjs(基于 git-commit-regulation 规范)
+# 2. 排版检查:autocorrect --lint(汉字与英文、数字、符号间空格)
+# 启用:git config core.hooksPath .githooks
+# 可绕过:git commit --no-verify(远程 CI 门禁不可绕过)
+
+# 当前钩子所在目录 | Current Hook Directory
+HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+# 1. 语法检查(透传退出码)
+node "$HOOK_DIR/../scripts/check-grammar.mjs" --file "$1" || exit $?
+
+# 2. 排版检查:过滤 git 注释行后交给 autocorrect --lint --stdin
+#    未安装 autocorrect 时跳过(语法检查仍生效)
+if command -v autocorrect > /dev/null 2>&1; then
+  grep -v '^#' "$1" | autocorrect --lint --stdin || {
+    echo "错误:提交信息排版不符合 AutoCorrect 规则(汉字与英文、数字、符号间应留空格)"
+    echo "提示:运行 autocorrect --fix --stdin 或手动调整后重试"
+    exit 1
+  }
+fi
+exit 0

+ 27 - 0
.githooks/pre-commit

@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# pre-commit 钩子:对暂存文件执行 autocorrect --lint 排版检查
+# 启用:git config core.hooksPath .githooks
+# 可绕过:git commit --no-verify(远程 CI 门禁不可绕过)
+
+# 未安装 autocorrect 时跳过
+if ! command -v autocorrect > /dev/null 2>&1; then
+  exit 0
+fi
+
+# 暂存文件(新增、修改、复制和重命名,排除删除;尊重 .autocorrectignore)
+# 逐文件检查便于定位错误;autocorrect 自动跳过二进制与不支持的类型。
+staged="$(git diff --cached --name-only --diff-filter=ACMR)"
+[ -z "$staged" ] && exit 0
+
+failed=0
+while IFS= read -r file; do
+  [ -f "$file" ] || continue
+  autocorrect --lint "$file" || failed=1
+done <<< "$staged"
+
+if [ "$failed" -ne 0 ]; then
+  echo "错误:暂存文件排版不符合 AutoCorrect 规则"
+  echo "提示:运行 autocorrect --fix <文件> 或手动调整后重新 git add"
+  exit 1
+fi
+exit 0

+ 22 - 0
.github/workflows/test.yml

@@ -0,0 +1,22 @@
+# ── 测试 · Tests ──
+# 纯逻辑层无游戏依赖,可在公共 runner 直接测试
+# The pure-logic layer has no game dependency and can be tested on a public runner
+name: 测试 · Tests
+
+on:
+  push:
+    branches: [master, main]
+  pull_request:
+  workflow_dispatch:
+
+jobs:
+  test:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - uses: actions/setup-dotnet@v4
+        with:
+          dotnet-version: "10.0.x"
+      # 运行单元测试 / Run unit tests
+      - name: 运行单元测试 · Run unit tests
+        run: dotnet test tests/OneShot.Tests/OneShot.Tests.csproj -c Release

+ 15 - 0
.gitignore

@@ -0,0 +1,15 @@
+# 构建产物
+bin/
+obj/
+artifacts/
+
+# 本地覆盖与 IDE
+local.props
+Directory.Build.local.props
+*.user
+.vs/
+.idea/
+
+# 反编译/临时研究产物
+/re/
+*.orig

+ 24 - 0
Directory.Build.props

@@ -0,0 +1,24 @@
+<Project>
+
+  <!--
+    游戏(SPT 客户端)根目录与引用路径。
+    优先使用环境变量 SPT_DIR;未设置时回退到本机 Lutris 前缀默认路径。
+    客户端程序集为专有文件,不随仓库分发,构建前需自备 SPT 客户端安装。
+  -->
+  <PropertyGroup>
+    <SPT_DIR Condition="'$(SPT_DIR)' == ''">$(HOME)/.local/lutris/escape-from-tarkov/drive_c/Battlestate Games/Escape from Tarkov</SPT_DIR>
+    <SPT_MANAGED>$(SPT_DIR)/EscapeFromTarkov_Data/Managed</SPT_MANAGED>
+    <SPT_BEPINEX_CORE>$(SPT_DIR)/BepInEx/core</SPT_BEPINEX_CORE>
+    <SPT_PLUGINS_SPT>$(SPT_DIR)/BepInEx/plugins/spt</SPT_PLUGINS_SPT>
+    <DeployToGame Condition="'$(DeployToGame)' == ''">true</DeployToGame>
+  </PropertyGroup>
+
+  <PropertyGroup>
+    <LangVersion>latest</LangVersion>
+    <Nullable>disable</Nullable>
+    <ImplicitUsings>disable</ImplicitUsings>
+    <Deterministic>true</Deterministic>
+    <GenerateDocumentationFile>false</GenerateDocumentationFile>
+  </PropertyGroup>
+
+</Project>

+ 21 - 0
LICENSE

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 PJ568
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 8 - 0
OneShot.slnx

@@ -0,0 +1,8 @@
+<Solution>
+  <Folder Name="/src/">
+    <Project Path="src/OneShot.Plugin/OneShot.Plugin.csproj" />
+  </Folder>
+  <Folder Name="/tests/">
+    <Project Path="tests/OneShot.Tests/OneShot.Tests.csproj" />
+  </Folder>
+</Solution>

+ 121 - 0
README.md

@@ -0,0 +1,121 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+# OneShot
+
+> 让《Single Player Tushonka》客户端在本次会话里只能进一次战局的 SPT 客户端插件。
+
+进入过一次战局(含藏身处)后,本插件会在本次 SPT 运行期间阻止你再开始新的战局;重启 SPT 即重置。适合“一把定输赢”或限制单次游玩时长的场景。
+
+## 功能
+
+- **会话级限制**:以“本次 SPT 进程”为单位,进入过一次战局或藏身处后不再允许开始新战局。
+- **可开关**:在配置中随时启用/关闭限制。
+- **可重置**:无需重启,在配置里勾选一次性重置项即可清除“已进过局”标记。
+- **本地化提示**:根据系统区域自动选择中/英文案。
+
+## 机制
+
+- **会话级**:标记只存于内存,SPT 进程结束后自然消失,重启即恢复。
+- **触发条件**:成功进入过至少一次战局或藏身处(判定钩子见 `docs/principle.md`)。
+- **被禁入口**:在已有标记时,开始战局的入口会被拦截(仅前端限制,见“已知限制”)。
+
+## 安装
+
+1. 下载 Releases 中的 `OneShot-v{版本}.zip`。
+2. 解压到游戏根目录,使 dll 位于
+   `BepInEx/plugins/OneShot/OneShot.dll`。
+3. 启动游戏。
+
+## 构建
+
+```shellscript
+# 指定游戏根目录(未设置时回退到本机 Lutris 前缀默认路径)
+export SPT_DIR="/path/to/Escape from Tarkov"
+dotnet build src/OneShot.Plugin/OneShot.Plugin.csproj -c Release -p:DeployToGame=false
+```
+
+纯逻辑单元测试:
+
+```shellscript
+dotnet test tests/OneShot.Tests/OneShot.Tests.csproj -c Release
+```
+
+## 配置
+
+游戏内按 **F12**(SPT 默认;可在其配置中改键)打开 BepInEx ConfigurationManager,找到 `OneShot` 分区:
+
+| 配置项 | 默认 | 说明 |
+| --- | --- | --- |
+| 启用限制 / Enable Restriction | 开 | 总开关;关闭后不再阻止开始新战局。 |
+| 重置已进局标记 / Reset Entered Flag | 关 | 勾选以清除“已进过局”标记,触发后自动取消勾选。 |
+
+## 已知限制
+
+- **仅前端限制,可被绕过**:本插件在客户端 UI/流程层拦截,无法阻止直接构造网络请求或绕过客户端的行为。
+- **会话级**:标记不落盘,进程结束后清除;这不是持久化或反作弊机制。
+
+## 许可证
+
+[MIT](LICENSE)
+
+===============================================================
+
+# OneShot
+
+> An SPT client plugin that lets you enter only one raid per Single Player Tushonka session.
+
+Once a raid (or the hideout) has been entered, the plugin blocks starting another raid for the rest of this SPT run; restarting SPT resets it. Useful for "one life" or single-session play.
+
+## Features
+
+- **Session-scoped**: the flag lives in memory for the SPT process; entering a raid or the hideout blocks further raid starts until restart.
+- **Toggleable**: enable/disable the restriction from config at any time.
+- **Resettable**: clear the "entered" flag from a one-shot config item without restarting.
+- **Localized message**: Chinese/English text chosen from the system locale.
+
+## How it works
+
+- **Session-scoped**: the flag is in-memory only and disappears when the SPT process ends.
+- **Trigger**: at least one raid or hideout entry has succeeded (hook points in `docs/principle.md`).
+- **Blocked entry**: once flagged, the raid-start entry is intercepted (client-side only, see limitations).
+
+## Installation
+
+1. Download `OneShot-v{version}.zip` from Releases.
+2. Extract it into the game root so the dll lands at
+   `BepInEx/plugins/OneShot/OneShot.dll`.
+3. Launch the game.
+
+## Build
+
+```shellscript
+# Point at the game root (falls back to the local Lutris prefix by default)
+export SPT_DIR="/path/to/Escape from Tarkov"
+dotnet build src/OneShot.Plugin/OneShot.Plugin.csproj -c Release -p:DeployToGame=false
+```
+
+Pure-logic unit tests:
+
+```shellscript
+dotnet test tests/OneShot.Tests/OneShot.Tests.csproj -c Release
+```
+
+## Configuration
+
+Press **F12** in game (the SPT default; rebindable in its config) to open BepInEx ConfigurationManager, then find the `OneShot` section:
+
+| Option | Default | Description |
+| --- | --- | --- |
+| 启用限制 / Enable Restriction | On | Master switch; when off, starting a new raid is no longer blocked. |
+| 重置已进局标记 / Reset Entered Flag | Off | Check to clear the "entered" flag; it unchecks itself afterwards. |
+
+## Known limitations
+
+- **Client-side only and bypassable**: the plugin intercepts at the client UI/flow layer and cannot stop crafted network requests or other bypasses.
+- **Session-scoped**: the flag is not persisted and is cleared when the process ends; this is not a persistence or anti-cheat mechanism.
+
+## License
+
+[MIT](LICENSE)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

+ 105 - 0
docs/development.md

@@ -0,0 +1,105 @@
+# 构建、测试、打包与发布
+
+## 前置
+
+本机需已安装 SPT 客户端。客户端程序集为专有文件,不随仓库分发。
+
+## `SPT_DIR`
+
+构建时通过环境变量 `SPT_DIR` 指定游戏根目录;未设置时回退到本机 Lutris 前缀的默认路径。
+
+```shellscript
+# 指定游戏根目录(未设置时回退到本机 Lutris 前缀默认路径)
+export SPT_DIR="/path/to/Escape from Tarkov"
+dotnet build src/OneShot.Plugin/OneShot.Plugin.csproj -c Release
+```
+
+Release 构建会自动把 dll 复制到 `$SPT_DIR/BepInEx/plugins/OneShot/`;可用 `-p:DeployToGame=false` 关闭自动部署。
+
+## 测试
+
+纯逻辑层(会话闸门、语言选择与文案)无游戏依赖,可直接测试:
+
+```shellscript
+dotnet test tests/OneShot.Tests/OneShot.Tests.csproj -c Release
+```
+
+## 打包与发布
+
+```shellscript
+# 仅打包
+scripts/package.sh
+# 产物:artifacts/OneShot-v{版本}.zip
+
+# 一键发布:构建 → 打包 → 打 tag → 推送 → 创建 GitHub Release
+scripts/release.sh
+# 预演(只构建打包并打印将执行的命令,需工作区干净)
+scripts/release.sh --dry-run
+```
+
+发布前置:已安装并完成鉴权的 GitHub CLI(`gh auth login`,或提供 `GH_TOKEN` 环境变量),且仓库已配置 `remote origin`。`release.sh` 会在打 tag 之前校验工作区干净、tag 不存在以及 gh 鉴权,发布后自动创建带 zip 附件的 Release。
+
+## 部署(本机)
+
+```shellscript
+scripts/package.sh
+# 解压 zip 到游戏根目录,或直接依赖 Release 构建的自动复制
+```
+
+## 为什么公共 CI 只跑纯逻辑单测
+
+客户端插件必须引用专有程序集(`Assembly-CSharp.dll`),公共 runner 无法构建,故仓库只保留 `test.yml`(跑纯逻辑单测);发行包用 `scripts/release.sh` 本地一键发布。
+
+===============================================================
+
+# Build, Test, Packaging and Release
+
+## Prerequisites
+
+A local SPT client install is required. The client assemblies are proprietary and are not distributed with this repository.
+
+## `SPT_DIR`
+
+Point at the game root with the `SPT_DIR` environment variable; when unset it falls back to the local Lutris prefix default path.
+
+```shellscript
+# Point at the game root (falls back to the local Lutris prefix by default)
+export SPT_DIR="/path/to/Escape from Tarkov"
+dotnet build src/OneShot.Plugin/OneShot.Plugin.csproj -c Release
+```
+
+A Release build copies the dll to `$SPT_DIR/BepInEx/plugins/OneShot/` automatically; disable the automatic deploy with `-p:DeployToGame=false`.
+
+## Test
+
+The pure-logic layer (session gate, locale selection and messages) has no game dependency and can be tested directly:
+
+```shellscript
+dotnet test tests/OneShot.Tests/OneShot.Tests.csproj -c Release
+```
+
+## Packaging and Release
+
+```shellscript
+# Package only
+scripts/package.sh
+# Output: artifacts/OneShot-v{version}.zip
+
+# One-command release: build → package → tag → push → create GitHub Release
+scripts/release.sh
+# Dry run (builds/packages and prints the commands; requires a clean work tree)
+scripts/release.sh --dry-run
+```
+
+Release prerequisites: an installed and authenticated GitHub CLI (`gh auth login`, or a `GH_TOKEN` environment variable), and a configured `remote origin`. `release.sh` checks a clean work tree, a fresh tag and gh authentication before tagging, then creates a Release with the zip attached.
+
+## Deploy (Local)
+
+```shellscript
+scripts/package.sh
+# Extract the zip into the game root, or rely on the automatic copy of Release builds
+```
+
+## Why Public CI Runs Only Pure-Logic Unit Tests
+
+A client plugin must reference proprietary assemblies (`Assembly-CSharp.dll`), which public runners cannot build, so the repository keeps only `test.yml` (pure-logic unit tests); release packages are produced locally with `scripts/release.sh`.

+ 87 - 0
docs/principle.md

@@ -0,0 +1,87 @@
+# 原理与钩子设计
+
+> 本文记录判定点与拦截钩子的设计。当前仓库为骨架,钩子尚未实现;实现时以本文为准。
+
+## 总体思路
+
+限制是**会话级**的:只需在内存里记录“本次 SPT 运行是否已进入过场景”,并在“开始战局”的入口查询该标记。数据流如下:
+
+```text
+进入战局/藏身处  →  置位标记 (SessionGate.MarkEnteredScene)
+试图开始战局    →  查询 (SessionGate.ShouldBlockStart)  →  阻止或放行
+```
+
+`OneShot.Core.SessionGate` 为纯逻辑状态机,不依赖游戏程序集,因此可在公共 CI 上直接单测。
+
+## 判定点:进入
+
+计划钩子点:`EFT.GameWorld.OnGameStarted`。
+
+- 当 `GameWorld` 启动完成,即视为“已进入一次战局”。
+- 藏身处同样经由 `GameWorld` 流程,故一并覆盖。
+- 置位动作幂等:重复进入只保持标记为真。
+
+## 拦截点:开始战局
+
+计划钩子点:`EFT.MainMenuShowOperation` / `EFT.UI.MenuScreen`。
+
+- 在主菜单开始战局的入口(`MainMenuShowOperation`)拦截:
+  当 `ShouldBlockStart(PluginConfig.Enabled.Value)` 为真时阻止流程继续。
+- 视图层(`EFT.UI.MenuScreen`)可用于展示“已被限制”提示;文案取自 `OneShotText.Get(...)`,按系统区域选择中/英文。
+
+> 具体钩子的目标签名需随 EFT 版本逆向确认;本骨架不实现钩子,只固定 `Patches/` 目录与纯逻辑接口。
+
+## 复位
+
+- **手动**:配置中的“重置已进局标记”触发 `SessionGate.Reset()`。
+- **自动**:SPT 进程结束,内存标记随之消失,无需持久化。
+
+## 界面说明
+
+- 配置界面由 BepInEx ConfigurationManager 提供(SPT 默认 F12)。
+- `ResetRequested` 为一次性操作项:勾选后由 `PluginConfig` 复位为 `false` 并触发事件,避免界面停留在“已勾选”。
+
+===============================================================
+
+# Design: Detection and Hook Points
+
+> This document records the detection point and interception hooks. The repository is currently a skeleton and the hooks are not implemented yet; implement against this document.
+
+## Approach
+
+The restriction is **session-scoped**: keep an in-memory flag for "has a scene been entered this SPT run" and consult it at the raid-start entry. Data flow:
+
+```text
+enter raid/hideout  →  set flag (SessionGate.MarkEnteredScene)
+try to start raid   →  query (SessionGate.ShouldBlockStart)  →  block or allow
+```
+
+`OneShot.Core.SessionGate` is a pure-logic state machine with no game-assembly dependency, so it can be unit-tested on public CI.
+
+## Detection: entering
+
+Planned hook: `EFT.GameWorld.OnGameStarted`.
+
+- Once `GameWorld` finishes starting, treat it as "a raid has been entered".
+- The hideout goes through the same `GameWorld` flow, so it is covered as well.
+- Setting the flag is idempotent: repeated entries keep it true.
+
+## Interception: starting a raid
+
+Planned hooks: `EFT.MainMenuShowOperation` / `EFT.UI.MenuScreen`.
+
+- Intercept the raid-start entry on the main menu (`MainMenuShowOperation`):
+  when `ShouldBlockStart(PluginConfig.Enabled.Value)` is true, stop the flow.
+- The view layer (`EFT.UI.MenuScreen`) can show the "blocked" message; text comes from `OneShotText.Get(...)`, chosen by system locale.
+
+> Exact hook signatures must be verified against the EFT build; this skeleton does not implement hooks and only fixes the `Patches/` directory and the pure-logic interface.
+
+## Reset
+
+- **Manual**: the "Reset Entered Flag" config fires `SessionGate.Reset()`.
+- **Automatic**: the in-memory flag disappears when the SPT process ends; no persistence.
+
+## UI notes
+
+- The config UI is provided by BepInEx ConfigurationManager (F12 by default in SPT).
+- `ResetRequested` is a one-shot action item: on check, `PluginConfig` resets it to `false` and raises the event so the UI does not stay on.

+ 164 - 0
scripts/check-grammar.mjs

@@ -0,0 +1,164 @@
+#!/usr/bin/env node
+// 基于 git-commit-regulation 规范的自包含提交信息语法检查
+// 规则源:https://github.com/PJ-568/git-commit-regulation(CC BY-SA 4.0)
+// 用法:node scripts/check-grammar.mjs            自测(正反例断言 + 历史提交报告)
+//       node scripts/check-grammar.mjs --file X  检查提交信息文件(commit-msg 钩子)
+
+import assert from "node:assert/strict";
+import { execSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+
+const REPO_DIR = fileURLToPath(new URL("..", import.meta.url));
+
+// 标题语法正则(与 git-commit-regulation README 附录“标题语法”同步维护)
+const TITLE_RE =
+  /^【(?<type>初始|更改|新增|修复|格式|文档|测试|维护)(?:,(?<scope>[\p{Script=Han}A-Za-z0-9_-]{1,16}))?】(?<summary>[^\n]{1,60})$/u;
+const HAN_ONLY_RE = /^[\p{Script=Han}]+$/u;
+const ISSUE_RE = /#\d+/u;
+
+// 解析提交信息;结构违规时抛出带原因的错误
+function parse(message) {
+  const text = message.replace(/\r\n/g, "\n").replace(/^\uFEFF/, "");
+  const lines = text.split("\n");
+  const titleLine = lines[0] ?? "";
+  const m = TITLE_RE.exec(titleLine);
+  if (!m) {
+    throw new Error(titleLine === "" ? "标题缺失" : "标题不符合语法");
+  }
+  const rest = lines.slice(1);
+  if (rest.length > 0 && rest[0] !== "") {
+    throw new Error("描述必须以一个空行与标题相隔");
+  }
+  let description = null;
+  if (rest.length > 1) {
+    const body = rest.slice(1).join("\n").replace(/\n+$/, "");
+    if (body !== "") description = body;
+  }
+  return {
+    type: m.groups.type,
+    scope: m.groups.scope ?? null,
+    summary: m.groups.summary,
+    description,
+  };
+}
+
+// 警告项(解析器应接受并提示)
+function warnings(parsed) {
+  const ws = [];
+  if (HAN_ONLY_RE.test(parsed.summary) && [...parsed.summary].length > 30) {
+    ws.push("摘要为纯汉字且超过 30 汉字(人工建议)");
+  }
+  if (ISSUE_RE.test(parsed.summary)) {
+    ws.push("标题包含问题编号,应移至描述");
+  }
+  return ws;
+}
+
+// —— 命令行模式:检查提交信息文件(commit-msg 钩子)——
+// simp: 只过滤 git 注释行(# 开头);正文中顶格的 #568 行同样被过滤,
+//       与 git 默认 cleanup 行为一致,故钩子不单独校验描述中的问题编号。
+const [mode, filePath] = process.argv.slice(2);
+if (mode === "--file") {
+  if (!filePath) {
+    console.error("用法:node scripts/check-grammar.mjs --file <路径>");
+    process.exit(2);
+  }
+  const cleaned = readFileSync(filePath, "utf8")
+    .split("\n")
+    .filter((line) => !line.startsWith("#"))
+    .join("\n")
+    .trim();
+  if (cleaned === "") {
+    console.error("错误:提交信息为空");
+    process.exit(1);
+  }
+  try {
+    const parsed = parse(cleaned);
+    const ws = warnings(parsed);
+    if (ws.length > 0) {
+      console.warn("警告:\n" + ws.map((w) => `- ${w}`).join("\n"));
+    }
+  } catch (e) {
+    console.error(`错误:${e.message}`);
+    process.exit(1);
+  }
+  process.exit(0);
+}
+
+// 正例与反例(与 git-commit-regulation README 附录表格一致)
+const positives = [
+  ["最小提交", "【修复】解决登录界面的输入验证问题"],
+  ["带范围", "【修复,认证】解决登录界面的输入验证问题"],
+  ["摘要 60 码点上限", "【新增】" + "a".repeat(60)],
+  [
+    "带描述",
+    "【修复,认证】解决登录界面的输入验证问题\n\n修复了登录界面中输入验证逻辑的问题。\n\n相关问题编号:\n\n#568",
+  ],
+];
+
+const negatives = [
+  ["摘要为空", "【初始】"],
+  ["类型不在枚举内", "【验证】执行检查"],
+  ["缺少左括号", "修复】解决登录界面的输入验证问题"],
+  ["半角逗号", "【修复,认证】解决登录界面的输入验证问题"],
+  ["范围含空格", "【修复, 认证】解决登录界面的输入验证问题"],
+  ["摘要超过 60 码点", "【新增】" + "a".repeat(61)],
+  ["描述未以空行相隔", "【修复】解决登录界面的输入验证问题\n第二行直接开始"],
+  ["空消息", ""],
+];
+
+let checked = 0;
+for (const [name, msg] of positives) {
+  assert.doesNotThrow(() => parse(msg), `正例应合法:${name}`);
+  checked++;
+}
+for (const [name, msg] of negatives) {
+  assert.throws(() => parse(msg), `反例应非法:${name}`);
+  checked++;
+}
+// 警告项断言
+assert.equal(
+  warnings(parse("【新增】" + "功".repeat(31))).length,
+  1,
+  "纯汉字摘要超过 30 汉字应发出警告",
+);
+assert.equal(
+  warnings(parse("【修复】解决 #568 问题")).length,
+  1,
+  "标题包含问题编号应发出警告",
+);
+checked += 2;
+
+// 项目历史提交检查(报告,不阻塞)
+// simp: 历史提交本身存在违规(如【初始】),故只报告不断言,避免脚本永远失败。
+let history = [];
+try {
+  const log = execSync("git log --format=%s%x00", { cwd: REPO_DIR }).toString();
+  // git 每条记录后附加换行,NUL 分割后需去除首尾空白
+  history = log
+    .split("\0")
+    .map((m) => m.trim())
+    .filter((m) => m !== "");
+} catch {
+  console.log("(跳过历史检查:非 git 环境)");
+}
+const report = [];
+for (const msg of history) {
+  try {
+    const ws = warnings(parse(msg));
+    if (ws.length > 0) report.push(`${msg}:${ws.join(";")}`);
+  } catch (e) {
+    report.push(`${msg}:${e.message}`);
+  }
+}
+
+console.log(
+  `断言通过:${checked} 个正反例与警告断言、${history.length} 条历史提交`,
+);
+if (report.length > 0) {
+  console.log("历史提交检查报告(不阻塞):");
+  for (const r of report) console.log(`- ${r}`);
+} else {
+  console.log("历史提交检查报告:全部合规");
+}

+ 39 - 0
scripts/package.sh

@@ -0,0 +1,39 @@
+#!/usr/bin/env bash
+# ── 本地打包 · Local packaging ──
+# 构建 Release 并把 dll 按游戏根目录结构打成 zip
+# Build Release and zip the dll using the game-root layout
+# 用法 / Usage:scripts/package.sh
+# 前置 / Prerequisite:本机已安装 SPT 客户端(用 SPT_DIR 指定其根目录)
+#   A local SPT client install (point SPT_DIR at its root)
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "$ROOT"
+
+export DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}"
+export PATH="$DOTNET_ROOT:$DOTNET_ROOT/tools:$PATH"
+
+# 从 csproj 读取版本号 / Read the version from the csproj
+VERSION="$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' src/OneShot.Plugin/OneShot.Plugin.csproj | head -1)"
+[ -n "$VERSION" ] || { echo "错误:未能从 csproj 读取 Version | Error: cannot read Version from csproj" >&2; exit 1; }
+
+OUT="artifacts"
+STAGE="$OUT/OneShot"
+
+# 清理旧产物 / Clean previous output
+rm -rf "$OUT"
+mkdir -p "$STAGE/BepInEx/plugins/OneShot"
+
+# 构建但不自动部署,改由 zip 分发 / Build without auto-deploy; the zip is the deliverable
+dotnet build src/OneShot.Plugin/OneShot.Plugin.csproj -c Release -p:DeployToGame=false
+
+cp "src/OneShot.Plugin/bin/Release/OneShot.dll" \
+   "$STAGE/BepInEx/plugins/OneShot/"
+
+(
+  cd "$STAGE"
+  zip -qr "../OneShot-v${VERSION}.zip" .
+)
+rm -rf "$STAGE"
+
+echo "已生成 artifacts/OneShot-v${VERSION}.zip | Generated artifacts/OneShot-v${VERSION}.zip"

+ 83 - 0
scripts/release.sh

@@ -0,0 +1,83 @@
+#!/usr/bin/env bash
+# ── 本地一键发布 · One-command local release ──
+# 构建 → 打包 → 打 tag → 推送 → 创建 GitHub Release
+# build → package → tag → push → create GitHub Release
+# 用法 / Usage:scripts/release.sh [--dry-run]
+# 前置 / Prerequisites:已安装 gh 并完成鉴权(gh auth login,或提供 GH_TOKEN),且仓库已配置 remote origin
+#   GitHub CLI (gh) installed and authenticated (gh auth login, or provide GH_TOKEN), with a configured remote origin
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "$ROOT"
+
+DRY_RUN=0
+if [ "${1:-}" = "--dry-run" ]; then
+  DRY_RUN=1
+fi
+
+# 从 csproj 读取版本号 / Read the version from the csproj
+VERSION="$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' src/OneShot.Plugin/OneShot.Plugin.csproj | head -1)"
+[ -n "$VERSION" ] || { echo "错误:未能从 csproj 读取 Version | Error: cannot read Version from csproj" >&2; exit 1; }
+
+# 校验 BepInPlugin 特性里的版本与 csproj 一致,避免两处漂移
+# Verify the BepInPlugin version matches the csproj so the two cannot drift apart
+PLUGIN_VERSION="$(grep -oE '\[BepInPlugin\([^]]*' src/OneShot.Plugin/Plugin.cs | grep -oE '"[0-9]+\.[0-9]+\.[0-9]+"' | tr -d '"' | tail -1)"
+if [ -n "$PLUGIN_VERSION" ] && [ "$PLUGIN_VERSION" != "$VERSION" ]; then
+  echo "错误:BepInPlugin 版本 $PLUGIN_VERSION 与 csproj 版本 $VERSION 不一致 | Error: BepInPlugin version $PLUGIN_VERSION does not match csproj version $VERSION" >&2
+  exit 1
+fi
+
+TAG="v$VERSION"
+
+# 工作区必须干净,避免发布内容与提交不一致
+# Require a clean work tree so the release matches the commit
+if [ -n "$(git status --porcelain)" ]; then
+  echo "错误:工作区有未提交改动,请先提交 | Error: uncommitted changes; commit them first" >&2
+  git status --short
+  exit 1
+fi
+
+BRANCH="$(git rev-parse --abbrev-ref HEAD)"
+if [ "$BRANCH" = "HEAD" ]; then
+  echo "错误:处于游离 HEAD,无法发布 | Error: detached HEAD, cannot release" >&2
+  exit 1
+fi
+
+# tag 不能已存在 / The tag must not already exist
+if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
+  echo "错误:tag $TAG 已存在 | Error: tag $TAG already exists" >&2
+  exit 1
+fi
+
+echo "版本 / Version:$VERSION   标签 / Tag:$TAG   分支 / Branch:$BRANCH"
+
+# 构建并打包(--dry-run 也会执行,以校验构建与产物)
+# Build and package (also runs under --dry-run to validate the build and artifact)
+bash scripts/package.sh
+ZIP="artifacts/OneShot-v${VERSION}.zip"
+[ -f "$ZIP" ] || { echo "错误:未找到产物 $ZIP | Error: artifact not found: $ZIP" >&2; exit 1; }
+
+if [ "$DRY_RUN" = "1" ]; then
+  echo "[dry-run] 将执行 / would run:"
+  echo "  git tag -a $TAG -m \"$TAG\""
+  echo "  git push origin $BRANCH"
+  echo "  git push origin $TAG"
+  echo "  gh release create $TAG $ZIP --generate-notes"
+  exit 0
+fi
+
+command -v gh >/dev/null 2>&1 || { echo "错误:未安装 GitHub CLI(gh)| Error: GitHub CLI (gh) not installed" >&2; exit 1; }
+git remote get-url origin >/dev/null 2>&1 || { echo "错误:未配置 git remote origin | Error: no git remote 'origin' configured" >&2; exit 1; }
+
+# 需要可用的 gh 鉴权(或提供 GH_TOKEN);在打 tag 之前校验,避免留下没有 Release 的悬空 tag
+# Require working gh auth (or GH_TOKEN); checked before tagging to avoid a dangling tag without a Release
+if [ -z "${GH_TOKEN:-}" ]; then
+  gh auth status >/dev/null 2>&1 || { echo "错误:gh 未登录,请先 gh auth login 或设置 GH_TOKEN | Error: gh is not authenticated; run gh auth login or set GH_TOKEN" >&2; exit 1; }
+fi
+
+git tag -a "$TAG" -m "OneShot $TAG"
+git push origin "$BRANCH"
+git push origin "$TAG"
+gh release create "$TAG" "$ZIP" --title "OneShot $TAG" --generate-notes
+
+echo "已发布 $TAG(产物:$ZIP)| Released $TAG (artifact: $ZIP)"

+ 24 - 0
src/OneShot.Core/LocaleSelector.cs

@@ -0,0 +1,24 @@
+namespace OneShot.Core
+{
+    /// <summary>
+    /// 根据 .NET 区域文化名选择文案语言。纯逻辑,无游戏/Unity 依赖。
+    /// Selects the message locale from a .NET culture name. Pure logic, no game/Unity dependency.
+    /// </summary>
+    public static class LocaleSelector
+    {
+        public const string English = "en";
+        public const string ChineseSimplified = "zh-CN";
+
+        /// <summary>
+        /// 归一化区域文化名:以 <c>zh</c> 开头者归为简体中文,其余归为英文,空值回退英文。
+        /// Normalizes a culture name: anything starting with <c>zh</c> maps to Simplified Chinese,
+        /// everything else maps to English, and empty values fall back to English.
+        /// </summary>
+        public static string Resolve(string culture)
+        {
+            if (string.IsNullOrWhiteSpace(culture)) return English;
+            if (culture.Trim().StartsWith("zh", System.StringComparison.OrdinalIgnoreCase)) return ChineseSimplified;
+            return English;
+        }
+    }
+}

+ 41 - 0
src/OneShot.Core/OneShotText.cs

@@ -0,0 +1,41 @@
+using System.Collections.Generic;
+
+namespace OneShot.Core
+{
+    /// <summary>
+    /// 内嵌本地化文案表。当前仅需展示一条“已被限制”提示,故不引入完整 i18n 框架。
+    /// Embedded localized strings. Only one "blocked" message is needed, so no full i18n framework is introduced.
+    /// </summary>
+    public static class OneShotText
+    {
+        /// <summary>“已被限制”提示的文案键。</summary>
+        public const string BlockedMessageKey = "oneshot/blocked_message";
+
+        private static readonly Dictionary<string, string> BlockedMessages = new Dictionary<string, string>
+        {
+            {
+                LocaleSelector.ChineseSimplified,
+                "本局 SPT 运行中你已进入过战局或藏身处,无法再开始游戏。重启 SPT 可重置。"
+            },
+            {
+                LocaleSelector.English,
+                "You have already entered a raid or the hideout during this SPT session, so you cannot start another raid. Restart SPT to reset."
+            },
+        };
+
+        /// <summary>
+        /// 按归一化语言返回“已被限制”提示;未知语言回退英文。
+        /// Returns the "blocked" message for a normalized locale; unknown locales fall back to English.
+        /// </summary>
+        public static string Get(string localeId)
+        {
+            string locale = LocaleSelector.Resolve(localeId);
+            if (BlockedMessages.TryGetValue(locale, out string message))
+            {
+                return message;
+            }
+
+            return BlockedMessages[LocaleSelector.English];
+        }
+    }
+}

+ 15 - 0
src/OneShot.Core/SessionGate.cs

@@ -0,0 +1,15 @@
+namespace OneShot.Core
+{
+    /// <summary>会话级闸门:记录本次 SPT 运行是否已进入过场景。</summary>
+    public sealed class SessionGate
+    {
+        public bool HasEnteredScene { get; private set; }
+
+        public void MarkEnteredScene() { HasEnteredScene = true; }
+
+        public void Reset() { HasEnteredScene = false; }
+
+        /// <summary>当功能启用且已进过场景时,是否应阻止开始新战局。</summary>
+        public bool ShouldBlockStart(bool featureEnabled) { return featureEnabled && HasEnteredScene; }
+    }
+}

+ 33 - 0
src/OneShot.Plugin/ConfigurationManagerAttributes.cs

@@ -0,0 +1,33 @@
+using System;
+using BepInEx.Configuration;
+
+namespace OneShot
+{
+    /// <summary>
+    /// 供 BepInEx.ConfigurationManager 通过反射读取的附加显示属性。
+    /// 字段名与上游 ConfigurationManager 约定保持一致,勿随意改名。
+    /// </summary>
+    public sealed class ConfigurationManagerAttributes
+    {
+        /// <summary>自定义绘制回调;为 null 时使用默认绘制。</summary>
+        public Action<ConfigEntryBase> CustomDrawer;
+
+        /// <summary>是否把数值范围显示为百分比。</summary>
+        public bool? ShowRangeAsPercent;
+
+        /// <summary>是否在插件列表中可见。</summary>
+        public bool? Browsable;
+
+        /// <summary>是否属于高级选项(仅在展开高级设置时显示)。</summary>
+        public bool? IsAdvanced;
+
+        /// <summary>是否隐藏“恢复默认”按钮。</summary>
+        public bool? HideDefaultButton;
+
+        /// <summary>是否隐藏设置项名称。</summary>
+        public bool? HideSettingName;
+
+        /// <summary>同一节内的排序权重,越小越靠前。</summary>
+        public int? Order;
+    }
+}

+ 48 - 0
src/OneShot.Plugin/Log.cs

@@ -0,0 +1,48 @@
+using BepInEx.Logging;
+
+namespace OneShot
+{
+    /// <summary>
+    /// 统一的日志出口。错误日志始终输出以便排障。
+    /// 本骨架未提供日志开关,故信息/警告日志也直接输出。
+    /// Unified logging outlet. Error logs are always emitted for troubleshooting.
+    /// This skeleton exposes no logging toggle, so info/warning logs are emitted directly as well.
+    /// </summary>
+    internal static class Log
+    {
+        private static ManualLogSource _logger;
+
+        /// <summary>
+        /// 注入 BepInEx 提供的日志源。
+        /// Injects the BepInEx-provided log source.
+        /// </summary>
+        public static void Init(ManualLogSource logger)
+        {
+            _logger = logger;
+        }
+
+        /// <summary>常规信息。Informational message.</summary>
+        public static void Info(string message)
+        {
+            _logger?.LogInfo(message);
+        }
+
+        /// <summary>诊断信息。Diagnostic message.</summary>
+        public static void Verbose(string message)
+        {
+            _logger?.LogDebug(message);
+        }
+
+        /// <summary>警告。Warning.</summary>
+        public static void Warn(string message)
+        {
+            _logger?.LogWarning(message);
+        }
+
+        /// <summary>错误,始终输出。Error, always emitted.</summary>
+        public static void Error(string message)
+        {
+            _logger?.LogError(message);
+        }
+    }
+}

+ 75 - 0
src/OneShot.Plugin/OneShot.Plugin.csproj

@@ -0,0 +1,75 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <TargetFramework>netstandard2.1</TargetFramework>
+    <AssemblyName>OneShot</AssemblyName>
+    <RootNamespace>OneShot</RootNamespace>
+    <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
+    <Version>0.1.0</Version>
+  </PropertyGroup>
+
+  <!-- 共享纯逻辑:与测试工程同源编译,避免多出一个运行时依赖 dll -->
+  <ItemGroup>
+    <Compile Include="..\OneShot.Core\**\*.cs" Link="Core\%(RecursiveDir)%(Filename)%(Extension)" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <Reference Include="BepInEx">
+      <HintPath>$(SPT_BEPINEX_CORE)/BepInEx.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="0Harmony">
+      <HintPath>$(SPT_BEPINEX_CORE)/0Harmony.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="spt-common">
+      <HintPath>$(SPT_PLUGINS_SPT)/spt-common.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="spt-reflection">
+      <HintPath>$(SPT_PLUGINS_SPT)/spt-reflection.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="Assembly-CSharp">
+      <HintPath>$(SPT_MANAGED)/Assembly-CSharp.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="UnityEngine">
+      <HintPath>$(SPT_MANAGED)/UnityEngine.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="UnityEngine.CoreModule">
+      <HintPath>$(SPT_MANAGED)/UnityEngine.CoreModule.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="UnityEngine.UI">
+      <HintPath>$(SPT_MANAGED)/UnityEngine.UI.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="UnityEngine.UIModule">
+      <HintPath>$(SPT_MANAGED)/UnityEngine.UIModule.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="UnityEngine.IMGUIModule">
+      <HintPath>$(SPT_MANAGED)/UnityEngine.IMGUIModule.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="Unity.TextMeshPro">
+      <HintPath>$(SPT_MANAGED)/Unity.TextMeshPro.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+    <Reference Include="Newtonsoft.Json">
+      <HintPath>$(SPT_MANAGED)/Newtonsoft.Json.dll</HintPath>
+      <Private>false</Private>
+    </Reference>
+  </ItemGroup>
+
+  <!-- 本地 Release 构建后自动部署到游戏插件目录(可用 -p:DeployToGame=false 关闭) -->
+  <Target Name="DeployToGame" AfterTargets="Build"
+          Condition="'$(DeployToGame)' == 'true' And '$(Configuration)' == 'Release' And Exists('$(SPT_DIR)')">
+    <MakeDir Directories="$(SPT_DIR)/BepInEx/plugins/OneShot" />
+    <Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SPT_DIR)/BepInEx/plugins/OneShot" />
+    <Message Importance="high" Text="已部署:$(SPT_DIR)/BepInEx/plugins/OneShot/$(TargetFileName)" />
+  </Target>
+
+</Project>

+ 4 - 0
src/OneShot.Plugin/Patches/.gitkeep

@@ -0,0 +1,4 @@
+# Harmony 钩子占位目录
+# Placeholder for Harmony patches.
+# 计划中的钩子点见 docs/principle.md(进入判定与开始战局拦截,另行实现)。
+# Planned hook points are documented in docs/principle.md (entry detection and raid-start interception).

+ 81 - 0
src/OneShot.Plugin/Plugin.cs

@@ -0,0 +1,81 @@
+// 具体 Harmony 钩子见 Patches/ 目录(另行实现)
+using BepInEx;
+using BepInEx.Configuration;
+using HarmonyLib;
+using OneShot.Core;
+
+namespace OneShot
+{
+    /// <summary>
+    /// 插件入口:初始化配置、日志与会话闸门。
+    /// 进入过一次战局(含藏身处)后,本次 SPT 会话内禁止再开始战局。
+    /// Plugin entry point: initializes config, logging and the session gate.
+    /// Once a raid (or the hideout) has been entered, starting another raid is blocked for this SPT session.
+    /// </summary>
+    [BepInPlugin("com.pj568.oneshot", "OneShot", "0.1.0")]
+    public class OneShotPlugin : BaseUnityPlugin
+    {
+        private const string HarmonyId = "com.pj568.oneshot";
+
+        /// <summary>
+        /// 会话级闸门,记录本次运行是否已进入过场景。
+        /// The session-level gate recording whether a scene has been entered this run.
+        /// </summary>
+        public static SessionGate Gate { get; private set; } = new SessionGate();
+
+        private Harmony _harmony;
+
+        private void Awake()
+        {
+            Log.Init(Logger);
+            PluginConfig.Init(Config);
+
+            PluginConfig.ResetTriggered += OnResetTriggered;
+
+            ApplyHarmonyPatches();
+
+            Log.Info("OneShot 已加载 | loaded");
+        }
+
+        private void OnDestroy()
+        {
+            PluginConfig.ResetTriggered -= OnResetTriggered;
+
+            if (_harmony == null)
+            {
+                return;
+            }
+
+            try
+            {
+                _harmony.UnpatchSelf();
+            }
+            catch (System.Exception e)
+            {
+                Log.Error("卸载 Harmony 补丁失败 | Failed to unpatch Harmony patches: " + e);
+            }
+        }
+
+        /// <summary>
+        /// 响应配置中的一次性重置请求,清除“已进过局”标记。
+        /// Handles the one-shot reset request from config by clearing the "entered" flag.
+        /// </summary>
+        private void OnResetTriggered()
+        {
+            Gate?.Reset();
+        }
+
+        private void ApplyHarmonyPatches()
+        {
+            try
+            {
+                _harmony = new Harmony(HarmonyId);
+                _harmony.PatchAll(typeof(OneShotPlugin).Assembly);
+            }
+            catch (System.Exception e)
+            {
+                Log.Error("应用 Harmony 补丁失败 | Failed to apply Harmony patches: " + e);
+            }
+        }
+    }
+}

+ 79 - 0
src/OneShot.Plugin/PluginConfig.cs

@@ -0,0 +1,79 @@
+using System;
+using BepInEx.Configuration;
+
+namespace OneShot
+{
+    /// <summary>
+    /// 插件配置项定义。配置界面由 BepInEx ConfigurationManager 提供(SPT 中默认 F12,可在其配置中改键)。
+    /// Plugin configuration definitions. The config UI is provided by BepInEx ConfigurationManager
+    /// (F12 by default in SPT; rebindable in its config).
+    /// </summary>
+    internal static class PluginConfig
+    {
+        private const string SectionGeneral = "1. 通用 · General";
+
+        /// <summary>
+        /// 底层配置文件,供插件订阅 <c>SettingChanged</c> 事件。
+        /// The underlying config file, used by the plugin to subscribe to <c>SettingChanged</c>.
+        /// </summary>
+        public static ConfigFile File { get; private set; }
+
+        /// <summary>启用限制。Enable the restriction.</summary>
+        public static ConfigEntry<bool> Enabled { get; private set; }
+
+        /// <summary>一次性重置请求;触发后自动取消勾选。A one-shot reset request; automatically unchecked after firing.</summary>
+        public static ConfigEntry<bool> ResetRequested { get; private set; }
+
+        /// <summary>重置被触发时通知插件清除“已进过局”标记。Raised when a reset is requested, so the plugin clears the flag.</summary>
+        public static event Action ResetTriggered;
+
+        /// <summary>
+        /// 绑定全部配置项并立即落盘,生成带注释的初始配置文件。
+        /// Binds all config entries and saves immediately, generating the initial annotated config file.
+        /// </summary>
+        public static void Init(ConfigFile config)
+        {
+            File = config;
+
+            Enabled = config.Bind(
+                SectionGeneral,
+                "启用限制 | Enable Restriction",
+                true,
+                new ConfigDescription(
+                    "总开关。关闭后不再阻止开始新战局。\nMaster switch. When off, starting a new raid is no longer blocked.",
+                    null,
+                    new ConfigurationManagerAttributes { Order = 1 }));
+
+            ResetRequested = config.Bind(
+                SectionGeneral,
+                "重置已进局标记 | Reset Entered Flag",
+                false,
+                new ConfigDescription(
+                    "勾选以重置“已进过局”标记(重置后会自动取消勾选)。\nCheck to reset the 'entered' flag (it unchecks itself automatically afterwards).",
+                    null,
+                    new ConfigurationManagerAttributes { Order = 2, HideDefaultButton = true }));
+
+            ResetRequested.SettingChanged += OnResetRequestedChanged;
+
+            config.Save();
+        }
+
+        /// <summary>
+        /// 一次性重置:勾选后清除标记,再由插件复位开关,避免界面长期停留在“已勾选”。
+        /// One-shot reset: clear the flag on check, then uncheck so the UI does not stay stuck on.
+        /// </summary>
+        private static void OnResetRequestedChanged(object sender, EventArgs e)
+        {
+            if (ResetRequested == null || !ResetRequested.Value)
+            {
+                return;
+            }
+
+            // 先复位开关,再通知插件;复位本身触发的回调会因值为 false 而提前返回。
+            // Reset the switch before notifying; the reset's own callback returns early because the value is false.
+            ResetRequested.Value = false;
+            File?.Save();
+            ResetTriggered?.Invoke();
+        }
+    }
+}

+ 49 - 0
tests/OneShot.Tests/LocaleSelectorTests.cs

@@ -0,0 +1,49 @@
+using OneShot.Core;
+using Xunit;
+
+namespace OneShot.Tests
+{
+    public class LocaleSelectorTests
+    {
+        [Theory]
+        [InlineData("zh-CN")]
+        [InlineData("zh-Hans")]
+        [InlineData("zh")]
+        public void Resolve_ChineseVariants_MapToChineseSimplified(string culture)
+        {
+            Assert.Equal(LocaleSelector.ChineseSimplified, LocaleSelector.Resolve(culture));
+        }
+
+        [Theory]
+        [InlineData("en-US")]
+        [InlineData("")]
+        [InlineData(null)]
+        public void Resolve_NonChineseOrEmpty_MapToEnglish(string culture)
+        {
+            Assert.Equal(LocaleSelector.English, LocaleSelector.Resolve(culture));
+        }
+
+        [Fact]
+        public void Get_Chinese_IsNonEmptyAndContainsChinese()
+        {
+            string message = OneShotText.Get(LocaleSelector.ChineseSimplified);
+
+            Assert.False(string.IsNullOrWhiteSpace(message));
+            Assert.Contains("战局", message);
+        }
+
+        [Fact]
+        public void Get_English_IsNonEmpty()
+        {
+            string message = OneShotText.Get(LocaleSelector.English);
+
+            Assert.False(string.IsNullOrWhiteSpace(message));
+        }
+
+        [Fact]
+        public void Get_UnknownLocale_FallsBackToEnglish()
+        {
+            Assert.Equal(OneShotText.Get(LocaleSelector.English), OneShotText.Get("fr"));
+        }
+    }
+}

+ 19 - 0
tests/OneShot.Tests/OneShot.Tests.csproj

@@ -0,0 +1,19 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <TargetFramework>net10.0</TargetFramework>
+    <RootNamespace>OneShot.Tests</RootNamespace>
+    <IsPackable>false</IsPackable>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <Compile Include="..\..\src\OneShot.Core\**\*.cs" Link="Core\%(RecursiveDir)%(Filename)%(Extension)" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
+    <PackageReference Include="xunit" Version="2.9.2" />
+    <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
+  </ItemGroup>
+
+</Project>

+ 63 - 0
tests/OneShot.Tests/SessionGateTests.cs

@@ -0,0 +1,63 @@
+using OneShot.Core;
+using Xunit;
+
+namespace OneShot.Tests
+{
+    public class SessionGateTests
+    {
+        [Fact]
+        public void HasEnteredScene_IsFalse_Initially()
+        {
+            SessionGate gate = new SessionGate();
+
+            Assert.False(gate.HasEnteredScene);
+        }
+
+        [Fact]
+        public void MarkEnteredScene_SetsFlagTrue()
+        {
+            SessionGate gate = new SessionGate();
+
+            gate.MarkEnteredScene();
+
+            Assert.True(gate.HasEnteredScene);
+        }
+
+        [Fact]
+        public void Reset_ClearsFlag()
+        {
+            SessionGate gate = new SessionGate();
+            gate.MarkEnteredScene();
+
+            gate.Reset();
+
+            Assert.False(gate.HasEnteredScene);
+        }
+
+        [Fact]
+        public void ShouldBlockStart_IsTrue_WhenEnabledAndEntered()
+        {
+            SessionGate gate = new SessionGate();
+            gate.MarkEnteredScene();
+
+            Assert.True(gate.ShouldBlockStart(true));
+        }
+
+        [Fact]
+        public void ShouldBlockStart_IsFalse_WhenEnabledButNotEntered()
+        {
+            SessionGate gate = new SessionGate();
+
+            Assert.False(gate.ShouldBlockStart(true));
+        }
+
+        [Fact]
+        public void ShouldBlockStart_IsAlwaysFalse_WhenDisabled()
+        {
+            SessionGate gate = new SessionGate();
+            gate.MarkEnteredScene();
+
+            Assert.False(gate.ShouldBlockStart(false));
+        }
+    }
+}