Explorar el Código

【初始】建立武器跨枪配件兼容服务端模组

PJ568 hace 2 meses
commit
a807ef402e

+ 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

+ 69 - 0
.github/workflows/build.yml

@@ -0,0 +1,69 @@
+name: Build Release
+
+on:
+  push:
+    tags:
+      - "v*"
+  workflow_dispatch:
+
+jobs:
+  build:
+    runs-on: ubuntu-latest
+    permissions:
+      contents: write
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v4
+
+      - name: Setup .NET
+        uses: actions/setup-dotnet@v4
+        with:
+          dotnet-version: "10.0.x"
+
+      - name: Restore
+        run: dotnet restore
+
+      - name: Build
+        run: dotnet build -c Release --no-restore
+
+      - name: Test
+        run: dotnet test tests/WeaponCrossModding.Tests/WeaponCrossModding.Tests.csproj -c Release
+
+      - name: Validate build output
+        run: |
+          test -f bin/Release/WeaponCrossModding.dll || exit 1
+          echo "Built WeaponCrossModding.dll"
+
+      - name: Compute mod version
+        id: version
+        run: |
+          VER=$(grep -oP '(?<=<Version>)[^<]+' WeaponCrossModding.csproj)
+          echo "version=$VER" >> "$GITHUB_OUTPUT"
+
+      - name: Package mod as SPT-ready zip
+        run: |
+          VER="${{ steps.version.outputs.version }}"
+          STAGE="staging"
+          # 4.1.x 把 mod 根目录从 SPT/ 改为 SPT_Runtime/,且新数据不向后兼容。
+          mkdir -p "$STAGE/SPT_Runtime/user/mods/WeaponCrossModding"
+          cp bin/Release/WeaponCrossModding.dll "$STAGE/SPT_Runtime/user/mods/WeaponCrossModding/"
+          cd "$STAGE"
+          ZIP_NAME="WeaponCrossModding-v${VER}.zip"
+          mkdir -p ../dist
+          zip -r "../dist/${ZIP_NAME}" SPT_Runtime
+          cd ..
+          echo "Packed dist/${ZIP_NAME}"
+          ls -lh dist/
+
+      - name: Upload artifact
+        uses: actions/upload-artifact@v4
+        with:
+          name: WeaponCrossModding-v${{ steps.version.outputs.version }}
+          path: dist/*.zip
+
+      - name: Create Release
+        if: startsWith(github.ref, 'refs/tags/')
+        uses: softprops/action-gh-release@v2
+        with:
+          files: dist/*.zip
+          generate_release_notes: true

+ 2 - 0
.gitignore

@@ -0,0 +1,2 @@
+bin/
+obj/

+ 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.

+ 75 - 0
README.md

@@ -0,0 +1,75 @@
+# PJ568's Weapon Cross Modding
+
+> 一个 SPT 4.1.x 服务端插件:往目标物品槽的过滤器白名单里追加配件 id,让指定武器、瞄具、枪托与握把实现跨武器兼容。
+
+本插件在服务端加载时,向目标物品槽的 `Slot.Properties.Filters[].Filter`(`HashSet<MongoId>`)白名单追加物品 id;
+对互斥关系,则往 `TemplateItem.Properties.ConflictingItems` 追加物品 id。
+所有注入均幂等:id 已存在时不重复添加。
+
+## 效果
+
+| UZI StormWerkz 顶盖导轨与护木底轨 | CR 200DS 前准星槽 |
+| --- | --- |
+| ![IWI UZI 9x19 冲锋枪](assets/UZI.webp) | ![Chiappa 犀牛 200DS 左轮手枪](assets/200DS.webp) |
+| 顶盖导轨装 ELCAN SpecterDR;护木底轨装 RK 系列前握把。 | 前准星槽装 StormWerkz 顶盖导轨与 MP-18 瞄具基座。 |
+
+| CR 50DS 前准星槽与战术设备槽 | PPSh-41 枪管与枪托槽 |
+| --- | --- |
+| ![Chiappa 犀牛 50DS 左轮手枪](assets/50DS.webp) | ![PPSh-41 冲锋枪](assets/PPSh.webp) |
+| 前准星槽装瞄具基座;战术设备槽装 RK 系列前握把。 | 枪管槽装莫辛纳甘枪管并挂三轨;枪托槽装 M14ALCS (MOD-0) 枪托。 |
+
+## 文档
+
+- [功能与互斥](docs/features.md)
+- [原理](docs/principle.md)
+- [构建、测试与发布](docs/development.md)
+- [实机验证](docs/verification.md)
+- [兼容性与限制](docs/compatibility.md)
+
+## 支持版本
+
+SPT `4.1.x`。
+
+## 许可证
+
+[MIT](LICENSE)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+# PJ568's Weapon Cross Modding
+
+> An SPT 4.1.x server plugin that appends accessory ids to slot filter whitelists, enabling cross-weapon compatibility between selected weapons, optics, stocks and grips.
+
+On load, the plugin appends item ids to the `Slot.Properties.Filters[].Filter` (`HashSet<MongoId>`) whitelist of the target item slots;
+for mutual exclusions, it appends item ids to `TemplateItem.Properties.ConflictingItems`.
+All injections are idempotent: an id already present is never added twice.
+
+## Effect
+
+| UZI StormWerkz top cover rail and lower handguard rail | CR 200DS front sight slot |
+| --- | --- |
+| ![IWI UZI 9x19 SMG](assets/UZI.webp) | ![Chiappa Rhino 200DS revolver](assets/200DS.webp) |
+| The top cover rail takes an ELCAN SpecterDR; the lower handguard rail takes an RK-series foregrip. | The front sight slot takes the StormWerkz top cover rail and the MP-18 scope base. |
+
+| CR 50DS front sight and tactical slots | PPSh-41 barrel and stock slots |
+| --- | --- |
+| ![Chiappa Rhino 50DS revolver](assets/50DS.webp) | ![PPSh-41 SMG](assets/PPSh.webp) |
+| The front sight slot takes a scope base; the tactical slot takes an RK-series foregrip. | The barrel slot takes a Mosin barrel with the tri-rail mounted on it; the stock slot takes the M14ALCS (MOD-0) buttstock. |
+
+## Documentation
+
+- [Features and conflicts](docs/features.md)
+- [Principles](docs/principle.md)
+- [Build, test and release](docs/development.md)
+- [In-game verification](docs/verification.md)
+- [Compatibility and limitations](docs/compatibility.md)
+
+## Supported versions
+
+SPT `4.1.x`.
+
+## License
+
+[MIT](LICENSE)
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

+ 34 - 0
WeaponCrossModding.csproj

@@ -0,0 +1,34 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <TargetFramework>net10.0</TargetFramework>
+    <ImplicitUsings>enable</ImplicitUsings>
+    <Nullable>enable</Nullable>
+    <LangVersion>latest</LangVersion>
+    <OutputType>Library</OutputType>
+    <AssemblyName>WeaponCrossModding</AssemblyName>
+    <RootNamespace>Pj568.WeaponCrossModding</RootNamespace>
+    <!--
+      兼容性:服务端 SPT 4.1.5 公开仓库最高 tag 为 4.1.2(4.1.3/4.1.4/4.1.5 未发布公开 tag),
+      钉到 4.1.2 是当前最稳的策略;服务端校验 mod 编译引用的 SPTarkov.Server.Core
+      AssemblyVersion,使用 4.1.2 编译的 mod 可被 4.1.5 宿主加载。
+    -->
+    <Version>0.1.0</Version>
+    <AssemblyVersion>0.1.0.0</AssemblyVersion>
+    <FileVersion>0.1.0.0</FileVersion>
+    <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <PackageReference Include="SPTarkov.Common" Version="4.1.2" />
+    <PackageReference Include="SPTarkov.DI" Version="4.1.2" />
+    <PackageReference Include="SPTarkov.Server.Core" Version="4.1.2" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <!-- 测试项目位于 tests/ 下,避免被主项目默认 glob 一并编译 -->
+    <Compile Remove="tests/**" />
+    <None Remove="tests/**" />
+  </ItemGroup>
+
+</Project>

BIN
assets/200DS.webp


BIN
assets/50DS.webp


BIN
assets/PPSh.webp


BIN
assets/UZI.webp


+ 21 - 0
docs/README.md

@@ -0,0 +1,21 @@
+# 文档索引
+
+本目录收录 PJ568's Weapon Cross Modding 的技术文档。README 保持精简,深入内容按主题拆分如下:
+
+- [功能与互斥](features.md):全部跨武器兼容条目与互斥关系的清单。
+- [原理](principle.md):槽位过滤器与冲突列表的数据模型、注入流程、幂等语义与日志形态。
+- [构建、测试与发布](development.md):`dotnet build`、单元测试、CI 自动发布与部署。
+- [实机验证](verification.md):启动自检日志、验证步骤与排查建议。
+- [兼容性与限制](compatibility.md):支持版本、与其它模组的关系、已知限制与命名说明。
+
+===============================================================
+
+# Documentation Index
+
+This directory holds the technical documentation for PJ568's Weapon Cross Modding. The README stays short; the in-depth material is split by topic below:
+
+- [Features and conflicts](features.md): the full list of cross-weapon compatibility entries and conflicts.
+- [Principles](principle.md): the data model of slot filters and conflict lists, the injection flow, idempotency semantics and the log shape.
+- [Build, test and release](development.md): `dotnet build`, unit tests, CI auto-release and deployment.
+- [In-game verification](verification.md): startup self-check logs, verification steps and troubleshooting tips.
+- [Compatibility and limitations](compatibility.md): supported versions, interaction with other mods, known limitations and naming notes.

+ 63 - 0
docs/compatibility.md

@@ -0,0 +1,63 @@
+# 兼容性与限制
+
+## 支持版本
+
+- SPT `4.1.x` 服务端(ServerMod)。
+
+## 与其它模组的关系
+
+- **幂等共存**:所有注入基于 `HashSet.Add`,与同样向槽位过滤器追加白名单的模组共存时不会产生重复条目,也不会互相覆盖。若另一模组已加入同一 id,本插件只记一条 `Debug` 日志。
+- **`WTT-ContentBackport`**:部分物品由该模组注入,例如 HUXWRX HX-QD 7.62x51 消音器(黑 / 黄褐色)与 Tyrant Designs MOD Chevron AR-15 镂空手枪式握把(黑 / 黄 / 红)。
+  - 这些物品作为**白名单新增项**时,插件只追加 id,不要求其存在,因此无论该模组是否安装都能正常加载。
+  - 这些物品作为**冲突目标**时(HUXWRX 消音器),若其尚未注入,插件仅记 `Debug` 并跳过;由于 PPSh-41 防尘盖一侧的冲突记录仍会建立,互斥关系依旧成立,并避免了对第三方模组加载顺序的依赖。
+- 插件只改写物品数据库,不注册 Harmony patch,也不与客户端插件争抢运行时方法。
+
+## 已知限制
+
+- **依赖物品 id 与槽位名**:注入目标取自具体物品 id 与槽位名;若上游数据在版本更新中变更,相关条目会跳过或失效。
+- **必须由服务端加载**:这是服务端模组,仅在服务端数据库层面放宽白名单;未部署到服务端时游戏内不会生效。
+- **版本敏感**:`SPTarkov.Server.Core` 等依赖与 SPT 服务端版本对齐,跨越 4.1.x 之外的版本可能需要重新适配。
+
+## 命名说明
+
+| 项目 | 值 |
+| --- | --- |
+| 展示名 | `PJ568's Weapon Cross Modding` |
+| 仓库 slug | `spt-weapon-cross-modding` |
+| 程序集 / 部署目录 | `WeaponCrossModding` |
+| ModGuid | `com.pj568.weaponcrossmodding` |
+| 作者 | `PJ568` |
+| 许可证 | MIT |
+
+===============================================================
+
+# Compatibility and Limitations
+
+## Supported Versions
+
+- SPT `4.1.x` server (ServerMod).
+
+## Interaction with Other Mods
+
+- **Idempotent coexistence**: every injection relies on `HashSet.Add`, so running alongside mods that also append to slot filters produces no duplicates and no overwrites. If another mod already added the same id, this plugin only writes a `Debug` entry.
+- **`WTT-ContentBackport`**: some items are injected by that mod, such as the HUXWRX HX-QD 7.62x51 suppressors (black / tan) and the Tyrant Designs MOD Chevron AR-15 skeletonized pistol grips (black / yellow / red).
+  - When these items are **whitelist additions**, the plugin only appends their ids and does not require them to exist, so it loads fine whether or not that mod is installed.
+  - When these items are **conflict targets** (the HUXWRX suppressors), if they are not yet injected the plugin only logs `Debug` and skips; because the PPSh-41 dust cover side still records the conflict, the exclusion still holds, avoiding any dependency on third-party load order.
+- The plugin only rewrites the item database. It registers no Harmony patch and never contends with client plugins for runtime methods.
+
+## Known Limitations
+
+- **Depends on item ids and slot names**: the injection targets come from concrete item ids and slot names; if upstream data changes in a version update, the affected entries are skipped or stop applying.
+- **Must be loaded by the server**: this is a server mod that widens whitelists only at the server database level; it has no in-game effect unless deployed to the server.
+- **Version sensitive**: dependencies such as `SPTarkov.Server.Core` are version-aligned with the SPT server, and going beyond the 4.1.x line may require re-adaptation.
+
+## Naming Notes
+
+| Item | Value |
+| --- | --- |
+| Display name | `PJ568's Weapon Cross Modding` |
+| Repository slug | `spt-weapon-cross-modding` |
+| Assembly / deploy directory | `WeaponCrossModding` |
+| ModGuid | `com.pj568.weaponcrossmodding` |
+| Author | `PJ568` |
+| License | MIT |

+ 91 - 0
docs/development.md

@@ -0,0 +1,91 @@
+# 构建、测试与发布
+
+## 前置
+
+本机需安装 .NET SDK(目标框架 `net10.0`)。依赖通过 NuGet 拉取(`SPTarkov.Server.Core`、`SPTarkov.DI`、`SPTarkov.Common`,版本对齐服务端 4.1.x),**无需本机 SPT 程序集**。
+
+## 构建
+
+```shellscript
+dotnet build -c Release
+```
+
+产物为 `bin/Release/WeaponCrossModding.dll`。
+
+## 测试
+
+单元测试位于 `tests/WeaponCrossModding.Tests/`,用最小物品 / 槽位夹具直接驱动插件的槽位注入,覆盖各白名单追加、互斥关系与幂等:
+
+```shellscript
+dotnet test tests/WeaponCrossModding.Tests/WeaponCrossModding.Tests.csproj
+```
+
+## CI 自动发布
+
+`.github/workflows/build.yml` 在推送 `v*` 标签(或手动触发)时自动构建并打包:
+
+1. `dotnet restore` 与 `dotnet build -c Release`。
+2. 运行 `dotnet test tests/WeaponCrossModding.Tests/WeaponCrossModding.Tests.csproj -c Release`。
+3. 校验 `bin/Release/WeaponCrossModding.dll` 存在。
+4. 从 csproj 读取 `<Version>`,按游戏根目录结构打包为 `WeaponCrossModding-v{版本}.zip`。
+5. 上传 zip 为 workflow artifact;标签触发时创建 GitHub Release 并附带该 zip。
+
+`Version`(csproj)应与标签保持一致(如标签 `v0.1.0` 对应 `<Version>0.1.0</Version>`)。
+
+## 本机部署
+
+将 `WeaponCrossModding.dll` 放入服务端 `user/mods/WeaponCrossModding/` 目录,然后重启服务端:
+
+```shellscript
+systemctl --user restart pj568-spt-server
+```
+
+也可以直接解压 Release 中的 `WeaponCrossModding-v{版本}.zip` 到对应目录。
+部署后按[实机验证](verification.md)检查启动日志。
+
+===============================================================
+
+# Build, Test and Release
+
+## Prerequisites
+
+A .NET SDK is required (target framework `net10.0`). Dependencies are pulled from NuGet (`SPTarkov.Server.Core`, `SPTarkov.DI`, `SPTarkov.Common`, version-aligned with server 4.1.x), so **no local SPT assemblies are needed**.
+
+## Build
+
+```shellscript
+dotnet build -c Release
+```
+
+The output is `bin/Release/WeaponCrossModding.dll`.
+
+## Test
+
+The unit tests live in `tests/WeaponCrossModding.Tests/`. They drive the plugin's slot injection directly with minimal item / slot fixtures, covering every whitelist addition, the conflict, and idempotency:
+
+```shellscript
+dotnet test tests/WeaponCrossModding.Tests/WeaponCrossModding.Tests.csproj
+```
+
+## CI Auto-Release
+
+`.github/workflows/build.yml` builds and packages automatically when a `v*` tag is pushed (or on manual dispatch):
+
+1. `dotnet restore` and `dotnet build -c Release`.
+2. Run `dotnet test tests/WeaponCrossModding.Tests/WeaponCrossModding.Tests.csproj -c Release`.
+3. Verify that `bin/Release/WeaponCrossModding.dll` exists.
+4. Read `<Version>` from the csproj and package it as `WeaponCrossModding-v{version}.zip` using the game-root layout.
+5. Upload the zip as a workflow artifact; on a tag push, create a GitHub Release with that zip attached.
+
+`Version` (csproj) should stay in sync with the tag (e.g. tag `v0.1.0` ↔ `<Version>0.1.0</Version>`).
+
+## Local Deployment
+
+Place `WeaponCrossModding.dll` into the server's `user/mods/WeaponCrossModding/` directory, then restart the server:
+
+```shellscript
+systemctl --user restart pj568-spt-server
+```
+
+Alternatively, extract `WeaponCrossModding-v{version}.zip` from a Release into the corresponding directory.
+After deploying, check the startup log as described in [In-game verification](verification.md).

+ 55 - 0
docs/features.md

@@ -0,0 +1,55 @@
+# 功能与互斥
+
+> 本文汇总 PJ568's Weapon Cross Modding 实现的全部跨武器兼容条目与互斥关系。所有条目均通过向目标槽位过滤器白名单追加物品 id 实现(互斥则写入冲突列表),详见[原理](principle.md)。
+
+## 瞄具与基座
+
+- UZI StormWerkz 顶盖导轨的 `mod_scope` 槽:新增 ELCAN SpecterDR 1x/4x(含 FDE 变体)与 SIG Sauer BRAVO4 4x30 瞄准镜。
+- CR 200DS、CR 50DS 的 `mod_sight_front` 前准星槽:新增 UZI StormWerkz 顶盖导轨与 MP-18 瞄具基座。
+- Aim Sports“三轨”莫辛步枪导轨的 `mod_scope` 槽:新增 M14 SAGE International DCSB 瞄具基座。
+
+## 枪管与枪托
+
+- PPSh-41 冲锋枪的 `mod_barrel` 枪管槽:新增莫辛纳甘全部 4 种尺寸枪管(200mm 锯短、220mm 锯短螺纹、514mm 卡宾、730mm 标准)。
+- PPSh-41 冲锋枪的 `mod_stock` 枪托槽:新增 Benelli M3 可伸缩枪托、PKM 木制枪托、Zenit PT-2 "Klassika" PK 机枪枪托、PKP 聚合物枪托、Ultima MP-155 塑料手枪式握把、KS-23 金属枪托与 M14 SAGE International M14ALCS (MOD-0) 枪托。
+
+## 握把与配件
+
+- Aim Sports“三轨”的第一个战术配件槽(`mod_tactical_000`):新增 13 款前握把(Zenit RK 系列、镂空型、垂直型、BCM MOD.3、TangoDown Stubby BGV-MK46K;不含 KeyMod / M-LOK 型)、SV-98 隔热带与 Fortis Shift 战术前握把。
+- Aim Sports“三轨”的第二个战术配件槽(`mod_tactical_001`):新增 SV-98 隔热带。
+- UZI StormWerkz 护木底轨的 `mod_tactical` 槽:新增 Zenit RK 系列前握把。
+- CR 50DS 的 `mod_tactical` 战术设备槽:新增 Zenit RK 系列前握把、KAC MWS 脚架转接器与 BT10 V8 Atlas 折叠脚架。
+- M14 SAGE International M14ALCS (MOD-0) 枪托的 `mod_pistol_grip` 握把位:新增 AR-15 Tactical Dynamics 镂空手枪式握把、Tyrant Designs MOD Chevron AR-15 镂空手枪式握把(黑 / 黄 / 红)与 AS VAL Rotor 43 手枪式握把附缓冲管转接器。
+
+## 互斥
+
+- PPSh-41 防尘盖与 HUXWRX HX-QD 7.62x51 消音器(含黄褐色变体)互不兼容。
+
+===============================================================
+
+# Features and Conflicts
+
+> This document collects every cross-weapon compatibility entry and conflict implemented by PJ568's Weapon Cross Modding. All entries add item ids to the target slot filter whitelist (conflicts are written to the conflict list); see [Principles](principle.md) for details.
+
+## Optics and mounts
+
+- `mod_scope` slot of the UZI StormWerkz top cover rail: adds the ELCAN SpecterDR 1x/4x (including the FDE variant) and the SIG Sauer BRAVO4 4x30.
+- `mod_sight_front` slot of the CR 200DS and CR 50DS: adds the UZI StormWerkz top cover rail and the MP-18 scope base.
+- `mod_scope` slot of the Aim Sports tri-rail Mosin mount: adds the M14 SAGE International DCSB scope mount.
+
+## Barrels and stocks
+
+- `mod_barrel` slot of the PPSh-41: adds all four Mosin barrel lengths (200 mm sawn-off, 220 mm threaded sawn-off, 514 mm carbine, 730 mm standard).
+- `mod_stock` slot of the PPSh-41: adds the Benelli M3 telescopic stock, the PKM wooden stock, the Zenit PT-2 "Klassika" PK stock, the PKP polymer stock, the Ultima MP-155 plastic pistol grip, the KS-23 metal stock and the M14 SAGE International M14ALCS (MOD-0) buttstock.
+
+## Grips and accessories
+
+- First tactical slot (`mod_tactical_000`) of the Aim Sports tri-rail: adds 13 foregrips (Zenit RK series, skeletonized, vertical, BCM MOD.3, TangoDown Stubby BGV-MK46K; excluding KeyMod / M-LOK types), the SV-98 heat ribbon and the Fortis Shift tactical foregrip.
+- Second tactical slot (`mod_tactical_001`) of the Aim Sports tri-rail: adds the SV-98 heat ribbon.
+- `mod_tactical` slot of the UZI StormWerkz lower handguard rail: adds the Zenit RK series foregrips.
+- `mod_tactical` slot of the CR 50DS: adds the Zenit RK series foregrips, the KAC MWS bipod adapter and the BT10 V8 Atlas folding bipod.
+- `mod_pistol_grip` slot of the M14 SAGE International M14ALCS (MOD-0) buttstock: adds the AR-15 Tactical Dynamics skeletonized pistol grip, the Tyrant Designs MOD Chevron AR-15 skeletonized pistol grips (black / yellow / red) and the AS VAL Rotor 43 pistol grip with buffer tube adapter.
+
+## Conflicts
+
+- The PPSh-41 dust cover is incompatible with the HUXWRX HX-QD 7.62x51 suppressors (including the tan variant).

+ 123 - 0
docs/principle.md

@@ -0,0 +1,123 @@
+# 原理
+
+> 本文说明 PJ568's Weapon Cross Modding 如何在 SPT 4.1.x 服务端修改物品数据,使其实现跨武器兼容。
+
+## 数据模型
+
+SPT 服务端把所有物品模板存放在 `TemplateTable.Items`(`Dictionary<MongoId, TemplateItem>`)中。与兼容性相关的字段有两处:
+
+### 槽位过滤器
+
+每个 `TemplateItem` 的 `Properties.Slots` 是一个 `Slot` 列表。每个 `Slot` 有:
+
+- `Name`:槽位名,如 `mod_scope`、`mod_sight_front`、`mod_barrel`、`mod_stock`、`mod_tactical`、`mod_tactical_000`、`mod_tactical_001`、`mod_pistol_grip`。
+- `Properties.Filters`:`SlotFilter` 列表。
+- `SlotFilter.Filter`:`HashSet<MongoId>`,即该槽位允许安装的物品 id 白名单。
+
+**要让一件物品能装进某个槽位,就是把这个物品的 id 加进该槽位过滤器的白名单。**
+
+### 冲突列表
+
+`TemplateItem.Properties.ConflictingItems` 是 `HashSet<MongoId>`。若 A 的 `ConflictingItems` 含 B 的 id(或反之),则 A 与 B 不能同时安装在一件武器上。
+
+## 注入流程
+
+插件入口实现 `IOnLoad`,并以 `[Injectable(InjectionType.Singleton, OnLoadOrder.Preload + 4)]` 注册,在服务端预加载阶段、原版数据库构建完成后运行一次。
+
+`OnLoadAsync(CancellationToken)` 的流程:
+
+1. 取出 `TemplateTable.Items`。
+2. 对每一组「宿主物品 + 槽位名 + 待追加 id」,调用 `AddItemIdsToSlot`:
+   - 若宿主 id 不在 `Items` 中,记警告并跳过;若宿主没有槽位,记警告并跳过。
+   - 按槽位名(`OrdinalIgnoreCase`)找到宿主的所有同名槽。
+   - 对每个槽的每个 `SlotFilter`,把各 id 加入 `Filter`。
+3. 对每一组互斥关系,调用 `AddConflictingItems`,把冲突 id 加入宿主物品的 `ConflictingItems`。
+4. 整个过程包在 `try/catch` 中:任何异常都被记录为 `error`,不会中断服务端启动。
+
+## 幂等
+
+注入全部基于 `HashSet` 的 `Add`:
+
+- `Add` 返回 `true` 表示新增成功,记一条 info 日志。
+- 返回 `false` 表示已存在,仅记一条 debug 日志,不重复写入。
+
+因此插件重复加载、或与其它同样追加白名单的模组共存时,都不会产生重复条目或冲突。
+
+### 缺失物品的处理
+
+- **白名单宿主缺失**(`AddItemIdsToSlot` 找不到宿主):记警告并跳过。追加的 id 本身无需存在。
+- **冲突目标缺失**(`AddConflictingItems` 找不到宿主):记 debug 并静默跳过。对由第三方模组注入的物品(如 HUXWRX HX-QD 消音器),这是有意为之:只要另一侧(PPSh-41 防尘盖)仍能写入冲突记录,互斥关系就已建立,从而避免对第三方模组加载顺序的依赖。
+
+## 日志形态
+
+成功的注入会输出(`Info`):
+
+```
+[Info][...] WeaponCrossModding: added '<物品 id>' to slot '<槽位名>' (<宿主物品名>)
+[Info][...] WeaponCrossModding: added conflicting item '<物品 id>' to '<宿主标签>' (<宿主物品名>)
+```
+
+已存在或缺失则只写 `Debug`,不打扰常规日志。
+
+===============================================================
+
+# Principles
+
+> This document explains how PJ568's Weapon Cross Modding modifies item data on the SPT 4.1.x server to achieve cross-weapon compatibility.
+
+## Data Model
+
+The SPT server stores every item template in `TemplateTable.Items` (`Dictionary<MongoId, TemplateItem>`). Two fields are relevant to compatibility:
+
+### Slot filters
+
+Each `TemplateItem`'s `Properties.Slots` is a list of `Slot`. Every `Slot` has:
+
+- `Name`: the slot name, such as `mod_scope`, `mod_sight_front`, `mod_barrel`, `mod_stock`, `mod_tactical`, `mod_tactical_000`, `mod_tactical_001`, `mod_pistol_grip`.
+- `Properties.Filters`: a list of `SlotFilter`.
+- `SlotFilter.Filter`: a `HashSet<MongoId>`, the whitelist of item ids the slot accepts.
+
+**Making an item fit a slot means adding that item's id to the slot filter's whitelist.**
+
+### Conflict list
+
+`TemplateItem.Properties.ConflictingItems` is a `HashSet<MongoId>`. If A's `ConflictingItems` contains B's id (or vice versa), A and B cannot be installed on the same weapon.
+
+## Injection Flow
+
+The plugin entry implements `IOnLoad` and is registered with `[Injectable(InjectionType.Singleton, OnLoadOrder.Preload + 4)]`, so it runs once during the server preload phase, after the vanilla database has been built.
+
+`OnLoadAsync(CancellationToken)` works as follows:
+
+1. Fetch `TemplateTable.Items`.
+2. For each group of "owner item + slot name + ids to add", call `AddItemIdsToSlot`:
+   - If the owner id is missing from `Items`, log a warning and skip; if the owner has no slots, log a warning and skip.
+   - Find all same-named slots (case-insensitive, `OrdinalIgnoreCase`).
+   - For every `SlotFilter` of every matching slot, add the ids to `Filter`.
+3. For each mutual exclusion, call `AddConflictingItems` to add the conflicting id to the owner item's `ConflictingItems`.
+4. The whole process is wrapped in `try/catch`: any exception is logged as `error` and never interrupts server startup.
+
+## Idempotency
+
+All injections rely on `HashSet.Add`:
+
+- `Add` returns `true` when the entry is new, and an info log is written.
+- It returns `false` when the entry already exists; only a debug log is written and nothing is duplicated.
+
+Reloading the plugin, or running it alongside other mods that also append to whitelists, therefore never produces duplicates or conflicts.
+
+### Handling missing items
+
+- **Missing whitelist owner** (`AddItemIdsToSlot` cannot find the owner): log a warning and skip. The added ids themselves need not exist.
+- **Missing conflict target** (`AddConflictingItems` cannot find the owner): log at debug level and skip silently. This is intentional for items injected by third-party mods (such as the HUXWRX HX-QD suppressors): as long as the other side (the PPSh-41 dust cover) still records the conflict, the exclusion is established, avoiding any dependency on third-party load order.
+
+## Log Shape
+
+Successful injections print (`Info`):
+
+```
+[Info][...] WeaponCrossModding: added '<item id>' to slot '<slot name>' (<owner item name>)
+[Info][...] WeaponCrossModding: added conflicting item '<item id>' to '<owner label>' (<owner item name>)
+```
+
+If the entry already exists or is missing, only `Debug` is written, keeping the regular log quiet.

+ 75 - 0
docs/verification.md

@@ -0,0 +1,75 @@
+# 实机验证
+
+## 启动自检
+
+服务端启动后,日志(`user/logs/spt/sptYYYYMMDD.log`)应出现本模组的加载记录:
+
+```
+[Info][ModValidator] 模组:PJ568's Weapon Cross Modding 版本… 已加载
+```
+
+随后是各条注入记录:
+
+```
+[Info][...] WeaponCrossModding: added '<物品 id>' to slot '<槽位名>' (<宿主物品名>)
+```
+
+槽位名应涵盖 `mod_scope`、`mod_sight_front`、`mod_barrel`、`mod_stock`、`mod_tactical`、`mod_tactical_000`、`mod_tactical_001`、`mod_pistol_grip`;互斥关系另会输出 `added conflicting item '…' to '…'`。
+
+## 验证步骤
+
+1. 部署 dll 并重启 `pj568-spt-server`。
+2. 打开 `user/logs/spt/sptYYYYMMDD.log`,确认出现上述加载行与注入行。
+3. 进入游戏,在武器改装界面检查目标组合是否可安装,例如:
+   - 在 UZI StormWerkz 顶盖导轨上安装 ELCAN SpecterDR 或 SIG Sauer BRAVO4;
+   - 在 CR 200DS / CR 50DS 前准星槽安装 StormWerkz 顶盖导轨或 MP-18 瞄具基座;
+   - 在 PPSh-41 上安装莫辛纳甘枪管或 M14ALCS (MOD-0) 枪托;
+   - 尝试同时安装 PPSh-41 防尘盖与 HUXWRX HX-QD 消音器,确认二者互斥。
+4. 若修改了物品 id,重新运行单元测试确认夹具仍与代码一致。
+
+## 排查建议
+
+- 所有运行日志都写入 `user/logs/spt/sptYYYYMMDD.log`,遇到异常先看该文件。
+- **看不到注入记录**:确认 dll 位于 `user/mods/WeaponCrossModding/`,且日志中没有本模组的加载错误。
+- **出现 `not found in Items` 警告**:该宿主物品 id 在当前数据库不存在,对应条目被跳过;多为数据版本或第三方模组差异所致。
+- **日志只有 `Debug`**:说明该 id 已存在(幂等生效),属正常情况。
+- **互斥未生效**:若 HUXWRX 消音器由第三方模组注入而当前缺失,插件会静默跳过消音器一侧,但防尘盖一侧的冲突记录仍会建立;确认防尘盖的 `ConflictingItems` 已包含消音器 id。
+
+===============================================================
+
+# In-Game Verification
+
+## Startup Self-Check
+
+After the server starts, the log (`user/logs/spt/sptYYYYMMDD.log`) should show this mod's load record:
+
+```
+[Info][ModValidator] 模组:PJ568's Weapon Cross Modding 版本… 已加载
+```
+
+followed by the individual injections:
+
+```
+[Info][...] WeaponCrossModding: added '<item id>' to slot '<slot name>' (<owner item name>)
+```
+
+The slot names should cover `mod_scope`, `mod_sight_front`, `mod_barrel`, `mod_stock`, `mod_tactical`, `mod_tactical_000`, `mod_tactical_001`, `mod_pistol_grip`; conflicts also print `added conflicting item '…' to '…'`.
+
+## Verification Steps
+
+1. Deploy the dll and restart `pj568-spt-server`.
+2. Open `user/logs/spt/sptYYYYMMDD.log` and confirm the load line and injection lines above.
+3. Enter the game and check the target combinations in the weapon modding screen, for example:
+   - mount the ELCAN SpecterDR or SIG Sauer BRAVO4 on the UZI StormWerkz top cover rail;
+   - mount the StormWerkz top cover rail or MP-18 scope base on the CR 200DS / CR 50DS front sight slot;
+   - mount a Mosin barrel or the M14ALCS (MOD-0) buttstock on the PPSh-41;
+   - try mounting the PPSh-41 dust cover and a HUXWRX HX-QD suppressor together and confirm they are mutually exclusive.
+4. If you changed any item id, re-run the unit tests to confirm the fixtures still match the code.
+
+## Troubleshooting
+
+- All runtime logs are written to `user/logs/spt/sptYYYYMMDD.log`; check that file first when something looks wrong.
+- **No injection records**: confirm the dll is at `user/mods/WeaponCrossModding/` and that the log contains no load error for this mod.
+- **A `not found in Items` warning appears**: the owner item id is absent from the current database and that entry was skipped; this is usually a data-version or third-party-mod difference.
+- **Only `Debug` entries appear**: the id already exists (idempotency in effect), which is normal.
+- **A conflict does not apply**: if the HUXWRX suppressor is injected by a third-party mod and is currently absent, the plugin silently skips the suppressor side, but the dust cover side still records the conflict; verify the dust cover's `ConflictingItems` contains the suppressor id.

+ 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("历史提交检查报告:全部合规");
+}

+ 319 - 0
src/Mod.cs

@@ -0,0 +1,319 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using SPTarkov.DI.Annotations;
+using SPTarkov.Server.Core.DI;
+using SPTarkov.Server.Core.Models.Common;
+using SPTarkov.Server.Core.Models.Eft.Common.Tables;
+using SPTarkov.Server.Core.Models.Spt.Tables;
+using SPTarkov.Common.Models.Logging;
+
+namespace Pj568.WeaponCrossModding;
+
+/// <summary>
+/// 服务端 mod:
+///   1. 让 UZI StormWerkz 瞄具基座的 mod_scope 槽支持安装 ELCAN SpecterDR 1x/4x 及其 FDE 变体,
+///      以及 SIG Sauer BRAVO4 4x30 瞄准镜;
+///   2. 让 StormWerkz 顶盖导轨可安装到 CR 200DS 转轮手枪的前准星槽;
+///   3. 让 CR 200DS 的前准星槽支持安装 MP-18 瞄具基座;
+///   4. 让 PPSh-41 冲锋枪的枪管槽支持安装莫辛纳甘的全部 4 种尺寸枪管;
+///   5. 让 PPSh-41 冲锋枪的枪托槽支持安装 Benelli M3 可伸缩枪托、PKM / PKP 枪托、Ultima MP-155 塑料手枪式握把与 KS-23 金属枪托;
+///   6. 让 HUXWRX HX-QD 消音器(含黄褐色变体)与 PPSh-41 防尘盖互不兼容;
+///   7. 让 Aim Sports“三轨”莫辛步枪导轨的第一个战术配件槽(mod_tactical_000)支持安装多种前握把(不含 KeyMod / M-LOK 型);
+///   8. 让 UZI StormWerkz 护木底轨的 mod_tactical 槽支持安装 Zenit RK 系列前握把;
+///   9. 让 PPSh-41 冲锋枪的枪托槽支持安装 M14 SAGE International M14ALCS (MOD-0) 枪托;
+///  10. 让 Aim Sports“三轨”的瞄具槽支持安装 M14 DCSB 瞄具基座;
+///  11. 让 Aim Sports“三轨”的第一个战术配件槽支持安装 SV-98 隔热带与 Fortis Shift 战术前握把;
+///  12. 让 Aim Sports“三轨”的第二个战术配件槽支持安装 SV-98 隔热带;
+///  13. 让 M14 SAGE International M14ALCS (MOD-0) 枪托的握把位支持安装 AR-15 Tactical Dynamics 镂空手枪式握把、
+///      Tyrant Designs MOD Chevron AR-15 镂空手枪式握把(黑 / 黄 / 红)与 AS VAL Rotor 43 手枪式握把附缓冲管转接器;
+///  14. 让 CR 50DS 转轮手枪的前准星槽支持安装 StormWerkz 顶盖导轨与 MP-18 瞄具基座;
+///  15. 让 CR 50DS 转轮手枪的战术设备槽支持安装 Zenit RK 系列前握把、KAC MWS 脚架转接器
+///      与 BT10 V8 Atlas 折叠脚架。
+///
+/// 做法:往目标槽的 SlotFilter.Filter(HashSet&lt;MongoId&gt;)追加物品 id(幂等)。
+/// </summary>
+[Injectable(InjectionType.Singleton, OnLoadOrder.Preload + 4)]
+public class WeaponCrossModdingPlugin(
+    ISptLogger<WeaponCrossModdingPlugin> logger,
+    TemplateTable templateTable) : IOnLoad
+{
+    private const string ScopeSlotName = "mod_scope";
+    private const string SightSlotName = "mod_sight_front";
+    private const string BarrelSlotName = "mod_barrel";
+    private const string StockSlotName = "mod_stock";
+    private const string TacticalSlotName = "mod_tactical";
+
+    // UZI StormWerkz 瞄具基座(顶盖导轨)
+    private const string StormwerkzTopCoverRailId = "6698c90829e062525d0ad8ad";
+
+    // ELCAN SpecterDR 1x/4x(黑)与 FDE 变体
+    private const string SpecterDrId = "57ac965c24597706be5f975c";
+    private const string SpecterDrFdeId = "57aca93d2459771f2c7e26db";
+
+    // SIG Sauer BRAVO4 4x30 瞄准镜
+    private const string Bravo4Id = "57adff4f24597737f373b6e6";
+
+    // CR 200DS 转轮手枪(Chiappa Rhino 200DS 9x19 revolver)—— 前准星槽。
+    private const string Cr200DsId = "624c2e8614da335f1e034d8c";
+
+    // CR 50DS 转轮手枪(Chiappa Rhino 50DS .357 revolver)—— 前准星槽与战术设备槽。
+    private const string Cr50DsId = "61a4c8884f95bc3b2c5dc96f";
+
+    // MP-18 瞄具基座
+    private const string Mp18ScopeBaseId = "61f804acfcba9556ea304cb8";
+
+    // KAC MWS 脚架转接器(自带 mod_bipod 槽)与 BT10 V8 Atlas 折叠脚架。
+    private const string KacMwsBipodAdapterId = "676175bb48fa5c377e06fc36";
+    private const string Bt10AtlasBipodId = "6644920d49817dc7d505ca71";
+
+    // PPSh-41 冲锋枪(承载枪管槽与枪托槽)。
+    private const string Ppsh41Id = "5ea03f7400685063ec28bfa8";
+
+    // 莫辛纳甘枪管(4 种尺寸)
+    private const string MosinBarrel200Id = "5bfd4cc90db834001d23e846"; // 200mm 锯短
+    private const string MosinBarrel220ThreadedId = "5bfd4cd60db834001c38f095"; // 220mm 锯短螺纹
+    private const string MosinBarrel514Id = "5bfd4cbe0db834001b73449f"; // 514mm 卡宾
+    private const string MosinBarrel730Id = "5ae09bff5acfc4001562219d"; // 730mm 标准
+
+    // PPSh-41 枪托槽兼容的枪托 / 握把。
+    private const string BenelliM3TelescopicStockId = "6259c3387d6aab70bc23a18d"; // Benelli M3 可伸缩枪托
+    private const string PkmWoodenStockId = "646371a9f2404ab67905c8e6"; // PKM 木制枪托
+    private const string PkZenitPt2StockId = "6492d7847363b8a52206bc52"; // Zenit PT-2 "Klassika" PK 机枪枪托
+    private const string PkpPolymerStockId = "6492e3a97df7d749100e29ee"; // PKP 聚合物枪托
+    private const string UltimaMp155PistolGripId = "606eef46232e5a31c233d500"; // Ultima MP-155 塑料手枪式握把
+    private const string Ks23MetalStockId = "5e848dc4e4dbc5266a4ec63d"; // KS-23 金属枪托(原版仅可装于 KS-23M 聚合物手枪式握把的 mod_stock 槽)
+
+    // M14 SAGE International M14ALCS (MOD-0) 枪托。
+    private const string M14AlcsButtstockId = "5addc7ac5acfc400194dbd90";
+
+    // M14 SAGE International DCSB 瞄具基座。
+    private const string M14DcsbMountId = "5addbffe5acfc4001714dfac";
+
+    // PPSh-41 防尘盖(mod_reciever 槽承载物品)。
+    private const string Ppsh41DustCoverId = "5ea03e5009aa976f2e7a514b";
+
+    // HUXWRX HX-QD 7.62x51 消音器(黑 / 黄褐色变体)—— 由 WTT-ContentBackport 注入。
+    private const string HuxwrxHxQdId = "6a158e4abf497aade10030e0";
+    private const string HuxwrxHxQdTanId = "6a1eb32c6cd328ea90037455";
+
+    // Aim Sports“三轨”莫辛步枪导轨;改第一个与第二个战术配件槽(mod_tactical_000 / mod_tactical_001)。
+    private const string AimSportsTriRailId = "5bbdb811d4351e45020113c7";
+    private const string AimSportsTriRailTacticalSlotName = "mod_tactical_000";
+    private const string AimSportsTriRailSecondTacticalSlotName = "mod_tactical_001";
+    private const string AimSportsTriRailLabel = "Aim Sports tri-rail";
+
+    // UZI StormWerkz 护木底轨(mod_tactical 槽)。
+    private const string StormwerkzLowerHandguardRailId = "66992f7d9950f5f4cd0602a8";
+    private const string StormwerkzLowerHandguardLabel = "UZI StormWerkz lower handguard rail";
+
+    // Zenit RK 系列前握把。
+    private static readonly string[] ZenitRkForegripIds =
+    [
+        "5c1bc4812e22164bef5cfde7", // RK-0
+        "5c1bc5612e221602b5429350", // RK-1
+        "5c1bc5af2e221602b412949b", // RK-2
+        "5c1bc5fb2e221602b1779b32", // RK-4
+        "5c1bc7432e221602b412949d", // RK-5
+        "5c1bc7752e221602b1779b34", // RK-6
+    ];
+
+    // Aim Sports“三轨”第一个战术配件槽兼容的前握把(RK 系列见上;不含 KeyMod / M-LOK 型)。
+    private static readonly string[] AimSportsTriRailForegripIds =
+    [
+        .. ZenitRkForegripIds,
+        // 镂空前握把
+        "5f6340d3ca442212f4047eb2", // Tactical Dynamics 镂空前握把
+        // 垂直前握把
+        "5c7fc87d2e221644f31c0298", // BCM GUNFIGHTER MOD 3 vertical
+        "5c87ca002e221600114cb150", // KAC vertical
+        "5cda9bcfd7f00c0c0b53e900", // ASh-12 vertical
+        // TangoDown Stubby BGV-MK46K
+        "558032614bdc2de7118b4585", // (Black)
+        "58c157be86f77403c74b2bb6", // (FDE)
+        "58c157c886f774032749fb06", // (Stealth Grey)
+    ];
+
+    // Aim Sports“三轨”第一 / 第二个战术配件槽兼容的其它配件。
+    private const string Sv98HeatRibbonId = "56083eab4bdc2d26448b456a"; // SV-98 隔热带(anti-heat ribbon)
+    private const string FortisShiftForegripId = "59f8a37386f7747af3328f06"; // Fortis Shift 战术前握把
+
+    // M14 SAGE International M14ALCS (MOD-0) 枪托的握把位兼容的握把。
+    private const string M14AlcsPistolGripSlotName = "mod_pistol_grip";
+    private const string TacticalDynamicsSkeletonizedGripId = "5b07db875acfc40dc528a5f6"; // AR-15 Tactical Dynamics 镂空手枪式握把
+
+    // Tyrant Designs MOD Chevron AR-15 镂空手枪式握把(黑 / 黄 / 红变体)—— 由 WTT-ContentBackport 注入。
+    private const string TyrantChevronGripBlackId = "6984b7d56be2752c150e6895";
+    private const string TyrantChevronGripYellowId = "698dac21772d6f3dc00e4284";
+    private const string TyrantChevronGripRedId = "6985eb089edef67ade080b72";
+
+    // AS VAL Rotor 43 手枪式握把附缓冲管转接器(自带 AR 规格缓冲管与 mod_stock_000 槽)。
+    private const string AsValRotor43GripId = "5a69a2ed8dc32e000d46d1f1";
+
+    // 日志中用于标识槽位承载者的短名。
+    private const string MountLabel = "mount";
+    private const string Cr200DsLabel = "CR 200DS";
+    private const string Cr50DsLabel = "CR 50DS";
+    private const string Ppsh41Label = "PPSh-41";
+    private const string M14ButtstockLabel = "M14ALCS (MOD-0) stock";
+
+    public Task OnLoadAsync(CancellationToken cancellationToken)
+    {
+        try
+        {
+            cancellationToken.ThrowIfCancellationRequested();
+
+            Dictionary<MongoId, TemplateItem> items = templateTable.Items;
+
+            // UZI StormWerkz 顶盖导轨的 mod_scope 槽:追加 SpecterDR 与 BRAVO4 瞄具。
+            AddItemIdsToSlot(items, StormwerkzTopCoverRailId, MountLabel, ScopeSlotName, SpecterDrId, SpecterDrFdeId, Bravo4Id);
+
+            // CR 200DS 前准星槽:追加 StormWerkz 顶盖导轨与 MP-18 瞄具基座。
+            AddItemIdsToSlot(items, Cr200DsId, Cr200DsLabel, SightSlotName, StormwerkzTopCoverRailId, Mp18ScopeBaseId);
+
+            // CR 50DS 前准星槽:追加 StormWerkz 顶盖导轨与 MP-18 瞄具基座。
+            AddItemIdsToSlot(items, Cr50DsId, Cr50DsLabel, SightSlotName, StormwerkzTopCoverRailId, Mp18ScopeBaseId);
+
+            // CR 50DS 战术设备槽:追加 Zenit RK 系列前握把、KAC MWS 脚架转接器与 BT10 V8 Atlas 折叠脚架。
+            AddItemIdsToSlot(items, Cr50DsId, Cr50DsLabel, TacticalSlotName, [.. ZenitRkForegripIds, KacMwsBipodAdapterId, Bt10AtlasBipodId]);
+
+            // PPSh-41 枪管槽:追加莫辛纳甘的全部尺寸枪管。
+            AddItemIdsToSlot(items, Ppsh41Id, Ppsh41Label, BarrelSlotName, MosinBarrel200Id, MosinBarrel220ThreadedId, MosinBarrel514Id, MosinBarrel730Id);
+
+            // PPSh-41 枪托槽:追加 Benelli M3 可伸缩枪托、PKM / PKP 枪托、Ultima MP-155 握把、
+            // KS-23 金属枪托,以及 M14 SAGE International M14ALCS (MOD-0) 枪托。
+            AddItemIdsToSlot(items, Ppsh41Id, Ppsh41Label, StockSlotName, BenelliM3TelescopicStockId, PkmWoodenStockId, PkZenitPt2StockId, PkpPolymerStockId, UltimaMp155PistolGripId, Ks23MetalStockId, M14AlcsButtstockId);
+
+            // PPSh-41 防尘盖与 HUXWRX HX-QD 消音器互不兼容。
+            AddDustCoverSuppressorConflict(items);
+
+            // Aim Sports“三轨”的第一个战术配件槽:追加多种前握把、SV-98 隔热带与 Fortis Shift 前握把。
+            AddItemIdsToSlot(items, AimSportsTriRailId, AimSportsTriRailLabel, AimSportsTriRailTacticalSlotName, [.. AimSportsTriRailForegripIds, Sv98HeatRibbonId, FortisShiftForegripId]);
+
+            // Aim Sports“三轨”的第二个战术配件槽:追加 SV-98 隔热带。
+            AddItemIdsToSlot(items, AimSportsTriRailId, AimSportsTriRailLabel, AimSportsTriRailSecondTacticalSlotName, Sv98HeatRibbonId);
+
+            // Aim Sports“三轨”的瞄具槽:追加 M14 DCSB 瞄具基座。
+            AddItemIdsToSlot(items, AimSportsTriRailId, AimSportsTriRailLabel, ScopeSlotName, M14DcsbMountId);
+
+            // M14ALCS (MOD-0) 枪托的握把位:追加 AR-15 Tactical Dynamics 镂空手枪式握把、
+            // Tyrant Designs MOD Chevron 镂空手枪式握把(黑 / 黄 / 红)与 AS VAL Rotor 43 手枪式握把。
+            AddItemIdsToSlot(items, M14AlcsButtstockId, M14ButtstockLabel, M14AlcsPistolGripSlotName,
+                TacticalDynamicsSkeletonizedGripId, TyrantChevronGripBlackId, TyrantChevronGripYellowId, TyrantChevronGripRedId, AsValRotor43GripId);
+
+            // UZI StormWerkz 护木底轨的 mod_tactical 槽:追加 Zenit RK 系列前握把。
+            AddItemIdsToSlot(items, StormwerkzLowerHandguardRailId, StormwerkzLowerHandguardLabel, TacticalSlotName, ZenitRkForegripIds);
+        }
+        catch (Exception ex)
+        {
+            logger.Error("WeaponCrossModding failed: " + ex.Message);
+        }
+
+        return Task.CompletedTask;
+    }
+
+    /// <summary>
+    /// 往 <paramref name="ownerId"/> 名为 <paramref name="slotName"/> 的槽的各 Filter 追加 <paramref name="itemIds"/>(幂等)。
+    /// </summary>
+    private void AddItemIdsToSlot(
+        Dictionary<MongoId, TemplateItem> items,
+        string ownerId,
+        string ownerLabel,
+        string slotName,
+        params string[] itemIds)
+    {
+        if (!items.TryGetValue(ownerId, out TemplateItem? owner))
+        {
+            logger.Warning($"WeaponCrossModding: {ownerLabel} id '{ownerId}' not found in Items");
+            return;
+        }
+
+        IEnumerable<Slot>? slots = owner.Properties?.Slots;
+        if (slots is null)
+        {
+            logger.Warning($"WeaponCrossModding: {ownerLabel} has no slots");
+            return;
+        }
+
+        foreach (Slot slot in slots.Where(s => s is not null && string.Equals(s.Name, slotName, StringComparison.OrdinalIgnoreCase)))
+        {
+            IEnumerable<SlotFilter>? filters = slot.Properties?.Filters;
+            if (filters is null)
+            {
+                continue;
+            }
+
+            foreach (SlotFilter filter in filters)
+            {
+                foreach (string itemId in itemIds)
+                {
+                    AddToFilter(filter, itemId, owner, slot);
+                }
+            }
+        }
+    }
+
+    /// <summary>
+    /// 让 PPSh-41 防尘盖与 HUXWRX HX-QD 消音器(含黄褐色变体)互不兼容(幂等)。
+    /// 防尘盖为原版物品、必定存在;消音器由 WTT-ContentBackport 注入,若不在 Items 中则跳过
+    /// (防尘盖侧足以建立冲突,且避开了第三方 mod 的加载时序依赖)。
+    /// </summary>
+    private void AddDustCoverSuppressorConflict(Dictionary<MongoId, TemplateItem> items)
+    {
+        AddConflictingItems(items, Ppsh41DustCoverId, "PPSh-41 dust cover", HuxwrxHxQdId, HuxwrxHxQdTanId);
+        AddConflictingItems(items, HuxwrxHxQdId, "HUXWRX HX-QD", Ppsh41DustCoverId);
+        AddConflictingItems(items, HuxwrxHxQdTanId, "HUXWRX HX-QD (Tan)", Ppsh41DustCoverId);
+    }
+
+    /// <summary>
+    /// 往 <paramref name="ownerId"/> 的 ConflictingItems 追加 <paramref name="conflictIds"/>(幂等)。
+    /// </summary>
+    private void AddConflictingItems(
+        Dictionary<MongoId, TemplateItem> items,
+        string ownerId,
+        string ownerLabel,
+        params string[] conflictIds)
+    {
+        if (!items.TryGetValue(ownerId, out TemplateItem? owner))
+        {
+            logger.Debug($"WeaponCrossModding: {ownerLabel} id '{ownerId}' not in Items, skip conflicting items");
+            return;
+        }
+
+        owner.Properties ??= new TemplateItemProperties();
+        owner.Properties.ConflictingItems ??= new HashSet<MongoId>();
+
+        foreach (string conflictId in conflictIds)
+        {
+            if (owner.Properties.ConflictingItems.Add(conflictId))
+            {
+                logger.Info($"WeaponCrossModding: added conflicting item '{conflictId}' to '{ownerLabel}' ({owner.Name})");
+            }
+            else
+            {
+                logger.Debug($"WeaponCrossModding: conflicting item '{conflictId}' already on '{ownerLabel}' ({owner.Name})");
+            }
+        }
+    }
+
+    private void AddToFilter(SlotFilter? filter, string itemId, TemplateItem parent, Slot slot)
+    {
+        if (filter is null)
+        {
+            return;
+        }
+
+        filter.Filter ??= new HashSet<MongoId>();
+
+        if (filter.Filter.Add(itemId))
+        {
+            logger.Info($"WeaponCrossModding: added '{itemId}' to slot '{slot.Name}' ({parent.Name})");
+        }
+        else
+        {
+            logger.Debug($"WeaponCrossModding: '{itemId}' already in slot '{slot.Name}' ({parent.Name})");
+        }
+    }
+}

+ 38 - 0
src/ModMetadata.cs

@@ -0,0 +1,38 @@
+using System.Collections.Generic;
+using SPTarkov.Server.Core.Models.Spt.Mod;
+using Ver = SemanticVersioning.Version;
+using Rng = SemanticVersioning.Range;
+
+namespace Pj568.WeaponCrossModding;
+
+/// <summary>
+/// 元数据:SPT 4.1.x 借此识别本 mod(版本取自程序集版本号)。
+/// 4.1.x 把旧的 AbstractModMetadata 抽象类替换为 IModMetadata 接口,
+/// 并删除了 IsBundleMod(bundles 通过 bundles.json 自动加载),
+/// 新增 HasPrepatcher 字段;License 收紧为非空。
+/// </summary>
+public class WeaponCrossModdingMetadata : IModMetadata
+{
+    public string ModGuid { get; init; } = "com.pj568.weaponcrossmodding";
+
+    public string Name { get; init; } = "PJ568's Weapon Cross Modding";
+
+    public string Author { get; init; } = "PJ568";
+
+    public List<string>? Contributors { get; init; }
+
+    public Ver Version { get; init; } =
+        new(typeof(WeaponCrossModdingMetadata).Assembly.GetName().Version?.ToString(3) ?? "0.1.0");
+
+    public Rng SptVersion { get; init; } = new("~4.1.0");
+
+    public bool HasPrepatcher { get; init; } = false;
+
+    public List<string>? Incompatibilities { get; init; }
+
+    public Dictionary<string, Rng>? ModDependencies { get; init; }
+
+    public string? Url { get; init; }
+
+    public string License { get; init; } = "MIT";
+}

+ 364 - 0
tests/WeaponCrossModding.Tests/ModTests.cs

@@ -0,0 +1,364 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Moq;
+using SPTarkov.Common.Models.Logging;
+using SPTarkov.Server.Core.Models.Common;
+using SPTarkov.Server.Core.Models.Eft.Common.Tables;
+using SPTarkov.Server.Core.Models.Spt.Tables;
+
+namespace Pj568.WeaponCrossModding.Tests;
+
+/// <summary>
+/// 针对 <see cref="WeaponCrossModdingPlugin"/> 的单元测试:
+/// 用最小的物品/槽位夹具直接驱动 <c>OnLoadAsync</c>,断言目标槽 Filter 的注入与幂等。
+/// 物品 id 与 src/Mod.cs 中的常量保持一致;若上游数据 id 变更,这里会先失败。
+/// </summary>
+public class WeaponCrossModdingPluginTests
+{
+    private const string Ppsh41Id = "5ea03f7400685063ec28bfa8";
+    private const string Ppsh41BarrelId = "5ea02bb600685063ec28bfa1";
+    private const string StormwerkzRailId = "6698c90829e062525d0ad8ad";
+    private const string SpecterDrId = "57ac965c24597706be5f975c";
+    private const string SpecterDrFdeId = "57aca93d2459771f2c7e26db";
+    private const string Bravo4Id = "57adff4f24597737f373b6e6";
+    private const string Cr200DsId = "624c2e8614da335f1e034d8c";
+    private const string Cr50DsId = "61a4c8884f95bc3b2c5dc96f";
+    private const string Mp18Id = "61f804acfcba9556ea304cb8";
+    private const string KacMwsBipodAdapterId = "676175bb48fa5c377e06fc36";
+    private const string Bt10AtlasBipodId = "6644920d49817dc7d505ca71";
+
+    private static readonly string[] MosinBarrelIds =
+    [
+        "5bfd4cc90db834001d23e846",
+        "5bfd4cd60db834001c38f095",
+        "5bfd4cbe0db834001b73449f",
+        "5ae09bff5acfc4001562219d",
+    ];
+
+    private const string Ppsh41StockId = "5ea03e9400685063ec28bfa4";
+
+    private static readonly string[] Ppsh41StockCompatIds =
+    [
+        "6259c3387d6aab70bc23a18d",
+        "646371a9f2404ab67905c8e6",
+        "6492d7847363b8a52206bc52",
+        "6492e3a97df7d749100e29ee",
+        "606eef46232e5a31c233d500",
+        "5e848dc4e4dbc5266a4ec63d",
+        "5addc7ac5acfc400194dbd90", // M14ALCS (MOD-0) 枪托
+    ];
+
+    private const string Ppsh41DustCoverId = "5ea03e5009aa976f2e7a514b";
+    private const string HuxwrxHxQdId = "6a158e4abf497aade10030e0";
+    private const string HuxwrxHxQdTanId = "6a1eb32c6cd328ea90037455";
+
+    private const string AimSportsTriRailId = "5bbdb811d4351e45020113c7";
+    private const string StormwerkzLowerHandguardRailId = "66992f7d9950f5f4cd0602a8";
+
+    private const string M14DcsbMountId = "5addbffe5acfc4001714dfac";
+
+    private const string Sv98HeatRibbonId = "56083eab4bdc2d26448b456a";
+    private const string FortisShiftForegripId = "59f8a37386f7747af3328f06";
+    private const string M14AlcsButtstockId = "5addc7ac5acfc400194dbd90";
+    private const string M14AlcsPistolGripId = "5addc7db5acfc4001669f279";
+
+    // 与 src/Mod.cs 对应:M14ALCS (MOD-0) 枪托握把位的新增握把。
+    private static readonly string[] M14AlcsPistolGripCompatIds =
+    [
+        "5b07db875acfc40dc528a5f6", // AR-15 Tactical Dynamics 镂空手枪式握把
+        "6984b7d56be2752c150e6895", // Tyrant Designs MOD Chevron 镂空手枪式握把(黑)
+        "698dac21772d6f3dc00e4284", // Tyrant Designs MOD Chevron 镂空手枪式握把(黄)
+        "6985eb089edef67ade080b72", // Tyrant Designs MOD Chevron 镂空手枪式握把(红)
+        "5a69a2ed8dc32e000d46d1f1", // AS VAL Rotor 43 手枪式握把附缓冲管转接器
+    ];
+
+    // 与 src/Mod.cs 的 ZenitRkForegripIds 对应。
+    private static readonly string[] ZenitRkForegripIds =
+    [
+        "5c1bc4812e22164bef5cfde7",
+        "5c1bc5612e221602b5429350",
+        "5c1bc5af2e221602b412949b",
+        "5c1bc5fb2e221602b1779b32",
+        "5c1bc7432e221602b412949d",
+        "5c1bc7752e221602b1779b34",
+    ];
+
+    // 与 src/Mod.cs 的 AimSportsTriRailForegripIds 对应(不含 MP9 与 Steyr AUG,也不含 KeyMod / M-LOK 型)。
+    private static readonly string[] AimSportsTriRailForegripIds =
+    [
+        "5c1bc4812e22164bef5cfde7",
+        "5c1bc5612e221602b5429350",
+        "5c1bc5af2e221602b412949b",
+        "5c1bc5fb2e221602b1779b32",
+        "5c1bc7432e221602b412949d",
+        "5c1bc7752e221602b1779b34",
+        "5f6340d3ca442212f4047eb2",
+        "5c7fc87d2e221644f31c0298",
+        "5c87ca002e221600114cb150",
+        "5cda9bcfd7f00c0c0b53e900",
+        "558032614bdc2de7118b4585",
+        "58c157be86f77403c74b2bb6",
+        "58c157c886f774032749fb06",
+    ];
+
+    private static WeaponCrossModdingPlugin BuildPlugin(Dictionary<MongoId, TemplateItem> items)
+    {
+        var logger = new Mock<ISptLogger<WeaponCrossModdingPlugin>>();
+        return new WeaponCrossModdingPlugin(logger.Object, CreateTemplateTable(items));
+    }
+
+    // TemplateTable(NuGet 4.1.2)带多个 required 成员,测试只关心 Items;
+    // 用反射实例化以绕过编译期 required 校验。
+    private static TemplateTable CreateTemplateTable(Dictionary<MongoId, TemplateItem> items)
+    {
+        var table = (TemplateTable)Activator.CreateInstance(typeof(TemplateTable))!;
+        typeof(TemplateTable).GetProperty(nameof(TemplateTable.Items))!.SetValue(table, items);
+        return table;
+    }
+
+    private static TemplateItem ItemWithSlot(string name, string slotName, params string[] initialFilter)
+    {
+        var filter = new SlotFilter
+        {
+            Filter = new HashSet<MongoId>(initialFilter.Select(id => new MongoId(id))),
+        };
+        var slot = new Slot
+        {
+            Name = slotName,
+            Properties = new SlotProperties { Filters = [filter] },
+        };
+        return new TemplateItem
+        {
+            Name = name,
+            Properties = new TemplateItemProperties { Slots = [slot] },
+        };
+    }
+
+    private static TemplateItem ItemWithConflicts(string name) => new()
+    {
+        Name = name,
+        Properties = new TemplateItemProperties { ConflictingItems = [] },
+    };
+
+    private static HashSet<MongoId> FilterOf(TemplateItem item, string slotName) =>
+        item.Properties!.Slots!.Single(s => s.Name == slotName).Properties!.Filters!.Single().Filter!;
+
+    [Fact]
+    public async Task AddsAllMosinBarrelsToPpsh41BarrelSlot()
+    {
+        var ppsh = ItemWithSlot("weapon_zis_ppsh41_762x25", "mod_barrel", Ppsh41BarrelId);
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(Ppsh41Id)] = ppsh };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(ppsh, "mod_barrel");
+        Assert.Contains(new MongoId(Ppsh41BarrelId), filter);
+        foreach (var id in MosinBarrelIds)
+        {
+            Assert.Contains(new MongoId(id), filter);
+        }
+
+        Assert.Equal(1 + MosinBarrelIds.Length, filter.Count);
+    }
+
+    [Fact]
+    public async Task IsIdempotentWhenLoadedTwice()
+    {
+        var ppsh = ItemWithSlot("weapon_zis_ppsh41_762x25", "mod_barrel", Ppsh41BarrelId);
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(Ppsh41Id)] = ppsh };
+        var plugin = BuildPlugin(items);
+
+        await plugin.OnLoadAsync(CancellationToken.None);
+        await plugin.OnLoadAsync(CancellationToken.None);
+
+        Assert.Equal(1 + MosinBarrelIds.Length, FilterOf(ppsh, "mod_barrel").Count);
+    }
+
+    [Fact]
+    public async Task AddsScopesToStormwerkzMountScopeSlot()
+    {
+        var mount = ItemWithSlot("mount_uzi_stormwerkz_top_cover_rail", "mod_scope");
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(StormwerkzRailId)] = mount };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(mount, "mod_scope");
+        Assert.Contains(new MongoId(SpecterDrId), filter);
+        Assert.Contains(new MongoId(SpecterDrFdeId), filter);
+        Assert.Contains(new MongoId(Bravo4Id), filter);
+        Assert.Equal(3, filter.Count);
+    }
+
+    [Fact]
+    public async Task AddsMountsToCr200DsSightSlot()
+    {
+        var revolver = ItemWithSlot("weapon_chiappa_rhino_200ds_9x19", "mod_sight_front");
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(Cr200DsId)] = revolver };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(revolver, "mod_sight_front");
+        Assert.Contains(new MongoId(StormwerkzRailId), filter);
+        Assert.Contains(new MongoId(Mp18Id), filter);
+        Assert.Equal(2, filter.Count);
+    }
+
+    [Fact]
+    public async Task AddsMountsToCr50DsSightSlot()
+    {
+        var revolver = ItemWithSlot("weapon_chiappa_rhino_50ds_9x33R", "mod_sight_front");
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(Cr50DsId)] = revolver };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(revolver, "mod_sight_front");
+        Assert.Contains(new MongoId(StormwerkzRailId), filter);
+        Assert.Contains(new MongoId(Mp18Id), filter);
+        Assert.Equal(2, filter.Count);
+    }
+
+    [Fact]
+    public async Task AddsPartsToCr50DsTacticalSlot()
+    {
+        var revolver = ItemWithSlot("weapon_chiappa_rhino_50ds_9x33R", "mod_tactical");
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(Cr50DsId)] = revolver };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(revolver, "mod_tactical");
+        foreach (var id in ZenitRkForegripIds)
+        {
+            Assert.Contains(new MongoId(id), filter);
+        }
+
+        Assert.Contains(new MongoId(KacMwsBipodAdapterId), filter);
+        Assert.Contains(new MongoId(Bt10AtlasBipodId), filter);
+        Assert.Equal(ZenitRkForegripIds.Length + 2, filter.Count);
+    }
+
+    [Fact]
+    public async Task AddsStocksToPpsh41StockSlot()
+    {
+        var ppsh = ItemWithSlot("weapon_zis_ppsh41_762x25", "mod_stock", Ppsh41StockId);
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(Ppsh41Id)] = ppsh };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(ppsh, "mod_stock");
+        Assert.Contains(new MongoId(Ppsh41StockId), filter);
+        foreach (var id in Ppsh41StockCompatIds)
+        {
+            Assert.Contains(new MongoId(id), filter);
+        }
+
+        Assert.Equal(1 + Ppsh41StockCompatIds.Length, filter.Count);
+    }
+
+    [Fact]
+    public async Task MakesPpsh41DustCoverConflictWithHuxwrxSuppressors()
+    {
+        var dustCover = ItemWithConflicts("PPSH-41 dust cover");
+        var black = ItemWithConflicts("HUXWRX HX-QD 7.62x51 sound suppressor");
+        var tan = ItemWithConflicts("HUXWRX HX-QD 7.62x51 sound suppressor (Tan)");
+        var items = new Dictionary<MongoId, TemplateItem>
+        {
+            [new MongoId(Ppsh41DustCoverId)] = dustCover,
+            [new MongoId(HuxwrxHxQdId)] = black,
+            [new MongoId(HuxwrxHxQdTanId)] = tan,
+        };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        Assert.Contains(new MongoId(HuxwrxHxQdId), dustCover.Properties!.ConflictingItems!);
+        Assert.Contains(new MongoId(HuxwrxHxQdTanId), dustCover.Properties!.ConflictingItems!);
+        Assert.Contains(new MongoId(Ppsh41DustCoverId), black.Properties!.ConflictingItems!);
+        Assert.Contains(new MongoId(Ppsh41DustCoverId), tan.Properties!.ConflictingItems!);
+    }
+
+    [Fact]
+    public async Task AddsPartsToAimSportsTriRailFirstTacticalSlot()
+    {
+        var rail = ItemWithSlot("mount_mosin_aim_sports_tri_rail", "mod_tactical_000");
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(AimSportsTriRailId)] = rail };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(rail, "mod_tactical_000");
+        Assert.Equal(AimSportsTriRailForegripIds.Length + 2, filter.Count);
+        foreach (var id in AimSportsTriRailForegripIds)
+        {
+            Assert.Contains(new MongoId(id), filter);
+        }
+
+        Assert.Contains(new MongoId(Sv98HeatRibbonId), filter);
+        Assert.Contains(new MongoId(FortisShiftForegripId), filter);
+    }
+
+    [Fact]
+    public async Task AddsPartsToAimSportsTriRailSecondTacticalSlot()
+    {
+        var rail = ItemWithSlot("mount_mosin_aim_sports_tri_rail", "mod_tactical_001");
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(AimSportsTriRailId)] = rail };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(rail, "mod_tactical_001");
+        Assert.Contains(new MongoId(Sv98HeatRibbonId), filter);
+        Assert.Single(filter);
+    }
+
+    [Fact]
+    public async Task AddsGripsToM14AlcsButtstockPistolGripSlot()
+    {
+        var buttstock = ItemWithSlot("stock_m14_sage_ebr_m14alcs_buttstock", "mod_pistol_grip", M14AlcsPistolGripId);
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(M14AlcsButtstockId)] = buttstock };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(buttstock, "mod_pistol_grip");
+        Assert.Contains(new MongoId(M14AlcsPistolGripId), filter);
+        foreach (var id in M14AlcsPistolGripCompatIds)
+        {
+            Assert.Contains(new MongoId(id), filter);
+        }
+
+        Assert.Equal(1 + M14AlcsPistolGripCompatIds.Length, filter.Count);
+    }
+
+    [Fact]
+    public async Task AddsZenitRkForegripsToStormwerkzLowerHandguardRail()
+    {
+        var rail = ItemWithSlot("handguard_uzi_stormwerkz_lower_rail", "mod_tactical");
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(StormwerkzLowerHandguardRailId)] = rail };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(rail, "mod_tactical");
+        Assert.Equal(ZenitRkForegripIds.Length, filter.Count);
+        foreach (var id in ZenitRkForegripIds)
+        {
+            Assert.Contains(new MongoId(id), filter);
+        }
+    }
+
+    [Fact]
+    public async Task AddsM14DcsbMountToTriRailScopeSlot()
+    {
+        var rail = ItemWithSlot("mount_mosin_aim_sports_tri_rail", "mod_scope");
+        var items = new Dictionary<MongoId, TemplateItem> { [new MongoId(AimSportsTriRailId)] = rail };
+
+        await BuildPlugin(items).OnLoadAsync(CancellationToken.None);
+
+        var filter = FilterOf(rail, "mod_scope");
+        Assert.Single(filter);
+        Assert.Contains(new MongoId(M14DcsbMountId), filter);
+    }
+
+    [Fact]
+    public async Task MissingItemsDoNotThrow()
+    {
+        await BuildPlugin(new Dictionary<MongoId, TemplateItem>()).OnLoadAsync(CancellationToken.None);
+    }
+}

+ 26 - 0
tests/WeaponCrossModding.Tests/WeaponCrossModding.Tests.csproj

@@ -0,0 +1,26 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <TargetFramework>net10.0</TargetFramework>
+    <ImplicitUsings>enable</ImplicitUsings>
+    <Nullable>enable</Nullable>
+    <IsPackable>false</IsPackable>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <PackageReference Include="coverlet.collector" Version="6.0.4" />
+    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
+    <PackageReference Include="Moq" Version="4.21.0" />
+    <PackageReference Include="xunit" Version="2.9.3" />
+    <PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <Using Include="Xunit" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <ProjectReference Include="..\..\WeaponCrossModding.csproj" />
+  </ItemGroup>
+
+</Project>