From 237271feb930b24a1a00df3eee1816a92855373b Mon Sep 17 00:00:00 2001 From: mcocdaa Date: Mon, 23 Nov 2026 06:44:53 +0100 Subject: [PATCH] refactor(bridge-rimtalk): resolve enums by name, fix About dependencies, and remove obsolete coordinator refactor: delegate bridge plumbing to Core and resolve RimTalk enums by name Replace local reflection/registration plumbing with RimMind-Core helpers (ExternalModBridgeCoordinator, ReflectionAccessor, SoftDependencyDetector) and resolve RimTalk enum members by name instead of hardcoded integer values, so the bridge no longer breaks when RimTalk reorders its enums. - RimTalkApiShim: drop the one-shot type resolution cache in favor of Accessor.GetCachedType; add TryResolveEnumValue and warn-once when a nested enum or member is missing; AddPromptEntry/RegisterPawnHook now take role/position/operation names ("System", "Relative", "Append"). - ContextPullBridge: only set IsRegistered after the provider actually registers, honor both enableContextPull and pullRimTalkHistory, and format role labels from ToString() instead of int mapping. - RimMindProviderReader: null-pawn and missing-provider short-circuit, per-category warn-once via a concurrent set, plus ResetForTesting. - Debug actions: report source providers and registered context keys with owner mods instead of scanning RimMind provider categories. - Remove BridgeModuleCoordinator, the csproj deploy target, and deploy-single.sh; deploy-single.ps1 now builds per GameVersion and mirrors with robocopy while excluding Core/Newtonsoft assemblies. - Tests: cover null pawns, missing nested enums, IsRegistered boundaries, real enum names, and add RimTalk.Data role stubs. - CI: trigger on IntegrationTests changes and allow manual dispatch. - Docs: rewrite README/AGENTS/About to describe dialogue gating and bidirectional context instead of bubble pipeline harmonization. --- .../skills/rimworld-mod-dev/SKILL.md | 616 ------------------ .github/workflows/test.yml | 3 + AGENTS.md | 50 +- About/About.xml | 27 +- INTRODUCTION.txt | 71 -- README.md | 42 +- README_zh.md | 42 +- Source/Bridge/BridgeModuleCoordinator.cs | 34 - Source/Bridge/ContextPullBridge.cs | 30 +- Source/Bridge/ContextPushBridge.cs | 4 +- Source/Bridge/PersonaPushBridge.cs | 4 +- Source/Bridge/RimMindProviderReader.cs | 35 +- Source/Bridge/RimTalkApiShim.cs | 138 ++-- .../BridgeRimTalkBehaviorAutotestSuite.cs | 1 - Source/Debug/BridgeRimTalkDebugActions.cs | 24 +- Source/RimMindBridgeRimTalk.csproj | 12 - .../Contracts/RimTalkGateContextContracts.cs | 36 +- .../RimTalkSettingsCompatibilityContracts.cs | 24 +- Tests/README.md | 17 +- Tests/RimTalkStubs.cs | 21 +- script/deploy-single.ps1 | 121 ++-- script/deploy-single.sh | 95 --- 22 files changed, 373 insertions(+), 1074 deletions(-) delete mode 100644 .claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md delete mode 100644 INTRODUCTION.txt delete mode 100644 Source/Bridge/BridgeModuleCoordinator.cs delete mode 100644 script/deploy-single.sh diff --git a/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md b/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md deleted file mode 100644 index 1b3829a..0000000 --- a/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md +++ /dev/null @@ -1,616 +0,0 @@ ---- -name: rimworld-mod-dev -description: This skill should be used when developing RimWorld mods, including creating C# Harmony patches, writing XML Defs, implementing AI integration for pawns or events, setting up mod structure, or debugging RimWorld mod issues. Activates for "rimworld mod", "harmony patch", "pawncomp", "incidentdef", "thinkTree", "storyteller", "jobgiver", "hediff", "defmodextension" topics. -version: 1.0.0 ---- - -# RimWorld Mod Development Skill - -This skill provides guidance for developing RimWorld mods, with a focus on C#/Harmony-based behavior modification and AI integration patterns. - ---- - -## Project Context - -- **Game version**: 1.5 / 1.6 -- **Target framework**: .NET Framework 4.8 (net48) -- **Required dependency**: Harmony (brrainz.harmony) - ---- - -## Mod Folder Structure - -``` -MyMod/ -├── About/ -│ ├── About.xml # Required: mod metadata, dependencies, supported versions -│ └── Preview.png # Required: 640x360 or 1280x720, < 1MB -├── Assemblies/ # Compiled DLL files -├── Defs/ # XML definitions (ThingDef, IncidentDef, etc.) -├── Patches/ # PatchOperations XML (safe cross-mod patching) -├── Languages/ # Localization files -│ └── English/ -│ └── Keyed/ -│ └── Keys.xml # Translation keys -├── Sounds/ # .ogg audio files -├── Textures/ # .png texture files (must be PoT: 32x32, 64x64, etc.) -├── Source/ # C# source code (not loaded by game) -│ └── MyMod/ -│ ├── MyModMain.cs -│ └── ... -└── LoadFolders.xml # Optional: conditional folder loading per version -``` - ---- - -## Core Technology Stack - -| Tech | Purpose | Notes | -|------|---------|-------| -| **Harmony** | Runtime method patching | Use PostFix over Prefix to reduce conflicts | -| **C# async/await** | AI API calls | Never block game main thread | -| **ConcurrentQueue** | Thread-safe result passing | Main thread consumes on next Tick | -| **ThingComp** | Per-pawn state storage | Serialized via ExposeData | -| **DefModExtension** | Extend XML Def fields | No C# subclassing needed | -| **Newtonsoft.Json** | JSON parsing | Already bundled in RimWorld | - ---- - -## AI Integration Pattern - -```csharp -// 1. Harmony patch on TickManager - runs every game tick -[HarmonyPatch(typeof(TickManager), "DoSingleTick")] -public static class TickManagerPatch -{ - static void Postfix() - { - // Consume AI results from queue (main thread safe) - while (AIRequestQueue.Results.TryDequeue(out var result)) - result.Apply(); - - // Enqueue new requests (triggers async AI call) - if (ShouldQueryAI()) - AIRequestQueue.Enqueue(new AIRequest(BuildContext())); - } -} - -// 2. Async AI call (runs on background thread) -public static async Task QueryAI(AIRequest request) -{ - var response = await httpClient.PostAsync(endpoint, content); - var result = ParseResponse(await response.Content.ReadAsStringAsync()); - AIRequestQueue.Results.Enqueue(result); -} -``` - ---- - -## Key Game Systems & How to Hook Them - -### Pawn Behavior (Jobs / ThinkTree) - -```csharp -// Force a pawn to do a specific job -pawn.jobs.StartJob(new Job(JobDefOf.GotoWander, targetCell), JobCondition.InterruptForced); - -// Hook into job giving (Harmony prefix on JobGiver_Work) -[HarmonyPatch(typeof(JobGiver_Work), "TryGiveJob")] -static void Postfix(Pawn pawn, ref Job __result) -{ - if (AIController.ShouldOverride(pawn)) - __result = AIController.GetAIJob(pawn); -} -``` - -### Incidents / Storyteller - -```csharp -// Custom StorytellerComp - AI selects which incident to fire -public class StorytellerComp_AIDirector : StorytellerComp -{ - public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) - { - var chosen = AIDirector.GetNextIncident(target); // reads from result queue - if (chosen != null) - yield return new FiringIncident(chosen, this); - } -} -``` - -XML registration: -```xml - - AIDirectorStoryteller - -
  • - - -``` - -### Thoughts / Mood - -```csharp -// Add a thought (affects mood) -pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SomeThought); - -// Remove a thought -pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDef(thoughtDef); -``` - -### Mental States - -```csharp -// Trigger mental break -pawn.mindState.mentalStateHandler.TryStartMentalState( - MentalStateDefOf.Berserk, forceWake: true); -``` - -### Faction Relations - -```csharp -Faction.OfPlayer.TryAffectGoodwillWith(otherFaction, delta: 15, - lookTarget: pawn, reason: HistoryEventDefOf.GiftsGiven); -``` - ---- - -## ThingComp Pattern (Per-Pawn State) - -```csharp -// 1. Properties class -public class CompProperties_AIController : CompProperties -{ - public CompProperties_AIController() => compClass = typeof(CompAIController); -} - -// 2. Comp class with save/load -public class CompAIController : ThingComp -{ - public bool AIEnabled = false; - public string LastAIDecision = ""; - - public override void ExposeData() - { - base.ExposeData(); - Scribe_Values.Look(ref AIEnabled, "aiEnabled", false); - Scribe_Values.Look(ref LastAIDecision, "lastAIDecision", ""); - } -} - -// 3. XML patch to add comp to all Pawns -// Patches/AddAIComp.xml -``` - -```xml - - - /Defs/ThingDef[thingClass="Pawn"]/comps - -
  • - - - -``` - ---- - -## Harmony Patch Patterns - -```csharp -// PostFix: runs after original method, can modify result -[HarmonyPatch(typeof(TargetClass), "MethodName")] -public static class MyPatch -{ - static void Postfix(ref ReturnType __result, Pawn __instance, OtherParam param) - { - // __result = modified return value - // __instance = the object the method was called on - } -} - -// Prefix: runs before original, can skip original with return false -[HarmonyPatch(typeof(TargetClass), "MethodName")] -public static class MyPatch -{ - static bool Prefix(ref ReturnType __result, Pawn __instance) - { - if (ShouldSkip(__instance)) - { - __result = myResult; - return false; // skip original - } - return true; // run original - } -} -``` - ---- - -## About.xml Template - -```xml - - - My Mod - YourName - YourName.MyMod - -
  • 1.5
  • -
  • 1.6
  • - - My awesome mod. - -
  • - brrainz.harmony - Harmony - steam://url/CommunityFilePage/2009463077 -
  • -
    - -
  • brrainz.harmony
  • -
    - -``` - ---- - -## Mod Entry Point Pattern - -```csharp -using HarmonyLib; -using Verse; - -namespace MyMod -{ - public class MyModMain : Mod - { - public static MyModSettings Settings; - - public MyModMain(ModContentPack content) : base(content) - { - Settings = GetSettings(); - new Harmony("YourName.MyMod").PatchAll(); - } - - public override string SettingsCategory() => "My Mod"; - public override void DoSettingsWindowContents(Rect rect) - => Settings.DoWindowContents(rect); - } - - public class MyModSettings : ModSettings - { - public string ApiKey = ""; - public string Model = "gpt-4o-mini"; - public int CooldownTicks = 2500; // ~1 game hour - - public override void ExposeData() - { - Scribe_Values.Look(ref ApiKey, "apiKey", ""); - Scribe_Values.Look(ref Model, "model", "gpt-4o-mini"); - Scribe_Values.Look(ref CooldownTicks, "cooldownTicks", 2500); - } - } -} -``` - ---- - -## AI Context Building (Game State → Prompt) - -Key game state to include in AI prompts: - -```csharp -public static string BuildGameContext(Map map) -{ - var sb = new StringBuilder(); - // Colony stats - sb.AppendLine($"Colonists: {map.mapPawns.FreeColonists.Count}"); - sb.AppendLine($"Food: {map.resourceCounter.GetCount(ThingDefOf.MealSimple)}"); - sb.AppendLine($"Threat: {StorytellerUtility.GetThreatBiggestGoodwill(Faction.OfPlayer)}"); - // Recent events (from WorldComponent history) - // Current threats - foreach (var raid in map.attackTargetsCache.TargetsHostileToColony) - sb.AppendLine($"Threat: {raid.Thing.Label}"); - return sb.ToString(); -} -``` - ---- - -## Common XML Def Types - -| Def | Purpose | -|-----|---------| -| `ThingDef` (thingClass=Pawn) | Pawn/creature definition | -| `IncidentDef` | Events (raids, traders, etc.) | -| `StorytellerDef` | Storyteller configuration | -| `ThoughtDef` | Mood thoughts | -| `MentalStateDef` | Mental breaks | -| `JobDef` | Work job types | -| `HediffDef` | Health conditions/implants | -| `TraitDef` | Pawn traits | -| `InteractionDef` | Social interactions | -| `ThinkTreeDef` | AI behavior tree | -| `DutyDef` | Temporary behavior duties | - -## Performance Guidelines - -- AI calls: minimum 2500 ticks (~1 game hour) cooldown between calls per pawn -- Use `ConcurrentQueue` for all cross-thread data transfer -- Cache game state reads (don't traverse all pawns every tick) -- Use `ModsConfig.IsActive("packageId")` for conditional compatibility patches -- Limit AI context to ~500 tokens for routine decisions - ---- - -## Debugging - -```csharp -// Log to RimWorld debug log -Log.Message("[MyMod] Debug info here"); -Log.Warning("[MyMod] Something unexpected"); -Log.Error("[MyMod] Something broke"); - -// Dev mode actions (shows in debug menu) -[DebugAction("MyMod", "Trigger AI Event")] -static void TriggerAIEvent() { /* ... */ } -``` - -Enable dev mode in game: Options → Development Mode - ---- - -## Pitfalls & Lessons Learned - -### 1. UnityWebRequest 只能在主线程调用 - -**症状**:`UnityWebRequest.SendWebRequest()` 在 `Task.Run` 内调用时返回 HTTP 0,无任何错误日志。 - -**原因**:Unity 的 `UnityWebRequest` 不是线程安全的,必须在主线程发起。 - -**修复**:后台线程 HTTP 调用改用 `System.Net.Http.HttpClient`(net48 支持,线程安全): - -```csharp -private static readonly HttpClient _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; - -// 可在 Task.Run 内安全调用 -using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = content }; -req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); -using var res = await _httpClient.SendAsync(req); -``` - ---- - -### 2. OpenAI 兼容 API 的 FormatEndpoint 三段式逻辑 - -用户填写的 endpoint 格式不一,需统一处理: - -```csharp -private static string FormatEndpoint(string baseUrl) -{ - if (string.IsNullOrEmpty(baseUrl)) return string.Empty; - string trimmed = baseUrl.Trim().TrimEnd('/'); - // 已是完整 endpoint → 不变 - if (trimmed.EndsWith("/chat/completions", StringComparison.OrdinalIgnoreCase)) - return trimmed; - var uri = new Uri(trimmed); - string path = uri.AbsolutePath.Trim('/'); - // 有版本路径(如 /v1)→ 只追加 /chat/completions - if (!string.IsNullOrEmpty(path)) - return trimmed + "/chat/completions"; - // 裸域名 → 追加 /v1/chat/completions - return trimmed + "/v1/chat/completions"; -} -``` - -| 输入 | 输出 | -|------|------| -| `https://api.deepseek.com` | `https://api.deepseek.com/v1/chat/completions` | -| `https://api.deepseek.com/v1` | `https://api.deepseek.com/v1/chat/completions` | -| `https://api.deepseek.com/v1/chat/completions` | 原样返回 | - ---- - -### 3. net48 中禁止使用 `dynamic` 类型 - -**症状**:编译报错,缺少 `Microsoft.CSharp` 引用。 - -**替代方案**:用 Newtonsoft.Json 的 `JObject`: - -```csharp -// 不要用 dynamic -// dynamic obj = JsonConvert.DeserializeObject(text); // 编译失败 - -// 改用 JObject -var jobj = JObject.Parse(text); -string reply = jobj["choices"]?[0]?["message"]?["content"]?.ToString() ?? ""; -int tokens = jobj["usage"]?["total_tokens"]?.Value() ?? 0; -``` - ---- - -### 4. RimWorld 纹理必须是 2 的幂次方(PoT) - -**症状**:`Texture X.png is being reloaded with reduced mipmap count (clamped to 2) due to non-power-of-two dimensions: (24x24)` - -**原因**:RimWorld(Unity)要求 UI 纹理尺寸为 2 的幂次方(16、32、64…)。 - -**规则**: -- 不要用游戏内置的非 PoT 纹理(如 `UI/Buttons/Info` 是 24×24) -- 自己提供纹理放在 `Textures/UI/MyMod/Icon.png`,使用 32×32 或 64×64 - -```csharp -// 错误:复用游戏内置 24×24 纹理 -ContentFinder.Get("UI/Buttons/Info", reportFailure: false) - -// 正确:使用自己的 32×32 纹理 -ContentFinder.Get("UI/MyMod/Icon", reportFailure: false) -``` - ---- - -### 5. `[DebugAction]` Dev 菜单搜索按动作名,不按分类名 - -Dev 菜单搜索框只匹配**动作名称**,不匹配 category 参数。 - -```csharp -// category="MyMod", name="Test API Connection" -[DebugAction("MyMod", "Test API Connection", actionType = DebugActionType.Action)] -``` - -- 搜索 `"MyMod"` → **找不到** -- 搜索 `"Test API"` → **可以找到** -- 或者在 Actions 列表滚动到 "MyMod" 分类下查看 - ---- - -### 6. Keyed XML 不会产生翻译错误 - -"Translation data has X errors" 这条日志**只来自 `DefInjected/` 翻译文件**(key 与 Def 不匹配时触发)。 - -`Languages/*/Keyed/*.xml` 无论多余还是缺失 key 都**不会**触发该错误: -- 多余的 key → 静默忽略 -- 缺失的 key → 代码中显示 key 原文字符串 - -如果看到翻译错误,首先检查其他 mod 的 DefInjected 目录,而非自己的 Keyed 文件。 - ---- - -### 7. WorkGiver 三模式扫描:用 `wg.def.scanCells` 区分,而非类型判断 - -**背景**:枚举某 WorkType 可执行目标时,WorkGiver 有三种工作模式。 - -**错误做法**:`if (scanner is WorkGiver_Grower)` — 只覆盖 Growing,漏掉 SmoothWall、BuildRoof、RemoveRoof、ClearSnow、PaintFloor 等 8 个格子类 WorkGiver。 - -**正确做法**:用 `wg.def.scanCells` 属性区分,与具体类型无关: - -```csharp -foreach (var wg in workType.workGiversByPriority) -{ - if (wg.Worker is not WorkGiver_Scanner scanner) continue; - - if (wg.scanCells) - { - // 格子类:Growing / SmoothWall / BuildRoof / RemoveRoof / - // ClearSnow / PaintFloor / ClearPollution 等 - var cells = scanner.PotentialWorkCellsGlobal(pawn); - foreach (var cell in cells) - { - if (scanner.HasJobOnCell(pawn, cell, false)) - // 处理 cell 目标 - } - } - else - { - // 物体类(默认):Mining / Hauling / Tend / Hunt 等 - // DoBill 工作台(Cooking / Crafting / Smithing)也在此分支, - // 额外通过 IBillGiver.BillStack.FirstShouldDoNow 获取账单名称 - var things = scanner.PotentialWorkThingsGlobal(pawn); - foreach (var thing in things) - { - if (scanner.HasJobOnThing(pawn, thing, false)) - // 处理 thing 目标 - } - } -} -``` - -`IBillGiver` 账单名称: -```csharp -if (thing is IBillGiver billGiver) -{ - var bill = billGiver.BillStack?.FirstShouldDoNow; - label = bill != null ? $"{thing.LabelShort} → {bill.LabelCap}" : thing.LabelShort; -} -``` - -所有 WorkGiver 调用包在 `try-catch` 内,部分 WorkGiver 在特定地图状态下会抛异常。 - ---- - -### 8. 插件 API 可扩展分类:C# 8 接口默认方法代替硬编码 HashSet - -**问题**:`ExecuteBatch` 需要知道哪些动作是 Job 类(需要 `requestQueueing`),原实现用硬编码 HashSet: -```csharp -// 脆弱:外部 mod 注册的 Job 类动作不在此集合中 -private static readonly HashSet _jobBasedIntents = new() { "force_rest", "assign_work", ... }; -``` - -**修复**:用 C# 8 接口默认方法声明扩展点: -```csharp -public interface IActionRule -{ - bool IsJobBased => false; // 默认非 Job 类;Job 类实现覆盖为 true - bool Execute(Pawn actor, Pawn? target, string? param, bool requestQueueing = false); -} - -// 内置 Job 类动作 -public class ForceRestAction : IActionRule -{ - public bool IsJobBased => true; - // ... -} - -// ExecuteBatch 直接读属性,无需查 HashSet -bool isJobAction = rule.IsJobBased; -``` - -**优点**:外部 mod 注册自定义 Job 类动作时,只需在自己的类中声明 `public bool IsJobBased => true;`,框架代码无需改动。 - ---- - -### 9. RimWorld AI 空闲判断:GotoWander ≠ 游戏空闲,但 = AI 可接管 - -**问题**:`pawn.jobs.curJob == null` 不足以判断"AI 是否可以重定向小人"。 - -- `GotoWander`:小人在漫步,`curJob != null`,游戏认为不空闲 -- `playerForced = true`:玩家手动命令的 Job,AI 不应打断 - -**正确的 AI 可接管判断**: - -```csharp -public static bool IsAdvisorIdle(Pawn pawn) -{ - var job = pawn.jobs?.curJob; - if (job == null) return true; - if (job.playerForced) return false; // 玩家命令优先 - - // 这些 Job 类型 AI 可安全打断 - var def = job.def; - return def == JobDefOf.Wait - || def == JobDefOf.Wait_Wander - || def == JobDefOf.GotoWander - || def == JobDefOf.Wait_MaintainPosture; -} -``` - -调试输出应明确区分:`"是否空闲(AI 可接管)"` 而非 `"游戏空闲"`,避免概念混淆。 - ---- - -### 10. ModSettings 孤儿条目:warn 但不删除,保留以备 mod 重启恢复 - -**场景**:玩家禁用了某外部 mod 的某动作(存入 `DisabledIntents`),然后卸载该外部 mod。 -下次加载时该 intentId 不再注册,但 `DisabledIntents` 仍保存着它。 - -**策略**:`[StaticConstructorOnStartup]`(所有 Mod 构造器完成后运行,此时所有动作已注册)中验证并 **warn 但不删除**: - -```csharp -[StaticConstructorOnStartup] -internal static class ActionsSettingsValidator -{ - static ActionsSettingsValidator() - { - if (MyModMain.Settings == null) return; - var registered = new HashSet(MyModAPI.GetSupportedIntents()); - foreach (var id in MyModMain.Settings.DisabledIntents) - { - if (!registered.Contains(id)) - Log.Warning($"[MyMod] 设置中有未注册的动作 '{id}'(对应 mod 未加载?),已保留以备恢复。"); - } - } -} -``` - -**为什么不删除**:若玩家重新启用该外部 mod,孤儿条目会自动重新生效,无需玩家重新配置。 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fb71105..d7378da 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,11 +1,13 @@ name: Unit Tests on: + workflow_dispatch: push: branches: [main, master] paths: - 'Source/**' - 'Tests/**' + - 'IntegrationTests/**' - 'ArchTests/**' - '.github/workflows/test.yml' pull_request: @@ -13,6 +15,7 @@ on: paths: - 'Source/**' - 'Tests/**' + - 'IntegrationTests/**' - 'ArchTests/**' - '.github/workflows/test.yml' diff --git a/AGENTS.md b/AGENTS.md index 9021eba..209a885 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,10 +15,16 @@ RimMind 与 RimTalk 模组协调层,对话门控 + 上下文双向推送/拉 | 项 | 值 | |----|-----| -| Target | net48, C#9.0, Nullable enable | -| Output | `../1.6/Assemblies/` | +| Target | RimWorld 1.6 (`net48`) / 1.7 (`net10.0`), C# 9.0, Nullable enable | +| Output | `../$(GameVersion)/Assemblies/` | | Assembly | RimMindBridgeRimTalk | -| 依赖 | RimMind Core + 运行时反射的 RimTalk | +| 依赖 | RimMind Core + 运行时反射的 RimTalk(其他 RimMind 子模组均可选) | + +```powershell +dotnet test RimMind-Bridge-RimTalk/Tests/RimMindBridgeRimTalk.Tests.csproj -c Release +dotnet build RimMind-Bridge-RimTalk/Source/RimMindBridgeRimTalk.csproj -c Release -p:GameVersion=1.6 +dotnet build RimMind-Bridge-RimTalk/Source/RimMindBridgeRimTalk.csproj -c Release -p:GameVersion=1.7 +``` ## 源码结构 @@ -26,8 +32,7 @@ RimMind 与 RimTalk 模组协调层,对话门控 + 上下文双向推送/拉 Source/ ├── RimMindBridgeRimTalkMod.cs Mod入口(委托Coordinator) ├── Bridge/ -│ ├── RimTalkBridgeCoordinator.cs 统一注册/注销入口(委托 BridgeModuleCoordinator) -│ ├── BridgeModuleCoordinator.cs IBridgeModule 集合对称 RegisterAll/UnregisterAll 调度器 +│ ├── RimTalkBridgeCoordinator.cs 统一注册/注销入口(委托 Core ExternalModBridgeCoordinator) │ ├── DialogueGate.cs 对话门控(ShouldSkipDialogue/ShouldSkipFloatMenuOption) │ ├── RimMindProviderReader.cs Core Provider 字符串读取与可选 Provider 失败告警边界 │ ├── PersonaFormatter.cs 共享人格字符串构建器(BuildFullProfile,供Push/PersonaPush复用) @@ -35,13 +40,15 @@ Source/ │ ├── ContextPushBridge.cs [IBridgeModule] 推送RimMind数据→RimTalk变量(5个)+PromptEntry(与PersonaPush Hook自动去重) │ ├── PersonaPushBridge.cs [IBridgeModule] 细粒度人格推送(4个变量+Traits/Mood Hook) │ ├── ContextPullBridge.cs [IBridgeModule] 拉取RimTalk对话→RimMind Provider(rimtalk_history, MainThreadSnapshot+MessageAccessors缓存) -│ └── RimTalkApiShim.cs 反射封装层(延迟类型解析+异常隔离告警) -├── Detection/RimTalkDetector.cs RimTalk激活检测(6000 tick TTL 缓存 + IsRimTalkApiAvailable 一次性类型探测, InvalidateCache 重置全部状态) +│ └── RimTalkApiShim.cs 反射封装层(委托 Core ReflectionAccessor + 按枚举名解析 HookOperation/PromptRole/PromptPosition) +├── Detection/RimTalkDetector.cs RimTalk激活检测(委托 Core SoftDependencyDetector, 6000 tick TTL 缓存 + API 类型探测) ├── Extensions/ │ ├── RimTalkSettingsTab.cs 设置Tab UI -│ ├── RimTalkFloatMenuSkipCheck.cs FloatMenu SkipCheck Harmony补丁 -│ └── RimTalkDialogueSkipCheck.cs Dialogue SkipCheck Harmony补丁 -├── Debug/BridgeRimTalkDebugActions.cs 6个DebugAction(含Force Unregister Bridges) +│ ├── RimTalkFloatMenuSkipCheck.cs FloatMenu ISkipCheck 扩展 +│ └── RimTalkDialogueSkipCheck.cs Dialogue ISkipCheck 扩展 +├── Debug/ +│ ├── BridgeRimTalkDebugActions.cs 6个DebugAction(含Force Unregister Bridges) +│ └── BridgeRimTalkBehaviorAutotestSuite.cs 游戏内行为自检套件 └── Settings/BridgeRimTalkSettings.cs 15项设置(dirty-flag写盘,变更才标记WriteSettings) Tests/ ├── RimTalkStubs.cs @@ -52,8 +59,8 @@ Tests/ ## 数据流 -- **Push(RimMind → RimTalk)**:Personality、Memory 和 Advisor 等子模组将字符串发布到 Core `RimMindAPI.Providers`;Bridge 只同步读取 Core Provider 结果,再通过 `RimTalkApiShim` 注册到 RimTalk(当启用 `injectPersonaToTraits` / `injectPersonaToMood` 时,`rimmind_personality` 自动跳过已由 `PersonaPushBridge` Hook 注入的段落以防重复)。Bridge 不编译引用任何子模组的 DTO、WorldComponent 或存储单例。 -- **Pull(RimTalk → RimMind)**:`ContextPullBridge` 注册 `rimtalk_history` Context Provider 时,通过 `RimMindAPI.MainThreadSnapshot.GetAsync` 将 Pawn 查找与存活校验(`RimMindPawnLookup.FindPawnByNumber` + `IsActiveSpawnedColonist`)及 `RimTalk.Data.TalkHistory` 反射读取统一封送到主线程快照执行,后台请求线程绝不直接触碰 Verse 或 RimTalk 实时集合。消息条目通过 `ConcurrentDictionary` 缓存 `Item1`/`Item2`(及可选 `Item3`/`Tick`/`Timestamp`)字段或属性访问器;若结构不兼容则触发单次告警(warn-once: `_warnedMissingTupleFields`)并置位 `_disabledDueToStructuralFailure` 自动停用拉取,避免重复反射开销与日志刷屏。 +- **Push(RimMind → RimTalk)**:Personality、Memory 和 Advisor 等子模组将字符串发布到 Core `RimMindAPI.Providers`;Bridge 只同步读取 Core Provider 结果(`RimMindProviderReader` 对缺失可选 Provider 静默短路,已注册失败按类目 warn-once),再通过 `RimTalkApiShim` 注册到 RimTalk(当启用 `injectPersonaToTraits` / `injectPersonaToMood` 时,`rimmind_personality` 自动跳过已由 `PersonaPushBridge` Hook 注入的段落以防重复)。Bridge 不编译引用任何子模组的 DTO、WorldComponent 或存储单例。 +- **Pull(RimTalk → RimMind)**:`ContextPullBridge` 注册 `rimtalk_history` Context Provider(`OwnerMod = "RimMindBridgeRimTalk"`,仅在实际注册成功后置 `IsRegistered = true`)时,通过 `RimMindAPI.MainThreadSnapshot.GetAsync` 将 Pawn 查找与存活校验(`RimMindPawnLookup.FindPawnByNumber` + `IsActiveSpawnedColonist`)及 `RimTalk.Data.TalkHistory` 反射读取统一封送到主线程快照执行,后台请求线程绝不直接触碰 Verse 或 RimTalk 实时集合。消息条目通过 `ConcurrentDictionary` 缓存 `Item1`/`Item2`(及可选 `Item3`/`Tick`/`Timestamp`)字段或属性访问器,角色名直接取 `roleValue?.ToString()`;若结构不兼容则调用 `Accessor.MarkStructuralFailure(...)` 触发单次告警并自动停用拉取,避免重复反射开销与日志刷屏。 ## RimTalkApiShim 反射方法 @@ -62,24 +69,23 @@ RegisterPawnVariable / RegisterEnvironmentVariable / RegisterPawnHook AddPromptEntry / UnregisterAllHooks / RemovePromptEntriesByModId / Cleanup ``` -反射目标类型: `RimTalk.API.RimTalkPromptAPI`, `ContextHookRegistry`, `ContextCategories.Pawn`, `PromptEntry`, `PromptRole`, `PromptPosition` +反射目标类型: `RimTalk.API.RimTalkPromptAPI`, `ContextHookRegistry`, `ContextCategories.Pawn`, `PromptEntry`, `PromptRole`, `PromptPosition`(枚举成员按名称解析,如 `Append`、`System`、`Relative`,严禁硬编码枚举整数值)。 ## Provider注册 | 模块 | ModId | 注册内容 | |------|-------|---------| -| ContextPushBridge | `Push` | 5个RimTalk变量(rimmind_personality/storyteller/memory/shaping/advisor_log) + PromptEntry | -| PersonaPushBridge | `Persona` | 4个RimTalk变量(rimmind_persona_desc/work/social/narrative) + Traits/Mood Hook | -| ContextPullBridge | `BridgeRimTalk` | RimMind Provider: rimtalk_history(L4_History, 0.5f, 6条) | +| ContextPushBridge | `RimMind.Bridge.RimTalk.Push` | 5个RimTalk变量(rimmind_personality/storyteller/memory/shaping/advisor_log) + PromptEntry | +| PersonaPushBridge | `RimMind.Bridge.RimTalk.Persona` | 4个RimTalk变量(rimmind_persona_desc/work/social/narrative) + Traits/Mood Hook | +| ContextPullBridge | `RimMindBridgeRimTalk` | RimMind ContextKey: rimtalk_history(L4_History, 0.5f, 6条) | ## 已知限制 -- DialogueGate无Unregister方法(skip check注册后无法清理) -- Cleanup不清理Variables(RimTalk API不提供Unregister;_registeredVariableIds死代码已归档至Refs/backup/RimMind-Bridge-RimTalk/,原仅写入从不读取) -- 设置变更需重启(Push/Pull注册仅在启动时执行) -- ContextPullBridge 反射容错:通过 `MessageAccessors` 缓存 `Item1`/`Item2` 字段或属性访问器;若 RimTalk 消息结构变化导致字段缺失,仅打印一次告警(`_warnedMissingTupleFields`)并置位 `_disabledDueToStructuralFailure` 熔断停用,直至重新 `Register()` -- DialogueGate全局门控(pawn参数已保留用于未来按pawn门控扩展,当前为全局门控) -- Unregister无自动调用点(RimWorld Mod生命周期无Dispose,需通过DebugAction"Force Unregister Bridges"手动清理) +- Cleanup 不清理 RimTalk 侧已注册的 Variables(RimTalk API 仅提供 `UnregisterAllHooks` 与 `RemovePromptEntriesByModId`) +- 设置变更需重启(Push/Pull 注册仅在启动时执行) +- ContextPullBridge 反射容错:通过 `MessageAccessors` 缓存 `Item1`/`Item2` 字段或属性访问器;若 RimTalk 消息结构变化导致字段缺失,调用 Core `ReflectionAccessor.MarkStructuralFailure` 单次告警并熔断停用,直至重新 `Register()` +- DialogueGate 全局门控(`pawn` 参数已保留用于未来按 pawn 门控扩展,当前为全局门控;可通过 `RimTalkBridgeCoordinator.Unregister()` 对称注销 SkipCheck) +- Unregister 无自动调用点(RimWorld Mod 生命周期无 Dispose,需通过 DebugAction "Force Unregister Bridges" 手动清理) ## 代码约定 diff --git a/About/About.xml b/About/About.xml index 15404e8..bb232f6 100644 --- a/About/About.xml +++ b/About/About.xml @@ -9,7 +9,7 @@
  • 1.7
  • [h1]RimMind - Bridge: RimTalk (v2.0)[/h1] -Speech bubble pipeline harmonization and bidirectional cognitive context bridge between the RimMind suite and the RimTalk mod. Unifies overhead dialogue rendering, prevents duplicate conversation triggers, and injects RimMind's Big-Five personality profiles, memories, advisor logs, and storyteller state into RimTalk prompts. +Dialogue mutual-exclusion gating and bidirectional cognitive context bridge between the RimMind suite and the RimTalk mod. Prevents duplicate conversation triggers, pushes RimMind's Big-Five personality profiles, memories, advisor logs, and storyteller state into RimTalk prompt variables/hooks, and pulls RimTalk dialogue history back into RimMind. [b]v2.0 Clean Architecture & RimWorld 1.6 / 1.7 Dual-Version Support:[/b] [list] @@ -32,8 +32,8 @@ RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with L [tr][td]RimMind-Personality[/td][td]Big-Five psychological profiles, dawn monologues & dynamic mood thoughts[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Personality]Link[/url][/td][/tr] [tr][td]RimMind-Storyteller[/td][td]AI Story Director, dramatic tension curve, chained arcs & Storyteller Altar[/td][td]Core, Memory[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Storyteller]Link[/url][/td][/tr] [tr][td]RimMind-Extension-ModelService[/td][td]Multi-provider routing, Anthropic KV cache, local gateways & load balancing[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Extension-ModelService]Link[/url][/td][/tr] -[tr][td]RimMind-Bridge-RimChat[/td][td]RimChat compatibility bridge: dialogue/action mutual exclusion & context sync[/td][td]Core, RimChat[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Bridge-RimChat]Link[/url][/td][/tr] -[tr][td][b]RimMind-Bridge-RimTalk[/b][/td][td]RimTalk compatibility bridge: bubble harmonization & bidirectional context[/td][td]Core, RimTalk[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Bridge-RimTalk]Link[/url][/td][/tr] +[tr][td]RimMind-Bridge-RimChat[/td][td]RimChat compatibility bridge: dialogue/action mutual exclusion & history pull[/td][td]Core, RimChat[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Bridge-RimChat]Link[/url][/td][/tr] +[tr][td][b]RimMind-Bridge-RimTalk[/b][/td][td]RimTalk compatibility bridge: dialogue gating & bidirectional context[/td][td]Core, RimTalk[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Bridge-RimTalk]Link[/url][/td][/tr] [/table] [code]Core ──┬── Actions ── Advisor ├── Dialogue @@ -45,8 +45,8 @@ RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with L [h2]Core Features[/h2] [list] -[*][b]Dialogue Mutual Exclusion Gating[/b] - Automatically skips overlapping [code]RimMind-Dialogue[/code] triggers (chitchat, automatic dialogue, player input) when RimTalk is active so two speech bubble systems never clash. -[*][b]Context Push (RimMind to RimTalk)[/b] - Registers RimMind data as RimTalk prompt variables ([code]rimmind_personality[/code], [code]rimmind_storyteller[/code], [code]rimmind_memory[/code], [code]rimmind_shaping[/code], [code]rimmind_advisor_log[/code], [code]rimmind_persona_desc[/code], [code]rimmind_persona_work[/code], [code]rimmind_persona_social[/code], [code]rimmind_persona_narrative[/code]). +[*][b]Dialogue Mutual Exclusion Gating[/b] - Automatically skips overlapping [code]RimMind-Dialogue[/code] triggers (chitchat, automatic dialogue, player input) when RimTalk is active so both mods never fire duplicate conversations. +[*][b]Context Push (RimMind to RimTalk)[/b] - Registers RimMind data as RimTalk prompt variables ([code]rimmind_personality[/code], [code]rimmind_storyteller[/code], [code]rimmind_memory[/code], [code]rimmind_shaping[/code], [code]rimmind_advisor_log[/code], [code]rimmind_persona_desc[/code], [code]rimmind_persona_work[/code], [code]rimmind_persona_social[/code], [code]rimmind_persona_narrative[/code]) plus a prompt entry. [*][b]Hook Context Enhancement[/b] - Optionally appends RimMind personality descriptions and psychological narratives directly into RimTalk's Traits and Mood context hooks. [*][b]Dialogue History Pull (RimTalk to RimMind)[/b] - Registers RimTalk's conversation history as the [code]rimtalk_history[/code] context provider in [code]RimMind-Core[/code], allowing Advisor, Personality, and Storyteller to reference RimTalk conversations. [/list] @@ -77,21 +77,6 @@ A: Yes. It automatically detects whether RimTalk is active and disables all hook RimMind - Core https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Core -
  • - mcocdaa.RimMindAdvisor - RimMind - Advisor - https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Advisor -
  • -
  • - mcocdaa.RimMindPersonality - RimMind - Personality - https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Personality -
  • -
  • - mcocdaa.RimMindMemory - RimMind - Memory - https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Memory -
  • cj.rimtalk RimTalk @@ -104,6 +89,8 @@ A: Yes. It automatically detects whether RimTalk is active and disables all hook
  • mcocdaa.RimMindCore
  • mcocdaa.RimMindMemory
  • mcocdaa.RimMindPersonality
  • +
  • mcocdaa.RimMindDialogue
  • +
  • mcocdaa.RimMindActions
  • mcocdaa.RimMindAdvisor
  • mcocdaa.RimMindStoryteller
  • diff --git a/INTRODUCTION.txt b/INTRODUCTION.txt deleted file mode 100644 index eae7041..0000000 --- a/INTRODUCTION.txt +++ /dev/null @@ -1,71 +0,0 @@ -[h1]RimMind - Bridge: RimTalk[/h1] -[h1]RimMind - Bridge: RimTalk (双模组协同桥梁)[/h1] - -你的殖民者脑子里住了两个 AI——让它们别再打架了。 -[i]连接 RimMind 与 RimTalk——统一角色性格与共享记忆,彻底杜绝人格分裂。[/i] -[i]Bridge RimMind with RimTalk — Synchronize pawn personas and share memories without contradictions.[/i] - -[h2] 为什么需要这个模组? [/h2] -你同时装了 RimMind 和 RimTalk。听起来很棒——殖民者既有人格和记忆,又能自由聊天。但很快你会发现: -[hr] -[h2]📖 中文介绍 / Chinese Overview[/h2] - -[b]殖民者刚在 RimTalk 里说自己喜欢独处,转头在 RimMind 里又变成了社交达人。[/b] -[b]RimMind-Bridge-RimTalk[/b] 解决同时安装 RimMind 与 RimTalk 时的双重人格脱节问题。它将 RimMind 生成的细腻人格画像与深层记忆无缝注入 RimTalk 对话引擎,确保小人在两套系统中性格如一、记忆连贯。 - -两个 AI 互不相知,殖民者像失忆一样在两边说着矛盾的话。更糟的是,两个对话系统同时弹出,殖民者被拉扯成两半。 -[h3]🌟 核心特性[/h3] -[list] -[*] [b]人格档案同步[/b]:RimMind 的大五人格与背景设定自动流入 RimTalk,使对话口吻完全吻合当事人性格。 -[*] [b]跨系统记忆流通[/b]:在 RimTalk 中的交谈经历可被 RimMind 记忆系统捕获,形成共同过往。 -[*] [b]门控与防争抢[/b]:协调对话触发时机,杜绝两套界面重叠。 -[/list] - -Bridge: RimTalk 让它们[b]共享记忆、互不干扰[/b]。 -[hr] -[h2]🌐 English Overview[/h2] - -[h2] 它让游戏变得更好玩 [/h2] -[b]RimMind-Bridge-RimTalk[/b] aligns pawn personalities and historical memories across both RimMind and RimTalk. - -[b] 殖民者终于有了一致的人格 [/b] -RimMind 为每个殖民者生成了独特的人格——性格描述、工作偏好、社交风格。Bridge 把这些注入 RimTalk,让 RimTalk 的对话也能[b]感知殖民者的内心[/b]。殖民者不再是 RimTalk 眼中的陌生人——他们在两边说的是同一个人。 -[h3]🌟 Key Highlights[/h3] -[list] -[*] [b]Unified Persona Sharing[/b]: Injects RimMind's Big Five profiles and lore into RimTalk dialogue generation. -[*] [b]Bidirectional Memory Flow[/b]: Past RimTalk conversations become part of RimMind's permanent memories. -[*] [b]Conflict-Free Coordination[/b]: Smoothly manages conversation triggers without UI overlapping. -[/list] - -[b] 两个 AI 终于有了共同记忆 [/b] -开启"上下文拉取"后,RimTalk 里发生的对话会流入 RimMind。殖民者在 RimTalk 里倾诉的烦恼,RimMind 也知道。两个系统不再是[b]失忆的两个灵魂[/b],而是共享记忆的同一个殖民者。 - -[b] 叙事者、记忆、顾问——全部打通 [/b] -RimMind 叙事者正在编织的故事线、殖民者深藏的长期记忆、AI 顾问的工作决策——这些都能推送到 RimTalk,让对话[b]更有深度[/b]。殖民者在 RimTalk 里聊天时,不再只是"你好"——而是带着自己的故事和经历。 - -[b] 对话不再打架 [/b] -RimTalk 激活时,自动跳过 RimMind 的重复对话触发。你可以精确控制——只跳闲聊?全部跳过?还是让两套对话系统共存?[b]完全由你决定[/b]。 - -[h2] 装了就用,没装也没事 [/h2] -不需要任何配置。RimTalk 激活时自动启用桥接。没装 RimTalk?完全没问题——本模组[b]静默跳过[/b],不报错不影响游戏。15 个可配置选项让你精确控制,但默认设置已经覆盖最常见的场景。 - -[h2] 推荐搭配 [/h2] -[table][tr][td][b] 模组 [/b][/td][td][b] 为什么推荐 [/b][/td][/tr][tr][td] RimMind-Core [/td][td] 必装,RimMind 套件核心 [/td][/tr][tr][td] RimMind-Personality [/td][td] 提供人格数据,让 RimTalk 感知殖民者性格 [/td][/tr][tr][td] RimMind-Memory [/td][td] 提供记忆和叙事者数据,丰富对话深度 [/td][/tr][tr][td] RimMind-Advisor [/td][td] 提供顾问决策记录,让对话更有背景 [/td][/tr][tr][td] RimMind-Dialogue [/td][td] 对话门控需要此模组 [/td][/tr][tr][td] RimTalk [/td][td] 另一个 AI 对话系统,本模组的桥接对象 [/td][/tr][/table] - -[h2] 常见问题 [/h2] -[b] Q: 不装 RimTalk 可以用吗? [/b] -A: 可以。RimTalk 未安装时所有桥接功能静默跳过,本模组不产生任何影响。 - -[b] Q: 推送的数据会占用很多 Token 吗? [/b] -A: 每类推送最多 5 条记录,且可通过设置独立开关控制。 - -[b] Q: RimTalk 更新后 API 变了怎么办? [/b] -A: 本模组通过反射调用 RimTalk API,所有调用都有 try-catch 保护。API 变更只会导致对应功能静默失效,不会崩溃。 - -[b] Q: 两个 AI 系统会冲突吗? [/b] -A: 不会。对话门控确保不会重复触发,上下文互通让两个系统共享信息而不是互相干扰。 -[hr] -[h2]⚙️ 依赖与顺序 / Requirements & Order[/h2] -[list] -[*] [b]必需前置 (Required)[/b]: Harmony, [b]RimMind-Core[/b], [b]RimTalk[/b] -[/list] diff --git a/README.md b/README.md index b00475b..a275d8c 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,18 @@
    -# RimMind-Bridge-RimTalk 🎨 -### Speech Bubble Pipeline Harmonization & Cognitive Bridge for RimWorld 1.6 & 1.7 +# RimMind-Bridge-RimTalk 🔗 +### Dialogue Gating & Bidirectional Context Bridge for RimWorld 1.6 & 1.7 **English** | [简体中文](README_zh.md)

    RimWorld 1.6 | 1.7 Dependency: RimMind-Core - Unit Tests + Unit Tests License: MIT

    -

    Harmonize overhead dialogue bubbles and inject RimMind's deep personality into RimTalk.

    +

    Coordinates dialogue gating with RimTalk while bidirectionally syncing RimMind personality, memory, advisor, and storyteller context.

    @@ -20,31 +20,32 @@ ## 📖 Overview -**RimMind-Bridge-RimTalk** provides an aesthetic rendering bridge between **RimMind** and the renowned **RimTalk** dialogue mod. Rather than having two competing speech bubble renderers clash on screen, this bridge unifies the visual pipeline and injects RimMind's Big-Five personality profiles and episodic memories into RimTalk prompts. +**RimMind-Bridge-RimTalk** is a zero-compile-dependency compatibility bridge between **RimMind** and the third-party **RimTalk** dialogue mod. It suppresses overlapping RimMind dialogue triggers when RimTalk is active, pushes RimMind cognitive providers into RimTalk prompt variables and context hooks via reflection (`RimTalkApiShim`), and pulls recent RimTalk dialogue history back into RimMind's context engine. ### Key Capabilities -- **Visual Bubble Harmonization**: Shares the overhead mote rendering pipeline, preventing bubble flickering, text clipping, and positioning collisions. -- **Cognitive Prompt Injection**: Dynamically injects RimMind's multi-tier memories and Big-Five traits into RimTalk conversations for deeper, more characterful dialogue. -- **Mutual Cooldown Management**: Coordinates interaction timing between both mod engines to prevent chat spam. +- **Dialogue Mutual-Exclusion Gating**: Independently suppresses RimMind's chitchat, auto dialogue, player input, and "Chat with X" float-menu triggers when RimTalk is active (with an override to keep both player chat entries). +- **Context Push (RimMind → RimTalk)**: Exposes optional RimMind providers (personality, work/social tendencies, AI narrative, memory, shaping history, advisor history, and storyteller state) as RimTalk template variables, a `RimMind Context` prompt entry, and optional Traits/Mood context hooks. +- **Context Pull (RimTalk → RimMind)**: Reads recent `RimTalk.Data.TalkHistory` messages via main-thread snapshots and cached reflection, registering them as the `rimtalk_history` context provider in `RimMind-Core`. --- ## 🎮 In-Game Showcase ![RimMind-Bridge-RimTalk Showcase](docs/images/showcase.jpg) -*Aesthetic speech bubble rendering: Colonists conversing with RimTalk visual motes powered by RimMind's personality and memory context.* +*Bidirectional integration in action: RimTalk conversations enriched with RimMind personality, memory, advisor, and storyteller context while RimMind stays aware of RimTalk chat history.* --- -## 🏛️ Pipeline Architecture +## 🏛️ Bidirectional Bridge Architecture ```mermaid -flowchart TD - Mind["RimMind Cognitive Engine (Personality & Memory)"] --> Bridge["RimMind-Bridge-RimTalk"] - Bridge --> Inject["Inject Context into RimTalk Prompt"] - Inject --> RimTalk["RimTalk Processing Engine"] - RimTalk --> BubblePipeline["Unified Overhead Bubble Pipeline"] - BubblePipeline --> Screen["Flicker-Free Overhead Mote on Screen"] +flowchart LR + CoreProviders["RimMind-Core Providers
    (Personality / Memory / Advisor / Storyteller)"] --> Push["ContextPushBridge & PersonaPushBridge"] + Push --> Shim["RimTalkApiShim (Reflection)"] + Shim --> RimTalk["RimTalk Prompt Variables & Hooks"] + RimTalkHistory["RimTalk TalkHistory"] --> Pull["ContextPullBridge (Main-Thread Snapshot)"] + Pull --> CoreContext["RimMind-Core ContextKeys (rimtalk_history)"] + Gate["DialogueGate (ISkipCheck)"] --> RimMindDialogue["RimMind-Dialogue Triggers & Float Menu"] ``` --- @@ -54,19 +55,22 @@ flowchart TD ```text 1. Harmony 2. Core (Vanilla RimWorld) -3. RimTalk (Optional third-party mod) +3. RimTalk (Required third-party mod) 4. RimMind-Core -5. RimMind-Bridge-RimTalk +5. [Optional RimMind submodules: Memory / Personality / Dialogue / Actions / Advisor / Storyteller] +6. RimMind-Bridge-RimTalk ``` --- ## 🧪 Developer Guide & Testing -Run unit tests directly: +Run unit tests and dual-version builds from the workspace root: ```powershell dotnet test RimMind-Bridge-RimTalk/Tests/RimMindBridgeRimTalk.Tests.csproj -c Release +dotnet build RimMind-Bridge-RimTalk/Source/RimMindBridgeRimTalk.csproj -c Release -p:GameVersion=1.6 +dotnet build RimMind-Bridge-RimTalk/Source/RimMindBridgeRimTalk.csproj -c Release -p:GameVersion=1.7 ``` --- diff --git a/README_zh.md b/README_zh.md index 18d18ad..4b4e447 100644 --- a/README_zh.md +++ b/README_zh.md @@ -1,18 +1,18 @@
    -# RimMind-Bridge-RimTalk 🎨 -### 专为 RimWorld 1.6 & 1.7 打造的气泡管线融合、认知记忆桥接与防打架协同系统 +# RimMind-Bridge-RimTalk 🔗 +### 专为 RimWorld 1.6 & 1.7 打造的对话门控与双向上下文桥接模块 [English](README.md) | **简体中文**

    RimWorld 1.6 | 1.7 依赖: RimMind-Core - 单元测试 + 单元测试 License: MIT

    -

    融合头顶气泡渲染管线,将 RimMind 的深度人格与三层记忆赋能至 RimTalk。

    +

    在 RimMind 与 RimTalk 之间提供对话互斥门控,并双向同步人格、记忆、顾问与叙事者上下文。

    @@ -20,31 +20,32 @@ ## 📖 模块概览 -**RimMind-Bridge-RimTalk** 为 **RimMind** 与经典对话模组 **RimTalk** 之间搭建了一座优雅的艺术表现力桥梁。它杜绝了两个模组各自定义气泡导致文字遮挡闪烁的问题,实现了渲染管线一体化,并将 RimMind 的大五人格与情节记忆注入 RimTalk。 +**RimMind-Bridge-RimTalk** 是 **RimMind** 与第三方对话模组 **RimTalk** 之间的零编译依赖兼容桥。它在 RimTalk 激活时按配置抑制重复的 RimMind 对话触发,通过反射封装(`RimTalkApiShim`)将 RimMind 的认知上下文推送为 RimTalk 模板变量与 Hook,并把 RimTalk 的对话历史回流至 RimMind 上下文引擎。 ### 核心特性 -- **气泡表现力管线融合**:共享头顶文本粒子渲染管线,消除双重气泡重合、文字截断与闪烁冲突。 -- **认知上下文深度赋能**:将 RimMind 的三层记忆库(情节、暗记忆)与大五人格画像动态注入 RimTalk 提示词,让对话更加契合小人生平。 -- **对话节奏协同控频**:在底层协调两个模组的交互冷却与触发时序,告别刷屏噪音。 +- **对话互斥门控**:在 RimTalk 激活时分别控制闲聊、自动对话、玩家对话与“与 X 对话”浮动菜单的跳过策略(支持强制保留双入口共存)。 +- **上下文推送(RimMind → RimTalk)**:读取已安装的可选 RimMind 子模组 Provider(人格画像、工作/社交倾向、AI 叙事、记忆、塑造历史、顾问记录、叙事者状态),注册为 RimTalk 模板变量、`RimMind Context` 提示词条目及可选的 Traits/Mood Hook。 +- **上下文拉取(RimTalk → RimMind)**:通过主线程快照与缓存反射安全读取 `RimTalk.Data.TalkHistory` 近期记录,注册为 `RimMind-Core` 的 `rimtalk_history` 上下文提供器。 --- ## 🎮 实机特性展示 ![RimMind-Bridge-RimTalk 实机展示](docs/images/showcase.jpg) -*唯美气泡协同实机:借助 RimTalk 的气泡渲染表现力,呈现由 RimMind 记忆与人格驱动的生动对话。* +*双向协同实机:RimTalk 提示词注入 RimMind 的人格、记忆、顾问与叙事者上下文,同时 RimMind 感知 RimTalk 的近期对话历史。* --- -## 🏛️ 协同流转架构 +## 🏛️ 双向桥接架构 ```mermaid -flowchart TD - Mind["RimMind 认知引擎 (人格画像与三层记忆)"] --> Bridge["RimMind-Bridge-RimTalk"] - Bridge --> Inject["将高维上下文注入 RimTalk 提示词"] - Inject --> RimTalk["RimTalk 处理中枢"] - RimTalk --> BubblePipeline["统一头顶气泡渲染管线"] - BubblePipeline --> Screen["在屏幕呈现稳定、优雅、防重叠的气泡"] +flowchart LR + CoreProviders["RimMind-Core Providers
    (人格 / 记忆 / 顾问 / 叙事者)"] --> Push["ContextPushBridge & PersonaPushBridge"] + Push --> Shim["RimTalkApiShim (反射适配层)"] + Shim --> RimTalk["RimTalk 提示词变量与 Hook"] + RimTalkHistory["RimTalk TalkHistory"] --> Pull["ContextPullBridge (主线程快照)"] + Pull --> CoreContext["RimMind-Core ContextKeys (rimtalk_history)"] + Gate["DialogueGate (ISkipCheck)"] --> RimMindDialogue["RimMind-Dialogue 触发与浮动菜单"] ``` --- @@ -54,19 +55,22 @@ flowchart TD ```text 1. Harmony 2. Core (RimWorld 原版) -3. RimTalk (第三方模组,可选) +3. RimTalk (前置第三方模组) 4. RimMind-Core -5. RimMind-Bridge-RimTalk +5. [可选 RimMind 子模组:Memory / Personality / Dialogue / Actions / Advisor / Storyteller] +6. RimMind-Bridge-RimTalk ``` --- ## 🧪 开发者测试指南 -运行单元测试: +从工作区根目录运行单元测试与双版本构建: ```powershell dotnet test RimMind-Bridge-RimTalk/Tests/RimMindBridgeRimTalk.Tests.csproj -c Release +dotnet build RimMind-Bridge-RimTalk/Source/RimMindBridgeRimTalk.csproj -c Release -p:GameVersion=1.6 +dotnet build RimMind-Bridge-RimTalk/Source/RimMindBridgeRimTalk.csproj -c Release -p:GameVersion=1.7 ``` --- diff --git a/Source/Bridge/BridgeModuleCoordinator.cs b/Source/Bridge/BridgeModuleCoordinator.cs deleted file mode 100644 index 53b4433..0000000 --- a/Source/Bridge/BridgeModuleCoordinator.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using RimMind.Application.Common.Interfaces.Extension; -using RimMind.Application.Features.Bridges; -using RimMind.Presentation.Api; - -namespace RimMind.Bridge.RimTalk.Bridge -{ - [Obsolete("Use RimMindAPI.Bridges.CreateCoordinator / ExternalModBridgeCoordinator directly.")] - internal sealed class BridgeModuleCoordinator - { - private readonly ExternalModBridgeCoordinator _inner; - - public BridgeModuleCoordinator( - IReadOnlyList modules, - Func isDependencyActive, - Action log, - Action warn) - { - _inner = RimMindAPI.Bridges.CreateCoordinator( - isDependencyActive, - modules, - gates: null, - logInfo: log, - logWarn: warn, - inactiveMessage: "RimTalk not active, bridge modules skipped."); - } - - public bool AreAllRegistered => _inner.AreAllRegistered; - public void RegisterAll() => _inner.RegisterAll(); - public void UnregisterAll() => _inner.UnregisterAll(); - public void Refresh() => _inner.Refresh(); - } -} diff --git a/Source/Bridge/ContextPullBridge.cs b/Source/Bridge/ContextPullBridge.cs index 824c9c8..90a0074 100644 --- a/Source/Bridge/ContextPullBridge.cs +++ b/Source/Bridge/ContextPullBridge.cs @@ -18,7 +18,7 @@ namespace RimMind.Bridge.RimTalk.Bridge { public sealed class ContextPullBridge : IBridgeModule { - private const string ModId = "RimMind.BridgeRimTalk"; + private const string ModId = "RimMindBridgeRimTalk"; private const string TalkHistoryTypeName = "RimTalk.Data.TalkHistory"; private const string GetMessageHistoryMethodName = "GetMessageHistory"; private const int MaxHistoryMessages = 6; @@ -30,7 +30,7 @@ public sealed class ContextPullBridge : IBridgeModule new ConcurrentDictionary(); public string Id => "context_pull"; - public string OwnerModId => "RimMindBridgeRimTalk"; + public string OwnerModId => ModId; public bool IsRegistered { get; private set; } internal static void ConfigureTypesForTesting(Type? talkHistoryType) @@ -45,24 +45,22 @@ public void Register() if (IsRegistered) return; if (!RimTalkDetector.IsRimTalkActive) return; var settings = BridgeRimTalkSettings.Get(); - if (!settings.enableContextPull) return; + if (!settings.enableContextPull || !settings.pullRimTalkHistory) return; Accessor.ResetStructuralFailure(); - if (settings.pullRimTalkHistory) - RegisterRimTalkHistoryProvider(); - - IsRegistered = true; + if (RegisterRimTalkHistoryProvider()) + IsRegistered = true; } - private void RegisterRimTalkHistoryProvider() + private bool RegisterRimTalkHistoryProvider() { if (ResolveGetMessageHistoryMethod() == null) { Accessor.WarnOnce( "history_unavailable", "[RimMind-Bridge-RimTalk] RimTalk history types not available, skipping provider registration."); - return; + return false; } RimMindAPI.Context.ContextKeys.Register(new ContextProviderDef( "rimtalk_history", ContextLayer.L4_History, 0.5f, @@ -76,6 +74,7 @@ private void RegisterRimTalkHistoryProvider() return BuildRimTalkHistoryContext(pawn!); }, null, ct: ct).ConfigureAwait(false); }, ModId, stalenessTicks: 3000)); // RimTalk history changes are external (no bus event): staleness only + return true; } private static MethodInfo? ResolveGetMessageHistoryMethod() @@ -197,17 +196,8 @@ private void RegisterRimTalkHistoryProvider() private static string FormatRoleLabel(object? roleValue) { - if (roleValue is int roleInt) - { - return roleInt switch - { - 0 => "System", - 1 => "User", - 2 => "AI", - _ => roleInt.ToString() - }; - } - return roleValue?.ToString() ?? "?"; + string? label = roleValue?.ToString(); + return string.IsNullOrWhiteSpace(label) ? "?" : label!; } public void Unregister() diff --git a/Source/Bridge/ContextPushBridge.cs b/Source/Bridge/ContextPushBridge.cs index 5b709d7..befab11 100644 --- a/Source/Bridge/ContextPushBridge.cs +++ b/Source/Bridge/ContextPushBridge.cs @@ -147,8 +147,8 @@ private static void RegisterPromptEntry(RimTalkContextPushPlan plan) RimTalkApiShim.AddPromptEntry( name: "RimMind Context", content: plan.PromptContent, - roleValue: 0, - positionValue: 0, + roleName: "System", + positionName: "Relative", sourceModId: ModId ); } diff --git a/Source/Bridge/PersonaPushBridge.cs b/Source/Bridge/PersonaPushBridge.cs index 2702ceb..ad037ae 100644 --- a/Source/Bridge/PersonaPushBridge.cs +++ b/Source/Bridge/PersonaPushBridge.cs @@ -80,7 +80,7 @@ private void RegisterPersonaHooks() RimTalkApiShim.RegisterPawnHook( ModId, "Traits", - 0, + "Append", (pawn, existing) => { var formatted = PersonaFormatter.BuildFullProfile( @@ -105,7 +105,7 @@ private void RegisterPersonaHooks() RimTalkApiShim.RegisterPawnHook( ModId, "Mood", - 0, + "Append", (pawn, existing) => { var narrative = RimMindProviderReader.GetPawn( diff --git a/Source/Bridge/RimMindProviderReader.cs b/Source/Bridge/RimMindProviderReader.cs index 68606f9..4250ecb 100644 --- a/Source/Bridge/RimMindProviderReader.cs +++ b/Source/Bridge/RimMindProviderReader.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; using Verse; @@ -16,11 +17,26 @@ internal static class RimMindProviderReader internal const string NarratorMemoryBrief = "memory.narrator_brief"; internal const string AdvisorHistoryBrief = "advisor.history_brief"; - internal static string GetPawn(string category, Pawn pawn) - => Resolve(category, RimMindAPI.Providers.GetProviderData(category, pawn)); + private static readonly ConcurrentDictionary WarnedCategories = + new ConcurrentDictionary(StringComparer.Ordinal); + + internal static void ResetForTesting() => WarnedCategories.Clear(); + + internal static string GetPawn(string category, Pawn? pawn) + { + if (pawn == null || string.IsNullOrEmpty(category)) + return string.Empty; + + return Resolve(category, RimMindAPI.Providers.GetProviderData(category, pawn)); + } internal static string GetStatic(string category) - => Resolve(category, RimMindAPI.Providers.GetStaticProviderData(category)); + { + if (string.IsNullOrEmpty(category)) + return string.Empty; + + return Resolve(category, RimMindAPI.Providers.GetStaticProviderData(category)); + } private static string Resolve( string category, @@ -29,7 +45,18 @@ private static string Resolve( if (result.IsOk) return result.Value ?? string.Empty; - if (RimMindAPI.Providers.GetRegisteredCategories().Contains(category)) + string errorMessage = result.Error.Message ?? string.Empty; + if (errorMessage.StartsWith("No provider registered", StringComparison.Ordinal) + || errorMessage.StartsWith("No static provider registered", StringComparison.Ordinal)) + { + return string.Empty; + } + + if (WarnedCategories.ContainsKey(category)) + return string.Empty; + + if (RimMindAPI.Providers.GetRegisteredCategories().Contains(category) + && WarnedCategories.TryAdd(category, 1)) { Log.WarningOnce( $"[RimMind-Bridge-RimTalk] Provider '{category}' failed: {result.Error}", diff --git a/Source/Bridge/RimTalkApiShim.cs b/Source/Bridge/RimTalkApiShim.cs index 077516e..58ceb09 100644 --- a/Source/Bridge/RimTalkApiShim.cs +++ b/Source/Bridge/RimTalkApiShim.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Concurrent; using System.Reflection; -using System.Runtime.CompilerServices; using RimMind.Application.Features.Bridges; using RimMind.Bridge.RimTalk.Detection; using RimMind.Domain.ValueObjects; @@ -31,13 +30,12 @@ public static class RimTalkApiShim private static readonly ConcurrentDictionary<(Type Parent, string Name), Type?> NestedTypeCache = new ConcurrentDictionary<(Type Parent, string Name), Type?>(); - private static Type? _apiType; - private static Type? _hookRegistryType; - private static Type? _contextCategoriesType; - private static Type? _promptEntryType; - private static Type? _promptRoleType; - private static Type? _promptPositionType; - private static bool _resolved; + private static Type? ApiType => Accessor.GetCachedType(ApiTypeName); + private static Type? HookRegistryType => Accessor.GetCachedType(HookRegistryTypeName); + private static Type? ContextCategoriesType => Accessor.GetCachedType(ContextCategoriesTypeName); + private static Type? PromptEntryType => Accessor.GetCachedType(PromptEntryTypeName); + private static Type? PromptRoleType => Accessor.GetCachedType(PromptRoleTypeName); + private static Type? PromptPositionType => Accessor.GetCachedType(PromptPositionTypeName); internal static void ConfigureTypesForTesting( Type? apiType, @@ -56,61 +54,50 @@ internal static void ConfigureTypesForTesting( Accessor.SetCachedType(PromptEntryTypeName, promptEntryType); Accessor.SetCachedType(PromptRoleTypeName, promptRoleType); Accessor.SetCachedType(PromptPositionTypeName, promptPositionType); - - _apiType = apiType; - _hookRegistryType = hookRegistryType; - _contextCategoriesType = contextCategoriesType; - _promptEntryType = promptEntryType; - _promptRoleType = promptRoleType; - _promptPositionType = promptPositionType; - _resolved = true; } public static bool IsAvailable => RimTalkDetector.IsRimTalkApiAvailable; - private static void EnsureResolved() + private static Type? GetCachedNestedType(Type parentType, string nestedName) { - if (_resolved) return; - _resolved = true; - ResolveTypes(); + return NestedTypeCache.GetOrAdd( + (parentType, nestedName), + static key => key.Parent.GetNestedType(key.Name)); } - [MethodImpl(MethodImplOptions.NoInlining)] - private static void ResolveTypes() + private static bool TryResolveEnumValue(Type enumType, string memberName, string warnKey, out object? value) { - try - { - _apiType = Accessor.GetCachedType(ApiTypeName); - _hookRegistryType = Accessor.GetCachedType(HookRegistryTypeName); - _contextCategoriesType = Accessor.GetCachedType(ContextCategoriesTypeName); - _promptEntryType = Accessor.GetCachedType(PromptEntryTypeName); - _promptRoleType = Accessor.GetCachedType(PromptRoleTypeName); - _promptPositionType = Accessor.GetCachedType(PromptPositionTypeName); - } - catch (Exception ex) + value = null; + if (!enumType.IsEnum || string.IsNullOrWhiteSpace(memberName)) + return false; + + string[] names = Enum.GetNames(enumType); + for (int i = 0; i < names.Length; i++) { - RimMindErrors.Warn($"[RimMind-Bridge-RimTalk] Failed to resolve RimTalk types: {ex.Message}"); + if (string.Equals(names[i], memberName, StringComparison.OrdinalIgnoreCase)) + { + value = Enum.Parse(enumType, names[i]); + return true; + } } - } - private static Type? GetCachedNestedType(Type parentType, string nestedName) - { - return NestedTypeCache.GetOrAdd( - (parentType, nestedName), - static key => key.Parent.GetNestedType(key.Name)); + Accessor.WarnOnce( + warnKey, + $"[RimMind-Bridge-RimTalk] Enum value '{memberName}' not found on {enumType.Name}."); + return false; } public static bool RegisterPawnVariable(string modId, string variableName, Func provider, string? description = null, int priority = 100) { if (!IsAvailable) return false; - EnsureResolved(); - if (_apiType == null) return false; + var apiType = ApiType; + if (apiType == null) return false; try { var method = Accessor.GetCachedMethod( - _apiType, + apiType, "RegisterPawnVariable", BindingFlags.Public | BindingFlags.Static, RegisterPawnVariableSignature); @@ -132,13 +119,13 @@ public static bool RegisterEnvironmentVariable(string modId, string variableName Func provider, string? description = null, int priority = 100) { if (!IsAvailable) return false; - EnsureResolved(); - if (_apiType == null) return false; + var apiType = ApiType; + if (apiType == null) return false; try { var method = Accessor.GetCachedMethod( - _apiType, + apiType, "RegisterEnvironmentVariable", BindingFlags.Public | BindingFlags.Static, RegisterEnvironmentVariableSignature); @@ -157,15 +144,17 @@ public static bool RegisterEnvironmentVariable(string modId, string variableName } public static bool RegisterPawnHook(string modId, string categoryKey, - int hookOperation, Func handler, int priority = 100) + string hookOperationName, Func handler, int priority = 100) { if (!IsAvailable) return false; - EnsureResolved(); - if (_apiType == null || _hookRegistryType == null || _contextCategoriesType == null) return false; + var apiType = ApiType; + var hookRegistryType = HookRegistryType; + var contextCategoriesType = ContextCategoriesType; + if (apiType == null || hookRegistryType == null || contextCategoriesType == null) return false; try { - var nestedPawnType = GetCachedNestedType(_contextCategoriesType, "Pawn"); + var nestedPawnType = GetCachedNestedType(contextCategoriesType, "Pawn"); if (nestedPawnType == null) { Accessor.WarnOnce( @@ -184,13 +173,20 @@ public static bool RegisterPawnHook(string modId, string categoryKey, object? categoryValue = categoryField.GetValue(null); if (categoryValue == null) return false; - var hookOpEnum = GetCachedNestedType(_hookRegistryType, "HookOperation"); - if (hookOpEnum == null) return false; + var hookOpEnum = GetCachedNestedType(hookRegistryType, "HookOperation"); + if (hookOpEnum == null) + { + Accessor.WarnOnce( + "nested:ContextHookRegistry.HookOperation", + "[RimMind-Bridge-RimTalk] ContextHookRegistry.HookOperation nested type not found"); + return false; + } - object? opValue = Enum.ToObject(hookOpEnum, hookOperation); + if (!TryResolveEnumValue(hookOpEnum, hookOperationName, $"enum:HookOperation:{hookOperationName}", out object? opValue)) + return false; var method = Accessor.GetCachedMethod( - _apiType, + apiType, "RegisterPawnHook", BindingFlags.Public | BindingFlags.Static); if (method == null) @@ -207,25 +203,29 @@ public static bool RegisterPawnHook(string modId, string categoryKey, } public static bool AddPromptEntry(string name, string content, - int roleValue = 0, int positionValue = 0, + string roleName = "System", string positionName = "Relative", int inChatDepth = 0, string? sourceModId = null) { if (!IsAvailable) return false; - EnsureResolved(); - if (_apiType == null || _promptEntryType == null) return false; + var apiType = ApiType; + var promptEntryType = PromptEntryType; + var promptRoleType = PromptRoleType; + var promptPositionType = PromptPositionType; + if (apiType == null || promptEntryType == null || promptRoleType == null || promptPositionType == null) + return false; try { var createMethod = Accessor.GetCachedMethod( - _apiType, + apiType, "CreatePromptEntry", BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(string), - _promptRoleType ?? typeof(int), - _promptPositionType ?? typeof(int), + promptRoleType, + promptPositionType, typeof(int), typeof(string) }); @@ -233,14 +233,16 @@ public static bool AddPromptEntry(string name, string content, if (createMethod == null) return false; - object? roleObj = _promptRoleType != null ? Enum.ToObject(_promptRoleType, roleValue) : roleValue; - object? posObj = _promptPositionType != null ? Enum.ToObject(_promptPositionType, positionValue) : positionValue; + if (!TryResolveEnumValue(promptRoleType, roleName, $"enum:PromptRole:{roleName}", out object? roleObj)) + return false; + if (!TryResolveEnumValue(promptPositionType, positionName, $"enum:PromptPosition:{positionName}", out object? posObj)) + return false; object? entry = createMethod.Invoke(null, new object?[] { name, content, roleObj, posObj, inChatDepth, sourceModId }); if (entry == null) return false; var addMethod = Accessor.GetCachedMethod( - _apiType, + apiType, "AddPromptEntry", BindingFlags.Public | BindingFlags.Static); if (addMethod == null) return false; @@ -258,13 +260,13 @@ public static bool AddPromptEntry(string name, string content, public static bool UnregisterAllHooks(string modId) { if (!IsAvailable) return false; - EnsureResolved(); - if (_apiType == null) return false; + var apiType = ApiType; + if (apiType == null) return false; try { var method = Accessor.GetCachedMethod( - _apiType, + apiType, "UnregisterAllHooks", BindingFlags.Public | BindingFlags.Static, warnIfMissing: false); @@ -283,13 +285,13 @@ public static bool UnregisterAllHooks(string modId) public static int RemovePromptEntriesByModId(string modId) { if (!IsAvailable) return 0; - EnsureResolved(); - if (_apiType == null) return 0; + var apiType = ApiType; + if (apiType == null) return 0; try { var method = Accessor.GetCachedMethod( - _apiType, + apiType, "RemovePromptEntriesByModId", BindingFlags.Public | BindingFlags.Static, warnIfMissing: false); diff --git a/Source/Debug/BridgeRimTalkBehaviorAutotestSuite.cs b/Source/Debug/BridgeRimTalkBehaviorAutotestSuite.cs index c909725..7aedabb 100644 --- a/Source/Debug/BridgeRimTalkBehaviorAutotestSuite.cs +++ b/Source/Debug/BridgeRimTalkBehaviorAutotestSuite.cs @@ -4,7 +4,6 @@ using RimMind.Bridge.RimTalk.Detection; using RimMind.Bridge.RimTalk.Settings; using RimMind.Presentation.Api; -using RimWorld; using Verse; namespace RimMind.Bridge.RimTalk.Debug diff --git a/Source/Debug/BridgeRimTalkDebugActions.cs b/Source/Debug/BridgeRimTalkDebugActions.cs index 1f0fd89..9a6f340 100644 --- a/Source/Debug/BridgeRimTalkDebugActions.cs +++ b/Source/Debug/BridgeRimTalkDebugActions.cs @@ -1,3 +1,4 @@ +using System; using System.Linq; using System.Text; using LudeonTK; @@ -40,8 +41,9 @@ private static void TestDialogueGateSelected() return; } + string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort ?? "?"; var sb = new StringBuilder(); - sb.AppendLine($"[RimMind-Bridge-RimTalk] Dialogue Gate Test for {pawn.Name.ToStringShort}:"); + sb.AppendLine($"[RimMind-Bridge-RimTalk] Dialogue Gate Test for {pawnName}:"); sb.AppendLine($" ShouldSkipDialogue(Chitchat): {RimMindAPI.Ext.ShouldSkipDialogue(pawn, "Chitchat")}"); sb.AppendLine($" ShouldSkipDialogue(Auto): {RimMindAPI.Ext.ShouldSkipDialogue(pawn, "Auto")}"); sb.AppendLine($" ShouldSkipDialogue(PlayerInput): {RimMindAPI.Ext.ShouldSkipDialogue(pawn, "PlayerInput")}"); @@ -57,12 +59,17 @@ private static void ShowContextPushState() sb.AppendLine("[RimMind-Bridge-RimTalk] Context Push State:"); var categories = RimMindAPI.Providers.GetRegisteredCategories(); - var rimtalkCategories = categories.Where(c => c.StartsWith("rimmind_") || c.StartsWith("rimtalk_")).ToList(); - sb.AppendLine($" RimMind registered rimtalk-related categories: {(rimtalkCategories.Count > 0 ? string.Join(", ", rimtalkCategories) : "none")}"); - sb.AppendLine(" (Note: Push variables are registered in RimTalk, not RimMind)"); + var sourceProviders = categories + .Where(c => c.StartsWith("personality.", StringComparison.Ordinal) + || c.StartsWith("memory.", StringComparison.Ordinal) + || c.StartsWith("advisor.", StringComparison.Ordinal)) + .ToList(); + sb.AppendLine($" RimMind source providers available ({sourceProviders.Count}): {(sourceProviders.Count > 0 ? string.Join(", ", sourceProviders) : "none")}"); + sb.AppendLine(" (Note: Push variables are registered in RimTalk via RimTalkApiShim)"); var settings = BridgeRimTalkSettings.Get(); sb.AppendLine(" Push Settings:"); + sb.AppendLine($" enableContextPush: {settings.enableContextPush}"); sb.AppendLine($" pushPersonality: {settings.pushPersonality}"); sb.AppendLine($" pushStoryteller: {settings.pushStoryteller}"); sb.AppendLine($" pushMemory: {settings.pushMemory}"); @@ -80,12 +87,15 @@ private static void ShowContextPullState() var sb = new StringBuilder(); sb.AppendLine("[RimMind-Bridge-RimTalk] Context Pull State:"); - var categories = RimMindAPI.Providers.GetRegisteredCategories(); - var rimtalkCategories = categories.Where(c => c.StartsWith("rimtalk_")).ToList(); - sb.AppendLine($" RimMind registered rimtalk-related providers: {(rimtalkCategories.Count > 0 ? string.Join(", ", rimtalkCategories) : "none")}"); + var contextKeys = RimMindAPI.Context.ContextKeys.GetAll(); + var rimtalkKeys = contextKeys + .Where(k => k.Key.StartsWith("rimtalk_", StringComparison.Ordinal)) + .ToList(); + sb.AppendLine($" RimMind registered rimtalk context keys ({rimtalkKeys.Count}): {(rimtalkKeys.Count > 0 ? string.Join(", ", rimtalkKeys.Select(k => $"{k.Key} ({k.OwnerMod})")) : "none")}"); var settings = BridgeRimTalkSettings.Get(); sb.AppendLine(" Pull Settings:"); + sb.AppendLine($" enableContextPull: {settings.enableContextPull}"); sb.AppendLine($" pullRimTalkHistory: {settings.pullRimTalkHistory}"); Log.Message(sb.ToString()); diff --git a/Source/RimMindBridgeRimTalk.csproj b/Source/RimMindBridgeRimTalk.csproj index 5e54557..744bf28 100644 --- a/Source/RimMindBridgeRimTalk.csproj +++ b/Source/RimMindBridgeRimTalk.csproj @@ -41,16 +41,4 @@ - - - $(RIMWORLD_DIR)\Mods\RimMind-Bridge-RimTalk\ - - - - - - - - diff --git a/Tests/Contracts/RimTalkGateContextContracts.cs b/Tests/Contracts/RimTalkGateContextContracts.cs index 554a99f..3d7e06b 100644 --- a/Tests/Contracts/RimTalkGateContextContracts.cs +++ b/Tests/Contracts/RimTalkGateContextContracts.cs @@ -14,6 +14,7 @@ using RimMind.Presentation.Api; using RimMind.Testing; using RimTalk.API; +using RimTalk.Data; using RimTalk.Prompt; using Verse; using Xunit; @@ -184,12 +185,14 @@ public void Context_providers_and_bridge_wiring_preserve_contracts() new[] { "test.static" }, RimMindAPI.Providers.StaticCalls); }), - ("missing optional providers are silent", () => + ("missing optional providers and null pawns are silent", () => { ResetProviders(); Assert.Equal(string.Empty, RimMindProviderReader.GetPawn("missing.category", new Pawn())); + Assert.Equal(string.Empty, + RimMindProviderReader.GetPawn("missing.category", null)); Assert.Empty(Log.Warnings); }), ("registered provider failures warn once per category", () => @@ -281,7 +284,7 @@ public void Context_providers_and_bridge_wiring_preserve_contracts() FakePromptEntry prompt = Assert.Single(FakeRimTalkPromptAPI.PromptEntries); Assert.Equal("RimMind Context", prompt.Name); Assert.Equal(FakePromptRole.System, prompt.Role); - Assert.Equal(FakePromptPosition.BeforeHistory, prompt.Position); + Assert.Equal(FakePromptPosition.Relative, prompt.Position); Assert.Equal(0, prompt.InChatDepth); Assert.Equal("RimMind.Bridge.RimTalk.Push", prompt.SourceModId); Assert.Contains("rimmind_personality", prompt.Content); @@ -486,23 +489,26 @@ public void Context_providers_and_bridge_wiring_preserve_contracts() FakeTalkHistory.Histories[targetPawn] = new ArrayList { - new FakeTalkMessage { Item1 = 1, Item2 = "Alice older line", Tick = 100 }, - new FakeTalkMessage { Item1 = 2, Item2 = "Alice newest line", Tick = 300 } + new FakeTalkMessage { Item1 = FakeTalkRole.User, Item2 = "Alice older line", Tick = 100 }, + new FakeTalkMessage { Item1 = FakeTalkRole.AI, Item2 = "Alice newest line", Tick = 300 } }; FakeTalkHistory.Histories[otherPawn] = new ArrayList { - new FakeTalkMessage { Item1 = 1, Item2 = "Bob mentions Alice at tick 200", Tick = 200 } + new FakeTalkMessage { Item1 = FakeTalkRole.User, Item2 = "Bob mentions Alice at tick 200", Tick = 200 } }; var pullBridge = new ContextPullBridge(); pullBridge.Register(); + Assert.True(pullBridge.IsRegistered); var def = Assert.Single(RimMindAPI.Context.ContextKeys.Definitions); + Assert.Equal("RimMindBridgeRimTalk", def.OwnerMod); string? text = def.Provider( new ProviderContext("dialogue", "trace") { PawnId = 10 }, CancellationToken.None).GetAwaiter().GetResult(); Assert.NotNull(text); Assert.StartsWith("[RimTalk Dialog History]" + Environment.NewLine + "[User] Alice older line", text); + Assert.Contains("[AI] Alice newest line", text); int idx100 = text!.IndexOf("Alice older line", StringComparison.Ordinal); int idx200 = text.IndexOf("Bob mentions Alice at tick 200", StringComparison.Ordinal); int idx300 = text.IndexOf("Alice newest line", StringComparison.Ordinal); @@ -525,6 +531,22 @@ public void Context_providers_and_bridge_wiring_preserve_contracts() new ProviderContext("dialogue", "trace") { PawnId = 10 }, CancellationToken.None).GetAwaiter().GetResult()); Assert.Single(Log.Warnings); + + // Missing TalkHistory type leaves IsRegistered false + RimMindAPI.Context.ContextKeys.Clear(); + ContextPullBridge.ConfigureTypesForTesting(null); + var unavailablePullBridge = new ContextPullBridge(); + unavailablePullBridge.Register(); + Assert.False(unavailablePullBridge.IsRegistered); + Assert.Empty(RimMindAPI.Context.ContextKeys.Definitions); + + // Disabled pullRimTalkHistory leaves IsRegistered false + ContextPullBridge.ConfigureTypesForTesting(typeof(FakeTalkHistory)); + BridgeRimTalkSettings.Get().pullRimTalkHistory = false; + var disabledPullBridge = new ContextPullBridge(); + disabledPullBridge.Register(); + Assert.False(disabledPullBridge.IsRegistered); + Assert.Empty(RimMindAPI.Context.ContextKeys.Definitions); }), ("production source has no child-mod compile dependency", () => { @@ -554,6 +576,7 @@ private static BridgeRimTalkSettings PrepareBridgeHarness() RimTalkDetector.IsRimTalkApiAvailable = true; BridgeRimTalkSettings.ResetForTesting(); RimMindAPI.Providers.Reset(); + RimMindProviderReader.ResetForTesting(); Log.Reset(); FakeRimTalkPromptAPI.Reset(); RimTalkApiShim.ConfigureTypesForTesting( @@ -611,13 +634,14 @@ private static void AssertHookMetadata( FakeRimTalkPromptAPI.PawnHookRegistration hook) { Assert.Equal("RimMind.Bridge.RimTalk.Persona", hook.ModId); - Assert.Equal(FakeContextHookRegistry.HookOperation.InsertBefore, hook.Operation); + Assert.Equal(FakeContextHookRegistry.HookOperation.Append, hook.Operation); Assert.Equal(90, hook.Priority); } private static void ResetProviders() { RimMindAPI.Providers.Reset(); + RimMindProviderReader.ResetForTesting(); Log.Reset(); } diff --git a/Tests/Contracts/RimTalkSettingsCompatibilityContracts.cs b/Tests/Contracts/RimTalkSettingsCompatibilityContracts.cs index 400cdd8..d61fd54 100644 --- a/Tests/Contracts/RimTalkSettingsCompatibilityContracts.cs +++ b/Tests/Contracts/RimTalkSettingsCompatibilityContracts.cs @@ -4,6 +4,8 @@ using RimMind.Bridge.RimTalk.Detection; using RimMind.Bridge.RimTalk.Settings; using RimMind.Testing; +using RimTalk.API; +using RimTalk.Prompt; using Verse; using Xunit; @@ -140,6 +142,20 @@ public void API_shim_preserves_exact_signature_and_failure_contracts() "value", _ => "context")); }), + ("missing HookOperation nested enum warns once and fails closed", () => + { + Log.Reset(); + RimTalkDetector.IsRimTalkApiAvailable = true; + RimTalkApiShim.ConfigureTypesForTesting( + typeof(FakeRimTalkPromptAPI), + hookRegistryType: typeof(MissingApi), + contextCategoriesType: typeof(FakeContextCategories)); + + Assert.False(RimTalkApiShim.RegisterPawnHook("owner", "Traits", "Append", (_, existing) => existing)); + Assert.False(RimTalkApiShim.RegisterPawnHook("owner", "Traits", "Append", (_, existing) => existing)); + Assert.Single(Log.Warnings); + Assert.Contains("HookOperation", Log.Warnings[0]); + }), ("cleanup remains safe when the dependency omits methods", () => { PrepareShim(typeof(MissingApi)); @@ -156,7 +172,9 @@ private static void PrepareShim(Type apiType) RimTalkDetector.IsRimTalkApiAvailable = true; RimTalkApiShim.ConfigureTypesForTesting( apiType, - promptEntryType: typeof(object)); + promptEntryType: typeof(object), + promptRoleType: typeof(FakePromptRole), + promptPositionType: typeof(FakePromptPosition)); } private static class CorrectPromptApi @@ -164,8 +182,8 @@ private static class CorrectPromptApi public static object CreatePromptEntry( string name, string content, - int role, - int position, + FakePromptRole role, + FakePromptPosition position, int depth, string? sourceModId) => new object(); diff --git a/Tests/README.md b/Tests/README.md index 915de48..b3c0d12 100644 --- a/Tests/README.md +++ b/Tests/README.md @@ -1,9 +1,14 @@ -# RimMind Bridge RimTalk contracts +# RimMind-Bridge-RimTalk Tests -The suite has two active contract groups: +Active contract suites live in `Contracts/*.cs` (6 xUnit Facts total): -- `RimTalkGateContextContracts` — dialogue gate, coordinator lifecycle, persona formatting, Core Provider reads and child-mod dependency boundaries. -- `RimTalkSettingsCompatibilityContracts` — safe defaults, dirty tracking, detector cache and reflection API compatibility. +- `RimTalkGateContextContracts` — dialogue gate, coordinator lifecycle, persona formatting, Core Provider reads (incl. null-pawn & missing-provider silence), context push/pull registration (real enum names & `IsRegistered` boundaries), and child-mod dependency isolation. +- `RimTalkSettingsCompatibilityContracts` — safe defaults, push plan filtering, detector cache invalidation, and `RimTalkApiShim` signature/enum/missing-nested-type contracts. -The fixed test budget is 6 Facts. `RimTalkStubs.cs` supplies the minimal Verse, -Harmony and `RimMindAPI.Providers` seams used by those contracts. +`RimTalkStubs.cs` supplies only external Verse/Harmony/Core/RimTalk seams (`HookOperation.Append`, `PromptRole`, `PromptPosition`, `FakeTalkRole`) needed to exercise production bridge sources on `net10.0` (`LangVersion 9.0`). + +## Run + +```powershell +dotnet test RimMind-Bridge-RimTalk/Tests/RimMindBridgeRimTalk.Tests.csproj -c Release +``` diff --git a/Tests/RimTalkStubs.cs b/Tests/RimTalkStubs.cs index 0ef055d..7c26b5c 100644 --- a/Tests/RimTalkStubs.cs +++ b/Tests/RimTalkStubs.cs @@ -341,7 +341,9 @@ public static class FakeContextHookRegistry { public enum HookOperation { - InsertBefore = 0 + Append = 0, + Prepend = 1, + Override = 2 } } @@ -513,16 +515,29 @@ public PawnHookRegistration( } } +namespace RimTalk.Data +{ + public enum FakeTalkRole + { + System = 0, + User = 1, + AI = 2 + } +} + namespace RimTalk.Prompt { public enum FakePromptRole { - System = 0 + System = 0, + User = 1, + Assistant = 2 } public enum FakePromptPosition { - BeforeHistory = 0 + Relative = 0, + InChat = 1 } public sealed class FakePromptEntry diff --git a/script/deploy-single.ps1 b/script/deploy-single.ps1 index feab55c..7670990 100644 --- a/script/deploy-single.ps1 +++ b/script/deploy-single.ps1 @@ -1,22 +1,22 @@ -# Deploy this RimMind mod to RimWorld Mods folder. +# Deploy this RimMind mod to RimWorld Mods folder (Windows PowerShell). # Place at: RimMind-*/script/deploy-single.ps1 # # Usage: # .\script\deploy-single.ps1 # .\script\deploy-single.ps1 "D:\Games\RimWorld" -# $env:RIMWORLD_PATH="D:\Games\RimWorld"; .\script\deploy-single.ps1 +# $env:RIMWORLD_DIR="D:\Games\RimWorld"; .\script\deploy-single.ps1 param( - [string]$RimWorldDir = "" + [string]$RimWorldDir = "", + [string[]]$GameVersions = @("1.7", "1.6") ) $ErrorActionPreference = "Stop" $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path -$ModDir = Resolve-Path (Join-Path $ScriptDir "..") +$ModDir = (Resolve-Path (Join-Path $ScriptDir "..")).Path $ModName = Split-Path -Leaf $ModDir -# 自动检测常见 RimWorld 安装路径 function Detect-RimWorldPath { $paths = @( "C:\Program Files (x86)\Steam\steamapps\common\RimWorld", @@ -31,15 +31,16 @@ function Detect-RimWorldPath { return $null } -# 解析 RimWorld 路径 -if ($env:RIMWORLD_PATH) { +if ($RimWorldDir -eq "" -and $env:RIMWORLD_DIR) { + $RimWorldDir = $env:RIMWORLD_DIR +} elseif ($RimWorldDir -eq "" -and $env:RIMWORLD_PATH) { $RimWorldDir = $env:RIMWORLD_PATH } elseif ($RimWorldDir -eq "") { $RimWorldDir = Detect-RimWorldPath if (-not $RimWorldDir) { Write-Error "Cannot find RimWorld installation" Write-Host " Usage: .\script\deploy-single.ps1 [RimWorldPath]" -ForegroundColor Yellow - Write-Host " Or: `$env:RIMWORLD_PATH='D:\Games\RimWorld'; .\script\deploy-single.ps1" -ForegroundColor Yellow + Write-Host " Or: `$env:RIMWORLD_DIR='D:\Games\RimWorld'; .\script\deploy-single.ps1" -ForegroundColor Yellow exit 1 } } @@ -50,56 +51,88 @@ if (-not (Test-Path $RimWorldDir)) { } $RimWorldMods = Join-Path $RimWorldDir "Mods" - -# 确保 Mods 目录存在 if (-not (Test-Path $RimWorldMods)) { Write-Error "Mods directory not found at $RimWorldMods" exit 1 } -# 构建 -$CSPROJ = Get-ChildItem -Path (Join-Path $ModDir "Source") -Filter "*.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1 -if ($CSPROJ) { - Write-Host "=== Building $ModName ===" -ForegroundColor Cyan - dotnet build $CSPROJ.FullName -c Release --nologo -v quiet - if ($LASTEXITCODE -ne 0) { - Write-Error "Build failed" - exit $LASTEXITCODE +# Build for all target game versions (1.7 & 1.6) +$SourceDir = Join-Path $ModDir "Source" + +foreach ($gameVersion in $GameVersions) { + Write-Host "=== Building $ModName (RimWorld $gameVersion) ===" -ForegroundColor Cyan + + if ($ModName -eq "RimMind-Core") { + $domainCsproj = Join-Path $SourceDir "Domain\RimMindCore.Domain.csproj" + $applicationCsproj = Join-Path $SourceDir "Application\RimMindCore.Application.csproj" + $coreCsproj = Get-ChildItem -Path $SourceDir -Filter "RimMindCore.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1 + + if (-not (Test-Path $domainCsproj)) { + Write-Error "Domain csproj not found: $domainCsproj" + exit 1 + } + if (-not (Test-Path $applicationCsproj)) { + Write-Error "Application csproj not found: $applicationCsproj" + exit 1 + } + if (-not $coreCsproj) { + Write-Error "Core csproj not found in $SourceDir" + exit 1 + } + + dotnet build $domainCsproj -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { Write-Error "Domain build failed ($gameVersion)"; exit $LASTEXITCODE } + + dotnet build $applicationCsproj -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { Write-Error "Application build failed ($gameVersion)"; exit $LASTEXITCODE } + + dotnet build $coreCsproj.FullName -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { Write-Error "Core build failed ($gameVersion)"; exit $LASTEXITCODE } + } else { + $csproj = Get-ChildItem -Path $SourceDir -Filter "*.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($csproj) { + dotnet build $csproj.FullName -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { + Write-Error "Build failed ($gameVersion)" + exit $LASTEXITCODE + } + } else { + Write-Host "No .csproj found in Source\, skipping build" -ForegroundColor Yellow + } } - Write-Host " Build successful" -} else { - Write-Host "No .csproj found in Source\, skipping build" -ForegroundColor Yellow } -# 部署 +# Deploy with clean runtime exclusions (never copy Core/Newtonsoft DLLs into non-Core mods) $DestDir = Join-Path $RimWorldMods $ModName Write-Host "=== Deploying $ModName -> $DestDir ===" -ForegroundColor Cyan -$ExcludeDirs = @('Source', 'Tests', 'obj', '.git', 'script') -$ExcludeFiles = @('*.csproj', '*.user', '.gitignore') -$SourceItems = Get-ChildItem -Path $ModDir | Where-Object { - $item = $_ - if ($item.PSIsContainer -and $ExcludeDirs -contains $item.Name) { return $false } - if (-not $item.PSIsContainer) { - foreach ($pattern in $ExcludeFiles) { - if ($item.Name -like $pattern) { return $false } - } - } - return $true +$excludeFiles = @( + "*.csproj", "*.user", ".gitignore", ".git", ".gitattributes", + ".coderabbit.yaml", ".pre-commit-config.yaml", + "AGENTS.md", "CLAUDE.md", "Directory.Build.props", "Directory.Build.targets", + "INTRODUCTION.txt", "*.deps.json" +) +if ($ModName -ne "RimMind-Core") { + $excludeFiles += @( + "0_RimMindDomain.*", "1_RimMindApplication.*", "2_RimMindCore.*", "Newtonsoft.Json.*" + ) } -if (Test-Path $DestDir) { - Get-ChildItem -Path $DestDir | Remove-Item -Recurse -Force +robocopy $ModDir $DestDir /MIR /XD Source Tests ArchTests IntegrationTests TestSupport obj bin .git .github .claude docs script /XF $excludeFiles /NFL /NDL /NJH /NJS /NP +if ($LASTEXITCODE -ge 8) { + Write-Error "Deployment failed (robocopy exit $LASTEXITCODE)" + exit $LASTEXITCODE } -foreach ($item in $SourceItems) { - Copy-Item -Path $item.FullName -Destination $DestDir -Recurse -Force +if ($ModName -ne "RimMind-Core") { + foreach ($ver in $GameVersions) { + $deployedAssemblies = Join-Path $DestDir "$ver\Assemblies" + if (Test-Path $deployedAssemblies) { + foreach ($pattern in @("0_RimMindDomain.*", "1_RimMindApplication.*", "2_RimMindCore.*", "Newtonsoft.Json.*")) { + Get-ChildItem -Path $deployedAssemblies -Filter $pattern -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue + } + } + } } -# 验证部署 -if (Test-Path $DestDir) { - Write-Host " Done: $DestDir" -ForegroundColor Green -} else { - Write-Error "Deployment verification failed" - exit 1 -} +Write-Host " Done: $DestDir" -ForegroundColor Green diff --git a/script/deploy-single.sh b/script/deploy-single.sh deleted file mode 100644 index 7dc5165..0000000 --- a/script/deploy-single.sh +++ /dev/null @@ -1,95 +0,0 @@ -#!/bin/bash -# Deploy this RimMind mod to RimWorld Mods folder. -# Place at: RimMind-*/script/deploy-single.sh -# -# Usage: -# ./script/deploy-single.sh # use default path -# ./script/deploy-single.sh /path/to/RimWorld # custom path -# RIMWORLD_PATH=/path/to/RimWorld ./script/deploy-single.sh # env var override - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -MOD_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" -MOD_NAME="$(basename "$MOD_DIR")" - -# 自动检测常见 RimWorld 安装路径 -detect_rimworld_path() { - local paths=( - "/mnt/c/Program Files (x86)/Steam/steamapps/common/RimWorld" - "/mnt/c/Program Files/Steam/steamapps/common/RimWorld" - "$HOME/.steam/steam/steamapps/common/RimWorld" - "$HOME/.local/share/Steam/steamapps/common/RimWorld" - ) - for path in "${paths[@]}"; do - if [[ -d $path ]]; then - echo "$path" - return 0 - fi - done - return 1 -} - -# 解析 RimWorld 路径 -if [[ -n ${RIMWORLD_PATH:-} ]]; then - RIMWORLD_PATH="$RIMWORLD_PATH" -elif [[ $# -gt 0 ]]; then - RIMWORLD_PATH="$1" -else - RIMWORLD_PATH=$(detect_rimworld_path) || { - echo "Error: Cannot find RimWorld installation" - echo " Usage: $0 [/path/to/RimWorld]" - echo " Or: export RIMWORLD_PATH=/path/to/RimWorld && $0" - exit 1 - } -fi - -RIMWORLD_MODS="$RIMWORLD_PATH/Mods" - -if [[ ! -d $RIMWORLD_PATH ]]; then - echo "Error: RimWorld not found at $RIMWORLD_PATH" - exit 1 -fi - -# 确保 Mods 目录存在 -if [[ ! -d $RIMWORLD_MODS ]]; then - echo "Error: Mods directory not found at $RIMWORLD_MODS" - exit 1 -fi - -# 构建 -CSPROJ=$(find "$MOD_DIR/Source" -maxdepth 1 -name "*.csproj" 2>/dev/null | head -1) -if [[ -n $CSPROJ ]]; then - echo "=== Building $MOD_NAME ===" - if ! dotnet build "$CSPROJ" -c Release --nologo -v quiet; then - echo "Error: Build failed" - exit 1 - fi - echo " Build successful" -else - echo "No .csproj found in Source/, skipping build" -fi - -# 部署 -echo "=== Deploying $MOD_NAME -> $RIMWORLD_MODS/$MOD_NAME ===" -if ! rsync -a --delete \ - --exclude='Source/' \ - --exclude='Tests/' \ - --exclude='*.csproj' \ - --exclude='*.user' \ - --exclude='obj/' \ - --exclude='.git/' \ - --exclude='.gitignore' \ - --exclude='script/' \ - "$MOD_DIR/" "$RIMWORLD_MODS/$MOD_NAME/"; then - echo "Error: Deployment failed" - exit 1 -fi - -# 验证部署 -if [[ -d "$RIMWORLD_MODS/$MOD_NAME" ]]; then - echo " Done: $RIMWORLD_MODS/$MOD_NAME" -else - echo "Error: Deployment verification failed" - exit 1 -fi